diff --git "a/4162.jsonl" "b/4162.jsonl" new file mode 100644--- /dev/null +++ "b/4162.jsonl" @@ -0,0 +1,686 @@ +{"seq_id":"554822511","text":"import json\nimport os\n\n\ndef default_image_layer_settings():\n settings = {\n \"color\": \"white\",\n \"contrastLimits\": [0., 255.],\n \"type\": \"image\"\n }\n return settings\n\n\ndef default_segmentation_layer_settings():\n settings = {\n \"color\": \"randomFromGlasbey\",\n \"contrastLimits\": [0., 1000.],\n \"type\": \"segmentation\"\n }\n return settings\n\n\ndef default_mask_layer_settings():\n settings = {\n \"color\": \"white\",\n \"contrastLimits\": [0., 1.],\n \"type\": \"mask\"\n }\n return settings\n\n\ndef default_layer_setting(layer_type):\n if layer_type == 'image':\n return default_image_layer_settings()\n elif layer_type == 'segmentation':\n return default_segmentation_layer_settings()\n elif layer_type == 'mask':\n return default_mask_layer_settings()\n raise ValueError(f\"Invalid layer type: {layer_type}\")\n\n\n# TODO check that all fields and values in settings are valid\ndef update_layer_settings(settings, layer_type):\n default_settings = default_layer_setting(layer_type)\n for key, value in default_settings:\n if key not in settings:\n settings.update({key: value})\n if settings['type'] != layer_type:\n raise ValueError(f\"Expect layer_type {layer_type}, got {settings['type']}\")\n return settings\n\n\ndef load_image_dict(image_dict_path):\n if os.path.exists(image_dict_path):\n with open(image_dict_path) as f:\n image_dict = json.load(f)\n else:\n image_dict = {}\n return image_dict\n\n\ndef add_to_image_dict(dataset_folder, layer_type, xml_path,\n settings=None, table_folder=None,\n overwrite=False):\n \"\"\" Add entry to the image dict.\n\n Arguments:\n dataset_folder [str] - path to the dataset folder\n layer_type [str] - type of the layer, 'image' or 'segmentation'\n xml_path [str] - path to the xml for the raw data of this dataset.\n settings [dict] - settings for the layer. (default: None)\n table_folder [str] - table folder for segmentations. (default: None)\n overwrite [bool] - whether to overwrite existing entries (default: False)\n \"\"\"\n if not os.path.exists(xml_path):\n raise ValueError(f\"{xml_path} does not exist\")\n layer_name = os.path.splitext(os.path.split(xml_path)[1])[0]\n\n image_folder = os.path.join(dataset_folder, 'images')\n image_dict_path = os.path.join(image_folder, 'images.json')\n image_dict = load_image_dict(image_dict_path)\n\n if layer_name in image_dict and not overwrite:\n raise ValueError(f\"{layer_name} is already in the image_dict\")\n\n if settings is None:\n settings = default_layer_setting(layer_type)\n else:\n settings = update_layer_settings(settings, layer_type)\n\n rel_path = os.path.relpath(xml_path, image_folder)\n settings.update({\n \"storage\": {\"local\": rel_path}\n })\n\n if table_folder is not None:\n\n if layer_type != 'segmentation':\n msg = f\"Table folder is only supported for segmentation layers, got {layer_type}\"\n raise ValueError(msg)\n rel_table_folder = os.path.relpath(table_folder, dataset_folder)\n settings.update({\n 'tableFolder': rel_table_folder\n })\n\n image_dict[layer_name] = settings\n with open(image_dict_path, 'w') as f:\n json.dump(image_dict, f, indent=2, sort_keys=True)\n","sub_path":"mobie/metadata/image_dict.py","file_name":"image_dict.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"18638743","text":"import matplotlib\r\nmatplotlib.use(\"Agg\")\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib import gridspec\r\nimport pickle\r\nimport os\r\n\r\nfrom scipy.stats import stats, spearmanr\r\n\r\nseeds = [20, 2020, 202020]\r\nstatss = []\r\nfor seed in seeds:\r\n with open(\"./fig_surgery/fig1_nb301_seed{seed}_stat.pkl\".format(seed=seed), \"rb\") as r_f:\r\n stat = {k: v[\"non_sparse\"] for k, v in pickle.load(r_f).items()}\r\n statss.append(stat)\r\n\r\nstats_list = [list(zip(*sorted([(int(os.path.basename(key).split(\".\")[0]), value) for key, value in stat.items()], key=lambda item: item[0]))) for stat in statss]\r\n\r\ndef minmax_n_at_k(predict_scores, true_scores, ks=[0.01, 0.05, 0.10, 0.20]):\r\n true_scores = np.array(true_scores)\r\n predict_scores = np.array(predict_scores)\r\n num_archs = len(true_scores)\r\n true_ranks = np.zeros(num_archs)\r\n true_ranks[np.argsort(true_scores)] = np.arange(num_archs)[::-1]\r\n predict_best_inds = np.argsort(predict_scores)[::-1]\r\n minn_at_ks = []\r\n for k in ks:\r\n ranks = true_ranks[predict_best_inds[:int(k * len(true_scores))]]\r\n minn = int(np.min(ranks)) + 1\r\n maxn = int(np.max(ranks)) + 1\r\n minn_at_ks.append((k, minn, float(minn) / num_archs, maxn, float(maxn) / num_archs))\r\n return minn_at_ks\r\n\r\n\r\ndef p_at_tb_k(predict_scores, true_scores, ratios=[0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0]):\r\n predict_scores = np.array(predict_scores)\r\n true_scores = np.array(true_scores)\r\n predict_inds = np.argsort(predict_scores)[::-1]\r\n num_archs = len(predict_scores)\r\n true_ranks = np.zeros(num_archs)\r\n true_ranks[np.argsort(true_scores)] = np.arange(num_archs)[::-1]\r\n patks = []\r\n for ratio in ratios:\r\n k = int(num_archs * ratio)\r\n if k < 1:\r\n continue\r\n top_inds = predict_inds[:k]\r\n bottom_inds = predict_inds[num_archs - k:]\r\n p_at_topk = len(np.where(true_ranks[top_inds] < k)[0]) / float(k)\r\n p_at_bottomk = len(np.where(true_ranks[bottom_inds] >= num_archs - k)[0]) / float(k)\r\n kd_at_topk = stats.kendalltau(predict_scores[top_inds], true_scores[top_inds]).correlation\r\n kd_at_bottomk = stats.kendalltau(predict_scores[bottom_inds], true_scores[bottom_inds]).correlation\r\n # [ratio, k, P@topK, P@bottomK, KT in predicted topK, KT in predicted bottomK]\r\n patks.append((ratio, k, p_at_topk, p_at_bottomk, kd_at_topk, kd_at_bottomk))\r\n return patks\r\n\r\n\r\ncriteria = {\r\n \"oneshot average\": lambda x, y: np.mean(x),\r\n \"linear\": lambda x, y: np.corrcoef(x, y)[0][1],\r\n \"kd\": lambda x, y: stats.kendalltau(x, y).correlation,\r\n \"spearmanr\": lambda x, y: spearmanr(x, y).correlation,\r\n \"BWR@K\": lambda x, y: minmax_n_at_k(x, y),\r\n \"P@tbK\": lambda x, y: p_at_tb_k(x, y),\r\n}\r\n\r\nwith open(\"/home/novauto/derived_res/derive_301/stat_acc.pkl\", \"rb\") as r_f:\r\n derived = pickle.load(r_f)\r\n\r\nmean_acc = derived[\"derive\"].mean(0)\r\ngt = derived[\"gt\"]\r\n\r\nmean_acc_corr = {}\r\nfor ck, cv in criteria.items():\r\n mean_acc_corr[ck] = [[cv(m, gt)] for m in mean_acc]\r\n\r\nres = {\"acc\": {}, \"loss\": {}}\r\nepochs = stats_list[0][0]\r\ninfo_names = stats_list[0][1][0][\"oneshot_acc\"].keys()\r\nfor info_name in info_names:\r\n res[\"acc\"][info_name] = list(\r\n zip(*[[epoch_stat[\"oneshot_acc\"][info_name] for epoch_stat in seed_stat[1]] for seed_stat in stats_list]))\r\n res[\"loss\"][info_name] = list(\r\n zip(*[[epoch_stat[\"oneshot_loss\"][info_name] for epoch_stat in seed_stat[1]] for seed_stat in stats_list]))\r\n\r\nres[\"mean_acc\"] = mean_acc_corr\r\n\r\nfig = plt.figure(figsize=[16.,6.])\r\ngs = gridspec.GridSpec(nrows=1, ncols=2)#, width_ratios=[3]*num_cols + [2])\r\n\r\ndef plot_trend_to_ax(ax, name):\r\n accs = np.array(res[name][\"oneshot average\"])\r\n linear = np.array(res[name][\"linear\"])\r\n spearmanrs = np.array(res[name][\"spearmanr\"])\r\n kds = np.array(res[name][\"kd\"])\r\n p_at_top5 = np.array(res[name][\"P@tbK\"])[:, :, 3, 2]\r\n p_at_bot5 = np.array(res[name][\"P@tbK\"])[:, :, 3, 3]\r\n# br_at_5 = np.array(res[name][\"BWR@K\"])[:, :, 1, 2]\r\n# wr_at_5 = np.array(res[name][\"BWR@K\"])[:, :, 1, 4]\r\n\r\n labels = [\"Oneshot average\", \"Linear correlation\", \"Spearman correlation\", \"Kendall's tau\", \"P@top5%\", \"P@bottom5%\", \"BR@5%\", \"WR@5%\"]\r\n colors = [\"#3A76AF\", \"#EF8536\", \"#519D3E\", \"#C53932\", \"#8D6AB8\", \"#8D6AB8\"]\r\n markers = {\r\n \"P@bottom5%\": \"^\"\r\n }\r\n linestyles={\"P@bottom5%\": \"--\"}\r\n lines = []\r\n for i, (nums, color, label) in enumerate(zip([accs, linear, spearmanrs, kds, p_at_top5, p_at_bot5], colors, labels)):\r\n if name == \"loss\" and i == 0:\r\n ax2 = ax.twinx()\r\n ax2.tick_params(labelsize = 16)\r\n ax2.set_ylabel(\"Oneshot loss\", fontsize=16)\r\n plot_ax = ax2\r\n else:\r\n plot_ax = ax\r\n avg, std = np.mean(nums, axis=-1), np.std(nums, axis=-1)\r\n lines.append(plot_ax.plot(epochs, avg, color=color, linewidth=2,\r\n label=label,linestyle=linestyles.get(label, \"-\"),mew=0.5,marker=markers.get(label, \"o\"))[0])\r\n plot_ax.fill_between(epochs, avg-std, avg+std, facecolor=color, alpha=0.2)\r\n return lines\r\n\r\n# ---- acc ----\r\nax = fig.add_subplot(gs[0, 0])\r\nax.tick_params(labelsize = 16)\r\nplot_trend_to_ax(ax, \"acc\")\r\nax.set_title(\"Oneshot accuracy\", fontsize=16)\r\nax.legend(fontsize=16)\r\n\r\n# ---- loss ----\r\nax = fig.add_subplot(gs[0, 1])\r\nax.tick_params(labelsize = 16)\r\nlines = plot_trend_to_ax(ax, \"loss\")\r\nax.set_title(\"Oneshot loss (negative)\", fontsize=16)\r\nlabels=[l.get_label() for l in lines]\r\n# ax.legend(lines,labels,fontsize=16)\r\n\r\n# ---- show ----\r\nplt.tight_layout()\r\nplt.savefig(\"fig1_nb301.pdf\")\r\n#plt.show()\r\n","sub_path":"plots/fig1_nb301.py","file_name":"fig1_nb301.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"345209348","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\ntest_utils\r\n------------\r\n\r\nTests for `cookiecutter.utils` module.\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport unittest\r\n\r\nfrom cookiecutter import utils\r\n\r\n\r\nclass TestUtils(unittest.TestCase):\r\n\r\n def test_make_sure_path_exists(self):\r\n self.assertTrue(utils.make_sure_path_exists('/usr/'))\r\n self.assertTrue(utils.make_sure_path_exists('tests/blah'))\r\n self.assertTrue(utils.make_sure_path_exists('tests/trailingslash/'))\r\n self.assertFalse(\r\n utils.make_sure_path_exists(\r\n '/this-dir-does-not-exist-and-cant-be-created/'.replace(\"/\", os.sep)\r\n )\r\n )\r\n shutil.rmtree('tests/blah/')\r\n shutil.rmtree('tests/trailingslash/')\r\n\r\n def test_unicode_open(self):\r\n \"\"\" Test unicode_open(filename, *args, **kwargs). \"\"\"\r\n\r\n unicode_text = u\"\"\"Polish: Ą Ł Ż\r\nChinese: 倀 倁 倂 倃 倄 倅 倆 倇 倈\r\nMusical Notes: ♬ ♫ ♯\"\"\"\r\n\r\n with utils.unicode_open('tests/files/unicode.txt') as f:\r\n opened_text = f.read()\r\n if sys.platform.startswith('win'):\r\n unicode_text = os.linesep.join([s for s in unicode_text.splitlines() if not s.isspace()])\r\n self.assertEqual(unicode_text, opened_text)\r\n\r\n def test_workin(self):\r\n cwd = os.getcwd()\r\n ch_to = 'tests/files'\r\n\r\n class TestException(Exception):\r\n pass\r\n\r\n def test_work_in():\r\n with utils.work_in(ch_to):\r\n test_dir = os.path.join(cwd, ch_to).replace(\"/\", os.sep)\r\n self.assertEqual(test_dir, os.getcwd())\r\n raise TestException()\r\n\r\n # Make sure we return to the correct folder\r\n self.assertEqual(cwd, os.getcwd())\r\n\r\n # Make sure that exceptions are still bubbled up\r\n self.assertRaises(TestException, test_work_in)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"425386592","text":"\"\"\"\n演示三维数组\n\"\"\"\n\nimport numpy as np\n\n\na = np.arange(1,7).reshape((2,3)) # 参数中前面是每一行个数,后面是维度\nb= np.arange(7,13).reshape((2,3))\n\n# 垂直方向操作\nc = np.vstack((a,b))\nprint('c:',c)\n\na,b = np.vsplit(c,2) # 拆成2份\nprint('垂直a,b:',a,'\\n',b)\n\n\n# 水平方向操作\nd = np.hstack((a,b))\na,b = np.hsplit(d,2)\nprint('水平a,b:',a,'\\n',b)\n\n\ne = np.dstack((a,b))\na,b = np.dsplit(e,2)\nprint('深度a,b:',a,'\\n',b)\n\n\na = a.reshape(3,2)\nb= b.reshape(3,2)\nprint(a,'\\n',b)\nc=np.concatenate((a,b),axis=1)\nprint('c:',c)\n\n# 通过给定的axis轴向与拆封的份数对c数组进行拆分\nnp.split(c,2,axis=0)\n\n","sub_path":"data_analysis/numpy/_04.many_dimen.py","file_name":"_04.many_dimen.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"520873798","text":"import numpy as np\nfrom imower.game.state import is_in_grid, next_pos, world_cell_transition\n\n\nclass MowSearchProblem:\n def __init__(self, game_state):\n self._grid = game_state[\"world_state\"].copy()\n self.grid_size = self._grid.shape\n self._e_ij = lambda i, j: i * self._grid.shape[1] + j\n\n elems_state = \"\".join([\"\".join(row) for row in self._grid.tolist()])\n self._initial_state = (game_state[\"mower_pos\"], elems_state, game_state[\"nb_propellers\"])\n self._penalties = game_state[\"penalties\"]\n self._earth_mode = game_state[\"earth_mode\"]\n self._expanded = 0\n\n def get_initial_state(self):\n return self._initial_state\n\n def goal_test(self, state):\n return 'H' not in state[1]\n\n def is_game_over(self, state):\n return state[2] == 0\n\n def actions(self, state):\n if self.is_game_over(state):\n return \"STOP\"\n la = np.array(['UP', 'DOWN', 'RIGHT', 'LEFT'])\n\n pos = state[0]\n nb_propellers = state[2]\n next_pos_game_state_wrapper = {\"mower_pos\": pos, \"world_state\": self._grid, \"nb_propellers\": nb_propellers}\n\n is_legals_actions = np.array([is_in_grid(next_pos(next_pos_game_state_wrapper, a), self._grid.shape) for a in la])\n return la[is_legals_actions].tolist()\n\n def result(self, state, action):\n pos = state[0]\n elems_state = list(state[1])\n nb_propellers = state[2]\n\n next_pos_game_state_wrapper = {\"mower_pos\": pos, \"world_state\": self._grid, \"nb_propellers\": nb_propellers}\n next_p = next_pos(next_pos_game_state_wrapper, action)\n\n if is_in_grid(next_p, self._grid.shape):\n pos = next_p\n ind_next_e = self._e_ij(*next_p)\n next_e = elems_state[ind_next_e]\n\n if next_e == 'R':\n nb_propellers = max(nb_propellers - 1, 0)\n\n elems_state[ind_next_e] = world_cell_transition(next_e, self._earth_mode)\n\n return pos, ''.join(elems_state), nb_propellers\n\n def step_cost(self, state, action):\n cost = 0\n pos = state[0]\n elems_state = state[1]\n nb_propellers = state[2]\n\n next_pos_game_state_wrapper = {\"mower_pos\": pos, \"world_state\": self._grid, \"nb_propellers\": nb_propellers}\n next_p = next_pos(next_pos_game_state_wrapper, action)\n ind_next_e = self._e_ij(*next_p)\n next_e = elems_state[ind_next_e]\n if next_e == 'R':\n if nb_propellers > 1:\n cost += self._penalties['lose_propeller']\n else:\n return 999999\n if (next_e == 'L') and self._earth_mode:\n cost += self._penalties['mow_to_earth']\n\n cost += self._penalties['living']\n return cost\n\n def get_path_cost(self, actions):\n state = self._initial_state\n cost = 0\n for action in actions:\n cost += self.step_cost(state, action)\n state = self.result(state, action)\n return cost\n","sub_path":"imower/agents/planning/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"582772777","text":"from util import json_load, json_dump, get_provinces_name, get_population, get_vaccines, moving_average\n\nimport matplotlib.pyplot as plt\nimport datetime\n\ndata = json_load(\"../components/gis/data/provinces-data-21days.json\")\nend = datetime.datetime.fromisoformat(max(data[0][\"cases\"].keys()))\nprovinces_name = get_provinces_name(json_load('../components/gis/geo/th-provinces-centroids.json'))\nvaccines_data = json_load('../components/gis/data/provincial-vaccination-data.json')\npopulations = get_population(vaccines_data)\nvaccines = get_vaccines(vaccines_data)\n\nimages = []\ni = 1\nfor province in data:\n name = province[\"name\"]\n names = list(province[\"cases\"])\n ys = list(province[\"cases\"].values())\n moving_aves = moving_average(ys)\n fig = plt.gcf()\n plt.cla()\n fig.set_size_inches(10, 5)\n if max(moving_aves[-14:]) < 10:\n plt.ylim(0, 10)\n else:\n plt.ylim(0, max(moving_aves[-14:]))\n plt.fill_between(names[-14:], 0, moving_aves[-14:], alpha=0.3, color='#dc3545', zorder=2)\n plt.plot(names[-14:], moving_aves[-14:], color='#dc3545', linewidth=25)\n plt.box(False)\n plt.xticks([])\n plt.yticks([])\n plt.savefig('../public/infection-graphs-build/' + str(provinces_name.index(name) + 1) + '.svg', bbox_inches=0,\n transparent=True)\n\n fig = plt.gcf()\n plt.cla()\n fig.set_size_inches(10, 5)\n if max(moving_aves[-7:]) < 10:\n plt.ylim(0, 10)\n else:\n plt.ylim(0, max(moving_aves[-7:]))\n plt.fill_between(names[-7:], 0, moving_aves[-7:], alpha=0.3, color='#dc3545', zorder=2)\n plt.plot(names[-7:], moving_aves[-7:], color='#dc3545', linewidth=25)\n plt.box(False)\n plt.xticks([])\n plt.yticks([])\n plt.savefig('../public/7days-infection-graphs-build/' + str(provinces_name.index(name) + 1) + '.svg', bbox_inches=0,\n transparent=True)\n\n if moving_aves[-14] > 0:\n change = int((moving_aves[-1] - moving_aves[-14]) * 100 / (moving_aves[-14]))\n else:\n change = int((moving_aves[-1] - 0) * 100 / 1)\n\n if moving_aves[-7] > 0:\n change_seven_days = int((moving_aves[-1] - moving_aves[-7]) * 100 / (moving_aves[-7]))\n else:\n change_seven_days = int((moving_aves[-1] - 0) * 100 / 1)\n\n images.append({\n \"name\": str(provinces_name.index(name) + 1) + \".svg\",\n \"change\": change,\n \"change-7days\": change_seven_days,\n \"total-14days\": sum(ys[-14:]),\n \"total-7days\": sum(ys[-7:]),\n \"province\": name,\n \"vax-coverage\": round(vaccines[name]['coverage'] * 100, 2),\n \"vax-1st-dose\": round((vaccines[name]['total-1st-dose'] / vaccines[name]['population']) * 100, 2),\n \"vax-2nd-dose\": round((vaccines[name]['total-2nd-dose'] / vaccines[name]['population']) * 100, 2),\n \"population\": populations[name],\n })\n i += 1\n\ndata = {'images': images,\n 'job': {\n 'ran_on': datetime.date.today().strftime(\"%m/%d/%Y %H:%M\"),\n 'dataset_updated_on': end.strftime(\"%m/%d/%Y %H:%M\")\n },\n }\njson_dump(data, '../components/build_job.json')\n\nprint('Finished building province graph')\n","sub_path":"bot_jobs/build_province_graph.py","file_name":"build_province_graph.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"10636907","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nsynthnn.exec.nn_predict\n\ncommand line interface to synthesize an MR (brain) image\nwith a trained pytorch NN (see nn_train)\n\nAuthor: Jacob Reinhold (jacob.reinhold@jhu.edu)\n\nCreated on: Nov 2, 2018\n\"\"\"\n\nimport logging\nfrom math import floor\nimport os\nimport sys\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n warnings.filterwarnings('ignore', category=UserWarning)\n import nibabel as nib\n import numpy as np\n import torch\n from synthnn.util.exec import get_args, get_device, setup_log\n from synthnn import glob_nii, split_filename, SynthNNError\n\n\n######## Helper functions ########\n\ndef fwd(mdl, img, temperature_map): return mdl.predict(img, temperature_map).cpu().detach().numpy()\n\n\ndef batch2d(model, img, out_img, axis, device, bs, i, nsyn, temperature_map):\n s = np.transpose(img[:,i:i+bs,:,:],[1,0,2,3]) if axis == 0 else \\\n np.transpose(img[:,:,i:i+bs,:],[2,0,1,3]) if axis == 1 else \\\n np.transpose(img[:,:,:,i:i+bs],[3,0,1,2])\n img_b = torch.from_numpy(s).to(device)\n for j in range(nsyn):\n if axis == 0:\n out_img[j,:,i:i+bs,:,:] = np.transpose(fwd(model, img_b, temperature_map), [1,0,2,3])\n elif axis == 1:\n out_img[j,:,:,i:i+bs,:] = np.transpose(fwd(model, img_b, temperature_map), [1,2,0,3])\n else:\n out_img[j,:,:,:,i:i+bs] = np.transpose(fwd(model, img_b, temperature_map), [1,2,3,0])\n\n\ndef save_imgs(out_img_nib, output_dir, k, logger):\n for i, oin in enumerate(out_img_nib):\n out_fn = output_dir + f'{k}_{i}.nii.gz'\n oin.to_filename(out_fn)\n logger.info(f'Finished synthesis. Saved as: {out_fn}.')\n\n\ndef get_overlapping_3d_idxs(psz, img):\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n stride = psz // 2\n indices = [torch.from_numpy(idxs) for idxs in np.indices(img.shape[1:])]\n for i in range(3): # create blocks from imgs (and indices)\n indices = [idxs.unfold(i, psz, stride) for idxs in indices]\n x, y, z = [idxs.contiguous().view(-1, psz, psz, psz) for idxs in indices]\n return x, y, z\n\n\n######### Main routine ###########\n\ndef main(args=None):\n args, no_config_file = get_args(args)\n setup_log(args.verbosity)\n logger = logging.getLogger(__name__)\n try:\n # set random seeds for reproducibility\n torch.manual_seed(args.seed)\n np.random.seed(args.seed)\n\n # define device to put tensors on\n device, use_cuda, n_gpus = get_device(args, logger)\n\n # determine if we enable dropout in prediction\n nsyn = args.monte_carlo or 1\n\n # only create temperature map if ord params used\n if args.ord_params is None and args.temperature_map:\n raise SynthNNError('temperature_map is only a valid option when using ordinal regression')\n\n # load the trained model\n if args.nn_arch.lower() == 'nconv':\n from synthnn.models.nconvnet import SimpleConvNet\n model = SimpleConvNet(args.n_layers, kernel_size=args.kernel_size, dropout_p=args.dropout_prob,\n n_input=args.n_input, n_output=args.n_output, is_3d=args.net3d)\n elif args.nn_arch.lower() == 'unet':\n from synthnn.models.unet import Unet\n model = Unet(args.n_layers, kernel_size=args.kernel_size, dropout_p=args.dropout_prob,\n channel_base_power=args.channel_base_power, add_two_up=args.add_two_up, normalization=args.normalization,\n activation=args.activation, output_activation=args.out_activation, is_3d=args.net3d,\n interp_mode=args.interp_mode, enable_dropout=nsyn > 1, enable_bias=args.enable_bias,\n n_input=args.n_input, n_output=args.n_output, no_skip=args.no_skip,\n ord_params=args.ord_params+[device] if args.ord_params is not None else None)\n elif args.nn_arch == 'vae':\n from synthnn.models.vae import VAE\n model = VAE(args.n_layers, args.img_dim, channel_base_power=args.channel_base_power,\n activation=args.activation, is_3d=args.net3d,\n n_input=args.n_input, n_output=args.n_output, latent_size=args.latent_size)\n else:\n raise SynthNNError(f'Invalid NN type: {args.nn_arch}. {{nconv, unet}} are the only supported options.')\n state_dict = torch.load(args.trained_model, map_location=device)\n model.load_state_dict(state_dict)\n model.eval()\n logger.debug(model)\n\n # put the model on the GPU if available and desired\n if use_cuda: model.cuda(device=device)\n\n # setup and start prediction loop (whole slice by whole slice)\n axis = args.sample_axis or 0\n if axis < 0 or axis > 2 and not isinstance(axis,int):\n raise ValueError('sample_axis must be an integer between 0 and 2 inclusive')\n bs = args.batch_size // args.n_gpus if args.n_gpus > 1 and use_cuda else args.batch_size\n psz = args.patch_size\n predict_dir = args.predict_dir or args.valid_source_dir\n output_dir = args.predict_out or os.getcwd() + '/syn_'\n num_imgs = len(glob_nii(predict_dir[0]))\n if any([len(glob_nii(pd)) != num_imgs for pd in predict_dir]) or num_imgs == 0:\n raise SynthNNError('Number of images in prediction directories must be positive and have an equal number '\n 'of images in each directory (e.g., so that img_t1_1 aligns with img_t2_1 etc. for multimodal synth)')\n predict_fns = zip(*[glob_nii(pd) for pd in predict_dir])\n\n if args.net3d and psz > 0 and args.calc_var:\n raise SynthNNError('Patch-based 3D variance calculation not currently supported.')\n\n if args.net3d: # 3D Synthesis Loop\n for k, fn in enumerate(predict_fns):\n _, base, _ = split_filename(fn[0])\n logger.info(f'Starting synthesis of image: {base}. ({k+1}/{num_imgs})')\n img_nib = nib.load(fn[0])\n img = np.stack([nib.load(f).get_data().view(np.float32) for f in fn]) # set to float32 to save memory\n if img.ndim == 3: img = img[np.newaxis, ...]\n if psz > 0: # patch-based 3D synthesis\n out_img = np.zeros((args.n_output,) + img.shape[1:])\n count_mtx = np.zeros(img.shape[1:])\n x, y, z = get_overlapping_3d_idxs(psz, img)\n dec_idxs = np.floor(np.percentile(np.arange(x.shape[0]), np.arange(0, 101, 5)))\n pct_complete = 0\n j = 0\n # The below for-loop handles collecting overlapping patches and putting\n # them into a batch format that pytorch models expect (i.e., [N,C,H,W,D])\n # and running the batch through the network (storing the results in out_img).\n for i, (xx, yy, zz) in enumerate(zip(x, y, z)):\n if i in dec_idxs:\n logger.info(f'{pct_complete}% Complete')\n pct_complete += 5\n count_mtx[xx, yy, zz] = count_mtx[xx, yy, zz] + 1\n if j == 0:\n batch = np.zeros((args.batch_size,) + img[:, xx, yy, zz].shape, dtype=np.float32)\n batch_idxs = [(xx, yy, zz)]\n batch[j, ...] = img[:, xx, yy, zz]\n j += 1\n elif j != args.batch_size:\n batch_idxs.append((xx, yy, zz))\n batch[j, ...] = img[:, xx, yy, zz]\n j += 1\n else:\n batch = torch.from_numpy(batch).to(device)\n predicted = np.zeros(batch.shape)\n for _ in range(nsyn):\n predicted += fwd(model, batch, args.temperature_map)\n for ii, (bx, by, bz) in enumerate(batch_idxs):\n out_img[:, bx, by, bz] = out_img[:, bx, by, bz] + predicted[ii, ...]\n j = 0\n count_mtx[count_mtx == 0] = 1 # avoid division by zero\n out_img_nib = [nib.Nifti1Image(out_img[i]/count_mtx, img_nib.affine, img_nib.header) for i in range(args.n_output)]\n else: # whole-image-based 3D synthesis\n out_img = np.zeros((nsyn,) + img.shape)\n test_img = torch.from_numpy(img).to(device)[None, ...] # add empty batch dimension\n for j in range(nsyn):\n out_img[j] = fwd(model, test_img, args.temperature_map)[0] # remove empty batch dimension\n out_img = np.mean(out_img, axis=0) if not args.calc_var else np.var(out_img, axis=0)\n out_img_nib = [nib.Nifti1Image(out_img[i], img_nib.affine, img_nib.header) for i in range(args.n_output)]\n save_imgs(out_img_nib, output_dir, k, logger)\n\n else: # 2D Synthesis Loop -- goes by slice, does not use patches\n for k, fn in enumerate(predict_fns):\n _, base, _ = split_filename(fn[0])\n logger.info(f'Starting synthesis of image: {base}. ({k+1}/{num_imgs})')\n img_nib = nib.load(fn[0])\n img = np.stack([nib.load(f).get_data().view(np.float32) for f in fn]) # set to float32 to save memory\n if img.ndim == 3: img = img[np.newaxis, ...]\n out_img = np.zeros((nsyn, args.n_output) + img.shape[1:])\n num_batches = floor(img.shape[axis+1] / bs) # add one to axis to ignore channel dim\n if img.shape[axis+1] / bs != num_batches:\n lbi = int(num_batches * bs) # last batch index\n num_batches += 1\n lbs = img.shape[axis+1] - lbi # last batch size\n else:\n lbi = None\n for i in range(num_batches if lbi is None else num_batches-1):\n logger.info(f'Starting batch ({i+1}/{num_batches})')\n batch2d(model, img, out_img, axis, device, bs, i*bs, nsyn, args.temperature_map)\n if lbi is not None:\n logger.info(f'Starting batch ({num_batches}/{num_batches})')\n batch2d(model, img, out_img, axis, device, lbs, lbi, nsyn, args.temperature_map)\n out_img = np.mean(out_img, axis=0) if not args.calc_var else np.var(out_img, axis=0)\n out_img_nib = [nib.Nifti1Image(out_img[i], img_nib.affine, img_nib.header) for i in range(args.n_output)]\n save_imgs(out_img_nib, output_dir, k, logger)\n\n return 0\n except Exception as e:\n logger.exception(e)\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:]))\n","sub_path":"synthnn/exec/nn_predict.py","file_name":"nn_predict.py","file_ext":"py","file_size_in_byte":11088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"652716817","text":"import nltk\nimport re\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \nfrom nltk.corpus import gutenberg as cg\n\n\ndef preprocess(text):\n text = text.lower()\n # remove just punctuation\n # tokenizer = RegexpTokenizer(r'\\w+')\n # remove punctuation & numbers\n tokenizer = RegexpTokenizer(r'[a-z]+')\n tokens = tokenizer.tokenize(text)\n # remove stop words\n stoplist = set(stopwords.words('english'))\n cleanwordlist = [word for word in tokens if word not in stoplist]\n # remove rare words\n freqDist = nltk.FreqDist(cleanwordlist)\n rare_words_len = int(len(cleanwordlist) * 0.05)\n rare_words = list(freqDist.keys())[-rare_words_len:]\n print(rare_words)\n after_rare_words= [word for word in cleanwordlist if word not in rare_words]\n return after_rare_words\n\nf = open('../lab2/notes.txt', 'r')\ncontents = f.read()\nf.close()\n\nraw_content = cg.raw(\"burgess-busterbrown.txt\")\nsentence = 'this is just a test2324!!!q234 asdlfijasdlkfj jeans t-shirt aisdf hi hello hey jeans lion lion lion lion lion lion ladf alsdfkj asdf' \npreprocess(contents)\n","sub_path":"lab4/lab4_preprocess.py","file_name":"lab4_preprocess.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"39822856","text":"from math import sqrt\n\ndef addMatrix(a, b):\n if len(a) != len(b) or len(a[0]) != len(b[0]):\n return None\n\n c = []\n for row in range(len(a)):\n c.append([])\n for col in range(len(a[row])):\n c[row].append(a[row][col] + b[row][col])\n return c\n\ndef getMatrix(num = \"\"):\n matrix = []\n string = \"행렬\" + str(num) + \"을 입력하세요.: \"\n line = input(string).split()\n n = round(sqrt(len(line)))\n for i in range(len(line)):\n if i % n == 0:\n matrix.append([])\n matrix[i // n].append(eval(line[i]))\n return matrix\n\nmat1 = getMatrix(1)\nmat2 = getMatrix(2)\nmat3 = addMatrix(mat1, mat2)\nprint(\"\\n두 행렬은 다음과 같이 더해집니다.\")\nfor i in range(3):\n print(('{0:5.1f}{1:5.1f}{2:5.1f}{3:>3s}{4:5.1f}{5:5.1f}{6:5.1f}{7:>3s}' +\n '{8:5.1f}{9:5.1f}{10:5.1f}').format(mat1[i][0], mat1[i][1], mat1[i][2], ' ' if i != 1 else '+',\n mat2[i][0], mat2[i][1], mat2[i][2], ' ' if i != 1 else '=',\n mat3[i][0], mat3[i][1], mat3[i][2]))","sub_path":"PythonProgramming/cp11/프로그래밍 연습문제(cp11)/11.5.py","file_name":"11.5.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"421605833","text":"from __future__ import print_function\n\nimport os\nimport orca\nimport pandas as pd\nfrom baus import datasources\n\n\n@orca.step()\ndef geographic_summary(parcels, households, jobs, buildings, year, superdistricts_geography,\n initial_summary_year, interim_summary_year, final_year): \n\n if year not in [initial_summary_year, interim_summary_year, final_year]:\n return\n\n households_df = orca.merge_tables('households', [parcels, buildings, households],\n columns=['juris', 'superdistrict', 'county', 'subregion', 'base_income_quartile',])\n\n jobs_df = orca.merge_tables('jobs', [parcels, buildings, jobs],\n columns=['juris', 'superdistrict', 'county', 'subregion', 'empsix'])\n\n buildings_df = orca.merge_tables('buildings', [parcels, buildings],\n columns=['juris', 'superdistrict', 'county', 'subregion', 'building_type', \n 'residential_units', 'deed_restricted_units', 'non_residential_sqft'])\n\n #### summarize regional results ####\n region = pd.DataFrame(index=['region'])\n region.index.name = 'region'\n\n # households\n region['tothh'] = households_df.size\n for quartile in [1, 2, 3, 4]:\n region['hhincq'+str(quartile)] = households_df[households_df.base_income_quartile == quartile].size\n\n # employees by sector\n region['totemp'] = jobs_df.size\n for empsix in [ 'AGREMPN', 'MWTEMPN', 'RETEMPN', 'FPSEMPN', 'HEREMPN', 'OTHEMPN']:\n region[empsix] = jobs_df[jobs_df.empsix == empsix].size\n\n # residential buildings\n region['residential_units'] = buildings_df.residential_units.sum() \n region['deed_restricted_units'] = buildings_df.deed_restricted_units.sum() \n region['sfdu'] = buildings_df[(buildings_df.building_type == 'HS') | (buildings_df.building_type == 'HT')].residential_units.sum()\n region['mfdu'] = buildings_df[(buildings_df.building_type == 'HM') | (buildings_df.building_type == 'MR')].residential_units.sum()\n \n # non-residential buildings\n region['non_residential_sqft'] = buildings_df.non_residential_sqft.sum()\n region.to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"geographic_summaries/region_summary_{}.csv\").format(year))\n\n #### summarize by sub-regional geography ####\n geographies = ['juris', 'superdistrict', 'county', 'subregion']\n\n for geography in geographies:\n\n # remove rows with null geography- seen with \"county\"\n buildings_df = buildings_df[~pd.isna(buildings_df[geography])]\n households_df = households_df[~pd.isna(households_df[geography])]\n jobs_df = jobs_df[~pd.isna(jobs_df[geography])]\n\n summary_table = pd.DataFrame(index=buildings_df[geography].unique())\n \n # add superdistrict name \n if geography == 'superdistrict':\n superdistricts_geography = superdistricts_geography.to_frame()\n summary_table = summary_table.merge(superdistricts_geography[['name']], left_index=True, right_index=True)\n\n # households\n summary_table['tothh'] = households_df.groupby(geography).size()\n for quartile in [1, 2, 3, 4]:\n summary_table['hhincq'+str(quartile)] = households_df[households_df.base_income_quartile == quartile].groupby(geography).size()\n\n # residential buildings\n summary_table['residential_units'] = buildings_df.groupby(geography).residential_units.sum() \n summary_table['deed_restricted_units'] = buildings_df.groupby(geography).deed_restricted_units.sum() \n summary_table['sfdu'] = buildings_df[(buildings_df.building_type == 'HS') | (buildings_df.building_type == 'HT')].\\\n groupby(geography).residential_units.sum()\n summary_table['mfdu'] = buildings_df[(buildings_df.building_type == 'HM') | (buildings_df.building_type == 'MR')].\\\n groupby(geography).residential_units.sum()\n \n # employees by sector\n summary_table['totemp'] = jobs_df.groupby(geography).size()\n for empsix in ['AGREMPN', 'MWTEMPN', 'RETEMPN', 'FPSEMPN', 'HEREMPN', 'OTHEMPN']:\n summary_table[empsix] = jobs_df[jobs_df.empsix == empsix].groupby(geography).size()\n\n # non-residential buildings\n summary_table['non_residential_sqft'] = buildings_df.groupby(geography)['non_residential_sqft'].sum().round(0)\n \n summary_table.index.name = geography\n summary_table = summary_table.sort_index()\n summary_table.fillna(0).to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"geographic_summaries/{}_summary_{}.csv\").\\\n format(geography, year))\n\n\n@orca.step()\ndef geographic_growth_summary(year, final_year, initial_summary_year):\n \n if year != final_year: \n return\n\n geographies = ['region', 'juris', 'superdistrict', 'county', 'subregion']\n\n for geography in geographies:\n\n # use 2015 as the base year\n year1 = pd.read_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"geographic_summaries/%s_summary_%d.csv\" % (geography, initial_summary_year)))\n year2 = pd.read_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"geographic_summaries/%s_summary_%d.csv\" % (geography, final_year)))\n\n geog_growth = year1.merge(year2, on=geography, suffixes=(\"_\"+str(initial_summary_year), \"_\"+str(final_year)))\n\n if geography == 'superdistict':\n geog_growth = geog_growth.rename(columns={\"name_\"+(str(initial_summary_year)): \"name\"})\n geog_growth = geog_growth.drop(columns=[\"name_\"+(str(final_year))])\n \n columns = ['tothh', 'totemp', 'residential_units', 'deed_restricted_units', 'non_residential_sqft']\n \n for col in columns:\n # growth in households/jobs/etc.\n geog_growth[col+\"_growth\"] = (geog_growth[col+\"_\"+str(final_year)] - \n geog_growth[col+\"_\"+str(initial_summary_year)])\n\n # percent change in geography's households/jobs/etc.\n geog_growth[col+'_pct_change'] = (round((geog_growth[col+\"_\"+str(final_year)] / \n geog_growth[col+\"_\"+str(initial_summary_year)] - 1) * 100, 2))\n\n # percent geography's growth of households/jobs/etc. of all regional growth in households/jobs/etc.\n geog_growth[col+'_pct_of_regional_growth'] = (round(((geog_growth[col+\"_growth\"]) / \n (geog_growth[col+\"_\"+str(final_year)].sum() - \n geog_growth[col+\"_\"+str(initial_summary_year)].sum())) * 100, 2))\n\n # change in the regional share of households/jobs/etc. in the geography \n geog_growth[col+\"_\"+str(initial_summary_year)+\"_regional_share\"] = (round(geog_growth[col+\"_\"+str(initial_summary_year)] / \n geog_growth[col+\"_\"+str(initial_summary_year)].sum(), 2))\n geog_growth[col+\"_\"+str(final_year)+\"_regional_share\"] = (round(geog_growth[col+\"_\"+str(final_year)] / \n geog_growth[col+\"_\"+str(final_year)].sum(), 2)) \n geog_growth[col+'_regional_share_change'] = (geog_growth[col+\"_\"+str(final_year)+\"_regional_share\"] - \n geog_growth[col+\"_\"+str(initial_summary_year)+\"_regional_share\"])\n \n geog_growth = geog_growth.fillna(0)\n geog_growth.to_csv(os.path.join(orca.get_injectable(\"outputs_dir\"), \"geographic_summaries/{}_summary_growth.csv\").format(geography))","sub_path":"baus/summaries/geographic_summaries.py","file_name":"geographic_summaries.py","file_ext":"py","file_size_in_byte":7670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"478626767","text":"import cv2\nimport numpy as np\nimport logging\n\ncap = cv2.VideoCapture('/home/ydbondt/Downloads/IMG_0607-non-HEVC.mov')\nfourcc = cv2.cv.CV_FOURCC(*'DIVX')\n\nif (cap.isOpened() == False):\n print(\"Error\")\n\nret, first_frame = cap.read()\nout = cv2.VideoWriter('output.avi', fourcc, 20.0, (first_frame.shape[1], first_frame.shape[0]))\n\nhistory_points = []\nwhile (cap.isOpened() == True):\n ret, frame = cap.read()\n if ret == True:\n \n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n lower_orange = np.array([0, 162, 186])\n upper_orange = np.array([46, 242, 255])\n\n rangeMask = cv2.inRange(hsv, lower_orange, upper_orange)\n\n contours, hierarchy = cv2.findContours(rangeMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE);\n\n for c in contours:\n M = cv2.moments(c)\n perimeter = cv2.arcLength(c, True)\n print(perimeter)\n if M[\"m00\"] != 0 and perimeter > 100:\n cv2.drawContours(frame, [c], -1, (0,255,0), 3)\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n point = (cX, cY)\n history_points.append(point)\n prev_point = None\n for p in history_points:\n if (prev_point is None):\n prev_point = p\n\n cv2.line(frame, prev_point, p, (0,255,0), 2)\n prev_point = p\n\n out.write(frame)\n cv2.imshow('Frame', frame);\n\n if cv2.waitKey(1) & 0xFF == ord('q'): # press q to quit\n break\n else:\n break\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n","sub_path":"detect-ball.py","file_name":"detect-ball.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"539521022","text":"import argparse\nimport sys\nimport collections\nimport os\n\n_stats_path = \"\"\n_software_flag = \"\"\n_graph_flag = \"\"\n_base_path = \"\"\n_graph_title = \"\"\n_output_path = \"\"\n_version = 0.0\nplt = None\n\nBOX_SEQ_LEN_LABEL = \"Sequence Length\"\n\n# Ensure these flags match with main EnTAP project #\n# Frame Selection = 1\n# Expression = 2\n# Similarity Search = 3\n# Ontology = 4\n#***************************************************#\n\n\ndef init_argparse():\n global _base_path\n global _stats_path\n global _software_flag\n global _graph_flag\n global _graph_title\n global _output_path\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', action='store', dest='stats', help='Path to graphing file', type=str)\n parser.add_argument('-s', action='store', dest='soft', help='Software flag', type=int)\n parser.add_argument('-g', action='store', dest='graph', help='Graph flag', type=int)\n parser.add_argument('-t', action='store', dest='title', help='Graph title', type=str)\n parser.add_argument('-p', action='store', dest='path', help='Output path', type=str)\n args = parser.parse_args()\n _stats_path = args.stats\n _output_path = args.path\n _graph_title = args.title\n if _graph_title is not None:\n _graph_title = _graph_title.replace(\"_\", \" \")\n _graph_flag = args.graph\n _software_flag = args.soft\n\n\ndef init_version():\n global _version\n _version = sys.version_info[0] + 0.1*sys.version_info[1]\n\n\ndef verify_package():\n is_2 = 2 <= _version < 3\n has_matplot = False\n if is_2:\n import imp\n try:\n imp.find_module(\"matplotlib\")\n has_matplot = True\n except ImportError:\n has_matplot = False\n elif _version >= 3.4:\n import importlib.util\n check = importlib.util.find_spec(\"matplotlib\")\n has_matplot = check is not None\n elif not is_2 and _version < 3.4:\n import importlib\n spam_loader = importlib.find_loader(\"matplotlib\")\n has_matplot = spam_loader is not None\n else:\n print(\"Python version not compatable.\")\n exit(1)\n if has_matplot:\n global plt\n import matplotlib.pyplot as plt\n else:\n print(\"Matplotlib module not found. Not able to graph data.\")\n exit(1)\n\n\ndef init_graphs():\n pass\n\n\ndef frame_selection_graphs():\n if _graph_flag == 1: # Pie chart of each gene type\n InputValues = parse_input(_stats_path)\n create_pie(_graph_title, _output_path, InputValues.values, InputValues.labels)\n elif _graph_flag == 2: # Box plot of rejected vs kept sequences and length\n input_vals = parse_input_dict(_stats_path)\n create_boxplot(_graph_title, _output_path, input_vals, BOX_SEQ_LEN_LABEL)\n\n pass\n\n\ndef expression_graphs():\n if _graph_flag == 1:\n input_vals = parse_input_dict(_stats_path)\n create_boxplot(_graph_title, _output_path, input_vals, BOX_SEQ_LEN_LABEL)\n pass\n\n\ndef sim_search_graphs():\n if _graph_flag == 1:\n InputValues = parse_input(_stats_path)\n create_bar(_graph_title, _output_path, InputValues.values, InputValues.labels,\n InputValues.xlabel, InputValues.ylabel)\n pass\n\n\ndef ontology_graphs():\n if _graph_flag == 1:\n InputValues = parse_input(_stats_path)\n create_bar(_graph_title, _output_path, InputValues.values, InputValues.labels,\n InputValues.xlabel, InputValues.ylabel)\n pass\n\n\ndef create_graphs(flag):\n if flag == -1: # Initial test case\n exit(0)\n if flag == 1:\n frame_selection_graphs()\n elif flag == 2:\n expression_graphs()\n elif flag == 3:\n sim_search_graphs()\n elif flag == 4:\n ontology_graphs()\n else:\n init_graphs()\n\n\ndef create_pie(title, file, vals, labels):\n plt.pie(vals, labels=labels, autopct=autopct_vals(vals))\n plt.axis('equal')\n plt.title(title)\n plt.gcf().subplots_adjust(bottom=0.15)\n plt.savefig(file)\n\n\n# label_vals = dictionary of lists containing different series. Such as all rejected seqs and kept\ndef create_boxplot(title, file, label_vals, y_label):\n data = []\n labels = label_vals.keys()\n for key in label_vals.keys():\n temp = []\n for val in label_vals[key]:\n temp.append(val)\n data.append(temp)\n plt.ylabel(y_label)\n plt.boxplot(data, labels=labels)\n plt.title(title)\n plt.gcf().subplots_adjust(bottom=0.15)\n plt.savefig(file)\n\n\ndef create_bar(title, file, vals, labels, xlabel, ylabel):\n plt.barh(range(len(labels)), vals, align='center', alpha=0.5) # Horizontal bar graph\n plt.yticks(range(len(labels)), labels)\n plt.ylabel(xlabel)\n plt.xlabel(ylabel)\n plt.title(title)\n plt.savefig(file, bbox_inches=\"tight\")\n\n\ndef autopct_vals(values):\n def my_autopct(pct):\n total = sum(values)\n val = int(round(pct * total / 100.0))\n return '{p:.2f}% ({v:d})'.format(p=pct, v=val)\n return my_autopct\n\n\n# Return collection containing values and labels for them\n# Primarily used for single label - value series, NOT multiple values to one label\ndef parse_input(path):\n UserVals = collections.namedtuple('Values', ['values', 'labels', 'xlabel', 'ylabel'])\n file = open(path, 'r')\n labels = file.readline().split('\\t')\n UserVals.xlabel = labels[0]\n UserVals.ylabel = labels[1]\n UserVals.labels = []\n UserVals.values= []\n for line in file:\n if not line:\n continue\n values = line.strip().split('\\t')\n UserVals.labels.append(values[0])\n UserVals.values.append(int(values[1]))\n return UserVals\n\n\ndef parse_input_dict(path):\n file = open(path, 'r')\n rows = file.readline().split('\\t') # not used currently\n series_dict = {}\n for line in file:\n if not line:\n continue\n values = line.strip().split('\\t')\n if not series_dict.__contains__(values[0]):\n series_dict[values[0]] = []\n series_dict[values[0]].append(int(values[1]))\n return series_dict\n\n\ndef main():\n init_version()\n verify_package()\n init_argparse()\n plt.ioff() # disable interactiveness\n create_graphs(_software_flag)\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/entap_graphing.py","file_name":"entap_graphing.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"326102182","text":"#等待输入\na = input(\"请输入一个时间(格式00:00:00):\") #输入一个时间的大小,要使用英文输入\n#分割\nb = a.split(\":\") #把a即输入的时间分割成列表形式\n#计算过程\nc = int(b[0]) * 3600 #提取时间的第一位,即小时数,并转换位秒\nd = int(b[1]) * 60 #提取时间的第二位,即分钟数,并转换位秒\ne = int(b[2]) #提取时间的第三位,即秒钟数\nf = c + d + e #算出时间的总秒数\n#输出\nprint('时间共:' + str(f) + '秒') #输出,结果需要转换为字符串\n","sub_path":"学校信息作业/时间分割.py","file_name":"时间分割.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"404760482","text":"from django import template\n\nfrom flatcontent.models import FlatContent\n\nregister = template.Library()\n\nclass FlatContentNode(template.Node):\n def __init__(self, slug, context_var=None, site_id=None):\n self.slug = slug\n self.context_var = context_var\n self.site_id = site_id\n\n def render(self, context):\n site_id = self.site_id\n if self.site_id != None:\n site_id = template.Variable(site_id).resolve(context)\n\n flat_content = FlatContent.get(slug=self.slug, site_id=site_id)\n if not self.context_var:\n return flat_content\n else:\n context[self.context_var] = flat_content\n return ''\n\ndef do_flatcontent(parser, token):\n \"\"\"\n Retrieves content from the ``FlatContent`` model given a slug, and\n optionally stores it in a context variable.\n \n Usage::\n \n {% flatcontent [slug] %}\n \n Optionally, you can specify a site using the following syntax::\n\n {% flatcontent [slug] for-site [site-id] %}\n\n To get the flatcontent into a variable for later use in the template or\n with tags and filters::\n \n {% flatcontent [slug] as [varname] %}\n \n \"\"\"\n bits = token.split_contents()\n len_bits = len(bits)\n varname = None\n if len_bits not in (2, 4, 6):\n raise template.TemplateSyntaxError(\"The flatcontent tag requires \"\n \"1, 3, or 5 arguments\")\n\n try:\n site_id = bits[bits.index('for-site') + 1]\n except ValueError:\n site_id = None\n\n try:\n context_var = bits[bits.index('as') + 1]\n except ValueError:\n context_var = None\n\n if len_bits > 2 and site_id is None and context_var is None:\n raise template.TemplateSyntaxError(\"The second or fourth argument \"\n \"should be 'as' or 'for-site'\")\n\n return FlatContentNode(bits[1], context_var=context_var, site_id=site_id)\n\nregister.tag('flatcontent', do_flatcontent)\n","sub_path":"flatcontent/templatetags/flatcontent_tags.py","file_name":"flatcontent_tags.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"164154694","text":"import os\n\n\n\"\"\"\nForks a process and runs another program.\nThis needs completing as it does not reap any of the children.\n\ncreated by: Daniel Gormly\n\"\"\"\n\n\ndef child():\n print(\"Child process\")\n os.execl(\"../../../run.sh\", \"run.sh\", \"\")\n os._exit(0)\n\n\ndef parent():\n while True:\n newpid = os.fork()\n if newpid == 0:\n child()\n else:\n pids = (os.getpid(), newpid)\n print(\"Parent: %d, Child: %d\" % pids)\n os.wait()\n reply = raw_input(\"q for quit / c for new fork\\n\")\n if reply == \"c\":\n continue\n else:\n break\n\nparent()","sub_path":"Python Examples/hub/forkExample.py","file_name":"forkExample.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"202812891","text":"#######################################\n# PART 1: IMPORT, FUNCTIONS\n# If any package is not imported use in CMD command: python -m pip install SomePackage\n\n# Import basic packages\nimport os\nfrom os import walk\n\n# Import tkinter for GUI elements\nimport tkinter as tk\nfrom tkinter import filedialog\n\nroot = tk.Tk()\nroot.withdraw()\n\n#######################################\n# PART 2: OPEN\n\n# Onboarding for the user\nprint(\"\"\"This script creates a TXT file of all IFC files in one Folder to be use for Navisworks Batch Utility.\nFor the script to function properly you need to provide it with an directory to a folder containing subfolders with *.nwd files.\"\"\")\n\n\n# Prompt user to select folder directory and check for a valid input\nfolder_dir = \"//eleaic.local/diski/Projekti/35_GEO/190175-2TDK/5_WORK/55_GEO/0_Splošno/00_BIM/01_Delni modeli\"\n\n# folder_dir = filedialog.askdirectory(\n# initialdir = os.path.abspath(\"..\"),\n# title = 'Please select a directory')\n\nif folder_dir == \"\":\n print(\"\\nPlease select a directory.\")\n input(\"Press Enter to exit...\")\n exit()\n\n#######################################\n# PART 3: FIND ALL SUBFOLDERS\n\n# Finds all level one subfolders in given folder_dir\nfiles = []\nfor (dirpath, dirnames, filenames) in walk(folder_dir):\n subfolders_dir = dirnames\n break\n\n#######################################\n# PART 4: FIND NWD FILES AND WRITE .TXT\n\nlist_txt_file = open(folder_dir + \"/Zbirni model_ListOfNWD.txt\", \"w\", encoding=\"utf-8\")\n\n# Checks each individual folder in subfolders_dir list\nfor folder in subfolders_dir:\n\n if folder.startswith(\"PZI_\"):\n subfolder_dir = folder_dir + \"/\" + folder\n\n files = []\n if not subfolder_dir.endswith(\"bkp\"):\n # Checks each individual file in filenames list for \".nwd\" ending and creates a list of them\n for (dirpath, dirnames, filenames) in walk(subfolder_dir):\n for file in filenames:\n if file.lower().endswith(\".nwd\"):\n files.append(file)\n\n # Writes .txt of all files in folder with specific name in .txt\n for f in files:\n list_txt_file.write(subfolder_dir + \"/\" + f + \"\\n\")\n\n break\n\nlist_txt_file.close()\n\nexit()\n","sub_path":"Federated Models for NWS/Scripts and Reports/07_CreateSubfolderLists_NWD.py","file_name":"07_CreateSubfolderLists_NWD.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"580595903","text":"def Check(line):\n\tif line.count('X')+line.count('T')==4: return 'X'\n\telif line.count('O')+line.count('T')==4: return 'O'\n\treturn None\n\t\n\ndef Win(board):\n\tfor i in xrange(0,13,4):\n\t\twinner = Check(board[i:i+4])\n\t\tif winner != None: return winner\n\n\tfor i in xrange(0,4):\n\t\twinner = Check(board[i]+board[i+4]+board[i+8]+board[i+12])\n\t\tif winner != None: return winner\n\t\t\n\twinner = Check(board[0]+board[5]+board[10]+board[15])\n\tif winner != None: return winner\n\twinner = Check(board[3]+board[6]+board[9]+board[12])\n\tif winner != None: return winner\n\t\n\treturn None\n\t\n\t\nif __name__ == \"__main__\":\n\n\tfin = open('A-large.in', 'r').readlines()\n\tfout = open('A-large.out', 'wb')\n\tT = int(fin[0].strip())\n\n\tfor i in xrange(T):\n\t\tboard = fin[5*i+1].strip() + fin[5*i+2].strip() + fin[5*i+3].strip() + fin[5*i+4].strip()\n\t\tempty = board.count('.')\n\t\twinner = Win(board)\n\t\tif winner!=None: fout.write('Case #{}: {} won\\n'.format(i+1,winner))\n\t\telif empty>0: fout.write('Case #{}: Game has not completed\\n'.format(i+1))\n\t\telse: fout.write('Case #{}: Draw\\n'.format(i+1))\n\t","sub_path":"solutions_2453486_1/Python/DDrDreDrew/Qualification_Source.py","file_name":"Qualification_Source.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"1397627","text":"import xml.sax,os,re\nimport sys\nimport time\nfrom collections import defaultdict\n#import Stemmer\nimport snowballstemmer\nfrom heapq import *\nimport glob\n\nstemmer = snowballstemmer.stemmer('english')\n#stemmer = Stemmer.Stemmer('english')\nstopwords ={}\ndicts = {'categories' : {}, 'references' : {},'title' : {}, 'body' : {},'external_links' : {},'infobox' :{}}\ndir_list=[\"categories\",\"references\",\"title\",\"body\",\"external_links\",\"infobox\"]\nfile_count = 1\nno_of_doc = 0\ncount = 0\ndocuments_per_file = 20000\nlines_per_doc = 8000\n\nft = open('./Index/title_id.txt','w')\n\nclass contenthandler(xml.sax.ContentHandler):\n\t\n\tdef __init__(self):\n\t\txml.sax.ContentHandler.__init__(self)\n\t\tself.doc_id = \"\"\n\t\tself.text = \"\"\n\t\tself.title = \"\"\n\t\tself.content = \"\"\n\t\tself.body = \"\"\n\t\tself.external_links = \"\"\n\t\tself.references = \"\"\n\t\tself.categories = \"\"\n\t\tself.infobox = \"\"\n\t\tself.current = \"\"\n\t\tself.parent = \"\"\n\t\tself.elements = []\n\n\tdef startElement(self,name,attrs):\n\t\t\n\t\tself.elements.append(name)\n\t\tif self.current:\n\t\t\tself.parent = self.current\n\t\tself.current = name\n\t\t\n\tdef endElement(self,name):\n\t\t\n\t\tif name == 'page':\n\t\t\tglobal no_of_doc,count,file_count,dicts\n\t\t\tno_of_doc += 1 \n\t\t\tcount += 1\n\t\t\tself.preprocessing(self.categories.lower(),'categories')\n\t\t\tself.preprocessing(self.references.lower(),'references')\n\t\t\tself.preprocessing(self.title.lower(),'title')\n\t\t\tself.preprocessing(self.body.lower(),'body')\n\t\t\tself.preprocessing(self.external_links.lower(),'external_links')\n\t\t\tself.preprocessing(self.infobox.lower(),'infobox')\n\t\t\tif count == documents_per_file:\n\t\t\t\tfor key in dir_list:\n\t\t\t\t\twrite_to_file(key, opfilepath + '/' + key)\n\t\t\t\t\t#print 'key :' + key + 'file count :' + str(file_count)\n\t\t\t\tdicts.clear()\n\t\t\t\tdicts = {'categories' : {}, 'references' : {},'title' : {}, 'body' : {},'external_links' : {},'infobox' :{}}\n\t\t\t\tfile_count += 1\n\t\t\t\tcount = 0\n\t\t\tft.write(str(self.doc_id.rstrip('\\n'))+':'+str(self.title))\n\n\t\tif name == 'id':\n\t\t\t#global no_of_doc\n\t\t\tif self.parent == 'page':\n\t\t\t\tself.doc_id = self.content\n\t\t\t#\tno_of_doc += 1\n\t\t\t\t#print 'document with id: ' + self.doc_id\n\t\t\n\t\tif name == 'title':\n\t\t\tself.title = self.content\n\t\t\t#ft.write(str(self.doc_id)+':'+str(self.title))\n\t\t\t#if self.doc_id != \"\":\n\t\t\t#\tft.write(self.title + \":\" + str(self.doc_id))\n\t\t\n\t\tif name == 'text':\n\t\t\tself.text = self.content\n\t\t\tself.parse_text()\n#\t\t\tself.categories,self.external_links,self.references,self.body,self.infobox = parse_text(self.text)\n\n\t\t# to get only one id so poping elements\n\t\tself.elements.pop()\n\t\tif self.elements:\n\t\t\tself.current = self.parent\n\t\t\tif len(self.elements) ==1:\n\t\t\t\tself.parent=\"\"\n\t\t\telse:\n\t\t\t\tself.parent= self.elements[-1]\n\t\telse:\n\t\t\tself.current=\"\"\n\t\tself.content =\"\"\n\t\t\n\n\tdef characters(self,content):\n\n\t\tuni = content.encode('utf-8').strip()\n\t\tif uni:\n\t\t\tself.content = self.content + uni + '\\n'\n\t\n\tdef preprocessing(self,text,flag):\n\t\t\n\t\ttext = re.sub(r'[^A-Za-z]', ' ', text)\n\t\tclean_text = text.split(' ')\n\t\tcontent = {}\n\t\tglobal dicts\n\t\tglobal stopwords\n\t\tfor i in range(len(clean_text)):\n\t\t\tif stemmer.stemWord(clean_text[i]) not in stopwords and len(clean_text[i])>0:\n\t\t\t\tif stemmer.stemWord(clean_text[i]) not in content:\n\t\t\t\t\tcontent[stemmer.stemWord(clean_text[i])]=1\n\t\t\t\telse:\n\t\t\t\t\tcontent[stemmer.stemWord(clean_text[i])]+=1\n\t\tfor (key,value) in content.iteritems():\n\t\t\tif key not in dicts[flag]:\n\t\t\t\tdicts[flag][key]=[1, str(self.doc_id.strip())+\":\"+str(value)+\",\"]\n\t\t\telse:\n\t\t\t\tdicts[flag][key][0]+=1\n\t\t\t\tdicts[flag][key][1]+=str(self.doc_id.strip())+\":\" + str(value)+\",\"\t\t\t\n\t\t#content.clear()\n\n\tdef parse_text(self):\n\n\t\tsentences = self.text.strip()\n\t\tsentences = sentences.split('\\n')\n\t\tself.categories = \"\"\n\t\tself.external_links = \"\"\n\t\tself.references = \"\"\n\t\tself.body = \"\"\n\t\tself.infobox = \"\"\n\t\tflag = 0\n\t\tfor line in sentences:\n\t\t\n\t\t\tif line.startswith(\"{{Infobox\"):\n\t\t\t\tflag = 1\n\t\t\t\tcontinue\n\t\t\telif flag == 1 and line == \"}}\":\n\t\t\t\tflag = 0\n\t\t\t\tcontinue\n\t\t\telif line.startswith(\"==References==\"):\n\t\t\t\tflag = 2\n\t\t\t\tcontinue\n\t\t\telif flag ==2 and (( line.startswith(\"==\") and line.find(\"Reference\")==-1) or line.startswith(\"[[Category:\") or line.startswith(\"{{\")):\n\t\t\t\tflag=0\n\t\t\telif flag ==3 and ( line.startswith(\"[[Category:\")):\n\t\t\t\tflag = 0\n\t\t\t\tcontinue\n\t\t\telif line.startswith(\"==External links==\"):\n\t\t\t\tflag = 3\n\t\t\t\tcontinue\n\t\n\t\t\tif line.startswith(\"[[Category:\"):\n\t\t\t\t#print \"entered category case\" + '\\n'\n\t\t\t\tself.categories += line[11:-2] + '\\n'\n\t\t\telif flag==0:\n\t\t\t\t#print \"entered body case\" + '\\n'\n\t\t\t\tself.body += line + '\\n'\n\t\t\telif flag ==1:\n\t\t\t\t#print \"entered infobox case\" + '\\n' \n\t\t\t\tself.infobox+=line+'\\n'\n\t\t\telif flag ==2:\n\t\t\t\t#print \"entered references case\" + '\\n'\n\t\t\t\tself.references += line + '\\n'\n\t\t\telif flag ==3:\n\t\t\t\t#print \"entered links case\" + '\\n'\n\t\t\t\tself.external_links +=line +'\\n'\n\nclass ExternalMerge:\n\n\tdef __init__(self,directory):\n\t\t\n\t\tself.file_name = directory + '/final'\n\t\tself.sec_file_name = directory + '/secondary.txt'\n\t\tself.directory = directory\n\t\tself.sub_count = 1\n\t\tself.latest_word = \"\"\n\t\tself.line_count = 0\n\t\tself.file_pointer = []\n\t\tself.l = []\n\t\tself.count = 0\n\n\tdef write_to_heap(self):\n\t\t\n\t\tglobal file_count\n\t\tfor i in xrange(1,file_count+1):\n\t\t\tf0 = open(self.directory+'/file'+str(i)+'.txt','r') \n\t\t\ts = f0.readline()[:-1]\n\t\t\ts1 = s[:s[:s.find(',')].find(':')]\n\t\t\tself.l.append((s1, s, f0))\n\t\t\tself.file_pointer.append(f0)\n\t\theapify(self.l)\n\n\tdef merge(self):\n\t\t\n\t\tglobal lines_per_doc\n\t\tf_sec = open(self.sec_file_name,'w')\n\t\tf = open(self.file_name + str(self.sub_count) + \".txt\",'w')\n\t\twhile(self.count < file_count):\n\t\t\ttop = heappop(self.l)\n\t\t\ts0 = top[0]\n\t\t\ts1 = top[1]\n\t\t\tf1 = top[2]\n\t\t\ts_list = []\n\t\t\ts_list.append(s1)\n\t\t\ts = f1.readline()[:-1]\n\t\t\tif s == '':\n\t\t\t\tself.count+=1\n\t\t\telse:\n\t\t\t\theappush(self.l, (s[:s[:s.find(',')].find(':')], s, f1))\n\n\t\t\tif self.count == file_count:\n\t\t\t\tbreak\n\n\t\t\twhile(1):\n\t\t\t\ttry:\n\t\t\t\t\ttmp = heappop(self.l)\n\t\t\t\texcept IndexError:\n\t\t\t\t\tbreak\n\t\t\t\ts0 = tmp[0]\n\t\t\t\ts2 = tmp[1]\n\t\t\t\tf2 = tmp[2]\n\t\t\t\t#print s2\n\t\t\t\t#print s_list[-1][:s_list[-1][:s2[-1].find(',')].find(':')]\n\t\t\t\tif s0 != s_list[-1][:s_list[-1][:s2[-1].find(',')].find(':')]:\n\t\t\t\t\theappush(self.l,(s0,s2,f2))\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\ts_list.append(s2)\n\t\t\t\t\ts3 = f2.readline()[:-1]\n\t\t\t\t\t#print s3\n\t\t\t\t\tif s3 == '':\n\t\t\t\t\t\tself.count += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\theappush(self.l,(s3[:s3[:s3.find(',')].find(':')],s3,f2))\n\n\t\t\tif len(s_list) == 1:\n\t\t\t\ts = s_list[0]\n\t\t\t\tself.line_count+=1\n\t\t\t\tself.latest_word = s[:s.find(':')]\n\t\t\t\t#print self.latest_word\n\t\t\t\tf.write(s+'\\n')\n\t\t\t\tif self.line_count == lines_per_doc: \n\t\t\t\t self.line_count = 0\n\t\t\t\t f.close()\n\t\t\t\t f_sec.write(self.file_name + str(self.sub_count)+\".txt\"+\":\"+self.latest_word+'\\n')\n\t\t\t\t self.sub_count += 1\n\t\t\t\t f = open(self.file_name+str(self.sub_count)+\".txt\",'w')\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tword_pre = s_list[0][:s_list[0].find(',')]\n\t\t\t\tword = word_pre[:word_pre.find(':')]\n\t\t\t\ttgif = 0\n\t\t\t\ts = \"\"\n\t\t\t\tflag = 0\n\t\t\t\tfor i in s_list:\n\t\t\t\t\tcontent = i[i.find(',')+1:]\n\t\t\t\t\tcontent_pre = i[:i.find(',')]\n\t\t\t\t\ttgif_tmp = int(content_pre[content_pre.find(':')+1:])\n\t\t\t\t\ttgif += tgif_tmp\n\t\t\t\t\tif flag == 0:\n\t\t\t\t\t\ts = content\n\t\t\t\t\t\tflag = 1\n\t\t\t\t\telse:\n\t\t\t\t\t\ts += ','+ content\n\t\t\t#print word+':'+str(tgif)+','+s+'\\n'\n\t\t\t\tself.line_count += 1\n\t\t\t\tself.latest_word = word\n\t\t\t\tf.write(word+':'+str(tgif)+','+s+'\\n')\n\t\t\t\tif self.line_count == lines_per_doc:\n\t\t\t\t self.line_count=0\n\t\t\t\t f.close()\n\t\t\t\t f_sec.write(self.file_name + str(self.sub_count)+\".txt\"+\":\"+word+'\\n')\n\t\t\t\t self.sub_count += 1\n\t\t\t\t f = open(self.file_name+str(self.sub_count)+\".txt\",'w')\n\t\tif f:\n\t\t\tf.close()\n\n\t\tif self.line_count>0:\n\t\t\tf_sec.write(self.file_name + str(self.sub_count)+\".txt\"+\":\"+self.latest_word+'\\n')\n\t\t\t\n\t\tf_sec.close()\n\n\t\tfor i in self.file_pointer:\t\n\t\t\ti.close()\n\ndef write_to_file(flag,directory):\n\t\n\t#global dicts,file_count\n\tglobal dicts\n\tglobal file_count\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\tkeys = dicts[flag].keys()\n\tkeys.sort()\n\tf = open(directory+'/file'+str(file_count)+\".txt\",'w')\n\tfor i in keys:\n\t\tfreq = dicts[flag][i][0]\n\t\tdoc_list = dicts[flag][i][1][:-1]\t\n\t\tfinal = i+\":\"+str(freq)+\",\"+doc_list+'\\n'\n\t\tf.write(final)\n\tf.close()\n\n\nif __name__ == \"__main__\":\n\t#start_time = time.time()\n\tipfilepath = sys.argv[1]\n\topfilepath = sys.argv[2]\n\tf = open('stopwords.txt','r')\n\tfor i in f:\n\t\tfor j in re.compile(r'[^A-Za-z]').split(i.lower()):\n\t\t\tif len(j)>0:\n\t\t\t\tstopwords[j.strip()] = True\n\tf.close()\n\tsource = open(ipfilepath,'r')\n\txml.sax.parse(source,contenthandler())\n\tft.close()\n\t#print \"before writing to file\"\n\tfor key in dir_list:\n\t\twrite_to_file(key,opfilepath+'/'+key)\n\t\t#os.remove(glob.glob(opfilepath + '/' + key + '/file*'))\n\t\tmerge_object = ExternalMerge(opfilepath + '/' + key)\n\t\tmerge_object.write_to_heap()\n\t\tmerge_object.merge()\n\t\tfor filename in glob.glob(opfilepath + '/' + key + '/file*'):\n\t\t\tos.remove(filename)\n\n\t\n\tf = open(opfilepath + \"/no_of_doc.txt\",'w'\t)\n\tf.write(str(no_of_doc) + '\\n')\n\tf.close()\t\n\t\n\t#print time.time()-start_time","sub_path":"parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":8959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"146615485","text":"import os\nimport json\nimport torch\nfrom tqdm import tqdm\nfrom metrics import Accuracy\nfrom torch.utils.data import DataLoader\nfrom torch.optim.lr_scheduler import StepLR\ntorch.manual_seed(42)\nfrom ipdb import set_trace as pdb\n\n\nclass Trainer:\n def __init__(self, device, trainData, validData, model, lr, batch_size, arch):\n self.device = device\n self.trainData = trainData\n self.validData = validData\n self.model = model\n self.criteria = torch.nn.BCEWithLogitsLoss()\n self.missing_criteria = torch.nn.MSELoss()\n self.opt = torch.optim.Adam(self.model.parameters(), lr=lr)\n self.scheduler = StepLR(self.opt, step_size=100, gamma=0.5)\n self.batch_size = batch_size\n self.arch = arch\n self.history = {'train': [], 'valid': []}\n\n def run_epoch(self, epoch, training):\n self.model.train(training)\n\n if training:\n description = 'Train'\n dataset = self.trainData\n shuffle = True\n else:\n description = 'Valid'\n dataset = self.validData\n shuffle = False\n dataloader = DataLoader(dataset=dataset,\n batch_size=self.batch_size,\n shuffle=shuffle,\n collate_fn=dataset.collate_fn,\n num_workers=4)\n\n trange = tqdm(enumerate(dataloader), total=len(dataloader), desc=description, ascii=True)\n\n f_loss = 0\n l_loss = 0\n accuracy = Accuracy()\n\n for i, (x, missing, y) in trange:\n o_labels, batch_f_loss, batch_l_loss = self.run_iter(x, missing, y)\n batch_loss = batch_f_loss + batch_l_loss\n\n if training:\n self.opt.zero_grad()\n batch_loss.backward()\n self.opt.step()\n\n f_loss += batch_f_loss.item()\n l_loss += batch_l_loss.item()\n accuracy.update(o_labels.cpu(), y)\n\n trange.set_postfix(accuracy=accuracy.print_score(), f_loss=f_loss / (i + 1), l_loss=l_loss / (i + 1))\n\n if training:\n self.history['train'].append({'accuracy': accuracy.get_score(), 'loss': f_loss / len(trange)})\n self.scheduler.step()\n else:\n self.history['valid'].append({'accuracy': accuracy.get_score(), 'loss': f_loss / len(trange)})\n\n def run_iter(self, x, missing, y):\n features = x.to(self.device)\n missing = missing.to(self.device)\n labels = y.to(self.device)\n o_missing, o_labels = self.model(features)\n f_loss = self.missing_criteria(o_missing, missing)\n l_loss = self.criteria(o_labels, labels)\n return o_labels, f_loss, l_loss\n\n def save(self, epoch):\n if not os.path.exists(self.arch):\n os.makedirs(self.arch)\n if epoch % 50 == 0:\n torch.save(self.model.state_dict(), self.arch + '/model.pkl.' + str(epoch))\n with open(self.arch + '/history.json', 'w') as f:\n json.dump(self.history, f, indent=4)\n","sub_path":"task2/src/trial1/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"606470600","text":"from unittest.mock import MagicMock\n\nfrom src.domain.item import Item\nfrom src.domain.shopping_list import ShoppingList\nfrom src.domain.shopping_list_item import ShoppingListItem\nfrom src.infrastructure.database.repositories.item import ItemRepositorySQL\nfrom src.infrastructure.database.repositories.shopping_list import ShoppingListRepositorySQL\nfrom src.usecases.add_item_to_current_list import AddItemToCurrentList\n\n\nclass AddItemToCurrentListTest:\n def setup_method(self):\n self.item_repository = ItemRepositorySQL()\n self.item_repository.add_item_to_referential = MagicMock()\n self.shopping_list_repository = ShoppingListRepositorySQL()\n self.shopping_list_repository.get_shopping_list = MagicMock()\n self.shopping_list_repository.update = MagicMock()\n self.add_item_to_current_list = AddItemToCurrentList(\n self.item_repository,\n self.shopping_list_repository\n )\n\n def should_add_item_to_current_user_shopping_list(self):\n # Given\n item_name = 'Cacao'\n user_id = 5\n item = Item(identifier=12, name='Caco')\n self.item_repository.add_item_to_referential.return_value = item\n shopping_list = ShoppingList(\n user_id=user_id,\n items=[\n ShoppingListItem(\n shopping_item_id=1,\n identifier=26,\n name='Lait'\n )\n ]\n )\n self.shopping_list_repository.get_shopping_list.return_value = shopping_list\n\n # When\n self.add_item_to_current_list.execute(new_item_name=item_name,\n user_id=user_id)\n\n # Then\n self.item_repository.add_item_to_referential.assert_called_once_with(item_name)\n self.shopping_list_repository.get_shopping_list.assert_called_once_with(user_id)\n self.shopping_list_repository.update.assert_called_once_with(shopping_list)\n","sub_path":"tests/usecases/add_item_to_current_list_test.py","file_name":"add_item_to_current_list_test.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"433881950","text":"#!/usr/bin/python3\nimport sys\nimport json_to_binary\nimport indexer\n'''\n将msr的训练集、测试集特征化序列化,变成工具包可以处理的样子\n'''\n\n \ndef _to_tags(sen):\n tags=[]\n for w in sen:\n if len(w)==1:\n tags.append(3)\n else:\n tags.append(0)\n for i in range(len(w)-2):tags.append(1)\n tags.append(2)\n return tags\n\n\ndef gen_keys(seq,i):\n mid=seq[i]\n left=seq[i-1] if i>0 else '#'\n left2=seq[i-2] if i-1>0 else '#'\n right=seq[i+1] if i+1=0,[inder(k) for k in gen_keys(seq,x)]) for x in range(len(seq))]\n for c,v in zip(_to_tags(line),fs):\n graph.append([0,[],c,v])\n if not graph:continue\n graph[0][0]+=1;\n graph[-1][0]+=2;\n for i in range(1,len(graph)):\n graph[i][1]=[i-1]\n json_to_binary.graph_to_file(graph,file)\n print('the end')\n file.close()\n\nif __name__=='__main__':\n if len(sys.argv)==1:#empty argv, do the debug\n print(\"reading training data\")\n train('msr_training.utf8','training.bin','index.json')\n print(\"reading test data\")\n test('index.json','msr_test_gold.utf8','test.bin')\n exit()\n \n task=sys.argv[1]\n if task=='l':\n print(\"reading training data\")\n #print((sys.argv[2],sys.argv[3],sys.argv[4]))\n train(sys.argv[2],sys.argv[3],sys.argv[4])\n exit()\n if task=='p':\n print(\"reading test data\")\n test(sys.argv[2],sys.argv[3],sys.argv[4])\n exit()\n \n","sub_path":" perminusminus/tagging/cws_transform.py","file_name":"cws_transform.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"354262091","text":"# -*- coding: utf-8 -*-\n\"\"\"\n# @SoftwareIDE : PyCharm2020Pro\n# @ProjectName : PySide2MVCFramework\n# @FileName : test_openQFile.py\n# @Author : 胡守杰\n# @Email : 2839414139@qq.com\n# @ZhFileDescription :\n# @EnFileDescription :\n\"\"\"\nfrom pyside2mvcframework.core.utils import OpenQFile\n\nif __name__ == '__main__':\n print(\"unit test from {filename}\".format(filename=__file__))\n with OpenQFile(\"测试.txt\") as fp:\n content = fp.readAll().data().decode()\n assert content == \"测试\"","sub_path":"test/test_openQFile.py","file_name":"test_openQFile.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"220805222","text":"# import tensorflow as tf\nimport numpy as np\nimport seaborn as sns\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nfrom sklearn.datasets import make_classification\n\ncmap1 = mpl.colors.ListedColormap(sns.color_palette('cubehelix'))\n\ndef draw_data(X_, y_):\n plt.scatter(X_[:, 0], X_[:, 1], c=y_, cmap=cmap1)\n\ndef graph_surface(X_, dec_fun):\n min, max = np.min(X_, axis=0), np.max(X_, axis=0)\n xlin, ylin = 800, 800\n x = np.linspace(min[0], max[0], xlin)\n y = np.linspace(min[1], max[1], ylin)\n xv, yv = np.meshgrid(x, y)\n data = np.vstack((xv.flatten(), yv.flatten()))\n decision = dec_fun(data.T)\n sns.set_palette('cubehelix')\n plt.pcolormesh(x, y, decision.reshape((xlin, ylin)), cmap=cmap1)\n\nclass BinaryLogReg():\n\n def __init__(self, D):\n self.w = np.random.randn(D)\n self.b = np.random.randn(1)\n\n def forward(self, x):\n s = np.dot(self.w, x.T) + self.b\n P1 = np.exp(s) / (1 + np.exp(s))\n return P1\n\n def fit(self, X, y, n_iters = 10000, eps = 0.001):\n for epoch in range(n_iters):\n P = self.forward(X)\n gs = P - (1 - y)\n self.w -= eps * np.dot(gs, X)\n self.b -= eps * np.sum(gs)\n loss = np.sum(np.abs(gs))\n if epoch % 100 == 0:\n print(\"Iter: {} / {}\\n\\tLoss: {}\".format(epoch, n_iters, loss))\n\nclass MulinomialLogReg():\n\n def __init__(self, D, C):\n self.W = np.random.randn(C, D)\n self.b = np.random.randn(C, 1)\n\n def forward(self, x):\n s = np.dot(self.W, x.T) + self.b\n P = np.apply_along_axis(self.softmax, 0, s)\n return P.T\n\n def classify(self, x):\n P = self.forward(x)\n return np.argmax(P, 1)\n\n def softmax(self, s):\n return np.exp(s) / np.sum(np.exp(s))\n\n def fit(self, X, y, n_iters = 10000, eps = 0.001):\n from sklearn.preprocessing import OneHotEncoder\n Y = OneHotEncoder().fit_transform(y.reshape((y.shape[0], 1))).toarray()\n for epoch in range(n_iters):\n P = self.forward(X)\n Gs = P - Y\n grad_w = np.dot(Gs.T, X)\n grad_b = np.sum(Gs, 0)\n grad_b = grad_b.reshape((grad_b.shape[0], 1))\n self.W -= eps * grad_w\n self.b -= eps * grad_b\n loss = np.sum(np.sum(np.abs(Gs)))\n if epoch % 100 == 0:\n print(\"Iter: {} / {}\\n\\tLoss: {}\".format(epoch, n_iters, loss))\n\ndef bin():\n C, D = 2, 2\n X, y = make_classification(n_samples=20, n_features=D, n_informative=2, n_redundant=0,\n n_repeated=0, n_classes=C, n_clusters_per_class=2, hypercube=True)\n\n logreg = BinaryLogReg(2)\n logreg.fit(X, y, n_iters=100000)\n\n graph_surface(X, logreg.forward)\n draw_data(X, y)\n\n plt.show()\n\n\ndef multi():\n C, D = 2, 2\n X, y = make_classification(n_samples=20, n_features=D, n_informative=2, n_redundant=0, n_repeated=0, n_classes=C, n_clusters_per_class=1, hypercube=True)\n mulreg = MulinomialLogReg(C, D)\n mulreg.fit(X, y, n_iters=10000)\n\n graph_surface(X, mulreg.classify)\n draw_data(X, y)\n\n plt.show()\n\nif __name__ == \"__main__\":\n # bin()\n multi()","sub_path":"vjezba0/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"386131593","text":"# 该示例用于将数据库表结构转换成go的struct\n\nimport mysql_parser as parser\n\n# 定义数据库配置\ndb_config = {\n 'user': 'root',\n 'password': 'root',\n 'host': '127.0.0.1',\n 'database': 'test'\n}\n\ngo_struct_template_header = \"type {table_name}Model struct {{\\n\"\ngo_struct_template_body = '\\t{field_name} {go_type} `orm:\"column({db_field_name})\"`\\n'\ngo_struct_template_footer = \"}\\n\"\n\ngo_field_const_template_header = \"const (\\n\"\ngo_field_const_template_body = '\\t{table_name}Field_{field_name} = \"{db_field_name}\"\\n'\ngo_field_const_template_footer = \")\\n\"\n\ngo_table_name_template = 'const Table{table_name} = \"{db_table_name}\"\\n'\n\n# 定义原始的数据库字段类型到go type的映射\nreflact_db_type = {\n \"bigint\": \"int64\"\n}\n\n# 将类型分类映射到gotype\nreflact_type_catalog = {\n parser.DB_INT_TYPE: \"int\",\n parser.DB_STRING_TYPE: \"string\",\n parser.DB_FLOAT_TYPE: \"float64\",\n parser.DB_STRING_TYPE: \"string\",\n parser.DB_UNKNOWN_TYPE: \"interface{}\",\n}\n\nresult = []\n\nfile = open(\"../../../trash/model.go\", \"w\")\n\n\ndef format_go_name(name):\n fs = name.split(\"_\")\n return \"\".join(list(\n map(\n lambda x: x.capitalize(), \n fs\n )))\n\n\ndef callback(table, fields_info):\n go_table_name = format_go_name(table)\n table_const = go_table_name_template.format(table_name=go_table_name, db_table_name=table)\n struct_header = go_struct_template_header.format(table_name=go_table_name)\n filed_const_header = go_field_const_template_header\n struct = struct_header\n filed_const = filed_const_header\n\n for field_obj in fields_info:\n field_name = field_obj[parser.FIELD_NAME]\n db_type = field_obj[parser.FIELD_TYPE]\n type_catalog = field_obj[parser.TYPE_CATALOG]\n\n if db_type in reflact_db_type:\n go_type = reflact_db_type[db_type]\n else:\n go_type = reflact_type_catalog.get(type_catalog, \"interface{}\")\n\n struct_body = go_struct_template_body.format(\n field_name=format_go_name(field_name),\n go_type=go_type,\n db_field_name=field_name\n )\n struct += struct_body\n\n field_const_body = go_field_const_template_body.format(\n table_name=go_table_name,\n field_name=format_go_name(field_name),\n db_field_name=field_name\n )\n filed_const += field_const_body\n \n struct += go_struct_template_footer\n filed_const += go_field_const_template_footer\n file.write(table_const)\n file.write(filed_const)\n file.write(struct)\n file.write(\"\\n\\n\")\n\n return 0\n\n\np = parser.MysqlParser(db_config)\np.walk_all_table_and_field(callback)","sub_path":"python/tools/gen_from_db/gen_go_struct.py","file_name":"gen_go_struct.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"180600098","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ali/ownCloud/Project/python/django-aparnik-framework-project/testandbuildprojectframework/aparnik/contrib/province/api/urls-town.py\n# Compiled at: 2020-01-05 09:49:45\n# Size of source mod 2**32: 370 bytes\nfrom django.conf.urls import url\nfrom aparnik.contrib.province.api.views import TownCreateAPIView, TownDetailAPIView, TownListAPIView\napp_name = 'province'\nurlpatterns = [\n url('^$', (TownListAPIView.as_view()), name='list'),\n url('^create/$', (TownCreateAPIView.as_view()), name='create'),\n url('^(?P\\\\d+)/$', (TownDetailAPIView.as_view()), name='detail')]","sub_path":"pycfiles/django-apar-1.1.6.45.tar/urls-town.cpython-37.py","file_name":"urls-town.cpython-37.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"328026533","text":"from __future__ import division, absolute_import, print_function\n\nfrom maya.api import OpenMaya\n\nimport mayawalk\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# Helpers\n\n\ndef create_node(node_type, parent=None, name=None):\n args = [node_type, parent] if parent is not None else [node_type]\n try: # Try to create a dependency node.\n modifier = OpenMaya.MDGModifier()\n node_mob = modifier.createNode(*args)\n except TypeError: # invalid node type (or invalid modifier)\n try: # Try to create a dag node.\n modifier = OpenMaya.MDagModifier()\n node_mob = modifier.createNode(*args)\n except TypeError: # invalid node type\n raise TypeError('Invalid node type: {}.'.format(node_type))\n if name is not None:\n modifier.renameNode(node_mob, name)\n modifier.doIt()\n\n # Renames created shapes.\n if node_mob.hasFn(OpenMaya.MFn.kTransform):\n dag = OpenMaya.MFnDagNode(node_mob)\n for index in range(dag.childCount()):\n child = dag.child(index)\n if child.hasFn(OpenMaya.MFn.kShape):\n modifier.renameNode(child, name + 'Shape')\n modifier.doIt()\n\n return node_mob\n\n\ndef find_plug(node, name):\n return OpenMaya.MFnDependencyNode(node).findPlug(name, False)\n\n# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n# Tests\n\n\ndef test_parent():\n parent = create_node('transform')\n child = create_node('transform', parent=parent)\n assert mayawalk.parent(child) == parent\n\n\ndef test_parent_world():\n world = OpenMaya.MItDependencyNodes(OpenMaya.MFn.kWorld).thisNode()\n node = create_node('transform')\n assert mayawalk.parent(node, include_world=False) is None\n assert mayawalk.parent(node, include_world=True) == world\n\n\ndef test_children_any():\n parent = create_node('transform')\n child_shape = create_node('nurbsCurve', parent=parent)\n child_transform = create_node('transform', parent=parent)\n assert list(mayawalk.children(parent)) == [child_shape, child_transform]\n\n\ndef test_children_filtered():\n parent = create_node('transform') # parent\n shape = create_node('nurbsCurve', parent=parent) # |- shape\n transform = create_node('transform', parent=parent) # |- transform\n\n found = list(mayawalk.children(parent, api_type=OpenMaya.MFn.kNurbsCurve))\n assert found == [shape]\n\n\ndef test_siblings_any():\n parent = create_node('transform') # parent\n node = create_node('transform', parent=parent) # |- node\n transform = create_node('transform', parent=parent) # |- transform\n joint = create_node('joint', parent=parent) # |- joint\n assert list(mayawalk.siblings(node)) == [transform, joint]\n\n\ndef test_siblings_filtered():\n parent = create_node('transform') # parent\n node = create_node('transform', parent=parent) # |- node\n transform = create_node('transform', parent=parent) # |- transform\n joint = create_node('joint', parent=parent) # |- joint\n assert list(mayawalk.siblings(node, api_type=OpenMaya.MFn.kJoint)) == [joint]\n\n\ndef test_siblings_world():\n # world\n node = create_node('transform') # |- node\n sibling = create_node('transform') # |- sibling\n\n # Default Maya camera nodes are also siblings of node.\n assert sibling in mayawalk.siblings(node)\n\n\ndef test_hierarchy_downstream():\n root = create_node('transform') # root\n curve_transform = create_node('transform', parent=root) # |- curve_transform\n shape = create_node('nurbsCurve', parent=curve_transform) # |- shape\n transform = create_node('transform', parent=root) # |- transform\n\n # Breadth first search\n breadth_first = list(mayawalk.hierarchy(root, depth_first=False))\n assert breadth_first == [root, curve_transform, transform, shape]\n\n # Depth first search\n depth_first = list(mayawalk.hierarchy(root, depth_first=True))\n assert depth_first == [root, transform, curve_transform, shape]\n\n\ndef test_hierarchy_upstream():\n parent = create_node('transform') # parent\n child = create_node('transform', parent=parent) # |- child\n grandchild = create_node('transform', parent=child) # |- grandchild\n\n found = list(mayawalk.hierarchy(grandchild, upstream=True))\n assert found == [grandchild, child, parent]\n\n\ndef test_hierarchy_stoppers():\n parent = create_node('transform') # parent\n child = create_node('transform', parent=parent) # |- child\n granchild = create_node('transform', parent=child) # |- grandchild\n assert list(mayawalk.hierarchy(parent, stoppers=[child])) == [parent, child]\n\n\ndef test_hierarchy_filtered():\n parent = create_node('transform') # parent\n child_joint = create_node('joint', parent=parent) # |- child_joint\n granchild = create_node('transform', parent=child_joint) # |- grandchild\n\n found = list(mayawalk.hierarchy(parent, api_type=OpenMaya.MFn.kJoint))\n assert found == [child_joint]\n\n\ndef test_top_nodes():\n node_a = create_node('transform') # node_a\n node_b = create_node('transform', parent=node_a) # |- node_b\n node_c = create_node('transform') # node_c\n node_d = create_node('transform', parent=node_c) # |- node_d\n node_e = create_node('transform', parent=node_d) # |- node_e\n\n found = list(mayawalk.top_nodes((node_a, node_b, node_d, node_e)))\n assert found == [node_a, node_d]\n\n\ndef test_top_nodes_sparse():\n node_a = create_node('transform') # node_a\n node_b = create_node('transform', parent=node_a) # |- node_b\n node_c = create_node('transform', parent=node_b) # |- node_c\n\n found = list(mayawalk.top_nodes((node_a, node_c), sparse=True))\n assert found == [node_a]\n\n\ndef test_plug_parent():\n node = OpenMaya.MFnDependencyNode(create_node('transform'))\n translate = node.findPlug('translate', False)\n translate_x = node.findPlug('translateX', False)\n assert mayawalk.plug_parent(translate) is None\n assert mayawalk.plug_parent(translate_x) == translate\n\n\ndef test_plug_children():\n node = OpenMaya.MFnDependencyNode(create_node('transform'))\n translate = node.findPlug('translate', False)\n children = [node.findPlug('translate' + axis, False) for axis in 'XYZ']\n assert list(mayawalk.plug_children(translate)) == children\n\n\ndef test_plug_children_reverse():\n node = OpenMaya.MFnDependencyNode(create_node('transform'))\n translate = node.findPlug('translate', False)\n children = [node.findPlug('translate' + axis, False) for axis in 'ZYX']\n assert list(mayawalk.plug_children(translate, reverse=True)) == children\n\n\ndef test_plugs():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n OpenMaya.MDGModifier().connect(plug_src, plug_dst).doIt()\n\n status = mayawalk.ConnectionStatus\n\n # Has plug\n assert plug_src in mayawalk.plugs(node_src)\n\n # Has connections\n assert list(mayawalk.plugs(node_src, status.kConnected)) == [plug_src]\n assert plug_src not in mayawalk.plugs(node_src, status.kDisconnected)\n\n # Has destination connections\n assert list(mayawalk.plugs(node_src, status.kConnectedDestinations)) == [plug_src]\n assert plug_src not in mayawalk.plugs(node_src, status.kDisconnectedDestinations)\n\n # Has no source connections\n assert plug_src not in mayawalk.plugs(node_src, status.kConnectedSources)\n assert plug_src in mayawalk.plugs(node_src, status.kDisconnectedSources)\n\n\ndef test_connected():\n src = create_node('transform')\n dst = create_node('transform')\n\n # source >> destination\n modifier = OpenMaya.MDGModifier()\n modifier.connect(find_plug(src, 'translateX'), find_plug(dst, 'translateY'))\n modifier.doIt()\n\n # Connected sources\n assert list(mayawalk.connected(src, sources=False, destinations=True)) == [dst]\n assert list(mayawalk.connected(dst, sources=True, destinations=False)) == [src]\n\n\ndef test_connections_visite_once():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n plug_loop = find_plug(node_src, 'translateZ')\n\n # source >> destination >> source\n modifier = OpenMaya.MDGModifier()\n modifier.connect(plug_src, plug_dst)\n modifier.connect(plug_dst, plug_loop)\n modifier.doIt()\n\n assert list(mayawalk.connections(node_src)) == [node_src, node_dst]\n\n# TODO write more tests for mayawalk.connections\n\n\ndef test_plug_children_ignore_placeholder_plug():\n node = create_node('transform')\n plug = find_plug(node, 'instObjGroups')\n\n # instObjGroups has a '[-1]' index, which is at the same time an array and a\n # compound. Maya crash When we try to query the compound child.\n # The goal of this test is to make sure mayawalk.plug_children return the array\n # children and not the compounds.\n assert list(mayawalk.plug_children(plug)) == []\n\n\ndef test_plug_children_array():\n node_src = create_node('transform')\n modifier = OpenMaya.MDGModifier()\n\n # Add an array of int.\n mattribute = OpenMaya.MFnNumericAttribute()\n attr_obj = mattribute.create('array', 'array', OpenMaya.MFnNumericData.kShort)\n mattribute.array = True\n modifier.addAttribute(node_src, attr_obj).doIt()\n array = find_plug(node_src, 'array')\n\n # Connect array plugs so they \"exists\".\n # array[0] >> array[3]\n index_1 = array.elementByLogicalIndex(1)\n index_3 = array.elementByLogicalIndex(3)\n modifier.connect(index_1, index_3).doIt()\n\n assert list(mayawalk.plug_children(array)) == [index_1, index_3]\n\n\ndef test_plug_has_source():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n OpenMaya.MDGModifier().connect(plug_src, plug_dst).doIt()\n assert mayawalk.plug_has_source(plug_dst)\n\n\ndef test_plug_has_source_nested():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n OpenMaya.MDGModifier().connect(plug_src, plug_dst).doIt()\n assert mayawalk.plug_has_source(find_plug(node_dst, 'translate'), nested=True)\n\n\ndef test_plug_has_destinations():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n OpenMaya.MDGModifier().connect(plug_src, plug_dst).doIt()\n assert mayawalk.plug_has_destinations(plug_src)\n\n\ndef test_plug_has_destinations_nested():\n node_src = create_node('transform')\n node_dst = create_node('transform')\n plug_src = find_plug(node_src, 'translateX')\n plug_dst = find_plug(node_dst, 'translateY')\n OpenMaya.MDGModifier().connect(plug_src, plug_dst).doIt()\n assert mayawalk.plug_has_destinations(find_plug(node_src, 'translate'), nested=True)\n","sub_path":"test_mayawalk.py","file_name":"test_mayawalk.py","file_ext":"py","file_size_in_byte":11360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"83954224","text":"# coding: utf-8\n\n\nclass Project(object):\n def __init__(self):\n # Project\n self.project_name = \"\"\n self.project_is_clear = False\n\n # Tasks\n self.task_id = 0\n self.task = {\n \"name\": \"\",\n \"weight\": 1,\n \"comment\": \"\",\n \"tags\": [],\n \"is_clear\": False,\n }\n self.tasks = {}\n\n def add_task(self, name=\"\", weight=1, comment=\"\", is_clear=False):\n # If task field is null\n if name == \"\":\n name = \"temp_{}\".format(len(self.tasks))\n\n # Add\n task = self.task.copy()\n task[\"name\"] = name\n task[\"weight\"] = weight\n task[\"comment\"] = comment\n task[\"is_clear\"] = is_clear\n self.tasks[self.task_id] = task\n self.task_id += 1\n\n def delete_task(self, task_id: int):\n self.tasks.pop(task_id)\n\n def update_task(self, task_id, name, weight, comment, is_clear):\n self.tasks[task_id][\"name\"] = name\n self.tasks[task_id][\"weight\"] = weight\n self.tasks[task_id][\"comment\"] = comment\n self.tasks[task_id][\"is_clear\"] = False\n\n\n\n\n\n\n\n\n\n\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"209756837","text":"# -*- coding: utf-8 -*-\n\n##############################################################################\n# TTYLight-Python: easily stylize terminal text\n##############################################################################\n#\n# Author: Travis Cardwell \n# Copyright: Copyright (c) 2013, Yuzu Technology, Inc.\n#\n# This file is subject to the terms and conditions defined in the License\n# file included with this source code.\n#\n##############################################################################\n\n\"\"\"\\\nttylight Command-Line Utility\n=============================\n\nThe ``ttylight`` command-line utility highlights string or regular expression\ntargets in streams of text.\n\nSee the :doc:`README <../README>` or run ``ttylight --help`` for usage\ninformation.\n\nAPI\n---\n\"\"\"\n\n\nimport argparse\nimport re\nimport sys\n\nimport ttylight\n\n\nCOLORS = [\n ('black', ttylight.Color.BLACK),\n ('red', ttylight.Color.RED),\n ('green', ttylight.Color.GREEN),\n ('yellow', ttylight.Color.YELLOW),\n ('blue', ttylight.Color.BLUE),\n ('magenta', ttylight.Color.MAGENTA),\n ('cyan', ttylight.Color.CYAN),\n ('white', ttylight.Color.WHITE),\n ('default', ttylight.Color.DEFAULT),\n]\n\n\nINTENSITIES = [\n ('normal', ttylight.Intensity.NORMAL),\n ('bold', ttylight.Intensity.BOLD),\n ('faint', ttylight.Intensity.FAINT),\n]\n\n\ndef color(arg):\n \"\"\"Parse color arguments\n\n Colors are specified using case-insensitive prefixes of the following\n strings:\n\n * 'black'\n * 'blue'\n * 'cyan'\n * 'default'\n * 'green'\n * 'magenta'\n * 'red'\n * 'white'\n * 'yellow'\n\n :param str arg: string argument from the command-line\n :returns: ttylight.Color constant\n :rtype: int\n \"\"\"\n arg_lc = arg.lower()\n for name, const in COLORS:\n if name.startswith(arg_lc):\n return const\n raise argparse.ArgumentTypeError(\"invalid color: {:s}\".format(arg))\n\n\ndef intensity(arg):\n \"\"\"Parse intensity arguments\n\n Intensities are specified using case-insensitive prefixes of the following\n strings:\n\n * 'bold'\n * 'faint'\n * 'normal'\n\n :param str arg: string argument from the command-line\n :returns: ttylight.Intensity constant\n :rtype: int\n \"\"\"\n arg_lc = arg.lower()\n for name, const in INTENSITIES:\n if name.startswith(arg_lc):\n return const\n raise argparse.ArgumentTypeError(\"invalid intensity: {:s}\".format(arg))\n\n\ndef target(arg):\n \"\"\"Parse target arguments\n\n Targets are either regular expressions (in ``s/.../`` format) or strings.\n\n :param str arg: string argument from the command line\n :returns: regular expression string for the target\n :rtype: str\n \"\"\"\n if arg.startswith('s/') and arg.endswith('/'):\n arg = arg[2:-1]\n else:\n arg = re.escape(arg)\n return arg\n\n\ndef print_chart():\n \"\"\"Print the style chart to STDOUT\n\n This function displays a chart of all possible combinations of foreground\n colors, background colors, and intensities in a chart.\n \"\"\"\n colors = [(color.upper().center(9), c) for color, c in COLORS]\n print(\"TTYLight-Python Chart\")\n for intensity, i in INTENSITIES:\n print('\\n[{:s}]'.format(intensity.upper()))\n for fgstr, fg in colors:\n line = ''\n for _bgstr, bg in colors:\n line += ttylight.stylize(fgstr, fg, bg, i)\n print(line)\n\n\ndef pipe():\n \"\"\"Pipe all lines from STDIN to STDOUT\n\n This function is used when no targets are given.\n \"\"\"\n for line in sys.stdin:\n sys.stdout.write(line)\n\n\ndef highlight(regex, fg, bg, intensity):\n \"\"\"Print highlighted lines from STDIN to STDOUT\n\n This function loops through the lines of ``STDIN``, highlights any targets\n that are in the line, and writes the result to ``STDOUT``.\n\n :param regex regex: compiled regular expression of what to highlight\n :param int fg: foreground color (ttylight.Color constant)\n :param int bg: background color (ttylight.Color constant)\n :param int intensity: intensity (ttylight.Intensity constant)\n \"\"\"\n for line in sys.stdin:\n even = True\n for part in regex.split(line):\n if even:\n sys.stdout.write(part)\n else:\n sys.stdout.write(ttylight.stylize(part, fg, bg, intensity))\n even = not even\n\n\ndef epilog():\n \"\"\"Calculate the --help epilog text\n\n This function renders the lists of colors and intensities for display in\n the help text.\n\n :returns: --help epilog text\n :rtype: str\n \"\"\"\n fst = lambda x: x[0]\n return (\"Colors: {\" + ', '.join(map(fst, COLORS)) +\n \"} Intensities: {\" + ', '.join(map(fst, INTENSITIES)) + \"}\")\n\n\ndef main(clargs=None):\n \"\"\"Parse command-line arguments and dispatch\n\n :param [str] clargs: list of command-line arguments (default: sys.argv)\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"ttylight Command-Line Utility\",\n epilog=epilog())\n parser.add_argument('-v', '--version', action='store_true',\n help=\"show version number and exit\")\n parser.add_argument('-c', '--chart', action='store_true',\n help=\"show color chart and exit\")\n parser.add_argument('-f', '--foreground', metavar='COLOR',\n type=color, default=ttylight.Color.YELLOW,\n help=\"foreground color (default: yellow)\")\n parser.add_argument('-b', '--background', metavar='COLOR',\n type=color, default=ttylight.Color.RED,\n help=\"background color (default: red)\")\n parser.add_argument('-i', '--intensity', metavar='INTENSITY',\n type=intensity, default=ttylight.Intensity.BOLD,\n help=\"intensity (default: bold)\")\n parser.add_argument('targets', metavar='TARGET', nargs='*',\n type=target,\n help=\"str|s/regex/\")\n args = parser.parse_args(clargs)\n if args.version:\n print('TTYLight-Python {:s}'.format(ttylight.__version__))\n elif args.chart:\n print_chart()\n else:\n try:\n if len(args.targets) < 1:\n pipe()\n else:\n highlight(re.compile('(' + '|'.join(args.targets) + ')'),\n args.foreground, args.background, args.intensity)\n except KeyboardInterrupt: # pragma: no cover\n pass\n\n\nif __name__ == '__main__': # pragma: no cover\n main()\n","sub_path":"ttylight/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"183587013","text":"import time\nfrom itertools import chain, combinations\nfrom collections import Counter\n\nimport numpy as np\n\ndef get_data(n, k, b):\n \"\"\"returns n random sets of length k\n with elements from 0..b-1\n \"\"\"\n\n for _ in range(n):\n yield set(np.random.randint(0, b, size=k))\n\n\ndef powerset(s):\n s = list(s)\n return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))\n\n\ndef smallest_unique_set(S, subset=None):\n \"\"\"Greedy version\"\"\"\n\n if subset is None:\n subset = set(chain.from_iterable(S))\n else:\n # filter elements\n S = [Si & subset for Si in S]\n p = []\n while S:\n c = Counter(chain.from_iterable(S))\n c = Counter({k: v for k, v in c.items() if k in subset})\n if subset - set(c):\n r = next(iter(subset - set(c)))\n p.append(r)\n break \n else:\n r, freq = c.most_common()[-1]\n if freq >= len(S):\n raise ValueError(\"No unique set exists\")\n p.append(r)\n S = [si for si in S if r in si]\n print(\"Remaining elements:\", len(S))\n return p\n\n\ndef smallest_unique_set_naive(S, subset=None):\n \"\"\"Naive version\"\"\"\n\n if subset is None:\n subset = set(chain.from_iterable(S))\n else:\n # filter elements\n S = [Si & subset for Si in S]\n p = []\n while S:\n c = subset & set(chain.from_iterable(S))\n if subset - c:\n r = next(iter(subset - c))\n p.append(r)\n break \n else:\n c = iter(c)\n while True:\n try:\n r = next(c)\n except StopIteration:\n raise ValueError(\"No unique set exists\")\n if r not in p:\n p.append(r)\n break\n S = [si for si in S if r in si]\n print(\"Remaining elements:\", len(S))\n return p\n\n\n\ndef smallest_unique_set_exhaustive(S, subset=None):\n \"\"\"Exhaustive version\"\"\"\n\n if subset is None:\n subset = set(chain.from_iterable(S))\n for si in S:\n if not subset - set(si):\n raise ValueError(\"No unique set exists\")\n\n for s in powerset(subset):\n s = set(s)\n for si in S:\n if not s - si:\n break\n else:\n return s\n\n\ndef main():\n #S = [[1, 2], [1, 2, 3], [1, 3], [2, 3], [3, 4]]\n n = 100000 # number of documents\n k = 500 # document length\n b = 10000 # words in dict\n S = [si for si in get_data(n, k, b)]\n S, subset = S[:-1], S[-1]\n #print(subset)\n #subset = set(range(b))\n t0 = time.time()\n naive = smallest_unique_set_naive(S, subset)\n t1 = time.time()\n print(\"Naive:\", naive)\n print(\"Naive len:\", len(naive))\n print(\"Naive time: {0:.3f}\".format(t1 - t0))\n t0 = time.time()\n naive = smallest_unique_set(S, subset)\n t1 = time.time()\n print(\"Greedy:\", naive)\n print(\"Greedy len:\", len(naive))\n print(\"Greedy time: {0:.3f}\".format(t1 - t0))\n '''\n t0 = time.time()\n exhaustive = smallest_unique_set_exhaustive(S)\n t1 = time.time()\n print(\"Exhaustive:\", exhaustive)\n print(\"Exhaustive len:\", len(exhaustive))\n print(\"Exhaustive time: {0:.3f}\".format(t1 - t0))\n '''\n\n\nif __name__ == '__main__':\n main()\n\n #for elem in get_data(100, 5, 7):\n # print(elem)","sub_path":"garageofcode/nphard/smallest_unique_set.py","file_name":"smallest_unique_set.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"155997912","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport re\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\n\ndef load_roc( fn ):\n x_fa = np.array( [] )\n y_pd = np.array( [] )\n with open(fn) as f:\n while (1):\n raw_line = f.readline()\n if not raw_line:\n break\n fields = raw_line.split()\n x_fa = np.append( x_fa, float( fields[47] ))\n y_pd = np.append( y_pd, float( fields[7] ))\n return (x_fa, y_pd)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser( description = 'Generate ROC plots from *.roc files.' )\n parser.add_argument( '-rangey', metavar='rangey', nargs='?', default='0:1',\n help='ymin:ymax (quote w/ spc for negative, i.e. \" -0.1:5\")' )\n parser.add_argument( '-rangex', metavar='rangex', nargs='?',\n help='xmin:xmax (quote w/ spc for negative, i.e. \" -0.1:5\")' )\n parser.add_argument( '-autoscale', action='store_true',\n help='Ignore -rangex -rangey and autoscale both axes of the plot.' )\n parser.add_argument( '-logx', action='store_true',\n help='Use logscale for x' )\n parser.add_argument( '-xlabel', nargs='?', default='Detection FA count', help='title for x axis' )\n parser.add_argument( '-ylabel', nargs='?', default='Detection PD', help='title for y axis' )\n parser.add_argument( '-title', nargs='?', help='title for plot' )\n parser.add_argument( '-lw', nargs='?', type=float, default=3, help='line width' )\n parser.add_argument( '-key', nargs='?', help='comma-separated set of strings labeling each line in order read', default=None )\n parser.add_argument( '-keyloc', nargs='?', help='Key location (\"upper left\", \"lower right\", etc; help for list)', default='best' )\n parser.add_argument( '-nokey', action='store_true', help='Set to suppress plot legend' )\n parser.add_argument( '-writeimage', default=None, help='Provide a filename of the image to write instead of displaying a window.' )\n parser.add_argument( 'rocfiles', metavar='ROC', nargs=argparse.REMAINDER,\n help='A score_events .roc file (from --roc-dump argument)' )\n args = parser.parse_args()\n\n\n fig = plt.figure()\n xscale_arg = 'log' if args.logx else 'linear'\n rocplot = plt.subplot(1, 1, 1, xscale=xscale_arg)\n rocplot.set_title( args.title ) if args.title else None\n plt.xlabel( args.xlabel )\n plt.ylabel( args.ylabel )\n plt.xticks()\n plt.yticks()\n\n user_titles = args.key.split(',') if args.key else None\n i = 0\n for fn in args.rocfiles:\n (x,y) = load_roc( fn )\n t = user_titles[i] if user_titles and i < len(user_titles) else fn\n sys.stderr.write(\"Info: %d: loading %s as '%s'...\\n\" % (i, fn, t) )\n rocplot.plot( x, y, linewidth=args.lw, label=t )\n i += 1\n\n\n if args.autoscale:\n rocplot.autoscale()\n else:\n tmp = args.rangey.split(':')\n if len(tmp) != 2:\n sys.stderr.write('Error: rangey option must be two floats separated by a colon, e.g. 0.2:0.7\\n');\n sys.exit(1)\n (ymin, ymax) = (float(tmp[0]), float(tmp[1]))\n rocplot.set_ylim(ymin,ymax)\n\n if args.rangex:\n tmp = args.rangex.split(':')\n if len(tmp) != 2:\n sys.stderr.write('Error: rangex option must be two floats separated by a colon, e.g. 0.2:0.7\\n');\n sys.exit(1)\n (xmin, xmax) = (float(tmp[0]), float(tmp[1]))\n rocplot.set_xlim(xmin,xmax)\n\n if not args.nokey:\n plt.legend( loc=args.keyloc )\n\n if args.writeimage:\n plt.savefig(args.writeimage)\n else:\n plt.show()\n\n","sub_path":"examples/scoring_and_roc_generation/plotroc.py","file_name":"plotroc.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"391866757","text":"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Efficient ImageNet input pipeline using tf.data.Dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nimport tensorflow as tf\n\nimport resnet_preprocessing\n\nMEAN_RGB = [0.485, 0.456, 0.406]\n\nclass Combine_RDC_ImageNet_Input(object):\n \"\"\"Generates PBRNet and Scenenet data input_pbrscenent for training or evaluation.\n\n The training data is assumed to be in TFRecord format with keys as specified\n in the dataset_parser below, sharded across 366 files, named sequentially:\n train-0\n train-1\n ...\n train-365\n\n The validation data is in the same format but sharded in 50 files.\n\n Args:\n is_training: `bool` for whether the input is for training\n data_dir: `str` for the directory of the training and validation data\n num_cores: `int` for the number of TPU cores\n \"\"\"\n\n def __init__(self, is_training, pbr_dir, scene_dir, imn_dir, num_cores=8, ab_depth=False, down_sample=1, color_dp_tl=True, rp_dp_tl=False, combine_3_task=True):\n # self.image_preprocessing_fn = resnet_preprocessing.full_imagenet_augment\n self.image_preprocessing_fn = resnet_preprocessing.depth_image_preprocess_image\n self.depth_preprocessing_fn = resnet_preprocessing.depth_preprocess_image\n self.rp_preprocessing_fn = resnet_preprocessing.rp_preprocess_image\n self.color_preprocessing_fn = resnet_preprocessing.col_preprocess_image\n self.rp_col_preprocessing_fn = resnet_preprocessing.rp_col_preprocess_image\n\n self.is_training = is_training\n self.pbr_dir = pbr_dir\n self.scene_dir = scene_dir\n self.imn_dir = imn_dir\n self.num_cores = num_cores\n self.pbr_training_data_num = 366\n self.scene_training_data_num = 843\n self.random_seed = 3\n self.ab_depth = ab_depth\n self.down_sample = down_sample\n self.color_dp_tl = color_dp_tl\n self.rp_dp_tl = rp_dp_tl\n self.combine_3_task = combine_3_task\n\n def dataset_parser_pbr_mlt(self, value):\n \"\"\"Parse an ImageNet record from a serialized string Tensor.\"\"\"\n keys_to_features = {\n 'mlt': tf.FixedLenFeature((), tf.string, '')\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n original_image = tf.reshape(parsed['mlt'], shape=[])\n original_image = tf.image.decode_png(original_image, channels=3)\n original_image = tf.image.convert_image_dtype(original_image, dtype=tf.float32)\n original_image.set_shape((480, 640, 3))\n if self.rp_dp_tl:\n offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])\n original_image -= offset\n return original_image\n\n def dataset_parser_pbr_depth(self, value):\n \"\"\"Parse an ImageNet record from a serialized string Tensor.\"\"\"\n keys_to_features = {\n 'depth': tf.FixedLenFeature((), tf.string, '')\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n depth_image = tf.reshape(parsed['depth'], shape=[])\n depth_image = tf.image.decode_png(depth_image, dtype=tf.uint16)\n depth_image.set_shape((480, 640, 1))\n depth_image = tf.cast(depth_image, tf.int32)\n return depth_image\n\n def dataset_parser_scene_photo(self, value):\n \"\"\"Parse an ImageNet record from a serialized string Tensor.\"\"\"\n keys_to_features = {\n 'photo': tf.FixedLenFeature((), tf.string, '')\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n original_image = tf.reshape(parsed['photo'], shape=[])\n original_image = tf.image.decode_png(original_image, channels=3)\n original_image = tf.image.convert_image_dtype(original_image, dtype=tf.float32)\n original_image.set_shape((240, 320, 3))\n if self.rp_dp_tl:\n offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])\n original_image -= offset\n return original_image\n\n def dataset_parser_scene_depth(self, value):\n \"\"\"Parse an ImageNet record from a serialized string Tensor.\"\"\"\n keys_to_features = {\n 'depth': tf.FixedLenFeature((), tf.string, '')\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n depth_image = tf.reshape(parsed['depth'], shape=[])\n depth_image = tf.image.decode_png(depth_image, dtype=tf.uint16)\n depth_image.set_shape((240, 320, 1))\n depth_image = tf.cast(depth_image, tf.int32)\n return depth_image\n def dataset_parser_rp(self, value):\n \"\"\"Parse an ImageNet record from a serialized string Tensor.\"\"\"\n keys_to_features = {\n 'images': tf.FixedLenFeature((), tf.string, ''),\n 'labels': tf.FixedLenFeature([], tf.int64, -1)\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n image = tf.reshape(parsed['images'], shape=[])\n image = tf.image.decode_jpeg(image, channels=3)\n \n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n \n image = self.rp_col_preprocessing_fn(\n image=image,\n is_training=self.is_training,\n down_sample=8,\n )\n #print(\"g_noise:\", self.g_noise)\n image = self.rp_preprocessing_fn(\n image=image,\n is_training=self.is_training,\n num_grids=1,\n g_noise=0,\n std=False,\n sub_mean=False,\n )\n\n label = tf.cast(tf.reshape(parsed['labels'], shape=[]), dtype=tf.int32)\n\n return image, label\n\n def dataset_parser_col(self, value):\n keys_to_features = {\n 'images': tf.FixedLenFeature((), tf.string, ''),\n 'labels': tf.FixedLenFeature([], tf.int64, -1)\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n print(\"parsed example\", parsed)\n\n image = tf.reshape(parsed['images'], shape=[])\n image = tf.image.decode_jpeg(image, channels=3)\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n print(\"image shape:\", image)\n l_image, Q_label = self.color_preprocessing_fn(\n image=image,\n is_training=self.is_training,\n down_sample=8,\n col_knn=True,\n combine_rp=True,\n ) \n\n print(\"data_provider output: image:\", l_image)\n print(\"label:\", Q_label)\n\n\n return l_image, Q_label\n\n\n def dataset_parser_together(self, value):\n print(\"together input:\", value) \n pbr_image, pbr_depth = self.image_preprocessing_fn(\n original_image = value['pbr_mlt'],\n depth_image = value['pbr_depth'],\n is_training = self.is_training,\n image_height=480,\n image_width=640,\n color_dp_tl=self.color_dp_tl,\n combine_3_task=self.combine_3_task,\n )\n scene_image, scene_depth = self.image_preprocessing_fn(\n original_image = value['scene_photo'],\n depth_image = value['scene_depth'],\n is_training = self.is_training,\n image_height=240,\n image_width=320,\n color_dp_tl=self.color_dp_tl,\n combine_3_task=self.combine_3_task,\n ) \n pbr_depth = self.depth_preprocessing_fn(\n image=pbr_depth,\n ab_depth=self.ab_depth,\n ) \n scene_depth = self.depth_preprocessing_fn(\n image=scene_depth,\n ab_depth=self.ab_depth,\n ) \n\n color_image, color_label = value['col_file']\n rp_image, _ = value['rp_file']\n\n return pbr_image, pbr_depth, scene_image, scene_depth, rp_image, color_image, color_label\n\n\n def input_fn(self, params):\n\n batch_size = params['batch_size']\n\n if self.is_training:\n pbr_mlt_file_pattern = os.path.join(self.pbr_dir, 'tfrecords', 'mlt', 'pbrnet_*')\n pbr_depth_file_pattern = os.path.join(self.pbr_dir, 'tfrecords', 'depth', 'pbrnet_*')\n scene_photo_file_pattern = os.path.join(self.scene_dir, 'scenenet_new', 'photo', 'data_*')\n scene_depth_file_pattern = os.path.join(self.scene_dir, 'scenenet_new', 'depth', 'data_*')\n rp_file_pattern = os.path.join(self.imn_dir, 'train-*')\n else:\n pbr_mlt_file_pattern = os.path.join(self.pbr_dir, 'tfrecords_val', 'mlt', 'pbrnet_*') \n pbr_depth_file_pattern = os.path.join(self.pbr_dir, 'tfrecords_val', 'depth', 'pbrnet_*')\n scene_photo_file_pattern = os.path.join(self.scene_dir, 'scenenet_new_val', 'photo', 'data_*')\n scene_depth_file_pattern = os.path.join(self.scene_dir, 'scenenet_new_val', 'depth', 'data_*')\n rp_file_pattern = os.path.join(self.imn_dir, 'validation-*') \n\n pbr_mlt_list = self.get_tfr_filenames(pbr_mlt_file_pattern) \n pbr_mlt_files = tf.data.Dataset.list_files(pbr_mlt_list)\n\n pbr_depth_list = self.get_tfr_filenames(pbr_depth_file_pattern)\n pbr_depth_files = tf.data.Dataset.list_files(pbr_depth_list)\n\n scene_photo_list = self.get_tfr_filenames(scene_photo_file_pattern)\n scene_photo_files = tf.data.Dataset.list_files(scene_photo_list) \n\n scene_depth_list = self.get_tfr_filenames(scene_depth_file_pattern)\n scene_depth_files = tf.data.Dataset.list_files(scene_depth_list)\n\n rp_files = tf.data.Dataset.list_files(rp_file_pattern)\n\n if self.is_training:\n pbr_mlt_files = pbr_mlt_files.repeat()\n pbr_depth_files = pbr_depth_files.repeat()\n scene_photo_files = scene_photo_files.repeat()\n scene_depth_files = scene_depth_files.repeat()\n rp_files = rp_files.shuffle(buffer_size=1024).repeat()\n else:\n pbr_mlt_files = pbr_mlt_files.repeat()\n pbr_depth_files = pbr_depth_files.repeat()\n scene_photo_files = scene_photo_files.repeat()\n scene_depth_files = scene_depth_files.repeat()\n rp_files = rp_files.repeat()\n\n files_dict = {'pbr_mlt': pbr_mlt_files, 'pbr_depth': pbr_depth_files, 'scene_photo': scene_photo_files, 'scene_depth': scene_depth_files, 'rp_file': rp_files}\n\n def fetch_dataset(filename):\n buffer_size = 8 * 1024 * 1024 # 1024 MiB per file\n dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)\n return dataset\n \n dataset_dict = {\n source: curr_dataset.apply(\n tf.contrib.data.parallel_interleave(\n fetch_dataset, cycle_length=self.num_cores, sloppy=False)) \\\n for source, curr_dataset in files_dict.items()\n }\n\n dataset_parser_dict = {}\n dataset_parser_dict['pbr_mlt'] = dataset_dict['pbr_mlt'].map(\n self.dataset_parser_pbr_mlt,\n num_parallel_calls=64)\n dataset_parser_dict['pbr_depth'] = dataset_dict['pbr_depth'].map(\n self.dataset_parser_pbr_depth,\n num_parallel_calls=64)\n dataset_parser_dict['scene_photo'] = dataset_dict['scene_photo'].map(\n self.dataset_parser_scene_photo,\n num_parallel_calls=64)\n dataset_parser_dict['scene_depth'] = dataset_dict['scene_depth'].map(\n self.dataset_parser_scene_depth,\n num_parallel_calls=64)\n dataset_parser_dict['rp_file'] = dataset_dict['rp_file'].map(\n self.dataset_parser_rp,\n num_parallel_calls=64)\n dataset_parser_dict['col_file'] = dataset_dict['rp_file'].shuffle(buffer_size=1024, seed=5).map(\n self.dataset_parser_col,\n num_parallel_calls=64)\n \n zip_dataset = tf.data.Dataset.zip(dataset_parser_dict)\n zip_dataset = zip_dataset.repeat()\n \n zip_dataset = zip_dataset.map(\n self.dataset_parser_together,\n num_parallel_calls=64)\n \n zip_dataset = zip_dataset.shuffle(buffer_size=1200, seed=4)\n\n zip_dataset = zip_dataset.apply(\n tf.contrib.data.batch_and_drop_remainder(batch_size))\n\n zip_dataset = zip_dataset.prefetch(2) # Prefetch overlaps in-feed with training\n\n pbr_image, pbr_depth, scene_image, scene_depth, rp_image, color_image, color_label = zip_dataset.make_one_shot_iterator().get_next()\n\n original_images = tf.concat([pbr_image, scene_image], 0)\n depth_images = tf.concat([pbr_depth, scene_depth], 0)\n\n tmp_concat = tf.concat([original_images, depth_images], 3)\n\n tmp_concat = tf.random_shuffle(tmp_concat, seed=5)\n\n original_image = tmp_concat[:,:,:,:3]\n depth_image = tmp_concat[:,:,:,3:]\n\n print(\"depth image:\", original_image)\n print(\"depth label:\", depth_image)\n print(\"rp image:\", rp_image)\n print(\"color image:\", color_image)\n print(\"color label:\", color_label)\n \n all_images = {}\n all_images['depth_image'] = original_image[:batch_size, :, :, :]\n all_images['depth_label'] = depth_image[:batch_size, :, :, :]\n all_images['rp_image'] = tf.reshape(rp_image, [batch_size, 4, 96, 96, 3])\n all_images['color_image'] = tf.reshape(color_image, [batch_size, 256, 256, 3])\n all_images['color_label'] = tf.reshape(color_label, [batch_size, 32, 32, 313])\n labels = tf.constant([[0], [1], [2], [3], [4], [5], [6], [7]])\n\n return all_images, labels\n\n def get_tfr_filenames(self, file_pattern='*.tfrecords'):\n datasource = tf.gfile.Glob(file_pattern)\n datasource.sort()\n\n return datasource \n","sub_path":"unsup_vvs/network_training/tpu_old_dps/combine_rdc_imn_input.py","file_name":"combine_rdc_imn_input.py","file_ext":"py","file_size_in_byte":14605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"347123580","text":"'''\nCreated on Nov 6, 2014\n\n@author: zoya\n'''\nimport os\n\nprint(os.path.abspath(\"yyy\"))\ndef EBIN(input_file, output_file):\n with open(input_file) as resource_file:\n values = resource_file.readlines()\n N = int(values[0])\n m = [float(x) for x in values[1].split(\" \")]\n print(N)\n print(m)\n result=[round(N*y, 3) for y in m]\n print (\" \".join(str(x) for x in result))\n \nEBIN(\"data/rosalind_ebin.txt\", \"src/data/rosalind_ebin_result.txt\")","sub_path":"src/com/zobar/rosalind/EBIN.py","file_name":"EBIN.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"133535866","text":"import argparse\nimport io\nimport json\nimport requests\nimport sys\nimport urllib\nimport os\n\nimport re\nimport numpy as np\nimport tensorflow as tf\n\nfrom PIL import Image\n\ndef main(args):\n model = tf.keras.models.load_model(args.model_path)\n\n title_vocab_path = os.path.join(args.resources_dir, \"title_vocab.json\")\n with open(title_vocab_path) as f:\n title_vocab = json.load(f)\n desc_vocab_path = os.path.join(args.resources_dir, \"desc_vocab.json\")\n with open(desc_vocab_path) as f:\n desc_vocab = json.load(f)\n\n if model.layers[0].name != 'image':\n model.layers[0]._name = 'image'\n\n # model.summary()\n\n inputs = get_inputs(args.product_id, title_vocab, desc_vocab)\n dataset = tf.data.Dataset.from_tensor_slices(inputs)\n dataset = dataset.batch(1)\n\n preds = model.predict(dataset)\n print(preds, type(preds))\n\ndef get_inputs(product_id, title_vocab, desc_vocab):\n endpoint = 'https://tome.tokopedia.com/v2.1/product/'\n inputs = {}\n try:\n resp = json.loads(urllib.request.urlopen(endpoint + str(product_id)).read().decode())\n inputs['token_title'] = preprocess_title(resp['data']['product_name'], title_vocab, 15) # need to preprocess title first; dummy example: np.expand_dims(np.zeros(15), axis=0)\n inputs['token_desc'] = preprocess_desc(resp['data']['product_description'], desc_vocab, 200) # need to preprocess description first; dummy example: np.expand_dims(np.zeros(200), axis=0)\n inputs['image'] = np.array([get_image_data(resp['data']['product_picture'][0]['url_original'])])\n inputs['price'] = np.array(get_price_feature(resp['data']['product_price']))\n except:\n inputs['token_title'] = None\n inputs['token_desc'] = None\n inputs['image'] = None\n inputs['price'] = None\n \n return inputs\n\ndef get_price_feature(price):\n return [1] if price >= 4000 and price <= 4100000 else [0]\n\ndef get_image_data(image_url):\n try:\n image_data = requests.get(image_url).content\n except:\n # get default image\n image = Image.new('RGB', (224, 224))\n image_byte = io.BytesIO()\n image.save(image_byte, format='jpeg')\n image_data = image_byte.getvalue()\n\n image_data = tf.io.decode_jpeg(image_data, channels=3)\n image_data = tf.image.convert_image_dtype(image_data, tf.float32)\n image_data = tf.image.resize(image_data, [224, 224])\n \n return image_data\n\ndef tokenize(string, vocab, max_length):\n string = string.split()\n tokens = []\n for i in string:\n try :\n tokens.append(vocab[i])\n except :\n tokens.append(len(vocab)+1)\n if len(tokens) > max_length:\n tokens = tokens[:max_length]\n elif len(tokens) < max_length:\n while len(tokens) < max_length:\n tokens.append(0)\n return np.array([tokens])\n\ndef parse_desc(product) :\n product = str(product)\n product = re.sub(\"_x000D_\", \" \", product)\n result_re = re.sub(\"[^A-Za-z0-9']+\", \" \", product)\n result_lower = result_re.lower()\n return result_lower\n\ndef preprocess_desc(product, vocab_list, max_length):\n product = parse_desc(product)\n product = tokenize(product, vocab_list, max_length)\n return product\n\ndef parse_title(product) :\n result_re = re.sub(\"[^A-Za-z0-9']+\", ' ', product)\n result_lower = result_re.lower()\n return result_lower\n\ndef preprocess_title(product, vocab_list, max_length):\n product = parse_title(product)\n product = tokenize(product, vocab_list, max_length)\n return product\n \ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--model_path', type=str, \n help='Path a directory containing the SavedModel')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=224)\n parser.add_argument('--product_id', type=int,\n help='Product id.', default=777472946)\n parser.add_argument('--resources_dir', type=str,\n help='Path a directory containing title and description vocabs')\n \n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))","sub_path":"model_image_text_dian/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"123591966","text":"import os\nfrom astropy.io import fits\nimport numpy as np\nimport matplotlib.pyplot as plt\n \npath = \"/home/pavan/Thesis/pattern_speed/Set 2/xQp55A-i30-10Rd/\"\n\n#making list of all surface density images\nden_list = [file for file in os.listdir(path) if file.endswith('.den.DB.i30.fits')]\nden_list = sorted(den_list)\n\n#making list of all radial velocity images\nvel_list = [file for file in os.listdir(path) if file.endswith('.vel.DB.i30.fits')]\nvel_list = sorted(vel_list)\n\n#number of image snapshots\nnum_files = len(den_list)\n\nif not os.path.exists(\"profile_dat\"):\n\tos.mkdir(\"profile_dat\")\n\nfor index in range(num_files):\n\tden_path = os.path.join(path, den_list[index])\n\tvel_path = os.path.join(path, vel_list[index])\n\n\twith fits.open(den_path) as den_hdul:\n\t\tden_data = den_hdul[0].data\n\n\tfilename = den_list[index][:-16] #strips the end .den.DB.i30.fits\n\n\twith fits.open(vel_path) as vel_hdul:\n\t\tvel_data = vel_hdul[0].data\n\t\t\n\t# IN THIS IMAGE, VERTICAL AXIS IS Y AND HORIZONTAL AXIS IS X (NOT ALWAYS TRUE)\n\n\txlen = den_data.shape[1]\n\tylen = den_data.shape[0]\n\n\t# summation of surface density (weighted by x and y)\n\ttot = sum(sum(den_data))\n\txtot = 0.\n\tytot = 0.\n\n\tfor y in range(ylen):\t\n\t\tfor x in range(xlen):\n\t\t\txtot += x*den_data[y,x]\n\t\t\tytot += y*den_data[y,x]\n\n\t# center of surface density\n\tx0 = int(xtot/tot)\n\ty0 = int(ytot/tot)\n\n\t# different slit translations\n\tyst = 50\n\t# negative slope of slit (since Y axis in image is reversed)\n\tm = 0\n\tfor st in range(-yst,yst+1):\n\t\t# choosing (x,y) in a slit passing through (x0,y0)\n\t\tline = []\n\t\tdist = []\t\n\t\tx_line = []\n\n\t\t# half-slit width\n\t\tif abs(st) <= 50:\n\t\t\tL = 50.0\t\t\n\t\tif abs(st) <= 30:\n\t\t\tL = 30.0\n\t\tif abs(st) <= 10:\n\t\t\tL = 10.0\n\n\t\tfor y in range(ylen):\n\t\t\tfor x in range(xlen):\n\t\t\t\tif (y-y0-st) == -m*(x-x0):\n\t\t\t\t\tline.append([x,y])\n\t\t\t\t\tif x!=x0:\n\t\t\t\t\t\tdist.append(np.sqrt((x-x0)**2+(y-y0-st)**2) * (abs(x-x0)/(x-x0)))\n\t\t\t\t\telse:\n\t\t\t\t\t\tdist.append(np.sqrt((x-x0)**2+(y-y0-st)**2))\n\t\t\t\t\tx_line.append(x-x0)\n\n\t\tif not os.path.exists(\"profile_dat/\"+filename):\n\t\t\tos.mkdir(\"profile_dat/\"+filename)\n\t\twith open(\"profile_dat/\"+filename+\"/profile_%d.dat\" %(st),\"w\") as f:\n\t\t\t# velocity and density slit profiles\n\t\t\tvel_line = np.empty(len(line))\n\t\t\tden_line = np.empty(len(line))\n\t\t\tfor i in range(len(line)):\n\t\t\t\tvel_line[i] = vel_data[line[i][1],line[i][0]]\n\t\t\t\tden_line[i] = den_data[line[i][1],line[i][0]]\n\t\t\t\tif vel_line[i] != -9999 and (dist[i] >= -L and dist[i] <= L):\n\t\t\t\t\tf.write(\"%f\\t%f\\t%f\\n\" %(x_line[i],vel_line[i],den_line[i]))\n\n\tprint(\"Line profiles extraction %d/%d iterations\" %(index+1,num_files))\n","sub_path":"Set 2/batch_split/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"215584928","text":"import time\nimport datetime\nimport MySQLdb\nimport discord\n\nTERMINATE = False\n\ndb_pool = {}\ndb_pool_id = 0\n\ndef databaseConnect():\n conn_info = None\n\n conn_id_todelete = []\n\n global db_pool\n global db_pool_id\n\n # Iterate through open connections and find the currently active one.\n for pool_id in db_pool:\n conn_info_iter = db_pool.get(pool_id)\n\n if conn_info_iter['closed'] is True:\n if conn_info_iter['count'] <= 0:\n conn_id_todelete.append(pool_id)\n else:\n conn_info = conn_info_iter\n\n # Close and remove dead connections.\n if len(conn_id_todelete) > 0:\n for pool_id in conn_id_todelete:\n conn_info_iter = db_pool[pool_id]\n conn_info_iter['conn'].close()\n\n del db_pool[pool_id]\n\n # Create a new connection.\n if conn_info is None:\n db_pool_id += 1\n conn_info = {\n 'conn': MySQLdb.connect(host=\"localhost\", user=\"thrash-bot\", passwd=\"thrash\", db=\"thrash\", charset=\"utf8\"),\n 'created': int(time.time()),\n 'count': 1,\n 'closed': False\n }\n db_pool[db_pool_id] = conn_info\n else:\n conn_info['count'] += 1\n\n return conn_info\n\n\ndef databaseClose(conn_info):\n conn_info['count'] -= 1\n\n # Expire old database connections.\n if (conn_info['created'] + 60) < int(time.time()):\n conn_info['closed'] = True\n\ndef logMsg(string):\n print(\"[{}] {}\".format(datetime.datetime.now(), string))\n\n return string\n\nasync def send_message(client, channel, text, image_name = None):\n try:\n return await channel.send(content=text)\n except discord.errors.Forbidden:\n logMsg('Could not message user: {}\\n{}'.format(channel, text))\n raise\n except:\n logMsg('Failed to send message to channel: {}\\n{}'.format(channel, text))\n\ndef formatMessage(user_target, message):\n return \"*{}*: {}\".format(user_target.display_name, message).replace(\"@\", \"\\{at\\}\")\n\n\"\"\" read a file named fname and return its contents as a string \"\"\"\ndef getValueFromFileContents(fname):\n\ttoken = \"\"\n\n\ttry:\n\t\tf_token = open(fname, \"r\")\n\t\tf_token_lines = f_token.readlines()\n\n\t\tfor line in f_token_lines:\n\t\t\tline = line.rstrip()\n\t\t\tif len(line) > 0:\n\t\t\t\ttoken = line\n\texcept IOError:\n\t\ttoken = \"\"\n\t\tprint(\"Could not read {} file.\".format(fname))\n\tfinally:\n\t\tf_token.close()\n\n\treturn token\n\n\"\"\" get the Discord API token from the config file on disk \"\"\"\ndef getToken():\n\treturn getValueFromFileContents(\"token\")","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"109325131","text":"#\n# Copyright(c) 2019 Intel Corporation\n# SPDX-License-Identifier: BSD-3-Clause-Clear\n#\n\nfrom ctypes import (\n c_void_p,\n c_int,\n c_uint32,\n c_uint64,\n CFUNCTYPE,\n Structure,\n POINTER,\n byref,\n cast,\n)\nfrom enum import IntEnum\n\nfrom ..ocf import OcfLib\nfrom .data import Data\nfrom .queue import Queue\n\n\nclass IoDir(IntEnum):\n READ = 0\n WRITE = 1\n\n\nclass IoOps(Structure):\n pass\n\n\nclass Io(Structure):\n START = CFUNCTYPE(None, c_void_p)\n HANDLE = CFUNCTYPE(None, c_void_p, c_void_p)\n END = CFUNCTYPE(None, c_void_p, c_int)\n\n _instances_ = {}\n _fields_ = [\n (\"_volume\", c_void_p),\n (\"_ops\", POINTER(IoOps)),\n (\"_addr\", c_uint64),\n (\"_flags\", c_uint64),\n (\"_bytes\", c_uint32),\n (\"_class\", c_uint32),\n (\"_dir\", c_uint32),\n (\"_io_queue\", c_void_p),\n (\"_start\", START),\n (\"_handle\", HANDLE),\n (\"_end\", END),\n (\"_priv1\", c_void_p),\n (\"_priv2\", c_void_p),\n ]\n\n @classmethod\n def from_pointer(cls, ref):\n c = cls.from_address(ref)\n cls._instances_[ref] = c\n OcfLib.getInstance().ocf_io_set_cmpl_wrapper(\n byref(c), None, None, c.c_end\n )\n return c\n\n @classmethod\n def get_instance(cls, ref):\n return cls._instances_[cast(ref, c_void_p).value]\n\n def del_object(self):\n del type(self)._instances_[cast(byref(self), c_void_p).value]\n\n def put(self):\n OcfLib.getInstance().ocf_io_put(byref(self))\n\n def get(self):\n OcfLib.getInstance().ocf_io_get(byref(self))\n\n @staticmethod\n @END\n def c_end(io, err):\n Io.get_instance(io).end(err)\n\n @staticmethod\n @START\n def c_start(io):\n Io.get_instance(io).start()\n\n @staticmethod\n @HANDLE\n def c_handle(io, opaque):\n Io.get_instance(io).handle(opaque)\n\n def end(self, err):\n try:\n self.callback(err)\n except: # noqa E722\n pass\n\n self.put()\n self.del_object()\n\n def submit(self):\n return OcfLib.getInstance().ocf_core_submit_io_wrapper(byref(self))\n\n def configure(\n self, addr: int, length: int, direction: IoDir, io_class: int, flags: int\n ):\n OcfLib.getInstance().ocf_io_configure_wrapper(\n byref(self), addr, length, direction, io_class, flags\n )\n\n def set_data(self, data: Data, offset: int = 0):\n self.data = data\n OcfLib.getInstance().ocf_io_set_data_wrapper(byref(self), data, offset)\n\n def set_queue(self, queue: Queue):\n OcfLib.getInstance().ocf_io_set_queue_wrapper(byref(self), queue.handle)\n\n\nIoOps.SET_DATA = CFUNCTYPE(c_int, POINTER(Io), c_void_p, c_uint32)\nIoOps.GET_DATA = CFUNCTYPE(c_void_p, POINTER(Io))\n\nIoOps._fields_ = [(\"_set_data\", IoOps.SET_DATA), (\"_get_data\", IoOps.GET_DATA)]\n\nlib = OcfLib.getInstance()\nlib.ocf_core_new_io_wrapper.restype = POINTER(Io)\nlib.ocf_io_set_cmpl_wrapper.argtypes = [POINTER(Io), c_void_p, c_void_p, Io.END]\nlib.ocf_io_configure_wrapper.argtypes = [\n POINTER(Io),\n c_uint64,\n c_uint32,\n c_uint32,\n c_uint32,\n c_uint64,\n]\nlib.ocf_io_set_queue_wrapper.argtypes = [POINTER(Io), c_uint32]\n\nlib.ocf_core_new_io_wrapper.argtypes = [c_void_p]\nlib.ocf_core_new_io_wrapper.restype = c_void_p\n\nlib.ocf_io_set_data_wrapper.argtypes = [POINTER(Io), c_void_p, c_uint32]\nlib.ocf_io_set_data_wrapper.restype = c_int\n\nlib.ocf_io_set_queue_wrapper.argtypes = [POINTER(Io), c_void_p]\n","sub_path":"tests/functional/pyocf/types/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"168275370","text":"import os\nfrom tqdm import tqdm\nimport cv2 \nimport numpy as np\nimport matplotlib.image as mim\nimport matplotlib.pyplot as plt\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import datasets, transforms\nimport torchvision.transforms.functional as TF\nimport torch.optim as optim\nfrom sklearn.model_selection import train_test_split\n\nprint(\"\\n\\n Deep af CAE Gray\")\n\nprint(\"\\n\\nGPU Available : \",torch.cuda.is_available())\n\nprint(\"\\n\\nNumber of GPU's : \", torch.cuda.device_count())\n\nX_train = np.load(\"X_train.npy\")\nX_train = X_train.reshape(X_train.shape[0],X_train.shape[1],X_train.shape[2],1)\nX_val = np.load(\"X_val.npy\")\nX_val = X_val.reshape(X_val.shape[0],X_val.shape[1],X_val.shape[2],1)\nY_train = np.load(\"Y_train.npy\")\nY_val = np.load(\"Y_val.npy\")\nprint(X_train.shape, X_val.shape, Y_train.shape, Y_val.shape)\n\nprint(\"\\n\\nLoaded Data\")\n\nclass CancerData(Dataset):\n def __init__(self, data, label):\n self.X_data = data\n self.Y_data = label\n\n def __len__(self):\n return self.X_data.shape[0]\n\n def transform_image(self, image):\n img_resized_tensor = TF.to_tensor(image)\n normalize_img = (image - 127.5) / 127.5\n return TF.to_tensor(normalize_img).type(torch.FloatTensor)\n\n def __getitem__(self, idx):\n # print(s\\n\\nelf.images[idx].shape)\n img_shape = self.X_data.shape\n img_batch = self.X_data[idx]\n lable_batch = self.Y_data[idx]\n return self.transform_image(img_batch), lable_batch\n\nData_train = CancerData(X_train, Y_train)\nData_val = CancerData(X_val, Y_val)\n\nBATCH_SIZE = 32\nLEARNING_RATE = 1e-4\nWEIGHT_DECAY = 0.0\nEpochs = 200\n\nprint(\"\\n - - HyperParameters : \",BATCH_SIZE,LEARNING_RATE,WEIGHT_DECAY,Epochs)\n\n'''\n#Best Gray\nBATCH_SIZE = 64\nLEARNING_RATE = 1e-5\nWEIGHT_DECAY = 0.0\nEpochs = 120 \n\n'''\n\ndata_loader_train = DataLoader(Data_train, batch_size=BATCH_SIZE, shuffle=True, num_workers=10)\ndata_loader_val = DataLoader(Data_val, batch_size=BATCH_SIZE, shuffle=True, num_workers=10)\nX_batch , Y_batch = next(iter(data_loader_val))\nprint(\"\\n\\nOne Batch : \",type(X_batch), X_batch.shape, X_batch.numpy().max(),X_batch.numpy().min(), Y_batch.shape)\n\nclass Network(nn.Module):\n\n def __init__ (self):\n\n super(Network, self).__init__()\n\n self.e_conv_1 = nn.Sequential(\n nn.ZeroPad2d((1, 2, 1, 2)),\n nn.Conv2d(bias=False,in_channels=1, out_channels=64, kernel_size=(5, 5), stride=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(64) \n )\n\n # 128x32x32\n self.e_conv_2 = nn.Sequential(\n nn.ZeroPad2d((1, 2, 1, 2)),\n nn.Conv2d(bias=False,in_channels=64, out_channels=128, kernel_size=(5, 5), stride=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 128x32x32\n #self.bn_128 = nn.BatchNorm2d(128)\n self.e_block_1 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 128x32x32\n self.e_block_2 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n \n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 128x32x32\n self.e_block_3 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n \n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 32x32x32\n self.e_conv_3 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=128, out_channels=32, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(32), \n )\n\n self.e_conv_4 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=32, out_channels=16, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2)),\n nn.BatchNorm2d(16),\n nn.Tanh()\n )\n # self.encoded_size = 100352\n # self.lin_in = nn.Linear( self.encoded_size , int(self.encoded_size/32) )\n # self.lin_out = nn.Linear( int(self.encoded_size/32) , self.encoded_size )\n\n # Linear\n\n self.encoded_size = 53824\n self.lin_in = nn.Linear( self.encoded_size , int(self.encoded_size/32) )\n self.lin_out = nn.Linear( int(self.encoded_size/32) , self.encoded_size )\n\n\n #Decoder\n\n # 128x64x64\n self.d_up_conv_0 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=16, out_channels=32, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(32), \n \n #nn.ZeroPad2d((1, 1, 1, 1)),\n nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=(2, 2), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(32), \n )\n\n self.d_up_conv_1 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=32, out_channels=64, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(64), \n\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.ConvTranspose2d(in_channels=64, out_channels=128, kernel_size=(2, 2), stride=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n\n # 128x64x64\n self.d_block_1 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n \n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 128x64x64\n self.d_block_2 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n \n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 128x64x64\n self.d_block_3 = nn.Sequential(\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n \n \n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=128, out_channels=128, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(128)\n \n )\n\n # 256x128x128\n self.d_up_conv_2 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=128, out_channels=32, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(32), \n\n nn.ZeroPad2d((1, 1, 1, 1)),\n nn.ConvTranspose2d(in_channels=32, out_channels=32, kernel_size=(2, 2), stride=(2, 2)),\n nn.ReLU(),\n nn.BatchNorm2d(32) \n )\n\n # 3x128x128\n self.d_up_conv_3 = nn.Sequential(\n nn.Conv2d(bias=False,in_channels=32, out_channels=16, kernel_size=(3, 3), stride=(1, 1)),\n nn.ReLU(),\n nn.BatchNorm2d(16), \n\n #nn.ReflectionPad2d((1, 1, 1, 1)),\n nn.Conv2d(bias=False,in_channels=16, out_channels=1, kernel_size=(3, 3), stride=(1, 1)),\n nn.Tanh()\n )\n\n def forward(self, x, encode=False):\n ec1 = self.e_conv_1(x)\n ec2 = self.e_conv_2(ec1)\n eblock1 = self.e_block_1(ec2) + ec2\n eblock2 = self.e_block_2(eblock1) + eblock1\n eblock3 = self.e_block_3(eblock2) + eblock2\n eblock4 = self.e_block_3(eblock3) + eblock3\n eblock5 = self.e_block_3(eblock4) + eblock4\n ec3 = self.e_conv_3(eblock5) \n ec4 = self.e_conv_4(ec3)\n self.sh = ec4.shape\n self.encoded = self.lin_in(ec4.view(len(ec4), -1))\n\n\n\n if encode:\n return self.encoded\n\n return self.decode(self.encoded)\n\n def decode(self, encoded):\n y = encoded #* 2.0 - 1 # (0|1) -> (-1|1)\n\n y = self.lin_out( y )\n y = y.view(self.sh)\n uc0 = self.d_up_conv_0(y)\n uc1 = self.d_up_conv_1(uc0)\n dblock1 = self.d_block_1(uc1) + uc1\n dblock2 = self.d_block_2(dblock1) + dblock1\n dblock3 = self.d_block_3(dblock2) + dblock2\n dblock4 = self.d_block_3(dblock3) + dblock3\n dblock5 = self.d_block_3(dblock4) + dblock4\n uc2 = self.d_up_conv_2(dblock5)\n dec = self.d_up_conv_3(uc2)\n\n return dec\n\nmodel = Network()\n\n#def weights_init(m):\n# if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Linear):\n# nn.init.xavier_uniform_(m.weight.data)\n #nn.init.xavier_uniform_(m.bias.data)\n\n\n\n\n#model.apply(weights_init)\n\nmodel = nn.DataParallel(model)\nmodel.cuda()\n# model = model.cuda()\n# min_loss = 10\n\n# x = torch.FloatTensor(X_batch)\n# op = model(x.cuda())\n\n\nbest_ep = 0\nbest_val_acc = -1\n\ndef train(epoch):\n \n #Train\n train_acc_sum = 0\n total_loss = 0 \n for batch_idx, batch in enumerate(tqdm(data_loader_train)):\n # model.train()\n images, targets = batch[0], batch[1]\n images, targets = images.cuda(), targets.cuda()\n \n optimizer.zero_grad()\n output = model(images)\n loss = criterion(output,images)\n loss.backward()\n optimizer.step()\n total_loss+=loss.item()\n \n\n op_train_loss = total_loss / (batch_idx + 1)\n\n return op_train_loss\n\ndef validate(epoch):\n\n #Validate\n acc_sum = 0\n total_loss = 0 \n with torch.no_grad():\n for batch_idx, batch in enumerate(data_loader_val):\n model.eval()\n images, targets = batch[0], batch[1]\n images, targets = images.cuda(), targets.cuda()\n output = model(images)\n # print(images.cpu().numpy().shape,images.cpu().numpy().shape)\n val_loss = criterion(output,images)\n total_loss+=val_loss.item()\n\n image = (images[0].cpu().numpy().transpose(1,2,0)*127.5 + 127.5).astype(np.int32)\n output = (output[0].cpu().numpy().transpose(1,2,0)*127.5 + 127.5).astype(np.int32)\n # mim.imsave(\"Outputs/image.png\",image)\n # mim.imsave(\"Outputs/output.png\",output)\n op_val_loss = total_loss / (batch_idx + 1)\n\n H,W,_ = image.shape\n return op_val_loss, image.reshape((H,W)), output.reshape((H,W))\n\n\noptimizer = torch.optim.Adam(model.parameters(), lr = LEARNING_RATE, weight_decay=WEIGHT_DECAY)\ncriterion = nn.MSELoss().cuda()\n\nbest_ep = 0\nbest_loss = 100\n\nfor i in range(Epochs):\n op_train_loss = train(i)\n op_val_loss,image, output = validate(i)\n print(\"\\n\\nEpoch - \",i, \" Train Loss : \", op_train_loss,\" Val Loss : \", op_val_loss, \"\\n\\n\")\n if op_val_loss None:\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n request = \"INSERT INTO Products(ProductName, Description, Category, WeightClass, WarrantlyPeriod, SupplierId, Status, ListPrice, MinimumPrice, PriceCurrency, CatalogURL) VALUES (\\\"\"+obj.ProductName+\"\\\", \\\"\"+obj.Description+\"\\\", \\\"\"+str(obj.Category)+\"\\\", \\\"\"+str(obj.WeightClass)+\"\\\", \\\"\"+str(obj.WarrantlyPeriod)+\"\\\", \\\"\"+str(obj.SupplierId)+\"\\\", \\\"\"+obj.Status+\"\\\", \\\"\"+str(obj.ListPrice)+\"\\\", \\\"\"+str(obj.MinimumPrice)+\"\\\", \\\"\"+obj.PriceCurrency+\"\\\", \\\"\"+obj.CatalogURL+\"\\\");\"\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def delete(self, id) -> None:\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n request = \"DELETE FROM Products WHERE ProductId = \"+str(id)+\";\"\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def edit(self, id, obj) -> None:\n request = \"UPDATE Products SET ProductName = '\" + obj.ProductName + \"',Description = '\" + obj.Description + \"',Category = \" + str(obj.Category) + \",WeightClass = \" + str(obj.WeightClass) + \",WarrantlyPeriod = \" + str(obj.WarrantlyPeriod) + \",SupplierId = \" + str(obj.SupplierId) + \",Status = '\" + obj.Status + \"',ListPrice = \" + str(obj.ListPrice) + \",MinimumPrice = \" + str(obj.MinimumPrice) + \",PriceCurrency = '\" + obj.PriceCurrency + \"',CatalogURL = '\" + obj.CatalogURL + \"' WHERE ProductId= \"+str(id)+\";\"\n print(request)\n connection = sqlite3.connect(self.sqlite_path)\n c = connection.cursor()\n c.execute(request)\n connection.commit()\n c.close()\n connection.close()\n\n def get(self) -> List[Product]:\n connection = sqlite3.connect(self.sqlite_path)\n cursor = connection.cursor()\n request = \"SELECT ProductId, ProductName, Description, Category, WeightClass, WarrantlyPeriod, SupplierId, Status, ListPrice, MinimumPrice, PriceCurrency, CatalogURL FROM Products\"\n cursor.execute(request)\n fetch = cursor.fetchall()\n ls = []\n for each in fetch:\n product = Product()\n product.load(each)\n ls.append(product)\n return ls\n\n def get_id(self, id) -> Product:\n connection = sqlite3.connect(self.sqlite_path)\n cursor = connection.cursor()\n request = \"SELECT * FROM Products WHERE ProductId = \"+str(id)\n cursor.execute(request)\n fetch = cursor.fetchone()\n product = Product()\n product.load(fetch)\n return product\n\n ","sub_path":"WebService/application/repositories/products_repository.py","file_name":"products_repository.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"531860524","text":"#!/usr/bin/env python\n\nimport sqlalchemy as db\nfrom sqlalchemy import inspect\n\nengine = db.create_engine('postgres://sfpsspfkxoefrk:394a5e3d8ff5b09142009ed610ef9002891a41f62b6418b7942014fc04ded0c4@ec2-54-221-212-126.compute-1.amazonaws.com:5432/d1k4lgpd2ju9o2')\nconnection = engine.connect()\nmetadata = db.MetaData()\n\nemp = db.Table('emp', metadata,\n db.Column('Id', db.Integer()),\n db.Column('name', db.String(255), nullable=False),\n db.Column('salary', db.Float(), default=100.0),\n db.Column('active', db.Boolean(), default=True)\n )\n\nmetadata.create_all(engine) #Creates the table\n\nquery = db.insert(emp).values(Id=2, name='naveen', salary=60000.00, active=True)\nResultProxy = connection.execute(query)\n\nprint(emp.columns.keys())\n\ninspector = inspect(engine)\nprint(inspector.get_columns('emp'))\n","sub_path":"flask-test/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"579415250","text":"import turtle\r\nfrom Algoritmos.Algoritmos import *\r\n\r\nLENGTH = 20\r\nwindow = turtle.Screen() #Creamos una ventana de turtle\r\nwindow.screensize(1000,1000) #Le dimos un tamaño a la ventana \r\n\r\nfig= turtle.Turtle() #Creamos el lapiz con el que vamos a dibujar\r\n\r\n\r\n\r\ndef linea(x_vars,y_vars): #DEfinimos la linua\r\n \"\"\"Dibuja una linea en pixeles\r\n\r\n Args:\r\n x_vars (list): [coordenadas x]\r\n y_vars (list): [coordenadas y]\r\n \"\"\"\r\n for i in range(len(x_vars)):\r\n x=LENGTH* x_vars[i]\r\n y=LENGTH* y_vars[i]\r\n\r\n fig.penup() #levantamos el lapiz para que no dibuje\r\n fig.goto(x,y)\r\n fig.pendown() #Colocamos el lapiz en el lienzo para poder dibujar\r\n for i in range(4): \r\n fig. fd(LENGTH) #\r\n fig.rt(90) #noventa grados\r\n\r\ndef cuadrilateros(matriz,algoritmo): #definimos el cuadrilatero dentro llamamos de matriz algoritmo \r\n if algoritmo == 1:\r\n lado1 = dda(matriz[0][0],matriz[0][1],matriz[1][0],matriz[1][1]) #matriz de [[x],[y]]\r\n lado2 = dda(matriz[0][0],matriz[0][1],matriz[2][0],matriz[2][1])\r\n lado3 = dda(matriz[2][0],matriz[2][1],matriz[3][0],matriz[3][1])\r\n lado4 = dda(matriz[1][0],matriz[1][1],matriz[3][0],matriz[3][1])\r\n else:\r\n lado1 = bresenham(matriz[0][0],matriz[0][1],matriz[1][0],matriz[1][1]) #matriz de [[x],[y]]\r\n lado2 = bresenham(matriz[0][0],matriz[0][1],matriz[2][0],matriz[2][1])\r\n lado3 = bresenham(matriz[2][0],matriz[2][1],matriz[3][0],matriz[3][1])\r\n lado4 = bresenham(matriz[1][0],matriz[1][1],matriz[3][0],matriz[3][1])\r\n return [lado1,lado2,lado3,lado4]\r\ndef triangulos(matriz,algoritmo):\r\n if algoritmo ==1:\r\n lado1 =dda(matriz[0][0], matriz[0][1], matriz[1][0],matriz[1][1])\r\n lado2 =dda(matriz[0][0], matriz[0][1], matriz[2][0],matriz[2][1])\r\n lado3 =dda(matriz[2][0], matriz[2][1], matriz[1][0],matriz[1][1])\r\n\r\n else:\r\n lado1 =bresenham(matriz[0][0], matriz[0][1], matriz[1][0],matriz[1][1])\r\n lado2 =bresenham(matriz[0][0], matriz[0][1], matriz[2][0],matriz[2][1])\r\n lado3 =bresenham(matriz[2][0], matriz[2][1], matriz[1][0],matriz[1][1])\r\n \r\n return [lado1,lado2,lado3]\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n print (\"\"\"Elije una opcion:\r\n 1) Cuadrilateros(Cuadrado/Rectangulo)\r\n 2)Triangulo equilatero\r\n 3)Triangulo rectangulo\r\n \"\"\")\r\n opcion = int(input(\"-->\"))\r\n\r\n print(\"\"\"Algoritmo a usar\r\n 1)dda\r\n 2)bresenham\r\n \"\"\")\r\n algoritmo = int(input(\"-->\"))\r\n #Definir listas\r\n if (opcion == 1):\r\n #Cuadrilateros\r\n width,height =input(\"(x,y) \").split(\",\")\r\n width = int(width)-1\r\n height = int(height)-1\r\n puntos = puntos_cuadrilateros(width, height) \r\n print(f\"Puntos: {puntos}\")\r\n resultados = cuadrilateros(puntos,algoritmo)\r\n print(f\"Resultados: {resultados}\")\r\n \r\n elif (opcion == 2):\r\n #Triangulo equilatero\r\n width =input(\"(base) \")\r\n width = int(width)-1\r\n puntos = puntos_equilateros(width) \r\n print(f\"Puntos: {puntos}\")\r\n resultados = triangulos(puntos,algoritmo)\r\n print(f\"Resultados: {resultados}\")\r\n \r\n elif (opcion == 3):\r\n #Triangulo rectangulo\r\n width,height=input(\"(x,y)\").split(\",\")\r\n width=int (width)\r\n height=int (height)\r\n puntos = puntos_Rectangulo(width, height)\r\n print(f\"Puntos:{puntos}\")\r\n resultados= triangulos(puntos,algoritmo)\r\n print(f\"Resultados:{resultados}\")\r\n\r\n elif (opcion == 4):\r\n #Poligono \r\n \r\n\r\n pass\r\n for punto in resultados:\r\n linea(punto[0],punto[1])\r\n\r\nturtle.mainloop()\r\n","sub_path":"TrazoDePoligonos_Erika Yazmin Dionisio Velasco_3601.c.py","file_name":"TrazoDePoligonos_Erika Yazmin Dionisio Velasco_3601.c.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"414143504","text":"import logging\nimport math\n\nimport lxml.html\nimport tqdm\n\nfrom .base import AbstractImport, Address, get_ssl_no_verify_opener\nfrom utils.utils import groupby\n\n\nclass GISNET(AbstractImport):\n # parametry do EPSG 2180\n # __MAX_BBOX_X = 20000\n # __MAX_BBOX_Y = 45000\n __MAX_BBOX_X = 1000\n __MAX_BBOX_Y = 1000\n __PRECISION = 10\n __base_url = (\n \"http://%s.gis-net.pl/geoserver-%s/wms?SERVICE=WMS&FORMAT=application/vnd.google-earth.kml+xml&\"\n \"VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS=Punkty_Adresowe&STYLES=&SRS=EPSG:2180&WIDTH=1000&\"\n \"HEIGHT=1000&BBOX=\"\n )\n __log = logging.getLogger(__name__).getChild(\"GISNET\")\n\n def __init__(self, gmina, terc):\n super(GISNET, self).__init__(terc=terc)\n self.terc = terc\n self.gmina = gmina\n\n @staticmethod\n def divide_bbox(minx, miny, maxx, maxy):\n \"\"\"divides bbox to tiles of maximum supported size by EMUiA WMS\"\"\"\n # noinspection PyTypeChecker\n return [\n (\n x / GISNET.__PRECISION,\n y / GISNET.__PRECISION,\n min(x / GISNET.__PRECISION + GISNET.__MAX_BBOX_X, maxx),\n min(y / GISNET.__PRECISION + GISNET.__MAX_BBOX_Y, maxy),\n )\n for x in range(\n math.floor(minx * GISNET.__PRECISION),\n math.ceil(maxx * GISNET.__PRECISION),\n GISNET.__MAX_BBOX_X * GISNET.__PRECISION,\n )\n for y in range(\n math.floor(miny * GISNET.__PRECISION),\n math.ceil(maxy * GISNET.__PRECISION),\n GISNET.__MAX_BBOX_Y * GISNET.__PRECISION,\n )\n ]\n\n def _convert_to_address(self, soup) -> Address:\n desc_soup = lxml.html.fromstring(\n str(soup.find(\"{http://www.opengis.net/kml/2.2}description\").text)\n )\n addr_kv = dict(\n (str(x.find(\"strong\").find(\"span\").text), str(x.find(\"span\").text))\n for x in desc_soup.find(\"ul\").iterchildren()\n )\n\n coords = (\n soup.find(\"{http://www.opengis.net/kml/2.2}Point\")\n .find(\"{http://www.opengis.net/kml/2.2}coordinates\")\n .text.split(\",\")\n )\n ret = Address.mapped_address(\n addr_kv[\"numer_adr\"],\n addr_kv.get(\"KOD_POCZTOWY\"),\n addr_kv.get(\"nazwa_ulicy\"),\n addr_kv[\"miejscowosc\"],\n addr_kv.get(\"TERYT_ULICY\"),\n addr_kv.get(\"TERYT_MIEJSCOWOSCI\"),\n \"%s.gis-net.pl\" % (self.gmina,),\n {\"lat\": coords[1], \"lon\": coords[0]},\n addr_kv.get(\"id_adres\"),\n )\n ret.status = addr_kv[\"status\"]\n return ret\n\n def _is_eligible(self, addr: Address):\n # TODO: check status?\n if addr.status.upper() != \"POGLĄDOWE\":\n self.__log.debug(\n \"Ignoring address %s, because status %s is not ZATWIERDZONY\",\n addr,\n addr.status.upper(),\n )\n return False\n if not addr.get_point().within(self.shape):\n # do not report anything about this, this is normal\n return False\n return True\n\n def fetch_tiles(self):\n bbox = self.get_bbox_2180()\n ret = []\n for i in tqdm.tqdm(self.divide_bbox(*bbox), \"Download\"):\n url = GISNET.__base_url % (self.gmina, self.gmina) + \",\".join(map(str, i))\n self.__log.info(\"Fetching from GISNET: %s\", url)\n opener = get_ssl_no_verify_opener()\n\n data = opener.open(url).read()\n self.__log.debug(\"Reponse size: %d\", len(data))\n soup = lxml.etree.fromstring(data)\n doc = soup.find(\n \"{http://www.opengis.net/kml/2.2}Document\"\n ) # be namespace aware\n if doc is not None:\n ret.extend(\n filter(\n self._is_eligible,\n map(\n self._convert_to_address,\n doc.iterchildren(\n \"{http://www.opengis.net/kml/2.2}Placemark\"\n ),\n ),\n )\n )\n else:\n raise ValueError(\n \"No data returned from GISNET possibly to wrong scale. Check __MAX_BBOX_X, \"\n \"__MAX_BBOX_Y, HEIGHT and WIDTH\"\n )\n # take latest version for each point (version is last element after dot in id_)\n ret = [\n max(v, key=lambda z: z.id_)\n for v in groupby(ret, lambda z: z.id_.rsplit(\".\", 1)[0]).values()\n ]\n return ret\n","sub_path":"data/gisnet.py","file_name":"gisnet.py","file_ext":"py","file_size_in_byte":4709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"427612819","text":"# -*- coding: utf-8 -*-\nimport jieba # 分词\nimport numpy as np #科学计算\nimport matplotlib.pyplot as plt #数据可视化\nfrom wordcloud import WordCloud,ImageColorGenerator,STOPWORDS #词云,颜色生成器,截止词语\n\nfrom PIL import Image #处理图片\n\ntextfile = open(\"rsa.txt\",'rb') #读取文本内容\ntextfile=textfile.read()\n# wordlist = jieba.cut(textfile,cut_all=True) #切割\nwordlist = jieba.cut_for_search(textfile) #切割\n\nspace_list = \" \".join(wordlist) #链接词语\n\nbackgroud = np.array(Image.open(\"2.jpg\")) #背景图片\n\nmywordcloud=WordCloud(background_color=\"pink\",#北京颜色\n mask=backgroud,#写字用的背景图,从背景图取颜色\n max_words=40,#最大词语数量\n stopwords=STOPWORDS, #停止的词语\n font_path=\"simkai.ttf\", #字体类型\n max_font_size=100, #字体大小\n random_state=30, #随机角度\n scale=1,\n ).generate(space_list) #生成词云\n\nimage_color = ImageColorGenerator(backgroud) #生成词云的颜色\nplt.imshow(mywordcloud) #显示词云\nplt.axis(\"off\") #不保存图片,关闭保存\nplt.show() #显示图片\n\n\n\n\n\n","sub_path":"day4/词云定制.py","file_name":"词云定制.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"298402770","text":"from flask import Flask\napp = Flask(__name__)\n \n@app.route('/')\ndef hello_world():\n return 'Hello World!'\n\nimport psycopg2 \nimport json\nfrom flask import jsonify\n \n \nfrom flask_cors import CORS\nfrom flask_cors import CORS, cross_origin\nfrom flask import Flask, render_template, redirect, url_for, request \n \nimport datetime\n\nCORS(app, support_credentials=True)\n\nimport json\n\n@app.route('/add_providers', methods=['POST'])\n@cross_origin(origin='*')\ndef get_provider():\n request_data = json.dumps(request.json)\n json_request=json.loads(request_data)\n provider = json_request['provider']\n project = json_request['project']\n owner = json_request['owner']\n environment = json_request['enviroment']\n print(provider,provider,owner,environment)\n try:\n connection = psycopg2.connect(user=\"postgres\",password=\"postgres\",host=\"127.0.0.1\",port=\"5432\",database=\"vue_web\")\n cursor = connection.cursor()\n datetime_string=datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n #insert into providers(provider,environment,project,owner,created_on) values ('aws','Development','test','wilson','2020-1-1'::timestamp);\n postgres_insert_query = \"\"\" INSERT INTO providers (provider, environment, project,owner,created_on) VALUES (%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(postgres_insert_query, ( provider,environment,project,owner,datetime_string))\n connection.commit()\n count = cursor.rowcount\n print (count, \"Record inserted successfully into mobile table\")\n except (Exception, psycopg2.Error) as error :\n print (\"Error while connecting to PostgreSQL\", error)\n return json.dumps({'result': 'fail'})\n finally:\n #closing database connection.\n if(connection):\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n return json.dumps({'result': 'success'})\n\n@cross_origin(origin='*')\n@app.route('/providers', methods=['GET'])\ndef add_provider():\n try:\n providers_list = []\n connection = psycopg2.connect(user=\"postgres\",password=\"postgres\",host=\"127.0.0.1\",port=\"5432\",database=\"vue_web\")\n cursor = connection.cursor()\n postgreSQL_select_Query = \"select provider,environment,project, owner, to_char(created_on, 'YYYY-DD-MM') from providers\"\n cursor.execute(postgreSQL_select_Query)\n providers = cursor.fetchall() \n except (Exception, psycopg2.Error) as error :\n print (\"Error while connecting to PostgreSQL\", error)\n return 'fail'\n finally:\n if(connection):\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n for provider in providers:\n providers_list.append(provider)\n return jsonify({'providers': providers_list})\n\n\n\nimport jenkins \n\n\n@app.route('/jenkins/jobs/run', methods=['POST'])\n@cross_origin(origin='*')\ndef jenkins_run_job():\n request_data = json.dumps(request.json)\n json_request=json.loads(request_data)\n job_name = json_request['job_name']\n print(job_name)\n # job_name='test_pipeline'\n server = jenkins.Jenkins('http://10.169.153.19:8090/', username='admin', password='QWEqwe123!@#') \n last_build_number = server.get_job_info(job_name)['lastCompletedBuild']['number']\n server.build_job(job_name)\n build_info = server.get_build_info(job_name, last_build_number)\n return json.dumps({'result': 'success','build_number': str(last_build_number),'job_url': 'http://10.169.153.19:8090/job/'+job_name+'/'+str(last_build_number) })\n \n\n\n\n\n@app.route('/jenkins/jobs/status1', methods=['GET'])\n@cross_origin(origin='*')\ndef jenkins_query_job1():\n # request_data = json.dumps(request.json)\n # json_request=json.loads(json.dumps(request.json))\n # job_name = json_request['job_name']\n # build_number = json_request['build_number']\n # job_url = json_request['job_url']\n print(request)\n # request_data = json.dumps(request.json)\n # json_request=json.loads(request_data)\n # job_name = json_request['job_name']\n # build_number=json_request('build_number')\n job_name=request.args.get('job_name')\n build_number=request.args.get('build_number')\n print(job_name,build_number)\n server = jenkins.Jenkins('http://10.169.153.19:8090/', username='admin', password='QWEqwe123!@#') \n build_info = server.get_build_info(job_name, int(build_number))\n print(build_info)\n if build_info['building']:\n print(build_info['building'])\n return json.dumps({'result': 'success','status': 'running'})\n elif not build_info['building'] and build_info['result'] =='ABORTED': \n print(build_info['result'])\n return json.dumps({'result': 'success','status': 'aborted'})\n elif not build_info['building'] and build_info['result'] =='SUCCESS': \n print(build_info['result'])\n return json.dumps({'result': 'success','status': 'SUCCESS'})\n\n\n@app.route('/deploymentjob/jobs/list', methods=['GET'])\n@cross_origin(origin='*')\ndef deploymentJob_query():\n jobs_list=[]\n try:\n connection = psycopg2.connect(user=\"postgres\",password=\"postgres\",host=\"127.0.0.1\",port=\"5432\",database=\"vue_web\")\n cursor = connection.cursor()\n if request.args.get('job_name') == None or request.args.get('build_number') == None :\n deploymentJob_query= \"\"\" select resourcetype,jobtype,name,environment,owner, datetime , status from deploymentjob \"\"\"\n print('query all the jobs')\n else:\n# job_name=request.args.get('job_name')\n# build_number=request.args.get('build_number')\n deploymentJob_query= \"\"\" select * from deploymentjob where \"\"\"\n cursor.execute(deploymentJob_query)\n jobs = cursor.fetchall()\n except (Exception, psycopg2.Error) as error :\n print (\"Error while connecting to PostgreSQL\", error)\n return 'fail'\n finally:\n if(connection):\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n for job in jobs:\n print(job)\n jobs_list.append({'resourcetype':job[0], 'jobtype':job[1],'name':job[2],'environment':job[3],'owner':job[4],'datetime':job[5],'status':job[6]})\n return jsonify({'jobs': jobs_list})\n #return json.dumps(t)\n\nimport json, ast\n\n@app.route('/deploymentjob/jobs/create', methods=['POST'])\n@cross_origin(origin='*')\ndef deploymentJob_create():\n request_data = json.dumps(request.json)\n request_data=json.loads(request_data)\n print(request_data['provider'])\n# request_data=ast.literal_eval(json.dumps(request.json))\n try:\n connection = psycopg2.connect(user=\"postgres\",password=\"postgres\",host=\"127.0.0.1\",port=\"5432\",database=\"vue_web\")\n cursor = connection.cursor()\n #deploymentJob_create= \"\"\" insert into deploymentjob VALUES (%s,%s,%s,%s,%s) \"\"\"\n deploymentJob_create=\"\"\" INSERT INTO deploymentjob (name, resourcetype, provider,jobtype, environment, owner, datetime, status) values (%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\n cursor.execute(deploymentJob_create,(request_data['name'],request_data['resourcetype'],request_data['provider'],request_data['jobtype'],request_data['environment'],request_data['owner'],request_data['datetime'],request_data['status'],))\n connection.commit()\n\n except (Exception, psycopg2.Error) as error :\n print (\"Error while connecting to PostgreSQL\", error)\n return json.dumps({'result': 'failed' })\n finally:\n if(connection):\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed\")\n return json.dumps({'result': 'success' })\n\n\n\nif __name__ == '__main__':\n app.run(\n\t host = '0.0.0.0',\n port = 7777, \n debug = True ) ","sub_path":"pythonWorkspace/python-jenkins.py","file_name":"python-jenkins.py","file_ext":"py","file_size_in_byte":7691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"234512283","text":"\"\"\"Code to create a permuted image through affine transformations.\"\"\"\n\n# Python imports.\nimport random\n\n# 3rd party imports.\nimport numpy as np\nimport scipy.ndimage\n\n# Testing imports.\nfrom matplotlib import pyplot as plt\n\n\ndef main(fileImage, maxRotation=0, maxShear=(0,), maxTranslation=(0,), maxScale=(1,), scaleUpProb=(0.5,),\n jointScale=False, inversionProb=(0.0,), backgroundColor=255):\n \"\"\"\n\n Transformations are treated as symmetric. A maximum rotation of 45 degrees is therefore a maximum rotation\n of 45 degrees clockwise and 45 degrees counterclockwise, thereby giving you a maximum total rotation of 90 degrees.\n\n sacle up prob is the probability of scaling up compared to scaling down\n\n we would need to center the image at (0, 0) first. However, at present\n # doing this causes the image to clip, and so the full transformation is done in non-clipping steps.\n\n joint scaling will cause the x axis scalingto be calcualted and then used for both axes (any entry in the maxScale\n list/tuple except the first will be ignroed)\n\n Perform operations sequentially in order to gain the desired control over the output.\n\n \"\"\"\n\n # Load the image and determine its size.\n imageArray = scipy.ndimage.imread(fileImage)\n\n # Create the scaling factors.\n # The difficulty with this is ensuring that the probability of scaling up and down is similar.\n # For example, if maxXScale == 5, then the probability of getting a scale value in (1, 5] is far greater\n # than the probability of getting a value in the range [0, 1). As the maximum scale factor gets bigger, it\n # only becomes more likely that scaling up will occur. Avoid this by uncoupling the scaling factor choice from\n # the direction of scaling.\n maxXScale = maxScale[0]\n maxYScale = maxScale[1] if len(maxScale) > 1 else maxScale[0]\n scaleX = 1\n scaleY = 1\n if maxXScale > 1:\n scaleX = random.uniform(1, maxXScale)\n scaleXDown = random.random() < scaleUpProb[0]\n scaleX = (1. / scaleX) if scaleXDown else scaleX\n if maxYScale > 1:\n if jointScale:\n # Scale the Y axis the same as the X axis.\n scaleY = scaleX\n else:\n # Potentially scale the axes differently.\n scaleY = random.uniform(1, maxYScale)\n scaleYDown = random.random() < (scaleUpProb[1] if len(scaleUpProb) > 1 else scaleUpProb[0])\n scaleY = (1. / scaleY) if scaleYDown else scaleY\n\n # Calculate the degree of rotation.\n degreeRotation = random.uniform(0, maxRotation * 2) - maxRotation\n\n # Create the shear matrix.\n shearMatrix = np.identity(2)\n maxXShear = maxShear[0]\n maxYShear = maxShear[1] if len(maxShear) > 1 else maxShear[0]\n degreeShearX = random.uniform(0, maxXShear * 2) - maxXShear\n degreeShearY = random.uniform(0, maxYShear * 2) - maxYShear\n radianShearX = np.deg2rad(degreeShearX)\n radianShearY = np.deg2rad(degreeShearY)\n shearMatrix[0, 1] = np.tan(radianShearY)\n shearMatrix[1, 0] = np.tan(radianShearX)\n\n # Create the translation.\n maxXTranslation = maxTranslation[0]\n maxYTranslation = maxTranslation[1] if len(maxTranslation) > 1 else maxTranslation[0]\n translationX = random.randint(0, maxXTranslation)\n translationY = random.randint(0, maxYTranslation)\n\n # Determine whether to invert the axes.\n xInversionProb = inversionProb[0]\n yInversionProb = inversionProb[1] if len(inversionProb) > 1 else inversionProb[0]\n isXInverted = random.random() < xInversionProb\n isYInverted = random.random() < yInversionProb\n\n # Create the transformed image.\n transformedImage = np.empty(imageArray.shape) # Create the correctly sized transformed image.\n transformedImage.fill(backgroundColor) # Fill the transformed image with only background.\n\n # Scale the image. The goal is to 'zoom' in or out of the image while keeping the array the same size.\n # This works by first zooming, and then placing the portion of the zoomed image desired into a correctly sized\n # (and possibly padded) array.\n # For example, if the zoom factor is 2, then the result of scipy.ndimage.zoom will be an array that is twice\n # the desired size. In order to resize this, the central portion of the zoomed array is taken and placed into\n # the transformed array. If the zoom factor was a fraction, then the entire zoomed image would be placed into\n # the transformed array with background padding around it.\n zoomedImage = scipy.ndimage.zoom(imageArray, [scaleY, scaleX], cval=backgroundColor) # Zoom.\n transSlice = {'X': [0, transformedImage.shape[1]],\n 'Y': [0, transformedImage.shape[0]]} # Slice of the transformed image where the zoom will be placed.\n zoomSlice = {'X': [0, zoomedImage.shape[1]],\n 'Y': [0, zoomedImage.shape[0]]} # Slice of the zoomed image to copy into the transformed image.\n pixelDifference = [abs(i - j) for i, j in zip(imageArray.shape, zoomedImage.shape)] # Image size difference.\n if scaleX < 1:\n # The zoomed image is smaller along the X axis than it should be. Take the zoomed image and center it along\n # the transformed image's X axis.\n transSlice['X'][0] = int(np.floor(pixelDifference[1] / 2))\n transSlice['X'][1] = transSlice['X'][0] + zoomedImage.shape[1]\n elif scaleX > 1:\n # The zoomed image is larger along the X axis than it should be. Take the zoomed image and remove some of\n # the left and right columns of pixels.\n zoomSlice['X'][0] = int(np.floor(pixelDifference[1] / 2))\n zoomSlice['X'][1] = zoomSlice['X'][0] + transformedImage.shape[1]\n if scaleY < 1:\n # The zoomed image is smaller along the Y axis than it should be. Take the zoomed image and center it along\n # the transformed image's Y axis.\n transSlice['Y'][0] = int(np.floor(pixelDifference[0] / 2))\n transSlice['Y'][1] = transSlice['Y'][0] + zoomedImage.shape[0]\n elif scaleY > 1:\n # The zoomed image is larger along the Y axis than it should be. Take the zoomed image and remove some of\n # the top and bottom of pixels.\n zoomSlice['Y'][0] = int(np.floor(pixelDifference[0] / 2))\n zoomSlice['Y'][1] = zoomSlice['Y'][0] + transformedImage.shape[0]\n transformedImage[transSlice['Y'][0]:transSlice['Y'][1], transSlice['X'][0]:transSlice['X'][1]] = \\\n zoomedImage[zoomSlice['Y'][0]:zoomSlice['Y'][1], zoomSlice['X'][0]:zoomSlice['X'][1]]\n\n # Rotate the image. This must be done with ndimage.rotate rather than ndimage.affine_transform as we want to rotate\n # around the center of the image. If we used affine_transform, then the rotation would be performed around (0, 0).\n # This could be countered by setting the center of the image to (0, 0), but then the rotation clips the image.\n transformedImage = scipy.ndimage.rotate(transformedImage, degreeRotation, cval=backgroundColor)\n\n # Shear the image. This can be done with affine_transform as we don't need it to occur at the center of the image.\n transformedImage = scipy.ndimage.affine_transform(transformedImage, shearMatrix, cval=backgroundColor)\n\n # Crop out any excess rows and columns that consist only of background pixels.\n backgroundRows = np.all(transformedImage == backgroundColor, axis=1)\n backgroundCols = np.all(transformedImage == backgroundColor, axis=0)\n transformedImage = transformedImage[~backgroundRows, :][:, ~backgroundCols]\n\n # Invert the image.\n if isXInverted:\n transformedImage = np.fliplr(transformedImage)\n if isYInverted:\n transformedImage = np.flipud(transformedImage)\n\n # Translate the image.\n transformedImage = scipy.ndimage.shift(transformedImage, [translationX, translationY], cval=backgroundColor)\n\n print(\"Translation : \", translationX, translationY)\n print(\"Inverserion : \", isXInverted, isYInverted)\n print(\"Shear : \", degreeShearX, degreeShearY)\n print(\"Scaled : \", scaleX, scaleY)\n print(\"Rotation\", degreeRotation)\n plt.imshow(transformedImage, cmap=\"Greys_r\")\n plt.show()\n\n return transformedImage\n","sub_path":"Code/Utilities/image_permutation.py","file_name":"image_permutation.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"103339816","text":"import argparse\n\nfrom .config import ExaParserConfig\nfrom .data.factory import get_data_handler\nfrom .job import Job\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-n\", \"--name\", required=True, help=\"job name\")\n parser.add_argument(\"-c\", \"--config\", help=\"full path to config file\")\n parser.add_argument(\"-w\", \"--work-dir\", dest=\"work_dir\", required=True, help=\"full path to working directory\")\n return parser.parse_args()\n\n\ndef main():\n args = parse_arguments()\n if args.config:\n ExaParserConfig.read(args.config)\n job = Job(args.name, args.work_dir)\n for handler in ExaParserConfig.get(\"global\", \"data_handlers\").replace(\" \", \"\").split(\",\"):\n get_data_handler(handler, job).handle()\n","sub_path":"exaparser/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"426679442","text":"## 2. Calculating differences ##\n\nfemale_diff = (10771 - 16280.5)/16280.5\nmale_diff = (21790 - 16280.5)/16280.5\n\n## 3. Updating the formula ##\n\nfemale_diff = ((10771 - 16280.5)**2)/16280.5\nmale_diff = ((21790 - 16280.5)**2)/16280.5\ngender_chisq = female_diff + male_diff\n\n## 4. Generating a distribution ##\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nchi_squared_values = []\nfor i in range(1000):\n fractions = np.random.random(32561,)\n binaries = []\n for num in fractions:\n if num < 0.5:\n binaries.append(0)\n else:\n binaries.append(1)\n male_ct = sum(binaries)\n female_ct = 32561 - male_ct\n male_diff = ((male_ct - 16280.5)**2)/16280.5\n female_diff = ((female_ct - 16280.5)**2)/16280.5\n gender_chisq = female_diff + male_diff\n chi_squared_values.append(gender_chisq)\n\nplt.hist(chi_squared_values)\nplt.show()\n\n## 6. Smaller samples ##\n\nfemale_diff = ((107.71 - 162.805)**2)/162.805\nmale_diff = ((217.90 - 162.805)**2)/162.805\ngender_chisq = female_diff + male_diff\n\n## 7. Sampling distribution equality ##\n\nchi_squared_values = []\nfor i in range(1000):\n fractions = np.random.random(300,)\n binaries = []\n for num in fractions:\n if num < 0.5:\n binaries.append(0)\n else:\n binaries.append(1)\n male_ct = sum(binaries)\n female_ct = 300 - male_ct\n male_diff = ((male_ct - 150)**2)/150\n female_diff = ((female_ct - 150)**2)/150\n gender_chisq = female_diff + male_diff\n chi_squared_values.append(gender_chisq)\n\nplt.hist(chi_squared_values)\nplt.show()\n\n## 9. Increasing degrees of freedom ##\n\nobserved = {\"white\":27816,\"black\":3124,\"asian\":1039,\"amerindian\":311,\"other\":271}\nexpected = {\"white\":26146.5,\"black\":3939.9,\"asian\":944.3,\"amerindian\":260.5,\"other\":1269.8}\ntotal = 32561\n\nrace_chisq = 0\nfor key in observed:\n diff = ((observed[key] - expected[key])**2)/expected[key]\n race_chisq += diff\n\n## 10. Using SciPy ##\n\nfrom scipy.stats import chisquare\nimport numpy as np\n\nobserved = [27816,3124,1039,311,271]\nexpected = [26146.5,3939.9,944.3,260.5,1269.8]\n\nrace_chisquare_value, race_pvalue = chisquare(observed, expected)","sub_path":"dataquest_exercises/prob_stats_intermediate/exercise_chi_squared_tests.py","file_name":"exercise_chi_squared_tests.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"301354934","text":"import os\nimport pytest\nfrom collections import namedtuple\n\nimport boto3\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\nimport mlflow\nimport mlflow.pyfunc\nimport mlflow.sklearn\nimport mlflow.sagemaker as mfs\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.models import Model\nfrom mlflow.protos.databricks_pb2 import ErrorCode, RESOURCE_DOES_NOT_EXIST, INVALID_PARAMETER_VALUE\nfrom mlflow.tracking.utils import _get_model_log_dir\n\nTrainedModel = namedtuple(\"TrainedModel\", [\"model_path\", \"run_id\"])\n\n\n@pytest.fixture\ndef pretrained_model():\n model_path = \"model\"\n with mlflow.start_run():\n X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)\n y = np.array([0, 0, 1, 1, 1, 0])\n lr = LogisticRegression()\n lr.fit(X, y)\n mlflow.sklearn.log_model(lr, model_path)\n run_id = mlflow.active_run().info.run_uuid\n return TrainedModel(model_path, run_id)\n\n\n@pytest.fixture\ndef sagemaker_client():\n return boto3.client(\"sagemaker\", region_name=\"us-west-2\")\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef set_boto_credentials():\n os.environ[\"AWS_ACCESS_KEY_ID\"] = \"NotARealAccessKey\"\n os.environ[\"AWS_SECRET_ACCESS_KEY\"] = \"NotARealSecretAccessKey\"\n os.environ[\"AWS_SESSION_TOKEN\"] = \"NotARealSessionToken\"\n\n\ndef mock_sagemaker_aws_services(fn):\n # Import `wraps` from `six` instead of `functools` to properly set the\n # wrapped function's `__wrapped__` attribute to the required value\n # in Python 2\n from six import wraps\n from moto import mock_s3, mock_ecr, mock_sts, mock_iam\n from tests.sagemaker.mock import mock_sagemaker\n\n @mock_ecr\n @mock_iam\n @mock_s3\n @mock_sagemaker\n @mock_sts\n @wraps(fn)\n def mock_wrapper(*args, **kwargs):\n # Create an ECR repository for the `mlflow-pyfunc` SageMaker docker image\n ecr_client = boto3.client(\"ecr\", region_name=\"us-west-2\")\n ecr_client.create_repository(repositoryName=mfs.DEFAULT_IMAGE_NAME)\n\n # Create the moto IAM role\n role_policy = \"\"\"\n {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Action\": \"*\",\n \"Resource\": \"*\"\n }\n ]\n }\n \"\"\"\n iam_client = boto3.client(\"iam\", region_name=\"us-west-2\")\n iam_client.create_role(RoleName=\"moto\", AssumeRolePolicyDocument=role_policy)\n\n return fn(*args, **kwargs)\n\n return mock_wrapper\n\n\ndef test_deployment_with_unsupported_flavor_raises_exception(pretrained_model):\n unsupported_flavor = \"this is not a valid flavor\"\n with pytest.raises(MlflowException) as exc:\n mfs.deploy(app_name=\"bad_flavor\",\n model_path=pretrained_model.model_path,\n run_id=pretrained_model.run_id,\n flavor=unsupported_flavor)\n\n assert exc.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)\n\n\ndef test_deployment_with_missing_flavor_raises_exception(pretrained_model):\n missing_flavor = \"mleap\"\n with pytest.raises(MlflowException) as exc:\n mfs.deploy(app_name=\"missing-flavor\",\n model_path=pretrained_model.model_path,\n run_id=pretrained_model.run_id,\n flavor=missing_flavor)\n\n assert exc.value.error_code == ErrorCode.Name(RESOURCE_DOES_NOT_EXIST)\n\n\ndef test_deployment_of_model_with_no_supported_flavors_raises_exception(pretrained_model):\n logged_model_path = _get_model_log_dir(pretrained_model.model_path, pretrained_model.run_id)\n model_config_path = os.path.join(logged_model_path, \"MLmodel\")\n model_config = Model.load(model_config_path)\n del model_config.flavors[mlflow.pyfunc.FLAVOR_NAME]\n model_config.save(path=model_config_path)\n\n with pytest.raises(MlflowException) as exc:\n mfs.deploy(app_name=\"missing-flavor\",\n model_path=logged_model_path,\n flavor=None)\n\n assert exc.value.error_code == ErrorCode.Name(RESOURCE_DOES_NOT_EXIST)\n\n\ndef test_validate_deployment_flavor_validates_python_function_flavor_successfully(\n pretrained_model):\n model_config_path = os.path.join(_get_model_log_dir(\n pretrained_model.model_path, pretrained_model.run_id), \"MLmodel\")\n model_config = Model.load(model_config_path)\n mfs._validate_deployment_flavor(\n model_config=model_config, flavor=mlflow.pyfunc.FLAVOR_NAME)\n\n\ndef test_get_preferred_deployment_flavor_obtains_valid_flavor_from_model(pretrained_model):\n model_config_path = os.path.join(_get_model_log_dir(\n pretrained_model.model_path, pretrained_model.run_id), \"MLmodel\")\n model_config = Model.load(model_config_path)\n\n selected_flavor = mfs._get_preferred_deployment_flavor(model_config=model_config)\n\n assert selected_flavor in mfs.SUPPORTED_DEPLOYMENT_FLAVORS\n assert selected_flavor in model_config.flavors\n\n\n@mock_sagemaker_aws_services\ndef test_deploy_creates_sagemaker_resources_with_expected_names(pretrained_model, sagemaker_client):\n app_name = \"test-app\"\n mfs.deploy(app_name=app_name,\n model_path=pretrained_model.model_path,\n run_id=pretrained_model.run_id,\n mode=mfs.DEPLOYMENT_MODE_CREATE)\n\n models_response = sagemaker_client.list_models()\n found_matching_model = False\n for model in models_response[\"Models\"]:\n if app_name in model[\"ModelName\"]:\n found_matching_model = True\n break\n assert found_matching_model\n\n endpoint_configs_response = sagemaker_client.list_endpoint_configs()\n found_matching_config = False\n for config in endpoint_configs_response[\"EndpointConfigs\"]:\n if app_name in config[\"EndpointConfigName\"]:\n found_matching_config = True\n break\n assert found_matching_config\n\n endpoints_response = sagemaker_client.list_endpoints()\n assert app_name in [endpoint[\"EndpointName\"] for endpoint in endpoints_response[\"Endpoints\"]]\n\n\n@mock_sagemaker_aws_services\ndef test_deploying_application_with_preexisting_name_in_create_mode_throws_exception(\n pretrained_model):\n app_name = \"test-app\"\n mfs.deploy(app_name=app_name,\n model_path=pretrained_model.model_path,\n run_id=pretrained_model.run_id,\n mode=mfs.DEPLOYMENT_MODE_CREATE)\n\n with pytest.raises(MlflowException) as exc:\n mfs.deploy(app_name=app_name,\n model_path=pretrained_model.model_path,\n run_id=pretrained_model.run_id,\n mode=mfs.DEPLOYMENT_MODE_CREATE)\n\n assert \"an application with the same name already exists\" in exc.value.message\n assert exc.value.error_code == ErrorCode.Name(INVALID_PARAMETER_VALUE)\n","sub_path":"tests/sagemaker/test_deployment.py","file_name":"test_deployment.py","file_ext":"py","file_size_in_byte":6793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"55743111","text":"import numpy, json\n\nclass NaiveBayesClassifier:\n\tdef __init__(self):\n\t\tself.classes = 'abcdefghijklmnopqrstuvwxyz0123456789'\n\n\tdef start_training(self):\n\t\tprint('Started training...')\n\t\ttraining_X = numpy.array([csv_line.split(',') for csv_line in open('Collected Training Data/training_X.csv').read().strip().split('\\n')]).astype(numpy.int)\n\t\ttraining_Y = open('Collected Training Data/training_Y.csv').read().strip().split('\\n')\n\t\t#---\n\t\tprobabilities_dict = {}\n\t\tprobabilities_dict['class_probs'] = []\n\t\tprobabilities_dict['0'] = {}\n\t\tprobabilities_dict['1'] = {}\n\t\t#---\n\t\tprogress_count = 0\n\t\t#---\n\t\tfor _class in self.classes:\n\t\t\tcurrent_class_matrix = numpy.array([list(training_X[i]) for i in range(len(training_X)) if training_Y[i] == _class])\n\t\t\tprobabilities_dict['1'][_class] = (current_class_matrix.sum(axis=0) + 1) / (len(current_class_matrix) + 36)\n\t\t\tprobabilities_dict['0'][_class] = 1 - probabilities_dict['1'][_class]\n\t\t\t#---jsonify---\n\t\t\tprobabilities_dict['0'][_class] = probabilities_dict['0'][_class].tolist()\n\t\t\tprobabilities_dict['1'][_class] = probabilities_dict['1'][_class].tolist()\n\t\t\tprobabilities_dict['class_probs'].append(open('Collected Training Data/training_Y.csv').read().count(_class) / float(len(training_Y)))\n\t\t\t#-------------\n\t\t\tprogress_count += 1\n\t\t\tprint('- Training progress:', str(progress_count * 100 / 36), '%')\n\t\tprint('====================')\n\t\tprint(' Training Complete!')\n\t\topen('Trained Model/brain.json', 'w').write(json.dumps(probabilities_dict, indent=4, sort_keys=True))\n\t\tprint('- Saved Trained Model/brain.json')\n\n\tdef getClassification(self, jchar_csv):\n\t\tprobabilities_dict = json.loads(open('brain.json', 'r').read())\n\t\t#\n\t\tprobs_class_given_features = {}\n\t\t#\n\t\tclass_index = 0\n\t\tfor _class in self.classes:\n\t\t\tfeature_index = 0\n\t\t\tprobs_class_given_features[_class] = probabilities_dict['class_probs'][class_index]\n\t\t\tfor feature in jchar_csv.split(','):\n\t\t\t\tprobs_class_given_features[_class] *= probabilities_dict[feature][_class][feature_index]\n\t\t\t\tfeature_index += 1\n\t\t\tclass_index += 1\n\t\t#\n\t\tmaximum_prob = max(probs_class_given_features.values())\n\t\tmax_keys = []\n\t\tfor key in probs_class_given_features.keys():\n\t\t\tif probs_class_given_features[key] == maximum_prob:\n\t\t\t\tmax_keys.append(key)\n\t\treturn max_keys[0]\n\n\n######\n######\n######\n\ndef main():\n\tclassifier = NaiveBayesClassifier()\n\ttestList = open('sample.csv', 'r').read().strip().split('\\n')\n\tfor t in testList:\n\t\tprint('solution:', classifier.getClassification(t))\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Training/naive_bayes_classifier.py","file_name":"naive_bayes_classifier.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"383704746","text":"from copy import deepcopy\nfrom sbmlutils.modelcreator import creator\nfrom models.utils.templates import MODEL_UNITS, UNITS\nfrom models.utils.utils import read_data, create_compartment, create_species, create_reaction\n\ndata = read_data(\"kidney/data.xlsx\")\nmid = data[\"info\"][\"mid\"][0]\nmodel_units = deepcopy(MODEL_UNITS)\nunits = deepcopy(UNITS)\n\ncompartments = [create_compartment(instance) for _,instance in data[\"compartment\"].iterrows()]\nspecies = [create_species(instance) for _,instance in data[\"specie\"].iterrows()]\nreactions = [create_reaction(instance, data[\"parameter\"]) for _, instance in data[\"reaction\"].iterrows()]\n\nports = []\n\n\ndef create_model(target_dir):\n return creator.create_model(\n modules=['models.kidney.model_kidney'],\n target_dir=target_dir,\n create_report=True\n )\n\n","sub_path":"models/kidney/model_kidney.py","file_name":"model_kidney.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"140347420","text":"from app.command.command import Command\nfrom app.service.shield_service import ShieldService\n\n\nclass SonicCommand(Command):\n def __init__(self):\n super().__init__('sonic')\n self.shield = ShieldService()\n\n async def turn(self, params):\n degree = params['degree']\n self.shield.set_sonic_direction(degree)\n","sub_path":"app/command/sonic_command.py","file_name":"sonic_command.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"534416826","text":"from tkinter import *\n\n\n#variables de stylo\ntitle_size_font = 16\ncontent_size_font = 12\ncolor_theme = \"snow\"\ncolor_button_w = \"firebrick1\"\ncolor_text_button_w = \"gray12\"\nfont = \"Garuda\"\ncolor_font_activate_button_w = \"gray8\"\ncolor_bg_activate_button_w = \"firebrick3\"\n\ncolor_button = \"deepskyblue3\"\ncolor_text_button = \"gray99\"\nfont = \"Garuda\"\ncolor_font_activate_button = \"gray25\"\ncolor_bg_activate_button = \"deep sky Blue\"\n\nresponse = \"hola\"\n\ndef kill_error(list_error,root):\n root1 = Tk()\n root1.title(\"Error\")\n root1.minsize (800, 480)\n\n root1.attributes(\"-type\",\"splash\")\n root1.attributes(\"-zoomed\", True)\n root1.fullScreenState = True\n root1.attributes('-fullscreen')\n root1.focus_force()\n root1.resizable(0,0)\n \n root1.config(bg =color_theme)\n\n frame = Frame(root1, pady = 15,padx = 15,bg = color_theme )\n Label(frame,text = \"Error detectado: \",font = (font,content_size_font),bg = color_theme).pack()\n\n for i in range(0,len(list_error)):\n error = list_error[i]\n error = error[0:len(error)-2]\n Label(frame,text = error, font = (font,content_size_font),bg = color_theme).pack()\n print(\"error: \" + error)\n frame.pack()\n\n Button(frame, text = \"Aceptar\" , activebackground = color_bg_activate_button_w, activeforeground = color_font_activate_button_w, \n font = (font ,content_size_font),bg = color_button_w, fg = color_text_button_w, command = root1.destroy).pack()\n\n root1.mainloop()\n root.destroy()\n\n\n\n\n","sub_path":"windows_errors.py","file_name":"windows_errors.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"422113988","text":"\"\"\"Helps to understand how the data base is.\"\"\"\r\nimport os.path\r\nfrom collections import Counter\r\n\r\n\r\ndef save_ram_to_xml_result(file, filename):\r\n \"\"\"\r\n :param file: file to save.\r\n\r\n :param filename: name of xml file.\r\n\r\n :return: has not.\r\n\r\n Saves the result of RAM → XML translation.\r\n \"\"\"\r\n with open(filename, \"wb\") as f:\r\n f.write(file.toprettyxml(encoding=\"utf-8\", indent=\" \"))\r\n\r\n\r\ndef get_source_xml_file_path(filename):\r\n return os.path.join(\"source_xmls\", filename)\r\n\r\n\r\ndef get_list_of_domain_types(schema_domains):\r\n \"\"\"\r\n :param schema_domains: DBClasses.Schema().domains list.\r\n\r\n :return: unique_types: list of domains types.\r\n \"\"\"\r\n domain_type_list = list()\r\n for domain in schema_domains:\r\n domain_type_list.append(domain.type)\r\n\r\n unique_types = list()\r\n for key in Counter(domain_type_list).keys():\r\n unique_types.append(key)\r\n\r\n return unique_types\r\n","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"533217586","text":"import torch\nfrom conv_dg import Conv\nimport numpy as np\nimport sys, math\n\n\nclass CRF(torch.nn.Module):\n def __init__(self, input_dim, conv_layers, num_labels, batch_size, cuda):\n \"\"\"\n Linear chain CRF as in Assignment 2\n \"\"\"\n super(CRF, self).__init__()\n\n self.input_dim = input_dim\n self.crf_input_dim = None # Calculated inside init_params() based on Conv layer I/O dims\n self.conv_layers = conv_layers\n self.num_labels = num_labels\n self.batch_size = batch_size\n self.use_cuda = cuda\n self.device = torch.device('cuda:0' if self.use_cuda else 'cpu')\n self.conv_objects = torch.nn.ModuleList() # Stores multiple Conv objects\n self.Ks = [] # Stores multiple Conv filters\n self.W = None # CRF parameter (node potential)\n self.T = None # CRF parameter (transition weights between node pairs)\n\n def init_params(self, Ks=None, W=None, T=None): # Define trainable parameters here, should be nn.Parameter or with requires_grad=True\n if Ks is None: # Initialize default Conv filters if nothing is passed via arguments\n for conv_layer in self.conv_layers:\n self.Ks.append(torch.nn.Parameter(torch.ones(conv_layer['filter_shape'], dtype=torch.float)))\n else:\n self.Ks = Ks # Initialize Conv filters with trained filters if passed via arguments\n\n # Define input & output dims of each Conv layer & store inside self.conv_layers. Formula: OutputDim = 1 + (InputDim − F + 2P)/S\n last_output_dim = self.input_dim.copy()\n for i, conv_layer in enumerate(self.conv_layers):\n self.conv_objects.append(Conv(K=self.Ks[i], padding=conv_layer['padding'], stride=conv_layer['stride'], device=self.device)) # Instantiate a new Conv object & append in ModuleList to register\n conv_layer['input_dim'] = last_output_dim.copy()\n output_dim_height = int(1 + (conv_layer['input_dim']['height'] - conv_layer['filter_shape'][-2] + 2*conv_layer['padding'])/conv_layer['stride'])\n output_dim_width = int(1 + (conv_layer['input_dim']['width'] - conv_layer['filter_shape'][-1] + 2*conv_layer['padding'])/conv_layer['stride'])\n output_dim_flattened = output_dim_height * output_dim_width\n conv_layer['output_dim'] = {'flattened': output_dim_flattened, 'height': output_dim_height, 'width': output_dim_width}\n last_output_dim = conv_layer['output_dim'].copy()\n\n # Define W with the flattened output dim of the last Conv filter that is getting stored in self.crf_input_dim\n self.crf_input_dim = last_output_dim['flattened']\n self.W = torch.nn.Parameter(torch.zeros((self.crf_input_dim, self.num_labels), dtype=torch.float)) if W is None else W\n self.T = torch.nn.Parameter(torch.zeros((self.num_labels, self.num_labels), dtype=torch.float)) if T is None else T\n\n ### Use GPU if available\n print([m for m in self.modules()])\n if self.use_cuda:\n [m.cuda() for m in self.modules()]\n\n def get_conv_feats(self, X):\n \"\"\"\n Generate convolution features for a given word\n \"\"\"\n convfeatures = X\n for i, conv_layer in enumerate(self.conv_layers):\n convfeatures = self.conv_objects[i](convfeatures.view(convfeatures.shape[:-1] + (conv_layer['input_dim']['height'], conv_layer['input_dim']['width']))) # Extend the last dim of X, e.g. 128 to (16,8)\n convfeatures = convfeatures.view(convfeatures.shape[:-2] + (convfeatures.shape[-1] * convfeatures.shape[-2],)) # Flatten last 2 dims, e.g. (16,8) to 128\n\n return convfeatures\n\n def predict(self, X): # returns predicted sequence\n features = self.get_conv_feats(X)\n prediction = self.crf_decode(features, self.W.t(), self.T)\n return prediction\n\n def forward(self, X, labels):\n \"\"\"\n Implement the objective of CRF here.\n The input (features) to the CRF module should be convolution features.\n \"\"\"\n features = self.get_conv_feats(X)\n log_prob = CRFautograd.apply(features, labels, self.W, self.T, self.device)\n return log_prob\n\n def loss(self, log_prob, C):\n \"\"\"\n Compute the negative conditional log-likelihood of a labelling given a sequence.\n \"\"\"\n average_log_loss = -C * log_prob\n W_norm = torch.tensor([(torch.norm(Wy.float())) ** 2 for Wy in self.W.t()]).sum() / 2\n T_norm = torch.tensor([torch.sum(torch.tensor([Tij ** 2 for Tij in row])) for row in self.T]).sum() / 2\n loss = average_log_loss + W_norm + T_norm\n return loss\n\n def crf_decode(self, X_train, W, T):\n y_pred = []\n n = self.num_labels\n m = self.crf_input_dim\n\n def maxSumBottomUp(X, W, T):\n l = torch.zeros((m, n)).to(self.device)\n opts = torch.zeros((m, n)).to(self.device)\n yStar = torch.zeros(m, dtype=torch.int8).to(self.device)\n for i in range(1, m):\n for a in range(n):\n tmp = torch.zeros(n).to(self.device)\n for b in range(n):\n tmp[b] = torch.dot(X[i - 1], W[b]) + T[a, b] + l[i - 1, b]\n l[i, a] = max(tmp)\n for b in range(n):\n opts[m - 1, b] = torch.dot(X[m - 1], W[b]) + l[m - 1, b]\n MAP = max(opts[m - 1])\n yStar[m - 1] = opts[m - 1].max(0)[1]\n for i in range(m - 1, 0, -1):\n for b in range(n):\n opts[i - 1, b] = torch.dot(X[i - 1], W[b]) + T[yStar[i], b] + l[i - 1, b]\n yStar[i - 1] = opts[i - 1].max(0)[1]\n return MAP, yStar\n\n for X in X_train:\n target = torch.zeros((m, 26), dtype=torch.int8).to(self.device)\n MAP, yStar = maxSumBottomUp(X, W, T)\n for i, j in enumerate(yStar):\n target[i][j - 1] = 1\n y_pred.append(target)\n return torch.stack(y_pred)\n\n\nclass CRFautograd(torch.autograd.Function):\n @staticmethod\n def forward(ctx, X, y, W, T, device):\n l, r = CRFautograd.fwdBwdMsgs(X, y, W, T, device)\n ctx.save_for_backward(X, y, W, T, l, r)\n ctx.device = device\n return CRFautograd.compute_log_probability(X, y, W, T, l, r, device)\n\n @staticmethod\n def backward(ctx, grad_out):\n # print('Bwd called')\n X, y, W, T, l, r = ctx.saved_tensors\n device = ctx.device\n g_W, g_T, g_X = CRFautograd.compute_gradient(X, y, W, T, l, r, device)\n g_W = grad_out * g_W\n g_T = grad_out * g_T\n g_X = grad_out * g_X\n return g_X, None, g_W, g_T, None\n\n @staticmethod\n def fwdBwdMsgs(X, y, W, T, device):\n num_ex = len(X)\n num_label = len(T) # 26\n\n l = torch.zeros((num_ex, num_label, max_word_length)).to(device)\n r = torch.zeros((num_ex, num_label, max_word_length)).to(device)\n\n for ex in range(num_ex):\n word_label = torch.nonzero(y[ex])[:, 1]\n word = X[ex, :len(word_label)]\n num_letter = len(word_label)\n\n def letter_func(l):\n return l.matmul(W)\n\n score = torch.stack([letter_func(l) for i, l in enumerate(torch.unbind(word, dim=0), 0)], dim=1)\n\n l[ex, :, 0] = 0\n r[ex, :, num_letter - 1] = 0\n for i in range(1, num_letter):\n v = l[ex, :, i - 1].add(score[:, i - 1]).view(num_label, 1)\n temp = T.add(v.repeat(1, num_label))\n max_temp = torch.max(temp, dim=0)[0].view((1, num_label))\n l[ex, :, i] = torch.add(\n torch.log(torch.sum(torch.exp((temp - max_temp.repeat(num_label, 1))), dim=0)), max_temp)\n\n for i in range(num_letter - 2, -1, -1):\n v = r[ex, :, i + 1].add(score[:, i + 1]).view(num_label, 1)\n temp = T.add(v.t().repeat(num_label, 1))\n max_temp = torch.max(temp, dim=1)[0].view(num_label, 1)\n r[ex, :, i] = torch.add(\n torch.log(torch.sum(torch.exp((temp - max_temp.repeat(1, num_label))), dim=1).view(26, 1)),\n max_temp).t()\n\n return l, r\n\n @staticmethod\n def compute_log_probability(X, y, W, T, l, r, device):\n num_ex = len(X)\n f = 0\n for ex in range(num_ex):\n word_label = torch.nonzero(y[ex])[:, 1]\n word = X[ex, :len(word_label)]\n num_letter = len(word_label)\n\n def letter_func(l):\n return l.matmul(W)\n\n score = torch.stack([letter_func(l) for i, l in enumerate(torch.unbind(word, dim=0), 0)], dim=1)\n\n l_plus_score = torch.add(l[ex, :, :num_letter], score)\n r_plus_score = torch.add(r[ex, :, :num_letter], score)\n marg = torch.add(l_plus_score, r_plus_score)\n marg = marg - score\n\n t = torch.max(marg[:, 0])\n f = f - math.log(torch.sum(torch.exp((marg[:, 0] - t).float()))) - t\n for i in range(num_letter):\n lab = word_label[i]\n f = f + score[lab][i]\n if i < num_letter - 1:\n next_lab = word_label[i + 1]\n f = f + T[lab][next_lab]\n return f/num_ex\n\n @staticmethod\n def compute_gradient(X, y, W, T, l, r, device):\n num_ex = len(X)\n num_features = len(W)\n num_label = len(T) # 26\n max_word_length = X.shape[1] # 14\n g_W = torch.zeros(W.shape).to(device)\n g_T = torch.zeros(T.shape).to(device)\n g_X = torch.zeros((num_ex, max_word_length, num_features)).to(device)\n for ex in range(num_ex):\n word_label = torch.nonzero(y[ex])[:, 1]\n word = X[ex, :len(word_label)]\n num_letter = len(word_label)\n\n def letter_func(l):\n return l.matmul(W)\n\n score = torch.stack([letter_func(l) for i, l in enumerate(torch.unbind(word, dim=0), 0)], dim=1)\n\n l_plus_score = torch.add(l[ex, :, :num_letter], score)\n r_plus_score = torch.add(r[ex, :, :num_letter], score)\n marg = torch.add(l_plus_score, r_plus_score)\n marg = marg - score # because score is added twice\n marg = torch.exp((marg - torch.max(marg, dim=0)[0].repeat(num_label, 1)).float())\n marg = marg / torch.sum(marg, dim=0).repeat(num_label, 1) # Normalization\n\n for i in range(num_letter):\n lab = word_label[i]\n V = marg[:, i].view(num_label, 1)\n V_X = V.clone()\n V[lab] = V[lab] - 1\n g_W = g_W - torch.matmul(word[i].view(num_features, 1), V.t())\n g_X[ex, i, :] = (W[:, lab].view(num_features, 1) - torch.matmul(W, V_X)).t()\n if i < num_letter - 1:\n next_lab = word_label[i + 1]\n V = torch.add(T, l_plus_score[:, i].view(num_label, 1).repeat(1, num_label))\n V = torch.add(V, r_plus_score[:, i + 1].view(num_label, 1).t().repeat(num_label, 1))\n V = torch.exp((V - torch.max(V)).float())\n g_T = g_T - V / torch.sum(V)\n g_T[lab][next_lab] = g_T[lab][next_lab] + 1\n return g_W / num_ex, g_T / num_ex, g_X / num_ex\n\n","sub_path":"try/dg/gpu/crf.py","file_name":"crf.py","file_ext":"py","file_size_in_byte":11379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"615331767","text":"# Project along the x and y axis, resulting in\n# training data of only 56 units.\n# It's a lot faster and results in a much smaller model.\n# This quick and naive approach approachs 93% accuracy, can likely be improved.\n# Need to find research about this method.\n\n\n# Import our dataset\n# Validation data is kept separate from the testing data, to avoid\n# underestimating our generalization error.\nfrom keras.datasets import mnist\nimport numpy as np\n\n(X, Y), (x_test, y_test) = mnist.load_data()\nXh = np.sum(X, axis=1)\nXv = np.sum(X, axis=2)\nX = np.append(Xh, Xv, axis=1)\n\nXh_test = np.sum(x_test, axis=1)\nXv_test = np.sum(x_test, axis=2)\nx_test = np.append(Xh_test, Xv_test, axis=1)\n\n(x_train, x_valid) = X[:50000,:], X[50000:,:]\n(y_train, y_valid) = Y[:50000], Y[50000:]\n\n# Normalize our dataset\nx_train = x_train / np.amax(x_train)\nx_test = x_test / np.amax(x_test)\n\n# Convert out target data from numbers (e.g. 5) to categories (e.g. [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])\nfrom keras.utils import np_utils\ny_train = np_utils.to_categorical(y_train, 10)\ny_test = np_utils.to_categorical(y_test, 10)\ny_valid = np_utils.to_categorical(y_valid, 10)\n\n# Model architecture:\nbatch_size = 128\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers.advanced_activations import PReLU\nfrom keras import backend \nimport keras.losses\n\n\n# model is Sequential, # Input: Nonex28x28x1 tensor\nmodel = Sequential()\n\nmodel.add(Dense(256, input_dim=56))\nmodel.add(PReLU())\n\nmodel.add(Dropout(0.1))\nmodel.add(Dense(128))\nmodel.add(PReLU())\n\nmodel.add(Dropout(0.1))\nmodel.add(Dense(128))\nmodel.add(PReLU())\n\nmodel.add(Dropout(0.1))\nmodel.add(Dense(128))\nmodel.add(PReLU())\n\nmodel.add(Dropout(0.05))\nmodel.add(Dense(10, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nepochs = 20\n\nmodel.fit(\n x_train,\n y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data = (x_valid, y_valid))\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint(score)\n\nmodel.save(\"mnist_projection.h5\")\n\n\n# Maybe there's an unsupervised learning approach that can project this data into\n# it's 'most representative' encoding, which can then be used to train the model,\n# resulting in faster convergence, higher accuracy, and a smaller saved model?\n","sub_path":"mnist_handwriting_keras_projection.py","file_name":"mnist_handwriting_keras_projection.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"602873793","text":"import tensorflow as tf\nimport numpy as np\n\ntf.reset_default_graph()\n\n# Create input data\nX = np.random.randn(2, 10, 8)\n\n# The second example is of length 6 \nX[1,6:] = 0\nX_lengths = [10, 6]\n\ninput_x = tf.placeholder(tf.float32, [None, 10, 8])\n\nseq_len = tf.placeholder(tf.int32, [None])\n\ncell = tf.nn.rnn_cell.LSTMCell(num_units=64, state_is_tuple=True)\n\noutputs, states = tf.nn.bidirectional_dynamic_rnn(\n cell_fw=cell,\n cell_bw=cell,\n dtype=tf.float64,\n sequence_length=X_lengths,\n inputs=X)\n\noutput_fw, output_bw = outputs\nstates_fw, states_bw = states\n\nprint(tf.shape(output_fw))\n\n# result = tf.contrib.learn.run_n(\n# {\"output_fw\": output_fw, \"output_bw\": output_bw, \"states_fw\": states_fw, \"states_bw\": states_bw},\n# n=1,\n# feed_dict=None)\n\nfinal_output = tf.concat([output_fw, output_bw], axis=2)\nprint(tf.shape(output_bw))\nprint(tf.shape(final_output))\n\nbatch_size = tf.shape(outputs)[0]\nindex = tf.range(0, batch_size) * \\\n 10 + (seq_len - 1)\n\noutput = tf.gather(tf.reshape(\n final_output, [-1, 64 * 2]), index)\n\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as sess:\n sess.run(init) \n output_fw_, fin, out, ind = sess.run(\n [output_fw, final_output, output, index], \n feed_dict={\n input_x: X,\n seq_len: X_lengths\n }\n )\n\n print(np.shape(output_fw_))\n print(np.shape(fin))\n print(np.shape(out))\n\nprint(ind)\nprint(output_fw_)\nprint(out)\n\n\n\"\"\"\n(2, 10, 64)\n(2, 10, 64)\n(2, 64)\n(2, 64)\n\"\"\"\n\n","sub_path":"tests/test_dynamic_rnn.py","file_name":"test_dynamic_rnn.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"89754027","text":"from tecton import batch_feature_view, Input, tecton_sliding_window, transformation, const, BackfillConfig\nfrom ads.entities import user\nfrom ads.data_sources.ad_impressions import ad_impressions_batch\nfrom datetime import datetime\n\n# Counts distinct ad ids for each user and window. The timestamp\n# for the feature is the end of the window, which is set by using\n# the tecton_sliding_window transformation\n@transformation(mode='spark_sql')\ndef user_distinct_ad_count_transformation(window_input_df):\n return f'''\n SELECT\n user_uuid as user_id,\n approx_count_distinct(ad_id) as distinct_ad_count,\n window_end as timestamp\n FROM\n {window_input_df}\n GROUP BY\n user_uuid, window_end\n '''\n\n@batch_feature_view(\n inputs={'ad_impressions': Input(ad_impressions_batch, window='7d')},\n entities=[user],\n mode='pipeline',\n ttl='1d',\n batch_schedule='1d',\n online=False,\n offline=False,\n feature_start_time=datetime(2021, 4, 1),\n backfill_config=BackfillConfig(\"multiple_batch_schedule_intervals_per_job\"),\n family='ad_serving',\n tags={'release': 'production'},\n owner='david@tecton.ai',\n description='How many distinct advertisements a user has been shown in the last week'\n)\ndef user_distinct_ad_count_7d(ad_impressions):\n return user_distinct_ad_count_transformation(\n # Use tecton_sliding_transformation to create trailing 7 day time windows.\n # The slide_interval defaults to the batch_schedule (1 day).\n tecton_sliding_window(ad_impressions,\n timestamp_key=const('timestamp'),\n window_size=const('7d')))\n","sub_path":"ads/features/batch_feature_views/user_distinct_ad_count_7d.py","file_name":"user_distinct_ad_count_7d.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"309464156","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport sys, json\nfrom scipy.linalg import expm, inv\nfrom scipy.stats import chi2\nimport lib, fisher\n\ndef EM_TN(tolerance,json_out,no_print,N_counts = 'multinomial',test = False):\n # p = exp(-alfaY*t)\n # q = exp(-beta*t)\n # r = exp(-alfaR*t)\n\n # N:\n # A C G T\n # A N[0][0] N[0][1] N[0][2] N[0][3]\n # C N[1][0] N[1][1] N[1][2] N[1][3]\n # G N[2][0] N[2][1] N[2][2] N[2][3]\n # T N[3][0] N[3][1] N[3][2] N[3][3]\n\n if(N_counts == 'multinomial'):\n # Create counts matrix from a random distribution\n temp = np.random.dirichlet(np.ones(2))\n while temp[0]<0.1 or temp[1]<0.1:\n temp = np.random.dirichlet(np.ones(2))\n freq = np.array([temp[0]/2,temp[1]/2,temp[1]/2,temp[0]/2])\n\n fR = freq[0]+freq[2]\n fY = freq[1]+freq[3]\n\n t = np.random.uniform(low=0.1,high=0.3)\n rho = np.random.normal(1,0.1)\n # rho = np.random.uniform(low=0.5,high=1.5)\n R = np.random.uniform(low=max((freq[0]*freq[2]+freq[1]*freq[3])/\\\n (fR*fY),rho)+0.2, high=5.0)\n\n b = 1/(2*fR*fY*(1+R))\n aY = (fR*fY*R-freq[0]*freq[2]-freq[1]*freq[3])/(2*(1+R)*\\\n (fY*freq[0]*freq[2]*rho+fR*freq[1]*freq[3]))\n aR = rho*aY\n\n r,p,q = np.exp(-t*aR),np.exp(-t*aY),np.exp(-t*b)\n if(not test):\n print('true t,r,p,q',t,r,p,q)\n true_params = [r,p,q]\n\n S = lib.TN(freq,p,q,r)\n N_counts = np.random.multinomial(1000000,np.reshape(S,16))\n N_counts = np.reshape(N_counts,(4,4))\n else:\n N_counts = lib.readFreqMatrix(N_counts)\n\n piA = lib.initialPi(0,N_counts)\n piC = lib.initialPi(1,N_counts)\n piG = lib.initialPi(2,N_counts)\n piT = lib.initialPi(3,N_counts)\n piR = piA+piG\n piY = piC+piT\n\n # estimate initial values for p,q,r,t using TN distance formula\n p,q,r,t = lib.initialParameters(piA,piC,piG,piT,N_counts)\n params = np.array([p,q,r])\n\n iteration = 0\n max_iterations = 1000\n p_val = np.inf\n info = np.ones((3,3),dtype=float)\n logLold = -np.inf\n logLnew = 1\n log_diff = np.inf\n\n json_data = {}\n json_data['params'] = []\n\n # while (p_val > tolerance and iteration < max_iterations) or iteration < 10 :\n while (log_diff > tolerance and iteration < max_iterations) or iteration < 10 :\n\n iteration += 1\n\n #E-step\n S = lib.TN([piA,piC,piG,piT],p,q,r)\n N = N_counts/S\n s1=q*r*(N[0][0]*piA+N[2][2]*piG)\n s2=q*p*(N[1][1]*piC+N[3][3]*piT)\n s3=q*(1.0-r)/piR*((piA**2.0*N[0][0]+piG**2.0*N[2][2])+piA*piG*(N[0][2]+N[2][0]))\n s4=q*(1.0-p)/piY*((piC**2.0*N[1][1]+piT**2.0*N[3][3])+piC*piT*(N[1][3]+N[3][1]))\n s5=lib.calcS5(N,[piA,piC,piG,piT],q)\n s6=lib.calcS(0,2,[piA,piC,piG,piT],p,q,r,N)\n s7=lib.calcS(2,0,[piA,piC,piG,piT],p,q,r,N)\n s8=lib.calcS(1,3,[piA,piC,piG,piT],p,q,r,N)\n s9=lib.calcS(3,1,[piA,piC,piG,piT],p,q,r,N)\n s10=s3\n s11=s4\n\n # Fisher E-step\n s_2 = fisher.fisher_E_Step(N_counts,r,p,q,[piA,piC,piG,piT,piR,piY])\n\n #M-step\n r=s1/(s1+s3)\n p=s2/(s2+s4)\n q=(s1+s2+s3+s4)/(s1+s2+s3+s4+s5)\n piA = (s6*(-s10+s6+s7))/((s6+s7)*(-s10-s11+s6+s7+s8+s9))\n piC = (s8*(-s11+s8+s9))/((s8+s9)*(-s10-s11+s6+s7+s8+s9))\n piG = (s7*(s10-s6-s7))/((s6+s7)*(s10+s11-s6-s7-s8-s9))\n piT = (1.0-piA-piC-piG)\n piR=piA+piG\n piY=piC+piT\n\n #Calculation of R,t,rho\n R,t,rho = lib.calcParameters(piA,piC,piG,piT,p,q,r)\n logLnew = lib.logLikelihood([piA,piC,piG,piT],p,q,r,N_counts)\n\n # if (logLold > logLnew):\n # print('LOG LIKELIHOOD ERROR. Iteration ',iteration)\n # print('%d r: %.8f p: %.8f q: %.8f LogLhood: %.10f convergence: %.5e ' % \\\n # (iteration,r,p,q,logLnew,chisq))\n # print('loglikelihood diff: ',logLnew-logLold)\n # return 1\n\n theta_diff = np.array([p,q,r]) - params\n chisq = np.matmul(np.matmul(np.transpose(theta_diff),\\\n info), theta_diff)\n p_val = chi2.cdf(chisq,3)\n\n info = fisher.fisher_info(r,p,q,[piA,piC,piG,piT],[s1,s2,s3,s4,s5],\\\n s_2,N_counts)\n\n log_diff = logLnew-logLold\n logLold=logLnew\n params = np.array([p,q,r])\n\n if(not no_print):\n print('%d t:%.8f r:%.8f p:%.8f q:%.8f LogLhood:%.10f p-val:%.5e ' % \\\n (iteration,t,r,p,q,logLnew,p_val))\n\n json_data['params'].append({\"r\":r, \"p\":p, \"q\":q, \"LogLhood\":logLnew, \"p_value\":p_val})\n # end of while loop\n\n fisher_information = fisher.fisher_info(r,p,q,[piA,piC,piG,piT],[s1,s2,s3,s4,s5],s_2,N_counts)\n if(not no_print):\n print('\\nfisher information:\\n',fisher_information)\n\n # append info to output json\n json_data['chisq'] = chisq\n json_data['fisher_info'] = fisher_information.tolist()\n json_data['iterations'] = iteration\n\n # save data in json file\n with open(json_out,'w') as outfile:\n json.dump(json_data,outfile)\n\n if(test):\n diff = np.array([r,p,q]) - true_params\n x2_validation = np.matmul(np.matmul(np.transpose(diff),fisher_information), diff)\n p_val = chi2.cdf(np.matmul(np.matmul(np.transpose(diff),fisher_information), diff),3)\n\n with open('em_chi_values.csv','a+') as outputfile:\n outputfile.write(str(p_val)+\",\"+str(R)+\",\"+str(rho)+\",\"+str(freq)+\"\\n\")\n\n with open('iterations.csv','a+') as outit:\n outit.write(str(iteration)+\"\\n\")\n","sub_path":"src/TN.py","file_name":"TN.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"491885194","text":"import string\n\nLOWER = string.ascii_lowercase\nUPPER = string.ascii_uppercase\nDIGITS = string.digits\n\ndef shift(cipher, key):\n text = \"\"\n \n for sel in cipher:\n search_space = DIGITS\n if sel in LOWER:\n search_space = LOWER\n elif sel in UPPER:\n search_space = UPPER\n\n for index, char in enumerate(search_space):\n if char == sel:\n shift_count = index - key\n while shift_count >= len(search_space):\n shift_count = (key - len(search_space))\n \n text += search_space[shift_count]\n break\n\n return text\n \n \n\ncipher_text = input(\"Enter Cipher Text: \")\nkey = int(input(\"Enter Numeric Key: \"))\nplain_text = shift(cipher_text, key)\nprint(\"Plain Text: \\n\" + plain_text)\n","sub_path":"rot13Cracker.py","file_name":"rot13Cracker.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"475370570","text":"import time\nimport multiprocessing\nimport random\n\n\n\nclass PC(object):\n\n def __init__(self):\n self._Q = multiprocessing.Queue()\n\n self._p1 = multiprocessing.Process(target=self.worker, args=(\"p1\",), daemon=True)\n self._p2 = multiprocessing.Process(target=self.worker, args=(\"p2\",), daemon=True)\n self._p1.start()\n self._p2.start()\n\n\n def consume(self):\n # this blocks if Queue is empty\n # and waits until new items arrive\n return self._Q.get()\n\n\n def worker(self, name):\n while True:\n time.sleep(1)\n rnd = random.randint(0, 1000)\n print(\"worker\", name, \"put\", rnd)\n self._Q.put(rnd)\n\n\nif __name__ == \"__main__\":\n print(\"start\")\n pc = PC()\n time.sleep(5)\n for i in range(20):\n print(\"consume\", pc.consume())\n\n","sub_path":"multiprocessing_tests/produce_consume.py","file_name":"produce_consume.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"33230565","text":"from rfid.commands.factory.rfid_command import RFIDCommand\nfrom typing import Callable, List\nfrom serial import Serial\nfrom time import sleep\nfrom . constants import ERR_CODES\n\n\nclass cmd_set_frequency_user_defined(RFIDCommand):\n \"\"\" Command set frequency of CZS6147 controller.\n The baudrate will be written to persistent memory.\n\n Regions:\n 0x01 FCC\n 0x02 ETSI\n 0x03 CHN\n 0x04 user defined\n\n Freq space:\n frequency space = FreqSpace x 10KHz [default: 50]\n\n Freq quantity:\n larger than 0. Steps count. [default: 10]\n\n Freq start:\n 865.00 MHz 928.00 MHz (865000 - 928000)\n\n Example params array:\n region (user) freq space freq quantity freq start\n [4, 50, 10, 865000]\n \"\"\"\n default_timeout = 0.1\n\n def __init__(self, frequency_params: List[int]):\n self.freq_params = frequency_params\n super().__init__('78', param_data=self.freq_params)\n\n @property\n def freq_params(self) -> List[int]:\n \"\"\"\n Returns: frequency parameter list.\n \"\"\"\n return self._freq_params\n\n @freq_params.setter\n def freq_params(self, freq_params: List[int]) -> None:\n assert 4 <= freq_params[0] <= 4, \"Spectrum region must be 4 (fixed)\"\n assert 0 <= freq_params[1] <= 1000, \"Freq space must be in range 0-1000\"\n assert 1 <= freq_params[2] <= 1000, \"Freq quantity 1-1000\"\n assert 865000 <= freq_params[3] <= 928000, \"Start frequency\"\n self._freq_params = freq_params\n\n def _process_result(self, result: bytes) -> bool:\n r = self._freq_params(result)[-1][-2]\n return ERR_CODES[f'0x{r}'][1]\n\n def __call__(self, session: Serial,\n callback: Callable[[bytes], bool] = _process_result) -> list[str]:\n \"\"\"\n sends the command to the specified serial session.\n Args:\n session: Serial session\n \"\"\"\n print(f\"Tx: {self.printable_command}\")\n session.write(self.command)\n sleep(self.default_timeout)\n in_waiting = session.in_waiting\n r = session.read(in_waiting)\n print(f\"Rx: {self.printable_bytestring(r)}\")\n r = callback(self, r)\n return r\n","sub_path":"rfid/commands/cmd_set_frequency_user_defined.py","file_name":"cmd_set_frequency_user_defined.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"225932749","text":"\nstart_lr = 0.002\ndecay_steps = 2000\ndecay_rate = 0.95\ntrain_epoch = 3 \n\nbatch_size_per_tower = 16 \ngpu_number = 16\nbatch_size = batch_size_per_tower * gpu_number\n\nz_size = 100\nk_size = 3\np_max = 10\nl = 1 #lambda\nratio = 0.5\n\nG_path_3D = \"./G_model_3D/\"\nG_path_2D = \"./G_model_2D/\"\nG_model_2D = G_path_2D + \"G.ckpt\"\nG_model_3D = G_path_3D + \"G.ckpt\"\nD_model = \"./D_model/sports1m_finetuning_ucf101.model\"\n\n\n# descriminator : drop_out\n\n\n\n\n\n\n\n\n\n","sub_path":"para_model.py","file_name":"para_model.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"457380999","text":"#!/usr/bin/env python3\n#-*-coding: utf-8-*-\n\n# Version: 0.1\n# Author: Song Huang \n# License: Copyright(c) 2015 Song.Huang\n# Summary: \n\nfrom lrucache import LRUTimerCache\nfrom entity import getEntityClass \nfrom utils import unique_id\nfrom log import log\nfrom tables import EntityDescription\n\n\nimport asyncio\n\nloop = asyncio.get_event_loop()\n\n\n\nclass UserManager(LRUTimerCache):\n _EntityClass = getEntityClass('character')\n\n def __init__(self):\n super().__init__()\n\n async def load(self, user, tables):\n if hasattr(user, tables):\n attr = getattr(user, tables, None)\n _value = await attr.value(user.key())\n log.info('table {0} got. value:{1}'.format(tables, _value))\n return _value\n log.info('tables {0} not got.'.format(tables))\n return [] \n\n async def get(self, ID):\n if ID not in self:\n _user = self._EntityClass.init()\n await _user.load(ID)\n if _user.key():\n self[ID] = _user\n else:\n return None\n else:\n _user = self[ID]\n\n return _user\n\n def new(self, tables, **kwargs):\n assert tables in EntityDescription\n\n if tables == 'character':\n _user = self._EntityClass.init()\n _user.new(**kwargs)\n ID = kwargs['ID']\n self[ID] = _user\n return _user\n \n _entity = getEntityClass(tables)\n _attr = _entity.init()\n _attr.new(**kwargs)\n log.info('user.item new. instance:{0}'.format(_attr))\n return _attr\n \n async def update(self, user, tables, **kwargs):\n if 'ID' in kwargs:\n kwargs['ID'] = kwargs['ID'].decode()\n if tables == 'character':\n user.update(**kwargs)\n log.info('tables {0} update.'.format(tables))\n else:\n attr = getattr(user, tables, None)\n if not attr:\n log.exception('tables {0} not exists.'.format(tables))\n return\n _target = await attr.get(user.key(), kwargs['ID'])\n if _target:\n _target.update(**kwargs)\n log.info('tables {0} update.'.format(tables))\n else:\n log.exception('tables {0} not exists.'.format(tables))\n \n async def delete(self, user, tables, delete_id):\n attr = getattr(user, talbes, None)\n if attr:\n _the_item = await attr.get(user.key(), delete_id)\n _the_item.delete()\n log.info('table {0} record delete : {1}'.format(tables, delete_id))\n else:\n log.exception('tables {0} not exists.'.format(tables))\n\n def _test_new(self):\n _user = self.new(\n ID =unique_id(),\n name='Donne',\n sex=2)\n\n log.info('user inited. instance:{0}'.format(\n _user,\n ))\ntry:\n g_UserMgr\nexcept NameError:\n g_UserMgr = UserManager()\n\n","sub_path":"src/character/manager/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"116236022","text":"# Python's version used: 3.8.2 64 bit\nimport turtle as t\n\n# Title of the window\nt.title(\"Spirangle!\")\n# Background color\nt.bgcolor(\"black\")\n\n# Drawing the spirangle\npen = t.Turtle()\npen.color(\"cyan\")\nfor side in range(46):\n pen.forward(10 * side)\n pen.right(360 / 3)\npen.hideturtle()\n\n# This prevent the window to close after the draw is finished\nt.done()","sub_path":"Turtle/Spirangle.py","file_name":"Spirangle.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"54105106","text":"\"\"\"\nAllow deletion of data in between cypress tests\n\"\"\"\nfrom django.apps import apps\nfrom django.core.management.base import BaseCommand\nfrom opendp_apps.cypress_utils.check_setup import are_cypress_settings_in_place\nfrom opendp_apps.cypress_utils import static_vals as cystatic\nfrom opendp_apps.user.models import OpenDPUser, DataverseUser\n\nclass Command(BaseCommand):\n help = \"Deletes data for Cypress tests\"\n\n def handle(self, *args, **options):\n \"\"\"Delete data in-between Cypress tests\"\"\"\n\n # Important check!!\n if not are_cypress_settings_in_place(): # Do not remove this check\n self.stdout.write(self.style.ERROR(cystatic.MESSAGE_CLEAR_DATA_CMD_ERR))\n return\n\n models_to_clear = [('terms_of_access', ['TermsOfAccessLog']),\n ('analysis', ['AnalysisPlan', 'ReleaseInfo', 'DepositorSetupInfo']),\n ('dataset', ['UploadFileInfo', 'DataverseFileInfo', 'DataSetInfo']),\n ('dataverses', ['DataverseHandoff']),\n ('user', ['DataverseUser', 'OpenDPUser'])\n ]\n\n self.stdout.write(self.style.WARNING('Preparing to delete test data'))\n\n for app_name, model_names in models_to_clear:\n for model_name in model_names:\n if model_name == 'OpenDPUser':\n (del_cnt, _ignore) = OpenDPUser.objects \\\n .exclude(username__in=['test_user', 'dev_admin']).delete()\n self.stdout.write(self.style.SUCCESS(f\"{app_name}.{model_name} {del_cnt} instance(s) deleted.\"))\n elif model_name == 'DataverseUser':\n (del_cnt, _ignore) = DataverseUser.objects \\\n .exclude(user__username__in=['test_user', 'dev_admin']).delete()\n self.stdout.write(self.style.SUCCESS(f\"{app_name}.{model_name} {del_cnt} instance(s) deleted.\"))\n else:\n ye_model = apps.get_model(app_name, model_name)\n (del_cnt, _ignore) = ye_model.objects.all().delete()\n self.stdout.write(self.style.SUCCESS(f\"{app_name}.{model_name} {del_cnt} instance(s) deleted.\"))\n\n self.stdout.write(self.style.SUCCESS(f\">> Data deletion complete.\"))\n\n","sub_path":"server/opendp_apps/cypress_utils/management/commands/clear_test_data.py","file_name":"clear_test_data.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"177225771","text":"###############################################################################\n#bibliotecas\n\n#básicas\nimport numpy as np #n-array\nimport pandas as pd #data frame\nimport matplotlib.pyplot as plt #plot\n\n#incerteza\nimport uncertainties as unc #incerteza\nimport uncertainties.unumpy as unp #n-array com incerteza\n\n#pessoal\nimport lablib as lab #funções para lab\n\n#especial\nfrom math import pi #número pi\nfrom math import sqrt #função raiz quadrada\nfrom textwrap import dedent #remove identação de mult-string\n\n\n\n\n\n#%%\n###############################################################################\n#anotando constantes\n\n#constantes físicas\na_g = 9.8 #aceleração da gravidade\nμ_0 = 4 * pi * 10**-7 #permeabilidade do vácuo\n\n\n\n#metodo\nNUMERO_OSCILACOES = 10 #número de oscilações por medição\n\n\n\n#incerteza de resolução dos instrumentos\nRES_REGUA = 1e-3 / (2 * 6**0.5) #1.00 mm, analógico\nRES_PAQUIMETRO = 0.05e-3 / (2 * 6**0.5) #0.05 mm, analógico\nRES_BALANCA = 0.1e-6 / (2 * 3**0.5) #0.10 mg, digital\nRES_CRONOMETRO = 0.01 / (2 * 3**0.5) #0.01 s , digital\n\n\n\n#tempo de reação\naux_dist_reacao = np.array([ #distancia de queda da regua em centimetros\n 19,\n 21,\n 23\n ])\naux_dist_reacao = aux_dist_reacao * 1e-2 #converte para metros\n \n#calcula tempo de reação\nTEMPO_REACAO = sqrt(2*aux_dist_reacao.mean()/a_g)\n\n#calcula a incerteza do tempo\nINC_TEMPO = sqrt(TEMPO_REACAO**2 + RES_CRONOMETRO**2)\n\n\n\n\n\n#%%\n###############################################################################\n#funções\n\n#calcula grandezas\ndef calc_tempo_reacao(h):\n '''\n Calcula tempo de reação a partir do teste da régua\n \n a_g * t**2/2 = h\n t = sqrt(2*h/a_g)\n '''\n \n return sqrt(2*h/a_g)\n \n\n\ndef calc_momento_inercia(m, L, r):\n '''\n Calcula o momento inéricia do imã\n '''\n \n return m * (r**2/4 + L**2/12)\n\n\n\ndef calc_momento_magnetico(a, m_I, R, N):\n '''\n Calcula o momento magnético do imã\n '''\n \n return a * (4*pi**2*m_I) * (5**1.5*R)/(8*μ_0*N)\n\n\n\ndef calc_campo_terra(b, m_I, μ):\n '''\n Calcula o campo magnético da Terra\n '''\n \n return b * (4*pi**2*m_I) / μ\n\n\n\ndef calc_zero(a, b):\n return - b/a\n\n\n\n#analise de dados\ndef extrai_coeficientes(corr, freq):\n '''\n Calcula os coeficientes da linearização\n '''\n \n #extrai valor nominal e incerteza da corrente\n X = unp.nominal_values(corr)\n dX = unp.std_devs(corr)\n \n #extrai valor nominal e incerteza da frequencia**2\n Y = unp.nominal_values(freq**2)\n dY = unp.std_devs(freq**2)\n \n #aplica odr linear aos dados e anota os coeficientes da reta\n a, b = lab.odr_linear(X, Y, dX, dY)\n \n return (a, b)\n\n\n\ndef plota_dados(corr, freq, coef_a, coef_b, path):\n '''\n Plota os dados experimentais e a regressão linear\n '''\n \n #trata dados\n x = unp.nominal_values(corr)\n y = unp.nominal_values(freq**2)\n dy = unp.std_devs(freq**2)\n \n a = unp.nominal_values(coef_a)\n b = unp.nominal_values(coef_b)\n \n #plota regressão\n plt.plot(\n x * 1e3,\n a*x + b,\n '-b',\n label = 'regressão linear'\n )\n \n #plota dados\n plt.errorbar(\n x * 1e3,\n y,\n dy,\n fmt = '.k',\n label = 'Dados experimentais'\n )\n \n #meta dados\n plt.title('Gráfico $f^2$ x $i$')\n plt.xlabel('Corrente $[mA]$')\n plt.ylabel('frequência$^2$ $[Hz^2]$')\n plt.legend()\n \n #salva e printa o grafico\n plt.savefig(path)\n plt.show()\n\n \n\ndef plota_dados(corr, freq, coef_a, coef_b):\n x = unp.nominal_values(corr)\n y = unp.nominal_values(freq**2)\n dy = unp.std_devs(freq**2)\n \n a = unp.nominal_values(coef_a)\n b = unp.nominal_values(coef_b)\n\n #plota regressão\n plt.plot(\n x * 1e3,\n a*x + b,\n '-b'\n )\n\n #plota dados\n plt.errorbar(\n x * 1e3,\n y,\n dy,\n fmt = '.k'\n )\n\n#%%\n###############################################################################\n#anotando valores\n\n#bobina\nbobina_sep = unc.ufloat( #separação: 108.2 mm ± RES_PAQUIMETRO\n 108.2e-3,\n RES_PAQUIMETRO\n )\n\nbobina_diam = unc.ufloat( #diametro: 19.7 cm ± RES_REGUA\n 19.7e-2,\n RES_REGUA\n )\n\nbobina_res = unc.ufloat( #resistência: 5.4 ± ? Ω\n 5.4,\n lab.incerteza_ohmimetro(5.4)\n )\n\nbobina_N = 140 #número de espiras: 140\n\n\n\n#imã\nima_comp = unc.ufloat( #comprimento: 25.20 mm ± RES_PAQUIMETRO\n 25.20e-3,\n RES_PAQUIMETRO\n )\n\nima_diam = unc.ufloat( #diâmetro: 6.00 mm ± RES_PAQUIMETRO\n 6.00e-3,\n RES_PAQUIMETRO\n )\n\nima_mas = unc.ufloat( #massa: 5.1532 mg ± RES_BALANCA\n 5.1532e-3,\n RES_BALANCA\n )\n\n\n\n#resistor\nresistor_res = unc.ufloat( #resistência: 82.4 ± ? Ω\n 82.4,\n lab.incerteza_ohmimetro(82.4)\n )\n\n\n\n\n\n#%%\n###############################################################################\n#anotando dados\n\n#para correntes positivas\naux_pos_med = np.array([ #período * NUMERO_OSCILACOES em segundos\n [11.81, 11.72, 11.59, 11.59, 11.56, 11.56, 11.75, 11.75],\n [ 9.78, 9.65, 9.75, 9.81, 9.71, 9.63, 9.59, 9.91],\n [ 8.41, 8.47, 8.44, 8.40, 8.25, 8.47, 8.38, 8.56],\n [ 7.56, 7.62, 7.47, 7.69, 7.60, 7.68, 7.66, 7.62],\n [ 6.87, 6.87, 6.94, 6.91, 6.87, 6.85, 6.97, 6.78],\n [ 6.37, 6.38, 6.41, 6.41, 6.37, 6.37, 6.25, 6.35],\n [ 5.90, 5.94, 5.93, 5.91, 5.84, 6.00, 5.93, 5.85],\n [ 5.60, 5.53, 5.59, 5.65, 5.75, 5.63, 5.53, 5.59],\n [ 5.35, 5.35, 5.31, 5.15, 5.29, 5.22, 5.28, 5.25],\n [ 5.10, 5.03, 5.13, 5.06, 5.03, 4.94, 5.07, 5.16],\n [ 4.87, 4.91, 4.85, 4.84, 4.84, 4.91, 4.82, 4.75],\n [ 4.62, 4.66, 4.66, 4.59, 4.63, 4.62, 4.63, 4.69],\n [ 4.53, 4.44, 4.40, 4.53, 4.44, 4.37, 4.38, 4.41],\n [ 4.25, 4.37, 4.59, 4.41, 4.32, 4.25, 4.31, 4.38]\n ])\n \naux_pos_corr = np.array([ #corrente em mA\n 22.01,\n 38.02,\n 54.19,\n 68.00,\n 82.80,\n 98.20,\n 116.5,\n 130.6,\n 147.4,\n 164.2,\n 180.0,\n 196.6,\n 213.9,\n 230.1\n ])\naux_pos_corr = aux_pos_corr * 1e-3 #converte para amperes\n \n \n \n#para correntes negativas\naux_neg_med = np.array([ #período * NUMERO_OSCILACOES\n [20.03, 19.91, 19.53, 19.69, 19.88],\n [12.91, 12.86, 12.97, 12.90, 12.88],\n [10.25, 10.15, 10.21, 10.21, 10.19],\n [ 8.69, 8.81, 8.79, 8.66, 8.69],\n [ 7.72, 7.66, 7.63, 7.60, 7.75],\n [ 7.10, 6.91, 6.97, 7.15, 7.00],\n [ 6.66, 6.63, 6.57, 6.60, 6.53],\n [ 6.22, 6.04, 6.16, 6.15, 6.09],\n [ 5.72, 5.66, 5.72, 5.75, 5.66],\n [ 5.40, 5.40, 5.41, 5.37, 5.37],\n [ 5.16, 5.16, 5.28, 5.13, 5.31],\n [ 5.07, 4.94, 4.90, 5.00, 5.00],\n [ 4.62, 4.72, 4.69, 4.66, 4.66],\n [ 4.59, 4.53, 4.56, 4.46, 4.59],\n ])\n \naux_neg_corr = np.array([ #corrente em mA\n -22.45,\n -37.51,\n -53.54,\n -69.70,\n -85.70,\n -101.3,\n -111.4,\n -128.4,\n -145.9,\n -162.2,\n -177.2,\n -193.8,\n -211.5,\n -225.6\n ])\naux_neg_corr = aux_neg_corr * 1e-3 #converte para amperes\n\n\n\n#tensão (a mesma para ambos os casos)\naux_volt = np.array([ #tensão em volt\n 2.0 ,\n 3.5 ,\n 5.0 ,\n 6.5 ,\n 8.0 ,\n 9.5 ,\n 11.0,\n 12.5,\n 14.0,\n 15.5,\n 17.0,\n 18.5,\n 20.0,\n 21.5\n ]) \n \n \n\n\n \n#%%\n###############################################################################\n#pré tratamento\n\n#inclui incerteza na medição\naux_volt = unp.uarray(\n aux_volt,\n lab.incerteza_voltimetro(aux_volt)\n )\n\n\n\n#para correntes positivas\n#inclui incertezas na medição\naux_pos_med = unp.umatrix(\n aux_pos_med,\n INC_TEMPO\n )\n\naux_pos_corr = unp.uarray(\n aux_pos_corr,\n lab.incerteza_amperimetro(aux_pos_corr)\n )\n\n#calcula período\naux_pos_per = aux_pos_med.mean(axis = 1) / NUMERO_OSCILACOES\n\n#transforma em array\naux_pos_per = np.array(aux_pos_per).ravel()\n\n#cria data frame\npositivo = pd.DataFrame(\n #dados\n data = {\n 'tensao' : aux_volt, \n 'corrente' : aux_pos_corr,\n 'frequencia' : 1 / aux_pos_per\n },\n\n #ordem das colunas\n columns = [\n 'tensao',\n 'corrente',\n 'frequencia'\n ]\n )\n\n\n\n#para correntes negativas\n#inclui incertezas na medição\naux_neg_med = unp.umatrix(\n aux_neg_med,\n INC_TEMPO\n )\n\naux_neg_corr = unp.uarray(\n aux_neg_corr,\n lab.incerteza_amperimetro(aux_neg_corr)\n )\n\n#calcula período\naux_neg_per = aux_neg_med.mean(axis = 1) / NUMERO_OSCILACOES\n\n#transforma em array\naux_neg_per = np.array(aux_neg_per).ravel()\n\n#cria data frame\nnegativo = pd.DataFrame(\n #dados\n data = {\n 'tensao' : aux_volt, \n 'corrente' : aux_neg_corr,\n 'frequencia' : 1 / aux_neg_per\n },\n\n #ordem das colunas\n columns = [\n 'tensao',\n 'corrente',\n 'frequencia'\n ]\n )\n\n\n\n\n\n#%%\n###############################################################################\n#calculando valores\n\n#imã\nima_m_I = calc_momento_inercia( #calcula momento de inércia do imã (cilindro)\n ima_mas, #massa\n ima_comp, #comprimento\n ima_diam / 2 #raio\n )\n\n\n\n#positivo\n#extrai coeficientes da linearização\npos_a, pos_b = extrai_coeficientes(\n positivo['corrente'],\n positivo['frequencia']\n )\n\n#negativo\n#extrai coeficientes da linearização\nneg_a, neg_b = extrai_coeficientes(\n negativo['corrente'],\n negativo['frequencia']\n )\n\n\n\n#calcula momento magnetico do imã e da terra para os coeficientes\ncoef_a = np.array([pos_a, neg_a])\ncoef_b = np.array([pos_b, neg_b])\n\npos_ima_μ, neg_ima_μ = calc_momento_magnetico( #calcula momento magnético\n coef_a, #coeficientes das retas\n ima_m_I, #momento de inércia\n bobina_diam/2, #raio da bobina\n bobina_N #número de espeiras na bobina\n )\nima_μ = np.array([pos_ima_μ, neg_ima_μ])\n\npos_B_T, neg_B_T = calc_campo_terra( #calcula campo magnético da terra\n coef_b, #coeficiente b da reta\n ima_m_I, #momento de inercia do ima\n ima_μ #momento magnetico do ima\n )\nB_T = np.array([pos_B_T, neg_B_T])\n\n\n#zero da função\npos_zero = calc_zero(pos_a, pos_b)\nneg_zero = calc_zero(neg_a, neg_b)\n\n\n\n\n\n#%%\n###############################################################################\n#plotando graficos\n\n#plota dados experimentais e a regressão\nplota_dados(\n positivo['corrente'],\n positivo['frequencia'],\n coef_a[0],\n coef_b[0]\n )\n\nplota_dados(\n negativo['corrente'],\n negativo['frequencia'],\n coef_a[1],\n coef_b[1]\n )\n\n#meta dados\nplt.title('Gráfico $f^2$ x $I$')\nplt.xlabel('Corrente $[mA]$')\nplt.ylabel('frequência$^2$ $[Hz^2]$')\n\n#salva e printa o grafico\nplt.savefig('figuras/grafico_f2xi')\nplt.show()\n\n\n\n\n\n#%%\n###############################################################################\n#salvando resultados\n\n#salva os data frames\npositivo.to_csv('resultados/positivo.csv')\nnegativo.to_csv('resultados/negativo.csv')\n\n\n\n#anota resultados em um arquivo\narq = open('resultados/resultados_obtidos.txt', 'w')\narq.write(dedent(\n '''\n Bobina:\n Separação = {:.1u} [m] \n Diametro = {:.1u} [m]\n Resistencia = {:.1u} [Ω]\n\n\n Imã:\n Comprimento = {:.1u} [m]\n Diametro = {:.1u} [m]\n Massa = {:.1u} [kg]\n Momento de inércia = {:.1u} [kg m^2]\n \n \n Resistor de potência:\n Resistência = {:.1u} [Ω]\n \n \n Positivo:\n Coeficiente a = {:.1u} [???]\n Coeficiente b = {:.1u} [???]\n Momento magnético = {:.1u} [N m / T]\n Campo da Terra = {:.1u} [T]\n Corrente anula freq = {:.1u} [A]\n \n \n Negativo:\n Coeficiente a = {:.1u} [???]\n Coeficiente b = {:.1u} [???]\n Momento magnético = {:.1u} [N m / T]\n Campo da Terra = {:.1u} [T]\n Corrente anula freq = {:.1u} [A]\n '''.format(\n bobina_sep,\n bobina_diam,\n bobina_res,\n ima_comp,\n ima_diam,\n ima_mas,\n ima_m_I,\n resistor_res,\n pos_a,\n pos_b,\n pos_ima_μ,\n pos_B_T,\n pos_zero,\n neg_a,\n neg_b,\n neg_ima_μ,\n neg_B_T,\n neg_zero\n )))\narq.close()\n","sub_path":"experimento_6/relatorio/analise.py","file_name":"analise.py","file_ext":"py","file_size_in_byte":13616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"361300723","text":"#!/usr/bin/python3\n\"\"\"This script contains the FileStorage class\"\"\"\n\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass FileStorage:\n \"\"\"This class handle all the created object into a json file\n Attrs:\n __file_path (str): file name to save objects\n __objects (dict): dictionary of BaseModel objects\n classes (dict): dictionary of classes\n \"\"\"\n __file_path = 'file.json'\n __objects = {}\n classes = {'BaseModel': BaseModel, 'User': User, 'State': State,\n 'City': City, 'Amenity': Amenity, 'Place': Place,\n 'Review': Review}\n\n def all(self):\n \"\"\"\n this returns all the objects\n \"\"\"\n return self.__objects\n\n def new(self, obj):\n \"\"\"This saves a new object into the __objects variable\"\"\"\n self.__objects[type(obj).__name__+'.'+str(obj.id)] = obj\n\n def reload(self):\n \"\"\"\n This reads all the objects from the json file and\n save them into the __objects variable\n \"\"\"\n try:\n with open(FileStorage.__file_path, mode=\"r\",\n encoding=\"utf-8\") as file:\n tmp_dir = json.load(file)\n\n for k, v in tmp_dir.items():\n cls = self.classes[v['__class__']]\n self.__objects[k] = cls(**v)\n except:\n pass\n\n def save(self):\n \"\"\"\n This functions rewrite the json file with the objects from\n the __objects variable\n \"\"\"\n eldir = {}\n for k in self.__objects.keys():\n eldir[k] = self.__objects[k].to_dict()\n with open(FileStorage.__file_path, mode=\"w\", encoding=\"utf-8\") as file:\n json.dump(eldir, file)\n","sub_path":"models/engine/file_storage.py","file_name":"file_storage.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"390565392","text":"from os.path import splitext, isfile\n\nfrom moviepy.editor import (VideoFileClip,\n TextClip,\n CompositeVideoClip)\n\n# 读取字幕文件\ndef read_srt(path):\n content = \"\"\n with open(path, 'r', encoding='UTF-8') as f:\n content = f.read()\n return content\n\n\n# 字幕拆分\ndef get_sequences(content):\n sequences = content.split('\\n\\n')\n sequences = [sequence.split('\\n') for sequence in sequences]\n # 去除每一句空值\n sequences = [list(filter(None, sequence)) for sequence in sequences]\n # 去除整体空值\n return list(filter(None, sequences))\n\n\ndef strFloatTime(tempStr):\n xx = tempStr.split(':')\n hour = int(xx[0])\n minute = int(xx[1])\n second = int(xx[2].split(',')[0])\n minsecond = int(xx[2].split(',')[1])\n allTime = hour * 60 * 60 + minute * 60 + second + minsecond / 1000\n return allTime\n\n\n\nclass RealizeAddSubtitles():\n '''\n 合成字幕与视频\n myfontsize = 40\n myfont='SimHei'\n mycolor = 'red'\n '''\n\n # 修改字体大小,字体类型,字体颜色\n def __init__(self, videoFile, txtFile,myfontsize,myfont,mycolor):\n self.src_video = videoFile\n self.sentences = txtFile\n if not (isfile(self.src_video) and self.src_video.endswith(('.avi', '.mp4')) and isfile(\n self.sentences) and self.sentences.endswith('.srt')):\n print('视频仅支持avi以及mp4,字幕仅支持srt格式')\n else:\n video = VideoFileClip(self.src_video)\n # 获取视频的宽度和高度\n w, h = video.w, video.h\n # 所有字幕剪辑\n txts = []\n content = read_srt(self.sentences)\n sequences = get_sequences(content)\n\n for line in sequences:\n if len(line)<3:\n continue\n sentences = line[2]\n start = line[1].split(' --> ')[0]\n end = line[1].split(' --> ')[1]\n\n start=strFloatTime(start)\n end=strFloatTime(end)\n start, end = map(float, (start, end))\n span=end-start\n txt = (TextClip(sentences, fontsize=myfontsize,\n font=myfont, size=(w - 20, myfontsize),\n align='center', color=mycolor)\n .set_position((10, h - 150))\n .set_duration(span)\n .set_start(start))\n\n txts.append(txt)\n # 合成视频,写入文件\n video = CompositeVideoClip([video, *txts])\n fn, ext = splitext(self.src_video)\n video.write_videofile(f'{fn}_over{ext}')\n\n\n# if __name__ == '__main__':\n# '''调用方法示例'''\n# srt_path = 'yyy.srt'\n# addSubtitles = RealizeAddSubtitles('yyy.mp4', srt_path)\n\n\n\n","sub_path":"code/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"370729935","text":"#_*_ coding=utf-8 _*_\n\nfrom selenium import webdriver\nimport unittest\nfrom pages import *\n\nclass TestPages(unittest.TestCase):\n def setUp(self):\n self.driver=webdriver.Firefox()\n self.driver.maximize_window()\n self.driver.get(\"http://192.168.1.36:8080/ISS10/index.jsp\")\n\n\n def login(self):\n page=LoginPage(self.driver)\n page.enter_username().send_keys(\"ROOT\")\n page.enter_password().send_keys(\"ROOT\")\n\n page.loginbutton().click()\n\n self.assertTrue(page.check_page_loaded())\n\n \n def test_com_sort(self):\n\n self.login()\n \n page=MainPage(self.driver)\n #进入商品分类界面\n page.go_to_com_sort_page()\n \n \n\n'''\n\n def tearDown(self):\n self.driver.close()\n self.driver.quit()\n'''\n\nif __name__ == \"__main__\":\n \n unittest.main()\n","sub_path":"ISSPageObject/testpage.py","file_name":"testpage.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"577717868","text":"from tkinter import *\n\ndef processClick(event):\n canvas.delete(\"text\")\n x = event.x\n y = event.y\n canvas.create_text(x, y, text = \"(\" + str(x) + \", \" + str(y) + \")\", anchor = S, tags = \"text\")\n\n#def processUnclick(event):\n# canvas.delete(\"text\")\n\nwindow = Tk()\nwindow.title(\"마우스 위치\")\n\nw, h = 400, 400\ncanvas = Canvas(window, width = w, height = h, bg = \"white\")\ncanvas.pack()\n\ncanvas.bind(\"\", processClick)\n#canvas.bind(\"\", processUnclick)\n\nwindow.mainloop()","sub_path":"PythonProgramming/cp09/프로그래밍 연습문제(cp09)/9.13.py","file_name":"9.13.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"291805900","text":"import smtplib\n\nfrom email.mime.text import MIMEText\n\nmsg = MIMEText(\"Un simple texto para validar que funciona correctamente un post-commit\")\nmsg['Subject'] = 'Correo enviado desde hook post-commit by-python'\nmsg['From'] = 'root-master@lab.example.com'\nmsg['To'] = 'root@lab.example.com'\n\ns = smtplib.SMTP('mail.example.com')\ns.sendmail('root-master@lab.example.com', ['root@lab.example.com'], msg.as_string())\ns.quit()\n","sub_path":"mailer.py","file_name":"mailer.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"124916258","text":"import webiopi\nimport time\nimport wiringpi\n\ndef getServoDutyForWebIOPi(val):\n val_min = 0.0\n val_max = 1.0\n servo_min = 36 # 50Hz(周期20ms)、デューティ比3.5%: 3.5*1024/100=約36\n servo_max = 102 # 50Hz(周期20ms)、デューティ比10%: 10*1024/100=約102\n\n duty = int((servo_max-servo_min)*(val-val_min)/(val_max-val_min) + servo_min)\n return duty\n\nwiringpi.wiringPiSetupGpio() # GPIO名で番号指定\nwiringpi.pinMode(18, wiringpi.GPIO.PWM_OUTPUT)\nwiringpi.pinMode(19, wiringpi.GPIO.PWM_OUTPUT)\nwiringpi.pwmSetMode(wiringpi.GPIO.PWM_MODE_MS) # 周波数固定\nwiringpi.pwmSetClock(375) # 50 Hz\nwiringpi.pwmWrite(18, getServoDutyForWebIOPi(0.5))\nwiringpi.pwmWrite(19, getServoDutyForWebIOPi(0.5))\n\n# デバッグ出力を有効に\nwebiopi.setDebug()\n\n# WebIOPiの起動時に呼ばれる関数\ndef setup():\n webiopi.debug(\"Script with macros - Setup\")\n\n# WebIOPiにより繰り返される関数\ndef loop():\n webiopi.sleep(5)\n\n# WebIOPi終了時に呼ばれる関数\ndef destroy():\n webiopi.debug(\"Script with macros - Destroy\")\n\n# PWMにデューティー比をセットするためのマクロ\n# commandIDは、iOSのSafariでPOSTがキャッシュされることへの対策\n@webiopi.macro\ndef setHwPWM(servoID, duty, commandID):\n id = int(servoID)\n duty = getServoDutyForWebIOPi(float(duty))\n if id==0:\n wiringpi.pwmWrite(18, duty)\n elif id==1:\n wiringpi.pwmWrite(19, duty)\n","sub_path":"raspi1-sample/09-samples/bb/07/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"219671319","text":"import logging #logging模块时Python自带的,直接导入使用\nfrom 接口自动化.API_2.common import project_path\nfrom 接口自动化.API_2.common import TestConfig\nclass MyLog: #定义一个日志类\n def __init__(self):\n self.logger_name=TestConfig.ReadConfig(project_path.config_ini_path).get_str('log_set', 'logger_name')\n def mylog(self,level,message):\n my_logger=logging.getLogger(self.logger_name) #定义一个收集器,从配置文件中获取收集器名字\n my_logger.setLevel('INFO') #设置级别\n formatter=logging.Formatter('[%(asctime)s]-%(levelname)s-%(filename)s-%(name)s-日志信息:%(message)s') #定义一个日志输出格式,可以自己加中括号或者加些其他符号\n ch=logging.StreamHandler() #设置控制台输出渠道\n ch.setLevel('ERROR') #设置级别 当日志收集级别和输出渠道级别不一致时,取交集\n ch.setFormatter(formatter) #按formatter格式输出日志到控制台\n fh=logging.FileHandler(project_path.log_path,encoding='utf-8') #设置文件输出渠道,文件追加方式默认为a,即日志会追加到文件末尾,如果模式不是a,则会覆盖清空之前的日志,与open函数的追加是一个意思\n fh.setLevel('INFO')\n fh.setFormatter(formatter) #按formatter格式输出日志到文件\n my_logger.addHandler(ch) #my_logger这日志收集器要增加ch这个输出渠道\n my_logger.addHandler(fh)\n if level=='DEBUG':\n my_logger.debug(message)\n elif level=='INFO':\n my_logger.info(message)\n elif level =='WARNING':\n my_logger.warning(message)\n elif level == 'ERROR':\n my_logger.error(message)\n elif level == 'CRITICAL':\n my_logger.critical(message)\n my_logger.removeHandler(fh)\n my_logger.removeHandler(ch)\n def debug(self,message):\n self.mylog('DEBUG',message)\n def info(self,message):\n self.mylog('INFO',message)\n def warning(self, message):\n self.mylog('WARNING', message)\n def error(self, message):\n self.mylog('ERROR', message)\n def critical(self, message):\n self.mylog('CRITICAL', message)\nif __name__=='__main__':\n # MyLog().mylog('ERROR','停电了') #类的实例化,调用函数\n test_logger=MyLog()\n test_logger.debug('我是一个优化后的DEBUG信息')\n test_logger.error('我是一个优化后的ERROR信息')\n","sub_path":"API_2/common/test_log.py","file_name":"test_log.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"644385757","text":"import json\nfrom bs4 import BeautifulSoup\nimport requests\n\n_categories = {'http://recipes.wikia.com': {'Standard,Main Dish': '/wiki/Category:Main_Dish_Recipes',\n 'Standard,Appetizer': '/wiki/Category:Appetizer_Recipes',\n 'Standard,Side Dish': '/wiki/Category:Side_Dish_Recipes',\n 'Standard,Beverages': '/wiki/Category:Beverage_Recipes'},\n 'http://healthyrecipes.wikia.com': {'Healthy,Main Dish': '/wiki/Category:Main_Dish_Recipes',\n 'Healthy,Appetizer': '/wiki/Category:Appetizer_Recipes',\n 'Healthy,Side Dish': '/wiki/Category:Side_Dish_Recipes',\n 'Healthy,Beverage': '/wiki/Category:Beverage_Recipes',\n 'Healthy,Gluten Free': '/wiki/Category:Gluten_Free_Recipes'},\n 'http://desserts.wikia.com': {'Desserts,Cake': '/wiki/Category:Cake_Recipes',\n 'Desserts,Cheesecake': '/wiki/Category:Cheesecake_Recipes',\n 'Desserts,Pie': '/wiki/Category:Pie_Recipes',\n 'Desserts,Dessert': '/wiki/Category:Pastry_Recipes',\n 'Desserts,Gluten Free': '/wiki/Category:Cookie_Recipes'},\n }\n_recipes = []\n_baseurls = ['http://recipes.wikia.com', 'http://healthyrecipes.wikia.com', 'http://desserts.wikia.com']\n\nfor base in _baseurls:\n categ = _categories[base]\n for category in categ.keys():\n url = base + categ[category]\n response = requests.get(url, timeout=5)\n content = BeautifulSoup(response.content, 'html.parser')\n div = content.find_all('li', attrs={'class': 'category-page__member'})\n for li in div:\n try:\n href = li.find('a')['href']\n itemUrl = base + href\n _response = requests.get(itemUrl, timeout=5)\n _content = BeautifulSoup(_response.content, 'html.parser')\n img = _content.find('img', attrs={'data-image-key': True, 'data-image-name': True})\n description = _content.find('span', attrs={'id': 'Description'}).parent.find_next_sibling()\n if img is not None and description.name == 'p' and 'contributed' not in description.text.lower():\n print(li.find('a').text.strip())\n name = _content.find('h1', attrs={'class': 'page-header__title'}).text\n imgUrl = img['src']\n ul = _content.find('span', attrs={'id': 'Ingredients'}).parent.find_next('ul').find_all('li')\n ingredients = []\n directions = []\n for _li in ul:\n ingredients.append(_li.text.strip())\n ol = _content.find('span', attrs={'id': 'Directions'}).parent.find_next('ol').find_all('li')\n for _li in ol:\n directions.append(_li.text.strip())\n _tokens = str(category).split(',')\n _recipe = {\n 'name': name,\n 'image': imgUrl,\n 'description': description.text.strip().replace('\\xa0', ''),\n 'ingredients': ingredients,\n 'directions': directions,\n 'category': _tokens[0],\n 'subcategory': _tokens[1]\n }\n _recipes.append(_recipe)\n except Exception:\n pass\n\nwith open('../data/RECIPES.json', 'w') as outfile:\n json.dump(_recipes, outfile)\n","sub_path":"python/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"255451590","text":"#!/usr/bin/env python\nimport numpy as np\nimport pandas as pd\nfrom action import primitive_action, exact_action\n\n# ==== you will need to fill in metropolis_sample ====\ndef metropolis_sample(paths,tot_action,nstep=150,sigma=0.5):\n\n nslice,nptcl,ndim,nconf = paths.shape\n acceptance = 0.0\n for istep in range(nstep):\n # single slice moves\n for islice in range(nslice):\n\n # calculate action\n old_action = 0.0\n\n # make a single slice move\n new_paths = paths.copy()\n\n # recalculate action \n new_action = 0.0\n\n # accept or reject configurations\n action_change = new_action - old_action\n prob = np.exp(-action_change)\n acc_idx = prob>np.random.rand(nconf)\n paths[:,:,:,acc_idx] = new_paths[:,:,:,acc_idx]\n\n # record acceptance rate\n acceptance += np.mean(acc_idx)/nstep/nslice\n return acceptance,paths\n# ==== you will need to fill in metropolis_sample ====\n\ndef test_1d_sho(my_action,omegas=[5.,10.,15.,20.,25.],nconf=256,tau=0.05,nslice=20):\n\n nptcl = 1\n ndim = 1\n\n lam = 0.5\n beta = tau*nslice\n\n data = {'omega':[],'x2':[],'x2e':[]}\n for omega in omegas:\n paths = np.random.randn(nslice,nptcl,ndim,nconf)\n tot_action = lambda x:my_action(x,omega,lam,tau)\n\n acc,new_paths = metropolis_sample(paths,tot_action)\n print( \"Cycle finished; acceptance = {acc:3.2f}.\".format(acc=acc) )\n\n x2_val = np.mean(new_paths**2.)\n x2_err = np.std(new_paths**2.)/np.sqrt(nconf)\n data['omega'].append(omega)\n data['x2'].append(x2_val)\n data['x2e'].append(x2_err)\n\n df = pd.DataFrame(data)\n return df\n\ndef compare_with_analytic(ax,df,beta):\n # compare to reference\n def analytic_x2(omega,beta):\n \"\"\" mean square deviation of 1D SHO with unit mass \"\"\"\n return 1./(2*omega)*1./np.tanh(beta*omega/2.)\n\n xmin = df['omega'].min()\n xmax = df['omega'].max()\n finex = np.linspace(xmin,xmax,100)\n refy = [analytic_x2(x,beta) for x in finex]\n\n ax.set_xlim(xmin-1,xmax+1)\n\n ref_line = ax.plot(finex,refy,lw=2,c='k',label='analytic')\n my_line = ax.errorbar(df['omega'],df['x2'],yerr=df['x2e'],fmt='x',mew=1,label='sampled')\n return ref_line,my_line\n\nif __name__ == '__main__':\n \n tau = 0.1\n nslice = 10\n #tau = 0.05\n #nslice = 20\n beta = tau*nslice\n\n # get data\n # ==========\n dat_fname = '1d_sho.csv'\n import os\n if not os.path.isfile(dat_fname):\n df = test_1d_sho(primitive_action,tau=tau,nslice=nslice)\n df.to_csv(dat_fname)\n else:\n df = pd.read_csv(dat_fname)\n # end if\n\n dat_fname1 = '1d_sho_exact.csv'\n import os\n if not os.path.isfile(dat_fname1):\n df1 = test_1d_sho(exact_action,tau=beta,nslice=1,nconf=4096)\n df1.to_csv(dat_fname1)\n else:\n df1 = pd.read_csv(dat_fname1)\n # end if\n\n # make plot\n # ==========\n import matplotlib.pyplot as plt\n fig,ax = plt.subplots(1,1)\n ax.set_xlabel('omega',fontsize=16)\n ax.set_ylabel(r'',fontsize=16)\n\n ref_line,my_line = compare_with_analytic(ax,df,beta)\n ref_line1,my_line1 = compare_with_analytic(ax,df1,beta)\n\n ax.legend(loc='upper right'\n ,handles=[ref_line[0],my_line,my_line1]\n ,labels=['analytic','sample primitve','sample exact']\n )\n plt.show()\n\n","sub_path":"extras/PIMC/vectorized/metropolis.py","file_name":"metropolis.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"278539996","text":"import argparse, re\n\nparser = argparse.ArgumentParser()\nparser.add_argument('file' )\nargs = parser.parse_args()\n\nf = open(args.file)\nlines = f.readlines()\nf.close()\n\nv = []\nt = []\n\nfor line in lines:\n\tif re.match(\"\\*ELEMENT\\_GROUPS\", line):\n\t\tbreak\n\tif re.match(\"\\d+\\s\\d+\\.?\\d*\\s10\", line):\n\t\tv.append(re.match(\"\\d+\", line).group())\n\telif re.match(\"\\d+\\s\\d+\\.?\\d*\\s0\\s\", line):\n\t\tt.append(re.match(\"\\d+\", line).group())\n\nf = open(\"input.in\", \"w\")\n\nf.write(\"Problema: celula\\n\")\n\nf.write(\"\\n\")\nf.write(\"data_entrada\\n\")\nf.write(\"archivo1: \" + args.file + \"\\n\")\nf.write(\"opcion: 1\\n\")\nf.write(\"archivo3: sistema.dat\\n\")\nf.write(\"\"\"\nsigint: \t0.13 \t\t#condutividad de la zona intraelular\nsigext: \t0.6 \t#condutividad de la zona extra\nsigmem: \t0.0000053\t#condutividad de la membrana\npermit : \t1.0 \t#permitividad de la membrana\nPotencial: \t1.0 \t#voltaje \nFrecuencia:\t0.0 \t\t#freq del campo en MGhz\nend_data\n\n\"\"\")\n\nf.write(\"dirichV: \" + str(len(v)) + \"\\n\")\nfor p in v:\n\tf.write(str(p) + \"\\n\")\n\nf.write(\"\\n\")\n\nf.write(\"dirichT: \" + str(len(t)) + \"\\n\")\nfor p in t:\n\tf.write(str(p) + \"\\n\")\n\nf.write(\"\\n\")\nf.write(\"end_dataCC\")\nf.write(\"\\n\")\n\nf.close()\n","sub_path":"fortran/potencial_transporte/generador.py","file_name":"generador.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"94595544","text":"#!/usr/bin/env python3\n\n#Libraries and functions needed\nimport smbus\t#For using I2C bus\nimport math\t\n#import gpsd\t#For GPS Module\nimport datetime\n#from time import sleep\n#import RPi.GPIO as GPIO\n\n#Initiliazation of I2C bus\nbus = smbus.SMBus(1)\n\n#Status LED initiliazation\n#GPIO.setmode(GPIO.BCM)\n#LIGHT_PIN = 25\n\n#Device Addresses\naddress = 0x68 # Sensor I2C address\n#address_mag = 0x0c #Sensor address for magnetometer\n\n#Control Addresses\npower_mgmt_1 = 0x6b\n\n# Register address from MPU 9255 register map for Accelerometer\naccel_config = 0x1c\naccel_xout_h = 0x3b\naccel_yout_h = 0x3d\naccel_zout_h = 0x3f\n\n# Register address from MPU 9255 register map for Gyroscope\ngyro_config = 0x1b\ngyro_xout_h = 0x43\ngyro_yout_h = 0x45\ngyro_zout_h = 0x47\n\n# Register address from MPU 9255 register map for Magnetometer\n#usr_cntrl = 0x6a\n#int_pin_conf = 0x37\n#cntrl = 0x0a\n#mag_xout_l = 0x03\n#mag_yout_l = 0x05\n#mag_zout_l = 0x07\n\n\"\"\"\n\tCommon Functions to be used\n\"\"\"\n\ndef read_byte(address, adr):\n\treturn bus.read_byte_data(address, adr)\n\ndef read_word(adr):\n\thigh = bus.read_byte_data(address, adr)\n\tlow = bus.read_byte_data(address, adr+1)\n\tval = (high << 8) + low\n\treturn val\n\ndef read_word_2c(adr):\n\tval = read_word(adr)\n\tif (val >= 0x8000):\n\t\treturn -((65535 - val) + 1)\n\telse:\n\t\treturn val\n'''\ndef read_word_mag(address, adr):\n\tlow = read_byte(address, adr)\n\thigh = read_byte(address, adr+1)\n\tval = (high << 8) + low\n\treturn val\n\ndef read_word_2c_mag(address, adr):\n\tval = read_word_mag(address, adr)\n\tif (val >= 0x8000):\n\t\treturn -((65535 - val) + 1)\n\telse:\n\t\treturn val\n'''\n\"\"\"\n\tAccelerometer Data\n\"\"\"\ndef acceleromter():\n\ttry:\n\t\taccel_xout = read_word_2c(accel_xout_h) #We just need to put H byte address\n\t\taccel_yout = read_word_2c(accel_yout_h) #as we are reading the word data\n\t\taccel_zout = read_word_2c(accel_zout_h)\n\n\t\taccel_xout_scaled = accel_xout / 8192.0 #According to the sensitivity you set\n\t\taccel_yout_scaled = accel_yout / 8192.0\n\t\taccel_zout_scaled = accel_zout / 8192.0\n\t\treturn accel_xout_scaled,accel_yout_scaled,accel_zout_scaled\n\texcept Exception as e:\n\t\treturn 'accel_xout_scaled','accel_yout_scaled','accel_zout_scaled'\n\n\"\"\"\n\tGyroscope Data\n\"\"\"\ndef gyroscope():\n\ttry:\n\t\tgyro_xout = read_word_2c(gyro_xout_h) #We just need to put H byte address\n\t\tgyro_yout = read_word_2c(gyro_yout_h) #as we are reading the word data\n\t\tgyro_zout = read_word_2c(gyro_zout_h)\n\n\t\tgyro_xout_scaled = gyro_xout / 65.5 #According to the sensitivity you set\n\t\tgyro_yout_scaled = gyro_yout / 65.5\n\t\tgyro_zout_scaled = gyro_zout / 65.5\n\t\t\n\t\treturn gyro_xout_scaled, gyro_yout_scaled, gyro_zout_scaled\n\texcept Exception as e:\n\t\treturn 'gyro_xout_scaled', 'gyro_yout_scaled', 'gyro_zout_scaled'\n\n\"\"\"\n\tMagnetometer Data\n\"\"\"\n'''\ndef magnetometer():\n\ttry:\n\t\t\t\t\n\t\t#initialize the power registers to wake up sensor\n\t\tbus.write_byte_data(address, power_mgmt_1, 0)\n\t\t\n\t\t#disable master i2c mode of sensor\n\t\tbus.write_byte_data(address, usr_cntrl, 0)\n\t\t\n\t\t# enable bypass mode to read directly from magnetometer\n\t\tbus.write_byte_data(address, int_pin_conf, 2)\n\t\t\n\t\t# setup magnetic sensors for contiuously reading data\n\t\tbus.write_byte_data(address_mag, 0x0a, 18)\n\t\t\n\t\tmag_xout = read_word_2c_mag(address_mag, mag_xout_l)\n\t\tmag_yout = read_word_2c_mag(address_mag, mag_yout_l)\n\t\tmag_zout = read_word_2c_mag(address_mag, mag_zout_l)\n\n\t\tmag_xout_scaled = mag_xout * 0.6 #From data sheet, there is only\n\t\tmag_yout_scaled = mag_yout * 0.6 #one sensitivity level for \n\t\tmag_zout_scaled = mag_zout * 0.6 #Magnetometer in MPU 9255 (Multiply as described in datasheet)\n\t\t\n\t\treturn mag_xout_scaled, mag_yout_scaled, mag_zout_scaled\n\texcept Exception as e:\n\t\treturn 'mag_xout_scaled', 'mag_yout_scaled', 'mag_zout_scaled'\n\n\"\"\"\n\tGPS Data\n\"\"\"\ndef gps():\n\ttry:\n\t\t\t\n\t\t# Connect to the local gpsd\n\t\tgpsd.connect()\n\n\t\t# Get gps position\n\t\tpacket = gpsd.get_current()\n\t\t#pos = packet.position()\n\t\t[lat, lng ]=packet.position()\n\t\t\n\t\t#Available Data from the packet\n\t\t#print(packet.position())\n\t\t#print(packet.altitude())\n\t\t#print(packet.movement())\n\t\t#print(packet.speed_vertical())\n\t\t#print(packet.speed())\n\t\t#print(packet.position_precision())\n\t\t#print(packet.map_url())\n\t\t#print(packet.time())\n\t\treturn lat, lng\n\texcept\tException as e:\n\t\treturn 'lat', 'lng'\n'''\n\"\"\"\n\tData Collection and Logging Module\n\"\"\"\nString_head = \"Time\" + \"\\t\" + \\\n\t\t \"Position_lat\" +\"\\t\" + \\\n\t\t \"Position_lng\" +\"\\t\" + \\\n\t\t \"Accelerometer_x\" +\"\\t\" + \\\n\t\t \"Accelerometer_y\" +\"\\t\" + \\\n\t\t \"Accelerometer_z\" +\"\\t\" + \\\n\t\t \"Gyroscope_x\" +\"\\t\" + \\\n\t\t \"Gyroscope_y\" +\"\\t\" + \\\n\t\t \"Gyroscope_z\" +\"\\t\" + \\\n\t\t \"Magnetometer_x\" + '\\t' + \\\n\t\t \"Magnetometer_y\" + '\\t' + \\\n\t\t \"Magnetometer_z\" + '\\n'\n\n\t\n# Setting power register to start getting sesnor data\nbus.write_byte_data(address, power_mgmt_1, 0)\n# Setting Acceleration register to set the sensitivity\n# 0,8,16 and 24 for 16384,8192,4096 and 2048 sensitivity respectively\nbus.write_byte_data(address, accel_config, 8) # for +/- 4g\n# Setting gyroscope register to set the sensitivity\n# 0,8,16 and 24 for 131,65.5,32.8 and 16.4 sensitivity respectively\nbus.write_byte_data(address, gyro_config, 8)\n\ndatafile = datetime.datetime.now().strftime(\"%Y%m%d-%H%M\")\ne = open(datafile + '.txt','a',)\ne.write(String_head)\nprint (\"Start Getting data\")\nwhile True:\n\ttry:\n\t\t#PIN = 25\n\t\t#GPIO.setup(PIN, GPIO.OUT)\n\t\t#GPIO.output(PIN, False)\t\n\t\ttime = datetime.datetime.now()\n\t\t#[lat, lng] = gps()\n\t\t[Accelerometer_x, Accelerometer_y, Accelerometer_z] = acceleromter()\n\t\t[Gyroscope_x, Gyroscope_y, Gyroscope_z] = gyroscope()\n\t\t#sleep(0.005)\t#Checking Magnetometer response if wait\n\t\t#[Magnetometer_x, Magnetometer_y, Magnetometer_z] = magnetometer()\n\n\t\t'''String = \"Time:\" + \"\\t\" + str(time) +\"\\t\" + \\\n\t\t\t\t \"Position:\" + str(pos) +\"\\t\" + \\\n\t\t\t\t \"Accelerometer:\" + str(acc) +\"\\t\" + \\\n\t\t\t\t \"Gyroscope:\" + str(gyro) +\"\\t\" + \\\n\t\t\t\t \"Magnetometer:\" + str(mag) + '\\n'\n\t\t'''\n\t\t#ttime = datetime.datetime.now().strftime(\"%H:%M:%S.%f\")\n\t\t#print datetime.datetime.now()\n\t\t#ttime = datetime.date(2002, 12, 26).strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n\t\ttime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n\t\tString_body = str(time) + \"\\t\" + \\\n\t\t\t \"lat\" +\"\\t\" + \\\n\t\t\t \"lng\" +\"\\t\" + \\\n\t\t\t str(Accelerometer_x) +\"\\t\" + \\\n\t\t\t str(Accelerometer_y) +\"\\t\" + \\\n\t\t\t str(Accelerometer_z) +\"\\t\" + \\\n\t\t\t str(Gyroscope_x) +\"\\t\" + \\\n\t\t\t str(Gyroscope_y) +\"\\t\" + \\\n\t\t\t str(Gyroscope_z) +\"\\t\" + \\\n\t\t\t \"Magnetometer_x\" + '\\t' + \\\n\t\t\t \"Magnetometer_y\" + '\\t' + \\\n\t\t\t \"Magnetometer_z\" + '\\n'\n\t\te.write(String_body)\n\t\t#GPIO.setup(PIN, GPIO.OUT)\n\t\t#GPIO.output(PIN, True)\n\t\tprint ('Data is being recorded: '+ str (time))\n\t\t#sleep(0.005)\t#Wait for next iteration\n\t\t#print (String)\n\t\t#sleep(2)\n\texcept KeyboardInterrupt:\n\t\te.close()\n\t\texit()\n","sub_path":"data_logger1.py","file_name":"data_logger1.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"356004230","text":"#!/usr/bin/env python\n\ninput()\ns = input().strip()\n\ndef find_best(s1, s2):\n return s1 if len(s1) < len(s2) else s2\n\ncache = {}\n\ndef find_ans(s):\n if len(s) == 1:\n cache[s] = (s, {s:1})\n return s, {s:1}\n\n ans = s\n ansrepeat = {s:1}\n for i in range(1, len(s)):\n p1, p2 = s[:i], s[i:]\n\n p1a, p1ar = find_ans(p1)\n p2a, p2ar = find_ans(p2)\n\n ans = find_best(ans, p1a + p2a)\n\n if p1 == p2:\n ansrepeat[p1] = 2\n\n if p1 in p2ar:\n ansrepeat[p1] = p2ar[p1]+1\n\n if p1 in ansrepeat:\n ans = find_best(ans, \"%d(%s)\"%(ansrepeat[p1], p1a))\n\n cache[s] = (ans, ansrepeat)\n return cache[s]\n\nprint(find_ans(s)[0])\n","sub_path":"20131209/AM/131209_tests/swallow/solutions/nocache.py","file_name":"nocache.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"596047713","text":"import sys\nimport os\nimport glob\nimport json\nimport pandas as pd\nfrom utils import *\n\n# with open(\"coco_class_list.txt\") as f:\nwith open(\"coco_paper_names.txt\") as f:\n obj_list = f.readlines()\n## remove whitespace characters like `\\n` at the end of each line\n obj_list = [x.strip() for x in obj_list]\n\n\nfilepath=\"/home/mayank_s/codebase/others/yolo/yolov4/yolov3/results.json\"\n# filepath=\"results.json\"\n\n# create VOC format files\nbblabel=[]\njson_list = glob.glob(filepath)\nif len(json_list) == 0:\n print(\"Error: no .json files found in detection-results\")\n sys.exit()\nfor tmp_file in json_list:\n #print(tmp_file)\n # 1. create new file (VOC format)\n # with open(tmp_file.replace(\".json\", \".txt\"), \"a\") as new_f:\n data = json.load(open(tmp_file))\n for obj in data:\n # image_id; \": 54959, \"; category_id; \": 78, \"; bbox; \": [433.644, 76.958, 199.733, 113.05], \"; score; \": 0.98185},\n file_name = obj['image_id']\n conf = obj['score']\n xmin = obj['bbox'][0]\n ymin = obj['bbox'][1]\n xmax = obj['bbox'][2]+xmin\n ymax = obj['bbox'][3]+ymin\n # box_=[xmin,ymin,xmax,ymax]\n # box2=xywh2xyxy(box_)\n obj_id = obj['category_id']\n # obj_id = obj['category_id'][0]\n print(obj_id)\n if file_name==\"164\":\n print('hurrr')\n print(file_name)\n obj_name = obj_list[int(obj_id)]\n # print(obj_name)\n width=height=0\n data_label = [file_name, width, height, obj_name, obj_id,xmin, ymin, xmax, ymax, conf]\n # data_label = [file_name, width, height, object_name, xmin, ymin, xmax, ymax]\n # if not ((xmin == xmax) and (ymin == ymax)):\n bblabel.append(data_label)\n # print(file_name)\n # print()\n # else:\n # print(\"file_name\")\n\ncolumns = ['filename', 'width', 'height', 'class','obj_category','xmin', 'ymin', 'xmax', 'ymax','conf']\n\ndf = pd.DataFrame(bblabel, columns=columns)\ndf.to_csv('yolo1.csv',index=False)\n\nprint(\"Conversion completed!\")\n","sub_path":"scripts/extra/convert_coco_result_json_to_csv.py","file_name":"convert_coco_result_json_to_csv.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"262114893","text":"# add water mark on my all pdf page\nimport PyPDF2\n\ntemplate =PyPDF2.PdfFileReader(open('super.pdf','rb'))\nwatermark =PyPDF2.PdfFileReader(open('wtr.pdf','rb'))\noutput =PyPDF2.PdfFileWriter()\n\n\n#looping to all page in pdf file\nfor i in range(template.getNumPages()):\n page = template.getPage(i)\n page.mergePage(watermark.getPage(0))\n output.addPage(page)\n\n with open('wtrmrkd_output.pdf','wb') as file:\n output.write(file)\n\n\n\n\n\n\n","sub_path":"pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"176028458","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport re\nimport sys\n\n\n# In[ ]:\n\n\nfor line in sys.stdin:\n line = line.strip()\n pt = r'(1(01*0)*1|0)*'\n if re.fullmatch(pt, line):\n print(line)\n\n","sub_path":"module3/regular_exp(10).py","file_name":"regular_exp(10).py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"45957137","text":"from gym.wrappers import Monitor\nimport glob\nimport io\nimport base64\nfrom IPython.display import HTML\nfrom IPython import display as ipythondisplay\n\n# modified from https://colab.research.google.com/drive/1flu31ulJlgiRL1dnN2ir8wGh9p7Zij2t#scrollTo=TCelFzWY9MBI\n\n\ndef show_video():\n mp4list = glob.glob('/content/video/*.mp4')\n if len(mp4list) > 0:\n mp4 = mp4list[0]\n video = io.open(mp4, 'r+b').read()\n encoded = base64.b64encode(video)\n ipythondisplay.display(HTML(data=''''''.format(encoded.decode('ascii'))))\n else:\n print(\"Could not find video\")\n\n\ndef wrap_env(env):\n env = Monitor(env, '/content/video', force=True)\n return env\n","sub_path":"hw2/cs285/infrastructure/colab_utils.py","file_name":"colab_utils.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"612060910","text":"#! /usr/bin/python2.7\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\nfrom geometry_msgs.msg import Twist, PointStamped, PoseStamped\nfrom sensor_msgs.msg import PointCloud2\nimport sensor_msgs.point_cloud2 as pc2\nimport tf\nimport tf2_ros\nimport tf2_py as tf2\nfrom tf2_sensor_msgs.tf2_sensor_msgs import do_transform_cloud\nimport tf2_geometry_msgs \n#import utils\nimport time\nimport math\nimport numpy as np\nfrom std_msgs.msg import String\nimport json \n#baseMover = nav.SimpleMoveBase()\n#rospy.init_node('move_group_python', anonymous=True)\nrobot = moveit_commander.RobotCommander()\nscene = moveit_commander.PlanningSceneInterface()\nbase_vel_pub = rospy.Publisher ('/hsrb/command_velocity', Twist, queue_size=1)\npubPlacingFeedback = rospy.Publisher('/feedbackOnPlacing', String, queue_size=10,latch=True)\npubGraspingFeedback = rospy.Publisher('/feedbackOnGrasping', String, queue_size=10,latch=True)\ncompleted = False\ncompleted1 = False\ncompleted2 = False\ncompleted3 = False\npointCloud = None\ngraspPose = None\nrospy.init_node('Test')\ntf_buffer = tf2_ros.Buffer()\ntf_listener = tf2_ros.TransformListener(tf_buffer)\n\nwhile(not completed2):\n try:\n groupGripper = moveit_commander.MoveGroupCommander(\"gripper\")\n print(\"Connected to commander gripper\")\n completed2 = True\n time.sleep(1)\n except: \n print(\"Error Connecting to gripper commander\")\n time.sleep(1)\nwhile(not completed1):\n try:\n groupWholeBody = moveit_commander.MoveGroupCommander(\"whole_body\")\n completed1 = True\n print(\"Connected to commander whole_body\")\n except: \n print(\"Error Connecting to whole body commander\")\n time.sleep(1)\nwhile(not completed3):\n try:\n groupArm = moveit_commander.MoveGroupCommander(\"arm\")\n completed3 = True\n print(\"Connected to commander arm\")\n except: \n print(\"Error Connecting to arm commander\")\n time.sleep(1)\n\ndef initListenerToPointCloud():\n subscriber = rospy.Subscriber(\n '/hsrb/head_rgbd_sensor/depth_registered/rectified_points',PointCloud2 ,definePointCloud) \n\ndef initListenerToGraspingTarget():\n subscriber = rospy.Subscriber('/graspingTarget',String,graspMotion)\n \ndef initListenerToPlacingTarget():\n subscriber = rospy.Subscriber('/placingTarget',String,placeMotion)\n\ndef definePointCloud(msg):\n global pointCloud \n pointCloud = msg\n\ndef _transform_pose(self,value, from_frame, to_frame):\n listener = tf.TransformListener()\n listener.waitForTransform(from_frame, to_frame, rospy.Time(0),rospy.Duration(4.0))\n point=PointStamped()\n point.header.frame_id = from_frame\n point.header.stamp =rospy.Time(0)\n point.point.x=value[0]\n point.point.y=value[1]\n point.point.z=value[2]\n point=listener.transformPoint(to_frame,point)\n return point\n\ndef mapPoseToRobotPose(pose):\n transform = tf_buffer.lookup_transform(\"odom\",\n pose.header.frame_id, #source frame\n rospy.Time(0), #get the tf at first available time\n rospy.Duration(1.0)) #wait for 1 second\n\n pose_transformed = tf2_geometry_msgs.do_transform_pose(pose, transform)\n return pose_transformed\n\ndef robotPoseToMapPose(pose):\n transform = tf_buffer.lookup_transform(\"map\",\n pose.header.frame_id, #source frame\n rospy.Time(0), #get the tf at first available time\n rospy.Duration(1.0)) #wait for 1 second\n\n pose_transformed = tf2_geometry_msgs.do_transform_pose(pose, transform)\n return pose_transformed\n\ndef pointcloudToPlanningScene(msg):\n global pointCloud\n global completed\n msg = pointCloud\n if not completed:\n try:\n trans = tf_buffer.lookup_transform(\"map\", msg.header.frame_id,\n rospy.Time(0),\n rospy.Duration(4))\n except tf2.LookupException as ex:\n rospy.logwarn(ex)\n return\n except tf2.ExtrapolationException as ex:\n rospy.logwarn(ex)\n return\n cloud_out = do_transform_cloud(msg, trans)\n rospy.sleep(2)\n scene.remove_world_object()\n rospy.sleep(2)\n data = pc2.read_points(cloud_out, field_names = (\"x\", \"y\", \"z\", \"rgb\"), skip_nans=True)\n counter = 0\n limitCounter = 0\n limit = 3\n for value in data:\n if limitCounter == limit:\n limitCounter = 0\n p = PoseStamped()\n p.header.frame_id = robot.get_planning_frame()\n p.pose.position.x = value[0]\n p.pose.position.y = value[1]\n p.pose.position.z = value[2]\n scene.add_box(\"point\"+str(counter), p, (0.01, 0.01, 0.01))\n counter = counter + 1\n completed = True\n limitCounter = limitCounter + 1\n print(\"completed scene\") \n\ndef graspMotion(msg):\n #pointcloudToPlanningScene()\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.0)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n pose = groupWholeBody.get_current_pose()\n print(pose)\n graspPose = robotPoseToMapPose(pose)\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 1.0)\n groupGripper.go()\n groupWholeBody.set_planning_time(20)\n groupWholeBody.set_workspace([-3.0, -3.0, 3.0, 3.0])\n #groupWholeBody.set_planner_id(\"TRAC_IKKConfigDefault\")\n groupWholeBody.set_planner_id(\"RRTConnectkConfigDefault\")\n completed = False\n\n my_dict=json.loads(msg.data)\n print(my_dict)\n p = PoseStamped()\n p.header.frame_id = \"map\"\n p.pose.position.x = float(my_dict[\"x\"])\n p.pose.position.y = float(my_dict[\"y\"])\n p.pose.position.z = float(my_dict[\"z\"])+0.02\n # p.pose.position.x = 1.62\n # p.pose.position.y = 0.3\n # p.pose.position.z = 0.43\n p.pose.orientation.x =graspPose.pose.orientation.x\n p.pose.orientation.y =graspPose.pose.orientation.y\n p.pose.orientation.z =graspPose.pose.orientation.z\n p.pose.orientation.w =graspPose.pose.orientation.w\n groupWholeBody.clear_pose_targets()\n groupWholeBody.set_pose_target(mapPoseToRobotPose(p))\n groupWholeBody.set_goal_tolerance(0.01)\n plan= groupWholeBody.plan()\n groupWholeBody.execute(plan)\n end_effector_value = groupWholeBody.get_current_pose()\n print(robotPoseToMapPose(end_effector_value)) \n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.2)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n pubGraspingFeedback.publish(\"True\") \n print(\"Publishing true to /feedbackOnGrasping\")\n\ndef graspMotionTest():\n #pointcloudToPlanningScene()\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.0)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n pose = groupWholeBody.get_current_pose()\n print(pose)\n graspPose = robotPoseToMapPose(pose)\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 1.0)\n groupGripper.go()\n groupWholeBody.set_planning_time(20)\n groupWholeBody.set_workspace([-3.0, -3.0, 3.0, 3.0])\n #groupWholeBody.set_planner_id(\"TRAC_IKKConfigDefault\")\n groupWholeBody.set_planner_id(\"RRTConnectkConfigDefault\")\n completed = False\n\n #my_dict=json.loads(msg.data)\n #print(my_dict)\n p = PoseStamped()\n p.header.frame_id = \"map\"\n #p.pose.position.x = float(my_dict[\"x\"])\n #p.pose.position.y = float(my_dict[\"y\"])\n #p.pose.position.z = float(my_dict[\"z\"])+0.02\n p.pose.position.x = 1.64\n p.pose.position.y = -0.04\n p.pose.position.z = 0.44\n p.pose.orientation.x =graspPose.pose.orientation.x\n p.pose.orientation.y =graspPose.pose.orientation.y\n p.pose.orientation.z =graspPose.pose.orientation.z\n p.pose.orientation.w =graspPose.pose.orientation.w\n groupWholeBody.clear_pose_targets()\n groupWholeBody.set_pose_target(mapPoseToRobotPose(p))\n groupWholeBody.set_goal_tolerance(0.01)\n plan= groupWholeBody.plan()\n groupWholeBody.execute(plan)\n end_effector_value = groupWholeBody.get_current_pose()\n print(robotPoseToMapPose(end_effector_value)) \n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.2)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n pubGraspingFeedback.publish(\"True\") \n print(\"Publishing true to /feedbackOnGrasping\")\n\ndef placeMotion(msg):\n #pointcloudToPlanningScene()\n pose = groupWholeBody.get_current_pose()\n print(pose)\n graspPose = robotPoseToMapPose(pose)\n groupWholeBody.set_planning_time(20)\n groupWholeBody.set_workspace([-3.0, -3.0, 3.0, 3.0])\n #groupWholeBody.set_planner_id(\"TRAC_IKKConfigDefault\")\n groupWholeBody.set_planner_id(\"RRTConnectkConfigDefault\")\n completed = False\n\n my_dict=json.loads(msg.data)\n print(my_dict)\n p = PoseStamped()\n p.header.frame_id = \"map\"\n p.pose.position.x = float(my_dict[\"x\"])\n p.pose.position.y = float(my_dict[\"y\"])\n p.pose.position.z = float(my_dict[\"z\"])+0.02\n #p.pose.position.x = 1.83\n #p.pose.position.y = 0.423\n #p.pose.position.z = 0.44\n p.pose.orientation.x =graspPose.pose.orientation.x\n p.pose.orientation.y =graspPose.pose.orientation.y\n p.pose.orientation.z =graspPose.pose.orientation.z\n p.pose.orientation.w =graspPose.pose.orientation.w\n groupWholeBody.clear_pose_targets()\n groupWholeBody.set_pose_target(mapPoseToRobotPose(p))\n groupWholeBody.set_goal_tolerance(0.01)\n plan= groupWholeBody.plan()\n groupWholeBody.execute(plan)\n end_effector_value = groupWholeBody.get_current_pose()\n print(robotPoseToMapPose(end_effector_value)) \n groupGripper.set_joint_value_target(\"hand_motor_joint\", 1.0)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.1)\n groupGripper.go()\n print(\"Publishing true to /feedbackOnPlacing\")\n pubPlacingFeedback.publish(\"True\") \n\ndef placeMotionTest():\n #pointcloudToPlanningScene()\n pose = groupWholeBody.get_current_pose()\n print(pose)\n graspPose = robotPoseToMapPose(pose)\n groupWholeBody.set_planning_time(20)\n groupWholeBody.set_workspace([-3.0, -3.0, 3.0, 3.0])\n #groupWholeBody.set_planner_id(\"TRAC_IKKConfigDefault\")\n groupWholeBody.set_planner_id(\"RRTConnectkConfigDefault\")\n completed = False\n\n #my_dict=json.loads(msg.data)\n #print(my_dict)\n p = PoseStamped()\n p.header.frame_id = \"map\"\n #p.pose.position.x = float(my_dict[\"x\"])\n #p.pose.position.y = float(my_dict[\"y\"])\n #p.pose.position.z = float(my_dict[\"z\"])+0.02\n p.pose.position.x = 1.83\n p.pose.position.y = 0.423\n p.pose.position.z = 0.44\n p.pose.orientation.x =graspPose.pose.orientation.x\n p.pose.orientation.y =graspPose.pose.orientation.y\n p.pose.orientation.z =graspPose.pose.orientation.z\n p.pose.orientation.w =graspPose.pose.orientation.w\n groupWholeBody.clear_pose_targets()\n groupWholeBody.set_pose_target(mapPoseToRobotPose(p))\n groupWholeBody.set_goal_tolerance(0.01)\n plan= groupWholeBody.plan()\n groupWholeBody.execute(plan)\n end_effector_value = groupWholeBody.get_current_pose()\n print(robotPoseToMapPose(end_effector_value)) \n groupGripper.set_joint_value_target(\"hand_motor_joint\", 1.0)\n groupGripper.go()\n groupArm.set_named_target('neutral')\n groupArm.go()\n groupGripper.set_joint_value_target(\"hand_motor_joint\", 0.1)\n groupGripper.go()\n pubPlacingFeedback.publish(\"True\") \n print(\"Publishing true to /feedbackOnPlacing\")\n\nif __name__ == '__main__':\n #initListenerToPointCloud()\n initListenerToGraspingTarget()\n initListenerToPlacingTarget()\n #graspMotionTest()\n #placeMotionTest()\n try:\n rospy.spin()\n except rospy.ROSException as e:\n rospy.logerr(e)\n","sub_path":"src/manip/manipulation/src/graspingTool.py","file_name":"graspingTool.py","file_ext":"py","file_size_in_byte":12105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"81837355","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\nimport os\n\nimport unittest\nimport pytest\n\nfrom postfixman import create_app\nfrom postfixman.extensions import db\nfrom postfixman.models import Mailbox\nfrom postfixman.models import Domain\nfrom postfixman.models import Alias\nimport sqlalchemy\n\n\nclass TestConfig(object):\n # SQLALCHEMY_DATABASE_URI = \\\n # 'postgresql+psycopg2://postfixman:postfixman@localhost:5432/postfixman'\n SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'\n SQLALCHEMY_ECHO = False\n TESTING = True\n\n\nclass ModelsTestCase(unittest.TestCase):\n def setUp(self):\n self.app = create_app(config=TestConfig())\n with self.app.test_request_context():\n db.create_all()\n\n def tearDown(self):\n with self.app.test_request_context():\n db.drop_all()\n\n def test_mailbox(self):\n with self.app.test_request_context():\n domain = Domain(name='domain.tld')\n\n db.session.add(domain)\n db.session.commit()\n\n assert len(list(domain.mailboxes)) == 0\n\n mailbox = Mailbox(domain=domain,\n username='user',\n name='Real Username')\n db.session.add(mailbox)\n db.session.commit()\n\n assert mailbox.username == 'user'\n assert mailbox.fully_qualified_domain_address == 'user@domain.tld'\n\n maildir = os.path.join(self.app.config['MAIL_ROOT'],\n domain.maildir,\n mailbox.username)\n assert mailbox.maildir == maildir\n\n assert len(list(domain.mailboxes)) == 1\n assert domain.mailboxes[0].username == 'user'\n\n def test_domain(self):\n with self.app.test_request_context():\n domain = Domain(name='domain.tld')\n db.session.add(domain)\n db.session.commit()\n\n assert domain.name == 'domain.tld'\n maildir = os.path.join(self.app.config['MAIL_ROOT'],\n domain.maildir)\n assert domain.maildir == maildir\n\n def test_alias(self):\n with self.app.test_request_context():\n domain = Domain(name='domain.tld')\n mailbox = Mailbox(domain=domain,\n username='info',\n name='Realname')\n\n alias = Alias(address='contact',\n mailbox=mailbox)\n\n assert alias.address == 'contact'\n assert alias.fully_qualified_domain_address == 'contact@domain.tld'\n\n db.session.add(alias)\n db.session.commit()\n\n def test_alias_unique(self):\n with self.app.test_request_context():\n\n with pytest.raises(sqlalchemy.exc.IntegrityError):\n domain = Domain(name='domain.tld')\n mailbox = Mailbox(domain=domain,\n username='info',\n name='Realname')\n alias = Alias(mailbox=mailbox,\n address='contact')\n alias2 = Alias(mailbox=mailbox,\n address='contact')\n db.session.add(alias)\n db.session.add(alias2)\n db.session.commit()\n\n def test_user_alias(self):\n with self.app.test_request_context():\n domain = Domain(name='domain.tld')\n mailbox = Mailbox(domain=domain,\n username='user',\n name='Real Name')\n alias = Alias(mailbox=mailbox,\n address='hello')\n db.session.add(alias)\n db.session.commit()\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"501928583","text":"import xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cartopy.crs as ccrs\nfrom scipy.signal import detrend\nfrom eofs.xarray import Eof\nimport iris\nfrom eofs.multivariate.iris import MultivariateEof\nimport iris.quickplot as qplt\nfrom tempfile import TemporaryFile\nimport time\nimport gc\n\nvariable_mslp = [\"PRMSL_GDS0_MSL\",\"mslp\"]\nvariable_rh = [\"RH_GDS0_ISBL\",\"rh\"]\nvariable_spfh = [\"SPFH_GDS0_ISBL\",\"spfh\"]\npfad = \"/home/srvx11/lehre/users/a1656041/ipython/Klima1/Data/JRA-55/all_datasets\"\n#pfad = \"/home/srvx11/lehre/users/a1656041/ipython/Klima1/Data/JRA-55/mslp_daily\"\n#pfad = \"/home/srvx11/lehre/users/a1656041/ipython/Klima1/Data/Data\"\n\ndef open_df(pfad,var):\n df = xr.open_mfdataset(pfad+'*'+var+'*')\n df = df.rename({'initial_time0_hours':'time','g0_lat_1':'lat','g0_lon_2':'lon'}).drop(\"initial_time0_encoded\")\n df.coords['lon'] = (df.coords['lon'] + 180) % 360 - 180\n df = df.chunk({'time':508,'lat':29,'lon':29})\n return df\ndef pref_df(ds_prep,window_size):\n ds_prep_resample = ds_prep.resample(time='1D').mean().chunk({'time':508,'lat':29,'lon':29})\n print(\"DailyMean_fertig\")\n #ds_prep = ds_prep.chunk({'time':-1})\n ds_prep_roll = ds_prep.rolling(time=window_size, center=True).construct('window_dim')\n print(\"RollMean_fertig\")\n return ds_prep_resample,ds_prep_roll\ndef anom_df(ds_prep,ds_prep_roll):\n ds_prep_clim = ds_prep_roll.groupby('time.dayofyear').mean(dim=['window_dim','time'])\n ds_prep_std = ds_prep_roll.groupby('time.dayofyear').std(dim=xr.ALL_DIMS)\n ds_prep = ds_prep.groupby('time.dayofyear') - ds_prep_clim\n ds_prep = ds_prep.groupby('time.dayofyear') / ds_prep_std\n #ds_prep = ds_prep.chunk({'time': -1})\n return ds_prep\n\ndf_mslp = open_df(pfad,'prmsl')\ndf_mslp.rename({variable_mslp[0]:variable_mslp[1]}).drop(\"initial_time0\")#,variable_rh[0]:variable_rh[1],variable_spfh[0]:variable_spfh[1]}).drop(\"initial_time0\")\ndf_mslp_resample,df_mslp_roll = pref_df(df_mslp,21)\nprint (\"prep_df fertig\")\ndf_mslp = anom_df(df_mslp_resample,df_mslp_roll)\ndf_mslp.to_netcdf('Anomalien_mslp.nc')\ndel df_mslp,df_mslp_resample,df_mslp_roll\ngc.collect()\n\ndf_rh = open_df(pfad,'rh')\ndf_rh.rename({variable_rh[0]:variable_rh[1]}).drop(\"initial_time0\")\ndf_rh_resample,df_rh_roll = pref_df(df_rh,21)\nprint (\"prep_df fertig\")\ndf_rh = anom_df(df_rh_resample,df_rh_roll)\ndf_rh.to_netcdf('Anomalien_rh.nc')\ndel df_rh,df_rh_resample,df_rh_roll\ngc.collect()\n\ndf_spfh = open_df(pfad,'spfh')\ndf_spfh.rename({variable_spfh[0]:variable_spfh[1]}).drop(\"initial_time0\")\ndf_spfh_resample,df_spfh_roll = pref_df(df_spfh,21)\nprint (\"prep_df fertig\")\ndf_spfh = anom_df(df_spfh_resample,df_spfh_roll)\ndf_spfh.to_netcdf('Anomalien_spfh.nc')\ngc.collect()\n\ndf = xr.open_mfdataset('*.nc')\nprint(df)","sub_path":"Anomalien.py","file_name":"Anomalien.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"428838221","text":"import os, argparse\nimport pandas as pd\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--pipistrel_folder', type=str, required=True)\n parser.add_argument('--csv_target', type=str, required=True)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_args()\n pipistrel_folder = args.pipistrel_folder\n csv_target = args.csv_target\n\n classes = ['nature', 'boat']\n dic = {}\n dic['ImageId'] = []\n dic['class'] = []\n for i, cls in enumerate(classes):\n for file in os.listdir(os.path.join(pipistrel_folder, cls)):\n dic['ImageId'].append(file)\n dic['class'].append(cls)\n\n df = pd.DataFrame(data=dic)\n\n df.to_csv(csv_target)\n","sub_path":"keras-classification/pipistrel_to_df.py","file_name":"pipistrel_to_df.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"238132599","text":"\"\"\"新浪微博爬虫\n为了实现能够发表文章,需要模拟登陆\n模拟登陆中,需要提取到加密算法\n验证码通过itchat发送至微信文件助手,收到验证码后回复\n反爬机制是通过加密实现,需要完整模拟浏览器行为\n\"\"\"\n\nimport os\nimport re\nimport rsa\nimport time\nimport json\nimport base64\nimport random\nimport logging\nimport requests\nimport config\nimport urllib.parse\nimport util\nfrom binascii import b2a_hex\n\n'''JS加密用户密码,需转换为Python代码加密\nif ((me.loginType & rsa) && me.servertime && sinaSSOEncoder && sinaSSOEncoder.RSAKey) {\n request.servertime = me.servertime;\n request.nonce = me.nonce;\n request.pwencode = \"rsa2\";\n request.rsakv = me.rsakv;\n var RSAKey = new sinaSSOEncoder.RSAKey();\n RSAKey.setPublic(me.rsaPubkey, \"10001\");\n password = RSAKey.encrypt([me.servertime, me.nonce].join(\"\\t\") + \"\\n\" + password)\n} else {\n if ((me.loginType & wsse) && me.servertime && sinaSSOEncoder && sinaSSOEncoder.hex_sha1) {\n request.servertime = me.servertime;\n request.nonce = me.nonce;\n request.pwencode = \"wsse\";\n password = sinaSSOEncoder.hex_sha1(\"\" + sinaSSOEncoder.hex_sha1(sinaSSOEncoder.hex_sha1(password)) + me.servertime + me.nonce)\n }\n}'''\n\n# 图片最大数量为9张\nif config.MAX_IMAGES < 0 or config.MAX_IMAGES > 9:\n config.MAX_IMAGES = 9\n\nclass SinaWeibo:\n \"\"\"新浪微博类\"\"\"\n def __init__(self, username, password):\n \"\"\"初始化\n @ param :username: 用户账号\n @ param :password: 用户密码\n \"\"\"\n self.username = username\n self.password = password\n self._session = requests.session()\n self._session.headers['user-agent'] = util.get_rand_ua()\n self._session.get('https://login.sina.com.cn/signup/signin.php')\n\n def _pre_login(self):\n \"\"\"预登录\"\"\"\n url = 'https://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su={}'\\\n '&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.19)&_={}'.format(urllib.parse.quote(self._get_su()), int(time.time()*1000))\n try:\n res = self._session.get(url).text\n res = re.findall(r\"({.*})\", res)[0]\n self._res = json.loads(res)\n self._nonce = self._res[\"nonce\"]\n self._pubkey = self._res[\"pubkey\"]\n self._rsakv = self._res[\"rsakv\"]\n self._servertime = self._res[\"servertime\"]\n # print(self.nonce,'\\n',self.pubkey,'\\n',self.rsakv,'\\n',self.servertime)\n except Exception as error:\n logging.error(\"WeiBoLogin pre_log error: %s\", error)\n\n def _get_su(self):\n \"\"\"加密用户账号\"\"\"\n return base64.b64encode(self.username.encode()).decode()\n\n def _get_sp(self):\n \"\"\"加密用户密码\"\"\"\n publickey = rsa.PublicKey(int(self._pubkey, 16), int('10001', 16))\n message = str(self._servertime) + '\\t' + str(self._nonce) + '\\n' + str(self.password)\n return b2a_hex(rsa.encrypt(message.encode(), publickey))\n\n def _login(self, captcha_handler=None):\n \"\"\"内部调用登陆\"\"\"\n data = {\n 'entry': 'account',\n 'gateway': '1',\n 'from': 'null',\n 'savestate': '30',\n 'useticket': '0',\n 'vsnf': '1',\n 'su': self._get_su(),\n 'service': 'account',\n 'servertime': self._servertime,\n 'nonce': self._nonce,\n 'pwencode': 'rsa2',\n 'rsakv': self._rsakv,\n 'sp': self._get_sp(),\n 'sr': '1920*1080',\n 'encoding': 'UTF-8',\n 'prelt': random.randint(1, 100),\n 'url': 'https://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',\n 'returntype': 'TEXT'\n }\n\n # 验证码\n if self._res[\"showpin\"] == 1:\n url = \"http://login.sina.com.cn/cgi/pin.php?r=%d&s=0&p=%s\" % (int(time.time()), self._res[\"pcid\"])\n with open(\"./temp/captcha.png\", \"wb\") as file_out:\n file_out.write(self._session.get(url).content)\n if captcha_handler is not None:\n captcha = captcha_handler()\n else:\n captcha = input(\"请输入微博登陆验证码: \")\n data[\"pcid\"] = self._res[\"pcid\"]\n data[\"door\"] = captcha\n\n\n url = 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.19)'\n json_data = self._session.post(url, data=data).json()\n\n #判断post登录是否成功\n if json_data['retcode'] == '0':\n params = {\n 'ticket': json_data['ticket'],\n 'ssosavestate': int(time.time()),\n 'callback': 'sinaSSOController.doCrossDomainCallBack',\n 'scriptId': 'ssoscript0',\n 'client': 'ssologin.js(v1.4.19)',\n '_': int(time.time()*1000)\n }\n #二次登录网页验证\n url = 'https://passport.weibo.com/wbsso/login'\n res = self._session.get(url, params=params)\n # print(res.text)\n json_data = json.loads(re.search(r'({\"result\":.*})', res.text).group())\n #判断是否登录成功\n if json_data['result'] is True:\n # print(res.cookies.get('userinfo'))\n logging.warning('微博登陆成功: %s', json_data)\n else:\n logging.warning('微博登陆失败: %s', json_data)\n else:\n logging.warning('微博登陆成功: %s', json_data)\n try:\n self.uid = json_data['userinfo']['uniqueid']\n return True\n except:\n return False\n\n def login(self, captcha_handler=None):\n \"\"\"登陆\"\"\"\n self._pre_login()\n return self._login(captcha_handler)\n\n def send_weibo(self, wbmsg):\n \"\"\"发表微博\"\"\"\n if not isinstance(wbmsg, WeiboMessage):\n raise ValueError('wbmsg must WeiboMessage class type')\n logging.warning('wbmsg must WeiboMessage class type')\n if wbmsg.is_empty():\n logging.warning('空消息不能发表')\n return\n pids = ''\n if wbmsg.has_image():\n pids = self.upload_images(wbmsg.images)\n data = wbmsg.get_send_data(pids)\n self._session.headers[\"Referer\"] = \"http://www.weibo.com/u/%s/home?wvr=5\" % self.uid\n try:\n self._session.post(\"https://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=%d\" \n % int(time.time() * 1000), data=data)\n logging.warning('成功发送微博 [%s] !' % str(wbmsg))\n except Exception as e:\n logging.warning('失败发送微博 [%s] !' % str(wbmsg))\n\n def upload_images(self, images):\n \"\"\"获取上传图片的pid\"\"\"\n pids = \"\"\n if len(images) > config.MAX_IMAGES:\n images = images[0: config.MAX_IMAGES]\n for image in images:\n pid = self._upload_image(image)\n if pid:\n pids += \" \" + pid\n time.sleep(10)\n return pids.strip()\n\n def _upload_image(self, image_file):\n \"\"\"长传图片至新浪后台\"\"\"\n if config.ADD_WATERMARK:\n url = \"http://picupload.service.weibo.com/interface/pic_upload.php?\\\n app=miniblog&data=1&url=\" \\\n + config.WATERMARK_URL + \"&markpos=1&logo=1&nick=\" \\\n + config.WATERMARK_NIKE + \\\n \"&marks=1&mime=image/jpeg&ct=0.5079312645830214\"\n else:\n url = \"http://picupload.service.weibo.com/interface/pic_upload.php?\\\n rotate=0&app=miniblog&s=json&mime=image/jpeg&data=1&wm=\"\n\n def upload():\n # self.http.headers[\"Content-Type\"] = \"application/octet-stream\"\n try:\n with open(image_file, 'rb') as f:\n img = f.read()\n resp = self._session.post(url, data=img)\n upload_json = re.search('{.*}}', resp.text).group(0)\n result = json.loads(upload_json)\n code = result[\"code\"]\n if code == \"A00006\":\n pid = result[\"data\"][\"pics\"][\"pic_1\"][\"pid\"]\n logging.warning(\"上传图片成功: %s\" % image_file)\n return True, pid\n except Exception as e:\n logging.warning(\"上传图片失败: %s\" % image_file)\n return False, None\n return False, None\n cnt = 0\n while cnt != 3:\n suc, pid = upload()\n if suc:\n return pid\n return None\n\nclass WeiboMessage:\n \"\"\"微博消息类\"\"\"\n def __init__(self, text, images=None):\n self.text = text if text is not None else \"\"\n self.images = images\n def has_image(self):\n \"\"\"是否有图片\"\"\"\n return self.images is not None and len(self.images) > 0\n def is_empty(self):\n \"\"\"消息是否为空\"\"\"\n return len(self.text) == 0 and not self.has_image()\n def get_send_data(self, pids=''):\n \"\"\"获取发送数据\"\"\"\n data = {\n \"location\": \"v6_content_home\",\n \"appkey\": \"\",\n \"style_type\": \"1\",\n \"pic_id\": pids,\n \"text\": self.text,\n \"pdetail\": \"\",\n \"rank\": \"0\",\n \"rankid\": \"\",\n \"module\": \"stissue\",\n \"pub_type\": \"dialog\",\n \"_t\": \"0\",\n }\n return data\n\n def __str__(self):\n return \"text: \" + self.text + os.linesep + \"images: \" + str(self.images)\n\n\nif __name__ == '__main__':\n sw = SinaWeibo(config.USERNAME, config.PASSWORD)\n sw.login()\n # sw.send_weibo(WeiboMessage('Helo, World!', [config.CAPTCHA_FILE]))\n","sub_path":"weibo.py","file_name":"weibo.py","file_ext":"py","file_size_in_byte":9809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"507384561","text":"import discord\nfrom discord.ext import commands\nfrom extras import permchecks\nimport asyncio\nimport logging\nlog = logging.getLogger('dev.massmove')\n\n\nclass Massmove:\n \"\"\"Massmove users to another voice channel\"\"\"\n\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(pass_context=True)\n @permchecks.admin_or_permissions(move_members=True)\n async def massmove(self, ctx, from_channel: discord.Channel, to_channel: discord.Channel):\n \"\"\"Massmove users to another voice channel\"\"\"\n await self._massmove(ctx, from_channel, to_channel)\n\n async def _massmove(self, ctx, from_channel, to_channel):\n \"\"\"Internal function: Massmove users to another voice channel\"\"\"\n # check if channels are voice channels. Or moving will be very... interesting...\n type_from = str(from_channel.type)\n type_to = str(to_channel.type)\n if type_from == 'text':\n await self.bot.say('{} is not a valid voice channel'.format(from_channel.name))\n log.debug('SID: {}, from_channel not a voice channel'.format(from_channel.server.id))\n elif type_to == 'text':\n await self.bot.say('{} is not a valid voice channel'.format(to_channel.name))\n log.debug('SID: {}, to_channel not a voice channel'.format(to_channel.server.id))\n else:\n try:\n log.debug('Starting move on SID: {}'.format(from_channel.server.id))\n log.debug('Getting copy of current list to move')\n voice_list = list(from_channel.voice_members)\n for member in voice_list:\n await self.bot.move_member(member, to_channel)\n log.debug('Member {} moved to channel {}'.format(member.id, to_channel.id))\n await asyncio.sleep(0.05)\n except discord.Forbidden:\n await self.bot.say('I have no permission to move members.')\n except discord.HTTPException:\n await self.bot.say('A error occured. Please try again')\n\n\ndef setup(bot):\n n = Massmove(bot)\n bot.add_cog(n)","sub_path":"massmove.py","file_name":"massmove.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"613701292","text":"\"\"\"\nAoC\n\"\"\"\nimport time\nimport sys\nfrom copy import copy, deepcopy\n\nstart_secs = time.time()\nprint('')\n\n# read in input file\nl=[]\nmy_file = open(\"inp.txt\", \"r\", encoding='utf-8')\nlines = my_file.readlines()\nfor line in lines:\n l.append(line.strip())\n\narr = l[0].split(',')\narr2 = arr.copy()\narr2.sort()\nsm = int(arr2[0])\nbg = int(arr2[-1])\n\nminpos = -1\nminfuel = sys.maxsize\nfor pos in range(sm, bg+1):\n fuel = 0\n for n in arr:\n fuel += abs(int(n) - pos)\n if fuel < minfuel:\n minfuel = fuel\n minpos = pos\n\nprint(minfuel)\n\nprint('')\nend_secs = time.time()\nprint('--- ' + str(end_secs-start_secs) + ' secs ---')\n","sub_path":"2021/day07/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"310907242","text":"import struct, asyncio\r\nfrom enum import Enum\r\nfrom .asyncProto import AsyncProto\r\nfrom .subscribe_pb2 import Subscribe\r\nfrom .constants import _SUBSCRIBE\r\n\r\nclass AsyncClient(AsyncProto):\r\n def __init__(self, addr, port, cb, message_buffers, MsgType, subscriptions, loop=None):\r\n \"\"\"\r\n cb must be a function that takes a single argument and processes it\r\n\r\n Do not do long-running operations in the update function without\r\n using asynchronous methods. It will be called once for each received\r\n message, possibly multiple times a \"tick\".\r\n \"\"\"\r\n super().__init__()\r\n self.loop = loop or asyncio.get_event_loop()\r\n self.addr = addr\r\n self.port = port\r\n self.subscriptions = subscriptions\r\n self.update = cb\r\n self.MsgType = MsgType\r\n self.message_buffers = message_buffers\r\n\r\n def connect(self):\r\n coro = self.loop.create_connection(lambda: self, self.addr, self.port)\r\n\r\n # this part is a little messy I'm not sure what's up with it\r\n # I can't promise it works if the loop is already running, which would\r\n # be the case if the connection dropped and tried to reconnect\r\n # the client can always be manually restarted though, of course.\r\n if not self.loop.is_running():\r\n self.loop.run_until_complete(coro)\r\n\r\n def connection_made(self, transport):\r\n super().connection_made(transport)\r\n if len(self.subscriptions) > 0:\r\n self.subscribe(self.subscriptions, Subscribe.SUBSCRIBE)\r\n\r\n def msg_received(self, data, msg_type):\r\n if msg_type != _SUBSCRIBE:\r\n msg = self.message_buffers[self.MsgType(msg_type)]()\r\n msg.ParseFromString(data)\r\n self.update(msg, self.MsgType(msg_type))\r\n\r\n def write(self, msg, msg_type):\r\n super().write(msg, msg_type)\r\n\r\n def subscribe(self, msg_types, direction):\r\n msg = Subscribe()\r\n for msg_type in msg_types:\r\n msg.msg_types.append(msg_type.value)\r\n msg.dir = direction\r\n self.write(msg.SerializeToString(), _SUBSCRIBE)\r\n\r\n\r\n # Yay also a context manager\r\n __enter__ = connect\r\n def __exit__(self, *args):\r\n self.transport.close()\r\n","sub_path":"2017-2018/RaspPi/robomodules/comm/asyncClient.py","file_name":"asyncClient.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"357520752","text":"# -*- coding: utf-8 -*-\nimport re\nimport scrapy\nfrom ..items import EventItem, CatItem, VenueItem\nfrom slugify import slugify\n\n\nclass LocktavernSpider(scrapy.Spider):\n name = \"locktavern\"\n allowed_domains = [\"lock-tavern.com\"]\n start_urls = ['http://lock-tavern.com/event-list/']\n\n def parse(self, response):\n urls = response.xpath('//h3/a/@href').extract()\n for url in urls:\n yield scrapy.Request(url, callback=self.individual_page)\n\n def individual_page(self, response):\n title = response.xpath('//h1/text()').extract_first()\n description = response.xpath('//div[@class=\"gdlr-event-content\"]/*/text()').extract()\n description = \" \".join(description)\n price = response.xpath('//div[@class=\"event-status-wrapper\"]/span/text()').extract_first()\n date = response.xpath('//div[@class=\"gdlr-info-date gdlr-info\"]/text()').extract_first().strip()\n regex_date = re.sub(r\"^(\\d+) / (\\w+) / (\\d+)$\", r\"\\1 \\2 \\3\", date)\n time = response.xpath('//div[@class=\"gdlr-info-time gdlr-info\"]/text()').extract_first().strip()\n regex_time = re.sub(r\"^(\\d+\\.*:*\\d*)(am|pm).*$\", r\"\\1 \\2\", time).replace('.', ':')\n start_datetime = regex_date + ' ' + regex_time\n category_id = CatItem.django_model.objects.get(id=1)\n venue_id = VenueItem.django_model.objects.get(id=3)\n slug = slugify(title)\n image_urls = response.xpath('//div[@class=\"gdlr-event-content\"]//img/@src').extract_first()\n youtube = response.xpath('//body').re_first('youtube.com/(?:embed/|watch\\?v=)([A-Za-z0-9_-]+)')\n\n fields = EventItem(title=title,\n description=description,\n price=price,\n published=1,\n start_date=start_datetime,\n event_url=response.url,\n category=category_id,\n venue=venue_id,\n slug=slug,\n seo_title=title,\n seo_description=description,\n youtube=youtube,\n image_urls=[image_urls]\n )\n\n yield fields\n","sub_path":"out4free_scrapers/out4free_scrapers/spiders/locktavernsite.py","file_name":"locktavernsite.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"308544739","text":"\"\"\"\n\nModule: Breach History\nAuthor: Edward Klesel\nDate: 08/07/2018\n\nDescription: Module containing methods required for the Email Breach Checker program, which queries the\n HaveIBeenPwned API to check whether accounts created using a given email address have been breached and\n details or the users account leaked.\n\n\"\"\"\n\nimport os\nfrom Classes.cBreaches import Breach, PastBreach\nfrom Modules.breachLogging import breachLog\nimport json\n\n# Load config\nwith open('Config.json', 'r') as f:\n config = json.loads(f.read())\n\n# Define the name/path of the file containing known breaches\nknownBreachFile = config['Run']['Known Breaches']\n\n\ndef checkFile():\n\n \"\"\"\n\n Title: checkFile\n Author: Edward Klesel\n Date: 08/07/2018\n\n Description: Checks if a file with a given name exists, and creates it if it does not.\n\n \"\"\"\n\n # Checks if the file already exists\n if not os.path.isfile(knownBreachFile):\n\n # Creates a new file and writes in the column headers.\n with open(knownBreachFile, 'w') as knownBreaches:\n knownBreaches.write('email,title,breachdate,modifieddate\\n')\n breachLog('debug', 'No known breaches found. Creating list of known breaches.')\n\n\ndef checkBreach(address, breach):\n\n \"\"\"\n\n Title: checkBreach\n Author: Edward Klesel\n Date: 08/07/2018\n\n Description: Checks the file containing breaches already known to the user. Returns True if known and False if\n it's a new breach. Can also check if the breach has been modified and needs amending.\n\n\n Arguments:\n\n address A simple string containing an email address.\n\n breach Information in json format about a given breach for a given email address.\n\n newBreach A Breach object which contains information about the breach, whether it is new of not, or whether\n it needs amending.\n\n Returns:\n\n\n\n \"\"\"\n\n # Creates a new Breach object\n newBreach = Breach(address, breach)\n\n # Opens the history file in read mode\n with open(knownBreachFile, 'r') as knownBreaches:\n\n for knownBreach in knownBreaches.read().splitlines():\n\n # Creates an object representing the past breach\n pastBreach = PastBreach(knownBreach)\n\n # Checks if this breach is already known to have happened\n if pastBreach.CoreInfo == newBreach.CoreInfo:\n\n # This is not a new breach\n newBreach.Write = False\n\n # Checks if the breach has been updated since the last check\n if pastBreach.ModifiedDate == newBreach.ModifiedDate:\n\n # This breach is unchanged since the last check\n newBreach.Amend = False\n breachLog('debug', 'The ' + newBreach.Title + ' breach on ' + newBreach.BreachDate +\n ' is already in the list of known breaches.')\n\n else:\n breachLog('info', 'There has been an update to the ' + newBreach.Title + ' breach on ' + newBreach.BreachDate + ' since the last check!')\n newBreach.Amend = True\n\n # If a matching breach has been found, break the loop\n break\n\n # The breach has not been seen before\n else:\n newBreach.Write = True\n newBreach.Amend = False\n\n if newBreach.Write == True:\n breachLog('debug', newBreach.Title + ' is not in the list of known breaches.')\n\n return newBreach\n\n\ndef writeBreach(newBreach):\n\n \"\"\"\n\n Title: writeBreach\n Author: Edward Klesel\n Date: 08/07/2018\n\n Description: Takes the breach information, formats it and writes it to the file containing known breaches.\n\n\n Arguments:\n\n newBreach A Breach object containing information about a given breach for a given email address. Used to\n determine whether the breach needs to be written to file.\n\n \"\"\"\n\n # Writes the new breach to the file containing known breaches\n with open(knownBreachFile, 'a') as knownBreaches:\n knownBreaches.write(newBreach.Info + '\\n')\n breachLog('debug', 'Writing ' + newBreach.Title + ' to the list of known breaches.')\n\n\ndef amendBreach(newBreach):\n\n \"\"\"\n\n Title: amendBreach\n Author: Edward Klesel\n Date: 08/07/2018\n\n Description: Takes the breach information, formats it and edits the dateModified in the file containing\n known breaches to indicate it's been updated.\n\n\n Arguments:\n\n newBreach A Breach object containing information about a given breach for a given email address. Used to\n determine whether the breach that is in the file needs to be amended.\n\n \"\"\"\n\n # Reads the list of breaches to memory\n with open(knownBreachFile, 'r') as knownBreachesAll:\n knownBreaches = knownBreachesAll.read().splitlines()\n\n # Cycles through the list of known breaches until the Core Info matches, then changes the modified date\n with open(knownBreachFile, 'w') as knownBreachesAmend:\n for knownBreach in knownBreaches:\n\n # If this is the breach which needs amending\n if PastBreach(knownBreach).CoreInfo == newBreach.CoreInfo:\n knownBreachesAmend.write(newBreach.Info + '\\n')\n breachLog('debug', 'Amending the ' + newBreach.Title + ' breach on ' + newBreach.BreachDate + '.')\n breachLog('warning', 'The ' + newBreach.Title + ' breach on ' + newBreach.BreachDate + ' has been updated since the last check!')\n\n # If it's not, don't change anything\n else:\n knownBreachesAmend.write(knownBreach + '\\n')\n","sub_path":"Modules/breachHistory.py","file_name":"breachHistory.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"314735402","text":"import numpy as np\nimport os\n\nfrom banzai.stages import Stage\nfrom banzai import logs\n\n\nclass ThousandsTest(Stage):\n \"\"\"\n Reject any images that have 20% or more of their pixels exactly equal to 1000.\n\n Notes\n =====\n When the Sinistro camera gets into a weird state, sometimes it just produces electrical noise\n in the images. When that happens, a large fraction of the pixels are set exactly to the value\n 1000.\n \"\"\"\n # Empirically we have decided that if 20% of the image exactly equals 1000\n # something bad probably happened, so we reject the image\n THOUSANDS_THRESHOLD = 0.2\n\n def __init__(self, pipeline_context):\n super(ThousandsTest, self).__init__(pipeline_context)\n\n @property\n def group_by_keywords(self):\n return None\n\n def do_stage(self, images):\n images_to_remove = []\n for image in images:\n npixels = np.product(image.data.shape)\n fraction_1000s = float(np.sum(image.data == 1000)) / npixels\n logging_tags = logs.image_config_to_tags(image, self.group_by_keywords)\n logs.add_tag(logging_tags, 'filename', os.path.basename(image.filename))\n logs.add_tag(logging_tags, 'FRAC1000', fraction_1000s)\n logs.add_tag(logging_tags, 'threshold', self.THOUSANDS_THRESHOLD)\n has_1000s_error = fraction_1000s > self.THOUSANDS_THRESHOLD\n qc_results = {'sinistro_thousands.failed': has_1000s_error,\n 'sinistro_thousands.fraction': fraction_1000s,\n 'sinistro_thousands.threshold': self.THOUSANDS_THRESHOLD}\n if has_1000s_error:\n self.logger.error('Image is mostly 1000s. Rejecting image', extra=logging_tags)\n qc_results['rejected'] = True\n images_to_remove.append(image)\n else:\n self.logger.info('Measuring fraction of 1000s.', extra=logging_tags)\n self.save_qc_results(qc_results, image)\n for image in images_to_remove:\n images.remove(image)\n\n return images\n","sub_path":"banzai/qc/sinistro_1000s.py","file_name":"sinistro_1000s.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"109760619","text":"import json\nimport os\nfrom airflow.compat.functools import cached_property\nfrom airflow.hooks.subprocess import SubprocessHook\nfrom airflow.models.baseoperator import BaseOperator\nfrom airflow.utils.operator_helpers import context_to_airflow_vars\n\nfrom astra import log\nfrom astra.utils import deserialize, flatten\nfrom astra.operators.utils import to_callable\nfrom astra.database.astradb import Task\n\n\nclass AstraOperator(BaseOperator):\n\n template_fields = (\"task_parameters\",)\n\n def __init__(\n self, task_name, task_parameters=None, return_id_kind=\"task\", **kwargs\n ) -> None:\n super(AstraOperator, self).__init__(**kwargs)\n self.task_name = task_name\n self.task_parameters = task_parameters or {}\n self.return_id_kind = f\"{return_id_kind}\".lower()\n if self.return_id_kind not in (\"task\", \"data_product\"):\n raise ValueError(f\"return_id_kind must be either `task` or `data_product`\")\n\n def execute(self, context):\n log.info(\n f\"Creating task {self.task_name} with task_parameters {self.task_parameters}\"\n )\n executable_class = to_callable(self.task_name)\n task = executable_class(**self.task_parameters)\n\n log.info(f\"Executing\")\n task.execute()\n log.info(f\"Done\")\n\n if self.return_id_kind == \"task\":\n outputs = [task.id for task in task.context[\"tasks\"]]\n elif self.return_id_kind == \"data_product\":\n outputs = []\n for t in task.context[\"tasks\"]:\n for dp in t.output_data_products:\n outputs.append(dp.id)\n\n return outputs\n\n\nclass TaskExecutor(BaseOperator):\n\n template_fields = (\"execute_task_ids\",)\n\n def __init__(\n self,\n execute_task_ids,\n **kwargs,\n ) -> None:\n super(TaskExecutor, self).__init__(**kwargs)\n self.execute_task_ids = execute_task_ids\n return None\n\n def execute(self, context):\n\n tasks = deserialize(self.execute_task_ids, Task)\n N = len(tasks)\n\n log.info(f\"Executing {N} tasks.\")\n\n for i, task in enumerate(tasks, start=1):\n log.info(f\"Executing item {i}/{N}: {task}\")\n try:\n result = task.instance().execute()\n except:\n log.exception(f\"Exception when executing item {task}\")\n else:\n log.info(f\"Completed task {task}\")\n\n return None\n","sub_path":"python/astra/operators/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"3014581","text":"class Solution:\n def maxProfit(self, prices, fee):\n \"\"\"\n :type prices: List[int]\n :type fee: int\n :rtype: int\n \"\"\"\n result = 0\n s1 = -99999999\n for price in prices:\n tmp = result \n result = max(result , s1+price) \n s1 = max(s1, tmp-price-fee) \n return result \n","sub_path":"Solutions/[714]BestTimetoBuyandSellStockwithTransactionFee/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"317605436","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 mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n head=ListNode(0)\n current=head\n while l1 and l2:\n if l1.val<=l2.val:\n current.next=l1\n l1=l1.next\n current=current.next\n else:\n current.next=l2\n l2=l2.next\n current=current.next\n if l1:\n current.next=l1\n else:\n current.next=l2\n return head.next\n\n '''\n above iteratively\n recursively\n if not l1 or not l2:\n return l1 or l2\n elif l1.val 0:\n for c in children:\n stag =\"<%s>\" % c.tag\n data = traverse(c)\n etag =\"\" % c.tag\n tail = ''\n if c.tail != None:\n tail = c.tail\n text += stag + data + etag + tail\n return text\n\n\nif __name__ == '__main__':\n path = '/Users/matthewharrison/PycharmProjects/cuddlenuggets/PatentZephyr/src/python/etl/templates/DTD/test_xml_walk.xml'\n root = ET.ElementTree(file=path)\n c = root.find('othercit')\n\n\n\n\n","sub_path":"src/python/etl/parser/ParserUtils.py","file_name":"ParserUtils.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"405564279","text":"import urllib3\nimport csv\nfrom datetime import date, timedelta\n\ndef make_url(date):\n return \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/{}.csv\".format(date)\n\ndef get_raw_spreadsheet_data(url):\n http = urllib3.PoolManager()\n r = http.request('GET', url)\n if r.status == 200:\n return r.data.decode(\"utf-8\")\n else:\n return ''\n\ndef parse_data_to_csv(data):\n result = csv.reader(str(data).splitlines())\n parsed_lines = list(result)\n return parsed_lines\n\n\ndef extract_daily_total(csv):\n for line in csv:\n if line[3] == 'Algeria':\n return line[7]\n\ndef get_daily_total(date):\n url = make_url(date)\n raw_data = get_raw_spreadsheet_data(url)\n\n if raw_data == '':\n return -1\n\n csv = parse_data_to_csv(raw_data)\n todays_total = extract_daily_total(csv)\n return todays_total\n\ndef get_daily_totals_for_timespan(start_date,end_date):\n delta = timedelta(days=1)\n while start_date <= end_date:\n formatted_date = start_date.strftime(\"%m-%d-%Y\")\n start_date += delta\n total = get_daily_total(formatted_date)\n print(\"date: {}, total: {}\".format(formatted_date,total))\n\nstart = date(2021, 7, 20)\nend = date(2021, 8, 4)\nget_daily_totals_for_timespan(start,end)","sub_path":"algeria_coronavirus.py","file_name":"algeria_coronavirus.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"283789291","text":"import queue\n\nadjacency_matrix = dict()\n\ndef load_graph( edge_lists ) :\n for u, v in edge_lists :\n if not u in adjacency_matrix :\n adjacency_matrix[u] = dict()\n adjacency_matrix[u][v] = 1\n\ndef run_floyd() :\n for logic in adjacency_matrix.keys() :\n pq = queue.PriorityQueue()\n pq.put([0, logic])\n visited_set = set()\n dist_dict = adjacency_matrix[logic]\n adjacency_matrix[logic][logic] = 0\n while not pq.empty() :\n cur_value, cur_logic = pq.get()\n if cur_logic in visited_set :\n continue\n visited_set.add(cur_logic)\n for next_logic, value in adjacency_matrix.get(cur_logic, dict()).items():\n if not next_logic in visited_set :\n if dist_dict.get(next_logic, cur_value + value + 1) >= cur_value + value :\n dist_dict[next_logic] = cur_value + value\n pq.put([cur_value + value, next_logic])\n\ndef save_result() :\n ret_list = []\n for key1, value1 in adjacency_matrix.items() :\n for key2, value2 in value1.items() :\n ret_list.append([key1, key2, value2])\n return ret_list\n\ndef create_indirect_edge_list( edge_lists ) :\n adjacency_matrix = dict()\n load_graph( edge_lists )\n run_floyd()\n return save_result()","sub_path":"server_dir/git_graph_draw/python_floyd.py","file_name":"python_floyd.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"357719880","text":"import networkx as nx \nimport sys\nimport networkx as nx\n\nbatchid = sys.argv[1]\napkid = sys.argv[2]\n\nlib_path = '../lib/' \nsys.path.insert(0, lib_path)\n\nfrom load_lib import load_data\n\nload = load_data()\nug = load.load_graph(batchid, apkid)\nline2sentence, line2reciprocal = load.load_graph_sentence(batchid, apkid)\n\npr = nx.pagerank(ug, alpha=0.85)\n\nsortedpr = sorted(pr.items(), key = lambda x:x[1], reverse=True)\n\nfout = open(load.out_path + \"pagerank_\" + batchid + \"_\" + apkid + \".txt\", \"w\")\nfor i in range(0, 5):\n\tlineid = int(sortedpr[i][0])\n\tfout.write(str(lineid) + \"\\t\" + line2sentence[lineid] + \"\\n\")\nfout.close()\n\n\n","sub_path":"graph_ranking/pagerank.py","file_name":"pagerank.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"153002378","text":"\"\"\"assets interface\n\n Wrap base methods with constants for assets (path, etc...\n\"\"\"\n\nfrom copy import deepcopy\n\nimport backoff\n\nfrom .constants import (\n CONFIRMATION_CONFIRMED,\n CONFIRMATION_FAILED,\n CONFIRMATION_PENDING,\n CONFIRMATION_STATUS,\n)\nfrom .errors import ArchivistUnconfirmedError\nfrom .logger import LOGGER\n\nMAX_TIME = 1200\n\n\ndef __lookup_max_time():\n return MAX_TIME\n\n\ndef __backoff_handler(details):\n LOGGER.debug(\"MAX_TIME %s\", MAX_TIME)\n LOGGER.debug(\n \"Backing off {wait:0.1f} seconds afters {tries} tries \"\n \"calling function {target} with args {args} and kwargs \"\n \"{kwargs}\".format(**details)\n )\n\n\ndef __on_giveup_confirmation(details):\n identity = details[\"args\"][1]\n elapsed = details[\"elapsed\"]\n raise ArchivistUnconfirmedError(\n f\"confirmation for {identity} timed out after {elapsed} seconds\"\n )\n\n\n@backoff.on_predicate(\n backoff.expo,\n logger=LOGGER,\n max_time=__lookup_max_time,\n on_backoff=__backoff_handler,\n on_giveup=__on_giveup_confirmation,\n)\ndef wait_for_confirmation(self, identity):\n \"\"\"docstring\"\"\"\n entity = self.read(identity)\n\n if CONFIRMATION_STATUS not in entity:\n raise ArchivistUnconfirmedError(\n f\"cannot confirm {identity} as confirmation_status is not present\"\n )\n\n if entity[CONFIRMATION_STATUS] == CONFIRMATION_FAILED:\n raise ArchivistUnconfirmedError(\n f\"confirmation for {identity} FAILED - this is unusable\"\n )\n\n if entity[CONFIRMATION_STATUS] == CONFIRMATION_CONFIRMED:\n return entity\n\n return None\n\n\ndef __on_giveup_confirmed(details):\n self = details[\"args\"][0]\n count = self.pending_count\n elapsed = details[\"elapsed\"]\n raise ArchivistUnconfirmedError(\n f\"{count} pending assets still present after {elapsed} seconds\"\n )\n\n\n@backoff.on_predicate(\n backoff.expo,\n logger=LOGGER,\n max_time=__lookup_max_time,\n on_backoff=__backoff_handler,\n on_giveup=__on_giveup_confirmed,\n)\ndef wait_for_confirmed(self, *, props=None, **kwargs):\n \"\"\"docstring\"\"\"\n newprops = deepcopy(props) if props else {}\n newprops[CONFIRMATION_STATUS] = CONFIRMATION_PENDING\n\n LOGGER.debug(\"Count unconfirmed assets %s\", newprops)\n count = self.count(props=newprops, **kwargs)\n\n if count == 0:\n # did any fail\n newprops = deepcopy(props) if props else {}\n newprops[CONFIRMATION_STATUS] = CONFIRMATION_FAILED\n count = self.count(props=newprops, **kwargs)\n if count > 0:\n raise ArchivistUnconfirmedError(f\"There are {count} FAILED assets\")\n\n return True\n\n self.pending_count = count\n return False\n","sub_path":"archivist/confirm.py","file_name":"confirm.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"369159590","text":"from unittest import mock\nfrom unittest.mock import MagicMock\n\nimport pytest\nimport wandb\nfrom wandb.errors import CommError\nfrom wandb.sdk.internal.internal_api import Api as InternalApi\nfrom wandb.sdk.launch.builder.build import EntryPoint\nfrom wandb.sdk.launch.errors import LaunchError\nfrom wandb.sdk.launch.launch import run\n\n\ndef test_launch_incorrect_backend(runner, user, monkeypatch, wandb_init, test_settings):\n launch_project = MagicMock()\n launch_project.get_single_entry_point.return_value = EntryPoint(\n \"blah\", [\"python\", \"test.py\"]\n )\n proj = \"test1\"\n uri = \"https://github.com/wandb/examples.git\"\n entry_point = [\"python\", \"/examples/examples/launch/launch-quickstart/train.py\"]\n settings = test_settings({\"project\": proj})\n api = InternalApi()\n\n monkeypatch.setattr(\n \"wandb.sdk.launch.launch.fetch_and_validate_project\",\n lambda _1, _2: launch_project,\n )\n\n monkeypatch.setattr(\n wandb.sdk.launch.builder.build,\n \"validate_docker_installation\",\n lambda: None,\n )\n\n monkeypatch.setattr(\n \"wandb.docker\",\n lambda: None,\n )\n monkeypatch.setattr(\n \"wandb.sdk.launch.loader.environment_from_config\",\n lambda *args, **kawrgs: MagicMock(),\n )\n monkeypatch.setattr(\n \"wandb.sdk.launch.loader.registry_from_config\",\n lambda *args, **kawrgs: MagicMock(),\n )\n monkeypatch.setattr(\n \"wandb.sdk.launch.loader.builder_from_config\",\n lambda *args, **kawrgs: MagicMock(),\n )\n r = wandb_init(settings=settings)\n r.finish()\n with pytest.raises(\n LaunchError,\n match=\"Could not create runner from config. Invalid runner name: testing123\",\n ):\n run(\n api,\n uri=uri,\n entity=user,\n project=proj,\n entry_point=entry_point,\n resource=\"testing123\",\n )\n\n\ndef test_launch_multi_run(relay_server, runner, user, wandb_init, test_settings):\n with runner.isolated_filesystem(), mock.patch.dict(\n \"os.environ\", {\"WANDB_RUN_ID\": \"test\", \"WANDB_LAUNCH\": \"true\"}\n ):\n run1 = wandb_init()\n run1.finish()\n\n run2 = wandb_init()\n run2.finish()\n\n assert run1.id == \"test\"\n assert run2.id != \"test\"\n\n\ndef test_launch_multi_run_context(\n relay_server, runner, user, wandb_init, test_settings\n):\n with runner.isolated_filesystem(), mock.patch.dict(\n \"os.environ\", {\"WANDB_RUN_ID\": \"test\", \"WANDB_LAUNCH\": \"true\"}\n ):\n with wandb_init() as run1:\n run1.log({\"test\": 1})\n\n with wandb_init() as run2:\n run2.log({\"test\": 2})\n\n assert run1.id == \"test\"\n assert run2.id != \"test\"\n\n\ndef test_launch_get_project_queue_error(user):\n proj = \"projectq32e\"\n api = InternalApi()\n with pytest.raises(\n CommError,\n match=f\"Error fetching run queues for {user}/{proj} check that you have access to this entity and project\",\n ):\n api.get_project_run_queues(user, proj)\n","sub_path":"tests/pytest_tests/system_tests/test_launch/test_launch.py","file_name":"test_launch.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"47074918","text":"import numpy as np\n\n\ndef left_pad(array,pad_length):\n\n if pad_length >= 0:\n return np.pad(array, (pad_length, 0), \"constant\", constant_values=(0, 0))\n elif pad_length < 0:\n return array[-pad_length:].copy()\n\n\ndef right_pad(array,pad_length):\n\n if pad_length >= 0:\n return np.pad(array,(0,pad_length),\"constant\", constant_values=(0, 0))\n elif pad_length < 0:\n return array[:pad_length]\n\ndef pad_the_same(a,b):\n pad_length = a.shape[0] - b.shape[0]\n if pad_length > 0 :\n b = right_pad(b,pad_length)\n elif pad_length < 0:\n a = right_pad(a,-pad_length)\n\n return a,b\n\ndef right_shift(array,length):\n \"\"\"\n :param array: origin signal\n :param length: shift length\n :return: shifted signal\n \"\"\"\n\n buf = right_pad(array, -length)\n return left_pad(buf,length)\n\n\ndef left_shift(array, length):\n \"\"\"\n :param array: origin signal\n :param length: shift length\n :return: shifted signal\n \"\"\"\n buf = left_pad(array, -length)\n return right_pad(buf, length)\n\n\n\n\ndef convolve(kernel_array, array):\n\n \"\"\"\n convolve\n :param kernel_array: kernel array\n :param array: array to convolve\n :return: left, right\n left is a array of result of convolve along left side\n left is a array of result of convolve along right side\n \"\"\"\n\n #卷積\n convolved = np.convolve(kernel_array[::-1], array)\n print(convolved)\n\n #往右shift的卷積\n right = convolved.copy()\n right = right[kernel_array.shape[0]-1:]\n\n #往左shift的卷積\n left = convolved.copy()\n left = left[:kernel_array.shape[0]][::-1]\n\n return left, right\n\n\ndef find_shift(kernel_array:np.ndarray, array:np.ndarray):\n\n #卷積\n left, right = convolve(kernel_array, array)\n range = -1\n\n\n #找到往右卷的最大值和位移\n r_max_idx = np.argmax(right[:range])\n r_max_value = right[:range].max()\n\n #找到往左卷的最大值和位移\n l_max_idx = np.argmax(left[:range])\n l_max_value = left[:range].max()\n\n print(r_max_idx,r_max_value)\n print(l_max_idx,l_max_value)\n\n # return int(r_max_idx)\n # 看往左往右哪個大,return那個值\n # 往右是正數\n # 往左是負數\n if r_max_value > l_max_value:\n return int(r_max_idx)\n else:\n return int(-l_max_idx)\n\ndef auto_shift(kernel_array:np.ndarray, array:np.ndarray):\n\n shift = find_shift(kernel_array,array)\n a1 = right_shift(kernel_array,shift)\n print(shift)\n # print(find_shift(a1,a2))\n\n return a1\n\nif __name__ == \"__main__\":\n\n\n a = np.zeros((5))\n\n a += 1\n\n a = left_pad(a,2)\n\n a = right_pad(a,3)\n\n\n b = np.array((1.,2.,3.,4.,5.))\n\n\n a1 = right_pad(a,2)\n a2 = left_pad(a,3)\n\n\n # print(b)\n # print(a1)\n # #\n # left,right = convolve(b,a1)\n #\n # print(left)\n # print(right)\n # print(np.convolve(a2,a1))\n\n print(a2)\n print(a1)\n\n a2 = auto_shift(a2,a1)\n print(a2)","sub_path":"npp.py","file_name":"npp.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"644832214","text":"\n\ndef loadDataSet():\n postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],\n ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],\n ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],\n ['stop', 'posting', 'stupid', 'worthless', 'garbage'],\n ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],\n ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]\n classVec = [0,1,0,1,0,1] #1 is abusive, 0 not\n return postingList,classVec\n\ndef createVocabList(dataset):\n vocabSet=set([])\n for document in dataset:\n vocabSet=vocabSet|set(document)\n return list(vocabSet)\n\ndef setOfWords2Vec(vocabList,inputSet):\n returnVec=[0]*len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)]=1\n else:\n print(\"the word:%s is not my vocabulary!\"%word)\n\n return returnVec\n\npostmsgs,postclasses=loadDataSet()\nvlist=createVocabList(postmsgs)\nprint(vlist)\nwvlist=setOfWords2Vec(vlist,postmsgs[0])\nprint(wvlist)\n\nfrom numpy import *\ndef trainNB0(trainMat,trainCate):\n numTrainDocs=len(trainMat)\n numWords=len(trainMat[0])\n pAbusive=sum(trainCate)/float(numTrainDocs)\n p0Num=ones(numWords)\n p1Num=ones(numWords)\n p0Denom=2.0\n p1Denom=2.0\n for i in range(numTrainDocs):\n if trainCate[i]==1:\n p1Num+=trainMat[i]\n p1Denom+=sum(trainMat[i])\n else:\n p0Num+=trainMat[i]\n p0Denom+=sum(trainMat[i])\n p1Vect=log(p1Num/p1Denom)\n p0Vect=log(p0Num/p0Denom)\n return p0Vect,p1Vect,pAbusive\ntestmat=[]\nfor msg in postmsgs:\n testmat.append(setOfWords2Vec(vlist,msg))\n\nprint(testmat)\np0V,p1V,pAb=trainNB0(testmat,postclasses)\nprint(p0V)\nprint(p1V)\nprint(pAb)\n\ndef classfyNB(vectoverify,p0V,p1V,pAb):\n p1=sum(vectoverify*p1V)+log(pAb)\n p0=sum(vectoverify*p0V)+log(1.0-pAb)\n if p1>p0:\n return 1\n else:\n return 0\n\ntestEntry=['love','my','dalmation']\nthisDoc=array(setOfWords2Vec(vlist,testEntry))\nprint (testEntry,'classified as: ',classfyNB(thisDoc,p0V,p1V,pAb))\ntestEntry=['stupid','garbage']\nthisDoc=array(setOfWords2Vec(vlist,testEntry))\nprint (testEntry,'classified as: ',classfyNB(thisDoc,p0V,p1V,pAb))\n\ndef bagOfWords2Vec(vocabList,inputSet):\n returnVec=[0]*len(vocabList)\n for word in inputSet:\n if word in vocabList:\n returnVec[vocabList.index(word)]+=1\n else:\n print(\"the word:%s is not my vocabulary!\"%word)\n\n","sub_path":"Ch04/john_edited_runnable_py3/bayes_py3.py","file_name":"bayes_py3.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"106605421","text":"import tensorflow as tf\n\n# initializer = tf.contrib.layers.xavier_initializer()\n# initializer = tf.random_normal_initializer(mean=0.0, stddev=0.2)\ninitializer = tf.truncated_normal_initializer(mean=0.0, stddev=0.2)\n\ndef conv2d(inputs, n_output, ks=4, s=2, padding='same', name='conv2d'):\n\twith tf.variable_scope(name):\n\t\tout = tf.layers.conv2d(inputs=inputs, filters=n_output, kernel_size=ks, strides=s, padding=padding,\n\t\t\tactivation=None, kernel_initializer=initializer, bias_initializer=tf.zeros_initializer())\n\t\treturn out\n\ndef deconv2d(inputs, n_output, ks=4, s=2, name='deconv2d'):\n\twith tf.variable_scope(name):\n\t\tout = tf.layers.conv2d_transpose(inputs=inputs, filters=n_output, kernel_size=ks, strides=s, \n\t\t\tpadding='same', activation=None, kernel_initializer=initializer, bias_initializer=tf.zeros_initializer())\n\t\treturn out\n\n# Maybe try use tf.layers.batch_norm later...\ndef instance_norm(inputs, name='instance_norm'):\n\twith tf.variable_scope(name):\n\t\tmean, variance = tf.nn.moments(inputs, axes=[1, 2], keep_dims=True)\n\t\tepsilon = 1e-5\n\t\tinv = tf.rsqrt(variance + epsilon)\n\t\tnormalized = (inputs - mean)*inv\n\n\t\tdepth = inputs.get_shape()[3]\t\t\n\t\tscale = tf.get_variable('scale', [depth], initializer=tf.random_normal_initializer(1.0, 0.02, dtype=tf.float32))\n\t\toffset = tf.get_variable('offset', [depth], initializer=tf.constant_initializer(0.0))\n\t\treturn scale*normalized + offset\n\n\n","sub_path":"LHY-ML/HW3-3-CycleGAN/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"80660984","text":"import math\r\n\r\nfile = open(\"input.txt\", 'r')\r\ncircuit = open(\"multiplication.cir\", 'w')\r\n\r\nlineNumber = 1;\r\nvarNumber = 1;\r\nalice = list([])\r\nbob = list([])\r\nserver = \"serverXinput\" #Bob\r\nclient = \"clientXinput\" #Alice\r\nfor line in file:\r\n\tsplitted = line.split()\r\n\tif (lineNumber == 1):\r\n\t\tvectorSize = int(splitted[0])\r\n\t\tlineNumber += 1\r\n\telif (lineNumber == 2):\r\n\t\tdomainSize = int(splitted[0])\r\n\t\tlineNumber += 1\r\n\telif (lineNumber == 3):\r\n\t\tthreshold = int(splitted[0])\r\n\t\tlineNumber += 1\r\n\telif (lineNumber == 4):\r\n\t\tfor i in splitted:\r\n\t\t\talice.append(int(i))\r\n\t\tlineNumber += 1\r\n\telif (lineNumber == 5):\r\n\t\tfor i in splitted:\r\n\t\t\tbob.append(int(i))\r\n\t\tlineNumber += 1\r\n\t\t\r\n#################Functon Defenitions ##############\r\ndef inputFileGeneration(inputFile, fileName, char):\r\n varIndex = 1;\r\n fileXwrite = open(fileName,'w')\r\n for i in inputFile:\r\n fileXwrite.write('%s%d %d \\n'%(char,varIndex,i))\r\n varIndex += 1\r\n if(char == 'a'):\r\n fileXwrite.write('threshold %d\\n'%(threshold))\r\n fileXwrite.close()\r\n\r\ndef inputVarGeneration(fileName, index):\r\n global varNumber\r\n fileXread = open(fileName,'r')\r\n for line in fileXread:\r\n splitted=line.split()\r\n if( splitted[0] != 'threshold'):\r\n circuit.write('.input %s %d %d \\n'%(splitted[0],index,domainSize))\r\n varNumber += 1\r\n fileXread.close()\r\n###################################################\r\n\r\n\r\n\r\n\r\ninputFileGeneration(alice, client, 'a')\r\ninputFileGeneration(bob, server, 'b')\r\n\r\ninputVarGeneration(client, 1)\r\ninputVarGeneration(server, 2)\r\ncircuit.write('.input threshold 1 %d\\n'%(2*domainSize))\r\ncircuit.write('.output result\\n')\r\n\r\n\r\nresXk = 1\r\nfor i in range(len(bob)):\r\n for j in range(domainSize):\r\n circuit.write('b%dXbit%d select b%d %d %d\\n'%((i+1),j,(i+1),j,(j+1)))\r\n for j in range(domainSize):\r\n circuit.write('repeatXb%dXbit%d concat '%((i+1),j))\r\n for k in range(domainSize):\r\n circuit.write('b%dXbit%d '%((i+1),j))\r\n circuit.write('\\n')\r\n for j in range(domainSize):\r\n circuit.write('mulXb%dXbit%d and repeatXb%dXbit%d a%d\\n'%((i+1),j,(i+1),j,(i+1)))\r\n\r\n for j in range(domainSize):\r\n if (j == 0):\r\n circuit.write('concatXb%dXbit%d concat 0:%d mulXb%dXbit%d\\n'%((i+1),j,(domainSize-j),(i+1),j))\r\n else:\r\n circuit.write('concatXb%dXbit%d concat 0:%d mulXb%dXbit%d 0:%d\\n'%((i+1),j,(domainSize-j),(i+1),j,j))\r\n \r\n\r\n k = 0\r\n \r\n for j in range(int(domainSize/2)):\r\n circuit.write('addXpart%dXb%d add concatXb%dXbit%d concatXb%dXbit%d\\n'%((j+1),(i+1),(i+1),(j+k),(i+1),(j+1+k)))\r\n k += 1\r\n if((domainSize%2) != 0):\r\n j += 1\r\n circuit.write('addXpart%dXb%d or concatXb%dXbit%d concatXb%dXbit%d\\n'%((j+1),(i+1),(i+1),(j+k),(i+1),(j+k)))\r\n k += 1\r\n rangeSize = int(domainSize/2)\r\n else:\r\n rangeSize = int(domainSize/2) - 1\r\n\r\n part = 1\r\n \r\n for j in range(rangeSize):\r\n circuit.write('addXpart%dXb%d add addXpart%dXb%d addXpart%dXb%d\\n'%((k+1),(i+1),(part),(i+1),(part+1),(i+1)))\r\n k += 1 \r\n part += 2\r\n\r\n \r\n if(i != 0):\r\n if (resXk == 1):\r\n circuit.write('res%d add addXpart%dXb%d addXpart%dXb%d\\n'%((resXk),(k),(i),(k),(i+1)))\r\n resXk += 1\r\n else:\r\n circuit.write('res%d add res%d addXpart%dXb%d\\n'%((resXk),(resXk-1),(k),(i+1)))\r\n resXk += 1\r\n\r\ncircuit.write('result gteu res%d threshold\\n'%(vectorSize-1)) \r\n \r\nfile.close()\r\ncircuit.close()\r\n\r\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"168256485","text":"#\n# [222] Count Complete Tree Nodes\n#\n# https://leetcode.com/problems/count-complete-tree-nodes/description/\n#\n# algorithms\n# Medium (27.99%)\n# Total Accepted: 80.8K\n# Total Submissions: 288.5K\n# Testcase Example: '[1,2,3,4,5,6]'\n#\n# Given a complete binary tree, count the number of nodes.\n#\n# Note:\n#\n# Definition of a complete binary tree from Wikipedia:\n# In a complete binary tree every level, except possibly the last, is\n# completely filled, and all nodes in the last level are as far left as\n# possible. It can have between 1 and 2h nodes inclusive at the last level h.\n#\n# Example:\n#\n#\n# Input:\n# ⁠ 1\n# ⁠ / \\\n# ⁠ 2 3\n# ⁠/ \\ /\n# 4 5 6\n#\n# Output: 6\n#\n#\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def countNodes(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # Get depth of tree\n k, cur = -1, root\n while cur:\n cur = cur.left\n k += 1\n if k == -1:\n return 0\n # Binary Search node nums, L, R -> [), O(lgn*lgn)\n L, R = 1 << k, 1 << (k+1)\n while L < R-1:\n M = (L + R) >> 1\n if self.check(root, k, M):\n L = M\n else:\n R = M\n return L\n\n def check(self, root, k, n):\n if root is None:\n return False\n if n == 1:\n return True\n if n - (1 << k) < (1 << (k-1)):\n return self.check(root.left, k-1, n - (1 << (k-1)))\n else:\n return self.check(root.right, k-1, n - (1 << k))\n","sub_path":"222.count-complete-tree-nodes.python3.py","file_name":"222.count-complete-tree-nodes.python3.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"538455057","text":"import sys\nfrom time import sleep\nimport json\n\nimport pygame\n\nfrom settings import Settings\nfrom game_stats import GameStats\nfrom scoreboard import Scoreboard\nfrom button import Button\nfrom ship import Ship\nfrom bullet import Bullet\nfrom alien import Alien\n\nfrom charecter import Charecter\n\n\nclass AlienInvasion:\n \"\"\"Overall class to manage game assets and behavior.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game and create the game resources.\"\"\"\n pygame.init()\n self.settings = Settings()\n\n # Setting the display\n self.screen = pygame.display.set_mode(\n (self.settings.screen_width, self.settings.screen_height))\n pygame.display.set_caption('Alien Invasion')\n\n self.stats = GameStats(self)\n self.sb = Scoreboard(self)\n self.ship = Ship(self)\n\n self.bullets = pygame.sprite.Group()\n self.aliens = pygame.sprite.Group()\n\n self._create_fleet()\n\n # Make the play button\n self.play_button = Button(self, 'Play')\n \n # self.charecter = Charecter(self)\n\n def run_game(self):\n \"\"\"Start the main loop for the game.\"\"\"\n print('Starting the game')\n while True:\n self._check_events()\n\n if self.stats.game_active:\n self.ship.update()\n self._update_aliens()\n self._update_bullets()\n \n self._update_screen()\n \n def _check_events(self):\n \"\"\"Respond to key presses and mouse events.\"\"\"\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n print('Quiting Alien Invasion...')\n self.stats.update_highscore()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n self._check_keydown_events(event)\n elif event.type == pygame.KEYUP:\n self._check_keyup_events(event)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = pygame.mouse.get_pos()\n self._check_play_button(mouse_pos)\n \n def _check_keydown_events(self, event):\n \"\"\"Respond to keydown events\"\"\"\n\n # Ship movement\n if event.key == self.settings.kb_right:\n self.ship.move_right = True\n elif event.key == self.settings.kb_left:\n self.ship.move_left = True\n \n # Firing bullets\n if event.key == self.settings.kb_fire:\n self._fire_bullet()\n\n # Game Interface\n if event.key == self.settings.kb_quit:\n print('Quiting Alien Invasion...')\n self.stats.update_highscore()\n sys.exit()\n \n if event.key == self.settings.kb_show_stats:\n self._print_stats()\n \n def _check_keyup_events(self, event):\n \"\"\"Respond to keyup events\"\"\"\n if event.key == self.settings.kb_right:\n self.ship.move_right = False\n elif event.key == self.settings.kb_left:\n self.ship.move_left = False\n \n def _check_play_button(self, mouse_pos):\n \"\"\"Start a new game when the player clicks play\"\"\"\n button_clicked = self.play_button.rect.collidepoint(mouse_pos)\n if button_clicked and not self.stats.game_active:\n # Reset the game statistics\n self.stats.reset_stats()\n self.stats.game_active = True\n self.sb.prep_score()\n self.sb.prep_level()\n self.sb.prep_ships()\n\n # Reset the game settings\n self.settings.initialize_dynamic_settings()\n \n # Get rid of any remaining aliens and bullets\n self.aliens.empty()\n self.bullets.empty()\n\n # Create a new fleet and center the ship\n self._create_fleet()\n self.ship.center_ship()\n\n # Hide the mouse cursor\n pygame.mouse.set_visible(False)\n\n def _ship_hit(self):\n \"\"\"Respond to the ship being hit by aliens\"\"\"\n \n if self.stats.ships_left > 0:\n # Decrement the ships left and update the scoreboard\n self.stats.ships_left -= 1\n self.sb.prep_ships()\n\n # Remove all of the bullets and aliens\n self.aliens.empty()\n self.bullets.empty()\n\n # Create a new fleet an center the ship\n self._create_fleet()\n self.ship.center_ship()\n\n # Pause\n sleep(0.5)\n\n # Print the lives left\n print(f'{self.stats.ships_left} lives left.')\n else:\n self.stats.game_active = False\n pygame.mouse.set_visible(True)\n print('Game Over!')\n \n \n def _fire_bullet(self):\n \"\"\"Create a new bullet and add it to the bullets group\"\"\"\n if len(self.bullets) < self.settings.max_bullets:\n new_bullet = Bullet(self)\n self.bullets.add(new_bullet)\n\n # Add the bullet count to the stats\n self.stats.shots_fired += 1\n\n def _update_bullets(self):\n \"\"\"Updates to the bullets in the game\"\"\"\n # Update the bullets possition\n self.bullets.update()\n\n # Getting rid of bullets that had disappeared\n for bullet in self.bullets.copy():\n if bullet.rect.bottom <= 0:\n self.bullets.remove(bullet)\n \n self._check_bullet_alien_collisions()\n \n def _check_bullet_alien_collisions(self):\n \"\"\"Check the collisions between the bullets and aliens\"\"\"\n # Add the aliens and bullets to a group and check if they collide,\n # if so remove the bullet and alien. Posible feature is an explosion\n collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)\n\n if collisions:\n self.stats.score += self.settings.alien_points\n self.sb.prep_score()\n self.sb.check_high_score()\n\n # Check if the fleet is destroyed, remove all bullets and spawn a new fleet\n if not self.aliens:\n self.bullets.empty\n print('Round won!')\n self._create_fleet()\n self.settings.increase_speed()\n\n # Increase level\n self.stats.level += 1\n self.sb.prep_level()\n\n def _create_fleet(self):\n \"\"\"Create the fleet of aliens.\"\"\"\n # Create an alien instance and find the number of aliens in a row\n # Spacing between each alien is equal to a half of the alien's width\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n available_space_x = self.settings.screen_width - alien_width\n number_aliens_x = available_space_x // (2 * alien_width)\n\n # Vertical spacing\n available_space_y = self.settings.screen_height - (3 * alien_height) - self.ship.rect.height\n row_number = available_space_y // (2 * alien_height)\n\n # Create the first row of aliens\n for alien_row in range(row_number):\n for alien_number in range(number_aliens_x):\n self._create_alien(alien_number, alien_row)\n \n # Add to the fleet_count stats\n self.stats.fleet_count += 1\n\n def _create_alien(self, alien_number, row_number):\n \"\"\"Create a single alien and place it in the fleet\"\"\"\n # Create an alien and place it in the row\n alien = Alien(self)\n alien_width, alien_height = alien.rect.size\n alien.x = 2 * alien_width * alien_number + 20\n alien.rect.x = alien.x\n alien.y = 2 * alien_height * row_number + 20\n alien.rect.y = alien.y\n self.aliens.add(alien)\n \n def _check_aliens_bottom(self):\n \"\"\"Check if any aliens have reached the bottom of the screen\"\"\"\n screen_rect = self.screen.get_rect()\n for alien in self.aliens.sprites():\n if alien.rect.bottom >= screen_rect.bottom:\n # Treat the case the same way as if the ship got hit\n self._ship_hit()\n break\n \n def _check_fleet_edges(self):\n \"\"\"Responding to every alien that reaches the edge\"\"\"\n for alien in self.aliens.sprites():\n if alien.check_edges():\n self._check_fleet_direction()\n break\n \n def _check_fleet_direction(self):\n \"\"\"Drop the fleet and change its direction\"\"\"\n for alien in self.aliens.sprites():\n alien.rect.y += self.settings.fleet_drop_speed\n self.settings.alien_direction *= -1\n\n def _update_aliens(self):\n \"\"\"\n Check if the fleet hits an edge,\n update the possition of all the aliens in the group\"\"\"\n self._check_fleet_edges()\n self.aliens.update()\n\n # Check if the ship collided with an alien\n if pygame.sprite.spritecollideany(self.ship, self.aliens):\n print('Ship hit!')\n self._ship_hit()\n\n # Look for aliens hitting the bottom of the screen\n self._check_aliens_bottom()\n \n def _print_stats(self):\n \"\"\"Print the game stats of the game\"\"\"\n print(' --- Game Stats --- \\n')\n \n print(f'Level - {self.stats.fleet_count}')\n print(f'Lives left - {self.stats.ships_left}')\n print(f'Total shots fired - {self.stats.shots_fired}')\n #print(f'Total aliens hit - {self.stats.aliens_hit}')\n\n def _update_screen(self):\n \"\"\"Update images to the screen, and flip to the new screen\"\"\"\n # Set the bg_color\n self.screen.blit(self.settings.bg_image, (0, 0))\n for bullet in self.bullets.sprites():\n bullet.draw_bullet()\n self.aliens.draw(self.screen)\n self.ship.blitme()\n\n self.sb.show_score()\n \n # Draw the button if the game is inactive\n if not self.stats.game_active:\n self.play_button.draw_button()\n \n #self.charecter.blitme()\n\n # Make the most recently drawn screen visible.q\n pygame.display.flip()\n\nif __name__ == '__main__':\n # Making na instance of the game and running it\n ai = AlienInvasion()\n ai.run_game()\n","sub_path":"Alien Invasion/alien_invasion.py","file_name":"alien_invasion.py","file_ext":"py","file_size_in_byte":10116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"205231351","text":"from utils.parse_utils import int_to_price, contains_maybe, epoch_to_date\nfrom classes import Column, Table\nimport utils.cog_utils.misc_utils as misc\nimport json, utils, datetime\n\n\"\"\" NOTE: find_equips and to_table should be able to handle the same keywords \"\"\"\n\n# Returns dict -- each key is an equip name -- each value is a list of dicts (sale data)\ndef find_equips(keyword_list):\n\t# inits\n\tdata= json.load(open(utils.AUCTION_FILE, encoding='utf-8'))\n\n\t# check timestamp is after jan 1st of that year\n\tdef check_date(timestamp, year):\n\t\treturn timestamp >= datetime.datetime(year,1,1).timestamp()\n\n\t# if keyword passed in, use it to filter results\n\tchecks= {\n\t\t\"min\": lambda x: int(x['price']) >= keyword_list['min'].value,\n\t\t\"max\": lambda x: int(x['price']) <= keyword_list['max'].value,\n\t\t\"date\": lambda x: check_date(x['time'], keyword_list['date'].value),\n\t\t\"seller\": lambda x: contains_maybe(to_search=x['seller'], to_find=keyword_list['seller'].value, spaced=False),\n\t\t\"buyer\": lambda x: contains_maybe(to_search=x['buyer'], to_find=keyword_list['buyer'].value, spaced=False),\n\t\t'name': lambda x: contains_maybe(to_search=x['name'], to_find=keyword_list['name'].value),\n\t\t\"rare\": lambda x: is_rare(x['name']),\n\t\t\"norare\": lambda x: not is_rare(x['name'])\n\t}\n\tchecks= [checks[x] for x in checks if x in keyword_list and keyword_list[x].has_value]\n\n\tfiltered= misc.filter_data(checks, data, keyword_list)\n\tfiltered.sort(key= lambda x: x['price'], reverse=True)\n\treturn filtered\n\n\n# convert equip results to a table (string) to print\n# certain columns are only printed if a relevant keyword is passed in (see key_map in config)\ndef to_table(command, eq_list, keyword_list, prop_dct=None):\n\tCONFIG= utils.load_yaml(utils.AUCTION_CONFIG)\n\tspecial_cols= ['thread', 'link', 'date'] # these have to be added last for formatting reasons\n\n\t# special formatting\n\tdef format_stats(c): c.max_width= CONFIG[command]['stat_col_width']; return c\n\tdef format_price(c): c.data= [str(int_to_price(x)) for x in c.data]; return c\n\tformat_rules= dict(stats=format_stats, price=format_price)\n\n\t# get cols\n\tcol_names= misc.get_col_names(keyword_list=keyword_list,\n\t\t\t\t\t\t\t\t default_cols=CONFIG[command]['default_cols'],\n\t\t\t\t\t\t\t\t key_map=CONFIG['key_map'])\n\tcols= misc.get_cols(data=eq_list, special_cols=special_cols, col_names=col_names,\n\t\t\t\t\t\tformat_rules=format_rules, CONFIG=CONFIG)\n\n\t# add date col\n\tif 'date' in col_names:\n\t\tdata= []\n\t\tfor x in eq_list:\n\t\t\tx['date']= epoch_to_date(x['time'])\n\t\t\ttmp= utils.render(CONFIG['date_template'],x)\n\t\t\tdata.append(tmp)\n\t\tcols.append(Column(data=data, header=CONFIG['equip_headers']['date']))\n\n\t# add link col\n\tif 'link' in col_names:\n\t\tcols.append(Column(data=[x['link'] for x in eq_list],\n\t\t\t\t\t\t header=CONFIG['equip_headers']['link'], is_link=True))\n\n\t# add thread col\n\tif 'thread' in col_names:\n\t\tcols.append(Column(data=[x['thread'] for x in eq_list],\n\t\t\t\t\t\t header=CONFIG['equip_headers']['thread'], is_link=True))\n\n\t# add attrs if requested\n\tret= Table(cols)\n\tif prop_dct:\n\t\tfor x in prop_dct:\n\t\t\tret.__dict__[x]= prop_dct[x]\n\n\treturn ret\n\n\n# Potentially valuable suffix / prefixes\ndef is_rare(name):\n\trares= [\"Savage\", \"Mystic\", \"Shielding\", \"Charged\", \"Frugal\", \"Radiant\"]\n\treturn any(x.lower() in name.lower() for x in rares)","sub_path":"utils/cog_utils/equip_utils.py","file_name":"equip_utils.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"264955326","text":"import re, requests, os\nfrom requests_html import HTML\n\ndef main():\n os.makedirs('tmp/', exist_ok=True)\n dajareshuu()\n kodomodajareshuu()\n uncyclopedia()\n dajarenoki()\n chakuwiwki()\n dajarenet()\n dajarenavi()\n hitokuchi()\n dareja()\n dajakura()\n\ndef dajakura():\n total = 0\n for i in range(26): # 0~25, only 26 and 27 will give garbled text, so crawl it manually\n dajare_elements = get_html('http://with2.net/dajakura/point{}.html'.format(i)).find('span.dajare')\n dajares = [d.text for d in dajare_elements]\n total += len(dajares)\n with open('./outputs/dajakura_{}.txt'.format(i), 'w') as f:\n f.write('\\n'.join(dajares))\n print(total)\n \ndef dareja():\n dajare_elements = get_html('http://wtpage.info/dajare/').find('td')\n dajares = [d.text for d in dajare_elements]\n print(len(dajares))\n with open('./outputs/dareja.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef hitokuchi():\n dajare_elements = get_html('http://www.biwa.ne.jp/~aki-ina/gyagu.html').find('section:nth-child(2) li')\n dajares = [d.text for d in dajare_elements]\n print(len(dajares))\n with open('./outputs/hitokuchi.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef dajarenavi():\n dajarenavi_get_links()\n \n with open('./tmplink.txt', 'r') as f:\n links = f.read().split('\\n')\n dajares = list() \n for i, link in enumerate(links):\n print('{}/{}: {}'.format(i+1, len(links), link))\n dajare_elements = get_html(link).find('.dajare')\n dajares += [d.text for d in dajare_elements]\n print(len(dajares))\n with open('./outputs/dajarenavi.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef dajarenavi_get_links():\n dajare_links = list()\n unique_category_links = list()\n \n links = [a.attrs['href'] for a in get_html('https://dajarenavi.net/').find('a[href^=\"menu\"]')] # a\n for link in links:\n slinks = [a.attrs['href'] for a in get_html('https://dajarenavi.net/' + link).find('a[href^=\"m_\"]')] # aa\n for slink in slinks:\n if slink == 'm_51_45_ha_no.htm': continue\n queued_links = [ 'https://dajarenavi.net/menu/0/' + slink ]\n while(len(queued_links) > 0):\n print(\"queued: {}, unique: {}\".format(len(queued_links), len(unique_category_links)) )\n category_link = queued_links.pop()\n relative_links = get_html( category_link).find('a[href^=\"../\"]')\n if relative_links == []: continue\n for a in relative_links:\n relative_link = a.attrs['href']\n if relative_link.endswith('index.htm'): continue\n if relative_link.startswith('../../'):\n dajare_links.append('https://dajarenavi.net/' + relative_link[6:])\n else:\n assert relative_link.startswith('../') is True\n new_category_link = 'https://dajarenavi.net/menu/' + relative_link[3:]\n if new_category_link not in unique_category_links:\n unique_category_links.append(new_category_link)\n queued_links.append(new_category_link)\n with open('./tmplink.txt', 'w') as f:\n f.write('\\n'.join(dajare_links))\n print(len(dajare_links))\n\ndef dajarenet():\n dajarenet_1()\n dajarenet_2()\n dajarenet_3()\n\ndef dajarenet_3():\n total_dajares = list()\n for i in range(1,7): # 1~6\n html = get_html('http://www.dajare.net/v001/{}.htm'.format(str(i).zfill(3)))\n dajare_elements = html.find('blockquote br')\n dajares = [e.text for e in dajare_elements]\n dajares = list(filter(lambda d: len(d)!=0, dajares))\n total_dajares += dajares\n with open('./outputs/dajarenet_3.txt', 'w') as f:\n f.write('\\n'.join(total_dajares))\n \ndef dajarenet_2():\n total_dajares = list()\n for initial in ['a', 'k', 's', 't', 'n', 'h', 'm', 'y', 'r', 'w']:\n html = get_html('http://www.dajare.net/{}.htm'.format(initial))\n text = html.find('pre')[0].text\n text = text.replace('\\u3000' ,\"\")\n dajares = list(filter(lambda d: re.search(r'[A-ZAB]', d) == None, text.split()) ) \n total_dajares += dajares\n with open('./outputs/dajarenet_2.txt', 'w') as f:\n f.write('\\n'.join(total_dajares))\n \ndef dajarenet_1():\n total_dajares = list()\n for i in range(1,84): # 1~83\n full_html = get_html('http://www.dajare.net/{}.htm'.format(str(i).zfill(3)))\n dajares = re.findall(r'(.+) li')\n dajares = list()\n for dajare_ele in dajare_elements:\n dajare = re.sub('$\\d+\\.', '', dajare_ele.text)\n dajare = re.sub('\\n.+', '', dajare)\n dajares.append(dajare)\n with open('./outputs/chakuwiki.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef dajarenoki():\n html = get_html('http://www.mori7.net/ki/dajare/index.php')\n dajare_links = html.find('ul a')[1::2]\n dajares = [link.text for link in dajare_links]\n with open('./outputs/dajarenoki.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n\ndef uncyclopedia():\n html = get_html('https://ja.uncyclopedia.info/wiki/%E3%83%80%E3%82%B8%E3%83%A3%E3%83%AC%E3%81%AE%E4%B8%80%E8%A6%A7')\n lists = html.find('.mw-parser-output ul')[:-1] # the last ul is not list of dajares\n dajares = list()\n for lst in lists:\n dajare_elements = lst.find('li')\n for dajare_element in dajare_elements:\n dajare = re.sub(r'\\[\\d+\\]', '', dajare_element.text)\n dajares.append(dajare)\n with open('./outputs/uncyclopedia.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef dajareshuu():\n html = get_html('https://dajareshuu.web.fc2.com/')\n cells = html.find('table[summary=\"ダジャレ\"] td:last-child')\n dajares = [cell.text for cell in cells]\n # print(dajares[:3])\n # print(dajares[-2:])\n with open('./outputs/dajareshuu.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n\ndef kodomodajareshuu():\n html = get_html('https://blog.goo.ne.jp/inocch2007-/e/0fbaebe9c98ee307797cf9aa72487f52')\n text = html.find('span.etBody')[0].text # find always return list, be careful\n dajares = re.findall(r'\\d+ \\w+ (.+)', text, re.MULTILINE)\n assert len(dajares) == 300\n with open('./outputs/kodomodajareshuu.txt', 'w') as f:\n f.write('\\n'.join(dajares))\n \ndef get_html(url):\n response = requests.get(url)\n response.encoding = response.apparent_encoding # solve garbled text\n html = HTML(html=response.text)\n return html\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"generate_corpus/crawl_other.py","file_name":"crawl_other.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"353003841","text":"from django.utils import timezone\nfrom django.utils.translation import activate\nfrom django.urls import reverse_lazy\nfrom django.test import tag\nfrom django.views.generic import DetailView\n\nfrom shared_models.views import CommonDetailView\nfrom whalebrary.test import FactoryFloor\nfrom whalebrary.test.common_tests import CommonWhalebraryTest as CommonTest\nfrom .. import views\n\n# Example how to run with keyword tags\n# python manage.py test whalebrary.test --tag transaction_new\n\n\nclass TestItemDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.ItemFactory()\n self.test_url = reverse_lazy('whalebrary:item_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/item_detail.html'\n self.user = self.get_and_login_user()\n\n @tag(\"Item\", \"item_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.ItemDetailView, CommonDetailView)\n\n @tag(\"Item\", \"item_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Item\", \"item_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n \"random_qty\",\n \"oh_qty_field_list\",\n \"random_sup\",\n \"sup_field_list\",\n \"random_ord\",\n \"ord_field_list\",\n \"random_lend\",\n \"lend_field_list\",\n \"random_file\",\n \"file_field_list\",\n\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestLocationDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.LocationFactory()\n self.test_url = reverse_lazy('whalebrary:location_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/location_detail.html'\n self.user = self.get_and_login_user(in_group=\"whalebrary_admin\")\n\n @tag(\"Location\", \"location_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.LocationDetailView, CommonDetailView)\n self.assert_inheritance(views.LocationDetailView, views.WhalebraryAdminAccessRequired)\n\n @tag(\"Location\", \"location_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Location\", \"location_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestTransactionDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.TransactionFactory()\n self.test_url = reverse_lazy('whalebrary:transaction_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/transaction_detail.html'\n self.user = self.get_and_login_user()\n\n @tag(\"Transaction\", \"transaction_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.TransactionDetailView, CommonDetailView)\n\n @tag(\"Transaction\", \"transaction_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Transaction\", \"transaction_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestOrderDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.OrderFactory()\n self.test_url = reverse_lazy('whalebrary:order_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/order_detail.html'\n self.user = self.get_and_login_user()\n\n @tag(\"Order\", \"order_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.OrderDetailView, CommonDetailView)\n self.assert_inheritance(views.OrderDetailView, views.WhalebraryAccessRequired)\n\n @tag(\"Order\", \"order_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Order\", \"order_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestPersonnelDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.PersonnelFactory()\n self.test_url = reverse_lazy('whalebrary:personnel_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/personnel_detail.html'\n self.user = self.get_and_login_user(in_group=\"whalebrary_admin\")\n\n @tag(\"Personnel\", \"personnel_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.PersonnelDetailView, CommonDetailView)\n self.assert_inheritance(views.PersonnelDetailView, views.WhalebraryAdminAccessRequired)\n\n @tag(\"Personnel\", \"personnel_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Personnel\", \"personnel_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestSupplierDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.SupplierFactory()\n self.test_url = reverse_lazy('whalebrary:supplier_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/supplier_detail.html'\n self.user = self.get_and_login_user()\n\n @tag(\"Supplier\", \"supplier_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.SupplierDetailView, CommonDetailView)\n self.assert_inheritance(views.SupplierDetailView, views.WhalebraryAccessRequired)\n\n @tag(\"Supplier\", \"supplier_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Supplier\", \"supplier_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\nclass TestIncidentDetailView(CommonTest):\n def setUp(self):\n super().setUp()\n self.instance = FactoryFloor.IncidentFactory()\n self.test_url = reverse_lazy('whalebrary:incident_detail', args=[self.instance.pk, ])\n self.expected_template = 'whalebrary/incident_detail.html'\n self.user = self.get_and_login_user()\n\n @tag(\"Incident\", \"incident_detail\", \"view\")\n def test_view_class(self):\n self.assert_inheritance(views.IncidentDetailView, CommonDetailView)\n self.assert_inheritance(views.IncidentDetailView, views.WhalebraryAccessRequired)\n\n @tag(\"Incident\", \"incident_detail\", \"access\")\n def test_view(self):\n self.assert_good_response(self.test_url)\n self.assert_non_public_view(test_url=self.test_url, expected_template=self.expected_template, user=self.user)\n\n @tag(\"Incident\", \"incident_detail\", \"context\")\n def test_context(self):\n context_vars = [\n \"field_list\",\n \"random_image\",\n \"image_field_list\",\n \"all_incidents\",\n \"mapbox_api_key\",\n ]\n self.assert_presence_of_context_vars(self.test_url, context_vars, user=self.user)\n\n\n","sub_path":"whalebrary/test/test_detail_views.py","file_name":"test_detail_views.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"296659017","text":"#--- Create a new mesh by keeping selected vertices and discarding the rest\n...\n#--- For each kept vertex, check to see if it is connected to other kept vertices\n#--- If not, then create new connections to maintain triangles\nfor i in self.vertIndices:\n thisVert = model.getShape().vtx[i]\n if not thisVert == self.originVertex:\n # Get this vertex's connecting vertices (cv)\n cvIndices = []\n faces = thisVert.connectedFaces()\n for f in faces:\n cv = str(f.getVertices())\n print(cv)\n # Split cv from nameNewShape.vtx[indices] to just indices\n cv = str(cv.split(\"[\")[1]).split(\"]\")[0]\n cv = cv.split(\",\")\n for s in cv:\n # If it is a slice of vertices\n if \":\" in s:\n s = self.expandSlice(s, True)\n if i in s:\n s.remove(i)\n cvIndices.extend(s)\n # Else, it's an individual vertex\n else:\n s = int(s)\n if s != i:\n cvIndices.append(s)\n\n cvIndices = set(cvIndices)\n # Check number of [connecting vertices] intersecting with [kept vertices]\n inBoth = cvIndices.intersection(setOfVertIndices)\n numInBoth = len(inBoth)\n...","sub_path":"assets/codesamples/xinpm.py","file_name":"xinpm.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"109653321","text":"def insert_sort(A):\n \"\"\"сортировка списка А вставками\"\"\"\n for top in range(1, len(A)):\n k = top\n while k > 0 and A[k-1] > A[k]:\n A[k], A[k-1] = A[k-1], A[k]\n k -= 1\n\ndef choice_sort(A):\n \"\"\"сортировка списка А выбором\"\"\"\n for position in range(0, len(A)-1):\n for k in range(position+1, len(A)):\n if A[k] < A[position]:\n A[k], A[position] = A[position], A[k]\n\ndef bubble_sort(A):\n \"\"\"сортировка списка А методом пузырька\"\"\"\n for bypass in range(1, len(A)):\n for bubble in range(0, len(A)-bypass):\n if A[bubble] > A[bubble+1]:\n A[bubble], A[bubble+1] = A[bubble+1], A[bubble]\n\n## processing command line input\n# returns sorting function by given name\ndef get_sort_algorithm(name):\n return {\n 'bubble': bubble_sort,\n 'choice': choice_sort,\n 'insert': insert_sort,\n }.get(name)\n\n# check if string parses to an int\ndef is_parses_to_int(int_string):\n try:\n int(int_string)\n except Exception as e:\n return False\n return True\n\n# divide and process command line args by their meaning\ndef process_args_list(args_list):\n args_list.pop(0) # first arg is expected to be a file name, so it's popped\n sort_method_name = args_list.pop(0) # second arg is expected to be a sorting name\n\n # trying to validate the second arg\n if is_parses_to_int(sort_method_name):\n print(\"First argument should be a sorting method name: insert, choice, bubble\")\n return\n\n algorithm = get_sort_algorithm(sort_method_name)\n\n # trying to validate given algorithm\n if algorithm is None:\n print(\"Выберите метод сортировки: insert, choice, bubble\")\n return\n else:\n print(algorithm.__doc__)\n\n # trying to parse the rest of the args to ints\n try:\n list_of_int_args = [int(arg) for arg in args_list]\n except Exception as e:\n print(\"cannot parse integer\")\n return\n\n # applying algorithms\n algorithm(list_of_int_args)\n\n print(\"Sorted list: \", str(list_of_int_args))\n print(\"Ok\")\n\nif __name__ == \"__main__\":\n process_args_list(sys.argv) # get command line args list and process\n","sub_path":"src/sortExr.py","file_name":"sortExr.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"65680614","text":"# Use a single array to implement three stacks.\n\nclass ThreeStacks():\n def __init__(self):\n self.array = [None, None, None] # container that is going to take items like a stack\n self.current = [0, 1, 2] # pointer to the last position of each stack\n \n def push(self, item, stack_number):\n if not stack_number in [0, 1, 2]: # choose the stack\n raise Exception(\"Bad stack number\")\n while len(self.array) <= self.current[stack_number]: # once size of current stack exceeds required\n self.array += [None] * len(self.array) # double the stack sizes\n self.array[self.current[stack_number]] = item # items in stack 0 is stored 2 items apart\n self.current[stack_number] += 3\n \n def pop(self, stack_number):\n if not stack_number in [0, 1, 2]:\n raise Exception(\"Bad stack number\")\n if self.current[stack_number] > 3: # if there is anything stored\n self.current[stack_number] -= 3 # goes back to the pointer to that thing\n item = self.array[self.current[stack_number]] # get the item\n self.array[self.current[stack_number]] = None # set the pointer to None\n return item\n\n#############################################################################\n\nclass FourStacks():\n def __init__(self):\n self.container = [None] * 4 # actual place to put the items\n self.pointer = [0,1,2,3] # keep track of where each stack is at\n\n def push(self,item,stack_number):\n if not stack_number in [0,1,2,3]: # if not in stated stacks, raise error\n raise Exception(\"Bad stack number\")\n if self.pointer[stack_number]>= len(self.container): #if pointer has moved and greater than length of container\n self.container+=([None]*len(self.container))\n self.container[self.pointer[stack_number]] = item\n self.pointer[stack_number]+=4\n\n def pop(self,stack_number):\n if not stack_number in [0,1,2,3]:\n raise Exception(\"Bad stack number\") \n if self.pointer[stack_number] >= 4: # if pointer has ever been moved ahead\n self.pointer[stack_number]-=4 # back one place\n item = self.container[self.pointer[stack_number]] # store the item as temp\n self.container[self.pointer[stack_number]] = None # set that place as None\n return item\n\nimport unittest\n\nclass Test(unittest.TestCase):\n def test_three_stacks(self):\n three_stacks = ThreeStacks()\n three_stacks.push(101, 0)\n three_stacks.push(102, 0)\n three_stacks.push(103, 0)\n three_stacks.push(201, 1)\n self.assertEqual(three_stacks.pop(0), 103)\n self.assertEqual(three_stacks.pop(1), 201)\n self.assertEqual(three_stacks.pop(1), None)\n self.assertEqual(three_stacks.pop(2), None)\n three_stacks.push(301, 2)\n three_stacks.push(302, 2)\n self.assertEqual(three_stacks.pop(2), 302)\n self.assertEqual(three_stacks.pop(2), 301)\n self.assertEqual(three_stacks.pop(2), None)\n def test_four_stacks(self):\n four_stacks = FourStacks()\n four_stacks.push(100, 0)\n four_stacks.push(110, 1)\n four_stacks.push(101, 0)\n four_stacks.push(102, 0)\n four_stacks.push(130, 3)\n self.assertEqual(four_stacks.pop(0),102)\n self.assertEqual(four_stacks.pop(0),101)\n self.assertEqual(four_stacks.pop(3),130)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"ch-03-stacks-and-queues/01-three-in-one.py","file_name":"01-three-in-one.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"98947332","text":"from tkinter import *\nimport random\n\nWIDTH = 800\nHEIGHT = 600\n\ncolor_lst = ['red', 'blue', 'green', 'yellow', 'orange',\n 'purple', 'cyan', 'magenta', 'pink']\n\ntk = Tk()\ncanvas = Canvas(tk, width=WIDTH, height=HEIGHT)\ntk.title(\"Drawing\")\ncanvas.pack()\n\n# canvas.create_line(0, 0, 500, 400)\n# canvas.create_rectangle(100, 100, 250, 250, fill=\"blue\")\n# canvas.create_oval(10, 10, 50, 50, fill=\"green\")\n# canvas.create_polygon(400, 10, 300, 300, 500, 300, fill=\"purple\")\n\nfor i in range(100):\n x1 = random.randrange(WIDTH)\n y1 = random.randrange(HEIGHT)\n x2 = random.randrange(WIDTH)\n y2 = random.randrange(HEIGHT)\n\n col = random.choice(color_lst)\n canvas.create_rectangle(x1, y1, x2, y2, fill=col)\n canvas.create_oval(x1, y1, x2, y2, fill=random.choice(color_lst))\n\ncanvas.mainloop()\n","sub_path":"Python/tkinter_example.py","file_name":"tkinter_example.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"437957774","text":"from django.conf import settings\nfrom django.contrib.admin.options import IS_POPUP_VAR\n\n\ndef sito_luca(request):\n context = {\n 'is_popup': (IS_POPUP_VAR in request.POST or\n IS_POPUP_VAR in request.GET),\n }\n for key, val in settings.SITO_LUCA_CONTEXT:\n context[key] = val\n context['version'] = settings.VERSION()\n return context\n","sub_path":"sito_luca/utilities/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"109599141","text":"#!/usr/bin/env python3\n\nimport argparse\nimport base64\nimport binascii\nimport json\nimport os\nimport time\nimport uuid\n\nfrom pprint import pprint\n\nimport happybase\nimport requests\nimport thriftpy2\n\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nfrom Crypto.Util import Counter\n\n\ndef main():\n args = command_line_args()\n connected = False\n attempts = 0\n init(args)\n while not connected and attempts < 100:\n try:\n connection = happybase.Connection(args.zookeeper_quorum)\n connection.open()\n\n if not args.skip_table_creation:\n connection.create_table(args.destination_table,\n {'cf': dict(max_versions=10)})\n\n table = connection.table(args.destination_table)\n connected = True\n\n if args.data_key_service:\n content = requests.get(f'{args.data_key_service}/datakey').json()\n encryption_key = content['plaintextDataKey']\n encrypted_key = content['ciphertextDataKey']\n master_key_id = content['dataKeyEncryptionKeyId']\n else:\n encryption_key = \"czMQLgW/OrzBZwFV9u4EBA==\"\n master_key_id = \"1234567890\"\n encrypted_key = \"blahblah\"\n\n with (open(args.sample_data_file)) as file:\n data = json.load(file)\n for datum in data:\n record_id = datum['id']\n timestamp = datum['cf:data']['timestamp']\n value = datum['cf:data']['value']\n if 'dbObject' in value:\n db_object = value['dbObject']\n if db_object != \"CORRUPT\":\n del value['dbObject']\n record = uniq_db_object()\n record_string = json.dumps(record)\n [iv, encrypted_record] = encrypt(encryption_key,\n record_string)\n value['encryption']['initialisationVector'] \\\n = iv.decode('ascii')\n\n if master_key_id:\n value['encryption']['keyEncryptionKeyId'] = \\\n master_key_id\n\n if encrypted_key:\n value['encryption']['encryptedEncryptionKey'] = \\\n encrypted_key\n\n value['dbObject'] = encrypted_record.decode('ascii')\n else:\n value['encryption']['initialisationVector'] = \"PHONEYVECTOR\"\n\n obj = {'cf:data': json.dumps(value)}\n table.put(record_id, obj, timestamp=int(timestamp))\n\n if args.dump_table_contents:\n for key, data in table.scan():\n print(key, data)\n\n if args.completed_flag:\n print(\"Creating directory: '{}'.\".format(args.completed_flag))\n os.makedirs(args.completed_flag)\n\n except (ConnectionError, thriftpy2.transport.TTransportException) as e:\n attempts = attempts + 1\n print(\"Failed to connect: '{}', attempt no {}.\".format(e, attempts))\n time.sleep(3)\n\n exit(0 if connected else 1)\n\n\ndef encrypt(key, plaintext):\n initialisation_vector = Random.new().read(AES.block_size)\n iv_int = int(binascii.hexlify(initialisation_vector), 16)\n counter = Counter.new(AES.block_size * 8, initial_value=iv_int)\n aes = AES.new(key.encode(\"utf8\"), AES.MODE_CTR, counter=counter)\n ciphertext = aes.encrypt(plaintext.encode(\"utf8\"))\n return (base64.b64encode(initialisation_vector),\n base64.b64encode(ciphertext))\n\ndef uc_object():\n return {\n \"_id\": {\n \"declarationId\": \"aaaa1111-abcd-4567-1234-1234567890ab\"\n },\n \"type\": \"addressDeclaration\",\n \"contractId\": \"aa16e682-fbd6-4fe3-880b-118ac09f992a\",\n \"addressNumber\": {\n \"type\": \"AddressLine\",\n \"cryptoId\": \"bd88a5f9-ab47-4ae0-80bf-e53908457b60\"\n },\n \"addressLine2\": None,\n \"townCity\": {\n \"type\": \"AddressLine\",\n \"cryptoId\": \"9ca3c63c-cbfc-452a-88fd-bb97f856fe60\"\n },\n \"postcode\": \"SM5 2LE\",\n \"processId\": \"3b313df5-96bc-40ff-8128-07d496379664\",\n \"effectiveDate\": {\n \"type\": \"SPECIFIC_EFFECTIVE_DATE\",\n \"date\": 20150320,\n \"knownDate\": 20150320\n },\n \"paymentEffectiveDate\": {\n \"type\": \"SPECIFIC_EFFECTIVE_DATE\",\n \"date\": 20150320,\n \"knownDate\": 20150320\n },\n \"createdDateTime\": {\n \"$date\":\"2015-03-20T12:23:25.183Z\"\n },\n \"_version\": 2,\n \"_lastModifiedDateTime\": {\n \"$date\": \"2018-12-14T15:01:02.000+0000\"\n }\n }\n\n\ndef guid():\n return str(uuid.uuid4())\n\n\ndef uniq_db_object():\n record = uc_object()\n record['_id']['declarationId'] = guid()\n record['contractId'] = guid()\n record['addressNumber']['cryptoId'] = guid()\n record['townCity']['cryptoId'] = guid()\n record['processId'] = guid()\n return record\n\n\ndef command_line_args():\n parser = argparse.ArgumentParser(description='Pre-populate hbase.')\n parser.add_argument('-c', '--completed-flag',\n help='The flag to write on successful completion.')\n parser.add_argument('-d', '--dump-table-contents', action='store_true',\n help='Dump table contents after inserts.')\n parser.add_argument('-k', '--data-key-service',\n help='Use the specified data key service.')\n parser.add_argument('-o', '--remove-output-file',\n help='Remove the output file.')\n parser.add_argument('-s', '--skip-table-creation', action='store_true',\n help='Do not create the target table.')\n parser.add_argument('-t', '--destination-table', default='ucdata',\n help='The table to write the records to.')\n parser.add_argument('-z', '--zookeeper-quorum', default='hbase',\n help='The zookeeper quorum host.')\n parser.add_argument('sample_data_file',\n help='File containing the sample data.')\n return parser.parse_args()\n\n\ndef init(args):\n if args.completed_flag:\n if os.path.isdir(args.completed_flag):\n print(\"Removing directory '{}'.\".format(args.completed_flag))\n os.removedirs(args.completed_flag)\n elif os.path.isfile(args.completed_flag):\n print(\"Removing file '{}'.\".format(args.completed_flag))\n os.remove(args.completed_flag)\n else:\n print(\"Argument --completed-flag was set but no file or folder to remove\")\n else:\n print(\"Argument --completed-flag not set, no file removed\")\n\n if args.remove_output_file:\n if os.path.isfile(args.remove_output_file):\n print(\"Removing file '{}'.\".format(args.remove_output_file))\n os.remove(args.remove_output_file)\n else:\n print(\"Argument --remove-output-file not set, no file removed\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/populate_hbase.py","file_name":"populate_hbase.py","file_ext":"py","file_size_in_byte":7362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"166596514","text":"# Copyright 1996-2021 Cyberbotics Ltd.\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\"\"\"Adapted from the Example of Python controller for Nao robot.\n\n This is a demo of dancing nao robots created by Milindi Kodikara\n Sound track - Bee Gees' Staying Alive\"\"\"\n\nfrom controller import Robot, Keyboard, Motion\nimport time\nfrom datetime import datetime, timedelta\nimport playsound\nfrom pygame import mixer\n\n\nclass Nao(Robot):\n PHALANX_MAX = 8\n\n # load motion files\n def loadMotionFiles(self):\n self.stand = (Motion('../../motions/StandUpFromFront.motion'), 4.2)\n self.fall = (Motion('../../motions/Fall.motion'), 3)\n \n self.handWave = (Motion('../../motions/HandWave.motion'), 2)\n self.handWaveLeft = (Motion('../../motions/HandWaveLeft.motion'), 2)\n\n self.forwards50 = (Motion('../../motions/Forwards50.motion'), 2.8)\n self.forwards = (Motion('../../motions/Forwards.motion'), 2.8)\n self.backwards = (Motion('../../motions/Backwards.motion'), 2)\n\n self.sideStepLeft = (Motion('../../motions/SideStepLeft.motion'), 5)\n self.sideStepLeft4 = (Motion('../../motions/SideStepLeft.motion'), 3.5)\n self.sideStepRight = (Motion('../../motions/SideStepRight.motion'), 3.5)\n\n self.turnLeft60 = (Motion('../../motions/TurnLeft60.motion'), 4.6)\n self.turnRight60 = (Motion('../../motions/TurnRight60.motion'), 4.8)\n\n self.turnRight40 = (Motion('../../motions/TurnRight40.motion'), 3)\n self.turnLeft40 = (Motion('../../motions/TurnLeft40.motion'), 3)\n\n self.turnLeft180 = (Motion('../../motions/TurnLeft180.motion'), 7.2)\n\n self.shoot = (Motion('../../motions/Shoot.motion'), 4)\n\n self.handHighRight = (Motion('../../motions/HandHighRight.motion'), 0.5)\n self.handHighLeft = (Motion('../../motions/HandHighLeft.motion'), 0.5)\n\n self.handDown = (Motion('../../motions/HandDown.motion'), 4)\n self.handsUp = (Motion('../../motions/HandsUp.motion'), 2)\n self.handsUpNoWiggle = (Motion('../../motions/HandsUpNoWiggle.motion'), 2.4)\n\n def startMotion(self, motion):\n # interrupt current motion\n if self.currentlyPlaying:\n self.currentlyPlaying.stop()\n\n # start new motion\n motion.play()\n self.currentlyPlaying = motion\n\n def setAllLedsColor(self, rgb):\n # these leds take RGB values\n for i in range(0, len(self.leds)):\n self.leds[i].set(rgb)\n\n # ear leds are single color (blue)\n # and take values between 0 - 255\n self.leds[5].set(rgb & 0xFF)\n self.leds[6].set(rgb & 0xFF)\n\n def setHandsAngle(self, angle):\n for i in range(0, self.PHALANX_MAX):\n clampedAngle = angle\n if clampedAngle > self.maxPhalanxMotorPosition[i]:\n clampedAngle = self.maxPhalanxMotorPosition[i]\n elif clampedAngle < self.minPhalanxMotorPosition[i]:\n clampedAngle = self.minPhalanxMotorPosition[i]\n\n if len(self.rphalanx) > i and self.rphalanx[i] is not None:\n self.rphalanx[i].setPosition(clampedAngle)\n if len(self.lphalanx) > i and self.lphalanx[i] is not None:\n self.lphalanx[i].setPosition(clampedAngle)\n\n def findAndEnableDevices(self):\n # get the time step of the current world.\n self.timeStep = int(self.getBasicTimeStep())\n\n # camera\n self.cameraTop = self.getDevice(\"CameraTop\")\n self.cameraBottom = self.getDevice(\"CameraBottom\")\n self.cameraTop.enable(4 * self.timeStep)\n self.cameraBottom.enable(4 * self.timeStep)\n\n # accelerometer\n self.accelerometer = self.getDevice('accelerometer')\n self.accelerometer.enable(4 * self.timeStep)\n\n # gyro\n self.gyro = self.getDevice('gyro')\n self.gyro.enable(4 * self.timeStep)\n\n # gps\n self.gps = self.getDevice('gps')\n self.gps.enable(4 * self.timeStep)\n\n # inertial unit\n self.inertialUnit = self.getDevice('inertial unit')\n self.inertialUnit.enable(self.timeStep)\n\n # ultrasound sensors\n self.us = []\n usNames = ['Sonar/Left', 'Sonar/Right']\n for i in range(0, len(usNames)):\n self.us.append(self.getDevice(usNames[i]))\n self.us[i].enable(self.timeStep)\n\n # foot sensors\n self.fsr = []\n fsrNames = ['LFsr', 'RFsr']\n for i in range(0, len(fsrNames)):\n self.fsr.append(self.getDevice(fsrNames[i]))\n self.fsr[i].enable(self.timeStep)\n\n # foot bumpers\n self.lfootlbumper = self.getDevice('LFoot/Bumper/Left')\n self.lfootrbumper = self.getDevice('LFoot/Bumper/Right')\n self.rfootlbumper = self.getDevice('RFoot/Bumper/Left')\n self.rfootrbumper = self.getDevice('RFoot/Bumper/Right')\n self.lfootlbumper.enable(self.timeStep)\n self.lfootrbumper.enable(self.timeStep)\n self.rfootlbumper.enable(self.timeStep)\n self.rfootrbumper.enable(self.timeStep)\n\n # there are 7 controlable LED groups in Webots\n self.leds = []\n self.leds.append(self.getDevice('ChestBoard/Led'))\n self.leds.append(self.getDevice('RFoot/Led'))\n self.leds.append(self.getDevice('LFoot/Led'))\n self.leds.append(self.getDevice('Face/Led/Right'))\n self.leds.append(self.getDevice('Face/Led/Left'))\n self.leds.append(self.getDevice('Ears/Led/Right'))\n self.leds.append(self.getDevice('Ears/Led/Left'))\n\n # get phalanx motor tags\n # the real Nao has only 2 motors for RHand/LHand\n # but in Webots we must implement RHand/LHand with 2x8 motors\n self.lphalanx = []\n self.rphalanx = []\n self.maxPhalanxMotorPosition = []\n self.minPhalanxMotorPosition = []\n for i in range(0, self.PHALANX_MAX):\n self.lphalanx.append(self.getDevice(\"LPhalanx%d\" % (i + 1)))\n self.rphalanx.append(self.getDevice(\"RPhalanx%d\" % (i + 1)))\n\n # assume right and left hands have the same motor position bounds\n self.maxPhalanxMotorPosition.append(self.rphalanx[i].getMaxPosition())\n self.minPhalanxMotorPosition.append(self.rphalanx[i].getMinPosition())\n\n # shoulder pitch motors\n self.RShoulderPitch = self.getDevice(\"RShoulderPitch\")\n self.LShoulderPitch = self.getDevice(\"LShoulderPitch\")\n\n # keyboard\n self.keyboard = self.getKeyboard()\n self.keyboard.enable(10 * self.timeStep)\n\n def __init__(self):\n Robot.__init__(self)\n self.currentlyPlaying = False\n\n # initialize stuff\n self.findAndEnableDevices()\n self.loadMotionFiles()\n\n def run(self):\n print(\"_________NAO DANCE BY GDSC-RMIT University__________\")\n\n # Play music using pygame\n\n mixer.init()\n\n mixer.music.load('song.mp3')\n\n mixer.music.play()\n\n time.sleep(1.5)\n\n self.handWave[0].play()\n\n # dance_steps = [self.forwards50, self.forwards50, self.forwards50, self.forwards,\n # self.handWave,\n # self.sideStepLeft,\n # self.backwards, self.backwards, self.handsUp, self.forwards50, self.forwards50,\n # self.sideStepRight, self.handWave, self.sideStepLeft4, self.handWaveLeft,\n # self.turnLeft40, self.handsUp, self.turnLeft40, self.turnLeft40,\n # self.turnLeft60, self.backwards, self.backwards, self.turnLeft60, self.turnLeft60, \n # self.turnLeft40, self.turnLeft10, self.forwards50, \n # self.sideStepRight, self.handsUpNoWiggle, \n # self.forwards50, self.handWave, self.forwards50]\n \n \n dance_steps = [self.forwards50, self.forwards50, self.forwards50, self.forwards,\n self.handWave,\n self.sideStepLeft,\n self.backwards, self.backwards, self.handsUp, self.forwards50, self.forwards50,\n self.sideStepRight, self.handWave, self.sideStepLeft4, self.handWaveLeft,\n self.turnLeft40, self.handsUp, self.turnLeft40, self.turnLeft40,\n self.turnLeft60, self.backwards, self.backwards, self.turnLeft60, self.turnLeft60,\n self.turnLeft60, self.handsUpNoWiggle,\n self.sideStepRight,\n self.forwards50, self.handWave, self.forwards50, self.forwards50,\n self.forwards50] \n\n fall = [self.fall, self.turnRight60, self.forwards50]\n\n dance_step_count = 0\n fall_count = 0\n\n for dance_step in dance_steps:\n\n dance_steps[dance_step_count][0].play()\n finish = datetime.now() + timedelta(seconds=dance_steps[dance_step_count][1])\n while finish > datetime.now():\n self.step(self.timeStep)\n\n dance_step_count = dance_step_count + 1\n\n mixer.music.stop()\n\n playsound.playsound('tape.mp3', False)\n\n for fall_step in fall:\n\n fall[fall_count][0].play()\n finish = datetime.now() + timedelta(seconds=fall[fall_count][1])\n while finish > datetime.now():\n self.step(self.timeStep)\n\n fall_count = fall_count + 1\n\n # create the Robot instance and run main loop\n\n\nrobot = Nao()\nrobot.run()\n","sub_path":"controllers/dancing_nao/dancing_nao.py","file_name":"dancing_nao.py","file_ext":"py","file_size_in_byte":10013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"507266101","text":"def mergeSort(input):\r\n\tdef merge(head, tail):\r\n\t\t#compare head of each list\r\n\t\tif head[0] < tail[0]:\r\n\t\t\t#first element of tail larger; concatenate with recursively sorted tails\r\n\t\t\treturn [head[0]] + (merge(head[1:],tail) if head[1:] else tail)\r\n\t\telse:\r\n\t\t\t#first element of head larger; concatenate with recursively sorted tails\r\n\t\t\treturn [tail[0]] + (merge(head,tail[1:]) if tail[1:] else head)\r\n\r\n\t#lists of length 1 are sorted\r\n\tif len(input) > 1:\r\n\t\t#split input and send to recursive merge function\r\n\t\thead = mergeSort(input[:int(len(input)/2)])\r\n\t\ttail = mergeSort(input[int(len(input)/2):])\r\n\t\treturn merge(head, tail)\r\n\telse:\r\n\t\treturn input","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"408213521","text":"import tensorflow as tf\nimport keras\n\nfrom keras.layers import *\n\ndef conv_block(base, filters, kernel_size, padding, strides, name):\n x = Conv2D(filters, kernel_size=kernel_size, padding=padding, strides=strides, name='conv'+name)(base)\n x = BatchNormalization(axis=3, epsilon=1.001e-5, name='batchnorm'+name)(x)\n x = Activation('relu', name='act'+name)(x)\n return x\n\ndef resnet50v2(classes=1000):\n\tinp = Input(shape=(224,224,3), name='input_layer')\n\tx = ZeroPadding2D(padding=(3, 3), name='conv0_pad')(inp)\n\tx = Conv2D(64, kernel_size=(7,7), padding='valid', strides=(2,2), activation='relu', name='conv_0')(x)\n\tx = ZeroPadding2D(padding=(1, 1), name='maxpool0_pad')(x)\n\tbase = MaxPool2D(pool_size=(3,3), strides=(2,2), name='maxpool_0')(x)\n\n\tprint('Stage 0:', base.shape)\n\n\t# Stage 1 (3 cnv_blocks)\n\tnames = ['_1_a', '_1_b', '_1_c']\n\tfor n in names:\n\t x = conv_block(base, 64, kernel_size=(1,1), padding='same', strides=(2,2), name=n+'1')\n\t x = conv_block(x, 64, kernel_size=(3,3), padding='same', strides=(1,1), name=n+'2')\n\t x1 = Conv2D(256, kernel_size=(1,1), padding='same', strides=(1,1), name='conv'+n+'3')(x)\n\t \n\t # shortcut\n\t x = BatchNormalization(axis=3, epsilon=1.001e-5, name='batchnorm'+n+'4')(base)\n\t x = Activation('relu', name='act'+n+'4')(x)\n\t shortcut = Conv2D(256, kernel_size=(1,1), padding='same', strides=(2,2), name='conv'+n+'4')(x)\n\t base = Add(name='add'+n+'1')([x1, shortcut])\n\t \n\n\tprint('Stage 1:', base.shape)\n\t \n\t# Stage 2 (4 cnv_blocks)\n\tnames = ['_2_a', '_2_b', '_2_c', '_2_d']\n\tfor n in names:\n\t x = conv_block(base, 128, kernel_size=(1,1), padding='same', strides=(2,2), name=n+'1')\n\t x = conv_block(x, 128, kernel_size=(3,3), padding='same', strides=(1,1), name=n+'2')\n\t x1 = Conv2D(512, kernel_size=(1,1), padding='same', strides=(1,1), name='conv'+n+'3')(x)\n\t \n\t # shortcut\n\t x = BatchNormalization(axis=3, epsilon=1.001e-5, name='batchnorm'+n+'4')(base)\n\t x = Activation('relu', name='act'+n+'4')(x)\n\t shortcut = Conv2D(512, kernel_size=(1,1), padding='same', strides=(2,2), name='conv'+n+'4')(x)\n\t base = Add(name='add'+n+'1')([x1, shortcut])\n\n\tprint('Stage 2:', base.shape)\n\t \n\t# Stage (6 cnv_blocks)\n\tnames = ['_3_a', '_3_b', '_3_c', '_3_d', '_3_e', '_3_f']\n\tfor n in names:\n\t x = conv_block(base, 256, kernel_size=(1,1), padding='same', strides=(2,2), name=n+'1')\n\t x = conv_block(x, 256, kernel_size=(3,3), padding='same', strides=(1,1), name=n+'2')\n\t x1 = Conv2D(1024, kernel_size=(1,1), padding='same', strides=(1,1), name='conv'+n+'3')(x)\n\t \n\t # shortcut\n\t x = BatchNormalization(axis=3, epsilon=1.001e-5, name='batchnorm'+n+'4')(base)\n\t x = Activation('relu', name='act'+n+'4')(x)\n\t shortcut = Conv2D(1024, kernel_size=(1,1), padding='same', strides=(2,2), name='conv'+n+'4')(x)\n\t base = Add(name='add'+n+'1')([x1, shortcut])\n\n\tprint('Stage 3:', base.shape)\n\n\t# Stage (3 cnv_blocks)\n\tnames = ['_4_a', '_4_b', '_4_c']\n\tfor n in names:\n\t x = conv_block(base, 512, kernel_size=(1,1), padding='same', strides=(2,2), name=n+'1')\n\t x = conv_block(x, 512, kernel_size=(3,3), padding='same', strides=(1,1), name=n+'2')\n\t x1 = Conv2D(2048, kernel_size=(1,1), padding='same', strides=(1,1), name='conv'+n+'3')(x)\n\t \n\t # shortcut\n\t x = BatchNormalization(axis=3, epsilon=1.001e-5, name='batchnorm'+n+'4')(base)\n\t x = Activation('relu', name='act'+n+'4')(x)\n\t shortcut = Conv2D(2048, kernel_size=(1,1), padding='same', strides=(2,2), name='conv'+n+'4')(x)\n\t base = Add(name='add'+n+'1')([x1, shortcut])\n\n\tprint('Stage 4:', base.shape)\n\n\tout = GlobalAveragePooling2D(name='global_avg_1')(base)\n\tout = Dense(classes, activation='softmax', name='dense_1')(out)\n\n\tmodel = keras.Model(inputs=inp, outputs=out, name=\"resnet50v2_model\")\n\n\topt = keras.optimizers.Adam(lr=0.001)\n\tmodel.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])\n\n\treturn model","sub_path":"TODO/resnet50v2.py","file_name":"resnet50v2.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"245984111","text":"#\n# GETNEXT Command Generator Application\n#\n# Perform SNMP GETNEXT operation with the following options:\n#\n# * with SNMPv2c, community 'public'\n# * over IPv4/UDP\n# * to an Agent at demo.snmplabs.com:161\n# * for an OID in string form\n# * resolve response OIDs and values into human-freidly form\n# * stop when response OIDs leave the scopes of initial OIDs\n#\n# This script performs similar to the following Net-SNMP command:\n# \n# $ snmpwalk -v2c -c public demo.snmplabs.com 1.3.6.1.2.1.1\n#\n# The lookupNames and lookupValues keyword arguments will make pysnmp\n# trying to resolve OIDs and values, in response variable-bindings,\n# into human-friendly form. If response OIDs do not belong to any of \n# currently loaded MIBs, unresolved OIDs and values will still be\n# returned.\n#\nfrom pysnmp.entity.rfc3413.oneliner import cmdgen\n\ncmdGen = cmdgen.CommandGenerator()\n\nerrorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(\n cmdgen.CommunityData('public'),\n cmdgen.UdpTransportTarget(('demo.snmplabs.com', 161)),\n '1.3.6.1.2.1.1',\n lookupNames=True, lookupValues=True\n)\n\nif errorIndication:\n print(errorIndication)\nelse:\n if errorStatus:\n print('%s at %s' % (\n errorStatus.prettyPrint(),\n errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'\n )\n )\n else:\n for varBindTableRow in varBindTable:\n for name, val in varBindTableRow:\n print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))\n","sub_path":"examples/v3arch/oneliner/manager/cmdgen/getnext-v2c-with-mib-resolution.py","file_name":"getnext-v2c-with-mib-resolution.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"619638550","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n#@created: 05.06.2011\r\n#@author: Aleksey Komissarov\r\n#@contact: ad3002@gmail.com \r\n'''\r\nSRA files.\r\nTODO: implement this.\r\nTODO: separate model from reader\r\n'''\r\n\r\nfrom trseeker.tools.sequence_tools import get_revcomp, get_gc\r\nfrom trseeker.tools.sequence_tools import clear_sequence\r\nimport re\r\ntry:\r\n from Bio import pairwise2\r\nexcept:\r\n print(\"Not Bio installed\")\r\nimport random\r\nfrom PyExp import WiseOpener\r\n\r\nclass FastqObj(object):\r\n\r\n def __init__(self, head, seq, strain, qual, phred33=False):\r\n self.head = head.strip()\r\n self.seq = seq.strip()\r\n self.qual = qual.strip()\r\n self.strain = strain.strip()\r\n self.id = head.strip().replace(\"#\", \" \").split()[0].replace(\"@\",\"\")\r\n # trimmeing input\r\n self.trimmed_seq = self.seq.strip()\r\n self.trimmed_qual = qual.strip()\r\n if phred33:\r\n self.qv = [ord(x)-33 for x in qual.strip()]\r\n # trimming results\r\n self.adaptor_positions = []\r\n self.adapter_contamination = None\r\n self.qual_junk = None\r\n self.status = True\r\n self.parts = []\r\n self.id = self.read_id_hiseq15\r\n \r\n\r\n\r\n @property\r\n def fastq(self):\r\n return \"%s\\n%s\\n%s\\n%s\\n\" % (\r\n self.head,\r\n self.seq.upper(),\r\n self.strain,\r\n self.qual,\r\n )\r\n\r\n\r\n def change_strain(self):\r\n if self.strain == \"+\":\r\n self.strain = \"-\"\r\n elif self.strain == \"-\":\r\n self.strain = \"+\"\r\n\r\n def split_read(self, position, step):\r\n ''' Return two new read_objs splitted by position.\r\n '''\r\n head1 = self.head+\":s1\"\r\n head2 = self.head+ \":s2\"\r\n seq1 = self.seq[:position]\r\n seq2 = self.seq[position-step:]\r\n qual1 = self.qual[:position]\r\n qual2 = self.qual[position-step:]\r\n read1 = FastqObj(head1, seq1, self.strain, qual1)\r\n read2 = FastqObj(head2, seq2, self.strain, qual2)\r\n return read1, read2\r\n\r\n\r\n def check_and_fix_read_q_legnths(self):\r\n\r\n l1 = len(self.seq)\r\n l2 = len(self.qual)\r\n if l1 != l2:\r\n l = min(l1, l2)\r\n self.seq = self.seq[:l]\r\n self.qual = self.qual[:l]\r\n return 1\r\n return 0\r\n\r\n\r\n def make_reversed(self):\r\n '''\r\n '''\r\n self.seq = self.seq[::-1]\r\n self.qual = self.qual[::-1]\r\n\r\n def fastq_with_error(self, error):\r\n return \"@%s__%s\\n%s\\n%s\\n%s\\n\" % (\r\n error,\r\n self.head[1:],\r\n self.seq,\r\n self.strain,\r\n self.qual,\r\n )\r\n\r\n def fastq_with_cov(self, cov):\r\n cov = \",\".join(map(str, cov))\r\n return \"%s%s\\n%s\\n%s\\n\" % (\r\n self.head,\r\n self.trimmed_seq,\r\n cov,\r\n self.trimmed_qual,\r\n )\r\n\r\n @property\r\n def trimmed_fastq(self):\r\n return \"%s%s\\n%s%s\\n\" % (\r\n self.head,\r\n self.trimmed_seq,\r\n self.strain,\r\n self.trimmed_qual,\r\n )\r\n\r\n @property\r\n def sequence(self):\r\n return self.seq.strip()\r\n\r\n @property\r\n def fasta(self):\r\n return \">%s\\n%s\\n\" % (\r\n self.head.strip(),\r\n self.seq.strip(),\r\n )\r\n\r\n @property\r\n def gc(self):\r\n return get_gc(self.seq)\r\n\r\n @property\r\n def length(self):\r\n return len(self.seq)\r\n\r\n @property\r\n def read_id(self):\r\n self.id = int(self.head.split()[0].split(\".\")[-1])\r\n return self.id\r\n\r\n @property\r\n def read_id_and_pair(self):\r\n try:\r\n self.id = int(self.head.split()[0].split(\".\")[-1])\r\n except:\r\n self.id = self.head.split()[0]\r\n self.pair = int(self.head.split()[1].split(\":\")[0])\r\n return self.id, self.pair\r\n\r\n @property\r\n def read_id_hiseq15(self):\r\n self.id = self.head.replace(\"#\", \" \").split()[0]\r\n return self.id\r\n\r\n def trim(self):\r\n '''\r\n '''\r\n raise NotImplemented\r\n \r\n def trim_by_quality_cutoff(self, cutoff=30):\r\n '''\r\n '''\r\n for i, q in enumerate(self.qv):\r\n if q < cutoff:\r\n self.trimmed_seq = self.trimmed_seq[:i]\r\n self.trimmed_qual = self.trimmed_qual[:i]\r\n self.qual_junk = self.trimmed_seq[i:]\r\n break\r\n\r\n def trim_exact_adaptor(self, adaptor, verbose=False):\r\n '''\r\n '''\r\n raise NotImplemented\r\n \r\n def trim_inexact_adaptor(self, adaptor, verbose=False, num_errors=2):\r\n '''\r\n '''\r\n raise NotImplemented\r\n\r\n def iter_kmers(self, k=23):\r\n '''\r\n '''\r\n for i in xrange(len(self.seq)-k+1):\r\n yield i, self.seq[i:i+k]\r\n\r\nclass PERun(object):\r\n pass\r\n\r\ndef fastq_reader(fastq_file, phred33=False, head_pattern=None):\r\n with WiseOpener(fastq_file) as fh:\r\n while True:\r\n try:\r\n head = fh.readline()\r\n if head == '':\r\n break\r\n if head_pattern:\r\n if not re.match(head_pattern, head):\r\n continue\r\n seq = fh.readline()\r\n strain = fh.readline()\r\n qual = fh.readline()\r\n fastq_obj = FastqObj(head, seq, strain, qual, phred33=phred33)\r\n yield fastq_obj\r\n except:\r\n break\r\n\r\ndef fastq_pe_reader(fastq_file1, fastq_file2, phred33=False, head_pattern=None):\r\n with WiseOpener(fastq_file1) as fh1:\r\n with WiseOpener(fastq_file2) as fh2:\r\n while True:\r\n try:\r\n head1 = fh1.readline()\r\n head2 = fh2.readline()\r\n if head1 == '':\r\n break\r\n if head_pattern:\r\n if not re.match(head_pattern, head1):\r\n continue\r\n seq1 = fh1.readline()\r\n strain1 = fh1.readline()\r\n qual1 = fh1.readline()\r\n fastq_obj1 = FastqObj(head1, seq1, strain1, qual1, phred33=phred33)\r\n\r\n seq2 = fh2.readline()\r\n strain2 = fh2.readline()\r\n qual2 = fh2.readline()\r\n fastq_obj2 = FastqObj(head2, seq2, strain2, qual2, phred33=phred33)\r\n\r\n yield fastq_obj1, fastq_obj2\r\n except:\r\n break\r\n\r\ndef fastq_iter_seqs_pe(fastq_file1, fastq_file2):\r\n with WiseOpener(fastq_file1) as fh1:\r\n with WiseOpener(fastq_file2) as fh2:\r\n while True:\r\n try:\r\n fh1.readline()\r\n seq1 = fh1.readline()\r\n fh1.readline()\r\n fh1.readline()\r\n \r\n fh2.readline()\r\n seq2 = fh2.readline()\r\n fh2.readline()\r\n fh2.readline()\r\n \r\n yield seq1, seq2\r\n except:\r\n break\r\n\r\ndef read_qual_reader(read_file, qual_file, phred33=False):\r\n \"\"\" Read fastq_obj from two files:\r\n with reads\r\n with corresponding quals\r\n \"\"\"\r\n with open(read_file) as fh:\r\n with open(qual_file) as qfh:\r\n rid = 0\r\n while True:\r\n try:\r\n seq = fh.readline()\r\n qual = qfh.readline()\r\n fastq_obj = FastqObj(\"@%s\" % rid, seq, \"+\", qual, phred33=phred33)\r\n yield fastq_obj\r\n rid += 1\r\n except Exception as e:\r\n print(e)\r\n break\r\n\r\ndef read_simple_qual_reader(read_file, qual_file, phred33=False):\r\n \"\"\" Read fastq_obj from two files:\r\n with reads\r\n with corresponding quals\r\n \"\"\"\r\n with open(read_file) as fh:\r\n with open(qual_file) as qfh:\r\n rid = 0\r\n while True:\r\n try:\r\n yield rid, fh.readline().strip(), qfh.readline().strip()\r\n rid += 1\r\n except Exception as e:\r\n print(e)\r\n break\r\n\r\ndef error_aware_fastq_reader(fastq_file, phred33=False, header=None):\r\n errors = 0\r\n ok = 0\r\n data = []\r\n with open(fastq_file) as fh:\r\n while True:\r\n # check head\r\n head = fh.readline()\r\n if not head:\r\n return\r\n if header and not head.startswith(header):\r\n print(\"Error with head:\", head.strip())\r\n errors += 1\r\n continue\r\n seq = fh.readline()\r\n if not seq[0].upper() in [\"A\", \"C\", \"T\", \"G\", \"N\"]:\r\n print()\r\n print(\"Error with seq:\", seq.strip())\r\n errors += 1\r\n continue\r\n strain = fh.readline()\r\n if header and strain.startswith(header):\r\n print()\r\n print(\"Error with strain:\", strain.strip())\r\n errors += 1\r\n continue\r\n qual = fh.readline()\r\n if header and qual.startswith(header):\r\n print()\r\n print(\"Error with qual:\", qual.strip())\r\n errors += 1\r\n continue\r\n if not len(qual) == len(seq):\r\n print()\r\n print(\"Error with qual length:\", qual.strip())\r\n errors += 1\r\n continue\r\n ok += 1\r\n fastq_obj = FastqObj(head, seq, strain, qual, phred33=phred33)\r\n # print errors, ok\r\n yield fastq_obj\r\n\r\n\r\ndef generate_fastq(seq, i, pair):\r\n head = \"@ART_%s %s\" % (i, pair)\r\n qual = \"\".join([random.choice([\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"I\"]) for x in range(len(seq))])\r\n return \"%s\\n%s\\n+\\n%s\\n\" % (\r\n head,\r\n seq.upper(),\r\n qual,\r\n )\r\n\r\n\r\ndef iter_sorted_pe_data(fastq1_file, fastq2_file):\r\n ''' Iterate over sorted PE fastq files.\r\n '''\r\n reader1 = error_aware_fastq_reader(fastq1_file)\r\n reader2 = error_aware_fastq_reader(fastq2_file)\r\n while True:\r\n read1 = None\r\n read2 = None\r\n if reader1 is None and reader2 is None:\r\n return\r\n if reader1:\r\n try:\r\n read1 = next(reader1)\r\n except StopIteration:\r\n read1 = None\r\n reader1 = None\r\n if reader2:\r\n try:\r\n read2 = next(reader2)\r\n except StopIteration:\r\n read2 = None\r\n reader2 = None\r\n if not read1:\r\n yield None, read2\r\n continue\r\n if not read2:\r\n yield read1, None\r\n continue\r\n if read1 and read2 and read1.id == read2.id:\r\n yield read1, read2\r\n continue\r\n if read1 and read2 and read1.id < read2.id:\r\n while True:\r\n yield read1, None\r\n if reader1:\r\n try:\r\n read1 = next(reader1)\r\n except StopIteration:\r\n read1 = None\r\n reader1 = None\r\n break\r\n else:\r\n break \r\n if read1.id == read2.id:\r\n yield read1, read2\r\n break\r\n if read1 and read2 and read1.id > read2.id:\r\n while True:\r\n yield None, read2\r\n if reader2:\r\n try:\r\n read2 = next(reader2)\r\n except StopIteration:\r\n read2 = None\r\n reader2 = None\r\n break\r\n else:\r\n break\r\n if read1.id == read2.id:\r\n yield read1, read2\r\n break","sub_path":"trseeker/seqio/sra_file.py","file_name":"sra_file.py","file_ext":"py","file_size_in_byte":12424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"497830914","text":"from flask import Flask, render_template, request\nimport pandas as pd\nimport json\nfrom visual_test import geo_1, line_smooth,map_visualmap,bar3, practitioner_bar,bar_base_with_animation, visitor_bar2,GDP_line, DIC_scatter, compare_bar3,book_distribute_map,library_and_museum_distribute,bar_stack0, museum_related_info_bar\nfrom pyecharts.charts import Page\nimport plotly as py\nimport numpy as np\n\nfrom jinja2 import Markup\n\napp = Flask(__name__)\n\ndf = pd.read_csv('/home/jidemn/mysite/All.csv',encoding=\"gbk\")\nregions_available_loaded = list(df[\"指标\"].dropna().unique())\n\nBQ = df[df['指标']== \"BaseQuantity\" ]\nC = df[df['指标']== \"Collection\" ]\nV = df[df['指标']== \"Visitors\" ]\nP = df[df['指标']== \"Practitioner\" ]\nPCF = df[df['指标']== \"PublicCulturalFinance\" ]\nCSMF = df[df['指标']== \"CultureSportsMediaFinance\" ]\nGDP = df[df['指标']== \"GDP\" ]\nP2 = df[df['指标']== \"Population\" ]\nBC = df[df['指标']== \"BookCollection\" ]\nNOLI = df[df['指标']== \"NumberOfLibraryInstitutions\" ]\nDIPC = df[df['指标']== \"DisposableIncomePerCapita\" ]\n\n\nDQ = BQ['地区']\nDQ = list(DQ)\nDQ1 = [dq.replace('市', '') for dq in DQ]\nDQ2 = [dq.replace('省', '') for dq in DQ1]\nDQ3 = [dq.replace('自治区', '') for dq in DQ2]\nDQ4 = [dq.replace('壮族', '') for dq in DQ3]\nDQ5 = [dq.replace('回族', '') for dq in DQ4]\nDQ_end = [dq.replace('维吾尔', '') for dq in DQ5]\n\n\nBQ2018 = list(BQ['2018年'])\nBQ2017 = list(BQ['2017年'])\nBQ2016 = list(BQ['2016年'])\nBQ2015 = list(BQ['2015年'])\nBQ2014 = list(BQ['2014年'])\nBQ2013 = list(BQ['2013年'])\nBQ2012 = list(BQ['2012年'])\nBQ2011 = list(BQ['2011年'])\nBQ2010 = list(BQ['2010年'])\n\n\nx = [list(z) for z in zip(DQ_end,BQ2018)]\n\n\nDQ = BQ['地区']\nDQ = list(DQ)\n\nv2018 = V['2018年']\nv2018 = list(v2018)\n\np2018 = P['2018年']\np2018 = list(p2018)\n\ncoll2018 = C['2018年']\ncoll2018 = list(coll2018)\n\ncoll2017 = C['2017年']\ncoll2017 = list(coll2017)\n\ncoll2016 = C['2016年']\ncoll2016 = list(coll2016)\n\ncoll2015 = C['2015年']\ncoll2015 = list(coll2015)\n\n\ny1 = [list(z) for z in zip(DQ_end,coll2018)]\n\ny2 = [list(z) for z in zip(DQ_end,coll2017)]\n\ny3 = [list(z) for z in zip(DQ_end,coll2016)]\n\ny4 = [list(z) for z in zip(DQ_end,coll2015)]\n\nf12018 = list(PCF[\"2018年\"])\nf22018 = list(CSMF[\"2018年\"])\n\n\n\nbx =[list(z) for z in zip(DQ_end,BC[\"2018年\"])]\n\n\n\ndef plot_all(kw):\n page = Page(layout=Page.SimplePageLayout)\n kw_map = {\"BaseQuantity\": [geo_1, line_smooth],\n \"Collection\": [map_visualmap],\n \"Practitioner\": [bar3, practitioner_bar],\n \"Visitors\": [bar_base_with_animation, visitor_bar2],\n \"GDP\": [GDP_line, DIC_scatter, compare_bar3],\n \"Population\": [GDP_line, DIC_scatter, compare_bar3],\n \"BookCollection\": [book_distribute_map,library_and_museum_distribute],\n \"PublicCulturalFinance\": [bar_stack0, museum_related_info_bar],\n \"CultureSportsMediaFinance\": [bar_stack0, museum_related_info_bar],\n \"NumberOfLibraryInstitutions\": [book_distribute_map,library_and_museum_distribute],\n \"DisposableIncomePerCapita\": [GDP_line, DIC_scatter, compare_bar3]\n }\n for f in kw_map[kw]:\n page.add(f())\n return page.render_embed()\n\n\nplot_desc = {\"BaseQuantity\": \" 从这两页的数据我们可以看出近八年间,山东、河南、浙江、陕西、四川等地的博物馆机构数激增。\\\n 尤其是山东省从2010年的114个狂涨到2018年的517个。从地图上看,2018年,我国博物馆机构主要集中于黄河中下游、长江下游地区。\\\n 和中国文明发展的方向基本一致,历史发展比较久远且兴盛的地区能够出现更多博物馆机构。\\\n 同时我们可以看见马太效应在这其中也有一定的显现,原本博物馆数量较多的地区博物馆增长量要比原本博物馆数量较少的地区要多很多,山东就是其中一个例子。\",\n \"Collection\": \"我国主要的博物馆收藏品分布在山东、陕西、四川三个大省,并明显呈现出东多西少的区域分布状况。这和我们对博物馆的原有印象也基本一致。\\\n 但是经济发达的地区不一定是博物馆发展最多的,当然,也一定的存在有博物馆的资源集中化的现象。就像北京,绝大多数的资源都集中到了故宫博物馆以及国家博物馆中。\" ,\n \"Practitioner\": \"陕西作为旅游胜地,博物馆规模大,从业人员多是可想而知的。其次,江苏地区有大量参观者进入,也容易催生一大批从业人员。\\\n 但从这里我们可以发现,从业人员的多寡与该地区机构数的多少并不是相互呼应的。同时,和博物馆的参观人数对比也可以看见两者的峰值都出现在不同的位置。\\\n 这和各地区博物馆的知名度、旅游人数、单个博物馆的机构大小也有一定的关系。\",\n \"Visitors\": \"结合我们之前学到的地理知识,我们观察到一个现象:在经济发达地区附近的比较郊区的地区会有比较多的参观者,尤其是观察长江三角洲地区。\\\n 另外,历史文化底蕴丰富的陕西也是参观者众多的地区。兵马俑、古长安皆在此地。\",\n \"GDP\": \"结合我们之前学到的地理知识,我们观察到一个现象:在经济发达地区附近的比较郊区的地区会有比较多的参观者,尤其是观察长江三角洲地区。\\\n 另外,历史文化底蕴丰富的陕西也是参观者众多的地区。兵马俑、古长安皆在此地。同时我们也可以知道,经济对于博物馆而言影响并没有我们想象中的大,\\\n 不能完全成为决定性影响。博物馆的发展是一个天时地利人和的结果,该地区原有的历史文化底蕴、时代经历在这其中有着很重要的地位。\",\n \"Population\": \"结合我们之前学到的地理知识,我们观察到一个现象:在经济发达地区附近的比较郊区的地区会有比较多的参观者,尤其是观察长江三角洲地区。\\\n 另外,历史文化底蕴丰富的陕西也是参观者众多的地区。兵马俑、古长安皆在此地。\",\n \"BookCollection\": \"经对比可以看见,书籍收藏分布与博物馆收藏分布之间还是有不少的重合点。可以看见,江苏、山东、四川、河南、上海等地对于公共文化服务的重视程度是比较高的。\",\n \"PublicCulturalFinance\": \"从图中可以看出 广东省在对于公共服务及文化输出的财政投入最大,博物馆机构数最多的山东省的投入反倒没有那么突出。\\\n 从这两个图的对比我们可以充分明白,经济投入与博物馆机构建设数量之间相关性并不强,但投入较少的海南、青海、宁夏等地博物馆机构数确实比较少,这里倒是显示出一致性。\",\n \"CultureSportsMediaFinance\": \"从图中可以看出 广东省在对于公共服务及文化输出的财政投入最大,博物馆机构数最多的山东省的投入反倒没有那么突出。\\\n 从这两个图的对比我们可以充分明白,经济投入与博物馆机构建设数量之间相关性并不强,但投入较少的海南、青海、宁夏等地博物馆机构数确实比较少。\",\n \"NumberOfLibraryInstitutions\": \"经对比可以看见,书籍收藏分布与博物馆收藏分布之间还是有不少的重合点。可以看见,江苏、山东、四川、上海等地对于公共文化服务的重视程度是比较高的。\",\n \"DisposableIncomePerCapita\": \"结合我们之前学到的地理知识,我们观察到一个现象:在经济发达地区附近的比较郊区的地区会有比较多的参观者,尤其是观察长江三角洲地区。\\\n 另外,历史文化底蕴丰富的陕西也是参观者众多的地区。兵马俑、古长安皆在此地。人们可支配收入的提升也会提高人们对于精神文化的追求,提高人们对于公共文化服务的重视程度。\"\n }\n\n@app.route('/',methods=['GET'])\ndef hu_run_2019():\n\n data_str = df.to_html()\n\n\n regions_available = regions_available_loaded\n return render_template('results2.html',\n the_res = data_str,\n the_select_region=regions_available)\n\n\n\n@app.route('/first',methods=['POST'])\ndef hu_run_select() -> 'html':\n\n\n\n the_region = request.form[\"the_region_selected\"]\n print(the_region)\n\n dfs = df.query(\"指标=='{}'\".format(the_region))\n\n\n data_str = dfs.to_html()\n\n\n regions_available = regions_available_loaded\n return render_template('results2.html',\n the_plot_all=plot_all(the_region),\n echart_desc=plot_desc[the_region],\n the_res=data_str,\n the_select_region=regions_available,\n )\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"visual_end.py","file_name":"visual_end.py","file_ext":"py","file_size_in_byte":9187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"426957294","text":"from django.conf.urls import patterns, url\nfrom django.views.generic.base import TemplateView\nfrom . import views\n\n\nurlpatterns = patterns(\n 'finance.cost.views',\n url(r\"^$\", \"index\"),\n url(r\"^graph/$\", \"graph\"),\n url(r\"^graph/json/$\", \"graph_json\"),\n url(r\"^graph/json/circle/$\", \"circle_graph_json\"),\n)\n","sub_path":"finance/cost/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"232746660","text":"#-*- coding:utf-8 -*-\nimport random\n\nl=list()\n\nfor line in open(\"rt-polarity.pos\",\"rb\"):\n l+=[\"+1 \"+line.decode(\"iso8859\")]\nfor line in open(\"rt-polarity.neg\",\"rb\"):\n l+=[\"-1 \"+line.decode(\"iso8859\")]\n\nrandom.shuffle(l)\n\nwith open(\"sentiment.txt\",\"w\") as f:\n for item in l:\n f.write(item)\n\nc_p=0\nc_n=0\nfor line in open(\"sentiment.txt\",\"r\"):\n if line.split(\" \")[0]==\"+1\":\n c_p+=1\n else:\n c_n+=1\nprint(str(c_p)+\"\\t\"+str(c_n))\n","sub_path":"osaki/chapter08/knock70.py","file_name":"knock70.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"197715865","text":"# custom function to create chart visualization plotting price, the algorithm's score, and slope of score line\r\n# inputs required are individual company ticker, the dataframe created by the algorithm, and choice of score indicator produced by the algorithm\r\n\r\ndef main_chart(ticker, df, indicator):\r\n df_plot = df\r\n score_color = 'cyan'\r\n price_color = '#00ff88'\r\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\r\n \r\n fig.add_trace(\r\n go.Scatter(\r\n x=df_plot['obs_date'], \r\n y=df_plot['price'], \r\n name='price', \r\n line=dict(\r\n color=price_color\r\n )\r\n ),\r\n secondary_y=False,\r\n )\r\n # -- Add functionality to toggle the trends\r\n fig.add_trace(\r\n go.Scatter(\r\n x=df_plot['obs_date'], \r\n y=df_plot['bestfit'], \r\n name='Score Trend', \r\n line=dict(\r\n color=score_color\r\n )\r\n ),\r\n secondary_y=True,\r\n )\r\n \r\n fig.add_trace(\r\n go.Scatter(\r\n x=df_plot['obs_date'], \r\n y=df_plot[indicator], \r\n name='Score', \r\n line=dict(\r\n color=score_color\r\n )\r\n ),\r\n secondary_y=True,\r\n )\r\n \r\n fig.update_layout(\r\n xaxis_rangeslider_visible = False,\r\n width = 900,\r\n height = 400,\r\n margin = dict(t=50, r=5, l=5, b=5),\r\n # paper_bgcolor = '#090909',\r\n paper_bgcolor = '#1B1B1B',\r\n plot_bgcolor = '#1B1B1B',\r\n font = dict(\r\n color='white',\r\n family='arial'\r\n ),\r\n # font_family='Arial',\r\n xaxis = dict(\r\n showgrid=False, \r\n zeroline=False\r\n ),\r\n yaxis = dict(\r\n showgrid=False, \r\n zeroline=False, \r\n ticks='inside'\r\n ),\r\n yaxis2 = dict(\r\n showgrid=False, \r\n zeroline=False, \r\n ticks='inside'\r\n ),\r\n showlegend = False,\r\n title = dict(\r\n text=ticker,\r\n font=dict(\r\n size=24\r\n )\r\n ),\r\n # annotations for future buy/sell signals. x/y location to be dynamic based on signal output\r\n # annotations=[\r\n # dict(text='BUY', x='2020-03-23', y=212.59),\r\n # dict(text='SELL', x='2020-02-19', y=314.37)\r\n # ]\r\n )\r\n # fig.update_xaxes(title_text='Date')\r\n fig.update_yaxes(\r\n title=dict(\r\n text='Price', \r\n font=dict(\r\n size=16\r\n )\r\n ), \r\n secondary_y=False, \r\n color=price_color\r\n )\r\n fig.update_yaxes(\r\n title=dict(\r\n text='Score', \r\n font=dict(\r\n size=16\r\n )\r\n ), \r\n secondary_y=True, \r\n color=score_color\r\n )\r\n chart = plot(fig, output_type='div')\r\n fig.show()\r\n # return chart","sub_path":"custom chart.py","file_name":"custom chart.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"243130071","text":"\"\"\"\nQuickBot wiring config.\n\nSpecifies which pins are used for motor control, IR sensors and wheel encoders.\n\"\"\"\n\n# Motor pins: (dir1_pin, dir2_pin, pwd_pin)\nRIGHT_MOTOR_PINS = 13, 19, 26\nLEFT_MOTOR_PINS = 20, 16, 21\n\n# IR sensors (clock-wise, starting with the rear left sensor):\n# rear-left, front-left, front, front-right, rear-right\n# Pair indicating ADC (ADC1 or ADC2) and channel (0 to 3)\nIR_PINS = ('P9_38', 'P9_40', 'P9_36', 'P9_35', 'P9_33')\n\n# Wheel encoder sensors: (left, right)\n# Pair indicating ADC (ADC1 or ADC2) and channel (0 to 3)\nENC_PINS = (('ADC1', 2), ('ADC1', 3))\n\n# i2c addresses of ADC1 and ADC2\nADC_ADDR = (0x48, 0x49)\n\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"621966318","text":"\"\"\"\n总结:\n   存储多个学生信息(姓名,年龄,成绩,性别)的多种方式\n\n1. exercise05字典内嵌列表:\n{\n \"张无忌\":[28,100,\"男\"],\n}\n2. exercise06字典内嵌字典:\n{\n \"张无忌\":{\"age\":28,\"score\":100,\"sex\":\"男\"},\n}\n3. exercise07列表内嵌字典:\n[\n {\"name\":\"张无忌\",\"age\":28,\"score\":100,\"sex\":\"男\"},\n]\n4. 列表内嵌列表\n[\n [\"张无忌\",28,100男],\n]\n选择策略:根据具体需求,结合优缺点,综合考虑(两害相权取其轻).\n 字典:\n 优点:根据键获取值,读取速度快;\n    代码可读性相对列表更高(根据键获取与根据索引获取).\n 缺点:内存占用大;\n    获取值只能根据键,不灵活.\n 列表:\n 优点:根据索引/切片,获取元素更灵活.\n 相比字典占内存更小。\n 缺点:通过索引获取,如果信息较多,可读性不高.\n\"\"\"\n\"\"\"\n练习:在控制台中录入多个人的多个喜好,输入空字符停止.\n例如:请输入姓名:\n 请输入第1个喜好:\n 请输入第2个喜好:\n ...\n 请输入姓名:\n ...\n 最后在控制台打印所有人的所有喜好.\n[\n {“无忌”:[赵敏,周芷若,小赵]}\n]\n\nlist_person_bobby = []\nwhile True:\n name = input(\"请输入姓名:\")\n if name == \"\":\n break\n dict_person = {name:[]}\n list_person_bobby.append(dict_person) \n while True:\n bobby = input(\"请输入喜好:\")\n if bobby == \"\":\n break\n dict_person[name].append(bobby)\n\"\"\"\n\n\"\"\"\n{\n “无忌”:[赵敏,周芷若,小赵]\n}\n\"\"\"\ndict_person_bobby = {}\nwhile True:\n name = input(\"请输入姓名:\")\n if name == \"\":\n break\n dict_person_bobby[name] = []\n while True:\n bobby = input(\"请输入喜好:\")\n if bobby == \"\":\n break\n dict_person_bobby[name].append(bobby)\n\nfor name, list_bobby in dict_person_bobby.items():\n print(\"%s喜欢:\" % name)\n for item in list_bobby:\n print(item)\n\n","sub_path":"python_one_learn/day06/exercise08.py","file_name":"exercise08.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"99719782","text":"import torch\nimport torch.nn.functional\nfrom attrdict import AttrDict\n\n\ndef _calculate_fan(dimensions, conv_params, axis):\n stride = conv_params.get('stride', [1, 1])[axis]\n padding = conv_params.get('padding', [0, 0])[axis]\n kernel_size = conv_params.get('kernel_size')[axis]\n dillation = conv_params.get('dillation', [1, 1])[axis]\n\n return torch.floor(\n (dimensions + 2 * padding - dillation * (kernel_size - 1) - 1) / stride + 1\n ).to(dtype=torch.long)\n\n\nclass Model(torch.nn.Module):\n def __init__(self, num_mel_bins, hidden_size, num_layers, num_tokens):\n super(Model, self).__init__()\n\n self.num_tokens = num_tokens\n self.num_layers = num_layers\n self.hidden_size = hidden_size\n\n self.bidirectional = True\n self.num_directions = 2 if self.bidirectional else 1\n\n self.num_mel_bins = num_mel_bins\n\n conv1_params = AttrDict(\n {\n \"in_channels\": 1,\n \"out_channels\": 32,\n \"kernel_size\": [21, 11],\n \"stride\": [1, 1]\n })\n conv2_params = AttrDict(\n {\n \"in_channels\": conv1_params['out_channels'],\n \"out_channels\": 64,\n \"kernel_size\": [11, 11],\n \"stride\": [1, 3]\n }\n )\n\n self.conv1_params = conv1_params\n self.conv2_params = conv2_params\n\n # [batch_size x 1 X num_mel_bins x time] -> [batch_size x conv2.out_channels x fan_num_mel_bins x fan_time]\n self.conv = torch.nn.Sequential(\n # write your code here\n\n # CONV 1\n torch.nn.Conv2d(**self.conv1_params, bias=False),\n # BATCH NORM 1\n torch.nn.BatchNorm2d(num_features=self.conv1_params['out_channels'], momentum=0.9),\n # RELU\n torch.nn.ReLU(inplace=True),\n\n # CONV 2\n torch.nn.Conv2d(**self.conv2_params, bias=False),\n # BATCH NORM 2\n torch.nn.BatchNorm2d(num_features=self.conv2_params['out_channels'], momentum=0.9),\n # RELU\n torch.nn.ReLU(inplace=True),\n )\n\n # YOUR CODE\n fan_num_mel_bins = _calculate_fan(\n _calculate_fan(torch.tensor(num_mel_bins), conv1_params, axis=0),\n conv2_params, axis=0\n ).item()\n rnn_input_size = self.conv2_params['out_channels'] * fan_num_mel_bins\n\n # 4 layers bidirectional lstm\n # YOUR CODE\n # [batch_size x fan_time x rnn_input_size] -> [batch_size x fan_time x num_directions * hidden_size], (h_n, c_n)\n self.lstm = torch.nn.LSTM(\n input_size=rnn_input_size, hidden_size=hidden_size, num_layers=self.num_layers,\n bias=True, batch_first=True, bidirectional=self.bidirectional\n )\n\n # YOUR CODE\n # [batch_size x num_directions * hidden_size] -> [batch_size, num_tokens]\n self.output_layer = torch.nn.Linear(self.num_directions * self.hidden_size, self.num_tokens)\n\n def forward(self, inputs, seq_lens, state=None):\n \"\"\"\n Input shape:\n audio: 3D tensor with shape (batch_size, num_mel_bins, num_timesteps)\n sequence_lengths: 1D tensor with shape (batch_size)\n Returns:\n 3D tensor with shape (new_num_timesteps, batch_size, alphabet_len)\n 1D tensor with shape (batch_size)\n \"\"\"\n\n outputs = inputs.unsqueeze(1) # conv2d input should be four-dimensional\n\n ### write your code here ###\n seq_lens = _calculate_fan(_calculate_fan(seq_lens, self.conv1_params, axis=1), self.conv2_params, axis=1)\n\n outputs = self.conv(outputs)\n\n outputs = self.transpose_and_reshape(outputs)\n outputs, (h_n, c_n) = self.lstm(outputs)\n\n outputs = self.output_layer(outputs)\n outputs = torch.transpose(outputs, 0, 1)\n outputs = torch.nn.functional.log_softmax(outputs, dim=-1)\n\n return outputs, seq_lens\n\n @staticmethod\n def transpose_and_reshape(inputs):\n \"\"\" This function will be very useful for converting the output of a convolutional layer\n to the input of a lstm layer\n\n Input shape:\n inputs: 4D tensor with shape (batch_size, num_filters, num_features, num_timesteps)\n Returns:\n 3D tensor with shape (batch_size, num_timesteps, new_num_features)\n \"\"\"\n # reshape # YOUR CODE\n # (batch_size, num_filters * num_features, num_timesteps)\n outputs = inputs.reshape(inputs.shape[0], inputs.shape[1] * inputs.shape[2], inputs.shape[3])\n # transpose # YOUR CODE\n # (batch_size, num_timesteps, new_num_features)\n outputs = torch.transpose(outputs, 1, 2)\n return outputs\n\n @staticmethod\n def get_new_seq_lens(seq_lens, conv1_kernel_size, conv1_stride, conv2_kernel_size, conv2_stride):\n \"\"\" Compute sequence_lengths after convolutions\n \"\"\"\n # write your code here\n seq_lens = _calculate_fan(seq_lens, {'kernel_size': [conv1_kernel_size], 'stride': [conv1_stride]}, axis=0)\n seq_lens = _calculate_fan(seq_lens, {'kernel_size': [conv2_kernel_size], 'stride': [conv2_stride]}, axis=0)\n return seq_lens\n","sub_path":"src/deepspeech.py","file_name":"deepspeech.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"157536617","text":"import pandas as pd\nimport numpy as np\nimport parameters as pm\nimport os\nimport prepare as pp\n# import matplotlib.pyplot as plt\n# %matplotlib inline\n\n\nimport copy\n\ndef read_data(filename,nfeat):\n\n df=pd.read_csv(filename,header=None,names=None)\n df=df.rename({1:'Type'},axis=1)\n # df=df.dropna()\n df.iloc[:][nfeat+2]=1.0\n return df\n\ndef readCluster(ClusterFile,):\n cluster=pd.read_csv(ClusterFile,delim_whitespace=True,header=None,names=None)\n cluster=cluster.rename({0:'Type'},axis=1)\n cluster=cluster.rename({1:'ClusterAssign'},axis=1)\n cluster=cluster.rename({2:'trainDataIndex'},axis=1)\n return cluster\n\n\ndef kmean_center(df,k,nfeat):\n # df=read_data()\n CaseNum=len(df)\n centroids={\n i+1:[\n df.iloc[np.random.randint(0,CaseNum)][m+3] \n for m in range(nfeat)\n ]\n for i in range(k)\n }\n return centroids\ndef kmean_center_design1(df,k,nfeat,center):\n # df=read_data()\n # CaseNum=len(df)\n centroids={\n i+1:[\n df.iloc[center[i]][m+3] \n for m in range(nfeat)\n ]\n for i in range(k)\n }\n return centroids\n\ndef kmean_center_design(df,k,nfeat,clusterDf):\n df=pd.concat([df,clusterDf], axis=1)\n # df=read_data()\n # CaseNum=len(df)\n centroids={\n i+1:[\n np.mean(df[df['ClusterAssign'] == i+1][m+3])\n for m in range(nfeat)\n ]\n for i in range(k)\n }\n return centroids\n\ndef assignment(df,centroids,nfeat,w_feat):\n for i in centroids.keys():\n df['dist_from_{}'.format(i)]=0\n for m in range(nfeat):\n df['dist_from_{}'.format(i)]=df['dist_from_{}'.format(i)]+(df.iloc[:][m+3]-centroids[i][m])**2*w_feat[m]\n df['dist_from_{}'.format(i)]=np.sqrt(df['dist_from_{}'.format(i)])\n \n centroids_dist_cols=['dist_from_{}'.format(i) for i in centroids.keys()]\n df['closest']=df.loc[:,centroids_dist_cols].idxmin(axis=1)\n df['closest'] = df['closest'].map(lambda x: int(x.lstrip('dist_from_')))\n return df\n\ndef update(centroids,df,nfeat):\n for i in centroids.keys():\n for m in range(nfeat):\n centroids[i][m] = np.mean(df[df['closest'] == i][m+3])\n return centroids \n\ndef writefile(df,df2file):\n df.to_csv(df2file,index=False)\n\ndef saveType(df1,itype):\n df1=df1[df1['Type']==itype]\n df1.reset_index(inplace=True)\n df1=df1.drop('index',axis=1)\n return df1\n\n\ndef shiftFeat(df1,nfeat,shiftScale):\n for m in range(nfeat):\n df1.iloc[:][m+3]=(df1.iloc[:][m+3]-shiftScale.iloc[m][0])*shiftScale.iloc[m][1]\n return df1\n\ndef readShift(shiftfile):\n shiftScale=pd.read_csv(shiftfile,delim_whitespace=True,header=None)\n print(shiftScale.head())\n return shiftScale\n\ndef measureKmean(df,centroids,nfeat,w_feat):\n dist=0\n for i in centroids.keys():\n for m in range(nfeat):\n dist=dist+np.sum((df[df['closest'] == i][m+3]-centroids[i][m])**2*w_feat[m])\n return dist\n\n \n\n# if __name__ == '__main__':\ndef runCluster(itype,alpha0=pm.alpha0,DesignCenter=pm.DesignCenter,k_dist0=pm.k_dist0,kernel_type=pm.kernel_type):\n\n nfeat=pm.realFeatNum\n ClusterNum=pm.ClusterNum[itype-1]\n\n# ********** input file *************** \n filename=os.path.join(pm.trainSetDir,'trainData.txt')\n ClusterFile=os.path.join('./output/','cluster_index.'+str(pm.atomType[itype-1]))\n # centerfile='center.'+str(itype)\n file_w_feat='weight_feat.'+str(itype)\n shiftfile='feat_shift.'+str(itype)\n # centerfile=os.path.join(pm.fitModelDir,centerfile)\n file_w_feat=os.path.join(pm.fitModelDir,file_w_feat)\n shiftfile=os.path.join(pm.fitModelDir,shiftfile)\n weight_feat=np.loadtxt(file_w_feat)\n w_feat=weight_feat[:,1]**2\n\n#*********** output file ************\n file_output='feat_cent.'+str(itype)\n # ClusterCase=['ClusterCase'+str(i+1) for i in range(ClusterNum)]\n df2file='df'+str(itype)+'.csv'\n file_output=os.path.join(pm.fitModelDir,file_output)\n df2file=os.path.join(pm.fitModelDir,df2file)\n#*********** shift the feature ************\n shiftScale=readShift(shiftfile)\n df=read_data(filename,nfeat)\n # print(df.head())\n df=shiftFeat(df,nfeat,shiftScale)\n # print(df.head())\n # print(len(df))\n#************* drop the other type ****************\n # df=saveType(df,pm.atomType[itype-1])\n # print(df.head())\n#************ Design Center ****************\n \n if DesignCenter:\n df=saveType(df,pm.atomType[itype-1])\n print(df.head())\n clusterDf=readCluster(ClusterFile)\n clusterDf=saveType(clusterDf,pm.atomType[itype-1])\n\n # center=np.loadtxt(centerfile,dtype=int)\n ClusterNum=np.max(clusterDf['ClusterAssign'])\n # print(center)\n print(ClusterNum)\n centroids=kmean_center_design(df,ClusterNum,nfeat,clusterDf)\n elif pm.DesignCenter2:\n center=pm.center[itype-1]\n ClusterNum=len(center)\n centroids=kmean_center_design1(df,ClusterNum,nfeat,center)\n df=saveType(df,pm.atomType[itype-1])\n print(df.head())\n else:\n df=saveType(df,pm.atomType[itype-1])\n print(df.head())\n centroids=kmean_center(df,ClusterNum,nfeat)\n \n# print(centroids)\n\n\n\n\n#************* k-mean cluster *****************\n df=assignment(df,centroids,nfeat,w_feat)\n centroids=update(centroids,df,nfeat)\n\n flg=0\n while True:\n flg=flg+1\n closest_centroids= df['closest'].copy(deep=True)\n centroids=update(centroids,df,nfeat)\n df=assignment(df,centroids,nfeat,w_feat)\n if closest_centroids.equals(df['closest']):\n break\n \n print(flg)\n print(df.head())\n# writefile(df,df2file)\n#*************** measure kmean ******************\n with open('./output/measureKmean','a') as f:\n dist=measureKmean(df,centroids,nfeat,w_feat)\n f.write(str(dist)+' \\n')\n\n\n#*************** calc weight ********************\n\n\n width={\n i+1:0\n for i in range(ClusterNum)\n }\n for i in centroids.keys():\n for m in range(nfeat): \n width[i]=width[i]+np.mean((df[df['closest']==i][m+3]-centroids[i][m])**2*w_feat[m])\n\n # print(ClusterNum)\n with open(file_output,'w') as f:\n f.writelines(str(ClusterNum)+','+str(alpha0)+','+str(k_dist0)+','+str(int(kernel_type))+'\\n')\n for i in centroids.keys():\n for m in range(nfeat):\n f.write(str(centroids[i][m]))\n f.write(' ')\n f.write('\\n')\n for i in centroids.keys():\n f.writelines(str(width[i])+'\\n')\n # print(ClusterNum)\n\n\n\nif __name__ == '__main__':\n shift=True\n if shift:\n pp.collectAllSourceFiles()\n pp.readFeatnum(os.path.join(pm.sourceFileList[0],'info.txt'))\n import fortran_fitting as ff\n ff.makeFitDirAndCopySomeFiles()\n # readFittingParameters()\n ff.copyData()\n ff.writeFitInput()\n command='make pca -C'+pm.fitModelDir\n # print(command)\n os.system(command)\n runCluster(2)\n\n\n \n\n","sub_path":"workdir/cluster_trainData3.py","file_name":"cluster_trainData3.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"477895698","text":"from collections import deque\n\nN , M = map(int,input().split())\n\nedge = [[] for _ in range(N)]\n\nfor _ in range(M) :\n x , y , z = map(int,input().split())\n\n edge[x-1].append(y-1)\n edge[y-1].append(x-1)\n\ncheck = [False] * N\n\nq = deque([0])\ncount = 1 # 連結成分の数\n\nwhile True:\n while q :\n current = q.popleft()\n\n if not check[current] :\n check[current] = True\n\n for n in edge[current] :\n if not check[n] :\n q.append(n)\n\n for v , status in enumerate(check) :\n if(not status) :\n q = deque([v])\n count += 1\n break\n else :\n break\n\nprint(count)\n\n\n","sub_path":"AtCoder/abc/126e.py","file_name":"126e.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"322915674","text":"import jwt\nimport json\nimport ecdsa\nimport datetime\nfrom keychain import PrivateKeychain, PublicKeychain\nfrom pybitcoin import BitcoinPrivateKey, BitcoinPublicKey\n\n\ndef sign_profile_tokens(profile_components, parent_private_key,\n signing_algorithm = 'ES256K'):\n \"\"\" Function for iterating through a list of profile components and\n signing separate individual profile tokens.\n \"\"\"\n\n if signing_algorithm == 'ES256K':\n signing_algorithm = 'ES256'\n else:\n raise ValueError(\"Unsupported signing algorithm\")\n\n token_records = []\n current_time = datetime.datetime.now()\n\n for profile_component in profile_components:\n private_key = BitcoinPrivateKey(parent_private_key)\n public_key = private_key.public_key()\n\n payload = {\n \"claim\": profile_component,\n \"subject\": {\n \"publicKey\": public_key.to_hex()\n },\n \"issuedAt\": current_time.isoformat(),\n \"expiresAt\": current_time.replace(current_time.year + 1).isoformat()\n }\n\n token = jwt.encode(\n payload, private_key.to_pem(), algorithm=signing_algorithm)\n decoded_token = jwt.decode(\n token, public_key.to_pem(), algorithms=[signing_algorithm])\n\n token_record = {\n \"token\": token,\n \"decoded_token\": decoded_token,\n \"publicKey\": public_key.to_hex(),\n \"parentPublicKey\": public_key.to_hex(),\n \"encrypted\": False\n }\n token_records.append(token_record)\n\n return token_records\n\n\ndef validate_token_record(token_record, parent_public_key,\n signing_algorithm = 'ES256'):\n \"\"\" A function for validating an individual token record and extracting\n the decoded token.\n \"\"\"\n\n if not (\"token\" in token_record and \"publicKey\" in token_record and \\\n \"parentPublicKey\" in token_record):\n raise ValueError(\"Invalid token record\")\n\n token = token_record[\"token\"]\n\n public_key = BitcoinPublicKey(parent_public_key)\n\n decoded_token = jwt.decode(\n token, public_key.to_pem(), algorithms=[signing_algorithm])\n\n decoded_token = json.loads(json.dumps(decoded_token))\n\n if \"subject\" not in decoded_token and \"publicKey\" not in decoded_token[\"subject\"]:\n raise ValueError(\"Invalid decoded token\")\n if \"claim\" not in decoded_token:\n raise ValueError(\"Invalid decoded token\")\n\n if token_record[\"publicKey\"] == token_record[\"parentPublicKey\"]:\n if token_record[\"publicKey\"] != decoded_token[\"subject\"][\"publicKey\"]:\n raise ValueError(\"Token's public key doesn't match\")\n else:\n raise ValueError(\"Verification of tokens signed with keychains is not yet supported\")\n\n return decoded_token\n\n\ndef get_profile_from_tokens(token_records, parent_public_key):\n \"\"\" A function for extracting a profile from a list of tokens.\n \"\"\"\n\n profile = {}\n\n for token_record in token_records:\n decoded_token = validate_token_record(token_record, parent_public_key)\n claim = decoded_token[\"claim\"]\n profile.update(claim)\n\n return profile\n","sub_path":"blockstack_profiles/tokening.py","file_name":"tokening.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"286265115","text":"import string\n\ndef buildEmptyMap(columns, rows):\n mapMatrix= [[0 for x in range(columns)] for x in range(rows)]\n return mapMatrix\n\n\ndef print_map(mapMatrix):\n print(\"You've opened: print_map(mapMatrix)\")\n print(\"Funct: print_map()\")\n for line in mapMatrix:\n print(line)\n\n\ndef print_map2(mapMatrix, rows):\n print(\"You've opened: print_map2(mapMatrix, rows)\")\n for y in range(rows):\n for x in range(len(mapMatrix[y])):\n print(mapMatrix[y][x], end='')\n print()\n\n\n\n\n\n\ndef format_map_excel(mapMatrix, rows):\n print(\"You've opened: format_map_excel(mapMatrix, rows)\")\n for y in range(rows):\n for x in range(len(mapMatrix[y])):\n if mapMatrix[y][x] == '\\t':\n mapMatrix[y][x] = ''\n elif mapMatrix[y][x] == '\\n':\n pass\n \n else:\n print(mapMatrix[y][x], end='')\n print()\n return mapMatrix\n\n\n\ndef format_map_every2nd(mapMatrix, rows):\n print(\"You've opened: format_map_every2nd(mapMatrix, rows)\")\n for y in range(rows):\n for x in range(len(mapMatrix[y])):\n if x%2 == 0:\n if mapMatrix[y][x] == '\\t':\n mapMatrix[y][x] = ''\n elif mapMatrix[y][x] == '\\n':\n mapMatrix[y][x] = ' '\n \n else:\n print(mapMatrix[y][x], end='')\n print()\n return mapMatrix\n\n\ndef format_map_0finder(mapMatrix, rows):\n print(\"You've opened: format_map_0finder(mapMatrix, rows)\")\n for y in range(rows):\n for x in range(len(mapMatrix[y])):\n if mapMatrix[y][x] == '0':\n mapMatrix[y][x] = ' '\n return mapMatrix\n\n\ndef openTroll():\n with open('cicaTrollFace.txt', 'r' ) as mazeFileTroll:\n columns = 57\n rows = 58\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in mazeFileTroll:\n mapKacsa[i] = list(line)\n i += 1\n \n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n print_map2(mapKacsa, rows)\n #return basic_dictonary\n\n\n\ndef openTest():\n with open('mazeFileLvl_test.txt', 'r' ) as mazeFileLvl_test:\n columns = 10\n rows = 10\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in mazeFileLvl_test:\n mapKacsa[i] = list(line)\n i += 1\n format_map_excel(mapKacsa,rows)\n format_map_0finder(mapKacsa,rows)\n\n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n return basic_dictonary\n \n \n\n\ndef open1():\n with open('mazeFileLvl_1.txt', 'r' ) as mazeFileLvl_1:\n columns = 11\n rows = 11\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in mazeFileLvl_1:\n mapKacsa[i] = list(line)\n #print(list(line))\n i += 1\n\n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n return basic_dictonary\n\n######################################################################\n\n\ndef open_hexa():\n with open('mazeFileLvl_hexa.txt', 'r' ) as mazeFileLvl_hexa:\n columns = 59\n rows = 30\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in mazeFileLvl_hexa:\n mapKacsa[i] = list(line)\n #print(list(line))\n i += 1\n \n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n print_map2(mapKacsa, rows)\n #return basic_dictonary\n\n######################################################################\n\n\ndef open_bunny():\n with open('mazeFileLvl_Bunny.txt', 'r' ) as mazeFileLvl_Bunny:\n columns = 67\n rows = 39\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in mazeFileLvl_Bunny:\n mapKacsa[i] = list(line)\n #print(list(line))\n i += 1\n \n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n #return basic_dictonary\n print_map2(mapKacsa,rows)\n\n\ndef open_screenFinal():\n with open('screenFinal', 'r' ) as fileScreenFinal:\n columns = 67\n rows = 34\n mapKacsa = buildEmptyMap(columns,rows)\n i = 0\n for line in fileScreenFinal:\n mapKacsa[i] = list(line)\n i += 1\n \n basic_dictonary = {\n 'positionStartYX' : [5,3], #TODO\n 'positionFinal' :[34,45],\n 'map' : mapKacsa,\n }\n return basic_dictonary\n\ndef simoMosogassEl():\n mapTroll = openTroll()\n mapTest = openTest()\n map1 = open1()\n mapHexa = open_hexa()\n mapBunny = open_bunny()\n mapFinal = open_screenFinal()\n\n#openTroll()\n#open_hexa()\n#open_bunny()","sub_path":"2.Menet/labirynthMaker.py","file_name":"labirynthMaker.py","file_ext":"py","file_size_in_byte":5137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"129029954","text":"import os\nimport argparse\nimport asyncio\nimport txaio\n\nfrom autobahn.wamp.types import RegisterOptions, PublishOptions\nfrom autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner\nfrom autobahn.wamp.exception import ApplicationError\n\n\nclass ClientSession(ApplicationSession):\n def onConnect(self):\n self.log.info(\"Client connected: {klass}\", klass=ApplicationSession)\n self.join(self.config.realm, [u'anonymous'])\n\n def onChallenge(self, challenge):\n self.log.info(\"Challenge for method {authmethod} received\", authmethod=challenge.method)\n raise Exception(\"We haven't asked for authentication!\")\n\n async def onJoin(self, details):\n await self.producer()\n\n async def producer(self):\n self.produce = True\n\n def stop_producing():\n self.produce = False\n\n await self.register(stop_producing, u'io.crossbar.example.client1.stop_producing',\n options=RegisterOptions(invoke=u'roundrobin'))\n\n # REGISTER\n def add2(a, b):\n print('----------------------------')\n print(\"add2 called with values {} and {}\".format(a, b))\n return a + b\n\n await self.register(add2, u'io.crossbar.example.client1.add2', options=RegisterOptions(invoke=u'roundrobin'))\n print('----------------------------')\n print('procedure registered: io.crossbar.example.client1.add2')\n\n counter = 0\n while self.produce:\n # PUBLISH\n await self.publish(u'io.crossbar.example.client1.oncounter', counter,\n options=PublishOptions(acknowledge=True, exclude_me=True))\n print('----------------------------')\n self.log.info(\"published to 'oncounter' with counter {counter}\", counter=counter)\n counter += 1\n print('----------------------------')\n\n await asyncio.sleep(1)\n\n await self.consumer()\n\n async def consumer(self):\n self.incoming_counter = 0\n\n # SUBSCRIBE\n def oncounter(counter):\n print('----------------------------')\n self.log.info(\"'oncounter' event, counter value: {counter}\", counter=counter)\n self.incoming_counter += 1\n\n await self.subscribe(oncounter, u'io.crossbar.example.client2.oncounter')\n print('----------------------------')\n self.log.info(\"subscribed to topic 'io.crossbar.example.client2.oncounter'\")\n\n x = 0\n while self.incoming_counter < 5 and x < 5:\n\n # CALL\n try:\n res = await self.call(u'io.crossbar.example.client2.add2', x, 3)\n print('----------------------------')\n self.log.info(\"add2 result: {result}\", result=res)\n x += 1\n except ApplicationError as e:\n # ignore errors due to the frontend not yet having\n # registered the procedure we would like to call\n if e.error != 'wamp.error.no_such_procedure':\n raise e\n\n await asyncio.sleep(2)\n\n res = await self.call(\"io.crossbar.example.client2.stop_producing\")\n print(res)\n\n self.leave()\n\n def onLeave(self, details):\n self.log.info(\"Router session closed ({details})\", details=details)\n self.disconnect()\n\n def onDisconnect(self):\n self.log.info(\"Router connection closed\")\n asyncio.get_event_loop().stop()\n\n\nif __name__ == '__main__':\n\n # Crossbar.io connection configuration\n url = os.environ.get('CBURL', u'ws://crossbar:8080/ws')\n realm = os.environ.get('CBREALM', u'realm1')\n\n # parse command line parameters\n parser = argparse.ArgumentParser()\n parser.add_argument('-d', '--debug', action='store_true', help='Enable debug output.')\n parser.add_argument('--url', dest='url', type=str, default=url,\n help='The router URL (default: \"ws://localhost:8080/ws\").')\n parser.add_argument('--realm', dest='realm', type=str, default=realm,\n help='The realm to join (default: \"realm1\").')\n\n args = parser.parse_args()\n\n # start logging\n if args.debug:\n txaio.start_logging(level='debug')\n else:\n txaio.start_logging(level='info')\n\n # any extra info we want to forward to our ClientSession (in self.config.extra)\n extra = {\n u'foobar': u'A custom value'\n }\n\n # now actually run a WAMP client using our session class ClientSession\n runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra)\n runner.run(ClientSession)\n","sub_path":"demo-gallery/python/test_component2.py","file_name":"test_component2.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"471038980","text":"# Copyright 2015 Donald Stufft\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.\nfrom __future__ import absolute_import, division, print_function\n\nimport cgi\nimport io\nimport re\nimport sys\nimport webbrowser\n\nimport distutils.log\nfrom distutils.command.check import check as _check\nfrom distutils.core import Command\nfrom tempfile import NamedTemporaryFile\nimport six\n\nfrom pygments import highlight\nfrom pygments.formatters import Terminal256Formatter\nfrom pygments.lexers import HtmlLexer\n\nfrom ..rst import render\n\n\n# Regular expression used to capture and reformat doctuils warnings into\n# something that a human can understand. This is loosely borrowed from\n# Sphinx: https://github.com/sphinx-doc/sphinx/blob\n# /c35eb6fade7a3b4a6de4183d1dd4196f04a5edaf/sphinx/util/docutils.py#L199\n_REPORT_RE = re.compile(\n r'^:(?P(?:\\d+)?): '\n r'\\((?PDEBUG|INFO|WARNING|ERROR|SEVERE)/(\\d+)?\\) '\n r'(?P.*)', re.DOTALL | re.MULTILINE)\n\n\nRST_TYPE = 'text/x-rst'\nMD_TYPE = 'text/markdown'\nPLAIN_TYPE = 'text/plain'\n\n\n@six.python_2_unicode_compatible\nclass _WarningStream(object):\n def __init__(self):\n self.output = io.StringIO()\n\n def write(self, text):\n matched = _REPORT_RE.search(text)\n\n if not matched:\n self.output.write(text)\n return\n\n self.output.write(\n u\"line {line}: {level_text}: {message}\\n\".format(\n level_text=matched.group('level').capitalize(),\n line=matched.group('line'),\n message=matched.group('message').rstrip('\\r\\n')))\n\n def __str__(self):\n return self.output.getvalue()\n\n\nclass Check(_check):\n def check_restructuredtext(self):\n \"\"\"\n Checks if the long string fields are reST-compliant.\n \"\"\"\n data = self.distribution.get_long_description()\n content_type = getattr(\n self.distribution.metadata, 'long_description_content_type', None)\n\n if content_type:\n content_type, _ = cgi.parse_header(content_type)\n if content_type != 'text/x-rst':\n self.warn(\n \"Not checking long description content type '%s', this \"\n \"command only checks 'text/x-rst'.\" % content_type)\n return\n\n # None or empty string should both trigger this branch.\n if not data or data == 'UNKNOWN':\n self.warn(\n \"The project's long_description is either missing or empty.\")\n return\n\n stream = _WarningStream()\n markup = render(data, stream=stream)\n\n if markup is None:\n self.warn(\n \"The project's long_description has invalid markup which will \"\n \"not be rendered on PyPI. The following syntax errors were \"\n \"detected:\\n%s\" % stream)\n return\n\n self.announce(\n \"The project's long description is valid RST.\",\n level=distutils.log.INFO)\n\n\nclass RenderReadme(Command):\n\n \"\"\"Render and display the long description as HTML.\"\"\"\n description = (\"render the long description as HTML\")\n user_options = [(\"preview\", None,\n \"Preview readme\"),\n (\"no-color\", None,\n \"Do not colorize...\"),\n (\"style=\", None,\n \"Pygments style to use to colorize HTML output.\")]\n\n def initialize_options(self):\n self.preview = False\n self.no_color = False\n self.style = 'native'\n\n def finalize_options(self):\n pass\n\n def get_renderer(self):\n content_type = getattr(\n self.distribution.metadata, 'long_description_content_type', None)\n\n if content_type == RST_TYPE:\n from ..rst import render as rst_render\n return rst_render\n elif content_type == MD_TYPE:\n from ..markdown import render as md_render\n return md_render\n elif content_type == PLAIN_TYPE:\n from ..txt import render as txt_render\n return txt_render\n else:\n from ..rst import render as rst_render\n return rst_render\n\n def run(self):\n \"\"\"Runs the command.\"\"\"\n\n data = self.distribution.get_long_description()\n stream = io.StringIO()\n # TODO: this will only work for RST!!!\n render = self.get_renderer()\n markup = render(data, stream=stream)\n\n for line in stream.getvalue().splitlines():\n if line.startswith(\"\"):\n line = line[8:]\n self.warn(line)\n\n if markup is None:\n self.warn(\"Invalid markup which will not be rendered on PyPI.\")\n\n if self.preview:\n with NamedTemporaryFile(\n prefix='render_readme_',\n suffix='.html',\n delete=False,\n ) as f:\n print('Writing readme to {0}'.format(f.name))\n f.write(markup.encode('utf-8'))\n\n webbrowser.open('file://' + f.name.replace('\\\\', '/'))\n else:\n if not self.no_color:\n lexer = HtmlLexer()\n formatter = Terminal256Formatter(style=self.style)\n markup = highlight(markup, lexer, formatter)\n sys.stdout.write(markup)\n","sub_path":"readme_renderer/integration/distutils.py","file_name":"distutils.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"80922812","text":"import threading\n\nclass Philosopher(threading.Thread):\n def __init__(self, index, left_lock, right_lock):\n threading.Thread.__init__(self)\n self.id = index\n self.left_lock = left_lock\n self.right_lock = right_lock\n\n\n def run(self):\n global count\n while True:\n while True:\n # 拿起左叉子\n self.left_lock.acquire(True)\n result.append([self.id, 2, 1])\n\n acquired = self.right_lock.acquire(False)\n if acquired: # 拿起右叉子\n result.append([self.id, 1, 1])\n break\n else:\n # 放下左叉子\n self.left_lock.release()\n result.append([self.id, 2, 2])\n\n # 进餐\n result.append([self.id, 0, 3])\n\n # 放下左叉子\n self.left_lock.release()\n result.append([self.id, 2, 2])\n\n # 放下右叉子\n self.right_lock.release()\n result.append([self.id, 1, 2])\n\n count += 1\n if count >= n:\n break\n\n\nif __name__ == '__main__':\n count = 0\n result = []\n n = 1\n philosophers_num = 5\n\n # 实例化5把锁和5个哲学家\n locks = [threading.Lock() for _ in range(philosophers_num)]\n threads = [Philosopher(i, locks[i], locks[(i+1) % philosophers_num]) for i in range(philosophers_num)]\n\n # 启动线程\n for ph_thread in threads:\n ph_thread.start()\n\n # 打印结果\n print(result)\n\n","sub_path":"Week03/dining_philosophers.py","file_name":"dining_philosophers.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"81637538","text":"#!/usr/bin/env python\n\n# -*- encoding: utf-8 -*-\n\n\"\"\"\n@Author : Amelia \n@Contact : yu_mengling@hust.edu.cn\n@File : test_courseinfodetail.py\n \n@Time : 18-7-18 下午11:08\n\"\"\"\n\n''' 慕课网免费课程详情页'''\nimport time\nfrom typing import Dict, Any, Union\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pymysql\n\n# 慕课网 python\n# https://www.imooc.com/learn/85 其中id可以直接从免费课程卡片页获取\n# url中有两个变量: user_id, page_num\n\nbase_url = 'https://www.imooc.com/learn/'\n\nheaders = {'user-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'}\n\nfor course_id in range(85, 86):\n user_url = base_url + str(course_id)\n res = requests.get(user_url, headers=headers)\n if res.status_code != 200:\n print('course %s not exist' % course_id)\n continue\n\n html_doc = res.text\n soup = BeautifulSoup(html_doc, 'html.parser')\n # course_list = soup.find_all(\"div\",class_=\"course-list-cont\")\n # # print course_list\n # for course in course_list:\n # print course\n course_detail = {}\n path_detail = soup.find('div', class_='path').get_text().strip().replace('\\n', '')\n course_tip = soup.find_all(\"dd\")\n course_tip_first = course_tip[0].get_text()\n course_tip_second = course_tip[1].get_text().strip()\n teacher_info = soup.find('span', class_=\"tit\").find(\"a\")\n teacher_name = teacher_info.get_text().strip()\n teacher_url = teacher_info[\"href\"]\n teacher_job = soup.find(\"span\", class_=\"job\").get_text()\n course_info = soup.find_all(\"span\", class_=\"meta-value\")\n course_duration = course_info[1].get_text()\n course_score = course_info[3].get_text()\n menu_pp = soup.find(\"ul\", class_=\"course-menu\").find_all(\"span\")\n comment_pp = menu_pp[0].get_text()\n score_pp = menu_pp[1].get_text()\n\n print(path_detail)\n print(course_tip_first)\n print(course_tip_second)\n print(teacher_name)\n print(teacher_url)\n print(teacher_job)\n # print(course_info)\n print(comment_pp)\n print(score_pp)\n print(\"done\")\n\n\n# if __name__ == '__main__':\n# pass","sub_path":"imooc_spider/test_courseinfodetail.py","file_name":"test_courseinfodetail.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"336070240","text":"#Original Source : https://github.com/pytorch/examples/blob/master/mnist/main.py\n\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch MNIST Example')\nparser.add_argument('--batch-size', type=int, default=64, metavar='N',\n\t\t\t\t\thelp='input batch size for training (default: 64)')\nparser.add_argument('--test-batch-size', type=int, default=10000, metavar='N',\n\t\t\t\t\thelp='input batch size for testing (default: 1000)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n\t\t\t\t\thelp='number of epochs to train (default: 10)')\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n\t\t\t\t\thelp='learning rate (default: 0.01)')\nparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n\t\t\t\t\thelp='SGD momentum (default: 0.5)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n\t\t\t\t\thelp='disables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n\t\t\t\t\thelp='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n\t\t\t\t\thelp='how many batches to wait before logging training status')\nparser.add_argument('--noiselayer', type=int, default=0.2, metavar='N',\n\t\t\t\t\thelp='choose which noise layer to use')\nparser.add_argument('--load', type=int, default=0, metavar='N',\n\t\t\t\t\thelp='load trained data from test.dat file')\nparser.add_argument('--filename', default=\"output.txt\", metavar='N',\n help='output filename')\n\n\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n\ttorch.cuda.manual_seed(args.seed)\n\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n\tdatasets.MNIST('../data', train=True, download=True,\n\t\t\t\t transform=transforms.Compose([\n\t\t\t\t\t transforms.ToTensor(),\n\t\t\t\t\t transforms.Normalize((0.1307,), (0.3081,))\n\t\t\t\t ])),\n\tbatch_size=args.batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n\tdatasets.MNIST('../data', train=False, transform=transforms.Compose([\n\t\t\t\t\t transforms.ToTensor(),\n\t\t\t\t\t transforms.Normalize((0.1307,), (0.3081,))\n\t\t\t\t ])),\n\tbatch_size=args.test_batch_size, shuffle=True, **kwargs)\n\n'''def gaussian(ins, stddev=args.std):\n\tglobal is_testing\n\tif is_testing:\n\t\treturn ins + Variable(torch.randn(ins.size()).cuda() * stddev)\n\treturn ins'''\n\ndef print_feature(input, filename):\n\tf = open(filename, 'w+')\n\tfor i in input:\n\t\tfor j in i:\n\t\t\tprint(j, file=f)\n\tf.close()\n\nclass Net(nn.Module):\n\tdef __init__(self):\n\t\tsuper(Net, self).__init__()\n\t\tself.conv1 = nn.Conv2d(1, 10, kernel_size=5)\n\t\tself.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n\t\tself.conv2_drop = nn.Dropout2d()\n\t\tself.fc1 = nn.Linear(320, 50)\n\t\tself.fc2 = nn.Linear(50, 10)\n\n\tdef forward(self, x):\n\t\tconv1_input = x\n\t\tx = self.conv1(x)\n\t\tconv1_output = x\n\t\tx = F.max_pool2d(x,2)\n\t\tx = F.relu(x)\n\t\t\n\t\tconv2_input = x\n\t\tx = self.conv2(x)\n\t\tconv2_output = x\n\t\tx = self.conv2_drop(x)\n\t\tx = F.max_pool2d(x, 2)\n\t\tx = F.relu(x)\n\n\t\tx = x.view(-1, 320)\n\t\t\n\t\tfc1_input = x\n\t\tx = self.fc1(x)\n\t\tfc1_output = x\n\t\tx = F.relu(x)\n\n\t\tx = F.dropout(x, training=self.training)\n\t\tfc2_input = x\n\t\tx = self.fc2(x)\n\t\tfc2_output = x\n\n\t\treturn (F.log_softmax(x),conv1_input,conv1_output,conv2_input,conv2_output, fc1_input, fc1_output, fc2_input, fc2_output)\n\n\tdef extract_weight(self):\n\t\tf = open('conv1_param.txt','w')\n\t\tfor i in self.conv1.parameters():\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\t\tf = open('conv2_param.txt','w')\n\t\tfor i in self.conv2.parameters():\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\t\tf = open('fc1_param.txt','w')\n\t\tfor i in self.fc1.parameters():\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\t\tf = open('fc2_param.txt','w')\n\t\tfor i in self.fc2.parameters():\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\n\nmodel = Net()\n\nif args.cuda:\n\tmodel.cuda()\noptimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)\n\ndef test():\n\tmodel.eval()\n\ttest_loss = 0\n\tcorrect = 0\n\tfor data, target in test_loader:\n\t\tif args.cuda:\n\t\t\tdata, target = data.cuda(), target.cuda()\n\t\tdata, target = Variable(data, volatile=True), Variable(target)\n\t\t(output,conv1_input,conv1_output,conv2_input,conv2_output,\n\t\t\tfc1_input, fc1_output, fc2_input, fc2_output) = model(data)\n\t\tf = open('conv1_input.txt','w+')\n\t\tfor i in conv1_input:\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\t\tf = open('conv1_output.txt','w+')\n\t\tfor i in conv1_output:\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\t\tf = open('conv2_input.txt','w+')\n\t\tfor i in conv2_input:\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\t\tf = open('conv2_output.txt','w+')\n\t\tfor i in conv2_output:\n\t\t\tfor j in i:\n\t\t\t\tprint(j,file = f)\n\t\tf.close()\n\t\tf = open('fc1_input.txt','w+')\n\t\tfor i in fc1_input:\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\t\tf = open('fc1_output.txt','w+')\n\t\tfor i in fc1_input:\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\t\tf = open('fc2_input.txt','w+')\n\t\tfor i in fc2_input:\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\t\tf = open('fc2_output.txt','w+')\n\t\tfor i in fc2_output:\n\t\t\tprint(i,file = f)\n\t\tf.close()\n\n\n\t\ttest_loss += F.nll_loss(output, target, size_average=False).data[0] # sum up batch loss\n\t\tpred = output.data.max(1, keepdim=True)[1] # get the index of the max log-probability\n\t\tcorrect += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n\ttest_loss /= len(test_loader.dataset)\n\t#f = open(\"record1.txt\", 'a+')\n\tprint('{}'.format(correct), end='\\t')\n\t#print('{}'.format(correct), end='\\t',file = f)\n\t#f.close()\n\n\n#for epoch in range(1, args.epochs + 1):\nglobal is_testing\nis_testing = 0\nif args.load == 1:\n\tmodel = torch.load('test1.dat')\nelif args.load == 2:\n\tmodel = torch.load('test2.dat')\nelif args.load == 3:\n\tmodel = torch.load('test3.dat')\nis_testing = 1\ntest()\n#model.extract_weight()\n","sub_path":"UNIST-Testvector/FeatureExtract.py","file_name":"FeatureExtract.py","file_ext":"py","file_size_in_byte":6010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"8273357","text":"\"\"\"\nCopyright 2013 Rackspace\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\"\"\"\nfrom datetime import datetime\nfrom json import dumps as json_to_str\nfrom cafe.engine.models.base import (AutoMarshallingModel,\n AutoMarshallingListModel)\n\n\nclass SystemInfo(AutoMarshallingModel):\n def __init__(self, disk_usage=None, os_type=None, memory_mb=None,\n architecture=None, cpu_cores=None, load_average=None,\n timestamp=None):\n super(SystemInfo, self).__init__()\n\n self.os_type = os_type\n self.memory_mb = memory_mb\n self.architecture = architecture\n self.cpu_cores = cpu_cores\n self.load_average = load_average\n self.disk_usage = disk_usage\n self.timestamp = timestamp\n\n def _obj_to_json(self):\n return json_to_str(self._obj_to_dict())\n\n def _obj_to_dict(self):\n return {\n 'os_type': self.os_type,\n 'memory_mb': self.memory_mb,\n 'architecture': self.architecture,\n 'cpu_cores': self.cpu_cores,\n 'disk_usage': self.disk_usage._obj_to_dict(),\n 'load_average': self.load_average._obj_to_dict(),\n 'timestamp': self.timestamp or datetime.utcnow().isoformat()\n }\n\n @classmethod\n def _dict_to_obj(cls, dic):\n disk_usage = DiskUsage._dict_to_obj(dic.get('disk_usage'))\n load_average = LoadAverage._dict_to_obj(dic.get('load_average'))\n\n kwargs = {\n 'os_type': dic.get('os_type'),\n 'memory_mb': dic.get('memory_mb'),\n 'architecture': dic.get('architecture'),\n 'cpu_cores': dic.get('cpu_cores'),\n 'disk_usage': disk_usage,\n 'load_average': load_average,\n 'timestamp': dic.get('timestamp')\n }\n return SystemInfo(**kwargs)\n\n\nclass LoadAverage(AutoMarshallingModel):\n\n def __init__(self, one_average=None, five_average=None,\n fifteen_average=None):\n super(LoadAverage, self).__init__()\n\n self.one_average = one_average\n self.five_average = five_average\n self.fifteen_average = fifteen_average\n\n def _obj_to_dict(self):\n return {\n '1': self.one_average,\n '5': self.five_average,\n '15': self.fifteen_average\n }\n\n def _obj_to_json(self):\n return json_to_str(self._obj_to_dict())\n\n @classmethod\n def _dict_to_obj(cls, dic):\n kwargs = {\n 'one_average': dic.get('1'),\n 'five_average': dic.get('5'),\n 'fifteen_average': dic.get('5')\n }\n return LoadAverage(**kwargs)\n\n\nclass DiskUsage(AutoMarshallingListModel):\n\n def _obj_to_dict(self):\n return [disk._obj_to_dict() for disk in self]\n\n def _obj_to_json(self):\n return json_to_str(self._obj_to_dict())\n\n @classmethod\n def _dict_to_obj(cls, json_dict):\n usage = cls()\n for disk in json_dict:\n part = Partition(name=disk.get('device'),\n used=disk.get('used'),\n total=disk.get('total'))\n usage.append(part)\n return usage\n\n\nclass Partition(AutoMarshallingModel):\n\n def __init__(self, name=None, total=None, used=None):\n super(Partition, self).__init__()\n\n self.name = name\n self.total = total\n self.used = used\n\n def _obj_to_dict(self):\n body = {\n 'device': self.name,\n 'total': self.total,\n 'used': self.used\n }\n return body\n\n def _obj_to_json(self):\n return json_to_str(self._obj_to_dict())\n","sub_path":"cloudcafe/meniscus/common/models/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"239154277","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport contextlib\nimport keyword\nimport functools\n\n\n@contextlib.contextmanager\ndef chdir(path):\n curr_dir = os.getcwd()\n os.chdir(path)\n yield\n os.chdir(curr_dir)\n\n\ndef is_valid_identifier(string):\n if not re.match(\"[_A-Za-z][_a-zA-Z0-9]*$\", string):\n return False\n if keyword.iskeyword(string):\n return False\n return True\n\n\ndef make_valid_identifier(string):\n string = string.strip()\n string = string.replace(\"-\", \"_\")\n string = string.replace(\" \", \"_\")\n string = re.sub('[^_a-zA-Z0-9]', '', string)\n string = string.lower()\n if is_valid_identifier(string):\n return string\n else:\n raise RuntimeError(\"String cannot be converted to a valid identifier.\")\n\n\ndef safe_set(namespace, attr, value):\n if not hasattr(namespace, attr) or getattr(namespace, attr) is None:\n setattr(namespace, attr, value)\n\n\ndef safe_get(namespace, attr):\n if hasattr(namespace, attr):\n return getattr(namespace, attr)\n\n\ndef list2str(lst, indent=0):\n lst_str = str(lst)\n lb = ',\\n' + indent*' '\n return lst_str.replace(', ', lb)\n\n\ndef exceptions2exit(exception_list):\n def exceptions2exit_decorator(func):\n @functools.wraps(func)\n def func_wrapper(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except tuple(exception_list) as e:\n print(e)\n sys.exit(1)\n return func_wrapper\n return exceptions2exit_decorator\n","sub_path":"pyscaffold/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"204964274","text":"# -*- coding:utf-8 -*-\n\"\"\"数据处理中间件\"\"\"\nimport time\nfrom .saveredis import *\nfrom .IDinfo import CID\n\n\ndef kline(pair, tid, j, linelist):\n \"\"\"处理k线数据\"\"\"\n list=[\n \"makl\", \"fmakl\", \"fiakl\", \"tmakl\", \"siakl\", \"dayakl\", \"weakl\", \"moakl\"\n ]\n cid = CID.get(pair.split(\"_\")[0])\n tway = pair.split(\"_\")[1].lower()\n key = list[j] + \"_\" + tid + \"_\" + str(cid) + \"_\" + tway\n save.set(key, linelist)\n return\n\n\ndef ticker(pair, tid, a, o, c, l, h):\n \"\"\"处理行情数据\"\"\"\n cid = CID.get(pair.split(\"_\")[0])\n tway = pair.split(\"_\")[1].lower()\n key = \"QuotationVolumeData24Hour\" + \"_\" + tid + \"_\" + str(cid) + \"_\" + tway\n value = {\n \"Infos\": [{\"t\": int(time.time()), \"a\": a, \"o\": o,\n \"c\": c, \"l\": l, \"h\": h,\n \"TID\": tid, \"CID\": cid, \"TWay\": tway,\n }]}\n save.set(key, value)\n return value\n\n\ndef trades(pair, tid, data):\n \"\"\"处理交易明细\"\"\"\n cid = CID.get(pair.split(\"_\")[0])\n tway = pair.split(\"_\")[1].lower()\n key = \"QuotationTradeDetailInfo_1\" + \"_\" + tid + \"_\" + str(cid) + \"_\" + tway\n value = {\n \"Infos\": eval(data), \"TID\": tid, \"CID\": cid, \"TWay\": tway,\n }\n save.set(key, value)\n return\n\n\ndef depth(pair, tid, bids, asks):\n \"\"\"处理市场深度\"\"\"\n cid = CID.get(pair.split(\"_\")[0])\n tway = pair.split(\"_\")[1].lower()\n key = \"QuotationMarketDepthInfo_1\" + \"_\" + tid + \"_\" + str(cid) + \"_\" + tway\n value = {\n \"ts\": int(time.time()), \"bids\": bids, \"asks\": asks, \"TID\": tid, \"CID\": cid, \"TWay\": tway,\n }\n save.set(key, value)\n return\n","sub_path":"hqhq/origin/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"88557175","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n@author: wenbin\r\n@filename: eric-straregy.py\r\n@created date: 2016/11/16 17:11\r\n@last modified: 2016/11/16 17:11\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\n# 第一步:设置基本参数\r\nstart = '2016-08-01'\r\nend = '2016-11-11'\r\nbenchmark = 'HS300'\r\ncapital_base = 2000000\r\nfreq = 'd'\r\nrefresh_rate = 3\r\n\r\n# 第二步:选择因子(分析师评级、速动比率),设置股票池\r\nuniverse = StockScreener(\r\n Factor.REC.value_range(2, None) & Factor.QuickRatio.value_range(2.5, None) & Factor.MA5.value_range(20, None)) + [\r\n '000610.XSHE', '000755.XSHE', '600149.XSHG', '600228.XSHG', '000507.XSHE', '002438.XSHE', '000609.XSHE',\r\n '002113.XSHE', '002148.XSHE', '002248.XSHE', '000779.XSHE', '000502.XSHE', '000586.XSHE', '600689.XSHG',\r\n '600671.XSHG', '601018.XSHG']\r\n\r\n\r\ndef initialize(account):\r\n account.i = 0\r\n account.daily_trigger_time = \"14:45\"\r\n account.init_universe = ['000610.XSHE', '000755.XSHE', '600149.XSHG', '000507.XSHE', '002438.XSHE', '000609.XSHE',\r\n '002113.XSHE', '002148.XSHE', '002248.XSHE', '000779.XSHE', '000502.XSHE', '000586.XSHE',\r\n '600689.XSHG', '600671.XSHG', ]\r\n\r\n\r\ndef handle_data(account):\r\n log.info(\"init universe:\" + str(account.init_universe))\r\n if account.i == 0 or len(account.security_position.keys()) <= 6 or len(account.security_position.keys()) >= 20:\r\n last_date = account.previous_date.strftime(\"%Y-%m-%d\")\r\n last_screener = universe.preview(last_date)\r\n\r\n log.info(last_screener)\r\n\r\n buylist = [sec for sec in last_screener if sec in account.init_universe]\r\n v = account.referencePortfolioValue\r\n d = len(buylist)\r\n\r\n # 卖出不在买入列表中的股票,估计持仓价值\r\n for stock in account.valid_secpos:\r\n if stock not in buylist:\r\n if stock in account.universe:\r\n order_to(stock, 0)\r\n else:\r\n v -= account.valid_secpos[stock] * account.referencePrice[stock]\r\n\r\n # 获得调仓数量\r\n change = {}\r\n for stock in buylist:\r\n p = account.referencePrice[stock]\r\n if p and not np.isnan(p):\r\n change[stock] = int(v / d / p) - account.valid_secpos.get(stock, 0)\r\n\r\n # 按先卖后买的顺序发出指令\r\n for stock in sorted(change, key=change.get):\r\n if change[stock] <= -100 or change[stock] >= 100:\r\n order(stock, change[stock])\r\n else:\r\n # 从stockscreener中读取符合筛选条件的n只买入股票\r\n last_date = account.previous_date.strftime(\"%Y-%m-%d\")\r\n last_screener = universe.preview(last_date)\r\n\r\n log.info(\"last_screener:\" + str(last_screener))\r\n\r\n open_last_screener = [i for i in last_screener if\r\n DataAPI.MktEqudGet(tradeDate=account.previous_date, secID=i, field=u\"isOpen\",\r\n pandas=\"1\").loc[0, 'isOpen'] == 1]\r\n\r\n log.info(\"buy_universe:\" + str(open_last_screener))\r\n\r\n buy_list = [stk for stk in open_last_screener if\r\n stk not in account.security_position.keys() and stk not in account.init_universe]\r\n\r\n # 生成业绩最好和最差的1只股票的卖出列表\r\n sell_dict = sorted(account.reference_return.items(), key=lambda d: d[1])\r\n sell_list = []\r\n for value in sell_dict:\r\n stk, _ = value\r\n sell_list.append(stk)\r\n\r\n log.info(\"sorted account.reference_return:\" + str(sell_dict))\r\n log.info(\"account.valid_secpos.keys:\" + str(account.avail_security_position.keys()))\r\n to_sell_list = [i for i in sell_list if i in account.avail_security_position.keys()]\r\n # available_sell_list = to_sell_list[0:len(to_sell_list):len(to_sell_list)-1]\r\n available_sell_list = to_sell_list[0:2]\r\n log.info(\"sell_list:\" + str(sell_list))\r\n log.info(\"available to sell universe:\" + str(available_sell_list))\r\n\r\n # 获取卖出股票的持仓权重\r\n value_sell = []\r\n for i in available_sell_list:\r\n \"{index}to sell value {value}:\".format(index=i,\r\n value=account.avail_security_position[i] * account.referencePrice[i])\r\n value_sell.append(\r\n account.avail_security_position[i] * account.referencePrice[i] / account.referencePortfolioValue)\r\n\r\n len_buy_list = 2 if len(buy_list) > 2 else len(buy_list)\r\n\r\n to_buy_list = [buy_list[i] for i in range(len_buy_list)]\r\n\r\n log.info(\"weight of universe:\" + str(value_sell))\r\n log.info(\"len of weights\" + str(len(value_sell)))\r\n log.info(\"len of buy_list:\" + str(len_buy_list))\r\n\r\n buy_dict = dict(zip(to_buy_list, value_sell))\r\n log.info(\"buy_dict:\" + str(buy_dict))\r\n for s in available_sell_list:\r\n order_to(s, 0)\r\n log.info(\"sell success\")\r\n for key in buy_dict:\r\n order_pct(key, buy_dict[key])\r\n log.info(\"order completed\")\r\n account.i += 1\r\n log.info(str(account.i))\r\n","sub_path":"eric-straregy.py","file_name":"eric-straregy.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"315632567","text":"import cvxpy as cp\nimport cvxpy.settings as s\nfrom cvxpy.tests.base_test import BaseTest\n\nimport numpy as np\n\n\ndef perturbcheck(problem, delta=1e-5, atol=1e-8, eps=1e-10):\n \"\"\"Checks the analytical derivative against a numerical computation.\"\"\"\n np.random.seed(0)\n # Compute perturbations analytically\n for param in problem.parameters():\n param.delta = delta * np.random.randn(*param.shape)\n problem.solve(requires_grad=True, eps=eps)\n problem.derivative()\n variable_values = [v.value for v in problem.variables()]\n deltas = [v.delta for v in problem.variables()]\n\n # Compute perturbations numerically\n old_values = {}\n for param in problem.parameters():\n old_values[param] = param.value\n param.value += param.delta\n problem.solve(cp.SCS, eps=eps)\n num_deltas = [\n v.value - old_value for (v, old_value)\n in zip(problem.variables(), variable_values)]\n\n for analytical, numerical in zip(deltas, num_deltas):\n np.testing.assert_allclose(analytical, numerical, atol=atol)\n\n for param in problem.parameters():\n param.value = old_values[param]\n\n\ndef gradcheck(problem, delta=1e-5, atol=1e-5, eps=1e-10):\n \"\"\"Checks the analytical adjoint derivative against a numerical computation.\"\"\"\n size = sum(p.size for p in problem.parameters())\n values = np.zeros(size)\n offset = 0\n for param in problem.parameters():\n values[offset:offset + param.size] = np.asarray(param.value).flatten()\n param.value = values[offset:offset + param.size].reshape(param.shape)\n offset += param.size\n\n numgrad = np.zeros(values.shape)\n for i in range(values.size):\n old = values[i]\n values[i] = old + 0.5 * delta\n problem.solve(cp.SCS, eps=eps)\n left_solns = [x.value for x in problem.variables()]\n\n values[i] = old - 0.5 * delta\n problem.solve(cp.SCS, eps=eps)\n right_solns = [x.value for x in problem.variables()]\n\n numgrad[i] = (np.sum(left_solns) - np.sum(right_solns)) / delta\n values[i] = old\n numgrads = []\n offset = 0\n for param in problem.parameters():\n numgrads.append(\n numgrad[offset:offset + param.size].reshape(param.shape))\n offset += param.size\n\n old_gradients = {}\n for x in problem.variables():\n old_gradients[x] = x.gradient\n x.gradient = None\n problem.solve(requires_grad=True, eps=eps)\n problem.backward()\n\n for param, numgrad in zip(problem.parameters(), numgrads):\n np.testing.assert_allclose(param.gradient, numgrad, atol=atol)\n\n for x in problem.variables():\n x.gradient = old_gradients[x]\n\n\nclass TestBackward(BaseTest):\n \"\"\"Test problem.backward() and problem.derivative().\"\"\"\n def setUp(self):\n try:\n import diffcp\n diffcp # for flake8\n except ImportError:\n self.skipTest(\"diffcp not installed.\")\n\n def test_scalar_quadratic(self):\n b = cp.Parameter()\n x = cp.Variable()\n quadratic = cp.square(x - 2 * b)\n problem = cp.Problem(cp.Minimize(quadratic), [x >= 0])\n b.value = 3.\n problem.solve(requires_grad=True, eps=1e-10)\n self.assertAlmostEqual(x.value, 6.)\n problem.backward()\n\n # x* = 2 * b, dx*/db = 2\n # x.gradient == None defaults to 1.0\n self.assertAlmostEqual(b.gradient, 2.)\n x.gradient = 4.\n problem.backward()\n self.assertAlmostEqual(b.gradient, 8.)\n gradcheck(problem, atol=1e-4)\n perturbcheck(problem, atol=1e-4)\n\n problem.solve(requires_grad=True, eps=1e-10)\n b.delta = 1e-3\n problem.derivative()\n self.assertAlmostEqual(x.delta, 2e-3)\n\n def test_l1_square(self):\n np.random.seed(0)\n n = 3\n x = cp.Variable(n)\n A = cp.Parameter((n, n))\n b = cp.Parameter(n, name='b')\n objective = cp.Minimize(cp.pnorm(A @ x - b, p=1))\n problem = cp.Problem(objective)\n self.assertTrue(problem.is_dpp())\n\n L = np.random.randn(n, n)\n A.value = L.T @ L + np.eye(n)\n b.value = np.random.randn(n)\n gradcheck(problem)\n perturbcheck(problem)\n\n def test_l1_rectangle(self):\n np.random.seed(0)\n m, n = 3, 2\n x = cp.Variable(n)\n A = cp.Parameter((m, n))\n b = cp.Parameter(m, name='b')\n objective = cp.Minimize(cp.pnorm(A @ x - b, p=1))\n problem = cp.Problem(objective)\n self.assertTrue(problem.is_dpp())\n\n A.value = np.random.randn(m, n)\n b.value = np.random.randn(m)\n gradcheck(problem)\n perturbcheck(problem)\n\n def test_least_squares(self):\n np.random.seed(0)\n m, n = 20, 5\n A = cp.Parameter((m, n))\n b = cp.Parameter(m)\n x = cp.Variable(n)\n obj = cp.sum_squares(A @ x - b) + cp.sum_squares(x)\n problem = cp.Problem(cp.Minimize(obj))\n\n A.value = np.random.randn(m, n)\n b.value = np.random.randn(m)\n gradcheck(problem)\n perturbcheck(problem)\n\n def test_logistic_regression(self):\n np.random.seed(0)\n N, n = 5, 2\n X_np = np.random.randn(N, n)\n a_true = np.random.randn(n, 1)\n\n def sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\n y = np.round(sigmoid(X_np @ a_true + np.random.randn(N, 1) * 0.5))\n\n a = cp.Variable((n, 1))\n X = cp.Parameter((N, n))\n lam = cp.Parameter(nonneg=True)\n log_likelihood = cp.sum(\n cp.multiply(y, X @ a) -\n cp.log_sum_exp(cp.hstack([np.zeros((N, 1)), X @ a]).T, axis=0,\n keepdims=True).T\n )\n problem = cp.Problem(\n cp.Minimize(-log_likelihood + lam * cp.sum_squares(a)))\n X.value = X_np\n lam.value = 1\n # TODO(akshayka): too low but this problem is ill-conditioned\n gradcheck(problem, atol=1e-1, eps=1e-8)\n perturbcheck(problem, atol=1e-4)\n\n def test_entropy_maximization(self):\n np.random.seed(0)\n n, m, p = 5, 3, 2\n\n tmp = np.random.rand(n)\n A_np = np.random.randn(m, n)\n b_np = A_np.dot(tmp)\n F_np = np.random.randn(p, n)\n g_np = F_np.dot(tmp) + np.random.rand(p)\n\n x = cp.Variable(n)\n A = cp.Parameter((m, n))\n b = cp.Parameter(m)\n F = cp.Parameter((p, n))\n g = cp.Parameter(p)\n obj = cp.Maximize(cp.sum(cp.entr(x)) - cp.sum_squares(x))\n constraints = [A @ x == b,\n F @ x <= g]\n problem = cp.Problem(obj, constraints)\n A.value = A_np\n b.value = b_np\n F.value = F_np\n g.value = g_np\n gradcheck(problem, atol=1e-2, eps=1e-8)\n perturbcheck(problem, atol=1e-4)\n\n def test_lml(self):\n np.random.seed(0)\n k = 2\n x = cp.Parameter(4)\n y = cp.Variable(4)\n obj = -x @ y - cp.sum(cp.entr(y)) - cp.sum(cp.entr(1. - y))\n cons = [cp.sum(y) == k]\n problem = cp.Problem(cp.Minimize(obj), cons)\n\n x.value = np.array([1., -1., -1., -1.])\n # TODO(akshayka): This tolerance is too low.\n gradcheck(problem, atol=1e-2)\n perturbcheck(problem, atol=1e-4)\n\n def test_sdp(self):\n np.random.seed(0)\n n = 3\n p = 3\n C = cp.Parameter((n, n))\n As = [cp.Parameter((n, n)) for _ in range(p)]\n bs = [cp.Parameter((1, 1)) for _ in range(p)]\n\n C.value = np.random.randn(n, n)\n for A, b in zip(As, bs):\n A.value = np.random.randn(n, n)\n b.value = np.random.randn(1, 1)\n\n X = cp.Variable((n, n), PSD=True)\n constraints = [cp.trace(As[i] @ X) == bs[i] for i in range(p)]\n problem = cp.Problem(cp.Minimize(cp.trace(C @ X) + cp.sum_squares(X)),\n constraints)\n gradcheck(problem, atol=1e-3)\n perturbcheck(problem)\n\n def test_forget_requires_grad(self):\n np.random.seed(0)\n m, n = 20, 5\n A = cp.Parameter((m, n))\n b = cp.Parameter(m)\n x = cp.Variable(n)\n obj = cp.sum_squares(A @ x - b) + cp.sum_squares(x)\n problem = cp.Problem(cp.Minimize(obj))\n A.value = np.random.randn(m, n)\n b.value = np.random.randn(m)\n problem.solve()\n with self.assertRaisesRegex(ValueError,\n \"backward can only be called after calling \"\n \"solve with `requires_grad=True`\"):\n problem.backward()\n with self.assertRaisesRegex(ValueError,\n \"derivative can only be called after calling \"\n \"solve with `requires_grad=True`\"):\n problem.derivative()\n\n def test_infeasible(self):\n x = cp.Variable()\n param = cp.Parameter()\n problem = cp.Problem(cp.Minimize(param), [x >= 1, x <= -1])\n param.value = 1\n try:\n problem.solve(requires_grad=True)\n except cp.SolverError:\n with self.assertRaisesRegex(ValueError, \"Backpropagating through \"\n \"infeasible/unbounded.*\"):\n problem.backward()\n with self.assertRaisesRegex(ValueError, \"Differentiating through \"\n \"infeasible/unbounded.*\"):\n problem.derivative()\n\n def test_unbounded(self):\n x = cp.Variable()\n param = cp.Parameter()\n problem = cp.Problem(cp.Minimize(x), [x <= param])\n param.value = 1\n try:\n problem.solve(requires_grad=True)\n except cp.SolverError:\n with self.assertRaisesRegex(ValueError, \"Backpropagating through \"\n \"infeasible/unbounded.*\"):\n problem.backward()\n with self.assertRaisesRegex(ValueError, \"Differentiating through \"\n \"infeasible/unbounded.*\"):\n problem.derivative()\n\n def test_unsupported_solver(self):\n x = cp.Variable()\n param = cp.Parameter()\n problem = cp.Problem(cp.Minimize(x), [x <= param])\n param.value = 1\n with self.assertRaisesRegex(ValueError,\n \"When requires_grad is True, the \"\n \"only supported solver is SCS.*\"):\n problem.solve(cp.ECOS, requires_grad=True)\n\n def test_zero_in_problem_data(self):\n x = cp.Variable()\n param = cp.Parameter()\n param.value = 0.0\n problem = cp.Problem(cp.Minimize(x), [param * x >= 0])\n data, _, _ = problem.get_problem_data(cp.DIFFCP)\n A = data[s.A]\n self.assertIn(0.0, A.data)\n","sub_path":"cvxpy/tests/test_derivative.py","file_name":"test_derivative.py","file_ext":"py","file_size_in_byte":10792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"390461778","text":"# Module Dependency\nimport pymongo\nimport datetime\nfrom flask import Flask, jsonify,render_template\nfrom scrape_mars import *\n\n# Import Flask\nfrom flask import Flask\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n#################################################\n# Flask Routes\n#################################################\ndef get_mars_info():\n\t# Create a connection to heroku mongodb database\n\tclient = pymongo.MongoClient(\"mongodb://admin:adminadmin@ds143245.mlab.com:43245/heroku_hsr9k4sx\")\n\tdb = client.heroku_hsr9k4sx\n\t\n\n # Create a connection to localhost\n\t# conn = \"mongodb://localhost:27017\"\n\t# client = pymongo.MongoClient(conn)\n\t# db = client.mars_db\n\n\n\t# Create a connection and database\n\t# conn = \"mongodb://localhost:27017\"\n\t# client = pymongo.MongoClient(conn)\n\t# db = client.mars_db\n\n\n\tmars_info = db.mars_db\n\tresults = list(db.mars_info.find().sort('date',pymongo.DESCENDING).limit(1))\n\n\treturn results\n\n\n@app.route(\"/\")\ndef index():\n\tresults = get_mars_info()\n\tprint(len(results))\n\tif len(results) == 0:\n\t\treturn render_template(\"default.html\")\n\telse:\n\t\treturn render_template(\"index.html\", mars=results[0])\n\n\n@app.route(\"/scrape\")\ndef mars_scrape():\n\t\"\"\"Return a list of all passenger names\"\"\"\n\t# Query all passengers\n\tscrape()\n\tresults = get_mars_info()\n\treturn render_template(\"index.html\", mars=results[0]) \n\n\nif __name__ == '__main__':\n\tapp.jinja_env.auto_reload = True\n\tapp.config['TEMPLATES_AUTO_RELOAD'] = True\n\tapp.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"318859564","text":"#!coding:utf-8\nfrom django.contrib import messages\n\n\nclass FilterMixin(object):\n\n # Estrutura de exemplo, onde o primeiro item é o campo do model e o segundo é o tipo de consulta\n # Ex: ('nome', \"icontains\")\n # filters = (\n # ('field', 'type'),\n # )\n\n def get_queryset(self):\n \n qs = super(FilterMixin, self).get_queryset()\n if not hasattr(self, 'filters'):\n return qs \n\n for field, type in self.filters:\n\n data = self.request.GET.get(field)\n if data:\n filter_arg = {field: data}\n if type:\n filter_arg = {\"%s__%s\" % (field, type): data}\n\n qs = qs.filter(**filter_arg)\n \n return qs\n \nclass MessageMixin(object):\n\n message_type = \"success\"\n # message = \"Formulário adicionado com sucesso\"\n\n def get_context_data(self, **kwargs):\n if hasattr(self, 'message'):\n getattr(messages, self.message_type)(self.request, self.message)\n return super(MessageMixin, self).get_context_data(**kwargs)","sub_path":"proj/utils/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"637447955","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport imageio\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\nimport tarfile\nfrom IPython.display import display, Image\nfrom sklearn.linear_model import LogisticRegression\nfrom six.moves.urllib.request import urlretrieve\nfrom six.moves import cPickle as pickle\nimport tensorflow as tf\n\nimage_size = 28\npixel_depth = 255.0\n\ndef make_arrays(nb_rows, img_size):\n if nb_rows:\n dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)\n labels = np.ndarray(nb_rows, dtype=np.int32)\n else:\n dataset, labels = None, None\n return dataset, labels\n\ndef merge_datasets(pickle_files, train_size, valid_size=0):\n num_classes = len(pickle_files)\n valid_dataset, valid_labels = make_arrays(valid_size, image_size)\n train_dataset, train_labels = make_arrays(train_size, image_size)\n vsize_per_class = valid_size // num_classes\n tsize_per_class = train_size // num_classes\n\n start_v, start_t = 0, 0\n end_v, end_t = vsize_per_class, tsize_per_class\n end_l = vsize_per_class+tsize_per_class\n for label, pickle_file in enumerate(pickle_files):\n try:\n with open(pickle_file, 'rb') as f:\n letter_set = pickle.load(f)\n # let's shuffle the letters to have random validation and training set\n np.random.shuffle(letter_set)\n if valid_dataset is not None:\n valid_letter = letter_set[:vsize_per_class, :, :]\n valid_dataset[start_v:end_v, :, :] = valid_letter\n valid_labels[start_v:end_v] = label\n start_v += vsize_per_class\n end_v += vsize_per_class\n\n train_letter = letter_set[vsize_per_class:end_l, :, :]\n train_dataset[start_t:end_t, :, :] = train_letter\n train_labels[start_t:end_t] = label\n start_t += tsize_per_class\n end_t += tsize_per_class\n except Exception as e:\n print('Unable to process data from', pickle_file, ':', e)\n raise\n\n return valid_dataset, valid_labels, train_dataset, train_labels\n\ndef randomize(dataset, labels):\n permutation = np.random.permutation(labels.shape[0])\n shuffled_dataset = dataset[permutation,:,:]\n shuffled_labels = labels[permutation]\n return shuffled_dataset, shuffled_labels\n\ndef main():\n train_folder = 'notMNIST_large'\n test_folder = 'notMNIST_small'\n\n train_datasets = [ os.path.join(train_folder, x) for x in os.listdir(train_folder) if x.endswith(\".pickle\") ]\n test_datasets = [ os.path.join(train_folder, x) for x in os.listdir(test_folder) if x.endswith(\".pickle\") ]\n\n train_size = 200000\n valid_size = 10000\n test_size = 10000\n\n valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(\n train_datasets, train_size, valid_size)\n _, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)\n\n print('Training:', train_dataset.shape, train_labels.shape)\n print('Validation:', valid_dataset.shape, valid_labels.shape)\n print('Testing:', test_dataset.shape, test_labels.shape)\n\n train_dataset, train_labels = randomize(train_dataset, train_labels)\n test_dataset, test_labels = randomize(test_dataset, test_labels)\n valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)\n\n learning_rate = 0.5\n epochs = 10\n batch_size = 100\n\n train_tensor = tf.convert_to_tensor(train_dataset)\n train_dataset = tf.Session().run(tf.reshape(train_tensor, [-1, image_size * image_size]))\n test_tensor = tf.convert_to_tensor(test_dataset)\n test_dataset = tf.Session().run(tf.reshape(test_tensor, [-1, image_size * image_size]))\n valid_tensor = tf.convert_to_tensor(valid_dataset)\n valid_dataset = tf.Session().run(tf.reshape(valid_tensor, [-1, image_size * image_size]))\n\n train_labels = tf.Session().run(tf.one_hot(train_labels, depth=10))\n test_labels = tf.Session().run(tf.one_hot(test_labels, depth=10))\n valid_labels = tf.Session().run(tf.one_hot(valid_labels, depth=10))\n\n # Layers\n # l1_dim = 300\n # l2_dim = 10\n x = tf.placeholder(tf.float32, [None, 784])\n y = tf.placeholder(tf.float32, [None, 10])\n # W1 = tf.Variable(tf.random_normal([784, l1_dim], stddev=0.3), name='W1')\n # b1 = tf.Variable(tf.random_normal([l1_dim]), name='b1')\n # W2 = tf.Variable(tf.random_normal([l1_dim, l2_dim], stddev=0.3), name='W2')\n # b2 = tf.Variable(tf.random_normal([l2_dim]), name='b2')\n #\n # l1_out = tf.nn.relu(tf.add(tf.matmul(x, W1), b1))\n # y_ = tf.nn.softmax(tf.add(tf.matmul(l1_out, W2), b2))\n\n\n input_layer = tf.reshape(x, [-1, 28, 28, 1])\n conv1 = tf.layers.conv2d(input_layer, filters=32, kernel_size=[5, 5], padding='same', activation=tf.nn.relu)\n pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)\n conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5], padding=\"same\", activation=tf.nn.relu)\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)\n pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])\n dense = tf.layers.dense(pool2_flat, units=1024, activation=tf.nn.relu)\n dropout = tf.layers.dropout(inputs=dense, rate=0.4, training=True)\n logits = tf.layers.dense(inputs=dropout, units=10)\n y_ = tf.nn.softmax(logits)\n\n y_clipped = tf.clip_by_value(y_, 1e-10, 0.9999999)\n # cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped) + (1 - y) * tf.log(1 - y_clipped), axis=1))\n cross_entropy = -tf.reduce_mean(tf.reduce_sum(y * tf.log(y_clipped), axis=1))\n optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)\n\n init_op = tf.global_variables_initializer()\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n print(\"Training starts ... \")\n sess = tf.Session()\n sess.run(init_op)\n total_batch = int(train_size / batch_size)\n for epoch in range(epochs):\n avg_cost = 0\n for i in range(total_batch):\n batch_x = train_dataset[batch_size * i : batch_size * (i+1), :]\n batch_y = train_labels[batch_size * i : batch_size * (i+1), :]\n _, c = sess.run([optimizer, cross_entropy], feed_dict={x: batch_x, y: batch_y})\n avg_cost += c / total_batch\n\n print(\"Epoch: \", (epoch + 1), \"cost=\", \"{:.3f}\".format(avg_cost))\n print(sess.run(accuracy, feed_dict={ x: test_dataset, y: test_labels }))\n \n\n # Actually run\n # const = tf.constant(2.0, name=\"const\")\n # b = tf.Variable(2.0, name='b')\n # b = tf.placeholder(tf.float32, [None, 1], name='b')\n # c = tf.Variable(1.0, name='c')\n # d = tf.add(b, c, name='d')\n # e = tf.add(c, const, name='e')\n # a = tf.multiply(d, e, name='a')\n #\n # init_op = tf.global_variables_initializer()\n # sess = tf.Session()\n # sess.run(init_op)\n # a_out = sess.run(a, feed_dict={ b: np.arange(0, 10)[:, np.newaxis] })\n # print(a_out)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"assignments/nmist.py","file_name":"nmist.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"523553071","text":"import hyperparams as hp\nimport re\nimport glob\nimport os\nimport pickle\nimport utils\nimport dill\nimport torch\nimport unicodedata\n\n\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n \ndef _normalize(s):\n s = unicodeToAscii(s.lower().strip())\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n return s\n\ndef load_model(latest=True,name=None):\n if name==None:\n if latest:\n field_paths = glob.glob(\"./models/fields/*\")\n latest_file = max(field_paths, key=os.path.getctime)\n pattern=re.compile(\"fields_([0-9\\-]*)_(\\d*).pkl\")\n \n with open(latest_file,'rb')as f:\n fields=dill.load(f)\n #with open(f\"./models/fields/{latest_file}\",'rb') as handle:\n # fields=pickle.load(handle)\n date_version=re.findall(pattern,latest_file)\n model_path=f\"./models/model/seq2seq_{date_version[0][0]}_{date_version[0][1]}.pt\"\n model = torch.load(model_path)\n return model,fields\n print(\"Please specify correct arguments\")\n else:\n pattern=re.compile(\"seq2seq_([0-9\\-]*)_(\\d*).pt\")\n date_version=re.findall(pattern,name)\n field_path=f\"./models/fields/fields_{date_version[0][0]}_{date_version[0][1]}.pkl\"\n with open(field_path,'rb')as f:\n fields=dill.load(f)\n #with open(field_path,'rb') as handle:\n #fields=pickle.load(handle)\n model_path=f\"./models/model/seq2seq_{date_version[0][0]}_{date_version[0][1]}.pt\"\n model = torch.load(model_path)\n return model,fields\n \nclass QuestionPredictor(object):\n def __init__(self,model=None,latest=True):\n self.model,self.fields=load_model(latest=latest,name=model)\n self.model.to(hp.device)\n def predict(self,sent,beam=False,beam_size=3):\n if beam:\n return utils.predict_beam(model=self.model,sent=_normalize(sent),fields=self.fields,beam_size=beam_size)\n return utils.predict(model=self.model,sent=_normalize(sent),fields=self.fields)\n","sub_path":".ipynb_checkpoints/test_serve-checkpoint.py","file_name":"test_serve-checkpoint.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"5814882","text":"import json\r\nimport re\r\nfrom tkinter import filedialog\r\n\r\nfull_intents = {}\r\nfull_variables = {}\r\nvars_dict = {}\r\nintents_dict = {}\r\nintent_permutations = {} # Dict of all possible intent names (with variables subbed in)\r\nink_intents = []\r\nink_vars = []\r\npermd_vars = {}\r\npermd_intents = {}\r\n\r\n\r\ndef main():\r\n global full_intents, full_variables, ink_intents, vars_dict, intents_dict\r\n ink_path = filedialog.askopenfilename(title=\"Select ink file\", filetypes=[(\"Ink Files\", \"*.ink\")]) # Path for ink\r\n ink_file = open(ink_path, 'r').read()\r\n\r\n # Strip from ink path the path and the file type, then add \"_intents.json\"\r\n encounter_intent_name = ink_path.split(\"/\")[-1].split(\".\")[0] + \"_intents.json\"\r\n json_boilerplate = json.loads(open(\"intents_boilerplate.json\", 'r').read())\r\n\r\n intents_master = json.loads(open(\"intents.json\", 'r').read()) # Dict object of json intents\r\n full_intents = intents_master[\"dialog\"][0][\"intents\"]\r\n full_variables = intents_master[\"dialog\"][1][\"variables\"]\r\n for entry in full_intents:\r\n intents_dict.update({entry[\"name\"] : entry[\"examples\"]})\r\n if \"alternative name\" in entry:\r\n for alt_name in entry[\"alternative name\"]:\r\n intents_dict.update({alt_name: entry[\"examples\"]})\r\n for entry in full_variables:\r\n vars_dict.update({entry[\"name\"]: entry[\"examples\"]})\r\n\r\n get_var_perms()\r\n get_intent_perms()\r\n relevant_ink = re.split(\"== encounter_start ==\", ink_file)[1]\r\n ink_intents = re.findall(r\"(?<=\\[)[^\\]]*(?=\\])\", relevant_ink) # Array of all intents in encounter\r\n placeholder_ink = []\r\n for ink_intent in ink_intents:\r\n placeholder_ink.append(str.lower(ink_intent))\r\n ink_intents = placeholder_ink\r\n for intent in permd_intents:\r\n for example in permd_intents[intent]:\r\n if str.lower(example) in ink_intents:\r\n entry = {\"name\": intent}\r\n entry.update({\"examples\": intents_dict[intent]})\r\n json_boilerplate[\"dialog\"][0][\"intents\"].append(entry)\r\n if re.findall(\"{[^}]*}\", intent): # If there are vars in the intent\r\n _vars = re.findall(r\"(?<={)[^}]*(?=})\", intent) # Get all vars\r\n while _vars:\r\n var_placeholder = _vars\r\n for _var in _vars: # For each _var\r\n for var_example in vars_dict[_var]:\r\n if re.findall(r\"{[^}]*}\", var_example):\r\n var_placeholder += re.findall(r\"(?<={)[^}]*(?=})\", var_example)\r\n var_entry = {\"name\": _var}\r\n var_entry.update({\"examples\": vars_dict[_var]})\r\n json_boilerplate[\"dialog\"][1][\"variables\"].append(var_entry)\r\n var_placeholder.remove(_var)\r\n _vars = var_placeholder\r\n encounter_intent_name = filedialog.asksaveasfilename(filetypes=[(\"JSON Files\", \"*.json\")])\r\n if str.lower(encounter_intent_name.split(\".\")[-1]) == \"json\":\r\n encounter_json = open(encounter_intent_name, 'w')\r\n else:\r\n encounter_json = open(encounter_intent_name + \".json\", 'w')\r\n encounter_json.write(json.dumps(json_boilerplate))\r\n\r\n\r\ndef get_var_perms():\r\n global vars_dict, permd_vars\r\n for _var in vars_dict:\r\n permd_vars[_var] = []\r\n for example in vars_dict[_var]:\r\n if len(example.split(\"; \")) > 1:\r\n if re.findall(\"{[^}]*}\", example):\r\n for split_perm in example.split(\"; \"):\r\n if re.findall(\"{[^}]*}\", split_perm):\r\n permd_vars[_var] += get_example_perms(split_perm)\r\n else:\r\n permd_vars[_var].append(split_perm)\r\n else:\r\n permd_vars[_var] += example.split(\"; \")\r\n elif re.findall(\"{[^}]*}\", example):\r\n permd_vars[_var] += get_example_perms(example)\r\n else:\r\n # If no semicolons and no brackets\r\n permd_vars[_var].append(example)\r\n\r\n\r\ndef get_example_perms(_in):\r\n # This function gets all the permutations of an example that contains brackets\r\n # and returns the permutations as a list\r\n permutations = []\r\n _vars = re.findall(r\"(?<={)[^}]*(?=})\", _in)\r\n for _var in _vars:\r\n # For each example of the current _var\r\n perms_placeholder = []\r\n for example in vars_dict[_var]:\r\n if not permutations:\r\n if re.findall(\"{[^}]*}\", example):\r\n # We must recurse if there are brackets in the example\r\n for subperm in get_example_perms(example):\r\n perms_placeholder.append(re.sub(\"{%s}\" % _var, subperm, _in))\r\n else:\r\n perms_placeholder.append(re.sub(\"{%s}\" % _var, example, _in))\r\n else:\r\n if re.findall(\"{[^}]*}\", example):\r\n # We must recurse if there are brackets in the example\r\n for subperm in get_example_perms(example):\r\n for perm in permutations:\r\n perms_placeholder.append(re.sub(\"{%s}\" % _var, subperm, perm))\r\n else:\r\n for perm in permutations:\r\n perms_placeholder.append(re.sub(\"{%s}\" % _var, example, perm))\r\n permutations = perms_placeholder\r\n return permutations\r\n\r\n\r\ndef get_intent_perms():\r\n global permd_intents\r\n for intent in intents_dict:\r\n perms = []\r\n permd_intents[intent] = []\r\n if re.findall(\"{[^}]*}\", intent):\r\n _vars = re.findall(r\"(?<={)[^}]*(?=})\", intent)\r\n for _var in _vars:\r\n placeholder_perms = []\r\n if _var in permd_vars:\r\n for example in permd_vars[_var]:\r\n if not perms:\r\n placeholder_perms.append(re.sub(\"{%s}\" % _var, example, intent))\r\n else:\r\n for perm in perms:\r\n placeholder_perms.append(re.sub(\"{%s}\" % _var, example, perm))\r\n perms = placeholder_perms\r\n permd_intents[intent] += perms\r\n\r\n else:\r\n permd_intents[intent] = [intent]\r\n\r\n\r\nmain()\r\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"400911567","text":"import os\nfrom site_scons.options import *\n\nEnsureSConsVersion(2, 3, 0)\nenv = Environment(tools = ['default', 'project', 'gcov'])\n\nadd_option('release',\n help='Execute a release build',\n nargs=0,\n)\n\nadd_option('gcov',\n help='Execute a gcov build',\n nargs=0,\n)\n\nadd_option('gcov-xml',\n help='Output coverage information in XML format',\n nargs=0,\n)\n\nadd_option('gcov-html',\n help='Output coverage information in HTML format',\n nargs=0,\n)\n\nadd_option('proper-clean',\n help='Remove the build output directory',\n nargs=0,\n)\n\nif has_option('proper-clean'):\n Execute(Action('rm -r build', 'Removing build output directory'))\n Exit(0)\n\nif has_option('release') and has_option('gcov'):\n env.FatalError('release build with gcov not supported.')\n\nif has_option('gcov'):\n gcov_options = {}\n if has_option('gcov-xml'):\n gcov_options['format'] = 'xml'\n if has_option('gcov-html'):\n gcov_options['format'] = 'html'\n env.EnableGcov(gcov_options)\n\nenv.Append(CXXFLAGS = [\n '--std=c++11', \n '-fmessage-length=0',\n '-Wall', '-Wextra', '-Werror'\n])\n\nenv.Append(LINKFLAGS = env['CXXFLAGS'])\n\nif has_option('release'):\n env.Append(CPPDEFINES = ['RELEASE'])\n env.Append(CXXFLAGS = ['-O3'])\nelse:\n env.Append(CPPDEFINES = ['DEBUG'])\n env.Append(CXXFLAGS = ['-O0', '-ggdb'])\n\nenv.Append(VARIANT_DIR = 'build/%s' % get_build_mode())\n\nfor target in ['applications', 'components']:\n env.SConscript('%s/SConscript' % target,\n exports = {'env': env},\n variant_dir=os.path.join(env['VARIANT_DIR'], target),\n duplicate=False)\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"418847380","text":"import numpy as np\nimport random\nimport collections\nimport timeit\nimport copy\n\nfrom dice_ml import diverse_counterfactuals as exp\nfrom dice_ml.utils.sample_architecture.vae_model import CF_VAE\n\n#Pytorch\nimport torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\nfrom torch.autograd import Variable\n\nclass DiceModelApproxGenCF:\n\n def __init__(self, data_interface, model_interface):\n \"\"\"\n :param data_interface: an interface class to data related params\n :param model_interface: an interface class to access trained ML model\n \"\"\" \n \n self.pred_model= model_interface\n self.data_interface= data_interface\n \n self.encoded_size=10\n self.data_size = len(self.data_interface.encoded_feature_names)\n\n # Dataset for training Variational Encoder Decoder model for CF Generation\n train_data_vae= self.data_interface.data_df.copy()\n \n #MAD\n #self.mad_feature_weights = self.data_interface.get_mads_from_training_data(normalized=False)\n\n #Creating list of encoded categorical and continuous feature indices\n encoded_categorical_feature_indexes = self.data_interface.get_data_params()[2] \n encoded_continuous_feature_indexes=[]\n for i in range(self.data_size):\n valid=1\n for v in encoded_categorical_feature_indexes:\n if i in v:\n valid=0\n if valid:\n encoded_continuous_feature_indexes.append(i) \n encoded_start_cat = len(encoded_continuous_feature_indexes)\n \n #One Hot Encoding for categorical features\n encoded_data = self.data_interface.one_hot_encode_data(train_data_vae)\n \n # The output/outcome variable position altered due to one_hot_encoding for categorical features: (Cont feat, Outcome, Cat feat) \n # Need to rearrange columns such that outcome variable comes at the last\n cols = list(encoded_data.columns)\n cols = cols[:encoded_start_cat] + cols[encoded_start_cat+1:] + [cols[encoded_start_cat]]\n encoded_data = encoded_data[cols] \n\n #Normlaise_Weights\n self.normalise_weights={} \n dataset = encoded_data.to_numpy()\n for idx in encoded_continuous_feature_indexes:\n _max= float(np.max( dataset[:,idx] ))\n _min= float(np.min( dataset[:,idx] ))\n self.normalise_weights[idx]=[_min, _max]\n\n # Normlization for continuous features\n encoded_data= self.data_interface.normalize_data(encoded_data)\n dataset = encoded_data.to_numpy()\n\n #Train, Val, Test Splits\n np.random.shuffle(dataset)\n test_size= int(0.1*dataset.shape[0])\n self.vae_test_dataset= dataset[:test_size]\n dataset= dataset[test_size:]\n self.vae_val_dataset= dataset[:test_size]\n self.vae_train_dataset= dataset[test_size:]\n\n #BaseGenCF Model\n self.cf_vae = CF_VAE(self.data_size, self.encoded_size, self.data_interface)\n \n #Hyperparam \n # Currently set to the specific values for the Adult dataset; dataset dependent\n # TODO: Make these hyperparam dataset dependent\n self.learning_rate= 1e-2\n self.batch_size= 2048\n self.validity_reg= 42.0 \n self.margin= 0.165\n self.epochs= 25\n self.wm1=1e-2\n self.wm2=1e-2\n self.wm3=1e-2\n \n #Optimizer \n self.cf_vae_optimizer = optim.Adam([\n {'params': filter(lambda p: p.requires_grad, self.cf_vae.encoder_mean.parameters()),'weight_decay': self.wm1},\n {'params': filter(lambda p: p.requires_grad, self.cf_vae.encoder_var.parameters()),'weight_decay': self.wm2},\n {'params': filter(lambda p: p.requires_grad, self.cf_vae.decoder_mean.parameters()),'weight_decay': self.wm3},\n ], lr=self.learning_rate\n )\n \n self.base_model_dir= '../dice_ml/utils/sample_trained_models/'\n self.dataset_name= 'adult'\n ##TODO: A general method to identify the dataset_name\n self.save_path=self.base_model_dir+ self.dataset_name +'-margin-' + str(self.margin) + '-validity_reg-'+ str(self.validity_reg) + '-epoch-' + str(self.epochs) + '-' + 'base-gen' + '.pth'\n \n def compute_loss( self, model_out, x, target_label ): \n\n em = model_out['em']\n ev = model_out['ev']\n z = model_out['z']\n dm = model_out['x_pred']\n mc_samples = model_out['mc_samples']\n #KL Divergence\n kl_divergence = 0.5*torch.mean( em**2 +ev - torch.log(ev) - 1, axis=1 ) \n\n #Reconstruction Term\n #Proximity: L1 Loss\n x_pred = dm[0] \n s= self.cf_vae.encoded_start_cat\n recon_err = -torch.sum( torch.abs(x[:,s:-1] - x_pred[:,s:-1]), axis=1 )\n for key in self.normalise_weights.keys():\n # recon_err+= -(1/mad_feature_weights[d.encoded_feature_names[int(key)]])*(normalise_weights[key][1] - normalise_weights[key][0])*torch.abs(x[:,key] - x_pred[:,key]) \n recon_err+= -(self.normalise_weights[key][1] - self.normalise_weights[key][0])*torch.abs(x[:,key] - x_pred[:,key]) \n\n # Sum to 1 over the categorical indexes of a feature\n for v in self.cf_vae.encoded_categorical_feature_indexes:\n temp = -torch.abs( 1.0-torch.sum( x_pred[:, v[0]:v[-1]+1], axis=1) )\n recon_err += temp\n\n count=0\n count+= torch.sum(x_pred[:,:s]<0,axis=1).float()\n count+= torch.sum(x_pred[:,:s]>1,axis=1).float() \n\n #Validity \n temp_logits = self.pred_model(x_pred)\n validity_loss= torch.zeros(1) \n temp_1= temp_logits[target_label==1,:]\n temp_0= temp_logits[target_label==0,:]\n validity_loss += F.hinge_embedding_loss( F.sigmoid(temp_1[:,1]) - F.sigmoid(temp_1[:,0]), torch.tensor(-1), self.margin, reduction='mean')\n validity_loss += F.hinge_embedding_loss( F.sigmoid(temp_0[:,0]) - F.sigmoid(temp_0[:,1]), torch.tensor(-1), self.margin, reduction='mean')\n\n for i in range(1,mc_samples):\n x_pred = dm[i] \n\n recon_err += -torch.sum( torch.abs(x[:,s:-1] - x_pred[:,s:-1]), axis=1 )\n for key in self.normalise_weights.keys():\n # recon_err+= -(1/mad_feature_weights[d.encoded_feature_names[int(key)]])*(normalise_weights[key][1] - normalise_weights[key][0])*torch.abs( (x[:,key] - x_pred[:,key]))\n recon_err+= -(self.normalise_weights[key][1] - self.normalise_weights[key][0])*torch.abs(x[:,key] - x_pred[:,key]) \n\n # Sum to 1 over the categorical indexes of a feature\n for v in self.cf_vae.encoded_categorical_feature_indexes:\n temp = -torch.abs( 1.0-torch.sum( x_pred[:, v[0]:v[-1]+1], axis=1) )\n recon_err += temp\n\n count+= torch.sum(x_pred[:,:s]<0,axis=1).float()\n count+= torch.sum(x_pred[:,:s]>1,axis=1).float() \n\n #Validity\n temp_logits = self.pred_model(x_pred)\n # validity_loss += -F.cross_entropy(temp_logits, target_label) \n temp_1= temp_logits[target_label==1,:]\n temp_0= temp_logits[target_label==0,:]\n validity_loss += F.hinge_embedding_loss( F.sigmoid(temp_1[:,1]) - F.sigmoid(temp_1[:,0]), torch.tensor(-1), self.margin, reduction='mean')\n validity_loss += F.hinge_embedding_loss( F.sigmoid(temp_0[:,0]) - F.sigmoid(temp_0[:,1]), torch.tensor(-1), self.margin, reduction='mean')\n\n recon_err = recon_err / mc_samples\n validity_loss = -1*self.validity_reg*validity_loss/mc_samples\n\n print('Avg wrong cont dim: ', torch.mean(count)/mc_samples)\n print('recon: ',-torch.mean(recon_err), ' KL: ', torch.mean(kl_divergence), ' Validity: ', -validity_loss)\n return -torch.mean(recon_err - kl_divergence) - validity_loss \n \n \n def train( self, constraint_type, constraint_variables, constraint_direction, constraint_reg, pre_trained=False ):\n \n ''' \n pre_trained: Bool Variable to check whether pre trained model exists to avoid training again \n constraint_type: Binary Variable currently: (1) unary / (0) monotonic\n constraint_variables: List of List: [[Effect, Cause1, Cause2, .... ]]\n constraint_direction: -1: Negative, 1: Positive ( By default has to be one for monotonic constraints )\n constraint_reg: Tunable Hyperparamter\n '''\n \n if pre_trained:\n self.cf_vae.load_state_dict(torch.load(self.save_path))\n self.cf_vae.eval()\n return \n \n ##TODO: Handling such dataset specific constraints in a more general way\n # CF Generation for only low to high income data points\n self.vae_train_dataset= self.vae_train_dataset[self.vae_train_dataset[:,-1]==0,:]\n self.vae_val_dataset= self.vae_val_dataset[self.vae_val_dataset[:,-1]==0,:]\n\n #Removing the outcome variable from the datasets\n self.vae_train_feat= self.vae_train_dataset[:,:-1]\n self.vae_val_feat= self.vae_val_dataset[:,:-1] \n \n for epoch in range(self.epochs):\n batch_num=0\n train_loss= 0.0\n train_size=0\n \n train_dataset= torch.tensor(self.vae_train_feat).float()\n train_dataset= torch.utils.data.DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)\n for train_x in enumerate(train_dataset):\n self.cf_vae_optimizer.zero_grad()\n \n train_x= train_x[1]\n train_y= 1.0-torch.argmax( self.pred_model(train_x), dim=1 )\n train_size+= train_x.shape[0]\n \n out= self.cf_vae(train_x, train_y)\n loss= self.compute_loss( out, train_x, train_y )\n \n #Unary Case\n if constraint_type:\n for const in constraint_variables:\n # Get the index from the feature name\n # Handle the categorical variable case here too\n const_idx= const[0]\n dm = out['x_pred']\n mc_samples = out['mc_samples']\n x_pred = dm[0]\n \n constraint_loss = F.hinge_embedding_loss( constraint_direction*(x_pred[:,const_idx] - train_x[:,const_idx]), torch.tensor(-1), 0)\n\n for j in range(1, mc_samples):\n x_pred = dm[j] \n constraint_loss+= F.hinge_embedding_loss( constraint_direction*(x_pred[:,const_idx] - train_x[:,const_idx]), torch.tensor(-1), 0) \n \n constraint_loss= constraint_loss/mc_samples\n constraint_loss= constraint_reg*constraint_loss\n loss+= constraint_loss\n print('Constraint: ', constraint_loss, torch.mean(constraint_loss) )\n else:\n #Train the regression model\n print('Yet to implement')\n \n loss.backward()\n train_loss += loss.item()\n self.cf_vae_optimizer.step()\n \n batch_num+=1\n \n ret= loss/batch_num\n print('Train Avg Loss: ', ret, train_size )\n \n #Save the model after training every 10 epochs and at the last epoch\n if (epoch!=0 and epoch%10==0) or epoch==self.epochs-1:\n torch.save(self.cf_vae.state_dict(), self.save_path) \n \n \n #The input arguments for this function same as the one defined for Diverse CF \n def generate_counterfactuals(self, query_instance, total_CFs, desired_class=\"opposite\", ):\n\n ## Loading the latest trained CFVAE model\n self.cf_vae.load_state_dict(torch.load(self.save_path))\n self.cf_vae.eval()\n \n # Converting query_instance into numpy array\n query_instance_org= query_instance\n \n query_instance = self.data_interface.prepare_query_instance(query_instance=query_instance, encode=True)\n query_instance = np.array([query_instance.iloc[0].values])\n \n print(query_instance.shape[0])\n if query_instance.shape[0] > self.batch_size:\n test_dataset= np.array_split( query_instance, query_instance.shape[0]//self.batch_size ,axis=0 )\n else:\n test_dataset= [ query_instance ] \n final_gen_cf=[]\n final_cf_pred=[]\n final_test_pred=[]\n for i in range(len(query_instance)):\n train_x = test_dataset[i]\n train_x= torch.tensor( train_x ).float()\n train_y = torch.argmax( self.pred_model(train_x), dim=1 ) \n \n curr_gen_cf=[]\n curr_cf_pred=[] \n curr_test_pred= train_y.numpy()\n \n for cf_count in range(total_CFs): \n recon_err, kl_err, x_true, x_pred, cf_label = self.cf_vae.compute_elbo( train_x, 1.0-train_y, self.pred_model )\n while( cf_label== train_y):\n print(cf_label, train_y)\n recon_err, kl_err, x_true, x_pred, cf_label = self.cf_vae.compute_elbo( train_x, 1.0-train_y, self.pred_model )\n \n x_pred= x_pred.detach().numpy()\n #Converting mixed scores into one hot feature representations\n for v in self.cf_vae.encoded_categorical_feature_indexes:\n curr_max= x_pred[:, v[0]]\n curr_max_idx= v[0]\n for idx in v:\n if curr_max < x_pred[:, idx]:\n curr_max= x_pred[:, idx]\n curr_max_idx= idx\n for idx in v:\n if idx==curr_max_idx:\n x_pred[:, idx]=1\n else:\n x_pred[:, idx]=0\n \n \n cf_label= cf_label.detach().numpy()\n cf_label= np.reshape( cf_label, (cf_label.shape[0],1) )\n \n curr_gen_cf.append( x_pred )\n curr_cf_pred.append( cf_label )\n \n final_gen_cf.append(curr_gen_cf)\n final_cf_pred.append(curr_cf_pred)\n final_test_pred.append(curr_test_pred)\n \n #CF Gen out\n result={}\n result['query-instance']= query_instance[0]\n result['test-pred']= final_test_pred[0][0]\n result['CF']= final_gen_cf[0]\n result['CF-Pred']= final_cf_pred[0]\n \n # Adding empty list for sparse cf gen and pred; adding 0 for the sparsity coffecient\n return exp.CounterfactualExamples(self.data_interface, result['query-instance'], result['test-pred'], result['CF'], result['CF-Pred'], None, None, 0)","sub_path":"dice_ml/dice_interfaces/dice_model_approx_gencf.py","file_name":"dice_model_approx_gencf.py","file_ext":"py","file_size_in_byte":15341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"444150264","text":"'''\nDCP #1\nThis problem was recently asked by Google.\nGiven a list of numbers and a number k, return whether any two numbers from the list add up to k.\nFor example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.\nBonus: Can you do this in one pass?\n'''\n\ndef findpair(arr,k):\n\tvisited=dict()\n\tfor i in arr:\n\t\tif(i not in visited):\n\t\t\tvisited[i]=1\n\t\telse:\n\t\t\tvisited[i]+=1\n\t\tj=k-i\n\t\tif(j in visited):\n\t\t\tif(i==j and visited[j]>=2):\n\t\t\t\treturn True\n\t\t\telif(i==j and visited[j]>2):\n\t\t\t\tcontinue\n\t\t\telif(i!=j):\n\t\t\t\treturn True\n\treturn False\n\nprint(findpair([10,15,3,7],17))\nprint(findpair([11,4,0,3],3))\nprint(findpair([1,2,3,4],8))\nprint(findpair([4,2,3,4],8))\nprint(findpair([11,4,0,3],13))","sub_path":"Hashing/PairSum_K.py","file_name":"PairSum_K.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"615807758","text":"def quicksort(A):\n if len(A) < 2:\n return A\n else:\n x = A[0]\n less = [i for i in A[1:] if i[0] <= x[0]]\n greater = [i for i in A[1:] if not i[0] <= x[0]]\n return quicksort(greater) + [x] + quicksort(less)\n \ndef quicksort1(A):\n if len(A) < 2:\n return A\n else:\n x = A[0][0]\n i = 0\n for j in range(len(A)-1):\n if A[j+1][0] <= x:\n A[j+1],A[i+1] = A[i+1], A[j+1]\n i += 1\n A[0],A[i] = A[i],A[0]\n less = quicksort1(A[:i])\n greater = quicksort1(A[i+1:])\n return greater + [A[i]] + less\n\t\t\ndef maximumbasis(A):\n\tfrom fractions import Fraction\n\tn=len(A)\n\tm=len(A[0])\n\tG=[]\n\tif n==1:\n\t\treturn({1},G[0][1])\n\t\t\n\tfor i in range(n):\n\t\ta=0\n\t\tfor j in range(m):\n\t\t\ta+=A[i][j]\n\t\tG.append([a,i])\t\n\t\t\n\tG=quicksort1(G)\n\t\n\t\n\t\n\tif G[0][0]==0:\n\t\treturn (set(),Fraction(0,1))\n\t\t\n\t\n\tM1=[G[0]]\n\tM2=[A[G[0][1]]]\n\tresult1=set()\n\tresult2=0\n\t\t\n\t\t\n\tfor j in range(1,n):\n\t\tX=[]\n\t\tM2.append([])\n\t\tfor i in range(len(M1)):\n\t\t\tstart=0\n\t\t\tx=0\n\t\t\twhile M2[i][start]==0:\n\t\t\t\t\tstart+=1\t\n\t\t\tfor k in range(len(X)):\n\t\t\t\tx+= -X[k]*M2[k][i]\n\t\t\tx=(x- A[G[j][1]][start])/M2[i][start]\n\t\t\tX.append(x)\n\t\tfor l in range(m):\n\t\t\tb=A[G[j][1]][l]\n\t\t\tfor h in range(len(X)):\n\t\t\t\tb+=X[h]*M2[h][l]\n\t\t\tM2[j].append(b)\n\t\tif M2[j]==[0]*m:\n\t\t\tM2=M2[:j]\n\t\t\tcontinue\n\t\tM1.append(G[j])\n\t\tif len(M2)==m:\n\t\t\tfor g in range(m):\n\t\t\t\tresult1.add(M1[g][1]+1)\n\t\t\t\tresult2+=M1[g][0]\n\t\t\treturn (result1, result2)\n\t\t\n\n\tfor g in range(len(M2)):\n\t\tresult1.add(M1[g][1]+1)\n\t\tresult2+=M1[g][0]\n\treturn (result1, result2)\n\t\t\t\n\t\t\t\n","sub_path":"PA1201.py","file_name":"PA1201.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"369050812","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 27 14:42:14 2018\n\n@author: howardhsu\n\"\"\"\ndef FirstFactorial(num): \n \n a = int(1)\n num = int(num)\n \n for i in range(1, num+1):\n a = a * i\n\n # code goes here \n return (a)\n \n# keep this function call here \nprint(FirstFactorial(input()))\n","sub_path":"FirstFactorial.py","file_name":"FirstFactorial.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"48596111","text":"from re import sub\n\nimport csv\nimport itertools\nimport random\nfrom random import shuffle\n\nimport pandas as pd\nfrom nltk.corpus import stopwords\nfrom gensim.models import KeyedVectors\nfrom sklearn.model_selection import train_test_split as split_data\n\nimport keras\nfrom keras.preprocessing.sequence import pad_sequences\nimport numpy as np\n\nclass Data(object):\n def __init__(self, path, maxlen=0):\n self.path = path\n self.maxlen = maxlen\n self.vocab_size = 1\n self.sentence_cols = ['sentence_A', 'sentence_B']\n self.x_train = list()\n self.y_train = list()\n self.x_val = list()\n self.y_val = list()\n self.vocab = set()\n self.word_to_id = dict()\n self.id_to_word = dict()\n self.run()\n\n def text_to_word_list(self, text):\n ''' Pre process and convert texts to a list of words '''\n text = str(text)\n text = text.lower()\n\n # Clean the text\n text = sub(r\"[^A-Za-z0-9^,!.\\/'+-=]\", \" \", text)\n text = sub(r\"what's\", \"what is \", text)\n text = sub(r\"\\'s\", \" \", text)\n text = sub(r\"\\'ve\", \" have \", text)\n text = sub(r\"can't\", \"cannot \", text)\n text = sub(r\"n't\", \" not \", text)\n text = sub(r\"i'm\", \"i am \", text)\n text = sub(r\"\\'re\", \" are \", text)\n text = sub(r\"\\'d\", \" would \", text)\n text = sub(r\"\\'ll\", \" will \", text)\n text = sub(r\",\", \" \", text)\n text = sub(r\"\\.\", \" \", text)\n text = sub(r\"!\", \" ! \", text)\n text = sub(r\"\\/\", \" \", text)\n text = sub(r\"\\^\", \" ^ \", text)\n text = sub(r\"\\+\", \" + \", text)\n text = sub(r\"\\-\", \" - \", text)\n text = sub(r\"\\=\", \" = \", text)\n text = sub(r\"'\", \" \", text)\n text = sub(r\"(\\d+)(k)\", r\"\\g<1>000\", text)\n text = sub(r\":\", \" : \", text)\n text = sub(r\" e g \", \" eg \", text)\n text = sub(r\" b g \", \" bg \", text)\n text = sub(r\" u s \", \" american \", text)\n text = sub(r\"\\0s\", \"0\", text)\n text = sub(r\" 9 11 \", \"911\", text)\n text = sub(r\"e - mail\", \"email\", text)\n text = sub(r\"j k\", \"jk\", text)\n text = sub(r\"\\s{2,}\", \" \", text)\n\n text = text.split()\n\n return text\n\n def load_sick(self):\n # Load training set\n train_df = pd.read_csv(self.path + 'SICK.txt', sep='\\t')\n\n stops = set(stopwords.words('english'))\n\n # Iterate over the sentences only of training dataset\n for index, row in train_df.iterrows():\n # Iterate through the text of both sentences of the row\n for sentence in self.sentence_cols:\n q2n = [] # sentence Numbers Representation\n for word in self.text_to_word_list(row[sentence]):\n # Remove unwanted words\n if word in stops:\n continue\n\n if word not in self.vocab:\n self.vocab.add(word)\n self.word_to_id[word] = self.vocab_size\n q2n.append(self.vocab_size)\n self.id_to_word[self.vocab_size] = word\n self.vocab_size += 1\n else:\n q2n.append(self.word_to_id[word])\n\n # Replace sentences as word to sentence as number representation\n train_df.set_value(index, sentence, q2n)\n\n return train_df\n\n def pad_sequences(self):\n if self.maxlen == 0:\n self.maxlen = max(max(len(seq) for seq in self.x_train[0]),\n max(len(seq) for seq in self.x_train[1]),\n max(len(seq) for seq in self.x_val[0]),\n max(len(seq) for seq in self.x_val[1]))\n\n # Zero padding\n for dataset, side in itertools.product([self.x_train, self.x_val], [0, 1]):\n dataset[side] = pad_sequences(dataset[side], maxlen=self.maxlen)\n\n def run(self):\n print('Loading data and building vocabulary.')\n train_df = self.load_sick()\n\n # Split to train validation\n validation_size = int(len(train_df)*0.2)\n training_size = len(train_df) - validation_size\n\n X = train_df[self.sentence_cols]\n Y = train_df['relatedness_score']\n\n self.x_train, self.x_val, self.y_train, self.y_val = split_data(X, Y, test_size=validation_size)\n\n # Split to lists\n self.x_train = [self.x_train.sentence_A, self.x_train.sentence_B]\n self.x_val = [self.x_val.sentence_A, self.x_val.sentence_B]\n\n # Convert labels to their numpy representations\n self.y_train = self.y_train.values\n self.y_val = self.y_val.values\n\n print('Padding Sequences.')\n self.pad_sequences()\n","sub_path":"sick_preprocessing.py","file_name":"sick_preprocessing.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"605249445","text":"import praw, time, datetime, traceback, obot\n#obot is used to login with OAuth, you will get an exception if you attempt to import it\n\n\"\"\"\nRemove and tempban script users.\n\"\"\"\n\n#login using file with oauth app details\nr = obot.login()\n\n#create empty arrays so we don't act on things twice\nrecentlyDonePosts = []\nrecentlyBannedUsers = []\nrecentlyModdedSubs = []\n\nbotActive = True\n\n#get posts from /r/mod\nrmod = r.get_subreddit(\"mod\")\n\n\n#string sent to user\nsentToUserString = \"You have been temporarily banned for using a comment overwrite script. This is considered spam. In future, please use a less spammy overwrite message. Thank you.\"\n\ndef is_banned(sub, user):\n if [i for i in list(r.get_banned(sub)) if i.name == user]:\n return True\n return False\n\n#post checker method\ndef check():\n #NOTE: I modified praw (not my modification) in order to allow for edited sort, so this won't work for you natively!\n #To add this yourself, see: http://redd.it/2y2rvj\n stream = praw.helpers._stream_generator(rmod.get_edited, 100)\n #this phrase is always found in the comments\n scriptKeyword = \"This comment has been overwritten by\"\n #make sure we get the right thing\n for comment in stream:\n try:\n text = comment.body\n except AttributeError:\n text = comment.selftext\n if scriptKeyword in text and comment.id not in recentlyDonePosts:\n if comment.banned_by == None:\n #string for mod note\n subofcomment = comment.subreddit\n modString = \"Greasemonkey overwrite script:\", comment.id\n \n if comment.author == None:\n cmtAuthor = \"[deleted]\"\n else:\n cmtAuthor = comment.author.name\n #ban args\n banargs = {\"duration\": 3, \"note\": modString, \"ban_message\": sentToUserString}\n \n #remove the comment regardless\n comment.remove(spam=False)\n print(\"Removed id \" + comment.id + \" by \" + cmtAuthor + \" from /r/\" + comment.subreddit.display_name)\n recentlyDonePosts.append(comment.id)\n #don't bother banning them if they're already banned\n \n try:\n if is_banned(subofcomment, cmtAuthor) or cmtAuthor in recentlyBannedUsers:\n pass\n else:\n if cmtAuthor == \"[deleted]\":\n pass\n else:\n rmod.add_ban(subofcomment, **banargs)\n recentlyBannedUsers.append(cmtAuthor)\n print(\"Tempbanned \" + cmtAuthor + \" in \" + \"/r/\" + comment.subreddit.display_name)\n except:\n recentlyBannedUsers.append(cmtAuthor)\n print(\"Couldn't ban \" + cmtAuthor + \" from /r/\" + comment.subreddit.display_name + \". No access permission?\")\n \n \n \n #let's relax a little\n time.sleep(1)\ndef getTime():\n currentSysTime = time.localtime()\n return time.strftime('%m/%d/%y @ %H:%M:%S', currentSysTime)\nwhile True:\n try:\n check()\n except:\n time.sleep(1)\n\n","sub_path":"orkiller.py","file_name":"orkiller.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"350936569","text":"#!/usr/bin/env python\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom setuptools import setup, find_packages\n\nDEPENDENCIES = [\n 'pyyaml'\n]\n\nsetup(\n name='sfmergeutility',\n version='0.1.4',\n packages=find_packages(exclude=(\"tests\",)),\n license='MIT',\n description='Service Fabric Yaml merge utility',\n install_requires=DEPENDENCIES,\n url='https://github.com/Azure/azure-cli-extensions',\n author='Microsoft Corporation',\n author_email='azpycli@microsoft.com',\n package_data={'sfmergeutility': ['settings.json']},\n include_package_data=True,\n)","sub_path":"src/mesh/sfmergeutility/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"622207659","text":"from engine.util.print_colors import color, print_description_colored_title\nfrom engine.setups.util import setup_and_run_experiment\nfrom engine.training_validation.loss import MSELoss\nfrom contrib.games.easy_map_4 import EasyMap\nfrom contrib.models.cnn_tuple import Net\n\n\ndef run(xp_name, params, epoch=0, export=False, email=0, file=False):\n # Ce que je veux\n\n setup_and_run_experiment(xp_name, EasyMap, params, Net, MSELoss(), epoch=epoch, export=export,\n email=email, file=file)\n\n\ndef description():\n desc = print_description_colored_title('Demo example', 'model_params')\n\n desc += \"This model accepts 64x64x80 tensors. It is composed of 1d convolutions.\\n\"\n desc += \"The idea is to learn the distribution of each variables independently \\n\"\n desc += \"of the spatial structure.\\n\\n\"\n desc += \"Parameters accepted by the model:\\n\"\n desc += \"\\t- [\" + color.RED + \"s_conv_layers\" + color.END + \"]: the size of each convolutional hidden layer,\\n\"\n desc += \"\\t- [\" + color.RED + \"n_conv_layers\" + color.END + \"]: the number of hidden convolutional layers,\\n\"\n desc += \"\\t- [\" + color.RED + \"s_layer\" + color.END + \"]: the size of each fully connected hidden layer,\\n\"\n desc += \"\\t- [\" + color.RED + \"n_layer\" + color.END + \"]: the number of fully connected hidden layers.\"\n return desc\n","sub_path":"projects/qrouting/easy_map_4/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"478100080","text":"from Tkinter import *\nimport struct\n\n# define point, polyline classes\nclass Point:\n # deinfe object initialization method\n def __init__(self, x=0.0, y=0.0):\n self.x = x\n self.y = y\n\nclass Polyline:\n # deinfe object initialization method\n def __init__(self, points=[], partsNum=0, partsIndex=0):\n self.points = points\n self.partsNum = partsNum\n self.partsIndex = partsIndex\n\n# open index file to read in binary mode\nshxFile = open('/Users/YJccccc/Desktop/GGS_650_Python/FinalProject/Neighborhood_Clusters/Neighborhood_Clusters.shx', 'rb')\n\n# ----Part 1: read and process the first 100 bytes\n# read index file header and interpret the meta information. e.g., bounding box, and # of #records\ns = shxFile.read(28) # read first 28 bytes\n# convert into 7 integers\n\n# get file length\nheader = struct.unpack('>iiiiiii', s)\nfileLength = header[len(header) - 1]\n\n# calcualate polyline numbers in the shape file based on index file length\npolylineNum = int((fileLength * 2 - 100) / 8)\n\n# read other 72 bytes in header\ns = shxFile.read(72)\n# convert into values\nheader = struct.unpack('i', s)\n # keep the offset in the list\n recordsOffset.append(offset[0] * 2)\n\nshxFile.close() # close the index file\n\n\n# ----Part2. read each polyline and prepare them in right order\n# open the main file for read in binary\nshpFile = open('/Users/YJccccc/Desktop/GGS_650_Python/FinalProject/Neighborhood_Clusters/Neighborhood_Clusters.shp', 'rb')\n# shapefile name can be replaced with any polyline\n\npolylines = [] # define an empty list for polylines\n\n# loop through each offset of all polylines\nfor offset in recordsOffset:\n # define two lists for holding values\n x, y = [], []\n # jump to partsNum and pointsNum of the polyline and read them out\n shpFile.seek(offset + 8 + 36)\n s = shpFile.read(8)\n polyline = Polyline() # generate an empty polyline object\n partsNum, pointsNum = struct.unpack('ii', s)\n polyline.partsNum = partsNum\n #print ('partsNum, pointsNum:', partsNum, pointsNum)\n s = shpFile.read(4 * partsNum)\n str = ''\n for i in range(partsNum):\n str = str + 'i'\n\n # get the starting point number of each part and keep in a partsIndex list\n polyline.partsIndex = struct.unpack(str, s)\n\n points = []\n for i in range(pointsNum):\n # read out polyline coordinates\n s = shpFile.read(16)\n x, y = struct.unpack('dd', s)\n\n # read the coordinates values\n # assemble data into objects of points, polyline, and polygon or other types\n point = Point(x, y)\n points.append(point)\n # assign points lists to the polyline\n polyline.points = points\n # add the polyline read to the\n polylines.append(polyline)\n\n\n# ----Part 3: prepare to visualize the data\n# create main window object\nroot = Tk()\n\n# define wondow size\nwindowWidth, windowHeight = 600, 600\n\n# calculate ratio for visualization\nratiox = (maxX - minX) / windowWidth\nratioy = (maxY - minY) / windowHeight\n\n# take the smaller ratio\nratio = ratiox\nif ratio < ratioy:\n ratio = ratioy\n\n# create canvas object\ncan = Canvas(root, width=600, height=600)\n\nfor polyline in polylines:\n xylist = [] # define an empty xylist for holding converted coordinates\n\n # loop through each point\n # and calculate the window coordinates, put in xylist\n for point in polyline.points:\n #print (point.x, point.y)\n winX = (point.x - minX) / ratio\n winY = - (point.y - maxY) / ratio\n xylist.append(winX)\n xylist.append(winY)\n #print \"xylist: \",xylist\n\n for k in range(polyline.partsNum): # visualize each part separately\n if (k == polyline.partsNum - 1):\n endPointIndex = len(polyline.points)\n else:\n endPointIndex = polyline.partsIndex[k + 1]\n\n # define a temporary list for holding the part coordinates\n tempXYlist = []\n\n for m in range(polyline.partsIndex[k], endPointIndex):\n # polyline.partsIndex[k]:the first point in this part\n # endPointIndex:the last point in this part\n tempXYlist.append(xylist[(m * 2)])\n tempXYlist.append(xylist[(m * 2 + 1)])\n #print \"tempXYList: \",tempXYlist\n\n # create the line\n can.create_line(tempXYlist, fill='blue')\n\ncan.pack()\nroot.mainloop()\n\nshpFile.close()\n","sub_path":"readShpFile.py","file_name":"readShpFile.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"305076936","text":"import abc\nfrom six import with_metaclass\nfrom .utils import docval, getargs, ExtenderMeta\nfrom warnings import warn\n\n\nclass Container(with_metaclass(ExtenderMeta, object)):\n\n _fieldsname = '__fields__'\n\n @docval({'name': 'name', 'type': str, 'doc': 'the name of this container'},\n {'name': 'parent', 'type': 'Container', 'doc': 'the Container that holds this Container', 'default': None},\n {'name': 'container_source', 'type': str, 'doc': 'the source of this container', 'default': None})\n def __init__(self, **kwargs):\n name = getargs('name', kwargs)\n if '/' in name:\n raise ValueError(\"name '\" + name + \"' cannot contain '/'\")\n self.__name = name\n self.__parent = getargs('parent', kwargs)\n self.__container_source = getargs('container_source', kwargs)\n self.__children = list()\n self.__modified = True\n\n def __repr__(self):\n return \"<%s '%s' at 0x%d>\" % (self.__class__.__name__, self.name, id(self))\n\n @property\n def modified(self):\n return self.__modified\n\n @docval({'name': 'modified', 'type': bool,\n 'doc': 'whether or not this Container has been modified', 'default': True})\n def set_modified(self, **kwargs):\n modified = getargs('modified', kwargs)\n self.__modified = modified\n if modified and self.parent is not None:\n self.parent.set_modified()\n\n @property\n def children(self):\n return tuple(self.__children)\n\n @docval({'name': 'child', 'type': 'Container',\n 'doc': 'the child Container for this Container', 'default': None})\n def add_child(self, **kwargs):\n child = getargs('child', kwargs)\n if child is not None:\n # if child.parent is a Container, then the mismatch between child.parent and parent\n # is used to make a soft/external link from the parent to a child elsewhere\n # if child.parent is not a Container, it is either None or a Proxy and should be set to self\n if not isinstance(child.parent, Container):\n self.__children.append(child)\n self.set_modified()\n child.parent = self\n else:\n warn('Cannot add None as child to a container %s' % self.name)\n\n @classmethod\n def type_hierarchy(cls):\n return cls.__mro__\n\n @property\n def name(self):\n '''\n The name of this Container\n '''\n return self.__name\n\n @property\n def container_source(self):\n '''\n The source of this Container\n '''\n return self.__container_source\n\n @container_source.setter\n def container_source(self, source):\n if self.__container_source is not None:\n raise Exception('cannot reassign container_source')\n self.__container_source = source\n\n @property\n def parent(self):\n '''\n The parent Container of this Container\n '''\n return self.__parent\n\n @parent.setter\n def parent(self, parent_container):\n if self.parent is parent_container:\n return\n\n if self.parent is not None:\n if isinstance(self.parent, Container):\n raise ValueError(('Cannot reassign parent to Container: %s. '\n 'Parent is already: %s.' % (repr(self), repr(self.parent))))\n else:\n if parent_container is None:\n raise ValueError(\"Got None for parent of '%s' - cannot overwrite Proxy with NoneType\" % repr(self))\n # TODO this assumes isinstance(parent_container, Proxy) but\n # circular import if we try to do that. Proxy would need to move\n # or Container extended with this functionality in build/map.py\n if self.parent.matches(parent_container):\n self.__parent = parent_container\n else:\n self.__parent.add_candidate(parent_container)\n else:\n self.__parent = parent_container\n\n\nclass Data(Container):\n\n @abc.abstractproperty\n def data(self):\n '''\n The data that is held by this Container\n '''\n pass\n\n def __nonzero__(self):\n return len(self.data) != 0\n\n\nclass DataRegion(Data):\n\n @abc.abstractproperty\n def data(self):\n '''\n The target data that this region applies to\n '''\n pass\n\n @abc.abstractproperty\n def region(self):\n '''\n The region that indexes into data e.g. slice or list of indices\n '''\n pass\n","sub_path":"src/hdmf/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"382677477","text":"import pickle\nimport logging\n\ndef save(data, filename):\n file = open(filename, 'wb')\n pickle.dump(data, file)\n file.close()\n\n\ndef read(filename):\n try:\n file = open(filename, 'rb')\n data = pickle.load(file)\n file.close()\n return data\n except:\n logging.info('error reading file', exc_info=True)\n return None\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"377756628","text":"from time import sleep\nfrom selenium import webdriver\n\n\n\nlink = \"http://suninjuly.github.io/wait2.html\"\n\nbrowser = webdriver.Chrome()\n# говорим WebDriver ждать все элементы в течение 5 секунд\nbrowser.implicitly_wait(5)\nbrowser.get(link)\n\n\ntry:\n\n button = browser.find_element_by_id(\"verify\")\n button.click()\n message = browser.find_element_by_id(\"verify_message\")\n\n assert \"successful\" in message.text\n\nexcept Exception as e:\n print(e)\n\n\nfinally:\n sleep(5)\n browser.quit()\n\n\n\n","sub_path":"2.4/cats_waits.py","file_name":"cats_waits.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"126189792","text":"'''\r\n给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。\r\n\r\n回文串 是正着读和反着读都一样的字符串。\r\n\r\n示例 1:\r\n输入:s = \"aab\"\r\n输出:[[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\r\n\r\n示例 2:\r\n输入:s = \"a\"\r\n输出:[[\"a\"]]\r\n\r\n提示:\r\n1 <= s.length <= 16\r\ns 仅由小写英文字母组成\r\n'''\r\nfrom typing import List\r\n\r\nfrom leetcode.tools.time import printTime\r\n\r\n\r\nclass Solution:\r\n '''\r\n 递归\r\n '''\r\n @printTime()\r\n def partition(self, s: str) -> List[List[str]]:\r\n self.len = len(s)\r\n mem1 = [[True for _ in range(self.len)] for _ in range(self.len)]\r\n for i in range(self.len - 1, - 1, -1):\r\n for j in range(i + 1, self.len):\r\n mem1[i][j] = s[i] == s[j] and mem1[i + 1][j - 1]\r\n mem = {}\r\n def re(index):\r\n if index in mem:\r\n return mem[index]\r\n ret = []\r\n for i in range(index, self.len):\r\n if mem1[index][i]:\r\n if i + 1 < self.len:\r\n temp = re(i + 1)\r\n for t in temp:\r\n t1 = [s[index:i + 1]]\r\n t1 += t\r\n ret.append(t1)\r\n else:\r\n ret.append([s[index:i + 1]])\r\n mem[index] = ret\r\n return ret\r\n return re(0)\r\n '''\r\n DP\r\n '''\r\n @printTime()\r\n def _1partition(self, s: str) -> List[List[str]]:\r\n self.len = len(s)\r\n mem = [[True for _ in range(self.len)] for _ in range(self.len)]\r\n for i in range(self.len - 1, - 1, -1):\r\n for j in range(i + 1, self.len):\r\n mem[i][j] = s[i] == s[j] and mem[i + 1][j - 1]\r\n dp = [[] for _ in range(self.len)]\r\n dp[0] = [[s[0]]]\r\n for i in range(1, self.len):\r\n for j in range(i + 1):\r\n if mem[j][i]:\r\n if j == 0:\r\n dp[i].append([s[j:i + 1]])\r\n continue\r\n for t in dp[j - 1]:\r\n t1 = t.copy()\r\n t1.append(s[j:i + 1])\r\n dp[i].append(t1)\r\n return dp[-1]\r\n\r\ns = 'aabcbaafiwefnpnngplwkenfowfnwoefhnwonegfnfwneoflwegwerghrthrtwhrtth'\r\nSolution().partition(s)\r\nSolution()._1partition(s)","sub_path":"leetcode/0131_M_分割回文串_DP.py","file_name":"0131_M_分割回文串_DP.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"126982677","text":"'''\nCheck-for-balanced-parentheses\nProblem Statement : Given an expression string x. Examine whether\n the pairs and the orders of\n “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.\n For example, the function should return\n 'true' for exp = “[()]{}{[()()]()}” \n and 'false' for exp = “[(])”.\nInput : Enter list of parentheses.\nOutput : Print True if it is balanced or else False.\n\nTime Complexity : O(n)\nSpace Complexity : O(n)\n'''\n\n\ndef Check(brackets): \n stack = [] \n \n # Traversing the Expression\n for i in brackets: \n if i in [\"(\", \"{\", \"[\"]: \n \n # Push the element in the stack\n stack.append(i) \n else: \n # IF current character is not opening \n # bracket, then it must be closing. \n if not stack: \n return False\n char = stack.pop() \n if char == '(': \n if i != \")\": \n return False\n if char == '{': \n if i != \"}\": \n return False\n if char == '[': \n if i != \"]\": \n return False\n # Check Empty Stack\n if stack:\n return False\n return True\n\n# -----------------------Driver Code-----------------------\n\n# INPUT\n# Enter the list of the brackets\nbrackets = input(\"Enter the brackets: \")\n# OUTPUT\nif(Check(brackets)):\n print(\"The parentheses are balnced\")\nelse:\n print(\"The parentheses are not balnced\")\n \n'''\nSAMPLE INPUT/OUTPUT:\nINPUT\n Enter the brackets: {{[[[()]]]}}{(())}\nOUTPUT\n The parentheses are balnced \n'''\n","sub_path":"Python/other/Check_for_balanced_parentheses.py","file_name":"Check_for_balanced_parentheses.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"565394949","text":"from utils import *\nimport numpy as np\n\nWCONFIG = {\n\t'windows': [\n\t\t{\n\t\t\t'x_start_stop': (700, 1280), \n\t\t\t'y_start_stop': (400, 590), \n\t\t\t'window_size' : 64,\n\t\t\t'step_size' : 16,\n\t\t\t'scale_factor': 1\n\t\t},\n\t\t{\n\t\t\t'x_start_stop': (700, 1280), \n\t\t\t'y_start_stop': (400, 650), \n\t\t\t'window_size' : 64,\n\t\t\t'step_size' : 32 ,\n\t\t\t'scale_factor': 2\n\t\t}\n\t\t# ,\n\t\t# {\n\t\t# \t'x_start_stop': (720, 1280), \n\t\t# \t'y_start_stop': (380, 680), \n\t\t# \t'window_size' : 64,\n\t\t# \t'step_size' : 16,\n\t\t# \t'scale_factor': 2\n\t\t# }\t\n\t]\n}\n\ndef slide_window(x_start_stop, y_start_stop, window_size, step_size, scale_factor):\n\t\"\"\"\n\tMethod will generate windows in the choosen area of interests.\n\t\"\"\"\n\n\t# rescale accotring to factor\n\twindow_size = window_size*scale_factor\n\n\t# calculate number of boxes for this window in both x and y directions\n\taoi_shape = np.array([y_start_stop[1] - y_start_stop[0], x_start_stop[1] - x_start_stop[0]])\n\tcounts = (((aoi_shape - window_size)//step_size) + 1).astype('int')\n\t\n\t# walk through calculations and generate boxes\n\twindows = []\n\tfor iy in range(counts[0]):\n\t\tfor ix in range(counts[1]):\n\t\t\ty_start = y_start_stop[0] + iy*step_size\n\t\t\tx_start = x_start_stop[0] + ix*step_size\n\n\t\t\twindows.append((\n\t\t\t\t(x_start, y_start), \n\t\t\t\t(x_start + window_size, y_start + window_size),\n\t\t\t\tscale_factor\n\t\t\t))\n\n\treturn windows\n\ndef generate_windows():\n\t\"\"\"\n\tMain method that will generate windows and then stack them together.\n\t\"\"\"\n\n\tglobal WCONFIG\n\treturn np.vstack([slide_window(**cfg) for cfg in WCONFIG['windows']])\n\n\nif __name__ == \"__main__\":\n\tptitle('Trying to generate windows grids on the test image...')\n\n\tpath = 'test_images/test1.jpg'\n\timg = load_image(path)\n\n\tfor config in WCONFIG['windows']:\n\t boxes = slide_window(**config)\n\t draw(draw_boxes(img, boxes))\n","sub_path":"windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"348948974","text":"import numpy as np\nimport nibabel as nib\nfrom data_loaders import Dataset\nfrom models import UNet3D\nfrom skimage.transform import resize\nimport os\nimport torch\nfrom collections import OrderedDict\nfrom sys import argv\nimport glob\nimport pdb\nimport torch.nn as nn\n\n########################################################################################################################\n# Code to segment a set of scans after model has been trained. Segmentation obtained by ensemble averaging outputs of the\n# models from the different folds. When calling script:\n\n# INPUT arguments:\n# arg1: path to where the preprocessed scans to segment are stored\n# arg2: path to where the Model_Saves are stored\n# arg3: epoch nr at which to to load a models save\n# arg4: path where to save the segmented scans. Code creates folder with name of run in it\n\n# OUTPUT:\n# segmented scans stored as nii.gz files in provided save results path\n########################################################################################################################\n\npreprocessed_data_path = '/data/xwj_work/Brats2018/val_nocrop/'\nmodel_saves_path = '/data/xwj_work/Brain_Tumour_Segmentation/train_nocrop/'\nepoch_nrs = [300, 290, 280] # Epoch at which to take the model saves (determined from loss plots)\nsave_results_path = '/data/xwj_work/Brain_Tumour_Segmentation/val_nocrop_sigmoid_results/'\n\nrun_name = model_saves_path[model_saves_path.rindex(\"/\") + 1:]\nsave_results_path = os.path.join(save_results_path, run_name)\nif not os.path.isdir(save_results_path):\n os.mkdir(save_results_path)\n\n# Get folder paths and names (IDS) of folders that store the preprocessed data\nvalist = glob.glob(preprocessed_data_path + '/Brats*')\nvalid_set = Dataset(valist, seg_provided=False, nozero=False)\n\n# Use GPU\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\ntorch.backends.cudnn.benchmark = True\nnum_folds = 2\nmodels = []\nfor epoch_nr in epoch_nrs:\n for fold in range(1, num_folds+1):\n model = UNet3D(4, 4, False, 16, 'crg', 8)\n print (\"Loading {}/Fold_fold{}_Epoch_{}.tar\".format(model_saves_path, fold, epoch_nr))\n checkpoint = torch.load(\"{}/Fold_fold{}_Epoch_{}.tar\".format(model_saves_path, fold, epoch_nr))\n# if list(checkpoint['model_state_dict'].keys())[0].find(\"module\") > -1:\n# new_state_dict = OrderedDict()\n# for k, v in checkpoint['model_state_dict'].items():\n# name = k[7:] # remove module.\n# new_state_dict[name] = v\n# model.load_state_dict(new_state_dict)\n# else:\n model.load_state_dict(checkpoint['model_state_dict'])\n model.to(device)\n model.eval()\n models.append(model)\nfor idx in range(0, len(valist)):\n with torch.no_grad():\n scans = valid_set[idx]\n scans = np.expand_dims(scans, 0)\n scans = torch.from_numpy(scans).to(device)\n seg_results = []\n for fold in range(len(models)):\n output = models[fold](scans)\n pdb.set_trace()\n output = torch.sigmoid(output)\n output = output.squeeze()\n seg_results.append(output)\n pdb.set_trace()\n seg_layer_avg = torch.mean(torch.stack(seg_results), dim=0)\n _, indices = seg_layer_avg.max(0)\n indices = indices.cpu().detach().numpy().astype('uint8')\n indices[indices == 3] = 4\n img = nib.Nifti1Image(indices, [[-1, -0, -0, 0], [-0, -1, -0, 239], [0, 0, 1, 0], [0, 0, 0, 1]])\n nib.save(img, \"{}/{}.nii.gz\".format(save_results_path, valist[idx].rsplit('/')[-1][:-10]))\n print('Saved example {}/{} for run {}'.format(idx + 1, len(valist), run_name))\n","sub_path":"segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"257380246","text":"import sys\nimport requests\nimport logging\nfrom .base import * # noqa\n\nfrom django_log_formatter_ecs import ECSFormatter\n\nCAN_ELEVATE_SSO_USER_PERMISSIONS = True\nCAN_CREATE_TEST_USER = True\n\nFRONT_END_SERVER = env(\n \"FRONT_END_SERVER\",\n default=\"http://localhost:3000\",\n)\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"front_end/build/static\"),\n os.path.join(BASE_DIR, \"node_modules/govuk-frontend\"),\n)\n\nSASS_PROCESSOR_INCLUDE_DIRS = [os.path.join(\"/node_modules\")]\n\nAUTHENTICATION_BACKENDS += [\n \"user.backends.CustomAuthbrokerBackend\",\n]\n\nASYNC_FILE_UPLOAD = False\n\nLOG_TO_ELK = env.bool(\"LOG_TO_ELK\", default=False)\nELK_ADDRESS = env(\"ELK_ADDRESS\", default=None)\n\nif LOG_TO_ELK:\n class LogstashHTTPHandler(logging.Handler):\n def emit(self, record):\n log_entry = self.format(record)\n\n return requests.post(\n ELK_ADDRESS,\n data='{}'.format(log_entry),\n headers={\n \"Content-type\": \"application/json\"\n },\n ).content\n\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"ecs_formatter\": {\n \"()\": ECSFormatter,\n },\n },\n 'handlers': {\n 'stdout': {\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n 'logstash': {\n '()': LogstashHTTPHandler,\n 'formatter': 'ecs_formatter',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['stdout', 'logstash', ],\n 'level': 'WARNING',\n 'propagate': True,\n },\n },\n }\nelse:\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n 'handlers': {\n 'stdout': {\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n },\n 'root': {\n 'handlers': ['stdout'],\n 'level': os.getenv('ROOT_LOG_LEVEL', 'INFO'),\n },\n 'loggers': {\n 'django': {\n 'handlers': ['stdout', ],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n 'propagate': True,\n },\n 'forecast.import_csv': {\n 'handlers': ['stdout', ],\n 'level': 'INFO',\n 'propagate': True,\n },\n },\n }\n","sub_path":"config/settings/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"34752806","text":"import tkinter as tk\n\nquestionNumber = 0\n\ndef answerKey(a,b):\n\treturn\ndef questions(questionNumber):\n\treturn (\"Question goes here\")\ndef answers(a,b):\n\treturn (\"answer choice goes here\")\n\nmainScr = tk.Tk()\n\nmainScr.configure(background='#FFF6CC')\n\ntitle = tk.Text(mainScr, height = 2, width = 57, font = 'helvetica 24')\ntitle.grid(row = 0, column = 0, columnspan = 4)\n\nphoto1 = ImageTK.PhotoImage(Image.open(\"The-Odyssey.jpg\"))\n\nimage = tk.Label(mainScr, image = photo1)\nimage.grid(row = 1, column = 0, columnspan = 4)\n\n\nquestion = tk.Text(mainScr, height = 20, width = 88, borderwidth=3, relief=tk.GROOVE, background='#FFF4BF', font ='mincho 14')\nquestion.insert(tk.INSERT, questions(questionNumber))\nquestion.config(state=\"disabled\")\nquestion.grid(row = 1, column = 0, columnspan = 4, padx=(30))\n\nresult = tk.Text(mainScr, height = 6, width = 69, borderwidth = 3, relief= tk.GROOVE, background = '#FFF4BF', font ='mincho 14')\nresult.config(state=\"disabled\")\nresult.grid(row=2, column = 0, columnspan = 2, rowspan = 2, padx=(30,0))\n\nanswerA = tk.Button(mainScr, text=answers(0,questionNumber), height = 3, width = 40, background='#D6C883',command = lambda: answerKey(questionNumber, \"a\"), font ='mincho 14')\nanswerA.grid(row = 4, column = 0, padx = (30,0))\n\nanswerB = tk.Button(mainScr, text=answers(1,questionNumber), height = 3, width = 40, background='#D6C883',command = lambda: answerKey(questionNumber, \"b\"), font ='mincho 14')\nanswerB.grid(row = 4, column = 1, columnspan = 3, padx = (0,30))\n\nanswerC = tk.Button(mainScr, text=answers(2,questionNumber), height = 3, width = 40, background='#D6C883',command = lambda: answerKey(questionNumber, \"c\"), font ='mincho 14')\nanswerC.grid(row = 5, column = 0, padx = (30,0))\n\nanswerD = tk.Button(mainScr, text=answers(3,questionNumber), height = 3, width = 40, background='#D6C883',command = lambda: answerKey(questionNumber, \"d\"), font ='mincho 14')\nanswerD.grid(row = 5, column = 1, columnspan = 3, padx = (0,30))\n\nscoreText = tk.Text(mainScr, height = 1, width = 6, borderwidth = 0)\nscoreText.insert(tk.INSERT, \"Score: \")\nscoreText.config(state=\"disabled\", background = '#FFF6CC')\nscoreText.grid(row = 2, column = 2, padx = (20,0))\n\nscore = tk.Text(mainScr, height = 1, width = 5, borderwidth = 0)\nscore.config(state=\"disabled\", background = '#FFF6CC')\nscore.insert(tk.INSERT,\"score\") #TEMP\nscore.grid(row = 2, column = 3, padx = (0,50))\n\ntk.mainloop()\n\n","sub_path":"Unit 1 Work/Creating The Solution/Experimenting/gameMainWindow.py","file_name":"gameMainWindow.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"83502452","text":"# -*- coding: cp1252 -*-\n\n# Panu Partanen Viikko 3 Tehtävä 5\n# GitHub https://github.com/Hea7hcliff/SchoolProgramming/tree/master/Python/Python16A\n\nimport pickle\nimport sys\nimport person\n\ndef main():\n \n persons = []\n running = True\n while(running) :\n menu = input(\"(1) Anna nimi\\n(2) Tulosta nimet\\n(3) Talleta fileon (nimet.dat)\\n(4) Lopeta ja lue file\\n-\\nMitä haluat tehdä? : \")\n menu = int(menu)\n per = person.Person()\n \n if(menu == 1) : \n per.firstname = input(\"Anna etunimi: \")\n per.lastname = input(\"Anna sukunimi: \")\n persons.append(per)\n continue\n\n if(menu == 2) :\n for i in persons:\n print(i)\n continue\n\n if(menu == 3) :\n with open(\"nimet.data\", \"wb\") as file:\n for p in persons:\n pickle.dump(p,file)\n print(\"Talletettu\\n\") \n continue\n\n if(menu == 4) :\n print(\"tiedostosi sisältö: \") \n with open(\"nimet.data\",\"rb\") as file:\n for p in persons:\n read = pickle.load(file)\n print(read)\n print(\"Lopetetaan\") \n running = False\n\n else : print(\"Väärä valinta\") \nmain()","sub_path":"Python/Python16A/Vko3/Tehtävä5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"60376221","text":"import model\nimport view\nimport random\n\ndefine_grid = [10,10]\nship_position = [random.randrange(0,define_grid[0]),random.randrange(0,define_grid[1])]\n\ndef run():\n grid1 = model.Grid(define_grid[0],define_grid[1], \" \")\n main_menu(grid1)\n\ndef main_menu(grid1):\n while True:\n grid1.set(ship_position[0], ship_position[1], \"@\")\n view.display_grid(grid1.data)\n guess = view.show_menu()\n grid1.set(int(guess[0]),int(guess[1]),\"0\")\n if guess == ship_position:\n print(\"You sank my BATTLESHIP!!!\")\n return\n view.display_grid(grid1.data)\n\nif __name__ == \"__main__\":\n run()","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"73919101","text":"\"\"\"\nParcours non récursif infixé avec pile d'un arbre binaire\n\"\"\"\n\nfrom Stack import *\nfrom BinaryTree import *\n\ndef infixe(binaryTree):\n stack = Stack() # Le stack de travail\n solution = [] # La solution\n \n stack.push(binaryTree) # On retient la racine\n \n fg = binaryTree.getLeft()\n \n while stack.size() > 0:\n \n while fg != None: # On va parcourir tout les fils gauche\n \n stack.push(fg) # On retient la racine\n fg = fg.getLeft() # On test le fils gauche\n \n fg = stack.pop() # On récupère le fils gauche\n solution.append(fg.getInfo()) # On le place dans la solution\n fd = fg.getRight() # On récupère sont fils droit\n \n while fd == None and stack.size() > 0: # On va parcourir le premier fils droit\n \n fg = stack.pop() # On récupère le fils gauche\n solution.append(fg.getInfo()) # On le place dans la solution\n fd = fg.getRight() # On récupère sont fils droit\n \n if fd != None:\n stack.push(fd) # On retient la racine\n fg = fd.getLeft()\n \n print(str(solution)) # On affiche la solution\n\nif __name__ == \"__main__\":\n binaryTree1 = BinaryTree('1')\n binaryTree2 = BinaryTree('2')\n binaryTree3 = BinaryTree('3')\n binaryTree4 = BinaryTree('4')\n binaryTree5 = BinaryTree('5')\n binaryTree6 = BinaryTree('6')\n binaryTree2.setLeft(binaryTree1)\n binaryTree2.setRight(binaryTree3)\n binaryTree5.setRight(binaryTree6)\n binaryTree4.setLeft(binaryTree2)\n binaryTree4.setRight(binaryTree5)\n infixe(binaryTree4)\n","sub_path":"INFO-BA-1/TP/algo/cha5-ex4.py","file_name":"cha5-ex4.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"399480503","text":"import os\nfrom flask import Flask\nfrom config import DevConfig, StagingConfig, ProductionConfig, config as c\nfrom blueprints import auth_bp, users_bp\nfrom orator import DatabaseManager, Model\napp = Flask(__name__)\n\ntry:\n if os.environ['ENV'] == 'development':\n app.config.from_object(DevConfig)\n elif os.environ['ENV'] == 'staging':\n app.config.from_object(StagingConfig)\n else:\n app.config.from_object(ProductionConfig)\nexcept KeyError as exc:\n app.config.from_object(ProductionConfig)\ndb = DatabaseManager(c)\napp.register_blueprint(auth_bp)\napp.register_blueprint(users_bp)\nModel.set_connection_resolver(db)\n\n\n@app.route('/')\ndef home():\n return \"Home\"\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"407018194","text":"import turtle\nimport random\n\n\nturtle.tracer(1,0)\nSIZE_X=800\nSIZE_Y=500\nturtle.setup(SIZE_X, SIZE_Y)\nturtle.penup()\n\nSQUARE_SIZE = 20\nSTART_LENGTH = 6\nTIME_STEP = 100\n\npos_list = []\nstamp_list = []\nfood_pos = []\nfood_stamps = []\nturtle.register_shape(\"pic2.gif\")\nsnake = turtle.clone()\nsnake.shape(\"pic2.gif\")\n\nturtle.hideturtle()\ndef score():\n turtle.write(\"GAME OVER! your score is {}\".format(len(stamp_list)- START_LENGTH), align = \"center\", font = (\"Arial\" , 20, \"normal\"))\n quit() \ndef new_stamp():\n snake_pos = snake.pos()\n pos_list.append(snake_pos)\n\n snake_stamp = snake.stamp()\n\n stamp_list.append(snake_stamp)\n\nfor i in range(0, START_LENGTH):\n x_pos=snake.pos()[0]\n y_pos=snake.pos()[1]\n x_pos+=SQUARE_SIZE\n snake.goto(x_pos, y_pos)\n new_stamp()\n\ndef remove_tail():\n old_stamp = stamp_list.pop(0) \n snake.clearstamp(old_stamp) \n pos_list.pop(0) \nsnake.direction = None\nUP_EDGE = 250\nDOWN_EDGE = -250\nRIGHT_EDGE = 400\nLEFT_EDGE = -400\n\ndef up():\n snake.direction=\"Up\"\n print(\"You pressed the up key!\")\n\ndef down():\n snake.direction=\"Down\"\n print(\"You pressed the down key!\")\n\ndef right():\n snake.direction=\"Right\"\n print(\"You pressed the right key!\")\n\ndef left():\n snake.direction=\"Left\"\n print(\"You pressed the left key!\")\n\nturtle.onkeypress(up, \"Up\")\nturtle.onkeypress(down,\"Down\")\nturtle.onkeypress(left,\"Left\")\nturtle.onkeypress(right,\"Right\")\n\nturtle.listen()\n\nturtle.register_shape(\"pic1.gif\")\nfood = turtle.clone()\nfood.shape(\"pic1.gif\") \nfood_pos = [(100,100), (-100,100), (-100,-100), (100,-100)]\nfood_stamps = []\n\n\nfor this_food_pos in food_pos:\n food.goto(this_food_pos)\n stamp = food.stamp()\n food_stamps.append(stamp)\n\ndef make_food():\n min_x=-int(SIZE_X/2/SQUARE_SIZE)+1\n max_x=int(SIZE_X/2/SQUARE_SIZE)-1\n min_y=-int(SIZE_Y/2/SQUARE_SIZE)+1\n max_y=int(SIZE_Y/2/SQUARE_SIZE)-1\n \n #Pick a position that is a random multiple of SQUARE_SIZE\n food_x = random.randint(min_x,max_x)*SQUARE_SIZE\n food_y = random.randint(min_y,max_y)*SQUARE_SIZE\n\n food.goto(food_x,food_y)\n food_pos.append(food.pos())\n food_stamps.append(food.stamp())\n\ndef move_snake():\n my_pos = snake.pos()\n x_pos = my_pos[0]\n y_pos = my_pos[1]\n\n\n if snake.direction == \"Up\":\n snake.goto(x_pos, y_pos + SQUARE_SIZE)\n print(\"You moved up!\")\n if snake.direction==\"Down\":\n snake.goto(x_pos, y_pos - SQUARE_SIZE)\n if snake.direction==\"Right\":\n snake.goto(x_pos + SQUARE_SIZE, y_pos)\n print(\"You moved up\")\n if snake.direction==\"Left\":\n snake.goto(x_pos - SQUARE_SIZE, y_pos)\n print(\"You moved Left\")\n new_stamp()\n remove_tail()\n \n \n new_pos = snake.pos()\n new_x_pos = new_pos[0]\n new_y_pos = new_pos[1]\n if new_x_pos >= RIGHT_EDGE:\n print(\"You hit the right edge! Game over!\")\n score()\n elif new_x_pos <= LEFT_EDGE:\n print(\"You hit the left edge! Game over!\")\n score()\n elif new_y_pos >= UP_EDGE:\n print(\"You hit the up edge! Game over!\")\n score()\n elif new_y_pos <= DOWN_EDGE:\n print(\"You hit the down edge! Game over!\")\n score()\n \n if snake.pos() in food_pos:\n food_index=food_pos.index(snake.pos())\n food.clearstamp(food_stamps[food_index]) \n food_pos.pop(food_index) \n food_stamps.pop(food_index) \n new_stamp()\n print(\"You have eaten the food!\")\n \n #if snake.pos() in pos_list[0:-1]:\n \n \n if len(food_stamps) <= 6 :\n make_food()\n \n\n \n\n turtle.ontimer(move_snake,TIME_STEP)\nmove_snake()\n \n\nturtle.mainloop()\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"449554363","text":"import asm.common as common\nimport parser.ast.ast_class as ast_class\nimport parser.ast.ast_param as ast_param\nimport parser.ast.ast_variable_declaration as ast_variable_declaration\n\nfrom manager import CodeGenManager\n\nNAMES = []\n\ndef set_simple_var(decl, src):\n '''Given a variable declaration (ASTParam or ASTVariableDeclaration), stores\n the value of src in it.'''\n store_code = []\n if isinstance(decl, ast_param.ASTParam):\n # Method parameter.\n index = CodeGenManager.cur_method.c_get_param_index(decl)\n store_code = common.set_param(index, src, CodeGenManager.N_PARAMS)\n elif decl.c_parent_method is not None:\n # Local variable.\n store_code = common.save_local_var(decl, src)\n else:\n # Last remaining case is a instance field access on the enclosing type.\n if not isinstance(decl, ast_variable_declaration.ASTVariableDeclaration):\n raise Exception('Simple variable is not an instance field')\n\n scratch_reg = [reg for reg in ['eax', 'ebx'] if reg != src][0]\n\n store_code = [\n '; using {0} as scratch'.format(scratch_reg),\n 'push {0} ; saving scratch'.format(scratch_reg),\n common.get_param(scratch_reg, 0, CodeGenManager.N_PARAMS),\n common.save_instance_field(scratch_reg, decl, src),\n 'pop {0} ; restoring scratch'.format(scratch_reg)\n ]\n\n return store_code\n\ndef get_simple_var(decl):\n '''Given a declaration, return code to get the variable'''\n if isinstance(decl, ast_param.ASTParam):\n # Method param.\n index = CodeGenManager.cur_method.c_get_param_index(decl)\n return common.get_param('eax', index, CodeGenManager.N_PARAMS)\n elif decl.c_parent_method is not None:\n # Local variable.\n return common.get_local_var('eax', decl)\n\n # Only remaining case should be an (instance) field of the encl type.\n if not isinstance(decl, ast_variable_declaration.ASTVariableDeclaration):\n raise Exception('Invalid instance var value retrieval.')\n\n # \"this\" is always the first param from an implicit \"this\".\n return [\n '; Field access of implicit \"this\"',\n common.get_param('eax', 0, CodeGenManager.N_PARAMS),\n common.get_instance_field('eax', 'eax', decl)\n ]\n\ndef get_simple_static_field(ids):\n '''Store the static field from an ASTIdentifier in $eax.'''\n f = _resolve_simple_static_fields(ids)\n return common.get_static_field('eax', f)\n\ndef set_simple_static_field(ids, src):\n '''Saves the value of src into the static field from an ASTIdentifier.'''\n f = _resolve_simple_static_fields(ids)\n return common.set_static_field(f, src)\n\ndef _resolve_simple_static_fields(ids):\n '''Resolve a simple static field access directly off the type.\n Example: ClassName.f'''\n name, defn = ids.first_definition\n if not isinstance(defn, ast_class.ASTClass):\n raise Exception('Trying to do a static field access off non-class')\n\n # Find the field using the last part of the id.\n f, encl_type = defn.environment.lookup_field(ids.parts[-1])\n if f is None or not f.is_static:\n raise Exception('Invalid static field access')\n\n return f\n\ndef get_field_access_from_annotation(ids, annotation):\n '''Returns code to get a instance field given ids and their annotations'''\n ret = ['; Getting (field) value of {0}'.format(ids)]\n\n # Resolve all parts of the ID before the final field access.\n t, code = _get_to_final(ids, annotation)\n ret.append(code)\n if t.is_array:\n # Crazy hack for arrays!\n return get_array_field(ids, ret)\n\n return get_field_from_final(t.definition, ids, ret)\n\ndef get_field_from_final(t, ids, code, get_addr=False):\n '''Returns code to get the instance field using the final idens part'''\n env = t.environment\n\n # The final part should be an instance field acccess.\n final_part = str(ids.parts[-1])\n f, encl_type = env.lookup_field(final_part)\n if get_addr:\n # Put the address of the field in eax.\n code.extend(common.get_instance_field_addr('eax', 'eax', f))\n else:\n # Put the actual value in eax.\n code.extend(common.get_instance_field('eax', 'eax', f))\n\n return code\n\ndef get_array_field(ids, code):\n '''Get an array field.\n\n The \"code\" param should have the asm code that places the array object\n in eax.'''\n # Thankfully, the only field on an array is its length.\n final_part = str(ids.parts[-1])\n if final_part != 'length':\n raise Exception('Tried to do non-length array-field access')\n\n code.append(common.get_array_length(dest='eax', src='eax'))\n return code\n\ndef get_field_from_parts(t, ids, init_asm, get_addr=False):\n import annotate_ids\n annotation = annotate_ids.annotate_from_type(t, ids.parts)\n t, field_asm = _get_to_final_from_type(t, annotation, init_asm)\n\n # Handle array field. Note: You should never be getting the address\n # of an array field.\n if not get_addr and t.is_array:\n return get_array_field(ids, field_asm)\n\n return [\n '; Get field off eax',\n get_field_from_final(t.definition, ids, field_asm, get_addr)\n ]\n\ndef _get_to_final(ids, annotation):\n '''Resolve to the final part of the identifier\n\n Returns (ASTType, asm_code)'''\n\n # Figure out where the field accesses or method invocations start.\n # - If it's off of a static variable, e.g. ClassName.static_var.f,\n # the annotation will start with static_var\n # - If it's off a local variable or field, e.g. v.f, the annotation\n # will start with v\n name, decl = annotation[0]\n t = _get_type_from_decl(decl)\n code = []\n if str(ids).startswith(name):\n # The first part matches the ID, which means we're going off a local var\n code = get_simple_var(decl)\n else:\n # The first part is a static variable access.\n code = common.get_static_field('eax', decl)\n\n if t.is_array:\n # Crazy hack for arrays!\n # If the type is an array, it's going to be the last part (because the\n # next part will be .length or one of J.L.O's methods.\n return t, code\n\n return _get_to_final_from_type(t, annotation, code)\n\ndef _get_to_final_from_type(t, annotation, code):\n '''Resolve to the final part of the identifier starting at a type\n Returns (ASTType, asm_code)'''\n\n env = t.definition.environment\n # After the start, keep doing instance field accesses off the previous\n # result.\n for name, decl in annotation[1:]:\n f, encl_type = env.lookup_field(name)\n t = f.type_node\n code.extend(common.get_instance_field('eax', 'eax', f))\n\n if t.is_array:\n # Crazy hack for arrays!\n # If the type is an array, it's going to be the last part (because the\n # next part will be .length or one of J.L.O's methods.\n return t, code\n\n env = t.definition.environment\n\n return t, code\n\ndef _get_type_from_decl(decl):\n '''Gets the ASTType from a declaration node\n\n A declaration node can be an ASTParam (method param) or an\n ASTVariableDeclaration (local or field)'''\n if isinstance(decl, ast_param.ASTParam):\n return decl.type\n elif isinstance(decl, ast_variable_declaration.ASTVariableDeclaration):\n return decl.type_node\n\n raise Exception('Invalid declaration type')\n","sub_path":"code_gen/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"605297707","text":"from mysql.connector import Error\nimport datetime\nimport logging\n#import time\n\nclass ObjectProjektClass:\n \"\"\" Main class for Saving object 36 arguments\"\"\"\n def __init__(self,id_load,title,description, celkova_cena, poznamka_k_cene, cena, naklady, id_ext, aktualizace, stavba,\n stav_objektu, vlastnictvi, podlazi,pocet_bytu,plocha_domu,plocha_zastavena,\n uzitna_plocha,plocha_podlahova,plocha_pozemku,plocha_zahrady,typ_domu,terasa, sklep, datum_nastegovani, rok_kolaudace,\n rok_reconstrukce, voda, plyn, topeni, odpad, telekomunikace, elektrina, doprava, komunikace,\n energ_narocnost_budovy, bezbarierovy, vybaveni,bazen,kontakt, link, date_open, umisteni_objektu, parkovani,garaz,puvodni_cena, region, subregion, obj_number, connection):\n \"\"\"Constructor\"\"\"\n self.id_load = id_load\n self.title = title\n self.description = description\n self.celkova_cena = celkova_cena\n self.poznamka_k_cene = poznamka_k_cene\n self.cena = cena\n self.naklady = naklady\n self.id_ext = id_ext\n self.aktualizace = aktualizace\n self.stavba = stavba\n self.stav_objektu = stav_objektu\n self.vlastnictvi = vlastnictvi\n self.podlazi = podlazi\n self.pocet_bytu = pocet_bytu\n self.plocha_domu = plocha_domu\n self.plocha_zastavena = plocha_zastavena\n self.uzitna_plocha = uzitna_plocha\n self.plocha_podlahova = plocha_podlahova\n self.plocha_pozemku = plocha_pozemku\n self.plocha_zahrady = plocha_zahrady\n self.typ_domu = typ_domu\n self.terasa = terasa\n self.sklep = sklep\n self.datum_nastegovani = datum_nastegovani\n self.rok_kolaudace = rok_kolaudace\n self.rok_reconstrukce = rok_reconstrukce\n self.voda = voda\n self.plyn = plyn\n self.topeni = topeni\n self.odpad = odpad\n self.telekomunikace = telekomunikace\n self.elektrina = elektrina\n self.doprava = doprava\n self.komunikace = komunikace\n self.energ_narocnost_budovy = energ_narocnost_budovy\n self.bezbarierovy = bezbarierovy\n self.vybaveni = vybaveni\n self.bazen = bazen\n self.kontakt = kontakt\n self.link = link\n self.date_open = date_open\n self.umisteni_objektu = umisteni_objektu\n self.parkovani = parkovani\n self.garaz = garaz\n self.puvodni_cena = puvodni_cena\n self.region = region\n self.subregion = subregion\n self.obj_number = obj_number\n self.connection = connection\n def values(self,objlist):\n longstr = \"\"\n for str in objlist:\n longstr = longstr + \"'\" + str + \"'\" + \",\"\n return longstr[0:len(longstr) - 1]\n\n def dbinsertprojekt(self):\n try:\n if self.connection.is_connected():\n # Date - today\n mydatetime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.date_open = mydatetime\n # 35\n objlist = list(self.__dict__.values())\n objlist.pop()\n query = \"INSERT INTO dbrealtor.projekt(id_load,title,description,celkova_cena,poznamka_k_cene,cena,naklady,id_ext,aktualizace,stavba,stav_objektu,vlastnictvi,\" \\\n \"podlazi,pocet_bytu,plocha_domu,plocha_zastavena,uzitna_plocha,plocha_podlahova,plocha_pozemku,plocha_zahrady,typ_domu,terasa,sklep,datum_nastegovani,rok_kolaudace,rok_reconstrukce,voda,plyn,topeni,odpad,telekomunikace,elektrina,\" \\\n \"doprava,komunikace,energ_narocnost_budovy,bezbarierovy,vybaveni,bazen,kontakt,link,date_open,umisteni_objektu,parkovani,garaz,puvodni_cena,region,subregion,obj_number)\" \\\n \" VALUES(\" + self.values(objlist) + \")\"\n cursor = self.connection.cursor()\n cursor.execute(query)\n self.connection.commit()\n #print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") + ' Inserted object_number: ', self.obj_number)\n logging.info(' Inserted object_number: %s', self.obj_number)\n cursor.close()\n return 'Inserted'\n except Exception as e:\n #print(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\") + \" Error while connecting to MySQL\", e)\n logging.error(\" Error while connecting to MySQL\" + e.msg)\n return 'Failed'\n #finally:\n # if (self.connection.is_connected()):\n # self.connection.close()","sub_path":"WebScraper/srealityscanner_projekty_class.py","file_name":"srealityscanner_projekty_class.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"157836979","text":"from src.abstract_cinema import CinemaScrapy\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\n\nclass CinepolisScrapy(CinemaScrapy):\n \"\"\"Scrapper of Cinepolis's billboard\"\"\"\n\n def __init__(self, driver_executable, browser_executable):\n \"\"\"This method initialize the scrapy\n\n Args:\n driver_executable (str): Driver for navigation. Defaults to\n \"chromedriver\".\n browser_executable (str): Path to browser executable.\n Defaults to \"/usr/bin/brave\".\n \"\"\"\n\n super().__init__(_cinema_page=\"http://www.villagecines.com/\")\n self.browser_executable = browser_executable\n self.driver_executable = driver_executable\n\n def driver(self):\n \"\"\"This method creates an instance of WebDriver\n\n Returns:\n WebDriver: Driver to navigate throw internet like a person\n \"\"\"\n options = webdriver.ChromeOptions()\n options.binary_location = self.browser_executable\n return webdriver.Chrome(\n executable_path=self.driver_executable, options=options\n )\n\n def _scrape_movie_title(self, driver):\n \"\"\"This method scraps the title of a movie\n\n Args:\n driver (WebDriver): Web container of the movie\n\n Returns:\n str: title of a movie\n \"\"\"\n return (\n driver.find_element_by_class_name(\"title-text\")\n .text.strip()\n .upper()\n )\n\n def _scrape_cinema_name(self, cinema):\n \"\"\" This method obtains the cinema's name\n\n Args:\n cinema (WebElement): Web element with a cinema's name\n\n Returns:\n str: cinema's name\n \"\"\"\n return cinema.find_element_by_class_name(\"btn-link\").text.strip()\n\n def _scrape_movie_auditorium_and_schedule(self, cinema):\n \"\"\"\n This method creates a dictionary with a cinema's name and\n it's showtime schedule\n\n Args:\n cinema (WebbElement): Web element with a cinema's schedule\n\n Returns:\n dict: auditorium as key and schedule as value\n \"\"\"\n return {\n combination.find_element_by_class_name(\n \"text-uppercase\"\n ).text.strip(): [\n anchor.text for anchor in combination.find_elements_by_tag_name(\"a\")\n ]\n for combination in cinema.find_elements_by_class_name(\n \"movie-showtimes-component-combination\"\n )\n }\n\n def _scrape_movie_schedule(self, driver):\n \"\"\"This method obtains a movie's schedule\n\n Args:\n movie_container (WebDriver): Web container of the movie\n\n Returns:\n dict: Movie with schedule data\n \"\"\"\n schedule_tab = driver.find_element_by_class_name(\n \"movie-detail-showtimes-component\"\n )\n\n schedule_data = {}\n for cinema in schedule_tab.find_elements_by_class_name(\n \"panel-primary\"\n ):\n cinema.click()\n schedule_data[\n self._scrape_cinema_name(cinema)\n ] = self._scrape_movie_auditorium_and_schedule(cinema)\n return {\"Horarios\": schedule_data}\n\n def _scrape_movie_synopsis(self, movie_driver):\n \"\"\"This method scraps the synopsis of a movie\n\n Args:\n movie_container (WebDriver): Web container of the movie\n\n Returns:\n dict: Dictionary with \"Sinopsis\" as key and a movie's\n synopsis as value\n \"\"\"\n return {\n \"Sinopsis\": movie_driver.find_element_by_id(\n \"sinopsis\"\n ).text.strip()\n }\n\n def _wait_for_traits(self, movie_driver, timeout=10):\n \"\"\"Wait for traits to load.\n\n Args:\n movie_driver (WebDriver): Movie's data container\n timeout (int, optional): time in second, to wait for tha\n page to do something. Defaults to 10.\n\n Raises:\n TimeoutException: When the trait didn't load after 'timeout'\n seconds\n\n \"\"\"\n\n WebDriverWait(movie_driver, timeout).until(\n EC.text_to_be_present_in_element((By.ID, \"tecnicos\"), \"Título\")\n )\n\n def _collect_movie_traits(self, movie_driver):\n \"\"\"This method fetches the traits of a movie from the movie\n container\n\n Args:\n movie_container (WebDriver): Web container of the movie\n\n Returns:\n dict: Collected traits of a movie\n \"\"\"\n movie_driver.find_element_by_id(\"tecnicos-tab\").click()\n self._wait_for_traits(movie_driver)\n\n traits = {}\n try:\n for trait in movie_driver.find_element_by_id(\"tecnicos\").text.split(\n \"\\n\"\n ):\n key, value = trait.split(\": \", 1)\n traits[key] = value\n except ValueError:\n pass\n\n return traits\n\n def _split_string_trait(self, traits, trait, separator):\n \"\"\"This method splits a string in 'traits' with key 'trait' by\n 'separator', replacing the original string with a list.\n\n Args:\n traits (dict): Traits of a movie\n trait (str): Movie trait representing a list\n separator (str): Separator of the trait's list\n\n Returns:\n dict: Traits of a movie\n \"\"\"\n if trait in traits.keys():\n traits[trait] = traits[trait].split(separator)\n return traits\n\n def _separate_movie_traits(self, traits):\n \"\"\"This methods splits every list-like string in 'traits' that's\n considered fitting\n\n Args:\n traits (dict): Traits of a movie\n\n Returns:\n dict: Traits of a movie with reformatted keys\n \"\"\"\n for trait in [\"Actores\", \"Género\"]:\n traits = self._split_string_trait(traits, trait, \", \")\n return traits\n\n def _normalize_movie(self, movie):\n \"\"\"This method normalizes a movie's data\n\n Args:\n movie (dict): A movie data\n\n Returns:\n dict: Normalized movie data\n \"\"\"\n if \"Duración\" in movie.keys():\n movie[\"Duración\"] = movie[\"Duración\"][:-1] + \"utos\"\n return movie\n\n def scrape(self):\n \"\"\"\n This method starts the scrapping of a cinepolis's billboard page\n\n Returns:\n dict: Data of movies\n str: Source of data\n \"\"\"\n movies = {}\n driver = self.driver()\n driver.get(self._cinema_page)\n movie_container = driver.find_element_by_class_name(\"movie-grid\")\n for movie in [\n anchor.get_attribute(\"href\")\n for anchor in movie_container.find_elements_by_tag_name(\"a\")\n ]:\n try:\n driver.get(movie)\n movies.update(self.scrape_movie(driver))\n except TimeoutException:\n pass\n\n driver.quit()\n return movies, \"Cinepolis\"\n","sub_path":"src/cinepolis.py","file_name":"cinepolis.py","file_ext":"py","file_size_in_byte":7211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"463578351","text":"\"\"\"\nContent store for compiled representation of paper.\n\nUses S3 as the underlying storage facility.\n\nThe intended use pattern is that a client (e.g. API controller) can check for\na compilation using the source ID (e.g. file manager source_id), the format,\nand the checksum of the source package (as reported by the FM service) before\ntaking any IO-intensive actions. See :meth:`StoreSession.get_status`.\n\nSimilarly, if a client needs to verify that a compilation product is available\nfor a specific source checksum, they would use :meth:`StoreSession.get_status`\nbefore calling :meth:`StoreSession.retrieve`. For that reason,\n:meth:`StoreSession.retrieve` is agnostic about checksums. This cuts down on\nan extra GET request to S3 every time we want to get a compiled resource.\n\"\"\"\nimport json\nfrom typing import Tuple, Optional, Dict, Union, List, Any, Mapping\nfrom functools import wraps\nfrom hashlib import md5\nfrom base64 import b64encode\nfrom collections import defaultdict\nimport boto3\nimport botocore\nfrom flask import Flask\n\nfrom arxiv.base import logging\nfrom arxiv.base.globals import get_application_global, get_application_config\n\nfrom ...domain import CompilationStatus, CompilationProduct\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DoesNotExist(RuntimeError):\n \"\"\"The requested content does not exist.\"\"\"\n\n\ndef hash_content(body: bytes) -> str:\n \"\"\"Generate an encoded MD5 hash of a bytes.\"\"\"\n return b64encode(md5(body).digest()).decode('utf-8')\n\n\nclass StoreSession(object):\n \"\"\"Represents an object store session.\"\"\"\n\n def __init__(self, buckets: List[Tuple[str, str]], version: str,\n verify: bool = False,\n region_name: Optional[str] = None,\n endpoint_url: Optional[str] = None,\n aws_access_key_id: Optional[str] = None,\n aws_secret_access_key: Optional[str] = None) -> None:\n \"\"\"Initialize with connection config parameters.\"\"\"\n self.buckets = buckets\n self.version = version\n self.region_name = region_name\n self.endpoint_url = endpoint_url\n self.aws_access_key_id = aws_access_key_id\n self.aws_secret_access_key = aws_secret_access_key\n\n # Compilation status is cached here, in case we're taking several\n # status-related actions in one request/execution context. Saves us\n # GET requests, which saves $$$.\n self._status: Dict[str, Dict[str, Dict[str, Dict[str, str]]]] = {}\n\n # Only add credentials to the client if they are explicitly set.\n # If they are not set, boto3 falls back to environment variables and\n # credentials files.\n params: Dict[str, Any] = dict(region_name=region_name)\n if aws_access_key_id and aws_secret_access_key:\n params.update(dict(\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key\n ))\n if endpoint_url:\n params.update(dict(\n endpoint_url=endpoint_url,\n verify=verify\n ))\n self.client = boto3.client('s3', **params)\n\n def _key(self, source_id: str, checksum: str,\n format: CompilationStatus.Formats) -> str:\n return f'{source_id}/{checksum}/{format.value}'\n\n def get_status(self, source_id: str, source_checksum: str,\n format: CompilationStatus.Formats,\n bucket: str = 'arxiv') -> CompilationStatus:\n \"\"\"\n Get the status of a compilation.\n\n Parameters\n ----------\n source_id : str\n The unique identifier of the source package.\n format: str\n Compilation format. See :attr:`CompilationStatus.Formats`.\n source_checksum : str\n Base64-encoded MD5 hash of the source package.\n bucket : str\n\n Returns\n -------\n :class:`CompilationStatus`\n\n Raises\n ------\n :class:`DoesNotExist`\n Raised if no status exists for the provided parameters.\n\n \"\"\"\n _key = self._key(source_id, source_checksum, format)\n key = f'{_key}/status.json'\n logger.debug('Get status for upload %s with key %s', source_id, key)\n try:\n response = self.client.get_object(\n Bucket=self._get_bucket(bucket),\n Key=key\n )\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"NoSuchKey\":\n raise DoesNotExist(f'No status data for {source_id} in bucket'\n f' {bucket}.') from e\n raise RuntimeError(f'Unhandled exception: {e}') from e\n data = json.loads(response['Body'].read().decode('utf-8'))\n data['format'] = CompilationStatus.Formats(data['format'])\n data['status'] = CompilationStatus.Statuses(data['status'])\n return CompilationStatus(**data)\n\n def set_status(self, status: CompilationStatus, bucket: str = 'arxiv') \\\n -> None:\n \"\"\"\n Update the status of a compilation.\n\n Parameters\n ----------\n status : :class:`CompilationStatus`\n bucket : str\n\n \"\"\"\n _key = self._key(status.source_id, status.source_checksum,\n status.format)\n key = f'{_key}/status.json'\n body = json.dumps(status.to_dict()).encode('utf-8')\n try:\n self.client.put_object(\n Body=body,\n Bucket=self._get_bucket(bucket),\n ContentMD5=hash_content(body),\n ContentType='application/json',\n Key=key\n )\n except botocore.exceptions.ClientError as e:\n raise RuntimeError(f'Unhandled exception: {e}') from e\n\n def store(self, product: CompilationProduct, bucket: str = 'arxiv') \\\n -> None:\n \"\"\"\n Store a compilation product.\n\n Parameters\n ----------\n product : :class:`CompilationProduct`\n bucket : str\n Default is ``'arxiv'``. Used in conjunction with :attr:`.buckets`\n to determine the S3 bucket where this content should be stored.\n\n \"\"\"\n if product.status is None or product.status.source_id is None:\n raise ValueError('source_id must be set')\n\n body = product.stream.read()\n status = product.status\n _key = self._key(status.source_id, status.source_checksum,\n status.format)\n key = f'{_key}/{status.source_id}.{status.ext}'\n try:\n self.client.put_object(\n Body=body,\n Bucket=self._get_bucket(bucket),\n ContentMD5=hash_content(body),\n ContentType=product.status.content_type,\n Key=key,\n )\n except botocore.exceptions.ClientError as e:\n raise RuntimeError(f'Unhandled exception: {e}') from e\n self.set_status(status, bucket=bucket)\n\n def retrieve(self, source_id: str, source_checksum: str,\n format: CompilationStatus.Formats,\n bucket: str = 'arxiv') -> CompilationProduct:\n \"\"\"\n Retrieve a compilation product.\n\n Parameters\n ----------\n source_id : str\n source_checksum : str\n format : enum\n One of :attr:`CompilationStatus.Formats`.\n bucket : str\n Default is ``'arxiv'``. Used in conjunction with :attr:`.buckets`\n to determine the S3 bucket from which the content should be\n retrieved\n\n Returns\n -------\n :class:`CompilationProduct`\n\n \"\"\"\n _key = self._key(source_id, source_checksum, format)\n key = f'{_key}/{source_id}.{CompilationStatus.get_ext(format)}'\n try:\n response = self.client.get_object(\n Bucket=self._get_bucket(bucket),\n Key=key\n )\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"NoSuchKey\":\n raise DoesNotExist(f'No {format} product for {source_id} in'\n f' bucket {bucket}') from e\n raise RuntimeError(f'Unhandled exception: {e}') from e\n return CompilationProduct(stream=response['Body'],\n checksum=response['ETag'][1:-1])\n\n def store_log(self, product: CompilationProduct, bucket: str = 'arxiv') \\\n -> None:\n \"\"\"\n Store a compilation log.\n\n Parameters\n ----------\n product : :class:`CompilationProduct`\n Stream should be log content.\n bucket : str\n Default is ``'arxiv'``. Used in conjunction with :attr:`.buckets`\n to determine the S3 bucket where this content should be stored.\n\n \"\"\"\n if product.status is None or product.status.source_id is None:\n raise ValueError('source_id must be set')\n\n body = product.stream.read()\n status = product.status\n _key = self._key(status.source_id, status.source_checksum,\n status.format)\n key = f'{_key}/{status.source_id}.{status.ext}.log'\n try:\n self.client.put_object(\n Body=body,\n Bucket=self._get_bucket(bucket),\n ContentMD5=hash_content(body),\n ContentType='text/plain',\n Key=key,\n )\n except botocore.exceptions.ClientError as e:\n raise RuntimeError(f'Unhandled exception: {e}') from e\n self.set_status(status, bucket=bucket)\n\n def retrieve_log(self, source_id: str, source_checksum: str,\n format: CompilationStatus.Formats,\n bucket: str = 'arxiv') -> CompilationProduct:\n \"\"\"\n Retrieve a compilation log.\n\n Parameters\n ----------\n source_id : str\n source_checksum : str\n format : enum\n One of :attr:`CompilationStatus.Formats`.\n bucket : str\n Default is ``'arxiv'``. Used in conjunction with :attr:`.buckets`\n to determine the S3 bucket from which the content should be\n retrieved\n\n Returns\n -------\n :class:`CompilationProduct`\n\n \"\"\"\n _key = self._key(source_id, source_checksum, format)\n key = f'{_key}/{source_id}.{CompilationStatus.get_ext(format)}.log'\n try:\n response = self.client.get_object(\n Bucket=self._get_bucket(bucket),\n Key=key\n )\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"NoSuchKey\":\n raise DoesNotExist(f'No {format} product for {source_id} in'\n f' bucket {bucket}') from e\n raise RuntimeError(f'Unhandled exception: {e}') from e\n return CompilationProduct(stream=response['Body'],\n checksum=response['ETag'][1:-1])\n\n def create_bucket(self) -> None:\n \"\"\"Create S3 buckets. This is just for testing.\"\"\"\n for key, bucket in self.buckets:\n self.client.create_bucket(Bucket=bucket)\n\n def _get_bucket(self, bucket: str) -> str:\n try:\n name: str = dict(self.buckets)[bucket]\n except KeyError as e:\n raise RuntimeError(f'No such bucket: {bucket}') from e\n return name\n\n\n@wraps(StoreSession.get_status)\ndef get_status(source_id: str, source_checksum: str,\n format: CompilationStatus.Formats, bucket: str = 'arxiv') \\\n -> CompilationStatus:\n \"\"\"See :func:`StoreSession.get_status`.\"\"\"\n s = current_session()\n return s.get_status(source_id, source_checksum, format, bucket=bucket)\n\n\n@wraps(StoreSession.set_status)\ndef set_status(status: CompilationStatus, bucket: str = 'arxiv') -> None:\n \"\"\"See :func:`StoreSession.get_status`.\"\"\"\n return current_session().set_status(status, bucket=bucket)\n\n\n@wraps(StoreSession.store)\ndef store(product: CompilationProduct, bucket: str = 'arxiv') -> None:\n \"\"\"See :func:`StoreSession.store`.\"\"\"\n return current_session().store(product, bucket=bucket)\n\n\n@wraps(StoreSession.store_log)\ndef store_log(product: CompilationProduct, bucket: str = 'arxiv') -> None:\n \"\"\"See :func:`StoreSession.store_log`.\"\"\"\n return current_session().store_log(product, bucket=bucket)\n\n\n@wraps(StoreSession.retrieve)\ndef retrieve(source_id: str, source_checksum: str,\n format: CompilationStatus.Formats,\n bucket: str = 'arxiv') -> CompilationProduct:\n \"\"\"See :func:`StoreSession.retrieve`.\"\"\"\n return current_session().retrieve(source_id, source_checksum, format,\n bucket=bucket)\n\n\n@wraps(StoreSession.retrieve_log)\ndef retrieve_log(source_id: str, source_checksum: str,\n format: CompilationStatus.Formats,\n bucket: str = 'arxiv') -> CompilationProduct:\n \"\"\"See :func:`StoreSession.retrieve_log`.\"\"\"\n return current_session().retrieve_log(source_id, source_checksum, format,\n bucket=bucket)\n\n\ndef init_app(app: Flask) -> None:\n \"\"\"Set defaults for required configuration parameters.\"\"\"\n app.config.setdefault('AWS_REGION', 'us-east-1')\n app.config.setdefault('AWS_ACCESS_KEY_ID', None)\n app.config.setdefault('AWS_SECRET_ACCESS_KEY', None)\n app.config.setdefault('S3_ENDPOINT', None)\n app.config.setdefault('S3_VERIFY', True)\n app.config.setdefault('S3_BUCKET', [])\n app.config.setdefault('VERSION', \"0.0\")\n\n\ndef get_session() -> StoreSession:\n \"\"\"Create a new :class:`botocore.client.S3` session.\"\"\"\n config = get_application_config()\n access_key = config.get('AWS_ACCESS_KEY_ID')\n secret_key = config.get('AWS_SECRET_ACCESS_KEY')\n endpoint = config.get('S3_ENDPOINT')\n verify = config.get('S3_VERIFY')\n region = config.get('AWS_REGION')\n buckets = config.get('S3_BUCKETS')\n version = config.get('VERSION')\n return StoreSession(buckets, version, verify, region,\n endpoint, access_key, secret_key)\n\n\ndef current_session() -> StoreSession:\n \"\"\"Get the current store session for this application.\"\"\"\n g = get_application_global()\n if g is None:\n return get_session()\n if 'store' not in g:\n g.store = get_session()\n store: StoreSession = g.store\n return store\n","sub_path":"compiler/services/store/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"49202701","text":"from flask import Flask\n\n# from day01 import demo\n\n# 1.0 创建flask的应用对象 核心 __name__魔法变量:当前文件所在模块的名字\napp = Flask(__name__)\n\n# 配置参数的使用方式\n# 1.1使用配置文件\n# app.config.from_pyfile(\"config.cfg\")\n\n# 1.3 直接操作config 字典\napp.config[\"DEBUG\"] = True\n\n\n# 视图函数 用装饰器绑定路由\n@app.route(\"/index\")\ndef index():\n print(\"nihao\")\n print(app.config.get(\"DEBUG\"))\n return \"你好啊 flask\"\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"day01/helloworld.py","file_name":"helloworld.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"277125219","text":"class Paging():\n def __init__(self,request,total,page_num,show_num=10,max_page_num=5):\n self.request=request\n self.total=total #总数据量\n #用户输入非数字,捕获错误,跳至第一页\n try:\n page_num = int(page_num)\n except Exception:\n page_num=1\n self.page_num=page_num #当前页\n self.show_num=show_num #一页显示数量\n self.max_page_num=max_page_num #最多显示的页码标签数\n\n page_sum,a=divmod(total,show_num) #总页码数\n if a:\n page_sum+=1\n\n #判断当前页是否在范围内\n if self.page_num<1:\n self.page_num=1\n elif self.page_num>page_sum:\n self.page_num=page_sum\n\n #页码的列表\n if page_sum < max_page_num:\n page_list=[i for i in range(1,page_sum+1)]\n else:# 让当前页显示在中间\n if self.page_num-max_page_num//2<1:\n page_list=[i for i in range(1,max_page_num+1)]\n elif self.page_num+max_page_num//2>page_sum:\n page_list=[i for i in range(page_sum-max_page_num+1,page_sum+1)]\n else:\n page_list=[i for i in range(self.page_num-max_page_num//2,self.page_num+max_page_num//2+1)]\n self.page_list=page_list\n\n #上页下页\n self.prev_page=self.page_num-1 if self.page_num>1 else 1\n self.next_page=self.page_num+1 if self.page_num«' %(self.request.path,self.prev_page)\n\n body=''\n for i in self.page_list:\n body+='
  • %s
  • ' %(self.request.path,i,i)\n\n\n tail='
  • »
  • ' %(self.request.path,self.next_page)\n\n return head+body+tail","sub_path":"lyh/app/tt.py","file_name":"tt.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"262903238","text":"import paramiko\nimport SETTINGS\nfrom Exceptions.vm_exception import VMException\nimport time\n\nclass VirtuaMachine:\n def __init__(self):\n self.mac = \"\"\n self.ip = \"\"\n self.xml = \"\"\n self.name = \"\"\n self.image = \"\"\n self.domain = None\n self.ssh = None\n self.cpu_set = \"\"\n\n def open_ssh(self):\n tries = 0\n while True:\n try:\n self.ssh = paramiko.SSHClient()\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.ssh.connect(hostname=self.ip, username=SETTINGS.USER, password=SETTINGS.PASSWORD, port=22)\n break\n except Exception:\n tries += 1\n if tries > 10:\n break\n time.sleep(4)\n continue\n\n def send_cmd_without_answer(self, cmd):\n self.ssh.exec_command(cmd)\n\n def send_cmd(self, cmd):\n # print(\"CMD to run in %s %s\"%(self.ip, cmd))\n stdin, stdout, stderr = self.ssh.exec_command(cmd)\n exit_status = stdout.channel.recv_exit_status() # Blocking call\n # if exit_status == 0:\n # print(\"'%s' is complete\"%cmd)\n # else:\n # print(\"Error\", exit_status)\n return stdout.read().decode('utf-8')","sub_path":"kvm/virtuamachine.py","file_name":"virtuamachine.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"518837179","text":"from bs4 import BeautifulSoup\nimport requests as req\nimport json, os.path\n\nif not os.path.isfile(\"./data.json\"):\n baseLink = \"https://the-familiar.fandom.com\"\n bookListPage = req.get(baseLink + \"/wiki/Category:Volumes\")\n bookListPageSoup = BeautifulSoup(bookListPage.text, \"lxml\")\n\n data = {\"colors\":{\n\t\t\"Xanther Ibrahim\": { \"primary\": \"#F7B7C7\", \"secondary\": \"#201C1A\" },\n\t\t\"Jingjing\": { \"primary\": \"#01ACE0\", \"secondary\": \"#E90280\" },\n\t\t\"Luther Perez\": { \"primary\": \"#231F1C\", \"secondary\": \"#FBE445\" },\n\t\t\"Anwar Ibrahim\": { \"primary\": \"#569254\", \"secondary\": \"#CA5A24\" },\n\t\t\"Astair Ibrahim\": { \"primary\": \"#F7831C\", \"secondary\": \"#FADCB1\" },\n\t\t\"Isand\\u00f2rno\": { \"primary\": \"#ECCE52\", \"secondary\": \"#813E19\" },\n\t\t\"\\u00d6zg\\u00fcr Yildirim\": { \"primary\": \"#855912\", \"secondary\": \"#BBBCB4\" },\n\t\t\"The Wizard\": { \"primary\": \"#A7A8A2\", \"secondary\": \"#79555C\" },\n\t\t\"Shnorhk Zildjian\": { \"primary\": \"#BE4935\", \"secondary\": \"#7D9AC5\" }\n }}\n \n data[\"books\"] = []\n\n for element in bookListPageSoup.find_all(\n \"a\", attrs={\"class\": \"category-page__member-link\"}\n ):\n volume = (element.text.split(\":\", 1)[0]).replace(\"Volume \", \"\")\n title = element.text.split(\": \", 1)[1]\n\n chapterCount = 1;\n chapters = []\n bookPage = req.get(baseLink + element[\"href\"])\n bookPageSoup = BeautifulSoup(bookPage.text, \"lxml\")\n for tag in bookPageSoup.find(\n \"span\", attrs={\"id\": \"Chapters\"}\n ).parent.next_siblings:\n if tag.name == \"h2\":\n break\n else:\n if tag != None:\n if tag.name != None:\n for li in tag.find_all(\"li\"):\n if li.a:\n chapterPage = req.get(li.a[\"href\"])\n chapterPageSoup = BeautifulSoup(\n chapterPage.text, \"lxml\"\n )\n narrator = \"\"\n start = \"\"\n end = \"\"\n summary = \"\"\n\n print(li.a)\n summaryComponent = chapterPageSoup.find(\n \"span\", attrs={\"id\": \"Summary\"}\n )\n \n if(summaryComponent!=None):\n for chapterTag in summaryComponent.parent.next_siblings:\n if chapterTag.name == \"h3\":\n break\n else:\n if chapterTag != None:\n if chapterTag.name == \"p\":\n summary += str(chapterTag.text)\n\n for tr in chapterPageSoup.find_all(\"tr\"):\n if str(tr.th.text).rstrip() == \"Narrator\":\n narrator = str(tr.th.next_sibling.text).rstrip()\n elif str(tr.th.text).rstrip() == \"Starts\":\n start = str(tr.th.next_sibling.text).rstrip()\n elif str(tr.th.text).rstrip() == \"Ends\":\n end = str(tr.th.next_sibling.text).rstrip()\n\n chapters.append(\n {\n \"title\": li.a.text,\n \"chapter\":chapterCount,\n \"narrator\": narrator,\n \"start\": start,\n \"end\": end,\n \"summary\": summary,\n }\n )\n else:\n chapters.append({\"title\": li.text, \"chapter\":chapterCount})\n else:\n chapters.append({\"title\": li.text, \"chapter\":chapterCount})\n chapterCount += 1;\n\n data[\"books\"].append({\"volume\": volume, \"title\": title, \"chapters\": chapters})\n with open(\"data.json\", \"w\") as outfile:\n json.dump(data, outfile)\n\nelse:\n print(\"Data already created!\")","sub_path":"dataCollector.py","file_name":"dataCollector.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"175200019","text":"from zope import interface, component\n\nfrom z3c.metrics import interfaces\n\n\nclass Engine(object):\n interface.implements(interfaces.IEngine)\n component.adapts(interfaces.IMetric,\n interfaces.ISubscription,\n interface.Interface)\n\n def __init__(self, metric, subscription, context):\n self.metric = metric\n self.subscription = subscription\n self.index = subscription.getIndex(context)\n self.scale = self.index.scale\n self.context = context\n\n def initScore(self):\n self.index.initScoreFor(self.context)\n\n def removeScore(self):\n self.index.removeScoreFor(self.context)\n\n\nclass WeightedEngine(Engine):\n component.adapts(interfaces.IMetric,\n interfaces.IWeightedSubscription,\n interface.Interface)\n\n def addValue(self, value):\n scaled = self.scale.fromValue(value)\n weighted = self.subscription.weight * scaled\n self.index.changeScoreFor(self.context, weighted)\n\n def changeValue(self, previous, current):\n scaled = (self.scale.fromValue(current) -\n self.scale.fromValue(previous))\n weighted = self.subscription.weight * scaled\n self.index.changeScoreFor(self.context, weighted)\n\n def removeValue(self, value):\n scaled = self.scale.fromValue(value)\n weighted = self.subscription.weight * scaled\n self.index.changeScoreFor(self.context, -weighted)\n","sub_path":"z3c.metrics/trunk/z3c/metrics/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"410387780","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 ('application', '0032_auto_20160427_2139'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='groups',\n name='updates',\n field=models.CommaSeparatedIntegerField(max_length=200, null=True, verbose_name='\\u0414\\u043e\\u043d\\u0430\\u0431\\u043e\\u0440\\u044b \\u0432 \\u0433\\u0440\\u0443\\u043f\\u043f\\u0443', blank=True),\n ),\n ]\n","sub_path":"application/migrations/0033_groups_updates.py","file_name":"0033_groups_updates.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"152151343","text":"import os\r\nimport csv\r\nimport re\r\nimport requests\r\nimport webbrowser\r\nfrom bs4 import BeautifulSoup\r\n\r\nos.system('tasklist /v /fi \"IMAGENAME eq Spotify.exe\" /fo List > list.csv')\r\n\r\nwith open('list.csv', encoding='latin1', newline='') as f:\r\n reader = csv.reader(f)\r\n data = list(reader)\r\n\r\ntitle = str(data[9])\r\ntitle = re.split(':', title)\r\ntitle = str(title[1])\r\ntitle = title[:-2]\r\ntitle = title[1:]\r\nprint(title)\r\n\r\nUSER_AGENT = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0\"\r\nheaders = {\"user-agent\": USER_AGENT}\r\nURL = \"https://google.com/search?q=\"+title+\" rap genius\"\r\nresp = requests.get(URL, headers=headers)\r\nsoup = BeautifulSoup(resp.content, \"html.parser\")\r\nresults = []\r\nfor g in soup.find_all('div', class_='r'):\r\n anchors = g.find_all('a')\r\n if anchors:\r\n link = anchors[0]['href']\r\n item = {\r\n link\r\n }\r\n results.append(item)\r\n results = str(results[0])\r\n break\r\n\r\nresults = results[:-2]\r\nresults = results[2:]\r\nwebbrowser.open(results)\r\nos.system('del list.csv')\r\n\r\n","sub_path":"SpotifyLyrics.py","file_name":"SpotifyLyrics.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"132513027","text":"import pytest\nfrom django.urls import reverse\n\n\n@pytest.mark.django_db\ndef test_index_action(admin_app,\n project):\n assert project.state == 'requested'\n url = reverse('crm_project_modeladmin_index')\n r = admin_app.get(url)\n r = r.click(\"Drop\")\n inputs = r.lxml.xpath(\".//*[@id='id_notes']\")\n assert len(inputs) == 1\n\n r = r.forms[1].submit().follow()\n\n project.refresh_from_db()\n assert project.state == 'stopped'\n assert len(r.context['messages']) == 1\n\n\n@pytest.mark.django_db\ndef test_inspect(admin_app,\n project):\n url = reverse('crm_project_modeladmin_inspect', kwargs={'instance_pk': project.pk})\n admin_app.get(url)\n\n\n@pytest.mark.django_db\ndef test_inspect_blank(admin_app, project_factory):\n project = project_factory.create(\n project_page=None,\n start_date=None,\n end_date=None,\n daily_rate=None\n )\n url = reverse('crm_project_modeladmin_inspect', kwargs={'instance_pk': project.pk})\n admin_app.get(url)\n","sub_path":"crm/tests/test_project_admin.py","file_name":"test_project_admin.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"505863378","text":"import isa\n\n# ------------------------------------------------------------------------------------------------------\n# THIS FILE ASKS FOR USER INPUT AND HANDLES THE OUTPUT\n# ------------------------------------------------------------------------------------------------------\n\nprint(\"==============================\")\nprint(\"| V0X's Great ISA Calculator |\")\nprint(\"==============================\")\nprint(\"\\nLast edited on 27 April 2019\")\nprint(\"\\n------------------------------\")\n\n# Ask for the input units\n# Check if the input number is possible\n\nsAltitudeType = \"\"\n\nwhile True:\n\n print(\"\\nIn which units do you want to enter your altitude?\\n\")\n print(\"1. In [m]\\n2. In [ft]\\n3. In [FL]\")\n\n sInputNo = input(\"\\nEnter your choice: \")\n\n if sInputNo == \"1\" or sInputNo == \"2\" or sInputNo == \"3\":\n sAltitudeType = sInputNo\n break\n else:\n print(\"\\nYou did not enter a valid choice. Please try again.\")\n\n# Let the user enter a custom starting temperature\n# Check if the input is valid, else the loop run again\n\nfSeaLevelTemp = 288.15\n\nwhile True:\n\n print(\"\\nDo you want to enter a custom sea level temperature? (Y/N)\")\n\n sInputNo = input(\"\\nEnter your choice: \")\n\n if sInputNo == \"y\" or sInputNo == \"Y\" or sInputNo == \"n\" or sInputNo == \"N\":\n while True:\n\n if sInputNo == \"n\" or sInputNo == \"N\":\n break\n\n sSeaLevelTemp = input(\"\\nEnter temperature [K]: \")\n\n # Check if input is actually a number\n try:\n float(sSeaLevelTemp)\n except:\n print(\"\\nYou did not enter a number. Please try again.\")\n continue\n\n # Convert string to float\n fSeaLevelTemp = float(sSeaLevelTemp)\n\n break\n \n break\n else:\n print(\"\\nYou did not enter a valid choice. Please try again.\")\n\n# Get the input altitude and calculate the temperature\n# If the input is invalid, let the loop run again\n\nfAltitude = 0\n\nwhile True:\n\n sAltitude = input(\"\\nEnter altitude: \")\n\n # Check if input is actually a number\n try:\n float(sAltitude)\n except:\n print(\"\\nYou did not enter a number. Please try again.\")\n continue\n\n # Convert string to float\n fAltitude = float(sAltitude)\n\n # Run conversion to metric units if required\n if sAltitudeType == \"2\":\n fAltitude = fAltitude*0.3048\n\n if sAltitudeType == \"3\":\n fAltitude = fAltitude*30.48\n\n # Run checks on the input\n if fAltitude < 0:\n print(\"\\nYou entered an altitude smaller than 0. Please try again.\")\n continue\n\n if fAltitude >= 84.852*1000:\n print(\"\\nYour altitude is too large: you are in outer space. Please try again.\")\n continue\n\n # If this point in the code is reached, the input was 100% so we can break out of the loop\n break\n\n# Calculate the resulting ISA values\n# These values will be stored in an array\n\narrISAValues = isa.calculateISAValues(fAltitude, fSeaLevelTemp)\n\n# Print results from input and calculation\n# Round them to some decimals\n\nprint(\"\\nTemperature: \", round(arrISAValues[0], 2), \" [K]\")\nprint(\"Pressure: \", round(arrISAValues[1], 2), \"[Pa]\")\nprint(\"Density: \", round(arrISAValues[2], 3), \"[kg/m^3]\\n\")","sub_path":"assignments/1/program/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"191260756","text":"\"\"\"\nprogram to run extract_table.py functions so as to avoid unnecessary modules and functions in the deployment package\n\"\"\"\n\nfrom pdftabextract.extract import datatable_to_dataframe\nfrom lambda_extract_table.TableClass import TableExtract\n\nif __name__ == '__main__':\n ini_file = \"/Users/andyspence/Project/SHV/src/Parse_data/table_id/extract.ini\"\n xml = '/Users/andyspence/Project/SHV/src/Parse_data/table_id/pl_data/f-00001122_2013_Im9.xml'\n\n print()\n # start = time.time()\n\n t = TableExtract(ini_file=ini_file, xml_file=xml)\n df = datatable_to_dataframe(t.table, split_texts_in_lines=True)\n\n # print(\"runtime: {0:0.2}secs\".format(time.time() - start))\n\n print(df)\n","sub_path":"src/Parse_data/table_id/functions/lambda_extract_table/run_extract_table.py","file_name":"run_extract_table.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"504161781","text":"from sqlalchemy.orm import attribute_keyed_dict, relationship\n\nfrom app.infrastructure.tables import projects_table, tasks_table\nfrom app.modules.projects.domain.project import Project, Task\n\n\ndef start_mappers(mapper_registry):\n mapper_registry.map_imperatively(\n Project,\n projects_table,\n properties={\n \"_id\": projects_table.c.id,\n \"_user_id\": projects_table.c.user_id,\n \"_name\": projects_table.c.name,\n \"_maximum_number_of_incomplete_tasks\": projects_table.c.maximum_number_of_incomplete_tasks,\n \"_last_task_number\": projects_table.c.last_task_number,\n \"_tasks_by_number\": relationship(\n Task,\n collection_class=attribute_keyed_dict(\"number\"),\n ),\n \"_archived_at\": projects_table.c.archived_at,\n \"_deleted_at\": projects_table.c.deleted_at,\n },\n )\n\n mapper_registry.map_imperatively(\n Task,\n tasks_table,\n properties={\n \"_number\": tasks_table.c.number,\n \"_name\": tasks_table.c.name,\n \"_created_by\": tasks_table.c.created_by,\n \"_completed_at\": tasks_table.c.completed_at,\n },\n )\n","sub_path":"app/modules/projects/infrastructure/mappers.py","file_name":"mappers.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"207502893","text":"from datetime import date\nfrom django.db.models import Sum,Avg\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\nfrom groups.models import *\nfrom events.models import *\n\ntoday = date.today()\n#helpers\ndef getPercentageIncrease(current,previous):\n percentage_increase =0\n try:\n percentage_increase = ((current - previous) / previous) * 100\n except:\n pass\n\n return percentage_increase\n\ndef getPercentageToTotal(figure,total):\n percentage = 0\n try:\n percentage = (figure/total)*100\n except:\n pass\n return percentage\n\nclass MemberCountStats(APIView):\n def get(self,request):\n dict = []\n number_of_groups = ChurchGroup.objects.all().count()\n total_new_members_count = ChurchGroupMembership.objects.filter(date_joined__month__gt=today.month-3,date_joined__year=today.year).count()\n total_members_in_groups = ChurchGroupMembership.objects.all().count()\n dict.append({\"number_of_groups\":number_of_groups,\"total_members_in_groups\":total_members_in_groups,\n \"total_new_members_count\":total_new_members_count,\"stats\":[]})\n for group in ChurchGroup.objects.all():\n members_count = group.number_of_members\n new_members_count = ChurchGroupMembership.objects.filter(church_group_id=group.id,date_joined__month__gt=today.month-3,date_joined__year=today.year).count()\n percentage_to_total = getPercentageToTotal(members_count,total_members_in_groups)\n\n group_tuple = {\"group\":str(group),\"members_count\":members_count,\"percentage_to_total\":percentage_to_total,\n \"new_members_count\":new_members_count}\n dict[0][\"stats\"].append(group_tuple)\n return Response(dict)\nclass EventAttendanceStats(APIView):\n def get(self,request):\n dict = []\n for month in range(1,today.month + 1):\n total_attendance_this_month = MemberThatAttendedEvent.objects.filter(event__start_datetime__month=month).count()\n total_attendance_last_month = MemberThatAttendedEvent.objects.filter(event__start_datetime__month=month-1).count()\n percentage_increase = getPercentageIncrease(total_attendance_this_month,total_attendance_last_month)\n\n month_tuple = {\"month\":month,\"total_attendance_this_month\":total_attendance_this_month,\"percentage_increase\":percentage_increase}\n dict.append(month_tuple)\n return Response(dict)\n","sub_path":"groups/api/views/statviews.py","file_name":"statviews.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"501210048","text":"from .models import MegafonAuthUser, MegafonBinar, MegafonPassport, MegafonOffer\nfrom sms.models import Botnet\nfrom django.http import HttpResponse\nimport logging\nimport redis\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.conf import settings\n\nr = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)\n\n# Create your views here.\n\n#----LOG CREATE -------------#\nlog = logging.getLogger(\"info\")\n\ndef check_bot(user_id):\n \n bot_counter = 0\n try:\n bots = MegafonBinar.objects.filter(referrer=user_id)\n except ObjectDoesNotExist:\n log.info(\"У пользователя {} нет клиентов!\".format(user_id))\n r.sadd('ListUserAddBot', user_id)\n log.info(\"Пользователь {} добавлен в очерель за ботами!\".format(user_id))\n else : \n for bot in bots:\n if bot.user.is_bot == \"T\":\n bot_counter = bot_counter + 1\n\n if bot_counter < 15:\n log.info(\"У пользователя {} менее 15 ботов!\".format(user_id))\n r.sadd('ListUserAddBot', user_id)\n log.info(\"Пользователь {} добавлен в очерель за ботами!\".format(user_id))\n \n \n\n \n \n \n ","sub_path":"infinans_rustam/check_bot.py","file_name":"check_bot.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"367383369","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# dense.py\n# \n# Copyright 2019 Lukáš Plevač \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n#\n\nimport numpy as np\nfrom ..activation import linear as defaultactivation\n\n'''\ndense layer (fully connect)\n\n@input ND numpy arrays\n@output ND numpy array with shape concat of all branches\n\nSAMPLE:\ninput-shape: (2,)\nconcat([\n [\n dense(3)\n ],\n\n [\n dense(3)\n ]\n])\noutput-shape(6,) \n'''\nclass concat:\n '''\n This function be called when code create layer it define branches\n \n @param object self\n @param list of branches - list what have lists of layers\n @return None\n '''\n def __init__(self, branches):\n self.branches = branches\n\n '''\n This function has be called when network model\n is being formed and it randomize kernel.\n it also defines what the output shape will be\n\n @param object self\n @param array inputshape - shape of input array\n @return array - shape of output array\n '''\n def __create__(self, inputshape):\n self.shape = inputshape[:]\n self.outshape = []\n realOutSahpe = []\n\n for branch in self.branches:\n out = inputshape[:]\n for layer in branch:\n out = layer.__create__(out)\n realOutSahpe = out\n self.outshape.append(out[0])\n \n realOutSahpe[0] = np.sum(self.outshape)\n return realOutSahpe\n\n '''\n This function has be called when network model do prediction.\n It do prediction with inputs and return predicted values\n\n @param object self\n @param numpy array inputs - array with input data with correct shape\n @return numpy array - predicted values\n '''\n def __forward__(self, inputs):\n outputs = []\n\n for branch in self.branches:\n out = inputs[:]\n for layer in branch:\n out = layer.__forward__(out)\n outputs.append(out)\n\n return np.concatenate(outputs)\n \n '''\n This function has be called when network model do backpropagation learning.\n It correct weights by error. It calc error of previous layer too.\n\n @param object self\n @param numpy array inputs - array with input data with correct shape\n @param numpy array output - array with output data (what layer predicted) with correct shape\n @param numpy array fail - array with fail (base: target - output) with correct shape\n @param float rate - rate value (size of correction jump)\n @return numpy array - error of previous layer\n '''\n def __backprop__(self, inputs, output, fail, rate):\n nextfail = []\n\n # first do forward\n outputs = []\n\n for branch in self.branches:\n outputs.append([inputs[:]])\n for layer in branch:\n outputs[-1].append(\n layer.__forward__(outputs[-1][-1])\n )\n\n start = 0\n for i in range(len(self.branches)): \n # split fail to branches\n localfail = fail[ start : start + self.outshape[i] ]\n start += self.outshape[i]\n\n for j in range(len(self.branches[i]) - 1, -1, -1):\n if hasattr(self.branches[i][j], '__backprop__'):\n localfail = self.branches[i][j].__backprop__(outputs[i][j], outputs[i][j + 1], localfail, rate)\n\n nextfail.append(localfail)\n\n return np.sum(nextfail, axis = 0) / len(self.branches)\n\n '''\n This function has be called when you what randomly evolute layer.\n It evolute every layer in every branch \n\n @param object self\n @param rate float - range of random number\n @return none\n '''\n def __evolute__(self, rate = 0.5):\n for branch in self.branches:\n for layer in branch:\n if hasattr(layer, '__evolute__'):\n layer.__evolute__(rate)\n\n","sub_path":"PSNN/layers/concat.py","file_name":"concat.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"652020521","text":"__author__ = 'dev.with.fun@gmail.com'\n\"\"\" Module to test chat repository\n\"\"\"\n\nfrom django.test import TestCase\nfrom chat.models import ChatBody\nfrom chat.repository import * \n\nclass RepositoryTestCase(TestCase):\n \"\"\" Server repository test case\n \"\"\"\n def test_upsert_chat_body(self):\n \"\"\" Summary line\n \n Method to test 'upsert chat body' logic\n \"\"\"\n # check if no chat bodies initially\n self.assertEquals(0, len(list(ChatBody.objects.all())))\n \n # insert new chat body\n upsert_chat_body(nickname = 'nick')\n \n # check if new body exists\n self.assertEquals(1, len(list(ChatBody.objects.all())))\n chat_body = ChatBody.objects.filter(nickname = 'nick')\n self.assertIsNotNone(chat_body)\n \n # update existing body\n upsert_chat_body(nickname = 'nick', login_id = '1', check_id = '2')\n self.assertEquals(1, len(list(ChatBody.objects.all())))\n chat_body = ChatBody.objects.get(nickname = 'nick')\n self.assertEquals('1', chat_body.login_id)\n self.assertEquals('2', chat_body.check_id)\n \n def test_remove_chat_body(self):\n \"\"\" Summary line\n \n Method to test 'remove chat body' logic\n \"\"\"\n \n # check if no chat bodies initially\n self.assertEquals(0, len(list(ChatBody.objects.all())))\n \n # insert new chat bodies\n upsert_chat_body(nickname = 'nick1')\n upsert_chat_body(nickname = 'nick2')\n \n # remove inserted body\n remove_chat_body(nickname = 'nick1')\n \n # check body with removed nickname doesn't exist\n self.assertEquals(1, len(list(ChatBody.objects.all())))\n chat_body = ChatBody.objects.get(nickname = 'nick2')\n self.assertIsNotNone(chat_body)\n \n # remove body again\n remove_chat_body(nickname = 'nick1')\n # check that everything is still ok\n self.assertEquals(1, len(list(ChatBody.objects.all())))\n \n def test_get_allbodies(self):\n \"\"\" Summary line\n \n Method to test 'get all chat bodies' logic\n \"\"\"\n \n # insert new chat bodies\n upsert_chat_body(nickname = 'nick1', login_id = '1')\n upsert_chat_body(nickname = 'nick2', )\n \n self.assertEquals(2, len(get_all_chat_bodies()))\n \n def test_get_chat_body_by_id(self):\n \"\"\" Summary line\n \n Method to test 'get chat body id' logic\n \"\"\"\n # insert new chat bodies\n upsert_chat_body(nickname = 'nick', login_id = '1')\n # get body\n body = get_chat_body_by_id(nickname = 'nick')\n # verify body\n self.assertIsNotNone(body)","sub_path":"chat/test_repository.py","file_name":"test_repository.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"107143995","text":"import uvicorn as uvicorn\nfrom fastapi import FastAPI\nfrom starlette.middleware.cors import CORSMiddleware\nimport numpy as np\n\n\nfrom new_model import new_model\nfrom Crime import Crime, Csv_Data\nimport pickle\nfrom Crime import Crime_Wo_Districts\n\napp = FastAPI()\norigins = ['*']\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\ninput = open(\"model.pkl\", \"rb\")\nmodel = pickle.load(input)\ninput = open(\"user_model.pkl\", \"rb\")\nnew_model = pickle.load(input)\n\npoints = [\n {\n \"name\": 'south',\n \"lat\": 24.8605,\n \"lng\": 67.0261\n },\n {\n # // east\n \"name\": 'east',\n \"lat\": 24.8844,\n \"lng\": 67.1443\n },\n {\n # // west\n \"name\": 'west',\n \"lat\": 24.8829,\n \"lng\": 66.9748\n },\n {\n # // central\n \"name\": 'central',\n \"lat\": 24.9313,\n \"lng\": 67.0374\n },\n {\n # // malir\n \"name\": 'malir',\n \"lat\": 25.0960,\n \"lng\": 67.1871\n }\n]\n\n\n@app.get('/')\ndef index():\n return {\"message\": \"hello\"}\n\n\n@app.get('/{name}')\ndef get_name(name: str):\n return {\"message\": \"hello \" + name}\n\n\n@app.post('/predict')\ndef predict_rate(data: Crime):\n data = data.dict()\n print(data)\n year = data['year']\n month = data['month']\n area1 = data['area1']\n area2 = data['area2']\n crimeType = data['crimeType']\n pre = model.predict([[year, month, area1, area2, crimeType]])\n return {\n 'year': str(year),\n 'month': str(month),\n 'area1': str(area1),\n 'area2': str(area2),\n 'crimeType': str(crimeType),\n 'prediction': str(pre),\n }\n\n\n@app.post('/predicts')\ndef predict_rate_of_different_districts(data: Crime_Wo_Districts):\n data = data.dict()\n pres = []\n year = data['year']\n month = data['month']\n crimeType = data['crimeType']\n for i in range(0, 5):\n area1 = points[i].get(\"lat\")\n area2 = points[i].get(\"lng\")\n print(area1)\n pres.append(model.predict([[year, month, area1, area2, crimeType]]))\n print(np.asfarray(model.predict([[year, month, area1, area2, crimeType]]), float))\n\n return {\n 'year': str(year),\n 'month': str(month),\n 'crimeType': str(crimeType),\n 'prediction': str(pres),\n 'south_prediction': str(pres[0]),\n 'east_prediction': str(pres[1]),\n 'west_prediction': str(pres[2]),\n 'central_prediction': str(pres[3]),\n 'malir_prediction': str(pres[4]),\n }\n\n@app.post('/userpredicts')\ndef User_predict(data: Crime_Wo_Districts):\n data = data.dict()\n pres = []\n year = data['year']\n month = data['month']\n crimeType = data['crimeType']\n for i in range(0, 5):\n area1 = points[i].get(\"lat\")\n area2 = points[i].get(\"lng\")\n print(area1)\n pres.append(new_model.predict([[year, month, area1, area2, crimeType]]))\n print(np.asfarray(new_model.predict([[year, month, area1, area2, crimeType]]), float))\n\n return {\n 'year': str(year),\n 'month': str(month),\n 'crimeType': str(crimeType),\n 'prediction': str(pres),\n 'south_prediction': str(pres[0]),\n 'east_prediction': str(pres[1]),\n 'west_prediction': str(pres[2]),\n 'central_prediction': str(pres[3]),\n 'malir_prediction': str(pres[4]),\n }\n\n@app.post('/csvupload')\ndef csvupload_train(data: Csv_Data):\n data.data.pop(0)\n acc = new_model(data.data)\n print('accuracy of ur model ', acc)\n if acc>0.1:\n return {\n \"accuracy\": str(acc),\n \"upload\": \"successful\",\n }\n else:\n return {\n \"accuracy\": str(acc),\n \"upload\": \"failed\",\n }\n\n\nif __name__ == '__main__':\n uvicorn.run(app, host='127.0.0.1', port=8000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"306579260","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\ndef plot():\n types = [\"dataset_number\", \"num_dataset_to_use\", \"train_accuracy\", \"test_accuracy\", \"train_time\", \"test_time\", \"batch_size\", \"epoch\", \"num_hidden\"]\n matrix = []\n\n reader = csv.reader(open(\"data/8_bar/rnn_results_dataset_sizes.csv\", \"rt\"), delimiter=',')\n for index, row in enumerate(reader):\n for i in range(len(types)):\n if index == 0:\n continue\n elif len(row) > 0:\n if len(matrix) <= i:\n matrix.append([])\n y = row[i]\n matrix[i].append(y)\n print(matrix)\n\n matrix = np.array(matrix)\n\n start_type = 2\n end_type = 4\n x_column = 1\n for i in range(start_type, end_type):\n x = matrix[x_column,1:]\n y = matrix[i,1:]\n plt.plot(x, y)\n plt.xscale('log')\n plt.legend(types[start_type:end_type], loc='lower right')\n plt.show()\n\nplot()\n","sub_path":"ML/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"135072082","text":"#!/usr/bin/python3\n\n# Class - A user-defined prototype for an object that defines a set of attributes that characterise any object of the class\n# Class variable - A variable shared by all instances of a class\n# Data member - attribute\n# Function overloading - The assignment of more than one behaviour to a particular function\n# Instance variable - Created inside a method\n# Inheritance - Transfer the characteristics of a class to other calsses that are derived from it\n# Instanciation - Creation of an object of a certain class. Eg class X y = X\n# Method - Function defined inside of a class\n# Object - A unique instance of a data structure in memory, defined by its class\n# Operator overloading - The assignment of more than one function to a particular operator\n\n # hasattr - Returns true if attribute exists\n # getattr - Returns the value of an attribute\n # setattr - Set attribute\n # delattr - Delete attribute\n\nclass ClassName:\n 'Optional class documentation string'\n\n\nclass Employee:\n 'Common base class for all employees'\n empCount = 0 # class variable (attribute). Global for all instances.\n\n def __init__(self, name, salary): # Initialiser. Built in method with 'self' argument (does not have to be called 'self')\n\t\t\t\t\t# self is like a memory manager and tracks each instance creation\n self.name = name\n self.salary = salary\n Employee.empCount += 1\t\t# Class name in from of attribute\n\n def displayCount(self):\n print (\"Total employees: %d\" %Employee.empCount)\n\n def displayEmployee(self):\n print (\"Name: \", self.name, \", Salary: \", self.salary)\n\nprint (\"Employee.__doc__:\", Employee.__doc__)\nprint (\"Employee.__name__:\", Employee.__name__)\n#print (\"Employee.__modules__:\", Employee.__modules__)\nprint (\"Employee.__bases__:\", Employee.__bases__)\nprint (\"Employee.__dict__:\", Employee.__dict__)\nprint (\"\")\nemp1 = Employee(\"Steve\", 100000)\nemp1.displayEmployee()\nemp1.displayCount()\n","sub_path":"python/20_object_orientated_programming.py","file_name":"20_object_orientated_programming.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"10263749","text":"from contextlib import contextmanager\n\nimport pyodbc\nimport time\n\nimport dbt.compat\nimport dbt.exceptions\nfrom dbt.adapters.base import Credentials\nfrom dbt.adapters.sql import SQLConnectionManager\n\nfrom dbt.logger import GLOBAL_LOGGER as logger\n\nAZUREDW_CREDENTIALS_CONTRACT = {\n 'type': 'object',\n 'additionalProperties': False,\n 'properties': {\n 'driver': {\n 'type': 'string',\n },\n 'host': {\n 'type': 'string',\n },\n 'database': {\n 'type': 'string',\n },\n 'schema': {\n 'type': 'string',\n },\n 'UID': {\n 'type': 'string',\n },\n 'PWD': {\n 'type': 'string',\n },\n 'authentication': {\n 'type': 'string',\n 'enum': ['ActiveDirectoryIntegrated','ActiveDirectoryMSI','ActiveDirectoryPassword','SqlPassword','TrustedConnection']\n }\n },\n 'required': ['driver','host', 'database', 'schema','authentication'],\n}\n\n\nclass AzureDWCredentials(Credentials):\n SCHEMA = AZUREDW_CREDENTIALS_CONTRACT;\n ALIASES = {\n 'user': 'UID'\n , 'username': 'UID'\n , 'pass': 'PWD'\n , 'password': 'PWD'\n , 'server': 'host'\n }\n\n @property\n def type(self):\n return 'azuredw'\n\n def _connection_keys(self):\n # return an iterator of keys to pretty-print in 'dbt debug'\n # raise NotImplementedError\n return ('server', 'database', 'schema', 'UID', 'authentication',)\n\n\nclass AzureDWConnectionManager(SQLConnectionManager):\n TYPE = 'azuredw'\n\n @contextmanager\n def exception_handler(self, sql):\n try:\n yield\n\n except pyodbc.DatabaseError as e:\n logger.debug('Database error: {}'.format(str(e)))\n\n try:\n # attempt to release the connection\n self.release()\n except pyodbc.Error:\n logger.debug(\"Failed to release connection!\")\n pass\n\n raise dbt.exceptions.DatabaseException(\n dbt.compat.to_string(e).strip())\n\n except Exception as e:\n logger.debug(\"Error running SQL: %s\", sql)\n logger.debug(\"Rolling back transaction.\")\n self.release()\n if isinstance(e, dbt.exceptions.RuntimeException):\n # during a sql query, an internal to dbt exception was raised.\n # this sounds a lot like a signal handler and probably has\n # useful information, so raise it without modification.\n raise\n\n raise dbt.exceptions.RuntimeException(e)\n\n def add_query(self, sql, auto_begin=True, bindings=None,\n abridge_sql_log=False):\n \n connection = self.get_thread_connection()\n if auto_begin and connection.transaction_open is False:\n self.begin()\n\n logger.debug('Using {} connection \"{}\".'\n .format(self.TYPE, connection.name))\n\n with self.exception_handler(sql):\n if abridge_sql_log:\n logger.debug('On %s: %s....', connection.name, sql[0:512])\n else:\n logger.debug('On %s: %s', connection.name, sql)\n pre = time.time()\n\n cursor = connection.handle.cursor()\n\n # pyodbc does not handle a None type binding!\n if bindings is None:\n cursor.execute(sql)\n else:\n logger.debug(f'bindings set as {bindings}')\n cursor.execute(sql, bindings)\n\n logger.debug(\"SQL status: %s in %0.2f seconds\",\n self.get_status(cursor), (time.time() - pre))\n\n return connection, cursor\n\n @classmethod\n def open(cls, connection):\n\n if connection.state == 'open':\n logger.debug('Connection is already open, skipping open.')\n return connection\n\n credentials = connection.credentials\n \n\n MASKED_PWD=credentials.PWD[0] + (\"*\" * len(credentials.PWD))[:-2] + credentials.PWD[-1]\n try:\n con_str = []\n con_str.append(f\"DRIVER={{{credentials.driver}}}\")\n con_str.append(f\"SERVER={credentials.host}\")\n con_str.append(f\"Database={credentials.database}\")\n\n if credentials.authentication == 'TrustedConnection':\n con_str.append(\"trusted_connection=yes\")\n else:\n con_str.append(f\"AUTHENTICATION={credentials.authentication}\")\n con_str.append(f\"UID={credentials.UID}\")\n con_str.append(f\"PWD={credentials.PWD}\")\n\n con_str_concat = ';'.join(con_str)\n con_str[-1] = f\"PWD={MASKED_PWD}\"\n con_str_masked = ';'.join(con_str)\n\n logger.debug(f'Using connection string: {con_str_masked}')\n del con_str\n\n handle = pyodbc.connect(con_str_concat, autocommit=True)\n\n connection.state = 'open'\n connection.handle = handle\n logger.debug(f'Connected to db: {credentials.database}')\n \n except pyodbc.Error as e:\n logger.debug(f\"Could not connect to db: {e}\")\n\n connection.handle = None\n connection.state = 'fail'\n\n raise dbt.exceptions.FailedToConnectException(str(e))\n\n return connection\n\n def cancel(self, connection):\n pass\n\n @classmethod\n def get_credentials(cls, credentials):\n return credentials\n\n @classmethod\n def get_status(cls, cursor):\n # return cursor.statusmessage\n return 'OK'\n\n def execute(self, sql, auto_begin=False, fetch=False):\n _, cursor = self.add_query(sql, auto_begin)\n status = self.get_status(cursor)\n if fetch:\n table = self.get_result_from_cursor(cursor)\n else:\n table = dbt.clients.agate_helper.empty_table()\n return status, table\n\n def add_begin_query(self):\n pass\n # return self.add_query('BEGIN TRANSACTION', auto_begin=False)\n\n def add_commit_query(self):\n pass\n # return self.add_query('COMMIT', auto_begin=False)\n\n @classmethod\n def get_result_from_cursor(cls, cursor):\n data = []\n column_names = []\n\n if cursor.description is not None:\n column_names = [col[0] for col in cursor.description]\n ## azure likes to give us empty string column names for scalar queries\n for i, col in enumerate(column_names):\n if col == '':\n column_names[i] = f'Column{i+1}'\n logger.debug(f'substituted empty column name in position {i} with `Column{i+1}`') \n rows = cursor.fetchall()\n data = cls.process_results(column_names, rows)\n try:\n return dbt.clients.agate_helper.table_from_data(data, column_names)\n except Exception as e:\n logger.debug(f'failure with rows: {rows}')\n logger.debug(f'Failure with data: {data}')\n logger.debug(f'Failure with column_names: {column_names}')\n raise e\n\n @classmethod\n def process_results(cls, column_names, rows):\n return [dict(zip(column_names, row)) for row in rows]\n","sub_path":"dbt/adapters/azuredw/connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"164314754","text":"import numpy as np\n\n\ndef huber_loss(a, delta):\n\t# np.where returns second arg if first arg evaluates to true. else returns third arg\n\tlosses = np.where(abs(a) <= delta, 1/2*(a**2), delta*(abs(a) - delta/2))\n\treturn losses\n\ndef train_huber(X, targets, delta):\n lr = 0.01 ## learning rate\n\n '''Input : X, targets [data and outcome], delta value\n Output : w,b \n '''\n \n epoch = 1\n max_epochs = 70\n # initialize my weights and bias to 0\n weights = np.zeros([4])\n bias = 0.0\n \n for epoch in range(max_epochs):\n\t # get predicted value of y\n\t y_pred = np.dot(X, weights) + bias\n\t a = y_pred-targets # shape (100, )\n\t \n\t # now since we are performing full batch we add all the losses and perform gradient descent\n\t losses = huber_loss(a, delta)\n\t total_loss = np.sum(losses)\n\t print('---------------------------------------------------------')\n\t print('Epoch : ', epoch, ' | Loss : ', total_loss)\n\t \n\t # calculate gradient of loss w.r.t. weights\n\t dLdy = a\n\t # since np.where can evaluate one condition evaluating to True or False, we will make of copy of 'a' called 'dLdy'. then apply resulants to 'dLdy' based on each condition applied on 'a'\n\t dLdy = np.where(abs(a) <= delta, a, dLdy) # condition 1 : if abs(a) <= delta, then return a\n\t dLdy = np.where(a > delta, delta, dLdy) # condition 2 : if a > delta, then return delta\n\t dLdy = np.where(a < -delta, -delta, dLdy) # condition 3 : if a < -delta, then return -delta\n\t dLdw = dLdy.dot(X)\n\n\t # update the weights\n\t weights = weights - (lr * dLdw) \n\t print('weights : ', weights)\n\n\t # calculate gradient of loss w.r.t. bias\n\t # as calculated the bias is the same as dLdy as dydb = 1, so, \n\t dLdb = np.sum(dLdy)\n\t bias = bias - (lr * dLdb)\n\t print('bias : ', bias)\n\n return weights, bias\n \n \n\n# Ground truth weights and bias used to generate toy data\nw_gt = [1, 2, 3, 4] # shape (4, ), these should be my weights after training \nb_gt = 5 # this should be my bias after training\n\n# Generate 100 training examples with 4 features\nX = np.random.randn(100, 4) # shape (100, 4)\ntargets = np.dot(X, w_gt) + b_gt # shape (100, )\n\n\n# Gradient descent\nw, b = train_huber(X, targets, delta=2)\n","sub_path":"HW2/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"473731044","text":"#! python3\n\n\"\"\"\nOn-Board control application for the Mars Rover (non-hardware)\n\"\"\"\n\nfrom mars_control import MarsControlMessage\nfrom time import sleep\nimport threading\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')\n# logging.disable(logging.INFO) # Uncomment to disable log messages\n\n\n# FUNCTIONS\ndef execute_command():\n while(mc_server.keepalive):\n if mc_server.switch_1:\n logging.info('Left drive enabled')\n else:\n logging.info('Left drive disabled')\n if mc_server.switch_2:\n logging.info('Right drive enabled')\n else:\n logging.info('Right drive disabled')\n if mc_server.switch_3:\n logging.info('Forward movement')\n else:\n logging.info('Reverse movement')\n if mc_server.switch_4:\n logging.info('Stepper ON')\n else:\n logging.info('Stepper OFF')\n if mc_server.button_1:\n logging.info('Sample collection')\n else:\n logging.info('No sample collection in progress')\n if mc_server.button_2:\n logging.info('Unload samples')\n else:\n logging.info('No unload in progress')\n logging.info('loop end'.center(20, '-'))\n sleep(5)\n\n\ndef adc_simulator():\n for n in range(10):\n mc_server.batteryv -= float(n)/287\n mc_server.lightsen += float(n)/142\n sleep(3)\n\n\nmc_server = MarsControlMessage()\nmc_server.create_socket()\n\n# Initial values\nmc_server.lightsen = 0.78\nmc_server.batteryv = 3.21\n\n\nt1 = threading.Thread(target=mc_server.serv)\nt2 = threading.Thread(target=execute_command)\nt3 = threading.Thread(target=adc_simulator)\n\nt1.start()\nt2.start()\nt3.start()\n\nt1.join()\nt2.join()\nt3.join()\n\nsleep(1)\nmc_server.close()\n","sub_path":"onboard_non-hw.py","file_name":"onboard_non-hw.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"131152445","text":"from commands.printing import *\nfrom collections import OrderedDict\n\n\nclass MetaBIOSUnencryptedWithoutLVMWithoutSwapFile(type):\n def __str__(self):\n return \"BIOS unencrypted without LVM and without Swapfile\"\n\n\nclass BIOSUnencryptedWithoutLVMWithoutSwapFile(metaclass=MetaBIOSUnencryptedWithoutLVMWithoutSwapFile):\n\n partitions = OrderedDict()\n\n def __init__(self):\n pass\n\n @staticmethod\n def explanation() -> str:\n return \"Requires at least one partition with bootflag.\"\n\n @staticmethod\n def mount():\n clear()\n\n user_choice = []\n\n while len(user_choice) != 1:\n user_choice = choose_out_of_list(\"Choose the root partition.\", get_partitions())\n\n BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions[\"/\"] = user_choice[0]\n\n user_choice = []\n\n if len(list(set(get_partitions()) - set(list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.values())))) >\\\n 0:\n while len(user_choice) != 1:\n user_choice = choose_out_of_list(\"Do you want to define any other partitions? E.g. /boot or /home\",\n [\"Yes\", \"No\"])\n\n else:\n user_choice = [\"No\"]\n\n while user_choice[0] == \"Yes\":\n user_choice = \"\"\n\n while (user_choice == \"\") or (user_choice[0] != \"/\") or \\\n (user_choice.strip() in list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.keys())) or \\\n (len(user_choice.split()) > 1):\n clear()\n if user_choice != \"\":\n print(\"That was not a valid name.\")\n print(\"\")\n user_choice = str(input(\"Enter the name of the partition. E.g. /boot or /home: \"))\n\n user_choice_1 = []\n\n while len(user_choice_1) != 1:\n user_choice_1 = \\\n choose_out_of_list(\"Choose the partition.\",\n list(set(get_partitions()) -\n set(list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.values()))))\n\n BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions[user_choice.strip()] = user_choice_1[0]\n\n user_choice = []\n\n if len(list(set(get_partitions()) - set(list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.values()\n )))) > 0:\n while len(user_choice) != 1:\n user_choice = choose_out_of_list(\"Do you want to define any other partitions? E.g. /boot or /home\",\n [\"Yes\", \"No\"])\n\n else:\n user_choice = [\"No\"]\n\n devices = list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.values())\n partition_names = list(BIOSUnencryptedWithoutLVMWithoutSwapFile.partitions.keys())\n\n for i in range(0, len(devices)):\n if shell([\"mkfs.ext4 -F \" + devices[i]], True, True)[0] != 0:\n print(\"There went something wrong with the formatting!\")\n input(\"Press enter to exit.\")\n clear()\n quit()\n\n if shell([\"mount \" + devices[0] + \" /mnt\"], True, True)[0] != 0:\n print(\"There went something wrong with the mounting!\")\n input(\"Press enter to exit.\")\n clear()\n quit()\n\n for i in range(1, len(partition_names)):\n if shell([\"mkdir -p /mnt\" + partition_names[i]], True, True)[0] != 0:\n print(\"There went something wrong with the creating of directories!\")\n input(\"Press enter to exit.\")\n clear()\n quit()\n\n for i in range(1, len(devices)):\n if shell([\"mount \" + devices[i] + \" /mnt\" + partition_names[i]], True, True)[0] != 0:\n print(\"There went something wrong with the mounting!\")\n input(\"Press enter to exit.\")\n clear()\n quit()\n\n clear()\n","sub_path":"src/partitioning/pre_chroot.py","file_name":"pre_chroot.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"487403185","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom scipy import sparse\nimport pickle\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom NN_utils import nn_pred\nfrom RawData_functions import label_2_matrix, remove_mt_rp, input_formatting, select_genes\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', type=str, help='Directory of input file', default=None)\n parser.add_argument('--input_is_csv', type=str, help='If set to True, the input will be formatted before running', default=False)\n parser.add_argument('--output', type=str, help='Directory of output file', default=None)\n parser.add_argument('--predictor', type=str, help='Which predictor to use, e.g. T_cell', default=None)\n args = parser.parse_args()\n input = args.input\n output = args.output\n model_tag = args.predictor # Tag of the pre-trained model\n\n ref_genes, _, _, _, _ = pickle.load(open('data/Input_parameter_'+model_tag+\".pickle\", \"rb\"))\n\n ###################################################\n # Load testing data\n ###################################################\n # Format conversion\n if args.input_is_csv:\n input_formatting(input, input+'.pickle')\n data = pickle.load(open(input+'.pickle', 'rb'))\n data[0], _ = select_genes(data[0], data[1], ref_genes)\n else:\n data = pickle.load(open(input, 'rb'))\n # Add dummy parameters\n if sparse.issparse(data[0]):\n data[0] = data[0].toarray()\n _, _, _, _, w_output = pickle.load(open('data/Input_parameter_'+model_tag+\".pickle\", \"rb\"))\n lab = [0] * len(data[0])\n lab[0] = 1\n lab_mat = label_2_matrix(lab_list=range(w_output), label=lab)\n data = data + [lab_mat] + [list(range(len(lab)))]\n # data[0], data[1] = remove_mt_rp(data[0], data[1])\n # data[0] = preprocessing.scale(data[0], axis=1)\n\n ###################################################\n # Make predictions\n ###################################################\n\n pred_prob, pred_lab = nn_pred(model_tag, data)\n if pred_prob.shape[1] == 2: # Binary prediction\n print('Percentage of predicted %s:\\t%f' % (model_tag, np.sum(pred_lab==1)/len(pred_lab)))\n df = pd.DataFrame({'Pred_prob': pred_prob[:, 1], 'Pred_lab': pred_lab})\n else:\n row_max = np.max(pred_prob, axis=1).reshape(-1,1)\n print('Percentage of prediction:\\n', np.mean((pred_prob == row_max)*1, axis=0))\n df = pd.DataFrame(np.append(pred_prob, pred_lab.reshape(-1,1), axis=1))\n df.to_csv(output)\n","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"479276999","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 18 18:10:04 2014\n\n@author: Kyle Ellefsen\n\"\"\"\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport global_vars as g\nimport pyqtgraph as pg\nfrom skimage.draw import polygon, line\nimport numpy as np\nfrom trace import roiPlot\nimport os\nimport time\n\n\nclass ROI(QWidget):\n \" This is an ROI. I need to document it better.\"\n translated=Signal()\n translate_done=Signal()\n deleteSignal=Signal()\n plotSignal=Signal()\n kind='freehand'\n def __init__(self,window,x,y):\n QWidget.__init__(self)\n self.window=window\n self.window.currentROI=self\n self.view=self.window.imageview.view\n self.path=QPainterPath(QPointF(x,y))\n self.pathitem=QGraphicsPathItem(self.view)\n self.color=Qt.yellow\n self.pathitem.setPen(QPen(self.color))\n self.pathitem.setPath(self.path)\n self.view.addItem(self.pathitem)\n self.mouseIsOver=False\n self.createActions()\n self.linkedROIs=[]\n self.beingDragged=False\n self.window.deleteButtonSignal.connect(self.deleteCurrentROI)\n self.window.closeSignal.connect(self.delete)\n self.colorDialog=QColorDialog()\n self.colorDialog.colorSelected.connect(self.colorSelected)\n\n def extend(self,x,y):\n self.path.lineTo(QPointF(x,y))\n self.pathitem.setPath(self.path)\n\n def deleteCurrentROI(self):\n if self.window.currentROI is self:\n self.delete()\n\n def getTraceWindow(self):\n trace_with_roi = [t for t in g.m.traceWindows if t.hasROI(self)]\n if len(trace_with_roi) == 1:\n return trace_with_roi[0]\n return False\n\n def delete(self):\n for roi in self.linkedROIs:\n roi.linkedROIs.remove(self)\n if self in self.window.rois:\n self.window.rois.remove(self)\n self.window.currentROI=None\n self.view.removeItem(self.pathitem)\n trace = self.getTraceWindow()\n if trace:\n a=set([r['roi'] for r in trace.rois])\n b=set(self.window.rois)\n if len(a.intersection(b))==0:\n trace.indexChanged.disconnect(self.window.setIndex)\n trace.removeROI(self)\n def getPoints(self):\n points=[]\n for i in np.arange(self.path.elementCount()):\n e=self.path.elementAt(i)\n x=int(np.round(e.x)); y=int(np.round(e.y))\n if len(points)==0 or points[-1]!=(x,y):\n points.append((x,y))\n self.pts=points\n self.minn=np.min(np.array( [np.array([p[0],p[1]]) for p in self.pts]),0)\n return self.pts\n def getArea(self):\n self.getMask()\n return len(self.mask)\n #cnt=np.array([np.array([np.array([p[1],p[0]])]) for p in self.pts ])\n #area = cv2.contourArea(cnt)\n #return area\n def drawFinished(self):\n self.path.closeSubpath()\n self.draw_from_points(self.getPoints()) #this rounds all the numbers down\n if self.getArea()<1:\n self.delete()\n self.window.currentROI=None\n else:\n self.window.rois.append(self)\n self.getMask()\n\n def mouseOver(self,x,y):\n if self.mouseIsOver is False and self.contains(x,y):\n self.mouseIsOver=True\n self.pathitem.setPen(QPen(Qt.red))\n elif self.mouseIsOver and self.contains(x,y) is False:\n self.mouseIsOver=False\n self.pathitem.setPen(QPen(self.color))\n\n def contextMenuEvent(self, event):\n self.menu = QMenu(self)\n trace = self.getTraceWindow()\n if trace:\n self.menu.addAction(self.unplotAct)\n else:\n self.menu.addAction(self.plotAct)\n self.menu.addAction(self.plotAllAct)\n self.menu.addAction(self.colorAct)\n self.menu.addAction(self.copyAct)\n self.menu.addAction(self.deleteAct)\n self.menu.addAction(self.saveAct)\n self.menu.exec_(event.screenPos().toQPoint())\n\n def plot(self):\n roiPlot(self)\n g.m.currentTrace.indexChanged.connect(self.window.setIndex)\n self.plotSignal.emit()\n\n def unplot(self):\n trace = self.getTraceWindow()\n trace.indexChanged.disconnect(self.window.setIndex)\n trace.removeROI(self)\n\n def copy(self):\n g.m.clipboard=self\n\n def save(self,filename):\n text=''\n for roi in g.m.currentWindow.rois:\n pts=roi.getPoints()\n text+=type(roi).kind+'\\n'\n for pt in pts:\n text+=\"{0:<4} {1:<4}\\n\".format(pt[0],pt[1])\n text+='\\n'\n f=open(filename,'w')\n f.write(text)\n f.close()\n def changeColor(self):\n self.colorDialog.open()\n \n def colorSelected(self, color):\n if color.isValid():\n self.color=QColor(color.name())\n self.pathitem.setPen(QPen(self.color))\n self.translate_done.emit()\n\n def save_gui(self):\n filename=g.m.settings['filename']\n if filename is not None and os.path.isfile(filename):\n filename= QFileDialog.getOpenFileName(g.m, 'Save ROI', filename, \"*.txt\")\n else:\n filename= QFileDialog.getOpenFileName(g.m, 'Save ROI', '', '*.txt')\n filename=str(filename)\n if filename != '':\n self.save(filename)\n else:\n g.m.statusBar().showMessage('No File Selected')\n \n def createActions(self):\n self.plotAct = QAction(\"&Plot\", self, triggered=self.plot)\n self.plotAllAct = QAction('&Plot All', self, triggered=lambda : [roi.plot() for roi in self.window.rois])\n self.colorAct = QAction(\"&Change Color\",self,triggered=self.changeColor)\n self.unplotAct = QAction(\"&un-Plot\", self, triggered=self.unplot)\n self.copyAct = QAction(\"&Copy\", self, triggered=self.copy)\n self.deleteAct = QAction(\"&Delete\", self, triggered=self.delete)\n self.saveAct = QAction(\"&Save\",self,triggered=lambda : self.save_gui)\n \n def contains(self,x,y):\n return self.path.contains(QPointF(x,y))\n def translate(self,difference,startpt):\n self.path.translate(difference)\n self.pathitem.setPath(self.path)\n for roi in self.linkedROIs:\n roi.draw_from_points(self.getPoints())\n roi.translated.emit()\n self.translated.emit()\n def finish_translate(self):\n for roi in self.linkedROIs:\n roi.draw_from_points(self.getPoints())\n roi.translate_done.emit()\n roi.beingDragged=False\n self.draw_from_points(self.getPoints())\n self.getMask()\n self.translate_done.emit()\n self.beingDragged=False\n def draw_from_points(self,pts):\n self.pts=pts\n self.path=QPainterPath(QPointF(pts[0][0],pts[0][1]))\n for i in np.arange(len(pts)-1)+1: \n self.path.lineTo(QPointF(pts[i][0],pts[i][1]))\n self.pathitem.setPath(self.path)\n \n def getMask(self):\n pts=self.pts\n tif=self.window.image\n x=np.array([p[0] for p in pts])\n y=np.array([p[1] for p in pts])\n nDims=len(tif.shape)\n if nDims==4: #if this is an RGB image stack\n tif=np.mean(tif,3)\n mask=np.zeros(tif[0,:,:].shape,np.bool)\n elif nDims==3:\n mask=np.zeros(tif[0,:,:].shape,np.bool)\n if nDims==2: #if this is a static image\n mask=np.zeros(tif.shape,np.bool)\n \n xx,yy=polygon(x,y,shape=mask.shape)\n mask[xx,yy]=True\n pts_plus=np.array(np.where(mask)).T\n for pt in pts_plus:\n if not self.path.contains(QPointF(pt[0],pt[1])):\n mask[pt[0],pt[1]]=0\n self.minn=np.min(np.array( [np.array([p[0],p[1]]) for p in self.pts]),0)\n self.mask=np.array(np.where(mask)).T-self.minn\n \n def getTrace(self,bounds=None,pts=None):\n ''' bounds are two points in time. If bounds is not None, we only calculate values between the bounds '''\n tif=self.window.image\n if len(tif.shape)==4: #if this is an RGB image stack\n tif=np.mean(tif,3)\n mx,my=tif[0,:,:].shape\n pts=self.mask+self.minn\n pts=pts[(pts[:,0]>=0)*(pts[:,0]=0)*(pts[:,1]len(tif): bounds[1]=len(tif)\n if bounds[0]>len(tif) or bounds[1]<0:\n return np.array([])\n mn=np.zeros(bounds[1]-bounds[0])\n for t in np.arange(bounds[0],bounds[1]):\n mn[t-bounds[0]]=np.mean(tif[t,xx,yy]) \n return mn\n \n def link(self,roi):\n '''This function links this roi to another, so a translation of one will cause a translation of the other'''\n self.linkedROIs.append(roi)\n roi.linkedROIs.append(self)\n\nclass ROI_line(ROI):\n kind='line'\n def __init__(self,window,x,y):\n ROI.__init__(self, window,x,y)\n self.kymographAct = QAction(\"&Kymograph\", self, triggered=self.update_kymograph)\n self.kymograph=None\n self.movingPoint=False #either False, 0 or 1\n self.beingDragged=False #either True or False depending on if a translation has been started or not\n def contextMenuEvent(self, event):\n self.menu = QMenu(self)\n if self.getTraceWindow():\n self.menu.addAction(self.unplotAct)\n else:\n self.menu.addAction(self.plotAct)\n self.menu.addAction(self.plotAllAct)\n self.menu.addAction(self.colorAct)\n self.menu.addAction(self.copyAct)\n self.menu.addAction(self.kymographAct)\n self.menu.addAction(self.deleteAct)\n self.menu.addAction(self.saveAct)\n self.menu.exec_(event.screenPos().toQPoint())\n def delete(self):\n ROI.delete(self)\n if self.kymograph is not None:\n self.kymograph.close()\n def update_kymograph(self):\n self.pts=self.getPoints()\n tif=self.window.image\n mt=tif.shape[0]\n x=np.array([p[0] for p in self.pts])\n y=np.array([p[1] for p in self.pts])\n xx,yy=line(x[0],y[0],x[1],y[1])\n mn=np.zeros((mt,len(xx)))\n for t in np.arange(mt):\n mn[t]=tif[t,xx,yy]\n mn=mn.T\n if self.kymograph is None:\n self.createKymograph(mn)\n else:\n self.kymograph.imageview.setImage(mn,autoLevels=False,autoRange=False)\n #self.kymograph.imageview.view.setAspectLocked(lock=True,ratio=mn.shape[1]/mn.shape[0])\n def createKymograph(self,mn):\n from window import Window\n oldwindow=g.m.currentWindow\n name=oldwindow.name+' - Kymograph'\n newWindow=Window(mn,name,metadata=self.window.metadata)\n self.kymograph=newWindow\n self.kymographproxy = pg.SignalProxy(self.translated, rateLimit=3, slot=self.update_kymograph) #This will only update 3 Hz\n self.kymograph.closeSignal.connect(self.deleteKymograph)\n def deleteKymograph(self):\n self.kymographproxy.disconnect()\n self.kymograph.closeSignal.disconnect(self.deleteKymograph)\n self.kymograph=None\n def contains(self,x,y):\n return self.path.intersects(QRectF(x-.5,y-.5,1,1)) #QRectF(x, y, width, height)\n def extend(self,x,y):\n e=self.path.elementAt(0)\n x0=int(np.round(e.x)); y0=int(np.round(e.y))\n self.path=QPainterPath(QPointF(x0,y0))\n self.path.lineTo(QPointF(x,y))\n self.pathitem.setPath(self.path)\n def drawFinished(self):\n self.draw_from_points(self.getPoints()) #this rounds all the numbers down\n if self.path.length()<2:\n self.delete()\n self.window.currentROI=None\n else:\n self.window.rois.append(self)\n def finish_translate(self):\n ROI.finish_translate(self)\n for roi in self.linkedROIs:\n roi.movingPoint=False\n self.movingPoint=False\n def translate(self,difference,startpt):\n ''' For an ROI_line object, this function must translate either one point, the other point, or the entire line, depending on where on the line we start.'''\n pts=self.getPoints() \n if self.beingDragged==False:\n self.beingDragged=True\n d0=np.sqrt(difference.x()**2+difference.y()**2) #this is the difference we have dragged since the last move\n d1=np.sqrt((self.window.x-pts[0][0])**2+(self.window.y-pts[0][1])**2)\n d2=np.sqrt((self.window.x-pts[1][0])**2+(self.window.y-pts[1][1])**2)\n if d1=mx: x2=mx-1\n if y2>=my: y2=my-1\n newtif=tif[:,x1:x2+1,y1:y2+1]\n elif len(tif.shape)==2:\n if x1<0: x1=0\n if y1<0: y1=0\n if x2>=mx: x2=mx-1\n if y2>=my: y2=my-1\n mx,my=tif.shape\n newtif=tif[x1:x2+1,y1:y2+1]\n return Window(newtif,self.window.name+' Cropped',metadata=self.window.metadata)\n \n def translate(self,difference,startpt):\n ''' For an ROI_line object, this function must translate either one point, the other point, or the entire line, depending on where on the line we start.'''\n pts=self.getPoints() \n if self.beingDragged==False:\n self.beingDragged=True\n distances=np.array([np.sqrt((startpt.x()-pts[i][0])**2+(startpt.y()-pts[i][1])**2) for i in np.arange(4)]) #distances away from each point in the rectangle\n closestpt=np.argmin(distances)\n if distances[closestpt] 1:\n for i in xrange(0, len(word)):\n # Get all deletes from the word and add to dictionary as\n # Key:Value :: Deletes:Originals\n wordDelete = word[:i] + word[i + 1:]\n if wordDelete in wordDeletes:\n wordDeletes[wordDelete].append(word)\n else:\n wordDeletes[wordDelete] = [word]\n return wordCount, wordDeletes\n\n\ndef topThree(dictionary):\n \"\"\" This method provides the top three suggestions from com1 dictionary of candidates.\n Using this method is the fastest way to find the maximum value within a list.\n As seen on http://stackoverflow.com/com1/12343826 \"\"\"\n # Get values from dictionary\n values = list(dictionary.values())\n # Get keys from dictionary\n keys = list(dictionary.keys())\n\n # Return = String formatted, key from values at index where values is maximum\n # Then delete that key:value pair\n try:\n suggestion1 = str(keys[values.index(max(values))])\n keys.__delitem__(values.index(max(values)))\n values.__delitem__(values.index(max(values)))\n except:\n suggestion1 = None\n try:\n suggestion2 = str(keys[values.index(max(values))])\n keys.__delitem__(values.index(max(values)))\n values.__delitem__(values.index(max(values)))\n except:\n suggestion2 = None\n try:\n suggestion3 = str(keys[values.index(max(values))])\n except:\n suggestion3 = None\n return suggestion1, suggestion2, suggestion3\n\n\ndef trim3toNone(object):\n \"\"\"This function trims or pads outputs to length 3\"\"\"\n # If more than three, TRIM\n if len(object) > 3:\n del object[3:]\n # If less than three, PAD\n else:\n while len(object) != 3:\n object.append(None)\n return object\n","sub_path":"eureka/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"55051814","text":"import numpy as np\nimport random\nimport math\nimport matplotlib.pyplot as plt\nimport torch\nfrom pyperlin import FractalPerlin2D\nfrom matplotlib.colors import LinearSegmentedColormap\n\nwidth = 1024\nheight = 1024\n\ncolour_list = [\"midnightblue\",\n \"royalblue\",\n \"lightseagreen\",\n \"gold\",\n \"darkgoldenrod\",\n \"forestgreen\",\n \"forestgreen\",\n \"darkgreen\",\n \"saddlebrown\",\n \"dimgrey\",\n \"darkgrey\",\n \"snow\"]\n\nnodes = [0.0, 0.12, 0.2, 0.22, 0.24, 0.3, 0.35, 0.65, 0.68, 0.7, 0.90, 1.0]\n\ncolour_map = LinearSegmentedColormap.from_list(\"Terrain cmap\", list(zip(nodes, colour_list)))\n\n\ndef generate_noise(w, h, n):\n shape = (n, h, w)\n resolutions = [(2 ** i, 2 ** i) for i in range(1, 7)] # lacunarity\n factors = [0.7 ** i for i in range(6)] # persistence\n g_cuda = torch.Generator(device='cuda')\n noise_layer = FractalPerlin2D(shape, resolutions, factors, generator=g_cuda)().cpu().numpy()[0]\n return noise_layer\n\n\ndef generate_poseidon_layer(w, h):\n p_layer = np.ones((h, w), dtype=float)\n conversion_point = random.randint(math.floor(0.7 * w), math.ceil(0.8 * w))\n x = int(0.2 * w)\n shade_fraction = 1 / x\n\n for row in p_layer:\n conversion_point += random.randint(-2, 1)\n shade_level = 1\n for i in range(w):\n if i < conversion_point:\n row[i] = 1\n elif i > conversion_point + x:\n row[i] = 0\n else:\n shade_level -= shade_fraction\n row[i] = shade_level\n\n np.save(\"p_layer.npy\", p_layer)\n plt.imsave(\"p_map.png\", p_layer, cmap='Blues')\n\n\ndef apply_poseidon_layer(noise_layer):\n poseidon_layer = np.load(\"p_layer.npy\")\n output_layer = np.multiply(noise_layer, poseidon_layer)\n\n return output_layer\n\n\ndef complete_map_gen(width, height, colour_map):\n generate_poseidon_layer(width, height)\n noise_layer = generate_noise(width, height, 8)\n normal_layer = (noise_layer / 2) + 0.5\n final_layer = normal_layer ** 0.5\n # final_layer = apply_poseidon_layer(normal_layer)\n np.save(f\"layers.npy\", final_layer)\n plt.imsave(f\"mapped.png\", final_layer, cmap=colour_map)\n\n\ndef read_cmap_file(filename):\n opened_cmap = plt.imread(filename)\n print(opened_cmap)\n\n# complete_map_gen(width, height, colour_map)\nread_cmap_file(\"cmap.png\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"110987632","text":"from Quartz.CoreGraphics import CGEventCreateScrollWheelEvent, CGEventPost, kCGHIDEventTap\nimport time\n\ndef scrollWheelUp(numTicks):\n for i in xrange(1, numTicks):\n time.sleep(.005)\n multiplier = 1 - (float(i) / numTicks)\n speed = 4 * multiplier\n event = CGEventCreateScrollWheelEvent(None, 0, 1, speed)\n CGEventPost(kCGHIDEventTap, event)\n\ndef scrollWheelDown(numTicks):\n for i in xrange(1, numTicks):\n time.sleep(.005)\n multiplier = 1 - (float(i) / numTicks)\n speed = 4 * multiplier\n event = CGEventCreateScrollWheelEvent(None, 0, 1, (-1)*speed)\n CGEventPost(kCGHIDEventTap, event)","sub_path":"scrollWheelMac.py","file_name":"scrollWheelMac.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"344536249","text":"import os\n\nHOST = os.environ.get('HOST') or ''\nPORT = os.environ.get('PORT') or 4000\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\nDATABASE = os.environ.get('DATABASE') or 'sqlite:///' + os.path.join(basedir, 'database.sqlite')\n\nLOBBY_ROOM_NAME = \"Lobby\"\nLOBBY_ROOM_DESC = \"Welcome to MtGMUD!!\\nYou are in the lobby area. Type 'help' to get started!\"\n\nADMIN = os.environ.get('ADMIN') or None\n\nBANNED_NAMES = ['admin', 'fuck', 'shit', 'asshole', 'ass', 'nigger']","sub_path":"app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"301332726","text":"##\n# @file read.py\n#\n# @brief read class definitions.\n#\n# @package readtty\n# @module read\n# @copyright\n\n##\n# @class read\n# @brief read class definition\n#\n# @module read\n# @see\nimport time\nimport types\nimport serial\nimport socket\nfrom traindb.traindb import traindb as dbConnection\nfrom write.write import write as publish\nfrom log.log import log as logger\nfrom config.config import config as setting\nclass read:\n writer = None\n db = None\n ticketFrom = ''\n ticketTo = ''\n ticketFare = 0\n ticketAdult = ''\n ticketChild = ''\n databasePath = ''\n logging = ''\n systemType = ''\n __cfg = None\n __ticketPrint = False\n __trainName = ''\n\n def __init__(self, databasePath, systemType):\n self.systemType = systemType\n self.logging = logger(self.systemType)\n self.databasePath = databasePath\n self.db = dbConnection(self.databasePath, self.logging)\n self.writer = publish(self.logging)\n self.__cfg = setting()\n self.__ticketPrint = False\n\n ##\n # @brief Read the serial port\n # @param void\n # @return void\n def readSerialport(self):\n self.logging.info(\"Reading the data from serial port\")\n try:\n serialPortName = self.__cfg.get('parser', 'serial_port_name')\n if serialPortName == '0':\n serialPortName = 0\n f = serial.Serial(serialPortName)\n #print f\n try:\n inputData = f.read(1)\n except serial.SerialException as e:\n self.logging.warn(\"Error reading port. Skipping byte\")\n\n while inputData:\n buf = self.byteToHex(inputData)\n\n if inputData == \"\":\n #print \"End Of File\"\n self.logging.info(\"End Of File\")\n\n try:\n inputData = f.read(1)\n except serial.SerialException as e:\n self.logging.warn(\"Error reading port.\")\n\n continue\n\n if buf != \"1B\":\n try:\n buf = self.byteToHex(f.read(1))\n except serial.SerialException as e:\n self.logging.warn(\"Error reading port.\")\n\n done = False\n packet = \"\"\n fieldValue = \"\"\n\n while done == False:\n try:\n inputData = f.read(1)\n except serial.SerialException as e:\n self.logging.warn(\"Error reading port.\")\n continue\n\n #print buf\n data = self.byteToHex(inputData)\n if inputData == \"\":\n #print \"End Of File\"\n self.logging.info(\"End of file\")\n break\n if data == \"1B\":\n #print \"Done\"\n done = True\n else:\n packet += data\n #print packet\n #print(\"Field Value-->\"+self.HexToChar(packet))\n self.processPacket(packet)\n f.close()\n except BaseException as e:\n self.logging.critical(e.args[0])\n\n ##\n # @brief Read the sample file for testing mode\n # @param Void\n # @return Void\n def readSampleFile(self, samplefile):\n self.logging.info(\"Reading the data from sample data file\")\n try:\n with open(samplefile) as f:\n f = open(samplefile, 'r')\n inputData = f.read(1)\n while inputData:\n buf = self.byteToHex(inputData)\n if inputData == \"\":\n #print \"End Of File\"\n self.logging.info(\"End the file\")\n inputData = f.read(1)\n continue\n if buf != \"1B\":\n buf = self.byteToHex(f.read(1))\n\n done = False\n packet = ''\n while done == False:\n inputData = f.read(1)\n data = self.byteToHex(inputData)\n if inputData == \"\":\n self.logging.info(\"End of file\")\n break\n # packet done\n if data == \"1B\":\n done = True\n else:\n packet += data\n #print \"Field -->\"+packet\n #print(\"Field Value-->\"+self.HexToChar(packet))\n self.processPacket(packet)\n f.close()\n except IOError as e:\n self.logging.critical(\"Error Sample file reading %s\" % e.args[0])\n\n self.readSampleFile(samplefile)\n\n ##\n # @brief Convert to string\n # @param String s\n # @return String\n def toStr(self, s):\n return s.decode(\"Hex\")\n\n ##\n # @brief Get station name\n # @param String station code\n # @return String\n def getStationName(self, sCode):\n # Remove the spaces in the train code\n sCode = sCode.replace(' ','')\n # Check if the scode is alphabet or not\n if not sCode.isalpha():\n rvalue = \".\"\n else:\n rvalue = self.db.getName(sCode)\n if type(rvalue) is types.StringType:\n return rvalue\n return unicode.encode(rvalue, \"utf-8\")\n\n ##\n # @brief Convert to byte to hex\n # @param Byte byteStr\n # @return String\n def byteToHex(self, byteStr ):\n return ''.join([\"%02X \" % ord(x) for x in byteStr]).strip()\n\n ##\n # @brief Convert to hex to char\n # @param String hexStr\n # @return String\n def HexToChar(self, hexStr):\n res = \"\"\n for i in range(len(hexStr)/2):\n realIdx = i*2\n res = res + chr(int(hexStr[realIdx:realIdx+2],16))\n return res\n\n ##\n # @brief check the string is it good\n # @param String first\n # @return String\n def goodPacket(self, first):\n if first == \"1B\" or first == \"2E\" or first == \"07\" or first== \"0D\" or first == \"\":\n return False\n else:\n return True\n\n ##\n # @brief Check the packet and extract the data\n # @param String packet\n # @return void\n def processPacket(self, packet):\n # Getting the clerk name\n\n if packet.startswith(\"5B316D55534552204E414D453A\"):\n #time.sleep(10)\n self.writer.updateFile('operatormode', 'login')\n hexTrainNumber = self.HexToChar(packet[24:len(packet)])\n self.logging.debug(\"Clerk Name is-->%s\" % hexTrainNumber)\n self.writer.updateFile('Clerk', hexTrainNumber)\n #time.sleep(10)\n\n # Matching the Train Number Pattern and displaying Train Number and Reservation\n elif packet.startswith(\"5B30343B333048\") or packet.startswith(\"5B30343B333548\"):\n if self.goodPacket(packet[14:16]):\n self.logging.debug('Transaction == ....... Reservation ........ ')\n hexTrainNumber = self.HexToChar(packet[14:len(packet)])\n self.logging.debug('Train Number is-->'+hexTrainNumber)\n self.writer.updateFile('TrainNo', hexTrainNumber)\n # Getting the train name\n self.__trainName = self.db.getTrainName(hexTrainNumber)\n self.__trainName = self.__trainName.strip()\n self.logging.debug ('Train Name from db -->'+self.__trainName)\n self.writer.updateFile('TrainName', self.__trainName)\n #self.writer.updateFile(\"TrainName\", \".\")\n self.writer.updateFile(\"From\", \".\")\n self.writer.updateFile(\"To\", \".\")\n self.writer.updateFile(\"Class\", \".\")\n self.writer.updateFile(\"Date\", \".\")\n self.writer.updateFile(\"Status\", \".\")\n self.writer.updateFile(\"Adult\", \".\")\n self.writer.updateFile(\"Child\", \".\")\n self.writer.updateFile(\"Fare\", \".\")\n self.ticketFrom = ''\n self.ticketTo = ''\n self.ticketFare = ''\n self.ticketAdult = ''\n self.ticketChild = ''\n\n # Matching the Train Number Pattern and displaying Train Number and cancellation\n elif packet.startswith(\"5B30383B303748\"):\n if self.goodPacket(packet[14:16]):\n self.logging.debug(\"Transaction == ....... Cancellation ...........\")\n hexTrainNumber = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train Number is-->\"+hexTrainNumber)\n self.writer.updateFile(\"TrainNo\", hexTrainNumber)\n self.writer.updateFile(\"TrainName\", \".\")\n self.writer.updateFile(\"From\", \".\")\n self.writer.updateFile(\"To\", \".\")\n self.writer.updateFile(\"Class\", \".\")\n self.writer.updateFile(\"Date\", \".\")\n self.writer.updateFile(\"Status\", \".\")\n self.writer.updateFile(\"Adult\", \".\")\n self.writer.updateFile(\"Child\", \".\")\n self.writer.updateFile(\"Fare\", \".\")\n self.ticketFrom = \"\"\n self.ticketTo = \"\"\n self.ticketFare = \"\"\n self.ticketAdult = ''\n self.ticketChild = ''\n\n\n # Matching the Train Number Pattern and displaying Train Number and Block Booking\n elif packet.startswith(\"5B30333B333848\"):\n if self.goodPacket(packet[14:16]):\n self.logging.debug(\"Tranction == ....... BlockBooking ........ \")\n hexTrainNumber = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train Number is-->\"+hexTrainNumber)\n self.writer.updateFile(\"TrainNo\", hexTrainNumber)\n self.writer.updateFile(\"TrainName\", \".\")\n self.writer.updateFile(\"From\", \".\")\n self.writer.updateFile(\"To\", \".\")\n self.writer.updateFile(\"Class\", \".\")\n self.writer.updateFile(\"Date\", \".\")\n self.writer.updateFile(\"Status\", \".\")\n self.writer.updateFile(\"Adult\", \".\")\n self.writer.updateFile(\"Child\", \".\")\n self.writer.updateFile(\"Fare\", \".\")\n self.ticketFrom = \"\"\n self.ticketTo = \"\"\n self.ticketFare = \"\"\n self.ticketAdult = ''\n self.ticketChild = ''\n\n\n # Matching the Train Name Pattern and displaying Train Name\n elif self.__trainName == '' and (packet.startswith(\"5B30343B353448\") or packet.startswith(\"5B30343B363448\")or \\\n packet.startswith(\"5B30343B353648\") or packet.startswith(\"5B30343B363648\") or \\\n packet.startswith(\"5B30343B353148\") or packet.startswith(\"5B30343B363148\") or \\\n packet.startswith(\"5B30383B313348\") or packet.startswith(\"5B30333B353848\")):\n if self.goodPacket(packet[14:16]):\n hexTrainName = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train Name from serial-->\"+hexTrainName)\n self.writer.updateFile(\"TrainName\", hexTrainName)\n\n # Matching the Train From Pattern and displaying Train From\n elif packet.startswith(\"5B30373B373448\") or packet.startswith(\"5B30373B333448\") or \\\n packet.startswith(\"5B30373B373748\") or packet.startswith(\"5B30373B333748\")or \\\n packet.startswith(\"5B30383B333648\") or packet.startswith(\"5B30343B333848\"):\n if self.goodPacket(packet[14:16]):\n hexTrainFrom = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train From -->\"+hexTrainFrom)\n stationFromName = self.getStationName(hexTrainFrom)\n self.writer.updateFile(\"From\", stationFromName)\n self.ticketFrom = stationFromName\n\n # Matching the Train To Pattern and displaying Train TO\n elif packet.startswith(\"5B30373B353448\") or packet.startswith(\"5B30373B313448\") or \\\n packet.startswith(\"5B30373B353748\") or packet.startswith(\"5B30373B313748\") or \\\n packet.startswith(\"5B30383B343148\") or packet.startswith(\"5B30353B333848\"):\n if self.goodPacket(packet[14:16]):\n hexTrainTo = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train TO -->\"+hexTrainTo)\n stationToName = self.getStationName(hexTrainTo)\n self.writer.updateFile(\"To\", stationToName)\n self.ticketTo = stationToName\n\n # Matching the Train Class Pattern and displaying Train Class\n elif packet.startswith(\"5B30353B373448\") or packet.startswith(\"5B30353B373548\") or \\\n packet.startswith(\"5B30383B343748\") or packet.startswith(\"5B30343B373448\"):\n #self.logging.debug(\"Packet--\"+packet\n if self.goodPacket(packet[14:16]):\n hexTrainClass = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train Class -->\"+hexTrainClass)\n self.writer.updateFile(\"Class\", hexTrainClass)\n\n # Matching the Train Date and Status Pattern and displaying Train Date and Status\n elif packet.startswith(\"5B316D44415445203A\") or packet.startswith(\"5B30383B333048\"):\n if self.goodPacket(packet[14:16]):\n hexTrainDate_Status = self.HexToChar(packet[12:len(packet)])\n self.logging.debug(\"train date and status-->\"+hexTrainDate_Status)\n self.logging.debug(\"Train Date -->\"+hexTrainDate_Status[3:10])\n self.logging.debug(\"Train Status -->\"+hexTrainDate_Status[33:len(hexTrainDate_Status)])\n self.writer.updateFile(\"Date\", hexTrainDate_Status[3:10])\n self.writer.updateFile(\"Status\", hexTrainDate_Status[33:len(hexTrainDate_Status)])\n\n # Matching the Train Adult Pattern and displaying Train Adult\n elif packet.startswith(\"5B30363B353448\") or packet.startswith(\"5B30383B333548\") or \\\n packet.startswith(\"5B30353B353848\"):\n #self.logging.debug(\"Packet--\"+packet\n if self.goodPacket(packet[14:16]):\n hexTrainAdult = self.HexToChar(packet[14:len(packet)])\n self.logging.debug(\"Train Adult -->\"+hexTrainAdult)\n self.writer.updateFile(\"Adult\", hexTrainAdult)\n self.ticketAdult = hexTrainAdult\n\n # Getting fare info from packets which contains 'TOTAL CASH TO BE COLLECTED'\n elif packet.startswith(\"5B316D43415348\"):\n if self.goodPacket(packet[50:52]):\n hexFareList = packet.split('564F554348455220464152453A')\n hexValue = hexFareList[0]\n hexTrainFare = self.toStr(hexValue[50:])\n hexTrainFare = self.integerCheck(hexTrainFare.strip())\n self.ticketFare = hexTrainFare\n self.logging.debug(\"Train Fare -->\"+self.ticketFare)\n #print hexTrainFare\n self.writer.updateFile(\"Fare\", self.ticketFare)\n\n # Getting fare info( rare case )\n elif packet.startswith(\"5B316D2020202020202020202020202020202020202020544F54414C2043415348\"):\n self.logging.debug(\"TOTAL CASH:: \" + packet[104:118])\n if self.goodPacket(packet[104:106]):\n hexTrainFare = self.toStr(packet[104:118])\n hexTrainFare = self.integerCheck(hexTrainFare.strip())\n self.logging.debug(\"Train Fare -->\" + hexTrainFare)\n #print hexTrainFare\n self.writer.updateFile(\"Fare\", hexTrainFare)\n self.ticketFare = hexTrainFare\n\n # Getting fare info\n elif packet.startswith(\"5B32323B353248\"):\n if self.goodPacket(packet[14:15]):\n hexTrainFare = self.toStr(packet[14:22])\n hexTrainFare = self.integerCheck(hexTrainFare.strip())\n self.logging.debug(\"Train Fare -->\" + hexTrainFare)\n self.writer.updateFile(\"Fare\", hexTrainFare)\n self.ticketFare = hexTrainFare\n\n # Matching the Number of Passengers Pattern and displaying Passengers\n #if packet.startswith(\"5B30353B353848\"):\n # if self.goodPacket(packet[14:16]):\n # hexTrainPassengers = self.HexToChar(packet[14:len(packet)])\n # self.logging.debug(\"Train Passengers -->\"+hexTrainPassengers[56:len(hexTrainPassengers)])\n\n # while ticket printing, store the booking details\n elif packet.startswith(\"5B316D5469636B6574205072696E746564205375636365737366756C6C792028592F4E2\"):\n storeTicketInfo = self.__cfg.get('parser', 'store_ticket_info')\n readttylog = self.__cfg.get('default', 'readttylog')\n if '0' != readttylog and 1 == int(storeTicketInfo) and self.__ticketPrint == False:\n self.logging.debug('Ticket Printed Successfully')\n self.db.addTicketLog(self.ticketFrom, self.ticketTo, self.ticketAdult, self.ticketChild, self.ticketFare, self.systemType)\n self.__ticketPrint = True\n time.sleep(1)\n\n # After printing the ticket, receive the 'Y' when clear screen\n elif self.__ticketPrint and packet.startswith(\"5B32376D0759\"):\n # Print 'thanks for booking msg'\n self.writer.displayTicketPrint()\n #print publish.getData()\n self.__clearData()\n\n # Getting date, adult and child info\n elif packet.startswith(\"480F20\"):\n if self.goodPacket(packet[62:66]):\n # Getting Adult Date\n value = self.HexToChar(packet[22:42])\n self.logging.debug(\"Date -->\"+value)\n self.writer.updateFile(\"Date\", value.strip())\n # Getting Adult info\n hexTrainAdult = self.HexToChar(packet[62:66])\n self.logging.debug(\"Adult -->\"+hexTrainAdult)\n self.writer.updateFile(\"Adult\", hexTrainAdult.strip())\n self.ticketAdult = hexTrainAdult\n # Getting Child info\n hexTrainAdult = self.HexToChar(packet[72:76])\n self.logging.debug(\"Child -->\"+hexTrainAdult)\n self.writer.updateFile(\"Child\", hexTrainAdult.strip())\n self.ticketChild = hexTrainAdult\n\n # Getting Class and Date info\n elif packet.startswith(\"5B306D0D0A0D0A20202031\"):\n if self.goodPacket(packet[140:144]):\n value = self.HexToChar(packet[140:144])\n self.logging.debug(\"Class -->\"+value)\n self.writer.updateFile(\"Class\", value.strip())\n value = self.HexToChar(packet[118:128])\n self.logging.debug(\"Date -->\"+value)\n self.writer.updateFile(\"Date\", value.strip())\n\n # while ticket cancellation, store the booking details\n elif packet.startswith(\"5B324B2543414E5F444F4E45\"):\n storeTicketInfo = self.__cfg.get('parser', 'store_ticket_info')\n readttylog = self.__cfg.get('default', 'readttylog')\n if '0' != readttylog and 1 == int(storeTicketInfo):\n self.logging.debug('Cancellation Done Successfully')\n # new changes.\n self.db.addTicketLog(self.ticketFrom, self.ticketTo, self.ticketAdult, self.ticketChild, self.ticketFare, self.systemType)\n # anothercase for capturing operator login\n elif packet.startswith('5B363B313648785F5F5F5F435F4F5F4E5F435F455F525F54'):\n self.writer.updateFile('operatormode', 'login')\n # Logout capturing\n elif packet.startswith('5B31303B31354820444F20594F55205741') or (packet.startswith('21486E') and '6C6F67676564206F7574' in packet):\n self.writer.updateFile('Clerk', '')\n self.__clearData()\n self.writer.updateFile('operatormode', 'logout')\n\n\n\n ##\n # @brief valid the is it number\n # @param String s\n # @return string r\n def integerCheck(self, s):\n r = \".\"\n if s.isdigit():\n r = s\n\n return r\n\n ##\n # @brief Clear ticket data\n # @param void\n # @return void\n def __clearData(self):\n self.writer.updateFile('TrainNo', '.')\n self.writer.updateFile('TrainName', '.')\n self.writer.updateFile('From', '.')\n self.writer.updateFile('To', '.')\n self.writer.updateFile('Class', '.')\n self.writer.updateFile('Date', '.')\n self.writer.updateFile('Status', '.')\n self.writer.updateFile('Adult', '.')\n self.writer.updateFile('Child', '.')\n self.writer.updateFile('Fare', '.')\n self.ticketFrom = ''\n self.ticketTo = ''\n self.ticketFare = ''\n self.ticketAdult = ''\n self.ticketChild = ''\n self.__trainName = ''\n self.__ticketPrint = False\n","sub_path":"html/read/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":21078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"292154513","text":"# Copyright (c) 2012 Stuart Pernsteiner\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# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 2. 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 AUTHOR \"AS IS\" AND ANY EXPRESS OR IMPLIED\n# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Ported to Inkscape 1.0 by Sofyan Sugianto \n\nimport inkex\n\nclass GroupToLayerEffect(inkex.Effect):\n def __init__(self):\n inkex.Effect.__init__(self)\n\n self.arg_parser.add_argument('-d', '--depth',\n type = int, dest = 'depth', default = 1, metavar = 'DEPTH',\n help = 'Convert nested group up to DEPTH layers deep')\n\n def effect(self):\n depth = self.options.depth\n\n self.tag_g = inkex.utils.addNS('g', 'svg')\n\n for node in self.svg.selected.values():\n self.convert_group(node, depth)\n\n def convert_group(self, node, depth):\n if depth <= 0:\n return\n\n if node.tag != self.tag_g:\n return\n\n node.set(inkex.utils.addNS('groupmode', 'inkscape'), 'layer')\n\n for child in node:\n self.convert_group(child, depth - 1)\n\n# Create effect instance and apply it.\neffect = GroupToLayerEffect()\neffect.run()\n","sub_path":"inkscape-1.0/group_to_layer.py","file_name":"group_to_layer.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"651651557","text":"import torch\nimport torch.nn as nn\nfrom inferno.extensions.layers.convolutional import ConvELU3D, Conv3D, BNReLUConv3D\nfrom inferno.extensions.layers.sampling import AnisotropicPool, AnisotropicUpsample, Upsample, GlobalMaskedAvgPool3d\nfrom .base import Xcoder\n\nCONV_TYPES = {'vanilla': ConvELU3D,\n 'conv_bn': BNReLUConv3D}\n\n\ndef get_pooler(scale_factor):\n assert isinstance(scale_factor, (int, list, tuple))\n if isinstance(scale_factor, (list, tuple)):\n assert len(scale_factor) == 3\n assert scale_factor[0] == 1\n # we need to make sure that the scale factor conforms with the single value\n # that AnisotropicPool expects\n pooler = AnisotropicPool(downscale_factor=scale_factor[1])\n else:\n if scale_factor > 0:\n pooler = nn.MaxPool3d(kernel_size=1 + scale_factor,\n stride=scale_factor,\n padding=1)\n else:\n pooler = None\n return pooler\n\n\ndef get_sampler(scale_factor):\n assert isinstance(scale_factor, (int, list, tuple))\n if isinstance(scale_factor, (list, tuple)):\n assert len(scale_factor) == 3\n # we need to make sure that the scale factor conforms with the single value\n # that AnisotropicPool expects\n assert scale_factor[0] == 1\n sampler = AnisotropicUpsample(scale_factor=scale_factor[1])\n else:\n if scale_factor > 0:\n sampler = Upsample(scale_factor=scale_factor)\n else:\n sampler = None\n return sampler\n\n\nclass Encoder(Xcoder):\n def __init__(self, in_channels, out_channels, kernel_size,\n conv_type=ConvELU3D, scale_factor=2):\n super(Encoder, self).__init__(in_channels, out_channels, kernel_size,\n conv_type=conv_type,\n pre_conv=get_pooler(scale_factor))\n\n\nclass Decoder(Xcoder):\n def __init__(self, in_channels, out_channels, kernel_size,\n conv_type=ConvELU3D, scale_factor=2):\n super(Decoder, self).__init__(in_channels, out_channels, kernel_size,\n conv_type=conv_type,\n post_conv=get_sampler(scale_factor))\n\n\nclass UNet3DNlNoSkip(nn.Module):\n \"\"\"\n 3D U-Net architecture without skip connections\n with the number of layers specified by the user.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n initial_num_fmaps,\n fmap_growth,\n num_layers=5,\n num_decode=None,\n scale_factor=2,\n emb_size=None,\n emb_fc=None,\n glob_pool='avg',\n final_activation='auto',\n conv_type_key='vanilla'):\n \"\"\"\n Parameter:\n ----------\n in_channels (int): number of input channels\n out_channels (int): number of output channels\n initial_num_fmaps (int): number of feature maps of the first layer\n fmap_growth (int): growth factor of the feature maps; the number of feature maps\n in layer k is given by initial_num_fmaps * fmap_growth**k\n num_layers (int): the number of layers (excluding the base) in the U-Net\n scale_factor (int or list / tuple): upscale / downscale factor (default: 2)\n glob_pool: the final global pooling (None, 'avg', 'max')\n final_activation: final activation used (default: 'auto')\n conv_type_key: convolution type used (default: 'vanilla')\n \"\"\"\n super(UNet3DNlNoSkip, self).__init__()\n\n assert conv_type_key in CONV_TYPES, conv_type_key\n conv_type = CONV_TYPES[conv_type_key]\n assert isinstance(scale_factor, (int, list, tuple))\n self.scale_factor = [scale_factor] * num_layers \\\n if isinstance(scale_factor, int) else scale_factor\n assert len(self.scale_factor) == num_layers\n self.scale_factor = [0] + self.scale_factor \\\n if isinstance(self.scale_factor, list) else (0,) + self.scale_factor\n # the entry can be a tuple/list for anisotropic sampling\n assert all(isinstance(sfactor, (int, list, tuple)) for sfactor in self.scale_factor)\n\n # The global pooling applied on the bottleneck embedding space\n # to convert the feature maps to a feature vector\n # of the same size for any input size\n if glob_pool == 'avg':\n self.global_pool = nn.AdaptiveAvgPool3d(1)\n elif glob_pool == 'max':\n self.global_pool = nn.AdaptiveMaxPool3d(1)\n elif glob_pool == 'avg_mask':\n self.global_pool = GlobalMaskedAvgPool3d()\n else:\n self.global_pool = None\n self.mask_value = 0\n\n # Set attributes\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n # Build encoders with proper number of feature maps\n # number of feature maps for the encoders\n\n fe = [in_channels]\n for n in range(num_layers):\n fe.append(initial_num_fmaps * fmap_growth**n)\n encoders = []\n for n in range(num_layers):\n encoders.append(Encoder(fe[n], fe[n+1], 3, conv_type=conv_type,\n scale_factor=self.scale_factor[n]))\n self.encoders = nn.ModuleList(encoders)\n\n # Build base\n # number of base output feature maps\n f0b = initial_num_fmaps * fmap_growth**num_layers\n\n self.base = Encoder(fe[num_layers], f0b, 3, conv_type=conv_type,\n scale_factor=self.scale_factor[num_layers])\n self.base_bottleneck = ConvELU3D(f0b, emb_size, 1) if emb_size is not None else None\n self.base_upsample = get_sampler(self.scale_factor[num_layers])\n\n emb_size = f0b if emb_size is None else emb_size\n self.emb_fc = nn.Linear(emb_size, emb_fc) if emb_fc else None\n\n # Decoders list\n fd = [f0b] if emb_size is None else [emb_size]\n if num_decode is None:\n num_decode = num_layers\n for n in reversed(range(num_decode)):\n fd.append(initial_num_fmaps * fmap_growth**n)\n decoders = []\n for n in range(num_decode):\n decoders.append(Decoder(fd[n], fd[n+1], 3, conv_type=conv_type,\n scale_factor=self.scale_factor[-n-2]))\n self.decoders = nn.ModuleList(decoders)\n\n # Build output\n self.output = Conv3D(fd[num_decode], out_channels, 3)\n # Parse final activation\n if final_activation == 'auto':\n final_activation = nn.Sigmoid() if out_channels == 1 else nn.Softmax3d()\n elif final_activation is None or final_activation == 'None':\n self.final_activation = None\n elif isinstance(final_activation, str):\n self.final_activation = getattr(nn, final_activation)()\n elif isinstance(final_activation, nn.Module):\n self.final_activation = final_activation\n else:\n raise NotImplementedError\n\n def get_mask(self, inp, mask_val):\n summed_inp = inp.abs().sum(axis=1).unsqueeze(1)\n mask = (~torch.isclose(summed_inp, torch.ones_like(summed_inp) * mask_val,\n atol=5e-03)).type(torch.float)\n # pool the mask\n for i in self.scale_factor:\n pooler = get_pooler(i)\n mask = mask if pooler is None else pooler(mask)\n return mask\n\n def pool(self, inp, mask=None):\n if isinstance(self.global_pool, GlobalMaskedAvgPool3d):\n assert mask is not None\n inp = self.global_pool(inp, mask)\n else:\n inp = self.global_pool(inp) if self.global_pool is not None else inp\n inp = torch.flatten(inp, 1)\n return inp\n\n def forward(self, x, just_encode=False):\n mask = self.get_mask(x, self.mask_value) \\\n if isinstance(self.global_pool, GlobalMaskedAvgPool3d) else None\n # encode\n for encoder in self.encoders:\n x = encoder(x)\n embedding = self.base(x)\n\n if self.base_bottleneck is not None:\n embedding = self.base_bottleneck(embedding)\n\n pooled_emb = self.pool(embedding, mask)\n if self.emb_fc is not None:\n pooled_emb = self.emb_fc(pooled_emb)\n\n if just_encode:\n return pooled_emb\n\n x = embedding if self.base_upsample is None else self.base_upsample(embedding)\n for decoder in self.decoders:\n x = decoder(x)\n\n x = self.output(x)\n if self.final_activation is not None:\n x = self.final_activation(x)\n\n return x, pooled_emb, pooled_emb\n","sub_path":"neurofire/models/unet/unet_3d_noskip_n_layers.py","file_name":"unet_3d_noskip_n_layers.py","file_ext":"py","file_size_in_byte":8768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"349585","text":"for i in range(int(input())):\n container, truck = map(int, input().split())\n weight_list = list(map(int, input().split()))\n truck_weights = list(map(int, input().split()))\n\n sum = 0\n weight_list.sort()\n weight_list.reverse()\n print(weight_list)\n for weight in weight_list:\n for idx, truck_weight in enumerate(truck_weights):\n if weight <= truck_weight:\n truck_weights.pop(idx)\n sum += weight\n break\n if not truck_weights:\n break\n print(f'#{i+1} {sum}')\n\n \n","sub_path":"Greedy/화물 도크.py","file_name":"화물 도크.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"338939946","text":"#Write a Python program to check whether a number is completely divisible by another\r\n#number. Accept two integer values from the user.\r\n \r\nnum1 = int(input('Enter first number: '))\r\nnum2 = int(input('Enter second number: ')) \r\n\r\n# % gives remainder\r\n\r\n\r\nif(num1 % num2 == 0):\r\n print('First number is divisible by second number')\r\n\r\nif(num1 % num2 != 0):\r\n print('First number is not divisible by second number')\r\n","sub_path":"task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"575140510","text":"from dataclasses import dataclass\nfrom datetime import timedelta\nfrom typing import Mapping, Optional, Sequence, Set\n\nfrom snuba.clickhouse.columns import (\n UUID,\n Array,\n ColumnSet,\n DateTime,\n FixedString,\n Float,\n Nested,\n)\nfrom snuba.clickhouse.columns import SchemaModifiers as Modifiers\nfrom snuba.clickhouse.columns import String, UInt\nfrom snuba.clickhouse.translators.snuba import SnubaClickhouseStrictTranslator\nfrom snuba.clickhouse.translators.snuba.allowed import (\n ColumnMapper,\n CurriedFunctionCallMapper,\n FunctionCallMapper,\n SubscriptableReferenceMapper,\n)\nfrom snuba.clickhouse.translators.snuba.mappers import (\n ColumnToLiteral,\n ColumnToMapping,\n SubscriptableMapper,\n)\nfrom snuba.clickhouse.translators.snuba.mapping import TranslationMappers\nfrom snuba.datasets.entities.events import BaseEventsEntity, EventsQueryStorageSelector\nfrom snuba.datasets.entities.transactions import BaseTransactionsEntity\nfrom snuba.datasets.entity import Entity\nfrom snuba.datasets.plans.single_storage import SelectedStorageQueryPlanBuilder\nfrom snuba.datasets.storages import StorageKey\nfrom snuba.datasets.storages.factory import get_storage\nfrom snuba.query.dsl import identity\nfrom snuba.query.expressions import (\n Column,\n CurriedFunctionCall,\n FunctionCall,\n Literal,\n SubscriptableReference,\n)\nfrom snuba.query.extensions import QueryExtension\nfrom snuba.query.matchers import FunctionCall as FunctionCallMatch\nfrom snuba.query.matchers import Literal as LiteralMatch\nfrom snuba.query.matchers import Or\nfrom snuba.query.matchers import String as StringMatch\nfrom snuba.query.processors import QueryProcessor\nfrom snuba.query.processors.basic_functions import BasicFunctionsProcessor\nfrom snuba.query.processors.tags_expander import TagsExpanderProcessor\nfrom snuba.query.processors.timeseries_processor import TimeSeriesProcessor\nfrom snuba.query.project_extension import ProjectExtension\nfrom snuba.query.timeseries_extension import TimeSeriesExtension\nfrom snuba.util import qualified_column\n\n\n@dataclass(frozen=True)\nclass DefaultNoneColumnMapper(ColumnMapper):\n \"\"\"\n This maps a list of column names to None (NULL in SQL) as it is done\n in the discover column_expr method today. It should not be used for\n any other reason or use case, thus it should not be moved out of\n the discover dataset file.\n \"\"\"\n\n columns: ColumnSet\n\n def attempt_map(\n self, expression: Column, children_translator: SnubaClickhouseStrictTranslator,\n ) -> Optional[Literal]:\n if expression.column_name in self.columns:\n return Literal(\n alias=expression.alias\n or qualified_column(\n expression.column_name, expression.table_name or \"\"\n ),\n value=None,\n )\n else:\n return None\n\n\n@dataclass\nclass DefaultNoneFunctionMapper(FunctionCallMapper):\n \"\"\"\n Maps the list of function names to NULL.\n \"\"\"\n\n function_names: Set[str]\n\n def __post_init__(self) -> None:\n self.function_match = FunctionCallMatch(\n Or([StringMatch(func) for func in self.function_names])\n )\n\n def attempt_map(\n self,\n expression: FunctionCall,\n children_translator: SnubaClickhouseStrictTranslator,\n ) -> Optional[FunctionCall]:\n if self.function_match.match(expression):\n return identity(Literal(None, None), expression.alias)\n\n return None\n\n\n@dataclass(frozen=True)\nclass DefaultIfNullFunctionMapper(FunctionCallMapper):\n \"\"\"\n If a function is being called on a column that doesn't exist, or is being\n called on NULL, change the entire function to be NULL.\n \"\"\"\n\n function_match = FunctionCallMatch(\n StringMatch(\"ifNull\"), (LiteralMatch(), LiteralMatch())\n )\n\n def attempt_map(\n self,\n expression: FunctionCall,\n children_translator: SnubaClickhouseStrictTranslator,\n ) -> Optional[FunctionCall]:\n parameters = tuple(p.accept(children_translator) for p in expression.parameters)\n all_null = True\n for param in parameters:\n # Handle wrapped functions that have been converted to ifNull(NULL, NULL)\n fmatch = self.function_match.match(param)\n if fmatch is None:\n if isinstance(param, Literal):\n if param.value is not None:\n all_null = False\n break\n else:\n all_null = False\n break\n\n if all_null and len(parameters) > 0:\n # Currently function mappers require returning other functions. So return this\n # to keep the mapper happy.\n return FunctionCall(\n expression.alias, \"ifNull\", (Literal(None, None), Literal(None, None))\n )\n\n return None\n\n\n@dataclass(frozen=True)\nclass DefaultIfNullCurriedFunctionMapper(CurriedFunctionCallMapper):\n \"\"\"\n If a curried function is being called on a column that doesn't exist, or is being\n called on NULL, change the entire function to be NULL.\n \"\"\"\n\n function_match = FunctionCallMatch(\n StringMatch(\"ifNull\"), (LiteralMatch(), LiteralMatch())\n )\n\n def attempt_map(\n self,\n expression: CurriedFunctionCall,\n children_translator: SnubaClickhouseStrictTranslator,\n ) -> Optional[CurriedFunctionCall]:\n internal_function = expression.internal_function.accept(children_translator)\n assert isinstance(internal_function, FunctionCall) # mypy\n parameters = tuple(p.accept(children_translator) for p in expression.parameters)\n\n all_null = True\n for param in parameters:\n # Handle wrapped functions that have been converted to ifNull(NULL, NULL)\n fmatch = self.function_match.match(param)\n if fmatch is None:\n if isinstance(param, Literal):\n if param.value is not None:\n all_null = False\n break\n else:\n all_null = False\n break\n\n if all_null and len(parameters) > 0:\n # Currently curried function mappers require returning other curried functions.\n # So return this to keep the mapper happy.\n return CurriedFunctionCall(\n alias=expression.alias,\n internal_function=FunctionCall(\n None,\n f\"{internal_function.function_name}OrNull\",\n internal_function.parameters,\n ),\n parameters=tuple(Literal(None, None) for p in parameters),\n )\n\n return None\n\n\n@dataclass(frozen=True)\nclass DefaultNoneSubscriptMapper(SubscriptableReferenceMapper):\n \"\"\"\n This maps a subscriptable reference to None (NULL in SQL) as it is done\n in the discover column_expr method today. It should not be used for\n any other reason or use case, thus it should not be moved out of\n the discover dataset file.\n \"\"\"\n\n subscript_names: Set[str]\n\n def attempt_map(\n self,\n expression: SubscriptableReference,\n children_translator: SnubaClickhouseStrictTranslator,\n ) -> Optional[Literal]:\n if expression.column.column_name in self.subscript_names:\n return Literal(alias=expression.alias, value=None)\n else:\n return None\n\n\nEVENTS_COLUMNS = ColumnSet(\n [\n (\"group_id\", UInt(64, Modifiers(nullable=True))),\n (\"primary_hash\", FixedString(32, Modifiers(nullable=True))),\n # Promoted tags\n (\"level\", String(Modifiers(nullable=True))),\n (\"logger\", String(Modifiers(nullable=True))),\n (\"server_name\", String(Modifiers(nullable=True))),\n (\"site\", String(Modifiers(nullable=True))),\n (\"url\", String(Modifiers(nullable=True))),\n (\"location\", String(Modifiers(nullable=True))),\n (\"culprit\", String(Modifiers(nullable=True))),\n (\"received\", DateTime(Modifiers(nullable=True))),\n (\"sdk_integrations\", Array(String(), Modifiers(nullable=True))),\n (\"version\", String(Modifiers(nullable=True))),\n # exception interface\n (\n \"exception_stacks\",\n Nested(\n [\n (\"type\", String(Modifiers(nullable=True))),\n (\"value\", String(Modifiers(nullable=True))),\n (\"mechanism_type\", String(Modifiers(nullable=True))),\n (\"mechanism_handled\", UInt(8, Modifiers(nullable=True))),\n ]\n ),\n ),\n (\n \"exception_frames\",\n Nested(\n [\n (\"abs_path\", String(Modifiers(nullable=True))),\n (\"filename\", String(Modifiers(nullable=True))),\n (\"package\", String(Modifiers(nullable=True))),\n (\"module\", String(Modifiers(nullable=True))),\n (\"function\", String(Modifiers(nullable=True))),\n (\"in_app\", UInt(8, Modifiers(nullable=True))),\n (\"colno\", UInt(32, Modifiers(nullable=True))),\n (\"lineno\", UInt(32, Modifiers(nullable=True))),\n (\"stack_level\", UInt(16)),\n ]\n ),\n ),\n (\"modules\", Nested([(\"name\", String()), (\"version\", String())])),\n ]\n)\n\nTRANSACTIONS_COLUMNS = ColumnSet(\n [\n (\"trace_id\", UUID(Modifiers(nullable=True))),\n (\"span_id\", UInt(64, Modifiers(nullable=True))),\n (\"transaction_hash\", UInt(64, Modifiers(nullable=True))),\n (\"transaction_op\", String(Modifiers(nullable=True))),\n (\"transaction_status\", UInt(8, Modifiers(nullable=True))),\n (\"duration\", UInt(32, Modifiers(nullable=True))),\n (\"measurements\", Nested([(\"key\", String()), (\"value\", Float(64))]),),\n ]\n)\n\n\nevents_translation_mappers = TranslationMappers(\n columns=[DefaultNoneColumnMapper(TRANSACTIONS_COLUMNS)],\n functions=[DefaultNoneFunctionMapper({\"apdex\", \"failure_rate\"})],\n subscriptables=[DefaultNoneSubscriptMapper({\"measurements\"})],\n)\n\ntransaction_translation_mappers = TranslationMappers(\n columns=[\n ColumnToLiteral(None, \"group_id\", 0),\n DefaultNoneColumnMapper(EVENTS_COLUMNS),\n ],\n functions=[DefaultNoneFunctionMapper({\"isHandled\", \"notHandled\"})],\n)\n\nnull_function_translation_mappers = TranslationMappers(\n curried_functions=[DefaultIfNullCurriedFunctionMapper()],\n functions=[DefaultIfNullFunctionMapper()],\n)\n\n\nclass DiscoverEntity(Entity):\n \"\"\"\n Entity that represents both errors and transactions. This is currently backed\n by the events storage but will eventually be switched to use use the merge table storage.\n \"\"\"\n\n def __init__(self) -> None:\n self.__common_columns = ColumnSet(\n [\n (\"event_id\", FixedString(32)),\n (\"project_id\", UInt(64)),\n (\"type\", String(Modifiers(nullable=True))),\n (\"timestamp\", DateTime()),\n (\"platform\", String(Modifiers(nullable=True))),\n (\"environment\", String(Modifiers(nullable=True))),\n (\"release\", String(Modifiers(nullable=True))),\n (\"dist\", String(Modifiers(nullable=True))),\n (\"user\", String(Modifiers(nullable=True))),\n (\"transaction\", String(Modifiers(nullable=True))),\n (\"message\", String(Modifiers(nullable=True))),\n (\"title\", String(Modifiers(nullable=True))),\n # User\n (\"user_id\", String(Modifiers(nullable=True))),\n (\"username\", String(Modifiers(nullable=True))),\n (\"email\", String(Modifiers(nullable=True))),\n (\"ip_address\", String(Modifiers(nullable=True))),\n # SDK\n (\"sdk_name\", String(Modifiers(nullable=True))),\n (\"sdk_version\", String(Modifiers(nullable=True))),\n # geo location context\n (\"geo_country_code\", String(Modifiers(nullable=True))),\n (\"geo_region\", String(Modifiers(nullable=True))),\n (\"geo_city\", String(Modifiers(nullable=True))),\n (\"http_method\", String(Modifiers(nullable=True))),\n (\"http_referer\", String(Modifiers(nullable=True))),\n # Other tags and context\n (\"tags\", Nested([(\"key\", String()), (\"value\", String())])),\n (\"contexts\", Nested([(\"key\", String()), (\"value\", String())])),\n ]\n )\n self.__events_columns = EVENTS_COLUMNS\n self.__transactions_columns = TRANSACTIONS_COLUMNS\n\n events_storage = get_storage(StorageKey.EVENTS)\n\n super().__init__(\n storages=[events_storage],\n query_plan_builder=SelectedStorageQueryPlanBuilder(\n selector=EventsQueryStorageSelector(\n mappers=events_translation_mappers.concat(\n transaction_translation_mappers\n )\n .concat(null_function_translation_mappers)\n .concat(\n TranslationMappers(\n # XXX: Remove once we are using errors\n columns=[\n ColumnToMapping(\n None, \"release\", None, \"tags\", \"sentry:release\"\n ),\n ColumnToMapping(\n None, \"dist\", None, \"tags\", \"sentry:dist\"\n ),\n ColumnToMapping(\n None, \"user\", None, \"tags\", \"sentry:user\"\n ),\n ],\n subscriptables=[\n SubscriptableMapper(None, \"tags\", None, \"tags\"),\n SubscriptableMapper(None, \"contexts\", None, \"contexts\"),\n ],\n )\n )\n )\n ),\n abstract_column_set=(\n self.__common_columns\n + self.__events_columns\n + self.__transactions_columns\n ),\n writable_storage=None,\n )\n\n def get_query_processors(self) -> Sequence[QueryProcessor]:\n return [\n TimeSeriesProcessor({\"time\": \"timestamp\"}, (\"timestamp\",)),\n TagsExpanderProcessor(),\n BasicFunctionsProcessor(),\n ]\n\n def get_extensions(self) -> Mapping[str, QueryExtension]:\n return {\n \"project\": ProjectExtension(project_column=\"project_id\"),\n \"timeseries\": TimeSeriesExtension(\n default_granularity=3600,\n default_window=timedelta(days=5),\n timestamp_column=\"timestamp\",\n ),\n }\n\n\nclass DiscoverEventsEntity(BaseEventsEntity):\n \"\"\"\n Identical to EventsEntity except it maps columns and functions present in the\n transactions entity to null. This logic will eventually move to Sentry and this\n entity can be deleted and replaced with the EventsEntity directly.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n custom_mappers=events_translation_mappers.concat(\n null_function_translation_mappers\n )\n )\n\n\nclass DiscoverTransactionsEntity(BaseTransactionsEntity):\n \"\"\"\n Identical to TransactionsEntity except it maps columns and functions present\n in the events entity to null. This logic will eventually move to Sentry and this\n entity can be deleted and replaced with the TransactionsEntity directly.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__(\n custom_mappers=transaction_translation_mappers.concat(\n null_function_translation_mappers\n )\n )\n","sub_path":"snuba/datasets/entities/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":16086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"454691963","text":"import bindings\nfrom bindings import LogLevel\nfrom bindings import Device\n\n\ndef render():\n renderer = bindings.RenderActions()\n renderer.set_renderer_log_level(LogLevel.PEDANTIC)\n \n # Name is case insensitive\n renderer.enable_renderer(\"PT\", Device.CPU)# | Device.CUDA)\n # Name is NOT case insensitive! There may be a 'Radiance' and a 'RaDiAnCe' target at the same time\n # Second parameter determines whether variance should be captured as well\n renderer.enable_render_target(\"Radiance\", False);\n renderer.enable_render_target(\"Normal\", True);\n renderer.enable_render_target(\"Albedo\", False);\n \n # Example file path to one of our testscenes (the default render target defaults to 'Radiance',\n\t# which we don't care about because we already enabled them prior)\n renderer.load_json(sceneJson=\"../../testscenes/material/blender_mat_preview.json\")\n renderer.load_scenario(\"Glossy Orange\")\n # Animation frames are implicitly clipped in the available range and start at 0\n renderer.set_current_animation_frame(3)\n # If desired you may loop over frame ranges by querying the available range\n print(renderer.get_current_animation_frame(), \" - \", renderer.get_animation_frame_count())\n # Setting renderer parameters is categorized by type (names are case sensitive!)\n renderer.renderer_set_parameter_int(\"Max. path length\", 8);\n # You'll receive a warning (if the log level is high enough) for parameters that don't exist\n renderer.renderer_set_parameter_float(\"FakeFloatParam\", 1.7);\n renderer.renderer_set_parameter_enum(\"FakeEnumParam\", \"EnumValueName\");\n\n # The screenshot pattern has multiple options to bake configuration details into them;\n # see the function 'take_screenshot' for more\n renderer.screenshotPattern = \"screenshot_folder/\" + renderer.screenshotPattern\n\n # Screenshots are implicitly taken and are (partially) opt-out\n #renderer.render_for_seconds(5)\n # Printing defaults to False\n renderer.render_for_iterations(8, printProgress=True, progressSteps=8, takeScreenshot=False)\n # For manual screenshot taking there are two options: take_screenshot saves all currently\n # enabled render targets, while take_denoised_screenshot looks for a render target 'Radiance'\n # and uses that to save a denoised version of said render target; it optionally incorporates\n # the targets 'Normal' and 'Albedo', if they exist and are enabled\n #renderer.take_screenshot(16)\n # You can also disable render targets (but not enable - not recorded is not recorded)\n # prior to screenshotting; here the second parameter indicates whether ONLY the variance\n # should be disabled\n renderer.take_denoised_screenshot(16)\n\nrender()","sub_path":"examples/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"24497352","text":"import numpy as np\r\nimport json\r\nimport tensorflow as tf\r\nimport tensorflow.keras.backend as K\r\n\r\nfrom lime import lime_image\r\nimport matplotlib.pyplot as plt\r\nfrom skimage.segmentation import mark_boundaries\r\n\r\nimport algo_readImgs as readImgs\r\n\r\n# https://marcotcr.github.io/lime/tutorials/Tutorial%20-%20images.html\r\n# https://github.com/marcotcr/lime/issues/453\r\n\r\ndef new_predict(img):\r\n\r\n imgSize = 64\r\n N = np.shape(img)[0]\r\n\r\n # convert to reshape\r\n new_img = np.reshape(img, (N*imgSize*imgSize, 3)) # (N*64*64, 3)\r\n new_img = list(new_img)\r\n\r\n # [[5, 5, 5], [255, 255, 255], [3, 3, 3], ..., [17, 17, 17]] (N*64*64 elements)\r\n # -> [5, 255, 3, ..., 17]\r\n for pixel in range(N*imgSize*imgSize):\r\n new_img[pixel] = new_img[pixel][0]\r\n\r\n # reshape image into (N, 64*64) \r\n new_img = np.reshape(new_img, (N, imgSize*imgSize))\r\n\r\n return model.predict(new_img)\r\n\r\ndef run_lime(start, end, model):\r\n\r\n import warnings\r\n warnings.filterwarnings('ignore')\r\n warnings.filterwarnings('always')\r\n\r\n # load images\r\n imgs = readImgs.readImgs(start, end)\r\n print('leng of imgs = ' + str(len(imgs)))\r\n imgSize = 64\r\n\r\n # reshape the image\r\n imgs = np.reshape(imgs, (end-start, imgSize*imgSize)).astype(float)\r\n\r\n print(np.shape(imgs))\r\n\r\n ###### LIME EXPLAINER ######\r\n # source: https://github.com/marcotcr/lime\r\n # https://github.com/marcotcr/lime/blob/master/doc/notebooks/Tutorial%20-%20Image%20Classification%20Keras.ipynb\r\n for i in range(len(imgs)):\r\n\r\n print('test for image ' + str(start + i))\r\n \r\n img = imgs[i]\r\n\r\n # convert into list to reshape\r\n img = list(img)\r\n\r\n # reshape image into (64, 64, 3)\r\n for pixel in range(imgSize*imgSize):\r\n img[pixel] = [img[pixel], img[pixel], img[pixel]]\r\n\r\n img = np.array(img)\r\n img = np.reshape(img, (imgSize, imgSize, 3))\r\n \r\n explainer = lime_image.LimeImageExplainer()\r\n explanation = explainer.explain_instance(img.astype('double'), new_predict, top_labels=1, hide_color=0, num_samples=1000)\r\n\r\n # explaination test\r\n temp, mask = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=True, num_features=5, hide_rest=True)\r\n plt.imshow(mark_boundaries(temp / 2 + 0.5, mask))\r\n plt.savefig('algo_1_lime_' + str(start + i) + '_0.png', bbox_inches='tight', pad_inches=0)\r\n\r\n # remove colorbar from image\r\n try:\r\n plt.colorbar().remove()\r\n except:\r\n pass\r\n \r\n #Select the same class explained on the figures above.\r\n ind = explanation.top_labels[0]\r\n\r\n #Map each explanation weight to the corresponding superpixel\r\n dict_heatmap = dict(explanation.local_exp[ind])\r\n heatmap = np.vectorize(dict_heatmap.get)(explanation.segments)\r\n \r\n plt.imshow(heatmap, cmap = 'RdBu', vmin = -heatmap.max(), vmax = heatmap.max())\r\n plt.savefig('algo_1_lime_' + str(start + i) + '_1.png', bbox_inches='tight', pad_inches=0)\r\n\r\nif __name__ == '__main__':\r\n \r\n # load pre-trained model and choose two images to explain\r\n trainI = [[0]*4096]\r\n trainO = [[0]*2]\r\n\r\n model = tf.keras.models.load_model('carTest_model')\r\n\r\n run_lime(400, 405, model)\r\n run_lime(800, 805, model)\r\n","sub_path":"AI/CAR_test_202102/algo_1_lime.py","file_name":"algo_1_lime.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"150229211","text":"'''\n\nBuildMaze class\n\nspecialList: List of nodes that are traps or that contain fees.\nstart: Starting position for the Agent\nexit: Exit position for the Agent\n\n'''\nimport math\nfrom Node import Node\n\nclass BuildMaze:\n def __init__(self):\n self.specialList = []\n\n with open('input2.txt', 'r') as f:\n startPos = f.readline()\n exitPos = f.readline()\n sandsPos = f.readline()\n spiderPos = f.readline()\n feePos = f.readline()\n\n temp = ParseCoordinates(startPos) \n for coordinate in temp:\n self.start = Node(coordinate.x, coordinate.y)\n\n temp = ParseCoordinates(exitPos)\n for coordinate in temp:\n self.exit = Node(coordinate.x, coordinate.y) \n\n temp = ParseCoordinates(sandsPos)\n for coordinate in temp:\n tempNode = Node(coordinate.x, coordinate.y)\n tempNode.specialValue = math.inf\n self.specialList.append(tempNode)\n\n temp = ParseCoordinates(spiderPos)\n temp = BuildSpiderNets(temp)\n for coordinate in temp:\n tempNode = Node(coordinate.x, coordinate.y)\n tempNode.specialValue = math.inf\n self.specialList.append(tempNode)\n\n temp = ParseFee(feePos)\n for fee, node in temp:\n node.fee = fee\n self.specialList.append(node)\ndef ParseCoordinates(coordinates):\n coordinates = coordinates.split()\n tempNodeList = []\n for item in coordinates:\n temp = list(map(int, item.strip('()').split(',')))\n tempNodeList.append(Node(temp[0], temp[1]))\n \n return tempNodeList\n\ndef ParseFee(feePos):\n feePos = feePos.split()\n feeList = []\n \n for item in feePos:\n item = item.split(':')\n tempList = ParseCoordinates(item[1])\n tempList.insert(0, int(item[0]))\n feeList.append(tempList)\n\n return feeList\n\ndef BuildSpiderNets(nodeList):\n spiderNetList = nodeList[:]\n for node in nodeList:\n retNodes = node.GenerateChildren()\n for item in retNodes:\n spiderNetList.append(item)\n \n return spiderNetList","sub_path":"BuildMaze.py","file_name":"BuildMaze.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"78669426","text":"import sys\nimport os\n\nimport cv2\nimport sklearn\nimport sklearn.model_selection\nimport sklearn.decomposition as sdecomp\nimport sklearn.ensemble\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\nprint('[LOG] Loading labels')\nf = open('pylabels.txt', 'r')\nlns = f.readlines()\nf.close()\n\nsim_labels = eval(lns[0])\n# print('Sim labels', sim_labels)\n\nf = None\nlns = None\n\nprint('[LOG] Loading all images into memory')\n\navg_row_weights = np.arange(1,51)\ndef avg_row_dark(img):\n def calc_row(row):\n return (row*avg_row_weights).sum() / row.sum()\n tf = np.max(img) - img\n return np.asarray([calc_row(r) for r in tf])\n\ndef label_to_cat(lbl):\n if lbl == [1,0]:\n return 0\n if lbl == [0,1]:\n return 1\n else:\n return 2 # neither exclusively left nor right\n\navg_dark_data = []\nlabels = []\n\nfor sim_no in range(1,100):\n print('Loading: sim', sim_no)\n category = label_to_cat(sim_labels[sim_no-1])\n if category == 2:\n continue\n\n for step in range(30,200):\n img = cv2.imread(\n 'processed/{}/{}.jpg'.format(sim_no,step),\n cv2.IMREAD_GRAYSCALE)\n img = img.reshape(50,50)\n\n avg_dark_data.append(avg_row_dark(img))\n labels.append(category)\n\n# convert everything into numpy-land\navg_dark_data = np.asarray(avg_dark_data)\nlabels = np.asarray(labels)\n\n# PCA\npca = sdecomp.PCA(n_components=7)\npca.fit(avg_dark_data)\nreduced_data = pca.transform(avg_dark_data)\n\ntrain_x, test_x, train_y, test_y = sklearn.model_selection.train_test_split(\n reduced_data, labels, test_size=0.3, random_state=42)\n\nmodel = sklearn.ensemble.RandomForestClassifier(\n n_estimators=500, oob_score=True, criterion='entropy')\nmodel = model.fit(train_x, train_y)\n\nimport sklearn.metrics as sm\npreds = model.predict(test_x)\nprint('Accuracy: ', sm.accuracy_score(preds, test_y))\nprint('Precision: ', sm.precision_score(preds, test_y))\n\ndef plot_feature_importances(forest, path):\n importances = forest.feature_importances_\n std = np.std([tree.feature_importances_ for tree in forest.estimators_], axis=0)\n indices = np.argsort(importances)[::-1]\n plt.figure()\n plt.title(\"Feature importances\")\n plt.bar(range(7), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(range(7), indices)\n plt.xlim([-1, 7])\n plt.savefig(path)\n plt.close()\n\nplot_feature_importances(model, 'figs/classical/rf_pca_importance.png')\n\n","sub_path":"modelpy/random-forest-pca.py","file_name":"random-forest-pca.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"67672005","text":"# 목적:\r\n# WPCN에서 HAP(=drone)의 위치와 충전 시간 할당 방법을 최적화한다.\r\n# 논문: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=7337464\r\n# Placement Optimization of Energy and Information Access Points in Wireless Powered Communication Networks\r\n# Suzhi Bi, Member, IEEE, and Rui Zhang, Senior Member, IEEE\r\n# Using Algorithm 5. Greedy algorithm for HAP placement optimization\r\n\r\n# map.txt의 구성:\r\n# (맵 세로길이) (맵 가로길이) (wireless device의 개수) (train 개수) (test 개수)\r\n\r\n# convex/concave function이므로 위치가 바뀜에 따라 THROUGHPUT의 값이 convex/concave하게 바뀜\r\n\r\nimport math\r\nimport random\r\nimport sys\r\nimport WPCN_helper_REAL_forPaper as WPCN_helper_REAL\r\n\r\n## find L2 norm of array\r\ndef L2norm(array):\r\n result = 0\r\n for i in range(len(array)): result += pow(array[i], 2)\r\n return math.sqrt(result)\r\n\r\n## add/subtract/mul/div array\r\n# option: 0(add), 1(subtract), 2(mul), 3(div)\r\ndef arrayOp(array0, array1, option):\r\n assert(len(array0) == len(array1))\r\n\r\n result = []\r\n for i in range(len(array0)):\r\n if option == 0: result.append(array0[i] + array1[i])\r\n elif option == 1: result.append(array0[i] - array1[i])\r\n elif option == 2: result.append(array0[i] * array1[i])\r\n elif option == 3: result.append(array0[i] / array1[i])\r\n return result\r\n\r\n# check if two arrays are equal\r\ndef arrayEqual(array0, array1):\r\n assert(len(array0) == len(array1))\r\n \r\n for i in range(len(array0)):\r\n if array0[i] != array1[i]: return False\r\n\r\n return True\r\n\r\n# distance\r\ndef distance(array0, array1):\r\n assert(len(array0) == len(array1))\r\n \r\n result = 0\r\n for i in range(len(array0)): result += pow(array0[i]-array1[i], 2)\r\n return math.sqrt(result)\r\n\r\n# Given j_k(b)'s, solve (20) for optimal AP placement vj*'s (=v1)\r\n# max(t, V^N)(t) s.t. Lk - a1,k - a2,k*||v_(j_k) - w_k||^dU >= t, k=1,...,K, b^l <= v_j <= b^h, j=1,...,N\r\n# that is, max(t, V^N)(t) s.t. Lk - a1,k - a2,k*||v_1 - w_k||^dU >= t, k=1,...,K, b^l <= v_1 <= b^h\r\n# -> t should be minimum value of Lk - a1,k - a2,k*||v_1 - w_k||^dU\r\n# -> So, the goal is to find \"the V^N that maximizes (min value of Lk - a1,k - a2,k*||v_1 - w_k||^dU)\"\r\n# **** None for NOT FEASIBLE ****\r\n\r\n# min value of Lk - a1,k - a2,k*||v_1k - w_k||^dU\r\ndef minOfT(L, a1, a2, w, dU, v1):\r\n K = len(L)\r\n \r\n result = L[0] - a1[0] - a2[0]*pow(L2norm(arrayOp(v1, w[0], 1)), dU)\r\n for k in range(1, K): result = min(result, L[k] - a1[k] - a2[k]*pow(L2norm(arrayOp(v1, w[k], 1)), dU))\r\n\r\n return result\r\n\r\n# main function for find optimal v1 using Gradient Descent Method\r\ndef findMaxV(L, a1, a2, w, dU, v1):\r\n K = len(L)\r\n\r\n # find optimal v1 using Gradient Descent Method\r\n lr = 300000000.0\r\n for i in range(7000): # 7000 iterations\r\n minOfTgivenV1 = minOfT(L, a1, a2, w, dU, v1) # minOfT by this v1\r\n\r\n v1_0 = [v1[0]+0.000001, v1[1]] # add 1.0e-6 to 1st element\r\n v1_1 = [v1[0], v1[1]+0.000001] # add 1.0e-6 to 2nd element\r\n minOfTgivenV1_0 = minOfT(L, a1, a2, w, dU, v1_0) # minOfT by v1_0\r\n minOfTgivenV1_1 = minOfT(L, a1, a2, w, dU, v1_1) # minOfT by v1_1\r\n\r\n # if i < 100 or i % 50 == 0: print(i, v1, minOfTgivenV1)\r\n\r\n # update v\r\n v1[0] += lr * (minOfTgivenV1_0 - minOfTgivenV1)\r\n v1[1] += lr * (minOfTgivenV1_1 - minOfTgivenV1)\r\n\r\n return v1\r\n\r\n## return a Feasible Solution of Problem (25) in the paper\r\n# max(t, u)t s.t. (t + u - L) * ||u-wk||^dD <= p\r\n# where k in {W1 U W2 U ... U Wi} = {W1} because there is only 1 HAP, u^l <= u_i(=u_1) <= u^h\r\n# where u_i,k = min(u_(i-1),k, a1,k+a2,k*||ui-wk||^dU)\r\n# -> u_1,k = min(u_0,k, a1,k+a2,k*||u1-wk||^dU)\r\n\r\n## using Algorithm 3. Trial-and-error method for N AP placement\r\n# input: K WD locations and 1 EN locations\r\n# output: locations of N APs [v1, ..., vN]\r\ndef feasibleSol(wdList_, HAPloc_, L, a1, a2, dU):\r\n K = len(wdList_)\r\n \r\n # Separate WDs into N cluster, and place each AP at a cluster center\r\n # use vj(0)'s to denote initial AP locations\r\n # -> no need to separate because the number of EN is 1\r\n \r\n v1 = [0, 0] # vj(0)'s (=v1) -> initialize as all 0's\r\n\r\n L = [] # values of Lk where k=1,...,K\r\n w = [] # values of wk where k=1,...,K (location of WD k)\r\n for k in range(K): w.append(wdList_[k])\r\n u = HAPloc_ # value of ui when i=1,2,...,M -> value of u1 (i=1) -> location of HAP\r\n\r\n # reference: VI. Simulation Results\r\n n = 0.51 # harvesting circuit efficiency (1.0 in report/200219_WPCN.pptx)\r\n Ad = [] # downlink antenna power gain for each WD k (hi = gi = 0.001 * 1.0^2 * d^(-2) = 0.001*d^(-2) in report/200219_WPCN.pptx)\r\n for k in range(K): Ad.append(3.0)\r\n fd = 915000000 # carrier frequency (915 MHz)\r\n P0 = 1.0 # transmit power (20.0 in report/200219_WPCN.pptx)\r\n dD = 2.2 # dD >= 2 denotes the path loss exponent in DL\r\n b = [] # b = [Ad*(3*10^8)/(4*PI*fd)]^dD for each WD k\r\n for k in range(K): b.append(Ad[k]*pow(300000000/(4*3.141592654*fd), dD))\r\n\r\n # With vj(0)'s, calculate j_k(b)'s using (6)\r\n jb = [] # j_k(b)'s for each k\r\n for k in range(K):\r\n jb.append(1) # j_k = argmin(j=1,...,N)||vj-wk||, k=1,...,K = argmin(j=1)||vj-wk|| = 1\r\n\r\n # With ui's, calculate Lk's using (5). (flag = 1)\r\n # Lk = n*b*P0*Sum(i=1,M)||ui-wk||^-dD, k=1,...,K\r\n # = n*b*P0*||u1-wk||^-dD, k=1,...,K because i=1\r\n for k in range(K): L.append(n * b[k] * P0 * pow(L2norm(arrayOp(u, w[k], 1)), -dD))\r\n flag = 1\r\n\r\n while flag == 1:\r\n \r\n # Given j_k(b)'s, solve (20) for optimal AP placement vj*'s (=v1)\r\n # max(t, V^N)(t) s.t. Lk - a1,k - a2,k*||v_(j_k) - w_k||^dU >= t, k=1,...,K, b^l <= v_j <= b^h, j=1,...,N\r\n v1op = findMaxV(L, a1, a2, w, dU, v1)\r\n\r\n # Given vj*'s (=v1), calculate j_k(a)'s using (6)\r\n ja = [] # j_k(a)'s for each k\r\n for i in range(K):\r\n ja.append(1) # j_k = argmin(j=1,...,N)||vj-wk||, k=1,...,K = argmin(j=1)||v1-wk|| = 1\r\n\r\n # check if j_k(a) == j_k(b) for all k\r\n jabSame = [] # jabSame[i] = True if and only if j_a[i] == j_a[b], otherwise False\r\n for i in range(K):\r\n if arrayEqual(ja, jb): jabSame.append(True)\r\n else: jabSame.append(False)\r\n\r\n # if j_k(a) != j_k(b) for some k, update j_k(b) = j_k(a) for k=1,2,...,K\r\n localOptFound = True # local optimum is found if and only if j_k(a) == j_k(b) for all k\r\n for k in range(K):\r\n if jabSame[k] == False: # j_k(a) != j_k(b) for some k\r\n jb[k] = ja[k]\r\n localOptFound == False\r\n\r\n # a local optimum is found, then return optimal vj*'s = v1op\r\n if localOptFound == True:\r\n flag = 0\r\n return v1op\r\n\r\n# 진행\r\n# K : LB <- -K, UB -> K where K is sufficiently large\r\n# et : error tolerance\r\ndef run(size, numTrain, numTest, numWD, deviceName, K, et):\r\n \r\n # 입력 정보\r\n originalScreen = [] # 각 맵의 스크린\r\n wdList = [] # 각 맵에서 wireless device의 위치를 저장한 배열, [[wd0Y, wd0X], [wd1Y, wd1X], ..., [wd(n-1)Y, wd(n-1)X]]\r\n\r\n # 평가 결과 저장\r\n RL = []\r\n\r\n # 1. 테스트용 맵 생성\r\n # 맵의 구성: .(공간), H(HAP), W(wireless device)\r\n if readOrWrite == 1: # 맵 파일을 쓰고 그 맵으로 테스트\r\n print('generating maps...')\r\n for i in range(numTest):\r\n initScreen_ = WPCN_helper_REAL.initScreen(size, False)\r\n \r\n originalScreen.append(initScreen_[0])\r\n wdList.append(initScreen_[2])\r\n\r\n # 맵 파일 작성\r\n f = open('originalMaps_' + str(size) + '_' + str(numWD) + '/DL_WPCN_' + ('0' if i < 1000 else '') + ('0' if i < 100 else '') + ('0' if i < 10 else '') + str(i) + '.txt', 'w')\r\n for j in range(size):\r\n for k in range(size):\r\n if originalScreen[i][j][k] == -1: f.write('W') # wireless device\r\n elif originalScreen[i][j][k] == 0: f.write('.') # space\r\n elif originalScreen[i][j][k] == 1: f.write('H') # HAP (not exist in the original map)\r\n f.write('\\n')\r\n f.close()\r\n \r\n else: # 기존 맵 파일 읽어서 기존 맵으로 테스트\r\n print('reading maps...')\r\n for i in range(numTrain, numTrain+numTest):\r\n f = open('originalMaps_' + str(size) + '_' + str(numWD) + '/DL_WPCN_' + ('0' if i < 1000 else '') + ('0' if i < 100 else '') + ('0' if i < 10 else '') + str(i) + '.txt', 'r')\r\n map_ = f.readlines() # 맵을 나타낸 배열\r\n f.close()\r\n \r\n for j in range(len(map_)): map_[j] = map_[j].replace('\\n', '') # 각 줄마다 개행문자 제거\r\n\r\n # originalScreen과 wdList 읽어오기\r\n wdListTemp = []\r\n thisScreen = [[0] * size for j in range(size)] # originalScreen에 추가할 맵(스크린)\r\n for j in range(size):\r\n for k in range(size):\r\n if map_[j][k] == 'W':\r\n thisScreen[j][k] = -1 # wireless device\r\n wdListTemp.append([j, k]) # wdListTemp에 추가\r\n elif map_[j][k] == '.': thisScreen[j][k] = 0 # space\r\n elif map_[j][k] == 'H': thisScreen[j][k] = 1 # HAP (not exist in the original map)\r\n \r\n originalScreen.append(thisScreen)\r\n wdList.append(wdListTemp)\r\n\r\n # 2~3. 논문에 나온 방법대로 실험 및 테스트\r\n while True:\r\n\r\n optiInfo = open('optiInfoForMap/optiInfoForMap_' + str(problemNo) + '_forPaper_' + str(size) + '_' + str(numWD) + '.txt', 'r')\r\n optiInformation = optiInfo.readlines()\r\n optiInfo.close()\r\n\r\n savePrint = ''\r\n saveResult = ''\r\n\r\n print('testing...')\r\n\r\n # 2. 실험 및 테스트\r\n for mode in range(1):\r\n\r\n sumTestThroughput = 0.0 # test throughput의 합계\r\n sumCorrectMaxThroughput = 0.0 # 정답의 throughput의 합계 (training data를 생성할 때와 같은 방법으로 최대 throughput 확인)\r\n\r\n if mode == 0:\r\n print(' < ORIGINAL >')\r\n savePrint += '< mode 0: original >\\n'\r\n saveResult += '< mode 0: original >\\n'\r\n elif mode == 1:\r\n print(' < ROUNDING >')\r\n savePrint += '\\n< mode 1: rounding >\\n'\r\n saveResult += '\\n< mode 1: rounding >\\n'\r\n \r\n for i in range(numTest):\r\n\r\n uStar = None # initialize solution u0*\r\n\r\n # 2-0. HAP의 최적의 x, y좌표 (optiX_test, optiY_test) 구하기\r\n\r\n # list of wireless device in i-th test data (in the form of [[wd0Y, wd0X], [wd1Y, wd1X], ..., [wd(n-1)Y, wd(n-1)X]])\r\n wdList_ = wdList[i]\r\n if i < 10: print('wdList of map ' + str(i) + ' : ' + str(wdList_))\r\n\r\n # count of wireless device in i-th test data\r\n wdCount = len(wdList_)\r\n\r\n # do not have to cluster wireless devices because the number of HAP is 1\r\n # for i=1 to M do : do not use because M=1\r\n\r\n L = [] # value of L0,0, L0,1, ..., L0,(n-1)\r\n U = [] # value of U0,0, U0,1, ..., U0,(n-1)\r\n a1 = [] # value of a1,0, a1,1, ..., a1,(n-1) (constant circuit power of WD k)\r\n a2 = [] # value of a2,0, a2,1, ..., a2,(n-1) (parameter related to transmission strategy used in UL communication)\r\n dU = 2.5 # UL channel path loss exponent\r\n HAPloc_ = [0.5, 0.5] # location of HAP (initialized as (0.5, 0.5))\r\n\r\n # append a1,0 and a2,0 values for each WD - reference: VI. Simulation Results\r\n for k in range(len(wdList_)):\r\n a1.append(0.00005)\r\n a2.append(0.0000014)\r\n\r\n assumption = [] # 0 if (a) is TRUE, and 1 if (b) is TRUE\r\n\r\n # Using Algorithm 5. Greedy algorithm for HAP placement optimization\r\n # value of i is always 1 because there is only 1 HAP\r\n for j in range(len(wdList_)):\r\n \r\n # Update L(i-1),k and U(i-1),k using (19) and (24) where i=1 -> L0,k and U0,k\r\n L.append(0)\r\n U.append(2147483647) # infinite\r\n\r\n StopFlag = 0\r\n \r\n while True:\r\n \r\n # LB <- -K, UB -> K where K is sufficiently large\r\n LB = -K\r\n UB = K\r\n\r\n while True:\r\n t = (UB + LB)/2 # ti <- (UB+LB)/2\r\n \r\n # Given ti, convert (25) into convex problem using procedures in Section V.B\r\n # find feasible solutions of the convex problem: solution of (25)\r\n sol = feasibleSol(wdList_, HAPloc_, L, a1, a2, dU) # using Algorithm 3: Trial-and-error method for N AP placement\r\n \r\n if sol != None: # Problem (25) is feasible given t:\r\n LB = t\r\n uStar = sol\r\n else:\r\n print(LB, UB)\r\n UB = t\r\n\r\n if abs(UB-LB) < et: break\r\n\r\n # check if all K assumptions are valid\r\n # Assume WD k satisfies condition (a) or (b)\r\n countA = 0 # (a) u(i-1)k < a1,k + a2,k*||ui* - wk||^dU is TRUE\r\n countB = 0 # (b) u(i-1)k >= a1,k + a2,k*||ui* - wk||^dU is TRUE\r\n\r\n # check for assumptions for each wireless device\r\n assumption = [] # initialize assumption array\r\n \r\n for k in range(len(wdList_)):\r\n \r\n # (a) u(i-1)k < a1,k + a2,k||ui* - wk||^dU\r\n # (a) u0k < a1,k + a2,k||u0* - wk||^dU because there is only 1 HAP\r\n if U[k] < a1[k] + a2[k]*pow(L2norm(arrayOp(uStar, wdList_[k], 1)), dU):\r\n assumption.append(0)\r\n countA += 1\r\n \r\n # (b) u(i-1)k >= a1,k + a2,k||ui* - wk||^dU\r\n # (b) u0k >= a1,k + a2,k||u0* - wk||^dU because there is only 1 HAP\r\n else:\r\n assumption.append(1)\r\n countB += 1 \r\n\r\n # set StopFlag 1 when all K assumptions are valid\r\n if countA == 0 or countB == 0: # all K assumptions are valid:\r\n StopFlag = 1\r\n\r\n [optiY_test, optiX_test] = [uStar[0], uStar[1]] # i-th HAP location = ui* (only 1 HAP -> u0*)\r\n\r\n else:\r\n StopFlag = 0\r\n \r\n # For each WD violating the assumption, switch the assumption from (a) to (b) or (b) to (a)\r\n countA = len(wdList_)\r\n countB = 0\r\n for j in range(len(wdList_)): assumption[j] = 1 # switch (a) to (b)\r\n\r\n if StopFlag == 1: break\r\n\r\n # 2-1. 테스트 결과 받아오기\r\n (throughput, HAPtime) = WPCN_helper_REAL.getThroughput(wdList_, uStar, size, problemNo)\r\n sumTestThroughput += throughput\r\n testScreen = originalScreen[i] # 테스트할 스크린\r\n\r\n # 2-2. testScreen과 optiScreen 중 일부 출력\r\n if i < 10: # 처음 10개의 map에 대해서만 출력\r\n # testScreen 출력\r\n print(' --- test input screen for map ' + str(i) + ' ---')\r\n toPrint = ''\r\n for j in range(size):\r\n toPrint += '['\r\n for k in range(size):\r\n if testScreen[j][k] == -1: toPrint += 'W '\r\n else: toPrint += '. '\r\n toPrint += ']\\n'\r\n print(toPrint)\r\n\r\n # 2-3. 정답과 비교\r\n # 최적의 HAP의 위치 및 할당 시간 찾기\r\n # HAP의 위치 및 할당 시간에 따른 throughput의 최댓값\r\n correctMaxThroughput = float(optiInformation[(numTrain + i) * (size + 1)].split(' ')[5])\r\n sumCorrectMaxThroughput += correctMaxThroughput\r\n\r\n # 정답과 비교\r\n printForThis = ('test throughput for map ' + str(i) + ' [Y=' + str(round(optiY_test, 3)) + ' X=' + str(round(optiX_test, 3)) + ' HT=' + str(HAPtime) + '] : '\r\n + str(round(throughput, 6)) + ' / ' + str(round(correctMaxThroughput, 6)) + ' ('\r\n + str(round(100.0 * throughput / correctMaxThroughput, 6)) + ' %)')\r\n print(printForThis)\r\n savePrint += printForThis + '\\n'\r\n if i < 10: print('')\r\n \r\n # 3. 평가\r\n percentage = round(100.0 * sumTestThroughput / sumCorrectMaxThroughput, 6)\r\n print('size:' + str(size) + ' test:' + str(numTest)\r\n + ' problem(0=Sum,1=Common):' + str(problemNo))\r\n print('total test throughput: ' + str(round(sumTestThroughput, 6)))\r\n print('total max throughput: ' + str(round(sumCorrectMaxThroughput, 6)))\r\n print('percentage : ' + str(percentage) + ' %')\r\n\r\n RL.append([size, numTest, problemNo, percentage])\r\n\r\n # 현��까지의 평가 결과 출력\r\n print('\\n <<< ESTIMATION RESULT >>>')\r\n print('No.\\tsize\\ttest\\tproblem\\tpercentage')\r\n\r\n saveResult += '\\n <<< ESTIMATION RESULT >>>\\nNo.\\tsize\\ttest\\tproblem\\tpercentage\\n'\r\n \r\n for i in range(len(RL)):\r\n toPrint = (str(i) + '\\t' + str(RL[i][0]) + '\\t' + str(RL[i][1]) + '\\t'\r\n + str(RL[i][2]) + '\\t' + (' ' if round(RL[i][3], 4) < 10.0 else '') + str(round(RL[i][3], 4)))\r\n print(toPrint)\r\n saveResult += (toPrint + '\\n')\r\n print('\\n')\r\n\r\n # 평가 결과 저장\r\n fSave = open('DL_WPCN_result_' + str(problemNo) + '_paper_forPaper' + '_' + str(size) + '_' + str(numWD) + '_K=' + str(K) + '_et=' + str(et) + '.txt', 'w')\r\n fSave.write(saveResult)\r\n fSave.close()\r\n\r\n fSavePrint = open('DL_WPCN_result_' + str(problemNo) + '_paper_forPaper' + '_' + str(size) + '_' + str(numWD) + '_K=' + str(K) + '_et=' + str(et) + '_print.txt', 'w')\r\n fSavePrint.write(savePrint)\r\n fSavePrint.close()\r\n\r\n # 학습 및 테스트 종료\r\n break\r\n\r\n# main\r\nif __name__ == '__main__':\r\n\r\n # 사용자 입력\r\n problemNo = int(input('0->sum throughtput maximization, 1->common throughtput maximization'))\r\n readOrWrite = int(input('0->read files, 1->create new files'))\r\n\r\n # 0. 파일을 읽어서 size 값과 train 개수, test 개수 구하기\r\n # 파일 형식 : (맵 세로길이) (맵 가로길이) (wireless device의 개수) (train 개수) (test 개수)\r\n # train 개수: 트레이닝할 데이터(맵)의 개수\r\n # test 개수 : 테스트할 데이터(맵)의 개수\r\n file = open('map.txt', 'r')\r\n read = file.readlines()\r\n file.close()\r\n deviceName = input('device name (for example, cpu:0 or gpu:0)')\r\n\r\n # 각 line의 configuration에 대하여 각각 실험\r\n for i in range(len(read)):\r\n readSplit = read[i].split(' ')\r\n \r\n height = int(readSplit[0]) # 맵의 세로길이 (= 가로길이 = size)\r\n size = height\r\n numWD = int(readSplit[2]) # wireless device의 개수\r\n numTrain = int(readSplit[3]) # 트레이닝할 데이터(맵)의 개수 (실제로는 트레이닝하지 않으며 파일 인덱싱에 사용됨)\r\n numTest = int(readSplit[4]) # 테스트할 데이터(맵)의 개수\r\n\r\n # RUN!\r\n for K in [10, 20, 40]: # for each K value\r\n for et in [0.00001, 0.000001, 0.0000001]: # for each error tolerance\r\n run(size, numTrain, numTest, numWD, deviceName, K, et)\r\n","sub_path":"WPCN/WPCN_paper_forPaper_option.py","file_name":"WPCN_paper_forPaper_option.py","file_ext":"py","file_size_in_byte":20558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"315536621","text":"from sqlalchemy.inspection import inspect\n\nfrom .exceptions import BadQuery, FieldNotFound, BadSpec\n\n\nclass Field(object):\n\n def __init__(self, model, field_name):\n self.model = model\n self.field_name = field_name\n\n def get_sqlalchemy_field(self):\n if self.field_name not in inspect(self.model).columns.keys():\n raise FieldNotFound(\n 'Model {} has no column `{}`.'.format(\n self.model, self.field_name\n )\n )\n return getattr(self.model, self.field_name)\n\n\ndef get_query_models(query):\n \"\"\"Get models from query.\n\n :param query:\n A :class:`sqlalchemy.orm.Query` instance.\n\n :returns:\n A dictionary with all the models included in the query.\n \"\"\"\n models = [col_desc['entity'] for col_desc in query.column_descriptions]\n models.extend(mapper.class_ for mapper in query._join_entities)\n return {\n model.__name__: model for model in models\n }\n\n\ndef get_model_from_spec(spec, query):\n \"\"\" Determine the model to which a spec applies on a given query.\n\n A spec that does not specify a model may be applied to a query that\n contains a single model. Otherwise the spec must specify the model to\n which it applies, and that model must be present in the query.\n\n :param query:\n A :class:`sqlalchemy.orm.Query` instance.\n\n :param spec:\n A dictionary that may or may not contain a model name to resolve\n against the query.\n\n :returns:\n A model instance.\n\n :raise BadSpec:\n If the spec is ambiguous or refers to a model not in the query.\n\n :raise BadQuery:\n If the query contains no models.\n\n \"\"\"\n models = get_query_models(query)\n if not models:\n raise BadQuery('The query does not contain any models.')\n\n model_name = spec.get('model')\n if model_name is not None:\n models = [v for (k, v) in models.items() if k == model_name]\n if not models:\n raise BadSpec(\n 'The query does not contain model `{}`.'.format(model_name)\n )\n model = models[0]\n else:\n if len(models) == 1:\n model = list(models.values())[0]\n else:\n raise BadSpec(\n \"Ambiguous spec. Please specify a model.\"\n )\n\n return model\n","sub_path":"sqlalchemy_filters/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"194043875","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 25 01:20:58 2018\r\n\r\n@author: Chieh-Hsu Yang\r\n\"\"\"\r\n\r\nimport os\r\nimport shutil\r\nimport time\r\nimport pandas as pd\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\n\r\n# Today's date\r\ndate_label = time.strftime('%Y%m%d')\r\n\r\ntry:\r\n #local\r\n os.chdir('C:\\\\Users\\\\User\\\\Desktop\\\\0047Automate_Script\\\\DLpack_Overstock\\\\')\r\nexcept:\r\n #0047\r\n os.chdir('N:\\\\E Commerce\\\\Public Share\\\\Dot Com - Overstock\\\\Q&A\\\\temp_DL_file\\\\')\r\n\r\n#storage Directory\r\nif 'Desktop\\\\0047Automate_Script' in os.getcwd():\r\n driver_path = 'C:\\\\Users\\\\User\\\\Anaconda3\\\\chrome\\\\chromedriver.exe'\r\n work_dir = 'C:\\\\Users\\\\User\\\\Desktop\\\\0047Automate_Script\\\\DLpack_Overstock\\\\'\r\n temp_dir = 'C:\\\\Users\\\\User\\\\Desktop\\\\0047Automate_Script\\\\DLpack_Overstock\\\\temp_DL_file\\\\'\r\n Download_dir = 'C:\\\\Users\\\\User\\\\Desktop\\\\0047Automate_Script\\\\DLpack_Overstock\\\\'\r\nelse: \r\n driver_path = 'C:\\\\Users\\\\raymond.hung\\\\chrome\\\\chromedriver.exe'\r\n work_dir = 'C:\\\\Users\\\\raymond.hung\\\\Documents\\\\Automate_Script\\\\DLpack_Overstock\\\\'\r\n temp_dir = 'N:\\\\E Commerce\\\\Public Share\\\\Dot Com - Overstock\\\\Q&A\\\\temp_DL_file\\\\'\r\n Download_dir = 'N:\\\\E Commerce\\\\Public Share\\\\Dot Com - Overstock\\\\Q&A\\\\'\r\n\r\nos.chdir(temp_dir)\r\n\r\n# Account and Password\r\nlogin_info = pd.read_csv(work_dir+ 'Account & Password.csv',index_col=0)\r\nusername = login_info.loc['Account', 'CONTENT']\r\npassword = login_info.loc['Password', 'CONTENT']\r\n\r\n# Chrome driver setting\r\noptions = webdriver.ChromeOptions()\r\noptions.add_argument(\"--start-maximized\")\r\nprefs = {'download.default_directory' : temp_dir}\r\noptions.add_experimental_option(\"prefs\", prefs)\r\ndriver = webdriver.Chrome(driver_path,chrome_options=options)\r\n \r\n# Supplier Oasis website turn into login page\r\nSupplier_Oasis = 'https://www.supplieroasis.com/Pages/default.aspx'\r\ndriver.get(Supplier_Oasis)\r\n\r\n# Wait for click Sign In button\r\nfor i in range(5):\r\n try:\r\n LoadingChecker = (By.LINK_TEXT, 'Sign In')\r\n WebDriverWait(driver, 120).until(EC.presence_of_element_located(LoadingChecker))\r\n driver.find_element_by_link_text('Sign In').click()\r\n break\r\n except:\r\n driver.refresh()\r\n if i == 2:\r\n driver.quit()\r\n driver = webdriver.Chrome(driver_path,chrome_options=options)\r\n Supplier_Oasis = 'https://www.supplieroasis.com/Pages/default.aspx'\r\n driver.get(Supplier_Oasis)\r\n\r\nfor i in range(5):\r\n try:\r\n LoadingChecker = (By.ID, 'ContentPlaceHolder1_SubmitButton')\r\n WebDriverWait(driver, 120).until(EC.presence_of_element_located(LoadingChecker))\r\n # Input username and password and login\r\n driver.find_element_by_id('ContentPlaceHolder1_UsernameTextBox').send_keys(username)\r\n driver.find_element_by_id('ContentPlaceHolder1_PasswordTextBox').send_keys(password)\r\n driver.find_element_by_id('ContentPlaceHolder1_SubmitButton').click()\r\n time.sleep(5)\r\n break\r\n except:\r\n driver.refresh()\r\n\r\nfor i in range(5):\r\n try:\r\n # Turn to Report page\r\n driver.get('https://edge.supplieroasis.com/partner-reports')\r\n \r\n LoadingChecker = (By.PARTIAL_LINK_TEXT, 'Product Dashboard')\r\n WebDriverWait(driver, 60).until(EC.presence_of_element_located(LoadingChecker))\r\n # Scroll to bottum and get the Product Dashboard href\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n driver.get(driver.find_element_by_partial_link_text('Product Dashboard').get_attribute('href'))\r\n time.sleep(30)\r\n break\r\n\r\n except:\r\n driver.refresh()\r\n \r\nfor i in range(5):\r\n try:\r\n # Click Product Questions & Answers\r\n LoadingChecker = (By.XPATH, '//*[@k=\"W858\"]')\r\n WebDriverWait(driver, 120).until(EC.presence_of_element_located(LoadingChecker))\r\n driver.find_element_by_xpath('//*[@k=\"W858\"]').click()\r\n time.sleep(10)\r\n break\r\n except:\r\n driver.refresh()\r\n time.sleep(10)\r\n\r\n# Shift to Q&A tab\r\nQA_page = driver.window_handles[-1]\r\ndriver.switch_to_window(QA_page)\r\n\r\n# Click dropdown menus then download excel file\r\ntry: \r\n LoadingChecker = (By.CSS_SELECTOR, '.mstrmojo-HBox-cell.mstrmojo-ToolBar-cell')\r\n WebDriverWait(driver, 120).until(EC.element_to_be_clickable(LoadingChecker))\r\n driver.find_elements_by_css_selector('.mstrmojo-HBox-cell.mstrmojo-ToolBar-cell')[0].click()\r\n time.sleep(5)\r\n driver.find_elements_by_css_selector('.mstrmojo-CMI-text')[1].click()\r\nexcept:\r\n LoadingChecker = (By.CLASS_NAME, 'tbDown')\r\n WebDriverWait(driver, 120).until(EC.element_to_be_clickable(LoadingChecker))\r\n driver.find_elements_by_class_name('tbDown')[0].click()\r\n time.sleep(5)\r\n driver.find_elements_by_class_name('cmd4')[0].click()\r\n \r\ntime.sleep(30)\r\n\r\ndriver.quit()\r\n\r\nshutil.move('Product Page Q & A.xlsx', Download_dir+'Product Page Q & A '+date_label+'.xlsx')\r\n","sub_path":"DL_OS_ProductQA.py","file_name":"DL_OS_ProductQA.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"41281415","text":"from spidev import SpiDev\nimport time\nimport RPi.GPIO as GPIO\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(6, GPIO.OUT)\n\nspi = SpiDev()\nspi.open(0, 0)\nspi.max_speed_hz = 390000\n\nprint(\"Flashlight to waitstate\")\n#string_to_send = \"state;1\\n\"\nstring_to_send = \"shot;1\\n\"\nstring_to_bytes = str.encode(string_to_send)\nGPIO.output(6, 1)\ntime.sleep(0.01)\nspi.xfer(string_to_bytes)\nGPIO.output(6, 0)\ntime.sleep(1)\nGPIO.cleanup()\n","sub_path":"Functions/InputsOutputs/old/spi_test.py","file_name":"spi_test.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"396459882","text":"from django.conf.urls import url\n\nfrom views import (\n\tGoalDetailView, GoalUpdateView, goal_delete, goal_add_me\n)\n\nurlpatterns = [\n url(r'detail/(?P[\\d]+)/$', GoalDetailView.as_view(), name='detail'),\n url(r'update/(?P[\\d]+)/$', GoalUpdateView.as_view(), name='update'),\n url(r'delete/(?P[\\d]+)/$', goal_delete, name='delete'),\n url(r'add_me/(?P[\\d]+)/$', goal_add_me, name='add_me'),\n]\n","sub_path":"goal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"156048096","text":"class Solution(object):\n def candy(self, ratings):\n \"\"\"\n :type ratings: List[int]\n :rtype: int\n \"\"\"\n left = [1 for i in range(len(ratings))]\n right = [1 for i in range(len(ratings))]\n\n for index, rating in enumerate(ratings[1:], 1):\n if rating > ratings[index-1]:\n left[index] = left[index-1] + 1\n\n for i in range(len(ratings)-2, -1, -1):\n if ratings[i] > ratings[i+1]:\n right[i] = right[i+1] + 1\n\n print(left)\n print(right)\n\n print([max(left[i],right[i]) for i in range(len(ratings))])\n return sum([max(left[i],right[i]) for i in range(len(ratings))])\n\n\ns = Solution()\ns.candy([5,3,1])","sub_path":"leetcode/algorithm/candy.py","file_name":"candy.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"97359848","text":"from ui.feature import Feature\nfrom ui.widget_generator import WidgetGenerator\n\nfrom system_info.dns_info import DNSInfo\nfrom system_info.hostname_info import HostnameInfo\nfrom system_info.network_info import InterfaceInfo\nfrom system_info.network_info import NetworkInfo\nfrom system_info.ntp_info import NTPInfo\nfrom system_setting.hostname_setting import HostnameSetting\nfrom system_setting.network_setting import NetworkCtrl\nfrom system_setting.network_setting import NetworkSetting\nfrom system_setting.ntp_setting import NtpCtrl\nfrom system_setting.ntp_setting import NtpSetting\n\nimport urwid\n\n\nclass SystemIdentification(Feature):\n def __init__(self, menu, content, footer):\n super(SystemIdentification, self).__init__(menu, content, footer)\n self.menu.add_menu_button('Network', self.set_content_widget)\n self.wg = WidgetGenerator(self.content.fieldmgr)\n self.hostnamehandler = HostnameHandler(self.wg)\n self.dnshandler = DNSHandler(self.wg)\n self.ntphandler = NTPHandler(self.wg)\n self.networkhandler = NetworkHandler(self.wg)\n\n def set_content_widget(self, b):\n self.display_system_identification()\n\n def __add_widget_to_content(self, widget_list):\n for widget in widget_list:\n self.content.add_widget(widget)\n\n def display_system_identification(self):\n self.content.clean_content_widget()\n # title\n self.content.add_widget(self.wg.gen_text('System Identification'))\n # hostname\n self.__add_widget_to_content(self.hostnamehandler.gen_hostname_setting_widgets())\n # DNS\n self.__add_widget_to_content(self.dnshandler.gen_dns_setting_widgets())\n # NTP\n self.__add_widget_to_content(self.ntphandler.gen_ntp_setting_widgets())\n self.content.add_widget(self.wg.gen_blank_line(2))\n # interface setting\n self.__add_widget_to_content(self.networkhandler.gen_network_setting_widgets())\n\n self.content.add_widget(self.wg.gen_blank_line())\n\n apply_btn = self.wg.gen_button(\"apply\", self.apply)\n reset_btn = self.wg.gen_button(\"reset\", self.reset)\n self.content.add_widget(self.wg.gen_apply_reset_line(apply_btn, reset_btn))\n\n def apply(self, b):\n try:\n self.hostnamehandler.set_hostname(self.content.fieldmgr)\n self.dnshandler.set_dnsserver(self.content.fieldmgr)\n self.ntphandler.set_ntpserver(self.content.fieldmgr)\n self.networkhandler.set_network(self.content.fieldmgr)\n self.footer.set_help_message('Success!')\n except Exception as e:\n self.footer.set_help_message(str(e))\n return\n\n self.display_system_identification()\n self.footer.set_help_message('')\n\n def reset(self, b):\n self.footer.set_help_message('')\n self.display_system_identification()\n\n\nclass HostnameHandler(object):\n def __init__(self, widget_generator):\n self.info = HostnameInfo()\n self.setting = HostnameSetting()\n self.wg = widget_generator\n\n def gen_hostname_setting_widgets(self):\n widgets = []\n widgets.append(self.wg.gen_text_field('Hostname', 'hostname', self.info.get_hostname()))\n return widgets\n\n def set_hostname(self, fieldmgr):\n old_hostname = self.info.get_hostname()\n new_hostname = fieldmgr.get_value('hostname')\n self.setting.set_hostname(old_hostname, new_hostname)\n\n\nclass DNSHandler(object):\n def __init__(self, widget_generator):\n self.info = DNSInfo()\n self.setting = NetworkSetting()\n self.wg = widget_generator\n\n def gen_dns_setting_widgets(self):\n widgets = []\n widgets.append(self.wg.gen_blank_line())\n for i in range(2):\n try:\n dns = self.info.get_dns_server()[i]\n except IndexError:\n dns = ''\n widgets.append(self.wg.gen_text_field('DNS Server%s' % (i + 1), 'dnsserver%s' % i, dns))\n return widgets\n\n def get_field_setting(self, fieldmgr):\n servers = []\n for i in range(2):\n if fieldmgr.get_value('dnsserver%s' % i) != '':\n servers.append(fieldmgr.get_value('dnsserver%s' % i))\n return servers\n\n def set_dnsserver(self, fieldmgr):\n dns_server = self.get_field_setting(fieldmgr)\n dns_config = self.setting.gen_dns_config(dns_server)\n self.setting.write_dns_config(dns_config)\n\n\nclass NTPHandler(object):\n def __init__(self, widget_generator):\n self.info = NTPInfo()\n self.setting = NtpSetting()\n self.wg = widget_generator\n\n def gen_ntp_setting_widgets(self):\n widgets = []\n widgets.append(self.wg.gen_blank_line())\n for i in range(2):\n try:\n ntp = self.info.get_ntp_server()[i]\n except IndexError:\n ntp = ''\n widgets.append(self.wg.gen_text_field('NTP Server%s' % (i + 1), 'ntpserver%s' % i, ntp))\n return widgets\n\n def get_field_setting(self, fieldmgr):\n servers = []\n for i in range(2):\n if fieldmgr.get_value('ntpserver%s' % i) != '':\n servers.append(fieldmgr.get_value('ntpserver%s' % i))\n return servers\n\n def set_ntpserver(self, fieldmgr):\n ntpctrl = NtpCtrl()\n ntp_server = self.get_field_setting(fieldmgr)\n ntp_config = self.setting.gen_ntp_config(ntp_server)\n self.setting.write_ntp_config(ntp_config)\n ntpctrl.restart()\n\n\nclass NetworkHandler(object):\n def __init__(self, widget_generator):\n self.info = NetworkInfo()\n self.setting = NetworkSetting()\n self.wg = widget_generator\n\n def get_interfaces_info(self):\n return self.info.get_interfaces_info(\n self.info.get_ethernet_device_names()\n )\n\n def gen_network_setting_widgets(self):\n widgets = []\n self.interfaces = self.get_interfaces_info()\n widgets.append(self.wg.gen_text('Ethernet device setting'))\n for interface in self.interfaces:\n widgets.append(self.gen_interface_info_form_widget(interface))\n widgets.append(self.wg.gen_blank_line(1))\n return widgets\n\n def gen_interface_info_form_widget(self, interface):\n device = interface.get_name()\n widgets = [\n self.wg.gen_text_uneditable_field('Device', device),\n self.wg.gen_text_uneditable_field('Mac_Address', interface.get_mac_address()),\n self.wg.gen_text_field('IP_Address', 'ip-address-%s' % device, interface.get_ip_address()),\n self.wg.gen_text_field('Netmask', 'netmask-%s' % device, interface.get_netmask()),\n self.wg.gen_text_field('Gateway', 'gateway-%s' % device, interface.get_gateway())\n ]\n widget = urwid.Pile(widgets)\n widget._iterable = True\n return widget\n\n def set_network(self, fieldmgr):\n networkctrl = NetworkCtrl()\n ifinfos = []\n for interface in self.interfaces:\n name = interface.get_name()\n ifinfos.append(\n InterfaceInfo(\n name,\n interface.get_mac_address(),\n fieldmgr.get_value('ip-address-%s' % name),\n fieldmgr.get_value('netmask-%s' % name),\n fieldmgr.get_value('gateway-%s' % name)\n )\n )\n networkctrl.stop_interface(name)\n network_config = self.setting.gen_network_config(ifinfos)\n self.setting.write_ip_config(network_config)\n for interface in self.interfaces:\n name = interface.get_name()\n if fieldmgr.get_value('ip-address-%s' % name):\n networkctrl.start_interface(name)\n","sub_path":"features/SystemIdentification.py","file_name":"SystemIdentification.py","file_ext":"py","file_size_in_byte":7773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"565833030","text":"import sys\nsys.path.insert(1, '../')\n\nfrom reframe import Relation\n\ndef test_rename_removes_col():\n '''\n assert that renaming a column removes the first column header and adds the second\n '''\n df = Relation(\"../country.csv\")\n renamed_df = df.rename(\"indepyear\", \"yearofindep\")\n assert \"indepyear\" in df.columns\n assert \"yearofindep\" not in df.columns\n assert \"indepyear\" not in renamed_df.columns\n assert \"yearofindep\" in renamed_df.columns\n \ndef test_rename_preserves_data():\n '''\n assert that renaming a column preserves the data\n '''\n df = Relation(\"../country.csv\")\n renamed_df = df.rename(\"governmentform\", \"formofgov\")\n assert df[\"governmentform\"].equals(renamed_df[\"formofgov\"])\n \n\ndef test_rename_nonexistent_cols():\n '''\n assert that renaming a fake column returns the same dataframe as before and that a new empty column is not added\n '''\n df = Relation(\"../country.csv\")\n renamed_df = df.rename(\"a_fake_column\", \"something_nice\")\n assert \"something_nice\" not in renamed_df.columns\n assert df.equals(renamed_df)\n ","sub_path":"tests/rename_test.py","file_name":"rename_test.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"552552050","text":"# Copyright 2021 The NetKet Authors - All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\n\nimport jax\nimport jax.numpy as jnp\nfrom jax.tree_util import tree_map\n\nfrom netket.operator import Squared\nfrom netket.stats import Stats\n\nfrom netket.variational import MCMixedState\n\nfrom .vmc_common import info\nfrom .abstract_variational_driver import AbstractVariationalDriver\n\n\nclass SteadyState(AbstractVariationalDriver):\n \"\"\"\n Steady-state driver minimizing L^†L.\n \"\"\"\n\n def __init__(\n self,\n lindbladian,\n optimizer,\n *args,\n variational_state=None,\n sr=None,\n sr_restart=False,\n **kwargs,\n ):\n \"\"\"\n Initializes the driver class.\n\n Args:\n lindbladian: The Lindbladian of the system.\n optimizer: Determines how optimization steps are performed given the\n bare energy gradient.\n sr: Determines whether and how stochastic reconfiguration\n is applied to the bare energy gradient before performing applying\n the optimizer. If this parameter is not passed or None, SR is not used.\n sr_restart: whever to restart the SR solver at every iteration, or use the\n previous result to speed it up\n\n \"\"\"\n if variational_state is None:\n variational_state = MCMixedState(*args, **kwargs)\n\n super().__init__(variational_state, optimizer, minimized_quantity_name=\"LdagL\")\n\n self._lind = lindbladian\n self._ldag_l = Squared(lindbladian)\n\n self.sr = sr\n self.sr_restart = sr_restart\n\n self._dp = None\n self._S = None\n self._sr_info = None\n\n def _forward_and_backward(self):\n \"\"\"\n Performs a number of VMC optimization steps.\n\n Args:\n n_steps (int): Number of steps to perform.\n \"\"\"\n\n self.state.reset()\n\n # Compute the local energy estimator and average Energy\n self._loss_stats, self._loss_grad = self.state.expect_and_grad(self._ldag_l)\n\n if self.sr is not None:\n self._S = self.state.quantum_geometric_tensor(self.sr)\n\n # use the previous solution as an initial guess to speed up the solution of the linear system\n x0 = self._dp if self.sr_restart is False else None\n self._dp, self._sr_info = self._S.solve(self._loss_grad, x0=x0)\n else:\n # tree_map(lambda x, y: x if is_ccomplex(y) else x.real, self._grads, self.state.parameters)\n self._dp = self._loss_grad\n\n # If parameters are real, then take only real part of the gradient (if it's complex)\n self._dp = jax.tree_multimap(\n lambda x, target: (x if jnp.iscomplexobj(target) else x.real),\n self._dp,\n self.state.parameters,\n )\n\n return self._dp\n\n @property\n def ldagl(self):\n \"\"\"\n Return MCMC statistics for the expectation value of observables in the\n current state of the driver.\n \"\"\"\n return self._loss_stats\n\n # def reset(self):\n # super().reset()\n\n def __repr__(self):\n return (\n \"SteadyState(\"\n + f\"\\n step_count = {self.step_count},\"\n + f\"\\n state = {self.state})\"\n )\n\n def info(self, depth=0):\n lines = [\n \"{}: {}\".format(name, info(obj, depth=depth + 1))\n for name, obj in [\n (\"Lindbladian \", self._lind),\n (\"Optimizer \", self._optimizer),\n (\"SR solver \", self.sr),\n ]\n ]\n return \"\\n{}\".format(\" \" * 3 * (depth + 1)).join([str(self)] + lines)\n","sub_path":"netket/driver/steady_state.py","file_name":"steady_state.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"93888298","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.core.window import Window\n\nclass MilesToKilometres(App):\n \"\"\" MilesToKilometres is a Kivy App for converting from miles to kilometres \"\"\"\n def build(self):\n \"\"\" build the Kivy app from the kv file \"\"\"\n Window.size = (800, 400)\n self.title = \"Convert Miles to Kilometres\"\n self.root = Builder.load_file('conversion.kv')\n self.miles = 10\n return self.root\n\n def handle_calculate(self):\n \"\"\" handle calculation (could be button press or other call), output result to label widget \"\"\"\n result = self.miles * 1.60934\n self.root.ids.output_label.text = str(result)\n\n def handle_increment(self, increment):\n \"\"\" handle calculation (could be button press or other call), output result to label widget \"\"\"\n self.miles += increment\n self.root.ids.input_number.text = str(self.miles)\n\n\nMilesToKilometres().run()","sub_path":"prac_06/miles to kilometres.py","file_name":"miles to kilometres.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"328217185","text":"# 使用账号登陆App Annie,抓取 2014 Jun - 2016 Jun的中国区IOS商店每月的'下载排行版'和'收入排行榜'\r\n# 使用Selenium 配合 BeautifulSoup;保存为csv文档\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions\r\nimport csv\r\nimport os\r\nimport time\r\nimport random\r\n\r\nannie_login_page = 'https://www.appannie.com/account/login/?next=/indexes/ios/rank/games/'\r\nannie_table_page = 'https://www.appannie.com/indexes/ios/rank/games/?month=%s&country=CN' # % '2014-06-01'\r\nuser_name = 'xxxxxx'\r\npassword = 'xxxxxx'\r\n\r\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36',\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}\r\nphantomJS_executable_path = r'C:\\Users\\m7catsue\\Desktop\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe'\r\nchromedriver_executable_path = r'C:\\Users\\m7catsue\\Desktop\\phantomjs-2.1.1-windows\\bin\\chromedriver.exe'\r\n\r\ncsv_download_path = r'C:\\Users\\m7catsue\\Desktop\\App_annie_download.csv'\r\ncsv_revenue_path = r'C:\\Users\\m7catsue\\Desktop\\App_annie_revenue.csv'\r\n\r\n# 需要迭代每月的首日作为当月的日期,带入url:\r\n# [1] 通过手动构建list获得所需日期 (不能scale)\r\n#month_tags = ['2014-06-01', '2014-07-01', '2014-08-01', '2014-09-01', '2014-10-01', '2014-11-01', '2014-12-01',\r\n #'2015-01-01', '2016-02-01', '2015-03-01']\r\n# [2] 通过pandas构建(pandas freq='M'默认以每月最后一日代表该月,需通过freq='D'来构建每月首日的日期)\r\nimport pandas as pd\r\ndates = pd.date_range('2014-06-01', '2016-06-30', freq='D') # dates.is_month_start返回对应位置的True/False\r\nmonth_tags = dates[dates.is_month_start].astype(str).tolist() # 先astype(str)再tolist(),否则list中元素类型是datetime对象\r\n\r\n# Set custom headers for selenium PhantomJS\r\nfor key in headers:\r\n webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.{}'.format(key)] = headers[key]\r\n# 创建Selenium webdriver对象\r\nweb_driver = webdriver.Chrome(chromedriver_executable_path)\r\n#web_driver = webdriver.PhantomJS(executable_path=phantomJS_executable_path)\r\n\r\n\r\ndef login_annie(driver):\r\n \"\"\"使用Selenium webdriver登录到App Annie\"\"\"\r\n driver.get(annie_login_page)\r\n WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.ID, 'submit'))) # 等待'登录'按钮出现\r\n # find relevant web elements\r\n user_name_input_field = driver.find_element_by_xpath(\"//*[@id='email']\")\r\n password_input_field = driver.find_element_by_xpath(\"//*[@id='password']\")\r\n remember_check_box = driver.find_element_by_xpath(\"//*[@id='id_remember_user']\")\r\n submit_buttom = driver.find_element_by_xpath(\"//*[@id='submit']\")\r\n # input user_name & password\r\n user_name_input_field.clear(); user_name_input_field.send_keys(user_name)\r\n password_input_field.clear(); password_input_field.send_keys(password)\r\n remember_check_box.click()\r\n submit_buttom.click()\r\n print('Clicked the submit button.')\r\n return driver\r\n\r\nif __name__ == '__main__':\r\n login_annie(web_driver) # Selenium webdriver登录\r\n\r\n for month_tag in month_tags: # month_tags包含所有的'月份标签'\r\n web_driver.get('https://www.appannie.com/indexes/ios/rank/games/?month=%s&country=CN' % month_tag)\r\n WebDriverWait(web_driver, 10).until(expected_conditions.visibility_of_element_located((By.XPATH,\r\n \"//*[@id='container']/div[2]/div/div[2]/div[3]/div/div/div[3]/div[2]/div[1]\")))\r\n soup = BeautifulSoup(web_driver.page_source, 'html.parser')\r\n\r\n # 每月下载榜top10\r\n table = soup.find('div', {'data-table': 'app-download-index'}).find('tbody', {'data-ref': 'main'})\r\n rows = table.findAll('tr')\r\n if not os.path.exists(csv_download_path):\r\n with open(csv_download_path, 'w', newline='', encoding='utf-8') as csvFile: # newline='',否则csv中两行间会有空白行\r\n writer = csv.writer(csvFile)\r\n writer.writerow([month_tag, '', '', '']) # 共4列\r\n for row in rows: # rows是list,包含web elements\r\n csvRow = [] # csvRow是要写入csv文档的每一行,每个元素以逗号分隔\r\n for cell in row.findAll(['td', 'th']):\r\n csvRow.append(cell.get_text())\r\n writer.writerow(csvRow)\r\n else:\r\n with open(csv_download_path, 'a', newline='', encoding='utf-8') as csvFile:\r\n writer = csv.writer(csvFile)\r\n writer.writerow([month_tag, '', '', ''])\r\n for row in rows: # rows是list,包含web elements\r\n csvRow = [] # csvRow是要写入csv文档的每一行,每个元素以逗号分隔\r\n for cell in row.findAll(['td', 'th']):\r\n csvRow.append(cell.get_text())\r\n writer.writerow(csvRow)\r\n\r\n # 每月收入榜top10\r\n table = soup.find('div', {'data-table': 'app-revenue-index'}).find('tbody', {'data-ref': 'main'})\r\n rows = table.findAll('tr')\r\n if not os.path.exists(csv_revenue_path):\r\n with open(csv_revenue_path, 'w', newline='', encoding='utf-8') as csvFile:\r\n writer = csv.writer(csvFile)\r\n writer.writerow([month_tag, '', '', ''])\r\n for row in rows: # rows是list,包含web elements\r\n csvRow = [] # csvRow是要写入csv文档的每一行,每个元素以逗号分隔\r\n for cell in row.findAll(['td', 'th']):\r\n csvRow.append(cell.get_text())\r\n writer.writerow(csvRow)\r\n else:\r\n with open(csv_revenue_path, 'a', newline='', encoding='utf-8') as csvFile:\r\n writer = csv.writer(csvFile)\r\n writer.writerow([month_tag, '', '', ''])\r\n for row in rows: # rows是list,包含web elements\r\n csvRow = [] # csvRow是要写入csv文档的每一行,每个元素以逗号分隔\r\n for cell in row.findAll(['td', 'th']):\r\n csvRow.append(cell.get_text())\r\n writer.writerow(csvRow)\r\n print('Data scraped: [%s]' % month_tag)\r\n time.sleep(random.uniform(1, 1.5))\r\n\r\n print('Processing Complete.')\r\n web_driver.close()\r\n","sub_path":"app_annie_scraper.py","file_name":"app_annie_scraper.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"556165280","text":"#! /usr/bin/env python2\n\nfilename = raw_input(\"Filename: \")\nf = open(filename, 'r')\n\ntimes = list()\n\nfor line in f:\n l = line.strip()\n newl = l[1:]\n times.append(newl)\n\nf.close()\n\nfout = open(filename, 'w')\n\nfor t in times:\n fout.write(\"%s\\n\" % t)\nfout.close()\n","sub_path":"nsbnt/script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"428733265","text":"__author__ = 'sarace'\n\nfrom django.conf.urls import url\napp_name=\"cooking\"\n\nfrom .views import cooking,recipe,ingredient\n\nurlpatterns = [\n url(r'^$', cooking.index,name='cooking_index'),\n url(r'^recipes/$',recipe.recipes_index,name=\"recipes_index\"),\n url(r'^recipe/(?P[0-9]+)',recipe.details,name='recipe_details'),\n url(r'^recipe/delete/(?P[0-9]+)',recipe.delete,name='recipe_delete'),\n url(r'^recipes/search/$',recipe.search,name='recipe_search'),\n url(r'^recipes/recipe_form/(?P[0-9]*)',recipe.recipe_form,name='recipe_form'),\n url(r'^recipes/add_modif/$',recipe.add_modify,name='recipe_add_modif'),\n url(r'^recipe/add_ingredient_to_recipe/$',recipe.add_ingredient_to_recipe,name=\"add_ingredient_to_recipe\"),\n url(r'^recipe/delete_ingredient_recipe/(?P[0-9]+)(?P\\w+)/',recipe.delete_ingredient_recipe,name='ingredient_recipe_delete'),\n url(r'^ingredients/$',ingredient.ingredients_index,name='ingredients_index'),\n url(r'^ingredient/(?P[0-9]+)',ingredient.details,name=\"ingredient_details\"),\n url(r'^ingredient/delete/(?P[0-9]+)',ingredient.delete,name='ingredient_delete'),\n url(r'^ingredients/search/$',ingredient.search,name='ingredient_search'),\n url(r'^ingredients/recipe_form/(?P[0-9]*)',ingredient.ingredient_form,name='ingredient_form'),\n url(r'^ingredients/add_modif/$',ingredient.add_modify,name='ingredient_add_modif'),\n]\n","sub_path":"cooking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"117486537","text":"# Copyright (c) 2013 Quixey\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\nimport subprocess\nimport tempfile\nimport logging\nfrom luigi.task import Task\nfrom luigi.file import File as localTarget\n\nlogger = logging.getLogger('luigi-interface')\n\nclass PigTask(Task):\n def get_script(self):\n return ''\n\n def run(self):\n # Setup any parameters for the script\n pig_params = []\n\n # Add pig script parameters\n param_pairs = self.script_parameters()\n if isinstance(param_pairs, dict):\n param_pairs = param_pairs.items()\n for key, value in param_pairs:\n pig_params += ['-p', '%s=%s' % (key, value)]\n\n temp_stdout = tempfile.TemporaryFile()\n script = self.get_script()\n if not script:\n logging.warn('Terminating pig script as no source script was set')\n return\n\n logger.info('Running pig script %s with parameters %s' % (script, ', '.join(pig_params)))\n\n def run_script(script, params):\n proc = subprocess.Popen(['pig', '-f', script] + params, stdout=temp_stdout, stderr=subprocess.PIPE)\n\n # Track the output so we can get error messages\n error_message = None\n while True:\n if proc.poll() is not None:\n break\n err_line = proc.stderr.readline()\n if err_line.strip():\n logger.info(err_line.strip())\n if err_line.find('ERROR ') != -1:\n error_message = err_line\n\n if proc.returncode == 0:\n return\n\n # Try to fetch error logs if possible\n message = 'Pig job failed with error %s. ' % error_message\n\n raise Exception(message)\n\n logger.info(\"Performing dry run\")\n run_script(script, pig_params + ['-c'])\n\n logger.info(\"Performing full script run\")\n run_script(script, pig_params)\n\n def script_parameters(self):\n return {}\n\n def output(self):\n return localTarget('./output_files/%s' % self.task_id)\n","sub_path":"luigi/pigtask.py","file_name":"pigtask.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"251466983","text":"# script to download photos from unsplash\nimport sys\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\n\nif len(sys.argv) > 1:\n\ttag = sys.argv[1]\n\tif len(sys.argv) > 2:\n\t\tlimit = int(sys.argv[2])\n\telse:\n\t\tlimit = 0\n\tlink = \"https://unsplash.com/search/photos/\"+tag\n\n\tprint(\"Downloading images for {}...\".format(tag))\n\tr=requests.get(link)\n\thtml=r.content\n\tsoup = BeautifulSoup(html, \"html.parser\")\n\tif limit:\n\t\tallImages = [x.get(\"src\") for x in soup.findAll(\"img\")][:limit]\n\telse:\n\t\tallImages = [x.get(\"src\") for x in soup.findAll(\"img\")]\n\timages = [x.split(\"?\")[0] for x in allImages if \"images.unsplash.com\" in x and \"profile\" not in x]\n\t# wget the files\n\tfor x in images:\n\t\tos.system(\"wget -q --no-check-certificate -c -P photos/{} {}\".format(tag.replace(\" \",\"-\"), x))\n\n\t# the files are without any extension\n\n\tos.chdir(\"photos/\"+tag)\n\tfiles = os.listdir(\".\")\n\tfor f in files:\n\t\tif not f.endswith(\".jpg\"):\n\t\t\tos.rename(f,f+\".jpg\")\nelse:\n\tprint(\"Enter tag.\\nUsage: python unsplash.py tag\\n\")\n","sub_path":"unsplash.py","file_name":"unsplash.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"526667047","text":"class Solution(object):\n def flipPancakes(self, pancakeStack):\n pancakeStatus = \"\"\n flipCount = -1\n\n for pancake in pancakeStack:\n if pancakeStatus != pancake:\n pancakeStatus = pancake\n flipCount += 1\n\n if pancake == '-':\n flipCount += 1\n\n return flipCount\n\n# raw_input() reads a string with a line of input, stripping the '\\n' (newline) at the end.\n# This is all you need for most Google Code Jam problems.\nt = int(input()) # read a line with a single integer\ntest = Solution()\n\nfor i in range(1, t + 1):\n pancakeStack = input()\n print(\"Case #{}: {}\".format(i, test.flipPancakes(pancakeStack)))\n # check out .format's specification for more formatting options","sub_path":"solutions_5634697451274240_0/Python/pilagod/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"230012122","text":"from core import *\nimport unittest\nimport weakref\n\nclass Service2(BaseService):\n def do_something(self):\n return \"something\"\n\nclass Service1(BaseService):\n\n service2 = Depends(\"Service2\")\n \n has_bind = False\n \n def bind(self, service_provider):\n super(Service1, self).bind(service_provider)\n self.has_bind = True\n\n def do_something_else(self):\n return self.service2.do_something() + \" else\"\n\nclass TestServiceProvider(unittest.TestCase):\n def setUp(self):\n self.provider = ServiceProvider()\n \n def test_services(self):\n provider = ServiceProvider()\n \n # Keys can be anything, even strings\n provider.register_factory(Service1, \"service1\")\n provider.register_factory(Service2, \"Service2\")\n \n s1 = provider.get_service(\"service1\")\n assert s1.has_bind\n assert isinstance(s1.service2, Service2), s1.service2\n \n assert s1 is not None\n assert isinstance(s1, Service1)\n self.assertEquals(s1.do_something_else(), \"something else\")\n \n ghost = weakref.ref(s1)\n \n # Direct referencing works too\n s1 = None\n provider = None\n assert ghost() is None\n\n def test_simple_factory(self):\n prov = self.provider\n one_srv = lambda service_provider: \"one\"\n two_srv = lambda service_provider: \"two\"\n prov.register_simple_factory(one_srv, \"one\")\n prov.register_simple_factory(two_srv, \"two\")\n \n self.assertEquals(prov.get_service(\"one\"), \"one\")\n self.assertEquals(prov.get_service(\"two\"), \"two\")\n \n def test_multiple_factory_base(self):\n prov = self.provider\n prov.register_factory(Service2, \"service1\", \"service2\", \"service3\")\n assert prov.factories.has_key(\"service1\")\n srv1 = prov.get_service(\"service1\")\n assert isinstance(srv1, Service2), repr(srv1)\n srv2 = prov.get_service(\"service2\")\n assert srv1 is srv2\n srv3 = prov.get_service(\"service3\")\n assert srv3 is srv1\n \n def test_multiple_factory(self):\n prov = self.provider\n prov.register_simple_factory(\n lambda service_provider: \"one\",\n \"service1\",\n \"service2\",\n \"service3\",\n )\n assert prov.factories.has_key(\"service1\")\n srv1 = prov.get_service(\"service1\")\n self.assertEquals(srv1, \"one\")\n srv2 = prov.get_service(\"service2\")\n assert srv1 is srv2\n srv3 = prov.get_service(\"service3\")\n assert srv3 is srv1\n\n def test_multiple_service(self):\n prov = self.provider\n prov.register_service(\"one\", \"service1\", \"service2\", \"service3\")\n srv1 = prov.get_service(\"service1\")\n self.assertEquals(srv1, \"one\")\n srv2 = prov.get_service(\"service2\")\n assert srv1 is srv2\n srv3 = prov.get_service(\"service3\")\n assert srv3 is srv1\n\n def test_remove_service(self):\n prov = self.provider\n prov.register_factory(Service2, \"service1\")\n srv1 = prov.get_service(\"service1\")\n srv2 = prov.get_service(\"service1\")\n assert srv1 is srv2\n # When we unregister a service the other is created too\n prov.unregister_service(\"service1\")\n srv2 = prov.get_service(\"service1\")\n assert srv1 is not srv2\n\n def test_remove_service2(self):\n prov = self.provider\n prov.register_service(\"one\", \"service1\")\n srv1 = prov.get_service(\"service1\")\n srv2 = prov.get_service(\"service1\")\n assert srv1 is srv2\n # When we unregister a service the other is created too\n prov.unregister_service(\"service1\")\n try:\n srv2 = prov.get_service(\"service1\")\n assert False\n except ServiceError:\n pass\n \n def test_remove_multiple_factories(self):\n prov = self.provider\n prov.register_factory(Service2, \"service1\", \"service2\", \"service3\")\n srv1 = prov.get_service(\"service1\")\n prov.unregister_factory(\"service1\")\n \n try:\n srv2 = prov.get_service(\"service1\")\n except ServiceNotFoundError:\n pass\n \n try:\n srv2 = prov.get_service(\"service2\")\n except ServiceNotFoundError:\n assert False\n \n assert srv2 is srv1\n \n # now 'Service2' factory instance is present on both 'service2'\n # and 'service3'\n prov.unregister_service(\"service2\")\n try:\n prov.unregister_service(\"service3\")\n # The service3 should already be vacant\n assert False\n except ServiceError:\n pass\n \n srv3 = prov.get_service(\"service3\")\n new_srv2 = prov.get_service(\"service2\")\n assert srv3 is new_srv2\n assert srv2 is not new_srv2\n \n # Try to change the order, everything should work the same\n try:\n prov.unregister_service(\"service2\")\n except ServiceError:\n assert False\n \n srv2 = new_srv2\n new_srv2 = prov.get_service(\"service2\")\n srv3 = prov.get_service(\"service3\")\n assert srv3 is new_srv2\n assert srv2 is not new_srv2\n \n def test_propagation(self):\n prov = self.provider\n prov.register_factory(Service2, \"service1\", \"service2\", \"service3\")\n \n prov.register_service(\"foo\", \"service1\")\n assert prov.get_service(\"service2\") == \"foo\"\n assert prov.get_service(\"service3\") == \"foo\"\n\n# Service discovery stuff\nclass TestPlugin(unittest.TestCase):\n def test_service(self):\n reg = Registry()\n reg.register_plugin(\n instance=\"foo\",\n singletons=(\"key1\", \"key2\", \"key3\"),\n )\n reg.register_plugin(\n instance=\"bar\",\n singletons=(\"key4\",)\n )\n assert reg.get_singleton(\"key1\") == \"foo\"\n assert reg.get_singleton(\"key2\") == \"foo\"\n assert reg.get_singleton(\"key3\") == \"foo\"\n assert reg.get_singleton(\"key4\") == \"bar\"\n try:\n reg.get_singleton(\"key5\")\n assert False\n except SingletonError:\n pass\n\n def test_features(self):\n reg = Registry()\n reg.register_plugin(\n instance=\"foo\",\n features=(\"feat1\", \"feat2\", \"feat3\")\n )\n reg.register_plugin(\n instance=\"bar\",\n features=(\"feat1\", \"feat3\"),\n )\n reg.register_plugin(\n instance=\"gin\",\n features=(\"feat2\", \"feat3\", \"feat4\"),\n )\n \n \n self.assert_eq(reg.get_features(\"feat1\"), [\"bar\", \"foo\"])\n self.assert_eq(reg.get_features(\"feat2\"), [\"gin\", \"foo\"])\n self.assert_eq(reg.get_features(\"feat3\"), [\"bar\", \"foo\", \"gin\"])\n self.assert_eq(reg.get_features(\"feat4\"), [\"gin\"])\n self.assert_eq(reg.get_features(\"df\"), [])\n\n def assert_eq(self, l1, l2):\n l1 = list(l1)\n l1.sort()\n l2.sort()\n self.assertEquals(l1, l2)\n\n def test_factory(self):\n reg = Registry()\n reg.register_plugin(factory=lambda foo: \"bar\", singletons=(\"foo\",))\n self.assertEquals(reg.get_singleton(\"foo\"), \"bar\")\n \n class S:\n def __init__(self, foo):\n pass\n \n # Make sure the objects are created once\n reg.register_plugin(factory=S, singletons=(\"bar\",))\n s1 = reg.get_singleton(\"bar\")\n s2 = reg.get_singleton(\"bar\")\n assert s1 is s2\n \n def test_unregister_plugin(self):\n reg = Registry()\n p = reg.register_plugin(factory=lambda foo: \"bar\", singletons=(\"foo\",), features=(\"feat1\",))\n assert reg.get_singleton(\"foo\") == \"bar\"\n self.assert_eq(reg.get_features(\"feat1\"), [\"bar\"])\n\n reg.unregister(p)\n \n try:\n reg.get_singleton(\"foo\")\n assert False\n except SingletonError:\n pass\n\n self.assert_eq(reg.get_features(\"feat1\"), [])\n\n\n def test_unregister_service(self):\n reg = Registry()\n p = reg.register_plugin(factory=lambda foo: \"me\", singletons=(\"foo\",), features=(\"bar\",))\n p = reg.plugins[p]\n \n self.assert_eq(reg.get_features(\"bar\"), [\"me\"])\n self.assertEqual(reg.get_singleton(\"foo\"), \"me\")\n\n reg.unregister_singleton(\"foo\")\n assert len(p.singletons) == 0\n try:\n reg.get_singleton(\"foo\")\n assert False\n except SingletonError:\n pass\n \n self.assert_eq(reg.get_features(\"bar\"), [\"me\"])\n \n try:\n reg.unregister_singleton(\"sdfds\")\n assert False\n except SingletonError:\n pass\n\n def test_unregister_features(self):\n reg = Registry()\n p = reg.register_plugin(factory=lambda foo: \"me\", singletons=(\"foo\",), features=(\"bar\",))\n self.assert_eq(reg.get_features(\"bar\"), [\"me\"])\n self.assertEqual(reg.get_singleton(\"foo\"), \"me\")\n\n reg.unregister_feature(\"bar\", p)\n self.assert_eq(reg.get_features(\"bar\"), [])\n\n def test_service_conflict(self):\n reg = Registry()\n p1 = reg.register_plugin(factory=lambda foo: \"me\", singletons=(\"foo\",), features=(\"bar\",))\n try:\n p2 = reg.register_plugin(factory=lambda foo: \"me2\", singletons=(\"foo\",), features=(\"bar\",))\n assert False\n except SingletonError:\n pass\n self.assert_eq(reg.get_features(\"bar\"), [\"me\"])\n assert reg.get_singleton(\"foo\") == \"me\"\n\n def test_ghost_plugin_entries(self):\n reg = Registry()\n p1 = reg.register_plugin(factory=lambda foo: \"me\", singletons=(\"foo\",))\n # Private stuff, shouldn't be tested\n p1 = reg.plugins[p1]\n \n assert len(reg.plugins) == 1\n assert len(p1.singletons) == 1\n assert len(p1.features) == 0\n reg.unregister_singleton(\"foo\")\n assert len(reg.plugins) == 0, reg.plugins\n assert len(p1.singletons) == 0\n assert len(p1.features) == 0\n\n real_p1 = reg.register_plugin(factory=lambda foo: \"me\", features=(\"foo\",))\n p1 = reg.plugins[real_p1]\n assert len(reg.plugins) == 1\n assert len(p1.singletons) == 0\n assert len(p1.features) == 1\n reg.unregister_feature(\"foo\", real_p1)\n assert len(reg.plugins) == 0\n assert len(p1.singletons) == 0\n assert len(p1.features) == 0\n \n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"branches/model-config/pida/utils/culebra/testcore.py","file_name":"testcore.py","file_ext":"py","file_size_in_byte":10602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"392616669","text":"import numpy as np\nfrom apogee.utils import spectra\n\na=np.loadtxt('C13.dat')\nvac=spectra.airtovac(a)\nfp=open('C13.wind','w')\nfor wind in vac :\n fp.write('{:12.3f}{:12.3f}{:3}\\n'.format(wind[0],wind[1],1))\nfp.close()\n\nwave=np.loadtxt('wave.dat')\nfor w in wave[:,0] :\n weight=0.\n for wind in vac :\n if w >wind[0] and w 0:\n split['credit'] = total\n\n splits.append(split)\n\n s = {\n 'account':\n finance.Account.objects.get(id=int(account_name['collected'])),\n 'amount': balance\n }\n if balance > 0:\n s['debit'] = balance\n if balance < 0:\n s['credit'] = -balance\n\n splits.append(s)\n\n return render_to_response(\n 'finance/transaction_update.html',\n {\n 'user': request.user,\n 'accounts': finance.Account.objects.order_by('name'),\n 'transaction': transaction,\n 'splits': splits,\n 'action': '/admin/finance/transaction/new/'\n })\n\n\n@view_perm_required\ndef show_losses(request):\n transcript = \"\"\n summary = []\n\n from django.db import connection\n cursor = connection.cursor()\n\n def add_amt(dict, key, value):\n # Add the given value into a dictionary, adding it to any existing\n # value.\n if key not in dict:\n dict[key] = Decimal(\"0.00\")\n dict[key] += value\n\n def show_dict(dict):\n # Convert a dictionary to a format more suitable for display in a\n # Django template.\n val = [{'key': k, 'value': v} for (k, v) in sorted(dict.items())]\n val.append({'key': 'TOTAL',\n 'value': sum(dict.values(), Decimal(\"0.00\"))})\n return val\n\n # FIXME: These ought to not be hard-coded\n acct_cash = finance.Account.objects.get(id=7)\n #acct_adjustments = finance.Account.objects.get(id=23)\n cashout_entity_soda = Entity.objects.get(id=1)\n cashout_entity_box = Entity.objects.get(id=2)\n\n cursor.execute(\"\"\"SELECT MIN(xacttime::date) FROM transactions\"\"\")\n (last_date,) = cursor.fetchone()\n\n cursor.execute(\"\"\"SELECT sum(amount)\n FROM finance_splits s JOIN finance_transactions t\n ON (s.transaction_id = t.id)\n WHERE account_id = %s AND date < %s\"\"\",\n [acct_cash.id, last_date])\n (balance,) = cursor.fetchone()\n\n cash_deltas = {'soda': Decimal(\"0.00\"), 'chezbob': Decimal(\"0.00\")}\n\n transcript += \"Starting cash: %s on %s\\n\\n\" % (balance, last_date)\n\n source_totals = {}\n for cashout in CashOut.objects.filter(\n datetime__gte=last_date).order_by('datetime'):\n transcript += str(cashout) + \"\\n\"\n cursor.execute(\"\"\"SELECT source, sum(xactvalue)\n FROM transactions\n WHERE (xacttype = 'ADD' OR xacttype = 'REFUND')\n AND xacttime >= %s AND xacttime < %s\n GROUP BY source\"\"\",\n [last_date, cashout.datetime])\n for (source, amt) in cursor.fetchall():\n transcript += \" Deposit: %s (%s)\\n\" % (amt, source)\n add_amt(source_totals, source, amt)\n balance += amt\n\n cursor.execute(\"\"\"SELECT s.amount, t.description\n FROM finance_splits s JOIN finance_transactions t\n ON (s.transaction_id = t.id)\n WHERE account_id = %s AND NOT auto_generated\n AND date::timestamp >= %s\n AND date::timestamp < %s\n ORDER BY date, t.id\"\"\",\n [acct_cash.id, last_date, cashout.datetime])\n other_transactions = []\n other_total = Decimal(\"0.00\")\n for (a, d) in cursor.fetchall():\n other_transactions.append({'key': d, 'value': -a})\n other_total -= a\n balance += a\n other_transactions.append({'key': \"TOTAL\", 'value': other_total})\n\n cashcount = False\n collected = {}\n for c in cashout.cashcount_set.all():\n if (\n c.entity in (cashout_entity_soda, cashout_entity_box) and\n c.total > 0):\n add_amt(collected, c.entity.name, c.total)\n transcript += \" Cash Count: %s (%s)\\n\" % (\n c.total, c.entity.name)\n cashcount = True\n if c.entity == cashout_entity_soda:\n cash_deltas['soda'] += c.total\n else:\n cash_deltas['chezbob'] += c.total\n if cashcount:\n transcript += \" Expected:\\n\"\n for (s, t) in source_totals.items():\n transcript += \" %s %s\\n\" % (t, s)\n if s not in cash_deltas:\n cash_deltas[s] = Decimal(\"0.00\")\n cash_deltas[s] -= t\n\n transcript += \" Cumulative Errors:\\n\"\n for (s, t) in cash_deltas.items():\n transcript += \" %s %s\\n\" % (t, s)\n\n transcript += \" BALANCE: %s\\n\" % (balance,)\n summary.append({'date': cashout.datetime,\n 'deposits': show_dict(source_totals),\n 'collected': show_dict(collected),\n 'extra': other_transactions,\n 'error': balance})\n\n source_totals = {}\n\n last_date = cashout.datetime\n\n return render_to_response('cashout/losses.html',\n {'summary': summary, 'debug': transcript})\n","sub_path":"django/chezbob/cashout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"567558852","text":"##\n# title: BreadInterface.Controller.py\n# by: Brian Kim\n# description: the bread and butter of BreadInterface.\n# Developers will subclass the Controller to utilitize\n# the familiar BreadInterface button layout in addition\n# to their own app-specific functionality\n#\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\nfrom ButtonLayout import ButtonLayout\nfrom Lifecycle import Lifecycle\n\n##\n# controller class\n#\nclass Controller( ButtonLayout, Lifecycle ):\n\n #\n # breadinterface lifecycle methods\n #\n\n def __init__( self, view, title='BreadInterface' ):\n self.title = title\n \n # controller\n self.frame = gtk.VBox()\n \n # frame\n self.top = gtk.HBox()\n self.view = view\n self.bottom = gtk.HBox()\n\n # bar\n self.tl = ButtonLayout.gtk_button(self.tl_label())\n self.tm = ButtonLayout.gtk_button(self.tm_label())\n self.tr = ButtonLayout.gtk_button(self.tr_label())\n self.bl = ButtonLayout.gtk_button(self.bl_label())\n self.bm = ButtonLayout.gtk_button(self.bm_label())\n self.br = ButtonLayout.gtk_button(self.br_label())\n \n # hook up the button actions\n self.tl.connect( \"clicked\", self.tl_clicked )\n self.tm.connect( \"clicked\", self.tm_clicked )\n self.tr.connect( \"clicked\", self.tr_clicked )\n self.bl.connect( \"clicked\", self.bl_clicked )\n self.bm.connect( \"clicked\", self.bm_clicked )\n self.br.connect( \"clicked\", self.br_clicked )\n\n # build the view\n self.top.pack_start( self.tl,False)\n self.top.pack_start( self.tm,True)\n self.top.pack_start( self.tr,False)\n\n self.bottom.pack_start( self.bl,False)\n self.bottom.pack_start( self.bm,True)\n self.bottom.pack_start( self.br,False)\n\n self.frame.pack_start( self.top,False)\n self.frame.pack_start( self.view,True)\n self.frame.pack_start( self.bottom,False)\n\n #\n # breadinterface button layout\n # - defaulting the top-middle label to be the title\n # - making the default button click to display button info\n #\n def tm_label( self ):\n return self.title\n\n def tm_clicked( self, v ):\n msg = gtk.MessageDialog( type=gtk.MESSAGE_INFO, \n flags=gtk.DIALOG_MODAL,\n buttons=gtk.BUTTONS_OK)\n \n info = 'Button Layout\\n\\ntop-left: '+self.tl_label()+' : '\n info += self.tl_info()\n info += '\\ntop-right: '+self.tr_label()+' : '\n info += self.tr_info()\n info += '\\nbottom-left: '+self.bl_label()+' : '\n info += self.bl_info()\n info += '\\nbottom-middle: '+self.bm_label()+' : '\n info += self.bm_info()\n info += '\\nbottom-right: '+self.br_label()+' : '\n info += self.br_info()\n msg.set_markup( info )\n msg.run()\n msg.destroy()\n\n def start( self ):\n self.frame.show_all()\n self.update()\n\n def update( self ):\n self.tl.set_label( self.tl_label() )\n self.tm.set_label( self.tm_label() )\n self.tr.set_label( self.tr_label() )\n self.bl.set_label( self.bl_label() )\n self.bm.set_label( self.bm_label() )\n self.br.set_label( self.br_label() )\n\n #\n # set the color style on the label\n # MUST BE DONE EVERY SINGLE TIME THE LABEL IS SET\n # HOW STUPID IS THAT????\n label = self.tl.get_child()\n style = label.get_style().copy()\n style.fg[gtk.STATE_NORMAL] = gtk.gdk.color_parse('#FFFFFF')\n style.fg[gtk.STATE_PRELIGHT] = gtk.gdk.color_parse('#FFFFFF')\n self.tl.get_child().set_style(style)\n self.tm.get_child().set_style(style)\n self.tr.get_child().set_style(style)\n self.bl.get_child().set_style(style)\n self.bm.get_child().set_style(style)\n self.br.get_child().set_style(style)\n \n self.view.update()\n\n def clear( self ):\n pass\n\n def stop( self ):\n self.frame.hide_all()\n \n","sub_path":"py/BreadInterface/interface/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"259152921","text":"import os\nimport sys, shutil\nfrom random import shuffle\n\nfrom Misc import processArguments, sortKey\n\nparams = {\n 'file_ext': 'jpg',\n 'out_file': 'list.txt',\n 'folder_name': '.',\n 'prefix': '',\n 'shuffle_files': 1,\n 'del_empty': 0,\n}\nprocessArguments(sys.argv[1:], params)\nfile_ext = params['file_ext']\nout_file = params['out_file']\nfolder_name = params['folder_name']\nshuffle_files = params['shuffle_files']\ndel_empty = params['del_empty']\nprefix = params['prefix']\n\nif os.path.isfile(folder_name):\n root_dir = os.path.abspath(os.getcwd())\n subfolders = [x.strip() for x in open(folder_name).readlines()]\n print('Looking for files with extension {:s} in sub folders of {:s} listed in {}'.format(\n file_ext, root_dir, folder_name))\n folder_name = root_dir\nelse:\n folder_name = os.path.abspath(folder_name)\n print('Looking for files with extension {:s} in sub folders of {:s}'.format(file_ext, folder_name))\n subfolders = [name for name in os.listdir(folder_name) if os.path.isdir(os.path.join(folder_name, name))]\nif prefix:\n print('Limiting search to only sub folders starting with {}'.format(prefix))\n subfolders = [x for x in subfolders if x.startswith(prefix)]\ntry:\n subfolders.sort(key=sortKey)\nexcept:\n subfolders.sort()\n\ntotal_files = 0\ncounts_file = open('file_counts.txt', 'w')\nfiles = []\nempty_folders = []\nfor subfolder in subfolders:\n subfolders_path = os.path.join(folder_name, subfolder)\n src_files = [f for f in os.listdir(subfolders_path) if os.path.isfile(os.path.join(subfolders_path, f))]\n if file_ext:\n src_files = [f for f in src_files if f.endswith(file_ext)]\n src_files.sort(key=sortKey)\n\n n_files = len(src_files)\n\n if del_empty and n_files == 0:\n empty_folders.append(subfolders_path)\n total_files += n_files\n files += [os.path.join(subfolders_path, f) for f in src_files]\n text = '{}:\\t{}\\t{}'.format(subfolder, n_files, total_files)\n print(text)\n counts_file.write(text + '\\n')\n\nprint('total_files: {}'.format(total_files))\ncounts_file.close()\n\nif shuffle_files:\n shuffle(files)\n\nout_fid = open(out_file, 'w')\nfor f in files:\n out_fid.write(f + '\\n')\nout_fid.close()\nif del_empty and empty_folders:\n print('Removing empty folders:')\n for folder in empty_folders:\n shutil.rmtree(folder)\n print(folder)\n\n","sub_path":"countFileInSubfolders.py","file_name":"countFileInSubfolders.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"340031860","text":"\"\"\"\n=============================\n@Time : 2020/5/27 20:13\n@Author : AllyZhou\n@FileDec: \n==============================\n\"\"\"\nfrom queue import Queue, LifoQueue, PriorityQueue\n\n\"\"\"\n队列:多个线程进行通信时能确保安全\n1.先入先出\n2.后入先出\n3.优先级队列\n\"\"\"\n# 初始化一个队列 默认是不限定队列的长度,也可以通过参数去指定队列中数据的最大长度\nq = Queue()\nq1 = Queue(maxsize=4)\n\n# 1、往队列中添加数据\nq.put(100)\nq1.put(1000)\nq1.put(1000)\nprint(q.qsize())\n# 队列中数据满了会堵塞,等待队列中的数据少了再加 可以设置等待的超时时间\n# q1.put(2000, timeout=1)\n# 往队列中添加数据不等待,如果队列中数据已满直接报错\nq1.put(100, block=False)\n# 2.往队列中获取数据\nq.get()\nq1.get()\n\n# 获取数据 设置等待的超时时间\nq1.get(timeout=1)\n# 获取数据不等待,如果队列中没有数据直接报错\nq1.get(block=False)\n# 3.判断队列中数据是否为空 队列中数据为空,返回True\nq.empty()\n# 4.判断队列中数据是否已满 队列中数据已满 返回True\nq.full()\n# 5.往队列中添加数据不等待\nq.put_nowait()\n# 6.获取数据不等待\nq1.get_nowait()\n# 7.获取队列中任务数量(多少条数据)\nq.qsize()\n# 8.join\nq1.join()\n","sub_path":"python基础高阶编程/py_10day/02python中的队列.py","file_name":"02python中的队列.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"299808087","text":"import numpy as np\nimport matplotlib as mpl\nfrom matplotlib.pyplot import *\nimport matplotlib.pyplot as plt\nfrom my_round import my_round\nfrom mpl_toolkits.basemap import Basemap\n### Drifter Coverage Map: Drogued vs Undrogued\n\nn=0.5\nlats=np.arange(-90,90.5,n)\nlons=np.arange(0,360.5,n)\n\ntimemap1=np.loadtxt(\"./Drifte_Coverage/Halfdeg_coverage_total.dat\",unpack=True)\n#timemap1=np.loadtxt(\"halfdeg_coverage_test1.dat\",unpack=True)\n#timemap2=np.loadtxt(\"halfdeg_coverage_test2.dat\",unpack=True)\n#timemap1=np.loadtxt(\"./Drifte_Coverage/1deg_coverage_drogued.dat\",unpack=True)\n#timemap2=np.loadtxt(\"./Drifte_Coverage/1deg_coverage_undrogued.dat\",unpack=True)\n#timemap1=np.loadtxt(\"./Drifte_Coverage/1deg_coverage_NONINO.dat\",unpack=True)\n#timemap2=np.loadtxt(\"./Drifte_Coverage/1deg_coverage_ELNINO.dat\",unpack=True)\n#timemap3=np.loadtxt(\"./Drifte_Coverage/1deg_coverage_LANINA.dat\",unpack=True)\n\ndef grid(vector,res,latarray,lonarray):\n\t# INPUT: Data vector\n\t# OUTPUT: 2D grid\n\tarray=np.zeros((latarray.size-1,lonarray.size-1))\n\tcount=-1\n\tfor i in range(latarray.size-1):\n\t\tfor j in range(lonarray.size-1):\n\t\t\tcount=count+1\n\t\t\tarray[i][j]=vector[count]\n\n\treturn array\n\n\ntimemap1=grid(timemap1,n,lats,lons)\n#timemap2=grid(timemap2,n,lats,lons)\n#timemap3=grid(timemap3,n,lats,lons)\n\nmasked1=np.ma.array(timemap1,mask=np.isnan(timemap1))\n#masked2=np.ma.array(timemap2,mask=np.isnan(timemap2))\n#masked3=np.ma.array(timemap3,mask=np.isnan(timemap3))\n#cmap=mpl.colors.ListedColormap(['w','b','y','r'])\n#bounds=[0,1,2,3,4]\n\ncmap=matplotlib.colors.ListedColormap(['w','#8080ff','#3333ff','#ffcc80','#ff9900','#ff8080','#ff0000'])\nbounds=[0,1,np.log10(50),2,np.log10(500),3]\nnorm=mpl.colors.BoundaryNorm(bounds,cmap.N)\n\n#plt.subplot(311)\nm = Basemap(projection='robin',lon_0=270,lat_0=0,resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='white',lake_color='white')\nm.drawmapboundary(fill_color='white')\nlonarray,latarray=np.meshgrid(lons[:-1],lats[:-1])\nc=m.pcolormesh(lonarray,latarray,np.log10(masked1),cmap=cmap,vmin=0,vmax=3,norm=norm,latlon=True)\n#plt.title(\"Standard State - No Nino\")\n\n\"\"\"\nplt.subplot(312)\nm = Basemap(projection='robin',lon_0=270,lat_0=0,resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='white',lake_color='white')\nm.drawmapboundary(fill_color='white')\nlonarray,latarray=np.meshgrid(lons[:-1],lats[:-1])\nc=m.pcolormesh(lonarray,latarray,np.log10(masked2),cmap=cmap,vmin=0,vmax=4,norm=norm,latlon=True)\nplt.title(\"El Nino\")\n\nplt.subplot(313)\nm = Basemap(projection='robin',lon_0=270,lat_0=0,resolution='c')\nm.drawcoastlines()\nm.fillcontinents(color='white',lake_color='white')\nm.drawmapboundary(fill_color='white')\nlonarray,latarray=np.meshgrid(lons[:-1],lats[:-1])\nc=m.pcolormesh(lonarray,latarray,np.log10(masked3),cmap=cmap,vmin=0,vmax=4,norm=norm,latlon=True)\nplt.title(\"La Nina\")\n\nplt.show()\n\"\"\"\nfig = plt.figure(figsize=(8, 3))\nax = fig.add_axes([0.05, 0.475, 0.9, 0.15])\n\ncb2=mpl.colorbar.ColorbarBase(ax,cmap=cmap,label=\"Number of coordinate readings\",ticks=bounds,norm=norm,orientation='horizontal',spacing='proportional')\ncb2.ax.set_xticklabels(['0','10$^1$',' ','10$^2$',' ','10$^3$'])\nplt.show()\n","sub_path":"GDP_DATA/Drifter_Coverage/coverage_plot.py","file_name":"coverage_plot.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"504872063","text":"# from MTarget import NullTarget, NoTarget, PlayerTarget\n\n# from enum import Enum\nfrom typing import Optional, NewType\n\nMPlayerID = NewType('MPlayerID', str)\n\nNOTARGET : MPlayerID = \"NOTARGET\"\n\nTOWN_ROLES = [\n 'TOWN',\n 'COP',\n 'DOCTOR',\n 'CELEB',\n 'MILLER',\n 'MILKY',\n 'MASON',\n]\n\nMAFIA_ROLES = [\n 'MAFIA',\n 'GODFATHER',\n 'STRIPPER',\n 'GOON',\n]\n\nROGUE_ROLES = [\n 'IDIOT',\n 'SURVIVOR',\n 'GUARD',\n 'AGENT',\n]\n\nALL_ROLES = TOWN_ROLES + MAFIA_ROLES + ROGUE_ROLES\n\nTARGETING_ROLES = {\n 'COP',\n 'DOCTOR',\n 'MILKY',\n 'STRIPPER',\n}\n\nCONTRACT_ROLES = {\n 'IDIOT',\n 'SURVIVOR',\n 'GUARD',\n 'AGENT',\n}\n\nclass MPlayer:\n def __init__(self, \n id : MPlayerID, \n role : str, \n vote : Optional[MPlayerID]=None, \n target: Optional[MPlayerID]=None\n ):\n\n self.id = id\n self.vote : Optional[MPlayerID] = vote\n self.role : str = role\n self.target : Optional[MPlayerID] = target\n\n def __str__(self):\n return \"[{id},{role}:{vote}:{target}]\".format(**self.__dict__)\n \n def __repr__(self):\n return \"[{id},{role}:{vote}:{target}]\".format(**self.__dict__)\n\n","sub_path":"mafiabot/MPlayer.py","file_name":"MPlayer.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"501557882","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\n\nif __name__==\"__main__\":\n rc('text', usetex=True)\n rc('font', family='serif')\n rc('xtick', labelsize=15)\n rc('ytick', labelsize=15)\n\n scans_valcartier1 = np.array([[0,0],\n [-10.133,-6.0960],\n [-5.183, 5.953],\n [6.06, 4.39],\n [1.51, -10.88]])\n connections_valcartier1 = [[0,2], [0,3], [0,1], [4,0]]\n\n scans_valcartier2 = np.array([[0,0],\n [-0.945, 11.42],\n [13.41, 1.46],\n [-0.327,-12.58],\n [-11.92,-0.84]])\n connections_valcartier2 = [[0,2], [0,3], [0,1], [4,0]]\n\n scans_sequoia = np.array([[0,0],\n [-7.51, -5.11],\n [-12.29, -11.89],\n [-22.68,-18.76],\n [-32.50,-14.92],\n [-24.28, -8.02],\n [-18.46, -4.39],\n [-12.24, 1.67]])\n connections_sequoia = [[0,7],[0,1],[6,1],[6,5],[5,2],[2,3],[3,4]]\n sites = [(\"Valcartier 1\", scans_valcartier1, connections_valcartier1),\n (\"Valcartier 2\", scans_valcartier2, connections_valcartier2),\n (\"Sequoia\", scans_sequoia, connections_sequoia)]\n for site in sites:\n title = site[0]\n scans = site[1]\n connections = site[2]\n if title == \"Sequoia\":\n xytext=(5,15)\n else:\n xytext=(-20,0)\n for connection in connections:\n plt.plot([scans[connection[0],0], scans[connection[1],0]],\n [scans[connection[0],1], scans[connection[1],1]],\n color=\"blue\")\n for i, xy in enumerate(scans):\n plt.annotate(\"Scan {}\".format(i+1),\n xy=xy, xytext=xytext,\n textcoords='offset points', ha='right', va='bottom',\n fontsize=16,\n arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))\n plt.scatter(scans[:,0], scans[:,1], s=90)\n plt.xlabel(\"$x$ position of scan\", fontsize=22)\n plt.ylabel(\"$y$ position of scan\", fontsize=22)\n plt.show()\n","sub_path":"python_utils/layout_graph.py","file_name":"layout_graph.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"454012428","text":"import requests\nfrom datetime import datetime\nimport json\nimport hmac\nimport hashlib\nimport base64\nimport re\nimport sys\n\n# 根据不同的机器人修改token,sec\n# 自己一个人的群机器人\ntoken = \"d693dbe0366fdee2b897f3a7c3649cb5650577dceac3d7628a850160dd5b5a2e\"\nsec = \"SEC69438e329615728d486e2f34afd97821d69bda1bb01ebd4187c3e5641cbea5b3\"\n\n\n# nsd1905的群机器人\n# token = \"b2775b5fa8b9336eac272ae9eef001973e0c14ae40520c7664e6a878f3bdb307\"\n# sec = \"SEC9fddb62c518ebeae737dcfd8562abc6ba291ae1451438520c4a121291e9d576e\"\n\n\ndef sent_msg(url, remiders, msg):\n headers = {'Content-Type': 'application/json; charset=utf-8'}\n data = {\n \"msgtype\": \"text\",\n \"at\": {\n \"atMobiles\": remiders,\n \"isAtAll\": False,\n },\n \"text\": {\n \"content\": msg,\n }\n }\n r = requests.post(url, data=json.dumps(data), headers=headers)\n return r.text\n\n\ndef secret(time_stamp, secret1):\n data = (str(time_stamp) + \"\\n\" + secret1).encode(\"utf_8\")\n secret1 = secret1.encode(\"utf-8\")\n signature = base64.b64encode(hmac.new(secret1, data, digestmod=hashlib.sha256).digest())\n reg = re.compile(r\"'(.*)'\")\n signature = str(re.findall(reg, str(signature))[0])\n\n return signature\n\n\nif __name__ == '__main__':\n timestamp = int(datetime.now().timestamp() * 1000)\n sign = secret(timestamp, sec)\n\n if len(sys.argv) > 1:\n msg = sys.argv[1] # 需要发送的输入的消息\n else:\n msg = \"对对对,说好的口碑呢???\" # 不输入参数,发送的默认信息\n \n url = \"https://oapi.dingtalk.com/robot/send?access_token=%s×tamp=%s&sign=%s\" % (token, timestamp, sign)\n print(sent_msg(url=url, remiders=[], msg=msg))\n","sub_path":"dngding_rober.py","file_name":"dngding_rober.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"583240386","text":"# !pip install -q tensorflow-gpu==2.0.0-rc1\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nbatch_size = 100\nepochs = 10000\nz_dim = 20\n\n# Noise for visualization\nz_vis = tf.random.normal([10, z_dim])\n\n# Load data\n(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()\nx_train = x_train / 255.0\nx_iter = iter(tf.data.Dataset.from_tensor_slices(x_train).shuffle(4 * batch_size).batch(batch_size).repeat())\n\n# Generator\nG = tf.keras.models.Sequential([\n tf.keras.layers.Dense(28*28 // 2, input_shape = (z_dim,), activation='relu'),\n tf.keras.layers.Dense(28*28, activation='sigmoid'),\n tf.keras.layers.Reshape((28, 28))])\n\n# Discriminator\nD = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(28*28 // 2, activation='relu'),\n tf.keras.layers.Dense(1)])\n\n# Loss functions\ncross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits = True)\ndef G_loss(D, x_fake):\n return cross_entropy(tf.ones_like(D(x_fake)), D(x_fake))\ndef D_loss(D, x_real, x_fake):\n return cross_entropy(tf.ones_like(D(x_real)), D(x_real)) + cross_entropy(tf.zeros_like(D(x_fake)), D(x_fake))\n\n# Optimizers\nG_opt = tf.keras.optimizers.Adam(1e-4)\nD_opt = tf.keras.optimizers.Adam(1e-4)\n\n# Train\nfor epoch in range(epochs):\n z_mb = tf.random.normal([batch_size, z_dim])\n x_real = next(x_iter)\n # Record operations\n with tf.GradientTape() as G_tape, tf.GradientTape() as D_tape: \n x_fake = G(z_mb)\n G_loss_curr = G_loss(D, x_fake)\n D_loss_curr = D_loss(D, x_real, x_fake)\n # Gradients\n G_grad = G_tape.gradient(G_loss_curr, G.trainable_variables)\n D_grad = D_tape.gradient(D_loss_curr, D.trainable_variables)\n # Apply gradients\n G_opt.apply_gradients(zip(G_grad, G.trainable_variables))\n D_opt.apply_gradients(zip(D_grad, D.trainable_variables))\n \n if epoch % 100 == 0:\n # Print results\n print('epoch: {}; G_loss: {:.6f}; D_loss: {:.6f}'.format(epoch+1, G_loss_curr, D_loss_curr))\n # Plot generated images\n for i in range(10):\n plt.subplot(2, 5, i+1)\n plt.imshow(G(z_vis)[i,:,:]*255.0)\n plt.axis('off')\n plt.show()\n","sub_path":"GAN.py","file_name":"GAN.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"566204887","text":"\"\"\"\n\n@author: Ying Meng (y(dot)meng201011(at)gmail(dot)com)\n\"\"\"\n\nimport os\nimport time\n\nimport models.svm_mnist as svm\nimport utils.model_utils as model_utils\nfrom attacks import craft_w_art\nfrom data.data import load_data\nfrom utils.file import *\nfrom utils.file import save_adv_examples\n\nMODEL_DIR = os.path.join(PATH.MODEL, 'svm_mnist')\nAE_DIR = os.path.join(PATH.ADVERSARIAL_FILE, 'svm_mnist')\n\ndef generate_adversarial_exmaple(model_file, X, Y, nb_classes, **attack_settings):\n print('@@@', attack_settings)\n assert model_file is not None\n\n attack = attack_settings['attack']\n attack_settings.__delitem__('attack')\n\n print('Loading model [{}]'.format(model_file))\n model = model_utils.load(model_file)\n\n print('Wrapping the model...')\n wrap_settings = {\n 'nb_classes': nb_classes,\n }\n model = model_utils.wrap(model, target_type='sklearnclassifier', **wrap_settings)\n\n X_adv = craft_w_art.craft(X, Y, model, attack=attack,\n **attack_settings)\n X_adv = np.clip(X_adv, 0., 1.)\n\n print('Test accuracy on clean: {}'.format(svm.evaluate(model, X, Y)))\n print('Test accuracy on AE: {}'.format(svm.evaluate(model, X_adv, Y)))\n\n # save adversarial examples\n save_adv_examples(X_adv, prefix='AE-test', dataset=DATA.mnist, transformation=TRANSFORMATION.clean,\n attack_method=attack, attack_params=attack_settings)\n return X_adv\n\n\ndef get_attack_conf(attack, i=2):\n # configs for paper\n attack_settings = {\n ATTACK.FGSM: {\n 'attack': ATTACK.FGSM,\n 'eps': 0.05 if i==0 else 0.15 if i==1 else 0.25,\n },\n ATTACK.BIM_L2: {\n 'attack': ATTACK.BIM_L2,\n 'eps': 0.75 if i==0 else 2.0 if i==1 else 9.5,\n },\n ATTACK.BIM_Li: {\n 'attack': ATTACK.BIM_Li,\n 'eps': 0.05 if i==0 else 0.1 if i==1 else 0.25,\n },\n ATTACK.JSMA: {\n 'attack': ATTACK.JSMA,\n 'theta': 2.0 if i==0 else 5.0 if i==1 else 35.0,\n },\n ATTACK.CW_L2: {\n 'attack': ATTACK.CW_L2,\n 'lr': 0.015 if i==0 else 0.015 if i==1 else 0.01,\n 'bsearch_steps': 10 if i==0 else 12 if i==1 else 20,\n },\n ATTACK.PGD: {\n 'attack': ATTACK.PGD,\n 'eps': 0.05 if i==0 else 0.075 if i==1 else 0.25,\n },\n }\n\n return attack_settings[attack]\n\n\nif __name__ == '__main__':\n (X_train, Y_train), (X_test, Y_test) = load_data(DATA.mnist)\n nb_tests, img_rows, img_cols, nb_channels = X_test.shape\n nb_samples = X_train.shape[0]\n nb_features = img_rows * img_cols * nb_channels\n nb_classes = Y_train.shape[1]\n\n # for test\n # nb_samples = 200\n # nb_tests = 200\n # X_train = X_train[:nb_samples]\n # Y_train = Y_train[:nb_samples]\n # X_test = X_test[:nb_tests]\n # Y_test = Y_test[:nb_tests]\n\n X_train = X_train.reshape(nb_samples, nb_features)\n X_test = X_test.reshape(nb_tests, nb_features)\n\n Y_train = np.argmax(Y_train, axis=1)\n Y_test = np.argmax(Y_test, axis=1)\n\n model_file = 'test-mnist-svm-clean.pkl'\n model_file = os.path.join(MODEL_DIR, model_file)\n\n data = {\n 'dataset': DATA.mnist,\n 'architecture': 'svm',\n }\n\n data['trans'] = TRANSFORMATION.clean\n data['train'] = (X_train, Y_train)\n data['test'] = (X_test, Y_test)\n\n # start = time.monotonic()\n # model = svm.train(data, svm.default_train_params)\n # duration = time.monotonic() - start\n # print('Training cost:', duration)\n # svm.save(model, model_file)\n\n start = time.monotonic()\n generate_adversarial_exmaple(model_file, X_test, Y_test,\n nb_classes, **get_attack_conf(ATTACK.CW_L2, 2))\n duration = time.monotonic() - start\n print('Generation cost:', duration)","sub_path":"src/tasks/craft_ae_svm_mnist.py","file_name":"craft_ae_svm_mnist.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"450210920","text":"# https://leetcode.com/problems/decode-ways/\n\"\"\"\nBacktracking (TLE)\nyou can have one digit or two. The first digits should not be 0 or it is non-effective\n\nYou also have to meet the following two requirements to have two digits.\n1. The first digits should not be zero\n2. The number is smaller than 26\n\"\"\"\nclass Solution:\n def numDecodings(self, s: str) -> int:\n res = []\n subset = []\n def dfs(i):\n if i >= len(s):\n res.append(subset.copy())\n return\n if s[i] != '0':\n subset.append(s[i])\n dfs(i + 1)\n subset.pop()\n if i + 1 < len(s) and int(s[i] + s[i + 1]) <= 26:\n subset.append(s[i] + s[i + 1])\n dfs(i + 2)\n subset.pop()\n dfs(0)\n return len(res)\n\n\"\"\"\nyou may notice that at index i, the possible solution depends on the resut from i+1(single digit) and i + 2 (double digits), \nso we have a fibonacchi dp[i] = dp[i + 1] + dp [i + 2]. But we have some constrains here, we can only have double digits if\n1. The first digits should not be zero\n2. The number is smaller than 26\n\nAnd also, if the initial is '0', we don't have any value at all, so we need to return 0\n\"\"\"\nclass Solution:\n def numDecodings(self, s: str) -> int:\n dp = {len(s) : 1}\n def dfs(i):\n if i in dp:\n return dp[i]\n if s[i] != '0':\n res = dfs(i + 1)\n if i + 1 < len(s) and int(s[i] + s[i + 1]) <= 26:\n res += dfs(i + 2)\n dp[i] = res\n return res\n return 0\n return dfs(0)","sub_path":"most_interviewed/dp/decode_ways.py","file_name":"decode_ways.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"342908867","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\n\nfrom panel.models import Character\n\n\ndef index(request):\n context = {'characters': Character.objects.all()}\n return render(request, 'index.html', context)\n\n\ndef info(request):\n if request.method == 'GET':\n return HttpResponse('ok')\n if request.method == 'POST':\n body = json.loads(request.body)\n\n for character_info in body['info']:\n defaults = {\n 'hostname': character_info['hostname'],\n 'yang': character_info['player_elk'],\n }\n\n character, created = Character.objects.update_or_create(\n name=character_info['player_name'], defaults=defaults)\n\n return HttpResponse('ok')\n","sub_path":"panel/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"607161447","text":"# Tung-Lin Lee\r\n# Assignment 7\r\nfrom Exercise6 import *\r\n\r\ndef contrastFillCircle(t) :\r\n '''fill the contrast color for filling the circle '''\r\n \r\n #initialize\r\n up()\r\n reset()\r\n down\r\n speed(100)\r\n \r\n userRadius = getRadius()\r\n if userRadius == -1:\r\n return False\r\n \r\n userColor = getColor()\r\n if userColor == \"unknown\":\r\n return False\r\n\r\n if userColor == \"red\":\r\n contrastColor = \"green\"\r\n elif userColor == \"blue\":\r\n contrastColor = \"pink\"\r\n else:\r\n contrastColor = \"brown\"\r\n \r\n numOfCircles = int(input(\"How many circles do you wnat?\"))\r\n if numOfCircles < 1 or numOfCircles > 20:\r\n print(\"number of circles must be between 1 and 20\")\r\n return -1\r\n\r\n x = 0\r\n y = 0\r\n for i in range(numOfCircles):\r\n begin_fill()\r\n drawCircle(t, userRadius, userColor)\r\n fillcolor(contrastColor)\r\n end_fill()\r\n userRadius -= userRadius/14\r\n x += userRadius/8\r\n y -= userRadius/8\r\n up()\r\n goto(x,y)\r\n down()\r\n right(36)\r\n return True\r\n\r\ndef main() :\r\n '''driver function'''\r\n choice = True\r\n t = Turtle()\r\n while choice == True:\r\n status = contrastFillCircle(t)\r\n if status == True:\r\n print(\"drawn\")\r\n else:\r\n print(\"sorry\")\r\n option = input(\"Continue? y/n:\")\r\n if option == \"y\" or option == \"Y\":\r\n choice = True\r\n else:\r\n choice = False\r\nmain()\r\n","sub_path":"CIS 40/HW7/Assignment7.py","file_name":"Assignment7.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"197255298","text":"import unittest, requests, json\n\nfrom dwolla import rest\nfrom mock import MagicMock\n\n\nclass RestTest(unittest.TestCase):\n '''\n We are testing the rest module against requests so that we see whether or not\n it is passing the proper request forward. Like this, we do not have to test\n against requests from other modules, but rather against rest.\n '''\n def setUp(self):\n # We make a new Rest object just in case any other\n # tests run before this one, so that they do not fail\n # because they are mocked.\n rest.r = rest.Rest()\n\n requests.post = MagicMock()\n requests.put = MagicMock()\n\n requests.get = MagicMock()\n requests.delete = MagicMock()\n json.loads = MagicMock()\n\n\n # In the below methods, dwollaparse is specified as values other than 'dwolla'\n # so as not to invoke an API exception since we evidently provide test data.\n\n def testpost(self):\n rest.r._post('/some/endpoint', {'key': 'value'}, {'alternate_token': 'AN OAUTH TOKEN', 'dwollaparse':'raw'}, custompostfix=False)\n requests.post.assert_any_call('https://sandbox.dwolla.com/oauth/rest/some/endpoint',\n '{\"key\": \"value\"}',\n headers={'Content-Type': 'application/json',\n 'User-Agent': 'dwolla-python/2.x',\n 'Authorization': 'AN OAUTH TOKEN'},\n proxies=False, timeout=15)\n\n def testpost_without_token(self):\n rest.r._post_without_token('/some/endpoint', {'key': 'value'}, {'dwollaparse':'raw'}, custompostfix=False)\n requests.post.assert_any_call('https://sandbox.dwolla.com/oauth/rest/some/endpoint',\n '{\"key\": \"value\"}',\n headers={'Content-Type': 'application/json',\n 'User-Agent': 'dwolla-python/2.x'},\n proxies=False, timeout=15)\n\n def testput(self):\n rest.r._put('/some/endpoint', {'key': 'value'}, {'alternate_token': 'AN OAUTH TOKEN', 'dwollaparse': 'raw'}, custompostfix=False)\n requests.put.assert_any_call('https://sandbox.dwolla.com/oauth/rest/some/endpoint',\n '{\"key\": \"value\"}',\n headers={'Content-Type': 'application/json',\n 'User-Agent': 'dwolla-python/2.x',\n 'Authorization': 'AN OAUTH TOKEN'},\n proxies=False, timeout=15)\n\n def testget(self):\n rest.r._get('/another/endpoint', {'another_key': 'another_value'}, {'alternate_token': 'AN OAUTH TOKEN', 'dwollaparse':'raw'})\n requests.get.assert_any_call('https://sandbox.dwolla.com/oauth/rest/another/endpoint',\n headers={'User-Agent': 'dwolla-python/2.x', 'Authorization': 'AN OAUTH TOKEN'},\n params={'another_key': 'another_value'},\n proxies=False, timeout=15)\n\n def testget_without_token(self):\n rest.r._get_without_token('/another/endpoint', {'another_key': 'another_value'}, {'dwollaparse':'raw'})\n requests.get.assert_any_call('https://sandbox.dwolla.com/oauth/rest/another/endpoint',\n headers={'User-Agent': 'dwolla-python/2.x'},\n params={'another_key': 'another_value'},\n proxies=False, timeout=15)\n\n def testdelete(self):\n rest.r._delete('/another/endpoint', {'another_key': 'another_value'}, {'alternate_token': 'AN OAUTH TOKEN', 'dwollaparse':'raw'})\n requests.delete.assert_any_call('https://sandbox.dwolla.com/oauth/rest/another/endpoint',\n headers={'User-Agent': 'dwolla-python/2.x', 'Authorization': 'AN OAUTH TOKEN'},\n params={'another_key': 'another_value'},\n proxies=False, timeout=15)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/testRest.py","file_name":"testRest.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"601436384","text":"from absl import app\nfrom absl import flags\nfrom tqdm import tqdm\nfrom transformers import get_linear_schedule_with_warmup\nimport numpy as np\nimport torch\nimport transformers\nfrom torch import nn, optim\nfrom torch.utils import data\nfrom collections import defaultdict\nimport os\nfrom model import BERTSentimentAnalyser\nfrom dataset import createDataLoader\nfrom utils import read_imdb\nfrom sklearn.metrics import f1_score\nimport logging\nimport time\n\n\nlogger = logging.getLogger(\"Assignment-1\")\nlogger.handlers = []\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('pre_trained_model_name', 'bert-base-uncased', 'Name of the pre-trained model to use')\nflags.DEFINE_string('data_path', './imdb dataset', 'Path to dataset')\nflags.DEFINE_float('lr', 2e-5, 'Learning Rate')\nflags.DEFINE_integer('epochs', 5, 'Number of training epochs')\nflags.DEFINE_integer('batch_size', 8, 'Train/eval batch size')\nflags.DEFINE_integer('max_len', 512, 'Maximum input sequence length')\nflags.DEFINE_string('output_path', './model_logs', 'Output path for model and logs')\nflags.DEFINE_bool('do_train', True, 'Set flag for training')\nflags.DEFINE_bool('do_eval', True, 'Set flag for evaluation')\nflags.DEFINE_bool('do_test', False, 'Set flag for testing')\nflags.DEFINE_string('load_model_path', '', 'Path to load saved model for testing')\n\n\n\ndef train_loop(\n model, \n data_loader,\n loss_fn,\n optimizer,\n device,\n scheduler,\n n_examples,\n epoch_num, batch_size):\n\n model = model.train()\n losses = []\n correct_predictions = 0\n\n f1 = 0\n batch_num = 0\n with tqdm(data_loader, unit=\"batch\") as tepoch:\n for batch in tepoch:\n \n tepoch.set_description(f\"Epoch {epoch_num}\")\n\n input_ids = batch['input_ids'].to(device)\n attention_mask = batch['attention_mask'].to(device)\n labels = batch['label'].to(device)\n\n # print(input_ids.shape)\n # print(attention_mask.shape)\n # print(labels.shape)\n outputs = model(input_ids = input_ids, attention_mask = attention_mask)\n\n _, preds = torch.max(outputs, dim = 1)\n\n loss = loss_fn(outputs, labels)\n\n batch_correct = torch.sum(preds == labels)\n correct_predictions += batch_correct \n losses.append(loss.item())\n\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), max_norm = 1.0)\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n \n f1 += f1_score(labels.cpu(), preds.cpu())\n batch_num += 1 \n\n\n \n\n tepoch.set_postfix(loss=loss.item(), accuracy=100. * (batch_correct.item()/batch_size))\n \n mean_loss = np.mean(losses)\n accuracy = correct_predictions.double()/n_examples\n return f1/batch_num, accuracy, mean_loss\n\n\ndef eval(model, data_loader, loss_fn, device, n_examples):\n model = model.eval()\n\n losses = []\n correct_predictions = 0\n\n f1 = 0\n batch_num = 0\n\n with torch.no_grad():\n with tqdm(data_loader, unit=\"batch\") as tepoch:\n for batch in tepoch:\n input_ids = batch['input_ids'].to(device)\n attention_mask = batch['attention_mask'].to(device)\n labels = batch['label'].to(device)\n\n outputs = model(input_ids = input_ids, attention_mask = attention_mask)\n\n _, preds = torch.max(outputs, dim = 1)\n\n loss = loss_fn(outputs, labels)\n \n f1 += f1_score(labels.cpu(), preds.cpu())\n batch_num += 1 \n\n correct_predictions += torch.sum(preds == labels)\n losses.append(loss.item())\n return f1/batch_num, correct_predictions.double()/n_examples, np.mean(losses)\n \n\n\n\ndef main(argv):\n\n if not os.path.exists(FLAGS.output_path):\n os.makedirs(FLAGS.output_path)\n\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n fh = logging.FileHandler(os.path.join(FLAGS.output_path, timestr+\".log\"))\n fh.setLevel(logging.INFO)\n logger.addHandler(fh)\n\n\n \n\n train_path = os.path.join(FLAGS.data_path, \"Train.csv\")\n test_path = os.path.join(FLAGS.data_path, \"Test.csv\")\n val_path = os.path.join(FLAGS.data_path, \"Valid.csv\")\n\n train_texts, train_labels = read_imdb(train_path)\n test_texts, test_labels = read_imdb(test_path)\n val_texts, val_labels = read_imdb(val_path)\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\n tokenizer = transformers.BertTokenizer.from_pretrained(FLAGS.pre_trained_model_name)\n loss_fn = nn.CrossEntropyLoss().to(device)\n\n if(FLAGS.do_train):\n train_DataLoader = createDataLoader(train_texts, train_labels, tokenizer, FLAGS.max_len, FLAGS.batch_size)\n if(FLAGS.do_test):\n test_DataLoader = createDataLoader(test_texts, test_labels, tokenizer, FLAGS.max_len, FLAGS.batch_size)\n if(FLAGS.do_eval):\n val_DataLoader = createDataLoader(val_texts, val_labels, tokenizer, FLAGS.max_len, FLAGS.batch_size)\n\n if(FLAGS.do_train):\n model = BERTSentimentAnalyser()\n\n optimizer = transformers.AdamW(model.parameters(), lr = FLAGS.lr, correct_bias = False)\n\n total_steps = len(train_DataLoader)*FLAGS.epochs\n\n scheduler = get_linear_schedule_with_warmup(\n optimizer,\n num_warmup_steps = 0,\n num_training_steps = total_steps\n )\n\n \n\n best_f1 = 0\n model = model.to(device)\n #scheduler = scheduler.to(device)\n #optimizer = optimizer.to(device)\n for epoch in range(FLAGS.epochs):\n train_epoch_f1, train_epoch_acc, train_epoch_loss = train_loop(\n model, \n train_DataLoader,\n loss_fn,\n optimizer,\n device,\n scheduler,\n len(train_texts),\n epoch+1,\n FLAGS.batch_size\n )\n\n print(f'Train loss: {train_epoch_loss} accuracy: {train_epoch_acc} F1: {train_epoch_f1}')\n logger.info(f'Train loss: {train_epoch_loss} accuracy: {train_epoch_acc} F1: {train_epoch_f1}')\n\n if(FLAGS.do_eval):\n val_epoch_f1, val_epoch_acc, val_epoch_loss = eval(\n model, \n val_DataLoader,\n loss_fn,\n device,\n len(val_texts)\n )\n print(f'Validation loss: {val_epoch_loss} accuracy: {val_epoch_acc} F1: {val_epoch_f1}')\n logger.info(f'Validation loss: {val_epoch_loss} accuracy: {val_epoch_acc} F1: {val_epoch_f1}')\n\n if(val_epoch_f1>best_f1):\n torch.save(model.state_dict(), os.path.join(FLAGS.output_path, 'best_model_state.bin'))\n best_f1 = val_epoch_f1\n \n else:\n if(train_epoch_f1>best_f1):\n torch.save(model.state_dict(), os.path.join(FLAGS.output_path, 'best_model_state.bin'))\n best_f1 = train_epoch_f1\n\n \n \n\n if(FLAGS.do_test):\n \n model = BERTSentimentAnalyser()\n model = model.to(device)\n\n if not FLAGS.load_model_path:\n model.load_state_dict(torch.load(os.path.join(FLAGS.output_path,'best_model_state.bin')))\n else:\n model.load_state_dict(torch.load(os.path.join(FLAGS.load_model_path,'best_model_state.bin')))\n\n test_f1, test_acc, test_loss = eval(\n model, \n test_DataLoader,\n loss_fn,\n device,\n len(test_texts)\n )\n print(f'Test loss: {test_loss} accuracy: {test_acc} F1: {test_f1}')\n logger.info(f'Test loss: {test_loss} accuracy: {test_acc} F1: {test_f1}')\n\n\n\nif __name__ == '__main__':\n app.run(main)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"262164581","text":"# -*- coding: utf-8 -*-\n\nfrom flask_testing import TestCase\nimport unittest\n\nimport exportsrv.app as app\n\nfrom stubdata import solrdata, bibTexTest, fieldedTest, xmlTest, cslTest, customTest, voTableTest, rssTest\nfrom exportsrv.views import default_solr_fields, return_bibTex_format_export, return_fielded_format_export, \\\n return_xml_format_export, return_csl_format_export, return_votable_format_export, return_rss_format_export\nfrom exportsrv.formatter.format import Format\nfrom exportsrv.formatter.bibTexFormat import BibTexFormat\nfrom exportsrv.formatter.fieldedFormat import FieldedFormat\nfrom exportsrv.formatter.xmlFormat import XMLFormat\nfrom exportsrv.formatter.cslJson import CSLJson\nfrom exportsrv.formatter.csl import CSL, adsFormatter\nfrom exportsrv.formatter.customFormat import CustomFormat\nfrom exportsrv.formatter.convertCF import convert\nfrom exportsrv.formatter.voTableFormat import VOTableFormat\nfrom exportsrv.formatter.rssFormat import RSSFormat\nfrom exportsrv.utils import get_eprint\n\n\nclass TestExports(TestCase):\n def create_app(self):\n app_ = app.create_app()\n return app_\n\n def test_bibtex(self):\n # format the stubdata using the code\n bibtex_export = BibTexFormat(solrdata.data).get(include_abs=False)\n # now compare it with an already formatted data that we know is correct\n assert (bibtex_export == bibTexTest.data)\n\n def test_bibtex_with_abs(self):\n # format the stubdata using the code\n bibtex_export = BibTexFormat(solrdata.data).get(include_abs=True)\n # now compare it with an already formatted data that we know is correct\n assert (bibtex_export == bibTexTest.data_with_abs)\n\n def test_ads(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_ads_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_ads)\n\n def test_endnote(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_endnote_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_endnote)\n\n def test_procite(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_procite_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_procite)\n\n def test_refman(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_refman_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_refman)\n\n def test_refworks(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_refworks_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_refworks)\n\n def test_medlars(self):\n # format the stubdata using the code\n fielded_export = FieldedFormat(solrdata.data).get_medlars_fielded()\n # now compare it with an already formatted data that we know is correct\n assert (fielded_export == fieldedTest.data_medlars)\n\n def test_dublinxml(self):\n # format the stubdata using the code\n xml_export = XMLFormat(solrdata.data).get_dublincore_xml()\n # now compare it with an already formatted data that we know is correct\n assert(xml_export == xmlTest.data_dublin_core)\n\n def test_refxml(self):\n # format the stubdata using the code\n xml_export = XMLFormat(solrdata.data).get_reference_xml(include_abs=False)\n # now compare it with an already formatted data that we know is correct\n assert(xml_export == xmlTest.data_ref)\n\n def test_refxml_with_abs(self):\n # format the stubdata using the code\n xml_export = XMLFormat(solrdata.data).get_reference_xml(include_abs=True)\n # now compare it with an already formatted data that we know is correct\n assert(xml_export == xmlTest.data_ref_with_abs)\n\n def test_aastex(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'aastex', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_AASTex)\n\n def test_icarus(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'icarus', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_Icarus)\n\n def test_mnras(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'mnras', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert(csl_export == cslTest.data_MNRAS)\n\n def test_soph(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'soph', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_SoPh)\n\n def test_aspc(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'aspc', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_ASPC)\n\n def test_apsj(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'apsj', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_APSJ)\n\n def test_aasj(self):\n # format the stubdata using the code\n csl_export = CSL(CSLJson(solrdata.data).get(), 'aasj', adsFormatter.latex).get()\n # now compare it with an already formatted data that we know is correct\n assert (csl_export == cslTest.data_AASJ)\n\n def test_custom(self):\n # format the stubdata using the code\n custom_format = CustomFormat(custom_format=r'\\\\bibitem[%m\\(%Y)]{%2H%Y}\\ %5.3l\\ %Y\\,%j\\,%V\\,%p \\n')\n custom_format.set_json_from_solr(solrdata.data)\n # now compare it with an already formatted data that we know is correct\n assert (custom_format.get() == customTest.data)\n # verify correct solr fields are fetched\n assert (custom_format.get_solr_fields() == 'author,year,pub,volume,page,bibcode')\n\n def test_convert(self):\n assert(convert(\"\\\\\\\\bibitem[%\\\\2m%(y)]\\{%za1%y} %\\\\8l %\\\\Y,%\\\\j,%\\\\V,%\\\\p\") == \"\\\\\\\\bibitem[%2m\\\\(%Y)]\\\\{%H%Y} %8l\\\\ %Y\\\\,%j\\\\,%V\\\\,%p\\\\\")\n\n def test_ads_formatter(self):\n assert(adsFormatter().verify('1'), True)\n assert(adsFormatter().verify(1), True)\n assert(adsFormatter().verify('10'), False)\n assert(adsFormatter().verify(10), False)\n\n def test_default_solr_fields(self):\n default_fields = 'author,title,year,date,pub,pub_raw,issue,volume,page,page_range,aff,doi,abstract,' \\\n 'citation_count,read_count,bibcode,identifier,copyright,keyword,doctype,' \\\n 'reference,comment,property,esources,data,isbn,pubnote,eid'\n assert (default_solr_fields() == default_fields)\n\n def test_bibtex_success(self):\n response = return_bibTex_format_export(solrdata.data, False)\n assert(response._status_code == 200)\n\n def test_bibtex_no_data(self):\n response = return_bibTex_format_export(None, False)\n assert(response._status_code == 404)\n\n def test_bibtex_data_error(self):\n solr_data = {\"error\" : \"data error\"}\n response = return_bibTex_format_export(solr_data, False)\n assert(response._status_code == 400)\n\n def test_fielded_success(self):\n for fielded_style in ['ADS','EndNote','ProCite','Refman','RefWorks','MEDLARS']:\n response = return_fielded_format_export(solrdata.data, fielded_style)\n assert(response._status_code == 200)\n\n def test_fielded_no_data(self):\n for fielded_style in ['ADS','EndNote','ProCite','Refman','RefWorks','MEDLARS']:\n response = return_fielded_format_export(None, fielded_style)\n assert(response._status_code == 404)\n\n def test_fielded_data_error(self):\n solr_data = {\"error\" : \"data error\"}\n for fielded_style in ['ADS','EndNote','ProCite','Refman','RefWorks','MEDLARS']:\n response = return_fielded_format_export(solr_data, fielded_style)\n assert(response._status_code == 400)\n\n def test_xml_success(self):\n for xml_style in ['DublinCore','Reference','ReferenceAbs']:\n response = return_xml_format_export(solrdata.data, xml_style)\n assert(response._status_code == 200)\n\n def test_xml_no_data(self):\n for xml_style in ['DublinCore','Reference','ReferenceAbs']:\n response = return_xml_format_export(None, xml_style)\n assert(response._status_code == 404)\n\n def test_xml_data_error(self):\n solr_data = {\"error\" : \"data error\"}\n for xml_style in ['DublinCore','Reference','ReferenceAbs']:\n response = return_xml_format_export(solr_data, xml_style)\n assert(response._status_code == 400)\n\n def test_csl(self):\n export_format = 2\n for csl_style in ['aastex','icarus','mnras', 'soph', 'aspc', 'apsj', 'aasj']:\n response = return_csl_format_export(solrdata.data, csl_style, export_format)\n assert(response._status_code == 200)\n\n def test_csl_no_data(self):\n export_format = 2\n for csl_style in ['aastex','icarus','mnras', 'soph', 'aspc', 'apsj', 'aasj']:\n response = return_csl_format_export(None, csl_style, export_format)\n assert(response._status_code == 404)\n\n def test_csl_data_error(self):\n export_format = 2\n solr_data = {\"error\" : \"data error\"}\n for csl_style in ['aastex','icarus','mnras', 'soph', 'aspc', 'apsj', 'aasj']:\n response = return_csl_format_export(solr_data, csl_style, export_format)\n assert(response._status_code == 400)\n\n\n def test_eprint(self):\n a_doc_no_eprint = solrdata.data['response'].get('docs')[0]\n assert (get_eprint(a_doc_no_eprint) == '')\n\n a_doc_arxiv = \\\n {\n \"bibcode\": \"2018arXiv180303598K\",\n \"eid\": \"arXiv:1803.03598\"\n }\n assert (get_eprint(a_doc_arxiv) == 'arXiv:1803.03598')\n\n a_doc_ascl = \\\n {\n \"bibcode\": \"2013ascl.soft08009C\",\n \"eid\": \"ascl:1308.009\"\n }\n assert (get_eprint(a_doc_ascl) == 'ascl:1308.009')\n\n def test_format_status(self):\n format_export = Format(solrdata.data)\n assert(format_export.get_status() == 0)\n\n def test_format_no_num_docs(self):\n solr_data = \\\n {\n \"responseHeader\":{\n \"status\":1,\n \"QTime\":1,\n \"params\":{\n \"sort\":\"date desc\",\n \"fq\":\"{!bitset}\",\n \"rows\":\"19\",\n \"q\":\"*:*\",\n \"start\":\"0\",\n \"wt\":\"json\",\n \"fl\":\"author,title,year,date,pub,pub_raw,issue,volume,page,page_range,aff,doi,abstract,citation_count,read_count,bibcode,identification,copyright,keyword,doctype,reference,comment,property,esources,data\"\n }\n }\n }\n format_export = Format(solr_data)\n assert(format_export.get_num_docs() == 0)\n\n def test_votable(self):\n # format the stubdata using the code\n votable_export = VOTableFormat(solrdata.data).get()\n # now compare it with an already formatted data that we know is correct\n assert (votable_export == voTableTest.data)\n\n def test_rss(self):\n # format the stubdata using the code\n rss_export = RSSFormat(solrdata.data).get()\n # now compare it with an already formatted data that we know is correct\n assert (rss_export == rssTest.data)\n\n def test_votable_success(self):\n response = return_votable_format_export(solrdata.data)\n assert(response._status_code == 200)\n\n def test_votable_no_data(self):\n response = return_votable_format_export(None)\n assert(response._status_code == 404)\n\n def test_votable_data_error(self):\n solr_data = {\"error\" : \"data error\"}\n response = return_votable_format_export(solr_data)\n assert(response._status_code == 400)\n\n def test_rss_success(self):\n response = return_rss_format_export(solrdata.data, '')\n assert(response._status_code == 200)\n\n def test_rss_no_data(self):\n response = return_rss_format_export(None, '')\n assert(response._status_code == 404)\n\n def test_rss_data_error(self):\n solr_data = {\"error\" : \"data error\"}\n response = return_rss_format_export(solr_data, '')\n assert(response._status_code == 400)\n\n def test_rss_authors(self):\n solr_data = \\\n {\n \"responseHeader\": {\n \"status\": 0,\n \"QTime\": 1,\n \"params\": {\n \"sort\": \"date desc\",\n \"fq\": \"{!bitset}\",\n \"rows\": \"19\",\n \"q\": \"*:*\",\n \"start\": \"0\",\n \"wt\": \"json\",\n \"fl\": \"author,title,year,date,pub,pub_raw,issue,volume,page,page_range,aff,doi,abstract,citation_count,read_count,bibcode,identification,copyright,keyword,doctype,reference,comment,property,esources,data\"\n }\n },\n \"response\": {\n \"start\": 0,\n \"numFound\": 4,\n \"docs\": [\n {\n \"title\": [\n \"A Microwave Free-Space Method Using Artificial Lens with Anti-reflection Layer\"\n ],\n \"author\": [\n \"Zhang, Yangjun\",\n \"Aratani, Yuki\",\n \"Nakazima, Hironari\"\n ],\n },\n {\n \"author\": [\n \"Ryan, R. E.\",\n \"McCullough, P. R.\"\n ],\n },\n {\n \"title\": [\n \"Resolving Gas-Phase Metallicity In Galaxies\"\n ],\n },\n {\n \"bibcode\": \"2017ascl.soft06009C\",\n },\n ]\n }\n }\n rss_export = RSSFormat(solrdata.data)\n # both author and title exists\n assert(rss_export._RSSFormat__get_author_title(solr_data['response'].get('docs')[0]) ==\n 'Zhang, Yangjun: A Microwave Free-Space Method Using Artificial Lens with Anti-reflection Layer')\n # only author\n assert(rss_export._RSSFormat__get_author_title(solr_data['response'].get('docs')[1]) == 'Ryan, R. E.')\n # only title\n assert(rss_export._RSSFormat__get_author_title(solr_data['response'].get('docs')[2]) ==\n 'Resolving Gas-Phase Metallicity In Galaxies')\n # neither author nor title exists\n assert(rss_export._RSSFormat__get_author_title(solr_data['response'].get('docs')[3]) == '')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"exportsrv/tests/unittests/test_export_service.py","file_name":"test_export_service.py","file_ext":"py","file_size_in_byte":16115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"206286097","text":"import math\nimport heapq\n\nclass minHeap(object):\n\tdef __init__(self, A=None):\n\t\tself.heap = A if A is not None else []\n\n\tdef swap(self, x, y):\n\t\ttemp = self.heap[x]\n\t\tself.heap[x] = self.heap[y]\n\t\tself.heap[y] = temp\n\n\tdef heapify(self, i):\n\t\tleft_idx = 2*i\n\t\tright_idx = (2*i) + 1\n\t\tsmallest = i\n\n\t\tif left_idx < len(self.heap) and self.heap[left_idx] < self.heap[i]:\n\t\t\tsmallest = left_idx\n\n\t\tif right_idx < len(self.heap) and self.heap[right_idx] < self.heap[smallest]:\n\t\t\tsmallest = right_idx\n\n\t\tif smallest != i:\n\t\t\tself.swap(i, smallest)\n\t\t\tself.heapify(smallest)\n\n\n\tdef build_heap(self):\n\t\tfor i in reversed(range(0, len(self.heap)//2)):\n\t\t\tself.heapify(i)\n\n\tdef insert(self, val):\n\t\tself.heap.append(val)\n\n\t\t# Bubble up\n\t\tcurr = len(self.heap) - 1\n\t\twhile curr > 0:\n\t\t\tparent = (curr-1)//2\n\t\t\tif self.heap[curr] < self.heap[parent]:\n\t\t\t\tself.swap(curr, parent)\n\t\t\t\tcurr = parent\n\t\t\telse:\n\t\t\t\tbreak\n\n\tdef extract_min(self):\n\t\tmin_val = self.heap.pop(0)\n\t\tself.swap(0, len(self.heap)-1)\n\t\tself.heapify(0)\n\t\treturn min_val\n\n\tdef __repr__(self):\n\t\treturn str(self.heap)\n\n\narr = [1, 3, 2, 10, 5, 2]\nheap = minHeap(arr)\nheap.build_heap()\n\nprint(heap)\nheap.insert(0)\nprint(heap)\nheap.insert(22)\nprint(heap)\nret = heap.extract_min()\nprint(\"returned {}\".format(ret))\nprint(heap)\n\n","sub_path":"Python/minHeap.py","file_name":"minHeap.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"4151520","text":"#!/usr/bin/env python3\nfrom dataReadWrite.ReadWriteHmetis import ReadWriteHmetis\nfrom dataReadWrite.ReadWriteKahip import ReadWriteKahip\nfrom dataReadWrite.ReadWriteKahypar import ReadWriteKahypar\nfrom dataReadWrite.ReadWritePatoh import ReadWritePatoh\nfrom dataReadWrite.ReadWriteWhmetis import ReadWriteWhmetis\n\nALGORITHMS = {\n \"hmetis\": ReadWriteHmetis,\n \"whmetis\": ReadWriteWhmetis,\n \"kahypar\": ReadWriteKahypar,\n \"kahip\": ReadWriteKahip,\n \"patoh\": ReadWritePatoh\n}\n\nALGO_RUN_TEMPLATES = {\n\n \"hmetis\": \"shmetis graph {num_clusters} 15\", # 15 is the unbalance factor\n\n \"kahip\": \"kaffpa graph --k={num_clusters} --preconfiguration=strong\",\n\n # \"metis\": \"gpmetis graph {num_clusters}\",\n\n # 0.01 is the imbalance factor\n # NOTE: For KaHyPar, all files under kahypar/config should be symlinked to\n # your home directory (or just cut_rKaHyPar_dissertation.ini)\n \"kahypar\": \"KaHyPar -h graph -k {num_clusters} -e 0.01 -o cut -m recursive -p ~/cut_rKaHyPar_dissertation.ini\",\n\n \"patoh\": \"patoh graph {num_clusters}\"\n\n}\n\nassert all(algo in ALGORITHMS for algo in ALGO_RUN_TEMPLATES)\n","sub_path":"python/dataReadWrite/ReadWriteAll.py","file_name":"ReadWriteAll.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"428940041","text":"#!/usr/bin/env python\n\n# Standard imports\nfrom operator import attrgetter\nfrom math import pi, sqrt, cosh, cos, acos\nimport ROOT, os\n\n# RootTools\nfrom RootTools.core.standard import *\n\n# helpers\nfrom Analysis.Tools.helpers import deltaPhi, deltaR2, deltaR, getCollection, getObjDict\nfrom Analysis.Tools.WeightInfo import WeightInfo\n\nfrom Analysis.Tools.leptonJetArbitration import cleanJetsAndLeptons\n\njetVars = ['pt/F', 'eta/F', 'phi/F', 'btagDeepB/F', 'btagDeepFlavB/F', 'index/I']\n\njetVarNames = [x.split('/')[0] for x in jetVars]\n\nlstm_jets_maxN = 10\nlstm_jetVars = ['pt/F', 'eta/F', 'phi/F', 'btagDeepFlavB/F', 'btagDeepFlavC/F', 'chEmEF/F', 'chHEF/F', 'neEmEF/F', 'neHEF/F', 'muEF/F', 'puId/F', 'qgl/F']\nlstm_jetVarNames = [x.split('/')[0] for x in lstm_jetVars]\n\nlepVars = ['pt/F','eta/F','phi/F','pdgId/I','cutBased/I','miniPFRelIso_all/F','pfRelIso03_all/F','mvaFall17V2Iso_WP90/O', 'mvaTOP/F', 'sip3d/F','lostHits/I','convVeto/I','dxy/F','dz/F','charge/I','deltaEtaSC/F','mediumId/I','eleIndex/I','muIndex/I']\nlepVarNames = [x.split('/')[0] for x in lepVars]\n\n# Training variables\nread_variables = [\\\n \"nBTag/I\",\n \"nJetGood/I\",\n \"nlep/I\",\n \"m3/F\",\n \"JetGood[%s]\"%(\",\".join(jetVars)),\n \"Jet[%s]\"%(\",\".join(lstm_jetVars)),\n \"lep[%s]\"%(\",\".join(lepVars)),\n \"met_pt/F\", \"met_phi/F\",\n \"l1_pt/F\",\n \"l1_eta/F\",\n \"l1_phi/F\",\n \"l2_pt/F\",\n \"l2_eta/F\",\n \"l2_phi/F\",\n #\"l3_pt/F\",\n #\"l3_eta/F\",\n #\"l3_phi/F\",\n \"l1_mvaTOP/F\",\n \"l2_mvaTOP/F\",\n #\"l3_mvaTOP/F\",\n \"year/I\",\n ]\n# sequence \nsequence = []\n\n# Fisher informations\nFIs = {\n}\n\n# Reco b-Jet Filter\ndef isBJet( j, tagger='DeepCSV', year=2016 ):\n if tagger == 'CSVv2':\n if year == 2016:\n # https://twiki.cern.ch/twikix/bin/viewauth/CMS/BtagRecommendation80XReReco\n return j['btagCSVV2'] > 0.8484 \n elif year == 2017:\n # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation94X\n return j['btagCSVV2'] > 0.8838 \n elif year == 2018:\n # UPDATE WHEN AVAILABLE\n return j['btagCSVV2'] > 0.8838 \n else:\n raise (NotImplementedError, \"Don't know what cut to use for year %s\"%year)\n elif tagger == 'DeepCSV':\n if year == 2016:\n # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation2016Legacy\n return j['btagDeepB'] > 0.6321\n elif year == 2017:\n # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation94X\n return j['btagDeepB'] > 0.4941\n elif year == 2018:\n # https://twiki.cern.ch/twiki/bin/viewauth/CMS/BtagRecommendation102X\n return j['btagDeepB'] > 0.4184\n else:\n raise (NotImplementedError, \"Don't know what cut to use for year %s\"%year)\n\ndef make_jets( event, sample ):\n event.jets = [getObjDict(event, 'JetGood_', jetVarNames, i) for i in range(int(event.nJetGood))] \n event.bJets = filter(lambda j:isBJet(j, year=event.year) and abs(j['eta'])<=2.4 , event.jets)\nsequence.append( make_jets )\n\ndef get_mll(event, sample):\n event.mll = sqrt(2*(event.l1_pt)*(event.l2_pt)*(cosh(event.l1_eta-event.l2_eta)-cos(event.l1_phi-event.l2_phi)))\nsequence.append(get_mll)\n\ndef getDeltaR(event, sample):\n if len(event.jets) >= 1:\n event.minDRjet_l1 = min(deltaR({'eta':event.jets[j]['eta'], 'phi':event.jets[j]['phi']}, {'eta':event.l1_eta, 'phi':event.l1_phi}) for j in range(len(event.jets)) )\n event.minDRjet_l2 = min(deltaR({'eta':event.jets[j]['eta'], 'phi':event.jets[j]['phi']}, {'eta':event.l2_eta, 'phi':event.l2_phi}) for j in range(len(event.jets)))\n else: \n event.minDRjet_l1 = -1 \n event.minDRjet_l2 = -1\n if len(event.bJets) >= 1:\n event.minDRbjet_l1 = min(deltaR({'eta':event.bJets[b]['eta'], 'phi':event.bJets[b]['phi']}, {'eta':event.l1_eta, 'phi':event.l1_phi}) for b in range(len(event.bJets) ))\n event.minDRbjet_l2 = min(deltaR({'eta':event.bJets[b]['eta'], 'phi':event.bJets[b]['phi']}, {'eta':event.l2_eta, 'phi':event.l2_phi}) for b in range(len(event.bJets )))\n else: \n event.minDRbjet_l1 = -1 \n event.minDRbjet_l2 = -1\nsequence.append(getDeltaR)\n\nall_mva_variables = {\n\n# global event properties \n \"mva_nJetGood\" :(lambda event, sample: event.nJetGood),\n \"mva_nBTag\" :(lambda event, sample: event.nBTag),\n# \"mva_nlep\" :(lambda event, sample: event.nlep),\n\n \"mva_met_pt\" :(lambda event, sample: event.met_pt),\n \"mva_l1_pt\" :(lambda event, sample: event.l1_pt),\n \"mva_l1_eta\" :(lambda event, sample: event.l1_eta),\n \"mva_l2_pt\" :(lambda event, sample: event.l2_pt),\n \"mva_l2_eta\" :(lambda event, sample: event.l2_eta),\n \"mva_l1_phi\" :(lambda event, sample: event.l1_phi),\n \"mva_l2_phi\" :(lambda event, sample: event.l2_phi),\n\n \"mva_mll\" :(lambda event, sample: event.mll),\n \"mva_l1_relIso\" :(lambda event, sample: event.lep_pfRelIso03_all[0]),\n \"mva_l2_relIso\" :(lambda event, sample: event.lep_pfRelIso03_all[1]),\n\n \"mva_ht\" :(lambda event, sample: sum( [j['pt'] for j in event.jets] ) ),\n\n \"mva_jet0_pt\" :(lambda event, sample: event.JetGood_pt[0] if event.nJetGood >=1 else 0),\n \"mva_jet0_eta\" :(lambda event, sample: event.JetGood_eta[0] if event.nJetGood >=1 else -10),\n \"mva_jet0_btagDeepB\" :(lambda event, sample: event.JetGood_btagDeepB[0] if (event.nJetGood >=1 and event.JetGood_btagDeepB[0]>-10) else -10),\n \"mva_jet1_pt\" :(lambda event, sample: event.JetGood_pt[1] if event.nJetGood >=2 else 0),\n \"mva_jet1_eta\" :(lambda event, sample: event.JetGood_eta[1] if event.nJetGood >=2 else -10),\n \"mva_jet2_pt\" :(lambda event, sample: event.JetGood_pt[2] if event.nJetGood >=3 else 0),\n \"mva_jet2_eta\" :(lambda event, sample: event.JetGood_eta[2] if event.nJetGood >=3 else -10),\n\n \"mva_jet3_pt\" :(lambda event, sample: event.JetGood_pt[2] if event.nJetGood >=4 else 0),\n \"mva_jet4_pt\" :(lambda event, sample: event.JetGood_pt[2] if event.nJetGood >=5 else 0),\n \"mva_jet5_pt\" :(lambda event, sample: event.JetGood_pt[2] if event.nJetGood >=6 else 0),\n\n \"mva_minDR_jl1\" :(lambda event, sample: event.minDRjet_l1 ),\n \"mva_minDR_bjl1\" :(lambda event, sample: event.minDRbjet_l1 ),\n \"mva_minDR_jl2\" :(lambda event, sample: event.minDRjet_l2 ),\n \"mva_minDR_bjl1\" :(lambda event, sample: event.minDRbjet_l2 ),\n\n }\n\ndef lstm_jets(event, sample):\n jets = [ getObjDict( event, 'Jet_', lstm_jetVarNames, event.JetGood_index[i] ) for i in range(int(event.nJetGood)) ]\n return jets\n\n# for the filler\nmva_vector_variables = {\n \"mva_Jet\": {\"func\":lstm_jets, \"name\":\"Jet\", \"vars\":lstm_jetVars, \"varnames\":lstm_jetVarNames}\n}\n\n## Using all variables\nmva_variables_ = all_mva_variables.keys()\nmva_variables_.sort()\nmva_variables = [ (key, value) for key, value in all_mva_variables.iteritems() if key in mva_variables_ ]\n\n# keep these branches in ntuple making\nkeep_branches = [\"GenMET_pt\", \"GenMET_phi\"]\n\nimport numpy as np\nimport operator\n\n# make predictions to be used with keras.predict\ndef predict_inputs( event, sample, jet_lstm = False):\n flat_variables = np.array([[getattr( event, mva_variable) for mva_variable, _ in mva_variables]])\n if jet_lstm:\n lstm_jets_maxN = 10 #remove after retraining\n jet_vector_var = mva_vector_variables[\"mva_Jet\"]\n jets = mva_vector_variables[\"mva_Jet\"][\"func\"](event,sample=None)\n jets = [ [ operator.itemgetter(varname)(jet) for varname in lstm_jetVarNames] for jet in jets[:lstm_jets_maxN] ]\n # zero padding\n jets += [ [0.]*len(lstm_jetVarNames)]*(max(0, lstm_jets_maxN-len(jets)))\n jets = np.array([jets])\n\n return [ flat_variables, jets ]\n else:\n return flat_variables\n\n\n# Dependence on TMB just for the sake of the example!\n\n#define training samples for multiclassification\nfrom TMB.Samples.nanoTuples_RunII_nanoAODv6_dilep_pp import * \n#use only Summer16\ntraining_samples = [ Summer16.TTZ, Summer16.DY]#, Summer16.TTW] \n\nassert len(training_samples)==len(set([s.name for s in training_samples])), \"training_samples names are not unique!\"\n\n# training selection\n\nfrom TMB.Tools.cutInterpreter import cutInterpreter\nselectionString = cutInterpreter.cutString( 'dilepVL' )\n","sub_path":"MVA/python/cfg_examples/ttZ_dy_example.py","file_name":"ttZ_dy_example.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"568873109","text":"from subprocess import call\nimport os\n\ndef SetCommandLine(Fuzzer, DeviceName, Ioctl_Code):\n Command = [Fuzzer, '-n', DeviceName, '-c']\n for ioctl in Ioctl_Code:\n Command.append(hex(ioctl))\n\ndef Dumpdir(path):\n if not os.path.isdir(path):\n os.mkdir(path)\n\ndef windbglog(path):\n kd_log = open(path + \"/windbg.log\", \"wb\")\n call([\"C:\\\\Program Files\\\\Debugging Tools for Windows (x64)\\\\kd.exe\", \"-z\", path, \"-c\", \"$$ 'Node':\n hm = {}\n if not node:\n return None\n queue = deque([])\n copy = Node(node.val)\n queue.append(node)\n hm[node] = copy\n \n while queue:\n curr = queue.popleft()\n \n for n in curr.neighbors:\n if n not in hm:\n copyNeighbor = Node(n.val)\n hm[n] = copyNeighbor\n queue.append(n)\n hm[curr].neighbors.append(hm[n])\n return copy #can also return hm[node]","sub_path":"cloneGraph.py","file_name":"cloneGraph.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"186855299","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 31 14:55:43 2018\n\n@author: k40\n\"\"\"\n\nimport os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport json\nimport pydicom\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport pandas as pd\nimport glob\n\n# Import Mask RCNN\n\nROOT_DIR = '/media/k40/新加卷/000MIA/MaskRCNN/'\n#ROOT_DIR = '/data/MaskRCNN/'\nDATA_DIR = os.path.join(ROOT_DIR, 'DATA')\n\n# To find local version of the library\nsys.path.append(os.path.join(ROOT_DIR, 'network_code/'))\nfrom config import Config\nimport utils\nimport pneumonia\nimport model as modellib\nfrom model import log\nimport visualize\nimport tensorflow as tf\nimport keras.backend.tensorflow_backend as KTF\n# 指定第一块GPU可用\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\nconfig_GPU = tf.ConfigProto()\nconfig_GPU.gpu_options.allow_growth = True # 不全部占满显存, 按需分配\nsess = tf.Session(config=config_GPU)\nKTF.set_session(sess)\ntrain_dicom_dir = os.path.join(DATA_DIR, 'stage_1_train_images')\ntest_dicom_dir = os.path.join(DATA_DIR, 'stage_1_test_images')\n\n\ndef get_dicom_fps(dicom_dir):\n dicom_fps = glob.glob(dicom_dir+'/'+'*.dcm')\n return list(set(dicom_fps))\n\n\ndef parse_dataset(dicom_dir, anns):\n image_fps = get_dicom_fps(dicom_dir)\n image_annotations = {fp: [] for fp in image_fps}\n for index, row in anns.iterrows():\n fp = os.path.join(dicom_dir, row['patientId']+'.dcm')\n image_annotations[fp].append(row)\n return image_fps, image_annotations\n\n# The following parameters have been selected to reduce running time for demonstration purposes \n# These are not optimal \n\nclass DetectorConfig(Config):\n \"\"\"Configuration for training pneumonia detection on the RSNA pneumonia dataset.\n Overrides values in the base Config class.\n \"\"\"\n \n # Give the configuration a recognizable name \n NAME = 'pneumonia'\n \n # Train on 1 GPU and 8 images per GPU. We can put multiple images on each\n # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).\n GPU_COUNT = 1\n IMAGES_PER_GPU = 4 \n \n BACKBONE = 'resnet50'\n \n NUM_CLASSES = 2 # background + 1 pneumonia classes\n \n # Use small images for faster training. Set the limits of the small side\n # the large side, and that determines the image shape.\n IMAGE_MIN_DIM = 512\n IMAGE_MAX_DIM = 512 \n IMAGE_MIN_DIM = 256\n IMAGE_MAX_DIM = 256 ###change \n RPN_ANCHOR_SCALES = (16,32, 64, 128, 256)\n RPN_ANCHOR_SCALES = (64,100, 121, 144, 169)\n RPN_ANCHOR_SCALES = (32,48, 64, 80, 96) ###change\n TRAIN_ROIS_PER_IMAGE = 32\n \n MAX_GT_INSTANCES = 3\n \n DETECTION_MAX_INSTANCES = 3\n DETECTION_MIN_CONFIDENCE = 0.9\n DETECTION_NMS_THRESHOLD = 0.1\n \n RPN_TRAIN_ANCHORS_PER_IMAGE = 16\n STEPS_PER_EPOCH = 100 \n TOP_DOWN_PYRAMID_SIZE = 32\n STEPS_PER_EPOCH = 100\n \nconfig = DetectorConfig()\nconfig.display()\n\n\n\n# training dataset\nanns = pd.read_csv(os.path.join(DATA_DIR, 'stage_1_train_labels.csv'))\nanns.head()\n\n\nimage_fps, image_annotations = parse_dataset(train_dicom_dir, anns=anns)\n\nds = pydicom.read_file(image_fps[0]) # read dicom image from filepath\nimage = ds.pixel_array # get image array\n\n# Original DICOM image size: 1024 x 1024\nORIG_SIZE = 1024\n######################################################################\n# Modify this line to use more or fewer images for training/validation.\n# To use all images, do: image_fps_list = list(image_fps)\n#image_fps_list = list(image_fps[:1000])\nimage_fps_list = list(image_fps)\n#####################################################################\n\n# split dataset into training vs. validation dataset\n# split ratio is set to 0.9 vs. 0.1 (train vs. validation, respectively)\nsorted(image_fps_list)\nrandom.seed(42)\nrandom.shuffle(image_fps_list)\n\nvalidation_split = 0.1\nsplit_index = int((1 - validation_split) * len(image_fps_list))\n\nimage_fps_train = image_fps_list[:split_index]\nimage_fps_val = image_fps_list[split_index:]\n\nprint(len(image_fps_train), len(image_fps_val))\n\n# prepare the training dataset 23115\ndataset_train = pneumonia.DetectorDataset(\n image_fps_train, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_train.prepare()\n\n# Show annotation(s) for a DICOM image\ntest_fp = random.choice(image_fps_train)\nimage_annotations[test_fp]\n\n# prepare the validation dataset 2569\ndataset_val = pneumonia.DetectorDataset(\n image_fps_val, image_annotations, ORIG_SIZE, ORIG_SIZE)\ndataset_val.prepare()\n\nclass InferenceConfig(DetectorConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\ninference_config = InferenceConfig()\n# Directory to save logs and trained model\nMODEL_DIR = os.path.join(ROOT_DIR, 'models_logs1') ###change\n# Recreate the model in inference mode\nmodel = modellib.MaskRCNN(mode='inference', \n config=inference_config,\n model_dir=MODEL_DIR)\n\nmodel_path = os.path.join(MODEL_DIR,'mask_rcnn_7.h5') ###change\n\nprint('Found model {}'.format(model_path))\n# Load trained weights (fill in path to trained weights here)\nassert model_path != \"\", \"Provide path to trained weights\"\nprint(\"Loading weights from \", model_path)\n#model.load_weights(model_path, by_name=True)\nmodel.load_weights(model_path, by_name=True)\n\n\n# set color for class\ndef get_colors_for_class_ids(class_ids):\n colors = []\n for class_id in class_ids:\n if class_id == 1:\n colors.append((.941, .204, .204))\n return colors\n\n'''\n# Show few example of ground truth vs. predictions on the validation dataset \ndataset = dataset_val\nfig = plt.figure(figsize=(10, 30))\n\nfor i in range(4):\n\n image_id = random.choice(dataset.image_ids)\n \n original_image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n modellib.load_image_gt(dataset_val, inference_config, \n image_id, use_mini_mask=False)\n \n plt.subplot(6, 2, 2*i + 1)\n visualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id, \n dataset.class_names,\n colors=get_colors_for_class_ids(gt_class_id), ax=fig.axes[-1])\n \n plt.subplot(6, 2, 2*i + 2)\n results = model.detect([original_image]) #, verbose=1)\n r = results[0]\n visualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'], \n dataset.class_names, r['scores'], \n colors=get_colors_for_class_ids(r['class_ids']), ax=fig.axes[-1])\n'''\n\n# Get filenames of test dataset DICOM images\ntest_image_fps = get_dicom_fps(test_dicom_dir)\n\n\n# Make predictions on test images, write out sample submission \ndef predict(image_fps, filepath='sample_submission.csv', min_conf=0.5): \n \n # assume square image\n resize_factor = ORIG_SIZE / config.IMAGE_SHAPE[0]\n \n with open(filepath, 'w') as file:\n for image_id in tqdm(image_fps): \n ds = pydicom.read_file(image_id)\n image = ds.pixel_array\n \n # If grayscale. Convert to RGB for consistency.\n if len(image.shape) != 3 or image.shape[2] != 3:\n image = np.stack((image,) * 3, -1) \n \n patient_id = os.path.splitext(os.path.basename(image_id))[0]\n\n results = model.detect([image])\n r = results[0]\n\n out_str = \"\"\n out_str += patient_id \n assert( len(r['rois']) == len(r['class_ids']) == len(r['scores']) )\n if len(r['rois']) == 0: \n pass\n else: \n num_instances = len(r['rois'])\n out_str += \",\"\n for i in range(num_instances): \n if r['scores'][i] > min_conf: \n out_str += ' '\n out_str += str(round(r['scores'][i], 2))\n out_str += ' '\n\n # x1, y1, width, height \n x1 = r['rois'][i][1]\n y1 = r['rois'][i][0]\n width = r['rois'][i][3] - x1 \n height = r['rois'][i][2] - y1 \n bboxes_str = \"{} {} {} {}\".format(x1*resize_factor, y1*resize_factor, \\\n width*resize_factor, height*resize_factor) \n bboxes_str = \"{} {} {} {}\".format(y1*resize_factor,x1*resize_factor,\\\n height*resize_factor,width*resize_factor) \n out_str += bboxes_str\n\n file.write(out_str+\"\\n\")\n \n \n# predict only the first 50 entries\nsample_submission_fp = os.path.join(ROOT_DIR,'sample_submission.csv')\npredict(test_image_fps[:1000], filepath=sample_submission_fp) \noutput = pd.read_csv(sample_submission_fp, names=['id', 'pred_string'])\noutput.head(1000)\n","sub_path":"kaggle_pneumonia/mrcnn/test_new.py","file_name":"test_new.py","file_ext":"py","file_size_in_byte":8782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"503217945","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import patterns, include, url\nfrom django.views.generic.base import TemplateView\n\nurlpatterns = patterns('apps.exh.views',\n #Edit by Chuang, conference publisher urls\n url(r'^exHallEdit$', 'display'),\n url(r'^changeEXInfo$', \"change_eliment\"),\n url(r'^showEXHCert$', \"show_cert_pic\"),\n url(r'^showEXH$', \"show_exh_pic\"),\n url(r'^exCityCommit', \"city_commit\"),\n url(r'^uploadEXHCert$', \"upload_cert\"),\n url(r'^uploadEXH$', \"upload_exh\"),\n url(r'^deleteEXHPic', \"delete_exh_pic\"),\n url(r'^deleteEXHCertPic', \"delete_cert_pic\"),\n url(r'^showEXHchar$', \"show_exh_char\"),\n url(r'^showEXHLayout$', \"show_exh_layout\"),\n url(r'^showEXHType$', \"show_exh_type\"),\n\n)\n","sub_path":"apps/exh/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"590826027","text":"\"\"\"WattServer URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import patterns,include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom Team.views import teamMemberAPI\nfrom Blog.views import postAPI,postAPIDetails\nfrom Animal.views import animalAPI,adoptAPI,storyAPI\n\nurlpatterns = patterns('',\n url('^markdown/', include( 'django_markdown.urls')),\n url(r'^tinymce/', include('tinymce.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^api/post/(?P[0-9]+)/$', postAPIDetails), #API TO ACCESS ALL POSTS. Only GET request Works\n url(r'^api/post/$', postAPI), #API TO ACCESS ALL POSTS. Only GET request Works\n url(r'^api/team/$', teamMemberAPI), #API TO ACCESS TEAM MEMBERS. Only GET request Works\n url(r'^api/animal/$', animalAPI), #API TO ACCESS All ANIMALS MEMBERS. Only GET request Works\n url(r'^api/adopt/$', adoptAPI), #API TO ACCESS ADOPTABLE ANIMALS MEMBERS. Only GET request Works\n url(r'^api/story/$', storyAPI), #API TO ACCESS \"HAPPY TAILS\" ANIMALS MEMBERS. Only GET request Works\n)\n\nurlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT}))\n\nadmin.site.site_header = 'Watts Project Administrator'\n","sub_path":"WattServer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"432205020","text":"import fnmatch\nimport shutil\nfrom collections import Counter\nfrom shutil import Error\nimport os\nimport cv2\nimport pickle\n\nimport numpy as np\n\nfilename = \"keypoints.p\"\nmodel = \"model\"\ndescriptors = \" descriptors.csv\"\nmodel_test = \" keypoint_test\"\nnumber_descriptor = 200\n\n\ndef detector_shift_training_base(dataset_path=\"./training\"):\n images_train = {}\n descs = []\n descriptor = []\n classes = []\n errors = []\n for path, dirs, files in os.walk(dataset_path):\n for file in files:\n if fnmatch.fnmatch(file, '*.jpg'):\n fullname = os.path.join(path, file)\n classe = os.path.basename(path)\n img = cv2.imread(fullname, 0)\n # height, weight, channels = img.shape\n # print(height, weight, channels)\n \"\"\"image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)\"\"\"\n images_train['image'] = img\n images_train['classe'] = classe\n classes.append(classe)\n sift = cv2.SIFT_create(number_descriptor)\n #sift = cv2.SIFT_create()\n # Take the first element of the dictionary to compute the keypoints and descriptor of the image\n keypoints, train_descriptor = sift.detectAndCompute(images_train['image'], None)\n descriptor.append(train_descriptor)\n sift_keypoints = [train_descriptor, classe]\n descs.append(sift_keypoints)\n\n i = 0\n keypoint = [train_descriptor, classe]\n for point in keypoints:\n temp = (point.pt, point.size, point.angle, point.response, point.octave,\n point.class_id)\n ++i\n keypoint.append(temp)\n # Keypoints with descriptor and classe of images and keypoints stored\n with open(model, \"wb+\") as fichier:\n pickle.dump(keypoint, fichier)\n # Store keypoints and descriptor into a file called model\n if not os.path.exists(\"keypoints_train\"):\n os.mkdir(\"keypoints_train\")\n print(\"folder Created \", \"keypoints\")\n else:\n break\n try:\n shutil.move(filename, \"model_keypoints\")\n except Error as err:\n errors.extend(err.args[0])\n # Keypoints with descriptor and classe of images\n with open('base_keypoints', 'wb+') as file:\n pickle.dump([descriptor, classes], file)\n\n with open(filename, \"wb+\") as base:\n pickle.dump(descs, base)\n\n\ndef decriptor_test_image(filename):\n des = pickle.load(open(filename, 'rb'))\n print(des)\n errors = []\n # Create sift object from Sift class\n sift = cv2.SIFT_create(number_descriptor)\n #sift = cv2.SIFT_create()\n # Joins the home directory to the users typed in folder\n user_input = input(\" Type the path of the image followed by the image : \")\n classe_name = os.path.dirname(os.path.abspath(user_input))\n classe = os.path.basename(classe_name)\n print(classe)\n img = cv2.imread(user_input)\n image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)\n keypoints, descriptor = sift.detectAndCompute(image_gray, None)\n cv2.imshow('original', img)\n img_with_keypoints = cv2.drawKeypoints(image_gray, keypoints, image_gray,\n flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n cv2.imshow('keypoints', img_with_keypoints)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n descriptor_test = [descriptor, classe]\n\n # Keypoints with descriptor and classe of images\n with open(\"Descriptor_test\", \"wb+\") as base:\n pickle.dump(descriptor_test, base)\n\n # print(keypoints, descriptor)\n i = 0\n keypoint = [descriptor, classe]\n for point in keypoints:\n temp = (point.pt, point.size, point.angle, point.response, point.octave,\n point.class_id)\n ++i\n keypoint.append(temp)\n\n with open(model_test, \"wb+\") as fichier:\n pickle.dump(keypoint, fichier)\n # Store keypoints and descriptor into a file called model\n if not os.path.exists(\"Keypoint_test\"):\n os.mkdir(\"Keypoint_test\")\n print(\"folder Created \", \"keypoints\")\n else:\n break\n try:\n shutil.move(model_test, \"Keypoint_test\")\n except Error as err:\n errors.extend(err.args[0])\n\n return descriptor_test\n\n\ndef matching(descriptor, descs, classes, k=3):\n correct = 0\n total = 0\n k_flann = 2\n FLANN_INDEX_KDTREE = 1\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n search_params = dict(checks=200)\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n M = []\n if len(descriptor) > k_flann:\n tmp = []\n for idy, v in enumerate(descs):\n c1 = 0\n matches = flann.knnMatch(v, descriptor, k=k_flann)\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n c1 += 1\n tmp.append(c1)\n M.append([idy, c1])\n M.sort(key=lambda x: x[1], reverse=True)\n\n k_nearest = M[:k]\n E = []\n for b in k_nearest:\n E.append(b[0])\n dav = Counter(E)\n\n predict = dav.most_common(1)[0][0]\n if classes[predict] == classes:\n correct +=1\n total +=1\n\n print(\" La classe predicte de l'image est : \", classes[predict])\n # print(\"le taux de precision overall\", round((100 * correct / total), 2), ' %')\n return predict, classes[predict]\n\n\ndef write_classes_unique():\n classes = []\n for doss in os.listdir(\"training\"):\n classes.append(doss)\n pickle.dump(classes, open(\"classes.cl\", \"wb\"))\n\n\ndef predict(filename, model='base_keypoints', show=False):\n # loading of descriptors's training\n des = pickle.load(open(model, 'rb'))\n descriptors = des[0]\n classes = des[1]\n classe_name = os.path.dirname(os.path.abspath(filename))\n classe = os.path.basename(classe_name)\n # print(classe)\n # Extracting the descriptors of input image\n # Create sift object from Sift class\n #sift = cv2.SIFT_create()\n sift = cv2.SIFT_create(number_descriptor)\n img = cv2.imread(filename, 0)\n\n keypoints, descriptor = sift.detectAndCompute(img, None)\n m = matching(descriptor, descriptors, classes)\n if show:\n cv2.imshow('Image test', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n # Matching function to predict the image test\n return m\n\n\ndef test(dataset_path=\"./test\"):\n correct = 0\n total = 0\n classes = pickle.load(open(\"classes.cl\", \"rb\"))\n print(isinstance(classes, list))\n matrice = np.zeros((len(classes), len(classes)))\n for path, dirs, files in os.walk(dataset_path):\n for file in files:\n if fnmatch.fnmatch(file, '*.jpg'):\n fullname = os.path.join(path, file)\n classe = os.path.basename(path)\n id_correct = classes.index(classe)\n pred = classes.index(predict(fullname)[1])\n if id_correct == pred:\n correct += 1\n total += 1\n\n matrice[id_correct][pred] += 1\n print(\"overall precision \", round((100 * correct / total), 2), ' %')\n with open('matrice_confusion', 'wb+') as file:\n pickle.dump(matrice, file)\n # print(matrice)\n\n\ndetector_shift_training_base(\"training\")\n#predict('test/watch/12.jpg', show=True)\nwrite_classes_unique()\n#test(dataset_path=\"./test\")\n#decriptor_test_image('model')","sub_path":"sift_objects_recognition.py","file_name":"sift_objects_recognition.py","file_ext":"py","file_size_in_byte":7829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"156911472","text":"'''\nROSHAMBO PROGRAM\n----------------\n\nCreate a program that randomly prints 1, 2, or 3.\nExpand the program so it randomly prints rock, paper, or scissors using if statements. Don't select from a list.\nAdd to the program so it first asks the user their choice as well as if they want to quit.\n(It will be easier if you have them enter 1 for rock, 2 for paper, and 3 for scissors.)\nAdd conditional statements to figure out who wins and keep the records\nWhen the user quits print a win/loss record\n\n'''\n\n\nperson=0\ntie=0\ncomp=0\ndone=False\nwhile not done:\n spr=int(input(\"Choose \\n 1.Rock \\n 2.Paper \\n 3.Scissors \\n Press Q to quit. \\n\"))\n import random\n num=random.randrange(1,4)\n if num==1:\n rps=\"Rock\"\n elif num == 2:\n rps=\"Paper\"\n elif num == 3:\n rps=\"Scissors\"\n if spr==1 and rps == \"Paper\":\n print(\"Paper, you lose\")\n comp+=1\n elif spr==2 and rps==\"Scissors\":\n print(\"Scissors, you lose\")\n comp+=1\n elif spr==3 and rps ==\"Rock\":\n print(\"Rock, you lose.\")\n comp+=1\n if spr==1 and rps==\"Scissors\":\n print(\"Scissors, you win\")\n person+=1\n elif spr==2 and rps==\"Rock\":\n print(\"Rock, you win\")\n person+=1\n elif spr==3 and rps == \"Paper\":\n print(\"Paper, you win\")\n person+=1\n if spr==1 and rps==\"Rock\":\n print(\"Rock, tie\")\n tie+=1\n elif spr==2 and rps==\"Paper\":\n print(\"Paper, tie\")\n tie+=1\n elif spr==3 and rps==\"Scissors\":\n print(\"Scissors, tie\")\n tie+=1\n elif spr== \"q\":\n done=True\n print(\"User Score:\", person)\n print(\"Computer score:\", comp)\n print(\"Ties:\", tie)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"5.2_Roshambo.py","file_name":"5.2_Roshambo.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"639549608","text":"\"\"\"\nRegion Of Interest (ROI) object\n===============================\n\nThis example illustrate the main functionalities and inputs of the roi\nobject i.e :\n\n * Use either the Brodmann, AAL or Talairach atlases and select ROI from it\n * Color control of ROI\n * Analyse source's anatomical location using an RoiObj\n * Project source's activity onto ROI\n\n.. image:: ../../picture/picobjects/ex_roi_obj.png\n\"\"\"\nimport numpy as np\n\nfrom visbrain.objects import RoiObj, ColorbarObj, SceneObj, SourceObj, BrainObj\nfrom visbrain.io import download_file, path_to_visbrain_data, read_nifti\n\n\"\"\"Get the path to Visbrain data and download deep sources\n\"\"\"\nvb_path = path_to_visbrain_data()\nmat = np.load(download_file('xyz_sample.npz'))\nxyz, subjects = mat['xyz'], mat['subjects']\ndata = np.random.uniform(low=-1., high=1., size=(xyz.shape[0],))\n\n# =============================================================================\n# MAIN SCENE\n# =============================================================================\nprint(\"-> Create a scene. By default, we fix the top view of the camera\")\nCAM_STATE = dict(azimuth=0, # azimuth angle\n elevation=90, # elevation angle\n scale_factor=200 * 100,\n distance=800 * 100,\n )\nCBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3.,\n rect=(-.3, -2., 1., 4.))\nsc = SceneObj(camera_state=CAM_STATE, bgcolor=(.1, .1, .1), size=(1400, 1000))\n\n# =============================================================================\n# FIND INDEX OF AN ROI\n# =============================================================================\n\"\"\"Here, we illustrate how to find the integer index of the ROI to plot\n\"\"\"\n# Method 1 : save all ROI in an excel file and search manually the ROI\nroi_to_find1 = RoiObj('brodmann') # Use Brodmann areas\nref_brod = roi_to_find1.get_labels(vb_path) # Save Brodmann\nroi_to_find1('aal') # Switch to AAL\nref_aal = roi_to_find1.get_labels(vb_path) # Save AAL\nroi_to_find1('talairach') # Switch to Talairach\nref_tal = roi_to_find1.get_labels(vb_path) # Save Talairach\n\n# Method 2 : use the `where_is` method\nroi_to_find1('brodmann') # Switch to Brodmann\nidx_ba6 = roi_to_find1.where_is('BA6') # Find only BA6\nprint(ref_brod.loc[idx_ba6])\nroi_to_find1('aal') # Switch to AAL\nidx_sma = roi_to_find1.where_is(['Supp Motor Area', '(L)'], union=False)\n\n# =============================================================================\n# BRAIN + BA6\n# =============================================================================\nprint('\\n-> Plot brodmann area 6')\nb_obj = BrainObj('B1')\nroi_brod = RoiObj('brodmann')\nidx_ba6 = roi_brod.where_is('BA6')\nroi_brod.select_roi(select=idx_ba6)\nroi_brod.get_labels(save_to_path=vb_path) # print available brodmann labels\nsc.add_to_subplot(roi_brod, row=0, col=0, title='Brodmann area 6')\nsc.add_to_subplot(b_obj, row=0, col=0, use_this_cam=True)\n\n# =============================================================================\n# MULTIPLE ROI + UNIQUE COLORS\n# =============================================================================\nprint('\\n-> Select and plot multiple ROI with random unique colors')\nroi_aal = RoiObj('aal')\nroi_aal.select_roi(select=[29, 30, 77, 78], unique_color=True, smooth=11)\nroi_aal.get_labels(save_to_path=vb_path) # save available AAL labels\nsc.add_to_subplot(roi_aal, row=0, col=1,\n title='Select and plot multiple ROI with unique colors')\n\n# =============================================================================\n# CUSTOM ROI + FIXED COLORS\n# =============================================================================\nprint(\"\\n-> Use a custom roi_object and plot dorsal and ventral thalamus with \"\n \"fixed colors\")\n# Download the MIST_ROI.zip archive. See the README inside the archive\ndownload_file('MIST_ROI.zip', unzip=True)\nnifti_file = path_to_visbrain_data('MIST_ROI.nii.gz')\ncsv_file = path_to_visbrain_data('MIST_ROI.csv')\n# Read the .csv file :\narr = np.genfromtxt(csv_file, delimiter=';', dtype=str)\n# Get column names, labels and index :\ncolumn_names = arr[0, :]\narr = np.delete(arr, 0, 0)\nn_roi = arr.shape[0]\nroi_index = arr[:, 0].astype(int)\nroi_labels = arr[:, [1, 2]].astype(object)\n# Build the struct array :\nlabel = np.zeros(n_roi, dtype=[('label', object), ('name', object)])\nlabel['label'] = roi_labels[:, 0]\nlabel['name'] = roi_labels[:, 1]\n# Get the volume and the hdr transformation :\nvol, _, hdr = read_nifti(nifti_file, hdr_as_array=True)\n# Define the ROI object and save it :\nroi_custom = RoiObj('mist_roi', vol=vol, labels=label, index=roi_index,\n hdr=hdr)\n# Find thalamus entries :\nidx_thalamus = roi_custom.where_is('THALAMUS')\ncolors = {55: 'slateblue', 56: 'olive', 63: 'darkred', 64: '#ab4642'}\nroi_custom.select_roi(idx_thalamus, smooth=11, roi_to_color=colors)\nsc.add_to_subplot(roi_custom, row=0, col=2,\n title='Plot dorsal and ventral thalamus with fixed colors')\n\n# =============================================================================\n# ANATOMICAL LOCATION OF SOURCES\n# =============================================================================\nprint('\\n-> Anatomical location of sources using an ROI object')\n# Define the ROI object :\nroi_tal = RoiObj('talairach')\nroi_tal.select_roi(select=[681, 682, 808, 809])\nroi_tal.translucent = True\nroi_tal.get_labels(save_to_path=vb_path) # save available Talairach labels\n# Define a source object :\ns_obj = SourceObj('FirstSources', xyz, data=data)\nanalysis = s_obj.analyse_sources(roi_tal)\ns_obj.color_sources(analysis=analysis, color_by='gyrus')\nsc.add_to_subplot(s_obj, row=1, col=0,\n title='Anatomical location of sources')\nsc.add_to_subplot(roi_tal, row=1, col=0, use_this_cam=True)\n\n# =============================================================================\n# SELECT SOURCES INSIDE ROI'S\n# =============================================================================\nprint('\\n-> Select only sources inside BA 4, 6 and 8')\n# Define the ROI object :\nroi_brod_2 = RoiObj('brodmann')\nroi_brod_2.select_roi(select=[4, 6, 8])\nroi_brod_2.translucent = True\n# Define a source object :\ns_obj_2 = SourceObj('SecondSources', xyz, data=data)\nanalysis = s_obj_2.analyse_sources(roi_brod_2, distance=20.,\n keep_only=['BA4', 'BA6', 'BA8'])\ns_obj_2.color_sources(data=data)\nsc.add_to_subplot(s_obj_2, row=1, col=1,\n title='Plot only sources in BA4, 6 and 8')\nsc.add_to_subplot(roi_brod_2, row=1, col=1, use_this_cam=True)\n\n# =============================================================================\n# CORTICAL PROJECTION OF SOURCE'S ACTIVITY\n# =============================================================================\nprint(\"\\n-> Project source's activity onto ROI\")\n# Define the ROI object :\nroi_brod_3 = RoiObj('aal')\nroi_brod_3.select_roi(select=[29, 30, 77, 78], smooth=11)\n# Define a source object :\ns_obj_3 = SourceObj('SecondSources', xyz, data=data)\nroi_brod_3.project_sources(s_obj_3, cmap='plasma', clim=(-1., 1.), vmin=-.5,\n vmax=.7, under='gray', over='red')\ncb_brod_3 = ColorbarObj(roi_brod_3, cblabel='Source activity', **CBAR_STATE)\nsc.add_to_subplot(roi_brod_3, row=1, col=2,\n title=\"Project source activity onto ROI\")\nsc.add_to_subplot(cb_brod_3, row=1, col=3, width_max=200)\n\nsc.preview()\n","sub_path":"examples/objects/ex_roi_object.py","file_name":"ex_roi_object.py","file_ext":"py","file_size_in_byte":7720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"98434604","text":"# COMP 4107\n# Fall 2018\n# Assignment 3\n# Yunkai Wang, student number 100968473\n# Jules Kuehn, student number 100661464\n\nfrom q1_helpers import *\n\n\n# calculate the weight based on the given input vectors using Hebbian's rule or\n# Storkey's rule based on the choice\ndef cal_weight(data, use_storkey_rule=False):\n p = len(data)\n W = np.zeros((input_len, input_len))\n\n for pixels, _ in data:\n # code for the bonus mark, Storkey's rule of learning\n if use_storkey_rule:\n # these variables relate to the terms used in Storkey's learning rule\n local_field = W.dot(pixels.transpose())\n term1 = np.outer(local_field, pixels) / input_len\n term2 = np.outer(pixels, local_field) / input_len\n W -= np.add(term1, term2)\n\n W += (pixels.transpose()).dot(pixels)\n W -= np.dot(np.identity(input_len), p)\n return W\n\n\n# feed the input vector to the network with the weight and threshold value\ndef test(weight, input):\n changed = True # a variable that indicates if there exist any node which changes its state\n \n vector = input[0]\n indices = list(range(0, len(vector))) # do it for every node in the network\n\n while changed: # repeat until converge\n changed = False\n\n # array to store new state after this iteration\n new_vector = np.array(\n [0 for _ in range(len(vector))]\n )\n shuffle(indices) # use different order every time\n \n for index in indices:\n s = compute_sum(weight, vector, index)\n new_vector[index] = 1 if s >= 0 else -1 # new state for the node\n \n changed = not np.allclose(vector, new_vector)\n vector = new_vector\n\n return vector\n\n\n# compute the sum by adding up the weights of all active edges that connects to the\n# given node\ndef compute_sum(weight, vector, node_index):\n return sum([weight[node_index][index] for index in range(len(vector)) if vector[index] == 1])\n\n\n# Among the training data, find the data that's closest to the stable state and\n# pick the label that corresponds to that data as the label for the state\ndef classify(vector, data):\n closestDis = float('inf')\n closestLabel = None\n\n for pixels, label in data:\n dis = np.linalg.norm(vector - pixels)\n if dis < closestDis:\n closestDis = dis\n closestLabel = label\n\n # print(\"Output vector, classified as\", str(closestLabel))\n # printVector(vector)\n\n return closestLabel\n\n\ndef test_network(num_training_data=5, num_testing_data=10, use_storkey_rule=False, reprs='random'):\n if reprs == 'all_centers':\n # pick representative training data (closest to kmeans centers)\n trainingData = getCenterOnesAndFives(num_training_data)\n elif reprs == 'most_similar':\n trainingData = getRepresentativeOnesAndFives(num_training_data)\n else:\n trainingData = getRandomOnesAndFives(num_training_data)\n W = cal_weight(trainingData, use_storkey_rule)\n testData = getRandomOnesAndFives(num_testing_data)\n correct = 0 # number of correct identified image\n\n for pixels, actual_label in testData:\n # print(\"Input digit, with actual label\", str(actual_label))\n # printVector(pixels)\n\n vector = test(W, pixels)\n label = classify(vector, trainingData)\n if actual_label == label: # correctly identified one image\n correct += 1\n\n # (2 * num_testing_data) because num_testing_data is for each of 1 and 5\n return correct / (2 * num_testing_data) # calculate the accuracy\n\n\n# It seems like feeding the network with 5 of each digit will cause the network\n# to forget everything, even if the original training data is tested. If I gave\n# only 1 image of each digit, the network will do a relatively good job.\ndef multi_trial(maxTrain, numTest, numTrials, representative, storkey):\n accuracies = {}\n\n for _ in range(numTrials):\n for numTrain in range(1, maxTrain + 1):\n accuracy = test_network(numTrain, numTest, use_storkey_rule=storkey, reprs=representative)\n print(\"number of training data for each digit:\", numTrain)\n print(\"number of test data for each digit:\", numTest)\n print(\"Storkey:\", storkey, \"; Representative training data:\", representative)\n print(\"accuracy:\", accuracy)\n if numTrain in accuracies:\n accuracies[numTrain].append(accuracy)\n else:\n accuracies[numTrain] = [accuracy]\n print(\"---\")\n\n # for numTrain in accuracies:\n # accuracies[numTrain] = np.average(accuracies[numTrain])\n\n print(accuracies)\n return accuracies\n\n\nmaxTrain = 5\nnumTest = 50\nnumTrials = 5\n\n\n\nf = open('q1_results.txt', 'w')\nf.write(f'maxTrain: {maxTrain}, numTest: {numTest}, numTrials: {numTrials}\\n')\nf.write('Random selection of training data, without Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'random', False)\nf.write(f'{results}\\n')\nf.write('K-means centers as training data, without Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'all_centers', False)\nf.write(f'{results}\\n')\nf.write('Most similar as training data, without Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'most_similar', False)\nf.write(f'{results}\\n')\nf.write('Random selection of training data, with Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'random', True)\nf.write(f'{results}\\n')\nf.write('K-means centers as training data, with Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'all_centers', True)\nf.write(f'{results}\\n')\nf.write('Most similar as training data, with Storkey:')\nresults = multi_trial(maxTrain, numTest, numTrials, 'most_similar', True)\nf.write(f'{results}\\n')\nf.close()\n\n# plt.ylim(0.4, 1)\n# plt.xticks(range(maxTrain + 1))\n# plt.plot(*zip(*sorted(results.items())))\n# plt.show()\n\n\n# ----------------------------------------------------------------\n# code for testing the network on the small example given in class\n# input_len = 4 # testing small images\n\n# # data found on slide 59 of Hopfield network\n# x1 = np.array([1, -1, -1, 1])\n# x2 = np.array([1, 1, -1, 1])\n# x3 = np.array([-1, 1, 1, -1])\n# # testing on the small example to find the problem\n# trainingData = [[x1, 1], [x2, 2], [x3, 3]]\n# W = cal_weight(trainingData, threshold=0)\n# print(W)\n# for pixels, actual_label in trainingData:\n# print(\"Start to test on pixels: \", pixels)\n# vector = test(W, pixels, threshold=0)\n# label = classify(vector, trainingData)\n# print(actual_label, label)","sub_path":"A3/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"132510222","text":"\"\"\"\nModule for storing convenience functions that wrap up automation_api functionality\n\"\"\"\n\nfrom cloudshell.workflow.orchestration.sandbox import Sandbox\n\n\ndef sb_print(sandbox, message):\n \"\"\"\n convenience printing method for printing to reservation output\n :param Sandbox sandbox:\n :param str message:\n :return:\n \"\"\"\n sandbox.automation_api.WriteMessageToReservationOutput(sandbox.id, message)\n\n\ndef get_reservation_resources(sandbox):\n \"\"\"\n :param Sandbox sandbox:\n :return:\n \"\"\"\n reservation_details = sandbox.automation_api.GetReservationDetails(reservationId=sandbox.id)\n resources = reservation_details.ReservationDescription.Resources\n return resources\n\n\ndef get_reservation_resources_by_family(sandbox, family_name):\n \"\"\"\n :param Sandbox sandbox:\n :param str family_name:\n :return:\n \"\"\"\n resources = get_reservation_resources(sandbox)\n target_resources = [resource for resource in resources\n if resource.ResourceFamilyName == family_name]\n return target_resources\n\n\ndef get_reservation_resources_by_model(sandbox, model_name):\n \"\"\"\n :param Sandbox sandbox:\n :param str model_name:\n :return:\n \"\"\"\n resources = get_reservation_resources(sandbox)\n target_resources = [resource for resource in resources\n if resource.ResourceModelName == model_name]\n return target_resources\n\n\ndef get_routes_info(sandbox):\n \"\"\"\n :param Sandbox sandbox:\n :return:\n \"\"\"\n reservation_details = sandbox.automation_api.GetReservationDetails(reservationId=sandbox.id)\n routes_info = reservation_details.ReservationDescription.RequestedRoutesInfo\n return routes_info\n\n\ndef connect_routes(sandbox, mapping_type=\"bi\", print_output=False):\n \"\"\"\n :param Sandbox sandbox:\n :param bool print_output: flag to turn print output on/off\n :param str mapping_type: set mapping type to bidirectional / unidirectional [\"bi\", \"uni\"]\n :return:\n \"\"\"\n routes = get_routes_info(sandbox)\n if print_output:\n sb_print(sandbox, \"===== Connecting All Routes =====\")\n\n if routes:\n if print_output:\n sb_print(sandbox, \"SOURCE -----> TARGET\")\n for route in routes:\n sandbox.automation_api.ConnectRoutesInReservation(reservationId=sandbox.id,\n endpoints=[route.Source, route.Target],\n mappingType=mapping_type)\n if print_output:\n sb_print(sandbox, route.Source + \" -----> \" + route.Target)\n else:\n if print_output:\n sb_print(sandbox, \"No routes were found in this sandbox\")\n if print_output:\n sb_print(sandbox, \"==========\")\n","sub_path":"helper_code/custom_helpers.py","file_name":"custom_helpers.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"203041794","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/3/10 15:40\n# @Author : Linder\n# @Email : lmj2018666@gmail.com\n# @Software: PyCharm\nnums=[i for i in map(int,input().split())]\nnums.sort()\ndiff=nums[1]-nums[0]\nflag='Possible'\nfor i in range(1,len(nums)-1):\n\tif nums[i+1]-nums[i]!=diff:\n\t\tflag='Impossible'\n\t\tbreak\n\nprint(flag)\n\n\n\n","sub_path":"牛客网/等差数列.py","file_name":"等差数列.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"193854207","text":"# 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# [START video_detect_logo_gcs]\n\nfrom google.cloud import videointelligence\n\n\ndef detect_logo_gcs(input_uri=\"gs://YOUR_BUCKET_ID/path/to/your/file.mp4\"):\n\n client = videointelligence.VideoIntelligenceServiceClient()\n\n features = [videointelligence.Feature.LOGO_RECOGNITION]\n\n operation = client.annotate_video(\n request={\"features\": features, \"input_uri\": input_uri}\n )\n\n print(\"Waiting for operation to complete...\")\n response = operation.result()\n\n # Get the first response, since we sent only one video.\n annotation_result = response.annotation_results[0]\n\n # Annotations for list of logos detected, tracked and recognized in video.\n for logo_recognition_annotation in annotation_result.logo_recognition_annotations:\n entity = logo_recognition_annotation.entity\n\n # Opaque entity ID. Some IDs may be available in [Google Knowledge Graph\n # Search API](https://developers.google.com/knowledge-graph/).\n print(\"Entity Id : {}\".format(entity.entity_id))\n\n print(\"Description : {}\".format(entity.description))\n\n # All logo tracks where the recognized logo appears. Each track corresponds\n # to one logo instance appearing in consecutive frames.\n for track in logo_recognition_annotation.tracks:\n\n # Video segment of a track.\n print(\n \"\\n\\tStart Time Offset : {}.{}\".format(\n track.segment.start_time_offset.seconds,\n track.segment.start_time_offset.microseconds * 1000,\n )\n )\n print(\n \"\\tEnd Time Offset : {}.{}\".format(\n track.segment.end_time_offset.seconds,\n track.segment.end_time_offset.microseconds * 1000,\n )\n )\n print(\"\\tConfidence : {}\".format(track.confidence))\n\n # The object with timestamp and attributes per frame in the track.\n for timestamped_object in track.timestamped_objects:\n # Normalized Bounding box in a frame, where the object is located.\n normalized_bounding_box = timestamped_object.normalized_bounding_box\n print(\"\\n\\t\\tLeft : {}\".format(normalized_bounding_box.left))\n print(\"\\t\\tTop : {}\".format(normalized_bounding_box.top))\n print(\"\\t\\tRight : {}\".format(normalized_bounding_box.right))\n print(\"\\t\\tBottom : {}\".format(normalized_bounding_box.bottom))\n\n # Optional. The attributes of the object in the bounding box.\n for attribute in timestamped_object.attributes:\n print(\"\\n\\t\\t\\tName : {}\".format(attribute.name))\n print(\"\\t\\t\\tConfidence : {}\".format(attribute.confidence))\n print(\"\\t\\t\\tValue : {}\".format(attribute.value))\n\n # Optional. Attributes in the track level.\n for track_attribute in track.attributes:\n print(\"\\n\\t\\tName : {}\".format(track_attribute.name))\n print(\"\\t\\tConfidence : {}\".format(track_attribute.confidence))\n print(\"\\t\\tValue : {}\".format(track_attribute.value))\n\n # All video segments where the recognized logo appears. There might be\n # multiple instances of the same logo class appearing in one VideoSegment.\n for segment in logo_recognition_annotation.segments:\n print(\n \"\\n\\tStart Time Offset : {}.{}\".format(\n segment.start_time_offset.seconds,\n segment.start_time_offset.microseconds * 1000,\n )\n )\n print(\n \"\\tEnd Time Offset : {}.{}\".format(\n segment.end_time_offset.seconds,\n segment.end_time_offset.microseconds * 1000,\n )\n )\n\n\n# [END video_detect_logo_gcs]\n","sub_path":"samples/analyze/video_detect_logo_gcs.py","file_name":"video_detect_logo_gcs.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"511266312","text":"# program to test the while loops\n\ndef main():\n\tn = int(input(\"Enter a number: \"))\n\tm = n\n\tf = 1\n\n\twhile n>0:\n\t\tf *= n # f = f * n\n\t\tn -= 1 # n = n - 1\n\n\tprint(\"Factorial of {} is {}\\n\".format(m, f))\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Examples/ex06.py","file_name":"ex06.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"286969379","text":"#Faça um Programa que leia um vetor de 5 números inteiros, mostre a soma, a multiplicação e os números.\r\n\r\nc = 0\r\nx = 5\r\nsoma = 0\r\nmulti = 1\r\nvetor_numeros = []\r\nwhile c < x:\r\n number = int(input(\"Digite um número: \"))\r\n soma = soma + number\r\n multi = multi * number\r\n vetor_numeros.append(number)\r\n c = c + 1\r\nprint(\"\\nOs números são: \",vetor_numeros)\r\nprint(\"A soma dos números é: \",soma)\r\nprint(\"A multiplicação dos números é: \",multi)\r\n\r\n","sub_path":"questões/Listas/questao07.py","file_name":"questao07.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"649955577","text":"import pytest\nimport os\nimport sys\nfrom subprocess import call\nimport numpy as np\nfrom flare.otf import OTF\nfrom flare.gp import GaussianProcess\nfrom flare.struc import Structure\nimport flare.kernels.kernels as en\n\ndef cleanup(casename: str = None):\n try:\n os.remove('cp2k.in')\n os.remove('cp2k-RESTART.wfn')\n if (casename is not None):\n for suffix in [\"-f.xyz\", \"-hyps.dat\", \".out\",\n \"_par-f.xyz\", \"_par-hyps.dat\", \"_par.out\",\n \"_par-stat.dat\", \"_par-std.xyz\", \"_par.xyz\",\n \"-stat.dat\", \"-std.xyz\", \".xyz\"]:\n os.remove(casename+suffix)\n except:\n pass\n\n# ------------------------------------------------------\n# test otf runs\n# ------------------------------------------------------\n@pytest.mark.skipif(not os.environ.get('CP2K_COMMAND',\n False), reason='CP2K_COMMAND not found '\n 'in environment: Please install CP2K '\n 'and set the CP2K_COMMAND env. '\n 'variable to point to cp2k.popt')\ndef test_otf_h2():\n \"\"\"\n Test that an otf run can survive going for more steps\n :return:\n \"\"\"\n call('cp ./test_files/cp2k_input_1.in ./cp2k.in'.split())\n\n cp2k_input = './cp2k.in'\n dt = 0.0001\n number_of_steps = 5\n cutoffs = np.array([5])\n dft_loc = os.environ.get('CP2K_COMMAND')\n std_tolerance_factor = -0.1\n\n # make gp model\n kernel = en.two_body\n kernel_grad = en.two_body_grad\n hyps = np.array([1, 1, 1])\n hyp_labels = ['Signal Std', 'Length Scale', 'Noise Std']\n energy_force_kernel = en.two_body_force_en\n\n gp = \\\n GaussianProcess(kernel=kernel,\n kernel_grad=kernel_grad,\n hyps=hyps,\n cutoffs=cutoffs,\n hyp_labels=hyp_labels,\n energy_force_kernel=energy_force_kernel,\n maxiter=50)\n\n otf = OTF(cp2k_input, dt, number_of_steps, gp, dft_loc,\n std_tolerance_factor, init_atoms=[0],\n calculate_energy=True, max_atoms_added=1,\n force_source=\"cp2k\",\n output_name='h2_otf_cp2k')\n\n otf.run()\n call('mkdir test_outputs'.split())\n call('mv h2_otf_cp2k*.* test_outputs'.split())\n cleanup(\"h2_otf_cp2k\")\n\n@pytest.mark.skipif(not os.environ.get('CP2K_COMMAND',\n False), reason='CP2K_COMMAND not found '\n 'in environment: Please install CP2K '\n ' and set the CP2K_COMMAND env. '\n 'variable to point to pw.x.')\ndef test_otf_al():\n \"\"\"\n Test that an otf run can survive going for more steps\n :return:\n \"\"\"\n call('cp ./test_files/cp2k_input_2.in ./cp2k.in'.split())\n\n cp2k_input = './cp2k.in'\n dt = 0.001\n number_of_steps = 5\n cutoffs = np.array([3.9, 3.9])\n dft_loc = os.environ.get('CP2K_COMMAND')\n std_tolerance_factor = 1\n max_atoms_added = 2\n freeze_hyps = 3\n\n # make gp model\n kernel = en.three_body\n kernel_grad = en.three_body_grad\n hyps = np.array([0.1, 1, 0.01])\n hyp_labels = ['Signal Std', 'Length Scale', 'Noise Std']\n energy_force_kernel = en.three_body_force_en\n\n gp = \\\n GaussianProcess(kernel=kernel,\n kernel_grad=kernel_grad,\n hyps=hyps,\n cutoffs=cutoffs,\n hyp_labels=hyp_labels,\n energy_force_kernel=energy_force_kernel,\n maxiter=50)\n\n otf = OTF(cp2k_input, dt, number_of_steps, gp, dft_loc,\n std_tolerance_factor, init_atoms=[0],\n calculate_energy=True, output_name='al_otf_cp2k',\n freeze_hyps=freeze_hyps, skip=5,\n force_source=\"cp2k\",\n max_atoms_added=max_atoms_added)\n\n otf.run()\n call('mkdir test_outputs'.split())\n call('mv al_otf_cp2k*.* test_outputs'.split())\n\n cleanup(\"al_otf_cp2k\")\n","sub_path":"tests/test_OTF_cp2k.py","file_name":"test_OTF_cp2k.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"161880732","text":"import sys\n\n\n# Calculate the total number of lines in a text file\ndef cal_lines(source_txt):\n number_lines = 0\n with open(source_txt, 'r', encoding='utf-8') as source_file:\n for line in source_file:\n number_lines += 1\n source_file.close()\n return number_lines\n\n\n# check a tag between two lines;\ndef check_sentence_pair(line_src, line_tgt, tag):\n if tag == 'SP':\n # format in src: open_tag src_token tgt_token close_tag\n # format in tgt: open_tag tgt_token close_tag\n open_sp = ''\n close_sp = ''\n src_tokens = line_src.split()\n tgt_tokens = line_tgt.split()\n try:\n open_pos_src = src_tokens.index(open_sp)\n except:\n open_pos_src = -1\n try:\n clos_pos_src = src_tokens.index(close_sp)\n except:\n clos_pos_src = -1\n try:\n open_pos_tgt = tgt_tokens.index(open_sp)\n except:\n open_pos_tgt = -1\n try:\n clos_pos_tgt = tgt_tokens.index(close_sp)\n except:\n clos_pos_tgt = -1\n\n # do statistics; false_positive = src has no tag, tgt has tag ; false_negative = src has tag, tgt has no tag;\n # false_positive = result_list.count(3)\n # false_negative = result_list.count(5)\n # correct = result_list.count(1); 2 if tag is correct, but token inside has changed\n # no_match = result_list.count(9)\n src_tag = False\n tgt_tag = False\n if open_pos_src >= 0 and clos_pos_src == (open_pos_src + 4):\n src_tag = True\n if open_pos_tgt >= 0 and clos_pos_tgt == (open_pos_tgt + 2):\n tgt_tag = True\n\n if src_tag == True and tgt_tag == False:\n return 5 # false negative\n if src_tag == False and tgt_tag == True:\n return 3 # false positive\n if src_tag == False and tgt_tag == False:\n return 9 # no match\n if src_tag == True and tgt_tag == True:\n if src_tokens[open_pos_src + 3] == tgt_tokens[open_pos_tgt + 1]:\n return 1 # correct\n else:\n print('copy tag is good, but token inside is wrong')\n print(src_tokens[open_pos_src + 3])\n print('to')\n print(tgt_tokens[open_pos_tgt + 1])\n return 2\n return -1\n\ndef main(para):\n # parameters: ratio, filenames\n # percentage of lines for processing\n ratio = 0.25\n\n # path for source text (before processing)\n source_txt_rd = './' + para[1]\n\n # path for target text(before processing)\n target_txt_rd = './' + para[2] + '.hyp_model_step_' + para[3]\n\n # compare the number of lines in source and target, if not same, quit\n total_lines = cal_lines(source_txt_rd)\n if len(target_txt_rd) > 3 and total_lines != cal_lines(target_txt_rd):\n print('source and target text have different numbers of lines')\n return\n print('total lines in file = ')\n print(total_lines)\n # calculate the TotalProcessLines\n total_process_lines = int(ratio * total_lines)\n print('total processing lines = ')\n print(total_process_lines)\n\n # initialize result list\n result_list = [-1]\n for i in range(total_lines-1):\n result_list.append(-1)\n print('initial result list = ')\n print(result_list)\n\n i = 0\n with open(source_txt_rd, 'r', encoding='utf-8') as source_file, open(target_txt_rd, 'r',\n encoding='utf-8') as target_file:\n for line_src in source_file:\n line_tgt = target_file.readline()\n # print(line_src)\n # print(line_tgt)\n result_list[i] = check_sentence_pair(line_src, line_tgt, 'SP')\n i += 1\n\n print('real result list = ')\n print(result_list)\n # do statistics; false_positive = src has no tag, tgt has tag ; false_negative = src has tag, tgt has no tag;\n false_positive = result_list.count(3)\n false_negative = result_list.count(5)\n correct = result_list.count(1)\n half_correct = result_list.count(2)\n no_match = result_list.count(9)\n if (correct + false_negative + false_positive) != 0:\n ratio_correct = correct/(correct + false_negative + false_positive)\n else:\n print('(correct + false_negative + false_positive) = 0 ! ')\n ratio_correct = -1\n\n print('correct = ')\n print(correct)\n print('half correct = ')\n print(half_correct)\n print('false_positive = ')\n print(false_positive)\n print('false_negative = ')\n print(false_negative)\n print('ratio_correct = ')\n print(ratio_correct)\n print('finish processing!')\n return\n\n\nif __name__ == '__main__':\n print('argv number ', len(sys.argv))\n # 1st argv: src file, such as test.en for en-zhen, test.en for en-de,,news-test.zh (for zh-en)\n # 2nd argv: tgt file,\n # 3nd argv: no. of checkpoints from 55k, e.g 70000, 95000\n main(sys.argv)\n","sub_path":"chosp-eval.py","file_name":"chosp-eval.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"128263100","text":"\"\"\"Support for launching a web browser on the host machine.\"\"\"\nimport webbrowser\n\nimport voluptuous as vol\n\nATTR_URL = \"url\"\nATTR_URL_DEFAULT = \"https://www.google.com\"\n\nDOMAIN = \"browser\"\n\nSERVICE_BROWSE_URL = \"browse_url\"\n\nSERVICE_BROWSE_URL_SCHEMA = vol.Schema(\n {\n # pylint: disable=no-value-for-parameter\n vol.Required(ATTR_URL, default=ATTR_URL_DEFAULT): vol.Url()\n }\n)\n\n\ndef setup(hass, config):\n \"\"\"Listen for browse_url events.\"\"\"\n\n hass.services.register(\n DOMAIN,\n SERVICE_BROWSE_URL,\n lambda service: webbrowser.open(service.data[ATTR_URL]),\n schema=SERVICE_BROWSE_URL_SCHEMA,\n )\n\n return True\n","sub_path":"homeassistant/components/browser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"338707074","text":"from fastapi import APIRouter, Depends, HTTPException\nfrom app.schemas import Intervention, InterventionCreate, InterventionUpdate\nfrom app import crud\nfrom app.api import get_db\nfrom app.core import authorization, set_policies\n\nfrom sqlalchemy.orm import Session\nfrom typing import List\n\nrouter = APIRouter()\n\npolicies = {\n \"interventions:create\": [\"owner\", \"manager\", \"contributor\"],\n \"interventions:get\": [\"owner\", \"manager\", \"contributor\", \"reader\"],\n \"interventions:get_year\": [\"owner\", \"manager\", \"contributor\", \"reader\"],\n \"interventions:update\": [\"owner\", \"manager\", \"contributor\"],\n \"interventions:delete\": [\"owner\", \"manager\", \"contributor\"],\n}\nset_policies(policies)\n\n\n@router.post(\"\", response_model=Intervention)\ndef create(\n organization_id: int,\n *,\n auth=Depends(authorization(\"interventions:create\")),\n request_intervention: InterventionCreate,\n db: Session = Depends(get_db),\n):\n request_intervention.organization_id = organization_id\n return crud.intervention.create(db, obj_in=request_intervention)\n\n\n@router.get(\"/{intervention_id}\", response_model=Intervention)\ndef get(\n intervention_id: int,\n *,\n auth=Depends(authorization(\"interventions:get\")),\n db: Session = Depends(get_db),\n):\n return crud.intervention.get(db, id=intervention_id)\n\n\n@router.get(\"/year/{year}\", response_model=List[Intervention])\ndef get_year(\n organization_id: int,\n year: int,\n *,\n auth=Depends(authorization(\"interventions:get_year\")),\n db: Session = Depends(get_db),\n):\n return crud.intervention.get_by_year(db, organization_id, year)\n\n\n@router.patch(\"/{intervention_id}\", response_model=Intervention)\ndef update(\n intervention_id: int,\n *,\n auth=Depends(authorization(\"interventions:update\")),\n request_intervention: InterventionUpdate,\n db: Session = Depends(get_db),\n):\n intervention_in_db = crud.intervention.get(db, id=intervention_id)\n\n if not intervention_in_db:\n raise HTTPException(status_code=404, detail=\"Intervention not found\")\n\n return crud.intervention.update(\n db, db_obj=intervention_in_db, obj_in=request_intervention\n )\n\n\n@router.delete(\"/{intervention_id}\", response_model=Intervention)\ndef delete(\n id: int,\n *,\n auth=Depends(authorization(\"interventions:delete\")),\n db: Session = Depends(get_db),\n):\n return crud.intervention.remove(db, id=id)\n","sub_path":"backend/app/app/api/api_v1/endpoints/intervention.py","file_name":"intervention.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"443320052","text":"# Q5 and Q6\n\nimport pandas as p\nimport pandasql as sql\nimport pylab as g\nimport os\n\nnation = p.read_excel(r\"..\\Football Data New Excel Format.xlsx\",\"Nation\")\n\nname = p.read_excel(r\"..\\Football Data New Excel Format.xlsx\",\"Name\")\n\nOverall = p.read_excel(r\"..\\Football Data New Excel Format.xlsx\",\"Overall\")\n\ndata = p.concat([nation,name,Overall],axis=1)\n\n# best player of nation\nresult = sql.sqldf(\"Select a.Nationality,a.Name,a.Overall from data a where Overall = (Select Max(Overall) from data b where a.Nationality=b.Nationality) order by Nationality\")\n\nuni_nation = list(set(result[\"Nationality\"]))\nuni_nation.sort()\ndict_players_of_nation = {}\ndict_players_overall = {}\nfile = open(\"Nation_Best_Player.txt\",\"wb\")\nfile1 = open(\"Nation_Overall_Max.txt\",\"wb\")\nfor x in uni_nation:\n\n list1 = []\n for y in list(result[\"Name\"][result[\"Nationality\"]==x]):\n list1.append(y)\n \n dict_players_of_nation.update({x:list1})\n dict_players_overall.update({x:list(result[\"Overall\"][result[\"Nationality\"]==x])[0]})\n file.write((str(x)+\",\"+str(list1)+\"\\n\").encode())\n file1.write((str(x)+\",\"+str(list(result[\"Overall\"][result[\"Nationality\"]==x])[0])+\"\\n\").encode())\n\nfile.close()\nfile1.close()\n\nimport SortDict as sd\n\ndict_players_overall = sd.srt(dict_players_overall,\"V\",True)\n\nx = list(dict_players_overall.keys())\ny = list(dict_players_overall.values())\n\ng.bar(x[:11],y[:11])\ng.xticks(rotation=90)\ncount = 0\nwhile count<11:\n g.text(count,y[count]+1,str(y[count]))\n count+=1\ng.title(\"Top 10 Nation by Overall Performance of their best player\")\ng.show()\n","sub_path":"Analysis/Post Visualization/Nation/Q5 Q6.py","file_name":"Q5 Q6.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"617974422","text":"import os\nimport sys\nimport random\n\naverages = {}\nstddev = 100\nnumber_of_lines = 1000000\nnumber_of_sellers = number_of_lines / 1000\nhacks = 20\nhack_odds = 3\n\ndef row(i):\n time = i\n \n t = time / 1000\n day = (t % 30) + 1\n month = ((t / 30) % 12) + 1\n year = (t / 30 / 12) + 2016\n amount = random.randint(10, 10000)\n buyer = random.randint(0, 50)\n seller = random.randint(0, number_of_sellers)\n credit_card = random.randint(0, 100000)\n latitude = random.randint(-500, 500)\n longitude = random.randint(-500, 500)\n return [time, year, month, day, amount, buyer, seller, credit_card, latitude, longitude]\n\ndef row_as_str(r):\n return \",\".join([ str(e) for e in r ]) + \"\\n\"\n\nif __name__ == '__main__':\n with open(\"mini_dataset.csv\", \"w\") as f:\n for i in range(number_of_lines):\n f.write(row_as_str(row(i)))","sub_path":"timeseries_generator.py","file_name":"timeseries_generator.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"468399045","text":"# utils.py\n\nimport pandas as pd\n\ndef read_and_clean( filename ):\n df = pd.read_csv(filename, index_col=['Date'], parse_dates=['Date'])\n df = clean_trans(df)\n return df\n\ndef clean_trans( df ):\n '''CLEAN_TRANS Removes reimbursable transactions'''\n \n df.loc[df['Transaction Type']=='debit', 'Amount'] *= -1\n df = df[df.Category != 'Reimbursement']\n df = df[df.Labels != 'NTU Reimbursable']\n df = df[df.Labels != 'USGS Reimbursable']\n df = df[df.Labels != 'Reimbursable']\n df = df[df.Labels != 'USGS Reimbursable Work Travel']\n df = df[df.Labels != 'Returned']\n df = df[df.Labels != 'Reimbursable Vacation']\n df = df[df.Labels != 'Reimbursable Work Travel']\n \n return df\n\ndef clean_cash_trans( df ):\n '''CLEAN_CASH_TRANS Removes cash transactions that were only entered for organizational purposes'''\n \n print('This function is not yet implemented.')\n\n# See documentation notes in trend_analysis.ipynb\n# The code in here is solid, but the use of inputs is sloppy, and\n# the overall implementation of this code is sloppy.\ndef trans_trend_plot( user, user_name, df, figures ):\n import os\n import pandas as pd\n import numpy as np\n import datetime as dt\n import matplotlib.pyplot as plt\n from bokeh.plotting import figure, curdoc, show, save, output_file\n from bokeh.models import ColumnDataSource, LabelSet, HoverTool, BoxZoomTool, NumeralTickFormatter, DatetimeTickFormatter\n from bokeh.models.widgets import Panel, Tabs\n from bokeh.layouts import column\n from bokeh.palettes import Blues, Greens\n\n import utils\n\n \n for group, cats in user.catlist.items():\n TITLE = \"FY Spending by Group: \" + group #+ ' ' + str(cats)\n tools = \"pan,wheel_zoom,reset,save\".split(',')\n ''' hover = HoverTool(tooltips=[\n (\"Date\",\"@DateStr\"),\n (\"Description\",\"@Description\"),\n (\"Amount\",\"@AmountStr\"),\n (\"BALANCE\",\"@CumAmountStr\")\n ])\n '''\n # https://bokeh.pydata.org/en/latest/docs/user_guide/tools.html\n hover = HoverTool(\n tooltips=[\n ('Date', '@Date{%F}'),\n ('Description', '@Description'),\n ('Amount', '@Amount{$0,0.00}'), # use @{ } for field names with spaces\n ('Balance', '@CumAmount{$0,0.00}'),\n ('Cum % Salary', '@CumPercent{0%}'), \n ],\n\n formatters={\n 'Date' : 'datetime',\n 'Amount' : 'numeral',\n 'CumAmount' : 'numeral',\n 'CumPercent' : 'numeral'\n },\n )\n tools.append(BoxZoomTool(dimensions='width'))\n tools.append(hover)\n\n p1 = figure(tools=tools, toolbar_location='right', logo='grey', plot_height=400, plot_width=1000, title=TITLE,\n x_axis_type='datetime'\n )\n p1.background_fill_color = \"#dddddd\"\n p1.xaxis.axis_label = \"Date\"\n p1.yaxis.axis_label = \"$\"\n p1.grid.grid_line_color = \"white\"\n\n \n p2 = figure(tools=tools, toolbar_location='right', logo='grey', plot_height=400, plot_width=1000, title=TITLE,\n x_axis_type='datetime'\n )\n p2.background_fill_color = \"#dddddd\"\n p2.xaxis.axis_label = \"Date\"\n p2.yaxis.axis_label = \"% Salary\"\n p2.grid.grid_line_color = \"white\"\n\n cmap = Blues[9][len(user.fiscal_years)-1::-1]\n #cmap = Blues[9][::int(-9/len(fiscal_years))]\n\n for i in range(len(user.fiscal_years)):\n fy = user.fiscal_years[i]\n line_clr = cmap[i]\n df = df.sort_index(axis=0, ascending=True)\n df2 = df[fy['start']:fy['stop']].sort_index(axis=0, ascending=True)\n df2 = df2[df2['Category'].isin(cats)]\n \n if len(df2) > 0:\n #df2['DateStr'] = df2.index.astype(str)\n df2['RelativeDate'] = df2.index - pd.Timestamp(fy['start']) + np.timedelta64(9, 'M')\n df2['CumAmount'] = df2['Amount'].cumsum().abs() # .abs().cumsum() <-- should work if all reimbursables are removed\n df2['CumPercent'] = df2['CumAmount'] / fy['salary']\n #df2['AmountStr'] = df2['Amount'].astype(str)\n #df2['CumAmountStr'] = df2['CumAmount'].astype(str)\n \n source = ColumnDataSource(df2)\n \n p1.step(\"RelativeDate\", \"CumAmount\", source=source, mode='after',\n line_color=line_clr, line_width=fy['lw'], legend=fy['label'])\n p1.circle(\"RelativeDate\", \"CumAmount\", source=source,\n color=None, size=fy['size'], fill_alpha=0.0)\n\n p2.step(\"RelativeDate\", \"CumPercent\", source=source, mode='after',\n line_color=line_clr, line_width=fy['lw'], legend=fy['label'])\n p2.circle(\"RelativeDate\", \"CumPercent\", source=source,\n color=None, size=fy['size'], fill_alpha=0.0)\n \n # https://bokeh.pydata.org/en/latest/docs/reference/models/formatters.html#bokeh.models.formatters.NumeralTickFormatter\n p1.yaxis[0].formatter = NumeralTickFormatter(format=\"$0a\")\n p2.yaxis[0].formatter = NumeralTickFormatter(format=\"0.0%\")\n p1.xaxis[0].formatter = DatetimeTickFormatter(months=\"%B\")\n p2.xaxis[0].formatter = DatetimeTickFormatter(months=\"%B\")\n \n p1.legend.location = 'top_left'\n p2.legend.location = 'top_left'\n\n tab1 = Panel(child=p1, title=\"Dollars\")\n tab2 = Panel(child=p2, title=\"% Salary\")\n\n tabs = Tabs(tabs=[ tab1, tab2 ])\n \n figures.append(tabs)\n\n filename=os.getcwd() + '/trend_analysis_' + user_name + '.html'\n output_file(filename, title=\"Trend Analysis (\" + user_name + \")\")\n show(column(figures))\n ","sub_path":"proj/PyFinance/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"74464170","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/tpDcc/dccs/maya/data/skin.py\n# Compiled at: 2020-05-13 19:28:33\n# Size of source mod 2**32: 19607 bytes\n\"\"\"\nModule that contains skin weights data classes for Maya\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\nimport os, json, threading\nfrom collections import OrderedDict\nimport tpDcc as tp, tpDcc.dccs.maya as maya\nfrom tpDcc.libs.python import fileio, folder, path as path_utils\nfrom tpDcc.dccs.maya.data import base\nfrom tpDcc.dccs.maya.core import helpers, shape as shape_utils, deformer as deform_utils\nfrom tpDcc.dccs.maya.core import decorators as maya_decorators, scene as scene_utils, geometry as geo_utils\n\nclass SkinWeightsData(base.MayaCustomData, object):\n\n def __init__(self, name=None, path=None):\n super(SkinWeightsData, self).__init__(name=name, path=path)\n\n @staticmethod\n def get_data_type():\n return 'maya.skin_weights'\n\n @staticmethod\n def get_data_extension():\n return 'skin'\n\n @staticmethod\n def get_data_title():\n return 'Skin Weights'\n\n def export_data(self, file_path=None, comment='-', create_version=True, *args, **kwargs):\n if not tp.is_maya():\n maya.logger.warning('Data must be exported from within Maya!')\n return False\n else:\n file_path = file_path or self.get_file()\n objects = kwargs.get('objects', None)\n if not objects:\n objects = tp.Dcc.selected_nodes(full_path=True)\n if not objects:\n maya.logger.warning('Nothing selected to export skin weights of. Please, select a mesh, curve, NURBS surface or lattice with skin weights to export')\n return False\n file_folder = os.path.dirname(file_path)\n obj_dirs = OrderedDict()\n skin_nodes = OrderedDict()\n geo_paths = OrderedDict()\n skin_weights = OrderedDict()\n for obj in objects:\n if shape_utils.is_a_shape(obj):\n obj = tp.Dcc.node_parent(obj, full_path=True)\n else:\n obj_filename = obj\n if obj.find('|') > -1:\n obj_filename = obj_filename.replace('|', '.')\n if obj_filename.startswith('.'):\n obj_filename = obj_filename[1:]\n if obj_filename.find(':') > -1:\n obj_filename = obj_filename.replace(':', '-')\n skin = deform_utils.find_deformer_by_type(obj, 'skinCluster')\n skin or maya.logger.warning('Skin exported failed! No skinCluster node found on \"{}\"'.format(obj))\n return False\n else:\n geo_path = path_utils.join_path(file_folder, obj_filename)\n if path_utils.is_dir(geo_path):\n folder.delete_folder(obj_filename, file_folder)\n geo_path = folder.create_folder(obj_filename, file_folder)\n geo_path or maya.logger.error('Unable to create skin weights directory: \"{}\" in \"{}\"'.format(obj_filename, file_folder))\n return False\n weights = deform_utils.get_skin_weights(skin)\n obj_dirs[obj] = obj_filename\n skin_nodes[obj] = skin\n geo_paths[obj] = geo_path\n skin_weights[obj] = weights\n\n for (obj, skin_node), (_, geo_path), (_, skin_weights) in zip(skin_nodes.items(), geo_paths.items(), skin_weights.items()):\n maya.logger.info('Exporting weights: {} > {} --> \"{}\"'.format(obj, skin_node, geo_path))\n info_lines = list()\n info_file = fileio.create_file('influence.info', geo_path)\n for influence in skin_weights:\n if not influence is None:\n if influence == 'None':\n pass\n else:\n weight_list = skin_weights[influence]\n if not weight_list:\n pass\n else:\n thread = MayaLoadWeightFileThread()\n influence_line = thread.run(influence, skin_node, skin_weights[influence], geo_path)\n if influence_line:\n info_lines.append(influence_line)\n\n writer = fileio.FileWriter(info_file)\n writer.write(info_lines)\n settings_file = fileio.create_file('settings.info', geo_path)\n setting_lines = list()\n if shape_utils.has_shape_of_type(obj, 'mesh'):\n self._export_mesh_obj(obj, geo_path)\n if tp.Dcc.attribute_exists(skin_node, 'blendWeights'):\n blend_weights = deform_utils.get_skin_blend_weights(skin_node)\n setting_lines.append(\"['blendWeights', {}]\".format(blend_weights))\n if tp.Dcc.attribute_exists(skin_node, 'skinningMethod'):\n skin_method = tp.Dcc.get_attribute_value(skin_node, 'skinningMethod')\n setting_lines.append(\"['skinningMethod', {}]\".format(skin_method))\n write_settings = fileio.FileWriter(settings_file)\n write_settings.write(setting_lines)\n maya.logger.info('Skin weights exported successfully: {} > {} --> \"{}\"'.format(obj, skin_node, geo_path))\n\n data_to_save = OrderedDict()\n for obj, obj_filename in obj_dirs.items():\n data_to_save[obj] = {'enabled':True, \n 'folder':obj_filename}\n\n with open(file_path, 'w') as (fh):\n json.dump(data_to_save, fh)\n maya.logger.info('Skin weights export operation completed successfully!')\n version = fileio.FileVersion(file_folder)\n version.save(comment)\n return True\n\n @maya_decorators.undo_chunk\n def import_data(self, file_path='', objects=None):\n \"\"\"\n Loads data object\n :param file_path: str, file path of file to load\n \"\"\"\n if not tp.is_maya():\n maya.logger.warning('Data must be exported from within Maya!')\n return False\n else:\n file_path = file_path or self.get_file()\n if not file_path or not os.path.isfile(file_path):\n maya.logger.warning('Impossible to import skin weights from: \"{}\"'.format(file_path))\n return False\n with open(file_path, 'r') as (fh):\n skin_data = json.load(fh)\n if not skin_data:\n maya.logger.warning('No skin data found in file: \"{}\"'.format(file_path))\n return False\n file_folder = os.path.dirname(file_path)\n folders = folder.get_folders(file_folder)\n if not objects:\n objects = tp.Dcc.selected_nodes(full_path=True) or list()\n for obj in objects:\n if obj in skin_data:\n pass\n else:\n skin_data[obj] = {'folder':tp.Dcc.node_short_name(obj), \n 'enabled':True}\n\n for obj, obj_data in skin_data.items():\n obj_folder = obj_data.get('folder', None)\n if not obj_folder:\n pass\n else:\n obj_enabled = obj_data.get('enabled', False) and obj_folder in folders\n obj_path = path_utils.clean_path(os.path.join(file_folder, obj_folder))\n if not not obj_enabled:\n if not os.path.isdir(obj_path):\n continue\n obj_exists = tp.Dcc.object_exists(obj)\n if not obj_exists:\n continue\n self._import_skin_weights(obj_path, obj)\n\n self._center_view()\n maya.logger.info('Imported \"{}\" skin data'.format(self.name))\n return True\n\n def get_skin_meshes(self, file_path=None):\n \"\"\"\n Returns all skinned meshes fro ma .skin file\n :param file_path: str\n :return: list(str)\n \"\"\"\n if not tp.is_maya():\n return\n else:\n file_path = file_path or self.get_file()\n if not file_path or not os.path.isfile(file_path):\n return\n skin_path = path_utils.join_path(path_utils.get_dirname(file_path), self.name)\n meshes = None\n if path_utils.is_dir(skin_path):\n meshes = folder.get_folders(skin_path)\n return meshes\n\n def remove_mesh(self, mesh, file_path=None):\n \"\"\"\n Removes a mesh from a .skin file\n :param mesh: str\n :param file_path: str\n :return: bool\n \"\"\"\n if not tp.is_maya():\n return\n else:\n file_path = file_path or self.get_file()\n if not file_path or not os.path.isfile(file_path):\n return\n skin_path = path_utils.join_path(path_utils.get_dirname(file_path), self.name)\n folder.delete_folder(mesh, skin_path)\n test_path = path_utils.join_path(skin_path, mesh)\n return bool(path_utils.is_dir(test_path))\n\n def _export_mesh_obj(self, mesh, data_path):\n \"\"\"\n Internal function that exports given mesh object (creates a backup of the mesh in disk)\n :param mesh: str\n :param data_path: str\n \"\"\"\n helpers.load_plugin('objExport')\n envelope_value = deform_utils.get_skin_envelope(mesh)\n deform_utils.set_skin_envelope(mesh, 0)\n maya.cmds.select(mesh)\n original_path = tp.Dcc.scene_name()\n mesh_path = '{}/mesh.obj'.format(data_path)\n try:\n maya.cmds.file(rename=mesh_path)\n maya.cmds.file(force=True,\n options='groups=0;ptgroups=0;materials=0;smoothing=0;normals=0',\n type='OBJexport',\n preserveReferences=False,\n exportSelected=True)\n finally:\n maya.cmds.file(rename=original_path)\n\n deform_utils.set_skin_envelope(mesh, envelope_value)\n\n def _import_mesh_obj(self, data_path):\n \"\"\"\n Internal function that imports mesh object stored in given path\n :param data_path: str, path that contains already exported mesh object\n :return: str, name of the imported mesh\n \"\"\"\n mesh_path = path_utils.join_path(data_path, 'mesh.obj')\n if not path_utils.is_file(mesh_path):\n return\n else:\n track = scene_utils.TrackNodes()\n track.load(node_type='mesh')\n maya.cmds.file(mesh_path, i=True, type='OBJ', ignoreVersion=True, options='mo=1')\n delta = track.get_delta()\n if delta:\n delta = tp.Dcc.node_parent(delta, full_path=True)\n return delta\n\n def _import_skin_weights(self, data_path, mesh):\n if not tp.Dcc.object_exists(mesh) or not os.path.isdir(data_path):\n return False\n else:\n is_valid_mesh = False\n shape_types = ['mesh', 'nurbsSurface', 'nurbsCurve', 'lattice']\n for shape_type in shape_types:\n if shape_utils.has_shape_of_type(mesh, shape_type):\n is_valid_mesh = True\n break\n\n if not is_valid_mesh:\n maya.logger.warning('Node \"{}\" is not a valid mesh node! Currently supported nodes include: {}'.format(mesh, shape_types))\n return False\n print('Importing skin clusters {} --> \"{}\"'.format(mesh, data_path))\n influence_dict = self._get_influences(data_path)\n if not influence_dict:\n maya.logger.warning('No influences data found for: {}'.format(mesh))\n return False\n influences = influence_dict.keys()\n if not influences:\n maya.logger.warning('No influences found for: \"{}\"'.format(mesh))\n return False\n influences.sort()\n maya.logger.debug('Influences found for {}: {}'.format(mesh, influences))\n short_name = tp.Dcc.node_short_name(mesh)\n transfer_mesh = None\n if shape_utils.has_shape_of_type(mesh, 'mesh'):\n orig_mesh = self._import_mesh_obj(data_path)\n if orig_mesh:\n mesh_match = geo_utils.is_mesh_compatible(orig_mesh, mesh)\n transfer_mesh = mesh_match or mesh\n mesh = orig_mesh\n else:\n tp.Dcc.delete_object(orig_mesh)\n add_joints = list()\n remove_entries = list()\n for influence in influences:\n joints = tp.Dcc.list_nodes(influence, full_path=True)\n if type(joints) == list:\n if len(joints) > 1:\n add_joints.append(joints[0])\n conflicting_count = len(joints)\n maya.logger.warning('Found {} joints with name {}. Using only the first one: {}'.format(conflicting_count, influence, joints[0]))\n remove_entries.append(influence)\n influence = joints[0]\n if not tp.Dcc.object_exists(influence):\n tp.Dcc.clear_selection()\n maya.cmds.joint(n=influence, p=(influence_dict[influence]['position']))\n\n for entry in remove_entries:\n influences.remove(entry)\n\n influences += add_joints\n skin_cluster = deform_utils.find_deformer_by_type(mesh, 'skinCluster')\n if skin_cluster:\n tp.Dcc.delete_object(skin_cluster)\n skin_cluster = maya.cmds.skinCluster(influences,\n mesh, tsb=True, n=(tp.Dcc.find_unique_name('skin_%s' % short_name)))[0]\n tp.Dcc.set_attribute_value(skin_cluster, 'normalizeWeights', 0)\n deform_utils.set_skin_weights_to_zero(skin_cluster)\n influence_index = 0\n influence_index_dict = deform_utils.get_skin_influences(skin_cluster, return_dict=True)\n progress_bar = tp.DccProgressBar('Import Skin', len(influence_dict.keys()))\n for influence in influences:\n orig_influence = influence\n if influence.count('|') > 1:\n split_influence = influence.split('|')\n if len(split_influence) > 1:\n influence = split_influence[(-1)]\n progress_bar.status('Importing skin mesh: {}, influence: {}'.format(short_name, influence))\n if 'weights' not in influence_dict[orig_influence]:\n maya.logger.warning('Weights msissing for influence: {}. Skipping it ...'.format(influence))\n else:\n weights = influence_dict[orig_influence]['weights']\n if influence not in influence_index_dict:\n pass\n else:\n index = influence_index_dict[influence]\n for i in range(len(weights)):\n weight = float(weights[i])\n if not weight == 0:\n if weight < 0.0001:\n pass\n else:\n attr = '{}.weightList[{}].weights[{}]'.format(skin_cluster, i, index)\n maya.cmds.setAttr(attr, weight)\n\n progress_bar.inc()\n if progress_bar.break_signaled():\n break\n influence_index += 1\n\n progress_bar.end()\n maya.cmds.skinCluster(skin_cluster, edit=True, normalizeWeights=1)\n maya.cmds.skinCluster(skin_cluster, edit=True, forceNormalizeWeights=True)\n settings_path = path_utils.join_path(data_path, 'settings.info')\n if path_utils.is_file(settings_path):\n lines = fileio.get_file_lines(settings_path)\n for line in lines:\n test_line = line.strip()\n if not test_line:\n pass\n else:\n line_list = eval(line)\n attr_name = line_list[0]\n value = line_list[1]\n if attr_name == 'blendWeights':\n deform_utils.set_skin_blend_weights(skin_cluster, value)\n elif tp.Dcc.attribute_exists(skin_cluster, attr_name):\n tp.Dcc.set_attribute_value(skin_cluster, attr_name, value)\n\n if transfer_mesh:\n maya.logger.info('Import sking weights: mesh topology does not match. Trying to transfer topology ...')\n deform_utils.skin_mesh_from_mesh(mesh, transfer_mesh)\n tp.Dcc.delete_object(mesh)\n maya.logger.info('Import skinCluster weights: {} from {}'.format(short_name, data_path))\n return True\n\n def _get_influences(self, folder_path):\n \"\"\"\n Internal function that returns a dictionary containing influences data from influence files\n contained in the given directory\n :param folder_path: str, path that contains influence file\n :return: dict, influence data\n \"\"\"\n influence_dict = dict()\n files = fileio.get_files(folder_path)\n if not files:\n return influence_dict\n else:\n info_file = path_utils.join_path(folder_path, 'influence.info')\n if not path_utils.is_file(info_file):\n return influence_dict\n info_lines = fileio.get_file_lines(info_file)\n for line in info_lines:\n if not line:\n pass\n else:\n line_dict = eval(line)\n influence_dict.update(line_dict)\n\n for influence in files:\n if not not influence.endswith('.weights'):\n if influence == 'influence.info':\n pass\n else:\n read_thread = MayaReadWeightFileThread()\n try:\n influence_dict = read_thread.run(influence_dict, folder_path, influence)\n except Exception as exc:\n maya.logger.error('Errors with influence \"{}\" while reading weight file: \"{}\" | {}'.format(influence, info_file, exc))\n\n return influence_dict\n\n\nclass MayaLoadWeightFileThread(threading.Thread, object):\n\n def __init__(self):\n super(MayaLoadWeightFileThread, self).__init__()\n\n def run(self, influence_index, skin, weights, file_path):\n influence_name = deform_utils.get_skin_influence_at_index(influence_index, skin)\n if not influence_name or not tp.Dcc.object_exists(influence_name):\n return\n else:\n weight_path = fileio.create_file('{}.weights'.format(influence_name), file_path)\n if not path_utils.is_file(weight_path):\n maya.logger.warning('\"{}\" is not a valid path to save skin weights into!'.format(file_path))\n return\n writer = fileio.FileWriter(weight_path)\n writer.write_line(weights)\n influence_position = tp.Dcc.node_world_space_translation(influence_name)\n return \"{'%s' : {'position' : %s}}\" % (influence_name, str(influence_position))\n\n\nclass MayaReadWeightFileThread(threading.Thread):\n\n def __init__(self):\n super(MayaReadWeightFileThread, self).__init__()\n\n def run(self, influence_dict, folder_path, influence):\n file_path = path_utils.join_path(folder_path, influence)\n influence = influence.split('.')[0]\n lines = fileio.get_file_lines(file_path)\n if not lines:\n influence_dict[influence]['weights'] = None\n return influence_dict\n else:\n weights = eval(lines[0])\n if influence in influence_dict:\n influence_dict[influence]['weights'] = weights\n return influence_dict","sub_path":"pycfiles/tpDcc_dccs_maya-0.0.10-py3.6/skin.cpython-36.py","file_name":"skin.cpython-36.py","file_ext":"py","file_size_in_byte":20633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"494820446","text":"#Reformats text into CSV\n\ndef reformat(text):\n\n lines = text.splitlines()\n for i in range(0, len(lines)):\n lines[i] = lines[i].replace(\"$\",\" \")\n \n lines = \"\\n\".join(lines)\n return lines\n\n\n\ndef main (word):\n \tdatafile = open(word, 'r')\n \ttext = datafile.read()\n \tdatafile.close()\n \tdatafile = open(word, 'w')\n \tdatafile.write(reformat(text))\n \tdatafile.close()\n\n\ndata = raw_input(\"Enter File Name: \")\nmain(data)","sub_path":"reformat2.py","file_name":"reformat2.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"263067373","text":"# 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef Merge(pHead1, pHead2):\n if not pHead1:\n return pHead2\n if not pHead2:\n return pHead1\n pMergeListNode = None\n if pHead1.val < pHead2.val:\n pMergeListNode = pHead1\n pMergeListNode.next = Merge(pMergeListNode, pHead2)\n else:\n pMergeListNode = pHead2\n pMergeListNode.next = Merge(pHead1, pHead2.next)\n pMergeListNode = pMergeListNode.next\n return pMergeListNode\n","sub_path":"offer/merge_listnode.py","file_name":"merge_listnode.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"97133359","text":"__author__ = 'shmakovs'\n\nimport sys\nsys.path.insert(0, \"/home/shmakovs/Fishing/Pipeline/Git/Fishing/\")\nimport Helper1603\n\nTAX_STATUS_UNKNOWN = \"Unknown\"\n\ndef GetTaxIds(FileName):\n TaxIds = dict()\n with open(FileName, \"r\") as File:\n for Line in File:\n #print(Line)\n LineValues = Line[:-1].split(\"\\t\")\n if LineValues[0] == \"good\":\n TaxIds[int(LineValues[1])] = \"good\"\n else:\n TaxIds[int(LineValues[1])] = \"bad\"\n\n\n return TaxIds\n\ndef GetContigID(LineValues):\n if \"|\" in LineValues[ANN_SUBJ_ID]:\n ContigIDValues = LineValues[ANN_SUBJ_ID].split(\"|\")\n if len(ContigIDValues) <= 3:\n ContigID = ContigIDValues[1]\n else:\n ContigID = ContigIDValues[3]\n else:\n ContigID = LineValues[ANN_SUBJ_ID]\n\n return ContigID\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/CRISPRicity/JointClusters/TypeIII/EcoliRNA.hits\"\n# # SpacersLengthsFileName = \"/panfs/pan1/prokdata/CRISPRicity/JointClusters/TypeIII/EcoliRRNA.len\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/CRISPRicity/JointClusters/TypeIII/PyrococcusRRNA.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/CRISPRicity/JointClusters/TypeIII/PyrococcusRRNA.len\"\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/myxilla_spacers.cl_virus.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/myxilla_spacers.cl_all.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/myxilla_spacers.cl.len\"\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/palmata_spacers.cl_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/palmata_spacers.cl_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/palmata_spacers.cl.len\"\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/panicea_spacers.cl.fasta_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/panicea_spacers.cl_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/panicea_spacers.cl.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/sitiens_spacers.cl_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/sitiens_spacers.cl_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/sitiens_spacers.cl.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/water_spacers.cl_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/water_spacers.cl_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/clusters/water_spacers.cl.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/myxilla_spacers_in_metagenome_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/myxilla_spacers_in_metagenome_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/myxilla_spacers_in_metagenome.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/palmata_spacers_in_metagenome_virus.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/palmata_spacers_in_metagenome_all.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/palmata_spacers_in_metagenome.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/panicea_spacers_in_metagenome_virus.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/panicea_spacers_in_metagenome.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/panicea_spacers_in_metagenome.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/sitiens_spacers_in_metagenome_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/sitiens_spacers_in_metagenome_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/sitiens_spacers_in_metagenome.len\"\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/water_spacers_in_metagenome_all.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/water_spacers_in_metagenome_virus.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/WaterMetagenome/water_spacers_in_metagenome.len\"\n\n#SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/Orphans/Spacers_from_Orphans_vs_virus.hits\"\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/Orphans/orphan_vs_all1603_unfiltered.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/SideProjects/Orphans/Spacers.len\"\n\n# SpacersHitsFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TmpFolder/BlastResults/VirusSpacer.hits\"\n# SpacersLengthsFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TmpFolder/SpacersLengths.tsv\"\n\nSpacersHitsFileName = \"/panfs/pan1/prokdata/SideProjects/2018/SmallCRISPRs/Repeat.hits\"\nSpacersLengthsFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TmpFolder/RepeatsLengths.tsv\"\n\n#ResFileName = SpacersHitsFileName + \"_good_0909\"\n#ResFileName = SpacersHitsFileName + \"_good_095095_euk\"\nResFileName = SpacersHitsFileName + \"_good_0508\"\n\nCoverage = 0.5#0.9#0.8\nIdentity = 0.8#0.9#0.7\n\nSpacersLengthsDict = dict()\nwith open(SpacersLengthsFileName, \"r\") as SpacersLengths:\n for Line in SpacersLengths:\n LineValues = Line[:-1].split(\"\\t\")\n SpacersLengthsDict[LineValues[0]] = int(LineValues[1])\n\n# TaxIDInfoFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TaxIdsAllInfo.tsv\"\n# TaxIDDict = GetTaxIds(TaxIDInfoFileName)\n#\n# RepeatGoodHitsFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TmpFolder/All1603_Repeats_new.seeds\"\n# CRISPRsFileName = \"/panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/TmpFolder/CRISPR_info_types_071117.tsv\"\n#\n# CRISPRs = dict()\n# CRISPRs = Helper1603.AddSeedsDict(CRISPRsFileName, CRISPRs, 200)\n# CRISPRs = Helper1603.AddSeedsDict(RepeatGoodHitsFileName, CRISPRs, 200)\n\n\n\n# query id, subject id, subject length, s. start, s. end, evalue, query seq, subject seq, q. start, q. end, bit score, score, subject tax ids, subject sci names, subject title\n# query id 0, subject id 1, subject ids 2, subject length 3, s. start 4, s. end 5, evalue 6, query seq 7, subject seq 8, q. start 9, q. end 10, score 11, subject sci names 12, subject title 13\n# query id 0, subject id 1, subject ids 2, subject length 3, s. start 4, s. end 5, evalue 6, query seq 7, subject seq 8, q. start 9, q. end 10, score 11, subject sci names 12, subject title 13\n# query id 0, subject id 1, subject ids 2, subject length 3, s. start 4, s. end 5, evalue 6, query seq 7, subject seq 8, q. start 9, q. end 10, score 11, subject tax ids 12, subject sci names 13, subject title 14\n# query id 0, subject id 1, subject ids 2, subject length 3, s. start 4, s. end 5, evalue 6, % identity 7, % query coverage per subject 8,\n# query seq 9, subject seq 10, q. start 11, q. end 12, score 13, subject tax ids 14, subject sci names 15, subject title 16\n# query id 0, subject id 1, subject length 2, s. start 3, s. end 4, evalue 5, query seq 6, subject seq 7, q. start 8, q. end 9, bit score 10, score 11, subject tax ids 12, subject sci names 13, subject title 14\n# query id 0, subject id 1, subject length 2, s. start 3, s. end 4, evalue 5, query seq 6, subject seq 7, q. start 8, q. end 9, bit score 10, score 11, subject tax ids 12, subject sci names 13, subject title 14\n# query id 0, subject id 1, subject ids 2, subject length 3, s. start 4, s. end 5, evalue 6, query seq 7, subject seq 8, q. start 9, q. end 10, score, subject tax ids, subject sci names, subject title\n\nANN_QUERY_ID = 0\nANN_SUBJ_ID = 1\n\nANN_START = 3#4#3\nANN_END = 4#5#4\n\nANN_QUERY_SEQ = 6#7#6\nANN_SUBJ_SEQ = 7#8#7\n\nANN_SUBJ_TAX_ID = 12\nANN_SCORE = 11\nANN_SUBJ_TITLE = 14\n\n\n#ScoreThreshold = 18# 23 18 #23\n# to get good hits, not only 1 per spacer\nwith open(ResFileName, \"w\") as ResFile:\n with open(SpacersHitsFileName, \"r\") as SpacersHitsFile:\n for Line in SpacersHitsFile:\n if Line[0] == \"'\":\n continue\n\n if Line[0] == \"#\":\n continue\n if Line[0] == \"[\":\n continue\n if Line[0:12] == \"CFastaReader\":\n continue\n if Line[0:7] == \"Warning\":\n continue\n if Line[0:5] == \"Error\":\n continue\n\n LineValues = Line[:-1].split(\"\\t\")\n\n if len(LineValues) < 10:\n print(Line)\n\n Start, Stop = Helper1603.minmax(int(LineValues[ANN_START]), int(LineValues[ANN_END]))\n SpacerID = LineValues[0]\n if not SpacerID in SpacersLengthsDict:\n continue\n\n # ContigID = GetContigID(LineValues).split(\".\")[0]\n # if Helper1603.IsInSeeds(ContigID, Start, Stop, CRISPRs):\n # continue\n\n AlignmentLength = Stop - Start + 1\n SpacerLength = SpacersLengthsDict[SpacerID]\n\n if Coverage * SpacerLength > AlignmentLength:\n continue\n\n if Identity * SpacerLength > Helper1603.CountMatches(LineValues[ANN_QUERY_SEQ], LineValues[ANN_SUBJ_SEQ], SpacerLength):#Score:\n continue\n\n # if LineValues[ANN_SUBJ_TAX_ID] != \"N/A\":\n # TaxId = int(LineValues[ANN_SUBJ_TAX_ID].split(\";\")[0])\n # if not TaxId in TaxIDDict:\n # if not \"phage\" in LineValues[ANN_SUBJ_TITLE].lower():\n # #ResFile.write(Line)\n # continue\n # else:\n # if TaxIDDict[TaxId] == \"bad\":\n # #ResFile.write(Line)\n # continue\n\n ResFile.write(Line)\n\n","sub_path":"CRISPRRate/TypeIII/BlastnFiltering.py","file_name":"BlastnFiltering.py","file_ext":"py","file_size_in_byte":10172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"199450035","text":"import random\nimport pygame\nclass Settings():\n \"\"\"存储《图片华容道》所有设置的类\"\"\"\n\n def __init__(self):\n \"\"\"初始化游戏设置\"\"\"\n #屏幕设置\n self.screen_width = 1090\n self.screen_height = 700\n self.bg_color = (255,255,255)\n #滑块设置\n self.block_width = 130\n self.block_height = 130\n #随机数设置,用于扣去随机一张图片\n self.random_row = random.randint(0, 2)\n self.random_col = random.randint(0, 2)\n self.ZERO_ROW = self.random_row\n self.ZERO_COL = self.random_col\n self.init_row = self.random_row\n self.init_col = self.random_col\n self.game_active = True\n self.win = False\n #随机打乱次数\n self.times = 10\n #难度增加系数\n self.times_speed = 20\n #重置步数的代价\n self.times_reset = 10\n ","sub_path":"huarongdao/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"633542431","text":"import numpy as np\nimport control.matlab as ctrl\nimport matplotlib.pyplot as plt\n\nm = 1 # 質量 [kg] 非負\nc = 1 # 減衰係数 [N/m] 非負\nk = 10 # バネ係数 [Ns/m] 非負\n\nsys = ctrl.tf((1),(m,c,k)) # 伝達関数\nprint(sys)\n\nt_range = (0,10) # 0~10秒の範囲をシミュレーション\ny, t = ctrl.impulse(sys, T=np.arange(*t_range, 0.01))\n\nprint(y)\n\nplt.figure(figsize=(7,4),dpi=120,facecolor='white')\nplt.hlines(0,*t_range,colors='gray',ls=':')\nplt.plot(t,y)\nplt.xlim(*t_range)\nplt.show()","sub_path":"mass_spring_dumper_simulation_using_State_Equation.py","file_name":"mass_spring_dumper_simulation_using_State_Equation.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"469232270","text":"import numpy as np\nfrom scipy import spatial\nimport pandas\nimport matplotlib.pyplot as plt\n\n# np.seterr(divide=\"ignore\", invalid=\"ignore\")\n\n\nclass ACO:\n def __init__(\n self,\n func,\n n_dim,\n size_pop=10,\n max_iter=20,\n alpha=1,\n beta=2,\n rho=0.1,\n distance_matrix=None,\n ):\n self.func = func\n self.n_dim = n_dim # 城市数量\n self.size_pop = size_pop # 蚂蚁数量\n self.max_iter = max_iter # 迭代次数\n self.alpha = alpha # 信息素重要程度\n self.beta = beta # 适应度的重要程度\n self.rho = rho # 信息素挥发速度\n\n self.prob_matrix_distance = 1 / ( # eta的值\n distance_matrix + 1e-10 * np.eye(n_dim, n_dim)\n ) # 避免除零错误\n\n self.Tau = np.ones((n_dim, n_dim)) # 信息素矩阵,每次迭代都会更新\n self.Table = np.zeros((size_pop, n_dim)).astype(np.int) # 某一代每个蚂蚁的爬行路径\n self.y = None # 某一代每个蚂蚁的爬行总距离\n self.generation_best_X, self.generation_best_Y = [], [] # 记录各代的最佳情况\n self.x_best_history, self.y_best_history = (\n self.generation_best_X,\n self.generation_best_Y,\n ) # 历史原因,为了保持统一\n self.best_x, self.best_y = None, None\n\n def run(self):\n for i in range(self.max_iter): # 对每次迭代\n prob_matrix = (self.Tau ** self.alpha) * (\n self.prob_matrix_distance\n ) ** self.beta # 转移概率,无须归一化。\n for j in range(self.size_pop): # 对每个蚂蚁\n self.Table[j, 0] = 0 # start point,其实可以随机,但没什么区别\n for k in range(self.n_dim - 1): # 蚂蚁到达的每个节点\n taboo_set = set(self.Table[j, : k + 1]) # 已经经过的点和当前点,不能再次经过\n allow_list = list(set(range(self.n_dim)) - taboo_set) # 在这些点中做选择\n prob = prob_matrix[self.Table[j, k], allow_list]\n prob = prob / prob.sum() # 概率归一化\n # print(prob)\n next_point = np.random.choice(allow_list, size=1, p=prob)[0]\n self.Table[j, k + 1] = next_point\n\n # 计算距离\n y = np.array([self.func(i) for i in self.Table])\n\n # 顺便记录历史最好情况\n index_best = y.argmin()\n x_best, y_best = self.Table[index_best, :].copy(), y[index_best].copy()\n self.generation_best_X.append(x_best)\n self.generation_best_Y.append(y_best)\n\n # 计算需要新涂抹的信息素\n Delta_tau = np.zeros((self.n_dim, self.n_dim))\n for j in range(self.size_pop): # 每个蚂蚁\n for k in range(self.n_dim - 1): # 每个节点\n n1, n2 = self.Table[j, k], self.Table[j, k + 1] # 蚂蚁从n1节点爬到n2节点\n Delta_tau[n1, n2] += 1 / y[j] # 涂抹的信息素\n n1, n2 = (\n self.Table[j, self.n_dim - 1],\n self.Table[j, 0],\n ) # 蚂蚁从最后一个节点爬回到第一个节点\n Delta_tau[n1, n2] += 1 / y[j] # 涂抹信息素\n\n # 信息素挥发+信息素涂抹\n self.Tau = (1 - self.rho) * self.Tau + Delta_tau\n\n best_generation = np.array(self.generation_best_Y).argmin()\n self.best_x = self.generation_best_X[best_generation]\n self.best_y = self.generation_best_Y[best_generation]\n return self.best_x, self.best_y\n\n # fit = run\n\n\nif __name__ == \"__main__\":\n num_points = 101\n\n points_coordinate = np.array( # data set\n [\n [40.00, 50.00],\n [45.00, 68.00],\n [45.00, 70.00],\n [42.00, 66.00],\n [42.00, 68.00],\n [42.00, 65.00],\n [40.00, 69.00],\n [40.00, 66.00],\n [38.00, 68.00],\n [38.00, 70.00],\n [35.00, 66.00],\n [35.00, 69.00],\n [25.00, 85.00],\n [22.00, 75.00],\n [22.00, 85.00],\n [20.00, 80.00],\n [20.00, 85.00],\n [18.00, 75.00],\n [15.00, 75.00],\n [15.00, 80.00],\n [30.00, 50.00],\n [30.00, 52.00],\n [28.00, 52.00],\n [28.00, 55.00],\n [25.00, 50.00],\n [25.00, 52.00],\n [25.00, 55.00],\n [23.00, 52.00],\n [23.00, 55.00],\n [20.00, 50.00],\n [20.00, 55.00],\n [10.00, 35.00],\n [10.00, 40.00],\n [8.00, 40.00],\n [8.00, 45.00],\n [5.00, 35.00],\n [5.00, 45.00],\n [2.00, 40.00],\n [0.00, 40.00],\n [0.00, 45.00],\n [35.00, 30.00],\n [35.00, 32.00],\n [33.00, 32.00],\n [33.00, 35.00],\n [32.00, 30.00],\n [30.00, 30.00],\n [30.00, 32.00],\n [30.00, 35.00],\n [28.00, 30.00],\n [28.00, 35.00],\n [26.00, 32.00],\n [25.00, 30.00],\n [25.00, 35.00],\n [44.00, 5.00],\n [42.00, 10.00],\n [42.00, 15.00],\n [40.00, 5.00],\n [40.00, 15.00],\n [38.00, 5.00],\n [38.00, 15.00],\n [35.00, 5.00],\n [50.00, 30.00],\n [50.00, 35.00],\n [50.00, 40.00],\n [48.00, 30.00],\n [48.00, 40.00],\n [47.00, 35.00],\n [47.00, 40.00],\n [45.00, 30.00],\n [45.00, 35.00],\n [95.00, 30.00],\n [95.00, 35.00],\n [53.00, 30.00],\n [92.00, 30.00],\n [53.00, 35.00],\n [45.00, 65.00],\n [90.00, 35.00],\n [88.00, 30.00],\n [88.00, 35.00],\n [87.00, 30.00],\n [85.00, 25.00],\n [85.00, 35.00],\n [75.00, 55.00],\n [72.00, 55.00],\n [70.00, 58.00],\n [68.00, 60.00],\n [66.00, 55.00],\n [65.00, 55.00],\n [65.00, 60.00],\n [63.00, 58.00],\n [60.00, 55.00],\n [60.00, 60.00],\n [67.00, 85.00],\n [65.00, 85.00],\n [65.00, 82.00],\n [62.00, 80.00],\n [60.00, 80.00],\n [60.00, 85.00],\n [58.00, 75.00],\n [55.00, 80.00],\n [55.00, 85.00],\n ]\n )\n\n # points_coordinate = np.random.rand(num_points, 2) # generate coordinate of points\n # print(points_coordinate.shape)\n\n distance_matrix = spatial.distance.cdist( # 计算两个点集合中两两点之间的距离\n points_coordinate, points_coordinate, metric=\"euclidean\"\n )\n\n # print(distance_matrix)\n\n def cal_total_distance(routine):\n (num_points,) = routine.shape\n return sum(\n [\n distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]]\n for i in range(num_points)\n ]\n )\n\n aco = ACO(\n func=cal_total_distance,\n n_dim=num_points,\n size_pop=50,\n max_iter=300,\n alpha=1,\n beta=2,\n rho=0.1,\n distance_matrix=distance_matrix,\n )\n\n best_x, best_y = aco.run()\n print(best_x)\n print(best_y)\n\n fig, ax = plt.subplots(1)\n best_points_ = np.concatenate([best_x, [best_x[0]]])\n best_points_coordinate = points_coordinate[best_points_, :]\n ax.plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], \"o-r\")\n # pandas.DataFrame(aco.y_best_history).cummin().plot(ax=ax[1])\n plt.show()","sub_path":"opt/ACO.py","file_name":"ACO.py","file_ext":"py","file_size_in_byte":7874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"379826854","text":"#!/usr/bin/python3\n\ninputFile = open('../data/aoristicValues.csv', 'r')\n\n# header\ninputFile.readline()\n\nvalues = list()\n\n# 98 values, from 5500 to 600 in 50-year intervals \nnumValues = int((5500-550)/50)\nfor i in range(numValues):\n values.append(0.0)\n\nfor line in inputFile:\n splitLine = line.strip().split(';')\n initialValue = 4\n i = initialValue\n while i ' ,values[i])\noutputFile.close()\n\n","sub_path":"03_spatiotemporal/sumValues.py","file_name":"sumValues.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"594324881","text":"##cobra.solvers.gurobi_solver\n#Interface to the gurobi 5.0.1 python solver\n\nfrom warnings import warn\nfrom os import name as __name\nfrom copy import deepcopy\nfrom itertools import izip\n###solver specific parameters\nfrom .parameters import status_dict, variable_kind_dict, \\\n sense_dict, parameter_mappings, parameter_defaults, \\\n objective_senses, default_objective_sense\n\nfrom ..core.Solution import Solution\nfrom time import time\nsolver_name = 'gurobi'\nobjective_senses = objective_senses[solver_name]\nparameter_mappings = parameter_mappings[solver_name]\nparameter_defaults = parameter_defaults[solver_name]\n\n## from numpy import array\nfrom gurobipy import Model, LinExpr, GRB, QuadExpr\nvariable_kind_dict = eval(variable_kind_dict[solver_name])\nstatus_dict = eval(status_dict[solver_name])\n__solver_class = Model\ndef get_status(lp):\n status = lp.status\n if status in status_dict:\n status = status_dict[status]\n else:\n status = 'failed'\n return status\n\ndef get_objective_value(lp):\n return lp.ObjVal\n\ndef format_solution(lp, cobra_model, **kwargs):\n status = get_status(lp)\n if status not in ('optimal', 'time_limit'):\n the_solution = Solution(None, status=status)\n else:\n objective_value = lp.ObjVal\n x = [v.X for v in lp.getVars()] \n x_dict = {r.id: value for r, value in izip(cobra_model.reactions, x)}\n if lp.isMIP:\n y = y_dict = None #MIP's don't have duals\n else:\n y = [c.Pi for c in lp.getConstrs()]\n y_dict = {m.id: value for m, value in izip(cobra_model.metabolites, y)}\n the_solution = Solution(objective_value, x=x, x_dict=x_dict, y=y,\n y_dict=y_dict, status=status)\n return(the_solution)\n\ndef set_parameter(lp, parameter_name, parameter_value):\n if parameter_name == 'ModelSense':\n lp.setAttr(parameter_name, objective_senses[parameter_value])\n else:\n lp.setParam(parameter_name, parameter_value)\n\ndef change_variable_bounds(lp, index, lower_bound, upper_bound):\n variable = lp.getVarByName(str(index))\n variable.lb = lower_bound\n variable.ub = upper_bound\n\n\ndef change_variable_objective(lp, index, objective):\n variable = lp.getVarByName(str(index))\n variable.obj = objective\n\n\ndef change_coefficient(lp, met_index, rxn_index, value):\n met = lp.getConstrByName(str(met_index))\n rxn = lp.getVarByName(str(rxn_index))\n lp.chgCoeff(met, rxn, value)\n\n\ndef update_problem(lp, cobra_model, **kwargs):\n \"\"\"A performance tunable method for updating a model problem file\n\n lp: A gurobi problem object\n\n cobra_model: the cobra.Model corresponding to 'lp'\n\n \"\"\"\n #When reusing the basis only assume that the objective coefficients or bounds can change\n try:\n quadratic_component = kwargs['quadratic_component']\n if quadratic_component is not None:\n warn(\"update_problem does not yet take quadratic_component as a parameter\")\n except:\n quadratic_component = None\n\n if 'copy_problem' in kwargs and kwargs['copy_problem']:\n lp = lp.copy()\n if 'reuse_basis' in kwargs and not kwargs['reuse_basis']:\n lp.reset()\n for the_variable, the_reaction in zip(lp.getVars(),\n cobra_model.reactions):\n the_variable.lb = float(the_reaction.lower_bound)\n the_variable.ub = float(the_reaction.upper_bound)\n the_variable.obj = float(the_reaction.objective_coefficient)\n\n\nsense_dict = eval(sense_dict[solver_name])\ndef create_problem(cobra_model, quadratic_component=None, **kwargs):\n \"\"\"Solver-specific method for constructing a solver problem from\n a cobra.Model. This can be tuned for performance using kwargs\n\n\n \"\"\"\n lp = Model(\"\")\n #Silence the solver\n set_parameter(lp, 'OutputFlag', 0)\n\n the_parameters = parameter_defaults\n if kwargs:\n the_parameters = deepcopy(parameter_defaults)\n the_parameters.update(kwargs)\n\n [set_parameter(lp, parameter_mappings[k], v)\n for k, v in the_parameters.iteritems() if k in parameter_mappings]\n\n\n # Create variables\n #TODO: Speed this up\n variable_list = [lp.addVar(float(x.lower_bound),\n float(x.upper_bound),\n float(x.objective_coefficient),\n variable_kind_dict[x.variable_kind],\n str(i))\n for i, x in enumerate(cobra_model.reactions)]\n reaction_to_variable = dict(zip(cobra_model.reactions,\n variable_list))\n # Integrate new variables\n lp.update()\n\n #Constraints are based on mass balance\n #Construct the lin expression lists and then add\n #TODO: Speed this up as it takes about .18 seconds\n #HERE\n for i, the_metabolite in enumerate(cobra_model.metabolites):\n constraint_coefficients = []\n constraint_variables = []\n for the_reaction in the_metabolite._reaction:\n constraint_coefficients.append(the_reaction._metabolites[the_metabolite])\n constraint_variables.append(reaction_to_variable[the_reaction])\n #Add the metabolite to the problem\n lp.addConstr(LinExpr(constraint_coefficients, constraint_variables),\n sense_dict[the_metabolite._constraint_sense.upper()],\n the_metabolite._bound,\n str(i))\n\n # Set objective to quadratic program\n if quadratic_component is not None:\n set_quadratic_objective(lp, quadratic_component)\n\n lp.update()\n return(lp)\n\n\ndef set_quadratic_objective(lp, quadratic_objective):\n if not hasattr(quadratic_objective, 'todok'):\n raise Exception('quadratic component must have method todok')\n variable_list = lp.getVars()\n linear_objective = lp.getObjective()\n # If there already was a quadratic expression set, this will be quadratic\n # and we need to extract the linear component\n if hasattr(linear_objective, \"getLinExpr\"): # duck typing\n linear_objective = linear_objective.getLinExpr()\n gur_quadratic_objective = QuadExpr()\n for (index_0, index_1), the_value in quadratic_objective.todok().items():\n # gurobi does not multiply by 1/2 (only does v^T Q v)\n gur_quadratic_objective.addTerms(the_value * 0.5,\n variable_list[index_0],\n variable_list[index_1])\n # this adds to the existing quadratic objectives\n lp.setObjective(gur_quadratic_objective + linear_objective)\n\ndef solve_problem(lp, **kwargs):\n \"\"\"A performance tunable method for updating a model problem file\n\n \"\"\"\n #Update parameter settings if provided\n if kwargs:\n [set_parameter(lp, parameter_mappings[k], v)\n for k, v in kwargs.iteritems() if k in parameter_mappings]\n\n lp.update()\n lp.optimize()\n status = get_status(lp)\n return status\n\n \ndef solve(cobra_model, **kwargs):\n \"\"\"\n\n \"\"\"\n #Start out with default parameters and then modify if\n #new onese are provided\n the_parameters = deepcopy(parameter_defaults)\n if kwargs:\n the_parameters.update(kwargs)\n for i in [\"new_objective\", \"update_problem\", \"the_problem\"]:\n if i in the_parameters:\n raise Exception(\"Option %s removed\" % i)\n if 'error_reporting' in the_parameters:\n warn(\"error_reporting deprecated\")\n\n #Create a new problem\n lp = create_problem(cobra_model, **the_parameters)\n\n\n ###Try to solve the problem using other methods if the first method doesn't work\n try:\n lp_method = the_parameters['lp_method']\n except:\n lp_method = 0\n the_methods = [0, 2, 1]\n if lp_method in the_methods:\n the_methods.remove(lp_method)\n #Start with the user specified method\n the_methods.insert(0, lp_method)\n for the_method in the_methods:\n the_parameters['lp_method'] = the_method\n try:\n status = solve_problem(lp, **the_parameters)\n except:\n status = 'failed'\n if status == 'optimal':\n break\n\n the_solution = format_solution(lp, cobra_model)\n #if status != 'optimal':\n # print '%s failed: %s'%(solver_name, status)\n #cobra_model.solution = the_solution\n #solution = {'the_problem': lp, 'the_solution': the_solution}\n return the_solution\n","sub_path":"bin/python/usr/lib/python2.7/site-packages/cobra/solvers/gurobi_solver.py","file_name":"gurobi_solver.py","file_ext":"py","file_size_in_byte":8418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"129229809","text":"# define a function to count to 3\ndef count_to_three():\n \n # Set number at 1\n count = 1\n\n # start loop, print each number in range\n while count < 4:\n for count in range(1, 4):\n print(count)\n count = count + 1\n\n# call function\ncount_to_three()\nprint()\n\n###############################\n\ndef greater_than_ten(integers):\n \"\"\"Function to find integers greater than 10\"\"\"\n\n big_int = []\n\n for num in integers:\n if num > 10:\n big_int.append(num)\n \n return big_int\n\nintegers = [1, 5, 23, 89, 11, 84, 5]\n\nbig_integers = greater_than_ten(integers)\nprint(big_integers)\nprint()\n\n################################\n\ndef make_sentence(person, place):\n \"\"\"Function returns sentence, like a mad lib, using arguments\"\"\"\n\n return \"Today I saw {} doing cartwheels in {}.\".format(person, place)\n\n# saves return value as variable sentence\nsentence = make_sentence(\"Captain Kirk\", \"Paris\")\nprint(sentence)\nprint()\n\n###################################\n\ndef find_words_in_common(list1, list2):\n \"\"\"Takes in 2 lists of words, returns new list of words in both lists\"\"\"\n\n both_list = []\n\n # evaluates each item in list1, checks to see if it's \n # in list 2. If in list 2, adds to new list\n for word in list1:\n if word in list2:\n both_list.append(word)\n \n return both_list\n\n# 2 lists of words\nhello_list = [\"hello\", \"aloha\", \"hola\", \"bonjour\", \"ahlan\"]\n\ngoodbye_list = [\"goodbye\", \"aloha\", \"adios\", \"adieu\", \"ma' salama\"]\n\n# call function, and print return value\nnew_list = find_words_in_common(hello_list, goodbye_list)\nprint(new_list)\nprint()\n\n######################################\n\ndef sum_unique_nums(nums_list):\n \"\"\"Finds unique integers in list, adds them together\"\"\"\n\n # blank list for populating with unique numbers\n unique_nums = []\n\n # evaluate each item in list. if not in new list \n # already, add it\n for num in nums_list:\n if num not in unique_nums:\n unique_nums.append(num)\n \n # adds together numbers in new list\n total = sum(unique_nums)\n\n return total\n\n# list of numbers to evaluate\nmy_nums = [4, 8, 4, 2, 15, 9, 1, 11, 8]\n\n# call function and save return\nsum_all = sum_unique_nums(my_nums)\nprint(sum_all)\nprint()\n\n#####################################\n\ndef select_evenly_divisible_integers(num1, num2, num3):\n \"\"\"Function to return list of integers that are evenly divisible by at least one number in arguments\"\"\"\n\n # blank list to be populated with evenly divisible \n # integers\n evenly_divided_nums = []\n\n # evaluates each integer in range 1 - 100 inclusive, # dividing each one in turn by each of the three\n # integers in arguments\n for num in range(1, 101): \n if num % num1 == 0 or num % num2 == 0 or num % num3 == 0:\n evenly_divided_nums.append(num)\n \n # returns new list of evenly divisible numbers\n return evenly_divided_nums\n\n# save return value as variable and print return\nnew_nums = select_evenly_divisible_integers(10, 12, 25)\nprint(new_nums)\nprint()\n","sub_path":"python/hb/coding_hw_3.py","file_name":"coding_hw_3.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"269582115","text":"# Auteurs: Thierry Blais et Bernard Sévigny\n\nfrom tkinter import * # Tk, Label, NSEW, dnd\nfrom canvas_damier import CanvasDamier\nfrom partie import Partie\nfrom position import Position\n# import interface_multi\nfrom datetime import date\n# from un_joueur import Un_joueur\nimport os\nfrom pickle import dump, load\n\nclass FenetrePartie(Tk):\n \"\"\"Interface graphique de la partie de dames.\n\n Attributes:\n partie (Partie): Le gestionnaire de la partie de dame\n canvas_damier (CanvasDamier): Le «widget» gérant l'affichage du damier à l'écran\n messages (Label): Un «widget» affichant des messages textes à l'utilisateur du programme\n\n TODO: AJOUTER VOS PROPRES ATTRIBUTS ICI!\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructeur de la classe FenetrePartie. On initialise une partie en utilisant la classe Partie du TP3 et\n on dispose les «widgets» dans la fenêtre.\n \"\"\"\n\n # Appel du constructeur de la classe de base (Tk)\n super().__init__()\n\n # La partie\n self.partie = Partie()\n\n # Création du canvas damier.\n self.canvas_damier = CanvasDamier(self, self.partie.damier, 60)\n self.canvas_damier.grid(sticky=NSEW)\n self.canvas_damier.bind('', self.selectionner)\n # self.canvas_damier.bind('', self.enregistrer_position_cible)\n\n # Ajout d'une étiquette d'information.\n self.messages1 = Label(self)\n self.messages1.grid()\n self.messages1['foreground'] = 'blue'\n self.messages1['text'] = 'Quelle pièce désirez-vous déplacer?'\n self.colonne_damier_reel = \"abcdefgh\"\n\n # Ajout des boutons : A permettant d'obtenir l'aide et B de quitter et d'enregistrer.\n self.bouton1_A = Button(self, text = 'Aide', command = self.aide,)\n self.bouton1_B = Button(self, text = 'Quitter', command = self.quitter_damier)\n self.bouton1_C = Button(self, text='Partie sauvegardée', command=self.partie_sauvegardee)\n self.bouton1_D = Button(self, text=\"Jouer contre l'ordinateur\", command=self.jouer_contre_ordinateur)\n self.bouton1_A.grid(row=2, column=0, pady=5)\n self.bouton1_B.grid(row=1, column=1, padx=25, pady=5) # , sticky=E)\n self.bouton1_C.grid(row=2, column=1, pady=5, sticky=E)\n self.bouton1_D.grid(row=2, column=0, pady=5)\n\n # Liste des mouvements\n self.messages1_B = Label(self)\n self.messages1_B.grid(row=0, column=1, sticky=N)\n self.messages1_B['foreground'] = 'black'\n self.messages1_B['text'] = \"Blanc Noir\\n───────\\n\"\n self.numero_deplacement = 1\n\n # Initialisation des attributs\n self.doit_prendre = False\n self.position_source_selectionnee = None\n self.position_source_forcee = None\n\n # Nom de la fenêtre («title» est une méthode de la classe de base «Tk»)\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue!\"\n self.title(\"Jeu de dames. Le joueur \" + self.titre_joueur)\n\n # Truc pour le redimensionnement automatique des éléments de la fenêtre.\n self.grid_columnconfigure(0, weight=1)\n self.grid_rowconfigure(0, weight=1)\n\n def selectionner(self, event):\n \"\"\"Méthode qui gère le clic de souris sur le damier. La méthode appelle les méthodes vérifiant la validité\n des sélections source et cible.\n Tant qu'une cible valide n'est pas sélectionnée, la position source peut être modifiée.\n\n Args:\n event (tkinter.Event): Objet décrivant l'évènement qui a causé l'appel de la méthode.\n\n \"\"\"\n try: # Permet d'affecter le premier clic à la position source et le second à la cible.\n if self.flg == 0: # Génère l'erreur qui affecte le premier clic.\n ligne = event.y // self.canvas_damier.n_pixels_par_case\n colonne = event.x // self.canvas_damier.n_pixels_par_case # On trouve le numéro de ligne/colonne en\n # divisant les positions en y/x par le nombre de pixels par case.\n self.position_cible = Position(ligne, colonne)\n\n self.messages1['foreground'] = 'black'\n position_source_damier_reel =self.colonne_damier_reel[self.position.colonne]\\\n + str(8 - self.position.ligne)\n position_cible_damier_reel = self.colonne_damier_reel[self.position_cible.colonne]\\\n + str(8 - self.position_cible.ligne)\n self.messages1['text'] = 'Pièce à la position {} déplacée à {}.'\\\n .format(position_source_damier_reel, position_cible_damier_reel)\n\n if not self.valider_et_enregistrer_position_cible()[0]:\n self.messages1['foreground'] = 'red'\n self.messages1['text'] = self.valider_et_enregistrer_position_cible()[1]\n raise ValueError\n\n retour_apres_deplacement = self.partie.damier.deplacer(self.position, self.position_cible)\n # ok, prise ou erreur\n if self.partie.couleur_joueur_courant == \"blanc\":\n self.messages1_B['text'] = self.messages1_B['text'] + str(self.numero_deplacement) + \"- \" + str(position_source_damier_reel) + \" \" + str(position_cible_damier_reel) + \" \"\n self.numero_deplacement += 1\n #if retour_apres_deplacement == \"prise\":\n # self.messages1_B['text'] = self.messages1_B['text'] + \"\\n\"\n else:\n #if retour_apres_deplacement == \"prise\":\n # self.messages1_B['text'] = self.messages1_B['text'] + \" \"\n self.messages1_B['text'] = self.messages1_B['text'] + str(position_source_damier_reel) + \" \" + str(position_cible_damier_reel) + \"\\n\"\n\n if retour_apres_deplacement == \"ok\":\n pass\n elif retour_apres_deplacement == \"prise\":\n if self.partie.damier.piece_peut_faire_une_prise(self.position_cible):\n\n self.position_source_forcee = self.position_cible\n self.doit_prendre = True\n\n if self.partie.couleur_joueur_courant == 'noir':\n self.messages1_B['text'] = self.messages1_B['text'] + \" \"\n else:\n self.messages1_B['text'] = self.messages1_B['text'] + \" \\n\"\n\n else:\n self.doit_prendre = False\n self.position_source_selectionnee = None\n self.position_source_forcee = None\n else:\n self.messages1['foreground'] = 'red'\n self.messages1['text'] = \"Il y a erreur dans le code!\"\n\n if self.doit_prendre == False:\n if self.partie.couleur_joueur_courant == \"blanc\":\n self.partie.couleur_joueur_courant = \"noir\"\n else:\n self.partie.couleur_joueur_courant = \"blanc\"\n\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue!\"\n self.title(\"Jeu de dames. Le joueur \" + self.titre_joueur)\n else:\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue et doit faire une prise!\"\n self.title(\"Jeu de dames. Le joueur \" + self.titre_joueur)\n\n del self.flg # Libère le drapeau pour le tour suivant\n\n except: # Permet de valider la position source et déterminer si une prise doit être faite.\n ligne = event.y // self.canvas_damier.n_pixels_par_case\n colonne = event.x // self.canvas_damier.n_pixels_par_case\n self.position = Position(ligne, colonne)\n position_source_damier_reel = self.colonne_damier_reel[self.position.colonne] + str(8 - self.position.ligne)\n if self.valider_prise_obligee()[0]:\n self.title(\"Jeu de dames. Le joueur \" + self.valider_prise_obligee()[1])\n if self.partie.damier.piece_peut_faire_une_prise(self.position):\n self.messages1['foreground'] = 'black'\n self.messages1['text'] = 'La pièce sélectionnée en position ' \\\n + position_source_damier_reel + ' peut faire une prise.'\n\n else:\n self.messages1['foreground'] = 'red'\n self.messages1['text'] = 'Sélectionnez une pièce qui peut faire une prise.'\n\n else:\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue!\"\n self.title(\"Jeu de dames. Le joueur \" + self.titre_joueur)\n\n if self.partie.position_source_valide(self.position)[0]:\n if self.valider_et_enregistrer_position_source()[0]:\n self.messages1['foreground'] = 'black'\n self.messages1['text'] = self.valider_et_enregistrer_position_source()[1]\n self.flg = 0 # Valide la position source et autorise la sélection de la cible\n else:\n self.messages1['foreground'] = 'red'\n self.messages1['text'] = self.valider_et_enregistrer_position_source()[1]\n\n else:\n self.messages1['foreground'] = 'red'\n self.messages1['text'] = self.partie.position_source_valide(self.position)[1]\n\n self.canvas_damier.actualiser()\n\n # Fin de partie\n if self.partie.damier.piece_de_couleur_peut_se_deplacer(self.partie.couleur_joueur_courant) or \\\n self.partie.damier.piece_de_couleur_peut_faire_une_prise(self.partie.couleur_joueur_courant):\n pass\n else:\n self.title(\"Jeu de dames. La partie est terminée!\")\n self.messages1['foreground'] = 'orange'\n if self.partie.couleur_joueur_courant == \"blanc\":\n self.partie.couleur_joueur_courant = \"noir\"\n else:\n self.partie.couleur_joueur_courant = \"blanc\"\n self.messages1['text'] = \"Le joueur \" + self.partie.couleur_joueur_courant + \" a gagné!\"\n\n def valider_prise_obligee(self):\n \"\"\"\n Détermine si le joueur actif doit ou non faire une prise. Rend la prise obligatoire dans le choix\n de la position source.\n return:\n [0] : True ou False\n [1] : Message à afficher si le joueur doit faire une prise.\n \"\"\"\n if self.partie.damier.piece_de_couleur_peut_faire_une_prise(self.partie.couleur_joueur_courant):\n self.doit_prendre = True\n if self.position_source_forcee is None: # C'est une première prise\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue et doit faire une prise!\"\n\n else: # Indique une prise successive\n position_source_damier_reel = self.colonne_damier_reel[self.position_source_forcee.colonne] + str(\n 8 - self.position_source_forcee.ligne)\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue. La pièce en position \"\\\n + position_source_damier_reel + \" doit faire une prise!\"\n return [True, self.titre_joueur]\n\n else:\n return [False, \"\"]\n\n def valider_et_enregistrer_position_source(self):\n \"\"\"\n S'assure que la position source doit faire une prise, si c'est le cas, sinon que la pièce choisie est de la\n couleur du joueur et qu'elle peut se déplacer.\n\n return:\n [0] : True ou False\n [1] : Message à afficher si la source n'est pas valide.\n \"\"\"\n position_source_damier_reel = self.colonne_damier_reel[self.position.colonne] + str(8 - self.position.ligne)\n if self.doit_prendre == True:\n if self.position_source_forcee is None:\n texte_messages1 = \"Vous devez prendre. Assurez-vous que la pièce sélectionnée, en position \" \\\n + position_source_damier_reel + \" peut prendre.\"\n return [True, texte_messages1]\n else:\n if self.position_source_forcee == self.position:\n self.messages1['foreground'] = 'red'\n texte_messages1 = \"Vous devez prendre à nouveau. La pièce en position \"\\\n + position_source_damier_reel + \" a été sélectionnée.\"\n return [True, texte_messages1]\n else:\n texte_messages1 = \"Vous devez prendre à nouveau. La pièce choisie ne peut pas être sélectionnée.\"\n return [False, texte_messages1]\n elif self.partie.damier.piece_peut_se_deplacer(self.position):\n self.messages1['foreground'] = 'black'\n texte_messages1 = 'La pièce en position ' + position_source_damier_reel \\\n + ' a été sélectionnée. Cliquez sur la cible désirée. '\n return [True, texte_messages1]\n else:\n texte_messages1 = \"La pièce que vous avez sélectionnée ne peut pas se déplacer. Veuillez \" \\\n \"faire un autre choix. \"\n return [False, texte_messages1]\n\n def valider_et_enregistrer_position_cible(self):\n \"\"\"\n S'assure que la pièce choisie comme position source peut se déplacer à la position cible, soit en faisant\n une prise ou en se déplaçant.\n\n return:\n [0] : True ou False\n [1] : Message à afficher si la cible n'est pas valide.\n \"\"\"\n if self.doit_prendre == True:\n if self.partie.damier.piece_peut_sauter_vers(self.position, self.position_cible,\n self.partie.couleur_joueur_courant):\n return [True, \"\"]\n\n else:\n texte_messages1 = \"La pièce choisie doit prendre une pièce adverse. La cible choisie doit être modifiée.\"\n return [False, texte_messages1]\n\n elif self.partie.damier.piece_peut_se_deplacer_vers(self.position, self.position_cible):\n return [True, \"\"]\n else:\n texte_messages1 = \"La pièce choisie ne peut pas être déplacée vers cette case.\"\n return [False, texte_messages1]\n\n def aide(self):\n \"\"\"\n Fait apparaître une fenêtre contextuelle présentant, sous la forme d'un texte, l'aide à l'utilisation\n du programme damier ainsi que les règlements applicables.\n Le bouton \"Quitter\" permet de fermer la fenêtre et de retourner au damier.\n \"\"\"\n self.fenetre_2 = Tk()\n self.fenetre_2.title(\"Aide et règlements\")\n\n texte_aide0 = Message(self.fenetre_2)\n texte_aide0['foreground'] = 'brown'\n\n texte_aide1 = Message(self.fenetre_2, width=492)\n texte_aide1['foreground'] = 'blue'\n\n texte_aide2 = Message(self.fenetre_2)\n texte_aide2['foreground'] = 'brown'\n\n texte_aide3 = Message(self.fenetre_2)\n texte_aide3['foreground'] = 'blue'\n\n Extrait_aide = open(\"Aide_reglements.txt\", 'r', encoding=\"utf-8\")\n texte_extrait = Extrait_aide.readlines()\n texte_aide0['text'] = texte_extrait[0]\n texte_aide1['text'] = texte_extrait[1]\n for i in range(2, 5):\n texte_aide1['text'] = texte_aide1['text'] + texte_extrait[i]\n\n texte_aide2['text'] = texte_extrait[5]\n texte_aide3['text'] = texte_extrait[6]\n for i in range(7, len(texte_extrait)):\n texte_aide3['text'] = texte_aide3['text'] + texte_extrait[i]\n Extrait_aide.close()\n texte_aide0.grid()\n texte_aide1.grid(sticky=W)\n texte_aide2.grid()\n texte_aide3.grid(sticky=W)\n bouton2_A = Button(self.fenetre_2, text='Quitter', command=self.fenetre_aide_quit)\n bouton2_A.grid()\n self.fenetre_2.tkraise() # mainloop()\n\n def fenetre_aide_quit(self):\n \"\"\"\n Méthode appelée par le bouton \"Quitter\" de la fenêtre \"Aide et règlements\".\n Permet de fermer la fenêtre en permettant aux joueurs de retourner au jeu déjà commencé.\n \"\"\"\n self.fenetre_2.withdraw()\n\n def quitter_damier(self):\n \"\"\"\n Méthode appelée par le bouton \"Quitter\" de la fenêtre principale du damier.\n Permet\n 1. de fermer la fenêtre avec ou sans sauvegarde de la partie en cours;\n 2.aux joueurs de retourner au jeu déjà commencé;\n 3. d'ouvrir une nouvelle partie sans fermer la partie en cours.\n Boutons activés :\n A. Quitter et sauvegarder\n B. Quitter sans sauvegarder\n C. Nouvelle partie\n D. Annuler et revenir à la partie\n \"\"\"\n self.fenetre_3 = Tk()\n self.fenetre_3.geometry(\"460x230\")\n self.fenetre_3.title(\"Pourquoi quitter?\")\n\n # texte_3_A = Message(self.fenetre_3)\n texte_3_A = Label(self.fenetre_3)\n texte_3_B = Label(self.fenetre_3)\n texte_3_C = Label(self.fenetre_3)\n texte_3_D = Label(self.fenetre_3)\n texte_3_A['text'] = \"1- Si vous ouvrez une nouvelle partie, la partie non terminée que vous venez de quitter\"\n texte_3_B['text'] = \"sera encore accessible et il sera possible de jouer deux parties à la fois!\\n \"\n texte_3_C['text'] = \"2- En annulant, vous retournez à la partie déjà ouverte.\\n \"\n texte_3_D['text'] = \"3- Si vous quittez sans sauvegarder, toutes les parties seront fermées.\"\n texte_3_A.grid(sticky=W)\n texte_3_B.grid(sticky=W)\n texte_3_C.grid(sticky=W)\n texte_3_D.grid(sticky=W)\n bouton3_A = Button(self.fenetre_3, text='Quitter et sauvegarder', command=self.sauvegarde_partie)\n bouton3_B = Button(self.fenetre_3, text='Quitter sans sauvegarder', command=self.quit)\n bouton3_C = Button(self.fenetre_3, text='Nouvelle partie', command=self.nouvelle_partie)\n bouton3_D = Button(self.fenetre_3, text='Annuler', command=self.fenetre_quit_annulee)\n bouton3_A.grid(row=4, column=0, pady=10, sticky=W)\n bouton3_B.grid(row=4, column=0, pady=10, sticky=E)\n bouton3_C.grid(row=5, column=0, sticky=W)\n bouton3_D.grid(row=5, column=0, sticky=E)\n self.fenetre_3.tkraise()\n\n def sauvegarde_partie(self):\n \"\"\"\n Méthode appelée par le bouton \"Quitter et sauvegarder\" de la fenêtre \"Quitter\".\n Permet de sauvegarder la partie au point où elle était rendue.\n \"\"\"\n self.fenetre_4 = Tk()\n self.fenetre_4.geometry(\"500x130\")\n self.fenetre_4.title(\"Fichier de sauvegarde\")\n # Sauvegarde de plusieurs parties à la même date\n # Le nom des fichiers contient la date de la sauvegarde\n n_fich = 1\n while os.path.isfile(\"Sauvegarde-\" + str(date.today()) + \"(\" + str(n_fich) + \").txt\"):\n n_fich += 1\n nom_fichier_sauvegarde = \"Sauvegarde-\" + str(date.today()) + \"(\" + str(n_fich) + \").txt\"\n\n fichier_partie = open(nom_fichier_sauvegarde, \"wb\")\n dump([self.partie.couleur_joueur_courant, self.partie.damier.cases], fichier_partie)\n\n fichier_partie.close()\n\n texte_4_A = Label(self.fenetre_4)\n texte_4_B = Label(self.fenetre_4)\n texte_4_C = Label(self.fenetre_4)\n texte_4_D = Label(self.fenetre_4)\n texte_4_A['foreground'] = 'blue'\n texte_4_B['foreground'] = 'green'\n texte_4_C['foreground'] = 'blue'\n texte_4_A['text'] = \"La partie que vous quittez a été sauvegardée dans le fichier : \"\n texte_4_B['text'] = nom_fichier_sauvegarde # + \"!\"\n texte_4_C['text'] = \"!\"\n texte_4_A.grid(row=0, column=0)\n texte_4_B.grid(row=0, column=1)\n texte_4_C.grid(row=0, column=2)\n texte_4_D.grid(row=1, column=0)\n bouton4_A = Button(self.fenetre_4, text='Quitter le jeu', command=self.quit)\n bouton4_B = Button(self.fenetre_4, text='Retour au jeu', command=self.retour_jeu)\n bouton4_A.grid(row=2, column=0, sticky=SW)\n bouton4_B.grid(row=2, column=0, sticky=SE)\n self.fenetre_4.tkraise()\n\n def nouvelle_partie(self):\n \"\"\"\n Méthode appelée par le bouton \"Nouvelle partie\" de la fenêtre \"Quitter\".\n Ouvre une autre fenêtre de jeu sans fermer le damier déjà commencé,\n permettant aux joueurs de jouer plusieurs parties simultanées.\n \"\"\"\n self.fenetre_3.withdraw()\n fenetre = FenetrePartie()\n fenetre.mainloop()\n\n def partie_sauvegardee(self):\n #TODO À compléter\n \"\"\"\n Méthode appelée par le bouton \"Partie sauvegardée\" de la fenêtre principale.\n Permet d'ouvrir une partie non complétée au point où elle avait été arrêtée.\n \"\"\"\n self.fenetre_5 = Tk()\n self.fenetre_5.geometry(\"400x230\") # Ajuster\n self.fenetre_5.title(\"Fichiers sauvegardés\")\n\n texte_5_A = Label(self.fenetre_5)\n bouton5_A = Button(self.fenetre_5, text='Annuler', command=self.ouverture_fich_annulee)\n\n self.liste_fich = Listbox(self.fenetre_5, width=27, height=10, selectmode=SINGLE)\n fich_insere = 0\n for nom_fich in os.listdir():\n if nom_fich[0:10] == \"Sauvegarde\":\n self.liste_fich.insert(END, nom_fich)\n fich_insere +=1\n if fich_insere != 0:\n texte_5_A['foreground'] = 'purple'\n texte_5_A['text'] = \"Liste des fichiers de sauvegarde dans le répertoire du projet :\"\n self.liste_fich.grid(row=2, column=0)\n self.liste_fich.bind('', lambda event : self.ouvrir_sauvegarde())\n\n else:\n texte_5_A['foreground'] = 'red'\n texte_5_A['text'] = \"Il n'y a pas de fichiers de sauvegarde dans le répertoire du projet.\"\n texte_5_A.grid(row=0, column=0) # Ajuster\n bouton5_A.grid(row=2, column=1, sticky=N)\n self.fenetre_5.tkraise()\n\n def ouvrir_sauvegarde(self):\n self.index_fich_select = self.liste_fich.curselection()[0]\n\n nom_fichier = open(self.liste_fich.get(self.index_fich_select), \"rb\")\n list_dic = load(nom_fichier)\n self.partie.couleur_joueur_courant = list_dic[0]\n self.partie.damier.cases = list_dic[1]\n # self.damier_ouvert = literal_eval(damier_cases)\n nom_fichier.close()\n self.fenetre_5.withdraw()\n self.titre_joueur = self.partie.couleur_joueur_courant + \" joue!\"\n self.title(\"Jeu de dames. Le joueur \" + self.titre_joueur)\n self.canvas_damier.actualiser()\n self.mainloop()\n\n def fenetre_quit_annulee(self):\n \"\"\"\n Méthode appelée par le bouton \"Annuler\" de la fenêtre \"Quitter\".\n Permet de fermer la fenêtre en permettant aux joueurs de retourner au jeu déjà commencé.\n \"\"\"\n self.fenetre_3.withdraw()\n\n def retour_jeu(self):\n \"\"\"\n Méthode appelée par le bouton \"Retour au jeu\" de la fenêtre \"Quitter et sauvegarder\".\n Ferme la fenêtre confirmant le nom du fichier de sauvegarde sans fermer ni le damier déjà commencé\n ni la fenêtre contextuelle, permettant aux joueurs de retourner à la partie en cours.\n \"\"\"\n self.fenetre_3.withdraw()\n self.fenetre_4.withdraw()\n\n def jouer_contre_ordinateur(self):\n#TODO Bouton B == Radiobutton\n \"\"\"\n Méthode appelée par le bouton \"Jouer contre l'ordinateur\" de la fenêtre principale du damier.\n Permet\n 1. de jouer contre l'ordinateur;\n 2. de choisir la couleur du joueur;\n 3. de laisser l,ordinateur jouer contre lui-même.\n Boutons activés :\n A. Jouer contre l'ordinateur\n B. Quitter sans sauvegarder\n C. Nouvelle partie\n D. Annuler et revenir à la partie\n \"\"\"\n self.fenetre_6 = Tk()\n self.fenetre_6.geometry(\"460x230\")\n self.fenetre_6.title(\"Jouer contre l'ordinateur!\")\n\n texte_6_A = Label(self.fenetre_6)\n texte_6_B = Label(self.fenetre_6)\n texte_6_C = Label(self.fenetre_6)\n texte_6_D = Label(self.fenetre_6)\n texte_6_A['text'] = \"1- Si vous jouez contre l'ordinateur, vous pouvez choisir la couleur que vous désirez\"\n texte_6_B['text'] = \"ou laisser l'ordinateur choisir aléatoirement.\\n \"\n texte_6_C['text'] = \"2- .\\n \"\n texte_6_D['text'] = \"3- \"\n texte_6_A.grid(sticky=W)\n texte_6_B.grid(sticky=W)\n texte_6_C.grid(sticky=W)\n texte_6_D.grid(sticky=W)\n # bouton6_A = Button(self.fenetre_6, text=\"Joueur contre l'ordinateur\", command=self.ouverture_un_joueur) # ??\n bouton6_B = Button(self.fenetre_6, text='Choix de la couleur', command=self.quit) # ??\n bouton6_C = Button(self.fenetre_6, text='Joue contre lui-même', command=self.nouvelle_partie) # ??\n bouton6_D = Button(self.fenetre_6, text='Annuler', command=self.fenetre_quit_annulee) # ??\n # bouton6_A.grid(row=4, column=0, pady=10, sticky=W)\n bouton6_B.grid(row=4, column=0, pady=10, sticky=E)\n bouton6_C.grid(row=5, column=0, sticky=W)\n bouton6_D.grid(row=5, column=0, sticky=E)\n self.fenetre_6.tkraise()\n\n def ouverture_un_joueur(self):\n # fenetre.withdraw()\n # interface_multi.joueur_unique(self)\n print(\" i-527 : Houba\")\n\n def ouverture_fich_annulee(self):\n \"\"\"\n Méthode appelée par le bouton \"Annuler\" de la fenêtre \"Quitter\".\n Permet de fermer la fenêtre en permettant aux joueurs de retourner au jeu déjà commencé.\n \"\"\"\n self.fenetre_5.withdraw()\n\nif __name__ == '__main__':\n # Point d'entrée principal du jeu de dame et de l'affichage du damier.\n fenetre = FenetrePartie()\n fenetre.mainloop()\n","sub_path":"interface_dames_backup.py","file_name":"interface_dames_backup.py","file_ext":"py","file_size_in_byte":26205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"455187547","text":"import numpy as np\nfrom oricrete.folding2 import \\\n YoshimuraCreasePattern, CnstrTargetFace, Folding, Initialization, CreasePatternView, \\\n link, fix, r_, s_, t_\n\n\nL_x = 3.0\nL_y = 2.0\nv = 0.2\n\ncp = YoshimuraCreasePattern(L_x=L_x, L_y=L_y, n_x=3, n_y=4)\n\nn_l_h = cp.N_h[0, :].flatten()\nn_r_h = cp.N_h[-1, :].flatten()\nn_lr_h = cp.N_h[(0, -1), :].flatten()\nn_fixed_y = cp.N_h[(0, -1), 2].flatten()\n\ncorner_slides = [([(cp.N_h[0, 0], 0, L_x), (cp.N_h[0, 0], 1, -L_y)], 0),\n ([(cp.N_h[-1, 0], 0, L_x), (cp.N_h[-1, 0], 1, L_y)], 0),\n ([(cp.N_h[-1, -1], 0, L_x), (cp.N_h[-1, -1], 1, -L_y)], 0),\n ([(cp.N_h[0, -1], 0, L_x), (cp.N_h[0, -1], 1, L_y)], 0),\n ([(cp.N_h[2, 0], 2, 1.0), (cp.N_h[2, -1], 2, -1.0)], 0),\n ([(cp.N_h[3, 0], 2, 1.0), (cp.N_h[3, -1], 2, -1.0)], 0),\n ([(cp.N_h[3, 0], 2, 1.0), (cp.N_h[2, 0], 2, -1.0)], 0),\n ([(cp.N_h[0, 2], 2, 1.0), (cp.N_h[-1, 2], 2, -1.0)], 0),\n ]\n\nface_z_t = CnstrTargetFace(\n F=[r_, s_, -0.6 * t_ * (r_ * (1 - r_ / L_x) + s_ * (1 - s_ / L_y))])\ninit = Initialization(cp=cp, tf_lst=[(face_z_t, cp.N)], t_init=0.1)\nfold = Folding(source=init,\n name='fold further',\n goal_function_type='potential_energy',\n n_steps=4,\n MAX_ITER=1000,\n dof_constraints=fix(n_l_h, [0], v) + fix(n_lr_h, [2]) +\n fix(n_fixed_y, [1]) + fix(n_r_h, [0], -v)\n )\nfold.u_t[-1]\n\nfold_further = Folding(source=fold,\n name='fold further',\n goal_function_type='potential_energy',\n n_steps=4,\n MAX_ITER=1000,\n dof_constraints=fix(n_l_h, [0], v) + fix(n_lr_h, [2]) +\n fix(n_fixed_y, [1]) + fix(n_r_h, [0], -v)\n )\nfold_further.u_t[-1]\n\n\nand_fold_further = Folding(source=fold_further,\n name='and fold further',\n goal_function_type='potential_energy',\n n_steps=4,\n MAX_ITER=1000,\n dof_constraints=fix(n_l_h, [0], 0) + fix(n_lr_h, [2]) +\n fix(n_fixed_y, [1]) + fix(n_r_h, [0], 0)\n )\nu_0 = np.zeros_like(fold_further.u_t[-1])\nu_0[12, 0] += 0.2\nand_fold_further.U_0 = u_0.flatten()\n\nand_fold_further.u_t[-1]\n\n\ncpw = CreasePatternView(root=init)\ncpw.configure_traits()\n","sub_path":"apps/sandbox/rch/ycp01_3x4_poteng_rigid.py","file_name":"ycp01_3x4_poteng_rigid.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"557812317","text":"#Whois Scan and Port Scan\r\nimport socket, threading\r\nimport time\r\nimport whois\r\n\r\n\r\ndef connect_tcp(host, port, delay, output):\r\n TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n TCPsock.settimeout(delay)\r\n try:\r\n TCPsock.connect((host, port))\r\n output[port] = 'OPEN'\r\n except:\r\n output[port] = ''\r\n\r\n\r\ndef scan_ports(host, delay):\r\n threads = [] # Runs connect_tcp\r\n output = {} # For Output\r\n for i in range(1000): # Spawns threads to scan ports\r\n t = threading.Thread(target=connect_tcp, args=(host, i, delay, output))\r\n threads.append(t)\r\n for i in range(1000):\r\n threads[i].start()\r\n for i in range(1000): # locks main thread until scan completion\r\n threads[i].join()\r\n for i in range(1000): # Printing all ports that are OPEN\r\n if output[i] == 'OPEN':\r\n print(str(i) + ': ' + output[i])\r\n\r\n\r\ndef main():\r\n host = input(\"Host IP or Domain: \")\r\n try:\r\n delay = int(input(\"timeout setting (2 is default): \"))\r\n except ValueError:\r\n delay = 2\r\n start_time = time.time()\r\n whois_result = whois.whois(host)\r\n print('---PORTS---')\r\n scan_ports(host, delay)\r\n print('---WHOIS---')\r\n print(whois_result)\r\n end_time = time.time() - start_time\r\n print('Took '+ str(end_time) + ' seconds')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"JustScan.py","file_name":"JustScan.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"268735670","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 11 20:37:15 2017\r\n@author: LeoLiu\r\n\"\"\"\r\n\r\n# 机器学习 大作业 1\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport time\r\nimport codecs\r\n\r\nfrom sklearn.preprocessing import Imputer\r\nfrom sklearn.cross_validation import train_test_split \r\nfrom sklearn.metrics import classification_report\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.ensemble import BaggingClassifier\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.naive_bayes import GaussianNB\r\n\r\n# 读取训练数据\r\ndef loadtainData(filePath):\r\n fr = open(filePath,'r+')\r\n lines = fr.readlines()\r\n retData = []\r\n retLabel = []\r\n for line in lines:\r\n items = line.strip().split(\" \")\r\n retLabel.append(items[-1])\r\n retData.append([int(items[i]) for i in range(0,(len(items)-1))])\r\n return retData,retLabel\r\n\r\n# 读取预测数据\r\ndef loadtestData(filePath):\r\n fr = open(filePath,'r+')\r\n lines = fr.readlines()\r\n retData = []\r\n for line in lines:\r\n items = line.strip().split(\" \")\r\n retData.append([int(items[i]) for i in range(0,len(items))])\r\n return retData\r\n\r\ndef CLF_Report(y_test, answer,CLF_Name):\r\n print('\\nThe classification report for '+CLF_Name+' :')\r\n print(classification_report(y_test, answer))\r\n print(\"\\n\")\r\n\r\ndef CLF_KNeighborsClassifier(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"KNeighborsClassifier\"\r\n print('Start training '+CLF_Name)\r\n knn = KNeighborsClassifier().fit(x_train, y_train)\r\n print('Training done')\r\n answer = knn.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n \r\ndef CLF_DecisionTreeClassifier(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"DecisionTreeClassifier\"\r\n print('Start training '+CLF_Name)\r\n dt = DecisionTreeClassifier().fit(x_train, y_train)\r\n print('Training done')\r\n answer = dt.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n\r\ndef CLF_GaussianNB(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"GaussianNB\"\r\n print('Start training '+CLF_Name)\r\n gnb = GaussianNB().fit(x_train, y_train)\r\n print('Training done')\r\n answer = gnb.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n \r\ndef CLF_RandomForestClassifier(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"RandomForestClassifier\"\r\n print('Start training '+CLF_Name)\r\n rf = RandomForestClassifier(random_state=0, n_estimators=500).fit(x_train, y_train)\r\n print('Training done')\r\n answer = rf.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n \r\ndef CLF_BaggingClassifier(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"BaggingClassifier\"\r\n print('Start training '+CLF_Name)\r\n bgclf = BaggingClassifier(KNeighborsClassifier(),max_samples=0.5, max_features=0.5).fit(x_train, y_train)\r\n print('Training done')\r\n answer = bgclf.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n \r\ndef CLF_GradientBoostingClassifier(x_train, x_test, y_train, y_test):\r\n CLF_Name=\"GradientBoostingClassifier\"\r\n print('Start training '+CLF_Name)\r\n gbclf = GradientBoostingClassifier(n_estimators=200).fit(x_train, y_train)\r\n print('Training done')\r\n answer = gbclf.predict(x_test)\r\n print('Prediction done')\r\n if(len(y_test)>0):\r\n CLF_Report(y_test, answer,CLF_Name)\r\n else:\r\n print(\"\\n\\n数据保存中...\")\r\n OutPutTestText(answer, len(answer) ,CLF_Name)\r\n \r\ndef OutPutTestText(answer, num ,CLF_Name):\r\n try:\r\n FileName=\"model_\"+CLF_Name+\" \"+(time.strftime('%Y%m%d',time.localtime(time.time())))+\".txt\"\r\n TextFile=codecs.open(FileName,\"w\",\"utf-8\")\r\n #TextFile.write(u\"\"+CLF_Name+\"\\n\")\r\n for i in range(num):\r\n answer_Temp=answer[i]\r\n TextFile.write(u\"\"+str(answer_Temp)+\"\\n\")\r\n TextFile.close()\r\n print(\"--> 文件保存成功! 文件名: \"+FileName+\"\\n--> 输出总数: %d个\"%(num))\r\n except:\r\n print(\"\\n-!-> 文件输出函数错误!\")\r\n \r\ndef main():\r\n \r\n # 文件地址\r\n Tain_filePath=\"data/data_train.txt\"\r\n Test_filePath=\"data/data_test.txt\"\r\n # 读取数据\r\n X,Y=loadtainData(Tain_filePath) \r\n print(\"读取 Tain 数据 OK \") \r\n print(\"Trian 数据总数: \",len(X))\r\n \r\n # 将数据分成 训练集与测试集\r\n CLF_Function_Flag=1; # 1 为输出txt文件 ; 0 为测试\r\n if(CLF_Function_Flag==1):\r\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.00)\r\n X_OutPut=loadtestData(Test_filePath)\r\n print(\"读取 Test 数据 OK \")\r\n print(\"Test 数据总数: \",len(X_OutPut))\r\n x_test=X_OutPut\r\n else:\r\n x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size = 0.30)\r\n # 打印参数\r\n print(\"训练集X 个数: \",len(x_train))\r\n print(\"训练集Y 个数: \",len(y_train))\r\n print(\"测试集X 个数: \",len(x_test))\r\n print(\"测试集Y 个数: \",len(y_test))\r\n # 训练 及 输出\r\n CLF_KNeighborsClassifier(x_train, x_test, y_train, y_test)\r\n CLF_RandomForestClassifier(x_train, x_test, y_train, y_test)\r\n CLF_DecisionTreeClassifier(x_train, x_test, y_train, y_test)\r\n CLF_BaggingClassifier(x_train, x_test, y_train, y_test)\r\n CLF_GradientBoostingClassifier(x_train, x_test, y_train, y_test)\r\n CLF_GaussianNB(x_train, x_test, y_train, y_test)\r\n \r\nmain()","sub_path":"机器学习/数据分析/HomeWorkA.py","file_name":"HomeWorkA.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"24220614","text":"import re\n\n__all__ = ['DupProductManager']\n\n\nclass DupProductManager(dict):\n\n def extend(self, docs):\n for doc in docs:\n self.append(doc)\n\n\n def append(self, doc):\n key = '{};{}'.format(\n doc.get('brand', '').lower().strip(),\n re.sub(r'\\s+', ' ', doc.get('title', '').lower().replace(' - ', ' ').strip()),\n )\n\n current = self.get(key)\n if current:\n current['department'].add(doc['department'])\n else:\n doc['department'] = set([doc['department']])\n doc['brand'] = doc.get('brand', '').strip()\n doc['title'] = doc.get('title', '').strip()\n self[key] = doc\n\n\n def process(self):\n result = []\n # Less efficient than self.values(), but grant idempotence\n for key in sorted(self.keys()):\n doc = self[key]\n depts = doc['department']\n\n if not depts:\n # It should never run\n doc['department'] = None\n\n elif len(doc['department']) == 1:\n doc['department'] = depts.pop()\n\n else:\n doc['department'] = sorted(depts)\n\n result.append(doc)\n return {'products': result}\n","sub_path":"src/crawler/duplication_management.py","file_name":"duplication_management.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"506042155","text":"import json\n\nfrom flask import render_template, redirect, url_for\nfrom werkzeug.exceptions import NotFound\n\nimport apps.vsrmn.bl.search as elastic\nfrom apps.auth import user_session\nfrom apps.db import db\nfrom apps.session import session_scope\nfrom apps.vsrmn.bl import documents, tagging, categories\nfrom apps.vsrmn.models import Document\n\n\ndef redirect_to_index():\n return redirect(url_for('index'))\n\n\ndef index():\n return render_template('vsrmn/index.html',\n categories=categories.get_for_index(user_session.is_logged()),\n is_logged=user_session.is_logged())\n\n\ndef document(doc_id=None):\n doc = Document.query.get_or_404(doc_id)\n if not (doc.visible or user_session.is_logged()):\n raise NotFound\n else:\n tags = [tag.name for tag in doc.tags]\n docs = categories.get_paginated(doc_id, 1)\n docs_for_js = documents.get_first_children(docs)\n number_of_children = categories.get_number_of_childs(db.session, doc_id)\n breadcrumbs = documents.get_breadcrumbs(doc_id)\n return render_template('vsrmn/document.html',\n document=Document.query.get_or_404(doc_id),\n breadcrumbs=breadcrumbs,\n number_of_children=number_of_children,\n tags=tags,\n is_logged=user_session.is_logged(),\n documents=json.dumps({'data': docs_for_js}))\n\n\ndef documents_tag(tag):\n if user_session.is_logged():\n docs = tagging.get_documents_with_tag(tag, hide_invisible=False)\n else:\n docs = tagging.get_documents_with_tag(tag)\n return render_template('vsrmn/search_results.html',\n documents=docs,\n search_terms=tag, is_logged=user_session.is_logged())\n\n\ndef search(search_terms=None, page=1):\n if search_terms is None or search_terms == '':\n return render_template('vsrmn/search_results.html', documents=[], is_logged=user_session.is_logged())\n if user_session.is_logged():\n docs = elastic.search_document(search_terms, page, hide_invisible=False)\n else:\n docs = elastic.search_document(search_terms, page)\n return render_template('vsrmn/search_results.html',\n documents=docs,\n search_terms=search_terms, is_logged=user_session.is_logged())\n\n\ndef documents_tree(doc_id, page=1):\n if not (Document.query.get(doc_id).visible or user_session.is_logged()):\n raise NotFound\n docs = categories.get_paginated(doc_id, page)\n docs_for_js = documents.get_first_children(docs)\n with session_scope() as session:\n number_of_children = categories.get_number_of_childs(session, doc_id)\n return render_template('vsrmn/documents_tree.html',\n category=Document.query.get(doc_id),\n number_of_children=number_of_children,\n documents=json.dumps({'data': docs_for_js}),\n pagination=docs,\n is_logged=user_session.is_logged())\n","sub_path":"apps/vsrmn/views/collective_views.py","file_name":"collective_views.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"632753333","text":"import csv\nfrom datetime import datetime\n\ndv_file = open(\"death_valley_2018_simple.csv\",\"r\")\n\nvalley_file = csv.reader(dv_file,delimiter=\",\")\n\nheader_row = next(valley_file)\n\nnames = []\nhighs = []\nlows = []\ndates = []\n\nfor row in (valley_file):\n\n try:\n high = int(row[4])\n low = int(row[5])\n thedate = datetime.strptime(row[2],'%Y-%m-%d')\n except ValueError:\n print(f\"Missing data for {thedate}\")\n else:\n highs.append(high)\n lows.append(low)\n dates.append(thedate)\n\n\nsitka_file = open(\"sitka_weather_2018_simple.csv\",\"r\")\n\ns_file = csv.reader(sitka_file,delimiter=\",\")\n\nheader1_row = next(s_file)\n\nhighs2 = []\nlows2 = []\ndates2 = []\n\nfor row in s_file:\n highs2.append(int(row[5]))\n lows2.append(int(row[6]))\n thedate2 = datetime.strptime(row[2],'%Y-%m-%d')\n dates2.append(thedate2)\n\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(2, sharex=True)\n\nax[0].plot(dates2,highs2, c=\"red\", alpha = 0.5)\nax[0].plot(dates2,lows2, c=\"blue\", alpha = 0.5)\n\nax[1].plot(dates,highs, c=\"red\", alpha = 0.5)\nax[1].plot(dates, lows, c=\"blue\", alpha = 0.5)\n\nfig.autofmt_xdate()\n\nax[0].fill_between(dates2, highs2, lows2, facecolor = 'blue', alpha=0.1)\nax[1].fill_between(dates, highs, lows, facecolor = 'blue', alpha=0.1)\n\nax[0].set_title('Sitka Airport, AK US')\nax[1].set_title('Death Valley, CA US')\nfig.suptitle('Temperature Comparison Between Sitka Airport, AK US and Death Valley, CA US')\n\nplt.show()\n\n\n\n\n","sub_path":"sitka_and_death_valley.py","file_name":"sitka_and_death_valley.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"203492417","text":"import ipaddress\nimport collections\nimport string\nimport unittest\nimport datetime\nimport re\nimport uuid\nimport subprocess\nimport random\n\nimport logging\nimport logging.config\n\nimport mechanize\n\nfrom pyswagger import App, Security\nfrom pyswagger.contrib.client.requests import Client\n\n\nlog = logging.getLogger(\"api\")\n\nclass HttpFormatter(logging.Formatter):\n\n def _formatHeaders(self, d):\n return '\\n'.join(f'{k}: {v}' for k, v in d.items())\n\n def formatMessage(self, record):\n result = super().formatMessage(record)\n if record.name == 'api':\n result += '''\n---------------- request ----------------\n{req.method} {req.url}\n{reqhdrs}\n\n{req.body}\n---------------- response ----------------\n{res.status_code} {res.reason} {res.url}\n{reshdrs}\n\n{res.text}\n---------------- end ----------------\n'''.format(req=record.req, res=record.res, reqhdrs=self._formatHeaders(record.req.headers),\n reshdrs=self._formatHeaders(record.res.headers), )\n\n return result\n\n\nlogging.config.dictConfig(\n {\n \"version\": 1,\n \"formatters\": {\n \"http\": {\n \"()\": HttpFormatter,\n \"format\": \"{asctime} {levelname} {name} {message}\",\n \"style\":'{',\n },\n \"detailed\": {\n \"class\": \"logging.Formatter\",\n \"format\": \"%(asctime)s %(name)-9s %(levelname)-4s %(message)s\",\n },\n \"plain\": {\n \"class\": \"logging.Formatter\",\n \"format\": \"%(message)s\",\n }\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": \"DEBUG\",\n \"formatter\": \"detailed\",\n },\n \"console_http\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": \"DEBUG\",\n \"formatter\": \"http\",\n },\n },\n \"root\": {\n \"level\": \"DEBUG\",\n \"handlers\": [\"console\"],\n \"propagate\": True\n },\n 'loggers': {\n 'api': {\n \"level\": \"INFO\",\n \"handlers\": [\"console_http\"]\n },\n \"requests.packages.urllib3\": {\n \"level\": \"DEBUG\",\n \"handlers\": [\"console\"],\n \"propagate\": True\n },\n },\n }\n)\n\nlog = logging.getLogger(\"api\")\n\nclass ApiError(Exception):\n pass\n\n\n\ndef logHttp(response, *args, **kwargs):\n extra = {'req': response.request, 'res': response}\n log.debug('HTTP', extra=extra)\n\nclass WGPClient:\n def __init__(self, url, *auths):\n app = App._create_(url)\n auth = Security(app)\n for t, cred in auths:\n auth.update_with(t, cred)\n\n client = Client(auth)\n self.app, self.client = app, client\n\n self.client._Client__s.hooks['response'] = logHttp\n\n def call(self, name, **kwargs):\n # print(f\"{name} {kwargs}\")\n op = self.app.op[name]\n req, resp = op(**kwargs)\n now = datetime.datetime.now()\n resp = self.client.request((req, resp))\n then = datetime.datetime.now()\n delta = then - now\n # print(f\"{resp.status} {delta}\")\n\n if 200 <= resp.status <= 299:\n pass\n elif 400 <= resp.status <= 499:\n raise ApiError(resp.data[\"Message\"])\n elif 500 == resp.status:\n raise ValueError(resp.data[\"Message\"])\n elif 501 == resp.status:\n raise NotImplementedError(name)\n elif 502 <= resp.status <= 599:\n raise ApiError(resp.data[\"Message\"])\n return resp\n\n def GetDevice(self, **kwargs):\n return self.call(\"GetDevice\", **kwargs).data\n\n def PatchDevice(self, **kwargs):\n return self.call(\"PatchDevice\", **kwargs).data\n\n def PutDevice(self, **kwargs):\n return self.call(\"PutDevice\", **kwargs).data\n\n def GetDevices(self, **kwargs):\n # FIXME - could return empty list?\n return self.call(\"GetDevices\", **kwargs).data or []\n\n def DeletePeer(self, **kwargs):\n return self.call(\"DeletePeer\", **kwargs).data\n\n def GetPeer(self, **kwargs):\n return self.call(\"GetPeer\", **kwargs).data\n\n def PatchPeer(self, **kwargs):\n return self.call(\"PatchPeer\", **kwargs).data\n\n def PostPeer(self, **kwargs):\n return self.call(\"PostPeer\", **kwargs).data\n\n def PutPeer(self, **kwargs):\n return self.call(\"PutPeer\", **kwargs).data\n\n def GetPeerDeploymentConfig(self, **kwargs):\n return self.call(\"GetPeerDeploymentConfig\", **kwargs).data\n\n def PostPeerDeploymentConfig(self, **kwargs):\n return self.call(\"PostPeerDeploymentConfig\", **kwargs).raw\n\n def GetPeerDeploymentInformation(self, **kwargs):\n return self.call(\"GetPeerDeploymentInformation\", **kwargs).data\n\n def GetPeers(self, **kwargs):\n return self.call(\"GetPeers\", **kwargs).data\n\n def DeleteUser(self, **kwargs):\n return self.call(\"DeleteUser\", **kwargs).data\n\n def GetUser(self, **kwargs):\n return self.call(\"GetUser\", **kwargs).data\n\n def PatchUser(self, **kwargs):\n return self.call(\"PatchUser\", **kwargs).data\n\n def PostUser(self, **kwargs):\n return self.call(\"PostUser\", **kwargs).data\n\n def PutUser(self, **kwargs):\n return self.call(\"PutUser\", **kwargs).data\n\n def GetUsers(self, **kwargs):\n return self.call(\"GetUsers\", **kwargs).data\n\n\ndef generate_wireguard_keys():\n \"\"\"\n Generate a WireGuard private & public key\n Requires that the 'wg' command is available on PATH\n Returns (private_key, public_key), both strings\n \"\"\"\n privkey = subprocess.check_output(\"wg genkey\", shell=True).decode(\"utf-8\").strip()\n pubkey = subprocess.check_output(f\"echo '{privkey}' | wg pubkey\", shell=True).decode(\"utf-8\").strip()\n return (privkey, pubkey)\n\n\nKeyTuple = collections.namedtuple(\"Keys\", \"private public\")\n\n\nclass TestAPI(unittest.TestCase):\n URL = 'http://localhost:8123/swagger/doc.json'\n AUTH = {\n \"api\": ('ApiBasicAuth', (\"wg@example.org\", \"abadchoice\")),\n \"general\": ('GeneralBasicAuth', (\"wg@example.org\", \"abadchoice\"))\n }\n DEVICE = \"wg-example0\"\n IFADDR = \"10.17.0.0/24\"\n log = logging.getLogger(\"TestAPI\")\n\n\n def _client(self, *auth):\n auth = [\"general\"] if auth is None else auth\n self.c = WGPClient(self.URL, *[self.AUTH[i] for i in auth])\n\n @property\n def randmail(self):\n return 'test+' + ''.join(\n [random.choice(string.ascii_lowercase + string.digits) for i in range(6)]) + '@example.org'\n\n @classmethod\n def setUpClass(cls) -> None:\n cls.finishInstallation()\n\n @classmethod\n def finishInstallation(cls) -> None:\n import http.cookiejar\n\n # Fake Cookie Policy to send the Secure cookies via http\n class InSecureCookiePolicy(http.cookiejar.DefaultCookiePolicy):\n def set_ok(self, cookie, request):\n return True\n\n def return_ok(self, cookie, request):\n return True\n\n def domain_return_ok(self, domain, request):\n return True\n\n def path_return_ok(self, path, request):\n return True\n\n b = mechanize.Browser()\n b.set_cookiejar(http.cookiejar.CookieJar(InSecureCookiePolicy()))\n b.set_handle_robots(False)\n b.open(\"http://localhost:8123/\")\n\n b.follow_link(text=\"Login\")\n\n b.select_form(name=\"login\")\n username, password = cls.AUTH['api'][1]\n b.form.set_value(username, \"username\")\n b.form.set_value(password, \"password\")\n\n b.submit()\n\n b.follow_link(text=\"Administration\")\n b.follow_link(predicate=lambda x: any([a == ('title', 'Edit interface settings') for a in x.attrs]))\n b.select_form(\"server\")\n\n values = {\n \"displayname\": \"example0\",\n \"endpoint\": \"wg.example.org:51280\",\n \"ip\": cls.IFADDR\n }\n for k, v in values.items():\n b.form.set_value(v, k)\n\n b.submit()\n\n b.select_form(\"server\")\n# cls.log.debug(b.form.get_value(\"ip\"))\n\n def setUp(self) -> None:\n self._client('api')\n self.user = self.randmail\n\n # create a user …\n self.c.PostUser(User={\"Firstname\": \"Test\", \"Lastname\": \"User\", \"Email\": self.user})\n\n self.keys = KeyTuple(*generate_wireguard_keys())\n\n\n def _test_generate(self):\n def key_of(op):\n a, *b = list(filter(lambda x: len(x), re.split(\"([A-Z][a-z]+)\", op.operationId)))\n return ''.join(b), a\n\n for op in sorted(self.c.app.op.values(), key=key_of):\n print(f\"\"\"\n def {op.operationId}(self, **kwargs):\n return self. call(\"{op.operationId}\", **kwargs)\n \"\"\")\n\n def test_ops(self):\n for op in sorted(self.c.app.op.values(), key=lambda op: op.operationId):\n self.assertTrue(hasattr(self.c, op.operationId), f\"{op.operationId} is missing\")\n\n def test_Device(self):\n # FIXME device has to be completed via webif to be valid before it can be used via API\n devices = self.c.GetDevices()\n self.assertTrue(len(devices) > 0)\n\n for device in devices:\n dev = self.c.GetDevice(DeviceName=device.DeviceName)\n with self.assertRaises(NotImplementedError):\n new = self.c.PutDevice(DeviceName=dev.DeviceName,\n Device={\n \"DeviceName\": dev.DeviceName,\n \"IPsStr\": dev.IPsStr,\n \"PrivateKey\": dev.PrivateKey,\n \"Type\": \"client\",\n \"PublicKey\": dev.PublicKey}\n )\n with self.assertRaises(NotImplementedError):\n new = self.c.PatchDevice(DeviceName=dev.DeviceName,\n Device={\n \"DeviceName\": dev.DeviceName,\n \"IPsStr\": dev.IPsStr,\n \"PrivateKey\": dev.PrivateKey,\n \"Type\": \"client\",\n \"PublicKey\": dev.PublicKey}\n )\n break\n\n def easy_peer(self):\n data = self.c.PostPeerDeploymentConfig(ProvisioningRequest={\"Email\": self.user, \"Identifier\": \"debug\"})\n data = data.decode()\n pubkey = re.search(\"# -WGP- PublicKey: (?P[^\\n]+)\\n\", data, re.MULTILINE)['pubkey']\n privkey = re.search(\"PrivateKey = (?P[^\\n]+)\\n\", data, re.MULTILINE)['key']\n self.keys = KeyTuple(privkey, pubkey)\n\n def test_Peers(self):\n\n privkey, pubkey = generate_wireguard_keys()\n peer = {\"UID\": uuid.uuid4().hex,\n \"Identifier\": uuid.uuid4().hex,\n \"DeviceName\": self.DEVICE,\n \"PublicKey\": pubkey,\n \"DeviceType\": \"client\",\n \"IPsStr\": str(self.IFADDR),\n \"Email\": self.user}\n\n # keypair is created server side if private key is not submitted\n with self.assertRaisesRegex(ApiError, \"peer not found\"):\n self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)\n\n # create\n peer[\"PrivateKey\"] = privkey\n p = self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)\n self.assertListEqual([p.PrivateKey, p.PublicKey], [privkey, pubkey])\n\n # lookup created peer\n for p in self.c.GetPeers(DeviceName=self.DEVICE):\n if pubkey == p.PublicKey:\n break\n else:\n self.assertTrue(False)\n\n # get\n gp = self.c.GetPeer(PublicKey=p.PublicKey)\n self.assertListEqual([gp.PrivateKey, gp.PublicKey], [p.PrivateKey, p.PublicKey])\n\n # change?\n peer['Identifier'] = 'changed'\n n = self.c.PatchPeer(PublicKey=p.PublicKey, Peer=peer)\n self.assertListEqual([n.PrivateKey, n.PublicKey], [privkey, pubkey])\n\n # change ?\n peer['Identifier'] = 'changedagain'\n n = self.c.PutPeer(PublicKey=p.PublicKey, Peer=peer)\n self.assertListEqual([n.PrivateKey, n.PublicKey], [privkey, pubkey])\n\n # invalid change operations\n n = peer.copy()\n n['PrivateKey'], n['PublicKey'] = generate_wireguard_keys()\n with self.assertRaisesRegex(ApiError, \"PublicKey parameter must match the model public key\"):\n self.c.PutPeer(PublicKey=p.PublicKey, Peer=n)\n\n with self.assertRaisesRegex(ApiError, \"PublicKey parameter must match the model public key\"):\n self.c.PatchPeer(PublicKey=p.PublicKey, Peer=n)\n\n n = self.c.DeletePeer(PublicKey=p.PublicKey)\n\n def test_Deployment(self):\n log.setLevel(logging.DEBUG)\n self._client(\"general\")\n self.easy_peer()\n\n self.c.GetPeerDeploymentConfig(PublicKey=self.keys.public)\n self.c.GetPeerDeploymentInformation(Email=self.user)\n log.setLevel(logging.INFO)\n\n def test_User(self):\n u = self.c.PostUser(User={\"Firstname\": \"Test\", \"Lastname\": \"User\", \"Email\": self.randmail})\n for i in self.c.GetUsers():\n if i.Email == u.Email:\n break\n else:\n self.assertTrue(False)\n\n u = self.c.GetUser(Email=u.Email)\n self.c.PutUser(Email=u.Email, User={\"Firstname\": \"Test\", \"Lastname\": \"User\", \"Email\": u.Email})\n self.c.PatchUser(Email=u.Email, User={\"Firstname\": \"Test\", \"Lastname\": \"User\", \"Email\": u.Email})\n\n # list a deleted user\n self.c.DeleteUser(Email=u.Email)\n\n for i in self.c.GetUsers():\n break\n\n\n def _clear_peers(self):\n for p in self.c.GetPeers(DeviceName=self.DEVICE):\n self.c.DeletePeer(PublicKey=p.PublicKey)\n\n def _clear_users(self):\n for p in self.c.GetUsers():\n if p.Email == self.AUTH['api'][1][0]:\n continue\n self.c.DeleteUser(Email=p.Email)\n\n\n def _createPeer(self):\n privkey, pubkey = generate_wireguard_keys()\n peer = {\"UID\": uuid.uuid4().hex,\n \"Identifier\": uuid.uuid4().hex,\n \"DeviceName\": self.DEVICE,\n \"PublicKey\": pubkey,\n \"PrivateKey\": privkey,\n \"DeviceType\": \"client\",\n # \"IPsStr\": str(self.ifaddr),\n \"Email\": self.user}\n self.c.PostPeer(DeviceName=self.DEVICE, Peer=peer)\n return pubkey\n\n def test_address_exhaustion(self):\n global log\n self._clear_peers()\n self._clear_users()\n\n self.NETWORK = ipaddress.ip_network(\"10.0.0.0/29\")\n addr = ipaddress.ip_address(\n random.randrange(int(self.NETWORK.network_address) + 1, int(self.NETWORK.broadcast_address) - 1))\n self.__class__.IFADDR = str(ipaddress.ip_interface(f\"{addr}/{self.NETWORK.prefixlen}\"))\n\n # reconfigure via web ui - set the ifaddr with less addrs in pool\n self.finishInstallation()\n\n keys = set()\n EADDRESSEXHAUSTED = \"failed to get available IP addresses: no more available address from cidr\"\n with self.assertRaisesRegex(ValueError, EADDRESSEXHAUSTED):\n for i in range(self.NETWORK.num_addresses + 1):\n keys.add(self._createPeer())\n\n n = keys.pop()\n self.c.DeletePeer(PublicKey=n)\n self._createPeer()\n\n with self.assertRaisesRegex(ValueError, EADDRESSEXHAUSTED):\n self._createPeer()\n\n # expand network\n self.NETWORK = ipaddress.ip_network(\"10.0.0.0/28\")\n addr = ipaddress.ip_address(\n random.randrange(int(self.NETWORK.network_address) + 1, int(self.NETWORK.broadcast_address) - 1))\n self.__class__.IFADDR = str(ipaddress.ip_interface(f\"{addr}/{self.NETWORK.prefixlen}\"))\n self.finishInstallation()\n self._createPeer()\n\n","sub_path":"tests/test_API.py","file_name":"test_API.py","file_ext":"py","file_size_in_byte":16105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"407878716","text":"# -*- coding:utf-8 -*-\n\n# ==============================================================================\n# 测试tornado的基本用法。\n# 1. tornado.web是tornado的基础web框架模块:\n# RequestHandler封装了对应一个请求的所有信息和方法,write(响应信息)就是写响应信息的一个方法。\n# Application是与服务器对接的接口,里面保存了路由信息表,其初始化接收的第一个参数就是一个路由信息映射元组的列表;\n# 其listen(端口)方法用来创建一个http服务器实例,并绑定到给定端口(注意:此时服务器并未开启监听)。\n# 2. tornado.ioloop是tornado的核心io循环模块,封装了Linux的epoll和BSD的kqueue,tornado高性能的基石。\n# IOLoop.current()返回当前线程的IOLoop实例。\n# IOLoop.start()启动IOLoop实例的I/O循环,同时服务器监听被打开。\n# 3. tornado.httpserver是tornado的HTTP服务器实现。\n# 4. tornado.options模块用来实现全局参数的定义、存储、转换。\n# options.define()用来定义options选项变量的方法,定义的变量可以在全局的tornado.options.options中获取使用。\n# options.options是全局的options对象,所有定义的选项变量都会作为该对象的属性。\n# options.parse_command_line()转换命令行参数,并将转换后的值对应的设置到全局options对象相关属性上。\n# 追加命令行参数的方式是--myoption=myvalue。\n# ==============================================================================\nimport tornado.ioloop\nimport tornado.web\nimport tornado.httpserver\nfrom tornado.web import RequestHandler\nfrom tornado.options import define, options, parse_command_line\n\n# 定义服务器监听端口选项\ndefine(\"port\", default=8000, type=int, help=\"run server on the given port.\")\n# 无意义,演示多值情况\ndefine(\"subject\", default=[], type=str, multiple=True, help=\"subjects.\")\n\n\nclass MainHandler(RequestHandler):\n def get(self):\n self.write(\"Hello, world\")\n\n\nclass IndexHandler(RequestHandler):\n def get(self):\n python_url = self.reverse_url(\"python_url\")\n self.write('subject'.format(python_url))\n\n\nclass SubjectHandler(RequestHandler):\n def initialize(self, subject):\n self.subject = subject\n\n def get(self):\n self.write(self.subject)\n\nhandlers = [\n (\"/\", IndexHandler),\n (\"/cpp\", SubjectHandler, {\"subject\": \"c++\"}),\n tornado.web.url(\"/python\", SubjectHandler, {\"subject\": \"python\"}, name=\"python_url\")\n]\n\n\ndef make_app():\n return tornado.web.Application([\n (\"/\", MainHandler),\n ])\n\n\ndef test_hello_world_app():\n \"\"\"\n 测试hello world的简单应用。\n :return:\n \"\"\"\n app = make_app()\n app.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n\n\ndef test_hello_world_server():\n \"\"\"\n 测试hello world的简单httpserver应用。\n :return:\n \"\"\"\n app = make_app()\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n\n\ndef test_multi_process():\n \"\"\"\n 测试hello world应用的多进程服务。\n :return:\n \"\"\"\n app = make_app()\n http_server = tornado.httpserver.HTTPServer(app)\n # 将服务器绑定到指定端口\n http_server.bind(8888)\n # 指定开启几个进程,默认值为1,即默认仅开启一个进程;\n # 如果为None或者<=0,则自动根据机器硬件的cpu核芯数创建同等数目的子进程;\n # 如果num_processes>0,则创建num_processes个子进程\n http_server.start(0)\n tornado.ioloop.IOLoop.current().start()\n\n\ndef test_options():\n \"\"\"\n 测试options选项在web应用中的用法。\n 命令python hello_world_demo.py llo--port=9000 --subject=python,c++,java,php,ios\n :return:\n \"\"\"\n parse_command_line()\n print(\"subject:{0}\".format(options.subject))\n app = make_app()\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n\n\ndef test_multi_handler():\n \"\"\"\n 测试http服务中的多种handler方法。\n :return:\n \"\"\"\n app = tornado.web.Application(handlers,\n debug=True)\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(8888)\n tornado.ioloop.IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n pass\n # test_options()\n # test_hello_world_server()\n test_multi_handler()\n\n","sub_path":"web_demo/tornado_demo/hello_world_demo.py","file_name":"hello_world_demo.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"417695031","text":"from __future__ import (absolute_import, division,\n print_function, unicode_literals)\nimport json\nfrom datetime import datetime\nimport pandas as pd\nimport io\nimport warnings\nwarnings.simplefilter('ignore')\n\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 12, 5\nimport pandas as pd\nimport seaborn as sns\n\nfines = []\nfines_json = json.loads(json.loads(io.open('fines.json', encoding='utf-8').read())['Value'])['Fines']\n\nfor fine in fines_json:\n fines.append({\n 'Дата и время': datetime.strptime(fine['ApnDetail'][2]['Value'], '%d.%m.%Y %H:%M:%S'),\n 'Номер постановления': fine['DAP'],\n 'Статья КоАП': fine['ApnDetail'][0]['Value'].replace('\\t', ' - '),\n 'Место правонарушения': fine['ApnDetail'][3]['Value'],\n 'Lat': fine['Latitude'],\n 'Lng': fine['Longitude'],\n 'Штраф': fine['FineSum'],\n })\n \nfines_df = pd.DataFrame.from_dict(fines)\n\n#print(fines_df.shape)\n#print(fines_df.head())\nprint(fines_df.describe())\n\nnew_df = fines_df[[x for x in fines_df.columns if 'Штраф' in x] + ['Дата и время']]\nnew_df.groupby('Дата и время').sum().plot()\n\ncols = ['Дата и время', 'Штраф']\nsns_plot = sns.pairplot(fines_df[cols])\n","sub_path":"slutsky.py","file_name":"slutsky.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"542648594","text":"#!/usr/bin/env python\nimport unittest, rostest\nimport rosnode, rospy\nimport time\n\nclass WallStopTest(unittest.TestCase):\n def set_and_get(self, lf, ls, rs, rf):\n with open(\"/dev/rtlightsensor0\", \"w\") as f:\n f.write(\"%d %d %d %d \\n\" % (rf, rs, ls, lf))\n\n time.sleep(0.3)\n\n with open(\"/dev/rtmotor_raw_l0\", \"r\") as lf, \\\n open(\"/dev/rtmotor_raw_r0\", \"r\") as rf:\n left = int(lf.readline().rstrip())\n right = int(rf.readline().rstrip())\n\n return left, right\n\n def test_io(self):\n left, right = self.set_and_get(51, 0, 0, 0) # wall fornt\n rospy.loginfo(str(left) + \" \" + str(right)) \n self.assertTrue(left > right, \"don't curve to right\") #\n\n left, right = self.set_and_get(0, 0, 0, 60) # wall front\n rospy.loginfo(str(left) + \" \" + str(right))\n self.assertTrue(left > right, \"don't curve to right\") #\n\n left, right = self.set_and_get(0, 0, 60, 0) # near to right\n rospy.loginfo(str(left) + \" \" + str(right))\n self.assertTrue(left < right , \"don't curve to left\")\n\n left, right = self.set_and_get(0, 60, 0, 0) # near to left\n rospy.loginfo(str(left) + \" \" + str(right))\n self.assertTrue(left > right , \"don't curve to right\")\n\n left, right = self.set_and_get(0, 0, 0, 0) # no wall\n rospy.loginfo(str(left) + \" \" + str(right))\n self.assertTrue(left < right , \"don't curve to left\")\n\n\n\n #left, right = self.set_and_get(0, 0, 49, 0) #curve to left\n #self.assertTrue(left < right , \"don't curve to left\")\n\n #left, right = self.set_and_get(0, 49, 0, 0) # near to left\n #self.assertTrue(left > right, \"don't curve to right\")\n\n\nif __name__ == '__main__':\n time.sleep(3)\n rospy.init_node('travis_test_wall_stop')\n rostest.rosrun('pimouse_run_corridor', 'travis_test_wall_stop', WallStopTest)\n","sub_path":"test/travis_test_wall_around.py","file_name":"travis_test_wall_around.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"246450717","text":"\"\"\"\n\nDefine n!! as\n\nn!! = 1 * 3 * 5 * ... * n if n is odd,\n\nn!! = 2 * 4 * 6 * ... * n if n is even.\n\nHence 8!! = 2 * 4 * 6 * 8 = 384, there is no zero at the end. 30!! has 3 zeros at the end.\n\nFor a positive integer n, please count how many zeros are there at the end of n!!.\n\nExample:\n\n30!! = 2 * 4 * 6 * 8 * 10 * ... * 22 * 24 * 26 * 28 * 30 \n30!! = 42849873690624000 (3 zeros at the end)\n\"\"\"\n\n\n\n\ndef count_zeros_n_double_fact(n): \n x= 2 if(n %2 ==0) else 1\n from functools import reduce\n tempRes=reduce(lambda x,y : x*y,range(x,n+1,2))\n res=len(str(tempRes)) - len(str(int(str(tempRes)[::-1])))\n return res\n \n\n\nassert(count_zeros_n_double_fact(8)== 0)\nassert(count_zeros_n_double_fact(30)== 3)\n\nprint(\"Done\")","sub_path":"Jungerstein1/jungerstein1.py","file_name":"jungerstein1.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"368402235","text":"import numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.io import loadmat\nfrom numpy.linalg import det, inv\nfrom math import sqrt, pi\nimport scipy.io\nimport matplotlib.pyplot as plt\nimport pickle\nimport sys\n\n\ndef ldaLearn(X, y):\n # Inputs\n # X - a N x d matrix with each row corresponding to a training example\n # y - a N x 1 column vector indicating the labels for each training example\n #\n # Outputs\n # means - A d x k matrix containing learnt means for each of the k classes\n # covmat - A single d x d learnt covariance matrix\n\n # IMPLEMENT THIS METHOD\n means = np.zeros((np.shape(X)[1], np.amax(y).astype(int)))\n\n for i in np.unique(y).astype(int):\n means[:, i - 1] = np.mean(X[np.where(y == i)[0], :], axis=0).transpose()\n covmat = np.cov(np.transpose(X))\n # print(means, '\\n',covmat)\n return means, covmat\n\n\ndef qdaLearn(X, y):\n # Inputs\n # X - a N x d matrix with each row corresponding to a training example\n # y - a N x 1 column vector indicating the labels for each training example\n #\n # Outputs\n # means - A d x k matrix containing learnt means for each of the k classes\n # covmats - A list of k d x d learnt covariance matrices for each of the k classes\n\n # IMPLEMENT THIS METHOD\n covmats = []\n means = np.zeros((np.shape(X)[1], np.amax(y).astype(int)))\n\n for i in np.unique(y).astype(int):\n means[:, i - 1] = np.mean(X[np.where(y == i)[0], :], axis=0).transpose()\n covmats.append(np.cov(X[np.where(y == i)[0], :].transpose()))\n # print(means, '\\n',covmats)\n return means, covmats\n\n\ndef ldaTest(means, covmat, Xtest, ytest):\n # Inputs\n # means, covmat - parameters of the LDA model\n # Xtest - a N x d matrix with each row corresponding to a test example\n # ytest - a N x 1 column vector indicating the labels for each test example\n # Outputs\n # acc - A scalar accuracy value\n # ypred - N x 1 column vector indicating the predicted labels\n\n # IMPLEMENT THIS METHOD\n acc = 0.\n kClass = means.shape[1]\n ypred = np.zeros((Xtest.shape[0], 1)).astype(float)\n inverse = inv(covmat)\n const = 1 / (sqrt(np.power(2 * np.pi, Xtest.shape[1]))) * sqrt(det(covmat))\n # print(ytest)\n pred = 0.\n i = 0\n while i < (Xtest.shape[0]):\n plist = []\n j = 0\n while j < (kClass):\n row = np.transpose(Xtest[i, :]) - means[:, j]\n res = const * np.exp(-0.5 * np.dot(np.dot(np.transpose(row), inverse), row))\n (plist.append(res))\n j += 1\n pred = max(plist)\n pred = (plist.index(pred))\n if (pred == ytest[i] - 1):\n acc += 1.\n ypred[i] = pred\n i += 1\n acc /= Xtest.shape[0]\n return acc, ypred\n\n\ndef qdaTest(means, covmats, Xtest, ytest):\n # Inputs\n # means, covmats - parameters of the QDA model\n # Xtest - a N x d matrix with each row corresponding to a test example\n # ytest - a N x 1 column vector indicating the labels for each test example\n # Outputs\n # acc - A scalar accuracy value\n # ypred - N x 1 column vector indicating the predicted labels\n\n # IMPLEMENT THIS METHOD\n acc = 0.\n kClass = means.shape[1]\n ypred = np.zeros((Xtest.shape[0], 1))\n inverse = np.copy(((covmats)))\n i = 0\n while i < (len(covmats)):\n inverse[i] = inv(covmats[i])\n i += 1\n constants = np.empty(kClass)\n i = 0\n while i < (kClass):\n constants[i] = 1 / (sqrt(np.power((2 * np.pi), Xtest.shape[1])) * sqrt(det(covmats[i])))\n i += 1\n i = 0\n while i < (Xtest.shape[0]):\n plist = []\n j = 0\n while j < (kClass):\n row = np.transpose(Xtest[i, :]) - means[:, j]\n res = constants[j] * np.exp(-0.5 * np.dot(np.dot(row.transpose(), inverse[j]), row))\n plist.append(res)\n j += 1\n pred = max(plist)\n pred = int(plist.index(pred))\n if (pred == int(ytest[i]) - 1):\n acc += 1\n ypred[i] = pred\n i += 1\n acc /= Xtest.shape[0]\n return acc, ypred\n\n\ndef learnOLERegression(X, y):\n # Inputs:\n # X = N x d\n # y = N x 1\n # Output:\n # w = d x 1\n\n # IMPLEMENT THIS METHOD\n # returns the dotrabs the dot product of inverse of\n transposeX = np.dot(X.transpose(), X)\n transposeY = np.dot(X.transpose(), y)\n w = np.dot(np.linalg.inv(transposeX), transposeY)\n #print(w)\n return w\n\n\ndef learnRidgeRegression(X, y, lambd):\n # Inputs:\n # X = N x d\n # y = N x 1\n # lambd = ridge parameter (scalar)\n # Output:\n # w = d x 1\n\n # IMPLEMENT THIS METHOD\n id = np.identity(X.shape[1])\n id = lambd*id\n w = np.dot(np.linalg.inv(np.dot(X.transpose(), X) + id), np.dot(X.transpose(), y))\n #print(w)\n return w\n\n\ndef testOLERegression(w, Xtest, ytest):\n # Inputs:\n # w = d x 1\n # Xtest = N x d\n # ytest = X x 1\n # Output:\n # mse\n\n # IMPLEMENT THIS METHOD\n\n #mse = np.sqrt(np.sum(np.square(ytest - np.dot(Xtest, w)))/Xtest.shape[0])\n\n somew = w.reshape((w.shape[0], 1))\n newW = np.sum(np.square((ytest - np.dot(Xtest, somew))))\n mse = (1.0 / Xtest.shape[0]) * (newW)\n return mse\n\ndef regressionObjVal(w, X, y, lambd):\n # compute squared error (scalar) and gradient of squared error with respect\n # to w (vector) for the given data X and y and the regularization parameter\n # lambda\n\n # IMPLEMENT THIS METHOD\n error = np.sum(np.square((y - np.dot(X, w.reshape((w.shape[0], 1))))))/2 + (0.5*lambd*np.sum(np.square(w)))\n gradience = np.dot(-1, np.dot(X.transpose(), (y - np.dot(X, w.reshape((w.shape[0], 1))))))\n error_grad = gradience[:, 0] + np.dot(lambd, w)\n return error, error_grad\n\n\ndef mapNonLinear(x, p):\n # Inputs:\n # x - a single column vector (N x 1)\n # p - integer (>= 0)\n # Outputs:\n # Xd - (N x (d+1))\n # IMPLEMENT THIS METHOD\n Xd = np.ones((x.shape[0], p + 1))\n i = 0\n while i < (x.shape[0]):\n j = 0\n while j < (p+1):\n Xd[i][j] = np.power(x[i], j)\n j +=1\n i += 1\n return Xd\n\n\n# Main script\n\n# Problem 1\n# load the sample data\nif sys.version_info.major == 2:\n X, y, Xtest, ytest = pickle.load(open('sample.pickle', 'rb'))\nelse:\n X, y, Xtest, ytest = pickle.load(open('sample.pickle', 'rb'), encoding='latin1')\n\n# LDA\nmeans, covmat = ldaLearn(X, y)\nldaacc, ldares = ldaTest(means, covmat, Xtest, ytest)\nprint('LDA Accuracy = ' + str(ldaacc))\n# QDA\nmeans, covmats = qdaLearn(X, y)\nqdaacc, qdares = qdaTest(means, covmats, Xtest, ytest)\nprint('QDA Accuracy = ' + str(qdaacc))\n\n# plotting boundaries\nx1 = np.linspace(-5, 20, 100)\nx2 = np.linspace(-5, 20, 100)\nxx1, xx2 = np.meshgrid(x1, x2)\nxx = np.zeros((x1.shape[0] * x2.shape[0], 2))\nxx[:, 0] = xx1.ravel()\nxx[:, 1] = xx2.ravel()\n\nfig = plt.figure(figsize=[12, 6])\nplt.subplot(1, 2, 1)\n\nzacc, zldares = ldaTest(means, covmat, xx, np.zeros((xx.shape[0], 1)))\nplt.contourf(x1, x2, zldares.reshape((x1.shape[0], x2.shape[0])), alpha=0.3)\nplt.scatter(Xtest[:, 0], Xtest[:, 1], c=ytest)\nplt.title('LDA')\n\nplt.subplot(1, 2, 2)\n\nzacc, zqdares = qdaTest(means, covmats, xx, np.zeros((xx.shape[0], 1)))\nplt.contourf(x1, x2, zqdares.reshape((x1.shape[0], x2.shape[0])), alpha=0.3)\nplt.scatter(Xtest[:, 0], Xtest[:, 1], c=ytest)\nplt.title('QDA')\n\nplt.show()\n# Problem 2\nif sys.version_info.major == 2:\n X, y, Xtest, ytest = pickle.load(open('diabetes.pickle', 'rb'))\nelse:\n X, y, Xtest, ytest = pickle.load(open('diabetes.pickle', 'rb'), encoding='latin1')\n\n# add intercept\nX_i = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1)\nXtest_i = np.concatenate((np.ones((Xtest.shape[0], 1)), Xtest), axis=1)\n\nw = learnOLERegression(X, y)\nmle = testOLERegression(w, Xtest, ytest)\n\nw_i = learnOLERegression(X_i, y)\nmle_i = testOLERegression(w_i, Xtest_i, ytest)\n\nprint('MSE without intercept ' + str(mle))\nprint('MSE with intercept ' + str(mle_i))\n\n# Problem 3\nk = 101\nlambdas = np.linspace(0, 1, num=k)\ni = 0\nmses3_train = np.zeros((k, 1))\nmses3 = np.zeros((k, 1))\nfor lambd in lambdas:\n w_l = learnRidgeRegression(X_i, y, lambd)\n mses3_train[i] = testOLERegression(w_l, X_i, y)\n mses3[i] = testOLERegression(w_l, Xtest_i, ytest)\n i = i + 1\nfig = plt.figure(figsize=[12, 6])\nplt.subplot(1, 2, 1)\nplt.plot(lambdas, mses3_train)\nplt.title('MSE for Train Data')\nplt.subplot(1, 2, 2)\nplt.plot(lambdas, mses3)\nplt.title('MSE for Test Data')\nplt.show()\n# Problem 4\nk = 101\nlambdas = np.linspace(0, 1, num=k)\ni = 0\nmses4_train = np.zeros((k, 1))\nmses4 = np.zeros((k, 1))\nopts = {'maxiter': 20} # Preferred value.\nw_init = np.ones((X_i.shape[1], 1))\nfor lambd in lambdas:\n args = (X_i, y, lambd)\n w_l = minimize(regressionObjVal, w_init, jac=True, args=args, method='CG', options=opts)\n w_l = np.transpose(np.array(w_l.x))\n w_l = np.reshape(w_l, [len(w_l), 1])\n mses4_train[i] = testOLERegression(w_l, X_i, y)\n mses4[i] = testOLERegression(w_l, Xtest_i, ytest)\n i = i + 1\nfig = plt.figure(figsize=[12, 6])\nplt.subplot(1, 2, 1)\nplt.plot(lambdas, mses4_train)\nplt.plot(lambdas, mses3_train)\nplt.title('MSE for Train Data')\nplt.legend(['Using scipy.minimize', 'Direct minimization'])\n\nplt.subplot(1, 2, 2)\nplt.plot(lambdas, mses4)\nplt.plot(lambdas, mses3)\nplt.title('MSE for Test Data')\nplt.legend(['Using scipy.minimize', 'Direct minimization'])\nplt.show()\n\n# Problem 5\npmax = 7\nlambda_opt = lambdas[np.argmin(mses4)]\n # REPLACE THIS WITH lambda_opt estimated from Problem 3\nmses5_train = np.zeros((pmax, 2))\nmses5 = np.zeros((pmax, 2))\nfor p in range(pmax):\n Xd = mapNonLinear(X[:, 2], p)\n Xdtest = mapNonLinear(Xtest[:, 2], p)\n w_d1 = learnRidgeRegression(Xd, y, 0)\n mses5_train[p, 0] = testOLERegression(w_d1, Xd, y)\n mses5[p, 0] = testOLERegression(w_d1, Xdtest, ytest)\n w_d2 = learnRidgeRegression(Xd, y, lambda_opt)\n mses5_train[p, 1] = testOLERegression(w_d2, Xd, y)\n mses5[p, 1] = testOLERegression(w_d2, Xdtest, ytest)\n\nfig = plt.figure(figsize=[12, 6])\nplt.subplot(1, 2, 1)\nplt.plot(range(pmax), mses5_train)\nplt.title('MSE for Train Data')\nplt.legend(('No Regularization', 'Regularization'))\nplt.subplot(1, 2, 2)\nplt.plot(range(pmax), mses5)\nplt.title('MSE for Test Data')\nplt.legend(('No Regularization', 'Regularization'))\nplt.show()","sub_path":"Assignment 2/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":10250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"502519813","text":"import flaky\nimport pytest\nfrom yggdrasil.tests import assert_raises, assert_equal\nimport yggdrasil.drivers.tests.test_ConnectionDriver as parent\nfrom yggdrasil import runner, tools\n\n\nclass TestClientParam(parent.TestConnectionParam):\n r\"\"\"Test parameters for ClientDriver class.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(TestClientParam, self).__init__(*args, **kwargs)\n self.driver = 'ClientDriver'\n self.args = None\n self.attr_list += ['comm', 'response_drivers',\n 'request_name', 'request_address']\n # Increased to allow forwarding between IPC comms on MacOS\n # self.timeout = 5.0\n self.route_timeout = 2 * self.timeout\n # self.debug_flag = True\n self.comm_name = tools.get_default_comm()\n self.server_comm = tools.get_default_comm()\n self.icomm_name = self.comm_name\n self.ocomm_name = self.server_comm\n\n @property\n def send_comm_kwargs(self):\n r\"\"\"dict: Keyword arguments for send comm.\"\"\"\n out = self.instance.icomm.opp_comm_kwargs()\n out['comm'] = 'ClientComm'\n return out\n\n @property\n def recv_comm_kwargs(self):\n r\"\"\"dict: Keyword arguments for recv comm.\"\"\"\n out = self.srv_drv.ocomm.opp_comm_kwargs()\n out['comm'] = 'ServerComm'\n return out\n\n @property\n def inst_kwargs(self):\n r\"\"\"dict: Keyword arguments for tested class.\"\"\"\n out = super(TestClientParam, self).inst_kwargs\n # out['request_name'] = self.srv_drv.request_name\n out['comm'] = self.srv_drv.comm\n out['comm_address'] = self.srv_drv.comm_address\n out['icomm_kws']['comm'] = self.comm_name\n return out\n \n def setup(self, *args, **kwargs):\n r\"\"\"Recover new client message on start-up.\"\"\"\n kwargs.setdefault('nprev_comm', self.comm_count)\n self.srv_drv = self.create_server()\n if not self.skip_start:\n self.srv_drv.start()\n super(TestClientParam, self).setup(*args, **kwargs)\n\n def teardown(self):\n r\"\"\"Recover end client message on teardown.\"\"\"\n if hasattr(self, 'srv_drv'):\n self.remove_instance(self.srv_drv)\n delattr(self, 'srv_drv')\n super(TestClientParam, self).teardown()\n\n def create_server(self, comm_address=None):\n r\"\"\"Create a new ServerDriver instance.\"\"\"\n inst = runner.create_driver(\n 'ServerDriver', 'TestServerRequestDriver.' + self.uuid,\n comm=self.server_comm,\n comm_address=comm_address,\n namespace=self.namespace, working_dir=self.working_dir,\n timeout=self.timeout)\n return inst\n\n \nclass TestClientDriverNoStart(TestClientParam,\n parent.TestConnectionDriverNoStart):\n r\"\"\"Test class for ClientDriver class without start.\"\"\"\n\n def test_error_attributes(self):\n r\"\"\"Test error raised when trying to access attributes set on recv.\"\"\"\n err_attr = ['request_id', 'model_response_address']\n for k in err_attr:\n assert_raises(AttributeError, getattr, self.instance, k)\n\n\nclass TestClientDriverNoInit(TestClientParam,\n parent.TestConnectionDriverNoInit):\n r\"\"\"Test class for ClientDriver class without init.\"\"\"\n pass\n \n\nclass TestClientDriver(TestClientParam, parent.TestConnectionDriver):\n r\"\"\"Test class for ClientDriver class.\"\"\"\n\n def setup(self, *args, **kwargs):\n r\"\"\"Wait for drivers to start.\"\"\"\n super(TestClientDriver, self).setup(*args, **kwargs)\n T = self.instance.start_timeout(self.timeout)\n while ((not T.is_out) and ((not self.instance.is_valid)\n or (not self.srv_drv.is_valid))):\n self.instance.sleep() # pragma: debug\n self.instance.stop_timeout()\n\n # # Disabled so that test message is not read by mistake\n # def test_purge(self):\n # r\"\"\"Disabled: Test purge of queue.\"\"\"\n # pass\n\n def test_send_recv(self, msg_send=None):\n r\"\"\"Test routing of a short message between client and server.\"\"\"\n if msg_send is None:\n msg_send = self.test_msg\n T = self.instance.start_timeout(self.timeout)\n while ((not T.is_out) and ((not self.instance.is_valid)\n or (not self.srv_drv.is_valid))):\n self.instance.sleep() # pragma: debug\n self.instance.stop_timeout()\n # Send a message to local output\n flag = self.send_comm.send(msg_send)\n assert(flag)\n # Receive on server side\n flag, srv_msg = self.recv_comm.recv(timeout=self.route_timeout)\n assert(flag)\n assert_equal(srv_msg, msg_send)\n self.instance.printStatus()\n self.srv_drv.printStatus()\n # Send reply back to client\n flag = self.recv_comm.send(srv_msg)\n assert(flag)\n # Receive response on client side\n flag, cli_msg = self.send_comm.recv(timeout=self.route_timeout)\n assert(flag)\n assert_equal(cli_msg, msg_send)\n\n @flaky.flaky(max_runs=3)\n @pytest.mark.timeout(60)\n def test_send_recv_nolimit(self):\n r\"\"\"Test routing of a large message between client and server.\"\"\"\n self.test_send_recv(msg_send=self.msg_long)\n","sub_path":"yggdrasil/drivers/tests/test_ClientDriver.py","file_name":"test_ClientDriver.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"122223561","text":"import zbar\n#from PIL import Image\nimport Image\n\ndef scanQR(name):\n #Creer een nieuwe lezer:\n scanner = zbar.ImageScanner()\n\n #Configureer de lezer:\n scanner.parse_config('enable')\n\n #Lees de gegevens van de afbeelding in:\n pil = Image.open(name).convert('L')\n width, height = pil.size\n raw = pil.tostring()\n\n #Definieer de afbeelding zelf:\n image = zbar.Image(width, height, 'Y800', raw)\n\n #Scan voor QR-codes:\n scanner.scan(image)\n result = ''\n for symbol in image:\n result += str(symbol.data)\n return result\n","sub_path":"Versie 1.1/QR.py","file_name":"QR.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"194855975","text":"##Ask a number and let know it is even or odd.\r\n\r\nnumber = int(input('Enter any number: '))\r\nremainder = number % 2\r\n\r\nif (number == 1 or remainder == 1):\r\n print ('Your '+str(number)+' is a odd number')\r\nelse:\r\n print ('Your number ' +str(number)+' is a even number')\r\n\r\n\r\ninput ('Press anything to exit')\r\n","sub_path":"even_or_odd.py","file_name":"even_or_odd.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"551848635","text":"#! /home/ssac27/anaconda3/envs/hack3/bin/python\n\nimport time\nimport os\n\nimport cv2\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.saved_model import tag_constants\n\n# bounding box utils\nfrom bboxes_utils import * \nimport core.utils as utils\n\n# hand\nfrom hand_webCam import hand_detection\n\n# ROS\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom ros_pub import *\n\n# depth camera \nimport pyrealsense2 as rs\nfrom realsense_depth import *\nfrom depth_cam_distance import depth_action\n\n\n# multiprocessing \nfrom functools import partial\nimport multiprocessing\nfrom multiprocessing import Pool, Process\n\nabsolute_path = os.path.dirname(os.path.abspath(__file__))\n\n\nMODEL_PATH = os.path.join(absolute_path, 'checkpoints/yolov4-tiny-416-small')\nIOU_THRESHOLD = 0.3\nSCORE_THRESHOLD = 0.35\nINPUT_SIZE = 416\n\n\n# load model\nsaved_model_loaded = tf.saved_model.load(MODEL_PATH, tags=[tag_constants.SERVING])\ninfer = saved_model_loaded.signatures['serving_default']\nprint(\"MODEL_PATH : \", MODEL_PATH)\n\nOPENCV_OBJECT_TRACKERS = {\n \"csrt\": cv2.TrackerCSRT_create,\n \"kcf\": cv2.TrackerKCF_create,\n \"boosting\": cv2.TrackerBoosting_create,\n \"mil\": cv2.TrackerMIL_create,\n \"tld\": cv2.TrackerTLD_create,\n \"medianflow\": cv2.TrackerMedianFlow_create,\n \"mosse\": cv2.TrackerMOSSE_create\n}\n\ndef main(video_path,pub):\n # processing\n num_cores = multiprocessing.cpu_count()\n pool = Pool(num_cores)\n\n # Definition of the parameters\n\n iou_ =0.0\n algo = \"csrt\" # 최소 8 ~ 21 \n #algo = \"csrt\" # kcf보다 느리지만 정확도 증가 \n success = False\n #DETECT_AFTER = 100 # 초기 frame 반복당 tracker initialize\n DETECT_AFTER = 35\n frame_number = -1\n pre_frame_chk = frame_number\n\n # 초기 x,y,w,h \n T_W, T_H = 80, 80\n x,y,w,h = 290,190,T_W,T_H\n\n\n # ============ cap read ============\n cap = cv2.VideoCapture(video_path)\n _, frame = cap.read()\n #dc = DepthCamera() \n #ret, _, frame = dc.get_frame()\n \n (H, W) = frame.shape[:2]\n\n # Bounding Box initial \n initBB = ( x, y, w, h)\n hand_initBB = (0,0,0,0)\n pre_initBB = (0,0,0,0)\n \n # OpenCV Traking API \n tracker = OPENCV_OBJECT_TRACKERS[algo]()\n\n # hand variable\n action = ''\n hand_center = (0)\n init_chk = True # 처음 시작 부분 check\n init_first = True # hand 부분만 적용\n\n # ros\n # 차량에 publish 할때의 값\n angular_z_pre = 0.0\n angular_z = 0.0\n linear_x_pre = 0.0\n linear_x = 0.0\n \n occlusion = False\n DIST_AFTER = 2\n\n # PUB_AFTER 만큼 반복 후 발행\n PUB_AFTER = 1\n twist = Twist()\n\n\n\n while cap.isOpened() :\n frame_number+=1\n #ret, depth_frame, frame = dc.get_frame()\n ret, frame = cap.read() # joo.jg 주석 \n if not ret:\n break\n \n\n # cam의 화면과 손의 위치가 동일하게 뒤집어줌\n frame = cv2.flip(frame, 1)\n image_np = np.array(frame)\n\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n frame_input = cv2.resize(image_np, (INPUT_SIZE, INPUT_SIZE))\n frame_input = frame_input / 255.\n frame_input = frame_input[np.newaxis, ...].astype(np.float32)\n frame_input = tf.constant(frame_input)\n start_time = time.time()\n\n # model에 frame input을 넣어서 예측\n pred_bbox = infer(frame_input)\n\n for key, value in pred_bbox.items():\n boxes = value[:, :, 0:4]\n pred_conf = value[:, :, 4:]\n\n # tf.image.combined_non_max_suppression \n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\n scores=tf.reshape(\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\n max_output_size_per_class=35,\n max_total_size=35,\n iou_threshold=IOU_THRESHOLD,\n score_threshold=SCORE_THRESHOLD\n )\n\n\n # 데이터를 numpy 요소로 변환 및 사용하지 않는 요소는 잘라낸다. \n num_objects = valid_detections.numpy()[0]\n bboxes = boxes.numpy()[0]\n bboxes = bboxes[0:int(num_objects)]\n scores = scores.numpy()[0]\n scores = scores[0:int(num_objects)]\n classes = classes.numpy()[0]\n classes = classes[0:int(num_objects)]\n\n # ymin, xmin, ymax, xmax ---> xmin, ymin, width, height\n original_h, original_w, _ = frame.shape\n bboxes = utils.format_boxes(bboxes, original_h, original_w)\n\n\n # ========== person detection end ===================\n # ================ hand detection start ===============\n\n img = frame.copy()\n \n if init_first and num_objects ==1:\n\n # move or stop 동작을 받아야 다음 step 가능\n\n if action == '' :\n x_min, y_min = bboxes[0][:2]\n #y_min = int(max(y_min-20, 0)); x_min = int(max(x_min-10, 0))\n action, (hand_x, hand_y, hand_w, hand_h) = hand_detection(cap, x_min, y_min)\n\n hand_center = (hand_x + hand_w//2)\n\n\n # =============== hand detection end =================\n # tracker 초기화\n # get_coordinates(bbox, 해당 bbox 안에 추적을 할 bounding_box)\n # bboxes : x_min, y_min, x_max, y_max [사람의 bounding box]\n \n hand_initBB, trueBB,iou_ = get_coordinates(bboxes, x_min, y_min, (hand_x + hand_w) , ( hand_y+hand_h) )\n hand_initBB = tuple(map( int, hand_initBB) )\n \n # 시작 hand bbox를 initBB로 초기화 해준다.\n pre_initBB = ( hand_initBB[0] + hand_initBB[2]//2 , hand_initBB[1] + hand_initBB[3]//2 ) #, hand_initBB[2], hand_initBB[3] )\n \n tracker.init(frame, hand_initBB)\n \n (success, box) = tracker.update(frame)\n if success :\n (x, y, w, h) = [int(v) for v in box]\n cv2.rectangle(frame, (x, y), (x + w, y + h),(255, 0, 120), 2)\n cv2.putText(frame, f\"hand tracking\", (x + w//2, y+h +10), cv2.FONT_HERSHEY_SIMPLEX,1,(255, 120, 120), 2)\n pred_bbox = [bboxes, scores, classes, num_objects]\n result = utils.draw_bbox(frame, pred_bbox,pub)\n\n init_first = False\n\n\n # 100 frame 단위로 DETECT trackes 확인 DETEVTER\n if not init_first and frame_number % DETECT_AFTER == (DETECT_AFTER-1) or not success :\n if num_objects>=1 :\n\n new_bboxes = get_box_distance(bboxes, [x, y, x+w, y+h], W)\n\n # ========================== process test _coordi (start) =========================\n\n func = partial(get_coordinates, new_bboxes, x, y, x+w )\n temp = pool.map(func , [y+h] )\n initBB, trueBB,iou_ = temp[-1]\n\n # ========================== process test _coordi (end) =========================\n\n initBB = tuple(map( int, initBB) )\n trueBB = tuple(map( int, trueBB) )\n\n\n # ==== 06.22 ===========\n # initBB 수정 전 rectangle\n cv2.putText(img, f\"iou_scores : {iou_} \" , (initBB[0] , initBB[1] ) , cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 0), 2)\n # 기존 tracker initBOX와 사람의 bbox를 기준으로 한 initBB 비교가 필요한 경우 아래 주석 해제 \n #cv2.rectangle(img, (initBB[0], initBB[1]), (initBB[0] + initBB[2], initBB[1] + initBB[3]),(255, 255, 0), 2)\n #cv2.putText(img, f\"old initBB box : {initBB} \", ( (initBB[0] ) , ( initBB[1] -20 ) ), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (102, 160, 145), 2)\n cv2.rectangle(img, (trueBB[0], trueBB[1]), (trueBB[0] + trueBB[2], trueBB[1] + trueBB[3]),(255, 255, 0), 2)\n\n\n init_hand_coorect = -1* ( W//2 - hand_center )//2\n\n if init_chk:\n initBB = ( trueBB[0] + (trueBB[2]//2) - T_W//2 + init_hand_coorect ), ( trueBB[1] + (trueBB[3]//2) - T_H//2) , T_W, T_H #, initBB[2], initBB[3] \n else : \n initBB = ( trueBB[0] + (trueBB[2]//2) - T_W//2 ), ( trueBB[1] + (trueBB[3]//2) - T_H//2) , initBB[2], initBB[3]#, T_W, T_H \n\n\n print(f\"new initBB :\", initBB)\n cv2.rectangle(img, (initBB[0], initBB[1]), (initBB[0] + initBB[2], initBB[1] + initBB[3]),(147, 200, 100), 2)\n cv2.putText(img, f\"new initBB box : {initBB} \", ( (initBB[0] + initBB[2] - 30) , ( initBB[1] + initBB[3]+20 ) ), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (102, 160, 145), 2)\n cv2.imshow('yolo', cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n\n tracker = OPENCV_OBJECT_TRACKERS[algo]()\n\n tracker.init(frame, initBB)\n\n if not init_first :\n\n (success, box) = tracker.update(frame)\n\n \n depth_dist = 0\n \n if success :\n (x, y, w, h) = [int(v) for v in box]\n #x = min(W,x+10); y = max(0,y-10)\n cv2.rectangle(frame, (x, y), (x + w, y + h),(255, 0, 120), 2)\n \n if len(box) <1 :\n print(\" 사람이 없습니다. \")\n \n # update 하기 위한 initBB \n diff_dist = round( np.linalg.norm( ((pre_initBB[0]) /W) - ((x+ w//2)/W) ),2)\n if diff_dist > 0.23 :#and DIST_AFTER:\n print(\"track bounding box 위치 문제 발생\") \n x = pre_initBB[0]\n y = pre_initBB[1] \n\n\n # depth로 범위 안에 포함되는지 와 거리 가져온다.\n cv2.putText(frame, f\"current : \", (x + w//2, y+h +10), cv2.FONT_HERSHEY_SIMPLEX,1,(255, 120, 120), 2)\n\n pred_bbox = [bboxes, scores, classes, num_objects]\n result = utils.draw_bbox(frame, pred_bbox)\n\n # ========================== process pool _move (start) =========================\n \n func = partial(get_move, W//2, x+(w//2), hand_center )\n temp = pool.map(func , [init_chk] )\n twist,angular_z, linear_x = temp[-1]\n \n # ========================== process pool _move (end) =========================\n init_chk= False\n \n ln_bboxes = len(bboxes) \n # depth cam으로 쟀을때 거리가 만족되는 경우 \n\n\n # =================== 21.06.19 수정 =============\n if ln_bboxes >=1 :\n pre_frame_chk = frame_number\n\n if abs(angular_z_pre) - abs(angular_z) > 0.3 :#\n print(f\"occlusion 발생 : {occlusion }\")\n occlusion = not occlusion\n # ----- 2021 06 - 19 코드 수정 ----\n time_wait_pub(0.01, pub,linear= 0, angular= angular_z_pre/2)\n occlusion = False\n elif not occlusion :#and ok:\n print(\" not occlusion, 정상 publish\")\n # 매 frame마다 발행이 아닌 일정 반복마다 발행\n if frame_number % PUB_AFTER == (PUB_AFTER-1) : \n pub.publish(twist)\n\n\n elif ln_bboxes < 1 :\n # 사람이 없는 경우 stop\n twist.linear.x = 0.0\n twist.angular.z = 0.0\n pub.publish(twist)\n\n occlusion = False\n\n angular_z_pre = angular_z\n #linear_x_pre = linear_x\n pre_initBB = (initBB[0]+ initBB[2]//2 , initBB[1] + initBB[3]//2 ) # , initBB[2], initBB[3]) \n # calculate frames per second of running detections\n fps = 1.0 / (time.time() - start_time)\n print(\"FPS: %.2f\" % fps)\n\n\n result = np.asarray(frame)\n result = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n cv2.imshow('result', result)\n key = cv2.waitKey(1)\n if key == ord('q') or key == 27:\n #dc.release()\n cap.release()\n pool.close()\n pool.join()\n break\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n \n rospy.init_node('scout_ros_detector_test', anonymous=False)\n pub = rospy.Publisher('/cmd_vel', \n Twist, \n queue_size=10)\n video_path = -1\n main(video_path,pub)\n\n","sub_path":"src/scripts/cv_tracking_hand_webCam_final.py","file_name":"cv_tracking_hand_webCam_final.py","file_ext":"py","file_size_in_byte":12454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"558023001","text":"\"\"\"\n******************************************************************************\n* Purpose :To take two strings as input such keep and peek and check for anagrams.\n*\n* @description:A anagram program for one string is anagrams of another if the second\n* is simply a rearrangment of the first.\n* @author : hemavathi B.V <>\n* @version : 3.7\n* @since : 15-feb-2019\n*\n******************************************************************************\n\"\"\"\nfrom Utility.UtilityTest import Programs\n\naccess = Programs.Program\n\nclass anagramString:\n try:\n string1 = str(input(\"Enter The First String :\")) # Read First String\n string2 = str(input(\"Enter The Second String :\")) # Read Second String\n\n\n access.checkAnagram(string1, string2) # Invoking function it takes Two arguments As String\n\n except ValueError:\n print(\"oops Something Went Wrong\")","sub_path":"algorithmPrograms/anagramString.py","file_name":"anagramString.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"243876073","text":"import json\nfrom pupil import Pupil\n\n\ndef get_int(prompt):\n while True:\n try:\n value = int(input(prompt))\n break\n except:\n print(\"Wrong input!\")\n continue\n return value\n\n\nclass Pupils:\n def __init__(self) -> None:\n try:\n with open(\"pupils.json\") as f:\n pupils_list = json.load(f)\n\n self.pupils = []\n for pupil_dict in pupils_list:\n p = Pupil()\n p.from_dict(pupil_dict)\n self.pupils += [p]\n\n except FileNotFoundError:\n self.pupils = []\n\n def __str__(self) -> str:\n st = \"\"\n for pupil in self.pupils:\n st += \"\\n\" + \"=\" * 15\n st += str(pupil)\n return st\n\n def save_pupils_data(self):\n list_to_write = []\n for pupil in self.pupils:\n list_to_write += [pupil.to_dict()]\n with open(\"pupils.json\", \"w\") as f:\n json.dump(list_to_write, f)\n\n def next_id(self):\n if not self.pupils:\n return 1001\n else:\n ids = []\n for p in self.pupils:\n ids.append(p.pupil_id)\n return max(ids) + 1\n\n def create_pupil(self):\n first_name = input(\"Give name: \")\n last_name = input(\"Give surname: \")\n fathers_name = input(\"Give father's name: \")\n\n for p in self.pupils:\n if first_name == p.first_name and last_name == p.last_name and fathers_name == p.fathers_name:\n print(\"This pupil already exists.\")\n ch = input(\"Do you want to continue? (y-yes, n-no): \")\n if ch == \"n\":\n return None\n\n age = get_int(\"Give age: \")\n class_name = get_int(\"Give class: \")\n id_card = input(\"Does he/she has an id card: (y-yes, n-no): \")\n if id_card == \"y\":\n id_number = input(\"give id card number: \")\n else:\n id_number = None\n pupil = Pupil(first_name, last_name, fathers_name, age,\n class_name, id_number, self.next_id())\n\n self.pupils.append(pupil)\n return pupil\n\n def pupil_update(self, pupil):\n print(pupil)\n print(\"=\" * 15)\n print(\"1-name\")\n print(\"2-surname\")\n print(\"3-father's name\")\n print(\"4-age\")\n print(\"5-class\")\n print(\"6-id number\")\n print(\"=\" * 15)\n update_choice = get_int(\"Pick something to update: \")\n if update_choice == 1:\n pupil.first_name = input(\"Give new name: \")\n elif update_choice == 2:\n pupil.last_name = input(\"Give new surname: \")\n elif update_choice == 3:\n pupil.fathers_name = input(\"Give new father's name: \")\n elif update_choice == 4:\n pupil.age = get_int(\"Give age: \")\n elif update_choice == 5:\n pupil.class_name = input(\"Give new class: \")\n elif update_choice == 6:\n pupil.id_number = input(\"Give new id number: \")\n\n print(\"=\" * 15)\n print(pupil)\n print(\"Pupil updated! \")\n\n def delete_pupil_by_id(self, pupil_id, lessons):\n for i in range(len(self.pupils)):\n if pupil_id == self.pupils[i].pupil_id:\n self.pupils.pop(i)\n print(\"Pupil deleted!\")\n for lesson in lessons.lessons:\n if pupil_id in lesson.pupil_ids:\n lesson.pupil_ids.remove(pupil_id)\n return\n else:\n print(\"No student with this id!\")\n\n def search_pupil_by_surname(self, last_name):\n match_pupils = []\n for pupil in self.pupils:\n if last_name == pupil.last_name:\n match_pupils.append(pupil)\n return match_pupils\n\n def search_pupil_by_id(self, pupil_id):\n for pupil in self.pupils:\n if pupil_id == pupil.pupil_id:\n return pupil\n return None\n\n def print_pupils_names(self):\n for pupil in self.pupils:\n print(\n f\"{pupil.first_name} {pupil.fathers_name}. {pupil.last_name}\")\n","sub_path":"Projects/DATAPROJECT/pupils.py","file_name":"pupils.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"63264166","text":"__author__ = 'Florian Rouyer'\n\nimport glob\nimport time\n\n\n################# Fonctions ###########################\n\n# Liste les entit? pr?sentes dans le fichier entity_list.txt pour en retourner une liste\ndef listEntity():\n entity = open('entity_list.txt')\n list = []\n list = entity.readlines()\n return list\n\n# Liste le repertoire des fichiers pr?sents dans /\ndef listrepertoire():\n list = glob.glob('Wikipedia_corpus/*.txt')\n return list\n\n# Prend en parametre une liste d'entit? et la formate pour associer dans une map les uri ainsi que le nom correspondant\ndef getEntity(listEntity):\n final = {}\n for entity in listEntity:\n personne = entity.split(\"/\")\n personne.reverse()\n val = personne[0].split(\",\")\n final[val[0].replace(\"_\", \" \")] = entity\n return final\n\ndef getNomComplet(elem):\n nomComplet = elem.split(\"(\")[0]\n nomComplet = nomComplet.split(\"\\n\")[0]\n return nomComplet\n\ndef getNom(elem):\n nom = elem.split(\"(\")[0]\n nom = nom.split(\"\\n\")[0]\n nom = nom.split(\" \")\n for i in range(nom.count('')): nom.remove('') # suppression des espaces de la liste\n taille = len(nom)\n if taille == 1:\n nom = nom\n else:\n nom = nom[1:taille]\n nom = ' '.join(nom)\n return nom\n\ndef getPrenom(elem):\n prenom = elem.split(\"(\")[0]\n prenom = prenom.split(\"\\n\")[0]\n prenom = prenom.split(\" \")[0]\n return prenom\n\ndef getBirthday():\n final = {}\n for fichier in listrepertoire():\n fichier = open(fichier)\n texte = fichier.read()\n foo = texte.split(\"(\")\n foo2 = foo[1].split(\")\")\n foo3 = foo2[0].split(\";\")\n foo3.reverse()\n foo = foo3[0].split(\"born\")\n foo.reverse()\n foo2 = foo[0].split(\"in\")\n foo3 = foo2[0].split(\"\\xe2\\x80\\x93\")\n final[fichier.name.split(\".\")[0].replace(\"_\",\" \")] = foo3[0]\n fichier.close()\n return final\n\n################## Debut du programme #####################\n\n\n\nbirthday = getBirthday()\nmap = getEntity(listEntity())\n\nfichierAniverssaire = open(\"result/birthday.txt\", \"w\")\n\nfor fichier in listrepertoire():\n fichierCourant = open(fichier)\n texteCourant = fichierCourant.read()\n fichierCourant.close()\n\n texte = \"\"\n\n for elem in map:\n nomComplet = getNomComplet(elem)\n\n while nomComplet in texteCourant:\n start = texteCourant.index(nomComplet)\n end = len(nomComplet) + start\n strStart = \" \"\n strEnd = \" \"\n fichierAniverssaire.write(strStart)\n fichierAniverssaire.write(\"\\n\")\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n texte = \"\"\n\n for elem in map:\n prenom = getPrenom(elem)\n prenom = \" \"+prenom+\" \"\n\n\n while prenom in texteCourant:\n start = texteCourant.index(prenom)\n end = len(prenom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n texte = \"\"\n\n for elem in map:\n nom = getNom(elem)\n nom = \" \"+nom+\" \"\n\n while nom in texteCourant:\n start = texteCourant.index(nom)\n end = len(nom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n\n texte = texte + texteCourant\n texteCourant = texte\n texte =\"\"\n\n for elem in map:\n prenom = \" he \"\n\n while prenom in texteCourant:\n start = texteCourant.index(prenom)\n end = len(prenom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n texte = \"\"\n\n for elem in map:\n prenom = \" He \"\n\n while prenom in texteCourant:\n start = texteCourant.index(prenom)\n end = len(prenom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n texte = \"\"\n\n for elem in map:\n prenom = \" she \"\n\n while prenom in texteCourant:\n start = texteCourant.index(prenom)\n end = len(prenom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n texte = \"\"\n\n for elem in map:\n prenom = \" She \"\n\n while prenom in texteCourant:\n start = texteCourant.index(prenom)\n end = len(prenom) + start\n strStart = \" \"\n strEnd = \" \"\n texte = texte + texteCourant[:start]+strStart+texteCourant[start:end]+strEnd\n texteCourant = texteCourant[end:]\n\n texte = texte + texteCourant\n texteCourant = texte\n\n result = open('result/'+fichierCourant.name.split(\"/\")[1], \"w\")\n result.write(texte)\n result.close()\n\nfichierAniverssaire.close()\n","sub_path":"exercice2.py","file_name":"exercice2.py","file_ext":"py","file_size_in_byte":6706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"286701850","text":"import torch\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport numpy as np\n\ndata_path = '/nas/longleaf/home/deep/Academics/Duke/Statistics790/data/cifar10'\ncifar10_train = datasets.CIFAR10(data_path, train=True, download=False, transform=transforms.ToTensor())\ncifar10_test = datasets.CIFAR10(data_path, train=True, download=False, transform=transforms.ToTensor())\n\n# This section is ONLY for debugging on a smaller dataset\n# N_train is training sample size; N_test is test sample size;\n\nN_train, N_test = len(cifar10_train), len(cifar10_test)\n#N_train, N_test = 5000, 1000\n\n\n# Scale variables\ncifar10_train.data = cifar10_train.data[0:N_train,:,:,:]\ncifar10_train.targets = np.array(cifar10_train.targets[0:N_train]).astype(float)\ncifar10_test.data = cifar10_test.data[0:N_test,:,:,:]\ncifar10_test.targets = np.array(cifar10_test.targets[0:N_test]).astype(float)\n\ncifar10_test_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=64, shuffle=False)\n\n# Convert to tensors\ncifar10_train_data = torch.from_numpy(cifar10_train.data)\ncifar10_train_targets = torch.from_numpy(cifar10_train.targets)\ncifar10_test_data = torch.from_numpy(cifar10_test.data)\ncifar10_test_targetrs = torch.from_numpy(cifar10_test.targets)\n\n# Get permuted indices then concatenate to create a longer list to allow for cycling through images\na = torch.randperm(N_train)\nb = torch.randperm(N_train)\nc = torch.randperm(N_train)\n\ntrain_indices = torch.cat((a, b, c), 0)\n\n# D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nD_in, H, D_out = 3072, 1024, 10\n\n# Instantiate a model and define loss function\n\nmodel = nn.Sequential(\n nn.Linear(D_in, H),\n nn.ReLU(),\n nn.Linear(H, H),\n nn.ReLU(),\n nn.Linear(H, D_out))\n\nloss_fn = nn.CrossEntropyLoss()\n\n# Define parameters for adaptive learning rate\neps0 = 0.01\nepstau = 0.01*eps0\ntau = 300\nk = 0\n\n# Variables to set up and interate through batches\n#numbatches = [10, 15, 20, 25, 5]\nnumbatches = [100, 150, 200, 250, 50]\nsizes = [32, 64, 128, 256, 512]\ncounter = 0\n\n# Train model\n\nfor n,s in zip(numbatches, sizes):\n for j in range(n):\n k += 1\n get = train_indices[counter:counter+s]\n counter += s\n \n # create batch \n input_batch = cifar10_train_data[get]\n target_batch = cifar10_train_targets[get]\n input_batch = torch.reshape(input_batch,[s,-1])\n outputs = model(input_batch.float())\n \n # compute loss and do back prop\n loss = loss_fn(outputs, target_batch.long())\n\n if k>tau:\n alpha_k = 1\n else:\n alpha_k = k / tau\n learning_rate = (1 - alpha_k)*eps0 + alpha_k*epstau\n optimizer = optim.SGD(model.parameters(), lr=learning_rate)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n # evaluate accuracy on test data\n correct = 0\n total = 0\n\n with torch.no_grad():\n for imgs, targets in cifar10_test_loader:\n batch_size = imgs.shape[0]\n outputs = model(imgs.view(batch_size, -1))\n _, predicted = torch.max(outputs, dim=1)\n total += targets.shape[0]\n correct += int((predicted == targets.long()).sum())\n \n \n print(\"Number of batches: %d, Batch size: %d, Loss: %f, Accuracy: %f\" % (n,s,float(loss),float(correct/total)))\n","sub_path":"hw3/ffn_cifar10_hw3.py","file_name":"ffn_cifar10_hw3.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"430337916","text":"from administrator.views import AmbassadorAPIView\nfrom rest_framework import serializers\nfrom rest_framework.permissions import IsAuthenticated\nfrom common.authentication import JWTAuthentication\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.cache import cache_page\n\nfrom core.models import Link, Product, Order, User\nfrom .serializers import LinkSerializer, ProductSerializer\nfrom django.core.cache import cache\nimport time\nimport math\nimport random, string\nfrom django_redis import get_redis_connection\n\n\nclass ProductFrontendAPIView(APIView):\n @method_decorator(cache_page(60*60*2, key_prefix='products_frontend')) # 2 hours\n def get(self, _):\n products = Product.objects.all()\n serializer = ProductSerializer(products, many=True)\n return Response(serializer.data)\n\n\nclass ProductBackendAPIView(APIView):\n\n def get(self, request):\n products = cache.get('products_backend')\n if not products:\n time.sleep(2) # 2 seconds for mimic the delay\n products = list(Product.objects.all())\n cache.set('products_backend', products, timeout=60*30) # 30 minutes\n\n # search products\n s = request.query_params.get('s', '').lower()\n if s:\n products = list([\n p for p in products\n if (s in p.title.lower()) or (s in p.description.lower())\n ])\n\n total = len(products)\n\n # sort products\n sort = request.query_params.get('sort', None)\n if sort == 'asc':\n products.sort(key=lambda p: p.price)\n elif sort == 'desc':\n products.sort(key=lambda p: p.price, reverse=True)\n\n # paginate products\n per_page = 9\n page = int(request.query_params.get('page', 1))\n start = (page -1) * per_page\n end = page * per_page\n\n data = ProductSerializer(products[start:end], many=True).data\n return Response({\n 'data': data,\n 'meta': {\n 'total': total,\n 'page': page,\n 'last_page': math.ceil(total / per_page)\n }\n })\n\n\nclass LinkAPIView(APIView):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticated]\n\n def post(self, request):\n user = request.user\n\n serializer = LinkSerializer(data={\n 'user': user.id,\n 'code': ''.join(random.choices(string.ascii_letters + string.digits, k=6)),\n 'products': request.data['products']\n })\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n return Response(serializer.data)\n\n\nclass StatsAPIView(APIView):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n user = request.user\n\n links = Link.objects.filter(user_id=user.id)\n\n return Response([self.format(link) for link in links])\n\n def format(self, link):\n orders = Order.objects.filter(code=link.code, complete=1)\n\n return {\n 'code': link.code,\n 'count': len(orders),\n 'revenue': sum (o.ambassador_revenue for o in orders)\n }\n\n\nclass RankingsAPIView(APIView):\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n con = get_redis_connection(\"default\")\n rankings = con.zrevrangebyscore('rankings', min=0, max=10000, withscores=True)\n\n return Response({\n r[0].decode(\"utf-8\"): r[1] for r in rankings\n })\n\n # ambassadors = User.objects.filter(is_ambassador=True)\n\n # response = list({\n # 'name': a.name,\n # 'revenue': a.revenue\n # } for a in ambassadors) # not object list\n\n # response.sort(key=lambda a: a['revenue'], reverse=True)\n\n # return Response(response)\n\n\n\n\n\n\n ","sub_path":"ambassador/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"85701072","text":"# -*- coding: utf-8 -*-\nimport sys\nimport unittest\nfrom io import StringIO\nfrom unittest import mock\nfrom datetime import datetime\n\nfrom pripara.user import Datetime, Str, Int, NOT_LOGGED_IN\n\n\nclass DatetimeTest(unittest.TestCase):\n def _makeOne(self):\n return Datetime()\n\n def test_initial(self):\n sbj = self._makeOne()\n self.assertIsNone(sbj.value)\n\n def test_with_valid_value(self):\n sbj = self._makeOne()\n sbj.value = '2017年1月10日'\n self.assertEqual(sbj.value, datetime(2017, 1, 10))\n\n def test_with_none(self):\n sbj = self._makeOne()\n sbj.value = None\n self.assertIsNone(sbj.value)\n\n def test_raise_with_invalid_format(self):\n sbj = self._makeOne()\n with self.assertRaises(ValueError):\n sbj.value = '2017/1/10'\n\n\nclass StrTest(unittest.TestCase):\n def _makeOne(self):\n return Str()\n\n def test_initial(self):\n sbj = self._makeOne()\n self.assertEqual(sbj.value, '')\n\n def test_with_valid_value(self):\n sbj = self._makeOne()\n v = 'hoge'\n sbj.value = v\n self.assertEqual(sbj.value, v)\n\n def test_raise_with_not_str(self):\n sbj = self._makeOne()\n with self.assertRaises(TypeError):\n sbj.value = 1\n\n def test_raise_with_none(self):\n sbj = self._makeOne()\n with self.assertRaises(TypeError):\n sbj.value = None\n\n def test_with_value_includes_spaces_at_both_edges(self):\n sbj = self._makeOne()\n v = 'hoge'\n sbj.value = f' {v} '\n self.assertEqual(sbj.value, v)\n\n\nclass IntTest(unittest.TestCase):\n def _makeOne(self):\n return Int()\n\n def test_initial(self):\n sbj = self._makeOne()\n self.assertEqual(sbj.value, 0)\n\n def test_with_valid_value(self):\n sbj = self._makeOne()\n v = 10\n sbj.value = v\n self.assertEqual(sbj.value, v)\n\n def test_raise_with_not_digit_str(self):\n sbj = self._makeOne()\n with self.assertRaises(TypeError):\n sbj.value = 'hoge'\n\n def test_with_digit_str(self):\n sbj = self._makeOne()\n v = '10'\n sbj.value = v\n self.assertEqual(sbj.value, int(v))\n\n def test_with_none(self):\n sbj = self._makeOne()\n sbj.value = None\n self.assertIsNone(sbj.value)\n\n\nclass UserTest(unittest.TestCase):\n def setUp(self):\n self.capture = StringIO()\n sys.stdout = self.capture\n self.email = 'mirei@pripara.com'\n self.password = 'puri'\n self.login_response = {\n 'play_data_date': '2017年10月1日',\n 'name': 'みれぃ',\n 'teammate': 100,\n 'id': 3,\n 'rank': '神アイドル',\n 'like': 1000000,\n 'weekly_ranking': 1,\n 'weekly_total': 1,\n }\n\n def tearDown(self):\n sys.stdout = sys.__stdout__\n\n def _makeOne(self, logged_in=False):\n with mock.patch('pripara.user.Config') as ConfigMock, \\\n mock.patch('pripara.user.Client') as ClientMock:\n ConfigMock().load = mock.Mock(return_value=None)\n ConfigMock().as_dict = mock.Mock(return_value={\n 'email': self.email,\n 'password': self.password,\n })\n ClientMock().login = mock.Mock(return_value=self.login_response)\n ClientMock().logged_in = mock.Mock(return_value=logged_in)()\n from pripara.user import User\n return User()\n\n def test_init(self):\n sbj = self._makeOne()\n for f in sbj.field_names:\n with self.subTest(f=f):\n self.assertTrue(hasattr(sbj, f'_{f}'))\n\n def test_login(self):\n sbj = self._makeOne(logged_in=True)\n sbj.login()\n for k, v in self.login_response.items():\n with self.subTest(k=k):\n if k == 'play_data_date':\n self.assertEqual(getattr(sbj, k), datetime.strptime(v, '%Y年%m月%d日'))\n continue\n self.assertEqual(getattr(sbj, k), v)\n\n def test_as_dict_before_login(self):\n sbj = self._makeOne()\n for field, T in sbj.fields:\n with self.subTest(field=field, T=T):\n self.assertEqual(getattr(sbj, field), T.default)\n\n def test_as_dict_after_login(self):\n sbj = self._makeOne(logged_in=True)\n sbj.login()\n expect = self.login_response.copy()\n expect['play_data_date'] = datetime.strptime(self.login_response['play_data_date'], '%Y年%m月%d日')\n self.assertEqual(sbj.as_dict(), expect)\n\n def test_info_before_login(self):\n sbj = self._makeOne()\n sbj.info\n self.assertEqual(self.capture.getvalue(), f'{NOT_LOGGED_IN}\\n')\n\n def test_info_after_login(self):\n sbj = self._makeOne(logged_in=True)\n sbj.login()\n self.capture.seek(0)\n self.capture.write('')\n sbj.info\n result = self.capture.getvalue().split('\\n')\n self.assertEqual(result[0], 'User data')\n self.assertEqual(result[1], f'-- As of {sbj.play_data_date.strftime(\"%Y/%m/%d\")} --')\n self.assertEqual(result[2], f'id:\\t{sbj.id}')\n self.assertEqual(result[3], f'name:\\t{sbj.name}')\n self.assertEqual(result[4], f'teammate:\\t{sbj.teammate}')\n self.assertEqual(result[5], f'rank:\\t{sbj.rank}')\n self.assertEqual(result[6], f'like:\\t{sbj.like}')\n self.assertEqual(result[7], f'weekly ranking:\\t{sbj.weekly_ranking}')\n self.assertEqual(result[8], f'weekly total:\\t{sbj.weekly_total}')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":5662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"282806667","text":"#----------------------------------------\n#--------- Torch Related Imports --------\n#----------------------------------------\nimport torch\nimport torch.distributed as distributed\n\n#----------------------------------------\n#--------- Local Imports ----------------\n#----------------------------------------\nfrom common.metrics.basic_metrics import ValAccuracyMetric\n\nclass ValMetrics():\n def __init__(self, config, allreduce=False):\n self.all_metrics = {}\n self.allreduce = allreduce\n\n def store(self, metric_name, metric_value, metric_type='Accuracy'):\n if metric_name not in self.all_metrics:\n # initialize a new metric\n self.all_metrics[metric_name] = eval(f'Val{metric_type}Metric')(metric_value, allreduce=self.allreduce)\n else:\n self.all_metrics[metric_name].update(metric_value)\n\n def wandb_log(self, step, use_wandb):\n if use_wandb:\n for metric_name, metric in self.all_metrics.items():\n metric.wandb_log(metric_name, step)\n","sub_path":"common/metrics/val_metrics.py","file_name":"val_metrics.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"630317894","text":"import pytest\nfrom pip._vendor import requests\nimport re\n\nfrom common.yaml_util import write_yaml, read_yaml\n\n\nclass TestApi:\n #111 access_token = \"\"\n global_token= \"\"\n session = requests.session()#会话\n\n # 必须带请求头,需要正则表达式,处理cookie鉴权以及session鉴权\n def test_get_token(self):\n url = \"https://demopmapi.liangyihui.net/official/login\"\n data = {\n \"alipayId\":\"2088042142174230\"\n }\n res = TestApi.session.request(\"post\",url=url,json=data)\n extract_data = {\"access_token\":res.json()['data']}\n write_yaml(extract_data)\n #111 result_value =res.text\n print(res.text)\n\n def test_search_review(self):\n url = \"https://demopmapi.liangyihui.net/official/patient/review\"\n data = {\n \"pageSize\": 10,\n \"direction\": 0,\n \"reviewDt\": \"\",\n \"access_token\":read_yaml(\"access_token\")\n }\n # header = {\n # \"access_token\":read_yaml(\"access_token\")\n # }\n res = TestApi.session.request(\"post\",url=url,data=data)\n print(res.json())\n\n\n\n\n\n\nif __name__ == '__main__':\n pytest.main(['-vs'])\n\n","sub_path":"testcases/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"473273095","text":"import time\nimport unittest\nimport numpy as np\nfrom StatisticalLearning.Feature.Kernel import Kernel\n\n\nclass TEST_Kernel(unittest.TestCase):\n\n def setUp(self):\n\n self._x = np.array([1, 2, 3])\n self._y = np.array([2, 3, 4])\n\n def test_kernel(self):\n self.assertEqual(Kernel.linear(self._x, self._y), 20)\n self.assertEqual(Kernel.polynomial(self._x, self._y), 20)\n self.assertEqual(Kernel.gaussian(self._x, self._y, sigma=1), np.exp(-1.5))\n self.assertEqual(Kernel.exponential(self._x, self._y, sigma=1), np.exp(-np.sqrt(3) / 2))\n self.assertEqual(Kernel.epanechnikov(self._x, self._y, sigma=1), 0)\n self.assertEqual(Kernel.tri_cube(self._x, self._y, sigma=1), 0)\n\n def test_njit(self):\n X = np.random.rand(1000, 10)\n Y = np.random.rand(1000, 10)\n\n # Compilation step\n Kernel.gaussian(X[0], Y[0], sigma=1)\n\n # With not-just-in-time\n start = time.time()\n for x, y in zip(X, Y):\n Kernel.gaussian(x, y, sigma=1)\n end = time.time()\n\n # Without compilation, expected time is 0.02 seconds\n self.assertTrue(end - start < 1e-8)\n\n\n\n\n","sub_path":"StatisticalLearning/UnitTest/TEST_Kernel.py","file_name":"TEST_Kernel.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"187551842","text":"# Copyright (c) 2016-2023 Association of Universities for Research in Astronomy, Inc. (AURA)\n# For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause\nfrom scheduler.graphql_mid.server import schema\nfrom lucupy.observatory.abstract import ObservatoryProperties\nfrom lucupy.observatory.gemini import GeminiProperties\n\n\ndef test_schedule_query():\n ObservatoryProperties.set_properties(GeminiProperties)\n query = \"\"\"\n query getNightPlans {\n schedule(newScheduleInput: {startTime: \"2018-10-01 08:00:00\",\n \t\t\t\t endTime: \"2018-10-03 08:00:00\",\n \t\t\t\t numNightsToSchedule: 3,\n \t\t\t\t site: \"ALL_SITES\"}) {\n nightPlans {\n nightIdx\n plansPerSite {\n endTime\n site\n startTime\n visits {\n atomEndIdx\n atomStartIdx\n obsId\n startTime\n }\n }\n }\n }\n }\n \"\"\"\n result = schema.execute_sync(query)\n assert result is not None\n result_data = result.data\n assert result_data is not None\n assert 'schedule' in result_data\n schedule = result_data['schedule']\n assert schedule is not None\n assert 'nightPlans' in schedule\n night_plans = schedule['nightPlans']\n assert night_plans is not None\n assert len(night_plans) >= 1\n night_plan = night_plans[0]\n assert night_plan is not None\n assert 'plansPerSite' in night_plan\n plan_per_site = night_plan['plansPerSite']\n assert plan_per_site is not None\n assert len(plan_per_site) >= 0\n plan = plan_per_site[0]\n assert plan is not None\n","sub_path":"tests/unit/scheduler/graphql_mid/test_graphql_queries.py","file_name":"test_graphql_queries.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"199707471","text":"\"\"\" Data collection pipeline \"\"\"\nimport logging\nfrom io import BytesIO\nfrom pathlib import Path\nfrom typing import List, Union, Optional, Tuple\n\nfrom datetime import datetime\nimport pandas as pd\n\nfrom wetterdienst.additionals.functions import (\n check_parameters,\n parse_enumeration_from_template,\n create_humanized_column_names_mapping,\n)\nfrom wetterdienst.enumerations.column_names_enumeration import DWDMetaColumns\nfrom wetterdienst.enumerations.parameter_enumeration import Parameter\nfrom wetterdienst.enumerations.period_type_enumeration import PeriodType\nfrom wetterdienst.enumerations.time_resolution_enumeration import TimeResolution\nfrom wetterdienst.constants.metadata import DWD_FOLDER_MAIN\nfrom wetterdienst.exceptions import InvalidParameterCombination\nfrom wetterdienst.indexing.file_index_creation import reset_file_index_cache\nfrom wetterdienst.file_path_handling.file_list_creation import (\n create_file_list_for_climate_observations,\n create_filepath_for_radolan,\n)\nfrom wetterdienst.download.download import (\n download_climate_observations_data_parallel,\n download_radolan_data,\n)\nfrom wetterdienst.parsing_data.parse_data_from_files import (\n parse_climate_observations_data,\n)\nfrom wetterdienst.data_storing import (\n restore_climate_observations,\n store_climate_observations,\n _build_local_store_key,\n store_radolan_data,\n restore_radolan_data,\n)\n\nlog = logging.getLogger(__name__)\n\n\nPOSSIBLE_ID_VARS = (\n DWDMetaColumns.STATION_ID.value,\n DWDMetaColumns.DATE.value,\n DWDMetaColumns.FROM_DATE.value,\n DWDMetaColumns.TO_DATE.value,\n)\n\nPOSSIBLE_DATE_VARS = (\n DWDMetaColumns.DATE.value,\n DWDMetaColumns.FROM_DATE.value,\n DWDMetaColumns.TO_DATE.value,\n)\n\n\ndef collect_climate_observations_data(\n station_ids: List[int],\n parameter: Union[Parameter, str],\n time_resolution: Union[TimeResolution, str],\n period_type: Union[PeriodType, str],\n folder: Union[str, Path] = DWD_FOLDER_MAIN,\n prefer_local: bool = False,\n write_file: bool = False,\n tidy_data: bool = True,\n humanize_column_names: bool = False,\n run_download_only: bool = False,\n create_new_file_index: bool = False,\n) -> Optional[pd.DataFrame]:\n \"\"\"\n Function that organizes the complete pipeline of data collection, either\n from the internet or from a local file. It therefor goes through every given\n station id and, given by the parameters, either tries to get data from local\n store and/or if fails tries to get data from the internet. Finally if wanted\n it will try to store the data in a hdf file.\n Args:\n station_ids: station ids that are trying to be loaded\n parameter: parameter as enumeration\n time_resolution: time resolution as enumeration\n period_type: period type as enumeration\n folder: folder for local file interaction\n prefer_local: boolean for if local data should be preferred\n write_file: boolean to write data to local storage\n tidy_data: boolean to tidy up data so that there's only one set of values for\n a datetime in a row\n e.g. station_id, parameter, element, datetime, value, quality\n humanize_column_names: boolean to yield column names better for\n human consumption\n run_download_only: boolean to run only the download and storing process\n create_new_file_index: boolean if to create a new file index for the\n data selection\n\n Returns:\n a pandas DataFrame with all the data given by the station ids\n \"\"\"\n parameter = parse_enumeration_from_template(parameter, Parameter)\n time_resolution = parse_enumeration_from_template(time_resolution, TimeResolution)\n period_type = parse_enumeration_from_template(period_type, PeriodType)\n\n if not check_parameters(parameter, time_resolution, period_type):\n raise InvalidParameterCombination(\n f\"The combination of {parameter.value}, {time_resolution.value}, \"\n f\"{period_type.value} is invalid.\"\n )\n\n if create_new_file_index:\n reset_file_index_cache()\n\n # List for collected pandas DataFrames per each station id\n data = []\n for station_id in set(station_ids):\n request_string = _build_local_store_key(\n station_id, parameter, time_resolution, period_type\n )\n\n if prefer_local:\n # Try restoring data\n station_data = restore_climate_observations(\n station_id, parameter, time_resolution, period_type, folder\n )\n\n # When successful append data and continue with next iteration\n if not station_data.empty:\n log.info(f\"Data for {request_string} restored from local.\")\n\n data.append(station_data)\n\n continue\n\n log.info(f\"Data for {request_string} will be collected from internet.\")\n\n remote_files = create_file_list_for_climate_observations(\n [station_id], parameter, time_resolution, period_type\n )\n\n if len(remote_files) == 0:\n log.info(f\"No files found for {request_string}. Station will be skipped.\")\n continue\n\n filenames_and_files = download_climate_observations_data_parallel(remote_files)\n\n station_data = parse_climate_observations_data(\n filenames_and_files, parameter, time_resolution\n )\n\n if write_file:\n store_climate_observations(\n station_data,\n station_id,\n parameter,\n time_resolution,\n period_type,\n folder,\n )\n\n data.append(station_data)\n\n if run_download_only:\n return None\n\n try:\n data = pd.concat(data)\n except ValueError:\n return pd.DataFrame()\n\n if tidy_data:\n data = _tidy_up_data(data, parameter)\n\n # Assign meaningful column names (humanized).\n if humanize_column_names:\n hcnm = create_humanized_column_names_mapping(time_resolution, parameter)\n if tidy_data:\n data[DWDMetaColumns.ELEMENT.value] = data[\n DWDMetaColumns.ELEMENT.value\n ].apply(lambda x: hcnm[x])\n else:\n data = data.rename(columns=hcnm)\n\n return data\n\n\ndef _tidy_up_data(df: pd.DataFrame, parameter: Parameter) -> pd.DataFrame:\n \"\"\"\n Function to create a tidy DataFrame by reshaping it, putting quality in a\n separate column and setting an extra column with the parameter.\n\n Args:\n df: DataFrame to be tidied\n parameter: the parameter that is written in a column to identify a set of\n different parameters amongst each other\n\n Returns:\n the tidied DataFrame\n \"\"\"\n id_vars = []\n date_vars = []\n\n # Add id columns based on metadata columns\n for column in POSSIBLE_ID_VARS:\n if column in df:\n id_vars.append(column)\n if column in POSSIBLE_DATE_VARS:\n date_vars.append(column)\n\n # Extract quality\n # Set empty quality for first columns until first QN column\n quality = pd.Series(dtype=int)\n column_quality = pd.Series(dtype=int)\n\n for column in df:\n # If is quality column, overwrite current \"column quality\"\n if column.startswith(\"QN\"):\n column_quality = df.pop(column)\n else:\n quality = quality.append(column_quality)\n\n df_tidy = df.melt(\n id_vars=id_vars,\n var_name=DWDMetaColumns.ELEMENT.value,\n value_name=DWDMetaColumns.VALUE.value,\n )\n\n df_tidy[DWDMetaColumns.PARAMETER.value] = parameter.name\n\n df_tidy[DWDMetaColumns.QUALITY.value] = quality.values\n\n # Reorder properly\n df_tidy = df_tidy.reindex(\n columns=[\n DWDMetaColumns.STATION_ID.value,\n DWDMetaColumns.PARAMETER.value,\n DWDMetaColumns.ELEMENT.value,\n *date_vars,\n DWDMetaColumns.VALUE.value,\n DWDMetaColumns.QUALITY.value,\n ]\n )\n\n return df_tidy\n\n\ndef collect_radolan_data(\n date_times: List[datetime],\n time_resolution: TimeResolution,\n prefer_local: bool = False,\n write_file: bool = False,\n folder: Union[str, Path] = DWD_FOLDER_MAIN,\n) -> List[Tuple[datetime, BytesIO]]:\n \"\"\"\n Function used to collect RADOLAN data for given datetimes and a time resolution.\n Additionally the file can be written to a local folder and read from there as well.\n Args:\n date_times: list of datetime objects for which RADOLAN shall be acquired\n time_resolution: the time resolution for requested data, either hourly or daily\n prefer_local: boolean if file should be read from local store instead\n write_file: boolean if file should be stored on the drive\n folder: path for storage\n\n Returns:\n list of tuples of a datetime and the corresponding file in bytes\n \"\"\"\n if time_resolution not in (TimeResolution.HOURLY, TimeResolution.DAILY):\n raise ValueError(\"RADOLAN is only offered in hourly and daily resolution.\")\n\n data = []\n # datetime = pd.to_datetime(datetime).replace(tzinfo=None)\n for date_time in date_times:\n if prefer_local:\n try:\n data.append(\n (\n date_time,\n restore_radolan_data(date_time, time_resolution, folder),\n )\n )\n\n log.info(f\"RADOLAN data for {str(date_time)} restored from local\")\n\n continue\n except FileNotFoundError:\n log.info(\n f\"RADOLAN data for {str(date_time)} will be collected from internet\"\n )\n\n remote_radolan_file_path = create_filepath_for_radolan(\n date_time, time_resolution\n )\n\n if remote_radolan_file_path == \"\":\n log.warning(f\"RADOLAN not found for {str(date_time)}, will be skipped.\")\n continue\n\n date_time_and_file = download_radolan_data(date_time, remote_radolan_file_path)\n\n data.append(date_time_and_file)\n\n if write_file:\n store_radolan_data(date_time_and_file, time_resolution, folder)\n\n return data\n","sub_path":"wetterdienst/data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":10203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"525320867","text":"#Karla Ivonne Serrano Arevalo\n#Karla Ivonne Serrano Arevalo\n#Ejerercicio 5.b\n#Diciembre 2016\n\nimport matplotlib.pyplot as plt \nimport numpy as np\nimport math\n\nt=np.linspace(0,2*math.pi,80)\nr=2-2*np.sin(t)+np.sin(t)*(np.sqrt(np.absolute(np.cos(t))))/(np.sin(t)+1.4)\nx=r*np.cos(t)\ny=r*np.sin(t)\nplt.plot(x,y,linewidth=5, color='r',label='Cora')\nplt.legend()\nplt.title('Laboratorio 3b ejercicio 5b')\nplt.xlabel('eje x')\nplt.ylabel('eje y')\nplt.fill_between(x,y,color='b')\nplt.grid(True)\nplt.show()\n","sub_path":"Laboratorio3b/ejercicio5/ejercicio5b.py","file_name":"ejercicio5b.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"461342909","text":"import subprocess\n\ntest = input(\"Enter test file: \")\ndelays = input(\"Enter delays: \")\n\nprint(\"\\nExecuting by reordering\")\nsubprocess.run(\"./a.exe \" + test + \" \" + delays + \" \" + \"0\")\nprint (\"\\n------------------------------------------------------------------\")\nsubprocess.run(\"./a.exe \" + test + \" \" + delays + \" \" + \"1\")\n\noldName = \"./old.txt\"\nnewName = \"./new.txt\"\n\noldFile = open(oldName).readlines() \n \noldFile_line = [] \n \nclockNew = 0\nclockOld = 0\n\ni = 0\nfor lines in oldFile: \n if (i == 0):\n clockOld = int(lines[6:])\n i = 1\n else:\n\t oldFile_line.append(lines) \n \nnewFile = open(newName).readlines() \n \nnewFile_line = [] \n\ni = 0 \nfor lines in newFile: \n if (i == 0):\n clockNew = int(lines[6:])\n i = 1\n else:\n\t newFile_line.append(lines) \n\nprint (\"\\n\")\n\nif (len(oldFile_line) != len(newFile_line)):\n print(\"Output not same!!\")\n\nelse:\n done = True\n for i in range(len(oldFile_line)):\n if (oldFile_line[i] != newFile_line[i]):\n done = False\n print(\"Without reordering: \", oldFile_line)\n print(\"Witg reordering: \", newFile_line)\n\n if (done):\n print(\"Output Matches!!\")\n\n print(\"Gain in clocks: \", clockOld-clockNew)\n","sub_path":"Assignment4/COL216_A4_2019CS10722/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"440405180","text":"#Say you have an array for which the ith element is the price of a given stock on day i.\n#If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.\n#Note that you cannot sell a stock before you buy one.\n#Example 1:\n\n#Input: [7,1,5,3,6,4]\n#Output: 5\n#Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n# Not 7-1 = 6, as selling price needs to be larger than buying price.\n\n#Example 2:\n#Input: [7,6,4,3,1]\n#Output: 0\n#Explanation: In this case, no transaction is done, i.e. max profit = 0.\n\n# going to iterate over the list once\n# want to find max profit\n# consider every curr_num to be smallest_num\n# smallest num is always attempted to be minimized\n# i.e. iteration 0 => smallest_num = 7\n# iteration 1 => smallest_num = min(7, 1) => 1\n# if we can minimize smallest num, minimize it and continue to the list\n# if we cant, then we want to check if we can maximize our profit\n# iteration 2 => smallest_num = 1, curr_num = 5\n# 5 < 1? no so maximize profit; res = max(0, 5-1)\n\n# o n time, o 1 space\n\ndef solve(stocks):\n if not stocks:\n return 0\n smallest_num = stocks[0]\n res = 0\n for stock in stocks[1:]:\n if stock < smallest_num:\n smallest_num = stock\n else:\n res = max(res, stock - smallest_num)\n return res\nnums = [7,1,5,3,6,4]\nprint(solve(nums)) # 5\n","sub_path":"tech_interview_handbook/121_best_time_to_buy_and_sell_stock.py","file_name":"121_best_time_to_buy_and_sell_stock.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"639500078","text":"import logging\nimport os\n\nfrom stograde.student import pull, clone_url\n\n\ndef test_pull_success(tmpdir, caplog):\n with tmpdir.as_cwd():\n clone_url('https://github.com/StoDevX/cs251-specs.git')\n with caplog.at_level(logging.DEBUG):\n pull('cs251-specs')\n\n log_messages = {(log.msg, log.levelname) for log in caplog.records}\n assert log_messages == {(\"Pulling cs251-specs's repository\", 'DEBUG')}\n\n\ndef test_pull_fail(tmpdir, capsys):\n with tmpdir.as_cwd():\n os.makedirs('not_a_git_repo')\n pull('not_a_git_repo')\n\n _, err = capsys.readouterr()\n\n assert err == ('Student directory not_a_git_repo is not a git repository\\n'\n 'Try running \"stograde repo reclone\"\\n')\n","sub_path":"test/student/test_pull.py","file_name":"test_pull.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"235884102","text":"from anim import AnimManager\n\nclass AnimDriver(object):\n \n def __init__(self, obj, values, attr, t, ease_func):\n self.start, self.end = values\n self.delta = self.end - self.start\n self.total_time = t * 1000.0\n self.t = 0.0\n self.obj = obj\n self.attr = attr\n self.ease_func = ease_func\n self.done = False\n\n def update(self, dT):\n value = self.ease_func(self.t, self.start, self.delta, self.total_time)\n self.obj[self.attr] = value\n\n if self.t >= self.total_time:\n return True\n\n self.t = min(self.t + dT, self.total_time)\n\n return False\n\nfrom maths.Vect2 import Vect2\nclass Vect2AnimDriver(AnimDriver):\n def __init__(self, src_vec, dest_vec, t, ease_func):\n super(Vect2AnimDriver, self).__init__(src_vec, dest_vec, None, t, ease_func)\n self.start, self.end = Vect2(src_vec), Vect2(dest_vec)\n self.delta = self.end - self.start\n\n def update(self, dT):\n new_x = self.ease_func(self.t, self.start.x, self.delta.x, self.total_time)\n new_y = self.ease_func(self.t, self.start.y, self.delta.y, self.total_time)\n\n #if self.start.y < 0:\n # print str(new_x) + ', ' + str(new_y)\n\n self.obj.x = new_x\n self.obj.y = new_y\n\n if self.t >= self.total_time:\n return True\n\n self.t = min(self.t + float(dT), self.total_time)\n\n return False","sub_path":"src/anim/AnimDriver.py","file_name":"AnimDriver.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"59143341","text":"# TLE\nclass Solution(object):\n def isSubsequence(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n m, n = len(t), len(s)\n if n == 0:\n return True\n elif m == 0:\n return False\n dp = [[False for j in xrange(n)] for i in xrange(m)]\n if s[0] == t[0]:\n dp[0][0] = True\n for i in xrange(1, m):\n if dp[i-1][0] or t[i] == s[0]:\n dp[i][0] = True\n for j in xrange(1, n):\n if dp[i-1][j] or (dp[i-1][j-1] and t[i] == s[j]):\n dp[i][j] = True\n return dp[m-1][n-1]\n","sub_path":"medium/392_Is_Subsequence/sub_tle.py","file_name":"sub_tle.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"90262268","text":"\r\nimport re\r\nimport os.path\r\n#assign1- take input as the phone number and validate\r\npattern = '^[0-9]{10}$'\r\nnumb = input(\"Enter the number\")\r\n\r\nmatches = re.search(pattern, numb)\r\nif matches:\r\n print(\"matched\")\r\nelse:\r\n print(\"not matched\")\r\n\r\n#assign2- from the current dire extract only .log files and read all email ids\r\n\r\n\r\nli = os.listdir(\"C:\\\\Users\\\\ssingh722\\\\Documents\\\\Python\\\\demo\")\r\nprint(li)\r\nfor i in li:\r\n net = os.path.splitext(i)\r\n if(net[1]==\".log\"):\r\n f = open(\"C:\\\\Users\\\\ssingh722\\\\Documents\\\\Python\\\\demo\\\\\" +i, \"rb\")\r\n data = f.read().decode()\r\n pattern = '\\S+@\\S+'\r\n matches = re.findall(pattern, data)\r\n print(matches)\r\n f.close()\r\n","sub_path":"Assignments/mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"481664301","text":"from django.db import connection\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\nimport re\n\nclass WordService(object):\n @staticmethod\n def count_vectorizer(text, language_identifier):\n alpha = re.sub(r\"/[^\\d\\s]/g\", \"\", text)\n if alpha == \"\": return\n vectorizer = CountVectorizer(token_pattern=r\"\\b[^\\d\\s\\']+\\b\", analyzer=\"word\")\n tokens = vectorizer.fit([text]).get_feature_names()\n length = [len(t) for t in tokens]\n freq = vectorizer.transform([text]).toarray()[0].tolist()\n lang = [language_identifier] * len(tokens)\n data = [list(t) for t in zip(tokens, length, freq, lang)]\n WordService.insert_words(data)\n\n @staticmethod\n def insert_words(data):\n print('start bulk insert words')\n with connection.cursor() as cursor: \n cursor.executemany(\n \"INSERT INTO words_word(word,length,count,language_id)\\\n VALUES (%s,%s,%s,%s) ON CONFLICT (word)\\\n DO UPDATE SET count = excluded.count + words_word.count;\", data)\n cursor.close()\n print('end bulk insert words')\n \n @staticmethod\n def update_word_freq(lang):\n print('start bulk update words')\n with connection.cursor() as cursor: \n cursor.execute(\n f\"WITH new_values AS (SELECT id, count / (SELECT SUM(count)::FLOAT FROM words_word) AS freq FROM words_word WHERE language_id={lang})\\\n update words_word as old_values\\\n set frequency = new_values.freq\\\n from new_values new_values\\\n where new_values.id = old_values.id;\"\n ) \n cursor.close()\n print('end bulk insert words')","sub_path":"backend/corpora/apps/words/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"292738356","text":"import sys\nfrom PyQt4 import QtGui, QtCore\n\nfrom time import strftime\nimport datetime\nfrom colour import Color\n\nclass Window(QtGui.QMainWindow):\n\n def __init__(self):\n super(Window, self).__init__()\n self.setGeometry(50, 50, 400, 100)\n self.setWindowTitle(\"PyQT tuts!\")\n self.setWindowIcon(QtGui.QIcon('/home/patrick/Desktop/256x256Icon.png'))\n self.setWindowOpacity(0.9)\n self.sp = 0\n self.timeremaining = 0\n self.periodstart = 0\n self.periodend = 0\n self.minutesleft = 0\n self.home()\n\n def home(self):\n\n self.timer = QtCore.QTimer(self)\n self.timer.timeout.connect(self.Time)\n self.timer.start(1000)\n self.lcd = QtGui.QLCDNumber(self)\n self.lcd.setNumDigits(8)\n self.setCentralWidget(self.lcd)\n self.show()\n\n def settlement_period(self):\n now = self.ceil_dt(datetime.datetime.now()) + datetime.timedelta(hours=1)\n current_hour = now.hour\n current_minute = now.minute\n\n if current_minute >= 30:\n HH_Add = 1\n else:\n HH_Add = 0\n\n return (current_hour * 2 + HH_Add)+1\n\n def countdown_colour(self):\n #print (datetime.datetime.now())\n self.setWindowTitle(datetime.datetime.now().strftime(\"%H:%M:%S\"))\n self.setWindowTitle(str(self.time_remaining()))\n\n def Time(self):\n #Code to run everytime the timer updates: Time,\n self.lcd.display(strftime(\"%H:%M:%S\"))\n bc = \"QLCDNumber{color:rgb(0, 0, 0); background-color:rgb(%s, %s, %s)}\" % (self.background_colour())\n self.setStyleSheet(bc)\n self.PeriodStartEnd()\n title = \"GC: %s | P: %s | T: %s - %s\" % (self.time_remaining(), self.settlement_period(), self.periodstart.strftime(\"%H:%M\"), self.periodend.strftime(\"%H:%M\") )\n self.setWindowTitle(title)\n\n def PeriodStartEnd(self):\n self.periodstart = self.ceil_dt(datetime.datetime.now()) + datetime.timedelta(hours=1)\n self.periodend = self.ceil_dt(datetime.datetime.now()) + datetime.timedelta(hours=1.5)\n\n def ceil_dt(self, dt):\n nsecs = dt.minute*60 + dt.second\n delta = (nsecs//1800)*1800 + 1800 - nsecs\n return dt + datetime.timedelta(seconds=delta)\n\n def time_remaining(self):\n t1 = self.ceil_dt(datetime.datetime.now())\n t2 = datetime.datetime.now()\n dt1 = datetime.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second)\n dt2 = datetime.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second)\n timediff = str((dt1-dt2))\n self.minutesleft = timediff.split(\":\")[1]\n return \"%s:%s\" % (timediff.split(\":\")[1],timediff.split(\":\")[2])\n\n def background_colour(self):\n green = Color(rgb=(0, 1, 0))\n yellow = Color(rgb=(1, 1, 0))\n red = Color(rgb=(1, 0, 0))\n\n RedtoYellow = list(red.range_to(Color(rgb=(1, 1, 0)), 15))\n YellowToGreen = list(yellow.range_to(Color(rgb=(0, 1, 0)), 15))\n\n BackgroundColour = RedtoYellow + YellowToGreen\n\n try:\n a = BackgroundColour[int(self.minutesleft)]\n except:\n a = red\n\n return (round(a.rgb[0]*255),round(a.rgb[1]*255),0)\n\n\ndef run():\n app = QtGui.QApplication(sys.argv)\n GUI = Window()\n sys.exit(app.exec_())\n\nrun()","sub_path":"Clock/pyQT Framework/sentdex.py","file_name":"sentdex.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"281842825","text":"from __future__ import absolute_import, division, print_function\n\n# for word econding\nimport codecs\n# for regex\nimport glob\nimport logging\n#for conccurency\nimport multiprocessing\nimport os\nimport pprint\n# more regex\nimport re\n\n# natural language toolkit\nimport nltk\nimport gensim.models.word2vec as w2v\n#dimensionality reduction\nimport sklearn.manifold\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\nnltk.download(\"punkt\")\nnltk.download(\"stopwords\")\n\nbook_filenames = sorted(glob.glob(\"got/*.txt\"))\n\nprint(\"Found books:\")\nbook_filenames\n\ncorpus_raw = u\"\"\nfor book_filename in book_filenames:\n print(\"Reading '{0}'...\".format(book_filename))\n with codecs.open(book_filename, \"r\", \"utf-8\") as book_file:\n corpus_raw += book_file.read()\n print(\"Corpus is now {0} characters long\".format(len(corpus_raw)))\n print()\n\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n### create sentences\nraw_sentences = tokenizer.tokenize(corpus_raw)\n\n#convert into a list of words\n#rtemove unnnecessary,, split into words, no hyphens\n#list of words\ndef sentence_to_wordlist(raw):\n clean = re.sub(\"[^a-zA-Z]\",\" \", raw)\n words = clean.split()\n return words\n\n#sentence where each word is tokenized\nsentences = []\nfor raw_sentence in raw_sentences:\n if len(raw_sentence) > 0:\n sentences.append(sentence_to_wordlist(raw_sentence))\n\n### Print raw sentences, after being curated and corpus size\nprint(raw_sentences[5])\nprint(sentence_to_wordlist(raw_sentences[5]))\ntoken_count = sum([len(sentence) for sentence in sentences])\nprint(\"The book corpus contains {0:,} tokens\".format(token_count))\n\ndel raw_sentence\n\n### Train the model\n\n#ONCE we have vectors\n#step 3 - build model\n#3 main tasks that vectors help with\n#DISTANCE, SIMILARITY, RANKING\n\n# Dimensionality of the resulting word vectors.\n#more dimensions, more computationally expensive to train\n#but also more accurate\n#more dimensions = more generalized\nnum_features = 300\n# Minimum word count threshold.\nmin_word_count = 3\n\n# Number of threads to run in parallel.\n#more workers, faster we train\nnum_workers = multiprocessing.cpu_count()\n\n# Context window length.\ncontext_size = 7\n\n# Downsample setting for frequent words.\n#0 - 1e-5 is good for this\ndownsampling = 1e-3\n\n# Seed for the RNG, to make the results reproducible.\n#random number generator\n#deterministic, good for debugging\nseed = 1\n\nthrones2vec = w2v.Word2Vec(\n sg=1,\n seed=seed,\n workers=num_workers,\n size=num_features,\n min_count=min_word_count,\n window=context_size,\n sample=downsampling\n)\n\nthrones2vec.build_vocab(sentences)\n\n### Start training, this might take a minute or two...\nthrones2vec.train(sentences, total_examples=thrones2vec.corpus_count, epochs=thrones2vec.iter)\n\n### Save the file\nthrones2vec.save(\"thrones2vec.w2v\")\n\n","sub_path":"word2vec/Thrones2Vec.py","file_name":"Thrones2Vec.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"537316187","text":"#From the 2019 competition\n#Slow but functional\n\naverages = []\nn = int(input())\n\nfor x in range(n):\n averages.append(int(input()))\n\nprimes = [2]\n\nfor i in range(3,max(averages)*2):\n isPrime = True\n for p in primes:\n if i%p==0:\n isPrime = False\n break\n if isPrime == True:\n primes.append(i)\n\nfoundPrimes = []\nfor average in averages:\n found = False\n a = average\n b = average\n count = 0\n while found == False:\n p = primes[count]\n a = 2*average-p\n \n if p == 2*average-a and a in primes:\n b = p\n found = True\n count += 1\n foundPrimes.append([b,a])\n\nfor foundPair in foundPrimes:\n for p in foundPair:\n print(p, end = \" \")\n print()\n","sub_path":"Average primes.py","file_name":"Average primes.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"53690630","text":"class Node:\r\n\r\n def __init__(self, matrix, hValue, symbol, opponentSymbol):\r\n self.matrix = matrix\r\n self.hValue = hValue\r\n self.symbol = symbol\r\n self.opponentSymbol = opponentSymbol\r\n self.x = 0\r\n self.y = 0\r\n self.bestChild = None\r\n\r\n def __str__(self):\r\n return \"Matrix: \" + str(self.matrix) + \", Heuristic value: \" + str(self.hValue) + \", Symbol: \" + self.symbol\r\n\r\n def getMatrix(self):\r\n return self.matrix\r\n\r\n def getPosition(self, x, y):\r\n return self.matrix[x][y]\r\n\r\n def setPosition(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def getHValue(self):\r\n return self.hValue\r\n\r\n def setHValue(self, hValue):\r\n self.hValue = hValue\r\n\r\n def getSymbol(self):\r\n return self.symbol\r\n\r\n def getOpponentSymbol(self):\r\n return self.opponentSymbol\r\n\r\n def getBestChild(self):\r\n return self.bestChild\r\n\r\n def setBestChild(self, bestChild):\r\n self.bestChild = bestChild\r\n\r\n def generateChildren(self, maximizingPlayer):\r\n emptyTiles = []\r\n children = []\r\n length = len(self.matrix)\r\n\r\n for i in range(length):\r\n for j in range(length):\r\n if self.matrix[i][j] == \" \":\r\n emptyTiles.append((i,j))\r\n \r\n for tile in emptyTiles:\r\n matrix = [[self.matrix[i][j] for j in range(3)] for i in range(3)]\r\n if maximizingPlayer:\r\n matrix[tile[0]][tile[1]] = self.symbol\r\n else:\r\n matrix[tile[0]][tile[1]] = self.opponentSymbol\r\n\r\n self.setPosition(tile[0],tile[1])\r\n hValue = 0\r\n\r\n for row in matrix:\r\n if row.count(self.symbol)==3:\r\n children.append(Node(matrix, 1, self.opponentSymbol, self.symbol))\r\n break\r\n if row.count(self.opponentSymbol)==3:\r\n children.append(Node(matrix, -1, self.opponentSymbol, self.symbol))\r\n break\r\n\r\n for i in range(3):\r\n if [matrix[0][i], matrix[1][i], matrix[2][i]].count(self.symbol)==3:\r\n children.append(Node(matrix, -1, self.opponentSymbol, self.symbol))\r\n break\r\n if [matrix[0][i], matrix[1][i], matrix[2][i]].count(self.opponentSymbol)==3:\r\n children.append(Node(matrix, -1, self.opponentSymbol, self.symbol))\r\n break\r\n\r\n if [matrix[0][0], matrix[1][1], matrix[2][2]].count(self.symbol)==3:\r\n children.append(Node(matrix, 1, self.opponentSymbol, self.symbol))\r\n elif [matrix[2][0], matrix[1][1], matrix[0][2]].count(self.symbol)==3:\r\n children.append(Node(matrix, 1, self.opponentSymbol, self.symbol))\r\n\r\n elif [matrix[0][0], matrix[1][1], matrix[2][2]].count(self.opponentSymbol)==3:\r\n children.append(Node(matrix, -1, self.opponentSymbol, self.symbol))\r\n elif [matrix[2][0], matrix[1][1], matrix[0][2]].count(self.opponentSymbol)==3:\r\n children.append(Node(matrix, -1, self.opponentSymbol, self.symbol))\r\n\r\n else:\r\n children.append(Node(matrix, 0, self.symbol, self.opponentSymbol))\r\n\r\n return children\r\n\r\n\r\nclass Player:\r\n\r\n def __init__(self, game, symbol):\r\n self.game = game\r\n self.symbol = symbol\r\n\r\n def __str__(self):\r\n return \"Player symbol: \" + self.symbol\r\n\r\n def isValid(self, x, y):\r\n return x>=0 and x<3 and y>=0 and y<3 and self.game.getPosition(x,y)==' '\r\n\r\n def makeMove(self):\r\n while True:\r\n x = int(input(\"Enter x position [0 to 2]: \"))\r\n y = int(input(\"Enter y position [0 to 2]: \"))\r\n \r\n try:\r\n if self.isValid(x,y):\r\n self.game.updateMatrix(x, y, self.symbol)\r\n self.game.showMatrix()\r\n print()\r\n return\r\n else:\r\n print(\"\\nInvalid coordinates, please try again.\\n\")\r\n except ValueError:\r\n print(\"\\nInvalid input (non integer). Please try again.\\n\")\r\n\r\n def getSymbol(self):\r\n return self.symbol\r\n\r\n\r\nclass Opponent:\r\n\r\n diff = {\"easy\" : 1, \"medium\" : 2, \"hard\" : 3}\r\n\r\n def __init__(self, game, symbol, opponentSymbol, difficulty):\r\n self.game = game\r\n self.symbol = symbol\r\n self.opponentSymbol = opponentSymbol\r\n self.depth = Opponent.diff[difficulty]\r\n\r\n def __str__(self):\r\n return \"Opponent's symbol: \" + self.symbol + \", \" + \"Difficulty (depth): \" + self.depth \r\n\r\n def getSymbol(self):\r\n return self.symbol\r\n\r\n def getOpponentSymbol(self):\r\n return self.opponentSymbol\r\n\r\n def bestMove(self, node, depth, maximizingPlayer):\r\n children = []\r\n nodeValue = node.getHValue()\r\n\r\n if nodeValue==1 or nodeValue==-1:\r\n return nodeValue, node\r\n else: \r\n children = node.generateChildren(maximizingPlayer)\r\n\r\n if depth==0 or len(children)==0:\r\n return node.getHValue(), node\r\n\r\n if maximizingPlayer:\r\n bestValue = -10\r\n bestNode = Node(None, bestValue, self.symbol, self.opponentSymbol)\r\n for child in children:\r\n tempValue, tempNode = self.bestMove(child, depth-1, False)\r\n bestValue = max([bestValue, tempValue])\r\n if bestValue == tempNode.getHValue():\r\n bestNode = tempNode\r\n node.setHValue(bestValue)\r\n node.setBestChild(bestNode)\r\n return bestValue, node\r\n\r\n else:\r\n bestValue = 10\r\n bestNode = Node(None, bestValue, self.symbol, self.opponentSymbol)\r\n for child in children:\r\n tempValue, tempNode = self.bestMove(child, depth-1, True)\r\n bestValue = min([bestValue, tempValue])\r\n if bestValue == tempNode.getHValue():\r\n bestNode = tempNode\r\n node.setHValue(bestValue)\r\n node.setBestChild(bestNode)\r\n return bestValue, node\r\n\r\n def makeMove(self):\r\n node = Node(self.game.getMatrix(), 0, self.symbol, self.opponentSymbol)\r\n depth = self.depth\r\n value, node = self.bestMove(node, depth, True)\r\n return node.getBestChild().getMatrix()\r\n\r\nclass Game:\r\n\r\n def __init__(self):\r\n self.rounds = 1\r\n self.matrix = [[\" \" for i in range(3)] for j in range(3)]\r\n\r\n def getRounds(self):\r\n return self.rounds\r\n\r\n def incrementRounds(self):\r\n self.rounds += 1\r\n\r\n def getMatrix(self):\r\n return self.matrix\r\n\r\n def setMatrix(self, matrix):\r\n self.matrix = matrix\r\n\r\n def update(self, matrix):\r\n self.matrix = matrix\r\n\r\n def updateMatrix(self, x, y, symbol):\r\n self.matrix[x][y] = symbol\r\n\r\n def getPosition(self, x, y):\r\n return self.matrix[x][y]\r\n\r\n def symbolWon(self, symbol):\r\n for row in self.matrix:\r\n if row.count(symbol) == 3:\r\n return True\r\n for i in range(3):\r\n if [self.matrix[0][i], self.matrix[1][i], self.matrix[2][i]].count(symbol)==3:\r\n return True\r\n if [self.matrix[0][0], self.matrix[1][1], self.matrix[2][2]].count(symbol)==3:\r\n return True\r\n if [self.matrix[2][0], self.matrix[1][1], self.matrix[0][2]].count(symbol)==3:\r\n return True\r\n return False\r\n\r\n def peerWon(self, peer):\r\n return self.symbolWon(peer.getSymbol())\r\n\r\n def isDraw(self):\r\n for i in range(3):\r\n for j in range(3):\r\n if self.matrix[i][j]==' ':\r\n return False\r\n return True\r\n\r\n def showMatrix(self):\r\n length = len(self.getMatrix())\r\n print()\r\n print(\"-\" * 13)\r\n for x in range(length):\r\n for y in range(length):\r\n print(\"|\", end=\" \")\r\n print(self.getPosition(x,y), end=\" \")\r\n print(\"|\")\r\n print(\"-\" * 13)\r\n print()\r\n\r\n def showMessage(self, wonString):\r\n print(wonString)\r\n print(\"Total rounds: \", self.getRounds())\r\n\r\n\r\nclass TicTacToe:\r\n\r\n EASY = \"easy\"\r\n MEDIUM = \"medium\"\r\n HARD = \"hard\"\r\n\r\n def __init__(self):\r\n self.player = None\r\n self.firstOpponent = None\r\n self.secondOpponent = None\r\n self.game = None\r\n\r\n def opponentMove(self, opponent):\r\n matrix = opponent.makeMove()\r\n self.game.update(matrix)\r\n self.game.showMatrix()\r\n\r\n\r\n def PlayerVsCpu(self, playerSymbol, opponentSymbol, opponentDifficulty):\r\n self.game = Game()\r\n self.player = Player(self.game, playerSymbol)\r\n self.firstOpponent = Opponent(self.game, opponentSymbol, playerSymbol, opponentDifficulty)\r\n self.game.showMatrix()\r\n\r\n while True:\r\n print(\"YOUR MOVE: \")\r\n self.player.makeMove()\r\n print()\r\n if self.game.peerWon(self.player):\r\n self.game.showMessage(\"You won!!\")\r\n break\r\n\r\n if self.game.isDraw():\r\n self.game.showMessage(\"Game ended in draw.\")\r\n break\r\n\r\n print(\"CPU MOVE: \")\r\n self.opponentMove(self.firstOpponent)\r\n print()\r\n if self.game.peerWon(self.firstOpponent):\r\n self.game.showMessage(\"CPU-1 won!!\")\r\n break\r\n\r\n if self.game.isDraw():\r\n self.game.showMessage(\"Game ended in draw.\")\r\n break\r\n\r\n self.game.incrementRounds()\r\n print()\r\n\r\n\r\nclass Program:\r\n\r\n def validate(self, diffLevel, validChoices):\r\n return diffLevel in validChoices\r\n\r\n def getDifficulty(self):\r\n difficulty = ''\r\n while True:\r\n print(\"\\nChoose difficulty level:\")\r\n print(\"1. EASY\")\r\n print(\"2. MEDIUM\")\r\n print(\"3. HARD\")\r\n difficultyLevel = int(input(\"\\nLevel [choose 1, 2 or 3]: \"))\r\n if self.validate(difficultyLevel, [1,2,3]):\r\n if difficultyLevel==1:\r\n difficulty = TicTacToe.EASY\r\n elif difficultyLevel==2:\r\n difficulty = TicTacToe.MEDIUM\r\n else:\r\n difficulty = TicTacToe.HARD\r\n return difficulty\r\n print(\"\\nInvalid input. Please try again.\\n\")\r\n\r\n def getSymbols(self):\r\n symbol = ''\r\n opponentSymbol = ''\r\n while True:\r\n print(\"\\nChoose player symbol: \")\r\n print(\"1. X\")\r\n print(\"2. O\")\r\n symbol = str(input(\"\\nSymbol [type X or O]: \"))\r\n if self.validate(symbol, ['x', 'X', 'o', 'O']):\r\n if symbol=='x' or symbol=='X':\r\n opponentSymbol = 'O'\r\n else:\r\n opponentSymbol = 'X'\r\n return (symbol.upper(), opponentSymbol)\r\n print(\"\\nInvalid input. Please try again.\\n\")\r\n\r\n def askForMatchReplay(self):\r\n while True:\r\n answer = str(input(\"\\nDo you want to replay that match? (Y/N): \"))\r\n if answer.lower()=='y':\r\n return True\r\n elif answer.lower()=='n':\r\n return False\r\n else:\r\n print(\"\\nInvalid input. Please try again.\\n\")\r\n print()\r\n\r\n def askToQuit(self):\r\n while True:\r\n print(\"\\nWhat do you want to do?\")\r\n print(\"1. Main menu\")\r\n print(\"2. Quit\")\r\n answer = int(input(\"\\nEnter choice [1 or 2]: \"))\r\n if self.validate(answer, [1,2]):\r\n return answer\r\n print(\"\\nInvalid input. Please try again.\\n\")\r\n\r\n def showTitle(self):\r\n print()\r\n print(\"###################\")\r\n print(\"### TIC-TAC-TOE ###\")\r\n print(\"###################\")\r\n print()\r\n\r\n def run(self):\r\n tictactoe = TicTacToe()\r\n self.showTitle()\r\n while True:\r\n difficulty = self.getDifficulty()\r\n symbols = self.getSymbols()\r\n while True:\r\n while True:\r\n tictactoe.PlayerVsCpu(symbols[0], symbols[1], difficulty)\r\n replay = self.askForMatchReplay()\r\n if not replay:\r\n break\r\n quit = self.askToQuit()\r\n if quit==1:\r\n break\r\n else:\r\n return\r\n\r\n########################################################################################\r\n\r\nif __name__ == '__main__':\r\n program = Program()\r\n program.run()\r\n","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":12950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"383551623","text":"\n\nfrom xai.brain.wordbase.verbs._interject import _INTERJECT\n\n#calss header\nclass _INTERJECTED(_INTERJECT, ):\n\tdef __init__(self,): \n\t\t_INTERJECT.__init__(self)\n\t\tself.name = \"INTERJECTED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"interject\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_interjected.py","file_name":"_interjected.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"95796879","text":"from concurrent import futures\nimport time\n\nimport grpc\n\nimport apservice_pb2_grpc\nimport apservice_pb2\n\nimport astropaper as ap\n\n_ONE_DAY_IN_SECONDS = 60 * 60 * 24\n\nclass WallpaperServicer(apservice_pb2_grpc.AstropaperServicer):\n def __init__(self):\n self.platform = ap.getPlatform()\n self.path = ap.getPath(self.platform)\n def GetNewWallpaper(self, request, context):\n self.wallpaper = ap.newWallpaper(self.path)\n ap.createPreview(self.path + '/' + self.wallpaper)\n print(\"Path : \" + self.path)\n print(\"Quantity: \" + str(request.quantity))\n return apservice_pb2.APIReply(reply=str(self.wallpaper))\n def SetupWallpaper(self, request, context):\n print(\"Setup request: \" + request.wallpaper)\n #print(\"The request is: \" + str(request))\n ap.wallpaperSetup(self.platform, request.wallpaper, self.path)\n return apservice_pb2.APIReply(reply=\"Wallpaper %s is set!\" % request.wallpaper)\n\ndef serve():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\n apservice_pb2_grpc.add_AstropaperServicer_to_server(WallpaperServicer(), server)\n server.add_insecure_port('[::]:50050')\n server.start()\n print(\"Server started, entering loop\")\n try:\n while True:\n time.sleep(15)\n except KeyboardInterrupt:\n server.stop(0)\n\nif __name__ == '__main__':\n serve()","sub_path":"Server/astroPaper_server.py","file_name":"astroPaper_server.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"225619038","text":"\"\"\"\n1391. Check if There is a Valid Path in a Grid\n\n\"\"\"\n\n# very tedis problem + a little dfs\n# but very similar to the real world problems\nclass Solution:\n def hasValidPath(self, grid: List[List[int]]) -> bool:\n valid_path_seg = {\n (0, 1): [1, 3, 5],\n (0, -1): [1, 4, 6],\n (1, 0): [2, 5, 6],\n (-1, 0): [2, 3, 4]\n }\n seg_dirs = {\n 1: [(0, -1), (0, 1)],\n 2: [(1, 0), (-1, 0)],\n 3: [(0, -1), (1, 0)],\n 4: [(1, 0), (0, 1)],\n 5: [(-1, 0), (0, -1)],\n 6: [(-1, 0), (0, 1)]\n }\n \n curr_loc = (0, 0)\n visited = set([(0, 0)])\n return self.dfs((0, 0), grid, visited, seg_dirs, valid_path_seg)\n\n def dfs(self, curr_loc, grid, visited, seg_dirs, valid_path_seg):\n n_row, n_col = len(grid), len(grid[0])\n x, y = curr_loc\n if x == n_row - 1 and y == n_col - 1:\n return True\n \n dirs = seg_dirs[grid[x][y]]\n can_finish = False\n for dx, dy in dirs:\n new_x, new_y = x + dx, y + dy\n if (new_x, new_y) in visited:\n continue\n if new_x < 0 or new_x>=n_row or new_y < 0 or new_y >= n_col:\n continue\n if grid[new_x][new_y] not in valid_path_seg[(dx, dy)]:\n continue\n visited.add((new_x, new_y))\n can_finish = self.dfs((new_x, new_y), grid, visited, seg_dirs, valid_path_seg) or can_finish\n return can_finish\n \n ","sub_path":"Widen/LC1391_Check_if_There_is_a_Valid_Path_in_a_Grid.py","file_name":"LC1391_Check_if_There_is_a_Valid_Path_in_a_Grid.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"420966377","text":"from . import VGGFace\nimport os\nimport gdown\nimport numpy as np\nfrom keras.models import Model, Sequential\nfrom keras.layers import Convolution2D, Flatten, Activation, Input\n\ndef loadModel(feature_extracted=False):\n\n model = VGGFace.baseModel()\n\n #--------------------------\n\n classes = 2\n base_model_output = Sequential()\n base_model_output = Convolution2D(classes, (1, 1), name='predictions')(model.layers[-4].output)\n base_model_output = Flatten()(base_model_output)\n base_model_output = Activation('softmax')(base_model_output)\n\n #--------------------------\n\n mask_model = Model(inputs=model.input, outputs=base_model_output)\n\n #--------------------------\n\n #load weights\n\n weight_path = './weights/mask_model_weights.h5'\n mask_model.load_weights(weight_path)\n\n if feature_extracted:\n input_layer = Input((7,7,512))\n mask_h = mask_model.layers[-7](input_layer)\n mask_h = mask_model.layers[-6](mask_h)\n mask_h = mask_model.layers[-5](mask_h)\n mask_h = mask_model.layers[-4](mask_h)\n mask_h = mask_model.layers[-3](mask_h)\n mask_h = mask_model.layers[-2](mask_h)\n mask_out = mask_model.layers[-1](mask_h)\n mask_model = Model(inputs = input_layer, outputs=mask_out)\n return mask_model\n else:\n return mask_model\n\n#--------------------------","sub_path":"model/analysis_models/Mask.py","file_name":"Mask.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"384099428","text":"# Card.py\n\"\"\"Class for playing cards\"\"\"\n#\n# Author: Bill Montana\n# Course: Coding for OOP\n# Section: A3\n# Date: 12 Feb 2018\n# IDE: PyCharm Community Edition\n#\n# Assignment Info\n# Example: Card Class\n# Source: Python Programming\n# Chapter: 10\n#\n# Program Description\n# Implementation of a class for a playing card\n#\n# Algorithm (pseudocode)\n# \n# \n# \n# \n# \n\nfrom random import randrange\nfrom graphics import *\n\n\nclass Card:\n def __init__(self, suit, rank):\n \"\"\"\n Card constructor method\n :param suit: int -> 0 = hearts, 1 = diamonds, 2 = clubs, 3 = spades\n :param rank: int -> number rank of card\n \"\"\"\n self.suit = suit\n self.rank = rank\n self.suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']\n self.ranks = ['null', 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']\n\n def setSuit(self, arg):\n \"\"\"Sets the suit (int, 0-4) of an individual card\"\"\"\n self.suit = arg\n\n def setRank(self, arg):\n self.rank = arg\n\n def getSuit(self):\n return self.suit\n\n def getRank(self):\n return self.rank\n\n def getSuitName(self):\n return self.suits[self.suit]\n\n def getRankName(self):\n return self.ranks[self.rank]\n\n def draw(self, win, center):\n \"\"\"\n Draws the card\n :param win: Graphics -> window in which to draw\n :param center: Point -> center of card\n :return: None\n \"\"\"\n _cards = {(0, 1): 'images/ace_of_hearts.gif', (0, 2): 'images/2_of_hearts.gif',\n (0, 3): 'images/3_of_hearts.gif', (0, 4): 'images/4_of_hearts.gif',\n (0, 5): 'images/5_of_hearts.gif', (0, 6): 'images/6_of_hearts.gif',\n (0, 7): 'images/7_of_hearts.gif', (0, 8): 'images/8_of_hearts.gif',\n (0, 9): 'images/9_of_hearts.gif', (0, 10): 'images/10_of_hearts.gif',\n (0, 11): 'images/jack_of_hearts2.gif', (0, 12): 'images/queen_of_hearts2.gif',\n (0, 13): 'images/king_of_hearts2.gif',\n (1, 1): 'images/ace_of_diamonds.gif', (1, 2): 'images/2_of_diamonds.gif',\n (1, 3): 'images/3_of_diamonds.gif', (1, 4): 'images/4_of_diamonds.gif',\n (1, 5): 'images/5_of_diamonds.gif', (1, 6): 'images/6_of_diamonds.gif',\n (1, 7): 'images/7_of_diamonds.gif', (1, 8): 'images/8_of_diamonds.gif',\n (1, 9): 'images/9_of_diamonds.gif', (1, 10): 'images/10_of_diamonds.gif',\n (1, 11): 'images/jack_of_diamonds2.gif', (1, 12): 'images/queen_of_diamonds2.gif',\n (1, 13): 'images/king_of_diamonds2.gif',\n (2, 1): 'images/ace_of_clubs.gif', (2, 2): 'images/2_of_clubs.gif',\n (2, 3): 'images/3_of_clubs.gif', (2, 4): 'images/4_of_clubs.gif',\n (2, 5): 'images/5_of_clubs.gif', (2, 6): 'images/6_of_clubs.gif',\n (2, 7): 'images/7_of_clubs.gif', (2, 8): 'images/8_of_clubs.gif',\n (2, 9): 'images/9_of_clubs.gif', (2, 10): 'images/10_of_clubs.gif',\n (2, 11): 'images/jack_of_clubs2.gif', (2, 12): 'images/queen_of_clubs2.gif',\n (2, 13): 'images/king_of_clubs2.gif',\n (3, 1): 'images/ace_of_spades.gif', (3, 2): 'images/2_of_spades.gif',\n (3, 3): 'images/3_of_spades.gif', (3, 4): 'images/4_of_spades.gif',\n (3, 5): 'images/5_of_spades.gif', (3, 6): 'images/6_of_spades.gif',\n (3, 7): 'images/7_of_spades.gif', (3, 8): 'images/8_of_spades.gif',\n (3, 9): 'images/9_of_spades.gif', (3, 10): 'images/10_of_spades.gif',\n (3, 11): 'images/jack_of_spades2.gif', (3, 12): 'images/queen_of_spades2.gif',\n (3, 13): 'images/king_of_spades2.gif'}\n cardImg = Image(center, _cards.get((self.suit, self.rank)))\n cardImg.draw(win)\n\n def __str__(self):\n return 'Suit: {} ({})\\tRank: {} ({})'.format(self.getSuitName(), self.getSuit(), self.getRankName(), self.getRank())\n\n\nclass Deck:\n def __init__(self):\n self.cards = []\n\n for s in range(4):\n for r in range(1, 14):\n self.cards.append(Card(s, r))\n\n def getDeck(self):\n return self.cards\n\n def shuffle(self):\n for i in range(self.getLength()):\n card1 = randrange(self.getLength()); card2 = card1\n while card2 == card1:\n card2 = randrange(self.getLength())\n self.swap(card1, card2)\n\n def swap(self, card1, card2):\n self.cards[card1], self.cards[card2] = self.cards[card2], self.cards[card1]\n\n def cut(self):\n _length = len(self.cards)\n cutPoint = randrange(_length // 2 - _length // 10, _length // 2 + _length // 10)\n cut1 = self.cards[:cutPoint]\n cut2 = self.cards[cutPoint+1:]\n self.cards = cut2 + cut1\n\n def getLength(self):\n return len(self.cards)\n\n def toString(self):\n for card in self.cards:\n print(card)\n\n\ndef main():\n deck = Deck()\n deck.shuffle()\n deck.toString()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Chapter10/U10_Ex12_FiveCards/Card.py","file_name":"Card.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"562646704","text":"from .skit import skit_extract_text, SkitLine, SkitChoices\nimport csv\n\ndef split_speakers(speakers):\n split = []\n for i in range(0, 16):\n if (speakers & (1 << i)) != 0:\n split.append(i)\n return split\n #return ','.join(split)\n\ndef extract_skits(l7cdir, outputdir):\n skits = {}\n for file in l7cdir.glob('_Data/Field/Skit/Data/*.dat'):\n with file.open('rb') as f:\n binary = f.read()\n path = file.relative_to(l7cdir / '_Data/Field/Skit/Data')\n skits['/'.join(path.parts)] = skit_extract_text(binary)\n\n with open(outputdir / 'Skit.csv', 'w', encoding='utf-8', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(['File', 'Field', 'Index', 'Speakers', 'Japanese'])\n for path, text in skits.items():\n for i, speaker in enumerate(text[0]):\n writer.writerow([path, 'speaker', i, '', speaker])\n for i, line in enumerate(text[1]):\n if isinstance(line, SkitLine):\n if line.speakerName:\n writer.writerow([path, 'line_speaker', i, '', line.speakerName])\n speakers = split_speakers(line.speakers)\n speakers = '\\n'.join(f'{i} [{text[0][i]}]' for i in speakers)\n writer.writerow([path, 'line', i, speakers, line.text])\n elif isinstance(line, SkitChoices):\n for j, choice in enumerate(line.choices):\n writer.writerow([path, 'choice', i, j, choice])\n\n","sub_path":"toir/formats/skits/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"540456689","text":"from py2neo import Graph, Node, Relationship, authenticate\nfrom passlib.hash import bcrypt\nfrom datetime import datetime\nimport queryService\nimport loadOntologyEntities, readOntology\nimport os\nimport uuid\n\n\n#url = os.environ.get('http://localhost:7474')\n#username = os.environ.get('NEO4J_USERNAME')\n#password = os.environ.get('NEO4J_PASSWORD')\n\n#if username and password:\n #authenticate(url.strip('http://'), username, password)\n\ngraph = Graph('http://localhost:7474/db/data/')\n#graph = Graph(\"http://emboRecTest:TIlvepIFyx5GEyWwsA2l@emborectest.sb04.stations.graphenedb.com:24789/db/data/\")\nclass User:\n def __init__(self, username):\n self.username = username\n\n def find(self):\n user = graph.find_one(\"User\", \"username\", self.username)\n return user\n\n def register(self, password, group, age):\n if not self.find():\n user = Node(\"OnlineMusicAccount\", username=self.username, password=bcrypt.encrypt(password))\n\n graph.create(user)\n\n\n affiliationNode = Node(\"Affiliation\", age=age, affiliation=group)\n graph.create(affiliationNode)\n affRel = Relationship(user, \"schema:affiliation\", affiliationNode)\n graph.create(affRel)\n\n nameNode = Node(\"OnlineMusicAccountName\", username=self.username)\n graph.create(nameNode)\n nameRel = Relationship(user, \"foaf:name\", nameNode)\n graph.create(nameRel)\n\n dateNode = Node(\"Date\", date=date())\n graph.create(dateNode)\n dateRel = Relationship(user, \"dcterms:created\", dateNode)\n graph.create(dateRel)\n\n\n\n\n return True\n else:\n return False\n\n def verify_password(self, password):\n user = self.find()\n if user:\n return bcrypt.verify(password, user['password'])\n else:\n return False\n\n\n def like_post(self, post_id):\n user = self.find()\n post = graph.find_one(\"Post\", \"id\", post_id)\n graph.create_unique(Relationship(user, \"LIKED\", post))\n\n def get_recent_posts(self):\n query = \"\"\"\n MATCH (user:User)-[:searchedFor]->(n)\n WHERE user.username = {username}\n RETURN user.username AS username, n\n \"\"\"\n\n return graph.cypher.execute(query, username=self.username)\n\n def get_statesR(self, stateR):\n user = self.find()\n\n search = Node(\n \"Search\",\n id=str(uuid.uuid4()),\n description=stateR,\n timestamp=timestamp(),\n date=date(),\n )\n search=graph.merge_one(\"SearchFreebase\",\"description\",stateR)\n rel = Relationship(user, \"searchedFor\", search)\n graph.create(rel)\n\n test, test2 = queryService.query(stateR)\n return test\n\n def get_statesO(self, stateO):\n user = self.find()\n\n search = Node(\n \"Search\",\n id=str(uuid.uuid4()),\n description=stateO,\n timestamp=timestamp(),\n date=date(),\n )\n search=graph.merge_one(\"SearchJamendo\",\"description\",stateO)\n rel = Relationship(user, \"searchedFor\", search)\n graph.create(rel)\n\n test, test2 = queryService.query(stateO)\n return test2\n\n def get_roles(self, role):\n user = self.find()\n test, test2 = queryService.query(role)\n return test, test2\n\n\n def get_events(self, event):\n user = self.find()\n test, test2, test3 = queryService.complexQuery(event)\n return test, test2, test3\n\n\n def get_similar_users(self):\n # Find three users who are most similar to the logged-in user\n # based on tags they've both blogged about.\n query = \"\"\"\n MATCH (you:User)-[:searchedFor]->(n)\n (they:User)-[:searchedFor]->(n)\n WHERE you.username = {username} AND you <> they\n RETURN they.username AS similar_user\n \"\"\"\n\n return graph.cypher.execute(query, username=self.username)\n\n def get_other_users(self):\n # Find three users who are most similar to the logged-in user\n # based on tags they've both blogged about.\n query = \"\"\"\n MATCH (user:User)\n WHERE user.username <> {username}\n RETURN user.username AS similar_user\n \"\"\"\n\n return graph.cypher.execute(query, username=self.username)\n\n def get_other_users2(self):\n # Find three users who are most similar to the logged-in user\n # based on tags they've both blogged about.\n query = \"\"\"\n MATCH (they:User)-[:searchedFor]->(n)<-[:searchedFor]-(you:User {username: {username} })\n WHERE they<>you\n RETURN they.username AS users, COUNT(n) AS entities\n ORDER BY entities DESC\n \"\"\"\n return graph.cypher.execute(query, username=self.username)\n\n\n def get_commonality_of_user(self, other):\n # Find how many of the logged-in user's posts the other user\n # has liked and which tags they've both blogged about.\n query = \"\"\"\n MATCH (they:User {username: {they} })\n MATCH (you:User {username: {you} })\n OPTIONAL MATCH (they)-[:CREATED]->(n)<-[:CREATED]-(you)\n RETURN COUNT(n) AS entities, n as entity, they as user\n \"\"\"\n\n return graph.cypher.execute(query, they=other.username, you=self.username)\n\n def add_node(self, stateCreateR, stateCreateO, file, newSound):\n print(stateCreateR, stateCreateO, file, newSound)\n g = readOntology.writeRDF(self.username, stateCreateR, stateCreateO, file, newSound)\n return g\n\ndef get_todays_recent_posts():\n query = \"\"\"\n MATCH (user:User)-[:searchedFor]->(n)\n WHERE n.date = {today}\n RETURN user.username AS username, n\n ORDER BY n.timestamp DESC LIMIT 5\n \"\"\"\n\n return graph.cypher.execute(query, today=date())\n\n#def fill_states():\n\n #moSub, moPred, moObj = loadOntologyEntities.query()\n\n #return moSub\n\n#def fill_roles():\n\n #moSub, moPred, moObj = loadOntologyEntities.query()\n\n #return moPred\n\n#def fill_events():\n\n #moSub, moPred, moObj = loadOntologyEntities.query()\n\n #return moObj\n\n\ndef fill_activities():\n query = \"\"\"\n MATCH (user:User)-[:searchedFor]->(n)\n RETURN n.description\n \"\"\"\n return graph.cypher.execute(query)\n\ndef fill_objects():\n query = \"\"\"\n MATCH (n:OBJECT) RETURN n.description\n \"\"\"\n return graph.cypher.execute(query)\n\ndef timestamp():\n epoch = datetime.utcfromtimestamp(0)\n now = datetime.now()\n delta = now - epoch\n return delta.total_seconds()\n\ndef date():\n return datetime.now().strftime('%Y-%m-%d')\n\n\n","sub_path":"app/modelsOld.py","file_name":"modelsOld.py","file_ext":"py","file_size_in_byte":6679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"4866146","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nargs = sys.argv\n\n#initial value mm\na = float(args[1]) #0.07\nb = float(args[2]) #0.02\nL = float(args[3]) #262.5\nlam = 0.625e-3\n\np = np.pi\nk = 2*p/lam\ntheta = np.linspace(-1, 1, 100000) #variable\nsin = np.sin(theta)\nalpha = k*a*sin/2\nbeta = k*b*sin/2\n\nz = L*sin\nI1 = 4*(np.sin(beta)*np.sin(beta)/(beta*beta))*np.cos(alpha)*np.cos(alpha)\nI2 = 4*(np.sin(beta)*np.sin(beta)/(beta*beta))\n\nxlim = 15\n\nm_a = lam*L/(2*a)\nm_b = lam*L/b\n\nprint ('interbal by alpha : {}'.format(m_a))\nprint ('interbal by beta : {}'.format(m_b))\n\nplt.figure(figsize=(7, 7))\n#ax = fig.add_subplot(1, 1, 1)\nplt.plot(z, I1)\nplt.plot(z, I2)\nplt.title('(a, b, L) = ({0}, {1}, {2})'.format(a, b, L), fontsize=18)\nplt.legend(['alpha', 'beta'], fontsize=18)\nplt.xlim(-xlim, xlim)\n#plt.locator_params(axis='x', tight=True, nbins=xlim*2)\n#plt.xticks(np.arange(-10, 10, 20))\nplt.xlabel('z [mm]', fontsize=18)\nplt.ylabel('Intensity', fontsize=18)\nplt.tick_params(labelsize=18)\n\nplt.savefig('2slitsred_{0}_{1}_{2}.png'.format(a, b, L))\nplt.show()\n","sub_path":"code/draw_theory_red.py","file_name":"draw_theory_red.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"376593933","text":"import django\n\n\nDJANGO_LT_15 = django.VERSION < (1, 5)\nDJANGO_LT_16 = django.VERSION < (1, 6)\nDJANGO_LT_17 = django.VERSION < (1, 7)\n\n\ndef wipe_id_fields_on_django_lt_17(fields):\n \"\"\"\n Remove fields ending in '_id' on Django < 1.7\n\n This required for tests checking the list of fields on a model because in\n Django 1.7, all the FKs appear as `other_model` and `other_model_id`.\n \"\"\"\n if DJANGO_LT_17:\n return [field for field in fields if not field.endswith('_id')]\n return fields\n\n\nclass Python2AssertMixin(object):\n \"\"\"\n Add python 3 asserts to python 2 TestCase\n\n Asserts added:\n * assertCountEqual\n * assertRegex\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Python2AssertMixin, self).__init__(*args, **kwargs)\n if not hasattr(self, 'assertCountEqual'):\n self.assertCountEqual = self.assertItemsEqual\n\n if not hasattr(self, 'assertRegex'):\n self.assertRegex = self.assertRegexpMatches\n","sub_path":"incuna_test_utils/compat.py","file_name":"compat.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"255939697","text":"from page import Page\nfrom components import header\nfrom components import menu\nfrom selenium.common.exceptions import (NoSuchElementException,\n StaleElementReferenceException)\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport main\nfrom selenium.webdriver.support.wait import WebDriverWait as WDW\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n# Page for entering confirmation code for updating personal settings. Code has 9 digits\n\nclass SettingsConfirmationPage(Page):\n url_tail = 'settings/code'\n dynamic = False\n\n def load(self):\n try:\n self.load_body()\n self.menu = menu.SideMenu(self.driver)\n self.header = header.PrivateHeader(self.driver)\n return True\n except (NoSuchElementException, StaleElementReferenceException) as e:\n return False\n\n def load_body(self):\n self.toast = (\n self.driver.find_element_by_class_name(\"sm-secret-code\"))\n self.code = self.read_code()\n self.form = self.driver.find_element_by_tag_name('form')\n self.code_input = self.form.find_element_by_tag_name('input')\n # self.wrong_email_button = self.driver.find_element_by_name()\n if main.is_web(): # no continue button on native\n self.continue_button = self.form.find_element_by_tag_name('button')\n\n def read_code(self):\n WDW(self.driver, 10).until(\n EC.element_to_be_clickable((By.CLASS_NAME, 'sm-secret-code')))\n code = self.toast.text\n code = code[:6]\n time.sleep(.2)\n self.click_toast()\n return code\n\n def click_toast(self):\n self.toast.click()\n time.sleep(.4)\n\n def remember_device(self):\n self.remember_checkbox.click()\n\n def enter_code(self):\n self.code_input.clear()\n self.code_input.send_keys(self.code)\n if main.is_ios():\n self.code_input.send_keys('')\n\n # iOS web. appears no need to click continue. Automatically validates after entering 9 digit code 2/20\n # no continue button on native app\n # if main.is_web():\n # raw_input('about to wait for button to enable')\n # WDW(self.driver, 10).until(lambda x : self.is_enabled(self.continue_button))\n # self.continue_button.click()\n\n def code_accepted(self):\n # After entering code, wait until continue button is enabled.\n WDW(self.driver, 10).until(lambda x : self.is_enabled(self.continue_button))\n return self.is_enabled(self.continue_button)\n","sub_path":"testing/pages/ps_confirmation.py","file_name":"ps_confirmation.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"329383954","text":"import logging\n\nlogger = logging.getLogger(__name__)\n\nimport multiprocessing\nimport os\n\nfrom chainer.dataset import DatasetMixin\nimport chainercv\nimport numpy as np\n\nfrom detector.hand_dataset.bbox_dataset import HandBBoxDataset as HandDataset\nfrom detector.graphics import camera\nfrom detector.hand_dataset.common_dataset import NUM_KEYPOINTS, STANDARD_KEYPOINT_NAMES, COLOR_MAP, EDGES, ROOT_IDX, REF_EDGE\nfrom detector.hand_dataset.common_dataset import make_keypoint_converter, wrist2palm\nfrom detector.hand_dataset.geometry_utils import DATA_CONVENTION\n\nMAX_FRAME_IDX = 1024\nDEFAULT_KEYPOINT_NAMES = [\n \"W\",\n \"T0\",\n \"T1\",\n \"T2\",\n \"T3\",\n \"I0\",\n \"I1\",\n \"I2\",\n \"I3\",\n \"M0\",\n \"M1\",\n \"M2\",\n \"M3\",\n \"R0\",\n \"R1\",\n \"R2\",\n \"R3\",\n \"L0\",\n \"L1\",\n \"L2\",\n \"L3\",\n]\n\nassert len(DEFAULT_KEYPOINT_NAMES) == NUM_KEYPOINTS\n\nNAME_CONVERTER = make_keypoint_converter(\n root=\"W\",\n fingers=[\"T\", \"I\", \"M\", \"R\", \"L\"],\n parts=[\"0\", \"1\", \"2\", \"3\"],\n sep=\"\",\n)\n\nINDEX_CONVERTER = [DEFAULT_KEYPOINT_NAMES.index(NAME_CONVERTER[k]) for k in STANDARD_KEYPOINT_NAMES]\nKEYPOINT_NAMES = STANDARD_KEYPOINT_NAMES\n\n\ndef create_camera_mat():\n # See README.txt\n camera_intr = np.array([\n [617.173, 0, 315.453],\n [0, 617.173, 242.259],\n [0, 0, 1],\n ])\n\n fx = fy = 617.173\n u0 = 315.453\n v0 = 242.259\n\n rgb_camera_intr = camera.CameraIntr(**{\"u0\": u0, \"v0\": v0, \"fx\": fx, \"fy\": fy})\n cameras = {}\n cameras[\"rgb_camera_intr\"] = rgb_camera_intr\n return cameras\n\n\nCAMERAS = create_camera_mat()\nRGB_CAMERA_INTR = CAMERAS[\"rgb_camera_intr\"]\nDEPTH_CAMERA_INTR = None\n\n\nclass GANeratedBaseDataset(DatasetMixin):\n\n def __init__(self, dataset_dir, debug=False, mode=\"train\"):\n self.rgb_camera = RGB_CAMERA_INTR\n self.depth_camera = DEPTH_CAMERA_INTR\n self.n_joints = NUM_KEYPOINTS\n self.root_idx = ROOT_IDX\n self.ref_edge = REF_EDGE\n self.mode = mode\n self.dataset_dir = dataset_dir\n self.annotations = self.load_annotations(dataset_dir, debug=debug)\n\n def __len__(self):\n return len(self.annotations)\n\n def read_rgb(self, rgb_path):\n return chainercv.utils.read_image(rgb_path)\n\n def get_example(self, i):\n return self.annotations[i]\n\n def lemma(self, obj, partition, debug):\n annotations = []\n logger.info(\"> {} {}\".format(obj, partition))\n for frame_idx in range(1, MAX_FRAME_IDX + 1):\n fmt = \"{0:04d}_{1}\"\n img_dir = os.path.join(self.dataset_dir, \"data\", obj, partition)\n name = fmt.format(frame_idx, \"color_composed.png\")\n color_composed_path = os.path.join(img_dir, name)\n name = fmt.format(frame_idx, \"crop_params.txt\")\n crop_params_path = os.path.join(img_dir, name)\n name = fmt.format(frame_idx, \"joint2D.txt\")\n joint2D_path = os.path.join(img_dir, name)\n name = fmt.format(frame_idx, \"joint_pos.txt\")\n joint_pos_path = os.path.join(img_dir, name)\n name = fmt.format(frame_idx, \"joint_pos_global.txt\")\n joint_pos_global_path = os.path.join(img_dir, name)\n if not os.path.exists(joint_pos_global_path):\n continue\n if DATA_CONVENTION == \"ZYX\":\n joint = np.loadtxt(joint_pos_global_path, delimiter=',').reshape(-1, 3)\n rgb_joint = joint[:, ::-1]\n else:\n rgb_joint = np.loadtxt(joint_pos_global_path, delimiter=',').reshape(-1, 3)\n\n rgb_joint = rgb_joint[INDEX_CONVERTER]\n rgb_joint = wrist2palm(rgb_joint)\n crop_u, crop_v, scale = crop_param = np.loadtxt(crop_params_path, delimiter=',')\n rgb_camera = RGB_CAMERA_INTR.translate_camera(y_offset=-crop_v, x_offset=-crop_u)\n rgb_camera = rgb_camera.scale_camera(y_scale=scale, x_scale=scale)\n example = {}\n example[\"hand_side\"] = \"left\"\n example[\"rgb_path\"] = color_composed_path\n example[\"rgb_joint\"] = rgb_joint\n example[\"rgb_camera\"] = rgb_camera\n annotations.append(example)\n if debug and len(annotations) > 10:\n return annotations\n return annotations\n\n def load_annotations(self, dataset_dir, debug=False):\n logger.info(\"> load annotation mode = {}\".format(self.mode))\n logger.info(\"> dataset_dir = {}\".format(dataset_dir))\n annotations = []\n queries = []\n for obj in [\"noObject\", \"withObject\"]:\n partitions = sorted(os.listdir(os.path.join(dataset_dir, \"data\", obj)))\n for partition in partitions:\n if self.mode == \"train\":\n if os.path.basename(partition) in [\"0001\", \"0002\", \"0003\"]:\n continue\n else:\n if not os.path.basename(partition) in [\"0001\", \"0002\", \"0003\"]:\n continue\n\n queries.append([obj, partition, debug])\n\n with multiprocessing.Pool() as pool:\n anns = pool.starmap(self.lemma, queries)\n for a in anns:\n annotations += a\n return annotations\n\n\ndef get_base_dataset(dataset_dir, **kwargs):\n base = GANeratedBaseDataset(dataset_dir, **kwargs)\n return base\n\n\ndef get_ganerated_dataset(dataset_dir, param, **kwargs):\n base = get_base_dataset(dataset_dir, **kwargs)\n dataset = HandDataset(base, param)\n return dataset\n\n\ndef get_dataset(dataset_dir, param, **kwargs):\n dataset = get_ganerated_dataset(dataset_dir, param, **kwargs)\n return dataset\n\n\ndef visualize_dataset(dataset_dir):\n from matplotlib import pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D # NOQA\n from chainercv.utils import read_image\n from visualizations import vis_point, vis_edge\n\n dataset = GANeratedBaseDataset(dataset_dir, debug=False, mode=\"train\")\n idx = np.random.choice(len(dataset))\n print(idx, len(dataset))\n example = dataset.get_example(idx)\n rgb_joint = example[\"rgb_joint\"]\n rgb_path = example[\"rgb_path\"]\n rgb = read_image(rgb_path)\n fig = plt.figure(figsize=(5, 10))\n ax2 = fig.add_subplot(211)\n ax4 = fig.add_subplot(212, projection=\"3d\")\n color = [COLOR_MAP[k] for k in KEYPOINT_NAMES]\n edge_color = [COLOR_MAP[s, t] for s, t in EDGES]\n rgb_vu = example[\"rgb_camera\"].zyx2vu(rgb_joint)\n vis_point(rgb_vu, img=rgb, color=color, ax=ax2)\n vis_edge(rgb_vu, indices=EDGES, color=edge_color, ax=ax2)\n\n vis_point(rgb_joint, color=color, ax=ax4)\n vis_edge(rgb_joint, indices=EDGES, color=edge_color, ax=ax4)\n\n for ax in [ax4]:\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"z\")\n ax.view_init(-65, -90)\n\n plt.show()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n logger.setLevel(logging.INFO)\n dataset_dir = os.path.expanduser(\"~/dataset/GANeratedHands_Release\")\n visualize_dataset(dataset_dir)\n","sub_path":"src/detector/hand_dataset/ganerated_dataset.py","file_name":"ganerated_dataset.py","file_ext":"py","file_size_in_byte":7015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"617839573","text":"import urllib.request,urllib.error\nfrom datetime import datetime\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n# Define a list of urls to check.\n# If a db is included in the site, include an extra url of a page that includes data from db\nurls_to_check = [\n\n\t# Everyday Lookism\n\t\"https://everydaylookism.bham.ac.uk/\",\n\t\"https://everydaylookism.bham.ac.uk/1\",\n\n\t# Hispanic Exile\n\t\"https://hispanic-exile.bham.ac.uk/\",\n\t\"https://hispanic-exile.bham.ac.uk/people/113\",\n\n\t# Digital Cultures (with hyphen)\n\t\"https://digital-cultures.bham.ac.uk/\",\n\t\"https://digital-cultures.bham.ac.uk/research/1\",\n\t# Digital Cultures (without hyphen)\n\t\"https://digitalcultures.bham.ac.uk/\",\n\t\"https://digitalcultures.bham.ac.uk/research/1\",\n\n\t# Testimony in Practice\n\t\"https://testimonyinpractice.bham.ac.uk/\",\n\t\"https://testimonyinpractice.bham.ac.uk/testimonies/\",\n\n\t# Everything To Everybody\n\t\"https://everythingtoeverybody.bham.ac.uk/\",\n\n\t# Out Of Our Minds\n\t\"https://outofourminds.bham.ac.uk/\",\n\t\"https://outofourminds.bham.ac.uk/blog/12\",\n\n\t# Visualise Baudelaire\n\t\"https://visualisebaudelairesong.bham.ac.uk/\",\n\n\t# Performance and the Environment\n\t\"https://theatre-environment.bham.ac.uk/\",\n\t\"https://theatre-environment.bham.ac.uk/gulp/tour/\",\n\n\t# AlterUmma\n\t\"https://alterumma.bham.ac.uk\",\n\n\t# Estoria\n\t\"https://transcribeestoria.bham.ac.uk/en/\"\n\n]\n\n\ndef build_error_dict(url, error):\n\t\"\"\"\n\tBuild and return a dictionary that includes error details\n\t\"\"\"\n\treturn {'url': url, 'error': error, 'datetime': datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")}\n\n\n# Loop through urls, storing any errors in list\nerrors_list = []\nfor url in urls_to_check:\n\n\ttry:\n\t\turllib.request.urlopen(url)\n\n\texcept urllib.error.HTTPError as error:\n\t\terrors_list.append(build_error_dict(url, error))\n\n\texcept urllib.error.URLError as error:\n\t\terrors_list.append(build_error_dict(url, error))\n\n\texcept:\n\t\terrors_list.append(build_error_dict(url, 'unknown error'))\n\n\n# Notify me of errors via email (if any exist)\nif(len(errors_list) > 0):\n\t\n\t# Set up the SMTP server\n\tserver = smtplib.SMTP(host='smtp.bham.ac.uk', port=25)\n\n\t# Build the email\n\temail = MIMEMultipart()\n\temail['From'] = \"m.j.allaway@bham.ac.uk\"\n\temail['To'] = \"allawamj@adf.bham.ac.uk\"\n\temail['Subject'] = \"Unable to reach URL(s)\"\n\n\t# Build message text and attach to email\n\terrors_text = \"Found {} error(s) from a total of {} URLs checked:\\n\".format(len(errors_list), len(urls_to_check))\n\tfor e in errors_list:\n\t\terrors_text += \"\\nurl: {}\\nerror: {}\\ndatetime: {}\\n\".format(e['url'], e['error'], e['datetime'])\n\temail.attach(MIMEText(str(errors_text), 'plain'))\n\n\t# Send the email\n\tserver.send_message(email)\n\n\t# Tidy up\n\tdel email\n\tserver.quit()\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"183734667","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport numpy as np\nfrom dash.dependencies import Output, Input\nimport dash_bootstrap_components as dbc\nfrom app import app\n\n\n\n\ndata = pd.read_csv(\"stockScreen.csv\")\nsymbols = pd.unique(data['stock'])\n\n\n\n\n\n\nheaderLayout = html.Div(children=[\n html.H1(children=\"Individual Stock\", className= 'header-content'),\n html.P(children=\"Screen for Trading Opportunities!\", className='header-description')],className='header')\n\nstockFilterLayout = html.Div(children=[\n html.Div(children='Stock', className='menu-title'),\n dcc.Dropdown(id= 'stock-filter',\n options=[{\"label\": symbol, \"value\": symbol} for symbol in symbols],\n value=symbols[0], clearable=False, className='filter-menus')], className='filter-menu2')\n\ndef makeLayouts(num_of_charts):\n #outList = [do_something_with(item) for i in range(num_of_charts)]\n outList = [html.Div(children=dcc.Graph(id=(\"stockchart\" + str(i)), config={\"displayModeBar\": False}), className='card') for i in range(num_of_charts)]\n return outList\n\nmenuLayout = html.Div(children=[stockFilterLayout], className='menu')\ngraphLayout = html.Div(children=makeLayouts(1), className = 'wrapper')\n\nlayout = html.Div(children=[headerLayout, menuLayout, graphLayout])\n\n\n@app.callback(\n Output(\"stockchart0\", \"figure\"),\n [Input(\"stock-filter\", \"value\"),\n# Input(\"date-range\", \"start_date\"),\n# Input(\"date-range\", \"end_date\"),\n ],\n)\n\ndef update_charts(symbol):\n filtered_data = data[data['stock'] == symbol]\n filtered_data = filtered_data.iloc[-60:]\n \n \n price_chart_figure = {\n \"data\": [\n{\n \"x\": filtered_data[\"Date\"],\n \"y\": filtered_data[\"Close\"],\n \"type\": \"lines\",\n \"hovertemplate\": \"$%{y:.2f}\",\n },\n ],\n \n \"layout\": {\"title\": {\"text\": str(symbol),\"x\": 0.05,\"xanchor\": \"left\"},\n \"xaxis\": {\"fixedrange\": True}, \n \"yaxis\": {\"tickprefix\": \"$\", \"fixedrange\": True}, \"colorway\": [\"#17B897\"],},}\n \n\n return price_chart_figure\n\n\n# if __name__ == \"__main__\":\n# app.run_server(debug=True)","sub_path":"insight/apps/stage.py","file_name":"stage.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"150384776","text":"\"\"\"\nA sample showing how to have a NAOqi service as a Python app.\n\"\"\"\nfrom threading import currentThread, Thread\n\nimport time\n\n__version__ = \"0.0.3\"\n\n\n\nimport qi\n\nimport stk.runner\nimport stk.events\nimport stk.services\nimport stk.logging\nimport vision_definitions\nimport numpy\nimport cv2\n\nclass Depthcamera(object):\n \"NAOqi service example (set/get on a simple value).\"\n\n APP_ID = \"com.aldebaran.Depthcamera\"\n def __init__(self, qiapp):\n # generic activity boilerplate\n self.qiapp = qiapp\n self.events = stk.events.EventHelper(qiapp.session)\n self.s = stk.services.ServiceCache(qiapp.session)\n self.logger = stk.logging.get_logger(qiapp.session, self.APP_ID)\n # Internal variables\n self.level = 0\n self.resolution = vision_definitions.kQVGA\n self.colorSpace = vision_definitions.kDepthColorSpace\n self.fps = 10\n self.camera = self.s.ALVideoDevice\n self.nameId = None\n self.thread = None\n\n\n def getImage(self):\n image = self.camera.getImageRemote(self.nameId)\n image_width = image[0]\n image_height = image[1]\n\n return numpy.frombuffer(image[6], numpy.uint8).reshape(image_height, image_width, 1)\n\n def releaseImage(self):\n self.camera.releaseImage(self.nameId)\n\n def unsubscribe(self):\n self.camera.unsubscribe(self.nameId)\n\n def subscribeCamera(self):\n # subscribe or subscribeCamera?? - subscribe is deprecated\n self.nameId = self.camera.subscribeCamera(\"DepthCamera\", 2, self.resolution, self.colorSpace, self.fps)\n\n @qi.bind(returnType=qi.Void, paramsType=[qi.String, qi.Int8])\n def record(self, name, t):\n fourcc = cv2.cv.CV_FOURCC(*'XVID')\n out = cv2.VideoWriter(\"/home/nao/\" + name, fourcc, self.fps, (320, 240), 0)\n self.subscribeCamera()\n for i in range(int(t) * self.fps):\n img = self.getImage()\n self.releaseImage()\n out.write(img)\n time.sleep(1.0 / float(self.fps))\n self.unsubscribe()\n out.release()\n\n def run(self, name):\n \"\"\"\n Loop on, wait for events until manual interruption.\n \"\"\"\n\n fourcc = cv2.cv.CV_FOURCC(*'XVID')\n out = cv2.VideoWriter(\"/home/nao/\" + name, fourcc, self.fps, (320, 240), 0)\n self.subscribeCamera()\n t = currentThread()\n\n while getattr(t, \"do_run\", True):\n img = self.getImage()\n self.releaseImage()\n out.write(img)\n time.sleep(1.0 / float(self.fps + 2))\n\n self.unsubscribe()\n out.release()\n\n @qi.bind(returnType=qi.Void, paramsType=[qi.String])\n def start_recording(self, name):\n self.thread = Thread(target=self.run,\n args=(name,))\n self.thread.start()\n\n @qi.bind(returnType=qi.Void, paramsType=[])\n def stop_recording(self):\n self.thread.do_run = False\n self.thread.join()\n\n @qi.bind(returnType=qi.Void, paramsType=[qi.Int8])\n def set(self, level):\n \"Set level\"\n self.level = level\n\n @qi.bind(returnType=qi.Int8, paramsType=[])\n def get(self):\n \"Get level\"\n return self.level\n\n @qi.bind(returnType=qi.Void, paramsType=[])\n def reset(self):\n \"Reset level to default value\"\n return self.set(0)\n\n @qi.bind(returnType=qi.Void, paramsType=[])\n def stop(self):\n \"Stop the service.\"\n self.logger.info(\"Depthcamera stopped by user request.\")\n self.qiapp.stop()\n\n @qi.nobind\n def on_stop(self):\n \"Cleanup (add yours if needed)\"\n self.logger.info(\"Depthcamera finished.\")\n\n####################\n# Setup and Run\n####################\n\nif __name__ == \"__main__\":\n stk.runner.run_service(Depthcamera)\n\n","sub_path":"depthCamera/grant_robot/app/scripts/depthcamera.py","file_name":"depthcamera.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"414683301","text":"## Bradley Swanson\n## ID: 4370381\n## CS3130\n## Final Project\n##\n## This module runs the client node of APS. The client is only used for\n## getting input from the user, and then submitting the processing request\n## to the server.\n\nimport socket\nimport time\nfrom socket_tools import recvcomp, sendcomp\nfrom constants import *\nimport uuid\nimport random\n\n# globals\ntcp_ip = None\ntcp_port = None\n\ndef start(ip, port):\n \"\"\"\n Starts the client module and begins the main loop.\n Allows for user input, and then sends the message to the\n server to execute the command specified by the user.\n \"\"\"\n global tcp_ip\n global tcp_port\n tcp_ip = ip\n tcp_port = port\n\n options = [\n quicksort,\n ]\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connect()\n while True:\n \"\"\"\n Main loop. Displays the menu, asks for a selection,\n and retrieves stock data\n \"\"\"\n menu()\n selection = getinput()\n print(\"--\")\n if selection == 1:\n quit()\n options[selection](sock)\n \n\n\ndef menu():\n \"\"\"A simple function for printing the menu\"\"\"\n m = \"\"\"--\nAlgorithm Processing System\n \nSelect one of following: \n 1) Quicksort\n 2) Quit\n \"\"\"\n print(m)\n\n\ndef getinput():\n \"\"\"Get user input and validate until good input\"\"\"\n while True:\n usrin = input(\">>>\")\n try:\n selection = int(usrin) - 1\n except Exception:\n print(\"Please enter a number selection only\")\n else:\n if selection not in range(2):\n print(\"Selection must be in range 1-2\")\n else:\n return selection\n\n\ndef connect():\n \"\"\"Connect to the server\"\"\"\n global sock\n print(\"Waiting for server...\")\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n while True:\n try:\n sock.connect((tcp_ip, tcp_port))\n except Exception as e:\n time.sleep(1)\n else:\n print(\"Server connected\")\n break\n\n\ndef sendrecv(msg):\n \"\"\"Send a request and get the response\"\"\"\n global sock\n while True:\n try:\n sendcomp(sock, msg)\n data = recvcomp(sock)\n if data == '':\n print(\"Server connection lost\")\n connect()\n continue\n else:\n data = data.split(\" \", 3)\n if data[0] == \"300\":\n print(\"COMPLETED\")\n print(data[3])\n print(\"--\")\n print(\"Press enter to continue\", end='')\n input()\n elif data[0] == \"400\":\n print(\"--\")\n print(\"No workers available to handle your request\")\n elif data[0] == \"500\":\n print(\"--\")\n print(\"Server does not support the entered command\")\n else:\n print(\"--\")\n print(\"Failed to parse server response\")\n break\n except Exception as e:\n print(e)\n print(\"Server connection lost\")\n connect()\n return data\n\n\ndef quicksort(sock):\n \"\"\"\n The function for dispatching a quicksort request.\n \"\"\"\n random.seed(time.time())\n while True:\n print(\"Enter a series of numbers separated by commas only. ie: 1,2,3,4,5\")\n print(\"Or type 'random ' to generate a random series. ie: random 10\")\n print(\"--\")\n text = input()\n print(\"--\")\n if text.startswith('random'):\n params = text.split(\" \")\n if len(params) < 2:\n print(\"Invalid input. Please specify length\")\n else:\n try:\n length = int(params[1])\n except Exception:\n print(\"Invalid input. Please specify length\")\n else:\n data = list()\n for i in range(length):\n data.append(random.randint(0,int(length*2)))\n break\n else:\n params = text.split(',')\n if len(params) < 2:\n print(\"Please enter at least two items\")\n else:\n data = list()\n for i in params:\n try:\n if i != '':\n data.append(int(i.strip()))\n except Exception:\n print(\"Please enter integers only\")\n print(\"--\")\n continue\n print(data)\n break\n print('--')\n guid = uuid.uuid4().hex\n msg = '200 {0} {1} {2}'.format(guid, QUICKSORT, data)\n print(\"QUICKSORT\")\n print(data)\n sendrecv(msg)\n\n\n\n\nif __name__ == \"__main__\":\n start(DEFAULT_IP, DEFAULT_PORT)\n\n\n\n\n\n\n\n","sub_path":"final_assignment/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"531287531","text":"from flask_login import login_required, current_user, login_user, logout_user, LoginManager\nfrom flask import jsonify, render_template, request, redirect, flash, url_for, abort\nfrom datetime import datetime, timedelta\nfrom is_safe_url import is_safe_url\n\nfrom app import app, db, bcrypt, login_manager\nfrom app.models import Event, User\nfrom app.forms import EventsForm, CreateUserForm, LoginForm\n\nlogin_manager = LoginManager()\nlogin_manager.login_view = 'login'\n# # login_manager.session_protection = 'strong'\nlogin_manager.init_app(app)\n\n@login_manager.user_loader\ndef user_loader(email):\n return User.query.filter_by(email=email).first()\n\n@login_manager.request_loader\ndef request_loader(request):\n email = request.form.get('email')\n user = User.query.filter_by(email=email).first()\n if not user:\n return\n user.authenticated = True\n db.session.add(user)\n db.session.commit()\n return user\n\n@app.route('/')\ndef index():\n mes = \"Hi, it is project about user's events!\"\n return render_template('index.html', mes=mes)\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n # if current_user.is_authenticated:\n # return redirect('/')\n form = LoginForm()\n print(f'form.email.data {form.email.data}')\n if form.validate_on_submit():\n curr_user = User.query.filter_by(email=form.email.data).first()\n if curr_user:\n if bcrypt.check_password_hash(curr_user.password, form.password.data):\n curr_user.authenticated = True\n db.session.add(curr_user)\n db.session.commit()\n login_user(curr_user, remember=True)\n print('current_user.email login = ', current_user.email) \n # return redirect(\"/events_list\")\n return redirect(\"/\")\n else:\n flash('Email or password is not correct')\n return redirect(\"/login\")\n else: \n # flash('Please, fill email and password fields!')\n return redirect(\"/create_user\")\n return render_template(\"login.html\", form=form)\n\n@app.route(\"/create_user\", methods=[\"GET\", \"POST\"])\ndef create_user():\n message = ''\n form = CreateUserForm()\n \n if form.validate_on_submit():\n email = request.form.get('email')\n password = request.form.get('password')\n new_user = User(email=email, password=bcrypt.generate_password_hash(password).decode('utf-8'))\n db.session.add(new_user)\n db.session.commit()\n flash('User created successfully')\n return redirect('/login')\n return render_template(\"create_user.html\", form=form)\n\n@app.route('/logout', methods=['POST', 'GET'])\n@login_required\ndef logout():\n user = current_user\n user.authenticated = False\n db.session.add(user)\n db.session.commit()\n logout_user()\n return redirect('/login')\n\n# @csrf.exempt\n# для залогиненного пользователя доступна форма, которая позволяет добавить событие.\n# У события должны быть следующие параметры: автор, время начала, время конца, тема и описание\n@app.route('/add_event', methods=['POST', 'GET'])\n@login_required\ndef add_event():\n events_form = EventsForm()\n print(f'add_event request.method {request.method} ')\n if request.method == 'POST':\n\n if events_form.validate_on_submit():\n\n author = request.form.get('author')\n from_date = request.form.get('from_date')\n to_date = request.form.get('to_date')\n theme = request.form.get('theme')\n description = request.form.get('description')\n author = current_user.email\n print(f'author {author}')\n ev = Event(author=author, from_date=from_date, to_date=to_date, theme=theme, description=description)\n db.session.add(ev)\n db.session.commit()\n return redirect('/events_list')\n flash(f'Form was not validated {events_form.errors}')\n \n return render_template('events.html', form=events_form)\n\n# список всех событий для залогиненного пользователя\n@app.route('/events_list')\n@login_required\ndef events_list():\n events = Event.query.order_by(Event.from_date).all()\n return render_template('events_list.html', object_list=events)\n\n@app.route('/events_user')\ndef events_user():\n events = Event.query.filter_by(author=current_user.email).all()\n return render_template('events_user.html', object_list=events)\n\n# Детальнее\n@app.route('/events/')\n@login_required\ndef view_event(_id):\n this_event = Event.query.get(_id)\n return render_template('view_event.html', event = this_event)\n\n# Обновить - редактировать\n@app.route('/events//edit', methods=['POST', 'GET'])\n@login_required\ndef edit_event(_id):\n this_event = Event.query.get(_id)\n if request.method == 'POST':\n this_event.from_date = request.form['from_date']\n this_event.to_date = request.form['to_date']\n this_event.theme = request.form['theme']\n this_event.description = request.form['description']\n try:\n db.session.add(this_event)\n db.session.commit()\n return redirect('/events_list')\n except:\n return 'При обновлении записи произошла ошибка'\n return render_template('edit_event.html', event = this_event)\n\n# Удалить\n@app.route('/events//del')\n@login_required\ndef delete_event(_id):\n del_event = Event.query.get_or_404(_id)\n print(del_event.theme)\n try:\n db.session.delete(del_event)\n db.session.commit()\n return redirect('/events_list')\n except:\n return 'При удалении события произошла ошибка'","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"645019982","text":"import arcade\nimport random\nimport math\nfrom array import array\n\nfrom Graphics.Particles.ParticleSystem import ParticleSystem\n\n\nclass FireballTrail(ParticleSystem):\n def __init__(self, context, physics):\n # load some shaders\n super().__init__(context)\n\n self.frame_count = 0\n self.physics = physics\n\n self.program = context.load_program(\n vertex_shader=\"Graphics/Particles/Fireball/Trail/fireball_trail.vs\",\n geometry_shader=\"Graphics/Particles/Fireball/Trail/fireball_trail.gs\",\n fragment_shader=\"Graphics/Particles/Fireball/Trail/fireball_trail.fs\",\n )\n\n self.burst_program = context.load_program(\n vertex_shader=\"Graphics/Particles/Fireball/Trail/fireball_trail_emit.vs\",\n )\n\n self.init_system(\n 5000,\n \"2f 2f 1f 1f\",\n [\"in_position\", \"in_velocity\", \"in_life_offset\", \"in_type\"],\n [0.0, 0.0, 0.0, 0.0, 1000.0, 0.0],\n 6.0)\n\n\n\n def render(self, projection_matrix, projectile_list):\n self.frame_count += 1\n if (self.frame_count % 3 == 0):\n self.do_emission(projectile_list)\n\n super().render(projection_matrix)\n\n def do_emission(self, projectile_list):\n if len(projectile_list) == 0:\n return\n vao = self.build_buffer(projectile_list)\n self.emit_with_program(self.burst_program, len(projectile_list), vao=vao)\n\n def build_projectile_data(self, projectile_list):\n data = []\n for projectile in projectile_list:\n data.append(projectile.center_x)\n data.append(projectile.center_y)\n\n velocity = self.physics.get_physics_object(sprite=projectile).body.velocity\n\n data.append(velocity[0])\n data.append(velocity[1])\n data.append(projectile.art_type)\n return data\n\n def build_buffer(self, projectile_list):\n\n projectile_data = self.build_projectile_data(projectile_list)\n\n asArray = array(\"f\", projectile_data)\n buffer = self.context.buffer(data=asArray)\n buffer_description = arcade.gl.BufferDescription(\n buffer, \"2f 2f 1f\", [\"in_position\", \"in_base_vel\", \"in_type\"]\n )\n vao = self.context.geometry([buffer_description])\n return vao\n","sub_path":"Graphics/Particles/Fireball/Trail/FireballTrail.py","file_name":"FireballTrail.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"392808762","text":"from os import path, environ\nimport subprocess\nTHIS_FOLDER = path.abspath(path.dirname(__file__))\n\n\ndef get_path_to_ssh_key():\n try:\n return environ['PATH_TO_SSH_KEY']\n except KeyError:\n raise ValueError('PATH_TO_SSH_KEY environment variable is not set')\n\n\ndef create_session_on_server(host, email):\n return subprocess.check_output(\n [\n 'fab',\n 'create_session_on_server:email={0}'.format(email),\n '-i{0}'.format(get_path_to_ssh_key()),\n '--host={0}'.format(host),\n '--hide=everything,status',\n ],\n cwd=THIS_FOLDER\n ).decode().strip()\n\n\ndef reset_database(host):\n subprocess.check_call(\n [\n 'fab', \n 'reset_database',\n '-i{0}'.format(get_path_to_ssh_key()),\n '--host={0}'.format(host)\n ],\n cwd=THIS_FOLDER\n )\n","sub_path":"functional_tests/server_tools.py","file_name":"server_tools.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"334047722","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport gzip\nimport os\nimport re\nimport sys\nimport tarfile\nimport tensorflow.python.platform\n\nimport tensorflow as tf\nimport cifar10_input as cifar10_input\n\nFLAGS = tf.app.flags.FLAGS\n\n\ntf.app.flags.DEFINE_integer('batch_size', 1,\n \"\"\"Number of images to process in a batch.\"\"\")\ntf.app.flags.DEFINE_string('data_dir', 'cifar10_data/',\n \"\"\"Path to the CIFAR-10 data directory.\"\"\")\n\n\n\n#图片大小和label的数量\nIMAGE_SIZE = cifar10_input.IMAGE_SIZE #224\nNUM_CLASSES = cifar10_input.NUM_CLASSES #5\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_EVAL\nTOWER_NAME = 'tower'\nMOVING_AVERAGE_DECAY = 0.9999 # 对平均数的衰退.\nNUM_EPOCHS_PER_DECAY = 350.0 # 学习速率衰退后的训练周期\nLEARNING_RATE_DECAY_FACTOR = 0.1 # 学习速率衰退的因素.\nINITIAL_LEARNING_RATE = 0.1 # 初始化学习速率.\n\n#-------------------------------读取二进制-------------------------------\ndef distorted_inputs():\n if not FLAGS.data_dir:\n raise ValueError('找不到data的文件目录')\n data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')\n return cifar10_input.distorted_inputs(data_dir=data_dir,\n batch_size=FLAGS.batch_size)\n\n#--------------------------------神经网络--------------------------------\ndef inference(images):\n # conv1\n with tf.variable_scope('conv1') as scope:\n #使用衰减权重\n kernel = _variable_with_weight_decay('weights', shape=[5, 5, 3, 64],\n stddev=1e-4, wd=0.0)\n\n print(images)\n\n conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')\n\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))\n bias = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(bias, name=scope.name)\n _activation_summary(conv1)\n\n #\n\n # pool1\n pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],\n padding='SAME', name='pool1')\n\n #\n # 输出归一化,把数据范围限制在你需要的范围\n norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm1')\n\n\n\n # conv2\n with tf.variable_scope('conv2') as scope:\n kernel = _variable_with_weight_decay('weights', shape=[5, 5, 64, 64],\n stddev=1e-4, wd=0.0)\n conv = tf.nn.conv2d(norm1, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n bias = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(bias, name=scope.name)\n _activation_summary(conv2)\n\n # norm2\n #norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n # name='norm2')\n # pool2\n pool2 = tf.nn.max_pool(conv2, ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1], padding='SAME', name='pool2')\n\n norm2 = tf.nn.lrn(pool2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm2')\n\n # conv3\n with tf.variable_scope('conv3') as scope:\n kernel = _variable_with_weight_decay('weights', shape=[5, 5, 64, 64],\n stddev=1e-4, wd=0.0)\n conv = tf.nn.conv2d(norm2, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n bias = tf.nn.bias_add(conv, biases)\n conv3 = tf.nn.relu(bias, name=scope.name)\n _activation_summary(conv3)\n\n # pool3\n pool3 = tf.nn.max_pool(conv3, ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1], padding='SAME', name='pool2')\n\n norm3 = tf.nn.lrn(pool3, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm2')\n\n # conv4\n with tf.variable_scope('conv4') as scope:\n kernel = _variable_with_weight_decay('weights', shape=[5, 5, 64, 64],\n stddev=1e-4, wd=0.0)\n conv = tf.nn.conv2d(norm3, kernel, [1, 1, 1, 1], padding='SAME')\n biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))\n bias = tf.nn.bias_add(conv, biases)\n conv4 = tf.nn.relu(bias, name=scope.name)\n _activation_summary(conv4)\n\n\n\n norm4 = tf.nn.lrn(conv4, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,\n name='norm2')\n\n # pool4\n pool4 = tf.nn.max_pool(norm4, ksize=[1, 3, 3, 1],\n strides=[1, 2, 2, 1], padding='SAME', name='pool2')\n\n\n\n\n\n\n\n\n # local3\n with tf.variable_scope('local3') as scope:\n\n dim = 1\n for d in pool4.get_shape()[1:].as_list():\n dim *= d\n\n #\n\n reshape = tf.reshape(pool4, [FLAGS.batch_size, dim])\n\n #\n weights = _variable_with_weight_decay('weights', shape=[dim, 384],\n stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [384], tf.constant_initializer(0.1))\n local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)\n print(local3)\n _activation_summary(local3)\n\n # local4\n with tf.variable_scope('local4') as scope:\n weights = _variable_with_weight_decay('weights', shape=[384, 192],\n stddev=0.04, wd=0.004)\n biases = _variable_on_cpu('biases', [192], tf.constant_initializer(0.1))\n local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name=scope.name)\n print(local4) #(1,192)\n _activation_summary(local4)\n\n\n with tf.variable_scope('softmax_linear') as scope:\n weights = _variable_with_weight_decay('weights', [192, NUM_CLASSES],\n stddev=1/192.0, wd=0.0)\n biases = _variable_on_cpu('biases', [NUM_CLASSES],\n tf.constant_initializer(0.0))\n softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)\n print(softmax_linear)\n _activation_summary(softmax_linear)\n\n return softmax_linear\n\n#------------------------------作报告-------------------------------\n\ndef _activation_summary(x):\n\n tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n tf.summary.histogram(tensor_name + '/activations', x)\n tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_fraction(x))\n\n#--------------------------cpu上初始化参数-------------------------\n\ndef _variable_on_cpu(name, shape, initializer):\n\n with tf.device('/cpu:0'):\n var = tf.get_variable(name, shape, initializer=initializer)\n return var\n\n\n\n#---------------------------创建衰减型参数-------------------------\n\ndef _variable_with_weight_decay(name, shape, stddev, wd):\n\n var = _variable_on_cpu(name, shape,\n tf.truncated_normal_initializer(stddev=stddev))\n if wd:\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\n#-----------------------------Loss-----------------------------\ndef loss(logits, labels):\n\n #将image和label组合起来\n\n sparse_labels = tf.reshape(labels, [FLAGS.batch_size, 1])\n\n #batches [1,10] , labels [1,1]\n\n indices = tf.reshape(tf.range(FLAGS.batch_size), [FLAGS.batch_size, 1])\n #indices = tf.reshape(range(FLAGS.batch_size), [FLAGS.batch_size, 1])\n #组合\n print(indices.shape,\"haha1\")\n print(sparse_labels.shape,\"mama1\")\n\n concated = tf.concat([indices, sparse_labels],1)\n dense_labels = tf.sparse_to_dense(concated,\n [FLAGS.batch_size, NUM_CLASSES],\n 1.0, 0.0)\n\n #计算交叉熵\n cross_entropy = tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=dense_labels, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\n\n#------------------------------train-------------------------\ndef train(total_loss, global_step):\n #返回一个训练的节点\n # 初始化训练速率.\n num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size\n decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)\n\n # 通过训练的步数来是训练速率衰减.\n lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE,\n global_step,\n decay_steps,\n LEARNING_RATE_DECAY_FACTOR,\n staircase=True)\n tf.summary.scalar('learning_rate', lr)\n\n\n loss_averages_op = _add_loss_summaries(total_loss)\n\n # 计算梯度\n with tf.control_dependencies([loss_averages_op]):\n opt = tf.train.GradientDescentOptimizer(lr)\n grads = opt.compute_gradients(total_loss)\n\n # 提供梯度\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n\n # 添加训练参数的直方图\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name, var)\n\n # 梯度直方图.\n for grad, var in grads:\n if grad is not None:\n tf.summary.histogram(var.op.name + '/gradients', grad)\n\n variable_averages = tf.train.ExponentialMovingAverage(\n MOVING_AVERAGE_DECAY, global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n with tf.control_dependencies([apply_gradient_op, variables_averages_op]):\n train_op = tf.no_op(name='train')\n\n return train_op\n\n\n#------------------------Loss记录----------------------\ndef _add_loss_summaries(total_loss):\n #产生移动平均损失.\n\n loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')\n losses = tf.get_collection('losses')\n loss_averages_op = loss_averages.apply(losses + [total_loss])\n\n for l in losses + [total_loss]:\n\n tf.summary.scalar(l.op.name +' (raw)', l)\n tf.summary.scalar(l.op.name, loss_averages.average(l))\n\n return loss_averages_op\n\n","sub_path":"cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":9974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"653393399","text":"import numpy as np\nimport PIL.Image as Image\nimport torch.nn.functional as functional\nimport torch\n\nimg_path = 'cups.png' \n\ndef apply_distortion(y,x, k1, k2):\n r2 = y**2 + x**2\n f = 1 + k1 * k2 + k2 * r2**2\n return y * f, x * f\n\ndef distorted_ordinates(y, x, h, w):\n y_n = 2 * (y/h) - 1\n x_n = 2 * (x/w) - 1\n # distortion function\n k1, k2 = 0.05,0.1\n y_d, x_d = apply_distortion(y_n,x_n,k1,k2) \n return y_d,x_d\n\ndef distorting_img(img_path):\n img = np.array(Image.open(img_path)).astype(np.float32)\n h,w,_ = img.shape\n img_d = np.zeros(img.shape)\n grid = torch.zeros(h,w,2)\n for y in range(h):\n for x in range(w):\n grid[y][x][1],grid[y][x][0] = distorted_ordinates(y,x,h,w)\n grid = grid.unsqueeze(0)\n img = torch.from_numpy(img).permute(2,0,1).unsqueeze(0)\n img_d = functional.grid_sample(img,grid,mode='bilinear',padding_mode='zeros')\n img_d = img_d.squeeze().permute(1,2,0).detach().cpu().numpy()\n Image.fromarray(img_d.astype(np.uint8)).save('img_d6.png')\n\n \nif __name__ == '__main__':\n distorting_img(img_path)\n","sub_path":"datasets/radial_len_dis.py","file_name":"radial_len_dis.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"424097753","text":"import tensorflow as tf\nimport numpy as np\nclass P_network:\n \n def __init__(self, state_size, output_size, n_actions, reward_decay = 0.99, sess = None):\n\n self.state_size = state_size\n self.output_size = output_size\n self.n_actions = n_actions\n self.sess = sess or tf.Session()\n\n self.gamma = reward_decay\n self.learning_rate = 0.02\n self.units_number = [10]\n self.layer_number = 1\n self.train_op,self.action_probabilities = None, None\n self.s,self.a,self.r = [],[],[]\n self.input_states, self.input_actions, self.input_action_values = None, None, None\n\n self.build_network()\n self.sess.run(tf.initialize_variables(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)))\n\n def build_network(self):\n\n with tf.name_scope('input'):\n self.input_states = tf.placeholder('float32',[None, self.state_size],'input_state')\n self.input_actions = tf.placeholder('int32',[None, ],'input_actions')\n self.input_action_values = tf.placeholder('float32',[None, ],'input_action_values')\n\n with tf.name_scope('network_body'):\n\n h = [None for i in range(self.layer_number)]\n\n for i in range(self.layer_number):\n input = self.input_states\n if i:\n input = h[i-1]\n h[i] = tf.layers.dense(\n inputs = input,\n units = self.units_number[i],\n activation = tf.nn.tanh,\n kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3, seed = 233),\n bias_initializer = tf.constant_initializer(0.1),\n kernel_regularizer = tf.nn.l2_loss, # 自动加进loss函数吗?\n name = 'h' + str(i)\n )\n \n output = tf.layers.dense(\n inputs = h[-1],\n units = self.output_size,\n activation = None,\n kernel_initializer = tf.random_normal_initializer(mean=0, stddev=0.3, seed = 233),\n bias_initializer = tf.constant_initializer(0.1),\n kernel_regularizer = tf.nn.l2_loss, # 自动加进loss函数吗?\n name = 'output_layer'\n )\n self.action_probabilities = tf.nn.softmax(output, name = 'action_probabilities')\n\n\n with tf.name_scope('loss'):\n loss = tf.reduce_sum( -tf.log(self.action_probabilities) * tf.one_hot(self.input_actions, self.n_actions),axis = 1)\n #loss_function = tf.reduce_sum(-tf.log(self.action_probabilities)*tf.one_hot(self.input_actions, self.n_actions), axis=1)\n loss_function = tf.reduce_mean( self.input_action_values * loss) # wrong here\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n #loss_function += sum(reg_losses) * 0.01\n\n with tf.name_scope('train'):\n \n self.train_op = tf.train.AdamOptimizer(self.learning_rate).minimize(loss_function)\n\n def choose_action(self,present_state):\n\n #prob_weights = self.sess.run(self.all_act_prob, feed_dict={self.tf_obs: state[None, :]})\n action_weights = self.sess.run(self.action_probabilities,feed_dict = {self.input_states : present_state[None, :]}) # different here\n #print('P', action_weights)\n choise = np.random.choice(range(action_weights.shape[1]), p = action_weights.ravel())\n return choise\n\n def store_transition(self,s,a,r):\n self.s.append(s)\n self.a.append(a)\n self.r.append(r)\n\n def clear_episode(self):\n self.s, self.a, self.r = [], [], []\n\n def learn(self):\n k = 20\n gamma2 = self.gamma ** k\n last = 0\n for i in range(len(self.s)-1,0,-1):\n self.r[i] += last * self.gamma\n last = self.r[i]\n# for i in range(len(self.s)):\n# if i + k < len(self.s):\n# self.r[i] -= gamma2 * self.r[i]\n\n self.sess.run(\n self.train_op,feed_dict = {\n self.input_states : self.s, \n self.input_actions : self.a,\n self.input_action_values: self.r})\n\n self.clear_episode()\n\n\n","sub_path":"Policy_network.py","file_name":"Policy_network.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"184129589","text":"'''\nThis module is used for cleaning cache.\n'''\n\nimport os\n\ncwd = os.getcwd()\ncacheList = []\nfor dirpath, dirnames, filenames in os.walk(cwd):\n if '__pycache__' in dirnames:\n cachePath = os.path.join(dirpath, '__pycache__')\n cacheList.append(cachePath)\n\n#cleaning the directory before removing it\nfor directory in cacheList:\n for dirpath, dirnames, filenames in os.walk(directory):\n for filename in filenames:\n fullpath = os.path.join(dirpath, filename)\n os.remove(fullpath)\n print('%s cleaned.' % dirpath[len(cwd):]) #this len() function is used for friendly display\n os.rmdir(dirpath)\n print('%s removed.' % dirpath[len(cwd):])\n\nfrom tkinter.messagebox import showinfo\nshowinfo('Finished!', 'Cleaning complete!')\n","sub_path":"CleanCache.py","file_name":"CleanCache.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"13995907","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\n\ndef conv_init(m):\n \"\"\"Initialize the convolution kernel\n :param m: Conv module\n :type m: nn.Module\n \"\"\"\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n\ndef bn_init(bn, scale):\n \"\"\"Initialize the batch norm kernel\n :param bn: Batchnorm module\n :type bn: nn.Module\n :param scale: The normalize scale\n :type scale: float\n \"\"\"\n nn.init.constant_(bn.weight, scale)\n nn.init.constant_(bn.bias, 0)\n","sub_path":"mda/core/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"151573082","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 23 17:06:24 2019\n\n@author: student\n\"\"\"\n\nimport torch.nn as nn\n\nclass SRCNN(nn.Module):\n def __init__(self,kernel1,kernel2,kernel3):\n super(SRCNN,self).__init__()\n self.conv1 = nn.Conv3d(3,32,kernel_size=kernel1,padding=0)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv3d(32,32,kernel_size=kernel2,padding=0)\n self.relu2 = nn.ReLU()\n self.conv3 = nn.Conv3d(32,3,kernel_size=kernel3,padding=0)\n \n def forward(self,x):\n out = self.conv1(x)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.relu2(out)\n out = self.conv3(out)\n\n return out\n","sub_path":"model_srcnn.py","file_name":"model_srcnn.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"500248552","text":"#! /usr/bin/env python\n# encoding: utf-8\n\nimport glob, os\n\nexcluded = []\ndef build(bld):\n cppFiles = set(\n file.split(\"/\")[-1]\n for file in glob.glob(bld.path.abspath() + \"/*.cpp\")\n ).difference(excluded)\n INCLUDES = [\"../../../\" + x for x in bld.env.INCLUDES_REL] + bld.env.INCLUDES_ABS\n\n bld.stlib(\n source = cppFiles,\n use = [\"utils\", \"containers\", \"database\"],\n target = \"iterators\",\n cxxflags = bld.env.CXXFLAGS,\n includes = INCLUDES,\n lib = bld.env.LDFLAGS_N\n )","sub_path":"source/containers/iterators/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"651679371","text":"from queue import PriorityQueue\r\nimport time\r\n\r\n\r\ndef get_maze(file_path):\r\n \"\"\"\r\n 用给定文件建立迷宫\r\n Args:\r\n file_path: 字符串 代表文件路径\r\n\r\n Returns:\r\n maze: 二维列表 代表迷宫 \r\n '1'墙 '0'通路 'S'起点 'E'终点\r\n \"\"\"\r\n fp = open(file_path)\r\n maze = [line.strip() for line in fp.readlines()]\r\n fp.close()\r\n maze = [list(line) for line in maze]\r\n return maze\r\n\r\n \r\ndef ucs(maze, start, end):\r\n \"\"\"\r\n 给定 迷宫 起点 终点 进行一致代价搜索\r\n Args:\r\n maze: 二维列表 代表迷宫\r\n start: (int, int) 起点坐标\r\n end: (int, int) 终点坐标\r\n Returns:\r\n fathers:字典 键为子节点坐标 值为父节点坐标\r\n 可以从终点回溯路径直到起点\r\n \"\"\"\r\n # 迷宫高和宽\r\n h, w = len(maze), len(maze[0])\r\n fathers = {} \r\n # 访问过的节点\r\n visited = set()\r\n # 优先队列,按照总路径cost自小到大\r\n pqueue = PriorityQueue()\r\n # 插入起始节点\r\n pqueue.put((0, start))\r\n fathers[start] = (-1, -1)\r\n\r\n # 直到队列为空\r\n while pqueue:\r\n # 取出最小的cost和对应节点\r\n cost, node = pqueue.get()\r\n if node not in visited:\r\n visited.add(node)\r\n\r\n # 到达终点则可以返回\r\n if node == end:\r\n return fathers\r\n # 遍历当前节点的邻居节点(即上下左右四个节点)\r\n for dx,dy in [(-1,0),(1,0),(0,-1),(0,+1)]:\r\n next_x, next_y = node[0]+dx, node[1]+dy\r\n # 保证坐标要合法\r\n if next_x < h and next_x >= 0 and next_y < w and next_y >= 0:\r\n # 保证改坐标不是墙或者已经访问过\r\n if maze[next_x][next_y] != '1' and (next_x, next_y) not in visited:\r\n # 将邻居节点的父节点设为当前节点\r\n fathers[(next_x, next_y)] = (node[0], node[1])\r\n # 总路径cost需要加上新的路径cost,此处迷宫全部为1\r\n total_cost = cost + 1\r\n # 将新的总cost和节点加入优先队列\r\n pqueue.put((total_cost, (next_x, next_y)))\r\n\r\ndef display_path(fathers):\r\n \"\"\"\r\n 给定 fathers字典可视化迷宫路径\r\n Args:\r\n fathers:字典 键为子节点坐标 值为父节点坐标\r\n 可以从终点回溯路径直到起点\r\n \"\"\"\r\n fp = open('D:/AI_Lab/lab9/MazeData.txt')\r\n maze = [line.strip() for line in fp.readlines()]\r\n fp.close()\r\n maze = [list(line) for line in maze]\r\n h, w = len(maze), len(maze[0])\r\n\r\n x, y = end[0], end[1]\r\n # 路径节点置为黄色的'O'\r\n while(x > 0):\r\n maze[x][y] = '\\033[1;33mO\\033[0m'\r\n x, y = fathers[(x,y)]\r\n # 将迷宫有墙的地方置为'W', 通路置为' '\r\n for x in range(h):\r\n for y in range(w):\r\n if(maze[x][y] == '0'):\r\n maze[x][y] = ' '\r\n elif(maze[x][y] == '1'):\r\n maze[x][y] = 'W'\r\n\r\n maze = [' '.join(line) for line in maze]\r\n for line in maze:\r\n print(line)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n maze = get_maze('D:/AI_Lab/lab9/MazeData.txt')\r\n start = (1,34)\r\n end = (16,1)\r\n time_start = time.time()\r\n fathers = ucs(maze, start, end)\r\n time_end = time.time()\r\n print('totally cost', time_end - time_start)\r\n\r\n display_path(fathers)\r\n","sub_path":"lab9/code/UCS.py","file_name":"UCS.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"322494812","text":"#005 - Par e Ímpar\n\nPar = []\nImpar = []\nlista = list(range(1,21))\n\nfor i in lista:\n if i % 2 == 0:\n Par.append(i)\n else:\n Impar.append(i)\n\nprint(Impar)\nprint(Par)","sub_path":"Revisões - UFRPE/#4: Listas - Slides/005 - Par e Ímpar.py","file_name":"005 - Par e Ímpar.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"395121487","text":"# coding = utf-8\n\"\"\"\ncreate on : 2017/08/17\nproject name : NLP_100\nfile name : problem_no_13 \n\nThis problem using hightemp.txt\nThis file is available at \"http://www.cl.ecei.tohoku.ac.jp/nlp100/\".\nThis file NOT include this repository.\nIf you need file, please get above web site.\n\nproblem : 12で作ったcol1.txtとcol2.txtを結合し,\n 元のファイルの1列目と2列目をタブ区切りで並べたテキストファイルを作成せよ.\n 確認にはpasteコマンドを用いよ.\n\nmake sure by bash command\n$ paste col1.txt col2.txt\n\"\"\"\n\nfrom problem_no_12 import problem_no_12\n\nHIGHTEMP_TEXT_PATH = \"./hightemp.txt\"\n\n\ndef problem_no_13():\n \"\"\" combine col1.txt and col2.txt\n and separate with tab string between both columns\n\n :return: message string\n \"\"\"\n\n # 12の課題を実行し、col1.txtとcol2.txtを作成\n print(problem_no_12())\n\n with open(\"./col1.txt\", mode=\"r\", encoding=\"utf-8\") as f:\n col1_data = f.readlines()\n\n with open(\"./col2.txt\", mode=\"r\", encoding=\"utf-8\") as f:\n col2_data = f.readlines()\n\n col_data = [col1.replace(\"\\n\", \"\\t\") + col2\n for col1, col2 in zip(col1_data, col2_data)]\n\n with open(\"./col.txt\", mode=\"w\", encoding=\"utf-8\") as f:\n f.writelines(col_data)\n\n return \"combine complete\"\n\n\nif __name__ == \"__main__\":\n print(problem_no_13())\n","sub_path":"codes/chapter_02/problem_no_13.py","file_name":"problem_no_13.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"1456328","text":"from random import choice\nimport string\nimport sqlite3\n\n\nclass Bank:\n\n ISS_ID = 400000\n\n def __init__(self):\n self.con = sqlite3.connect('card.s3db')\n self.create_table()\n self.first_screen()\n\n def create_table(self):\n sql = \"\"\"create table if not exists card (\n id integer,\n number text,\n pin text,\n balance integer default 0)\"\"\"\n self.con.execute(sql)\n self.con.commit()\n\n def generate_new_card_number(self):\n while True:\n acc_number = self.generate_new_number(9)\n first_part = str(self.ISS_ID) + str(acc_number)\n checksum = self.luhn_generate(first_part)\n generated_card = str(first_part) + str(checksum)\n if not self.card_check(generated_card):\n continue\n else:\n return generated_card\n\n @staticmethod\n def generate_new_number(digits):\n chars = string.digits\n random = ''.join(choice(chars) for _ in range(digits))\n return random\n\n @staticmethod\n def luhn_checksum(s):\n digits = list(map(int, s))\n odd_sum = sum(digits[-1::-2])\n even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]])\n return (odd_sum + even_sum) % 10\n\n def luhn_verify(self, s):\n return self.luhn_checksum(s) == 0\n\n def luhn_generate(self, s):\n cksum = self.luhn_checksum(s + '0')\n return (10 - cksum) % 10\n\n def first_screen(self):\n print(\"\")\n print(\"1. Create an account\")\n print(\"2. Log into account\")\n print(\"0. Exit\")\n choice = input()\n\n if choice == \"1\":\n self.card_created()\n elif choice == \"2\":\n self.login()\n elif choice == \"0\":\n print(\"\")\n print(\"Bye!\")\n exit()\n\n def logged_in(self, card, pin):\n print(\"\")\n print(\"1. Balance\")\n print(\"2. Add income\")\n print(\"3. Do transfer\")\n print(\"4. Close account\")\n print(\"5. Log out\")\n print(\"0. Exit\")\n\n choice = str(input())\n\n if choice == \"1\":\n print(\"\")\n print(\"Balance: \", self.get_balance(card))\n self.logged_in(card, pin)\n elif choice == \"2\":\n self.add_income(card, pin)\n elif choice == \"3\":\n self.transfer(card, pin)\n elif choice == \"4\":\n print(\"\")\n self.close_account(card, pin)\n elif choice == \"5\":\n print(\"\")\n print(\"You have successfully logged out!\")\n self.first_screen()\n elif choice == \"0\":\n print(\"\")\n print(\"Bye!\")\n exit()\n\n def card_created(self):\n number, pin = self.create_card()\n print(\"\")\n print(\"Your card has been created\")\n print(\"Your card number:\")\n print(number)\n print(\"Your card PIN:\")\n print(pin)\n self.first_screen()\n\n def add_income(self, card, pin):\n print(\"\")\n print(\"Enter income:\")\n income = int(input())\n sql = \"\"\"\n update card set balance = balance + ? where number = ?\"\"\"\n self.con.execute(sql, (int(income), card))\n self.con.commit()\n print(\"Income was added!\")\n self.logged_in(card, pin)\n\n def transfer(self, card, pin):\n print(\"Transfer\")\n print(\"Enter card number:\")\n to_account = input()\n\n if not self.luhn_verify(to_account):\n print(\"Probably you made a mistake in the card number. Please try again!\")\n self.logged_in(card, pin)\n\n if self.card_check(to_account):\n print(\"Such a card does not exist.\")\n self.logged_in(card, pin)\n\n print(\"Enter how much money you want to transfer:\")\n transfer_amount = int(input())\n\n if transfer_amount > self.get_balance(card):\n print(\"Not enough money!\")\n self.logged_in(card, pin)\n\n sql = \"\"\"\n update card set balance = balance - ? where number = ?\"\"\"\n self.con.execute(sql, (transfer_amount, card))\n sql = \"\"\"\n update card set balance = balance + ? where number = ?\"\"\"\n self.con.execute(sql, (transfer_amount, to_account))\n self.con.commit()\n print(\"Success!\")\n self.logged_in(card, pin)\n\n def close_account(self, card, pin):\n sql = \"\"\"\n delete from card where number = ?\"\"\"\n self.con.execute(sql, (card,))\n self.con.commit()\n print(\"The account has been closed!\")\n self.first_screen()\n\n def login(self):\n print(\"\")\n print(\"Enter your card number:\")\n entered_card = str(input())\n print(\"Enter your PIN:\")\n entered_pin = str(input())\n\n if self.card_pin_check(entered_card, entered_pin):\n print(\"\")\n print(\"You have successfully logged in!\")\n self.logged_in(entered_card, entered_pin)\n\n else:\n print(\"\")\n print(\"Wrong card number or PIN!\")\n self.first_screen()\n\n def create_card(self):\n card_number = str(self.generate_new_card_number())\n pin = str(self.generate_new_number(4))\n sql = \"\"\"\n insert into card (number, pin)\n values (?, ?)\"\"\"\n self.con.execute(sql, (card_number, pin))\n self.con.commit()\n return card_number, pin\n\n def card_check(self, card_number):\n sql = \"\"\"\n select count(*) from card where number = ?\"\"\"\n result = self.con.execute(sql, (card_number,)).fetchone()\n if result is None:\n return True\n else:\n return result[0] == 0\n\n def card_pin_check(self, card, pin):\n sql = \"\"\"\n select 1 from card where pin = ? and number = ?\"\"\"\n result = self.con.execute(sql, (pin, card)).fetchone()\n if result is None:\n return False\n else:\n return result[0] == 1\n\n def get_balance(self, card):\n sql = \"\"\"\n select balance from card where number = ?\"\"\"\n return self.con.execute(sql, (card,)).fetchone()[0]\n\n\nif __name__ == '__main__':\n run = Bank()\n","sub_path":"medium/Simple Banking System/Simple Banking System/task/banking/banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"342682843","text":"import cv2\nimport numpy as np\nimport os\nfrom random import sample\nimport json\n\n\npath = 'data/augmentation/'\noutput_img_dir = 'data/datasets/train/img/'\noutput_anno_dir = 'data/datasets/train/anno/'\n\nnum = 10000\nclasses = 28\nvis = False\nmin_resolution = 30 # min size of a symbol\n\n\ndef get_size(symbol_gray, width, height, a, b):\n\n symbol_shape = symbol_gray.shape\n long_side = max(symbol_shape[0], symbol_shape[1])\n\n upper = min(width//(a+1), height//(b+1))\n lower = min(min_resolution, upper)\n target = np.random.choice(range(lower, upper))\n\n scale = target / long_side\n size_h = int(symbol_shape[0]*scale)\n size_w = int(symbol_shape[1]*scale)\n\n return size_h, size_w\n\n\ndef gen_place(width, height, a, b, n):\n # a places in width\n # b places in height\n\n # init\n labels = []\n\n # img_ori = np.zeros((height, width)) # black background\n img_ori = 255 * np.ones((height, width), dtype=np.uint8) # do not forget dtype=np.uint8 !!!\n # generate n numbers from 0~a*b-1, no repeat after setting replace=False\n choice = np.random.choice(a * b, n, replace=False)\n for i in range(n):\n row = choice[i] // a\n col = choice[i] % a\n center_x = int(width * (col+1) / (a+1))\n center_y = int(height * (row+1) / (b+1))\n\n # rand choice id\n symbol_id = np.random.choice(range(1, classes+1))\n\n # rand choice one img from augmentation data if this symbol_id\n symbol_list = os.listdir(path + str(symbol_id) + '/')\n symbol_name = sample(symbol_list, 1)[0]\n print('symbol_id & symbol_name\\n', symbol_id, symbol_name)\n symbol_img = cv2.imread(path + str(symbol_id) + '/' + symbol_name)\n symbol_gray = cv2.cvtColor(symbol_img, cv2.COLOR_BGR2GRAY)\n\n # get a random size # height & width\n symbol_size = get_size(symbol_gray, width, height, a, b)\n symbol_resized = cv2.resize(symbol_gray, (symbol_size[1], symbol_size[0]))\n\n # replace the original image with a reshaped symbol template\n replace_y = (center_y-symbol_size[0]//2, center_y+symbol_resized.shape[0]-symbol_size[0]//2)\n replace_x = (center_x-symbol_size[1]//2, center_x+symbol_resized.shape[1]-symbol_size[1]//2)\n img_ori[replace_y[0]:replace_y[1], replace_x[0]:replace_x[1]] = symbol_resized\n\n # TODO cjq: all the values are 0 and 255, need some processing ?\n # img = img_ori * np.random.choice(range(6, 10)) / 10 # value rand\n\n # add the bbox for present class(symbol_id)\n labels.append([replace_x[0], replace_y[0], replace_x[1], replace_y[1], int(symbol_id)])\n\n return dict(img=img_ori, labels=labels)\n\n\ndef main():\n for i in range(num):\n img_dict = gen_place(900, 900, 5, 5, 10)\n img = img_dict['img']\n bbox = img_dict['labels']\n height = img.shape[0]\n width = img.shape[1]\n image_info = dict(width=width, height=height)\n anno = dict(image_info=image_info, bbox=bbox)\n\n cv2.imwrite(output_img_dir + str(i) + '.jpg', img)\n with open(output_anno_dir + str(i) + '.json', 'w') as f:\n json.dump(anno, f)\n\n if vis:\n img = img_dict['img']\n for box in anno['bbox']:\n x1, y1, x2, y2, id = box\n cv2.rectangle(img, (x1, y1), (x2, y2), 0, thickness=1)\n cv2.imshow('test', img)\n if cv2.waitKey(0):\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()","sub_path":"legacy/gen_whole_img.py","file_name":"gen_whole_img.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"575720139","text":"def quick_sort(l):\n lenl = len(l)-1\n llist, rlist = [], []\n if len(l) <=1:\n return l\n pivot = l.pop()\n for item in l:\n if item < pivot:\n llist.append(item)\n else:\n rlist.append(item)\n return quick_sort(llist) + [pivot] + quick_sort(rlist)\n\nif __name__ == '__main__':\n import random\n l = [random.randint(1, 20) for _ in range(20)]\n print('before sort', l)\n print(quick_sort(l))\n print('after sort', l)\n\n\n","sub_path":"python_code/python_algorithm/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"281819861","text":"import json\nfrom pprint import pprint\nfrom decouple import config\n\nimport requests\nfrom flask import Flask, request\n\nfrom . import utils\n\napp = Flask(__name__)\n\nBOT_TOKEN = config('BOT_TOKEN')\nSERVER_URL = f'{config(\"NGROK_URL\")}/{BOT_TOKEN}'\n\n\ndef _get_url(method):\n return 'https://api.telegram.org/bot{}/{}'.format(BOT_TOKEN, method)\n\n\ndef _process_message(update):\n data = {}\n data['chat_id'] = update['message']['from']['id']\n\n if update['message']['text'].lower().find('nadaprafazer') == 1:\n command = update['message']['text'].split()\n if len(command) >= 2:\n threads = json.dumps(utils.get_reddits(command[1], 5000), indent=2)\n data['text'] = threads\n else:\n data['text'] = 'Exemplo: /NadaPraFazer cats;dogs'\n else:\n data['text'] = 'Help: /NadaPraFazer [+ Lista de subrredits]'\n\n requests.post(_get_url('sendMessage'), data=data)\n\n\n@app.route('/{}'.format(BOT_TOKEN), methods=['POST'])\ndef _process_update():\n if request.method == 'POST':\n update = request.get_json()\n if 'message' in update:\n _process_message(update)\n return 'ok!', 200\n\n\ndef _configure():\n requests.get(_get_url('setWebhook'), data={'url': SERVER_URL})\n response = requests.get(_get_url('getWebhookInfo'))\n pprint(response.status_code)\n pprint(response.json())\n\n\n_configure()\n","sub_path":"crawlers/reddit/telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"324226479","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 2 14:26:40 2019\n\n@author: Education\n\"\"\"\nimport hashlib #used to import for cryptography\n\n\ntry:\n file = open(\"romeo.txt\",'rt')\n\n for line in file:\n h = hashlib.sha1(line.encode()) #encode function is used to encode a string \n #hashib is used to make a object of hashlib \nexcept Exception as e:\n print(e) \n \nelse: \n print(h.hexdigest()) #hesxdigest function used to get the hash value in hexdecimal value\n #print(h.digest()) #hash value in \\ form\n\nfinally:\n file.close()\n\n\n","sub_path":"SHA1.py","file_name":"SHA1.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"196944211","text":"import sys\nsys.path.append(sys.path[0] + '/../py')\nimport tensorflow as tf\nfrom tensorflow.python.platform import googletest\nfrom fm_ops import fm_ops\n\nclass FmParserOpTest(tf.test.TestCase):\n def testBasic(self):\n with self.test_session():\n labels, ori_ids, feature_ids, feature_vals, feature_poses = fm_ops.fm_parser([\" 1 1234:10 2:1 0:2 \", \"0.8 0:1 2:1 10:20.3\", \"-10\"])\n self.assertAllClose([1, 0.8, -10], labels.eval())\n self.assertAllEqual([1234, 2, 0, 10], ori_ids.eval())\n self.assertAllEqual([0, 1, 2, 2, 1, 3], feature_ids.eval())\n self.assertAllClose([10, 1, 2, 1, 1, 20.3], feature_vals.eval())\n self.assertAllEqual([0, 3, 6, 6], feature_poses.eval())\n\n def testError(self):\n with self.test_session():\n with self.assertRaisesOpError(\"Invalid format for example: 12 123\"):\n fm_ops.fm_parser([\" 12 123\"]).labels.eval()\n with self.assertRaisesOpError(\"Invalid format for example: 12 123:312 0 \"):\n fm_ops.fm_parser([\" 12 123:312 0 \"]).labels.eval()\n \nif __name__ == \"__main__\":\n googletest.main()\n","sub_path":"test/fm_parser_op_test.py","file_name":"fm_parser_op_test.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"450290220","text":"\"\"\"The Nextcloud integration.\"\"\"\nfrom datetime import timedelta\nimport logging\n\nfrom nextcloudmonitor import NextcloudMonitor, NextcloudMonitorError\nimport voluptuous as vol\n\nfrom homeassistant.const import (\n CONF_PASSWORD,\n CONF_SCAN_INTERVAL,\n CONF_URL,\n CONF_USERNAME,\n Platform,\n)\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import config_validation as cv, discovery\nfrom homeassistant.helpers.event import track_time_interval\nfrom homeassistant.helpers.typing import ConfigType\n\n_LOGGER = logging.getLogger(__name__)\n\nDOMAIN = \"nextcloud\"\nPLATFORMS = (Platform.SENSOR, Platform.BINARY_SENSOR)\nSCAN_INTERVAL = timedelta(seconds=60)\n\n# Validate user configuration\nCONFIG_SCHEMA = vol.Schema(\n {\n DOMAIN: vol.Schema(\n {\n vol.Required(CONF_URL): cv.url,\n vol.Required(CONF_USERNAME): cv.string,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,\n }\n )\n },\n extra=vol.ALLOW_EXTRA,\n)\nBINARY_SENSORS = (\n \"nextcloud_system_enable_avatars\",\n \"nextcloud_system_enable_previews\",\n \"nextcloud_system_filelocking.enabled\",\n \"nextcloud_system_debug\",\n)\n\nSENSORS = (\n \"nextcloud_system_version\",\n \"nextcloud_system_theme\",\n \"nextcloud_system_memcache.local\",\n \"nextcloud_system_memcache.distributed\",\n \"nextcloud_system_memcache.locking\",\n \"nextcloud_system_freespace\",\n \"nextcloud_system_cpuload\",\n \"nextcloud_system_mem_total\",\n \"nextcloud_system_mem_free\",\n \"nextcloud_system_swap_total\",\n \"nextcloud_system_swap_free\",\n \"nextcloud_system_apps_num_installed\",\n \"nextcloud_system_apps_num_updates_available\",\n \"nextcloud_system_apps_app_updates_calendar\",\n \"nextcloud_system_apps_app_updates_contacts\",\n \"nextcloud_system_apps_app_updates_tasks\",\n \"nextcloud_system_apps_app_updates_twofactor_totp\",\n \"nextcloud_storage_num_users\",\n \"nextcloud_storage_num_files\",\n \"nextcloud_storage_num_storages\",\n \"nextcloud_storage_num_storages_local\",\n \"nextcloud_storage_num_storages_home\",\n \"nextcloud_storage_num_storages_other\",\n \"nextcloud_shares_num_shares\",\n \"nextcloud_shares_num_shares_user\",\n \"nextcloud_shares_num_shares_groups\",\n \"nextcloud_shares_num_shares_link\",\n \"nextcloud_shares_num_shares_mail\",\n \"nextcloud_shares_num_shares_room\",\n \"nextcloud_shares_num_shares_link_no_password\",\n \"nextcloud_shares_num_fed_shares_sent\",\n \"nextcloud_shares_num_fed_shares_received\",\n \"nextcloud_shares_permissions_3_1\",\n \"nextcloud_server_webserver\",\n \"nextcloud_server_php_version\",\n \"nextcloud_server_php_memory_limit\",\n \"nextcloud_server_php_max_execution_time\",\n \"nextcloud_server_php_upload_max_filesize\",\n \"nextcloud_database_type\",\n \"nextcloud_database_version\",\n \"nextcloud_activeUsers_last5minutes\",\n \"nextcloud_activeUsers_last1hour\",\n \"nextcloud_activeUsers_last24hours\",\n)\n\n\ndef setup(hass: HomeAssistant, config: ConfigType) -> bool:\n \"\"\"Set up the Nextcloud integration.\"\"\"\n # Fetch Nextcloud Monitor api data\n conf = config[DOMAIN]\n\n try:\n ncm = NextcloudMonitor(conf[CONF_URL], conf[CONF_USERNAME], conf[CONF_PASSWORD])\n except NextcloudMonitorError:\n _LOGGER.error(\"Nextcloud setup failed - Check configuration\")\n return False\n\n hass.data[DOMAIN] = get_data_points(ncm.data)\n hass.data[DOMAIN][\"instance\"] = conf[CONF_URL]\n\n def nextcloud_update(event_time):\n \"\"\"Update data from nextcloud api.\"\"\"\n try:\n ncm.update()\n except NextcloudMonitorError:\n _LOGGER.error(\"Nextcloud update failed\")\n return False\n\n hass.data[DOMAIN] = get_data_points(ncm.data)\n hass.data[DOMAIN][\"instance\"] = conf[CONF_URL]\n\n # Update sensors on time interval\n track_time_interval(hass, nextcloud_update, conf[CONF_SCAN_INTERVAL])\n\n for platform in PLATFORMS:\n discovery.load_platform(hass, platform, DOMAIN, {}, config)\n\n return True\n\n\n# Use recursion to create list of sensors & values based on nextcloud api data\ndef get_data_points(api_data, key_path=\"\", leaf=False):\n \"\"\"Use Recursion to discover data-points and values.\n\n Get dictionary of data-points by recursing through dict returned by api until\n the dictionary value does not contain another dictionary and use the\n resulting path of dictionary keys and resulting value as the name/value\n for the data-point.\n\n returns: dictionary of data-point/values\n \"\"\"\n result = {}\n for key, value in api_data.items():\n if isinstance(value, dict):\n if leaf:\n key_path = f\"{key}_\"\n if not leaf:\n key_path += f\"{key}_\"\n leaf = True\n result.update(get_data_points(value, key_path, leaf))\n else:\n result[f\"{DOMAIN}_{key_path}{key}\"] = value\n leaf = False\n return result\n","sub_path":"homeassistant/components/nextcloud/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"710740","text":"# Fallout 76 Perk Viewer\n# Work in progress...\n\nimport bs4\nimport requests\n\n# Get perks page \ndef souper(url):\n res = requests.get(url)\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n return soup\n\n# List SPECIAL stat names\ndef get_stat_names(soup_object):\n stats = []\n stat_names = soup_object.find_all(\"span\", class_=\"mw-headline\")\n del stat_names[0:2]\n for name in stat_names:\n stats.append(name.text)\n return stats\n\n# List the perk names\ndef get_perk_names(soup_object):\n perks = []\n perk_table = soup_object(\"table\")[5:12]\n for table in perk_table:\n perk_names = table.find_all(\"a\")\n for name in perk_names:\n perks.append(name.text)\n return perks\n\n# List perk names by correspoding SPECIAL stat\ndef perks_by_stat(soup_object):\n stat_names = soup_object.find_all(\"span\", class_=\"mw-headline\")\n del stat_names[0:2]\n perk_table = soup_object(\"table\")[5:12]\n perk_dict = {}\n for stat,table in zip(stat_names,perk_table):\n perk_dict[stat.text] = {}\n perk_names = table.find_all(\"a\")\n for name in perk_names:\n perk_dict[stat.text][name.text] = {}\n return perk_dict\n\nsoup = souper('https://fallout.gamepedia.com/Fallout_76_perks')\n\nall_perks = perks_by_stat(soup)\n\nprint(str(all_perks))\n\n# TO-DO\n# \n# Output individual perk descriptions & ranks\n","sub_path":"perkboy.py","file_name":"perkboy.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"421896846","text":"import pandas\nimport numpy as np\nfrom tqdm import tqdm\n\n#define column names\ncolnames = ['ID', 'Case Number', 'Date', 'Block', 'IUCR','PrimaryType','Description','Location Description','Arrest','Domestic','Beat','District','Ward','Community','FBI Code','XCoordinate','YCoordinate','Year','Updated On','Latitude','Longitude','Location']\ndata = pandas.read_csv('crimes2016.csv', names=colnames) #extract data\n\n#extract useful columns to lists\nX = data.XCoordinate.tolist()\nY = data.YCoordinate.tolist()\nLat = data.Latitude.tolist()\nLong = data.Longitude.tolist()\nP = data.PrimaryType.tolist()\n\n#convert to numpy array for ease of use\nX = np.array(X)\nY = np.array(Y)\nLat = np.array(Lat)\nLong = np.array(Long)\nP = np.array(P)\n\n#get rid of first column containing string of column name\nX = np.delete(X,0)\nY = np.delete(Y,0)\nLat = np.delete(Lat,0)\nLong = np.delete(Long,0)\nP = np.delete(P,0)\n\n#get rid of any incomplete 'nan' entries from the data (using indexing for speed instead of deleting)\ndataLen = len(X)\nfor i in tqdm(range(len(X))):\n\tif X[i] == 'nan': #n.b. no entry in X iff no entry in Y (true for our data)\n\t\tdataLen -= 1\n\nXclean = np.zeros(dataLen) #define arrays\nYclean = np.zeros(dataLen)\nLatclean = np.zeros(dataLen)\nLongclean = np.zeros(dataLen)\nPclean = [0] * dataLen\nind = 0 \nfor i in tqdm(range(len(X))):\n\tif X[i] != 'nan':\n\t\tXclean[ind] = X[i]\n\t\tYclean[ind] = Y[i]\n\t\tLatclean[ind] = Lat[i]\n\t\tLongclean[ind] = Long[i]\n\t\tPclean[ind] = P[i]\n\t\tind += 1\n\n\n#save arrays\ndataCoord = np.array([Xclean,Yclean])\ndataLL = np.array([Latclean,Longclean])\n\nnp.save('dataCoord.npy',dataCoord)\nnp.save('dataLL.npy',dataLL)\nnp.save('severity.npy',Pclean)\n\n\n# import scipy.io\n\n# scipy.io.savemat('data.mat', dict(X=Xclean, Y=Yclean))\n\n","sub_path":"data_read.py","file_name":"data_read.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"155693869","text":"from google.cloud import vision\nfrom google.cloud.vision import types\n\n\ndef query_web_detection(img_url, max_results=20):\n client = vision.ImageAnnotatorClient()\n d = {\n 'image': {\n 'source': {\n 'image_uri': img_url\n }\n },\n 'features': [{\n 'type': 'WEB_DETECTION',\n 'max_results': max_results\n }]\n }\n response = client.annotate_image(d).web_detection\n return response\n\n\ndef unpack_json(j):\n j = j['webDetection']\n for p in j['pagesWithMatchingImages']:\n print(p['url'])\n print('\\n\\n')\n\n for p in j['partialMatchingImages']:\n print(p['url'])\n\n\ndef _test():\n \"\"\"\n Change the url below, get all full_matching_images and pages_with_matching_images in the console\n :return:\n \"\"\"\n r = query_web_detection(\"https://images-cn.ssl-images-amazon.com/images/I/61rxMvX9BKL._SY679_.jpg\", 5000)\n for url in r.partial_matching_images:\n print(url.url)\n print('\\n')\n for url in r.pages_with_matching_images:\n print(url.url)\n\n\nif __name__ == '__main__':\n _test()","sub_path":"haystack/app/analyzer/MagicHayStack/google_vision.py","file_name":"google_vision.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"505881541","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 27 10:58:28 2019\n\n@author: jsten\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\n\n\nmuL=mu\ntuaL=tua\nDeltaL=Delta\nVmaxL=Vmax\nLL=L\nNtL=Nt\nNwL=Nw\ndtL=dt\nBDL=BD\n\ndirectory=\"C:\\\\Users\\\\jsten\\\\Documents\\\\Reaserch\\\\Interaction Error\\\\TEBD_clean\\\\data_std\\\\\"\ndirectoryF=\"C:\\\\Users\\\\jsten\\\\Documents\\\\Reaserch\\\\Interaction Error\\\\TEBD_clean\\\\figures_std\\\\\"\n\nfile=\"_m\"+str(muL)+\"_J\"+str(tuaL)+\"_D\"+str(DeltaL)+\"_V\"+str(VmaxL)+\"_L\"+str(LL)+\"_tr\"+str(NtL)+\"_tw\"+str(NwL)+\"_dt\"+str(dtL)+\"_BD\"+str('F')+\"_N\"+str(n2-n1)\n\nwith open(directory+file+\"_phA\"+\".txt\",\"rb\") as f:\n phAL=pickle.load(f)\nwith open(directory+file+\"_phB\"+\".txt\",\"rb\") as f:\n phBL=pickle.load(f)\nwith open(directory+file+\"_lapA\"+\".txt\",\"rb\") as f:\n lapAL=pickle.load(f)\nwith open(directory+file+\"_lapB\"+\".txt\",\"rb\") as f:\n lapBL=pickle.load(f)\nwith open(directory+file+\"_parP\"+\".txt\",\"rb\") as f:\n parPL=pickle.load(f)\nwith open(directory+file+\"_parM\"+\".txt\",\"rb\") as f:\n parML=pickle.load(f)\nwith open(directory+file+\"_wlist\"+\".txt\",\"rb\") as f:\n wlistL=pickle.load(f)\nwith open(directory+file+\"_TparP\"+\".txt\",\"rb\") as f:\n TparPL=pickle.load(f)\nwith open(directory+file+\"_TparM\"+\".txt\",\"rb\") as f:\n TparML=pickle.load(f)\nwith open(directory+file+\"_EendP\"+\".txt\",\"rb\") as f:\n EendPL=pickle.load(f)\nwith open(directory+file+\"_EendM\"+\".txt\",\"rb\") as f:\n EendML=pickle.load(f)\nwith open(directory+file+\"_EmidP\"+\".txt\",\"rb\") as f:\n EmidPL=pickle.load(f)\nwith open(directory+file+\"_EmidM\"+\".txt\",\"rb\") as f:\n EmidML=pickle.load(f)\n\n\n\nplt.figure(\"Phase Error\")\n#plt.xlim(-0.01,0.1)\n#plt.ylim(-0.00,0.002)\nplt.scatter(wlistL,phAL,s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Phase Error\")\nplt.savefig(directoryF+file+\"_phA\"+\".svg\")\nplt.show()\n\nplt.figure(\"Parity Error\")\n#plt.xlim(-0.01,0.2)\n#plt.ylim(-0.00,0.002)\nplt.scatter(wlistL,parPL,s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Parity Error\")\nplt.savefig(directoryF+file+\"_parP\"+\".svg\")\nplt.show()\n\nplt.figure(\"Lap Error\")\n#plt.xlim(-0.01,0.2)\n#plt.ylim(-0.00,0.002)\nplt.scatter(wlistL,lapAL,s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Lap Error\")\nplt.savefig(directoryF+file+\"_lapA\"+\".svg\")\nplt.show()\n\n\nplt.figure(\"Total Parity\")\n#plt.xlim(-0.01,0.2)\n#plt.ylim(-0.01,0.05)\nplt.scatter(wlistL,TparPL,s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Total Parity\")\nplt.savefig(directoryF+file+\"_TparP\"+\".svg\")\nplt.show()\n\nplt.figure(\"Energy\")\n#plt.xlim(-0.01,0.2)\n#plt.ylim(-0.01,0.05)\nplt.scatter(wlistL,np.array(EendPL)-np.array(EendML),s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Energy\")\nplt.savefig(directoryF+file+\"_Eend\"+\".svg\")\nplt.show()\n\nplt.figure(\"Mid Energy\")\n#plt.xlim(-0.01,0.2)\n#plt.ylim(-0.01,0.05)\nplt.scatter(wlistL,np.array(EmidPL)-np.array(EmidML),s=50)\nplt.xlabel(\"Ramp Time\")\nplt.ylabel(\"Energy\")\nplt.savefig(directoryF+file+\"_Emid\"+\".svg\")\nplt.show()\n\n","sub_path":"plotting_std/plotting_BD.py","file_name":"plotting_BD.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"333784563","text":"#!/usr/bin/env python3\n# encoding: utf-8\n# Import Statements:\nfrom iOSReader import reader\nimport datetime\nimport matplotlib.pyplot as plt\nfrom clint.textui import progress\n\nr = reader()\n\n# Constants:\nprefix = \"Sechler\"\nnumlines = 10\nword = \"love\"\n\n# Initialize the reader.\nr.addAddressBook(\"People/\" + prefix + \"/AddressBook/AddressBook.sqlitedb\")\nr.addSMSDatabase(\"People/\" + prefix + \"/SMS/sms.db\")\nnumberlist = sorted(r.getListOfNumbers(), key=lambda item: r.countFromNumber(item), reverse=True)[:numlines]\n\nfor i in numberlist:\n print(r.getNameFromNumber(i) + \": \" + str(r.instancesOf(word, i)))\n print(r.getNameFromNumber(i) + \": \" + str(r.instancesOf(word, i)/r.countFromNumber(i)))\n","sub_path":"wordsearch.py","file_name":"wordsearch.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"124461182","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\nb=2\nimport sys\nsys.setrecursionlimit(1000000)\nimport numpy as np\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom graphviz import Graph\n\n\nclass Node(object):\t#class of node\n\tdef __init__(self, key):\n\t\tself.key = key\t#value\n\t\tself.left = None\t#left children node\n\t\tself.right = None\t#right children node\n\t\tself.height = 0\t#hegiht\n\n\nclass AVLtree(object):\t# class of AVL tree\n\tdef __init__(self):\t# root point\n\t\tself.root = None\n\n\tdef find(self, key):\t# search node\n\t\tnode = self.root\n\t\twhile(key != node.key and node != None):\t#iterate to find \n\t\t\tif key < node.key:\n\t\t\t\tnode = node.left\n\t\t\telif key > node.key:\n\t\t\t\tnode = node.right\n\t\tif key == node.key:\t# founded return \n\t\t\treturn node\n\t\telse:\t#not found\n\t\t\treturn \"not found\"\n\n\tdef findroot(self):\n\t\treturn self.root\t#return root\n\n\tdef insert(self, key, node):\t#insert node\n \n \n \n\t\tif node == None:\t#initialize root node\n\t\t\tnode = Node(key)\n\t\t\tnode.height = 1\n\t\t\treturn node\n\t\t\t\n\t\telse:\n\t\t\tif key > node.key:\n\t\t\t\tnode.right = self.insert(key, node.right)\n\n\t\t\telse:\n\t\t\t\tnode.left = self.insert(key, node.left)\n\t\t\t#print(f\"left height is {self.height(node.left)}, right height is {self.height(node.right)}\")\n\t\t\tnode.height = max(self.height(node.left), self.height(node.right)) + 1\n\n\t\t\tif abs(self.height(node.left) - self.height(node.right)) >= 2:\n\t\t\t\tnode = self.rotate(node)\n\n\t\t\treturn node\n\n\tdef rotate(self, node):\t#rotate to become balance\n\t\tif node == None:\n\t\t\treturn\n\n\t\tif self.height(node.left) - self.height(node.right) >= 2:\t#left children and right children are in unbalance, left children has bigger height\n\t\t\tif self.chheight(node.left, 0) - self.chheight(node.left, 1) >= 0:\t#\tleft left children is higher than right left childern\n\t\t\t\tnode = self.rightrotate(node)\t#in situation, we do left rotation\n\t\t\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#reset the height\n\t\t\t\treturn node\n\t\t\tif self.chheight(node.left, 0) - self.chheight(node.left, 1) < 0:\t#\tleft left children is smaller than right left childern\n\t\t\t\tnode = self.LRrotate(node)\t\t#in situation, we do right left rotation\n\t\t\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#reset the height\n\t\t\t\treturn node\n\n\t\telif self.height(node.left) - self.height(node.right) <= -2:\t##left children and right children are in unbalance, right children has bigger height\n\t\t\tif self.chheight(node.right, 0) - self.chheight(node.right, 1) <= 0:\t#\tleft right children is smaller than right right childern\n\t\t\t\tnode = self.leftrotate(node)\t#right rotation\n\t\t\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#reset the height\n\t\t\t\treturn node\n\t\t\tif self.chheight(node.right, 0) - self.chheight(node.right, 1) > 0:\t#\tleft right children is higher than right right childern\n\t\t\t\tnode = self.RLrotate(node)\t#left right rotation\n\t\t\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#reset the height\n\t\t\t\treturn node\n\t\t\n\t\t#node.right = self.rotate(node.right)\t#iterate to next node\n\t\t#node.left = self.rotate(node.left)\t#iterate to next node\n\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#reset the height\n\n\t\treturn node\n\t\t#node.height = max(self.height(node.right), self.height(node.left)) + 1\n\n\tdef height(self, node):\n\t\tif node == None:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn node.height #height\n\n\tdef chheight(self, node, ctype):\t#return the height of children's children\n\t\tif(node == None):\n\t\t\treturn 0\n\t\telse:\n\t\t\tif ctype == 0:\n\t\t\t\treturn self.height(node.left)\n\t\t\telse:\n\t\t\t\treturn self.height(node.right)\n\n\tdef present(self):\t#exhibition\n\t\tnode = []\n\t\tedge = []\n\t\tnumber = []\n\t\tdot = Graph(name = 'graph drawing', comment = 'Graph Drawing')\n\t\n\t\tbufferlist = []\n\t\tparent = []\n\t\tcurrnode = self.root\n\t\tbufferlist.append(currnode)\n\t\tparent.append(None)\n\t\twhile len(bufferlist) != 0:\n\t\t\tcurrnode = bufferlist.pop(0)\n\t\t\tcurr_parent = parent.pop(0)\n\t\t\tprint(f\"{currnode.key}, the height is {currnode.height}, the parent is {curr_parent}\")\n\t\t\tnode.append(currnode.key)\n\t\t\tif(curr_parent != None):\n\t\t\t\tedge.append((curr_parent, currnode.key))\n\t\t\tif currnode.left != None:\n\t\t\t\tbufferlist.append(currnode.left)\n\t\t\t\tparent.append(currnode.key)\n\n\t\t\tif currnode.right != None:\n\t\t\t\tbufferlist.append(currnode.right)\n\t\t\t\tparent.append(currnode.key)\n\n\t\tfor i in range(len(node)):\n\t\t\tdot.node(str(node[i]), str(node[i]))\n\n\t\tfor i in edge:\n\t\t\tdot.edge(str(i[0]), str(i[1]))\n\n\t\tdot.render('output-graph.gv', view=True)\n\t\n\n\tdef rightrotate(self, node):\t\t#left rotation\n\t\ttempnode = node.left \n\t\tnode.left = tempnode.right #change the right children of new father to be the left children of old father\n\t\ttempnode.right = node #change the relation of father and son\n\t\tnode.height = max(self.height(node.right), self.height(node.left)) + 1\t#change height\n\t\ttempnode.height = max(self.height(tempnode), self.height(node)) + 1\n\t\t#if node == self.root:\n\t\t#\tself.root = tempnode\n\t\treturn tempnode\n\n\n\tdef leftrotate(self, node):\n\t\ttempnode = node.right\n\t\tnode.right = tempnode.left #change the left children of new father to be the right children of old father\n\t\ttempnode.left = node##hange the relation of father and son\n\t\tnode.height = max(self.height(node.right), self.height(node.left))+1 #change height\n\t\ttempnode.height = max(self.height(tempnode.left), self.height(node))+1\n\t\t#if node == self.root:\n\t\t#\tself.root = tempnode\n\n\t\treturn tempnode\n\n\tdef LRrotate(self,node):\n\t\tnode.left = self.leftrotate(node.left)# do left rotation\n\t\treturn self.rightrotate(node)\t#then do right rotation\n\t\t\t\t\n\tdef RLrotate(self, node):\n\t\tnode.right = self.rightrotate(node.right)\t#do right rotation\n\t\treturn self.leftrotate(node)\t#then do left rotation\n\t'''\n\tdef setheight(self, node):\t#calculate the height of each node\n\t\tcurrnode = node\n\t\tif currnode == None:\n\t\t\treturn 0\n\n\t\tcurrnode.height = max(self.setheight(currnode.left), self.setheight(currnode.right)) + 1\n\t\treturn currnode.height\n\t'''\n\tdef findmin(self, node, node_p, type):\t#find the minimum number is the right subtree\n\t\tcurrnode = node\n\t\tif currnode.left != None:\n\t\t\tvalue = self.findmin(currnode.left, currnode, 0)\t\n\t\t\treturn value\n\t\tvalue = currnode.key\n\t\tif type == 1:\n\t\t\tnode_p.right = currnode.right\n\t\t\tnode_p.height = max(self.height(node_p.left), self.height(node_p.right)) + 1\n\t\telse:\n\t\t\tnode_p.left = currnode.right\n\t\t\tnode_p.height = max(self.height(node_p.left), self.height(node_p.right)) + 1\n\t\treturn value\n\n\tdef findmax(self, node, node_p, type):\t#find the max number in the left subtree\n\t\tcurrnode = node\n\t\tif currnode.right != None:\n\t\t\tvalue = self.findmax(currnode.right, currnode, 1)\n\t\t\treturn value\n\t\tvalue = currnode.key\n\t\tif type == 1:\n\t\t\tnode_p.right = currnode.left\n\t\t\tnode_p.height = max(self.height(node_p.left), self.height(node_p.right)) + 1\n\t\telse:\n\t\t\tnode_p.left = currnode.left\n\t\t\tnode_p.height = max(self.height(node_p.left), self.height(node_p.right)) + 1\n\t\treturn value\n\n\tdef delete_(self,key):\t# delete certain number\n\t\tif(key == self.root.key):\t# when the number is the root\n\t\t\tdata = self.findmax(self.root.left, self.root, 0)\n\t\t\tself.root.key = data\n\t\t\tif abs(self.height(self.root.left) - self.height(self.root.right)) >= 2:\n\t\t\t\tself.root = self.rotate(self.root)\n\t\t\tself.root.height = max(self.height(self.root.left), self.height(self.root.right)) + 1\n\t\t\treturn self.root\n\n\t\telse:\t# otherwise iteration on the subtree\n\t\t\tif self.root.right != None and key > self.root.key:\n\t\t\t\tself.root.right = self.delete(self.root.right, key, self.root, 1)\n\t\t\t\tif abs(self.height(self.root.left) - self.height(self.root.right)) >= 2:\t#check balance\n\t\t\t\t\tself.root = self.rotate(self.root)\n\t\t\t\tself.root.height = max(self.height(self.root.left), self.height(self.root.right)) + 1\n\n\t\t\tif self.root.left != None and key < self.root.key:\n\t\t\t\tself.root.left = self.delete(self.root.left, key, self.root, 0)\n\t\t\t\tif abs(self.height(self.root.left) - self.height(self.root.right)) >= 2:\n\t\t\t\t\tself.root = self.rotate(self.root)\n\t\t\t\tself.root.height = max(self.height(self.root.left), self.height(self.root.right)) + 1\n\t\t\treturn self.root\n\n\tdef delete(self, node, key, node_p, type):\t# when the numbe is on the subtree\n\t\tif node.key == key:\t#when the number is a leaf\n\t\t\tif node.right == None and node.left == None:\n\t\t\t\treturn None\n\t\t\telif node.right == None:\t#when the number have only one children\n\t\t\t\treturn node.left\n\t\t\telif node.left == None:\n\t\t\t\treturn node.right\n\t\t\telse:\n\t\t\t\tdata = self.findmax(node.left, node, 0)\t#when the number have 2 children\n\t\t\t\tnode.key = data\n\n\t\t\t\treturn node\n\n\t\telif node.key < key:\t#iteration to find the number\n\t\t\tif node.right != None:\n\t\t\t\tnode.right = self.delete(node.right, key, node, 1)\n\t\t\t\t\n\t\t\t\tif abs(self.height(node.left) - self.height(node.right)) >= 2:\n\t\t\t\t\tnode = self.rotate(node)\n\t\t\t\t\t\n\t\t\t\tnode.height = max(self.height(node.left), self.height(node.right)) + 1\n\t\t\t\treturn node\n\t\t\telse:\n\t\t\t\tprint(\"Not exist\")\n\t\t\t\t\n\t\t\treturn node\n\n\t\telif node.key > key:\n\t\t\tif node.left != None:\n\t\t\t\t\n\t\t\t\tnode.left = self.delete(node.left, key, node, 0)\n\t\t\t\t#node.height = max(self.height(node.left), self.height(node.right)) + 1\n\t\t\t\tif abs(self.height(node.left) - self.height(node.right)) >= 2:\n\t\t\t\t\tnode = self.rotate(node)\n\t\t\t\t\t\n\t\t\t\tnode.height = max(self.height(node.left), self.height(node.right)) + 1\n\t\t\t\treturn node\n\t\t\telse:\n\t\t\t\tprint(\"Not exist\")\n\t\t\t\t\n\t\t\treturn node\n\n\tdef balance_check(self, node):\t# check balance\n\t\tif abs(self.height(node.left) - self.height(node.right)) <= 1:\n\t\t\tif node.left != None:\n\t\t\t\tself.balance_check(node.left)\n\t\t\tif node.right != None:\n\t\t\t\tself.balance_check(node.right)\n\n\t\t\treturn 'success'\n\t\telse:\n\t\t\treturn 'fail'\n\n\n\nclass BST(object):\n\tdef __init__(self):\n\t\tself.root = None\n\n\tdef insert(self, key):\n\t\tif(self.root == None):\n\t\t\tself.root = Node(key)\n\t\t\tself.root.height = 1\n\t\telse:\n\t\t\tnode = self.root\n\t\t\twhile ((node.right != None and key > (node.key)) or (key < (node.key) and node.left != None)):\n\t\t\t\tif key < node.key:\n\t\t\t\t\tnode = node.left\n\t\t\t\telif key > node.key:\n\t\t\t\t\tnode = node.right\n\n\t\t\tif key < node.key:\n\t\t\t\tnode.left = Node(key)\n\t\t\telif key > node.key:\n\t\t\t\tnode.right = Node(key)\n\t\treturn\n\n\tdef present(self):\n\t\tbufferlist = []\n\t\tcurrnode = self.root\n\t\tbufferlist.append(currnode)\n\t\t\n\t\twhile len(bufferlist) != 0:\n\t\t\tcurrnode = bufferlist.pop(0)\n\t\t\t\n\t\t\tprint(f\"{currnode.key}, the height is {currnode.height}\")\n\n\t\t\tif currnode.left != None:\n\t\t\t\tbufferlist.append(currnode.left)\n\t\t\t\t\n\t\t\tif currnode.right != None:\n\t\t\t\tbufferlist.append(currnode.right)\n\n\t\treturn\n\n\tdef setheight(self, node):\n\t\tcurrnode = node\n\t\tif currnode == None:\n\t\t\treturn 0\n\t\tcurrnode.height = max(self.setheight(currnode.left), self.setheight(currnode.right)) + 1\n\t\treturn currnode.height\n\n\tdef findroot(self):\n\t\treturn self.root\n\n\tdef find(self, key):\t# search node\n\t\tnode = self.root\n\t\twhile(key != node.key and node != None):\n\t\t\tif key < node.key:\n\t\t\t\tnode = node.left\n\t\t\telif key > node.key:\n\t\t\t\tnode = node.right\n\t\tif key == node.key:\n\t\t\treturn node\n\t\telse:\n\t\t\treturn \"not found\"\n\ntree = AVLtree()\ngroup = [21, 25, 15, 27, 80, 14, 35, 46, 67, 13, 70, 49, 37, 22, 90, 48, 33, 99, 100]\n#group = [54, 45, 63, 36, 51, 61, 18, 39, 47, 52]\nfor i in group:\n\ttree.root = tree.insert(i, tree.root)\n#tree.root = tree.delete_(63)\ntree.present()\ntree.root = tree.delete_(18)\ntree.present()\nprint(tree.balance_check(tree.root))\n'''\ncount = 0\nfor i in range(2000):\t# test \n\ttree = AVLtree()\n\tgroup = random.sample(range(1, 30), 5)\n\tfor i in group:\n\t\ttree.root = tree.insert(i, tree.root)\n\n\tk = np.random.randint(0,5)\n\ttree.delete_(group[k])\n\tif tree.balance_check(tree.root) == 'fail':\n\t\ttree.present()\n\t\tprint(f\"\\n delet {group[k]}\\n\")\n\t\tprint(group)\n\t\tcount += 1\n\n\telse:\n\t\tprint(\"success\")\n\nprint(count)\n'''\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"avl.py","file_name":"avl.py","file_ext":"py","file_size_in_byte":11728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"64582923","text":"\"\"\"\nThis module handles the user interactions in the maze program.\n\nThe module expects the modules 'fileIO' and 'solver' (from own package)\nIt implements several functions to display information and get information\nfrom the terminal. Most output is normed to a width of 80 characters.\n\"\"\"\nimport os\n\nfrom . import fileIO\nfrom .solver import GOAL, START, WALL # the . in front implies a local import\n\n\n# constants matching the options of solving a maze, creating a maze or\n# quitting the program to a number\nSOLVE_A_MAZE = 0\nCREATE_A_MAZE = 1\nQUIT = 2\n\n\ndef show_welcome():\n \"\"\"Displays an instructing welcome message to the user.\"\"\"\n # define functions that formats a line of the help text to be put between\n # two pipes and have a length of 78 characters, for a total width of 80\n help_line = lambda line: f\"*{line:^78}*\"\n\n # text to present to the user\n help_text = (\n \"This somewhat interactive program will let you choose a maze\" + \"\\n\"\n \"of your liking. Our little solver will then do its best to\" + \"\\n\"\n \"find a way through the maze. In the end it will show you the\" + \"\\n\"\n \"result of the search and you can choose to save the solved\" + \"\\n\"\n \"version to show all your friends how amazing your maze solving\" + \"\\n\"\n \"skills are! ;)\" + \"\\n\"\n \"You also have the possibility to design your own maze that our\" + \"\\n\"\n \"solver will then attempt to solve for you.\" + \"\\n\"\n \"Have fun!\"\n )\n # get text as a list and normalize line lengths\n help_text = help_text.splitlines()\n line_length = max(len(line) for line in help_text)\n help_text = [f\"{line:<{line_length}}\" for line in help_text]\n\n # print first line\n print(f\"\\n{'Maze Solver':*^80}\")\n # use help_line() to format all lines in the text, then print\n for line in help_text:\n print(help_line(line))\n # print last line\n print(f\"{'':*^80}\")\n\ndef menu():\n \"\"\"\n Displays the main menu and instructions to the user, then lets them choose\n an option.\n\n Returns:\n get_user_choice(\"Please choose a menu option.\", 3): Option chosen by\n the user\n \"\"\"\n\n # define functions that formats a line of the menu text to be put between\n # two pipes and have a length of 78 characters\n menu_line = lambda line: f\"|{line:^78}|\"\n\n # text to present to the user\n menu_text = (\n \"\" + \"\\n\"\n \"You have the following options to choose from: \" + \"\\n\"\n \"\" + \"\\n\"\n \"0) Choose an existing maze to be solved\" + \"\\n\"\n \"1) Create your own maze\" + \"\\n\"\n \"2) Exit\" + \"\\n\"\n \"\"\n )\n # get text as a list and normalize line lengths\n menu_text = menu_text.splitlines()\n line_length = max(len(line) for line in menu_text)\n menu_text = [f\"{line:<{line_length}}\" for line in menu_text]\n\n # print first line\n print(f\"\\n{'Main Menu':~^80}\")\n # use menu_line() to format all lines in the text, then print\n for line in menu_text:\n print(menu_line(line))\n # print last line\n print(f\"{'':~^80}\\n\")\n\n # let user choose a menu option and return the choice\n return get_user_choice(\"Please choose a menu option.\", 3)\n\n\n\ndef present_mazes(maze_list, print_mazes=False):\n \"\"\"\n Shows the available maze IDs and maze names to the user. Is able to show the\n corresponding mazes as well.\n\n Args:\n maze_list: list of all available mazes\n print_maze: boolean indicating if the mazes should be shown as well.\n defaults to False.\n \"\"\"\n print(\"The following mazes are available:\")\n\n # go through all mazes in the list and assign an index to each of them\n for i, maze in enumerate(maze_list):\n\n # show maze name and ID\n maze_name = os.path.splitext(maze)[0]\n print(f\"ID {i:<4} {maze_name}\")\n\n # show the corresponding mazes as well if this option was chosen\n if print_mazes:\n show_maze(fileIO.get_maze(maze))\n\n print()\n\n\ndef get_user_choice(msg, length):\n \"\"\"\n Makes user choose an existing index in a given range from 0 to length - 1.\n\n Args:\n msg: Message to be shown to user when asked for input of an index\n length: length of indices, so valid indices are between 0 and length - 1\n\n Returns:\n idx: chosen index\n \"\"\"\n\n idx = -1\n\n # let user enter an ID as long as the ID is not valid\n while idx == -1:\n\n # get maze index by user input\n try:\n val = input(msg + \"\\n\")\n idx = int(val)\n\n # raise an error if maze index cannot be matched to a maze\n if not (0 <= idx < length):\n raise ValueError(\"Index out of range.\")\n\n # show available maze indices to user if index was invalid\n except ValueError:\n idx = -1\n print(f\"Valid inputs are: {', '.join(range(length))}\")\n\n # return index of chosen maze\n return idx\n\ndef choose_maze():\n \"\"\"\n Lets the user choose a maze to solve out of a list of mazes.\n\n Return:\n maze_list[idx]: maze with ID 'idx' chosen by the user\n \"\"\"\n # let user choose whether to display only the maze names or the complete\n # mazes and save this choice in 'full' as True/False\n choice = input(\n \"Would you like to see the mazes in full \"\n \"or only the names of the mazes? (f[ull]/n[ames])\\n\"\n ).lower()\n full = choice in ['f', 'full']\n\n # get all mazes\n maze_list = fileIO.get_maze_list()\n # show all the maze IDs and, if user chose to, corresponding mazes\n present_mazes(maze_list, full)\n\n # let user choose a maze id and check input\n msg = \"Please enter the id of the maze you want to use.\"\n idx = get_user_choice(msg, len(maze_list))\n\n # show only chosen maze to user if they did not decide to show all the mazes\n if not full:\n show_maze(fileIO.get_maze(maze_list[idx]))\n print()\n\n # return the maze chosen by the user\n return maze_list[idx]\n\ndef show_maze(grid):\n \"\"\"\n Prints a maze line by line.\n\n Args:\n grid: the maze\n \"\"\"\n # go through each line of the maze\n for line in grid:\n # add a space between characters for readability and print\n print(\" \".join(line))\n\n\ndef user_save(solved, grid):\n \"\"\"\n Make user choose if they want to save the solved maze and returns choice.\n\n Args:\n solved: boolean indicating whether maze was solved or not\n grid: the maze\n\n Returns:\n True if user decides to save the maze by typing 'y'\n False if user decides to not save the maze by not typing 'y' or if the\n maze was not solved\n \"\"\"\n # no way was found through the maze so there is no solved maze to save\n if not solved:\n print(\"Oh no, that's embarrassing. We found no way through the maze.\")\n return False\n\n # if maze was solved\n else:\n # show solved maze to the user\n show_maze(grid)\n print(\"Wooho! There is the way!\")\n\n # ask if user wants to save maze and return choice (True/False)\n print(\"Do you want to save the maze solution? (y/n)\")\n return (input().lower() == 'y')\n\n\ndef create_maze():\n \"\"\"\n Lets the user enter a new maze row by row and returns it and its name.\n\n Returns:\n maze_name: name of the new maze\n maze: new maze as string\n \"\"\"\n\n # show instructions to user\n print(\n \"Welcome to CREATE-A-MAZE!\\n\"\n \"Enter your maze row by row. Make sure that all rows \"\n \"have the same length. Each maze needs to have a start \"\n f\"position ({START}) and a goal position ({GOAL}). Use \"\n f\"{WALL} for the walls of the maze. They are impassable \"\n \"for the solver. It is suggested to surround the maze \"\n \"with walls for better readability.\\n\"\n \"Just press enter (on an empty line) to end input.\\n\"\n \"Please enter your maze now:\"\n )\n # create empty maze\n maze = \"\"\n\n # get a new row, get its length and add to the maze\n row = input()\n row_length = len(row)\n maze += row\n\n # if row is not empty (user is not finished yet)\n while row != '':\n\n # get a new row\n row = input()\n\n # break loop if new row is empty (user is finished)\n if row == '':\n break\n\n # all rows of the maze need to have the same length\n if len(row) != row_length:\n\n # print message and current maze to remind user to put in rows of\n # fitting length\n print(f\"Sorry, this row length {len(row)} had the wrong length. Should be {row_length}.\")\n print(\"Maze so far:\")\n show_maze(fileIO.build_maze(maze))\n # go back to beginning of the loop\n continue\n\n # if length was fitting we are now able to add the new row to the maze\n maze += \"\\n\" + row\n\n # show finished maze to the user\n print(\"Your inputted maze:\")\n show_maze(fileIO.build_maze(maze))\n\n # make user choose name for the maze\n maze_name = input(\"Give your maze a name!\\n\")\n\n # return maze name and new maze (as string)\n return maze_name, maze\n","sub_path":"2018/08/08_Ex_Sol/mazesolver/userIO.py","file_name":"userIO.py","file_ext":"py","file_size_in_byte":9181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"548609540","text":"def DancingWithTheGooglers(inputFile, outputFile):\n\tf = open(inputFile)\n\tinputLine = f.readlines()\n\tf.close()\n\tT = int(inputLine[0])\n\tf = open(outputFile, 'w')\n\tfor t in range(1, T + 1):\n\t\tline = inputLine[t]\n\t\tintegers = line.split()\n\t\tN = integers.pop(0)\n\t\tS = int(integers.pop(0))\n\t\tp = int(integers.pop(0))\n\t\tscores = integers\n\t\tnormalLimit = p + 2 * max(0, p - 1)\n\t\tsurprisingLimit = p + 2 * max(0, p - 2)\n\t\tnormal = 0\n\t\tsurprising = 0\n\t\tfor score in scores:\n\t\t\tscore = int(score)\n\t\t\tif score >= normalLimit:\n\t\t\t\tnormal += 1\n\t\t\telif score >= surprisingLimit:\n\t\t\t\tsurprising += 1\n\t\tf.write('Case #' + str(t) + ': ' + str(normal + min(S, surprising))\n\t\t\t\t+ '\\n')\n\tf.close()\n","sub_path":"solutions_1595491_1/Python/lahgh4Ch/DancingWithTheGooglers.py","file_name":"DancingWithTheGooglers.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"599424655","text":"\"\"\"\n연도를 넘겨주면 해당 연도가 윤년인지 아닌지를 리턴해주는\n\nIsLeapYear(inYear) 함수를 작성하세요\n\n단, 윤년은 2012년 2016년 같이 4로 나누어 떨어지는 연도이지만, 2100년과 같이 4와 100으로 동시에 나누어 떨어지는 경우에는 윤년이 아닙니다\n\"\"\"\ndef IsLeapYear(inYear):\n if( (( inYear % 4 ) == 0 ) and ((inYear % 100) != 0)):\n return print(\"윤년입니다.\")\n else: return print(\"윤년이 아닙니다.\")\n\nIsLeapYear(2016)\nIsLeapYear(2100)\n\n\"\"\"\n1. for 문을 이용해서 3의 배수를 구해주세요.\n결과 : \"~는 3의 배수입니다\"\n\na= [12,78,6,94,587,156,789,481,567,74,12444]\n\"\"\"\na= [12,78,6,94,587,156,789,481,567,74,12444]\n[print(\"%d는 3의 배수입니다.\" %i) for i in a if i % 3 == 0]\n\n\"\"\"\n2. while문을 이용하여 아래와 같은 문답을 작성하시오\n(정답을 맞췄을 때에는 stop이 되야합니다.)\n\n제주도에서 가장 유명한 것은 무엇일까요?\n1. 배추\n2. 딸기\n3. 포도\n4. 이스트소프트\n5. 다음카카오\n6. 귤\n\n정답은?\n\"\"\"\n\nL = [\"배추\", \"딸기\", \"포도\", \"이스트소프트\", \"다음카카오\", \"귤\"]\nwhile (1):\n print(\"제주도에서 가장 유명한 것은 무엇일까요?\")\n for i, v in enumerate(L, 1):\n print(\"%d.\"%i, v)\n\n choice = input(\"정답은? \")\n if choice == \"귤\" or choice == '6':\n break\n\n\"\"\"\n1.\n>>>num = 0\n>>>while 1:\n\t#코드 구현하세용\n\t#\n\t#\n\ncontinue또는 break를 이용해서 0~10 중 짝수만 출력하도록 하세요.\n위의 코드 아래부분을 채워주세요.(0,2,4,6,8,10 이 출력 되면 됨)\n\"\"\"\nnum = 0\nwhile 1:\n if num % 2 == 0:\n print(num)\n num += 1\n elif num > 10:\n break\n else:\n num += 1\n continue\n\"\"\"\n2.\n1번 문제를 while 1 대신 range함수를 이용하여 구현하세요.\n\"\"\"\n\nfor i in range(11):\n if i % 2 == 0:\n print(i)\n\n\"\"\"\n3.\ndef positive(l):\n result = []\n for i in l:\n if i > 0:\n result.append(i)\n return result\n\nprint(positive([1,-3,2,0,-5,6]))\n\n위의 코드를 filter함수를 이용하여 재작성하시오\n\"\"\"\nL = [1, -3, 2, 0, -5, 6]\ndef positive(i):\n return i > 0\n\nprint(list(filter(positive, L)))\n\n\n\n","sub_path":"A/SeokKwon Kang/week4/week4.py","file_name":"week4.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"119667551","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 27 21:17:33 2017\n\n@author: misakawa\n\"\"\"\n\nclass Debugger(object):\n attribute_acceses = []\n method_calls = []\n \nimport time\ndef wrapperf(self, func):\n def _f(*args, **kwargs):\n start = time.time()\n d = {'class':self.__class__,\n 'method':func.__name__,\n 'args': [], \n 'kwargs':kwargs,\n 'time':0\n }\n d['args'] = tuple([self]+list(args)) # fuck py27\n Debugger.method_calls.append(d)\n ret = func(*args, **kwargs)\n d['time'] = time.time()-start\n return ret\n return _f\n\n\ndef wrappera( k, v, self, action):\n d = {'class':self.__class__,\n 'action':action,\n 'attribute':k,\n 'value':v\n } \n Debugger.attribute_acceses.append(d)\n return v\n\ndef setter_hook(func):\n def fkpy27(self, name, value):\n wrappera(name, value, self, 'set')\n return func(self,name,value)\n return fkpy27\n\ndef getter_hook(func):\n def fkpy27(self, name):\n v = func(self, name)\n if name in ('__class__','__name__'):\n return v\n if callable(v):\n wrappera(name, v, self, 'get')\n return wrapperf(self, v)\n return wrappera(name, v, self, 'get')\n return fkpy27\n \n \n\ndef init_hook(func, name):\n def fkpy27(*args, **kwargs):\n start = time.time()\n d = {'class':name,\n 'method':name,\n 'args':args,\n 'kwargs':kwargs,\n 'time':0\n } \n Debugger.method_calls.append(d)\n ret = func(*args, **kwargs)\n d['time'] = time.time()-start\n return ret\n return fkpy27\n\n\nclass Meta(type):\n def __new__(cls, name, bases, attrs):\n \n attrs['__init__'] = init_hook(attrs['__init__'], name)\n attrs['__getattribute__'] = getter_hook(object.__getattribute__)\n attrs['__setattr__'] = setter_hook(object.__setattr__)\n return type.__new__(cls, name, bases, attrs)\n \nclass Foo(metaclass = Meta):\n __metaclass__ = Meta\n def __init__(self, x):\n self.x = x\n\n def bar(self, v):\n return (self.x, v)\n \na = Foo(1)\na.bar(2)","sub_path":".shadow/codewars/py27_metadbg.py","file_name":"py27_metadbg.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"71534935","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom env.items import EnvItem\nfrom scrapy.http import Request\nfrom env.city import get_province_city\nimport time\nimport datetime\nimport string\n\ndef get_start_urls(start_date,end_date):\n start_time = datetime.datetime.strptime(start_date,'%Y-%m-%d')\n end_time = datetime.datetime.strptime(end_date,'%Y-%m-%d')\n delta_time = datetime.timedelta(days=1)\n while start_time <= end_time:\n date_str=start_time.strftime('%Y-%m-%d')\n year = date_str[0:4]\n month = string.atoi(date_str[5:7])\n day = string.atoi(date_str[8:10])\n date_str_2='%s-%d-%d' %(year,month,day)\n start_time = start_time + delta_time\n tmp_url='http://www.envir.gov.cn/info/index.asp?rsDate=%s&month=%s&year=%s' %(date_str_2,month,year)\n yield tmp_url\n\nclass EnvirSpider(scrapy.Spider):\n name = \"envir\"\n allowed_domains = [\"envir.gov.cn\"]\n url_list = get_start_urls(\"2008-01-01\",\"2010-12-31\")\n start_urls = tuple(url_list)\n# start_urls = ('http://www.envir.gov.cn/info/index.asp?rsDate=2013-12-23&month=12&year=2013',)\n\n def parse(self, response):\n try:\n newslistlb = response.css('a[class=\"xm\"]')\n tmp_str=response.url.split('=')[1].split('&')[0].split('-')\n tmp_date = '%04d-%02d-%02d' %(string.atoi(tmp_str[0]),string.atoi(tmp_str[1]),string.atoi(tmp_str[2]))\n for li in newslistlb:\n item = EnvItem()\n\n item[\"link\"] = \"http://www.envir.gov.cn\"+ li.xpath(\"@href\").extract()[0]\n item[\"title\"] = li.xpath(\"text()\").extract()[0]\n #tmp_arr=item[\"link\"].split(\"/\")\n #item[\"date\"] = str(\"-\".join(tmp_arr[-3:-1])+\"-\"+tmp_arr[-1][2:4])\n item[\"date\"] = str(tmp_date)\n (province, city) = get_province_city(item[\"title\"])\n item[\"province\"] = province\n item[\"city\"] = city\n yield item\n except:\n pass\n\n\n\n\n","sub_path":"envspider/env/env/spiders/envir.py","file_name":"envir.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"338144363","text":"#!/usr/bin/python2.7\nfrom OpenSSL import crypto\nimport time\n\nTYPE_RSA = crypto.TYPE_RSA\n\ncertKey=crypto.load_privatekey(crypto.FILETYPE_PEM, open(\"cert.key\", 'rt').read())\nissuerCert=crypto.load_certificate(crypto.FILETYPE_PEM, open(\"ca.crt\", 'rt').read())\nissuerKey=crypto.load_privatekey(crypto.FILETYPE_PEM, open(\"ca.key\", 'rt').read())\n\nreq = crypto.X509Req()\nreq.get_subject().CN = \"albert.apple.com\"\nreq.set_pubkey(certKey)\nreq.sign(certKey, \"sha1\")\n#csrstr = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)\nepoch = int(time.time() * 1000)\ncert = crypto.X509()\ncert.set_serial_number(epoch)\ncert.gmtime_adj_notBefore(0)\ncert.gmtime_adj_notAfter(60 * 60 * 24 * 3650)\ncert.set_issuer(issuerCert.get_subject())\ncert.set_subject(req.get_subject())\ncert.set_pubkey(req.get_pubkey())\ncert.sign(issuerKey, \"sha256\")\nwith open(\"test.crt\", \"w\") as cert_file:\n cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"102213079","text":"class Fib(object):\n\tdef __init__(self):\n\t\tself.a, self.b = 0,1\n\n\tdef __iter__(self):\n\t\treturn self\n\n\tdef __next__(self):\n\t\tself.a, self.b = self.b, self.a+self.b\n\t\tif self.a>100000:\n\t\t\traise StopIteration()\n\t\treturn self.a\n\n\tdef __getitem__(self, n):\n\t\tif isinstance(n, int):\n\t\t\ta,b = 1,1\n\t\t\tfor i in range(n):\n\t\t\t\ta,b = b, a+b\n\t\t\treturn a\n\t\telif isinstance(n, slice):\n\t\t\tprint('start, stop : ',n.start, n.stop)\n\t\t\treturn 0\n\t\telif isinstance(n, str):\n\t\t\tprint('get :',n)\n\t\t\treturn 0\n\n\tdef __delitem__(self, n):\n\t\tprint('delete',n)\n\n\tdef __getattr__(self, attr):\n\t\tprint('get', attr)\n\t\tif attr == 'get':\n\t\t\treturn 'get'\n\t\t#return function\n\t\telif attr == 'func':\n\t\t\treturn lambda: 'function'\n\t\t\n\t\traise AttributeError('Fib object has no attribute \\'%s\\'' % attr)\n\n\n\nf = Fib()\nfor i in f:\n\tprint(i)\n\nprint(f[1], f[1:2], f[:2], 'f[100] = %s' % f[100])\nf['g']\ndel(f[1])\nf.get\nf.hello\nprint(f.func())","sub_path":"classTest/Fib.py","file_name":"Fib.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"428844794","text":"# Your code here\nimport math\nimport random\nimport time\n\n\ndef slowfun_too_slow(x, y):\n v = math.pow(x, y)\n v = math.factorial(v)\n v //= (x + y)\n v %= 982451653\n\n return v\n\n\nmy_dict = {}\n\n\ndef slowfun(x, y):\n \"\"\"\n Rewrite slowfun_too_slow() in here so that the program produces the same\n output, but completes quickly instead of taking ages to run.\n \"\"\"\n\n check_key = (x, y)\n\n if check_key in my_dict:\n return my_dict[check_key]\n\n else:\n v = math.pow(x, y)\n v = math.factorial(v)\n v //= (x + y)\n v %= 982451653\n my_dict[check_key] = v\n return v\n\n # Your code here\n\n\n# Do not modify below this line!\nstart = time.time()\n\n\nfor i in range(50000):\n x = random.randrange(2, 14)\n y = random.randrange(3, 6)\n # print(f'{i}: {x},{y}: {slowfun(x, y)}')\n slowfun(x, y)\n\n\nend = time.time()\nprint(f\"time elapsed: {start - end}\")\n","sub_path":"applications/lookup_table/lookup_table.py","file_name":"lookup_table.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"3979228","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 26 17:38:53 2018\n\n@author: aleja\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom factors.MatrixService import reduceMatrixCol\n\n#############################3\ndef getFollowersUser(userdata):\n return userdata[\"music\"][\"num_followers\"]\n \ndef getArtistsUser(userdata):\n return userdata[\"music\"][\"num_artists\"]\n\ndef getMusicsUser(userdata):\n return userdata[\"music\"][\"num_songs\"]\n\ndef calculateExpertFactorMatrix(users,coldstart):\n numberOfUsers = len(users)\n \n #create expert matrix\n ExpertMatrix = np.zeros((numberOfUsers, numberOfUsers))\n # Passing through users and creating the expert matrix\n\n for refereceIdx, referenceUser in enumerate(users):\n for secondaryIdx, secondaryUser in enumerate(users):\n # If secondaryUser is the referenceUser, continue\n if (secondaryUser['id'] == referenceUser['id']):\n continue\n elif (secondaryUser['id'] == coldstart or referenceUser['id'] == coldstart):\n continue\n # The number of factors for expert (followers, Musics and Artist)\n numFactors = 3\n \n # Getting followers on references user\n followersOfUser= getFollowersUser(referenceUser)\n # Getting followes on secondary user\n followersSecondaryUser = getFollowersUser(secondaryUser)\n # Getting MUsics\n MusicsOfUser = getMusicsUser(referenceUser)\n MusicsSecondaryUser = getMusicsUser(secondaryUser)\n # Getting Artists\n ArtistsOfUser = getArtistsUser(referenceUser)\n ArtistSecondaryUser = getArtistsUser(secondaryUser)\n \n followerMetric = 0\n sumFollowers = (followersOfUser+followersSecondaryUser)\n if (sumFollowers != 0):\n followerMetric = followersOfUser/sumFollowers\n\n musicMetric = 0\n sumMusic = (MusicsOfUser+MusicsSecondaryUser)\n if (sumMusic != 0):\n musicMetric = MusicsOfUser/sumMusic\n\n artistMetric = 0\n sumArtist = (ArtistsOfUser+ArtistSecondaryUser)\n if (sumArtist != 0):\n artistMetric = ArtistsOfUser/sumArtist\n \n # Calculating the Expert factor between 2 users\n Fexp = (followerMetric + musicMetric + artistMetric)/numFactors\n \n ExpertMatrix[refereceIdx][secondaryIdx] = Fexp\n \n \n return ExpertMatrix\n\ndef calculateExpert(data,coldstart):\n users = data[\"users\"]\n numberOfUsers = len(users)\n\n # If there's just one user, the expert factor is 0\n if (numberOfUsers == 1):\n return { users[0]['id']: 0 }\n \n #calculating Expert Matrix\n ExpertMatrix = calculateExpertFactorMatrix(users,coldstart)\n #expert dict\n Experts = {}\n reducedVector = reduceMatrixCol(ExpertMatrix)\n for reducedIdx, reducedSum in enumerate(reducedVector):\n if (numberOfUsers==2):\n userFactor = reducedSum / (numberOfUsers - 1)\n Experts[users[reducedIdx]['id']] = userFactor\n else:\n userFactor = reducedSum / (numberOfUsers - 2)\n Experts[users[reducedIdx]['id']] = userFactor\n \n return Experts\n","sub_path":"src/factors/ColdstartExpertFactor.py","file_name":"ColdstartExpertFactor.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"566076215","text":"\"\"\"\nConsider numbers t(n) of the form t(n) = 2n2-1 with n > 1.\nThe first such numbers are 7, 17, 31, 49, 71, 97, 127 and 161.\nIt turns out that only 49 = 7*7 and 161 = 7*23 are not prime.\nFor n ? 10000 there are 2202 numbers t(n) that are prime.\n\nHow many numbers t(n) are prime for n ? 50,000,000 ?\n\"\"\"\nimport time\nimport math\nstart_time = time.time()\n\ncount = 0\nint_is_prime = []\n\ndef is_prime(num):\n d = 2\n while d * d <= num and num % d != 0:\n d += 1\n return d * d > num\n# print(\"List of Primes is completed\")\n\nfor x in range(2, 10000):\n# for x in range(2, 50000000):\n x = 2*x**2-1\n # if x % 7 == 0:\n # continue\n if is_prime(x):\n count += 1\nprint(count)\n\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n# input()","sub_path":"_216.py","file_name":"_216.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"594098015","text":"import discord\nfrom discord import Permissions\nfrom discord.ext import commands\nfrom utilities import get_string, fetch_res, update_res\nfrom utilities.configuration import configuration_options\nimport os\nfrom typing import Dict, Tuple, Any, List\n\nclass Core(commands.Cog):\n def __init__(self, bot: commands.Bot) -> None:\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_ready(self) -> None:\n \"\"\"Prints message to terminal when bot is ready\"\"\"\n print(f\"Logged on as {self.bot.user}\")\n\n\n def prepare_feature_strings(self, guild_config: Dict[str, Any]) -> Tuple[str, str]:\n guild_lang = guild_config[\"language\"]\n \n guild_features = guild_config[\"features\"]\n feature_string = \"- \" + \"\\n- \".join(guild_features) if guild_features else get_string(\"noFeatures\", guild_lang)\n\n feature_name = lambda n: n.split(\".\")[0]\n feature_filter = lambda n: n.endswith(\".py\") and feature_name(n) not in guild_features and feature_name(n) != \"core\"\n\n available_features = [feature_name(feature) for feature in os.listdir(\"src/cogs/\") if feature_filter(feature)]\n\n available_feature_string = \"- \" + \"\\n- \".join(available_features) if available_features else get_string(\"allFeatures\", guild_lang)\n\n return (feature_string, available_feature_string)\n\n @commands.command()\n async def configure(self, ctx: commands.Context, feature: str=None, option: str=None, *args) -> None:\n guild_configurations = fetch_res(\"local/guild_configurations\")\n guild_config = guild_configurations[str(ctx.guild.id)]\n guild_lang = guild_config[\"language\"]\n \n if not ctx.author.guild_permissions.manage_guild:\n await ctx.send(get_string(\"permissions\", guild_lang))\n return\n \n if feature is None:\n await ctx.send(get_string(\"configurationHelp\", guild_lang) % self.prepare_feature_strings(guild_config))\n return\n else:\n if option is None:\n await ctx.send(get_string(f\"{feature}Configuration\", guild_lang))\n return\n if option == \"enable\":\n if feature not in guild_config[\"features\"]:\n guild_configurations[str(ctx.guild.id)][\"features\"].append(feature)\n update_res(\"local/guild_configurations\", guild_configurations)\n await ctx.send(get_string(\"featureEnabled\", guild_lang) % feature)\n else:\n await ctx.send(get_string(\"featureAlreadyEnabled\", guild_lang) % feature)\n elif option == \"disable\":\n if feature in guild_config[\"features\"]:\n guild_configurations[str(ctx.guild.id)][\"features\"].remove(feature)\n update_res(\"local/guild_configurations\", guild_configurations)\n await ctx.send(get_string(\"featureDisabled\", guild_lang) % feature)\n else:\n await ctx.send(get_string(\"featureAlreadyDisabled\", guild_lang) % feature)\n else:\n await configuration_options[feature][option](ctx, *args)\n\n @commands.command()\n async def help(self, ctx: commands.Context, option: str=None) -> None:\n guild_config = fetch_res(\"local/guild_configurations\")[str(ctx.guild.id)]\n guild_lang = guild_config[\"language\"]\n embed = discord.Embed(title=get_string(\"help\", guild_lang), description=get_string(\"description\", guild_lang))\n\n embed.add_field(name=get_string(\"usage\", guild_lang), value=get_string(\"usageHelp\", guild_lang), inline=False)\n\n feature_name = lambda n: n.split(\".\")[0]\n feature_filter = lambda n: n.endswith(\".py\") and feature_name(n) != \"core\"\n\n features = list(map(feature_name, filter(feature_filter, os.listdir(\"src/cogs/\"))))\n feature_string = \"- \" + \"\\n- \".join(features) if features else get_string(\"allFeatures\", guild_lang)\n\n embed.add_field(name=get_string(\"features\", guild_lang), value=feature_string, inline=False)\n\n await ctx.send(embed=embed)\n\ndef setup(bot: commands.Bot) -> None:\n bot.add_cog(Core(bot))\n","sub_path":"src/cogs/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"341389640","text":"import time\n\nN_ITEMS = 60000\n\nl = []\n\nstart = time.time()\n\nfor item in range(N_ITEMS):\n l.insert(0, item)\n\n\nend = time.time()\n\nprint(\"It took %f seconds to insert %d items into the beginning of a list\" %(end - start, N_ITEMS))\n\n","sub_path":"profiling/insert_many.py","file_name":"insert_many.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"377138529","text":"import csv\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\n\n\ndef read_data(filename):\n data = []\n with open(filename) as csvfile:\n csvdata = csv.reader(csvfile, delimiter=\",\", quotechar='\"')\n for row in csvdata:\n data.append((row[1].split(), row[0]))\n return data\n\ndef prepare_sequence(seq, to_ix):\n idxs = [to_ix[w] for w in seq]\n #print(idxs)\n tensor = torch.LongTensor(idxs)\n return autograd.Variable(tensor)\n\ndef make_target(label, label_to_ix):\n #print([label_to_ix[label]])\n return autograd.Variable(torch.LongTensor([label_to_ix[label]]))\n\ndef tag_name(log_probs, label):\n smax = nn.Softmax()\n pred_out = smax(log_probs)[0].data\n # print(pred_out)\n out = False\n p_out = 0\n p_label = label\n if (pred_out[0] > pred_out[1] and pred_out[0] > pred_out[2]):\n p_out = pred_out[0]\n p_label = \"NONE\"\n if label == \"NONE\":\n out = True\n elif (pred_out[1] > pred_out[0] and pred_out[1] > pred_out[2]):\n p_out = pred_out[1]\n p_label = \"DEBIT\"\n if label == \"DEBIT\":\n out = True\n elif pred_out[2] > pred_out[0] and pred_out[2] > pred_out[1]:\n p_out = pred_out[2]\n p_label = \"CREDIT\"\n if label == \"CREDIT\":\n out = True\n return (out, p_out, p_label)\n\n\ndef readLangData(lang):\n print(\"Reading lines...\")\n\n # Read the file and split into lines\n lines = open('data/alice.%s' % (lang), encoding='utf-8'). \\\n read().strip().split('\\n')\n\n return lines\n\n\n","sub_path":"translation/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"345299053","text":"import MySQLdb\ndef dbEntry(sql):\n db = MySQLdb.connect(\"localhost\",\"pi\",\"openhabiann\",\"SmartLab\")\n cursor= db.cursor()\n try:\n cursor.execute(sql)\n db.commit()\n except Exception as e:\n print(e)\n db.rollback()\n db.close()\n","sub_path":"IotTest/Right/DatabaseC.py","file_name":"DatabaseC.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"206865773","text":"\"\"\"empty message\n\nRevision ID: a63dd3065aa7\nRevises: eb497edfb2b3\nCreate Date: 2021-02-13 15:38:32.759657\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a63dd3065aa7'\ndown_revision = 'eb497edfb2b3'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user_model', schema=None) as batch_op:\n batch_op.create_unique_constraint(batch_op.f('uq_user_model_email'), ['email'])\n batch_op.create_unique_constraint(batch_op.f('uq_user_model_username'), ['username'])\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user_model', schema=None) as batch_op:\n batch_op.drop_constraint(batch_op.f('uq_user_model_username'), type_='unique')\n batch_op.drop_constraint(batch_op.f('uq_user_model_email'), type_='unique')\n\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a63dd3065aa7_.py","file_name":"a63dd3065aa7_.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"586823915","text":"import time\nfrom util import load_and_parse\n\n\ndef parse_function(line):\n return int(line)\n\n\ndata = load_and_parse(\"data.txt\", parse_function)\n\n\ndef part_one(data):\n l = []\n for val in data:\n if len(l) < 25:\n l.append(val)\n else:\n if find_val(val, l):\n l.pop(0)\n l.append(val)\n else:\n return val\n\n\ndef find_val(val, data):\n two_sum = {}\n for num in data:\n if num in two_sum and two_sum[num] != num:\n return True\n else:\n two_sum[val-num] = num\n\n return False\n\n\ndef part_two(data, target):\n start = 0\n end = start\n total = 0\n l = []\n while end < len(data) and total < target:\n total += data[end]\n l.append(data[end])\n end += 1\n while total > target:\n total -= data[start]\n start += 1\n l.pop(0)\n\n l.sort()\n return l[0] + l[-1]\n\ntarget = part_one(data)\nprint(target)\nprint(part_two(data, target))\n","sub_path":"Day9/day_solution.py","file_name":"day_solution.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"583566642","text":"import sqlite3\n\nurl = 'C:/Users/W7/python-workspace/myPythonpractice/test.db'\n\n#normal conncect\nconn = sqlite3.connect(url)\n\n#auto_commit\n# conn = sqlite3.connect(url, isolation_level=None)\n\n#cursor\ncs = conn.cursor()\n\n# sql = \"select * from customer where category=? and region=?\"\n# cs.execute(sql, (1, 'Sea'))\n\n# # sql = \"select * from customer where id = :Id\"\n# # cs.execute(sql, {\"Id\": 1})\n\n# for row in cs.fetchall():\n# print(row)\n\nsql = \"insert into customer(name,category,region) values (?, ?, ?)\"\n# cs.execute(sql, ('홍길동', 1, '서울'))\n\ndata = (\n ('홍진우', 1, '서울'),\n ('강지수', 2, '부산'),\n ('김청진', 1, '서울'),\n)\n\ncs.executemany(sql, data)\n\n#commit\nconn.commit()\n\nconn.close()\n","sub_path":"DB/sqlite_EX_0.py","file_name":"sqlite_EX_0.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"518084929","text":"# Copyright 2014 VMware, Inc.\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 xml.etree.ElementTree as et\n\nfrom oslo_log import log as logging\n\nWAIT_INTERVAL = 2000\nMAX_ATTEMPTS = 5\n\nLOG = logging.getLogger(__name__)\n\n\nclass NsxSecurityGroupUtils(object):\n\n def __init__(self, nsxv_manager):\n LOG.debug(\"Start Security Group Utils initialization\")\n self.nsxv_manager = nsxv_manager\n\n def to_xml_string(self, element):\n return et.tostring(element)\n\n def get_section_with_rules(self, name, rules, section_id=None):\n \"\"\"Helper method to create section dict with rules.\"\"\"\n\n section = et.Element('section')\n section.attrib['name'] = name\n if section_id:\n section.attrib['id'] = section_id\n for rule in rules:\n section.append(rule)\n return section\n\n def get_container(self, nsx_sg_id):\n container = {'type': 'SecurityGroup', 'value': nsx_sg_id}\n return container\n\n def get_remote_container(self, remote_group_id, remote_ip_mac):\n container = None\n if remote_group_id is not None:\n return self.get_container(remote_group_id)\n if remote_ip_mac is not None:\n container = {'type': 'Ipv4Address', 'value': remote_ip_mac}\n return container\n\n def get_rule_config(self, applied_to_ids, name, action='allow',\n applied_to='SecurityGroup',\n source=None, destination=None, services=None,\n flags=None, logged=False):\n \"\"\"Helper method to create a nsx rule dict.\"\"\"\n ruleTag = et.Element('rule')\n ruleTag.attrib['logged'] = 'true' if logged else 'false'\n nameTag = et.SubElement(ruleTag, 'name')\n nameTag.text = name\n actionTag = et.SubElement(ruleTag, 'action')\n actionTag.text = action\n\n apList = et.SubElement(ruleTag, 'appliedToList')\n for applied_to_id in applied_to_ids:\n apTag = et.SubElement(apList, 'appliedTo')\n apTypeTag = et.SubElement(apTag, 'type')\n apTypeTag.text = applied_to\n apValueTag = et.SubElement(apTag, 'value')\n apValueTag.text = applied_to_id\n\n if source is not None:\n sources = et.SubElement(ruleTag, 'sources')\n sources.attrib['excluded'] = 'false'\n srcTag = et.SubElement(sources, 'source')\n srcTypeTag = et.SubElement(srcTag, 'type')\n srcTypeTag.text = source['type']\n srcValueTag = et.SubElement(srcTag, 'value')\n srcValueTag.text = source['value']\n\n if destination is not None:\n dests = et.SubElement(ruleTag, 'destinations')\n dests.attrib['excluded'] = 'false'\n destTag = et.SubElement(dests, 'destination')\n destTypeTag = et.SubElement(destTag, 'type')\n destTypeTag.text = destination['type']\n destValueTag = et.SubElement(destTag, 'value')\n destValueTag.text = destination['value']\n\n if services:\n s = et.SubElement(ruleTag, 'services')\n for protocol, port, icmptype, icmpcode in services:\n svcTag = et.SubElement(s, 'service')\n try:\n int(protocol)\n svcProtocolTag = et.SubElement(svcTag, 'protocol')\n svcProtocolTag.text = str(protocol)\n except ValueError:\n svcProtocolTag = et.SubElement(svcTag, 'protocolName')\n svcProtocolTag.text = protocol\n if port is not None:\n svcPortTag = et.SubElement(svcTag, 'destinationPort')\n svcPortTag.text = str(port)\n if icmptype is not None:\n svcPortTag = et.SubElement(svcTag, 'subProtocol')\n svcPortTag.text = str(icmptype)\n if icmpcode is not None:\n svcPortTag = et.SubElement(svcTag, 'icmpCode')\n svcPortTag.text = str(icmpcode)\n\n if flags:\n if flags.get('ethertype') is not None:\n pktTag = et.SubElement(ruleTag, 'packetType')\n pktTag.text = flags.get('ethertype')\n if flags.get('direction') is not None:\n dirTag = et.SubElement(ruleTag, 'direction')\n dirTag.text = flags.get('direction')\n return ruleTag\n\n def get_rule_id_pair_from_section(self, resp):\n root = et.fromstring(resp)\n pairs = []\n for rule in root.findall('rule'):\n pair = {'nsx_id': rule.attrib.get('id'),\n 'neutron_id': rule.find('name').text}\n pairs.append(pair)\n return pairs\n\n def extend_section_with_rules(self, section, nsx_rules):\n section.extend(nsx_rules)\n\n def parse_section(self, xml_string):\n return et.fromstring(xml_string)\n\n def get_nsx_sg_name(self, sg_data):\n return '%(name)s (%(id)s)' % sg_data\n\n def get_nsx_section_name(self, nsx_sg_name):\n return 'SG Section: %s' % nsx_sg_name\n\n def parse_and_get_section_id(self, section_xml):\n section = et.fromstring(section_xml)\n return section.attrib['id']\n\n def is_section_logged(self, section):\n # Determine if this section rules are being logged by the first rule\n # 'logged' value.\n rule = section.find('rule')\n if rule is not None:\n return rule.attrib.get('logged') == 'true'\n return False\n\n def set_rules_logged_option(self, section, logged):\n value = 'true' if logged else 'false'\n rules = section.findall('rule')\n updated = False\n for rule in rules:\n if rule.attrib['logged'] != value:\n rule.attrib['logged'] = value\n updated = True\n return updated\n","sub_path":"vmware_nsx/plugins/nsx_v/vshield/securitygroup_utils.py","file_name":"securitygroup_utils.py","file_ext":"py","file_size_in_byte":6399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"231796834","text":"import re\nimport sys\nimport subprocess\n\n\"\"\"\nUsage:\n python3 xx.py \n python3 xx.py \n\"\"\"\n\n\ndef protocol_transform(url):\n protocol = {\n 'ssh': 'git@github.com:',\n 'https': 'https://github.com/'\n }\n if url.startswith('g'):\n return protocol['https'] + url[len(protocol['ssh']):]\n else:\n return protocol['ssh'] + url[len(protocol['https']):]\n\n\ndef get_remote_name():\n remote_names = subprocess.getoutput('git remote').split('\\n')\n if len(sys.argv) != 2:\n print(\"Your remote names: {}\".format(\" \".join(remote_names)))\n remote_name = input(\"You must type one arg to specify a remote name: \")\n else:\n remote_name = sys.argv[1]\n return remote_name\n\n\ndef get_url(remote_name):\n remotes = subprocess.getoutput('git remote -v')\n ROW_REG = re.compile(r'.*{}.*'.format('origin'))\n remote = re.search(ROW_REG, remotes).group()\n url = re.split('[ \\t]', remote)[1]\n return url\n\n\nif __name__ == '__main__':\n remote_name = get_remote_name()\n url = get_url(remote_name)\n transformed_url = protocol_transform(url)\n subprocess.call(\n 'git remote set-url origin {}'.format(transformed_url), shell=True)\n","sub_path":"git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"515044733","text":"from django.shortcuts import render, redirect\nfrom album.models import Album\nfrom django.core.files.storage import FileSystemStorage\nimport datetime\nimport random\nimport sys, os\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef album(request):\n rsAlbum = Album.objects.all()\n\n return render(request, \"infoweb/album_list.html\")\n # return render(request, \"infoweb/album_list.html\")\n\n\ndef album_write(request):\n return render(request, \"infoweb/album_write.html\", )\n\n\ndef album_insert(request):\n\n atitle = request.POST['a_title']\n atype = request.POST['a_type']\n anote = request.POST['a_note']\n\n name_date = str(datetime.datetime.today().year) + '_' + str(datetime.datetime.today().month) + '_' + str(datetime.datetime.today().day)\n\n uploaded_file = request.FILES['ufile']\n name_old = uploaded_file.name\n name_ext = os.path.splitext(name_old)[1]\n name_new = 'A' + name_date + '_' + str(random.randint(1000000000, 9999999999))\n\n fs = FileSystemStorage(location='static/board/photos')\n\n name = fs.save(name_new + name_ext, uploaded_file)\n\n rows = Album.objects.create(a_title=atitle, a_note=anote, a_type=atype, a_image=name, a_usage='1')\n\n return redirect('album')\n\n\ndef album_view(request):\n ano = request.GET['a_no']\n\n rsData = Album.objects.get(a_no=ano)\n rsData.a_count += 1\n rsData.save()\n\n rsDetail = Album.objects.filter(a_no=ano)\n\n return render(request, \"infoweb/album_view.html\", {'rsDetail': rsDetail,'a_no': ano,})\n\ndef album_edit(request):\n ano = request.GET['a_no']\n rsDetail = Album.objects.filter(a_no=ano)\n\n return render(request, \"infoweb/album_edit.html\", {'rsDetail': rsDetail,'a_no': ano,})\n\n\ndef album_update(request):\n\n ano = request.POST['a_no']\n atitle = request.POST['a_title']\n atype = request.POST['a_type']\n anote = request.POST['a_note']\n\n if 'ufile' in request.FILES:\n name_date = str(datetime.datetime.today().year) + '_' + str(datetime.datetime.today().month) + '_' + str(datetime.datetime.today().day)\n\n uploaded_file = request.FILES['ufile']\n name_old = uploaded_file.name\n name_ext = os.path.splitext(name_old)[1]\n name_new = 'A' + name_date + '_' + str(random.randint(1000000000, 9999999999))\n\n fs = FileSystemStorage(location='static/board/photos')\n\n fname = fs.save(name_new + name_ext, uploaded_file)\n\n album = Album.objects.get(a_no=ano)\n album.a_title = atitle\n album.a_type = atype\n album.a_note = anote\n album.a_image = fname\n album.save()\n else:\n album = Album.objects.get(a_no=ano)\n album.a_title = atitle\n album.a_type = atype\n album.a_note = anote\n album.save()\n\n return redirect('album')\n\ndef album_delete(request):\n ano = request.GET['a_no']\n album = Album.objects.get(a_no=ano)\n album.a_usage = '0'\n album.save()\n\n return redirect('album')\n","sub_path":"album/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"294649412","text":"import json\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom datawinners.accountmanagement.decorators import valid_web_user\nfrom datawinners.entity.helper import get_organization_telephone_number\nfrom datawinners.entity.views import get_example_sms\nfrom datawinners.main.database import get_database_manager\nfrom datawinners.project.web_questionnaire_form import SurveyResponseForm\nfrom mangrove.form_model.form_model import REPORTER\nfrom datawinners.project.helper import get_preview_for_field, hide_entity_question\nfrom datawinners.project.models import Project\nfrom datawinners.project.subject_question_creator import SubjectQuestionFieldCreator\nfrom datawinners.project.wizard_view import create_questionnaire\n\n\ndef get_questions(form_model):\n fields = form_model.fields\n if form_model.is_entity_type_reporter():\n fields = hide_entity_question(form_model.fields)\n\n return [get_preview_for_field(field) for field in fields]\n\n\ndef get_questionnaire_form_model(manager, project_info, post):\n return create_questionnaire(post, manager, entity_type=unicode(project_info['entity_type']),\n name=unicode(project_info['name']), language=unicode(project_info['language']))\n\ndef get_sms_preview_context(manager, post, project_info):\n form_model = get_questionnaire_form_model(manager, project_info, post)\n example_sms = \"%s\" % form_model.form_code\n example_sms += get_example_sms(form_model.fields)\n return {\"questionnaire_code\": post[\"questionnaire-code\"],\n \"questions\": get_questions(form_model),\n \"project\": project_info,\n \"example_sms\": example_sms}\n\n\n@valid_web_user\ndef sms_preview(request):\n manager = get_database_manager(request.user)\n context = {'org_number': get_organization_telephone_number(request)}\n project_info = json.loads(request.POST['profile_form'])\n context.update(get_sms_preview_context(manager, request.POST, project_info))\n\n return render_to_response(\"project/sms_instruction_preview.html\", context, context_instance=RequestContext(request))\n\n\ndef add_link_context(project):\n if project.entity_type == REPORTER:\n text = _(\"Add a datasender\")\n return {'url': '#', 'text': text}\n else:\n text = _(\"Register a %(subject)s\") % {'subject': project.entity_type}\n return {'url': '#', 'text': text}\n\n\ndef get_web_preview_context(manager, post, project_info):\n form_model = get_questionnaire_form_model(manager, project_info, post)\n project = Project(name=unicode(project_info['name']), goals=unicode(project_info['goals']),\n project_type='survey', entity_type=unicode(project_info['entity_type']),\n activity_report=unicode(project_info['activity_report']),\n state=post['project_state'], devices=[u'sms', u'web', u'smartPhone'],\n language=unicode(project_info['language']))\n\n questionnaire_form = SurveyResponseForm(form_model,SubjectQuestionFieldCreator(manager, project))\n return {'project': project_info,\n 'questionnaire_form': questionnaire_form,\n 'add_link': add_link_context(project), }\n\n\n@valid_web_user\ndef web_preview(request):\n project_info = json.loads(request.POST['profile_form'])\n manager = get_database_manager(request.user)\n\n return render_to_response(\"project/web_instruction_preview.html\",\n get_web_preview_context(manager, request.POST, project_info),\n context_instance=RequestContext(request))\n\n\n@valid_web_user\ndef smart_phone_preview(request):\n language_code = request.LANGUAGE_CODE\n instruction_template = \"alldata/smart_phone_instruction_\" + language_code + \".html\"\n\n return render_to_response(\"project/smart_phone_instruction_preview.html\",\n {\"instruction_template\": instruction_template},\n context_instance=RequestContext(request))\n\n\n@valid_web_user\ndef questionnaire_sms_preview(request):\n manager = get_database_manager(request.user)\n context = {'org_number': get_organization_telephone_number(request)}\n project_info = Project.load(manager.database, request.POST['project_id'])\n if project_info:\n context.update(get_sms_preview_context(manager, request.POST, project_info))\n\n return render_to_response(\"project/sms_instruction_preview.html\", context, context_instance=RequestContext(request))\n\n\n@valid_web_user\ndef questionnaire_web_preview(request):\n manager = get_database_manager(request.user)\n project_info = Project.load(manager.database, request.POST[\"project_id\"])\n\n context = get_web_preview_context(manager, request.POST, project_info) if project_info else {}\n return render_to_response(\"project/web_instruction_preview.html\",\n context,\n context_instance=RequestContext(request))\n","sub_path":"datawinners/project/preview_views.py","file_name":"preview_views.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"266123944","text":"from django.urls import re_path\nfrom . import views\n\napp_name = 'redirectapp'\n\nurlpatterns = [\n # re_path(r'connectftp/(?P\\d{4}-\\d{2}-\\d{2})$', views.connectftp, name = 'connectftp')\n re_path(r'clients$', views.clients, name = 'clients'),\n re_path(r'bills$', views.bills, name = 'bills'),\n re_path(r'prices$', views.prices, name = 'prices'),\n]\n\n","sub_path":"redirectapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"579168968","text":"# encoding=utf8\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nfrom tensorflow.contrib import crf\n\n\nclass BiLSTMModel(object):\n def __init__(self, max_len=200, vocab_size=None, class_num=None, model_save_path=None, embed_size=256, hs=512):\n self.timestep_size = self.max_len = max_len\n self.vocab_size = vocab_size\n self.input_size = self.embedding_size = embed_size\n self.class_num = class_num\n self.hidden_size = hs\n self.lr = tf.placeholder(tf.float32, [])\n self.keep_prob = tf.placeholder(tf.float32, [])\n self.batch_size = tf.placeholder(tf.int32, [])\n self.model_save_path = model_save_path\n\n self.train()\n\n def train(self):\n with tf.variable_scope('Inputs'):\n self.X_inputs = tf.placeholder(tf.int32, [None, self.timestep_size], name='X_input')\n self.y_inputs = tf.placeholder(tf.int32, [None, self.timestep_size], name='y_input')\n\n with tf.variable_scope('Embeddings'):\n self.embedding = tf.get_variable(\"embedding\", [self.vocab_size, self.embedding_size], dtype=tf.float32)\n self.inputs = tf.nn.embedding_lookup(self.embedding, self.X_inputs)\n self.length = tf.cast(tf.reduce_sum(tf.sign(self.X_inputs), 1), tf.int32)\n\n with tf.variable_scope(\"BiLSTM\"):\n softmax_w = tf.Variable(tf.truncated_normal([self.hidden_size * 2, self.class_num], stddev=0.1))\n softmax_b = tf.Variable(tf.constant(0.1, shape=[self.class_num]))\n cell = rnn.LSTMCell(self.hidden_size, reuse=tf.get_variable_scope().reuse)\n self.lstm_cell = rnn.DropoutWrapper(cell, output_keep_prob=self.keep_prob)\n (output_fw, output_bw), _ = tf.nn.bidirectional_dynamic_rnn(self.lstm_cell, self.lstm_cell, self.inputs,\n sequence_length=self.length, dtype=tf.float32)\n output = tf.concat([output_fw, output_bw], axis=-1)\n bilstm_output = tf.reshape(output, [-1, self.hidden_size * 2])\n\n #print('The shape of BiLstm Layer output:', bilstm_output.shape)\n\n with tf.variable_scope('outputs'):\n self.y_pred = tf.matmul(bilstm_output,\n softmax_w) + softmax_b # there is no softmax, reduce the amount of calculation.\n\n self.scores = tf.reshape(self.y_pred, [-1, self.timestep_size,\n self.class_num]) # [batchsize, timesteps, num_class]\n #print('The shape of Output Layer:', self.scores.shape)\n log_likelihood, self.transition_params = crf.crf_log_likelihood(self.scores, self.y_inputs, self.length)\n self.loss = tf.reduce_mean(-log_likelihood)\n\n optimizer = tf.train.AdamOptimizer(learning_rate=self.lr)\n self.train_op = optimizer.minimize(self.loss)","sub_path":"cws/BiLSTM.py","file_name":"BiLSTM.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"626112272","text":"import cv2\nimport numpy as np\n# import matplotlib.pyplot as plt\n# import glob\n# import scipy.io\nimport time\n\n# from keras.models import Sequential, Model\n# from keras.layers import Reshape, Activation, Conv2D, Input, MaxPooling2D, BatchNormalization, Flatten, Dense\n# from keras.layers.advanced_activations import LeakyReLU\n# from keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\n# from keras.optimizers import SGD, Adam\n# from keras.models import load_model, Model\n\nDOWNSAMPLE_RATIO = 2\nCONFIDENCE = 0.4\nTHRESH = 0.5\ninpWidth = 416\ninpHeight = 416\n\nGAMMA = 1.5\ninvGamma = 1.0/GAMMA\ntable = np.array([((i / 255.0) ** invGamma) * 255 for i in range(0, 256)]).astype(\"uint8\")\\\n\ndef gammaCorrection(image):\n return cv2.LUT(image, table)\n\ndef drawBBoxes(classID, conf, left, top, right, bottom):\n color = [int(c) for c in COLORS[classID]]\n cv2.rectangle(frame, (left, top), (right, bottom), color)\n\n text = \"{} : {:.4f}\".format(LABELS[classID], conf)\n\n labelSize, baseLine = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n top = max(top, labelSize[1])\n cv2.putText(frame, text, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n\n\ndef postProcess(frame, outs):\n frameHeight, frameWidth = frame.shape[:2]\n\n boxes = []\n confidences = []\n classIDs = []\n \n for output in layerOutputs:\n for detection in output:\n scores = detection[5:]\n classID = np.argmax(scores)\n confidence = scores[classID]\n\n if confidence > CONFIDENCE:\n box = detection[0:4] * np.array([frameWidth, frameHeight, frameWidth, frameHeight])\n (centerX, centerY, width, height) = box.astype(\"int\")\n\n left = int(centerX - (width / 2))\n top = int(centerY - (height / 2))\n\n boxes.append([left, top, int(width), int(height)])\n confidences.append(float(confidence))\n classIDs.append(classID)\n\n idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESH)\n\n if len(idxs) > 0:\n for i in idxs:\n i = i[0]\n (x, y) = (boxes[i][0], boxes[i][1])\n (w, h) = (boxes[i][2], boxes[i][3])\n \n\n drawBBoxes(classIDs[i], confidences[i], x, y, x + w, y + h)\n\n\n\nyolo_model_path = \"models/yolov3-tiny.h5\"\nyolo_weights_path = \"models/yolov3-tiny.weights\"\nyolo_cfg_path = \"models/yolov3-tiny.cfg\"\nyolo_labels_path = \"models/coco.names\"\n\nwith open(yolo_labels_path, 'rt') as f:\n LABELS = f.read().rstrip(\"\\n\").split(\"\\n\")\n\nnp.random.seed(42)\nCOLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype=\"uint8\")\n\nnet = cv2.dnn.readNetFromDarknet(yolo_cfg_path, yolo_weights_path)\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)\n\nvideo_file = \"../video 2_processed.mov\"\ncap = cv2.VideoCapture(video_file)\n\nif(cap.isOpened() == False):\n print(\"Error opening video file\")\n\nfirstFrame = True\n\nwhile(cap.isOpened()):\n\n ret, frame = cap.read()\n if ret == False:\n print(\"Not able to read video stream\")\n\n frame = cv2.resize(frame, None, \n fx = 1.0/DOWNSAMPLE_RATIO, \n fy = 1.0/DOWNSAMPLE_RATIO, \n interpolation = cv2.INTER_LINEAR)\n\n if firstFrame:\n height, width = frame.shape[:2]\n vid_writer = cv2.VideoWriter('vehicle_detection_yolo.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 15, (width,height))\n firstFrame = False\n\n frame = gammaCorrection(frame)\n\n blob = cv2.dnn.blobFromImage(frame, 1/255.0, (inpWidth, inpHeight), swapRB = True, crop=False)\n \n net.setInput(blob)\n\n ln = net.getLayerNames()\n ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n layerOutputs = net.forward(ln)\n\n postProcess(frame, layerOutputs)\n\n t, _ = net.getPerfProfile()\n label = 'FPS: %.2f' % (cv2.getTickFrequency() / t)\n cv2.putText(frame, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n\n cv2.imshow(\"test\", frame)\n vid_writer.write(frame)\n # cv2.waitKey(0)\n\n if cv2.waitKey(1) & 0xFF == 27:\n break\n\ncap.release()\nvid_writer.release()\ncv2.destroyAllWindows()\n\n# NORM_H, NORM_W = 416, 416\n# GRID_H, GRID_W = 13 , 13\n# BATCH_SIZE = 8\n# BOX = 5\n# ORIG_CLASS = 20\n\n# model = Sequential()\n\n# #Layer 1\n# model.add(Conv2D(16, (3,3), strides=(1,1), padding='same', use_bias=False, input_shape=(416,416,3)))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n\n# # Layer 2 - 5\n# for i in range(0, 4):\n# model.add(Conv2D(32*(2**i), (3,3), strides=(1,1), padding='same', use_bias=False))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n\n# # Layer 6\n# model.add(Conv2D(512, (3,3), strides=(1,1), padding='same', use_bias=False))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n# model.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1), padding='same'))\n\n# # Later 7\n# model.add(Conv2D(1024, (3,3), strides=(1,1), padding='same', use_bias=False))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n\n# # Later 8\n# model.add(Conv2D(256, (1,1), strides=(1,1), padding='same', use_bias=False))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n\n# # Layer 9\n# model.add(Conv2D(512, (3,3), strides=(1,1), padding='same', use_bias=False))\n# model.add(BatchNormalization())\n# model.add(LeakyReLU(alpha=0.1))\n\n# # Layer 10\n# model.add(Conv2D(BOX * (4 + 1 + ORIG_CLASS), (1, 1), strides=(1, 1), kernel_initializer='he_normal'))\n\n\n# model.add(Activation('linear'))\n# model.add(Reshape((GRID_H, GRID_W, BOX, 4 + 1 + ORIG_CLASS)))\n\n# model.summary()","sub_path":"Autonomous-Driving/vehicleDetection.py","file_name":"vehicleDetection.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"402677142","text":"import json\nfrom pytest_mock import mocker\nfrom woqlclient import const\n\ndef mocked_requests(*args,**kwargs):\n\n\tclass MockResponse:\n\n\t\tdef json(self):\n\t\t\tif(self._json_data==None):\n\t\t\t\traise ValueError(\"EXCEPTION NO JSON OBJECT\")\n\t\t\treturn self._json_data\n\n\t\t@property\n\t\tdef status_code(self):\n\t\t\treturn self._status_code\n\n\t\t@property\n\t\tdef url(self):\n\t\t\treturn self._url\n\n\t\t@property\n\t\tdef text(self):\n\t\t\treturn self._text\n\n\t\tdef __init__(self,url,status,actionType):\n\n\t\t\t# set status code and content\n\t\t\tself._json_data=None\n\t\t\tself._text=None\n\t\t\tself._status_code=status\n\t\t\tself._content='cont'\n\t\t\tself._url=url\n\t\t\t# add json data if provided\n\t\t\tprint('ACTION TYPE', actionType)\n\t\t\tif actionType==const.CONNECT:\n\t\t\t\twith open('tests/capabilitiesResponse.json') as json_file:\n\t\t\t\t\tjson_data = json.load(json_file)\n\t\t\t\t\tself._json_data=json_data\n\t\t\t\t\tjson_file.close()\n\n\t\t\telif actionType==const.GET_SCHEMA:\n\t\t\t\twith open('tests/getSchemaTurtleResponse.txt') as text_file:\n\t\t\t\t\tself._text=text_file.read();\n\t\t\t\t\ttext_file.close();\n\n\t\t\telif actionType==const.WOQL_SELECT:\n\t\t\t\twith open('tests/getAllClassQueryResponse.json') as json_file:\n\t\t\t\t\tjson_data = json.load(json_file)\n\t\t\t\t\tself._json_data=json_data\n\t\t\t\t\tjson_file.close()\n\n\t\t\telif actionType==const.CREATE_DATABASE or actionType==const.DELETE_DATABASE or actionType==const.UPDATE_SCHEMA:\n\t\t\t\tself._json_data={\"terminus:status\":\"terminus:success\"}\n\n\tif args[0] == 'http://localhost:6363/myFirstTerminusDB/schema?terminus%3Aencoding=terminus%3Aturtle':\n\t\treturn MockResponse(args[0], 200,const.GET_SCHEMA)\n\n\telif args[0] == 'http://195.201.12.87:6363/myFirstTerminusDB/schema':\n\t\treturn MockResponse(args[0], 200,const.UPDATE_SCHEMA)\n\n\telif (args[0].find(\"http://localhost:6363/myFirstTerminusDB/woql\")!=-1):\n\t\treturn MockResponse(args[0], 200,const.WOQL_SELECT)\n\n\telif args[0] == \"http://localhost:6363/myFirstTerminusDB\" :\n\t\treturn MockResponse(args[0], 200,const.DELETE_DATABASE)\n\n\treturn MockResponse(args[0],200,const.CONNECT)\n","sub_path":"tests/mockResponse.py","file_name":"mockResponse.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"472259390","text":"from informationExtraction import person\r\nimport unittest\r\n\r\nclass TestPerson(unittest.TestCase):\r\n\r\n\tdef testIsPersonRealTrue(self):\r\n\t\tp = person.Person(\"Angela\", \"Medicine\")\r\n\t\tb = person.Person.isPersonReal(p)\r\n\t\tself.assertEqual(b, True)\r\n\r\n\tdef testIsPersonRealFalse(self):\r\n\t\tp = person.Person(\"Tracer\", \"Chronology\")\r\n\t\tb = person.Person.isPersonReal(p)\r\n\t\tself.assertEqual(b, False)\r\n\t\t\r\nif __name__ == \"__main__\":\r\n\t\tunittest.main()","sub_path":"software/information_extraction/testPerson.py","file_name":"testPerson.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"622572818","text":"from sense_hat import SenseHat\nfrom time import sleep\n# Snurra på golvet/bordet och läs rotation runt yaw(\"gira\")axeln.\n# + kombinera det med att läsa av fröjdepinnen(\"joystick\").\n# ...men här håller olika delar på och skriver sönder/över varandra på 8x8 displayen.\n# ...knapparna är tilldelade lite hit och dit ;-(\n\n## https://pythonhosted.org/sense-hat/api/#imu-sensor\n##Kolla vilka i2c enheter som är inkopplade just nu \n##$ sudo i2cdetect -y 1\n## 0 1 2 3 4 5 6 7 8 9 a b c d e f\n##00: -- -- -- -- -- -- -- -- -- -- -- -- -- \n##10: -- -- -- -- -- -- -- -- -- -- -- -- 1c -- -- -- \n##20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n##30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- \n##40: -- -- -- -- -- -- UU -- -- -- -- -- -- -- -- -- \n##50: -- -- -- -- -- -- -- -- -- -- -- -- 5c -- -- 5f \n##60: -- -- -- -- -- -- -- -- -- -- 6a -- -- -- -- -- \n##70: -- -- -- -- -- -- -- -- \n\nsense = SenseHat()\nsense.clear()\n\n# Define the functions\ndef red():\n sense.clear(255, 0, 0)\n\ndef blue():\n sense.clear(0, 0, 255)\n\ndef green():\n sense.clear(0, 255, 0)\n \ndef yellow():\n sense.clear(255, 255, 0)\n\n# Tell the program which function to associate with which direction\nsense.stick.direction_up = red\nsense.stick.direction_down = blue\nsense.stick.direction_left = green\nsense.stick.direction_right = yellow\nsense.stick.direction_middle = sense.clear # Press the enter key\n\ntry:\n # Denna kod kör bara en gång!\n # Visa tecken på 8x8 Display/Matrix\n sense.show_letter(\"1\") \n event = sense.stick.wait_for_event()\n sleep(0.1)\n event = sense.stick.wait_for_event(emptybuffer=True)\n sense.clear()\n \n sense.show_letter(\"2\") \n pressure = round (sense.get_pressure(),1)\n print(\"Pressure: %s Millibars\" % pressure)\n temp = round (sense.get_temperature(),1)\n print(\"Temperature: %s C\" % temp)\n \n sense.show_letter(\"3\") \n event = sense.stick.wait_for_event()\n sleep(0.1)\n event = sense.stick.wait_for_event(emptybuffer=True)\n sense.clear()\n \n # Visa bokstav(\"pil\") på 8x8 Display/Matrix\n sense.show_letter(\"V\")\n event = sense.stick.wait_for_event()\n print (\"Try...\")\n while True:\n #o = sense.get_orientation_radians() \n o = sense.get_orientation_degrees()\n pitchRaw = o[\"pitch\"]\n rollRaw = o[\"roll\"]\n yawRaw = o[\"yaw\"]\n \n pitch = round(pitchRaw,0)\n roll = round(rollRaw ,0)\n yaw = round(yawRaw ,0)\n print(\"pitch {0} roll {1} yaw {2}\".format(pitch, roll, yaw))\n\n if (yaw < 90.0):\n sense.set_rotation(0)\n elif (yaw >= 90.0 and yaw < 180.0 ):\n sense.set_rotation(90)\n elif (yaw >= 180.0 and yaw < 270.0 ):\n sense.set_rotation(180)\n elif (yaw >= 270.0 and yaw < 360.0 ):\n sense.set_rotation(270)\n else:\n sense.show_letter(\"?\") # Detta kan aldrig hända!!!\n\nexcept KeyboardInterrupt:\n # User pressed CTRL-C\n # Reset GPIO settings\n print (\"Cancel! Ctrl-C pressed...\")\n sense.clear()\n","sub_path":"diagnos/RPi_senseHat/SenseHAT-IMU+joystick(verZ).py","file_name":"SenseHAT-IMU+joystick(verZ).py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"623907018","text":"# JSON stringify method converts an object or value to a JSON string.\n\n# Clarifications:\n# a) Given an object or value convert to a valid JSON string format. Valid JSON\n# format involves data in name/value pairs, data separated by commas, curly\n# braces to hold objects, and square brackets to hold arrays. Can be hash or array \n# with nested hashes or arrays like {key:{key1:{}} or of the like ['here', True, None].\n# b) Break it down into valid syntax which are (name/value pairs, commas, curly braces, square\n# brackets) and valid values (string, number, object, array, boolean, null).\n# c) Given {'x': 5, 'y': 6} return \"{'x':5,'y':6}\"\n# d) Given [new Thing('thing'), True, None] return \"['thing',True,None]\"\n#\n# Edge cases:\n# a) Given None return None\n# b) Given invalid JSON such as 'string' raise Exception\n# c) Given {} return '{}'\n# d) Given [] return '[]'\n#\n# Algorithms:\n# a) if array iterate over each element and concatenate the string representation\n# to the output string.\n# b) if key/value, such as {key: {key1: [value1, value2], key2: value3}}, then you should\n# concatenate key to output string, then repeat process for value. For instance, add\n# key to output string and call the same function on the value to key. \n\ndef jsonStringifyObjectHelper(json, syntax):\n if isinstance(json, str):\n return syntax + json + syntax\n else:\n return str(json)\n\ndef jsonStringifyArrayHelper(json, syntax):\n output = '['\n for i in range(len(json)):\n output += jsonStringifyObjectHelper(json[i], syntax)\n if not len(json)-1 == i:\n output += ','\n return output + ']'\n\ndef jsonStringifyDictHelper(json, syntax):\n output = '{'\n for key, value in json.iteritems():\n output += syntax + key + syntax + ':'\n output += jsonStringifyCollectionHelper(value)\n output += ','\n return output + '}'\n\ndef jsonStringifyCollectionHelper(json):\n output = ''\n if output == '':\n syntax = '\"'\n else:\n syntax = \"'\"\n\n if isinstance(json, list):\n return jsonStringifyArrayHelper(json, syntax)\n elif isinstance(json, dict):\n return jsonStringifyDictHelper(json, syntax)\n else:\n return output + jsonStringifyObjectHelper(json, '\"')\n\ndef jsonStringify(json):\n if json == None:\n return None\n if not isinstance(json, list) and not isinstance(json, dict):\n raise Exception('invalid JSON input')\n return jsonStringifyCollectionHelper(json)\n\nassert(jsonStringify(None) == None)\nassert(jsonStringify([]) == '[]')\nassert(jsonStringify([True, False, 'string']) == '[True,False,\"string\"]')\nassert(jsonStringify({}) == '{}')\nprint(jsonStringify({'key1': 'value1', 'key2': 'value2'}))\n# assert(jsonStringify({'key1': 'value1', 'key2': 'value2'}) == '{\"key1\":\"value1\",\"key2\":\"value2\"}')\njsonStringify('string') # expect Exception\n","sub_path":"jsonStringify.py","file_name":"jsonStringify.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"478121162","text":"#!/usr/bin/env python\n#\n# File Name: Chapter05.py\n# Author: Evan Pete Walsh\n# Contact: epwalsh@iastate.edu\n# Creation Date: 13-10-2015\n# Last Modified: Tue Oct 13 21:07:36 2015\n# =============================================================================\n\n'''Purpose'''\n\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport numpy as np\n\nobj = Series([4, 7, -5, 3])\nobj.values\nobj.index\n\nobj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])\nobj2.index\nobj2[obj2 > 0]\nnp.exp(obj2)\n\n'b' in obj2\n\nsdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}\n\nobj3 = Series(sdata)\nobj3\n\nstates = ['California', 'Ohio', 'Oregon', 'Texas']\nobj4 = Series(sdata, index=states)\nobj4\npd.isnull(obj4)\npd.notnull(obj4)\nobj4.isnull()\n\nobj3 + obj4\n\nobj4.name = 'population'\nobj4.index.name = 'state'\nobj4\n\nobj\nobj.index = ['Bob', 'Steve', 'Jeff', 'Ryan']\n\ndata = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],\n 'year': [2000, 2001, 2002, 2001, 2002],\n 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}\nframe = DataFrame(data)\nframe\n\nDataFrame(data, columns=['year', 'state', 'pop'])\n\nframe2 = DataFrame(data, columns=['year', 'state', 'pop', 'debt'],\n index=['one', 'two', 'three', 'four', 'five'])\nframe2\n\nframe2['state']\nframe2.year\n\nframe2.ix['three']\nframe2['debt'] = 16.5\n\nframe2['debt'] = np.arange(5.)\nframe2\n\nval = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five'])\nframe2['debt'] = val\nframe2\n\nframe2['eastern'] = frame2.state == 'Ohio'\ndel frame2['eastern']\n\npop = {'Nevada': {2001: 2.4, 2002: 2.9},\n 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}\nframe3 = DataFrame(pop)\nframe3\n\nframe3.T\n\nframe3.index.name = 'year'\nframe3.columns.name = 'state'\nframe3.values\nframe2.values\n\n\nobj = Series(range(3), index=['a', 'b', 'c'])\nindex = obj.index\nindex\nindex[1:]\n\nindex = pd.Index(np.arange(3))\nobj2 = Series([1.5, -2.5, 0], index=index)\nobj2\nobj2.index is index\n","sub_path":"Python/Python_Data_Book/Chapter05.py","file_name":"Chapter05.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"111371659","text":"\n# python plotHiC_withTADs_withCols.py\n\nimport os\nimport sys\nimport re\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.ndimage import rotate\nfrom scipy.sparse import coo_matrix, triu\n\ndef to_matrix(data, chrom1, chrom2, \n resolution, assembly=\"hg19\",\n start1=None, end1=None, \n start2=None, end2=None):\n \n if all([x is not None for x in [start1, end1, start2, end2]]):\n start_bin1 = start1//resolution\n end_bin1 = end1//resolution\n start_bin2 = start2//resolution\n end_bin2 = end2//resolution\n else:\n chromsize = load_chromsizes(assembly)\n chromsize1 = chromsize[chrom1]\n chromsize2 = chromsize[chrom2]\n start_bin1 = 0\n end_bin1 = chromsize1//resolution\n start_bin2 = 0\n end_bin2 = chromsize2//resolution\n \n n_bins_1 = end_bin1 - start_bin1 + 1#int(chromsize1 / resolution) + 1\n n_bins_2 = end_bin2 - start_bin2 + 1#int(chromsize2 / resolution) + 1\n \n bin1s = data.bin1//resolution - start_bin1#(data.bin1 / resolution).astype(int).values\n bin2s = data.bin2//resolution - start_bin2#(data.bin2 / resolution).astype(int).values\n values = data.value.values\n \n\n print(\"values=\")\n print(values.shape)\n\n\n print(\"bin1s=\")\n print(bin1s.shape)\n\n print(\"n_bins_1\")\n print(n_bins_1)\n\n\n print(\"bin2s=\")\n print(bin2s.shape)\n\n print(\"n_bins_2\")\n print(n_bins_2) \n \n \n m = coo_matrix( (values, (bin1s, bin2s)), shape=(n_bins_1, n_bins_2) )\n if chrom1 == chrom2:\n m = triu(m, k=1).T + m\n return m\n\n#expr_ds = None\n\n\nmatrix_file = \"GM12878_chr19_25kb_matrix_list.txt\"\ntad_file = \"select_TADs_to_plot_topdom.txt\"\n\nassert os.path.exists(matrix_file)\nassert os.path.exists(tad_file)\n\n#map_start = 2140000\n#map_end = 2960000\nmap_start = 1000000\nmap_end = 5000000\n\nresolution = 25000\n\n#myargs = sys.argv\n#if(len(myargs) == 5):\n# hic_ds = myargs[1]\n# expr_ds = myargs[2]\n# select_tad = myargs[3]\n# matrix_file = myargs[4]\n#elif(len(myargs) == 4):\n# hic_ds = myargs[1]\n# select_tad = myargs[2]\n# matrix_file = myargs[3]\n#else: \n# hic_ds = \"ENCSR489OCU_NCI-H460_40kb\"\n# expr_ds = \"TCGAlusc_norm_lusc\"\n# #matrix_file = \"mega_ENCSR489OCU_NCI-H460_mat_chr10_40kb_ob.txt\"\n# matrix_file = \"ENCSR489OCU-NCI-H460_10kb_chr10.txt\"\n# select_tad = \"chr10_TAD268\"\n# #matrix_file = \"mega_ENCSR489OCU_NCI-H460_mat_chr11_40kb_ob.txt\"\n# #select_tad = \"chr11_TAD390\"\n\n\nout_dir = os.path.join(\"PLOTHIC_WITHTADS_WITHCOLS\")\noutput_file = os.path.join(out_dir, \"plot_selected_tads_chr19_25kb\"+str(map_start)+\"_\"+str(map_end)+\".pdf\")\n\nchrom=\"chr19\"\n\n# SOME PARAMETERS FOR PLOTTING\nother_col_tad = \"black\"\nselect_col_tad = \"green\"\n#other_col_lab = \"black\"\n#select_col_lab = \"green\"\nnAround_toplot = 2\nnSurroundBins = 2\nshrink = 1\ntad_lwd = 1.2\nlab_offset = -0.8\nlabSize = 10 \nlabBox = True\naddGenes = True\ngeneSymbPos = \"right\" \ngenesOffset = 0.5\nsymbolOffset = 0.1\nwithBox = True\n \nif nAround_toplot == 0: \n geneSymbPos = \"above\" \n geneName_size = 8\n geneBar_height = 0.2\n genesSpacing = 0.5\n\nelif nAround_toplot == 2: \n geneName_size = 8\n geneBar_height = 1\n genesSpacing = 1.2\n\nelse : \n geneName_size = 8\n geneBar_height = 0.2\n \ngene_col = \"darkblue\"\ngene_lwd = 1\nplot_labs = True\nplotTit = \"GM12878_chr19_25kb 2140001-2960000 \"\n#if expr_ds:\n# plotTit += \" - \" + expr_ds\n\n#if addGenes:\n# assert expr_ds\n\n################################################################################################################################# PARAMETERS TO SET HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nsetDir = os.path.join(\"/media\", \"electron\")\nsetDir = os.path.join(\"/\")\n\n\n\n#################################################################################################################################\n\n\n\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n\n \ntad_dt = pd.read_csv(tad_file, sep=\"\\t\", header=None, names = ['chromo', 'start', 'end', \"region\"] )\n\n#select_idxs= tad_dt[tad_dt['region'] == select_tad].index\n#select_idxs= list(range(tad_dt.shape[0]))\n##assert len(select_idxs) == 1\n#select_idx = int(tad_dt[tad_dt['region'] == select_tad].index[0]) \n\n#chrom = tad_dt['chromo'][select_idx]\n#assert re.match(chrom, select_tad)\n\n#start_pos_list = list(tad_dt['start'][(select_idx-nAround_toplot):(select_idx+nAround_toplot+1)])\n#start_pos_list = list(tad_dt['start'][(select_idx-nAround_toplot):(select_idx+nAround_toplot+1)] - 1)\n#end_pos_list = list(tad_dt['end'][(select_idx-nAround_toplot):(select_idx+nAround_toplot+1)])\n#end_pos_list = list(tad_dt['end'][(select_idx-nAround_toplot):(select_idx+nAround_toplot+1)] + 1)\n\nstart_pos_list = list(tad_dt['start'] - 1)\nend_pos_list = list(tad_dt['end'])\n\n\n#lab_list = ([\"\"] * nAround_toplot) + [select_tad] + ([\"\"] * nAround_toplot)\nlab_list = (list(tad_dt['region']) )\ncol_list_tad = ([select_col_tad] *len(lab_list))\n#col_list_tad = ([other_col_tad] * nAround_toplot) + [select_col_tad] + ([other_col_tad] * nAround_toplot)\n#col_list_lab = ([other_col_lab] * nAround_toplot) + [select_col_lab] + ([other_col_lab] * nAround_toplot)\n\n\n#map_start = start_pos_list[0] - nSurroundBins*resolution\n#map_end = end_pos_list[len(end_pos_list)-1] + nSurroundBins*resolution\n\n\n\nassert len(start_pos_list) == len(end_pos_list) == len(lab_list) == len(col_list_tad)\n\ntad_toplot = [\n start_pos_list,\n end_pos_list,\n lab_list,\n col_list_tad\n]\n\nprint(tad_toplot)\n \n# LOAD AND SUBSET Hi-C DATA\n\n\ndata = pd.read_csv(matrix_file, sep=\"\\t\", header=None, names=['chromo', 'bin1', 'bin2', 'value'])\n\ndel data['chromo']\n\nprint(data.head())\n\ndata['bin1'] *= resolution\ndata['bin2'] *= resolution\n\nprint(data.head())\n\nassert all(list(data['bin1'] <= data['bin2']))\n\ndata = data[(data.bin1>=map_start) & (data.bin2<=map_end)]\nm = to_matrix(data, chrom, chrom, resolution, start1=map_start, end1=map_end, start2=map_start, end2=map_end)\n\n# retrieve the height of the plot (half-diagonal)\ndiagonal_height = np.sqrt(m.shape[0]**2 / 2)\n\nmy_map = plt.get_cmap(\"Reds\")\nmy_map.set_under('white')\nfig, ax = plt.subplots(1, 1, figsize=(10, 10))\nX = np.log10(np.triu(m.todense()*shrink) + 1)\nax.matshow( rotate(X, 45), cmap=my_map, vmin=0.01 )\n\nplt.ylim(diagonal_height)\n\nplt.xticks([])\nplt.yticks([])\nplt.axis('on')\n\nif not withBox:\n plt.box(on=None)\n\ntad_start=tad_toplot[0][0]\ntad_end= tad_toplot[1][0]\ntad_lab=tad_toplot[2][0]\ntad_col=tad_toplot[3][0]\n \nfor tad_start, tad_end , tad_lab, tad_col in zip(tad_toplot[0], tad_toplot[1], tad_toplot[2], tad_toplot[3]):\n\n tad_start_bin = (tad_start - map_start)//resolution \n tad_end_bin = (tad_end - map_start)//resolution\n\n conv_start = np.sqrt(2) * tad_start_bin # distance to bin start: on the side of the square, it is the # of bins but in triangle plot, it is the diagonal\n conv_end = np.sqrt(2) * tad_end_bin\n\n tad_height = diagonal_height-(conv_end-conv_start)*0.5 # needs the \"diagonal_heigh\" because the way it is plotted and the orientation of the y-axis\n \n tad_triangle = np.array([\n [conv_start,diagonal_height],\n [0.5*(conv_start+conv_end), tad_height],\n [conv_end, diagonal_height]\n ])\n\n print(tad_triangle)\n\n tadTri = plt.Polygon(tad_triangle, facecolor='none', edgecolor=tad_col, linewidth=tad_lwd)\n ax.add_patch(tadTri)\n\n if labBox:\n plt.text(0.5*(conv_start+conv_end),tad_height + lab_offset,tad_lab, fontsize=labSize, horizontalalignment='center', verticalalignment='bottom',\n bbox=dict(facecolor=tad_col, alpha=0.5), fontweight='bold')\n else:\n plt.text(0.5*(conv_start+conv_end),tad_height + lab_offset,tad_lab, fontsize=labSize, horizontalalignment='center', verticalalignment='bottom', fontweight='bold')\n \n \n\n\n# first_start = start_pos_list[0]\n# first_end = 0.5*( start_pos_list[0] + end_pos_list[len(end_pos_list)-1])\n# first_lab = \"FOO_FIRST_GENE\"\n# conv_gene_start = np.sqrt(2) * (first_start - map_start)/resolution\n# conv_gene_end = np.sqrt(2) * (first_end - map_start)/resolution\n# ax.add_patch(Rectangle((conv_gene_start, genePos), (conv_gene_end-conv_gene_start), height=0.2,\n# facecolor=gene_col, clip_on=False))\n# plt.text(0.5*(conv_gene_start+conv_gene_end), genePos-symbolOffset, first_lab, fontsize=8, horizontalalignment='center', verticalalignment='center')\n# genePos += genesSpacing\n\n#for i in range(tad_genes_symbols_dt.shape[0]):\n# conv_gene_start = np.sqrt(2) * (tad_genes_symbols_dt['start'][i] - map_start)/resolution\n# conv_gene_end = np.sqrt(2) * (tad_genes_symbols_dt['end'][i] - map_start)/resolution\n# \n# ax.add_patch(Rectangle((conv_gene_start, genePos), (conv_gene_end-conv_gene_start), height=geneBar_height, \n# facecolor=gene_col, clip_on=False))\n# \n## plt.hlines(y=genePos, xmin=conv_gene_start, xmax=conv_gene_end)\n## plt.hlines(y=genePos, xmin=map_start, xmax=map_end)\n# \n# ax.axhline(y=genePos, xmin=map_start, xmax=map_end, c = 'red')\n# plt.axhline(y=genePos)\n# plt.axhline(y=genePos+geneBar_height)\n# \n# symb_pos = 0.5*(genePos+geneBar_height + genePos)\n# \n# if geneSymbPos == \"above\":\n# plt.text(0.5*(conv_gene_start+conv_gene_end), genePos-symbolOffset,tad_genes_symbols_dt['symbol'][i], fontsize=geneName_size, horizontalalignment='center', verticalalignment='center')\n# elif geneSymbPos == \"right\":\n# plt.text(conv_gene_end, symb_pos,tad_genes_symbols_dt['symbol'][i], fontsize=geneName_size, horizontalalignment='left', verticalalignment='center')\n# elif geneSymbPos == \"left\":\n# plt.text(conv_gene_start, symb_pos,tad_genes_symbols_dt['symbol'][i], fontsize=geneName_size, horizontalalignment='right', verticalalignment='center')\n\n# genePos += genesSpacing\n \n \n# last_start = 0.5*( start_pos_list[0] + end_pos_list[len(end_pos_list)-1])\n# last_end = end_pos_list[len(end_pos_list)-1]\n# conv_gene_start = np.sqrt(2) * (last_start - map_start)/resolution\n# conv_gene_end = np.sqrt(2) * (last_end - map_start)/resolution\n# print(\"LAST\");print(conv_gene_start);print(genePos);print(conv_gene_end-conv_gene_start)\n# ax.add_patch(Rectangle((conv_gene_start, genePos), (conv_gene_end-conv_gene_start), height=0.2,\n# facecolor=gene_col, clip_on=False))\n# plt.text(0.5*(conv_gene_start+conv_gene_end), genePos-symbolOffset, last_lab, fontsize=8, horizontalalignment='center', verticalalignment='center')\n# genePos += genesSpacing\n \n \nplt.title(plotTit, fontweight=\"bold\") \n\nif output_file:\n\tplt.savefig(output_file, bbox_inches='tight',transparent=True)#, pad_inches=0)\n \n\tprint(\"... saved: \" + output_file + \"\\n\")\n \n","sub_path":"plotHiC_withTADs_withCols.py","file_name":"plotHiC_withTADs_withCols.py","file_ext":"py","file_size_in_byte":10942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"221601299","text":"################################################################################\r\n# MIT License\r\n#\r\n# Copyright (c) 2018\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to conditions.\r\n#\r\n# Author: Deep Learning Course | Fall 2018\r\n# Date Created: 2018-09-04\r\n################################################################################\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport math\r\n\r\n################################################################################\r\n\r\nclass VanillaRNN(nn.Module):\r\n\r\n def __init__(self, seq_length, input_dim, num_hidden, num_classes, batch_size, device='cpu'):\r\n super(VanillaRNN, self).__init__()\r\n # Initialization here ...\r\n\r\n self.seq_length = seq_length\r\n self.batch_size = batch_size\r\n self.input_dim = input_dim\r\n self.hidden_dim = num_hidden\r\n self.num_classes = num_classes\r\n\r\n if 'cuda' in device.lower() and torch.cuda.is_available():\r\n self.device = torch.device('cuda')\r\n else:\r\n self.device = torch.device('cpu')\r\n print(self.device)\r\n\r\n #Parameters\r\n self.w_hx = nn.Parameter( torch.randn(input_dim,num_hidden,device=self.device))\r\n self.w_hh = nn.Parameter( torch.rand(num_hidden,num_hidden,device=self.device))\r\n self.b_h = nn.Parameter( torch.rand(num_hidden,device=self.device)) #,1))\r\n self.w_ph = nn.Parameter( torch.randn(num_hidden,num_classes,device=self.device))\r\n self.b_p = nn.Parameter( torch.rand(num_classes,device=self.device)) #,1))\r\n\r\n #Initial h\r\n self.prev_h = torch.zeros(batch_size,num_hidden,device=self.device)\r\n\r\n #From NLP1: This is PyTorch's default initialization method\r\n stdv = 1.0 / math.sqrt(num_hidden)\r\n for weight in self.parameters():\r\n weight.data.uniform_(-stdv, stdv)\r\n\r\n\r\n def forward(self, x):\r\n # Implementation here ...\r\n #pass\r\n\r\n #Using self.prev_h directly resulted into error:\r\n #RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.\r\n prev_h = self.prev_h\r\n\r\n #For every timestep input in x\r\n for i in range(self.seq_length):\r\n single_x_batch = x[:,i]\r\n single_x_batch = single_x_batch.view((single_x_batch.shape[0],1))\r\n inside = single_x_batch @ self.w_hx + prev_h @ self.w_hh + self.b_h\r\n prev_h = torch.tanh(inside)\r\n\r\n #Only compute the cross-entropy for the last timestep, so only last output is needed\r\n p = prev_h @ self.w_ph + self.b_p\r\n\r\n\r\n return p","sub_path":"assignment_2/part1/vanilla_rnn.py","file_name":"vanilla_rnn.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"455255327","text":"from gensim.models.doc2vec import TaggedDocument\nfrom elasticsearch import Elasticsearch\nfrom lib.app_init import config\nimport glob\nimport re\n\nclass MecabTokenizer(object):\n\tdef __init__(self):\n\t\tself.tagger = MeCab.Tagger()\n\t\tself.jp_filter = re.compile(r'[㐀-䶵一-鿋豈-頻]|[ぁ-んァ-ン]')\n\n\tdef tokenize(self, sent):\n\t \n\t self.tagger.parse(\"\")\n\t graph = self.tagger.parseToNode(sent)\n\t words = []\n\t \n\t while graph:\n\t words.append(graph.surface)\n\t graph = graph.next\n\t filtered = [word for word in words if self.jp_filter.match(word)]\n\t return filtered\n\nclass KuromojiTokenizer(object):\n # def __init__(self):\n # self.es = Elasticsearch([config['elasticsearch']['url']],\n # verify_certs=False\n # )\n\n def tokenize(self, text):\n params = {\n 'analyzer': 'kuromoji',\n 'text': text\n }\n r = self.es.indices.analyze(body=params)\n tokens = [token['token'] for token in r['tokens']]\n return tokens\n\n def pos_tokenize(self, text):\n params = {\n 'analyzer': 'kuromoji',\n 'text': text,\n 'explain': True\n }\n r = self.es.indices.analyze(body=params)\n tokens = [token['token'] for token in r['detail']['analyzer']['tokens']]\n pos = [token['partOfSpeech'] for token in r['detail']['analyzer']['tokens']]\n return tokens, pos","sub_path":"nlu/lib/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"223484598","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 17 15:06:14 2020\r\n\r\n@author: pdavi\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nfrom imblearn.over_sampling import SMOTE # For Oversampling\r\nfrom sklearn.neural_network import *\r\n\r\ntrain = pd.read_csv('train.csv')\r\ntest = pd.read_csv('test.csv')\r\n\r\n\r\n#print(train.describe())\r\nX = train[train.columns[1:]].values\r\ny = np.vstack(train['label'].values)\r\n\r\n# print('\\n')\r\n# print('X and y Input Data: ', X.shape, y.shape)\r\n\r\n\r\nX_train, X_test2, y_train, y_test2 = train_test_split(X, y, test_size=0.3,\r\n random_state=42)\r\n\r\n# print('Training Set Shape: ', X_train_original.shape, y_train_original.shape)\r\n\r\nX_val, X_test, y_val, y_test = train_test_split(X_test2, y_test2, test_size=0.33,random_state=42)\r\n\r\n# print('Validation Set Shape: ', X_val.shape,y_val.shape)\r\n# print('Test Set Shape: ', X_test.shape, y_test.shape)\r\n\r\n#doOversampling = True\r\n\r\n# if doOversampling:\r\n# # Apply regular SMOTE\r\n# sm = SMOTE()\r\n# X_train, y_train = sm.fit_sample(X_train_original, y_train_original)\r\n# print('Training Set Shape after oversampling: ', X_train.shape, y_train.shape)\r\n# print(pd.crosstab(y_train,y_train))\r\n# else:\r\n# X_train = X_train_original\r\n# y_train = y_train_original\r\n\r\n\r\n#NN Classifier\r\nMLPClassifier(solver = 'adam', activation='relu', alpha=1e-04,\r\n batch_size='auto', beta_1=0.9, beta_2=0.999, early_stopping=False,\r\n epsilon=1e-08, hidden_layer_sizes=(100), learning_rate='adaptive',\r\n learning_rate_init=0.005, max_iter=2500, momentum=0.9,\r\n nesterovs_momentum=True, power_t=0.5, random_state=42, shuffle=True,\r\n tol=1e-05, validation_fraction=0.1, verbose=True,\r\n warm_start=True)\r\n\r\nclf_MLP = MLPClassifier(alpha=1e-05, hidden_layer_sizes=(64))\r\n\r\nclf_MLP.fit(X_train, y_train)\r\ny_pred_MLP = clf_MLP.predict(X_val)\r\n\r\nprint(' Accuracy of Model ')\r\nprint('--------------------------------')\r\nprint('Neural Network '+\"{:.2f}\".format(accuracy_score(y_val, y_pred_MLP)*100)+'%')\r\n\r\n#Confusion Matrices\r\n# print('Neural Network ')\r\n# cm_MLP = confusion_matrix(y_val,y_pred_MLP)\r\n# print(cm_MLP)\r\n# print('\\n')\r\n\r\n# y_test = y_test.reshape(-1)\r\n# y_train_original = y_train.reshape(-1)\r\n\r\n# y_pred_train_MLP = clf_MLP.predict(X_train)\r\n# y_pred_test_MLP = clf_MLP.predict(X_test)\r\n# cm_MLP_train = confusion_matrix(y_train_original,y_pred_train_MLP)\r\n# cm_MLP_test = confusion_matrix(y_test,y_pred_test_MLP)\r\n\r\n# print('Neural Network Classification Matrix ')\r\n# print('Training')\r\n# print(cm_MLP_train)\r\n# print('Validation')\r\n# print(cm_MLP)\r\n# print('Test')\r\n# print(cm_MLP_test)\r\n# print(\"\\n\")\r\n\r\nypred = clf_MLP.predict(test)\r\nimport csv\r\nchanges = []\r\nfor i in range(len(ypred)):\r\n changes.append((i+1,ypred[i])) \r\n \r\noutfile=open('digits1.csv','w', newline='')\r\nwriter=csv.writer(outfile)\r\nwriter.writerow([\"ImageId\", \"Label\"])\r\nwriter.writerows(changes)","sub_path":"numberClassifier.py","file_name":"numberClassifier.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"63516698","text":"obj=open('sample','r')\nc1=0\nc2=0\nc3=0\nfor line in obj:\n c1+=1\n wordslist=line.split()\n c2+=len(wordslist)\n c3+=len(line)\nprint(c1)\nprint(c2)\nprint(c3)\n","sub_path":"7-8(am)/all folders/practice/PYTHON/practice/filehandling/read3.py","file_name":"read3.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"642601396","text":"#!/usr/bin/python\n\nimport matplotlib.pyplot as plt\nfrom urllib.parse import unquote_plus\nimport sys\n\n### Read load test results into memory.\n\nf = open(sys.argv[1], \"r\")\nnext(f)\n# lines = filter(lambda l: len(l.split(',')) == 7, f.readlines())\n# lines = f.readlines()\n# f.close()\n\n### Extract response times.\nresponses = [(i, *l.strip().split(',')) for i, l in enumerate(f)]\n# path,method,num_requests,num_failures,min_response_time,max_response_time,avg_response_time\n# response_times = [(i, len(unquote_plus(l.strip().split(',')[0].replace('/detect+lang/', ''))),int(l.strip().split(',')[-1])) for i, l in enumerate(f)]\n\n### Plot the graph.\n\n# request_id = [l[0] for l in response_times]\nrequest_length = [len(unquote_plus(l[1].replace('/detect_lang/', ''))) for l in responses]\nnum_requests = [int(l[3]) for l in responses]\nnum_fails = [int(l[4]) for l in responses]\nmin_response_time = min([int(l[5]) for l in responses])\nmax_response_time = max([int(l[6]) for l in responses])\n#fail_rate = [float(l[4])/float(l[3]) for l in responses]\nresponse_time = [int(l[-1]) for l in responses]\n\nf.close()\nprint('Average response time - all requests and RPS')\navg_r_t = sum(response_time)/sum(num_requests)\nprint(avg_r_t, 1/(avg_r_t/1000))\nprint()\nprint('Average response time - successful requests and RPS')\navg_s_r_t = sum(response_time)/(sum(num_requests)-sum(num_fails))\nprint(avg_s_r_t, 1/(avg_s_r_t/1000))\nprint()\nprint('min, max response time')\nprint(min_response_time, max_response_time)\nprint()\nprint('Fail rate')\nprint(sum(num_fails)/sum(num_requests))\n\ngraph = plt.figure(1)\nplt.scatter(request_length, response_time)\nplt.savefig(sys.argv[1].strip(\".csv\")+\".png\", dpi=300)\n\n","sub_path":"loadtest/show_response_times.py","file_name":"show_response_times.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"365973379","text":"# coding:utf-8\n\"\"\"\n Purpose: Simple CNN and Scatt+CNN models\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom kymatio import Scattering2D\n\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conva = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, padding=1, stride=2)\n self.convb = nn.Conv2d(in_channels=64, out_channels=81, kernel_size=3, padding=1, stride=2)\n\n self.conv1 = nn.Conv2d(in_channels=81, out_channels=64, kernel_size=3, padding=1)\n self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1)\n self.fc1 = nn.Linear(in_features=64, out_features=10)\n\n def forward(self, x):\n x = self.conva(x)\n x = F.relu(x)\n x = self.convb(x)\n x = F.relu(x)\n\n # Common base\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.adaptive_avg_pool2d(x, (1, 1))\n x = x.view(-1, 64)\n x = self.fc1(x)\n return x\n\n\nclass ScattCNN(nn.Module):\n def __init__(self, input_shape=(28, 28), J=2, L=8):\n super(ScattCNN, self).__init__()\n\n self.scattering = Scattering2D(J=J, shape=input_shape)\n if torch.cuda.is_available():\n print(\"Move scattering to GPU\")\n self.scattering = self.scattering.cuda()\n self.K = 1 + J * L + L ** 2 * (J - 1) * J // 2\n self.scatt_output_shape = tuple([x // 2 ** J for x in input_shape])\n self.bn = nn.BatchNorm2d(self.K)\n self.conv = nn.Conv2d(in_channels=self.K, out_channels=self.K, kernel_size=3, padding=1)\n\n self.conv1 = nn.Conv2d(in_channels=self.K, out_channels=64, kernel_size=3, padding=1)\n self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1)\n self.fc1 = nn.Linear(in_features=64, out_features=10)\n\n def forward(self, x):\n x = self.scattering(x)\n x = x.view(-1, self.K, *self.scatt_output_shape)\n x = self.bn(x)\n x = self.conv(x)\n x = F.relu(x)\n\n # Common base\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.relu(x)\n x = F.adaptive_avg_pool2d(x, (1, 1))\n x = x.view(-1, 64)\n x = self.fc1(x)\n return x\n\n\nif __name__ == '__main__':\n from torchsummary import summary\n\n print(\"CNN only model:\")\n model = CNN().to(\"cuda\")\n summary(model, input_size=(1, 28, 28))\n print(\"\")\n print(\"Scatt + CNN model:\")\n model = ScattCNN().to(\"cuda\")\n summary(model, input_size=(1, 28, 28))\n","sub_path":"Python/different_dataset_sizes/models/simple_model.py","file_name":"simple_model.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"440548655","text":"import torch\nfrom torchvision import datasets, transforms\nimport torch.utils.data.sampler as sampler\nimport torch.utils.data as data\nimport torch.backends.cudnn as cudnn\n\nimport numpy as np\nimport argparse\nimport random\nimport os\n\nfrom custom_datasets import *\nimport model\nimport vgg\nimport resnet\nfrom solver import Solver\nfrom utils import *\nimport arguments\n\n\ndef cifar_transformer():\n return transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.5, 0.5, 0.5,],\n std=[0.5, 0.5, 0.5]),\n ])\n\ndef main(args):\n if args.dataset == 'cifar10':\n test_dataloader = data.DataLoader(\n datasets.CIFAR10(args.data_path, download=True, transform=cifar_transformer(), train=False),\n batch_size=args.batch_size, drop_last=False)\n\n # train_dataset = CIFAR10(args.data_path)\n querry_dataloader = data.DataLoader(\n CIFAR10(args.data_path),\n batch_size=args.batch_size, drop_last=True)\n args.num_images = 50000\n # args.num_val = 5000\n # args.budget = 2500\n # args.initial_budget = 5000\n args.num_classes = 10\n elif args.dataset == 'cifar100':\n test_dataloader = data.DataLoader(\n datasets.CIFAR100(args.data_path, download=True, transform=cifar_transformer(), train=False),\n batch_size=args.batch_size, drop_last=False)\n\n train_dataset = CIFAR100(args.data_path)\n querry_dataloader = data.DataLoader(\n CIFAR100(args.data_path),\n batch_size=args.batch_size, shuffle=True, drop_last=True)\n\n args.num_val = 5000\n args.num_images = 50000\n args.budget = 2500\n args.initial_budget = 5000\n args.num_classes = 100\n \n elif args.dataset == 'tinyimagenet':\n test_dataloader = data.DataLoader(\n TinyImageNet(args.data_path, transform=tinyimagenet_transform(), train=False),\n batch_size=args.batch_size, drop_last=False)\n \n querry_dataloader = data.DataLoader(\n TinyImageNet(args.data_path, transform=tinyimagenet_transform(), train=True),\n shuffle=True, batch_size=args.batch_size, drop_last=True)\n args.num_classes = 200\n args.num_images = 100000\n\n\n elif args.dataset == 'imagenet':\n test_dataloader = data.DataLoader(\n datasets.ImageFolder(args.data_path, transform=imagenet_transformer()),\n drop_last=False, batch_size=args.batch_size)\n\n train_dataset = ImageNet(args.data_path)\n\n args.num_val = 128120\n args.num_images = 1281167\n args.budget = 64060\n args.initial_budget = 128120\n args.num_classes = 1000\n else:\n raise NotImplementedError\n\n args.cuda = torch.cuda.is_available()\n\n # all_indices = set(np.arange(args.num_images))\n # val_indices = random.sample(all_indices, args.num_val)\n # all_indices = np.setdiff1d(list(all_indices), val_indices)\n\n # initial_indices = random.sample(list(all_indices), args.initial_budget)\n # sampler = data.sampler.SubsetRandomSampler(initial_indices)\n # sampler = data.sampler.SubsetRandomSampler(list(all_indices))\n # val_sampler = data.sampler.SubsetRandomSampler(val_indices)\n\n # dataset with labels available\n # querry_dataloader = data.DataLoader(train_dataset, sampler=sampler, \n # batch_size=args.batch_size, drop_last=True)\n # val_dataloader = data.DataLoader(train_dataset, sampler=val_sampler,\n # batch_size=args.batch_size, drop_last=False)\n val_dataloader = None\n \n args.cuda = args.cuda and torch.cuda.is_available()\n solver = Solver(args, test_dataloader)\n\n # splits = [0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]\n splits = [1.]\n\n # current_indices = list(initial_indices)\n\n # accuracies = []\n \n print('==> Building models...')\n\n # task_model = vgg.vgg16_bn(num_classes=args.num_classes)\n task_model = resnet.ResNet34(num_classes=args.num_classes)\n # task_model = model.Approximator(args.latent_dim, args.num_classes)\n vae = model.VAE(args.latent_dim)\n discriminator = model.Discriminator(args.latent_dim)\n\n if args.cuda:\n vae = vae.cuda()\n discriminator = discriminator.cuda()\n task_model = task_model.cuda()\n vae = torch.nn.DataParallel(vae)\n discriminator = torch.nn.DataParallel(discriminator)\n task_model = torch.nn.DataParallel(task_model)\n\n\n for epoch in range(args.train_epochs):\n \n # unlabeled_indices = np.setdiff1d(list(all_indices), current_indices)\n # unlabeled_sampler = data.sampler.SubsetRandomSampler(unlabeled_indices)\n # unlabeled_dataloader = data.DataLoader(train_dataset, \n # sampler=unlabeled_sampler, batch_size=args.batch_size, drop_last=False)\n unlabeled_dataloader = None\n print('\\nEpoch: %d' % epoch)\n # train the models on the current data\n acc, vae, discriminator, task_model = solver.train(epoch,\n querry_dataloader,\n val_dataloader,\n task_model, \n vae, \n discriminator,\n unlabeled_dataloader)\n\n\n # print('Final accuracy with {}% of data is: {:.2f}'.format(int(split*100), acc))\n # accuracies.append(acc)\n\n # sampled_indices = solver.sample_for_labeling(vae, discriminator, unlabeled_dataloader)\n # current_indices = list(current_indices) + list(sampled_indices)\n # sampler = data.sampler.SubsetRandomSampler(current_indices)\n # querry_dataloader = data.DataLoader(train_dataset, sampler=sampler, \n # batch_size=args.batch_size, drop_last=True)\n\n # torch.save(accuracies, os.path.join(args.out_path, args.log_name))\n\nif __name__ == '__main__':\n args = arguments.get_args()\n main(args)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"115148965","text":"import json\nimport os\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom scl_scrapper.models import CBTNuggets\n\n\nclass Command(BaseCommand):\n\n def handle(self, *args, **options):\n\n CBTNuggets.objects.all().delete()\n\n cbt = CBTNuggets.objects.create()\n with open(os.path.join(settings.SCRAPPED_DATA_DIR, 'cbtnuggets', 'courses.json')) as f:\n data = json.load(f)\n cbt.courses = data\n cbt.save()\n\n with open(os.path.join(settings.SCRAPPED_DATA_DIR, 'cbtnuggets', 'syllabus.json')) as f:\n data = json.load(f)\n cbt.syllabus = data\n cbt.save()\n\n\n","sub_path":"db/scl/scl_scrapper/management/commands/write_cbt_nuggets_to_db.py","file_name":"write_cbt_nuggets_to_db.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"486724984","text":"from confusable_homoglyphs import confusables\n\ndef is_valid_int(char):\n try:\n return isinstance(int(char), int)\n except:\n return False\n\ndef string_coerce(string):\n #do initial test for safety\n test = bool(confusables.is_confusable(string, preferred_aliases=['latin', 'common']))\n\n if not test:\n return string\n\n string_chars = []\n for char in string:\n aliases = confusables.is_confusable(char, greedy=False, preferred_aliases=[], allow_digit=False)\n string_chars += aliases\n\n coerced = []\n for char in string_chars:\n if char['alias'] == 'LATIN':\n coerced.append(char['character'])\n\n elif is_valid_int(char):\n coerced.append(char['character'])\n\n else:\n for homoglyph in char['homoglyphs']:\n if homoglyph['n'].startswith('LATIN') or homoglyph['n'].startswith('DIGIT'):\n coerced.append(homoglyph['c'])\n break\n\n return ''.join(coerced)\n\nif __name__ == '__main__':\n test_strings = (\n '𐌚chan', #unsafe\n '8chan', #safe\n 'уolo', #unsafe\n 'Κiller Quеen', #unsafe\n 'This is a safe sentence.', #safe\n \"It'ѕ lit yo\" #unsafe\n )\n\n for string in test_strings:\n #handle sentences by checking each word individually\n words = string.split(' ')\n result = \"\"\n\n for word in words:\n result += ' {}'.format(string_coerce(word))\n\n result = result.strip()\n\n test_original = bool(confusables.is_confusable(string, preferred_aliases=['latin', 'common']))\n\n print('Original is unsafe: {}'.format(str(test_original)))\n print('{} -> {}'.format(string, result))\n test_new = bool(confusables.is_confusable(result, preferred_aliases=['latin', 'common']))\n print('Coersion is unsafe: {}\\n'.format(str(test_new)))\n","sub_path":"coerce_string.py","file_name":"coerce_string.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"189659600","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Net(nn.Module):\n def __init__(self, action_dim):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=2)\n self.bn1 = nn.BatchNorm2d(32)\n self.conv2 = nn.Conv2d(32, 64, kernel_size=5, stride=2, padding=2)\n self.bn2 = nn.BatchNorm2d(64)\n self.conv3 = nn.Conv2d(64, 32, kernel_size=5, stride=1, padding=2)\n self.bn3 = nn.BatchNorm2d(32)\n self.fc_1 = nn.Linear(25 * 25 * 32, 512)\n self.fc_2 = nn.Linear(512, action_dim)\n\n def forward(self, state):\n s_1 = F.relu(self.bn1(self.conv1(state)))\n s_2 = F.relu(self.bn2(self.conv2(s_1)))\n s_3 = F.relu(self.bn3(self.conv3(s_2)))\n s_4 = F.relu(self.fc_1(s_3.view(s_3.size(0), -1)))\n action = self.fc_2(s_4.view(s_4.size(0), -1))\n\n return action","sub_path":"4つ色テスト2/Net.py","file_name":"Net.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"263176117","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n +---------------+\n+----+ camtest.py +--------------------+\n| +---------------+ | \n| |\n+-----------------------------------------+\n\"\"\"\n \nimport sys, os, time\nsys.path.append('/usr/local/lib/python2.4/site-packages/libavg')\nimport avg\n\n# AVG globale Variablen\nlog = avg.Logger.get()\npl = avg.Player() # thePlayer\ncam = avg.Camera() # theCamera\navgFile = \"camera_test.avg\"\n\npl.setDisplayEngine(avg.OGL)\npl.setResolution(0,1280,1024,24)\npl.showCursor(1) \npl.loadFile(avgFile)\n\npl.play()\npl.getElementByID('camera').play\n","sub_path":"src/camtest.py","file_name":"camtest.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"317303337","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport skimage\nimport utils\n\ndef magnitude(fft_im):\n real = fft_im.real\n imag = fft_im.imag\n return np.sqrt(real**2 + imag**2)\n\ndef convolve_im(im: np.array,\n kernel: np.array,\n verbose=True):\n \"\"\" Convolves the image (im) with the spatial kernel (kernel),\n and returns the resulting image.\n\n \"verbose\" can be used for turning on/off visualization\n convolution\n\n Note: kernel can be of different shape than im.\n\n Args:\n im: np.array of shape [H, W]\n kernel: np.array of shape [K, K] \n verbose: bool\n Returns:\n im: np.array of shape [H, W]\n \"\"\"\n # START YOUR CODE HERE ### (You can change anything inside this block)\n\n #since kernel might be of different shape than the image\n #we need to pad with the difference\n x_pad = len(im[1])-len(kernel[1])\n y_pad = len(im[0])-len(kernel[0])\n kernel = np.pad(kernel, ((0, y_pad), (x_pad, 0)), 'constant', constant_values=(0,0))\n\n #apply fft to both the kernel and image\n im_fourier = np.fft.fft2(im)\n kernel_fourier = np.fft.fft2(kernel)\n #use the convolution theorem\n conved_im_fourier = im_fourier * kernel_fourier\n\n #shift DC component to center and apply log transform for visualization\n viz_kernel_fft = np.fft.fftshift(np.log(magnitude(kernel_fourier)+1))\n viz_im = np.fft.fftshift(np.log(magnitude(im_fourier)+1))\n viz_im_conved = np.fft.fftshift(np.log(magnitude(conved_im_fourier)+1))\n\n #shift back to spatial domain with inverse fft\n conv_result = np.fft.ifft2(conved_im_fourier).real\n\n if verbose:\n # Use plt.subplot to place two or more images beside eachother\n plt.figure(figsize=(20, 4))\n # plt.subplot(num_rows, num_cols, position (1-indexed))\n plt.subplot(1, 5, 1)\n plt.imshow(im, cmap=\"gray\")\n plt.subplot(1, 5, 2)\n # Visualize FFT\n plt.imshow(viz_im, cmap=\"gray\")\n plt.subplot(1, 5, 3)\n # Visualize FFT kernel\n plt.imshow(viz_kernel_fft, cmap=\"gray\")\n plt.subplot(1, 5, 4)\n # Visualize filtered FFT image\n plt.imshow(viz_im_conved, cmap=\"gray\")\n plt.subplot(1, 5, 5)\n # Visualize filtered spatial image\n plt.imshow(conv_result, cmap=\"gray\")\n\n ### END YOUR CODE HERE ###\n return conv_result\n\n\nif __name__ == \"__main__\":\n verbose = True # change if you want\n\n # Changing this code should not be needed\n im = skimage.data.camera()\n im = utils.uint8_to_float(im)\n\n # DO NOT CHANGE\n gaussian_kernel = np.array([\n [1, 4, 6, 4, 1],\n [4, 16, 24, 16, 4],\n [6, 24, 36, 24, 6],\n [4, 16, 24, 16, 4],\n [1, 4, 6, 4, 1],\n ]) / 256\n image_gaussian = convolve_im(im, gaussian_kernel, verbose)\n\n # DO NOT CHANGE\n sobel_horizontal = np.array([\n [-1, 0, 1],\n [-2, 0, 2],\n [-1, 0, 1]\n ])\n image_sobelx = convolve_im(im, sobel_horizontal, verbose)\n\n if verbose:\n plt.show()\n\n utils.save_im(\"camera_gaussian.png\", image_gaussian)\n utils.save_im(\"camera_sobelx.png\", image_sobelx)\n","sub_path":"assignment2/task4b.py","file_name":"task4b.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"105906310","text":"\"\"\"\nContains possible interactions with the Galaxy Datasets\n\"\"\"\nfrom bioblend.galaxy.client import Client\nimport shutil\nimport urllib2\nimport os\nimport time\nimport logging\n\nlog = logging.getLogger(__name__)\n\nclass DatasetClient(Client):\n def __init__(self, galaxy_instance):\n self.module = 'datasets'\n super(DatasetClient, self).__init__(galaxy_instance)\n\n def show_dataset(self, dataset_id, deleted=False):\n \"\"\"\n Display information about and/or content of a dataset. This can be a\n history or a library dataset.\n \"\"\"\n return Client._get(self, id=dataset_id, deleted=deleted)\n\n def download_dataset(self, dataset_id, file_path=None, use_default_filename=True, wait_for_completion=False, maxwait=12000):\n \"\"\"\n Downloads the dataset identified by 'id'.\n\n :type dataset_id: string\n :param dataset_id: Encoded Dataset ID\n\n :type file_path: string\n :param file_path: If the file_path argument is provided, the dataset will be streamed to disk\n at that path (Should not contain filename if use_default_name=True).\n If the file_path argument is not provided, the dataset content is loaded into memory\n and returned by the method (Memory consumption may be heavy as the entire file\n will be in memory).\n\n :type use_default_name: boolean\n :param use_default_name: If the use_default_name parameter is True, the exported\n file will be saved as file_local_path/%s,\n where %s is the dataset name.\n If use_default_name is False, file_local_path is assumed to\n contain the full file path including filename.\n\n :type wait_for_completion: boolean\n :param wait_for_completion: If wait_for_completion is True, this call will block till the dataset is ready.\n If the dataset state becomes invalid, a DatasetStateException will be thrown.\n\n :type maxwait: float\n :param maxwait: Time (in seconds) to wait for dataset to complete.\n If the dataset state is not complete within this time, a DatasetTimeoutException will be thrown.\n\n :rtype: dict\n :return: If a file_path argument is not provided, returns a dict containing the file_content.\n Otherwise returns nothing.\n \"\"\"\n if wait_for_completion:\n self._block_until_dataset_ready(dataset_id, maxwait=maxwait)\n\n dataset = self.show_dataset(dataset_id)\n if not dataset['state'] == 'ok':\n raise DatasetStateException(\"Dataset not ready. Dataset id: %s, current state: %s\" % (dataset_id, dataset['state']))\n\n # Append the dataset_id to the base history contents URL\n url = '/'.join([self.gi.base_url, dataset['download_url']])\n if file_path is None:\n r = self.gi.make_get_request(url)\n return r.content\n else:\n req = urllib2.urlopen(url)\n\n if use_default_filename:\n file_local_path = os.path.join(file_path, dataset['name'])\n else:\n file_local_path = file_path\n\n with open(file_local_path, 'wb') as fp:\n shutil.copyfileobj(req, fp)\n\n def _is_dataset_complete(self, dataset_id):\n dataset = self.show_dataset(dataset_id)\n state = dataset['state']\n return (state == 'ok' or state == 'error')\n\n def _block_until_dataset_ready(self, dataset_id, maxwait=12000, interval=30, raise_on_timeout=True):\n \"\"\"\n Wait until the dataset state changes to ok or error.\n Based on: https://github.com/salimfadhley/jenkinsapi/blob/master/jenkinsapi/api.py\n \"\"\"\n assert maxwait > 0\n assert maxwait > interval\n assert interval > 0\n\n for time_left in xrange(maxwait, 0, -interval):\n if self._is_dataset_complete(dataset_id):\n return\n log.warn( \"Waiting for dataset %s to complete. Will wait another %is\" % (dataset_id, time_left))\n time.sleep(interval)\n if raise_on_timeout:\n #noinspection PyUnboundLocalVariable\n raise DatasetTimeoutException(\"Waited too long for dataset to complete: %s\" % dataset_id)\n\nclass DatasetStateException(Exception):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\nclass DatasetTimeoutException(Exception):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return repr(self.value)\n","sub_path":"bioblend/galaxy/datasets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"594443292","text":"\"\"\"Identify windows with very high depth for potential filtering.\n\nIn non-targeted experiments, high depth regions are often due to collapsed repeats\nor other structure which can create long run times and incorrect results in\nsmall and structural variant calling.\n\"\"\"\nimport os\nimport sys\n\nimport yaml\n\nfrom bcbio import utils\nfrom bcbio.pipeline import datadict as dd\nfrom bcbio.variation import bedutils\n\ndef _get_files(data):\n work_bam = dd.get_align_bam(data) or dd.get_work_bam(data)\n out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), \"align\", dd.get_sample_name(data)))\n out_file = \"%s-highdepth.bed\" % os.path.join(out_dir, utils.splitext_plus(os.path.basename(work_bam))[0])\n stats_file = \"%s-stats.yaml\" % utils.splitext_plus(out_file)[0]\n return work_bam, out_file, stats_file\n\ndef combine_file_rename(x):\n return x.replace(\"-callable.bed\", \"-highdepth.bed\")\n\ndef combine_callable_bed(in_files, out_file, config):\n bedutils.combine(filter(lambda x: utils.file_exists(x), [combine_file_rename(x) for x in in_files]),\n combine_file_rename(out_file), config)\n callable_bed = bedutils.combine(in_files, out_file, config)\n return callable_bed\n\ndef bin_depths(min_cov, max_cov, window_size, callable_out, highdepth_out):\n \"\"\"Provide bins of covered regions, including a separate file of high depth regions.\n \"\"\"\n last = (None, None)\n last_window = -1\n depth_cache = []\n cache = []\n\n def mean(vals):\n return sum(vals) / float(window_size)\n\n with open(callable_out, \"w\") as callable_handle:\n with open(highdepth_out, \"w\") as highdepth_handle:\n for chrom, pos, depth in (l.rstrip(\"\\r\\n\").split(\"\\t\", 3) for l in sys.stdin):\n depth, pos = int(depth), int(pos)\n if pos / window_size != last_window:\n if mean(depth_cache) > max_cov:\n highdepth_handle.write(\"%s\\t%d\\t%d\\t%.2f\\n\" %\n (chrom, last_window * window_size,\n last_window * window_size + window_size, mean(depth_cache)))\n depth_cache = depth_cache[:0]\n last_window = pos / window_size\n depth_cache.append(depth)\n\n key = (chrom, \"NO_COVERAGE\" if depth == 0 else \"LOW_COVERAGE\" if depth < min_cov else \"CALLABLE\")\n if key != last or pos != cache[-1][1] + 1:\n if last[0] is not None:\n callable_handle.write(\"\\t\".join((last[0], str(int(cache[0][1]) - 1),\n str(cache[-1][1]), last[1])) + \"\\n\")\n last = key\n cache = cache[:0]\n cache.append((chrom, pos, depth))\n if cache:\n callable_handle.write(\"\\t\".join((chrom, str(int(cache[0][1]) - 1),\n str(cache[-1][1]), last[1])) + \"\\n\")\n\ndef get_stats_file(data):\n return _get_files(data)[-1]\n\ndef get_median_coverage(data):\n stats_file = get_stats_file(data)\n if not utils.file_exists(stats_file):\n return 0\n else:\n with open(stats_file) as in_handle:\n stats = yaml.safe_load(in_handle)\n return stats[\"median_cov\"]\n","sub_path":"bcbio/bam/highdepth.py","file_name":"highdepth.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"571278317","text":"# encoding: utf-8\n# !/usr/bin/python\nimport cv2\nimport glob\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# 设置终止条件\ncrireria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 0.001)\n\n# 做一些3D点\nobjp = np.zeros((6 * 7, 3), np.float32)\nobjp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)\nprint(objp)\nobjpoints = []\nimgpoints = []\n\nimages = glob.glob('../resource/calibra/*')\nfor fname in images:\n img = cv2.imread(fname)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, (7, 6), None)\n\n if ret == True:\n # 画出亚像素精度角点\n objpoints.append(objp)\n corners2 = cv2.cornerSubPix(gray, corners, (7, 6), (-1, -1), crireria)\n imgpoints.append(corners2)\n cv2.drawChessboardCorners(img, (7, 6), corners2, ret)\n\n # 标定\n # Size imageSize, 在计算相机内部参数和畸变矩阵需要\n # cameraMatrix 为内部参数矩阵, 输入一个cvMat\n # distCoeffs为畸变矩阵.\n # 我们要使用的函数是 cv2.calibrateCamera()。它会返回摄像机矩阵,畸变系数,旋转和变换向量等。\n # mtx内参矩阵, dist畸变系数, rvecs旋转向量,外餐 tvecs平移向量,内参\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape, None, None)\n\n print(fname, \"rvecs\", rvecs)\n cv2.imshow('img', img)\n cv2.waitKey(100)\n\n k = cv2.waitKey(500) & 0xff\n h, w = img.shape[:2]\n\n # 畸变矫正\n # 如果缩放系数 alpha = 0,返回的非畸变图像会带有最少量的不想要的像素。\n # 它甚至有可能在图像角点去除一些像素。如果 alpha = 1,所有的像素都会被返回,\n # 还有一些黑图像。它还会返回一个 ROI 图像,我们可以用来对结果进行裁剪。\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h)) # roi只是一个元组\n x, y, w, h = roi\n print(roi)\n\n # 去除畸变\n if k == ord('q'):\n # undistort\n dst = cv2.undistort(img, mtx, dist, newCameraMatrix=newcameramtx)\n dst = dst[y:y + h, x:x + w]\n cv2.imshow('undistortimg', dst)\n cv2.waitKey(100)\n else:\n # remapping。先找到畸变到非畸变的映射方程,再用重映射方程\n mapx, mapy = cv2.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w, h), 5)\n dst = cv2.remap(img, mapx, mapy, cv2.INTER_LINEAR)\n # dst = dst[y:y+h, x:x+w] #你可以试试注释这一步\n cv2.imshow('undistortimg ', dst)\n cv2.waitKey(100)\n\n # 我们可以用反向投影对我们找到的参数的准确性评估,结果约接近0越好\n # 有了内部参数:畸变参数和旋转变换矩阵,我们可以用cv2.projectPoints()去\n # 把对象点转换到图像点,然后就可以计算变换得到图像与角点检测算法的绝对差了。\n # 然后我们计算所有标定图像的误差平均值。\n mean_error = 0\n for i in range(len(objpoints)):\n imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)\n error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2) / len(imgpoints2)\n mean_error += error\n print(\"total error: \", mean_error / len(objpoints))\n","sub_path":"camera/camera_cal2.py","file_name":"camera_cal2.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"404633901","text":"import re #libreria de expresiones regulares\n\npath =\"Codigo.js\"\n\ntry:\n archivo=open(path, 'r')\nexcept:\n print(\"El archivo que intentas abrir no existe\")\n quit()\n\ntexto=\"\"\n\nfor linea in archivo:\n texto+=linea\n\n\nexp1=re.compile('[a-zA-Z][\\w\\d]*')\nresult1=exp1.findall(texto)\n\nexp2=r\"\\bconsole\\b|\\blog\\b|\\blet\\b|\\bvar\\b|\\bconst\\b|\\bpush\\b|\\bpop\\b|\\bunshift\\b|\\bshift\\b|\\bslice\\b|\\bsplice\\b|\\breverse\\b|\\bsplit\\b|\\bjoin\\b|\\bsort\\b|\\bindexOf\\b|\\bfindIndex\\b|\\bfind\\b|\\bnew\\b|\\bSet\\b|\\bof\\b|\\bforEach\\b|\\bsome\\b|\\bevery\\b|\\blenght\\b|\\bmap\\b|\\bfilter\\b|\\breduce\\b|\\btoFixed\\b|\\bparseInt\\b|\\bparseFloat\\b|\\bMath.random\\b|\\bthis\\b|\\bdelete\\b|\\bObject.getPrototypeOf\\b|\\bObject.assign\\b|\\bString.prototype\\b|\\bhasOwnProperty\\b|\\blegs\\b|\\blastIndex\\b|\\bincludes\\b|\\bstartsWith\\b|\\bendsWith\\b|\\breplace\\b|\\bsubstr\\b|\\breturn\\b|\\bprompt\\b|\\balert\\b|\\bArray\\b|\\bbreak\\b|\\bcase\\b|\\bcatch\\b|\\bclass\\b|\\bdefault\\b|\\bdo\\b|\\belse\\b|\\belseif\\b|\\bendsswitch\\b|\\beval\\b|\\bextends\\b|\\bfor\\b|\\bfunction\\b|\\bif\\b|\\bimplements\\b|\\binclude\\b|\\binstanceof\\b|\\binterface\\b|\\bprint\\b|\\bprivate\\b|\\bprotected\\b|\\bpublic\\b|\\brequire\\b|\\bstatic\\b|\\bswitch\\b|\\bthrow\\b|\\btry\\b|\\buse\\b|\\bwhile\\b|\\btrue\\b|\\bfalse\\b\"\nresult2=re.findall(exp2, texto)\n\nexp3=re.compile('\\d*\\.?\\d+')\nresult3=exp3.findall(texto)\n\nexp4=re.compile('\\*\\*|--|\\+\\+|\\+=|-=|/=|\\%|\\+|-|\\*|/|=')\nresult4=exp4.findall(texto)\n\nexp5=re.compile('<|<=|>|>=|==|!=')\nresult5=exp5.findall(texto)\n\nfor i in result1:\n if(i!=\"console\" and i!=\"log\" and i!=\"let\" and i!=\"var\" and i!=\"const\" and i!=\"push\" and i!=\"pop\" and i!=\"unshift\" and i!=\"shift\" and i!=\"slice\" and i!=\"splice\" and i!=\"reverse\" and i!=\"split\" and i!=\"join\" and i!=\"sort\" and i!=\"indexOf\" and i!=\"findIndex\" and i!=\"find\" and i!=\"new\" and i!=\"Set\"\n and i!=\"of\" and i!=\"forEach\" and i!=\"some\" and i!=\"every\" and i!=\"lenght\" and i!=\"map\" and i!=\"filter\" and i!=\"reduce\" and i!=\"toFixed\" and i!=\"parseInt\" and i!=\"parseFloat\"\n and i!=\"Math.random\" and i!=\"this\" and i!=\"delete\" and i!=\"Object.getPrototypeOf\" and i!=\"Object.assign\" and i!=\"String.prototype\" and i!=\"hasOwnProperty\" and i!=\"legs\" and i!=\"lastIndex\" and i!=\"includes\" and i!=\"startsWith\" and i!=\"endsWith\"\n and i!=\"replace\" and i!=\"substr\" and i!=\"return\" and i!=\"prompt\" and i!=\"alert\" and i!=\"Array\" and i!=\"break\" and i!=\"case\" and i!=\"catch\" and i!=\"class\" and i!=\"default\" and i!=\"do\" and i!=\"else\" and i!=\"elseif\"\n and i!=\"endsswitch\" and i!=\"eval\" and i!=\"extends\" and i!=\"for\" and i!=\"function\" and i!=\"if\" and i!=\"implements\" and i!=\"include\" and i!=\"instanceof\" and i!=\"interface\" and i!=\"print\"\n and i!=\"private\" and i!=\"protected\" and i!=\"public\" and i!=\"require\" and i!=\"static\" and i!=\"switch\" and i!=\"throw\" and i!=\"try\" and i!=\"use\" and i!=\"while\" and i!=\"true\" and i!=\"false\"):\n print(\"Identificador: \"+i)\n\n\nfor j in result2:\n print(\"Palabras reservadas: \"+j)\n\nfor j in result3:\n print(\"Números: \"+j)\n \n \n\nfor k in result4:\n print(\"Operadores aritméticos: \"+k)\n\n\nfor l in result5:\n print(\"Operadores relacionales: \"+l)\n\n\n\n\n","sub_path":"Ejercicios_Unidad4_Analisis _lexico/ejercicios.py","file_name":"ejercicios.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"221848868","text":"from __future__ import division\r\nfrom PIL import Image\r\nfrom os import listdir, path, makedirs\r\n#from os.path import isfile, join, exist\r\nimport numpy as np\r\nimport argparse\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"-s\",\"--SampleDir\", type=str,\r\n help=\"directory for samples\",\r\n default = '../data/pre_noise/ibm1jpg41')\r\nparser.add_argument(\"-r\",\"--ResultDir\", type=str,\r\n help=\"directory for samples\",\r\n default = 'sensors')\r\nparser.add_argument(\"-t\",\"--Threshold\", type=float,\r\n help=\"threshold for every placement\",\r\n default = 0.9)\r\nargs = parser.parse_args()\r\n\r\n\r\nPicPath = args.SampleDir\r\nPicFiles = [ f for f in listdir(PicPath) if path.isfile(path.join(PicPath,f)) and f.strip().split('.')[-1]=='jpg']\r\n\r\nprint(str(len(PicFiles)) + ' files.')\r\n\r\npx_per_pic = 1082\r\nNsensor = 9\r\nthreshold = args.Threshold\r\n\r\n### Read Pixels Out\r\ncountflag = 0\r\nfor Pic in PicFiles:\r\n Im = Image.open(path.join(PicPath, Pic))\r\n Im = Im.convert('L')\r\n pic_per_Pic = Im.size[1]*Im.size[1]\r\n Px = np.asarray(Im) > threshold*255\r\n ImPx = np.reshape(1*Px,(pic_per_Pic,-1))\r\n if countflag == 0:\r\n AllPx = ImPx\r\n else:\r\n AllPx = np.vstack((AllPx, ImPx))\r\n countflag = countflag + 1\r\n print(countflag)\r\n\r\nprint(AllPx)\r\nprint(AllPx.shape)\r\n\r\nAllPxs = AllPx\r\n### Remove All 1's\r\nmask0 = np.zeros((AllPx.shape[0]))\r\nidxc = np.where(np.sum(AllPxs, axis=0) == AllPx.shape[0])\r\nif idxc[0].size > 0:\r\n for i in xrange(idxc[0].size):\r\n AllPxs[:,idxc[0][i]] = mask0\r\n\r\n\r\n### Place Sensors\r\nPlaces = [535, 85, 11]\r\nfor i in xrange(len(Places)):\r\n ### Check Whether There Is Noise Left\r\n if AllPxs.size < 1:\r\n print('All covered')\r\n break\r\n ### Select A Sensor\r\n print(np.unique(np.sum(AllPxs, axis=0)))\r\n #idxc = np.argmax(np.sum(AllPxs, axis=0))\r\n #Places.append(str(int(idxc)))\r\n idxc = Places[i]\r\n col = AllPxs[:,idxc]\r\n idxt = np.where(col==1)\r\n AllPxs = np.delete(AllPxs, idxt[0], 0)\r\n print(str(i+1) + '-th sensor...')\r\n print('Left uncovered:')\r\n print(AllPxs.shape)\r\n\r\n\r\n### Store Results\r\n#if not path.exists(args.ResultDir):\r\n# makedirs(args.ResultDir)\r\n\r\n#fo = open(path.join(args.ResultDir,'cover0_from_'+ path.basename(args.SampleDir) + '_' + str(threshold)),'w')\r\n#fo.write(','.join(Places))\r\n#fo.close()","sub_path":"Selected/scripts/Cover_0.py","file_name":"Cover_0.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"551651326","text":"import sys\ntest = int(sys.stdin.readline())\nfor i in range (test):\n count = 0\n nj =[] # list for n , k \n nl =[] # list for values of n\n nj =list(map(int, input().split())) \n nl =list(map(int, input().split()))\n for _ in range (int(nj[0])):\n if(int(nl[_] )<= 0):\n count = count + 1\n else:\n break\n if((int(count)) >= (int(nj[1]))):\n print('NO')\n else:\n print('YES')\n\n \n\n","sub_path":"HackerRank/src/Challenges/Angry Professor.py","file_name":"Angry Professor.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"308084949","text":"import nltk\nfrom nltk.stem.porter import *\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\nfrom gensim.test.utils import datapath\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom gensim.utils import simple_preprocess\nfrom gensim import corpora, models\nfrom flask import jsonify\nimport gensim\nimport pickle\nfrom nltk.corpus import wordnet\nfrom pprint import pprint\nnltk.download('wordnet')\n\nwordnet.ensure_loaded()\n\n\nclass ImageCrawler:\n def __init__(self, theme, image_index_location=\"image_index.pkl\", topic_model_location=\"lda_model.pkl\", dictionary_location=\"dictionary.pkl\"):\n # Jerry's theme matching code goes here\n self.theme = theme\n self.__image_index_location = image_index_location\n self.__topic_model_location = topic_model_location\n self.__dictionary_location = dictionary_location\n self.__topic_model = self.__load_topic_model()\n self.__image_index = self.__load_image_index()\n self.__dictionary = self.__load_dictionary()\n pass\n\n # Load image_index, topic model, dictionary\n def __load_topic_model(self):\n location = self.__topic_model_location\n with open(location, \"rb\") as file:\n topic_model = pickle.load(file)\n return topic_model\n\n def __load_image_index(self):\n location = self.__image_index_location\n with open(location, \"rb\") as file:\n image_index = pickle.load(file)\n return image_index\n\n def __load_dictionary(self):\n location = self.__dictionary_location\n with open(location, \"rb\") as file:\n dictionary = pickle.load(file)\n return dictionary\n\n def __synonyms(self, word):\n list = \"\"\n synonyms_found = []\n for syn in wordnet.synsets(word):\n for name in syn.lemma_names():\n if name not in synonyms_found:\n list = list + \" \" + name.replace(\"_\", \" \")\n synonyms_found.append(name)\n return list\n\n def __add_synonyms_to_sentence(self, sentence):\n final = \"\"\n\n for word in sentence.split():\n final = final + self.__synonyms(word)\n return final\n\n def __lemmatize_stemming(self, text):\n return PorterStemmer().stem(WordNetLemmatizer().lemmatize(text, pos='v'))\n\n def __preprocess(self, text):\n result = []\n for token in gensim.utils.simple_preprocess(text):\n if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:\n result.append(self.__lemmatize_stemming(token))\n return result\n\n def matching_image_locations(self, matching_threshold):\n # convert the theme to topics\n relevant_topics = []\n theme = self.theme\n topic_model = self.__topic_model\n image_index = self.__image_index\n dictionary = self.__dictionary\n\n unseen_doc_with_syn = self.__add_synonyms_to_sentence(theme)\n bow_vector = dictionary.doc2bow(self.__preprocess(unseen_doc_with_syn))\n for index, score in topic_model[bow_vector]:\n relevant_topics.append(index)\n\n # find images that match those topics\n img_list = []\n\n for img_entry in image_index:\n total_score = 0\n topic_scores = []\n\n for topic in img_entry['topics']:\n if topic['topic_index'] in relevant_topics:\n total_score = total_score + topic['score']\n topic_score_detail = {\n 'score': topic['score'],\n 'topic_index': topic['topic_index']\n # 'topic_tags': topic_model.print_topics(-1)[topic['topic_index']][1]\n # 'topic_tags': topic_model.show_topics()\n }\n topic_scores.append(topic_score_detail)\n\n if total_score > matching_threshold:\n list_entry = {\n 'img': img_entry['img'],\n 'img_tag': img_entry['label'],\n 'total_score': total_score,\n 'topic_scores': topic_scores\n }\n img_list.append(list_entry)\n\n num_imgs_to_select = 25\n selected_imgs = []\n for entry in sorted(img_list, key=lambda x: x['total_score'], reverse=True)[:num_imgs_to_select]:\n # Getting only the name of the image from the path\n image_name = entry['img'].split('thumbnails/')\n selected_imgs.append(image_name[1])\n\n # selected_imgs_dict = {i+1: selected_imgs[i] for i in range(0, len(selected_imgs))}\n\n potential_images = {}\n potential_images['potential_images'] = (selected_imgs)\n return jsonify(potential_images)\n","sub_path":"Code/ArtistEndpoint/ImageCrawler.py","file_name":"ImageCrawler.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"131171287","text":"import time\nimport random\nimport itertools\n\nPAUSE_AMOUNT = 1\nDIE = list(range(1, 7))\nOTUCOME = {(1, 1): 'ピンゾロの丁', (1, 2): 'イチニの半', (1, 3): 'サンミチの丁', (1, 4): 'ヨイチの半', (1, 5): 'グイチの', (1, 6): 'イチロクの半',\n (2, 2): 'ニゾロの丁', (2, 3): 'サニの半', (2, 4): 'シニの丁', (2, 5): 'グニの半', (2, 6): 'ニロクの丁',\n (3, 3): 'サンゾロの丁', (3, 4): 'シソウの半', (3, 5): 'グサンの丁', (3, 6): 'サブロクの',\n (4, 4): 'シゾロの丁', (4, 5): 'グシの半', (4, 6): 'シロクの丁',\n (5, 5): 'ゴゾロの丁', (5, 6): 'ゴロクの半', (6, 6): 'ロクゾロの丁'}\n\n\ndef main():\n print('''Cho-Han\n In this traditional Japanese dice game, two dice are rolled in a bamboo\n cup by the dealer sitting on the floor. The player must guess if the\n dice total to an even (cho) or odd (han) number.\n ''')\n\n money = 5000\n\n while money > 0:\n print(\n f'You have {money} mon. How much do you bet? (1-{money} or QUIT)')\n inputBet = input_bet(money)\n if eval(str(inputBet).lower() + '== quit'):\n break\n\n print('The dealer swirls the cup and you hear the rattle of dice.')\n time.sleep(PAUSE_AMOUNT)\n print('The dealer slams the cup on the floor, still covering the dice and asks for your bet.')\n print(' '*5 + 'CHO (even) or HAN (odd)?')\n userGuess = input_guess()\n\n print('The dealer lifts the cup to reaveal:')\n diceNum = tuple(sorted(random.choices(DIE, k=2)))\n print(' '*(8-len(OTUCOME[diceNum])) + OTUCOME[diceNum])\n print(' '*5 + str(diceNum[0]) + ' - ' + str(diceNum[1]))\n\n if (sum(diceNum) % 2 and userGuess == 'HAN') or (sum(diceNum) % 2 == 0 and userGuess == 'CHO'):\n print(f'You won! You take {2*inputBet} mon.')\n print(f'The house collects a {int(0.1*inputBet)} mon fee.')\n money += int(1.9*inputBet)\n else:\n print(f'You lost. The house take yours {inputBet} mon bet.')\n money -= inputBet\n\n\ndef input_bet(userMoney):\n while True:\n bet = input('> ')\n if bet.isdigit() and eval(bet + '<=' + str(userMoney)):\n bet = int(bet)\n print(f'Bet: {bet} mon')\n break\n elif bet.lower() == 'quit':\n print(f'You quit the game. Your money is {userMoney} mon.')\n break\n print(\n f'Invalid input. Please input a bet in range of 1-{userMoney}, or QUIT')\n\n return bet\n\n\ndef input_guess():\n while True:\n guess = input('> ').upper()\n if guess in ['CHO', 'HAN']:\n print(f'Your guess is {guess}')\n break\n print(f'Invalid input. Please input CHO or HAN')\n\n return guess\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Chapter_10_Cho-Han/Cho-Han.py","file_name":"Cho-Han.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"375572018","text":"from dataclasses import dataclass\n\n@dataclass\nclass School:\n name = \"\"\n teachers = []\n students = []\n def __str__(self):\n string = f\"[{self.name}. Teachers: {self.teachers[0].__str__()}\"\n for teacher in self.teachers[1:]:\n string += \", \" + teacher.__str__()\n string += f\", Students: {self.students[0].__str__()}\"\n for student in self.students[1:]:\n string += \", \" + student.__str__()\n return string\n\n@dataclass\nclass Person:\n name = \"\"\n def __str__(self):\n return f\"[{self.name}, who has nothing to do with this program]\"\n\n@dataclass\nclass Teacher(Person):\n subject = \"\"\n def __str__(self):\n return f\"[{self.name}, teaches {self.subject}]\"\n\n@dataclass\nclass Student(Person):\n teacher = None\n def __str__(self):\n return f\"[{self.name}, taught {self.teacher.subject} by {self.teacher.name}]\"\n\ndef create_school(name: str) -> School:\n school = School()\n school.name = name\n return school\n\ndef create_teacher(name: str, subject: str) -> Teacher:\n teacher = Teacher()\n teacher.name = name\n teacher.subject = subject\n return teacher\n\ndef create_student(name: str, teacher: Teacher) -> Student:\n student = Student()\n student.name = name\n student.teacher = teacher\n return student\n\ndef add_teacher(school: School, teacher: Teacher) -> None:\n school.teachers.append(teacher)\n\ndef enrol_student(school: School, student: Student) -> None:\n school.students.append(student)\n\ndef enrol_students(school: School, students: \"Student[]\") -> None:\n school.students += students\n\nif __name__ == \"__main__\":\n cherwell = create_school(\"The Cherwell School Sixth Form\")\n teacher = create_teacher(\"Teacher\", \"Computer Science\")\n student1 = create_student(\"Student Alpha\", teacher)\n student2 = create_student(\"Student Beta\", teacher)\n student3 = create_student(\"Student Gamma\", teacher)\n add_teacher(cherwell, teacher)\n enrol_students(cherwell, [student1, student2, student3])\n","sub_path":"2.2 programming techniques/school.py","file_name":"school.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"499754712","text":"import os, signal\nimport sys\nimport json\nimport shutil\nimport logging\nimport multiprocessing as mp\nsys.path.append('..')\nfrom data_source.fr24_crawler import Fr24Crawler\nfrom state import State\n\n\ndef _help():\n print('可用指令及用法:\\n'\n '\\tset \\t修改全局变量\\t\\t\\tset parm args\\n'\n '\\tshow\\t查看全局变量\\t\\t\\tshow parm\\n'\n '\\thelp\\t查看帮助\\t\\t\\t\\thelp (cmd)\\n'\n '\\tload\\t读取最新文件\\t\\t\\tload\\n'\n '\\tdata\\t显示读取后的文件中的数据\\tdata (fields)\\n'\n '全局变量及格式:\\n'\n '\\tloc\\t\\t\\t搜索中心坐标\\t\\tlatitude longitude\\n'\n '\\trng\\t\\t\\t搜索区域西北角坐标\\tlatitude longitude\\n'\n '\\tinterval\\t工作间隔\\t\\t\\tseconds\\n'\n '\\tenabled \\tLED显示模式\\t\\ton/off on/off on/off\\n'\n '数据关键字:\\n'\n '\\tlongitude\\t\\t\\t经度\\n'\n '\\tlatitude\\t\\t\\t纬度\\n'\n '\\theading\\t\\t\\t\\t航向\\n'\n '\\taltitude\\t\\t\\t高度\\n'\n '\\tground_speed\\t\\t地速\\n'\n '\\tsquawk_number\\t\\t应答机编码\\n'\n '\\tregistration_number\\t国籍注册号\\n'\n '\\tflight_number\\t\\t航班号\\n'\n '\\tdeparture_airport\\t始发机场\\n'\n '\\tarrival_airport\\t\\t目的机场\\n'\n '\\tvertical_speed\\t\\t垂直速度')\n\n\ndef _main():\n f = None\n while True:\n ipt = input().split()\n if not ipt:\n continue\n if ipt[0] in ['help', '?']:\n if len(ipt) == 1:\n _help()\n continue\n if len(ipt) > 2:\n print('Too many fields!')\n continue\n if ipt[1] == 'set':\n print('set \\t修改全局变量\\tset parm args')\n continue\n if ipt[1] == 'show':\n print('show\\t查看全局变量\\tshow parm')\n continue\n if ipt[1] == 'help':\n print('help\\t查看帮助\\thelp (cmd)')\n continue\n if ipt[1] == 'load':\n print('load\\t读取最新文件\\tload')\n continue\n if ipt[1] == 'data':\n print('data\\t显示读取后的文件中的数据\\tdata (fields)')\n continue\n print('No such command!')\n continue\n if ipt[0] == 'set':\n if len(ipt) < 3:\n print('Not enough fields!')\n continue\n # 修改loc\n if ipt[1] in ['loc', 'location', 'coord', 'coordinate', 'coordinates']:\n if len(ipt) == 3:\n print('Not enough fields!')\n continue\n if len(ipt) > 4:\n print('Too many fields!')\n continue\n # syntax正确:\n temp = loc[0]\n try:\n loc[0] = float(ipt[2])\n except ValueError:\n print('Invalid value!')\n continue\n try:\n loc[1] = float(ipt[3])\n except ValueError:\n print('Invalid value!')\n # reverse the change in case last one was successful\n loc[0] = temp\n continue\n # 修改rng\n if ipt[1] in ['rng', 'range', 'corner']:\n if len(ipt) == 3:\n print('Not enough fields!')\n continue\n if len(ipt) > 4:\n print('Too many fields!')\n continue\n # syntax正确:\n temp = rng[0]\n try:\n rng[0] = float(ipt[2])\n except ValueError:\n print('Invalid value!')\n continue\n try:\n rng[1] = float(ipt[3])\n except ValueError:\n print('Invalid value!')\n # reverse the change in case last one was successful\n rng[0] = temp\n continue\n # 修改interval\n if ipt[1] in ['interval', 'itv', 'frequency', 'freq']:\n if len(ipt) > 4:\n print('Too many fields!')\n continue\n # syntax正确:\n try:\n interval.value = float(ipt[2])\n except ValueError:\n print('Invalid value!')\n continue\n # 修改led的mode\n if ipt[1] in ['enabled', 'enable', 'mode', 'led', 'led_mode']:\n if len(ipt) < 5:\n print('Not enough fields!')\n continue\n if len(ipt) > 5:\n print('Too many fields!')\n continue\n # syntax正确:\n temp = enabled[0]\n temp1 = enabled[1]\n if ipt[2] in ['on', 'On', 'true', 'True', '1']:\n enabled[0] = 1\n elif ipt[2] in ['off', 'Off', 'false', 'False', '0']:\n enabled[0] = 0\n else:\n print('Invalid value!')\n continue\n if ipt[3] in ['on', 'On', 'true', 'True', '1']:\n enabled[1] = 1\n elif ipt[3] in ['off', 'Off', 'false', 'False', '0']:\n enabled[1] = 0\n else:\n print('Invalid value!')\n enabled[0] = temp\n continue\n if ipt[4] in ['on', 'On', 'true', 'True', '1']:\n enabled[2] = 1\n elif ipt[4] in ['off', 'Off', 'false', 'False', '0']:\n enabled[2] = 0\n else:\n print('Invalid value!')\n enabled[0] = temp\n enabled[1] = temp1\n continue\n if ipt[0] == 'show':\n if len(ipt) == 1:\n print('Not enough fields!')\n continue\n if len(ipt) > 2:\n print('Too many fields!')\n continue\n # 显示loc\n if ipt[1] in ['loc', 'location', 'coord', 'coordinate', 'coordinates']:\n print('Coordinate: ', loc[0], ', ', loc[1])\n continue\n # 显示rng\n if ipt[1] in ['rng', 'range', 'corner']:\n print('NW Corner Coordinate: ', rng[0], ', ', rng[1])\n continue\n # 显示interval\n if ipt[1] in ['interval', 'itv', 'frequency', 'freq']:\n print('Work Interval: ', interval.value)\n continue\n # 显示led mode\n if ipt[1] in ['enabled', 'enable', 'mode', 'led', 'led_mode']:\n out = ['Off', 'Off', 'Off']\n for i in range(3):\n if enabled[i]:\n out[i] = 'On'\n print('LED Display:\\n\\t# of Flights: ', out[0], '\\n\\tTaking Off: ', out[1], '\\n\\tLanding: ', out[2])\n continue\n if ipt[0] == 'load':\n if len(ipt) > 1:\n print('Too many fields!')\n continue\n data_dir = os.listdir('data')\n with open('data/' + max(data_dir)) as f:\n filedata = f.read()\n print('Loaded {} with {} flight(s).'.format(max(data_dir), len(filedata) - 1))\n continue\n if ipt[0] == 'data':\n flights = json.loads(filedata)\n data = flights.pop(0)\n f.close()\n f = open\n if len(ipt) == 1:\n for i in data:\n print(i, ':', data[i])\n lines = ''\n for flight in flights:\n for i in flight:\n lines += str(i) + ':' + str(flight[i]) + '\\t'\n lines += '\\n'\n print(lines)\n continue\n for i in ipt[1:]:\n if i not in flights[0]:\n print('\"{}\" is not a valid field!'.format(i))\n continue\n for i in data:\n print(i,':',data[i])\n lines = ''\n for flight in flights:\n for i in flight:\n if i in ipt[1:]:\n lines += str(i) + ':' + str(flight[i]) + '\\t'\n lines += '\\n'\n print(lines)\n continue\n print('Invalid syntax!\\n'\n 'For help, type help or ?')\n\n\ndef _draw():\n \"\"\"\n Function `_main`:\n\n Implement your chart rendering in this function.\n \"\"\"\n while True:\n pass\n\n\ndef cli_start(logger):\n pid = os.fork()\n if pid == 0:\n process2_pid = os.fork()\n pid_main = os.getppid()\n if process2_pid == 0:\n ppid = os.getppid()\n try:\n state = State()\n state.spin(enabled, interval)\n except KeyboardInterrupt:\n # 退出时删除生成的所有json文件\n shutil.rmtree('data')\n os.mkdir('data')\n os.kill(ppid, signal.SIGINT)\n else:\n try:\n crawler = Fr24Crawler()\n crawler.spin(loc, rng, interval)\n except KeyboardInterrupt:\n # The process is being killed, let the child process exit.\n logger.warning(\"Crawler exits.\")\n os.kill(pid, signal.SIGINT)\n os.kill(crawler_pid, signal.SIGINT) \n else:\n pid_main = os.getpid()\n try:\n _main()\n except KeyboardInterrupt:\n os.kill(pid_main, signal.SIGINT)\n\n\n# 初始化共享内存\nloc = mp.Array('d', (31.17940, 121.59043))\nrng = mp.Array('d', (32.67940, 120.09043))\ninterval = mp.Value('d', 5.0)\nenabled = mp.Array('i', (1, 1, 1))\n","sub_path":"cli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"434272085","text":"import urllib\nimport urllib2\n\n#BGG API Interface calls, returns xml\n\ndef get_want_to_play(geek_name):\n #use api to get want to play lists\n #xml format http://www.boardgamegeek.com/xmlapi/collection/?wanttoplay=<0,1>\n apiurl = \"http://www.boardgamegeek.com/xmlapi/collection/%s?wanttoplay=1\" % (urllib.quote(geek_name))\n return urllib2.urlopen(apiurl).read()\n\ndef get_games_from_idlist(game_list):\n #retrieve board game names for these items\n # /xmlapi/boardgame/,[...]\n bglistapiurl = \"http://www.boardgamegeek.com/xmlapi/boardgame/\"\n count = 0\n for item in game_list:\n if count != 0:\n bglistapiurl = bglistapiurl + ','\n bglistapiurl = bglistapiurl + item\n count+=1\n \n return urllib2.urlopen(bglistapiurl).read()\n ","sub_path":"geeksearchplusweb/geekinterface.py","file_name":"geekinterface.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"628677355","text":"# organization/models.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\nfrom django.core.validators import RegexValidator\nfrom django.db import models\nfrom django.db.models import Q\nfrom exception.models import handle_exception, \\\n handle_record_found_more_than_one_exception, handle_record_not_saved_exception\nfrom import_export_facebook.models import FacebookManager\nfrom import_export_twitter.functions import retrieve_twitter_user_info\nfrom twitter.models import TwitterUserManager\nfrom voter.models import VoterManager\nimport wevote_functions.admin\nfrom wevote_functions.functions import convert_to_int, extract_twitter_handle_from_text_string, positive_value_exists\nfrom wevote_settings.models import fetch_next_we_vote_id_last_org_integer, fetch_site_unique_id_prefix\n\nNONPROFIT_501C3 = '3'\nNONPROFIT_501C4 = '4'\nPOLITICAL_ACTION_COMMITTEE = 'P'\nCORPORATION = 'C'\nNEWS_CORPORATION = 'N'\nUNKNOWN = 'U'\nORGANIZATION_TYPE_CHOICES = (\n (NONPROFIT_501C3, 'Nonprofit 501c3'),\n (NONPROFIT_501C4, 'Nonprofit 501c4'),\n (POLITICAL_ACTION_COMMITTEE, 'Political Action Committee'),\n (CORPORATION, 'Corporation'),\n (NEWS_CORPORATION, 'News Corporation'),\n (UNKNOWN, 'Unknown'),\n)\n\nalphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='Only alphanumeric characters are allowed.')\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\n\nclass OrganizationManager(models.Manager):\n \"\"\"\n A class for working with the Organization model\n \"\"\"\n def create_organization_simple(self, organization_name, organization_website, organization_twitter_handle,\n organization_email='', organization_facebook='', organization_image=''):\n try:\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n organization = self.create(organization_name=organization_name,\n organization_website=organization_website,\n organization_twitter_handle=organization_twitter_handle,\n organization_email=organization_email,\n organization_facebook=organization_facebook,\n organization_image=organization_image)\n except Exception as e:\n handle_record_not_saved_exception(e, logger=logger)\n organization = Organization\n return organization\n\n def create_organization(self, organization_name, organization_website='', organization_twitter_handle='',\n organization_email='', organization_facebook='', organization_image=''):\n try:\n if not positive_value_exists(organization_name):\n organization_name = \"\"\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n # TODO DALE We should stop saving organization_twitter_handle without saving a TwitterLinkToOrganization\n organization = Organization.create(organization_name=organization_name,\n organization_website=organization_website,\n organization_twitter_handle=organization_twitter_handle,\n organization_email=organization_email,\n organization_facebook=organization_facebook,\n organization_image=organization_image)\n organization.save() # We do this so the we_vote_id is created\n status = \"CREATE_ORGANIZATION_SUCCESSFUL\"\n success = True\n organization_created = True\n except Exception as e:\n handle_record_not_saved_exception(e, logger=logger)\n organization = Organization\n status = \"CREATE_ORGANIZATION_FAILED\"\n success = False\n organization_created = False\n results = {\n 'success': success,\n 'status': status,\n 'organization': organization,\n 'organization_created': organization_created,\n }\n return results\n\n def retrieve_organization_from_id(self, organization_id):\n return self.retrieve_organization(organization_id)\n\n def retrieve_organization_from_we_vote_id(self, organization_we_vote_id):\n return self.retrieve_organization(0, organization_we_vote_id)\n\n def retrieve_organization_from_vote_smart_id(self, vote_smart_id):\n return self.retrieve_organization(0, '', vote_smart_id)\n\n def retrieve_organization_from_twitter_user_id(self, twitter_user_id):\n organization_we_vote_id = ''\n\n twitter_user_manager = TwitterUserManager()\n twitter_retrieve_results = twitter_user_manager.retrieve_twitter_link_to_organization_from_twitter_user_id(\n twitter_user_id)\n if twitter_retrieve_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_retrieve_results['twitter_link_to_organization']\n organization_we_vote_id = twitter_link_to_organization.organization_we_vote_id\n\n organization_id = 0\n return self.retrieve_organization(organization_id, organization_we_vote_id)\n\n def retrieve_organization_from_twitter_user_id_old(self, twitter_user_id):\n \"\"\"\n We will phase this out\n :param twitter_user_id:\n :return:\n \"\"\"\n return self.retrieve_organization(0, '', '', twitter_user_id)\n\n def retrieve_organization(self, organization_id, we_vote_id=None, vote_smart_id=None, twitter_user_id=None):\n error_result = False\n exception_does_not_exist = False\n exception_multiple_object_returned = False\n organization_on_stage = Organization()\n organization_on_stage_id = 0\n status = \"ERROR_ENTERING_RETRIEVE_ORGANIZATION\"\n try:\n if positive_value_exists(organization_id):\n status = \"ERROR_RETRIEVING_ORGANIZATION_WITH_ID\"\n organization_on_stage = Organization.objects.get(id=organization_id)\n organization_on_stage_id = organization_on_stage.id\n status = \"ORGANIZATION_FOUND_WITH_ID\"\n elif positive_value_exists(we_vote_id):\n status = \"ERROR_RETRIEVING_ORGANIZATION_WITH_WE_VOTE_ID\"\n organization_on_stage = Organization.objects.get(we_vote_id=we_vote_id)\n organization_on_stage_id = organization_on_stage.id\n status = \"ORGANIZATION_FOUND_WITH_WE_VOTE_ID\"\n elif positive_value_exists(vote_smart_id):\n status = \"ERROR_RETRIEVING_ORGANIZATION_WITH_VOTE_SMART_ID\"\n organization_on_stage = Organization.objects.get(vote_smart_id=vote_smart_id)\n organization_on_stage_id = organization_on_stage.id\n status = \"ORGANIZATION_FOUND_WITH_VOTE_SMART_ID\"\n elif positive_value_exists(twitter_user_id):\n status = \"ERROR_RETRIEVING_ORGANIZATION_WITH_TWITTER_ID\"\n organization_on_stage = Organization.objects.get(twitter_user_id=twitter_user_id)\n organization_on_stage_id = organization_on_stage.id\n status = \"ORGANIZATION_FOUND_WITH_TWITTER_ID\"\n except Organization.MultipleObjectsReturned as e:\n handle_record_found_more_than_one_exception(e, logger)\n error_result = True\n exception_multiple_object_returned = True\n status = \"ERROR_MORE_THAN_ONE_ORGANIZATION_FOUND\"\n # logger.warn(\"Organization.MultipleObjectsReturned\")\n except Organization.DoesNotExist:\n error_result = True\n exception_does_not_exist = True\n status += \", ORGANIZATION_NOT_FOUND\"\n # logger.warn(\"Organization.DoesNotExist\")\n\n organization_on_stage_found = True if organization_on_stage_id > 0 else False\n results = {\n 'success': True if organization_on_stage_found else False,\n 'status': status,\n 'organization_found': organization_on_stage_found,\n 'organization_id':\n organization_on_stage.id if organization_on_stage.id else organization_on_stage_id,\n 'we_vote_id':\n organization_on_stage.we_vote_id if organization_on_stage.we_vote_id else we_vote_id,\n 'organization': organization_on_stage,\n 'error_result': error_result,\n 'DoesNotExist': exception_does_not_exist,\n 'MultipleObjectsReturned': exception_multiple_object_returned,\n }\n return results\n\n def fetch_organization_id(self, we_vote_id):\n organization_id = 0\n if positive_value_exists(we_vote_id):\n organization_manager = OrganizationManager()\n results = organization_manager.retrieve_organization(organization_id, we_vote_id)\n if results['success']:\n return results['organization_id']\n return 0\n\n def fetch_twitter_id_from_organization_we_vote_id(self, organization_we_vote_id):\n if positive_value_exists(organization_we_vote_id):\n twitter_user_manager = TwitterUserManager()\n organization_twitter_id = twitter_user_manager.fetch_twitter_id_from_organization_we_vote_id(\n organization_we_vote_id)\n else:\n organization_twitter_id = 0\n\n return organization_twitter_id\n\n def fetch_twitter_handle_from_organization_we_vote_id(self, organization_we_vote_id):\n if positive_value_exists(organization_we_vote_id):\n twitter_user_manager = TwitterUserManager()\n organization_twitter_handle = twitter_user_manager.fetch_twitter_handle_from_organization_we_vote_id(\n organization_we_vote_id)\n else:\n organization_twitter_handle = ''\n\n return organization_twitter_handle\n\n def fetch_we_vote_id_from_local_id(self, organization_id):\n if positive_value_exists(organization_id):\n results = self.retrieve_organization(organization_id)\n if results['organization_found']:\n organization = results['organization']\n return organization.we_vote_id\n else:\n return ''\n else:\n return ''\n\n def organization_name_needs_repair(self, organization):\n \"\"\"\n See also position_speaker_name_needs_repair\n :param organization:\n :return:\n \"\"\"\n if not hasattr(organization, 'organization_name'):\n return False\n if organization.organization_name.startswith(\"Voter-\") \\\n or organization.organization_name.startswith(\"null\") \\\n or organization.organization_name is \"\" \\\n or organization.organization_name.startswith(\"wv\"):\n return True\n return False\n\n def repair_organization(self, organization):\n if not hasattr(organization, 'organization_name'):\n return organization\n\n # Is there a Twitter handle linked to this organization? If so, update the information.\n twitter_user_manager = TwitterUserManager()\n twitter_link_results = twitter_user_manager.retrieve_twitter_link_to_organization_from_organization_we_vote_id(\n organization.we_vote_id)\n if twitter_link_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_link_results['twitter_link_to_organization']\n\n twitter_results = \\\n twitter_user_manager.retrieve_twitter_user_locally_or_remotely(twitter_link_to_organization.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n try:\n organization.organization_name = twitter_user.twitter_name\n organization.twitter_description = twitter_user.twitter_description\n organization.twitter_followers_count = twitter_user.twitter_followers_count\n organization.twitter_profile_image_url_https = twitter_user.twitter_profile_image_url_https\n organization.organization_website = twitter_user.twitter_url\n organization.twitter_name = twitter_user.twitter_name\n organization.save()\n except Exception as e:\n pass\n return organization\n\n # We can use any of these four unique identifiers:\n # organization.id, we_vote_id, organization_website, organization_twitter_handle\n # Pass in the value if we want it saved. Pass in \"False\" if we want to leave it the same.\n def update_or_create_organization(self, organization_id, we_vote_id,\n organization_website_search, organization_twitter_search,\n organization_name=False, organization_website=False,\n organization_twitter_handle=False, organization_email=False,\n organization_facebook=False, organization_image=False,\n refresh_from_twitter=False,\n facebook_id=False, facebook_email=False,\n facebook_profile_image_url_https=False\n ):\n \"\"\"\n Either update or create an organization entry.\n \"\"\"\n exception_does_not_exist = False\n exception_multiple_object_returned = False\n organization_on_stage_found = False\n new_organization_created = False\n organization_on_stage = Organization()\n status = \"ENTERING_UPDATE_OR_CREATE_ORGANIZATION\"\n\n organization_id = convert_to_int(organization_id) if positive_value_exists(organization_id) else False\n we_vote_id = we_vote_id.strip().lower() if we_vote_id else False\n organization_website_search = organization_website_search.strip() if organization_website_search else False\n organization_twitter_search = organization_twitter_search.strip() if organization_twitter_search else False\n organization_name = organization_name.strip() if organization_name else False\n organization_website = organization_website.strip() if organization_website else False\n # TODO DALE We should stop saving organization_twitter_handle without saving a TwitterLinkToOrganization\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n organization_twitter_handle = organization_twitter_handle.strip() if organization_twitter_handle else False\n organization_email = organization_email.strip() if organization_email else False\n organization_facebook = organization_facebook.strip() if organization_facebook else False\n organization_image = organization_image.strip() if organization_image else False\n\n # Values that can only be updated by a refresh_from_twitter\n twitter_user_id = False\n twitter_name = False\n twitter_followers_count = False\n twitter_profile_image_url_https = False\n twitter_profile_banner_url_https = False\n twitter_profile_background_image_url_https = False\n twitter_description = False\n twitter_location = False\n twitter_url = False\n\n # Facebook values\n facebook_email = facebook_email.strip() if facebook_email else False\n\n # In order of authority\n # 1) organization_id exists? Find it with organization_id or fail\n # 2) we_vote_id exists? Find it with we_vote_id or fail\n # 3) facebook_id exists? Try to find it. If not, go to step 4\n # 4) organization_website_search exists? Try to find it. If not, go to step 5\n # 5) organization_twitter_search exists? Try to find it. If not, exit\n\n success = False\n if positive_value_exists(organization_id) or positive_value_exists(we_vote_id):\n # If here, we know we are updating\n # 1) organization_id exists? Find it with organization_id or fail\n # 2) we_vote_id exists? Find it with we_vote_id or fail\n organization_results = self.retrieve_organization(organization_id, we_vote_id)\n if organization_results['success']:\n organization_on_stage = organization_results['organization']\n organization_on_stage_found = True\n\n # Now that we have an organization to update, get supplemental data from Twitter if\n # refresh_from_twitter is true\n if positive_value_exists(organization_twitter_handle) and refresh_from_twitter:\n twitter_user_id = 0\n results = retrieve_twitter_user_info(twitter_user_id, organization_twitter_handle)\n if results['success']:\n twitter_json = results['twitter_json']\n if positive_value_exists(twitter_json['id']):\n twitter_user_id = convert_to_int(twitter_json['id'])\n if positive_value_exists(twitter_json['name']):\n twitter_name = twitter_json['name']\n # Use Twitter value if a value for this variable was NOT passed in\n if not positive_value_exists(organization_name):\n organization_name = twitter_json['name']\n # TODO DALE Look more closely at saving the actual url from twitter (not the Twitter shortcut)\n # if positive_value_exists(twitter_json['twitter_url']):\n # # Use Twitter value if a value for this variable was NOT passed in\n # if not positive_value_exists(organization_website):\n # organization_website = twitter_json['twitter_url']\n twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n if positive_value_exists(twitter_json['profile_image_url_https']):\n twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n if 'profile_banner_url' in twitter_json:\n twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n twitter_description = twitter_json['description']\n twitter_location = twitter_json['location']\n\n value_changed = False\n if organization_name or organization_website or organization_twitter_handle \\\n or organization_email or organization_facebook or organization_image:\n value_changed = True\n if organization_name:\n organization_on_stage.organization_name = organization_name\n if organization_website:\n organization_on_stage.organization_website = organization_website\n if organization_twitter_handle:\n organization_on_stage.organization_twitter_handle = organization_twitter_handle\n if organization_email:\n organization_on_stage.organization_email = organization_email\n if organization_facebook:\n organization_on_stage.organization_facebook = organization_facebook\n if organization_image:\n organization_on_stage.organization_image = organization_image\n\n if twitter_user_id or twitter_name or twitter_followers_count or twitter_profile_image_url_https \\\n or twitter_profile_banner_url_https or twitter_profile_background_image_url_https \\\n or twitter_description or twitter_location:\n # Values that can only be added by a refresh_from_twitter\n value_changed = True\n if twitter_user_id:\n organization_on_stage.twitter_user_id = twitter_user_id\n if twitter_name:\n organization_on_stage.twitter_name = twitter_name\n if twitter_followers_count:\n organization_on_stage.twitter_followers_count = twitter_followers_count\n if twitter_profile_image_url_https:\n organization_on_stage.twitter_profile_image_url_https = twitter_profile_image_url_https\n if twitter_profile_banner_url_https:\n organization_on_stage.twitter_profile_banner_url_https = twitter_profile_banner_url_https\n if twitter_profile_background_image_url_https:\n organization_on_stage.twitter_profile_background_image_url_https = \\\n twitter_profile_background_image_url_https\n if twitter_description:\n organization_on_stage.twitter_description = twitter_description\n if twitter_location:\n organization_on_stage.twitter_location = twitter_location\n\n if value_changed:\n organization_on_stage.save()\n success = True\n status = \"SAVED_WITH_ORG_ID_OR_WE_VOTE_ID\"\n else:\n success = True\n status = \"NO_CHANGES_SAVED_WITH_ORG_ID_OR_WE_VOTE_ID\"\n else:\n status = \"ORGANIZATION_COULD_NOT_BE_FOUND_WITH_ORG_ID_OR_WE_VOTE_ID\"\n else:\n try:\n found_with_status = ''\n organization_on_stage_found = False\n\n # 3a) FacebookLinkToVoter exists? If not, go to step 3b\n if not organization_on_stage_found and positive_value_exists(facebook_id):\n facebook_manager = FacebookManager()\n facebook_results = facebook_manager.retrieve_facebook_link_to_voter(facebook_id)\n if facebook_results['facebook_link_to_voter_found']:\n facebook_link_to_voter = facebook_results['facebook_link_to_voter']\n voter_manager = VoterManager()\n voter_results = \\\n voter_manager.retrieve_voter_by_we_vote_id(facebook_link_to_voter.voter_we_vote_id)\n if voter_results['voter_found']:\n voter = voter_results['voter']\n if positive_value_exists(voter.linked_organization_we_vote_id):\n try:\n organization_on_stage = Organization.objects.get(\n we_vote_id=voter.linked_organization_we_vote_id)\n organization_on_stage_found = True\n found_with_status = \"FOUND_WITH_FACEBOOK_LINK_TO_VOTER\"\n except Organization.MultipleObjectsReturned as e:\n exception_multiple_object_returned = True\n logger.warn(\"Organization.MultipleObjectsReturned FACEBOOK_LINK_TO_VOTER\")\n except Organization.DoesNotExist as e:\n # Not a problem -- an organization matching this facebook_id wasn't found\n exception_does_not_exist = True\n\n # 3b) facebook_id exists? Try to find it. If not, go to step 4\n if not organization_on_stage_found and positive_value_exists(facebook_id):\n try:\n organization_on_stage = Organization.objects.get(\n facebook_id=facebook_id)\n organization_on_stage_found = True\n found_with_status = \"FOUND_WITH_FACEBOOK_ID\"\n except Organization.MultipleObjectsReturned as e:\n handle_record_found_more_than_one_exception(e, logger)\n exception_multiple_object_returned = True\n logger.warn(\"Organization.MultipleObjectsReturned facebook_id\")\n except Organization.DoesNotExist as e:\n # Not a problem -- an organization matching this facebook_id wasn't found\n exception_does_not_exist = True\n\n # 4) organization_website_search exists? Try to find it. If not, go to step 5\n if not organization_on_stage_found and positive_value_exists(organization_website_search):\n try:\n organization_on_stage = Organization.objects.get(\n organization_website__iexact=organization_website_search)\n organization_on_stage_found = True\n found_with_status = \"FOUND_WITH_WEBSITE\"\n except Organization.MultipleObjectsReturned as e:\n handle_record_found_more_than_one_exception(e, logger)\n exception_multiple_object_returned = True\n logger.warn(\"Organization.MultipleObjectsReturned organization_website\")\n except Organization.DoesNotExist as e:\n # Not a problem -- an organization matching this organization_website wasn't found\n exception_does_not_exist = True\n\n # 5) organization_twitter_search exists? Try to find it. If not, exit\n if not organization_on_stage_found and positive_value_exists(organization_twitter_search):\n try:\n organization_on_stage = Organization.objects.get(\n organization_twitter_handle__iexact=organization_twitter_search)\n organization_on_stage_found = True\n found_with_status = \"FOUND_WITH_TWITTER\"\n except Organization.MultipleObjectsReturned as e:\n handle_record_found_more_than_one_exception(e, logger)\n exception_multiple_object_returned = True\n logger.warn(\"Organization.MultipleObjectsReturned organization_twitter_handle\")\n except Organization.DoesNotExist as e:\n # Not a problem -- an organization matching this twitter handle wasn't found\n exception_does_not_exist = True\n\n if organization_on_stage_found:\n value_changed = False\n\n # 3) Save based on facebook_id\n if facebook_id or facebook_email or facebook_profile_image_url_https:\n value_changed = True\n if facebook_id:\n organization_on_stage.facebook_id = facebook_id\n if facebook_email:\n organization_on_stage.facebook_email = facebook_email\n if facebook_profile_image_url_https:\n organization_on_stage.facebook_profile_image_url_https = facebook_profile_image_url_https\n\n # 4 & 5) Save values entered in steps 4 & 5\n # Now that we have an organization to update, get supplemental data from Twitter if\n # refresh_from_twitter is true\n if positive_value_exists(organization_twitter_handle) and refresh_from_twitter:\n twitter_user_id = 0\n results = retrieve_twitter_user_info(twitter_user_id, organization_twitter_handle)\n if results['success']:\n twitter_json = results['twitter_json']\n if positive_value_exists(twitter_json['id']):\n twitter_user_id = convert_to_int(twitter_json['id'])\n if positive_value_exists(twitter_json['name']):\n twitter_name = twitter_json['name']\n # Use Twitter value if a value for this variable was NOT passed in\n if not positive_value_exists(organization_name):\n organization_name = twitter_json['name']\n twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n if positive_value_exists(twitter_json['profile_image_url_https']):\n twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n if 'profile_banner_url' in twitter_json:\n twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n twitter_description = twitter_json['description']\n twitter_location = twitter_json['location']\n\n if organization_name or organization_website or organization_twitter_handle \\\n or organization_email or organization_facebook or organization_image:\n value_changed = True\n if organization_name:\n organization_on_stage.organization_name = organization_name\n if organization_website:\n organization_on_stage.organization_website = organization_website\n if organization_twitter_handle:\n organization_on_stage.organization_twitter_handle = organization_twitter_handle\n if organization_email:\n organization_on_stage.organization_email = organization_email\n if organization_facebook:\n organization_on_stage.organization_facebook = organization_facebook\n if organization_image:\n organization_on_stage.organization_image = organization_image\n\n if twitter_user_id or twitter_name or twitter_followers_count or twitter_profile_image_url_https \\\n or twitter_profile_banner_url_https or twitter_profile_background_image_url_https \\\n or twitter_description or twitter_location:\n # Values that can only be added by a refresh_from_twitter\n value_changed = True\n if twitter_user_id:\n organization_on_stage.twitter_user_id = twitter_user_id\n if twitter_name:\n organization_on_stage.twitter_name = twitter_name\n if twitter_followers_count:\n organization_on_stage.twitter_followers_count = twitter_followers_count\n if twitter_profile_image_url_https:\n organization_on_stage.twitter_profile_image_url_https = twitter_profile_image_url_https\n if twitter_profile_banner_url_https:\n organization_on_stage.twitter_profile_banner_url_https = twitter_profile_banner_url_https\n if twitter_profile_background_image_url_https:\n organization_on_stage.twitter_profile_background_image_url_https = \\\n twitter_profile_background_image_url_https\n if twitter_description:\n organization_on_stage.twitter_description = twitter_description\n if twitter_location:\n organization_on_stage.twitter_location = twitter_location\n\n if value_changed:\n organization_on_stage.save()\n success = True\n status = found_with_status + \" SAVED\"\n else:\n success = True\n status = found_with_status + \" NO_CHANGES_SAVED\"\n except Exception as e:\n handle_record_not_saved_exception(e, logger=logger)\n\n if not organization_on_stage_found:\n try:\n # Now that we have an organization to update, get supplemental data from Twitter if\n # refresh_from_twitter is true\n if positive_value_exists(organization_twitter_handle) and refresh_from_twitter:\n twitter_user_id = 0\n results = retrieve_twitter_user_info(twitter_user_id, organization_twitter_handle)\n if results['success']:\n twitter_json = results['twitter_json']\n if positive_value_exists(twitter_json['id']):\n twitter_user_id = convert_to_int(twitter_json['id'])\n if positive_value_exists(twitter_json['name']):\n twitter_name = twitter_json['name']\n # Use Twitter value if a value for this variable was NOT passed in\n if not positive_value_exists(organization_name):\n organization_name = twitter_json['name']\n twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n if positive_value_exists(twitter_json['profile_image_url_https']):\n twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n if 'profile_banner_url' in twitter_json:\n twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n twitter_description = twitter_json['description']\n twitter_location = twitter_json['location']\n\n # If here, create new organization\n results = Organization.objects.create_organization(organization_name, organization_website,\n organization_twitter_handle, organization_email,\n organization_facebook, organization_image)\n if results['success']:\n new_organization_created = True\n success = True\n value_changed = False\n status = \"NEW_ORGANIZATION_CREATED_IN_UPDATE_OR_CREATE\"\n organization_on_stage = results['organization']\n\n if twitter_user_id or twitter_name or twitter_followers_count or twitter_profile_image_url_https \\\n or twitter_profile_banner_url_https or twitter_profile_background_image_url_https \\\n or twitter_description or twitter_location:\n value_changed = True\n status += \" TWITTER_VALUES_RETRIEVED\"\n\n # Values that can only be added by a refresh_from_twitter\n if twitter_user_id:\n organization_on_stage.twitter_user_id = twitter_user_id\n if twitter_name:\n organization_on_stage.twitter_name = twitter_name\n if twitter_followers_count:\n organization_on_stage.twitter_followers_count = twitter_followers_count\n if twitter_profile_image_url_https:\n organization_on_stage.twitter_profile_image_url_https = twitter_profile_image_url_https\n if twitter_profile_banner_url_https:\n organization_on_stage.twitter_profile_banner_url_https = twitter_profile_banner_url_https\n if twitter_profile_background_image_url_https:\n organization_on_stage.twitter_profile_background_image_url_https = \\\n twitter_profile_background_image_url_https\n if twitter_description:\n organization_on_stage.twitter_description = twitter_description\n if twitter_location:\n organization_on_stage.twitter_location = twitter_location\n\n if facebook_id or facebook_email or facebook_profile_image_url_https:\n value_changed = True\n status += \" FACEBOOK_VALUES_TO_BE_ADDED\"\n if facebook_id:\n organization_on_stage.facebook_id = facebook_id\n if facebook_email:\n organization_on_stage.facebook_email = facebook_email\n if facebook_profile_image_url_https:\n organization_on_stage.facebook_profile_image_url_https = facebook_profile_image_url_https\n\n if value_changed:\n organization_on_stage.save()\n status += \" EXTRA_VALUES_SAVED\"\n else:\n status += \" EXTRA_VALUES_NOT_SAVED\"\n\n else:\n success = False\n status = results['status']\n organization_on_stage = Organization\n\n except Exception as e:\n handle_record_not_saved_exception(e, logger=logger)\n success = False\n status = \"NEW_ORGANIZATION_COULD_NOT_BE_CREATED_OR_EXTRA_VALUES_ADDED\"\n organization_on_stage = Organization\n\n results = {\n 'success': success,\n 'status': status,\n 'DoesNotExist': exception_does_not_exist,\n 'MultipleObjectsReturned': exception_multiple_object_returned,\n 'organization': organization_on_stage,\n 'new_organization_created': new_organization_created,\n }\n return results\n\n def update_organization_social_media(self, organization, organization_twitter_handle=False,\n organization_facebook=False):\n \"\"\"\n Update an organization entry with general social media data. If a value is passed in False\n it means \"Do not update\"\n \"\"\"\n exception_does_not_exist = False\n exception_multiple_object_returned = False\n success = False\n status = \"ENTERING_UPDATE_ORGANIZATION_SOCIAL_MEDIA\"\n values_changed = False\n\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n organization_twitter_handle = organization_twitter_handle.strip() if organization_twitter_handle else False\n organization_facebook = organization_facebook.strip() if organization_facebook else False\n # organization_image = organization_image.strip() if organization_image else False\n\n if organization:\n if organization_twitter_handle:\n organization_twitter_handle = str(organization_twitter_handle)\n object_organization_twitter_handle = str(organization.organization_twitter_handle)\n if organization_twitter_handle.lower() != object_organization_twitter_handle.lower():\n organization.organization_twitter_handle = organization_twitter_handle\n values_changed = True\n if organization_facebook:\n if organization_facebook != organization.organization_facebook:\n organization.organization_facebook = organization_facebook\n values_changed = True\n\n if values_changed:\n organization.save()\n success = True\n status = \"SAVED_ORG_SOCIAL_MEDIA\"\n else:\n success = True\n status = \"NO_CHANGES_SAVED_TO_ORG_SOCIAL_MEDIA\"\n\n results = {\n 'success': success,\n 'status': status,\n 'DoesNotExist': exception_does_not_exist,\n 'MultipleObjectsReturned': exception_multiple_object_returned,\n 'organization': organization,\n }\n return results\n\n def update_organization_twitter_details(self, organization, twitter_json,\n cached_twitter_profile_image_url_https=False,\n cached_twitter_profile_background_image_url_https=False,\n cached_twitter_profile_banner_url_https=False,\n we_vote_hosted_profile_image_url_large=False,\n we_vote_hosted_profile_image_url_medium=False,\n we_vote_hosted_profile_image_url_tiny=False):\n \"\"\"\n Update an organization entry with details retrieved from the Twitter API.\n \"\"\"\n success = False\n status = \"ENTERING_UPDATE_ORGANIZATION_TWITTER_DETAILS\"\n values_changed = False\n\n # TODO DALE We should stop saving organization_twitter_handle without saving a TwitterLinkToOrganization\n if organization:\n if 'id' in twitter_json and positive_value_exists(twitter_json['id']):\n if convert_to_int(twitter_json['id']) != organization.twitter_user_id:\n organization.twitter_user_id = convert_to_int(twitter_json['id'])\n values_changed = True\n if 'screen_name' in twitter_json and positive_value_exists(twitter_json['screen_name']):\n incoming_twitter_screen_name = str(twitter_json['screen_name'])\n if incoming_twitter_screen_name is False or incoming_twitter_screen_name == 'False':\n incoming_twitter_screen_name = \"\"\n organization_twitter_handle = str(organization.organization_twitter_handle)\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n if incoming_twitter_screen_name.lower() != organization_twitter_handle.lower():\n organization.organization_twitter_handle = twitter_json['screen_name']\n values_changed = True\n if 'name' in twitter_json and positive_value_exists(twitter_json['name']):\n if twitter_json['name'] != organization.twitter_name:\n organization.twitter_name = twitter_json['name']\n values_changed = True\n if 'followers_count' in twitter_json and positive_value_exists(twitter_json['followers_count']):\n if convert_to_int(twitter_json['followers_count']) != organization.twitter_followers_count:\n organization.twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_image_url_https):\n organization.twitter_profile_image_url_https = cached_twitter_profile_image_url_https\n values_changed = True\n elif 'profile_image_url_https' in twitter_json and positive_value_exists(\n twitter_json['profile_image_url_https']):\n if twitter_json['profile_image_url_https'] != organization.twitter_profile_image_url_https:\n organization.twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_banner_url_https):\n organization.twitter_profile_banner_url_https = cached_twitter_profile_banner_url_https\n values_changed = True\n elif 'profile_banner_url' in twitter_json and positive_value_exists(twitter_json['profile_banner_url']):\n if twitter_json['profile_banner_url'] != organization.twitter_profile_banner_url_https:\n organization.twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_background_image_url_https):\n organization.twitter_profile_background_image_url_https = \\\n cached_twitter_profile_background_image_url_https\n values_changed = True\n elif 'profile_background_image_url_https' in twitter_json and positive_value_exists(\n twitter_json['profile_background_image_url_https']):\n if twitter_json['profile_background_image_url_https'] != \\\n organization.twitter_profile_background_image_url_https:\n organization.twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_large):\n organization.we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_image_url_large\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_medium):\n organization.we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_image_url_medium\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_tiny):\n organization.we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_image_url_tiny\n values_changed = True\n\n if 'description' in twitter_json and positive_value_exists(twitter_json['description']):\n if twitter_json['description'] != organization.twitter_description:\n organization.twitter_description = twitter_json['description']\n values_changed = True\n if 'location' in twitter_json and positive_value_exists(twitter_json['location']):\n if twitter_json['location'] != organization.twitter_location:\n organization.twitter_location = twitter_json['location']\n values_changed = True\n\n if values_changed:\n organization.save()\n success = True\n status = \"SAVED_ORG_TWITTER_DETAILS\"\n else:\n success = True\n status = \"NO_CHANGES_SAVED_TO_ORG_TWITTER_DETAILS\"\n\n results = {\n 'success': success,\n 'status': status,\n 'organization': organization,\n }\n return results\n\n def clear_organization_twitter_details(self, organization):\n \"\"\"\n Update an organization entry with details retrieved from the Twitter API.\n \"\"\"\n success = False\n status = \"ENTERING_UPDATE_ORGANIZATION_TWITTER_DETAILS\"\n\n if organization:\n organization.twitter_user_id = 0\n # We leave the handle in place\n # organization.organization_twitter_handle = \"\"\n organization.twitter_name = ''\n organization.twitter_followers_count = 0\n organization.twitter_profile_image_url_https = ''\n organization.we_vote_hosted_profile_image_url_large = ''\n organization.we_vote_hosted_profile_image_url_medium = ''\n organization.we_vote_hosted_profile_image_url_tiny = ''\n organization.twitter_description = ''\n organization.twitter_location = ''\n organization.save()\n success = True\n status = \"CLEARED_ORG_TWITTER_DETAILS\"\n\n results = {\n 'success': success,\n 'status': status,\n 'organization': organization,\n }\n return results\n\n def delete_organization(self, organization_id):\n organization_id = convert_to_int(organization_id)\n organization_deleted = False\n\n try:\n if organization_id:\n results = self.retrieve_organization(organization_id)\n if results['organization_found']:\n organization = results['organization']\n organization_id = organization.id\n organization.delete()\n organization_deleted = True\n except Exception as e:\n handle_exception(e, logger=logger)\n\n results = {\n 'success': organization_deleted,\n 'organization_deleted': organization_deleted,\n 'organization_id': organization_id,\n }\n return results\n\n\nclass OrganizationListManager(models.Manager):\n \"\"\"\n A class for working with lists of Organizations\n \"\"\"\n\n def organization_search_find_any_possibilities(self, organization_name, organization_twitter_handle='',\n organization_website='', organization_email='',\n organization_facebook=''):\n \"\"\"\n We want to find *any* possible organization that includes any of the search terms\n :param organization_name:\n :param organization_twitter_handle:\n :param organization_website:\n :param organization_email:\n :param organization_facebook:\n :return:\n \"\"\"\n organization_list_for_json = {}\n try:\n filters = []\n organization_list_for_json = []\n organization_objects_list = []\n if positive_value_exists(organization_name):\n new_filter = Q(organization_name__icontains=organization_name)\n # # Find entries with any word in the string - DALE 2016-05-06 This didn't feel right\n # from functools import reduce\n # organization_name_list = organization_name.split(\" \")\n # new_filter = reduce(lambda x, y: x | y,\n # [Q(organization_name__icontains=word) for word in organization_name_list])\n filters.append(new_filter)\n\n if positive_value_exists(organization_twitter_handle): # TODO DALE TwitterLinkToOrganization instead?\n new_filter = Q(organization_twitter_handle__icontains=organization_twitter_handle)\n filters.append(new_filter)\n\n if positive_value_exists(organization_website):\n new_filter = Q(organization_website__icontains=organization_website)\n filters.append(new_filter)\n\n if positive_value_exists(organization_email):\n new_filter = Q(organization_email__icontains=organization_email)\n filters.append(new_filter)\n\n if positive_value_exists(organization_facebook):\n new_filter = Q(organization_facebook__icontains=organization_facebook)\n filters.append(new_filter)\n\n # Add the first query\n if len(filters):\n final_filters = filters.pop()\n\n # ...and \"OR\" the remaining items in the list\n for item in filters:\n final_filters |= item\n\n organization_objects_list = Organization.objects.filter(final_filters)\n\n if len(organization_objects_list):\n organizations_found = True\n status = 'ORGANIZATIONS_RETRIEVED'\n for organization in organization_objects_list:\n one_organization_json = {\n 'organization_id': organization.id,\n 'organization_we_vote_id': organization.we_vote_id,\n 'organization_name':\n organization.organization_name if positive_value_exists(\n organization.organization_name) else '',\n 'organization_website': organization.organization_website if positive_value_exists(\n organization.organization_website) else '',\n 'organization_twitter_handle':\n organization.organization_twitter_handle if positive_value_exists(\n organization.organization_twitter_handle) else '',\n 'organization_email':\n organization.organization_email if positive_value_exists(\n organization.organization_email) else '',\n 'organization_facebook':\n organization.organization_facebook if positive_value_exists(\n organization.organization_facebook) else '',\n }\n organization_list_for_json.append(one_organization_json)\n else:\n organizations_found = False\n status = 'NO_ORGANIZATIONS_RETRIEVED'\n success = True\n except Organization.DoesNotExist:\n # No organizations found. Not a problem.\n organizations_found = False\n status = 'NO_ORGANIZATIONS_FOUND_DoesNotExist'\n success = True # We are still successful if no organizations are found\n except Exception as e:\n organizations_found = False\n handle_exception(e, logger=logger)\n status = 'FAILED organization_search_find_any_possibilities ' \\\n '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))\n success = False\n\n results = {\n 'status': status,\n 'success': success,\n 'organizations_found': organizations_found,\n 'organizations_list': organization_list_for_json,\n }\n return results\n\n def retrieve_organizations_by_id_list(self, organization_ids_followed_by_voter):\n organization_list = []\n organization_list_found = False\n\n if not type(organization_ids_followed_by_voter) is list:\n status = 'NO_ORGANIZATIONS_FOUND_MISSING_ORGANIZATION_LIST'\n success = False\n results = {\n 'success': success,\n 'status': status,\n 'organization_list_found': organization_list_found,\n 'organization_list': organization_list,\n }\n return results\n\n if not len(organization_ids_followed_by_voter):\n status = 'NO_ORGANIZATIONS_FOUND_NO_ORGANIZATIONS_IN_LIST'\n success = False\n results = {\n 'success': success,\n 'status': status,\n 'organization_list_found': organization_list_found,\n 'organization_list': organization_list,\n }\n return results\n\n try:\n organization_queryset = Organization.objects.all()\n organization_queryset = organization_queryset.filter(\n id__in=organization_ids_followed_by_voter)\n organization_queryset = organization_queryset.order_by('organization_name')\n organization_list = organization_queryset\n\n if len(organization_list):\n organization_list_found = True\n status = 'ORGANIZATIONS_FOUND_BY_ORGANIZATION_LIST'\n else:\n status = 'NO_ORGANIZATIONS_FOUND_BY_ORGANIZATION_LIST'\n success = True\n except Exception as e:\n status = 'retrieve_organizations_by_id_list: Unable to retrieve organizations from db. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n success = False\n\n results = {\n 'success': success,\n 'status': status,\n 'organization_list_found': organization_list_found,\n 'organization_list': organization_list,\n }\n return results\n\n def retrieve_organizations_from_non_unique_identifiers(self, twitter_handle):\n organization_list_objects = []\n organization_list_found = False\n success = False\n status = \"\"\n twitter_handle_filtered = extract_twitter_handle_from_text_string(twitter_handle)\n\n # See if we have linked an organization to this Twitter handle\n twitter_user_manager = TwitterUserManager()\n results = twitter_user_manager.retrieve_twitter_link_to_organization_from_twitter_handle(\n twitter_handle_filtered)\n if results['twitter_link_to_organization_found']:\n twitter_link_to_organization = results['twitter_link_to_organization']\n organization_manager = OrganizationManager()\n organization_results = organization_manager.retrieve_organization_from_we_vote_id(\n twitter_link_to_organization.organization_we_vote_id)\n if organization_results['organization_found']:\n organization = organization_results['organization']\n organization_list_found = True\n organization_list_objects.append(organization)\n success = True\n status = \"ORGANIZATION_FOUND_FROM_TWITTER_LINK_TO_ORGANIZATION\"\n else:\n try:\n organization_queryset = Organization.objects.all()\n organization_queryset = organization_queryset.filter(\n organization_twitter_handle__iexact=twitter_handle_filtered)\n # If multiple organizations claim the same Twitter handle, select the one with... ??\n # organization_queryset = organization_queryset.order_by('-twitter_followers_count')\n\n organization_list_objects = organization_queryset\n\n if len(organization_list_objects):\n organization_list_found = True\n status = 'ORGANIZATIONS_RETRIEVED_FROM_TWITTER_HANDLE'\n success = True\n else:\n status = 'NO_ORGANIZATIONS_RETRIEVED_FROM_TWITTER_HANDLE'\n success = True\n except Organization.DoesNotExist:\n # No organizations found. Not a problem.\n status = 'NO_ORGANIZATIONS_FOUND_FROM_TWITTER_HANDLE_DoesNotExist'\n organization_list_objects = []\n success = True\n except Exception as e:\n handle_exception(e, logger=logger)\n status = 'FAILED retrieve_organizations_from_non_unique_identifiers ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n success = False\n\n results = {\n 'success': success,\n 'status': status,\n 'organization_list_found': organization_list_found,\n 'organization_list': organization_list_objects,\n }\n return results\n\n def retrieve_possible_duplicate_organizations(self, organization_name, organization_twitter_handle, vote_smart_id,\n we_vote_id_from_master=''):\n organization_list_objects = []\n filters = []\n organization_list_found = False\n\n try:\n organization_queryset = Organization.objects.all()\n\n # Ignore entries with we_vote_id coming in from master server\n if positive_value_exists(we_vote_id_from_master):\n organization_queryset = organization_queryset.filter(~Q(we_vote_id__iexact=we_vote_id_from_master))\n\n # We want to find organizations with *any* of these values\n if positive_value_exists(organization_name):\n new_filter = Q(organization_name__iexact=organization_name)\n filters.append(new_filter)\n\n if positive_value_exists(organization_twitter_handle):\n new_filter = Q(organization_twitter_handle__iexact=organization_twitter_handle)\n filters.append(new_filter)\n\n if positive_value_exists(vote_smart_id):\n new_filter = Q(vote_smart_id=vote_smart_id)\n filters.append(new_filter)\n\n # Add the first query\n if len(filters):\n final_filters = filters.pop()\n\n # ...and \"OR\" the remaining items in the list\n for item in filters:\n final_filters |= item\n\n organization_queryset = organization_queryset.filter(final_filters)\n\n organization_list_objects = organization_queryset\n\n if len(organization_list_objects):\n organization_list_found = True\n status = 'DUPLICATE_ORGANIZATIONS_RETRIEVED'\n success = True\n else:\n status = 'NO_DUPLICATE_ORGANIZATIONS_RETRIEVED'\n success = True\n except Organization.DoesNotExist:\n # No organizations found. Not a problem.\n status = 'NO_DUPLICATE_ORGANIZATIONS_FOUND_DoesNotExist'\n organization_list_objects = []\n success = True\n except Exception as e:\n handle_exception(e, logger=logger)\n status = 'FAILED retrieve_possible_duplicate_organizations ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n success = False\n\n results = {\n 'success': success,\n 'status': status,\n 'organization_list_found': organization_list_found,\n 'organization_list': organization_list_objects,\n }\n return results\n\n\nclass Organization(models.Model):\n # We are relying on built-in Python id field\n\n # The we_vote_id identifier is unique across all We Vote sites, and allows us to share our org info with other\n # organizations\n # It starts with \"wv\" then we add on a database specific identifier like \"3v\" (WeVoteSetting.site_unique_id_prefix)\n # then the string \"org\", and then a sequential integer like \"123\".\n # We keep the last value in WeVoteSetting.we_vote_id_last_org_integer\n we_vote_id = models.CharField(\n verbose_name=\"we vote permanent id\", max_length=255, null=True, blank=True, unique=True)\n organization_name = models.CharField(\n verbose_name=\"organization name\", max_length=255, null=False, blank=False)\n organization_website = models.URLField(verbose_name='url of the endorsing organization', blank=True, null=True)\n organization_email = models.EmailField(\n verbose_name='organization contact email address', max_length=255, unique=False, null=True, blank=True)\n organization_contact_name = models.CharField(max_length=255, null=True, unique=False)\n organization_facebook = models.URLField(verbose_name='url of facebook page', blank=True, null=True)\n organization_image = models.CharField(verbose_name='organization image', max_length=255, null=True, unique=False)\n state_served_code = models.CharField(verbose_name=\"state this organization serves\", max_length=2,\n null=True, blank=True)\n # The vote_smart special interest group sigId for this organization\n vote_smart_id = models.BigIntegerField(\n verbose_name=\"vote smart special interest group id\", null=True, blank=True, unique=True)\n organization_description = models.TextField(\n verbose_name=\"Text description of this organization.\", null=True, blank=True)\n organization_address = models.CharField(\n verbose_name='organization street address', max_length=255, unique=False, null=True, blank=True)\n organization_city = models.CharField(max_length=255, null=True, blank=True)\n organization_state = models.CharField(max_length=2, null=True, blank=True)\n organization_zip = models.CharField(max_length=255, null=True, blank=True)\n organization_phone1 = models.CharField(max_length=255, null=True, blank=True)\n organization_phone2 = models.CharField(max_length=255, null=True, blank=True)\n organization_fax = models.CharField(max_length=255, null=True, blank=True)\n\n # Facebook session information\n facebook_id = models.BigIntegerField(verbose_name=\"facebook big integer id\", null=True, blank=True)\n facebook_email = models.EmailField(verbose_name='facebook email address', max_length=255, unique=False,\n null=True, blank=True)\n fb_username = models.CharField(unique=True, max_length=20, validators=[alphanumeric], null=True)\n facebook_profile_image_url_https = models.URLField(verbose_name='url of image from facebook', blank=True, null=True)\n\n # Twitter information\n twitter_user_id = models.BigIntegerField(verbose_name=\"twitter id\", null=True, blank=True)\n organization_twitter_handle = models.CharField(\n verbose_name='organization twitter screen_name', max_length=255, null=True, unique=False)\n twitter_name = models.CharField(\n verbose_name=\"org name from twitter\", max_length=255, null=True, blank=True)\n twitter_location = models.CharField(\n verbose_name=\"org location from twitter\", max_length=255, null=True, blank=True)\n twitter_followers_count = models.IntegerField(verbose_name=\"number of twitter followers\",\n null=False, blank=True, default=0)\n twitter_profile_image_url_https = models.URLField(verbose_name='url of user logo from twitter',\n blank=True, null=True)\n twitter_profile_background_image_url_https = models.URLField(verbose_name='tile-able background from twitter',\n blank=True, null=True)\n twitter_profile_banner_url_https = models.URLField(verbose_name='profile banner image from twitter',\n blank=True, null=True)\n twitter_description = models.CharField(verbose_name=\"Text description of this organization from twitter.\",\n max_length=255, null=True, blank=True)\n we_vote_hosted_profile_image_url_large = models.URLField(verbose_name='we vote hosted large image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_medium = models.URLField(verbose_name='we vote hosted medium image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_tiny = models.URLField(verbose_name='we vote hosted tiny image url',\n blank=True, null=True)\n\n wikipedia_page_id = models.BigIntegerField(verbose_name=\"pageid\", null=True, blank=True)\n wikipedia_page_title = models.CharField(\n verbose_name=\"Page title on Wikipedia\", max_length=255, null=True, blank=True)\n wikipedia_thumbnail_url = models.URLField(verbose_name='url of wikipedia logo thumbnail', blank=True, null=True)\n wikipedia_thumbnail_width = models.IntegerField(verbose_name=\"width of photo\", null=True, blank=True)\n wikipedia_thumbnail_height = models.IntegerField(verbose_name=\"height of photo\", null=True, blank=True)\n wikipedia_photo_url = models.URLField(verbose_name='url of wikipedia logo', blank=True, null=True)\n\n ballotpedia_page_title = models.CharField(\n verbose_name=\"Page title on Ballotpedia\", max_length=255, null=True, blank=True)\n ballotpedia_photo_url = models.URLField(verbose_name='url of ballotpedia logo', blank=True, null=True)\n\n organization_type = models.CharField(\n verbose_name=\"type of org\", max_length=1, choices=ORGANIZATION_TYPE_CHOICES, default=UNKNOWN)\n date_last_changed = models.DateTimeField(verbose_name='date last changed', null=True, auto_now=True)\n\n organization_endorsements_api_url = models.URLField(verbose_name='url of endorsements importer', blank=True, null=True)\n\n def __unicode__(self):\n return str(self.organization_name)\n\n def organization_photo_url(self):\n if positive_value_exists(self.organization_image):\n return self.organization_image\n elif positive_value_exists(self.twitter_profile_image_url_https):\n return self.twitter_profile_image_url_https_bigger()\n elif positive_value_exists(self.wikipedia_photo_url):\n return self.wikipedia_photo_url\n return ''\n\n def twitter_profile_image_url_https_bigger(self):\n if self.we_vote_hosted_profile_image_url_large:\n return self.we_vote_hosted_profile_image_url_large\n elif self.twitter_profile_image_url_https:\n return self.twitter_profile_image_url_https.replace(\"_normal\", \"_bigger\")\n else:\n return ''\n\n def twitter_profile_image_url_https_original(self):\n if self.twitter_profile_image_url_https:\n return self.twitter_profile_image_url_https.replace(\"_normal\", \"\")\n else:\n return ''\n\n class Meta:\n ordering = ('organization_name',)\n\n objects = OrganizationManager()\n\n @classmethod\n def create(cls, organization_name, organization_website, organization_twitter_handle, organization_email,\n organization_facebook, organization_image):\n if organization_twitter_handle is False or organization_twitter_handle == 'False':\n organization_twitter_handle = \"\"\n\n organization = cls(organization_name=organization_name,\n organization_website=organization_website,\n organization_twitter_handle=organization_twitter_handle,\n organization_email=organization_email,\n organization_facebook=organization_facebook,\n organization_image=organization_image)\n return organization\n\n # We override the save function so we can auto-generate we_vote_id\n def save(self, *args, **kwargs):\n # Even if this organization came from another source we still need a unique we_vote_id\n if self.we_vote_id:\n self.we_vote_id = self.we_vote_id.strip().lower()\n if self.we_vote_id == \"\" or self.we_vote_id is None: # If there isn't a value...\n # ...generate a new id\n site_unique_id_prefix = fetch_site_unique_id_prefix()\n next_local_integer = fetch_next_we_vote_id_last_org_integer()\n # \"wv\" = We Vote\n # site_unique_id_prefix = a generated (or assigned) unique id for one server running We Vote\n # \"org\" = tells us this is a unique id for an org\n # next_integer = a unique, sequential integer for this server - not necessarily tied to database id\n self.we_vote_id = \"wv{site_unique_id_prefix}org{next_integer}\".format(\n site_unique_id_prefix=site_unique_id_prefix,\n next_integer=next_local_integer,\n )\n # TODO we need to deal with the situation where we_vote_id is NOT unique on save\n super(Organization, self).save(*args, **kwargs)\n\n def is_nonprofit_501c3(self):\n return self.organization_type in NONPROFIT_501C3\n\n def is_nonprofit_501c4(self):\n return self.organization_type in NONPROFIT_501C4\n\n def is_political_action_committee(self):\n return self.organization_type in POLITICAL_ACTION_COMMITTEE\n\n def is_corporation(self):\n return self.organization_type in CORPORATION\n\n def is_news_corporation(self):\n return self.organization_type in NEWS_CORPORATION\n\n def is_organization_type_specified(self):\n return self.organization_type in (\n NONPROFIT_501C3, NONPROFIT_501C4, POLITICAL_ACTION_COMMITTEE,\n CORPORATION, NEWS_CORPORATION)\n\n def generate_facebook_link(self):\n if self.organization_facebook:\n return \"https://facebook.com/{facebook_page}\".format(facebook_page=self.organization_facebook)\n else:\n return ''\n\n def generate_twitter_link(self):\n if self.organization_twitter_handle:\n return \"https://twitter.com/{twitter_handle}\".format(twitter_handle=self.organization_twitter_handle)\n else:\n return ''\n\n def generate_wikipedia_link(self):\n if self.wikipedia_page_title:\n encoded_page_title = self.wikipedia_page_title.replace(\" \", \"_\")\n return \"https://en.wikipedia.org/wiki/{page_title}\".format(page_title=encoded_page_title)\n else:\n return ''\n","sub_path":"organization/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":73852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"236801654","text":"import sys\nimport time\nimport json\nimport requests\nfrom vector import VectorClock\nfrom threading import Thread\nimport bottle\nfrom bottle import run, get, post, view, request, redirect\nfrom urllib3.exceptions import MaxRetryError\n\nbottle.debug(True)\n\npeers = set(sys.argv[2:])\n\nnick = \"Nobody\"\nmyId = sys.argv[1]\n\n#Relogios\nrelogio = VectorClock(myId)\n\nmessages = set([(\"Nobody\", \"Hello!\", srt(relogio.getClocks()))])\n\n#ServerSide\n@get('/')\n@view('index')\ndef index():\n return {'messages': messages, 'nick': nick}\n\n@post('/send')\ndef sendMessage():\n global relogio\n relogio.add()\n global nick\n m = request.forms.get('message')\n nick = request.forms.get('nick')\n messages.add((nick, m, relogio.getClocks()))\n redirect('/')\n\n@post('/peers')\ndef myPeers():\n global relogio\n relogio.add()\n peers.union(request.forms.get('id'))\n data = json.dumps(list(peers))\n return data\n\ndef getPeersFrom(host):\n link = \"http://localhost:\"+ host + \"/peers\"\n try:\n resposta = requests.post(link, data={'id' : myId})\n if resposta.status_code == 200 :\n payload=json.loads(resposta.text)\n return set(payload)\n except MaxRetryError:\n print(\"Conection Error, numero maximo de tentativas\")\n except requests.exceptions.ConnectionError:\n print(\"Conection Error!\")\n return set([])\n\ndef serverSide():\n global relogio\n relogio.add()\n while True:\n time.sleep(5)\n N = set([])\n global peers\n for host in peers:\n lista = getPeersFrom(host)\n if lista.difference(peers) and lista:\n N = N.union(lista.difference(peers))\n peers = peers.union(N)\n\n#ClienteSide\n@get('/message')\ndef getPeers():\n global relogio\n relogio.add()\n data = json.dumps(list(messages))\n return data\n\ndef getMessagesFrom(host):\n link = \"http://localhost:\"+ host + \"/message\"\n try:\n resposta = requests.get(link)\n if (resposta.status_code == 200) :\n mensagens = json.loads(resposta.text)\n payload = set((a, b, c) for [a,b,c] in mensagens)\n return payload\n except MaxRetryError:\n print (\"Conection Error, numero maximo de tentativas!\")\n except requests.exceptions.ConnectionError:\n print (\"Conection Error!\")\n return set([])\n\ndef clientSide():\n global relogio\n relogio.add()\n while True:\n time.sleep(5)\n N = set([])\n global messages\n for host in peers:\n resposta = getMessagesFrom(host)\n N = N.union(resposta.difference(messages))\n messages = messages.union(N)\n for line in messages :\n \trelogio.unionClocks(line[2])\n\nthreadClient=Thread(None, clientSide, (), {}, None)\nthreadClient.start()\nthreadServer=Thread(None, serverSide, (), {}, None)\nthreadServer.start()\n\n\nrun(host='localhost', port=sys.argv[1])\n","sub_path":"trabalho3/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"454283168","text":"name = \"vikash sharma\"\nprofession = 'data scientist'\nage = 18\n\n#a = f\"hello my name is {name}, my profession is {profession} and my age is {age} \"\n#a = \"this is {}\".format(name)\n#a = \"this is {} and my profession is {}\".format(name,profession)\na = \"this is {}, profession{} and age is {}\".format(profession,name,age)\na = \"this is {1}, profession is {0} and age is {2}\".format(profession,name,age)\nprint(a)","sub_path":"10 format.py","file_name":"10 format.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"503996939","text":"# import openpyxl\n\n# wb = openpyxl.Workbook()\n# ws = wb.worksheets[0]\n# img = openpyxl.drawing.image.Image('img.jpg')\n# img.anchor = 'A1'\n# ws.add_image(img)\n# wb.save('out.xlsx')\n\n\nimport pyqrcode\n\n\ndef generate_qr():\n link_to_post = \"https://medium.com/@ngengesenior/qr-codes-generation-with-python-377735be6c5f\"\n url = pyqrcode.create(link_to_post)\n url.png('url.png', scale=5)\n print(\"Printing QR code\")\n print(url.terminal())\n\n\nif __name__ == '__main__':\n generate_qr()","sub_path":"excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"516991777","text":"import os\r\nimport telebot\r\nfrom flask import Flask\r\nfrom pymongo import MongoClient\r\n\r\nVERSION = \"3.12.1\"\r\n\r\nKNOWN_COMMANDS = {\r\n '/about': 'Learn more about HepiR and see available commands',\r\n '/login': 'Connect your telegram account to an existing Zevere account',\r\n '/me': 'Get Profile information about the connected Zevere user account',\r\n '/lists': 'Manage your task lists through the List Management screen',\r\n '/logout': 'Disconnect your telegram account from the connected Zevere account'\r\n}\r\n\r\nNO_AUTH_KNOWN_COMMANDS = {k: KNOWN_COMMANDS[k]\r\n for k in KNOWN_COMMANDS.keys() & {'/about', '/login'}}\r\n\r\nLOCAL_ENV = False\r\n\r\nif LOCAL_ENV:\r\n from dev_env import *\r\nelse:\r\n WEBHOOK_URL = 'https://zv-chatbot-hepir.herokuapp.com'\r\n\r\n # picked up from heroku configs\r\n PORT = int(os.environ['PORT'])\r\n TOKEN = os.environ['TOKEN']\r\n MONGODB_URI = os.environ['MONGODB_URI']\r\n BOT_USERNAME = os.environ['BOT_USERNAME']\r\n VIVID_USER = os.environ['VIVID_USER']\r\n VIVID_PASSWORD = os.environ['VIVID_PASSWORD']\r\n\r\n# hardcoded constants because we decided not to use heroku environment variables for these things\r\nMONGODB_COLLECTION = 'users'\r\n# last element at end of URI\r\nMONGODB_DBNAME = MONGODB_URI.split('/')[-1]\r\nBORZOO_ROOT_URL = 'https://zv-webapi-borzoo.herokuapp.com'\r\nVIVID_ROOT_URL = 'https://zv-botops-vivid.herokuapp.com'\r\nCOHERENT_ROOT_URL = 'https://zevere.herokuapp.com/'\r\nTG_USERNAME_URL = 'https://t.me'\r\n\r\nclient = MongoClient(MONGODB_URI)\r\ndb = client[MONGODB_DBNAME]\r\nuser_collection = db[MONGODB_COLLECTION]\r\n\r\nbot = telebot.TeleBot(TOKEN)\r\napp = Flask(__name__)\r\n","sub_path":"src/properties.py","file_name":"properties.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"287314071","text":"\"\"\"Classes for managing Hubitat devices.\"\"\"\n\nfrom json import loads\nfrom logging import getLogger\nfrom typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union, cast\n\nfrom hubitatmaker import Device, Event, Hub as HubitatHub\n\nfrom homeassistant.components.sensor import DEVICE_CLASS_TEMPERATURE\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import (\n ATTR_HIDDEN,\n CONF_ACCESS_TOKEN,\n CONF_HOST,\n CONF_ID,\n CONF_TEMPERATURE_UNIT,\n)\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.helpers import device_registry\nfrom homeassistant.helpers.device_registry import DeviceRegistry\nfrom homeassistant.helpers.entity import Entity\n\nfrom .const import (\n ATTR_ATTRIBUTE,\n ATTR_HA_DEVICE_ID,\n ATTR_HUB,\n CONF_APP_ID,\n CONF_HUBITAT_EVENT,\n CONF_SERVER_PORT,\n CONF_SERVER_URL,\n DOMAIN,\n PLATFORMS,\n TEMP_F,\n TRIGGER_CAPABILITIES,\n)\nfrom .util import get_hub_short_id, get_token_hash\n\n# Hubitat attributes that should be emitted as HA events\n_TRIGGER_ATTRS = tuple([v.attr for v in TRIGGER_CAPABILITIES.values()])\n# A mapping from Hubitat attribute names to the attribute names that should be\n# used for HA events\n_TRIGGER_ATTR_MAP = {v.attr: v.event for v in TRIGGER_CAPABILITIES.values()}\n\n_LOGGER = getLogger(__name__)\n\nListener = Callable[[Event], None]\n\n\nclass Hub:\n \"\"\"Representation of a Hubitat hub.\"\"\"\n\n def __init__(self, hass: HomeAssistant, entry: ConfigEntry, index: int):\n \"\"\"Initialize a Hubitat manager.\"\"\"\n if CONF_HOST not in entry.data:\n raise ValueError(\"Missing host in config entry\")\n if CONF_APP_ID not in entry.data:\n raise ValueError(\"Missing app ID in config entry\")\n if CONF_ACCESS_TOKEN not in entry.data:\n raise ValueError(\"Missing access token in config entry\")\n\n self.hass = hass\n self.config_entry = entry\n self.entities: List[\"HubitatEntity\"] = []\n self.event_emitters: List[\"HubitatEventEmitter\"] = []\n\n self._temperature_unit = (\n entry.options.get(\n CONF_TEMPERATURE_UNIT, entry.data.get(CONF_TEMPERATURE_UNIT)\n )\n or TEMP_F\n )\n\n if index == 1:\n self._hub_entity_id = \"hubitat.hub\"\n else:\n self._hub_entity_id = f\"hubitat.hub_{index}\"\n\n self.unsub_config_listener = entry.add_update_listener(_update_entry)\n\n @property\n def app_id(self) -> str:\n \"\"\"The Maker API app ID for this hub.\"\"\"\n return cast(str, self.config_entry.data.get(CONF_APP_ID))\n\n @property\n def devices(self) -> Mapping[str, Device]:\n \"\"\"The Hubitat devices known to this hub.\"\"\"\n return self._hub.devices\n\n @property\n def entity_id(self) -> str:\n \"\"\"The entity ID of this hub.\"\"\"\n return self._hub_entity_id\n\n @property\n def host(self) -> str:\n \"\"\"The IP address of the associated Hubitat hub.\"\"\"\n return cast(\n str,\n self.config_entry.options.get(\n CONF_HOST, self.config_entry.data.get(CONF_HOST)\n ),\n )\n\n @property\n def id(self) -> str:\n \"\"\"A unique ID for this hub instance.\"\"\"\n return get_hub_short_id(self._hub)\n\n @property\n def mac(self) -> Optional[str]:\n \"\"\"The MAC address of the associated Hubitat hub.\"\"\"\n return self._hub.mac\n\n @property\n def port(self) -> Optional[int]:\n \"\"\"The port used for the Hubitat event receiver.\"\"\"\n return self._hub.port\n\n @property\n def event_url(self) -> str:\n \"\"\"The event URL that Hubitat should POST events to.\"\"\"\n return self._hub.event_url\n\n @property\n def token(self) -> str:\n \"\"\"The token used to access the Maker API.\"\"\"\n return cast(str, self.config_entry.data.get(CONF_ACCESS_TOKEN))\n\n @property\n def temperature_unit(self) -> str:\n \"\"\"The units used for temperature values.\"\"\"\n return self._temperature_unit\n\n def add_device_listener(self, device_id: str, listener: Listener) -> None:\n \"\"\"Add a listener for events for a specific device.\"\"\"\n self._hub.add_device_listener(device_id, listener)\n\n def add_entities(self, entities: Sequence[\"HubitatEntity\"]) -> None:\n \"\"\"Add entities to this hub.\"\"\"\n self.entities.extend(entities)\n\n def add_event_emitters(self, emitters: Sequence[\"HubitatEventEmitter\"]) -> None:\n \"\"\"Add event emitters to this hub.\"\"\"\n self.event_emitters.extend(emitters)\n\n def remove_device_listeners(self, device_id: str) -> None:\n \"\"\"Remove all listeners for a specific device.\"\"\"\n self._hub.remove_device_listeners(device_id)\n\n def set_temperature_unit(self, temp_unit: str) -> None:\n \"\"\"Set the hub's temperature units.\"\"\"\n _LOGGER.debug(\"Setting hub temperature unit to %s\", temp_unit)\n self._temperature_unit = temp_unit\n\n def stop(self) -> None:\n \"\"\"Stop the hub.\"\"\"\n self._hub.stop()\n\n async def unload(self) -> None:\n \"\"\"Unload the hub.\"\"\"\n for emitter in self.event_emitters:\n await emitter.async_will_remove_from_hass()\n self.unsub_config_listener()\n\n async def async_setup(self) -> bool:\n \"\"\"Initialize this hub instance.\"\"\"\n entry = self.config_entry\n url = entry.options.get(CONF_SERVER_URL, entry.data.get(CONF_SERVER_URL))\n port = entry.options.get(CONF_SERVER_PORT, entry.data.get(CONF_SERVER_PORT))\n\n # Previous versions of the integration may have saved a value of \"\" for\n # server_url with the assumption that a use_server_url flag would control\n # it's use. The current version uses a value of null for \"no user URL\"\n # rather than a flag.\n if url == \"\":\n url = None\n\n _LOGGER.debug(\"Initializing Hubitat hub with event server on port %s\", port)\n self._hub = HubitatHub(\n self.host, self.app_id, self.token, port=port, event_url=url\n )\n\n await self._hub.start()\n\n hub = self._hub\n hass = self.hass\n config_entry = self.config_entry\n\n for platform in PLATFORMS:\n hass.async_create_task(\n hass.config_entries.async_forward_entry_setup(config_entry, platform)\n )\n\n _LOGGER.debug(\"Registered platforms\")\n\n # Create an entity for the Hubitat hub with basic hub information\n hass.states.async_set(\n self.entity_id,\n \"connected\",\n {\n CONF_ID: f\"{hub.host}::{hub.app_id}\",\n CONF_HOST: hub.host,\n ATTR_HIDDEN: True,\n CONF_TEMPERATURE_UNIT: self.temperature_unit,\n },\n )\n\n return True\n\n async def async_update_device_registry(self) -> None:\n \"\"\"Add a device for this hub to the device registry.\"\"\"\n dreg = cast(DeviceRegistry, await device_registry.async_get_registry(self.hass))\n dreg.async_get_or_create(\n config_entry_id=self.config_entry.entry_id,\n connections={(device_registry.CONNECTION_NETWORK_MAC, self._hub.mac)},\n identifiers={(DOMAIN, self.id)},\n manufacturer=\"Hubitat\",\n name=\"Hubitat Elevation\",\n )\n\n @staticmethod\n async def async_update_options(\n hass: HomeAssistant, config_entry: ConfigEntry\n ) -> None:\n \"\"\"Handle options update.\"\"\"\n _LOGGER.debug(\"Handling options update...\")\n hub = get_hub(hass, config_entry.entry_id)\n\n host: Optional[str] = config_entry.options.get(\n CONF_HOST, config_entry.data.get(CONF_HOST)\n )\n if host is not None and host != hub.host:\n await hub.set_host(host)\n _LOGGER.debug(\"Set hub host to %s\", host)\n\n port = (\n config_entry.options.get(\n CONF_SERVER_PORT, config_entry.data.get(CONF_SERVER_PORT)\n )\n or 0\n )\n if port != hub.port:\n await hub.set_port(port)\n _LOGGER.debug(\"Set event server port to %s\", port)\n\n url = config_entry.options.get(\n CONF_SERVER_URL, config_entry.data.get(CONF_SERVER_URL)\n )\n if url == \"\":\n url = None\n if url != hub.event_url:\n await hub.set_event_url(url)\n _LOGGER.debug(\"Set event server URL to %s\", url)\n\n temp_unit = (\n config_entry.options.get(\n CONF_TEMPERATURE_UNIT, config_entry.data.get(CONF_TEMPERATURE_UNIT)\n )\n or TEMP_F\n )\n if temp_unit != hub.temperature_unit:\n hub.set_temperature_unit(temp_unit)\n for entity in hub.entities:\n if entity.device_class == DEVICE_CLASS_TEMPERATURE:\n entity.update_state()\n _LOGGER.debug(\"Set temperature units to %s\", temp_unit)\n\n hass.states.async_set(\n hub.entity_id,\n \"connected\",\n {CONF_HOST: hub.host, CONF_TEMPERATURE_UNIT: hub.temperature_unit},\n )\n\n async def check_config(self) -> None:\n \"\"\"Verify that the hub is accessible.\"\"\"\n await self._hub.check_config()\n\n async def refresh_device(self, device_id: str) -> None:\n \"\"\"Load current data for a specific device.\"\"\"\n await self._hub.refresh_device(device_id)\n\n async def send_command(\n self, device_id: str, command: str, arg: Optional[Union[str, int]]\n ) -> None:\n \"\"\"Send a device command to Hubitat.\"\"\"\n await self._hub.send_command(device_id, command, arg)\n\n async def set_host(self, host: str) -> None:\n \"\"\"Set the host address that the Hubitat hub is accessible at.\"\"\"\n _LOGGER.debug(\"Setting Hubitat host to %s\", host)\n self._hub.set_host(host)\n\n async def set_port(self, port: int) -> None:\n \"\"\"Set the port that the event listener server will listen on.\"\"\"\n _LOGGER.debug(\"Setting event listener port to %s\", port)\n await self._hub.set_port(port)\n\n async def set_event_url(self, url: Optional[str]) -> None:\n \"\"\"Set the port that the event listener server will listen on.\"\"\"\n _LOGGER.debug(\"Setting event server URL to %s\", url)\n await self._hub.set_event_url(url)\n\n\nclass HubitatBase:\n \"\"\"Base class for Hubitat entities and event emitters.\"\"\"\n\n def __init__(self, hub: Hub, device: Device, temp: Optional[bool] = False) -> None:\n \"\"\"Initialize a device.\"\"\"\n self._hub = hub\n self._device: Device = device\n self._id = f\"{get_token_hash(hub.token)}::{self._device.id}\"\n self._old_ids = [\n f\"{self._hub.host}::{self._hub.app_id}::{self._device.id}\",\n f\"{self._hub.mac}::{self._hub.app_id}::{self._device.id}\",\n ]\n self._temp = temp\n\n # Sometimes entities may be temporary, created only to compute entity\n # metadata. Don't register device listeners for temprorary entities.\n if not temp:\n self._hub.add_device_listener(self._device.id, self.handle_event)\n\n @property\n def device_id(self) -> str:\n \"\"\"Return the hub-local id for this device.\"\"\"\n return self._device.id\n\n @property\n def device_info(self) -> Dict[str, Any]:\n \"\"\"Return the device info.\"\"\"\n return {\n \"identifiers\": {(DOMAIN, self.device_id)},\n \"name\": self._device.name,\n \"manufacturer\": \"Hubitat\",\n \"model\": self.type,\n \"via_device\": (DOMAIN, self._hub.id),\n }\n\n @property\n def old_unique_ids(self) -> List[str]:\n \"\"\"Return the legacy unique for this device.\"\"\"\n return self._old_ids\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return a unique for this device.\"\"\"\n return self._id\n\n @property\n def name(self) -> str:\n \"\"\"Return the display name of this device.\"\"\"\n return self._device.name\n\n @property\n def type(self) -> str:\n \"\"\"Return the type name of this device.\"\"\"\n return self._device.type\n\n async def async_will_remove_from_hass(self) -> None:\n \"\"\"Run when entity will be removed from hass.\"\"\"\n self._hub.remove_device_listeners(self.device_id)\n\n @callback\n def get_attr(self, attr: str) -> Union[float, int, str, None]:\n \"\"\"Get the current value of an attribute.\"\"\"\n if attr in self._device.attributes:\n return self._device.attributes[attr].value\n return None\n\n @callback\n def get_float_attr(self, attr: str) -> Optional[float]:\n \"\"\"Get the current value of an attribute.\"\"\"\n val = self.get_attr(attr)\n if val is None:\n return None\n return float(val)\n\n @callback\n def get_int_attr(self, attr: str) -> Optional[int]:\n \"\"\"Get the current value of an attribute.\"\"\"\n val = self.get_float_attr(attr)\n if val is None:\n return None\n return round(val)\n\n @callback\n def get_json_attr(self, attr: str) -> Optional[Dict[str, Any]]:\n \"\"\"Get the current value of an attribute.\"\"\"\n val = self.get_str_attr(attr)\n if val is None:\n return None\n return cast(Dict[str, Any], loads(val))\n\n @callback\n def get_str_attr(self, attr: str) -> Optional[str]:\n \"\"\"Get the current value of an attribute.\"\"\"\n val = self.get_attr(attr)\n if val is None:\n return None\n return str(val)\n\n @property\n def last_update(self) -> float:\n \"\"\"Return the last update time of this device.\"\"\"\n return self._device.last_update\n\n def handle_event(self, event: Event) -> None:\n \"\"\"Handle an event received from the Hubitat hub.\"\"\"\n if event.attribute in _TRIGGER_ATTRS:\n evt = dict(event)\n evt[ATTR_ATTRIBUTE] = _TRIGGER_ATTR_MAP[event.attribute]\n evt[ATTR_HUB] = self._hub.id\n evt[ATTR_HA_DEVICE_ID] = self._id\n self._hub.hass.bus.async_fire(CONF_HUBITAT_EVENT, evt)\n _LOGGER.debug(\"Emitted event %s\", evt)\n\n\nclass HubitatEntity(HubitatBase, Entity):\n \"\"\"An entity related to a Hubitat device.\"\"\"\n\n # Hubitat will push device updates\n should_poll = False\n\n @property\n def is_disabled(self) -> bool:\n \"\"\"Indicate whether this device is currently disabled.\"\"\"\n if self.registry_entry:\n return self.registry_entry.disabled_by is not None\n return False\n\n async def async_update(self) -> None:\n \"\"\"Fetch new data for this device.\"\"\"\n await self._hub.refresh_device(self.device_id)\n\n async def send_command(\n self, command: str, *args: Optional[Union[int, str]]\n ) -> None:\n \"\"\"Send a command to this device.\"\"\"\n arg = \",\".join([str(a) for a in args]) if args else None\n await self._hub.send_command(self.device_id, command, arg)\n _LOGGER.debug(\"sent %s to %s\", command, self.device_id)\n\n def handle_event(self, event: Event) -> None:\n \"\"\"Handle a device event.\"\"\"\n self.update_state()\n super().handle_event(event)\n\n def update_state(self) -> None:\n \"\"\"Request that Home Assistant update this device's state.\"\"\"\n if not self.is_disabled:\n self.async_schedule_update_ha_state()\n\n\nclass HubitatEventEmitter(HubitatBase):\n \"\"\"An event emitter related to a Hubitat device.\"\"\"\n\n async def update_device_registry(self) -> None:\n \"\"\"Register a device for the event emitter.\"\"\"\n # Create a device for the emitter since Home Assistant doesn't\n # automatically do that as it does for entities.\n entry = self._hub.config_entry\n dreg = cast(\n DeviceRegistry, await device_registry.async_get_registry(self._hub.hass)\n )\n dreg.async_get_or_create(config_entry_id=entry.entry_id, **self.device_info)\n _LOGGER.debug(\"Created device for %s\", self)\n\n def __repr__(self) -> str:\n \"\"\"Return the representation.\"\"\"\n return f\"\"\n\n\ndef get_hub(hass: HomeAssistant, config_entry_id: str) -> Hub:\n \"\"\"Get the Hub device associated with a given config entry.\"\"\"\n return hass.data[DOMAIN][config_entry_id]\n\n\nasync def _update_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None:\n await hass.config_entries.async_reload(config_entry.entry_id)\n","sub_path":"custom_components/hubitat/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":16435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"265006097","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\"\"\"\nTest the glm utilities.\n\"\"\"\nfrom __future__ import with_statement\n\nimport os\n\nimport numpy as np\n\nfrom nibabel import load, Nifti1Image, save\n\nfrom nistats.glm import (\n percent_mean_scaling, session_glm, FirstLevelGLM, compute_contrast)\n\nfrom nose.tools import assert_true, assert_equal, assert_raises\nfrom numpy.testing import (assert_array_almost_equal, assert_almost_equal,\n assert_array_equal)\nfrom nibabel.tmpdirs import InTemporaryDirectory\nimport pandas as pd\n\n\n# This directory path\nBASEDIR = os.path.dirname(os.path.abspath(__file__))\nFUNCFILE = os.path.join(BASEDIR, 'functional.nii.gz')\n\n\ndef write_fake_fmri_data(shapes, rk=3, affine=np.eye(4)):\n mask_file, fmri_files, design_files = 'mask.nii', [], []\n for i, shape in enumerate(shapes):\n fmri_files.append('fmri_run%d.nii' % i)\n data = np.random.randn(*shape)\n data[1:-1, 1:-1, 1:-1] += 100\n save(Nifti1Image(data, affine), fmri_files[-1])\n design_files.append('dmtx_%d.csv' % i)\n pd.DataFrame(np.random.randn(shape[3], rk),\n columns=['', '', '']).to_csv(design_files[-1])\n save(Nifti1Image((np.random.rand(*shape[:3]) > .5).astype(np.int8),\n affine), mask_file)\n return mask_file, fmri_files, design_files\n\n\ndef generate_fake_fmri_data(shapes, rk=3, affine=np.eye(4)):\n fmri_data = []\n design_matrices = []\n for i, shape in enumerate(shapes):\n data = np.random.randn(*shape)\n data[1:-1, 1:-1, 1:-1] += 100\n fmri_data.append(Nifti1Image(data, affine))\n design_matrices.append(pd.DataFrame(np.random.randn(shape[3], rk),\n columns=['', '', '']))\n mask = Nifti1Image((np.random.rand(*shape[:3]) > .5).astype(np.int8),\n affine)\n return mask, fmri_data, design_matrices\n\n\ndef test_high_level_glm_one_session():\n # New API\n shapes, rk = [(7, 8, 9, 15)], 3\n mask, fmri_data, design_matrices = generate_fake_fmri_data(shapes, rk)\n\n single_session_model = FirstLevelGLM(mask=None).fit(\n fmri_data[0], design_matrices[0])\n assert_true(isinstance(single_session_model.masker_.mask_img_,\n Nifti1Image))\n\n single_session_model = FirstLevelGLM(mask=mask).fit(\n fmri_data[0], design_matrices[0])\n z1, = single_session_model.transform(np.eye(rk)[:1])\n assert_true(isinstance(z1, Nifti1Image))\n\n\ndef test_high_level_glm_with_data():\n # New API\n shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3\n mask, fmri_data, design_matrices = write_fake_fmri_data(shapes, rk)\n\n multi_session_model = FirstLevelGLM(mask=None).fit(\n fmri_data, design_matrices)\n n_voxels = multi_session_model.masker_.mask_img_.get_data().sum()\n z_image, = multi_session_model.transform([np.eye(rk)[1]] * 2)\n assert_equal(np.sum(z_image.get_data() != 0), n_voxels)\n assert_true(z_image.get_data().std() < 3. )\n\n # with mask\n multi_session_model = FirstLevelGLM(mask=mask).fit(\n fmri_data, design_matrices)\n z_image, effect_image, variance_image = multi_session_model.transform(\n [np.eye(rk)[:2]] * 2, output_effects=True, output_variance=True)\n assert_array_equal(z_image.get_data() == 0., load(mask).get_data() == 0.)\n assert_true(\n (variance_image.get_data()[load(mask).get_data() > 0, 0] > .001).all())\n\n\ndef test_high_level_glm_with_paths():\n # New API\n shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 14)), 3\n with InTemporaryDirectory():\n mask_file, fmri_files, design_files = write_fake_fmri_data(shapes, rk)\n multi_session_model = FirstLevelGLM(mask=None).fit(\n fmri_files, design_files)\n z_image, = multi_session_model.transform([np.eye(rk)[1]] * 2)\n assert_array_equal(z_image.get_affine(), load(mask_file).get_affine())\n assert_true(z_image.get_data().std() < 3.)\n # Delete objects attached to files to avoid WindowsError when deleting\n # temporary directory\n del z_image, fmri_files, multi_session_model\n\n\ndef test_high_level_glm_null_contrasts():\n # test that contrast computation is resilient to 0 values.\n # new API\n shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 19)), 3\n mask, fmri_data, design_matrices = generate_fake_fmri_data(shapes, rk)\n\n multi_session_model = FirstLevelGLM(mask=None).fit(\n fmri_data, design_matrices)\n single_session_model = FirstLevelGLM(mask=None).fit(\n fmri_data[0], design_matrices[0])\n z1, = multi_session_model.transform([np.eye(rk)[:1], np.zeros((1, rk))],\n output_z=False, output_stat=True)\n z2, = single_session_model.transform([np.eye(rk)[:1]],\n output_z=False, output_stat=True)\n np.testing.assert_almost_equal(z1.get_data(), z2.get_data())\n\n\ndef test_session_glm():\n # New API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n\n # ols case\n labels, results = session_glm(Y, X, 'ols')\n assert_array_equal(labels, np.zeros(n))\n assert_equal(list(results.keys()), [0.0])\n assert_equal(results[0.0].theta.shape, (q, n))\n assert_almost_equal(results[0.0].theta.mean(), 0, 1)\n assert_almost_equal(results[0.0].theta.var(), 1. / p, 1)\n\n # ar(1) case\n labels, results = session_glm(Y, X, 'ar1')\n assert_equal(len(labels), n)\n assert_true(len(results.keys()) > 1)\n tmp = sum([val.theta.shape[1] for val in results.values()])\n assert_equal(tmp, n)\n\n # non-existant case\n assert_raises(ValueError, session_glm, Y, X, 'ar2')\n assert_raises(ValueError, session_glm, Y, X.T)\n\n\ndef test_Tcontrast():\n # new API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n labels, results = session_glm(Y, X, 'ar1')\n con_val = np.eye(q)[0]\n z_vals = compute_contrast(labels, results, con_val).z_score()\n assert_almost_equal(z_vals.mean(), 0, 0)\n assert_almost_equal(z_vals.std(), 1, 0)\n\n\ndef test_Fcontrast():\n # new API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n for model in ['ols', 'ar1']:\n labels, results = session_glm(Y, X, model)\n for con_val in [np.eye(q)[0], np.eye(q)[:3]]:\n z_vals = compute_contrast(\n labels, results, con_val, contrast_type='F').z_score()\n assert_almost_equal(z_vals.mean(), 0, 0)\n assert_almost_equal(z_vals.std(), 1, 0)\n\n\ndef test_t_contrast_add():\n # new API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n lab, res = session_glm(Y, X, 'ols')\n c1, c2 = np.eye(q)[0], np.eye(q)[1]\n con = compute_contrast(lab, res, c1) + compute_contrast(lab, res, c2)\n z_vals = con.z_score()\n assert_almost_equal(z_vals.mean(), 0, 0)\n assert_almost_equal(z_vals.std(), 1, 0)\n\n\ndef test_F_contrast_add():\n # new API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n lab, res = session_glm(Y, X, 'ar1')\n c1, c2 = np.eye(q)[:2], np.eye(q)[2:4]\n con = compute_contrast(lab, res, c1) + compute_contrast(lab, res, c2)\n z_vals = con.z_score()\n assert_almost_equal(z_vals.mean(), 0, 0)\n assert_almost_equal(z_vals.std(), 1, 0)\n\n # first test with dependent contrast\n con1 = compute_contrast(lab, res, c1)\n con2 = compute_contrast(lab, res, c1) + compute_contrast(lab, res, c1)\n assert_almost_equal(con1.effect * 2, con2.effect)\n assert_almost_equal(con1.variance * 2, con2.variance)\n assert_almost_equal(con1.stat() * 2, con2.stat())\n\n\ndef test_contrast_mul():\n # new API\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n lab, res = session_glm(Y, X, 'ar1')\n for c1 in [np.eye(q)[0], np.eye(q)[:3]]:\n con1 = compute_contrast(lab, res, c1)\n con2 = con1 * 2\n assert_almost_equal(con1.effect * 2, con2.effect)\n # assert_almost_equal(con1.variance * 2, con2.variance) FIXME\n # assert_almost_equal(con1.stat() * 2, con2.stat()) FIXME\n assert_almost_equal(con1.z_score(), con2.z_score())\n\n\ndef test_contrast_values():\n # new API\n # but this test is circular and should be removed\n n, p, q = 100, 80, 10\n X, Y = np.random.randn(p, q), np.random.randn(p, n)\n lab, res = session_glm(Y, X, 'ar1', bins=1)\n # t test\n cval = np.eye(q)[0]\n con = compute_contrast(lab, res, cval)\n t_ref = list(res.values())[0].Tcontrast(cval).t\n assert_almost_equal(np.ravel(con.stat()), t_ref)\n # F test\n cval = np.eye(q)[:3]\n con = compute_contrast(lab, res, cval)\n F_ref = list(res.values())[0].Fcontrast(cval).F\n # Note that the values are not strictly equal,\n # this seems to be related to a bug in Mahalanobis\n assert_almost_equal(np.ravel(con.stat()), F_ref, 3)\n\n\ndef test_scaling():\n \"\"\"Test the scaling function\"\"\"\n shape = (400, 10)\n u = np.random.randn(*shape)\n mean = 100 * np.random.rand(shape[1]) + 1\n Y = u + mean\n Y_, mean_ = percent_mean_scaling(Y)\n assert_almost_equal(Y_.mean(0), 0, 5)\n assert_almost_equal(mean_, mean, 0)\n assert_true(Y.std() > 1)\n\n\ndef test_fmri_inputs():\n # Test processing of FMRI inputs\n with InTemporaryDirectory():\n shapes = ((7, 8, 9, 10),)\n mask, FUNCFILE, _ = write_fake_fmri_data(shapes)\n FUNCFILE = FUNCFILE[0]\n func_img = load(FUNCFILE)\n T = func_img.shape[-1]\n des = pd.DataFrame(np.ones((T, 1)), columns=[''])\n des_fname = 'design.csv'\n des.to_csv(des_fname)\n for fi in func_img, FUNCFILE:\n for d in des, des_fname:\n FirstLevelGLM().fit(fi, d)\n FirstLevelGLM(mask=None).fit([fi], d)\n FirstLevelGLM(mask=mask).fit(fi, [d])\n FirstLevelGLM(mask=mask).fit([fi], [d])\n FirstLevelGLM(mask=mask).fit([fi, fi], [d, d])\n FirstLevelGLM(mask=None).fit((fi, fi), (d, d))\n assert_raises(\n ValueError, FirstLevelGLM(mask=None).fit, [fi, fi], d)\n assert_raises(\n ValueError, FirstLevelGLM(mask=None).fit, fi, [d, d])\n","sub_path":"nistats/tests/test_glm.py","file_name":"test_glm.py","file_ext":"py","file_size_in_byte":10300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"90809482","text":"from django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nfrom django.urls import reverse\n\nfrom azbankgateways import bankfactories, models as bank_models, default_settings as settings\n\nfrom .models import Payment\n\n# Create your views here.\n\ndef check_payment_successful(request):\n if Payment.status ==True:\n return HttpResponse(\"pardakht ba movafaghiat anjam shod\")\n\n else:\n return HttpResponse(\"پرداخت دچار خطا شد\")\n\n\n\n\ndef go_to_gateway_view(request):\n # خواندن مبلغ از هر جایی که مد نظر است\n amount = 1000\n # تنظیم شماره موبایل کاربر از هر جایی که مد نظر است\n user_mobile_number = '+989112221234' # اختیاری\n\n factory = bankfactories.BankFactory()\n bank = factory.create() # or factory.create(bank_models.BankType.BMI) or set identifier\n bank.set_request(request)\n bank.set_amount(amount)\n # یو آر ال بازگشت به نرم افزار برای ادامه فرآیند\n bank.set_client_callback_url(reverse('callback-gateway'))\n bank.set_mobile_number(user_mobile_number) # اختیاری\n\n # در صورت تمایل اتصال این رکورد به رکورد فاکتور یا هر چیزی که بعدا بتوانید ارتباط بین محصول یا خدمات را با این\n # پرداخت برقرار کنید.\n bank_record = bank.ready()\n\n # هدایت کاربر به درگاه بانک\n return bank.redirect_gateway()\n\n","sub_path":"payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"359921572","text":"#!/bin/python3\n\n\ndef plus_minus(arr):\n \"\"\" Returns formatted strings with the ratio of positive,\n negative and zero elements in the array \"\"\"\n\n num_positive = 0\n num_negative = 0\n num_zeros = 0\n\n for i in range(n):\n if arr[i] > 0:\n num_positive += 1\n elif arr[i] < 0:\n num_negative += 1\n else:\n num_zeros += 1\n\n ratio_positive = num_positive / n\n ratio_negative = num_negative / n\n ratio_zeros = num_zeros / n\n\n print(str.format('{0:.6f}', ratio_positive))\n print(str.format('{0:.6f}', ratio_negative))\n print(str.format('{0:.6f}', ratio_zeros))\n\n\nif __name__ == '__main__':\n n = int(input())\n array = list(map(int, input().rstrip().split()))\n\n plus_minus(array)\n","sub_path":"problem_solving/algorithms/warmup/plus_minus.py","file_name":"plus_minus.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"373530807","text":"import os\nimport sys\nimport json\nimport time\n\nfrom queues.executor import ScriptHandler\n\nwith open(sys.argv[1], 'r+') as file_obj:\n crawled_data = json.loads(file_obj.read())\n\nparsed_datas = ['No Data from Script Execution']\ntry:\n error_lines = list()\n for data in crawled_data:\n parsed_data = ScriptHandler(data)._execute_script_function(1)\n # parsed_data = ScriptHandler(data).execute_parse()\n print(parsed_data.keys())\n print(parsed_data['hotel'])\n parsed_datas.append(parsed_data)\n if not parsed_datas:\n error_lines.append('\\nNo Data from Script Execution for Input\\n%s' % json.dumps(data))\nexcept Exception as e:\n import traceback\n crawled_data = None\n type_, value_, traceback_ = sys.exc_info()\n error_lines = traceback.format_tb(traceback_)\n\nif parsed_datas:\n file_data = parsed_datas\n file_identifier = 'parsed_data'\nelse:\n file_data = \"\\n\".join(error_lines)\n file_identifier = 'error_data'\n\nfrom pdb import set_trace; set_trace()\nfile_distincter = time.time()\nwith open('%s_%s_%s.json' % (crawled_data['ParserScript'], file_identifier, file_distincter), 'w+') as file_obj:\n print(\"filename\")\n print(os.path.abspath('') + '/' + file_obj.name)\n file_obj.write(json.dumps(file_data))\n\n","sub_path":"eCube_Hotel_2/HotelMessaging/AetosParsingService/start_test.py","file_name":"start_test.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"466633037","text":"from unittest import TestCase\n\nimport ahocorasick\n\nfrom dark.reads import AARead\n\nfrom light.features import Landmark\nimport light.landmarks.ac_alpha_helix_3_10\nfrom light.landmarks import AC_AlphaHelix_3_10\nfrom light.parameters import DatabaseParameters\n\n\ndef setAlphaHelices_3_10(helices):\n \"\"\"\n Make an Aho Corasick matcher for the given helices and monkey patch\n light.landmarks.ac_alpha_helix_3_10 to use it.\n Also set the acAlphaHelix310Filename database parameter to 'xxx', to make\n sure that the right Aho Corasick matcher is used.\n\n This function is used by tests that want to check against a specific\n set of helices instead of the full set.\n\n @param helices: An iterable of C{str} helix sequences.\n\n @return: A C{light.landmarks.ac_alpha_helix_3_10} instance with its\n acAlphaHelix310Filename set to 'xxx'.\n \"\"\"\n ac = ahocorasick.Automaton(ahocorasick.STORE_LENGTH)\n\n if ahocorasick.unicode:\n add = ac.add_word\n else:\n # The Aho Corasick module has been compiled without unicode\n # support, to reduce its memory use. Arrange to give it bytes.\n def add(s):\n \"\"\"\n Add a string to an Aho Corasick automaton as bytes.\n\n @param s: A C{str} to add.\n \"\"\"\n ac.add_word(s.encode('utf-8'))\n\n list(map(add, helices))\n ac.make_automaton()\n light.landmarks.ac_alpha_helix_3_10._AC = ac\n dbParams = DatabaseParameters(acAlphaHelix310Filename='xxx')\n return AC_AlphaHelix_3_10(dbParams)\n\n\nclass TestACAlphaHelix_3_10(TestCase):\n \"\"\"\n Tests for the light.landmarks.ac_alpha_helix_3_10.AC_AlphaHelix_3_10 class.\n \"\"\"\n def setUp(self):\n \"\"\"\n Keep track of the original Aho Corasick matcher and stored filename so\n we can restore them after each test. This allows tests to install their\n own matcher and filename without breaking things for tests that want to\n use the original.\n \"\"\"\n self.originalAC = light.landmarks.ac_alpha_helix_3_10._AC\n self.originalFile = \\\n light.landmarks.ac_alpha_helix_3_10._STORED_AC_FILENAME\n\n def tearDown(self):\n \"\"\"\n Restore the original Aho Corasick state machine.\n \"\"\"\n light.landmarks.ac_alpha_helix_3_10._AC = self.originalAC\n light.landmarks.ac_alpha_helix_3_10._STORED_AC_FILENAME = \\\n self.originalFile\n\n def testFindNothing(self):\n \"\"\"\n The find method must return an empty generator when no helix is\n present.\n \"\"\"\n finder = setAlphaHelices_3_10(['XXX', 'YYY'])\n read = AARead('id', 'FRFRFRFRFRFRFRFRFRFF')\n result = list(finder.find(read))\n self.assertEqual([], result)\n\n def testFullMatch(self):\n \"\"\"\n The find method must return the full read sequence when it fully\n matches an alpha helix.\n \"\"\"\n finder = setAlphaHelices_3_10(['FFFF'])\n read = AARead('id', 'FFFF')\n result = list(finder.find(read))\n self.assertEqual([Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 4)],\n result)\n\n def testFindContiguousMatches(self):\n \"\"\"\n The find method must find matches that are contiguous.\n \"\"\"\n finder = setAlphaHelices_3_10(['RRR', 'FFF'])\n read = AARead('id', 'FFFRRR')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 3),\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 3, 3),\n ],\n sorted(result))\n\n def testFindSeparatedMatches(self):\n \"\"\"\n The find method must find matches that are separated.\n \"\"\"\n finder = setAlphaHelices_3_10(['RRRRR', 'FFF'])\n read = AARead('id', 'FFFMMRRRRR')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 3),\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 5, 5),\n ],\n sorted(result))\n\n def testFindPartiallyOverlappingMatches(self):\n \"\"\"\n The find method must return overlapping helices.\n \"\"\"\n finder = setAlphaHelices_3_10(['FFFFR', 'FRMMM'])\n read = AARead('id', 'FFFFRMMM')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 5),\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 3, 5),\n ],\n sorted(result))\n\n def testFindCompletelyOverlappingMatches(self):\n \"\"\"\n The find method must return all helices, including those that overlap.\n \"\"\"\n finder = setAlphaHelices_3_10(['FF', 'FFF'])\n read = AARead('id', 'FFF')\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 2),\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 0, 3),\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 1, 2),\n ],\n sorted(result))\n\n def testFindUsingBuiltInAlphaHelices(self):\n \"\"\"\n The find method must be able to find helices in the default alpha\n helix substring file loaded by light/landmarks/ac_alpha_helix_3_10.py\n (in data/ac-alpha-helix-3-10-substrings-1-0.5).\n \"\"\"\n read = AARead('id', 'RCELARTLKRAHTYT')\n finder = AC_AlphaHelix_3_10()\n result = list(finder.find(read))\n self.assertEqual(\n [\n Landmark('AC AlphaHelix_3_10', 'ACAH310', 10, 5),\n ],\n sorted(result))\n","sub_path":"test/landmarks/test_ac_alpha_helix_3_10.py","file_name":"test_ac_alpha_helix_3_10.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"522869421","text":"\"\"\"\nUsage ::\n\n # Import\n import psana.pscalib.calib.MDBWebUtils as wu\n from psana.pscalib.calib.MDBWebUtils import calib_constants\n\n _ = wu.request(url, query=None)\n _ = wu.database_names(url=cc.URL)\n _ = wu.collection_names(dbname, url=cc.URL)\n _ = wu.find_docs(dbname, colname, query={'ctype':'pedestals'}, url=cc.URL)\n _ = wu.find_doc(dbname, colname, query={'ctype':'pedestals'}, url=cc.URL)\n _ = wu.select_latest_doc(docs, query) :\n _ = wu.get_doc_for_docid(dbname, colname, docid, url=cc.URL)\n _ = wu.get_data_for_id(dbname, dataid, url=cc.URL)\n _ = wu.get_data_for_docid(dbname, colname, docid, url=cc.URL)\n _ = wu.get_data_for_doc(dbname, colname, doc, url=cc.URL)\n data,doc = wu.calib_constants(det, exp=None, ctype='pedestals', run=None, time_sec=None, vers=None, url=cc.URL)\n d = wu.calib_constants_all_types(det, exp=None, run=None, time_sec=None, vers=None, url=cc.URL)\n d = {ctype:(data,doc),}\n\n test_*()\n\"\"\"\n#------------------------------\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport numpy as np\n\nimport psana.pscalib.calib.CalibConstants as cc\nfrom requests import get, post, delete #put\nimport json\nfrom time import time\nfrom numpy import fromstring\n#from psana.pscalib.calib.MDBUtils import dbnames_collection_query, object_from_data_string\nimport psana.pscalib.calib.MDBUtils as mu\n\n#------------------------------\n#------------------------------\n\ndef request(url, query=None) :\n #logger.debug('==== query: %s' % str(query))\n t0_sec = time()\n r = get(url, query)\n dt = time()-t0_sec\n logger.debug('CONSUMED TIME by request %.6f sec\\n for url=%s query=%s' % (dt, url, str(query)))\n return r\n\n#------------------------------\n\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/test_db\"\ndef database_names(url=cc.URL) :\n \"\"\"Returns list of database names for url.\n \"\"\"\n r = request(url)\n return r.json()\n\n#------------------------------\n\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/test_db/test_coll\"\ndef collection_names(dbname, url=cc.URL) :\n \"\"\"Returns list of collection names for dbname and url.\n \"\"\"\n r = request('%s/%s'%(url,dbname))\n return r.json()\n\n#------------------------------\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/test_db/test_coll?query_string=%7B%20%22item%22...\"\ndef find_docs(dbname, colname, query={'ctype':'pedestals'}, url=cc.URL) :\n \"\"\"Returns list of documents for query, e.g. query={'ctype':'pedestals', \"run\":{ \"$gte\":80}}\n \"\"\"\n query_string=str(query).replace(\"'\",'\"')\n logger.debug('find_docs query: %s' % query_string)\n r = request('%s/%s/%s'%(url,dbname,colname),{\"query_string\": query_string})\n try:\n return r.json()\n except:\n msg = '**** find_docs responce: %s' % str(r)\\\n + '\\n conversion to json failed, return None for query: %s' % str(query)\n logger.warning(msg)\n return None\n\n#------------------------------\n\ndef find_doc(dbname, colname, query={'ctype':'pedestals'}, url=cc.URL) :\n \"\"\"Returns document for query.\n 1. finds all documents for query\n 2. select the latest for run or time_sec\n \"\"\"\n docs = find_docs(dbname, colname, query, url)\n if docs is None : return None\n\n return select_latest_doc(docs, query)\n\n#------------------------------\n\ndef select_latest_doc(docs, query) :\n \"\"\"Returns a single document for query selected by time_sec (if available) or run\n \"\"\"\n if len(docs)==0 :\n # commented out by cpo since this happens routinely the way\n # that Mona is fetching calibration constants in psana.\n #logger.warning('find_docs returns list of length 0 for query: %s' % query)\n return None\n\n qkeys = query.keys()\n key_sort = 'time_sec' if 'time_sec' in qkeys else 'run'\n\n logger.debug('select_latest_doc: %s\\nkey_sort: %s' % (str(query), key_sort))\n vals = [int(d[key_sort]) for d in docs]\n vals.sort(reverse=True)\n logger.debug('find_doc values: %s' % str(vals))\n val_sel = int(vals[0])\n logger.debug('find_doc select document for %s: %s' % (key_sort,val_sel))\n for d in docs : \n if d[key_sort]==val_sel : \n return d\n return None\n\n#------------------------------\n\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/cdb_cxic0415/cspad_0001/5b6893e81ead141643fe4344\"\ndef get_doc_for_docid(dbname, colname, docid, url=cc.URL) :\n \"\"\"Returns document for docid.\n \"\"\"\n r = request('%s/%s/%s/%s'%(url,dbname,colname,docid))\n return r.json()\n\n#------------------------------\n\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/cdb_cxic0415/gridfs/5b6893d91ead141643fe3f6a\" \ndef get_data_for_id(dbname, dataid, url=cc.URL) :\n \"\"\"Returns raw data from GridFS, at this level there is no info for parsing.\n \"\"\"\n r = request('%s/%s/gridfs/%s'%(url,dbname,dataid))\n logger.debug('get_data_for_docid:'\\\n +'\\n r.status_code: %s\\n r.headers: %s\\n r.encoding: %s\\n r.content: %s...\\n' % \n (str(r.status_code), str(r.headers), str(r.encoding), str(r.content[:50])))\n return r.content\n\n#------------------------------\n\ndef get_data_for_docid(dbname, colname, docid, url=cc.URL) :\n \"\"\"Returns data from GridFS using docid.\n \"\"\"\n doc = get_doc_for_docid(dbname, colname, docid, url)\n logger.debug('get_data_for_docid: %s' % str(doc))\n return get_data_for_doc(dbname, colname, doc, url)\n\n#------------------------------\n\n# curl -s \"https://pswww.slac.stanford.edu/calib_ws/cdb_cxic0415/cspad_0001/gridfs/5b6893e81ead141643fe4344\"\ndef get_data_for_doc(dbname, colname, doc, url=cc.URL) :\n \"\"\"Returns data from GridFS using doc.\n \"\"\"\n logger.debug('get_data_for_doc: %s', str(doc))\n idd = doc.get('id_data', None)\n if idd is None :\n logger.debug(\"get_data_for_doc: key 'id_data' is missing in selected document...\")\n return None\n\n r2 = request('%s/%s/gridfs/%s'%(url,dbname,idd))\n s = r2.content\n\n return mu.object_from_data_string(s, doc)\n\n#------------------------------\n\ndef calib_constants(det, exp=None, ctype='pedestals', run=None, time_sec=None, vers=None, url=cc.URL) :\n \"\"\"Returns calibration constants and document with metadata for specified parameters. \n To get meaningful constants, at least a few parameters must be specified, e.g.:\n - det, ctype, time_sec\n - det, ctype, version\n - det, exp, ctype, run\n - det, exp, ctype, time_sec\n - det, exp, ctype, run, version\n etc...\n \"\"\"\n db_det, db_exp, colname, query = mu.dbnames_collection_query(det, exp, ctype, run, time_sec, vers)\n logger.debug('get_constants: %s %s %s %s' % (db_det, db_exp, colname, str(query)))\n dbname = db_det if exp is None else db_exp\n doc = find_doc(dbname, colname, query, url)\n if doc is None :\n # commented out by cpo since this happens routinely the way\n # that Mona is fetching calibration constants in psana.\n #logger.warning('document is not available for query: %s' % str(query))\n return (None, None)\n return (get_data_for_doc(dbname, colname, doc, url), doc)\n\n#------------------------------\n\ndef calib_constants_all_types(det, exp=None, run=None, time_sec=None, vers=None, url=cc.URL) :\n \"\"\" returns constants for all ctype-s\n \"\"\"\n ctype=None\n db_det, db_exp, colname, query = mu.dbnames_collection_query(det, exp, ctype, run, time_sec, vers)\n dbname = db_det if exp is None else db_exp\n docs = find_docs(dbname, colname, query, url)\n #logger.debug('find_docs: number of docs found: %d' % len(docs))\n if docs is None : return None\n\n ctypes = set([d.get('ctype',None) for d in docs])\n ctypes.discard(None)\n logger.debug('calib_constants_all_types - found ctypes: %s' % str(ctypes))\n\n resp = {}\n for ct in ctypes :\n docs_for_type = [d for d in docs if d.get('ctype',None)==ct]\n doc = select_latest_doc(docs_for_type, query)\n if doc is None : continue\n resp[ct] = (get_data_for_doc(dbname, colname, doc, url), doc)\n\n return resp\n\n#------------------------------\n#-------- 2020-04-30 ----------\n#------------------------------\n\ndef add_data_from_file(dbname, fname, sfx=None, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\"Adds data from file to the database/gridfs.\n \"\"\"\n _sfx = sfx if sfx is not None else fname.rsplit('.')[-1]\n files = [('files', (fname, open(fname, 'rb'), 'image/'+_sfx))]\n resp = post(url+dbname+'/gridfs/', headers=krbheaders, files=files)\n logger.debug('add_data_from_file: %s to %s/gridfs/ resp: %s type: %s' % (fname, dbname, resp.text, type(resp)))\n #jdic = resp.json() # type \n return resp.json().get('_id',None)\n\n#------------------------------\n\ndef add_data(dbname, data, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\"Adds binary data to the database/gridfs.\n \"\"\"\n import io\n headers = dict(krbheaders) # krbheaders \n headers['Content-Type'] = 'application/octet-stream'\n f = io.BytesIO(mu.encode_data(data)) # io.StringIO(data)\n d = f.read()\n logger.debug('add_data byte-data:',d)\n resp = post(url+dbname+'/gridfs/', headers=headers, data=d)\n logger.debug('add_data: to %s/gridfs/ resp: %s' % (dbname, resp.text))\n return resp.json().get('_id',None)\n\n#------------------------------\n\ndef add_document(dbname, colname, doc, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\"Adds document to database collection.\n \"\"\"\n resp = post(url+dbname+'/'+colname+'/', headers=krbheaders, json=doc)\n logger.debug('add_document: %s\\n to %s/%s resp: %s' % (str(doc), dbname, colname, resp.text))\n return resp.json().get('_id',None)\n\n#------------------------------\n\ndef add_data_and_doc(data, dbname, colname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS, **kwargs) :\n \"\"\"Adds data and document to the db\n \"\"\"\n id_data = add_data(dbname, data, url, krbheaders)\n if id_data is None :\n logger.warning('id_data is None')\n return None\n doc = mu.docdic(data, id_data, **kwargs)\n id_doc = add_document(dbname, colname, doc, url, krbheaders)\n if id_doc is None :\n logger.warning('id_doc is None')\n return None\n return id_data, id_doc\n\n#------------------------------\n\n\n\n\"\"\"\ndef add_data_and_two_docs(data, exp, det, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS, **kwargs) :\n '''TBD: Adds data and document to experiment and detector data bases\n '''\n dbname_exp = mu.db_prefixed_name(exp)\n\n\n id_data = add_data(dbname, data, url, krbheaders)\n if id_data is None :\n logger.warning('id_data is None')\n return None\n doc = mu.docdic(data, id_data, **kwargs)\n id_doc = add_document(dbname, colname, doc, url, krbheaders)\n if id_doc is None :\n logger.warning('id_doc is None')\n return None\n return id_data, id_doc\n\"\"\"\n\n\n\n\n\n\n#------------------------------\n\n\n\"\"\"\n\ndef insert_data_and_two_docs(data, fs_exp, fs_det, col_exp, col_det, **kwargs) :\n\n t0_sec = time()\n id_data_exp = insert_data(data, fs_exp)\n id_data_det = insert_data(data, fs_det)\n\n msg = 'Insert data time %.6f sec' % (time()-t0_sec)\\\n + '\\n - in fs_exp %s id_data_exp: %s' % (fs_exp, id_data_exp)\\\n + '\\n - in fs_det %s id_data_det: %s' % (fs_det, id_data_det)\n logger.debug(msg)\n\n doc = docdic(data, id_data_exp, **kwargs)\n logger.debug(doc_info(doc, fmt=' %s:%s')) #sep='\\n %16s : %s'\n\n t0_sec = time()\n id_exp = insert_document(doc, col_exp)\n doc['id_data'] = id_data_det # override\n doc['id_exp'] = id_exp # add\n id_det = insert_document(doc, col_det)\n\n msg = 'Insert 2 docs time %.6f sec' % (time()-t0_sec)\n if col_exp is not None : msg += '\\n - in collection %s id_exp : %s' % (col_exp.name, id_exp)\n if col_det is not None : msg += '\\n - in collection %s id_det : %s' % (col_det.name, id_det)\n logger.debug(msg)\n\n return id_data_exp, id_data_det, id_exp, id_det\n\"\"\"\n\n\n\n\n\n\n#------------------------------\n\ndef delete_database(dbname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\"Deletes database for (str) dbname, e.g. dbname='cdb_opal_0001'.\n \"\"\"\n resp = delete(url+dbname, headers=krbheaders)\n logger.debug(resp.text)\n return resp\n\n#------------------------------\n\ndef delete_collection(dbname, colname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\" Deletes collection from database.\n \"\"\"\n resp = delete(url+dbname+'/'+colname, headers=krbheaders)\n logger.debug(resp.text)\n return resp\n\n#------------------------------\n\ndef delete_document(dbname, colname, doc_id, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) :\n \"\"\"Deletes document for specified _id from database/collection.\n \"\"\"\n resp = delete(url+dbname+'/'+colname+'/'+ doc_id, headers=krbheaders)\n logger.debug(resp.text)\n return resp\n\n#------------------------------\n#--------- TESTS ------------\n#------------------------------\n\nif __name__ == \"__main__\" :\n\n TEST_FNAME_PNG = '/reg/g/psdm/detector/data2_test/misc/small_img.png'\n\n def test_database_names() :\n print('test_database_names:', database_names())\n\n#------------------------------\n\n def test_collection_names() :\n dbname = sys.argv[2] if len(sys.argv) > 2 else 'cdb_cspad_0001'\n print('test_collection_names:', collection_names(dbname))\n\n#------------------------------\n\n def test_find_docs() :\n docs = find_docs('cdb_cspad_0001', 'cspad_0001')\n print('find_docs: number of docs found: %d' % len(docs))\n print('test_find_docs returns:', type(docs))\n for i,d in enumerate(docs) :\n print('%04d %12s %10s run:%04d time_sec:%10s %s' % (i, d['ctype'], d['experiment'], d['run'], str(d['time_sec']), d['detector']))\n\n if len(docs)==0 : return\n doc0 = docs[0]\n print('doc0 type:', type(doc0))\n print('doc0:', doc0)\n print('doc0.keys():', doc0.keys())\n\n#------------------------------\n\n def test_get_random_doc_and_data_ids(det='cspad_0001') :\n dbname = mu.db_prefixed_name(det)\n colname = det\n doc = find_doc(dbname, colname, query={'ctype':'pedestals'})\n print('Pick up any doc for dbname:%s colname:%s pedestals: ' % (dbname,colname))\n print('Document: %s' % str(doc))\n id_doc = doc.get('_id', None)\n id_data = doc.get('id_data', None)\n print('_id : %s id_data : %s' % (id_doc, id_data))\n return id_doc, id_data, dbname, colname\n\n#------------------------------\n\n def test_find_doc() :\n #doc = find_doc('cdb_cxic0415', 'cspad_0001', query={'ctype':'pedestals', 'run':{'$lte':40}})\n #print('====> test_find_doc for run: %s' % str(doc))\n\n #doc = find_doc('cdb_cxid9114', 'cspad_0001', query={'ctype':'pedestals', 'time_sec':{'$lte':1402851400}})\n #print('====> test_find_doc for time_sec: %s' % str(doc))\n\n _,_,_,_ = test_get_random_doc_and_data_ids(det='cspad_0001') \n _,_,_,_ = test_get_random_doc_and_data_ids(det='cspad_0002') \n\n#------------------------------\n\n def test_get_data_for_id() :\n id_doc, id_data, dbname, colname = test_get_random_doc_and_data_ids(det='cspad_0001')\n o = get_data_for_id(dbname, id_data)\n print('test_get_data_for_id: r.content raw data: %s ...' % str(o[:500]))\n\n#------------------------------\n\n def test_get_data_for_docid() :\n id_doc, id_data, dbname, colname = test_get_random_doc_and_data_ids(det='cspad_0001')\n o = get_data_for_docid(dbname, colname, id_doc)\n #o = get_data_for_docid('cdb_cxid9114', 'cspad_0001', '5b6cdde71ead144f115319be')\n print_ndarr(o, 'test_get_data_for_docid o:', first=0, last=10)\n\n#------------------------------\n\n def test_dbnames_collection_query() :\n det='cspad_0001'\n db_det, db_exp, colname, query = mu.dbnames_collection_query(det, exp=None, ctype='pedestals', run=50, time_sec=None, vers=None)\n print('test_dbnames_collection_query:', db_det, db_exp, colname, query)\n\n#------------------------------\n\n def test_calib_constants() :\n det = 'cspad_0001'\n data, doc = calib_constants('cspad_0001', exp='cxic0415', ctype='pedestals', run=50, time_sec=None, vers=None) #, url=cc.URL)\n print_ndarr(data, '==== test_calib_constants', first=0, last=5)\n print('==== doc: %s' % str(doc))\n\n#------------------------------\n\n def test_calib_constants_text() :\n det = 'cspad_0001'\n data, doc = calib_constants(det, exp='cxic0415', ctype='geometry', run=50, time_sec=None, vers=None) #, url=cc.URL)\n print('==== test_calib_constants_text data:', data)\n print('==== doc: %s' % str(doc))\n\n det = 'tmo_quadanode'\n data, doc = calib_constants(det, exp='amox27716', ctype='calibcfg', run=100, time_sec=None, vers=None) #, url=cc.URL)\n print('==== test_calib_constants_text data:', data)\n print('==== doc: %s' % str(doc))\n\n#------------------------------\n\n def test_calib_constants_dict() :\n det = 'opal1000_0059'\n #data, doc = calib_constants(det, exp='amox23616', ctype='lasingoffreference', run=60, time_sec=None, vers=None)\n data, doc = calib_constants(det, exp=None, ctype='lasingoffreference', run=60, time_sec=None, vers=None)\n print('==== test_calib_constants_dict data:', data)\n print('XXXX ==== type(data)', type(data))\n print('XXXX ==== type(doc) ', type(doc))\n print('==== doc: %s' % doc)\n\n#------------------------------\n\n def test_calib_constants_all_types() :\n #resp = calib_constants_all_types('tmo_quadanode', exp='amox27716', run=100, time_sec=None, vers=None) #, url=cc.URL)\n\n resp = calib_constants_all_types('pnccd_0001', exp='amo86615', run=200, time_sec=None, vers=None) #, url=cc.URL)\n print('==== test_calib_constants_text data:') #, resp)\n\n for k,v in resp.items() :\n print('ctype:%16s data and meta:' % k, type(v[0]), type(v[1]))\n\n import pickle\n s = pickle.dumps(resp)\n print('IF YOU SEE THIS, dict FOR ctypes SHOULD BE pickle-d')\n\n#------------------------------\n\n def test_insert_constants(expname='test_exp', detname='test_det', ctype='test_ctype', runnum=10, data='test text sampele') :\n \"\"\" Inserts constants using direct MongoDB interface from MDBUtils.\n \"\"\"\n import psana.pyalgos.generic.Utils as gu\n\n print('test_delete_database 1:', database_names())\n #txt = '%s\\nThis is a string\\n to test\\ncalibration storage' % gu.str_tstamp()\n #data, ctype = txt, 'testtext'; logger.debug('txt: %s' % str(data))\n #data, ctype = get_test_nda(), 'testnda'; logger.debug(info_ndarr(data, 'nda'))\n #data, ctype = get_test_dic(), 'testdict'; logger.debug('dict: %s' % str(data))\n\n kwa = {'user' : gu.get_login()}\n t0_sec = time()\n ts = gu.str_tstamp(fmt='%Y-%m-%dT%H:%M:%S%z', time_sec=t0_sec)\n mu.insert_constants('%s - saved at %s'%(data,ts), expname, detname, ctype, runnum+int(tname), int(t0_sec),\\\n time_stamp=ts, **kwa)\n print('test_delete_database 2:', database_names())\n\n#------------------------------\n\n def test_delete_database(dbname='cdb_test_det'):\n print('test_delete_database %s' % dbname)\n print('test_delete_database BEFORE:', database_names())\n resp = delete_database(dbname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('test_delete_database AFTER :', database_names())\n\n#------------------------------\n\n def test_delete_collection(dbname='cdb_test_exp', colname='test_det'):\n print('test_delete_collection %s collection: %s' % (dbname, colname))\n print('test_delete_collection BEFORE:', collection_names(dbname, url=cc.URL))\n resp = delete_collection(dbname, colname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('test_delete_collection AFTER :', collection_names(dbname, url=cc.URL))\n\n#------------------------------\n\n def test_delete_document(dbname='cdb_test_exp', colname='test_det', query={'ctype':'test_ctype'}):\n doc = find_doc(dbname, colname, query=query, url=cc.URL)\n print('find_doc:', doc)\n if doc is None : \n logger.warning('test_delete_document: Non-found document in db:%s col:%s query:%s' % (dbname,colname,str(query)))\n return\n id = doc.get('_id', None)\n print('test_delete_document for doc _id:', id)\n resp = delete_document(dbname, colname, id, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('test_delete_document resp:', resp)\n\n#------------------------------\n\n def test_add_data_from_file(dbname='cdb_test_det', fname=TEST_FNAME_PNG) :\n resp = add_data_from_file(dbname, fname, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('test_add_data_from_file resp: %s of type: %s' % (resp, type(resp)))\n\n#------------------------------\n\n def test_add_data(dbname='cdb_test_det') :\n #data = 'some text is here'\n data = np.array(range(12))\n resp = add_data(dbname, data, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('test_add_data: %s\\n to: %s/gridfs/\\n resp: %s' % (str(data), dbname, resp))\n\n#------------------------------\n\n def test_add_document(dbname='cdb_test_det', colname='test_det', doc={'ctype':'test_ctype'}):\n from psana.pyalgos.generic.Utils import str_tstamp\n doc['time_stamp'] = str_tstamp(fmt='%Y-%m-%dT%H:%M:%S%z')\n resp = add_document(dbname, colname, doc, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS)\n print('\\ntest_add_document: %s\\n to: %s/%s\\n resp: %s' % (str(doc), dbname, colname, resp))\n\n#------------------------------\n\nif __name__ == \"__main__\" :\n def usage() : \n return 'Use command: python %s , where = 0,1,2,...,9' % sys.argv[0]\\\n + '\\n 0: test_database_names'\\\n + '\\n 1: test_collection_names [dbname]'\\\n + '\\n 2: test_find_docs'\\\n + '\\n 3: test_find_doc'\\\n + '\\n 4: test_get_data_for_id'\\\n + '\\n 5: test_get_data_for_docid'\\\n + '\\n 6: test_dbnames_collection_query'\\\n + '\\n 7: test_calib_constants'\\\n + '\\n 8: test_calib_constants_text'\\\n + '\\n 9: test_calib_constants_dict'\\\n + '\\n 10: test_calib_constants_all_types'\\\n + '\\n 11: test_insert_constants [using direct access methods of MDBUtils]'\\\n + '\\n 12: test_delete_database'\\\n + '\\n 13: test_delete_collection'\\\n + '\\n 14: test_delete_document'\\\n + '\\n 15: test_add_data_from_file'\\\n + '\\n 16: test_add_data'\\\n + '\\n 17: test_add_document'\\\n + ''\n\n#------------------------------\n\nif __name__ == \"__main__\" :\n import os\n import sys\n from psana.pyalgos.generic.NDArrUtils import print_ndarr # info_ndarr, print_ndarr\n global print_ndarr\n logging.basicConfig(format='[%(levelname).1s] L%(lineno)04d : %(message)s', level=logging.DEBUG) # logging.INFO\n\n logger.info('\\n%s\\n' % usage())\n tname = sys.argv[1] if len(sys.argv) > 1 else '0'\n logger.info('%s\\nTest %s:' % (50*'_',tname))\n if tname == '0' : test_database_names()\n elif tname == '1' : test_collection_names()\n elif tname == '2' : test_find_docs()\n elif tname == '3' : test_find_doc()\n elif tname == '4' : test_get_data_for_id()\n elif tname == '5' : test_get_data_for_docid()\n elif tname == '6' : test_dbnames_collection_query()\n elif tname == '7' : test_calib_constants()\n elif tname == '8' : test_calib_constants_text()\n elif tname == '9' : test_calib_constants_dict()\n elif tname =='10' : test_calib_constants_all_types()\n elif tname =='11' : test_insert_constants()\n elif tname =='12' : test_delete_database()\n elif tname =='13' : test_delete_collection()\n elif tname =='14' : test_delete_document()\n elif tname =='15' : test_add_data_from_file()\n elif tname =='16' : test_add_data()\n elif tname =='17' : test_add_document()\n\n else : logger.info('Not-recognized test name: %s' % tname)\n sys.exit('End of test %s' % tname)\n\n#------------------------------\n","sub_path":"psana/psana/pscalib/calib/MDBWebUtils.py","file_name":"MDBWebUtils.py","file_ext":"py","file_size_in_byte":23665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"107359717","text":"# Complexity\n# Time: O(N)\n# Space: O(N)\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n chars_idx = {}\n global_answer = local_answer= start = 0\n \n for idx, char in enumerate(s):\n \n if char in chars_idx and chars_idx[char] >= start:\n start = chars_idx[char] + 1\n local_answer = idx - start + 1\n \n else:\n local_answer += 1\n global_answer = max(global_answer, local_answer)\n \n chars_idx[char] = idx\n \n return global_answer\n \n \n","sub_path":"leetcode/3_longest_substring_without_repeating_characters.py","file_name":"3_longest_substring_without_repeating_characters.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"36866874","text":"# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom IPython.display import display, Image, HTML\nimport cv2\n\nTRAIN_DIR = 'train/'\nTEST_DIR = 'test/'\n\n# used for scaling/normalization\nIMAGE_SIZE = 150; # 150x150. Also, 224, 96, 64, and 32 are also common\nCHANNELS = 3\npixel_depth = 255.0 # Number of levels per pixel.\n\n# for small-sample testing\nOUTFILE = '/Users/pal004/Desktop/CatsVsDogsRedux/CatsAndDogs_pal15Jan2017_SmallerTest.npsave.bin'\nTRAINING_AND_VALIDATION_SIZE_DOGS = 1000\nTRAINING_AND_VALIDATION_SIZE_CATS = 1000\nTRAINING_AND_VALIDATION_SIZE_ALL = 2000\nTRAINING_SIZE = 1600 # TRAINING_SIZE + VALID_SIZE must equal TRAINING_AND_VALIDATION_SIZE_ALL\nVALID_SIZE = 400\nTEST_SIZE_ALL = 500\n\nif (TRAINING_SIZE + VALID_SIZE != TRAINING_AND_VALIDATION_SIZE_ALL):\n print (\"Error, check that TRAINING_SIZE+VALID_SIZE is equal to TRAINING_AND_VALIDATION_SIZE_ALL\")\n exit ()\n\ntrain_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)]\ntrain_dogs = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog' in i]\ntrain_cats = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat' in i]\ntest_images = [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\ntrain_images = train_dogs[:TRAINING_AND_VALIDATION_SIZE_DOGS] + train_cats[:TRAINING_AND_VALIDATION_SIZE_CATS]\ntrain_labels = np.array ((['dogs'] * TRAINING_AND_VALIDATION_SIZE_DOGS) + (['cats'] * TRAINING_AND_VALIDATION_SIZE_CATS))\ntest_images = test_images[:TEST_SIZE_ALL]\ntest_labels = np.array (['unknownclass'] * TEST_SIZE_ALL)\n\n# resizes to IMAGE_SIZE/IMAGE_SIZE while keeping aspect ratio the same. pads on right/bottom as appropriate\ndef read_image(file_path):\n img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE\n if (img.shape[0] >= img.shape[1]): # height is greater than width\n resizeto = (IMAGE_SIZE, int (round (IMAGE_SIZE * (float (img.shape[1]) / img.shape[0]))));\n else:\n resizeto = (int (round (IMAGE_SIZE * (float (img.shape[0]) / img.shape[1]))), IMAGE_SIZE);\n\n img2 = cv2.resize(img, (resizeto[1], resizeto[0]), interpolation=cv2.INTER_CUBIC)\n img3 = cv2.copyMakeBorder(img2, 0, IMAGE_SIZE - img2.shape[0], 0, IMAGE_SIZE - img2.shape[1], cv2.BORDER_CONSTANT, 0)\n\n return img3[:,:,::-1] # turn into rgb format\n\ndef prep_data(images):\n count = len(images)\n data = np.ndarray((count, IMAGE_SIZE, IMAGE_SIZE, CHANNELS), dtype=np.float32)\n\n for i, image_file in enumerate(images):\n image = read_image(image_file);\n image_data = np.array (image, dtype=np.float32);\n image_data[:,:,0] = (image_data[:,:,0].astype(float) - pixel_depth / 2) / pixel_depth\n image_data[:,:,1] = (image_data[:,:,1].astype(float) - pixel_depth / 2) / pixel_depth\n image_data[:,:,2] = (image_data[:,:,2].astype(float) - pixel_depth / 2) / pixel_depth\n\n data[i] = image_data; # image_data.T\n if i%250 == 0: print('Processed {} of {}'.format(i, count))\n return data\n\ntrain_normalized = prep_data(train_images)\ntest_normalized = prep_data(test_images)\n\nprint(\"Train shape: {}\".format(train_normalized.shape))\nprint(\"Test shape: {}\".format(test_normalized.shape))\n\nplt.imshow (train_normalized[0,:,:,:], interpolation='nearest')\nplt.figure ()\nplt.imshow (train_normalized[1,:,:,:], interpolation='nearest')\nplt.figure ()\nplt.imshow (train_normalized[2,:,:,:], interpolation='nearest')\nplt.figure ()\nplt.imshow (train_normalized[1000,:,:,:], interpolation='nearest')\nplt.figure ()\nplt.imshow (train_normalized[1001,:,:,:], interpolation='nearest')\nplt.figure ()\nplt.imshow (train_normalized[1002,:,:,:], interpolation='nearest')\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"584420328","text":"#/usr/bin/python\n\nimport requests\n\nPRICE_URI = 'https://api.coinbase.com/v2/prices/{0}-{1}/{2}'\n\n\ndef get_sell_price(currency = 'USD', coin = 'BTC'):\n request_uri = PRICE_URI.format(coin, currency, 'sell')\n res = requests.get(request_uri).json()\n if 'data' in res:\n sell_price = res['data']['amount']\n return sell_price\n elif 'errors' in res:\n return -1\n\n\ndef get_buy_price(currency = 'USD', coin = 'BTC'):\n request_uri = PRICE_URI.format(coin, currency, 'buy')\n res = requests.get(request_uri).json()\n if 'data' in res:\n buy_price = res['data']['amount']\n return buy_price\n elif 'errors' in res:\n return -1","sub_path":"price.py","file_name":"price.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"60152935","text":"#python3 script\n#Racetrack(Exercise 5.8): train and save an optimal policy, use algorithm in page 117\n#author: Xiang Chao\n\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport math\nimport copy\n\nstart = time.time()\n\ndef VelocityToActionList(v_x, v_y):\n if v_x < 0 or v_x > 4:\n print('v_x out 0~4')\n exit(1)\n if v_y < 0 or v_y > 4:\n print('v_y out 0~4')\n exit(1)\n if v_x == 0:\n if v_y == 0:\n action_list = np.array([[1,2], [2,1], [2,2]])\n elif v_y == 1:\n action_list = np.array([[1,1], [1,2], [2,0], [2,1], [2,2]])\n elif v_y == 2 or v_y == 3:\n action_list = np.array([[1,0], [1,1], [1,2], [2,0], [2,1], [2,2]])\n elif v_y == 4:\n action_list = np.array([[1,0], [1,1], [2,0], [2,1]])\n elif v_x == 1:\n if v_y == 0:\n action_list = np.array([[0,2], [1,1], [1,2], [2,1], [2,2]])\n elif v_y == 1:\n action_list = np.array([[0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]])\n elif v_y == 2 or v_y == 3:\n action_list = np.array([[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]])\n elif v_y == 4:\n action_list = np.array([[0,0], [0,1], [1,0], [1,1], [2,0], [2,1]])\n elif v_x == 2 or v_x == 3:\n if v_y == 0:\n action_list = np.array([[0,1], [0,2], [1,1], [1,2], [2,1], [2,2]])\n elif v_y == 1 or v_y == 2 or v_y == 3:\n action_list = np.array([[0,0], [0,1], [0,2], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2]])\n elif v_y == 4:\n action_list = np.array([[0,0], [0,1], [1,0], [1,1], [2,0], [2,1]])\n elif v_x == 4:\n if v_y == 0:\n action_list = np.array([[0,1], [0,2], [1,1], [1,2]])\n elif v_y == 1 or v_y == 2 or v_y == 3:\n action_list = np.array([[0,0], [0,1], [0,2], [1,0], [1,1], [1,2]])\n elif v_y == 4:\n action_list = np.array([[0,0], [0,1], [1,0], [1,1]])\n return action_list\n\ndef OneStep(state, PI, eps_mu, p_v_dont_change, track, h, w, starting_line, fin_x, fin_y1, fin_y2):\n action_list = VelocityToActionList(state[2], state[3])\n if random.random() > eps_mu:\n action = PI[state[0], state[1], state[2], state[3], :]\n else:\n action = action_list[np.random.randint(action_list.shape[0]), :]\n\n if np.all(action == PI[state[0], state[1], state[2], state[3], :]):\n MU_action = (1 - eps_mu) + eps_mu/(action_list.shape[0])\n else:\n MU_action = eps_mu/(action_list.shape[0])\n\n next_state = np.zeros(4, dtype=np.int8)\n if random.random() > p_v_dont_change:\n next_state[2] = state[2] + action[0] - 1\n next_state[3] = state[3] + action[1] - 1\n else:\n next_state[2] = state[2]\n next_state[3] = state[3]\n next_state[1] = state[1] + next_state[2]# horizontal coordinate\n next_state[0] = state[0] - next_state[3]# vertical coordinate\n\n if next_state[0] < 0 or next_state[0] >= h or next_state[1] < 0 or next_state[1] >= w or track[next_state[0], next_state[1]] == -1:\n if next_state[1] > fin_x:\n intersection = (next_state[0] - state[0])/(next_state[1] - state[1]) * (fin_x - state[1]) + state[0]\n if intersection >= fin_y1 and intersection <= fin_y2:\n next_state = 'Terminal'\n else:\n next_state = tuple(starting_line[np.random.randint(starting_line.shape[0]), :]) + (0, 0)\n else:\n next_state = tuple(starting_line[np.random.randint(starting_line.shape[0]), :]) + (0, 0)\n else:\n next_state = tuple(next_state)\n\n return tuple(action), MU_action, next_state\n\ntrack = np.load('track_1.npy')\nh, w = track.shape\nstarting_line = np.argwhere(track == 1)#, each row is a starting position\nfinish_line = np.argwhere(track == 2)\nfin_x = finish_line[0, 1]# the x coordinate of the finish line\nfin_y1 = np.min(finish_line[:, 0]) # the topmost y coordinate of the finish line\nfin_y2 = np.max(finish_line[:, 0]) # the undermost y coordinate of the finish line\nQ = np.zeros(track.shape+(5,5)+(3,3))\n#s: track.shape: position(vertical + horizontal)\n# (5,5): velocity(right+up), and can't move left or down\n#a: (3,3): acceleration(horizontal+vertical): 0, minus 1; 1, do nothing; 2, plus 1\nC = np.zeros(Q.shape)\n\nPI = np.zeros(track.shape+(5,5)+(2,), dtype=np.int8)#target policy\n# PI = np.load('policy_1_eps_mu_0.3_episode_150000.npy')\nfor i in range(h):# initial PI\n for j in range(w):\n for v_x in range(5):\n for v_y in range(5):\n action_list = VelocityToActionList(v_x, v_y)\n PI[i, j, v_x, v_y, :] = action_list[np.random.randint(action_list.shape[0]), :]\n\neps_mu = 0.3# behavior policy is the 'eps_mu'-soft of the current target policy \np_v_dont_change = 0\ngamma = 0.9#the discount for reward\nMaxEpisode = 300000#the max number of episodes\nEpisodePerEvaluation = 1000#the number of episodes per policy evaluation\nMaxTimestep = 100000# the max number of timesteps for each episodes\ncnt_episode = 0\nPI_CH = copy.deepcopy(PI)\nwhile True:\n cnt_episode = cnt_episode + 1\n episode = []\n state = tuple(starting_line[np.random.randint(starting_line.shape[0]), :]) + (0, 0)\n #choose a state from starting line randomly with 0 velocity\n timestep = 0\n while True:\n timestep = timestep + 1\n action, MU_action, next_state = OneStep(state, PI, eps_mu, p_v_dont_change, track, h, w, starting_line, fin_x, fin_y1, fin_y2)\n episode.append((state, action, MU_action))\n state = next_state\n if state == 'Terminal':\n episode.append(state)\n break\n if timestep > MaxTimestep:\n print('occur an episode of whitch length is over ' + str(MaxTimestep))\n break\n\n if episode.pop() == 'Terminal':\n G = 0\n W = 1.0\n while episode:\n state, action, MU_action = episode.pop()\n G = gamma * G - 1\n C[state+action] = C[state+action] + W\n Q[state+action] = Q[state+action] + (W / C[state+action]) * (G - Q[state+action])\n\n action_list = VelocityToActionList(state[2], state[3])\n A_greedy = action_list[0, :]\n q_max = Q[state[0],state[1],state[2],state[3],A_greedy[0],A_greedy[1]]\n for i in range(action_list.shape[0]):\n if Q[state[0],state[1],state[2],state[3],action_list[i, 0],action_list[i, 1]] > q_max:\n A_greedy = action_list[i, :]\n q_max = Q[state[0],state[1],state[2],state[3],action_list[i, 0],action_list[i, 1]]\n PI_CH[state[0],state[1],state[2],state[3], :] = A_greedy\n\n if tuple(PI[state[0],state[1],state[2],state[3], :]) == action:\n W = W / MU_action\n else:\n break\n\n # if tuple(A_greedy) != action:\n # break\n # W = W / MU_action\n\n if cnt_episode % EpisodePerEvaluation == 0:\n PI = copy.deepcopy(PI_CH)\n # Q = np.zeros(Q.shape)\n # C = np.zeros(Q.shape)\n\n else:\n cnt_episode = cnt_episode - 1\n\n if cnt_episode >= MaxEpisode:\n break\n\n\n\nnp.save('policy_2_track_1_eps_mu_'+str(eps_mu)+'_pvdontch_'+str(p_v_dont_change)+'_episode_'+str(MaxEpisode)+'_EpiPerEva_'+str(EpisodePerEvaluation)+'.npy', PI)\nnp.save('Q_of_policy_2_track_1_eps_mu_'+str(eps_mu)+'_pvdontch_'+str(p_v_dont_change)+'_episode_'+str(MaxEpisode)+'_EpiPerEva_'+str(EpisodePerEvaluation)+'.npy', Q)\nnp.save('C_of_policy_2_track_1_eps_mu_'+str(eps_mu)+'_pvdontch_'+str(p_v_dont_change)+'_episode_'+str(MaxEpisode)+'_EpiPerEva_'+str(EpisodePerEvaluation)+'.npy', C)\n\nend = time.time()\nprint('time cost: '+str((end-start)//3600)+'h'+str(((end-start)%3600)//60)+'m'+str(((end-start)%3600)%60)+'s')","sub_path":"Chapter_5/racetrack_2/train_policy_2.py","file_name":"train_policy_2.py","file_ext":"py","file_size_in_byte":7826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"160931087","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib import admin\ntry:\n from modeltranslation.admin import TranslationAdmin\nexcept:\n from django.contrib.admin.options import ModelAdmin as TranslationAdmin\n\nfrom ckeditor_uploader.widgets import CKEditorUploadingWidget\n\nfrom .models import Page\n\n\n@admin.register(Page)\nclass PageAdmin(TranslationAdmin):\n list_display = ('title', 'slug',\n 'is_published', 'is_in_sitemap', 'is_body_only',\n 'created_at', 'updated_at',\n 'description', 'keywords')\n list_filter = ('is_published', 'is_in_sitemap', 'is_body_only',)\n search_fields = ['slug', 'title']\n prepopulated_fields = {'slug': ('title',)}\n\n date_hierarchy = 'created_at'\n\n class Media:\n js = (\n 'modeltranslation/js/force_jquery.js',\n 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js',\n 'modeltranslation/js/tabbed_translation_fields.js',\n )\n css = {\n 'screen': ('modeltranslation/css/tabbed_translation_fields.css',),\n }\n\n def formfield_for_dbfield(self, db_field, **kwargs):\n if db_field.name in ('body_html'):\n return db_field.formfield(widget=CKEditorUploadingWidget(config_name='admin_area'))\n return super(PageAdmin, self).formfield_for_dbfield(db_field, **kwargs)\n","sub_path":"src/apps/pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"239164685","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nimport sys\nimport struct\nimport zlib\nimport numpy as np\nimport h5py\nimport math\nimport cooler\nimport pandas as pd\nfrom collections import OrderedDict\n\nversion = 'dummy'\n\n\nNORMS = ['VC', 'VC_SQRT', 'KR']\n\n\n#read function\ndef readcstr(f):\n # buf = bytearray()\n buf = b\"\"\n while True:\n b = f.read(1)\n if b is None or b == b\"\\0\":\n # return str(buf,encoding=\"utf-8\", errors=\"strict\")\n return buf.decode(\"utf-8\", errors=\"ignore\")\n else:\n buf += b\n # buf.append(b)\n\n\ndef read_header(infile):\n \"\"\"\n Takes in a .hic file and returns a dictionary containing information about\n the chromosome. Keys are chromosome index numbers (0 through # of chroms contained\n in file) and values are [chr idx (int), chr name (str), chrom length (str)].\n Returns the masterindex used by the file as well as the open file object.\n \"\"\"\n req=open(infile, 'rb')\n chrs = {}\n resolutions = []\n magic_string = struct.unpack('<3s', req.read(3))[0]\n req.read(1)\n if (magic_string != b\"HIC\"):\n print('This does not appear to be a HiC file; magic string is incorrect')\n sys.exit()\n global version\n version = struct.unpack('\")\n force_exit(warn_string, req)\n if (not (unit==\"BP\" or unit==\"FRAG\")):\n print(\"Unit specified incorrectly, must be one of \")\n force_exit(warn_string, req)\n\n chr1ind = chr1[0]\n chr2ind = chr2[0]\n c1pos1 = 0\n c1pos2 = int(chr1[2])\n c2pos1 = 0\n c2pos2 = int(chr2[2])\n c1 = min(chr1ind, chr2ind)\n c2 = max(chr1ind, chr2ind)\n chr_key = str(c1) + \"_\" + str(c2)\n\n try:\n pair_footer_info[chr_key]\n except KeyError:\n warn_string = (\n 'ERROR. There is a discrepancy between the chrs declared in the ' +\n 'infile header and the actual information it contains.\\nThe '\n 'intersection between ' + chr1[1] + ' and ' + chr2[1] + \n ' could not be found in the file.')\n force_exit(warn_string, req)\n myFilePos = pair_footer_info[chr_key]\n\n if (norm != \"NONE\"):\n #import ipdb; ipdb.set_trace()\n c1Norm = read_normalization_vector(req, chr_footer_info[c1])\n c2Norm = read_normalization_vector(req, chr_footer_info[c2])\n chrom_map[chr1[1]] = c1Norm\n chrom_map[chr2[1]] = c2Norm\n\n covered_chr_pairs.append(chr_key)\n\n\ndef hic2cool_extractnorms(infile, outfile, resolution=0, \n exclude_MT=False, command_line=False):\n \"\"\"\n Main function that coordinates the reading of header and footer from infile\n and uses that information to parse the hic matrix.\n Opens outfile and writes in form of .cool file\n Params:\n str .hic filename\n str .cool output filename\n int bp bin size. If 0, use all. Defaults to 0.\n Final .cool structure will change depending on this param (see README)\n str normalization type. Defaults to KR, optionally NONE, VC, or VC_SQRT\n bool. If True, ignore MT contacts. Defaults to False.\n bool. True if executing from run_hic.py. Prompts hic headers\n be printed to stdout.\n \"\"\"\n from collections import OrderedDict\n import cooler\n\n unit = 'BP' # only using base pair unit for now\n resolution = int(resolution)\n\n req, used_chrs, resolutions, masteridx, genome = read_header(infile)\n \n chromosomes = [used_chrs[i][1] for i in range(1, len(used_chrs))]\n lengths = [used_chrs[i][2] for i in range(1, len(used_chrs))]\n chromsizes = pd.Series(index=chromosomes, data=lengths)\n \n \n if command_line: # print hic header info for command line usage\n chr_names = [used_chrs[key][1] for key in used_chrs.keys()]\n print('################')\n print('### hic2cool ###')\n print('################')\n print('hic file header info:')\n print('Chromosomes: ', chr_names)\n print('Resolutions: ', resolutions)\n print('Genome: ', genome)\n \n if exclude_MT: # remove chr25, which is MT, if this flag is set\n used_chrs.pop(25, None)\n\n # ensure user input binsize is a resolution supported by the hic file\n if resolution != 0 and resolution not in resolutions:\n error_str = (\n 'ERROR. Given binsize (in bp) is not a supported resolution in ' +\n 'this file.\\nPlease use 0 (all resolutions) or use one of: ' + \n resolutions)\n force_exit(error_str, req)\n\n use_resolutions = resolutions if resolution == 0 else [resolution]\n\n cooler_groups = {}\n for path in cooler.io.ls(outfile):\n binsize = cooler.Cooler(outfile + '::' + path).info['bin-size']\n cooler_groups[binsize] = path\n print('MCOOL contents:')\n print(cooler_groups)\n \n for norm in NORMS:\n print('Norm:', norm)\n\n for binsize in use_resolutions:\n chrom_map = {}\n bins = cooler.binnify(chromsizes, binsize)\n req, pair_footer_info, chr_footer_info = read_footer(\n req, masteridx, norm, unit, binsize)\n\n covered_chr_pairs = [] \n for chr_x in used_chrs:\n if used_chrs[chr_x][1].lower() == 'all':\n continue\n for chr_y in used_chrs:\n if used_chrs[chr_y][1].lower() == 'all':\n continue\n c1 = min(chr_x, chr_y)\n c2 = max(chr_x, chr_y)\n # ensure this is true\n # since matrices are upper triangular, no need to cover \n # c1-c2 and c2-c1 reciprocally\n if str(c1) + \"_\" + str(c2) in covered_chr_pairs:\n continue\n parse_norm(\n norm, \n req, \n used_chrs[c1], \n used_chrs[c2], \n unit, \n binsize, \n covered_chr_pairs, \n pair_footer_info, \n chr_footer_info, \n chrom_map\n )\n\n lengths_in_bins = bins.groupby('chrom').size()\n # hic normalization vector lengths have inconsistent lengths...\n # truncate appropriately\n vector = np.concatenate([\n chrom_map[chrom][:lengths_in_bins.loc[chrom]]\n for chrom in chromosomes\n ])\n bins[norm] = vector\n print('Resolution:', binsize)\n print(bins.head())\n print('Writing to cool file...')\n group_path = cooler_groups[binsize]\n cooler.io.append(\n outfile + '::' + group_path,\n 'bins',\n {norm: bins[norm].values},\n force=True)\n req.close()\n\n\ndef force_exit(message, req):\n \"\"\"\n Exit the program due to some error. Print out message and close the given\n input files.\n \"\"\"\n req.close()\n print(message, file=sys.stderr)\n sys.exit()\n\n\nif __name__ == '__main__':\n\n import argparse\n\n def main():\n \"\"\"\n Execute the program from the command line\n Args are:\n python hic2cool.py \n \n \n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"infile\", help=\".hic input file\")\n parser.add_argument(\"outfile\", help=\".cool output file\")\n parser.add_argument(\"-r\", \"--resolution\",\n help=\"integer bp resolution desired in cooler file. \"\n \"Setting to 0 (default) will use all resolutions. \"\n \"If all resolutions are used, a multi-res .cool file will be \"\n \"created, which has a different hdf5 structure. See the \"\n \"README for more info\", type=int, default=0)\n parser.add_argument(\"-e\", \"--exclude_MT\", \n help=\"if used, exclude the mitochondria (MT) from the output\", \n action=\"store_true\")\n args = parser.parse_args()\n # these parameters adapted from theaidenlab/straw\n # KR is default normalization type and BP is the unit for binsize\n hic2cool_extractnorms(\n args.infile, \n args.outfile, \n args.resolution, \n #args.normalization, \n args.exclude_MT, \n True)\n main()\n","sub_path":"hic2cool_extractnorms.py","file_name":"hic2cool_extractnorms.py","file_ext":"py","file_size_in_byte":13474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"288453309","text":"\"\"\"Top-level functions for the `projsearch.parse` module - this file should\ntypically not be accessed directly, since its name space is imported into the\ntop-level namespace `projsearch.parse`.\"\"\"\n\nfrom . import types, commands\nfrom ..functional import exists\nfrom ..run import RunParameters\nimport itertools\n\n__all__ = ['machine_line', 'input_file_to_machine_lines',\n 'input_file_to_parameters', 'user_input_to_machine_input',\n 'key_value_statements', 'key_value_sets', 'next_run_parameters']\n\n_needed_params = set([\"state\", \"sequence\", \"laser\", \"time\"])\n\ndef machine_line(str):\n \"\"\"machine_line(str: string) -> RunParameters\n\n Parse a single string from the machine-readable file into a set of\n RunParameters which can be used to run a single optimisation.\n\n The machine-readable string should look like\n state={'g1':1,'g0':1j};sequence=[0,1];laser=(0,0.1,1000);time=3600\n or something similar. Importantly, it should be entirely on a single line\n with 'key=val' pairs separated by a ';'. All other whitespace is ignored,\n so can be included for human readability if desired.\n\n Raises:\n ValueError -- if there were issues in parsing.\"\"\"\n def keyval(part):\n sides = [ x.strip() for x in part.split(\"=\") ]\n if len(sides) is not 2 or exists(lambda x: x is \"\", sides):\n raise ValueError(\"Could not parse '{}' for a key-val pair.\"\n .format(part.strip()))\n return sides\n dict_ = dict(map(keyval, filter(lambda x: x.strip() != \"\", str.split(\";\"))))\n got = set(dict_)\n if _needed_params - got != set():\n raise ValueError(\"Did not get a value for {} in entry '{}'.\"\n .format(_needed_params - got, str.strip()))\n elif got - _needed_params != set():\n raise ValueError(\"Found extra keys {} in entry '{}'.\"\n .format(got - _needed_params, str.strip()))\n return RunParameters(types.state(dict_[\"state\"]),\n types.sequence(dict_[\"sequence\"]),\n types.laser(dict_[\"laser\"]),\n types.time(dict_[\"time\"]))\n\ndef _cut_comment(str_):\n \"\"\"_cut_comment(str_: str) -> str\n\n Return a slice of the input string which has any present comment removed. A\n comment begins with the character '#', and runs til the end of the line.\n This functions returns everything before the comment character.\"\"\"\n comment_start = str_.find('#')\n if comment_start is -1:\n return str_\n else:\n return str_[:comment_start]\n\ndef key_value_statements(file, s_sep=';', kv_sep='='):\n \"\"\"key_value_statements(file: file object, ?s_sep, ?kv_sep) -> generator\n\n Returns a generator of dictionaries, for looping through a file\n statement-by-statement, removing comments and whitespace as necessary.\n\n Arguments:\n file: file object -- A file opened for reading in string mode.\n s_sep: string --\n The string which is considered to separate statements which occur on the\n same line.\n kv_sep: string -- The string which separates the key from its value.\n\n Returns:\n generator of dict with keys:\n 'key': str -- the \"key\" side of the pair.\n 'value': str -- the \"value\" side of the pair.\n 'line': int > 0 -- the line number the statement was found on.\n 'statement': str -- the whole statement that was parsed.\"\"\"\n for line_num, line in enumerate(file):\n for stmt in map(lambda s: s.strip(), _cut_comment(line).split(s_sep)):\n if stmt == '':\n continue\n parts = list(map(lambda s: s.strip(), stmt.split(kv_sep)))\n if len(parts) is not 2 or exists(lambda s: s == '', parts):\n raise ValueError(\"Could not interpret statement '\" + stmt\n + \"' on line {} of '\".format(line_num + 1)\n + file.name + \"'.\")\n else:\n yield {'key': parts[0], 'value': parts[1],\n 'line': line_num + 1, 'statement': stmt}\n\ndef key_value_sets(keys, statements):\n \"\"\"key_value_sets(keys, statements) -> generator of list of (str * str)\n\n Group sets of key-value statements into consecutive groups which each have\n exactly one of the `keys` in.\n\n Arguments:\n keys: set of str --\n The set of keys that is required to be filled for one group.\n statements: generator of dict -- The output of `key_value_statements`.\n\n Returns:\n generator of list of ((key: str) * (value: str))\n\n Raises:\n ValueError --\n - If an unknown key is encountered.\n - If a duplicate key is encountered before a set is complete.\n - If the `statements` generator is exhausted with an incomplete set.\"\"\"\n params = []\n for stmt in statements:\n if exists(lambda t: t[0] == stmt['key'], params):\n raise ValueError(\n \"Encountered another specifier for '\" + stmt['key'] + \"'\"\n + \" on line {}\".format(stmt['line'])\n + \" before the previous input set was completed.\")\n elif stmt['key'] not in keys:\n raise ValueError(\n \"Encountered unknown parameter specifier '\"\n + stmt['key'] + \"' in statement '\" + stmt['statement'] + \"'\"\n + \" on line {}\".format(stmt['line']))\n params.append((stmt['key'], stmt['value']))\n if set(map(lambda t: t[0], params)) == keys:\n yield params\n params = []\n if len(params) != 0:\n raise ValueError(\"End-of-file encountered \"\n + \"before the last specifier was complete.\")\n\ndef next_run_parameters(statements):\n \"\"\"next_run_parameters(statements) -> generator of RunParameters\n\n Get a generator which returns all of the next defined set of RunParameters\n in the 'key-val' `statements` iterator argument. This returns a generator\n because one input set can define multiple RunParameters by means of user\n commands.\n\n Arguments:\n statements: generator of (str * str) --\n A 'key-val' generator, such as that created by the function\n `key_value_statements`.\n\n Returns:\n generator of RunParameters --\n A generator which will return all the next set of defineed\n RunParameters, including expanding any user commands.\n\n Raises:\n ValueError --\n - If an unknown key was encountered in a key-val pair.\n - If a duplicate key was encountered in the same set of specifiers.\n - If statements run out while a parameter set is still being built.\n StopIteration --\n If there is no next set of RunParameters to take, i.e. the statements\n run out immediately after a completed set of specifiers was found.\"\"\"\n return commands.expand(next(key_value_sets(_needed_params, statements)))\n\ndef _machine_line_from_run_parameters(run_params):\n \"\"\"_machine_line_from_run_parameters(run_params: RunParameters) -> str\n\n Parse a set of RunParameters into the string of a machine line.\"\"\"\n return \"state=\" + types.string.state(run_params.state)\\\n + \";sequence=\" + types.string.sequence(run_params.sequence)\\\n + \";laser=\" + types.string.laser(run_params.laser)\\\n + \";time=\" + types.string.time(run_params.time)\n\ndef input_file_to_machine_lines(file_name):\n \"\"\"input_file_to_machine_lines(file_name: str) -> generator of str\n\n Acquire the lock on the human-readable input file with path `file_name`,\n then return an iterator which yields each machine-readable line specified in\n order. Commands in the input file which produce ranges will be treated like\n for loops, with the first encountered sequence being the outer-most loop.\n\n The generator will close the file when it encounters an unreadable line, or\n when the generator is fully consumed.\"\"\"\n with open(file_name, \"r\") as file:\n try:\n statements = key_value_statements(file)\n while True:\n yield from map(_machine_line_from_run_parameters,\n next_run_parameters(statements))\n except StopIteration:\n return\n\ndef input_file_to_parameters(file_name):\n \"\"\"input_file_to_parameters(file_name: str) -> generator of RunParameters\n\n Acquire the lock on the human-readable input file with path `file_name`,\n then return an iterator which yields each set of RunParameters in file\n order. Commands in the input file which produce ranges will be treated like\n for loops, with the first encountered sequence being the outer-most loop.\n\n The generator will close the file when it encounters an unreadable line, or\n when the generator is fully consumed.\"\"\"\n with open(file_name, \"r\") as file:\n try:\n statements = key_value_statements(file)\n while True:\n yield from next_run_parameters(statements)\n except StopIteration:\n return\n\ndef user_input_to_machine_input(user_file_name, machine_file_name):\n \"\"\"user_input_to_machine_input(user_file_name: str, machine_file_name: str)\n -> None\n\n Converts a single user input file into machine-readable lines which are then\n appended to the (possibly non-existing) file called `machine_file_name`.\"\"\"\n with open(machine_file_name, \"a\") as out:\n for line in input_file_to_machine_lines(user_file_name):\n out.write(line + \"\\n\")\n","sub_path":"parse/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":9449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"98718386","text":"# https://www.lintcode.com/problem/split-string/description?_from=ladder&&fromId=1\n\n\nclass Solution:\n \"\"\"\n @param: : a string to be split\n @return: all possible split string array\n \"\"\"\n\n def splitString(self, s):\n # write your code here\n result = []\n self.dfs(result, [], s)\n return result\n\n def dfs(self, result, path, s):\n if s == \"\":\n result.append(path[:])\n return\n\n for i in range(2):\n if i + 1 <= len(s):\n path.append(s[: i + 1])\n self.dfs(result, path, s[i + 1 :])\n path.pop()\n","sub_path":"implicit-graph-dfs/lint-680/lint-680.py","file_name":"lint-680.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"8702012","text":"from lib.cog import Cog\nimport json\n\nfrom lib.command import makeCommand, Command\n\n\nclass Debug(Cog):\n def __init__(self, bot):\n super().__init__(bot)\n\n @makeCommand(name=\"people\", description=\"get the current userlist\")\n async def people(self, c: Command):\n await self.bot.send_message(self.bot.accounts.__str__())\n\n @makeCommand(name=\"reload\", description=\" reloads a cog\")\n async def reload(self, c: Command):\n self.bot.remove_cog(c.message)\n self.bot.add_cog(c.message)\n await self.bot.send_message(f\"reloaded {c.message} Cog\")\n","sub_path":"modules/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"383214588","text":"# -*- coding: utf-8 -*-\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 inspect\nimport logging\nimport logging.config\nimport logging.handlers\nimport os\nimport six\ntry:\n import syslog\nexcept ImportError:\n syslog = None\nfrom oslo_utils import encodeutils\n\n\nNullHandler = logging.NullHandler\n\n\ndef _get_binary_name():\n return os.path.basename(inspect.stack()[-1][1])\n\n\n_AUDIT = logging.INFO + 1\n_TRACE = 5\n\n\nif syslog is not None:\n class OSSysLogHandler(logging.Handler):\n \"\"\"Syslog based handler. Only available on UNIX-like platforms.\"\"\"\n severity_map = {\n \"CRITICAL\": syslog.LOG_CRIT,\n \"DEBUG\": syslog.LOG_DEBUG,\n \"ERROR\": syslog.LOG_ERR,\n \"INFO\": syslog.LOG_INFO,\n \"WARNING\": syslog.LOG_WARNING,\n \"WARN\": syslog.LOG_WARNING,\n }\n\n def __init__(self, facility=syslog.LOG_USER):\n # Do not use super() unless type(logging.Handler) is 'type'\n # (i.e. >= Python 2.7).\n logging.Handler.__init__(self)\n binary_name = _get_binary_name()\n syslog.openlog(binary_name, 0, facility)\n\n def emit(self, record):\n priority = self.severity_map.get(record.levelname,\n syslog.LOG_DEBUG)\n message = self.format(record)\n\n # NOTE(gangila): In python2, the syslog function takes in 's' as\n # the format argument, which means it either accepts python string\n # (str = 'a') or unicode strings (str = u'a'), the PyArg_ParseTuple\n # then if needed converts the unicode objects to C strings using\n # the *default encoding*. This default encoding is 'ascii' in case\n # of python2 while it has been changed to 'utf-8' in case of\n # python3. What this leads to is when we supply a syslog message\n # like:\n # >>> syslog.syslog(syslog.LOG_DEBUG, u\"François Deppierraz\")\n # In case of python2 the above fails with TypeError: [priority,]\n # message string. Because python2 doesn't explicitly encode as\n # 'utf-8' and use the system default encoding ascii, which raises\n # a UnicodeEncodeError (UnicodeEncodeError: 'ascii' codec can't\n # encode character u'\\xe7' in position 4: ordinal not in\n # range(128)), and hence the error message that's set in the code\n # (TypeError: [priority,] message string) gets shown to the user.\n # However, this in the case of Python3, where the system default\n # encoding is 'utf-8' works without any issues. Therefore, we need\n # to safe_encode in case of python2 and not in case of Python3.\n if six.PY2:\n message = encodeutils.safe_encode(self.format(record))\n\n syslog.syslog(priority, message)\n\n\nclass ColorHandler(logging.StreamHandler):\n LEVEL_COLORS = {\n _TRACE: '\\033[00;35m', # MAGENTA\n logging.DEBUG: '\\033[00;32m', # GREEN\n logging.INFO: '\\033[00;36m', # CYAN\n _AUDIT: '\\033[01;36m', # BOLD CYAN\n logging.WARN: '\\033[01;33m', # BOLD YELLOW\n logging.ERROR: '\\033[01;31m', # BOLD RED\n logging.CRITICAL: '\\033[01;31m', # BOLD RED\n }\n\n def format(self, record):\n record.color = self.LEVEL_COLORS[record.levelno]\n return logging.StreamHandler.format(self, record)\n","sub_path":"filesystems/vnx_rootfs_lxc_ubuntu64-16.04-v025-openstack-compute/rootfs/usr/lib/python2.7/dist-packages/oslo_log/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"381068098","text":"#!/usr/bin/env python3\nimport os, sys, re\nimport json\nimport logging as L\n\n# Take the Stats.json and produce a basic text table of the unassigned\n# barcodes. This code was originally in multiqc_edgen/modules/edgen_unassigned/edgen_unassigned.py\n# but it got a little complex so I'm breaking it out into the pipeline proper.\n\n# Note that if there are no barcodes in the run or the Stats.json contains multiple lanes the\n# output will be empty and a warning will be logged on STDERR.\n\ndef format_lines(json_data, maxlines=None, commentor=lambda *ub: []):\n \"\"\"Given the content of a Stats.json file as a Python object,\n return a list of lines that we can embed into the MultiQC report.\n \"\"\"\n ub = json_data.get(\"UnknownBarcodes\")\n\n if not ub:\n L.warning(\"No unknown barcodes in this JSON data.\")\n return []\n if len(ub) != 1:\n # TODO - check I got this right\n L.warning(\"JSON data contains info for more than one lane.\")\n return []\n\n # There is one lane. Good.\n ub_codes = ub[0][\"Barcodes\"]\n\n # Now we have a dict. In the original files the list is sorted by count but this will\n # be lost, so re-sort. Also we can lose the overspill.\n ub_sorted = sorted(ub_codes.items(), key=lambda i: int(i[1]), reverse=True)[:maxlines]\n\n # Add comment to the end of each line. This incolves converting the tuples to lists.\n ub_sorted = [ list(ub) + commentor(*ub) for ub in ub_sorted ]\n\n # I had this calculate the right widths and format into columns, but Matt says he\n # copy-pastes the list into Excel and needs literal tab characters. OK.\n return [ \"\\t\".join(map(str,i)) for i in ub_sorted ]\n\ndef make_revcomp_commentor(sdict):\n \"\"\"Return a commentor function that looks for likely reverse-complement\n issues. Note we don't look for reversed or swapped codes or anything\n other than revcomp.\n \"\"\"\n # Sanitize all the names in sdict, while also ensuring that changes to\n # the original dict cannot alter the function output.\n newdict = { k: v.split('__')[-1] for k, v in sdict.items() }\n\n # We only care about the barcode not the count, so define the fuction like so:\n def comm_func(bc, *_):\n\n # Simple case\n if bc in newdict:\n return [\"is \" + newdict[bc]]\n\n # The bc may or may not have a '+'\n bc_split = bc.split('+')\n\n if len(bc_split) > 2:\n # I could make this work for any number of indices but it would just\n # make the code ugly and would never do anything useful.\n return []\n elif len(bc_split) == 1:\n if revcomp(bc) in newdict:\n return [\"revcomp of \" + newdict[revcomp(bc)]]\n else:\n # No match, no message\n return []\n else:\n # Here we need a list of possible matches - see the unit tests\n poss_matches = [ ('idx1',\n newdict.get(revcomp(bc_split[0]) + \"+\" + bc_split[1])),\n ('idx2',\n newdict.get(bc_split[0] + \"+\" + revcomp(bc_split[1]))),\n ('idx1+2',\n newdict.get(revcomp(bc_split[0]) + \"+\" + revcomp(bc_split[1]))) ]\n # String-ify. For the no-match case we need to return an empty list, not an empty\n # string.\n res = \"; \".join([ \"revcomp {} of {}\".format(*pm) for pm in poss_matches\n if pm[1] ])\n return [res] if res else []\n\n return comm_func\n\ndef revcomp(seq, rep_table=str.maketrans('ATCGatcg', 'TAGCtagc')):\n \"\"\"The classic!\n \"\"\"\n return seq.translate(rep_table)[::-1]\n\ndef get_samples_list(json_data):\n \"\"\"This is implemented elsewhere, but I'll re-implement it here. List\n the samples from the JSON, in the form of as dict of {barcode: sample}\n \"\"\"\n con_res = json_data.get('ConversionResults')\n\n # We expect one of these, and then there should be a DemuxResults list that is one\n # per sample.\n if not con_res or len(con_res) != 1:\n L.warning(\"Cannot get table of sample barcodes from JSON data\")\n return {}\n\n dem_res = con_res[0][\"DemuxResults\"]\n if not dem_res:\n L.warning(\"Table of sample barcodes from JSON data is empty\")\n\n res = {}\n for sample in dem_res:\n sample_name = sample.get(\"SampleId\") or sample.get(\"SampleName\") or 'unnamed'\n\n # In Stats.json a sample may have multiple index sequences. Not sure if bcl2fastq actually supports\n # this but we have a list in any case.\n for sample_index in sample.get(\"IndexMetrics\", []):\n res[sample_index[\"IndexSequence\"]] = sample_name\n\n return res\n\ndef main(args):\n if not len(args) == 1:\n exit(\"Usage: unassigned_to_table.py \")\n\n with open(args[0]) as sfh:\n json_data = json.load(sfh)\n\n # Commentor needs to know the expected samples\n expected_samples = get_samples_list(json_data)\n commentor = make_revcomp_commentor(expected_samples)\n\n out_lines = format_lines(json_data, maxlines=200, commentor=commentor)\n\n for l in out_lines:\n print(l)\n\nif __name__ == '__main__':\n # Logging in use for the benefit of unit tests\n L.basicConfig(format='{message:s}', level=L.INFO, style='{')\n main(sys.argv[1:])\n","sub_path":"unassigned_to_table.py","file_name":"unassigned_to_table.py","file_ext":"py","file_size_in_byte":5348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"322146927","text":"\"\"\"Tests for common.field\"\"\"\n\nimport pytest\nimport tensorflow as tf\n\nimport deepr as dpr\n\n\n@pytest.mark.parametrize(\"shape, expected\", [([None, None], False), ([2], True), ([None, 2], False)])\ndef test_has_fixed_len(shape, expected):\n \"\"\"Test has_fixed_len method\"\"\"\n field = dpr.Field(name=\"name\", shape=shape, dtype=tf.int32)\n assert field.has_fixed_len() == expected\n assert field.has_fixed_len() != field.has_var_len()\n\n\n@pytest.mark.parametrize(\n \"field\",\n [\n dpr.Field(name=\"name\", shape=[None, None], dtype=tf.int32),\n dpr.Field(name=\"name\", shape=[2], dtype=tf.int32),\n dpr.Field(name=\"name\", shape=[None, 2], dtype=tf.int32),\n ],\n)\ndef test_as_feature(field):\n \"\"\"Test as_feature method\"\"\"\n field.as_feature()\n\n\ndef test_startswith():\n \"\"\"Test startswith method\"\"\"\n assert dpr.Field(name=\"inputPositive\", shape=[None, None], dtype=tf.int32).startswith(\"input\")\n","sub_path":"tests/unit/utils/test_utils_field.py","file_name":"test_utils_field.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"30785864","text":"# William Leighton Dawson\n# Center for Cyber Security\n# New York University - Abu Dhabi\n# Implementation of the NIST Randomness Test Suite\n# 1. The Frequency (Monobit) Test\n\nfrom helpers import s_n, s_obs\nfrom math import sqrt, erfc\n\n\ndef Frequency(e):\n n = len(e)\n # if n < 100 and not ignore_recommendations:\n # raise LengthError()\n S_n = s_n(e)\n S_obs = s_obs(e)\n p = erfc(S_obs / sqrt(2))\n outstr = \"Frequency (Monobit) Test:\\n\"\n outstr += \"n = %d\\n\" % n\n outstr += \"S_n = %d\\n\" % S_n\n outstr += \"S_obs = %.6f\\n\" % S_obs\n outstr += \"P-value = %.6f\\n\" % p\n open(\"./test_results/Frequency.txt\", \"w\").write(outstr)\n if p < 0.01:\n return False\n else:\n return True\n","sub_path":"tests/Frequency.py","file_name":"Frequency.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"427166461","text":"import uuid\nfrom typing import List, Dict, Tuple, Any\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom copy import deepcopy\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, PolynomialFeatures\nimport torch\n\nfrom lib.utils import read_jsonl, write_jsonl, ML_OPERATIONS_LIST\n\n\n@dataclass(unsafe_hash=True)\nclass TreeNode:\n\n id: str\n model_name: str\n batch_size: int\n seq_len: int\n node_type: str\n\n parent_name: str\n instance_type: str\n scope: str\n level: str\n level_name: str\n child_nodes: List[\"TreeNode\"] = None\n\n feature_list: List[str] = None\n features: List[float] = None\n\n gold_energy: float = None # Name change to ground_truth_energy\n predicted_energy: float = None\n\n loss: float = None\n subtree_loss: float = None\n subtree_error_sum: float = None\n subtree_error_count: int = None\n subtree_error_perc: float = None\n\n original_node_dict: Dict = None\n\n def description(self):\n print(\n f\"NODE INFORMATION - Scope: {self.scope}, instance type: {self.instance_type}, \"\n f\"level: {self.level}, parent: {self.parent_name}\"\n )\n\n @classmethod\n def read_from_json(\n cls,\n tree_dict: Dict,\n feature_list: List[str],\n model_name: str = None,\n seq_len: str = None,\n batch_size: str = None,\n ) -> \"TreeNode\":\n\n if \"model_name\" in tree_dict:\n tree_dict = deepcopy(tree_dict)\n root_is_model_node = True\n\n assert not any(\n (model_name, seq_len, batch_size)\n ), \"Don't pass model_name, seq_len or batch_size at as arguments at root level.\"\n\n model_name = tree_dict.pop(\"model_name\")\n seq_len = tree_dict.pop(\"seq_len\")\n batch_size = tree_dict.pop(\"batch_size\")\n tree_dict = tree_dict.pop(\"frontend_tree\")\n\n else:\n root_is_model_node = False\n\n subtrees_dicts = tree_dict[\"child_nodes_obj\"]\n\n features = []\n for feature_name in feature_list:\n\n if feature_name == \"batch_size\":\n feature_value = batch_size\n elif feature_name == \"seq_len\":\n feature_value = seq_len\n elif feature_name == \"input_size\":\n feature_value = batch_size * seq_len\n else:\n feature_value = tree_dict[feature_name]\n features.append(feature_value)\n\n node_type = tree_dict[\"type\"]\n\n # Temporary fix for the format change, maybe update later?\n if node_type == \"ml-np\":\n node_type = \"ml\"\n\n if not subtrees_dicts:\n assert node_type == \"ml\", f\"Leaf nodes must be ml typed. Found {node_type}\"\n\n # There are some discrepancies in names: MatMul vs matmul.\n tree_dict[\"instance_type\"] = tree_dict[\"instance_type\"].lower()\n\n # This is just to make it compatible with old-code\n level_name = f\"{tree_dict['scope']}:{tree_dict['instance_type']}\"\n\n attributes_dict = {\n \"id\": tree_dict[\"id\"],\n \"scope\": tree_dict[\"scope\"],\n \"level\": tree_dict[\"level\"],\n \"parent_name\": tree_dict[\"parent_name\"],\n \"instance_type\": tree_dict[\"instance_type\"],\n \"level_name\": level_name,\n \"features\": features,\n \"model_name\": model_name,\n \"batch_size\": batch_size,\n \"seq_len\": seq_len,\n \"node_type\": node_type,\n \"gold_energy\": tree_dict.get(\"ground_truth_energy\", None),\n \"predicted_energy\": tree_dict.get(\"predicted_energy\", None),\n \"original_node_dict\": tree_dict, # For getting the predictions back in original format.\n }\n\n tree_node = TreeNode(**attributes_dict)\n tree_node.child_nodes = [\n cls.read_from_json(\n subtree_dict,\n feature_list=feature_list,\n model_name=model_name,\n seq_len=seq_len,\n batch_size=batch_size,\n )\n for subtree_dict in subtrees_dicts\n ]\n\n return tree_node\n\n def write_to_json(self, root_is_model_node: bool = True) -> Dict:\n\n child_nodes = self.child_nodes\n\n tree_node_dict = self.original_node_dict\n tree_node_dict[\"id\"] = self.id\n tree_node_dict[\"predicted_energy\"] = float(self.predicted_energy)\n\n tree_node_dict[\"child_nodes_obj\"] = [\n child_node.write_to_json(False) for child_node in child_nodes\n ]\n if root_is_model_node:\n tree_node_dict = {\n \"model_name\": self.model_name,\n \"seq_len\": self.seq_len,\n \"batch_size\": self.batch_size,\n \"frontend_tree\": tree_node_dict,\n }\n return deepcopy(tree_node_dict)\n\n @classmethod\n def read_from_jsons(\n cls, jsons: List[Dict], feature_list: List[str]\n ) -> List[\"TreeNode\"]:\n return [TreeNode.read_from_json(tree_dict, feature_list) for tree_dict in jsons]\n\n @classmethod\n def write_to_jsons(cls, tree_nodes: List[\"TreeNode\"]) -> List[Dict]:\n return [tree_node.write_to_json() for tree_node in tree_nodes]\n\n def get_subtree_nodes(self, node_types: List[str]) -> List[\"TreeNode\"]:\n \"\"\"\n Enumerates all ML-level (leaf) nodes of the tree.\n \"\"\"\n for node_type in node_types:\n assert node_type in (\"model\", \"module\", \"ml\")\n\n if self.node_type in node_types:\n yield self\n\n for child in self.child_nodes:\n for leaf in child.get_subtree_nodes(node_types):\n yield leaf\n\n def update_tree_node_attributes(\n self, attribute: str, node_id_to_attribute_value: Dict[str, Any]\n ):\n \"\"\"\n Iterates through the full tree and updates attribute values for the given attribute\n of the node with the matching node-id.\n \"\"\"\n if self.id in node_id_to_attribute_value:\n setattr(self, attribute, node_id_to_attribute_value[self.id])\n\n for child_node in self.child_nodes:\n child_node.update_tree_node_attributes(\n attribute, node_id_to_attribute_value\n )\n\n def get_subtree_nodes_attributes(\n self, node_types: List[str], attributes: List[str]\n ) -> List[Dict]:\n \"\"\"\n Enumerates nodes of the given node_types and extracts the given\n attributes of each of them into a list of dictionaries.\n \"\"\"\n\n nodes_attributes = []\n for node in self.get_subtree_nodes(node_types):\n nodes_attributes.append(\n {attribute: getattr(node, attribute) for attribute in attributes}\n )\n\n return nodes_attributes\n\n def get_ml_level_data(self, output_attr: str = \"gold_energy\") -> Dict[str, List]:\n \"\"\"\n Loads ML-level data (ids, features and outputs/energies) for each operation-type\n \"\"\"\n nodes_attributes = self.get_subtree_nodes_attributes(\n [\"ml\"], [\"id\", \"features\", \"gold_energy\", \"level_name\", \"instance_type\"]\n ) # level_name was used for legacy code.\n\n for node_attributes in nodes_attributes:\n node_attributes[\"ids\"] = node_attributes[\"id\"]\n node_attributes[\"outputs\"] = node_attributes[output_attr]\n\n operationwise_nodes_attributes = defaultdict(list)\n\n for node_attributes in nodes_attributes:\n # # level_name was used for legacy code:\n # level_name = node_attributes[\"level_name\"]\n # operation_type = level_name.split(\":\")[1]\n\n operation_type = node_attributes[\"instance_type\"]\n if operation_type in ML_OPERATIONS_LIST:\n operationwise_nodes_attributes[operation_type].append(node_attributes)\n else:\n print(\n f\"WARNING: No ML-level model found for operation_type: {operation_type}\"\n )\n\n return operationwise_nodes_attributes\n\n @classmethod\n def prepare_for_non_ml_training(\n cls,\n tree_nodes: List[\"TreeNode\"],\n standardize_features: bool = True,\n polynomial_features: bool = True,\n ) -> Tuple[List[\"TreeNode\"], List]:\n \"\"\"\n Runs feature transformations (standardizer and polynomial expander), save them as tensors\n and then also saves gold_energy as tensors.\n \"\"\"\n\n nodes_attributes = []\n for tree_node in tree_nodes:\n nodes_attributes.extend(\n tree_node.get_subtree_nodes_attributes(\n [\"ml\", \"module\", \"model\"], [\"id\", \"features\", \"gold_energy\"]\n )\n )\n\n assert len(\n set([node_attributes[\"id\"] for node_attributes in nodes_attributes])\n ) == len(nodes_attributes), \"Node-ids need to be unique, but they aren't.\"\n\n all_features = np.stack(\n [\n np.array(node_attributes[\"features\"])\n for node_attributes in nodes_attributes\n ],\n axis=0,\n )\n\n transformations = []\n\n if standardize_features:\n scale_standardizer = StandardScaler().fit(all_features)\n all_features = scale_standardizer.transform(all_features)\n transformations.append(scale_standardizer)\n\n if polynomial_features:\n poly_reg = PolynomialFeatures(degree=3).fit(all_features)\n all_features = poly_reg.transform(all_features)\n transformations.append(poly_reg)\n\n all_features = torch.tensor(all_features, dtype=torch.float32)\n\n id_to_features = {\n node_attributes[\"id\"]: features.unsqueeze(0)\n for node_attributes, features in zip(nodes_attributes, all_features)\n }\n for tree_node in tree_nodes:\n tree_node.update_tree_node_attributes(\"features\", id_to_features)\n\n id_to_gold_energy = {\n node_attributes[\"id\"]: torch.tensor(node_attributes[\"gold_energy\"])\n for node_attributes in nodes_attributes\n }\n for tree_node in tree_nodes:\n tree_node.update_tree_node_attributes(\"gold_energy\", id_to_gold_energy)\n\n return tree_nodes, transformations\n\n @classmethod\n def prepare_for_non_ml_predicting(\n cls,\n tree_nodes: List[\"TreeNode\"],\n transformations: List,\n ) -> List[\"TreeNode\"]:\n \"\"\"\n Runs transformations trained on the training data, and changes\n features/gold_energy fields to tensors.\n \"\"\"\n\n nodes_attributes = []\n for tree_node in tree_nodes:\n nodes_attributes.extend(\n tree_node.get_subtree_nodes_attributes(\n [\"ml\", \"module\", \"model\"], [\"id\", \"features\", \"gold_energy\"]\n )\n )\n\n assert len(\n set([node_attributes[\"id\"] for node_attributes in nodes_attributes])\n ) == len(nodes_attributes), \"Node-ids need to be unique, but they aren't.\"\n\n all_features = np.stack(\n [\n np.array(node_attributes[\"features\"])\n for node_attributes in nodes_attributes\n ],\n axis=0,\n )\n\n for transformation in transformations:\n all_features = transformation.transform(all_features)\n\n all_features = torch.tensor(all_features, dtype=torch.float32)\n\n id_to_features = {\n node_attributes[\"id\"]: features.unsqueeze(0)\n for node_attributes, features in zip(nodes_attributes, all_features)\n }\n for tree_node in tree_nodes:\n tree_node.update_tree_node_attributes(\"features\", id_to_features)\n\n id_to_gold_energy = {\n node_attributes[\"id\"]: (\n torch.tensor(node_attributes[\"gold_energy\"])\n if node_attributes.get(\"gold_energy\", None)\n else None\n )\n for node_attributes in nodes_attributes\n }\n for tree_node in tree_nodes:\n tree_node.update_tree_node_attributes(\"gold_energy\", id_to_gold_energy)\n\n return tree_nodes\n","sub_path":"lib/tree_node.py","file_name":"tree_node.py","file_ext":"py","file_size_in_byte":12158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"574569253","text":"#coding=utf-8\r\nimport os,os.path,shutil\r\n\r\n\r\nsource_path = 'F:\\download'\r\ntarget_path = 'G:\\secret'\r\nexts = ['mp4','avi','rmvb', 'rm', 'asf', 'divx', 'mpg', 'mpeg', 'mpe', 'wmv', 'mp4', 'mkv', 'vob']\r\n\r\nfor root,dirs,files in os.walk(source_path):\r\n if len(files) > 0 :\r\n for m_file in files:\r\n name, ext = os.path.splitext(m_file)\r\n ext = ext.lstrip('.')\r\n source_file_path = os.path.join(root,m_file)\r\n if ext in exts:\r\n shutil.copy(source_file_path,target_path)\r\n","sub_path":"copy_file.py","file_name":"copy_file.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"6369079","text":"#!/usr/bin/python3\n\"\"\"prints the State object with the name passed as argument from the\n...database hbtn_0e_6_usa\"\"\"\n\nimport sys\nfrom model_state import Base, State\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nif __name__ == '__main__':\n \"\"\"Your code should not be executed when imported\"\"\"\n\n # This engine just used to query for list of databases\n mysql_engine = create_engine('mysql://{}:{}@{}:{}/{}'.format(\n sys.argv[1], sys.argv[2],\n 'localhost', 3306, sys.argv[3]))\n\n # create a configured \"Session\" class and create a Session\n Session = sessionmaker(bind=mysql_engine)\n session = Session()\n\n for state in session.query(\n State).order_by(State.id).filter(State.name.like(sys.argv[4])):\n if state.id:\n print(\"{}\".format(state.id))\n break\n else:\n print(\"Not found\")\n","sub_path":"0x0F-python-object_relational_mapping/10-model_state_my_get.py","file_name":"10-model_state_my_get.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"491160490","text":"import mxnet as mx\nimport gluonnlp as nlp\n\nfrom bert_qa_evaluate import PredResult, predict, predict_span\n\nfrom mxnet.gluon.data.dataset import Dataset\n\nimport random\nimport numpy as np\n\n# https://gluon-nlp.mxnet.io/examples/sentence_embedding/bert.html\n\nimport model, data\n\nfrom mxnet.gluon import nn, Trainer, Block\n\n# https://blog.csdn.net/HappyRocking/article/details/80900890\nimport re\npattern = r'\\?|\\.|\\!|;'\n\nfrom mxnet import nd, autograd, gluon\nfrom mxnet.gluon.data import DataLoader, ArrayDataset\n\nclass VerifierDataset(Dataset):\n def __init__(self, data):\n self.data = data\n def __getitem__(self, idx):\n return self.data[idx]\n def __len__(self):\n return len(self.data)\n\nclass verifier_layers(Block):\n def __init__(self, dropout=0.0, num_classes=2, in_units=768, prefix=None, params=None):\n super(verifier_layers, self).__init__(prefix=prefix, params=params)\n with self.name_scope():\n self.classifier = nn.HybridSequential(prefix=prefix)\n self.classifier.add(nn.Dense(units=in_units, flatten=False, activation='tanh'))\n if dropout:\n self.classifier.add(nn.Dropout(rate=dropout))\n self.classifier.add(nn.Dense(units=num_classes))\n def forward(self, inputs):\n '''\n inputs are bert outputs\n '''\n return self.classifier(inputs)\n\nclass AnswerVerifyThreshold(object):\n def __init__(self, tokenizer=nlp.data.BERTBasicTokenizer(lower=True),\n max_answer_length=30,\n n_best_size=20,\n max_len=384,\n version_2=True,\n ctx=mx.cpu()):\n self.tokenizer=tokenizer\n self.max_answer_length=max_answer_length\n self.n_best_size=n_best_size\n self.version_2=version_2\n self.ctx = ctx\n\n self.data = list()\n\n self.option = 2\n\n if self.option == 1:\n self.null_score_diff_threshold = 0.0 # normally between -5 and -1\n # TODO: consider cleverer ways such as svm etc.\n elif self.option == 2:\n self.threshold = 0.45 # 0.5\n self.batch_size = 1024\n self.classifier = nn.HybridSequential()\n with self.classifier.name_scope():\n self.classifier.add(nn.Dense(units=10, activation='relu')) # input layer\n self.classifier.add(nn.Dense(units=10, activation='relu')) # inner layer 1\n self.classifier.add(nn.Dense(units=10, activation='relu')) # inner layer 2\n self.classifier.add(nn.Dense(units=1)) # output layer: notice, it must have only 1 neuron for regression\n self.classifier.initialize(init=mx.init.Xavier(), ctx=ctx)\n self.loss = gluon.loss.SigmoidBinaryCrossEntropyLoss()\n self.trainer = Trainer(params=self.classifier.collect_params(), optimizer='sgd',\n optimizer_params={'learning_rate': 0.1}) # 0.01, 0.1\n\n\n def train(self, train_features, example_ids, out, token_types=None, bert_out=None, num_epochs=1, verbose=False):\n if not self.version_2:\n return \n raw_data = self.get_training_data(train_features, example_ids, out, token_types=token_types)\n self.data.extend(raw_data)\n\n def evaluate(self, score_diff, best_pred):\n # asserted that prediction is not null\n if self.option == 1:\n if score_diff > self.null_score_diff_threshold:\n answerable = 0.\n else:\n answerable = 1.\n elif self.option == 2:\n data = mx.nd.array([[score_diff, best_pred]]).as_in_context(self.ctx)\n # Do forward pass on a batch of validation data\n output = self.classifier(data)\n # getting prediction as a sigmoid\n prediction = output.sigmoid()\n # Converting neuron outputs to classes\n predicted_classes = mx.nd.ceil(prediction - self.threshold)\n # calculate probabilities of belonging to different classes. F1 metric works only with this notation\n # prediction = prediction.reshape(-1)\n answerable = predicted_classes[0].asscalar()\n # print(score_diff, best_pred, \"answerable:\", answerable)\n # reset the data\n return answerable\n\n def update(self, epochs=100):\n if self.option == 1:\n data_numpy = np.array(self.data)\n X = np.array(data_numpy[:,:-1])\n y = np.array(data_numpy[:,-1])\n # np.mean()\n # self.null_score_diff_threshold = np.median(data_numpy[:,0])\n self.null_score_diff_threshold = np.mean(data_numpy[:,0]) + np.std(data_numpy[:,0]) * .05\n elif self.option == 2:\n data_numpy = np.array(self.data)\n X = nd.array(data_numpy[:,:-1])\n y = nd.array(data_numpy[:,-1])\n train_dataset = ArrayDataset(X, y)\n train_dataloader = DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)\n for e in range(epochs):\n cumulative_train_loss = 0\n for i, (data, label) in enumerate(train_dataloader):\n data = data.as_in_context(self.ctx)\n label = label.as_in_context(self.ctx)\n with autograd.record():\n # Do forward pass on a batch of training data\n output = self.classifier(data)\n # Calculate loss for the training data batch\n loss_result = self.loss(output, label)\n # Calculate gradients\n loss_result.backward()\n # Update parameters of the network\n self.trainer.step(len(data))\n self.data = list()\n\n def get_training_data(self, train_features, example_ids, out, token_types=None):\n output = mx.nd.split(out, axis=2, num_outputs=2)\n example_ids = example_ids.asnumpy().tolist()\n pred_start = output[0].reshape((0, -3)).asnumpy()\n pred_end = output[1].reshape((0, -3)).asnumpy()\n raw_data = []\n for example_id, start, end in zip(example_ids, pred_start, pred_end):\n results = [PredResult(start=start, end=end)]\n features = train_features[example_id]\n label = 0 if features[0].is_impossible else 1\n prediction, score_diff, top_predict = predict(\n features=features,\n results=results,\n tokenizer=self.tokenizer,\n max_answer_length=self.max_answer_length,\n n_best_size=self.n_best_size,\n version_2=self.version_2)\n non_empty_top = 1. if top_predict else 0.\n # print(prediction, \",\" , top_predict, \",\", features[0].orig_answer_text)\n raw_data.append([score_diff, non_empty_top, label])\n return raw_data\n\n\n\nclass AnswerVerifyDense(object):\n def __init__(self,\n max_answer_length=30,\n null_score_diff_threshold=-2.0,\n n_best_size=20,\n max_len=384,\n dropout=0.0,\n in_units=768,\n version_2=True,\n mode='classification',\n extract_sentence=True,\n ctx=mx.cpu(),\n offsets=False,\n prefix=None,\n params=None):\n self.max_answer_length=max_answer_length\n self.null_score_diff_threshold=null_score_diff_threshold\n self.n_best_size=n_best_size\n self.version_2=version_2\n self.ctx = ctx\n self.offsets=offsets\n self.mode = mode\n assert mode in ['classification', 'regression']\n self.num_classes = 2 if mode == 'classification' else 1\n\n # the model's definition\n self.dense_layer = verifier_layers(dropout=dropout, \n num_classes=self.num_classes, \n in_units=in_units, \n prefix=prefix, \n params=params)\n self.dense_layer.collect_params().initialize(init=mx.init.Normal(0.02), ctx=self.ctx)\n\n # the trainer's definition\n self.step_cnt = 0\n self.schedule = mx.lr_scheduler.FactorScheduler(step=1000, factor=0.9)\n self.schedule.base_lr = 3e-5\n self.eps = 5e-9\n self.extract_sentence = extract_sentence\n self.trainer = mx.gluon.Trainer(self.dense_layer.collect_params(), 'adam',\n {'learning_rate': self.schedule.base_lr, 'epsilon': self.eps}, update_on_kvstore=False)\n self.params = [p for p in self.dense_layer.collect_params().values() if p.grad_req != 'null']\n\n # loss function\n self.loss_function = self.get_loss()\n self.loss_function.hybridize(static_alloc=True)\n\n def get_loss(self):\n if self.num_classes == 1:\n return mx.gluon.loss.L2Loss()\n elif self.num_classes == 2:\n return mx.gluon.loss.SoftmaxCELoss()\n\n def parse_sentences(self, all_features, example_ids, out, token_types, bert_out):\n output = mx.nd.split(out, axis=2, num_outputs=2)\n example_ids = example_ids.asnumpy().tolist()\n pred_start = output[0].reshape((0, -3)).asnumpy()\n pred_end = output[1].reshape((0, -3)).asnumpy()\n verifier_input_shape = (bert_out.shape[0], bert_out.shape[1] + self.max_answer_length, bert_out.shape[2])\n verifier_input = mx.nd.zeros(verifier_input_shape, ctx=self.ctx)\n labels = mx.nd.array([[0 if all_features[eid][0].is_impossible else 1] \\\n for eid in example_ids]).as_in_context(self.ctx)\n labels_pred = mx.nd.zeros(labels.shape, ctx=self.ctx)\n for idx, data in enumerate(zip(example_ids, pred_start, pred_end, token_types)):\n example_id, start, end, token = data\n results = [PredResult(start=start, end=end)]\n features = all_features[example_id]\n prediction = predict_span(\n features=features,\n results=results,\n max_answer_length=self.max_answer_length,\n n_best_size=self.n_best_size,\n offsets=self.offsets,\n version_2=self.version_2)\n num_total_tokens = len(features[0].tokens)\n num_query_tokens = int((1 - token).sum().max().asscalar()) - 2\n num_contx_tokens = num_total_tokens - num_query_tokens - 3\n num_answr_tokens = prediction[1] - prediction[0] + 1\n\n if self.extract_sentence:\n # the sentence\n if num_answr_tokens == 0:\n sentence_idx = (num_query_tokens + 2, num_contx_tokens + num_query_tokens + 2)\n num_sentc_tokens = num_contx_tokens\n else:\n sentence_begin = num_query_tokens + 2\n sentence_end = num_contx_tokens + num_query_tokens + 2\n sequence_tokens = features[0].tokens\n sentence_ends_included = { i \\\n for i in range(len(sequence_tokens)) \\\n if sequence_tokens[i].find('.') != -1 or sequence_tokens[i].find('?') != -1 or sequence_tokens[i].find('!') != -1}\n sentence_ends_included.add(num_total_tokens - 2) # the ending\n sentence_begins_included = {i + 1 for i in sentence_ends_included}\n if num_total_tokens - 1 in sentence_begins_included:\n sentence_begins_included.remove(num_total_tokens - 1)\n if num_query_tokens + 1 in sentence_begins_included:\n sentence_begins_included.remove(num_query_tokens + 1)\n sentence_begins_included.add(1)\n sentence_begins_included.add(num_query_tokens + 2)\n begin_idxs = sorted(list(sentence_begins_included))\n end_idxs = sorted(list(sentence_ends_included))\n for i in range(len(begin_idxs) - 1):\n if begin_idxs[i] <= prediction[0] and begin_idxs[i+1] > prediction[0]:\n sentence_begin = begin_idxs[i]\n break \n for i in range(len(end_idxs) - 1):\n if end_idxs[i] < prediction[1] and end_idxs[i+1] >= prediction[1]:\n sentence_end = end_idxs[i+1]\n break\n sentence_idx = (sentence_begin, sentence_end)\n num_sentc_tokens = sentence_end - sentence_begin + 1\n # the beginning\n verifier_input[idx, 0, :] = bert_out[idx, 0, :]\n # the sentence embedding\n verifier_input[idx, 1:num_sentc_tokens+1, :] = bert_out[idx, sentence_idx[0]:sentence_idx[1]+1, :]\n # the query embedding\n verifier_input[idx, num_sentc_tokens+1: num_query_tokens+num_sentc_tokens+1, :] \\\n = bert_out[idx, 1:num_query_tokens+1, :]\n # the separater\n verifier_input[idx, num_query_tokens+num_sentc_tokens+1, :] = bert_out[idx, num_query_tokens+1, :]\n # the answer\n if num_answr_tokens > 0:\n verifier_input[idx, num_query_tokens+num_sentc_tokens+2:num_answr_tokens+num_query_tokens+num_sentc_tokens+2, :] \\\n = bert_out[idx, prediction[0]:prediction[1]+1,:]\n # the ending\n verifier_input[idx, num_answr_tokens+num_query_tokens+num_sentc_tokens+2, :] \\\n = bert_out[idx, num_query_tokens + num_contx_tokens+2, :]\n else:\n # the beginning\n verifier_input[idx, 0, :] = bert_out[idx, 0, :]\n # the context embedding\n verifier_input[idx, 1:num_contx_tokens+1, :] = bert_out[idx, num_query_tokens + 2: num_contx_tokens + num_query_tokens + 2, :]\n # the query embedding\n verifier_input[idx, num_contx_tokens+1: num_query_tokens+num_contx_tokens+1, :] \\\n = bert_out[idx, 1:num_query_tokens+1, :]\n # the separater\n verifier_input[idx, num_query_tokens+num_contx_tokens+1, :] = bert_out[idx, num_query_tokens+1, :]\n # the answer\n if num_answr_tokens > 0:\n verifier_input[idx, num_query_tokens+num_contx_tokens+2:num_answr_tokens+num_query_tokens+num_contx_tokens+2, :] \\\n = bert_out[idx, prediction[0]:prediction[1]+1,:]\n # the ending\n verifier_input[idx, num_answr_tokens+num_query_tokens+num_contx_tokens+2, :] \\\n = bert_out[idx, num_query_tokens + num_contx_tokens+2, :]\n # the predicted answerability\n return verifier_input, labels\n\n def train(self, train_features, example_ids, out, token_types=None, bert_out=None, num_epochs=1, verbose=False):\n if not self.version_2:\n return\n data = self.parse_sentences(train_features, example_ids, out, token_types, bert_out)\n verifier_input, labels = data\n for epoch_id in range(num_epochs):\n with mx.autograd.record():\n verify_out = self.dense_layer(verifier_input)\n ls = self.loss_function(verify_out, labels).mean()\n ls.backward()\n # Gradient clipping\n self.trainer.allreduce_grads()\n nlp.utils.clip_grad_global_norm(self.params, 1)\n self.trainer.update(1)\n self.trainer.set_learning_rate(self.schedule(self.step_cnt))\n self.step_cnt += 1\n if verbose:\n print(\"epoch {0} in dense-layer verifier ({2}), loss {1}\".format(epoch_id, ls.asscalar(), self.mode))\n \n def evaluate(self, dev_features, example_ids, out, token_types, bert_out):\n if not self.version_2:\n return mx.nd.ones(example_ids.shape)\n data = self.parse_sentences(dev_features, example_ids, out, token_types, bert_out)\n verifier_input, _ = data\n verifier_output = self.dense_layer(verifier_input)\n if self.num_classes == 1:\n pred = verifier_output.reshape(-1)\n elif self.num_classes == 2:\n pred = mx.ndarray.argmax(verifier_output, axis=1)\n return pred\n\n\nclass AnswerVerify(object):\n '''\n The BERT-based verifier\n code reference: https://gluon-nlp.mxnet.io/examples/sentence_embedding/bert.html\n mostly verifies the format of [S;Q;$;A]\n '''\n def __init__(self, tokenizer=nlp.data.BERTBasicTokenizer(lower=True),\n max_answer_length=30,\n null_score_diff_threshold=-2.0,\n n_best_size=20,\n max_len=384,\n version_2=True,\n extract_sentence=True,\n offsets=False,\n epochs=1,\n ctx=mx.cpu()):\n self.tokenizer=tokenizer\n self.max_answer_length=max_answer_length\n self.null_score_diff_threshold=null_score_diff_threshold\n self.n_best_size=n_best_size\n self.version_2=version_2\n self.offsets = offsets\n self.epochs = epochs\n\n # The labels for the two classes [(0 = not proper) or (1 = proper)]\n self.all_labels = [0, 1]\n # whether to transform the data as sentence pairs.\n # for single sentence classification, set pair=False\n # for regression task, set class_labels=None\n # for inference without label available, set has_label=False\n self.pair = True\n # The maximum length of an input sequence\n self.max_len = min(max_len, 256) # TODO: try to increase this size\n\n self.lr = 5e-6\n self.eps = 1e-9\n self.batch_size = 12\n\n self.extract_sentence = extract_sentence\n\n self.get_model(ctx)\n self.get_loss()\n\n self.metric = mx.metric.Accuracy()\n\n self.get_data_transform()\n\n self.data = list()\n\n def get_model(self, ctx):\n bert_base, self.vocabulary = nlp.model.get_model('bert_12_768_12',\n dataset_name='book_corpus_wiki_en_uncased',\n pretrained=True, ctx=ctx, use_pooler=True,\n use_decoder=False, use_classifier=False)\n self.ctx = ctx\n self.bert_classifier = model.classification.BERTClassifier(bert_base, num_classes=2, dropout=0.0)\n self.bert_classifier.classifier.initialize(init=mx.init.Normal(0.02), ctx=self.ctx)\n self.bert_classifier.hybridize(static_alloc=True)\n self.trainer = mx.gluon.Trainer(self.bert_classifier.collect_params(), 'adam',\n {'learning_rate': self.lr, 'epsilon': self.eps}, update_on_kvstore=False)\n # The gradients for these params are clipped later\n self.params = [p for p in self.bert_classifier.collect_params().values() if p.grad_req != 'null']\n\n def get_loss(self):\n self.loss_function = mx.gluon.loss.SoftmaxCELoss()\n self.loss_function.hybridize(static_alloc=True)\n\n def get_data_transform(self):\n bert_tokenizer = nlp.data.BERTTokenizer(self.vocabulary, lower=True)\n self.transform = data.transform.BERTDatasetTransform(bert_tokenizer, self.max_len,\n class_labels=self.all_labels,\n has_label=True,\n pad=True,\n pair=self.pair)\n\n def train(self, train_features, example_ids, out, token_types=None, bert_out=None):\n if not self.version_2:\n return\n data_raw = self.parse_sentences(train_features, example_ids, out)\n if len(data_raw):\n self.data.extend(data_raw)\n\n def update(self, verbose=True):\n dataset_raw = VerifierDataset(self.data)\n\n dataset = dataset_raw.transform(self.transform)\n sample_id = 0\n '''\n print('vocabulary used for tokenization = \\n%s'% self.vocabulary)\n print('%s token id = %s'%(self.vocabulary.padding_token, self.vocabulary[self.vocabulary.padding_token]))\n print('%s token id = %s'%(self.vocabulary.cls_token, self.vocabulary[self.vocabulary.cls_token]))\n print('%s token id = %s'%(self.vocabulary.sep_token, self.vocabulary[self.vocabulary.sep_token]))\n print('token ids = \\n%s'%dataset[sample_id][0])\n print('valid length = \\n%s'%dataset[sample_id][1])\n print('segment ids = \\n%s'%dataset[sample_id][2])\n print('label = \\n%s'%dataset[sample_id][3])\n exit(0)\n '''\n # The FixedBucketSampler and the DataLoader for making the mini-batches\n train_sampler = nlp.data.FixedBucketSampler(lengths=[int(item[1]) for item in dataset],\n batch_size=self.batch_size,\n num_buckets=1, # number of buckets (mini-batches), by default 10;\n shuffle=True)\n dataloader = mx.gluon.data.DataLoader(dataset, batch_sampler=train_sampler)\n\n for epoch_id in range(self.epochs):\n if verbose:\n self.metric.reset()\n step_loss = 0\n for batch_id, data in enumerate(dataloader):\n token_ids, valid_length, segment_ids, label = data\n with mx.autograd.record():\n\n # Load the data to the GPU (or CPU if GPU disabled)\n token_ids = token_ids.as_in_context(self.ctx)\n valid_length = valid_length.as_in_context(self.ctx)\n segment_ids = segment_ids.as_in_context(self.ctx)\n label = label.as_in_context(self.ctx)\n\n # Forward computation\n out = self.bert_classifier(token_ids, segment_ids, valid_length.astype('float32'))\n ls = self.loss_function(out, label).mean()\n\n # And backwards computation\n ls.backward()\n # Gradient clipping\n self.trainer.allreduce_grads()\n nlp.utils.clip_grad_global_norm(self.params, 1)\n self.trainer.update(1)\n\n if verbose:\n # update the loss and metric\n step_loss += ls.asscalar()\n self.metric.update([label], [out])\n if verbose:\n print('[Epoch {}] loss={:.4f}, lr={:.7f}, acc={:.3f}'\n .format(epoch_id,\n step_loss / len(dataloader),\n self.trainer.learning_rate, # TODO: add learning rate scheduler latter\n self.metric.get()[1]))\n step_loss = 0 \n\n self.data = list() \n # exit(0)\n\n def evaluate(self, dev_feature, prediction):\n # asserted that prediction is not null\n if not self.version_2:\n # return True\n return 1.0\n raw_data = []\n for feature in dev_feature:\n context_text = ' '.join(feature.doc_tokens)\n question_text = feature.question_text\n label = 0 if feature.is_impossible else 1\n sentences = re.split(pattern, context_text)\n sentence_text = self.find_sentence(sentences, prediction)\n first_part = sentence_text + '. ' + question_text\n second_part = prediction\n raw_data.append([first_part, second_part, label])\n dataset_raw = VerifierDataset(raw_data)\n dataset = dataset_raw.transform(self.transform)\n train_sampler = nlp.data.FixedBucketSampler(lengths=[int(item[1]) for item in dataset],\n batch_size=1,\n num_buckets=1,\n shuffle=True)\n dataloader = mx.gluon.data.DataLoader(dataset, batch_sampler=train_sampler)\n for data in dataloader:\n token_ids, valid_length, segment_ids, label = data\n out = self.bert_classifier(token_ids.as_in_context(self.ctx), segment_ids.as_in_context(self.ctx),\n valid_length.astype('float32').as_in_context(self.ctx))\n # result = out.asnumpy().reshape(-1).tolist()\n # pred = mx.ndarray.argmax(out, axis=1).astype(int)[0]\n pred = mx.ndarray.argmax(out, axis=1)[0]\n # print(out, pred, label)\n # exit(0)\n\n # eval_result = pred == 1 # True\n eval_result = pred\n return eval_result\n\n def parse_sentences(self, train_features, example_ids, out, token_types=None):\n output = mx.nd.split(out, axis=2, num_outputs=2)\n example_ids = example_ids.asnumpy().tolist()\n pred_start = output[0].reshape((0, -3)).asnumpy()\n pred_end = output[1].reshape((0, -3)).asnumpy()\n raw_data = []\n for example_id, start, end in zip(example_ids, pred_start, pred_end):\n results = [PredResult(start=start, end=end)]\n features = train_features[example_id]\n label = 0 if features[0].is_impossible else 1\n context_text = ' '.join(features[0].doc_tokens)\n question_text = features[0].question_text\n answer_text = features[0].orig_answer_text\n prediction, _, _ = predict( # TODO: use this more wisely, for example, GAN\n features=features,\n results=results,\n tokenizer=self.tokenizer,\n max_answer_length=self.max_answer_length,\n n_best_size=self.n_best_size,\n version_2=self.version_2,\n offsets=self.offsets)\n # if len(prediction) == 0:\n # continue # not validating for n/a output\n if self.extract_sentence:\n sentences = list(filter(lambda x: len(x.strip())>0, re.split(pattern, context_text) ))\n if label == 1:\n answer_sentence = self.find_sentence(sentences, answer_text)\n raw_data.append([answer_sentence + '. ' + question_text, answer_text, label])\n elif len(prediction) > 0:\n sentence_text = self.find_sentence(sentences, prediction)\n raw_data.append([sentence_text + '. ' + question_text, prediction, label])\n else:\n first_part = context_text + '. ' + question_text\n if label == 1:\n raw_data.append([first_part, answer_text, label])\n elif len(prediction) > 0:\n raw_data.append([first_part, prediction, label])\n # dataset = VerifierDataset(raw_data)\n # return dataset\n return raw_data\n\n def find_sentence(self, sentences, target):\n if len(target) == 0:\n return random.choice(sentences)\n sentence_text = ''\n for s in sentences:\n if s.find(target) != -1:\n sentence_text = s\n break\n if len(sentence_text) == 0:\n sentence_text = random.choice(sentences)\n return sentence_text\n\n","sub_path":"scripts/bert/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":27659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"556321097","text":"import socket\nimport threading\nimport unittest\nimport json\nimport time\nfrom p2pbazaar.p2pnode import P2PNode\nfrom p2pbazaar import trackerPort\nfrom p2pbazaar.test import mocks\n\nclass P2PNodeTest(unittest.TestCase):\n def setUp(self):\n self.testNode = P2PNode()\n self.trackerThread = threading.Thread(target=self.trackerFunc)\n self.nodeThread = threading.Thread(target=self.nodeFunc)\n self.trackerEvent = threading.Event()\n self.nodeEvent = threading.Event()\n \n def trackerFunc(self):\n self.mockTracker = mocks.MockTracker()\n self.trackerEvent.set()\n self.mockTracker.accept()\n \n def nodeFunc(self):\n self.mockNode = mocks.MockNode(id = 2001)\n self.nodeEvent.set()\n self.mockNode.accept()\n \n \n def tearDown(self):\n self.testNode.shutdown()\n del self.testNode\n \nclass StartupTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.mockNode = mocks.MockNode(port = 1000)\n \n def runTest(self):\n self.assertTrue(self.testNode.startup())\n targetPort = self.testNode.listenSocket.getsockname()[1]\n self.mockNode.connect(port = targetPort)\n msg = json.dumps({\"type\":\"ping\"})\n self.mockNode.sendToNode(msg)\n \n def tearDown(self):\n P2PNodeTest.tearDown(self)\n self.mockNode.shutdown()\n del self.mockNode\n \nclass TrackerConnectTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.trackerThread.start()\n \n def trackerFunc(self):\n P2PNodeTest.trackerFunc(self)\n msg = self.mockTracker.receiveDict()\n self.assertIn(\"type\", msg)\n self.assertEquals(msg[\"type\"], \"thisisme\")\n self.assertIn(\"port\", msg)\n self.assertEquals(msg[\"port\"], self.testNode.listenSocket.getsockname()[1])\n self.mockTracker.sendTIY(1000)\n self.trackerEvent.set()\n \n def runTest(self):\n self.assertTrue(self.trackerEvent.wait(5))\n self.trackerEvent.clear()\n self.assertTrue(self.testNode.trackerConnect())\n self.assertTrue(self.trackerEvent.wait(5))\n return\n \n def tearDown(self):\n P2PNodeTest.tearDown(self)\n self.mockTracker.shutdown()\n del self.mockTracker\n \nclass RequestNodeTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.trackerThread.start()\n \n def trackerFunc(self):\n P2PNodeTest.trackerFunc(self)\n msg = self.mockTracker.receiveDict()\n self.mockTracker.sendTIY(1000)\n self.trackerEvent.set()\n msg = self.mockTracker.receiveDict()\n self.assertIn(\"type\", msg)\n self.assertEquals(msg[\"type\"], \"nodereq\")\n self.assertIn(\"idList\", msg)\n self.assertIn(1000, msg[\"idList\"])\n self.trackerEvent.set()\n \n def runTest(self):\n self.assertTrue(self.trackerEvent.wait(5))\n self.trackerEvent.clear()\n self.testNode.trackerConnect()\n self.assertTrue(self.trackerEvent.wait(5))\n self.trackerEvent.clear()\n self.assertTrue(self.testNode.requestOtherNode())\n self.assertTrue(self.trackerEvent.wait(5))\n return\n \n def tearDown(self):\n P2PNodeTest.tearDown(self)\n self.mockTracker.shutdown()\n del self.mockTracker\n \nclass ConnectNodeTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.nodeThread.start()\n \n def nodeFunc(self):\n P2PNodeTest.nodeFunc(self)\n msg = self.mockNode.receiveDict()\n self.assertIn(\"type\", msg)\n self.assertEquals(msg[\"type\"], \"thisisme\")\n self.assertIn(\"id\", msg)\n self.assertEquals(msg[\"id\"], self.testNode.idNum)\n self.assertIn(\"port\", msg)\n self.assertEquals(msg[\"port\"], self.testNode.listenSocket.getsockname()[1])\n self.nodeEvent.set()\n \n def runTest(self):\n self.assertTrue(self.nodeEvent.wait(5))\n self.nodeEvent.clear()\n self.assertTrue(self.testNode.connectNode(otherID = 2001, otherNodePort = self.mockNode.listenPort))\n self.assertTrue(self.nodeEvent.wait(5))\n self.nodeEvent.clear()\n self.assertIn(2001, self.testNode.connectedNodeDict)\n self.mockNode.shutdown()\n del self.mockNode\n \n \nclass DisconnectNodeTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.nodeThread.start()\n \n def nodeFunc(self):\n P2PNodeTest.nodeFunc(self)\n msg = self.mockNode.receiveDict()\n self.nodeEvent.set()\n msg = self.mockNode.receiveDict()\n self.assertIn(\"type\", msg)\n self.assertEquals(msg[\"type\"], \"dc\")\n time.sleep(5)\n msg = self.mockNode.receive()\n self.assertEquals(msg, \"\")\n self.nodeEvent.set()\n \n def runTest(self):\n self.assertTrue(self.nodeEvent.wait(5))\n self.nodeEvent.clear()\n self.testNode.connectNode(otherID = 2001, otherNodePort = self.mockNode.listenPort)\n self.assertTrue(self.nodeEvent.wait(5))\n self.nodeEvent.clear()\n self.testNode.disconnectNode(otherID = 2001)\n self.assertTrue(self.nodeEvent.wait(10))\n self.assertNotIn(2001, self.testNode.connectedNodeDict)\n self.mockNode.shutdown()\n del self.mockNode\n \n\nclass HandleReceivedTrackerTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.mockTrackerThread = mocks.MockThread()\n self.testNode.trackerThread = self.mockTrackerThread\n \n def runTest(self):\n \n #Test ThisIsYou\n msg = json.dumps({\"type\":\"thisisyou\"})\n self.assertTrue(self.testNode.handleReceivedTracker(inPacketData = msg))\n \n #Test ping\n msg = json.dumps({\"type\":\"ping\"})\n self.assertTrue(self.testNode.handleReceivedTracker(inPacketData = msg))\n \n #Test error\n msg = json.dumps({\"type\":\"error\"})\n self.assertTrue(self.testNode.handleReceivedTracker(inPacketData = msg))\n \n #Test node reply\n msg = json.dumps({\"type\":\"nodereply\"})\n self.assertTrue(self.testNode.handleReceivedTracker(inPacketData = msg))\n \n #Test unrecognized message\n msg = json.dumps({\"type\":\"lolwat\"})\n self.assertFalse(self.testNode.handleReceivedTracker(inPacketData = msg))\n \n return\n \nclass HandleReceivedNodeTest(P2PNodeTest):\n def setUp(self):\n P2PNodeTest.setUp(self)\n self.mockNodeThread = mocks.MockThread()\n\n def runTest(self):\n thread = self.mockNodeThread\n \n #Test ping\n msg = json.dumps({\"type\":\"ping\"})\n self.assertTrue(self.testNode.handleReceivedNode(inPacketData = msg, connectThread = thread))\n \n #Test ThisIsMe\n msg = json.dumps({\"type\":\"thisisme\"})\n self.assertTrue(self.testNode.handleReceivedNode(inPacketData = msg, connectThread = thread))\n \n #Test error\n msg = json.dumps({\"type\":\"error\"})\n self.assertTrue(self.testNode.handleReceivedNode(inPacketData = msg, connectThread = thread))\n \n #Test disconnect\n msg = json.dumps({\"type\":\"dc\"})\n self.assertTrue(self.testNode.handleReceivedNode(inPacketData = msg, connectThread = thread))\n \n #Test search\n msg = json.dumps({\"type\":\"search\"})\n self.assertTrue(self.testNode.handleReceivedNode(inPacketData = msg, connectThread = thread))\n \n return\n \n \nclass PassOnSearchTest(P2PNodeTest):\n def runTest(self):\n mockNodeList=[mocks.MockNode(id = (n + 2001)) for n in range(3)]\n for node in mockNodeList:\n self.testNode.connectNode(node.idNum, node.listenPort)\n node.accept()\n recvData = [mockNodeList[n].receiveDict() for n in range(3)]\n \n searchReq1 = {\"type\":\"search\", \"returnPath\":[5, 7, 9], \"item\":\"socks\", \"id\":84}\n \n self.assertEquals(self.testNode.passOnSearchRequest(searchReq1), [2001, 2002, 2003])\n \n recvData = [mockNodeList[n].receiveDict() for n in range(3)]\n \n expectedMsg = searchReq1\n \n self.assertIn(84, self.testNode.searchRequestsSentList)\n self.assertIn(84, self.testNode.searchRequestsReceivedDict)\n self.assertEquals(self.testNode.searchRequestsReceivedDict[84], [5, 7, 9, self.testNode.idNum])\n for data in recvData:\n self.assertEquals(data, expectedMsg)\n \n searchReq2 = {\"type\":\"search\", \"returnPath\":[5, 7, 2001], \"item\":\"socks\", \"id\":76}\n expectedMsg = searchReq2\n \n self.testNode.passOnSearchRequest(searchReq2)\n \n self.assertRaises(socket.timeout, mockNodeList[0].receiveDict)\n recvData2 = [mockNodeList[n].receiveDict() for n in range(1,3)]\n \n \n self.assertIn(76, self.testNode.searchRequestsSentList)\n self.assertIn(76, self.testNode.searchRequestsReceivedDict)\n self.assertEquals(self.testNode.searchRequestsReceivedDict[76], [5, 7, 2001, self.testNode.idNum])\n self.assertEquals(expectedMsg, recvData2[0])\n self.assertEquals(expectedMsg, recvData2[1])\n \n for node in mockNodeList:\n node.shutdown()\n \n return\n \nclass ShutdownTest(P2PNodeTest):\n def runTest(self):\n self.testNode.shutdown()\n time.sleep(6)\n self.assertFalse(self.testNode.connectedNodeDict)\n self.assertTrue(self.testNode.trackerThread.shutdownFlag)\n self.assertTrue(self.testNode.listenThread.shutdownFlag)\n self.assertTrue(self.testNode.shutdownFlag)\n \nclass MakeTIMTest(P2PNodeTest):\n def runTest(self):\n self.testNode.startup()\n expectedMSG = json.dumps({\"type\":\"thisisme\", \"port\":self.testNode.listenSocket.getsockname()[1], \"id\":self.testNode.idNum})\n self.assertEquals(self.testNode._makeTIM(), expectedMSG)\n \nclass MakePingTest(P2PNodeTest):\n def runTest(self):\n expectedMSG = json.dumps({\"type\":\"ping\"})\n self.assertEquals(self.testNode._makePing(), expectedMSG)\n \nclass MakeSearchReqTest(P2PNodeTest):\n def runTest(self):\n inMsg = {\"returnPath\":[]}\n expectedMSG = json.dumps({\"returnPath\":[self.testNode.idNum]})\n self.assertEquals(self.testNode._makeSearchReq(inMsg), expectedMSG)\n \nclass MakeDCTest(P2PNodeTest):\n def runTest(self):\n expectedMSG = json.dumps({\"type\":\"dc\"})\n self.assertEquals(self.testNode._makeDC(), expectedMSG)\n \nclass MakeNodeReqTest(P2PNodeTest):\n def runTest(self):\n self.testNode.connectedNodeDict[2] = mocks.MockThread()\n expectedMSG = json.dumps({\"type\":\"nodereq\", \"idList\":[self.testNode.idNum, 2]})\n self.assertEquals(self.testNode._makeNodeReq(), expectedMSG)\n \nclass MakeErrorTest(P2PNodeTest):\n def runTest(self):\n expectedMSG = json.dumps({\"type\":\"error\", \"code\":\"bleh\"})\n self.assertEquals(self.testNode._makeError(errorCode = \"bleh\"), expectedMSG)\n expectedMSG = json.dumps({\"type\":\"error\", \"code\":\"bleh\", \"info\":\"Nothing in particular\"})\n self.assertEquals(self.testNode._makeError(errorCode = \"bleh\", readableMsg = \"Nothing in particular\"), expectedMSG)\n \nclass HandleTIMTest(P2PNodeTest):\n def runTest(self):\n mockThread = mocks.MockThread()\n self.testNode.connectedNodeDict[2001] = mockThread\n \n data = {}\n self.assertFalse(self.testNode._handleTIM(inData = data, connectThread = mockThread))\n \n data = {\"id\":2001}\n self.assertFalse(self.testNode._handleTIM(inData = data, connectThread = mockThread))\n \n data = {\"id\":2002}\n self.assertTrue(self.testNode._handleTIM(inData = data, connectThread = mockThread))\n self.assertNotIn(2001, self.testNode.connectedNodeDict)\n self.assertIn(2002, self.testNode.connectedNodeDict)\n self.assertIs(self.testNode.connectedNodeDict[2002], mockThread)\n self.assertTrue(mockThread.connectedEvent.isSet())\n \nclass HandleTIYTest(P2PNodeTest):\n def runTest(self):\n mockThread = mocks.MockThread()\n self.testNode.idNum = 2001\n \n data = {\"id\":40}\n self.assertFalse(self.testNode._handleTIY(data, mockThread))\n self.assertEquals(self.testNode.idNum, 2001)\n self.assertFalse(mockThread.connectEvent.isSet())\n \n self.testNode.trackerThread = mockThread\n data = {}\n self.assertFalse(self.testNode._handleTIY(data, mockThread))\n self.assertEquals(self.testNode.idNum, 2001)\n self.assertFalse(mockThread.connectEvent.isSet())\n \n data = {\"id\":-1}\n self.assertFalse(self.testNode._handleTIY(data, mockThread))\n self.assertEquals(self.testNode.idNum, 2001)\n self.assertFalse(mockThread.connectEvent.isSet())\n \n data = {\"id\":40}\n self.assertTrue(self.testNode._handleTIY(data, mockThread))\n self.assertEquals(self.testNode.idNum, 40)\n self.assertTrue(mockThread.connectEvent.isSet())\n \nclass HandlePingTest(P2PNodeTest):\n def runTest(self):\n mockThread = mocks.MockThread()\n mockThread.expectingPing = True\n self.assertFalse(self.testNode._handlePing(mockThread))\n self.assertFalse(mockThread.expectingPing)\n \n self.assertTrue(self.testNode._handlePing(mockThread))\n expectedMsg = json.dumps({\"type\":\"ping\"})\n self.assertEquals(mockThread.sentMsg, expectedMsg)\n \nclass HandleErrorTest(P2PNodeTest):\n def runTest(self):\n mockThread = mocks.MockThread()\n \n data = {}\n self.assertEquals(self.testNode._handleError(data, mockThread), (\"Bad message\", None))\n self.assertIsNone(mockThread.sentMsg)\n \n data = {\"code\":\"lolwat\"}\n self.assertEquals(self.testNode._handleError(data, mockThread), (\"Unrecognized message\", None))\n self.assertIsNone(mockThread.sentMsg)\n \n data = {\"code\":\"notim\"}\n self.assertEquals(self.testNode._handleError(data, mockThread), (\"notim\", None))\n self.assertEquals(mockThread.sentMsg, self.testNode._makeTIM())\n \nclass HandleDCTest(P2PNodeTest):\n def runTest(self):\n mockThread = mocks.MockThread()\n self.testNode._handleDC(mockThread)\n self.assertTrue(mockThread.shutdownFlag)\n \nclass HandleSearchTest(P2PNodeTest):\n def runTest(self):\n data = {}\n self.assertFalse(self.testNode._handleSearch(data))\n \n data = {\"id\":3}\n self.assertFalse(self.testNode._handleSearch(data))\n \n data = {\"returnPath\":[]}\n self.assertFalse(self.testNode._handleSearch(data))\n \n data = {\"id\":3, \"returnPath\":[]}\n self.assertTrue(self.testNode._handleSearch(data))\n \nclass HandleNodeReplyTest(P2PNodeTest):\n def runTest(self):\n data = {}\n mockThread = mocks.MockThread()\n self.testNode.trackerThread = mockThread\n self.assertFalse(self.testNode._handleNodeReply(data))\n \n data = {\"id\":2001, \"port\":1001}\n self.assertFalse(self.testNode._handleNodeReply(data))\n \n data = {}\n mockThread.expectingNodeReply = True\n self.assertFalse(self.testNode._handleNodeReply(data))\n self.assertTrue(mockThread.expectingNodeReply)\n \n self.nodeThread.start()\n self.assertTrue(self.nodeEvent.wait(5))\n data = {\"id\":self.mockNode.idNum, \"port\":self.mockNode.listenPort}\n self.assertTrue(self.testNode._handleNodeReply(data))\n self.assertFalse(mockThread.expectingNodeReply)\n \nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"p2pbazaar/test/p2pnodetest.py","file_name":"p2pnodetest.py","file_ext":"py","file_size_in_byte":15842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"651326806","text":"price = int(input('Price: '))\nwhile price <= 0:\n print ('Declined.Price must be non negative')\n price = int(input('Please input again: '))\n\nprint ('price accepted ')\n\npopulation = int(input('Population: '))\nwhile population <= 0:\n raise ValuError ('Declined.Population must be non negative')\n\nprint ('population accepted')\n","sub_path":"erroraise.py","file_name":"erroraise.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"396861208","text":"'''\r\nThe Morse object. This stores the indices and MORSE parameters.\r\n'''\r\nfrom itertools import combinations_with_replacement\r\nfrom squid.forcefields.helper import check_restriction\r\n\r\n\r\nBOUND_EPS = 1E-6\r\n# These are the identifiers in the parameter file that we seek out\r\n# NOTE! THEY ARE CASE SENSITIVE!\r\nMORSE_PFILE_ID = \"MORSE\"\r\nEND_ID = \"END\"\r\n\r\n\"\"\"\r\nThe Morse class contains:\r\n- :func:`__init__`\r\n- :func:`__repr__`\r\n- :func:`__eq__`\r\n- :func:`__hash__`\r\n- :func:`_printer`\r\n- :func:`print_lower`\r\n- :func:`print_upper`\r\n- :func:`unpack`\r\n- :func:`pack`\r\n- :func:`validate`\r\n- :func:`assign_line`\r\n- :func:`fix`\r\n- :classmethod:`load_smrff`\r\n------------\r\n\"\"\"\r\n\r\n\r\nclass Morse(object):\r\n '''\r\n Initialize the Morse object. The potential form can be found on the\r\n LAMMPs webpage (http://lammps.sandia.gov/doc/pair_Morse.html). Either\r\n specify all the parameters, or pass a string to line, but not both. If\r\n both are specified, an error will be thrown.\r\n **Parameters**\r\n indices: *list or tuple, str or int*\r\n The indices of the atom types in this pairwise interaction.\r\n D0: *float*\r\n D0 describes the well depth (energy units)\r\n (defined relative to the dissociated atoms).\r\n alpha: *float*\r\n alpha controls the 'width' of the potential\r\n (the smaller alpha is, the larger the well).\r\n r0: *float*\r\n r0 describes the equilibrium bond distance.\r\n rc: *float*\r\n rc describes the cutoff of the pairwise interaction.\r\n line: *str*\r\n A line from a parameter file to be parsed.\r\n **Returns**\r\n Morse: :class:`Morse`\r\n A Morse object.\r\n '''\r\n\r\n def __init__(self, indices=None, D0=None, alpha=None, r0=None, rc=None, line=None):\r\n # Assign default bounds\r\n # For the programmer: The bounds need reconsidering.\r\n self.D0_bounds = (0.1, 1000)\r\n self.alpha_bounds = (0.1, 100)\r\n self.r0_bounds = (0.1, 5.0)\r\n self.rc_bounds = (0.1, 15.0)\r\n\r\n # How many parameters exist in this potential\r\n self.N_params = 4\r\n\r\n if line is not None and all([x is None for x in [indices, D0, alpha, r0, rc]]):\r\n self.assign_line(line)\r\n elif line is None and all([x is not None for x in [indices, D0, alpha, r0, rc]]):\r\n assert isinstance(indices, list) or isinstance(indices, tuple), \"In Morse, initialized with indices not being a list or tuple!\"\r\n\r\n self.indices, self.D0, self.alpha, self.r0, self.rc = indices, D0, alpha, r0, rc\r\n\r\n self.validate()\r\n else:\r\n raise Exception(\"Either specify all Morse parameters, or the line to be parsed, but not both.\")\r\n\r\n def __repr__(self):\r\n '''\r\n This prints out a representation of this Morse object, in the format\r\n that is output to the smrff parameter file.\r\n **Returns**\r\n Morse: *str*\r\n A string representation of Morse parameters.\r\n It is in the following order:\r\n indices D0 alpha r0 rc\r\n '''\r\n return self._printer(with_indices=True, bounds=None)\r\n\r\n def __eq__(self, other):\r\n\r\n if isinstance(other, tuple) or isinstance(other, list):\r\n indices = [str(o) if str(o) != \"*\" else str(i) for o, i in zip(other, self.indices)]\r\n elif hasattr(other, indices):\r\n indices = [str(o) if str(o) != \"*\" else str(i) for o, i in zip(other.indices, self.indices)]\r\n else:\r\n return False\r\n\r\n return (all([x == y for x, y in zip(self.indices, indices)]) or\r\n all([x == y for x, y in zip(self.indices, indices[::-1])]))\r\n\r\n def __hash__(self):\r\n return hash(tuple(self.unpack(with_indices=True) + self.unpack(bounds=0) + self.unpack(bounds=1)))\r\n\r\n def _printer(self, with_indices=True, bounds=None):\r\n '''\r\n This prints out a representation of this Morse object,\r\n in the format that is output to the smrff parameter file.\r\n **Parameters**\r\n with_indices: *bool, optional*\r\n Whether to also include the indices in the output.\r\n bounds: *int, optional*\r\n Whether to output the lower bounds (0), or upper bounds (1).\r\n If None, then the parameters themselves are output instead (default).\r\n **Returns**\r\n Morse: *str*\r\n A string representation of Morse parameters.\r\n It is in the following order: indices D0 alpha r0 rc\r\n '''\r\n self.validate()\r\n return (\" \".join(list(self.indices)) +\r\n \" %.7f %.7f %.7f %.7f\" % tuple(self.unpack(with_indices=with_indices, bounds=bounds)[1:]))\r\n\r\n def print_lower(self):\r\n '''\r\n This prints out a representation of this Morse object's lower bound,\r\n in the format that is output to the smrff parameter file.\r\n **Returns**\r\n Morse: *str*\r\n A string representation of Morse parameters.\r\n It is in the following order: indices D0 alpha r0 rc\r\n '''\r\n return self._printer(with_indices=True, bounds=0)\r\n\r\n def print_upper(self):\r\n '''\r\n This prints out a representation of this Morse object's upper bound,\r\n in the format that is output to the smrff parameter file.\r\n **Returns**\r\n Morse: *str*\r\n A string representation of Morse parameters.\r\n It is in the following order: indices D0 alpha r0 rc\r\n '''\r\n return self._printer(with_indices=True, bounds=1)\r\n\r\n def unpack(self, with_indices=True, bounds=None, with_bounds=False):\r\n '''\r\n This function unpacks the Morse object into a list.\r\n **Parameters**\r\n with_indices: *bool, optional*\r\n Whether to also include the indices in the list.\r\n bounds: *int, optional*\r\n Whether to output the lower bounds (0), or upper bounds (1).\r\n If None, then the parameters themselves are output instead (default).\r\n **Returns**\r\n Morse: *list, str/float*\r\n A list, holding the string of the indices, D0, alpha, r0, rc.\r\n '''\r\n self.validate()\r\n\r\n pkg = []\r\n\r\n if bounds is not None:\r\n if with_indices:\r\n pkg.append([self.indices,\r\n self.D0_bounds[bounds], self.alpha_bounds[bounds],\r\n self.r0_bounds[bounds], self.rc_bounds[bounds]])\r\n else:\r\n pkg.append([self.D0_bounds[bounds], self.alpha_bounds[bounds],\r\n self.r0_bounds[bounds], self.rc_bounds[bounds]])\r\n else:\r\n if with_indices:\r\n pkg.append([self.indices,\r\n self.D0, self.alpha, self.r0, self.rc])\r\n else:\r\n pkg.append([self.D0, self.alpha, self.r0, self.rc])\r\n\r\n if with_bounds:\r\n # Get all lower and upper bounds added to pkg\r\n # After this, pkg = [params, lower, upper]\r\n for bnd in zip(zip(self.D0_bounds, self.alpha_bounds, self.r0_bounds, self.rc_bounds)):\r\n pkg.append(*bnd)\r\n\r\n return pkg\r\n\r\n return pkg[0]\r\n\r\n\r\n def pack(self, params):\r\n '''\r\n This function packs the Morse object from a list.\r\n **Parameters**\r\n params: *list*\r\n A list holding the indices, D0, alpha, r0, rc.\r\n **Returns**\r\n None\r\n '''\r\n assert len(params) in [4, 5], \"In Morse, tried packing %d parameters. Should be either 4 or 5!\" % len(params)\r\n\r\n if len(params) == 5:\r\n offset = 0\r\n self.indices = params[0 + offset]\r\n else:\r\n offset = -1\r\n self.D0 = params[1 + offset]\r\n self.alpha = params[2 + offset]\r\n self.r0 = params[3 + offset]\r\n self.rc = params[4 + offset]\r\n\r\n self.validate()\r\n\r\n def validate(self):\r\n '''\r\n This function will validate data integrity.\r\n In this case, we simply ensure data types are appropriate.\r\n '''\r\n self.indices = [str(x) for x in self.indices]\r\n self.D0 = float(self.D0)\r\n self.alpha = float(self.alpha)\r\n self.r0 = float(self.r0)\r\n self.rc = float(self.rc)\r\n params = [self.D0, self.alpha, self.r0, self.rc]\r\n bounds = [self.D0_bounds, self.alpha_bounds, self.r0_bounds, self.rc_bounds]\r\n names = [\"D0\", \"alpha\", \"r0\", \"rc\"]\r\n for param, bound, name in zip(params, bounds, names):\r\n assert param >= (bound[0] - BOUND_EPS) and param <= (bound[1] + BOUND_EPS), \"In Morse %s, parameter %s = %.2f is outside of it's range = [%.2f, %.2f]!\" % (str(self.indices), name, param, bound[0], bound[1])\r\n\r\n @staticmethod\r\n def parse_line(line):\r\n \"\"\"\r\n Parse line inputs and assign to this object.\r\n **Parameters**\r\n line: *str*\r\n A string that holds a three-body Morse parameter set.\r\n **Returns**\r\n None\r\n \"\"\"\r\n line = line.strip().split()\r\n\r\n indices = (line[0], line[1])\r\n D0 = float(line[2])\r\n alpha = float(line[3])\r\n r0 = float(line[4])\r\n rc = float(line[5])\r\n\r\n return indices, D0, alpha, r0, rc\r\n\r\n def assign_line(self, line):\r\n self.indices, self.D0, self.alpha, self.r0, self.rc = self.parse_line(line)\r\n self.validate()\r\n\r\n def fix(self, params='all', value=None):\r\n '''\r\n This will fix these parameters by assigning bounds to the values themselves.\r\n '''\r\n if params == 'all':\r\n if value is not None:\r\n assert isinstance(value, list) or isinstance(value, tuple), \"Error - Trying to set all Morse params without passing list/tuple (passed %s).\" % str(value)\r\n assert len(value) == 4, \"Error - Not the right number of parameters (4) passed to fix all in Morse (passed %s).\" % str(value)\r\n self.D0, self.alpha, self.r0, self.rc = [float(f) for f in value]\r\n self.D0_bounds = (self.D0, self.D0)\r\n self.alpha_bounds = (self.alpha, self.alpha)\r\n self.r0_bounds = (self.r0, self.r0)\r\n self.rc_bounds = (self.rc, self.rc)\r\n elif params == 'D0':\r\n if value is not None:\r\n if isinstance(value, list) or isinstance(value, tuple):\r\n assert len(value) == 1, \"Error - passed more than one value when fixing D0 in Morse (passed %s).\" % str(value)\r\n value = value[0]\r\n self.D0 = float(value)\r\n self.D0_bounds = (self.D0, self.D0)\r\n elif params == 'alpha':\r\n if value is not None:\r\n if isinstance(value, list) or isinstance(value, tuple):\r\n assert len(value) == 1, \"Error - passed more than one value when fixing alpha in Morse (passed %s).\" % str(value)\r\n value = value[0]\r\n self.alpha = float(value)\r\n self.alpha_bounds = (self.alpha, self.alpha)\r\n elif params == \"r0\":\r\n if value is not None:\r\n if isinstance(value, list) or isinstance(value, tuple):\r\n assert len(value) == 1, \"Error - passed more than one value when fixing r0 in Morse (passed %s).\" % str(value)\r\n value = value[0]\r\n self.r0 = float(value)\r\n self.r0_bounds = (self.r0, self.r0)\r\n elif params == \"rc\":\r\n if value is not None:\r\n if isinstance(value, list) or isinstance(value, tuple):\r\n assert len(value) == 1, \"Error - passed more than one value when fixing rc in Morse (passed %s).\" % str(value)\r\n value = value[0]\r\n self.rc = float(value)\r\n self.rc_bounds = (self.rc, self.rc)\r\n else:\r\n raise Exception(\"In Morse, tried fixing %s parameter (does not exist)!\" % params)\r\n\r\n @classmethod\r\n def load_smrff(cls, pfile, pfptr=None, restrict=None):\r\n '''\r\n Given a parameter file, import the Morse parameters if possible.\r\n **Parameters**\r\n pfile: *str*\r\n A parsed smrff parameter file input string.\r\n (no comments or trailing white spaces)\r\n pfptr: *str*\r\n The name of a parameter file to be parsed.\r\n If specified, then pfile is ignored.\r\n (you may simply pass None as pfile)\r\n (For programmer: The name of this parameter must be changed. It is hard to understand.)\r\n **Returns**\r\n Morse_objs: *list, Morse*, or *None*\r\n Returns a list of Morse objects if possible, else None.\r\n '''\r\n import squid.forcefields.smrff as smrff_utils\r\n\r\n # Ensure correct pfile format, and that we even need to parse it.\r\n if pfptr is not None:\r\n pfile = smrff_utils.parse_pfile(pfptr)\r\n if MORSE_PFILE_ID not in pfile:\r\n return []\r\n pfile = pfile[pfile.index(MORSE_PFILE_ID):]\r\n pfile = pfile[:pfile.index(END_ID)].split(\"\\n\")[1:-1]\r\n\r\n pfile = [cls.parse_line(line) for line in pfile]\r\n\r\n return [\r\n cls(indices=indices, D0=D0, alpha=alpha, r0=r0, rc=rc, line=None)\r\n for indices, D0, alpha, r0, rc in pfile if check_restriction(indices, restrict)\r\n ]\r\n\r\n @classmethod\r\n def generate(cls, atom_types):\r\n '''\r\n Randomly generate parameters for morse.\r\n\r\n **Parameters**\r\n\r\n atom_types: *list, str*\r\n A list of all the atom types to have parameters generated for.\r\n\r\n **Returns**\r\n\r\n morse_objs: *list, Morse*\r\n Returns a list of Morse objects.\r\n '''\r\n from helper import random_in_range\r\n\r\n morse_objs = []\r\n\r\n for indices in combinations_with_replacement(atom_types, 2):\r\n D0 = random_in_range((0.1, 1000))\r\n alpha = random_in_range((0.1, 100))\r\n r0 = random_in_range((0.1, 5.0))\r\n rc = random_in_range((0.1, 15.0))\r\n morse_objs.append(cls(indices, D0, alpha, r0, rc))\r\n\r\n return morse_objs\r\n\r\n","sub_path":"squid/forcefields/morse.py","file_name":"morse.py","file_ext":"py","file_size_in_byte":14395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"421206279","text":"import retro\nimport sys\nimport numpy as np\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel\nfrom PyQt5.QtGui import QImage, QPixmap\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtCore import QTimer\nfrom PyQt5.QtGui import QPainter, QPen, QBrush, QColor\n\n\nclass MyApp(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.height = 0\n self.width = 0\n\n\n self.env = retro.make(game='SuperMarioBros-Nes', state='Level1-1')\n # 램 정보 가져오기\n\n\n # 새 게임 시작\n self.env.reset()\n # 화면 가져오기\n self.screen = self.env.get_screen()\n # 키 배열 B, NULL, SELECT, START, U, D, L, R, A\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n\n\n # 창의 크기 고정\n self.setFixedSize(1200, 480)\n\n # 창 제목\n self.setWindowTitle('GA Mario')\n\n self.label_image = QLabel(self)\n self.label_image.setGeometry(0, 0, 428, 480)\n\n\n\n\n # 타이머 생성\n qtimer = QTimer(self)\n # 타이머에 실행할 함수 연결\n qtimer.timeout.connect(self.timer)\n # 1초마다 연결된 함수를 실행\n qtimer.start(1000//60)\n # 창 띄우기\n self.show()\n\n\n\n def keyPressEvent(self, event):\n key = event.key()\n\n if key == Qt.Key_Up:\n self.button = [0, 0, 0, 0, 1, 0, 0, 0, 0]\n\n if key == Qt.Key_Down:\n self.button = [0, 0, 0, 0, 0, 1, 0, 0, 0]\n\n if key == Qt.Key_Left:\n self.button = [0, 0, 0, 0, 0, 0, 1, 0, 0]\n\n if key == Qt.Key_Right:\n self.button = [0, 0, 0, 0, 0, 0, 0, 1, 0]\n\n if key == Qt.Key_Z:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 1]\n\n if key == Qt.Key_X:\n self.button = [1, 0, 0, 0, 0, 0, 0, 0, 0]\n\n def keyReleaseEvent(self, event):\n key = event.key()\n\n if key == Qt.Key_Up:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n if key == Qt.Key_Down:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n if key == Qt.Key_Left:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n if key == Qt.Key_Right:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n if key == Qt.Key_Z:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n if key == Qt.Key_X:\n self.button = [0, 0, 0, 0, 0, 0, 0, 0, 0]\n\n def update_screen(self):\n image = self.env.get_screen()\n qimage = QImage(image, image.shape[1], image.shape[0], QImage.Format_RGB888)\n pixmap = QPixmap(qimage)\n pixmap = pixmap.scaled(428, 480, Qt.IgnoreAspectRatio)\n self.label_image.setPixmap(pixmap)\n\n def paintEvent(self, event):\n\n ram = self.env.get_ram()\n\n full_screen_tiles = ram[0x0500:0x069F + 1]\n\n full_screen_tiles_count = full_screen_tiles.shape[0]\n full_screen_page1_tile = full_screen_tiles[:full_screen_tiles_count // 2].reshape((13, 16))\n full_screen_page2_tile = full_screen_tiles[full_screen_tiles_count // 2:].reshape((13, 16))\n\n full_screen_tile = np.concatenate((full_screen_page1_tile, full_screen_page2_tile), axis=1).astype(np.int)\n\n painter = QPainter()\n\n painter.begin(self)\n\n\n for first_arry in full_screen_tile:\n\n for second_array in first_arry:\n\n if second_array == 0:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.gray))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n elif second_array == 84:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.blue))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n elif second_array == 192:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.green))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n elif second_array == 193:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.darkYellow))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n elif second_array == 6:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.red))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n else:\n painter.setPen(QPen(Qt.black, 1.0, Qt.SolidLine))\n\n painter.setBrush(QBrush(Qt.blue))\n\n painter.drawRect(540 + self.width, 20 + self.height, 20, 20)\n\n self.width += 20\n\n\n\n self.width = 0\n self.height += 20\n\n\n\n\n\n def timer(self):\n self.env.step(np.array(self.button))\n self.update_screen()\n self.update()\n self.height = 0\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = MyApp()\n sys.exit(app.exec())","sub_path":"lab_mario/도전과제 8.py","file_name":"도전과제 8.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"157508576","text":"\"\"\"Build in connectors.\n\n\nConnectors have to implement `process_request`.\n\"\"\"\nfrom .errors import HTTPError\n\ntry:\n import aiohttp\n import asyncio\n\n class AHConnector:\n \"\"\"Connector implementation using aiohttp.\"\"\"\n def __init__(self, sess=None, loop=None):\n self.loop = loop or asyncio.get_event_loop()\n self.sess = sess or aiohttp.ClientSession(loop=self.loop)\n self.closed = False\n\n def __del__(self):\n if not self.closed:\n self.close()\n\n def close(self):\n self.closed = True\n self.sess.close()\n\n @asyncio.coroutine\n def process_request(self, endpoint, data, type_):\n \"\"\"Make and process the request.\n\n Parameters\n -----------\n endpoint : `str`\n The HTTP endpoint to make a request to\n data : `dict`\n The parameters for making the HTTP request\n type_ : `type`\n A converter to which to pass the response json and return.\n \"\"\"\n resp = yield from self.sess.get(endpoint, params=data)\n if resp.status != 200:\n raise HTTPError(resp.status, resp.reason, (yield from resp.text()))\n data = yield from resp.json()\n resp.close()\n return type_(data)\nexcept ImportError:\n pass\n\ntry:\n import requests\n\n class ReqConnector:\n \"\"\"Connector implementation using requests.\"\"\"\n def __init__(self, sess=None):\n self.sess = sess or requests.Session()\n\n def __del__(self):\n self.close()\n\n def close(self):\n self.sess.close()\n\n def process_request(self, endpoint, data, type_):\n \"\"\"Make and process the request.\n\n Parameters\n -----------\n endpoint : `str`\n The HTTP endpoint to make a request to\n data : `dict`\n The parameters for making the HTTP request\n type_ : `type`\n A converter to which to pass the response json and return.\n \"\"\"\n resp = self.sess.get(endpoint, params=data)\n if resp.status_code != 200:\n raise HTTPError(resp.status_code, resp.reason, resp.text)\n data = resp.json()\n resp.close()\n return type_(data)\nexcept ImportError:\n pass\n","sub_path":"osuapi/connectors.py","file_name":"connectors.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"298310614","text":"import numpy as np\nimport numpy.linalg as nla\n\n\ndef kmeans(data, k, num_iterations, num_inits=10, verbose=False):\n \"\"\"Execute the k-means algorithm for\n determining the best k clusters of data\n points in a dataset.\n \n Parameters\n ----------\n data : ndarray, (n,d)\n n data points in R^d.\n k : int\n The number of clusters to separate\n the data into.\n num_iterations : int\n The number of iterations of the k-means\n algorithm to execute.\n num_inits : int, optional\n Number of random initializations to try.\n Returns the best result.\n verbose : bool, optional\n Specifies whether to print info about\n the execution of the algorithm.\n \n \n Return\n ------\n (clusters, data_point_assigment, centroids)\n The results of the k-means algorithm. Clusters\n is a list of the clusters (which are lists of ints).\n data_point_assigment is a (n,) numpy array of ints \n that indicates which cluster a data point has been\n assigned to. And centroids is (k,d) numpy array\n specifying the cluster centers.\n \"\"\"\n \n # Number of data points\n num_data_points = int(data.shape[0])\n \n # Spatial dimension d\n d = int(data.shape[1])\n \n best_results = None\n best_total_distance = np.inf\n \n for init in range(num_inits):\n # Map from data point index to cluster index.\n data_point_assignment = np.zeros(num_data_points, dtype=int)\n # list of data points in clusters\n clusters = [[]] * k\n\n # Initialize the centroids \n # using k-randomly sampled points.\n centroids = np.zeros((d,k))\n for ind_cluster in range(k):\n inds_data = np.random.choice(num_data_points, k)\n centroid = np.mean(data[inds_data, :], axis=0)\n\n centroids[:, ind_cluster] = centroid\n\n for iteration in range(num_iterations):\n if verbose:\n print('==== Iteration {}/{} ===='.format(iteration+1, num_iterations))\n print('centroids = {}'.format(centroids))\n\n clusters = []\n for ind_c in range(k):\n clusters.append([])\n\n # Assignment step:\n # Assign each data point to the \n # cluster with nearest centroid.\n total_distance = 0.0\n for ind_point in range(num_data_points):\n distances = np.array([nla.norm(data[ind_point, :] - centroids[:, ind_c]) for ind_c in range(k)])\n ind_cluster = np.argmin(distances)\n \n total_distance += distances[ind_cluster]\n\n data_point_assignment[ind_point] = ind_cluster\n clusters[ind_cluster].append(ind_point)\n\n # Update step:\n # Update the centroids of the\n # new clusters.\n for ind_cluster in range(k):\n cluster = clusters[ind_cluster]\n cluster_data = np.array([data[ind_point, :] for ind_point in cluster])\n centroid = np.mean(cluster_data, axis=0)\n\n centroids[:, ind_cluster] = centroid\n \n if total_distance < best_total_distance:\n best_total_distance = total_distance\n best_results = (clusters, data_point_assignment, centroids)\n \n return best_results\n\ndef spectral_clustering(data, k, num_iterations, kernel_fun, L_type='unnormalized', num_inits=10, verbose=False):\n \"\"\"Execute the spectral clustering algorithm for\n determining the best k clusters of data\n points in a dataset.\n \n Parameters\n ----------\n data : ndarray, (n,d)\n n data points in R^d.\n k : int\n The number of clusters to separate\n the data into.\n num_iterations : int\n The number of iterations of the k-means\n algorithm to execute.\n kernel_fun : function(ndarray, ndarray)\n A kernel function that computes a similarity\n between two numpy arrays.\n L_type : str, optional\n The type of graph Laplacian to use: 'unnormalized' \n (default), 'symmetric', or 'randomwalk'.\n num_inits : int, optional\n Number of random initializations to try.\n Returns the best result.\n verbose : bool, optional\n Specifies whether to print info about\n the execution of the algorithm.\n \n \n Return\n ------\n (clusters, data_point_assigment, centroids)\n The results of the k-means algorithm on the spectrally\n embedded data. Clusters is a list of the clusters \n (which are lists of ints). data_point_assigment is \n a (n,) numpy array of ints that indicates which \n cluster a data point has been assigned to. And \n centroids is (k,d) numpy array specifying the \n cluster centers.\n \"\"\"\n \n num_samples = int(data.shape[0])\n \n # The kernel matrix of the data.\n kernel_matrix = np.zeros((num_samples, num_samples))\n for i in range(num_samples):\n for j in range(i, num_samples):\n kernel_matrix[i,j] = kernel_fun(data[i,:], data[j,:])\n kernel_matrix[j,i] = kernel_matrix[i,j]\n\n degrees = np.sum(kernel_matrix, axis=0)\n \n # Degree matrix\n D = np.diag(degrees)\n # Kernel (affinity) matrix\n K = kernel_matrix\n \n if L_type == 'unnormalized':\n L = D - K\n elif L_type == 'symmetric':\n Dinvsqrt = np.diag(degrees**(-0.5))\n L = np.eye(num_samples) - np.dot(Dinvsqrt, np.dot(K, Dinvsqrt))\n elif L_type == 'randomwalk':\n Dinv = np.diag(1.0 / degrees)\n L = np.eye(num_samples) - np.dot(Dinv, K)\n \n (eigvals, eigvecs) = nla.eigh(L)\n \n spectral_data = eigvecs[:, 1:(k+1)]\n \n return kmeans(spectral_data, k, num_iterations, num_inits=num_inits, verbose=verbose)\n","sub_path":"assets/codes/spectralclustering/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":5878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"193143315","text":"from data_inputs import load_data\r\n\r\nBLACK = 0\r\nWHITE = 1\r\nCLEAR = 2\r\n\r\n\r\ndef get_grid(data, width, height):\r\n grid = []\r\n for h in range(height):\r\n row = []\r\n grid.append(row)\r\n for w in range(width):\r\n row.append(int(data.pop(0)))\r\n return grid\r\n\r\n\r\ndef get_layers(data, width, height):\r\n sol = []\r\n while data:\r\n grid = get_grid(data, width, height)\r\n sol.append(grid)\r\n return sol\r\n\r\n\r\ndef count_val(grid, val):\r\n count = 0\r\n for row in grid:\r\n for x in row:\r\n if x == val:\r\n count += 1\r\n return count\r\n\r\n\r\ndef grid_to_colour_grid(g):\r\n colours = g[0]\r\n for layer in g[1:]:\r\n for x, row in enumerate(layer):\r\n for y, val in enumerate(row):\r\n if colours[x][y] == CLEAR:\r\n colours[x][y] = val\r\n return colours\r\n\r\n\r\nif __name__ == '__main__':\r\n data = load_data(8)[0]\r\n data = list(data)\r\n\r\n test = list('123456789012')\r\n assert get_layers(test, 3, 2) == [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [0, 1, 2]]]\r\n\r\n g = get_layers(data, 25, 6)\r\n sol = []\r\n for idx, grid in enumerate(g):\r\n sol.append((count_val(grid, 0), idx))\r\n layer = g[min(sol)[1]]\r\n print(count_val(layer, 1) * count_val(layer, 2))\r\n\r\n # Part 2\r\n test = list('0222112222120000')\r\n g = get_layers(test, 2, 2)\r\n assert grid_to_colour_grid(g) == [[0, 1], [1, 0]]\r\n\r\n data = load_data(8)[0]\r\n data = list(data)\r\n g = get_layers(data, 25, 6)\r\n pxls = grid_to_colour_grid(g)\r\n for i in pxls:\r\n line = ''.join(map(str, i))\r\n print(line.replace('0', ' ').replace('1', '\\u2588'))\r\n","sub_path":"aoc08.py","file_name":"aoc08.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"271826711","text":"import sys\nimport pickle\nfrom sklearn.decomposition import PCA\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom shapely.geometry import LineString\nimport scipy.io\n\n\n\ndef updatePCs(stormNumber):\n\n with open(r'nourishmentProfileEOFs2.pickle', \"rb\") as input_file:\n outputEOFs = pickle.load(input_file)\n\n zInt = outputEOFs['zInt']\n x = outputEOFs['x']\n dist = x\n originalIPCA = PCA(n_components=9)\n origPCs = originalIPCA.fit_transform(zInt)\n\n dataPredS = scipy.io.loadmat('latestScarpProfile2.mat')\n distm = dataPredS['dist']\n predScarpX = dataPredS['predScarpX']\n predScarpZ = dataPredS['predScarpZ']\n zInterp = dataPredS['zInterp']\n\n newPCs = originalIPCA.transform(zInterp)#surrogateProf.reshape(1,-1))\n\n #newPCs = [pc1,pc2,pc3,pc4,pc5,pc6,pc7,pc8,pc9]\n newPCsProfile = originalIPCA.inverse_transform(newPCs)\n\n latestPCs = dict()\n latestPCs['newPCs'] = newPCs\n latestPCs['newPCsProfile'] = newPCsProfile\n latestPCs['dist'] = dist\n scipy.io.savemat('latestProfileFit2.mat', latestPCs)\n\n return newPCs\n\n\n\nif __name__ == '__main__':\n\n stormNumber = float(sys.argv[1])\n\n newPCs = updatePCs(stormNumber)\n","sub_path":"convertToPCs2.py","file_name":"convertToPCs2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"402776682","text":"import pygame\nfrom Constants import *\nfrom Player import *\n\nclass Main():\n def __init__(self, screen):\n \"\"\"\n Init function\n :param screen:\n \"\"\"\n self.screen = screen\n self.background = pygame.image.load('images/background.jpg')\n self.player = Player(\"Sergiy\")\n self.running = True\n self.main_loop()\n\n def handle_events(self):\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n self.running = False\n\n # Moving player\n elif e.type == pygame.KEYDOWN: # On key down\n if e.key == pygame.K_RIGHT:\n self.player.direction = RIGHT\n self.player.moving = [1, 0, 0, 0]\n if e.key == pygame.K_DOWN:\n self.player.direction = DOWN\n self.player.moving = [0, 1, 0, 0]\n if e.key == pygame.K_LEFT:\n self.player.direction = LEFT\n self.player.moving = [0, 0, 1, 0]\n if e.key == pygame.K_UP:\n self.player.direction = UP\n self.player.moving = [0, 0, 0, 1]\n\n elif e.type == pygame.KEYUP: # On key up\n if e.key == pygame.K_UP:\n self.player.moving[UP] = 0\n if e.key == pygame.K_DOWN:\n self.player.moving[DOWN] = 0\n if e.key == pygame.K_LEFT:\n self.player.moving[LEFT] = 0\n if e.key == pygame.K_RIGHT:\n self.player.moving[RIGHT] = 0\n\n\n def render(self):\n \"\"\"\n Rendering everything\n \"\"\"\n self.screen.blit(self.background, (0, 0))\n self.player.render(screen)\n pygame.display.flip()\n\n def main_loop(self):\n \"\"\"\n The main loop\n \"\"\"\n while self.running == True:\n self.player.move()\n self.render()\n self.handle_events()\n\n\npygame.init()\nscreen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\ngame = Main(screen)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"441106477","text":"from resources.src.common.utils import *\n\n\nclass Main(object):\n def __init__(self):\n notice(\"Starting %s, version %s\" % (SCRIPT_ID, SCRIPT_VERSION))\n from resources.src.gui.main_window import MainWindow\n MainWindow(\"main_window.xml\", SCRIPT_PATH, 'Default').doModal()\n del MainWindow\n\nif (__name__ == \"__main__\"):\n Main()\n debug(\"Stopping %s, version %s\" % (SCRIPT_ID, SCRIPT_VERSION))\n\n","sub_path":"script.video.iptv.novoe.tv/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"526211840","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\n# filename : example4.py\n# 선택정렬 \nimport timeit, random\n\ndef sel_sort(a):\n n = len(a)\n for i in range(0, n - 1): \n min_idx = i\n for j in range(i + 1, n):\n if a[j] > a[min_idx]:\n min_idx = j\n a[i], a[min_idx] = a[min_idx], a[i]\n \n print (a)\n\nmyList = []\nnum = random.randrange(0, 1000)\nfor i in range(2) :\n while num in myList : # 중복될 경우\n num = random.randrange(0, 1000) # 다시 난수 생성\n myList.append(num) # 중복 되지 않은 경우만 추가\n\nstart = timeit.default_timer()\nsel_sort(myList)\nstop = timeit.default_timer()\nprint (\"execute time : %f\" %(stop - start))\n\n\n\n","sub_path":"algorithm/example4.py","file_name":"example4.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"34500702","text":"##################################################\n# csvmodule.py\n##################################################\n# CSV data loading & saving\n###################################################\n\nimport csv\n\n'''load data from CSV file'''\ndef loaddata(filename):\n f=open(filename,mode='r')\n data=[]\n csv_reader=csv.DictReader(f)\n line=0\n for row in csv_reader:\n if line != 0 :\n t1 = row['team1']\n t2 = row['team2']\n data.append((float(t1),float(t2)))\n line=line+1\n f.close()\n return data\n\n'''Store probability data'''\ndef store_probability_data(D,folder):\n f=open('{}{}'.format(folder,\"probability.csv\"), mode='w')\n fieldnames=['data','win1','win2','equality']\n\n writer=csv.DictWriter(f , fieldnames=fieldnames)\n writer.writeheader()\n writer.writerow({'data': 'prognostics',\n 'win1': D['prog_1'],\n 'win2': D['prog_2'],\n 'equality': D['prog_eq']})\n writer.writerow({'data': 'count',\n 'win1': D['count_win_1'],\n 'win2': D['count_win_2'],\n 'equality': D['count_eq']})\n\n writer.writerow({'data': 'frequency',\n 'win1': D['freq_win_1'],\n 'win2': D['freq_win_2'],\n 'equality': D['freq_eq']})\n\n writer.writerow({'data': 'probability_binomial',\n 'win1': D['p1_binomial'],\n 'win2': D['p2_binomial'],\n 'equality': D['peq_binomial']})\n\n writer.writerow({'data': 'probability_pascal',\n 'win1': D['p1_pascal'],\n 'win2': D['p2_pascal'],\n 'equality': D['peq_pascal']})\n\n writer.writerow({'data': 'risk_binomial',\n 'win1': D['risk1_binomial'],\n 'win2': D['risk2_binomial'],\n 'equality': D['riskeq_binomial']})\n\n writer.writerow({'data': 'risk_pascal',\n 'win1': D['risk1_pascal'],\n 'win2': D['risk2_pascal'],\n 'equality': D['riskeq_pascal']})\n\n f.close()\n\n'''Store quantitative data'''\ndef store_quant_data(D,folder):\n f=open('{}{}'.format(folder,\"quantitative.csv\"), mode='w')\n fieldnames=['data','team1','team2','total']\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerow({'data':'mean',\n 'team1':D['mean1'],\n 'team2':D['mean2'],\n 'total':D['total_mean']})\n\n writer.writerow({'data':'std_deviation',\n 'team1':D['std_dev_1'],\n 'team2':D['std_dev_2'],\n 'total':D['total_std_dev']})\n f.close()\n","sub_path":"csvmodule.py","file_name":"csvmodule.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"416650621","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n#Aim is to print a list of all the titles from nzherald.co.nz\r\n\r\n#requesting info from the nzherald\r\nr = requests.get('https://nzherald.co.nz')\r\n#getting html\r\nweb_page = r.text\r\n# Passing to BeautifulSoup\r\nworkpls = BeautifulSoup(web_page)\r\n\r\n#Matching all the titles, which were all h3 at this website\r\ntitles = workpls.find_all('h3')\r\n\r\n#Saving to text file\r\nfilee = open('C:/Users/Matt/Downloads/Life man/Crypto/datasci/Python programs/Titles.txt', 'w')\r\n\r\n#Writing to text file\r\nfor i in range(0,len(titles)):\r\n filee.write(titles[i].get_text() +'\\n')\r\n\r\nfilee.close()\r\nprint('File created!')\r\n","sub_path":"Requests.py","file_name":"Requests.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"333069179","text":"import pyccl as ccl\nimport numpy as np\nfrom ..lss import LinearBiasSystematic\n\n\nclass DummySource(object):\n pass\n\n\ndef test_linear_bias_systematic_smoke():\n src = DummySource()\n src.z_ = np.linspace(0, 2.0, 10)\n src.bias_ = 30.0\n cosmo = ccl.Cosmology(\n Omega_c=0.27,\n Omega_b=0.045,\n Omega_k=0.0,\n w0=-1.0,\n wa=0.0,\n sigma8=0.8,\n n_s=0.96,\n h=0.67)\n gf = ccl.growth_factor(cosmo, 1.0 / (1.0 + src.z_))\n params = {\n '__alphag': 0.2,\n '__alphaz': 0.5,\n '__z_piv': 0.4}\n sys = LinearBiasSystematic(\n alphag='__alphag',\n alphaz='__alphaz',\n z_piv='__z_piv')\n\n sys.apply(cosmo, params, src)\n bias = 30.0 * gf**0.2 * ((1.0 + src.z_) / (1.0 + 0.4)) ** 0.5\n assert np.allclose(src.bias_, bias)\n","sub_path":"firecrown/ccl/systematics/tests/test_lss.py","file_name":"test_lss.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"224976549","text":"from PIL import Image, ImageFilter, ImageDraw, ImageFont\n\n#load the image\nim = Image.open('IMG_1.jpg')\nim_to_draw = im.copy()\ndraw = ImageDraw.Draw(im_to_draw)\nfont = ImageFont.truetype('arial.ttf',40)\n\ntext = '1234'\nposition_x,position_y = (20,20)\ncolor = (255,0,0)\ndraw.text((position_x,position_y),text,color,font=font)\nim_to_draw.save('im_draw_font.jpg')\nim_to_draw.show()\n","sub_path":"fanli/578/578.py","file_name":"578.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"55281005","text":"#\n# @lc app=leetcode id=1262 lang=python\n#\n# [1262] Greatest Sum Divisible by Three\n#\n\n# @lc code=start\n\nclass Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n curSum = 0\n minRemainderTwo = 10001\n minRemainderOne = 10001\n for num in nums:\n curSum += num\n if num % 3 == 2:\n minRemainderOne = min(minRemainderOne, minRemainderTwo + num)\n minRemainderTwo = min(minRemainderTwo, num)\n if num % 3 == 1:\n minRemainderTwo = min(minRemainderTwo, minRemainderOne + num)\n minRemainderOne = min(minRemainderOne, num)\n if curSum % 3 == 0:\n return curSum\n if curSum % 3 == 1 and minRemainderOne != 10001:\n return curSum - minRemainderOne\n if curSum % 3 == 2 and minRemainderTwo != 10001:\n return curSum - minRemainderTwo\n return 0\n# @lc code=end\n","sub_path":"Leetcode/1262.greatest-sum-divisible-by-three.py","file_name":"1262.greatest-sum-divisible-by-three.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"285836217","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport os\n\nx = []\ny = []\n\ndir = os.path.dirname(__file__)\ncsv_filepath = os.path.join(dir, '../csv/gfi_label_distribution_lowercase.csv')\n\nwith open(csv_filepath, 'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n next(plots)\n for row in plots:\n x.append(row[0])\n y.append(int(row[1]))\n\ncsfont = {'fontname':'Times New Roman'}\nindexes = np.arange(len(x))\nplt.bar(indexes, y)\nplt.xticks(indexes, x, rotation=45, ha=\"right\", **csfont)\nplt.ylabel('Issues', **csfont)\nplt.tight_layout()\nplt.show()","sub_path":"py/gfi_label_distribution_lowercase.py","file_name":"gfi_label_distribution_lowercase.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"429062032","text":"import yaml\n\nfrom server.fragment.data import (CodeFragment,\n CodeParam)\nfrom server.fragment.loader import CodeFragmentLoader\n\n\nclass YamlLoader(CodeFragmentLoader):\n \"\"\"\n The yaml loader implements the code fragment loader interface for files in the yaml format.\n\n It can load fragments from the single yaml resource file and creates the code parameters\n and code fragments that are specified in that file.\n\n Attributes:\n __instance (YamlLoader): The classes single instance.\n _fragments (list): The loaded fragments.\n _loader_files (list): The filenames to load from.\n \"\"\"\n\n __instance = None\n\n _fragments = []\n _loader_files = [] # of str\n\n @staticmethod\n def get_instance() -> 'YamlLoader':\n \"\"\"\n Static method to access the single instance.\n\n Construct the instance if not already done.\n \"\"\"\n if YamlLoader.__instance is None:\n YamlLoader()\n return YamlLoader.__instance\n\n def __init__(self) -> None:\n \"\"\"\n The YamlLoader class is a singleton. Use get_instance() to access the instance.\n\n Raises an exception if the class already got instantiated. Load the default fragments\n and return self as the instance.\n \"\"\"\n if YamlLoader.__instance is not None:\n raise Exception(\"Class %r is a singleton\" % self.__class__.__name__)\n\n self.load_default()\n YamlLoader.__instance = self\n\n # Override\n def load_default(self) -> None:\n \"\"\"Loads the default code fragments.\"\"\"\n # TODO: Find yaml resources generically\n # TODO: Support multiple resouce files\n filename = \"./server/fragment/resources/fragments-pandas.yml\"\n self.clear_code_fragments()\n self.load_from(filename)\n\n # Override\n def load_from(self, path: str) -> None:\n \"\"\"Loads code fragments from a specific file.\"\"\"\n with open(path, 'r') as f:\n parsed = yaml.safe_load_all(f)\n\n global_params = {}\n for doc in parsed:\n if doc is None:\n continue\n\n keys = doc.keys()\n rec_type = doc[\"recType\"]\n\n # Missing mandatory fields raise a KeyError\n if rec_type == \"params\":\n code_param = CodeParam(\n rec_id=doc[\"recID\"],\n group=doc[\"group\"] if \"group\" in keys else None,\n name=doc[\"name\"],\n type_=doc[\"type\"],\n vars_=doc[\"vars\"] if \"vars\" in keys else None,\n expr=doc[\"expr\"] if \"expr\" in keys else None\n )\n global_params[code_param._name] = code_param\n elif rec_type == \"code\":\n code = doc[\"code\"]\n params_list = self.parse_variables(code)\n default_params = self.cast_to_params(doc[\"parameter\"] if \"parameter\" in keys else [])\n\n code_fragment = CodeFragment(\n rec_id=doc[\"recID\"],\n group=doc[\"group\"] if \"group\" in keys else None,\n parent=doc[\"parent\"] if \"parent\" in keys else None,\n related=doc[\"related\"] if \"related\" in keys else None,\n textkeys=doc[\"textkey\"] if \"textkey\" in keys else [],\n keywords=doc[\"keywords\"] if \"keywords\" in keys else [],\n sources=doc[\"sources\"] if \"sources\" in keys else None,\n documentation=doc[\"documentation\"] if \"documentation\" in keys else None,\n code=code,\n params_list=params_list,\n default_params=self.filter_params(params_list, default_params, global_params)\n )\n\n self._fragments.append(code_fragment)\n else:\n # TODO: Error system\n print(\"Unknown recType %r\" % rec_type)\n f.close()\n\n def parse_variables(self, code: str) -> list: # of strings\n \"\"\"Extract the paramter names from a code fragment.\"\"\"\n params_list = []\n left = code.find(\"$\")\n while left != -1:\n right = code.find(\"$\", left + 1)\n params_list.append(code[left + 1:right])\n left = code.find(\"$\", right + 1)\n return params_list\n\n def filter_params(self, variables: list, default_params: dict, global_params: dict) -> dict:\n \"\"\"Filter for parameters that are contained in the default and gloabal params.\"\"\"\n params = dict()\n for var in variables:\n if var in global_params.keys():\n params[var] = global_params[var]\n if var in default_params.keys():\n params[var] = default_params[var]\n return params\n\n def cast_to_params(self, parameter: list) -> dict:\n \"\"\"Create a parameter from the parsed yaml format.\"\"\"\n params = {}\n\n for param in parameter:\n if \"name\" not in param.keys():\n continue\n\n name = param[\"name\"]\n params[name] = CodeParam(\n name=name,\n vars_=param[\"vars\"] if \"vars\" in param.keys() else None,\n expr=param[\"expr\"] if \"expr\" in param.keys() else None\n )\n\n return params\n\n # Override\n def clear_code_fragments(self) -> None:\n \"\"\"Clear the list of code fragments.\"\"\"\n self._fragments.clear()\n\n # Override\n def get_code_fragments(self) -> list:\n \"\"\"Return the list of code fragments.\"\"\"\n return self._fragments\n\n # Override\n def get_code_fragments_with_id(self) -> dict:\n \"\"\"Return the list of code fragments with their id.\"\"\"\n fragment_map = dict()\n for fragment in self._fragments:\n fragment_map[fragment._rec_id] = fragment\n return fragment_map\n","sub_path":"server/fragment/loader/YamlLoader.py","file_name":"YamlLoader.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"321244230","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 ('productos', '0004_auto_20150917_0229'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='discount',\n name='products',\n ),\n migrations.AddField(\n model_name='discount',\n name='product',\n field=models.ForeignKey(related_name='discount', blank=True, to='productos.Product', null=True),\n ),\n ]\n","sub_path":"productos/migrations/0005_auto_20150922_2326.py","file_name":"0005_auto_20150922_2326.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"639401176","text":"import pyspeckit\nimport os\nfrom pyspeckit.spectrum.models import nh2d\nimport numpy as np\n\nimport astropy.units as u\n\nif not os.path.exists('o-nh2d_spec.fits'):\n import astropy.utils.data as aud\n from astropy.io import fits\n f = aud.download_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/o-nh2d_spec.fits')\n with fits.open(f) as ff:\n ff.writeto('o-nh2d_spec.fits')\n\n# Load the spectrum \nspec = pyspeckit.Spectrum('o-nh2d_spec.fits')\n# Determine rms from line free section and load into cube\nrms = np.std(spec.data[10:370])\nspec.error[:] = rms\n# setup spectral axis\nspec.xarr.refX = 85.92627*u.GHz\nspec.xarr.velocity_convention = 'radio'\nspec.xarr.convert_to_unit('km/s')\n# define useful shortcuts for True and False\nF=False\nT=True\n# Setup of matplotlib\nimport matplotlib.pyplot as plt\nplt.ion()\n# Add NH2D fitter\nspec.Registry.add_fitter('nh2d_vtau', pyspeckit.models.nh2d.nh2d_vtau_fitter,4)\n# run spectral fit using some reasonable guesses\nspec.specfit(fittype='nh2d_vtau', guesses=[6.51, 4.4, 0.214, 0.1088], \n verbose_level=4, signal_cut=1.5, limitedmax=[F,T,T,T], limitedmin=[T,T,T,T], \n minpars=[0, 0, -1, 0.05], maxpars=[30.,50.,1,0.5], fixed=[F,F,F,F])\n# plot best fit\nspec.plotter(errstyle='fill')\nspec.specfit.plot_fit()\n#save figure\nplt.savefig('example_o-NH2D.png')\n","sub_path":"examples/example_oNH2D.py","file_name":"example_oNH2D.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"472132761","text":"\n\nfrom xai.brain.wordbase.nouns._beater import _BEATER\n\n#calss header\nclass _BEATERS(_BEATER, ):\n\tdef __init__(self,): \n\t\t_BEATER.__init__(self)\n\t\tself.name = \"BEATERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"beater\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_beaters.py","file_name":"_beaters.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"238629409","text":"\nfrom typing import Any, Dict, Optional, Type, List\n\nimport time\nimport habitat\nimport roslibpy\nfrom argparse import Namespace\nfrom roslibpy import Message, Ros, Topic\nfrom gym import Space, spaces\n\nfrom habitat_baselines.config.default import get_config\nimport numpy as np\nimport base64\nimport cv2\nfrom habitat import Config, Env\nfrom habitat.core.dataset import Dataset, Episode\n\nfrom habitat_baselines.common.baseline_registry import baseline_registry\nimport math\n\n\ndef quaternion_to_euler(x, y, z, w):\n t0 = +2.0 * (w * x + y * z)\n t1 = +1.0 - 2.0 * (x * x + y * y)\n roll = math.atan2(t0, t1)\n t2 = +2.0 * (w * y - z * x)\n t2 = +1.0 if t2 > +1.0 else t2\n t2 = -1.0 if t2 < -1.0 else t2\n pitch = math.asin(t2)\n t3 = +2.0 * (w * z + x * y)\n t4 = +1.0 - 2.0 * (y * y + z * z)\n yaw = math.atan2(t3, t4)\n return [yaw, pitch, roll]\n\n\ndef _get_movement_ros_message(fw_step, r_step):\n frame_id = 'base_footprint'\n m = Message({\n 'header': {\n 'frame_id': frame_id\n },\n 'pose': {\n 'position': {\n 'x': fw_step,\n 'y': 0,\n 'z': 0\n },\n 'orientation': {\n 'x': 0,\n 'y': 0,\n 'z': r_step,\n 'w': 1\n }\n }\n })\n return m\n\nclass PepperRecord:\n def __init__(self):\n # Initialize ROS Bridge\n config = get_config()\n self._pepper_config = config.PEPPER\n self._ros = roslibpy.Ros(host='localhost', port=9090)\n self._ros.run()\n assert self._ros.is_connected, \"ROS not connected\"\n\n sim_config = config.TASK_CONFIG.SIMULATOR\n\n self._image_width = sim_config.RGB_SENSOR.WIDTH\n self._image_height = sim_config.RGB_SENSOR.HEIGHT\n self._norm_depth = sim_config.DEPTH_SENSOR.NORMALIZE_DEPTH\n\n self.goal_sensor_uuid = config.TASK_CONFIG.TASK.GOAL_SENSOR_UUID\n print(self.goal_sensor_uuid)\n self._goal_sensor_dim = config.TASK_CONFIG.TASK.\\\n POINTGOAL_WITH_GPS_COMPASS_SENSOR.DIMENSIONALITY\n\n self._buffer_size = self._pepper_config.BufferSize\n self._forward_step = self._pepper_config.ForwardStep\n self._turn_step = self._pepper_config.TurnStep\n\n self._depth_buffer = []\n self._rgb_buffer = []\n\n # Subscribe to RGB and Depth topics\n # RGBTopic: '/pepper_robot/naoqi_driver/camera/front/image_raw'\n # DepthTopic: '/pepper_robot/naoqi_driver/camera/depth/image_raw'\n # MoveTopic: '/move_base_simple/goal'\n self._listener_rgb = Topic(self._ros,\n self._pepper_config.RGBTopic,\n 'sensor_msgs/Image')\n self._listener_depth = Topic(self._ros,\n self._pepper_config.DepthTopic,\n 'sensor_msgs/Image')\n\n self._listener_rgb.subscribe(lambda message:\n self._fetch_rgb(message))\n self._listener_depth.subscribe(lambda message:\n self._fetch_depth(message))\n\n self._fresh_rgb = False\n self._fresh_depth = False\n\n self.image_pairs = []\n self.last_rgb = time.time()\n self.last_depth = time.time()\n\n def close(self) -> None:\n self._ros.close()\n\n def rgb_message_to_cv(self, message):\n img = np.frombuffer(base64.b64decode(message['data']), np.uint8)\n img = img.reshape((message['height'], message['width'], 3))\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img = cv2.resize(img, (self._image_width, self._image_height))\n return img\n\n def depth_message_to_cv(self, message):\n img = np.frombuffer(base64.b64decode(message['data']), np.uint16)\n img = img.reshape((message['height'], message['width'], 1))\n img = (img.astype(np.float) / 9100).astype(np.float)\n img = img.clip(0.0, 1.0)\n img = cv2.resize(img, (self._image_width, self._image_height))\n img = img.reshape((self._image_height, self._image_width, 1))\n return img\n\n def _fetch_rgb(self, message):\n self._rgb_buffer.append(message)\n print(\"RGB:\", time.time() - self.last_rgb)\n self.last_rgb = time.time()\n\n def _fetch_depth(self, msg):\n self._depth_buffer.append(msg)\n print(\"DEPTH:\", time.time() - self.last_depth)\n self.last_depth = time.time()\n\n if len(self._depth_buffer) > 1:\n message = self._depth_buffer[-2]\n\n t_stamp_depth = message['header']['stamp']['secs']\n rgb_in_same_second = [rgb for rgb in self._rgb_buffer\n if (rgb['header']['stamp']['secs'] -\n t_stamp_depth) == 0]\n\n if len(rgb_in_same_second) > 0:\n diff_in_nsecs = abs(message['header']['stamp']['nsecs'] -\n rgb_in_same_second[-1]['header']['stamp']['nsecs'])\n\n if diff_in_nsecs > 200000000:\n return\n\n depth_img = self.depth_message_to_cv(message)\n rgb_img = self.rgb_message_to_cv(rgb_in_same_second[0])\n\n self.image_pairs.append({'rgb': rgb_img, 'depth': depth_img})\n print(len(self.image_pairs))\n\n\npepper = PepperRecord()\nwhile len(pepper.image_pairs) < 10:\n pass\n\nfor pair in pepper.image_pairs:\n cv2.imshow(\"RGB\", pair['rgb'])\n cv2.imshow(\"Depth\", pair['depth'])\n cv2.waitKey(0)\n\n\n\n\n","sub_path":"aimas/pepper_record.py","file_name":"pepper_record.py","file_ext":"py","file_size_in_byte":5549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"145232340","text":"from django.test import TestCase, Client\nfrom django.urls import resolve\nfrom .views import index\nfrom .models import Diary\nfrom django.utils import timezone\n\nimport os\nimport environ\n\n# Create your tests here.\nclient_main = Client()\nroot = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /)\nenv = environ.Env(DEBUG=(bool, False),)\nenviron.Env.read_env('.env')\n\ndef setUpModule():\n\tprint(\"\\nTesting Lab 3\")\n\tclient_main.post('/custom_auth/login/', {\"username\": env(\"SSO_USERNAME\"), \"password\": env(\"SSO_PASSWORD\")})\n\n# Create your tests here.\nclass Lab3Test(TestCase):\n\tdef test_lab_3_url_is_exist(self):\n\t\tresponse = client_main.get('/lab-3/')\n\t\tself.assertEqual(response.status_code,200)\n\n\tdef test_lab_3_using_to_do_list_template(self):\n\t\tresponse = client_main.get('/lab-3/')\n\t\tself.assertTemplateUsed(response, 'to_do_list.html')\n\n\tdef test_lab_3_using_index_func(self):\n\t\tfound = resolve('/lab-3/')\n\t\tself.assertEqual(found.func, index)\n\n\tdef test_model_can_create_new_activity(self):\n\t\t#Creating a new activity\n\t\tnew_activity = Diary.objects.create(date=timezone.now(),activity='Aku mau latihan ngoding deh')\n\t\t#Retrieving all available activity\n\t\tcounting_all_available_activity = Diary.objects.all().count()\n\t\tself.assertEqual(counting_all_available_activity,1)\n\n\tdef test_can_save_a_POST_request(self):\n\t\tresponse = client_main.post('/lab-3/add_activity/', data={'date': '2017-10-12T14:14', 'activity' : 'Maen Dota Kayaknya Enak'})\n\t\tcounting_all_available_activity = Diary.objects.all().count()\n\t\tself.assertEqual(counting_all_available_activity, 1)\n\t\tself.assertEqual(response.status_code, 302)\n\t\tself.assertEqual(response['location'], '/lab-3/')\n\t\tnew_response = client_main.get('/lab-3/')\n\t\thtml_response = new_response.content.decode('utf8')\n\t\tself.assertIn('Maen Dota Kayaknya Enak', html_response)\n\n\tdef test_can_handle_date_time_errors(self):\n\t\tresponse = client_main.post('/lab-3/add_activity/', data={'date': '99999-10-12T14:14', 'activity' : 'Maen Dota Kayaknya Enak'})\n\t\tcounting_all_available_activity = Diary.objects.all().count()\n\t\tself.assertEqual(counting_all_available_activity, 0)\n\t\tself.assertEqual(response.status_code, 302)\n\t\tself.assertEqual(response['location'], '/lab-3/')\n\t\tnew_response = client_main.get('/lab-3/')\n\t\thtml_response = new_response.content.decode('utf8')\n\t\tself.assertIn('ERROR: Date should be from 0001-01-01T00:00 to 9999-31-12T23:59.', html_response)\n\n\tdef test_can_handle_empty_activity(self):\n\t\tresponse = client_main.post('/lab-3/add_activity/', data={'date': '2017-10-12T14:14', 'activity' : ''})\n\t\tcounting_all_available_activity = Diary.objects.all().count()\n\t\tself.assertEqual(counting_all_available_activity, 0)\n\t\tself.assertEqual(response.status_code, 302)\n\t\tself.assertEqual(response['location'], '/lab-3/')\n\t\tnew_response = client_main.get('/lab-3/')\n\t\thtml_response = new_response.content.decode('utf8')\n\t\tself.assertIn('ERROR: Activity should not be empty.', html_response)\n\n\tdef test_can_handle_whitespace_only_activity(self):\n\t\tresponse = client_main.post('/lab-3/add_activity/', data={'date': '2017-10-12T14:14', 'activity' : '\\t'})\n\t\tcounting_all_available_activity = Diary.objects.all().count()\n\t\tself.assertEqual(counting_all_available_activity, 0)\n\t\tself.assertEqual(response.status_code, 302)\n\t\tself.assertEqual(response['location'], '/lab-3/')\n\t\tnew_response = client_main.get('/lab-3/')\n\t\thtml_response = new_response.content.decode('utf8')\n\t\tself.assertIn('ERROR: Activity should not be empty.', html_response)","sub_path":"lab_3/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"527420261","text":"from pipeline_stage_functions import *\nimport memory_file, register_file\n\n# The Buffers to hold on to values in between pipeline stages\n# {'fetch_decode' : None, 'decode_execute' : None, 'execute_memory' : None, 'memory_writeback' : None}\n\nbuffers, pcs_in_order = {}, []\nnum_instructions, num_data_transfer, num_alu, num_control = 0, 0, 0, 0\nnum_stalls, num_data_hazards, num_control_hazards, num_branch_mispredictions = 0, 0, 0, 0\nnum_stalls_data, num_stalls_control = 0, 0\nfetch = True\nlst_hazard = \"\"\ninst_cache_stats, data_cache_stats = [], []\n\n# Function to enable data forwarding\n# Modes can either be 'M_M', 'M_E', 'E_E', 'M_D', 'E_D'\n# from_ins & to_ins range from 0 to 4 (both included) (with from_ins < to_ins)\ndef data_forward(mode, from_ins, to_ins, to_reg) :\n\n\tif mode == 'M_E' :\n\t\tbuffers[pcs_in_order[to_ins]]['decode_execute'][to_reg] = buffers[pcs_in_order[from_ins]]['memory_writeback']['value']\n\telif mode == 'E_E' :\n\t\tbuffers[pcs_in_order[to_ins]]['decode_execute'][to_reg] = buffers[pcs_in_order[from_ins]]['execute_memory']['value']\n\n\n# return type is (hazard_present, in_instruction_no, forwarding_from_instr_1, forwarding_from_instr_2, the value to be forwarded)\ndef check_data_hazard(PC):\n\t# global buffers\n\tif pcs_in_order[0] == PC:\n\t\treturn False, -1, -1, -1, -1\n\telif pcs_in_order[1] == PC:\n\t\tif buffers[pcs_in_order[1]]['decode_execute']['rs1'] != '00000' and buffers[pcs_in_order[1]]['decode_execute']['rs1'] and buffers[pcs_in_order[0]]['decode_execute']['rd'] == buffers[pcs_in_order[1]]['decode_execute']['rs1']:\n\t\t\treturn True, 1, 0, -1, 'rs1'\n\t\telif buffers[pcs_in_order[1]]['decode_execute']['rs2'] != '00000' and buffers[pcs_in_order[1]]['decode_execute']['rs2'] and buffers[pcs_in_order[0]]['decode_execute']['rd'] == buffers[pcs_in_order[1]]['decode_execute']['rs2']:\n\t\t\treturn True, 1, 0, -1, 'rs2'\n\telse:\n\t\ti = 0\n\t\tfor i in range(1, len(pcs_in_order)):\n\t\t\tif pcs_in_order[i] == PC:\n\t\t\t\tbreak\n\t\tif buffers[pcs_in_order[i]]['decode_execute']['rs1'] == None and buffers[pcs_in_order[i]]['decode_execute']['rs2'] == None:\n\t\t\treturn False, -1, -1, -1, -1\n\t\telif buffers[pcs_in_order[i]]['decode_execute']['rs1'] == '00000' and buffers[pcs_in_order[i]]['decode_execute']['rs2'] == '00000':\n\t\t\treturn False, -1, -1, -1, -1\n\t\telif buffers[pcs_in_order[i - 1]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs1'] and buffers[pcs_in_order[i - 2]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs2']:\n\t\t\treturn True, i, i - 1, i - 2, 'rs1rs2'\n\t\telif buffers[pcs_in_order[i - 2]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs1'] and buffers[pcs_in_order[i - 1]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs2']:\n\t\t\treturn True, i, i - 1, i - 2, 'rs2rs1'\n\t\telif buffers[pcs_in_order[i]]['decode_execute']['rs1'] != '00000' and buffers[pcs_in_order[i]]['decode_execute']['rs1'] and buffers[pcs_in_order[i-1]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs1']:\n\t\t\treturn True, i, i-1, -1, 'rs1'\n\t\telif buffers[pcs_in_order[i]]['decode_execute']['rs2'] != '00000' and buffers[pcs_in_order[i]]['decode_execute']['rs2'] and buffers[pcs_in_order[i-1]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs2']:\n\t\t\treturn True, i, i-1, -1, 'rs2'\n\t\telif buffers[pcs_in_order[i]]['decode_execute']['rs1'] != '00000' and buffers[pcs_in_order[i]]['decode_execute']['rs1'] and buffers[pcs_in_order[i-2]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs1']:\n\t\t\treturn True, i, i-2, -1, 'rs1'\n\t\telif buffers[pcs_in_order[i]]['decode_execute']['rs2'] != '00000' and buffers[pcs_in_order[i]]['decode_execute']['rs2'] and buffers[pcs_in_order[i-2]]['decode_execute']['rd'] == buffers[pcs_in_order[i]]['decode_execute']['rs2']:\n\t\t\treturn True, i, i-2, -1, 'rs2'\n\treturn False, -1, -1, -1, -1\n\n\ndef input_for_execute(PC, control_signals):\n\tif control_signals['mux_alu'] == 'register_&_register' and control_signals['is_control_instruction'] == False:\n\t\treturn (PC, buffers[PC]['decode_execute']['rs1_val'], buffers[PC]['decode_execute']['rs2_val'], None, 32, 32, control_signals['alu_op'], control_signals)\n\t\n\telif control_signals['mux_alu'] == 'register_&_immediate' and control_signals['is_control_instruction'] == False:\n\t\treturn (PC, buffers[PC]['decode_execute']['rs1_val'], buffers[PC]['decode_execute']['imm'],None, 32, 12, control_signals['alu_op'], control_signals)\n\n\telif control_signals['mux_alu'] == 'register_&_register_&_immediate':\n\t\treturn (PC, buffers[PC]['decode_execute']['rs1_val'], buffers[PC]['decode_execute']['imm'],None, 32, 12, control_signals['alu_op'], control_signals)\n\t\t\n\telif control_signals['mux_alu'] == 'pc_&_imm':\n\t\treturn (PC, PC, buffers[PC]['decode_execute']['imm'],None, 32, 32, control_signals['alu_op'], control_signals)\n\t\t\n\telif control_signals['mux_alu'] == 'only_imm':\n\t\treturn (PC, buffers[PC]['decode_execute']['imm'], hex(12), None, 20, 12, control_signals['alu_op'], control_signals)\n\n\telif control_signals['is_control_instruction'] == True:\n\t\tif control_signals['mux_writeback'] == 'PC':\n\t\t\treturn (PC, PC, buffers[PC]['decode_execute']['imm'], None, 32, 20, control_signals['alu_op'], control_signals)\n\t\telse:\n\t\t\treturn (PC, buffers[PC]['decode_execute']['rs1_val'], buffers[PC]['decode_execute']['rs2_val'], buffers[PC]['decode_execute']['imm'], 32, 12, control_signals['alu_op'], control_signals)\n\n\n\ndef input_for_memory(PC, control_signals):\n\tif control_signals['mux_memory'] == 'MAR_&_MDR':\n\t\treturn (PC, buffers[PC]['execute_memory']['value'], buffers[PC]['decode_execute']['rs2_val'], control_signals['memory_size'], control_signals)\n\n\telif control_signals['mux_memory'] == 'MAR':\n\t\treturn (PC, buffers[PC]['execute_memory']['value'], None, control_signals['memory_size'], control_signals)\n\n\treturn (PC, None, None, None, control_signals)\n\n# info_per_stage is in format\n# [('f' , (pc, prev_branch, branch_inst))\n# ('d' , instruction, pc)\n# ('e' , (pc, value1, value2, total_bits1, total_bits2, op, control_signals))\n# ('m' , (pc, MAR, MDR, num_bytes, control_signals))\n# ('w' , (pc, register_num, value, control_signals))\n# All these will be stored in a list (of size 5), with each index representing an instruction & each new list representing a new cycle\n\ndef execute_pipeline(info_per_stage, forwarding=True, req_PC = None) :\n\n\tglobal buffers\n\tglobal pcs_in_order\n\tglobal num_instructions\n\tglobal num_data_transfer\n\tglobal num_alu\n\tglobal num_control\n\tglobal num_stalls_data\n\tglobal num_stalls_control\n\tglobal num_stalls\n\tglobal num_data_hazards\n\tglobal num_control_hazards\n\tglobal num_branch_mispredictions\n\tglobal fetch\n\tglobal lst_hazard\n\tinfo_nxt_stage = []\n\tstall = False\n\tflush = False\n\n\tinst_details = {}\n\tcycle_details = {}\n\n\t_PC, branch_inst, dest_PC = None, False, None\n\n\tfor i in range(len(info_per_stage)):\n\t\t\n\t\tif info_per_stage[i][0] == 'f':\n\t\t\t# print(\"NEW FETCH\")\n\t\t\t_PC, IR, branch_inst, dest_PC = pipeline_fetch(info_per_stage[i][1])\n\t\t\tif memory_file.read_data_from_memory(_PC, 4, 'instruction_cache') == '0x00000000':\n\t\t\t\tfetch = False\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tpcs_in_order.append(_PC)\n\t\t\t# print(\"PC and IR\", _PC, IR, \"\\n\")\n\t\t\tbuffers[_PC] = {'fetch_decode' : IR, 'decode_execute' : None, 'execute_memory' : None, 'memory_writeback' : None}\n\t\t\tif _PC == req_PC:\n\t\t\t\tinst_details[_PC+\"_fetch_decode\"] = buffers[_PC]['fetch_decode']\n\t\t\tcycle_details[_PC+\"_fetch_decode\"] = buffers[_PC]['fetch_decode']\n\t\t\tinfo_nxt_stage.append(('d', (IR, _PC)))\n\n\n\n\t\telif info_per_stage[i][0] == 'd' :\n\t\t\tPC, control_signals, instruction_dict = pipeline_decode(info_per_stage[i][1])\n\n\t\t\trs1_val, rs2_val = None, None\n\t\t\tif instruction_dict['rs1']:\n\t\t\t\trs1_val = register_file.get_register_val(\"x\" + str(int(instruction_dict['rs1'], 2)))\n\t\t\tif instruction_dict['rs2']:\n\t\t\t\trs2_val = register_file.get_register_val(\"x\" + str(int(instruction_dict['rs2'], 2)))\n\t\t\tbuffers[PC]['decode_execute'] = {'rs1': instruction_dict['rs1'], 'rs2': instruction_dict['rs2'],\n\t\t\t\t\t\t\t\t\t\t\t 'rd': instruction_dict['rd'], 'rs1_val': rs1_val, 'rs2_val': rs2_val,\n\t\t\t\t\t\t\t\t\t\t\t 'imm': instruction_dict['imm'], 'type': control_signals['mux_memory']}\n\n\t\t\tif PC == req_PC:\n\t\t\t\tinst_details[PC+\"_decode_execute\"] = {'opc_code': instruction_dict['opc_code'],'funct3': instruction_dict['funct3'],'funct7': instruction_dict['funct7'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'rs1': instruction_dict['rs1'], 'rs2': instruction_dict['rs2'], 'rd': instruction_dict['rd'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'imm': instruction_dict['imm']}\n\t\t\tcycle_details[PC+\"_decode_execute\"] = {'opc_code': instruction_dict['opc_code'],'funct3': instruction_dict['funct3'],'funct7': instruction_dict['funct7'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'rs1': instruction_dict['rs1'], 'rs2': instruction_dict['rs2'], 'rd': instruction_dict['rd'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'imm': instruction_dict['imm'] }\n\n\t\t\tch, to_inst, from_inst1, from_inst2, to_reg = check_data_hazard(PC)\n\t\t\tif ch and control_signals['is_control_instruction'] and lst_hazard != pcs_in_order[from_inst1] + pcs_in_order[to_inst]:\n\t\t\t\tlst_hazard = pcs_in_order[from_inst1] + pcs_in_order[to_inst]\n\t\t\t\tnum_control_hazards+=1\n\t\t\telif ch and lst_hazard != pcs_in_order[from_inst1] + pcs_in_order[to_inst]:\n\t\t\t\tlst_hazard = pcs_in_order[from_inst1] + pcs_in_order[to_inst]\n\t\t\t\tnum_data_hazards+=1\n\n\t\t\t# print(\"Debug: \", PC, to_inst, from_inst1, from_inst2, to_reg)\n\t\t\tif ch == False:\n\t\t\t\t\t# print(\"YES\")\n\t\t\t\t\tif control_signals['is_control_instruction']:\n\t\t\t\t\t\tnew_pc = handle_branches(PC, control_signals, instruction_dict, [rs1_val, rs2_val])\n\t\t\t\t\t\t# print(\"NEW_PC : \", new_pc)\n\t\t\t\t\t\tlst_pc = info_per_stage[i + 1][1][0]\n\t\t\t\t\t\tif not check_in_bat(PC):\n\t\t\t\t\t\t\tlst_pc = alu(PC, '0x00000004', 32, 32, 'addition')\n\t\t\t\t\t\tif lst_pc != new_pc:\n\t\t\t\t\t\t\tflush = True\n\t\t\t\t\t\t\tinfo_nxt_stage.append(('e', input_for_execute(PC, control_signals)))\n\t\t\t\t\t\t\tif fetch:\n\t\t\t\t\t\t\t\tinfo_nxt_stage.append(('f', (new_pc, True)))\n\t\t\t\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\tif forwarding:\n\t\t\t\t\tif from_inst1 != -1:\n\t\t\t\t\t\tif buffers[pcs_in_order[from_inst1]]['decode_execute']['type'] == 'MAR' and buffers[pcs_in_order[from_inst1]]['memory_writeback']:\n\t\t\t\t\t\t\tdata_forward('M_E', from_inst1, to_inst, to_reg[:3]+'_val')\n\t\t\t\t\t\telif buffers[pcs_in_order[from_inst1]]['decode_execute']['type'] != 'MAR' and buffers[pcs_in_order[from_inst1]]['execute_memory']:\n\t\t\t\t\t\t\tdata_forward('E_E', from_inst1, to_inst, to_reg[:3]+'_val')\n\t\t\t\t\t\t\t# print(\"BOOM\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif not control_signals['is_control_instruction']:\n\t\t\t\t\t\t\t\tnum_stalls_data+=1\n\t\t\t\t\t\t\tstall = True\n\n\t\t\t\t\t\tif len(to_reg) > 3:\n\t\t\t\t\t\t\tto_reg = to_reg[3:]\n\n\n\t\t\t\t\tif from_inst2 != -1 and not stall:\n\t\t\t\t\t\tif buffers[pcs_in_order[from_inst2]]['decode_execute']['type'] == 'MAR' and buffers[pcs_in_order[from_inst2]]['memory_writeback']:\n\t\t\t\t\t\t\tdata_forward('M_E', from_inst2, to_inst, to_reg[:3]+'_val')\n\t\t\t\t\t\telif buffers[pcs_in_order[from_inst2]]['decode_execute']['type'] != 'MAR' and buffers[pcs_in_order[from_inst2]]['execute_memory']:\n\t\t\t\t\t\t\tdata_forward('E_E', from_inst2, to_inst, to_reg[:3]+'_val')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tif not control_signals['is_control_instruction']:\n\t\t\t\t\t\t\t\tnum_stalls_data+=1\n\t\t\t\t\t\t\tstall = True\n\n\t\t\t\t\t\n\t\t\t\t\tif control_signals['is_control_instruction'] and not stall:\n\t\t\t\t\t\tnew_pc = handle_branches(PC, control_signals, instruction_dict, [buffers[PC]['decode_execute']['rs1_val'], buffers[PC]['decode_execute']['rs2_val']])\n\t\t\t\t\t\tlst_pc = info_per_stage[i + 1][1][0]\n\t\t\t\t\t\tif not check_in_bat(PC):\n\t\t\t\t\t\t\tlst_pc = alu(PC, '0x00000004', 32, 32, 'addition')\n\t\t\t\t\t\t# print(\"NEW_PC : \", new_pc)\n\t\t\t\t\t\tif lst_pc != new_pc:\n\t\t\t\t\t\t\tflush = True\n\t\t\t\t\t\t\tinfo_nxt_stage.append(('e', input_for_execute(PC, control_signals)))\n\t\t\t\t\t\t\tif fetch:\n\t\t\t\t\t\t\t\tinfo_nxt_stage.append(('f', (new_pc, True)))\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\telse:\n\t\t\t\t\tif not control_signals['is_control_instruction']:\n\t\t\t\t\t\tnum_stalls_data += 1\n\t\t\t\t\tstall = True\n\n\t\t\tif stall:\n\t\t\t\tinfo_nxt_stage.append(('d', info_per_stage[i][1]))\n\t\t\t\tif fetch:\n\t\t\t\t\tif branch_inst and dest_PC:\n\t\t\t\t\t\tinfo_nxt_stage.append(('f', (dest_PC, branch_inst)))\n\t\t\t\t\telse:\n\t\t\t\t\t\tinfo_nxt_stage.append(('f', (PC, branch_inst)))\n\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\tinfo_nxt_stage.append(('e', input_for_execute(PC, control_signals)))\n\n\n\n\n\t\telif info_per_stage[i][0] == 'e':\n\t\t\tPC, value, control_signals = pipeline_execute(info_per_stage[i][1])\n\t\t\tif control_signals['is_control_instruction'] == True and control_signals['mux_writeback'] == 'PC':\n\t\t\t\tbuffers[PC]['execute_memory'] = {'value': value['nxt_pc']}\n\t\t\telse:\n\t\t\t\tbuffers[PC]['execute_memory'] = {'value': value}\n\n\t\t\t# if not branch_prediction and control_signals['is_control_instruction'] == True:\n\t\t\t# \tif info_per_stage[i+1][1][0] != value['nxt_pc']:\n\t\t\t# \t\t\t\tflush = True\n\t\t\t# \t\t\t\tif pcs_in_order[-1] == info_per_stage[i+1][1][0]:\n\t\t\t# \t\t\t\t\tpcs_in_order = pcs_in_order[:-1]\n\t\t\t# \t\t\t\tinfo_nxt_stage.append(('m', input_for_memory(PC, control_signals)))\n\t\t\t# \t\t\t\tif fetch:\n\t\t\t# \t\t\t\t\tinfo_nxt_stage.append(('f', (value['nxt_pc'], prev_branch, True)))\n\t\t\t# \t\t\t\tbreak\n\t\t\t# else:\n\t\t\tif PC == req_PC:\n\t\t\t\tinst_details[PC+\"_execute_memory\"] = buffers[PC]['execute_memory']\n\t\t\tcycle_details[PC+\"_execute_memory\"] = buffers[PC]['execute_memory']\n\t\t\tinfo_nxt_stage.append(('m', input_for_memory(PC, control_signals)))\n\n\n\n\t\telif info_per_stage[i][0] == 'm':\n\t\t\tPC, value, control_signals = pipeline_memory_access(info_per_stage[i][1])\n\n\t\t\tif value and control_signals['mux_writeback']:\n\t\t\t\tbuffers[PC]['memory_writeback'] = {'value': value}\n\t\t\telif control_signals['mux_writeback'] == None:\n\t\t\t\tbuffers[PC]['memory_writeback'] = {'value': None}\n\t\t\telse:\n\t\t\t\tbuffers[PC]['memory_writeback'] = {'value': buffers[PC]['execute_memory']['value']}\n\n\t\t\trd = None\n\t\t\tif buffers[PC]['decode_execute']['rd']:\n\t\t\t\trd = \"x\" + str(int(buffers[PC]['decode_execute']['rd'], 2))\n\n\t\t\tif PC == req_PC:\n\t\t\t\tinst_details[PC+\"_memory_writeback\"] = buffers[PC]['memory_writeback']\n\t\t\tcycle_details[PC+\"_memory_writeback\"] = buffers[PC]['memory_writeback']\n\t\t\tinfo_nxt_stage.append(('w', (PC, rd, buffers[PC]['memory_writeback']['value'], control_signals)))\n\n\n\n\t\telif info_per_stage[i][0] == 'w':\n\t\t\tPC, control_signals = pipeline_write_back(info_per_stage[i][1])\n\t\t\tnum_instructions+=1\n\t\t\tif control_signals['is_control_instruction']:\n\t\t\t\tnum_control += 1\n\t\t\telif control_signals['mux_writeback'] == 'alu':\n\t\t\t\tnum_alu += 1\n\t\t\telif control_signals['mux_writeback'] == 'MDR' or control_signals['mux_writeback'] == None:\n\t\t\t\tnum_data_transfer += 1\n\n\t\t\tpcs_in_order = pcs_in_order[1:]\n\t\t\t# del buffers[PC]\n\t\t\t\n\tif not stall and not flush and fetch:\n\t\tif branch_inst:\n\t\t\tinfo_nxt_stage.append(('f', (dest_PC, True)))\n\t\telse:\n\t\t\t# print(\"YO\")\n\t\t\tinfo_nxt_stage.append(('f', (_PC, branch_inst)))\n\n\t# print(\"Data Hazards\", len(data_hazard), \"control_hazard\", control_hazard)\n\tif stall:\n\t\tnum_stalls+=1\n\tif flush:\n\t\tnum_branch_mispredictions+=1\n\n\treturn info_nxt_stage, cycle_details, inst_details\n\ndef print_required_values():\n\tglobal pcs_in_order\n\tglobal num_instructions\n\tglobal num_data_transfer\n\tglobal num_alu\n\tglobal num_control\n\tglobal num_stalls_data\n\tglobal num_stalls_control\n\tglobal num_stalls\n\tglobal num_data_hazards\n\tglobal num_control_hazards\n\tglobal num_branch_mispredictions\n\tstats = {}\n\tnum_stalls_control = num_stalls - num_stalls_data\n\t# print(\"num_instructions, num_data_transfer, num_alu, num_control : \", num_instructions, num_data_transfer, num_alu, num_control)\n\t# print(\"num_stalls, num_data_hazards, num_control_hazards, num_branch_mispredictions : \", num_stalls, num_data_hazards, num_control_hazards, num_branch_mispredictions)\n\t# print(\"num_stalls_data, num_stalls_control: \", num_stalls_data, num_stalls_control)\n\n\tstats['num_instructions'] = num_instructions\n\tstats['num_data_transfer'] = num_data_transfer\n\tstats['num_alu'], stats['num_control'] = num_alu, num_control\n\tstats['num_stalls'], stats['num_data_hazards'], stats['num_control_hazards'], stats['num_branch_mispredictions'] = num_stalls, num_data_hazards, num_control_hazards, num_branch_mispredictions\n\tstats['num_stalls_data'],stats['num_stalls_control'] = num_stalls_data, num_stalls_control\n\t\n\treturn stats\n\n","sub_path":"Phase3/pipelined_execution.py","file_name":"pipelined_execution.py","file_ext":"py","file_size_in_byte":16050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"15908091","text":"from __future__ import generator_stop\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom .numpy import bincount_batch, unblock\n\nif TYPE_CHECKING:\n\tfrom fractions import Fraction\n\tfrom typing import Tuple, Union\n\tRational = Union[float, Fraction]\n\ndef grayscale(arr):\n\treturn np.sum(arr, axis=-1) // arr.shape[-1]\n\ndef histogram_1d(arr, levels):\n\t# type: (np.ndarray, int) -> np.ndarray\n\n\t\"\"\" Input shape of `arr`: [batch..., x]. Histogrammed over x and batched over the remaining dimensions.\n\t\tOutput shape: [batch..., levels]\n\t\"\"\"\n\n\treturn bincount_batch(arr, -1, levels)\n\ndef resize_oar(max_width, max_height, dar):\n\t# type: (int, int, Rational) -> Tuple[int, int]\n\n\tmaxdar = max_width / max_height\n\n\tif dar >= maxdar: # wider than it should be\n\t\twidth = max_width\n\t\theight = int(width / dar)\n\telse: # thinner than it should be\n\t\theight = max_height\n\t\twidth = int(height * dar)\n\n\treturn width, height\n\ndef resize_maxsize(max_width, max_height, width, height):\n\t# type: (int, int, int, int) -> Tuple[int, int]\n\n\treturn resize_oar(max_width, max_height, width / height)\n\ndef histogram_2d(arr, levels):\n\t# type: (np.ndarray, int) -> np.ndarray\n\n\t\"\"\" Input shape of `arr`: [batch..., y, x]. Histogrammed over x and y and batched over\n\t\tthe remaining dimensions.\n\t\tOutput shape: [batch..., levels]\n\t\"\"\"\n\n\tif len(arr.shape) < 2:\n\t\traise ValueError(\"arr must be at least 2-dimensional\")\n\n\tnewshape = arr.shape[:-2] + (arr.shape[-2] * arr.shape[-1], )\n\tflattened = np.reshape(arr, newshape)\n\n\treturn bincount_batch(flattened, -1, levels)\n\ndef block_histogram_2d(arr, by, bx, levels):\n\t# type: (np.ndarray, int, int, int) -> np.ndarray\n\n\t\"\"\" Input shape of `arr`: [batch..., y, x]. Histogrammed over blocks of size bx and by\n\t\tand batched over the remaining dimensions.\n\t\tOutput shape: [batch..., y/by, x/bx, levels]\n\t\"\"\"\n\n\tinvx = arr.shape[-1] // bx # dimensions in unblock go from innerst to outerst\n\tinvy = arr.shape[-2] // by\n\tblocks = unblock(arr, invx, invy)\n\tblock_hists = histogram_1d(blocks, levels)\n\treturn block_hists.reshape(arr.shape[:-2] + (invy, invx, -1))\n\ndef image_histogram(arr, levels=256):\n\t# type: (np.ndarray, int) -> np.ndarray\n\n\t\"\"\" Input shape of `arr`: [batch..., x, y, channel]. It is summed over channels to create a grayscale\n\t\timage, then histogrammed over x and y and batched over the remaining dimensions.\n\t\tOutput shape: [batch..., levels]\n\t\"\"\"\n\n\tif len(arr.shape) < 3:\n\t\traise ValueError(\"arr must be at least 3-dimensional\")\n\n\tgray = grayscale(arr)\n\treturn histogram_2d(gray, levels)\n\ndef image_block_histogram(arr, bx, by, levels=256):\n\t# type: (np.ndarray, int, int, int) -> np.ndarray\n\n\t\"\"\" Input shape of `arr`: [batch..., x, y, channels]. It is summed over channels to create a grayscale\n\t\timage, then histogrammed over x and y and batched over the remaining dimensions.\n\t\tOutput shape: [batch..., bx, by, levels]\n\t\"\"\"\n\n\tif len(arr.shape) < 3:\n\t\traise ValueError(\"arr must be at least 3-dimensional\")\n\n\tgray = grayscale(arr)\n\treturn block_histogram_2d(gray, bx, by, levels)\n","sub_path":"genutility/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"258361246","text":"from pathlib import Path\n\nfrom django.test import TestCase\nfrom papermerge.core.models import Folder, KVStoreNode\nfrom papermerge.test.utils import create_root_user\n\n# points to papermerge.testing folder\nBASE_DIR = Path(__file__).parent\n\n\nclass TestFolder(TestCase):\n\n def setUp(self):\n self.user = create_root_user()\n\n def test_delete_parent_deletes_nested_folder_as_well(self):\n \"\"\"\n If folder C is child of folder P, then when\n deleting P - C will be deleted as well\n \"\"\"\n p = Folder.objects.create(\n title=\"P\",\n user=self.user\n )\n\n Folder.objects.create(\n title=\"C\",\n user=self.user,\n parent=p\n )\n\n p = Folder.objects.get(title=\"P\")\n self.assertEqual(p.get_children().count(), 1)\n\n Folder.objects.get(title=\"P\").delete()\n\n with self.assertRaises(Folder.DoesNotExist):\n Folder.objects.get(title=\"C\")\n\n def test_delete_nested_folder_does_not_delete_parent(self):\n \"\"\"\n If folder C is child of folder P, then when\n deleting C - P should not be deleted\n \"\"\"\n p = Folder.objects.create(\n title=\"P\",\n user=self.user\n )\n\n Folder.objects.create(\n title=\"C\",\n user=self.user,\n parent=p\n )\n\n p = Folder.objects.get(title=\"P\")\n self.assertEqual(p.get_children().count(), 1)\n\n Folder.objects.get(title=\"C\").delete()\n\n try:\n Folder.objects.get(title=\"P\")\n except Folder.DoesNotExist:\n self.fail(\n \"Parent folder was deleted when child\"\n \" deletion only was intended\"\n )\n\n def test_basic_kvstore_for_folder(self):\n \"\"\"\n kvstore is per node: i.e. per folder and per document\n f = Folder()\n f.kv = instance of KVNode, which operates on f.kvstore\n f.kvstore = QuerySet of KVStoreNodes stores key values for nodes\n \"\"\"\n p = Folder.objects.create(\n title=\"P\",\n user=self.user\n )\n p.kv.add(key=\"shop\")\n p.kv.add(key=\"price\")\n p.kv.add(key=\"date\")\n\n self.assertEqual(\n 3,\n p.kvstore.count()\n )\n\n p.kv.remove(key=\"shop\")\n\n self.assertEqual(\n 2,\n p.kvstore.count()\n )\n\n def test_folders_kvstore_propagates_to_subfolders(self):\n \"\"\"\n Folder's kvstore propagates to all its descendent folders,\n documents, pages\n \"\"\"\n top = Folder.objects.create(\n title=\"top\",\n user=self.user\n )\n top.save()\n sub = Folder.objects.create(\n title=\"sub\",\n parent=top,\n user=self.user\n )\n sub.save()\n self.assertEqual(\n 0,\n top.kvstore.count()\n )\n self.assertEqual(\n 0,\n sub.kvstore.count()\n )\n top.kv.add(key=\"shop\")\n self.assertEqual(\n 1,\n top.kvstore.count()\n )\n # kvstore propagated from parent folder to descendents\n self.assertEqual(\n 1,\n sub.kvstore.count()\n )\n","sub_path":"papermerge/test/test_folder.py","file_name":"test_folder.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"606130513","text":"from Indiv import Indiv, IndivInt, IndivReal\nfrom random import random\n\n\nclass Popul:\n\n def __init__(self, popsize, indsize, indivs=[]):#nao passmos um gene\n self.popsize = popsize# numero de individuos da populacao (10 listas)\n self.indsize = indsize#tamanho dos individuos (cada individuo (lista) com 5 elementos)\n if indivs:#se os individuos forem fornecidos\n self.indivs = indivs #individuos\n else:\n self.initRandomPop()#se nao temos de gerar de forma aleatoria\n\n def getIndiv(self, index):#ir buscar um individuo x\n return self.indivs[index]#index = x, vai dar a posicao desse individuo\n\n def initRandomPop(self):#gerar individuos de forma aleatoria\n self.indivs = []\n for _ in range(self.popsize):#quantidade de listas a gerar\n indiv_i = Indiv(self.indsize, [])#gerar os individuos aleatoriamente (n de elemntos, lista)\n self.indivs.append(indiv_i)#adicionar os individuos a lista\n\n def getFitnesses(self, indivs=None):#ir buscar a todas as fitness dos individuos(valores de aptidao)\n fitnesses = []#abrir lista de fitnesses\n if not indivs:# se nao forem inseridos os individuos\n indivs = self.indivs\n for ind in indivs:# se forem inseridos individuos\n fitnesses.append(ind.getFitness())#adicionar o fitness à lista\n return fitnesses\n\n def bestSolution(self):# melhor solucao dos individuos\n return max(self.indivs)\n\n def bestFitness(self):#individuo que tem a avaliacao maxima\n indv = self.bestSolution()#melhor solucao\n return indv.getFitness()#dar o fitness dessa solucao\n\n\n def selection(self, n, indivs=None):#mecanismo de selecao para reproducao\n res = []\n fitnesses = list(self.linscaling(self.getFitnesses(indivs)))#vai obter os fitnesses dos individuos e fazer a normalizacao\n for _ in range(n):# n = numero de novos descendentes\n sel = self.roulette(fitnesses)#selecao atraves da roleta (sel = posicao do fitnesse)\n fitnesses[sel] = 0.0 #\n res.append(sel)\n return res\n\n def roulette(self, f):#f = lista ja das somas dos individuos ??\n tot = sum(f)#soma de f\n val = random()#melhor valor de selecao/aptidao ??\n acum = 0.0#acumulacao de valores de aptidao\n ind = 0#inicializacao de individuos\n while acum < val:\n acum += (f[ind] / tot)#acumulacao\n ind += 1 #somar um individuo\n return ind-1#??\n\n def linscaling(self, fitnesses):#normalizacao do valor de aptidao para [0,1]\n mx = max(fitnesses)#maximo valor de aptidao\n mn = min(fitnesses)#valor minimo de apridao\n res = []#lista de fitnesses normalizado\n for f in fitnesses:\n val = (f-mn)/(mx-mn)\n res.append(val)\n return res\n #exemplo:\n #fitnesses = [1,2,3,4]\n #(1-1)/(4-1) = 0.0 ! (2-1)/(4-1)=0.33 |...\n #res = [0.0, 0.3333333333333333, 0.6666666666666666, 1.0]\n\n def recombination(self, parents, noffspring):#nooffspring = quantas novas solucoes queremos gerar a partir da populacao existente\n offspring = []\n new_inds = 0#inicializacao de novos individuos\n while new_inds < noffspring:\n parent1 = self.indivs[parents[new_inds]]#ir buscar um progenitor 1 aos individuos\n parent2 = self.indivs[parents[new_inds+1]]#ir buscar um progenitor 2 aos individuos\n offsp1, offsp2 = parent1.crossover(parent2)#fazer o cruzamento entre o progenitor 1 e 2\n offsp1.mutation()#aplica mutacao a nova geracao\n offsp2.mutation()#aplica mutacao a nova geracao\n offspring.append(offsp1)#adicionar a lista de novos descendentes\n offspring.append(offsp2)#adicionar a lista de novos descendentes\n new_inds += 2\n return offspring\n\n def reinsertion(self, offspring):#mecanismo de reinsercao -> selecao dos individuos que vao constituir a populacao OU iteracao seguinte\n #offspring = descendentes\n #Exemplo= tenho uma pop com 100 individuos\n #quero 50 descendentes mas para completar a geracao seguinte ainda me faltam 50, ENTAO faco a selecao(roleta)\n tokeep = self.selection(self.popsize-len(offspring))#selecao de individuos\n ind_offsp = 0\n for i in range(self.popsize):\n if i not in tokeep:\n self.indivs[i] = offspring[ind_offsp]#preencher o resto da pop com novos individuos\n ind_offsp += 1\n\n\nclass PopulInt(Popul):\n\n def __init__(self, popsize, indsize, ub, indivs=[]):\n self.ub = ub\n Popul.__init__(self, popsize, indsize, indivs)\n\n def initRandomPop(self):\n self.indivs = []\n for _ in range(self.popsize):#quantidade de listas a gerar\n indiv_i = IndivInt(self.indsize, [], 0, self.ub)#diferenca IndivInt #gerar os individuos aleatoriamente (n de elemntos, lista)\n self.indivs.append(indiv_i)#adicionar os individuos a lista\n\n\nclass PopulReal(Popul):\n\n def __init__(self, popsize, indsize, lb=0.0, ub=1.0, indivs=[]):\n # completar\n self.lb = lb\n self.ub = ub\n Popul.__init__(self, popsize, indsize, indivs)\n\n\n def initRandomPop(self):\n # completar\n self.indivs = []\n for _ in range(self.popsize):\n indiv_i = IndivReal(self.indsize, [], lb = self.lb, ub = self.ub)\n self.indivs.append(indiv_i)\n pass\n","sub_path":"aula6/Popul.py","file_name":"Popul.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"261043567","text":"import pytest\n\nfrom dante.core import commands\nfrom dante.core import utils\n\n\npytestmark = pytest.mark.utils\n\n\ndef test_filter_tree():\n # preconditions\n tree = commands.get_package_tree()\n\n # action\n filtered_tree = utils.filter_tree(tree=tree, list_all=True)\n\n # verification\n assert set(filtered_tree) == set(tree)\n\n\ndef test_filter_tree_only_top_level():\n # preconditions\n tree = commands.get_package_tree()\n\n # action\n filtered_tree = utils.filter_tree(tree=tree, list_all=False)\n\n # verification\n assert not set(filtered_tree) == set(tree)\n\n\ndef test_filter_tree_only_specified():\n # preconditions\n tree = commands.get_package_tree()\n show_only = {'pip'}\n\n # action\n filtered_tree = utils.filter_tree(tree=tree, show_only=show_only)\n\n # verification\n assert len(filtered_tree) == 1\n assert 'pip' in [package.key for package in filtered_tree]\n","sub_path":"dante/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"369577929","text":"import requests\r\nfrom termcolor import cprint,colored\r\nimport colorama\r\nfrom colorama import Fore\r\ncolorama.init()\r\ndef inputs(country):\r\n r = requests.get('http://newsapi.org/v2/top-headlines?country='+country+'&category=business&apiKey=72d6e0915737435d805d05ff0cda7cc0')\r\n c =r.json()['totalResults']\r\n while(c==0):\r\n country = input(Fore.RED+\"Enter the valid country code :\")\r\n r = requests.get('http://newsapi.org/v2/top-headlines?country='+country+'&category=business&apiKey=72d6e0915737435d805d05ff0cda7cc0')\r\n c =r.json()['totalResults']\r\n return r\r\ndef news_intrested(country):\r\n r = inputs(country)\r\n l = len(r.json()['articles'])\r\n for i in range(0,l):\r\n cprint(f\"{i+1} {r.json()['articles'][i]['title']} \",'green')\r\ndef news_bot():\r\n print()\r\n country=input(\"Enter the country code of the news you are intrested in: \")\r\n inputs(country)\r\n news_intrested(country)\r\n print()\r\n number = int(input(\"Enter the number of the news which you are interested to know in extension :\"))\r\n try:\r\n def extended_news(number,country):\r\n r = inputs(country)\r\n print()\r\n cprint(f\"DESCRIPTION OF THE NEWS : {Fore.WHITE+r.json()['articles'][number-1]['description']} \",\"cyan\")\r\n print()\r\n cprint(f\"CONTENT OF THE NEWS: {Fore.WHITE+r.json()['articles'][number-1]['content']} \",\"cyan\")\r\n print()\r\n cprint(f\"To get more information visite the WEBSITE :{Fore.YELLOW+r.json()['articles'][number-1]['url']} \",'cyan')\r\n print()\r\n cprint(f\"It was PUBLISHED ON: {Fore.WHITE+r.json()['articles'][number-1]['publishedAt']} \",'cyan')\r\n print()\r\n cprint(\"-------***Do you want to know about any other news say yes or no****-------\")\r\n print()\r\n boole = input()\r\n if(boole.lower()==\"yes\"):\r\n number1= int(input(\"Enter the number of the news you want to know about :\"))\r\n extended_news(number1,country)\r\n else:\r\n print(\"-------***Do you want to know about any other country news say yes or no***-----\")\r\n boole=input()\r\n if(boole.lower()==\"yes\"):\r\n country1 = input(\"Enter the country code:\")\r\n inputs(country1)\r\n news_intrested(country1)\r\n number2= int(input(\"Enter the news you are interested in:\"))\r\n extended_news(number2,country1)\r\n else:\r\n print()\r\n cprint(\"Thanks for showing interest in watching news from our bot. please visit again \",\"yellow\")\r\n extended_news(number,country)\r\n except Exception:\r\n cprint(\"Enter valid number :\",'red')\r\n num = int(input())\r\n extended_news(num,country)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"newsbot.py","file_name":"newsbot.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"514714516","text":"# Author: Luv Patel (201501459@daiict.ac.in)\n\n\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\nimport numpy as np\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='3'\n\nfrom keras.datasets import mnist\nfrom keras.models import Sequential, load_model\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.utils import np_utils\nfrom keras import initializers\n\n(X_train_a, y_train_a), (X_test, y_test) = mnist.load_data()\n\n\nprint(\"Machine Learning assignment1_code\")\n\nprint(\"X_train's dimensions\", X_train_a.shape)\nprint(\"y_train's dimensions\", y_train_a.shape)\nprint(\"X_train's dimensions\", X_test.shape)\nprint(\"y_train's dimensions\", y_test.shape)\n\n# building the input vector from the 28x28 pixels\nX_train_a = X_train_a.reshape(60000, 784)\nX_test = X_test.reshape(10000, 784)\nX_train_a = X_train_a.astype('float32')\nX_test = X_test.astype('float32')\n\n# normalizing the data to help with the training\nX_train_a /= 255\nX_test /= 255\n\n\nidx = np.random.randint(60000, size=10000)\nX_train = X_train_a[idx,:]\ny_train = y_train_a[idx]\n# print the final input shape ready for training\nprint(\"Here is a train matrix dimension\", X_train.shape)\nprint(\"Here is a test matrix dimension\", X_test.shape)\n\n\nprint(np.unique(y_train, return_counts=True))\n\nn_classes = 10\nprint(\"here is a dimension before one-hot encoding were: \", y_train.shape)\nY_train = np_utils.to_categorical(y_train, n_classes)\nY_test = np_utils.to_categorical(y_test, n_classes)\nprint(\"here are the dimensions after one-hot encoding were : \", Y_train.shape)\n\n\nacc_train = [[[0 for kk in xrange(4)] for jj in xrange(3)] for ii in xrange(3)]\nloss_train = [[[0 for kkk in xrange(4)] for jjj in xrange(3)] for iii in xrange(3)]\nacc_test = [[[0 for kk in xrange(4)] for jj in xrange(3)] for ii in xrange(3)]\nloss_test = [[[0 for kkk in xrange(4)] for jjj in xrange(3)] for iii in xrange(3)]\n# matrix_acc[0][0][3] = [1,2,3,4]\n# print(matrix_acc)\n\nstdv = 0.05\nstdname = '005'\narchname = '1'\nfunct = 'linear'\nfor i in range(3):\n\tfor j in range(3):\n\t\tfor k in range(4):\n\t\t\tarchname='1'\n\t\t\tif i==0:\n\t\t\t\tstdv=0.05\n\t\t\t\tstdname='005'\n\t\t\telif i==1:\n\t\t\t\tstdv=0.5\n\t\t\t\tstdname='050'\n\t\t\telse:\n\t\t\t\tstdv=1\n\t\t\t\tstdname='100'\n\n\t\t\tif k==0:\n\t\t\t\tfunct = 'linear'\n\t\t\telif k==1:\n\t\t\t\tfunct = 'sigmoid'\n\t\t\telif k==2:\n\t\t\t\tfunct = 'tanh'\n\t\t\telse:\n\t\t\t\tfunct = 'relu'\n\n\t\t\tmodel = Sequential()\n\t\t\tmodel.add(Dense(128, input_shape=(784,), kernel_initializer=initializers.random_normal(stddev=stdv)))\n\t\t\tmodel.add(Activation(funct)) \n\t\t\tmodel.add(Dropout(0.2))\n\n\t\t\tif j>0:\n\t\t\t\tmodel.add(Dense(64, kernel_initializer=initializers.random_normal(stddev=stdv)))\n\t\t\t\tmodel.add(Activation(funct))\n\t\t\t\tmodel.add(Dropout(0.2))\n\t\t\t\tarchname = '2'\n\n\t\t\tif j>1:\n\t\t\t\tmodel.add(Dense(64, kernel_initializer=initializers.random_normal(stddev=stdv)))\n\t\t\t\tmodel.add(Activation(funct))\n\t\t\t\tmodel.add(Dropout(0.2))\n\t\t\t\tarchname = '3'\n\n\t\t\tmodel.add(Dense(10, kernel_initializer=initializers.random_normal(stddev=stdv)))\n\t\t\tmodel.add(Activation('softmax'))\n\n\t\t\tmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='sgd')\n\n\t\t\thistory = model.fit(X_train, Y_train,\n\t\t\t batch_size=128, epochs=15,\n\t\t\t verbose=2,\n\t\t\t validation_data=(X_test, Y_test))\n\n\t\t\tsave_dir = \"./results/\"\n\t\t\tmodel_name = 'ML4DM_assignment_code'+'_arch_'+archname+'__std_'+stdname+'__act_'+funct+'.h5'\n\t\t\tmodel_path = os.path.join(save_dir, model_name)\n\t\t\tmodel.save(model_path)\n\t\t\tprint('Let us Save a trained model at %s for future use' % model_path)\n\n\t\t\tacc_train[i][j][k] = history.history['acc']\n\t\t\tloss_train[i][j][k] = history.history['loss']\n\t\t\tacc_test[i][j][k] = history.history['val_acc']\n\t\t\tloss_test[i][j][k] = history.history['val_loss']\n\t\t\t\n\t\t\tfig = plt.figure()\n\t\t\tplt.subplot(2,1,1)\n\t\t\tplt.plot(history.history['acc'])\n\t\t\tplt.plot(history.history['val_acc'])\n\t\t\tplt.title('accuracy level'+'_arrch_'+archname+'__standers_'+stdname+'__act_'+funct)\n\t\t\tplt.ylabel('accuracy on y axis')\n\t\t\tplt.xlabel('epoch on x axis')\n\t\t\tplt.legend(['train model', 'test model'], loc='lower right')\n\n\t\t\tplt.subplot(2,1,2)\n\t\t\tplt.plot(history.history['loss'])\n\t\t\tplt.plot(history.history['val_loss'])\n\t\t\tplt.title('loss level'+'_arch_'+archname+'__standers_'+stdname+'__act_'+funct)\n\t\t\tplt.ylabel('loss on y axis')\n\t\t\tplt.xlabel('epoch on x axis')\n\t\t\tplt.legend(['train model', 'test model'], loc='upper right')\n\n\t\t\tplt.tight_layout()\n\t\t\tplt.show()\n\t\t\tfig\n\n\t\t\tmnist_model = load_model(\"./results/\"+model_name)\n\t\t\tloss_and_metrics = mnist_model.evaluate(X_test, Y_test, verbose=2)\n\n\t\t\tprint(\"Total Loss of test\", loss_and_metrics[0])\n\t\t\tprint(\"Overall Test Accuracy\", loss_and_metrics[1])\n\n\t\t\tmnist_model = load_model(\"./results/\"+model_name)\n\t\t\tpredicted_classes = mnist_model.predict_classes(X_test)\n\n\t\t\tcorrect_indices = np.nonzero(predicted_classes == y_test)[0]\n\t\t\tincorrect_indices = np.nonzero(predicted_classes != y_test)[0]\n\t\t\tprint()\n\t\t\tprint()\n\t\t\tprint()\n\t\t\tprint(len(correct_indices),\" hey it is classified correctly\")\n\t\t\tprint(len(incorrect_indices),\" it is classified incorrectly\")\n\n\nsio.savemat('./acc_train.mat', mdict={'acc_train': acc_train})\nsio.savemat('./loss_train.mat', mdict={'loss_train': loss_train})\nsio.savemat('./acc_test.mat', mdict={'acc_test': acc_test})\nsio.savemat('./loss_test.mat', mdict={'loss_test': loss_test})\n\n","sub_path":"CS404_ML4DM_LAB_ASSIGNMENT_201501459_Luv Patel/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"80935351","text":"from bs4 import BeautifulSoup\nimport time, re\n\n# upsert to mongo collection\ndef upsertToMongo(jobs_collection, job):\n jobs_collection.replace_one({'jobId': job['jobId']}, job, upsert=True)\n\ngoogleUrl = 'https://careers.google.com'\n \ndef scrapeGoogle(browser, jobs_collection):\n browser.get(googleUrl + '/jobs/results/?company=Google&company=Google%20Fiber&company=YouTube&employment_type=FULL_TIME&employment_type=INTERN&hl=en_US&jlo=en_US&q=software%20engineering&sort_by=relevance')\n time.sleep(5)\n listOfUrls = []\n \n htmlFile = browser.page_source\n \n soup = BeautifulSoup(htmlFile, 'html.parser')\n \n jobAs = soup.find('ol', class_='gc-h-unstyled-list gc-p-results__results-list').find_all('a', class_='gc-card')\n \n for a in jobAs:\n url = a['href']\n listOfUrls.append(url)\n \n nextPageUrl = ''\n hasNextPage = True\n nextPageUrl = soup.find('div', class_='gc-action-group gc-action-group--center').find_all('a')[1]['href']\n \n while hasNextPage:\n try:\n browser.get(googleUrl + nextPageUrl)\n time.sleep(5)\n\n htmlFile = browser.page_source\n\n soup = BeautifulSoup(htmlFile, 'html.parser')\n\n jobAs = soup.find('ol', class_='gc-h-unstyled-list gc-p-results__results-list').find_all('a', class_='gc-card')\n\n for a in jobAs:\n listOfUrls.append(a['href'])\n\n prevNextLinks = soup.find('div', class_='gc-action-group gc-action-group--center').find_all('a')\n nextPageUrl = prevNextLinks[1]['href']\n\n # google just hide the links but they are still there, so break if no jobs displayed\n if len(jobAs) < 1:\n break\n except Exception as e:\n hasNextPage = False\n \n index = 1\n for url in listOfUrls:\n try:\n jobUrl = googleUrl + url\n browser.get(jobUrl)\n time.sleep(5)\n print('progress ' + str(index) + ' total ' + str(len(listOfUrls)))\n index = index + 1\n\n htmlFile = browser.page_source\n\n soup = BeautifulSoup(htmlFile, 'html.parser')\n\n jobTitle = soup.find('h1').text.strip()\n jobLocation = soup.find('li', class_='gc-job-tags__location').text.strip()\n\n uls = soup.find('div', class_='gc-job-qualifications gc-user-generated-content').find_all('ul')\n jobDescription = ''\n jobBackupDescription = ''\n jobExperienceDescription = ''\n\n for ul in uls:\n for li in ul.find_all('li'):\n jobDescription = jobDescription + ' ' + li.text.strip()\n jobBackupDescription = li.text.strip()\n\n if bool(re.search(r'\\d', li.text)):\n jobExperienceDescription = li.text.strip()\n\n if jobExperienceDescription == '':\n jobExperienceDescription = jobBackupDescription\n\n # get jobId\n urlArr = jobUrl.split('?')\n\n newSplatUrl = urlArr[len(urlArr) - 2]\n\n extraNewSplatUrl = newSplatUrl.split('/')\n megaExtraNewSplatUrl = extraNewSplatUrl[len(extraNewSplatUrl) - 2]\n\n # data to insert\n if jobDescription != '':\n jobObj = {\n 'jobId': 'go' + megaExtraNewSplatUrl.split('-')[0],\n 'company': 'google',\n 'url': googleUrl + url,\n 'title': jobTitle,\n 'longDescription': jobDescription.strip(),\n 'location': jobLocation,\n 'time': round(time.time() * 1000),\n 'shortDescription': jobExperienceDescription,\n }\n \n upsertToMongo(\n jobs_collection,\n jobObj\n )\n \n except Exception as e:\n pass\n\n","sub_path":"fang-scraper/google_scrape.py","file_name":"google_scrape.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"112233867","text":"from django.contrib import messages\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.text import slugify\n\nfrom core.forms import ReservaChangeForm, QuartoChangeForm\nfrom core.models import Reserva, Quarto, ImagemQuarto, Pacote\n\n\ndef index(request):\n pacotes = Pacote.objects.all()\n return render(request, 'core/index.html', {\n 'pacotes': pacotes,\n })\n\n\ndef info(request):\n return render(request, 'core/info.html')\n\n\n#def quarto_list(request):\n# quartos = Quarto.objects.order_by('name')\n# return render(request, 'core/quarto_list.html', {\n# 'quartos': quartos,\n# })\n\n\ndef reserva_list(request):\n reservas = Reserva.objects.prefetch_related(\n 'quarto',\n ).order_by('start_date')\n return render(request, 'core/reserva_list.html', {\n 'reservas': reservas,\n })\n\n\ndef quarto_view(request, quarto_slug):\n quarto = get_object_or_404(Quarto, slug=quarto_slug)\n photos = ImagemQuarto.objects.filter(quarto=quarto)\n return render(request, 'core/quarto_view.html', {\n 'quarto': quarto,\n 'photos': photos,\n })\n\n\ndef reserva_calendar(request):\n reservas = Reserva.objects.prefetch_related(\n 'quarto',\n ).order_by('end_date')\n return render(request, 'core/reserva_calendar.html', {\n 'reservas': reservas,\n })\n\n\ndef quarto_add(request):\n if str(request.user) != 'AnonymousUser':\n form = QuartoChangeForm()\n if request.method == 'POST':\n form = QuartoChangeForm(request.POST, request.FILES)\n if form.is_valid():\n quarto = form.save(commit=False)\n quarto.slug = slugify(quarto.name)\n quarto.save()\n messages.add_message(\n request,\n messages.SUCCESS,\n extra_tags='success',\n message='Quarto {name} cadastrado com sucesso.'.format(\n name=quarto.name\n )\n )\n return redirect('core:quarto-list')\n return render(request, 'core/quarto_change.html', {\n 'form': form,\n })\n else:\n return redirect('core:index')\n\n\ndef quarto_change(request, quarto_id):\n quarto = get_object_or_404(Quarto, id=quarto_id)\n form = QuartoChangeForm(instance=quarto)\n if request.method == 'POST':\n form = QuartoChangeForm(data=request.POST, instance=quarto)\n if form.is_valid():\n quarto = form.save(commit=False)\n quarto.slug = slugify(quarto.name)\n quarto.save()\n messages.add_message(\n request,\n messages.SUCCESS,\n extra_tags='success',\n message='Quarto {name} editado com sucesso.'.format(\n name=quarto.name\n )\n )\n return redirect('core:quarto-list')\n return render(request, 'core/quarto_change.html', {\n 'form': form,\n 'quarto': quarto,\n })\n\n\ndef reserva_add(request):\n quartos = Quarto.objects.all()\n form = ReservaChangeForm()\n \n if request.method == 'POST':\n form = ReservaChangeForm(request.POST, request.FILES)\n if form.is_valid():\n reserva = form.save()\n messages.add_message(\n request,\n messages.SUCCESS,\n extra_tags='success',\n message='{name} sua reserva foi adcionada com sucesso.'.format(\n name=reserva.name,\n\n )\n )\n form.send_mail()\n return redirect('core:reserva-list')\n return render(request, 'core/reserva_change.html', {\n 'form': form,\n 'quartos': quartos,\n })\n\n\ndef reserva_change(request, reserva_id):\n reserva = get_object_or_404(Reserva, id=reserva_id)\n quartos = Quarto.objects.all()\n form = ReservaChangeForm(instance=reserva)\n if request.method == 'POST':\n form = ReservaChangeForm(data=request.POST, instance=reserva)\n if form.is_valid():\n reserva.save()\n messages.add_message(\n request,\n messages.SUCCESS,\n extra_tags='success',\n message='Reserva {name} editada com sucesso.'.format(\n name=reserva.name\n )\n )\n return redirect('core:reserva-list')\n return render(request, 'core/reserva_change.html', {\n 'form': form,\n 'quartos': quartos,\n 'reserva': reserva,\n })\n\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"488811390","text":"class EvenOrODDNumber:\n\n @classmethod\n def is_odd_or_even(cls, number):\n return 'even' if number % 2 == 0 else 'odd'\n\n @classmethod\n def check_even_or_odd_numbers_on_range(cls, min, max):\n result = []\n for numbers in range(min, max + 1):\n result.append(\"{} : is {}\".format(numbers, cls.is_odd_or_even(numbers)))\n return result\n","sub_path":"OmarHuanca/python/session2/EvenOrODDNumber.py","file_name":"EvenOrODDNumber.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"185728180","text":"from turtle import Screen, Turtle\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nimport time\r\nfrom score import Score\r\nimport logging\r\n\r\nlogger = logging.getLogger()\r\nlogger.setLevel(logging.INFO)\r\n\r\n\r\n###########################################################################################\r\ndef main_flow(WIDTH: int = 800, HEIGHT: int = 600) -> bool:\r\n \"\"\"\r\n\r\n :param WIDTH:\r\n :param HEIGHT:\r\n :return:\r\n \"\"\"\r\n \"\"\" create screen \"\"\"\r\n screen = Screen()\r\n screen.title(\"Ping Pong Gong\")\r\n screen.bgcolor(\"Black\")\r\n screen.setup(width=WIDTH, height=HEIGHT)\r\n middle_line = Turtle()\r\n logger.debug(f\"Screen size: {WIDTH, HEIGHT}\")\r\n\r\n screen.tracer(0) # shuts down the animation\r\n # drow middle line\r\n middle_line.pencolor(\"white\")\r\n middle_line.penup()\r\n middle_line.goto(0, -500)\r\n middle_line.left(90)\r\n\r\n for i in range(100):\r\n middle_line.pendown()\r\n middle_line.forward(10)\r\n middle_line.penup()\r\n middle_line.forward(10)\r\n left_paddle = Paddle(begin=\"left\")\r\n right_paddle = Paddle(begin=\"right\")\r\n\r\n screen.listen()\r\n screen.onkey(fun=right_paddle.go_up, key=\"Up\")\r\n screen.onkey(fun=right_paddle.go_down, key=\"Down\")\r\n screen.onkey(fun=left_paddle.go_up, key=\"w\")\r\n screen.onkey(fun=left_paddle.go_down, key=\"s\")\r\n\r\n ball = Ball()\r\n score = Score()\r\n ball.speed(\"fastest\")\r\n\r\n game_om = True\r\n while game_om:\r\n time.sleep(0.092)\r\n screen.update()\r\n ball.move()\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce_y()\r\n\r\n if ball.distance(right_paddle) < 50 and ball.xcor() > 340:\r\n ball.bounce_x()\r\n if ball.distance(left_paddle) < 50 and ball.xcor() < -340:\r\n ball.bounce_x()\r\n if ball.xcor() > 380:\r\n score.right_goal()\r\n ball.goto(0, 0)\r\n if ball.xcor() < -380:\r\n ball.goto(0, 0)\r\n score.left_goal()\r\n\r\n screen.exitonclick()\r\n return True\r\n\r\n\r\nif __name__ == '__main__':\r\n logger.info(\"started run\")\r\n\r\n main_flow()\r\n logger.info(\"finished run\")\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"575828281","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/4/12 9:02 PM\n# @Author : zhongch4g\n# @Site : \n# @File : binaryTreePath.py\n# @Software: IntelliJ IDEA\n\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n\n\nclass Solution:\n \"\"\"\n @param root: the root of the binary tree\n @return: all root-to-leaf paths\n \"\"\"\n def binaryTreePaths(self, root):\n # write your code here\n # Solve\n if (root is None):\n return []\n\n if (root.left is None and root.right is None):\n return [str(root.val)]\n paths = []\n\n left = self.binaryTreePaths(root.left)\n right = self.binaryTreePaths(root.right)\n\n # Combine\n for path in left:\n paths.append(str(root.val) + '->' + path)\n for path in right:\n paths.append(str(root.val) + '->' + path)\n return paths\n\n def traverse_binary_tree_path(self, root):\n if (root is None):\n return []\n path = []\n self.dfs(root, [str(root.val)], path)\n print(path)\n\n def dfs(self, root, curpath, path):\n if (root.left is None and root.right is None):\n path.append('->'.join(curpath))\n return\n\n if (root.left):\n curpath.append(str(root.left.val))\n self.dfs(root.left, curpath, path)\n curpath.pop()\n if (root.right):\n curpath.append(str(root.right.val))\n self.dfs(root.right, curpath, path)\n curpath.pop()\n\n\n def maximum_depth_of_binary_tree(self, root):\n if (root is None):\n return 0\n if (root.left is None and root.right is None):\n return 1\n\n left = self.maximum_depth_of_binary_tree(root.left)\n right = self.maximum_depth_of_binary_tree(root.right)\n\n # Solve\n return max(left, right) + 1\n\n\n\nroot = TreeNode(1)\nnode1 = TreeNode(2)\nnode2 = TreeNode(3)\nnode3 = TreeNode(4)\nnode4 = TreeNode(5)\nroot.left = node1\nroot.right = node2\nnode1.left = node3\nnode1.right = node4\nsolution = Solution()\nprint(solution.traverse_binary_tree_path(root))\n# print(solution.maximum_depth_of_binary_tree(root))","sub_path":"extra/binaryTreePath.py","file_name":"binaryTreePath.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"262573903","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 RERO.\n#\n# Swiss Open Access Repository is free software; you can redistribute it\n# and/or modify it under the terms of the MIT License; see LICENSE file for\n# more details.\n\n\"\"\"Test OAuth with ORCID.\"\"\"\n\nimport sonar.modules.oauth.orcid as sonar_orcid\n\n\ndef test_account_info(app, mock_api_read_record, orcid_record, user_record):\n \"\"\"Test account info extraction.\"\"\"\n assert sonar_orcid.account_info(None, orcid_record) == user_record\n\n\ndef test_account_setup(app, orcid_record, models_fixture,\n remote_account_fixture):\n \"\"\"Test account setup after login.\"\"\"\n remote_account, remote_token = remote_account_fixture\n\n ioc = app.extensions['oauthlib.client']\n\n sonar_orcid.account_setup(ioc.remote_apps['orcid'], remote_token,\n orcid_record)\n\n assert remote_account.extra_data['orcid'] == orcid_record['orcid']\n\n\ndef test_get_orcid_record(mock_api_read_record, app, orcid_record):\n \"\"\"Test to get an orcid detail.\"\"\"\n # Test valid returned record\n record = sonar_orcid.get_orcid_record(orcid_record['orcid'],\n orcid_record['access_token'])\n assert record['orcid-identifier']['path'] == orcid_record['orcid']\n\n # Test error when request_type is invalid\n record = sonar_orcid.get_orcid_record(orcid_record['orcid'],\n orcid_record['access_token'], 'FAKE')\n assert not record\n\n # Test error when access token is invalid\n record = sonar_orcid.get_orcid_record(orcid_record['orcid'],\n 'NOT_EXISTING')\n assert not record\n\n # Test error when record id does not exist\n record = sonar_orcid.get_orcid_record('NOT_EXISTING',\n orcid_record['access_token'])\n assert not record\n\n\ndef test_get_orcid_record_email(mock_api_read_record, app, orcid_record):\n \"\"\"Test getting ORCID record email.\"\"\"\n # Test existing email\n email = sonar_orcid.get_orcid_record_email(orcid_record['orcid'],\n orcid_record['access_token'])\n assert email == 'john.doe@test.com'\n\n # Test when record id does not exists\n email = sonar_orcid.get_orcid_record_email('NOT_EXISTING',\n orcid_record['access_token'])\n assert email == ''\n\n # Test when access token does not exists\n email = sonar_orcid.get_orcid_record_email(orcid_record['orcid'],\n 'NOT_EXISTING')\n assert email == ''\n","sub_path":"tests/ui/oauth/test_oauth_orcid.py","file_name":"test_oauth_orcid.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"180824058","text":"# coding=utf-8\n# Copyright (c) 2017 Dell Inc. or its subsidiaries.\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 unittest\n\nfrom ddt import ddt, data, unpack\n\nfrom nagiosunity import commands\nfrom nagiosunity.tests import utils\n\nresult_dict = {'battery': 0, 'dae': 0, 'disk': 0, 'dpe': 0, 'ethernet_port': 2,\n 'fan': 0, 'fc_port': 1, 'io_module': 0, 'lcc': 0, 'lun': 0,\n 'memory_module': 0, 'pool': 0, 'power_supply': 0, 'sas_port': 0,\n 'sp': 0, 'ssc': 0, 'ssd': 0, 'system': 0, 'array_hardware': 2}\n\n\n@ddt\nclass CommandsTest(unittest.TestCase):\n @unpack\n @data(*commands.commands_dict.items())\n @utils.patch_unity\n def test_check(self, name, command):\n if name not in result_dict:\n return self.skipTest(\n \"Please specify the expected result in result_dict.\")\n c = command(options={})\n r = c.check()\n self.assertEqual(result_dict[name], r,\n \"Assert failed for {}\".format(name))\n","sub_path":"nagiosunity/tests/commands/test_all_commands.py","file_name":"test_all_commands.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"481301274","text":"\n'''\n - Written module to enhance our file output.\n'''\n\nimport time\nimport subprocess\n\ndef gitAdd(fileName, repoDir):\n cmd = 'git add ' + fileName\n pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )\n (out, error) = pipe.communicate()\n print (out,error)\n pipe.wait()\n return\n\ndef gitCommit(commitMessage, repoDir):\n cmd = 'git commit -am \"%s\"'%commitMessage\n pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )\n (out, error) = pipe.communicate()\n print (out,error)\n pipe.wait()\n return\ndef gitPush(repoDir):\n cmd = 'git push '\n pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )\n (out, error) = pipe.communicate()\n pipe.wait()\n return\n\ntemp=time.localtime(time.time())\nuploaddate= str(temp[0])+'_'+str(temp[1])+'_'+str(temp[2])+'_'+str(temp[3])+'_'+str(temp[4])\n\nrepoDir='/mnt/c/Users/Mdotg/Desktop/testingLinux/PythonTipsandTricks/dailyScript'\n#'d:\\\\c_Billy\\\\vfat\\\\Programming\\\\Projector\\\\billyccm' # your git repository , windows your need to use double backslash for right directory.\ngitAdd('.',repoDir )\ngitCommit(uploaddate, repoDir)\ngitPush(repoDir)\n\n# ------------------------------------------------------------------------------\n# PYTHONSCRIPT: myfile.py\n# ------------------------------------------------------------------------------\n# Project: n/a\n# Created by: user on 22/7/2015\n# $Last Update: 2015-09-09 by user $\n# $Comment: Added comment keyword $\n# $Hash: ec56f527333c0c0af98c2ed3ab3395c6c8a50624 $\n# ------------------------------------------------------------------------------\nimport random\ncommitNo = random.randint(150,180)\nfileNo = random.randint(1,10)\n\ndef createFile():\n subprocess.call([\"ls\", \"-l\"])\n subprocess.call([\"touch\",\"fileaddedNew.txt\"])\n\ndef deleteFile():\n subprocess.call([\"ls\", \"-l\"])\n subprocess.call([\"rm\",\"-rf\",\"fileaddedNew.txt\"])\n\n# ------------------------------------------------------------------------------\n# PYTHONSCRIPT: myfile.py\n# ------------------------------------------------------------------------------\n# Project: n/a\n# Created by: user on 22/7/2015\n# $Last Update: 2015-09-09 by user $\n# $Comment: Added comment keyword $\n# $Hash: ec56f527333c0c0af98c2ed3ab3395c6c8a50624 $\n# ------------------------------------------------------------------------------\n\n# https://stackoverflow.com/questions/373335/how-do-i-get-a-cron-like-scheduler-in-python\nimport schedule\nimport time\n\n# def job():\n# print(\"I'm working...\")\n# createFile()\n\ndef pushMyfiles():\n gitAdd('.',repoDir )\n gitCommit(uploaddate, repoDir)\n gitPush(repoDir)\n\nschedule.every(0.10).minutes.do(createFile)\nschedule.every(0.15).minutes.do(pushMyfiles)\nschedule.every(0.20).minutes.do(deleteFile)\n# schedule.every().hour.do(job)\n# schedule.every().day.at(\"10:30\").do(job)\n\ncounter = 0\nwhile 1:\n schedule.run_pending()\n time.sleep(1)\n if counter >= commitNo:\n break\n else:\n counter = counter +1\n print(f\"current commit = {counter}/{commitNo}\")\n\n\n","sub_path":"dailyScript/P08_automateGitPushProcessWindows.py","file_name":"P08_automateGitPushProcessWindows.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"117347292","text":"#!/usr/bin/env python\n# encoding=utf-8\n\n\"\"\"\n@Author: zhongjianlv\n\n@Create Date: 18-5-12, 10:24\n\n@Description:\n\n@Update Date: 18-5-12, 10:24\n\"\"\"\nimport numpy as np\nimport time\nimport os\nimport gc\nimport pandas as pd\nfrom sklearn.metrics import roc_auc_score\nimport functools\nfrom sklearn.model_selection import StratifiedKFold\nfrom scipy.stats import spearmanr\nfrom sklearn.preprocessing import LabelEncoder\nfrom joblib import dump, load, Parallel, delayed\n# from smooth import HyperParam\nimport contextlib\nfrom contextlib import contextmanager\nfrom itertools import product\nfrom DMF.smooth import HyperParam\nMAX_DIS_FUNCTION = []\n\n\n################## 辅助函数 #####################\ndef performance(f): # 定义装饰器函数,功能是传进来的函数进行包装并返回包装后的函数\n @functools.wraps(f)\n def fn(*args, **kw): # 对传进来的函数进行包装的函数\n t_start = time.time() # 记录函数开始时间\n r = f(*args, **kw) # 调用函数\n t_end = time.time() # 记录函数结束时间\n print('call %s() in %fs' % (f.__name__, (t_end - t_start))) # 打印调用函数的属性信息,并打印调用函数所用的时间\n return r # 返回包装后的函数\n\n return fn # 调用包装后的函数\n\ndef checkpath(f):\n # 检查一下用来存放checkpoint的path是否存在了\n @functools.wraps(f)\n def fn(*args, **kw):\n if 'checkpath' in args[0].keys():\n if os.path.exists(args[0]['checkpath'])==False:\n os.makedirs(args[0]['checkpath'])\n f(*args, **kw)\n return fn\n\ndef dump_feature(f): # 定义装饰器函数,功能是传进来的函数进行包装并返回包装后的函数\n @functools.wraps(f)\n def fn(*args, **kw): # 对传进来的函数进行包装的函数\n path = os.path.join(args[-1], \"features\")\n if (not os.path.exists(path)):\n os.mkdir(path)\n t_start = time.time()\n if (len(args) > 1):\n fname = f.__name__\n for _n in args[:-1]:\n fname += \"_{}\".format(_n)\n fname += \".feather\"\n dump_path = os.path.join(path, fname)\n else:\n dump_path = os.path.join(path, f.__name__ + '.feather')\n if os.path.exists(dump_path):\n r = pd.read_feather(dump_path, nthreads=4)\n else:\n r = f(*args, **kw)\n downcast(r)\n r.reset_index(drop=True, inplace=True)\n for c in r.columns:\n if r[c].dtype == 'float64':\n r[c] = r[c].astype('float32')\n r.to_feather(dump_path)\n gc.collect()\n t_end = time.time()\n print('call %s() in %fs' % (f.__name__, (t_end - t_start)))\n return r\n return fn\n\n\nMAIN_ID = [\"uid\", \"pid\"]\ndef dump_feature_remove_main_id(f): # 定义装饰器函数,功能是传进来的函数进行包装并返回包装后的函数\n @functools.wraps(f)\n def fn(*args, **kw): # 对传进来的函数进行包装的函数\n path = os.path.join(args[-1], \"features_remove_main_id\")\n if (not os.path.exists(path)):\n os.mkdir(path)\n t_start = time.time()\n if (len(args) > 1):\n fname = f.__name__\n for _n in args[:-1]:\n fname += \"_{}\".format(_n)\n fname += \".feather\"\n dump_path = os.path.join(path, fname)\n else:\n dump_path = os.path.join(path, f.__name__ + '.feather')\n if os.path.exists(dump_path):\n r = pd.read_feather(dump_path, nthreads=4)\n downcast(r)\n else:\n r = f(*args, **kw)\n r.sort_values(by=MAIN_ID, inplace=True)\n # remove main id\n if(f.__name__ != 'click_label'):\n for _c in MAIN_ID:\n del r[_c]\n # down bit\n for c in r.columns:\n if r[c].dtype == 'float64':\n r[c] = r[c].astype('float32')\n r.reset_index(drop=True, inplace=True)\n r.to_feather(dump_path)\n gc.collect()\n t_end = time.time()\n print('call %s() in %fs' % (f.__name__, (t_end - t_start)))\n return r\n return fn\n\n# 合并节约内存\n@performance\ndef concat(L):\n result = None\n for l in L:\n if result is None:\n result = l\n else:\n result[l.columns.tolist()] = l\n return result\n\n# def check_labeled_existing(f):\n# @functools.wraps(f)\n# def fn(*args, **kw):\n# if \n\ndef log(labels):\n return np.log(labels + 1)\n\ndef exp(labels):\n return np.exp(labels) - 1\n\ndef euclidean(values1, values2):\n \"\"\"\n 欧式距离\n :param values1: n_sample * f_leangth\n :param values2: n_sample * f_leangth 或者 f_leangth\n :return:\n \"\"\"\n return np.sqrt(np.sum((values1 - values2) ** 2, axis=1))\n\n\ndef cosine(values1, values2):\n \"\"\"\n 余弦距离\n :param values1: n_sample * f_leangth\n :param values2: n_sample * f_leangth 或者 f_leangth\n :return:\n \"\"\"\n return np.sum((values1 * values2), axis=1) / (np.sqrt(np.sum(values1 ** 2, axis=1)) * np.sqrt(np.sum(values2 ** 2)))\nMAX_DIS_FUNCTION.append(cosine)\n\n\n\ndef optm_cosine(v1, v2):\n \"\"\"\n 优化一波余弦距离\n \"\"\"\n n_samples, f_features = v1.shape\n n_centers, f_features = v2.shape\n return np.dot(v1, v2.T) / np.dot(np.linalg.norm(v1, axis=1).reshape(n_samples, -1), np.linalg.norm(v2, axis=1).reshape(-1, n_centers))\nMAX_DIS_FUNCTION.append(optm_cosine)\n# 过滤缺失值过多的特征\ndef filter_feature_by_missing(df, origin_feature_names, threshold=0.95):\n \"\"\"\n 过滤缺失率大于threshold的特征\n :param df: 数据集df\n :param origin_feature_names: 要过滤的特征\n :param threshold:\n :return: 去除特征,保留特征\n \"\"\"\n remove_feature_name = []\n stay_feature_name = []\n for _f in origin_feature_names:\n nan_size = df[_f].isnull().sum()\n nan_ratio = float(nan_size) / df.shape[0]\n if nan_ratio > threshold:\n remove_feature_name.append(_f)\n else:\n stay_feature_name.append(_f)\n return remove_feature_name, stay_feature_name\n\n\ndef filter_feature_by_spearmanr(df, origin_feature_names, target_column, threshold=0.1):\n \"\"\"\n 过滤皮尔森相关系数小于threshold的特征\n :param df:\n :param origin_feature_names:\n :param threshold:\n :return:\n \"\"\"\n remove_feature_name = []\n stay_feature_name = []\n y = df[target_column].values\n for _f in origin_feature_names:\n if (df[_f].dtypes == object):\n temp = label_encode(df[[_f]].copy(), [_f])[_f]\n else:\n temp = df[_f]\n score = spearmanr(temp.values, y).correlation\n if score < threshold:\n remove_feature_name.append(_f)\n else:\n stay_feature_name.append(_f)\n return remove_feature_name, stay_feature_name\n\n\ndef filter_feature_which_0std(df, origin_feature_names):\n \"\"\"\n 去除方差为0的特征列\n :param df:\n :param origin_feature_names:\n :return:\n \"\"\"\n remove_feature_name = []\n stay_feature_name = []\n for _f in origin_feature_names:\n if (df[_f].dtypes == object):\n temp = df[_f]\n if (len(temp[~temp.isnull()].unique()) <= 1):\n remove_feature_name.append(_f)\n else:\n stay_feature_name.append(_f)\n else:\n s = df[_f].std()\n if s == 0:\n remove_feature_name.append(_f)\n else:\n stay_feature_name.append(_f)\n return remove_feature_name, stay_feature_name\n\ndef fill_feature(df, fill_features, cate_method=\"mode\", num_method=\"median\", other_fill_value=-1, threshold = 0.01):\n \"\"\"\n 填充缺失率小于threshold的列,mode 为众数填充,median为中位数填充,mean为均值填充\n 超过threshold的填充-1\n :param df:\n :param fill_features:\n :param cate_method:\n :param num_method:\n :param threshold:\n :return:\n \"\"\"\n for _f in fill_features:\n nan_size = df[_f].isnull().sum()\n nan_ratio = float(nan_size) / df.shape[0]\n if nan_ratio < threshold:\n if(df[_f].dtypes == object):\n if(cate_method == \"mode\"):\n df[_f] = df[_f].fillna(df[_f].mode()[0])\n else:\n print(\"error fill cate method\", num_method)\n exit(1)\n else:\n if(num_method == \"median\"):\n df[_f] = df[_f].fillna(df[_f].median())\n elif(num_method == \"mean\"):\n df[_f] = df[_f].fillna(df[_f].mean())\n else:\n print(\"error fill num method\", num_method)\n exit(1)\n else:\n df[_f] = df[_f].fillna(other_fill_value)\n\n return df\n\ndef detect_cate_columns(df, detect_columns):\n \"\"\"\n 检测cate列和数字列\n :param df:\n :param detect_columns:\n :return: 类别类,数字列\n \"\"\"\n part = df[detect_columns]\n cate_columns = part.columns[part.dtypes == object]\n num_columns = part.columns[part.dtypes != object]\n return cate_columns, num_columns\n\n\ndef label_encode(df, transform_columns):\n \"\"\"\n 将df中的transform_columns列转为label列\n :param df:\n :param transform_columns:\n :return:\n \"\"\"\n for _c in transform_columns:\n uniques = df[_c].unique()\n _d = dict(zip(uniques, range(len(uniques))))\n df[_c] = df[_c].apply(lambda x: _d[x])\n return df\n\n\ndef train_test_split_stratifiedKFold(n_split, random_state, shuffle, target_df, target_column):\n \"\"\"\n StratifiedKFold划分训练和验证\n :param n_split:\n :param random_state:\n :param shuffle:\n :param target_df:\n :param target_column:\n :return: [(train1_index,valid1_index),(train2_index,valid2_index),...]\n \"\"\"\n skf = StratifiedKFold(n_splits=n_split, random_state=random_state, shuffle=shuffle)\n g = skf.split(np.arange(target_df.shape[0]), target_df[target_column].values)\n splits = []\n for _x, _y in g:\n splits.append((_x, _y))\n return splits\n\ndef detect_cates_for_narrayx(x, threshold=10):\n \"\"\"\n 将数量小于等于threshold的认为 是cate列\n :param x: np_array\n :param threshold:\n :return:\n \"\"\"\n cates = []\n for _i in range(x.shape[1]):\n if(len(np.unique(x[:, _i])) <= threshold):\n if(np.isnan(x[:, _i]).sum()==0):\n x[:, _i] = x[:, _i].astype(int)\n cates.append(_i)\n return cates\n\ndef transform_float_to_int_for_narrayx(x, cates):\n \"\"\"\n 将x中cates的列的全部转换为int\n :param x: np_array\n :param cates:\n :return:\n \"\"\"\n x = x.copy()\n for _i in cates:\n x[:, _i] = x[:, _i].astype(int)\n return x\n\ndef downcast(df):\n \"\"\"\n 降位\n :param df:\n :return:\n \"\"\"\n print (df.info(memory_usage='deep'))\n df_int = df.select_dtypes(include=['int64', 'int32']).apply(pd.to_numeric, downcast='integer')\n df[df_int.columns] = df_int\n del df_int; gc.collect()\n print (df.info(memory_usage='deep'))\n df_float64 = df.select_dtypes(include=['float64']).apply(pd.to_numeric, downcast='float')\n df[df_float64.columns] = df_float64\n del df_float64; gc.collect()\n print (df.info(memory_usage='deep'))\n\n\ndef lgb_stacking_feature(params,trainx,trainy,testx,probe_name,topk=0,feature_names=None,cv=3,rounds=3):\n from DMF.Stacking import StackingBaseModel\n newtrain = np.zeros(shape=(trainx.shape[0],))\n newtest = np.zeros(shape=(testx.shape[0],))\n\n for _i in range(rounds):\n stack = StackingBaseModel(None, \"lgb\", params, cv, use_valid=False, random_state=2018 * _i,\n top_k_origin_feature=topk)\n stack.set_feature_names(feature_names)\n _ntest = stack.fit_transfrom(trainx, trainy, testx)\n _ntrain = stack.trainx_\n newtrain += _ntrain[:, 0]\n newtest += _ntest[:, 0]\n newtrain /= rounds\n newtest /= rounds\n topkfname = stack.topk_feature_name\n dftrain = pd.DataFrame(newtrain)\n dftest = pd.DataFrame(newtest)\n dftrain.columns = [probe_name+\"_probe\"]\n dftest.columns = [probe_name+\"_probe\"]\n df1 = pd.concat([dftrain, dftest], axis=0).reset_index(drop=True)\n if(topkfname is not None):\n newtrain2 = _ntrain[:, 1:]\n newtest2 = _ntest[:, 1:]\n dftrain2 = pd.DataFrame(newtrain2)\n dftest2 = pd.DataFrame(newtest2)\n dftrain2.columns = topkfname\n dftest2.columns = topkfname\n df2 = pd.concat([dftrain2, dftest2], axis=0).reset_index(drop=True)\n df1 = concat([df1, df2])\n return df1\n\n\ndef encode_vt(train_df, test_df, variable, target):\n col_name = \"_\".join([variable, target])\n if target != 'playing_time':\n grouped = train_df.groupby(variable, as_index=False)[target].agg({\"C\": \"size\", \"V\": \"sum\"})\n print ('start smooth')\n hyper = HyperParam(1, 1)\n C = grouped['C']\n V = grouped['V']\n hyper.update_from_data_by_moment(C, V)\n print ('end smooth')\n grouped[col_name] = (hyper.alpha + V) / (hyper.alpha + hyper.beta + C)\n grouped[col_name] = grouped[col_name].astype('float32')\n df = test_df[[variable]].merge(grouped, 'left', variable)[col_name]\n df = np.asarray(df, dtype=np.float32)\n else:\n grouped = train_df.groupby(variable, as_index=False)[target].agg({col_name: \"mean\"})\n df = test_df[[variable]].merge(grouped, 'left', variable)[col_name]\n df = np.asarray(df, dtype=np.float32) \n return df\n\nif __name__ == '__main__':\n print(cosine(np.asarray([[1, 2, 3], [2, 5, 10], [2, 4, 6]]), np.asarray([1, 2, 3])))\n print(euclidean.__name__)\n print(cosine in MAX_DIS_FUNCTION)\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":13844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"129892573","text":"'''Doc build constants'''\n\nimport os\nimport re\n\nfrom django.conf import settings\nfrom django.utils.translation import ugettext_lazy as _\n\n\nSPHINX_TEMPLATE_DIR = os.path.join(settings.SITE_ROOT, 'readthedocs',\n 'templates', 'sphinx')\nMKDOCS_TEMPLATE_DIR = os.path.join(settings.SITE_ROOT, 'readthedocs',\n 'templates', 'mkdocs')\nSPHINX_STATIC_DIR = os.path.join(SPHINX_TEMPLATE_DIR, '_static')\n\nPDF_RE = re.compile('Output written on (.*?)')\n\nDOCKER_SOCKET = getattr(settings, 'DOCKER_SOCKET', 'unix:///var/run/docker.sock')\nDOCKER_VERSION = getattr(settings, 'DOCKER_VERSION', 'auto')\nDOCKER_IMAGE = getattr(settings, 'DOCKER_IMAGE', 'rtfd-build')\nDOCKER_LIMITS = {'memory': '200m', 'time': 600}\nDOCKER_LIMITS.update(getattr(settings, 'DOCKER_LIMITS', {}))\n\nDOCKER_TIMEOUT_EXIT_CODE = 42\nDOCKER_OOM_EXIT_CODE = 137\n\nDOCKER_HOSTNAME_MAX_LEN = 64\n","sub_path":"readthedocs/doc_builder/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"53941504","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot2d(xAxis, yAxis, x, y):\n plt.scatter(x, y)\n plt.axis([min(x)-5000, max(x)+5000, min(y)-5000, max(y)+5000])\n plt.xlabel(xAxis)\n plt.ylabel(yAxis)\n plt.title(\"Pareto front: \" + xAxis + \" vs. \" + yAxis)\n\n plt.savefig(\"../Images/plots/\" + xAxis + \"_\" + yAxis)\n plt.close()\n","sub_path":"Project 3/Python/plotter2d.py","file_name":"plotter2d.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"389390896","text":"class Solution(object):\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n d = dict()\n for s in strs:\n key = ''.join(sorted(s))\n if key in d:\n d[key].append(s)\n else:\n d[key] = list()\n d[key].append(s)\n rt = list()\n for key in d:\n rt.append(d[key])\n\n return rt\n","sub_path":"49-group-anagram.py","file_name":"49-group-anagram.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"349917752","text":"from gymenv_v2 import make_multiple_env\nimport numpy as np\n\n\nimport wandb\nwandb.login()\n# run=wandb.init(project=\"finalproject\", entity=\"ieor-4575\", tags=[\"training-easy\"])\n#run=wandb.init(project=\"finalproject\", entity=\"ieor-4575\", tags=[\"training-hard\"])\n\n\n### TRAINING\n\n# Setup: You may generate your own instances on which you train the cutting agent.\ncustom_config = {\n \"load_dir\" : 'instances/randomip_n60_m60', # this is the location of the randomly generated instances (you may specify a different directory)\n \"idx_list\" : list(range(20)), # take the first 20 instances from the directory\n \"timelimit\" : 50, # the maximum horizon length is 50\n \"reward_type\" : 'obj' # DO NOT CHANGE reward_type\n}\n\n# Easy Setup: Use the following environment settings. We will evaluate your agent with the same easy config below:\neasy_config = {\n \"load_dir\" : 'instances/train_10_n60_m60',\n \"idx_list\" : list(range(10)),\n \"timelimit\" : 50,\n \"reward_type\" : 'obj'\n}\n\n# Hard Setup: Use the following environment settings. We will evaluate your agent with the same hard config below:\nhard_config = {\n \"load_dir\" : 'instances/train_100_n60_m60',\n \"idx_list\" : list(range(99)),\n \"timelimit\" : 50,\n \"reward_type\" : 'obj'\n}\n\nif __name__ == \"__main__\":\n # create env\n\n for _ in range(2):\n run=wandb.init(project=\"finalproject\", entity=\"ieor-4575\", tags=[\"test\"], reinit=True)\n env = make_multiple_env(**easy_config) \n for e in range(2):\n # gym loop\n s = env.reset() # samples a random instance every time env.reset() is called\n d = False\n t = 0\n repisode = 0\n\n while not d:\n a = np.random.randint(0, s[-1].size, 1) # s[-1].size shows the number of actions, i.e., cuts available at state s\n s, r, d, _ = env.step(list(a))\n # print('episode', e, 'step', t, 'reward', r, 'action space size', s[-1].size, 'action', a[0])\n \n A, b, c0, cuts_a, cuts_b = s\n #print(A.shape, b.shape, c0.shape, cuts_a.shape, cuts_b.shape)\n\n t += 1\n repisode += r\n wandb.log({\"Training reward\" : repisode})\n print(f'Training reward: {repisode}')\n\t\n\t#wandb logging\n\t#if using hard-config make sure to use \"training-hard\" tag in wandb.init in the initialization on top\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"240661760","text":"\"\"\"\n1281. Subtract the Product and Sum of Digits of an Integer\n==========================================================\neasy\n\nGiven an integer number n, return the difference between the product of its digits and the sum of its digits.\n\"\"\"\n\nfrom src.decorator.decorator import register\n\nfunctions = []\n\n\n@register(functions)\ndef subtract_product_and_sum(n: int) -> int:\n product, total = 1, 0\n while n:\n n, remain = divmod(n, 10)\n product *= remain\n total += remain\n return product - total\n\n\n@register(functions)\ndef subtract_product_and_sum_1(n: int) -> int:\n product, total = 1, 0\n for i in str(n):\n product *= int(i)\n total += int(i)\n return product - total\n","sub_path":"src/number/digit/subtract_a_product_and_sum_of_digits_of_an_integer.py","file_name":"subtract_a_product_and_sum_of_digits_of_an_integer.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"82740496","text":"\"\"\"\n\n Student : Shahreen Shahjahan Psyche\n Time : O(NKlogK) [Where N is the number of average elements and K is the number of LinkedList/Also the size of the heap]\n Space : O(K) [My Heap size]\n \n Pased Test Cases : Yes\n\n\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\n\n# As python's heapq does not allow me to pass the ListNode class directly, thats why I am creating a wrapper class, which matches the value with other values of\n# the heap while pushing into the heap\n\nclass Node(object):\n \n def __init__(self, val: int, node = None):\n self.val = val\n self.node = node\n\n def __repr__(self):\n return f'Node value: {self.val}'\n \n # comparing values\n def __lt__(self, other):\n return self.val < other.val\n \n def returnNode(self):\n return self.node\n \n \nclass Solution:\n def minHeap(self, lists):\n \n import heapq\n \n # this is the heap\n track = []\n # creating a dummy node for cleaner code\n dummyNode = ListNode(float('-inf'))\n head = dummyNode\n \n # first pushing all the heads of the linked lists inside the list in the heap\n for i in range(len(lists)):\n # edge case\n if not lists[i]:\n continue\n curr = Node(lists[i].val, lists[i])\n heapq.heappush(track, curr)\n \n # now in this loop, until my heap is empty it runs and one by listnode it extracts from heap, adds into the LinkedList and finally pushes the next\n # element if available inside the heap\n while track:\n curr = heapq.heappop(track)\n curr_node = curr.returnNode()\n dummyNode.next = curr_node\n if curr_node.next:\n heapq.heappush(track, Node(curr_node.next.val, curr_node.next))\n dummyNode = dummyNode.next \n \n return head.next \n \n \n \n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n \n if not lists:\n return \n \n head = self.minHeap(lists)\n \n return head\n \n \n","sub_path":"Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"644651790","text":"\n# --------------------------------------------------------------------------\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"\"Software\"\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n#\n# --------------------------------------------------------------------------\nimport pytest\nfrom azure.core.rest import HttpRequest\nfrom dpgservicedriveninitialversiontolerant import DPGClient as DPGClientInitial\nfrom dpgservicedrivenupdateoneversiontolerant import DPGClient as DPGClientUpdateOne\n\n@pytest.fixture\ndef initial_client():\n with DPGClientInitial() as client:\n yield client\n\n@pytest.fixture\ndef update_one_client():\n with DPGClientUpdateOne() as client:\n yield client\n\ndef test_add_optional_parameter_to_required(initial_client, update_one_client):\n initial_client.params.get_required(\n parameter=\"foo\"\n )\n update_one_client.params.get_required(\n parameter=\"foo\"\n )\n update_one_client.params.get_required(\n parameter=\"foo\",\n new_parameter=\"bar\",\n )\n\ndef test_add_optional_parameter_to_none(initial_client, update_one_client):\n initial_client.params.head_no_params()\n update_one_client.params.head_no_params()\n update_one_client.params.head_no_params(\n new_parameter=\"bar\"\n )\n\ndef test_add_optional_parameter_to_required_optional(initial_client, update_one_client):\n initial_client.params.put_required_optional(\n required_param=\"foo\",\n optional_param=\"bar\"\n )\n update_one_client.params.put_required_optional(\n required_param=\"foo\",\n optional_param=\"bar\"\n )\n update_one_client.params.put_required_optional(\n required_param=\"foo\",\n optional_param=\"bar\",\n new_parameter=\"baz\"\n )\n update_one_client.params.put_required_optional(\n required_param=\"foo\",\n new_parameter=\"baz\"\n )\n\ndef test_add_optional_parameter_to_optional(initial_client, update_one_client):\n initial_client.params.get_optional(\n optional_param=\"foo\"\n )\n update_one_client.params.get_optional(\n optional_param=\"foo\"\n )\n update_one_client.params.get_optional(\n optional_param=\"foo\",\n new_parameter=\"bar\"\n )\n\ndef test_add_new_content_type(initial_client, update_one_client):\n initial_client.params.post_parameters({ \"url\": \"http://example.org/myimage.jpeg\" })\n update_one_client.params.post_parameters({ \"url\": \"http://example.org/myimage.jpeg\" })\n update_one_client.params.post_parameters(b\"hello\", content_type=\"image/jpeg\")\n\ndef test_add_new_operation(initial_client, update_one_client):\n with pytest.raises(AttributeError):\n initial_client.params.delete_parameters()\n update_one_client.params.delete_parameters()\n\ndef test_add_new_path(initial_client, update_one_client):\n with pytest.raises(AttributeError):\n initial_client.params.get_new_operation()\n assert update_one_client.params.get_new_operation() == {'message': 'An object was successfully returned'}\n\ndef test_glass_breaker(update_one_client):\n request = HttpRequest(method=\"GET\", url=\"/servicedriven/glassbreaker\", params=[], headers={\"Accept\": \"application/json\"})\n response = update_one_client.send_request(request)\n assert response.status_code == 200\n assert response.json() == {'message': 'An object was successfully returned'}\n","sub_path":"packages/autorest.python/test/dpg/version-tolerant/AcceptanceTests/test_service_driven.py","file_name":"test_service_driven.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"401412561","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# =============================================================================\n\"\"\"The Following Is An Example for xattr.\n\nAnswer for: https://stackoverflow.com/q/52403922/1896134\nShowcasing a 'How-to' example.\n\"\"\"\n# =============================================================================\n\nimport xattr\n\nprint(\"{}\".format(xattr.__file__))\n# '/usr/local/lib/python3.7/site-packages/xattr/__init__.py'\n\n\ndef showww_me_the_meta(file_name):\n \"\"\"Using Python's XATTR to list Key Meta Names for File.\"\"\"\n print(\"Showing Initial Names & Values.\")\n attrz = xattr.listxattr(file_name)\n result = (\"A. Info Showcased Init: {}\".format(attrz))\n print(\"{}\".format(result))\n return result\n\n\ndef update_the_meta(file_name):\n \"\"\"Using Python's XATTR to Update Key Meta Names for File.\"\"\"\n xattr.setxattr(file_name, 'custom.comment',\n 'I tawt I taw a puddy tat!.'.encode('utf-8'))\n xattr.setxattr(file_name, 'Music.Artist',\n 'I did! '\n 'I did taw a puddy tat!'.encode('utf-8'))\n get_the_meta_values(file_name)\n return\n\n\ndef get_the_meta_values(file_name):\n \"\"\"Example Looping thru keys to get the values.\"\"\"\n print(\"B. Listing Meta for: {}\".format(file_name))\n attrz = xattr.listxattr(file_name)\n print(\"\")\n for i in reversed(attrz):\n abc = xattr.getxattr(file_name, i)\n result = (\"{} : {}\".format(i, abc))\n print(\" {}\".format(result))\n print(\"\")\n return\n\n\ndef remove_the_meta(file_name):\n \"\"\"Example of removing the keys added to the file.\"\"\"\n xattr.removexattr(file_name, 'custom.comment')\n xattr.removexattr(file_name, 'Music.Artist')\n attrz = xattr.listxattr(file_name)\n result = (\"C. Info Removed Meta: {}\".format(attrz))\n print(\"{}\".format(result))\n return result\n\n\nif __name__ == '__main__':\n showww_me_the_meta('xattr_example.py')\n update_the_meta('xattr_example.py')\n remove_the_meta('xattr_example.py')\n","sub_path":"xattr_example.py","file_name":"xattr_example.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"450251294","text":"from handlers import BaseHandler\nfrom google.appengine.ext import ndb\nfrom models import posts_key, Comment\n\nclass ShowPost(BaseHandler):\n \"\"\"show one post page.\"\"\"\n def get(self, post_id):\n post_key = ndb.Key('Post', int(post_id), parent=posts_key())\n post = post_key.get()\n comments = Comment.query() \\\n .filter(Comment.post_key == post_key) \\\n .order(-Comment.created) \\\n .fetch(10)\n if not post:\n self.error(404)\n return\n self.render(\"page-blog-post.html\",\n p=post,\n post_id=post_id,\n comments=comments)\n return\n\n","sub_path":"handlers/ShowPost.py","file_name":"ShowPost.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"594395783","text":"from rlcard.games.hearts.dealer import HeartsDealer\nfrom rlcard.games.hearts.dealer import HeartsMiniDealer\nfrom rlcard.games.hearts.player import HeartsPlayer as Player\nfrom rlcard.games.hearts.round import HeartsRound as Round\nfrom rlcard.games.hearts.utils import get_first_player\nimport copy\n\nclass HeartsGame(object):\n\n def __init__(self, allow_step_back=False, shooting_the_moon_enabled=False):\n self.allow_step_back = allow_step_back\n self.shooting_the_moon_enabled = shooting_the_moon_enabled\n self.num_players = 4\n self.payoffs = [0 for _ in range(self.num_players)]\n self.history = []\n\n self.dealer_class = HeartsDealer\n self.dealer = self.dealer_class()\n\n self.deck_size = len(self.dealer.deck)\n \n def init_game(self):\n ''' Initialize players and state\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): The first state in one game\n (int): Current player's id\n '''\n # Initalize payoffs\n self.payoffs = [0 for _ in range(self.num_players)]\n\n # Initialize a dealer that can deal cards\n self.dealer = self.dealer_class()\n\n # Initialize four players to play the game\n self.players = [Player(i) for i in range(self.num_players)]\n\n # Deal all cards to each player to prepare for the game\n self.dealer.deal_cards(self.players)\n \n first_player = get_first_player(self.players)\n\n self.round = Round(self.dealer, self.num_players, first_player)\n\n # Save the hisory for stepping back to the last state.\n self.history = []\n\n self.card_played_in_game = []\n\n player_id = self.round.current_player\n state = self.get_state(player_id)\n return state, player_id\n\n def step(self, action):\n ''' Get the next state\n\n Args:\n action (str): A specific action\n\n Returns:\n (tuple): Tuple containing:\n\n (dict): next player's state\n (int): next plater's id\n '''\n\n if self.allow_step_back:\n # First snapshot the current state\n his_dealer = copy.deepcopy(self.dealer)\n his_round = copy.deepcopy(self.round)\n his_players = copy.deepcopy(self.players)\n self.history.append((his_dealer, his_players, his_round))\n\n self.round.proceed_round(self.players, action)\n\n if self.is_over():\n if self.allow_step_back:\n # First snapshot the current state\n his_dealer = copy.deepcopy(self.dealer)\n his_round = copy.deepcopy(self.round)\n his_players = copy.deepcopy(self.players)\n self.history.append((his_dealer, his_players, his_round))\n\n player_id = self.round.current_player\n state = self.get_state(player_id)\n return state, player_id\n\n def step_back(self):\n ''' Return to the previous state of the game\n\n Returns:\n (bool): True if the game steps back successfully\n '''\n if not self.history:\n return False\n self.dealer, self.players, self.round = self.history.pop()\n return True\n\n def get_state(self, player_id):\n ''' Return player's state\n\n Args:\n player_id (int): player id\n\n Returns:\n (dict): The state of the player\n '''\n state = self.round.get_state(self.players, player_id)\n return state\n\n def get_payoffs(self):\n ''' Return the payoffs of the game \n (negative scores of each player)\n \n Returns:\n (list): Each entry corresponds to the payoff of one player\n '''\n for idx in range(len(self.players)):\n player = self.players[idx]\n for card in player.collected:\n if card.suit == 'H':\n self.payoffs[idx] -= 1\n elif (card.suit == 'S' and card.rank == 'Q'):\n self.payoffs[idx] -= (self.__class__.get_action_num() / 4)\n if self.shooting_the_moon_enabled:\n if self.payoffs[idx] == -26: # Shooting the moon\n self.payoffs[idx] = 0\n for idx2 in range(len(self.players)):\n if not idx2 == idx:\n self.payoffs[idx2] = -26\n return self.payoffs\n return self.payoffs\n\n def get_legal_actions(self):\n ''' Return the legal actions for current player\n\n Returns:\n (list): A list of legal actions\n '''\n\n return self.round.get_legal_actions(self.players, self.round.current_player)\n\n def get_player_num(self):\n ''' Return the number of players in Hearts\n\n Returns:\n (int): The number of players in the game\n '''\n return self.num_players\n\n @staticmethod\n def get_action_num():\n ''' Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 52 (size of deck) actions\n '''\n return 52\n\n def get_player_id(self):\n ''' Return the current player's id\n\n Returns:\n (int): current player's id\n '''\n return self.round.current_player\n\n def is_over(self):\n ''' Check if the game is over\n\n Returns:\n (boolean): True if the game is over\n '''\n return self.round.is_over\n\n\nclass HeartsMiniGame(HeartsGame):\n def __init__(self, allow_step_back=False):\n super().__init__(allow_step_back)\n self.dealer_class = HeartsMiniDealer\n self.dealer = self.dealer_class()\n\n @staticmethod\n def get_action_num():\n ''' Return the number of applicable actions\n\n Returns:\n (int): The number of actions. There are 52 (size of deck) actions\n '''\n return 8\n\n\n\n# Done\n\n## For test\nimport numpy as np\nif __name__ == '__main__':\n #import time\n #random.seed(0)\n #start = time.time()\n game = HeartsGame()\n for _ in range(1):\n state, button = game.init_game()\n print(button, state)\n i = 0\n while not game.is_over():\n i += 1\n legal_actions = game.get_legal_actions()\n print('legal_actions', legal_actions)\n action = np.random.choice(legal_actions)\n print('action', action)\n print()\n state, button = game.step(action)\n print(button, state)\n print(game.get_payoffs())\n print('step', i)\n","sub_path":"rlcard/games/hearts/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"619987669","text":"import ADS.MergeSortRecursive\n\n\nclass MergeSortInterative(ADS.MergeSortRecursive.MergeSortRecursive):\n def merge_sort(self, list_, left, right):\n\n \"\"\"\n Iterative version of the Merge Sort Algorithm\n \"\"\"\n factor = 2\n temp_mid = 0\n # Main loop to iterate over the array by 2^n.\n while 1:\n index = 0\n left = 0\n right = len(list_) - (len(list_) % factor) - 1\n mid = (factor / 2) - 1\n\n # Auxiliary array to merge subdivisions\n while index < right:\n temp_left = index\n temp_right = temp_left + factor - 1\n mid2 = (temp_right + temp_left) / 2\n self.merge(list_, temp_left, mid2, temp_right)\n index = (index + factor)\n\n # Chek if there is something to merge from the remaining\n # Sub-array created by the factor\n if len(list_) % factor and temp_mid != 0:\n # merge sub array to later be merged to the final array\n self.merge(list_, right + 1, temp_mid, len(list_) - 1)\n # Update the pivot\n mid = right\n # Increase the factor\n factor = factor * 2\n temp_mid = right\n\n # Final merge, merge subarrays created by the subdivision\n # of the factor to the main array.\n if factor > len(list_):\n mid = right\n right = len(list_) - 1\n self.merge(list_, 0, mid, right)\n break\n\n\n# obj = MergeSortInterative()\n# obj.test(8)\n\n","sub_path":"ADS/Sorting.py","file_name":"Sorting.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"384012367","text":"#!/usr/bin/python3\n###!/usr/bin/env python3\n'''\n#Created on Jul 13, 2015\n\n#@author: gwa\n'''\nimport re\nimport shutil\nimport sys\n\n# extract version and HF number for archive name\ndef nameit(version): \n regex1 = re.compile(r'(\\d\\.){1,2}\\d{1,}')\n regex2 = re.compile(r'(hf)(?i)\\d')\n regex3 = re.compile(r'(P\\d{1,2})(?i)')\n v1 = (regex1.search(version)).group(0) # extract formatted version\n x2 = regex2.search(version) # extract hf number, if available\n x3 = regex3.search(version) # extract patch number, if available\n v2 = v3 = '0' \n if x2:\n v2 = (x2.group(0)).lstrip(r'HF')\n if x3:\n v3 = (x3.group(0)).lstrip(r'P')\n return (v1, v2, v3) \n \ndef get_arc_name(version,buildnum):\n \n components = {'hpux':'Applications.Manager_AM.Image_',\n 'solaris':'Applications.Manager_AM.Image_',\n 'guides':'Applications.Manager_Documentation_Guides_',\n 'relnotes':'Applications.Manager_Documentation_Release.Notes_'}\n \n subcomponents = {'8':{'hpux':'HPUX_HPIA64_HPVMS_LINUX_WINDOWS',\n 'solaris':'SOLARIS_AIX_LINUX_WINDOWS'},\n '9':{'hpux':'HPIA64.LINUX.WINDOWS',\n 'solaris':'SOLARIS.AIX.LINUX.WINDOWS'}}\n\n ver, hf, p = nameit(version) # extract version, patch and hotfix numbers\n \n pat1 = re.compile(r'^[8,9]') # is this AM 8 or AM 9?\n vmajor = (pat1.match(ver)).group(0)\n \n pat2 = re.compile(r'.*?trunk')\n if pat2.match(version) :\n print(\"do not zip for trunk builds\")\n exit()\n \n suffix='_'\n if vmajor == '8':\n suffix += ver + '_' + p\n else:\n suffix += ver.replace('.', '_')\n suffix += '_' + hf\n suffix += '+build.' + buildnum #+ '.zip'\n \n subcomps = 'hpux', 'solaris' # ,'guides','relnotes'\n dirname = r'/chasm/nt4_e/invent/NT' + version \n arcnames={}\n for subcomp in subcomps:\n arcname = dirname + '/' + components[subcomp] + subcomponents[vmajor][subcomp] + suffix \n rootdir = dirname + '/' + subcomponents[vmajor][subcomp]\n shutil.make_archive(arcname, 'zip', rootdir)\n arcnames[subcomp]=arcname\n\n return arcnames\n \nif __name__ == '__main__':\n\n v=sys.argv[1] # version (branch)\n b=sys.argv[2] # build number \n arcnames = get_arc_name(v,b)\n\n print (arcnames['hpux']+'.zip',arcnames['solaris']+'.zip',sep='\\n')\n","sub_path":"specific/AMBldZip.py","file_name":"AMBldZip.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"566787495","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n\nyears = ['2013','2014','2015','2016','2017','2018']\nquarters = ['Q1','Q2','Q3','Q4']\ncustomers = ['Elec- Agricultural','Elec- Commercial','Elec- Industrial','Elec- Residential']\ncount = 0\n\nfor y in years:\n \n # there is no data yet for 2018 quarter 4\n if y == '2018':\n quarters = ['Q1','Q2','Q3']\n \n for q in quarters:\n \n # store the name of the .csv file we want to open\n filename = 'PGE_' + y + '_' + q + '_ElectricUsageByZip.csv'\n \n # import the specified filename, store in pandas DataFrame format\n # thousands = ',' is to get rid of the commas in the spreadsheet numbers\n # header = 0 signifies that the first row should be considered column\n # titles (headers)\n df_data = pd.read_csv(filename,thousands=',',header=0)\n \n # what quarter is it?\n q_index = quarters.index(q)\n \n # column titles switch to uppercase in 2016 Q3\n # this allows the code to adapt to the change\n isCapital = False\n if int(y) >= 2017 or (y == '2016' and q == 'Q3') or (y == '2016' and q == 'Q4'):\n isCapital = True\n \n # look at the three months in this quarter\n for m in range(1,4):\n \n # add 3 if it's quarter 2, 6 if it's quarter 3, etc.\n month = m + q_index*3 \n \n # empty array to store our data for each month\n output = [int(y),month]\n \n # select only the data in the specified month\n if isCapital:\n month_data = df_data[df_data['MONTH']==month]\n else:\n month_data = df_data[df_data['Month']==month]\n \n # look at the different customer classes\n for c in customers:\n \n # select only the data for the specified customer class\n if isCapital:\n customer_data = month_data[month_data['CUSTOMERCLASS'] == c]\n else:\n customer_data = month_data[month_data['CustomerClass'] == c]\n \n # calculate total electricity demand for that month/customer class\n # combination\n if isCapital:\n total = np.sum(customer_data.loc[:,'TOTALKWH'])\n else:\n total = np.sum(customer_data.loc[:,'TotalkWh'])\n \n # add on total to output row vector\n output = np.append(output,total)\n \n # store row vector\n if count < 1:\n O = output\n else:\n O = np.vstack((O,output))\n \n count = count + 1\n \n print(output)\n\ndf_O = pd.DataFrame(O)\ndf_O.columns = ['Year','Month','Agriculture','Commercial','Industrial','Residential']\ndf_O.to_csv('Monthly_consumption_by_class.csv')\n \n","sub_path":"usage_by_class.py","file_name":"usage_by_class.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"175740984","text":"import allure\nimport json\nfrom tools.report import log_tool\nfrom tools.data import string_tool\nfrom tools.report import assert_tool\n# 项目根目录建config包,里面建conf.py文件,用于配置\nfrom config import conf\nfrom tools.data.json_path_tool import *\n\n# log decorator\ndef logs(func):\n def _func(*args, **kwargs):\n r= func(*args, **kwargs)\n request = \"-------------------request-------------\" \\\n \"\\n{0}\\n{1}\\n{2}\".format(r.url, string_tool.dic_to_str(r.request.headers), r.request.body)\n log_tool.info(request)\n response = \"---------------response----------------\" \\\n \"\\n{0}\\n{1}\\n{2}\".format(r.status_code, string_tool.dic_to_str(r.headers), r.text)\n log_tool.info(response)\n allure.attach(request,'request',allure.attachment_type.TEXT)\n allure.attach(response, 'response', allure.attachment_type.TEXT)\n return r\n return _func\n\n\n\n# screenshot decorator\ndef shot(func):\n def function(*args, **kwargs):\n allure.attach(args[0].driver.get_screenshot_as_png(), args[1] + '之前', allure.attachment_type.PNG)\n i = 1\n res = None\n while(i <= 3):\n try:\n res = func(*args, **kwargs)\n break\n except :\n if i == 3:\n allure.attach(args[0].driver.get_screenshot_as_png(), args[1] + '之后', allure.attachment_type.PNG)\n raise\n i += 1\n allure.attach(args[0].driver.get_screenshot_as_png(), args[1] + '之后', allure.attachment_type.PNG)\n return res\n return function\n\n\ndef is_empty(a):\n if isinstance(a,int) or not a:\n return True\n elif(isinstance(a,str) and len(a)==0):\n return True\n return False\n\n\n\ndef datas(func):\n def function(*args,**kwargs):\n data=kwargs.pop(\"pub_data\")\n d = kwargs\n keys = list(kwargs.keys())\n for k in ['json_data','json']:\n if k in keys :\n keys.remove(k)\n value = d.pop(k)\n if (isinstance(value, str)):\n d['json'] = json.loads(value)\n else:\n d['json']=value\n with allure.step(\"第一步:获取url\"):\n pass\n if 'uri' in keys:\n keys.remove('uri')\n value = d.pop('uri')\n d['url'] = value\n for k in [\"feature\",'story','tag','testcase','description','title','issue','link','mro','severity']:\n if k in keys:\n keys.remove(k)\n value = d.pop(k)\n if not is_empty(value) and isinstance(value,list):\n getattr(allure.dynamic, k)(*value)\n elif(not is_empty(value) and isinstance(value,str)):\n getattr(allure.dynamic, k)(value)\n with allure.step(\"第二步:准备测试数据\"):pass\n try:\n index_dic(data, data)\n index_dic(d,data)\n except:\n print(\"数据转换失败\")\n raise\n if \"url\" not in keys:\n print(\"请输入正确的uri\")\n if 'http://' not in d[\"url\"]:\n d[\"url\"] = conf.API_URL + d[\"url\"]\n for s in [\"status_code\",'expect',\"json_path\"]:\n if s in keys:\n keys.remove(s)\n exec(\"{} = d.pop(s)\".format(s))\n\n else:\n exec(\"{}=None\".format(s))\n with allure.step(\"第三步:发送请求\"):\n resp = func(*args,**kwargs)\n try:\n exec('''\nif(len(json_path) != 0):\n for path in json_path:\n get_json_data(resp.json(),path,data)''')\n\n except:\n pass\n a = '''\nif not is_empty(status_code): \n # 判断响应码\n allure.attach(\"预期结果:{}\\\\n------------------------------------------------------\\\\n实际结果:{}\".format(status_code, resp.status_code), \"响应状态码断言\", allure.attachment_type.TEXT)\n assert_tool.assert_equal(resp.status_code, status_code)\nif not is_empty(expect):\n # 判断响应码\n allure.attach(\"预期结果:{}\\\\n------------------------------------------------------\\\\n实际结果:{}\".format(expect, resp.text), \"响应正文断言\", allure.attachment_type.TEXT)\n assert_tool.assert_in(resp.text, expect)'''\n with allure.step(\"第四步:判断结果\"):\n exec(a)\n\n return resp\n return function\n\n\n\n\n\n","sub_path":"tools/report/decorators_tool.py","file_name":"decorators_tool.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"325075353","text":"import csv\r\nfrom pathlib import Path\r\nfrom typing import List\r\nfrom bisect import bisect_left\r\nfrom dataclasses import dataclass\r\n\r\nclass LookupTable:\r\n\r\n def __init__(self, file_name: str):\r\n self.file_name = file_name\r\n\r\n def get_column(self, name: str) -> List[float]:\r\n \"\"\"\r\n Get all data in a column\r\n :param name: Name of the column\r\n :return: List of float values in the column\r\n \"\"\"\r\n data_folder = Path(__file__).absolute().parent\r\n file = open(data_folder / self.file_name)\r\n reader = csv.DictReader(file)\r\n return [float(row[name]) for row in reader]\r\n\r\n @staticmethod\r\n def find_index(column: List[float], value: float) -> int:\r\n return bisect_left(column, value, hi=len(column) - 1)\r\n\r\n\r\n@dataclass\r\nclass LookupSimulationResult:\r\n speed_reached: float\r\n time_passed: float = 0.0\r\n distance_traveled: float = 0.0\r\n\r\n\r\nclass KinematicsLookupTable(LookupTable):\r\n\r\n def __init__(self, file_name: str):\r\n super().__init__(file_name)\r\n self.distances = self.get_column('player0_loc_y')\r\n self.times = self.get_column('time')\r\n self.speeds = self.get_column('player0_vel_y')\r\n assert self.distances\r\n assert self.times\r\n assert self.speeds\r\n\r\n # shift times so that it starts at 0\r\n t0 = self.times[0]\r\n for i in range(len(self.times)):\r\n self.times[i] -= t0\r\n\r\n def simulate_until_limit(self,\r\n initial_speed: float,\r\n time_limit: float = None,\r\n distance_limit: float = None,\r\n speed_limit: float = None) -> LookupSimulationResult:\r\n\r\n # atleast one limit must be set\r\n assert time_limit or distance_limit or speed_limit\r\n\r\n # limits must be positive\r\n if time_limit:\r\n assert time_limit > 0\r\n if speed_limit:\r\n assert speed_limit > 0\r\n if distance_limit:\r\n assert distance_limit > 0\r\n\r\n assert not speed_limit or speed_limit > initial_speed\r\n\r\n starting_index = self.find_index(self.speeds, initial_speed)\r\n # TODO: Interpolate\r\n initial_time = self.times[starting_index]\r\n initial_distance = self.distances[starting_index]\r\n\r\n\r\n final_indexes = []\r\n\r\n if time_limit:\r\n index = self.find_index(self.times, initial_time + time_limit)\r\n final_indexes.append(index)\r\n\r\n if distance_limit:\r\n index = self.find_index(self.distances, initial_distance + distance_limit)\r\n final_indexes.append(index)\r\n\r\n if speed_limit:\r\n index = self.find_index(self.speeds, speed_limit)\r\n final_indexes.append(index)\r\n\r\n final_index = min(final_indexes) # use the soonest reached limit\r\n\r\n # TODO: Interpolate values\r\n return LookupSimulationResult(self.speeds[final_index],\r\n self.times[final_index] - initial_time,\r\n self.distances[final_index] - initial_distance)\r\n\r\n \r\n\r\nBOOST_LUT = KinematicsLookupTable('boost.csv')\r\nTHROTTLE_LUT = KinematicsLookupTable('throttle.csv')","sub_path":"data/lookup_tables.py","file_name":"lookup_tables.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"280064808","text":"import kaizen.rules\n\nclass Gnupg(kaizen.rules.ConfigureRules):\n\n url = \"ftp://ftp.gnupg.org/gcrypt/gnupg/gnupg-2.0.18.tar.bz2\"\n hash = { \"md5\" : \"2f37e0722666a0fedbe4d9f9227ac4d7\",\n \"sha1\" : \"5ec2f718760cc3121970a140aeea004b64545c46\" }\n version = \"2.0.18\"\n name = \"gnupg\"\n\n depends = [\"libgpg-error\",\n \"libassuan\",\n \"pinentry\",\n \"libgcrypt\",\n \"libksba\",\n \"pth\",\n \"gettext\",\n \"zlib\",\n \"libiconv\",\n \"bzip2\",\n \"curl\",\n \"dirmngr\",\n ]\n","sub_path":"gnupg2/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"68488082","text":"import logging\nimport pymorphy2\nimport random\nimport string\n\nfrom django.contrib.auth.models import User\n\n\ndef get_logger(name):\n\n return logging.getLogger(name)\n\n\ndef word_gent(word):\n\n morph = pymorphy2.MorphAnalyzer()\n\n objects = morph.parse(word)\n\n if len(objects) > 1:\n objects.sort(key=lambda it: len(it.normal_form), reverse=True)\n\n objectt = objects[0]\n\n inflected_result = objectt.inflect({'gent'})\n if inflected_result:\n inflected = inflected_result.word\n\n if word[0].isupper():\n inflected = inflected.capitalize()\n\n return inflected\n return word\n\n\ndef get_staff_ids(exclude=None):\n\n assert exclude is None or isinstance(exclude, list), 'Exclude must be list'\n\n users = User.objects.filter(is_staff=True)\n ids = set()\n\n if len(users) > 0:\n ids.update([it.id for it in users])\n\n if exclude is not None:\n ids = ids - set(exclude)\n\n return list(ids)\n\n\ndef translit(string):\n\n dic = {\n 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'e',\n 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm',\n 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',\n 'ф': 'f', 'х': 'h', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'sch', 'ь': '',\n 'ы': 'y', 'ъ': '', 'э': 'e', 'ю': 'ju', 'я': 'ja', 'a': 'а', 'b': 'б',\n 'c': 'ц', 'd': 'д', 'e': 'е', 'f': 'ф', 'g': 'г', 'h': 'х', 'i': 'и',\n 'j': 'й', 'k': 'к', 'l': 'л', 'm': 'м', 'n': 'н', 'o': 'о', 'p': 'п',\n 'q': 'q', 'r': 'р', 's': 'с', 't': 'т', 'u': 'у', 'v': 'в', 'w': 'w',\n 'x': 'x', 'y': 'ы', 'z': 'з'\n }\n\n result = ''\n\n for letter in string:\n result += dic.get(letter, letter)\n\n return result\n\n\ndef random_string(length):\n\n return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))\n","sub_path":"app/judge/api/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"99479109","text":"import math\nimport webbrowser\n\ndef menu():\n \"\"\"A function that simply prints the menu\"\"\"\n print()\n print('(0) Input a new list')\n print('(1) Print the current list')\n print('(2) Find the average price')\n print('(3) Find the standard deviation')\n print('(4) Find the minimum and its day')\n print('(5) Find the maximum and its day')\n print('(6) Your TT investment plan')\n print('(9) Quit')\n print()\n\ndef add(L):\n \"\"\"sum of a list\"\"\"\n added = 0\n if len(L) == 0:\n return 0\n else:\n for x in L:\n added = added + x\n return added\n\ndef avg(L):\n \"\"\"average of a list\"\"\"\n return add(L)/len(L)\n\ndef var(L):\n \"\"\"finds the variance of a list\"\"\"\n LC = [(x-avg(L))**2 for x in L]\n return avg(LC)\n\ndef standev(L):\n \"\"\"returns the standard deviation of list of numbers L\"\"\"\n return math.sqrt(var(L))\n\ndef find_min(L):\n \"\"\"min(L)\"\"\"\n result = L[0]\n for x in L:\n if x < result:\n result = x\n return result\n\ndef find_min_loc(L):\n \"\"\"returns the minimum of L\n and the location/index/day of that minimum.\n Argument L: a nonempty list of numbers.\n Results: the smallest value in L, its location (index)\n \"\"\"\n minval = L[0]\n minloc = 0\n\n for i in list(range(len(L))):\n if L[i] < minval: # a smaller one was found!\n minval = L[i]\n minloc = i\n\n return minval, minloc\n\ndef find_max(L):\n \"\"\"max(L)\"\"\"\n result = L[0]\n for x in L:\n if x > result:\n result = x\n return result\n\ndef find_max_loc(L):\n \"\"\"max(L) and the location/index/day of that maximum.\n Argument L: a nonempty list of numbers.\n Results: the max value of L, its location (index)\n \"\"\"\n maxval = L[0]\n maxloc = 0\n\n for i in list(range(len(L))):\n if L[i] > maxval:\n maxval = L[i]\n maxloc = i\n\n return maxval, maxloc\n\ndef maxsofar(L):\n \"\"\"goes through a list and finds the max so far\"\"\"\n maxval = L[0]\n maxloc = 0\n for i in range(len(L)):\n if L[i] >= maxval:\n maxval = L[i]\n maxloc = i\n return maxloc\n\ndef tts(L):\n \"\"\"determines best days to buy stocks based on the smallest value \n that is followed by the largest value for maximum profit\"\"\"\n maxloc = maxsofar(L)\n optsellday = 0\n optbuyday = 0\n for b in list(range(len(L))):\n for s in list(range(len(L))):\n profit = L[b]-L[s]\n if profit == maxloc:\n optsellday = s\n optbuyday = b\n return optbuyday, optsellday\n\ndef main():\n \"\"\"The main user-interaction loop\"\"\"\n\n L = [] # an initial list\n\n while True: # the user-interaction loop\n print(\"\\n\\nThe list is\", L)\n menu()\n choice = input(\"Choose an option: \")\n\n # \"Clean and check\" the user's input\n try:\n choice = int(choice) # make into an int!\n except:\n print(\"Unacceptable input. Try again.\")\n continue\n\n # run the appropriate menu option\n if choice == 9: # quit\n break # Leaves the while loop altogether\n\n elif choice == 0: # enter a new list\n newL = input(\"Enter a new list: \") # enter _something_\n \n # \"Clean and check\" the user's input\n try: \n newL = eval(newL) # eval runs Python's interpreter! Note: Danger!\n if type(newL) != type([]): \n print(\"That didn't seem like a list. Not changing L.\")\n else: \n L = newL # Here, things were OK, so let's set our list, L\n except:\n print(\"Syntax error. Not changing L.\")\n\n elif choice == 1: # print current list\n print(\"The current list is \", L)\n\n elif choice == 2: # average price of list\n if len(L) == 0:\n print(0)\n else:\n print('The average is ', avg(L))\n\n elif choice == 3: # standard deviation\n if len(L) == 0:\n print(0)\n else:\n print('The standard deviation is', standev(L))\n\n elif choice == 4: # minimum and corresponding day\n if len(L) == 0:\n print(0)\n else:\n minval, minloc = find_min_loc(L)\n print(\"The minimum value in L is\", minval, \", which occurs on day\", minloc)\n\n elif choice == 5: # maximum and corresponding day\n if len(L) == 0:\n print(0)\n else:\n maxval, maxloc = find_max_loc(L)\n print(\"The maximum value in L is\", maxval, \", which occurs on day\", maxloc)\n \n elif choice == 6: # investment plan\n optminday = 0\n optmaxday = 0\n minval, minloc = find_min_loc(L)\n maxval, maxloc = find_max_loc(L)\n optbuyday, optsellday = tts(L)\n if len(L) == 0:\n print(0)\n elif minloc < maxloc: # if the regular min occurs before the regular max\n optbuyday = minloc\n optsellday = maxloc\n else:\n optbuyday = optbuyday\n optsellday = optsellday\n\n print('You should buy on day', optbuyday, 'and sell on day', optsellday)\n\n else:\n webbrowser.open_new_tab('https://www.youtube.com/watch?v=Jk6jVl1fAn0')\n print(\"That's not on the menu!\")\n\n print()\n print(\"Session ended\")","sub_path":"hw9pr4.py","file_name":"hw9pr4.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"350226741","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"write2DB\")\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\nfrom CondCore.CondDB.CondDB_cfi import *\n\n#################################\n# Produce a SQLITE FILE\n#\nCondDBBeamSpotObjects = CondDB.clone(connect = cms.string('sqlite_file:test.db')) # choose an output name\n\n#################################\n#\n# upload conditions to orcon\n#\n#process.CondDBCommon.connect = \"oracle://cms_orcoff_prep/CMS_COND_BEAMSPOT\"\n#process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')\n#process.GlobalTag.globaltag = 'MC_31X_V2::All'\n\n#################################\n\nprocess.PoolDBOutputService = cms.Service(\"PoolDBOutputService\",\n #process.CondDBCommon,\n CondDBBeamSpotObjects,\n timetype = cms.untracked.string('lumiid'), #('lumiid'), #('runnumber')\n toPut = cms.VPSet(cms.PSet(\n record = cms.string('BeamSpotOnlineHLTObjectsRcd'), # BeamSpotOnlineHLT record\n tag = cms.string('BSHLT_tag') )), # choose your favourite tag\n loadBlobStreamer = cms.untracked.bool(False)\n)\n\nprocess.source = cms.Source(\"EmptySource\")\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(1)\n )\n\nprocess.beamspotonlinewriter = cms.EDAnalyzer(\"BeamSpotOnlineHLTRcdWriter\",\n InputFileName = cms.untracked.string('../data/BeamFitResults_Run306171.txt'), # choose your input file\n #IOVStartRun = cms.untracked.uint32(306171), # Customize your Run\n #IOVStartLumi = cms.untracked.uint32(497), # Customize your Lumi\n )\n\nprocess.p = cms.Path(process.beamspotonlinewriter)","sub_path":"CondTools/BeamSpot/test/BeamSpotOnlineHLTRcdWriter_cfg.py","file_name":"BeamSpotOnlineHLTRcdWriter_cfg.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"437939705","text":"import csv\nfrom Algo_Class import *\n\nDIR = r'D:\\Data'\nInputFile = DIR + r'\\data1.csv'\ncsv_reader = csv.reader(open(InputFile, 'r'))\n\nkf_writer = csv.writer(open(DIR + r'\\kf.csv', 'w', newline=''))\nsins_writer = csv.writer(open(DIR + r'\\sins.csv', 'w', newline=''))\nrt_writer = csv.writer(open(DIR + r'\\rt.csv', 'w', newline=''))\n\ntimu = 0\nts = 0.01\n\n# 读取数据\nindex = 0\ndatas = []\nfor row in csv_reader:\n if index == 0:\n index += 1\n continue\n else:\n datas.append(list(map(float, row)))\n\ngpspos = np.array([[34.196255 * pa.deg], [108.875677 * pa.deg], [410.70]])\nkf = CKalman(15, 6)\nkf.Init16(CSINS(A2Q(np.array([[-0.821], [3.690], [6.960]]) * pa.deg), np.array([[0.0], [0.0], [0.0]]), gpspos, timu))\n\nfor (data, i) in zip(datas, range(len(datas))):\n timu = data[0]\n wm = np.array([[data[1]], [data[2]], [data[3]]])\n vm = np.array([[data[4]], [data[5]], [data[6]]])\n wm = wm * pa.dps * ts\n vm = vm * ts\n if data[19] > 0 and timu > 60:\n gpsvn = np.array([[data[16]], [data[17]], [data[18]]])\n gpspos = np.array([[data[19]], [data[20]], [data[21]]])\n gpspos[0, 0] *= pa.deg\n gpspos[1, 0] *= pa.deg\n kf.SetMeas(gpsvn, gpspos, timu)\n\n #kf.TDUpdate([wm], [vm], 1, ts, 10)\n kf.Update([wm], [vm], 1, ts)\n\n #print(kf.sins.pos[0, 0], kf.sins.pos[1, 0], kf.sins.pos[2, 0])\n kf_in = kf.Xk.flatten().tolist()[0]\n for j in range(kf.Pk.shape[0]):\n kf_in.append(kf.Pk[j, j])\n kf_in.append(kf.kftk)\n kf_writer.writerow(kf_in)\n\n sins_in = kf.sins.att.flatten().tolist()\n sins_in += kf.sins.vn.flatten().tolist()\n sins_in += kf.sins.pos.flatten().tolist()\n sins_in += kf.sins.eb.flatten().tolist()\n sins_in += kf.sins.db.flatten().tolist()\n sins_in.append(kf.sins.tk)\n sins_writer.writerow(sins_in)\n\n rt_in = kf.Rt.flatten().tolist()\n rt_writer.writerow(rt_in)\n\n if i % 1000 == 0:\n print(str(i/100))\n","sub_path":"PSINS_KEIL1.43/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"351731235","text":"from django.conf.urls import url\r\nfrom django.contrib import admin\r\nfrom django.urls import path\r\nfrom . import views\r\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\r\nurlpatterns = [\r\n path('index', views.index),\r\n path('register', views.register),\r\n path('do_register', views.do_register),\r\n path('login', views.login),\r\n path('do_login', views.do_login),\r\n path('logout', views.logout),\r\n path('prediction', views.prediction),\r\n path('user', views.user),\r\n path('modify', views.modify),\r\n path('users', views.users),\r\n path('remove_user', views.remove_user),\r\n]\r\nurlpatterns+=staticfiles_urlpatterns()","sub_path":"spark_web/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"614381530","text":"from graph import Graph\n\ndef constuct_path(u, v, visited):\n \"\"\"Construct the path b/n two vertices, given DFS tree vertices and edges\"\"\"\n path = []\n if v in visited:\n path.append(v)\n w = v\n \"\"\"Follow the edge-vertice-edge .. till u is reached\"\"\"\n while w is not u:\n e = visited[w]\n w1 = e.other(w)\n path.append(w1)\n w = w1\n path.reverse()\n return path\n\ndef dfs(g, u, visited):\n \"\"\"DFS for graph g, starting with vertex u\"\"\"\n #print(\"Visiting: \", u.element())\n for e in g.incident_edges(u):\n v = e.other(u)\n if v not in visited:\n #print(\"Discovering vertex:\", v.element(), \" through the edge:\", e.element())\n visited[v] = e\n dfs(g, v, visited)\n return visited\n\ndef construct_graph(file_path):\n \"\"\"Construct the graph from the file which contain the edges\"\"\"\n f = open(file_path, \"r\")\n\n graph = Graph()\n\n vertices = {} #Collect vertices in this dictonary\n\n #Each line in the file is an edge\n for line in f:\n u_val, v_val = line.split()\n if u_val not in vertices:\n u = graph.add_vertex(u_val) #Add the vertex u to the graph, if it's not in it yet\n vertices[u_val] = u\n else:\n u = vertices[u_val]\n\n if v_val not in vertices:\n v = graph.add_vertex(v_val) #Add the vertex v ...\n vertices[v_val] = v\n else:\n v = vertices[v_val]\n\n\n name = u_val+\"_\"+v_val\n graph.add_edge(u, v, name) #Add the new edge to the graph\n\n # Return the newly minted graph\n return graph, vertices\n\nif __name__ == \"__main__\":\n \"\"\"Drives the creation of graph, run DFS and connectivity b/n two vertices\"\"\"\n g, vertices = construct_graph(\"dfs_graph.txt\")\n g.show()\n\n visited = {}\n visited[vertices['0']] = None #Starting vertex is trivially discovered\n visited = dfs(g, vertices['0'], visited) #Run DFS and return the DFS tree\n\n u = vertices['0']\n v = vertices['6']\n path = constuct_path(u, v, visited) #Construct path between two vertices\n\n for u in path:\n print(u.element(), end=\" \")\n print()\n","sub_path":"graphs/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"454990344","text":"from scipy.integrate import odeint\r\nimport numpy as np\r\nfrom leer_eof import leer_eof,utc2time\r\nimport matplotlib.pylab as plt\r\nfrom time import perf_counter\r\n\r\ng = 6.6740831*(10**-11) #Nm**2/k**2\r\nm_t = 5.98*(10**24) #Kg masa tierra\r\nr_atmosfera = (6371 + 80)*1000 #metros\r\nkm = 1000\r\nR_tierra = 6371.*km\r\n\r\nhr = 3600 #2 dias en segundos\r\nomega = (2*np.pi)/(24*3600) #2*Pi/24 horas en segundos\r\n\r\n\r\n\r\n\r\ndef satelite(z,t):\r\n \r\n #Matriz de rotación\r\n R = np.array([[np.cos(omega*t), -np.sin(omega*t), 0], [np.sin(omega*t), np.cos(omega*t), 0], [0, 0, 1]])\r\n\r\n #Primera derivada de R\r\n dR_dt = np.array([[-np.sin(omega*t), -np.cos(omega*t), 0], [np.cos(omega*t), -np.sin(omega*t), 0], [0, 0, 0]])*(omega)\r\n\r\n #Segunda derivada de R\r\n dR_dt2 = np.array([[-np.cos(omega*t), np.sin(omega*t), 0], [-np.sin(omega*t), -np.cos(omega*t), 0], [0, 0, 0]])*(omega**2)\r\n \r\n z1 = z[0:3]\r\n r2 = np.dot(z1,z1)\r\n r = np.sqrt(r2)\r\n \r\n J2 = 1.75553*(10**10)*1000**5\r\n \r\n X_J2 = J2*(z[0]/r**7)* (6*z[2]**2-3/2*(z[0]**2+z[1]**2))\r\n Y_J2 = J2*(z[1]/r**7)* (6*z[2]**2-3/2*(z[0]**2+z[1]**2))\r\n Z_J2 = J2*(z[2]/r**7)* (3*z[2]**2-9/2*(z[0]**2+z[1]**2))\r\n J_2 = np.array([X_J2,Y_J2,Z_J2])\r\n \r\n J3 = -2.61913*(10**11)*1000**6\r\n \r\n X_J3 = J3*z[0]*z[2]/r**9* (10*z[2]**2-15/2*(z[0]**2+z[1]**2))\r\n Y_J3 = J3*z[1]*z[2]/r**9* (10*z[2]**2-15/2*(z[0]**2+z[1]**2))\r\n Z_J3 = J3/r**9* (4*z[2]**2*(z[2]**2-3*(z[0]**2+z[1]**2))+3/2*(z[0]**2 + z[1]**2)**2)\r\n J_3 = np.array([X_J3,Y_J3,Z_J3])\r\n \r\n zp = np.zeros(6)\r\n zp[0:3] = z[3:6]\r\n z2 = ((-g*m_t)/(r**3))*z[0:3] - R.T@(dR_dt2@z[0:3] + 2*dR_dt@z[3:6]) + J_2 + J_3\r\n zp[3:6] = z2\r\n return zp\r\n\r\ndef eulerint(zp, z0, t, Nsubdivisiones=1):\r\n Nt = len(t)\r\n Ndim = len(np.array(z0))\r\n \r\n z = np.zeros((Nt, Ndim))\r\n z[0,:] = z0[:]\r\n \r\n for i in range (1, Nt):\r\n t_anterior = t[i-1]\r\n \r\n dt = (t[i] - t[i-1])/Nsubdivisiones\r\n z_temp = z[i-1, :].copy()\r\n \r\n for k in range (Nsubdivisiones):\r\n z_temp += dt * satelite(z_temp, t_anterior + k*dt) \r\n z[i,:] = z_temp\r\n return z\r\n\r\n\r\nt, x, y, z, vx, vy, vz = leer_eof(\"S1B_OPER_AUX_POEORB_OPOD_20200827T111142_V20200806T225942_20200808T005942.EOF\")\r\n\r\nz0 = np.array([x[0],y[0],z[0],vx[0],vy[0],vz[0]])\r\nt1 = perf_counter()\r\nsol = odeint(satelite,z0,t)\r\nt2 = perf_counter()\r\ntime = t2-t1\r\nprint(time)\r\n\r\nxs = sol[:,0]\r\nys = sol[:,1]\r\nzs = sol[:,2]\r\n\r\nzp = sol[:,:]\r\n\r\n\r\nsol = eulerint(zp,z0,t,Nsubdivisiones = 1)\r\n\r\n\r\n\r\ny_1=[-5e6,0,5e6]\r\neje_y=[\"-5000\",\"0\",\"5000\"]\r\nx_1=[0,18000,36000,54000,72000,90000]\r\neje_x=[\"0\",\"5\",\"10\",\"15\",\"20\",\"25\"]\r\n\r\nx_e = sol[:,0]\r\ny_e = sol[:,1]\r\nz_e = sol[:,2]\r\n\r\ndiferencia_odeint = np.sqrt((x-xs)**2+(y-ys)**2+(z-zs)**2)\r\ndiferencia_euler = np.sqrt((x-x_e)**2+(y-y_e)**2+(z-z_e)**2)\r\n\r\n\r\nplt.plot(t/3600,diferencia_odeint/1000)\r\nplt.ylabel(\"Deriva, (Km)\")\r\nplt.xlabel(\"Tiempo, t (horas)\")\r\nplt.title(\"Distancia entre posición real y predicha con correción J2 + J3, Deltamax = 1748,56 (Km)\")\r\n\r\nplt.savefig(\"Distancia entre posición real y predicha con correción J2,J3.png\")\r\nplt.show()\r\n","sub_path":"Entrega 5/Entrega 5.6.py","file_name":"Entrega 5.6.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"362774986","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nimport util.util as util\nfrom .InnerCosFunction import InnerCosFunction\n\nclass InnerCos(nn.Module):\n def __init__(self, crit='MSE', strength=1, skip=0, layer_to_last=3):\n super(InnerCos, self).__init__()\n self.crit = crit\n self.criterion = torch.nn.MSELoss() if self.crit == 'MSE' else torch.nn.L1Loss()\n self.strength = strength\n # To define whether this layer is skipped.\n self.skip = skip\n self.layer_to_last = layer_to_last\n # Init a dummy value is fine.\n self.target = torch.tensor(1.0)\n\n def set_mask(self, mask_global):\n mask = util.cal_feat_mask(mask_global, self.layer_to_last)\n self.mask = mask.squeeze()\n self.mask = self.mask.float()\n\n def forward(self, in_data):\n self.bs, self.c, _, _ = in_data.size()\n self.mask = self.mask.to(in_data)\n if not self.skip:\n # It works like this:\n # Each iteration contains 2 forward, In the first forward, we input GT, just to get the target.\n # In the second forward, we input corrupted image, then back-propagate the network, the guidance loss works as expected.\n self.output = InnerCosFunction.apply(in_data, self.criterion, self.strength, self.target, self.mask)\n self.target = in_data.narrow(1, self.c // 2, self.c // 2).detach() # the latter part\n else:\n self.output = in_data\n return self.output\n\n\n def __repr__(self):\n skip_str = 'True' if not self.skip else 'False'\n return self.__class__.__name__+ '(' \\\n + 'skip: ' + skip_str \\\n + 'layer ' + str(self.layer_to_last) + ' to last' \\\n + ' ,strength: ' + str(self.strength) + ')'","sub_path":"models/shift_net/InnerCos.py","file_name":"InnerCos.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"423630121","text":"# Project Euler #64: Odd period square roots\r\nfrom math import sqrt\r\n\r\ndef odd_periods_below (N):\r\n odd_period = 0\r\n for n in range(2, N+1):\r\n a = a0 = int(sqrt(n))\r\n if a0**2 == n: continue # Stops if is a square \r\n m = 0\r\n d = 1\r\n period = 0\r\n while a!=2*a0:\r\n m = d*a-m\r\n d = (n-m*m)//d\r\n a = (a0+m)//d\r\n period+=1\r\n if period % 2 == 1:\r\n odd_period += 1\r\n return odd_period\r\n\r\nprint (odd_periods_below(int(input())))","sub_path":"Hacker Rank - Project Euler/hackerrank-euler064.py","file_name":"hackerrank-euler064.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"122638547","text":"from sklearn.ensemble import ExtraTreesClassifier\n\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n\n\nclass ExtraTreesClassifierModel:\n r\"\"\"\n Class to encapsulate the mechanics of running extra\n tree classification algorithm on the online news dataset\n \"\"\"\n def __init__(self, train_data,\n test_data,\n n_estimators,\n max_depth):\n self.classifier = ExtraTreesClassifier(n_estimators=n_estimators,\n max_depth=max_depth,\n random_state=0, n_jobs=10,\n )\n self.x_train, self.y_train = train_data\n self.x_test, self.y_test = test_data\n\n def train_model(self):\n print(\"Training the Extra Trees Classifier Model\")\n self.classifier.fit(self.x_train, self.y_train)\n\n def test_model(self):\n y_pred = self.classifier.predict(self.x_test)\n print(\"=\" * 40)\n print(\"Classification Report\")\n print(\"=\" * 40)\n print(classification_report(self.y_test, y_pred))\n accuracy = 100 * accuracy_score(self.y_test, y_pred)\n return accuracy\n\n def predict(self, x):\n return self.classifier.predict(x)\n\n\n\n","sub_path":"CSC440FinalProject-tusharku/com/uofr/course/csc440/project/newspopularity/models/ExtraTreeClassifier.py","file_name":"ExtraTreeClassifier.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"22722775","text":"from flask import Flask, render_template, request\nimport json\nimport requests\n\n\ndef make_post(data):\n UNBABEL_USERNAME = \"fullstack-challenge\"\n UNBABEL_API_KEY = \"9db71b322d43a6ac0f681784ebdcc6409bb83359\"\n\n headers = {\n \"Authorization\": \"ApiKey {}:{}\".format(UNBABEL_USERNAME, UNBABEL_API_KEY),\n 'Content-Type': 'application/json',\n }\n\n data = json.dumps(data)\n print(f'DATA: {data}')\n\n resTrans = requests.post(\n 'https://sandbox.unbabel.com/tapi/v2/translation/', headers=headers, data=data)\n return resTrans.json()\n\n# print(f'POST resTrans: {resTrans}')\n","sub_path":"post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"507337745","text":"from pathlib import Path\nfrom xml.etree import ElementTree \nfrom shutil import copy\nfrom obspy.signal.rotate import rotate2zne\n\ndef get_mts(mts_file,stat=None,phase=None, syn=False):\n '''Function to get the .mts file for a phase and read in the xml.\n\n Args:\n mts_file- filename (minus extension) of the data XML we want to read\n stat - the station code (data is stored by station code)\n phase (str) - phase code (ScS,SKS,SKKS, etc.) to fetch data for\n \n Returns:\n data (ElementTree) - ElementTree XML structure containing the required data XML\n\n Examples:\n >>> Set.get_mts('SKS')\n\n '''\n if syn:\n mts_file = '{}.mts'.format(mts_file)\n \n xml = ElementTree.parse(mts_file) # Parse the xml file (output from sheba as .mts)\n data = xml.getroot() # Gets the root element of the XML. In this case (the .mts) this is the tag which we want to inject into the\n # the bigger Pathset XML file\n for file in ['file1','file2','file3']:# Loop over file tags to add in pointer to data dir\n f = data.find(file).text\n # print(f)\n f_new = 'data/{}'.format(f)\n data.find(file).text = f_new\n\n return data\n\ndef get_sac(fileID,dst_path,src_path,stat,phase, syn=False):\n '''Function to copy data to the local data directory \"data\" if it is not already there (mainly useful for test/first runs).\n\n Args:\n fileID - filename (minus extension) of the sac data to copy\n stat - the station code (data is stored by station code)\n phase (str) - phase code (ScS,SKS,SKKS, etc.) \n Returns:\n\n Examples:\n >>> Set.get_sac('SKS')\n '''\n for comp in ['E','N','Z']:\n f = Path('/Users/ja17375/Projects/Epac_fast_anom/data/{}.BH{}'.format(fileID,comp))\n if f.is_file():\n #print(f'{f} exists, not copying'.format(fileID,comp))\n pass\n else:\n print(f'File not found, copying from {src_path} if possible') \n if syn:\n file = f'{fileID}.BH{comp}'\n f = fileID.split('/')[-1]\n dst = '/Users/ja17375/Projects/Epac_fast_anom/data/{}.BH{}'.format(f,comp)\n print(f'Copy synthetic data {file}')\n else:\n dst = f'{dst_path}/data/{fileID}.BH{comp}'\n file = f'{src_path}/{stat}/{phase}/{fileID}.BH{comp}'\n \n _ = copy(file, dst)\n \ndef rotate_traces(st):\n '''\n Function to rotate an obspy stream (assuming a SAC file read in) to ZNE using rotate2zne\n '''\n bh1 = st.select(channel = 'BH1')\n bh2 = st.select(channel = 'BH2')\n bhz = st.select(channel = 'BHZ')\n \n bh1_data = bh1[0].data\n bh1_inc = bh1[0].stats.sac['cmpinc']\n bh1_az = bh1[0].stats.sac['cmpaz']\n \n bh2_data = bh2[0].data\n bh2_inc = bh2[0].stats.sac['cmpinc']\n bh2_az = bh2[0].stats.sac['cmpaz']\n \n bhz_data = bhz[0].data\n bhz_inc = bhz[0].stats.sac['cmpinc']\n bhz_az = bhz[0].stats.sac['cmpaz']\n \n (Z,N,E) = rotate2zne(bhz_data, bhz_az, bhz_inc,\n bh1_data, bh1_az, bh1_inc,\n bh2_data, bh2_az, bh2_inc,\n )\n \n st.select(channel = 'BH1')[0].data = E\n st.select(channel = 'BH2')[0].data = N\n st.select(channel = 'BHZ')[0].data = Z\n \n return st \n ","sub_path":"sactools.py","file_name":"sactools.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"409333496","text":"import tkinter as tk\n\n\nclass Main(Frame):\n def __init__(self, root):\n super(Main, self).__init__(root)\n# Функция вычисления операций калькулятора\ndef calculate(operation: object, label_text=None):\n global formula, buttons\n\n if operation == 'C':\n formula = ''\n elif operation == 'def':\n formula = formula[0: -1]\n elif operation == 'X^2':\n formula = str((eval(formula)) ** 2)\n elif operation == '=':\n formula = str((eval(formula)))\n else:\n if formula == '0':\n formula = ''\n formula += operation\n label_text.configure(text=formula)\n\n\n # Создание окна для вывода вычислений\n formula = '0'\n label_text = tk.Label(text=formula, font=('Roboto', 20, 'bold'), bg='black', fg='white')\n label_text.place(x=11, y=50)\n\n\n # Создание кнопок\n buttons = ['C', 'def', '*', '=', '1', '2', '3', '/', '4', '5', '6', '+', '7', '8', '9', '-', '+/-', '0',\n '%', 'X^2']\n x = 10\n y = 140\n for button in buttons:\n get_lbl = lambda x=button: calculate(x)\n tk.Button(text=button, bg='orange', font=('Roboto', 15), command=get_lbl).place(x=x, y=y, width=115, height=79)\n x += 117\n if x > 400:\n x = 10\n y += 81\n\nwindow = tk.Tk()\nwindow.title('Calculator')\nwindow.geometry('485x550+200+200')\nwindow.resizable(False, False)\nwindow.configure(bg='green')\nwindow.mainloop()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"525277360","text":"# -*- coding: utf-8 -*-\nclass LockPicker(object):\n\n\tdef __init__(self, sticky_number, first_guess, second_guess):\n\t\tself.sticky_number = sticky_number\n\t\tself.first_guess = first_guess\n\t\tself.second_guess = second_guess\n\t\tself.sticky_remainder = sticky_number%4\n\n\tdef __generate_guess_list(self, initial_guess):\n\t\tguess_list = []\n\t\tfor multiple in range(0,4):\n\t\t\tguess = initial_guess + 10*multiple\n\t\t\tif guess%4 == self.sticky_remainder:\n\t\t\t\tguess_list.append(guess)\n\t\treturn guess_list\n\n\n\tdef generate_combination(self):\n\t\tfirst_digit = self.sticky_number + 5\n\t\tthird_guess_list = []\n\n\t\tthird_guess_list.extend(self.__generate_guess_list(initial_guess=self.first_guess))\n\t\tthird_guess_list.extend(self.__generate_guess_list(initial_guess=self.second_guess))\n\n\t\tsecond_digit_base_two = self.sticky_remainder + 2\n\t\tsecond_digit_base_six = self.sticky_remainder + 6\n\t\tsecond_guess_list = [second_digit_base_two, second_digit_base_six]\n\n\t\tfor _ in range(0,4): \n\t\t\tsecond_digit_base_two += 8\n\t\t\tsecond_digit_base_six += 8 \n\t\t\tsecond_guess_list.append(second_digit_base_two)\n\t\t\tsecond_guess_list.append(second_digit_base_six)\n\n\t\treturn (first_digit, second_guess_list, third_guess_list)\n\ndef main(): \n\tpicker = LockPicker(sticky_number=6, first_guess=1, second_guess=8)\n\tpossible_combination = picker.generate_combination()\n\tprint(\"First Digit: {f}\".format(f=possible_combination[0]))\n\tprint(\"Second Digit: {s}\".format(s = possible_combination[1]))\n\tprint(\"Third Digit: {t}\".format(t=possible_combination[2]))\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"master_lock.py","file_name":"master_lock.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"644374","text":"number = [3,6,4,2,9,6,57,38,4,3,7824,46,2]\n\ndef quick_sort(n):\n \n if len(n) <= 1:\n return n\n else:\n pivot = n.pop()\n left = []\n right = []\n for item in n:\n if item < pivot:\n left.append(item)\n else:\n right.append(item)\n return quick_sort(left) + [pivot]+ quick_sort(right)\n\n\nprint(quick_sort(number))\n","sub_path":"python_algorithms/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"611398181","text":"from datetime import datetime\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom freezegun import freeze_time\n\nfrom directory_validators import company as shared_validators\n\nfrom directory_constants import company_types, choices\nfrom pytz import UTC\n\nfrom company.tests import VALID_REQUEST_DATA\nfrom company import models, serializers, validators\nfrom company.tests.factories import CompanyFactory\n\n\n@pytest.fixture\ndef company():\n return CompanyFactory()\n\n\n@pytest.fixture\ndef company_case_study_one(company):\n return models.CompanyCaseStudy.objects.create(\n title='a title one',\n description='a description one',\n sector=choices.INDUSTRIES[1][0],\n website='http://www.example.com',\n keywords='goog, great',\n testimonial='very nice',\n testimonial_name='Lord Voldemort',\n testimonial_job_title='Evil overlord',\n testimonial_company='Death Eaters',\n company=company,\n )\n\n\n@pytest.fixture\ndef company_case_study_two(company):\n return models.CompanyCaseStudy.objects.create(\n title='a title one',\n description='a description one',\n sector=choices.INDUSTRIES[1][0],\n website='http://www.example.com',\n keywords='goog, great',\n testimonial='very nice',\n testimonial_name='Albus Dumbledore',\n testimonial_job_title='Headmaster',\n testimonial_company='Hogwarts',\n company=company,\n )\n\n\n@pytest.fixture\ndef case_study_data(company):\n return {\n 'title': 'a title',\n 'description': 'a description',\n 'sector': choices.INDUSTRIES[1][0],\n 'website': 'http://www.example.com',\n 'keywords': 'good, great',\n 'testimonial': 'very nice',\n 'testimonial_name': 'Lord Voldemort',\n 'testimonial_job_title': 'Evil overlord',\n 'testimonial_company': 'Death Eaters',\n 'company': company.pk,\n 'short_summary': 'Very nice',\n 'image_one_caption': 'Nice image one',\n 'image_two_caption': 'Nice image two',\n 'image_three_caption': 'Nice image three',\n }\n\n\n@pytest.mark.django_db\ndef test_company_serializer_untouches_is_published():\n data = {\n 'number': \"01234567\",\n 'has_exported_before': True,\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'title': 'test_title',\n 'firstname': 'test_firstname',\n 'lastname': 'test_lastname',\n 'address_line_1': 'test_address_line_1',\n 'address_line_2': 'test_address_line_2',\n 'locality': 'test_locality',\n 'postal_code': 'test_postal_code',\n 'country': 'test_country',\n }\n serializer = serializers.CompanySerializer(data=data)\n\n assert serializer.is_valid(), serializer.errors\n instance = serializer.save()\n\n assert instance.is_published is False\n\n\n@pytest.mark.django_db\ndef test_company_serializer_is_published_field_with_isd():\n data = {\n 'number': \"01234567\",\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'firstname': 'test_firstname',\n 'is_published_investment_support_directory': True,\n }\n serializer = serializers.CompanySerializer(data=data)\n\n assert serializer.is_valid(), serializer.errors\n instance = serializer.save()\n\n assert instance.is_published is True\n\n\n@pytest.mark.django_db\ndef test_company_serializer_is_published_field_with_fab():\n data = {\n 'number': \"01234567\",\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'firstname': 'test_firstname',\n 'is_published_find_a_supplier': True,\n }\n serializer = serializers.CompanySerializer(data=data)\n\n assert serializer.is_valid(), serializer.errors\n instance = serializer.save()\n\n assert instance.is_published is True\n\n\n@pytest.mark.django_db\ndef test_company_serializer_sole_trader():\n data = {\n 'number': \"01234567\",\n 'has_exported_before': True,\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'title': 'test_title',\n 'firstname': 'test_firstname',\n 'lastname': 'test_lastname',\n 'address_line_1': 'test_address_line_1',\n 'address_line_2': 'test_address_line_2',\n 'locality': 'test_locality',\n 'postal_code': 'test_postal_code',\n 'country': 'test_country',\n 'company_type': company_types.SOLE_TRADER,\n }\n serializer = serializers.CompanySerializer(data=data)\n\n assert serializer.is_valid(), serializer.errors\n instance = serializer.save()\n\n assert instance.company_type == company_types.SOLE_TRADER\n assert instance.number.startswith('ST')\n assert len(instance.number) == 8\n\n\n@freeze_time(\"2016-01-09 12:16:11\")\n@pytest.mark.django_db\ndef test_company_serializer_doesnt_allow_changing_modified_timestamp():\n data = {\n 'number': \"01234567\",\n 'has_exported_before': True,\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'title': 'test_title',\n 'firstname': 'test_firstname',\n 'lastname': 'test_lastname',\n 'address_line_1': 'test_address_line_1',\n 'address_line_2': 'test_address_line_2',\n 'locality': 'test_locality',\n 'postal_code': 'test_postal_code',\n 'country': 'test_country',\n 'modified': datetime(2013, 3, 4, 15, 3, 1, 987654),\n }\n serializer = serializers.CompanySerializer(data=data)\n assert serializer.is_valid() is True\n\n company = serializer.save()\n\n # modified is the value of when the serializer save method was called\n # instead of what we tried to update it to\n assert company.modified == datetime(2016, 1, 9, 12, 16, 11, tzinfo=UTC)\n\n\ndef test_company_serializer_has_keywords_shared_serializers():\n serializer = serializers.CompanySerializer()\n validators = serializer.fields['keywords'].validators\n assert shared_validators.keywords_special_characters in validators\n assert shared_validators.keywords_word_limit in validators\n\n\n@pytest.mark.django_db\ndef test_company_serializer_doesnt_accept_number_under_8_chars():\n data = {'number': \"1234567\"}\n serializer = serializers.CompanySerializer(data=data)\n\n valid = serializer.is_valid()\n\n assert valid is False\n assert 'number' in serializer.errors\n error_msg = 'Company number must be 8 characters'\n assert error_msg in serializer.errors['number']\n\n\n@pytest.mark.django_db\ndef test_company_serializer_doesnt_accept_number_over_8_chars():\n data = {\n 'number': \"012345678\",\n 'has_exported_before': True,\n 'name': 'Earnest Corp',\n 'date_of_creation': '2010-10-10',\n 'title': 'test_title',\n 'firstname': 'test_firstname',\n 'lastname': 'test_lastname',\n 'address_line_1': 'test_address_line_1',\n 'address_line_2': 'test_address_line_2',\n 'locality': 'test_locality',\n 'postal_code': 'test_postal_code',\n 'country': 'test_country',\n }\n serializer = serializers.CompanySerializer(data=data)\n\n valid = serializer.is_valid()\n\n assert valid is False\n assert 'number' in serializer.errors\n error_msg = 'Ensure this field has no more than 8 characters.'\n assert error_msg in serializer.errors['number']\n\n\n@pytest.mark.django_db\ndef test_company_serializer_save():\n serializer = serializers.CompanySerializer(data=VALID_REQUEST_DATA)\n serializer.is_valid()\n\n company = serializer.save()\n\n assert company.name == VALID_REQUEST_DATA['name']\n assert company.number == VALID_REQUEST_DATA['number']\n assert company.website == VALID_REQUEST_DATA['website']\n assert company.description == VALID_REQUEST_DATA['description']\n assert len(company.verification_code) == 12\n\n\n@pytest.mark.django_db\ndef test_company_serializer_nested_case_study(\n company, company_case_study_one, company_case_study_two\n):\n case_studies = [\n serializers.CompanyCaseStudySerializer(company_case_study_one).data,\n serializers.CompanyCaseStudySerializer(company_case_study_two).data,\n ]\n serializer = serializers.CompanySerializer(company)\n\n assert len(serializer.data['supplier_case_studies']) == len(case_studies)\n assert case_studies[0] in serializer.data['supplier_case_studies']\n assert case_studies[1] in serializer.data['supplier_case_studies']\n\n\ndef test_company_number_serializer_validators():\n serializer = serializers.CompanyNumberValidatorSerializer()\n field = serializer.get_fields()['number']\n\n assert validators.company_unique in field.validators\n\n\n@pytest.mark.django_db\ndef test_company_case_study_explicit_value(case_study_data):\n request = Mock()\n company = CompanyFactory()\n request.user.supplier.company = company\n serializer = serializers.CompanyCaseStudySerializer(\n data=case_study_data, context={'request': request}\n )\n\n assert serializer.is_valid()\n data = serializer.validated_data\n\n assert data['company'] == company\n assert data['website'] == case_study_data['website']\n assert data['testimonial'] == case_study_data['testimonial']\n assert data['testimonial_name'] == case_study_data['testimonial_name']\n assert data['testimonial_job_title'] == (\n case_study_data['testimonial_job_title']\n )\n assert data['testimonial_company'] == (\n case_study_data['testimonial_company']\n )\n\n\n@pytest.mark.django_db\ndef test_company_case_study_with_company(company_case_study_one):\n serializer = serializers.CompanyCaseStudyWithCompanySerializer(\n company_case_study_one\n )\n assert isinstance(serializer.data['company'], dict)\n\n\ndef test_company_search_serializer():\n serializer = serializers.SearchSerializer(\n data={'page': 1, 'size': 10, 'term': 'thing'}\n )\n\n assert serializer.is_valid() is True\n\n\ndef test_company_search_serializer_empty_term_sector():\n serializer = serializers.SearchSerializer(\n data={'page': 1, 'size': 10}\n )\n\n message = serializers.SearchSerializer.MESSAGE_MISSING_QUERY\n assert serializer.is_valid() is False\n assert serializer.errors == {'non_field_errors': [message]}\n\n\n@pytest.mark.parametrize('field, field_value', [\n ['expertise_industries', [choices.INDUSTRIES[1][0]]],\n ['expertise_regions', [choices.EXPERTISE_REGION_CHOICES[1][0]]],\n ['expertise_countries', [choices.COUNTRY_CHOICES[1][0]]],\n ['expertise_languages', [choices.EXPERTISE_LANGUAGES[1][0]]],\n ['expertise_products_services_labels', ['IT']],\n])\ndef test_company_search_serializer_optional_field(field, field_value):\n\n serializer = serializers.SearchSerializer(\n data={'page': 1, 'size': 10, field: field_value}\n )\n\n assert serializer.is_valid() is True\n","sub_path":"company/tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":10689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"638508318","text":"# https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/python\nfrom collections import Counter\ndef duplicate_encode(word):\n letter_counts = Counter(word.lower())\n new_string = \"\"\n for letter in word.lower():\n if letter_counts[letter] == 1:\n new_string += '('\n elif letter_counts[letter] > 1:\n new_string += ')'\n return new_string\n\n\n\n","sub_path":"pythonCodeWars/duplicateEncoder.py","file_name":"duplicateEncoder.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"653448785","text":"#TODO: minimal imports\n\nimport IPython as ipy\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom seqeval.metrics import classification_report\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils\nimport torch.optim as optim\nimport torch.optim.lr_scheduler\nimport torch.utils.data as data\nfrom tqdm.auto import tqdm\nimport itertools as it\nimport time\n\n# load vocab and (glove) embeddings\ndef load_emb(path, total=None):\n toks = []\n embs = []\n with open(path, 'r') as f:\n for l in tqdm(f, path, total=total):\n tok, *emb = l.strip().split()\n emb = [float(x) for x in emb]\n toks.append(tok)\n embs.append(emb)\n assert('PAD_TOK' not in toks and 'UNK_TOK' not in toks)\n toks += ['PAD_TOK', 'UNK_TOK']\n embs += [[0.]*len(emb), [0.]*len(emb)]\n tok_to_id = dict(zip(toks, it.count()))\n emb = torch.tensor(embs)\n return tok_to_id, emb\n\n# load characters from (training) data\ndef load_chrs(path, total=None):\n chars = set()\n with open(path, 'r') as f:\n for l in tqdm(f, path, total=total):\n try:\n for c in l.strip().split()[2]:\n chars.add(c)\n except:\n pass\n assert('PAD_CHR' not in chars and 'UNK_CHR' not in chars)\n chars = sorted(chars)\n chars.append('PAD_CHR')\n chars.append('UNK_CHR')\n return dict(zip(chars, it.count()))\n\n# load classes from (training) data\ndef load_classes(path, total=None):\n id_to_lbl = set()\n with open(path, 'r') as f:\n for l in tqdm(f, path, total=total):\n try:\n id_to_lbl.add(l.strip().split()[3])\n except:\n pass\n assert('PAD_LBL' not in id_to_lbl)\n id_to_lbl = sorted(id_to_lbl)\n id_to_lbl.append('PAD_LBL')\n lbl_to_id = {k:v for v, k in enumerate(id_to_lbl)}\n return lbl_to_id, id_to_lbl\n\n# load data from train/dev/test file\n# W: num_seqs x seq_len x word_len - id of characters\n# X: num_seqs x seq_len - id of tokens\n# Y: num_seqs x seq_len - id of labels\ndef load_data(path, tok_to_id, lbl_to_id, chr_to_id):\n with open(path, 'r') as f:\n seqs = f.read().split('\\n\\n')\n if not seqs[-1].strip():\n seqs.pop()\n if seqs[0][0] == '\\n':\n seqs[0] = seqs[0][1:]\n seqs = [l.split('\\n') for l in seqs]\n seq_len = max((len(seq) for seq in seqs))\n seqs = [[l.split(' ') for l in seq] for seq in seqs]\n wrd_len = max((max((len(cols[2]) for cols in seq)) for seq in seqs))\n W = torch.empty((len(seqs), seq_len, wrd_len), dtype=torch.long).fill_(chr_to_id['PAD_CHR'])\n X = torch.empty((len(seqs), seq_len), dtype=torch.long).fill_(tok_to_id['PAD_TOK'])\n Y = torch.empty((len(seqs), seq_len), dtype=torch.long).fill_(lbl_to_id['PAD_LBL'])\n for i, seq in enumerate(tqdm(seqs, 'sequences')):\n for j, cols in enumerate(seq):\n assert(j < seq_len)\n tok, _, wrd, lbl = cols\n for k, ch in enumerate(wrd):\n try:\n W[i,j,k] = chr_to_id[ch]\n except KeyError:\n W[i,j,k] = chr_to_id['UNK_CHR']\n try:\n X[i,j] = tok_to_id[tok]\n except KeyError:\n X[i,j] = tok_to_id['UNK_TOK'] \n Y[i,j] = lbl_to_id[lbl]\n return W, X, Y\n\n# NER model intended for top-level training\nclass NERModel(nn.Module):\n def __init__(self, embed_model, seq_tag_model, pad_lbl_id, pad_tok_id):\n super().__init__()\n self.embed_model = embed_model\n self.seq_tag_model = seq_tag_model\n self.pad_lbl_id = pad_lbl_id\n self.pad_tok_id = pad_tok_id\n self.cross_entropy_loss = nn.CrossEntropyLoss(ignore_index=pad_lbl_id)\n\n def forward(self, W, X):\n # trim to max sequence length in batch for speed\n #max_len = torch.max(torch.sum(X != self.pad_tok_id, dim=-1))\n #print(max_len)\n #X = X[...,:max_len]\n return self.seq_tag_model(self.embed_model(W, X))\n \n def predict(self, W, X):\n with torch.no_grad():\n self.eval()\n Y_hat = self(W, X)\n pred = torch.argmax(Y_hat, dim=-1)\n # restore original shape\n pad = torch.empty(*pred.shape[:-1], X.shape[-1]-pred.shape[-1], dtype=torch.long, device=pred.device).fill_(Y_hat.shape[-1])\n return torch.cat((pred, pad), dim=-1)\n \n def criterion(self, Y, Y_hat):\n # trim to match shape\n Y = Y[...,:Y_hat.shape[-2]]\n return self.cross_entropy_loss(Y_hat.transpose(1,2), Y)\n \n def device(self):\n return next(self.parameters()).device\n \n def batch_predict(self, W, X, batch_size):\n loader = data.DataLoader(data.TensorDataset(W, X), batch_size=batch_size)\n return torch.cat([self.predict(batch_W.to(self.device()), batch_X.to(self.device())) for batch_W, batch_X in loader])\n\n\n# BiLSTM sequence tagger module\nclass SeqTagModel(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, dropout_prob):\n super().__init__()\n # dropout on the input as in lample et. al.\n self.dropout = nn.Dropout(dropout_prob)\n # trainable initial hidden representation and state\n self.h0 = nn.Parameter(torch.randn(2, hidden_size))\n self.c0 = nn.Parameter(torch.randn(2, hidden_size))\n self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True, bidirectional=True)\n self.linear = nn.Linear(2*hidden_size, output_size)\n \n def forward(self, X):\n D = self.dropout(X)\n H, _ = self.lstm(D, (self.h0[:,None,:].expand(-1,D.shape[0],-1).contiguous(), self.c0[:,None,:].expand(-1,D.shape[0],-1).contiguous()))\n return self.linear(H)\n\n# LSTMCell module with layer norm\nclass LSTMCellLN(nn.Module):\n def __init__(self, input_size, hidden_size):\n super().__init__()\n self.hidden_size = hidden_size\n k = torch.sqrt(1/torch.tensor(hidden_size, dtype=torch.float))\n self.Wh = nn.Parameter(torch.empty(hidden_size, 4*hidden_size).uniform_(-k, k))\n self.Wx = nn.Parameter(torch.empty(input_size, 4*hidden_size).uniform_(-k, k))\n # initialize forget gate biases to 1 to promote remembering\n self.b = nn.Parameter(torch.cat((torch.ones(hidden_size), torch.zeros(3*hidden_size))))\n self.lnh = nn.LayerNorm(4*hidden_size)\n self.lnx = nn.LayerNorm(4*hidden_size)\n self.lnc = nn.LayerNorm(hidden_size)\n \n def forward(self, X, HC):\n H, C = HC\n f, i, o, g = torch.split(self.lnh(H@self.Wh) + self.lnx(X@self.Wx) + self.b, [self.hidden_size]*4, dim=-1)\n C = torch.sigmoid(f) * C + torch.sigmoid(i) * torch.tanh(g)\n H = torch.sigmoid(o) * torch.tanh(self.lnc(C))\n return H, C\n\n# BiLSTM sequence tagger module based on layer normalized LSTMCell\nclass LNSeqTagModel(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, dropout_prob):\n super().__init__()\n self.hidden_size = hidden_size\n self.dropout = nn.Dropout(dropout_prob)\n self.lstm_cell_f = LSTMCellLN(input_size, hidden_size)\n self.h0_f = nn.Parameter(torch.randn(hidden_size))\n self.c0_f = nn.Parameter(torch.randn(hidden_size))\n self.lstm_cell_b = LSTMCellLN(input_size, hidden_size)\n self.h0_b = nn.Parameter(torch.randn(hidden_size))\n self.c0_b = nn.Parameter(torch.randn(hidden_size))\n self.linear = nn.Linear(2*hidden_size, output_size)\n \n def forward(self, X):\n D = self.dropout(X)\n H = torch.empty(X.shape[0], X.shape[1], 2*self.hidden_size, device=X.device)\n \n h = self.h0_f.expand(X.shape[0], -1).contiguous()\n c = self.c0_f.expand(X.shape[0], -1).contiguous()\n for i in range(X.shape[1]):\n h, c = self.lstm_cell_f(D[:,i,:], (h, c))\n H[:,i,:self.hidden_size] = h\n\n h = self.h0_b[None,:].expand(X.shape[0], -1).contiguous()\n c = self.c0_b[None,:].expand(X.shape[0], -1).contiguous()\n for i in range(X.shape[1]-1,-1,-1):\n h, c = self.lstm_cell_b(D[:,i,:], (h, c))\n H[:,i,-self.hidden_size:] = h\n\n return self.linear(H)\n \n# token embedding module\nclass TokEmbModel(nn.Module):\n def __init__(self, init_emb, pad_tok_id):\n super().__init__()\n self.embedding = nn.Embedding.from_pretrained(init_emb, freeze=False, padding_idx=pad_tok_id)\n \n def forward(self, W, X):\n return self.embedding(X)\n \n# character embedding module\nclass ChrEmbModel(nn.Module):\n def __init__(self, n_embs, pad_chr_id, unk_chr_id, unk_replace_prob, emb_size, hidden_size):\n super().__init__()\n self.embedding = nn.Embedding(n_embs, emb_size, padding_idx=pad_chr_id)\n self.h0 = nn.Parameter(torch.randn(2, hidden_size))\n self.c0 = nn.Parameter(torch.randn(2, hidden_size))\n self.lstm = nn.LSTM(emb_size, hidden_size, batch_first=True, bidirectional=True)\n self.pad_chr_id = pad_chr_id\n self.unk_chr_id = unk_chr_id\n self.unk_replace_prob = unk_replace_prob\n\n def forward(self, W, X):\n # trim to max sequence length in batch for speed\n W = W[...,:X.shape[-1],:]\n Z = W.reshape(-1,W.shape[-1])\n max_len = torch.max(torch.sum(Z != self.pad_chr_id, dim=-1))\n Z = Z[...,:max_len]\n if self.training:\n Z[torch.empty(Z.shape).uniform_() < self.unk_replace_prob] = self.unk_chr_id\n E = self.embedding(Z)\n _, (H, _) = self.lstm(E, (self.h0[:,None,:].expand(-1,E.shape[0],-1).contiguous(), self.c0[:,None,:].expand(-1,E.shape[0],-1).contiguous()))\n return H.reshape(*W.shape[:-1],-1)\n\n# character + token embedding module\nclass ChrTokEmbModel(nn.Module):\n def __init__(self, chr_emb_model, tok_emb_model):\n super().__init__()\n self.chr_emb_model = chr_emb_model\n self.tok_emb_model = tok_emb_model\n \n def forward(self, W, X):\n return torch.cat((self.chr_emb_model(W, X), self.tok_emb_model(W, X)), dim=-1)\n\n# token level accuracy and macro F1 (note that micro F1 == accuracy at token level)\ndef metric(Y_true, Y_pred, n_classes):\n with torch.no_grad():\n # trim\n Y_true = Y_true[...,:Y_pred.shape[-1]]\n Y_true = Y_true.reshape(-1)\n Y_pred = Y_pred.reshape(-1)\n # discard pad labels\n Y_pred = Y_pred[Y_true != n_classes]\n Y_true = Y_true[Y_true != n_classes]\n # accuracy\n acc = torch.sum(Y_true == Y_pred).float() / torch.numel(Y_true)\n Z_true = F.one_hot(Y_true, n_classes)\n Z_pred = F.one_hot(Y_pred, n_classes)\n S_tp = torch.sum(Z_true & Z_pred, dim=0).float()\n S_t = torch.sum(Z_true, dim=0).float()\n S_p = torch.sum(Z_pred, dim=0).float()\n f1 = 2 * S_tp / (S_t + S_p)\n # do not consider classes with no examples when taking mean\n f1 = f1[~torch.isnan(f1)]\n macro_F1 = torch.mean(f1)\n return [acc.item(), macro_F1.item()]\n\ndef plot_losses(train_losses, dev_losses, new_train_losses, new_dev_losses):\n plt.subplot(121)\n plt.plot(dev_losses, label='dev')\n plt.plot(train_losses, label='train')\n plt.legend()\n plt.title('All Epochs')\n plt.xlabel('iterations')\n plt.ylabel('loss')\n plt.subplot(122)\n plt.plot(new_dev_losses, label='dev')\n plt.plot(new_train_losses, label='train')\n plt.legend()\n plt.title('Last Epoch')\n plt.xlabel('iterations')\n plt.ylabel('loss')\n plt.suptitle('Loss Curves')\n\ndef plot_metrics(train_metrics_np, dev_metrics_np):\n plt.subplot(121)\n plt.plot(train_metrics_np[:,0], label='train')\n plt.plot(dev_metrics_np[:,0], label='dev')\n plt.legend()\n plt.title('Accuracy')\n plt.xlabel('iterations')\n plt.ylim(0,1)\n plt.subplot(122)\n plt.plot(train_metrics_np[:,1], label='train')\n plt.plot(dev_metrics_np[:,1], label='dev')\n plt.legend()\n plt.title('Macro-F1')\n plt.xlabel('iterations')\n plt.ylim(0,1)\n plt.suptitle('Token-level Metrics at Training')\n\ndef train_epoch(model, opt, train_loader, dev_loader, grad_clip_norm, n_classes, id_to_lbl, pad_lbl_id):\n train_losses = []\n train_metrics = []\n dev_losses = []\n dev_metrics = []\n for (train_W_batch, train_X_batch, train_Y_batch), (dev_W_batch, dev_X_batch, dev_Y_batch) in \\\n zip(tqdm(train_loader, 'batches', leave=False), it.cycle(dev_loader)):\n with torch.no_grad():\n model.eval()\n dev_W_batch = dev_W_batch.to(model.device())\n dev_X_batch = dev_X_batch.to(model.device())\n dev_Y_batch = dev_Y_batch.to(model.device())\n dev_pred_batch = model(dev_W_batch, dev_X_batch)\n dev_loss = model.criterion(dev_Y_batch, dev_pred_batch)\n dev_losses.append(dev_loss.item())\n dev_metric = metric(dev_Y_batch, torch.argmax(dev_pred_batch, dim=-1), n_classes)\n dev_metrics.append(dev_metric)\n\n model.train()\n train_W_batch = train_W_batch.to(model.device())\n train_X_batch = train_X_batch.to(model.device())\n train_Y_batch = train_Y_batch.to(model.device())\n train_pred_batch = model(train_W_batch, train_X_batch)\n train_loss = model.criterion(train_Y_batch, train_pred_batch)\n train_losses.append(train_loss.item())\n train_metric = metric(train_Y_batch, torch.argmax(train_pred_batch, dim=-1), n_classes)\n \n train_metrics.append(train_metric)\n opt.zero_grad()\n train_loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), grad_clip_norm)\n opt.step()\n return train_losses, train_metrics, dev_losses, dev_metrics \n\ndef train_loop(train_set, dev_set, model, lr, cos_max, n_classes, train_batch_size, dev_batch_size, grad_clip_norm, patience, max_epochs, show, id_to_lbl, pad_lbl_id):\n train_loader = data.DataLoader(data.TensorDataset(*train_set), batch_size=train_batch_size, shuffle=True)\n dev_loader = data.DataLoader(data.TensorDataset(*dev_set), batch_size=dev_batch_size, shuffle=True)\n opt = optim.Adam(model.parameters(), lr=lr)\n lr_sched = optim.lr_scheduler.CosineAnnealingLR(opt, cos_max)\n \n train_losses = []\n dev_losses = []\n train_metrics = []\n dev_metrics = []\n \n prev_mean_dev_losses = float('inf')\n for epoch in tqdm(range(max_epochs), 'epochs'):\n new_train_losses, new_train_metrics, new_dev_losses, new_dev_metrics = \\\n train_epoch(model, opt, train_loader, dev_loader, grad_clip_norm, n_classes, id_to_lbl, pad_lbl_id)\n lr_sched.step()\n\n # early stopping\n mean_dev_losses = sum(new_dev_losses)/len(new_dev_losses)\n if mean_dev_losses < prev_mean_dev_losses:\n patience_ctr = 0\n best = model.state_dict()\n else:\n patience_ctr += 1\n if patience_ctr == patience:\n model.load_state_dict(best)\n break\n prev_mean_dev_losses = mean_dev_losses\n\n train_losses += new_train_losses\n dev_losses += new_dev_losses\n train_metrics += new_train_metrics\n dev_metrics += new_dev_metrics\n \n tqdm.write(f'epoch: {epoch}/{max_epochs}\\t lr: {opt.param_groups[0][\"lr\"]:.6f}\\t dev loss: {mean_dev_losses:.6f}\\t')\n if show:\n plt.figure(figsize=(12,4))\n plot_losses(train_losses, dev_losses, new_train_losses, new_dev_losses)\n ipy.display.clear_output(wait=True)\n plt.show()\n\n train_metrics_np = np.array(train_metrics)\n dev_metrics_np = np.array(dev_metrics)\n plt.figure(figsize=(12,4))\n plot_metrics(train_metrics_np, dev_metrics_np)\n plt.show()\n \n return train_losses, train_metrics, dev_losses, dev_metrics\n\ndef to_lbl_seq(Y, id_to_lbl):\n ret = []\n for seq in Y:\n row = []\n for lbl_id in seq:\n lbl = id_to_lbl[lbl_id]\n if lbl == 'PAD_LBL':\n break\n row.append(lbl)\n ret.append(row)\n return ret\n\ndef conll_report(Y_true, Y_pred, id_to_lbl, pad_lbl_id):\n assert(Y_true.shape == Y_pred.shape)\n Y_pred[Y_true == pad_lbl_id] = pad_lbl_id\n return classification_report(to_lbl_seq(Y_true, id_to_lbl), to_lbl_seq(Y_pred, id_to_lbl))\n","sub_path":"A1/2018CS10416_2018CS50404/ner.py","file_name":"ner.py","file_ext":"py","file_size_in_byte":16307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"177184169","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef load_artificial_train(num=100):\n \"\"\"Load artificial training data\n returns: train_x (M x N)\n \"\"\" \n train_x = np.linspace(1.0, 10.0, num)[:, np.newaxis]\n train_y = np.sin(train_x) + 0.1 * np.power(train_x , 2) + \\\n 0.5 * np.random.randn(num, 1)\n\n return train_x, train_y\n\ndef load_mnist_train():\n with np.load(\"TINY_MNIST.npz\") as data:\n x, t = data[\"x\"], data[\"t\"]\n return x, t\n\ndef load_mnist_valid():\n with np.load(\"TINY_MNIST.npz\") as data:\n x_eval , t_eval = data[\"x_eval\"], data[\"t_eval\"]\n return x_eval,t_eval\n\ndef l2_distance(a, b):\n if a.shape[0] != b.shape[0]:\n raise ValueError(\"A and B should be of same dimensionality\")\n\n aa = np.sum(a**2, axis=0)\n bb = np.sum(b**2, axis=0)\n ab = np.dot(a.T, b)\n\n return np.sqrt(aa[:, np.newaxis] + bb[np.newaxis, :] - 2*ab)\n\ndef k_nearest_neighbors(k, train_data, train_labels, valid_data):\n\n dist = l2_distance(train_data.T, valid_data.T)\n nearest = np.argsort(dist, axis=1)[:,:k]\n\n train_labels = train_labels.reshape(-1)\n valid_labels = train_labels[nearest]\n\n valid_labels = (np.mean(valid_labels, axis=1) >= 0.5).astype(np.int)\n valid_labels = valid_labels.reshape(-1,1)\n\n return valid_labels\n\ndef plot_error(train_error, valid_error):\n plt.figure(1)\n plt.clf()\n plt.plot(range(len(train_error)), train_error, 'b', label='Train')\n plt.plot(range(len(valid_error)), valid_error, 'g', label='Validation')\n plt.xlabel('Epochs')\n plt.ylabel('Error')\n plt.legend()\n plt.draw()\n raw_input('Press Enter to exit.')\n\ndef plot_lr (x,y,t):\n plt.figure(1)\n plt.clf()\n plt.plot(x,t, 'yo', x, y, '--k' )\n plt.show()\n","sub_path":"Asst1/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"121878488","text":"import os\nfrom pathlib import Path\nimport pytest\nfrom click.testing import CliRunner\nfrom .. import main\n\n\n@pytest.mark.parametrize(\n \"directory, organization, workflow, override, target, abort\",\n [(None, 'org', 'wf', None, '.', True),\n ('.', 'org', 'wf', None, '.', True),\n (None, 'org', 'wf', 'y', '.', False),\n ('.', 'org', 'wf', 'y', '.', False),\n ('niflow-org-wf', 'org', 'wf', None, 'niflow-org-wf', False),\n ('org-wf', 'org', 'wf', None, 'niflow-org-wf', False),\n ('ow', 'org', 'wf', '', 'niflow-org-wf', False),\n ('ow', 'org', 'wf', 'y', 'niflow-org-wf', False),\n ('ow', 'org', 'wf', 'n', 'niflow-ow', False)])\ndef test_init_path_selection(directory, organization, workflow, override, target, abort):\n runner = CliRunner()\n\n args = ['init']\n inputs = []\n\n orig_path = Path(directory or '.')\n targ_path = Path(target)\n\n if directory is not None:\n args.append(directory)\n\n # Non-standard paths prompt user input\n if orig_path.name not in (f'niflow-{organization}-{workflow}',\n f'{organization}-{workflow}'):\n inputs.extend([organization, workflow])\n if override is not None:\n inputs.append(override)\n\n with runner.isolated_filesystem():\n result = runner.invoke(main, args, '\\n'.join(inputs))\n\n if abort:\n assert result.exit_code != 0\n assert not (targ_path / '.git').exists()\n else:\n assert result.exit_code == 0\n\n assert targ_path.exists()\n assert (targ_path / '.git').exists()\n\n\n@pytest.mark.parametrize(\n \"author, email, gitconfig\",\n [('Test Author', 'unreal3214@fake2182.tld', os.devnull),\n ('Test Author', 'unreal3214@fake2182.tld', 'tmp_gitconfig')])\ndef test_init_python(author, email, gitconfig):\n runner = CliRunner()\n\n args = ['init', 'niflow-org-wf', '--language', 'python']\n\n with runner.isolated_filesystem():\n inputs = None\n if gitconfig != os.devnull:\n config_path = Path(gitconfig)\n config_path.write_text(f'[user]\\n\\temail = {email}\\n\\tname = {author}')\n gitconfig = str(config_path.absolute())\n else:\n inputs = '\\n'.join([author, email])\n\n result = runner.invoke(main, args, inputs, env={'GIT_CONFIG': gitconfig})\n\n assert result.exit_code == 0\n\n if gitconfig == os.devnull:\n assert 'Enter package author name: ' in result.stdout\n assert 'Enter package author email: ' in result.stdout\n else:\n assert 'Enter package author name: ' not in result.stdout\n assert 'Enter package author email: ' not in result.stdout\n","sub_path":"niflow_manager/cli/tests/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"128643804","text":"import asyncio\nimport json\nimport time\n\nimport redis\nimport aredis\n\nredis_pool = aredis.ConnectionPool(\n host='10.0.0.48',\n port=6379,\n db=1\n)\n\ndef aredis_cli():\n return aredis.StrictRedis(\n connection_pool=redis_pool,\n decode_responses=True, # 自动解码\n )\n\n\n\nclass TaskModel():\n def __init__(self, *args, **kwargs):\n self.redis_client = aredis_cli()\n\n async def push(self, semaphore, site, type, value):\n async with semaphore:\n await self.redis_client.lpush('{}_{}'.format(site, type), value)\n\n\nif __name__ == '__main__':\n\n file = 'key_yinguo.list'\n site = 'yinguo'\n\n\n def company():\n with open(file, 'r', encoding='utf-8') as f:\n while True:\n line = f.readline()\n if not line:\n break\n yield line.strip()\n\n\n def gene(to_fill):\n task = {'page': 1, 'site': site, 'type': 1, 'keyword': to_fill}\n return json.dumps(task, ensure_ascii=False)\n\n\n loop = asyncio.get_event_loop()\n t = TaskModel().push\n semaphore = asyncio.Semaphore(500)\n task = [asyncio.ensure_future(t(semaphore, site ,type=1, value=gene(i))) for i in company()]\n start = time.time()\n loop.run_until_complete(asyncio.wait(task))\n endtime = time.time() - start\n print(endtime)\n loop.close()\n","sub_path":"tasks_import/async_import_task_yinguo.py","file_name":"async_import_task_yinguo.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"134561750","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFlask-PluginKit\n===============\n\n基于Flask的插件式开发工具(Web program plugin development kit based on flask).\n\n使用概述(Overview)\n~~~~~~~~~~~~~~~~~~\n\n安装(Installation)\n\n::\n\n $ pip install Flask-PluginKit\n\n普通模式(Usage)\n\n::\n\n from flask_pluginkit import PluginManager\n plugin = PluginManager(app)\n\n工厂模式(The factory pattern)\n\n::\n\n from flask_pluginkit import PluginManager\n plugin = PluginManager()\n plugin.init_app(app)\n\n文档(Documentation)\n~~~~~~~~~~~~~~~~~~~\n\n`点击这(Click here) `__\n\nLICENSE\n~~~~~~~\n\n`MIT LICENSE `__\n\n\"\"\"\n\nimport os\nimport sys\nfrom setuptools import setup, Command\n\n\nversion = '0.1.6'\n\n\nclass PublishCommand(Command):\n\n description = \"Publish a new version to pypi\"\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n os.system(\"pip install -U setuptools twine wheel\")\n os.system(\"python setup.py sdist bdist_wheel\")\n os.system(\"twine upload dist/*\")\n print(\"V%s Released Success\" % version)\n sys.exit()\n\n\nsetup(\n name='Flask-PluginKit',\n version=version,\n url='https://github.com/staugur/Flask-PluginKit',\n license='MIT',\n author='staugur',\n author_email='staugur@saintic.com',\n keywords=\"flask plugin\",\n description='Load and run plugins for your Flask application',\n long_description=__doc__,\n long_description_content_type=\"text/x-rst\",\n packages=['flask_pluginkit'],\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n install_requires=[\n 'Flask>=0.6',\n 'psutil'\n ],\n cmdclass={\n 'publish': PublishCommand,\n },\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Flask',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"120489379","text":"import numpy as np\nimport ctypes as ct\nimport matplotlib.pyplot as plt\n# For Python under Linux\n#ADQAPI = ct.cdll.LoadLibrary(\"libadq.so\")\n# For Python under Windows\nADQAPI = ct.cdll.LoadLibrary(\"ADQAPI.dll\")\nADQAPI.ADQAPI_GetRevision()\n\n# Manually set return type from some ADQAPI functions\nADQAPI.CreateADQControlUnit.restype = ct.c_void_p\nADQAPI.ADQ_GetRevision.restype = ct.c_void_p\nADQAPI.ADQ_GetPtrStream.restype = ct.POINTER(ct.c_int16)\nADQAPI.ADQControlUnit_FindDevices.argtypes = [ct.c_void_p]\n\n# Create ADQControlUnit\nadq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit())\nADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.')\n\n# Convenience function\ndef adq_status(status):\n if (status==0):\n return 'FAILURE'\n else:\n return 'OK' \n\n# Find ADQ devices\nADQAPI.ADQControlUnit_FindDevices(adq_cu)\nn_of_ADQ = ADQAPI.ADQControlUnit_NofADQ(adq_cu)\nprint('Number of ADQ found: {}'.format(n_of_ADQ))\n\nif n_of_ADQ < 2:\n print('Failed to find two devices, aborting..')\nelse:\n for adq_num in range(1, 3):\n # Get revision info from ADQ\n rev = ADQAPI.ADQ_GetRevision(adq_cu, adq_num)\n revision = ct.cast(rev, ct.POINTER(ct.c_int))\n print('\\nConnected to ADQ #{:d}'.format(adq_num))\n # print('\\nConnected to ADQ #%d'%(adq_num))\n # Print revision information\n print('FPGA Revision: {}'.format(revision[0]))\n if (revision[1]):\n print('Local copy')\n else:\n print('SVN Managed')\n if (revision[2]):\n print('Mixed Revision')\n else:\n print('SVN Updated')\n print('')\n\n # Get serial number and product name from ADQ\n serial_number = ADQAPI.ADQ_GetBoardSerialNumber(adq_cu, adq_num)\n # product_name = ADQ_GetBoardProductName(adq_cu, adq_num)\n print('Board serial number: {}' .format(serial_number))\n # print(\"Board product name: {}\\n\" .format(product_name))\n\n # Set clock source as Internal clock source, external 10 MHz reference\n ADQ_CLOCK_INT_INTREF = 0\n ADQ_CLOCK_INT_EXTREF = 1\n ADQ_CLOCK_EXT = 2\n ADQ_CLOCK_INT_PXIREF = 3\n # clock_source = ADQ_CLOCK_INT_EXTREF # run internal clock with external reference clock for synchronization\n clock_source = ADQ_CLOCK_INT_EXTREF\n success = ADQAPI.ADQ_SetClockSource(adq_cu, adq_num, clock_source)\n if (success == 0):\n print('ADQ_SetClockSource failed.')\n\n ##########################\n # Test pattern\n # ADQAPI.ADQ_SetTestPatternMode(adq_cu, adq_num, 4)\n ##########################\n # Sample skip\n # ADQAPI.ADQ_SetSampleSkip(adq_cu, adq_num, 1)\n ##########################\n\n # Set trig mode\n SW_TRIG = 1\n EXT_TRIG = 2\n LVL_TRIG = 3\n INT_TRIG = 4\n EXT_SYNC = 9\n trigger = EXT_TRIG\n # trigger = SW_TRIG\n success = ADQAPI.ADQ_SetTriggerMode(adq_cu, adq_num, trigger)\n if (success == 0):\n print('ADQ_SetTriggerMode failed.')\n\n # Set Up Collection with MultiRecord\n number_of_records = 1\n samples_per_record = 500 * 10**6\n ADQAPI.ADQ_MultiRecordSetup(adq_cu, adq_num, number_of_records, samples_per_record)\n\n num_devices = 2\n device_data = [None] * num_devices\n figure_toggle = True\n plot_length = 1000\n\n figure_toggle = not figure_toggle\n # Enable Triggers of two ADQ 7\n for adq_num in range(1, num_devices+1):\n ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)\n ADQAPI.ADQ_ArmTrigger(adq_cu, adq_num)\n\n for adq_num in range(1, num_devices+1):\n while(ADQAPI.ADQ_GetAcquiredAll(adq_cu,adq_num) == 0):\n if (trigger == SW_TRIG):\n ADQAPI.ADQ_SWTrig(adq_cu, adq_num)\n print('ADQ #{:d} Waiting for trigger ...'.format(adq_num))\n\n # Setup target buffers for data\n max_number_of_channels = ADQAPI.ADQ_GetNofChannels(adq_cu, adq_num)\n print('Number of channels: {}'.format(max_number_of_channels))\n target_buffers=(ct.POINTER(ct.c_int16*samples_per_record*number_of_records)*max_number_of_channels)()\n for bufp in target_buffers:\n bufp.contents = (ct.c_int16*samples_per_record*number_of_records)()\n\n # Get data from ADQ\n ADQ_TRANSFER_MODE_NORMAL = 0\n ADQ_CHANNELS_MASK = 0xFF\n print('reading data...', end='', flush=True)\n status = ADQAPI.ADQ_GetData(adq_cu, adq_num, target_buffers,\n samples_per_record*number_of_records, 2,\n 0, number_of_records, ADQ_CHANNELS_MASK,\n 0, samples_per_record, ADQ_TRANSFER_MODE_NORMAL)\n print('ADQ_GetData returned {}'.format(adq_status(status)))\n\n # Re-arrange data in numpy arrays\n device_data[adq_num-1] = np.frombuffer(target_buffers[0].contents[0],dtype=np.int16)\n # data_16bit_ch1 = np.frombuffer(target_buffers[1].contents[0],dtype=np.int16)\n # data_16bit_ch2 = np.frombuffer(target_buffers[2].contents[0],dtype=np.int16)\n # data_16bit_ch3 = np.frombuffer(target_buffers[3].contents[0],dtype=np.int16)\n\n # Plot data\n for fig_num in range(2):\n plt.figure('figure_{}'.format(fig_num))\n plt.clf()\n plt.grid()\n for data in device_data:\n if fig_num == 0:\n plt.plot(data[:plot_length])\n else:\n plt.plot(data[-plot_length:])\n # plt.plot(data_16bit_ch1, '.--')\n # plt.plot(data_16bit_ch2, '.--')\n # plt.plot(data_16bit_ch3, '.--')\n\n # plt.show()\n plt.pause(0.1)\n\n # Only disarm trigger after data is collected\n ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)\n ADQAPI.ADQ_MultiRecordClose(adq_cu, adq_num)\n\n # Delete ADQControlunit\n ADQAPI.DeleteADQControlUnit(adq_cu)\n\n print('Done')\n\n\n# This can be used to completely unload the DLL in Windows\n#ct.windll.kernel32.FreeLibrary(ADQAPI._handle)\n","sub_path":"ADQ-PYTHON/ADQ_multirecord_ sync_test.py","file_name":"ADQ_multirecord_ sync_test.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"267264379","text":"class Solution:\n def minSubArrayLen(self, s: int, nums: list) -> int:\n total = left = 0\n result = len(nums)\n for right, n in enumerate(nums):\n total += n\n while total >= s:\n result = min(result, right - left + 1)\n total -= nums[left]\n left += 1\n return result if result <= len(nums) else 0\n\n\nif __name__ == '__main__':\n print(Solution().minSubArrayLen(3, [1, 1]))\n","sub_path":"lecode/Minimum Size Subarray Sum.py","file_name":"Minimum Size Subarray Sum.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"448996119","text":"from flask import Flask, request, redirect, render_template\nfrom flask_sqlalchemy import SQLAlchemy \n\napp = Flask(__name__)\napp.config['DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:admin1@localhost:8889/build-a-blog'\napp.config['SQLALCHEMY_ECHO'] = True\ndb = SQLAlchemy(app)\n\nclass Blog(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(120))\n body = db.Column(db.String(1000))\n\ndef __init__(self, name, body):\n self.name = name\n self.body = body\n \n@app.route('/')\ndef homepage():\n return redirect('/blog')\n\n@app.route('/newpost', methods=['GET'])\ndef new_post():\n return render_template('newpost.html')\n\n@app.route('/newpost', methods=['POST'])\ndef newpost():\n blog_name = request.form['blog']\n body = request.form['body']\n\n if len(blog_name) == 0:\n name_error = \"Title is required\"\n else:\n name_error = \"\"\n\n if len(body) == 0:\n body_error = \"Content is required\"\n else:\n body_error = \"\"\n\n if not name_error and not body_error:\n new_blog = Blog(blog_name,body)\n db.session.add(new_blog)\n db.session.commit()\n blog_id = str(new_blog.id)\n return redirect('/individual?id=' + blog_id)\n else:\n return render_template('newpost.html', blog=blog_name, name_error=name_error, body=body, body_error=body_error)\n\n\n@app.route('/blog')\ndef index():\n if request.args.get('id'):\n blog_id = request.args.get('id')\n blog = Blog.query.get(blog_id)\n return render_template('individual.html', blog=blog)\n \n blogs = Blog.query.all()\n return render_template('blog.html', blogs=blogs)\n\n\n@app.route('/individual')\ndef individual_blog():\n blog_id = request.args.get('id')\n blog = Blog.query.get(blog_id)\n return render_template('individual.html', blog=blog)\n\nif __name__ == '__main__':\n app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"452352837","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom tasks.models import ContestUser\nfrom userprofile.models import Team\nimport random\nfrom django.db.models import Q\nfrom django.db.models.functions import datetime\nfrom django.utils import timezone\nfrom .forms import ContestRegister\nfrom django.contrib.auth.decorators import login_required\nfrom tasks.models import Theme, TaskCase, Solution, Contest, Rang, TaskContestCase, Message, GlobalThemeName\nfrom checker.virdicts import Virdict\nfrom .forms import CheckForm\nimport logging\nimport time\nfrom django.db.models import Q\n# Get an instance of a logger\nlogger = logging.getLogger('ok')\ndef check(task, user):\n if Solution.objects.filter(username=user, task=task.task, verdict = Virdict.ACCEPTED).exists():\n return 1\n if Solution.objects.filter(username=user, task=task.task).exists():\n return 2\n return 0\ndef solved(task):\n return len(Solution.objects.filter(task=task.task, verdict = Virdict.ACCEPTED))\ndef submited(task):\n return len(Solution.objects.filter(task=task.task))\ndef check_team(task, team):\n fl = 0\n for user in team.users.all():\n if Solution.objects.filter(username=user, task=task.task, verdict = Virdict.ACCEPTED).exists():\n return 1\n if Solution.objects.filter(username=user, task=task.task).exists():\n fl = 2\n return fl\n\ndef get_theme_queryset(query=None):\n queryset = []\n queries = query.split(\" \")\n for q in queries:\n themes = Theme.objects.filter(\n Q(name__icontains=q)\n ).distinct()\n for theme in themes:\n queryset.append(theme)\n return list(set(queryset))\ndef hard(t):\n return GlobalThemeName.objects.get(global_them=t.general_theme.all()[0], theme=t).hardness\ndef progress(t, request):\n cnt_all = 0\n cnt = 0\n\n for i in t.tasks.all():\n cnt_all += 1\n if (Solution.objects.filter(verdict=Virdict.ACCEPTED).filter(username=request.user).filter(task=i).count() > 0):\n cnt += 1\n return int(cnt * 100 / cnt_all)\n@login_required(login_url='../../auth/login/')\ndef themes(request):\n themes = Theme.objects.all()\n themes_clean = [(hard(theme), theme, progress(theme, request)) for theme in themes]\n if request.GET:\n query = request.GET['q']\n themes = get_theme_queryset(query)\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/index.html', context={'themes': themes, 'user': request.user})\n return render(request, 'contest/index.html', context={'themes': themes_clean, 'user': request.user})\n\n@login_required(login_url='../../../auth/login/')\ndef theme(request, theme_name):\n tasks = [[check(task, request.user), task, solved(task), submited(task)] for task in TaskCase.objects.filter(theme__name=theme_name).all()]\n context = {\"theme\": tasks, \"user\": request.user}\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/theme.html', context)\n return render(request, 'contest/theme.html', context)\n\n@login_required(login_url='../../../auth/login')\ndef contests(request):\n contests = Contest.objects.filter(finishDate__date__gte=datetime.timezone.now())\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/contests.html', context={'contests' : contests, 'user' : request.user})\n return render(request, 'contest/contests.html', context={'contests' : contests, 'user' : request.user})\n\n@login_required(login_url='../../../auth/login')\ndef contest(request, contest_name):\n\n\n now = timezone.now()\n contest = Contest.objects.get(name = contest_name)\n if request.method == \"POST\":\n team = Team.objects.get(pk=request.POST['team'])\n new_contest_user = ContestUser(team = team, user = request.user, point=0, contest = contest)\n new_contest_user.save()\n if now > contest.startDate and now < contest.finishDate:\n if len(ContestUser.objects.filter(contest=contest, user=request.user).all()) == 0:\n return render(request, 'contest/ContestRegister.html', context={'form' : ContestRegister(user=request.user)})\n team = ContestUser.objects.filter(contest=contest, user=request.user).all()[0].team\n score = 0\n Mayscore = 0\n for task in contest.tasks.all():\n mfl = False\n sfl = False\n for user in team.users.all():\n if not sfl and Solution.objects.filter(username = user).filter(verdict = Virdict.ACCEPTED).filter(task = task).exists():\n score += TaskContestCase.objects.get(task=task, contest__name=contest_name).points\n sfl = True\n if not mfl and Solution.objects.filter(username = user).filter(Q(verdict = Virdict.ACCEPTED_FOR_EVUALETION_IN_CONTEST) | Q(verdict = Virdict.ACCEPTED) | Q(verdict = Virdict.ACCEPTED_FOR_EVUALETION)).filter(task = task).exists():\n Mayscore += TaskContestCase.objects.get(task=task, contest__name=contest_name).points\n mfl = True\n tasks = [[check_team(task, team), task, solved(task), submited(task)] for task in TaskContestCase.objects.filter(contest__name=contest_name).all()]\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/contest.html', context={'tasks' : tasks, 'user' : request.user, 'score' : score, 'Mayscore' : Mayscore, 'name' : tasks[0][1].contest.name})\n return render(request, 'contest/contest.html', context={'tasks' : tasks, 'user' : request.user, 'score' : score, 'Mayscore' : Mayscore, 'name' : tasks[0][1].contest.name})\n return render(request, 'contest/solutionError.html')\n\n\n@login_required(login_url='../../auth/login/')\ndef solutions(request):\n solutions = Solution.objects.all()\n need = []\n for sol in solutions:\n if len(sol.task.theme_set.all()) == 0:\n continue\n theme = sol.task.theme_set.all()[0]\n global_theme = theme.general_theme.all()[0]\n rang = 10000\n if rang > sol.need_rang and sol.username != request.user and (sol.verdict == Virdict.ACCEPTED_FOR_EVUALETION or sol.verdict == Virdict.APPLICATION or sol.verdict == Virdict.ACCEPTED_FOR_EVUALETION):\n need.append(sol)\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/solutions.html', context={'submits': need, 'user' : request.user})\n return render(request, 'contest/solutions.html', context={'submits': need, 'user' : request.user})\n\n@login_required(login_url='../../../auth/login/')\ndef solution(request, submit_id):\n submit = Solution.objects.get(id=submit_id)\n if (submit.username == request.user):\n if (submit.verdict == Virdict.REJECTED):\n if (request.method == 'POST'):\n form = CheckForm(request.POST)\n if form.is_valid():\n new_message = Message(text=form.cleaned_data['comment'])\n new_message.save()\n submit.verdict = Virdict.APPLICATION\n submit.comments.add(new_message)\n submit.need_rang += 1\n submit.save()\n return redirect('/themes/solutions')\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/ownSolutionJudgeReject.html', context={'submit': submit, 'user' : request.user, 'form' : CheckForm()})\n return render(request, 'contest/ownSolutionJudgeReject.html', context={'submit': submit, 'user' : request.user, 'form' : CheckForm()})\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/ownSolutionJudge.html', context={'submit': submit, 'user' : request.user})\n return render(request, 'contest/ownSolutionJudge.html', context={'submit': submit, 'user' : request.user})\n if (submit.verdict != Virdict.ACCEPTED_FOR_EVUALETION and submit.verdict != Virdict.APPLICATION):\n \treturn render(request, 'contest/ContestError.html')\n theme = submit.task.theme_set.all()[0]\n global_theme = theme.general_theme.all()[0]\n rang = 0\n try:\n rang = Rang.objects.get(user=request.user, theme=global_theme).point\n except:\n pass\n\n if (request.method == 'POST'):\n form = CheckForm(request.POST)\n if form.is_valid():\n new_message = Message(text=form.cleaned_data['comment'])\n new_message.save()\n if 'OK' in request.POST:\n logs = open(\"okknig\", 'a')\n logs.write(\"{} сдал задачу из темы {} под названием {}. Принимал {}. Время {}\".format(submit.username.username, theme.name, submit.task.title, request.user.username, time.time()))\n logs.close()\n submit.task.solvers.add(request.user)\n submit.verdict = Virdict.ACCEPTED\n submit.comments.add(new_message)\n else:\n submit.verdict = Virdict.REJECTED\n submit.comments.add(new_message)\n submit.save()\n return redirect('/themes/solutions')\n if (request.user_agent.is_mobile):\n return render(request, 'contest/mobile/solutionJudge.html', context={'submit': submit, 'form' : CheckForm(), 'user' : request.user})\n return render(request, 'contest/solutionJudge.html', context={'submit': submit, 'form' : CheckForm(), 'user' : request.user})\n\n","sub_path":"contest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"181223824","text":"# mac_specific.py\r\n# The Raskin Center for Humane Interfaces (RCHI) 2004-2005\r\n\r\nVERSION = \"$Id: mac_specific.hpy,v 1.11 2005/04/01 22:22:32 varmaa Exp $\"\r\n\r\n# This module is the Macintosh (OS X) implementation of the\r\n# [os]_specific modules.\r\n\r\n# --------------------------\r\n# Clipboard\r\n# --------------------------\r\n\r\n# MacOS clipboard integration without dependencies, taken from\r\n# http://www.macdrifter.com/2011/12/python-and-the-mac-clipboard.html\r\n\r\nimport subprocess\r\n\r\ndef getClipboard():\r\n p = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)\r\n retcode = p.wait()\r\n data = p.stdout.read()\r\n return data\r\n\r\ndef setClipboard(data):\r\n p = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)\r\n p.stdin.write(data)\r\n p.stdin.close()\r\n retcode = p.wait()\r\n\r\n\r\n# --------------------------\r\n# Key bindings\r\n# --------------------------\r\n\r\n# We need to guarantee that keybindings are set appropriately.\r\n# We here establish some accessible constants that key.py will\r\n# call when establishing keybindings.\r\n\r\nStart_LEAP_Forward_Keybinding = 'right alt\\\\' \r\nEnd_LEAP_Forward_Keybinding = 'right alt/' \r\nLEAP_Forward_Select_Keybinding = 'left alt\\\\'\r\nStart_LEAP_Backward_Keybinding = 'left alt\\\\'\r\nEnd_LEAP_Backward_Keybinding = 'left alt/'\r\nLEAP_Backward_Select_Keybinding = 'right alt\\\\'\r\n\r\n\r\nStart_Command_Keybinding = 'left ctrl\\\\'\r\nEnd_Command_Keybinding = 'left ctrl/'\r\n\r\nDelete_Keybinding = 'backspace\\\\'\r\n\r\nCreep_Left_Keybinding = 'left\\\\'\r\nCreep_Right_Keybinding = 'right\\\\'\r\n\r\n# --------------------------\r\n# Fonts\r\n# --------------------------\r\n\r\nDefault_Font = {'size' : 16, 'font' : 'sans'}\r\nQuasimode_Font = {'size' : 30, 'font' : 'sans', 'outline': 1}\r\n","sub_path":"mac_specific.py","file_name":"mac_specific.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"464684149","text":"import matplotlib.pyplot as plt\nfrom maze_plot import *\nfrom get_neighbors import *\nimport numpy as np\nfrom collections import deque\n\ndef bfs_path(bfs_maze, cur_node, bfs_parent):\n bfs_maze[len(bfs_maze)-1, len(bfs_maze)-1] = -2\n count = 2\n temp_node = cur_node\n while temp_node != (0,0):\n bfs_maze[temp_node] = -2\n (i,j) = temp_node\n temp_node = bfs_parent[i][j]\n count += 1\n count += 1\n bfs_maze[0,0] = -2\n print(\"Path length : \",count)\n maze_plot_final(bfs_maze,\"b\")\n return\n\n\ndef breadth_first_search(bfs_maze,display=True):\n bfs_maze=bfs_maze.copy()\n source = (0,0)\n goal = (len(bfs_maze)-1, len(bfs_maze)-1)\n bfs_maze[source] = -1\n bfs_visited = np.zeros((len(bfs_maze), len(bfs_maze)), dtype = int)\n bfs_queue = deque([source])\n neighbors = []\n flag = 0\n bfs_parent = [[None for _ in range(len(bfs_maze))] for _ in range(len(bfs_maze))]\n #bfs_parent[] = source\n\n while len(bfs_queue) != 0 and flag == 0:\n\n cur_node = bfs_queue.popleft()\n bfs_maze[cur_node] = -2\n neighbors = traversable_neighbors(bfs_maze, cur_node)\n if len(neighbors) != 0:\n for node in neighbors:\n (i,j) = node\n if node == goal:\n flag = 1\n if display:\n bfs_path(bfs_maze, cur_node, bfs_parent)\n break\n return 1\n if bfs_parent[i][j] == None:\n bfs_parent[i][j] = cur_node\n bfs_queue.append(node)\n bfs_maze[cur_node] = -1\n\n if flag == 0:\n if display:\n print(\"No Path Found :(\")\n maze_plot_final(bfs_maze)\n return 0\n","sub_path":"breadth_first_search.py","file_name":"breadth_first_search.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"385874679","text":"#!/usr/bin/python\n\"\"\"\n description: A basic http server\n author : Ashwani Singh\n created on : 24 Nov, 2015\n\"\"\"\n\nfrom http.server import HTTPServer, CGIHTTPRequestHandler\nfrom optparse import OptionParser\n\n\nclass BasicHttpServer:\n port = 8080\n host = '127.0.0.1'\n httpd = None\n\n def __init__(self, hostname='127.0.0.1', portno=8080):\n self.port = int(portno)\n self.host = hostname\n self.create()\n\n def create(self):\n httpd = HTTPServer((self.host, self.port), CGIHTTPRequestHandler)\n self.httpd = httpd\n\n def start(self):\n print(\"Starting simple http server on %s:%d\" % (self.host, self.port))\n self.httpd.serve_forever()\n\n\"\"\"\n Main function\n\"\"\"\n\n\ndef main():\n usage = \"usage: %prog [options] arg\"\n parser = OptionParser(usage)\n parser.add_option(\"-a\", \"--hostname\", action=\"store\", dest=\"hostname\",\n default='127.0.0.1', help=\"hostname for server defaults to 127.0.0.1\")\n parser.add_option(\"-p\", \"--port\", action=\"store\", dest=\"port\",\n default=8080, help=\"port for server defaults to 8080\")\n parsed_options,parsed_args = parser.parse_args()\n\n host = parsed_options.hostname if parsed_options.hostname else '127.0.0.1'\n port = int(parsed_options.port) if parsed_options.port else 8080\n\n try:\n # creating new simple http server\n http_server = BasicHttpServer(host, port)\n http_server.start()\n except OSError as oserr:\n print(\"Failed to start server on %s:%d\" % (host, int(port)))\n print(\"OS Error: \" + str(oserr))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"PycharmProjects/samp_proj1/venv/lib/python3.5/site-packages/BasicHttpServer.py","file_name":"BasicHttpServer.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"608967220","text":"# -*- coding: utf-8 -*-\nimport pprint\nfrom openeo_core.jobs_job_id import GET_JOBS_ID_DOC, DELETE_JOBS_ID_DOC\nfrom openeo_core.jobs_job_id import JobsJobId\nfrom graas_openeo_core_wrapper.graas_interface import GRaaSInterface\nfrom flask import make_response, jsonify\nfrom flask_restful_swagger_2 import swagger\nfrom graas_openeo_core_wrapper.graph_db import GraphDB\n\n__license__ = \"Apache License, Version 2.0\"\n__author__ = \"Sören Gebbert\"\n__copyright__ = \"Copyright 20186, Sören Gebbert\"\n__maintainer__ = \"Soeren Gebbert\"\n__email__ = \"soerengebbert@googlemail.com\"\n\n\nclass GRaaSJobsJobId(JobsJobId):\n\n def __init__(self):\n self.iface = GRaaSInterface()\n self.db = GraphDB()\n\n @swagger.doc(GET_JOBS_ID_DOC)\n def get(self, job_id):\n\n try:\n status, response = self.iface.resource_info(job_id)\n if status == 200:\n process_graph = self.db[job_id]\n\n info = dict(job_id=job_id,\n user_id=response[\"user_id\"],\n status=response[\"status\"],\n process_graph=process_graph,\n submitted=response[\"accept_datetime\"],\n last_update=response[\"datetime\"],\n consumed_credits=response[\"time_delta\"],\n job_info=response)\n\n if \"urls\" in response and \"resources\" in response[\"urls\"]:\n info[\"resources\"] = response[\"urls\"][\"resources\"]\n\n return make_response(jsonify(info), 200)\n else:\n process_graph = self.db[job_id]\n info = dict(job_id=job_id,\n status=\"error\",\n process_graph=process_graph,\n job_info=response)\n\n return make_response(jsonify(info), status)\n except Exception as e:\n return make_response(jsonify({\"error\": str(e)}), 500)\n\n @swagger.doc(DELETE_JOBS_ID_DOC)\n def delete(self, job_id):\n\n try:\n status, response = self.iface.resource_info(job_id)\n\n if status == 200:\n\n process_graph = self.db[job_id]\n info = dict(job_id=job_id,\n user_id=\"scheduled\",\n status=\"submitted\",\n process_graph=process_graph,\n submitted=response[\"accept_datetime\"],\n last_update=response[\"datetime\"],\n consumed_credits=response[\"time_delta\"],\n job_info=response)\n\n status, response = self.iface.delete_resource(job_id)\n if status != 200:\n process_graph = self.db[job_id]\n info = dict(job_id=job_id,\n status=\"error\",\n process_graph=process_graph,\n job_info=response)\n return make_response(jsonify(info), status)\n else:\n process_graph = self.db[job_id]\n info = dict(job_id=job_id,\n status=\"error\",\n process_graph=process_graph,\n job_info=response)\n\n return make_response(jsonify(info), status)\n except Exception as e:\n return make_response(jsonify({\"error\": str(e)}), 500)\n","sub_path":"src/graas_openeo_core_wrapper/jobs_job_id.py","file_name":"jobs_job_id.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"80446983","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2020, Geoffrey M. Poore\n# All rights reserved.\n#\n# Licensed under the BSD 3-Clause License:\n# http://opensource.org/licenses/BSD-3-Clause\n#\n\n\nfrom .quiz import Quiz\n\n\nBEFORE_ITEMS = '''\\\n\n\n \n \n \n cc_maxattempts\n 1\n \n \n
    \n'''\n\nAFTER_ITEMS = '''\\\n
    \n
    \n
    \n'''\n\n\nSTART_ITEM = '''\\\n \n'''\n\nEND_ITEM = '''\\\n \n'''\n\n\nITEM_METADATA = '''\\\n \n \n \n question_type\n {question_type}\n \n \n points_possible\n {points_possible}\n \n \n original_answer_ids\n {original_answer_ids}\n \n \n assessment_question_identifierref\n {assessment_question_identifierref}\n \n \n \n'''\n\n\nITEM_PRESENTATION = '''\\\n \n \n {question_xml}\n \n \n \n{choices}\n \n \n \n'''\n\nITEM_PRESENTATION_CHOICE = '''\\\n \n \n {choice_xml}\n \n '''\n\n\nITEM_RESPROCESSING_START = '''\\\n \n \n \n \n'''\n\nITEM_RESPROCESSING_GENERAL_FEEDBACK = '''\\\n \n \n \n \n \n \n'''\n\nITEM_RESPROCESSING_CHOICE_FEEDBACK = '''\\\n \n \n {ident}\n \n \n \n'''\n\nITEM_RESPROCESSING_SET_CORRECT_WITH_FEEDBACK = '''\\\n \n \n {ident}\n \n 100\n \n \n'''\n\nITEM_RESPROCESSING_SET_CORRECT_NO_FEEDBACK = '''\\\n \n \n {ident}\n \n 100\n \n'''\n\nITEM_RESPROCESSING_INCORRECT_FEEDBACK = '''\\\n \n \n \n \n \n \n'''\n\nITEM_RESPROCESSING_END = '''\\\n \n'''\n\n\nITEM_FEEDBACK_GENERAL = '''\\\n \n \n \n {feedback}\n \n \n \n'''\n\nITEM_FEEDBACK_CORRECT = '''\\\n \n \n \n {feedback}\n \n \n \n'''\n\nITEM_FEEDBACK_INCORRECT = '''\\\n \n \n \n <p>Wrong comment</p>\n \n \n \n'''\n\nITEM_FEEDBACK_INDIVIDUAL = '''\\\n \n \n \n {feedback}\n \n \n \n'''\n\n\n\n\ndef assessment(*, quiz: Quiz, assessment_identifier: str, title: str) -> str:\n '''\n Generate assessment XML from Quiz.\n '''\n xml = []\n xml.append(BEFORE_ITEMS.format(assessment_identifier=assessment_identifier,\n title=title))\n for question in quiz.questions:\n correct_choice = None\n for choice in question.choices:\n if choice.correct:\n correct_choice = choice\n break\n if correct_choice is None:\n raise TypeError\n\n xml.append(START_ITEM.format(question_identifier=f'text2qti_question_{question.id}',\n question_title=question.title_xml))\n\n xml.append(ITEM_METADATA.format(question_type=question.type,\n points_possible=question.points_possible,\n original_answer_ids=','.join(f'text2qti_choice_{c.id}' for c in question.choices),\n assessment_question_identifierref=f'text2qti_question_ref_{question.id}'))\n\n choices = '\\n'.join(ITEM_PRESENTATION_CHOICE.format(ident=f'text2qti_choice_{c.id}', choice_xml=c.choice_xml)\n for c in question.choices)\n xml.append(ITEM_PRESENTATION.format(question_xml=question.question_xml,\n choices=choices))\n\n resprocessing = []\n resprocessing.append(ITEM_RESPROCESSING_START)\n if question.feedback_raw is not None:\n resprocessing.append(ITEM_RESPROCESSING_GENERAL_FEEDBACK)\n for choice in question.choices:\n if choice.feedback_raw is not None:\n resprocessing.append(ITEM_RESPROCESSING_CHOICE_FEEDBACK.format(ident=f'text2qti_choice_{choice.id}'))\n if question.correct_feedback_raw is not None:\n resprocessing.append(ITEM_RESPROCESSING_SET_CORRECT_WITH_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}'))\n else:\n resprocessing.append(ITEM_RESPROCESSING_SET_CORRECT_NO_FEEDBACK.format(ident=f'text2qti_choice_{correct_choice.id}'))\n if question.incorrect_feedback_raw is not None:\n resprocessing.append(ITEM_RESPROCESSING_INCORRECT_FEEDBACK)\n resprocessing.append(ITEM_RESPROCESSING_END)\n xml.append(''.join(resprocessing))\n\n if question.feedback_raw is not None:\n xml.append(ITEM_FEEDBACK_GENERAL.format(feedback=question.feedback_xml))\n if question.correct_feedback_raw is not None:\n xml.append(ITEM_FEEDBACK_CORRECT.format(feedback=question.correct_feedback_xml))\n if question.incorrect_feedback_raw is not None:\n xml.append(ITEM_FEEDBACK_INCORRECT.format(feedback=question.incorrect_feedback_xml))\n for choice in question.choices:\n if choice.feedback_raw is not None:\n xml.append(ITEM_FEEDBACK_INDIVIDUAL.format(ident=f'text2qti_choice_{choice.id}',\n feedback=choice.feedback_xml))\n\n xml.append(END_ITEM)\n\n xml.append(AFTER_ITEMS)\n\n return ''.join(xml)\n","sub_path":"text2qti/xml_assessment.py","file_name":"xml_assessment.py","file_ext":"py","file_size_in_byte":8487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"145726943","text":"\"\"\"General utility functions.\"\"\"\nimport contextlib\nfrom asyncio import ensure_future\nfrom functools import partial\nimport datetime\nfrom util.commands.errors import PassException\ndef bdel(s, r): return (s[len(r):] if s.startswith(r) else s)\n\nclass DiscordFuncs():\n def __init__(self, bot):\n self.bot = bot\n def __getattr__(self, name):\n new_func = None\n coro = getattr(self.bot, name)\n if not callable(coro):\n raise AttributeError('Class can only access client functions')\n def async_wrap(coro, *args, **kwargs):\n ensure_future(coro(*args, **kwargs))\n new_func = partial(async_wrap, coro)\n new_func.__name__ = coro.__name__\n new_func.__qualname__ = coro.__qualname__\n return new_func\n\ndef _import(mod_name, var_name=None, attr_name=''):\n ret = \"globals()['{}'] = imp('{}')\"\n if var_name:\n if attr_name:\n attr_name = '.' + attr_name\n ret = ret.format(var_name, mod_name) + attr_name\n else:\n ret = ret.format(mod_name, mod_name)\n return ret\n\n\ndef _set_var(var_name, expr):\n return \"globals()['{}'] = {}\".format(var_name, expr)\n\ndef _del_var(var_name):\n return \"del globals()['{}']\".format(var_name)\n\nsnowtime = lambda i: datetime.datetime.fromtimestamp(((float(int(i)) / 4194304.0) + 1420070400000.0 + 18000000.0) / 1000.0).strftime('%a %b %d, %Y %I:%M:%S %p')\n\nclass PrintException(Exception):\n \"\"\"An exception that prints the error.\"\"\"\n def __init__(self, err):\n print(str(err))\n self.err = err\n super().__init__()\n\n@contextlib.contextmanager\ndef assert_msg(ctx, msg: str):\n \"\"\"Assert. If error, send msg.\"\"\"\n try:\n yield\n except AssertionError:\n ensure_future(ctx.bot.send_message(ctx.message.channel, msg))\n raise PassException()\n","sub_path":"util/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"25737943","text":"# Copyright 2019 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 unittest\nimport json\nfrom table_validator.utils import bigquery_utils\nfrom google.cloud import bigquery\n\n\nclass TestUtils(unittest.TestCase):\n\n def __init__(self, config_file):\n super().__init__()\n with open(config_file) as json_file:\n self.config_data = json.load(json_file)\n self.verify_config()\n\n def verify_config(self):\n \"\"\"\n This method will verify the format of the config file. If anything is out of the ordinary\n format it will let the user know.\n \"\"\"\n if (self.config_data['leftTablename'].count('.') or self.config_data['rightTablename'].count('.')) != (2 or 1) and self.config_data['leftTablename'].count('.') == self.config_data['rightTablename'].count('.'):\n ValueError('Your configuration file tablenames are not correctly formatted table should be in the format '\n '`[dataset name].[table name]` or `[project name].[dataset name].[table name]`')\n if 'leftDatasetname' in self.config_data.keys() and 'rightDatasetname' in self.config_data.keys():\n if (self.config_data['leftDatasetname'].count('.') or self.config_data['rightDatasetname'].count('.')) != (1 or 0) and self.config_data['leftDatasetname'].count('.') == self.config_data['rightDatasetname'].count('.'):\n ValueError('Your configuration file datasetnames are not correctly formatted table should be in the '\n 'format `[dataset name]` or `[project name].[dataset name]` in leftDatasetname and '\n 'rightDatasetname')\n if self.config_data['destinationDataset'].count('.') > 0:\n ValueError('destinationDataset should not have any `.`')\n\n lproject_id, rproject_id = '', ''\n if self.config_data['leftTablename'].count('.') == 2:\n lproject_id, ldataset, ltablename = self.config_data['leftTablename'].split('.')\n rproject_id, rdataset, rtablename = self.config_data['rightTablename'].split('.')\n else:\n ldataset, ltablename = self.config_data['leftTablename'].split('.')\n rdataset, rtablename = self.config_data['rightTablename'].split('.')\n self.left_tablename = ldataset + '.' + ltablename\n self.right_tablename = rdataset + '.' + rtablename\n if 'leftDatasetname' in self.config_data.keys() and self.config_data['leftDatasetname'].count('.') == 1:\n lproject_id, _ = self.config_data['leftDatasetname'].split('.')\n rproject_id, _ = self.config_data['rightDatasetname'].split('.')\n if lproject_id != rproject_id:\n ValueError('Project names in tablenames and datasetnames should be equal')\n self.client = bigquery.Client(project=self.config_data['project_id'])\n\n def test_compare_columns(self):\n self.assertTrue(\n bigquery_utils.compare_columns([3, 2, 1],\n [3, 2, 1]), msg='two columns are not equal')\n self.assertFalse(\n bigquery_utils.compare_columns(['1', '2', '3'],\n ['3', '2']), msg='two columns are equal')\n\n def test_get_console_link_for_table_ref_and_get_table_ref_and_query_job_link(self):\n\n left_table = bigquery_utils.get_table_ref(self.client,\n self.left_tablename)\n right_table = bigquery_utils.get_table_ref(self.client,\n self.right_tablename)\n self.assertTrue(left_table)\n self.assertFalse(\n bigquery_utils.get_table_ref(self.client,\n self.config_data['project_id']))\n self.assertTrue(right_table)\n self.assertTrue(\n bigquery_utils.get_console_link_for_table_ref(left_table))\n self.assertRaises(\n bigquery_utils.get_console_link_for_table_ref(left_table))\n self.assertTrue(\n bigquery_utils.get_console_link_for_table_ref(right_table))\n\n job_config = bigquery.QueryJobConfig()\n table_ref = bigquery_utils.get_table_ref(self.client, self.config_data['destinationDataset'])\n destination_dataset = self.config_data['destinationDataset']\n destination_table = '{}.{}'.format(destination_dataset, self.left_tablename.split('.')[1])\n\n print('Creating ( {} )'.format(destination_table.split('.')[1]))\n if table_ref:\n job_config.destination = table_ref\n job_config.write_disposition = 'WRITE_TRUNCATE'\n\n # Start the query, passing in the extra configuration.\n query_job = self.client.query('SELECT word, SUM(word_count) AS count FROM '\n '`bigquery-public-data`.samples.shakespeare WHERE word LIKE \"%raisin%\" GROUP BY'\n ' word', job_config=job_config)\n query_link = bigquery_utils.get_console_link_for_query_job(query_job)\n self.assertTrue(query_link)\n print('View Query\\n{}'.format(query_link))\n\n def get_full_columns_list(self):\n self.assertTrue(\n bigquery_utils.get_full_columns_list(self.client, self.config_data['excludeColumnMapping'],\n self.config_data['primaryKeys'], self.left_tablename,\n self.right_tablename)\n )\n","sub_path":"tools/table_validator/tests/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":5989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"158484148","text":"from flask import Flask\n\n\ndef create_app():\n app = Flask('hello-service')\n\n @app.route('/')\n def hello():\n return \"Hello World!\\n\"\n\n return app\n\n\nif __name__ == '__main__':\n app = create_app()\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"184691424","text":"from __future__ import print_function\n\nimport fontforge\nfrom math import radians\nfrom psMat import translate\nfrom sys import argv\n\nclass Stroker(object):\n def __init__(self, fontname):\n self.fontname = fontname\n self.dotwidth = max(0, 100 - self.nibwidth)\n self.dotheight = max(0, 100 - self.nibheight)\n def modify_font(self, f):\n f.strokedfont = False\n\n for g in f.glyphs():\n for i, c in enumerate(list(g.layers[1])):\n newc = self.adjust_contour(c)\n if newc != None: g.layers[1] += newc\n g.stroke(*self.nib)\n g.removeOverlap()\n g.addExtrema()\n g.transform(translate(0, self.nibheight/2.0))\n\n f.familyname = self.familyname\n f.fontname = self.fontname\n f.fullname = self.fullname\n f.appendSFNTName('English (US)', 'Preferred Family', self.familyname)\n f.private['StdHW'] = self.nibheight\n f.private['StdVW'] = self.nibwidth\n def adjustblue(y): return y - 100 + self.nibheight\n bv = list(f.private['BlueValues'])\n bv[1:] = map(adjustblue, bv[1:])\n f.private['BlueValues'] = tuple(bv)\n f.uwidth = self.nibheight\n f.os2_weight = self.ttfweight\n f.weight = self.weight\n return f\n def adjust_contour(self, c):\n # This function just expands dots.\n if len(c) != 1: return None\n if self.dotwidth == 0 and self.dotheight == 0: return None\n newc = fontforge.contour()\n newc.moveTo(c[0].x + self.dotwidth/2, c[0].y)\n newc.lineTo(c[0].x, c[0].y + self.dotheight/2)\n newc.lineTo(c[0].x - self.dotwidth/2, c[0].y)\n newc.lineTo(c[0].x, c[0].y - self.dotheight/2)\n newc.closed = True\n return newc\n \nclass Plotter(Stroker):\n familyname = \"Bedstead Plotter\"\n def __init__(self, penwidth, weight, ttfweight):\n self.nib = ['circular', penwidth, 'round', 'round']\n self.nibwidth = self.nibheight = penwidth\n self.fontname = \"BedsteadPlotter-\" + weight\n self.fullname = \"%s %s\" % (self.familyname, weight)\n self.ttfweight = ttfweight\n self.weight = weight\n super(Plotter, self).__init__(\"BedsteadPlotter-\" + weight)\n\nclass Chiseltip(Stroker):\n familyname = \"Bedstead Chiseltip\"\n fullname = \"Bedstead Chiseltip\"\n weight = \"Medium\"\n ttfweight = 500\n def __init__(self):\n chisel = fontforge.contour()\n chisel.moveTo(-56, 7)\n chisel.lineTo(39, 41)\n chisel.lineTo(56, -7)\n chisel.lineTo(-39, -41)\n chisel.closed = True\n self.nib = ['polygonal', chisel]\n self.nibwidth = 112\n self.nibheight = 82\n super(Chiseltip, self).__init__(\"BedsteadChiseltip\")\n\nmodes = {\n 'plotter-thin': Plotter(10, \"Thin\", 100),\n 'plotter-light': Plotter(50, \"Light\", 300),\n 'plotter-medium': Plotter(100, \"Medium\", 500),\n 'plotter-bold': Plotter(150, \"Bold\", 700),\n 'chiseltip': Chiseltip(),\n}\n\nmode = modes[argv[1]]\n\nf = fontforge.open(argv[2])\n\nmode.modify_font(f)\n\nf.save(argv[3])\n\n","sub_path":"strokefont.py","file_name":"strokefont.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"407657526","text":"def get_opcode(file_name):\n\twith open(file_name, \"r\") as input_file:\n\t\tinput_string = input_file.read()\n\t\treturn list(map(int, input_string.split(\",\")))\n\n\ndef set_element(list, position, element):\n\twhile len(list) < position + 1:\n\t\tlist.append(0)\n\tlist[position] = element\n\ndef get_element(list, position):\n\tif position > len(list) - 1:\n\t\treturn 0\n\treturn list[position]\n\ndef get_position(opcode, i, operation, mode, position, offset):\n\t# literal mode: \n\tif (position == \"3\" and operation not in []) or (position == \"1\" and operation in [\"3\"]):\n\t\tif mode in [\"0\", \"1\"]:\n\t\t\treturn i + position\n\t\treturn i + position + offset\n\t\t\n\tif mode == \"0\":\n\t\treturn get_element(opcode, i + position)\n\tif mode == \"1\":\n\t\treturn i + position\n\tif mode == \"2\":\n\t\treturn get_element(opcode, i + position) + offset\n\t\n\ndef iterate_opcode(opcode, input_queue=[]):\n\t# opcode position\n\ti = 0\n\toffset = 0\n\n\twhile True:\n\t\tfull_operation = str(get_element(opcode, i)).rjust(5, '0')\n\t\toperation = full_operation[3:5]\n\n\n\t\t# end\n\t\tif operation == \"99\":\n\t\t\tyield None\n\n\t\tpos1 = get_position(opcode, i, operation, full_operation[2], 1, offset)\n\t\t\n\t\tif operation not in [\"03\", \"04\", \"09\"]:\n\t\t\tpos2 = get_position(opcode, i, operation, full_operation[1], 2, offset)\n\t\t\n\t\t\tif operation not in [\"05\", \"06\"]:\n\t\t\t\tpos3 = get_position(opcode, i, operation, full_operation[0], 3, offset)\n\n\t\t# add\n\t\tif operation == \"01\":\n\t\t\tset_element(opcode, pos3, get_element(opcode, pos1) + get_element(opcode, pos2))\n\n\t\t\tif str(get_element(opcode, i)).rjust(5, '0') == full_operation:\n\t\t\t\ti += 4\n\n\t\t# mult\n\t\telif operation == \"02\":\n\t\t\tset_element(opcode, pos3, get_element(opcode, pos1) * get_element(opcode, pos2))\n\n\t\t\tif str(get_element(opcode, i)).rjust(5, '0') == full_operation:\n\t\t\t\ti += 4\n\n\t\t# input\n\t\telif operation == \"03\":\n\t\t\tif len(input_queue) > 0:\n\t\t\t\tset_element(opcode, pos1, input_queue.pop(0))\n\t\t\telse:\n\t\t\t\tset_element(opcode, pos1, int(input(\"input: \")))\n\n\t\t\tif str(get_element(opcode, i)).rjust(5, '0') == full_operation:\n\t\t\t\ti += 2\n\n\t\t# output\n\t\telif operation == \"04\":\n\t\t\tyield get_element(opcode, pos1)\n\t\t\ti += 2\n\n\t\t# jump if !0\n\t\telif operation == \"05\":\n\t\t\tif get_element(opcode, pos1) != 0:\n\t\t\t\ti = get_element(opcode, pos2)\n\t\t\telse:\n\t\t\t\ti += 3\n\n\t\t# jump if 0\n\t\telif operation == \"06\":\n\t\t\tif get_element(opcode, pos1) == 0:\n\t\t\t\ti = get_element(opcode, pos2)\n\t\t\telse:\n\t\t\t\ti += 3\n\n\t\t# less than\n\t\telif operation == \"07\":\n\t\t\tif get_element(opcode, pos1) < get_element(opcode, pos2):\n\t\t\t\tset_element(opcode, pos3, 1)\n\t\t\telse:\n\t\t\t\tset_element(opcode, pos3, 0)\n\n\t\t\tif str(get_element(opcode, i)).rjust(5, '0') == full_operation:\n\t\t\t\ti += 4\n\n\t\t# equals\n\t\telif operation == \"08\":\n\t\t\tif get_element(opcode, pos1) == get_element(opcode, pos2):\n\t\t\t\tset_element(opcode, pos3, 1)\n\t\t\telse:\n\t\t\t\tset_element(opcode, pos3, 0)\n\n\t\t\tif str(get_element(opcode, i)).rjust(5, '0') == full_operation:\n\t\t\t\ti += 4\n\t\t\n\t\t# offset adjustment\n\t\telif operation == \"09\":\n\t\t\toffset += get_element(opcode, pos1)\n\n\t\t\ti += 2\n\t\t\n\t\t# oopsie\n\t\telse:\n\t\t\tprint(full_operation, i, offset)\n\t\t\tbreak\n\ndef run_opcode(file_name):\n\topcode = get_opcode(file_name)\n\tgen = iterate_opcode(opcode, [2])\n\toutput = [next(gen)]\n\twhile output[-1] != None:\n\t\toutput.append(next(gen))\n\tprint(output)\n\nrun_opcode(\"day9_input.txt\")","sub_path":"solutions/day9-2.py","file_name":"day9-2.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"317758542","text":"\"\"\"\r\nCreated on Sun Jul 27 18:23:34 2019\r\n\r\n@author: Luka\r\n\"\"\"\r\nfrom copy import deepcopy\r\nimport random\r\nimport matplotlib.pyplot as plt \r\nfrom numpy.random import choice\r\nimport numpy as np\r\n#Jedno je fiksna verovatnoća, druga je dve varijable, za explore i exploit (razlika ova dva broja, fermijeva raspodela može beta puta razlika)\r\n#Two types of strategies (da ne bude binarno, može da bude kontinualne, mogu da uče agenti)\r\nstrategy = ['exploit', 'explore'] \r\n#Two personality types (Da ljudi imaju različit parametar za explore, exploit)\r\npersonalities = ['R', 'I']\r\n#Knowledge represents what scientists arleady know so they can exploit a collaboration (da li ima mehanizam kako se znanje stvari\r\n#Koja sveukupna količina znanja? Rekomobinacija znanja? Neko random dodavanje? Da budu integeri potencijalno\r\nknowledge = [[],['A'],['B'],['A','B']]\r\n#Points are accumulated through scientific activity\r\npoints = [1,2,3,4,5]\r\n\r\ndef make_agent(strategy, personality,knowledge,points):\r\n return [strategy,personality,knowledge,points]\r\nprint(type(make_agent('exploit','R',['A'],2)))\r\n\r\n#Creating random population \r\ndef make_population_random(N):\r\n population = []\r\n for i in range(N):\r\n s = random.choice(strategy)\r\n p = random.choice(personalities)\r\n k = random.choice(knowledge)\r\n b = random.choice(points)\r\n agent = make_agent(s,p,k,b)\r\n population.append(agent)\r\n return population\r\n\r\n#Counting average points\r\ndef count(population):\r\n t = 0. \r\n for agent in population:\r\n t += agent[3] \r\n return t / len(population)\r\n\r\n#pop = make_population_random(3)\r\n#print(pop)\r\n#print(count(pop))\r\n\r\n#Choosing two random agents\r\ndef choose_pair(population):\r\n i = random.randint(0, len(population) - 1) \r\n j = random.randint(0, len(population) - 1)\r\n while i == j:\r\n j = random.randint(0, len(population) - 1) # Da ne budu 2 puta\r\n return population[i], population[j] \r\n\r\n\r\n#Interacting two random agents, kako se definiše exploit zapravo, kako se boduje\r\ndef interact(first,second): \r\n if first[0] == \"explore\" and len(first[1]) < 2: #Explore strategy and not full knowledge list\r\n first[2].append(second[2])\r\n elif first[0] == \"exploit\": # Exploit strategy\r\n if first[2]==second[2]:\r\n first[3]+= random.randint(1,4)\r\n second[3]+=random.randint(1,4)\r\n else:\r\n pass \r\n \r\n# explore test\r\n#Agent1 = ['explore','R',['A'],2]\r\n#Agent2 = ['exploit','R',['B'],2]\r\n#print(Agent1)\r\n#print(Agent2)\r\n#interact(Agent1,Agent2)\r\n#print(Agent1)\r\n#print(Agent2)\r\n##exploit test\r\n#Agent1 = ['exploit','R',['A'],2]\r\n#Agent2 = ['exploit','R',['A'],2]\r\n#print(Agent1)\r\n#print(Agent2)\r\n#interact(Agent1,Agent2)\r\n#print(Agent1)\r\n#print(Agent2)\r\n\r\ndef simulate(n, k):\r\n population = make_population_random(n) #Create random population\r\n proportion = [] # make an empty list to keep track of the porportions after every interaction \r\n for i in range(k): \r\n x,y = choose_pair(population) # choose a pair from the population \r\n interact(x,y) # make the chosen pair interact\r\n proportion.append(count(population)) # track the proportion of the vowels in the population during intrtaction\r\n return population, proportion\r\n\r\n\r\nplt.figure(figsize=(9, 3))\r\nplt.title('Changes in average points of numbers over time')\r\nplt.ylabel('Average number of points')\r\nplt.xlabel('Time [Number of interactions')\r\nplt.axis([0, 50, 0, 20])\r\n#\r\n#\r\n#\r\ndef batch_simulate(n,k,s):\r\n batch_proportions=[]\r\n for i in range(s):\r\n new_population, proportion = simulate(n, k)\r\n batch_proportions.append(proportion)\r\n return batch_proportions\r\n\r\nresults = batch_simulate(5,50,10)\r\nprint(results)\r\nfor i in results:\r\n plt.plot(i)\r\n \r\n#Jednostavan explore exploit, poeni, biranje","sub_path":"Science.py","file_name":"Science.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"181218019","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\n\r\nveriler = pd.read_csv('musteriler.csv')\r\nprint(veriler)\r\n\r\nx=veriler.iloc[:,[3,4]].values\r\nwcss=[]\r\nkume_sayisi_listesi=range(1,11)\r\n\r\nfrom sklearn.cluster import KMeans\r\n\r\nfor i in kume_sayisi_listesi:\r\n kmeans=KMeans(n_clusters=i, init='k-means++',max_iter=300, n_init=10, random_state=0)\r\n kmeans.fit(x)\r\n wcss.append(kmeans.inertia_)\r\n\r\nplt.plot(kume_sayisi_listesi,wcss)\r\nplt.title('Chart To Determine The Number Of Sets')\r\nplt.xlabel('Number Of Sets')\r\nplt.ylabel('WCSS')\r\nplt.show()\r\n\r\nkmeans=KMeans(n_clusters=4, init='k-means++',max_iter=300, n_init=10, random_state=0)\r\ny_kmeans=kmeans.fit_predict(x)\r\n\r\nplt.scatter(x[y_kmeans==0,0],x[y_kmeans==0,1],s=100,c='red',label=\"Set1\")\r\nplt.scatter(x[y_kmeans==1,0],x[y_kmeans==1,1],s=100,c='green',label=\"Set2\")\r\nplt.scatter(x[y_kmeans==2,0],x[y_kmeans==2,1],s=100,c='blue',label=\"Set3\")\r\nplt.scatter(x[y_kmeans==3,0],x[y_kmeans==3,1],s=100,c='orange',label=\"Set4\")\r\nplt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c='yellow',label='Centers of Clusters')\r\nplt.title('Money Market Segmentation')\r\nplt.xlabel('Volume')\r\nplt.ylabel('Income')\r\nplt.legend()\r\nplt.show()\r\n\r\n\r\nfrom sklearn.cluster import AgglomerativeClustering\r\nac = AgglomerativeClustering(n_clusters=4, affinity='euclidean', linkage='ward')\r\ny_kmeans = ac.fit_predict(x)\r\n\r\n\r\nplt.scatter(x[y_kmeans==0,0],x[y_kmeans==0,1],s=100,c='red',label=\"Set1\")\r\nplt.scatter(x[y_kmeans==1,0],x[y_kmeans==1,1],s=100,c='green',label=\"Set2\")\r\nplt.scatter(x[y_kmeans==2,0],x[y_kmeans==2,1],s=100,c='blue',label=\"Set3\")\r\nplt.scatter(x[y_kmeans==3,0],x[y_kmeans==3,1],s=100,c='orange',label=\"Set4\")\r\n\r\nplt.title('Money Market Segmentation')\r\nplt.xlabel('Volume')\r\nplt.ylabel('Income')\r\nplt.legend()\r\nplt.show()\r\n\r\nimport scipy.cluster.hierarchy as sch\r\ndendrogram = sch.dendrogram(sch.linkage(x, method='ward'))\r\nplt.title('Money Market Segmentation')\r\nplt.xlabel('Income')\r\nplt.ylabel('Volume')\r\nplt.legend()\r\nplt.show()\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":"musterilerkmean.py","file_name":"musterilerkmean.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"608502259","text":"# Copyright (c) 2009-2015, Dmitry Vasiliev \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,\n# this list of conditions and the following disclaimer.\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# * Neither the name of the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# 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\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom __future__ import with_statement\n\n__author__ = \"Dmitry Vasiliev \"\n\nfrom inspect import getargspec\nimport sys\nfrom sys import exc_info\nfrom traceback import extract_tb\nfrom threading import Lock\nimport uuid\n\nfrom erlport import Atom\n\n\nclass Error(Exception):\n \"\"\"ErlPort Error.\"\"\"\n\nclass InvalidMessage(Error):\n \"\"\"Invalid message.\"\"\"\n\nclass UnknownMessage(Error):\n \"\"\"Unknown message.\"\"\"\n\nclass UnexpectedMessage(Error):\n \"\"\"Unexpected message.\"\"\"\n\nclass UnexpectedResponses(UnexpectedMessage):\n \"\"\"Unexpected responses.\"\"\"\n\nclass DuplicateMessageId(Error):\n \"\"\"Duplicate message ID.\"\"\"\n\nclass CallError(Error):\n \"\"\"Call error.\"\"\"\n\n def __init__(self, value):\n if type(value) != tuple or len(value) != 4:\n value = None, None, value, []\n self.language, self.type, self.value, self.stacktrace = value\n Error.__init__(self, value)\n\nclass Responses(object):\n\n def __init__(self):\n self.__responses = {}\n self.__lock = Lock()\n\n def get(self, response_id, default=None):\n with self.__lock:\n if response_id is None:\n if self.__responses:\n raise UnexpectedResponses(self.__responses)\n elif response_id in self.__responses:\n return self.__responses.pop(response_id)\n return default\n\n def put(self, response_id, message, default=None):\n if response_id is None:\n raise UnexpectedMessage(message)\n with self.__lock:\n if response_id in self.__responses:\n raise DuplicateMessageId(message)\n try:\n if response_id == message[1]:\n return message\n except IndexError:\n raise InvalidMessage(message)\n self.__responses[response_id] = message\n return default\n\n\nclass MessageHandler(object):\n\n def __init__(self, port):\n self.port = port\n self.set_default_encoder()\n self.set_default_decoder()\n self.set_default_message_handler()\n self._self = None\n self.responses = Responses()\n\n def new_message_id(self):\n return uuid.uuid4().int\n\n def set_default_encoder(self):\n self.encoder = lambda o: o\n\n def set_encoder(self, encoder):\n self._check_handler(encoder)\n self.encoder = encoder\n\n def set_default_decoder(self):\n self.decoder = lambda o: o\n\n def set_decoder(self, decoder):\n self._check_handler(decoder)\n self.decoder = decoder\n\n def set_default_message_handler(self):\n self.handler = lambda o: None\n\n def set_message_handler(self, handler):\n self._check_handler(handler)\n self.handler = handler\n\n def _check_handler(self, handler):\n # getargspec will raise TypeError if handler is not a function\n args, varargs, _keywords, defaults = getargspec(handler)\n largs = len(args)\n too_much = largs > 1 and largs - len(default) > 1\n too_few = largs == 0 and varargs is None\n if too_much or too_few:\n raise ValueError(\"expected single argument function: %r\"\n % (handler,))\n\n def start(self):\n try:\n self._receive()\n except EOFError:\n pass\n\n def _receive(self, expect_id=None, expect_message=False):\n marker = object()\n while True:\n expected = self.responses.get(expect_id, marker)\n if expected is not marker:\n return expected\n message = self.port.read()\n try:\n mtype = message[0]\n except (IndexError, TypeError):\n raise InvalidMessage(message)\n\n if mtype == \"C\":\n try:\n mid, module, function, args = message[1:]\n except ValueError:\n raise InvalidMessage(message)\n self._call_with_error_handler(\n mid, self._incoming_call, mid, module, function, args)\n elif mtype == \"M\":\n if expect_message:\n return message\n try:\n payload, = message[1:]\n except ValueError:\n raise InvalidMessage(message)\n self._call_with_error_handler(None, self.handler, payload)\n elif mtype == \"r\" or mtype == \"e\":\n expected = self.responses.put(expect_id, message, marker)\n if expected is not marker:\n return expected\n else:\n raise UnknownMessage(message)\n\n def cast(self, pid, message):\n # It's safe to call it from multiple threads because port.write will be\n # locked\n self.port.write((Atom('M'), pid, message))\n\n def call(self, module, function, args):\n if not isinstance(module, Atom):\n raise ValueError(module)\n if not isinstance(function, Atom):\n raise ValueError(function)\n if not isinstance(args, list):\n raise ValueError(args)\n return self._call(module, function, args, Atom('N'))\n\n def self(self):\n if self._self is None:\n self._self = self._call(Atom('erlang'), Atom('self'), [], Atom('L'))\n return self._self\n\n def make_ref(self):\n return self._call(Atom('erlang'), Atom('make_ref'), [], Atom('L'))\n\n def _call(self, module, function, args, context):\n mid = self.new_message_id()\n self.port.write((Atom('C'), mid, module, function,\n map(self.encoder, args), context))\n\n response = self._receive(expect_id=mid)\n\n try:\n mtype, _mid, value = response\n except ValueError:\n raise InvalidMessage(response)\n if mtype != \"r\":\n if mtype == \"e\":\n raise CallError(value)\n raise UnknownMessage(response)\n return self.decoder(value)\n\n def _incoming_call(self, mid, module, function, args):\n objects = function.split(\".\")\n f = sys.modules.get(module)\n if not f:\n f = __import__(module, {}, {}, [objects[0]])\n for o in objects:\n f = getattr(f, o)\n result = Atom(\"r\"), mid, self.encoder(f(*map(self.decoder, args)))\n self.port.write(result)\n\n def _call_with_error_handler(self, mid, function, *args):\n try:\n function(*args)\n except:\n t, val, tb = exc_info()\n exc = Atom(\"%s.%s\" % (t.__module__, t.__name__))\n exc_tb = extract_tb(tb)\n exc_tb.reverse()\n error = Atom(\"python\"), exc, unicode(val), exc_tb\n if mid is not None:\n result = Atom(\"e\"), mid, error\n else:\n result = Atom(\"e\"), error\n self.port.write(result)\n\ndef setup_api_functions(handler):\n global call, cast, self, make_ref\n global set_default_encoder, set_default_decoder\n global set_default_message_handler\n global set_encoder, set_decoder, set_message_handler\n call = handler.call\n cast = handler.cast\n self = handler.self\n make_ref = handler.make_ref\n set_encoder = handler.set_encoder\n set_decoder = handler.set_decoder\n set_message_handler = handler.set_message_handler\n set_default_encoder = handler.set_default_encoder\n set_default_decoder = handler.set_default_decoder\n set_default_message_handler = handler.set_default_message_handler\n\ndef setup(port):\n import stdio\n global MessageHandler, setup\n handler = MessageHandler(port)\n setup_api_functions(handler)\n stdio.redirect(port)\n del MessageHandler, setup\n handler.start()\n","sub_path":"priv/python2/erlport/erlang.py","file_name":"erlang.py","file_ext":"py","file_size_in_byte":9257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"69049315","text":"import os\nimport pickle\nimport webapp2, jinja2\nfrom google.appengine.ext import db\ntry:\n import json\nexcept ImportError:\n from django.utils import simplejson as json\n\n# Initialize the jinja environment\njinja_environment = jinja2.Environment(autoescape=True,\n loader=(jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))) \n\n# Import all of the StochSS Models\nfrom handlers.modeleditor import *\nfrom handlers.exportimport import *\n\npath = os.path.abspath(os.path.dirname(__file__))\n\nclass MainPage(webapp2.RequestHandler):\n '''\n '''\n def get(self):\n #Get all data\n context = {\n \"all_models\": db.GqlQuery(\"SELECT * FROM StochKitModelWrapper\").fetch(1000)\n }\n template = jinja_environment.get_template(\"main_page.html\")\n return self.response.out.write(template.render({'active_upload': True}, **context))\n \n def post(self):\n request_data = json.loads(self.request.POST.items()[0][0])\n logging.info(request_data)\n context = {}\n selected_models = request_data['modelsToExport']\n # Create a zip archive\n if len(selected_models) > 0:\n szip = SuperZip(os.path.abspath(os.path.dirname(__file__)) + '/../app2/static/tmp/')\n for model in selected_models:\n model = db.GqlQuery(\"SELECT * FROM StochKitModelWrapper WHERE model_name = :1\", model).get()\n szip.addStochKitModel(model)\n szip.close()\n context[\"status\"] = True\n context[\"zipLocation\"] = os.path.relpath(szip.getFileName(), path)\n else:\n context[\"status\"] = False\n context[\"msg\"] = \"There were no selected models.\"\n self.response.headers['Content-Type'] = 'application/json'\n self.response.write(json.dumps(context))\n\n\napp = webapp2.WSGIApplication([('/', MainPage)], debug=True)\nlogging.getLogger().setLevel(logging.DEBUG)\n","sub_path":"app2/export-ye-olde-stochssapp.py","file_name":"export-ye-olde-stochssapp.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"361518673","text":"try:\n from Notify import Main as NotifyMain\n Notify = NotifyMain()\nexcept(ImportError):\n print(\"Failed to import Notify\")\nimport datetime\nimport os\nimport time\nclass Telemetry():\n def __init__(self):\n self.CurrentDay = 0\n self.CurrentMonth = 0\n self.CurrentYear = 0\n self.CurrentHour = 0\n self.CurrentMinute = 0\n self.DateUntil = 0\n ###\n\n def GetNewDate(self):\n self.CurrentDay = datetime.datetime.today().day\n self.CurrentMonth = datetime.datetime.today().month\n self.CurrentYear = datetime.datetime.today().year\n self.CurrentHour = datetime.datetime.today().hour\n self.CurrentMinute = datetime.datetime.today().minute\n #print(self.CurrentDay, self.CurrentMonth, self.CurrentYear)\n\n def TimeUntilDate(self,day, month, year):\n self.GetNewDate()\n FirstDate = datetime.datetime(year,month,day)\n SecondDate = datetime.datetime(self.CurrentYear, self.CurrentMonth, self.CurrentDay)\n DeltaDate = FirstDate - SecondDate\n DeltaDate = str(DeltaDate)\n DeltaDate = DeltaDate[:2]\n DeltaDate = int(DeltaDate)\n return DeltaDate - 1\n\nTelemetry = Telemetry()\n\nclass UI():\n def __init__(self):\n Telemetry.GetNewDate()\n self.CurrentHour = Telemetry.CurrentHour\n self.CurrentMinute = Telemetry.CurrentMinute\n #self.events = [[0, \"EVENT\"],[date,\"string\"],[date,\"string\",\"string\"]\n self.Events = []\n self.DataFile = open(\"DATA.txt\",\"r+\")\n\n def ReadEventsFromTextFile(self):\n Data = []\n Cache = self.DataFile.read()\n rows = Cache.split(\"\\n\")\n for column in rows:\n if len(column) > 0:\n columns = column.split(\",\")\n self.Events.append(columns)\n for count in range(0,len(self.Events)):\n print(self.Events[count])\n\n def Container(self):\n os.system(\"clear\")\n Telemetry.GetNewDate()\n NumberOfEvents = 0\n print(\"\"\"\n |------------------------------------------------------|\n | {}:{}\n |-----|---------------------------------------|--------|\n |DATE | EVENTS | PROG |\n \"\"\".format(self.CurrentHour, self.CurrentMinute))\n for count in range(0,len(self.Events)):\n NumberOfEvents = len(self.Events[count]) - 2\n print(\"|{:<5}|{:<38}|{:<9}\".format(self.Events[count][0], self.Events[1:NumberOfEvents]),self.Events[NumberOfEvents + 1])\n\n\n def MainMenu(self):\n print(\"\"\"\n |---------------------------------------|\n | MAIN |\n |[1] Start |\n |[2] Quick Time until |\n |---------------------------------------|\n \"\"\")\n while True:\n try:\n menuchoice = int(input(\"> \"))\n if menuchoice not in [1,2]:\n Notify.Error(\"Please enter a valid input.\")\n else:\n break\n except(ValueError):\n Notify.Error(\"Please enter a valid input\")\n if menuchoice == 1:\n self.Start()\n elif menuchoice == 2:\n print(\"Andreea Arriving in:\",Telemetry.TimeUntilDate(5,9,2017),\"days.\")\n\n\n\nUI = UI()\n#UI.MainMenu()\nUI.ReadEventsFromTextFile()\nUI.Container()\n\n\n","sub_path":"AES_Master/AES 4.3/Misc/Days.py","file_name":"Days.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"448469831","text":"#Fibonacci functions\r\n\r\ndef fib_n(item):\r\n f1 = f2 = 1\r\n\r\n while item > 2:\r\n buff =f2\r\n f2 =f1 +f2\r\n f1 = buff\r\n item -= 1\r\n return f2\r\n\r\ndef fib_row(item):\r\n f1 = f2 =2\r\n print(f1, f2, end=' ')\r\n while item >2:\r\n buff =f2\r\n f2 = f1+f2\r\n f1 = buff\r\n print(f2, end=' ')\r\n item -= 1\r\n print()\r\n\r\nn = int(input())\r\nm = fib_n(n)\r\nprint(m)\r\n\r\nfib_row(n)","sub_path":"Incepator/functions/functions3.py","file_name":"functions3.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"312151720","text":"import os\nfrom operator import itemgetter\nfrom collections import Counter\nwith open(\"hightemp.txt\") as file:\n lines = file.readlines()\n first_column_list = [x.split(\"\\t\")[0] for x in lines]\n frequency_list = Counter(first_column_list)\n data = frequency_list.most_common()\n data.sort(key=lambda tup: tup[0], reverse=True) # sorted name\n data.sort(key=lambda tup: tup[1], reverse=True) # sorted freq.\n for item in data:\n print(\"{} {}\".format(item[1], item[0]))\nprint(\"確認\")\nos.system(\"cut -f 1 hightemp.txt | sort -r | uniq -c | sort -r\")\n","sub_path":"bambi/chapter02/knock19.py","file_name":"knock19.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"338123949","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 21 10:49:01 2018\n\n@author: utke.markus\n\n------------------------------- IMPORTANT NOTE: --------------------------------------\n\nPlease use this fork of keras for good results:\nhttps://github.com/datumbox/keras/tree/bugfix/trainable_bn\n\nRead about why this is necessary here:\nhttp://blog.datumbox.com/the-batch-normalization-layer-of-keras-is-broken/\n\"\"\"\n\nimport numpy as np\nnp.random.seed(7)\n\nimport tensorflow as tf\ntf.Session()\ntf.set_random_seed(9)\nfrom keras.applications import densenet, xception, resnet50, mobilenet_v2\n\nfrom importData import DataSequenceNew\nfrom tools import plotPrediction, setTrainability, ValidationCallback, buildModel\n\n\n\n#%%\n\n# filepaths for training and validation set\n#filepathTrain = \"D:\\\\All\\\\\" \nfilepathTrain = \"J:\\\\DataSet\\\\NewDataset\\\\All\\\\\"\n#filepathVal = \"D:\\\\All\\\\\"\n\nfilepathVal = \"J:\\\\DataSet\\\\NewDataset\\\\All\\\\\"\nfilepathVMAF = \"J:\\\\DataSet\\\\NewDataset\\\\ParsedVMAF.XLSX\"\n\n# title for saving the model\ntitle = \"VGGSaman\"\n\n# parameters for training and validation\npatchSize = 299 # size of the quadratic patches 299\nnPatches = 13 # number of patches for each frame\nbatchSize = 64 # batch size for training\neverynthTrain = 13 # distance between frames that are used for training; only every nth image is used\neverynthVal = 23 # distance between frames that are used for validation; only every nth image is used\nepochs = 100 # number of epochs for training\nnTrainableLayers = 204 # number of trainable layers\n\nmodelBuilder = resnet50 #DenseNet121 # choose: xception.Xception, resnet50.ResNet50, densenet.DenseNet121, mobilenet_v2.MobileNetV2, ...\n\n# disjunct lists of training and validation indices\n# use '[x for x in enumerate(glob.glob(filepath + \"\\\\*\"))]' to show the list of all folder names with their indices\n# in this case the validation set consists of: CSGO_Part2, Hearthstone_Part2, Dota_Part1, Dota_Part2, ProjectCar_Part1, ProjectCar_Part2\ntrainIndexes = np.arange(390)\nvalIndexes = np.hstack((np.arange(18, 33), np.arange(191, 209), np.arange(69, 105), np.arange(272, 282))) \ntrainIndexes = np.delete(trainIndexes, valIndexes)\n\n\n#%%\n\nnTrainVideos = len(trainIndexes)\nnValVideos = len(valIndexes)\n\n# generators for training and validation\ndsVal = DataSequenceNew(filepathVal, filepathVMAF, valIndexes, patchSize = patchSize, everynth = everynthVal, batchSize = 10, preprocess = densenet.preprocess_input, shuffle = False, returnMode = 2, nPatches = nPatches)\ndsTrain = DataSequenceNew(filepathTrain, filepathVMAF, trainIndexes, patchSize = patchSize, nPatches = nPatches, everynth = everynthTrain, batchSize = batchSize, preprocess = densenet.preprocess_input)\n\n# callback to track the validation loss\nvalidationLossHistory = ValidationCallback(dsVal, nValVideos, title)\n\n# build the model\nmodel = buildModel(modelBuilder, patchSize)\n\n# set the trainability of all the layers, except the last nTrainableLayers to false\nsetTrainability(model, nTrainableLayers)\n\n# compile the model\nmodel.compile(loss = 'mean_squared_error', optimizer = 'adam')\n\n# print model summary\n#model.summary()\n\n#%%\n\n# train the model\nmodel.fit_generator(dsTrain, steps_per_epoch = None, epochs = epochs, verbose = 1, callbacks=[validationLossHistory])#, lossHistory, TerminateOnNaN()])\n\n#%%\n#plot the predictions and \nbestEpoch = validationLossHistory.bestEpoch\nplotPrediction(validationLossHistory.preds[bestEpoch], validationLossHistory.yVal, validationLossHistory.nValVideos, title)\n\nbestEpoch = validationLossHistory.bestEpoch\nnp.save(title, (validationLossHistory.metricsPerFrame[bestEpoch], validationLossHistory.metricsPerVideo[bestEpoch]))\n","sub_path":"Training/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"151369046","text":"import ntpath\nimport matplotlib\nmatplotlib.use('TKAgg')\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef read_hic(fname):\n\tdata=np.genfromtxt(fname, delimiter='\\t', usecols=[0,1,3],dtype=None)\n\n\n\ti_min=data[0][0]\n\tj_max=data[-1][1]\n\tn=j_max-i_min+1\n\n\tH=np.zeros((n,n))\n\tfor r in range(data.size):\n\t i=(data[r][0])-i_min\n\t j=(data[r][1])-i_min\n\n\t H[i][j]=(data[r][2])\n\t#H=H[:, ~np.all(H == 0, axis=0)] \n\t#H=H[~np.all(H == 0, axis=1)] \n\t#Remove all zero columns and rows\n\t#~ is the logical negation\n\treturn H\ndef plot_hic(H,fname):\n\tplt.figure(figsize=(4, 4), dpi=200)\n\tplt.imshow(H,cmap = plt.cm.get_cmap('Reds'))\n\tplt.clim(0, 30);\n\tplt.colorbar()\n\tplt.title(fname)\n\tfigure_name=fname+\".png\"\n\tplt.savefig(figure_name, dpi='figure', metadata=None)\n\tplt.show() \narguments=len(sys.argv)-1\npos=1\n#the input arguments are paired. the first one is del. the second one is prediction\nwhile(pos<=arguments):\n\tfname=(sys.argv[pos])\n\tDel=np.genfromtxt(fname, delimiter='\\t', dtype=float)\n\tplot_hic(Del,fname)\n\n\tfname=(sys.argv[pos+1])\n\tPrediction=read_hic(fname)\n\tplot_hic(Prediction,fname)\n\tfname=ntpath.basename(fname)+'Prediction_Del'\n\tPrediction_Del=Prediction-Del\n\tplot_hic(Prediction_Del,fname)\n\tpos+=2\n","sub_path":"src/plot_hic.py","file_name":"plot_hic.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"258248367","text":"# 使用字典更新一个对象, 看ok不OK?\n#\n#\n\nclass A:\n a1 = 1\n a2 = 2\n a3 = 3\n a4 = 4\n\n def __str__(self):\n return ' {},{},{},{}'.format( self.a1, self.a2, self.a3, self.a4)\n\n\ndict1 = {\n 'a1': '-1',\n 'a2': '20'\n}\na = A()\n\nfor item in dict1.keys():\n if hasattr(a, item):\n setattr(a, item, dict1[item])\n\nprint(a)\n\n","sub_path":"week1_basic/dict_update_object.py","file_name":"dict_update_object.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"241239957","text":"\"\"\"\nProject 4 - Computing alignments of sequences\n\"\"\"\n\ndef build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):\n \"\"\"\n builds a scoring matrix as a dictionary of dictionaries.\n \"\"\"\n ret = {}\n alphabet2 = alphabet.copy()\n alphabet2.add('-')\n for item1 in alphabet2:\n ret[item1] = {}\n for item2 in alphabet2:\n if item1 == '-' or item2 == '-':\n ret[item1][item2] = dash_score\n elif item1 == item2:\n ret[item1][item2] = diag_score\n else:\n ret[item1][item2] = off_diag_score\n return ret\n\ndef compute_alignment_matrix(seq_x, seq_y, scoring_matrix, global_flag):\n \"\"\"\n computes an alignment matrix using the method\n \"\"\"\n return [[0]]\n\ndef compute_global_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):\n \"\"\"\n Takes as input two sequences seq_x and seq_y whose elements share a common alphabet with the scoring matrix scoring_matrix . This function computes a global alignment of seq_x and seq_y using the global alignment matrix alignment_matrix .\n \"\"\"\n return ({'A': {'A': 6, 'C': 2, '-': -4, 'T': 2, 'G': 2}, 'C': {'A': 2, 'C': 6, '-': -4, 'T': 2, 'G': 2}, '-': {'A': -4, 'C': -4, '-': -4, 'T': -4, 'G': -4}, 'T': {'A': 2, 'C': 2, '-': -4, 'T': 6, 'G': 2}, 'G': {'A': 2, 'C': 2, '-': -4, 'T': 2, 'G': 6}}, 0, '', '', True)\n\ndef compute_local_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):\n \"\"\"\n Takes as input two sequences seq_x and seq_y whose elements share a common alphabet with the scoring matrix scoring_matrix . This function computes a local alignment of seq_x and seq_y using the local alignment matrix alignment_matrix .\n \"\"\"\n return ({'A': {'A': 6, 'C': 2, '-': -4, 'T': 2, 'G': 2}, 'C': {'A': 2, 'C': 6, '-': -4, 'T': 2, 'G': 2}, '-': {'A': -4, 'C': -4, '-': -4, 'T': -4, 'G': -4}, 'T': {'A': 2, 'C': 2, '-': -4, 'T': 6, 'G': 2}, 'G': {'A': 2, 'C': 2, '-': -4, 'T': 2, 'G': 6}}, 0, '', '', False)\n\n\n#print build_scoring_matrix(set(['A', 'C', '-', 'T', 'G']), 2, 1, 0)\n#print build_scoring_matrix(set(['A', 'C', 'T', 'G']), 6, 2, -4)\n\n","sub_path":"python/project4.py","file_name":"project4.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"533896587","text":"def add_order(order, path):\n with open(path, 'a') as f:\n f.write('\\n' + order)\n\n with open(path, 'r') as f:\n a = f.readlines()\n\n s = [1 for el in a if el.split(':')[1] == 'active']\n return sum(s)\n\n\ndef add_order(order, path):\n import os\n if os.path.exists(path):\n order = '\\n' + order\n f = open(path, 'a')\n f.write(order)\n\n f.close()\n\n with open(path, 'r') as f:\n a = f.readlines()\n\n f.close()\n print(a)\n s = [el for el in a if el != '\\n' and el.split(':')[1].strip() == 'active']\n print(s)\n return s\n\n\ndef add_order(order, path):\n import os\n if os.path.exists(path):\n order = '\\n' + order\n f = open(path, 'a')\n f.write(order)\n\n f.close()\n\n with open(path, 'r') as f:\n a = f.read()\n\n f.close()\n return a.count(':active')\n\n\nprint(add_order('ss:not active', 'b.txt'))\n","sub_path":"lesson6/auto_homework/hw6_3.py","file_name":"hw6_3.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"481961149","text":"import sklearn\nimport tensorflow as tf\nfrom absl.testing import parameterized\n\nfrom pyroclast.common.tf_util import setup_tfds\nfrom pyroclast.cpvae.model import CpVAE\nfrom pyroclast.cpvae.tf_models import VAEDecoder, VAEEncoder\nfrom pyroclast.cpvae.ddt import DDT\n\n\nclass CpVAETest(parameterized.TestCase):\n\n def setUp(self):\n super(CpVAETest, self).setUp()\n self.args = dict()\n self.args['dataset'] = 'mnist'\n self.args['encoder'] = 'mnist_encoder'\n self.args['decoder'] = 'mnist_decoder'\n self.args['epochs'] = 1\n self.args['data_limit'] = 80\n self.args['latent_dim'] = 10\n self.args['batch_size'] = 8\n self.args['output_dir'] = 'cpvae_cpvae_test'\n\n self.ds = setup_tfds(self.args['dataset'], self.args['batch_size'],\n None, self.args['data_limit'])\n self.encoder = VAEEncoder(self.args['encoder'], self.args['latent_dim'])\n self.decoder = VAEDecoder(self.args['decoder'], self.ds['shape'][-1])\n decision_tree = sklearn.tree.DecisionTreeClassifier(\n max_depth=2, min_weight_fraction_leaf=0.01, max_leaf_nodes=4)\n self.DDT = DDT(decision_tree, 10)\n\n def test_vae_loss(self):\n output_distributions = ['disc_logistic', 'l2', 'bernoulli']\n for dist in output_distributions:\n # require the outputs of CpVAE loss fn to be non-negative and have size equal to batch size\n model = CpVAE(self.encoder,\n self.decoder,\n self.DDT,\n self.args['latent_dim'],\n self.ds['num_classes'],\n 1,\n output_dist=dist)\n model.classifier.update_model_tree(self.ds['train'],\n model.posterior)\n\n for batch in self.ds['train']:\n x = tf.cast(batch['image'], tf.float32)\n x_hat, _, z_posterior, x_hat_scale = model(x)\n distortion, rate = model.vae_loss(x, x_hat, x_hat_scale,\n z_posterior)\n assert distortion.shape == self.args[\n 'batch_size'], 'output_dist is {}'.format(dist)\n # assert not any(distortion < 0.)\n assert rate.shape == self.args['batch_size']\n assert not any(rate < 0.)\n break\n","sub_path":"pyroclast/cpvae/model_test.py","file_name":"model_test.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"498729310","text":"from urllib.parse import urlparse, urljoin\nfrom flask import request\nfrom datetime import datetime, date, timedelta\nimport re\n\n\ndef valid_uuid(uuid):\n return re.fullmatch('[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}', uuid) is not None\n\n\ndef valid_semester(semester):\n return re.fullmatch('(V|H)[1-9][0-9]{3}', semester) is not None\n\n\ndef is_safe_url(target):\n ref_url = urlparse(request.host_url)\n test_url = urlparse(urljoin(request.host_url, target))\n return test_url.scheme in ('http', 'https') and \\\n ref_url.netloc == test_url.netloc\n\n\ndef get_semester(group_info):\n semester_date = None\n # Means the course is active (in current semester)\n if 'notAfter' not in group_info['membership']:\n semester_date = datetime.now()\n else:\n end_date = group_info['membership']['notAfter']\n semester_date = datetime.strptime(end_date, '%Y-%m-%dT%H:%M:%SZ')\n year = semester_date.year\n season = 'V' if semester_date.month < 7 else 'H'\n return '{}{}'.format(season, year)\n\ndef get_lecturedates(start_date, end_date, weekday_list):\n dates = [start_date + timedelta(days=x) for x in range((end_date-start_date).days+1)]\n lecture_dates = []\n for date in dates:\n if(date.strftime(\"%A\").lower() in weekday_list):\n lecture_dates.append(date)\n return lecture_dates\n","sub_path":"chalktalk/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"360487699","text":"from pecan import conf, request, response, abort # noqa\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nSession = scoped_session(sessionmaker())\n\n\ndef _engine_from_config(configuration):\n configuration = dict(configuration)\n url = configuration.pop('url')\n return create_engine(url, **configuration)\n\n\ndef init_model():\n \"\"\"\n This is a stub method which is called at application startup time.\n\n If you need to bind to a parsed database configuration, set up tables or\n ORM classes, or perform any database initialization, this is the\n recommended place to do it.\n\n For more information working with databases, and some common recipes,\n see https://pecan.readthedocs.io/en/latest/databases.html\n \"\"\"\n conf.sqlalchemy.engine = _engine_from_config(conf.sqlalchemy)\n\n\ndef start():\n Session.bind = conf.sqlalchemy.engine\n\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Headers'] = '*'\n response.headers['Access-Control-Allow-Methods'] = '*'\n\n response.headers['Cache-Control'] = 'no-cache,must-revalidate'\n response.headers['Pragma'] = 'no-cache'\n response.headers['Expires'] = '0'\n\n if request.method == 'OPTIONS':\n abort(200, headers={\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Methods': '*'\n })\n\n\ndef commit():\n Session().commit()\n\n\ndef rollback():\n Session().rollback()\n\n\ndef clear():\n Session.remove()\n","sub_path":"backend/bbsapi/bbsapi/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"428819029","text":"# quadratic.py\r\n# A program that computes the real roots of a quadratic equation\r\n# The program also illustrates the use of Python's math library\r\n# NOTE: The program crashes if the equation has no real roots\r\n\r\nimport math #this command makes the math library(module) available \r\n\r\ndef main():\r\n print(\"This program finds the real solutions to a quadratic equation\")\r\n print()\r\n \r\n a,b,c = eval(input(\"Please enter the coefficients (a,b,c): \"))\r\n \r\n discRoot = math.sqrt(b*b-4*a*c)\r\n root1 = (-b + discRoot) / (2*a)\r\n root2 = (-b - discRoot) / (2*a)\r\n \r\n print()\r\n print(\"The solutions are: \", root1, root2)\r\n\r\nmain()\r\n\r\n","sub_path":"misc_other/quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"243906631","text":"#!/usr/bin/env python3\n\nfrom src.day11.part1 import occupied_count, print_map, EMPTY, OCCUPIED, FLOOR\n\nEND = '|'\n\n\ndef waiting_area(seat_map, print_steps):\n round = 0\n while True:\n new_seat_map = generate_new_seat_map_part2(seat_map)\n if print_steps:\n print(round)\n print_map(new_seat_map)\n if new_seat_map == seat_map:\n break\n seat_map = new_seat_map\n round += 1\n return occupied_count(seat_map)\n\n\ndef generate_new_seat_map_part2(seat_map):\n new_seat_map = []\n for x, line in enumerate(seat_map):\n new_row = []\n for y, cell in enumerate(line):\n new_row.append(new_value_part2(x, y, seat_map))\n new_seat_map.append(new_row)\n return new_seat_map\n\n\ndef new_value_part2(x, y, seat_map):\n # ABC --> y\n # D$E |\n # FGH \\/ x\n current = seat_map[x][y]\n if current == EMPTY:\n pass\n if current == FLOOR:\n return FLOOR\n # head in each direction until you hit the END or an occupied seat\n directions = [\n lambda x, y: (x-1, y-1), # a\n lambda x, y: (x-1, y), # b\n lambda x, y: (x-1, y+1), # c\n lambda x, y: (x, y-1), # d\n lambda x, y: (x, y+1), # e\n lambda x, y: (x+1, y-1), # f\n lambda x, y: (x+1, y), # g\n lambda x, y: (x+1, y+1) # h\n ]\n occupied_count = 0\n for direction in directions:\n new_x, new_y = x, y\n while True:\n new_x, new_y = direction(new_x, new_y)\n cell_contents = cell_value(new_x, new_y, seat_map)\n if cell_contents == END:\n break\n elif cell_contents == OCCUPIED:\n occupied_count += 1\n break\n if current == EMPTY and occupied_count == 0:\n return OCCUPIED\n if current == OCCUPIED and occupied_count >= 5:\n return EMPTY\n return current\n\n\ndef cell_value(x, y, seat_map):\n if x < 0 \\\n or x >= len(seat_map) \\\n or y < 0 or y >= len(seat_map[0]) \\\n or seat_map[x][y] == EMPTY:\n return END\n return seat_map[x][y]\n\n\nif __name__ == '__main__':\n with open('input', 'r') as file:\n lines = [line.strip() for line in file.readlines()]\n print('Result: ' + str(waiting_area(lines, False)))\n","sub_path":"src/day11/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"445997069","text":"from django.shortcuts import render\nfrom site_parser.models import Results\n\ndef index(request):\n msg = ''\n res = Results.objects.all().order_by('id')\n for r in res:\n msg += r.urls\n mm = filter(lambda x: x if x else '', [r.title, r.charset, r.h1])\n for x in mm:\n msg+=\" - \"+x\n msg+=\"\\n\"\n return render(request, 'site_parser/index.html', {'msg': msg})\n","sub_path":"site_parser/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"154321355","text":"# -*- coding: utf-8 -*-\n#################################################################################\n# Author : Niova Group ApS ()\n# Copyright(c): 2018-Present Niova Group ApS\n# License URL : https://invoice-scan.com/license/\n# All Rights Reserved.\n#################################################################################\nfrom odoo import models, api, fields, _\nfrom odoo.exceptions import UserError\n\n\nclass AccountInvoiceChangeCompany(models.TransientModel):\n _name = 'account.invoice.change.company'\n _description = 'Account Invoice Change Company'\n \n new_company_id = fields.Many2one('res.company', string='New Company', required=True)\n \n def _change_company(self, invoice, new_company):\n invoice = invoice.sudo()\n if invoice.state != 'draft' or new_company == invoice.company_id:\n return False\n \n # Change company\n invoice = invoice.with_company(new_company.id).with_context(company_id=new_company.id, default_move_type=invoice.move_type)\n invoice.journal_id = invoice._get_default_journal().id\n invoice.company_id = new_company\n context = {\n 'journal_id': invoice.journal_id.id, \n 'move_type': 'in_invoice',\n 'default_move_type': 'in_invoice',\n 'partner_id': invoice.partner_id.id,\n 'company_id': invoice.company_id.id}\n invoice = invoice.with_context(context)\n if invoice.partner_id:\n invoice._onchange_partner_id()\n \n # Clear lines, because it is not doable else\n invoice.action_clear_invoice_lines()\n invoice._auto_attach_invoice_lines()\n return True\n\n def action_change_company(self):\n context = dict(self._context or {})\n active_ids = context.get('active_ids', []) or []\n \n for invoice in self.env['account.move'].browse(active_ids):\n status = self._change_company(invoice, self.new_company_id)\n if status:\n invoice._cr.commit()\n if len(active_ids) == 1:\n # Return to list view, because we cannot look at an invoice in a different company\n # when we stays in the old company\n action = self.env.ref('account.action_move_in_invoice_type').read()[0]\n return action\n elif len(active_ids) == 1:\n raise UserError(_(\"Not able to change company in state different from draft or has the same company.\"))\n else:\n invoice._cr.rollback()\n return {'type': 'ir.actions.act_window_close'}\n ","sub_path":"niova_invoice_scan/wizard/account_invoice_change_company.py","file_name":"account_invoice_change_company.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"464015267","text":"from flask import Flask, request\nimport time\nimport json\nimport uuid\nimport hashlib\n\n\napp = Flask(__name__)\nacount = {'01234567895031231456': ('zhou3', '123')}\nregister_object = []\nVIIDServerID = '01234567895031231457'\n\n\ndef dataTime():\n return time.strftime('%Y%m%d%H%M%S', time.localtime())\n\n\ndef digest_auth(Authorization, deviceID):\n h = {}\n obj = Authorization.replace('Digest', '').replace(' ', '').split(',')\n for elem in obj:\n h[elem.split('=')[0]] = elem.replace(elem.split('=')[0]+'=', '')\n\n uri = h['uri'].replace('\"','')\n cnonce = h['cnonce'].replace('\"','')\n nonce = h['nonce'].replace('\"','')\n realm = h['realm'].replace('\"','')\n nc = h['nc']\n qop = h['qop'].replace('\"','')\n user = acount[deviceID][0]\n passwd = acount[deviceID][1]\n \n HA1 = hashlib.md5((user+':'+realm+':'+passwd).encode()).hexdigest()\n HA2 = hashlib.md5(('POST:'+uri).encode()).hexdigest()\n HD = nonce+':'+nc+':'+cnonce+':'+qop\n response = hashlib.md5((HA1+':'+HD+':'+HA2).encode()).hexdigest()\n\n # print(response, h['response'].replace('\"',''))\n \n if response == h['response'].replace('\"',''):\n return True\n else:\n return False\n \n\n# 布控后,接受回调地址的告警\n@app.route('/alarm', methods=['POST'])\ndef recv_alarm():\n if request.method == 'POST':\n print('\\n' + '*'*78 + '\\n' + '请求头部:' + '-'*52)\n print(request.headers)\n print('请求消息体:'+ '-'*50)\n print(json.loads(request.get_data().decode()))\n return '', 200\n\n\n# 订阅后,接受回调地址的通知\n@app.route('/notification', methods=['POST'])\ndef recv_notification():\n if request.method == 'POST':\n print('\\n' + '*'*78 + '\\n' + '请求头部:' + '-'*52)\n print(request.headers)\n print('请求消息体:'+ '-'*50)\n print(json.loads(request.get_data().decode()))\n return '', 200\n\n\n# 校时\n@app.route('/VIID/System/Time', methods=['GET'])\ndef timeCheck():\n if request.method == 'GET':\n return json.dumps({\"SystemTimeObject\":\n {\"VIIDServerID\": VIIDServerID,\n \"TimeMode\": 1,\n \"LocalTime\": dataTime(),\n \"TimeZone\": \"shanghai\"}\n }), 201\n\n\n# 保活\n@app.route('/VIID/System/Keepalive', methods=['POST'])\ndef keepalive():\n if request.method == 'POST':\n DeviceID = json.loads(request.get_data().decode())\\\n ['KeepaliveObject']['DeviceID']\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": DeviceID,\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/Keepalive\",\n \"StatusCode\": \"0\",\n \"StatusString\": \"keepalive success\"}\n }), 201\n\n\n# 注销\n@app.route('/VIID/System/UnRegister', methods=['POST'])\ndef unRegister():\n if request.method == 'POST':\n DeviceID = json.loads(request.get_data().decode())\\\n ['UnRegisterObject']['DeviceID']\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": DeviceID,\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/UnRegister\",\n \"StatusCode\": \"0\",\n \"StatusString\": \"unRegister success\"}\n }), 201\n \n\n# 注册\n@app.route('/VIID/System/Register', methods=['POST'])\ndef register():\n if request.method == 'POST':\n # print(request.headers)\n if 'Authorization' not in request.headers:\n nonce = str(uuid.uuid1()).replace('-','')[:20]\n opaque = str(uuid.uuid1()).replace('-','')[:20]\n headers = {'WWW-Authenticate': 'Digest realm=\"VIID\",qop=\"auth\",'+\\\n 'nonce=\"'+nonce+'\",opaque=\"'+opaque+'\"',\n 'Access-Control-Allow-'+\\\n 'Methods': 'POST', 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': 'Origin, No-Cache, '+\\\n 'X-Requested-With, If-Modified-Since, Pragma,Accept,'+\\\n ' Authorization,Last-Modified, Cache-Control, Expires'+\\\n ', Content-Type,User-Identify',\n 'Content-Type': 'text/plain; charset=utf-8',\n 'Access-Control-Expose-Headers': 'Content-Type,'+\\\n 'Connection,WWW-Authenticate,User-Identify,'+\\\n 'Authorization', 'Access-Control-Max-Age': '1728000'\n }\n # print(headers)\n return json.dumps({'ResponseStatusObject':\n {'StatusString': 'invalid authorization Header',\n 'StatusCode': '4',\n 'Id': '',\n 'LocalTime': dataTime(),\n 'RequestURL': '/VIID/System/Register'}\n }), 401, headers\n elif 'Authorization' in request.headers:\n DeviceID = json.loads(request.get_data().decode())\\\n ['RegisterObject']['DeviceID']\n # print(DeviceID)\n if DeviceID not in acount:\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": '',\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/Register\",\n \"StatusCode\": \"4\",\n \"StatusString\": \"invaild DeviceID\"}\n }), 405\n if digest_auth(request.headers['Authorization'], DeviceID):\n print(DeviceID, 'Register success')\n register_object.append(DeviceID)\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": DeviceID,\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/Register\",\n \"StatusCode\": \"0\",\n \"StatusString\": \"Register success\"}\n }), 201\n else:\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": '',\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/Register\",\n \"StatusCode\": \"4\",\n \"StatusString\": \"invaild Authorization\"}\n }), 401\n else:\n return json.dumps({\"ResponseStatusObject\":\n {\"Id\": '',\n \"LocalTime\": dataTime(),\n \"RequestURL\": \"/VIID/System/Register\",\n \"StatusCode\": \"4\",\n \"StatusString\": \"invaild requset method\"}\n }), 405\n \n\nif __name__ == '__main__':\n app.run('192.168.2.105', 5656)\n\n","sub_path":"viid-server.py","file_name":"viid-server.py","file_ext":"py","file_size_in_byte":7139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"509297547","text":"import a2.services.classroom_service as classroom_service\nimport a2.services.user_service as user_service\n\nfrom flask_restplus import Namespace, reqparse, Resource, fields, abort\n\nfrom a2.decorators.token import auth_required\n\nparser = reqparse.RequestParser()\n\napi = Namespace('classroom', description=\"Namespace to manage classrooms. \")\n\nuser_fields = api.model('UserFields', {\n \"idUser\": fields.Integer(attribute=\"user.idUser\"),\n \"name\": fields.String(attribute=\"user.name\"),\n \"isAdmin\": fields.Boolean(attribute=\"user.isAdmin\"),\n \"internal_code\": fields.Integer(attribute=\"user.internalCode\")\n})\n\nclassroom_fields = api.model('ClassroomResponse', {\n \"idClassroom\": fields.Integer,\n \"name\": fields.String,\n 'users': fields.List(fields.Nested(user_fields)),\n})\n\nclassroom_overview_fields = api.model('ClassroomOverview', {\n \"idClassroom\": fields.Integer,\n \"name\": fields.String\n})\n\n\n@api.route('/')\nclass ClassroomResource(Resource):\n\n @auth_required\n @api.doc(\"Get all classrooms (only general information such as name \")\n @api.marshal_with(classroom_overview_fields)\n def get(self):\n return classroom_service.getAllClassrooms()\n\n @auth_required\n @api.doc(\"Create new classroom. \")\n @api.marshal_with(classroom_fields)\n @api.expect(api.model('ClassroomInput', {\"name\": fields.String}))\n def post(self):\n parser.add_argument(\"name\")\n parsed_args = parser.parse_args()\n\n new_classroom = classroom_service.addClassroom(parsed_args['name'])\n\n return new_classroom\n\n\n@api.route('/')\nclass ClassroomUserResource(Resource):\n\n @api.expect(api.model('UserClassroomInput', {\"id_user\": fields.Integer}))\n @api.response(200, \"User with id: {} added to group: {} \")\n @api.response(404, \"User or classroom not found. \")\n def post(self, id_classroom):\n parser.add_argument(\"id_user\")\n\n parsed_args = parser.parse_args()\n id_user = parsed_args['id_user']\n\n user = user_service.getUser(id_user)\n classroom = classroom_service.getClassroomById(id_classroom)\n\n if user and classroom:\n classroom_service.addUserToClassRoom(classroom.idClassroom, user.idUser, False)\n\n return {\n \"message\": \"User with id: {} added to classroom: {}\".format(user.idUser, classroom.idClassroom)\n }\n else:\n abort(404, \"User or classroom not found. \")\n\n return False\n\n @api.marshal_with(classroom_fields)\n def get(self, id_classroom):\n classroom = classroom_service.getClassroomById(id_classroom)\n\n return classroom\n\n","sub_path":"backend/a2/resources/classroom_resource.py","file_name":"classroom_resource.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"243550695","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom atris.models import HistoricalRecord\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.utils.timezone import now\n\nfrom pytest import mark\n\nfrom tests.models import Poll, Choice, Voter\n\n\n@mark.django_db\ndef test_get_records_by_app_label_and_model_name_returns_specific_entries():\n # arrange\n weather = Poll.objects.create(question='How is the weather?',\n pub_date=now())\n dinner = Poll.objects.create(question='What is for dinner',\n pub_date=now())\n dinner.question = \"What's for dinner?\"\n dinner.save()\n weather.delete()\n ham = Choice.objects.create(poll=dinner, choice='Ham & eggs', votes=0)\n Voter.objects.create(choice=ham, name='John')\n # act\n result = HistoricalRecord.objects.by_app_label_and_model_name(\n Poll._meta.app_label, Poll._meta.model_name\n )\n # assert\n assert result.count() == 4\n poll_content_type = ContentType.objects.get_for_model(Poll)\n by_content_type = result.filter(content_type=poll_content_type)\n assert by_content_type.filter(history_type='+').count() == 2\n assert by_content_type.filter(history_type='-').count() == 1\n assert by_content_type.filter(history_type='~').count() == 1\n\n\n@mark.django_db\ndef test_no_records_by_app_label_and_model_name_returned():\n # arrange\n Poll.objects.create(question='How is the weather?', pub_date=now())\n # act\n result = HistoricalRecord.objects.by_app_label_and_model_name(\n Choice._meta.app_label, Choice._meta.model_name\n )\n # assert\n assert result.exists() is False\n","sub_path":"tests/tests/unit/test_historical_record_queryset.py","file_name":"test_historical_record_queryset.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"352204663","text":"# -*- coding: utf-8 -*-\n# © <2016> \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nfrom openerp import fields, models\n\nclass ev_hr_job(models.Model):\n\t_inherit \t\t= 'hr.job'\n\n\tcompetences \t= fields.Many2many(\n\t\t'hr.eval.comp',\n\t\tstring='Competencias del puesto',\n\t\tondelete='cascade'\n\t)\n\n","sub_path":"hr_evaluation_360/models/ev_hr_job.py","file_name":"ev_hr_job.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"220909621","text":"import argparse\nfrom tqdm import tqdm\nimport os\nimport PIL.Image as Image\nfrom models import resnet101\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom tools import data_transformer\n\nparser = argparse.ArgumentParser(description='RecVis A3 evaluation script')\nparser.add_argument('--data', type=str, default='bird_dataset', metavar='D',\n help=\"folder where data is located. test_images/ need to be found in the folder\")\nparser.add_argument('--model', type=str, default='model.pth', metavar='M',\n help=\"the model file to be evaluated. Usually it is of the form model_X.pth\")\nparser.add_argument('--outdir', type=str, default='features', metavar='D',\n help=\"output directory of the images features\")\n\nargs = parser.parse_args()\nuse_cuda = torch.cuda.is_available()\n\nstate_dict = torch.load(args.model,map_location=lambda storage, loc: storage)\nmodel, input_size = resnet101()\nmodel.load_state_dict(state_dict)\nmodel.eval()\n\nmodel_feature = nn.Sequential(*list(model.children())[:-1])\nfor param in model_feature.parameters():\n param.requires_grad = False\n\n\nif use_cuda:\n print('Using GPU')\n model.cuda()\nelse:\n print('Using CPU')\n\ndata_transforms = data_transformer(input_size)\n\n#test_dir = args.data + '/test_images/mistery_category'\n\ndef read_file_to_dic(path):\n result = {}\n with open(path, 'r') as f:\n for line in f:\n items = line.split()\n key, value = items[0], items[1]\n result[key] = value\n return result\n\ndef read_class_label_to_dic(path):\n result = dict()\n with open(path, 'r') as f:\n for line in f:\n items = line.split()\n image_id, class_label = items[0], items[1]\n if class_label in result:\n result[class_label].append(image_id)\n else:\n result[class_label] = [image_id]\n return result\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n with Image.open(f) as img:\n return img.convert('RGB')\n\nimages_dic = read_file_to_dic('data/CUB_200_2011/CUB_200_2011/images.txt')\nclass_label_dic = read_class_label_to_dic('data/CUB_200_2011/CUB_200_2011/image_class_labels.txt')\n\n\ntotal = 0\nfor categary_id in class_label_dic.keys():\n count = 0\n print(\"Start calculating category \" + categary_id)\n output_file = open(args.outdir+'/'+categary_id+'.txt', \"w\")\n output_file.write(\"Id|Path|Categories|Feature\\n\")\n image_ids = class_label_dic[categary_id]\n for image_id in image_ids:\n count +=1\n image_path = images_dic[image_id]\n data = data_transforms(pil_loader('data/CUB_200_2011/CUB_200_2011/images/'+image_path))\n data = data.view(1, data.size(0), data.size(1), data.size(2))\n if use_cuda:\n data = data.cuda()\n output = np.reshape(model(data).data, 200)\n feature = np.reshape(model_feature(data),(2048))\n pred = np.argsort(-output)[:5]\n output_file.write(\"%s|%s|%s|%s\\n\" % (image_id, image_path, str(pred.tolist()), str(feature.tolist())))\n total += count\n print(\"Finish calculating category \" + categary_id + \". This category contains \" + str(count) + \" images. By now totally \" + str(total) +\" images processed\")\n output_file.close()\n\nprint(\"Succesfully wrote \" + args.outdir + ', you can find each category features with its label number')\n","sub_path":"Model/get_all_images_feature.py","file_name":"get_all_images_feature.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"87035520","text":"from itertools import permutations\n\nimport numpy as np\n\n\nclass Processor:\n def __init__(self, data: np.array, inputs: list):\n self.data = np.append(data, np.zeros(200000, dtype=int))\n self.inputs = inputs\n self.outputs = []\n self.pos = 0\n self.base = 0\n self.halted = 0\n\n @staticmethod\n def process_opcode_and_param(number):\n param = str(number)\n opcode = int(param[-2:])\n mode = param[:-2]\n mode = \"0\" * (3 - len(mode)) + mode\n return opcode, mode[::-1]\n\n def get_index(self, mode, index):\n if mode == \"0\":\n return self.data[index]\n elif mode == \"1\":\n return index\n elif mode == \"2\":\n return self.data[index] + self.base\n\n def get_value(self, mode, index):\n return self.data[self.get_index(mode, index)]\n\n def go(self):\n opcode, mode = self.process_opcode_and_param(self.data[self.pos])\n\n if opcode == 1:\n self.data[self.get_index(mode[2], self.pos + 3)] = self.get_value(\n mode[0], self.pos + 1\n ) + self.get_value(mode[1], self.pos + 2)\n\n self.pos += 4\n\n elif opcode == 2:\n self.data[self.get_index(mode[2], self.pos + 3)] = self.get_value(\n mode[0], self.pos + 1\n ) * self.get_value(mode[1], self.pos + 2)\n self.pos += 4\n\n elif opcode == 3:\n if len(self.inputs) == 0:\n raise ValueError(\"No more inputs!\")\n next_input = self.inputs.pop()\n self.data[self.get_index(mode[0], self.pos + 1)] = next_input\n self.pos += 2\n\n elif opcode == 4:\n self.outputs.append(self.get_value(mode[0], self.pos + 1))\n self.pos += 2\n\n elif opcode == 5:\n if self.get_value(mode[0], self.pos + 1) != 0:\n self.pos = self.get_value(mode[1], self.pos + 2)\n else:\n self.pos += 3\n\n elif opcode == 6:\n if self.get_value(mode[0], self.pos + 1) == 0:\n self.pos = self.get_value(mode[1], self.pos + 2)\n else:\n self.pos += 3\n\n elif opcode == 7:\n value = (\n 1\n if self.get_value(mode[0], self.pos + 1)\n < self.get_value(mode[1], self.pos + 2)\n else 0\n )\n self.data[self.get_index(mode[2], self.pos + 3)] = value\n self.pos += 4\n\n elif opcode == 8:\n value = (\n 1\n if self.get_value(mode[0], self.pos + 1)\n == self.get_value(mode[1], self.pos + 2)\n else 0\n )\n self.data[self.get_index(mode[2], self.pos + 3)] = value\n self.pos += 4\n\n elif opcode == 9:\n self.base += self.get_value(mode[0], self.pos + 1)\n self.pos += 2\n\n elif opcode == 99:\n self.halted = 1\n\n else:\n print(f\"opcode: {opcode}, mode: {mode}\")\n raise ValueError\n\n\ndef solve_amplifier(data, single_input):\n amplifier = Processor(data, single_input)\n while not amplifier.halted:\n amplifier.go()\n return amplifier\n\n\nif __name__ == \"__main__\":\n data = np.genfromtxt(\"day9.txt\", delimiter=\",\", dtype=int)\n inputs = [1]\n\n amplifier = solve_amplifier(data, inputs)\n print(amplifier.outputs[0])\n","sub_path":"2019/day9-1.py","file_name":"day9-1.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"604857679","text":"\n# coding: utf-8\n\n# In[2]:\n\nget_ipython().magic('load_ext autoreload')\nget_ipython().magic('autoreload 2')\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\nimport math\nimport random as rd\n\nimport matplotlib.pyplot as plt\nfrom scipy.stats.stats import pearsonr\nimport warnings\n\n\n# In[5]:\n\nbaseSaveDir = \"/Volumes/Macintosh/cloudDrives/GDrives/pombe_sim/nucleus_sphere/\"\n\nk = 2\nl = 100\nR = 0.5\nalpha_1 = 2 * R / l\nm = 3#int(l / 100)\n\nx_a = np.zeros(l)\ny_a = np.zeros(l)\nx_b = np.zeros(l)\ny_b = np.zeros(l)\nc = np.zeros(l)\nL = np.zeros(l)\nL_th = np.zeros(l)\ndangle = np.zeros([l-1, k])\nspindle = np.zeros([2,2])\nx_a[0] = - R\ny_a[0] = 0.0001\nx_b[0] = - R\ny_b[0] = 0\nc[0] = R\nfor i in range(l):\n L_th[i] = ((0.5) / ((l))) *(i) + 0.7\n \nfor j in range(k-1):\n for i in range(l-1):\n #throw dye to decide which pole to move\n if i/m == int(i/m):\n test = rd.randint(0,1)\n #print(test)\n if test == 0:\n #forward one step\n alpha_1 = 2 * R / l\n if test == 1:\n #stay where it is\n alpha_1 = 0\n x_a[i+1] = x_a[i] + alpha_1\n y_a[i+1] = np.sqrt((R)**2 - x_a[i+1]**2)\n# x_a[i+1] = x_a[i]\n# y_a[i+1] = y_a[i]\n A = ((R**2-L_th[i+1]**2+x_a[i+1]**2+y_a[i+1]**2)/(2*y_a[i+1]))\n rapp = x_a[i+1]/y_a[i+1]\n delta = 4*(R**2-A**2+rapp*rapp*R**2)\n x_b[i+1] = ((2*A*rapp-np.sqrt(delta))/(2*(1+rapp**2)))\n y_b[i+1] = A - rapp*x_b[i+1]\n L[i+1] = np.sqrt((x_a[i+1] - x_b[i+1]) ** 2 + (y_a[i+1] - y_b[i+1]) ** 2)\n c[i+1] = np.sqrt(((x_a[i+1] + x_b[i+1]) / 2) ** 2 + ((y_a[i+1] + y_b[i+1]) / 2) ** 2 )\n #delta angle\n dangle[i, j] = np.arccos((y_a[i] - y_b[i]) / L[i])\n #refresh coords of spindle (two points)\n spindle[0,0] = x_a[i+1]\n spindle[0,1] = y_a[i+1]\n spindle[1,0] = x_b[i+1]\n spindle[1,1] = y_b[i+1]\n fname = baseSaveDir + 'figs/random/' + str(i)\n fig, ax = plt.subplots()\n ax.plot(x_a[0:i+1], y_a[0:i+1], \"o\", color='blue')\n ax.plot(x_b[0:i+1], y_b[0:i+1], \"o\", color='red')\n ax.plot(spindle[:,0], spindle[:,1], \"-\", color='black')\n ax.set_xlim([-R,R])\n ax.set_ylim([-R,R])\n ax.set_aspect(\"equal\")\n fig.savefig(fname)\n plt.close(fig) \n fig, ax = plt.subplots()\n ax.plot(dangle[0:i] * 180 / 3.14, \"-o\", color='blue')\n ax.set_xlim([0,l])\n ax.set_ylim([0,90])\n fig.savefig(baseSaveDir+ 'angle/random/' + str(i))\n plt.close(fig) \n \nfig, ax = plt.subplots()\nax.plot(L, \"-o\", color='blue')\nax.plot(L_th, \"-\", color='black')\nfig, ax = plt.subplots()\nax.plot(x_a, y_a, \"-o\", color='blue')\nax.plot(x_b, y_b, \"-o\", color='red')\nax.plot(spindle[:,0], spindle[:,1], \"-\", color='black')\nax.set_aspect(\"equal\")\nfig, ax = plt.subplots()\nax.plot(dangle * 180 / 3.14, \"-\", color='black')\n\n\n# In[ ]:\n\n\n\n\n# In[6]:\n\nget_ipython().magic('matplotlib inline')\n\nk = 10\nl = 100 #total x points\nR = 1.5 #radius\nalpha_1 = 2 * R / l\nm = int(l / 100)\n\nx_a = np.zeros(l) #x pos of pole a\ny_a = np.zeros(l) #y pos of pole a\nx_b = np.zeros(l) #x pos of pole b\ny_b = np.zeros(l) #y pos of pole b\nc = np.zeros(l)\nL = np.zeros(l)\nL_th = np.zeros(l)\ndangle = np.zeros([l-1, k]) #delta angle\nspindle = np.zeros([2,2]) #\n#pole a begins from (-R, 0)\nx_a[0] = - R \ny_a[0] = 0\n#pole b begins from (-R, 0)\nx_b[0] = - R\ny_b[0] = 0\n\nc[0] = R\nfor i in range(l):\n L_th[i] = ((2 * R) / (np.sqrt(l))) * np.sqrt(i)\n \nfor j in range(k-1):\n for i in range(l-1):\n if i/m == int(i/m):\n test = rd.randint(0,1)\n #print(test)\n if test == 0:\n y_a[i+1] = y_a[i] + (L_th[i+1]-L_th[i]) / 2\n if test == 1:\n y_a[i+1] = y_a[i] + 0\n #y_a[i+1] = L_th[i+1] / 2\n x_a[i+1] = - np.sqrt((R)**2 - y_a[i+1]**2)\n x_b[i+1] = x_a[i+1]\n y_b[i+1] = - y_a[i+1]\n L[i+1] = np.sqrt((x_a[i+1] - x_b[i+1]) ** 2 + (y_a[i+1] - y_b[i+1]) ** 2)\n c[i+1] = np.sqrt(((x_a[i+1] + x_b[i+1]) / 2) ** 2 + ((y_a[i+1] + y_b[i+1]) / 2) ** 2 )\n dangle[i, j] = np.arccos((y_a[i] - y_b[i]) / L[i])\n spindle[0,0] = x_a[i+1]\n spindle[0,1] = y_a[i+1]\n spindle[1,0] = x_b[i+1]\n spindle[1,1] = y_b[i+1]\n \n \nfig, ax = plt.subplots()\nax.plot(L, \"-o\", color='blue')\nax.plot(L_th, \"-\", color='black')\nfig, ax = plt.subplots()\nax.plot(x_a, y_a, \"-o\", color='blue')\nax.plot(x_b, y_b, \"-o\", color='red')\nax.plot(spindle[:,0], spindle[:,1], \"-\", color='black')\nax.set_aspect(\"equal\")\nfig, ax = plt.subplots()\nax.plot(dangle * 180 / 3.14, \"-\", color='black')\n\n\n# In[110]:\n\nk = 50\nl = 2000\nL_initial = 3\nL_final = 4\nalpha_1 = 2 * R / l\n\nx_a = np.zeros(l)\ny_a = np.zeros(l)\nx_b = np.zeros(l)\ny_b = np.zeros(l)\nc = np.zeros(l)\nL = np.zeros(l)\nL_th2 = np.zeros(l)\ndangle = np.zeros([l-1, k])\nspindle = np.zeros([2,2])\nx_a[0] = - R\ny_a[0] = 0\nx_b[0] = - R\ny_b[0] = 0\nc[0] = R\nfor i in range(l):\n L_th2[i] = L_initial + ((L_final - L_initial) / (l)) * (i)\n \n \nfig, ax = plt.subplots()\nax.plot(L_th2, \"-\", color='black')\n\n\n# In[126]:\n\nget_ipython().magic('matplotlib inline')\n\nl = 50\nR = 2\nalpha_1 = 2 * R / l\n\nx_a = np.zeros(l)\ny_a = np.zeros(l)\nx_b = np.zeros(l)\ny_b = np.zeros(l)\nA = -1\nB = 0.5\nx_a[0] = - R/2\ny_a[0] = 0\nx_b[0] = - R/2\ny_b[0] = 0\nc[0] = R\nfor i in range(l):\n L_th[i] = ((2 * R) / (np.sqrt(l))) * np.sqrt(i)\n \nfor i in range(l-1):\n x_a[i+1] = x_a[i] + alpha_1\n y_a[i+1] = np.sqrt(B**2 - ((B*x_a[i+1])**2)/(A**2))\n x_b[i+1] = x_b[i] + alpha_1\n y_b[i+1] = - np.sqrt(B**2 - ((B*x_b[i+1])**2)/(A**2))\n \n \n\nfig, ax = plt.subplots()\nax.plot(x_a, y_a, \"-o\", color='blue')\nax.plot(x_b, y_b, \"-o\", color='red')\nax.set_aspect(\"equal\")\n\n\n# In[39]:\n\nspindle = np.zeros([2,2])\nspindle[0,0] = 1\nprint(spindle)\nspindle[0,1] = 2\nspindle[1,0] = 3\nspindle[1,1] = 4\nprint(spindle)\n\n\nfig, ax = plt.subplots()\nax.plot(spindle[:,0], spindle[:,1], \"-\", color='black')\n\n\n# In[79]:\n\nprint(x_a)\n\n\n# In[38]:\n\nfor i in range(l-1):\n while x_a[i+1] ** 2 + y_a[i+1] ** 2 < 0.99 * d/2 or x_a[i+1] ** 2 + y_a[i+1] ** 2 > 1.01 * d/2:\n x_a[i+1] = x_a[i] + rd.uniform(0,alpha_1)\n y_a[i+1] = y_a[i] + rd.uniform(0,alpha_1)\n y_b[i+1] = y_b[i] - rd.uniform(0,alpha_1)\n print(2 * x_a[i+1] * np.sqrt((d/2)**2 - y_b[i+1]**2) - 2 * y_a[i+1] * y_b[i+1])\n print((L_th[i+1]**2 - 2 * (d/2)**2)*0.99)\n print((L_th[i+1]**2 - 2 * (d/2)**2)*1.01)\n \n\n\n# In[34]:\n\nprint(i)\n\n","sub_path":"simu_pombe/Prometaphase_model-Copy1.py","file_name":"Prometaphase_model-Copy1.py","file_ext":"py","file_size_in_byte":6537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"583825751","text":"\"\"\"\ntests for meld.colfuncs\n\"\"\"\n\nimport os\nimport pandas as pd\nimport meld.colfuncs\n\nCURRENT_PATH = os.path.dirname(__file__)\nTEST_PATH = os.path.join(CURRENT_PATH, \"test_data\", \"test_run0/DATA.csv\")\n\ndef test_collapse_cols():\n \"\"\"meld.colfuncs.collapse_cols(dataframe, sep)\"\"\"\n example_df = pd.read_csv(TEST_PATH, header=[0,1])\n collapsed_colnames = meld.colfuncs.collapse_cols(example_df, sep=\"_\")\n example_df.columns = collapsed_colnames\n expected_colnames = [\"Image_ImageNumber\",\n \"Image_Intensity_channel_1\",\n \"Cell_Area\",\n \"Cell_Eccentricity\",\n \"Nucleus_Area\",\n \"Nucleus_Eccentricity\",\n \"Metadata_Well\"]\n assert collapsed_colnames == expected_colnames\n\n\ndef test_inflate_cols():\n \"\"\"meld.colfuncs.inflate_cols(dataframe)\"\"\"\n # create example dataframe\n example_df = pd.DataFrame(\n {\"Image_ImageNumber\": [1, 2, 3],\n \"Cell_Area\" : [20, 20, 20],\n \"Nuclei_Perimeter\" : [15, 15, 15]}\n )\n example_df.columns = meld.colfuncs.inflate_cols(example_df, sep=\"_\")\n # check the columns are MultiIndexed\n assert isinstance(example_df.columns, pd.core.index.MultiIndex)\n","sub_path":"tests/test_colfuncs.py","file_name":"test_colfuncs.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"584673006","text":"from imutils.video import VideoStream\nimport numpy as np\nimport argparse\nimport imutils\nimport pickle\nimport time\nimport cv2\nimport os\nimport threading\nimport simpleaudio as sa\n\nimport RPi.GPIO as gpio\n\nMOTOR1_FORWARD_GPIO = 14\nON = 1\nOFF = 0\n\ngpio.setmode(gpio.BCM)\ngpio.setwarnings(False)\ngpio.setup(MOTOR1_FORWARD_GPIO, gpio.OUT)\ngpio.output(MOTOR1_FORWARD_GPIO, OFF)\n\ncamIndex = 0\nminConfidence = 0.95\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--detector\", type=str, default=\"face_detection_model\",\n help=\"path to OpenCV's deep learning face detector\")\nap.add_argument(\"-m\", \"--embedding-model\", type=str, default=\"models/openface_nn4.small2.v1.t7\",\n help=\"path to OpenCV's deep learning face embedding model\")\nap.add_argument(\"-r\", \"--recognizer\", type=str, default=\"recognizer.pickle\",\n help=\"path to model trained to recognize faces\")\nap.add_argument(\"-l\", \"--le\", type=str, default=\"labels.pickle\",\n help=\"path to label encoder\")\nap.add_argument(\"-c\", \"--confidence\", type=float, default=0.7,\n help=\"minimum probability to filter weak detections\")\nargs = vars(ap.parse_args())\n\n# load our serialized face detector from disk\nprint(\"[INFO] loading face detector...\")\nprotoPath = \"models/deploy.prototxt\"\nmodelPath = \"models/res10_300x300_ssd_iter_140000.caffemodel\"\ndetector = cv2.dnn.readNetFromCaffe(protoPath, modelPath)\ndetector.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD)\n\n# load our serialized face embedding model from disk and set the\n# preferable target to MYRIAD\nprint(\"[INFO] loading face recognizer...\")\nembedder = cv2.dnn.readNetFromTorch(args[\"embedding_model\"])\nembedder.setPreferableTarget(cv2.dnn.DNN_TARGET_MYRIAD)\n\n# load the actual face recognition model along with the label encoder\nrecognizer = pickle.loads(open(args[\"recognizer\"], \"rb\").read())\nle = pickle.loads(open(args[\"le\"], \"rb\").read())\n\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=camIndex).start()\ntime.sleep(2.0)\n\nfilename1 = 'abhisar.wav'\nwave_obj1 = sa.WaveObject.from_wave_file(filename1)\n\nfilename2 = 'aditya.wav'\nwave_obj2 = sa.WaveObject.from_wave_file(filename2)\n\nfilename3 = 'srinivas.wav'\nwave_obj3 = sa.WaveObject.from_wave_file(filename3)\n\nrecName = \"\"\n\nhuman_detected = False\nplaySound = False\nfail_safe = []\n\nrunMotor = False\n\nmask_play = False\n\ntotalFrames = 0\n\n\ndef thread_for_maskDetection():\n global human_detected\n global play_obj\n global play_obj1\n global vs\n global mask_play\n global totalFrames\n global playSound\n global recName\n global runMotor\n while True:\n # grab the frame from the threaded video stream\n frame = vs.read()\n frame = imutils.resize(frame, width=320)\n # frame = cv2.rotate(frame, cv2.ROTATE_180)\n\n # frame = gamma(frame, gamma=0.5)\n\n # resize the frame to have a width of 600 pixels (while\n # maintaining the aspect ratio), and then grab the image\n # dimensions\n # frame = imutils.resize(frame, width=600)\n (h, w) = frame.shape[:2]\n\n # construct a blob from the image\n imageBlob = cv2.dnn.blobFromImage(\n cv2.resize(frame, (300, 300)), 1.0, (300, 300),\n (104.0, 177.0, 123.0), swapRB=False, crop=False)\n\n # apply OpenCV's deep learning-based face detector to localize\n # faces in the input image\n detector.setInput(imageBlob)\n detections = detector.forward()\n\n # print(\"Human_Detected: {}\".format(human_detected))\n # loop over the detections\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with\n # the prediction\n confidence = detections[0, 0, i, 2]\n # print(confidence)\n # filter out weak detections\n if confidence > args[\"confidence\"]:\n # compute the (x, y)-coordinates of the bounding box for\n # the face\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # extract the face ROI\n face = frame[startY:endY, startX:endX]\n (fH, fW) = face.shape[:2]\n\n # ensure the face width and height are sufficiently large\n if fW < 20 or fH < 20:\n continue\n\n # construct a blob for the face ROI, then pass the blob\n # through our face embedding model to obtain the 128-d\n # quantification of the face\n faceBlob = cv2.dnn.blobFromImage(cv2.resize(face,\n (96, 96)), 1.0 / 255, (96, 96), (0, 0, 0),\n swapRB=True, crop=False)\n embedder.setInput(faceBlob)\n vec = embedder.forward()\n\n # perform classification to recognize the face\n preds = recognizer.predict_proba(vec)[0]\n j = np.argmax(preds)\n proba = preds[j]\n name = le.classes_[j]\n print(\"Proba {} + Name {} \".format(proba, name))\n\n if proba > minConfidence and name == \"Srinivas\":\n playSound = True\n runMotor = True\n recName = \"Srinivas\"\n\n if proba > minConfidence and name == \"Aditya\":\n playSound = True\n runMotor = True\n recName = \"Aditya\"\n\n if proba > minConfidence and name == \"Abhisar\":\n playSound = True\n runMotor = True\n recName = \"Abhisar\"\n\n time.sleep(7)\n\n # draw the bounding box of the face along with the\n # associated probability\n text = \"{}: {:.2f}%\".format(name, proba * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)\n cv2.putText(frame, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)\n\n totalFrames += 1\n cv2.imshow(\"Attendance Tracker\", frame)\n cv2.waitKey(1)\n\n\ndef thread_for_playing_sound():\n global playSound\n global recName\n while True:\n if playSound and recName == \"Abhisar\":\n play_obj1 = wave_obj1.play()\n play_obj1.wait_done()\n playSound = False\n recName = \"\"\n elif playSound and recName == \"Aditya\":\n play_obj2 = wave_obj2.play()\n play_obj2.wait_done()\n playSound = False\n recName = \"\"\n elif playSound and recName == \"Srinivas\":\n play_obj3 = wave_obj3.play()\n play_obj3.wait_done()\n playSound = False\n recName = \"\"\n else:\n pass\n\ndef thread_for_running_motors():\n global runMotor\n while True:\n if runMotor:\n gpio.output(MOTOR1_FORWARD_GPIO, ON)\n time.sleep(3)\n print(\"[INFO]: Stopping Motor...\")\n gpio.output(MOTOR1_FORWARD_GPIO, OFF)\n time.sleep(2)\n runMotor = False\n\n\nif __name__ == \"__main__\":\n t1 = threading.Thread(target=thread_for_maskDetection)\n t2 = threading.Thread(target=thread_for_playing_sound)\n t3 = threading.Thread(target=thread_for_running_motors)\n\n t1.start()\n t2.start()\n t3.start()\n\n t1.join()\n t2.join()\n t3.join()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Product_Line_Code/Automated_Attendance_System/attendance_tracker_old.py","file_name":"attendance_tracker_old.py","file_ext":"py","file_size_in_byte":7576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"598521180","text":"class Store:\n\n def __init__(self, name: str, type: str, capacity: int):\n self.name = name\n self.type = type\n self.capacity = capacity\n self.items = {}\n self.current_quantity = 0\n\n @staticmethod\n def from_size(name: str, type: str, size: int):\n return Store(name, type, int(size/2))\n\n def add_item(self, item_name: str):\n if not self.capacity > self.current_quantity:\n return f\"Not enough capacity in the store\"\n\n self.current_quantity += 1\n if item_name in self.items.keys():\n self.items[item_name] += 1\n else:\n self.items[item_name] = 1\n return f\"{item_name} added to the store\"\n\n def remove_item(self, item_name: str, amount: int):\n if item_name in self.items.keys() and self.items[item_name] >= amount:\n self.items[item_name] -= amount\n self.current_quantity -= amount\n return f\"{amount} {item_name} removed from the store\"\n return f\"Cannot remove {amount} {item_name}\"\n\n def __repr__(self):\n return f\"{self.name} of type {self.type} with capacity {self.capacity}\"\n\n\nfirst_store = Store(\"First store\", \"Fruit and Veg\", 20)\nsecond_store = Store.from_size(\"Second store\", \"Clothes\", 500)\n\nprint(first_store)\nprint(second_store)\n\nprint(first_store.add_item(\"potato\"))\nprint(second_store.add_item(\"jeans\"))\nprint(first_store.remove_item(\"tomatoes\", 1))\nprint(second_store.remove_item(\"jeans\", 1))\n\n","sub_path":"attributes_and_methods_lecture3/LAB/01_new_store.py","file_name":"01_new_store.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"239170020","text":"'''判断101-200之间有多少个素数,并输出所有素数。'''\nn = 0\nfor i in range(101,201):\n for a in range(2,i):\n if i % a == 0: \n break\n else:\n print(i)\n n = n + 1\nprint('101-200之间有{}个素数'.format(n))","sub_path":"1906101009肖文星/ago/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"86201440","text":"# Copyright 2016 VMware, Inc.\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.\nimport mock\n\nfrom oslo_config import cfg\nfrom oslo_utils import uuidutils\n\nfrom neutron import context\nfrom neutron.objects import base as base_object\nfrom neutron.objects.qos import policy as policy_object\nfrom neutron.objects.qos import rule as rule_object\nfrom neutron.services.qos import qos_plugin\nfrom neutron.tests.unit.services.qos import base\n\nfrom vmware_nsx.common import utils\nfrom vmware_nsx.db import db as nsx_db\nfrom vmware_nsx.nsxlib import v3 as nsxlib\nfrom vmware_nsx.services.qos.nsx_v3 import utils as qos_utils\nfrom vmware_nsx.tests.unit.nsxlib.v3 import nsxlib_testcase\n\nPLUGIN_NAME = 'vmware_nsx.plugins.nsx_v3.plugin.NsxV3Plugin'\n\n\nclass TestQosNsxV3Notification(nsxlib_testcase.NsxClientTestCase,\n base.BaseQosTestCase):\n\n def setUp(self):\n super(TestQosNsxV3Notification, self).setUp()\n self.setup_coreplugin(PLUGIN_NAME)\n\n # Add a dummy notification driver that calls our handler directly\n # (to skip the message queue)\n cfg.CONF.set_override(\n \"notification_drivers\",\n ['vmware_nsx.tests.unit.services.qos.fake_notifier.'\n 'DummyNotificationDriver'],\n \"qos\")\n\n self.qos_plugin = qos_plugin.QoSPlugin()\n self.ctxt = context.Context('fake_user', 'fake_tenant')\n self.policy_data = {\n 'policy': {'id': uuidutils.generate_uuid(),\n 'tenant_id': uuidutils.generate_uuid(),\n 'name': 'test-policy',\n 'description': 'Test policy description',\n 'shared': True}}\n self.rule_data = {\n 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(),\n 'max_kbps': 2000,\n 'max_burst_kbps': 150}}\n self.dscp_rule_data = {\n 'dscp_marking_rule': {'id': uuidutils.generate_uuid(),\n 'dscp_mark': 22}}\n\n self.policy = policy_object.QosPolicy(\n self.ctxt, **self.policy_data['policy'])\n\n self.rule = rule_object.QosBandwidthLimitRule(\n self.ctxt, **self.rule_data['bandwidth_limit_rule'])\n self.dscp_rule = rule_object.QosDscpMarkingRule(\n self.ctxt, **self.dscp_rule_data['dscp_marking_rule'])\n\n self.fake_profile_id = 'fake_profile'\n self.fake_profile = {'id': self.fake_profile_id}\n\n mock.patch('neutron.objects.db.api.create_object').start()\n mock.patch('neutron.objects.db.api.update_object').start()\n mock.patch('neutron.objects.db.api.delete_object').start()\n mock.patch(\n 'neutron.objects.qos.policy.QosPolicy.obj_load_attr').start()\n mock.patch.object(nsx_db, 'get_switch_profile_by_qos_policy',\n return_value=self.fake_profile_id).start()\n\n @mock.patch(\n 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin'\n '.create_rbac_policy')\n @mock.patch.object(nsx_db, 'add_qos_policy_profile_mapping')\n def test_policy_create_profile(self, fake_db_add, fake_rbac_create):\n # test the switch profile creation when a QoS policy is created\n with mock.patch.object(nsxlib, 'create_qos_switching_profile',\n return_value=self.fake_profile) as create_profile:\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=self.policy):\n with mock.patch('neutron.objects.qos.policy.QosPolicy.create'):\n policy = self.qos_plugin.create_policy(self.ctxt,\n self.policy_data)\n expected_tags = utils.build_v3_tags_payload(\n policy,\n resource_type='os-neutron-qos-id',\n project_name=self.ctxt.tenant_name)\n\n create_profile.assert_called_once_with(\n description=self.policy_data[\"policy\"][\"description\"],\n name=self.policy_data[\"policy\"][\"name\"],\n tags=expected_tags)\n # verify that the policy->profile mapping entry was added\n self.assertTrue(fake_db_add.called)\n\n @mock.patch(\n 'neutron.objects.rbac_db.RbacNeutronDbObjectMixin'\n '.create_rbac_policy')\n def test_policy_update_profile(self, *mocks):\n # test the switch profile update when a QoS policy is updated\n fields = base_object.get_updatable_fields(\n policy_object.QosPolicy, self.policy_data['policy'])\n with mock.patch.object(nsxlib,\n 'update_qos_switching_profile') as update_profile:\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=self.policy):\n with mock.patch('neutron.objects.qos.policy.QosPolicy.update'):\n self.qos_plugin.update_policy(\n self.ctxt, self.policy.id, {'policy': fields})\n # verify that the profile was updated with the correct data\n self.policy_data[\"policy\"][\"id\"] = self.policy.id\n expected_tags = utils.build_v3_tags_payload(\n self.policy_data[\"policy\"],\n resource_type='os-neutron-qos-id',\n project_name=self.ctxt.tenant_name)\n\n update_profile.assert_called_once_with(\n self.fake_profile_id,\n description=self.policy_data[\"policy\"][\"description\"],\n name=self.policy_data[\"policy\"][\"name\"],\n tags=expected_tags\n )\n\n @mock.patch.object(policy_object.QosPolicy, 'reload_rules')\n def test_bw_rule_create_profile(self, *mocks):\n # test the switch profile update when a QoS BW rule is created\n _policy = policy_object.QosPolicy(\n self.ctxt, **self.policy_data['policy'])\n # add a rule to the policy\n setattr(_policy, \"rules\", [self.rule])\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=_policy):\n with mock.patch.object(nsxlib,\n 'update_qos_switching_profile_shaping') as update_profile:\n self.qos_plugin.update_policy_bandwidth_limit_rule(\n self.ctxt, self.rule.id, _policy.id, self.rule_data)\n\n # validate the data on the profile\n rule_dict = self.rule_data['bandwidth_limit_rule']\n expected_bw = rule_dict['max_kbps'] / 1024\n expected_burst = rule_dict['max_burst_kbps'] * 128\n update_profile.assert_called_once_with(\n self.fake_profile_id,\n average_bandwidth=expected_bw,\n burst_size=expected_burst,\n peak_bandwidth=expected_bw,\n shaping_enabled=True,\n qos_marking='trusted',\n dscp=0\n )\n\n @mock.patch.object(policy_object.QosPolicy, 'reload_rules')\n def test_bw_rule_create_profile_minimal_val(self, *mocks):\n # test the switch profile update when a QoS rule is created\n # with an invalid limit value\n bad_limit = qos_utils.MAX_KBPS_MIN_VALUE - 1\n rule_data = {\n 'bandwidth_limit_rule': {'id': uuidutils.generate_uuid(),\n 'max_kbps': bad_limit,\n 'max_burst_kbps': 150}}\n\n rule = rule_object.QosBandwidthLimitRule(\n self.ctxt, **rule_data['bandwidth_limit_rule'])\n\n _policy = policy_object.QosPolicy(\n self.ctxt, **self.policy_data['policy'])\n # add a rule to the policy\n setattr(_policy, \"rules\", [rule])\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=_policy):\n with mock.patch.object(nsxlib,\n 'update_qos_switching_profile_shaping') as update_profile:\n self.qos_plugin.update_policy_bandwidth_limit_rule(\n self.ctxt, rule.id, _policy.id, rule_data)\n\n # validate the data on the profile\n rule_dict = rule_data['bandwidth_limit_rule']\n expected_bw = qos_utils.MAX_KBPS_MIN_VALUE / 1024\n expected_burst = rule_dict['max_burst_kbps'] * 128\n update_profile.assert_called_once_with(\n self.fake_profile_id,\n average_bandwidth=expected_bw,\n burst_size=expected_burst,\n peak_bandwidth=expected_bw,\n shaping_enabled=True,\n dscp=0,\n qos_marking='trusted'\n )\n\n @mock.patch.object(policy_object.QosPolicy, 'reload_rules')\n def test_dscp_rule_create_profile(self, *mocks):\n # test the switch profile update when a QoS DSCP rule is created\n _policy = policy_object.QosPolicy(\n self.ctxt, **self.policy_data['policy'])\n # add a rule to the policy\n setattr(_policy, \"rules\", [self.dscp_rule])\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=_policy):\n with mock.patch.object(nsxlib,\n 'update_qos_switching_profile_shaping') as update_profile:\n with mock.patch('neutron.objects.db.api.'\n 'update_object', return_value=self.dscp_rule_data):\n self.qos_plugin.update_policy_dscp_marking_rule(\n self.ctxt, self.dscp_rule.id,\n _policy.id, self.dscp_rule_data)\n\n # validate the data on the profile\n rule_dict = self.dscp_rule_data['dscp_marking_rule']\n dscp_mark = rule_dict['dscp_mark']\n update_profile.assert_called_once_with(\n self.fake_profile_id,\n average_bandwidth=None,\n burst_size=None,\n peak_bandwidth=None,\n shaping_enabled=False,\n qos_marking='untrusted',\n dscp=dscp_mark\n )\n\n @mock.patch('neutron.objects.db.api.get_objects',\n return_value=[])\n def test_rule_delete_profile(self, mock_objects):\n # test the switch profile update when a QoS rule is deleted\n _policy = policy_object.QosPolicy(\n self.ctxt, **self.policy_data['policy'])\n # The mock will return the policy without the rule,\n # as if it was deleted\n with mock.patch('neutron.objects.qos.policy.QosPolicy.get_object',\n return_value=_policy):\n with mock.patch.object(nsxlib,\n 'update_qos_switching_profile_shaping') as update_profile:\n setattr(_policy, \"rules\", [self.rule])\n self.qos_plugin.delete_policy_bandwidth_limit_rule(\n self.ctxt, self.rule.id, self.policy.id)\n # validate the data on the profile\n update_profile.assert_called_once_with(\n self.fake_profile_id,\n shaping_enabled=False,\n average_bandwidth=None,\n burst_size=None,\n dscp=0,\n peak_bandwidth=None,\n qos_marking='trusted'\n )\n\n @mock.patch('neutron.objects.db.api.get_object', return_value=None)\n def test_policy_delete_profile(self, *mocks):\n # test the switch profile deletion when a QoS policy is deleted\n with mock.patch.object(nsxlib, 'delete_qos_switching_profile',\n return_value=self.fake_profile) as delete_profile:\n self.qos_plugin.delete_policy(self.ctxt, self.policy.id)\n delete_profile.assert_called_once_with(self.fake_profile_id)\n","sub_path":"vmware_nsx/tests/unit/services/qos/test_nsxv3_notification.py","file_name":"test_nsxv3_notification.py","file_ext":"py","file_size_in_byte":12634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"429222535","text":"#!/usr/bin/env python\n\nimport frozen, os, platform, re, uuid\n\nif platform.system() == \"Windows\":\n\timport _winreg\n\n__firstInstall__ = False\n\ndef is_first_install():\n\treturn __firstInstall__\n\ndef initialize():\n\t\"\"\"\n\tPeform certain initialization functions relating to the directory\n\tMainly, checking if it exists. If it doesn't it is assumed that\n\tthis is being run for the first time.\n\t\"\"\"\n\t\n\tpath = get_default_path()\n\t__firstInstall__ = False\n\t\n\tif not os.path.exists(path):\n\t\t__firstInstall__ = True\n\t\tos.makedirs(path)\n\t\n\t# Make sure each of these exists\n\tdirs = [\"bin\", \"config\", \"html\", \"log\", \"patch\", \"temp\", \"unity3d\",\n\t\t\tos.path.join(path, \"unity3d\", \"nslay\"),\n\t\t\tos.path.join(path, \"unity3d\", \"nplay\")\n\t]\n\t\n\tfor dir in dirs:\n\t\tdirPath = os.path.join(path,dir)\n\t\tif not os.path.exists(dirPath):\n\t\t\tos.makedirs(dirPath)\n\t\n\t# Do first install stuff\n\tif is_first_install() and frozen.we_are_frozen():\n\t\tpass # Todo\n\t\n\t# Generate the JS file\n\t#generate_js_path_file()\n\ndef generate_js_path_file():\n\tlatest = get_latest_nplay_client()\n\tif latest is None:\n\t\treturn\n\t\n\tif platform.system() == \"Windows\":\n\t\tlatest = latest.replace(\"\\\\\", \"\\\\\\\\\")\n\t\n\ttext = 'window.latestClientPath = \"%s\";' % latest\n\t\n\tprint(\"Generating with: %s\" % text)\n\t\n\ttry:\n\t\tf = open(os.path.join(get_default_path(), \"html\", \"js\", \"generated_path.js\"), \"w+\")\n\t\tf.write(text)\n\t\tf.close()\n\texcept IOError as e:\n\t\tprint(str(e))\n\t\treturn\n\ndef get_nplay_client_path(version=\"1.8.3.3\"):\n\t\"\"\" Get the expected path of the NPlay client with specified version \"\"\"\n\treturn os.path.join(get_default_path(), \"unity3d\", \"NPlay_\" + version + \".unity3d\")\n\ndef get_latest_nplay_client():\n\tgreatestVersion = None\n\tclientPath = os.path.join(get_default_path(), \"unity3d\")\n\t\n\tp = re.compile(r\"^NPlay_((\\d+\\.)*\\d+)\\.unity3d$\")\n\tdirs = os.listdir(clientPath)\n\tfor dir in dirs:\n\t\tm = p.match(dir)\n\t\tif m is None: continue\n\t\t\n\t\tversionStr = m.group(1)\n\t\t\n\t\t# Set the greatest version\n\t\tif greatestVersion is None:\n\t\t\tgreatestVersion = versionStr\n\t\telse:\n\t\t\tgreatestVersion = get_greater_version(greatestVersion, versionStr)\n\t\n\t# No NPlay clients found?\n\tif greatestVersion is None:\n\t\treturn None\n\t\n\t# Return absolute path to the latest version\n\treturn os.path.join(clientPath, \"NPlay_\" + greatestVersion + \".unity3d\")\n\ndef get_nslay_client_path():\n\t\"\"\" Get the latest NSlay client path,\n\tshould always be at $PATCHER/unity3d/NSlay.unity3d \"\"\"\n\treturn os.path.join(get_default_path(), \"unity3d\", \"NSlay_BeGone.unity3d\")\n\ndef has_nslay_client():\n\treturn os.path.isfile(get_nslay_client_path())\n\t\ndef get_greater_version(v1, v2):\n\t\"\"\" Helper function for getting the greatest version Id \"\"\"\n\tv1s = v1.split(\".\")\n\tv2s = v2.split(\".\")\n\t\n\tm = min(len(v1s), len(v2s))\n\tfor i in xrange(0, m):\n\t\tn1 = int(v1s[i])\n\t\tn2 = int(v2s[i])\n\t\tif n1 > n2:\n\t\t\treturn v1\n\t\telif n2 > n1:\n\t\t\treturn v2\n\t\n\t# If we're still here, we're doing a comparison like\n\t# \"1.2.3\" vs. \"1.2.3.4\"\n\t# Just return the longer string\n\tif len(v1) > len(v2):\n\t\treturn v1\n\telse:\n\t\treturn v2\n\t\ndef cleanup_temp():\n\t\"\"\" Cleanup the temp directory. Meant to be called on start/exit. \"\"\"\n\tpath = os.path.join(get_default_path(), \"temp\")\n\t\n\t# Get list of files in temp\n\ttfiles = []\n\tfor (dirpath, dirnames, filenames) in os.walk(path):\n\t\ttfiles.extend(filenames)\n\t\tbreak\n\t\n\t# Remove each file in temp\n\tfor tfile in tfiles:\n\t\tos.remove(os.path.join(path, tfile))\n\t\ndef get_default_path():\n\t\"\"\" Get the default path of this directory \"\"\"\n\tif platform.system() == \"Windows\":\n\t\t# Get the AppData directory\n\t\tpath = os.path.join(os.getenv(\"APPDATA\"), \"NSlay\", \"Patcher\")\n\telse: # Assuming OSX/Unix-based\n\t\tpath = os.path.expanduser(os.path.join(\"~\", \".nslay\", \"patcher\"))\n\treturn path\n\ndef get_html_path():\n\treturn os.path.join(get_default_path(), \"html\", \"BeGone.html\")\n\t\ndef get_temp_file():\n\t\"\"\" Get the path to a possible random file in the temp directory \"\"\"\n\tfilename = str(uuid.uuid4()).replace(\"-\", \"\")\n\treturn os.path.join(get_default_path(), \"temp\", filename)\n\ndef get_default_browser():\n\t\"\"\" Attempt to detect the default browser \"\"\"\n\tif platform.system() == \"Windows\":\n\t\tbrowser = \"Internet Explorer\"\n\t\ttry:\n\t\t\twith _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, \"Software\\Classes\\http\\shell\\open\\command\") as key:\n\t\t\t\t# Note: \"(Default)\" = None\n\t\t\t\tkeyinfo = _winreg.QueryValueEx(key, None)\n\t\t\t\t\n\t\t\t\tif \"firefox.exe\" in keyinfo[0]:\n\t\t\t\t\tbrowser = \"firefox\"\n\t\t\t\telif \"chrome.exe\" in keyinfo[0]:\n\t\t\t\t\tbrowser = \"chrome\"\n\t\t\t\telif \"safari.exe\" in keyinfo[0]:\n\t\t\t\t\tbrowser = \"safari\"\n\t\t\t\telif \"opera.exe\" in keyinfo[0]:\n\t\t\t\t\tbrowser = \"opera\"\n\t\t\t\t\n\t\t\t\t_winreg.CloseKey(key)\n\t\texcept WindowsError as e:\n\t\t\tprint(str(e))\n\t\t\tpass\n\t\t\n\t\treturn browser","sub_path":"src/nslay/patcher/appdir.py","file_name":"appdir.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"122101246","text":"from clustering_g import *\n\nX = make_clusters()\nxdf = pd.DataFrame(X)\nxdf['id'] = range(1,len(xdf)+1)\n\nlabeled_dfs, wcss_df, summary_dfs = clustering_g(xdf, nclstr_min=2, nclstr_max=15, nclstr_step=1)\n\nS_list = list(wcss_df['wcss'])\n\nK_range = [int(x) for x in list(wcss_df['nclstr'])]\n\n\n\n","sub_path":"PythonClustering/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"318589653","text":"\"\"\"\nStochastic Model FBHP\n---------------------\n\n\n\n\n\nNotes:\n\n04/30/2016 - this model is in development and not yet ready. The skeleton\nstill reflects the FSHP model. I have to add the banded structure to this.\n\n\n\n\"\"\"\n\n\n\n__author__ = 'krishnab'\n__version__ = '0.1.0'\n\n\nfrom operator import neg, truediv\nimport numpy as np\nimport pandas as pd\nfrom numpy.random import binomial\nfrom .Models import Base_model\n\n\nMODEL_RUN_COLUMNS = list(['number_f1',\n 'number_f2',\n 'number_f3',\n 'number_m1',\n 'number_m2',\n 'number_m3',\n 'vacancies_3',\n 'vacancies_2',\n 'vacancies_1',\n 'prom1',\n 'prom2',\n 'gender_proportion_overall',\n 'unfilled_vacancies',\n 'department_size',\n 'f_hire_3',\n 'm_hire_3',\n 'f_hire_2',\n 'm_hire_2',\n 'f_hire_1',\n 'm_hire_1',\n 'f_prom_3',\n 'm_prom_3',\n 'f_prom_2',\n 'm_prom_2',\n 'f_prom_1',\n 'm_prom_1'])\n\nEXPORT_COLUMNS_FOR_CSV = list([ 'hiring_rate_women_1',\n 'hiring_rate_women_2',\n 'hiring_rate_women_3',\n 'hiring_rate_men_1',\n 'hiring_rate_men_2',\n 'hiring_rate_men_3',\n 'attrition_rate_women_1',\n 'attrition_rate_women_2',\n 'attrition_rate_women_3',\n 'attrition_rate_men_1',\n 'attrition_rate_men_2',\n 'attrition_rate_men_3',\n 'probablity_of_outside_hire_1',\n 'probability_of_outside_hire_2',\n 'probability_of_outside_hire_3',\n 'female_promotion_rate_1',\n 'female_promotion_rate_2',\n 'male_promotion_rate_1',\n 'male_promotion_rate_2',\n 'dept_size_upperbound',\n 'dept_size_lowerbound',\n 'dept_size_exogenous_variation_range',\n 'duration'])\n\nclass Mod_Stoch_FBHP(Base_model):\n\n def __init__(self, **kwds):\n Base_model.__init__(self, **kwds)\n self.name = \"Hire-Promote\"\n self.label = \"Hire-Promote\"\n def run_model(self):\n\n ## initialize data structure\n\n self.res = np.zeros([self.duration,\n len(MODEL_RUN_COLUMNS) +\n len(\n EXPORT_COLUMNS_FOR_CSV)],\n dtype=np.float32)\n\n self.res[0, 0] = self.nf1\n self.res[0, 1] = self.nf2\n self.res[0, 2] = self.nf3\n self.res[0, 3] = self.nm1\n self.res[0, 4] = self.nm2\n self.res[0, 5] = self.nm3\n self.res[0, 6] = 0\n self.res[0, 7] = 0\n self.res[0, 8] = 0\n self.res[0, 9] = self.female_promotion_probability_1\n self.res[0, 10] = self.female_promotion_probability_2\n self.res[0, 11] = np.float32(\n sum(list([self.nf1, self.nf2, self.nf3])) / sum(list([self.nf1,\n self.nf2,\n self.nf3,\n self.nm1,\n self.nm2,\n self.nm3])))\n self.res[0,12] = 0\n self.res[0,13] = self.res[0, 0:6].sum()\n self.res[0,14:] = 0\n\n # I assign the state variables to temporary variables. That way I\n # don't have to worry about overwriting the original state variables.\n\n hiring_rate_female_level_1 = self.bf1\n hiring_rate_female_level_2 = self.bf2\n hiring_rate_female_level_3 = self.bf3\n attrition_rate_female_level_1 = self.df1\n attrition_rate_female_level_2 = self.df2\n attrition_rate_female_level_3 = self.df3\n attrition_rate_male_level_1 = self.dm1\n attrition_rate_male_level_2 = self.dm2\n attrition_rate_male_level_3 = self.dm3\n probability_of_outside_hire_level_3 = self.phire3\n probability_of_outside_hire_level_2 = self.phire2\n female_promotion_probability_1_2 = self.female_promotion_probability_1\n female_promotion_probability_2_3 = self.female_promotion_probability_2\n department_size_upper_bound = self.upperbound\n department_size_lower_bound = self.lowerbound\n variation_range = self.variation_range\n unfilled_vacanies = 0\n change_to_level_1 = 0\n change_to_level_2 = 0\n change_to_level_3 = 0\n\n for i in range(1, self.duration):\n # initialize variables for this iteration\n\n\n\n prev_number_of_females_level_1 = self.res[i - 1, 0]\n prev_number_of_females_level_2 = self.res[i - 1, 1]\n prev_number_of_females_level_3 = self.res[i - 1, 2]\n prev_number_of_males_level_1 = self.res[i - 1, 3]\n prev_number_of_males_level_2 = self.res[i - 1, 4]\n prev_number_of_males_level_3 = self.res[i - 1, 5]\n prev_number_of_vacancies_level_3 = self.res[i - 1, 6]\n prev_number_of_vacancies_level_2 = self.res[i - 1, 7]\n prev_number_of_vacancies_level_1 = self.res[i - 1, 8]\n prev_promotion_rate_female_level_1 = self.female_promotion_probability_1\n prev_promotion_rate_female_level_2 = self.female_promotion_probability_2\n department_size = self.res[i - 1, 0:6].sum()\n\n\n # Process Model\n\n # Determine department size variation for this timestep\n\n\n # first both female and males leave the department according to binomial probability.\n\n female_attrition_level_3 = binomial(prev_number_of_females_level_3,\n attrition_rate_female_level_3)\n\n male_attrition_level_3 = binomial(prev_number_of_males_level_3,\n attrition_rate_male_level_3)\n\n # the departures create a set of vacancies. These vacancies are the basis for new hiring\n total_vacancies_3 = female_attrition_level_3 + \\\n male_attrition_level_3 + change_to_level_3\n\n # women are hired first and then men\n hiring_female_3 = binomial(max(0,total_vacancies_3),\n probability_of_outside_hire_level_3 * hiring_rate_female_level_3)\n\n hiring_male_3 = binomial(max(0, total_vacancies_3 - hiring_female_3),\n probability_of_outside_hire_level_3 * (\n 1 - hiring_rate_female_level_3))\n\n total_hiring_3 = hiring_female_3 + hiring_male_3\n\n # level 3 vacancies that are not filled by new hires create opportunities\n # for promotion from level 2. Again women are promoted first and men second.\n # Also note the error trap that if we try to promote more professors from\n # level 2 than there exist at level 2, then we will prevent this from happening.\n\n vacancies_remaining_after_hiring_3 = total_vacancies_3 - total_hiring_3\n\n potential_promotions_after_hiring_3 = max(0,\n vacancies_remaining_after_hiring_3)\n\n promotions_of_females_level_2_3 = binomial(min(\n potential_promotions_after_hiring_3,\n prev_number_of_females_level_2),\n female_promotion_probability_2_3)\n\n promotions_of_males_level_2_3 = binomial(max(0,min(\n vacancies_remaining_after_hiring_3\n -promotions_of_females_level_2_3,\n prev_number_of_males_level_2)),\n 1 - female_promotion_probability_2_3)\n\n # attrition at level 2 - either people leave from attrition or promotion\n\n female_attrition_level_2 = binomial(\n max(0,prev_number_of_females_level_2\n - promotions_of_females_level_2_3),\n attrition_rate_female_level_2)\n\n male_attrition_level_2 = binomial(\n max(0,prev_number_of_males_level_2\n - promotions_of_males_level_2_3),\n attrition_rate_male_level_2)\n\n # the departures create a set of vacancies. These vacancies are the basis for new hiring\n total_vacancies_2 = sum(list([female_attrition_level_2,\n male_attrition_level_2,\n promotions_of_females_level_2_3,\n promotions_of_males_level_2_3,\n change_to_level_2]))\n\n hiring_female_2 = binomial(max(0,total_vacancies_2),\n probability_of_outside_hire_level_2 * hiring_rate_female_level_2)\n hiring_male_2 = binomial(max(0,total_vacancies_2-hiring_female_2),\n probability_of_outside_hire_level_2 * (1-hiring_rate_female_level_2))\n\n total_hiring_2 = hiring_female_2 + hiring_male_2\n\n vacancies_remaining_after_hiring_2 = total_vacancies_2 - total_hiring_2\n\n potential_promotions_after_hiring_2 = max(0,\n vacancies_remaining_after_hiring_2)\n\n promotions_of_females_level_1_2 = binomial(max(0,\n min(potential_promotions_after_hiring_2, prev_number_of_females_level_1)),\n female_promotion_probability_1_2)\n\n promotions_of_males_level_1_2 = binomial(max(0,min(\n vacancies_remaining_after_hiring_2 -\n promotions_of_females_level_1_2,\n prev_number_of_females_level_1)),\n probability_of_outside_hire_level_2*(1 - female_promotion_probability_1_2))\n\n\n ## Level 1\n\n female_attrition_level_1 = binomial(max(0,prev_number_of_females_level_1-promotions_of_females_level_1_2),\n attrition_rate_female_level_1)\n\n male_attrition_level_1 = binomial(max(0,prev_number_of_males_level_1-promotions_of_males_level_1_2),\n attrition_rate_male_level_1)\n\n total_vacancies_1 = sum(list([female_attrition_level_1,\n male_attrition_level_1,\n promotions_of_females_level_1_2,\n promotions_of_males_level_1_2,\n change_to_level_1]))\n\n hiring_female_1 = binomial(max(0,total_vacancies_1),\n hiring_rate_female_level_1)\n\n hiring_male_1 = binomial(max(0,total_vacancies_1 - hiring_female_1),\n 1 - hiring_rate_female_level_1)\n\n # Write state variables to array and move to next iteration\n\n self.res[i, 0] = number_of_females_level_1 = sum(\n list([prev_number_of_females_level_1,\n neg(female_attrition_level_1),\n neg(promotions_of_females_level_1_2),\n hiring_female_1]))\n\n assert (number_of_females_level_1 >= 0), \"negative number of females 1\"\n\n\n self.res[i, 1] = number_of_females_level_2 = max(0, sum(\n list([prev_number_of_females_level_2,\n neg(female_attrition_level_2),\n neg(promotions_of_females_level_2_3),\n promotions_of_females_level_1_2,\n hiring_female_2])))\n\n self.res[i, 2] = number_of_females_level_3 = sum(list([\n prev_number_of_females_level_3,\n neg(female_attrition_level_3),\n promotions_of_females_level_2_3,\n hiring_female_3]))\n\n self.res[i, 3] = number_of_males_level_1 = sum(list([\n prev_number_of_males_level_1,\n neg(male_attrition_level_1),\n neg(promotions_of_males_level_1_2),\n hiring_male_1]))\n\n self.res[i, 4] = number_of_males_level_2 = sum(\n list([prev_number_of_males_level_2,\n neg(male_attrition_level_2),\n neg(promotions_of_males_level_2_3),\n promotions_of_males_level_1_2,\n hiring_male_2]))\n\n self.res[i, 5] = number_of_males_level_3 = sum(\n list([prev_number_of_males_level_3,\n neg(male_attrition_level_3),\n promotions_of_males_level_2_3,\n hiring_male_3]))\n\n self.res[i, 6] = sum(list([\n male_attrition_level_3,\n female_attrition_level_3]))\n\n self.res[i, 7] = sum(list([\n male_attrition_level_2,\n female_attrition_level_2,\n promotions_of_females_level_2_3,\n promotions_of_males_level_2_3]))\n\n self.res[i, 8] = sum(list([\n male_attrition_level_1,\n female_attrition_level_1,\n promotions_of_males_level_1_2,\n promotions_of_females_level_1_2]))\n\n self.res[i, 9] = self.female_promotion_probability_1\n self.res[i, 10] = self.female_promotion_probability_2\n self.res[i, 11] = np.float32(\n truediv(sum(list([number_of_females_level_1,\n number_of_females_level_2,\n number_of_females_level_3])), sum(list([\n number_of_females_level_1,\n number_of_females_level_2,\n number_of_females_level_3,\n number_of_males_level_1,\n number_of_males_level_2,\n number_of_males_level_3]))))\n unfilled_vacanies = abs(department_size - self.res[i, 0:6].sum())\n\n self.res[i, 12] = unfilled_vacanies\n department_size = self.res[i, 0:6].sum()\n self.res[i, 13] = department_size\n self.res[i, 14] = hiring_female_3\n self.res[i, 15] = hiring_male_3\n self.res[i, 16] = hiring_female_2\n self.res[i, 17] = hiring_male_2\n self.res[i, 18] = hiring_female_1\n self.res[i, 19] = hiring_male_1\n self.res[i, 20] = 0\n self.res[i, 21] = 0\n self.res[i, 22] = promotions_of_females_level_2_3\n self.res[i, 23] = promotions_of_males_level_2_3\n self.res[i, 24] = promotions_of_females_level_1_2\n self.res[i, 25] = promotions_of_males_level_1_2\n self.res[i, 26] = hiring_rate_female_level_1\n self.res[i, 27] = hiring_rate_female_level_2\n self.res[i, 28] = hiring_rate_female_level_3\n self.res[i, 29] = 1 - hiring_rate_female_level_1\n self.res[i, 30] = 1 - hiring_rate_female_level_2\n self.res[i, 31] = 1 - hiring_rate_female_level_3\n self.res[i, 32] = attrition_rate_female_level_1\n self.res[i, 33] = attrition_rate_female_level_2\n self.res[i, 34] = attrition_rate_female_level_3\n self.res[i, 35] = attrition_rate_male_level_1\n self.res[i, 36] = attrition_rate_male_level_2\n self.res[i, 37] = attrition_rate_male_level_3\n self.res[i, 38] = 1\n self.res[i, 39] = probability_of_outside_hire_level_2\n self.res[i, 40] = probability_of_outside_hire_level_3\n self.res[i, 41] = female_promotion_probability_1_2\n self.res[i, 42] = female_promotion_probability_2_3\n self.res[i, 43] = 1 - female_promotion_probability_1_2\n self.res[i, 44] = 1 - female_promotion_probability_2_3\n self.res[i, 45] = department_size_upper_bound\n self.res[i, 46] = department_size_lower_bound\n self.res[i, 47] = variation_range\n self.res[i, 48] = self.duration\n\n\n # this produces an array of values. Then I need to assign the\n # values to levels. So if I have say a range of variation of 5. I\n # will get something like [-1,0,1,-1,0] or something. I need to\n # turn this into something like [2,-1,0]. That means randomly\n # assigning the values in the array to levels.\n\n flag = False\n while flag == False:\n\n changes = np.random.choice([-1, 0, 1], variation_range)\n\n levels = np.random.choice([1, 2, 3], variation_range) #\n # random level\n # choice\n\n # need to test whether the candidate changes keep the\n # department size within bounds.\n # print([\"old dept size:\", department_size,\n # \"new dept size:\", self.res[i, 0:6].sum(),\n # \"candidate:\", department_size +\n # changes.sum(),\n # \" added postions: \", changes.sum(),\n # \"unfilled \", unfilled_vacanies])\n if (department_size + changes.sum() <=\n department_size_upper_bound and department_size +\n changes.sum() >= department_size_lower_bound):\n change_to_level_3 = np.int(changes[np.where(levels ==\n 3)[0]].sum())\n change_to_level_2 = np.int(changes[np.where(levels ==\n 2)[0]].sum())\n change_to_level_1 = np.int(changes[np.where(levels ==\n 1)[0]].sum())\n flag = True\n\n if (department_size > department_size_upper_bound):\n change_to_level_3 = 0\n change_to_level_2 = 0\n change_to_level_1 = 0\n\n flag = True\n\n if department_size < department_size_lower_bound:\n changes = np.ones(variation_range)\n change_to_level_3 = np.int(changes[np.where(levels ==\n 3)[0]].sum())\n change_to_level_2 = np.int(changes[np.where(levels ==\n 2)[0]].sum())\n change_to_level_1 = np.int(changes[np.where(levels ==\n 1)[0]].sum())\n flag = True\n\n\n\n df_ = pd.DataFrame(self.res)\n df_.columns = MODEL_RUN_COLUMNS + EXPORT_COLUMNS_FOR_CSV\n\n recarray_results = df_.to_records(index=True)\n self.run = recarray_results\n return recarray_results\n\n","sub_path":"pyugend/Mod_Stoch_FBHP.py","file_name":"Mod_Stoch_FBHP.py","file_ext":"py","file_size_in_byte":19358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"497241459","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nMy_location = []\n\ndef coord_banks(lat, lng):\n global My_location\n My_location = [lat, lng]\n Banks = []\n URLt = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={0},{1}&radius=2000&type=bank&language=ru&key=AIzaSyA4TW4MaPG_YUkCrUWJypsFIgO1OGre6m8'\n URL = URLt.format(lat, lng)\n inf_banks_location = json.loads(requests.get(URL).content)['results']\n for bank in inf_banks_location:\n Banks.append([bank['name'], bank['geometry']['location']['lat'], bank['geometry']['location']['lng']])\n return Banks\n\ndef sortByDist(Bank):\n return ((Bank[1] - float(My_location[0])) ** 2 + (Bank[2] - float(My_location[1])) ** 2)\n \n\ndef nearest_10(lat, lng):\n Banks = coord_banks(lat, lng)\n Banks.sort(key=sortByDist)\n return Banks[:10]\n\n \n","sub_path":"gapi.py","file_name":"gapi.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"599307375","text":"#!/usr/bin/env python\n# check.py\nimport os, subprocess\nfrom pkg_resources import parse_version\n\n\ndef get_version_number(parsed_version_nr=None):\n \"\"\"\n We check if update version is newer then us\n\n IMPORTANT NOTE: If you want to execute an executable from the compiled exe\n and get back the return or output you have to use subprocess and configure it proper.\n Be sure to set stdout/stdin to subprocess.PIPE. Otherwise getdaily will loose the handle\n to executed program.\n \"\"\"\n\n if parsed_version_nr is not None:\n output = parsed_version_nr\n else:\n _LOCALVERSION = 'getdaily.exe -version' # parse -version to get version number from getdaily\n\n abscommand = os.path.abspath(_LOCALVERSION)\n\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW\n\n output = subprocess.Popen(abscommand, startupinfo=startupinfo, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT, stdin=subprocess.PIPE).communicate()\n\n output = output[0].strip() # filter version number from output\n\n return output\n\ndef check_am_i_old(local_ver_num, update_ver_num):\n \"\"\"\n compare versions and return if we are old or not.\n :return: True or False\n \"\"\"\n\n amiold = parse_version(local_ver_num) < parse_version(update_ver_num)\n\n return amiold","sub_path":"Updater/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"295876827","text":"import os\nfrom queryable import rawsqueryable_obj\nfrom file import rawsfile\n\nclass rawsdir(rawsqueryable_obj):\n '''Represents as a whole all the raws contained within a directory.'''\n \n def __init__(self, *args, **kwargs):\n '''Constructor for rawsdir object.'''\n self.files = {}\n if len(args) or len(kwargs): self.read(*args, **kwargs)\n \n def getfile(self, filename, create=False):\n rfile = self.files.get(filename)\n if create and rfile is None:\n return self.addfile(filename)\n else:\n return rfile\n def addfile(self, filename=None, rfile=None, path=None):\n if path is not None:\n return self.addpath(path)\n else:\n if rfile and not filename: filename = rfile.header\n if filename in self.files: raise KeyError\n if not rfile: rfile = rawsfile(header=filename)\n self.files[filename] = rfile\n rfile.dir = self\n return rfile\n def setfile(self, filename=None, rfile=None):\n if rfile and not filename: filename = rfile.header\n rfile.dir = self\n self.files[filename] = rfile\n def removefile(self, filename=None, rfile=None):\n if not rfile.dir == self: raise ValueError\n if rfile and not filename: filename = rfile.header\n rfile.dir = None\n del self.files[filename]\n \n def addpath(self, path):\n with open(path, 'rb') as rfilestream:\n rfile = rawsfile(path=path, rfile=rfilestream, dir=self)\n if rfile.header in self.files: raise ValueError\n self.files[rfile.header] = rfile\n return rfile\n \n def __getitem__(self, name): return self.getfile(name)\n def __setitem__(self, name, value): return self.setfile(name, value)\n \n def read(self, path, log=None):\n '''Reads raws from all text files in the specified directory.'''\n for filename in os.listdir(path):\n filepath = os.path.join(path, filename)\n if filename.endswith('.txt') and os.path.isfile(filepath\n ):\n if log: log.debug('Reading file %s...' % filepath)\n with open(filepath, 'rb') as rfile:\n filenamekey = os.path.splitext(os.path.basename(filename))[0]\n self.files[filenamekey] = rawsfile(path=filepath, rfile=rfile, dir=self)\n return self\n \n def write(self, path, log=None):\n '''Writes raws to the specified directory.'''\n for filename in self.files:\n filepath = os.path.join(path, filename)\n if not filepath.endswith('.txt'): filepath += '.txt'\n with open(filepath, 'wb') as rfile:\n if log: log.debug('Writing file %s...' % filepath)\n self.files[filename].write(rfile)\n return self\n \n def tokens(self):\n '''Iterate through all tokens.'''\n for filename in self.files:\n for token in self.files[filename].tokens():\n yield token\n","sub_path":"raws/dir.py","file_name":"dir.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"358184580","text":"class Solution:\r\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\r\n candidates.sort()\r\n\r\n ans = []\r\n\r\n def backtrack(curr, pos, target):\r\n if target == 0:\r\n ans.append(curr.copy())\r\n\r\n if target <= 0:\r\n return\r\n\r\n prev = -1\r\n\r\n for i in range(pos, len(candidates)):\r\n if candidates[i] == prev:\r\n continue\r\n\r\n curr.append(candidates[i])\r\n backtrack(curr, i + 1, target - candidates[i])\r\n\r\n curr.pop()\r\n\r\n prev = candidates[i]\r\n\r\n backtrack([], 0, target)\r\n\r\n return ans\r\n","sub_path":"combination-sum-ii.py","file_name":"combination-sum-ii.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"263570275","text":"# 反转链表\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def ReverseList(self, pHead):\n if not pHead or not pHead.next:\n return pHead\n\n Node = None\n while pHead:\n p = pHead\n pHead = pHead.next\n p.next = Node\n Node = p\n return Node","sub_path":"basic_algorithm/reverserlist.py","file_name":"reverserlist.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"217158334","text":"import numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.utils.data as D\n\nimport random\n\nfrom PIL import Image\nimport PIL.ImageChops as ImageChops\nimport PIL.ImageOps as ImageOps\nfrom scipy import ndimage\n\nimport torchvision\nfrom torchvision import transforms as T\n\nclass ImagesDS(D.Dataset):\n def __init__(self, csv_file, img_dir, mode='train', useBothSites=True, channels=[1, 2, 3, 4, 5, 6], useOnly=0, withoutControls=False):\n\n df = pd.read_csv(csv_file)\n self.records = df.to_records(index=False)\n self.channels = channels\n self.mode = mode\n self.img_dir = img_dir\n self.useBothSites = useBothSites\n self.withoutControls = withoutControls\n Nexamples = df.shape[0]\n if useOnly > 0:\n Nexamples = min(Nexamples, useOnly)\n if useBothSites:\n self.len = 2 * Nexamples # site1 and site2\n else:\n self.len = Nexamples\n\n @staticmethod\n def _remove_artifacts(img):\n x1 = img[1 - 1, :, :]\n x2 = img[2 - 1, :, :]\n x3 = img[3 - 1, :, :]\n x4 = img[4 - 1, :, :]\n x5 = img[5 - 1, :, :]\n x6 = img[6 - 1, :, :]\n tt = 0.3\n boolVector = (x1 > tt) & (x2 > tt) & (x3 > tt) & (x4 > tt) & (x5 > tt) & (x6 > tt)\n y1 = np.where(boolVector, 0.3, x1)\n y2 = np.where(boolVector, 0.3, x2)\n y3 = np.where(boolVector, 0.3, x3)\n y4 = np.where(boolVector, 0.3, x4)\n y5 = np.where(boolVector, 0.3, x5)\n y6 = np.where(boolVector, 0.3, x6)\n # and x3>0.1 and x4>0.1 and x5>0.1 and x6>0.1\n # img[1-1, :, :] = torch.as_tensor(y1)\n img[2 - 1, :, :] = torch.as_tensor(y2)\n img[3 - 1, :, :] = torch.as_tensor(y3)\n # img[4-1, :, :] = torch.as_tensor(y4)\n img[5 - 1, :, :] = torch.as_tensor(y5)\n img[6 - 1, :, :] = torch.as_tensor(y6)\n\n return img\n\n def _add_noise(img, mean=0, std=0.1):\n\n noise = img.new_tensor(img.data).normal_(mean=mean,std = std)\n #print(img)\n #print(img.shape)\n #print(noise.shape)\n out = torch.add(img, noise)\n\n return out\n\n @staticmethod\n def _correct_overlaping_channels(img):\n img = ImagesDS._remove_artifacts(img)\n # return img\n tt = 0.1\n # CORRECT OVERLAPPING CHANNELS\n # correct nucleolus:\n x0 = img[1 - 1, :, :] # nucleus\n x = img[4 - 1, :, :] # nucleolus\n x = np.where(x > x0, x0, x)\n img[4 - 1, :, :] = torch.as_tensor(x)\n\n # correct golgi (remove nucleus signal and actin signal)\n x1 = img[1 - 1, :, :] # nucleus\n x2 = img[3 - 1, :, :].numpy() # actin\n x = img[6 - 1, :, :] # golgi\n # remove nucleus from golgi\n x = np.where(x1 > tt, 0, x)\n # remove actin from golgi\n x = np.where(x2 > x, 0, x)\n img[6 - 1, :, :] = torch.as_tensor(x)\n\n # remove necleus signal from endoplasmatic reticulum\n x0 = img[1 - 1, :, :] # nucleus\n x = img[2 - 1, :, :] # ER\n x = np.where(x0 > 0.3, 0, x)\n img[2 - 1, :, :] = torch.as_tensor(x)\n\n # correct actin and mitochondria (remove nucleolus signal)\n x0 = img[4 - 1, :, :] # nucleolus\n x1 = img[3 - 1, :, :] # actin\n x2 = img[5 - 1, :, :] # mitochondria\n x3 = img[6 - 1, :, :].numpy() # golgi\n\n # remove nucleolus signal\n x1 = np.where(x0 > tt, 0, x1)\n # remove golgi from actin\n x1 = np.where(x3 > x1, 0, x1)\n img[3 - 1, :, :] = torch.as_tensor(x1)\n\n # remove nucleolus from mitochondria\n x2 = np.where(x0 > tt, 0, x2)\n img[5 - 1, :, :] = torch.as_tensor(x2)\n\n return img\n\n @staticmethod\n def _load_img_as_tensor(file_name, r1, r2, r3, startx=0, starty=0, noiseLevel=0,size=512):\n output_size = 336\n\n with Image.open(file_name) as img:\n\n img = T.functional.crop(img, startx, starty, size, size)\n #img = T.functional.resize(img,output_size)\n\n angle = r1 * 90\n\n img = T.functional.rotate(img, angle)\n if r2 == 1:\n img = T.functional.hflip(img)\n if r3 == 1:\n img = T.functional.vflip(img)\n\n # remove noise (all intensity lower than 10)\n if noiseLevel > 0:\n img = ImageChops.subtract(img, ImageChops.constant(img, noiseLevel))\n \n \n # Contrast stretching\n img = ImageOps.autocontrast(img, cutoff=1, ignore=None)\n\n # VERY VERY slow\n #img = ndimage.median_filter(img, 3)\n\n #m1 = np.percentile(img,1)\n #m99 = np.percentile(img,99)\n\n #print(f'GG: {m1} {m99}')\n #img = np.where(imgm99,m99,img)\n\n\n # transform = T.Compose([T.ToTensor(), normalize])\n # transform = T.Compose([T.RandomVerticalFlip(), T.RandomHorizontalFlip(), T.ToTensor(), normalize])\n img = T.ToTensor()(img)\n return img\n\n def _get_img_path(self, index, channel, site=1, negative=False):\n \n if site == None:\n site = (index % 2) + 1\n # otherwise use site from the input parameter\n\n if self.useBothSites:\n my_index = index // 2\n else:\n my_index = index\n\n experiment, well, plate = self.records[my_index].experiment, self.records[my_index].well, self.records[\n my_index].plate\n\n if negative==True:\n well = self.records[my_index].negative\n\n return '/'.join([self.img_dir, 'train', experiment, f'Plate{plate}', f'{well}_s{site}_w{channel}.png']) # all files were moved to train\n\n def __getitem__(self, index):\n GETBOTHSITES = 1\n\n paths = [self._get_img_path(index, ch, site=None) for ch in self.channels]\n if GETBOTHSITES == 1 and self.withoutControls==False:\n randomSite = random.randint(1, 2)\n paths2 = [self._get_img_path(index, ch, negative=True, site = randomSite) for ch in self.channels]\n\n if self.useBothSites:\n dd = 2\n else:\n dd = 1\n\n experiment = self.records[index // dd].experiment\n cellLine = torch.FloatTensor([0, 0, 0, 0])\n if 'HEPG2' in experiment:\n cellLine[0] = 1\n if 'HUVEC' in experiment:\n cellLine[1] = 1\n if 'RPE' in experiment:\n cellLine[2] = 1\n if 'U2OS' in experiment:\n cellLine[3] = 1\n \n\n normalize = T.Normalize(mean=[0.485, 0.485, 0.485, 0.485, 0.485, 0.485, ],\n std=[0.229, 0.229, 0.229, 0.229, 0.229, 0.229, ])\n\n r1 = random.randint(0, 3)\n r2 = random.randint(0, 1)\n r3 = random.randint(0, 1)\n startx=random.randint(0, 175)\n starty=random.randint(0, 175)\n size=336\n img = torch.cat([self._load_img_as_tensor(img_path, r1, r2, r3, startx=startx, starty=starty, size=size) for img_path in paths])\n img = ImagesDS._correct_overlaping_channels(img)\n img = normalize(img)\n\n if GETBOTHSITES == 1:\n orderTensor = torch.FloatTensor([[1], [-1]])\n if self.withoutControls == False:\n r1 = random.randint(0, 3)\n r2 = random.randint(0, 1)\n r3 = random.randint(0, 1)\n startx=random.randint(0, 175)\n starty=random.randint(0, 175)\n size=336\n img2 = torch.cat([self._load_img_as_tensor(img_path, r1, r2, r3, startx=startx, starty=starty, size=size) for img_path in paths2])\n img2 = ImagesDS._correct_overlaping_channels(img2)\n img2 = normalize(img2)\n\n order = random.randint(0, 1)\n returnVal = [img, img2, cellLine, orderTensor]\n if order == 1:\n orderTensor = torch.FloatTensor([[-1], [1]])\n returnVal = [img2, img, cellLine, orderTensor]\n else:\n returnVal = [img, img, cellLine, orderTensor]\n \n if self.mode == 'train' or self.mode == 'val':\n return returnVal, self.records[index // dd].sirna\n else:\n return returnVal, 0\n \n else:\n if self.mode == 'train':\n return [img, cellLine], self.records[index // dd].sirna\n else:\n return [img, cellLine], 0 # self.records[index//dd].id_code\n\n def __len__(self):\n \"\"\"\n Total number of samples in the dataset\n \"\"\"\n return self.len\n","sub_path":"ImagesDS_negative.py","file_name":"ImagesDS_negative.py","file_ext":"py","file_size_in_byte":8619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"12949056","text":"atletas = []\r\nnotas = []\r\n\r\nfor i in range(2):\r\n linha = []\r\n atleta = input(\"Diga o nome do %dº atleta: \"%(i+1))\r\n atletas.append(atleta)\r\n for j in range(5):\r\n nota = float(input(\"Diga a %dª nota que esse atleta recebeu: \" %(j+1)))\r\n linha.append(nota)\r\n notas.append(linha)\r\n\r\nfor i in range(2):\r\n for j in range(5):\r\n menor = notas[0][0]\r\n maior = notas[0][0]\r\n media = 0\r\n if notas[i][j] > maior:\r\n maior = notas[i][j]\r\n if notas[i][j] < menor:\r\n menor = notas[i][j]\r\n notas[i].sort()\r\n media = (notas[i][1] + notas[i][2] + notas[i][3])/3\r\n print(\"Resultado Final:\")\r\n print(\"Atleta:\", atletas[i])\r\n print(\"Melhor Nota:\",maior)\r\n print(\"Pior Nota: \", menor)\r\n print(\"Média: \", media)\r\n","sub_path":"matriz com notas e nome.py","file_name":"matriz com notas e nome.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"635677567","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nExercices pratiques autour des itérations.\n\nChaque exercice suivra les concepts du tdd (test driven development).\nDans chaque éxercices vous aurez accés aux réponses (résultats attendus).\nReste à coder et vérifier si les résultats réels suivent les résultats attendus.\n\nPour faire cet exercice, copiez ce fichier sur votre ordinateur.\nRendez vous dans chaque fonction commençant par test_.\nA l'intérieur vous y trouverez un énoncé, une partie pour coder, et les réponses\n\nVous y trouverez 2 indicateurs:\n# CODE HERE\n\n# STOP HERE\n\nVous pourrez résoudre chaque exercice entre ces balises.\nNe touchez à rien d'autre que le code entre ces deux balises (ou alors vous trichez :D).\n\nA chaque exercice vous pouvez éxecuter ce fichier comme ceci:\npython3 iterations.py\n\nLe script vous affichera alors si vous avez bon à chaque exercice.\n\n\"\"\"\nimport unittest\n\n\nclass Test_iterations(unittest.TestCase):\n\n def test_treat_records(self):\n \"\"\"\n Vous êtes scientifique et vous devez traiter des données pour les interpréter.\n\n Différentes variables seront déjà disponibles:\n - daily_records: une liste de dictionnaires contenant les résultats d'analyses journalières.\n Pour chaque analyse, la date est précisée ainsi\n que les résultats d'une analyse répétée 4 fois (pour plus de précision).\n Les résultats\n Exemple: [{\"day\": \"2017-10-19\", \"result\": (0, 0.2, 0.4, 0)}]\n\n Vous devez donc:\n - Filtrer les analyses si aucun résultat n'est enregistré (None) ou\n si le nombre de répétitions n'est pas 4.\n - Pour chaque analyse filtrée (chaque jour), calculer la moyenne des 4 résultats.\n Arrondissez les résultats à 2 chiffres après la virgule.\n Enregistrer les résultats (gardez le même format!!!) dans une variable daily_results.\n - Calculer la moyenne des résultats moyens journaliers (daily_results)\n et stocker le résultat dans une variable mean_result.\n\n Différents scénarios vont être testé dans cet exercice !\n Veiller donc à respecter l'indentation.\n \"\"\"\n\n def analyze(daily_records):\n\n # CODE HERE\n def mean(values):\n return sum(values) / len(values)\n\n def record_is_valid(record):\n return (record[\"result\"] is not None) and (len(record[\"result\"]) == 4)\n\n def format_record(record):\n return {\"day\": record[\"day\"], \"result\": round(mean(record[\"result\"]), 4)}\n\n def build_daily_results(records):\n return [format_record(record) for record in daily_records if record_is_valid(record)]\n\n daily_results = []\n total_results = 0\n\n for record in daily_records:\n if (record[\"result\"] is not None) and (len(record[\"result\"]) == 4):\n result = sum(record[\"result\"]) / len(record[\"result\"])\n total_results += result\n daily_results.append({\"day\": record[\"day\"], \"result\": round(result, 4)})\n\n mean_result = total_results / len(daily_results)\n # STOP HERE\n\n print(\"Mean result: \", mean_result)\n return daily_results, mean_result\n\n self.assertEqual(\n analyze([\n {\"day\": \"2017-10-19\", \"result\": (0, 0.2, 0.4, 0)},\n {\"day\": \"2017-10-18\", \"result\": (0.8, 0.2, 0.4, 0.4)},\n {\"day\": \"2017-10-22\", \"result\": None},\n {\"day\": \"2017-10-17\", \"result\": (0, 0.2, 0.2, 0.1)},\n {\"day\": \"2017-10-20\", \"result\": (0, 0.4, 0.4, 0.4)},\n {\"day\": \"2017-10-21\", \"result\": (0, 0.1, 0.4, 0.2)}\n ]),\n ([\n {\"day\": \"2017-10-19\", \"result\": 0.15},\n {\"day\": \"2017-10-18\", \"result\": 0.45},\n {\"day\": \"2017-10-17\", \"result\": 0.125},\n {\"day\": \"2017-10-20\", \"result\": 0.3},\n {\"day\": \"2017-10-21\", \"result\": 0.175}],\n 0.24)\n )\n self.assertEqual(\n analyze([\n {\"day\": \"2017-11-19\", \"result\": (0, 0.2, 0.4, 0)},\n {\"day\": \"2017-11-18\", \"result\": (0.8, 0.2, 0.4, 0.4)},\n {\"day\": \"2017-11-17\", \"result\": (0.8, 0.2, 0.4, 0.4, 1.8)},\n {\"day\": \"2017-11-16\", \"result\": (0.8, 0.2)},\n {\"day\": \"2017-11-15\", \"result\": None},\n ]),\n ([\n {\"day\": \"2017-11-19\", \"result\": 0.15},\n {\"day\": \"2017-11-18\", \"result\": 0.45}],\n 0.3)\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"beginners_part_01/answers/iterations_test.py","file_name":"iterations_test.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"26867910","text":"#!/usr/bin/python\n#\n# Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)\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\"\"\"\nPartitions should be loaded with data in the last step only. Thus, generator\nobjects are necessary. Inside 'task' functions we will call their 'generate'\nmethod in order to retrieve the partition. These partitions can previously be\nloaded on master and sent to workers, or read from files on worker nodes.\n\"\"\"\nimport pickle\nimport sys\n\n\nclass IPartitionGenerator(object):\n \"\"\"\n Everyone implements this.\n \"\"\"\n def retrieve_data(self):\n raise NotImplementedError\n\n\nclass BasicDataLoader(IPartitionGenerator):\n\n def __init__(self, data):\n super(BasicDataLoader, self).__init__()\n self.data = data\n\n def retrieve_data(self):\n ret = list()\n if isinstance(self.data, list):\n ret.extend(self.data)\n else:\n ret.append(self.data)\n return ret\n\n\nclass IteratorLoader(IPartitionGenerator):\n\n def __init__(self, iterable, start, end):\n super(IteratorLoader, self).__init__()\n self.iterable = iterable\n self.start = start\n self.end = end\n\n def retrieve_data(self):\n \"\"\"\n Divide and retrieve the next partition.\n :return:\n \"\"\"\n\n # If it's a dict\n if isinstance(self.iterable, dict):\n sorted_keys = sorted(self.iterable.keys())\n for key in sorted_keys[self.start:self.end]:\n yield key, self.iterable[key]\n elif isinstance(self.iterable, list):\n for item in iter(self.iterable[self.start:self.end]):\n yield item\n else:\n index = 0\n for item in iter(self.iterable):\n index += 1\n if index > self.end:\n break\n elif index > self.start:\n yield item\n\n\nclass WorkerFileLoader(IPartitionGenerator):\n\n def __init__(self, file_paths, single_file=False, start=0, chunk_size=None):\n super(WorkerFileLoader, self).__init__()\n\n self.file_paths = file_paths\n self.single_file = single_file\n self.start = start\n self.chunk_size = chunk_size\n\n if self.single_file and not chunk_size:\n raise Exception(\"Missing chunk_size argument...\")\n\n def retrieve_data(self):\n\n if self.single_file:\n fp = open(self.file_paths[0])\n fp.seek(self.start)\n temp = fp.read(self.chunk_size)\n fp.close()\n return [temp]\n\n ret = list()\n for file_path in self.file_paths:\n content = open(file_path).read()\n ret.append((file_path, content))\n\n return ret\n\n\nclass PickleLoader(IPartitionGenerator):\n\n def __init__(self, pickle_path):\n super(PickleLoader, self).__init__()\n self.pickle_path = pickle_path\n\n def retrieve_data(self):\n ret = pickle.load(open(self.pickle_path, \"rb\"))\n return ret\n\n\ndef read_in_chunks(file_name, chunk_size=1024, strip=True):\n \"\"\"Lazy function (generator) to read a file piece by piece.\n Default chunk size: 1k.\"\"\"\n partition = list()\n f = open(file_name)\n collected = 0\n for line in f:\n _line = line.rstrip(\"\\n\") if strip else line\n partition.append(_line)\n collected += sys.getsizeof(_line)\n if collected > chunk_size:\n yield partition\n partition = []\n collected = 0\n\n if partition:\n yield partition\n\n\ndef read_lines(file_name, num_of_lines=1024, strip=True):\n \"\"\"\n Lazy function (generator) to read a file line by line.\n :param file_name:\n :param num_of_lines: total number of lines in each partition\n :param strip: if line separators should be stripped from lines\n \"\"\"\n partition = list()\n f = open(file_name)\n collected = 0\n for line in f:\n _line = line.rstrip(\"\\n\") if strip else line\n partition.append(_line)\n collected += 1\n if collected > num_of_lines:\n yield partition\n partition = []\n collected = 0\n\n if partition:\n yield partition\n","sub_path":"compss/programming_model/bindings/python/src/pycompss/dds/partition_generators.py","file_name":"partition_generators.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"263729600","text":"from random import choice,randint\nimport string\nstrs = string.ascii_letters + string.digits\nsum = ''\nfor i in range(5):\n num = choice(strs)\n sum += num\nprint(sum)\n\na = choice([randint(1,100) for i in range(10)])\nprint(a)\n\nstr = '你好'\nprint(str.encode('utf8'))\nb = str.encode('utf8')\nprint(b.decode('utf8'))","sub_path":"python/linux/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"6963712","text":"\"\"\"Class definitions for trainable aligners\"\"\"\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Optional\n\nfrom .base import BaseAligner\n\nif TYPE_CHECKING:\n from logging import Logger\n\n from ..aligner.pretrained import PretrainedAligner\n from ..config import AlignConfig, TrainingConfig\n from ..corpus import Corpus\n from ..dictionary import Dictionary\n\n__all__ = [\"TrainableAligner\"]\n\n\nclass TrainableAligner(BaseAligner):\n \"\"\"\n Aligner that aligns and trains acoustics models on a large dataset\n\n Parameters\n ----------\n corpus : :class:`~montreal_forced_aligner.corpus.base.Corpus`\n Corpus object for the dataset\n dictionary : :class:`~montreal_forced_aligner.dictionary.Dictionary`\n Dictionary object for the pronunciation dictionary\n training_config : :class:`~montreal_forced_aligner.config.TrainingConfig`\n Configuration to train a model\n align_config : :class:`~montreal_forced_aligner.config.align_config.AlignConfig`\n Configuration for alignment\n temp_directory : str, optional\n Specifies the temporary directory root to save files need for Kaldi.\n If not specified, it will be set to ``~/Documents/MFA``\n debug: bool\n Flag for debug mode, default is False\n verbose: bool\n Flag for verbose mode, default is False\n logger: :class:`~logging.Logger`\n Logger to use\n pretrained_aligner: :class:`~montreal_forced_aligner.aligner.pretrained.PretrainedAligner`, optional\n Pretrained aligner to use as input to training\n \"\"\"\n\n def __init__(\n self,\n corpus: Corpus,\n dictionary: Dictionary,\n training_config: TrainingConfig,\n align_config: AlignConfig,\n temp_directory: Optional[str] = None,\n debug: bool = False,\n verbose: bool = False,\n logger: Optional[Logger] = None,\n pretrained_aligner: Optional[PretrainedAligner] = None,\n ):\n self.training_config = training_config\n self.pretrained_aligner = pretrained_aligner\n if self.pretrained_aligner is not None:\n acoustic_model = pretrained_aligner.acoustic_model\n else:\n acoustic_model = None\n super(TrainableAligner, self).__init__(\n corpus,\n dictionary,\n align_config,\n temp_directory,\n debug,\n verbose,\n logger,\n acoustic_model=acoustic_model,\n )\n for trainer in self.training_config.training_configs:\n trainer.logger = self.logger\n\n def save(self, path: str, root_directory: Optional[str] = None) -> None:\n \"\"\"\n Output an acoustic model and dictionary to the specified path\n\n Parameters\n ----------\n path : str\n Path to save acoustic model and dictionary\n root_directory : str or None\n Path for root directory of temporary files\n \"\"\"\n self.training_config.values()[-1].save(path, root_directory)\n self.logger.info(\"Saved model to {}\".format(path))\n\n @property\n def meta(self) -> dict:\n \"\"\"Acoustic model parameters\"\"\"\n from ..utils import get_mfa_version\n\n data = {\n \"phones\": sorted(self.dictionary.nonsil_phones),\n \"version\": get_mfa_version(),\n \"architecture\": self.training_config.values()[-1].architecture,\n \"phone_type\": self.training_config.values()[-1].phone_type,\n \"features\": self.align_config.feature_config.params(),\n }\n return data\n\n def train(self, generate_final_alignments: bool = True) -> None:\n \"\"\"\n Run through the training configurations to produce a final acoustic model\n\n Parameters\n ----------\n generate_final_alignments: bool\n Flag for whether final alignments should be generated at the end of training, defaults to True\n \"\"\"\n previous = self.pretrained_aligner\n for identifier, trainer in self.training_config.items():\n trainer.debug = self.debug\n trainer.logger = self.logger\n if previous is not None:\n previous.align(trainer.subset)\n trainer.init_training(\n identifier, self.temp_directory, self.corpus, self.dictionary, previous\n )\n trainer.train()\n previous = trainer\n if generate_final_alignments:\n previous.align(None)\n\n @property\n def align_directory(self) -> str:\n \"\"\"Align directory\"\"\"\n return self.training_config.values()[-1].align_directory\n","sub_path":"montreal_forced_aligner/aligner/trainable.py","file_name":"trainable.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"259620109","text":"from django.shortcuts import render, redirect\nfrom .forms import DocumentForm\n\n# Create your views here.\ndef model_form_upload(request):\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('index')\n else:\n form = DocumentForm()\n return render(request, 'upload/model_form_upload.html', {\n 'form': form\n })\n\ndef index(request):\n \"\"\"\n \"\"\"\n return render(\n request,\n 'index.html',\n)","sub_path":"upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"552559250","text":"'''\nPaint Fill:\n Given a 2D array, a point and a color, fill the surrounding area with the same color.\n'''\n\ndef paint_fill(arr, target, loc, init=None):\n dims = arr.shape\n if loc[0] >= dims[0] or loc[1] >= dims[1] or loc[0] < 0 or loc[1] < 0:\n return # end recursion (1) if the loc is invalid\n if init is None:\n init = arr[loc[0], loc[1]]\n if arr[loc[0], loc[1]] == target or arr[loc[0], loc[1]] != init:\n return # end recursion (2) if cell color is already the target color or (3) if cell color is not initial color\n arr[loc[0], loc[1]] = target\n paint_fill(arr, target, (loc[0] - 1, loc[1]), init)\n paint_fill(arr, target, (loc[0] + 1, loc[1]), init)\n paint_fill(arr, target, (loc[0], loc[1] - 1), init)\n paint_fill(arr, target, (loc[0], loc[1] + 1), init)\n return","sub_path":"Cracking the Coding Interview/Recursion and Dynamic Programming/PaintFill.py","file_name":"PaintFill.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"255120458","text":"Tappo = 0\nNumPrecedente = -1\nN = int(input())\nVerificate = False\n\nwhile N != Tappo: \n if NumPrecedente == -1:\n NumPrecedente = N\n N = int(input()) \n else:\n if (N%2 == 0 and NumPrecedente%2 == 0) or ((N+NumPrecedente) % N == 0 or (N+NumPrecedente) % NumPrecedente == 0): \n Verificate = True\n NumPrecedente = N\n N = int(input()) \nif Verificate:\n print('SI', end='')\nelse:\n print('NO', end='')\n \n \n \n \n","sub_path":"DomJudge/Scripts/n17.py","file_name":"n17.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"261783784","text":"# -*- coding: utf-8 -*- \n \nimport os \n\ndef file_name(file_dir):\n\tfor root, dirs, files in os.walk(file_dir):\n\t\tprint('-'*100)\n\t\tprint(root)\n\t\tprint(dirs)\n\t\tfor name in files:\n\t\t\tprint('- '+name)\n\nif __name__ == '__main__':\n\tpath = ['./complex-compressive-sensing','./paper','./codes','./my-codes']\n\tfor p in path:\t\n\t\tfile_name(p)\n","sub_path":"fetch_file_name.py","file_name":"fetch_file_name.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"421589687","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\nPACKAGE = 'iLog'\nVERSION = '0.1'\n\n\nsetup(\n name=PACKAGE, version=VERSION,\n description=\"A plugin for Log Graph\",\n packages=find_packages(exclude=['ez_setup', '*.tests*']),\n package_data={\n 'iLog': ['templates/*.html', \n 'htdocs/css/*.css',\n 'htdocs/js/*.js',\n 'htdocs/images/*',\n 'htdocs/log/*']\n },\n entry_points = {\n 'trac.plugins': [\n 'iLog.web_ui = iLog.web_ui',\n ]\n }\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"310443687","text":"\"\"\"Functions for working with MPI processor distributions\"\"\"\nfrom __future__ import division, print_function, absolute_import, unicode_literals\n#***************************************************************************************************\n# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights\n# in this software.\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\n# in compliance with the License. You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.\n#***************************************************************************************************\n\nimport numpy as _np\nimport warnings as _warnings\nimport itertools as _itertools\nfrom . import slicetools as _slct\nfrom . import compattools as _compat\nfrom .matrixtools import _fas, _findx, _findx_shape\n\n\ndef distribute_indices(indices, comm, allow_split_comm=True):\n \"\"\"\n Partition an array of indices (any type) evenly among `comm`'s processors.\n\n Parameters\n ----------\n indices : list\n An array of items (any type) which are to be partitioned.\n\n comm : mpi4py.MPI.Comm\n The communicator which specifies the number of processors and\n which may be split into returned sub-communicators.\n\n allow_split_comm : bool\n If True, when there are more processors than indices,\n multiple processors will be given the *same* set of local\n indices and `comm` will be split into sub-communicators,\n one for each group of processors that are given the same\n indices. If False, then \"extra\" processors are simply given\n nothing to do, i.e. empty lists of local indices.\n\n Returns\n -------\n loc_indices : list\n A list containing the elements of `indices` belonging to the current\n processor.\n\n owners : dict\n A dictionary mapping the elements of `indices` to integer ranks, such\n that `owners[el]` gives the rank of the processor responsible for\n communicating that element's results to the other processors. Note that\n in the case when `allow_split_comm=True` and multiple procesors have\n computed the results for a given element, only a single (the first)\n processor rank \"owns\" the element, and is thus responsible for sharing\n the results. This notion of ownership is useful when gathering the\n results.\n\n loc_comm : mpi4py.MPI.Comm or None\n The local communicator for the group of processors which have been\n given the same `loc_indices` to compute, obtained by splitting `comm`.\n If `loc_indices` is unique to the current processor, or if\n `allow_split_comm` is False, None is returned.\n \"\"\"\n if comm is None:\n nprocs, rank = 1, 0\n else:\n nprocs = comm.Get_size()\n rank = comm.Get_rank()\n\n loc_indices, owners = distribute_indices_base(indices, nprocs, rank,\n allow_split_comm)\n\n #Split comm into sub-comms when there are more procs than\n # indices, resulting in all procs getting only a\n # single index and multiple procs getting the *same*\n # (single) index.\n #if nprocs > 1 and len(indices)==1 and (comm is not None) and allow_split_comm:\n # loc_comm = comm #split is unnecessary\n #el\n if nprocs > len(indices) and (comm is not None) and allow_split_comm:\n color = loc_indices[0] if isinstance(loc_indices[0], int) \\\n else (int(hash(loc_indices[0])) >> 32) # mpi4py only allows 32-bit ints\n loc_comm = comm.Split(color=color, key=rank)\n else:\n loc_comm = None\n\n return loc_indices, owners, loc_comm\n\n\ndef distribute_indices_base(indices, nprocs, rank, allow_split_comm=True):\n \"\"\"\n Partition an array of \"indices\" evenly among a given number of \"processors\"\n\n This function is similar to :func:`distribute_indices`, but allows for more\n a more generalized notion of what a \"processor\" is, since the number of\n processors and rank are given independently and do not have to be\n associated with an MPI comm. Note also that `indices` can be an arbitrary\n list of items, making this function very general.\n\n Parameters\n ----------\n indices : list\n An array of items (any type) which are to be partitioned.\n\n nprocs : int\n The number of \"processors\" to distribute the elements of\n `indices` among.\n\n rank : int\n The rank of the current \"processor\" (must be an integer\n between 0 and `nprocs-1`). Note that this value is not\n obtained from any MPI communicator.\n\n allow_split_comm : bool\n If True, when there are more processors than indices,\n multiple processors will be given the *same* set of local\n indices. If False, then extra processors are simply given\n nothing to do, i.e. empty lists of local indices.\n\n Returns\n -------\n loc_indices : list\n A list containing the elements of `indices` belonging to the current\n processor (i.e. the one specified by `rank`).\n\n owners : dict\n A dictionary mapping the elements of `indices` to integer ranks, such\n that `owners[el]` gives the rank of the processor responsible for\n communicating that element's results to the other processors. Note that\n in the case when `allow_split_comm=True` and multiple procesors have\n computed the results for a given element, only a single (the first)\n processor rank \"owns\" the element, and is thus responsible for sharing\n the results. This notion of ownership is useful when gathering the\n results.\n \"\"\"\n nIndices = len(indices)\n if nIndices == 0: # special case when == 0\n return [], {}\n\n if nprocs >= nIndices:\n if allow_split_comm:\n nloc_std = nprocs // nIndices # this many processors per index, w/out any \"extra\"\n extra = nprocs - nloc_std * nIndices # extra procs\n # indices 0 to extra-1 get (nloc_std+1) processors each\n # incides extra to nIndices-1 get nloc_std processors each\n if rank < extra * (nloc_std + 1):\n loc_indices = [indices[rank // (nloc_std + 1)]]\n else:\n loc_indices = [indices[\n extra + (rank - extra * (nloc_std + 1)) // nloc_std]]\n\n # owners dict gives rank of first (chief) processor for each index\n # (the \"owner\" of a given index is responsible for communicating\n # results for that index to the other processors)\n owners = {indices[i]: i * (nloc_std + 1) for i in range(extra)}\n owners.update({indices[i]: extra * (nloc_std + 1) + (i - extra) * nloc_std\n for i in range(extra, nIndices)})\n else:\n #Not allowed to assign multiple procs the same local index\n # (presumably b/c there is no way to sub-divide the work\n # performed for a single index among multiple procs)\n if rank < nIndices:\n loc_indices = [indices[rank]]\n else:\n loc_indices = [] # extra procs do nothing\n owners = {indices[i]: i for i in range(nIndices)}\n\n else:\n nloc_std = nIndices // nprocs\n extra = nIndices - nloc_std * nprocs # extra indices\n # so assign (nloc_std+1) indices to first extra procs\n if rank < extra:\n nloc = nloc_std + 1\n nstart = rank * (nloc_std + 1)\n loc_indices = [indices[rank // (nloc_std + 1)]]\n else:\n nloc = nloc_std\n nstart = extra * (nloc_std + 1) + (rank - extra) * nloc_std\n loc_indices = [indices[i] for i in range(nstart, nstart + nloc)]\n\n owners = {} # which rank \"owns\" each index\n for r in range(extra):\n nstart = r * (nloc_std + 1)\n for i in range(nstart, nstart + (nloc_std + 1)):\n owners[indices[i]] = r\n for r in range(extra, nprocs):\n nstart = extra * (nloc_std + 1) + (r - extra) * nloc_std\n for i in range(nstart, nstart + nloc_std):\n owners[indices[i]] = r\n\n return loc_indices, owners\n\n\ndef slice_up_slice(slc, num_slices):\n \"\"\"\n Divides up `slc` into `num_slices` slices.\n\n Parameters\n ----------\n slc : slice\n The slice to be divided.\n\n num_slices : int\n The number of slices to divide the range into.\n\n Returns\n -------\n list of slices\n \"\"\"\n assert(slc.step is None) # currently, no support for step != None slices\n if slc.start is None or slc.stop is None:\n return slice_up_range(0, num_slices)\n else:\n return slice_up_range(slc.stop - slc.start, num_slices, slc.start)\n\n\ndef slice_up_range(n, num_slices, start=0):\n \"\"\"\n Divides up `range(start,start+n)` into `num_slices` slices.\n\n Parameters\n ----------\n n : int\n The number of (consecutive) indices in the range to be divided.\n\n num_slices : int\n The number of slices to divide the range into.\n\n start : int, optional\n The starting entry of the range, so that the range to be\n divided is `range(start,start+n)`.\n\n Returns\n -------\n list of slices\n \"\"\"\n base = n // num_slices # base slice size\n m1 = n - base * num_slices # num base+1 size slices\n m2 = num_slices - m1 # num base size slices\n assert(((base + 1) * m1 + base * m2) == n)\n\n off = start\n ret = [slice(off + (base + 1) * i, off + (base + 1) * (i + 1)) for i in range(m1)]\n off += (base + 1) * m1\n ret += [slice(off + base * i, off + base * (i + 1)) for i in range(m2)]\n assert(len(ret) == num_slices)\n return ret\n\n\ndef distribute_slice(s, comm, allow_split_comm=True):\n \"\"\"\n Partition a continuous slice evenly among `comm`'s processors.\n\n This function is similar to :func:`distribute_indices`, but\n is specific to the case when the indices being distributed\n are a consecutive set of integers (specified by a slice).\n\n Parameters\n ----------\n s : slice\n The slice to be partitioned.\n\n comm : mpi4py.MPI.Comm\n The communicator which specifies the number of processors and\n which may be split into returned sub-communicators.\n\n allow_split_comm : bool\n If True, when there are more processors than slice indices,\n multiple processors will be given the *same* local slice\n and `comm` will be split into sub-communicators, one for each\n group of processors that are given the same local slice.\n If False, then \"extra\" processors are simply given\n nothing to do, i.e. an empty local slice.\n\n Returns\n -------\n slices : list of slices\n The list of *unique* slices assigned to different processors. It's\n possible that a single slice (i.e. element of `slices`) is assigned\n to multiple processors (when there are more processors than indices\n in `s`.\n\n loc_slice : slice\n A slice specifying the indices belonging to the current processor.\n\n owners : dict\n A dictionary giving the owning rank of each slice. Values are integer\n ranks and keys are integers into `slices`, specifying which slice.\n\n loc_comm : mpi4py.MPI.Comm or None\n The local communicator for the group of processors which have been\n given the same `loc_slice` to compute, obtained by splitting `comm`.\n If `loc_slice` is unique to the current processor, or if\n `allow_split_comm` is False, None is returned.\n \"\"\"\n if comm is None:\n nprocs, rank = 1, 0\n else:\n nprocs = comm.Get_size()\n rank = comm.Get_rank()\n\n slices = slice_up_slice(s, min(nprocs, _slct.length(s)))\n assert(len(slices) <= nprocs)\n loc_iSlices, slcOwners = \\\n distribute_indices_base(list(range(len(slices))), nprocs, rank,\n allow_split_comm)\n assert(len(loc_iSlices) <= 1) # should not assign more than one slice to\n # each proc by design (there are only nprocs slices)\n\n if len(loc_iSlices) == 1:\n loc_slice = slices[loc_iSlices[0]]\n\n #Split comm into sub-comms when there are more procs than\n # indices, resulting in all procs getting only a\n # single index and multiple procs getting the *same*\n # (single) index.\n if nprocs > _slct.length(s) and (comm is not None) and allow_split_comm:\n loc_comm = comm.Split(color=loc_iSlices[0], key=rank)\n else:\n loc_comm = None\n\n else:\n loc_slice = slice(None)\n loc_comm = None\n\n return slices, loc_slice, slcOwners, loc_comm\n\n\ndef gather_slices(slices, slice_owners, arToFill,\n arToFillInds, axes, comm, max_buffer_size=None):\n \"\"\"\n Gathers data within a numpy array, `arToFill`, according to given slices.\n\n Upon entry it is assumed that the different processors within `comm` have\n computed different parts of `arToFill`, namely different slices of the\n `axis`-th axis. At exit, data has been gathered such that all processors\n have the results for the entire `arToFill` (or at least for all the slices\n given).\n\n Parameters\n ----------\n slices : list\n A list of all the slices (computed by *any* of the processors, not\n just the current one). Each element of `slices` may be either a\n single slice or a tuple of slices (when gathering across multiple\n dimensions).\n\n slice_owners : dict\n A dictionary mapping the index of a slice (or tuple of slices)\n within `slices` to an integer rank of the processor responsible\n for communicating that slice's data to the rest of the processors.\n\n arToFill : numpy.ndarray\n The array which contains partial data upon entry and the gathered\n data upon exit.\n\n arToFillInds : list\n A list of slice or index-arrays specifying the (fixed) sub-array of\n `arToFill` that should be gathered into. The elements of\n `arToFillInds` are taken to be indices for the leading dimension\n first, and any unspecified dimensions or `None` elements are\n assumed to be unrestricted (as if `slice(None,None)`). Note that\n the combination of `arToFill` and `arToFillInds` is essentally like\n passing `arToFill[arToFillInds]` to this function, except it will\n work with index arrays as well as slices.\n\n axes : int or tuple of ints\n The axis or axes of `arToFill` on which the slices apply (which axis\n do the slices in `slices` refer to?). Note that `len(axes)` must\n be equal to the number of slices (i.e. the tuple length) of each\n element of `slices`.\n\n comm : mpi4py.MPI.Comm or None\n The communicator specifying the processors involved and used\n to perform the gather operation.\n\n max_buffer_size : int or None\n The maximum buffer size in bytes that is allowed to be used\n for gathering data. If None, there is no limit.\n\n Returns\n -------\n None\n \"\"\"\n if comm is None: return # no gathering needed!\n\n #Perform broadcasts for each slice in order\n my_rank = comm.Get_rank()\n arIndx = [slice(None, None)] * arToFill.ndim\n arIndx[0:len(arToFillInds)] = arToFillInds\n\n axes = (axes,) if _compat.isint(axes) else axes\n\n max_indices = [None] * len(axes)\n if max_buffer_size is not None: # no maximum of buffer size\n chunkBytes = arToFill.nbytes # start with the entire array as the \"chunk\"\n for iaxis, axis in enumerate(axes):\n # Consider restricting the chunk size along the iaxis-th axis.\n # If we can achieve the desired max_buffer_size by restricting\n # just along this axis, great. Otherwise, restrict to at most\n # 1 index along this axis and keep going.\n bytes_per_index = chunkBytes / arToFill.shape[axis]\n max_inds = int(max_buffer_size / bytes_per_index)\n if max_inds == 0:\n max_indices[iaxis] = 1\n chunkBytes /= arToFill.shape[axis]\n else:\n max_indices[iaxis] = max_inds\n break\n else:\n _warnings.warn(\"gather_slices: Could not achieve max_buffer_size\")\n\n for iSlice, slcOrSlcTup in enumerate(slices):\n owner = slice_owners[iSlice] # owner's rank\n slcTup = (slcOrSlcTup,) if isinstance(slcOrSlcTup, slice) else slcOrSlcTup\n assert(len(slcTup) == len(axes))\n\n #Get the a list of the (sub-)slices along each axis, whose product\n # (along the specified axes) gives the entire block given by slcTup\n axisSlices = []\n for iaxis, axis in enumerate(axes):\n slc = slcTup[iaxis]\n if max_indices[iaxis] is None or max_indices[iaxis] >= _slct.length(slc):\n axisSlices.append([slc]) # arIndx[axis] = slc\n else:\n axisSlices.append(_slct.divide(slc, max_indices[iaxis]))\n\n for axSlcs in _itertools.product(*axisSlices):\n #create arIndx from per-axis (sub-)slices and broadcast\n for iaxis, axis in enumerate(axes):\n arIndx[axis] = axSlcs[iaxis]\n\n #broadcast arIndx slice\n buf = _findx(arToFill, arIndx, True) if (my_rank == owner) \\\n else _np.empty(_findx_shape(arToFill, arIndx), arToFill.dtype)\n comm.Bcast(buf, root=owner)\n if my_rank != owner: _fas(arToFill, arIndx, buf)\n buf = None # free buffer mem asap\n\n\ndef gather_slices_by_owner(slicesIOwn, arToFill, arToFillInds,\n axes, comm, max_buffer_size=None):\n \"\"\"\n Gathers data within a numpy array, `arToFill`, according to given slices.\n\n Upon entry it is assumed that the different processors within `comm` have\n computed different parts of `arToFill`, namely different slices of the\n axes indexed by `axes`. At exit, data has been gathered such that all processors\n have the results for the entire `arToFill` (or at least for all the slices\n given).\n\n Parameters\n ----------\n slicesIOwn : list\n A list of all the slices computed by the *current* processor.\n Each element of `slices` may be either a single slice or a\n tuple of slices (when gathering across multiple dimensions).\n\n arToFill : numpy.ndarray\n The array which contains partial data upon entry and the gathered\n data upon exit.\n\n arToFillInds : list\n A list of slice or index-arrays specifying the (fixed) sub-array of\n `arToFill` that should be gathered into. The elements of\n `arToFillInds` are taken to be indices for the leading dimension\n first, and any unspecified dimensions or `None` elements are\n assumed to be unrestricted (as if `slice(None,None)`). Note that\n the combination of `arToFill` and `arToFillInds` is essentally like\n passing `arToFill[arToFillInds]` to this function, except it will\n work with index arrays as well as slices.\n\n axes : int or tuple of ints\n The axis or axes of `arToFill` on which the slices apply (which axis\n do the slices in `slices` refer to?). Note that `len(axes)` must\n be equal to the number of slices (i.e. the tuple length) of each\n element of `slices`.\n\n comm : mpi4py.MPI.Comm or None\n The communicator specifying the processors involved and used\n to perform the gather operation.\n\n max_buffer_size : int or None\n The maximum buffer size in bytes that is allowed to be used\n for gathering data. If None, there is no limit.\n\n Returns\n -------\n None\n \"\"\"\n\n #Note: same beginning as gather_slices (TODO: consolidate?)\n if comm is None: return # no gathering needed!\n\n #Perform broadcasts for each slice in order\n my_rank = comm.Get_rank()\n arIndx = [slice(None, None)] * arToFill.ndim\n arIndx[0:len(arToFillInds)] = arToFillInds\n\n axes = (axes,) if _compat.isint(axes) else axes\n\n max_indices = [None] * len(axes)\n if max_buffer_size is not None: # no maximum of buffer size\n chunkBytes = arToFill.nbytes # start with the entire array as the \"chunk\"\n for iaxis, axis in enumerate(axes):\n # Consider restricting the chunk size along the iaxis-th axis.\n # If we can achieve the desired max_buffer_size by restricting\n # just along this axis, great. Otherwise, restrict to at most\n # 1 index along this axis and keep going.\n bytes_per_index = chunkBytes / arToFill.shape[axis]\n max_inds = int(max_buffer_size / bytes_per_index)\n if max_inds == 0:\n max_indices[iaxis] = 1\n chunkBytes /= arToFill.shape[axis]\n else:\n max_indices[iaxis] = max_inds\n break\n else:\n _warnings.warn(\"gather_slices_by_owner: Could not achieve max_buffer_size\")\n # -- end part that is the same as gather_slices\n\n #Get a list of the slices to broadcast, indexed by the rank of the owner proc\n slices_by_owner = comm.allgather(slicesIOwn)\n for owner, slices in enumerate(slices_by_owner):\n for slcOrSlcTup in slices:\n slcTup = (slcOrSlcTup,) if isinstance(slcOrSlcTup, slice) else slcOrSlcTup\n assert(len(slcTup) == len(axes))\n\n #Get the a list of the (sub-)slices along each axis, whose product\n # (along the specified axes) gives the entire block given by slcTup\n axisSlices = []\n for iaxis, axis in enumerate(axes):\n slc = slcTup[iaxis]\n if max_indices[iaxis] is None or max_indices[iaxis] >= _slct.length(slc):\n axisSlices.append([slc]) # arIndx[axis] = slc\n else:\n axisSlices.append(_slct.divide(slc, max_indices[iaxis]))\n\n for axSlcs in _itertools.product(*axisSlices):\n #create arIndx from per-axis (sub-)slices and broadcast\n for iaxis, axis in enumerate(axes):\n arIndx[axis] = axSlcs[iaxis]\n\n #broadcast arIndx slice\n buf = _findx(arToFill, arIndx, True) if (my_rank == owner) \\\n else _np.empty(_findx_shape(arToFill, arIndx), arToFill.dtype)\n comm.Bcast(buf, root=owner)\n if my_rank != owner: _fas(arToFill, arIndx, buf)\n buf = None # free buffer mem asap\n\n\ndef gather_indices(indices, index_owners, arToFill, arToFillInds,\n axes, comm, max_buffer_size=None):\n \"\"\"\n Gathers data within a numpy array, `arToFill`, according to given indices.\n\n Upon entry it is assumed that the different processors within `comm` have\n computed different parts of `arToFill`, namely different slices or\n index-arrays of the `axis`-th axis. At exit, data has been gathered such\n that all processors have the results for the entire `arToFill` (or at least\n for all the indices given).\n\n Parameters\n ----------\n indices : list\n A list of all the integer-arrays or slices (computed by *any* of\n the processors, not just the current one). Each element of `indices`\n may be either a single slice/index-array or a tuple of such\n elements (when gathering across multiple dimensions).\n\n index_owners : dict\n A dictionary mapping the index of an element within `slices` to an\n integer rank of the processor responsible for communicating that\n slice/index-array's data to the rest of the processors.\n\n arToFill : numpy.ndarray\n The array which contains partial data upon entry and the gathered\n data upon exit.\n\n arToFillInds : list\n A list of slice or index-arrays specifying the (fixed) sub-array of\n `arToFill` that should be gathered into. The elements of\n `arToFillInds` are taken to be indices for the leading dimension\n first, and any unspecified dimensions or `None` elements are\n assumed to be unrestricted (as if `slice(None,None)`). Note that\n the combination of `arToFill` and `arToFillInds` is essentally like\n passing `arToFill[arToFillInds]` to this function, except it will\n work with index arrays as well as slices.\n\n axes : int or tuple of ints\n The axis or axes of `arToFill` on which the slices apply (which axis\n do the elements of `indices` refer to?). Note that `len(axes)` must\n be equal to the number of sub-indices (i.e. the tuple length) of each\n element of `indices`.\n\n comm : mpi4py.MPI.Comm or None\n The communicator specifying the processors involved and used\n to perform the gather operation.\n\n max_buffer_size : int or None\n The maximum buffer size in bytes that is allowed to be used\n for gathering data. If None, there is no limit.\n\n Returns\n -------\n None\n \"\"\"\n if comm is None: return # no gathering needed!\n\n #Perform broadcasts for each slice in order\n my_rank = comm.Get_rank()\n arIndx = [slice(None, None)] * arToFill.ndim\n arIndx[0:len(arToFillInds)] = arToFillInds\n\n axes = (axes,) if _compat.isint(axes) else axes\n\n max_indices = [None] * len(axes)\n if max_buffer_size is not None: # no maximum of buffer size\n chunkBytes = arToFill.nbytes # start with the entire array as the \"chunk\"\n for iaxis, axis in enumerate(axes):\n # Consider restricting the chunk size along the iaxis-th axis.\n # If we can achieve the desired max_buffer_size by restricting\n # just along this axis, great. Otherwise, restrict to at most\n # 1 index along this axis and keep going.\n bytes_per_index = chunkBytes / arToFill.shape[axis]\n max_inds = int(max_buffer_size / bytes_per_index)\n if max_inds == 0:\n max_indices[iaxis] = 1\n chunkBytes /= arToFill.shape[axis]\n else:\n max_indices[iaxis] = max_inds\n break\n else:\n _warnings.warn(\"gather_indices: Could not achieve max_buffer_size\")\n\n for iIndex, indOrIndTup in enumerate(indices):\n owner = index_owners[iIndex] # owner's rank\n indTup = (indOrIndTup,) if not isinstance(indOrIndTup, tuple) else indOrIndTup\n assert(len(indTup) == len(axes))\n\n def to_slice_list(indexArrayOrSlice):\n \"\"\"Breaks a slice or index array into a list of slices\"\"\"\n if isinstance(indexArrayOrSlice, slice):\n return [indexArrayOrSlice] # easy!\n\n lst = indexArrayOrSlice\n if len(lst) == 0: return [slice(0, 0)]\n\n slc_lst = []\n i = 0; N = len(lst)\n while i < N:\n start = lst[i]\n step = lst[i + 1] - lst[i] if i + 1 < N else None\n while i + 1 < N and lst[i + 1] - lst[i] == step: i += 1\n stop = lst[i] + 1\n slc_lst.append(slice(start, stop, None if step == 1 else step))\n i += 1\n\n return slc_lst\n\n #Get the a list of the (sub-)indices along each axis, whose product\n # (along the specified axes) gives the entire block given by slcTup\n axisSlices = []\n for iaxis, axis in enumerate(axes):\n ind = indTup[iaxis]\n sub_slices = []\n\n #break `ind`, which may be either a single slice or an index array,\n # into a list of slices that are broadcast one at a time (sometimes\n # these `ind_slice` slices themselves need to be broken up further\n # to obey max_buffer_size).\n for islice in to_slice_list(ind):\n if max_indices[iaxis] is None or max_indices[iaxis] >= _slct.length(islice):\n sub_slices.append(islice) # arIndx[axis] = slc\n else:\n sub_slices.extend(_slct.divide(islice, max_indices[iaxis]))\n axisSlices.append(sub_slices)\n\n for axSlcs in _itertools.product(*axisSlices):\n #create arIndx from per-axis (sub-)slices and broadcast\n for iaxis, axis in enumerate(axes):\n arIndx[axis] = axSlcs[iaxis]\n\n #broadcast arIndx slice\n buf = _findx(arToFill, arIndx, True) if (my_rank == owner) \\\n else _np.empty(_findx_shape(arToFill, arIndx), arToFill.dtype)\n comm.Bcast(buf, root=owner)\n if my_rank != owner: _fas(arToFill, arIndx, buf)\n buf = None # free buffer mem asap\n\n\ndef distribute_for_dot(contracted_dim, comm):\n \"\"\"\n Prepares for one or muliple distributed dot products given the dimension\n to be contracted (i.e. the number of columns of A or rows of B in dot(A,B)).\n The returned slice should be passed as `loc_slice` to :func:`mpidot`.\n\n Parameters\n ----------\n contracted_dim : int\n The dimension that will be contracted in ensuing :func:`mpidot`\n calls (see above).\n\n comm : mpi4py.MPI.Comm or None\n The communicator used to perform the distribution.\n\n Returns\n -------\n slice\n The \"local\" slice specifying the indices belonging to the current\n processor. Should be passed to :func:`mpidot` as `loc_slice`.\n \"\"\"\n loc_indices, _, _ = distribute_indices(\n list(range(contracted_dim)), comm, False)\n\n #Make sure local columns are contiguous\n start, stop = loc_indices[0], loc_indices[-1] + 1\n assert(loc_indices == list(range(start, stop)))\n return slice(start, stop) # local column range as a slice\n\n\ndef mpidot(a, b, loc_slice, comm):\n \"\"\"\n Performs a distributed dot product, dot(a,b).\n\n Parameters\n ----------\n a,b : numpy.ndarray\n Arrays to dot together.\n\n loc_slice : slice\n A slice specifying the indices along the contracted dimension belonging\n to this processor (obtained from :func:`distribute_for_dot`)\n\n comm : mpi4py.MPI.Comm or None\n The communicator used to parallelize the dot product.\n\n Returns\n -------\n numpy.ndarray\n \"\"\"\n if comm is None or comm.Get_size() == 1:\n assert(loc_slice == slice(0, b.shape[0]))\n return _np.dot(a, b)\n\n from mpi4py import MPI # not at top so can import pygsti on cluster login nodes\n loc_dot = _np.dot(a[:, loc_slice], b[loc_slice, :])\n result = _np.empty(loc_dot.shape, loc_dot.dtype)\n comm.Allreduce(loc_dot, result, op=MPI.SUM)\n\n #DEBUG: assert(_np.linalg.norm( _np.dot(a,b) - result ) < 1e-6)\n return result\n\n #myNCols = loc_col_slice.stop - loc_col_slice.start\n ## Gather pieces of coulomb tensor together\n #nCols = comm.allgather(myNCols) #gather column counts into an array\n #displacements = _np.concatenate(([0],_np.cumsum(sizes))) #calc displacements\n #\n #result = np.empty(displacements[-1], a.dtype)\n #comm.Allgatherv([CTelsLoc, size, MPI.F_DOUBLE_COMPLEX], \\\n # [CTels, (sizes,displacements[:-1]), MPI.F_DOUBLE_COMPLEX])\n\n\ndef parallel_apply(f, l, comm):\n '''\n Apply a function, f to every element of a list, l in parallel, using MPI\n Parameters\n ----------\n f : function\n function of an item in the list l\n l : list\n list of items as arguments to f\n comm : MPI Comm\n MPI communicator object for organizing parallel programs\n\n Returns\n -------\n results : list\n list of items after f has been applied\n '''\n locArgs, _, locComm = distribute_indices(l, comm)\n if locComm is None or locComm.Get_rank() == 0: # only first proc in local comm group\n locResults = [f(arg) for arg in locArgs] # needs to do anything\n else: locResults = []\n results = comm.allgather(locResults) # Certain there is a better way to do this (see above)\n results = list(_itertools.chain.from_iterable(results)) # list-of-lists -> single list\n return results\n\n\ndef get_comm():\n '''\n Get a comm object\n\n Returns\n -------\n MPI.Comm\n Comm object to be passed down to parallel pygsti routines\n '''\n from mpi4py import MPI # not at top so can import pygsti on cluster login nodes\n return MPI.COMM_WORLD\n","sub_path":"packages/pygsti/tools/mpitools.py","file_name":"mpitools.py","file_ext":"py","file_size_in_byte":32466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"473923510","text":"a=[]\nfor v in range(4):\n a.append(input('Enter a Number :'))\n print(a)\n\ndef selectionSort(a):\n for j in range(len(a)):\n min = j\n for i in range(j+1,len(a)):\n if(a[min] >a [i]):\n min = i\n temp = a[j]\n a[j] = a[min]\n a[min] = temp\n\nselectionSort(a)\nprint(a)\n","sub_path":"Sorting Algorithms/selectionSort.py","file_name":"selectionSort.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"141725458","text":"# coding:utf-8\nfrom mall.core.orm import Flow, ResponseData\nimport logging\n\nlogger = logging.getLogger(\"mall.db\")\n\n\ndef flow_sample(time_stamp, name, action, details):\n \"\"\"生成购物消费流水信息记录\"\"\"\n flow = Flow(time_stamp, name, action, details)\n code = 200\n msg = u\"新建消费流水模型成功,详情:{0}\".format(flow.__dict__)\n logger.debug(ResponseData(code, msg).__dict__)\n\n return ResponseData(code, msg, flow)\n","sub_path":"14、练习的项目/5_ATM+购物商城程序/shopping_mall/mall/db/flow_sample.py","file_name":"flow_sample.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"187515467","text":"# 差分を1,2次元目\n# 3次元目にもとの位置の番号を入れる\n\nimport random\nfrom typing import Tuple\n#import numpy as np\nimport numpy as np\nfrom PIL import Image\n\n\n\n\nclass puzzle():\n\n def __init__(self,hight,width,numOfselect,numOfmove,type = \"zero2end\"):\n self.hight = hight\n self.width = width\n self.s_time = numOfselect\n self.m_time = numOfmove\n self.fowerd_rec = dict()\n self.backwerd_rec = dict()\n self.pazzle = [[0] * self.width for i in range(self.hight)]\n self.ndarray = np.zeros((self.hight,self.width,3))\n self.ans = [[0] * self.width for i in range(self.hight)]\n self.ndarray_ans = np.zeros((self.hight,self.width,3))\n self.place_dimension = [[0] * self.width for i in range(self.hight)]\n self.cartesian_coodinates()\n self.zero2end()\n #下は答えを16baisiteru \n self.ndarray_ans= np.array(self.ans)*16\n # 下はplace_dimension をpazzle に追加してる\n self.pazzle = np.array(self.pazzle) + np.array(self.place_dimension)\n self.pazzle = self.pazzle.tolist()\n #print_2d(self.pazzle)\n \n \n #実際にパズルを作成するmain\n def create(self):\n for i in range(self.s_time):\n target = self.select_cell()\n #print(f\"we select {target}\")\n move_time_of_target = random.randint(1,self.m_time)\n intial_target = target\n self.fowerd_rec[intial_target] = \"\"\n for j in range(move_time_of_target):\n #print(f\"move {target}\")\n target = self.move_cell(target,intial_target)\n self.make_pic(target)\n self.make_backword(target,intial_target)\n return self.pazzle\n\n \n def list2ndarray(self):\n self.ndarray = np.array(self.pazzle)*16\n return self.ndarray, self.ndarray_ans\n\n\n # マス選択、移動\n def select_cell(self):\n return (random.randrange(0,self.hight),random.randrange(0,self.width))\n \n def move_cell(self,target,i_target):\n moveList = [\"D\",\"L\",\"U\",\"R\"]\n\n way = random.randrange(1,5)\n have_record = len(self.fowerd_rec[i_target])\n if have_record:\n if moveList[way-1] == self.fowerd_rec[i_target][-1]:\n while(moveList[way-1] == self.fowerd_rec[i_target][-1]):\n way = random.randrange(1,5)\n \n if way == 1 : # 上\n self.pazzle[target[0]-1][target[1]], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[target[0]-1][target[1]]\n #print(f\"swap {self.pazzle[target[0]-1][target[1]]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"U\"\n if target[0]-1 < 0:\n return (self.hight-1,target[1])\n else:\n return (target[0]-1,target[1])\n elif way == 2: #右\n if target[1] + 1 < self.width:\n self.pazzle[target[0]][target[1]+1], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[target[0]][target[1]+1]\n #print(f\"swap {self.pazzle[target[0]][target[1]+1]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"R\"\n return (target[0],target[1]+1)\n else:\n self.pazzle[target[0]][0], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[target[0]][0]\n #print(f\"swap {self.pazzle[target[0]][-1]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"R\"\n return (target[0],0)\n elif way == 3: #下\n if target[0] + 1< self.hight:\n self.pazzle[target[0]+1][target[1]], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[target[0]+1][target[1]]\n #print(f\"swap {self.pazzle[target[0]+1][target[1]]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"D\"\n return (target[0] + 1,target[1])\n else:\n self.pazzle[0][target[1]], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[0][target[1]]\n #print(f\"swap {self.pazzle[-1][target[1]]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"D\"\n return (0,target[1])\n elif way == 4: #左\n self.pazzle[target[0]][target[1]-1], self.pazzle[target[0]][target[1]] = self.pazzle[target[0]][target[1]] , self.pazzle[target[0]][target[1]-1]\n #print(f\"swap {self.pazzle[target[0]][target[1]-1]} {self.pazzle[target[0]][target[1]] }\")\n self.fowerd_rec[i_target] += \"L\"\n if target[1]-1 < 0:\n return(target[0],self.width-1)\n else:\n return (target[0] ,target[1]-1)\n \n def make_backword(self,target,i_target):\n target = list(target)\n if target[0] < 0:\n #print(f\"bbb {target}\")\n target[0] = self.hight+target[0]\n #print(f\"aaa {target}\")\n if target[1] < 0:\n #print(f\"bbb {target}\")\n target[1] = self.width+target[1]\n #print(f\"aaa {target}\")\n target = tuple(target)\n self.backwerd_rec[target] = \"\"\n for i in self.fowerd_rec[i_target]:\n if i == \"U\":\n self.backwerd_rec[target] += \"D\"\n elif i == \"D\":\n self.backwerd_rec[target] += \"U\"\n elif i == \"R\":\n self.backwerd_rec[target] += \"L\"\n elif i == \"L\":\n self.backwerd_rec[target] += \"R\"\n \n\n #数字の初期化バリエーションs\n def zero2end(self):\n #このバージョンのために変更元は他のバージョンを参照\n for i in range(self.hight):\n for j in range(self.width):\n self.place_dimension[i][j] = [0,0,i* self.width + j]\n \n def cartesian_coodinates(self):\n for i in range(self.hight):\n for j in range(self.width):\n self.pazzle[i][j] = [i,j,0]\n self.ans[i][j] = [i,j,0]\n \n def deffrence(self):\n p ,a = pazzle.list2ndarray()\n return p -a \n\n def make_pic(self,target,type = \"nomal\"):\n folder = target\n label = file_num[folder[0]][folder[1]]\n f_num = folder[0]*16 + folder[1]\n deffrences = self.deffrence()\n deffrences = deffrences + self.place_dimension\n Image.fromarray(deffrences.astype(np.uint8)).save(f\"E:/procon/data/16x16_v0/{folder}_{f_num}/{label}.jpg\")\n file_num[folder[0]][folder[1]] += 1\n #print_2d(deffrences)\n \n \ndef print_2d(my_list):\n for a in my_list:\n print(*a) \n\n# pazzle = puzzle(4, 4, 1, 3)\n# print_2d(pazzle.create())\n# print(pazzle.fowerd_rec)\n# print(pazzle.backwerd_rec)\nfile_num = [[0] * 16 for i in range(16)]\n\nfor i in range(20000):\n select = random.randint(2,128)\n pazzle = puzzle(16, 16, select, 30 ,\"cartesian_coordinates\")\n pazzle.create()\n # print(pazzle.fowerd_rec)\n # print(pazzle.backwerd_rec)\n\n # print(\"pazzle\")\n # print_2d(pazzle.pazzle)\n\n # p, a = pazzle.list2ndarray()\n # print(\"sabun\")\n # deffrence = p - a\n # print(\"diff\")\n # print(deffrence)\n # print(f\"p \\n {p}\")\n # print(f\"a \\n {a[1]}\")\n # print(f\"b \\n {pazzle.ans[1]}\")\n # #print(pazzle.ndarray)\n # print(pazzle.ans)\n print(i)\n\n","sub_path":"generate_pazzle_v5.py","file_name":"generate_pazzle_v5.py","file_ext":"py","file_size_in_byte":7550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"548572326","text":"#Write a function, is_prime, which takes a single integer argument and returns True\n# when the argument is a prime number and False otherwise. Add tests for cases like this:\nimport math as m\n\ndef is_prime(n):\n counter = 0\n for i in range(1,n+1):\n if n % i == 0:\n counter += 1\n if counter >= 3:\n return False\n else:\n continue\n return True\n\ndef prime_list(n):\n for i in range(1,n):\n print(i, end=' {0} \\n'.format(is_prime(i)))\n\nprime_list(240)","sub_path":"ex_7_26_10.py","file_name":"ex_7_26_10.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"623919830","text":"from selenium import webdriver\nimport time\nimport re\n#import linkGrabber\n\n#Opening a firebox session\ndriver = webdriver.Firefox()\ndriver.implicitly_wait(30)\ndriver.maximize_window()\n\n#Opening a webpage\ndriver.get('http://google.com')\n\n#Search in text box\nsearchField = driver.find_element_by_name('q')\nsearchField.clear()\n\nurls = driver.find_elements_by_xpath('//*[@href]')\n\nfor links in urls:\n print(links.get_attribute(\"href\"))\ntime.sleep(5)\n\n#Enter the search and submit\nsearchField.send_keys('500px Photos')\nsearchField.submit()\n\n#Grab links\n#links = linkGrabber.links()\n#urls = links.find(limits=10)\n#print(urls)\n\n\n\n\n","sub_path":"Learning/PracticeApps/SeachProduct.py","file_name":"SeachProduct.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"585223707","text":"\nimport re\n\nimport MeCab\nfrom pykakasi import kakasi\n\nfrom consts import MECAB_NUM\n\n\nclass RomanaizeST:\n \"\"\"\n 編集距離算出クラス\n \"\"\"\n def __init__(self):\n \"\"\"\n 初期化メソッド\n \"\"\"\n k = kakasi()\n k.setMode('K', 'a')\n self.conv = k.getConverter()\n self.tagger = MeCab.Tagger('-d /var/lib/mecab/dic/debian')\n\n def katakanize(self, text: str) -> str:\n \"\"\"\n 文字列をカタカナに変換する\n\n @return: カタカナ文字列\n \"\"\"\n morphed = [re.split(r\"[,\\t\\s\\n]\", w) for w in self.tagger.parse(text).split(\"\\n\")]\n morphed.remove([\"\"])\n morphed.remove([\"EOS\"])\n k = [morph[MECAB_NUM] if morph[MECAB_NUM] != \"*\" else morph[0] for morph in morphed]\n\n return \"\".join(k)\n\n def romanaize(self, text: str) -> list:\n \"\"\"\n カタカナ文字列をローマ字にして返す\n\n @return: ローマ字に変換済み文字列\n \"\"\"\n katakana = self.katakanize(text)\n\n if type(katakana) == str:\n katakana = [katakana]\n\n return [self.conv.do(k) for k in katakana]\n\n\nif __name__ == '__main__':\n rs = RomanaizeST()\n print(rs.romanaize(\"横浜\"))\n","sub_path":"deploy_station/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"297923382","text":"import EconEvalInputData as D\nimport ProbabilisticSupport as Support\nimport ProbilisticParamClasses as P\nfrom ParallelClasses import ParallelMultiCohort\n\nN_COHORTS = 200 # number of cohorts\n\nif __name__ == '__main__': # this line is needed to avoid errors that occur on Windows computers\n\n # create a multi-cohort to simulate under mono therapy\n multiCohortMono = ParallelMultiCohort(\n ids=range(N_COHORTS),\n pop_size=D.POP_SIZE,\n therapy=P.Therapies.MONO\n )\n\n multiCohortMono.simulate(sim_length=D.SIM_LENGTH)\n\n # create a multi-cohort to simulate under combi therapy\n multiCohortCombo = ParallelMultiCohort(\n ids=range(N_COHORTS),\n pop_size=D.POP_SIZE,\n therapy=P.Therapies.COMBO\n )\n\n multiCohortCombo.simulate(sim_length=D.SIM_LENGTH)\n\n # print the estimates for the mean survival time and mean time to AIDS\n Support.print_outcomes(multi_cohort_outcomes=multiCohortMono.multiCohortOutcomes,\n therapy_name=P.Therapies.MONO)\n Support.print_outcomes(multi_cohort_outcomes=multiCohortCombo.multiCohortOutcomes,\n therapy_name=P.Therapies.COMBO)\n\n # draw survival curves and histograms\n Support.plot_survival_curves_and_histograms(multi_cohort_outcomes_mono=multiCohortMono.multiCohortOutcomes,\n multi_cohort_outcomes_combo=multiCohortCombo.multiCohortOutcomes)\n\n # print comparative outcomes\n Support.print_comparative_outcomes(multi_cohort_outcomes_mono=multiCohortMono.multiCohortOutcomes,\n multi_cohort_outcomes_combo=multiCohortCombo.multiCohortOutcomes)\n\n # report the CEA results\n Support.report_CEA_CBA(multi_cohort_outcomes_mono=multiCohortMono.multiCohortOutcomes,\n multi_cohort_outcomes_combo=multiCohortCombo.multiCohortOutcomes)","sub_path":"CompareAlternatives.py","file_name":"CompareAlternatives.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"561294747","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 30 23:02:30 2020\r\n\r\n@author: wang_\r\n\"\"\"\r\n\r\n#%% \r\nfrom scipy import signal\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.signal import stft\r\nfrom scipy.io import wavfile\r\nfrom numpy import ma\r\nfrom matplotlib import ticker, cm\r\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\r\n\r\ndef get_wave_form(path):\r\n wav_sci = wavfile.read(path)\r\n wave_form = wav_sci[1]\r\n if wave_form.ndim > 1:\r\n wave_form = wave_form[:, 0]\r\n return wave_form\r\n\r\ndef get_STFT_power(wave_form):\r\n f, t, Zxx = signal.stft(wave_form, fs=48000, nperseg = 1000)\r\n Zxx = np.flipud(Zxx)\r\n power = 10* np.log10(abs(Zxx))\r\n #power[power<-] = -10000\r\n \r\n return power, f, t\r\n \r\n#%% Single plot \r\n\r\ni = 2\r\n\r\nfn = \"\"\r\ntarget_model = \"ibm\"\r\ntarget_model_name = {\"google\": \"Google\", \"wit\": \"Wit\", \"ibm\": \"IBM\", \"azure\" : \"Azure\"}\r\n\r\n\r\ntitle_list = ['Original command', \"Noise Signal\", \"Segmented Perturbation on \"+ target_model_name[target_model] ]\r\n\r\noriginal_path = \"AudioSamples\\\\Experiment4_SoundSample\\\\sound1\\\\\"\r\nsegment_path = \"AudioSamples\\\\Experiment4_SoundSample\\\\attack1\\\\\"\r\n\r\nwave_form_original = get_wave_form( original_path + fn +\".wav\")\r\nwave_form_RPG = np.random.randint(-100, 100, size=137088)\r\nwave_form_segment = get_wave_form(segment_path + fn + \"_\" + target_model + \"_fine_tune_delete_breadth_first.wav\")\r\n\r\nwave_form_list = [wave_form_original, wave_form_RPG, wave_form_segment ]\r\n\r\npower_original, f, t = get_STFT_power(wave_form_original)\r\npower_RPG, f, t = get_STFT_power(wave_form_RPG)\r\npower_segment, f, t = get_STFT_power(wave_form_segment)\r\n\r\npower_list = [power_original, power_RPG, power_segment]\r\n\r\n# set \r\nplt.rcParams['savefig.dpi'] = 800 #\r\nplt.rcParams['figure.dpi'] = 800 #\r\n# \r\n\r\nax = plt.subplot(111)\r\n\r\nim = ax.imshow(power_list[i], cmap=\"YlOrRd\", interpolation='none', origin='lower')\r\nax.set_ylabel(\"Frequency (Hz)\")\r\nax.set_xlabel(\"Time (s)\")\r\nx_ind = [0, 100, 190]\r\ny_ind = range(0, 500, 50)\r\n\r\nax.set_title(title_list[i])\r\nax.set_xticks(x_ind)\r\nax.set_yticks(y_ind)\r\nax.set_xticklabels(np.around(t[x_ind], decimals=1))\r\nax.set_yticklabels( f[y_ind])\r\n\r\ndivider = make_axes_locatable(ax)\r\ncax = divider.append_axes(\"right\", size=\"10%\", pad=0.1)\r\ncolorbar = plt.colorbar(im, cax=cax)\r\ncolorbar.set_label(\"Power/Frequency (dB/Hz)\")\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"STFT.py","file_name":"STFT.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"420032165","text":"#!/usr/bin/env python\n\n# Ivan Silva\n\n\nimport sys, signal, os\n# import select\nimport optparse\nfrom socket import *\n\nparser = optparse.OptionParser()\nparser.add_option('-p', '--port', dest=\"port\", default=25000, type=int, help=\"server port\")\nparser.add_option('-s', '--server', dest=\"server\", default=\"::127.0.0.1\", help=\"server IP or name\")\nparser.add_option('-6', action=\"store_true\", dest=\"ip6\", default=\"True\", help=\"IPv6\")\nparser.add_option('-b', '--bufsize', dest=\"bufsize\", default=1024, type=int, help=\"dimensione buffer\")\noptions, remainder = parser.parse_args()\n\nprint(\" port:\", options.port, \" server:\", options.server, \"bufsize:\", options.bufsize, \"IPv6:\", options.ip6)\n\n\ndef handler_alrm(signum, frame):\n print('Signal handler called with signal', signum)\n signal.alarm(options.timeout)\n global N\n N = 0\n\n\ndef handler_int(signum, frame):\n print('Signal handler called with signal', signum)\n sys.exit(0)\n\n\n# signal.signal(signal.SIGALRM, handler_alrm)\nsignal.signal(signal.SIGINT, handler_int)\n\nif options.ip6 is True:\n s = socket(AF_INET6, SOCK_DGRAM)\nelse:\n s = socket(AF_INET, SOCK_DGRAM)\n\ns.bind((options.server, options.port))\n\nwhile (1):\n data, addr = s.recvfrom(options.bufsize)\n print(\"addr:\", addr, \" data:\", data.decode())\n","sub_path":"3.2UDP/dgram6/dgram_server6.py","file_name":"dgram_server6.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"494246207","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='action',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('deleted', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='action_type',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('a_type', models.CharField(max_length=255)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('deleted', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='gift',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('gift_details', models.CharField(max_length=1000)),\n ('receipt_date', models.DateField()),\n ('receipt_place', models.CharField(max_length=255)),\n ('occassion', models.CharField(max_length=255)),\n ('value', models.CharField(max_length=255)),\n ('agency_name', models.CharField(max_length=255)),\n ('is_acted_upon', models.CharField(max_length=255)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('deleted', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='user',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dob', models.DateField()),\n ('designation', models.CharField(max_length=255)),\n ('department', models.CharField(max_length=255)),\n ('e_number', models.CharField(max_length=255)),\n ('address', models.CharField(max_length=1000)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('deleted', models.DateTimeField(auto_now_add=True)),\n ('django_user_ref', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.AddField(\n model_name='gift',\n name='django_user_ref',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='action',\n name='action_ref',\n field=models.ForeignKey(to='gds_app.action_type'),\n ),\n migrations.AddField(\n model_name='action',\n name='gift_ref',\n field=models.ForeignKey(to='gds_app.gift'),\n ),\n ]\n","sub_path":"gds_project/gds_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"438412049","text":"# Project Euler - Problem 3\n# Published 02/11/2001 - 18:00\n# What is the largest prime factor of the number 600851475143 ?\n\n###\n\ndef even(n):\n if n % 2 == 0:\n return True\n else:\n return False\n\ndef is_prime(n):\n if even(n):\n return False\n i = 3\n if n < i:\n return False\n while i <= n/2:\n if n % i == 0:\n #print(i)\n return False\n i += 2\n return True\n# currently iterates through every odd number after checking not even\n# couple be improved eg. if not div by 3, then no need to check 9, 15 etc.\n\ndef prime_factors(n):\n factors = []\n i = 2\n while i <= n/2:\n if n % i == 0:\n n = int(n/i)\n factors.append(i)\n i = 2\n else:\n i += 1\n factors.append(n)\n return factors\n\nprint(prime_factors(600851475143))\n \n\n\n","sub_path":"chapmanh/problem_003.py","file_name":"problem_003.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"446572438","text":"import urllib.request\nimport json \nimport configparser\nimport logging\nfrom logging import handlers, StreamHandler\nfrom collections import OrderedDict\nfrom urllib.parse import urljoin\nfrom datetime import datetime\nfrom sys import exit\n\n\n\n##############################################################################\n# Classes\nclass PSCAPI:\n\tpath_notification = '/integrationServices/v3/notification'\n\n\tdef __init__(self, server, api_key, con_id):\n\t\tself.server = server\n\t\tself.api_token = api_key + '/' + con_id\n\n\tdef getNotification(self):\n\t\turl = urljoin(self.server, self.path_notification)\n\t\treturn self._get(url)\n\n\tdef _get(self, url):\n\t\treq = urllib.request.Request(url)\n\t\treq.add_header('X-Auth-Token', self.api_token) # IMDL: multiple headder\n\n\t\ttry:\n\t\t\twith urllib.request.urlopen(req) as res:\n\t\t\t\tbody = res.read()\n\t\t\treturn 'success', body.decode('utf-8')\n\t\texcept urllib.error.HTTPError as err:\n\t\t\treturn 'HTTPError', str(err.code)\n\t\texcept urllib.error.URLError as err:\n\t\t\treturn 'URLError', str(err.reason)\n\n\nclass PSCJsonAlert:\n\tdef __init__(self, json_txt, connector_name):\n\t\tself.connector_name = connector_name\n\t\tself.output_str_list = []\n\t\t_json_txt = json_txt.replace('\\n','') #Response body has '\\n'. Getting error if it is not removed.\n\t\tjson_dict = json.loads(_json_txt)\n\t\tself._mkOutList(json_dict)\n\n\n\tdef _mkOutList(self, json_dict):\n\t\tfor per_alert_dict in json_dict['notifications']: #If there is no alert, this foreach finishs without loop. \n\t\t\toutput_str = self._mkPerAltStr(per_alert_dict)\n\t\t\tself.output_str_list.append(output_str)\n\n\n\tdef _mkPerAltStr(self, per_alert_dict):\n\t\t_output = OrderedDict()\n\t\t#fixed strings might change in a future release.\n\t\t_output['source'] = self.connector_name\n\t\t_output['version']= 'CEF:0'\n\t\t_output['vendor'] = 'CBJ'\n\t\t_output['product'] = 'PSC_Syslog_Connector_oss'\n\t\t_output['dev_version'] = '1.0'\n\t\t_output['signature'] = 'Active_Threat' # \"Signature\" is always \"Active_Threat\".\n\t\t_output['name'] = per_alert_dict['threatInfo']['summary']\n\t\t_output['severity'] = per_alert_dict['threatInfo']['score']\n\t\t_output['extention'] = self._mkAltExtension(per_alert_dict)\n\n\t\t_output_str = ''\n\t\tfor v in _output.values():\n\t\t\t_output_str += str(v)\n\t\t\t_output_str += '|'\n\n\t\treturn _output_str[:-1]\n\n\n\tdef _mkAltExtension(self, per_alert_dict):\n\t\t_extension = OrderedDict()\n\t\teventtime = per_alert_dict['threatInfo']['time'] # Should I use 'eventTime' instead of 'time'?\n\t\tdate_str = datetime.fromtimestamp(int(eventtime) / 1000)\n\t\t_extension['rt'] = '\"' + date_str.strftime('%b %d %Y %H:%M:%S') + '\"' # Format = Dec 06 2018 22:04:53\n\t\t_extension['dvchost'] = per_alert_dict['deviceInfo']['deviceName'] \n\t\t_extension['duser'] = per_alert_dict['deviceInfo']['email'] \n\t\t_extension['dvc'] = per_alert_dict['deviceInfo']['internalIpAddress'] \n\t\t_extension['cs3Label'] = '\"Link\"'\n\t\t_extension['cs3'] = '\"' + per_alert_dict['url'] + '\"'\n\t\t_extension['cs4Label'] = '\"Threat_ID\"'\n\t\t_extension['cs4'] = '\"' + per_alert_dict['threatInfo']['incidentId'] + '\"'\n\t\t_extension['act'] = 'Alert'\n\n\t\t_extension_str = ''\n\t\tfor k, v in _extension.items():\n\t\t\t_extension_str += k + '=' + str(v) + ' '\n\n\t\treturn _extension_str[:-1]\n\n\tdef getOutputList(self):\n\t\treturn self.output_str_list\n\n\nclass SendSyslog:\n\tdef __init__(self, syslog_server_port, facility):\n\t\tsyslog_server, syslog_port = syslog_server_port.split(':')\n\t\tself.my_syslog = logging.getLogger('MySyslog')\n\t\tself.my_syslog.setLevel(logging.DEBUG) #IMCL.\n\t\thandler = logging.handlers.SysLogHandler(address = (syslog_server,int(syslog_port)), facility=facility) #IMCL facility\n\t\tformatter = logging.Formatter('%(message)s') \n\t\thandler.setFormatter(formatter)\n\t\tself.my_syslog.addHandler(handler)\n\n\tdef send(self, priority, msg):\n\t\t#alert, emerg, notice are not supported in python logging module.\n\t\tif priority == 'debug':\n\t\t\t\tself.my_syslog.debug(msg)\n\t\telif priority == 'info':\n\t\t\t\tself.my_syslog.info(msg)\n\t\telif priority == 'warn':\n\t\t\t\tself.my_syslog.warn(msg)\n\t\telif priority == 'error':\n\t\t\t\tself.my_syslog.error(msg)\n\t\telif priority == 'critical':\n\t\t\t\tself.my_syslog.critical(msg)\n\t\t\n\nclass LocalLogging:\n\t_log_disable_flag = False\n\t_log_format = '%(asctime)s : %(levelname)s : %(message)s'\n\n\tdef __init__(self, log_file, level):\n\t\tself.llogger = logging.getLogger('LocalLogging')\n#\t\tself.llogger.setLevel(logging.INFO)\t\n\t\tself._setLoggingLevel(level)\n\n\t\tif not log_file:\n\t\t\tself._log_disable_flag = True\n\t\t\treturn\n\t\telif log_file == 'STDOUT':\n\t\t\tfile_handler = StreamHandler()\n\t\telse:\n#\t\t\tfile_handler = logging.FileHandler(filename=log_file)\n\t\t\tfile_handler = logging.FileHandler(log_file, 'a', 'utf-8')\n\n\n\t\tfile_handler.setLevel(logging.DEBUG)\n\t\thandler_format = logging.Formatter(self._log_format)\n\t\tfile_handler.setFormatter(handler_format)\n\t\tself.llogger.addHandler(file_handler)\n\n\n\tdef _setLoggingLevel(self, level):\n\t\tif level == 'debug':\n\t\t\t\tself.llogger.setLevel(logging.DEBUG)\t\n\t\telif level == 'info':\n\t\t\t\tself.llogger.setLevel(logging.INFO)\t\n\t\telif level == 'warn':\n\t\t\t\tself.llogger.setLevel(logging.WARN)\t\n\t\telif level == 'error':\n\t\t\t\tself.llogger.setLevel(logging.ERROR)\t\n\t\telif level == 'critical':\n\t\t\t\tself.llogger.setLevel(logging.CRITICAL)\t\n\n\n\tdef write(self, level, msg):\n\t\tif self._log_disable_flag == True:\n\t\t\treturn\n\n\t\tif level == 'debug':\n\t\t\t\tself.llogger.debug(msg)\n\t\telif level == 'info':\n\t\t\t\tself.llogger.info(msg)\n\t\telif level == 'warn':\n\t\t\t\tself.llogger.warn(msg)\n\t\telif level == 'error':\n\t\t\t\tself.llogger.error(msg)\n\t\telif level == 'critical':\n\t\t\t\tself.llogger.critical(msg)\n\n\n\n##############################################################################\n# main()\nconfig = configparser.ConfigParser()\nconfig.read('config.ini', 'UTF-8')\n\nll = LocalLogging(config.get('connector_log', 'log_file'), config.get('connector_log', 'log_level'))\n\nll.write('info','Start')\n\n# Get Alert from PSC\nll.write('debug', 'Getting json started.')\npapi = PSCAPI(config.get('cbdefense1', 'server_url'), config.get('cbdefense1', 'api_key'), config.get('cbdefense1', 'connector_id'))\nhttp_stat, resp_body = papi.getNotification()\ndel papi\nif http_stat != 'success':\n\tll.write('debug', http_stat + ':' + resp_body)\n\texit()\n\t\nll.write('debug', resp_body)\nll.write('debug', 'Getting json finished.')\n\n# Parse response body\npja = PSCJsonAlert(resp_body, config.get('cbdefense1', 'connector_name'))\noutput_list = pja.getOutputList() #Get each output str in list format.\n\nalt_cnt = len(output_list)\nll.write('info', 'Alert count:' + str(alt_cnt))\n\nif not alt_cnt:\n\tll.write('info', 'Finished.')\n\texit()\n\n#Send syslog\nll.write('debug', 'Sending syslog started.')\nss = SendSyslog(config.get('general', 'udp_out'), config.get('general', 'facility'))\n\nfor msg in output_list:\n\tss.send(config.get('general', 'priority'), msg)\n\nll.write('info', 'Finished.')\n\n\n","sub_path":"PSC_Syslog_Connector.py","file_name":"PSC_Syslog_Connector.py","file_ext":"py","file_size_in_byte":6764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"110985576","text":"\"\"\"Implementation example of a Control Volume Finite Differences for the\nsteadystate diffusion equation. The equation is of the form:\n\n.. math::\n\n 0 = \\\\nabla \\\\cdot \\\\big[ D(\\\\mathbf{r}) \\\\ \\\\nabla\\\\phi(\\\\mathbf{r}) \\\\big]\n\nWhere :math:`D(\\\\mathbf{r})` is the diffusion coefficient and\n:math:`\\\\phi(\\\\mathbf{r})` is the density of the diffusion material.\n\n\"\"\"\n\nimport numpy as np\n\nfrom elliptic.Kernel.EntityKernelMixins import DimensionEntityKernelMixin\nfrom elliptic.Kernel.ArrayKernelMixins import (FillVectorKernelMixin,\n FillMatrixKernelMixin)\nfrom elliptic.Kernel import AdjKernelMixin\nfrom .Physical import Dirichlet, Neumann\n\nCACHE_ADJ = True\n\n\nclass EquivDiff(DimensionEntityKernelMixin, FillVectorKernelMixin,\n AdjKernelMixin):\n \"\"\"Kernel which calculates the equivalent diffusivity in the faces.\n\n \"\"\"\n cache_adj = CACHE_ADJ\n\n entity_dim = 2\n bridge_dim = 2\n target_dim = 3\n depth = 1\n solution_dim = 2\n\n @classmethod\n def run(cls, m, elem):\n adj = cls.get_adj(m, elem, cls.bridge_dim, cls.target_dim, cls.depth)\n\n if len(adj) > 1:\n edge_center = cls.get_center(m, elem)\n el1_center = cls.get_center(m, adj[0])\n el2_center = cls.get_center(m, adj[1])\n dx1 = np.linalg.norm(el1_center - edge_center)\n dx2 = np.linalg.norm(el2_center - edge_center)\n D1 = cls.get_physical(m, adj[0]).value\n D2 = cls.get_physical(m, adj[1]).value\n\n D_equiv = (2*D1*D2) / (D1*dx2 + D2*dx1)\n\n cls.fill_array(m, [(elem, D_equiv)])\n else:\n cls.fill_array(m, [(elem, 0)])\n\n\nclass FillDiag(DimensionEntityKernelMixin, FillMatrixKernelMixin,\n AdjKernelMixin):\n \"\"\"Fills the matrix diagonals.\n\n \"\"\"\n cache_adj = CACHE_ADJ\n\n array_name = \"A\"\n share = True\n\n entity_dim = 3\n solution_dim = 3\n\n @classmethod\n def run(cls, m, elem):\n # Default value\n value = 0\n\n for dim in range(0, cls.entity_dim):\n adj_faces_physical = cls.get_adj_physical(\n m, elem, dim, dim, phys_type=[Dirichlet])\n # If the current element has a boundary condition,\n # sets value to 1\n if adj_faces_physical:\n value = 1\n break\n\n results = {\n 'set': [(elem, [elem], [value])],\n 'sum': []\n }\n\n cls.fill_array(m, results)\n\n\nclass FillBoundary(DimensionEntityKernelMixin, FillVectorKernelMixin,\n AdjKernelMixin):\n \"\"\"Fills the vector 'b' with boundary conditions.\n\n \"\"\"\n cache_adj = CACHE_ADJ\n\n array_name = \"b\"\n entity_dim = 3\n solution_dim = 3\n\n @classmethod\n def run(cls, m, elem):\n value = 0\n\n for dim in range(0, cls.entity_dim):\n adj_faces_physical = cls.get_adj_physical(\n m, elem, dim, dim, phys_type=[Dirichlet, Neumann])\n # If the current element has a boundary condition,\n # sets value to the constrained value\n if adj_faces_physical:\n value = adj_faces_physical.value\n break\n\n cls.fill_array(m, [(elem, value)])\n\n\nclass CVFDKernel(DimensionEntityKernelMixin, FillMatrixKernelMixin,\n AdjKernelMixin):\n \"\"\"Example kernel for the CC-FVM method. This kernel iterates on the mesh\n faces and fills the transmissibility matrix accordingly.\n\n \"\"\"\n cache_adj = CACHE_ADJ\n\n array_name = \"A\"\n share = True\n\n entity_dim = 2\n bridge_dim = 2\n target_dim = 3\n depth = 1\n solution_dim = 3\n\n depends = [EquivDiff, FillDiag, FillBoundary]\n\n @classmethod\n def run(cls, m, elem):\n results = {\n 'set': [],\n 'sum': []\n }\n\n # Gets the equivalent diffusivity for the face\n K_equiv = cls.EquivDiff_array[elem]\n\n adj = cls.get_adj(m, elem, cls.bridge_dim, cls.target_dim, cls.depth)\n adj = list(adj)\n\n # If the face has two adjacend volumes\n if len(adj) == 2:\n # Check if those volumes do not have any faces with boundary\n # conditions of type Dirichlet\n for dim in range(0, cls.entity_dim+1):\n adj0_faces_physical = cls.get_adj_physical(\n m, adj[0], dim, dim, phys_type=[Dirichlet])\n # Uses the first Dirichlet condition found\n if adj0_faces_physical:\n break\n\n for dim in range(0, cls.entity_dim+1):\n adj1_faces_physical = cls.get_adj_physical(\n m, adj[1], dim, dim, phys_type=[Dirichlet])\n # Uses the first Dirichlet condition found\n if adj1_faces_physical:\n break\n\n if not adj0_faces_physical:\n results['set'].append((adj[0], [adj[1]], [-K_equiv]))\n results['sum'].append((adj[0], [adj[0]], [K_equiv]))\n\n if not adj1_faces_physical:\n results['set'].append((adj[1], [adj[0]], [-K_equiv]))\n results['sum'].append((adj[1], [adj[1]], [K_equiv]))\n\n cls.fill_array(m, results)\n","sub_path":"examples/CVFD_Example/CVFD/Kernel.py","file_name":"Kernel.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"323641823","text":"\"\"\"Contains the base class for the simulation.\"\"\"\nimport numpy as np\nfrom tqdm import auto as tqdm\nimport numba\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport pandas\nimport seaborn\nfrom . import analysis\nimport zarr\nimport datetime\n\nclass Simulation:\n \"\"\"Base class for SOC simulations.\"\"\"\n values = NotImplemented\n saved_snapshots = NotImplemented\n\n BOUNDARY_SIZE = BC = 1\n def __init__(self, L: int, save_every: int = 1, wait_for_n_iters: int = 10):\n \"\"\"__init__\n\n :param L: linear size of lattice, without boundary layers\n :type L: int\n :param save_every: number of iterations per snapshot save\n :type save_every: int or None\n \"\"\"\n self.L = L\n self.visited = np.zeros((self.L_with_boundary, self.L_with_boundary), dtype=bool)\n self.data_acquisition = []\n self.save_every = save_every\n self.wait_for_n_iters = wait_for_n_iters\n # zliczanie relaksacji\n self.releases = np.zeros((self.L_with_boundary, self.L_with_boundary), dtype=int)\n\n @property\n def size(self):\n return self.L**2\n\n @property\n def L_with_boundary(self):\n return self.L + 2 * self.BOUNDARY_SIZE\n\n def drive(self):\n \"\"\"\n Drive the simulation by adding particles from the outside.\n\n Must be overriden in subclasses.\n \"\"\"\n raise NotImplementedError(\"Your model needs to override the drive method!\")\n\n def topple_dissipate(self):\n \"\"\"\n Distribute material from overloaded sites to neighbors.\n\n Must be overriden in subclasses.\n \"\"\"\n raise NotImplementedError(\"Your model needs to override the topple method!\")\n\n @classmethod\n def clean_boundary_inplace(cls, array: np.ndarray) -> np.ndarray:\n \"\"\"\n Convenience wrapper to `clean_boundary_inplace` with the simulation's boundary size. \n\n :param array:\n :type array: np.ndarray\n :rtype: np.ndarray\n \"\"\"\n return clean_boundary_inplace(array, self.BOUNDARY_SIZE)\n\n def AvalancheLoop(self) -> dict:\n \"\"\"\n Bring the current simulation's state to equilibrium by repeatedly\n toppling and dissipating.\n\n Returns a dictionary with the total size of the avalanche\n and the number of iterations the avalanche took.\n\n :rtype: dict\n \"\"\"\n self.visited[...] = False\n self.releases[...] = 0\n number_of_iterations = self.topple_dissipate()\n \n AvalancheSize = self.visited.sum()\n NumberOfReleases = self.releases.sum()\n return dict(AvalancheSize=AvalancheSize, NumberOfReleases=NumberOfReleases, number_of_iterations=number_of_iterations)\n\n def run(self, N_iterations: int,\n filename: str = None,\n wait_for_n_iters: int = 10,\n ) -> dict:\n\n \"\"\"\n Simulation loop. Drives the simulation, possibly starts avalanches, gathers data.\n\n :param N_iterations: number of iterations (per grid node if `scale` is True)\n :type N_iterations: int\n :rtype: dict\n :param filename: filename for saving snapshots. if None, saves to memory; by default if False, makes something like array_Manna_2019-12-17T19:40:00.546426.zarr\n :type filename: str\n :param wait_for_n_iters: wait this many iterations before collecting data\n (lets model thermalize)\n :type wait_for_n_iters: int\n \"\"\"\n if filename is False:\n filename = f\"array_{self.__class__.__name__}_{datetime.datetime.now().isoformat()}.zarr\"\n scaled_wait_for_n_iters = wait_for_n_iters\n scaled_n_iterations = N_iterations + scaled_wait_for_n_iters\n if scaled_n_iterations % self.save_every != 0:\n raise ValueError(f\"Ensure save_every ({self.save_every}) is a divisor of the total number of iterations ({scaled_n_iterations})\")\n print(f\"Waiting for wait_for_n_iters={wait_for_n_iters} iterations before collecting data. This should let the system thermalize.\")\n\n total_snapshots = max([scaled_n_iterations // self.save_every, 1])\n self.saved_snapshots = zarr.open(filename,\n shape=(\n total_snapshots, # czas\n self.L_with_boundary, # x\n self.L_with_boundary, # y\n ),\n chunks=(\n 100,\n self.L_with_boundary,\n self.L_with_boundary,\n ),\n dtype=self.values.dtype,\n )\n self.saved_snapshots.attrs['save_every'] = self.save_every\n\n for i in tqdm.trange(scaled_n_iterations):\n self.drive()\n observables = self.AvalancheLoop()\n if i >= scaled_wait_for_n_iters:\n self.data_acquisition.append(observables)\n if self.save_every is not None and (i % self.save_every) == 0:\n self._save_snapshot(i)\n return filename\n\n def _save_snapshot(self, i):\n self.saved_snapshots[i // self.save_every] = self.values\n\n @property\n def data_df(self):\n return pandas.DataFrame(self.data_acquisition)\n\n def plot_histogram(self, column='AvalancheSize', num=50, filename = None, plot = True):\n return analysis.plot_histogram(self.data_df, column, num, filename, plot)\n\n def plot_state(self, with_boundaries = False):\n \"\"\"\n Plots the current state of the simulation.\n \"\"\"\n fig, ax = plt.subplots()\n\n if with_boundaries:\n values = self.values\n else:\n values = self.values[self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE]\n \n IM = ax.imshow(values, interpolation='nearest')\n \n plt.colorbar(IM)\n return fig\n\n def animate_states(self, notebook: bool = False, with_boundaries: bool = False,\n interval = 30,\n ):\n \"\"\"\n Animates the collected states of the simulation.\n\n :param notebook: if True, displays via html5 video in a notebook;\n otherwise returns MPL animation\n :type notebook: bool\n :param with_boundaries: include boundaries in the animation?\n :type with_boundaries: bool\n \"\"\"\n fig, ax = plt.subplots()\n\n if with_boundaries:\n values = np.dstack(self.saved_snapshots)\n else:\n values = np.dstack(self.saved_snapshots)[self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, self.BOUNDARY_SIZE:-self.BOUNDARY_SIZE, :]\n\n IM = ax.imshow(values[:, :, 0],\n interpolation='nearest',\n vmin = values.min(),\n vmax = values.max()\n )\n \n plt.colorbar(IM)\n iterations = values.shape[2]\n title = ax.set_title(\"Iteration {}/{}\".format(0, iterations * self.save_every))\n\n def animate(i):\n IM.set_data(values[:,:,i])\n title.set_text(\"Iteration {}/{}\".format(i * self.save_every, iterations * self.save_every))\n return IM, title\n\n anim = animation.FuncAnimation(fig,\n animate,\n frames=iterations,\n interval=interval,\n )\n if notebook:\n from IPython.display import HTML, display\n plt.close(anim._fig)\n display(HTML(anim.to_html5_video()))\n else:\n return anim\n \n def get_exponent(self, *args, **kwargs):\n return analysis.get_exponent(self.data_df, *args, **kwargs)\n\n @classmethod\n def from_file(cls, filename):\n saved_snapshots = zarr.open(filename)\n save_every = saved_snapshots.attrs['save_every']\n L = saved_snapshots.shape[1] - 2 * cls.BOUNDARY_SIZE\n self = cls(L=L, save_every=save_every)\n self.values = saved_snapshots[-1]\n self.saved_snapshots = saved_snapshots\n return self\n \n@numba.njit\ndef clean_boundary_inplace(array: np.ndarray, boundary_size: int, fill_value = False) -> np.ndarray:\n \"\"\"\n Fill `array` at the boundary with `fill_value`.\n\n Useful to make sure sites on the borders do not become active and don't start toppling.\n\n Works inplace - will modify the existing array!\n\n :param array:\n :type array: np.ndarray\n :param boundary_size:\n :type boundary_size: int\n :param fill_value:\n :rtype: np.ndarray\n \"\"\"\n array[:boundary_size, :] = fill_value\n array[-boundary_size:, :] = fill_value\n array[:, :boundary_size] = fill_value\n array[:, -boundary_size:] = fill_value\n return array\n\n","sub_path":"SOC/common/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":9150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"547898076","text":"import gdspy\nimport numpy as np\n\nfrom spira import param\nfrom copy import copy, deepcopy\n\nfrom spira.gdsii.utils import *\nfrom spira.core.initializer import ElementalInitializer\nfrom spira.core.mixin.transform import TranformationMixin\nfrom spira.core.mixin.property import PolygonMixin\n\n\nclass __Polygon__(gdspy.PolygonSet, ElementalInitializer):\n\n __mixins__ = [TranformationMixin, PolygonMixin]\n\n __committed__ = {}\n\n def __eq__(self, other):\n return self.id == other.id\n\n def __hash__(self):\n return hash(self.id)\n\n def __deepcopy__(self, memo):\n ply = self.modified_copy(\n shape=deepcopy(self.shape),\n gdslayer=deepcopy(self.gdslayer),\n gdspy_commit=deepcopy(self.gdspy_commit))\n return ply\n\n def __add__(self, other):\n polygons = []\n assert isinstance(other, Polygons)\n if self.gdslayer == other.gdslayer:\n for points in self.shape.points:\n polygons.append(np.array(points))\n for points in other.polygons:\n polygons.append(np.array(points))\n self.shape.points = polygons\n else:\n raise ValueError(\"To add masks the polygon layers \\\n must be the same.\")\n return self\n\n def __sub__(self, other):\n pp = bool_operation(subj=self.shape.points,\n clip=other.shape.points,\n method='difference')\n if len(pp) > 0:\n return Polygons(shape=pp, gdslayer=self.gdslayer)\n else:\n return None\n\n def __and__(self, other):\n pp = bool_operation(subj=other.shape.points,\n clip=self.shape.points,\n method='intersection')\n if len(pp) > 0:\n return Polygons(shape=pp, gdslayer=self.gdslayer)\n else:\n return None\n\n def __or__(self, other):\n pp = bool_operation(subj=other.shape.points,\n clip=self.shape.points,\n method='union')\n\n if len(pp) > 0:\n return Polygons(shape=pp, gdslayer=self.gdslayer)\n else:\n return None\n\n\nclass PolygonAbstract(__Polygon__):\n\n gdslayer = param.LayerField()\n gdspy_commit = param.BoolField()\n clockwise = param.BoolField(default=True)\n\n nodes = param.DataField(fdef_name='create_nodes')\n edges = param.DataField(fdef_name='create_edges')\n\n def __init__(self, shape, **kwargs):\n from spira.lgm.shapes.shape import __Shape__\n from spira.lgm.shapes.shape import Shape\n\n if issubclass(type(shape), __Shape__):\n self.shape = shape\n elif isinstance(shape, (list, set, np.ndarray)):\n self.shape = Shape(points=shape)\n else:\n raise ValueError('Shape type not supported!')\n\n ElementalInitializer.__init__(self, **kwargs)\n gdspy.PolygonSet.__init__(self,\n self.shape.points,\n layer=self.gdslayer.number,\n datatype=self.gdslayer.datatype,\n verbose=False)\n\n def create_nodes(self):\n \"\"\" Created nodes of each point in the polygon array.\n Converting a point to a node allows us to bind\n other objects to that specific node or point. \"\"\"\n pass\n\n def create_edges(self):\n \"\"\" A list of tuples containing two nodes. \"\"\"\n pass\n\n def move_edge(self):\n pass\n\n def commit_to_gdspy(self, cell):\n if self.__repr__() not in list(PolygonAbstract.__committed__.keys()):\n ply = deepcopy(self.shape.points)\n P = gdspy.PolygonSet(ply, self.gdslayer.number, self.gdslayer.datatype)\n cell.add(P)\n PolygonAbstract.__committed__.update({self.__repr__():P})\n else:\n cell.add(PolygonAbstract.__committed__[self.__repr__()])\n\n def flat_copy(self, level=-1, commit_to_gdspy=False):\n elems = []\n for points in self.shape.points:\n c_poly = self.modified_copy(shape=deepcopy([points]),\n gdspy_commit=self.gdspy_commit)\n elems.append(c_poly)\n if commit_to_gdspy:\n self.gdspy_commit = True\n return elems\n\n def merge(self, other):\n if isinstance(other, (list, set)):\n pass\n elif isinstance(other, Polygons):\n pass\n else:\n raise ValueError('Type is not supported for Polygon merging.')\n\n def transform(self, transform):\n if transform['reflection']:\n self.reflect(p1=[0,0], p2=[1,0])\n if transform['rotation']:\n self.rotate(angle=transform['rotation'])\n if transform['midpoint']:\n self.translate(dx=transform['midpoint'][0], dy=transform['midpoint'][1])\n self.shape.points = self.polygons\n return self\n\n def reflect(self, p1=(0,1), p2=(0,0)):\n for n, points in enumerate(self.shape.points):\n self.shape.points[n] = self.__reflect__(points, p1, p2)\n self.shape.points = self.polygons\n return self\n\n def rotate(self, angle=45, center=(0,0)):\n super().rotate(angle=angle*np.pi/180, center=center)\n self.shape.points = self.polygons\n return self\n\n def translate(self, dx, dy):\n super().translate(dx=dx, dy=dy)\n self.shape.points = self.polygons\n return self\n\n def stretch(self, stretch_class):\n p = stretch_class.apply_to_polygon(self.points[0])\n self.shape.points = [np.array(p)]\n return self\n\n def move(self, midpoint=(0,0), destination=None, axis=None):\n from spira.gdsii.elemental.port import __Port__\n \"\"\" Moves elements of the Device from the midpoint point to the destination. Both\n midpoint and destination can be 1x2 array-like, Port, or a key\n corresponding to one of the Ports in this device \"\"\"\n\n if destination is None:\n destination = midpoint\n midpoint = [0,0]\n\n if issubclass(type(midpoint), __Port__):\n o = midpoint.midpoint\n elif np.array(midpoint).size == 2:\n o = midpoint\n elif midpoint in self.ports:\n o = self.ports[midpoint].midpoint\n else:\n raise ValueError(\"[PHIDL] [DeviceReference.move()] ``midpoint`` \" +\n \"not array-like, a port, or port name\")\n\n if issubclass(type(destination), __Port__):\n d = destination.midpoint\n elif np.array(destination).size == 2:\n d = destination\n elif destination in self.ports:\n d = self.ports[destination].midpoint\n else:\n raise ValueError(\"[PHIDL] [DeviceReference.move()] ``destination`` \" +\n \"not array-like, a port, or port name\")\n\n if axis == 'x':\n d = (d[0], o[1])\n if axis == 'y':\n d = (o[0], d[1])\n\n dx, dy = np.array(d) - o\n\n self.translate(dx, dy)\n\n return self\n\n def fast_boolean(self, other, operation):\n mm = gdspy.fast_boolean(\n self.shape.points,\n other.shape.points,\n operation=operation\n )\n return Polygons(shape=mm.points, gdslayer=self.gdslayer)\n\n\nclass Polygons(PolygonAbstract):\n \"\"\" Elemental that connects shapes to the GDSII file format.\n Polygons are objects that represents the shapes in a layout.\n\n Examples\n --------\n >>> layer = spira.Layer(number=99)\n >>> rect_shape = spira.RectangleShape(p1=[0,0], p2=[1,1])\n >>> ply = spira.Polygons(shape=rect_shape, gdslayer=layer)\n \"\"\"\n\n def __init__(self, shape, **kwargs):\n super().__init__(shape, **kwargs)\n\n def __repr__(self):\n if self is None:\n return 'Polygon is None!'\n # return (\"[SPiRA: Polygon] (\" +\n # \"{} vertices, layer {}, datatype {})\").format(\n # sum([len(p) for p in self.shape.points]),\n # self.gdslayer.number, self.gdslayer.datatype)\n return (\"[SPiRA: Polygon] ({} center, \" +\n \"{} vertices, layer {}, datatype {})\").format(\n self.center, sum([len(p) for p in self.shape.points]),\n self.gdslayer.number, self.gdslayer.datatype)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"spira/gdsii/elemental/polygons.py","file_name":"polygons.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"459297189","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.books),\n path('add_book', views.add_books),\n path('book/', views.book_profile),\n path('add_author_to_book/book/add_author', views.add_author_to_book),\n path('authors', views.authors),\n path('add_author', views.add_author),\n path('author/', views.author_profile),\n path('add_book_to_author/author/add_book', views.add_book_to_author)\n]\n","sub_path":"Django/books_authors_proj/books_authors_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"104455957","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# The MIT License (MIT)\n\n# Copyright (c) 2017-2020 CNRS\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# AUTHORS\n# Hervé BREDIN - http://herve.niderb.fr\n\n\nfrom ._version import get_versions\n\n__version__ = get_versions()[\"version\"]\ndel get_versions\n\nimport pandas as pd\nfrom pathlib import Path\nfrom pyannote.core import Segment, Timeline, Annotation\nfrom pyannote.database import Database\nfrom pyannote.database.protocol import SpeakerVerificationProtocol\n\n\nclass CNCeleb2(SpeakerVerificationProtocol):\n def train_iter(self):\n\n path = Path(__file__).parent / \"data\"\n path = path / f\"cnceleb2_duration.txt.gz\"\n content = pd.read_table(\n path, names=[\"uri\", \"duration\"], index_col=\"uri\", delim_whitespace=True\n )\n\n for uri, duration in content.itertuples():\n\n speaker = uri.split(\"/\")[0]\n speaker = f\"CNCeleb_{speaker}\"\n\n segment = Segment(0, duration)\n\n annotation = Annotation(uri=uri)\n annotation[segment] = speaker\n\n annotated = Timeline(segments=[segment], uri=uri)\n\n yield {\n \"uri\": uri,\n \"database\": \"CNCeleb\",\n \"annotation\": annotation,\n \"annotated\": annotated,\n }\n\n def development_iter(self):\n raise NotImplementedError(\"This protocol does not define a development set.\")\n\n def development_trial_iter(self):\n raise NotImplementedError(\n \"This protocol does not define trials on the development set.\"\n )\n\n def test_iter(self):\n raise NotImplementedError(\"This protocol does not define a test set.\")\n\n def test_trial_iter(self):\n raise NotImplementedError(\n \"This protocol does not define trials on the test set.\"\n )\n\n\nclass CNCeleb(Database):\n \"\"\"CNCeleb\n\n References\n ----------\n CN-CELEB: a challenging Chinese speaker recognition dataset},\n Fan, Yue and Kang, JW and Li, LT and Li, KC and Chen, HL and Cheng, ST and Zhang, PY and Zhou, ZY and Cai, YQ and Wang, Dong\n 2020 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)\n \"\"\"\n\n def __init__(self, **kwargs):\n super(CNCeleb, self).__init__(**kwargs)\n self.register_protocol(\"SpeakerVerification\", \"CNCeleb\", CNCeleb2)\n\n\nfrom . import _version\n\n__version__ = _version.get_versions()[\"version\"]\n\n","sub_path":"CNCeleb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"403682216","text":"#!/usr/bin/env python3\n\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\n\n# Defaults:\nGECKO = '/mnt/d/projects/open-realestate/drivers/geckodriver.exe'\nURL = 'http://maps2.roktech.net/durhamnc_gomaps4/'\n\n# Options:\noptions = Options()\noptions.add_argument('--headless')\n\n# Create driver.\ndriver = webdriver.Firefox(executable_path = GECKO, options = options)\n\n# Get webpage.\ndriver.get(URL)\n","sub_path":"ARCHIVE/launch_gecko.py","file_name":"launch_gecko.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"54514959","text":"import pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom decimal import Decimal\nimport torch\nfrom ase.units import fs, kB\nimport ignite\nimport torchfes as fes\nimport pnpot\nimport pointneighbor as pn\n\ntorch.set_default_dtype(torch.float64)\n\nn_ring = 16\nhbar = 1.0\nk = 1.0\nkbt = 0.1\nbeta = 10.0\n\n\ndef make_inp():\n n_atm = 1\n n_bch = n_ring\n n_dim = 1\n cel = torch.eye(n_dim)[None, :, :].expand((n_bch, n_dim, n_dim)) * 1000\n pos = torch.rand([n_bch, n_atm, n_dim])\n pbc = torch.zeros([n_bch, n_dim], dtype=torch.bool)\n elm = torch.ones([n_bch, n_atm])\n mas = torch.ones([n_bch, n_atm])\n inp = fes.mol.init_mol(cel, pbc, elm, pos, mas)\n inp = fes.mol.add_nvt(inp, 0.01, 0.1)\n inp = fes.mol.add_global_langevin(inp, 0.7)\n return inp\n\n\ndef make_inp_or_continue(path):\n if path.is_file():\n with fes.rec.open_torch(path, 'rb') as f:\n mol = f[-1]\n mode = 'ab'\n else:\n mol = make_inp()\n mode = 'wb'\n return mol, mode\n\n\ndef main():\n trj_path = Path('md')\n mol, mode = make_inp_or_continue(trj_path)\n mol[fes.p.dtm] = mol[fes.p.dtm].mean(dim=0, keepdim=True)\n mdl = pnpot.classical.Quadratic(torch.tensor([k]))\n adj = fes.adj.SetAdjSftSpcVecSod(\n pn.Coo2FulSimple(1.0), [(fes.p.coo, 1.0)]\n )\n evl = fes.ff.get_adj_eng_frc(adj, mdl)\n mom = fes.md.UpdtMom(0.5)\n base = fes.md.rpmd_base(hbar, beta, n_ring, 'cpu')\n pos = fes.md.RpmdPos(base, mol[fes.p.mas], mol[fes.p.dtm].item(), 1)\n lan = fes.md.RpmdLangevin(\n base, 0.7, mol[fes.p.dtm].item() * 0.5, mol[fes.p.mas], 1)\n kin = fes.md.RpmdKin(base)\n # mol[fes.p.mom][:, 0, 0] = torch.tensor([-0.39253548, -0.23131893, -0.39253548, -0.23131893])\n mol = evl(mol)\n pos_lst = []\n pot_lst = []\n kin_lst = []\n mol[fes.p.mom][:, 0, 0] = torch.ones(n_ring)\n mol[fes.p.pos][:, 0, 0] = torch.zeros(n_ring)\n for i in range(40000):\n mol = lan(mol)\n # print(mol[fes.p.mom].flatten())\n mol = mom(mol)\n mol = pos(mol)\n mol = evl(mol)\n mol = kin(mol)\n mol = mom(mol)\n mol = lan(mol)\n # print(mol[fes.p.mom].flatten())\n # print(mol[fes.p.pos].flatten())\n pos_lst.append(mol[fes.p.pos][:, 0, 0])\n pot_lst.append(mol[fes.p.eng][:])\n kin_lst.append(mol[fes.p.rpm_kin])\n print(i)\n with open('tmp.pkl', 'wb') as f:\n pickle.dump([pos_lst, pot_lst, kin_lst], f)\n\n\ndef gound(x, hbar, m, k):\n omega = torch.sqrt(k / m)\n xi = torch.sqrt(m * omega / hbar) * x\n return torch.exp(-0.5 * xi * xi)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"example/rpmd/md.py","file_name":"md.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"187923015","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 2 12:29:59 2018\r\n\r\n@author: Shrikant\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport random\r\n\r\nimg_ball = cv2.imread(\"football.jpg\",0)\r\nimg_player = cv2.imread(\"player.jpg\",0)\r\ncv2.imshow(\"football\",img_ball)\r\ncv2.imshow(\"player\",img_player)\r\n\r\n\r\nresult = cv2.matchTemplate(img_ball,img_player,cv2.TM_CCOEFF_NORMED)\r\nmin_val,max_val,min_loc,max_loc=cv2.minMax(result)\r\nprint(max_val.max_loc)\r\ncv2.circle(result,max_loc,15,255,2)\r\ncv2.imshow(\"Matching\",result)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"template matching.py","file_name":"template matching.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"310064571","text":"'''\nGiven a number of integers, combine them so it would create the largest number.\n\nExample:\n\nInput: [17, 7, 2, 45, 72]\nOutput: 77245217\n'''\nfrom functools import cmp_to_key\n\ndef cmpr(x, y):\n x, y = str(x), str(y)\n if x[0] == y[0]:\n while len(x) > len(y):\n y += y[0]\n \n while len(x) < len(y):\n x += x[0]\n \n return 1 if x > y else -1\n\ndef largestNum(nums):\n nums.sort(key = cmp_to_key(cmpr), reverse = True)\n return ''.join(map(str, nums))\n \nif __name__ == '__main__':\n print(largestNum([17, 7, 2, 45, 72]))\n","sub_path":"other/make_largest_number.py","file_name":"make_largest_number.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"608659704","text":"import inspect\nimport sys\nfrom contextlib import contextmanager\nfrom functools import wraps, partial\nfrom types import MethodType\nimport warnings\nfrom threading import RLock\n\nfrom easypy.collections import intersected_dict\n\n\ndef deprecated(func=None, message=None):\n if not callable(func):\n return partial(deprecated, message=func)\n message = (\" \"+message) if message else \"\"\n message = \"Hey! '%s' is deprecated!%s\" % (func.__name__, message)\n\n @wraps(func)\n def inner(*args, **kwargs):\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n return func(*args, **kwargs)\n return inner\n\n\ndef parametrizeable_decorator(deco):\n @wraps(deco)\n def inner(func=None, **kwargs):\n if func is None:\n return partial(deco, **kwargs)\n else:\n return wraps(func)(deco(func, **kwargs))\n return inner\n\n\ndef singleton_contextmanager(func):\n class CtxManager():\n def __init__(self, func):\n self.count = 0\n self.func_cm = contextmanager(func)\n self._lock = RLock()\n\n def __enter__(self):\n with self._lock:\n if self.count == 0:\n self.ctm = self.func_cm()\n self.obj = self.ctm.__enter__()\n self.count += 1\n\n def __exit__(self, *args):\n with self._lock:\n self.count -= 1\n if self.count > 0:\n return\n self.ctm.__exit__(*sys.exc_info())\n del self.ctm\n del self.obj\n\n return CtxManager(func)\n\n\n_singleton_contextmanager_method_attr_lock = RLock()\n\n\ndef singleton_contextmanager_method(func):\n cached_attr_name = '__singleton_contextmanager_method__' + func.__name__\n\n # Wrap with a context manager to get proper IPython documentation\n @contextmanager\n @wraps(func)\n def inner(self):\n with _singleton_contextmanager_method_attr_lock:\n try:\n cm = getattr(self, cached_attr_name)\n except AttributeError:\n cm = singleton_contextmanager(partial(func, self))\n setattr(self, cached_attr_name, cm)\n with cm as val:\n yield val\n\n return inner\n\n\ndef kwargs_resilient(func):\n spec = inspect.getfullargspec(getattr(func, '__wrapped__', func))\n acceptable_args = set(spec.args or ())\n if isinstance(func, MethodType):\n acceptable_args -= {spec.args[0]}\n\n def inner(*args, **kwargs):\n if spec.varkw is None:\n # if function does not get **kwargs, pass only params which it can accept\n kwargs = intersected_dict(kwargs, acceptable_args)\n return func(*args, **kwargs)\n\n return inner\n\n\ndef reusable_contextmanager(context_manager):\n if not hasattr(context_manager, '_recreate_cm'):\n return context_manager # context manager is already reusable (was not created usin yield funcion\n\n class ReusableCtx:\n def __enter__(self):\n self.cm = context_manager._recreate_cm()\n return self.cm.__enter__()\n\n def __exit__(self, *args):\n self.cm.__exit__(*args)\n\n return ReusableCtx()\n\n\ndef as_list(generator):\n @wraps(generator)\n def inner(*args, **kwargs):\n return list(generator(*args, **kwargs))\n return inner\n","sub_path":"easypy/decorations.py","file_name":"decorations.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"76291734","text":"from django.views.generic.list import ListView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\nfrom core.views import VerificaVigenciaUsuario\nfrom aplicaciones.models import Aplicacion\nfrom proyectos.models import Proyecto\nfrom .forms import AplicacionForm\nfrom registration.views import VerificaVigenciaUsuario, PropietarioProyecto\n\nclass AplicacionListaView(ListView):\n model = Aplicacion\n\nclass EditarAplicacionView(UpdateView):\n model = Aplicacion\n form_class = AplicacionForm\n template_name_suffix = '_update_form'\n\n def get_success_url(self):\n return reverse_lazy('aplicaciones:editar', args=[self.object.id]) + '?ok'\n\n def get_context_data(self,**kwargs):\n context = super(EditarAplicacionView, self).get_context_data(**kwargs)\n context['vigente'] = VerificaVigenciaUsuario(self.request.user)\n try:\n context['error'] = ''\n proyecto = Proyecto.objects.get(id=self.object.proyecto.id,usuario=self.request.user)\n # modelos = Modelo.objects.filter(aplicacion = self.object)\n context['proyecto'] = proyecto\n context['nombre'] = self.object.nombre\n # context['listamodelo'] = modelos\n context['proyecto_id'] = self.object.proyecto.id\n context['aplicacion'] = self.object\n # context['mensaje_error'] = self.request.GET['mensaje_error']\n # context['numero'] = Modelo.objects.filter(aplicacion=self.object).count()\n # verifica si tiene vigencia de uso\n # context['vigente'] = VerificaVigenciaUsuario(self.request.user)\n except:\n context['error'] = '!!! No eres el propietario del proyecto !!!'\n return context\n\n def post(self,request,*args,**kwargs):\n self.object = self.get_object()\n form = self.get_form()\n aplicacion = form.save(commit=False)\n mensaje_error=''\n proyecto = Proyecto.objects.get(id=self.request.GET['proyecto_id'])\n # Validar que el modelo sea unico\n nombre_antiguo = Aplicacion.objects.get(id=self.request.GET['aplicacion_id'], proyecto=proyecto).nombre\n if nombre_antiguo != aplicacion.nombre:\n if Aplicacion.objects.filter(nombre=aplicacion.nombre,proyecto=proyecto).count() == 0:\n aplicacion.save()\n return HttpResponseRedirect(self.get_success_url())\n else:\n mensaje_error = 'La Aplicacion ' + aplicacion.nombre + ' ya existe en el proyecto, intente con otro nombre'\n return HttpResponseRedirect('/aplicaciones/editar/' + str(aplicacion.id) + '/?proyecto_id=' + str(proyecto.id) + '&aplicacion_id=' + str(aplicacion.id) + '&mensaje_error=' + mensaje_error) \n else:\n aplicacion.save()\n return HttpResponseRedirect(self.get_success_url())\n\n # return render(request, 'modelos/modelo_update_form.html', {'form': form,'mensaje_error':mensaje_error})\n\n\nfrom django.http import HttpResponseRedirect\n\nclass CrearAplicacionView(CreateView):\n model = Aplicacion\n form_class = AplicacionForm\n\n def get_success_url(self):\n return reverse_lazy('proyectos:arbol') + '?proyecto_id=' + self.request.GET['proyecto_id']\n\n def get_context_data(self,**kwargs):\n context = super(CrearAplicacionView, self).get_context_data(**kwargs)\n context['vigente'] = VerificaVigenciaUsuario(self.request.user)\n try:\n context['error'] = ''\n proyecto = Proyecto.objects.get(id=self.request.GET['proyecto_id'],usuario=self.request.user)\n context['proyecto'] = proyecto\n # context['mensaje_error'] = self.request.GET['mensaje_error']\n # verifica si tiene vigencia de uso\n # context['vigente'] = VerificaVigenciaUsuario(self.request.user)\n except:\n context['error'] = '!!! No eres el propietario del proyecto !!!'\n return context\n\n def post(self,request,*args,**kwargs):\n mensaje_error=''\n form = self.form_class(request.POST)\n proyecto = Proyecto.objects.get(id = request.GET['proyecto_id'])\n if form.is_valid():\n aplicacion = form.save(commit=False)\n aplicacion.proyecto = proyecto\n # Validar que el modelo sea unico\n\n if Aplicacion.objects.filter(nombre=aplicacion.nombre,proyecto=aplicacion.proyecto).count() == 0:\n aplicacion.save()\n return HttpResponseRedirect(self.get_success_url())\n else:\n mensaje_error = 'La Aplicacion ' + aplicacion.nombre + ' ya existe en el proyecto, intente con otro nombre'\n return HttpResponseRedirect('/aplicaciones/crear' + '/?proyecto_id=' + str(proyecto.id) + '&mensaje_error=' + mensaje_error) \n # aplicacion.save()\n # return HttpResponseRedirect(self.get_success_url())\n return HttpResponseRedirect('/aplicaciones/crear' + '/?proyecto_id=' + str(proyecto.id)) \n # return render(request, 'aplicaciones/aplicacion_form.html', {'form': form})\n\nclass BorrarAplicacionView(DeleteView):\n model = Aplicacion\n\n def get_success_url(self):\n return reverse_lazy('proyectos:arbol') + '?proyecto_id=' + self.request.GET['proyecto_id']\n\n def get_context_data(self,**kwargs):\n context = super(BorrarAplicacionView, self).get_context_data(**kwargs)\n context['vigente'] = VerificaVigenciaUsuario(self.request.user)\n try:\n context['error'] = ''\n # proyecto = Proyecto.objects.get(id=self.object.proyecto.id,usuario=self.request.user)\n obj = Aplicacion.objects.get(id=self.object.id)\n context['nombre'] = obj.nombre\n context['proyecto_id'] = obj.proyecto.id\n except:\n context['error'] = '!!! No eres el propietario del proyecto !!!'\n return context\n\n ","sub_path":"genesis/aplicaciones/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"532601457","text":"import datetime, json\nimport numpy as np\nimport torch\nfrom transformers import BertTokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport os\nimport logging\nfrom tabulate import tabulate # https://pypi.org/project/tabulate/\n\n\ndef get_bool_value(str_bool):\n if str_bool.upper() == \"TRUE\" or str_bool.upper() == \"T\":\n return True\n else:\n return False\n\n\ndef get_torch_device(verbose=True):\n use_cuda = False\n if torch.cuda.is_available():\n # Tell PyTorch to use the GPU.\n device = torch.device(\"cuda\")\n use_cuda = True\n if verbose:\n print('There are %d GPU(s) available.' % torch.cuda.device_count())\n print('We will use the GPU:', torch.cuda.get_device_name(0))\n else:\n if verbose: print('No GPU available, using the CPU instead.')\n device = torch.device(\"cpu\")\n return device, use_cuda\n\n\ndevice, USE_CUDA = get_torch_device(verbose=False)\nLongTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor\n\n\ndef build_label_vocab(list_of_labels):\n label2index = {\"[PAD]\": 0, \"[UNK]\": 1}\n for i, labelset in enumerate(list_of_labels):\n for l in labelset:\n if l not in label2index:\n label2index[l] = len(label2index)\n return label2index\n\n\ndef expand_to_wordpieces(original_sentence, original_labels, tokenizer):\n \"\"\"\n Also Expands BIO, but assigns the original label ONLY to the Head of the WordPiece (First WP)\n :param original_sentence: List of Full-Words\n :param original_labels: List of Labels corresponding to each Full-Word\n :param tokenizer: To convert it into BERT-model WordPieces\n :return:\n \"\"\"\n\n txt_sentence = \" \".join(original_sentence)\n\n txt_sentence = txt_sentence.replace(\"#\", \"N\")\n word_pieces = tokenizer.tokenize(txt_sentence)\n\n tmp_labels, lbl_ix = [], 0\n head_tokens = [1] * len(word_pieces)\n for i, tok in enumerate(word_pieces):\n if \"##\" in tok:\n tmp_labels.append(\"X\")\n head_tokens[i] = 0\n else:\n tmp_labels.append(original_labels[lbl_ix])\n lbl_ix += 1\n\n word_pieces = [\"[CLS]\"] + word_pieces + [\"[SEP]\"]\n labels = [\"O\"] + tmp_labels + [\"O\"]\n head_tokens = [0] + head_tokens + [0]\n return word_pieces, labels, head_tokens\n\n\ndef get_data(filepath, tokenizer, include_labels):\n sentences, verb_indicators, all_labels = [], [], []\n with open(filepath) as f:\n for i, line in enumerate(f.readlines()):\n obj = json.loads(line)\n # Get WordPiece Indices\n wordpieces, labelset, head_toks = expand_to_wordpieces(obj[\"seq_words\"], obj[\"BIO\"], tokenizer)\n # print(wordpieces)\n # print(labelset)\n # print(\"------------\")\n input_ids = tokenizer.convert_tokens_to_ids(wordpieces)\n sentences.append(input_ids)\n # Verb Indicator (which predicate to label)\n bio_verb = [1 if label[-2:] == \"-V\" else 0 for label in labelset]\n verb_indicators.append(bio_verb)\n # Get Gold Labels (For training or for evaluation)\n if include_labels:\n all_labels.append(labelset)\n\n return sentences, verb_indicators, all_labels\n\n\ndef load_srl_dataset(filepath, tokenizer, max_len, include_labels, label2index):\n sentences, verb_indicators, labels = get_data(filepath, tokenizer, include_labels)\n seq_lengths = [len(s) for s in sentences]\n logging.info(f\"MAX SEQ LENGTH IN DATASET IS {max(seq_lengths)}\")\n # BUILD VOCABULARY IF NECESSARY\n label_ixs = []\n if not label2index: label2index = build_label_vocab(labels)\n # CONVERT LABELS TO THEIR INDICES\n for i, labelset in enumerate(labels):\n label_ixs.append([label2index.get(l, 1) for l in labelset])\n # PAD ALL SEQUENCES\n input_ids = pad_sequences(sentences, maxlen=max_len, dtype=\"long\", value=0, truncating=\"post\", padding=\"post\")\n input_is_pred = pad_sequences(verb_indicators, maxlen=max_len, dtype=\"long\", value=0, truncating=\"post\", padding=\"post\")\n if include_labels:\n label_ids = pad_sequences(label_ixs, maxlen=max_len, dtype=\"long\", value=0, truncating=\"post\", padding=\"post\")\n label_ids = LongTensor(label_ids)\n else:\n label_ids = None\n # Create attention masks\n attention_masks = []\n # For each sentence...\n for i, sent in enumerate(input_ids):\n # Create the attention mask.\n # - If a token ID is 0, then it's padding, set the mask to 0.\n # - If a token ID is > 0, then it's a real token, set the mask to 1.\n att_mask = [int(token_id > 0) for token_id in sent]\n # Store the attention mask for this sentence.\n attention_masks.append(att_mask)\n return label2index, LongTensor(input_ids), LongTensor(attention_masks), label_ids, LongTensor(seq_lengths), LongTensor(input_is_pred)\n\n\ndef get_metrics(false_pos, false_neg, true_pos):\n _denom1 = true_pos + false_pos\n precision = true_pos / _denom1 if _denom1 else 0\n _denom2 = true_pos + false_neg\n recall = true_pos / _denom2 if _denom2 else 0\n _denom3 = precision + recall\n F1 = 2 * ((precision * recall) / _denom3) if _denom3 else 0\n return precision*100, recall*100, F1*100\n\n\ndef _add_to_eval_dicts(eval_metrics, arg_excess, arg_missed, arg_match):\n for arg in eval_metrics[\"excess\"]:\n arg_excess[arg] += 1\n for arg in eval_metrics[\"missed\"]:\n arg_missed[arg] += 1\n for arg in eval_metrics[\"match\"]:\n arg_match[arg] += 1\n return arg_excess, arg_missed, arg_match\n\n\ndef evaluate_tagset(gold_labels, pred_labels, ignore_verb_label):\n label_filter = [\"X\", \"O\", \"B-V\"] if ignore_verb_label else [\"X\", \"O\"]\n gld = set([f\"{i}_{y.strip('B-')}\" for i, y in enumerate(gold_labels) if y not in label_filter])\n sys = set([f\"{i}_{y.strip('B-')}\" for i, y in enumerate(pred_labels) if y not in label_filter])\n\n excess = sys - gld # False Positives\n missed = gld - sys # False Negatives\n true_pos = sys.intersection(gld)\n\n eval_obj = {\"excess\": [x.split(\"_\")[1] for x in excess],\n \"missed\": [x.split(\"_\")[1] for x in missed],\n \"match\": [x.split(\"_\")[1] for x in true_pos]}\n return eval_obj\n\n\ndef format_time(elapsed):\n '''\n Takes a time in seconds and returns a string hh:mm:ss\n '''\n # Round to the nearest second.\n elapsed_rounded = int(round((elapsed)))\n\n # Format as hh:mm:ss\n return str(datetime.timedelta(seconds=elapsed_rounded))\n\n\ndef save_losses(losses, filename):\n out = open(filename, \"w\")\n out.write(json.dumps({\"losses\": losses})+\"\\n\")\n\n\ndef save_label_dict(label2index, filename):\n out = open(filename, \"w\")\n out.write(json.dumps(label2index))\n\n\ndef load_label_dict(modelpath):\n fp = open(modelpath)\n label_dict = json.load(fp)\n return label_dict\n\n\ndef get_overall_metrics(arg_excess, arg_missed, arg_match, save_to_file=None, print_metrics=True):\n # for x in arg_match.items():\n # print(x)\n processed_args = set()\n results = []\n tot_excess, tot_missed, tot_match = 0, 0, 0\n for arg, count in arg_match.items():\n excess = arg_excess.get(arg, 0)\n missed = arg_missed.get(arg, 0)\n p,r,f = get_metrics(false_pos=excess, false_neg=missed, true_pos=count)\n processed_args.add(arg)\n results.append((arg, count, excess, missed, p, r, f))\n tot_excess += excess\n tot_missed += missed\n tot_match += count\n for arg, count in arg_excess.items():\n if arg not in processed_args:\n excess = count\n missed = arg_missed.get(arg, 0)\n correct = arg_match.get(arg, 0)\n p, r, f = get_metrics(false_pos=excess, false_neg=missed, true_pos=correct) # p,r,f = 0,0,0\n processed_args.add(arg)\n results.append((arg, correct, excess, missed, p, r, f))\n tot_excess += excess\n tot_missed += missed\n tot_match += correct\n for arg, count in arg_missed.items():\n if arg not in processed_args:\n excess = arg_excess.get(arg, 0)\n correct = arg_match.get(arg, 0)\n missed = count\n p, r, f = get_metrics(false_pos=excess, false_neg=missed, true_pos=correct) # p,r,f = 0,0,0\n results.append((arg, correct, excess, missed, p, r, f))\n tot_excess += excess\n tot_missed += missed\n tot_match += correct\n results = sorted(results, key= lambda x: x[0])\n\n prec, rec, F1 = get_metrics(false_pos=tot_excess, false_neg=tot_missed, true_pos=tot_match)\n\n if print_metrics:\n print(\"\\n--- OVERALL ---\\nCorrect: {0}\\tExcess: {1}\\tMissed: {2}\\nPrecision: {3:.2f}\\t\\tRecall: {4:.2f}\\nF1: {5:.2f}\\n\".format(tot_match, tot_excess, tot_missed, prec, rec, F1))\n print(tabulate(results, headers=[\"corr.\", \"excess\", \"missed\", \"prec.\", \"rec.\", \"F1\"], floatfmt=\".2f\"))\n if save_to_file:\n fout = open(save_to_file, \"w\")\n fout.write(\"\\n--- OVERALL ---\\nCorrect: {0}\\tExcess: {1}\\tMissed: {2}\\nPrecision: {3:.2f}\\t\\tRecall: {4:.2f}\\nF1: {5:.2f}\\n\".format(tot_match, tot_excess, tot_missed, prec, rec, F1))\n fout.write(tabulate(results, headers=[\"corr.\", \"excess\", \"missed\", \"prec.\", \"rec.\", \"F1\"], floatfmt=\".2f\"))\n return prec, rec, F1\n\n\n# Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained()\ndef save_model(output_dir, arg_dict, model, tokenizer):\n # Create output directory if needed\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n print(\"Saving model to %s\" % output_dir)\n # Save a trained model, configuration and tokenizer using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training\n model_to_save.save_pretrained(output_dir)\n tokenizer.save_pretrained(output_dir)\n # Good practice: save your training arguments together with the trained model\n torch.save(arg_dict, os.path.join(output_dir, 'training_args.bin'))\n\n\ndef load_model(model_class, tokenizer_class, model_dir):\n # Load a trained model and vocabulary that you have fine-tuned\n model = model_class.from_pretrained(model_dir)\n tokenizer = tokenizer_class.from_pretrained(model_dir)\n # Copy the model to the GPU.\n model.to(device)\n return model, tokenizer","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"384563084","text":"from django.views.generic import View\nfrom django.views.decorators.http import require_http_methods\nfrom django.views import generic \nimport hmac\nimport os\nfrom django.contrib.auth import hashers\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .models import *\nfrom django.forms.models import model_to_dict\nfrom api import models\nfrom json import dumps\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.core import serializers\nfrom django.shortcuts import render, redirect\nfrom .forms import *\nfrom models import settings\nimport datetime\n\n'''\nCheck password, create/delete/get authenticator\n'''\n# def check_user_password(request):\n# \temail_addr = request.POST.get('email')\n# \tpassword = request.POST.get('password')\n# \tfound_profile = True\n# \ttry:\n# \t\tuser = Profile.objects.get(email=email_addr)\n# \texcept ObjectDoesNotExist:\n# \t\tfound_profile = False\n# \tresp = {}\n# \tif (found_profile and hashers.check_password(password, user.password)):\n# \t\tresp['ok'] = True\n# \t\tresp['result'] = model_to_dict(user)\n# \telse:\n# \t\tresp['ok'] = False\n# \t\tresp['result'] = \"Invalid email or password\"\n# \treturn JsonResponse(resp)\n\ndef createAuth(request):\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tu = Profile.objects.get(username = request.POST['username'])\n\t\texcept Profile.DoesNotExist:\n\t\t\treturn JsonResponse(\"User Does Not Exist\",safe=False)\n\t\tif not hashers.check_password(request.POST[\"password\"], u.password):\n\t\t\treturn JsonResponse(\"Incorrect password\", safe=False)\t\n\t\t#\tCheck if the newly generated authenticator already exists in the database\n\t\ttry: \n\t\t\tuser = Authenticator.objects.get(user_id=u.pk)\n\t\t\tdeleteAuth(request,user.authenticator)\n\t\texcept Authenticator.DoesNotExist:\n\t\t\tpass\n\t\tauth_hash = hmac.new(key = settings.SECRET_KEY.encode('utf-8'), msg = os.urandom(32), digestmod = 'sha256').hexdigest()\n\t\tauth = Authenticator.objects.create(date_created = datetime.datetime.now(), user_id = u.pk, authenticator=auth_hash)\n\t\ttry:\n\t\t\tauth.save()\n\t\t\tresp=model_to_dict(auth)\n\t\t\treturn JsonResponse(resp)\n\t\t\t#resp['ok'] = True\n\t\t\t#resp[\"result\"] = {\"authenticator\": model_to_dict(auth)}\n\t\texcept KeyError:\n\t\t\t#resp['ok'] = False\n\t\t\treturn JsonResponse(\"Failed to create authenticator\", safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\t\n\n# def getAuth(request, authenticator):\n# \tif request.method == 'GET':\n# \t\ttry:\n# \t\t\tauthenticator = Authenticator.objects.filter(pk=authenticator)\n# \t\texcept ObjectDoesNotExist:\n# \t\t\treturn JsonResponse(\"User has not been authenticated yet.\",safe=False)\n# \t\t# auth = Authenticator.objects.filter(user_id=pk)\n# \t\talist = []\n# \t\tfor i in auth:\n# \t\t\talist.append(model_to_dict(i))\n# \t\t\treturn JsonResponse(alist, safe=False)\n# \t\treturn JsonResponse(\"User does not exist\", safe=False)\n# \telse:\n# \t\treturn JsonResponse(\"Must Get\",safe=False)\t\n\ndef deleteAuth(request,authenticator):\n\ttry:\n\t\tauthenticator = Authenticator.objects.get(pk=authenticator)\n\texcept ObjectDoesNotExist:\n\t\treturn JsonResponse(\"User has not been authenticated yet.\",safe=False)\n\tauthenticator.delete()\n\treturn JsonResponse(\"Successfully deleted user authentication\",safe=False)\n\ndef checkAuth(request):\n\ttry:\n\t\tuser = Profile.objects.get(username = request.POST['username'])\n\texcept ObjectDoesNotExist:\n\t\treturn JsonResponse(\"Authenticator does not exist.\",safe=False)\n\texcept KeyError:\n\t\ttry: \n\t\t\tu = Authenticator.objects.get(pk = request.POST['authenticator'])\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Authenticator does not exist.\",safe=False)\n\t\treturn JsonResponse( model_to_dict(u),safe=False)\n\ttry:\n\t\tu = Authenticator.objects.get(user_id=user.pk)\n\texcept ObjectDoesNotExist:\n\t\treturn JsonResponse(\"Authenticator does not exist.\",safe=False)\n\texcept KeyError:\n\t\treturn JsonResponse(\"Authenticator Does Not Exist\",safe=False)\n\ttry:\n\t\tpw = request.POST[\"password\"];\n\texcept KeyError:\n\t\treturn JsonResponse(\"Incorrect password\", safe=False)\t\n\tif not hashers.check_password(request.POST[\"password\"], user.password):\n\t\treturn JsonResponse(\"Incorrect password\", safe=False)\t\n\telse:\n\t\treturn JsonResponse( model_to_dict(u),safe=False)\n\n\n\ndef authView(request):\n\tauths = Authenticator.objects.all()\n\tresponse = []\n\tfor auth in auths:\n\t\tresponse.append(model_to_dict(auth))\n\treturn JsonResponse(response,safe=False)\n\t# try:\n\t# \tauthenticator = Authenticator.objects.get(pk=request.POST['authenticator'])\n\t# except ObjectDoesNotExist:\n\t# \treturn JsonResponse(\"Authenticator does not exist.\",safe=False)\n\t# return JsonResponse( model_to_dict(authenticator),safe=False)\n\n\n\n'''\nCafe (create, edit, delete, retrieve, IndexView)\n'''\n\ndef indexView(request):\n\tif request.method == 'GET':\n\t\tresult = {}\n\t\ttry:\n\t\t\tresult[\"ok\"] = True\n\t\t\tresult[\"result\"] = [model_to_dict(cafe) for cafe in Cafe.objects.all()]\n\t\texcept Exception:\n\t\t\tresult[\"ok\"] = False\n\t\t\tresult[\"result\"] = []\n\t\treturn JsonResponse(result)\n\telse:\n\t\treturn JsonResponse(\"Must Get\",safe=False)\t\t\n\ndef create_cafe(request):\n\tif request.method == 'POST':\n\t\tresult = {}\n\t\tresult_msg = None\n\t\ttry:\n\t\t\treq_input = {\n\t\t\t'name': request.POST['name'],\n\t\t\t'location':request.POST['location'],\n\t\t\t'date':request.POST['date'],\n\t\t\t'description':request.POST['description'],\n\t\t\t'Calories':request.POST['Calories'],\n\t\t\t}\n\t\texcept KeyError:\n\t\t\treq_input = {}\n\t\tform = CafeForm(req_input)\n\t\tif form.is_valid():\n\t\t\tcafe = form.save()\n\t\t\tresult[\"ok\"] = True\n\t\t\tresult[\"result\"] = {\"id\": cafe.id}\n\t\t\treturn JsonResponse(req_input,safe=False)\n\t\telse:\n\t\t\tresult_msg = \"Input did not contain all the required fields.\"\n\t\t\treturn JsonResponse(result_msg,safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\t\n\ndef delete_cafe(request, pk):\n\tif request.method == 'POST':\n\t\tresp = {}\n\t\tcafefound = True\n\t\ttry:\n\t\t\tcafe = Cafe.objects.get(pk=pk)\n\t\t\tcafe.delete()\n\t\texcept ObjectDoesNotExist:\n\t\t\tcafefound = False\n\t\t\treturn JsonResponse(\"This meal does not exist.\",safe=False)\n\t\tif cafefound:\n\t\t\treturn JsonResponse(\"Deleted meal\", safe=False)\n\telse:\t\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\t\n\n'''\nComment (create, delete, commentView)\n'''\n\n\ndef commentView(request):\n\tif request.method == 'GET':\n\t\tresult = {}\n\t\ttry:\n\t\t\tresult[\"ok\"] = True\n\t\t\tresult[\"result\"] = [model_to_dict(comment) for comment in Comment.objects.all()]\n\t\texcept Exception:\n\t\t\tresult[\"ok\"] = False\n\t\t\tresult[\"result\"] = []\n\t\treturn JsonResponse(result)\n\telse:\n\t\treturn JsonResponse(\"Must Get\",safe=False)\t\t\n\ndef create_comment(request):\n\tif request.method == 'POST':\t\t\n\t\tresult = {}\n\t\tresult_msg = None\n\t\ttry:\n\t\t\treq_input = {\n\t\t\t'description': request.POST['description'],\n\t\t\t'feedback':request.POST['feedback'],\n\t\t\t'date_written':request.POST['date_written'],\n\t\t\t'rating':request.POST['rating'],\n\t\t\t}\n\t\texcept KeyError:\n\t\t\treq_input = {}\n\t\t\tresult_msg = \"Input did not contain all the required fields.\"\n\t\tform = CommentForm(req_input)\n\t\tif form.is_valid():\n\t\t\tcomment = form.save()\n\t\t\treturn JsonResponse(req_input,safe=False)\n\t\telse:\n\t\t\treturn JsonResponse(result_msg,safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\n\ndef delete_comment(request, pk):\n\tif request.method == 'POST':\t\t\n\t\tresp = {}\n\t\tcommentfound = True\n\t\ttry:\n\t\t\tcomment = Comment.objects.get(pk=pk)\n\t\t\tcomment.delete()\n\t\texcept ObjectDoesNotExist:\n\t\t\tcommentfound = False\n\t\t\treturn JsonResponse(\"This comment does not exist.\",safe=False)\n\t\tif commentfound:\n\t\t\treturn JsonResponse(\"Deleted comment \", safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\n\n'''\nProfile (create, retrieve, IndexView)\n'''\n\ndef profileView(request):\n\tif request.method == 'GET':\t\t\t\n\t\tresult = {}\n\t\ttry:\n\t\t\tresult[\"ok\"] = True\n\t\t\tresult[\"result\"] = [model_to_dict(profile) for profile in Profile.objects.all()]\n\t\texcept Exception:\n\t\t\tresult[\"ok\"] = False\n\t\t\tresult[\"result\"] = []\n\t\treturn JsonResponse(result)\n\telse:\n\t\treturn JsonResponse(\"Must Get\",safe=False)\t\n\n\ndef create_profile(request):\n\tif request.method == 'POST':\n\t\tuser = Profile()\n\t\tuser.username = request.POST['username']\n\t\tuser.email = request.POST['email']\n\t\tpw =request.POST['password']\n\t\tuser.password = hashers.make_password(request.POST['password'])\n\t\tif user.username ==\"\" or user.email ==\"\" or pw ==\"\":\n\t\t\treturn JsonResponse(\"Input did not contain all the required fields.\",safe=False)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tu = Profile.objects.get(username=request.POST['username'])\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\ttry:\n\t\t\t\t\tv = Profile.objects.get(email=request.POST['email'])\n\t\t\t\texcept ObjectDoesNotExist:\n\t\t\t\t\tuser.save()\n\t\t\t\t\treturn JsonResponse(model_to_dict(user))\n\t\t\t\treturn JsonResponse(\"unique\",safe=False)\n\t\t\treturn JsonResponse(\"unique\",safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\n\n\ndef delete_profile(request, pk):\n\tif request.method == 'POST':\t\n\t\tresp = {}\n\t\tprofilefound = True\n\t\ttry:\n\t\t\tprofile = Profile.objects.get(pk=pk)\n\t\t\tprofile.delete()\n\t\texcept ObjectDoesNotExist:\n\t\t\tprofilefound = False\n\t\t\treturn JsonResponse(\"This profile does not exist.\",safe=False)\n\t\tif profilefound:\n\t\t\treturn JsonResponse(\"Deleted profile \", safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\t\n\ndef retrieve_profile(request):\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tprofile = Profile.objects.get(username=request.POST['username'])\n\t\t\tp = [model_to_dict(profile)];\n\t\t\t#return JsonResponse(model_to_dict(profile))\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Profile does not exist.\",safe=False)\n\t\tif hashers.check_password(request.POST[\"password\"], model_to_dict(profile)[\"password\"]):\n\t\t\treturn JsonResponse(model_to_dict(profile))\t\t\t\n\t\telse:\n\t\t\treturn JsonResponse(\"Incorrect Password\", safe=False)\n\t\t\n\telse:\n\t\treturn JsonResponse(\"Must Post\",safe=False)\n\ndef check_dup(request):\n\tif request.method == 'POST':\n\t\ttry:\n\t\t\tprofile = Profile.objects.get(username=request.POST['username'])\n\t\t\tp = [model_to_dict(profile)];\n\t\texcept ObjectDoesNotExist:\n\t\t\ttry:\n\t\t\t\tprofile = Profile.objects.get(email=request.POST['email'])\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\treturn JsonResponse(\"Valid input\", safe=False)\n\t\t\treturn JsonResponse(\"Duplicate email\",safe=False)\n\t\treturn JsonResponse(\"Duplicate username\",safe=False)\n\telse:\n\t\treturn JsonResponse(\"Must Post\", safe=False)\n\ndef get_recent_meals(request):\n if request.method == 'GET':\n recent_meals = Cafe.objects.order_by('-date')[:3]\n meallist = []\n for i in recent_meals:\n meallist.append(model_to_dict(i))\n return JsonResponse(meallist, safe=False)\n else:\n return JsonResponse(\"Must make GET request.\",safe=False)\n\ndef retrieve_cafe_all(request):\n\t\tif request.method != 'GET':\n\t\t\treturn JsonResponse(\"Must make GET request.\",safe=False) \n\t\tmeals = Cafe.objects.all()\n\t\tresponse = []\n\t\tfor meal in meals:\n\t\t\tresponse.append(model_to_dict(meal))\n\t\treturn JsonResponse(response,safe=False)\n\t\ndef retrieve_comment_all(request):\n\t\tif request.method == 'GET':\n\t\t\t\tcomments = Comment.objects.all()\n\t\t\t\tcommentlist = []\n\t\t\t\tfor i in comments:\n\t\t\t\t\tcommentlist.append(model_to_dict(i))\n\t\t\t\treturn JsonResponse(commentlist, safe=False)\n\t\telse:\n\t\t\t\treturn JsonResponse(\"Must make GET request.\",safe=False)\n\n'''\nRetrieve and Update Cafe, Comment, Profile\n'''\nclass CafeRetrieveUpdate(View):\n\n\tdef get(self, request, pk):\n\t\tresult = {}\n\t\ttry:\n\t\t\tcafe = Cafe.objects.get(pk=pk)\n\t\t\treturn JsonResponse(model_to_dict(cafe))\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Cafe does not exist.\",safe=False)\n\n\tdef post(self, request, pk):\n\t\tresult = {}\n\t\ttry:\n\t\t\tcafe = Cafe.objects.get(pk=pk)\n\t\t\tcafe_fields = [c.name for c in Cafe._meta.get_fields()]\n\t\t\tfor field in cafe_fields:\n\t\t\t\tif field in request.POST:\n\t\t\t\t\tsetattr(cafe, field, request.POST[field])\n\t\t\tcafe.save()\n\t\t\treturn JsonResponse(model_to_dict(cafe))\t\t\t\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Cafe does not exist.\",safe=False)\n\nclass CommentRetrieveUpdate(View):\n\tdef get(self, request, pk):\n\t\tresult = {}\n\t\ttry:\n\t\t\tcomment = Comment.objects.get(pk=pk)\n\t\t\treturn JsonResponse(model_to_dict(comment))\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Comment does not exist.\",safe=False)\n\n\tdef post(self, request, pk):\n\t\tresult = {}\n\t\ttry:\n\t\t\tcomment = Comment.objects.get(pk=pk)\n\t\t\tcomment_fields = [c_field.name for c_field in Comment._meta.get_fields()]\n\t\t\tfor field in comment_fields:\n\t\t\t\tif field in request.POST:\n\t\t\t\t\tsetattr(comment, field, request.POST[field])\n\t\t\tcomment.save()\n\t\t\treturn JsonResponse(model_to_dict(comment))\t\t\t\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Comment does not exist.\",safe=False)\n\nclass ProfileRetrieveUpdate(View):\n\tdef get(self, request, pk):\n\t\ttry:\n\t\t\tprofile = Profile.objects.get(pk=pk)\n\t\t\tif hashers.check_password(request.POST['password'], profile.password):\n\t\t\t\treturn JsonResponse(model_to_dict(profile))\t\t\t\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Profile does not exist.\",safe=False)\n\n\tdef post(self, request, pk):\n\t\tresult = {}\n\t\ttry:\n\t\t\tprofile = Profile.objects.get(pk=pk)\n\t\t\tprofile_fields = [p_field.username for p_field in Profile._meta.get_fields()]\n\t\t\tfor field in profile_fields:\n\t\t\t\tif field in request.POST:\n\t\t\t\t\tsetattr(profile, field, request.POST[field])\n\t\t\tprofile.save()\n\t\t\treturn JsonResponse(model_to_dict(profile))\t\t\t\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse(\"Profile does not exist.\",safe=False)\n\n","sub_path":"app/models/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"464447804","text":"from enum import Enum\nimport numpy as np\nimport cv2\nfrom Util import *\nfrom image_stitching import Stitcher\nfrom sensor import Sensor\nfrom threading import Thread\n\nimport os\n\nclass FeedSelections(Enum):\n Overhead = 0\n Left = 1\n Rear = 2\n Right = 3\n\nfeedToCamMap = {\n FeedSelections.Overhead: [CamList.Left, CamList.Right, CamList.Rear],\n FeedSelections.Left: CamList.Left,\n FeedSelections.Right: CamList.Right,\n FeedSelections.Rear: CamList.Rear\n }\n\nfeedToTitleMap = {\n FeedSelections.Overhead: \"Panorama\",\n FeedSelections.Left: \"Left Camera\",\n FeedSelections.Right: \"Right Camera\",\n FeedSelections.Rear: \"Rear Camera\"\n}\n\nfeedListVals = [feedList for feedList in FeedSelections]\n\nclass Model:\n def __init__(self, leftCapture, rightCapture, rearCapture, sensorVals):\n self.displayToFeedMap = {\n DisplaySelection.MainLeft: FeedSelections.Overhead,\n DisplaySelection.Right: FeedSelections.Overhead\n }\n\n prefix = os.path.join(os.getcwd(), 'defaultImages')\n\n over = cv2.imread(os.path.join(prefix, 'overheadDefault.jpg'))\n left = cv2.imread(os.path.join(prefix, 'leftDefault.jpg'))\n right = cv2.imread(os.path.join(prefix, 'rightDefault.jpg'))\n rear = cv2.imread(os.path.join(prefix, 'rearDefault.jpg'))\n\n self.feedToDefaultMap = {\n FeedSelections.Overhead: over,\n FeedSelections.Left: left,\n FeedSelections.Right: right,\n FeedSelections.Rear: rear\n }\n\n self.stitcher = Stitcher()\n\n #Create the left sensor\n self.leftSensor = Sensor(sensorVals[CamList.Left][GPIO.TRIG], sensorVals[CamList.Left][GPIO.ECHO])\n self.rightSensor = Sensor(sensorVals[CamList.Right][GPIO.TRIG], sensorVals[CamList.Right][GPIO.ECHO])\n self.rearSensor = Sensor(sensorVals[CamList.Rear][GPIO.TRIG], sensorVals[CamList.Rear][GPIO.ECHO])\n\n #Run a thread to start the readings\n self.leftThread = Thread(target = self.leftSensor.startSensors)\n self.rightThread = Thread(target = self.rightSensor.startSensors)\n self.rearThread = Thread(target=self.rearSensor.startSensors)\n\n self.leftThread.start()\n self.rightThread.start()\n self.rearThread.start()\n\n self.notificationsMuted = True\n self.leftCapture = leftCapture\n self.rightCapture = rightCapture\n self.rearCapture = rearCapture\n\n def stop(self):\n self.rightSensor.stop()\n self.leftSensor.stop()\n self.rearSensor.stop()\n self.leftThread.join()\n self.rightThread.join()\n self.rearThread.join()\n\n def changeFeed(self, displaySelection, desiredCamSelection):\n\n if desiredCamSelection == CamList.Left:\n feedSelection = FeedSelections.Left\n elif desiredCamSelection == CamList.Rear:\n feedSelection = FeedSelections.Rear\n else:\n feedSelection = FeedSelections.Right\n\n self.displayToFeedMap[displaySelection] = feedSelection\n\n def nextFeed(self, displaySelection):\n curSelection = self.displayToFeedMap[displaySelection]\n self.displayToFeedMap[displaySelection] = \\\n feedListVals[(curSelection.value + 1) % len(feedListVals)]\n\n def prevFeed(self, displaySelection):\n curSelection = self.displayToFeedMap[displaySelection]\n self.displayToFeedMap[displaySelection] = \\\n feedListVals[len(feedListVals) - 1 if curSelection.value == 0 else curSelection.value - 1]\n\n def toggleNotifications(self, notificationsMuted):\n self.notificationsMuted = notificationsMuted\n\n def getFeed(self, displaySelection, color):\n # Get the needed feeds for the relevant display selection\n feedSelection = self.displayToFeedMap[displaySelection]\n\n if feedSelection == FeedSelections.Overhead:\n # Pull from all feeds and stitch them together\n try:\n leftFeed = self.getWebcamFrame(self.leftCapture)\n rightFeed = self.getWebcamFrame(self.rightCapture)\n rearFeed = self.getWebcamFrame(self.rearCapture)\n\n if leftFeed is None or rightFeed is None or rearFeed is None:\n return self.feedToDefaultMap[feedSelection], feedToTitleMap[feedSelection]\n\n stitchedArray = self.stitcher.stitch([leftFeed, rearFeed, rightFeed], color)\n stitchedImage = stitchedArray\n return stitchedImage, feedToTitleMap[feedSelection]\n except RuntimeError:\n return self.feedToDefaultMap[feedSelection], feedToTitleMap[feedSelection]\n\n elif feedSelection == FeedSelections.Left:\n leftFeed = self.getWebcamFrame(self.leftCapture)\n if leftFeed is None:\n return self.feedToDefaultMap[feedSelection], feedToTitleMap[feedSelection]\n\n return leftFeed, feedToTitleMap[feedSelection]\n elif feedSelection == FeedSelections.Right:\n rightFeed = self.getWebcamFrame(self.rightCapture)\n if rightFeed is None:\n return self.feedToDefaultMap[feedSelection], feedToTitleMap[feedSelection]\n\n return rightFeed, feedToTitleMap[feedSelection]\n elif feedSelection == FeedSelections.Rear:\n rearFeed = self.getWebcamFrame(self.rearCapture, False)\n if rearFeed is None:\n return self.feedToDefaultMap[feedSelection], feedToTitleMap[feedSelection]\n\n return rearFeed, feedToTitleMap[feedSelection]\n\n\n def recalibrate(self):\n try:\n self.stitcher.calibrate()\n except RuntimeError:\n return\n\n\n def getReading(self):\n\n if self.notificationsMuted:\n return {}\n\n readings = {\n CamList.Left: self.leftSensor.getReading(),\n CamList.Right: self.rightSensor.getReading(),\n CamList.Rear: self.rearSensor.getReading(),\n\n }\n\n return readings\n\n def setThreshold(self, threshold):\n self.leftSensor.setThreshold(threshold)\n self.rightSensor.setThreshold(threshold)\n self.rearSensor.setThreshold(threshold)\n\n @staticmethod\n def getWebcamFrame(capture, fix_distortion = True):\n ret, frame = capture.retrieve()\n\n if not ret:\n return None\n\n if frame.shape[0] != 480:\n frame = cv2.resize(frame, None, fx=0.444444, fy=0.444444)[:, 106:746, :]\n\n frame_to_display = undistort(frame) if fix_distortion else frame\n\n return cv2.flip(frame_to_display, 1)\n\n\n\n\nDIM=(640, 480)\nK=np.array([[269.6616655760057, 0.0, 322.2636869266894], [0.0, 270.57327145833693, 211.76621398914702], [0.0, 0.0, 1.0]])\nD=np.array([[-0.04175871736401356], [-0.0031884652828571736], [0.0006001904789516924], [-0.0009174281553332885]])\ndef undistort(img):\n h,w = img.shape[:2]\n map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, DIM, cv2.CV_16SC2)\n undistorted_img = cv2.remap(img, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)\n return undistorted_img\n\n","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"25400607","text":"#Escribe un programa que:\n# * Cree un diccionario con el nombre de tres amigos y asocie a cada uno su edad.\n# * Pida el nombre de un amigo y escriba su edad. Si el nombre no está en el diccionario que escriba: 'No sé su edad'.\n\ndiccionario = {'Antonio':24,'Jesus':30,'Pepe':27}\n\na = input(\"Dime el nombre de tu amigo para saber su edad: \")\nif a in diccionario:\n print(diccionario[a])\nelse:\n print(\"No sé su edad\")","sub_path":"Practicas/ejercicio3.py","file_name":"ejercicio3.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"431803145","text":"#!/usr/bin/env python\n\n\n# this script takes as its input a sample sheet and a file list as defined by the ChIPseq pipeline README. It checks that sample sheet entries conform to the formatting requirements, that sample names match those in the file list and that the bam files listed in the file list and their bai index files exist\n\nimport sys\nimport argparse\nimport re\nimport os.path\n#########################################################################################################################################################################\nparser = argparse.ArgumentParser(description='Check sample details.')\n# Basic Input Files, required\n\nparser.add_argument(\"-s\", \"--samplesheet\", type=str, metavar=\"Filename\", dest=\"sampleSheetFile\", \n help=\"The path to the sample sheet to be checked.\", required=True)\nparser.add_argument(\"-f\", \"--filelist\", type=str, metavar=\"Filename\", dest=\"fileListFile\", help=\"The path to the file list to be checked.\", required=True)\nparser.add_argument(\"-d\", \"--bamdir\", type=str, metavar=\"Directory\", dest=\"bamDirectory\", help=\"The path to the file list to be checked.\", required=True)\nparser.add_argument(\"-o\", \"--outputfile\", type=str, metavar=\"Filename\", dest=\"goodSampleSheetFile\", help=\"An output file that will be generated if the sample sheet passes all checks.\")\nparser.add_argument(\"-e\", \"--errorfile\", type=str, metavar=\"Filename\", dest=\"badSampleSheetFile\", help=\"An output file that will be generated if the sample sheet fails any checks. This will contain details of the errors.\")\n\n\nargs = parser.parse_args()\n\nsampleSheetFile = args.sampleSheetFile\nfileListFile = args.fileListFile\nbamDirectory = str(args.bamDirectory)\nerrorOutFile = str(args.badSampleSheetFile)\nsuccessOutFile = str(args.goodSampleSheetFile)\n\nif errorOutFile=='None':\n errorOutFile = 'ChIPseqPipeline_PreFlightCheck.Error.README'\n\nif successOutFile=='None':\n successOutFile = '.ChIPseqPipeline_PreFlightCheck.checked_ok'\n\n#########################################################################################################################################################################\n## First check the input files are present\n\ntry:\n sampleSheet = open(sampleSheetFile,'r')\nexcept IOError:\n sys.exit(\"The sample sheet '\"+sampleSheetFile+\"' does not exist. Please try again.\")\n\ntry:\n fileList = open(fileListFile,'r')\nexcept IOError:\n sys.exit(\"The file list '\"+fileListFile+\"' does not exist. Please try again.\")\n\n################################################################################################################################################################################\n## Create a dictionary containing the sample sheet data with the column headers as keys\n\n# create empty dictionary with all possible columns as keys\n\nallColumns = ('MatchingInput', 'SampleName', 'SampleType', 'Tissue', 'Replicate', 'Treatment', 'Factor', 'Condition')\nsampleDict = dict((el, []) for el in allColumns)\n\n# get data and transpose\nsampleHeaderRow = sampleSheet.readline().strip().split(\",\")\nwith sampleSheet as f:\n lis = [x.strip().split(',') for x in f]\n\ntSampleSheet = zip(*lis)\n\n# populate the dictionary values for columns present in the sample sheet\nfor i in range(0, len(sampleHeaderRow)):\n sampleDict[sampleHeaderRow[i]] = tSampleSheet[i]\n\n################################################################################################################################################################################\n## Create a dictionary containing the file list data with the column headers as keys\n\n# create empty dictionary with all possible columns as keys\n\nallColumns = ('SampleName','SourceID','Filename')\nfileDict = dict((el, []) for el in allColumns)\n\n# get data and transpose\nfileHeaderRow = fileList.readline().strip().split(\",\")\nwith fileList as f:\n lis = [x.strip().split(',') for x in f]\n\ntfileList = zip(*lis)\n\n# populate the dictionary values for columns present in the file list\nfor i in range(0, len(fileHeaderRow)):\n fileDict[fileHeaderRow[i]] = tfileList[i]\n\n\n################################################################################################################################################################################\n## Check the sample sheet and file list to see if they are csv and there the requisite columns\n\nsampleRequiredColumns = (\"SampleName\", \"SampleType\", \"MatchingInput\")\nsampleSheetCheck = all( str(i) in sampleHeaderRow for i in sampleRequiredColumns)\nfileRequiredColumns = (\"SampleName\", \"Filename\")\nfileListCheck = all( str(i) in fileHeaderRow for i in fileRequiredColumns)\nif not sampleSheetCheck or not fileListCheck:\n try:\n errorOut = open(errorOutFile,'w')\n except IOError:\n sys.exit(\"Unable to write to the output file '\"+errorOutFile+\"'. There was a problem with the sample sheet.\")\n if not sampleSheetCheck:\n errorOut.write(\"The column headers '\"+\"', '\".join([str(i) for i in sampleRequiredColumns])+\"' are required in the sample sheet, but could not be found.\\n\")\n if not fileListCheck:\n errorOut.write(\"The column headers '\"+\"', '\".join([str(i) for i in fileRequiredColumns])+\"' are required in the file list, but could not be found.\\n\")\n errorOut.write('Either they are not present or the format is not csv.\\n')\n errorOut.write('Please refer to the README for further details on the correct format and contents of the input files.\\n')\n sys.exit(\"There was a problem with the sample sheet and/or the file list. Please the error file: \"+errorOutFile)\n\n################################################################################################################################################################################\n## Check each column of the sample sheet to ensure it is correct\n# Do any of the entries violate the requirements for special characters\n# Does the MatchingInput column contain sample names that match names in the SampleName column\n\n#check sample names\nbadSampleName = []\nfor sampleName in sampleDict['SampleName']:\n if(re.search('^[0-9]| ', sampleName)):\n badSampleName.append(sampleName)\nsampleNameCheck = len(badSampleName) > 0 \n\n#check sample type\nbadSampleType = [sampleDict['SampleType'][i] for i, x in enumerate(sampleDict['SampleType']) if x not in ('sample', 'chip', 'control', 'input')]\nsampleTypeCheck = len(badSampleType) > 0\n\n#check Matching Input is in SampleName column (or missing for inputs)\ninputs = [sampleDict['SampleName'][i] for i, x in enumerate(sampleDict['SampleType']) if x in ('control', 'input')]\nbadMatchingInput = [sampleDict['SampleName'][i] for i, x in enumerate(sampleDict['MatchingInput']) if x not in inputs]\nmatchingInputCheck = len(badMatchingInput) > 0 \n\n# check factoring columns for punctuation or spaces\n\ndef checkMetaData(metaColumn):\n badMeta= []\n for metaValue in metaColumn:\n if(not metaValue.isalnum() and metaValue):\n badMeta.append(metaValue)\n return badMeta\n\nbadTissue = checkMetaData(sampleDict['Tissue'])\ntissueCheck = len(badTissue) > 0 \n\nbadCondition = checkMetaData(sampleDict['Condition'])\nconditionCheck = len(badCondition) > 0 \n\nbadTreatment = checkMetaData(sampleDict['Treatment'])\ntreatmentCheck = len(badTreatment) > 0 \n\nbadFactor = checkMetaData(sampleDict['Factor'])\nfactorCheck = len(badFactor) > 0 \n\n##check replicate column only contains numbers for samples\ndef is_number(s):\n try:\n float(s)\n return False\n except ValueError:\n return True\n\nreplicateCheck = any(is_number(sampleDict['Replicate'][i]) for i, x in enumerate(sampleDict['SampleType']) if x in ('sample', 'chip'))\n\n################################################################################################################################################################################\n## Check that the sample names in the sample sheet match the sample names in the file list\n\nmismatchedSampleNames = [ sampleDict['SampleName'][i] for i,x in enumerate(sampleDict['SampleName']) if x not in fileDict['SampleName']]\nmismatchCheck = len(mismatchedSampleNames) > 0\n\n################################################################################################################################################################################\n## Check that the bam files listed in the file list actually exist\n\nmissingBams = []\nfor bamFile in fileDict['Filename']:\n filePath = bamDirectory+\"/\"+bamFile\n if not os.path.isfile(filePath):\n missingBams.append(bamFile)\nbamsCheck = len(missingBams) > 0\n\n################################################################################################################################################################################\n## Write error output if necessary\n\nif sampleNameCheck or sampleTypeCheck or matchingInputCheck or tissueCheck or conditionCheck or treatmentCheck or factorCheck or replicateCheck or mismatchCheck or bamsCheck:\n try:\n errorOut = open(errorOutFile,'w')\n except IOError:\n sys.exit(\"Unable to write to the output file '\"+errorOutFile+\"'. There was a problem with the sample sheet.\")\nif sampleNameCheck or sampleTypeCheck or matchingInputCheck or tissueCheck or conditionCheck or treatmentCheck or factorCheck or replicateCheck:\n errorOut.write(\"There are errors in the sample sheet - \"+sampleSheetFile+\". Please refer to the README for detailed instructions on the correct contents.\\n\")\n errorOut.write(\"Errors are listed below:\\n\\n\")\nif sampleNameCheck:\n errorOut.write(\"\\tSample names should not contain spaces or begin with a number. The following SampleNames are incorrect:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badSampleName])+\"'\\n\\n\")\nif sampleTypeCheck:\n errorOut.write(\"\\tSample types should be one of 'sample', 'chip', 'input', or 'control'. The following SampleTypes are incorrect:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badSampleType])+\"'\\n\\n\")\nif matchingInputCheck:\n errorOut.write(\"\\tThe MatchingInput should either be empty (for inputs) or match an input sample name in the SampleName column. The following samples have an incorrect matching input entry:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badMatchingInput])+\"'\\n\\n\")\nif tissueCheck:\n errorOut.write(\"\\tThe Tissue column is incorrectly formatted - letters and numbers only. Incorrect entries are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badTissue])+\"'\\n\\n\")\nif conditionCheck:\n errorOut.write(\"\\tThe Condition column is incorrectly formatted - letters and numbers only. Incorrect entries are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badCondition])+\"'\\n\\n\")\nif treatmentCheck:\n errorOut.write(\"\\tThe Treatment column is incorrectly formatted - letters and numbers only. Incorrect entries are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badTreatment])+\"'\\n\\n\")\nif factorCheck:\n errorOut.write(\"\\tThe Factor column is incorrectly formatted - letters and numbers only. Incorrect entries are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in badFactor])+\"'\\n\\n\")\nif replicateCheck:\n errorOut.write(\"\\tThere is an error in the Replicate column, they should only be numbers.\\n\\n\")\nif mismatchCheck or bamsCheck:\n errorOut.write(\"There are errors in the file list - \"+fileListFile+\". Please refer to the README for detailed instructions on the correct contents.\\n\")\n errorOut.write(\"Errors are listed below:\\n\\n\")\nif mismatchCheck:\n errorOut.write(\"\\tNot all sample listed in the sample sheet have a corresponding entry in the file list. Missing samples are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in mismatchedSampleNames])+\"'\\n\\n\")\nif bamsCheck:\n errorOut.write(\"\\tIt was not possible to locate all of the bam files listed in the file list. The directory searched was:\\n\")\n errorOut.write(\"\\t\\t'\"+bamDirectory+\"'\\n\")\n errorOut.write(\"\\tThe missing files are:\\n\")\n errorOut.write(\"\\t\\t'\"+\"', '\".join([str(i) for i in missingBams])+\"'\\n\\n\")\n \nerrorOut.close()\n\n######################\n","sub_path":"PipelineRelated/ChIPseq/pipeline_devel/scrap/PipelinePrechecker.py","file_name":"PipelinePrechecker.py","file_ext":"py","file_size_in_byte":12086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"478138378","text":"#!/usr/bin/env python\n# coding=utf-8\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom torch.autograd import Variable\nimport numpy as np\nimport time\nimport os\nimport copy\nimport argparse\nfrom PIL import Image\nfrom scipy.spatial.distance import cdist\nfrom sklearn.metrics import confusion_matrix\nfrom utils_incremental.utils_pytorch import *\nfrom algorithms.GFK_distill_cosine_nce import GFK_NCE\n#from algorithms.GFK_distill_normalise import GFK ### dikomen padahal berhasil\nfrom algorithms.GFK_cosine_embedding import GFK\nfrom algorithms.nca_loss import nca\nfrom algorithms.triplet_loss import TripletLoss\n\ncur_features = []\nref_features = []\nold_scores = []\nnew_scores = []\n\ngfk = GFK()\ngfk_nce = GFK_NCE()\n\n\ndef get_ref_features(self, inputs, outputs):\n global ref_features\n ref_features = inputs[0]\n\ndef get_cur_features(self, inputs, outputs):\n global cur_features\n cur_features = inputs[0]\n\ndef get_old_scores_before_scale(self, inputs, outputs):\n global old_scores\n old_scores = outputs\n\ndef get_new_scores_before_scale(self, inputs, outputs):\n global new_scores\n new_scores = outputs\n\ndef incremental_train_and_eval_AMR_LF_GF(epochs, tg_model, ref_model, tg_optimizer, tg_lr_scheduler, \\\n trainloader, testloader, \\\n iteration, start_iteration, \\\n lamda, \\\n dist, K, lw_mr, \\\n weight_per_class=None, device=None):\n if device is None:\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n #trainset.train_data = X_train.astype('uint8')\n #trainset.train_labels = Y_train\n #trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,\n # shuffle=True, num_workers=2)\n #testset.test_data = X_valid.astype('uint8')\n #testset.test_labels = Y_valid\n #testloader = torch.utils.data.DataLoader(testset, batch_size=100,\n # shuffle=False, num_workers=2)\n #print('Max and Min of train labels: {}, {}'.format(min(Y_train), max(Y_train)))\n #print('Max and Min of valid labels: {}, {}'.format(min(Y_valid), max(Y_valid)))\n criterion = TripletLoss()\n\n if iteration > start_iteration:\n ref_model.eval()\n num_old_classes = ref_model.fc.out_features\n # handle_ref_features = ref_model.fc.register_forward_hook(get_ref_features)\n # handle_cur_features = tg_model.fc.register_forward_hook(get_cur_features)\n handle_old_scores_bs = tg_model.fc.fc1.register_forward_hook(get_old_scores_before_scale)\n handle_new_scores_bs = tg_model.fc.fc2.register_forward_hook(get_new_scores_before_scale)\n\n # L1_lambda = .4#5\n # L3_lambda = 6.\n # scheduled_factor = math.sqrt((iteration - start_iteration) /1.) ## for 10 phases\n\n #Lamda: 0.01 1.0simon123\n lamda = 14.\n print('Lamda: ', lamda)\n\n for epoch in range(epochs):\n #train\n #break\n tg_model.train()\n train_loss = 0\n train_loss1 = 0\n train_loss2 = 0\n train_loss3 = 0\n correct = 0\n total = 0\n tg_lr_scheduler.step()\n print('Epoch: %d, LR: ' % epoch, end='')\n # print(tg_lr_scheduler.get_lr())\n for batch_idx, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.cuda(), targets.cuda()#to(device)\n tg_optimizer.zero_grad()\n curr_features, outputs = tg_model(inputs, is_feature=True)\n if iteration == start_iteration:\n loss = nn.CrossEntropyLoss(weight_per_class)(outputs, targets)\n else:\n ref_features, ref_outputs = ref_model(inputs, is_feature=True)\n # loss1 = nn.CosineEmbeddingLoss()(cur_features, ref_features.detach(), \\\n # torch.ones(inputs.shape[0]).to(device)) * lamda\n\n idx = np.where(targets.cpu().numpy() < old_scores.size(-1)) ### GET OLD features from the prev phase\n idx_new = np.where(targets.cpu().numpy() >= old_scores.size(-1))\n selected_ref_features = ref_features#[idx]#torch.cat((ref_features[idx], 0.15*ref_features[idx_new]), dim=0)\n selected_curr_features =curr_features#[idx]# torch.cat((curr_features[idx], 0.15*curr_features[idx_new]), dim=0)\n\n loss1 = 0.\n loss3 = 0.\n #if selected_curr_features.size(0) >= 64:\n # loss1 = gfk_nce.fit(selected_ref_features.detach(), selected_curr_features,\n # targets, max_class=(old_scores.size(-1)+new_scores.size(-1)))*lamda*L1_lambda\n loss2 = nn.CrossEntropyLoss(weight_per_class)(outputs, targets)#*0.8\n #loss2 = nca(outputs, targets)#*2\n loss1 = gfk.fit(selected_ref_features.detach(), selected_curr_features)*lamda\n #loss3, predicted, dist_ap, dist_an = criterion(curr_features, targets)\n\n\n # #################################################\n # #scores before scale, [-1, 1]\n outputs_bs = torch.cat((old_scores, new_scores), dim=1)\n assert(outputs_bs.size()==outputs.size())\n #print(\"outputs_bs:\", outputs_bs.size(), outputs_bs)\n #print(\"targets:\", targets.size(), targets)\n #get groud truth scores\n gt_index = torch.zeros(outputs_bs.size()).to(device)\n gt_index = gt_index.scatter(1, targets.view(-1,1), 1).ge(0.5)\n gt_scores = outputs_bs.masked_select(gt_index)\n #print(\"gt_index:\", gt_index.size(), gt_index)\n #print(\"gt_scores:\", gt_scores.size(), gt_scores)\n #get top-K scores on none gt classes\n none_gt_index = torch.zeros(outputs_bs.size()).to(device)\n none_gt_index = none_gt_index.scatter(1, targets.view(-1,1), 1).le(0.5)\n none_gt_scores = outputs_bs.masked_select(none_gt_index).reshape((outputs_bs.size(0), outputs.size(1)-1))\n #print(\"none_gt_index:\", none_gt_index.size(), none_gt_index)\n #print(\"none_gt_scores:\", none_gt_scores.size(), none_gt_scores)\n hard_scores = none_gt_scores.topk(K, dim=1)[0]\n #print(\"hard_scores:\", hard_scores.size(), hard_scores)\n #the index of hard samples, i.e., samples of old classes\n hard_index = targets.lt(num_old_classes)\n hard_num = torch.nonzero(hard_index).size(0)\n #print(\"hard examples size: \", hard_num)\n if hard_num > 0:\n gt_scores = gt_scores[hard_index].view(-1, 1).repeat(1, K)\n hard_scores = hard_scores[hard_index]\n assert(gt_scores.size() == hard_scores.size())\n assert(gt_scores.size(0) == hard_num)\n #print(\"hard example gt scores: \", gt_scores.size(), gt_scores)\n #print(\"hard example max novel scores: \", hard_scores.size(), hard_scores)\n loss3 = nn.MarginRankingLoss(margin=dist)(gt_scores.view(-1, 1), \\\n hard_scores.view(-1, 1), torch.ones(hard_num*K).to(device)) * lw_mr\n else:\n loss3 = torch.zeros(1).to(device)\n ################################################\n\n loss = loss1 + loss2 + loss3*0\n loss.backward()\n tg_optimizer.step()\n\n train_loss += loss.item()\n if iteration > start_iteration:\n #if selected_curr_features.size(0) > 80:\n train_loss1 += loss1.item()\n train_loss2 += loss2.item()\n train_loss3 += loss3.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n #break\n #if iteration == 0:\n # msg = 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % \\\n # (train_loss/(batch_idx+1), 100.*correct/total, correct, total)\n #else:\n # msg = 'Loss1: %.3f Loss2: %.3f Loss: %.3f | Acc: %.3f%% (%d/%d)' % \\\n # (loss1.item(), loss2.item(), train_loss/(batch_idx+1), 100.*correct/total, correct, total)\n #progress_bar(batch_idx, len(trainloader), msg)\n if iteration == start_iteration:\n print('Train set: {}, Train Loss: {:.4f} Acc: {:.4f}'.format(\\\n len(trainloader), train_loss/(batch_idx+1), 100.*correct/total))\n ## break\n else:\n print('Train set: {}, Train Loss1: {:.4f}, Train Loss2: {:.4f}, Train Loss3: {:.4f},\\\n Train Loss: {:.4f} Acc: {:.4f}'.format(len(trainloader), \\\n train_loss1/(batch_idx+1), train_loss2/(batch_idx+1), train_loss3/(batch_idx+1),\n train_loss/(batch_idx+1), 100.*correct/total))\n #\n # #eval\n # tg_model.eval()\n # test_loss = 0\n # correct = 0\n # total = 0\n # with torch.no_grad():\n # for batch_idx, (inputs, targets) in enumerate(testloader):\n # inputs, targets = inputs.to(device), targets.to(device)\n # outputs = tg_model(inputs)\n # loss = nn.CrossEntropyLoss(weight_per_class)(outputs, targets)\n #\n # test_loss += loss.item()\n # _, predicted = outputs.max(1)\n # total += targets.size(0)\n # correct += predicted.eq(targets).sum().item()\n #\n # #progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n # # % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n # print('Test set: {} Test Loss: {:.4f} Acc: {:.4f}'.format(\\\n # len(testloader), test_loss/(batch_idx+1), 100.*correct/total))\n \n if iteration > start_iteration:\n print(\"Removing register_forward_hook\")\n # handle_ref_features.remove()\n # handle_cur_features.remove()\n handle_old_scores_bs.remove()\n handle_new_scores_bs.remove()\n return tg_model","sub_path":"utils_incremental/incremental_train_and_eval_AMR_LF_GF.py","file_name":"incremental_train_and_eval_AMR_LF_GF.py","file_ext":"py","file_size_in_byte":10215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"424970955","text":"'''\n#1\ndef printArgs(x):print(x)\n\n#2\ndef adder(x,y):return x+y\n\nadder(1,2)\nadder('a','b')\nprint(adder([1,2,3],[4,5,6]))\n\n#3\n\ndef adder1(*args):\n first =args[0]\n for x in args[1:]:\n first +=x\n return first\n\nprint(adder1(1,2,3,4,5))\nprint(adder1('a','b','c'))\n'''\n\n'''\n#4\ndef adder2(good=1,bad=3,ugly=2 ):\n return good +bad+ugly\n\nprint(adder2(5,6,7))\n\ndef adder3(**kargs):\n l=list(kargs.values())\n first=l[0]\n for x in l[1:]:\n first+=x\n return first\n\nprint(adder3(a=1,b=2,c=3,d=5,e=6))\n'''\n\n'''\n#5\ndef copyDict(tempDic):\n newDic={}\n if tempDic:\n for k,v in tempDic.items():\n newDic[k]=v\n return newDic\n'''\n'''\n#6\n\ndef addDic(dic1,dic2):\n dic1.update(dic2)\n return dic1\n '''\n\n'''\n#8\n\ndef func(y):\n if y<=1:\n print(y,'not prime')\n else:\n x=y//2\n for x in range(2,y):\n if y%x==0:\n print(y,'has factor ',x)\n break\n\n else:\n print(y,'is prime')\n\n'''\n\n'''\n#9\nfrom math import sqrt \ndef newList1():\n l=[2,4,9,16,25]\n new = []\n for x in l:\n new.append(sqrt(x))\n return new\n\ndef newList2():\n l=[2,4,9,16,25]\n return list(map(sqrt,l))\n\ndef newList3():\n l=[2,4,9,16,25]\n return [sqrt(x) for x in l]\n\n'''\n\n#9\nimport mytimer,sys\nfrom math import sqrt \n\n\nreps=1000\nrepslist =range(reps)\n\n\ndef mathMod(): #最快\n for i in repslist:\n res = sqrt(i)\n return res\n\ndef powCall():\n for i in repslist:\n res = pow(i,.5)\n return res\n\ndef powExpr():\n for i in repslist:\n res = i ** .5\n return res\n\n\n\nprint(sys.version)\nfor tester in (mytimer.timer,mytimer.best):\n print('<{0}>'.format(tester.__name__))\n for test in (mathMod,powCall,powExpr):\n elapsed, result = tester(test)\n print('-'*35)\n print('{0}:{1:.5f} => {2}'.format(test.__name__,elapsed,result))\n \n \n'''\n结果\n3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 10:22:32) [MSC v.1900 64 bit (AMD64)]\n\n-----------------------------------\nmathMod:0.14781 => 31.606961258558215\n-----------------------------------\npowCall:0.27560 => 31.606961258558215\n-----------------------------------\npowExpr:0.19534 => 31.606961258558215\n\n-----------------------------------\nmathMod:0.00015 => 31.606961258558215\n-----------------------------------\npowCall:0.00027 => 31.606961258558215\n-----------------------------------\npowExpr:0.00019 => 31.606961258558215\n'''\n\n\n\n\n \n ","sub_path":"Learning Python/CH19/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"541022142","text":"import requests\n\n\ndef main():\n print(\"Logging in...\")\n session = requests.Session()\n url = \"https://minecraft-zh.gamepedia.com/api.php\"\n meta_token_param = {\n \"action\": \"query\",\n \"meta\": \"tokens\",\n \"type\": \"login\",\n \"format\": \"json\"\n }\n data = session.get(url=url, params=meta_token_param).json()\n login_token = data['query']['tokens']['logintoken']\n login_param = {\n \"action\": \"login\",\n \"lgname\": \"MysticNebula70@Homura\",\n \"lgpassword\": \"j8ih3qkg1smjao81tstgd1l0ah03lveb\",\n \"format\": \"json\",\n \"lgtoken\": login_token\n }\n data = session.post(url, login_param).json()\n login_param = {}\n meta_token_param = {\n \"action\": \"query\",\n \"meta\": \"tokens\",\n \"type\": \"csrf\",\n \"format\": \"json\",\n }\n data = session.get(url=url, params=meta_token_param).json()\n csrf_token = data['query']['tokens']['csrftoken']\n page = input(\"Page name: \")\n page_query_param = {\n \"action\": \"query\",\n \"prop\": \"revisions\",\n \"titles\": page,\n \"rvlimit\": 1,\n \"format\": \"json\"\n }\n data = session.get(url=url, params=page_query_param).json()\n pages = data['query']['pages']\n if '-1' in pages.keys():\n print(\"Error: Page does not exist.\")\n else:\n for k, v in pages.items():\n revision = v['revisions']\n revision = revision[0]\n print(f\"User: {revision['user']}\\nSummary: {revision['comment']}\")\n if input(\"Undo this? [y/n]\") == 'y':\n reason = input(\"Undo reason: \")\n revid = revision['revid']\n begin_rev = revision['parentid']\n undo_param = {\n \"action\": \"edit\",\n \"title\": page,\n \"undo\": revid,\n \"undoafter\": begin_rev,\n \"token\": csrf_token,\n \"format\": \"json\"\n }\n if reason != \"\":\n undo_param.update({\"summary\": reason})\n data = session.post(url, undo_param).json()\n print(\"Undone revision.\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"undo-zh.py","file_name":"undo-zh.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"24551717","text":"# Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.\n# \n# Example:\n# \n# Input: 1->2->4, 1->3->4\n# Output: 1->1->2->3->4->4\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef mergeTwoLists(l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n curr = None\n hd = curr\n while l1 and l2:\n if l1.val <= l2.val:\n if not hd:\n hd = l1\n curr = hd\n else:\n curr.next = l1\n curr = curr.next\n l1 = l1.next\n else:\n if not hd:\n hd = l2\n curr = hd\n else:\n curr.next = l2\n curr = curr.next\n l2 = l2.next\n\n if l1:\n if not hd:\n hd = l1\n else:\n curr.next = l1\n \n if l2:\n if not hd:\n hd = l2\n else:\n curr.next = l2\n\n return hd\n\n\na = ListNode(1)\na.next = ListNode(2)\na.next.next = ListNode(4)\n\nb = ListNode(1)\nb.next = ListNode(3)\nb.next.next = ListNode(4)\n\nc = mergeTwoLists(a,b)\n\ncurr = c\nwhile curr:\n print( str(curr.val) )\n curr = curr.next\n\na = None\n\nb = ListNode(1)\n\nc = mergeTwoLists(a,b)\n\ncurr = c\nwhile curr:\n print( str(curr.val) )\n curr = curr.next\n","sub_path":"python/leetcode_questions/merge_two_lists.py","file_name":"merge_two_lists.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"547699416","text":"# encoding:utf-8\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@File : face_detect.py\n@Time : 2020/09/24 21:47:34\n@Author : guo.zhiwei\n@Contact : zhiweiguo1991@163.com\n@Desc : None\n'''\n\n# here put the import lib\nimport sys\nsys.path.append('../')\nimport os \nimport dlib \nimport cv2\nimport numpy as np \nimport torch\nfrom collections import OrderedDict\nfrom process.augmentation import *\nimport torch.nn.functional as F\n\n# 获取不同规格的活体检测模型\ndef get_fas_model(model_name, num_class, is_first_bn):\n if model_name == 'baseline':\n from model.model_baseline import Net\n elif model_name == 'model_A':\n from model.FaceBagNet_model_A import Net\n elif model_name == 'model_B':\n from model.FaceBagNet_model_B import Net\n elif model_name == 'model_C':\n from model.FaceBagNet_model_C import Net\n\n net = Net(num_class=num_class,is_first_bn=is_first_bn)\n return net\n\n\n\nclass Face(object):\n def __init__(self, predictor_model_path, fas_model_path, fas_model_name, rec_model, img_size=100):\n super(Face, self).__init__()\n self.img_size = img_size\n self.detector = dlib.get_frontal_face_detector()\n self.predictor = self.load_predictor(predictor_model_path)\n self.fas_model = self.load_fas_model(fas_model_name, fas_model_path)\n self.rec_model = dlib.face_recognition_model_v1(rec_model)\n self.face_features = self.get_face_feature_lib()\n\n def load_fas_model(self, model_name, model_path):\n fas_model = get_fas_model(model_name=model_name, num_class=2, is_first_bn=True)\n if torch.cuda.is_available():\n state_dict = torch.load(model_path, map_location='cuda')\n else:\n state_dict = torch.load(model_path, map_location='cpu')\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n fas_model.load_state_dict(new_state_dict)\n if torch.cuda.is_available():\n net = fas_model.cuda()\n return fas_model\n\n def load_predictor(self, model_path):\n return dlib.shape_predictor(model_path)\n\n def show_landmarks(self, img, shape, show=True, save=True):\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n for i in range(68):\n cv2.putText(img, str(i), (shape.part(i).x, shape.part(i).y), \n cv2.FONT_HERSHEY_DUPLEX, 0.3, (0, 0, 255), 1,\n cv2.LINE_AA)\n # cv2.drawKeypoints(img, (sp.part(i).x, sp.part(i).y),img, [0, 0, 255])\n title = 'img_landmarks'\n if save:\n filename = title + '.jpg'\n cv2.imwrite(filename, img)\n print(\"save img_landmarks.jpg ok !!!\")\n # os.system(\"open %s\"%(filename)) \n if show:\n cv2.imshow(title, img)\n cv2.waitKey(0)\n cv2.destroyWindow(title)\n\n def get_landmarks(self, img):\n dets = self.detector(img, 1) # 检测人脸\n if len(dets) == 1: \n shape = self.predictor(img, dets[0]) # 关键点提取\n #print(\"Computing descriptor on aligned image ..\")\n return shape\n else:\n print(\"No face !!!\")\n return None\n\n def face_alignment(self, img, landmarks):\n #人脸对齐 face alignment\n face_img = dlib.get_face_chip(img, landmarks, size=self.img_size)\n #self.show_landmarks(img, shape, show=False, save=True) \n return face_img \n\n def get_face_status(self, face_img, landmarks):\n #h, w = face_img.shape[0], face_img.shape[1]\n #landmarks = np.matrix([[p.x, p.y] for p in landmarks.parts()]) # 得到68*2的np\n #x_min, x_max = np.min(landmarks[:,0]), np.max(landmarks[:,0])\n #y_min, y_max = np.min(landmarks[:,1]), np.max(landmarks[:,1])\n #new_size = max(x_max-x_min+20, y_max-y_min+30)\n #face_img = face_img[max(0, y_min-25):min(h, y_max+5), max(0, x_min-10):min(w, x_max+10), :]\n face_img = color_augumentor(face_img, target_shape=(64, 64, 3), is_infer=True)\n num = len(face_img)\n face_img = np.concatenate(face_img, axis=0)\n face_img = np.transpose(face_img, (0, 3, 1, 2))\n face_img = face_img.astype(np.float32)\n face_img = face_img.reshape([num, 3, 64, 64])\n face_img = face_img / 255.0\n input_image = torch.FloatTensor(face_img)\n #input_image = input_image.unsqueeze(0)\n if torch.cuda.is_available():\n input_image = input_image.cuda()\n with torch.no_grad():\n logit,_,_ = self.fas_model(input_image)\n logit = logit.view(1,num,2)\n logit = torch.mean(logit, dim = 1, keepdim = False)\n prob = F.softmax(logit, 1)\n return np.argmax(prob.detach().cpu().numpy())\n \n def compute_face_feature(self, img):\n landmarks = self.get_landmarks(img)\n face_img = self.face_alignment(img, landmarks)\n #计算对齐后人脸的128维特征向量\n face_feature = self.rec_model.compute_face_descriptor(face_img)\n return np.array(face_feature)\n\n def get_face_feature_lib(self, img_dir='./face_lib'):\n face_features = []\n # 当前库中只有两个人\n for i in range(2):\n img_path = img_dir + '/' + str(i+1) + '.jpg'\n img = cv2.imread(img_path)\n feature = self.compute_face_feature(img)\n face_features.append(feature)\n return face_features\n\n def compute_distence(self, a, b):\n a_norm = np.linalg.norm(a)\n b_norm = np.linalg.norm(b)\n return 1 - np.dot(a, b.T)/(a_norm * b_norm)\n\n def face_compare(self, feature):\n # 采用余弦距离计算\n dis_threshold = 0.1\n min_dist = 2\n person_idx = -1\n for i in range(len(self.face_features)):\n dist = self.compute_distence(feature, self.face_features[i])\n if dist < dis_threshold and dist < min_dist:\n min_dist = dist\n person_idx = i\n return person_idx\n \n def face_recognition(self, img):\n landmarks = self.get_landmarks(img)\n face_img = self.face_alignment(img, landmarks)\n face_status = self.get_face_status(face_img, landmarks)\n if face_status == 0:\n print('非活体人脸!!!')\n return \n #计算对齐后人脸的128维特征向量\n face_feature = self.rec_model.compute_face_descriptor(face_img)\n face_feature = np.array(face_feature)\n person_idx = self.face_compare(face_feature)\n if person_idx >= 0:\n print(\"当前图像中的人是库中person_{} .\".format(person_idx+1))\n else:\n print(\"当前图像中的人不在人脸库中!!!\")\n\n\nif __name__ == '__main__':\n img_size = 150\n predictor_model_path = './shape_predictor_68_face_landmarks.dat'\n fas_model_path = './global_min_acer_model.pth'\n rec_model = './dlib_face_recognition_resnet_model_v1.dat'\n face_obj = Face(predictor_model_path=predictor_model_path, \n fas_model_path=fas_model_path, \n fas_model_name='model_A', \n rec_model=rec_model,\n img_size=img_size)\n img_path = './test_imgs/101.jpg' \n img = cv2.imread(img_path)\n '''\n landmarks = face_obj.get_landmarks(img)\n face_img = face_obj.face_alignment(img, landmarks)\n face_status = face_obj.get_face_status(face_img, landmarks)\n face_res = '活体人脸' if face_status == 1 else '假体人脸'\n print(face_res)\n '''\n face_obj.face_recognition(img)\n\n # 调用摄像头\n cap = cv2.VideoCapture(0)\n while True:\n ret, frame = cap.read()\n face_obj.face_recognition(frame)\n if cv2.waitKey(10) == 'q':\n break\n cap.release()\n cv2.desdroyAllWindows()\n\n\n","sub_path":"practical_course/week_20/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":7951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"637981685","text":"import numpy as np\n\ndef randInitializeWeights(L_in, L_out):\n \"\"\"randomly initializes the weights of a layer with L_in incoming connections and L_out outgoing\n connections.\n\n Note that W should be set to a matrix of size(L_out, 1 + L_in) as the column row of W handles the \"bias\" terms\n \"\"\"\n\n # ====================== YOUR CODE HERE ======================\n # Instructions: Initialize W randomly so that we break the symmetry while\n # training the neural network.\n #\n # Note: The first row of W corresponds to the parameters for the bias units\n #\n\n ep = np.sqrt(6)/np.sqrt(L_in+L_out)\n print('range of random values should be: ',-ep,' : ',ep)\n \n W = np.random.random([L_out,L_in+1]) \n W = W*2*ep-ep\n\n print('range of random values is: ',np.min(W),' : ',np.max(W))\n# =========================================================================\n\n return W\n\n","sub_path":"ex4/randInitializeWeights.py","file_name":"randInitializeWeights.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"60980268","text":"#!/usr/bin/env python\n\n\n# Import libraries\nimport os\nimport pysam\nimport argparse\nfrom random import random\nimport errno\nimport time\n\n\n\n############################################################\n# #\n# Functions #\n# #\n############################################################\n\n# check if folder exists\ndef make_sure_path_exists(path):\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n\n# CIGAR parse function\ndef readLength_CIGAR(cigar):\n \"\"\"\n Reads the CIGAR string to take it into consideration when defining\n the read length\n \"\"\"\n\n digitHold=\"\"\n cigarChars=\"\"\n numList=[]\n for char_c in cigar:\n if char_c.isdigit():\n digitHold+=str(char_c)\n else:\n numList.append(int(digitHold))\n cigarChars+=char_c\n digitHold=\"\"\n\n result=-1 #subtract one because of first position\n for char in range(0, len(cigarChars)):\n if not cigarChars[char] in [\"I\",\"D\"]:\n result+=numList[char]\n\n return result\n\n\n\n# Remove temporary files\ndef removeTemp(bamid):\n filesInDir=os.listdir(os.getcwd())\n for f in filesInDir:\n if bamid in f:\n os.remove(f)\n\n\n\n\n############################################################\n# #\n# MAIN #\n# #\n############################################################\n\n# Input arguments\nparser = argparse.ArgumentParser(description=\"\"\"Returns the last base \n coordinates for mNET-seq reads. It considers the library to be \n secondstranded, with the last base sequenced in read 2 and the \n strand information that of read 1. Result will be \n filename_sorted.bam file and respective index.\"\"\")\n\n\nparser.add_argument('-f', '--filepath', metavar='filepath', nargs='+',\n help='One or more file paths, separated by spaces.')\nparser.add_argument('-s', '--filename', metavar='filename', nargs='+',\n help=\"\"\"New file prefixes (no extension), separated by \n spaces. In the same number as the file paths.\"\"\")\nparser.add_argument('-d','--outdir', dest='outDir', nargs='?', \n default=\"./\", help=\"Output directory. Defaults to './'.\")\nargs = parser.parse_args()\n\nfiles = args.filepath\nfilenames = args.filename\noutdir=args.outDir\n\nif len(files)!=len(filenames):\n raise NameError('Number of files and new file names disagree.')\n\nmake_sure_path_exists(outdir)\n\n\n# Running for each bam file supplied\nfor bam, name in zip(files, filenames):\n start_time = time.time()\n bamid=str(int(random()*10000)) # id for the temp files\n\n #bam to sam\n infileHeader = pysam.AlignmentFile(bam, mode='rb').header\n infile = pysam.AlignmentFile(bam, mode='rb', header=infileHeader)\n outfile = pysam.AlignmentFile(name+\"_temp\"+bamid+\".sam\", \"wh\", header=infileHeader, template=infile)\n for s in infile:\n outfile.write(s)\n infile.close()\n outfile.close()\n\n\n result=open(name+\"_snr_temp\"+bamid+\".sam\",'w')\n\n\n # Get coordinates\n with open(name+\"_temp\"+bamid+\".sam\") as infile:\n for line in infile:\n if not line.startswith(\"@\"):\n line=line.strip(\"\\n\").split(\"\\t\")\n\n # added filtering for Soft Clipped reads\n if not \"I\" in line[5] and not \"D\" in line[5] and not \"S\" in line[5]:\n\n # Distinguish flag\n if line[1]==\"0\":\n #forward\n add_to_start=readLength_CIGAR(line[5])\n line[3]=str(int(line[3])+add_to_start)\n line[9]=line[9][-1]\n line[10]=line[10][-1]\n line[5]=\"1M\"\n\n elif line[1]==\"16\":\n #reverse\n line[9]=line[9][0]\n line[10]=line[10][0]\n line[5]=\"1M\"\n\n else:\n print(line)\n\n\n\n result.write(\"\\t\".join(line)+\"\\n\")\n \n else: #write header\n result.write(line)\n\n result.close()\n \n\n \n #new sam to bam, then sort and index\n infile = pysam.AlignmentFile(name+\"_snr_temp\"+bamid+\".sam\", \"r\")\n outfile = pysam.AlignmentFile(name+\"_snr_temp\"+bamid+\".bam\", \"wb\", template=infile)\n for s in infile:\n outfile.write(s)\n infile.close()\n outfile.close()\n\n #sorted_file=pysam.sort(name+\"_snr_temp\"+bamid+\".bam\", outdir+name+\"_sorted\")\n sorted_file=pysam.sort('-o', outdir+name+\"_sorted.bam\", name+\"_snr_temp\"+bamid+\".bam\")\n sorted_file=pysam.index(outdir+name+\"_sorted.bam\")\n \n removeTemp(bamid)\n\n print(name+\" done!\")\n print(\"--- %s seconds ---\" % round(time.time() - start_time, 2))\n\nprint(\"Finished!\")\n","sub_path":"get_SNR_bam_merged_reads.py","file_name":"get_SNR_bam_merged_reads.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"75467394","text":"# task_4.py\n# Глава 3, задача 4.\n# А вот задача посложнее. Напишите на псевдокоде алгоритм игры, в которой случайное число от 1 до 100 за­\n# гадывает человек, а отгадывает компьютер. Прежде чем приступать к решению, задумайтесь над тем, какой\n# должна быть оптимальная стратегия отадывания. Если алгоритм на псевдокоде будет удачным, попробуйт��\n# реализовать игру на Pythoп.\n\nimport random\n\nprint(\n \"\"\"\n=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=\n\n *** Я отгадаю твоё число от 1 до 100! ***\n Отвечай на мои вопросы только символами: <, > или =, если я угадал!\n\n Начинаем!\n\n=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=\n \"\"\"\n)\n\nnumber = random.randint(1, 100)\nhint = \"\"\n\nwhile hint != \"=\":\n print(\"Я думаю, это число\", number)\n hint = input(\"Я прав? \")\n\n if hint == \"<\":\n number = random.randint(1, number)\n elif hint == \">\":\n number = random.randint(number, 100)\n else:\n continue\n\nprint(\"\\n*** Я снова показал своё совершенство перед жалкими людишками! ***\")\n\ninput(\"\\n\\nНажмите Enter, чтобы выйти.\")","sub_path":"chapter_3/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"204361680","text":"import threading\nimport socket\nimport sys\nimport pickle\nimport queue\n\n# lock to serialize console output\nlock = threading.Lock()\n\nclass A:\n a=\"asdasd\"\n\ndef peerlisten():\n print(\"Peer listen\")\n server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n server_socket.bind(('0.0.0.0',1000))\n server_socket.listen(1)\n\n while True:\n print (\"Waiting for commands\")\n (client_socket, client_address) = server_socket.accept()\n t = threading.Thread(target=peerhandler,args=(client_socket,))\n t.start()\n t.join()\n\n server_socket.close()\n\ndef peerhandler(client_socket=None):\n client_data = client_socket.recv(1024)\n a = pickle.loads(client_data)\n print (\"GOT COMMAND FROM \"+ a.a)\n b = A()\n client_socket.send(pickle.dumps(b, -1))\n client_socket.shutdown(2)\n client_socket.close()\n\ndef connectpeer():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((\"127.0.0.1\", 1000))\n a = A()\n s.send(pickle.dumps(a, -1))\n\n srv_data = s.recv(1024)\n b = pickle.loads(srv_data)\n print(b.a)\n s.close()\n\nt = threading.Thread(target=peerlisten)\nt.start()\nt = threading.Thread(target=connectpeer)\nt.start()\n","sub_path":"Source/Peer.py","file_name":"Peer.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"173862997","text":"r=int(input(\"enter number of rows:\"))\nfor i in range(r):\n for l in range(0,r-i):\n print(end=\" \")\n for j in range(0,i+1):\n if j==0 or i==0:\n c=1\n print(c,end=\" \")\n else:\n c=(int)(c*(i-j+1)/j)\n print(c,end=\" \")\n print() \n \n","sub_path":"pascal.py","file_name":"pascal.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"218164367","text":"from big_ol_pile_of_manim_imports import *\n\nclass Shapes(Scene):\n CONFIG = {\"radius\" : np.arange(2,5,1),\n \"symbols\": [r\"\\mars\", r\"\\earth\", r\"\\mercury\"]}\n\n def construct(self):\n print(\"Start\")\n ALLCIRCS = [Circle(radius=num_rad)for num_rad in self.radius]\n ALLSYMBOLS= [TexMobject(stin).scale(6) for stin in self.symbols]\n dot = Dot()\n dot2 = Dot()\n self.add(dot,dot2)\n for n, shape in enumerate(ALLCIRCS):\n self.play(Transform(dot,ALLCIRCS[n]),Transform(dot2,ALLSYMBOLS[n]), run_time=1)\n self.wait(2)\n\n\nif __name__ == \"__main__\":\n module_name = os.path.basename(__file__)\n command = \"python3.7 -m manim -pl -o earth_sofi --leave_progress_bars \" + module_name + \" Shapes \"\n os.system(command)\n\n\n\n","sub_path":"Tutorial/n0_shapes_with_enimuerate.py","file_name":"n0_shapes_with_enimuerate.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"600588219","text":"import random\nfrom cs1graphics import *\nimport itertools\n\nimg_path = 'images/'\n\nsuit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']\nface_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']\nvalue = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n\n\n\nbj_board = Canvas(600, 400, 'dark green', 'Black Jack 101')\n\n\n\"\"\"\nDefine the Card class\n\"\"\"\nclass Card:\n def __init__(self, suit, face, value, image, state):\n self.suit = suit\n self.value = value\n self.face = face\n self.image = image\n self.state = state\n\n\ndef create_deck(number = 1):\n \"\"\"\n Create a list(\"deck\") of all 52 cards, shuffle them and return the list.\n The list 'deck' have to include Card objects\n A Card is represented by a object with four attributes: the face, the suit, value, state, and the image object\n First, Have to define class 'Card'\n \"\"\"\n deck = []\n for suit, face in itertools.product(suit_names, face_names):\n if face == \"Ace\":\n value = 11\n elif face in ['Jack', 'Queen', 'King']:\n value = 10\n else:\n value = int(face)\n img = Image(img_path+suit+\"_\"+face + \".png\")\n state = True\n card = Card(suit, face, value, img, state)\n deck.append(card)\n random.shuffle(deck)\n return deck\n\n\ndef hand_value(hand):\n \"\"\"\n hand is a list including card objects\n Compute the value of the cards in the list \"hand\"\n \"\"\"\n val = 0 \n for card in hand:\n val += card.value\n\n return val\n\n\ndef card_string(card):\n \"\"\"\n Parameter \"card\" is a Card object\n Return a nice string to represent a card\n (sucn as \"a King of Spades\" or \"an Ace of Diamonds\")\n \"\"\"\n article = \"\"\n if card.face == 'Ace':\n article = \"an \"\n elif card.face in ['Jack', 'Queen', 'King']:\n article = \"a \"\n return article + card.face + \" of \" + card.suit\n\n\ndef ask_yesno(prompt):\n \"\"\"\n Display the text prompt and let's the user enter a string.\n If the user enters \"y\", the function returns \"True\",\n and if the user enters \"n\", the function returns \"False\".\n If the user enters anything else, the function prints \"I beg your pardon!\", and asks again,\n\trepreting this until the user has entered a correct string.\n \"\"\"\n more = input(prompt)\n while more not in [\"y\", \"n\"]:\n print(\"I beg your pardon!\")\n more = input(prompt)\n return more == 'y'\n\n\ndef draw_card(dealer,player):\n \"\"\"\n This funuction add the cards of dealer and player to canvas, bj_board.\n If the state of each Card object is false, then you have to show the hidden card image(Back.png).\n\tThe dealer's first card is hidden state.\n The parameter dealer and player are List objects including Card Objects.\n\n The start position of dealer's card is (100,100).\n The start position of player's card is (100,300).\n\n You can use the following methods for positioning images and text:\n Image() Object, Text() Object, moveTo() method, setDepth() method.\n\n You should use help function -\n help('cs1graphics.Image') -> about Image(), moveTo(), setDepth()\n help('cs1graphics.Text') -> about Text(),moveTo(), setDepth()\n \"\"\"\n # hidden_img = Image(img_path+\"back.png\")\n depth = 100\n x0,y0 = 100,100\n x1,y1 = 100,300\n ix = 30\n\n bj_board.clear()\n for card in dealer:\n if card.state:\n card.image.moveTo(x0, y0)\n card.image.setDepth(depth)\n bj_board.add(card.image)\n else:\n img = Image(img_path+\"Back.png\")\n img.moveTo(x0, y0)\n img.setDepth(depth)\n bj_board.add(img)\n x0 += ix\n \n for card in player:\n if card.state:\n card.image.moveTo(x1, y1)\n card.image.setDepth(depth)\n bj_board.add(card.image)\n else:\n img = Image(img_path+\"back.png\")\n img.moveTo(x1, y1)\n img.setDepth(depth)\n bj_board.add(img)\n x1 += ix\n\n\ndef main():\n\n deck = []\n\n while True:\n # prompt for starting a new game and create a deck\n print (\"Welcome to Black Jack 101!\\n\")\n if len(deck) < 12:\n deck = create_deck()\n\n # create two hands of dealer and player\n dealer = []\n player = []\n\n # initial two dealings\n card = deck.pop()\n print (\"You are dealt \" + card_string(card))\n player.append(card)\n\n card = deck.pop()\n print (\"Dealer is dealt a hidden card\")\n card.state=False\n dealer.append(card)\n\n card = deck.pop()\n print (\"You are dealt \" + card_string(card))\n player.append(card)\n\n card = deck.pop()\n print (\"Dealer is dealt \" + card_string(card))\n dealer.append(card)\n\n print (\"Your total is\", hand_value(player))\n draw_card(dealer,player)\n\n\n # player's turn to draw cards\n while hand_value(player) < 21 and ask_yesno(\"Would you like another card? (y/n) \"):\n # draw a card for the player\n card = deck.pop()\n print (\"You are dealt \" + card_string(card))\n player.append(card)\n print (\"Your total is\", hand_value(player))\n\n draw_card(dealer,player)\n # if the player's score is over 21, the player loses immediately.\n if hand_value(player) > 21:\n print (\"You went over 21! You lost.\")\n dealer[0].state = True\n draw_card(dealer,player)\n else:\n # draw cards for the dealer while the dealer's score is less than 17\n print (\"\\nThe dealer's hidden card was \" + card_string(dealer[0]))\n while hand_value(dealer) < 17:\n card = deck.pop()\n print (\"Dealer is dealt \" + card_string(card))\n dealer.append(card)\n print (\"The dealer's total is\", hand_value(dealer))\n\n dealer[0].state = True\n draw_card(dealer,player)\n # summary\n player_total = hand_value(player)\n dealer_total = hand_value(dealer)\n print (\"\\nYour total is\", player_total)\n print (\"The dealer's total is\", dealer_total)\n\n if dealer_total > 21:\n print (\"The dealer went over 21! You win!\")\n else:\n if player_total > dealer_total:\n print (\"You win!\")\n elif player_total < dealer_total:\n print (\"You lost!\")\n else:\n print (\"You have a tie!\")\n\n if not ask_yesno(\"\\nPlay another round? (y/n) \"):\n bj_board.close()\n break\n\nmain()\n","sub_path":"lab9/memento.py","file_name":"memento.py","file_ext":"py","file_size_in_byte":6668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"324202455","text":"#!/usr/bin/python3.4\n__author__ = 'ale'\n\n# Descrizione\n# ===========\n# Python script che esegue principalmente la funzione di testare\n# la velocità di internet e di salvare i dati in un file di log.\n# Si divide quindi in 3 fase:\n# - eseguire speedtest\n# - parse the output\n# - aggiunge l'output al file di log.\n#\n# Dependency: python 3.4\n# speedtest-cli - https://github.com/sivel/speedtest-\n#\n\nimport subprocess\nimport re\nimport time\nimport os\n\n\n#CONFIGURA LA POSIZIONE DELLE CARTELLE in variabili GLOBALI\n#posizione dello script\nMYPATH = \"/home/ale/Documents/Projects/monitor-internetband/\"\n#posizione del file\nSPEEDTEST_PATH = \"/usr/local/bin/\"\n\n\n#get data e ora and print it\nmytime = (time.strftime(\"%d/%m/%Y\\t%H:%M:%S\"))\nprint(mytime+\"\\n-----------------\")\n\n#RUN THE COMMAND\nprint(\"Testing the internet speed...\")\ntry:\n mycommand = subprocess.check_output([SPEEDTEST_PATH+\"speedtest\", \"--simple\"], stderr=subprocess.STDOUT)\n #converti il file da bytes-like a stringa\n mycommand = mycommand.decode(\"utf-8\")\n\n #DEBUG MODE: fake commnad\n #mycommand = \"b'Ping: 12.96 ms\\nDownload: 1.17 Mbits/s\\nUpload: 0.79 Mbits/s\\n'\" #FAKE COMMAND\n #mycommand = subprocess.check_output([\"cat\", \"baabasd asdasd\"], stderr=subprocess.STDOUT) # exit with 1\n\nexcept Exception:\n print(\"!!! Problema riscontrato nel test di connessione a internet !!!\")\n #aggiunta di una finta stringa, in caso di problema di connessione fa il parsi di questa stringa.\n mycommand = 'Ping: 2000.00 ms\\nDownload: 0.00 Mbits/s\\nUpload: 0.00 Mbits/s\\n'\n\n\n#stampa a video i risultati del test\nprint(mycommand)\n\n#CAPTURE THE OUTPUT TEXT\nprint(\"parsing data...\")\n#find Ping\nping = re.search(r\"Ping: (.*) ms\", mycommand).group(1)\n#find Download\ndownload = re.search(r\"Download: (.*) Mbits\", mycommand).group(1)\n#find Upload\nupload = re.search(r\"Upload: (.*) Mbits\", mycommand).group(1)\n\n#LEGGI FILE\nprint(\"updating the log file...\")\ntry:\n myfile = open(os.path.join(MYPATH+\"speed_log.txt\"), \"a\")\n myfile.write(mytime+\"\\t\"+ping+\"\\t\"+download+\"\\t\"+upload+\"\\n\")\n myfile.close()\n print(\"DONE\")\nexcept IOError:\n raise IOError(\"OPSS, can't open/find the file??? \")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"467302513","text":"'''\nThis programming challenge is a classic interview question for software engineers:\ngiven a string, find the longest sub-string that contains, at most, two characters.\n\nAuthor: /u/Regul\nFormal Inputs & Outputs\nInput Description\n\nThrough standard console input, you will be given a string to search, which only\ncontains lower-case alphabet letters.\nOutput Description\n\nSimply print the longest sub-string of the given string that contains, at most, two\nunique characters. If you find multiple sub-strings that match the description,\nprint the last sub-string (furthest to the right).\nSample Inputs\n\nabbccc\nabcabcabcabccc\nqwertyytrewq\n\nSample Outputs\n\nbbccc\nbccc\ntyyt\n'''\n\n\ndef sub_string(strng):\n indexes = []\n totals = []\n accum = 1\n temp = 0\n count = 0\n\n for x in range(0, len(strng)):\n if count == 0:\n temp = x\n try:\n one = strng[x]\n next = strng[x+1]\n if strng[x] != strng[x + 1]:\n indexes.append(temp)\n totals.append(accum)\n accum = 1\n count = 0\n continue\n except IndexError:\n indexes.append(temp)\n totals.append(accum)\n accum = 1\n count = 0\n continue\n if count == 0:\n temp = x\n count += 1\n accum += 1\n\n '''pull out largest value, if more than one, \n furthest right.'''\n # largest series\n max_series = (max(totals))\n\n # index of the largest series\n mx = []\n for x in range(len(totals)):\n if totals[x] == max(totals):\n mx.append(x)\n indx = mx[-1]\n #indx = totals.index(max_series)\n\n # indexes of series either side\n try:\n indexes_of_interest = indexes[indx-1], indexes[indx], indexes[indx+1]\n indexes_of_interest = list(indexes_of_interest)\n except IndexError:\n indexes_of_interest = indexes[indx-1], indexes[indx]\n\n # if string totals all the same\n if totals[1:] == totals[:-1]:\n indexes_of_interest = indexes[-2:]\n\n output = ''\n # if len index_of_interest is 2\n if len(indexes_of_interest) == 2:\n for x in indexes_of_interest:\n num = totals[indexes.index(x)]\n output += strng[x:x + num]\n # if first == last\n elif strng[indexes_of_interest[0]] == strng[indexes_of_interest[2]]:\n for x in indexes_of_interest:\n num = totals[indexes.index(x)]\n output += strng[x:x + num]\n elif strng[indexes_of_interest[0]] < strng[indexes_of_interest[2]]:\n indexes_of_interest.pop(2)\n for x in indexes_of_interest:\n num = totals[indexes.index(x)]\n output += strng[x:x + num]\n else:\n indexes_of_interest.pop(0)\n for x in indexes_of_interest:\n num = totals[indexes.index(x)]\n output += strng[x:x + num]\n return output\n\n\nif __name__ == '__main__':\n\n candidates = ['aabbc', 'abcabcabcabccc', 'abbccc', 'qwertyytrewq', 'abcdef']\n output = []\n\n for candidate in candidates:\n ans = sub_string(candidate)\n output.append(ans)\n\n print(output)","sub_path":"albums/3/challenge127_easy/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"196460681","text":"# MGEAR is under the terms of the MIT License\n\n# Copyright (c) 2016 Jeremie Passerin, Miquel Campos\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Author: Jeremie Passerin geerem@hotmail.com www.jeremiepasserin.com\n# Author: Miquel Campos hello@miquel-campos.com www.miquel-campos.com\n# Date: 2016 / 10 / 10\n\n\nimport unittest\nimport pymel.core as pm\nimport mgear.maya.rigbits.channelWrangler as cw\nimport mgear.maya.attribute as att\n\n\nclass cwTestCase(unittest.TestCase):\n\n def setUp(self):\n self.config = { \"movePolicy\":\"merge\",\n \"proxyPolicy\":\"index\",\n \"map\":[ [\"shoulder_ik\", \"armUI_R0_ctl\", \"armUI_L0_ctl\", 0],\n [\"shoulder_rotRef\", \"armUI_R0_ctl\", \"armUI_L0_ctl\", 0],\n [\"shoulder_rotRef\", \"armUI_R1_ctl\", \"armUI_L0_ctl\", 0]]}\n\n self.pcs = pm.polyCube(n=\"armUI_R0_ctl\")\n self.pcs2 = pm.polyCube(n=\"armUI_R1_ctl\")\n self.pct = pm.polyCube(n=\"armUI_L0_ctl\")\n att.addAttribute(self.pcs[0], \"shoulder_ik\", \"double\", 0, minValue=0, maxValue=1 )\n ch2 = att.addAttribute(self.pcs[0], \"shoulder_rotRef\", \"double\", 0, minValue=0, maxValue=1 )\n ch3 = att.addAttribute(self.pcs2[0], \"shoulder_rotRef\", \"double\", 0, minValue=0, maxValue=1 )\n pm.connectAttr(ch2, self.pcs[0].ty)\n pm.connectAttr(ch3, self.pcs2[0].ty)\n\n\n def tearDown(self):\n pm.delete(self.pcs)\n pm.delete(self.pcs2)\n pm.delete(self.pct)\n\n def test_applyChannelConfig(self):\n self.assertIsNone(cw._applyChannelConfig(self.config))\n\n # def test_applyChannelConfigFromFile(self):\n # filePath = \"\"\n # self.assertIsNone(cw.applyChannelConfig(filePath))\n\n\n\n\nif __name__=='__main__':\n unittest.main(exit=False)\n","sub_path":"tests/test_rigbits_channelWrangler.py","file_name":"test_rigbits_channelWrangler.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"471287056","text":"#! /usr/bin/env python\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport data_helpers\nfrom tensorflow.contrib import learn\nfrom predict import predict_from_trained\n\nif __name__ == '__main__':\n\n # Parameters\n # ==================================================\n\n # Data Parameters\n tf.flags.DEFINE_string(\"positive_data_file\", \"\", \"Data source for the positive data.\")\n tf.flags.DEFINE_string(\"negative_data_file\", \"\", \"Data source for the positive data.\")\n tf.flags.DEFINE_string(\"tsv_data_file\", \"\",\n \"TSV data source where first column is data and second is label. (Default: '')\")\n\n # Eval Parameters\n tf.flags.DEFINE_integer(\"batch_size\", 64, \"Batch Size (default: 64)\")\n tf.flags.DEFINE_string(\"checkpoint_dir\", \"\", \"Checkpoint directory from training run\")\n\n # Misc Parameters\n tf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\n tf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n tf.flags.DEFINE_boolean(\"calculate_pr\", False, \"Calculate Precision recall, pr curve\")\n\n FLAGS = tf.flags.FLAGS\n tf.flags.DEFINE_string(\"prediction_file\", os.path.join(FLAGS.checkpoint_dir, \"..\", \"prediction.csv\"),\n \"Predicted output\")\n FLAGS._parse_flags()\n print(\"\\nParameters:\")\n for attr, value in sorted(FLAGS.__flags.items()):\n print(\"{}={}\".format(attr.upper(), value))\n print(\"\")\n\n if FLAGS.tsv_data_file is not \"\":\n x_raw, y_2column = data_helpers.load_from_tsv(FLAGS.tsv_data_file)\n else:\n x_raw, y_2column = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)\n y_test = np.argmax(y_2column, axis=1)\n\n # Map data into vocabulary\n vocab_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"vocab\")\n vocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\n x_test = np.array(list(vocab_processor.transform(x_raw)))\n\n print(\"\\nEvaluating...\\n\")\n\n all_predictions, all_probabilities = predict_from_trained(x_test, FLAGS)\n # Print accuracy if y_test is defined\n if y_test is not None:\n correct_predictions = float(sum(all_predictions == y_test))\n print(\"Total number of test examples: {}\".format(len(y_test)))\n print(\"Accuracy: {:g}\".format(correct_predictions / float(len(y_test))))\n\n # Save the evaluation to a csv\n predictions_human_readable = np.column_stack((all_predictions,\n y_test,\n [\"{}\".format(probability[1]) for probability in all_probabilities],\n np.array(x_raw)))\n output_filename = FLAGS.prediction_file\n print(\"Saving evaluation to {0}\".format(output_filename))\n with open(output_filename, 'w', encoding='utf-8') as f:\n f.writelines('{0}\\t{1}\\t{2}\\t{3}\\n'.format(int(round(float(i[0]))), int(float(i[1])), i[2], i[3]) for i in\n predictions_human_readable)\n\n if FLAGS.calculate_pr:\n from sklearn.metrics import classification_report, precision_recall_curve\n\n pr_report = classification_report(y_true=y_test, y_pred=all_predictions, digits=5)\n with open(output_filename + '.pr.txt', 'w') as f:\n f.write(pr_report)\n print(pr_report)\n\n import matplotlib.pyplot as plt\n\n precision, recall, _ = precision_recall_curve(y_test, all_probabilities[:, 1])\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n plt.title('2-class Precision-Recall curve')\n plt.step(recall, precision, color='b', alpha=0.2,\n where='post')\n plt.fill_between(recall, precision, step='post', alpha=0.2,\n color='b')\n plt.savefig(output_filename + 'prcurve.png')\n","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"336729332","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^home/$', views.home, name='home'),\n url(r'^contact/$', views.contact, name='contact'),\n url(r'^download/$', views.download, name='download'),\n url(r'^connect/$', views.connect, name='connect'),\n url(r'^front/$', views.front, name='front'),\n url(r'^tweet/$', views.tweet, name='tweet'),\n url(r'^reply_and_retweet/$', views.reply_and_retweet, name='reply_and_retweet'),\n url(r'^filtering/$', views.filtering, name='filtering'),\n url(r'^lists/$', views.lists, name='lists'),\n url(r'^rss_reader/$', views.rss_reader, name='rss_reader'),\n\n]\n","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"607112176","text":"# SPDX-License-Identifier: Apache-2.0\n#\n# Copyright (C) 2015, ARM Limited and contributors.\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.\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, WITHOUT\n# 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 logging\nimport os\nimport re\nimport webbrowser\n\nfrom . import System\n\nclass Workload(object):\n \"\"\"\n Base class for Android related workloads\n \"\"\"\n\n _packages = None\n _availables = {}\n\n def __init__(self, test_env):\n \"\"\"\n Initialized workloads available on the specified test environment\n\n test_env: target test environmen\n \"\"\"\n self._te = test_env\n self._target = test_env.target\n self._log = logging.getLogger('Workload')\n\n # Set of data reported in output of each run\n self.trace_file = None\n self.nrg_report = None\n\n def _adb(self, cmd):\n return 'adb -s {} {}'.format(self._target.adb_name, cmd)\n\n @classmethod\n def _subclasses(cls):\n \"\"\"\n Recursively get all subclasses\n \"\"\"\n nodes = cls.__subclasses__()\n return nodes + [child for node in nodes for child in node._subclasses()]\n\n @classmethod\n def _check_availables(cls, test_env):\n \"\"\"\n List the supported android workloads which are available on the target\n \"\"\"\n\n _log = logging.getLogger('Workload')\n\n # Getting the list of installed packages\n cls._packages = test_env.target.list_packages()\n _log.debug('Packages:\\n%s', cls._packages)\n\n _log.debug('Building list of available workloads...')\n for sc in Workload._subclasses():\n _log.debug('Checking workload [%s]...', sc.__name__)\n if sc.package in cls._packages or sc.package == '':\n cls._availables[sc.__name__.lower()] = sc\n\n _log.info('Supported workloads available on target:')\n _log.info(' %s', ', '.join(cls._availables.keys()))\n\n @classmethod\n def getInstance(cls, test_env, name):\n \"\"\"\n Get a reference to the specified Android workload\n \"\"\"\n\n # Initialize list of available workloads\n if cls._packages is None:\n cls._check_availables(test_env)\n\n if name.lower() not in cls._availables:\n msg = 'Workload [{}] not available on target'.format(name)\n raise ValueError(msg)\n\n return cls._availables[name.lower()](test_env)\n\n def run(self, out_dir, collect='',\n **kwargs):\n raise RuntimeError('Not implemeted')\n\n def tracingStart(self):\n if 'ftrace' in self.collect and 'systrace' in self.collect:\n msg = 'ftrace and systrace cannot be used at the same time'\n raise ValueError(msg)\n # Start FTrace\n if 'ftrace' in self.collect:\n self.trace_file = os.path.join(self.out_dir, 'trace.dat')\n self._log.info('FTrace START')\n self._te.ftrace.start()\n # Start Systrace (mutually exclusive with ftrace)\n elif 'systrace' in self.collect:\n self.trace_file = os.path.join(self.out_dir, 'trace.html')\n # Get the systrace time\n match = re.search(r'systrace_([0-9]+)', self.collect)\n self._trace_time = match.group(1) if match else None\n self._log.info('Systrace START')\n self._systrace_output = System.systrace_start(\n self._te, self.trace_file, self._trace_time)\n # Initialize energy meter results\n if 'energy' in self.collect and self._te.emeter:\n self._te.emeter.reset()\n self._log.info('Energy meter STARTED')\n\n def tracingStop(self):\n # Collect energy meter results\n if 'energy' in self.collect and self._te.emeter:\n self.nrg_report = self._te.emeter.report(self.out_dir)\n self._log.info('Energy meter STOPPED')\n # Stop FTrace\n if 'ftrace' in self.collect:\n self._te.ftrace.stop()\n self._log.info('FTrace STOP')\n self._te.ftrace.get_trace(self.trace_file)\n # Stop Systrace (mutually exclusive with ftrace)\n elif 'systrace' in self.collect:\n if not self._systrace_output:\n self._log.warning('Systrace is not running!')\n else:\n self._log.info('Waiting systrace report [%s]...',\n self.trace_file)\n if self._trace_time is None:\n # Systrace expects \n self._systrace_output.sendline('')\n self._systrace_output.wait()\n # Dump a platform description\n self._te.platform_dump(self.out_dir)\n\n def traceShow(self):\n \"\"\"\n Open the collected trace using the most appropriate native viewer.\n\n The native viewer depends on the specified trace format:\n - ftrace: open using kernelshark\n - systrace: open using a browser\n\n In both cases the native viewer is assumed to be available in the host\n machine.\n \"\"\"\n\n if 'ftrace' in self.collect:\n os.popen(\"kernelshark {}\".format(self.trace_file))\n return\n\n if 'systrace' in self.collect:\n webbrowser.open(self.trace_file)\n return\n\n self._log.warning('No trace collected since last run')\n\n# vim :set tabstop=4 shiftwidth=4 expandtab textwidth=80\n","sub_path":"libs/utils/android/workload.py","file_name":"workload.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"530932368","text":"\n'''\nan armstrong number is a number where the sum of each digit raised to the power\nof the number of digits of the original number is equal to the original number\n\n145\n\n1^3\n4^3\n5^3\n=145\n\n5643\n5^4\n6^4\n4^4\n3^4\n=5643\n\n-find the sum of the total digits powered\n-power numbers\n-compare final sum to original number\n-given a number, find its digits\n----------------------------------------------------------------------------------------------------------------\n'''\ndef is_armstrong(number):\n\tstrumber = str(number)\n\tnumberofdigits = len(strumber)\n\tsum = 0\n\n\n\tfor strdigit in strumber:\n\t\tdigit = int(strdigit)\n\t\tsum = sum + (digit**numberofdigits)\n\n\tif(sum == int(strumber)):\n\t\treturn True\n\telse:\n\t\treturn False\nfor x in range(100000000000000000000):\n\tarmstrong = is_armstrong(x)\n\tif (armstrong == True):\n\t\tprint(str(x) + \"is an armstrong number\")\n","sub_path":"armstrong.py","file_name":"armstrong.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"227276475","text":"################################################################################\n#\n# Package : AlphaPy\n# Module : system\n# Created : July 11, 2013\n#\n# Copyright 2017 ScottFree Analytics LLC\n# Mark Conway & Robert D. Scott II\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\n\n#\n# Imports\n#\n\nfrom alphapy.frame import Frame\nfrom alphapy.frame import frame_name\nfrom alphapy.frame import write_frame\nfrom alphapy.globals import Orders\nfrom alphapy.globals import SSEP\nfrom alphapy.market_variables import vexec\nfrom alphapy.space import Space\nfrom alphapy.portfolio import Trade\n\nimport logging\nfrom pandas import DataFrame\n\n\n#\n# Initialize logger\n#\n\nlogger = logging.getLogger(__name__)\n\n\n#\n# Class System\n#\n\nclass System(object):\n \"\"\"Create a new system. All systems are stored in\n ``System.systems``. Duplicate names are not allowed.\n\n Parameters\n ----------\n name : str\n The system name.\n longentry : str\n Name of the conditional feature for a long entry.\n shortentry : str, optional\n Name of the conditional feature for a short entry.\n longexit : str, optional\n Name of the conditional feature for a long exit.\n shortexit : str, optional\n Name of the conditional feature for a short exit.\n holdperiod : int, optional\n Holding period of a position.\n scale : bool, optional\n Add to a position for a signal in the same direction.\n\n Attributes\n ----------\n systems : dict\n Class variable for storing all known systems\n\n Examples\n --------\n \n >>> System('closer', hc, lc)\n\n \"\"\"\n\n # class variable to track all systems\n\n systems = {}\n\n # __new__\n \n def __new__(cls,\n name,\n longentry,\n shortentry = None,\n longexit = None,\n shortexit = None,\n holdperiod = 0,\n scale = False):\n # create system name\n if name not in System.systems:\n return super(System, cls).__new__(cls)\n else:\n logger.info(\"System %s already exists\", name)\n \n # __init__\n \n def __init__(self,\n name,\n longentry,\n shortentry = None,\n longexit = None,\n shortexit = None,\n holdperiod = 0,\n scale = False):\n # initialization\n self.name = name\n self.longentry = longentry\n self.shortentry = shortentry\n self.longexit = longexit\n self.shortexit = shortexit\n self.holdperiod = holdperiod\n self.scale = scale\n # add system to systems list\n System.systems[name] = self\n \n # __str__\n\n def __str__(self):\n return self.name\n\n\n#\n# Function long_short\n#\n\ndef long_short(system, name, space, quantity):\n r\"\"\"Run a long/short system.\n\n A long/short system is always in the market. At any given\n time, either a long position is active, or a short position\n is active.\n\n Parameters\n ----------\n system : alphapy.System\n The long/short system to run.\n name : str\n The symbol to trade.\n space : alphapy.Space\n Namespace of instrument prices.\n quantity : float\n The amount of the ``name`` to trade, e.g., number of shares\n\n Returns\n -------\n tradelist : list\n List of trade entries and exits.\n\n Other Parameters\n ----------------\n Frame.frames : dict\n All of the data frames containing price data.\n\n \"\"\"\n # extract the system parameters\n longentry = system.longentry\n shortentry = system.shortentry\n longexit = system.longexit\n shortexit = system.shortexit\n holdperiod = system.holdperiod\n scale = system.scale\n # price frame\n pf = Frame.frames[frame_name(name, space)].df\n # initialize the trade list\n tradelist = []\n # evaluate the long and short events\n if longentry:\n vexec(pf, longentry)\n if shortentry:\n vexec(pf, shortentry)\n if longexit:\n vexec(pf, longexit)\n if shortexit:\n vexec(pf, shortexit)\n # generate trade file\n inlong = False\n inshort = False\n h = 0\n p = 0\n q = quantity\n for dt, row in pf.iterrows():\n # evaluate entry and exit conditions\n lerow = None\n if longentry:\n lerow = row[longentry]\n serow = None\n if shortentry:\n serow = row[shortentry]\n lxrow = None\n if longexit:\n lxrow = row[longexit]\n sxrow = None\n if shortexit:\n sxrow = row[shortexit]\n # get closing price\n c = row['close']\n # process the long and short events\n if lerow:\n if p < 0:\n # short active, so exit short\n tradelist.append((dt, [name, Orders.sx, -p, c]))\n inshort = False\n h = 0\n p = 0\n if p == 0 or scale:\n # go long (again)\n tradelist.append((dt, [name, Orders.le, q, c]))\n inlong = True\n p = p + q\n elif serow:\n if p > 0:\n # long active, so exit long\n tradelist.append((dt, [name, Orders.lx, -p, c]))\n inlong = False\n h = 0\n p = 0\n if p == 0 or scale:\n # go short (again)\n tradelist.append((dt, [name, Orders.se, -q, c]))\n inshort = True\n p = p - q\n # check exit conditions\n if inlong and h > 0 and lxrow:\n # long active, so exit long\n tradelist.append((dt, [name, Orders.lx, -p, c]))\n inlong = False\n h = 0\n p = 0\n if inshort and h > 0 and sxrow:\n # short active, so exit short\n tradelist.append((dt, [name, Orders.sx, -p, c]))\n inshort = False\n h = 0\n p = 0\n # if a holding period was given, then check for exit\n if holdperiod > 0 and h >= holdperiod:\n if inlong:\n tradelist.append((dt, [name, Orders.lh, -p, c]))\n inlong = False\n if inshort:\n tradelist.append((dt, [name, Orders.sh, -p, c]))\n inshort = False\n h = 0\n p = 0\n # increment the hold counter\n if inlong or inshort:\n h += 1\n return tradelist\n\n\n#\n# Function open_range_breakout\n#\n\ndef open_range_breakout(name, space, quantity, t1=3, t2=12):\n r\"\"\"Run an Opening Range Breakout (ORB) system.\n\n An ORB system is an intraday strategy that waits for price to\n \"break out\" in a certain direction after establishing an\n initial High-Low range. The timing of the trade is either\n time-based (e.g., 30 minutes after the Open) or price-based\n (e.g., 20% of the average daily range). Either the position\n is held until the end of the trading day, or the position is\n closed with a stop loss (e.g., the other side of the opening\n range).\n\n Parameters\n ----------\n name : str\n The symbol to trade.\n space : alphapy.Space\n Namespace of instrument prices.\n quantity : float\n The amount of the ``name`` to trade, e.g., number of shares\n\n Returns\n -------\n tradelist : list\n List of trade entries and exits.\n\n Other Parameters\n ----------------\n Frame.frames : dict\n All of the data frames containing price data.\n\n \"\"\"\n # price frame\n pf = Frame.frames[frame_name(name, space)].df\n # initialize the trade list\n tradelist = []\n # generate trade file\n for dt, row in pf.iterrows():\n # extract data from row\n bar_number = row['bar_number']\n h = row['high']\n l = row['low']\n c = row['close']\n end_of_day = row['end_of_day']\n # open range breakout\n if bar_number == 0:\n # new day\n traded = False\n inlong = False\n inshort = False\n hh = h\n ll = l\n elif bar_number < t1:\n # set opening range\n if h > hh:\n hh = h\n if l < ll:\n ll = l\n else:\n if not traded and bar_number < t2:\n # trigger trade\n if h > hh:\n # long breakout triggers\n tradelist.append((dt, [name, Orders.le, quantity, hh]))\n inlong = True\n traded = True\n if l < ll and not traded:\n # short breakout triggers\n tradelist.append((dt, [name, Orders.se, -quantity, ll]))\n inshort = True\n traded = True\n # test stop loss\n if inlong and l < ll:\n tradelist.append((dt, [name, Orders.lx, -quantity, ll]))\n inlong = False\n if inshort and h > hh:\n tradelist.append((dt, [name, Orders.sx, quantity, hh]))\n inshort = False\n # exit any positions at the end of the day\n if inlong and end_of_day:\n # long active, so exit long\n tradelist.append((dt, [name, Orders.lx, -quantity, c]))\n if inshort and end_of_day:\n # short active, so exit short\n tradelist.append((dt, [name, Orders.sx, quantity, c]))\n return tradelist\n\n\n#\n# Function run_system\n#\n\ndef run_system(model,\n system,\n group,\n system_params=None,\n quantity = 1):\n r\"\"\"Run a system for a given group, creating a trades frame.\n\n Parameters\n ----------\n model : alphapy.Model\n The model object with specifications.\n system : alphapy.System or str\n The system to run, either a long/short system or a local one\n identified by function name, e.g., 'open_range_breakout'.\n group : alphapy.Group\n The group of symbols to test.\n system_params : list, optional\n The parameters for the given system.\n quantity : float, optional\n The amount to trade for each symbol, e.g., number of shares\n\n Returns\n -------\n tf : pandas.DataFrame\n All of the trades for this ``group``.\n\n \"\"\"\n\n if system.__class__ == str:\n system_name = system\n else:\n system_name = system.name\n\n logger.info(\"Generating Trades for System %s\", system_name)\n\n # Unpack the model data.\n\n directory = model.specs['directory']\n extension = model.specs['extension']\n separator = model.specs['separator']\n\n # Extract the group information.\n\n gname = group.name\n gmembers = group.members\n gspace = group.space\n\n # Run the system for each member of the group\n\n gtlist = []\n for symbol in gmembers:\n # generate the trades for this member\n if system.__class__ == str:\n try:\n tlist = globals()[system_name](symbol, gspace, quantity,\n *system_params)\n except:\n logger.info(\"Could not execute system for %s\", symbol)\n else:\n # call default long/short system\n tlist = long_short(system, symbol, gspace, quantity)\n if tlist:\n # create the local trades frame\n df = DataFrame.from_items(tlist, orient='index', columns=Trade.states)\n # add trades to global trade list\n for item in tlist:\n gtlist.append(item)\n else:\n logger.info(\"No trades for symbol %s\", symbol)\n\n # Create group trades frame\n\n tf = None\n if gtlist:\n tspace = Space(system_name, \"trades\", group.space.fractal)\n gtlist = sorted(gtlist, key=lambda x: x[0])\n tf = DataFrame.from_items(gtlist, orient='index', columns=Trade.states)\n tfname = frame_name(gname, tspace)\n system_dir = SSEP.join([directory, 'systems'])\n write_frame(tf, system_dir, tfname, extension, separator,\n index=True, index_label='date')\n del tspace\n else:\n logger.info(\"No trades were found\")\n\n # Return trades frame\n return tf\n","sub_path":"alphapy/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":12781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"321173829","text":"\"\"\"\n(1) This code shows averages and scales of discrete uniform distribution.\n(2) Compare discrete uniform distributions for the number of probablity variables.\n\"\"\"\n\n\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style('darkgrid')\n\n\ndef averages_and_scales():\n # Poisson distribution settings\n mean = 1\n trials = 1000\n poisson_rand = np.random.poisson(mean, trials)\n\n # show averages and scales\n print(\"--- sum of random numbers ---\")\n print(\"sum: {}\".format(np.sum(poisson_rand)))\n print()\n print(\"--- averages ---\")\n print(\"maximum: {}\".format(np.max(poisson_rand)))\n print(\"minimum: {}\".format(np.min(poisson_rand)))\n print(\"median : {}\".format(np.median(poisson_rand)))\n print(\"mean : {}\".format(np.mean(poisson_rand)))\n print(\"mode : {}\".format(sp.stats.mode(poisson_rand)))\n print()\n print(\"--- scales ---\")\n print(\"variance : {}\".format(np.var(poisson_rand)))\n print(\"standard deviation: {}\".format(np.std(poisson_rand)))\n print(\"skewness : {}\".format(sp.stats.skew(poisson_rand)))\n print(\"kurtosis : {}\".format(sp.stats.kurtosis(poisson_rand)))\n print()\n\n # plot Poisson distribution\n plt.title(\"Poisson distribution\")\n plt.hist(poisson_rand, bins=max(poisson_rand), normed=True, label=\"$\\lambda = $\"+str(mean))\n plt.xlabel(\"Probablity variables\")\n plt.ylabel(\"Probablity\")\n plt.legend()\n plt.show()\n\n\ndef comparison():\n # Poisson distribution settings\n mean = np.array([1, 5, 10, 20])\n trials = 1000000\n pr_dist = np.array([np.random.poisson(m, trials) for m in mean])\n\n # plot Poisson distribution and comparison\n for i in range(len(mean)):\n plt.hist(pr_dist[i], bins=max(pr_dist[i]), alpha=0.7, normed=True, label=\"$\\lambda$ = \"+str(mean[i]))\n plt.title(\"Poisson distribution\")\n plt.xlabel(\"Probablity variables\")\n plt.ylabel(\"Probablity\")\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n averages_and_scales()\n comparison()\n","sub_path":"probablity_distributions/discrete_distribution/poisson_distribution.py","file_name":"poisson_distribution.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"627304081","text":"\n# PyQt import\nfrom PyQt5.QtCore import QFile, QTextStream\n\n# Project import\nfrom labnote.resources import resources\n\n\ndef set_style_sheet(object, file):\n # Set style sheet\n qss = QFile(file)\n qss.open(QFile.ReadOnly)\n style = QTextStream(qss).readAll()\n object.setStyleSheet(style)\n qss.close()\n","sub_path":"labnote/core/stylesheet.py","file_name":"stylesheet.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"637617818","text":"\"\"\"\nExport your keynote file to HTML. Pass the keynote file (to extract the\npresentation notes) and the extracted HTML directory to this script, and it\nwill attempt to inject the presenter notes it extracted from the Keynote file\ninto the HTML.\n\nOnly tested on Keynote '09, Chrome 24.0.1312.56\n\"\"\"\n\nimport os\nimport random\nimport string\nimport subprocess\nimport sys\n\nfrom lxml import etree, html\n\n\ndef extract_notes(keynote_file):\n # keynote file is a giant compressed xml file - uncompress it\n tempdir = '/tmp/keynote_thing.{0}.xml'.format(\n \"\".join(random.sample(string.ascii_letters, 10)))\n os.mkdir(tempdir)\n subprocess.check_call(['unzip', keynote_file, '-d', tempdir])\n xml = etree.parse(tempdir + '/index.apxl')\n root = xml.getroot()\n\n # get all the presenter note xml elements\n notes = root.xpath('.//key:notes//sf:text-body', namespaces=root.nsmap)\n\n # replace all the funky keynote tags with html tags - I am stupid and don't\n # know xslt, so do this the slow way\n sf_namespace = '{{{0}}}'.format(root.nsmap['sf'])\n\n def replace_node(node):\n if node.tag.startswith(sf_namespace):\n node.tag = node.tag.replace(sf_namespace, '')\n if node.tag == 'link':\n node.tag = 'a'\n else:\n if node.tag == 'text-body':\n node.tag = 'div'\n node.attrib.clear()\n node.nsmap.clear()\n\n for child in node.getchildren():\n replace_node(child)\n\n for idx, note in enumerate(notes):\n replace_node(note)\n note.attrib['id'] = 'slidePresenterNotes{0}'.format(idx)\n note.attrib['class'] = 'presenterNotes'\n\n return notes\n\n\ndef inject_js(html_file, presenter_notes):\n doc = html.parse(html_file)\n head = doc.xpath(\"//head\")[0]\n body = doc.xpath(\"//body\")[0]\n\n style = etree.Element(\"style\")\n style.text = \"\"\"\n #presenterNotes {\n margin: auto 0; width: 15%; background-color: #CCCCCC;\n padding: 0 5px; color: black; border: 1px solid black;\"\n }\n #presenterNotesSlideNumber {\n font-weight: bold;\n }\n \"\"\"\n\n notes = etree.Element(\"div\", **{\"id\": \"presenterNotes\"})\n notes.append(etree.Element(\"div\", **{\"id\": \"presenterNotesSlideNumber\"}))\n notes.extend(presenter_notes)\n\n handler = etree.Element(\"script\")\n handler.text = \"\"\"\n function injectPresenterNotes () {\n\n injection_self = this;\n injection_self.presenterNotes = document.getElementById(\n \"presenterNotes\");\n\n injection_self.lastSlideNumber = -1;\n function updatePresenterNotes () {\n if (currentEventTimeline != injection_self.lastSlideNumber) {\n // hide other slide notes\n injection_self.presenterNotes.select(\n '[class=\"presenterNotes\"]').invoke('hide');\n // display the notes for the slide that is visible\n $('slidePresenterNotes' + currentEventTimeline).show();\n // update the slide number label\n $('presenterNotesSlideNumber').update(\n \"Presenter notes for Slide \" + (currentEventTimeline + 1));\n injection_self.lastSlideNumber = currentEventTimeline;\n }\n };\n\n updatePresenterNotes();\n // update every 100 ms because it could take this number a little while\n // to change\n setInterval(updatePresenterNotes, 100);\n }\n \"\"\"\n\n head.append(style)\n head.append(handler)\n body.insert(0, notes)\n body.attrib['onload'] = \"; \".join(\n [x for x in (body.attrib.get('onload', '').rstrip(';'),\n \"injectPresenterNotes();\") if x])\n\n doc.write(html_file, method=\"html\")\n\n\ndef modify_all_html(html_dir, presenter_notes):\n find_output = subprocess.check_output(\n ['find', html_dir, '-name', '*.html'])\n all_html = [name for name in find_output.split('\\n') if name]\n for html_file in all_html:\n inject_js(html_file, presenter_notes)\n\n\npresenter_notes = extract_notes(sys.argv[1])\nmodify_all_html(sys.argv[2], presenter_notes)\n","sub_path":"dockerized-gists/4644918/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"112456105","text":"# Uses python3\nimport sys\nfrom collections import namedtuple\nfrom operator import attrgetter\n\nSegment = namedtuple('Segment', 'start end')\n\ndef optimal_points(segments):\n points = []\n #write your code here\n segments_s = sorted(segments, key=attrgetter(\"end\"))\n s_end_prev = 0\n for s in segments_s:\n if s_end_prev == 0:\n s_end_prev = s.end\n points.append(s_end_prev)\n else:\n if s_end_prev < s.start:\n s_end_prev = s.end\n points.append(s_end_prev)\n return set(points)\n\nif __name__ == '__main__':\n #input = \"3 1 3 2 5 3 6\" #sys.stdin.read()\n # input = \"4 4 7 1 3 2 5 5 6\"\n input = sys.stdin.read()\n n, *data = map(int, input.split())\n segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))\n points = optimal_points(segments)\n print(len(points))\n for p in points:\n print(p, end=' ')\n","sub_path":"covering_segments.py","file_name":"covering_segments.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"488612959","text":"# 文件对象的缓冲\n'''\n问题: 文件写入硬件设备,使用系统调用,\nI/O操作时间很长,减少I/O操作次数\n文件通常使用缓冲区 (凑够块大小才使用缓冲)\n缓冲区大小 4096\n全缓冲,open 函数 buffering 设置为大于一整数n,n为缓冲区大小\n行缓冲,open buffering 设置为1\n无缓冲 open buffering 设置为0\n'''\nf = open('demo.txt','w')\n\nf.write('+' * 2045)\nf.close()\n\n# 全缓冲修改缓冲区大小 tail -f demo2.txt 监测文件\nf2 = open('demo2.txt','w',buffering=2048)\nf2.write('a' * 2047)\nf2.write('aqie')\nf2.close()\n\n\n# 行缓冲\nf3 = open('demo3.txt','w',buffering=1)\nf3.write('aqie123')\nf3.write('\\n')\nf3.close()\n\n\n","sub_path":"ln4/filecache.py","file_name":"filecache.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"323052440","text":"import sys\nfrom PyQt5.QtWidgets import (QApplication, QProgressDialog)\nfrom PyQt5.QtCore import Qt\nimport time\n \n \ndef show_progress(max=100):\n progress = QProgressDialog(\"Doing stuff...[0/0]\", \"Abort\", 0, max, None)\n progress.setWindowModality(Qt.WindowModal)\n progress.setModal(True)\n progress.show()\n for i in range(max + 1):\n progress.setValue(i)\n progress.setLabelText(\"Doing stuff...[{}/{}]\".format(\n i, progress.maximum()))\n if progress.wasCanceled():\n break\n time.sleep(0.05)\n \n \nif __name__ == '__main__':\n app = QApplication(sys.argv)\n show_progress(max=210)","sub_path":"source/example/progress_bar_example3.py","file_name":"progress_bar_example3.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"30393482","text":"# python 2\n# from lib2to3.fixes import fix_set_literal http://python-future.org/futurize.html?highlight=set\n# builtins\nfrom unittest import TestCase, main\n# custom\ntry:\n from utilities import change_settings_for_testing\n from classpropertyparser import ClassPropertyParser\n from cssbuilder import CSSBuilder\nexcept ImportError:\n from blowdrycss.utilities import change_settings_for_testing\n from blowdrycss.classpropertyparser import ClassPropertyParser\n from blowdrycss.cssbuilder import CSSBuilder\n\ntry:\n import settings.blowdrycss_settings as settings # development case\nexcept ImportError:\n try:\n import blowdrycss_settings as settings # development \"python setup.py test\" case\n except ImportError:\n import blowdrycss.blowdrycss_settings as settings # packaged deployment case\n\n__author__ = 'chad nelson'\n__project__ = 'blowdrycss'\n\n\n# Change settings directories for testing\nchange_settings_for_testing()\n\nclass TestCSSStyleBuilder(TestCase):\n def test_get_css_text_sets(self):\n # TODO: Check back at bitbucket cssutils to see if a resolution is available.\n # 'rem' units are raise an error in cssutils.css.CSSStyleRule.\n # https://bitbucket.org/cthedot/cssutils/issues/60/using-units-of-rem-produces-an-invalid\n class_set = {\n 'cue-x5_0p', 'margin-top-10', 'bgc-h000', 'hide', 'margin-20', 'padding-top-10', 'height-200', 'padding-10',\n 'valign-middle', 'b', 'width-150', 'width-50', 'font-size-48', 'c-blue', 'margin-top-50px',\n 'text-align-center', 'height-50px', 'height-150px', 'bold', 'color-hfff', 'padding-b1 a5 c1% e5',\n 'margin-1a% 10x% 3q% 1mp3', 'font-size-1_23rem'\n }\n expected_clean_set = {\n 'margin-top-10', 'margin-20', 'padding-top-10', 'height-200', 'padding-10', 'width-150', 'width-50',\n 'font-size-48',\n 'c-blue', 'height-150px', 'bgc-h000', 'bold', 'color-hfff', 'height-50px', 'text-align-center',\n 'margin-top-50px', 'valign-middle', 'font-size-1_23rem'\n }\n expected_removed_set = {\n 'cue-x5_0p (cssutils invalid property value: x5.0%)',\n 'hide (property_name not found in property_alias_dict.)',\n 'padding-b1 a5 c1% e5 (Only a-z, 0-9, \"_\", and \"-\" are allowed in class name.)',\n 'b (property_name not found in property_alias_dict.)',\n 'margin-1a% 10x% 3q% 1mp3 (Only a-z, 0-9, \"_\", and \"-\" are allowed in class name.)'\n }\n property_parser = ClassPropertyParser(class_set=class_set)\n style_builder = CSSBuilder(property_parser=property_parser)\n self.assertTrue(style_builder.property_parser.class_set == expected_clean_set,\n msg=style_builder.property_parser.class_set)\n self.assertTrue(style_builder.property_parser.removed_class_set == expected_removed_set,\n msg=style_builder.property_parser.removed_class_set)\n\n def test_get_css_text_output_convert_to_em(self):\n class_set = {\n 'margin-top-10', 'bgc-h000', 'hide', 'margin-20', 'padding-top-10', 'height-200', 'padding-10',\n 'valign-middle', 'b', 'width-150', 'width-50', 'font-size-48', 'c-blue', 'margin-top-50px',\n 'text-align-center', 'height-50px', 'height-150px', 'bold', 'color-hfff'\n }\n expected_properties = [\n 'background-color: #000', 'vertical-align: middle', 'color: blue', 'margin-top: 3.125em',\n 'text-align: center', 'height: 3.125em', 'height: 9.375em', 'font-weight: bold', 'color: #fff'\n ]\n property_parser = ClassPropertyParser(class_set=class_set)\n css_builder = CSSBuilder(property_parser=property_parser)\n css_text = css_builder.get_css_text().decode('utf-8')\n\n for expected in expected_properties:\n self.assertTrue(expected in css_text, msg=expected + ' and ' + css_text)\n if expected in css_text:\n css_text = css_text.replace(expected, '')\n\n def test_get_css_text_output_no_conversion(self):\n class_set = {\n 'margin-top-10', 'bgc-h000', 'hide', 'margin-20', 'padding-top-10', 'height-200', 'padding-10',\n 'valign-middle', 'b', 'width-150', 'width-50', 'font-size-48', 'c-blue', 'margin-top-50px',\n 'text-align-center', 'height-50px', 'height-150px', 'bold', 'color-hfff',\n }\n expected_properties = [\n 'background-color: #000', 'vertical-align: middle', 'color: blue', 'margin-top: 50px',\n 'text-align: center', 'height: 50px', 'height: 150px', 'font-weight: bold', 'color: #fff',\n ]\n settings.use_em = False\n property_parser = ClassPropertyParser(class_set=class_set)\n css_builder = CSSBuilder(property_parser=property_parser)\n css_text = css_builder.get_css_text().decode('utf-8')\n\n for expected in expected_properties:\n self.assertTrue(expected in css_text, msg=expected + ' and ' + css_text)\n if expected in css_text:\n css_text = css_text.replace(expected, '')\n\n settings.use_em = True\n\nif __name__ == '__main__':\n main()\n","sub_path":"blowdrycss/unit_tests/test_CSSBuilder.py","file_name":"test_CSSBuilder.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"61640188","text":"import os\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test\n\n# allow setup.py to be run from any path\n# os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\n\nPATH = os.path.join(os.path.dirname(__file__), 'README.md')\n\n\ntry:\n import pypandoc\n README = pypandoc.convert(PATH, 'rst')\nexcept ImportError:\n README = open(PATH).read()\n\n\nclass Test(test):\n user_options = [\n ('test-labels=', 'l', \"Test labels to pass to runner.py test\"),\n ('djtest-args=', 'a', \"Arguments to pass to runner.py test\"),\n ]\n\n def initialize_options(self):\n test.initialize_options(self)\n self.test_labels = 'tests'\n self.djtest_args = ''\n\n def finalize_options(self):\n test.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n from tests.runner import main\n\n test_labels = self.test_labels.split()\n djtest_args = self.djtest_args.split()\n main(['runner.py', 'test'] + test_labels + djtest_args)\n\n\nsetup(\n name='dj-uri.js',\n version='0.0.1',\n packages=find_packages(),\n include_package_data=True,\n license='MIT License',\n long_description=README,\n url='https://github.com/rpkilby/dj-uri.js',\n author='Ryan P Kilby',\n author_email='rpkilby@ncsu.edu',\n\n cmdclass={\n 'test': Test,\n },\n\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Topic :: Internet :: WWW/HTTP',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"466067918","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfor num in np.arange(1,7):\n img = cv2.imread('/Users/zhangmin/PycharmProjects/carno_demo/img/{}.jpg'.format(num))[100:450,0:960]\n #cv2.imshow('img',img)\n\n #灰度化\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n #高斯滤波\n gaussian = cv2.GaussianBlur(gray, (5, 5), 0, 0, cv2.BORDER_DEFAULT)\n #cv2.imshow('gaussian',gaussian)\n #中值滤波\n median = cv2.medianBlur(gaussian, 3)\n #cv2.imshow('median',median)\n #sobel边缘检测\n sobel = cv2.Sobel(median, cv2.CV_8U, 1, 0, ksize = 3)\n #cv2.imshow('sobel',sobel)\n #二值化\n ret, binary = cv2.threshold(sobel, 100, 255, cv2.THRESH_BINARY)\n #cv2.imshow('binary',binary)\n\n kernel_1 = cv2.getStructuringElement(cv2.MORPH_RECT,(33, 1))\n kernel_2 = cv2.getStructuringElement(cv2.MORPH_RECT,(27, 21))\n #膨胀图像\n dilated = cv2.dilate(binary,kernel_1)\n #显示膨胀后的图像\n #cv2.imshow(\"dilated\",dilated);\n\n #腐蚀图像\n eroded = cv2.erode(dilated,kernel_2)\n #显示腐蚀后的图像\n #cv2.imshow(\"eroded\",eroded);\n\n #膨胀图像,第二次\n dilated = cv2.dilate(eroded,kernel_2)\n #显示膨胀后的图像\n #cv2.imshow(\"dilated_{}\".format(num),dilated);\n\n def find_carno_regin(dilated):\n region = []\n #查找轮廓\n im, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n\n for i in np.arange(len(contours)):\n cnt = contours[i]\n # 计算该轮廓的面积\n area = cv2.contourArea(cnt)\n\n # 面积小的都筛选掉\n if (area < 3000 or area > 8000):\n continue\n\n # 轮廓近似,作用很小\n #epsilon = 0.001 * cv2.arcLength(cnt, True)\n #approx = cv2.approxPolyDP(cnt, epsilon, True)\n\n # 找到最小的矩形,该矩形可能有方向\n rect = cv2.minAreaRect(cnt)\n #print(\"rect is: \")\n #print(rect)\n\n # box是四个点的坐标\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n\n # 计算高和宽\n height = abs(box[0][1] - box[2][1])\n width = abs(box[0][0] - box[2][0])\n\n # 车牌正常情况下长高比在2.7-5之间\n ratio = float(width) / float(height)\n #print(ratio)\n if (ratio > 6 or ratio < 2):\n continue\n #print(area)\n region.append(box)\n\n return region\n\n region = find_carno_regin(dilated)\n\n img_2 = img.copy()\n def cut_carno(region):\n for i in np.arange(len(region)):\n box = region[i]\n result = cv2.drawContours(img_2, [box], -1, (0,255,0), 3)\n cv2.imshow('result_{}'.format(num),result)\n\n ys = [box[0, 1], box[1, 1], box[2, 1], box[3, 1]]\n xs = [box[0, 0], box[1, 0], box[2, 0], box[3, 0]]\n ys_sorted_index = np.argsort(ys)\n xs_sorted_index = np.argsort(xs)\n\n x1 = box[xs_sorted_index[0], 0]\n x2 = box[xs_sorted_index[3], 0]\n\n y1 = box[ys_sorted_index[0], 1]\n y2 = box[ys_sorted_index[3], 1]\n\n img_3 = img.copy()\n carno = img_3[y1:y2, x1:x2]\n cv2.imshow('carno_{}_{}'.format(num,i),carno)\n\n cut_carno(region)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"image_about.py","file_name":"image_about.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"577417295","text":"n = int(input())\n\npeople = list(map(int, input().split()))\n\nif n == 1:\n print(people[0])\nelse:\n #정렬 -> 누적되는 시간이 줄어든다.\n people.sort()\n\n i_sum = 0\n min_sum = 0\n\n for i in range(n):\n #i_sum에는 이전 사람들이 돈을 인출하는데 걸렸던 시간을 포함 + people[i]는 현재 사람이 돈을 인출하는데 걸리는 시간\n # = 한 사람이 돈을 인출하는데 걸리는 전체 시간\n min_sum += (i_sum + people[i])\n\n #i_sum에 현재 사람이 인출하는 데 걸리는 시간을 더하여 다음 사람 순서의 min_sum 계산에 반영할 수 있도록 한다.\n i_sum += people[i]\n \n print(min_sum)","sub_path":"Python/DAYOUNG/15_그리디알고리즘/3_ATM.py","file_name":"3_ATM.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"346478698","text":"import torch.nn as nn\nfrom model.conv_sn_chen import conv_spectral_norm\nfrom model.bn_sn_chen import bn_spectral_norm\n\nclass DnCNN(nn.Module):\n def __init__(self, channels, num_of_layers=17, lip=1.0, no_bn=False):\n super(DnCNN, self).__init__()\n kernel_size = 3\n padding = 1\n features = 64\n if lip > 0.0:\n sigmas = [pow(lip, 1.0/num_of_layers) for _ in range(num_of_layers)]\n else:\n sigmas = [0.0 for _ in range(num_of_layers)]\n\n # if adaptive:\n # sigmas = [5.0, 2.0, 1.0, 0.681, 0.464, 0.316]\n # assert len(sigmas) == num_of_layers, \"Length of SN list uncompatible with num of layers.\"\n\n def conv_layer(cin, cout, sigma):\n conv = nn.Conv2d(in_channels=cin,\n out_channels=cout,\n kernel_size=kernel_size,\n padding=padding,\n bias=False)\n if sigma > 0.0:\n return conv_spectral_norm(conv, sigma=sigma)\n else:\n return conv\n\n def bn_layer(n_features, sigma=1.0):\n bn = nn.BatchNorm2d(n_features)\n if sigma > 0.0:\n return bn_spectral_norm(bn, sigma=sigma)\n else:\n return bn\n\n layers = []\n layers.append(conv_layer(channels, features, sigmas[0]))\n layers.append(nn.ReLU(inplace=True))\n print(\"conv_1 with SN {}\".format(sigmas[0]))\n\n for i in range(1, num_of_layers-1):\n layers.append(conv_layer(features, features, sigmas[i])) # conv layer\n print(\"conv_{} with SN {}\".format(i+1, sigmas[i]))\n if not no_bn:\n layers.append(bn_layer(features, 0.0)) # bn layer\n layers.append(nn.ReLU(inplace=True))\n\n layers.append(conv_layer(features, channels, sigmas[-1]))\n print(\"conv_{} with SN {}\".format(num_of_layers, sigmas[-1]))\n self.dncnn = nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.dncnn(x)\n return out\n\n","sub_path":"training/model/full_realsn_models.py","file_name":"full_realsn_models.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"274227907","text":"import asyncio\nimport time\nfrom random import randint\n\n@asyncio.coroutine\ndef StartState():\n print('Start State called \\n')\n input_value=randint(0,1)\n time.sleep(2)\n if(input_value==0):\n result=yield from State2(input_value)\n print('State Start: yield from State2 ' + result)\n else:\n result=yield from State1(input_value)\n print('State Sart: yield from State1 ' + result)\n print(\"resume of the transition: \\nStart State calling \"+result)\n\n@asyncio.coroutine\ndef State1(transition_value):\n outputValue=str((\"State 1 with transition value = %s \\n\"%(transition_value)))\n input_value=randint(0,1)\n time.sleep(5)\n print(\"...Evaluating...\")\n print('State 1')\n if (input_value==0):\n result = yield from State3(input_value)\n print('State 1: yield from State3 '+result)\n else:\n result = yield from State2(input_value)\n print('State 2: yield from State3 '+result)\n result=\"State 1 calling \"+result\n print(result + 'hhhhhhhhhhhhhhhhh')\n return (outputValue+str(result))\n\n@asyncio.coroutine\ndef State2(transition_value):\n outputValue=str((\"State 2 with transition value = %s \\n\"%(transition_value)))\n input_value=randint(0,1)\n time.sleep(5)\n print(\"...Evaluating...\")\n print('State 2')\n if (input_value==0):\n result = yield from State1(input_value)\n print('State 2: yield from State1 '+result)\n else:\n result = yield from State3(input_value)\n print('State 2: yield from State3 '+result)\n result=\"State 2 calling \"+result\n print(result + 'hhhhhhhhhhhhhhhhh')\n return (outputValue+str(result))\n\n@asyncio.coroutine\ndef State3(transition_value):\n outputValue = str((\"State 3 with transition value = %s \\n\" % (transition_value)))\n input_value = randint(0, 1)\n time.sleep(5)\n print(\"...Evaluating...\")\n print('State 3')\n if (input_value == 0):\n result = yield from State1(input_value)\n print('State 3: yield from State1 '+result)\n else:\n result = yield from EndState(input_value)\n print('State 3: yield from EndState '+result)\n result = \"State 3 calling \" + result\n print(result+'hhhhhhhhhhhhhhhhh')\n return (outputValue + str(result))\n\n@asyncio.coroutine\ndef EndState(transition_value):\n outputValue=str((\"End State with transition value = %s \\n\"%(transition_value)))\n print(\"...Stop Computation...\")\n print('End State ')\n return (outputValue)\n\nif __name__=='__main__':\n print(\" Finite State Machine simulation with Asyncio Coroutine \")\n loop=asyncio.get_event_loop()\n loop.run_until_complete(StartState())\n\n","sub_path":"cor.py","file_name":"cor.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"316661543","text":"# Component - Variable Costs\n\nimport pandas\n\n# yes_no_checker goes here\n# ensures that a field must be answered with either yes or no\ndef yes_no_checker(question):\n to_check = [\"yes\", \"no\"]\n\n valid = False\n while not valid:\n response = input(question).lower()\n\n for var_item in to_check:\n if response == var_item:\n return response\n elif response == var_item[0]:\n return var_item\n \n print(\"Please enter either yes or no \\n\")\n\n# Number checker function goes here\n# Checks that it is not 0\ndef number_checker(question, error, num_type):\n valid = False\n while not valid:\n\n try:\n response = num_type(input(question))\n \n if response <= 0:\n print(error)\n else:\n return response\n\n except ValueError:\n print(error)\n\n# not_blank function here\n# Ensures that any input must not be left blank, the field must not be left empty\ndef not_blank(question, error):\n valid = False\n\n while not valid:\n response = input(question)\n\n if response != \"\":\n return response\n else:\n print(error)\n print()\n\n# currency function goes here\n# Puts something into a currency format with two decimal places\ndef currency(x):\n return \"${:.2f}\".format(x)\n\n# get_expenses function goes here\n# Gets expenses and then returns them as a list which has the data frame and sub total\ndef get_expenses(var_fixed):\n \n item_list = []\n quantity_list = []\n price_list = []\n\n variable_dict = {\n \"Item\": item_list,\n \"Quantity\": quantity_list,\n \"Price\": price_list\n }\n\n # loop to get component, quantity and price\n item_name = \"\"\n while item_name.lower() != \"xxx\":\n\n print()\n # get name, quantity and item\n item_name = not_blank(\"Item name: \", \"Name cannot be blank\")\n if item_name.lower() == \"xxx\":\n print(\"No Costs were given\")\n break\n\n if var_fixed == \"variable\":\n quantity = number_checker(\"Quantity: \", \"The amount must be a whole number\", int)\n else:\n quantity = 1\n\n price = number_checker(\"How much for a single item $\", \"The price must be a number more than 0\", float)\n\n # add item, quantity and price to lists\n item_list.append(item_name)\n quantity_list.append(quantity)\n price_list.append(price)\n\n expense_frame = pandas.DataFrame(variable_dict)\n expense_frame = expense_frame.set_index('Item')\n\n # Calculate cost of each component\n expense_frame['Cost'] = expense_frame['Quantity'] * expense_frame['Price']\n\n # Find sub total\n sub_total = expense_frame['Cost'].sum()\n\n # Currency Formatting (uses currency function)\n add_dollars = ['Price', 'Cost']\n for item in add_dollars:\n expense_frame[item] = expense_frame[item].apply(currency)\n\n return [expense_frame, sub_total]\n\ndef expense_print(heading, frame, subtotal):\n print()\n print(\"{} Costs\".format(heading))\n print(frame)\n print()\n print(\"{} Costs: ${:.2f}\".format(heading, subtotal))\n\n return \"\"\n\n\n# Main Routine\n\n\n# Get user data\nproduct_name = not_blank(\"Product name: \", \"Product Name cannot be blank\")\n\nprint()\nprint(\"Please enter your variable costs below...\")\n\n# Variable Costs\nvariable_expenses = get_expenses(\"variable\")\nvariable_frame = variable_expenses[0]\nvariable_sub = variable_expenses[1]\n\nprint()\n\n# Printing Area\nprint()\nprint(\"Fundraising - {}\".format(product_name))\nprint()\n\nexpense_print(\"Variable\", variable_frame, variable_sub)\n\nprint()\nprint(\"Total Costs: ${:.2f}\".format(variable_sub))\n","sub_path":"03_variable_costs_v2.py","file_name":"03_variable_costs_v2.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"431274743","text":"#!/usr/bin/python\n# -*- coding: latin-1 -*-\n\nimport gpio\nfrom time import sleep\n\nclass sensorLight:\n def __init__(self, gpio_int = 26):\n self.__Leuchte = gpio.GPIOout(gpio_int)\n\n def activate(self, boolLeuchte):\n return self.SetLeuchte(True, boolLeuchte)\n\n def deactivate(self, boolLeuchte):\n return self.SetLeuchte(False, boolLeuchte)\n \n def SetLeuchte(self, LeuchteAn, boolLeuchte):\n boolL = boolLeuchte\n if LeuchteAn:\n iI = 0\n while iI < 3:\n # print 'an' + str(iI)\n self.__Leuchte.on()\n sleep(0.1)\n self.__Leuchte.off()\n sleep(0.1)\n iI = iI + 1\n # 1 Konstant an\n # 2 Pulse schnell\n # 3 Pulse langsam\n boolL = True\n else:\n iI = 0\n while iI < 5:\n # print 'aus' + str(iI)\n self.__Leuchte.on()\n sleep(0.1)\n self.__Leuchte.off()\n sleep(0.1)\n iI = iI + 1\n # 4 Lauf links langsam\n # 5 Lauf rechts langsam\n # 6 Lauf links schnell\n # 7 Lauf links rechts\n # 8 Aus\n boolL = False\n return boolL\n \n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n","sub_path":"python/sensorLight.py","file_name":"sensorLight.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"284244421","text":"#!/usr/bin/python3\nimport sys\nimport itertools\n\nunderscore = False\ndef next(index, char):\n global underscore\n if(char == '_'):\n underscore = True\n ret = ''\n else:\n ret = char.upper() if underscore or index == 0 else char.lower()\n underscore = False\n return ret\n\nprint(str().join(list(itertools.starmap(next, enumerate(list(sys.argv[1]))))))\n","sub_path":"pascal.py","file_name":"pascal.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"90596405","text":"# -*- coding: utf-8 -*-\nclass Solution:\n def minimumTotal(self, triangle):\n n = len(triangle)\n f = [[0] * n for _ in range(n)]\n print(f)\n f[0][0] = triangle[0][0]\n\n for i in range(1, n):\n f[i][0] = f[i - 1][0] + triangle[i][0]\n for j in range(1, i):\n f[i][j] = min(f[i - 1][j - 1], f[i - 1][j]) + triangle[i][j]\n f[i][i] = f[i - 1][i - 1] + triangle[i][i]\n print(f)\n\n return min(f[n - 1])\n\n\n\n\nsolution = Solution()\ninputs = [[2],[3,4],[6,5,7],[4,1,8,3]]\nres = solution.minimumTotal(inputs)\n\nprint(res)\n\n\nclass Solution2:\n def minimumTotal(self, triangle) :\n n = len(triangle)\n f = [0] * n\n f[0] = triangle[0][0]\n\n for i in range(1, n):\n f[i] = f[i - 1] + triangle[i][i]\n for j in range(i - 1, 0, -1):\n f[j] = min(f[j - 1], f[j]) + triangle[i][j]\n f[0] += triangle[i][0]\n\n print(f)\n\n return min(f)\n\nsolution2 = Solution2()\ninputs = [[2],[3,4],[6,5,7],[4,1,8,3]]\nres = solution2.minimumTotal(inputs)\n\nprint(res)\n\n\n\nclass Solution3:\n def minPoint(self,triangel,i,j):\n if i == len(triangel)-1: #最底层,递归基\n return triangel[i][j]\n else:\n return triangel[i][j] + min(self.minPoint(triangel,i+1,j),self.minPoint(triangel,i+1,j+1)) #顶点值 he #子问题的较小者\n\n def minimumTotal(self, triangle):\n \"\"\"\n :type triangle: List[List[int]]\n :rtype: int\n \"\"\"\n return self.minPoint(triangle,0,0)\n\nsolution3=Solution3()\n\nres = solution3.minimumTotal(inputs)\n\nprint(res)","sub_path":"3-LeetCode/120-.py","file_name":"120-.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"283337500","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError, UserError\n\n\nclass SaleOrder(models.Model):\n _inherit = \"sale.order\"\n\n @api.multi\n def _visit_count(self):\n for rec in self: \n rec.visit_count = self.env['visit.visit'].search_count([('sale_id', '=', rec.id)])\n\n visit_count = fields.Integer(compute=\"_visit_count\", readonly=True, string=\"Visits\")\n\n @api.multi\n def sale_visit_action(self):\n return {\n 'name': _('Visits'),\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': 'visit.visit',\n 'type': 'ir.actions.act_window',\n 'domain': [('sale_id','=', self.id)],\n 'context': {\n 'default_partner_id': self.partner_id.id,\n 'default_sale_id': self.id,\n 'default_project_id': self.project_id.id,\n }\n }","sub_path":"acs_visits/models/sale.py","file_name":"sale.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"534119471","text":"from datetime \\\n import datetime, date, timedelta\n\nfrom decimal \\\n import *\n\nfrom django \\\n import forms\n\nfrom django.db \\\n import models\n\nfrom django.forms \\\n import ModelForm\n\nfrom django.utils \\\n import timezone\n\nfrom profiles.models \\\n import BoomUser\n\nclass TimeStampedModel(models.Model):\n created = models.DateField(default=date.today())\n modified = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n\nclass Status(TimeStampedModel):\n HAWAII, ALASKA, PUERTO_RICO = (0,1,2)\n PORT_CHOICES = (\n (HAWAII, \"Hawaii\"),\n (ALASKA, \"Alaska\"),\n (PUERTO_RICO, \"Puerto Rico\"),\n )\n NOT_YET_BILLED, BILLED, REFUNDED, INVALID, DECLINED = (0,1,2,3,4)\n BILLING_TYPE = (\n (NOT_YET_BILLED, \"Not Yet Billed\"),\n (BILLED, \"Billed\"),\n (DECLINED, \"Declined\"),\n (INVALID, \"Invalid Card\"),\n (REFUNDED, \"Refunded\"),\n )\n NOT_ASSIGNED, ASSIGNED, PICKED_UP, DELIVERED = (0,1,2,3)\n DELIVERY_STATUS = (\n (NOT_ASSIGNED, \"Not Yet Assigned\"),\n (ASSIGNED, \"Assigned\"),\n (PICKED_UP, \"Picked Up\"),\n (DELIVERED, \"Delivered\"),\n )\n ACTIVE, ON_HOLD, CANCELLED = (0,1,2)\n ACTIVITY_STATUS = (\n (ACTIVE, \"Active\"),\n (ON_HOLD, \"On-Hold\"),\n (CANCELLED, \"Cancelled\"),\n )\n\n delivery_status = models.IntegerField(\n 'Delivery Status',\n max_length = 2,\n blank = False,\n null = False,\n default = 0,\n choices = DELIVERY_STATUS\n )\n billing_status = models.IntegerField(\n 'Billing Status',\n max_length = 2,\n blank = False,\n null = False,\n default = 0,\n choices = BILLING_TYPE\n )\n activity_status = models.IntegerField(\n 'Activity Status',\n max_length = 2,\n blank = False,\n null = False,\n default = 0,\n choices = ACTIVITY_STATUS\n )\n port_choices = models.CharField(\n 'Choose a Port (Leave Blank If None)',\n max_length = 255,\n blank = True,\n null = False,\n default = \"\",\n choices = PORT_CHOICES\n )\n bumped = models.BooleanField('Has This Order Been Bumped?',default=False)\n blackout = models.BooleanField(\"Are There 'Black Out' States Involved In This Order?\",default=False)\n has_auth = models.BooleanField('Has The Auth Form Been Returned?',default=False)\n\n def __unicode__(self):\n return \"Status #\"+str(self.id)\n\n def get_delivery_status(self):\n return self.delivery_status\n\n def delivery_status_to_str(self):\n if self.delivery_status == 0:\n return \"Not Yet Assigned\"\n elif self.delivery_status == 1:\n return \"Assigned\"\n elif self.delivery_status == 2:\n return \"Picked Up\"\n else:\n return \"Delivered\"\n\n def get_port(self):\n return self.port_choices\n\n def get_activity_status(self):\n return self.activity_status\n \n def get_activity_to_str(self):\n if self.activity_status == 0:\n return \"Order is Active\"\n elif self.activity_status == 1:\n return \"On-Hold\"\n else:\n return \"Cancelled\"\n\n def get_billing_status_to_str(self):\n if self.billing_status == 0:\n return \"Not Yet Billed\"\n elif self.billing_status == 1:\n return \"Billed\"\n elif self.billing_status == 2: \n return \"Declined\"\n\n elif self.billing_status == 3:\n return \"Invalid\"\n else:\n return \"Refunded\"\n\n def bump_order(self):\n self.bumped = True\n\n def bump_down(self):\n self.bumped = False\n\n def is_unassigned(self):\n self.delivery_status = 0\n\n def is_scheduled(self):\n self.delivery_status = 1\n\n def is_picked_up(self):\n self.delivery_status = 2\n\n def is_delivered(self):\n self.delivery_status = 3\n\n\n\nclass LeadProvider(TimeStampedModel):\n lead_provider_name = models.CharField(max_length=64)\n description = models.CharField(max_length=255,null=False,blank=True,default=\"\")\n\n def __unicode__(self):\n return self.lead_provider_name\n \n\nclass Order(TimeStampedModel):\n jtracker_id = models.IntegerField('JTracker Order ID',primary_key=True)\n lead_provider = models.ForeignKey(LeadProvider)\n status = models.OneToOneField(Status,related_name='this_status')\n date_requested = models.DateField('Requested Pick Up Date', default=date.today() + timedelta(days = 5))\n date_scheduled = models.DateField('Date Scheduled For Pick Up',null=True,blank=True)\n date_picked_up = models.DateField('Date Picked Up',null=True,blank=True)\n date_delivered = models.DateField('Date Delivered',null=True,blank=True)\n notes = models.TextField('Notes',null=True,blank=True)\n owner = models.ForeignKey(BoomUser,default=1)\n original_total = models.DecimalField(\n 'Original Total Price',\n max_digits = 20,\n decimal_places = 2,\n default = 0.00\n )\n\n def __unicode__(self):\n return \"Order #\"+str(self.jtracker_id)\n\n def get_id(self):\n return self.jtracker_id\n\n def get_owner(self):\n return self.owner.username\n\n def original_total_has_changed(self, amount):\n return amount > self.original_total\n\n def is_scheduled(self):\n return self.date_scheduled != None\n\n def is_picked_up(self):\n return self.date_picked_up != None\n\n def is_delivered(self):\n return self.date_delivered != None\n\n\nclass Payment(TimeStampedModel):\n CARRIER_PAY, DEPOSIT, REFUND = (0,1,2)\n PAYMENT_CHOICES = (\n (CARRIER_PAY, \"Carrier Pay\"),\n (DEPOSIT, \"Deposit\"),\n (REFUND, \"Refund\"),\n )\n jtracker_id = models.ForeignKey(Order)\n amount = models.DecimalField(\n 'Payment Amount',\n max_digits = 20,\n decimal_places = 2,\n default = 0.00\n )\n payment_type = models.IntegerField(\n 'Payment Type',\n max_length = 2,\n null = False,\n choices = PAYMENT_CHOICES\n )\n\n def __unicode__(self):\n return self.type_to_string()+\" \"+str(Decimal(self.amount))\n\n def type_to_string(self):\n if self.payment_type == 0:\n return \"Carrier Pay\"\n elif self.payment_type == 1:\n return \"Deposit\"\n else:\n return \"Refund\"\n","sub_path":"aatStats/orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"81381462","text":"from django.shortcuts import render, get_list_or_404\nfrom .models import InputData\nfrom django.http import HttpResponseRedirect\nfrom .forms import InputForm\n\n# Create your views here.\n\n\ndef index(request):\n list_of_rows = get_list_or_404(InputData)\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = InputForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n input_user_field = form.cleaned_data['input_user_field']\n new_data = InputData(data_row=input_user_field)\n new_data.save()\n return HttpResponseRedirect('/')\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = InputForm()\n\n return render(request, 'userlist/index.html', {'form': form, 'list_of_rows': list_of_rows})","sub_path":"userlist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"265241189","text":"# -*- coding: utf-8 -*-\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\n\nn_samples = 400\nn_features = 2\ncenters = 4\n\ndata1, y1 = make_blobs(n_samples, n_features, centers, random_state=2)\ndata2, y2 = make_blobs(n_samples, n_features, centers, cluster_std=(1, 2.5, 0.5, 2), random_state=2)\ndata3 = np.vstack((data1[y1 == 0], data1[y1 == 1][:50], data1[y1 == 2][:20], data1[y1 == 3][:5]))\ny3 = np.array([0] * 100 + [1] * 50 + [2] * 20 + [3] * 5)\n\ncls = KMeans(n_clusters=4)\n\ny1_hat = cls.fit_predict(data1)\ny2_hat = cls.fit_predict(data2)\ny3_hat = cls.fit_predict(data3)\n\ndata_r = np.dot(data1, np.array(((1, 1), (1, 3))))\ny_r_hat = cls.fit_predict(data_r)\n\ncmap = matplotlib.colors.ListedColormap('rgbm')\n\n\ndef expand(_min, _max):\n _dis = (_max - _min) * 0.1\n return _min - _dis, _max + _dis\n\n\nplt.figure(figsize=(9, 10), facecolor='w')\nplt.subplot(421)\nplt.title('Raw data')\nplt.scatter(data1[:, 0], data1[:, 1], c=y1, cmap=cmap)\nx1_min, x2_min = np.min(data1, axis=0)\nx1_max, x2_max = np.max(data1, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(422)\nplt.title('K-means++ data')\nplt.scatter(data1[:, 0], data1[:, 1], c=y1_hat, cmap=cmap)\nx1_min, x2_min = np.min(data1, axis=0)\nx1_max, x2_max = np.max(data1, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(423)\nplt.title('Rotated raw data')\nplt.scatter(data_r[:, 0], data_r[:, 1], c=y1, cmap=cmap)\nx1_min, x2_min = np.min(data_r, axis=0)\nx1_max, x2_max = np.max(data_r, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(424)\nplt.title('Rotated k-means++ data')\nplt.scatter(data_r[:, 0], data_r[:, 1], c=y_r_hat, cmap=cmap)\nx1_min, x2_min = np.min(data_r, axis=0)\nx1_max, x2_max = np.max(data_r, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(425)\nplt.title('Uncertain variance data')\nplt.scatter(data2[:, 0], data2[:, 1], c=y2, cmap=cmap)\nx1_min, x2_min = np.min(data2, axis=0)\nx1_max, x2_max = np.max(data2, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(426)\nplt.title('Uncertain variance k-means++ data')\nplt.scatter(data2[:, 0], data2[:, 1], c=y2_hat, cmap=cmap)\nx1_min, x2_min = np.min(data2, axis=0)\nx1_max, x2_max = np.max(data2, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(427)\nplt.title('Uneven data')\nplt.scatter(data3[:, 0], data3[:, 1], c=y3, cmap=cmap)\nx1_min, x2_min = np.min(data3, axis=0)\nx1_max, x2_max = np.max(data3, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.subplot(428)\nplt.title('Uneven k-means++ data')\nplt.scatter(data3[:, 0], data3[:, 1], c=y3_hat, cmap=cmap)\nx1_min, x2_min = np.min(data3, axis=0)\nx1_max, x2_max = np.max(data3, axis=0)\nleft, right = expand(x1_min, x1_max)\nbottom, top = expand(x2_min, x2_max)\nplt.xlim((left, right))\nplt.ylim((bottom, top))\nplt.grid(True)\n\nplt.suptitle('Impact of data distribution on K-means clustering', fontsize=18)\nplt.tight_layout(2, rect=(0, 0, 1, 0.97))\nplt.show()\n","sub_path":"battle/cluster_kmeans.py","file_name":"cluster_kmeans.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"594740253","text":"from games import *\n\nclass State:\n def __init__(self,board,turn,castle,lastMove,numberOfMoves):\n self.board=board\n self.turn=turn\n self.castle=castle\n self.lastMove=lastMove\n self.numberOfMoves=numberOfMoves\n self.check=0\n\nclass Chess(Game):\n\n def __init__(self,board,nMoves,castle=0,lastMove=[],numberOfMoves=0, ):\n self.initial=State(board,1,castle,lastMove,numberOfMoves)\n self.nMoves=nMoves\n\n def getMoves(self,board,turn,pos,func):\n \"\"\"\n Retorna una lista con los movimientos posibles de la pieza en pos\n segun func\n \"\"\"\n moves=[]\n for m in func(board,turn,pos):\n moves.append(m) \n\n return moves\n\n\n def possibleMoves(self,board,turn):\n \"Retorna una lista con las celdas a las que se puede mover turn\"\n \" mov=[(x,y),(x1,y1)] \"\n possibleMoves=[]\n \n for i in range(8):\n for j in range(8):\n cell=board[i][j]*turn\n if(cell>0):\n if(cell==1):\n for m in self.getMoves(board,turn,[i,j],self.pawn):\n possibleMoves.append(m)\n elif(cell==2):\n for m in self.getMoves(board,turn,[i,j],self.knight):\n possibleMoves.append(m)\n elif(cell==3):\n for m in self.getMoves(board,turn,[i,j],self.bishop):\n possibleMoves.append(m)\n elif(cell==4):\n for m in self.getMoves(board,turn,[i,j],self.rook):\n possibleMoves.append(m)\n elif(cell==5):\n for m in self.getMoves(board,turn,[i,j],self.queen):\n possibleMoves.append(m)\n elif(cell==6):\n for m in self.getMoves(board,turn,[i,j],self.king):\n possibleMoves.append(m)\n\n return possibleMoves\n\n\n def scanDirections(self,board,turn,pos,directions,listOfMoves):\n index=0\n sawKing=[]\n while index<4: \n \"Controla cada direccion\"\n x=pos[0] + directions[index][0]\n y=pos[1] + directions[index][1]\n \n \"Para cada dir, recorre hasta el final\"\n while((x<8 and y<8) and (x>=0 and y>=0)):\n \"Controla cada futura celda\"\n if(board[x][y]==0):\n \"si esta vacia,es valido\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n elif(board[x][y]*turn<0):\n \"si hay una pieza del oponente, es valido, pero no avanza mas\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n if not (abs(board[x][y])==6):\n break\n else:\n sawKing=[x,y]\n else:\n \"si hay una pieza propia, no avanza mas\"\n if(sawKing==[x-directions[index][0],y-directions[index][1]]):\n \"En el mov anterior se cruzaron con el rey, la agrega\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n else:\n break\n\n \"avanza una celda mas en la misma direccion\"\n x+=directions[index][0]\n y+=directions[index][1]\n\n index+=1\n\n def bishop(self,board,turn,pos):\n listOfMoves=[]\n directions=[[1,1],[1,-1],[-1,1],[-1,-1]]\n \n self.scanDirections(board,turn,pos,directions,listOfMoves) \n return listOfMoves\n\n def rook(self,board,turn,pos):\n listOfMoves=[]\n directions=[[1,0],[-1,0],[0,1],[0,-1]]\n \n self.scanDirections(board,turn,pos,directions,listOfMoves)\n return listOfMoves\n\n def queen(self,board,turn,pos):\n listOfMoves=[]\n directions=[[1,1],[1,-1],[-1,1],[-1,-1]]\n\n self.scanDirections(board,turn,pos,directions,listOfMoves)\n directions=[[1,0],[-1,0],[0,1],[0,-1]]\n self.scanDirections(board,turn,pos,directions,listOfMoves)\n\n return listOfMoves\n \n def knight(self,board,turn,pos):\n listOfMoves=[]\n directions=[[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2],[-1,-2]]\n\n index=0\n while index <8:\n x=pos[0] + directions[index][0]\n y=pos[1] + directions[index][1]\n\n if((x<8 and y<8) and (x>=0 and y>=0)):\n \"Controla cada futura celda\"\n if(board[x][y]==0):\n \"si esta vacia,es valido\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n elif(board[x][y]*turn<0):\n \"si hay una pieza del oponente, es valido\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n else:\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n \n index+=1\n\n return listOfMoves\n\n \n def king(self,board,turn,pos):\n listOfMoves=[]\n directions=[[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]]\n futureCells=[]\n \n index=0\n while index <8:\n x=pos[0] + directions[index][0]\n y=pos[1] + directions[index][1]\n\n if((x<8 and y<8) and (x>=0 and y>=0)):\n \"Controla cada futura celda\"\n if(board[x][y]==0):\n \"si esta vacia,es valido\"\n futureCells.append((x,y))\n elif(board[x][y]*turn<0):\n \"si hay una pieza del oponente, es valido\"\n futureCells.append((x,y))\n index+=1\n\n if(turn==-1):\n opponentMoves=self.possibleMoves(board,turn*-1)\n for m in opponentMoves:\n if(m[1] in futureCells):\n futureCells.remove(m[1])\n\n for m in futureCells:\n listOfMoves.append([(pos[0],pos[1]),m])\n \n\n return listOfMoves\n\n def pawn(self,board,turn,pos):\n listOfMoves=[]\n x=pos[0]\n y=pos[1]\n e=-1*turn #Indica el sentido del mov, Blancas -, Negras +\n \n \"Avance sin captura\"\n x+=e*1\n if((x<8 and y<8) and (x>=0 and y>=0)):\n if(board[x][y]==0):\n \"si esta vacia,es valido\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n\n \"si esta en su posicion original, es valido avanzar dos casillas\"\n if((pos[0]+turn==0) or (pos[0]+turn==7)):\n x+=e*1\n if(board[x][y]==0):\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n\n \"Avance con captura\"\n directions=[[e*1,-1],[e*1,1]]\n index=0\n while index <2:\n x=pos[0] + directions[index][0]\n y=pos[1] + directions[index][1]\n\n if((x<8 and y<8) and (x>=0 and y>=0)):\n if(board[x][y]*turn<0):\n \"si hay una pieza del oponente, es valido\"\n listOfMoves.append([(pos[0],pos[1]),(x,y)])\n \n index+=1\n\n #*** VER CAPTURA AL PASO ***#\n \n return listOfMoves\n\n\n def actions(self, state):\n \"Return a list of the allowable moves at this point.\"\n return self.possibleMoves(state.board,state.turn)\n\n def result(self, state, move):\n \"Return the state that results from making a move from a state.\"\n \"move (a,b,c) a=origin cell b=destination cell c=specifies a piece in case of promotion\"\n \"move=[(x,y),(x1,y1)] \"\n \n pos0=list(move[0])\n pos1=list(move[1])\n\n newboard=[[0] * 8 for i in range(8)]\n for i in range(8):\n for j in range(8):\n newboard[i][j]= state.board[i][j]\n\n piece=newboard[pos0[0]][pos0[1]]\n newboard[pos0[0]][pos0[1]]=0\n\n \"en caso de conoracion, simpre se obtiene una reina\"\n if(piece==1):\n if(pos1[0]==0 or pos1[0]==7):\n piece=5*state.turn\n\n newboard[pos1[0]][pos1[1]]=piece\n\n newState=State(newboard,state.turn*-1,0,move,state.numberOfMoves+1)\n\n return newState\n\n\n def evaluate(self,board,check):\n k=q=r=b=n=p=0\n k1=q1=r1=b1=n1=p1=0\n for i in range(8):\n for j in range(8):\n if(board[i][j]==6):\n k=6\n elif (board[i][j]==-6):\n k=-6\n elif (board[i][j]==5):\n q=5\n elif (board[i][j]==-5):\n q=-5\n elif (board[i][j]==4):\n r=4\n elif (board[i][j]==-4):\n r=-4\n elif (board[i][j]==3):\n b=3\n elif (board[i][j]==-3):\n b=-3\n elif (board[i][j]==2):\n n=2\n elif (board[i][j]==-2):\n n=-2\n elif (board[i][j]==1):\n p=1\n elif (board[i][j]==-1):\n p=-1\n\n M=len(self.possibleMoves(board,1))\n M1=len(self.possibleMoves(board,-1))\n\n Pfunc=200*(k-k1) + 9*(q-q1) +5*(r-r1)+3*(b-b1 + n-n1) +(p-p1) + 0.1*(M-M1)+check\n\n return Pfunc\n\n\n def utility(self, state, player):\n \"Return the value of this final state to player.\"\n if(state.check==100):\n return 100\n if(state.numberOfMoves>self.nMoves):\n return -100\n \n \n return 0\n \n \n def terminal_test(self, state):\n \"Return True if this is a final state for the game.\"\n blackKingMoves=[]\n\n if(state.numberOfMoves==self.nMoves):\n pos=[]\n for i in range(8):\n for j in range(8):\n if(state.board[i][j]==-6):\n pos=[i,j]\n \n if(pos!=[]):\n \n blackKingMoves=self.king(state.board,-1,pos)\n whiteMoves=self.possibleMoves(state.board,1)\n\n blackKingCells=[]\n for m in blackKingMoves:\n blackKingCells.append(m[1]) \n blackKingCells.append(tuple(pos))\n\n for m in whiteMoves:\n if(m[1] in blackKingCells):\n blackKingCells.remove(m[1])\n\n if(blackKingCells==[]):\n state.check=100\n return True\n\n return True\n \n return False \n\n def to_move(self, state):\n \"Return the player whose move it is in this state.\"\n return state.turn","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":10779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"564782067","text":"import pafy\n\nfrom core import internals\nfrom core import const\n\nimport os\nimport pprint\n\nlog = const.log\n# Please respect this YouTube token :)\npafy.set_api_key('AIzaSyAnItl3udec-Q1d5bkjKJGL-RgrKO_vU90')\n\n\ndef go_pafy(raw_song, meta_tags=None):\n \"\"\" Parse track from YouTube. \"\"\"\n if internals.is_youtube(raw_song):\n track_info = pafy.new(raw_song)\n else:\n track_url = generate_youtube_url(raw_song, meta_tags)\n\n if track_url:\n track_info = pafy.new(track_url)\n else:\n track_info = None\n\n return track_info\n\n\ndef get_youtube_title(content, number=None):\n \"\"\" Get the YouTube video's title. \"\"\"\n title = content.title\n if number:\n return '{0}. {1}'.format(number, title)\n else:\n return title\n\n\ndef download_song(file_name, content):\n \"\"\" Download the audio file from YouTube. \"\"\"\n _, extension = os.path.splitext(file_name)\n if extension in ('.webm', '.m4a'):\n link = content.getbestaudio(preftype=extension[1:])\n else:\n log.debug('No audio streams available for {} type'.format(extension))\n return False\n\n if link:\n log.debug('Downloading from URL: ' + link.url)\n filepath = os.path.join(const.args.folder, file_name)\n log.debug('Saving to: ' + filepath)\n link.download(filepath=filepath)\n return True\n else:\n log.debug('No audio streams available')\n return False\n\n\ndef generate_youtube_url(raw_song, meta_tags, tries_remaining=5):\n \"\"\" Search for the song on YouTube and generate a URL to its video. \"\"\"\n # prevents an infinite loop but allows for a few retries\n if tries_remaining == 0:\n log.debug('No tries left. I quit.')\n return\n\n query = { 'part' : 'snippet',\n 'maxResults' : 50,\n 'type' : 'video' }\n\n if const.args.music_videos_only:\n query['videoCategoryId'] = '10'\n\n if not meta_tags:\n song = raw_song\n query['q'] = song\n else:\n song = '{0} - {1}'.format(meta_tags['artists'][0]['name'],\n meta_tags['name'])\n query['q'] = song\n log.debug('query: {0}'.format(query))\n\n data = pafy.call_gdata('search', query)\n query_results = {'part': 'contentDetails,snippet,statistics',\n 'maxResults': 50,\n 'id': ','.join(i['id']['videoId'] for i in data['items'])}\n log.debug('query_results: {0}'.format(query_results))\n\n vdata = pafy.call_gdata('videos', query_results)\n\n videos = []\n for x in vdata['items']:\n duration_s = pafy.playlist.parseISO8591(x['contentDetails']['duration'])\n youtubedetails = {'link': x['id'], 'title': x['snippet']['title'],\n 'videotime':internals.videotime_from_seconds(duration_s),\n 'seconds': duration_s}\n videos.append(youtubedetails)\n if not meta_tags:\n break\n\n if not videos:\n return None\n\n if const.args.manual:\n log.info(song)\n log.info('0. Skip downloading this song.\\n')\n # fetch all video links on first page on YouTube\n for i, v in enumerate(videos):\n log.info(u'{0}. {1} {2} {3}'.format(i+1, v['title'], v['videotime'],\n \"http://youtube.com/watch?v=\"+v['link']))\n # let user select the song to download\n result = internals.input_link(videos)\n if not result:\n return None\n else:\n if not meta_tags:\n # if the metadata could not be acquired, take the first result\n # from Youtube because the proper song length is unknown\n result = videos[0]\n log.debug('Since no metadata found on Spotify, going with the first result')\n else:\n # filter out videos that do not have a similar length to the Spotify song\n duration_tolerance = 10\n max_duration_tolerance = 20\n possible_videos_by_duration = list()\n\n '''\n start with a reasonable duration_tolerance, and increment duration_tolerance\n until one of the Youtube results falls within the correct duration or\n the duration_tolerance has reached the max_duration_tolerance\n '''\n while len(possible_videos_by_duration) == 0:\n possible_videos_by_duration = list(filter(lambda x: abs(x['seconds'] - meta_tags['duration']) <= duration_tolerance, videos))\n duration_tolerance += 1\n if duration_tolerance > max_duration_tolerance:\n log.error(\"{0} by {1} was not found.\\n\".format(meta_tags['name'], meta_tags['artists'][0]['name']))\n return None\n\n result = possible_videos_by_duration[0]\n\n if result:\n url = \"http://youtube.com/watch?v=\" + result['link']\n else:\n url = None\n\n return url\n","sub_path":"core/youtube_tools.py","file_name":"youtube_tools.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"93215526","text":"import math\nimport numpy as np\nimport skimage, skimage.transform\nfrom functools import lru_cache\nfrom PIL import Image\nfrom random import gauss\nfrom vectormath import Vector2\n\n\ndef rand(x):\n return max(-2 * x, min(2 * x, gauss(0, 1) * x))\n\n\ndef crop_image(image_path, center, scale, rotate, resolution=256):\n image = Image.open(image_path)\n\n width, height = image.size\n center = Vector2(center) # assign new array\n\n crop_ratio = 200 * scale / resolution\n\n if crop_ratio >= 2: # if box size is greater than two time of resolution px\n # scale down image\n height = math.floor(height / crop_ratio)\n width = math.floor(width / crop_ratio)\n\n if max([height, width]) < 2:\n # Zoomed out so much that the image is now a single pixel or less\n raise ValueError(\"Width or height is invalid!\")\n\n image = image.resize((width, height), Image.BILINEAR)\n\n center /= crop_ratio\n scale /= crop_ratio\n\n ul = (center - 200 * scale / 2).astype(int)\n br = (center + 200 * scale / 2).astype(int) # Vector2\n\n if crop_ratio >= 2: # force image size 256 x 256\n br -= (br - ul - resolution)\n\n pad_length = math.ceil(((ul - br).length - (br.x - ul.x)) / 2)\n\n if rotate != 0:\n ul -= pad_length\n br += pad_length\n\n crop_src = [max(0, ul.x), max(0, ul.y), min(width, br.x), min(height, br.y)]\n crop_dst = [max(0, -ul.x), max(0, -ul.y), min(width, br.x) - ul.x, min(height, br.y) - ul.y]\n crop_image = image.crop(crop_src)\n\n new_image = Image.new(\"RGB\", (br.x - ul.x, br.y - ul.y))\n new_image.paste(crop_image, box=crop_dst)\n\n if rotate != 0:\n new_image = new_image.rotate(rotate, resample=Image.BILINEAR)\n new_image = new_image.crop(box=(pad_length, pad_length,\n new_image.width - pad_length, new_image.height - pad_length))\n\n if crop_ratio < 2:\n new_image = new_image.resize((resolution, resolution), Image.BILINEAR)\n\n return new_image\n\n\n@lru_cache(maxsize=32)\ndef gaussian(size, sigma=0.25, mean=0.5):\n width = size\n height = size\n amplitude = 1.0\n sigma_u = sigma\n sigma_v = sigma\n mean_u = mean * width + 0.5\n mean_v = mean * height + 0.5\n\n over_sigma_u = 1.0 / (sigma_u * width)\n over_sigma_v = 1.0 / (sigma_v * height)\n\n x = np.arange(0, width, 1)\n y = x[:, np.newaxis]\n\n du = (x + 1 - mean_u) * over_sigma_u\n dv = (y + 1 - mean_v) * over_sigma_v\n\n return amplitude * np.exp(-0.5 * (du * du + dv * dv))\n\n\ndef draw_heatmap(size, y0, x0, sigma=1):\n pad = 3 * sigma\n y0, x0 = int(y0), int(x0)\n dst = [max(0, y0 - pad), max(0, min(size, y0 + pad + 1)), max(0, x0 - pad), max(0, min(size, x0 + pad + 1))]\n src = [-min(0, y0 - pad), pad + min(pad, size - y0 - 1) + 1, -min(0, x0 - pad), pad + min(pad, size - x0 - 1) + 1]\n\n heatmap = np.zeros([size, size])\n g = gaussian(3 * 2 * sigma + 1)\n heatmap[dst[0]:dst[1], dst[2]:dst[3]] = g[src[0]:src[1], src[2]:src[3]]\n\n return heatmap\n","sub_path":"MPII/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"387959384","text":"from __future__ import annotations\n\nimport typing as t\nfrom dataclasses import dataclass, field\n\nfrom piccolo.columns import And, Column, Or, Secret, Where\nfrom piccolo.columns.column_types import ForeignKey\nfrom piccolo.custom_types import Combinable\nfrom piccolo.querystring import QueryString\nfrom piccolo.utils.sql_values import convert_to_sql_value\n\nif t.TYPE_CHECKING: # pragma: no cover\n from piccolo.columns.base import Selectable\n from piccolo.table import Table # noqa\n\n\n@dataclass\nclass Limit:\n __slots__ = (\"number\",)\n\n number: int\n\n def __post_init__(self):\n if type(self.number) != int:\n raise TypeError(\"Limit must be an integer\")\n\n @property\n def querystring(self) -> QueryString:\n return QueryString(f\" LIMIT {self.number}\")\n\n def __str__(self) -> str:\n return self.querystring.__str__()\n\n def copy(self) -> Limit:\n return self.__class__(number=self.number)\n\n\n@dataclass\nclass Offset:\n __slots__ = (\"number\",)\n\n number: int\n\n def __post_init__(self):\n if type(self.number) != int:\n raise TypeError(\"Limit must be an integer\")\n\n @property\n def querystring(self) -> QueryString:\n return QueryString(f\" OFFSET {self.number}\")\n\n def __str__(self) -> str:\n return self.querystring.__str__()\n\n\n@dataclass\nclass OrderBy:\n __slots__ = (\"columns\", \"ascending\")\n\n columns: t.Sequence[Column]\n ascending: bool\n\n @property\n def querystring(self) -> QueryString:\n order = \"ASC\" if self.ascending else \"DESC\"\n columns_names = \", \".join(\n i._meta.get_full_name(just_alias=True) for i in self.columns\n )\n\n return QueryString(f\" ORDER BY {columns_names} {order}\")\n\n def __str__(self):\n return self.querystring.__str__()\n\n\n@dataclass\nclass Output:\n\n as_json: bool = False\n as_list: bool = False\n as_objects: bool = False\n load_json: bool = False\n nested: bool = False\n\n def copy(self) -> Output:\n return self.__class__(\n as_json=self.as_json,\n as_list=self.as_list,\n as_objects=self.as_objects,\n load_json=self.load_json,\n nested=self.nested,\n )\n\n\n@dataclass\nclass WhereDelegate:\n\n _where: t.Optional[Combinable] = None\n _where_columns: t.List[Column] = field(default_factory=list)\n\n def get_where_columns(self):\n \"\"\"\n Retrieves all columns used in the where clause - in case joins are\n needed.\n \"\"\"\n self._where_columns = []\n self._extract_columns(self._where)\n return self._where_columns\n\n def _extract_columns(self, combinable: Combinable):\n if isinstance(combinable, Where):\n self._where_columns.append(combinable.column)\n elif isinstance(combinable, (And, Or)):\n self._extract_columns(combinable.first)\n self._extract_columns(combinable.second)\n\n def where(self, *where: Combinable):\n for arg in where:\n self._where = And(self._where, arg) if self._where else arg\n\n\n@dataclass\nclass OrderByDelegate:\n\n _order_by: t.Optional[OrderBy] = None\n\n def get_order_by_columns(self) -> t.List[Column]:\n return list(self._order_by.columns) if self._order_by else []\n\n def order_by(self, *columns: Column, ascending=True):\n self._order_by = OrderBy(columns, ascending)\n\n\n@dataclass\nclass LimitDelegate:\n\n _limit: t.Optional[Limit] = None\n _first: bool = False\n\n def limit(self, number: int):\n self._limit = Limit(number)\n\n def first(self):\n self.limit(1)\n self._first = True\n\n def copy(self) -> LimitDelegate:\n _limit = self._limit.copy() if self._limit is not None else None\n return self.__class__(_limit=_limit, _first=self._first)\n\n\n@dataclass\nclass DistinctDelegate:\n\n _distinct: bool = False\n\n def distinct(self):\n self._distinct = True\n\n\n@dataclass\nclass CountDelegate:\n\n _count: bool = False\n\n def count(self):\n self._count = True\n\n\n@dataclass\nclass AddDelegate:\n\n _add: t.List[Table] = field(default_factory=list)\n\n def add(self, *instances: Table, table_class: t.Type[Table]):\n for instance in instances:\n if not isinstance(instance, table_class):\n raise TypeError(\"Incompatible type added.\")\n\n self._add += instances\n\n\n@dataclass\nclass OutputDelegate:\n \"\"\"\n Example usage:\n\n .output(as_list=True)\n .output(as_json=True)\n .output(as_json=True, as_list=True)\n \"\"\"\n\n _output: Output = field(default_factory=Output)\n\n def output(\n self,\n as_list: t.Optional[bool] = None,\n as_json: t.Optional[bool] = None,\n load_json: t.Optional[bool] = None,\n nested: t.Optional[bool] = None,\n ):\n \"\"\"\n :param as_list:\n If each row only returns a single value, compile all of the results\n into a single list.\n :param as_json:\n The results are serialised into JSON. It's equivalent to running\n `json.dumps` on the result.\n :param load_json:\n If True, any JSON fields will have the JSON values returned from\n the database loaded as Python objects.\n \"\"\"\n # We do it like this, so output can be called multiple times, without\n # overriding any existing values if they're not specified.\n if as_list is not None:\n self._output.as_list = bool(as_list)\n\n if as_json is not None:\n self._output.as_json = bool(as_json)\n\n if load_json is not None:\n self._output.load_json = bool(load_json)\n\n if nested is not None:\n self._output.nested = bool(nested)\n\n def copy(self) -> OutputDelegate:\n _output = self._output.copy() if self._output is not None else None\n return self.__class__(_output=_output)\n\n\n@dataclass\nclass PrefetchDelegate:\n \"\"\"\n Example usage:\n\n .prefetch(MyTable.column_a, MyTable.column_b)\n \"\"\"\n\n fk_columns: t.List[ForeignKey] = field(default_factory=list)\n\n def prefetch(self, *fk_columns: t.Union[ForeignKey, t.List[ForeignKey]]):\n \"\"\"\n :param columns:\n We accept ``ForeignKey`` and ``List[ForeignKey]`` here, in case\n someone passes in a list by accident when using ``all_related()``,\n in which case we flatten the list.\n\n \"\"\"\n _fk_columns: t.List[ForeignKey] = []\n for column in fk_columns:\n if isinstance(column, list):\n _fk_columns.extend(column)\n else:\n _fk_columns.append(column)\n\n combined = self.fk_columns + _fk_columns\n self.fk_columns = combined\n\n\n@dataclass\nclass ColumnsDelegate:\n \"\"\"\n Example usage:\n\n .columns(MyTable.column_a, MyTable.column_b)\n \"\"\"\n\n selected_columns: t.Sequence[Selectable] = field(default_factory=list)\n\n def columns(self, *columns: t.Union[Selectable, t.List[Selectable]]):\n \"\"\"\n :param columns:\n We accept ``Selectable`` and ``List[Selectable]`` here, in case\n someone passes in a list by accident when using ``all_columns()``,\n in which case we flatten the list.\n\n \"\"\"\n _columns = []\n for column in columns:\n if isinstance(column, list):\n _columns.extend(column)\n else:\n _columns.append(column)\n\n combined = list(self.selected_columns) + _columns\n self.selected_columns = combined\n\n def remove_secret_columns(self):\n self.selected_columns = [\n i for i in self.selected_columns if not isinstance(i, Secret)\n ]\n\n\n@dataclass\nclass ValuesDelegate:\n \"\"\"\n Used to specify new column values - primarily used in update queries.\n \"\"\"\n\n table: t.Type[Table]\n _values: t.Dict[Column, t.Any] = field(default_factory=dict)\n\n def values(self, values: t.Dict[t.Union[Column, str], t.Any]):\n \"\"\"\n Example usage:\n\n .. code-block:: python\n\n .values({MyTable.column_a: 1})\n\n # Or:\n .values({'column_a': 1})\n\n # Or:\n .values(column_a=1})\n\n \"\"\"\n cleaned_values: t.Dict[Column, t.Any] = {}\n for key, value in values.items():\n if isinstance(key, Column):\n column = key\n elif isinstance(key, str):\n column = self.table._meta.get_column_by_name(key)\n else:\n raise ValueError(\n f\"Unrecognised key - {key} is neither a Column or the \"\n \"name of a Column.\"\n )\n cleaned_values[column] = value\n\n self._values.update(cleaned_values)\n\n def get_sql_values(self) -> t.List[t.Any]:\n \"\"\"\n Convert any Enums into values, and serialise any JSON.\n \"\"\"\n return [\n convert_to_sql_value(value=value, column=column)\n for column, value in self._values.items()\n ]\n\n\n@dataclass\nclass OffsetDelegate:\n \"\"\"\n Used to offset the results - for example, to return row 100 and onward.\n\n Typically used in conjunction with order_by and limit.\n\n Example usage:\n\n .offset(100)\n \"\"\"\n\n _offset: t.Optional[Offset] = None\n\n def offset(self, number: int = 0):\n self._offset = Offset(number)\n\n\n@dataclass\nclass GroupBy:\n __slots__ = (\"columns\",)\n\n columns: t.Sequence[Column]\n\n @property\n def querystring(self) -> QueryString:\n columns_names = \", \".join(\n i._meta.get_full_name(just_alias=True) for i in self.columns\n )\n\n return QueryString(f\" GROUP BY {columns_names}\")\n\n def __str__(self):\n return self.querystring.__str__()\n\n\n@dataclass\nclass GroupByDelegate:\n \"\"\"\n Used to group results - needed when doing aggregation.\n\n .group_by(Band.name)\n \"\"\"\n\n _group_by: t.Optional[GroupBy] = None\n\n def group_by(self, *columns: Column):\n self._group_by = GroupBy(columns=columns)\n","sub_path":"piccolo/query/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":10015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"536170645","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport math\nimport warnings\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import ScalarFormatter\nimport numpy as np\nimport optuna\nimport pandas as pd\nimport seaborn as sns\nfrom covsirphy.util.argument import find_args\nfrom covsirphy.util.error import deprecate\nfrom covsirphy.util.stopwatch import StopWatch\nfrom covsirphy.util.evaluator import Evaluator\nfrom covsirphy.util.term import Term\nfrom covsirphy.ode.mbase import ModelBase\nfrom covsirphy.simulation.simulator import ODESimulator\n\n\nclass Estimator(Term):\n \"\"\"\n Hyperparameter optimization of an ODE model.\n\n Args:\n record_df (pandas.DataFrame)\n Index\n reset index\n Columns\n - Date (pd.Timestamp): Observation date\n - Confirmed (int): the number of confirmed cases\n - Infected (int): the number of currently infected cases\n - Fatal (int): the number of fatal cases\n - Recovered (int): the number of recovered cases\n - any other columns will be ignored\n model (covsirphy.ModelBase): ODE model\n population (int): total population in the place\n tau (int): tau value [min], a divisor of 1440\n kwargs: parameter values of the model and data subseting\n \"\"\"\n np.seterr(divide=\"raise\")\n optuna.logging.disable_default_handler()\n warnings.simplefilter(\"ignore\", FutureWarning)\n warnings.simplefilter(\"ignore\", SyntaxWarning)\n\n @deprecate(\"Estimator\", new=\"ODEHandler\", version=\"2.19.1-zeta-fu1\")\n def __init__(self, record_df, model, population, tau=None, **kwargs):\n # ODE model\n self.model = self._ensure_subclass(model, ModelBase, name=\"model\")\n self.variables = model.VARIABLES[:]\n self.variables_evaluate = [\n v for (v, p) in zip(model.VARIABLES, model.WEIGHTS) if p > 0]\n # Dataset\n if not set(self.NLOC_COLUMNS).issubset(record_df.columns):\n record_df = model.restore(record_df)\n self._ensure_dataframe(record_df, name=\"record_df\", columns=self.NLOC_COLUMNS)\n self.record_df = record_df.copy()\n # Settings for simulation\n self.population = self._ensure_population(population)\n df = model.tau_free(self.record_df, population, tau=None)\n self.y0_dict = {\n k: df.loc[df.index[0], k] for k in model.VARIABLES}\n # Fixed parameter values\n self.fixed_dict = {\n k: v for (k, v) in kwargs.items()\n if k in set(model.PARAMETERS) and v is not None\n }\n # For optimization\n self.study = None\n self.total_trials = 0\n self.runtime = 0\n # Tau value\n self.tau_final = self._ensure_tau(tau)\n self.tau_candidates = self.divisors(1440)\n self.tau = tau\n if tau is None:\n self.step_n = None\n self.taufree_df = pd.DataFrame()\n else:\n self._set_taufree()\n # Metrics\n self._metric = None\n # Keyword arguments of ModelBase.param_range()\n self._param_range_dict = {}\n\n def _init_study(self, seed, pruner, upper, percentile):\n \"\"\"\n Initialize Optuna study.\n\n Args:\n seed (int or None): random seed of hyperparameter optimization\n pruner (str): Hyperband, Median, Threshold or Percentile\n upper (float): works for \"threshold\" pruner,\n intermediate score is larger than this value, it prunes\n percentile (float): works for \"threshold\" pruner,\n the best intermediate value is in the bottom percentile among trials, it prunes\n \"\"\"\n pruner_dict = {\n \"hyperband\": optuna.pruners.HyperbandPruner(),\n \"median\": optuna.pruners.MedianPruner(),\n \"threshold\": optuna.pruners.ThresholdPruner(upper=upper),\n \"percentile\": optuna.pruners.PercentilePruner(percentile=percentile),\n }\n try:\n self.study = optuna.create_study(\n direction=\"minimize\",\n sampler=optuna.samplers.TPESampler(seed=seed),\n pruner=pruner_dict[pruner.lower()],\n )\n except KeyError:\n raise KeyError(\n f\"@pruner should be selected from {', '.join(pruner_dict.keys())}.\")\n\n def run(self, timeout=180, reset_n_max=3, timeout_iteration=5, tail_n=4, allowance=(0.99, 1.01),\n seed=0, pruner=\"threshold\", upper=0.5, percentile=50, metric=None, metrics=\"RMSLE\", **kwargs):\n \"\"\"\n Run optimization.\n If the result satisfied the following conditions, optimization ends.\n - Score did not change in the last @tail_n iterations.\n - Monotonic increasing variables increases monotonically.\n - Predicted values are in the allowance when each actual value shows max value.\n\n Args:\n timeout (int): timeout of optimization\n reset_n_max (int): if study was reset @reset_n_max times, will not be reset anymore\n timeout_iteration (int): time-out of one iteration\n tail_n (int): the number of iterations to decide whether score did not change for the last iterations\n allowance (tuple(float, float)): the allowance of the predicted value\n seed (int or None): random seed of hyperparameter optimization\n pruner (str): hyperband, median, threshold or percentile\n upper (float): works for \"threshold\" pruner,\n intermediate score is larger than this value, it prunes\n percentile (float): works for \"Percentile\" pruner,\n the best intermediate value is in the bottom percentile among trials, it prunes\n metric (str or None): metric name or None (use @metrics)\n metrics (str): alias of @metric\n kwargs: keyword arguments of ModelBase.param_range()\n\n Note:\n @n_jobs was obsoleted because this does not work effectively in Optuna.\n\n Note:\n Please refer to covsirphy.Evaluator.score() for metric names\n \"\"\"\n self._metric = metric or metrics\n self._param_range_dict = find_args(self.model.param_range, **kwargs)\n # Create a study of optuna\n if self.study is None:\n self._init_study(seed=seed, pruner=pruner, upper=upper, percentile=percentile)\n reset_n = 0\n iteration_n = math.ceil(timeout / timeout_iteration)\n increasing_cols = [f\"{v}{self.P}\" for v in self.model.VARS_INCLEASE]\n stopwatch = StopWatch()\n scores = []\n for _ in range(iteration_n):\n # Perform optimization\n self.study.optimize(self._objective, n_jobs=1, timeout=timeout_iteration)\n # If score did not change in the last iterations, stop running\n tau, param_dict = self._param()\n scores.append(self._score(tau=tau, param_dict=param_dict))\n if len(scores) >= tail_n and len(set(scores[-tail_n:])) == 1:\n break\n # Create a table to compare observed/estimated values\n comp_df = self._compare(tau=tau, param_dict=param_dict)\n # Check monotonic variables\n mono_ok_list = [comp_df[col].is_monotonic_increasing for col in increasing_cols]\n if not all(mono_ok_list):\n if reset_n == reset_n_max - 1:\n break\n # Initialize the study\n self._init_study(seed=seed)\n reset_n += 1\n continue\n # Need additional trials when the values are not in allowance\n if self._is_in_allowance(comp_df, allowance):\n break\n # Calculate run-time and the number of trials\n self.runtime += stopwatch.stop()\n self.total_trials = len(self.study.trials)\n\n def _is_in_allowance(self, comp_df, allowance):\n \"\"\"\n Return whether all max values of predicted values are in allowance or not.\n\n Args:\n comp_df (pandas.DataFrame): [description]\n allowance (tuple(float, float)): the allowance of the predicted value\n\n Returns:\n (bool): True when all max values of predicted values are in allowance\n \"\"\"\n a_max_values = [comp_df[f\"{v}{self.A}\"].max() for v in self.variables]\n p_max_values = [comp_df[f\"{v}{self.P}\"].max() for v in self.variables]\n allowance0, allowance1 = allowance\n ok_list = [\n (a * allowance0 <= p) and (p <= a * allowance1)\n for (a, p) in zip(a_max_values, p_max_values)\n ]\n return all(ok_list)\n\n def _objective(self, trial):\n \"\"\"\n Objective function of Optuna study.\n This defines the parameter values using Optuna.\n\n Args:\n trial (optuna.trial): a trial of the study\n\n Returns:\n float: score of the error function to minimize\n \"\"\"\n self.tau = self.tau_final or trial.suggest_categorical(self.TAU, self.tau_candidates)\n self._set_taufree()\n # Set parameters of the models\n model_param_dict = self.model.param_range(\n self.taufree_df, self.population, **self._param_range_dict)\n param_dict = {\n k: self._suggest(trial, k, *v)\n for (k, v) in model_param_dict.items()\n if k not in self.fixed_dict.keys()\n }\n param_dict.update(self.fixed_dict)\n return self._score(self.tau, param_dict)\n\n def _suggest(self, trial, name, min_value, max_value):\n \"\"\"\n Suggest parameter value for the trial.\n\n Args:\n trial (optuna.trial): a trial of the study\n name (str): parameter name\n min_value (float): minimum value of the parameter\n max_value (float): max value of the parameter\n\n Returns:\n optuna.trial\n \"\"\"\n try:\n return trial.suggest_uniform(name, min_value, max_value)\n except (OverflowError, np.AxisError):\n return trial.suggest_uniform(name, 0, 1)\n\n def _set_taufree(self):\n \"\"\"\n Divide T by tau in the training dataset and calculate the number of steps.\n \"\"\"\n self.taufree_df = self.model.tau_free(self.record_df, self.population, tau=self.tau)\n self.step_n = int(self.taufree_df[self.TS].max())\n\n def _score(self, tau, param_dict):\n \"\"\"\n Calculate score.\n\n Args:\n tau (int): tau value [min]\n param_dict (dict[str, int or float]): dictionary of parameter values\n\n Returns:\n float: score\n \"\"\"\n self.tau = tau\n self._set_taufree()\n cols = [self.TS, *self.variables_evaluate]\n rec_df = self.taufree_df.loc[:, cols]\n sim_df = self._simulate(self.step_n, param_dict).loc[:, cols]\n evaluator = Evaluator(rec_df, sim_df, on=self.TS)\n return evaluator.score(metric=self._metric)\n\n def _simulate(self, step_n, param_dict):\n \"\"\"\n Simulate the values with the parameters.\n\n Args:\n step_n (int): number of iteration\n dict[str, int or float]: dictionary of parameter values\n\n Returns:\n pandas.DataFrame:\n Index\n reset index\n Columns\n - t (int): Elapsed time divided by tau value [-]\n - columns with dimensionalized variables\n \"\"\"\n simulator = ODESimulator()\n simulator.add(\n model=self.model,\n step_n=step_n,\n population=self.population,\n param_dict=param_dict,\n y0_dict=self.y0_dict\n )\n return simulator.taufree()\n\n def _compare(self, tau, param_dict):\n \"\"\"\n Return comparison table.\n\n Args:\n tau (int): tau value [min]\n dict[str, int or float]: dictionary of parameter values\n\n Returns:\n pandas.DataFrame:\n Index\n t (int): Elapsed time divided by tau value [-]\n Columns\n - columns with \"_actual\"\n - columns with \"_predicted:\n - columns are defined by self.variables\n \"\"\"\n self.tau = tau\n self._set_taufree()\n sim_df = self._simulate(self.step_n, param_dict)\n df = self.taufree_df.merge(sim_df, on=self.TS, suffixes=(self.A, self.P))\n return df.set_index(self.TS)\n\n def _param(self):\n \"\"\"\n Return the estimated parameters as a dictionary.\n\n Returns:\n tuple(int, dict[str, int or float]): tau value and dictionary of parameter values\n \"\"\"\n try:\n param_dict = self.study.best_params.copy()\n except ValueError:\n param_dict = {p: 0 for p in self.model.PARAMETERS}\n if self.tau_final is None:\n param_dict[self.TAU] = None\n param_dict.update(self.fixed_dict)\n tau = self.tau_final or param_dict.pop(self.TAU)\n return (tau, param_dict)\n\n def to_dict(self):\n \"\"\"\n Summarize the results of optimization.\n\n Returns:\n dict[str, float or int]:\n - (parameters of the model)\n - tau\n - Rt: basic or phase-dependent reproduction number\n - (dimensional parameters [day])\n - {metric name}: score with the metric\n - Trials: the number of trials\n - Runtime: run time of estimation\n \"\"\"\n tau, param_dict = self._param()\n model_instance = self.model(population=self.population, **param_dict)\n return {\n **param_dict,\n self.TAU: tau,\n self.RT: model_instance.calc_r0(),\n **model_instance.calc_days_dict(tau),\n self._metric: self._score(tau, param_dict),\n self.TRIALS: self.total_trials,\n self.RUNTIME: StopWatch.show(self.runtime)\n }\n\n def _history(self):\n \"\"\"\n Return dataframe to show the history of optimization.\n\n Args:\n show_figure (bool): if True, show the history as a pair-plot of parameters.\n filename (str): filename of the figure, or None (show figure)\n\n Returns:\n pandas.DataFrame: the history\n \"\"\"\n # Create dataframe of the history\n df = self.study.trials_dataframe()\n series = df[\"datetime_complete\"] - df[\"datetime_start\"]\n df[\"time[s]\"] = series.dt.total_seconds()\n drop_cols = [\n \"datetime_complete\", \"datetime_start\", \"system_attrs__number\"]\n return df.drop(drop_cols, axis=1, errors=\"ignore\")\n\n def history(self, show_figure=True, filename=None):\n \"\"\"\n Return dataframe to show the history of optimization.\n\n Args:\n show_figure (bool): if True, show the history as a pair-plot of parameters.\n filename (str): filename of the figure, or None (show figure)\n\n Returns:\n pandas.DataFrame: the history\n \"\"\"\n df = self._history()\n if not show_figure:\n return df\n # Show figure\n fig_df = df.loc[:, df.columns.str.startswith(\"params_\")]\n fig_df.columns = fig_df.columns.str.replace(\"params_\", \"\")\n warnings.simplefilter(\"ignore\", category=UserWarning)\n sns.pairplot(fig_df, diag_kind=\"kde\", markers=\"+\")\n # Save figure or show figure\n if filename is None:\n plt.show()\n return df\n plt.savefig(filename, bbox_inches=\"tight\", transparent=False, dpi=300)\n plt.clf()\n return df\n\n def accuracy(self, show_figure=True, filename=None):\n \"\"\"\n Show accuracy as a figure.\n\n Args:\n show_figure (bool): if True, show the result as a figure\n filename (str): filename of the figure, or None (show figure)\n\n Returns:\n pandas.DataFrame:\n Index\n t (int): Elapsed time divided by tau value [-]\n Columns\n - columns with \"_actual\"\n - columns with \"_predicted:\n - columns are defined by self.variables\n \"\"\"\n # Create a table to compare observed/estimated values\n df = self._compare(*self._param())\n if not show_figure:\n return df\n # Variables to show accuracy\n variables = [\n v for (i, (p, v))\n in enumerate(zip(self.model.WEIGHTS, self.model.VARIABLES))\n if p != 0 and i != 0\n ]\n # Prepare figure object\n val_len = len(variables) + 1\n fig, axes = plt.subplots(\n ncols=1, nrows=val_len, figsize=(9, 6 * val_len / 2))\n # Comparison of each variable\n for (ax, v) in zip(axes.ravel()[1:], variables):\n df[[f\"{v}{self.A}\", f\"{v}{self.P}\"]].plot.line(\n ax=ax, ylim=(None, None), sharex=True,\n title=f\"{self.model.NAME}: Comparison regarding {v}(t)\"\n )\n ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))\n ax.ticklabel_format(style=\"sci\", axis=\"y\", scilimits=(0, 0))\n ax.legend(\n bbox_to_anchor=(1.02, 0), loc=\"lower left\", borderaxespad=0\n )\n # Summarize in a figure\n for v in variables:\n df[f\"{v}_diff\"] = df[f\"{v}{self.A}\"] - df[f\"{v}{self.P}\"]\n df[f\"{v}_diff\"].plot.line(\n ax=axes.ravel()[0], sharex=True,\n title=f\"{self.model.NAME}: observed - estimated\"\n )\n axes.ravel()[0].axhline(y=0, color=\"black\", linestyle=\"--\")\n axes.ravel()[0].yaxis.set_major_formatter(\n ScalarFormatter(useMathText=True))\n axes.ravel()[0].ticklabel_format(\n style=\"sci\", axis=\"y\", scilimits=(0, 0))\n axes.ravel()[0].legend(\n bbox_to_anchor=(1.02, 0), loc=\"lower left\", borderaxespad=0)\n fig.tight_layout()\n # Save figure or show figure\n if filename is None:\n plt.show()\n return df\n plt.savefig(filename, bbox_inches=\"tight\", transparent=False, dpi=300)\n plt.clf()\n return df\n\n\nclass Optimizer(Estimator):\n \"\"\"\n This is deprecated. Please use Estimator class.\n \"\"\"\n @deprecate(\"covsirphy.Estimator()\", new=\"covsirphy.Estimator\", version=\"2.17.0-eta\")\n def __init__(self, record_df, model, population, tau=None, **kwargs):\n super().__init__(record_df, model, population, tau=tau, **kwargs)\n","sub_path":"covsirphy/simulation/estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":18633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"375449709","text":"from selenium import webdriver\nimport unittest\nimport time\n\ndriver = webdriver.Chrome()\n\n# driver.find_element_by_name(\"tj_trnews\").click()\n# navs = driver.find_elements_by_class_name(\"mnav\")\n# for i in navs:\n# i.click()\n# driver.back()\n# for index in range(len(navs)):\n# navs = driver.find_elements_by_class_name(\"mnav\")\n# navs[index].click()\n# driver.back()\n# time.sleep(1)\n \n# counter = len(navs)\n# for index in range(counter):\n# i = index + 1\n# css = \"#u1>a:nth-child(\"+str(i)+\")\"\n# driver.find_element_by_css_selector(css).click()\n# driver.back()\n# driver.find_element_by_link_text(\"新闻\").click()\n# driver.find_element_by_partial_link_text(\"新\").click()\n \n\n\n\ndef search():\n baidu_input = driver.find_element_by_id(\"kw\")\n baidu_input.send_keys(\"仓鼠\")\n time.sleep(1)\n baidu_input.clear()\n baidu_input.send_keys(\"金丝熊\")\n # driver.find_element_by_class_name(\"bg s_btn\").click()\n driver.find_element_by_id(\"su\").click()\n\n time.sleep(1)\n content = driver.find_element_by_id(\"content_left\")\n with open(\"kele.txt\",'w', encoding = \"utf-8\") as f :\n f.write(content.text)\n\n# print(content.text)\n\n# time.sleep(3)\n# driver.quit()\n###京东\n# text = driver.find_element_by_css_selector(\".price.J-p-7081550\").text\ndriver.get(\"https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=shou%27j&pvid=8efa5cc4abe84804b801a390f641a2eb\")\n# print(\"打开首页之后浏览器窗口个数\",len(driver.window_handles))\n# text1 = driver.find_elements_by_css_selector(\".gl-item\")#多个元素调用的是elements,而且不需要调用text\n# num = len(text1)\n# print(num)\nimg = driver.find_elements_by_css_selector('li.gl-item>div.gl-i-wrap>div.p-img>a:nth-child(1)')\n# eles = driver.find_elements_by_xpath(\"//*[@id='J_goodsList']/ul/li[1]/div/div[1]/a\")\n\n#####img是一个数组?可遍历的\n# num = len(eles)\nnum = len(img)\nprint(num)\n# img[0].click()\n# print(\"打开第一个之后浏览器窗口个数\",len(driver.window_handles))\n# all_windows = driver.window_handles\n# driver.switch_to_window(all_windows[0])\n# img[1].click()\n#循环切换手机界面\n# for i in range(num) :\n# # img = driver.find_elements_by_css_selector(\"li.gl-item>div.gl-i-wrap>div.p-img>a:nth-child(1)\")\n# driver.maximize_window()#窗口最大化,碍于二维码\n# img[i].click()\n# all_windows = driver.window_handles\n# # print(len(all_windows))\n# # time.sleep(2)\n# driver.switch_to.window(all_windows[1])#切换到第二个\n# time.sleep(2)\n# driver.close() #关闭当前tab\n# driver.switch_to.window(all_windows[0])#切换第一个\n\n\n\n \n\n\n\n\n \n","sub_path":"before/0105_first_lseeon.py","file_name":"0105_first_lseeon.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"368442955","text":"import logging\nimport sys\nimport os\nimport argparse\n\nfrom .metabase import MetabaseClient\nfrom .parsers.dbt_folder import DbtFolderReader\nfrom .parsers.dbt_manifest import DbtManifestReader\n\nfrom typing import Iterable, List, Union\n\n__version__ = \"0.8.0\"\n\n\ndef export(\n dbt_database: str,\n metabase_database: str,\n metabase_host: str,\n metabase_user: str,\n metabase_password: str,\n dbt_manifest_path: str = \"\",\n dbt_path: str = \"\",\n dbt_docs_url: str = None,\n metabase_use_http: bool = False,\n metabase_verify: Union[str, bool] = True,\n metabase_sync_skip: bool = False,\n metabase_sync_timeout: int = None,\n schema: str = \"public\",\n schema_excludes: Iterable = None,\n includes: Iterable = None,\n excludes: Iterable = None,\n include_tags: bool = True,\n):\n \"\"\"Exports models from dbt to Metabase.\n\n Args:\n dbt_database (str): Source database name.\n metabase_database (str): Target Metabase database name. Database in Metabase is aliased.\n metabase_host (str): Metabase hostname.\n metabase_user (str): Metabase username.\n metabase_password (str): Metabase password.\n dbt_manifest_path (str, optional): Path to dbt project manifest.json [Primary]. Defaults to \"\".\n dbt_path (str, optional): Path to dbt project. [Alternative]. Defaults to \"\".\n dbt_docs_url (str, optional): URL to your dbt docs hosted catalog, a link will be appended to the model description (only works for manifest parsing). Defaults to None.\n metabase_use_http (bool, optional): Use HTTP to connect to Metabase instead of the default HTTPS. Defaults to False.\n metabase_verify (Union[str, bool], optional): Supply path to certificate or disable verification. Defaults to True.\n metabase_sync_skip (bool, optional): Skip synchronizing Metabase database before export. Defaults to False.\n metabase_sync_timeout (int, optional): Metabase synchronization timeout in seconds. Defaults to None.\n schema (str, optional): Target schema name. Defaults to \"public\".\n schema_excludes (Iterable, optional): Alternative to target schema, specify schema exclusions (only works for manifest parsing). Defaults to None.\n includes (Iterable, optional): Model names to limit processing to. Defaults to None.\n excludes (Iterable, optional): Model names to exclude. Defaults to None.\n include_tags (bool, optional): Append the dbt tags to the end of the table description. Defaults to True.\n \"\"\"\n\n if schema_excludes is None:\n schema_excludes = []\n if includes is None:\n includes = []\n if excludes is None:\n excludes = []\n\n # Assertions\n assert bool(dbt_path) != bool(\n dbt_manifest_path\n ), \"Bad arguments. dbt_path and dbt_manifest_path cannot be provide at the same time. One option must be specified.\"\n if dbt_path:\n assert (\n schema and not schema_excludes\n ), \"Must target a single schema if using yaml parser, multiple schemas not supported.\"\n assert bool(schema) != bool(\n schema_excludes\n ), \"Bad arguments. schema and schema_excludes cannot be provide at the same time. One option must be specified.\"\n\n # Instantiate Metabase client\n mbc = MetabaseClient(\n host=metabase_host,\n user=metabase_user,\n password=metabase_password,\n use_http=metabase_use_http,\n verify=metabase_verify,\n )\n reader: Union[DbtFolderReader, DbtManifestReader]\n\n # Resolve dbt reader being either YAML or manifest.json based\n if dbt_path:\n reader = DbtFolderReader(os.path.expandvars(dbt_path))\n else:\n reader = DbtManifestReader(os.path.expandvars(dbt_manifest_path))\n\n if schema_excludes:\n schema_excludes = {schema.upper() for schema in schema_excludes}\n\n # Process dbt stuff\n models = reader.read_models(\n database=dbt_database,\n schema=schema,\n schema_excludes=schema_excludes,\n includes=includes,\n excludes=excludes,\n include_tags=include_tags,\n docs_url=dbt_docs_url,\n )\n\n # Sync and attempt schema alignment prior to execution; if timeout is not explicitly set, proceed regardless of success\n if not metabase_sync_skip:\n if metabase_sync_timeout is not None and not mbc.sync_and_wait(\n metabase_database, schema, models, metabase_sync_timeout\n ):\n logging.critical(\"Sync timeout reached, models still not compatible\")\n return\n\n # Process Metabase stuff\n mbc.export_models(metabase_database, schema, models, reader.catch_aliases)\n\n\ndef main(args: List = None):\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(message)s\", level=logging.INFO\n )\n\n parser = argparse.ArgumentParser(\n description=\"Model synchronization from dbt to Metabase.\"\n )\n parser.add_argument(\"command\", choices=[\"export\"], help=\"command to execute\")\n\n # dbt arguments\n parser.add_argument(\n \"--dbt_database\",\n metavar=\"DB\",\n required=True,\n help=\"Target database name as specified in dbt\",\n )\n parser.add_argument(\n \"--dbt_path\",\n help=\"Path to dbt project. Cannot be specified with --dbt_manifest_path\",\n )\n parser.add_argument(\n \"--dbt_manifest_path\",\n help=\"Path to dbt manifest.json (typically located in the /target/ directory of the dbt project directory). Cannot be specified with --dbt_path\",\n )\n parser.add_argument(\n \"--dbt_docs\",\n metavar=\"URL\",\n help=\"Pass in URL to dbt docs site. Appends dbt docs URL for each model to Metabase table description\",\n )\n\n # Metabase arguments\n parser.add_argument(\n \"--metabase_database\",\n metavar=\"DB\",\n required=True,\n help=\"Target database name as set in Metabase (typically aliased)\",\n )\n parser.add_argument(\n \"--metabase_host\", metavar=\"HOST\", required=True, help=\"Metabase hostname\"\n )\n parser.add_argument(\n \"--metabase_user\", metavar=\"USER\", required=True, help=\"Metabase username\"\n )\n parser.add_argument(\n \"--metabase_password\", metavar=\"PASS\", required=True, help=\"Metabase password\"\n )\n parser.add_argument(\n \"--metabase_use_http\",\n action=\"store_true\",\n help=\"use HTTP to connect to Metabase instead of HTTPS\",\n )\n parser.add_argument(\n \"--metabase_verify\",\n metavar=\"CERT\",\n help=\"Path to certificate bundle used by Metabase client\",\n )\n parser.add_argument(\n \"--metabase_sync_skip\",\n action=\"store_true\",\n help=\"Skip synchronizing Metabase database before export\",\n )\n parser.add_argument(\n \"--metabase_sync_timeout\",\n metavar=\"SECS\",\n type=int,\n help=\"Synchronization timeout (in secs). If set, we will fail hard on synchronization failure; if not set, we will proceed after attempting sync regardless of success\",\n )\n\n # Common/misc arguments\n parser.add_argument(\n \"--schema\",\n metavar=\"SCHEMA\",\n help=\"Target schema name. Cannot be specified with --schema_excludes\",\n )\n parser.add_argument(\n \"--schema_excludes\",\n help=\"Target schemas to exclude. Cannot be specified with --schema. Will sync all schemas not excluded\",\n )\n parser.add_argument(\n \"--includes\",\n metavar=\"MODELS\",\n nargs=\"*\",\n default=[],\n help=\"Model names to limit processing to\",\n )\n parser.add_argument(\n \"--excludes\",\n metavar=\"MODELS\",\n nargs=\"*\",\n default=[],\n help=\"Model names to exclude\",\n )\n parser.add_argument(\n \"--include_tags\",\n action=\"store_true\",\n default=False,\n help=\"Append tags to Table descriptions in Metabase\",\n )\n parser.add_argument(\n \"--verbose\",\n action=\"store_true\",\n default=False,\n help=\"Verbose output\",\n )\n\n parsed = parser.parse_args(args=args)\n\n if parsed.verbose:\n logger = logging.getLogger()\n logger.addHandler(logging.StreamHandler(sys.stdout))\n logger.setLevel(logging.DEBUG)\n\n if parsed.command == \"export\":\n export(\n dbt_database=parsed.dbt_database,\n dbt_manifest_path=parsed.dbt_manifest_path,\n dbt_path=parsed.dbt_path,\n dbt_docs_url=parsed.dbt_docs,\n metabase_database=parsed.metabase_database,\n metabase_host=parsed.metabase_host,\n metabase_user=parsed.metabase_user,\n metabase_password=parsed.metabase_password,\n metabase_use_http=parsed.metabase_use_http,\n metabase_verify=parsed.metabase_verify,\n metabase_sync_skip=parsed.metabase_sync_skip,\n metabase_sync_timeout=parsed.metabase_sync_timeout,\n schema=parsed.schema,\n schema_excludes=parsed.schema_excludes,\n includes=parsed.includes,\n excludes=parsed.excludes,\n include_tags=parsed.include_tags,\n )\n","sub_path":"dbtmetabase/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"636442228","text":"class Vertex: ##图中的顶点是抽象的,具体表示内容可以自己拓展\n def __init__(self,value):\n self.value=value\n\n\n\nclass Graph: ##无向图\n def __init__(self):\n self.INFINITE = float(\"inf\") ##INFINITE大于python所有数\n\n\n\n\n def Receive_Graph_info(self):\n Vertexs=[]\n Edges=dict()\n print(\"输入你的顶点值,按e退出顶点值的输入\")\n while True:\n vertex_value=input()\n if vertex_value == 'e':\n break\n Vertexs.append(vertex_value)\n print(\"输入你的图的边关系,按e退出\")\n for vertex in Vertexs:\n print(\"输入\"+str(vertex)+\"顶点对应点边与权值,按e退出\")\n while True:\n connect_edge=input(str(vertex)+\"的对应边:\")\n if connect_edge =='e':\n break\n weight = input(str(vertex)+\"与顶点\"+str(connect_edge)+\"对应的权值:\")\n Edges[str(vertex)+\"->\"+str(connect_edge)]=weight\n\n return Vertexs,Edges\n\n\n\n def Generate_AdjacencyMatrix(self,Vertexs,Edgess): ##不维护用户输入的错误\n Vertexs_num=len(Vertexs)\n AdjacencyMatrix=[[ self.INFINITE for i in range(Vertexs_num)]for i in range(Vertexs_num)] ##利用列表生成式构造矩阵\n for i in range(Vertexs_num):\n AdjacencyMatrix[i][i]=0 ##每个顶点到自己到距离是0\n\n for edge_relationship in Edgess: ##利用边关系的数据,每次提取一组边关系,然后写入矩阵以及对应的权值\n temporylist=[]\n weight=Edgess[edge_relationship]\n for i in edge_relationship.split('->'):\n temporylist.append(int(i)) ##split分割后是str格式,这里我需要int格式\n AdjacencyMatrix[temporylist[0]][temporylist[1]]=weight ##如果利用无向图矩阵对称性质可以优化代码\n\n return AdjacencyMatrix\n\n\n\n'''\nINF=float(\"inf\")\nmatrix=[[INF for i in range(5)] for i in range(5)]\nfor i in range(5):\n matrix[i][i]=0\n\ntemporyvertexs=[0,1,2,3,4]\ntemporydict={'0->1':4,'0->2':4,'0->3':6,'0->4':6,'1->0':4,'1->2':2,'2->1':2,'2->0':4,'2->3':8,'3->2':8,'3->0':6,'3->4':9,'4->0':6,'4->3':9}\nfor edge_relationship in temporydict:\n a=[]\n w=temporydict[edge_relationship]\n for i in edge_relationship.split('->'):\n a.append(int(i))\n matrix[a[0]][a[1]]=w\nprint(matrix)\na=Graph()\nv,w=a.Receive_Graph_info()\nprint(a.Generate_AdjacencyMatrix(v,w))\n领接矩阵测试通过!\n'''\n","sub_path":"Graph/AdjacencyMatrix.py","file_name":"AdjacencyMatrix.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"166222857","text":"import numpy as np\nimport tensorflow as tf\nimport sklearn.preprocessing as prep\n\n\ndef variance_scaling_initializer(factor=2.0, mode='FAN_IN', uniform=False, seed=None, dtype=tf.float32):\n # https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/contrib/layers/python/layers/initializers.py\n if not dtype.is_floating:\n raise TypeError('Cannot create initializer for non-floating point type.')\n if mode not in ['FAN_IN', 'FAN_OUT', 'FAN_AVG']:\n raise TypeError('Unknown mode %s [FAN_IN, FAN_OUT, FAN_AVG]', mode)\n\n def _initializer(shape, dtype=dtype, partition_info=None):\n \"\"\"Initializer function.\"\"\"\n if not dtype.is_floating:\n raise TypeError('Cannot create initializer for non-floating point type.')\n # Estimating fan_in and fan_out is not possible to do perfectly, but we try.\n # This is the right thing for matrix multiply and convolutions.\n if shape:\n fan_in = float(shape[-2]) if len(shape) > 1 else float(shape[-1])\n fan_out = float(shape[-1])\n else:\n fan_in = 1.0\n fan_out = 1.0\n for dim in shape[:-2]:\n fan_in *= float(dim)\n fan_out *= float(dim)\n if mode == 'FAN_IN':\n # Count only number of input connections.\n n = fan_in\n elif mode == 'FAN_OUT':\n # Count only number of output connections.\n n = fan_out\n elif mode == 'FAN_AVG':\n # Average number of inputs and output connections.\n n = (fan_in + fan_out) / 2.0\n if uniform:\n # To get stddev = math.sqrt(factor / n) need to adjust for uniform.\n limit = np.sqrt(3.0 * factor / n)\n return tf.random_uniform(shape, -limit, limit, dtype, seed=seed)\n else:\n # To get stddev = math.sqrt(factor / n) need to adjust for truncated.\n trunc_stddev = np.sqrt(1.3 * factor / n)\n return tf.truncated_normal(shape, 0.0, trunc_stddev, dtype, seed=seed)\n\n return _initializer\n\n\ndef xavier_initializer(uniform=True, seed=None, dtype=tf.float32):\n return variance_scaling_initializer(factor=1.0, mode='FAN_AVG', uniform=uniform, seed=seed, dtype=dtype)\n\n\n'''\ndef xavier_init(shape, constant=1):\n # shape must be a list with at least two elements\n assert len(shape) > 1\n fan_in = shape[0]\n fan_out = shape[1]\n low = -constant * np.sqrt(6.0 / (fan_in + fan_out))\n high = constant * np.sqrt(6.0 / (fan_in + fan_out))\n return tf.random_uniform((fan_in, fan_out), minval=low, maxval=high, dtype=tf.float32)\n'''\n\n\ndef zscore(data, axis=0, truncate=False, scale=False):\n if axis == 1:\n data = data.transpose()\n preprocessor = prep.StandardScaler().fit(data)\n data = preprocessor.transform(data)\n if truncate:\n data = np.clip(data, -3, 3)\n if scale:\n prep.minmax_scale(data, feature_range=(-1, 1))\n if axis == 1:\n return data.transpose()\n return data, preprocessor\n\n\ndef min_max_scale(data):\n preprocessor = prep.MinMaxScaler().fit(data)\n data = preprocessor.transform(data)\n return data\n\n\ndef get_random_block_from_data(data, batch_size):\n start_index = np.random.randint(0, len(data) - batch_size)\n return data[start_index:(start_index + batch_size)]\n\n\ndef montage_batch(images):\n \"\"\"Draws all filters (n_input * n_output filters) as a\n montage image separated by 1 pixel borders.\n\n Parameters\n ----------\n batch : numpy.ndarray\n Input array to create montage of.\n\n Returns\n -------\n m : numpy.ndarray\n Montage image.\n \"\"\"\n img_h = images.shape[1]\n img_w = images.shape[2]\n n_plots = int(np.ceil(np.sqrt(images.shape[0])))\n m = np.ones(\n (images.shape[1] * n_plots + n_plots + 1,\n images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5\n\n for i in range(n_plots):\n for j in range(n_plots):\n this_filter = i * n_plots + j\n if this_filter < images.shape[0]:\n this_img = images[this_filter, ...]\n m[1 + i + i * img_h:1 + i + (i + 1) * img_h,\n 1 + j + j * img_w:1 + j + (j + 1) * img_w, :] = this_img\n return m\n","sub_path":"test2d-conv/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"435474539","text":"\"\"\"Code to load node attributes table and graph from edgelist.\nBased on https://github.com/dmlc/dgl/blob/master/python/dgl/data/citation_graph.py.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.sparse as sp\nimport os, sys\nfrom dgl import DGLGraph\nimport pandas as pd\nfrom itertools import chain\n\nimport dgl\n\nclass NodeandEdgeDataset():\n \"\"\"Joint dataset including an edge list for creating a graph from an edge list and a node attribute table \n with columns: d3mIndex, nodeId, feat1,...,featN, node_label.\n \"\"\"\n def __init__(self):\n #self._load()\n pass \n\n def _load_node_attr(self, node_features: pd.DataFrame):\n # idx_features_labels = np.genfromtxt(\"{}/cora/cora.content\".\n # format(self.dir),\n # dtype=np.dtype(str))\n idx_features_labels = node_features.to_numpy()\n # features = sp.csr_matrix(idx_features_labels[:, 1:-1],\n # dtype=np.float32)\n features = sp.csr_matrix(idx_features_labels[:, 2:-1], # skip 1st two columns: d3mindex, node_id\n dtype=np.float32)\n features = _normalize(features)\n self.features = np.array(features.todense())\n # Use the entire training data set.\n # self.train_mask = _sample_mask(range(140), labels.shape[0])\n # self.val_mask = _sample_mask(range(200, 500), labels.shape[0])\n # self.test_mask = _sample_mask(range(500, 1500), labels.shape[0])\n return features\n\n def _load_node_labels(self, node_features: pd.DataFrame):\n idx_features_labels = node_features.to_numpy()\n labels = _encode_onehot(idx_features_labels[:, -1])\n self.num_labels = labels.shape[1]\n self.labels = np.where(labels)[1]\n return labels\n\n # def _load_graph(self, graph_edgelist: pd.DataFrame, node_features: pd.DataFrame):\n # idx_features_labels = node_features.to_numpy()\n # labels = _encode_onehot(idx_features_labels[:, -1])\n # # build graph\n # #idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n # idx = np.array(idx_features_labels[:, 1], dtype=np.int32) # Use node_id, not d3mindex\n # idx_map = {j: i for i, j in enumerate(idx)}\n # # edges_unordered = np.genfromtxt(\"{}/cora/cora.cites\".format(self.dir),\n # # dtype=np.int32)\n # edges_unordered = graph_edgelist.to_numpy()\n # edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),\n # dtype=np.int32).reshape(edges_unordered.shape)\n # adj = sp.coo_matrix((np.ones(edges.shape[0]),\n # (edges[:, 0], edges[:, 1])),\n # shape=(labels.shape[0], labels.shape[0]),\n # dtype=np.float32)\n\n # # build symmetric adjacency matrix\n # adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n # self.graph = nx.from_scipy_sparse_matrix(adj, create_using=nx.DiGraph())\n # return self.graph\n\n def _load_graph(self, graph_edgelist: pd.DataFrame, node_features: pd.DataFrame):\n # labels = _encode_onehot(node_features.label.values)\n # idx = node_features.nodeID.values.astype(int)\n idx = set(chain(set(graph_edgelist[\"node1\"].values),set(graph_edgelist[\"node2\"].values)))\n idx_map = {j: i for i, j in enumerate(idx)}\n num_nodes = len(idx_map)\n print(f\"idx_map length = {num_nodes}\")\n edges_unordered = graph_edgelist[[\"node1\", \"node2\"]].values\n edges = np.array(\n [\n (idx_map[i], idx_map[j])\n for i, j in edges_unordered\n if (i in idx_map and j in idx_map)\n ]\n )\n print(f\"edges length = {len(edges)}\")\n # adj = sp.coo_matrix(\n # (np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),\n # shape=(labels.shape[0], labels.shape[0]),\n # dtype=np.float32,\n # )\n adj = sp.coo_matrix(\n (np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),\n shape=(num_nodes, num_nodes),\n dtype=np.float32,\n )\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n self.graph = nx.from_scipy_sparse_matrix(adj, create_using=nx.DiGraph())\n return self.graph\n \n def __getitem__(self, idx):\n assert idx == 0, \"This dataset has only one graph\"\n g = DGLGraph(self.graph)\n # g.ndata['train_mask'] = self.train_mask\n # g.ndata['val_mask'] = self.val_mask\n # g.ndata['test_mask'] = self.test_mask\n g.ndata['label'] = self.labels\n g.ndata['feat'] = self.features\n return g\n \n def __len__(self):\n return 1\n\n\n\ndef _normalize(mx):\n \"\"\"Row-normalize sparse matrix\"\"\"\n rowsum = np.array(mx.sum(1))\n r_inv = np.power(rowsum, -1).flatten()\n r_inv[np.isinf(r_inv)] = 0.\n r_mat_inv = sp.diags(r_inv)\n mx = r_mat_inv.dot(mx)\n return mx\n\ndef _encode_onehot(labels):\n classes = list(sorted(set(labels)))\n classes_dict = {c: np.identity(len(classes))[i, :] for i, c in\n enumerate(classes)}\n labels_onehot = np.array(list(map(classes_dict.get, labels)),\n dtype=np.int32)\n return labels_onehot\n\ndef _sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return mask\n","sub_path":"nk_gcn_vertex_class/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"457803140","text":"'''\r\nAbbiamo immagini in formato png ottenute inserendo su di uno sfondo monocolore rettangoli \r\ndi vari colori i cui assi sono sempre parallei agli assi dell'immagine.\r\n\r\nVedi ad esempio l'immagine Img1.png\r\n\r\nPer caricare e salvare immagini PNG usate le funzioni load e save che abbiamo preparato nel modulo immagini.py .\r\n\r\nScrivere una funzione quadrato(filename, C) che prende in input:\r\n- il percorso di un file (filename) che contine un immagine in formato png della tipologia appena descritta.\r\n- una tupla C che rappresenta un colore in formato RGB (3 valori interi tra 0 e 255 compresi)\r\n\r\nLa funzione deve restituire nell'ordine:\r\n- la lunghezza del lato del quadrato pieno di dimensione massima e colore C interamente visibile nell'immagine. \r\n- le coordinate (x,y) del pixel dell'immagine che corrisponde alla posizione \r\nall'interno dell'immagine del punto in alto a sinistra del quadrato. \r\n\r\nIn caso ci siano più quadrati di dimensione massima, va considerato quello il cui punto \r\nin alto a sinistra occupa la riga minima (e a parita' di riga la colonna minima) all'interno dell' immagine. \r\n\r\nSi può assumere che nell'immagine e' sempre presente almeno un pixel del colore cercato.\r\n\r\nPer gli esempi vedere il file grade01.txt\r\n\r\nATTENZIONE: Il timeout è impostato a 10*N secondi (con N numero di test del grader).\r\n'''\r\n\r\n#from immagini import *\r\nimport png\r\n \r\ndef quadrato(filename,c):\r\n '''Implementare qui la funzione'''\r\n with open(filename, mode='rb') as f:\r\n reader = png.Reader(file=f)\r\n w, h, png_img, _ = reader.asRGB8()\r\n img = []\r\n for line in png_img:\r\n l = []\r\n for i in range(0, len(line), 3):\r\n l+=[(line[i], line[i+1], line[i+2])]\r\n img+=[l]\r\n\r\n# img=load(filename)\r\n massimo=0\r\n ret=(0,(0,0))\r\n test=0\r\n a=0\r\n for x in range(len(img)):\r\n #print(\"X=\"+str(x)+ \" \")\r\n for y in range(len(img[0])):\r\n if c==img[x][y]:\r\n\r\n i=1\r\n test=0\r\n while (test==0 and x+imassimo:\r\n \r\n massimo=i\r\n ret=(i,(y,x))\r\n \r\n\r\n \r\n\r\n return ret\r\n\r\n\r\n","sub_path":"students/1814615/homework03/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"444295732","text":"# -*- coding: UTF-8 -*-\n\"\"\"LOG日志处理\"\"\"\n\nimport re\nimport xlwt\nimport datetime\n# FILLE_NAME = '20171018-4s'\n# FILLE_NAME = 'LOG_rocksdb_origin-ycsb_1G_50G_onlyrun_cld'\n# FILLE_NAME = 'LOG-4s-nocompression'\nFILLE_NAME = 'LOG_slot_optimal_default_ycsb_run_60G'\nFILLE_NAME = r'G:\\1-RocksDB\\Slot_Optimal实验\\LOG_slot_optimal-nocompression-ycsb_insert_60G'\n\ndef find(regex, text):\n \"\"\"查找正则表达式匹配结果\"\"\"\n pattern = re.compile(regex, re.DOTALL + re.MULTILINE)\n return pattern.findall(text)\n\ndef get_textlist(path, regex):\n \"\"\"将log按照时间间隔分段\"\"\"\n with open(path, 'r') as fread:\n text = fread.read()\n textlist = re.split(regex, text)\n del textlist[0]\n return textlist\n\ndef get_title(table, level_name_list, db_name_list):\n \"\"\"获得表头\"\"\"\n for name in level_name_list:\n for i in range(8):\n table[0].append(\"L\"+str(i)+\" \"+name)\n for name in db_name_list:\n table[0].append(name)\n\ndef get_row(text):\n \"\"\"获得表的每一行的值\"\"\"\n # Level Files Size Score Read(GB)\n regex_line = r'L(\\d)\\s*(\\d+)/\\d+\\s*(\\d+\\.?\\d*\\s\\w+)\\s*(\\d+\\.?\\d*)\\s*\\d+\\.?\\d*\\s*'\n # Rn(GB) Rnp1(GB) Write(GB) Wnew(GB) Moved(GB) W-Amp\n regex_line += r'\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*(\\d+\\.?\\d*)\\s*'\n # Rd(MB/s) Wr(MB/s) Comp(sec)Comp(cnt)Avg(sec)\n regex_line += r'\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\s*\\d+\\s*(\\d+\\.?\\d*)\\s*'\n\n regex_line = r'L(\\d)\\s*(\\d+)/\\d+\\s*(\\d+\\.?\\d*\\s\\w+)\\s*(\\d+\\.?\\d*)\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*(\\d+\\.?\\d*)\\s*\\d+\\.?\\d*\\s*\\d+\\.?\\d*\\s*\\d+\\s*\\d+\\s*(\\d+\\.?\\d*)\\s*'\n level_list = find(regex_line, text) #返回 [[层号,files,size,score,w-amp,avg(sec)]]\n # 返回 interval compaction: [[写入量(GB),写入速率(MB/s)]]\n # inter_com = find(r'Interval\\scompaction:\\s(\\d+\\.?\\d*)\\sGB\\swrite,\\\n # \\s(\\d+\\.?\\d*)\\sMB/s\\swrite', text)\n time_detail = find(r'\\d\\d\\d\\d/\\d\\d/\\d\\d-(\\d\\d:\\d\\d:\\d\\d)\\.\\d+.*?\\n\\*\\* DB Stats \\*\\*', text)\n time_sec = find(r'Uptime\\(secs\\):\\s(\\d+\\.?\\d*)\\stotal', text)\n #返回interval write ingest速率(MB/s)\n int_write = find(r'Interval\\swrites.*?ingest:\\s\\d+\\.?\\d*\\s\\w*,\\s(\\d+\\.?\\d*)\\sMB/s', text)\n #返回前台写入停顿频率\n int_stall = find(r'Interval\\sstall:\\s\\d\\d:\\d\\d:\\d+\\.?\\d*\\sH:M:S,\\s(\\d+\\.?\\d*)\\spercent', text)\n if len(level_list) <= 0 or len(int_write) <= 0 or len(int_stall) <= 0:\n print(\"can't find\")\n return [-1]*(5*8+3)\n num_in_l = (len(level_list[0])-1)\n level = [[-1 for j in range(8)] for i in range(num_in_l)]\n for one in level_list:\n for i in range(num_in_l):\n if i == 0: #files num 为整型\n level[i][int(one[0])] = int(one[i+1])\n elif i == 1: #对size不同单位,如MB、GB统一转换为MB\n size_list = one[i+1].split(\" \")\n if size_list[1] == \"GB\":\n level[i][int(one[0])] = float(size_list[0])*1024\n elif size_list[1] == \"MB\":\n level[i][int(one[0])] = float(size_list[0])\n else:\n pass\n else: #其他为浮点型\n level[i][int(one[0])] = float(one[i+1])\n row = []\n for i in level:\n for j in i:\n row.append(j)\n for i in int_write:\n row.append(float(i))\n for i in int_stall:\n row.append(float(i))\n row.append(float(time_sec[0]))\n row.append(time_detail[0])\n return row\n\ndef get_table(textlist):\n \"\"\"将log分段的表转换为table\"\"\"\n table = [[]]\n level_name_list = [\"Files\", \"Size (MB)\", \"score\", \"w-amp\", \"avg(sec)\"]\n db_name_list = [\"interval write ingest(MB/s)\", \"Interval stall(%)\", \"time sec\", \"time_detail\"]\n get_title(table, level_name_list, db_name_list)\n for text in textlist:\n row = get_row(text)\n if row:\n table.append(row)\n return table\n\ndef table2xls(table, xlsname):\n \"\"\"将table写入excel\"\"\"\n xlswb = xlwt.Workbook(encoding='utf-8')\n xlsws = xlswb.add_sheet('test')\n for i, row in enumerate(table):\n for j, one in enumerate(row):\n xlsws.write(i, j, one)\n xlswb.save(xlsname)\n\n# 处理统计表\n# 将日志分段,按照------- DUMPING STATS -------\nbeginTime = datetime.datetime.now()\n\nTEXT_LIST = get_textlist(FILLE_NAME, r'------- DUMPING STATS -------')\nTABLE = get_table(TEXT_LIST)\ntable2xls(TABLE, FILLE_NAME + \".xls\")\nendTime = datetime.datetime.now()\nprint(\"The script uses \"+(str)(endTime - beginTime))\n\n# # 处理时间\n# C_TABLE = []\n# C_TABLE.append([\"time\", \"from level1\", \"from level2\", \"to level\", \"score\"])\n# with open(FILLE_NAME + \".log\", 'r') as f:\n# for line in f:\n# if re.match(r'.*?Compacting\\s\\d@\\d\\s\\+\\s\\d@\\d\\sfiles\\sto.*?,\\sscore.*?', line):\n# print(line)\n# c_time = re.search(r'\\d\\d:\\d\\d:\\d\\d', line)\n# [(c_l1, c_l2)] = re.findall(r'\\d@(\\d) \\+ \\d@(\\d)', line)\n# c_l = re.search(r'L(\\d)', line)\n# [c_score] = re.findall(r'score (\\d+\\.\\d+)', line)\n# C_TABLE.append([c_time.group(0), c_l1, c_l2, c_l.group(0), c_score])\n# table2xls(C_TABLE, \"exactly time.xls\")\n","sub_path":"[Important]python_log_parse/logstat_log_new.py","file_name":"logstat_log_new.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"183169054","text":"import discord\nimport discord.utils\nimport pymongo\nimport asyncio\nfrom bot_index import selfRoleDB, streamDB, delegationDB\nfrom discord.ext import commands\n\n\nclass Roles(commands.Cog):\n\n \"\"\"Self-Assigned roles as well as auto-streamer role\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(aliases=['asar'], description=\"\")\n @commands.has_guild_permissions(administrator=True)\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def addSar(self, ctx, *, role: discord.Role):\n \"\"\"Add Roles for Self-Assignment\"\"\"\n assignableRole = {\n \"guild_id\": str(ctx.guild.id),\n \"roleName\": str(role).casefold(),\n \"roleID\": str(role.id),\n \"realRoleName\": str(role)\n }\n selfRoleDB.insert_one(assignableRole)\n embed = discord.Embed(title=\"Role Added\", description=\"Role '**\"+str(role)+\"**', has been added to the list of self-assignable roles!\", color=0x00ff00)\n await ctx.send(embed=embed)\n\n @addSar.error\n async def addSarError(self, ctx, error):\n if isinstance(error, commands.CommandError):\n embed = discord.Embed(title=\"Role Not Found\", description=\"Role does not exist, or capitalization is not correct. Adding with asar requires exact capitalization, rsar or iam do not.\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @commands.command(aliases=['rsar'], description=\"\")\n @commands.has_guild_permissions(administrator=True)\n async def remSar(self, ctx, *, roles):\n \"\"\"Remove Roles for Self-Assignment\"\"\"\n assignableRole = {\n \"guild_id\": str(ctx.guild.id),\n \"roleName\": str(roles).casefold(),\n }\n findEntry = selfRoleDB.find_one(assignableRole)\n rrName = findEntry['realRoleName']\n if findEntry != None:\n selfRoleDB.delete_one(assignableRole)\n embed = discord.Embed(title=\"Role Removed\", description=\"Role '**\"+str(rrName)+\"**', has been removed the list of self-assignable roles!\", color=0x00ff00)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(title=\"Error\", description=\"Role '**\"+str(roles)+\"**', was not found in the database. Please check that it is in listSar first\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @commands.command(aliases=['lsar'], description=\"\")\n async def listSar(self, ctx):\n \"\"\"List all self-assignable roles in current server\"\"\"\n assignableRole = {\n \"guild_id\": str(ctx.guild.id)\n }\n findEntry = selfRoleDB.find(assignableRole) \n if findEntry != None:\n findEntry.sort([('realRoleName', pymongo.ASCENDING)])\n values = [d['realRoleName'] for d in findEntry]\n roles = \"\"\n for entry in values:\n roles += entry + '\\n'\n embed = discord.Embed(title=\"Self Assign Role List\", description=str(roles), color=0xffff00)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(title=\"Error\", description=\"No self assigned roles have been found. Make a new one with addSar [Role]\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @commands.command(description=\"\")\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def iam(self, ctx, *, roles):\n \"\"\"Give yourself a self-assignable role\"\"\"\n search = {\n \"guild_id\": str(ctx.guild.id),\n \"roleName\": str(roles).casefold()\n } # finding the guild ID and the specific role name, as I am not getting role ID atm to make the iam accept any case, whereas discord.py is case sensitive\n guildReturn = selfRoleDB.find_one(search) # search for the specified cases above, this will obviously not work well if a server has a role named the same thing\n if guildReturn != None:\n try:\n rolesFound = int(guildReturn['roleID']) #declaring the roleID as int, as it's stored as a string but it needs to be passed to guild.get_role as an int\n findRole = ctx.guild.get_role(rolesFound)\n await ctx.message.author.add_roles(findRole)\n embed = discord.Embed(title=\"Role Given\", description=\"You are now '**\" +str(findRole)+\"**'\", color=0x00ff00)\n await ctx.send(embed=embed, delete_after=5)\n await asyncio.sleep(5)\n await ctx.message.delete()\n except KeyError as err:\n print(\"Error for result: \" +guildReturn+'--'+ err)\n else:\n embed = discord.Embed(title=\"Error\", description=\"Error finding '**\"+str(roles)+\"**'! Check lsar for the list of roles available here.\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @iam.error\n async def iamError(self, ctx, error):\n if isinstance(error, commands.BotMissingPermissions):\n embed = discord.Embed(title=\"Permissions Error\", description=\"Void Bot does not have permissions to use this command\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @commands.command(description=\"\")\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def iamnot(self, ctx, *, roles):\n \"\"\"Remove a self-assignable role from yourself\"\"\"\n search = {\n \"guild_id\": str(ctx.guild.id),\n \"roleName\": str(roles).casefold()\n } # finding the guild ID and the specific role name, as I am not getting role ID atm to make the iam accept any case, whereas discord.py is case sensitive\n guildReturn = selfRoleDB.find_one(search) # search for the specified cases above, this will obviously not work well if a server has a role named the same thing\n if guildReturn != None:\n try:\n rolesFound = int(guildReturn['roleID']) #declaring the roleID as int, as it's stored as a string but it needs to be passed to guild.get_role as an int\n findRole = ctx.guild.get_role(rolesFound)\n await ctx.message.author.remove_roles(findRole)\n embed = discord.Embed(title=\"Role Removed\", description=\"You are no longer '**\" +str(findRole)+\"**'\", color=0x00ff00)\n await ctx.send(embed=embed, delete_after=5)\n await asyncio.sleep(5)\n await ctx.message.delete()\n except KeyError as err:\n print(\"Error for result: \" +guildReturn+'--'+ err)\n else:\n embed = discord.Embed(title=\"Error\", description=\"Error finding '**\"+str(roles)+\"**'! Check lsar for the list of roles available here.\", color=0xff0000)\n await ctx.send(embed=embed)\n\n @commands.command(description=\"\")\n @commands.bot_has_guild_permissions(manage_roles=True)\n @commands.has_guild_permissions(manage_roles=True)\n async def streamRole(self, ctx, *, role: discord.Role):\n \"\"\"Add a role to automatically give streamers\"\"\"\n if not role:\n embed = discord.Embed(title=\"Role Not Found\", description=\"Role name is case sensitive. Please try again.\", color=0xaa0000)\n await ctx.send(embed=embed)\n\n else:\n streamingRole = {\n \"guild_id\": str(ctx.guild.id),\n \"roleID\": str(role.id), \n \"role_name\": str(role).casefold()\n }\n streamDB.insert_one(streamingRole)\n embed = discord.Embed(title=\"Role Added\", description=f\"The role {role}, will be auto-applied to anyone detected as live!\", color=0x00aa00)\n await ctx.send(embed=embed)\n\n @commands.command(aliases=['rmStreamRole'], description=\"\")\n @commands.has_guild_permissions(manage_roles=True)\n async def removeStreamRole(self, ctx, *, role):\n \"\"\"Removes the role to automatically give streamers\"\"\"\n search = {\n \"guild_id\": str(ctx.guild.id),\n \"role_name\": str(role).casefold()\n }\n findIt = streamDB.find_one(search)\n if findIt != None:\n streamDB.delete_one(search)\n embed = discord.Embed(title=\"Role Removed\", description=f\"The role {role}, will no longer be auto-applied to users detected as live.\", color=0x00aa00)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(title=\"Role Not Found\", description=f\"The role {role}, was not found as a streamer role. Make sure it is spelled correctly and try again.\", color=0xaa0000)\n await ctx.send(embed=embed)\n\n @commands.group()\n @commands.has_guild_permissions(administrator=True)\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def delegate(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send(\"Invalid command passed\")\n\n @delegate.command()\n async def add(self, ctx, user : discord.Member, *, role : discord.Role):\n search = {\n \"guild_id\": ctx.guild.id,\n \"role\": role.id\n }\n searchDB = delegationDB.find_one(search)\n if searchDB != None:\n memberID = user.id\n if memberID in searchDB['manager']:\n embed = discord.Embed(title=\"Already Manager\", description=f\"User {user}, is already a manager for {role}\", color=0xaa0000)\n await ctx.send(embed=embed)\n else:\n delegationDB.find_one_and_update(search, {'$push': {\"manager\": user.id}})\n embed = discord.Embed(title=\"Manager Added\", description=f\"User {user}, was added as a manager for {role}\", color=0x00aa00)\n await ctx.send(embed=embed)\n else:\n listInsertion = [user.id]\n addition = {\n \"guild_id\": ctx.guild.id,\n \"manager\": listInsertion,\n \"role\": role.id,\n \"role_name\": str(role).casefold(),\n \"mods\": []\n }\n delegationDB.insert_one(addition)\n embed = discord.Embed(title=\"Manager Added\", description=f\"User {user}, was added as a manager for {role}\", color=0x00aa00)\n await ctx.send(embed=embed)\n\n @delegate.command()\n async def remove(self, ctx, user: discord.Member, *, role: discord.Role):\n search = {\n \"guild_id\": ctx.guild.id,\n \"role\": role.id\n }\n searchDB = delegationDB.find_one(search)\n if searchDB != None and user.id in searchDB['manager']:\n delegationDB.find_one_and_update(search, {'$pull': {\"manager\": user.id}})\n embed = discord.Embed(title=\"Manager Removed\", description=f\"User {user}, is no longer a manager for {role}\", color=0x00aa00)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(title=\"Manager Not Found\", description=f\"User {user}, is not a manager for {role}\", color=0xaa0000)\n await ctx.send(embed=embed)\n\n @commands.group()\n @commands.bot_has_guild_permissions(manage_roles=True)\n async def role(self, ctx):\n if ctx.invoked_subcommand is None:\n await ctx.send(\"Invalid command passed\")\n\n @role.group(description=\"This is a test description of a subcommand\")\n async def give(self, ctx, user: discord.Member, *, role : discord.Role = None):\n if not role:\n search = {\n \"guild_id\": ctx.guild.id,\n \"manager\": ctx.author.id\n }\n searchDB = delegationDB.find(search)\n if searchDB != None:\n amount = 0\n for i in searchDB:\n amount += 1\n if amount > 1:\n embed = discord.Embed(title=\"Specify Role\", description=\"You are a manager for more than one role in this guild. Please specify the role you want to apply after the user.\", color=0xaa0000)\n await ctx.send(embed=embed)\n return\n else:\n print('1')\n return\n else:\n search = {\n \"guild_id\": ctx.guild.id,\n \"manager\": ctx.author.id,\n \"role\": role.id\n }\n searchDB = delegationDB.find_one(search)\n @give.command(description=\"This is a test description of a sub-sub command description\")\n async def testing(self, ctx):\n print('hi')\n\n @role.command(description=\"ayyyyyyyyyyyyyyy\")\n async def take(self, ctx, user: discord.Member, *, role : discord.Role = None):\n if not role:\n print('no role')\n else:\n print('role')\n\n\ndef setup(bot):\n bot.add_cog(Roles(bot))\n","sub_path":"cmds/roles/roles.py","file_name":"roles.py","file_ext":"py","file_size_in_byte":12549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"6946242","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport json\nimport pymongo\nimport time\n\nclass DemoPipeline(object):\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient('localhost', 27017)\n self.db = self.client.spider\n self.t66y = self.db.t66y\n\n def process_item(self, item, spider):\n\n data = {\n 'title': item['title'],\n 'url': item['url'],\n 'time': int(time.time()),\n 'status': 0\n }\n if not self.t66y.find_one({'url': item['url']}) :\n self.t66y.insert_one(data)\n\n return item\n\n # def close_spider(self):","sub_path":"demo/demo/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"26880864","text":"class Solution(object):\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n lennums = len(nums)\n if lennums < 2:\n return -1 if not lennums or lennums[0] != target else 0\n bottom = 0\n if nums[0] > nums[-1]:\n begin, end = 0, lennums-1\n mid = (begin+end)/2\n while begin < mid:\n if nums[mid] > nums[end]:\n begin = mid + 1\n else:\n end = mid\n mid = (begin + end)/2\n bottom = end\n top = bottom + lennums - 1\n while bottom < top:\n mid = (bottom+top)/2\n if target == nums[mid%lennums]:\n return mid%lennums\n elif target > nums[mid%lennums]:\n bottom = mid\n else:\n top = mid\n return bottom%lennums if target == nums[bottom%lennums] else -1\n\n","sub_path":"Search_in_Rotated_Sorted_Array.py","file_name":"Search_in_Rotated_Sorted_Array.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"444444700","text":"from tkinter import *\r\nimport pandas as pd\r\n\r\n\r\ndef get_data(path):\r\n d = pd.read_csv(path)\r\n d.index = d.index + 1\r\n return d\r\n\r\n\r\ndata = get_data(r'G:\\Data science\\ExcelR\\Projects\\PROJECT SARVAGNYA TEAM 6\\Questions_ans.csv')\r\n# topic = pd.DataFrame(zip(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], data['Labels'].unique()),\r\n# columns=['Topic_Labels', 'Topics']) # columns=['Topics']\r\n# topic.set_index('Topic_Labels', inplace=True)\r\n\r\nBG_GRAY = \"#ABB2B9\"\r\nBG_COLOR = \"#17202A\"\r\nTEXT_COLOR = \"#EAECEE\"\r\n\r\nFONT = \"Helvetica 14\"\r\nFONT_BOLD = \"Helvetica 13 bold\"\r\n\r\ntopics = {'A': 'Hierarchial', 'B': 'k_means', 'C': 'PCA', 'D': 'Random_forest', 'E': 'SVM',\r\n 'F': 'KNN', 'G': 'NAÏVE BAYES', 'H': 'Decision tree', 'I': 'Logistic'}\r\ntopic = \"t\"\r\nquestions = data.copy()\r\n\r\nuser_inputs=(\"hey\",\"Hello\",\"hello\", \"Good Day\", \"hi\",'Hi','Hey')\r\n\r\n\r\ndef get_response(msg):\r\n # questions = {'A': list(range(21)), 'B': list(range(21, 42)), 'C': list(range(42, 52)),\r\n # 'D': list(range(52, 74)), 'E': list(range(74, 89)), 'F': list(range(89, 109)),\r\n # 'G': list(range(109, 121)), 'H': list(range(121, 146)), 'I': list(range(146, 166))}\r\n try:\r\n if msg in user_inputs:\r\n return f'''Hello..... Choose the topic you want to study\r\n \r\n A :- HIERARCHICAL\r\n B :- K-MEANS\r\n C :- PCA\r\n D :- RANDOM FOREST\r\n E :- SVM\r\n F :- KNN\r\n G :- NAIVE BAYES\r\n H :- DECISION TREE\r\n I :- LOGISTIC'''\r\n elif msg == 'x':\r\n return f\"Bye, See you next time\"\r\n elif msg == '#':\r\n return f'''\r\n A :- HIRARCHICAL\r\n B :- K-MEANS\r\n C :- PCA\r\n D :- RANDOM FOREST\r\n E :- SVM\r\n F :- KNN\r\n G :- NAIVE BAYES\r\n H :- DECISION TREE\r\n I :- LOGISTIC\r\n \r\n Select one option\r\n or\r\n Select \"x\" to exit\r\n or\r\n Select \"?\" for questions list'''\r\n elif msg.upper() in topics:\r\n global topic\r\n topic = str(topics[msg.upper()])\r\n global questions\r\n questions = data[data.Labels == topic]\r\n return f'''list of Questions under the topic {topic}\r\n \r\n {data[data.Labels == topics[msg.upper()]].loc[:, 'Questions']}\r\n \r\n Select any one question number for Answer'''\r\n elif msg == '?':\r\n return f'''list of Questions under the topic {topic}\r\n \r\n {questions.loc[:, 'Questions']}\r\n \r\n Select any one question number for Answer'''\r\n elif int(msg) in range(167):\r\n return f'''Question no {int(msg)} : {questions.loc[int(msg), 'Questions']} \r\n \r\n Answer: {data.loc[int(msg), 'Answers']}'''\r\n else:\r\n return f'''Sorry, The Question number is our of range...\r\n Select \"#\" for Topics list\r\n Select \"?\" for Questions from the TOPIC\r\n Select \"x\" to exit'''\r\n\r\n except:\r\n return f'''Sorry, You selected a Wrong Option...\r\nSelect \"#\" for Topics list\r\nSelect \"?\" for Questions from the TOPIC\r\nSelect \"x\" to exit'''\r\n\r\n\r\nclass ChatApplication:\r\n\r\n def __init__(self):\r\n self.window = Tk()\r\n self._setup_main_window()\r\n\r\n def run(self):\r\n self.window.mainloop()\r\n\r\n def _setup_main_window(self):\r\n self.window.title(\"Chat\")\r\n self.window.resizable(width=False, height=False)\r\n self.window.configure(width=500, height=600, bg=BG_COLOR)\r\n\r\n # head label\r\n head_label = Label(self.window, bg=BG_COLOR, fg=TEXT_COLOR,\r\n text='''Welcome to \"SARVAGNYA\"''', font=FONT_BOLD, pady=10)\r\n head_label.place(relwidth=1)\r\n head_label1 = Label(self.window, bg=BG_COLOR, fg=TEXT_COLOR,\r\n text='Your personal DS interview prep tool', font=FONT, pady=10)\r\n head_label1.place(relwidth=1, rely=0.05)\r\n # tiny divider\r\n line = Label(self.window, width=650, bg=BG_GRAY)\r\n line.place(relwidth=1, rely=0.12, relheight=0.01)\r\n\r\n # text widget\r\n self.text_widget = Text(self.window, width=20, height=2, bg=BG_COLOR, fg=TEXT_COLOR,\r\n font=FONT, padx=5, pady=5)\r\n self.text_widget.place(relheight=0.77, relwidth=1, rely=0.13)\r\n self.text_widget.configure(cursor=\"arrow\", state=DISABLED)\r\n\r\n # scroll bar\r\n scrollbar = Scrollbar(self.text_widget)\r\n scrollbar.place(relheight=1, relx=0.97)\r\n scrollbar.configure(command=self.text_widget.yview)\r\n\r\n # bottom label\r\n bottom_label = Label(self.window, bg=BG_GRAY, height=60)\r\n bottom_label.place(relwidth=1, rely=0.895)\r\n\r\n # message entry box\r\n self.msg_entry = Entry(bottom_label, bg=\"#2C3E50\", fg=TEXT_COLOR, font=FONT)\r\n self.msg_entry.place(relwidth=0.77, relheight=0.06, rely=0.008, relx=0.011)\r\n self.msg_entry.focus()\r\n self.msg_entry.bind(\"\", self._on_enter_pressed)\r\n\r\n # send button\r\n send_button = Button(bottom_label, text=\"Send\", font=FONT_BOLD, width=20, bg=BG_GRAY,\r\n command=lambda: self._on_enter_pressed(None))\r\n send_button.place(relx=0.77, rely=0.008, relheight=0.06, relwidth=0.22)\r\n\r\n def _on_enter_pressed(self, event):\r\n msg = self.msg_entry.get()\r\n self._insert_message(msg, \"You\")\r\n\r\n def _insert_message(self, msg, sender):\r\n # if not msg:\r\n # return\r\n\r\n self.msg_entry.delete(0, END)\r\n msg1 = f\"{sender}: {msg}\\n\\n\"\r\n self.text_widget.configure(state=NORMAL)\r\n self.text_widget.insert(END, msg1)\r\n self.text_widget.configure(state=DISABLED)\r\n\r\n msg2 = f\"Sarvagnya: \\n{get_response(msg)}\\n\\n\"\r\n self.text_widget.configure(state=NORMAL)\r\n self.text_widget.insert(END, msg2)\r\n # self.text_widget.insert(END, 'Select any one option\\n\\n')\r\n self.text_widget.configure(state=DISABLED)\r\n\r\n self.text_widget.see(END)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app = ChatApplication()\r\n app.run()\r\n","sub_path":"tkChatbotDeploy.py","file_name":"tkChatbotDeploy.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"267756401","text":"# mod_dash/main.py\n\n#\n# Copyright (c) 2013\n# Nexa Center for Internet & Society, Politecnico di Torino (DAUIN)\n# and Simone Basso \n#\n# This file is part of Neubot .\n#\n# Neubot is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Neubot is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Neubot. If not, see .\n#\n\n\"\"\" The MPEG DASH test main() \"\"\"\n\n# Adapted from neubot/raw.py\n\nimport getopt\nimport logging\nimport sys\n\nif __name__ == \"__main__\":\n sys.path.insert(0, \".\")\n\nfrom .server_glue import DASHServerGlue\nfrom .server_negotiate import DASHNegotiateServer\nfrom .server_smpl import DASHServerSmpl\n\nfrom ..runtime.http_server import HttpServer\nfrom ..negotiate_server import NegotiateServer\n\nfrom .config import CONFIG\nfrom ..runtime.poller import POLLER\n\nfrom . import backend\nfrom . import log\n\nUSAGE = \"\"\"\\\nusage: neubot dash [-6flnv] [-A address] [-b backend] [-d datadir] [-p port]\"\"\"\n\ndef main(args):\n \"\"\" Main function \"\"\"\n try:\n options, arguments = getopt.getopt(args[1:], \"6A:b:d:flnp:v\")\n except getopt.error:\n sys.exit(USAGE)\n if arguments:\n sys.exit(USAGE)\n\n prefer_ipv6 = 0\n address = \"127.0.0.1\"\n backend = \"volatile\"\n datadir = None # means: pick the default\n force = 0\n listen = 0\n negotiate = 1\n port = 80\n noisy = 0\n for name, value in options:\n if name == \"-6\":\n prefer_ipv6 = 1\n elif name == \"-A\":\n address = value\n elif name == \"-b\":\n backend = value\n elif name == \"-d\":\n datadir = value\n elif name == \"-f\":\n force = 1\n elif name == \"-l\":\n listen = 1\n elif name == \"-n\":\n negotiate = 0\n elif name == \"-p\":\n port = int(value)\n elif name == \"-v\":\n noisy = 1\n\n if noisy:\n log.set_verbose()\n\n conf = CONFIG.copy()\n\n backend.setup(CONFIG[\"unpriv_user\"], datadir)\n\n if listen:\n if not negotiate:\n server = DASHServerSmpl(POLLER)\n server.configure(conf)\n server.listen((address, port))\n\n else:\n # Code adapted from neubot/server.py\n\n conf[\"http.server.rootdir\"] = \"\"\n server = ServerHTTP(POLLER)\n server.configure(conf)\n server.listen((address, port))\n\n negotiate_server = NegotiateServer(POLLER)\n negotiate_server.configure(conf)\n server.register_child(negotiate_server, \"/negotiate\")\n server.register_child(negotiate_server, \"/collect\")\n\n dash_negotiate_server = DASHNegotiateServer()\n negotiate_server.register_module(\"dash\", dash_negotiate_server)\n\n dash_server = DASHServerGlue(POLLER, dash_negotiate_server)\n dash_server.configure(conf)\n server.register_child(dash_server, \"/dash\")\n\n else:\n logging.warning(\"dash: client mode not implemented\")\n sys.exit(1)\n\n POLLER.loop()\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"96733454","text":"import re\nfrom typing import List, Dict, Set, Any\n\nimport requests\nfrom bibtexparser.bibdatabase import BibDatabase\nfrom bibtexparser.bparser import BibTexParser\nfrom bibtexparser.bwriter import BibTexWriter\nfrom bibtexparser.customization import homogenize_latex_encoding, latex_to_unicode\n\nfrom src.get_publication_fetching_data import get_publication_fetching_data\n\n# To run this script, you need to download a file credentials.json from\n# https://developers.google.com/sheets/api/quickstart/python and put it into the folder \"secret\" on the same level as the\n# \"src\" folder.\n\npublication_fetching_data = get_publication_fetching_data()\n\nexisting = \"../sda.bib\"\nblacklist = \"blacklist.txt\"\n\n\ndef get_candidate_publications():\n ignored_titles = get_ignored_titles()\n candidate_publications = fetch_candidate_publications(ignored_titles)\n print_candidates(candidate_publications)\n\n with open(existing, \"a\") as bib:\n new_entries = bibtex_entries_to_string(candidate_publications)\n bib.write(new_entries)\n\n\ndef get_ignored_titles() -> Set[str]:\n \"\"\"Returns the titles of publications that we already included in our list or that we explicitly ignore.\"\"\"\n\n existing_publications = parse_bibtex_file(existing)\n existing_titles = [\n normalize_title(publication[\"title\"])\n for publication in existing_publications\n if \"title\" in publication\n ]\n\n blacklisted_titles = parse_blacklisted_titles()\n print(\"Blacklisted titles:\\n\")\n for title in blacklisted_titles:\n print(title)\n print(\"\\n========================================\\n\")\n\n ignored_titles = set()\n ignored_titles = ignored_titles.union(existing_titles)\n ignored_titles = ignored_titles.union(blacklisted_titles)\n\n return ignored_titles\n\n\ndef parse_bibtex_file(path: str) -> List[Dict]:\n try:\n with open(path, \"r\", encoding=\"UTF-8\") as file:\n return create_bibtex_parser().parse_file(file).entries\n except IndexError:\n return []\n\n\ndef create_bibtex_parser() -> BibTexParser:\n bibtex_parser = BibTexParser(common_strings=True)\n bibtex_parser.ignore_nonstandard_types = False\n bibtex_parser.homogenize_fields = True\n bibtex_parser.customization = homogenize_latex_encoding\n return bibtex_parser\n\n\ndef parse_blacklisted_titles() -> Set[str]:\n with (open(blacklist, \"r\", encoding=\"UTF-8\")) as file:\n return set(map(normalize_title, file))\n\n\ndef normalize_title(title: str) -> str:\n lower_unicode = latex_to_unicode(title).lower()\n no_punctuation = re.sub(r\"[-,;:.!?/\\\\'\\\"]\", \" \", lower_unicode)\n normalized_whitespace = re.sub(r\"[\\n\\r\\s]+\", \" \", no_punctuation).strip()\n return normalized_whitespace\n\n\ndef fetch_candidate_publications(ignored_titles: Set[str]) -> List[Dict]:\n result = []\n normalized_title_to_author_ids = {}\n sda_publications = set()\n\n for entry in publication_fetching_data:\n dblp_url, start_year, end_year, author_id = entry[0], entry[1], entry[2], entry[3]\n\n batch = fetch_from_dblp(dblp_url)\n for publication in batch:\n normalized_title = normalize_title(publication[\"title\"])\n\n remember_author_id(normalized_title, author_id, normalized_title_to_author_ids)\n if is_sda_publication(publication, start_year, end_year):\n sda_publications.add(normalized_title)\n\n if \"author\" in publication and normalized_title not in ignored_titles:\n result.append(publication)\n ignored_titles.add(normalized_title)\n\n add_author_ids_as_keywords(result, normalized_title_to_author_ids, sda_publications)\n\n return result\n\n\ndef fetch_from_dblp(dblp_url: str) -> List[Dict]:\n bibtex_string = requests.get(f\"{dblp_url}.bib\").content.decode(\"utf-8\")\n return parse_bibtex_string(bibtex_string)\n\n\ndef parse_bibtex_string(s: str) -> List[Dict]:\n return create_bibtex_parser().parse(s).entries\n\n\ndef remember_author_id(normalized_title: str, author_id: str, normalized_title_to_author_ids: Dict[str, Set]):\n if normalized_title not in normalized_title_to_author_ids:\n normalized_title_to_author_ids[normalized_title] = set()\n\n normalized_title_to_author_ids[normalized_title].add(author_id)\n\n\ndef is_sda_publication(publication, start_year_string: str, end_year_string: str) -> bool:\n if not is_valid_year(publication[\"year\"]):\n return True\n\n publication_year = int(publication[\"year\"])\n start_year = int(start_year_string) if is_valid_year(start_year_string) else 9999\n end_year = int(end_year_string) if is_valid_year(end_year_string) else 9999\n\n return start_year <= publication_year <= end_year\n\n\ndef is_valid_year(value: Any) -> bool:\n return type(value) == str and value.isnumeric()\n\n\ndef add_author_ids_as_keywords(publications: List[Dict], normalized_title_to_author_ids: Dict[str, Set],\n sda_publications: Set[str]):\n for entry in publications:\n normalized_title = normalize_title(entry[\"title\"])\n author_ids = normalized_title_to_author_ids[normalized_title]\n\n # Add author IDs as keywords\n if \"keywords\" not in entry:\n entry[\"keywords\"] = \"\"\n else:\n entry[\"keywords\"] += \" \"\n entry[\"keywords\"] += \" \".join(author_ids)\n\n # Mark SDA publications using a keyword\n if normalized_title in sda_publications:\n entry[\"keywords\"] += \" \" + \"sda-pub\"\n\n entry[\"keywords\"].replace(\",\", \" \")\n\n\ndef print_candidates(candidates: List[Dict]):\n count = len(candidates)\n if count == 0:\n print(\"No suggestions.\")\n else:\n if count == 1:\n print(\"One suggestion:\\n\")\n else:\n print(f\"{count} suggestions:\\n\")\n\n output = bibtex_entries_to_string(candidates)\n print(output)\n\n\ndef bibtex_entries_to_string(entries: List[Dict]):\n if len(entries) == 0:\n return \"\"\n\n writer = BibTexWriter()\n writer.align_values = True\n writer.indent = \" \"\n\n db = BibDatabase()\n db.entries = entries\n\n return writer.write(db)\n\n\nif __name__ == '__main__':\n get_candidate_publications()\n","sub_path":"src/find_new_entries.py","file_name":"find_new_entries.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"174284025","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUsage:\n main.py train --yaml-file= [--evaluate] [options]\n main.py evaluate --yaml-file= [options]\n main.py test --model-path= [--results-folder=]\n\nOptions:\n -h --help show this screen.\n --no-cuda don't use GPU (by default will try to use GPU)\n --clip-grad= gradient clipping [default: 5.0]\n --log-every= log every [default: 10]\n --patience= wait for how many iterations to decay learning rate [default: 5]\n --max-num-trial= terminate training after how many trials [default: 5]\n --lr-decay= learning rate decay [default: 0.5]\n --sample-size= sample size [default: 5]\n --dropout= dropout [default: 0.3]\n --log-file= name of log file to log all output\n\"\"\"\n\nimport os\nfrom docopt import docopt\nimport copy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import StepLR\n\nimport numpy as np\n\nimport time\nimport utils\n\nfrom models.brits import Model as BRITS\nfrom models.rits import Model as RITS\n\nimport argparse\nimport data_loader\n\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\nfrom utils import read_json, save_json, read_yaml\nfrom pdb import set_trace\n\ndef plot_losses(losses, experiment_name, results_folder):\n loss_graph_save_path = os.path.join(results_folder, \"loss_graph.png\")\n train_losses, val_losses = losses\n plt.plot(np.arange(len(train_losses)), train_losses, label=\"Train loss\")\n plt.plot(np.arange(len(val_losses)), val_losses, label=\"Validation loss\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Average loss\")\n plt.title(\"{}: Training and validation losses\".format(experiment_name))\n plt.legend(loc = \"upper right\")\n log(\"Saving loss graph to {}\".format(loss_graph_save_path))\n plt.savefig(loss_graph_save_path)\n\ndef log(string, log_file = None):\n \"\"\"\n A convenience function to print to standard output as well as write to\n a log file. Note that LOG_FILE is a global variable set in main and\n is specified by a command line argument. See docopt string at top\n of this file.\n\n param string (str): string to print and log to file\n \"\"\"\n if log_file is not None:\n log_file.write(string + '\\n')\n if LOG_FILE is not None:\n LOG_FILE.write(string + '\\n')\n print(string)\n\ndef run_on_data(model, data_iter, optimizer):\n loss = 0.0\n for idx, data in enumerate(data_iter):\n ret = model.run_on_batch(data, optimizer)\n loss += ret['loss'].item()\n return loss / len(data_iter)\n\ndef run_training(model, optimizer, train_iter, val_iter, max_epoch):\n train_losses = []\n val_losses = []\n for epoch in range(max_epoch):\n log(\"Epoch {}\".format(epoch))\n model.train()\n train_loss = run_on_data(model, train_iter, optimizer)\n model.eval()\n val_loss = run_on_data(model, val_iter, None)\n log(\"Train loss: {}, Val loss: {}\".format(train_loss, val_loss))\n\n train_losses.append(train_loss)\n val_losses.append(val_loss)\n\n \n return train_losses, val_losses\n\ndef set_random_seed(seed):\n if seed:\n log(\"Running training with random seed {}\".format(seed))\n torch.manual_seed(seed)\n else:\n log(\"WARNING: The random number generator has not been seeded.\")\n log(\"You are encouraged to run with a random seed for reproducibility!\")\n\ndef set_cuda(model, no_cuda):\n if not no_cuda and torch.cuda.is_available():\n log(\"CUDA is available, using GPU...\")\n log(\"Pass --no-cuda to main.py if you don't want GPU\")\n return model.cuda()\n else:\n log(\"Using CPU...\")\n return model\n\ndef load_optimizer(model, optimizer_name, lr):\n return getattr(optim, optimizer_name)(model.parameters(), lr=lr)\n\ndef save_model(model, results_folder):\n model_save_path = os.path.join(results_folder, \"trained_model.pt\")\n log(\"Saving model to {}\".format(model_save_path))\n torch.save(model.state_dict(), model_save_path)\n\ndef train(args, yaml_data):\n \n\n set_random_seed(yaml_data[\"seed\"])\n train_iter, model = load_data_and_model(yaml_data, \"train_data\")\n model = set_cuda(model, args[\"--no-cuda\"])\n\n batch_size = yaml_data[\"batch_size\"]\n val_iter, _ = data_loader.get_loader(yaml_data[\"val_data\"], batch_size)\n\n optimizer = load_optimizer(model, yaml_data[\"optimizer\"], yaml_data[\"lr\"])\n\n max_epoch = yaml_data[\"max_epoch\"] \n losses = run_training(model, optimizer, train_iter, val_iter, max_epoch)\n save_model(model, yaml_data[\"results_folder\"])\n plot_losses(losses, yaml_data[\"experiment_name\"], yaml_data[\"results_folder\"])\n\n if args[\"--evaluate\"]:\n val_data = yaml_data[\"val_data\"]\n data_iter, _ = data_loader.get_loader(val_data, batch_size)\n evaluate(model, data_iter, yaml_data[\"results_folder\"])\n\ndef evaluate(model, val_iter, results_folder):\n model.eval()\n\n labels = []\n preds = []\n\n evals = []\n imputations = []\n\n for idx, data in enumerate(val_iter):\n data = utils.to_var(data)\n ret = model.run_on_batch(data, None)\n\n eval_masks = ret['eval_masks'].data.cpu().numpy()\n eval_ = ret['evals'].data.cpu().numpy()\n imputation = ret['imputations'].data.cpu().numpy()\n\n evals += eval_[np.where(eval_masks == 1)].tolist()\n imputations += imputation[np.where(eval_masks == 1)].tolist()\n\n \n evals = np.asarray(evals)\n imputations = np.asarray(imputations)\n\n mae = \"MAE: {}\".format(np.abs(evals - imputations).mean())\n mre = \"MRE: {}\".format(np.abs(evals - imputations).sum() / np.abs(evals).sum())\n nrmse = \"NRMSE: {}\".format(np.sqrt(np.power(evals - imputations, 2).mean()) / (evals.max() - evals.min()))\n\n with open(os.path.join(results_folder, \"stats.txt\"), 'w') as stats_file:\n log(mae, stats_file)\n log(mre, stats_file)\n log(nrmse, stats_file)\n\ndef load_data_and_model(yaml_data, data_type):\n data_path = yaml_data[data_type]\n batch_size = yaml_data[\"batch_size\"]\n model_name = yaml_data[\"model\"]\n hidden_size = yaml_data[\"hidden_size\"]\n data_iter, input_dim = data_loader.get_loader(data_path, batch_size)\n model = globals()[model_name](input_dim = input_dim, hidden_size = hidden_size)\n return data_iter, model\n\ndef prep_eval(yaml_data, no_cuda):\n data_iter, model = load_data_and_model(yaml_data, \"val_data\")\n results_folder = yaml_data[\"results_folder\"]\n model_save_path = os.path.join(results_folder, \"trained_model.pt\")\n if not no_cuda and torch.cuda.is_available():\n device_name = \"cuda\"\n else:\n device_name = \"cpu\"\n device = torch.device(device_name)\n map_location = device if device_name == \"cpu\" else None\n model.load_state_dict(torch.load(model_save_path, map_location = map_location))\n if device_name == \"cuda\": \n model.to(device)\n return data_iter, model\n\ndef set_log_file(log_file, results_folder):\n \"\"\"\n Opens a writeable file object to log output and sets as a global\n variable. \n\n :param log_file (str): name of log file to write to, can be None\n * if None, no log file is created\n :param results_folder (str): folder to save log file to\n \"\"\"\n global LOG_FILE\n LOG_FILE = None\n if log_file is not None:\n log_file_path = os.path.join(results_folder, log_file + \".txt\")\n LOG_FILE = open(log_file_path, 'w')\n log(\"Created log file at {}\".format(log_file_path))\n\ndef main():\n args = docopt(__doc__)\n yaml_data = read_yaml(args[\"--yaml-file\"])\n set_log_file(args[\"--log-file\"], yaml_data[\"results_folder\"])\n\n if args[\"train\"]:\n train(args, yaml_data)\n elif args[\"evaluate\"]:\n data_iter, model = prep_eval(yaml_data, args[\"--no-cuda\"])\n evaluate(model, data_iter, yaml_data[\"results_folder\"])\n\n if LOG_FILE is not None:\n LOG_FILE.close()\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"200685960","text":"\ndef decimal_to_binary(num):\n bin = \"\"\n while(num > 0):\n bin = bin + str(divmod(num, 2)[1])\n num = divmod(num, 2)[0]\n return bin[::-1]\n\n\ndef decimal_to_oct(num):\n bin = \"\"\n while(num > 0):\n bin = bin + str(divmod(num, 8)[1])\n num = divmod(num, 8)[0]\n return bin[::-1]\n\n\nif __name__ == \"__main__\":\n print(decimal_to_oct(100))\n\n","sub_path":"decimal_to_bin.py","file_name":"decimal_to_bin.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"}