code
stringlengths
13
1.2M
order_type
stringclasses
1 value
original_example
dict
step_ids
listlengths
1
5
__doc__ = """ Dataset Module Utilities - mostly for handling files and datasets """ import glob import os import random from meshparty import mesh_io # Datasets ----------------------- SVEN_BASE = "seungmount/research/svenmd" NICK_BASE = "seungmount/research/Nick/" BOTH_BASE = "seungmount/research/nick_and_sven" DATASET_DIRS = { "orig_full_cells": [f"{SVEN_BASE}/pointnet_axoness_gt_180223/"], "soma_vs_rest": [f"{SVEN_BASE}/pointnet_soma_masked_180401"], "orphans": [f"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/", f"{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/"], "orphans2": [f"{NICK_BASE}/pointnet/orphan_dataset/train_val_axons", f"{NICK_BASE}/pointnet/orphan_dataset/train_val_dends/"], "orphan_axons": [f"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/"], "orphan_axons_refined": [(f"{SVEN_BASE}" "/pointnet_orphan_axons_gt_180308_refined/")], "pinky100_orphan_dends": [(f"{BOTH_BASE}/data/180920_orphan_dends/")], "orphan_axons_pinky100": [(f"{SVEN_BASE}/InhAnalysis/meshes_put_axon/")], "fish_refined": [f"{SVEN_BASE}/180831_meshes_ashwin_refined/"], "full_cells_unrefined": [(f"{SVEN_BASE}" "/pointnet_full_semantic_labels" "_masked_180401")], "full_cells_refined": [(f"{SVEN_BASE}" "/pointnet_full_semantic_labels" "_masked_180401_refined/")], "pinky100_orphan_dend_features": [(f"{BOTH_BASE}" "/nick_archive/p100_dend_outer" "/inference/proj32/")], "pinky100_orphan_dend_features_32": [(f"{BOTH_BASE}" "/nick_archive/p100_dend_outer_32" "/inference/")], "default": [f"{SVEN_BASE}/pointnet_axoness_gt_rfc_based_masked_180322/", f"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/", f"{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/"] } # -------------------------------- def fetch_dset_dirs(dset_name=None): """ Finds the global pathname to a list of directories which represent a dataset by name. """ assert (dset_name is None) or (dset_name in DATASET_DIRS), "invalid name" dset_name = "default" if dset_name is None else dset_name home = os.path.expanduser("~") return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name]) def files_from_dir(dirname, exts=["obj", "h5"]): """ Searches a directory for a set of extensions and returns the files matching those extensions, sorted by basename """ filenames = list() for ext in exts: ext_expr = os.path.join(dirname, f"*.{ext}") filenames.extend(glob.glob(ext_expr)) return sorted(filenames, key=os.path.basename) def split_files(filenames, train_split=0.8, val_split=0.1, test_split=0.1, seed=None): if seed is not None: random.seed(seed) # Normalizing splits for arbitrary values total = train_split + val_split + test_split train_split = train_split / total val_split = val_split / total test_split = test_split / total n_train = round(train_split * len(filenames)) n_val = round(val_split * len(filenames)) permutation = random.sample(filenames, len(filenames)) train_files = permutation[:n_train] val_files = permutation[n_train:(n_train+n_val)] test_files = permutation[(n_train+n_val):] return train_files, val_files, test_files # Helper functions for testing (e.g. sample.py) def pull_n_samples(dset, n): """Pulls n random samples from a dataset object""" return list(dset[i] for i in random.sample(range(len(dset)), n)) def save_samples(samples, output_prefix="sample"): """Saves a list of samples to ply files (with h5 labels)""" for (i, vertices) in enumerate(samples): vertex_fname = "{pref}{i}_vertices.ply".format(pref=output_prefix, i=i) if os.path.dirname(vertex_fname) == "": vertex_fname = "./" + vertex_fname mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)
normal
{ "blob_id": "fd0db093b72dad4657d71788405fcca4ba55daff", "index": 8529, "step-1": "<mask token>\n\n\ndef fetch_dset_dirs(dset_name=None):\n \"\"\"\n Finds the global pathname to a list of directories which represent a\n dataset by name.\n \"\"\"\n assert dset_name is None or dset_name in DATASET_DIRS, 'invalid name'\n dset_name = 'default' if dset_name is None else dset_name\n home = os.path.expanduser('~')\n return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name])\n\n\n<mask token>\n\n\ndef split_files(filenames, train_split=0.8, val_split=0.1, test_split=0.1,\n seed=None):\n if seed is not None:\n random.seed(seed)\n total = train_split + val_split + test_split\n train_split = train_split / total\n val_split = val_split / total\n test_split = test_split / total\n n_train = round(train_split * len(filenames))\n n_val = round(val_split * len(filenames))\n permutation = random.sample(filenames, len(filenames))\n train_files = permutation[:n_train]\n val_files = permutation[n_train:n_train + n_val]\n test_files = permutation[n_train + n_val:]\n return train_files, val_files, test_files\n\n\n<mask token>\n\n\ndef save_samples(samples, output_prefix='sample'):\n \"\"\"Saves a list of samples to ply files (with h5 labels)\"\"\"\n for i, vertices in enumerate(samples):\n vertex_fname = '{pref}{i}_vertices.ply'.format(pref=output_prefix, i=i)\n if os.path.dirname(vertex_fname) == '':\n vertex_fname = './' + vertex_fname\n mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)\n", "step-2": "<mask token>\n\n\ndef fetch_dset_dirs(dset_name=None):\n \"\"\"\n Finds the global pathname to a list of directories which represent a\n dataset by name.\n \"\"\"\n assert dset_name is None or dset_name in DATASET_DIRS, 'invalid name'\n dset_name = 'default' if dset_name is None else dset_name\n home = os.path.expanduser('~')\n return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name])\n\n\ndef files_from_dir(dirname, exts=['obj', 'h5']):\n \"\"\"\n Searches a directory for a set of extensions and returns the files\n matching those extensions, sorted by basename\n \"\"\"\n filenames = list()\n for ext in exts:\n ext_expr = os.path.join(dirname, f'*.{ext}')\n filenames.extend(glob.glob(ext_expr))\n return sorted(filenames, key=os.path.basename)\n\n\ndef split_files(filenames, train_split=0.8, val_split=0.1, test_split=0.1,\n seed=None):\n if seed is not None:\n random.seed(seed)\n total = train_split + val_split + test_split\n train_split = train_split / total\n val_split = val_split / total\n test_split = test_split / total\n n_train = round(train_split * len(filenames))\n n_val = round(val_split * len(filenames))\n permutation = random.sample(filenames, len(filenames))\n train_files = permutation[:n_train]\n val_files = permutation[n_train:n_train + n_val]\n test_files = permutation[n_train + n_val:]\n return train_files, val_files, test_files\n\n\n<mask token>\n\n\ndef save_samples(samples, output_prefix='sample'):\n \"\"\"Saves a list of samples to ply files (with h5 labels)\"\"\"\n for i, vertices in enumerate(samples):\n vertex_fname = '{pref}{i}_vertices.ply'.format(pref=output_prefix, i=i)\n if os.path.dirname(vertex_fname) == '':\n vertex_fname = './' + vertex_fname\n mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)\n", "step-3": "__doc__ = \"\"\"\nDataset Module Utilities - mostly for handling files and datasets\n\"\"\"\n<mask token>\nSVEN_BASE = 'seungmount/research/svenmd'\nNICK_BASE = 'seungmount/research/Nick/'\nBOTH_BASE = 'seungmount/research/nick_and_sven'\nDATASET_DIRS = {'orig_full_cells': [\n f'{SVEN_BASE}/pointnet_axoness_gt_180223/'], 'soma_vs_rest': [\n f'{SVEN_BASE}/pointnet_soma_masked_180401'], 'orphans': [\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/',\n f'{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/'], 'orphans2': [\n f'{NICK_BASE}/pointnet/orphan_dataset/train_val_axons',\n f'{NICK_BASE}/pointnet/orphan_dataset/train_val_dends/'],\n 'orphan_axons': [f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/'],\n 'orphan_axons_refined': [\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308_refined/'],\n 'pinky100_orphan_dends': [f'{BOTH_BASE}/data/180920_orphan_dends/'],\n 'orphan_axons_pinky100': [f'{SVEN_BASE}/InhAnalysis/meshes_put_axon/'],\n 'fish_refined': [f'{SVEN_BASE}/180831_meshes_ashwin_refined/'],\n 'full_cells_unrefined': [\n f'{SVEN_BASE}/pointnet_full_semantic_labels_masked_180401'],\n 'full_cells_refined': [\n f'{SVEN_BASE}/pointnet_full_semantic_labels_masked_180401_refined/'],\n 'pinky100_orphan_dend_features': [\n f'{BOTH_BASE}/nick_archive/p100_dend_outer/inference/proj32/'],\n 'pinky100_orphan_dend_features_32': [\n f'{BOTH_BASE}/nick_archive/p100_dend_outer_32/inference/'], 'default':\n [f'{SVEN_BASE}/pointnet_axoness_gt_rfc_based_masked_180322/',\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/',\n f'{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/']}\n\n\ndef fetch_dset_dirs(dset_name=None):\n \"\"\"\n Finds the global pathname to a list of directories which represent a\n dataset by name.\n \"\"\"\n assert dset_name is None or dset_name in DATASET_DIRS, 'invalid name'\n dset_name = 'default' if dset_name is None else dset_name\n home = os.path.expanduser('~')\n return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name])\n\n\ndef files_from_dir(dirname, exts=['obj', 'h5']):\n \"\"\"\n Searches a directory for a set of extensions and returns the files\n matching those extensions, sorted by basename\n \"\"\"\n filenames = list()\n for ext in exts:\n ext_expr = os.path.join(dirname, f'*.{ext}')\n filenames.extend(glob.glob(ext_expr))\n return sorted(filenames, key=os.path.basename)\n\n\ndef split_files(filenames, train_split=0.8, val_split=0.1, test_split=0.1,\n seed=None):\n if seed is not None:\n random.seed(seed)\n total = train_split + val_split + test_split\n train_split = train_split / total\n val_split = val_split / total\n test_split = test_split / total\n n_train = round(train_split * len(filenames))\n n_val = round(val_split * len(filenames))\n permutation = random.sample(filenames, len(filenames))\n train_files = permutation[:n_train]\n val_files = permutation[n_train:n_train + n_val]\n test_files = permutation[n_train + n_val:]\n return train_files, val_files, test_files\n\n\ndef pull_n_samples(dset, n):\n \"\"\"Pulls n random samples from a dataset object\"\"\"\n return list(dset[i] for i in random.sample(range(len(dset)), n))\n\n\ndef save_samples(samples, output_prefix='sample'):\n \"\"\"Saves a list of samples to ply files (with h5 labels)\"\"\"\n for i, vertices in enumerate(samples):\n vertex_fname = '{pref}{i}_vertices.ply'.format(pref=output_prefix, i=i)\n if os.path.dirname(vertex_fname) == '':\n vertex_fname = './' + vertex_fname\n mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)\n", "step-4": "__doc__ = \"\"\"\nDataset Module Utilities - mostly for handling files and datasets\n\"\"\"\nimport glob\nimport os\nimport random\nfrom meshparty import mesh_io\nSVEN_BASE = 'seungmount/research/svenmd'\nNICK_BASE = 'seungmount/research/Nick/'\nBOTH_BASE = 'seungmount/research/nick_and_sven'\nDATASET_DIRS = {'orig_full_cells': [\n f'{SVEN_BASE}/pointnet_axoness_gt_180223/'], 'soma_vs_rest': [\n f'{SVEN_BASE}/pointnet_soma_masked_180401'], 'orphans': [\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/',\n f'{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/'], 'orphans2': [\n f'{NICK_BASE}/pointnet/orphan_dataset/train_val_axons',\n f'{NICK_BASE}/pointnet/orphan_dataset/train_val_dends/'],\n 'orphan_axons': [f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/'],\n 'orphan_axons_refined': [\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308_refined/'],\n 'pinky100_orphan_dends': [f'{BOTH_BASE}/data/180920_orphan_dends/'],\n 'orphan_axons_pinky100': [f'{SVEN_BASE}/InhAnalysis/meshes_put_axon/'],\n 'fish_refined': [f'{SVEN_BASE}/180831_meshes_ashwin_refined/'],\n 'full_cells_unrefined': [\n f'{SVEN_BASE}/pointnet_full_semantic_labels_masked_180401'],\n 'full_cells_refined': [\n f'{SVEN_BASE}/pointnet_full_semantic_labels_masked_180401_refined/'],\n 'pinky100_orphan_dend_features': [\n f'{BOTH_BASE}/nick_archive/p100_dend_outer/inference/proj32/'],\n 'pinky100_orphan_dend_features_32': [\n f'{BOTH_BASE}/nick_archive/p100_dend_outer_32/inference/'], 'default':\n [f'{SVEN_BASE}/pointnet_axoness_gt_rfc_based_masked_180322/',\n f'{SVEN_BASE}/pointnet_orphan_axons_gt_180308/',\n f'{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/']}\n\n\ndef fetch_dset_dirs(dset_name=None):\n \"\"\"\n Finds the global pathname to a list of directories which represent a\n dataset by name.\n \"\"\"\n assert dset_name is None or dset_name in DATASET_DIRS, 'invalid name'\n dset_name = 'default' if dset_name is None else dset_name\n home = os.path.expanduser('~')\n return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name])\n\n\ndef files_from_dir(dirname, exts=['obj', 'h5']):\n \"\"\"\n Searches a directory for a set of extensions and returns the files\n matching those extensions, sorted by basename\n \"\"\"\n filenames = list()\n for ext in exts:\n ext_expr = os.path.join(dirname, f'*.{ext}')\n filenames.extend(glob.glob(ext_expr))\n return sorted(filenames, key=os.path.basename)\n\n\ndef split_files(filenames, train_split=0.8, val_split=0.1, test_split=0.1,\n seed=None):\n if seed is not None:\n random.seed(seed)\n total = train_split + val_split + test_split\n train_split = train_split / total\n val_split = val_split / total\n test_split = test_split / total\n n_train = round(train_split * len(filenames))\n n_val = round(val_split * len(filenames))\n permutation = random.sample(filenames, len(filenames))\n train_files = permutation[:n_train]\n val_files = permutation[n_train:n_train + n_val]\n test_files = permutation[n_train + n_val:]\n return train_files, val_files, test_files\n\n\ndef pull_n_samples(dset, n):\n \"\"\"Pulls n random samples from a dataset object\"\"\"\n return list(dset[i] for i in random.sample(range(len(dset)), n))\n\n\ndef save_samples(samples, output_prefix='sample'):\n \"\"\"Saves a list of samples to ply files (with h5 labels)\"\"\"\n for i, vertices in enumerate(samples):\n vertex_fname = '{pref}{i}_vertices.ply'.format(pref=output_prefix, i=i)\n if os.path.dirname(vertex_fname) == '':\n vertex_fname = './' + vertex_fname\n mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)\n", "step-5": "__doc__ = \"\"\"\nDataset Module Utilities - mostly for handling files and datasets\n\"\"\"\nimport glob\nimport os\nimport random\n\nfrom meshparty import mesh_io\n\n\n# Datasets -----------------------\nSVEN_BASE = \"seungmount/research/svenmd\"\nNICK_BASE = \"seungmount/research/Nick/\"\nBOTH_BASE = \"seungmount/research/nick_and_sven\"\nDATASET_DIRS = {\n \"orig_full_cells\": [f\"{SVEN_BASE}/pointnet_axoness_gt_180223/\"],\n\n \"soma_vs_rest\": [f\"{SVEN_BASE}/pointnet_soma_masked_180401\"],\n\n \"orphans\": [f\"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/\",\n f\"{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/\"],\n\n \"orphans2\": [f\"{NICK_BASE}/pointnet/orphan_dataset/train_val_axons\",\n f\"{NICK_BASE}/pointnet/orphan_dataset/train_val_dends/\"],\n\n \"orphan_axons\": [f\"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/\"],\n\n \"orphan_axons_refined\": [(f\"{SVEN_BASE}\"\n \"/pointnet_orphan_axons_gt_180308_refined/\")],\n\n \"pinky100_orphan_dends\": [(f\"{BOTH_BASE}/data/180920_orphan_dends/\")],\n\n \"orphan_axons_pinky100\": [(f\"{SVEN_BASE}/InhAnalysis/meshes_put_axon/\")],\n\n \"fish_refined\": [f\"{SVEN_BASE}/180831_meshes_ashwin_refined/\"],\n\n \"full_cells_unrefined\": [(f\"{SVEN_BASE}\"\n \"/pointnet_full_semantic_labels\"\n \"_masked_180401\")],\n\n \"full_cells_refined\": [(f\"{SVEN_BASE}\"\n \"/pointnet_full_semantic_labels\"\n \"_masked_180401_refined/\")],\n\n \"pinky100_orphan_dend_features\": [(f\"{BOTH_BASE}\"\n \"/nick_archive/p100_dend_outer\"\n \"/inference/proj32/\")],\n\n \"pinky100_orphan_dend_features_32\": [(f\"{BOTH_BASE}\"\n \"/nick_archive/p100_dend_outer_32\"\n \"/inference/\")],\n\n \"default\": [f\"{SVEN_BASE}/pointnet_axoness_gt_rfc_based_masked_180322/\",\n f\"{SVEN_BASE}/pointnet_orphan_axons_gt_180308/\",\n f\"{SVEN_BASE}/pointnet_orphan_dendrites_gt_180308/\"]\n}\n# --------------------------------\n\n\ndef fetch_dset_dirs(dset_name=None):\n \"\"\"\n Finds the global pathname to a list of directories which represent a\n dataset by name.\n \"\"\"\n assert (dset_name is None) or (dset_name in DATASET_DIRS), \"invalid name\"\n\n dset_name = \"default\" if dset_name is None else dset_name\n\n home = os.path.expanduser(\"~\")\n\n return list(os.path.join(home, d) for d in DATASET_DIRS[dset_name])\n\n\ndef files_from_dir(dirname, exts=[\"obj\", \"h5\"]):\n \"\"\"\n Searches a directory for a set of extensions and returns the files\n matching those extensions, sorted by basename\n \"\"\"\n filenames = list()\n for ext in exts:\n ext_expr = os.path.join(dirname, f\"*.{ext}\")\n filenames.extend(glob.glob(ext_expr))\n\n return sorted(filenames, key=os.path.basename)\n\n\ndef split_files(filenames, train_split=0.8,\n val_split=0.1, test_split=0.1, seed=None):\n\n if seed is not None:\n random.seed(seed)\n\n # Normalizing splits for arbitrary values\n total = train_split + val_split + test_split\n\n train_split = train_split / total\n val_split = val_split / total\n test_split = test_split / total\n\n n_train = round(train_split * len(filenames))\n n_val = round(val_split * len(filenames))\n\n permutation = random.sample(filenames, len(filenames))\n\n train_files = permutation[:n_train]\n val_files = permutation[n_train:(n_train+n_val)]\n test_files = permutation[(n_train+n_val):]\n\n return train_files, val_files, test_files\n\n\n# Helper functions for testing (e.g. sample.py)\ndef pull_n_samples(dset, n):\n \"\"\"Pulls n random samples from a dataset object\"\"\"\n return list(dset[i] for i in random.sample(range(len(dset)), n))\n\n\ndef save_samples(samples, output_prefix=\"sample\"):\n \"\"\"Saves a list of samples to ply files (with h5 labels)\"\"\"\n\n for (i, vertices) in enumerate(samples):\n vertex_fname = \"{pref}{i}_vertices.ply\".format(pref=output_prefix, i=i)\n if os.path.dirname(vertex_fname) == \"\":\n vertex_fname = \"./\" + vertex_fname\n mesh_io.Mesh.write_vertices_ply(None, vertex_fname, coords=vertices)\n", "step-ids": [ 3, 4, 6, 7, 8 ] }
[ 3, 4, 6, 7, 8 ]
from django.db import models import django.utils.timezone as timezone # Create your models here. # Create your models here. class Categories(models.Model): # 文章分类 name = models.CharField(max_length=200, verbose_name = "分类名称") parent = models.ForeignKey('self', default=0, on_delete=models.DO_NOTHING, null = True, blank = True, verbose_name = "上级分类") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") def __str__(self): return self.name class Meta: verbose_name_plural = '分类管理' class Wordroots(models.Model): # 爬取的词 SHIRT_SIZES = ( (0, '否'), (1, '是'), ) name = models.CharField(max_length=255, verbose_name = "词语") is_done = models.IntegerField(default=0, choices=SHIRT_SIZES, verbose_name = "是否采集") category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING, verbose_name = "分类名称") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '词库管理' class Articles(models.Model): # 抓取的数据组合的文章 wordroot = models.CharField(max_length=255, verbose_name = "词根") title = models.CharField(max_length=255, verbose_name = "标题") content = models.TextField(null = True, blank = True, verbose_name = "内容组合") category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING, verbose_name = "分类名称") image = models.ImageField(max_length=255, null = True, blank = True, verbose_name = "图片") video = models.FileField(max_length=255, null = True, blank = True, verbose_name = "视频") question = models.CharField(max_length=255, null = True, blank = True, verbose_name = "问答问题") answer = models.TextField(null = True, blank = True, verbose_name = "问答回答") baike_title = models.CharField(max_length=255, null = True, blank = True, verbose_name = "百科标题") baike_content = models.TextField(null = True, blank = True, verbose_name = "百科内容") seo_keywords = models.CharField(max_length=255, null = True, blank = True, verbose_name = "关键词") seo_description = models.CharField(max_length=255, null = True, blank = True, verbose_name = "描述") click_count = models.IntegerField(default=0, verbose_name = "点击") order = models.IntegerField(default=0, verbose_name = "排序") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '文章管理' class Baikes(models.Model): # 百科 wordroot_text = models.CharField(max_length=255, verbose_name = "词根") wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = "词根id, 可空") url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "爬取链接") title = models.CharField(max_length=255, null = True, blank = True, verbose_name = "标题") content = models.TextField(null = True, blank = True, verbose_name = "内容") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '百度百科' class Zhidaos(models.Model): # 知道 wordroot_text = models.CharField(max_length=255, verbose_name = "词根") wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = "词根id, 可空") url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "爬取链接") title = models.CharField(max_length=255, null = True, blank = True, verbose_name = "标题") content = models.TextField(null = True, blank = True, verbose_name = "内容") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '百度知道' class Images(models.Model): # 图片 wordroot_text = models.CharField(max_length=255, verbose_name = "词根") wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = "词根id, 可空") url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "爬取链接") image = models.CharField(max_length=255, null = True, blank = True, verbose_name = "图片链接") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '百度图片' class Youkus(models.Model): # 优酷 wordroot_text = models.CharField(max_length=255, verbose_name = "词根") wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = "词根id, 可空") url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "爬取链接") video = models.CharField(max_length=255, null = True, blank = True, verbose_name = "视频分享地址") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '优酷视频' class Tags(models.Model): #标签 name = models.CharField(max_length=255, verbose_name = "标签名称") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = '标签管理' class TagMaps(models.Model): article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING) tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING) class ScrapyRules(models.Model): # 爬虫链接及规则 name = models.CharField(max_length = 255, verbose_name = "爬取网站") url = models.CharField(max_length = 255, verbose_name = "爬取链接") search_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "搜索爬取规则") title_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "标题爬取规则") content_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "内容爬取规则") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = "链接管理" class ScrapyLogs(models.Model): # 爬虫日志 url = models.CharField(max_length = 255, verbose_name = "爬取链接") title = models.CharField(max_length = 255, null = True, blank = True, verbose_name = "页面标题") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = "爬虫日志" class ScrapyTasks(models.Model): # 定时任务 # 爬取的词 SHIRT_SIZES = ( ('0', '否'), ('1', '是'), ) CYCLE_TYPE = ( ('0', '按指定日期时间执行'), ('1', '按指定时间每天执行'), ('2', '按指定时间每周执行'), ('3', '按指定时间每月执行'), ) start_date_at = models.DateField(default = timezone.now, verbose_name = "开始时间") start_time_at = models.TimeField(default = timezone.now, verbose_name = "开始时间") task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE, verbose_name = "定时方式") is_done = models.IntegerField(default=0, choices=SHIRT_SIZES, verbose_name = "是否包含已采集") created_at = models.DateTimeField(default = timezone.now, verbose_name = "添加日期") updated_at = models.DateTimeField(default = timezone.now, verbose_name = "修改日期") class Meta: verbose_name_plural = "爬虫任务"
normal
{ "blob_id": "512a13084a860e2784020664a3d5824d9dace6db", "index": 7764, "step-1": "<mask token>\n\n\nclass Images(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n image = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='图片链接')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度图片'\n\n\nclass Youkus(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n video = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='视频分享地址')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '优酷视频'\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=255, verbose_name='标签名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '标签管理'\n\n\nclass TagMaps(models.Model):\n article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING)\n tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING)\n\n\nclass ScrapyRules(models.Model):\n name = models.CharField(max_length=255, verbose_name='爬取网站')\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n search_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='搜索爬取规则')\n title_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题爬取规则')\n content_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='内容爬取规则')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '链接管理'\n\n\nclass ScrapyLogs(models.Model):\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='页面标题')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫日志'\n\n\nclass ScrapyTasks(models.Model):\n SHIRT_SIZES = ('0', '否'), ('1', '是')\n CYCLE_TYPE = ('0', '按指定日期时间执行'), ('1', '按指定时间每天执行'), ('2', '按指定时间每周执行'), (\n '3', '按指定时间每月执行')\n start_date_at = models.DateField(default=timezone.now, verbose_name='开始时间')\n start_time_at = models.TimeField(default=timezone.now, verbose_name='开始时间')\n task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE,\n verbose_name='定时方式')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否包含已采集')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫任务'\n", "step-2": "<mask token>\n\n\nclass Articles(models.Model):\n wordroot = models.CharField(max_length=255, verbose_name='词根')\n title = models.CharField(max_length=255, verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容组合')\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING,\n verbose_name='分类名称')\n image = models.ImageField(max_length=255, null=True, blank=True,\n verbose_name='图片')\n video = models.FileField(max_length=255, null=True, blank=True,\n verbose_name='视频')\n question = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='问答问题')\n answer = models.TextField(null=True, blank=True, verbose_name='问答回答')\n baike_title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='百科标题')\n baike_content = models.TextField(null=True, blank=True, verbose_name='百科内容'\n )\n seo_keywords = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='关键词')\n seo_description = models.CharField(max_length=255, null=True, blank=\n True, verbose_name='描述')\n click_count = models.IntegerField(default=0, verbose_name='点击')\n order = models.IntegerField(default=0, verbose_name='排序')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '文章管理'\n\n\nclass Baikes(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度百科'\n\n\nclass Zhidaos(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度知道'\n\n\nclass Images(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n image = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='图片链接')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度图片'\n\n\nclass Youkus(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n video = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='视频分享地址')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '优酷视频'\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=255, verbose_name='标签名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '标签管理'\n\n\nclass TagMaps(models.Model):\n article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING)\n tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING)\n\n\nclass ScrapyRules(models.Model):\n name = models.CharField(max_length=255, verbose_name='爬取网站')\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n search_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='搜索爬取规则')\n title_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题爬取规则')\n content_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='内容爬取规则')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '链接管理'\n\n\nclass ScrapyLogs(models.Model):\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='页面标题')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫日志'\n\n\nclass ScrapyTasks(models.Model):\n SHIRT_SIZES = ('0', '否'), ('1', '是')\n CYCLE_TYPE = ('0', '按指定日期时间执行'), ('1', '按指定时间每天执行'), ('2', '按指定时间每周执行'), (\n '3', '按指定时间每月执行')\n start_date_at = models.DateField(default=timezone.now, verbose_name='开始时间')\n start_time_at = models.TimeField(default=timezone.now, verbose_name='开始时间')\n task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE,\n verbose_name='定时方式')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否包含已采集')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫任务'\n", "step-3": "<mask token>\n\n\nclass Wordroots(models.Model):\n SHIRT_SIZES = (0, '否'), (1, '是')\n name = models.CharField(max_length=255, verbose_name='词语')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否采集')\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING,\n verbose_name='分类名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '词库管理'\n\n\nclass Articles(models.Model):\n wordroot = models.CharField(max_length=255, verbose_name='词根')\n title = models.CharField(max_length=255, verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容组合')\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING,\n verbose_name='分类名称')\n image = models.ImageField(max_length=255, null=True, blank=True,\n verbose_name='图片')\n video = models.FileField(max_length=255, null=True, blank=True,\n verbose_name='视频')\n question = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='问答问题')\n answer = models.TextField(null=True, blank=True, verbose_name='问答回答')\n baike_title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='百科标题')\n baike_content = models.TextField(null=True, blank=True, verbose_name='百科内容'\n )\n seo_keywords = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='关键词')\n seo_description = models.CharField(max_length=255, null=True, blank=\n True, verbose_name='描述')\n click_count = models.IntegerField(default=0, verbose_name='点击')\n order = models.IntegerField(default=0, verbose_name='排序')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '文章管理'\n\n\nclass Baikes(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度百科'\n\n\nclass Zhidaos(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度知道'\n\n\nclass Images(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n image = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='图片链接')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度图片'\n\n\nclass Youkus(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n video = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='视频分享地址')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '优酷视频'\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=255, verbose_name='标签名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '标签管理'\n\n\nclass TagMaps(models.Model):\n article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING)\n tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING)\n\n\nclass ScrapyRules(models.Model):\n name = models.CharField(max_length=255, verbose_name='爬取网站')\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n search_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='搜索爬取规则')\n title_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题爬取规则')\n content_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='内容爬取规则')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '链接管理'\n\n\nclass ScrapyLogs(models.Model):\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='页面标题')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫日志'\n\n\nclass ScrapyTasks(models.Model):\n SHIRT_SIZES = ('0', '否'), ('1', '是')\n CYCLE_TYPE = ('0', '按指定日期时间执行'), ('1', '按指定时间每天执行'), ('2', '按指定时间每周执行'), (\n '3', '按指定时间每月执行')\n start_date_at = models.DateField(default=timezone.now, verbose_name='开始时间')\n start_time_at = models.TimeField(default=timezone.now, verbose_name='开始时间')\n task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE,\n verbose_name='定时方式')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否包含已采集')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫任务'\n", "step-4": "from django.db import models\nimport django.utils.timezone as timezone\n\n\nclass Categories(models.Model):\n name = models.CharField(max_length=200, verbose_name='分类名称')\n parent = models.ForeignKey('self', default=0, on_delete=models.\n DO_NOTHING, null=True, blank=True, verbose_name='上级分类')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n verbose_name_plural = '分类管理'\n\n\nclass Wordroots(models.Model):\n SHIRT_SIZES = (0, '否'), (1, '是')\n name = models.CharField(max_length=255, verbose_name='词语')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否采集')\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING,\n verbose_name='分类名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '词库管理'\n\n\nclass Articles(models.Model):\n wordroot = models.CharField(max_length=255, verbose_name='词根')\n title = models.CharField(max_length=255, verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容组合')\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING,\n verbose_name='分类名称')\n image = models.ImageField(max_length=255, null=True, blank=True,\n verbose_name='图片')\n video = models.FileField(max_length=255, null=True, blank=True,\n verbose_name='视频')\n question = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='问答问题')\n answer = models.TextField(null=True, blank=True, verbose_name='问答回答')\n baike_title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='百科标题')\n baike_content = models.TextField(null=True, blank=True, verbose_name='百科内容'\n )\n seo_keywords = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='关键词')\n seo_description = models.CharField(max_length=255, null=True, blank=\n True, verbose_name='描述')\n click_count = models.IntegerField(default=0, verbose_name='点击')\n order = models.IntegerField(default=0, verbose_name='排序')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '文章管理'\n\n\nclass Baikes(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度百科'\n\n\nclass Zhidaos(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题')\n content = models.TextField(null=True, blank=True, verbose_name='内容')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度知道'\n\n\nclass Images(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n image = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='图片链接')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '百度图片'\n\n\nclass Youkus(models.Model):\n wordroot_text = models.CharField(max_length=255, verbose_name='词根')\n wordroot_id = models.IntegerField(default=0, null=True, blank=True,\n verbose_name='词根id, 可空')\n url = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='爬取链接')\n video = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='视频分享地址')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '优酷视频'\n\n\nclass Tags(models.Model):\n name = models.CharField(max_length=255, verbose_name='标签名称')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '标签管理'\n\n\nclass TagMaps(models.Model):\n article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING)\n tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING)\n\n\nclass ScrapyRules(models.Model):\n name = models.CharField(max_length=255, verbose_name='爬取网站')\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n search_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='搜索爬取规则')\n title_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='标题爬取规则')\n content_rules = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='内容爬取规则')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '链接管理'\n\n\nclass ScrapyLogs(models.Model):\n url = models.CharField(max_length=255, verbose_name='爬取链接')\n title = models.CharField(max_length=255, null=True, blank=True,\n verbose_name='页面标题')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫日志'\n\n\nclass ScrapyTasks(models.Model):\n SHIRT_SIZES = ('0', '否'), ('1', '是')\n CYCLE_TYPE = ('0', '按指定日期时间执行'), ('1', '按指定时间每天执行'), ('2', '按指定时间每周执行'), (\n '3', '按指定时间每月执行')\n start_date_at = models.DateField(default=timezone.now, verbose_name='开始时间')\n start_time_at = models.TimeField(default=timezone.now, verbose_name='开始时间')\n task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE,\n verbose_name='定时方式')\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES,\n verbose_name='是否包含已采集')\n created_at = models.DateTimeField(default=timezone.now, verbose_name='添加日期'\n )\n updated_at = models.DateTimeField(default=timezone.now, verbose_name='修改日期'\n )\n\n\n class Meta:\n verbose_name_plural = '爬虫任务'\n", "step-5": "from django.db import models\nimport django.utils.timezone as timezone\n\n# Create your models here.\n\n# Create your models here.\nclass Categories(models.Model):\n # 文章分类\n name = models.CharField(max_length=200, verbose_name = \"分类名称\")\n parent = models.ForeignKey('self', default=0, on_delete=models.DO_NOTHING, null = True, blank = True, verbose_name = \"上级分类\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name_plural = '分类管理'\n\n\nclass Wordroots(models.Model):\n # 爬取的词\n SHIRT_SIZES = (\n (0, '否'),\n (1, '是'),\n )\n name = models.CharField(max_length=255, verbose_name = \"词语\")\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES, verbose_name = \"是否采集\")\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING, verbose_name = \"分类名称\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n\n class Meta:\n verbose_name_plural = '词库管理'\n\n\nclass Articles(models.Model):\n # 抓取的数据组合的文章\n wordroot = models.CharField(max_length=255, verbose_name = \"词根\")\n title = models.CharField(max_length=255, verbose_name = \"标题\")\n content = models.TextField(null = True, blank = True, verbose_name = \"内容组合\")\n category = models.ForeignKey(Categories, on_delete=models.DO_NOTHING, verbose_name = \"分类名称\")\n image = models.ImageField(max_length=255, null = True, blank = True, verbose_name = \"图片\")\n video = models.FileField(max_length=255, null = True, blank = True, verbose_name = \"视频\")\n question = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"问答问题\")\n answer = models.TextField(null = True, blank = True, verbose_name = \"问答回答\")\n baike_title = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"百科标题\")\n baike_content = models.TextField(null = True, blank = True, verbose_name = \"百科内容\")\n seo_keywords = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"关键词\")\n seo_description = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"描述\")\n click_count = models.IntegerField(default=0, verbose_name = \"点击\")\n order = models.IntegerField(default=0, verbose_name = \"排序\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '文章管理'\n\n \nclass Baikes(models.Model):\n # 百科\n wordroot_text = models.CharField(max_length=255, verbose_name = \"词根\")\n wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = \"词根id, 可空\")\n url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"爬取链接\")\n title = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"标题\")\n content = models.TextField(null = True, blank = True, verbose_name = \"内容\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '百度百科'\n\n\nclass Zhidaos(models.Model):\n # 知道\n wordroot_text = models.CharField(max_length=255, verbose_name = \"词根\")\n wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = \"词根id, 可空\")\n url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"爬取链接\")\n title = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"标题\")\n content = models.TextField(null = True, blank = True, verbose_name = \"内容\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '百度知道'\n\n\nclass Images(models.Model):\n # 图片\n wordroot_text = models.CharField(max_length=255, verbose_name = \"词根\")\n wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = \"词根id, 可空\")\n url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"爬取链接\")\n image = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"图片链接\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '百度图片'\n\n\nclass Youkus(models.Model):\n # 优酷\n wordroot_text = models.CharField(max_length=255, verbose_name = \"词根\")\n wordroot_id = models.IntegerField(default=0, null = True, blank = True, verbose_name = \"词根id, 可空\")\n url = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"爬取链接\")\n video = models.CharField(max_length=255, null = True, blank = True, verbose_name = \"视频分享地址\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '优酷视频'\n\nclass Tags(models.Model):\n #标签\n name = models.CharField(max_length=255, verbose_name = \"标签名称\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = '标签管理'\n\nclass TagMaps(models.Model):\n article = models.ForeignKey(Articles, on_delete=models.DO_NOTHING)\n tag = models.ForeignKey(Tags, on_delete=models.DO_NOTHING)\n\n\nclass ScrapyRules(models.Model):\n # 爬虫链接及规则\n name = models.CharField(max_length = 255, verbose_name = \"爬取网站\")\n url = models.CharField(max_length = 255, verbose_name = \"爬取链接\")\n search_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"搜索爬取规则\")\n title_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"标题爬取规则\")\n content_rules = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"内容爬取规则\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = \"链接管理\"\n\n\nclass ScrapyLogs(models.Model):\n # 爬虫日志\n url = models.CharField(max_length = 255, verbose_name = \"爬取链接\")\n title = models.CharField(max_length = 255, null = True, blank = True, verbose_name = \"页面标题\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = \"爬虫日志\"\n\n\nclass ScrapyTasks(models.Model):\n # 定时任务\n # 爬取的词\n SHIRT_SIZES = (\n ('0', '否'),\n ('1', '是'),\n )\n CYCLE_TYPE = (\n ('0', '按指定日期时间执行'),\n ('1', '按指定时间每天执行'),\n ('2', '按指定时间每周执行'),\n ('3', '按指定时间每月执行'),\n )\n start_date_at = models.DateField(default = timezone.now, verbose_name = \"开始时间\")\n start_time_at = models.TimeField(default = timezone.now, verbose_name = \"开始时间\")\n task_cycle = models.IntegerField(default=0, choices=CYCLE_TYPE, verbose_name = \"定时方式\")\n is_done = models.IntegerField(default=0, choices=SHIRT_SIZES, verbose_name = \"是否包含已采集\")\n created_at = models.DateTimeField(default = timezone.now, verbose_name = \"添加日期\")\n updated_at = models.DateTimeField(default = timezone.now, verbose_name = \"修改日期\")\n\n class Meta:\n verbose_name_plural = \"爬虫任务\"\n\n", "step-ids": [ 14, 20, 22, 26, 27 ] }
[ 14, 20, 22, 26, 27 ]
''' Created on 2021. 4. 8. @author: user ''' import matplotlib.pyplot as plt import numpy as np plt.rc("font", family="Malgun Gothic") def scoreBarChart(names, score): plt.bar(names, score) plt.show() def multiBarChart(names, score): plt.plot(names, score, "ro--") plt.plot([1, 2, 3], [70, 80, 90], "bo:") plt.plot([1, 1, 1], [10, 20, 30], "r>--", [4, 4, 4], [40, 50, 60], "y*-.") plt.text(3, 96, "평균 : {}".format(np.mean(score))) plt.grid(True) plt.xlabel("이름") plt.ylabel("점수") plt.title("국어 점수") plt.show() if __name__=="__main__": names = ["홍길동", "이순신", "강감찬", "김유신", "임꺽정"] score = [89, 86, 97, 77, 92] #scoreBarChart(names, score) multiBarChart(names, score)
normal
{ "blob_id": "542602a42eb873508ce2ec39d0856f10cc1e04ff", "index": 8426, "step-1": "<mask token>\n\n\ndef scoreBarChart(names, score):\n plt.bar(names, score)\n plt.show()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef scoreBarChart(names, score):\n plt.bar(names, score)\n plt.show()\n\n\ndef multiBarChart(names, score):\n plt.plot(names, score, 'ro--')\n plt.plot([1, 2, 3], [70, 80, 90], 'bo:')\n plt.plot([1, 1, 1], [10, 20, 30], 'r>--', [4, 4, 4], [40, 50, 60], 'y*-.')\n plt.text(3, 96, '평균 : {}'.format(np.mean(score)))\n plt.grid(True)\n plt.xlabel('이름')\n plt.ylabel('점수')\n plt.title('국어 점수')\n plt.show()\n\n\n<mask token>\n", "step-3": "<mask token>\nplt.rc('font', family='Malgun Gothic')\n\n\ndef scoreBarChart(names, score):\n plt.bar(names, score)\n plt.show()\n\n\ndef multiBarChart(names, score):\n plt.plot(names, score, 'ro--')\n plt.plot([1, 2, 3], [70, 80, 90], 'bo:')\n plt.plot([1, 1, 1], [10, 20, 30], 'r>--', [4, 4, 4], [40, 50, 60], 'y*-.')\n plt.text(3, 96, '평균 : {}'.format(np.mean(score)))\n plt.grid(True)\n plt.xlabel('이름')\n plt.ylabel('점수')\n plt.title('국어 점수')\n plt.show()\n\n\nif __name__ == '__main__':\n names = ['홍길동', '이순신', '강감찬', '김유신', '임꺽정']\n score = [89, 86, 97, 77, 92]\n multiBarChart(names, score)\n", "step-4": "<mask token>\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.rc('font', family='Malgun Gothic')\n\n\ndef scoreBarChart(names, score):\n plt.bar(names, score)\n plt.show()\n\n\ndef multiBarChart(names, score):\n plt.plot(names, score, 'ro--')\n plt.plot([1, 2, 3], [70, 80, 90], 'bo:')\n plt.plot([1, 1, 1], [10, 20, 30], 'r>--', [4, 4, 4], [40, 50, 60], 'y*-.')\n plt.text(3, 96, '평균 : {}'.format(np.mean(score)))\n plt.grid(True)\n plt.xlabel('이름')\n plt.ylabel('점수')\n plt.title('국어 점수')\n plt.show()\n\n\nif __name__ == '__main__':\n names = ['홍길동', '이순신', '강감찬', '김유신', '임꺽정']\n score = [89, 86, 97, 77, 92]\n multiBarChart(names, score)\n", "step-5": "'''\nCreated on 2021. 4. 8.\n\n@author: user\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rc(\"font\", family=\"Malgun Gothic\")\n\ndef scoreBarChart(names, score):\n plt.bar(names, score)\n plt.show()\n \ndef multiBarChart(names, score):\n plt.plot(names, score, \"ro--\")\n \n plt.plot([1, 2, 3], [70, 80, 90], \"bo:\")\n plt.plot([1, 1, 1], [10, 20, 30], \"r>--\", [4, 4, 4], [40, 50, 60], \"y*-.\")\n \n plt.text(3, 96, \"평균 : {}\".format(np.mean(score)))\n plt.grid(True)\n \n plt.xlabel(\"이름\")\n plt.ylabel(\"점수\")\n plt.title(\"국어 점수\")\n plt.show()\n\n\nif __name__==\"__main__\":\n names = [\"홍길동\", \"이순신\", \"강감찬\", \"김유신\", \"임꺽정\"]\n score = [89, 86, 97, 77, 92]\n \n #scoreBarChart(names, score)\n multiBarChart(names, score)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
Xeval[[1,2],:] # *** Spyder Python Console History Log *** Xeval[:,:] optfunc.P(Xeval[:,:]) optfunc.P(Xeval) optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.P(Xeval[[0,1,],:]) optfunc.P(Xeval[[0,1],:]) optfunc.P(Xeval[[0,1,2,3],:]) optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.P(Xeval[[0,1,2],:]) Xeval[[0,1,2,3,4],:] Xeval[[0,1,2,3],:] Xeval[[0,1,2],:] optfunc.gp_list[0] optfunc.gp_list[0](Xeval) optfunc.gp_list[0].preduct(Xeval) optfunc.gp_list[0].predict(Xeval) optfunc.gp_list[0].predict(Xeval[[0,1,2,3,4],:]) optfunc.gp_list[0].predict(Xeval[[0,1,2,3],:]) optfunc.gp_list[0].predict(Xeval[[0,1,2],:]) optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.ypred optfunc.P(Xeval[[0,1,2],:]) optfunc.ypred optfunc.P(Xeval[[0,1,2,3,4],:]) optfunc.MSE optfunc.sigma optfunc.P(Xeval[[0,1,2],:]) optfunc.sigma optfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,2,3],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,2,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,1],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,1,1],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[zeros(1,5)],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[np.zeros(1,5)],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[np.zeros(1,5),:],eval_MSE=True) np.zeros(1,5) np.zeros(5) optfunc.gp_list[0].predict(Xeval[np.zeros(15),:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[np.zeros(5),:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[np.zeros(5)],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True) Xeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:] optfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,2,3],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True) Xeval[[0,1,2,3]] Xeval[[0,1,2]] Xeval[[0,1,2],:] optfunc.gp_list[0].predict(Xeval[[0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict(Xeval[[0,0,0,0],:],eval_MSE=True) optfunc.gp_list[0].predict([0.5,0.5],:],eval_MSE=True) optfunc.gp_list[0].predict([0.5,0.5],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.5]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.49]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.48]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.495]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.499]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.4999]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.49999]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.5]],eval_MSE=True) optfunc.gp_list[0].predict([[0.5,0.5001]],eval_MSE=True) for i in range(0,100) for i in range(0,100): y[i],s[i] = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = [] s = [] for i in range(0,100): y[i],s[i] = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) for i in range(0,100): optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) for i in range(0,100): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] y optfunc.gp_list[0] runfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3') y = [] s = [] for i in range(0,100): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] y = [] s = [] for i in range(0,200): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] y = [] s = [] for i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] runfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3') y = [] s = [] for i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] runfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3') y = [] s = [] for i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b] runfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3') ##---(Wed Mar 23 11:14:55 2016)--- runfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')
normal
{ "blob_id": "02b20c3f5941873dfd22a7fbedb825e66c613ace", "index": 2278, "step-1": "Xeval[[1,2],:]\r\n# *** Spyder Python Console History Log ***\r\nXeval[:,:]\r\noptfunc.P(Xeval[:,:])\r\noptfunc.P(Xeval)\r\noptfunc.P(Xeval[[0,1,2,3,4],:])\r\noptfunc.P(Xeval[[0,1,],:])\r\noptfunc.P(Xeval[[0,1],:])\r\noptfunc.P(Xeval[[0,1,2,3],:])\r\noptfunc.P(Xeval[[0,1,2,3,4],:])\r\noptfunc.P(Xeval[[0,1,2],:])\r\nXeval[[0,1,2,3,4],:]\r\nXeval[[0,1,2,3],:]\r\nXeval[[0,1,2],:]\r\noptfunc.gp_list[0]\r\noptfunc.gp_list[0](Xeval)\r\noptfunc.gp_list[0].preduct(Xeval)\r\noptfunc.gp_list[0].predict(Xeval)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2,3,4],:])\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2,3],:])\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2],:])\r\noptfunc.P(Xeval[[0,1,2,3,4],:])\r\noptfunc.ypred\r\noptfunc.P(Xeval[[0,1,2],:])\r\noptfunc.ypred\r\noptfunc.P(Xeval[[0,1,2,3,4],:])\r\noptfunc.MSE\r\noptfunc.sigma\r\noptfunc.P(Xeval[[0,1,2],:])\r\noptfunc.sigma\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2,3],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,1],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,1,1],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[zeros(1,5)],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[np.zeros(1,5)],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[np.zeros(1,5),:],eval_MSE=True)\r\nnp.zeros(1,5)\r\nnp.zeros(5)\r\noptfunc.gp_list[0].predict(Xeval[np.zeros(15),:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[np.zeros(5),:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[np.zeros(5)],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True)\r\nXeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:]\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2,3],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,1,2],:],eval_MSE=True)\r\nXeval[[0,1,2,3]]\r\nXeval[[0,1,2]]\r\nXeval[[0,1,2],:]\r\noptfunc.gp_list[0].predict(Xeval[[0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict(Xeval[[0,0,0,0],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict([0.5,0.5],:],eval_MSE=True)\r\noptfunc.gp_list[0].predict([0.5,0.5],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.5]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.49]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.48]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.495]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.499]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.4999]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.49999]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.5]],eval_MSE=True)\r\noptfunc.gp_list[0].predict([[0.5,0.5001]],eval_MSE=True)\r\nfor i in range(0,100)\r\nfor i in range(0,100): y[i],s[i] = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True)\r\ny = []\r\ns = []\r\nfor i in range(0,100): y[i],s[i] = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True)\r\nfor i in range(0,100): optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True)\r\nfor i in range(0,100): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\ny\r\noptfunc.gp_list[0]\r\nrunfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')\r\ny = []\r\ns = []\r\nfor i in range(0,100): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\ny = []\r\ns = []\r\nfor i in range(0,200): a, b = optfunc.gp_list[0].predict([[0.5,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\ny = []\r\ns = []\r\nfor i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\nrunfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')\r\ny = []\r\ns = []\r\nfor i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\nrunfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')\r\ny = []\r\ns = []\r\nfor i in range(0,200): a, b = optfunc.gp_list[0].predict([[1.,i*0.01]],eval_MSE=True) y = np.r_[y,a] s = np.r_[s,b]\r\nrunfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')\r\n\r\n##---(Wed Mar 23 11:14:55 2016)---\r\nrunfile('C:/Users/b4/.spyder2-py3/PEIOPT.py', wdir='C:/Users/b4/.spyder2-py3')", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import numpy as np a = np.ones((3,4)) b = np.ones((4,1)) # a.shape = (3,4) # b.shape = (4,1) c = np.zeros_like(a) for i in range(3): for j in range(4): c[i][j] = a[i][j] + b[j] print(c) d = a+b.T print(d)
normal
{ "blob_id": "d6213698423902771011caf6b5206dd4e3b27450", "index": 5753, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(3):\n for j in range(4):\n c[i][j] = a[i][j] + b[j]\nprint(c)\n<mask token>\nprint(d)\n", "step-3": "<mask token>\na = np.ones((3, 4))\nb = np.ones((4, 1))\nc = np.zeros_like(a)\nfor i in range(3):\n for j in range(4):\n c[i][j] = a[i][j] + b[j]\nprint(c)\nd = a + b.T\nprint(d)\n", "step-4": "import numpy as np\na = np.ones((3, 4))\nb = np.ones((4, 1))\nc = np.zeros_like(a)\nfor i in range(3):\n for j in range(4):\n c[i][j] = a[i][j] + b[j]\nprint(c)\nd = a + b.T\nprint(d)\n", "step-5": "import numpy as np\n\na = np.ones((3,4))\nb = np.ones((4,1))\n# a.shape = (3,4)\n# b.shape = (4,1)\n\nc = np.zeros_like(a)\n\nfor i in range(3):\n for j in range(4):\n c[i][j] = a[i][j] + b[j]\n\nprint(c)\n\nd = a+b.T\nprint(d)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Generated by Django 3.0.5 on 2020-05-02 18:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('weatherData', '0001_initial'), ] operations = [ migrations.AddField( model_name='city', name='username', field=models.CharField(default='[email protected]', max_length=100), ), ]
normal
{ "blob_id": "6b6b734c136f3c4ed5b2789ab384bab9a9ea7b58", "index": 9368, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('weatherData', '0001_initial')]\n operations = [migrations.AddField(model_name='city', name='username',\n field=models.CharField(default='[email protected]', max_length=100))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('weatherData', '0001_initial')]\n operations = [migrations.AddField(model_name='city', name='username',\n field=models.CharField(default='[email protected]', max_length=100))]\n", "step-5": "# Generated by Django 3.0.5 on 2020-05-02 18:58\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('weatherData', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='city',\n name='username',\n field=models.CharField(default='[email protected]', max_length=100),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import sys INF = sys.maxsize def bellman_ford(graph,start): distance = {} predecessor = {} # 거리 값, 이전 정점 초기화 for node in graph: distance[node] = INF predecessor[node] = None distance[start] = 0 # V-1개마큼 반복 for _ in range(len(graph)-1): for node in graph: for neigbor in graph[node]: if distance[neigbor] > distance[node] + graph[node][neigbor]: distance[neigbor] = distance[node] + graph[node][neigbor] predecessor[neigbor] = node # 음수 사이클이 존재하는지 (1번더 반복후 V-1번 반복했을때랑 같으면 음수사이클X 다르면 음수사이클 존재) for node in graph: for neigbor in graph[node]: if distance[neigbor] > distance[node] + graph[node][neigbor]: return -1, "그래프에 음수 사이클이 존재합니다." return distance,graph # 음수 사이클이 존재하지 않는 그래프 graph = { 'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {}, 'D': {'B': 1, 'C': 5}, 'E': {'D': -3} } # 그래프 정보와 시작 정점을 넘김 distance, predecessor = bellman_ford(graph, start='A') print(distance) print(predecessor) # 음수 사이클이 존재하는 그래프 graph = { 'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {'A': -5}, 'D': {'B': 1, 'C': 5}, 'E': {'D': -3} } distance, predecessor = bellman_ford(graph, start='A') print(distance) print(predecessor)
normal
{ "blob_id": "8ebf031cb294c69bf744d543b18783d6ac5ef257", "index": 1910, "step-1": "<mask token>\n\n\ndef bellman_ford(graph, start):\n distance = {}\n predecessor = {}\n for node in graph:\n distance[node] = INF\n predecessor[node] = None\n distance[start] = 0\n for _ in range(len(graph) - 1):\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n distance[neigbor] = distance[node] + graph[node][neigbor]\n predecessor[neigbor] = node\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n return -1, '그래프에 음수 사이클이 존재합니다.'\n return distance, graph\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef bellman_ford(graph, start):\n distance = {}\n predecessor = {}\n for node in graph:\n distance[node] = INF\n predecessor[node] = None\n distance[start] = 0\n for _ in range(len(graph) - 1):\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n distance[neigbor] = distance[node] + graph[node][neigbor]\n predecessor[neigbor] = node\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n return -1, '그래프에 음수 사이클이 존재합니다.'\n return distance, graph\n\n\n<mask token>\nprint(distance)\nprint(predecessor)\n<mask token>\nprint(distance)\nprint(predecessor)\n", "step-3": "<mask token>\nINF = sys.maxsize\n\n\ndef bellman_ford(graph, start):\n distance = {}\n predecessor = {}\n for node in graph:\n distance[node] = INF\n predecessor[node] = None\n distance[start] = 0\n for _ in range(len(graph) - 1):\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n distance[neigbor] = distance[node] + graph[node][neigbor]\n predecessor[neigbor] = node\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n return -1, '그래프에 음수 사이클이 존재합니다.'\n return distance, graph\n\n\ngraph = {'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {},\n 'D': {'B': 1, 'C': 5}, 'E': {'D': -3}}\ndistance, predecessor = bellman_ford(graph, start='A')\nprint(distance)\nprint(predecessor)\ngraph = {'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {'A': \n -5}, 'D': {'B': 1, 'C': 5}, 'E': {'D': -3}}\ndistance, predecessor = bellman_ford(graph, start='A')\nprint(distance)\nprint(predecessor)\n", "step-4": "import sys\nINF = sys.maxsize\n\n\ndef bellman_ford(graph, start):\n distance = {}\n predecessor = {}\n for node in graph:\n distance[node] = INF\n predecessor[node] = None\n distance[start] = 0\n for _ in range(len(graph) - 1):\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n distance[neigbor] = distance[node] + graph[node][neigbor]\n predecessor[neigbor] = node\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n return -1, '그래프에 음수 사이클이 존재합니다.'\n return distance, graph\n\n\ngraph = {'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {},\n 'D': {'B': 1, 'C': 5}, 'E': {'D': -3}}\ndistance, predecessor = bellman_ford(graph, start='A')\nprint(distance)\nprint(predecessor)\ngraph = {'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {'A': \n -5}, 'D': {'B': 1, 'C': 5}, 'E': {'D': -3}}\ndistance, predecessor = bellman_ford(graph, start='A')\nprint(distance)\nprint(predecessor)\n", "step-5": "import sys\nINF = sys.maxsize\ndef bellman_ford(graph,start):\n distance = {}\n predecessor = {}\n \n # 거리 값, 이전 정점 초기화\n for node in graph:\n distance[node] = INF\n predecessor[node] = None\n distance[start] = 0\n\n # V-1개마큼 반복\n for _ in range(len(graph)-1):\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n distance[neigbor] = distance[node] + graph[node][neigbor]\n predecessor[neigbor] = node\n \n # 음수 사이클이 존재하는지 (1번더 반복후 V-1번 반복했을때랑 같으면 음수사이클X 다르면 음수사이클 존재)\n for node in graph:\n for neigbor in graph[node]:\n if distance[neigbor] > distance[node] + graph[node][neigbor]:\n return -1, \"그래프에 음수 사이클이 존재합니다.\"\n \n return distance,graph\n\n# 음수 사이클이 존재하지 않는 그래프\ngraph = {\n 'A': {'B': -1, 'C': 4},\n 'B': {'C': 3, 'D': 2, 'E': 2},\n 'C': {},\n 'D': {'B': 1, 'C': 5},\n 'E': {'D': -3}\n}\n\n# 그래프 정보와 시작 정점을 넘김\ndistance, predecessor = bellman_ford(graph, start='A')\n\nprint(distance)\nprint(predecessor)\n\n\n# 음수 사이클이 존재하는 그래프\ngraph = {\n 'A': {'B': -1, 'C': 4},\n 'B': {'C': 3, 'D': 2, 'E': 2},\n 'C': {'A': -5},\n 'D': {'B': 1, 'C': 5},\n 'E': {'D': -3}\n}\n\n\ndistance, predecessor = bellman_ford(graph, start='A')\n\nprint(distance)\nprint(predecessor)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-10-28 17:50 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='EMR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('emergency', models.CharField(default='', max_length=10)), ], ), migrations.CreateModel( name='EMRNote', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)), ('comments', models.CharField(default='', max_length=500)), ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='EMRTrackedMetric', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)), ('label', models.CharField(default='', max_length=200)), ('comments', models.CharField(default='', max_length=500)), ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='EMRVitals', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)), ('restingBPM', models.IntegerField(default=0)), ('bloodPressure', models.CharField(default='', max_length=10)), ('height', models.FloatField(default=0)), ('weight', models.FloatField(default=0)), ('age', models.IntegerField(default=0)), ('comments', models.CharField(default='', max_length=1000)), ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')), ], options={ 'abstract': False, }, ), ]
normal
{ "blob_id": "b0064a5cd494d5ad232f27c63a4df2c56a4c6a66", "index": 5241, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='EMR', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('emergency', models.CharField(default='',\n max_length=10))]), migrations.CreateModel(name='EMRNote', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('dateCreated', models.\n DateTimeField(default=django.utils.timezone.now)), ('comments',\n models.CharField(default='', max_length=500)), ('emr', models.\n ForeignKey(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='emr.EMR'))], options={'abstract': False}),\n migrations.CreateModel(name='EMRTrackedMetric', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('dateCreated', models.DateTimeField(\n default=django.utils.timezone.now)), ('label', models.CharField(\n default='', max_length=200)), ('comments', models.CharField(default\n ='', max_length=500)), ('emr', models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR'))],\n options={'abstract': False}), migrations.CreateModel(name=\n 'EMRVitals', fields=[('id', models.AutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), (\n 'dateCreated', models.DateTimeField(default=django.utils.timezone.\n now)), ('restingBPM', models.IntegerField(default=0)), (\n 'bloodPressure', models.CharField(default='', max_length=10)), (\n 'height', models.FloatField(default=0)), ('weight', models.\n FloatField(default=0)), ('age', models.IntegerField(default=0)), (\n 'comments', models.CharField(default='', max_length=1000)), ('emr',\n models.ForeignKey(blank=True, null=True, on_delete=django.db.models\n .deletion.CASCADE, to='emr.EMR'))], options={'abstract': False})]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='EMR', fields=[('id', models.\n AutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), ('emergency', models.CharField(default='',\n max_length=10))]), migrations.CreateModel(name='EMRNote', fields=[(\n 'id', models.AutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), ('dateCreated', models.\n DateTimeField(default=django.utils.timezone.now)), ('comments',\n models.CharField(default='', max_length=500)), ('emr', models.\n ForeignKey(blank=True, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='emr.EMR'))], options={'abstract': False}),\n migrations.CreateModel(name='EMRTrackedMetric', fields=[('id',\n models.AutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('dateCreated', models.DateTimeField(\n default=django.utils.timezone.now)), ('label', models.CharField(\n default='', max_length=200)), ('comments', models.CharField(default\n ='', max_length=500)), ('emr', models.ForeignKey(blank=True, null=\n True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR'))],\n options={'abstract': False}), migrations.CreateModel(name=\n 'EMRVitals', fields=[('id', models.AutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), (\n 'dateCreated', models.DateTimeField(default=django.utils.timezone.\n now)), ('restingBPM', models.IntegerField(default=0)), (\n 'bloodPressure', models.CharField(default='', max_length=10)), (\n 'height', models.FloatField(default=0)), ('weight', models.\n FloatField(default=0)), ('age', models.IntegerField(default=0)), (\n 'comments', models.CharField(default='', max_length=1000)), ('emr',\n models.ForeignKey(blank=True, null=True, on_delete=django.db.models\n .deletion.CASCADE, to='emr.EMR'))], options={'abstract': False})]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.1 on 2016-10-28 17:50\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='EMR',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('emergency', models.CharField(default='', max_length=10)),\n ],\n ),\n migrations.CreateModel(\n name='EMRNote',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)),\n ('comments', models.CharField(default='', max_length=500)),\n ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='EMRTrackedMetric',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)),\n ('label', models.CharField(default='', max_length=200)),\n ('comments', models.CharField(default='', max_length=500)),\n ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='EMRVitals',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('dateCreated', models.DateTimeField(default=django.utils.timezone.now)),\n ('restingBPM', models.IntegerField(default=0)),\n ('bloodPressure', models.CharField(default='', max_length=10)),\n ('height', models.FloatField(default=0)),\n ('weight', models.FloatField(default=0)),\n ('age', models.IntegerField(default=0)),\n ('comments', models.CharField(default='', max_length=1000)),\n ('emr', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='emr.EMR')),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Generated by Django 2.2.17 on 2020-12-05 07:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('service', '0001_initial'), ] operations = [ migrations.AlterField( model_name='identification', name='id_card_img', field=models.ImageField(blank=True, null=True, upload_to='images/img_card/'), ), migrations.AlterField( model_name='identification', name='selfie_img', field=models.ImageField(blank=True, null=True, upload_to='images/img_selfie/'), ), ]
normal
{ "blob_id": "b6a0a49e05fbc0ac7673d6c9e8ca4d263c8bb5cd", "index": 7132, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('service', '0001_initial')]\n operations = [migrations.AlterField(model_name='identification', name=\n 'id_card_img', field=models.ImageField(blank=True, null=True,\n upload_to='images/img_card/')), migrations.AlterField(model_name=\n 'identification', name='selfie_img', field=models.ImageField(blank=\n True, null=True, upload_to='images/img_selfie/'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('service', '0001_initial')]\n operations = [migrations.AlterField(model_name='identification', name=\n 'id_card_img', field=models.ImageField(blank=True, null=True,\n upload_to='images/img_card/')), migrations.AlterField(model_name=\n 'identification', name='selfie_img', field=models.ImageField(blank=\n True, null=True, upload_to='images/img_selfie/'))]\n", "step-5": "# Generated by Django 2.2.17 on 2020-12-05 07:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('service', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='identification',\n name='id_card_img',\n field=models.ImageField(blank=True, null=True, upload_to='images/img_card/'),\n ),\n migrations.AlterField(\n model_name='identification',\n name='selfie_img',\n field=models.ImageField(blank=True, null=True, upload_to='images/img_selfie/'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import csv from bookstoscrapy import settings def write_to_csv(item): writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n') writer.writerow([item[key] for key in item.keys()]) class WriteToCsv(object): item_counter = 0 def process_item(self, item, spider): write_to_csv(item) return item
normal
{ "blob_id": "f0c621583caf6eea6f790649862a03a464f6574b", "index": 3727, "step-1": "<mask token>\n\n\nclass WriteToCsv(object):\n <mask token>\n\n def process_item(self, item, spider):\n write_to_csv(item)\n return item\n", "step-2": "<mask token>\n\n\nclass WriteToCsv(object):\n item_counter = 0\n\n def process_item(self, item, spider):\n write_to_csv(item)\n return item\n", "step-3": "<mask token>\n\n\ndef write_to_csv(item):\n writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\\n')\n writer.writerow([item[key] for key in item.keys()])\n\n\nclass WriteToCsv(object):\n item_counter = 0\n\n def process_item(self, item, spider):\n write_to_csv(item)\n return item\n", "step-4": "import csv\nfrom bookstoscrapy import settings\n\n\ndef write_to_csv(item):\n writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\\n')\n writer.writerow([item[key] for key in item.keys()])\n\n\nclass WriteToCsv(object):\n item_counter = 0\n\n def process_item(self, item, spider):\n write_to_csv(item)\n return item\n", "step-5": "# -*- 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: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nimport csv\nfrom bookstoscrapy import settings\n\n\ndef write_to_csv(item):\n writer = csv.writer(open(settings.csv_file_path, 'a'),\n lineterminator='\\n')\n writer.writerow([item[key] for key in item.keys()])\n\n\nclass WriteToCsv(object):\n item_counter = 0\n\n def process_item(self, item, spider):\n write_to_csv(item)\n return item\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
# Generated by Django 3.1.7 on 2021-04-16 05:56 from django.db import migrations import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('Checkbook', '0002_auto_20210415_2250'), ] operations = [ migrations.AlterModelManagers( name='transaction', managers=[ ('Transactions', django.db.models.manager.Manager()), ], ), ]
normal
{ "blob_id": "f15f49a29f91181d0aaf66b19ce9616dc7576be8", "index": 6740, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('Checkbook', '0002_auto_20210415_2250')]\n operations = [migrations.AlterModelManagers(name='transaction',\n managers=[('Transactions', django.db.models.manager.Manager())])]\n", "step-4": "from django.db import migrations\nimport django.db.models.manager\n\n\nclass Migration(migrations.Migration):\n dependencies = [('Checkbook', '0002_auto_20210415_2250')]\n operations = [migrations.AlterModelManagers(name='transaction',\n managers=[('Transactions', django.db.models.manager.Manager())])]\n", "step-5": "# Generated by Django 3.1.7 on 2021-04-16 05:56\n\nfrom django.db import migrations\nimport django.db.models.manager\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Checkbook', '0002_auto_20210415_2250'),\n ]\n\n operations = [\n migrations.AlterModelManagers(\n name='transaction',\n managers=[\n ('Transactions', django.db.models.manager.Manager()),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
class Fail(Exception): def __init__(self, message): super().__init__(message) class Student: def __init__(self, rollNo, name, marks): self.rollNo = rollNo self.name = name self.marks = marks def displayDetails(self): print('{} \t {} \t {}'.format(self.name, self.rollNo, self.marks)) try: if self.marks < 40: raise Fail('Student {} has Scored {} marks and has Failed ' .format(self.name, self.marks)) except Fail as f: print(f) myStudentList = [] num = int(input('Enter the number of Students : ')) for i in range(num): rollNo, name, marks = input('Enter Roll-no,Name,Marks of Student {} : ' .format(i + 1)).split(',') print('----------------------------------------') marks = int(marks) myStudentList.append(Student(rollNo, name, marks)) print('DETAILS OF STUDENTS ARE : ') for i in range(num): myStudentList[i].displayDetails()
normal
{ "blob_id": "ddf074e400551d2c147d898fe876a31d13a72699", "index": 5324, "step-1": "<mask token>\n\n\nclass Student:\n <mask token>\n\n def displayDetails(self):\n print('{} \\t {} \\t {}'.format(self.name, self.rollNo, self.marks))\n try:\n if self.marks < 40:\n raise Fail('Student {} has Scored {} marks and has Failed '\n .format(self.name, self.marks))\n except Fail as f:\n print(f)\n\n\n<mask token>\n", "step-2": "class Fail(Exception):\n\n def __init__(self, message):\n super().__init__(message)\n\n\nclass Student:\n\n def __init__(self, rollNo, name, marks):\n self.rollNo = rollNo\n self.name = name\n self.marks = marks\n\n def displayDetails(self):\n print('{} \\t {} \\t {}'.format(self.name, self.rollNo, self.marks))\n try:\n if self.marks < 40:\n raise Fail('Student {} has Scored {} marks and has Failed '\n .format(self.name, self.marks))\n except Fail as f:\n print(f)\n\n\n<mask token>\n", "step-3": "class Fail(Exception):\n\n def __init__(self, message):\n super().__init__(message)\n\n\nclass Student:\n\n def __init__(self, rollNo, name, marks):\n self.rollNo = rollNo\n self.name = name\n self.marks = marks\n\n def displayDetails(self):\n print('{} \\t {} \\t {}'.format(self.name, self.rollNo, self.marks))\n try:\n if self.marks < 40:\n raise Fail('Student {} has Scored {} marks and has Failed '\n .format(self.name, self.marks))\n except Fail as f:\n print(f)\n\n\n<mask token>\nfor i in range(num):\n rollNo, name, marks = input('Enter Roll-no,Name,Marks of Student {} : '\n .format(i + 1)).split(',')\n print('----------------------------------------')\n marks = int(marks)\n myStudentList.append(Student(rollNo, name, marks))\nprint('DETAILS OF STUDENTS ARE : ')\nfor i in range(num):\n myStudentList[i].displayDetails()\n", "step-4": "class Fail(Exception):\n\n def __init__(self, message):\n super().__init__(message)\n\n\nclass Student:\n\n def __init__(self, rollNo, name, marks):\n self.rollNo = rollNo\n self.name = name\n self.marks = marks\n\n def displayDetails(self):\n print('{} \\t {} \\t {}'.format(self.name, self.rollNo, self.marks))\n try:\n if self.marks < 40:\n raise Fail('Student {} has Scored {} marks and has Failed '\n .format(self.name, self.marks))\n except Fail as f:\n print(f)\n\n\nmyStudentList = []\nnum = int(input('Enter the number of Students : '))\nfor i in range(num):\n rollNo, name, marks = input('Enter Roll-no,Name,Marks of Student {} : '\n .format(i + 1)).split(',')\n print('----------------------------------------')\n marks = int(marks)\n myStudentList.append(Student(rollNo, name, marks))\nprint('DETAILS OF STUDENTS ARE : ')\nfor i in range(num):\n myStudentList[i].displayDetails()\n", "step-5": null, "step-ids": [ 2, 5, 6, 7 ] }
[ 2, 5, 6, 7 ]
r""" 测试dispatch >>> from url_router.map import Map >>> from url_router.rule import Rule >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/foo', endpoint='foo'), ... Rule('/bar/', endpoint='bar'), ... Rule('/any/<name>', endpoint='any'), ... Rule('/string/<string:name>', endpoint='string'), ... Rule('/integer/<int:name>', endpoint='integer'), ... Rule('/float/<float:name>', endpoint='float') ... ]) >>> adapter = m.bind('example.org', '/') >>> def view_func(endpoint, args): ... print(f'endpoint:{endpoint}\nargs:{args}') ... return str(endpoint) ... >>> adapter.dispatch(view_func, '/') endpoint:index args:{} 'index' >>> adapter.dispatch(view_func, '/any/value') endpoint:any args:{'name': 'value'} 'any' >>> adapter.dispatch(view_func, '/missing') Traceback (most recent call last): ... url_router.exceptions.NotFound """ if __name__ == "__main__": import doctest doctest.testmod()
normal
{ "blob_id": "3cca7408eb88f91f295c581c29d3d1e95298f337", "index": 6445, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n", "step-3": "r\"\"\" 测试dispatch\n\n>>> from url_router.map import Map\n>>> from url_router.rule import Rule\n>>> m = Map([\n... Rule('/', endpoint='index'),\n... Rule('/foo', endpoint='foo'),\n... Rule('/bar/', endpoint='bar'),\n... Rule('/any/<name>', endpoint='any'),\n... Rule('/string/<string:name>', endpoint='string'),\n... Rule('/integer/<int:name>', endpoint='integer'),\n... Rule('/float/<float:name>', endpoint='float')\n... ])\n>>> adapter = m.bind('example.org', '/')\n\n>>> def view_func(endpoint, args):\n... print(f'endpoint:{endpoint}\\nargs:{args}')\n... return str(endpoint)\n...\n\n\n>>> adapter.dispatch(view_func, '/')\nendpoint:index\nargs:{}\n'index'\n\n>>> adapter.dispatch(view_func, '/any/value')\nendpoint:any\nargs:{'name': 'value'}\n'any'\n\n>>> adapter.dispatch(view_func, '/missing')\nTraceback (most recent call last):\n ...\nurl_router.exceptions.NotFound\n\"\"\"\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import requests from bs4 import BeautifulSoup url = "http://javmobile.net/?s=julia" r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") imgs = soup.find_all("img" , {"class": "entry-thumb"}) images = [] titles = [] srcs = [] for img in imgs: images.append(img.get("src")) titles.append(img.get("title")) srcs.append(img.get("href")) videos = [] for src in srcs: url2 = "http://javmobile.net/censored/oppai/pppd-524-spence-mammary-gland-development-clinic-special-julia.html" r2 = requests.get(url2) soup2 = BeautifulSoup(r2.content, "html.parser") jsonList = {} for i in range(0,len(images)): jsonList.append({"name" : titles[i], "thumb": images[i]}) print jsonList
normal
{ "blob_id": "a9df8e45c8b5068aeec2b79e21de6217a3103bb4", "index": 2492, "step-1": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurl = \"http://javmobile.net/?s=julia\"\nr = requests.get(url)\n\nsoup = BeautifulSoup(r.content, \"html.parser\")\n\nimgs = soup.find_all(\"img\" , {\"class\": \"entry-thumb\"})\n\n\nimages = []\ntitles = []\nsrcs = []\n\nfor img in imgs:\n images.append(img.get(\"src\"))\n titles.append(img.get(\"title\"))\n srcs.append(img.get(\"href\"))\n\nvideos = []\n\nfor src in srcs:\n url2 = \"http://javmobile.net/censored/oppai/pppd-524-spence-mammary-gland-development-clinic-special-julia.html\"\n r2 = requests.get(url2)\n soup2 = BeautifulSoup(r2.content, \"html.parser\")\n\n\njsonList = {}\nfor i in range(0,len(images)):\n jsonList.append({\"name\" : titles[i], \"thumb\": images[i]})\n\nprint jsonList", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from typing import List from fastapi import Depends, FastAPI, HTTPException from sqlalchemy.orm import Session from myfirstpython.fastapi import models, crud, schemas from myfirstpython.fastapi.dbconnection import engine, SessionLocal models.Base.metadata.create_all(bind=engine) app = FastAPI() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.post("/jobs/", response_model=schemas.JobCreate) def create_job(job: schemas.JobCreate, db: Session = Depends(get_db)): db_job = crud.get_job(db, job.title) if db_job: raise HTTPException(status_code=400, detail="Job already Posted") return crud.create_job(db=db, job=job) @app.get("/jobs/", response_model=List[schemas.Job]) def read_jobs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): jobs = crud.get_jobs(db, skip=skip, limit=limit) return jobs @app.get("/jobs/{job_id}", response_model=schemas.Job) def read_job(job_id: int, db: Session = Depends(get_db)): db_job = crud.get_job(db, job_id=job_id) if db_job is None: raise HTTPException(status_code=404, detail="Job not found") return db_job @app.post("/cands/", response_model=schemas.CanCreate) def create_can(can: schemas.CanCreate, db: Session = Depends(get_db)): db_can = crud.get_candidate(db, can.email) if db_can: raise HTTPException(status_code=400, detail="Candidate already Present") return crud.create_candidate(db=db, can=can) @app.get("/cands/", response_model=List[schemas.Can]) def read_cans(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): cans = crud.get_candidates(db, skip=skip, limit=limit) return cans @app.get("/cands/{email}", response_model=schemas.Can) def read_can(email: str, db: Session = Depends(get_db)): db_can = crud.get_candidate(db, email) if db_can is None: raise HTTPException(status_code=404, detail="Candidate not found") return db_can @app.get("/jobapps/", response_model=List[schemas.AppBase]) def read_jobapps(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): jobapps = crud.get_jobapps(db, skip=skip, limit=limit) return jobapps @app.get("/jobapps/{appid}", response_model=schemas.AppBase) def read_jobapp(appid: int, db: Session = Depends(get_db)): db_jobapp = crud.get_jobapp(db, appid) if db_jobapp is None: raise HTTPException(status_code=404, detail="Job Application not found") return db_jobapp
normal
{ "blob_id": "ad474f5120ca2a8c81b18071ab364e6d6cf9e653", "index": 7031, "step-1": "<mask token>\n\n\[email protected]('/jobs/', response_model=List[schemas.Job])\ndef read_jobs(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobs = crud.get_jobs(db, skip=skip, limit=limit)\n return jobs\n\n\[email protected]('/jobs/{job_id}', response_model=schemas.Job)\ndef read_job(job_id: int, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job_id=job_id)\n if db_job is None:\n raise HTTPException(status_code=404, detail='Job not found')\n return db_job\n\n\[email protected]('/cands/', response_model=schemas.CanCreate)\ndef create_can(can: schemas.CanCreate, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, can.email)\n if db_can:\n raise HTTPException(status_code=400, detail='Candidate already Present'\n )\n return crud.create_candidate(db=db, can=can)\n\n\[email protected]('/cands/', response_model=List[schemas.Can])\ndef read_cans(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n cans = crud.get_candidates(db, skip=skip, limit=limit)\n return cans\n\n\[email protected]('/cands/{email}', response_model=schemas.Can)\ndef read_can(email: str, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, email)\n if db_can is None:\n raise HTTPException(status_code=404, detail='Candidate not found')\n return db_can\n\n\[email protected]('/jobapps/', response_model=List[schemas.AppBase])\ndef read_jobapps(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobapps = crud.get_jobapps(db, skip=skip, limit=limit)\n return jobapps\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\n<mask token>\n\n\[email protected]('/jobs/', response_model=List[schemas.Job])\ndef read_jobs(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobs = crud.get_jobs(db, skip=skip, limit=limit)\n return jobs\n\n\[email protected]('/jobs/{job_id}', response_model=schemas.Job)\ndef read_job(job_id: int, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job_id=job_id)\n if db_job is None:\n raise HTTPException(status_code=404, detail='Job not found')\n return db_job\n\n\[email protected]('/cands/', response_model=schemas.CanCreate)\ndef create_can(can: schemas.CanCreate, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, can.email)\n if db_can:\n raise HTTPException(status_code=400, detail='Candidate already Present'\n )\n return crud.create_candidate(db=db, can=can)\n\n\[email protected]('/cands/', response_model=List[schemas.Can])\ndef read_cans(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n cans = crud.get_candidates(db, skip=skip, limit=limit)\n return cans\n\n\[email protected]('/cands/{email}', response_model=schemas.Can)\ndef read_can(email: str, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, email)\n if db_can is None:\n raise HTTPException(status_code=404, detail='Candidate not found')\n return db_can\n\n\[email protected]('/jobapps/', response_model=List[schemas.AppBase])\ndef read_jobapps(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobapps = crud.get_jobapps(db, skip=skip, limit=limit)\n return jobapps\n\n\[email protected]('/jobapps/{appid}', response_model=schemas.AppBase)\ndef read_jobapp(appid: int, db: Session=Depends(get_db)):\n db_jobapp = crud.get_jobapp(db, appid)\n if db_jobapp is None:\n raise HTTPException(status_code=404, detail='Job Application not found'\n )\n return db_jobapp\n", "step-3": "<mask token>\nmodels.Base.metadata.create_all(bind=engine)\n<mask token>\n\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\[email protected]('/jobs/', response_model=schemas.JobCreate)\ndef create_job(job: schemas.JobCreate, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job.title)\n if db_job:\n raise HTTPException(status_code=400, detail='Job already Posted')\n return crud.create_job(db=db, job=job)\n\n\[email protected]('/jobs/', response_model=List[schemas.Job])\ndef read_jobs(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobs = crud.get_jobs(db, skip=skip, limit=limit)\n return jobs\n\n\[email protected]('/jobs/{job_id}', response_model=schemas.Job)\ndef read_job(job_id: int, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job_id=job_id)\n if db_job is None:\n raise HTTPException(status_code=404, detail='Job not found')\n return db_job\n\n\[email protected]('/cands/', response_model=schemas.CanCreate)\ndef create_can(can: schemas.CanCreate, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, can.email)\n if db_can:\n raise HTTPException(status_code=400, detail='Candidate already Present'\n )\n return crud.create_candidate(db=db, can=can)\n\n\[email protected]('/cands/', response_model=List[schemas.Can])\ndef read_cans(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n cans = crud.get_candidates(db, skip=skip, limit=limit)\n return cans\n\n\[email protected]('/cands/{email}', response_model=schemas.Can)\ndef read_can(email: str, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, email)\n if db_can is None:\n raise HTTPException(status_code=404, detail='Candidate not found')\n return db_can\n\n\[email protected]('/jobapps/', response_model=List[schemas.AppBase])\ndef read_jobapps(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobapps = crud.get_jobapps(db, skip=skip, limit=limit)\n return jobapps\n\n\[email protected]('/jobapps/{appid}', response_model=schemas.AppBase)\ndef read_jobapp(appid: int, db: Session=Depends(get_db)):\n db_jobapp = crud.get_jobapp(db, appid)\n if db_jobapp is None:\n raise HTTPException(status_code=404, detail='Job Application not found'\n )\n return db_jobapp\n", "step-4": "<mask token>\nmodels.Base.metadata.create_all(bind=engine)\napp = FastAPI()\n\n\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\[email protected]('/jobs/', response_model=schemas.JobCreate)\ndef create_job(job: schemas.JobCreate, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job.title)\n if db_job:\n raise HTTPException(status_code=400, detail='Job already Posted')\n return crud.create_job(db=db, job=job)\n\n\[email protected]('/jobs/', response_model=List[schemas.Job])\ndef read_jobs(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobs = crud.get_jobs(db, skip=skip, limit=limit)\n return jobs\n\n\[email protected]('/jobs/{job_id}', response_model=schemas.Job)\ndef read_job(job_id: int, db: Session=Depends(get_db)):\n db_job = crud.get_job(db, job_id=job_id)\n if db_job is None:\n raise HTTPException(status_code=404, detail='Job not found')\n return db_job\n\n\[email protected]('/cands/', response_model=schemas.CanCreate)\ndef create_can(can: schemas.CanCreate, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, can.email)\n if db_can:\n raise HTTPException(status_code=400, detail='Candidate already Present'\n )\n return crud.create_candidate(db=db, can=can)\n\n\[email protected]('/cands/', response_model=List[schemas.Can])\ndef read_cans(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n cans = crud.get_candidates(db, skip=skip, limit=limit)\n return cans\n\n\[email protected]('/cands/{email}', response_model=schemas.Can)\ndef read_can(email: str, db: Session=Depends(get_db)):\n db_can = crud.get_candidate(db, email)\n if db_can is None:\n raise HTTPException(status_code=404, detail='Candidate not found')\n return db_can\n\n\[email protected]('/jobapps/', response_model=List[schemas.AppBase])\ndef read_jobapps(skip: int=0, limit: int=100, db: Session=Depends(get_db)):\n jobapps = crud.get_jobapps(db, skip=skip, limit=limit)\n return jobapps\n\n\[email protected]('/jobapps/{appid}', response_model=schemas.AppBase)\ndef read_jobapp(appid: int, db: Session=Depends(get_db)):\n db_jobapp = crud.get_jobapp(db, appid)\n if db_jobapp is None:\n raise HTTPException(status_code=404, detail='Job Application not found'\n )\n return db_jobapp\n", "step-5": "from typing import List\n\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom sqlalchemy.orm import Session\n\nfrom myfirstpython.fastapi import models, crud, schemas\nfrom myfirstpython.fastapi.dbconnection import engine, SessionLocal\n\nmodels.Base.metadata.create_all(bind=engine)\n\napp = FastAPI()\n\n\n# Dependency\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\[email protected](\"/jobs/\", response_model=schemas.JobCreate)\ndef create_job(job: schemas.JobCreate, db: Session = Depends(get_db)):\n db_job = crud.get_job(db, job.title)\n if db_job:\n raise HTTPException(status_code=400, detail=\"Job already Posted\")\n return crud.create_job(db=db, job=job)\n\n\[email protected](\"/jobs/\", response_model=List[schemas.Job])\ndef read_jobs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n jobs = crud.get_jobs(db, skip=skip, limit=limit)\n return jobs\n\n\[email protected](\"/jobs/{job_id}\", response_model=schemas.Job)\ndef read_job(job_id: int, db: Session = Depends(get_db)):\n db_job = crud.get_job(db, job_id=job_id)\n if db_job is None:\n raise HTTPException(status_code=404, detail=\"Job not found\")\n return db_job\n\n\[email protected](\"/cands/\", response_model=schemas.CanCreate)\ndef create_can(can: schemas.CanCreate, db: Session = Depends(get_db)):\n db_can = crud.get_candidate(db, can.email)\n if db_can:\n raise HTTPException(status_code=400, detail=\"Candidate already Present\")\n return crud.create_candidate(db=db, can=can)\n\n\[email protected](\"/cands/\", response_model=List[schemas.Can])\ndef read_cans(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n cans = crud.get_candidates(db, skip=skip, limit=limit)\n return cans\n\n\[email protected](\"/cands/{email}\", response_model=schemas.Can)\ndef read_can(email: str, db: Session = Depends(get_db)):\n db_can = crud.get_candidate(db, email)\n if db_can is None:\n raise HTTPException(status_code=404, detail=\"Candidate not found\")\n return db_can\n\n\[email protected](\"/jobapps/\", response_model=List[schemas.AppBase])\ndef read_jobapps(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n jobapps = crud.get_jobapps(db, skip=skip, limit=limit)\n return jobapps\n\n\[email protected](\"/jobapps/{appid}\", response_model=schemas.AppBase)\ndef read_jobapp(appid: int, db: Session = Depends(get_db)):\n db_jobapp = crud.get_jobapp(db, appid)\n if db_jobapp is None:\n raise HTTPException(status_code=404, detail=\"Job Application not found\")\n return db_jobapp\n", "step-ids": [ 6, 8, 10, 11, 13 ] }
[ 6, 8, 10, 11, 13 ]
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox from PyQt5.QtCore import QDate, QTime, QDateTime, Qt from OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog from OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog from OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog from OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog class TeacherGUI(): def __init__(self): pass @classmethod def setup(cls, ui_mainwindow): cls.__ui_mainwindow = ui_mainwindow @classmethod def display_all_active_school_classes(cls, school_classes): cls.__ui_mainwindow.tableWidget_14.clear() row = 0 col = 0 for (school_class_id, ) in school_classes: school_class_text = "Class " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item) if (col >= 4): col = 0 row += 1 else: col += 1 @classmethod def display_all_exams(cls, all_exams): cls.__ui_mainwindow.tableWidget_5.clear() row = 0 col = 0 for (exam_id, ) in all_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item) if (col >= 9): col = 0 row += 1 else: col += 1 @classmethod def display_not_completed_exams(cls, not_completed_exams): cls.__ui_mainwindow.tableWidget_16.clear() row = 0 col = 0 for (exam_id, ) in not_completed_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item) if (col >= 6): col = 0 row += 1 else: col += 1 @classmethod def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams): cls.__ui_mainwindow.tableWidget_17.clear() row = 0 col = 0 for (exam_id, ) in ready_to_be_marked_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item) if (col >= 3): col = 0 row += 1 else: col += 1 @classmethod def display_single_answer_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_SingleAnswerQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label.setText(question_body) cls.__ui_dialog.label_3.setText("A " + option_A_text) cls.__ui_dialog.label_4.setText("B " + option_B_text) cls.__ui_dialog.label_5.setText("C " + option_C_text) cls.__ui_dialog.label_6.setText("D " + option_D_text) cls.__ui_dialog.label_7.setText("E " + option_E_text) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def display_multiple_answers_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit_14.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label.setText(question_body) cls.__ui_dialog.label_3.setText(option_A_text) cls.__ui_dialog.label_4.setText(option_B_text) cls.__ui_dialog.label_5.setText(option_C_text) cls.__ui_dialog.label_6.setText(option_D_text) cls.__ui_dialog.label_7.setText(option_E_text) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def display_essay_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit_19.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_EssayQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) if (question_body == ""): cls.__ui_dialog.label.setText("Question Body") else: cls.__ui_dialog.label.setText(question_body) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def close_dialog(cls): cls.__dialog.close() @classmethod def get_single_answer_question_details(cls): question_body = cls.__ui_mainwindow.textEdit.toPlainText() if (question_body == ""): return None option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText() if (option_A_text == ""): return None option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText() if (option_B_text == ""): return None option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText() if (option_C_text == ""): return None option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText() if (option_D_text == ""): return None option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText() if (option_E_text == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_3.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text() if (phrase_tag_text == ""): return None correct_answers_list = [] if (cls.__ui_mainwindow.radioButton.isChecked()): correct_answers_list.append("A") if (cls.__ui_mainwindow.radioButton_2.isChecked()): correct_answers_list.append("B") if (cls.__ui_mainwindow.radioButton_5.isChecked()): correct_answers_list.append("C") if (cls.__ui_mainwindow.radioButton_3.isChecked()): correct_answers_list.append("D") if (cls.__ui_mainwindow.radioButton_4.isChecked()): correct_answers_list.append("E") if (correct_answers_list == []): return None if (len(correct_answers_list) > 1): return None return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list) @classmethod def get_multiple_answers_question_details(cls): question_body = cls.__ui_mainwindow.textEdit_14.toPlainText() if (question_body == ""): return None option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText() if (option_A_text == ""): return None option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText() if (option_B_text == ""): return None option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText() if (option_C_text == ""): return None option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText() if (option_D_text == ""): return None option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText() if (option_E_text == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_25.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text() if (phrase_tag_text == ""): return None correct_answers_list = [] if (cls.__ui_mainwindow.checkBox.isChecked()): correct_answers_list.append("A") if (cls.__ui_mainwindow.checkBox_2.isChecked()): correct_answers_list.append("B") if (cls.__ui_mainwindow.checkBox_3.isChecked()): correct_answers_list.append("C") if (cls.__ui_mainwindow.checkBox_4.isChecked()): correct_answers_list.append("D") if (cls.__ui_mainwindow.checkBox_5.isChecked()): correct_answers_list.append("E") if (correct_answers_list == []): return None if (len(correct_answers_list) > 4): return None return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list) @classmethod def get_essay_question_details(cls): question_body = cls.__ui_mainwindow.textEdit_19.toPlainText() if (question_body == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_26.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text() if (phrase_tag_text == ""): return None return (question_body, year_level, phrase_tag_text) @classmethod def display_all_active_questions(cls, active_questions_tuple): row = 0 col = 0 for question_pk_tuple in active_questions_tuple: question_pk = question_pk_tuple[0] question_text = "Question " + str(question_pk) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item) if (col >= 7): col = 0 row += 1 else: col += 1 @classmethod def display_create_single_answer_question_success(cls): cls.__ui_mainwindow.label_4.setText("Create Single Answer Question Success") @classmethod def display_invalid_single_answer_question_creation_message(cls): cls.__ui_mainwindow.label_4.setText("Invalid Single Answer Question Creation") @classmethod def display_create_multiple_answers_question_success(cls): cls.__ui_mainwindow.label_11.setText("Create Multiple Answers Question Success") @classmethod def display_invalid_multiple_answers_question_creation_message(cls): cls.__ui_mainwindow.label_11.setText("Invalid Multiple Answers Question Creation") @classmethod def display_invalid_essay_question_creation_message(cls): cls.__ui_mainwindow.label_42.setText("Invalid Essay Question Creation") @classmethod def display_create_essay_question_success(cls): cls.__ui_mainwindow.label_42.setText("Create Essay Question Success") @classmethod def display_invalid_modification_message(cls): cls.__ui_mainwindow.label_57.setText("Invalid Modification") @classmethod def refresh_create_single_answer_question_page(cls): cls.__ui_mainwindow.textEdit.clear() cls.__ui_mainwindow.textEdit_2.clear() cls.__ui_mainwindow.textEdit_3.clear() cls.__ui_mainwindow.textEdit_4.clear() cls.__ui_mainwindow.textEdit_5.clear() cls.__ui_mainwindow.textEdit_6.clear() cls.__ui_mainwindow.lineEdit_3.clear() cls.__ui_mainwindow.lineEdit_4.clear() cls.__ui_mainwindow.radioButton.setChecked(False) cls.__ui_mainwindow.radioButton_2.setChecked(False) cls.__ui_mainwindow.radioButton_3.setChecked(False) cls.__ui_mainwindow.radioButton_4.setChecked(False) cls.__ui_mainwindow.radioButton_5.setChecked(False) @classmethod def refresh_create_multiple_answers_question_page(cls): cls.__ui_mainwindow.textEdit_14.clear() cls.__ui_mainwindow.textEdit_13.clear() cls.__ui_mainwindow.textEdit_15.clear() cls.__ui_mainwindow.textEdit_16.clear() cls.__ui_mainwindow.textEdit_17.clear() cls.__ui_mainwindow.textEdit_18.clear() cls.__ui_mainwindow.lineEdit_25.clear() cls.__ui_mainwindow.lineEdit_7.clear() cls.__ui_mainwindow.checkBox.setChecked(False) cls.__ui_mainwindow.checkBox_2.setChecked(False) cls.__ui_mainwindow.checkBox_3.setChecked(False) cls.__ui_mainwindow.checkBox_4.setChecked(False) cls.__ui_mainwindow.checkBox_5.setChecked(False) @classmethod def refresh_view_or_modify_question_page(cls): cls.__ui_mainwindow.lineEdit_5.clear() cls.__ui_mainwindow.label_45.setText("Question ID: ") cls.__ui_mainwindow.label_47.setText("Question Type: ") cls.__ui_mainwindow.label_57.clear() cls.__ui_mainwindow.label_12.clear() cls.__ui_mainwindow.textEdit_7.clear() cls.__ui_mainwindow.textEdit_8.clear() cls.__ui_mainwindow.textEdit_9.clear() cls.__ui_mainwindow.textEdit_10.clear() cls.__ui_mainwindow.textEdit_11.clear() cls.__ui_mainwindow.textEdit_20.clear() cls.__ui_mainwindow.lineEdit_6.clear() cls.__ui_mainwindow.lineEdit_8.clear() cls.__ui_mainwindow.lineEdit_28.clear() cls.__ui_mainwindow.radioButton_6.setDisabled(False) cls.__ui_mainwindow.radioButton_7.setDisabled(False) cls.__ui_mainwindow.radioButton_8.setDisabled(False) cls.__ui_mainwindow.radioButton_9.setDisabled(False) cls.__ui_mainwindow.radioButton_10.setDisabled(False) cls.__ui_mainwindow.textEdit_8.setDisabled(False) cls.__ui_mainwindow.textEdit_9.setDisabled(False) cls.__ui_mainwindow.textEdit_10.setDisabled(False) cls.__ui_mainwindow.textEdit_11.setDisabled(False) cls.__ui_mainwindow.textEdit_20.setDisabled(False) cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_6.setChecked(False) cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_7.setChecked(False) cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_8.setChecked(False) cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_9.setChecked(False) cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_10.setChecked(False) @classmethod def refresh_create_essay_question_page(cls): cls.__ui_mainwindow.textEdit_19.clear() cls.__ui_mainwindow.lineEdit_26.clear() cls.__ui_mainwindow.lineEdit_27.clear() @classmethod def refresh_create_exam_page(cls): cls.__ui_mainwindow.tableWidget_3.clear() cls.__ui_mainwindow.tableWidget_4.clear() cls.__ui_mainwindow.lineEdit_10.clear() cls.__ui_mainwindow.lineEdit_11.clear() cls.__ui_mainwindow.lineEdit_12.clear() cls.__ui_mainwindow.lineEdit_13.clear() @classmethod def get_question_id_to_load(cls): question_id_text = cls.__ui_mainwindow.lineEdit_5.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def load_single_answer_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] option_A_text = question_details[6] option_B_text = question_details[7] option_C_text = question_details[8] option_D_text = question_details[9] option_E_text = question_details[10] correct_answer = question_details[11] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.textEdit_8.setText(option_A_text) cls.__ui_mainwindow.textEdit_9.setText(option_B_text) cls.__ui_mainwindow.textEdit_10.setText(option_C_text) cls.__ui_mainwindow.textEdit_11.setText(option_D_text) cls.__ui_mainwindow.textEdit_20.setText(option_E_text) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) if (correct_answer == "A"): cls.__ui_mainwindow.radioButton_6.setChecked(True) elif (correct_answer == "B"): cls.__ui_mainwindow.radioButton_7.setChecked(True) elif (correct_answer == "C"): cls.__ui_mainwindow.radioButton_8.setChecked(True) elif (correct_answer == "D"): cls.__ui_mainwindow.radioButton_9.setChecked(True) elif (correct_answer == "E"): cls.__ui_mainwindow.radioButton_10.setChecked(True) @classmethod def load_multiple_answers_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] option_A_text = question_details[6] option_B_text = question_details[7] option_C_text = question_details[8] option_D_text = question_details[9] option_E_text = question_details[10] correct_answers = question_details[11] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.textEdit_8.setText(option_A_text) cls.__ui_mainwindow.textEdit_9.setText(option_B_text) cls.__ui_mainwindow.textEdit_10.setText(option_C_text) cls.__ui_mainwindow.textEdit_11.setText(option_D_text) cls.__ui_mainwindow.textEdit_20.setText(option_E_text) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) if (correct_answers.count("A") == 1): cls.__ui_mainwindow.radioButton_6.setChecked(True) if (correct_answers.count("B") == 1): cls.__ui_mainwindow.radioButton_7.setChecked(True) if (correct_answers.count("C") == 1): cls.__ui_mainwindow.radioButton_8.setChecked(True) if (correct_answers.count("D") == 1): cls.__ui_mainwindow.radioButton_9.setChecked(True) if (correct_answers.count("E") == 1): cls.__ui_mainwindow.radioButton_10.setChecked(True) @classmethod def load_essay_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.radioButton_6.setDisabled(True) cls.__ui_mainwindow.radioButton_7.setDisabled(True) cls.__ui_mainwindow.radioButton_8.setDisabled(True) cls.__ui_mainwindow.radioButton_9.setDisabled(True) cls.__ui_mainwindow.radioButton_10.setDisabled(True) cls.__ui_mainwindow.textEdit_8.setDisabled(True) cls.__ui_mainwindow.textEdit_9.setDisabled(True) cls.__ui_mainwindow.textEdit_10.setDisabled(True) cls.__ui_mainwindow.textEdit_11.setDisabled(True) cls.__ui_mainwindow.textEdit_20.setDisabled(True) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) @classmethod def display_question_id_invalid_to_load_message(cls): cls.__ui_mainwindow.label_12.setText("Invalid Question ID To Load") @classmethod def display_modification_success_message(cls): cls.__ui_mainwindow.label_57.setText("Modification Success") @classmethod def display_invalid_school_class_id_message(cls): cls.__ui_mainwindow.label_14.setText("Invalid School Class ID") cls.__ui_mainwindow.tableWidget_15.clear() @classmethod def get_question_type_to_modify(cls): question_type_text = cls.__ui_mainwindow.label_47.text() if (question_type_text == "Question Type: Single Answer"): return "Single Answer" elif (question_type_text == "Question Type: Multiple Answers"): return "Multiple Answers" elif (question_type_text == "Question Type: Essay"): return "Essay" @classmethod def get_single_answer_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() points = int(cls.__ui_mainwindow.lineEdit_28.text()) year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) question_tag = cls.__ui_mainwindow.lineEdit_8.text() question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText() correct_answer = cls.get_single_correct_answer_to_modify() if (correct_answer == None): return None return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer) @classmethod def get_multiple_answers_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() points = int(cls.__ui_mainwindow.lineEdit_28.text()) year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) question_tag = cls.__ui_mainwindow.lineEdit_8.text() question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText() correct_answers = cls.get_multiple_correct_answers_to_modify() if (correct_answers == None): return None return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers) @classmethod def get_essay_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() try: points = int(cls.__ui_mainwindow.lineEdit_28.text()) except: return None try: year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) except: return None question_tag = cls.__ui_mainwindow.lineEdit_8.text() if (question_tag == ""): return None question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() if (question_body == ""): return None return (question_pk, question_type, points, year_level, question_tag, question_body) @classmethod def get_question_id_to_modify(cls): question_id_text = cls.__ui_mainwindow.label_45.text() question_id_text_split = question_id_text.split() question_id = int(question_id_text_split.pop()) return question_id @classmethod def get_single_correct_answer_to_modify(cls): correct_answer = "" if (cls.__ui_mainwindow.radioButton_6.isChecked()): correct_answer = correct_answer + "A" if (cls.__ui_mainwindow.radioButton_7.isChecked()): correct_answer = correct_answer + "B" if (cls.__ui_mainwindow.radioButton_8.isChecked()): correct_answer = correct_answer + "C" if (cls.__ui_mainwindow.radioButton_9.isChecked()): correct_answer = correct_answer + "D" if (cls.__ui_mainwindow.radioButton_10.isChecked()): correct_answer = correct_answer + "E" if (len(correct_answer) == 0): return None if (len(correct_answer) > 1): return None return correct_answer @classmethod def get_multiple_correct_answers_to_modify(cls): correct_answers = "" if (cls.__ui_mainwindow.radioButton_6.isChecked()): correct_answers = correct_answers + "A" if (cls.__ui_mainwindow.radioButton_7.isChecked()): correct_answers = correct_answers + "B" if (cls.__ui_mainwindow.radioButton_8.isChecked()): correct_answers = correct_answers + "C" if (cls.__ui_mainwindow.radioButton_9.isChecked()): correct_answers = correct_answers + "D" if (cls.__ui_mainwindow.radioButton_10.isChecked()): correct_answers = correct_answers + "E" if (len(correct_answers) == 0): return None if (len(correct_answers) > 4): return None return correct_answers @classmethod def get_school_class_id_to_view_students(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def display_school_class_details(cls, school_class_details): cls.__ui_mainwindow.tableWidget_15.clear() row = 0 col = 0 for (student, ) in school_class_details: student_item = QTableWidgetItem(student) cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item) if (col >= 1): col = 0 row += 1 else: col += 1 @classmethod def refresh_view_school_class_details_page(cls): cls.__ui_mainwindow.label_14.clear() @classmethod def get_number_of_questions_in_current_exam(cls): number_of_questions = 0 row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None): number_of_questions += 1 row += 1 return number_of_questions @classmethod def get_number_of_school_classes_in_current_exam(cls): number_of_school_classes = 0 row = 0 col = 0 for counter in range(5): if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None): number_of_school_classes += 1 row += 1 return number_of_school_classes @classmethod def display_number_of_questions_full_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Questions Are Full In Current Exam") @classmethod def display_number_of_school_classes_full_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Classes Are Full In Current Exam") @classmethod def display_no_question_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("No Question In Current Exam") @classmethod def display_no_school_class_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("No School Class In Current Exam") @classmethod def display_question_id_already_added_to_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Already Added To Current Exam") @classmethod def display_school_class_id_already_added_to_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Class ID Already Added To Current Exam") @classmethod def display_question_id_invalid_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Invalid") @classmethod def display_school_class_id_invalid_message(cls): cls.__ui_mainwindow.label_17.setText("School CLass ID Invalid") @classmethod def display_question_id_not_already_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Not Aleady In Current Exam") @classmethod def display_school_class_id_not_already_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Class ID Not Aleady In Current Exam") @classmethod def display_create_exam_success_message(cls): cls.__ui_mainwindow.label_17.setText("Create Exam Success") @classmethod def refresh_mark_exam_drop_box(cls): cls.__ui_mainwindow.tableWidget_19.clear() @classmethod def get_question_id_to_add_to_exam(cls): question_id_text = cls.__ui_mainwindow.lineEdit_10.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def get_school_class_id_to_add_to_exam(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def get_question_id_to_remove_from_exam(cls): question_id_text = cls.__ui_mainwindow.lineEdit_12.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def get_school_class_id_to_remove_from_exam(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def add_question_id_to_current_exam(cls, question_id): row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None): question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item) cls.__ui_mainwindow.lineEdit_10.clear() cls.__ui_mainwindow.label_17.clear() return row += 1 @classmethod def add_school_class_id_to_current_exam(cls, school_class_id): row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None): school_class_text = "CLass " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item) cls.__ui_mainwindow.lineEdit_11.clear() cls.__ui_mainwindow.label_17.clear() return row += 1 @classmethod def remove_question_id_from_current_exam(cls, question_id): col = 0 for row in range(10): question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col) if (question_item != None): question_text = question_item.text() question_text_split = question_text.split(" ") question_id_in_exam = int(question_text_split.pop()) if (question_id_in_exam == question_id): cls.__ui_mainwindow.tableWidget_3.takeItem(row, col) cls.__ui_mainwindow.lineEdit_12.clear() cls.__ui_mainwindow.label_17.clear() return @classmethod def remove_school_class_id_from_current_exam(cls, school_class_id): col = 0 for row in range(5): school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col) if (school_class_item != None): school_class_text = school_class_item.text() school_class_text_split = school_class_text.split(" ") school_class_id_in_exam = int(school_class_text_split.pop()) if (school_class_id_in_exam == school_class_id): cls.__ui_mainwindow.tableWidget_4.takeItem(row, col) cls.__ui_mainwindow.lineEdit_13.clear() cls.__ui_mainwindow.label_17.clear() return @classmethod def is_question_id_already_added_to_current_exam(cls, question_id): string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam() list_of_question_ids = string_of_question_ids_in_current_exam.split(" ") return list_of_question_ids.count(str(question_id)) == 1 @classmethod def is_school_class_id_already_added_to_current_exam(cls, school_class_id): string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam() list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(" ") return list_of_school_classes_ids.count(str(school_class_id)) == 1 @classmethod def get_string_of_question_ids_in_current_exam(cls): string_of_question_ids = "" col = 0 for row in range(10): question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col) if (question_item != None): question_text = question_item.text() question_text_split = question_text.split(" ") question_id = question_text_split.pop() string_of_question_ids = string_of_question_ids + question_id + " " return string_of_question_ids.rstrip() @classmethod def get_string_of_school_classes_ids_in_current_exam(cls): string_of_school_classes_ids = "" col = 0 for row in range(10): school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col) if (school_class_item != None): school_class_text = school_class_item.text() school_class_text_split = school_class_text.split(" ") school_class_id = school_class_text_split.pop() string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + " " return string_of_school_classes_ids.rstrip() @classmethod def get_exam_id_to_mark(cls): exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0) exam_text = exam_item.text() exam_text_split = exam_text.split(" ") exam_id_text = exam_text_split.pop() return int(exam_id_text) @classmethod def display_exam_id_on_marking_exam_page(cls, exam_id): cls.__ui_mainwindow.label_49.setText("Exam ID: " + str(exam_id)) @classmethod def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list): cls.__ui_mainwindow.tableWidget_6.clear() row = 0 col = 0 for student_name in students_names_list: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item) if (col >= 4): row += 1 col = 0 else: col += 1 @classmethod def get_student_name_to_mark_answers(cls): student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0) student_name = student_item.text() return student_name @classmethod def get_exam_id_to_mark_student_answers(cls): exam_id_text = cls.__ui_mainwindow.label_49.text() exam_id_text_split = exam_id_text.split(" ") exam_id = exam_id_text_split.pop() return int(exam_id) @classmethod def display_exam_id_on_mark_student_answers_page(cls, exam_id): exam_id_text = "Exam ID: " + str(exam_id) cls.__ui_mainwindow.label_62.setText(exam_id_text) @classmethod def display_student_id_on_mark_student_answers_page(cls, student_id): student_id_text = "Student ID: " + str(student_id) cls.__ui_mainwindow.label_63.setText(student_id_text) @classmethod def display_student_name_on_mark_student_answers_page(cls,student_name): student_name_text = "Student Name: " + str(student_name) cls.__ui_mainwindow.label_50.setText(student_name_text) @classmethod def display_questions_ready_to_be_marked(cls, questions_ids_tuple): cls.__ui_mainwindow.tableWidget_25.clear() row = 0 col = 0 for (question_id,) in questions_ids_tuple: question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item) row += 1 @classmethod def get_question_id_to_mark(cls): question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0) if (question_item == None): return None question_id_text = question_item.text() question_id_text_list = question_id_text.split(" ") question_id = question_id_text_list.pop() return int(question_id) @classmethod def get_exam_id_on_marking_question_page(cls): exam_id_text = cls.__ui_mainwindow.label_62.text() exam_id_text_list = exam_id_text.split(" ") exam_id = exam_id_text_list.pop() return int(exam_id) @classmethod def get_student_id_on_marking_question_page(cls): student_id_text = cls.__ui_mainwindow.label_63.text() student_id_text_list = student_id_text.split(" ") student_id = student_id_text_list.pop() return int(student_id) @classmethod def setup_essay_question_ui_dialog_to_mark(cls, question_details): question_body = question_details[0] student_answer = question_details[1] available_points = question_details[2] cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_MarkingEssayQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label_2.setText(question_body) cls.__ui_dialog.label_3.setText(student_answer) cls.__ui_dialog.label_4.setText("Total Available Points: " + str(available_points)) cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) cls.__dialog.show() return cls.__ui_dialog @classmethod def get_essay_question_marked_points(cls): points_text = cls.__ui_dialog.lineEdit.text() return int(points_text) @classmethod def refresh_drop_question_to_mark_box(cls): cls.__ui_mainwindow.tableWidget_26.clear() @classmethod def refresh_mark_student_questions_answers_page(cls): cls.__ui_mainwindow.label_62.clear() cls.__ui_mainwindow.label_63.clear() cls.__ui_mainwindow.label_50.clear() @classmethod def display_no_more_questions_to_mark_message(cls): cls.__ui_mainwindow.label_66.setText("No More Questions To Mark") @classmethod def display_marked_exams(cls, marked_exams_ids): cls.__ui_mainwindow.tableWidget_18.clear() row = 0 col = 0 for (exam_id,) in marked_exams_ids: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item) if (col >= 4): row += 1 col = 0 else: col += 1 @classmethod def display_no_question_selected_to_mark_message(cls): cls.__ui_mainwindow.label_66.setText("No Question Selected To Mark") @classmethod def refresh_drop_student_to_mark_questions_box(cls): cls.__ui_mainwindow.tableWidget_19.clear() @classmethod def get_exam_id_to_release_result(cls): exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0) if (exam_item == None): return None exam_id_text = exam_item.text() exam_id_text_list = exam_id_text.split(" ") exam_id = exam_id_text_list.pop() return int(exam_id) @classmethod def display_result_released_exams(cls, result_released_exams_ids): cls.__ui_mainwindow.tableWidget_11.clear() row = 0 col = 0 for (exam_id,) in result_released_exams_ids: exam_text = "Exam " + str(exam_id) + " Result" exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item) if (col >= 9): row += 1 col = 0 else: col += 1 @classmethod def refresh_drop_exam_to_release_result_box(cls): cls.__ui_mainwindow.tableWidget_21.clear() @classmethod def display_exam_results(cls, exam_results_ids): cls.__ui_mainwindow.tableWidget_11.clear() row = 0 col = 0 for (exam_result_id, ) in exam_results_ids: exam_result_text = "Exam " + str(exam_result_id) + " Result" exam_result_item = QTableWidgetItem(exam_result_text) cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item) if (col >= 9): row += 1 col = 0 else: col += 1 @classmethod def get_exam_result_id_to_load_details(cls): exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text() return int(exam_result_id_text) @classmethod def display_school_classes_to_view_exam_result_details(cls, school_classes_ids): school_classes_ids_list = cls.make_string_to_list(school_classes_ids) cls.__ui_mainwindow.tableWidget_12.clear() row = 0 col = 0 for school_class_id in school_classes_ids_list: school_class_text = "Class " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item) row += 1 @classmethod def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id): cls.__ui_mainwindow.label_33.setText("Exam Result ID: " + str(exam_result_id)) @classmethod def get_school_class_id_to_view_exam_result(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text() try: school_class_id = int(school_class_id_text) except: return None return school_class_id @classmethod def display_students_full_names_to_view_exam_result(cls, students_full_names): cls.__ui_mainwindow.tableWidget_13.clear() row = 0 col = 0 for (student_full_name, ) in students_full_names: student_item = QTableWidgetItem(student_full_name) cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item) row += 1 @classmethod def get_student_full_name_to_view_exam_result(cls): student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0) student_name_text = student_item.text() return student_name_text @classmethod def get_exam_result_id_on_view_exam_result_page(cls): exam_result_id_text = cls.__ui_mainwindow.label_33.text() exam_result_id_text_list = exam_result_id_text.split(" ") exam_result_id = exam_result_id_text_list.pop() try: exam_result_id_int = int(exam_result_id) return exam_result_id_int except: return None @classmethod def display_student_exam_result_details(cls, exam_result_details): student_id = exam_result_details[0] student_full_name = exam_result_details[1] date_of_birth = exam_result_details[2] school_class_id = exam_result_details[3] exam_id = exam_result_details[4] total_available_points = exam_result_details[5] total_points_gained = exam_result_details[6] average_percentage_mark = exam_result_details[7] cls.__ui_mainwindow.label_58.setText(str(student_id)) cls.__ui_mainwindow.label_72.setText(str(student_full_name)) cls.__ui_mainwindow.label_75.setText(str(date_of_birth)) cls.__ui_mainwindow.label_76.setText(str(school_class_id)) cls.__ui_mainwindow.label_77.setText(str(exam_id)) cls.__ui_mainwindow.label_78.setText(str(total_available_points)) cls.__ui_mainwindow.label_79.setText(str(total_points_gained)) cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + " %") @classmethod def get_exam_id_to_view_details(cls): exam_id_text = cls.__ui_mainwindow.lineEdit_14.text() if (exam_id_text == ""): return None try: exam_id = int(exam_id_text) return exam_id except: return None @classmethod def diaplay_exam_id_on_view_exam_details_page(cls, exam_id): cls.__ui_mainwindow.label_18.setText("Exam ID: " + str(exam_id)) @classmethod def display_questions_on_view_exam_details_page(cls, questions_ids): cls.__ui_mainwindow.tableWidget_7.clear() questions_ids_list = cls.make_string_to_list(questions_ids) row = 0 col = 0 for question_id in questions_ids_list: question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item) row += 1 @classmethod def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_first_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_27.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item) row += 1 @classmethod def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_67.setText("CLass " + str(school_class_id)) @classmethod def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_second_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_28.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item) row += 1 @classmethod def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_68.setText("CLass " + str(school_class_id)) @classmethod def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_third_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_29.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item) row += 1 @classmethod def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_69.setText("CLass " + str(school_class_id)) @classmethod def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_30.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item) row += 1 @classmethod def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_70.setText("CLass " + str(school_class_id)) @classmethod def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_31.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item) row += 1 @classmethod def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_71.setText("CLass " + str(school_class_id)) @classmethod def make_string_to_list(cls, any_string): any_string = str(any_string) any_list = any_string.split(" ") return any_list @classmethod def refresh_drop_student_to_view_exam_result_details_box(cls): cls.__ui_mainwindow.tableWidget_22.clear() @classmethod def display_exam_result_id_invalid_message(cls): cls.__ui_mainwindow.label_32.setText("Exam Result ID Invalid") @classmethod def refresh_load_exam_result_details_page(cls): cls.__ui_mainwindow.label_33.clear() cls.__ui_mainwindow.tableWidget_12.clear() cls.__ui_mainwindow.lineEdit_23.clear() cls.__ui_mainwindow.tableWidget_13.clear() cls.__ui_mainwindow.tableWidget_22.clear() cls.__ui_mainwindow.label_58.clear() cls.__ui_mainwindow.label_72.clear() cls.__ui_mainwindow.label_75.clear() cls.__ui_mainwindow.label_76.clear() cls.__ui_mainwindow.label_77.clear() cls.__ui_mainwindow.label_78.clear() cls.__ui_mainwindow.label_79.clear() cls.__ui_mainwindow.label_80.clear() @classmethod def refresh_exam_result_id_validity_error_message(cls): cls.__ui_mainwindow.label_32.clear() @classmethod def display_school_class_id_invalid_to_view_result_message(cls): cls.__ui_mainwindow.label_81.setText("School Class ID Invalid To View") @classmethod def refresh_school_class_details_table_on_view_exam_result_page(cls): cls.__ui_mainwindow.tableWidget_13.clear() @classmethod def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls): cls.__ui_mainwindow.label_81.clear() @classmethod def refresh_student_exam_result_details(cls): cls.__ui_mainwindow.label_58.clear() cls.__ui_mainwindow.label_72.clear() cls.__ui_mainwindow.label_75.clear() cls.__ui_mainwindow.label_76.clear() cls.__ui_mainwindow.label_77.clear() cls.__ui_mainwindow.label_78.clear() cls.__ui_mainwindow.label_79.clear() cls.__ui_mainwindow.label_80.clear() @classmethod def display_no_exam_result_id_selected_message(cls): cls.__ui_mainwindow.label_81.setText("No Exam Result ID Selected") @classmethod def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.lineEdit_23.clear() @classmethod def refresh_view_exam_details_by_id_page(cls): cls.__ui_mainwindow.label_18.setText("Exam ID : ") cls.__ui_mainwindow.tableWidget_7.clear() cls.__ui_mainwindow.label_67.clear() cls.__ui_mainwindow.label_68.clear() cls.__ui_mainwindow.label_69.clear() cls.__ui_mainwindow.label_70.clear() cls.__ui_mainwindow.label_71.clear() cls.__ui_mainwindow.tableWidget_27.clear() cls.__ui_mainwindow.tableWidget_28.clear() cls.__ui_mainwindow.tableWidget_29.clear() cls.__ui_mainwindow.tableWidget_30.clear() cls.__ui_mainwindow.tableWidget_31.clear() @classmethod def refresh_students_table_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.tableWidget_13.clear() @classmethod def refresh_school_classes_table_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.tableWidget_12.clear() def __str__(self): return ("This is TeacherGUI Object")
normal
{ "blob_id": "98f234ca0cbec419466de0504fd8d5c68fd07627", "index": 9609, "step-1": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-4": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.checkBox.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.checkBox_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.checkBox_3.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.checkBox_4.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.checkBox_5.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 4:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answer = correct_answer + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answer = correct_answer + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answer = correct_answer + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answer = correct_answer + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answer = correct_answer + 'E'\n if len(correct_answer) == 0:\n return None\n if len(correct_answer) > 1:\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) != None:\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText('Exam ID: ' + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0, 0)\n if question_item == None:\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(' ')\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText('Total Available Points: ' + str(\n available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if exam_id_text == '':\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-5": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox\nfrom PyQt5.QtCore import QDate, QTime, QDateTime, Qt\n\n\nfrom OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog\nfrom OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog\n\n\nclass TeacherGUI():\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for (school_class_id, ) in school_classes:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item)\n if (col >= 4):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for (exam_id, ) in all_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if (col >= 9):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for (exam_id, ) in not_completed_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if (col >= 6):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for (exam_id, ) in ready_to_be_marked_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if (col >= 3):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(\"A \" + option_A_text)\n cls.__ui_dialog.label_4.setText(\"B \" + option_B_text)\n cls.__ui_dialog.label_5.setText(\"C \" + option_C_text)\n cls.__ui_dialog.label_6.setText(\"D \" + option_D_text)\n cls.__ui_dialog.label_7.setText(\"E \" + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if (question_body == \"\"):\n cls.__ui_dialog.label.setText(\"Question Body\")\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.radioButton.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.radioButton_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.radioButton_5.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.radioButton_3.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.radioButton_4.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 1):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.checkBox.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.checkBox_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.checkBox_3.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.checkBox_4.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.checkBox_5.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 4):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if (question_body == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if (phrase_tag_text == \"\"):\n return None\n return (question_body, year_level, phrase_tag_text)\n\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = \"Question \" + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if (col >= 7):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\"Create Single Answer Question Success\")\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\"Invalid Single Answer Question Creation\")\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\"Create Multiple Answers Question Success\")\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\"Invalid Multiple Answers Question Creation\")\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText(\"Invalid Essay Question Creation\")\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText(\"Create Essay Question Success\")\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Invalid Modification\")\n\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n\n @classmethod\n def refresh_create_multiple_answers_question_page(cls):\n cls.__ui_mainwindow.textEdit_14.clear()\n cls.__ui_mainwindow.textEdit_13.clear()\n cls.__ui_mainwindow.textEdit_15.clear()\n cls.__ui_mainwindow.textEdit_16.clear()\n cls.__ui_mainwindow.textEdit_17.clear()\n cls.__ui_mainwindow.textEdit_18.clear()\n cls.__ui_mainwindow.lineEdit_25.clear()\n cls.__ui_mainwindow.lineEdit_7.clear()\n cls.__ui_mainwindow.checkBox.setChecked(False)\n cls.__ui_mainwindow.checkBox_2.setChecked(False)\n cls.__ui_mainwindow.checkBox_3.setChecked(False)\n cls.__ui_mainwindow.checkBox_4.setChecked(False)\n cls.__ui_mainwindow.checkBox_5.setChecked(False)\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \")\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \")\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answer == \"A\"):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif (correct_answer == \"B\"):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif (correct_answer == \"C\"):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif (correct_answer == \"D\"):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif (correct_answer == \"E\"):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answers.count(\"A\") == 1):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if (correct_answers.count(\"B\") == 1):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if (correct_answers.count(\"C\") == 1):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if (correct_answers.count(\"D\") == 1):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if (correct_answers.count(\"E\") == 1):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText(\"Invalid Question ID To Load\")\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Modification Success\")\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText(\"Invalid School Class ID\")\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if (question_type_text == \"Question Type: Single Answer\"):\n return \"Single Answer\"\n elif (question_type_text == \"Question Type: Multiple Answers\"):\n return \"Multiple Answers\"\n elif (question_type_text == \"Question Type: Essay\"):\n return \"Essay\"\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if (correct_answer == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if (correct_answers == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if (question_tag == \"\"):\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if (question_body == \"\"):\n return None\n return (question_pk, question_type, points, year_level, question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answer = correct_answer + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answer = correct_answer + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answer = correct_answer + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answer = correct_answer + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answer = correct_answer + \"E\"\n if (len(correct_answer) == 0):\n return None\n if (len(correct_answer) > 1):\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answers = correct_answers + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answers = correct_answers + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answers = correct_answers + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answers = correct_answers + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answers = correct_answers + \"E\"\n if (len(correct_answers) == 0):\n return None\n if (len(correct_answers) > 4):\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for (student, ) in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if (col >= 1):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None):\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None):\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Questions Are Full In Current Exam\")\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Classes Are Full In Current Exam\")\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No Question In Current Exam\")\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No School Class In Current Exam\")\n\n @classmethod\n def display_question_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Already Added To Current Exam\")\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Already Added To Current Exam\")\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Invalid\")\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School CLass ID Invalid\")\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Create Exam Success\")\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None):\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None):\n school_class_text = \"CLass \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id_in_exam = int(question_text_split.pop())\n if (question_id_in_exam == question_id):\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id_in_exam = int(school_class_text_split.pop())\n if (school_class_id_in_exam == school_class_id):\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def is_question_id_already_added_to_current_exam(cls, question_id):\n string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam()\n list_of_question_ids = string_of_question_ids_in_current_exam.split(\" \")\n return list_of_question_ids.count(str(question_id)) == 1\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam()\n list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(\" \")\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = \"\"\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id = question_text_split.pop()\n string_of_question_ids = string_of_question_ids + question_id + \" \"\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = \"\"\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + \" \"\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(\" \")\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(\" \")\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n\n @classmethod\n def display_exam_id_on_mark_student_answers_page(cls, exam_id):\n exam_id_text = \"Exam ID: \" + str(exam_id)\n cls.__ui_mainwindow.label_62.setText(exam_id_text)\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = \"Student ID: \" + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls,student_name):\n student_name_text = \"Student Name: \" + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for (question_id,) in questions_ids_tuple:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0)\n if (question_item == None):\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(\" \")\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(\" \")\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText(\"Total Available Points: \" + str(available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No More Questions To Mark\")\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for (exam_id,) in marked_exams_ids:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No Question Selected To Mark\")\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0)\n if (exam_item == None):\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_id,) in result_released_exams_ids:\n exam_text = \"Exam \" + str(exam_id) + \" Result\"\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_result_id, ) in exam_results_ids:\n exam_result_text = \"Exam \" + str(exam_result_id) + \" Result\"\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n\n @classmethod\n def display_school_classes_to_view_exam_result_details(cls, school_classes_ids):\n school_classes_ids_list = cls.make_string_to_list(school_classes_ids)\n cls.__ui_mainwindow.tableWidget_12.clear()\n row = 0\n col = 0\n for school_class_id in school_classes_ids_list:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item)\n row += 1\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id):\n cls.__ui_mainwindow.label_33.setText(\"Exam Result ID: \" + str(exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls, students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for (student_full_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(\" \")\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + \" %\")\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if (exam_id_text == \"\"):\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n\n @classmethod\n def diaplay_exam_id_on_view_exam_details_page(cls, exam_id):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_67.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_68.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_69.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_70.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_71.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(\" \")\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText(\"Exam Result ID Invalid\")\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"School Class ID Invalid To View\")\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"No Exam Result ID Selected\")\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID : \")\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_classes_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_12.clear()\n\n\n\n\n\n def __str__(self):\n return (\"This is TeacherGUI Object\")", "step-ids": [ 100, 103, 113, 122, 132 ] }
[ 100, 103, 113, 122, 132 ]
from typing import * class Solution: def isMonotonic(self, A: List[int]) ->bool: flag = 0 for i in range(1, len(A)): diff = A[i] - A[i - 1] if diff * flag < 0: return False if flag == 0: flag = diff return True sl = Solution() inp = [1, 2, 2, 2, 1] print(sl.isMonotonic(inp))
normal
{ "blob_id": "a55d1286485e66a64aa78259ad1b1922c5c4c831", "index": 4385, "step-1": "<mask token>\n\n\nclass Solution:\n\n def isMonotonic(self, A: List[int]) ->bool:\n flag = 0\n for i in range(1, len(A)):\n diff = A[i] - A[i - 1]\n if diff * flag < 0:\n return False\n if flag == 0:\n flag = diff\n return True\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def isMonotonic(self, A: List[int]) ->bool:\n flag = 0\n for i in range(1, len(A)):\n diff = A[i] - A[i - 1]\n if diff * flag < 0:\n return False\n if flag == 0:\n flag = diff\n return True\n\n\n<mask token>\nprint(sl.isMonotonic(inp))\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def isMonotonic(self, A: List[int]) ->bool:\n flag = 0\n for i in range(1, len(A)):\n diff = A[i] - A[i - 1]\n if diff * flag < 0:\n return False\n if flag == 0:\n flag = diff\n return True\n\n\nsl = Solution()\ninp = [1, 2, 2, 2, 1]\nprint(sl.isMonotonic(inp))\n", "step-4": "from typing import *\n\n\nclass Solution:\n\n def isMonotonic(self, A: List[int]) ->bool:\n flag = 0\n for i in range(1, len(A)):\n diff = A[i] - A[i - 1]\n if diff * flag < 0:\n return False\n if flag == 0:\n flag = diff\n return True\n\n\nsl = Solution()\ninp = [1, 2, 2, 2, 1]\nprint(sl.isMonotonic(inp))\n", "step-5": null, "step-ids": [ 2, 3, 4, 5 ] }
[ 2, 3, 4, 5 ]
from import_export.admin import ImportExportMixin from django.contrib import admin from import_export import resources, widgets, fields from .models import Addgroup,Addsystemname,Zhuanzhebushi,Yewuzerenbumen,czyylx,Zhuanze,Data from import_export import fields, resources from import_export.widgets import ForeignKeyWidget # Register your models here. class DataResource(resources.ModelResource): groupname = fields.Field( widget=widgets.ForeignKeyWidget(Addgroup, 'name')) system_name = fields.Field(column_name='system_name', attribute='system_name', widget=widgets.ForeignKeyWidget(Addsystemname, 'name')) I6000 = fields.Field(column_name='I6000', attribute='I6000') class Meta: fields = ('groupname','system_name','I6000') class DataAdmin(ImportExportMixin,admin.ModelAdmin): list_display = ['groupname','system_name','I6000','xtjslx','bslx','ywbs','ywzrbs','yunxingzhuangtai','url','xtsxsj','xtxxsj','ip','xunijiqunip','date'] resources_class = DataResource admin.site.register(Data,DataAdmin)
normal
{ "blob_id": "016b64a2eb4af3034d54272c878fb917506d330c", "index": 648, "step-1": "<mask token>\n\n\nclass DataResource(resources.ModelResource):\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n fields = 'groupname', 'system_name', 'I6000'\n\n\nclass DataAdmin(ImportExportMixin, admin.ModelAdmin):\n list_display = ['groupname', 'system_name', 'I6000', 'xtjslx', 'bslx',\n 'ywbs', 'ywzrbs', 'yunxingzhuangtai', 'url', 'xtsxsj', 'xtxxsj',\n 'ip', 'xunijiqunip', 'date']\n resources_class = DataResource\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass DataResource(resources.ModelResource):\n groupname = fields.Field(widget=widgets.ForeignKeyWidget(Addgroup, 'name'))\n system_name = fields.Field(column_name='system_name', attribute=\n 'system_name', widget=widgets.ForeignKeyWidget(Addsystemname, 'name'))\n I6000 = fields.Field(column_name='I6000', attribute='I6000')\n\n\n class Meta:\n fields = 'groupname', 'system_name', 'I6000'\n\n\nclass DataAdmin(ImportExportMixin, admin.ModelAdmin):\n list_display = ['groupname', 'system_name', 'I6000', 'xtjslx', 'bslx',\n 'ywbs', 'ywzrbs', 'yunxingzhuangtai', 'url', 'xtsxsj', 'xtxxsj',\n 'ip', 'xunijiqunip', 'date']\n resources_class = DataResource\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass DataResource(resources.ModelResource):\n groupname = fields.Field(widget=widgets.ForeignKeyWidget(Addgroup, 'name'))\n system_name = fields.Field(column_name='system_name', attribute=\n 'system_name', widget=widgets.ForeignKeyWidget(Addsystemname, 'name'))\n I6000 = fields.Field(column_name='I6000', attribute='I6000')\n\n\n class Meta:\n fields = 'groupname', 'system_name', 'I6000'\n\n\nclass DataAdmin(ImportExportMixin, admin.ModelAdmin):\n list_display = ['groupname', 'system_name', 'I6000', 'xtjslx', 'bslx',\n 'ywbs', 'ywzrbs', 'yunxingzhuangtai', 'url', 'xtsxsj', 'xtxxsj',\n 'ip', 'xunijiqunip', 'date']\n resources_class = DataResource\n\n\nadmin.site.register(Data, DataAdmin)\n", "step-4": "from import_export.admin import ImportExportMixin\nfrom django.contrib import admin\nfrom import_export import resources, widgets, fields\nfrom .models import Addgroup, Addsystemname, Zhuanzhebushi, Yewuzerenbumen, czyylx, Zhuanze, Data\nfrom import_export import fields, resources\nfrom import_export.widgets import ForeignKeyWidget\n\n\nclass DataResource(resources.ModelResource):\n groupname = fields.Field(widget=widgets.ForeignKeyWidget(Addgroup, 'name'))\n system_name = fields.Field(column_name='system_name', attribute=\n 'system_name', widget=widgets.ForeignKeyWidget(Addsystemname, 'name'))\n I6000 = fields.Field(column_name='I6000', attribute='I6000')\n\n\n class Meta:\n fields = 'groupname', 'system_name', 'I6000'\n\n\nclass DataAdmin(ImportExportMixin, admin.ModelAdmin):\n list_display = ['groupname', 'system_name', 'I6000', 'xtjslx', 'bslx',\n 'ywbs', 'ywzrbs', 'yunxingzhuangtai', 'url', 'xtsxsj', 'xtxxsj',\n 'ip', 'xunijiqunip', 'date']\n resources_class = DataResource\n\n\nadmin.site.register(Data, DataAdmin)\n", "step-5": "from import_export.admin import ImportExportMixin\nfrom django.contrib import admin\nfrom import_export import resources, widgets, fields\nfrom .models import Addgroup,Addsystemname,Zhuanzhebushi,Yewuzerenbumen,czyylx,Zhuanze,Data\nfrom import_export import fields, resources\nfrom import_export.widgets import ForeignKeyWidget\n# Register your models here.\n\nclass DataResource(resources.ModelResource):\n groupname = fields.Field( widget=widgets.ForeignKeyWidget(Addgroup, 'name'))\n system_name = fields.Field(column_name='system_name', attribute='system_name', widget=widgets.ForeignKeyWidget(Addsystemname, 'name'))\n I6000 = fields.Field(column_name='I6000', attribute='I6000')\n class Meta:\n fields = ('groupname','system_name','I6000')\n\nclass DataAdmin(ImportExportMixin,admin.ModelAdmin):\n list_display = ['groupname','system_name','I6000','xtjslx','bslx','ywbs','ywzrbs','yunxingzhuangtai','url','xtsxsj','xtxxsj','ip','xunijiqunip','date']\n resources_class = DataResource\n\n\nadmin.site.register(Data,DataAdmin)", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# Generated by Django 2.2.13 on 2021-08-11 15:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("notifications", "0011_auto_20171229_1747"), ] operations = [ migrations.AlterField( model_name="notification", name="date", field=models.DateTimeField(auto_now=True, verbose_name="Dato"), ), migrations.AlterField( model_name="notification", name="priority", field=models.PositiveIntegerField( choices=[(0, "Low"), (1, "Medium"), (2, "High")], default=1, verbose_name="priority", ), ), migrations.AlterField( model_name="notification", name="sent_mail", field=models.BooleanField(default=False, verbose_name="sent mail"), ), ]
normal
{ "blob_id": "fa045ccd4e54332f6c05bf64e3318e05b8123a10", "index": 3317, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('notifications', '0011_auto_20171229_1747')]\n operations = [migrations.AlterField(model_name='notification', name=\n 'date', field=models.DateTimeField(auto_now=True, verbose_name=\n 'Dato')), migrations.AlterField(model_name='notification', name=\n 'priority', field=models.PositiveIntegerField(choices=[(0, 'Low'),\n (1, 'Medium'), (2, 'High')], default=1, verbose_name='priority')),\n migrations.AlterField(model_name='notification', name='sent_mail',\n field=models.BooleanField(default=False, verbose_name='sent mail'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('notifications', '0011_auto_20171229_1747')]\n operations = [migrations.AlterField(model_name='notification', name=\n 'date', field=models.DateTimeField(auto_now=True, verbose_name=\n 'Dato')), migrations.AlterField(model_name='notification', name=\n 'priority', field=models.PositiveIntegerField(choices=[(0, 'Low'),\n (1, 'Medium'), (2, 'High')], default=1, verbose_name='priority')),\n migrations.AlterField(model_name='notification', name='sent_mail',\n field=models.BooleanField(default=False, verbose_name='sent mail'))]\n", "step-5": "# Generated by Django 2.2.13 on 2021-08-11 15:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n (\"notifications\", \"0011_auto_20171229_1747\"),\n ]\n\n operations = [\n migrations.AlterField(\n model_name=\"notification\",\n name=\"date\",\n field=models.DateTimeField(auto_now=True, verbose_name=\"Dato\"),\n ),\n migrations.AlterField(\n model_name=\"notification\",\n name=\"priority\",\n field=models.PositiveIntegerField(\n choices=[(0, \"Low\"), (1, \"Medium\"), (2, \"High\")],\n default=1,\n verbose_name=\"priority\",\n ),\n ),\n migrations.AlterField(\n model_name=\"notification\",\n name=\"sent_mail\",\n field=models.BooleanField(default=False, verbose_name=\"sent mail\"),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python #-*- coding: utf-8 -*- import pygtk pygtk.require("2.0") import gtk from testarMsg import * class tgApp(object): def __init__(self): builder = gtk.Builder() builder.add_from_file("../tg.glade") self.window = builder.get_object("window1") self.text_area = builder.get_object("text_entry") self.window.show() self.opcao = "" builder.connect_signals({"gtk_main_quit": gtk.main_quit, "on_button_analisar_clicked": self.analisar_frase, "on_button_clear_clicked": self.clear_text, "on_button_dilma_clicked": self.opcao_dilma, "on_button_copa_clicked": self.opcao_copa, "on_button_palmeiras_clicked": self.opcao_palmeiras, "on_button_fatec_clicked": self.opcao_fatec, "on_sad_show": self.sad_show, }) def analisar_frase(self, widget): """Função: analisar a frase que o usuário""" frase = self.text_area.get_text() if ( frase != ""): frase_proc= normalizar(frase) self.text_area.set_text(frase) if (self.opcao == 'dilma' or self.opcao == 'copa' or self.opcao == 'palmeiras' or self.opcao == 'fatec'): print("Opcao: %s "%self.opcao) featureList = gera_lista_features(self.opcao) lista_feature_fell = get_lista_feature_fell() features_msg = getFeatureVector(frase_proc) training_set = apply_features(extract_features,lista_feature_fell) fell = avaliar_Sentimento(features_msg,training_set) print ("Sentimento: %s "%fell) def clear_text(self, widget): """Função: para apagar o texto na área de texto""" self.text_area.set_text("") def opcao_dilma(self, widget): """Função: para definir a opcao Dilma""" self.opcao="dilma" def opcao_copa(self, widget): """Função: para definir a opcao Copa""" self.opcao="copa" def opcao_palmeiras(self, widget): """Função: para definir a opcao Palmeiras""" self.opcao="palmeiras" def opcao_fatec(self, widget): """Função: para definir a opcao Fatec""" self.opcao="fatec" def sad_show(self,widget): """Função: para definir se imagem Sad ira aparecer""" self.visible=True if __name__ == "__main__": app = tgApp() gtk.main()
normal
{ "blob_id": "6b6fac3bfb1b1478dd491fc4dd9c45a19aeb7bd8", "index": 6102, "step-1": "<mask token>\n\n\nclass tgApp(object):\n\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file('../tg.glade')\n self.window = builder.get_object('window1')\n self.text_area = builder.get_object('text_entry')\n self.window.show()\n self.opcao = ''\n builder.connect_signals({'gtk_main_quit': gtk.main_quit,\n 'on_button_analisar_clicked': self.analisar_frase,\n 'on_button_clear_clicked': self.clear_text,\n 'on_button_dilma_clicked': self.opcao_dilma,\n 'on_button_copa_clicked': self.opcao_copa,\n 'on_button_palmeiras_clicked': self.opcao_palmeiras,\n 'on_button_fatec_clicked': self.opcao_fatec, 'on_sad_show':\n self.sad_show})\n <mask token>\n\n def clear_text(self, widget):\n \"\"\"Função: para apagar o texto na área de texto\"\"\"\n self.text_area.set_text('')\n\n def opcao_dilma(self, widget):\n \"\"\"Função: para definir a opcao Dilma\"\"\"\n self.opcao = 'dilma'\n\n def opcao_copa(self, widget):\n \"\"\"Função: para definir a opcao Copa\"\"\"\n self.opcao = 'copa'\n <mask token>\n\n def opcao_fatec(self, widget):\n \"\"\"Função: para definir a opcao Fatec\"\"\"\n self.opcao = 'fatec'\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass tgApp(object):\n\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file('../tg.glade')\n self.window = builder.get_object('window1')\n self.text_area = builder.get_object('text_entry')\n self.window.show()\n self.opcao = ''\n builder.connect_signals({'gtk_main_quit': gtk.main_quit,\n 'on_button_analisar_clicked': self.analisar_frase,\n 'on_button_clear_clicked': self.clear_text,\n 'on_button_dilma_clicked': self.opcao_dilma,\n 'on_button_copa_clicked': self.opcao_copa,\n 'on_button_palmeiras_clicked': self.opcao_palmeiras,\n 'on_button_fatec_clicked': self.opcao_fatec, 'on_sad_show':\n self.sad_show})\n <mask token>\n\n def clear_text(self, widget):\n \"\"\"Função: para apagar o texto na área de texto\"\"\"\n self.text_area.set_text('')\n\n def opcao_dilma(self, widget):\n \"\"\"Função: para definir a opcao Dilma\"\"\"\n self.opcao = 'dilma'\n\n def opcao_copa(self, widget):\n \"\"\"Função: para definir a opcao Copa\"\"\"\n self.opcao = 'copa'\n\n def opcao_palmeiras(self, widget):\n \"\"\"Função: para definir a opcao Palmeiras\"\"\"\n self.opcao = 'palmeiras'\n\n def opcao_fatec(self, widget):\n \"\"\"Função: para definir a opcao Fatec\"\"\"\n self.opcao = 'fatec'\n\n def sad_show(self, widget):\n \"\"\"Função: para definir se imagem Sad ira aparecer\"\"\"\n self.visible = True\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass tgApp(object):\n\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file('../tg.glade')\n self.window = builder.get_object('window1')\n self.text_area = builder.get_object('text_entry')\n self.window.show()\n self.opcao = ''\n builder.connect_signals({'gtk_main_quit': gtk.main_quit,\n 'on_button_analisar_clicked': self.analisar_frase,\n 'on_button_clear_clicked': self.clear_text,\n 'on_button_dilma_clicked': self.opcao_dilma,\n 'on_button_copa_clicked': self.opcao_copa,\n 'on_button_palmeiras_clicked': self.opcao_palmeiras,\n 'on_button_fatec_clicked': self.opcao_fatec, 'on_sad_show':\n self.sad_show})\n\n def analisar_frase(self, widget):\n \"\"\"Função: analisar a frase que o usuário\"\"\"\n frase = self.text_area.get_text()\n if frase != '':\n frase_proc = normalizar(frase)\n self.text_area.set_text(frase)\n if (self.opcao == 'dilma' or self.opcao == 'copa' or self.opcao ==\n 'palmeiras' or self.opcao == 'fatec'):\n print('Opcao: %s ' % self.opcao)\n featureList = gera_lista_features(self.opcao)\n lista_feature_fell = get_lista_feature_fell()\n features_msg = getFeatureVector(frase_proc)\n training_set = apply_features(extract_features,\n lista_feature_fell)\n fell = avaliar_Sentimento(features_msg, training_set)\n print('Sentimento: %s ' % fell)\n\n def clear_text(self, widget):\n \"\"\"Função: para apagar o texto na área de texto\"\"\"\n self.text_area.set_text('')\n\n def opcao_dilma(self, widget):\n \"\"\"Função: para definir a opcao Dilma\"\"\"\n self.opcao = 'dilma'\n\n def opcao_copa(self, widget):\n \"\"\"Função: para definir a opcao Copa\"\"\"\n self.opcao = 'copa'\n\n def opcao_palmeiras(self, widget):\n \"\"\"Função: para definir a opcao Palmeiras\"\"\"\n self.opcao = 'palmeiras'\n\n def opcao_fatec(self, widget):\n \"\"\"Função: para definir a opcao Fatec\"\"\"\n self.opcao = 'fatec'\n\n def sad_show(self, widget):\n \"\"\"Função: para definir se imagem Sad ira aparecer\"\"\"\n self.visible = True\n\n\n<mask token>\n", "step-4": "<mask token>\npygtk.require('2.0')\n<mask token>\n\n\nclass tgApp(object):\n\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file('../tg.glade')\n self.window = builder.get_object('window1')\n self.text_area = builder.get_object('text_entry')\n self.window.show()\n self.opcao = ''\n builder.connect_signals({'gtk_main_quit': gtk.main_quit,\n 'on_button_analisar_clicked': self.analisar_frase,\n 'on_button_clear_clicked': self.clear_text,\n 'on_button_dilma_clicked': self.opcao_dilma,\n 'on_button_copa_clicked': self.opcao_copa,\n 'on_button_palmeiras_clicked': self.opcao_palmeiras,\n 'on_button_fatec_clicked': self.opcao_fatec, 'on_sad_show':\n self.sad_show})\n\n def analisar_frase(self, widget):\n \"\"\"Função: analisar a frase que o usuário\"\"\"\n frase = self.text_area.get_text()\n if frase != '':\n frase_proc = normalizar(frase)\n self.text_area.set_text(frase)\n if (self.opcao == 'dilma' or self.opcao == 'copa' or self.opcao ==\n 'palmeiras' or self.opcao == 'fatec'):\n print('Opcao: %s ' % self.opcao)\n featureList = gera_lista_features(self.opcao)\n lista_feature_fell = get_lista_feature_fell()\n features_msg = getFeatureVector(frase_proc)\n training_set = apply_features(extract_features,\n lista_feature_fell)\n fell = avaliar_Sentimento(features_msg, training_set)\n print('Sentimento: %s ' % fell)\n\n def clear_text(self, widget):\n \"\"\"Função: para apagar o texto na área de texto\"\"\"\n self.text_area.set_text('')\n\n def opcao_dilma(self, widget):\n \"\"\"Função: para definir a opcao Dilma\"\"\"\n self.opcao = 'dilma'\n\n def opcao_copa(self, widget):\n \"\"\"Função: para definir a opcao Copa\"\"\"\n self.opcao = 'copa'\n\n def opcao_palmeiras(self, widget):\n \"\"\"Função: para definir a opcao Palmeiras\"\"\"\n self.opcao = 'palmeiras'\n\n def opcao_fatec(self, widget):\n \"\"\"Função: para definir a opcao Fatec\"\"\"\n self.opcao = 'fatec'\n\n def sad_show(self, widget):\n \"\"\"Função: para definir se imagem Sad ira aparecer\"\"\"\n self.visible = True\n\n\nif __name__ == '__main__':\n app = tgApp()\n gtk.main()\n", "step-5": "#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\nfrom testarMsg import *\n\n\nclass tgApp(object):\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file(\"../tg.glade\")\n self.window = builder.get_object(\"window1\")\n self.text_area = builder.get_object(\"text_entry\")\n self.window.show()\n self.opcao = \"\"\n builder.connect_signals({\"gtk_main_quit\": gtk.main_quit,\n \"on_button_analisar_clicked\": self.analisar_frase,\n \"on_button_clear_clicked\": self.clear_text,\n \"on_button_dilma_clicked\": self.opcao_dilma,\n \"on_button_copa_clicked\": self.opcao_copa,\n \"on_button_palmeiras_clicked\": self.opcao_palmeiras,\n \"on_button_fatec_clicked\": self.opcao_fatec,\n \"on_sad_show\": self.sad_show,\n })\n \n def analisar_frase(self, widget):\n \"\"\"Função: analisar a frase que o usuário\"\"\"\n frase = self.text_area.get_text()\n if ( frase != \"\"):\n frase_proc= normalizar(frase)\n self.text_area.set_text(frase)\n if (self.opcao == 'dilma' or self.opcao == 'copa' or self.opcao == 'palmeiras' or self.opcao == 'fatec'):\n print(\"Opcao: %s \"%self.opcao)\n featureList = gera_lista_features(self.opcao)\n lista_feature_fell = get_lista_feature_fell()\n features_msg = getFeatureVector(frase_proc)\n training_set = apply_features(extract_features,lista_feature_fell)\n fell = avaliar_Sentimento(features_msg,training_set)\n print (\"Sentimento: %s \"%fell)\n \n \n def clear_text(self, widget):\n \"\"\"Função: para apagar o texto na área de texto\"\"\"\n self.text_area.set_text(\"\")\n\n def opcao_dilma(self, widget):\n \"\"\"Função: para definir a opcao Dilma\"\"\"\n self.opcao=\"dilma\"\n \n def opcao_copa(self, widget):\n \"\"\"Função: para definir a opcao Copa\"\"\"\n self.opcao=\"copa\"\n\n def opcao_palmeiras(self, widget):\n \"\"\"Função: para definir a opcao Palmeiras\"\"\"\n self.opcao=\"palmeiras\"\n\n def opcao_fatec(self, widget):\n \"\"\"Função: para definir a opcao Fatec\"\"\"\n self.opcao=\"fatec\"\n \n def sad_show(self,widget):\n \"\"\"Função: para definir se imagem Sad ira aparecer\"\"\"\n self.visible=True\n\n \nif __name__ == \"__main__\":\n \n app = tgApp()\n gtk.main()\n \n \n", "step-ids": [ 6, 8, 9, 10, 12 ] }
[ 6, 8, 9, 10, 12 ]
""" common tests """ from django.test import TestCase from src.core.common import get_method_config from src.predictive_model.classification.models import ClassificationMethods from src.predictive_model.models import PredictiveModels from src.utils.tests_utils import create_test_job, create_test_predictive_model class TestCommon(TestCase): def test_get_method_config(self): job = create_test_job( predictive_model=create_test_predictive_model( predictive_model=PredictiveModels.CLASSIFICATION.value, prediction_method=ClassificationMethods.RANDOM_FOREST.value ) ) method, config = get_method_config(job) self.assertEqual(ClassificationMethods.RANDOM_FOREST.value, method) self.assertEqual({ 'max_depth': None, 'max_features': 'auto', 'n_estimators': 10, }, config)
normal
{ "blob_id": "824038a56e8aaf4adf6ec813a5728ab318547582", "index": 1638, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass TestCommon(TestCase):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestCommon(TestCase):\n\n def test_get_method_config(self):\n job = create_test_job(predictive_model=create_test_predictive_model\n (predictive_model=PredictiveModels.CLASSIFICATION.value,\n prediction_method=ClassificationMethods.RANDOM_FOREST.value))\n method, config = get_method_config(job)\n self.assertEqual(ClassificationMethods.RANDOM_FOREST.value, method)\n self.assertEqual({'max_depth': None, 'max_features': 'auto',\n 'n_estimators': 10}, config)\n", "step-4": "<mask token>\nfrom django.test import TestCase\nfrom src.core.common import get_method_config\nfrom src.predictive_model.classification.models import ClassificationMethods\nfrom src.predictive_model.models import PredictiveModels\nfrom src.utils.tests_utils import create_test_job, create_test_predictive_model\n\n\nclass TestCommon(TestCase):\n\n def test_get_method_config(self):\n job = create_test_job(predictive_model=create_test_predictive_model\n (predictive_model=PredictiveModels.CLASSIFICATION.value,\n prediction_method=ClassificationMethods.RANDOM_FOREST.value))\n method, config = get_method_config(job)\n self.assertEqual(ClassificationMethods.RANDOM_FOREST.value, method)\n self.assertEqual({'max_depth': None, 'max_features': 'auto',\n 'n_estimators': 10}, config)\n", "step-5": "\"\"\"\ncommon tests\n\"\"\"\n\nfrom django.test import TestCase\n\nfrom src.core.common import get_method_config\nfrom src.predictive_model.classification.models import ClassificationMethods\nfrom src.predictive_model.models import PredictiveModels\nfrom src.utils.tests_utils import create_test_job, create_test_predictive_model\n\n\nclass TestCommon(TestCase):\n def test_get_method_config(self):\n job = create_test_job(\n predictive_model=create_test_predictive_model(\n predictive_model=PredictiveModels.CLASSIFICATION.value,\n prediction_method=ClassificationMethods.RANDOM_FOREST.value\n )\n )\n\n method, config = get_method_config(job)\n\n self.assertEqual(ClassificationMethods.RANDOM_FOREST.value, method)\n self.assertEqual({\n 'max_depth': None,\n 'max_features': 'auto',\n 'n_estimators': 10,\n }, config)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# https://daphne-dev.github.io/2020/09/24/algo-022/ def solution(n): arr = [[0 for _ in range(i+1)] for i in range(n)] # 경우의수 는 3가지 # 1. y축이 증가하면서 수가 증가 # 2. x축이 증가하면서 수가 증가 # 3. y,x축이 감소하면서 수가 증가 size = n num = 0 x = 0 y = -1 while True: # 1번 for _ in range(size): num += 1 y += 1 arr[y][x] = num size-=1 if size == 0: break # 2번 for _ in range(size): num += 1 x += 1 arr[y][x] = num size-=1 if size == 0: break # 3번 for _ in range(size): num += 1 x -= 1 y -= 1 arr[y][x] = num size-=1 if size == 0: break answer = [] for i in arr: answer.extend(i) return answer # print(solution(4))
normal
{ "blob_id": "3c029adb59cd6db1e3d4a22e6561f5e2ae827d60", "index": 2465, "step-1": "<mask token>\n", "step-2": "def solution(n):\n arr = [[(0) for _ in range(i + 1)] for i in range(n)]\n size = n\n num = 0\n x = 0\n y = -1\n while True:\n for _ in range(size):\n num += 1\n y += 1\n arr[y][x] = num\n size -= 1\n if size == 0:\n break\n for _ in range(size):\n num += 1\n x += 1\n arr[y][x] = num\n size -= 1\n if size == 0:\n break\n for _ in range(size):\n num += 1\n x -= 1\n y -= 1\n arr[y][x] = num\n size -= 1\n if size == 0:\n break\n answer = []\n for i in arr:\n answer.extend(i)\n return answer\n", "step-3": "# https://daphne-dev.github.io/2020/09/24/algo-022/\ndef solution(n):\n arr = [[0 for _ in range(i+1)] for i in range(n)]\n # 경우의수 는 3가지\n # 1. y축이 증가하면서 수가 증가\n # 2. x축이 증가하면서 수가 증가\n # 3. y,x축이 감소하면서 수가 증가\n size = n\n num = 0\n x = 0\n y = -1\n while True:\n # 1번\n for _ in range(size):\n num += 1\n y += 1\n arr[y][x] = num\n size-=1\n if size == 0:\n break\n # 2번\n for _ in range(size):\n num += 1\n x += 1\n arr[y][x] = num\n size-=1\n if size == 0:\n break\n # 3번\n for _ in range(size):\n num += 1\n x -= 1\n y -= 1\n arr[y][x] = num\n size-=1\n if size == 0:\n break\n answer = []\n for i in arr:\n answer.extend(i)\n return answer\n# print(solution(4))", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import tensorflow.keras from PIL import Image, ImageOps from os import listdir from os.path import isfile, join import numpy as np import glob import cv2 np.set_printoptions(suppress = True) # Load the model model = tensorflow.keras.models.load_model('./converted_keras/keras_model.h5') # Create the array of the right shape to feed into the keras model # The 'length' or number of images you can put into the array is # determined by the first position in the shape tuple, in this case 1. data = np.ndarray(shape = (1, 224, 224, 3), dtype = np.float32) path = glob.glob("/Users/zjisuoo/Documents/zjisuoo_git/OurChord/00_NOTE_DATA/TEST/*.png") images = [] for image in path : n1 = cv2.imread(image) n2 = cv2.resize(n1, (244, 244)) images.append(n2) print(image) #turn the image int a numpy array image_array = np.array(n2) # Normalize the image normalized_image_array = (image_array.astype(dtype = np.float32) / 127.0) - 1 # Load the image into the array data = normalized_image_array # run the inference prediction = model.predict(data) # print(prediction) if(prediction[0][0] > 0.8): print("2분음표") elif(prediction[0][1] > 0.8): print("4분음표") elif(prediction[0][2] > 0.8): print("8분음표") elif(prediction[0][3] > 0.8): print("16분음표") else: print("음표아님")
normal
{ "blob_id": "13b69ec61d6b2129f1974ce7cae91c84100b3b58", "index": 449, "step-1": "<mask token>\n", "step-2": "<mask token>\nnp.set_printoptions(suppress=True)\n<mask token>\nfor image in path:\n n1 = cv2.imread(image)\n n2 = cv2.resize(n1, (244, 244))\n images.append(n2)\n print(image)\n<mask token>\nif prediction[0][0] > 0.8:\n print('2분음표')\nelif prediction[0][1] > 0.8:\n print('4분음표')\nelif prediction[0][2] > 0.8:\n print('8분음표')\nelif prediction[0][3] > 0.8:\n print('16분음표')\nelse:\n print('음표아님')\n", "step-3": "<mask token>\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('./converted_keras/keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\npath = glob.glob(\n '/Users/zjisuoo/Documents/zjisuoo_git/OurChord/00_NOTE_DATA/TEST/*.png')\nimages = []\nfor image in path:\n n1 = cv2.imread(image)\n n2 = cv2.resize(n1, (244, 244))\n images.append(n2)\n print(image)\nimage_array = np.array(n2)\nnormalized_image_array = image_array.astype(dtype=np.float32) / 127.0 - 1\ndata = normalized_image_array\nprediction = model.predict(data)\nif prediction[0][0] > 0.8:\n print('2분음표')\nelif prediction[0][1] > 0.8:\n print('4분음표')\nelif prediction[0][2] > 0.8:\n print('8분음표')\nelif prediction[0][3] > 0.8:\n print('16분음표')\nelse:\n print('음표아님')\n", "step-4": "import tensorflow.keras\nfrom PIL import Image, ImageOps\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\nimport glob\nimport cv2\nnp.set_printoptions(suppress=True)\nmodel = tensorflow.keras.models.load_model('./converted_keras/keras_model.h5')\ndata = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\npath = glob.glob(\n '/Users/zjisuoo/Documents/zjisuoo_git/OurChord/00_NOTE_DATA/TEST/*.png')\nimages = []\nfor image in path:\n n1 = cv2.imread(image)\n n2 = cv2.resize(n1, (244, 244))\n images.append(n2)\n print(image)\nimage_array = np.array(n2)\nnormalized_image_array = image_array.astype(dtype=np.float32) / 127.0 - 1\ndata = normalized_image_array\nprediction = model.predict(data)\nif prediction[0][0] > 0.8:\n print('2분음표')\nelif prediction[0][1] > 0.8:\n print('4분음표')\nelif prediction[0][2] > 0.8:\n print('8분음표')\nelif prediction[0][3] > 0.8:\n print('16분음표')\nelse:\n print('음표아님')\n", "step-5": "import tensorflow.keras\nfrom PIL import Image, ImageOps\nfrom os import listdir\nfrom os.path import isfile, join\nimport numpy as np\nimport glob\nimport cv2\n\nnp.set_printoptions(suppress = True)\n\n# Load the model\nmodel = tensorflow.keras.models.load_model('./converted_keras/keras_model.h5')\n\n# Create the array of the right shape to feed into the keras model\n# The 'length' or number of images you can put into the array is\n# determined by the first position in the shape tuple, in this case 1.\ndata = np.ndarray(shape = (1, 224, 224, 3), dtype = np.float32)\n\npath = glob.glob(\"/Users/zjisuoo/Documents/zjisuoo_git/OurChord/00_NOTE_DATA/TEST/*.png\")\nimages = []\n\nfor image in path :\n n1 = cv2.imread(image)\n n2 = cv2.resize(n1, (244, 244))\n images.append(n2)\n\n print(image)\n\n#turn the image int a numpy array\nimage_array = np.array(n2)\n\n# Normalize the image\nnormalized_image_array = (image_array.astype(dtype = np.float32) / 127.0) - 1\n\n# Load the image into the array\ndata = normalized_image_array\n\n# run the inference\nprediction = model.predict(data)\n# print(prediction)\n\nif(prediction[0][0] > 0.8):\n print(\"2분음표\")\nelif(prediction[0][1] > 0.8):\n print(\"4분음표\")\nelif(prediction[0][2] > 0.8):\n print(\"8분음표\")\nelif(prediction[0][3] > 0.8):\n print(\"16분음표\")\nelse:\n print(\"음표아님\")", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-14 19:37 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Assemblage', '0002_auto_20161014_1710'), ] operations = [ migrations.RemoveField( model_name='hotelingroup', name='negative_votes', ), migrations.RemoveField( model_name='hotelingroup', name='positive_votes', ), migrations.RemoveField( model_name='hotelingroup', name='voters', ), migrations.AddField( model_name='hotelingroup', name='negative_voters', field=models.ManyToManyField(related_name='hotelingroup_negative_voters', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='hotelingroup', name='positive_voters', field=models.ManyToManyField(related_name='hotelingroup_positive_voters', to=settings.AUTH_USER_MODEL), ), ]
normal
{ "blob_id": "8c05259ce577e6b6a6efdf778832e9bb817e47fd", "index": 1414, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('Assemblage', '0002_auto_20161014_1710')]\n operations = [migrations.RemoveField(model_name='hotelingroup', name=\n 'negative_votes'), migrations.RemoveField(model_name='hotelingroup',\n name='positive_votes'), migrations.RemoveField(model_name=\n 'hotelingroup', name='voters'), migrations.AddField(model_name=\n 'hotelingroup', name='negative_voters', field=models.\n ManyToManyField(related_name='hotelingroup_negative_voters', to=\n settings.AUTH_USER_MODEL)), migrations.AddField(model_name=\n 'hotelingroup', name='positive_voters', field=models.\n ManyToManyField(related_name='hotelingroup_positive_voters', to=\n settings.AUTH_USER_MODEL))]\n", "step-4": "from __future__ import unicode_literals\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [migrations.swappable_dependency(settings.\n AUTH_USER_MODEL), ('Assemblage', '0002_auto_20161014_1710')]\n operations = [migrations.RemoveField(model_name='hotelingroup', name=\n 'negative_votes'), migrations.RemoveField(model_name='hotelingroup',\n name='positive_votes'), migrations.RemoveField(model_name=\n 'hotelingroup', name='voters'), migrations.AddField(model_name=\n 'hotelingroup', name='negative_voters', field=models.\n ManyToManyField(related_name='hotelingroup_negative_voters', to=\n settings.AUTH_USER_MODEL)), migrations.AddField(model_name=\n 'hotelingroup', name='positive_voters', field=models.\n ManyToManyField(related_name='hotelingroup_positive_voters', to=\n settings.AUTH_USER_MODEL))]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.2 on 2016-10-14 19:37\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('Assemblage', '0002_auto_20161014_1710'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='hotelingroup',\n name='negative_votes',\n ),\n migrations.RemoveField(\n model_name='hotelingroup',\n name='positive_votes',\n ),\n migrations.RemoveField(\n model_name='hotelingroup',\n name='voters',\n ),\n migrations.AddField(\n model_name='hotelingroup',\n name='negative_voters',\n field=models.ManyToManyField(related_name='hotelingroup_negative_voters', to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='hotelingroup',\n name='positive_voters',\n field=models.ManyToManyField(related_name='hotelingroup_positive_voters', to=settings.AUTH_USER_MODEL),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import sys def caesar( plaintext, key ): if int( key ) < 0: return plaintext_ascii = [ ( ord( char ) + int( key ) ) for char in plaintext ] for ascii in plaintext_ascii: if ( ascii < 97 and ascii > 90 ) or ascii > 122: ascii -= 25 ciphertext = ''.join( [ chr( ascii ) for ascii in plaintext_ascii ] ) print( 'ciphertext: {}'.format( ciphertext ) ) if __name__ == '__main__': if len( sys.argv ) is not 3: print( 'Usage: python caesar.py plaintext key' ) else: caesar( sys.argv[1], sys.argv[2] )
normal
{ "blob_id": "9a7c6998e9e486f0497d3684f9c7a422c8e13521", "index": 7076, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef caesar(plaintext, key):\n if int(key) < 0:\n return\n plaintext_ascii = [(ord(char) + int(key)) for char in plaintext]\n for ascii in plaintext_ascii:\n if ascii < 97 and ascii > 90 or ascii > 122:\n ascii -= 25\n ciphertext = ''.join([chr(ascii) for ascii in plaintext_ascii])\n print('ciphertext: {}'.format(ciphertext))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef caesar(plaintext, key):\n if int(key) < 0:\n return\n plaintext_ascii = [(ord(char) + int(key)) for char in plaintext]\n for ascii in plaintext_ascii:\n if ascii < 97 and ascii > 90 or ascii > 122:\n ascii -= 25\n ciphertext = ''.join([chr(ascii) for ascii in plaintext_ascii])\n print('ciphertext: {}'.format(ciphertext))\n\n\nif __name__ == '__main__':\n if len(sys.argv) is not 3:\n print('Usage: python caesar.py plaintext key')\n else:\n caesar(sys.argv[1], sys.argv[2])\n", "step-4": "import sys\n\n\ndef caesar(plaintext, key):\n if int(key) < 0:\n return\n plaintext_ascii = [(ord(char) + int(key)) for char in plaintext]\n for ascii in plaintext_ascii:\n if ascii < 97 and ascii > 90 or ascii > 122:\n ascii -= 25\n ciphertext = ''.join([chr(ascii) for ascii in plaintext_ascii])\n print('ciphertext: {}'.format(ciphertext))\n\n\nif __name__ == '__main__':\n if len(sys.argv) is not 3:\n print('Usage: python caesar.py plaintext key')\n else:\n caesar(sys.argv[1], sys.argv[2])\n", "step-5": "import sys\n\ndef caesar( plaintext, key ):\n if int( key ) < 0:\n return\n\n plaintext_ascii = [ ( ord( char ) + int( key ) ) for char in plaintext ]\n for ascii in plaintext_ascii:\n if ( ascii < 97 and ascii > 90 ) or ascii > 122:\n ascii -= 25\n\n ciphertext = ''.join( [ chr( ascii ) for ascii in plaintext_ascii ] )\n print( 'ciphertext: {}'.format( ciphertext ) )\n\nif __name__ == '__main__':\n if len( sys.argv ) is not 3:\n print( 'Usage: python caesar.py plaintext key' )\n else:\n caesar( sys.argv[1], sys.argv[2] )", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Importing datasets wrangling libraries import numpy as np import pandas as pd incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns)
normal
{ "blob_id": "1deab16d6c574bf532c561b8d6d88aac6e5d996c", "index": 8355, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(incd_data.columns)\n", "step-3": "<mask token>\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS',\n 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000',\n 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-4": "import numpy as np\nimport pandas as pd\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS',\n 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000',\n 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-5": "# Importing datasets wrangling libraries\nimport numpy as np\nimport pandas as pd\n\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module that defines a controller for database's operations over business rules """ # built-in dependencies import functools import typing # external dependencies import sqlalchemy from sqlalchemy.orm import sessionmaker # project dependencies from database.table import ResourceTable __authors__ = ["Gabriel Castro", "Gustavo Possebon", "Henrique Kops"] __date__ = "24/10/2020" class _DatabaseResourceTableController: """ Controller for resource table access """ def __init__(self): # sqlalchemy self.engine = sqlalchemy.create_engine("sqlite:///db.sqlite3") self.session = sessionmaker(bind=self.engine) def register_peer(self, peer_id: str, peer_ip: str, peer_port: int, resource_name: str, resource_path: str, resource_hash: str) -> None: """ Register 'peer x resource' relationship at database :param peer_id: Peer's id :param peer_ip: Peer's ip :param peer_port: Peer's listen port :param resource_name: Resource's name :param resource_path: Resource's path :param resource_hash: Resource's MD5 """ session = self.session() try: new_resource = ResourceTable() new_resource.peerId = peer_id new_resource.peerIp = peer_ip new_resource.peerPort = peer_port new_resource.resourceName = resource_name new_resource.resourcePath = resource_path new_resource.resourceHash = resource_hash session.add(new_resource) session.commit() finally: session.close() def get_available_peer(self, resource_name: str) -> typing.List: """ Get peer's ip and port and resource's path, name and hash that contains same resource name :param resource_name: Name of the resource to be searched at database :return: List containing matching peer's and resource's info """ session = self.session() try: available_peers = session\ .query( ResourceTable.peerIp, ResourceTable.peerPort, ResourceTable.resourcePath, ResourceTable.resourceName, ResourceTable.resourceHash )\ .filter(ResourceTable.resourceName == resource_name)\ .group_by(ResourceTable.peerId)\ .all() if available_peers: return available_peers[0] else: return [] finally: session.close() def get_all_resources(self) -> typing.List: """ Get every register of peer's ip and port and resource's path, name and hash :return: List of every 'peer x resource' info """ session = self.session() try: available_peers = session\ .query( ResourceTable.peerIp, ResourceTable.peerPort, ResourceTable.resourcePath, ResourceTable.resourceName, ResourceTable.resourceHash )\ .group_by(ResourceTable.peerId, ResourceTable.resourceHash)\ .all() return available_peers finally: session.close() def drop_peer(self, peer_id: str) -> None: """ Delete every record that contains same peer's id :param peer_id: Peer's ip to be used as filter """ session = self.session() try: session\ .query(ResourceTable)\ .filter(ResourceTable.peerId == peer_id)\ .delete() session.commit() finally: session.close() @functools.lru_cache() def get_database_resource_table_controller() -> [_DatabaseResourceTableController]: """ Singleton for DatabaseResourceTableController class :return: Same instance for DatabaseResourceTableController class """ return _DatabaseResourceTableController()
normal
{ "blob_id": "c024e12fe06e47187c25a9f384ceed566bf94645", "index": 6909, "step-1": "<mask token>\n\n\nclass _DatabaseResourceTableController:\n <mask token>\n <mask token>\n\n def register_peer(self, peer_id: str, peer_ip: str, peer_port: int,\n resource_name: str, resource_path: str, resource_hash: str) ->None:\n \"\"\"\n Register 'peer x resource' relationship at database\n\n :param peer_id: Peer's id\n :param peer_ip: Peer's ip\n :param peer_port: Peer's listen port\n :param resource_name: Resource's name\n :param resource_path: Resource's path\n :param resource_hash: Resource's MD5\n \"\"\"\n session = self.session()\n try:\n new_resource = ResourceTable()\n new_resource.peerId = peer_id\n new_resource.peerIp = peer_ip\n new_resource.peerPort = peer_port\n new_resource.resourceName = resource_name\n new_resource.resourcePath = resource_path\n new_resource.resourceHash = resource_hash\n session.add(new_resource)\n session.commit()\n finally:\n session.close()\n\n def get_available_peer(self, resource_name: str) ->typing.List:\n \"\"\"\n Get peer's ip and port and resource's path, name and hash\n that contains same resource name\n\n :param resource_name: Name of the resource to be searched at database\n :return: List containing matching peer's and resource's info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash).filter(\n ResourceTable.resourceName == resource_name).group_by(\n ResourceTable.peerId).all()\n if available_peers:\n return available_peers[0]\n else:\n return []\n finally:\n session.close()\n\n def get_all_resources(self) ->typing.List:\n \"\"\"\n Get every register of peer's ip and port and resource's path, name and hash\n\n :return: List of every 'peer x resource' info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash\n ).group_by(ResourceTable.peerId, ResourceTable.resourceHash\n ).all()\n return available_peers\n finally:\n session.close()\n\n def drop_peer(self, peer_id: str) ->None:\n \"\"\"\n Delete every record that contains same peer's id\n\n :param peer_id: Peer's ip to be used as filter\n \"\"\"\n session = self.session()\n try:\n session.query(ResourceTable).filter(ResourceTable.peerId == peer_id\n ).delete()\n session.commit()\n finally:\n session.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass _DatabaseResourceTableController:\n <mask token>\n\n def __init__(self):\n self.engine = sqlalchemy.create_engine('sqlite:///db.sqlite3')\n self.session = sessionmaker(bind=self.engine)\n\n def register_peer(self, peer_id: str, peer_ip: str, peer_port: int,\n resource_name: str, resource_path: str, resource_hash: str) ->None:\n \"\"\"\n Register 'peer x resource' relationship at database\n\n :param peer_id: Peer's id\n :param peer_ip: Peer's ip\n :param peer_port: Peer's listen port\n :param resource_name: Resource's name\n :param resource_path: Resource's path\n :param resource_hash: Resource's MD5\n \"\"\"\n session = self.session()\n try:\n new_resource = ResourceTable()\n new_resource.peerId = peer_id\n new_resource.peerIp = peer_ip\n new_resource.peerPort = peer_port\n new_resource.resourceName = resource_name\n new_resource.resourcePath = resource_path\n new_resource.resourceHash = resource_hash\n session.add(new_resource)\n session.commit()\n finally:\n session.close()\n\n def get_available_peer(self, resource_name: str) ->typing.List:\n \"\"\"\n Get peer's ip and port and resource's path, name and hash\n that contains same resource name\n\n :param resource_name: Name of the resource to be searched at database\n :return: List containing matching peer's and resource's info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash).filter(\n ResourceTable.resourceName == resource_name).group_by(\n ResourceTable.peerId).all()\n if available_peers:\n return available_peers[0]\n else:\n return []\n finally:\n session.close()\n\n def get_all_resources(self) ->typing.List:\n \"\"\"\n Get every register of peer's ip and port and resource's path, name and hash\n\n :return: List of every 'peer x resource' info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash\n ).group_by(ResourceTable.peerId, ResourceTable.resourceHash\n ).all()\n return available_peers\n finally:\n session.close()\n\n def drop_peer(self, peer_id: str) ->None:\n \"\"\"\n Delete every record that contains same peer's id\n\n :param peer_id: Peer's ip to be used as filter\n \"\"\"\n session = self.session()\n try:\n session.query(ResourceTable).filter(ResourceTable.peerId == peer_id\n ).delete()\n session.commit()\n finally:\n session.close()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass _DatabaseResourceTableController:\n \"\"\"\n Controller for resource table access\n \"\"\"\n\n def __init__(self):\n self.engine = sqlalchemy.create_engine('sqlite:///db.sqlite3')\n self.session = sessionmaker(bind=self.engine)\n\n def register_peer(self, peer_id: str, peer_ip: str, peer_port: int,\n resource_name: str, resource_path: str, resource_hash: str) ->None:\n \"\"\"\n Register 'peer x resource' relationship at database\n\n :param peer_id: Peer's id\n :param peer_ip: Peer's ip\n :param peer_port: Peer's listen port\n :param resource_name: Resource's name\n :param resource_path: Resource's path\n :param resource_hash: Resource's MD5\n \"\"\"\n session = self.session()\n try:\n new_resource = ResourceTable()\n new_resource.peerId = peer_id\n new_resource.peerIp = peer_ip\n new_resource.peerPort = peer_port\n new_resource.resourceName = resource_name\n new_resource.resourcePath = resource_path\n new_resource.resourceHash = resource_hash\n session.add(new_resource)\n session.commit()\n finally:\n session.close()\n\n def get_available_peer(self, resource_name: str) ->typing.List:\n \"\"\"\n Get peer's ip and port and resource's path, name and hash\n that contains same resource name\n\n :param resource_name: Name of the resource to be searched at database\n :return: List containing matching peer's and resource's info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash).filter(\n ResourceTable.resourceName == resource_name).group_by(\n ResourceTable.peerId).all()\n if available_peers:\n return available_peers[0]\n else:\n return []\n finally:\n session.close()\n\n def get_all_resources(self) ->typing.List:\n \"\"\"\n Get every register of peer's ip and port and resource's path, name and hash\n\n :return: List of every 'peer x resource' info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash\n ).group_by(ResourceTable.peerId, ResourceTable.resourceHash\n ).all()\n return available_peers\n finally:\n session.close()\n\n def drop_peer(self, peer_id: str) ->None:\n \"\"\"\n Delete every record that contains same peer's id\n\n :param peer_id: Peer's ip to be used as filter\n \"\"\"\n session = self.session()\n try:\n session.query(ResourceTable).filter(ResourceTable.peerId == peer_id\n ).delete()\n session.commit()\n finally:\n session.close()\n\n\n<mask token>\n", "step-4": "<mask token>\n__authors__ = ['Gabriel Castro', 'Gustavo Possebon', 'Henrique Kops']\n__date__ = '24/10/2020'\n\n\nclass _DatabaseResourceTableController:\n \"\"\"\n Controller for resource table access\n \"\"\"\n\n def __init__(self):\n self.engine = sqlalchemy.create_engine('sqlite:///db.sqlite3')\n self.session = sessionmaker(bind=self.engine)\n\n def register_peer(self, peer_id: str, peer_ip: str, peer_port: int,\n resource_name: str, resource_path: str, resource_hash: str) ->None:\n \"\"\"\n Register 'peer x resource' relationship at database\n\n :param peer_id: Peer's id\n :param peer_ip: Peer's ip\n :param peer_port: Peer's listen port\n :param resource_name: Resource's name\n :param resource_path: Resource's path\n :param resource_hash: Resource's MD5\n \"\"\"\n session = self.session()\n try:\n new_resource = ResourceTable()\n new_resource.peerId = peer_id\n new_resource.peerIp = peer_ip\n new_resource.peerPort = peer_port\n new_resource.resourceName = resource_name\n new_resource.resourcePath = resource_path\n new_resource.resourceHash = resource_hash\n session.add(new_resource)\n session.commit()\n finally:\n session.close()\n\n def get_available_peer(self, resource_name: str) ->typing.List:\n \"\"\"\n Get peer's ip and port and resource's path, name and hash\n that contains same resource name\n\n :param resource_name: Name of the resource to be searched at database\n :return: List containing matching peer's and resource's info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash).filter(\n ResourceTable.resourceName == resource_name).group_by(\n ResourceTable.peerId).all()\n if available_peers:\n return available_peers[0]\n else:\n return []\n finally:\n session.close()\n\n def get_all_resources(self) ->typing.List:\n \"\"\"\n Get every register of peer's ip and port and resource's path, name and hash\n\n :return: List of every 'peer x resource' info\n \"\"\"\n session = self.session()\n try:\n available_peers = session.query(ResourceTable.peerIp,\n ResourceTable.peerPort, ResourceTable.resourcePath,\n ResourceTable.resourceName, ResourceTable.resourceHash\n ).group_by(ResourceTable.peerId, ResourceTable.resourceHash\n ).all()\n return available_peers\n finally:\n session.close()\n\n def drop_peer(self, peer_id: str) ->None:\n \"\"\"\n Delete every record that contains same peer's id\n\n :param peer_id: Peer's ip to be used as filter\n \"\"\"\n session = self.session()\n try:\n session.query(ResourceTable).filter(ResourceTable.peerId == peer_id\n ).delete()\n session.commit()\n finally:\n session.close()\n\n\[email protected]_cache()\ndef get_database_resource_table_controller() ->[\n _DatabaseResourceTableController]:\n \"\"\"\n Singleton for DatabaseResourceTableController class\n\n :return: Same instance for DatabaseResourceTableController class\n \"\"\"\n return _DatabaseResourceTableController()\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule that defines a controller for database's operations over business rules\n\"\"\"\n\n# built-in dependencies\nimport functools\nimport typing\n\n# external dependencies\nimport sqlalchemy\nfrom sqlalchemy.orm import sessionmaker\n\n# project dependencies\nfrom database.table import ResourceTable\n\n__authors__ = [\"Gabriel Castro\", \"Gustavo Possebon\", \"Henrique Kops\"]\n__date__ = \"24/10/2020\"\n\n\nclass _DatabaseResourceTableController:\n \"\"\"\n Controller for resource table access\n \"\"\"\n\n def __init__(self):\n # sqlalchemy\n self.engine = sqlalchemy.create_engine(\"sqlite:///db.sqlite3\")\n self.session = sessionmaker(bind=self.engine)\n\n def register_peer(self, peer_id: str, peer_ip: str, peer_port: int,\n resource_name: str, resource_path: str, resource_hash: str) -> None:\n \"\"\"\n Register 'peer x resource' relationship at database\n\n :param peer_id: Peer's id\n :param peer_ip: Peer's ip\n :param peer_port: Peer's listen port\n :param resource_name: Resource's name\n :param resource_path: Resource's path\n :param resource_hash: Resource's MD5\n \"\"\"\n\n session = self.session()\n\n try:\n new_resource = ResourceTable()\n\n new_resource.peerId = peer_id\n new_resource.peerIp = peer_ip\n new_resource.peerPort = peer_port\n new_resource.resourceName = resource_name\n new_resource.resourcePath = resource_path\n new_resource.resourceHash = resource_hash\n\n session.add(new_resource)\n session.commit()\n\n finally:\n session.close()\n\n def get_available_peer(self, resource_name: str) -> typing.List:\n \"\"\"\n Get peer's ip and port and resource's path, name and hash\n that contains same resource name\n\n :param resource_name: Name of the resource to be searched at database\n :return: List containing matching peer's and resource's info\n \"\"\"\n\n session = self.session()\n\n try:\n available_peers = session\\\n .query(\n ResourceTable.peerIp,\n ResourceTable.peerPort,\n ResourceTable.resourcePath,\n ResourceTable.resourceName,\n ResourceTable.resourceHash\n )\\\n .filter(ResourceTable.resourceName == resource_name)\\\n .group_by(ResourceTable.peerId)\\\n .all()\n\n if available_peers:\n return available_peers[0]\n\n else:\n return []\n\n finally:\n session.close()\n\n def get_all_resources(self) -> typing.List:\n \"\"\"\n Get every register of peer's ip and port and resource's path, name and hash\n\n :return: List of every 'peer x resource' info\n \"\"\"\n\n session = self.session()\n\n try:\n available_peers = session\\\n .query(\n ResourceTable.peerIp,\n ResourceTable.peerPort,\n ResourceTable.resourcePath,\n ResourceTable.resourceName,\n ResourceTable.resourceHash\n )\\\n .group_by(ResourceTable.peerId, ResourceTable.resourceHash)\\\n .all()\n\n return available_peers\n\n finally:\n session.close()\n\n def drop_peer(self, peer_id: str) -> None:\n \"\"\"\n Delete every record that contains same peer's id\n\n :param peer_id: Peer's ip to be used as filter\n \"\"\"\n\n session = self.session()\n try:\n session\\\n .query(ResourceTable)\\\n .filter(ResourceTable.peerId == peer_id)\\\n .delete()\n session.commit()\n\n finally:\n session.close()\n\n\[email protected]_cache()\ndef get_database_resource_table_controller() -> [_DatabaseResourceTableController]:\n \"\"\"\n Singleton for DatabaseResourceTableController class\n\n :return: Same instance for DatabaseResourceTableController class\n \"\"\"\n\n return _DatabaseResourceTableController()\n", "step-ids": [ 5, 6, 7, 9, 11 ] }
[ 5, 6, 7, 9, 11 ]
import matplotlib.pyplot as plt import numpy as np x = [1, 2, 2.5, 3, 4] # x-coordinates for graph y = [1, 4, 7, 9, 15] # y-coordinates plt.axis([0, 6, 0, 20]) # creating my x and y axis range. 0-6 is x, 0-20 is y plt.plot(x, y, 'ro') # can see graph has a linear correspondence, therefore, can use linear regression that cn give us good predictions # can create a line of best fit --> don't entirely understand syntax for line of best fit # np.polyfit takes in x and y values, then the number of points (or connections) you want for your LBF plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x))) plt.show()
normal
{ "blob_id": "c69c8ba218935e5bb065b3b925cc7c5f1aa2957b", "index": 5806, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n", "step-3": "<mask token>\nx = [1, 2, 2.5, 3, 4]\ny = [1, 4, 7, 9, 15]\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n", "step-4": "import matplotlib.pyplot as plt\nimport numpy as np\nx = [1, 2, 2.5, 3, 4]\ny = [1, 4, 7, 9, 15]\nplt.axis([0, 6, 0, 20])\nplt.plot(x, y, 'ro')\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n", "step-5": "\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx = [1, 2, 2.5, 3, 4] # x-coordinates for graph\ny = [1, 4, 7, 9, 15] # y-coordinates\nplt.axis([0, 6, 0, 20]) # creating my x and y axis range. 0-6 is x, 0-20 is y\n\nplt.plot(x, y, 'ro')\n# can see graph has a linear correspondence, therefore, can use linear regression that cn give us good predictions\n# can create a line of best fit --> don't entirely understand syntax for line of best fit\n# np.polyfit takes in x and y values, then the number of points (or connections) you want for your LBF\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))\nplt.show()\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Alonso Vidales" __email__ = "[email protected]" __date__ = "2013-11-11" class ConnectedSets: """ This is a classic percolation problem, the algorithms uses an array of integer to represent tees, each tree will be a set of connected elements """ __debug = False def link_nodes(self, left, right): """ For two given nodes, search for the root node of each tree, after obtaine the two root nodes, point the right root node to the left root node connecting the two trees To represent the trees, an array is used, the root nodes are -1 and the value on each positions points to the position of the parent node """ if self.__debug: print "Linking: %s - %s" % (left, right) root_left = (left[0] * len(self.__matrix)) + left[1] parent_left = self.__percolation[root_left] while parent_left != -1: root_left = parent_left parent_left = self.__percolation[parent_left] root_right = (right[0] * len(self.__matrix)) + right[1] parent_right = self.__percolation[root_right] while parent_right != -1: root_right = parent_right parent_right = self.__percolation[parent_right] if root_right != root_left: self.__percolation[root_right] = root_left if self.__debug: print "Link: %d - %d - %s" % (root_left, root_right, self.__percolation) def resolve(self): size = len(self.__matrix) for rowPos in range(size): for colPos in range(size): # Check left connection if colPos > 0: if self.__matrix[rowPos][colPos - 1] == self.__matrix[rowPos][colPos]: # Link pos with left self.link_nodes((rowPos, colPos - 1), (rowPos, colPos)) # Check top-right connection if (colPos + 1) < size and rowPos > 0: if self.__matrix[rowPos - 1][colPos + 1] == self.__matrix[rowPos][colPos]: # Link pos with top-left self.link_nodes((rowPos - 1, colPos + 1), (rowPos, colPos)) # Check top-left connection if colPos > 0 and rowPos > 0: if self.__matrix[rowPos - 1][colPos - 1] == self.__matrix[rowPos][colPos]: # Link pos with top-left self.link_nodes((rowPos - 1, colPos - 1), (rowPos, colPos)) # Check top connection if rowPos > 0: if self.__matrix[rowPos - 1][colPos] == self.__matrix[rowPos][colPos]: # Link pos with top self.link_nodes((rowPos - 1, colPos), (rowPos, colPos)) if self.__debug: print self.__percolation components = 0 # Get all the root nodes of the trees (nodes with -1 as parent), and # check if the root node on the original matrix contains a 1 for pos in range(len(self.__percolation)): if self.__percolation[pos] == -1 and self.__matrix[pos / size][pos % size] == 1: components += 1 return components def __init__(self, matrix): self.__percolation = [-1] * (len(matrix) ** 2) self.__matrix = matrix if __name__ == "__main__": for problem in range(int(raw_input())): matrix = [] for row in range(int(raw_input())): matrix.append(map(int, raw_input().split())) print ConnectedSets(matrix).resolve()
normal
{ "blob_id": "d18c0fa29ccdabdd9e11622e8aaec91ff96117df", "index": 6650, "step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n\n__author__ = \"Alonso Vidales\"\n__email__ = \"[email protected]\"\n__date__ = \"2013-11-11\"\n\nclass ConnectedSets:\n \"\"\"\n This is a classic percolation problem, the algorithms uses an array\n of integer to represent tees, each tree will be a set of connected elements\n \"\"\"\n __debug = False\n\n def link_nodes(self, left, right):\n \"\"\"\n For two given nodes, search for the root node of each tree, after\n obtaine the two root nodes, point the right root node to the left root\n node connecting the two trees\n To represent the trees, an array is used, the root nodes are -1 and the\n value on each positions points to the position of the parent node\n \"\"\"\n if self.__debug:\n print \"Linking: %s - %s\" % (left, right)\n root_left = (left[0] * len(self.__matrix)) + left[1]\n parent_left = self.__percolation[root_left]\n\n while parent_left != -1:\n root_left = parent_left\n parent_left = self.__percolation[parent_left]\n\n root_right = (right[0] * len(self.__matrix)) + right[1]\n parent_right = self.__percolation[root_right]\n while parent_right != -1:\n root_right = parent_right\n parent_right = self.__percolation[parent_right]\n\n if root_right != root_left:\n self.__percolation[root_right] = root_left\n if self.__debug:\n print \"Link: %d - %d - %s\" % (root_left, root_right, self.__percolation)\n\n def resolve(self):\n size = len(self.__matrix)\n\n for rowPos in range(size):\n for colPos in range(size):\n # Check left connection\n if colPos > 0:\n if self.__matrix[rowPos][colPos - 1] == self.__matrix[rowPos][colPos]:\n # Link pos with left\n self.link_nodes((rowPos, colPos - 1), (rowPos, colPos))\n\n # Check top-right connection\n if (colPos + 1) < size and rowPos > 0:\n if self.__matrix[rowPos - 1][colPos + 1] == self.__matrix[rowPos][colPos]:\n # Link pos with top-left\n self.link_nodes((rowPos - 1, colPos + 1), (rowPos, colPos))\n\n # Check top-left connection\n if colPos > 0 and rowPos > 0:\n if self.__matrix[rowPos - 1][colPos - 1] == self.__matrix[rowPos][colPos]:\n # Link pos with top-left\n self.link_nodes((rowPos - 1, colPos - 1), (rowPos, colPos))\n\n # Check top connection\n if rowPos > 0:\n if self.__matrix[rowPos - 1][colPos] == self.__matrix[rowPos][colPos]:\n # Link pos with top\n self.link_nodes((rowPos - 1, colPos), (rowPos, colPos))\n\n if self.__debug:\n print self.__percolation\n\n components = 0\n # Get all the root nodes of the trees (nodes with -1 as parent), and\n # check if the root node on the original matrix contains a 1\n for pos in range(len(self.__percolation)):\n if self.__percolation[pos] == -1 and self.__matrix[pos / size][pos % size] == 1:\n components += 1\n\n return components\n\n def __init__(self, matrix):\n self.__percolation = [-1] * (len(matrix) ** 2)\n self.__matrix = matrix\n\nif __name__ == \"__main__\":\n for problem in range(int(raw_input())):\n matrix = []\n for row in range(int(raw_input())):\n matrix.append(map(int, raw_input().split()))\n\n print ConnectedSets(matrix).resolve()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#!/usr/bin/env python ''' @author : Mitchell Van Braeckel @id : 1002297 @date : 10/10/2020 @version : python 3.8-32 / python 3.8.5 @course : CIS*4010 Cloud Computing @brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD @note : Description: There are many CSV files containing info from the OECD about agricultural production, each for various regions around the world. Queries all 4 tables (northamerica, canada, usa, mexico -table names) based on a commodity (code key or label), looking for all common variables between CAN, USA, and MEX, outputting all results (for all years) in a table, then output the specific NA definition 'hit' results and probable conclusion for NA definition per variable, as well as an overall conclusion for NA definition NOTE: forgot to add ability to specify commodity as cmd line arg instead of STDIN NOTE: assume year range is 2010 to 2029 (inclusive) NOTE: assume perfect user input for commodity and variables - however, if input commodity that's not a valid commodity code or label, exits program with error message NOTE: NA definition hit refers to if the calculated sum from different tables of CAN, USA, MEX are equal to that of NA (CAN+USA, CAN+USA+MEX, or Neither) ''' ''' IMPROVEMENT: Use 'encodings' table instead of the CSV file ''' ############################################# IMPORTS ############################################# # IMPORTS - 'pip install <import-package>' import boto3 import csv import sys from boto3.dynamodb.conditions import Key, Attr ############################################ CONSTANTS ############################################ # TABLE CONSTANTS NORTH_AMERICA = "northamerica" CANADA = "canada" USA = "usa" MEXICO = "mexico" TABLE_LIST = [NORTH_AMERICA, CANADA, USA, MEXICO] YEAR_RANGE = range(2010, 2030) # OTHER CONSTANTS OUTPUT_FORMAT = "{:<8}{:<18}{:<18}{:<18}{:<18}{:<18}{:<18}{:<10}" ENCODINGS_CSV = "encodings.csv" #ENCODINGS_TABLE_NAME = "encodings" USAGE_STATEMENT = "Usage: py queryOECD.py <commodity-code|commodity-label>" ############################## STATE VARIABLES, INITIALIZATION, MAIN ############################## # MAIN - Declares global vars and state here, then ask for commodity (check both key/label), # look for all common variables between CAN, USA, and MEX, outputting all results (for all years) in a table, # then output the specific NA definition 'hit' results and probable conclusion for NA definition def main(): #globals global dynamodb_client global dynamodb_resource global na_table global canada_table global usa_table global mexico_table global total_can_usa global total_can_usa_mex global total_neither # ========== ARGUMENTS ========== # Collect command line arguments when executing this python script argc = len(sys.argv) bad_usage_flag = False # Check #of args (deal with it later tho) # 1 optional arg for commodity, otherwise prompt user for it if argc > 2: bad_usage_flag = True print("Error: Too many arguments.") # Exit with usage statement if flag has been triggered for any reason if bad_usage_flag: sys.exit(USAGE_STATEMENT) # ========== AWS DYNAMO DB ========== # Init AWS DynamoDB client and resource (NOTE: these are global) dynamodb_client = boto3.client("dynamodb") dynamodb_resource = boto3.resource("dynamodb") # Validate AWS DynamoDB credentials (by testing if 'list_tables()' works) try: dynamodb_client.list_tables() except Exception as e: print("Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')") sys.exit(f"[ERROR] {e}") # Check the 4 tables exist, then get them all err_output = "" table_list = dynamodb_client.list_tables()['TableNames'] print(f"Existing Tables: {table_list}") for t in TABLE_LIST: if t not in table_list: err_output += f"Error: Invalid table name '{t}' - table does not exist.\n" # Print all tables that did not exist, then exit if err_output != "": print(err_output.strip("\n")) sys.exit("ERROR: Terminating program because unable to get table that does not exist.") # Get all tables (after checking they exist) (NOTE: these are global) na_table = dynamodb_resource.Table(NORTH_AMERICA) canada_table = dynamodb_resource.Table(CANADA) usa_table = dynamodb_resource.Table(USA) mexico_table = dynamodb_resource.Table(MEXICO) # Open the encodings CSV file and read its contents commodity_encodings_dict = {} variable_encodings_dict = {} with open(ENCODINGS_CSV, "r", newline='') as csv_file: csv_content = csv.reader(csv_file, delimiter=',') # if field is var or commodity, set a key-value pair between code and label (in the respective map) for row in csv_content: if row[2] == "variable": variable_encodings_dict[row[0]] = row[1] elif row[2] == "commodity": commodity_encodings_dict[row[0]] = row[1] csv_file.close() # Check args for commodity now, otherwise prompt user if argc == 2: commodity_input = sys.argv[1] else: # Ask user for commodity commodity_input = input("Commodity: ").strip() # Check if input exists as code key, otherwise try to convert assumed label to code key (if not a label, code will be None after) if commodity_input.upper() in commodity_encodings_dict: commodity_code = commodity_input.upper() else: commodity_code = convert_dict_label_to_code_key(commodity_input, commodity_encodings_dict) # Check if commodity found a code or None print(f"ENCODING: {commodity_code}") if commodity_code is None: print(f"Error: Commodity '{commodity_input}' was not found.") sys.exit("ERROR: Terminating program because input does not exist as an encoding commodity code or label.") # Init total accumulators for each category total_can_usa = 0 total_can_usa_mex = 0 total_neither = 0 # iterate through each variable and analyze data (if applicable) for var in variable_encodings_dict.keys(): if is_common_variable(commodity_code, var): output_table(commodity_code, var, variable_encodings_dict, commodity_encodings_dict) # Determine the NA definition for this variable based on #of 'hits' per year max_hits = max(total_can_usa, total_can_usa_mex, total_neither) if total_can_usa == max_hits: na_defn = "CAN+USA" elif total_can_usa_mex == max_hits: na_defn = "CAN+USA+MEX" else: na_defn = "Neither" print(f"Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither") print(f"Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\n") ############################################ FUNCTIONS ############################################ # Converts the label of a dict into its code key, returns None if not a label def convert_dict_label_to_code_key(label, encodings_dict): # Get the key of the label if the label exists in the dict as a value if label in list(encodings_dict.values()): return list(encodings_dict.keys())[list(encodings_dict.values()).index(label)] else: return None # Check if a commodity code + variable is common across all 4 tables, return true if it is def is_common_variable(commodity_code, variable): return (has_commodity_and_variable(na_table, commodity_code, variable) and has_commodity_and_variable(canada_table, commodity_code, variable) and has_commodity_and_variable(usa_table, commodity_code, variable) and has_commodity_and_variable(mexico_table, commodity_code, variable)) # Check if a table has data for commodity code + variable (ie. scan table), returns true if at least 1 item is found def has_commodity_and_variable(table, commodity_code, variable): response = table.scan( FilterExpression = Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable) ) return response['Count'] > 0 # Retrieves and outputs table data based on commodity and variable and analyze for NA definition def output_table(commodity_code, variable, variable_encodings_dict, commodity_encodings_dict): # Bring in globals to modify global total_can_usa global total_can_usa_mex global total_neither # Init local accumulators temp_can_usa = 0 temp_can_usa_mex = 0 temp_neither = 0 # Print table headers: common variable (for commodity code) across all 4 tables, and table column names print(f"Variable: {variable_encodings_dict[variable]}") print(OUTPUT_FORMAT.format("Year", "North America", "Canada", "USA", "Mexico", "CAN+USA", "CAN+USA+MEX", "NA Defn")) # Retrieve all data, from all years (ie. the items from the scan) na_scan_data = na_table.scan( FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable) )['Items'] can_scan_data = canada_table.scan( FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable) )['Items'] usa_scan_data = usa_table.scan( FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable) )['Items'] mex_scan_data = mexico_table.scan( FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable) )['Items'] # Sort each scan data by key na_scan_data.sort(key=data_sort) can_scan_data.sort(key=data_sort) usa_scan_data.sort(key=data_sort) mex_scan_data.sort(key=data_sort) # Analyze data for year in YEAR_RANGE: # For each relevant year, calculate total value using multiplication factor i = year - 2010 na_value = na_scan_data[i]['value'] * (10**na_scan_data[i]['mfactor']) can_value = can_scan_data[i]['value'] * (10**can_scan_data[i]['mfactor']) usa_value = usa_scan_data[i]['value'] * (10**usa_scan_data[i]['mfactor']) mex_value = mex_scan_data[i]['value'] * (10**mex_scan_data[i]['mfactor']) # Calc temp sums for the CAN+USA and CAN+USA+MEX columns temp_can_usa_value = can_value + usa_value temp_can_usa_mex_value = can_value + usa_value + mex_value # Determine OECD def of NA, by checking if the temp calc sums from scan data calc values are equivalent to CAN+USA sum, CAN+USA+MEX sum, or Neither # Note: accumulate the #of accurate NA def 'hits' if temp_can_usa_value == na_value: na_defn = 'CAN+USA' temp_can_usa += 1 elif temp_can_usa_mex_value == na_value: na_defn = 'CAN+USA+MEX' temp_can_usa_mex += 1 else: na_defn = 'Neither' temp_neither += 1 # Print table row for current year print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value, mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn)) # Determine the NA definition for this variable based on #of 'hits' per year max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither) if temp_can_usa == max_hits: na_defn = "CAN+USA" elif temp_can_usa_mex == max_hits: na_defn = "CAN+USA+MEX" else: na_defn = "Neither" print(f"North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither") print(f"Therefore we can conclude North America = {na_defn}\n") # Accumulate global totals using temp local accumulators for NA definition 'hits' total_can_usa += temp_can_usa total_can_usa_mex += temp_can_usa_mex total_neither += temp_neither # Sorter Helper for queried data by year def data_sort(elem): return elem['year'] ################################################################################################### main()
normal
{ "blob_id": "05186093820dffd047b0e7b5a69eb33f94f78b80", "index": 6787, "step-1": "<mask token>\n\n\ndef main():\n global dynamodb_client\n global dynamodb_resource\n global na_table\n global canada_table\n global usa_table\n global mexico_table\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n argc = len(sys.argv)\n bad_usage_flag = False\n if argc > 2:\n bad_usage_flag = True\n print('Error: Too many arguments.')\n if bad_usage_flag:\n sys.exit(USAGE_STATEMENT)\n dynamodb_client = boto3.client('dynamodb')\n dynamodb_resource = boto3.resource('dynamodb')\n try:\n dynamodb_client.list_tables()\n except Exception as e:\n print(\n \"Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')\"\n )\n sys.exit(f'[ERROR] {e}')\n err_output = ''\n table_list = dynamodb_client.list_tables()['TableNames']\n print(f'Existing Tables: {table_list}')\n for t in TABLE_LIST:\n if t not in table_list:\n err_output += (\n f\"Error: Invalid table name '{t}' - table does not exist.\\n\")\n if err_output != '':\n print(err_output.strip('\\n'))\n sys.exit(\n 'ERROR: Terminating program because unable to get table that does not exist.'\n )\n na_table = dynamodb_resource.Table(NORTH_AMERICA)\n canada_table = dynamodb_resource.Table(CANADA)\n usa_table = dynamodb_resource.Table(USA)\n mexico_table = dynamodb_resource.Table(MEXICO)\n commodity_encodings_dict = {}\n variable_encodings_dict = {}\n with open(ENCODINGS_CSV, 'r', newline='') as csv_file:\n csv_content = csv.reader(csv_file, delimiter=',')\n for row in csv_content:\n if row[2] == 'variable':\n variable_encodings_dict[row[0]] = row[1]\n elif row[2] == 'commodity':\n commodity_encodings_dict[row[0]] = row[1]\n csv_file.close()\n if argc == 2:\n commodity_input = sys.argv[1]\n else:\n commodity_input = input('Commodity: ').strip()\n if commodity_input.upper() in commodity_encodings_dict:\n commodity_code = commodity_input.upper()\n else:\n commodity_code = convert_dict_label_to_code_key(commodity_input,\n commodity_encodings_dict)\n print(f'ENCODING: {commodity_code}')\n if commodity_code is None:\n print(f\"Error: Commodity '{commodity_input}' was not found.\")\n sys.exit(\n 'ERROR: Terminating program because input does not exist as an encoding commodity code or label.'\n )\n total_can_usa = 0\n total_can_usa_mex = 0\n total_neither = 0\n for var in variable_encodings_dict.keys():\n if is_common_variable(commodity_code, var):\n output_table(commodity_code, var, variable_encodings_dict,\n commodity_encodings_dict)\n max_hits = max(total_can_usa, total_can_usa_mex, total_neither)\n if total_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif total_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither'\n )\n print(\n f'Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\\n'\n )\n\n\ndef convert_dict_label_to_code_key(label, encodings_dict):\n if label in list(encodings_dict.values()):\n return list(encodings_dict.keys())[list(encodings_dict.values()).\n index(label)]\n else:\n return None\n\n\n<mask token>\n\n\ndef has_commodity_and_variable(table, commodity_code, variable):\n response = table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))\n return response['Count'] > 0\n\n\ndef output_table(commodity_code, variable, variable_encodings_dict,\n commodity_encodings_dict):\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n temp_can_usa = 0\n temp_can_usa_mex = 0\n temp_neither = 0\n print(f'Variable: {variable_encodings_dict[variable]}')\n print(OUTPUT_FORMAT.format('Year', 'North America', 'Canada', 'USA',\n 'Mexico', 'CAN+USA', 'CAN+USA+MEX', 'NA Defn'))\n na_scan_data = na_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n can_scan_data = canada_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n usa_scan_data = usa_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n mex_scan_data = mexico_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n na_scan_data.sort(key=data_sort)\n can_scan_data.sort(key=data_sort)\n usa_scan_data.sort(key=data_sort)\n mex_scan_data.sort(key=data_sort)\n for year in YEAR_RANGE:\n i = year - 2010\n na_value = na_scan_data[i]['value'] * 10 ** na_scan_data[i]['mfactor']\n can_value = can_scan_data[i]['value'] * 10 ** can_scan_data[i][\n 'mfactor']\n usa_value = usa_scan_data[i]['value'] * 10 ** usa_scan_data[i][\n 'mfactor']\n mex_value = mex_scan_data[i]['value'] * 10 ** mex_scan_data[i][\n 'mfactor']\n temp_can_usa_value = can_value + usa_value\n temp_can_usa_mex_value = can_value + usa_value + mex_value\n if temp_can_usa_value == na_value:\n na_defn = 'CAN+USA'\n temp_can_usa += 1\n elif temp_can_usa_mex_value == na_value:\n na_defn = 'CAN+USA+MEX'\n temp_can_usa_mex += 1\n else:\n na_defn = 'Neither'\n temp_neither += 1\n print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value,\n mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn))\n max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither)\n if temp_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif temp_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither'\n )\n print(f'Therefore we can conclude North America = {na_defn}\\n')\n total_can_usa += temp_can_usa\n total_can_usa_mex += temp_can_usa_mex\n total_neither += temp_neither\n\n\ndef data_sort(elem):\n return elem['year']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n global dynamodb_client\n global dynamodb_resource\n global na_table\n global canada_table\n global usa_table\n global mexico_table\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n argc = len(sys.argv)\n bad_usage_flag = False\n if argc > 2:\n bad_usage_flag = True\n print('Error: Too many arguments.')\n if bad_usage_flag:\n sys.exit(USAGE_STATEMENT)\n dynamodb_client = boto3.client('dynamodb')\n dynamodb_resource = boto3.resource('dynamodb')\n try:\n dynamodb_client.list_tables()\n except Exception as e:\n print(\n \"Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')\"\n )\n sys.exit(f'[ERROR] {e}')\n err_output = ''\n table_list = dynamodb_client.list_tables()['TableNames']\n print(f'Existing Tables: {table_list}')\n for t in TABLE_LIST:\n if t not in table_list:\n err_output += (\n f\"Error: Invalid table name '{t}' - table does not exist.\\n\")\n if err_output != '':\n print(err_output.strip('\\n'))\n sys.exit(\n 'ERROR: Terminating program because unable to get table that does not exist.'\n )\n na_table = dynamodb_resource.Table(NORTH_AMERICA)\n canada_table = dynamodb_resource.Table(CANADA)\n usa_table = dynamodb_resource.Table(USA)\n mexico_table = dynamodb_resource.Table(MEXICO)\n commodity_encodings_dict = {}\n variable_encodings_dict = {}\n with open(ENCODINGS_CSV, 'r', newline='') as csv_file:\n csv_content = csv.reader(csv_file, delimiter=',')\n for row in csv_content:\n if row[2] == 'variable':\n variable_encodings_dict[row[0]] = row[1]\n elif row[2] == 'commodity':\n commodity_encodings_dict[row[0]] = row[1]\n csv_file.close()\n if argc == 2:\n commodity_input = sys.argv[1]\n else:\n commodity_input = input('Commodity: ').strip()\n if commodity_input.upper() in commodity_encodings_dict:\n commodity_code = commodity_input.upper()\n else:\n commodity_code = convert_dict_label_to_code_key(commodity_input,\n commodity_encodings_dict)\n print(f'ENCODING: {commodity_code}')\n if commodity_code is None:\n print(f\"Error: Commodity '{commodity_input}' was not found.\")\n sys.exit(\n 'ERROR: Terminating program because input does not exist as an encoding commodity code or label.'\n )\n total_can_usa = 0\n total_can_usa_mex = 0\n total_neither = 0\n for var in variable_encodings_dict.keys():\n if is_common_variable(commodity_code, var):\n output_table(commodity_code, var, variable_encodings_dict,\n commodity_encodings_dict)\n max_hits = max(total_can_usa, total_can_usa_mex, total_neither)\n if total_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif total_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither'\n )\n print(\n f'Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\\n'\n )\n\n\ndef convert_dict_label_to_code_key(label, encodings_dict):\n if label in list(encodings_dict.values()):\n return list(encodings_dict.keys())[list(encodings_dict.values()).\n index(label)]\n else:\n return None\n\n\ndef is_common_variable(commodity_code, variable):\n return has_commodity_and_variable(na_table, commodity_code, variable\n ) and has_commodity_and_variable(canada_table, commodity_code, variable\n ) and has_commodity_and_variable(usa_table, commodity_code, variable\n ) and has_commodity_and_variable(mexico_table, commodity_code, variable\n )\n\n\ndef has_commodity_and_variable(table, commodity_code, variable):\n response = table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))\n return response['Count'] > 0\n\n\ndef output_table(commodity_code, variable, variable_encodings_dict,\n commodity_encodings_dict):\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n temp_can_usa = 0\n temp_can_usa_mex = 0\n temp_neither = 0\n print(f'Variable: {variable_encodings_dict[variable]}')\n print(OUTPUT_FORMAT.format('Year', 'North America', 'Canada', 'USA',\n 'Mexico', 'CAN+USA', 'CAN+USA+MEX', 'NA Defn'))\n na_scan_data = na_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n can_scan_data = canada_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n usa_scan_data = usa_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n mex_scan_data = mexico_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n na_scan_data.sort(key=data_sort)\n can_scan_data.sort(key=data_sort)\n usa_scan_data.sort(key=data_sort)\n mex_scan_data.sort(key=data_sort)\n for year in YEAR_RANGE:\n i = year - 2010\n na_value = na_scan_data[i]['value'] * 10 ** na_scan_data[i]['mfactor']\n can_value = can_scan_data[i]['value'] * 10 ** can_scan_data[i][\n 'mfactor']\n usa_value = usa_scan_data[i]['value'] * 10 ** usa_scan_data[i][\n 'mfactor']\n mex_value = mex_scan_data[i]['value'] * 10 ** mex_scan_data[i][\n 'mfactor']\n temp_can_usa_value = can_value + usa_value\n temp_can_usa_mex_value = can_value + usa_value + mex_value\n if temp_can_usa_value == na_value:\n na_defn = 'CAN+USA'\n temp_can_usa += 1\n elif temp_can_usa_mex_value == na_value:\n na_defn = 'CAN+USA+MEX'\n temp_can_usa_mex += 1\n else:\n na_defn = 'Neither'\n temp_neither += 1\n print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value,\n mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn))\n max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither)\n if temp_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif temp_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither'\n )\n print(f'Therefore we can conclude North America = {na_defn}\\n')\n total_can_usa += temp_can_usa\n total_can_usa_mex += temp_can_usa_mex\n total_neither += temp_neither\n\n\ndef data_sort(elem):\n return elem['year']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n global dynamodb_client\n global dynamodb_resource\n global na_table\n global canada_table\n global usa_table\n global mexico_table\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n argc = len(sys.argv)\n bad_usage_flag = False\n if argc > 2:\n bad_usage_flag = True\n print('Error: Too many arguments.')\n if bad_usage_flag:\n sys.exit(USAGE_STATEMENT)\n dynamodb_client = boto3.client('dynamodb')\n dynamodb_resource = boto3.resource('dynamodb')\n try:\n dynamodb_client.list_tables()\n except Exception as e:\n print(\n \"Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')\"\n )\n sys.exit(f'[ERROR] {e}')\n err_output = ''\n table_list = dynamodb_client.list_tables()['TableNames']\n print(f'Existing Tables: {table_list}')\n for t in TABLE_LIST:\n if t not in table_list:\n err_output += (\n f\"Error: Invalid table name '{t}' - table does not exist.\\n\")\n if err_output != '':\n print(err_output.strip('\\n'))\n sys.exit(\n 'ERROR: Terminating program because unable to get table that does not exist.'\n )\n na_table = dynamodb_resource.Table(NORTH_AMERICA)\n canada_table = dynamodb_resource.Table(CANADA)\n usa_table = dynamodb_resource.Table(USA)\n mexico_table = dynamodb_resource.Table(MEXICO)\n commodity_encodings_dict = {}\n variable_encodings_dict = {}\n with open(ENCODINGS_CSV, 'r', newline='') as csv_file:\n csv_content = csv.reader(csv_file, delimiter=',')\n for row in csv_content:\n if row[2] == 'variable':\n variable_encodings_dict[row[0]] = row[1]\n elif row[2] == 'commodity':\n commodity_encodings_dict[row[0]] = row[1]\n csv_file.close()\n if argc == 2:\n commodity_input = sys.argv[1]\n else:\n commodity_input = input('Commodity: ').strip()\n if commodity_input.upper() in commodity_encodings_dict:\n commodity_code = commodity_input.upper()\n else:\n commodity_code = convert_dict_label_to_code_key(commodity_input,\n commodity_encodings_dict)\n print(f'ENCODING: {commodity_code}')\n if commodity_code is None:\n print(f\"Error: Commodity '{commodity_input}' was not found.\")\n sys.exit(\n 'ERROR: Terminating program because input does not exist as an encoding commodity code or label.'\n )\n total_can_usa = 0\n total_can_usa_mex = 0\n total_neither = 0\n for var in variable_encodings_dict.keys():\n if is_common_variable(commodity_code, var):\n output_table(commodity_code, var, variable_encodings_dict,\n commodity_encodings_dict)\n max_hits = max(total_can_usa, total_can_usa_mex, total_neither)\n if total_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif total_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither'\n )\n print(\n f'Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\\n'\n )\n\n\ndef convert_dict_label_to_code_key(label, encodings_dict):\n if label in list(encodings_dict.values()):\n return list(encodings_dict.keys())[list(encodings_dict.values()).\n index(label)]\n else:\n return None\n\n\ndef is_common_variable(commodity_code, variable):\n return has_commodity_and_variable(na_table, commodity_code, variable\n ) and has_commodity_and_variable(canada_table, commodity_code, variable\n ) and has_commodity_and_variable(usa_table, commodity_code, variable\n ) and has_commodity_and_variable(mexico_table, commodity_code, variable\n )\n\n\ndef has_commodity_and_variable(table, commodity_code, variable):\n response = table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))\n return response['Count'] > 0\n\n\ndef output_table(commodity_code, variable, variable_encodings_dict,\n commodity_encodings_dict):\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n temp_can_usa = 0\n temp_can_usa_mex = 0\n temp_neither = 0\n print(f'Variable: {variable_encodings_dict[variable]}')\n print(OUTPUT_FORMAT.format('Year', 'North America', 'Canada', 'USA',\n 'Mexico', 'CAN+USA', 'CAN+USA+MEX', 'NA Defn'))\n na_scan_data = na_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n can_scan_data = canada_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n usa_scan_data = usa_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n mex_scan_data = mexico_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n na_scan_data.sort(key=data_sort)\n can_scan_data.sort(key=data_sort)\n usa_scan_data.sort(key=data_sort)\n mex_scan_data.sort(key=data_sort)\n for year in YEAR_RANGE:\n i = year - 2010\n na_value = na_scan_data[i]['value'] * 10 ** na_scan_data[i]['mfactor']\n can_value = can_scan_data[i]['value'] * 10 ** can_scan_data[i][\n 'mfactor']\n usa_value = usa_scan_data[i]['value'] * 10 ** usa_scan_data[i][\n 'mfactor']\n mex_value = mex_scan_data[i]['value'] * 10 ** mex_scan_data[i][\n 'mfactor']\n temp_can_usa_value = can_value + usa_value\n temp_can_usa_mex_value = can_value + usa_value + mex_value\n if temp_can_usa_value == na_value:\n na_defn = 'CAN+USA'\n temp_can_usa += 1\n elif temp_can_usa_mex_value == na_value:\n na_defn = 'CAN+USA+MEX'\n temp_can_usa_mex += 1\n else:\n na_defn = 'Neither'\n temp_neither += 1\n print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value,\n mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn))\n max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither)\n if temp_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif temp_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither'\n )\n print(f'Therefore we can conclude North America = {na_defn}\\n')\n total_can_usa += temp_can_usa\n total_can_usa_mex += temp_can_usa_mex\n total_neither += temp_neither\n\n\ndef data_sort(elem):\n return elem['year']\n\n\nmain()\n", "step-4": "<mask token>\nimport boto3\nimport csv\nimport sys\nfrom boto3.dynamodb.conditions import Key, Attr\nNORTH_AMERICA = 'northamerica'\nCANADA = 'canada'\nUSA = 'usa'\nMEXICO = 'mexico'\nTABLE_LIST = [NORTH_AMERICA, CANADA, USA, MEXICO]\nYEAR_RANGE = range(2010, 2030)\nOUTPUT_FORMAT = '{:<8}{:<18}{:<18}{:<18}{:<18}{:<18}{:<18}{:<10}'\nENCODINGS_CSV = 'encodings.csv'\nUSAGE_STATEMENT = 'Usage: py queryOECD.py <commodity-code|commodity-label>'\n\n\ndef main():\n global dynamodb_client\n global dynamodb_resource\n global na_table\n global canada_table\n global usa_table\n global mexico_table\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n argc = len(sys.argv)\n bad_usage_flag = False\n if argc > 2:\n bad_usage_flag = True\n print('Error: Too many arguments.')\n if bad_usage_flag:\n sys.exit(USAGE_STATEMENT)\n dynamodb_client = boto3.client('dynamodb')\n dynamodb_resource = boto3.resource('dynamodb')\n try:\n dynamodb_client.list_tables()\n except Exception as e:\n print(\n \"Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')\"\n )\n sys.exit(f'[ERROR] {e}')\n err_output = ''\n table_list = dynamodb_client.list_tables()['TableNames']\n print(f'Existing Tables: {table_list}')\n for t in TABLE_LIST:\n if t not in table_list:\n err_output += (\n f\"Error: Invalid table name '{t}' - table does not exist.\\n\")\n if err_output != '':\n print(err_output.strip('\\n'))\n sys.exit(\n 'ERROR: Terminating program because unable to get table that does not exist.'\n )\n na_table = dynamodb_resource.Table(NORTH_AMERICA)\n canada_table = dynamodb_resource.Table(CANADA)\n usa_table = dynamodb_resource.Table(USA)\n mexico_table = dynamodb_resource.Table(MEXICO)\n commodity_encodings_dict = {}\n variable_encodings_dict = {}\n with open(ENCODINGS_CSV, 'r', newline='') as csv_file:\n csv_content = csv.reader(csv_file, delimiter=',')\n for row in csv_content:\n if row[2] == 'variable':\n variable_encodings_dict[row[0]] = row[1]\n elif row[2] == 'commodity':\n commodity_encodings_dict[row[0]] = row[1]\n csv_file.close()\n if argc == 2:\n commodity_input = sys.argv[1]\n else:\n commodity_input = input('Commodity: ').strip()\n if commodity_input.upper() in commodity_encodings_dict:\n commodity_code = commodity_input.upper()\n else:\n commodity_code = convert_dict_label_to_code_key(commodity_input,\n commodity_encodings_dict)\n print(f'ENCODING: {commodity_code}')\n if commodity_code is None:\n print(f\"Error: Commodity '{commodity_input}' was not found.\")\n sys.exit(\n 'ERROR: Terminating program because input does not exist as an encoding commodity code or label.'\n )\n total_can_usa = 0\n total_can_usa_mex = 0\n total_neither = 0\n for var in variable_encodings_dict.keys():\n if is_common_variable(commodity_code, var):\n output_table(commodity_code, var, variable_encodings_dict,\n commodity_encodings_dict)\n max_hits = max(total_can_usa, total_can_usa_mex, total_neither)\n if total_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif total_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither'\n )\n print(\n f'Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\\n'\n )\n\n\ndef convert_dict_label_to_code_key(label, encodings_dict):\n if label in list(encodings_dict.values()):\n return list(encodings_dict.keys())[list(encodings_dict.values()).\n index(label)]\n else:\n return None\n\n\ndef is_common_variable(commodity_code, variable):\n return has_commodity_and_variable(na_table, commodity_code, variable\n ) and has_commodity_and_variable(canada_table, commodity_code, variable\n ) and has_commodity_and_variable(usa_table, commodity_code, variable\n ) and has_commodity_and_variable(mexico_table, commodity_code, variable\n )\n\n\ndef has_commodity_and_variable(table, commodity_code, variable):\n response = table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))\n return response['Count'] > 0\n\n\ndef output_table(commodity_code, variable, variable_encodings_dict,\n commodity_encodings_dict):\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n temp_can_usa = 0\n temp_can_usa_mex = 0\n temp_neither = 0\n print(f'Variable: {variable_encodings_dict[variable]}')\n print(OUTPUT_FORMAT.format('Year', 'North America', 'Canada', 'USA',\n 'Mexico', 'CAN+USA', 'CAN+USA+MEX', 'NA Defn'))\n na_scan_data = na_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n can_scan_data = canada_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n usa_scan_data = usa_table.scan(FilterExpression=Attr('commodity').eq(\n commodity_code) & Attr('variable').eq(variable))['Items']\n mex_scan_data = mexico_table.scan(FilterExpression=Attr('commodity').eq\n (commodity_code) & Attr('variable').eq(variable))['Items']\n na_scan_data.sort(key=data_sort)\n can_scan_data.sort(key=data_sort)\n usa_scan_data.sort(key=data_sort)\n mex_scan_data.sort(key=data_sort)\n for year in YEAR_RANGE:\n i = year - 2010\n na_value = na_scan_data[i]['value'] * 10 ** na_scan_data[i]['mfactor']\n can_value = can_scan_data[i]['value'] * 10 ** can_scan_data[i][\n 'mfactor']\n usa_value = usa_scan_data[i]['value'] * 10 ** usa_scan_data[i][\n 'mfactor']\n mex_value = mex_scan_data[i]['value'] * 10 ** mex_scan_data[i][\n 'mfactor']\n temp_can_usa_value = can_value + usa_value\n temp_can_usa_mex_value = can_value + usa_value + mex_value\n if temp_can_usa_value == na_value:\n na_defn = 'CAN+USA'\n temp_can_usa += 1\n elif temp_can_usa_mex_value == na_value:\n na_defn = 'CAN+USA+MEX'\n temp_can_usa_mex += 1\n else:\n na_defn = 'Neither'\n temp_neither += 1\n print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value,\n mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn))\n max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither)\n if temp_can_usa == max_hits:\n na_defn = 'CAN+USA'\n elif temp_can_usa_mex == max_hits:\n na_defn = 'CAN+USA+MEX'\n else:\n na_defn = 'Neither'\n print(\n f'North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither'\n )\n print(f'Therefore we can conclude North America = {na_defn}\\n')\n total_can_usa += temp_can_usa\n total_can_usa_mex += temp_can_usa_mex\n total_neither += temp_neither\n\n\ndef data_sort(elem):\n return elem['year']\n\n\nmain()\n", "step-5": "#!/usr/bin/env python\n\n'''\n@author : Mitchell Van Braeckel\n@id : 1002297\n@date : 10/10/2020\n@version : python 3.8-32 / python 3.8.5\n@course : CIS*4010 Cloud Computing\n@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD\n\n@note :\n Description: There are many CSV files containing info from the OECD about agricultural production, each for various regions around the world.\n Queries all 4 tables (northamerica, canada, usa, mexico -table names) based on a commodity (code key or label),\n looking for all common variables between CAN, USA, and MEX, outputting all results (for all years) in a table,\n then output the specific NA definition 'hit' results and probable conclusion for NA definition per variable,\n as well as an overall conclusion for NA definition\n\n NOTE: forgot to add ability to specify commodity as cmd line arg instead of STDIN\n\n NOTE: assume year range is 2010 to 2029 (inclusive)\n NOTE: assume perfect user input for commodity and variables\n - however, if input commodity that's not a valid commodity code or label, exits program with error message\n NOTE: NA definition hit refers to if the calculated sum from different tables of CAN, USA, MEX are equal to that of NA (CAN+USA, CAN+USA+MEX, or Neither)\n'''\n\n'''\n IMPROVEMENT: Use 'encodings' table instead of the CSV file\n'''\n\n############################################# IMPORTS #############################################\n\n# IMPORTS - 'pip install <import-package>'\nimport boto3\nimport csv\nimport sys\nfrom boto3.dynamodb.conditions import Key, Attr\n\n############################################ CONSTANTS ############################################\n\n# TABLE CONSTANTS\nNORTH_AMERICA = \"northamerica\"\nCANADA = \"canada\"\nUSA = \"usa\"\nMEXICO = \"mexico\"\nTABLE_LIST = [NORTH_AMERICA, CANADA, USA, MEXICO]\nYEAR_RANGE = range(2010, 2030)\n\n# OTHER CONSTANTS\nOUTPUT_FORMAT = \"{:<8}{:<18}{:<18}{:<18}{:<18}{:<18}{:<18}{:<10}\"\nENCODINGS_CSV = \"encodings.csv\"\n#ENCODINGS_TABLE_NAME = \"encodings\"\nUSAGE_STATEMENT = \"Usage: py queryOECD.py <commodity-code|commodity-label>\"\n\n############################## STATE VARIABLES, INITIALIZATION, MAIN ##############################\n\n# MAIN - Declares global vars and state here, then ask for commodity (check both key/label),\n# look for all common variables between CAN, USA, and MEX, outputting all results (for all years) in a table,\n# then output the specific NA definition 'hit' results and probable conclusion for NA definition\ndef main():\n #globals\n global dynamodb_client\n global dynamodb_resource\n global na_table\n global canada_table\n global usa_table\n global mexico_table\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n\n # ========== ARGUMENTS ==========\n\n # Collect command line arguments when executing this python script\n argc = len(sys.argv)\n bad_usage_flag = False\n \n # Check #of args (deal with it later tho)\n # 1 optional arg for commodity, otherwise prompt user for it\n if argc > 2:\n bad_usage_flag = True\n print(\"Error: Too many arguments.\")\n \n # Exit with usage statement if flag has been triggered for any reason\n if bad_usage_flag:\n sys.exit(USAGE_STATEMENT)\n\n # ========== AWS DYNAMO DB ==========\n\n # Init AWS DynamoDB client and resource (NOTE: these are global)\n dynamodb_client = boto3.client(\"dynamodb\")\n dynamodb_resource = boto3.resource(\"dynamodb\")\n\n # Validate AWS DynamoDB credentials (by testing if 'list_tables()' works)\n try:\n dynamodb_client.list_tables()\n except Exception as e:\n print(\"Error: Invalid or expired credentials (or insufficient permissions to call 'list_tables()')\")\n sys.exit(f\"[ERROR] {e}\")\n\n # Check the 4 tables exist, then get them all\n err_output = \"\"\n table_list = dynamodb_client.list_tables()['TableNames']\n\n print(f\"Existing Tables: {table_list}\")\n\n for t in TABLE_LIST:\n if t not in table_list:\n err_output += f\"Error: Invalid table name '{t}' - table does not exist.\\n\"\n \n # Print all tables that did not exist, then exit\n if err_output != \"\":\n print(err_output.strip(\"\\n\"))\n sys.exit(\"ERROR: Terminating program because unable to get table that does not exist.\")\n\n # Get all tables (after checking they exist) (NOTE: these are global)\n na_table = dynamodb_resource.Table(NORTH_AMERICA)\n canada_table = dynamodb_resource.Table(CANADA)\n usa_table = dynamodb_resource.Table(USA)\n mexico_table = dynamodb_resource.Table(MEXICO)\n\n # Open the encodings CSV file and read its contents\n commodity_encodings_dict = {}\n variable_encodings_dict = {}\n with open(ENCODINGS_CSV, \"r\", newline='') as csv_file:\n csv_content = csv.reader(csv_file, delimiter=',')\n\n # if field is var or commodity, set a key-value pair between code and label (in the respective map)\n for row in csv_content:\n if row[2] == \"variable\":\n variable_encodings_dict[row[0]] = row[1]\n elif row[2] == \"commodity\":\n commodity_encodings_dict[row[0]] = row[1]\n csv_file.close()\n\n # Check args for commodity now, otherwise prompt user\n if argc == 2:\n commodity_input = sys.argv[1]\n else:\n # Ask user for commodity\n commodity_input = input(\"Commodity: \").strip()\n \n # Check if input exists as code key, otherwise try to convert assumed label to code key (if not a label, code will be None after)\n if commodity_input.upper() in commodity_encodings_dict:\n commodity_code = commodity_input.upper()\n else:\n commodity_code = convert_dict_label_to_code_key(commodity_input, commodity_encodings_dict)\n\n # Check if commodity found a code or None\n print(f\"ENCODING: {commodity_code}\")\n if commodity_code is None:\n print(f\"Error: Commodity '{commodity_input}' was not found.\")\n sys.exit(\"ERROR: Terminating program because input does not exist as an encoding commodity code or label.\")\n\n # Init total accumulators for each category\n total_can_usa = 0\n total_can_usa_mex = 0\n total_neither = 0\n\n # iterate through each variable and analyze data (if applicable)\n for var in variable_encodings_dict.keys():\n if is_common_variable(commodity_code, var):\n output_table(commodity_code, var, variable_encodings_dict, commodity_encodings_dict)\n\n # Determine the NA definition for this variable based on #of 'hits' per year\n max_hits = max(total_can_usa, total_can_usa_mex, total_neither)\n if total_can_usa == max_hits:\n na_defn = \"CAN+USA\"\n elif total_can_usa_mex == max_hits:\n na_defn = \"CAN+USA+MEX\"\n else:\n na_defn = \"Neither\"\n\n print(f\"Overall North America Definition Results: {total_can_usa} CAN+USA, {total_can_usa_mex} CAN+USA+MEX, {total_neither} Neither\")\n print(f\"Conclusion for all {commodity_encodings_dict[commodity_code]} variables = {na_defn}\\n\")\n\n############################################ FUNCTIONS ############################################\n\n# Converts the label of a dict into its code key, returns None if not a label\ndef convert_dict_label_to_code_key(label, encodings_dict):\n # Get the key of the label if the label exists in the dict as a value\n if label in list(encodings_dict.values()):\n return list(encodings_dict.keys())[list(encodings_dict.values()).index(label)]\n else:\n return None\n\n# Check if a commodity code + variable is common across all 4 tables, return true if it is\ndef is_common_variable(commodity_code, variable):\n return (has_commodity_and_variable(na_table, commodity_code, variable) and\n has_commodity_and_variable(canada_table, commodity_code, variable) and\n has_commodity_and_variable(usa_table, commodity_code, variable) and\n has_commodity_and_variable(mexico_table, commodity_code, variable))\n\n# Check if a table has data for commodity code + variable (ie. scan table), returns true if at least 1 item is found\ndef has_commodity_and_variable(table, commodity_code, variable):\n response = table.scan(\n FilterExpression = Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)\n )\n return response['Count'] > 0\n\n# Retrieves and outputs table data based on commodity and variable and analyze for NA definition\ndef output_table(commodity_code, variable, variable_encodings_dict, commodity_encodings_dict):\n # Bring in globals to modify\n global total_can_usa\n global total_can_usa_mex\n global total_neither\n\n # Init local accumulators\n temp_can_usa = 0\n temp_can_usa_mex = 0\n temp_neither = 0\n\n # Print table headers: common variable (for commodity code) across all 4 tables, and table column names\n print(f\"Variable: {variable_encodings_dict[variable]}\")\n print(OUTPUT_FORMAT.format(\"Year\", \"North America\", \"Canada\", \"USA\", \"Mexico\", \"CAN+USA\", \"CAN+USA+MEX\", \"NA Defn\"))\n\n # Retrieve all data, from all years (ie. the items from the scan)\n na_scan_data = na_table.scan(\n FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)\n )['Items']\n can_scan_data = canada_table.scan(\n FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)\n )['Items']\n usa_scan_data = usa_table.scan(\n FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)\n )['Items']\n mex_scan_data = mexico_table.scan(\n FilterExpression=Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)\n )['Items']\n\n # Sort each scan data by key\n na_scan_data.sort(key=data_sort)\n can_scan_data.sort(key=data_sort)\n usa_scan_data.sort(key=data_sort)\n mex_scan_data.sort(key=data_sort)\n\n # Analyze data\n for year in YEAR_RANGE:\n # For each relevant year, calculate total value using multiplication factor\n i = year - 2010\n na_value = na_scan_data[i]['value'] * (10**na_scan_data[i]['mfactor'])\n can_value = can_scan_data[i]['value'] * (10**can_scan_data[i]['mfactor'])\n usa_value = usa_scan_data[i]['value'] * (10**usa_scan_data[i]['mfactor'])\n mex_value = mex_scan_data[i]['value'] * (10**mex_scan_data[i]['mfactor'])\n\n # Calc temp sums for the CAN+USA and CAN+USA+MEX columns\n temp_can_usa_value = can_value + usa_value\n temp_can_usa_mex_value = can_value + usa_value + mex_value\n\n # Determine OECD def of NA, by checking if the temp calc sums from scan data calc values are equivalent to CAN+USA sum, CAN+USA+MEX sum, or Neither\n # Note: accumulate the #of accurate NA def 'hits'\n if temp_can_usa_value == na_value:\n na_defn = 'CAN+USA'\n temp_can_usa += 1\n elif temp_can_usa_mex_value == na_value:\n na_defn = 'CAN+USA+MEX'\n temp_can_usa_mex += 1\n else:\n na_defn = 'Neither'\n temp_neither += 1\n\n # Print table row for current year\n print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value, mex_value, temp_can_usa_value, temp_can_usa_mex_value, na_defn))\n\n # Determine the NA definition for this variable based on #of 'hits' per year\n max_hits = max(temp_can_usa, temp_can_usa_mex, temp_neither)\n if temp_can_usa == max_hits:\n na_defn = \"CAN+USA\"\n elif temp_can_usa_mex == max_hits:\n na_defn = \"CAN+USA+MEX\"\n else:\n na_defn = \"Neither\"\n\n print(f\"North America Definition Results: {temp_can_usa} CAN+USA, {temp_can_usa_mex} CAN+USA+MEX, {temp_neither} Neither\")\n print(f\"Therefore we can conclude North America = {na_defn}\\n\")\n\n # Accumulate global totals using temp local accumulators for NA definition 'hits'\n total_can_usa += temp_can_usa\n total_can_usa_mex += temp_can_usa_mex\n total_neither += temp_neither\n\n# Sorter Helper for queried data by year\ndef data_sort(elem):\n return elem['year']\n\n###################################################################################################\n\nmain()\n", "step-ids": [ 5, 6, 7, 9, 10 ] }
[ 5, 6, 7, 9, 10 ]
import math print(dir(math)) # Prints a list of entities residing in the math module
normal
{ "blob_id": "94056e8920d265831da67bd1d999330a47a7ef0d", "index": 1991, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(dir(math))\n", "step-3": "import math\nprint(dir(math))\n", "step-4": "import math\nprint(dir(math))\n\n# Prints a list of entities residing in the math module", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#Voir paragraphe "3.6 Normalizing Text", page 107 de NLP with Python from nltk.stem.snowball import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer # Il faut retirer les stopwords avant de stemmer stemmer = SnowballStemmer("english", ignore_stopwords=True) lemmatizer = WordNetLemmatizer() source = ["having", "have", "needs", "need", "inflation", "inflate", "developments", "developing", "aggregation", "aggregated", "population", "poverty", "poor", "poorer", "men", "man", "gases", "gas", "sues", "utilized", "damaged"] stems1 = [stemmer.stem(word) for word in source] stems2 = [lemmatizer.lemmatize(word) for word in source] stems3 = [stemmer.stem(word) for word in stems2] print(stems1) print(stems2) print(stems3)
normal
{ "blob_id": "1f1677687ba6ca47b18728b0fd3b9926436e9796", "index": 2949, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-3": "<mask token>\nstemmer = SnowballStemmer('english', ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\nsource = ['having', 'have', 'needs', 'need', 'inflation', 'inflate',\n 'developments', 'developing', 'aggregation', 'aggregated', 'population',\n 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues',\n 'utilized', 'damaged']\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-4": "from nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\nstemmer = SnowballStemmer('english', ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\nsource = ['having', 'have', 'needs', 'need', 'inflation', 'inflate',\n 'developments', 'developing', 'aggregation', 'aggregated', 'population',\n 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues',\n 'utilized', 'damaged']\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-5": "#Voir paragraphe \"3.6 Normalizing Text\", page 107 de NLP with Python\n\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n# Il faut retirer les stopwords avant de stemmer\n\nstemmer = SnowballStemmer(\"english\", ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\n\nsource = [\"having\", \"have\", \"needs\", \"need\", \"inflation\", \"inflate\", \"developments\", \"developing\", \"aggregation\",\n \"aggregated\", \"population\", \"poverty\", \"poor\", \"poorer\", \"men\", \"man\", \"gases\", \"gas\", \"sues\", \"utilized\",\n \"damaged\"]\n\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\n\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
linha = input().split() a = float(linha[0]) b = float(linha[1]) c = float(linha[2]) t = (a*c)/2 print('TRIANGULO: {:.3f}'.format(t)) pi = 3.14159 print("CIRCULO: {:.3f}".format(pi*c**2)) print('TRAPEZIO: {:.3f}'.format( ((a+b)*c)/2 )) print("QUADRADO: {:.3f}".format(b**2)) print("RETANGULO: {:.3f}".format(a*b))
normal
{ "blob_id": "d44d9003e9b86722a0fc1dfe958de462db9cd5f1", "index": 1670, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('TRIANGULO: {:.3f}'.format(t))\n<mask token>\nprint('CIRCULO: {:.3f}'.format(pi * c ** 2))\nprint('TRAPEZIO: {:.3f}'.format((a + b) * c / 2))\nprint('QUADRADO: {:.3f}'.format(b ** 2))\nprint('RETANGULO: {:.3f}'.format(a * b))\n", "step-3": "linha = input().split()\na = float(linha[0])\nb = float(linha[1])\nc = float(linha[2])\nt = a * c / 2\nprint('TRIANGULO: {:.3f}'.format(t))\npi = 3.14159\nprint('CIRCULO: {:.3f}'.format(pi * c ** 2))\nprint('TRAPEZIO: {:.3f}'.format((a + b) * c / 2))\nprint('QUADRADO: {:.3f}'.format(b ** 2))\nprint('RETANGULO: {:.3f}'.format(a * b))\n", "step-4": "linha = input().split()\n\na = float(linha[0])\nb = float(linha[1])\nc = float(linha[2])\n\nt = (a*c)/2\n\nprint('TRIANGULO: {:.3f}'.format(t))\n\npi = 3.14159\n\nprint(\"CIRCULO: {:.3f}\".format(pi*c**2))\n\nprint('TRAPEZIO: {:.3f}'.format( ((a+b)*c)/2 ))\n\nprint(\"QUADRADO: {:.3f}\".format(b**2))\n\nprint(\"RETANGULO: {:.3f}\".format(a*b))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" """ import cPickle as pickle def convert_cpu_stats_to_num_array(cpuStats): """ Given a list of statistics (tuples[timestamp, total_cpu, kernel_cpu, vm, rss]) Return five numarrays """ print "Converting cpus stats into numpy array" c0 = [] c1 = [] c2 = [] c3 = [] c4 = [] # TODO - need a pythonic/numpy way for corner turning gc.disable() for c in cpuStats: c0.append(c[0]) c1.append(c[1]) c2.append(c[2]) c3.append(c[3]) c4.append(c[4]) gc.enable() return (np.array(c0), np.array(c1), np.array(c2), np.array(c3), np.array(c4)) def plot_cpu_mem_usage_from_file(cpufile, figfile, stt=None, x_max=None, time_label=None): """ Plot CPU and memory usage from a cpu log file parameters: cpufile: the full path of the cpu log file (string) figfile: the full path of the plot file (string) stt: start time stamp in seconds (Integer, None if let it done automatically) x_max: the duration of the time axis in seconds (Integer, None automatically set) time_label: full path to the application activity log (string) each line is something like this: 2014-08-17 04:44:24 major cycle 3 2014-08-17 04:45:44 make image If set, the plot tries to draw vertical lines along the time axis to show these activities This is an experimental feature, need more work """ reList = [] if os.path.exists(cpufile): try: pkl_file = open(cpufile, 'rb') print 'Loading CPU stats object from file %s' % cpufile cpuStatsList = pickle.load(pkl_file) pkl_file.close() if cpuStatsList == None: raise Exception("The CPU stats object is None when reading from the file") reList += cpuStatsList #return cpuStatsList except Exception, e: ex = str(e) import traceback print 'Fail to load the CPU stats from file %s: %s' % (cpufile, ex) traceback.print_exc() raise e else: print 'Cannot locate the CPU stats file %s' % cpufile fig = pl.figure() plot_cpu_mem_usage(fig, x_max, reList, stt, standalone = True, time_label = time_label) #fig.savefig('/tmp/cpu_mem_usage.pdf') fig.savefig(figfile) pl.close(fig) def plot_cpu_mem_usage(fig, cpuStats, x_max = None, stt = None, standalone = False, time_label = None): if standalone: ax1 = fig.add_subplot(111) else: ax1 = fig.add_subplot(211) ax1.set_xlabel('Time (seconds)', fontsize = 9) ax1.set_ylabel('CPU usage (% of Wall Clock time)', fontsize = 9) ax1.set_title('CPU and Memory usage', fontsize=10) ax1.tick_params(axis='both', which='major', labelsize=8) ax1.tick_params(axis='both', which='minor', labelsize=6) # get the data in numpy array ta, tc, kc, vm, rss = convert_cpu_stats_to_num_array(cpuStats) if stt is None: stt = ta ta -= stt st = int(ta[0]) ed = int(ta[-1]) if x_max is None: x_max = ed elif ed > x_max: x_max = ed # create x-axis (whole integer seconds) between st and ed # x = np.r_[st:ed + 1] x = ta.astype(np.int64) # plot the total cpu ax1.plot(x, tc, color = 'g', linestyle = '-', label = 'total cpu') # plot the kernel cpu ax1.plot(x, kc, color = 'r', linestyle = '--', label = 'kernel cpu') # plot the virtual mem ax2 = ax1.twinx() ax2.set_ylabel('Memory usage (MB)', fontsize = 9) ax2.tick_params(axis='y', which='major', labelsize=8) ax2.tick_params(axis='y', which='minor', labelsize=6) ax2.plot(x, vm / 1024.0 ** 2, color = 'b', linestyle = ':', label = 'virtual memory') # plot the rss ax2.plot(x, rss / 1024.0 ** 2, color = 'k', linestyle = '-.', label = 'resident memory') mmm = max(tc) ax1.set_ylim([0, 1.5 * mmm]) ax1.set_xlim([0, x_max]) # align the time axis to accommodate cpu/memory # it should read a template and then populate the time if time_label: import datetime with open(time_label) as f: c = 0 for line in f: fs = line.split('\t') aa = fs[0].replace(' ', ',').replace('-',',').replace(':',',') aaa = aa.split(',') tstamp = (datetime.datetime(int(aaa[0]),int(aaa[1]),int(aaa[2]),int(aaa[3]),int(aaa[4]),int(aaa[5])) - datetime.datetime(1970,1,1)).total_seconds() tstamp -= stt if (c % 2 == 0): delt = 0 co = 'k' ls = 'dotted' else: delt = 50 co = 'm' ls = 'dashed' ax1.vlines(tstamp, 0, 1.5 * mmm, colors = co, linestyles=ls) ax1.text(tstamp - 25, 1 * mmm + delt, fs[1], fontsize = 7) c += 1 ax1.legend(loc='upper left', shadow=True, prop={'size':8}) ax2.legend(loc='upper right', shadow=True, prop={'size':8})
normal
{ "blob_id": "85f5f9370896eac17dc72bbbf8d2dd1d7adc3a5b", "index": 7872, "step-1": "\"\"\"\n\n\"\"\"\nimport cPickle as pickle\n\n\ndef convert_cpu_stats_to_num_array(cpuStats):\n \"\"\"\n Given a list of statistics (tuples[timestamp, total_cpu, kernel_cpu, vm, rss])\n Return five numarrays\n \"\"\"\n print \"Converting cpus stats into numpy array\"\n c0 = []\n c1 = []\n c2 = []\n c3 = []\n c4 = []\n # TODO - need a pythonic/numpy way for corner turning\n gc.disable()\n for c in cpuStats:\n c0.append(c[0])\n c1.append(c[1])\n c2.append(c[2])\n c3.append(c[3])\n c4.append(c[4])\n gc.enable()\n\n return (np.array(c0), np.array(c1), np.array(c2), np.array(c3), np.array(c4))\n\n\ndef plot_cpu_mem_usage_from_file(cpufile, figfile, stt=None, x_max=None, time_label=None):\n \"\"\"\n Plot CPU and memory usage from a cpu log file\n\n parameters:\n cpufile: the full path of the cpu log file (string)\n figfile: the full path of the plot file (string)\n stt: start time stamp in seconds (Integer,\n None if let it done automatically)\n x_max: the duration of the time axis in seconds (Integer,\n None automatically set)\n time_label: full path to the application activity log (string)\n each line is something like this:\n 2014-08-17 04:44:24 major cycle 3\n 2014-08-17 04:45:44 make image\n\n If set, the plot tries to draw vertical lines along the\n time axis to show these activities This is an experimental\n feature, need more work\n\n \"\"\"\n reList = []\n if os.path.exists(cpufile):\n try:\n pkl_file = open(cpufile, 'rb')\n print 'Loading CPU stats object from file %s' % cpufile\n cpuStatsList = pickle.load(pkl_file)\n pkl_file.close()\n if cpuStatsList == None:\n raise Exception(\"The CPU stats object is None when reading from the file\")\n reList += cpuStatsList\n #return cpuStatsList\n\n except Exception, e:\n ex = str(e)\n import traceback\n print 'Fail to load the CPU stats from file %s: %s' % (cpufile, ex)\n traceback.print_exc()\n raise e\n else:\n print 'Cannot locate the CPU stats file %s' % cpufile\n fig = pl.figure()\n plot_cpu_mem_usage(fig, x_max, reList, stt, standalone = True, time_label = time_label)\n #fig.savefig('/tmp/cpu_mem_usage.pdf')\n fig.savefig(figfile)\n pl.close(fig)\n\n\ndef plot_cpu_mem_usage(fig, cpuStats, x_max = None, stt = None,\n standalone = False, time_label = None):\n if standalone:\n ax1 = fig.add_subplot(111)\n else:\n ax1 = fig.add_subplot(211)\n ax1.set_xlabel('Time (seconds)', fontsize = 9)\n\n ax1.set_ylabel('CPU usage (% of Wall Clock time)', fontsize = 9)\n ax1.set_title('CPU and Memory usage', fontsize=10)\n ax1.tick_params(axis='both', which='major', labelsize=8)\n ax1.tick_params(axis='both', which='minor', labelsize=6)\n\n # get the data in numpy array\n ta, tc, kc, vm, rss = convert_cpu_stats_to_num_array(cpuStats)\n if stt is None:\n stt = ta\n ta -= stt\n st = int(ta[0])\n ed = int(ta[-1])\n if x_max is None:\n x_max = ed\n elif ed > x_max:\n x_max = ed\n\n # create x-axis (whole integer seconds) between st and ed\n # x = np.r_[st:ed + 1]\n x = ta.astype(np.int64)\n\n # plot the total cpu\n ax1.plot(x, tc, color = 'g', linestyle = '-', label = 'total cpu')\n\n # plot the kernel cpu\n ax1.plot(x, kc, color = 'r', linestyle = '--', label = 'kernel cpu')\n\n # plot the virtual mem\n\n ax2 = ax1.twinx()\n ax2.set_ylabel('Memory usage (MB)', fontsize = 9)\n ax2.tick_params(axis='y', which='major', labelsize=8)\n ax2.tick_params(axis='y', which='minor', labelsize=6)\n ax2.plot(x, vm / 1024.0 ** 2, color = 'b', linestyle = ':', label = 'virtual memory')\n\n # plot the rss\n ax2.plot(x, rss / 1024.0 ** 2, color = 'k', linestyle = '-.', label = 'resident memory')\n mmm = max(tc)\n ax1.set_ylim([0, 1.5 * mmm])\n\n ax1.set_xlim([0, x_max]) # align the time axis to accommodate cpu/memory\n\n # it should read a template and then populate the time\n if time_label:\n import datetime\n with open(time_label) as f:\n c = 0\n for line in f:\n fs = line.split('\\t')\n aa = fs[0].replace(' ', ',').replace('-',',').replace(':',',')\n aaa = aa.split(',')\n tstamp = (datetime.datetime(int(aaa[0]),int(aaa[1]),int(aaa[2]),int(aaa[3]),int(aaa[4]),int(aaa[5])) - datetime.datetime(1970,1,1)).total_seconds()\n tstamp -= stt\n if (c % 2 == 0):\n delt = 0\n co = 'k'\n ls = 'dotted'\n else:\n delt = 50\n co = 'm'\n ls = 'dashed'\n ax1.vlines(tstamp, 0, 1.5 * mmm, colors = co, linestyles=ls)\n ax1.text(tstamp - 25, 1 * mmm + delt, fs[1], fontsize = 7)\n c += 1\n ax1.legend(loc='upper left', shadow=True, prop={'size':8})\n ax2.legend(loc='upper right', shadow=True, prop={'size':8})\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
''' The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause. ''' #Modifying the values using while loop in a list l1: list = [1,2,3,4,5,6,7,8,9,10] print("The original list: " , l1) i=0 while (i < len(l1)): l1[i] = l1[i] + 100 i=i+1 print("The modified new list is: ", l1) #Guessing game using while-else loop number = 23 while True: guess = int(input('Enter an integer : ')) #input statement to enter data from console if guess == number: print('Congratulations, you guessed it.') break elif guess < number: print('No, it is a little higher than that.') continue else: print('No, it is a little lower than that.') continue # Do anything else you want to do here print('Done')
normal
{ "blob_id": "6a3fd3323ed8792853afdf5af76161f3e20d4896", "index": 4443, "step-1": "<mask token>\n", "step-2": "<mask token>\nl1: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint('The original list: ', l1)\n<mask token>\nwhile i < len(l1):\n l1[i] = l1[i] + 100\n i = i + 1\nprint('The modified new list is: ', l1)\n<mask token>\nwhile True:\n guess = int(input('Enter an integer : '))\n if guess == number:\n print('Congratulations, you guessed it.')\n break\n elif guess < number:\n print('No, it is a little higher than that.')\n continue\n else:\n print('No, it is a little lower than that.')\n continue\nprint('Done')\n", "step-3": "<mask token>\nl1: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nprint('The original list: ', l1)\ni = 0\nwhile i < len(l1):\n l1[i] = l1[i] + 100\n i = i + 1\nprint('The modified new list is: ', l1)\nnumber = 23\nwhile True:\n guess = int(input('Enter an integer : '))\n if guess == number:\n print('Congratulations, you guessed it.')\n break\n elif guess < number:\n print('No, it is a little higher than that.')\n continue\n else:\n print('No, it is a little lower than that.')\n continue\nprint('Done')\n", "step-4": "'''\nThe while statement allows you to repeatedly execute a block of statements as long as a condition is true.\nA while statement is an example of what is called a looping statement. A while statement can have an optional else clause.\n'''\n\n#Modifying the values using while loop in a list\nl1: list = [1,2,3,4,5,6,7,8,9,10]\nprint(\"The original list: \" , l1)\n\ni=0\nwhile (i < len(l1)):\n l1[i] = l1[i] + 100\n i=i+1\nprint(\"The modified new list is: \", l1)\n\n#Guessing game using while-else loop\nnumber = 23\n\nwhile True:\n guess = int(input('Enter an integer : ')) #input statement to enter data from console\n if guess == number:\n print('Congratulations, you guessed it.')\n break\n elif guess < number:\n print('No, it is a little higher than that.')\n continue\n else:\n print('No, it is a little lower than that.')\n continue\n\n# Do anything else you want to do here\nprint('Done')\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# coding=utf-8 # Copyright 2021-Present The THUCTC Authors from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import torch import torch.nn as nn import thuctc.utils as utils from thuctc.modules.module import Module from thuctc.modules.layer_norm import LayerNorm class PositionalEmbedding(torch.nn.Module): def __init__(self): super(PositionalEmbedding, self).__init__() def forward(self, inputs): if inputs.dim() != 3: raise ValueError("The rank of input must be 3.") length = inputs.shape[1] channels = inputs.shape[2] half_dim = channels // 2 positions = torch.arange(length, dtype=inputs.dtype, device=inputs.device) dimensions = torch.arange(half_dim, dtype=inputs.dtype, device=inputs.device) scale = math.log(10000.0) / float(half_dim - 1) dimensions.mul_(-scale).exp_() scaled_time = positions.unsqueeze(1) * dimensions.unsqueeze(0) signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1) if channels % 2 == 1: pad = torch.zeros([signal.shape[0], 1], dtype=inputs.dtype, device=inputs.device) signal = torch.cat([signal, pad], axis=1) return inputs + torch.reshape(signal, [1, -1, channels]).to(inputs) class Embedding(Module): def __init__(self, embed_nums, embed_dims, bias=False, name="embedding"): super(Embedding, self).__init__(name=name) self.embed_nums = embed_nums self.embed_dims = embed_dims with utils.scope(name): self.weight = nn.Parameter( torch.empty(self.embed_nums, self.embed_dims)) self.add_name(self.weight, "weight") if bias: self.bias = nn.Parameter( torch.zeros(self.embed_dims)) self.add_name(self.bias, "bias") else: self.bias = None self.reset_parameters() def reset_parameters(self): nn.init.normal_(self.weight, mean=0.0, std=self.embed_dims ** -0.5) def forward(self, inputs): outputs = nn.functional.embedding(inputs, self.weight) if self.bias is not None: outputs = outputs + self.bias return outputs class UnifiedEmbedding(Module): def __init__(self, params, pos_embed=None, type_embed=False, layer_norm=False, dropout=0.0, scale=False, name="embedding"): super(UnifiedEmbedding, self).__init__(name=name) self.pos_embed = pos_embed self.type_embed = type_embed self.vocab_size = len(params.vocabulary["source"]) self.embedding_size = params.embedding_size self.layer_norm = None self.out_dropout = None self.scale = scale if dropout > 0: self.out_dropout = nn.Dropout(p=dropout) with utils.scope(name): self.word_embeddings = Embedding(self.vocab_size, self.embedding_size, name="word_embedding") if self.pos_embed is not None: if self.pos_embed == "learnable": self.pos_embeddings = Embedding(params.max_pos, self.embedding_size, name="pos_embedding") elif self.pos_embed == "functional": self.pos_embeddings = PositionalEmbedding() else: raise ValueError("Unsupported position " "embedding: %s" % pos_embed) if self.type_embed: self.type_embeddings = Embedding(params.type_vocab_size, self.embedding_size, name="type_embedding") if layer_norm: self.layer_norm = LayerNorm(self.embedding_size, eps=params.layer_norm_eps) def resize_word_embedding(self, new_vocab_size): old_embeddings = self.word_embeddings old_num_tokens, old_embedding_dim = old_embeddings.weight.size() new_embeddings = Embedding(new_vocab_size, old_embedding_dim, name="word_embedding").to(old_embeddings.weight) new_embeddings.reset_parameters() new_embeddings.weight.data[:old_num_tokens, :] = old_embeddings.weight.data self.word_embeddings = new_embeddings self.vocab_size = new_vocab_size def forward(self, input_ids, token_type_ids=None, position_ids=None): inp_shape = input_ids.size() inp_length = inp_shape[1] inputs = self.word_embeddings(input_ids) if self.scale: inputs = inputs * (self.embedding_size ** 0.5) if self.pos_embed is not None: if self.pos_embed == "learnable": if position_ids is None: position_ids = torch.arange(inp_length).to(input_ids) position_ids = position_ids.unsqueeze(0).expand_as(input_ids) inputs = inputs + self.pos_embeddings(position_ids) elif self.pos_embed == "functional": inputs = self.pos_embeddings(inputs) if self.type_embed: if token_type_ids is None: token_type_ids = torch.zeros_like(input_ids) inputs = inputs + self.type_embeddings(token_type_ids) if self.layer_norm is not None: inputs = self.layer_norm(inputs) if self.out_dropout is not None: inputs = self.out_dropout(inputs) return inputs
normal
{ "blob_id": "c773b273ad6953bf9c74b11c44aff16e9fd0860e", "index": 3468, "step-1": "<mask token>\n\n\nclass Embedding(Module):\n\n def __init__(self, embed_nums, embed_dims, bias=False, name='embedding'):\n super(Embedding, self).__init__(name=name)\n self.embed_nums = embed_nums\n self.embed_dims = embed_dims\n with utils.scope(name):\n self.weight = nn.Parameter(torch.empty(self.embed_nums, self.\n embed_dims))\n self.add_name(self.weight, 'weight')\n if bias:\n self.bias = nn.Parameter(torch.zeros(self.embed_dims))\n self.add_name(self.bias, 'bias')\n else:\n self.bias = None\n self.reset_parameters()\n <mask token>\n\n def forward(self, inputs):\n outputs = nn.functional.embedding(inputs, self.weight)\n if self.bias is not None:\n outputs = outputs + self.bias\n return outputs\n\n\nclass UnifiedEmbedding(Module):\n\n def __init__(self, params, pos_embed=None, type_embed=False, layer_norm\n =False, dropout=0.0, scale=False, name='embedding'):\n super(UnifiedEmbedding, self).__init__(name=name)\n self.pos_embed = pos_embed\n self.type_embed = type_embed\n self.vocab_size = len(params.vocabulary['source'])\n self.embedding_size = params.embedding_size\n self.layer_norm = None\n self.out_dropout = None\n self.scale = scale\n if dropout > 0:\n self.out_dropout = nn.Dropout(p=dropout)\n with utils.scope(name):\n self.word_embeddings = Embedding(self.vocab_size, self.\n embedding_size, name='word_embedding')\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n self.pos_embeddings = Embedding(params.max_pos, self.\n embedding_size, name='pos_embedding')\n elif self.pos_embed == 'functional':\n self.pos_embeddings = PositionalEmbedding()\n else:\n raise ValueError('Unsupported position embedding: %s' %\n pos_embed)\n if self.type_embed:\n self.type_embeddings = Embedding(params.type_vocab_size,\n self.embedding_size, name='type_embedding')\n if layer_norm:\n self.layer_norm = LayerNorm(self.embedding_size, eps=params\n .layer_norm_eps)\n\n def resize_word_embedding(self, new_vocab_size):\n old_embeddings = self.word_embeddings\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n new_embeddings = Embedding(new_vocab_size, old_embedding_dim, name=\n 'word_embedding').to(old_embeddings.weight)\n new_embeddings.reset_parameters()\n new_embeddings.weight.data[:old_num_tokens, :\n ] = old_embeddings.weight.data\n self.word_embeddings = new_embeddings\n self.vocab_size = new_vocab_size\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n inp_shape = input_ids.size()\n inp_length = inp_shape[1]\n inputs = self.word_embeddings(input_ids)\n if self.scale:\n inputs = inputs * self.embedding_size ** 0.5\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n if position_ids is None:\n position_ids = torch.arange(inp_length).to(input_ids)\n position_ids = position_ids.unsqueeze(0).expand_as(\n input_ids)\n inputs = inputs + self.pos_embeddings(position_ids)\n elif self.pos_embed == 'functional':\n inputs = self.pos_embeddings(inputs)\n if self.type_embed:\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n inputs = inputs + self.type_embeddings(token_type_ids)\n if self.layer_norm is not None:\n inputs = self.layer_norm(inputs)\n if self.out_dropout is not None:\n inputs = self.out_dropout(inputs)\n return inputs\n", "step-2": "<mask token>\n\n\nclass PositionalEmbedding(torch.nn.Module):\n <mask token>\n <mask token>\n\n\nclass Embedding(Module):\n\n def __init__(self, embed_nums, embed_dims, bias=False, name='embedding'):\n super(Embedding, self).__init__(name=name)\n self.embed_nums = embed_nums\n self.embed_dims = embed_dims\n with utils.scope(name):\n self.weight = nn.Parameter(torch.empty(self.embed_nums, self.\n embed_dims))\n self.add_name(self.weight, 'weight')\n if bias:\n self.bias = nn.Parameter(torch.zeros(self.embed_dims))\n self.add_name(self.bias, 'bias')\n else:\n self.bias = None\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.normal_(self.weight, mean=0.0, std=self.embed_dims ** -0.5)\n\n def forward(self, inputs):\n outputs = nn.functional.embedding(inputs, self.weight)\n if self.bias is not None:\n outputs = outputs + self.bias\n return outputs\n\n\nclass UnifiedEmbedding(Module):\n\n def __init__(self, params, pos_embed=None, type_embed=False, layer_norm\n =False, dropout=0.0, scale=False, name='embedding'):\n super(UnifiedEmbedding, self).__init__(name=name)\n self.pos_embed = pos_embed\n self.type_embed = type_embed\n self.vocab_size = len(params.vocabulary['source'])\n self.embedding_size = params.embedding_size\n self.layer_norm = None\n self.out_dropout = None\n self.scale = scale\n if dropout > 0:\n self.out_dropout = nn.Dropout(p=dropout)\n with utils.scope(name):\n self.word_embeddings = Embedding(self.vocab_size, self.\n embedding_size, name='word_embedding')\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n self.pos_embeddings = Embedding(params.max_pos, self.\n embedding_size, name='pos_embedding')\n elif self.pos_embed == 'functional':\n self.pos_embeddings = PositionalEmbedding()\n else:\n raise ValueError('Unsupported position embedding: %s' %\n pos_embed)\n if self.type_embed:\n self.type_embeddings = Embedding(params.type_vocab_size,\n self.embedding_size, name='type_embedding')\n if layer_norm:\n self.layer_norm = LayerNorm(self.embedding_size, eps=params\n .layer_norm_eps)\n\n def resize_word_embedding(self, new_vocab_size):\n old_embeddings = self.word_embeddings\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n new_embeddings = Embedding(new_vocab_size, old_embedding_dim, name=\n 'word_embedding').to(old_embeddings.weight)\n new_embeddings.reset_parameters()\n new_embeddings.weight.data[:old_num_tokens, :\n ] = old_embeddings.weight.data\n self.word_embeddings = new_embeddings\n self.vocab_size = new_vocab_size\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n inp_shape = input_ids.size()\n inp_length = inp_shape[1]\n inputs = self.word_embeddings(input_ids)\n if self.scale:\n inputs = inputs * self.embedding_size ** 0.5\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n if position_ids is None:\n position_ids = torch.arange(inp_length).to(input_ids)\n position_ids = position_ids.unsqueeze(0).expand_as(\n input_ids)\n inputs = inputs + self.pos_embeddings(position_ids)\n elif self.pos_embed == 'functional':\n inputs = self.pos_embeddings(inputs)\n if self.type_embed:\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n inputs = inputs + self.type_embeddings(token_type_ids)\n if self.layer_norm is not None:\n inputs = self.layer_norm(inputs)\n if self.out_dropout is not None:\n inputs = self.out_dropout(inputs)\n return inputs\n", "step-3": "<mask token>\n\n\nclass PositionalEmbedding(torch.nn.Module):\n <mask token>\n\n def forward(self, inputs):\n if inputs.dim() != 3:\n raise ValueError('The rank of input must be 3.')\n length = inputs.shape[1]\n channels = inputs.shape[2]\n half_dim = channels // 2\n positions = torch.arange(length, dtype=inputs.dtype, device=inputs.\n device)\n dimensions = torch.arange(half_dim, dtype=inputs.dtype, device=\n inputs.device)\n scale = math.log(10000.0) / float(half_dim - 1)\n dimensions.mul_(-scale).exp_()\n scaled_time = positions.unsqueeze(1) * dimensions.unsqueeze(0)\n signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)],\n dim=1)\n if channels % 2 == 1:\n pad = torch.zeros([signal.shape[0], 1], dtype=inputs.dtype,\n device=inputs.device)\n signal = torch.cat([signal, pad], axis=1)\n return inputs + torch.reshape(signal, [1, -1, channels]).to(inputs)\n\n\nclass Embedding(Module):\n\n def __init__(self, embed_nums, embed_dims, bias=False, name='embedding'):\n super(Embedding, self).__init__(name=name)\n self.embed_nums = embed_nums\n self.embed_dims = embed_dims\n with utils.scope(name):\n self.weight = nn.Parameter(torch.empty(self.embed_nums, self.\n embed_dims))\n self.add_name(self.weight, 'weight')\n if bias:\n self.bias = nn.Parameter(torch.zeros(self.embed_dims))\n self.add_name(self.bias, 'bias')\n else:\n self.bias = None\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.normal_(self.weight, mean=0.0, std=self.embed_dims ** -0.5)\n\n def forward(self, inputs):\n outputs = nn.functional.embedding(inputs, self.weight)\n if self.bias is not None:\n outputs = outputs + self.bias\n return outputs\n\n\nclass UnifiedEmbedding(Module):\n\n def __init__(self, params, pos_embed=None, type_embed=False, layer_norm\n =False, dropout=0.0, scale=False, name='embedding'):\n super(UnifiedEmbedding, self).__init__(name=name)\n self.pos_embed = pos_embed\n self.type_embed = type_embed\n self.vocab_size = len(params.vocabulary['source'])\n self.embedding_size = params.embedding_size\n self.layer_norm = None\n self.out_dropout = None\n self.scale = scale\n if dropout > 0:\n self.out_dropout = nn.Dropout(p=dropout)\n with utils.scope(name):\n self.word_embeddings = Embedding(self.vocab_size, self.\n embedding_size, name='word_embedding')\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n self.pos_embeddings = Embedding(params.max_pos, self.\n embedding_size, name='pos_embedding')\n elif self.pos_embed == 'functional':\n self.pos_embeddings = PositionalEmbedding()\n else:\n raise ValueError('Unsupported position embedding: %s' %\n pos_embed)\n if self.type_embed:\n self.type_embeddings = Embedding(params.type_vocab_size,\n self.embedding_size, name='type_embedding')\n if layer_norm:\n self.layer_norm = LayerNorm(self.embedding_size, eps=params\n .layer_norm_eps)\n\n def resize_word_embedding(self, new_vocab_size):\n old_embeddings = self.word_embeddings\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n new_embeddings = Embedding(new_vocab_size, old_embedding_dim, name=\n 'word_embedding').to(old_embeddings.weight)\n new_embeddings.reset_parameters()\n new_embeddings.weight.data[:old_num_tokens, :\n ] = old_embeddings.weight.data\n self.word_embeddings = new_embeddings\n self.vocab_size = new_vocab_size\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n inp_shape = input_ids.size()\n inp_length = inp_shape[1]\n inputs = self.word_embeddings(input_ids)\n if self.scale:\n inputs = inputs * self.embedding_size ** 0.5\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n if position_ids is None:\n position_ids = torch.arange(inp_length).to(input_ids)\n position_ids = position_ids.unsqueeze(0).expand_as(\n input_ids)\n inputs = inputs + self.pos_embeddings(position_ids)\n elif self.pos_embed == 'functional':\n inputs = self.pos_embeddings(inputs)\n if self.type_embed:\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n inputs = inputs + self.type_embeddings(token_type_ids)\n if self.layer_norm is not None:\n inputs = self.layer_norm(inputs)\n if self.out_dropout is not None:\n inputs = self.out_dropout(inputs)\n return inputs\n", "step-4": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport math\nimport torch\nimport torch.nn as nn\nimport thuctc.utils as utils\nfrom thuctc.modules.module import Module\nfrom thuctc.modules.layer_norm import LayerNorm\n\n\nclass PositionalEmbedding(torch.nn.Module):\n\n def __init__(self):\n super(PositionalEmbedding, self).__init__()\n\n def forward(self, inputs):\n if inputs.dim() != 3:\n raise ValueError('The rank of input must be 3.')\n length = inputs.shape[1]\n channels = inputs.shape[2]\n half_dim = channels // 2\n positions = torch.arange(length, dtype=inputs.dtype, device=inputs.\n device)\n dimensions = torch.arange(half_dim, dtype=inputs.dtype, device=\n inputs.device)\n scale = math.log(10000.0) / float(half_dim - 1)\n dimensions.mul_(-scale).exp_()\n scaled_time = positions.unsqueeze(1) * dimensions.unsqueeze(0)\n signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)],\n dim=1)\n if channels % 2 == 1:\n pad = torch.zeros([signal.shape[0], 1], dtype=inputs.dtype,\n device=inputs.device)\n signal = torch.cat([signal, pad], axis=1)\n return inputs + torch.reshape(signal, [1, -1, channels]).to(inputs)\n\n\nclass Embedding(Module):\n\n def __init__(self, embed_nums, embed_dims, bias=False, name='embedding'):\n super(Embedding, self).__init__(name=name)\n self.embed_nums = embed_nums\n self.embed_dims = embed_dims\n with utils.scope(name):\n self.weight = nn.Parameter(torch.empty(self.embed_nums, self.\n embed_dims))\n self.add_name(self.weight, 'weight')\n if bias:\n self.bias = nn.Parameter(torch.zeros(self.embed_dims))\n self.add_name(self.bias, 'bias')\n else:\n self.bias = None\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.normal_(self.weight, mean=0.0, std=self.embed_dims ** -0.5)\n\n def forward(self, inputs):\n outputs = nn.functional.embedding(inputs, self.weight)\n if self.bias is not None:\n outputs = outputs + self.bias\n return outputs\n\n\nclass UnifiedEmbedding(Module):\n\n def __init__(self, params, pos_embed=None, type_embed=False, layer_norm\n =False, dropout=0.0, scale=False, name='embedding'):\n super(UnifiedEmbedding, self).__init__(name=name)\n self.pos_embed = pos_embed\n self.type_embed = type_embed\n self.vocab_size = len(params.vocabulary['source'])\n self.embedding_size = params.embedding_size\n self.layer_norm = None\n self.out_dropout = None\n self.scale = scale\n if dropout > 0:\n self.out_dropout = nn.Dropout(p=dropout)\n with utils.scope(name):\n self.word_embeddings = Embedding(self.vocab_size, self.\n embedding_size, name='word_embedding')\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n self.pos_embeddings = Embedding(params.max_pos, self.\n embedding_size, name='pos_embedding')\n elif self.pos_embed == 'functional':\n self.pos_embeddings = PositionalEmbedding()\n else:\n raise ValueError('Unsupported position embedding: %s' %\n pos_embed)\n if self.type_embed:\n self.type_embeddings = Embedding(params.type_vocab_size,\n self.embedding_size, name='type_embedding')\n if layer_norm:\n self.layer_norm = LayerNorm(self.embedding_size, eps=params\n .layer_norm_eps)\n\n def resize_word_embedding(self, new_vocab_size):\n old_embeddings = self.word_embeddings\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n new_embeddings = Embedding(new_vocab_size, old_embedding_dim, name=\n 'word_embedding').to(old_embeddings.weight)\n new_embeddings.reset_parameters()\n new_embeddings.weight.data[:old_num_tokens, :\n ] = old_embeddings.weight.data\n self.word_embeddings = new_embeddings\n self.vocab_size = new_vocab_size\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n inp_shape = input_ids.size()\n inp_length = inp_shape[1]\n inputs = self.word_embeddings(input_ids)\n if self.scale:\n inputs = inputs * self.embedding_size ** 0.5\n if self.pos_embed is not None:\n if self.pos_embed == 'learnable':\n if position_ids is None:\n position_ids = torch.arange(inp_length).to(input_ids)\n position_ids = position_ids.unsqueeze(0).expand_as(\n input_ids)\n inputs = inputs + self.pos_embeddings(position_ids)\n elif self.pos_embed == 'functional':\n inputs = self.pos_embeddings(inputs)\n if self.type_embed:\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n inputs = inputs + self.type_embeddings(token_type_ids)\n if self.layer_norm is not None:\n inputs = self.layer_norm(inputs)\n if self.out_dropout is not None:\n inputs = self.out_dropout(inputs)\n return inputs\n", "step-5": "# coding=utf-8\n# Copyright 2021-Present The THUCTC Authors\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport torch\n\nimport torch.nn as nn\nimport thuctc.utils as utils\n\nfrom thuctc.modules.module import Module\nfrom thuctc.modules.layer_norm import LayerNorm\n\n\nclass PositionalEmbedding(torch.nn.Module):\n\n def __init__(self):\n super(PositionalEmbedding, self).__init__()\n\n def forward(self, inputs):\n if inputs.dim() != 3:\n raise ValueError(\"The rank of input must be 3.\")\n\n length = inputs.shape[1]\n channels = inputs.shape[2]\n half_dim = channels // 2\n\n positions = torch.arange(length, dtype=inputs.dtype,\n device=inputs.device)\n dimensions = torch.arange(half_dim, dtype=inputs.dtype,\n device=inputs.device)\n\n scale = math.log(10000.0) / float(half_dim - 1)\n dimensions.mul_(-scale).exp_()\n\n scaled_time = positions.unsqueeze(1) * dimensions.unsqueeze(0)\n signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)],\n dim=1)\n\n if channels % 2 == 1:\n pad = torch.zeros([signal.shape[0], 1], dtype=inputs.dtype,\n device=inputs.device)\n signal = torch.cat([signal, pad], axis=1)\n\n return inputs + torch.reshape(signal, [1, -1, channels]).to(inputs)\n\n\nclass Embedding(Module):\n\n def __init__(self, embed_nums, embed_dims, bias=False, name=\"embedding\"):\n super(Embedding, self).__init__(name=name)\n\n self.embed_nums = embed_nums\n self.embed_dims = embed_dims\n\n with utils.scope(name):\n self.weight = nn.Parameter(\n torch.empty(self.embed_nums, self.embed_dims))\n self.add_name(self.weight, \"weight\")\n\n if bias:\n self.bias = nn.Parameter(\n torch.zeros(self.embed_dims))\n self.add_name(self.bias, \"bias\")\n else:\n self.bias = None\n\n self.reset_parameters()\n\n def reset_parameters(self):\n nn.init.normal_(self.weight, mean=0.0,\n std=self.embed_dims ** -0.5)\n\n def forward(self, inputs):\n outputs = nn.functional.embedding(inputs, self.weight)\n\n if self.bias is not None:\n outputs = outputs + self.bias\n\n return outputs\n\n\nclass UnifiedEmbedding(Module):\n\n def __init__(self, params, pos_embed=None, type_embed=False,\n layer_norm=False, dropout=0.0, scale=False, name=\"embedding\"):\n super(UnifiedEmbedding, self).__init__(name=name)\n\n self.pos_embed = pos_embed\n self.type_embed = type_embed\n self.vocab_size = len(params.vocabulary[\"source\"])\n self.embedding_size = params.embedding_size\n self.layer_norm = None\n self.out_dropout = None\n self.scale = scale\n\n if dropout > 0:\n self.out_dropout = nn.Dropout(p=dropout)\n\n with utils.scope(name):\n self.word_embeddings = Embedding(self.vocab_size,\n self.embedding_size,\n name=\"word_embedding\")\n\n if self.pos_embed is not None:\n if self.pos_embed == \"learnable\":\n self.pos_embeddings = Embedding(params.max_pos,\n self.embedding_size,\n name=\"pos_embedding\")\n elif self.pos_embed == \"functional\":\n self.pos_embeddings = PositionalEmbedding()\n else:\n raise ValueError(\"Unsupported position \"\n \"embedding: %s\" % pos_embed)\n\n if self.type_embed:\n self.type_embeddings = Embedding(params.type_vocab_size,\n self.embedding_size,\n name=\"type_embedding\")\n\n if layer_norm:\n self.layer_norm = LayerNorm(self.embedding_size,\n eps=params.layer_norm_eps)\n\n def resize_word_embedding(self, new_vocab_size): \n old_embeddings = self.word_embeddings\n old_num_tokens, old_embedding_dim = old_embeddings.weight.size()\n new_embeddings = Embedding(new_vocab_size,\n old_embedding_dim,\n name=\"word_embedding\").to(old_embeddings.weight)\n new_embeddings.reset_parameters()\n new_embeddings.weight.data[:old_num_tokens, :] = old_embeddings.weight.data\n self.word_embeddings = new_embeddings\n self.vocab_size = new_vocab_size\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n inp_shape = input_ids.size()\n inp_length = inp_shape[1]\n\n inputs = self.word_embeddings(input_ids)\n\n if self.scale:\n inputs = inputs * (self.embedding_size ** 0.5)\n\n if self.pos_embed is not None:\n if self.pos_embed == \"learnable\":\n if position_ids is None:\n position_ids = torch.arange(inp_length).to(input_ids)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n\n inputs = inputs + self.pos_embeddings(position_ids)\n elif self.pos_embed == \"functional\":\n inputs = self.pos_embeddings(inputs)\n\n if self.type_embed:\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n inputs = inputs + self.type_embeddings(token_type_ids)\n\n if self.layer_norm is not None:\n inputs = self.layer_norm(inputs)\n\n if self.out_dropout is not None:\n inputs = self.out_dropout(inputs)\n\n return inputs\n", "step-ids": [ 7, 9, 10, 12, 13 ] }
[ 7, 9, 10, 12, 13 ]
from django.db import models from django.urls import reverse from django.conf import settings from embed_video.fields import EmbedVideoField from django.contrib.auth.models import AbstractBaseUser User = settings.AUTH_USER_MODEL # Create your models here. """class User(models.Model): username = models.CharField(max_length=20) created_at = models.DateTimeField() is_enabled = models.BooleanField(default=True) email = models.EmailField() password = models.CharField(max_length=20) def __str__(self): return self.username""" class Post(models.Model): is_enabled = models.BooleanField(default=True) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, blank=True, null=True, default='' ) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, blank=True) author = models.ForeignKey( User, on_delete=models.PROTECT ) class Meta: ordering = ['parent_id', 'created_at'] def display_text(self): short = " ".join(self.text.split()[0:5]) if len(short) > 20: short = self.text[:20] + "..." return short display_text.short_description = 'Text' def __str__(self): space = " " return f'{space.join(self.text.split()[0:5])} ({str(self.created_at)})' def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) class Item(models.Model): video = EmbedVideoField()
normal
{ "blob_id": "5c4a48de94cf5bfe67e6a74c33a317fa1da8d2fa", "index": 7330, "step-1": "<mask token>\n\n\nclass Post(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n ordering = ['parent_id', 'created_at']\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Item(models.Model):\n video = EmbedVideoField()\n", "step-2": "<mask token>\n\n\nclass Post(models.Model):\n is_enabled = models.BooleanField(default=True)\n parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True,\n null=True, default='')\n text = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True, blank=True)\n author = models.ForeignKey(User, on_delete=models.PROTECT)\n\n\n class Meta:\n ordering = ['parent_id', 'created_at']\n\n def display_text(self):\n short = ' '.join(self.text.split()[0:5])\n if len(short) > 20:\n short = self.text[:20] + '...'\n return short\n display_text.short_description = 'Text'\n\n def __str__(self):\n space = ' '\n return f'{space.join(self.text.split()[0:5])} ({str(self.created_at)})'\n\n def get_absolute_url(self):\n return reverse('post-detail', args=[str(self.id)])\n\n\nclass Item(models.Model):\n video = EmbedVideoField()\n", "step-3": "<mask token>\nUser = settings.AUTH_USER_MODEL\n<mask token>\n\n\nclass Post(models.Model):\n is_enabled = models.BooleanField(default=True)\n parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True,\n null=True, default='')\n text = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True, blank=True)\n author = models.ForeignKey(User, on_delete=models.PROTECT)\n\n\n class Meta:\n ordering = ['parent_id', 'created_at']\n\n def display_text(self):\n short = ' '.join(self.text.split()[0:5])\n if len(short) > 20:\n short = self.text[:20] + '...'\n return short\n display_text.short_description = 'Text'\n\n def __str__(self):\n space = ' '\n return f'{space.join(self.text.split()[0:5])} ({str(self.created_at)})'\n\n def get_absolute_url(self):\n return reverse('post-detail', args=[str(self.id)])\n\n\nclass Item(models.Model):\n video = EmbedVideoField()\n", "step-4": "from django.db import models\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom embed_video.fields import EmbedVideoField\nfrom django.contrib.auth.models import AbstractBaseUser\nUser = settings.AUTH_USER_MODEL\n<mask token>\n\n\nclass Post(models.Model):\n is_enabled = models.BooleanField(default=True)\n parent = models.ForeignKey('self', on_delete=models.PROTECT, blank=True,\n null=True, default='')\n text = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True, blank=True)\n author = models.ForeignKey(User, on_delete=models.PROTECT)\n\n\n class Meta:\n ordering = ['parent_id', 'created_at']\n\n def display_text(self):\n short = ' '.join(self.text.split()[0:5])\n if len(short) > 20:\n short = self.text[:20] + '...'\n return short\n display_text.short_description = 'Text'\n\n def __str__(self):\n space = ' '\n return f'{space.join(self.text.split()[0:5])} ({str(self.created_at)})'\n\n def get_absolute_url(self):\n return reverse('post-detail', args=[str(self.id)])\n\n\nclass Item(models.Model):\n video = EmbedVideoField()\n", "step-5": "from django.db import models\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom embed_video.fields import EmbedVideoField\nfrom django.contrib.auth.models import AbstractBaseUser\n\nUser = settings.AUTH_USER_MODEL\n\n# Create your models here.\n\n\"\"\"class User(models.Model):\n username = models.CharField(max_length=20)\n created_at = models.DateTimeField()\n is_enabled = models.BooleanField(default=True)\n email = models.EmailField()\n password = models.CharField(max_length=20)\n\n def __str__(self):\n return self.username\"\"\"\n\n\nclass Post(models.Model):\n is_enabled = models.BooleanField(default=True)\n parent = models.ForeignKey(\n 'self', on_delete=models.PROTECT, blank=True, null=True, default=''\n )\n text = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True, blank=True)\n author = models.ForeignKey(\n User,\n on_delete=models.PROTECT\n )\n\n class Meta:\n ordering = ['parent_id', 'created_at']\n\n def display_text(self):\n short = \" \".join(self.text.split()[0:5])\n if len(short) > 20:\n short = self.text[:20] + \"...\"\n return short\n\n display_text.short_description = 'Text'\n\n def __str__(self):\n space = \" \"\n return f'{space.join(self.text.split()[0:5])} ({str(self.created_at)})'\n\n def get_absolute_url(self):\n return reverse('post-detail', args=[str(self.id)])\n\n\nclass Item(models.Model):\n video = EmbedVideoField()\n", "step-ids": [ 3, 7, 8, 9, 10 ] }
[ 3, 7, 8, 9, 10 ]
/home/mitchellwoodbine/Documents/github/getargs/GetArgs.py
normal
{ "blob_id": "0065a493767a2080a20f8b55f76ddeae92dc27f1", "index": 3359, "step-1": "/home/mitchellwoodbine/Documents/github/getargs/GetArgs.py", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
/Users/apple/miniconda3/lib/python3.7/sre_constants.py
normal
{ "blob_id": "71a5ba520f8bc42e80d8f4ce8cf332bdd5fb96de", "index": 5293, "step-1": "/Users/apple/miniconda3/lib/python3.7/sre_constants.py", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# 6. Evaluate Classifier: you can use any metric you choose for this assignment # (accuracy is the easiest one). Feel free to evaluate it on the same data you # built the model on (this is not a good idea in general but for this assignment, # it is fine). We haven't covered models and evaluation yet, so don't worry about # creating validation sets or cross-validation. import pandas as pd import matplotlib.pyplot as plt import pylab as pl from sklearn.metrics import roc_curve, auc, classification_report, confusion_matrix # credits to https://github.com/yhat/DataGotham2013/blob/master/notebooks/8%20-%20Fitting%20and%20Evaluating%20Your%20Model.ipynb def evaluate(model, X_te, y_te): ''' Given the model and independent and dependent testing data, print out statements that evaluate classifier ''' probs = model.predict_proba(X_te) plt.hist(probs[:,1]) plt.xlabel('Likelihood of Significant Financial') plt.ylabel('Frequency') # We should also look at Accuracy print("Accuracy = " + str(model.score(X_te, y_te))) # Finally -- Precision & Recall y_hat = model.predict(X_te) print(classification_report(y_te, y_hat, labels=[0, 1])) y_hat = model.predict(X_te) confusion_matrix = pd.crosstab(y_hat, y_te, rownames=["Actual"], colnames=["Predicted"]) print(confusion_matrix) def plot_roc(probs, y_te): ''' Plots ROC curve. ''' plt.figure() fpr, tpr, thresholds = roc_curve(y_te, probs) roc_auc = auc(fpr, tpr) pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc) pl.plot([0, 1], [0, 1], 'k--') pl.xlim([0.0, 1.05]) pl.ylim([0.0, 1.05]) pl.xlabel('False Positive Rate') pl.ylabel('True Positive Rate') pl.title("ROC Curve") pl.legend(loc="lower right") pl.show()
normal
{ "blob_id": "62de629d8f28435ea8dc3dc093cac95e7cedf128", "index": 7859, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef evaluate(model, X_te, y_te):\n \"\"\"\n Given the model and independent and dependent testing data,\n print out statements that evaluate classifier\n \"\"\"\n probs = model.predict_proba(X_te)\n plt.hist(probs[:, 1])\n plt.xlabel('Likelihood of Significant Financial')\n plt.ylabel('Frequency')\n print('Accuracy = ' + str(model.score(X_te, y_te)))\n y_hat = model.predict(X_te)\n print(classification_report(y_te, y_hat, labels=[0, 1]))\n y_hat = model.predict(X_te)\n confusion_matrix = pd.crosstab(y_hat, y_te, rownames=['Actual'],\n colnames=['Predicted'])\n print(confusion_matrix)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef evaluate(model, X_te, y_te):\n \"\"\"\n Given the model and independent and dependent testing data,\n print out statements that evaluate classifier\n \"\"\"\n probs = model.predict_proba(X_te)\n plt.hist(probs[:, 1])\n plt.xlabel('Likelihood of Significant Financial')\n plt.ylabel('Frequency')\n print('Accuracy = ' + str(model.score(X_te, y_te)))\n y_hat = model.predict(X_te)\n print(classification_report(y_te, y_hat, labels=[0, 1]))\n y_hat = model.predict(X_te)\n confusion_matrix = pd.crosstab(y_hat, y_te, rownames=['Actual'],\n colnames=['Predicted'])\n print(confusion_matrix)\n\n\ndef plot_roc(probs, y_te):\n \"\"\"\n Plots ROC curve.\n \"\"\"\n plt.figure()\n fpr, tpr, thresholds = roc_curve(y_te, probs)\n roc_auc = auc(fpr, tpr)\n pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\n pl.plot([0, 1], [0, 1], 'k--')\n pl.xlim([0.0, 1.05])\n pl.ylim([0.0, 1.05])\n pl.xlabel('False Positive Rate')\n pl.ylabel('True Positive Rate')\n pl.title('ROC Curve')\n pl.legend(loc='lower right')\n pl.show()\n", "step-4": "import pandas as pd\nimport matplotlib.pyplot as plt\nimport pylab as pl\nfrom sklearn.metrics import roc_curve, auc, classification_report, confusion_matrix\n\n\ndef evaluate(model, X_te, y_te):\n \"\"\"\n Given the model and independent and dependent testing data,\n print out statements that evaluate classifier\n \"\"\"\n probs = model.predict_proba(X_te)\n plt.hist(probs[:, 1])\n plt.xlabel('Likelihood of Significant Financial')\n plt.ylabel('Frequency')\n print('Accuracy = ' + str(model.score(X_te, y_te)))\n y_hat = model.predict(X_te)\n print(classification_report(y_te, y_hat, labels=[0, 1]))\n y_hat = model.predict(X_te)\n confusion_matrix = pd.crosstab(y_hat, y_te, rownames=['Actual'],\n colnames=['Predicted'])\n print(confusion_matrix)\n\n\ndef plot_roc(probs, y_te):\n \"\"\"\n Plots ROC curve.\n \"\"\"\n plt.figure()\n fpr, tpr, thresholds = roc_curve(y_te, probs)\n roc_auc = auc(fpr, tpr)\n pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\n pl.plot([0, 1], [0, 1], 'k--')\n pl.xlim([0.0, 1.05])\n pl.ylim([0.0, 1.05])\n pl.xlabel('False Positive Rate')\n pl.ylabel('True Positive Rate')\n pl.title('ROC Curve')\n pl.legend(loc='lower right')\n pl.show()\n", "step-5": "# 6. Evaluate Classifier: you can use any metric you choose for this assignment \n# (accuracy is the easiest one). Feel free to evaluate it on the same data you \n# built the model on (this is not a good idea in general but for this assignment, \n# it is fine). We haven't covered models and evaluation yet, so don't worry about \n# creating validation sets or cross-validation. \n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pylab as pl\nfrom sklearn.metrics import roc_curve, auc, classification_report, confusion_matrix\n\n# credits to https://github.com/yhat/DataGotham2013/blob/master/notebooks/8%20-%20Fitting%20and%20Evaluating%20Your%20Model.ipynb\n\ndef evaluate(model, X_te, y_te):\n '''\n Given the model and independent and dependent testing data,\n print out statements that evaluate classifier\n '''\n probs = model.predict_proba(X_te)\n \n plt.hist(probs[:,1])\n plt.xlabel('Likelihood of Significant Financial')\n plt.ylabel('Frequency')\n\n # We should also look at Accuracy\n print(\"Accuracy = \" + str(model.score(X_te, y_te)))\n\n # Finally -- Precision & Recall\n y_hat = model.predict(X_te)\n print(classification_report(y_te, y_hat, labels=[0, 1]))\n \n y_hat = model.predict(X_te) \n confusion_matrix = pd.crosstab(y_hat, \n y_te, \n rownames=[\"Actual\"], \n colnames=[\"Predicted\"])\n print(confusion_matrix)\n\ndef plot_roc(probs, y_te):\n '''\n Plots ROC curve.\n '''\n plt.figure()\n fpr, tpr, thresholds = roc_curve(y_te, probs)\n roc_auc = auc(fpr, tpr)\n pl.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\n pl.plot([0, 1], [0, 1], 'k--')\n pl.xlim([0.0, 1.05])\n pl.ylim([0.0, 1.05])\n pl.xlabel('False Positive Rate')\n pl.ylabel('True Positive Rate')\n pl.title(\"ROC Curve\")\n pl.legend(loc=\"lower right\")\n pl.show()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
__author__ = 'tomer' import sqlite3 from random import randint import test_data def init_database(conn): c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS catalogs (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)''') c.execute('''CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)''') c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)''') c.execute('''CREATE TABLE IF NOT EXISTS products_bought (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)''') c.execute('''CREATE TABLE IF NOT EXISTS product_context (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)''') c.execute('''CREATE TABLE IF NOT EXISTS recommendations (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)''') def load_fake_data(conn): c = conn.cursor() c.execute('''DELETE FROM catalogs''') c.execute('''DELETE FROM products''') c.execute('''DELETE FROM users''') c.execute('''DELETE FROM products_bought''') c.execute('''DELETE FROM product_context''') c.execute('''DELETE FROM recommendations''') catalogs = [] c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''',('BestBuy',)) catalogs.append(c.lastrowid) c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''',('RiteAid',)) catalogs.append(c.lastrowid) ppl = [] c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Tomer',)) ppl.append(c.lastrowid) c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Alex',)) ppl.append(c.lastrowid) c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Matt',)) ppl.append(c.lastrowid) c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Rachael',)) ppl.append(c.lastrowid) c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Sam',)) ppl.append(c.lastrowid) c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Joey',)) ppl.append(c.lastrowid) products = [] # Load fake products for i in range(1,20): c.execute('''INSERT INTO products (id,sku_id,catalog_id, product_name, price,description) VALUES (NULL,?,?,?,?,?)''',(randint(1,2000),catalogs[randint(0,len(catalogs)-1)],'Movie' + str(i),randint(1,2000),'Title' + str(i))) products.append(c.lastrowid) # Load fake transactions for i in range(1,50): c.execute('''INSERT INTO products_bought (id,user_id, product_id) VALUES (NULL,?,?)''',(ppl[randint(0,len(ppl)-1)],products[randint(0,len(products)-1)])) values = (c.lastrowid,device[randint(0,len(device)-1)],oses[randint(0,len(oses)-1)], times[randint(0,len(times)-1)], days[randint(0,len(days)-1)], lats[randint(0,len(lats)-1)], lons[randint(0,len(lons)-1)],randint(0,5),randint(0,30)) c.execute('''INSERT INTO product_context (id,recommendation_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)''',values) # Load fake recommendations for i in range(1,1000): product_id = products[randint(0, len(products) - 1)] c.execute('''INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'true')''',(ppl[randint(0,len(ppl)-1)],product_id)) values = (c.lastrowid,product_id,device[randint(0,len(device)-1)],oses[randint(0,len(oses)-1)], times[randint(0,len(times)-1)], days[randint(0,len(days)-1)], lats[randint(0,len(lats)-1)], lons[randint(0,len(lons)-1)],randint(0,3),randint(0,3)) c.execute('''INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''',values) conn.commit() oses = ['IOS', 'Android']#, 'Windows10', 'macOS'] device = ['mobile']#, 'computer'] ''' times = ['10:33 AM', '2:38 PM', '3:01 AM', '12:31 AM', '2:56 PM', '8:01 AM', '5:00 PM', '9:38 PM', '3:01 AM'] ''' times = ['morning', 'afternoon', 'night'] days = ['M']#['M', 'T', 'W', 'R', 'F', 'S', 'Su'] ''' lats = ['-149.8935557', '-149.9054948', '-149.7522', '-149.8643361', '-149.8379726', '-149.9092788', '-149.7364877', '-149.8211', '-149.8445832', '-149.9728678'] ''' lats = ['north']#, 'south'] ''' lons = ['61.21759217', '61.19533942', '61.2297', '61.19525062', '61.13751355', '61.13994658', '61.19533265', '61.2156', '61.13806145', '61.176693'] ''' lons = ['east']#, 'west'] def get_users(conn): c = conn.cursor() c.execute('''select * from users''') return c.fetchall() def get_catalogs(conn): c = conn.cursor() c.execute('''select * from catalogs''') return c.fetchall() def get_products(conn, catalog_id): c = conn.cursor() c.execute('''select * from products where catalog_id = ?''',(catalog_id,)) return c.fetchall() def get_product_by_id(conn, catalog_id, product_id): c = conn.cursor() c.execute('''SELECT * FROM products WHERE catalog_id = ? AND id = ?''',(catalog_id,product_id)) return c.fetchall() def get_products_bought(conn, catalog_id): c = conn.cursor() c.execute('''select pb.* from products_bought pb, catalogs cat, products p where pb.product_id = p.id and p.catalog_id = ?''',(catalog_id,)) return c.fetchall() def get_all_data(conn): c = conn.cursor() c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id''') return c. fetchall() def get_data_for_user(conn,userid): c = conn.cursor() c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?''',(userid,)) return c.fetchall() def get_data_for_user_and_catalog(conn, userid, catalogid): c = conn.cursor() c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ? and c.id = ?''',(userid,catalogid)) return c.fetchall() def get_transactions_for_catalog(conn,catalogid): c = conn.cursor() c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and c.id = ?''',(catalogid,)) return c.fetchall() def get_recommendations_by_user(conn,userId): c = conn.cursor() c.execute('''select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.user_id = ?''',(userId,)) return c.fetchall() def get_recommendations_by_product(conn,productId): c = conn.cursor() c.execute('''select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?''',(productId,)) return c.fetchall() def get_connection(): return sqlite3.connect('recommendation_engine.db') def generate_context(product_id): return [product_id, device[randint(0, len(device) - 1)], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)] def add_recommendation(conn, product_ids,user_ids,contexts): ids = [] c = conn.cursor() for i in range(0,len(product_ids)): product_id = product_ids[i] user_id = user_ids[i] context = contexts[i] c.execute('''INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'false')''', (user_id, product_id)) context.insert(0,c.lastrowid) ids.append(c.lastrowid) c.execute( '''INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''', context) conn.commit() c.execute('select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.id in (%s)' % ','.join('?'*len(ids)), ids) return c.fetchall() def get_probability(conn, x, giveny): c = conn.cursor() query = '''select count(*) from product_context where ''' first = True params = [] for key,val in x.items(): if not first: query += ' and ' else: first = False query += str(key) + '=?' params.append(str(val)) c.execute(query,params) total = c.fetchone()[0] for key,val in giveny.items(): query += ' and ' + str(key) + '=?' params.append(str(val)) c.execute(query,params) smaller = c.fetchone()[0] if total == 0: return 0 else: return smaller/float(total) def load_test_data(conn): c = conn.cursor() # Clear database c.execute('''DELETE FROM catalogs''') c.execute('''DELETE FROM products''') c.execute('''DELETE FROM users''') c.execute('''DELETE FROM products_bought''') c.execute('''DELETE FROM product_context''') c.execute('''DELETE FROM recommendations''') # Initialize users user_names = test_data.USER_NAMES # Initialize movie names product_names = test_data.PRODUCT_NAMES # Initialize Prices prices = test_data.POSSIBLE_PRICES # Load test catalog catalog_ids = [] c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''', ('MovieDatabase',)) catalog_ids.append(c.lastrowid) # Load test users user_ids = [] for user in user_names: c.execute('''INSERT INTO users (user_name) VALUES (?)''', (user,)) user_ids.append(c.lastrowid) # Load test products product_ids = [] for product in product_names: values = (randint(1, 2000), catalog_ids[0], product, prices[randint(0, len(prices)-1)], 'desc') c.execute('''INSERT INTO products (id, sku_id, catalog_id, product_name, price, description) VALUES (NULL,?,?,?,?,?)''', values) product_ids.append(c.lastrowid) # Load fake transactions for i in range(1, 50): values = (user_ids[randint(0, len(user_ids)-1)], product_ids[randint(0, len(product_ids)-1)]) c.execute('''INSERT INTO products_bought (id,user_id,product_id) VALUES (NULL,?,?)''', values) values = (c.lastrowid, device[randint(0, len(device) - 1)], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)) c.execute('''INSERT INTO product_context (id,recommendation_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)''', values) # Load fake recommendations for i in range(1, 1000): product_id = product_ids[randint(0, len(product_ids)-1)] values = (user_ids[randint(0, len(user_ids)-1)], product_id,) c.execute('''INSERT INTO recommendations (id,user_id,product_id,interacted) VALUES (NULL,?,?,'True')''', values) values =(c.lastrowid, product_id, device[randint(0, len(device) - 1)], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)) c.execute('''INSERT INTO product_context (id,recommendation_id,product_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''', values) conn.commit()
normal
{ "blob_id": "46b1e5adbd956c35820d7d2b17628364388cdcd7", "index": 3638, "step-1": "<mask token>\n\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products\n (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products_bought\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS product_context\n (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS recommendations\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)\"\"\"\n )\n\n\n<mask token>\n\n\ndef get_users(conn):\n c = conn.cursor()\n c.execute('select * from users')\n return c.fetchall()\n\n\ndef get_catalogs(conn):\n c = conn.cursor()\n c.execute('select * from catalogs')\n return c.fetchall()\n\n\n<mask token>\n\n\ndef get_product_by_id(conn, catalog_id, product_id):\n c = conn.cursor()\n c.execute('SELECT * FROM products WHERE catalog_id = ? AND id = ?', (\n catalog_id, product_id))\n return c.fetchall()\n\n\n<mask token>\n\n\ndef get_all_data(conn):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id'\n )\n return c.fetchall()\n\n\ndef get_data_for_user(conn, userid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?'\n , (userid,))\n return c.fetchall()\n\n\n<mask token>\n\n\ndef get_recommendations_by_product(conn, productId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?'\n , (productId,))\n return c.fetchall()\n\n\n<mask token>\n\n\ndef generate_context(product_id):\n return [product_id, device[randint(0, len(device) - 1)], oses[randint(0,\n len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0,\n len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, \n len(lons) - 1)], randint(0, 3), randint(0, 3)]\n\n\n<mask token>\n\n\ndef get_probability(conn, x, giveny):\n c = conn.cursor()\n query = 'select count(*) from product_context where '\n first = True\n params = []\n for key, val in x.items():\n if not first:\n query += ' and '\n else:\n first = False\n query += str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n total = c.fetchone()[0]\n for key, val in giveny.items():\n query += ' and ' + str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n smaller = c.fetchone()[0]\n if total == 0:\n return 0\n else:\n return smaller / float(total)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products\n (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products_bought\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS product_context\n (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS recommendations\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)\"\"\"\n )\n\n\ndef load_fake_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n catalogs = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('BestBuy',))\n catalogs.append(c.lastrowid)\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('RiteAid',))\n catalogs.append(c.lastrowid)\n ppl = []\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Tomer',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Alex',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Matt',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Rachael',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Sam',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Joey',))\n ppl.append(c.lastrowid)\n products = []\n for i in range(1, 20):\n c.execute(\n 'INSERT INTO products (id,sku_id,catalog_id, product_name, price,description) VALUES (NULL,?,?,?,?,?)'\n , (randint(1, 2000), catalogs[randint(0, len(catalogs) - 1)], \n 'Movie' + str(i), randint(1, 2000), 'Title' + str(i)))\n products.append(c.lastrowid)\n for i in range(1, 50):\n c.execute(\n 'INSERT INTO products_bought (id,user_id, product_id) VALUES (NULL,?,?)'\n , (ppl[randint(0, len(ppl) - 1)], products[randint(0, len(\n products) - 1)]))\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 5), randint(0, 30)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = products[randint(0, len(products) - 1)]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'true')\"\n , (ppl[randint(0, len(ppl) - 1)], product_id))\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n\n\n<mask token>\n\n\ndef get_users(conn):\n c = conn.cursor()\n c.execute('select * from users')\n return c.fetchall()\n\n\ndef get_catalogs(conn):\n c = conn.cursor()\n c.execute('select * from catalogs')\n return c.fetchall()\n\n\ndef get_products(conn, catalog_id):\n c = conn.cursor()\n c.execute('select * from products where catalog_id = ?', (catalog_id,))\n return c.fetchall()\n\n\ndef get_product_by_id(conn, catalog_id, product_id):\n c = conn.cursor()\n c.execute('SELECT * FROM products WHERE catalog_id = ? AND id = ?', (\n catalog_id, product_id))\n return c.fetchall()\n\n\ndef get_products_bought(conn, catalog_id):\n c = conn.cursor()\n c.execute(\n 'select pb.* from products_bought pb, catalogs cat, products p where pb.product_id = p.id and p.catalog_id = ?'\n , (catalog_id,))\n return c.fetchall()\n\n\ndef get_all_data(conn):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id'\n )\n return c.fetchall()\n\n\ndef get_data_for_user(conn, userid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?'\n , (userid,))\n return c.fetchall()\n\n\ndef get_data_for_user_and_catalog(conn, userid, catalogid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ? and c.id = ?'\n , (userid, catalogid))\n return c.fetchall()\n\n\n<mask token>\n\n\ndef get_recommendations_by_user(conn, userId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.user_id = ?'\n , (userId,))\n return c.fetchall()\n\n\ndef get_recommendations_by_product(conn, productId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?'\n , (productId,))\n return c.fetchall()\n\n\ndef get_connection():\n return sqlite3.connect('recommendation_engine.db')\n\n\ndef generate_context(product_id):\n return [product_id, device[randint(0, len(device) - 1)], oses[randint(0,\n len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0,\n len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, \n len(lons) - 1)], randint(0, 3), randint(0, 3)]\n\n\ndef add_recommendation(conn, product_ids, user_ids, contexts):\n ids = []\n c = conn.cursor()\n for i in range(0, len(product_ids)):\n product_id = product_ids[i]\n user_id = user_ids[i]\n context = contexts[i]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'false')\"\n , (user_id, product_id))\n context.insert(0, c.lastrowid)\n ids.append(c.lastrowid)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , context)\n conn.commit()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.id in (%s)'\n % ','.join('?' * len(ids)), ids)\n return c.fetchall()\n\n\ndef get_probability(conn, x, giveny):\n c = conn.cursor()\n query = 'select count(*) from product_context where '\n first = True\n params = []\n for key, val in x.items():\n if not first:\n query += ' and '\n else:\n first = False\n query += str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n total = c.fetchone()[0]\n for key, val in giveny.items():\n query += ' and ' + str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n smaller = c.fetchone()[0]\n if total == 0:\n return 0\n else:\n return smaller / float(total)\n\n\ndef load_test_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n user_names = test_data.USER_NAMES\n product_names = test_data.PRODUCT_NAMES\n prices = test_data.POSSIBLE_PRICES\n catalog_ids = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', (\n 'MovieDatabase',))\n catalog_ids.append(c.lastrowid)\n user_ids = []\n for user in user_names:\n c.execute('INSERT INTO users (user_name) VALUES (?)', (user,))\n user_ids.append(c.lastrowid)\n product_ids = []\n for product in product_names:\n values = randint(1, 2000), catalog_ids[0], product, prices[randint(\n 0, len(prices) - 1)], 'desc'\n c.execute(\n 'INSERT INTO products (id, sku_id, catalog_id, product_name, price, description) VALUES (NULL,?,?,?,?,?)'\n , values)\n product_ids.append(c.lastrowid)\n for i in range(1, 50):\n values = user_ids[randint(0, len(user_ids) - 1)], product_ids[randint\n (0, len(product_ids) - 1)]\n c.execute(\n 'INSERT INTO products_bought (id,user_id,product_id) VALUES (NULL,?,?)'\n , values)\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = product_ids[randint(0, len(product_ids) - 1)]\n values = user_ids[randint(0, len(user_ids) - 1)], product_id\n c.execute(\n \"INSERT INTO recommendations (id,user_id,product_id,interacted) VALUES (NULL,?,?,'True')\"\n , values)\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,product_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n", "step-3": "__author__ = 'tomer'\n<mask token>\n\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products\n (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products_bought\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS product_context\n (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS recommendations\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)\"\"\"\n )\n\n\ndef load_fake_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n catalogs = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('BestBuy',))\n catalogs.append(c.lastrowid)\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('RiteAid',))\n catalogs.append(c.lastrowid)\n ppl = []\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Tomer',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Alex',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Matt',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Rachael',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Sam',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Joey',))\n ppl.append(c.lastrowid)\n products = []\n for i in range(1, 20):\n c.execute(\n 'INSERT INTO products (id,sku_id,catalog_id, product_name, price,description) VALUES (NULL,?,?,?,?,?)'\n , (randint(1, 2000), catalogs[randint(0, len(catalogs) - 1)], \n 'Movie' + str(i), randint(1, 2000), 'Title' + str(i)))\n products.append(c.lastrowid)\n for i in range(1, 50):\n c.execute(\n 'INSERT INTO products_bought (id,user_id, product_id) VALUES (NULL,?,?)'\n , (ppl[randint(0, len(ppl) - 1)], products[randint(0, len(\n products) - 1)]))\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 5), randint(0, 30)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = products[randint(0, len(products) - 1)]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'true')\"\n , (ppl[randint(0, len(ppl) - 1)], product_id))\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n\n\noses = ['IOS', 'Android']\ndevice = ['mobile']\n<mask token>\ntimes = ['morning', 'afternoon', 'night']\ndays = ['M']\n<mask token>\nlats = ['north']\n<mask token>\nlons = ['east']\n\n\ndef get_users(conn):\n c = conn.cursor()\n c.execute('select * from users')\n return c.fetchall()\n\n\ndef get_catalogs(conn):\n c = conn.cursor()\n c.execute('select * from catalogs')\n return c.fetchall()\n\n\ndef get_products(conn, catalog_id):\n c = conn.cursor()\n c.execute('select * from products where catalog_id = ?', (catalog_id,))\n return c.fetchall()\n\n\ndef get_product_by_id(conn, catalog_id, product_id):\n c = conn.cursor()\n c.execute('SELECT * FROM products WHERE catalog_id = ? AND id = ?', (\n catalog_id, product_id))\n return c.fetchall()\n\n\ndef get_products_bought(conn, catalog_id):\n c = conn.cursor()\n c.execute(\n 'select pb.* from products_bought pb, catalogs cat, products p where pb.product_id = p.id and p.catalog_id = ?'\n , (catalog_id,))\n return c.fetchall()\n\n\ndef get_all_data(conn):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id'\n )\n return c.fetchall()\n\n\ndef get_data_for_user(conn, userid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?'\n , (userid,))\n return c.fetchall()\n\n\ndef get_data_for_user_and_catalog(conn, userid, catalogid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ? and c.id = ?'\n , (userid, catalogid))\n return c.fetchall()\n\n\ndef get_transactions_for_catalog(conn, catalogid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and c.id = ?'\n , (catalogid,))\n return c.fetchall()\n\n\ndef get_recommendations_by_user(conn, userId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.user_id = ?'\n , (userId,))\n return c.fetchall()\n\n\ndef get_recommendations_by_product(conn, productId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?'\n , (productId,))\n return c.fetchall()\n\n\ndef get_connection():\n return sqlite3.connect('recommendation_engine.db')\n\n\ndef generate_context(product_id):\n return [product_id, device[randint(0, len(device) - 1)], oses[randint(0,\n len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0,\n len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, \n len(lons) - 1)], randint(0, 3), randint(0, 3)]\n\n\ndef add_recommendation(conn, product_ids, user_ids, contexts):\n ids = []\n c = conn.cursor()\n for i in range(0, len(product_ids)):\n product_id = product_ids[i]\n user_id = user_ids[i]\n context = contexts[i]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'false')\"\n , (user_id, product_id))\n context.insert(0, c.lastrowid)\n ids.append(c.lastrowid)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , context)\n conn.commit()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.id in (%s)'\n % ','.join('?' * len(ids)), ids)\n return c.fetchall()\n\n\ndef get_probability(conn, x, giveny):\n c = conn.cursor()\n query = 'select count(*) from product_context where '\n first = True\n params = []\n for key, val in x.items():\n if not first:\n query += ' and '\n else:\n first = False\n query += str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n total = c.fetchone()[0]\n for key, val in giveny.items():\n query += ' and ' + str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n smaller = c.fetchone()[0]\n if total == 0:\n return 0\n else:\n return smaller / float(total)\n\n\ndef load_test_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n user_names = test_data.USER_NAMES\n product_names = test_data.PRODUCT_NAMES\n prices = test_data.POSSIBLE_PRICES\n catalog_ids = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', (\n 'MovieDatabase',))\n catalog_ids.append(c.lastrowid)\n user_ids = []\n for user in user_names:\n c.execute('INSERT INTO users (user_name) VALUES (?)', (user,))\n user_ids.append(c.lastrowid)\n product_ids = []\n for product in product_names:\n values = randint(1, 2000), catalog_ids[0], product, prices[randint(\n 0, len(prices) - 1)], 'desc'\n c.execute(\n 'INSERT INTO products (id, sku_id, catalog_id, product_name, price, description) VALUES (NULL,?,?,?,?,?)'\n , values)\n product_ids.append(c.lastrowid)\n for i in range(1, 50):\n values = user_ids[randint(0, len(user_ids) - 1)], product_ids[randint\n (0, len(product_ids) - 1)]\n c.execute(\n 'INSERT INTO products_bought (id,user_id,product_id) VALUES (NULL,?,?)'\n , values)\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = product_ids[randint(0, len(product_ids) - 1)]\n values = user_ids[randint(0, len(user_ids) - 1)], product_id\n c.execute(\n \"INSERT INTO recommendations (id,user_id,product_id,interacted) VALUES (NULL,?,?,'True')\"\n , values)\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,product_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n", "step-4": "__author__ = 'tomer'\nimport sqlite3\nfrom random import randint\nimport test_data\n\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products\n (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS products_bought\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS product_context\n (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)\"\"\"\n )\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS recommendations\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)\"\"\"\n )\n\n\ndef load_fake_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n catalogs = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('BestBuy',))\n catalogs.append(c.lastrowid)\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', ('RiteAid',))\n catalogs.append(c.lastrowid)\n ppl = []\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Tomer',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Alex',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Matt',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Rachael',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Sam',))\n ppl.append(c.lastrowid)\n c.execute('INSERT INTO users (user_name) VALUES (?)', ('Joey',))\n ppl.append(c.lastrowid)\n products = []\n for i in range(1, 20):\n c.execute(\n 'INSERT INTO products (id,sku_id,catalog_id, product_name, price,description) VALUES (NULL,?,?,?,?,?)'\n , (randint(1, 2000), catalogs[randint(0, len(catalogs) - 1)], \n 'Movie' + str(i), randint(1, 2000), 'Title' + str(i)))\n products.append(c.lastrowid)\n for i in range(1, 50):\n c.execute(\n 'INSERT INTO products_bought (id,user_id, product_id) VALUES (NULL,?,?)'\n , (ppl[randint(0, len(ppl) - 1)], products[randint(0, len(\n products) - 1)]))\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 5), randint(0, 30)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = products[randint(0, len(products) - 1)]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'true')\"\n , (ppl[randint(0, len(ppl) - 1)], product_id))\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n\n\noses = ['IOS', 'Android']\ndevice = ['mobile']\n<mask token>\ntimes = ['morning', 'afternoon', 'night']\ndays = ['M']\n<mask token>\nlats = ['north']\n<mask token>\nlons = ['east']\n\n\ndef get_users(conn):\n c = conn.cursor()\n c.execute('select * from users')\n return c.fetchall()\n\n\ndef get_catalogs(conn):\n c = conn.cursor()\n c.execute('select * from catalogs')\n return c.fetchall()\n\n\ndef get_products(conn, catalog_id):\n c = conn.cursor()\n c.execute('select * from products where catalog_id = ?', (catalog_id,))\n return c.fetchall()\n\n\ndef get_product_by_id(conn, catalog_id, product_id):\n c = conn.cursor()\n c.execute('SELECT * FROM products WHERE catalog_id = ? AND id = ?', (\n catalog_id, product_id))\n return c.fetchall()\n\n\ndef get_products_bought(conn, catalog_id):\n c = conn.cursor()\n c.execute(\n 'select pb.* from products_bought pb, catalogs cat, products p where pb.product_id = p.id and p.catalog_id = ?'\n , (catalog_id,))\n return c.fetchall()\n\n\ndef get_all_data(conn):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id'\n )\n return c.fetchall()\n\n\ndef get_data_for_user(conn, userid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?'\n , (userid,))\n return c.fetchall()\n\n\ndef get_data_for_user_and_catalog(conn, userid, catalogid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ? and c.id = ?'\n , (userid, catalogid))\n return c.fetchall()\n\n\ndef get_transactions_for_catalog(conn, catalogid):\n c = conn.cursor()\n c.execute(\n 'select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and c.id = ?'\n , (catalogid,))\n return c.fetchall()\n\n\ndef get_recommendations_by_user(conn, userId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.user_id = ?'\n , (userId,))\n return c.fetchall()\n\n\ndef get_recommendations_by_product(conn, productId):\n c = conn.cursor()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?'\n , (productId,))\n return c.fetchall()\n\n\ndef get_connection():\n return sqlite3.connect('recommendation_engine.db')\n\n\ndef generate_context(product_id):\n return [product_id, device[randint(0, len(device) - 1)], oses[randint(0,\n len(oses) - 1)], times[randint(0, len(times) - 1)], days[randint(0,\n len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[randint(0, \n len(lons) - 1)], randint(0, 3), randint(0, 3)]\n\n\ndef add_recommendation(conn, product_ids, user_ids, contexts):\n ids = []\n c = conn.cursor()\n for i in range(0, len(product_ids)):\n product_id = product_ids[i]\n user_id = user_ids[i]\n context = contexts[i]\n c.execute(\n \"INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'false')\"\n , (user_id, product_id))\n context.insert(0, c.lastrowid)\n ids.append(c.lastrowid)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , context)\n conn.commit()\n c.execute(\n 'select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.id in (%s)'\n % ','.join('?' * len(ids)), ids)\n return c.fetchall()\n\n\ndef get_probability(conn, x, giveny):\n c = conn.cursor()\n query = 'select count(*) from product_context where '\n first = True\n params = []\n for key, val in x.items():\n if not first:\n query += ' and '\n else:\n first = False\n query += str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n total = c.fetchone()[0]\n for key, val in giveny.items():\n query += ' and ' + str(key) + '=?'\n params.append(str(val))\n c.execute(query, params)\n smaller = c.fetchone()[0]\n if total == 0:\n return 0\n else:\n return smaller / float(total)\n\n\ndef load_test_data(conn):\n c = conn.cursor()\n c.execute('DELETE FROM catalogs')\n c.execute('DELETE FROM products')\n c.execute('DELETE FROM users')\n c.execute('DELETE FROM products_bought')\n c.execute('DELETE FROM product_context')\n c.execute('DELETE FROM recommendations')\n user_names = test_data.USER_NAMES\n product_names = test_data.PRODUCT_NAMES\n prices = test_data.POSSIBLE_PRICES\n catalog_ids = []\n c.execute('INSERT INTO catalogs (catalog_name) VALUES (?)', (\n 'MovieDatabase',))\n catalog_ids.append(c.lastrowid)\n user_ids = []\n for user in user_names:\n c.execute('INSERT INTO users (user_name) VALUES (?)', (user,))\n user_ids.append(c.lastrowid)\n product_ids = []\n for product in product_names:\n values = randint(1, 2000), catalog_ids[0], product, prices[randint(\n 0, len(prices) - 1)], 'desc'\n c.execute(\n 'INSERT INTO products (id, sku_id, catalog_id, product_name, price, description) VALUES (NULL,?,?,?,?,?)'\n , values)\n product_ids.append(c.lastrowid)\n for i in range(1, 50):\n values = user_ids[randint(0, len(user_ids) - 1)], product_ids[randint\n (0, len(product_ids) - 1)]\n c.execute(\n 'INSERT INTO products_bought (id,user_id,product_id) VALUES (NULL,?,?)'\n , values)\n values = c.lastrowid, device[randint(0, len(device) - 1)], oses[randint\n (0, len(oses) - 1)], times[randint(0, len(times) - 1)], days[\n randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)], lons[\n randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)'\n , values)\n for i in range(1, 1000):\n product_id = product_ids[randint(0, len(product_ids) - 1)]\n values = user_ids[randint(0, len(user_ids) - 1)], product_id\n c.execute(\n \"INSERT INTO recommendations (id,user_id,product_id,interacted) VALUES (NULL,?,?,'True')\"\n , values)\n values = c.lastrowid, product_id, device[randint(0, len(device) - 1)\n ], oses[randint(0, len(oses) - 1)], times[randint(0, len(times) -\n 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) -\n 1)], lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)\n c.execute(\n 'INSERT INTO product_context (id,recommendation_id,product_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)'\n , values)\n conn.commit()\n", "step-5": "__author__ = 'tomer'\nimport sqlite3\nfrom random import randint\nimport test_data\n\ndef init_database(conn):\n c = conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS catalogs\n (id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)''')\n c.execute('''CREATE TABLE IF NOT EXISTS products\n (id INTEGER PRIMARY KEY AUTOINCREMENT, sku_id INTEGER, catalog_id INTEGER, product_name TEXT, price FLOAT, description TEXT)''')\n c.execute('''CREATE TABLE IF NOT EXISTS users\n (id INTEGER PRIMARY KEY AUTOINCREMENT, user_name TEXT)''')\n c.execute('''CREATE TABLE IF NOT EXISTS products_bought\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER,product_id INTEGER)''')\n c.execute('''CREATE TABLE IF NOT EXISTS product_context\n (id INTEGER PRIMARY KEY AUTOINCREMENT,recommendation_id INTEGER, product_id INTEGER, device TEXT, os TEXT, time_of_day TEXT, day_of_week TEXT, latitude float, longitude float,num_items_in_cart INTEGER, purchases_in_last_month INTEGER)''')\n c.execute('''CREATE TABLE IF NOT EXISTS recommendations\n (id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER, product_id INTEGER, interacted BOOLEAN)''')\n\n\ndef load_fake_data(conn):\n\n c = conn.cursor()\n c.execute('''DELETE FROM catalogs''')\n c.execute('''DELETE FROM products''')\n c.execute('''DELETE FROM users''')\n c.execute('''DELETE FROM products_bought''')\n c.execute('''DELETE FROM product_context''')\n c.execute('''DELETE FROM recommendations''')\n\n catalogs = []\n c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''',('BestBuy',))\n catalogs.append(c.lastrowid)\n c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''',('RiteAid',))\n catalogs.append(c.lastrowid)\n\n\n ppl = []\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Tomer',))\n ppl.append(c.lastrowid)\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Alex',))\n ppl.append(c.lastrowid)\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Matt',))\n ppl.append(c.lastrowid)\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Rachael',))\n ppl.append(c.lastrowid)\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Sam',))\n ppl.append(c.lastrowid)\n c.execute('''INSERT INTO users (user_name) VALUES (?)''',('Joey',))\n ppl.append(c.lastrowid)\n\n products = []\n # Load fake products\n for i in range(1,20):\n c.execute('''INSERT INTO products (id,sku_id,catalog_id, product_name, price,description) VALUES (NULL,?,?,?,?,?)''',(randint(1,2000),catalogs[randint(0,len(catalogs)-1)],'Movie' + str(i),randint(1,2000),'Title' + str(i)))\n products.append(c.lastrowid)\n\n # Load fake transactions\n for i in range(1,50):\n c.execute('''INSERT INTO products_bought (id,user_id, product_id) VALUES (NULL,?,?)''',(ppl[randint(0,len(ppl)-1)],products[randint(0,len(products)-1)]))\n values = (c.lastrowid,device[randint(0,len(device)-1)],oses[randint(0,len(oses)-1)], times[randint(0,len(times)-1)], days[randint(0,len(days)-1)], lats[randint(0,len(lats)-1)], lons[randint(0,len(lons)-1)],randint(0,5),randint(0,30))\n c.execute('''INSERT INTO product_context (id,recommendation_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)''',values)\n\n # Load fake recommendations\n for i in range(1,1000):\n product_id = products[randint(0, len(products) - 1)]\n c.execute('''INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'true')''',(ppl[randint(0,len(ppl)-1)],product_id))\n values = (c.lastrowid,product_id,device[randint(0,len(device)-1)],oses[randint(0,len(oses)-1)], times[randint(0,len(times)-1)], days[randint(0,len(days)-1)], lats[randint(0,len(lats)-1)], lons[randint(0,len(lons)-1)],randint(0,3),randint(0,3))\n c.execute('''INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''',values)\n conn.commit()\n\n\noses = ['IOS', 'Android']#, 'Windows10', 'macOS']\ndevice = ['mobile']#, 'computer']\n'''\ntimes = ['10:33 AM',\n'2:38 PM',\n'3:01 AM',\n'12:31 AM',\n'2:56 PM',\n'8:01 AM',\n'5:00 PM',\n'9:38 PM',\n'3:01 AM']\n'''\ntimes = ['morning', 'afternoon', 'night']\n\ndays = ['M']#['M', 'T', 'W', 'R', 'F', 'S', 'Su']\n\n'''\nlats = ['-149.8935557',\n'-149.9054948',\n'-149.7522',\n'-149.8643361',\n'-149.8379726',\n'-149.9092788',\n'-149.7364877',\n'-149.8211',\n'-149.8445832',\n'-149.9728678']\n'''\nlats = ['north']#, 'south']\n\n'''\nlons = ['61.21759217',\n'61.19533942',\n'61.2297',\n'61.19525062',\n'61.13751355',\n'61.13994658',\n'61.19533265',\n'61.2156',\n'61.13806145',\n'61.176693']\n'''\nlons = ['east']#, 'west']\n\n\ndef get_users(conn):\n c = conn.cursor()\n c.execute('''select * from users''')\n return c.fetchall()\n\n\ndef get_catalogs(conn):\n c = conn.cursor()\n c.execute('''select * from catalogs''')\n return c.fetchall()\n\n\ndef get_products(conn, catalog_id):\n c = conn.cursor()\n c.execute('''select * from products where catalog_id = ?''',(catalog_id,))\n return c.fetchall()\n\n\ndef get_product_by_id(conn, catalog_id, product_id):\n c = conn.cursor()\n c.execute('''SELECT * FROM products WHERE catalog_id = ? AND id = ?''',(catalog_id,product_id))\n return c.fetchall()\n\n\ndef get_products_bought(conn, catalog_id):\n c = conn.cursor()\n c.execute('''select pb.* from products_bought pb, catalogs cat, products p where pb.product_id = p.id and p.catalog_id = ?''',(catalog_id,))\n return c.fetchall()\n\n\ndef get_all_data(conn):\n c = conn.cursor()\n c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id''')\n return c. fetchall()\n\n\ndef get_data_for_user(conn,userid):\n c = conn.cursor()\n c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ?''',(userid,))\n return c.fetchall()\n\n\ndef get_data_for_user_and_catalog(conn, userid, catalogid):\n c = conn.cursor()\n c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and u.id = ? and c.id = ?''',(userid,catalogid))\n return c.fetchall()\n\n\ndef get_transactions_for_catalog(conn,catalogid):\n c = conn.cursor()\n c.execute('''select u.*, p.*, c.* from users u, products p, products_bought pb, catalogs c where p.id = pb.product_id and p.catalog_id == c.id and u.id = pb.user_id and c.id = ?''',(catalogid,))\n return c.fetchall()\n\n\ndef get_recommendations_by_user(conn,userId):\n c = conn.cursor()\n c.execute('''select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.user_id = ?''',(userId,))\n return c.fetchall()\n\n\ndef get_recommendations_by_product(conn,productId):\n c = conn.cursor()\n c.execute('''select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.product_id = ?''',(productId,))\n return c.fetchall()\n\n\ndef get_connection():\n return sqlite3.connect('recommendation_engine.db')\n\n\ndef generate_context(product_id):\n return [product_id, device[randint(0, len(device) - 1)], oses[randint(0, len(oses) - 1)],\n times[randint(0, len(times) - 1)], days[randint(0, len(days) - 1)], lats[randint(0, len(lats) - 1)],\n lons[randint(0, len(lons) - 1)], randint(0, 3), randint(0, 3)]\n\n\ndef add_recommendation(conn, product_ids,user_ids,contexts):\n ids = []\n c = conn.cursor()\n for i in range(0,len(product_ids)):\n product_id = product_ids[i]\n user_id = user_ids[i]\n context = contexts[i]\n c.execute('''INSERT INTO recommendations (id,user_id, product_id, interacted) VALUES (NULL,?,?,'false')''',\n (user_id, product_id))\n context.insert(0,c.lastrowid)\n ids.append(c.lastrowid)\n c.execute( '''INSERT INTO product_context (id,recommendation_id , product_id , device , os , time_of_day , day_of_week , latitude , longitude ,num_items_in_cart , purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''',\n context)\n conn.commit()\n c.execute('select r.*, c.* from recommendations r, product_context c where r.id = c.recommendation_id and r.id in (%s)' %\n ','.join('?'*len(ids)), ids)\n return c.fetchall()\n\n\ndef get_probability(conn, x, giveny):\n c = conn.cursor()\n query = '''select count(*) from product_context where '''\n first = True\n params = []\n for key,val in x.items():\n if not first:\n query += ' and '\n else:\n first = False\n query += str(key) + '=?'\n params.append(str(val))\n c.execute(query,params)\n total = c.fetchone()[0]\n\n for key,val in giveny.items():\n query += ' and ' + str(key) + '=?'\n params.append(str(val))\n c.execute(query,params)\n smaller = c.fetchone()[0]\n if total == 0:\n return 0\n else:\n return smaller/float(total)\n\n\ndef load_test_data(conn):\n c = conn.cursor()\n\n # Clear database\n c.execute('''DELETE FROM catalogs''')\n c.execute('''DELETE FROM products''')\n c.execute('''DELETE FROM users''')\n c.execute('''DELETE FROM products_bought''')\n c.execute('''DELETE FROM product_context''')\n c.execute('''DELETE FROM recommendations''')\n\n # Initialize users\n user_names = test_data.USER_NAMES\n\n # Initialize movie names\n product_names = test_data.PRODUCT_NAMES\n\n # Initialize Prices\n prices = test_data.POSSIBLE_PRICES\n\n # Load test catalog\n catalog_ids = []\n c.execute('''INSERT INTO catalogs (catalog_name) VALUES (?)''', ('MovieDatabase',))\n catalog_ids.append(c.lastrowid)\n\n # Load test users\n user_ids = []\n for user in user_names:\n c.execute('''INSERT INTO users (user_name) VALUES (?)''', (user,))\n user_ids.append(c.lastrowid)\n\n # Load test products\n product_ids = []\n for product in product_names:\n values = (randint(1, 2000), catalog_ids[0], product, prices[randint(0, len(prices)-1)], 'desc')\n c.execute('''INSERT INTO products (id, sku_id, catalog_id, product_name, price, description) VALUES (NULL,?,?,?,?,?)''', values)\n product_ids.append(c.lastrowid)\n\n # Load fake transactions\n for i in range(1, 50):\n values = (user_ids[randint(0, len(user_ids)-1)], product_ids[randint(0, len(product_ids)-1)])\n c.execute('''INSERT INTO products_bought (id,user_id,product_id) VALUES (NULL,?,?)''', values)\n\n values = (c.lastrowid,\n device[randint(0, len(device) - 1)],\n oses[randint(0, len(oses) - 1)],\n times[randint(0, len(times) - 1)],\n days[randint(0, len(days) - 1)],\n lats[randint(0, len(lats) - 1)],\n lons[randint(0, len(lons) - 1)],\n randint(0, 3),\n randint(0, 3))\n c.execute('''INSERT INTO product_context (id,recommendation_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?)''', values)\n\n # Load fake recommendations\n for i in range(1, 1000):\n product_id = product_ids[randint(0, len(product_ids)-1)]\n values = (user_ids[randint(0, len(user_ids)-1)], product_id,)\n c.execute('''INSERT INTO recommendations (id,user_id,product_id,interacted) VALUES (NULL,?,?,'True')''', values)\n\n values =(c.lastrowid,\n product_id,\n device[randint(0, len(device) - 1)],\n oses[randint(0, len(oses) - 1)],\n times[randint(0, len(times) - 1)],\n days[randint(0, len(days) - 1)],\n lats[randint(0, len(lats) - 1)],\n lons[randint(0, len(lons) - 1)],\n randint(0, 3),\n randint(0, 3))\n c.execute('''INSERT INTO product_context (id,recommendation_id,product_id,device,os,time_of_day,day_of_week,latitude,longitude,num_items_in_cart,purchases_in_last_month) VALUES (NULL,?,?,?,?,?,?,?,?,?,?)''', values)\n\n conn.commit()\n\n", "step-ids": [ 9, 17, 19, 20, 21 ] }
[ 9, 17, 19, 20, 21 ]
# use local image import io import os from google.cloud import vision from google.oauth2 import service_account creds = service_account.Credentials.from_service_account_file('./key.json') client = vision.ImageAnnotatorClient( credentials=creds, ) # The name of the image file to annotate file_name = os.path.join( os.path.dirname(__file__), "./dog.jpg") # Loads the image into memory with io.open(file_name, 'rb') as image_file: content = image_file.read() request = { "image": { "content": content }, "features": [ { "max_results": 2, "type": "LABEL_DETECTION" }, { "type": "SAFE_SEARCH_DETECTION" } ] } response = client.annotate_image(request) print(response) print(response.safe_search_annotation.adult) for label in response.label_annotations: print(label.description)
normal
{ "blob_id": "800573786913ff2fc37845193b5584a0a815533f", "index": 8340, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n<mask token>\nprint(response)\nprint(response.safe_search_annotation.adult)\nfor label in response.label_annotations:\n print(label.description)\n", "step-3": "<mask token>\ncreds = service_account.Credentials.from_service_account_file('./key.json')\nclient = vision.ImageAnnotatorClient(credentials=creds)\nfile_name = os.path.join(os.path.dirname(__file__), './dog.jpg')\nwith io.open(file_name, 'rb') as image_file:\n content = image_file.read()\nrequest = {'image': {'content': content}, 'features': [{'max_results': 2,\n 'type': 'LABEL_DETECTION'}, {'type': 'SAFE_SEARCH_DETECTION'}]}\nresponse = client.annotate_image(request)\nprint(response)\nprint(response.safe_search_annotation.adult)\nfor label in response.label_annotations:\n print(label.description)\n", "step-4": "import io\nimport os\nfrom google.cloud import vision\nfrom google.oauth2 import service_account\ncreds = service_account.Credentials.from_service_account_file('./key.json')\nclient = vision.ImageAnnotatorClient(credentials=creds)\nfile_name = os.path.join(os.path.dirname(__file__), './dog.jpg')\nwith io.open(file_name, 'rb') as image_file:\n content = image_file.read()\nrequest = {'image': {'content': content}, 'features': [{'max_results': 2,\n 'type': 'LABEL_DETECTION'}, {'type': 'SAFE_SEARCH_DETECTION'}]}\nresponse = client.annotate_image(request)\nprint(response)\nprint(response.safe_search_annotation.adult)\nfor label in response.label_annotations:\n print(label.description)\n", "step-5": "# use local image\n\nimport io\nimport os\n\nfrom google.cloud import vision\nfrom google.oauth2 import service_account\n\ncreds = service_account.Credentials.from_service_account_file('./key.json')\n\nclient = vision.ImageAnnotatorClient(\n credentials=creds,\n)\n\n# The name of the image file to annotate\nfile_name = os.path.join(\n os.path.dirname(__file__),\n \"./dog.jpg\")\n\n# Loads the image into memory\nwith io.open(file_name, 'rb') as image_file:\n content = image_file.read()\n\nrequest = {\n \"image\": {\n \"content\": content\n }, \n \"features\": [\n {\n \"max_results\": 2,\n \"type\": \"LABEL_DETECTION\"\n },\n {\n \"type\": \"SAFE_SEARCH_DETECTION\"\n }\n ]\n}\n\nresponse = client.annotate_image(request)\n\nprint(response)\n\nprint(response.safe_search_annotation.adult)\n\nfor label in response.label_annotations:\n print(label.description)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from flask import Flask, request, g from flask_restful import Resource, Api from sqlalchemy import create_engine from flask import jsonify import json import eth_account import algosdk from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.orm import load_only from datetime import datetime import sys from models import Base, Order, Log engine = create_engine('sqlite:///orders.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) app = Flask(__name__) # These decorators allow you to use g.session to access the database inside the request code # g is an "application global" https://flask.palletsprojects.com/en/1.1.x/api/#application-globals @app.before_request def create_session(): g.session = scoped_session(DBSession) @app.teardown_appcontext # def shutdown_session(response_or_exc): def shutdown_session(exception=None): sys.stdout.flush() g.session.commit() g.session.remove() """ Suggested helper methods """ # check whether “sig” is a valid signature of json.dumps(payload), # using the signature algorithm specified by the platform field. # Be sure to verify the payload using the sender_pk. def check_sig(payload,sig): pk = payload['sender_pk'] platform = payload['platform'] payload_json = json.dumps(payload) result = False if platform == "Algorand": print("Algorand") if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk): print("Algo sig verifies!") result = True elif platform == "Ethereum": print("Ethereum") eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json) if eth_account.Account.recover_message(eth_encoded_msg, signature=sig) == pk: print("Eth sig verifies!") result = True return result, payload_json # def fill_order(order,txes=[]): # pass # the inner recursive function def fill_order(): # get the order you just inserted from the DB current_order = g.session.query(Order).order_by(Order.id.desc()).first() # print("_order_id") # print(current_order.id) # Check if there are any existing orders that match and add them into a list order_list = [] orders = g.session.query(Order).filter(Order.filled == None).all() for existing_order in orders: # if ((existing_order.buy_amount != 0) and (current_order.sell_amount != 0)): if ((existing_order.buy_currency == current_order.sell_currency) and (existing_order.sell_currency == current_order.buy_currency) and (existing_order.sell_amount / existing_order.buy_amount >= current_order.buy_amount / current_order.sell_amount) and (existing_order.counterparty_id == None)): order_list.append(existing_order) # If a match is found between order and existing_order if (len(order_list) > 0): # print(" order_list_length") # print(len(order_list)) # pick the first one in the list match_order = order_list[0] # Set the filled field to be the current timestamp on both orders # Set counterparty_id to be the id of the other order match_order.filled = datetime.now() current_order.filled = datetime.now() match_order.counterparty_id = current_order.id current_order.counterparty_id = match_order.id g.session.commit() # if both orders can completely fill each other # no child order needs to be generated # If match_order is not completely filled if (current_order.sell_amount < match_order.buy_amount): # print("_match_order is not completely filled") diff = match_order.buy_amount - current_order.sell_amount exchange_rate_match = match_order.sell_amount / match_order.buy_amount sell_amount_new_match = diff * exchange_rate_match # print(match_order.id) # print(diff) # print(sell_amount_new_match) new_order = Order(sender_pk=match_order.sender_pk, receiver_pk=match_order.receiver_pk, buy_currency=match_order.buy_currency, sell_currency=match_order.sell_currency, buy_amount=diff, sell_amount=sell_amount_new_match, creator_id=match_order.id) g.session.add(new_order) g.session.commit() print("M") fill_order() # If current_order is not completely filled if (current_order.buy_amount > match_order.sell_amount): # print("_current_order is not completely filled") diff = current_order.buy_amount - match_order.sell_amount exchange_rate_current = current_order.buy_amount / current_order.sell_amount sell_amount_new_current = diff / exchange_rate_current # print(current_order.id) # print(diff) # print(sell_amount_new_current) new_order = Order(sender_pk=current_order.sender_pk, receiver_pk=current_order.receiver_pk, buy_currency=current_order.buy_currency, sell_currency=current_order.sell_currency, buy_amount=diff, sell_amount=sell_amount_new_current, creator_id=current_order.id) g.session.add(new_order) g.session.commit() print("C") fill_order() # Takes input dictionary d and writes it to the Log table # Hint: use json.dumps or str() to get it in a nice string form def log_message(d): create_session() order_obj = Log(message=d) g.session.add(order_obj) shutdown_session() # convert a row in DB into a dict def row2dict(row): return { c.name: getattr(row, c.name) for c in row.__table__.columns } # print a dictionary nicely def print_dict(d): for key, value in d.items(): print(key, ' : ', value) """ End of helper methods """ @app.route('/trade', methods=['POST']) def trade(): print("In trade endpoint") if request.method == "POST": print("--------- trade ---------") content = request.get_json(silent=True) print( f"content = {json.dumps(content)}" ) columns = [ "sender_pk", "receiver_pk", "buy_currency", "sell_currency", "buy_amount", "sell_amount", "platform" ] fields = [ "sig", "payload" ] # check whether the input contains both "sig" and "payload" for field in fields: if not field in content.keys(): print( f"{field} not received by Trade" ) print( json.dumps(content) ) log_message(content) return jsonify( False ) # check whether the input contains all 7 fields of payload for column in columns: if not column in content['payload'].keys(): print( f"{column} not received by Trade" ) print( json.dumps(content) ) log_message(content) return jsonify( False ) #Your code here #Note that you can access the database session using g.session # TODO 1: Check the signature # extract contents from json sig = content['sig'] payload = content['payload'] platform = payload['platform'] # The platform must be either “Algorand” or "Ethereum". platforms = ["Algorand", "Ethereum"] if not platform in platforms: print("input platform is not Algorand or Ethereum") return jsonify(False) # check signature check_result = check_sig(payload,sig) result = check_result[0] payload_json = check_result[1] # TODO 2: Add the order to the database # TODO 4: Be sure to return jsonify(True) or jsonify(False) depending on if the method was successful # If the signature does not verify, do not insert the order into the “Order” table. # Instead, insert a record into the “Log” table, with the message field set to be json.dumps(payload). if result is False: print("signature does NOT verify") log_message(payload_json) return jsonify(result) # If the signature verifies, store the signature, # as well as all of the fields under the ‘payload’ in the “Order” table EXCEPT for 'platform’. if result is True: print("signature verifies") create_session() order_obj = Order(sender_pk=payload['sender_pk'], receiver_pk=payload['receiver_pk'], buy_currency=payload['buy_currency'], sell_currency=payload['sell_currency'], buy_amount=payload['buy_amount'], sell_amount=payload['sell_amount'], signature=sig) g.session.add(order_obj) # TODO 3: Fill the order fill_order() shutdown_session() return jsonify(result) @app.route('/order_book') def order_book(): #Your code here #Note that you can access the database session using g.session # The “/order_book” endpoint should return a list of all orders in the database. # The response should contain a single key “data” that refers to a list of orders formatted as JSON. # Each order should be a dict with (at least) the following fields # ("sender_pk", "receiver_pk", "buy_currency", "sell_currency", "buy_amount", "sell_amount", “signature”). print("--------- order_book ---------") create_session() # get orders from DB into a list order_dict_list = [ row2dict(order) for order in g.session.query(Order).all() ] # add the list into a dict result = { 'data': order_dict_list } print("order book length: ") print(len(order_dict_list)) # print_dict(order_dict_list[-2]) # print_dict(order_dict_list[-1]) shutdown_session() return jsonify(result) if __name__ == '__main__': app.run(port='5002')
normal
{ "blob_id": "d9bdf466abecb50c399556b99b41896eead0cb4b", "index": 2959, "step-1": "<mask token>\n\n\[email protected]_request\ndef create_session():\n g.session = scoped_session(DBSession)\n\n\n<mask token>\n\n\ndef check_sig(payload, sig):\n pk = payload['sender_pk']\n platform = payload['platform']\n payload_json = json.dumps(payload)\n result = False\n if platform == 'Algorand':\n print('Algorand')\n if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk):\n print('Algo sig verifies!')\n result = True\n elif platform == 'Ethereum':\n print('Ethereum')\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json\n )\n if eth_account.Account.recover_message(eth_encoded_msg, signature=sig\n ) == pk:\n print('Eth sig verifies!')\n result = True\n return result, payload_json\n\n\ndef fill_order():\n current_order = g.session.query(Order).order_by(Order.id.desc()).first()\n order_list = []\n orders = g.session.query(Order).filter(Order.filled == None).all()\n for existing_order in orders:\n if (existing_order.buy_currency == current_order.sell_currency and \n existing_order.sell_currency == current_order.buy_currency and \n existing_order.sell_amount / existing_order.buy_amount >= \n current_order.buy_amount / current_order.sell_amount and \n existing_order.counterparty_id == None):\n order_list.append(existing_order)\n if len(order_list) > 0:\n match_order = order_list[0]\n match_order.filled = datetime.now()\n current_order.filled = datetime.now()\n match_order.counterparty_id = current_order.id\n current_order.counterparty_id = match_order.id\n g.session.commit()\n if current_order.sell_amount < match_order.buy_amount:\n diff = match_order.buy_amount - current_order.sell_amount\n exchange_rate_match = (match_order.sell_amount / match_order.\n buy_amount)\n sell_amount_new_match = diff * exchange_rate_match\n new_order = Order(sender_pk=match_order.sender_pk, receiver_pk=\n match_order.receiver_pk, buy_currency=match_order.\n buy_currency, sell_currency=match_order.sell_currency,\n buy_amount=diff, sell_amount=sell_amount_new_match,\n creator_id=match_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('M')\n fill_order()\n if current_order.buy_amount > match_order.sell_amount:\n diff = current_order.buy_amount - match_order.sell_amount\n exchange_rate_current = (current_order.buy_amount /\n current_order.sell_amount)\n sell_amount_new_current = diff / exchange_rate_current\n new_order = Order(sender_pk=current_order.sender_pk,\n receiver_pk=current_order.receiver_pk, buy_currency=\n current_order.buy_currency, sell_currency=current_order.\n sell_currency, buy_amount=diff, sell_amount=\n sell_amount_new_current, creator_id=current_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('C')\n fill_order()\n\n\n<mask token>\n\n\ndef row2dict(row):\n return {c.name: getattr(row, c.name) for c in row.__table__.columns}\n\n\ndef print_dict(d):\n for key, value in d.items():\n print(key, ' : ', value)\n\n\n<mask token>\n\n\[email protected]('/trade', methods=['POST'])\ndef trade():\n print('In trade endpoint')\n if request.method == 'POST':\n print('--------- trade ---------')\n content = request.get_json(silent=True)\n print(f'content = {json.dumps(content)}')\n columns = ['sender_pk', 'receiver_pk', 'buy_currency',\n 'sell_currency', 'buy_amount', 'sell_amount', 'platform']\n fields = ['sig', 'payload']\n for field in fields:\n if not field in content.keys():\n print(f'{field} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n for column in columns:\n if not column in content['payload'].keys():\n print(f'{column} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n sig = content['sig']\n payload = content['payload']\n platform = payload['platform']\n platforms = ['Algorand', 'Ethereum']\n if not platform in platforms:\n print('input platform is not Algorand or Ethereum')\n return jsonify(False)\n check_result = check_sig(payload, sig)\n result = check_result[0]\n payload_json = check_result[1]\n if result is False:\n print('signature does NOT verify')\n log_message(payload_json)\n return jsonify(result)\n if result is True:\n print('signature verifies')\n create_session()\n order_obj = Order(sender_pk=payload['sender_pk'], receiver_pk=\n payload['receiver_pk'], buy_currency=payload['buy_currency'\n ], sell_currency=payload['sell_currency'], buy_amount=\n payload['buy_amount'], sell_amount=payload['sell_amount'],\n signature=sig)\n g.session.add(order_obj)\n fill_order()\n shutdown_session()\n return jsonify(result)\n\n\[email protected]('/order_book')\ndef order_book():\n print('--------- order_book ---------')\n create_session()\n order_dict_list = [row2dict(order) for order in g.session.query(Order).\n all()]\n result = {'data': order_dict_list}\n print('order book length: ')\n print(len(order_dict_list))\n shutdown_session()\n return jsonify(result)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\[email protected]_request\ndef create_session():\n g.session = scoped_session(DBSession)\n\n\[email protected]_appcontext\ndef shutdown_session(exception=None):\n sys.stdout.flush()\n g.session.commit()\n g.session.remove()\n\n\n<mask token>\n\n\ndef check_sig(payload, sig):\n pk = payload['sender_pk']\n platform = payload['platform']\n payload_json = json.dumps(payload)\n result = False\n if platform == 'Algorand':\n print('Algorand')\n if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk):\n print('Algo sig verifies!')\n result = True\n elif platform == 'Ethereum':\n print('Ethereum')\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json\n )\n if eth_account.Account.recover_message(eth_encoded_msg, signature=sig\n ) == pk:\n print('Eth sig verifies!')\n result = True\n return result, payload_json\n\n\ndef fill_order():\n current_order = g.session.query(Order).order_by(Order.id.desc()).first()\n order_list = []\n orders = g.session.query(Order).filter(Order.filled == None).all()\n for existing_order in orders:\n if (existing_order.buy_currency == current_order.sell_currency and \n existing_order.sell_currency == current_order.buy_currency and \n existing_order.sell_amount / existing_order.buy_amount >= \n current_order.buy_amount / current_order.sell_amount and \n existing_order.counterparty_id == None):\n order_list.append(existing_order)\n if len(order_list) > 0:\n match_order = order_list[0]\n match_order.filled = datetime.now()\n current_order.filled = datetime.now()\n match_order.counterparty_id = current_order.id\n current_order.counterparty_id = match_order.id\n g.session.commit()\n if current_order.sell_amount < match_order.buy_amount:\n diff = match_order.buy_amount - current_order.sell_amount\n exchange_rate_match = (match_order.sell_amount / match_order.\n buy_amount)\n sell_amount_new_match = diff * exchange_rate_match\n new_order = Order(sender_pk=match_order.sender_pk, receiver_pk=\n match_order.receiver_pk, buy_currency=match_order.\n buy_currency, sell_currency=match_order.sell_currency,\n buy_amount=diff, sell_amount=sell_amount_new_match,\n creator_id=match_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('M')\n fill_order()\n if current_order.buy_amount > match_order.sell_amount:\n diff = current_order.buy_amount - match_order.sell_amount\n exchange_rate_current = (current_order.buy_amount /\n current_order.sell_amount)\n sell_amount_new_current = diff / exchange_rate_current\n new_order = Order(sender_pk=current_order.sender_pk,\n receiver_pk=current_order.receiver_pk, buy_currency=\n current_order.buy_currency, sell_currency=current_order.\n sell_currency, buy_amount=diff, sell_amount=\n sell_amount_new_current, creator_id=current_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('C')\n fill_order()\n\n\n<mask token>\n\n\ndef row2dict(row):\n return {c.name: getattr(row, c.name) for c in row.__table__.columns}\n\n\ndef print_dict(d):\n for key, value in d.items():\n print(key, ' : ', value)\n\n\n<mask token>\n\n\[email protected]('/trade', methods=['POST'])\ndef trade():\n print('In trade endpoint')\n if request.method == 'POST':\n print('--------- trade ---------')\n content = request.get_json(silent=True)\n print(f'content = {json.dumps(content)}')\n columns = ['sender_pk', 'receiver_pk', 'buy_currency',\n 'sell_currency', 'buy_amount', 'sell_amount', 'platform']\n fields = ['sig', 'payload']\n for field in fields:\n if not field in content.keys():\n print(f'{field} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n for column in columns:\n if not column in content['payload'].keys():\n print(f'{column} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n sig = content['sig']\n payload = content['payload']\n platform = payload['platform']\n platforms = ['Algorand', 'Ethereum']\n if not platform in platforms:\n print('input platform is not Algorand or Ethereum')\n return jsonify(False)\n check_result = check_sig(payload, sig)\n result = check_result[0]\n payload_json = check_result[1]\n if result is False:\n print('signature does NOT verify')\n log_message(payload_json)\n return jsonify(result)\n if result is True:\n print('signature verifies')\n create_session()\n order_obj = Order(sender_pk=payload['sender_pk'], receiver_pk=\n payload['receiver_pk'], buy_currency=payload['buy_currency'\n ], sell_currency=payload['sell_currency'], buy_amount=\n payload['buy_amount'], sell_amount=payload['sell_amount'],\n signature=sig)\n g.session.add(order_obj)\n fill_order()\n shutdown_session()\n return jsonify(result)\n\n\[email protected]('/order_book')\ndef order_book():\n print('--------- order_book ---------')\n create_session()\n order_dict_list = [row2dict(order) for order in g.session.query(Order).\n all()]\n result = {'data': order_dict_list}\n print('order book length: ')\n print(len(order_dict_list))\n shutdown_session()\n return jsonify(result)\n\n\n<mask token>\n", "step-3": "<mask token>\nengine = create_engine('sqlite:///orders.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\napp = Flask(__name__)\n\n\[email protected]_request\ndef create_session():\n g.session = scoped_session(DBSession)\n\n\[email protected]_appcontext\ndef shutdown_session(exception=None):\n sys.stdout.flush()\n g.session.commit()\n g.session.remove()\n\n\n<mask token>\n\n\ndef check_sig(payload, sig):\n pk = payload['sender_pk']\n platform = payload['platform']\n payload_json = json.dumps(payload)\n result = False\n if platform == 'Algorand':\n print('Algorand')\n if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk):\n print('Algo sig verifies!')\n result = True\n elif platform == 'Ethereum':\n print('Ethereum')\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json\n )\n if eth_account.Account.recover_message(eth_encoded_msg, signature=sig\n ) == pk:\n print('Eth sig verifies!')\n result = True\n return result, payload_json\n\n\ndef fill_order():\n current_order = g.session.query(Order).order_by(Order.id.desc()).first()\n order_list = []\n orders = g.session.query(Order).filter(Order.filled == None).all()\n for existing_order in orders:\n if (existing_order.buy_currency == current_order.sell_currency and \n existing_order.sell_currency == current_order.buy_currency and \n existing_order.sell_amount / existing_order.buy_amount >= \n current_order.buy_amount / current_order.sell_amount and \n existing_order.counterparty_id == None):\n order_list.append(existing_order)\n if len(order_list) > 0:\n match_order = order_list[0]\n match_order.filled = datetime.now()\n current_order.filled = datetime.now()\n match_order.counterparty_id = current_order.id\n current_order.counterparty_id = match_order.id\n g.session.commit()\n if current_order.sell_amount < match_order.buy_amount:\n diff = match_order.buy_amount - current_order.sell_amount\n exchange_rate_match = (match_order.sell_amount / match_order.\n buy_amount)\n sell_amount_new_match = diff * exchange_rate_match\n new_order = Order(sender_pk=match_order.sender_pk, receiver_pk=\n match_order.receiver_pk, buy_currency=match_order.\n buy_currency, sell_currency=match_order.sell_currency,\n buy_amount=diff, sell_amount=sell_amount_new_match,\n creator_id=match_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('M')\n fill_order()\n if current_order.buy_amount > match_order.sell_amount:\n diff = current_order.buy_amount - match_order.sell_amount\n exchange_rate_current = (current_order.buy_amount /\n current_order.sell_amount)\n sell_amount_new_current = diff / exchange_rate_current\n new_order = Order(sender_pk=current_order.sender_pk,\n receiver_pk=current_order.receiver_pk, buy_currency=\n current_order.buy_currency, sell_currency=current_order.\n sell_currency, buy_amount=diff, sell_amount=\n sell_amount_new_current, creator_id=current_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('C')\n fill_order()\n\n\ndef log_message(d):\n create_session()\n order_obj = Log(message=d)\n g.session.add(order_obj)\n shutdown_session()\n\n\ndef row2dict(row):\n return {c.name: getattr(row, c.name) for c in row.__table__.columns}\n\n\ndef print_dict(d):\n for key, value in d.items():\n print(key, ' : ', value)\n\n\n<mask token>\n\n\[email protected]('/trade', methods=['POST'])\ndef trade():\n print('In trade endpoint')\n if request.method == 'POST':\n print('--------- trade ---------')\n content = request.get_json(silent=True)\n print(f'content = {json.dumps(content)}')\n columns = ['sender_pk', 'receiver_pk', 'buy_currency',\n 'sell_currency', 'buy_amount', 'sell_amount', 'platform']\n fields = ['sig', 'payload']\n for field in fields:\n if not field in content.keys():\n print(f'{field} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n for column in columns:\n if not column in content['payload'].keys():\n print(f'{column} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n sig = content['sig']\n payload = content['payload']\n platform = payload['platform']\n platforms = ['Algorand', 'Ethereum']\n if not platform in platforms:\n print('input platform is not Algorand or Ethereum')\n return jsonify(False)\n check_result = check_sig(payload, sig)\n result = check_result[0]\n payload_json = check_result[1]\n if result is False:\n print('signature does NOT verify')\n log_message(payload_json)\n return jsonify(result)\n if result is True:\n print('signature verifies')\n create_session()\n order_obj = Order(sender_pk=payload['sender_pk'], receiver_pk=\n payload['receiver_pk'], buy_currency=payload['buy_currency'\n ], sell_currency=payload['sell_currency'], buy_amount=\n payload['buy_amount'], sell_amount=payload['sell_amount'],\n signature=sig)\n g.session.add(order_obj)\n fill_order()\n shutdown_session()\n return jsonify(result)\n\n\[email protected]('/order_book')\ndef order_book():\n print('--------- order_book ---------')\n create_session()\n order_dict_list = [row2dict(order) for order in g.session.query(Order).\n all()]\n result = {'data': order_dict_list}\n print('order book length: ')\n print(len(order_dict_list))\n shutdown_session()\n return jsonify(result)\n\n\nif __name__ == '__main__':\n app.run(port='5002')\n", "step-4": "from flask import Flask, request, g\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom flask import jsonify\nimport json\nimport eth_account\nimport algosdk\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import load_only\nfrom datetime import datetime\nimport sys\nfrom models import Base, Order, Log\nengine = create_engine('sqlite:///orders.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\napp = Flask(__name__)\n\n\[email protected]_request\ndef create_session():\n g.session = scoped_session(DBSession)\n\n\[email protected]_appcontext\ndef shutdown_session(exception=None):\n sys.stdout.flush()\n g.session.commit()\n g.session.remove()\n\n\n<mask token>\n\n\ndef check_sig(payload, sig):\n pk = payload['sender_pk']\n platform = payload['platform']\n payload_json = json.dumps(payload)\n result = False\n if platform == 'Algorand':\n print('Algorand')\n if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk):\n print('Algo sig verifies!')\n result = True\n elif platform == 'Ethereum':\n print('Ethereum')\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json\n )\n if eth_account.Account.recover_message(eth_encoded_msg, signature=sig\n ) == pk:\n print('Eth sig verifies!')\n result = True\n return result, payload_json\n\n\ndef fill_order():\n current_order = g.session.query(Order).order_by(Order.id.desc()).first()\n order_list = []\n orders = g.session.query(Order).filter(Order.filled == None).all()\n for existing_order in orders:\n if (existing_order.buy_currency == current_order.sell_currency and \n existing_order.sell_currency == current_order.buy_currency and \n existing_order.sell_amount / existing_order.buy_amount >= \n current_order.buy_amount / current_order.sell_amount and \n existing_order.counterparty_id == None):\n order_list.append(existing_order)\n if len(order_list) > 0:\n match_order = order_list[0]\n match_order.filled = datetime.now()\n current_order.filled = datetime.now()\n match_order.counterparty_id = current_order.id\n current_order.counterparty_id = match_order.id\n g.session.commit()\n if current_order.sell_amount < match_order.buy_amount:\n diff = match_order.buy_amount - current_order.sell_amount\n exchange_rate_match = (match_order.sell_amount / match_order.\n buy_amount)\n sell_amount_new_match = diff * exchange_rate_match\n new_order = Order(sender_pk=match_order.sender_pk, receiver_pk=\n match_order.receiver_pk, buy_currency=match_order.\n buy_currency, sell_currency=match_order.sell_currency,\n buy_amount=diff, sell_amount=sell_amount_new_match,\n creator_id=match_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('M')\n fill_order()\n if current_order.buy_amount > match_order.sell_amount:\n diff = current_order.buy_amount - match_order.sell_amount\n exchange_rate_current = (current_order.buy_amount /\n current_order.sell_amount)\n sell_amount_new_current = diff / exchange_rate_current\n new_order = Order(sender_pk=current_order.sender_pk,\n receiver_pk=current_order.receiver_pk, buy_currency=\n current_order.buy_currency, sell_currency=current_order.\n sell_currency, buy_amount=diff, sell_amount=\n sell_amount_new_current, creator_id=current_order.id)\n g.session.add(new_order)\n g.session.commit()\n print('C')\n fill_order()\n\n\ndef log_message(d):\n create_session()\n order_obj = Log(message=d)\n g.session.add(order_obj)\n shutdown_session()\n\n\ndef row2dict(row):\n return {c.name: getattr(row, c.name) for c in row.__table__.columns}\n\n\ndef print_dict(d):\n for key, value in d.items():\n print(key, ' : ', value)\n\n\n<mask token>\n\n\[email protected]('/trade', methods=['POST'])\ndef trade():\n print('In trade endpoint')\n if request.method == 'POST':\n print('--------- trade ---------')\n content = request.get_json(silent=True)\n print(f'content = {json.dumps(content)}')\n columns = ['sender_pk', 'receiver_pk', 'buy_currency',\n 'sell_currency', 'buy_amount', 'sell_amount', 'platform']\n fields = ['sig', 'payload']\n for field in fields:\n if not field in content.keys():\n print(f'{field} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n for column in columns:\n if not column in content['payload'].keys():\n print(f'{column} not received by Trade')\n print(json.dumps(content))\n log_message(content)\n return jsonify(False)\n sig = content['sig']\n payload = content['payload']\n platform = payload['platform']\n platforms = ['Algorand', 'Ethereum']\n if not platform in platforms:\n print('input platform is not Algorand or Ethereum')\n return jsonify(False)\n check_result = check_sig(payload, sig)\n result = check_result[0]\n payload_json = check_result[1]\n if result is False:\n print('signature does NOT verify')\n log_message(payload_json)\n return jsonify(result)\n if result is True:\n print('signature verifies')\n create_session()\n order_obj = Order(sender_pk=payload['sender_pk'], receiver_pk=\n payload['receiver_pk'], buy_currency=payload['buy_currency'\n ], sell_currency=payload['sell_currency'], buy_amount=\n payload['buy_amount'], sell_amount=payload['sell_amount'],\n signature=sig)\n g.session.add(order_obj)\n fill_order()\n shutdown_session()\n return jsonify(result)\n\n\[email protected]('/order_book')\ndef order_book():\n print('--------- order_book ---------')\n create_session()\n order_dict_list = [row2dict(order) for order in g.session.query(Order).\n all()]\n result = {'data': order_dict_list}\n print('order book length: ')\n print(len(order_dict_list))\n shutdown_session()\n return jsonify(result)\n\n\nif __name__ == '__main__':\n app.run(port='5002')\n", "step-5": "from flask import Flask, request, g\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom flask import jsonify\nimport json\nimport eth_account\nimport algosdk\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import load_only\nfrom datetime import datetime\nimport sys\n\nfrom models import Base, Order, Log\nengine = create_engine('sqlite:///orders.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\n\napp = Flask(__name__)\n\n# These decorators allow you to use g.session to access the database inside the request code\n# g is an \"application global\" https://flask.palletsprojects.com/en/1.1.x/api/#application-globals\n\[email protected]_request\ndef create_session():\n g.session = scoped_session(DBSession) \n\[email protected]_appcontext\n# def shutdown_session(response_or_exc):\ndef shutdown_session(exception=None):\n sys.stdout.flush()\n g.session.commit()\n g.session.remove()\n\n\n\"\"\" Suggested helper methods \"\"\"\n\n\n# check whether “sig” is a valid signature of json.dumps(payload),\n# using the signature algorithm specified by the platform field.\n# Be sure to verify the payload using the sender_pk.\ndef check_sig(payload,sig):\n \n pk = payload['sender_pk']\n platform = payload['platform']\n payload_json = json.dumps(payload)\n result = False\n \n if platform == \"Algorand\":\n print(\"Algorand\")\n if algosdk.util.verify_bytes(payload_json.encode('utf-8'), sig, pk):\n print(\"Algo sig verifies!\")\n result = True\n\n elif platform == \"Ethereum\":\n print(\"Ethereum\")\n eth_encoded_msg = eth_account.messages.encode_defunct(text=payload_json)\n if eth_account.Account.recover_message(eth_encoded_msg, signature=sig) == pk:\n print(\"Eth sig verifies!\")\n result = True\n \n return result, payload_json\n\n\n\n\n\n\n\n\n\n# def fill_order(order,txes=[]):\n# pass\n\n\n# the inner recursive function\ndef fill_order():\n # get the order you just inserted from the DB\n current_order = g.session.query(Order).order_by(Order.id.desc()).first()\n # print(\"_order_id\")\n # print(current_order.id)\n\n # Check if there are any existing orders that match and add them into a list\n order_list = []\n orders = g.session.query(Order).filter(Order.filled == None).all()\n for existing_order in orders:\n # if ((existing_order.buy_amount != 0) and (current_order.sell_amount != 0)):\n if ((existing_order.buy_currency == current_order.sell_currency)\n and (existing_order.sell_currency == current_order.buy_currency)\n and (existing_order.sell_amount / existing_order.buy_amount\n >= current_order.buy_amount / current_order.sell_amount)\n and (existing_order.counterparty_id == None)):\n order_list.append(existing_order)\n\n # If a match is found between order and existing_order\n if (len(order_list) > 0):\n # print(\" order_list_length\")\n # print(len(order_list))\n # pick the first one in the list\n match_order = order_list[0]\n\n # Set the filled field to be the current timestamp on both orders\n # Set counterparty_id to be the id of the other order\n match_order.filled = datetime.now()\n current_order.filled = datetime.now()\n match_order.counterparty_id = current_order.id\n current_order.counterparty_id = match_order.id\n g.session.commit()\n\n # if both orders can completely fill each other\n # no child order needs to be generated\n\n # If match_order is not completely filled\n if (current_order.sell_amount < match_order.buy_amount):\n # print(\"_match_order is not completely filled\")\n diff = match_order.buy_amount - current_order.sell_amount\n exchange_rate_match = match_order.sell_amount / match_order.buy_amount\n sell_amount_new_match = diff * exchange_rate_match\n # print(match_order.id)\n # print(diff)\n # print(sell_amount_new_match)\n new_order = Order(sender_pk=match_order.sender_pk,\n receiver_pk=match_order.receiver_pk,\n buy_currency=match_order.buy_currency,\n sell_currency=match_order.sell_currency,\n buy_amount=diff,\n sell_amount=sell_amount_new_match,\n creator_id=match_order.id)\n g.session.add(new_order)\n g.session.commit()\n print(\"M\")\n fill_order()\n\n # If current_order is not completely filled\n if (current_order.buy_amount > match_order.sell_amount):\n # print(\"_current_order is not completely filled\")\n diff = current_order.buy_amount - match_order.sell_amount\n exchange_rate_current = current_order.buy_amount / current_order.sell_amount\n sell_amount_new_current = diff / exchange_rate_current\n # print(current_order.id)\n # print(diff)\n # print(sell_amount_new_current)\n new_order = Order(sender_pk=current_order.sender_pk,\n receiver_pk=current_order.receiver_pk,\n buy_currency=current_order.buy_currency,\n sell_currency=current_order.sell_currency,\n buy_amount=diff,\n sell_amount=sell_amount_new_current,\n creator_id=current_order.id)\n g.session.add(new_order)\n g.session.commit()\n print(\"C\")\n fill_order()\n\n\n\n\n\n\n\n\n# Takes input dictionary d and writes it to the Log table\n# Hint: use json.dumps or str() to get it in a nice string form\ndef log_message(d):\n create_session()\n order_obj = Log(message=d)\n g.session.add(order_obj)\n shutdown_session()\n\n\n# convert a row in DB into a dict\ndef row2dict(row):\n return {\n c.name: getattr(row, c.name)\n for c in row.__table__.columns\n }\n\n# print a dictionary nicely\ndef print_dict(d):\n for key, value in d.items():\n print(key, ' : ', value)\n\n \n \n \n\n \n\"\"\" End of helper methods \"\"\"\n\n\[email protected]('/trade', methods=['POST'])\ndef trade():\n print(\"In trade endpoint\")\n if request.method == \"POST\":\n print(\"--------- trade ---------\")\n content = request.get_json(silent=True)\n print( f\"content = {json.dumps(content)}\" )\n columns = [ \"sender_pk\", \"receiver_pk\", \"buy_currency\", \"sell_currency\", \"buy_amount\", \"sell_amount\", \"platform\" ]\n fields = [ \"sig\", \"payload\" ]\n\n # check whether the input contains both \"sig\" and \"payload\"\n for field in fields:\n if not field in content.keys():\n print( f\"{field} not received by Trade\" )\n print( json.dumps(content) )\n log_message(content)\n return jsonify( False )\n \n # check whether the input contains all 7 fields of payload\n for column in columns:\n if not column in content['payload'].keys():\n print( f\"{column} not received by Trade\" )\n print( json.dumps(content) )\n log_message(content)\n return jsonify( False )\n \n #Your code here\n #Note that you can access the database session using g.session\n\n # TODO 1: Check the signature\n \n # extract contents from json\n sig = content['sig']\n payload = content['payload']\n platform = payload['platform']\n\n # The platform must be either “Algorand” or \"Ethereum\".\n platforms = [\"Algorand\", \"Ethereum\"]\n if not platform in platforms:\n print(\"input platform is not Algorand or Ethereum\")\n return jsonify(False)\n \n # check signature\n check_result = check_sig(payload,sig)\n result = check_result[0]\n payload_json = check_result[1]\n \n # TODO 2: Add the order to the database\n # TODO 4: Be sure to return jsonify(True) or jsonify(False) depending on if the method was successful\n \n # If the signature does not verify, do not insert the order into the “Order” table.\n # Instead, insert a record into the “Log” table, with the message field set to be json.dumps(payload).\n if result is False:\n print(\"signature does NOT verify\")\n log_message(payload_json) \n return jsonify(result)\n \n # If the signature verifies, store the signature,\n # as well as all of the fields under the ‘payload’ in the “Order” table EXCEPT for 'platform’.\n if result is True:\n print(\"signature verifies\")\n create_session()\n order_obj = Order(sender_pk=payload['sender_pk'],\n receiver_pk=payload['receiver_pk'],\n buy_currency=payload['buy_currency'],\n sell_currency=payload['sell_currency'],\n buy_amount=payload['buy_amount'],\n sell_amount=payload['sell_amount'],\n signature=sig) \n g.session.add(order_obj)\n \n # TODO 3: Fill the order\n fill_order()\n shutdown_session()\n return jsonify(result)\n \n \n \n \n\[email protected]('/order_book')\ndef order_book():\n #Your code here\n #Note that you can access the database session using g.session\n \n # The “/order_book” endpoint should return a list of all orders in the database.\n # The response should contain a single key “data” that refers to a list of orders formatted as JSON.\n # Each order should be a dict with (at least) the following fields\n # (\"sender_pk\", \"receiver_pk\", \"buy_currency\", \"sell_currency\", \"buy_amount\", \"sell_amount\", “signature”).\n print(\"--------- order_book ---------\")\n create_session()\n \n # get orders from DB into a list\n order_dict_list = [\n row2dict(order)\n for order in g.session.query(Order).all()\n ]\n \n # add the list into a dict\n result = {\n 'data': order_dict_list\n } \n \n print(\"order book length: \")\n print(len(order_dict_list))\n # print_dict(order_dict_list[-2])\n # print_dict(order_dict_list[-1])\n\n shutdown_session()\n return jsonify(result)\n \n\n \nif __name__ == '__main__':\n app.run(port='5002')\n", "step-ids": [ 7, 8, 11, 12, 13 ] }
[ 7, 8, 11, 12, 13 ]
import requests, shutil, os, glob from zipfile import ZipFile import pandas as pd from xlrd import open_workbook import csv # zipfilename = 'desiya_hotels' # try: # # downloading zip file # r = requests.get('http://staticstore.travelguru.com/testdump/1300001176/Excel.zip', auth=('testdump', 'testdump'), verify=False,stream=True) #Note web_link is https:// # r.raw.decode_content = True # with open(os.path.join(os.path.dirname(__file__), 'storage/{}.zip'.format(zipfilename)), 'wb') as f: # shutil.copyfileobj(r.raw, f) # # #extracting zip file as xls file # with ZipFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.zip'))[0], 'r') as zip: # zip.extractall(os.path.join(os.path.dirname(__file__), 'storage/')) # #Rename xls file name as "desiya_hotels" # if glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls')): # for filename in glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[a-zA-z].xls')): # os.remove(filename) # os.rename(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls'))[0], os.path.join(os.path.dirname(__file__),'storage/{}.xls'.format(zipfilename))) # else: # print('unzipped xls file is not found in storare folder') # except Exception as e: # print("Error while downloading zip file") #read xls file # xls = pd.ExcelFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.xls'))[0]) # df = pd.read_excel(xls, sheet_name=0, index_col=None) # print(df['Name']) # print(df.head(5)) # for index, row in df.iterrows(): # print(index, row[3]) #convert xls to csvc # df.to_csv(os.path.join(os.path.dirname(__file__),'storage/{}'.format('robot.csv')), encoding='utf-8', index=False) #convert xls file to csv using xlrd module xlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0] wb = open_workbook(xlsfile) sheet = wb.sheet_by_name('robot_list') with open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), "w") as file: writer = csv.writer(file, delimiter=",") headers = [cell.value for cell in sheet.row(0)] writer.writerow(headers) for i in range(1, sheet.nrows): rowvalue_list = [str(cell.value).strip() if cell.value else None for cell in sheet.row(i)] writer.writerow(rowvalue_list)
normal
{ "blob_id": "1ef9df43725196904ec6c0c881f4a1204174b176", "index": 375, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-3": "<mask token>\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__),\n 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-4": "import requests, shutil, os, glob\nfrom zipfile import ZipFile\nimport pandas as pd\nfrom xlrd import open_workbook\nimport csv\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__),\n 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'),\n 'w') as file:\n writer = csv.writer(file, delimiter=',')\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [(str(cell.value).strip() if cell.value else None) for\n cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n", "step-5": "\n\nimport requests, shutil, os, glob\nfrom zipfile import ZipFile\nimport pandas as pd\nfrom xlrd import open_workbook\nimport csv\n\n# zipfilename = 'desiya_hotels'\n# try:\n# # downloading zip file\n# r = requests.get('http://staticstore.travelguru.com/testdump/1300001176/Excel.zip', auth=('testdump', 'testdump'), verify=False,stream=True) #Note web_link is https://\n# r.raw.decode_content = True\n# with open(os.path.join(os.path.dirname(__file__), 'storage/{}.zip'.format(zipfilename)), 'wb') as f:\n# shutil.copyfileobj(r.raw, f)\n#\n# #extracting zip file as xls file\n# with ZipFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.zip'))[0], 'r') as zip:\n# zip.extractall(os.path.join(os.path.dirname(__file__), 'storage/'))\n# #Rename xls file name as \"desiya_hotels\"\n# if glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls')):\n# for filename in glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[a-zA-z].xls')):\n# os.remove(filename)\n# os.rename(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/*[0-9].xls'))[0], os.path.join(os.path.dirname(__file__),'storage/{}.xls'.format(zipfilename)))\n# else:\n# print('unzipped xls file is not found in storare folder')\n# except Exception as e:\n# print(\"Error while downloading zip file\")\n\n#read xls file\n# xls = pd.ExcelFile(glob.glob(os.path.join(os.path.dirname(__file__), 'storage/desiya*.xls'))[0])\n# df = pd.read_excel(xls, sheet_name=0, index_col=None)\n# print(df['Name'])\n# print(df.head(5))\n# for index, row in df.iterrows():\n# print(index, row[3])\n\n#convert xls to csvc\n# df.to_csv(os.path.join(os.path.dirname(__file__),'storage/{}'.format('robot.csv')), encoding='utf-8', index=False)\n\n\n#convert xls file to csv using xlrd module\nxlsfile = glob.glob(os.path.join(os.path.dirname(__file__), 'storage/robot*.xls'))[0]\nwb = open_workbook(xlsfile)\nsheet = wb.sheet_by_name('robot_list')\nwith open(os.path.join(os.path.dirname(__file__), 'storage/robot_list.csv'), \"w\") as file:\n writer = csv.writer(file, delimiter=\",\")\n headers = [cell.value for cell in sheet.row(0)]\n writer.writerow(headers)\n for i in range(1, sheet.nrows):\n rowvalue_list = [str(cell.value).strip() if cell.value else None for cell in sheet.row(i)]\n writer.writerow(rowvalue_list)\n\n\n\n\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from sqlalchemy import create_engine from sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey from sqlalchemy.sql import select from sqlalchemy import text #Creating a database 'college.db' engine = create_engine('sqlite:///college.db', echo=True) meta = MetaData() #Creating a Students table students = Table( 'students',meta, Column('id',Integer,primary_key=True), Column('name',String), Column('lastname',String) ) meta.create_all(engine) #Inserting values conn = engine.connect() ins = students.insert().values(name='Ravi',lastname='Mahajan') res = conn.execute(ins) # Execute many commands conn.execute(students.insert(),[ {'name': 'Rajiv', 'lastname': 'Khanna'}, {'name': 'Komal', 'lastname': 'Bhandari'}, {'name': 'Abdul', 'lastname': 'Sattar'}, {'name': 'Priya', 'lastname': 'Rajhans'}, ]) # Selecting from table Students s = students.select() result = conn.execute(s) # row = result.fetchall() for row in result: print(row) # Where condition s = students.select().where(students.c.id>2) result = conn.execute(s) row = result.fetchall() print(row) s = select([students]) result = conn.execute(s) for row in result: print(row) # Using text to execute query using text t = text('SELECT * from students') result = conn.execute(t) # Update stmt = students.update().where(students.c.lastname=='Khanna').values(lastname='Bhatt') conn.execute(stmt) s = students.select() conn.execute(s).fetchall() from sqlalchemy.sql.expression import update stmt = update(students).where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor') stmt2 = students.delete().where(students.c.lastname=='Rajhans') conn.execute(stmt) addresses = Table( 'addresses', meta, Column('id', Integer, primary_key = True), Column('st_id', Integer, ForeignKey('students.id')), Column('postal_add', String), Column('email_add', String)) meta.create_all(engine) conn.execute(addresses.insert(), [ {'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'[email protected]'}, {'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'[email protected]'}, {'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'[email protected]'}, {'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'[email protected]'}, {'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'[email protected]'}, ]) # Update query for Multiple tables stmt = students.update().values({students.c.name:'xyz', addresses.c.email_add:'[email protected]'}).where(students.c.id == addresses.c.id) # using joins from sqlalchemy import join from sqlalchemy.sql import select j = students.join(addresses,students.c.id==addresses.c.st_id) stmt = select([students]).select_from(j) result = conn.execute(stmt) for res in result: print(res)
normal
{ "blob_id": "7ea6fefa75d36ff45dcea49919fdc632e378a73f", "index": 9113, "step-1": "<mask token>\n", "step-2": "<mask token>\nmeta.create_all(engine)\n<mask token>\nconn.execute(students.insert(), [{'name': 'Rajiv', 'lastname': 'Khanna'}, {\n 'name': 'Komal', 'lastname': 'Bhandari'}, {'name': 'Abdul', 'lastname':\n 'Sattar'}, {'name': 'Priya', 'lastname': 'Rajhans'}])\n<mask token>\nfor row in result:\n print(row)\n<mask token>\nprint(row)\n<mask token>\nfor row in result:\n print(row)\n<mask token>\nconn.execute(stmt)\n<mask token>\nconn.execute(s).fetchall()\n<mask token>\nconn.execute(stmt)\n<mask token>\nmeta.create_all(engine)\nconn.execute(addresses.insert(), [{'st_id': 1, 'postal_add':\n 'Shivajinagar Pune', 'email_add': '[email protected]'}, {'st_id': 1,\n 'postal_add': 'ChurchGate Mumbai', 'email_add': '[email protected]'}, {\n 'st_id': 3, 'postal_add': 'Jubilee Hills Hyderabad', 'email_add':\n '[email protected]'}, {'st_id': 5, 'postal_add': 'MG Road Bangaluru',\n 'email_add': '[email protected]'}, {'st_id': 2, 'postal_add':\n 'Cannought Place new Delhi', 'email_add': '[email protected]'}])\n<mask token>\nfor res in result:\n print(res)\n", "step-3": "<mask token>\nengine = create_engine('sqlite:///college.db', echo=True)\nmeta = MetaData()\nstudents = Table('students', meta, Column('id', Integer, primary_key=True),\n Column('name', String), Column('lastname', String))\nmeta.create_all(engine)\nconn = engine.connect()\nins = students.insert().values(name='Ravi', lastname='Mahajan')\nres = conn.execute(ins)\nconn.execute(students.insert(), [{'name': 'Rajiv', 'lastname': 'Khanna'}, {\n 'name': 'Komal', 'lastname': 'Bhandari'}, {'name': 'Abdul', 'lastname':\n 'Sattar'}, {'name': 'Priya', 'lastname': 'Rajhans'}])\ns = students.select()\nresult = conn.execute(s)\nfor row in result:\n print(row)\ns = students.select().where(students.c.id > 2)\nresult = conn.execute(s)\nrow = result.fetchall()\nprint(row)\ns = select([students])\nresult = conn.execute(s)\nfor row in result:\n print(row)\nt = text('SELECT * from students')\nresult = conn.execute(t)\nstmt = students.update().where(students.c.lastname == 'Khanna').values(lastname\n ='Bhatt')\nconn.execute(stmt)\ns = students.select()\nconn.execute(s).fetchall()\n<mask token>\nstmt = update(students).where(students.c.lastname == 'Khanna').values(lastname\n ='Kapoor')\nstmt2 = students.delete().where(students.c.lastname == 'Rajhans')\nconn.execute(stmt)\naddresses = Table('addresses', meta, Column('id', Integer, primary_key=True\n ), Column('st_id', Integer, ForeignKey('students.id')), Column(\n 'postal_add', String), Column('email_add', String))\nmeta.create_all(engine)\nconn.execute(addresses.insert(), [{'st_id': 1, 'postal_add':\n 'Shivajinagar Pune', 'email_add': '[email protected]'}, {'st_id': 1,\n 'postal_add': 'ChurchGate Mumbai', 'email_add': '[email protected]'}, {\n 'st_id': 3, 'postal_add': 'Jubilee Hills Hyderabad', 'email_add':\n '[email protected]'}, {'st_id': 5, 'postal_add': 'MG Road Bangaluru',\n 'email_add': '[email protected]'}, {'st_id': 2, 'postal_add':\n 'Cannought Place new Delhi', 'email_add': '[email protected]'}])\nstmt = students.update().values({students.c.name: 'xyz', addresses.c.\n email_add: '[email protected]'}).where(students.c.id == addresses.c.id)\n<mask token>\nj = students.join(addresses, students.c.id == addresses.c.st_id)\nstmt = select([students]).select_from(j)\nresult = conn.execute(stmt)\nfor res in result:\n print(res)\n", "step-4": "from sqlalchemy import create_engine\nfrom sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey\nfrom sqlalchemy.sql import select\nfrom sqlalchemy import text\nengine = create_engine('sqlite:///college.db', echo=True)\nmeta = MetaData()\nstudents = Table('students', meta, Column('id', Integer, primary_key=True),\n Column('name', String), Column('lastname', String))\nmeta.create_all(engine)\nconn = engine.connect()\nins = students.insert().values(name='Ravi', lastname='Mahajan')\nres = conn.execute(ins)\nconn.execute(students.insert(), [{'name': 'Rajiv', 'lastname': 'Khanna'}, {\n 'name': 'Komal', 'lastname': 'Bhandari'}, {'name': 'Abdul', 'lastname':\n 'Sattar'}, {'name': 'Priya', 'lastname': 'Rajhans'}])\ns = students.select()\nresult = conn.execute(s)\nfor row in result:\n print(row)\ns = students.select().where(students.c.id > 2)\nresult = conn.execute(s)\nrow = result.fetchall()\nprint(row)\ns = select([students])\nresult = conn.execute(s)\nfor row in result:\n print(row)\nt = text('SELECT * from students')\nresult = conn.execute(t)\nstmt = students.update().where(students.c.lastname == 'Khanna').values(lastname\n ='Bhatt')\nconn.execute(stmt)\ns = students.select()\nconn.execute(s).fetchall()\nfrom sqlalchemy.sql.expression import update\nstmt = update(students).where(students.c.lastname == 'Khanna').values(lastname\n ='Kapoor')\nstmt2 = students.delete().where(students.c.lastname == 'Rajhans')\nconn.execute(stmt)\naddresses = Table('addresses', meta, Column('id', Integer, primary_key=True\n ), Column('st_id', Integer, ForeignKey('students.id')), Column(\n 'postal_add', String), Column('email_add', String))\nmeta.create_all(engine)\nconn.execute(addresses.insert(), [{'st_id': 1, 'postal_add':\n 'Shivajinagar Pune', 'email_add': '[email protected]'}, {'st_id': 1,\n 'postal_add': 'ChurchGate Mumbai', 'email_add': '[email protected]'}, {\n 'st_id': 3, 'postal_add': 'Jubilee Hills Hyderabad', 'email_add':\n '[email protected]'}, {'st_id': 5, 'postal_add': 'MG Road Bangaluru',\n 'email_add': '[email protected]'}, {'st_id': 2, 'postal_add':\n 'Cannought Place new Delhi', 'email_add': '[email protected]'}])\nstmt = students.update().values({students.c.name: 'xyz', addresses.c.\n email_add: '[email protected]'}).where(students.c.id == addresses.c.id)\nfrom sqlalchemy import join\nfrom sqlalchemy.sql import select\nj = students.join(addresses, students.c.id == addresses.c.st_id)\nstmt = select([students]).select_from(j)\nresult = conn.execute(stmt)\nfor res in result:\n print(res)\n", "step-5": "from sqlalchemy import create_engine\r\nfrom sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey\r\nfrom sqlalchemy.sql import select\r\nfrom sqlalchemy import text\r\n\r\n#Creating a database 'college.db'\r\nengine = create_engine('sqlite:///college.db', echo=True)\r\nmeta = MetaData()\r\n\r\n#Creating a Students table\r\nstudents = Table(\r\n 'students',meta,\r\n Column('id',Integer,primary_key=True),\r\n Column('name',String),\r\n Column('lastname',String)\r\n)\r\nmeta.create_all(engine)\r\n\r\n#Inserting values\r\nconn = engine.connect()\r\nins = students.insert().values(name='Ravi',lastname='Mahajan')\r\nres = conn.execute(ins)\r\n\r\n# Execute many commands\r\nconn.execute(students.insert(),[\r\n {'name': 'Rajiv', 'lastname': 'Khanna'},\r\n {'name': 'Komal', 'lastname': 'Bhandari'},\r\n {'name': 'Abdul', 'lastname': 'Sattar'},\r\n {'name': 'Priya', 'lastname': 'Rajhans'},\r\n])\r\n\r\n# Selecting from table Students\r\ns = students.select()\r\nresult = conn.execute(s)\r\n# row = result.fetchall()\r\nfor row in result:\r\n print(row)\r\n\r\n# Where condition\r\ns = students.select().where(students.c.id>2)\r\nresult = conn.execute(s)\r\nrow = result.fetchall()\r\nprint(row)\r\n\r\ns = select([students])\r\nresult = conn.execute(s)\r\nfor row in result:\r\n print(row)\r\n\r\n# Using text to execute query using text\r\nt = text('SELECT * from students')\r\nresult = conn.execute(t)\r\n\r\n# Update\r\nstmt = students.update().where(students.c.lastname=='Khanna').values(lastname='Bhatt')\r\nconn.execute(stmt)\r\ns = students.select()\r\nconn.execute(s).fetchall()\r\n\r\nfrom sqlalchemy.sql.expression import update\r\nstmt = update(students).where(students.c.lastname == 'Khanna').values(lastname = 'Kapoor')\r\n\r\nstmt2 = students.delete().where(students.c.lastname=='Rajhans')\r\nconn.execute(stmt)\r\n\r\naddresses = Table(\r\n 'addresses', meta,\r\n Column('id', Integer, primary_key = True),\r\n Column('st_id', Integer, ForeignKey('students.id')),\r\n Column('postal_add', String),\r\n Column('email_add', String))\r\n\r\nmeta.create_all(engine)\r\n\r\nconn.execute(addresses.insert(), [\r\n {'st_id':1, 'postal_add':'Shivajinagar Pune', 'email_add':'[email protected]'},\r\n {'st_id':1, 'postal_add':'ChurchGate Mumbai', 'email_add':'[email protected]'},\r\n {'st_id':3, 'postal_add':'Jubilee Hills Hyderabad', 'email_add':'[email protected]'},\r\n {'st_id':5, 'postal_add':'MG Road Bangaluru', 'email_add':'[email protected]'},\r\n {'st_id':2, 'postal_add':'Cannought Place new Delhi', 'email_add':'[email protected]'},\r\n])\r\n\r\n# Update query for Multiple tables\r\nstmt = students.update().values({students.c.name:'xyz',\r\n addresses.c.email_add:'[email protected]'}).where(students.c.id == addresses.c.id)\r\n\r\n# using joins\r\nfrom sqlalchemy import join\r\nfrom sqlalchemy.sql import select\r\nj = students.join(addresses,students.c.id==addresses.c.st_id)\r\nstmt = select([students]).select_from(j)\r\nresult = conn.execute(stmt)\r\nfor res in result:\r\n print(res)\r\n\r\n\r\n\r\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
''' Code for mmDGM Author: Chongxuan Li ([email protected]) Version = '1.0' ''' import gpulearn_mm_z_x import sys, os import time import color n_hidden = (500,500) if len(sys.argv) > 2: n_hidden = tuple([int(x) for x in sys.argv[2:]]) nz=500 if os.environ.has_key('nz'): nz = int(os.environ['nz']) if os.environ.has_key('stepsize'): alpha = float(os.environ['stepsize']) else: alpha = 3e-4 if os.environ.has_key('decay1'): decay1 = float(os.environ['decay1']) else: decay1 = 0.1 if os.environ.has_key('decay2'): decay2 = float(os.environ['decay2']) else: decay2 = 0.001 if os.environ.has_key('random_seed'): seed = 0 if int(os.environ['random_seed']) == 1: seed = int(time.time()) if int(os.environ['random_seed'] > 1): seed = int(os.environ['random_seed']) color.printRed('random_seed ' + str(seed)) else: seed = int(time.time()) color.printRed('random_seed ' + str(seed)) #print 'random_seed (bool) missing.' #exit() gpulearn_mm_z_x.main(dataset=sys.argv[1], n_z=nz, n_hidden=n_hidden, seed=seed, comment='', alpha=alpha, decay1=decay1, decay2=decay2, gfx=True) #gpulearn_z_x.main(n_data=50000, dataset='svhn_pca', n_z=300, n_hidden=(500,500), seed=0)
normal
{ "blob_id": "40158bbfd9c95a8344f34431d0b0e98c4a1bf6ed", "index": 476, "step-1": "<mask token>\n", "step-2": "<mask token>\nif len(sys.argv) > 2:\n n_hidden = tuple([int(x) for x in sys.argv[2:]])\n<mask token>\nif os.environ.has_key('nz'):\n nz = int(os.environ['nz'])\nif os.environ.has_key('stepsize'):\n alpha = float(os.environ['stepsize'])\nelse:\n alpha = 0.0003\nif os.environ.has_key('decay1'):\n decay1 = float(os.environ['decay1'])\nelse:\n decay1 = 0.1\nif os.environ.has_key('decay2'):\n decay2 = float(os.environ['decay2'])\nelse:\n decay2 = 0.001\nif os.environ.has_key('random_seed'):\n seed = 0\n if int(os.environ['random_seed']) == 1:\n seed = int(time.time())\n if int(os.environ['random_seed'] > 1):\n seed = int(os.environ['random_seed'])\n color.printRed('random_seed ' + str(seed))\nelse:\n seed = int(time.time())\n color.printRed('random_seed ' + str(seed))\ngpulearn_mm_z_x.main(dataset=sys.argv[1], n_z=nz, n_hidden=n_hidden, seed=\n seed, comment='', alpha=alpha, decay1=decay1, decay2=decay2, gfx=True)\n", "step-3": "<mask token>\nn_hidden = 500, 500\nif len(sys.argv) > 2:\n n_hidden = tuple([int(x) for x in sys.argv[2:]])\nnz = 500\nif os.environ.has_key('nz'):\n nz = int(os.environ['nz'])\nif os.environ.has_key('stepsize'):\n alpha = float(os.environ['stepsize'])\nelse:\n alpha = 0.0003\nif os.environ.has_key('decay1'):\n decay1 = float(os.environ['decay1'])\nelse:\n decay1 = 0.1\nif os.environ.has_key('decay2'):\n decay2 = float(os.environ['decay2'])\nelse:\n decay2 = 0.001\nif os.environ.has_key('random_seed'):\n seed = 0\n if int(os.environ['random_seed']) == 1:\n seed = int(time.time())\n if int(os.environ['random_seed'] > 1):\n seed = int(os.environ['random_seed'])\n color.printRed('random_seed ' + str(seed))\nelse:\n seed = int(time.time())\n color.printRed('random_seed ' + str(seed))\ngpulearn_mm_z_x.main(dataset=sys.argv[1], n_z=nz, n_hidden=n_hidden, seed=\n seed, comment='', alpha=alpha, decay1=decay1, decay2=decay2, gfx=True)\n", "step-4": "<mask token>\nimport gpulearn_mm_z_x\nimport sys, os\nimport time\nimport color\nn_hidden = 500, 500\nif len(sys.argv) > 2:\n n_hidden = tuple([int(x) for x in sys.argv[2:]])\nnz = 500\nif os.environ.has_key('nz'):\n nz = int(os.environ['nz'])\nif os.environ.has_key('stepsize'):\n alpha = float(os.environ['stepsize'])\nelse:\n alpha = 0.0003\nif os.environ.has_key('decay1'):\n decay1 = float(os.environ['decay1'])\nelse:\n decay1 = 0.1\nif os.environ.has_key('decay2'):\n decay2 = float(os.environ['decay2'])\nelse:\n decay2 = 0.001\nif os.environ.has_key('random_seed'):\n seed = 0\n if int(os.environ['random_seed']) == 1:\n seed = int(time.time())\n if int(os.environ['random_seed'] > 1):\n seed = int(os.environ['random_seed'])\n color.printRed('random_seed ' + str(seed))\nelse:\n seed = int(time.time())\n color.printRed('random_seed ' + str(seed))\ngpulearn_mm_z_x.main(dataset=sys.argv[1], n_z=nz, n_hidden=n_hidden, seed=\n seed, comment='', alpha=alpha, decay1=decay1, decay2=decay2, gfx=True)\n", "step-5": "'''\nCode for mmDGM\nAuthor: Chongxuan Li ([email protected])\nVersion = '1.0'\n'''\n\nimport gpulearn_mm_z_x\nimport sys, os\nimport time\nimport color\n\nn_hidden = (500,500)\nif len(sys.argv) > 2:\n n_hidden = tuple([int(x) for x in sys.argv[2:]])\nnz=500\nif os.environ.has_key('nz'):\n nz = int(os.environ['nz'])\nif os.environ.has_key('stepsize'):\n alpha = float(os.environ['stepsize'])\nelse:\n alpha = 3e-4\nif os.environ.has_key('decay1'):\n decay1 = float(os.environ['decay1'])\nelse:\n decay1 = 0.1\nif os.environ.has_key('decay2'):\n decay2 = float(os.environ['decay2'])\nelse:\n decay2 = 0.001\nif os.environ.has_key('random_seed'):\n seed = 0\n if int(os.environ['random_seed']) == 1:\n seed = int(time.time())\n if int(os.environ['random_seed'] > 1):\n seed = int(os.environ['random_seed'])\n color.printRed('random_seed ' + str(seed))\nelse:\n seed = int(time.time())\n color.printRed('random_seed ' + str(seed))\n #print 'random_seed (bool) missing.' \n #exit()\n \ngpulearn_mm_z_x.main(dataset=sys.argv[1], n_z=nz, n_hidden=n_hidden, seed=seed, comment='', alpha=alpha, decay1=decay1, decay2=decay2, gfx=True)\n\n\n#gpulearn_z_x.main(n_data=50000, dataset='svhn_pca', n_z=300, n_hidden=(500,500), seed=0)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
''' Created on May 18, 2010 @author: Abi.Mohammadi & Majid.Vesal ''' from threading import current_thread import copy import time from deltapy.core import DeltaException, Context import deltapy.security.services as security_services import deltapy.security.session.services as session_services import deltapy.unique_id.services as unique_id_services class SessionException(DeltaException): ''' A class for handling session exceptions. ''' pass #class SessionContext(Context): # ''' # A class for saving some data in session domain. # ''' # # def __init__(self, session): # ''' # @param session: # ''' # # Context.__init__(self) # self['__session__'] = session # # def __setitem__(self, key, value): # ''' # Sets new item or updates existing item in context # # @param key: # @param value: # ''' # # result = Context.__setitem__(self, key, value) # self['__session__'].update() # return result class SessionContext(dict): ''' A class for saving some data in session domain. ''' def __init__(self, session): ''' @param session: ''' super(SessionContext, self).__init__() self._ticket = session.get_ticket() def __setitem__(self, key, value): ''' Sets new item or updates existing item in context @param key: @param value: ''' result = super(SessionContext, self).__setitem__(key, value) # Updating session because of this change in session context session_services.get_session(self._ticket, False).update() return result class Session: """ A class for storing session information. """ class StateEnum: ''' A class for defining session state. ''' ACTIVE = "Active" INACTIVE = "Inactive" CLOSED = "Closed" KILLED = "Killed" EXPIRED = "Expired" DISABLED = "Disabled" def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None): self._ticket = ticket self._state = Session.StateEnum.INACTIVE self._create_date = time.time() self._id = unique_id_services.get_id('session_id') self._context = SessionContext(self) self._user_id = user.id self._client_ip = client_ip self._client_request = None self._lifetime = lifetime # millisecond def get_client_ip(self): ''' Returns the user IP address. ''' return self._client_ip def close(self): ''' Closes the session. ''' session_services.close_session(self) def active(self, client_request): ''' Activates the session. Sets this session to current thread. ''' self._set_client_request(client_request) thread = current_thread() thread.__LOCALE__ = client_request.context.get('__LOCALE__') session_services.active_session(self) def _set_client_request(self, client_request): ''' Sets call context to session. ''' if client_request.context is None: client_request.context = {} self._client_request = copy.deepcopy(client_request) def get_call_context(self): ''' Returns call context. @return {} ''' return self._client_request.context def get_internal_context(self): ''' Retunrs internal system context for the current call @rtype: dict @return: internal context dictionary ''' if not hasattr(self._client_request, 'internal_context') or \ self._client_request.internal_context is None: self._client_request.internal_context = {} return self._client_request.internal_context def get_client_request(self): ''' Returns current client request. @rtype: ClientRequest @return: client request ''' return self._client_request def get_ticket(self): ''' Returns session ID. @return: str ''' return self._ticket def get_id(self): ''' Returns session ID. @return: int ''' return self._id def get_user(self): ''' Returns the user which creates this session. @return: user ''' return security_services.get_user(self._user_id) def get_user_id(self): ''' Returns the user which creates this session. @return: user ''' return self._user_id def update(self): ''' Updates session. ''' session_services.update_session(self) def cleanup(self): ''' Cleanups the session. ''' session_services.cleanup_session(self) def get_state(self): ''' Returns the session state. @return: str ''' return self._state def set_state(self, state): ''' Returns the session state. @return: str ''' self._state = state self.update() def get_creation_date(self): ''' Returns the session creation date. @return: ''' return time.ctime(self._create_date) def get_context(self): ''' Returns session context. @return: SessionContext ''' return self._context def __str__(self): return "%s[%s]" % (self.__class__.__name__, self.get_ticket()) def __repr__(self): return "%s[%s]" % (self.__class__.__name__, self.get_ticket()) def is_expired(self): """ If session is expired, returns True. @return: Is expired @rtype: bool """ if self._lifetime is not None and self._lifetime > 0: # 300 seconds waite is the tolerance ! # The unit of lifetime is millisecond if (time.time() - self._create_date) * 1000 > self._lifetime + 300000: return True return False
normal
{ "blob_id": "80469fd945a21c1bd2b5590047016a4b60880c88", "index": 7006, "step-1": "<mask token>\n\n\nclass Session:\n <mask token>\n\n\n class StateEnum:\n \"\"\"\n A class for defining session state.\n \"\"\"\n ACTIVE = 'Active'\n INACTIVE = 'Inactive'\n CLOSED = 'Closed'\n KILLED = 'Killed'\n EXPIRED = 'Expired'\n DISABLED = 'Disabled'\n\n def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None):\n self._ticket = ticket\n self._state = Session.StateEnum.INACTIVE\n self._create_date = time.time()\n self._id = unique_id_services.get_id('session_id')\n self._context = SessionContext(self)\n self._user_id = user.id\n self._client_ip = client_ip\n self._client_request = None\n self._lifetime = lifetime\n\n def get_client_ip(self):\n \"\"\"\n Returns the user IP address.\n \"\"\"\n return self._client_ip\n\n def close(self):\n \"\"\"\n Closes the session.\n \"\"\"\n session_services.close_session(self)\n\n def active(self, client_request):\n \"\"\"\n Activates the session. Sets this session to current thread.\n \"\"\"\n self._set_client_request(client_request)\n thread = current_thread()\n thread.__LOCALE__ = client_request.context.get('__LOCALE__')\n session_services.active_session(self)\n\n def _set_client_request(self, client_request):\n \"\"\"\n Sets call context to session.\n \"\"\"\n if client_request.context is None:\n client_request.context = {}\n self._client_request = copy.deepcopy(client_request)\n\n def get_call_context(self):\n \"\"\"\n Returns call context.\n \n @return {}\n \"\"\"\n return self._client_request.context\n\n def get_internal_context(self):\n \"\"\"\n Retunrs internal system context for the current call\n\n @rtype: dict\n @return: internal context dictionary\n \"\"\"\n if not hasattr(self._client_request, 'internal_context'\n ) or self._client_request.internal_context is None:\n self._client_request.internal_context = {}\n return self._client_request.internal_context\n\n def get_client_request(self):\n \"\"\"\n Returns current client request.\n \n @rtype: ClientRequest\n @return: client request\n \"\"\"\n return self._client_request\n <mask token>\n\n def get_id(self):\n \"\"\"\n Returns session ID.\n \n @return: int\n \"\"\"\n return self._id\n\n def get_user(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return security_services.get_user(self._user_id)\n\n def get_user_id(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return self._user_id\n\n def update(self):\n \"\"\"\n Updates session.\n \"\"\"\n session_services.update_session(self)\n\n def cleanup(self):\n \"\"\"\n Cleanups the session.\n \"\"\"\n session_services.cleanup_session(self)\n\n def get_state(self):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n return self._state\n <mask token>\n\n def get_creation_date(self):\n \"\"\"\n Returns the session creation date.\n \n @return: \n \"\"\"\n return time.ctime(self._create_date)\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def is_expired(self):\n \"\"\"\n If session is expired, returns True.\n\n @return: Is expired\n @rtype: bool\n \"\"\"\n if self._lifetime is not None and self._lifetime > 0:\n if (time.time() - self._create_date\n ) * 1000 > self._lifetime + 300000:\n return True\n return False\n", "step-2": "<mask token>\n\n\nclass Session:\n <mask token>\n\n\n class StateEnum:\n \"\"\"\n A class for defining session state.\n \"\"\"\n ACTIVE = 'Active'\n INACTIVE = 'Inactive'\n CLOSED = 'Closed'\n KILLED = 'Killed'\n EXPIRED = 'Expired'\n DISABLED = 'Disabled'\n\n def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None):\n self._ticket = ticket\n self._state = Session.StateEnum.INACTIVE\n self._create_date = time.time()\n self._id = unique_id_services.get_id('session_id')\n self._context = SessionContext(self)\n self._user_id = user.id\n self._client_ip = client_ip\n self._client_request = None\n self._lifetime = lifetime\n\n def get_client_ip(self):\n \"\"\"\n Returns the user IP address.\n \"\"\"\n return self._client_ip\n\n def close(self):\n \"\"\"\n Closes the session.\n \"\"\"\n session_services.close_session(self)\n\n def active(self, client_request):\n \"\"\"\n Activates the session. Sets this session to current thread.\n \"\"\"\n self._set_client_request(client_request)\n thread = current_thread()\n thread.__LOCALE__ = client_request.context.get('__LOCALE__')\n session_services.active_session(self)\n\n def _set_client_request(self, client_request):\n \"\"\"\n Sets call context to session.\n \"\"\"\n if client_request.context is None:\n client_request.context = {}\n self._client_request = copy.deepcopy(client_request)\n\n def get_call_context(self):\n \"\"\"\n Returns call context.\n \n @return {}\n \"\"\"\n return self._client_request.context\n\n def get_internal_context(self):\n \"\"\"\n Retunrs internal system context for the current call\n\n @rtype: dict\n @return: internal context dictionary\n \"\"\"\n if not hasattr(self._client_request, 'internal_context'\n ) or self._client_request.internal_context is None:\n self._client_request.internal_context = {}\n return self._client_request.internal_context\n\n def get_client_request(self):\n \"\"\"\n Returns current client request.\n \n @rtype: ClientRequest\n @return: client request\n \"\"\"\n return self._client_request\n\n def get_ticket(self):\n \"\"\"\n Returns session ID.\n \n @return: str\n \"\"\"\n return self._ticket\n\n def get_id(self):\n \"\"\"\n Returns session ID.\n \n @return: int\n \"\"\"\n return self._id\n\n def get_user(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return security_services.get_user(self._user_id)\n\n def get_user_id(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return self._user_id\n\n def update(self):\n \"\"\"\n Updates session.\n \"\"\"\n session_services.update_session(self)\n\n def cleanup(self):\n \"\"\"\n Cleanups the session.\n \"\"\"\n session_services.cleanup_session(self)\n\n def get_state(self):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n return self._state\n\n def set_state(self, state):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n self._state = state\n self.update()\n\n def get_creation_date(self):\n \"\"\"\n Returns the session creation date.\n \n @return: \n \"\"\"\n return time.ctime(self._create_date)\n\n def get_context(self):\n \"\"\"\n Returns session context.\n \n @return: SessionContext\n \"\"\"\n return self._context\n <mask token>\n\n def __repr__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def is_expired(self):\n \"\"\"\n If session is expired, returns True.\n\n @return: Is expired\n @rtype: bool\n \"\"\"\n if self._lifetime is not None and self._lifetime > 0:\n if (time.time() - self._create_date\n ) * 1000 > self._lifetime + 300000:\n return True\n return False\n", "step-3": "<mask token>\n\n\nclass SessionContext(dict):\n <mask token>\n <mask token>\n\n def __setitem__(self, key, value):\n \"\"\"\n Sets new item or updates existing item in context\n \n @param key:\n @param value:\n \"\"\"\n result = super(SessionContext, self).__setitem__(key, value)\n session_services.get_session(self._ticket, False).update()\n return result\n\n\nclass Session:\n \"\"\"\n A class for storing session information.\n \"\"\"\n\n\n class StateEnum:\n \"\"\"\n A class for defining session state.\n \"\"\"\n ACTIVE = 'Active'\n INACTIVE = 'Inactive'\n CLOSED = 'Closed'\n KILLED = 'Killed'\n EXPIRED = 'Expired'\n DISABLED = 'Disabled'\n\n def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None):\n self._ticket = ticket\n self._state = Session.StateEnum.INACTIVE\n self._create_date = time.time()\n self._id = unique_id_services.get_id('session_id')\n self._context = SessionContext(self)\n self._user_id = user.id\n self._client_ip = client_ip\n self._client_request = None\n self._lifetime = lifetime\n\n def get_client_ip(self):\n \"\"\"\n Returns the user IP address.\n \"\"\"\n return self._client_ip\n\n def close(self):\n \"\"\"\n Closes the session.\n \"\"\"\n session_services.close_session(self)\n\n def active(self, client_request):\n \"\"\"\n Activates the session. Sets this session to current thread.\n \"\"\"\n self._set_client_request(client_request)\n thread = current_thread()\n thread.__LOCALE__ = client_request.context.get('__LOCALE__')\n session_services.active_session(self)\n\n def _set_client_request(self, client_request):\n \"\"\"\n Sets call context to session.\n \"\"\"\n if client_request.context is None:\n client_request.context = {}\n self._client_request = copy.deepcopy(client_request)\n\n def get_call_context(self):\n \"\"\"\n Returns call context.\n \n @return {}\n \"\"\"\n return self._client_request.context\n\n def get_internal_context(self):\n \"\"\"\n Retunrs internal system context for the current call\n\n @rtype: dict\n @return: internal context dictionary\n \"\"\"\n if not hasattr(self._client_request, 'internal_context'\n ) or self._client_request.internal_context is None:\n self._client_request.internal_context = {}\n return self._client_request.internal_context\n\n def get_client_request(self):\n \"\"\"\n Returns current client request.\n \n @rtype: ClientRequest\n @return: client request\n \"\"\"\n return self._client_request\n\n def get_ticket(self):\n \"\"\"\n Returns session ID.\n \n @return: str\n \"\"\"\n return self._ticket\n\n def get_id(self):\n \"\"\"\n Returns session ID.\n \n @return: int\n \"\"\"\n return self._id\n\n def get_user(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return security_services.get_user(self._user_id)\n\n def get_user_id(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return self._user_id\n\n def update(self):\n \"\"\"\n Updates session.\n \"\"\"\n session_services.update_session(self)\n\n def cleanup(self):\n \"\"\"\n Cleanups the session.\n \"\"\"\n session_services.cleanup_session(self)\n\n def get_state(self):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n return self._state\n\n def set_state(self, state):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n self._state = state\n self.update()\n\n def get_creation_date(self):\n \"\"\"\n Returns the session creation date.\n \n @return: \n \"\"\"\n return time.ctime(self._create_date)\n\n def get_context(self):\n \"\"\"\n Returns session context.\n \n @return: SessionContext\n \"\"\"\n return self._context\n\n def __str__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def __repr__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def is_expired(self):\n \"\"\"\n If session is expired, returns True.\n\n @return: Is expired\n @rtype: bool\n \"\"\"\n if self._lifetime is not None and self._lifetime > 0:\n if (time.time() - self._create_date\n ) * 1000 > self._lifetime + 300000:\n return True\n return False\n", "step-4": "<mask token>\n\n\nclass SessionException(DeltaException):\n <mask token>\n pass\n\n\nclass SessionContext(dict):\n \"\"\"\n A class for saving some data in session domain.\n \"\"\"\n\n def __init__(self, session):\n \"\"\"\n @param session:\n \"\"\"\n super(SessionContext, self).__init__()\n self._ticket = session.get_ticket()\n\n def __setitem__(self, key, value):\n \"\"\"\n Sets new item or updates existing item in context\n \n @param key:\n @param value:\n \"\"\"\n result = super(SessionContext, self).__setitem__(key, value)\n session_services.get_session(self._ticket, False).update()\n return result\n\n\nclass Session:\n \"\"\"\n A class for storing session information.\n \"\"\"\n\n\n class StateEnum:\n \"\"\"\n A class for defining session state.\n \"\"\"\n ACTIVE = 'Active'\n INACTIVE = 'Inactive'\n CLOSED = 'Closed'\n KILLED = 'Killed'\n EXPIRED = 'Expired'\n DISABLED = 'Disabled'\n\n def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None):\n self._ticket = ticket\n self._state = Session.StateEnum.INACTIVE\n self._create_date = time.time()\n self._id = unique_id_services.get_id('session_id')\n self._context = SessionContext(self)\n self._user_id = user.id\n self._client_ip = client_ip\n self._client_request = None\n self._lifetime = lifetime\n\n def get_client_ip(self):\n \"\"\"\n Returns the user IP address.\n \"\"\"\n return self._client_ip\n\n def close(self):\n \"\"\"\n Closes the session.\n \"\"\"\n session_services.close_session(self)\n\n def active(self, client_request):\n \"\"\"\n Activates the session. Sets this session to current thread.\n \"\"\"\n self._set_client_request(client_request)\n thread = current_thread()\n thread.__LOCALE__ = client_request.context.get('__LOCALE__')\n session_services.active_session(self)\n\n def _set_client_request(self, client_request):\n \"\"\"\n Sets call context to session.\n \"\"\"\n if client_request.context is None:\n client_request.context = {}\n self._client_request = copy.deepcopy(client_request)\n\n def get_call_context(self):\n \"\"\"\n Returns call context.\n \n @return {}\n \"\"\"\n return self._client_request.context\n\n def get_internal_context(self):\n \"\"\"\n Retunrs internal system context for the current call\n\n @rtype: dict\n @return: internal context dictionary\n \"\"\"\n if not hasattr(self._client_request, 'internal_context'\n ) or self._client_request.internal_context is None:\n self._client_request.internal_context = {}\n return self._client_request.internal_context\n\n def get_client_request(self):\n \"\"\"\n Returns current client request.\n \n @rtype: ClientRequest\n @return: client request\n \"\"\"\n return self._client_request\n\n def get_ticket(self):\n \"\"\"\n Returns session ID.\n \n @return: str\n \"\"\"\n return self._ticket\n\n def get_id(self):\n \"\"\"\n Returns session ID.\n \n @return: int\n \"\"\"\n return self._id\n\n def get_user(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return security_services.get_user(self._user_id)\n\n def get_user_id(self):\n \"\"\"\n Returns the user which creates this session.\n \n @return: user\n \"\"\"\n return self._user_id\n\n def update(self):\n \"\"\"\n Updates session.\n \"\"\"\n session_services.update_session(self)\n\n def cleanup(self):\n \"\"\"\n Cleanups the session.\n \"\"\"\n session_services.cleanup_session(self)\n\n def get_state(self):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n return self._state\n\n def set_state(self, state):\n \"\"\"\n Returns the session state.\n \n @return: str\n \"\"\"\n self._state = state\n self.update()\n\n def get_creation_date(self):\n \"\"\"\n Returns the session creation date.\n \n @return: \n \"\"\"\n return time.ctime(self._create_date)\n\n def get_context(self):\n \"\"\"\n Returns session context.\n \n @return: SessionContext\n \"\"\"\n return self._context\n\n def __str__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def __repr__(self):\n return '%s[%s]' % (self.__class__.__name__, self.get_ticket())\n\n def is_expired(self):\n \"\"\"\n If session is expired, returns True.\n\n @return: Is expired\n @rtype: bool\n \"\"\"\n if self._lifetime is not None and self._lifetime > 0:\n if (time.time() - self._create_date\n ) * 1000 > self._lifetime + 300000:\n return True\n return False\n", "step-5": "'''\nCreated on May 18, 2010\n\n@author: Abi.Mohammadi & Majid.Vesal\n'''\n\nfrom threading import current_thread\n\nimport copy\nimport time\n\nfrom deltapy.core import DeltaException, Context\n\nimport deltapy.security.services as security_services\nimport deltapy.security.session.services as session_services\nimport deltapy.unique_id.services as unique_id_services\n\nclass SessionException(DeltaException):\n '''\n A class for handling session exceptions.\n '''\n pass\n\n#class SessionContext(Context):\n# '''\n# A class for saving some data in session domain.\n# '''\n# \n# def __init__(self, session):\n# '''\n# @param session:\n# '''\n# \n# Context.__init__(self)\n# self['__session__'] = session\n# \n# def __setitem__(self, key, value):\n# '''\n# Sets new item or updates existing item in context\n# \n# @param key:\n# @param value:\n# '''\n# \n# result = Context.__setitem__(self, key, value)\n# self['__session__'].update()\n# return result\n\nclass SessionContext(dict):\n '''\n A class for saving some data in session domain.\n '''\n \n def __init__(self, session):\n '''\n @param session:\n '''\n \n super(SessionContext, self).__init__()\n self._ticket = session.get_ticket()\n \n def __setitem__(self, key, value):\n '''\n Sets new item or updates existing item in context\n \n @param key:\n @param value:\n '''\n result = super(SessionContext, self).__setitem__(key, value)\n \n # Updating session because of this change in session context\n session_services.get_session(self._ticket, False).update()\n \n return result\n\nclass Session:\n \"\"\"\n A class for storing session information.\n \"\"\"\n\n class StateEnum:\n '''\n A class for defining session state.\n '''\n ACTIVE = \"Active\"\n INACTIVE = \"Inactive\"\n CLOSED = \"Closed\"\n KILLED = \"Killed\"\n EXPIRED = \"Expired\"\n DISABLED = \"Disabled\"\n\n def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None):\n self._ticket = ticket\n self._state = Session.StateEnum.INACTIVE\n self._create_date = time.time()\n self._id = unique_id_services.get_id('session_id')\n self._context = SessionContext(self)\n self._user_id = user.id\n self._client_ip = client_ip\n self._client_request = None\n self._lifetime = lifetime # millisecond\n \n def get_client_ip(self):\n '''\n Returns the user IP address.\n '''\n \n return self._client_ip\n \n def close(self):\n '''\n Closes the session.\n '''\n session_services.close_session(self)\n \n def active(self, client_request):\n '''\n Activates the session. Sets this session to current thread.\n '''\n \n self._set_client_request(client_request)\n thread = current_thread()\n thread.__LOCALE__ = client_request.context.get('__LOCALE__')\n session_services.active_session(self)\n \n def _set_client_request(self, client_request):\n '''\n Sets call context to session.\n '''\n \n if client_request.context is None:\n client_request.context = {}\n self._client_request = copy.deepcopy(client_request)\n \n def get_call_context(self):\n '''\n Returns call context.\n \n @return {}\n '''\n \n return self._client_request.context\n\n def get_internal_context(self):\n '''\n Retunrs internal system context for the current call\n\n @rtype: dict\n @return: internal context dictionary\n '''\n\n if not hasattr(self._client_request, 'internal_context') or \\\n self._client_request.internal_context is None:\n self._client_request.internal_context = {}\n\n return self._client_request.internal_context\n \n def get_client_request(self):\n '''\n Returns current client request.\n \n @rtype: ClientRequest\n @return: client request\n '''\n \n return self._client_request\n\n def get_ticket(self):\n '''\n Returns session ID.\n \n @return: str\n '''\n \n return self._ticket\n \n def get_id(self):\n '''\n Returns session ID.\n \n @return: int\n '''\n \n return self._id\n \n\n def get_user(self):\n '''\n Returns the user which creates this session.\n \n @return: user\n '''\n \n return security_services.get_user(self._user_id)\n \n def get_user_id(self):\n '''\n Returns the user which creates this session.\n \n @return: user\n '''\n \n return self._user_id\n\n def update(self):\n '''\n Updates session.\n '''\n \n session_services.update_session(self)\n \n def cleanup(self):\n '''\n Cleanups the session.\n '''\n \n session_services.cleanup_session(self)\n \n def get_state(self):\n '''\n Returns the session state.\n \n @return: str\n '''\n \n return self._state\n \n def set_state(self, state):\n '''\n Returns the session state.\n \n @return: str\n '''\n \n self._state = state\n self.update()\n\n def get_creation_date(self):\n '''\n Returns the session creation date.\n \n @return: \n '''\n \n return time.ctime(self._create_date)\n \n def get_context(self):\n '''\n Returns session context.\n \n @return: SessionContext\n '''\n \n return self._context \n \n def __str__(self):\n return \"%s[%s]\" % (self.__class__.__name__, self.get_ticket())\n \n def __repr__(self):\n return \"%s[%s]\" % (self.__class__.__name__, self.get_ticket())\n\n def is_expired(self):\n \"\"\"\n If session is expired, returns True.\n\n @return: Is expired\n @rtype: bool\n \"\"\"\n\n if self._lifetime is not None and self._lifetime > 0:\n # 300 seconds waite is the tolerance !\n # The unit of lifetime is millisecond\n if (time.time() - self._create_date) * 1000 > self._lifetime + 300000:\n return True\n\n return False\n", "step-ids": [ 18, 21, 25, 28, 31 ] }
[ 18, 21, 25, 28, 31 ]
from rest_framework.serializers import ModelSerializer from rest_framework.serializers import ReadOnlyField from rest_framework.serializers import SlugField from rest_framework.validators import UniqueValidator from django.db import models from illumidesk.teams.util import get_next_unique_team_slug from illumidesk.users.models import IllumiDeskUser from .models import Invitation from .models import Membership from .models import Team class IllumiDeskUserSerializer(ModelSerializer): class Meta: model = IllumiDeskUser fields = ('first_name', 'last_name', 'get_display_name') abstract = True class MembershipSerializer(ModelSerializer): first_name = ReadOnlyField(source='user.first_name') last_name = ReadOnlyField(source='user.last_name') display_name = ReadOnlyField(source='user.get_display_name') class Meta: model = Membership fields = ('id', 'first_name', 'last_name', 'display_name', 'role') class InvitationSerializer(ModelSerializer): id = ReadOnlyField() invited_by = ReadOnlyField(source='invited_by.get_display_name') class Meta: model = Invitation fields = ('id', 'team', 'email', 'role', 'invited_by', 'is_accepted') class TeamSerializer(ModelSerializer): slug = SlugField( required=False, validators=[UniqueValidator(queryset=Team.objects.all())], ) members = MembershipSerializer(source='membership_set', many=True, read_only=True) invitations = InvitationSerializer(many=True, read_only=True, source='pending_invitations') dashboard_url = ReadOnlyField() class Meta: model = Team fields = ('id', 'name', 'slug', 'members', 'invitations', 'dashboard_url') def create(self, validated_data): team_name = validated_data.get("name", None) validated_data['slug'] = validated_data.get("slug", get_next_unique_team_slug(team_name)) return super().create(validated_data)
normal
{ "blob_id": "c005ae9dc8b50e24d72dbc99329bb5585d617081", "index": 5590, "step-1": "<mask token>\n\n\nclass InvitationSerializer(ModelSerializer):\n <mask token>\n <mask token>\n\n\n class Meta:\n model = Invitation\n fields = 'id', 'team', 'email', 'role', 'invited_by', 'is_accepted'\n\n\nclass TeamSerializer(ModelSerializer):\n slug = SlugField(required=False, validators=[UniqueValidator(queryset=\n Team.objects.all())])\n members = MembershipSerializer(source='membership_set', many=True,\n read_only=True)\n invitations = InvitationSerializer(many=True, read_only=True, source=\n 'pending_invitations')\n dashboard_url = ReadOnlyField()\n\n\n class Meta:\n model = Team\n fields = ('id', 'name', 'slug', 'members', 'invitations',\n 'dashboard_url')\n\n def create(self, validated_data):\n team_name = validated_data.get('name', None)\n validated_data['slug'] = validated_data.get('slug',\n get_next_unique_team_slug(team_name))\n return super().create(validated_data)\n", "step-2": "<mask token>\n\n\nclass MembershipSerializer(ModelSerializer):\n <mask token>\n <mask token>\n <mask token>\n\n\n class Meta:\n model = Membership\n fields = 'id', 'first_name', 'last_name', 'display_name', 'role'\n\n\nclass InvitationSerializer(ModelSerializer):\n id = ReadOnlyField()\n invited_by = ReadOnlyField(source='invited_by.get_display_name')\n\n\n class Meta:\n model = Invitation\n fields = 'id', 'team', 'email', 'role', 'invited_by', 'is_accepted'\n\n\nclass TeamSerializer(ModelSerializer):\n slug = SlugField(required=False, validators=[UniqueValidator(queryset=\n Team.objects.all())])\n members = MembershipSerializer(source='membership_set', many=True,\n read_only=True)\n invitations = InvitationSerializer(many=True, read_only=True, source=\n 'pending_invitations')\n dashboard_url = ReadOnlyField()\n\n\n class Meta:\n model = Team\n fields = ('id', 'name', 'slug', 'members', 'invitations',\n 'dashboard_url')\n\n def create(self, validated_data):\n team_name = validated_data.get('name', None)\n validated_data['slug'] = validated_data.get('slug',\n get_next_unique_team_slug(team_name))\n return super().create(validated_data)\n", "step-3": "<mask token>\n\n\nclass IllumiDeskUserSerializer(ModelSerializer):\n\n\n class Meta:\n model = IllumiDeskUser\n fields = 'first_name', 'last_name', 'get_display_name'\n abstract = True\n\n\nclass MembershipSerializer(ModelSerializer):\n first_name = ReadOnlyField(source='user.first_name')\n last_name = ReadOnlyField(source='user.last_name')\n display_name = ReadOnlyField(source='user.get_display_name')\n\n\n class Meta:\n model = Membership\n fields = 'id', 'first_name', 'last_name', 'display_name', 'role'\n\n\nclass InvitationSerializer(ModelSerializer):\n id = ReadOnlyField()\n invited_by = ReadOnlyField(source='invited_by.get_display_name')\n\n\n class Meta:\n model = Invitation\n fields = 'id', 'team', 'email', 'role', 'invited_by', 'is_accepted'\n\n\nclass TeamSerializer(ModelSerializer):\n slug = SlugField(required=False, validators=[UniqueValidator(queryset=\n Team.objects.all())])\n members = MembershipSerializer(source='membership_set', many=True,\n read_only=True)\n invitations = InvitationSerializer(many=True, read_only=True, source=\n 'pending_invitations')\n dashboard_url = ReadOnlyField()\n\n\n class Meta:\n model = Team\n fields = ('id', 'name', 'slug', 'members', 'invitations',\n 'dashboard_url')\n\n def create(self, validated_data):\n team_name = validated_data.get('name', None)\n validated_data['slug'] = validated_data.get('slug',\n get_next_unique_team_slug(team_name))\n return super().create(validated_data)\n", "step-4": "from rest_framework.serializers import ModelSerializer\nfrom rest_framework.serializers import ReadOnlyField\nfrom rest_framework.serializers import SlugField\nfrom rest_framework.validators import UniqueValidator\nfrom django.db import models\nfrom illumidesk.teams.util import get_next_unique_team_slug\nfrom illumidesk.users.models import IllumiDeskUser\nfrom .models import Invitation\nfrom .models import Membership\nfrom .models import Team\n\n\nclass IllumiDeskUserSerializer(ModelSerializer):\n\n\n class Meta:\n model = IllumiDeskUser\n fields = 'first_name', 'last_name', 'get_display_name'\n abstract = True\n\n\nclass MembershipSerializer(ModelSerializer):\n first_name = ReadOnlyField(source='user.first_name')\n last_name = ReadOnlyField(source='user.last_name')\n display_name = ReadOnlyField(source='user.get_display_name')\n\n\n class Meta:\n model = Membership\n fields = 'id', 'first_name', 'last_name', 'display_name', 'role'\n\n\nclass InvitationSerializer(ModelSerializer):\n id = ReadOnlyField()\n invited_by = ReadOnlyField(source='invited_by.get_display_name')\n\n\n class Meta:\n model = Invitation\n fields = 'id', 'team', 'email', 'role', 'invited_by', 'is_accepted'\n\n\nclass TeamSerializer(ModelSerializer):\n slug = SlugField(required=False, validators=[UniqueValidator(queryset=\n Team.objects.all())])\n members = MembershipSerializer(source='membership_set', many=True,\n read_only=True)\n invitations = InvitationSerializer(many=True, read_only=True, source=\n 'pending_invitations')\n dashboard_url = ReadOnlyField()\n\n\n class Meta:\n model = Team\n fields = ('id', 'name', 'slug', 'members', 'invitations',\n 'dashboard_url')\n\n def create(self, validated_data):\n team_name = validated_data.get('name', None)\n validated_data['slug'] = validated_data.get('slug',\n get_next_unique_team_slug(team_name))\n return super().create(validated_data)\n", "step-5": "from rest_framework.serializers import ModelSerializer\nfrom rest_framework.serializers import ReadOnlyField\nfrom rest_framework.serializers import SlugField\nfrom rest_framework.validators import UniqueValidator\n\nfrom django.db import models\n\nfrom illumidesk.teams.util import get_next_unique_team_slug\nfrom illumidesk.users.models import IllumiDeskUser\n\nfrom .models import Invitation\nfrom .models import Membership\nfrom .models import Team\n\n\nclass IllumiDeskUserSerializer(ModelSerializer):\n class Meta:\n model = IllumiDeskUser\n fields = ('first_name', 'last_name', 'get_display_name')\n abstract = True\n\nclass MembershipSerializer(ModelSerializer):\n first_name = ReadOnlyField(source='user.first_name')\n last_name = ReadOnlyField(source='user.last_name')\n display_name = ReadOnlyField(source='user.get_display_name')\n\n class Meta:\n model = Membership\n fields = ('id', 'first_name', 'last_name', 'display_name', 'role')\n\n\nclass InvitationSerializer(ModelSerializer):\n id = ReadOnlyField()\n invited_by = ReadOnlyField(source='invited_by.get_display_name')\n\n class Meta:\n model = Invitation\n fields = ('id', 'team', 'email', 'role', 'invited_by', 'is_accepted')\n\n\nclass TeamSerializer(ModelSerializer):\n slug = SlugField(\n required=False,\n validators=[UniqueValidator(queryset=Team.objects.all())],\n )\n members = MembershipSerializer(source='membership_set', many=True, read_only=True)\n invitations = InvitationSerializer(many=True, read_only=True, source='pending_invitations')\n dashboard_url = ReadOnlyField()\n\n class Meta:\n model = Team\n fields = ('id', 'name', 'slug', 'members', 'invitations', 'dashboard_url')\n\n def create(self, validated_data):\n team_name = validated_data.get(\"name\", None)\n validated_data['slug'] = validated_data.get(\"slug\", get_next_unique_team_slug(team_name))\n return super().create(validated_data)\n", "step-ids": [ 4, 6, 8, 9, 10 ] }
[ 4, 6, 8, 9, 10 ]
from robocorp_ls_core.python_ls import PythonLanguageServer from robocorp_ls_core.basic import overrides from robocorp_ls_core.robotframework_log import get_logger from typing import Optional, List, Dict from robocorp_ls_core.protocols import IConfig, IMonitor, ITestInfoTypedDict, IWorkspace from functools import partial from robocorp_ls_core.jsonrpc.endpoint import require_monitor from robocorp_ls_core.lsp import ( SymbolInformationTypedDict, FoldingRangeTypedDict, HoverTypedDict, TextDocumentTypedDict, CodeLensTypedDict, DocumentSymbolTypedDict, PositionTypedDict, ) from robotframework_ls.impl.protocols import IKeywordFound from robocorp_ls_core.watchdog_wrapper import IFSObserver import itertools log = get_logger(__name__) class RobotFrameworkServerApi(PythonLanguageServer): """ This is a custom server. It uses the same message-format used in the language server but with custom messages (i.e.: this is not the language server, but an API to use the bits we need from robotframework in a separate process). """ def __init__( self, read_from, write_to, libspec_manager=None, observer: Optional[IFSObserver] = None, ): from robotframework_ls.impl.libspec_manager import LibspecManager if libspec_manager is None: try: libspec_manager = LibspecManager(observer=observer) except: log.exception("Unable to properly initialize the LibspecManager.") raise self.libspec_manager = libspec_manager PythonLanguageServer.__init__(self, read_from, write_to) self._version = None self._next_time = partial(next, itertools.count(0)) @overrides(PythonLanguageServer._create_config) def _create_config(self) -> IConfig: from robotframework_ls.robot_config import RobotConfig return RobotConfig() def m_version(self): if self._version is not None: return self._version try: import robot # noqa except: log.exception("Unable to import 'robot'.") version = "NO_ROBOT" else: try: from robot import get_version version = get_version(naked=True) except: log.exception("Unable to get version.") version = "N/A" # Too old? self._version = version return self._version def _check_min_version(self, min_version): from robocorp_ls_core.basic import check_min_version version = self.m_version() return check_min_version(version, min_version) @overrides(PythonLanguageServer.m_workspace__did_change_configuration) def m_workspace__did_change_configuration(self, **kwargs): PythonLanguageServer.m_workspace__did_change_configuration(self, **kwargs) self.libspec_manager.config = self.config @overrides(PythonLanguageServer.lint) def lint(self, *args, **kwargs): pass # No-op for this server. @overrides(PythonLanguageServer.cancel_lint) def cancel_lint(self, *args, **kwargs): pass # No-op for this server. @overrides(PythonLanguageServer._obtain_fs_observer) def _obtain_fs_observer(self) -> IFSObserver: return self.libspec_manager.fs_observer @overrides(PythonLanguageServer._create_workspace) def _create_workspace( self, root_uri: str, fs_observer: IFSObserver, workspace_folders ) -> IWorkspace: from robotframework_ls.impl.robot_workspace import RobotWorkspace return RobotWorkspace( root_uri, fs_observer, workspace_folders, libspec_manager=self.libspec_manager, ) def m_lint(self, doc_uri): if not self._check_min_version((3, 2)): from robocorp_ls_core.lsp import Error msg = ( "robotframework version (%s) too old for linting.\n" "Please install a newer version and restart the language server." % (self.m_version(),) ) log.info(msg) return [Error(msg, (0, 0), (1, 0)).to_lsp_diagnostic()] func = partial(self._threaded_lint, doc_uri) func = require_monitor(func) return func def _threaded_lint(self, doc_uri, monitor: IMonitor): from robocorp_ls_core.jsonrpc.exceptions import JsonRpcRequestCancelled from robotframework_ls.impl.robot_lsp_constants import ( OPTION_ROBOT_LINT_ROBOCOP_ENABLED, ) from robocorp_ls_core import uris from robocorp_ls_core.lsp import Error try: from robotframework_ls.impl.ast_utils import collect_errors from robotframework_ls.impl import code_analysis import os.path log.debug("Lint: starting (in thread).") completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return [] config = completion_context.config robocop_enabled = config is None or config.get_setting( OPTION_ROBOT_LINT_ROBOCOP_ENABLED, bool, False ) ast = completion_context.get_ast() source = completion_context.doc.source monitor.check_cancelled() errors = collect_errors(ast) log.debug("Collected AST errors (in thread): %s", len(errors)) monitor.check_cancelled() analysis_errors = code_analysis.collect_analysis_errors(completion_context) monitor.check_cancelled() log.debug("Collected analysis errors (in thread): %s", len(analysis_errors)) errors.extend(analysis_errors) lsp_diagnostics = [error.to_lsp_diagnostic() for error in errors] try: if robocop_enabled: from robocorp_ls_core.robocop_wrapper import ( collect_robocop_diagnostics, ) workspace = completion_context.workspace if workspace is not None: project_root = workspace.root_path else: project_root = os.path.abspath(".") monitor.check_cancelled() lsp_diagnostics.extend( collect_robocop_diagnostics( project_root, ast, uris.to_fs_path(doc_uri), source ) ) except Exception as e: log.exception( "Error collecting Robocop errors (possibly an unsupported Robocop version is installed)." ) lsp_diagnostics.append( Error( f"Error collecting Robocop errors: {e}", (0, 0), (1, 0) ).to_lsp_diagnostic() ) return lsp_diagnostics except JsonRpcRequestCancelled: raise JsonRpcRequestCancelled("Lint cancelled (inside lint)") except Exception as e: log.exception("Error collecting errors.") ret = [ Error( f"Error collecting Robocop errors: {e}", (0, 0), (1, 0) ).to_lsp_diagnostic() ] return ret def m_complete_all(self, doc_uri, line, col): func = partial(self._threaded_complete_all, doc_uri, line, col) func = require_monitor(func) return func def _threaded_complete_all(self, doc_uri, line, col, monitor: IMonitor): completion_context = self._create_completion_context( doc_uri, line, col, monitor ) if completion_context is None: return [] return self._complete_from_completion_context(completion_context) def _complete_from_completion_context(self, completion_context): from robotframework_ls.impl import section_name_completions from robotframework_ls.impl import keyword_completions from robotframework_ls.impl import variable_completions from robotframework_ls.impl import dictionary_completions from robotframework_ls.impl import filesystem_section_completions from robotframework_ls.impl import keyword_parameter_completions from robotframework_ls.impl import auto_import_completions from robotframework_ls.impl.collect_keywords import ( collect_keyword_name_to_keyword_found, ) from robotframework_ls.impl import ast_utils ret = section_name_completions.complete(completion_context) if not ret: ret.extend(filesystem_section_completions.complete(completion_context)) if not ret: token_info = completion_context.get_current_token() if token_info is not None: token = ast_utils.get_keyword_name_token( token_info.node, token_info.token ) if token is not None: keyword_name_to_keyword_found: Dict[ str, List[IKeywordFound] ] = collect_keyword_name_to_keyword_found(completion_context) ret.extend(keyword_completions.complete(completion_context)) ret.extend( auto_import_completions.complete( completion_context, keyword_name_to_keyword_found ) ) return ret if not ret: ret.extend(variable_completions.complete(completion_context)) if not ret: ret.extend(dictionary_completions.complete(completion_context)) if not ret: ret.extend(keyword_parameter_completions.complete(completion_context)) return ret def m_section_name_complete(self, doc_uri, line, col): from robotframework_ls.impl import section_name_completions completion_context = self._create_completion_context(doc_uri, line, col, None) if completion_context is None: return [] return section_name_completions.complete(completion_context) def m_keyword_complete(self, doc_uri, line, col): from robotframework_ls.impl import keyword_completions completion_context = self._create_completion_context(doc_uri, line, col, None) if completion_context is None: return [] return keyword_completions.complete(completion_context) def m_find_definition(self, doc_uri, line, col): func = partial(self._threaded_find_definition, doc_uri, line, col) func = require_monitor(func) return func def _threaded_find_definition(self, doc_uri, line, col, monitor) -> Optional[list]: from robotframework_ls.impl.find_definition import find_definition import os.path from robocorp_ls_core.lsp import Location, Range from robocorp_ls_core import uris completion_context = self._create_completion_context( doc_uri, line, col, monitor ) if completion_context is None: return None definitions = find_definition(completion_context) ret = [] for definition in definitions: if not definition.source: log.info("Found definition with empty source (%s).", definition) continue if not os.path.exists(definition.source): log.info( "Found definition: %s (but source does not exist).", definition ) continue lineno = definition.lineno if lineno is None or lineno < 0: lineno = 0 end_lineno = definition.end_lineno if end_lineno is None or end_lineno < 0: end_lineno = 0 col_offset = definition.col_offset end_col_offset = definition.end_col_offset ret.append( Location( uris.from_fs_path(definition.source), Range((lineno, col_offset), (end_lineno, end_col_offset)), ).to_dict() ) return ret def m_code_format(self, text_document, options): func = partial(self._threaded_code_format, text_document, options) func = require_monitor(func) return func def _threaded_code_format(self, text_document, options, monitor: IMonitor): from robotframework_ls.impl.formatting import create_text_edit_from_diff from robocorp_ls_core.lsp import TextDocumentItem import os.path from robotframework_ls.impl.robot_lsp_constants import ( OPTION_ROBOT_CODE_FORMATTER, ) from robotframework_ls.impl.robot_lsp_constants import ( OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY, ) from robotframework_ls.impl.robot_lsp_constants import ( OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY, ) text_document_item = TextDocumentItem(**text_document) text = text_document_item.text if not text: completion_context = self._create_completion_context( text_document_item.uri, 0, 0, monitor ) if completion_context is None: return [] text = completion_context.doc.source if not text: return [] if options is None: options = {} tab_size = options.get("tabSize", 4) # Default for now is the builtin. This will probably be changed in the future. formatter = self._config.get_setting( OPTION_ROBOT_CODE_FORMATTER, str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY ) if formatter not in ( OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY, ): log.critical( f"Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}." ) return [] if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY: from robotframework_ls.impl.formatting import robot_source_format new_contents = robot_source_format(text, space_count=tab_size) else: if not self._check_min_version((4, 0)): log.critical( f"To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}" ) return [] from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format ast = completion_context.get_ast() path = completion_context.doc.path dirname = "." try: os.stat(path) except: # It doesn't exist ws = self._workspace if ws is not None: dirname = ws.root_path else: dirname = os.path.dirname(path) new_contents = robot_tidy_source_format(ast, dirname) if new_contents is None or new_contents == text: return [] return [x.to_dict() for x in create_text_edit_from_diff(text, new_contents)] def _create_completion_context( self, doc_uri, line, col, monitor: Optional[IMonitor] ): from robotframework_ls.impl.completion_context import CompletionContext if not self._check_min_version((3, 2)): log.info("robotframework version too old.") return None workspace = self.workspace if not workspace: log.info("Workspace still not initialized.") return None document = workspace.get_document(doc_uri, accept_from_file=True) if document is None: log.info("Unable to get document for uri: %s.", doc_uri) return None return CompletionContext( document, line, col, workspace=workspace, config=self.config, monitor=monitor, ) def m_signature_help(self, doc_uri: str, line: int, col: int): func = partial(self._threaded_signature_help, doc_uri, line, col) func = require_monitor(func) return func def _threaded_signature_help( self, doc_uri: str, line: int, col: int, monitor: IMonitor ) -> Optional[dict]: from robotframework_ls.impl.signature_help import signature_help completion_context = self._create_completion_context( doc_uri, line, col, monitor ) if completion_context is None: return None return signature_help(completion_context) def m_folding_range(self, doc_uri: str): func = partial(self._threaded_folding_range, doc_uri) func = require_monitor(func) return func def _threaded_folding_range( self, doc_uri: str, monitor: IMonitor ) -> List[FoldingRangeTypedDict]: from robotframework_ls.impl.folding_range import folding_range completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return [] return folding_range(completion_context) def m_code_lens(self, doc_uri: str): func = partial(self._threaded_code_lens, doc_uri) func = require_monitor(func) return func def _threaded_code_lens( self, doc_uri: str, monitor: IMonitor ) -> List[CodeLensTypedDict]: from robotframework_ls.impl.code_lens import code_lens completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return [] return code_lens(completion_context) def m_resolve_code_lens(self, **code_lens: CodeLensTypedDict): func = partial(self._threaded_resolve_code_lens, code_lens) func = require_monitor(func) return func def _threaded_resolve_code_lens( self, code_lens: CodeLensTypedDict, monitor: IMonitor ) -> CodeLensTypedDict: from robotframework_ls.impl.code_lens import code_lens_resolve data = code_lens.get("data") if not isinstance(data, dict): return code_lens doc_uri = data.get("uri") completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return code_lens return code_lens_resolve(completion_context, code_lens) def m_document_symbol(self, doc_uri: str): func = partial(self._threaded_document_symbol, doc_uri) func = require_monitor(func) return func def _threaded_document_symbol( self, doc_uri: str, monitor: IMonitor ) -> List[DocumentSymbolTypedDict]: from robotframework_ls.impl.document_symbol import document_symbol completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return [] return document_symbol(completion_context) def m_list_tests(self, doc_uri: str): func = partial(self._threaded_list_tests, doc_uri) func = require_monitor(func) return func def _threaded_list_tests( self, doc_uri: str, monitor: IMonitor ) -> List[ITestInfoTypedDict]: from robotframework_ls.impl.code_lens import list_tests completion_context = self._create_completion_context(doc_uri, 0, 0, monitor) if completion_context is None: return [] return list_tests(completion_context) def m_hover(self, doc_uri: str, line: int, col: int): func = partial(self._threaded_hover, doc_uri, line, col) func = require_monitor(func) return func def _threaded_hover( self, doc_uri: str, line, col, monitor: IMonitor ) -> Optional[HoverTypedDict]: from robotframework_ls.impl.hover import hover completion_context = self._create_completion_context( doc_uri, line, col, monitor ) if completion_context is None: return None return hover(completion_context) def m_workspace_symbols(self, query: Optional[str] = None): func = partial(self._threaded_workspace_symbols, query) func = require_monitor(func) return func def _threaded_workspace_symbols( self, query: Optional[str], monitor: IMonitor ) -> Optional[List[SymbolInformationTypedDict]]: from robotframework_ls.impl.workspace_symbols import workspace_symbols from robotframework_ls.impl.completion_context import BaseContext from robotframework_ls.impl.protocols import IRobotWorkspace from typing import cast workspace = self._workspace if not workspace: return [] robot_workspace = cast(IRobotWorkspace, workspace) return workspace_symbols( query, BaseContext(workspace=robot_workspace, config=self.config, monitor=monitor), ) def m_text_document__semantic_tokens__range(self, textDocument=None, range=None): raise RuntimeError("Not currently implemented!") def m_text_document__semantic_tokens__full(self, textDocument=None): func = partial(self.threaded_semantic_tokens_full, textDocument=textDocument) func = require_monitor(func) return func def threaded_semantic_tokens_full( self, textDocument: TextDocumentTypedDict, monitor: Optional[IMonitor] = None ): from robotframework_ls.impl.semantic_tokens import semantic_tokens_full doc_uri = textDocument["uri"] context = self._create_completion_context(doc_uri, -1, -1, monitor) if context is None: return {"resultId": None, "data": []} return {"resultId": None, "data": semantic_tokens_full(context)} def m_monaco_completions_from_code_full( self, prefix: str = "", full_code: str = "", position=PositionTypedDict, uri: str = "", indent: str = "", ): func = partial( self.threaded_monaco_completions_from_code_full, prefix=prefix, full_code=full_code, position=position, uri=uri, indent=indent, ) func = require_monitor(func) return func def threaded_monaco_completions_from_code_full( self, prefix: str, full_code: str, position: PositionTypedDict, uri: str, indent: str, monitor: Optional[IMonitor] = None, ): from robotframework_ls.impl.robot_workspace import RobotDocument from robotframework_ls.impl.completion_context import CompletionContext from robocorp_ls_core.workspace import Document from robotframework_ls.impl import section_completions from robotframework_ls.impl import snippets_completions from robotframework_ls.server_api.monaco_conversions import ( convert_to_monaco_completion, ) from robotframework_ls.impl.completion_context import CompletionType d = Document(uri, prefix) last_line, _last_col = d.get_last_line_col() line = last_line + position["line"] col = position["character"] col += len(indent) document = RobotDocument(uri, full_code) completion_context = CompletionContext( document, line, col, config=self.config, monitor=monitor, workspace=self.workspace, ) completion_context.type = CompletionType.shell completions = self._complete_from_completion_context(completion_context) completions.extend(section_completions.complete(completion_context)) completions.extend(snippets_completions.complete(completion_context)) return { "suggestions": [ convert_to_monaco_completion( c, line_delta=last_line, col_delta=len(indent), uri=uri ) for c in completions ] } def m_semantic_tokens_from_code_full( self, prefix: str = "", full_code: str = "", indent: str = "" ): func = partial( self.threaded_semantic_tokens_from_code_full, prefix=prefix, full_code=full_code, indent=indent, ) func = require_monitor(func) return func def threaded_semantic_tokens_from_code_full( self, prefix: str, full_code: str, indent: str, monitor: Optional[IMonitor] = None, ): from robotframework_ls.impl.semantic_tokens import semantic_tokens_full_from_ast try: from robotframework_ls.impl.robot_workspace import RobotDocument doc = RobotDocument("") doc.source = full_code ast = doc.get_ast() data = semantic_tokens_full_from_ast(ast, monitor) if not prefix: return {"resultId": None, "data": data} # We have to exclude the prefix from the coloring... # debug info... # import io # from robotframework_ls.impl.semantic_tokens import decode_semantic_tokens # stream = io.StringIO() # decode_semantic_tokens(data, doc, stream) # found = stream.getvalue() prefix_doc = RobotDocument("") prefix_doc.source = prefix last_line, last_col = prefix_doc.get_last_line_col() # Now we have the data from the full code, but we need to remove whatever # we have in the prefix from the result... ints_iter = iter(data) line = 0 col = 0 new_data = [] indent_len = len(indent) while True: try: line_delta = next(ints_iter) except StopIteration: break col_delta = next(ints_iter) token_len = next(ints_iter) token_type = next(ints_iter) token_modifier = next(ints_iter) line += line_delta if line_delta == 0: col += col_delta else: col = col_delta if line >= last_line: new_data.append(line - last_line) new_data.append(col_delta - indent_len) new_data.append(token_len) new_data.append(token_type) new_data.append(token_modifier) # Ok, now, we have to add the indent_len to all the # next lines while True: try: line_delta = next(ints_iter) except StopIteration: break col_delta = next(ints_iter) token_len = next(ints_iter) token_type = next(ints_iter) token_modifier = next(ints_iter) new_data.append(line_delta) if line_delta > 0: new_data.append(col_delta - indent_len) else: new_data.append(col_delta) new_data.append(token_len) new_data.append(token_type) new_data.append(token_modifier) break # Approach changed so that we always have a new line # i.e.: # \n<indent><code> # # so, the condition below no longer applies. # elif line == last_line and col >= last_col: # new_data.append(0) # new_data.append(col - last_col) # new_data.append(token_len) # new_data.append(token_type) # new_data.append(token_modifier) # new_data.extend(ints_iter) # break # debug info... # temp_stream = io.StringIO() # temp_doc = RobotDocument("") # temp_doc.source = full_code[len(prefix) :] # decode_semantic_tokens(new_data, temp_doc, temp_stream) # temp_found = temp_stream.getvalue() return {"resultId": None, "data": new_data} except: log.exception("Error computing semantic tokens from code.") return {"resultId": None, "data": []} def m_shutdown(self, **_kwargs): PythonLanguageServer.m_shutdown(self, **_kwargs) self.libspec_manager.dispose() def m_exit(self, **_kwargs): PythonLanguageServer.m_exit(self, **_kwargs) self.libspec_manager.dispose()
normal
{ "blob_id": "18b43ea8696e2e54f4c1cbbece4cde1fd3130145", "index": 194, "step-1": "<mask token>\n\n\nclass RobotFrameworkServerApi(PythonLanguageServer):\n <mask token>\n\n def __init__(self, read_from, write_to, libspec_manager=None, observer:\n Optional[IFSObserver]=None):\n from robotframework_ls.impl.libspec_manager import LibspecManager\n if libspec_manager is None:\n try:\n libspec_manager = LibspecManager(observer=observer)\n except:\n log.exception(\n 'Unable to properly initialize the LibspecManager.')\n raise\n self.libspec_manager = libspec_manager\n PythonLanguageServer.__init__(self, read_from, write_to)\n self._version = None\n self._next_time = partial(next, itertools.count(0))\n <mask token>\n <mask token>\n\n def _check_min_version(self, min_version):\n from robocorp_ls_core.basic import check_min_version\n version = self.m_version()\n return check_min_version(version, min_version)\n\n @overrides(PythonLanguageServer.m_workspace__did_change_configuration)\n def m_workspace__did_change_configuration(self, **kwargs):\n PythonLanguageServer.m_workspace__did_change_configuration(self, **\n kwargs)\n self.libspec_manager.config = self.config\n\n @overrides(PythonLanguageServer.lint)\n def lint(self, *args, **kwargs):\n pass\n <mask token>\n <mask token>\n\n @overrides(PythonLanguageServer._create_workspace)\n def _create_workspace(self, root_uri: str, fs_observer: IFSObserver,\n workspace_folders) ->IWorkspace:\n from robotframework_ls.impl.robot_workspace import RobotWorkspace\n return RobotWorkspace(root_uri, fs_observer, workspace_folders,\n libspec_manager=self.libspec_manager)\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _complete_from_completion_context(self, completion_context):\n from robotframework_ls.impl import section_name_completions\n from robotframework_ls.impl import keyword_completions\n from robotframework_ls.impl import variable_completions\n from robotframework_ls.impl import dictionary_completions\n from robotframework_ls.impl import filesystem_section_completions\n from robotframework_ls.impl import keyword_parameter_completions\n from robotframework_ls.impl import auto_import_completions\n from robotframework_ls.impl.collect_keywords import collect_keyword_name_to_keyword_found\n from robotframework_ls.impl import ast_utils\n ret = section_name_completions.complete(completion_context)\n if not ret:\n ret.extend(filesystem_section_completions.complete(\n completion_context))\n if not ret:\n token_info = completion_context.get_current_token()\n if token_info is not None:\n token = ast_utils.get_keyword_name_token(token_info.node,\n token_info.token)\n if token is not None:\n keyword_name_to_keyword_found: Dict[str, List[\n IKeywordFound]\n ] = collect_keyword_name_to_keyword_found(\n completion_context)\n ret.extend(keyword_completions.complete(completion_context)\n )\n ret.extend(auto_import_completions.complete(\n completion_context, keyword_name_to_keyword_found))\n return ret\n if not ret:\n ret.extend(variable_completions.complete(completion_context))\n if not ret:\n ret.extend(dictionary_completions.complete(completion_context))\n if not ret:\n ret.extend(keyword_parameter_completions.complete(\n completion_context))\n return ret\n <mask token>\n <mask token>\n\n def m_find_definition(self, doc_uri, line, col):\n func = partial(self._threaded_find_definition, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_find_definition(self, doc_uri, line, col, monitor\n ) ->Optional[list]:\n from robotframework_ls.impl.find_definition import find_definition\n import os.path\n from robocorp_ls_core.lsp import Location, Range\n from robocorp_ls_core import uris\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n definitions = find_definition(completion_context)\n ret = []\n for definition in definitions:\n if not definition.source:\n log.info('Found definition with empty source (%s).', definition\n )\n continue\n if not os.path.exists(definition.source):\n log.info('Found definition: %s (but source does not exist).',\n definition)\n continue\n lineno = definition.lineno\n if lineno is None or lineno < 0:\n lineno = 0\n end_lineno = definition.end_lineno\n if end_lineno is None or end_lineno < 0:\n end_lineno = 0\n col_offset = definition.col_offset\n end_col_offset = definition.end_col_offset\n ret.append(Location(uris.from_fs_path(definition.source), Range\n ((lineno, col_offset), (end_lineno, end_col_offset))).to_dict()\n )\n return ret\n <mask token>\n\n def _threaded_code_format(self, text_document, options, monitor: IMonitor):\n from robotframework_ls.impl.formatting import create_text_edit_from_diff\n from robocorp_ls_core.lsp import TextDocumentItem\n import os.path\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY\n text_document_item = TextDocumentItem(**text_document)\n text = text_document_item.text\n if not text:\n completion_context = self._create_completion_context(\n text_document_item.uri, 0, 0, monitor)\n if completion_context is None:\n return []\n text = completion_context.doc.source\n if not text:\n return []\n if options is None:\n options = {}\n tab_size = options.get('tabSize', 4)\n formatter = self._config.get_setting(OPTION_ROBOT_CODE_FORMATTER,\n str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY)\n if formatter not in (OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY):\n log.critical(\n f'Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}.'\n )\n return []\n if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY:\n from robotframework_ls.impl.formatting import robot_source_format\n new_contents = robot_source_format(text, space_count=tab_size)\n else:\n if not self._check_min_version((4, 0)):\n log.critical(\n f'To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}'\n )\n return []\n from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format\n ast = completion_context.get_ast()\n path = completion_context.doc.path\n dirname = '.'\n try:\n os.stat(path)\n except:\n ws = self._workspace\n if ws is not None:\n dirname = ws.root_path\n else:\n dirname = os.path.dirname(path)\n new_contents = robot_tidy_source_format(ast, dirname)\n if new_contents is None or new_contents == text:\n return []\n return [x.to_dict() for x in create_text_edit_from_diff(text,\n new_contents)]\n <mask token>\n <mask token>\n <mask token>\n\n def m_folding_range(self, doc_uri: str):\n func = partial(self._threaded_folding_range, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_folding_range(self, doc_uri: str, monitor: IMonitor) ->List[\n FoldingRangeTypedDict]:\n from robotframework_ls.impl.folding_range import folding_range\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return folding_range(completion_context)\n <mask token>\n\n def _threaded_code_lens(self, doc_uri: str, monitor: IMonitor) ->List[\n CodeLensTypedDict]:\n from robotframework_ls.impl.code_lens import code_lens\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return code_lens(completion_context)\n <mask token>\n <mask token>\n <mask token>\n\n def _threaded_document_symbol(self, doc_uri: str, monitor: IMonitor\n ) ->List[DocumentSymbolTypedDict]:\n from robotframework_ls.impl.document_symbol import document_symbol\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return document_symbol(completion_context)\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def m_workspace_symbols(self, query: Optional[str]=None):\n func = partial(self._threaded_workspace_symbols, query)\n func = require_monitor(func)\n return func\n\n def _threaded_workspace_symbols(self, query: Optional[str], monitor:\n IMonitor) ->Optional[List[SymbolInformationTypedDict]]:\n from robotframework_ls.impl.workspace_symbols import workspace_symbols\n from robotframework_ls.impl.completion_context import BaseContext\n from robotframework_ls.impl.protocols import IRobotWorkspace\n from typing import cast\n workspace = self._workspace\n if not workspace:\n return []\n robot_workspace = cast(IRobotWorkspace, workspace)\n return workspace_symbols(query, BaseContext(workspace=\n robot_workspace, config=self.config, monitor=monitor))\n <mask token>\n <mask token>\n\n def threaded_semantic_tokens_full(self, textDocument:\n TextDocumentTypedDict, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full\n doc_uri = textDocument['uri']\n context = self._create_completion_context(doc_uri, -1, -1, monitor)\n if context is None:\n return {'resultId': None, 'data': []}\n return {'resultId': None, 'data': semantic_tokens_full(context)}\n\n def m_monaco_completions_from_code_full(self, prefix: str='', full_code:\n str='', position=PositionTypedDict, uri: str='', indent: str=''):\n func = partial(self.threaded_monaco_completions_from_code_full,\n prefix=prefix, full_code=full_code, position=position, uri=uri,\n indent=indent)\n func = require_monitor(func)\n return func\n\n def threaded_monaco_completions_from_code_full(self, prefix: str,\n full_code: str, position: PositionTypedDict, uri: str, indent: str,\n monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.robot_workspace import RobotDocument\n from robotframework_ls.impl.completion_context import CompletionContext\n from robocorp_ls_core.workspace import Document\n from robotframework_ls.impl import section_completions\n from robotframework_ls.impl import snippets_completions\n from robotframework_ls.server_api.monaco_conversions import convert_to_monaco_completion\n from robotframework_ls.impl.completion_context import CompletionType\n d = Document(uri, prefix)\n last_line, _last_col = d.get_last_line_col()\n line = last_line + position['line']\n col = position['character']\n col += len(indent)\n document = RobotDocument(uri, full_code)\n completion_context = CompletionContext(document, line, col, config=\n self.config, monitor=monitor, workspace=self.workspace)\n completion_context.type = CompletionType.shell\n completions = self._complete_from_completion_context(completion_context\n )\n completions.extend(section_completions.complete(completion_context))\n completions.extend(snippets_completions.complete(completion_context))\n return {'suggestions': [convert_to_monaco_completion(c, line_delta=\n last_line, col_delta=len(indent), uri=uri) for c in completions]}\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass RobotFrameworkServerApi(PythonLanguageServer):\n <mask token>\n\n def __init__(self, read_from, write_to, libspec_manager=None, observer:\n Optional[IFSObserver]=None):\n from robotframework_ls.impl.libspec_manager import LibspecManager\n if libspec_manager is None:\n try:\n libspec_manager = LibspecManager(observer=observer)\n except:\n log.exception(\n 'Unable to properly initialize the LibspecManager.')\n raise\n self.libspec_manager = libspec_manager\n PythonLanguageServer.__init__(self, read_from, write_to)\n self._version = None\n self._next_time = partial(next, itertools.count(0))\n <mask token>\n <mask token>\n\n def _check_min_version(self, min_version):\n from robocorp_ls_core.basic import check_min_version\n version = self.m_version()\n return check_min_version(version, min_version)\n\n @overrides(PythonLanguageServer.m_workspace__did_change_configuration)\n def m_workspace__did_change_configuration(self, **kwargs):\n PythonLanguageServer.m_workspace__did_change_configuration(self, **\n kwargs)\n self.libspec_manager.config = self.config\n\n @overrides(PythonLanguageServer.lint)\n def lint(self, *args, **kwargs):\n pass\n\n @overrides(PythonLanguageServer.cancel_lint)\n def cancel_lint(self, *args, **kwargs):\n pass\n <mask token>\n\n @overrides(PythonLanguageServer._create_workspace)\n def _create_workspace(self, root_uri: str, fs_observer: IFSObserver,\n workspace_folders) ->IWorkspace:\n from robotframework_ls.impl.robot_workspace import RobotWorkspace\n return RobotWorkspace(root_uri, fs_observer, workspace_folders,\n libspec_manager=self.libspec_manager)\n\n def m_lint(self, doc_uri):\n if not self._check_min_version((3, 2)):\n from robocorp_ls_core.lsp import Error\n msg = (\n \"\"\"robotframework version (%s) too old for linting.\nPlease install a newer version and restart the language server.\"\"\"\n % (self.m_version(),))\n log.info(msg)\n return [Error(msg, (0, 0), (1, 0)).to_lsp_diagnostic()]\n func = partial(self._threaded_lint, doc_uri)\n func = require_monitor(func)\n return func\n <mask token>\n\n def m_complete_all(self, doc_uri, line, col):\n func = partial(self._threaded_complete_all, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_complete_all(self, doc_uri, line, col, monitor: IMonitor):\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return []\n return self._complete_from_completion_context(completion_context)\n\n def _complete_from_completion_context(self, completion_context):\n from robotframework_ls.impl import section_name_completions\n from robotframework_ls.impl import keyword_completions\n from robotframework_ls.impl import variable_completions\n from robotframework_ls.impl import dictionary_completions\n from robotframework_ls.impl import filesystem_section_completions\n from robotframework_ls.impl import keyword_parameter_completions\n from robotframework_ls.impl import auto_import_completions\n from robotframework_ls.impl.collect_keywords import collect_keyword_name_to_keyword_found\n from robotframework_ls.impl import ast_utils\n ret = section_name_completions.complete(completion_context)\n if not ret:\n ret.extend(filesystem_section_completions.complete(\n completion_context))\n if not ret:\n token_info = completion_context.get_current_token()\n if token_info is not None:\n token = ast_utils.get_keyword_name_token(token_info.node,\n token_info.token)\n if token is not None:\n keyword_name_to_keyword_found: Dict[str, List[\n IKeywordFound]\n ] = collect_keyword_name_to_keyword_found(\n completion_context)\n ret.extend(keyword_completions.complete(completion_context)\n )\n ret.extend(auto_import_completions.complete(\n completion_context, keyword_name_to_keyword_found))\n return ret\n if not ret:\n ret.extend(variable_completions.complete(completion_context))\n if not ret:\n ret.extend(dictionary_completions.complete(completion_context))\n if not ret:\n ret.extend(keyword_parameter_completions.complete(\n completion_context))\n return ret\n\n def m_section_name_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import section_name_completions\n completion_context = self._create_completion_context(doc_uri, line,\n col, None)\n if completion_context is None:\n return []\n return section_name_completions.complete(completion_context)\n <mask token>\n\n def m_find_definition(self, doc_uri, line, col):\n func = partial(self._threaded_find_definition, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_find_definition(self, doc_uri, line, col, monitor\n ) ->Optional[list]:\n from robotframework_ls.impl.find_definition import find_definition\n import os.path\n from robocorp_ls_core.lsp import Location, Range\n from robocorp_ls_core import uris\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n definitions = find_definition(completion_context)\n ret = []\n for definition in definitions:\n if not definition.source:\n log.info('Found definition with empty source (%s).', definition\n )\n continue\n if not os.path.exists(definition.source):\n log.info('Found definition: %s (but source does not exist).',\n definition)\n continue\n lineno = definition.lineno\n if lineno is None or lineno < 0:\n lineno = 0\n end_lineno = definition.end_lineno\n if end_lineno is None or end_lineno < 0:\n end_lineno = 0\n col_offset = definition.col_offset\n end_col_offset = definition.end_col_offset\n ret.append(Location(uris.from_fs_path(definition.source), Range\n ((lineno, col_offset), (end_lineno, end_col_offset))).to_dict()\n )\n return ret\n <mask token>\n\n def _threaded_code_format(self, text_document, options, monitor: IMonitor):\n from robotframework_ls.impl.formatting import create_text_edit_from_diff\n from robocorp_ls_core.lsp import TextDocumentItem\n import os.path\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY\n text_document_item = TextDocumentItem(**text_document)\n text = text_document_item.text\n if not text:\n completion_context = self._create_completion_context(\n text_document_item.uri, 0, 0, monitor)\n if completion_context is None:\n return []\n text = completion_context.doc.source\n if not text:\n return []\n if options is None:\n options = {}\n tab_size = options.get('tabSize', 4)\n formatter = self._config.get_setting(OPTION_ROBOT_CODE_FORMATTER,\n str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY)\n if formatter not in (OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY):\n log.critical(\n f'Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}.'\n )\n return []\n if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY:\n from robotframework_ls.impl.formatting import robot_source_format\n new_contents = robot_source_format(text, space_count=tab_size)\n else:\n if not self._check_min_version((4, 0)):\n log.critical(\n f'To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}'\n )\n return []\n from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format\n ast = completion_context.get_ast()\n path = completion_context.doc.path\n dirname = '.'\n try:\n os.stat(path)\n except:\n ws = self._workspace\n if ws is not None:\n dirname = ws.root_path\n else:\n dirname = os.path.dirname(path)\n new_contents = robot_tidy_source_format(ast, dirname)\n if new_contents is None or new_contents == text:\n return []\n return [x.to_dict() for x in create_text_edit_from_diff(text,\n new_contents)]\n <mask token>\n <mask token>\n\n def _threaded_signature_help(self, doc_uri: str, line: int, col: int,\n monitor: IMonitor) ->Optional[dict]:\n from robotframework_ls.impl.signature_help import signature_help\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return signature_help(completion_context)\n\n def m_folding_range(self, doc_uri: str):\n func = partial(self._threaded_folding_range, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_folding_range(self, doc_uri: str, monitor: IMonitor) ->List[\n FoldingRangeTypedDict]:\n from robotframework_ls.impl.folding_range import folding_range\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return folding_range(completion_context)\n\n def m_code_lens(self, doc_uri: str):\n func = partial(self._threaded_code_lens, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_code_lens(self, doc_uri: str, monitor: IMonitor) ->List[\n CodeLensTypedDict]:\n from robotframework_ls.impl.code_lens import code_lens\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return code_lens(completion_context)\n\n def m_resolve_code_lens(self, **code_lens: CodeLensTypedDict):\n func = partial(self._threaded_resolve_code_lens, code_lens)\n func = require_monitor(func)\n return func\n <mask token>\n\n def m_document_symbol(self, doc_uri: str):\n func = partial(self._threaded_document_symbol, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_document_symbol(self, doc_uri: str, monitor: IMonitor\n ) ->List[DocumentSymbolTypedDict]:\n from robotframework_ls.impl.document_symbol import document_symbol\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return document_symbol(completion_context)\n <mask token>\n\n def _threaded_list_tests(self, doc_uri: str, monitor: IMonitor) ->List[\n ITestInfoTypedDict]:\n from robotframework_ls.impl.code_lens import list_tests\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return list_tests(completion_context)\n <mask token>\n\n def _threaded_hover(self, doc_uri: str, line, col, monitor: IMonitor\n ) ->Optional[HoverTypedDict]:\n from robotframework_ls.impl.hover import hover\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return hover(completion_context)\n\n def m_workspace_symbols(self, query: Optional[str]=None):\n func = partial(self._threaded_workspace_symbols, query)\n func = require_monitor(func)\n return func\n\n def _threaded_workspace_symbols(self, query: Optional[str], monitor:\n IMonitor) ->Optional[List[SymbolInformationTypedDict]]:\n from robotframework_ls.impl.workspace_symbols import workspace_symbols\n from robotframework_ls.impl.completion_context import BaseContext\n from robotframework_ls.impl.protocols import IRobotWorkspace\n from typing import cast\n workspace = self._workspace\n if not workspace:\n return []\n robot_workspace = cast(IRobotWorkspace, workspace)\n return workspace_symbols(query, BaseContext(workspace=\n robot_workspace, config=self.config, monitor=monitor))\n <mask token>\n\n def m_text_document__semantic_tokens__full(self, textDocument=None):\n func = partial(self.threaded_semantic_tokens_full, textDocument=\n textDocument)\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_full(self, textDocument:\n TextDocumentTypedDict, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full\n doc_uri = textDocument['uri']\n context = self._create_completion_context(doc_uri, -1, -1, monitor)\n if context is None:\n return {'resultId': None, 'data': []}\n return {'resultId': None, 'data': semantic_tokens_full(context)}\n\n def m_monaco_completions_from_code_full(self, prefix: str='', full_code:\n str='', position=PositionTypedDict, uri: str='', indent: str=''):\n func = partial(self.threaded_monaco_completions_from_code_full,\n prefix=prefix, full_code=full_code, position=position, uri=uri,\n indent=indent)\n func = require_monitor(func)\n return func\n\n def threaded_monaco_completions_from_code_full(self, prefix: str,\n full_code: str, position: PositionTypedDict, uri: str, indent: str,\n monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.robot_workspace import RobotDocument\n from robotframework_ls.impl.completion_context import CompletionContext\n from robocorp_ls_core.workspace import Document\n from robotframework_ls.impl import section_completions\n from robotframework_ls.impl import snippets_completions\n from robotframework_ls.server_api.monaco_conversions import convert_to_monaco_completion\n from robotframework_ls.impl.completion_context import CompletionType\n d = Document(uri, prefix)\n last_line, _last_col = d.get_last_line_col()\n line = last_line + position['line']\n col = position['character']\n col += len(indent)\n document = RobotDocument(uri, full_code)\n completion_context = CompletionContext(document, line, col, config=\n self.config, monitor=monitor, workspace=self.workspace)\n completion_context.type = CompletionType.shell\n completions = self._complete_from_completion_context(completion_context\n )\n completions.extend(section_completions.complete(completion_context))\n completions.extend(snippets_completions.complete(completion_context))\n return {'suggestions': [convert_to_monaco_completion(c, line_delta=\n last_line, col_delta=len(indent), uri=uri) for c in completions]}\n <mask token>\n\n def threaded_semantic_tokens_from_code_full(self, prefix: str,\n full_code: str, indent: str, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full_from_ast\n try:\n from robotframework_ls.impl.robot_workspace import RobotDocument\n doc = RobotDocument('')\n doc.source = full_code\n ast = doc.get_ast()\n data = semantic_tokens_full_from_ast(ast, monitor)\n if not prefix:\n return {'resultId': None, 'data': data}\n prefix_doc = RobotDocument('')\n prefix_doc.source = prefix\n last_line, last_col = prefix_doc.get_last_line_col()\n ints_iter = iter(data)\n line = 0\n col = 0\n new_data = []\n indent_len = len(indent)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n line += line_delta\n if line_delta == 0:\n col += col_delta\n else:\n col = col_delta\n if line >= last_line:\n new_data.append(line - last_line)\n new_data.append(col_delta - indent_len)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n new_data.append(line_delta)\n if line_delta > 0:\n new_data.append(col_delta - indent_len)\n else:\n new_data.append(col_delta)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n break\n return {'resultId': None, 'data': new_data}\n except:\n log.exception('Error computing semantic tokens from code.')\n return {'resultId': None, 'data': []}\n <mask token>\n\n def m_exit(self, **_kwargs):\n PythonLanguageServer.m_exit(self, **_kwargs)\n self.libspec_manager.dispose()\n", "step-3": "<mask token>\n\n\nclass RobotFrameworkServerApi(PythonLanguageServer):\n <mask token>\n\n def __init__(self, read_from, write_to, libspec_manager=None, observer:\n Optional[IFSObserver]=None):\n from robotframework_ls.impl.libspec_manager import LibspecManager\n if libspec_manager is None:\n try:\n libspec_manager = LibspecManager(observer=observer)\n except:\n log.exception(\n 'Unable to properly initialize the LibspecManager.')\n raise\n self.libspec_manager = libspec_manager\n PythonLanguageServer.__init__(self, read_from, write_to)\n self._version = None\n self._next_time = partial(next, itertools.count(0))\n <mask token>\n <mask token>\n\n def _check_min_version(self, min_version):\n from robocorp_ls_core.basic import check_min_version\n version = self.m_version()\n return check_min_version(version, min_version)\n\n @overrides(PythonLanguageServer.m_workspace__did_change_configuration)\n def m_workspace__did_change_configuration(self, **kwargs):\n PythonLanguageServer.m_workspace__did_change_configuration(self, **\n kwargs)\n self.libspec_manager.config = self.config\n\n @overrides(PythonLanguageServer.lint)\n def lint(self, *args, **kwargs):\n pass\n\n @overrides(PythonLanguageServer.cancel_lint)\n def cancel_lint(self, *args, **kwargs):\n pass\n <mask token>\n\n @overrides(PythonLanguageServer._create_workspace)\n def _create_workspace(self, root_uri: str, fs_observer: IFSObserver,\n workspace_folders) ->IWorkspace:\n from robotframework_ls.impl.robot_workspace import RobotWorkspace\n return RobotWorkspace(root_uri, fs_observer, workspace_folders,\n libspec_manager=self.libspec_manager)\n\n def m_lint(self, doc_uri):\n if not self._check_min_version((3, 2)):\n from robocorp_ls_core.lsp import Error\n msg = (\n \"\"\"robotframework version (%s) too old for linting.\nPlease install a newer version and restart the language server.\"\"\"\n % (self.m_version(),))\n log.info(msg)\n return [Error(msg, (0, 0), (1, 0)).to_lsp_diagnostic()]\n func = partial(self._threaded_lint, doc_uri)\n func = require_monitor(func)\n return func\n <mask token>\n\n def m_complete_all(self, doc_uri, line, col):\n func = partial(self._threaded_complete_all, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_complete_all(self, doc_uri, line, col, monitor: IMonitor):\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return []\n return self._complete_from_completion_context(completion_context)\n\n def _complete_from_completion_context(self, completion_context):\n from robotframework_ls.impl import section_name_completions\n from robotframework_ls.impl import keyword_completions\n from robotframework_ls.impl import variable_completions\n from robotframework_ls.impl import dictionary_completions\n from robotframework_ls.impl import filesystem_section_completions\n from robotframework_ls.impl import keyword_parameter_completions\n from robotframework_ls.impl import auto_import_completions\n from robotframework_ls.impl.collect_keywords import collect_keyword_name_to_keyword_found\n from robotframework_ls.impl import ast_utils\n ret = section_name_completions.complete(completion_context)\n if not ret:\n ret.extend(filesystem_section_completions.complete(\n completion_context))\n if not ret:\n token_info = completion_context.get_current_token()\n if token_info is not None:\n token = ast_utils.get_keyword_name_token(token_info.node,\n token_info.token)\n if token is not None:\n keyword_name_to_keyword_found: Dict[str, List[\n IKeywordFound]\n ] = collect_keyword_name_to_keyword_found(\n completion_context)\n ret.extend(keyword_completions.complete(completion_context)\n )\n ret.extend(auto_import_completions.complete(\n completion_context, keyword_name_to_keyword_found))\n return ret\n if not ret:\n ret.extend(variable_completions.complete(completion_context))\n if not ret:\n ret.extend(dictionary_completions.complete(completion_context))\n if not ret:\n ret.extend(keyword_parameter_completions.complete(\n completion_context))\n return ret\n\n def m_section_name_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import section_name_completions\n completion_context = self._create_completion_context(doc_uri, line,\n col, None)\n if completion_context is None:\n return []\n return section_name_completions.complete(completion_context)\n <mask token>\n\n def m_find_definition(self, doc_uri, line, col):\n func = partial(self._threaded_find_definition, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_find_definition(self, doc_uri, line, col, monitor\n ) ->Optional[list]:\n from robotframework_ls.impl.find_definition import find_definition\n import os.path\n from robocorp_ls_core.lsp import Location, Range\n from robocorp_ls_core import uris\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n definitions = find_definition(completion_context)\n ret = []\n for definition in definitions:\n if not definition.source:\n log.info('Found definition with empty source (%s).', definition\n )\n continue\n if not os.path.exists(definition.source):\n log.info('Found definition: %s (but source does not exist).',\n definition)\n continue\n lineno = definition.lineno\n if lineno is None or lineno < 0:\n lineno = 0\n end_lineno = definition.end_lineno\n if end_lineno is None or end_lineno < 0:\n end_lineno = 0\n col_offset = definition.col_offset\n end_col_offset = definition.end_col_offset\n ret.append(Location(uris.from_fs_path(definition.source), Range\n ((lineno, col_offset), (end_lineno, end_col_offset))).to_dict()\n )\n return ret\n <mask token>\n\n def _threaded_code_format(self, text_document, options, monitor: IMonitor):\n from robotframework_ls.impl.formatting import create_text_edit_from_diff\n from robocorp_ls_core.lsp import TextDocumentItem\n import os.path\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY\n text_document_item = TextDocumentItem(**text_document)\n text = text_document_item.text\n if not text:\n completion_context = self._create_completion_context(\n text_document_item.uri, 0, 0, monitor)\n if completion_context is None:\n return []\n text = completion_context.doc.source\n if not text:\n return []\n if options is None:\n options = {}\n tab_size = options.get('tabSize', 4)\n formatter = self._config.get_setting(OPTION_ROBOT_CODE_FORMATTER,\n str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY)\n if formatter not in (OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY):\n log.critical(\n f'Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}.'\n )\n return []\n if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY:\n from robotframework_ls.impl.formatting import robot_source_format\n new_contents = robot_source_format(text, space_count=tab_size)\n else:\n if not self._check_min_version((4, 0)):\n log.critical(\n f'To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}'\n )\n return []\n from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format\n ast = completion_context.get_ast()\n path = completion_context.doc.path\n dirname = '.'\n try:\n os.stat(path)\n except:\n ws = self._workspace\n if ws is not None:\n dirname = ws.root_path\n else:\n dirname = os.path.dirname(path)\n new_contents = robot_tidy_source_format(ast, dirname)\n if new_contents is None or new_contents == text:\n return []\n return [x.to_dict() for x in create_text_edit_from_diff(text,\n new_contents)]\n <mask token>\n <mask token>\n\n def _threaded_signature_help(self, doc_uri: str, line: int, col: int,\n monitor: IMonitor) ->Optional[dict]:\n from robotframework_ls.impl.signature_help import signature_help\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return signature_help(completion_context)\n\n def m_folding_range(self, doc_uri: str):\n func = partial(self._threaded_folding_range, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_folding_range(self, doc_uri: str, monitor: IMonitor) ->List[\n FoldingRangeTypedDict]:\n from robotframework_ls.impl.folding_range import folding_range\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return folding_range(completion_context)\n\n def m_code_lens(self, doc_uri: str):\n func = partial(self._threaded_code_lens, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_code_lens(self, doc_uri: str, monitor: IMonitor) ->List[\n CodeLensTypedDict]:\n from robotframework_ls.impl.code_lens import code_lens\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return code_lens(completion_context)\n\n def m_resolve_code_lens(self, **code_lens: CodeLensTypedDict):\n func = partial(self._threaded_resolve_code_lens, code_lens)\n func = require_monitor(func)\n return func\n\n def _threaded_resolve_code_lens(self, code_lens: CodeLensTypedDict,\n monitor: IMonitor) ->CodeLensTypedDict:\n from robotframework_ls.impl.code_lens import code_lens_resolve\n data = code_lens.get('data')\n if not isinstance(data, dict):\n return code_lens\n doc_uri = data.get('uri')\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return code_lens\n return code_lens_resolve(completion_context, code_lens)\n\n def m_document_symbol(self, doc_uri: str):\n func = partial(self._threaded_document_symbol, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_document_symbol(self, doc_uri: str, monitor: IMonitor\n ) ->List[DocumentSymbolTypedDict]:\n from robotframework_ls.impl.document_symbol import document_symbol\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return document_symbol(completion_context)\n <mask token>\n\n def _threaded_list_tests(self, doc_uri: str, monitor: IMonitor) ->List[\n ITestInfoTypedDict]:\n from robotframework_ls.impl.code_lens import list_tests\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return list_tests(completion_context)\n <mask token>\n\n def _threaded_hover(self, doc_uri: str, line, col, monitor: IMonitor\n ) ->Optional[HoverTypedDict]:\n from robotframework_ls.impl.hover import hover\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return hover(completion_context)\n\n def m_workspace_symbols(self, query: Optional[str]=None):\n func = partial(self._threaded_workspace_symbols, query)\n func = require_monitor(func)\n return func\n\n def _threaded_workspace_symbols(self, query: Optional[str], monitor:\n IMonitor) ->Optional[List[SymbolInformationTypedDict]]:\n from robotframework_ls.impl.workspace_symbols import workspace_symbols\n from robotframework_ls.impl.completion_context import BaseContext\n from robotframework_ls.impl.protocols import IRobotWorkspace\n from typing import cast\n workspace = self._workspace\n if not workspace:\n return []\n robot_workspace = cast(IRobotWorkspace, workspace)\n return workspace_symbols(query, BaseContext(workspace=\n robot_workspace, config=self.config, monitor=monitor))\n <mask token>\n\n def m_text_document__semantic_tokens__full(self, textDocument=None):\n func = partial(self.threaded_semantic_tokens_full, textDocument=\n textDocument)\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_full(self, textDocument:\n TextDocumentTypedDict, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full\n doc_uri = textDocument['uri']\n context = self._create_completion_context(doc_uri, -1, -1, monitor)\n if context is None:\n return {'resultId': None, 'data': []}\n return {'resultId': None, 'data': semantic_tokens_full(context)}\n\n def m_monaco_completions_from_code_full(self, prefix: str='', full_code:\n str='', position=PositionTypedDict, uri: str='', indent: str=''):\n func = partial(self.threaded_monaco_completions_from_code_full,\n prefix=prefix, full_code=full_code, position=position, uri=uri,\n indent=indent)\n func = require_monitor(func)\n return func\n\n def threaded_monaco_completions_from_code_full(self, prefix: str,\n full_code: str, position: PositionTypedDict, uri: str, indent: str,\n monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.robot_workspace import RobotDocument\n from robotframework_ls.impl.completion_context import CompletionContext\n from robocorp_ls_core.workspace import Document\n from robotframework_ls.impl import section_completions\n from robotframework_ls.impl import snippets_completions\n from robotframework_ls.server_api.monaco_conversions import convert_to_monaco_completion\n from robotframework_ls.impl.completion_context import CompletionType\n d = Document(uri, prefix)\n last_line, _last_col = d.get_last_line_col()\n line = last_line + position['line']\n col = position['character']\n col += len(indent)\n document = RobotDocument(uri, full_code)\n completion_context = CompletionContext(document, line, col, config=\n self.config, monitor=monitor, workspace=self.workspace)\n completion_context.type = CompletionType.shell\n completions = self._complete_from_completion_context(completion_context\n )\n completions.extend(section_completions.complete(completion_context))\n completions.extend(snippets_completions.complete(completion_context))\n return {'suggestions': [convert_to_monaco_completion(c, line_delta=\n last_line, col_delta=len(indent), uri=uri) for c in completions]}\n <mask token>\n\n def threaded_semantic_tokens_from_code_full(self, prefix: str,\n full_code: str, indent: str, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full_from_ast\n try:\n from robotframework_ls.impl.robot_workspace import RobotDocument\n doc = RobotDocument('')\n doc.source = full_code\n ast = doc.get_ast()\n data = semantic_tokens_full_from_ast(ast, monitor)\n if not prefix:\n return {'resultId': None, 'data': data}\n prefix_doc = RobotDocument('')\n prefix_doc.source = prefix\n last_line, last_col = prefix_doc.get_last_line_col()\n ints_iter = iter(data)\n line = 0\n col = 0\n new_data = []\n indent_len = len(indent)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n line += line_delta\n if line_delta == 0:\n col += col_delta\n else:\n col = col_delta\n if line >= last_line:\n new_data.append(line - last_line)\n new_data.append(col_delta - indent_len)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n new_data.append(line_delta)\n if line_delta > 0:\n new_data.append(col_delta - indent_len)\n else:\n new_data.append(col_delta)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n break\n return {'resultId': None, 'data': new_data}\n except:\n log.exception('Error computing semantic tokens from code.')\n return {'resultId': None, 'data': []}\n\n def m_shutdown(self, **_kwargs):\n PythonLanguageServer.m_shutdown(self, **_kwargs)\n self.libspec_manager.dispose()\n\n def m_exit(self, **_kwargs):\n PythonLanguageServer.m_exit(self, **_kwargs)\n self.libspec_manager.dispose()\n", "step-4": "<mask token>\n\n\nclass RobotFrameworkServerApi(PythonLanguageServer):\n <mask token>\n\n def __init__(self, read_from, write_to, libspec_manager=None, observer:\n Optional[IFSObserver]=None):\n from robotframework_ls.impl.libspec_manager import LibspecManager\n if libspec_manager is None:\n try:\n libspec_manager = LibspecManager(observer=observer)\n except:\n log.exception(\n 'Unable to properly initialize the LibspecManager.')\n raise\n self.libspec_manager = libspec_manager\n PythonLanguageServer.__init__(self, read_from, write_to)\n self._version = None\n self._next_time = partial(next, itertools.count(0))\n\n @overrides(PythonLanguageServer._create_config)\n def _create_config(self) ->IConfig:\n from robotframework_ls.robot_config import RobotConfig\n return RobotConfig()\n\n def m_version(self):\n if self._version is not None:\n return self._version\n try:\n import robot\n except:\n log.exception(\"Unable to import 'robot'.\")\n version = 'NO_ROBOT'\n else:\n try:\n from robot import get_version\n version = get_version(naked=True)\n except:\n log.exception('Unable to get version.')\n version = 'N/A'\n self._version = version\n return self._version\n\n def _check_min_version(self, min_version):\n from robocorp_ls_core.basic import check_min_version\n version = self.m_version()\n return check_min_version(version, min_version)\n\n @overrides(PythonLanguageServer.m_workspace__did_change_configuration)\n def m_workspace__did_change_configuration(self, **kwargs):\n PythonLanguageServer.m_workspace__did_change_configuration(self, **\n kwargs)\n self.libspec_manager.config = self.config\n\n @overrides(PythonLanguageServer.lint)\n def lint(self, *args, **kwargs):\n pass\n\n @overrides(PythonLanguageServer.cancel_lint)\n def cancel_lint(self, *args, **kwargs):\n pass\n <mask token>\n\n @overrides(PythonLanguageServer._create_workspace)\n def _create_workspace(self, root_uri: str, fs_observer: IFSObserver,\n workspace_folders) ->IWorkspace:\n from robotframework_ls.impl.robot_workspace import RobotWorkspace\n return RobotWorkspace(root_uri, fs_observer, workspace_folders,\n libspec_manager=self.libspec_manager)\n\n def m_lint(self, doc_uri):\n if not self._check_min_version((3, 2)):\n from robocorp_ls_core.lsp import Error\n msg = (\n \"\"\"robotframework version (%s) too old for linting.\nPlease install a newer version and restart the language server.\"\"\"\n % (self.m_version(),))\n log.info(msg)\n return [Error(msg, (0, 0), (1, 0)).to_lsp_diagnostic()]\n func = partial(self._threaded_lint, doc_uri)\n func = require_monitor(func)\n return func\n <mask token>\n\n def m_complete_all(self, doc_uri, line, col):\n func = partial(self._threaded_complete_all, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_complete_all(self, doc_uri, line, col, monitor: IMonitor):\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return []\n return self._complete_from_completion_context(completion_context)\n\n def _complete_from_completion_context(self, completion_context):\n from robotframework_ls.impl import section_name_completions\n from robotframework_ls.impl import keyword_completions\n from robotframework_ls.impl import variable_completions\n from robotframework_ls.impl import dictionary_completions\n from robotframework_ls.impl import filesystem_section_completions\n from robotframework_ls.impl import keyword_parameter_completions\n from robotframework_ls.impl import auto_import_completions\n from robotframework_ls.impl.collect_keywords import collect_keyword_name_to_keyword_found\n from robotframework_ls.impl import ast_utils\n ret = section_name_completions.complete(completion_context)\n if not ret:\n ret.extend(filesystem_section_completions.complete(\n completion_context))\n if not ret:\n token_info = completion_context.get_current_token()\n if token_info is not None:\n token = ast_utils.get_keyword_name_token(token_info.node,\n token_info.token)\n if token is not None:\n keyword_name_to_keyword_found: Dict[str, List[\n IKeywordFound]\n ] = collect_keyword_name_to_keyword_found(\n completion_context)\n ret.extend(keyword_completions.complete(completion_context)\n )\n ret.extend(auto_import_completions.complete(\n completion_context, keyword_name_to_keyword_found))\n return ret\n if not ret:\n ret.extend(variable_completions.complete(completion_context))\n if not ret:\n ret.extend(dictionary_completions.complete(completion_context))\n if not ret:\n ret.extend(keyword_parameter_completions.complete(\n completion_context))\n return ret\n\n def m_section_name_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import section_name_completions\n completion_context = self._create_completion_context(doc_uri, line,\n col, None)\n if completion_context is None:\n return []\n return section_name_completions.complete(completion_context)\n\n def m_keyword_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import keyword_completions\n completion_context = self._create_completion_context(doc_uri, line,\n col, None)\n if completion_context is None:\n return []\n return keyword_completions.complete(completion_context)\n\n def m_find_definition(self, doc_uri, line, col):\n func = partial(self._threaded_find_definition, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_find_definition(self, doc_uri, line, col, monitor\n ) ->Optional[list]:\n from robotframework_ls.impl.find_definition import find_definition\n import os.path\n from robocorp_ls_core.lsp import Location, Range\n from robocorp_ls_core import uris\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n definitions = find_definition(completion_context)\n ret = []\n for definition in definitions:\n if not definition.source:\n log.info('Found definition with empty source (%s).', definition\n )\n continue\n if not os.path.exists(definition.source):\n log.info('Found definition: %s (but source does not exist).',\n definition)\n continue\n lineno = definition.lineno\n if lineno is None or lineno < 0:\n lineno = 0\n end_lineno = definition.end_lineno\n if end_lineno is None or end_lineno < 0:\n end_lineno = 0\n col_offset = definition.col_offset\n end_col_offset = definition.end_col_offset\n ret.append(Location(uris.from_fs_path(definition.source), Range\n ((lineno, col_offset), (end_lineno, end_col_offset))).to_dict()\n )\n return ret\n\n def m_code_format(self, text_document, options):\n func = partial(self._threaded_code_format, text_document, options)\n func = require_monitor(func)\n return func\n\n def _threaded_code_format(self, text_document, options, monitor: IMonitor):\n from robotframework_ls.impl.formatting import create_text_edit_from_diff\n from robocorp_ls_core.lsp import TextDocumentItem\n import os.path\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY\n from robotframework_ls.impl.robot_lsp_constants import OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY\n text_document_item = TextDocumentItem(**text_document)\n text = text_document_item.text\n if not text:\n completion_context = self._create_completion_context(\n text_document_item.uri, 0, 0, monitor)\n if completion_context is None:\n return []\n text = completion_context.doc.source\n if not text:\n return []\n if options is None:\n options = {}\n tab_size = options.get('tabSize', 4)\n formatter = self._config.get_setting(OPTION_ROBOT_CODE_FORMATTER,\n str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY)\n if formatter not in (OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY):\n log.critical(\n f'Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}.'\n )\n return []\n if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY:\n from robotframework_ls.impl.formatting import robot_source_format\n new_contents = robot_source_format(text, space_count=tab_size)\n else:\n if not self._check_min_version((4, 0)):\n log.critical(\n f'To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}'\n )\n return []\n from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format\n ast = completion_context.get_ast()\n path = completion_context.doc.path\n dirname = '.'\n try:\n os.stat(path)\n except:\n ws = self._workspace\n if ws is not None:\n dirname = ws.root_path\n else:\n dirname = os.path.dirname(path)\n new_contents = robot_tidy_source_format(ast, dirname)\n if new_contents is None or new_contents == text:\n return []\n return [x.to_dict() for x in create_text_edit_from_diff(text,\n new_contents)]\n <mask token>\n\n def m_signature_help(self, doc_uri: str, line: int, col: int):\n func = partial(self._threaded_signature_help, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_signature_help(self, doc_uri: str, line: int, col: int,\n monitor: IMonitor) ->Optional[dict]:\n from robotframework_ls.impl.signature_help import signature_help\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return signature_help(completion_context)\n\n def m_folding_range(self, doc_uri: str):\n func = partial(self._threaded_folding_range, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_folding_range(self, doc_uri: str, monitor: IMonitor) ->List[\n FoldingRangeTypedDict]:\n from robotframework_ls.impl.folding_range import folding_range\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return folding_range(completion_context)\n\n def m_code_lens(self, doc_uri: str):\n func = partial(self._threaded_code_lens, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_code_lens(self, doc_uri: str, monitor: IMonitor) ->List[\n CodeLensTypedDict]:\n from robotframework_ls.impl.code_lens import code_lens\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return code_lens(completion_context)\n\n def m_resolve_code_lens(self, **code_lens: CodeLensTypedDict):\n func = partial(self._threaded_resolve_code_lens, code_lens)\n func = require_monitor(func)\n return func\n\n def _threaded_resolve_code_lens(self, code_lens: CodeLensTypedDict,\n monitor: IMonitor) ->CodeLensTypedDict:\n from robotframework_ls.impl.code_lens import code_lens_resolve\n data = code_lens.get('data')\n if not isinstance(data, dict):\n return code_lens\n doc_uri = data.get('uri')\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return code_lens\n return code_lens_resolve(completion_context, code_lens)\n\n def m_document_symbol(self, doc_uri: str):\n func = partial(self._threaded_document_symbol, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_document_symbol(self, doc_uri: str, monitor: IMonitor\n ) ->List[DocumentSymbolTypedDict]:\n from robotframework_ls.impl.document_symbol import document_symbol\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return document_symbol(completion_context)\n\n def m_list_tests(self, doc_uri: str):\n func = partial(self._threaded_list_tests, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_list_tests(self, doc_uri: str, monitor: IMonitor) ->List[\n ITestInfoTypedDict]:\n from robotframework_ls.impl.code_lens import list_tests\n completion_context = self._create_completion_context(doc_uri, 0, 0,\n monitor)\n if completion_context is None:\n return []\n return list_tests(completion_context)\n\n def m_hover(self, doc_uri: str, line: int, col: int):\n func = partial(self._threaded_hover, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_hover(self, doc_uri: str, line, col, monitor: IMonitor\n ) ->Optional[HoverTypedDict]:\n from robotframework_ls.impl.hover import hover\n completion_context = self._create_completion_context(doc_uri, line,\n col, monitor)\n if completion_context is None:\n return None\n return hover(completion_context)\n\n def m_workspace_symbols(self, query: Optional[str]=None):\n func = partial(self._threaded_workspace_symbols, query)\n func = require_monitor(func)\n return func\n\n def _threaded_workspace_symbols(self, query: Optional[str], monitor:\n IMonitor) ->Optional[List[SymbolInformationTypedDict]]:\n from robotframework_ls.impl.workspace_symbols import workspace_symbols\n from robotframework_ls.impl.completion_context import BaseContext\n from robotframework_ls.impl.protocols import IRobotWorkspace\n from typing import cast\n workspace = self._workspace\n if not workspace:\n return []\n robot_workspace = cast(IRobotWorkspace, workspace)\n return workspace_symbols(query, BaseContext(workspace=\n robot_workspace, config=self.config, monitor=monitor))\n\n def m_text_document__semantic_tokens__range(self, textDocument=None,\n range=None):\n raise RuntimeError('Not currently implemented!')\n\n def m_text_document__semantic_tokens__full(self, textDocument=None):\n func = partial(self.threaded_semantic_tokens_full, textDocument=\n textDocument)\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_full(self, textDocument:\n TextDocumentTypedDict, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full\n doc_uri = textDocument['uri']\n context = self._create_completion_context(doc_uri, -1, -1, monitor)\n if context is None:\n return {'resultId': None, 'data': []}\n return {'resultId': None, 'data': semantic_tokens_full(context)}\n\n def m_monaco_completions_from_code_full(self, prefix: str='', full_code:\n str='', position=PositionTypedDict, uri: str='', indent: str=''):\n func = partial(self.threaded_monaco_completions_from_code_full,\n prefix=prefix, full_code=full_code, position=position, uri=uri,\n indent=indent)\n func = require_monitor(func)\n return func\n\n def threaded_monaco_completions_from_code_full(self, prefix: str,\n full_code: str, position: PositionTypedDict, uri: str, indent: str,\n monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.robot_workspace import RobotDocument\n from robotframework_ls.impl.completion_context import CompletionContext\n from robocorp_ls_core.workspace import Document\n from robotframework_ls.impl import section_completions\n from robotframework_ls.impl import snippets_completions\n from robotframework_ls.server_api.monaco_conversions import convert_to_monaco_completion\n from robotframework_ls.impl.completion_context import CompletionType\n d = Document(uri, prefix)\n last_line, _last_col = d.get_last_line_col()\n line = last_line + position['line']\n col = position['character']\n col += len(indent)\n document = RobotDocument(uri, full_code)\n completion_context = CompletionContext(document, line, col, config=\n self.config, monitor=monitor, workspace=self.workspace)\n completion_context.type = CompletionType.shell\n completions = self._complete_from_completion_context(completion_context\n )\n completions.extend(section_completions.complete(completion_context))\n completions.extend(snippets_completions.complete(completion_context))\n return {'suggestions': [convert_to_monaco_completion(c, line_delta=\n last_line, col_delta=len(indent), uri=uri) for c in completions]}\n\n def m_semantic_tokens_from_code_full(self, prefix: str='', full_code:\n str='', indent: str=''):\n func = partial(self.threaded_semantic_tokens_from_code_full, prefix\n =prefix, full_code=full_code, indent=indent)\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_from_code_full(self, prefix: str,\n full_code: str, indent: str, monitor: Optional[IMonitor]=None):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full_from_ast\n try:\n from robotframework_ls.impl.robot_workspace import RobotDocument\n doc = RobotDocument('')\n doc.source = full_code\n ast = doc.get_ast()\n data = semantic_tokens_full_from_ast(ast, monitor)\n if not prefix:\n return {'resultId': None, 'data': data}\n prefix_doc = RobotDocument('')\n prefix_doc.source = prefix\n last_line, last_col = prefix_doc.get_last_line_col()\n ints_iter = iter(data)\n line = 0\n col = 0\n new_data = []\n indent_len = len(indent)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n line += line_delta\n if line_delta == 0:\n col += col_delta\n else:\n col = col_delta\n if line >= last_line:\n new_data.append(line - last_line)\n new_data.append(col_delta - indent_len)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n new_data.append(line_delta)\n if line_delta > 0:\n new_data.append(col_delta - indent_len)\n else:\n new_data.append(col_delta)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n break\n return {'resultId': None, 'data': new_data}\n except:\n log.exception('Error computing semantic tokens from code.')\n return {'resultId': None, 'data': []}\n\n def m_shutdown(self, **_kwargs):\n PythonLanguageServer.m_shutdown(self, **_kwargs)\n self.libspec_manager.dispose()\n\n def m_exit(self, **_kwargs):\n PythonLanguageServer.m_exit(self, **_kwargs)\n self.libspec_manager.dispose()\n", "step-5": "from robocorp_ls_core.python_ls import PythonLanguageServer\nfrom robocorp_ls_core.basic import overrides\nfrom robocorp_ls_core.robotframework_log import get_logger\nfrom typing import Optional, List, Dict\nfrom robocorp_ls_core.protocols import IConfig, IMonitor, ITestInfoTypedDict, IWorkspace\nfrom functools import partial\nfrom robocorp_ls_core.jsonrpc.endpoint import require_monitor\nfrom robocorp_ls_core.lsp import (\n SymbolInformationTypedDict,\n FoldingRangeTypedDict,\n HoverTypedDict,\n TextDocumentTypedDict,\n CodeLensTypedDict,\n DocumentSymbolTypedDict,\n PositionTypedDict,\n)\nfrom robotframework_ls.impl.protocols import IKeywordFound\nfrom robocorp_ls_core.watchdog_wrapper import IFSObserver\nimport itertools\n\n\nlog = get_logger(__name__)\n\n\nclass RobotFrameworkServerApi(PythonLanguageServer):\n \"\"\"\n This is a custom server. It uses the same message-format used in the language\n server but with custom messages (i.e.: this is not the language server, but\n an API to use the bits we need from robotframework in a separate process).\n \"\"\"\n\n def __init__(\n self,\n read_from,\n write_to,\n libspec_manager=None,\n observer: Optional[IFSObserver] = None,\n ):\n from robotframework_ls.impl.libspec_manager import LibspecManager\n\n if libspec_manager is None:\n try:\n libspec_manager = LibspecManager(observer=observer)\n except:\n log.exception(\"Unable to properly initialize the LibspecManager.\")\n raise\n\n self.libspec_manager = libspec_manager\n PythonLanguageServer.__init__(self, read_from, write_to)\n self._version = None\n self._next_time = partial(next, itertools.count(0))\n\n @overrides(PythonLanguageServer._create_config)\n def _create_config(self) -> IConfig:\n from robotframework_ls.robot_config import RobotConfig\n\n return RobotConfig()\n\n def m_version(self):\n if self._version is not None:\n return self._version\n try:\n import robot # noqa\n except:\n log.exception(\"Unable to import 'robot'.\")\n version = \"NO_ROBOT\"\n else:\n try:\n from robot import get_version\n\n version = get_version(naked=True)\n except:\n log.exception(\"Unable to get version.\")\n version = \"N/A\" # Too old?\n self._version = version\n return self._version\n\n def _check_min_version(self, min_version):\n from robocorp_ls_core.basic import check_min_version\n\n version = self.m_version()\n return check_min_version(version, min_version)\n\n @overrides(PythonLanguageServer.m_workspace__did_change_configuration)\n def m_workspace__did_change_configuration(self, **kwargs):\n PythonLanguageServer.m_workspace__did_change_configuration(self, **kwargs)\n self.libspec_manager.config = self.config\n\n @overrides(PythonLanguageServer.lint)\n def lint(self, *args, **kwargs):\n pass # No-op for this server.\n\n @overrides(PythonLanguageServer.cancel_lint)\n def cancel_lint(self, *args, **kwargs):\n pass # No-op for this server.\n\n @overrides(PythonLanguageServer._obtain_fs_observer)\n def _obtain_fs_observer(self) -> IFSObserver:\n return self.libspec_manager.fs_observer\n\n @overrides(PythonLanguageServer._create_workspace)\n def _create_workspace(\n self, root_uri: str, fs_observer: IFSObserver, workspace_folders\n ) -> IWorkspace:\n from robotframework_ls.impl.robot_workspace import RobotWorkspace\n\n return RobotWorkspace(\n root_uri,\n fs_observer,\n workspace_folders,\n libspec_manager=self.libspec_manager,\n )\n\n def m_lint(self, doc_uri):\n if not self._check_min_version((3, 2)):\n from robocorp_ls_core.lsp import Error\n\n msg = (\n \"robotframework version (%s) too old for linting.\\n\"\n \"Please install a newer version and restart the language server.\"\n % (self.m_version(),)\n )\n log.info(msg)\n return [Error(msg, (0, 0), (1, 0)).to_lsp_diagnostic()]\n\n func = partial(self._threaded_lint, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_lint(self, doc_uri, monitor: IMonitor):\n from robocorp_ls_core.jsonrpc.exceptions import JsonRpcRequestCancelled\n from robotframework_ls.impl.robot_lsp_constants import (\n OPTION_ROBOT_LINT_ROBOCOP_ENABLED,\n )\n from robocorp_ls_core import uris\n from robocorp_ls_core.lsp import Error\n\n try:\n from robotframework_ls.impl.ast_utils import collect_errors\n from robotframework_ls.impl import code_analysis\n import os.path\n\n log.debug(\"Lint: starting (in thread).\")\n\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return []\n\n config = completion_context.config\n robocop_enabled = config is None or config.get_setting(\n OPTION_ROBOT_LINT_ROBOCOP_ENABLED, bool, False\n )\n\n ast = completion_context.get_ast()\n source = completion_context.doc.source\n monitor.check_cancelled()\n errors = collect_errors(ast)\n log.debug(\"Collected AST errors (in thread): %s\", len(errors))\n monitor.check_cancelled()\n analysis_errors = code_analysis.collect_analysis_errors(completion_context)\n monitor.check_cancelled()\n log.debug(\"Collected analysis errors (in thread): %s\", len(analysis_errors))\n errors.extend(analysis_errors)\n\n lsp_diagnostics = [error.to_lsp_diagnostic() for error in errors]\n\n try:\n if robocop_enabled:\n from robocorp_ls_core.robocop_wrapper import (\n collect_robocop_diagnostics,\n )\n\n workspace = completion_context.workspace\n if workspace is not None:\n project_root = workspace.root_path\n else:\n project_root = os.path.abspath(\".\")\n\n monitor.check_cancelled()\n lsp_diagnostics.extend(\n collect_robocop_diagnostics(\n project_root, ast, uris.to_fs_path(doc_uri), source\n )\n )\n except Exception as e:\n log.exception(\n \"Error collecting Robocop errors (possibly an unsupported Robocop version is installed).\"\n )\n lsp_diagnostics.append(\n Error(\n f\"Error collecting Robocop errors: {e}\", (0, 0), (1, 0)\n ).to_lsp_diagnostic()\n )\n\n return lsp_diagnostics\n except JsonRpcRequestCancelled:\n raise JsonRpcRequestCancelled(\"Lint cancelled (inside lint)\")\n except Exception as e:\n log.exception(\"Error collecting errors.\")\n ret = [\n Error(\n f\"Error collecting Robocop errors: {e}\", (0, 0), (1, 0)\n ).to_lsp_diagnostic()\n ]\n return ret\n\n def m_complete_all(self, doc_uri, line, col):\n func = partial(self._threaded_complete_all, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_complete_all(self, doc_uri, line, col, monitor: IMonitor):\n completion_context = self._create_completion_context(\n doc_uri, line, col, monitor\n )\n if completion_context is None:\n return []\n\n return self._complete_from_completion_context(completion_context)\n\n def _complete_from_completion_context(self, completion_context):\n from robotframework_ls.impl import section_name_completions\n from robotframework_ls.impl import keyword_completions\n from robotframework_ls.impl import variable_completions\n from robotframework_ls.impl import dictionary_completions\n from robotframework_ls.impl import filesystem_section_completions\n from robotframework_ls.impl import keyword_parameter_completions\n from robotframework_ls.impl import auto_import_completions\n from robotframework_ls.impl.collect_keywords import (\n collect_keyword_name_to_keyword_found,\n )\n from robotframework_ls.impl import ast_utils\n\n ret = section_name_completions.complete(completion_context)\n if not ret:\n ret.extend(filesystem_section_completions.complete(completion_context))\n\n if not ret:\n token_info = completion_context.get_current_token()\n if token_info is not None:\n token = ast_utils.get_keyword_name_token(\n token_info.node, token_info.token\n )\n if token is not None:\n keyword_name_to_keyword_found: Dict[\n str, List[IKeywordFound]\n ] = collect_keyword_name_to_keyword_found(completion_context)\n ret.extend(keyword_completions.complete(completion_context))\n ret.extend(\n auto_import_completions.complete(\n completion_context, keyword_name_to_keyword_found\n )\n )\n return ret\n\n if not ret:\n ret.extend(variable_completions.complete(completion_context))\n\n if not ret:\n ret.extend(dictionary_completions.complete(completion_context))\n\n if not ret:\n ret.extend(keyword_parameter_completions.complete(completion_context))\n\n return ret\n\n def m_section_name_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import section_name_completions\n\n completion_context = self._create_completion_context(doc_uri, line, col, None)\n if completion_context is None:\n return []\n\n return section_name_completions.complete(completion_context)\n\n def m_keyword_complete(self, doc_uri, line, col):\n from robotframework_ls.impl import keyword_completions\n\n completion_context = self._create_completion_context(doc_uri, line, col, None)\n if completion_context is None:\n return []\n return keyword_completions.complete(completion_context)\n\n def m_find_definition(self, doc_uri, line, col):\n func = partial(self._threaded_find_definition, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_find_definition(self, doc_uri, line, col, monitor) -> Optional[list]:\n from robotframework_ls.impl.find_definition import find_definition\n import os.path\n from robocorp_ls_core.lsp import Location, Range\n from robocorp_ls_core import uris\n\n completion_context = self._create_completion_context(\n doc_uri, line, col, monitor\n )\n if completion_context is None:\n return None\n definitions = find_definition(completion_context)\n ret = []\n for definition in definitions:\n if not definition.source:\n log.info(\"Found definition with empty source (%s).\", definition)\n continue\n\n if not os.path.exists(definition.source):\n log.info(\n \"Found definition: %s (but source does not exist).\", definition\n )\n continue\n\n lineno = definition.lineno\n if lineno is None or lineno < 0:\n lineno = 0\n\n end_lineno = definition.end_lineno\n if end_lineno is None or end_lineno < 0:\n end_lineno = 0\n\n col_offset = definition.col_offset\n end_col_offset = definition.end_col_offset\n\n ret.append(\n Location(\n uris.from_fs_path(definition.source),\n Range((lineno, col_offset), (end_lineno, end_col_offset)),\n ).to_dict()\n )\n return ret\n\n def m_code_format(self, text_document, options):\n func = partial(self._threaded_code_format, text_document, options)\n func = require_monitor(func)\n return func\n\n def _threaded_code_format(self, text_document, options, monitor: IMonitor):\n from robotframework_ls.impl.formatting import create_text_edit_from_diff\n from robocorp_ls_core.lsp import TextDocumentItem\n import os.path\n from robotframework_ls.impl.robot_lsp_constants import (\n OPTION_ROBOT_CODE_FORMATTER,\n )\n from robotframework_ls.impl.robot_lsp_constants import (\n OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n )\n from robotframework_ls.impl.robot_lsp_constants import (\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY,\n )\n\n text_document_item = TextDocumentItem(**text_document)\n text = text_document_item.text\n if not text:\n completion_context = self._create_completion_context(\n text_document_item.uri, 0, 0, monitor\n )\n if completion_context is None:\n return []\n text = completion_context.doc.source\n\n if not text:\n return []\n\n if options is None:\n options = {}\n tab_size = options.get(\"tabSize\", 4)\n\n # Default for now is the builtin. This will probably be changed in the future.\n formatter = self._config.get_setting(\n OPTION_ROBOT_CODE_FORMATTER, str, OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY\n )\n if formatter not in (\n OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY,\n OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY,\n ):\n log.critical(\n f\"Code formatter invalid: {formatter}. Please select one of: {OPTION_ROBOT_CODE_FORMATTER_ROBOTIDY}, {OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY}.\"\n )\n return []\n\n if formatter == OPTION_ROBOT_CODE_FORMATTER_BUILTIN_TIDY:\n from robotframework_ls.impl.formatting import robot_source_format\n\n new_contents = robot_source_format(text, space_count=tab_size)\n\n else:\n if not self._check_min_version((4, 0)):\n log.critical(\n f\"To use the robotidy formatter, at least Robot Framework 4 is needed. Found: {self.m_version()}\"\n )\n return []\n\n from robocorp_ls_core.robotidy_wrapper import robot_tidy_source_format\n\n ast = completion_context.get_ast()\n path = completion_context.doc.path\n dirname = \".\"\n try:\n os.stat(path)\n except:\n # It doesn't exist\n ws = self._workspace\n if ws is not None:\n dirname = ws.root_path\n else:\n dirname = os.path.dirname(path)\n\n new_contents = robot_tidy_source_format(ast, dirname)\n\n if new_contents is None or new_contents == text:\n return []\n return [x.to_dict() for x in create_text_edit_from_diff(text, new_contents)]\n\n def _create_completion_context(\n self, doc_uri, line, col, monitor: Optional[IMonitor]\n ):\n from robotframework_ls.impl.completion_context import CompletionContext\n\n if not self._check_min_version((3, 2)):\n log.info(\"robotframework version too old.\")\n return None\n workspace = self.workspace\n if not workspace:\n log.info(\"Workspace still not initialized.\")\n return None\n\n document = workspace.get_document(doc_uri, accept_from_file=True)\n if document is None:\n log.info(\"Unable to get document for uri: %s.\", doc_uri)\n return None\n return CompletionContext(\n document,\n line,\n col,\n workspace=workspace,\n config=self.config,\n monitor=monitor,\n )\n\n def m_signature_help(self, doc_uri: str, line: int, col: int):\n func = partial(self._threaded_signature_help, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_signature_help(\n self, doc_uri: str, line: int, col: int, monitor: IMonitor\n ) -> Optional[dict]:\n from robotframework_ls.impl.signature_help import signature_help\n\n completion_context = self._create_completion_context(\n doc_uri, line, col, monitor\n )\n if completion_context is None:\n return None\n\n return signature_help(completion_context)\n\n def m_folding_range(self, doc_uri: str):\n func = partial(self._threaded_folding_range, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_folding_range(\n self, doc_uri: str, monitor: IMonitor\n ) -> List[FoldingRangeTypedDict]:\n from robotframework_ls.impl.folding_range import folding_range\n\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return []\n\n return folding_range(completion_context)\n\n def m_code_lens(self, doc_uri: str):\n func = partial(self._threaded_code_lens, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_code_lens(\n self, doc_uri: str, monitor: IMonitor\n ) -> List[CodeLensTypedDict]:\n from robotframework_ls.impl.code_lens import code_lens\n\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return []\n\n return code_lens(completion_context)\n\n def m_resolve_code_lens(self, **code_lens: CodeLensTypedDict):\n func = partial(self._threaded_resolve_code_lens, code_lens)\n func = require_monitor(func)\n return func\n\n def _threaded_resolve_code_lens(\n self, code_lens: CodeLensTypedDict, monitor: IMonitor\n ) -> CodeLensTypedDict:\n from robotframework_ls.impl.code_lens import code_lens_resolve\n\n data = code_lens.get(\"data\")\n if not isinstance(data, dict):\n return code_lens\n\n doc_uri = data.get(\"uri\")\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return code_lens\n\n return code_lens_resolve(completion_context, code_lens)\n\n def m_document_symbol(self, doc_uri: str):\n func = partial(self._threaded_document_symbol, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_document_symbol(\n self, doc_uri: str, monitor: IMonitor\n ) -> List[DocumentSymbolTypedDict]:\n from robotframework_ls.impl.document_symbol import document_symbol\n\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return []\n\n return document_symbol(completion_context)\n\n def m_list_tests(self, doc_uri: str):\n func = partial(self._threaded_list_tests, doc_uri)\n func = require_monitor(func)\n return func\n\n def _threaded_list_tests(\n self, doc_uri: str, monitor: IMonitor\n ) -> List[ITestInfoTypedDict]:\n from robotframework_ls.impl.code_lens import list_tests\n\n completion_context = self._create_completion_context(doc_uri, 0, 0, monitor)\n if completion_context is None:\n return []\n\n return list_tests(completion_context)\n\n def m_hover(self, doc_uri: str, line: int, col: int):\n func = partial(self._threaded_hover, doc_uri, line, col)\n func = require_monitor(func)\n return func\n\n def _threaded_hover(\n self, doc_uri: str, line, col, monitor: IMonitor\n ) -> Optional[HoverTypedDict]:\n from robotframework_ls.impl.hover import hover\n\n completion_context = self._create_completion_context(\n doc_uri, line, col, monitor\n )\n if completion_context is None:\n return None\n\n return hover(completion_context)\n\n def m_workspace_symbols(self, query: Optional[str] = None):\n func = partial(self._threaded_workspace_symbols, query)\n func = require_monitor(func)\n return func\n\n def _threaded_workspace_symbols(\n self, query: Optional[str], monitor: IMonitor\n ) -> Optional[List[SymbolInformationTypedDict]]:\n from robotframework_ls.impl.workspace_symbols import workspace_symbols\n from robotframework_ls.impl.completion_context import BaseContext\n from robotframework_ls.impl.protocols import IRobotWorkspace\n from typing import cast\n\n workspace = self._workspace\n if not workspace:\n return []\n\n robot_workspace = cast(IRobotWorkspace, workspace)\n\n return workspace_symbols(\n query,\n BaseContext(workspace=robot_workspace, config=self.config, monitor=monitor),\n )\n\n def m_text_document__semantic_tokens__range(self, textDocument=None, range=None):\n raise RuntimeError(\"Not currently implemented!\")\n\n def m_text_document__semantic_tokens__full(self, textDocument=None):\n func = partial(self.threaded_semantic_tokens_full, textDocument=textDocument)\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_full(\n self, textDocument: TextDocumentTypedDict, monitor: Optional[IMonitor] = None\n ):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full\n\n doc_uri = textDocument[\"uri\"]\n context = self._create_completion_context(doc_uri, -1, -1, monitor)\n if context is None:\n return {\"resultId\": None, \"data\": []}\n return {\"resultId\": None, \"data\": semantic_tokens_full(context)}\n\n def m_monaco_completions_from_code_full(\n self,\n prefix: str = \"\",\n full_code: str = \"\",\n position=PositionTypedDict,\n uri: str = \"\",\n indent: str = \"\",\n ):\n func = partial(\n self.threaded_monaco_completions_from_code_full,\n prefix=prefix,\n full_code=full_code,\n position=position,\n uri=uri,\n indent=indent,\n )\n func = require_monitor(func)\n return func\n\n def threaded_monaco_completions_from_code_full(\n self,\n prefix: str,\n full_code: str,\n position: PositionTypedDict,\n uri: str,\n indent: str,\n monitor: Optional[IMonitor] = None,\n ):\n from robotframework_ls.impl.robot_workspace import RobotDocument\n from robotframework_ls.impl.completion_context import CompletionContext\n from robocorp_ls_core.workspace import Document\n from robotframework_ls.impl import section_completions\n from robotframework_ls.impl import snippets_completions\n from robotframework_ls.server_api.monaco_conversions import (\n convert_to_monaco_completion,\n )\n from robotframework_ls.impl.completion_context import CompletionType\n\n d = Document(uri, prefix)\n last_line, _last_col = d.get_last_line_col()\n line = last_line + position[\"line\"]\n\n col = position[\"character\"]\n col += len(indent)\n\n document = RobotDocument(uri, full_code)\n completion_context = CompletionContext(\n document,\n line,\n col,\n config=self.config,\n monitor=monitor,\n workspace=self.workspace,\n )\n completion_context.type = CompletionType.shell\n completions = self._complete_from_completion_context(completion_context)\n completions.extend(section_completions.complete(completion_context))\n completions.extend(snippets_completions.complete(completion_context))\n\n return {\n \"suggestions\": [\n convert_to_monaco_completion(\n c, line_delta=last_line, col_delta=len(indent), uri=uri\n )\n for c in completions\n ]\n }\n\n def m_semantic_tokens_from_code_full(\n self, prefix: str = \"\", full_code: str = \"\", indent: str = \"\"\n ):\n func = partial(\n self.threaded_semantic_tokens_from_code_full,\n prefix=prefix,\n full_code=full_code,\n indent=indent,\n )\n func = require_monitor(func)\n return func\n\n def threaded_semantic_tokens_from_code_full(\n self,\n prefix: str,\n full_code: str,\n indent: str,\n monitor: Optional[IMonitor] = None,\n ):\n from robotframework_ls.impl.semantic_tokens import semantic_tokens_full_from_ast\n\n try:\n from robotframework_ls.impl.robot_workspace import RobotDocument\n\n doc = RobotDocument(\"\")\n doc.source = full_code\n ast = doc.get_ast()\n data = semantic_tokens_full_from_ast(ast, monitor)\n if not prefix:\n return {\"resultId\": None, \"data\": data}\n\n # We have to exclude the prefix from the coloring...\n\n # debug info...\n # import io\n # from robotframework_ls.impl.semantic_tokens import decode_semantic_tokens\n # stream = io.StringIO()\n # decode_semantic_tokens(data, doc, stream)\n # found = stream.getvalue()\n\n prefix_doc = RobotDocument(\"\")\n prefix_doc.source = prefix\n last_line, last_col = prefix_doc.get_last_line_col()\n\n # Now we have the data from the full code, but we need to remove whatever\n # we have in the prefix from the result...\n ints_iter = iter(data)\n line = 0\n col = 0\n new_data = []\n indent_len = len(indent)\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n line += line_delta\n if line_delta == 0:\n col += col_delta\n else:\n col = col_delta\n\n if line >= last_line:\n new_data.append(line - last_line)\n new_data.append(col_delta - indent_len)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n\n # Ok, now, we have to add the indent_len to all the\n # next lines\n while True:\n try:\n line_delta = next(ints_iter)\n except StopIteration:\n break\n col_delta = next(ints_iter)\n token_len = next(ints_iter)\n token_type = next(ints_iter)\n token_modifier = next(ints_iter)\n\n new_data.append(line_delta)\n if line_delta > 0:\n new_data.append(col_delta - indent_len)\n else:\n new_data.append(col_delta)\n new_data.append(token_len)\n new_data.append(token_type)\n new_data.append(token_modifier)\n\n break\n\n # Approach changed so that we always have a new line\n # i.e.:\n # \\n<indent><code>\n #\n # so, the condition below no longer applies.\n # elif line == last_line and col >= last_col:\n # new_data.append(0)\n # new_data.append(col - last_col)\n # new_data.append(token_len)\n # new_data.append(token_type)\n # new_data.append(token_modifier)\n # new_data.extend(ints_iter)\n # break\n\n # debug info...\n # temp_stream = io.StringIO()\n # temp_doc = RobotDocument(\"\")\n # temp_doc.source = full_code[len(prefix) :]\n # decode_semantic_tokens(new_data, temp_doc, temp_stream)\n # temp_found = temp_stream.getvalue()\n\n return {\"resultId\": None, \"data\": new_data}\n except:\n log.exception(\"Error computing semantic tokens from code.\")\n return {\"resultId\": None, \"data\": []}\n\n def m_shutdown(self, **_kwargs):\n PythonLanguageServer.m_shutdown(self, **_kwargs)\n self.libspec_manager.dispose()\n\n def m_exit(self, **_kwargs):\n PythonLanguageServer.m_exit(self, **_kwargs)\n self.libspec_manager.dispose()\n", "step-ids": [ 19, 33, 35, 44, 51 ] }
[ 19, 33, 35, 44, 51 ]
from django.forms import ModelForm from contactform.models import ContactRequest class ContactRequestForm(ModelForm): class Meta: model = ContactRequest
normal
{ "blob_id": "97637e2114254b41ef6e777e60b3ddab1d4622e8", "index": 4606, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ContactRequestForm(ModelForm):\n\n\n class Meta:\n model = ContactRequest\n", "step-3": "from django.forms import ModelForm\nfrom contactform.models import ContactRequest\n\n\nclass ContactRequestForm(ModelForm):\n\n\n class Meta:\n model = ContactRequest\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
class Enumerator(object): """For Python we just wrap the iterator""" def __init__(self, next): self.iterator = next def __next__(self): return next(self.iterator) # Python 2.7 next = __next__ def __iter__(self): return self
normal
{ "blob_id": "1ca20b0cd9217623ff039ab352acd09df8dfae1b", "index": 8235, "step-1": "class Enumerator(object):\n <mask token>\n <mask token>\n\n def __next__(self):\n return next(self.iterator)\n <mask token>\n\n def __iter__(self):\n return self\n", "step-2": "class Enumerator(object):\n <mask token>\n\n def __init__(self, next):\n self.iterator = next\n\n def __next__(self):\n return next(self.iterator)\n <mask token>\n\n def __iter__(self):\n return self\n", "step-3": "class Enumerator(object):\n <mask token>\n\n def __init__(self, next):\n self.iterator = next\n\n def __next__(self):\n return next(self.iterator)\n next = __next__\n\n def __iter__(self):\n return self\n", "step-4": "class Enumerator(object):\n \"\"\"For Python we just wrap the iterator\"\"\"\n\n def __init__(self, next):\n self.iterator = next\n\n def __next__(self):\n return next(self.iterator)\n next = __next__\n\n def __iter__(self):\n return self\n", "step-5": "class Enumerator(object):\n \"\"\"For Python we just wrap the iterator\"\"\"\n\n def __init__(self, next):\n self.iterator = next\n\n def __next__(self):\n return next(self.iterator)\n\n # Python 2.7\n next = __next__\n\n def __iter__(self):\n return self\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
from io import StringIO from pathlib import Path from unittest import TestCase from doculabs.samon import constants from doculabs.samon.elements import BaseElement, AnonymusElement from doculabs.samon.expressions import Condition, ForLoop, Bind class BaseElementTest(TestCase): def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path): xml_benchmark = Path(__file__).parent / xml_benchmark with xml_benchmark.open('r', encoding='utf-8') as f: xml_benchmark = f.read() self.assertEqual(generated_xml, xml_benchmark) def test_parse_xml_attributes(self): xml_attrs = { # AttributesNSImpl like object (None, 'attr1'): 'val1', # NS, attr_name ('http://example.org', 'attr2'): 'val2' } element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'}) def test_parse_expressions(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}if'], Condition) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}for'], ForLoop) self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind) def test_data_binding(self): xml_attrs = { (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue() self.assertEqual(xml, '<tag attr2="example_value">\n</tag>\n') def test_eval_forloop(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val', (None, 'class'): 'class_name' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/forloop.xml') def test_eval_if(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7', (None, 'class'): 'class_name' } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val': 8}, indent=0).getvalue() self.assertEqual(xml, '') xml = e.to_string(context={'val': 7}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/ifcond.xml') def test_if_and_for_precedence(self): xml_attrs = { (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val', } e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs) xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0).getvalue() self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml') def test_render_anonymuselement(self): e = AnonymusElement(text='example') self.assertEqual(e.to_string(context={}).getvalue(), 'example\n')
normal
{ "blob_id": "c6b98cf309e2f1a0d279ec8dc728ffd3fe45dfdb", "index": 4792, "step-1": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n <mask token>\n <mask token>\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n <mask token>\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-2": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n <mask token>\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-3": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org',\n 'attr2'): 'val2'}\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1',\n '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n <mask token>\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-4": "<mask token>\n\n\nclass BaseElementTest(TestCase):\n\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = {(None, 'attr1'): 'val1', ('http://example.org',\n 'attr2'): 'val2'}\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1',\n '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs[\n '{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {(constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue(\n )\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'a in val', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n\n def test_eval_if(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val == 7', (None, 'class'): 'class_name'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 8}, indent=0).getvalue()\n self.assertEqual(xml, '')\n xml = e.to_string(context={'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/ifcond.xml')\n\n def test_if_and_for_precedence(self):\n xml_attrs = {(constants.XML_NAMESPACE_FLOW_CONTROL, 'if'):\n 'val > 7', (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'):\n 'val in val2', (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'):\n 'val'}\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0\n ).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-5": "from io import StringIO\nfrom pathlib import Path\nfrom unittest import TestCase\n\nfrom doculabs.samon import constants\nfrom doculabs.samon.elements import BaseElement, AnonymusElement\nfrom doculabs.samon.expressions import Condition, ForLoop, Bind\n\n\nclass BaseElementTest(TestCase):\n def assertXmlEqual(self, generated_xml: str, xml_benchmark: Path):\n xml_benchmark = Path(__file__).parent / xml_benchmark\n with xml_benchmark.open('r', encoding='utf-8') as f:\n xml_benchmark = f.read()\n\n self.assertEqual(generated_xml, xml_benchmark)\n\n def test_parse_xml_attributes(self):\n xml_attrs = { # AttributesNSImpl like object\n (None, 'attr1'): 'val1', # NS, attr_name\n ('http://example.org', 'attr2'): 'val2'\n }\n\n element = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertEqual(element.xml_attrs, {'attr1': 'val1', '{http://example.org}attr2': 'val2'})\n\n def test_parse_expressions(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7',\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val',\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}if'], Condition)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#control}for'], ForLoop)\n self.assertIsInstance(e.xml_attrs['{https://doculabs.io/2020/xtmpl#data-binding}attr2'], Bind)\n\n def test_data_binding(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr2'): 'val'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 'example_value'}, indent=0).getvalue()\n self.assertEqual(xml, '<tag attr2=\"example_value\">\\n</tag>\\n')\n\n def test_eval_forloop(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'a in val',\n (None, 'class'): 'class_name'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': [1, 2, 3]}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/forloop.xml')\n\n def test_eval_if(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val == 7',\n (None, 'class'): 'class_name'\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val': 8}, indent=0).getvalue()\n self.assertEqual(xml, '')\n\n xml = e.to_string(context={'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/ifcond.xml')\n\n def test_if_and_for_precedence(self):\n xml_attrs = {\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'if'): 'val > 7',\n (constants.XML_NAMESPACE_FLOW_CONTROL, 'for'): 'val in val2',\n (constants.XML_NAMESPACE_DATA_BINDING, 'attr1'): 'val',\n }\n\n e = BaseElement(xml_tag='tag', xml_attrs=xml_attrs)\n xml = e.to_string(context={'val2': [7, 8, 9], 'val': 7}, indent=0).getvalue()\n self.assertXmlEqual(xml, 'assets/elements/if_and_for.xml')\n\n def test_render_anonymuselement(self):\n e = AnonymusElement(text='example')\n self.assertEqual(e.to_string(context={}).getvalue(), 'example\\n')\n", "step-ids": [ 5, 7, 8, 9, 11 ] }
[ 5, 7, 8, 9, 11 ]
import tests.functions as functions if __name__ == "__main__": # functions.validate_all_redirects("linked.data.gov.au-vocabularies.json") conf = open("../conf/linked.data.gov.au-vocabularies.conf") new = [ "anzsrc-for", "anzsrc-seo", "ausplots-cv", "australian-phone-area-codes", "care", "corveg-cv", "nrm", "reg-roles", "reg-statuses", "address-type", "australian-states-and-territories", "bc-labels", "data-access-rights", "dataciteroles", "depth-reference", "geo-commodities", "geoadminfeatures", "geofeatures", "geological-observation-instrument", "geological-observation-method", "geological-observation-type", "geological-sites", "geometry-roles", "georesource-report", "gsq-alias", "gsq-dataset-theme", "gsq-roles", "gsq-sample-facility", "iso639-1", "iso-19157-data-quality-dimension", "iso-iec-25012-data-quality-dimension", "nsw-quality-dimension", "party-identifier-type", "qg-agent", "qg-file-types", "qg-security-classifications", "qg-sites", "qld-data-licenses", "iso19115-1/RoleCode", "minerals", "nslvoc", "observation-detail-type", "organisation-activity-status", "organisation-name-types", "organisation-type", "party-relationship", "queensland-crs", "qld-resource-permit-status", "qld-resource-permit", "qld-utm-zones", "geou", "iso11179-6/RolesAndResponsibilities", "qesd-qkd", "qesd-uom", "qld-obsprop", "report-detail-type", "report-status", "resource-project-lifecycle", "resource-types", "result-type", "sample-detail-type", "sample-location-status", "sample-location-types", "sample-material", "sample-preparation-methods", "sample-relationship", "sample-type", "seismic-dimensionality", "site-detail-type", "site-relationships", "site-status", "supermodel/terms", "survey-detail-type", "survey-method", "survey-relationship-type", "survey-status", "survey-type", "telephone-type", "tk-labels", "trs" ] lines = conf.readlines() for n in new: for line in lines: if n in line: pattern, match = line.split("$", 1) print(pattern.strip().replace("RewriteRule ^", "https://linked.data.gov.au/"), " -- ", match.split("[R")[0].replace('"', '').strip()) break
normal
{ "blob_id": "4a620957b2cd1e5945d98e49a5eae5d5592ef5a2", "index": 3911, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n conf = open('../conf/linked.data.gov.au-vocabularies.conf')\n new = ['anzsrc-for', 'anzsrc-seo', 'ausplots-cv',\n 'australian-phone-area-codes', 'care', 'corveg-cv', 'nrm',\n 'reg-roles', 'reg-statuses', 'address-type',\n 'australian-states-and-territories', 'bc-labels',\n 'data-access-rights', 'dataciteroles', 'depth-reference',\n 'geo-commodities', 'geoadminfeatures', 'geofeatures',\n 'geological-observation-instrument',\n 'geological-observation-method', 'geological-observation-type',\n 'geological-sites', 'geometry-roles', 'georesource-report',\n 'gsq-alias', 'gsq-dataset-theme', 'gsq-roles',\n 'gsq-sample-facility', 'iso639-1',\n 'iso-19157-data-quality-dimension',\n 'iso-iec-25012-data-quality-dimension', 'nsw-quality-dimension',\n 'party-identifier-type', 'qg-agent', 'qg-file-types',\n 'qg-security-classifications', 'qg-sites', 'qld-data-licenses',\n 'iso19115-1/RoleCode', 'minerals', 'nslvoc',\n 'observation-detail-type', 'organisation-activity-status',\n 'organisation-name-types', 'organisation-type',\n 'party-relationship', 'queensland-crs',\n 'qld-resource-permit-status', 'qld-resource-permit',\n 'qld-utm-zones', 'geou', 'iso11179-6/RolesAndResponsibilities',\n 'qesd-qkd', 'qesd-uom', 'qld-obsprop', 'report-detail-type',\n 'report-status', 'resource-project-lifecycle', 'resource-types',\n 'result-type', 'sample-detail-type', 'sample-location-status',\n 'sample-location-types', 'sample-material',\n 'sample-preparation-methods', 'sample-relationship', 'sample-type',\n 'seismic-dimensionality', 'site-detail-type', 'site-relationships',\n 'site-status', 'supermodel/terms', 'survey-detail-type',\n 'survey-method', 'survey-relationship-type', 'survey-status',\n 'survey-type', 'telephone-type', 'tk-labels', 'trs']\n lines = conf.readlines()\n for n in new:\n for line in lines:\n if n in line:\n pattern, match = line.split('$', 1)\n print(pattern.strip().replace('RewriteRule ^',\n 'https://linked.data.gov.au/'), ' -- ', match.split(\n '[R')[0].replace('\"', '').strip())\n break\n", "step-3": "import tests.functions as functions\nif __name__ == '__main__':\n conf = open('../conf/linked.data.gov.au-vocabularies.conf')\n new = ['anzsrc-for', 'anzsrc-seo', 'ausplots-cv',\n 'australian-phone-area-codes', 'care', 'corveg-cv', 'nrm',\n 'reg-roles', 'reg-statuses', 'address-type',\n 'australian-states-and-territories', 'bc-labels',\n 'data-access-rights', 'dataciteroles', 'depth-reference',\n 'geo-commodities', 'geoadminfeatures', 'geofeatures',\n 'geological-observation-instrument',\n 'geological-observation-method', 'geological-observation-type',\n 'geological-sites', 'geometry-roles', 'georesource-report',\n 'gsq-alias', 'gsq-dataset-theme', 'gsq-roles',\n 'gsq-sample-facility', 'iso639-1',\n 'iso-19157-data-quality-dimension',\n 'iso-iec-25012-data-quality-dimension', 'nsw-quality-dimension',\n 'party-identifier-type', 'qg-agent', 'qg-file-types',\n 'qg-security-classifications', 'qg-sites', 'qld-data-licenses',\n 'iso19115-1/RoleCode', 'minerals', 'nslvoc',\n 'observation-detail-type', 'organisation-activity-status',\n 'organisation-name-types', 'organisation-type',\n 'party-relationship', 'queensland-crs',\n 'qld-resource-permit-status', 'qld-resource-permit',\n 'qld-utm-zones', 'geou', 'iso11179-6/RolesAndResponsibilities',\n 'qesd-qkd', 'qesd-uom', 'qld-obsprop', 'report-detail-type',\n 'report-status', 'resource-project-lifecycle', 'resource-types',\n 'result-type', 'sample-detail-type', 'sample-location-status',\n 'sample-location-types', 'sample-material',\n 'sample-preparation-methods', 'sample-relationship', 'sample-type',\n 'seismic-dimensionality', 'site-detail-type', 'site-relationships',\n 'site-status', 'supermodel/terms', 'survey-detail-type',\n 'survey-method', 'survey-relationship-type', 'survey-status',\n 'survey-type', 'telephone-type', 'tk-labels', 'trs']\n lines = conf.readlines()\n for n in new:\n for line in lines:\n if n in line:\n pattern, match = line.split('$', 1)\n print(pattern.strip().replace('RewriteRule ^',\n 'https://linked.data.gov.au/'), ' -- ', match.split(\n '[R')[0].replace('\"', '').strip())\n break\n", "step-4": "import tests.functions as functions\n\nif __name__ == \"__main__\":\n # functions.validate_all_redirects(\"linked.data.gov.au-vocabularies.json\")\n\n conf = open(\"../conf/linked.data.gov.au-vocabularies.conf\")\n new = [\n \"anzsrc-for\",\n \"anzsrc-seo\",\n \"ausplots-cv\",\n \"australian-phone-area-codes\",\n \"care\",\n \"corveg-cv\",\n \"nrm\",\n \"reg-roles\",\n \"reg-statuses\",\n \"address-type\",\n \"australian-states-and-territories\",\n \"bc-labels\",\n \"data-access-rights\",\n \"dataciteroles\",\n \"depth-reference\",\n \"geo-commodities\",\n \"geoadminfeatures\",\n \"geofeatures\",\n \"geological-observation-instrument\",\n \"geological-observation-method\",\n \"geological-observation-type\",\n \"geological-sites\",\n \"geometry-roles\",\n \"georesource-report\",\n \"gsq-alias\",\n \"gsq-dataset-theme\",\n \"gsq-roles\",\n \"gsq-sample-facility\",\n \"iso639-1\",\n \"iso-19157-data-quality-dimension\",\n \"iso-iec-25012-data-quality-dimension\",\n \"nsw-quality-dimension\",\n \"party-identifier-type\",\n \"qg-agent\",\n \"qg-file-types\",\n \"qg-security-classifications\",\n \"qg-sites\",\n \"qld-data-licenses\",\n \"iso19115-1/RoleCode\",\n \"minerals\",\n \"nslvoc\",\n \"observation-detail-type\",\n \"organisation-activity-status\",\n \"organisation-name-types\",\n \"organisation-type\",\n \"party-relationship\",\n \"queensland-crs\",\n \"qld-resource-permit-status\",\n \"qld-resource-permit\",\n \"qld-utm-zones\",\n \"geou\",\n \"iso11179-6/RolesAndResponsibilities\",\n \"qesd-qkd\",\n \"qesd-uom\",\n \"qld-obsprop\",\n \"report-detail-type\",\n \"report-status\",\n \"resource-project-lifecycle\",\n \"resource-types\",\n \"result-type\",\n \"sample-detail-type\",\n \"sample-location-status\",\n \"sample-location-types\",\n \"sample-material\",\n \"sample-preparation-methods\",\n \"sample-relationship\",\n \"sample-type\",\n \"seismic-dimensionality\",\n \"site-detail-type\",\n \"site-relationships\",\n \"site-status\",\n \"supermodel/terms\",\n \"survey-detail-type\",\n \"survey-method\",\n \"survey-relationship-type\",\n \"survey-status\",\n \"survey-type\",\n \"telephone-type\",\n \"tk-labels\",\n \"trs\"\n ]\n lines = conf.readlines()\n\n for n in new:\n for line in lines:\n if n in line:\n pattern, match = line.split(\"$\", 1)\n print(pattern.strip().replace(\"RewriteRule ^\", \"https://linked.data.gov.au/\"), \" -- \", match.split(\"[R\")[0].replace('\"', '').strip())\n break", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import heapq as heap import networkx as nx import copy import random def remove_jumps(moves): res = [] for move in moves: if move[2] > 1: move[3].reverse() res.extend(make_moves_from_path(move[3])) else: res.append(move) return res def make_moves_from_path(path): moves = [] p = path[:] for i in range(len(p)-1): moves.append((p[i+1], p[i], 1, [p[i+1], p[i]])) return moves def find_nearest_hole(o,r,graph, start): visited, queue = [], [(start, [start])] results = [] while queue: (node, search_path) = queue.pop(0) if node not in visited: visited.append(node) adjacent = graph.adj[node] for neighbor in adjacent: if neighbor in o: if neighbor not in visited: queue.append((neighbor, search_path + [neighbor])) else: if neighbor != r: results.append(search_path + [neighbor]) moves = [] for res in results: moves.append((res[0], res[-1], len(res)-1, res)) return moves def move_robot(o,r,graph,node_from,node_to): obstacles = o[:] robot = r if not node_from == r: raise RuntimeError('node_from is not robot ' + node_from) if node_to in obstacles: raise RuntimeError('node_to is obstacle ' + node_to) robot = node_to return (obstacles,robot) def move_obstacle(o,r,graph,node_from,node_to): obstacles = o[:] robot = r if node_from not in obstacles: raise RuntimeError('node_from is not obstacle ' + node_from) if node_to in obstacles: raise RuntimeError('node_to is obstacle ' + node_to) if node_to == robot: raise RuntimeError('node_to is robot' + node_to) obstacles.append(node_to) obstacles.remove(node_from) return(obstacles,robot) def make_move(o,r,graph,node_from,node_to): if node_from == None: return (o, r) if( r == node_from): return move_robot(o,r,graph,node_from,node_to) if ( node_from in o): return move_obstacle(o,r,graph,node_from,node_to) raise RuntimeError('Cant move from ' + node_from) def make_moves(o,r,graph,moves): obstacles= o[:] robot = r for move in moves: obstacles,robot = make_move(obstacles,robot,graph,move[0],move[1]) return (obstacles,robot) def is_hole(o, r, node): if (node not in o): return True return False def possible_robot_moves(o, r, graph): moves=[] robot_node = r robot_neighbors = graph.adj[r] for neighbor in robot_neighbors: if is_hole(o,r,neighbor): moves.append((robot_node, neighbor, 1, [robot_node, neighbor])) return moves def possible_obstacle_moves(o,r,graph,obstacle): obstacle_neighbors = graph.adj[obstacle] moves = [] for neighbor in obstacle_neighbors: if is_hole(o,r,neighbor) and neighbor != r: moves.append((obstacle, neighbor, 1, [obstacle, neighbor])) else: if neighbor != r: nh = find_nearest_hole(o, r, graph, neighbor) if len(nh) > 0: moves.extend(find_nearest_hole(o,r,graph, neighbor)) return moves def possible_obstacles_moves(o,r,graph): moves = [] for obstacle in o: moves.extend(possible_obstacle_moves(o,r,graph,obstacle)) return moves def possible_moves(o,r,graph): moves = [] moves.extend(possible_robot_moves(o,r,graph)) moves.extend(possible_obstacles_moves(o,r,graph)) return moves def color(o,r,graph,node,target,start): if (node in o and node == target): return 'c' if node in o: return 'r' if node == r: return 'b' if node == start: return 'y' if node == target: return 'g' return 'w' def create_state(o, r): o.sort() return '-'.join(o) + ' ___ R = ' + r #__________________________________________________________________________________ def fitness_fun_heap(graph, obstacles, robot, target, num_of_moves): shortest = nx.shortest_path(graph,robot,target) score = -len(shortest) - num_of_moves for obstacle in obstacles: if obstacle in shortest: score = score - 1 return -score def solve_heap(o,r,graph,t): round = 0 visited = set([]) queue= [(-1000,[],o,r)] while queue: score,moves,obstacles,robot = heap.heappop(queue) obstacles.sort() st = ('#'.join(obstacles),robot) if ( st not in visited ): visited.add(st) score = fitness_fun_heap(graph,obstacles,robot,t,len(moves)) pm = possible_moves(obstacles,robot,graph) for move in pm: new_moves = moves[:] new_moves.append(move) newobstacles,newrobot = make_moves(obstacles,robot,graph,[move]) if t == newrobot: print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!") return new_moves round = round+1 if (round % 100000 == 0): print ("Visited = " + str(len(visited))) heap.heappush(queue,(score,new_moves,newobstacles,newrobot)) def solve_brute_force(o,r,graph,t): num_of_solutions = 0 all_solutions = [] round = 0 visited = set([]) queue = [([],o,r)] while queue: moves,obstacles,robot = queue.pop(0) obstacles.sort() st = ('#'.join(obstacles),robot) if ( st not in visited ): visited.add(st) pm = possible_moves(obstacles,robot,graph) for move in pm: new_moves = moves[:] new_moves.append(move) newobstacles,newrobot = make_moves(obstacles,robot,graph,[move]) if t == newrobot: all_solutions.append(new_moves) round = round+1 if (round % 100000 == 0): print ("Visited = " + str(len(visited))) queue.append((new_moves,newobstacles,newrobot)) print('Number of solutions: ' + str(len(all_solutions))) best = min(all_solutions, key = lambda x : len(x)) return best
normal
{ "blob_id": "800edfc61635564abf8297c4f33c59d48cc99960", "index": 4058, "step-1": "<mask token>\n\n\ndef make_moves_from_path(path):\n moves = []\n p = path[:]\n for i in range(len(p) - 1):\n moves.append((p[i + 1], p[i], 1, [p[i + 1], p[i]]))\n return moves\n\n\ndef find_nearest_hole(o, r, graph, start):\n visited, queue = [], [(start, [start])]\n results = []\n while queue:\n node, search_path = queue.pop(0)\n if node not in visited:\n visited.append(node)\n adjacent = graph.adj[node]\n for neighbor in adjacent:\n if neighbor in o:\n if neighbor not in visited:\n queue.append((neighbor, search_path + [neighbor]))\n elif neighbor != r:\n results.append(search_path + [neighbor])\n moves = []\n for res in results:\n moves.append((res[0], res[-1], len(res) - 1, res))\n return moves\n\n\ndef move_robot(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if not node_from == r:\n raise RuntimeError('node_from is not robot ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n robot = node_to\n return obstacles, robot\n\n\n<mask token>\n\n\ndef possible_robot_moves(o, r, graph):\n moves = []\n robot_node = r\n robot_neighbors = graph.adj[r]\n for neighbor in robot_neighbors:\n if is_hole(o, r, neighbor):\n moves.append((robot_node, neighbor, 1, [robot_node, neighbor]))\n return moves\n\n\ndef possible_obstacle_moves(o, r, graph, obstacle):\n obstacle_neighbors = graph.adj[obstacle]\n moves = []\n for neighbor in obstacle_neighbors:\n if is_hole(o, r, neighbor) and neighbor != r:\n moves.append((obstacle, neighbor, 1, [obstacle, neighbor]))\n elif neighbor != r:\n nh = find_nearest_hole(o, r, graph, neighbor)\n if len(nh) > 0:\n moves.extend(find_nearest_hole(o, r, graph, neighbor))\n return moves\n\n\n<mask token>\n\n\ndef possible_moves(o, r, graph):\n moves = []\n moves.extend(possible_robot_moves(o, r, graph))\n moves.extend(possible_obstacles_moves(o, r, graph))\n return moves\n\n\n<mask token>\n\n\ndef solve_heap(o, r, graph, t):\n round = 0\n visited = set([])\n queue = [(-1000, [], o, r)]\n while queue:\n score, moves, obstacles, robot = heap.heappop(queue)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n score = fitness_fun_heap(graph, obstacles, robot, t, len(moves))\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n return new_moves\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n heap.heappush(queue, (score, new_moves, newobstacles, newrobot)\n )\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef remove_jumps(moves):\n res = []\n for move in moves:\n if move[2] > 1:\n move[3].reverse()\n res.extend(make_moves_from_path(move[3]))\n else:\n res.append(move)\n return res\n\n\ndef make_moves_from_path(path):\n moves = []\n p = path[:]\n for i in range(len(p) - 1):\n moves.append((p[i + 1], p[i], 1, [p[i + 1], p[i]]))\n return moves\n\n\ndef find_nearest_hole(o, r, graph, start):\n visited, queue = [], [(start, [start])]\n results = []\n while queue:\n node, search_path = queue.pop(0)\n if node not in visited:\n visited.append(node)\n adjacent = graph.adj[node]\n for neighbor in adjacent:\n if neighbor in o:\n if neighbor not in visited:\n queue.append((neighbor, search_path + [neighbor]))\n elif neighbor != r:\n results.append(search_path + [neighbor])\n moves = []\n for res in results:\n moves.append((res[0], res[-1], len(res) - 1, res))\n return moves\n\n\ndef move_robot(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if not node_from == r:\n raise RuntimeError('node_from is not robot ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n robot = node_to\n return obstacles, robot\n\n\ndef move_obstacle(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if node_from not in obstacles:\n raise RuntimeError('node_from is not obstacle ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n if node_to == robot:\n raise RuntimeError('node_to is robot' + node_to)\n obstacles.append(node_to)\n obstacles.remove(node_from)\n return obstacles, robot\n\n\n<mask token>\n\n\ndef possible_robot_moves(o, r, graph):\n moves = []\n robot_node = r\n robot_neighbors = graph.adj[r]\n for neighbor in robot_neighbors:\n if is_hole(o, r, neighbor):\n moves.append((robot_node, neighbor, 1, [robot_node, neighbor]))\n return moves\n\n\ndef possible_obstacle_moves(o, r, graph, obstacle):\n obstacle_neighbors = graph.adj[obstacle]\n moves = []\n for neighbor in obstacle_neighbors:\n if is_hole(o, r, neighbor) and neighbor != r:\n moves.append((obstacle, neighbor, 1, [obstacle, neighbor]))\n elif neighbor != r:\n nh = find_nearest_hole(o, r, graph, neighbor)\n if len(nh) > 0:\n moves.extend(find_nearest_hole(o, r, graph, neighbor))\n return moves\n\n\n<mask token>\n\n\ndef possible_moves(o, r, graph):\n moves = []\n moves.extend(possible_robot_moves(o, r, graph))\n moves.extend(possible_obstacles_moves(o, r, graph))\n return moves\n\n\ndef color(o, r, graph, node, target, start):\n if node in o and node == target:\n return 'c'\n if node in o:\n return 'r'\n if node == r:\n return 'b'\n if node == start:\n return 'y'\n if node == target:\n return 'g'\n return 'w'\n\n\n<mask token>\n\n\ndef solve_heap(o, r, graph, t):\n round = 0\n visited = set([])\n queue = [(-1000, [], o, r)]\n while queue:\n score, moves, obstacles, robot = heap.heappop(queue)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n score = fitness_fun_heap(graph, obstacles, robot, t, len(moves))\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n return new_moves\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n heap.heappush(queue, (score, new_moves, newobstacles, newrobot)\n )\n\n\ndef solve_brute_force(o, r, graph, t):\n num_of_solutions = 0\n all_solutions = []\n round = 0\n visited = set([])\n queue = [([], o, r)]\n while queue:\n moves, obstacles, robot = queue.pop(0)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n all_solutions.append(new_moves)\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n queue.append((new_moves, newobstacles, newrobot))\n print('Number of solutions: ' + str(len(all_solutions)))\n best = min(all_solutions, key=lambda x: len(x))\n return best\n", "step-3": "<mask token>\n\n\ndef remove_jumps(moves):\n res = []\n for move in moves:\n if move[2] > 1:\n move[3].reverse()\n res.extend(make_moves_from_path(move[3]))\n else:\n res.append(move)\n return res\n\n\ndef make_moves_from_path(path):\n moves = []\n p = path[:]\n for i in range(len(p) - 1):\n moves.append((p[i + 1], p[i], 1, [p[i + 1], p[i]]))\n return moves\n\n\ndef find_nearest_hole(o, r, graph, start):\n visited, queue = [], [(start, [start])]\n results = []\n while queue:\n node, search_path = queue.pop(0)\n if node not in visited:\n visited.append(node)\n adjacent = graph.adj[node]\n for neighbor in adjacent:\n if neighbor in o:\n if neighbor not in visited:\n queue.append((neighbor, search_path + [neighbor]))\n elif neighbor != r:\n results.append(search_path + [neighbor])\n moves = []\n for res in results:\n moves.append((res[0], res[-1], len(res) - 1, res))\n return moves\n\n\ndef move_robot(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if not node_from == r:\n raise RuntimeError('node_from is not robot ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n robot = node_to\n return obstacles, robot\n\n\ndef move_obstacle(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if node_from not in obstacles:\n raise RuntimeError('node_from is not obstacle ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n if node_to == robot:\n raise RuntimeError('node_to is robot' + node_to)\n obstacles.append(node_to)\n obstacles.remove(node_from)\n return obstacles, robot\n\n\n<mask token>\n\n\ndef possible_robot_moves(o, r, graph):\n moves = []\n robot_node = r\n robot_neighbors = graph.adj[r]\n for neighbor in robot_neighbors:\n if is_hole(o, r, neighbor):\n moves.append((robot_node, neighbor, 1, [robot_node, neighbor]))\n return moves\n\n\ndef possible_obstacle_moves(o, r, graph, obstacle):\n obstacle_neighbors = graph.adj[obstacle]\n moves = []\n for neighbor in obstacle_neighbors:\n if is_hole(o, r, neighbor) and neighbor != r:\n moves.append((obstacle, neighbor, 1, [obstacle, neighbor]))\n elif neighbor != r:\n nh = find_nearest_hole(o, r, graph, neighbor)\n if len(nh) > 0:\n moves.extend(find_nearest_hole(o, r, graph, neighbor))\n return moves\n\n\n<mask token>\n\n\ndef possible_moves(o, r, graph):\n moves = []\n moves.extend(possible_robot_moves(o, r, graph))\n moves.extend(possible_obstacles_moves(o, r, graph))\n return moves\n\n\ndef color(o, r, graph, node, target, start):\n if node in o and node == target:\n return 'c'\n if node in o:\n return 'r'\n if node == r:\n return 'b'\n if node == start:\n return 'y'\n if node == target:\n return 'g'\n return 'w'\n\n\n<mask token>\n\n\ndef fitness_fun_heap(graph, obstacles, robot, target, num_of_moves):\n shortest = nx.shortest_path(graph, robot, target)\n score = -len(shortest) - num_of_moves\n for obstacle in obstacles:\n if obstacle in shortest:\n score = score - 1\n return -score\n\n\ndef solve_heap(o, r, graph, t):\n round = 0\n visited = set([])\n queue = [(-1000, [], o, r)]\n while queue:\n score, moves, obstacles, robot = heap.heappop(queue)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n score = fitness_fun_heap(graph, obstacles, robot, t, len(moves))\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n return new_moves\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n heap.heappush(queue, (score, new_moves, newobstacles, newrobot)\n )\n\n\ndef solve_brute_force(o, r, graph, t):\n num_of_solutions = 0\n all_solutions = []\n round = 0\n visited = set([])\n queue = [([], o, r)]\n while queue:\n moves, obstacles, robot = queue.pop(0)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n all_solutions.append(new_moves)\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n queue.append((new_moves, newobstacles, newrobot))\n print('Number of solutions: ' + str(len(all_solutions)))\n best = min(all_solutions, key=lambda x: len(x))\n return best\n", "step-4": "<mask token>\n\n\ndef remove_jumps(moves):\n res = []\n for move in moves:\n if move[2] > 1:\n move[3].reverse()\n res.extend(make_moves_from_path(move[3]))\n else:\n res.append(move)\n return res\n\n\ndef make_moves_from_path(path):\n moves = []\n p = path[:]\n for i in range(len(p) - 1):\n moves.append((p[i + 1], p[i], 1, [p[i + 1], p[i]]))\n return moves\n\n\ndef find_nearest_hole(o, r, graph, start):\n visited, queue = [], [(start, [start])]\n results = []\n while queue:\n node, search_path = queue.pop(0)\n if node not in visited:\n visited.append(node)\n adjacent = graph.adj[node]\n for neighbor in adjacent:\n if neighbor in o:\n if neighbor not in visited:\n queue.append((neighbor, search_path + [neighbor]))\n elif neighbor != r:\n results.append(search_path + [neighbor])\n moves = []\n for res in results:\n moves.append((res[0], res[-1], len(res) - 1, res))\n return moves\n\n\ndef move_robot(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if not node_from == r:\n raise RuntimeError('node_from is not robot ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n robot = node_to\n return obstacles, robot\n\n\ndef move_obstacle(o, r, graph, node_from, node_to):\n obstacles = o[:]\n robot = r\n if node_from not in obstacles:\n raise RuntimeError('node_from is not obstacle ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n if node_to == robot:\n raise RuntimeError('node_to is robot' + node_to)\n obstacles.append(node_to)\n obstacles.remove(node_from)\n return obstacles, robot\n\n\ndef make_move(o, r, graph, node_from, node_to):\n if node_from == None:\n return o, r\n if r == node_from:\n return move_robot(o, r, graph, node_from, node_to)\n if node_from in o:\n return move_obstacle(o, r, graph, node_from, node_to)\n raise RuntimeError('Cant move from ' + node_from)\n\n\n<mask token>\n\n\ndef is_hole(o, r, node):\n if node not in o:\n return True\n return False\n\n\ndef possible_robot_moves(o, r, graph):\n moves = []\n robot_node = r\n robot_neighbors = graph.adj[r]\n for neighbor in robot_neighbors:\n if is_hole(o, r, neighbor):\n moves.append((robot_node, neighbor, 1, [robot_node, neighbor]))\n return moves\n\n\ndef possible_obstacle_moves(o, r, graph, obstacle):\n obstacle_neighbors = graph.adj[obstacle]\n moves = []\n for neighbor in obstacle_neighbors:\n if is_hole(o, r, neighbor) and neighbor != r:\n moves.append((obstacle, neighbor, 1, [obstacle, neighbor]))\n elif neighbor != r:\n nh = find_nearest_hole(o, r, graph, neighbor)\n if len(nh) > 0:\n moves.extend(find_nearest_hole(o, r, graph, neighbor))\n return moves\n\n\ndef possible_obstacles_moves(o, r, graph):\n moves = []\n for obstacle in o:\n moves.extend(possible_obstacle_moves(o, r, graph, obstacle))\n return moves\n\n\ndef possible_moves(o, r, graph):\n moves = []\n moves.extend(possible_robot_moves(o, r, graph))\n moves.extend(possible_obstacles_moves(o, r, graph))\n return moves\n\n\ndef color(o, r, graph, node, target, start):\n if node in o and node == target:\n return 'c'\n if node in o:\n return 'r'\n if node == r:\n return 'b'\n if node == start:\n return 'y'\n if node == target:\n return 'g'\n return 'w'\n\n\ndef create_state(o, r):\n o.sort()\n return '-'.join(o) + ' ___ R = ' + r\n\n\ndef fitness_fun_heap(graph, obstacles, robot, target, num_of_moves):\n shortest = nx.shortest_path(graph, robot, target)\n score = -len(shortest) - num_of_moves\n for obstacle in obstacles:\n if obstacle in shortest:\n score = score - 1\n return -score\n\n\ndef solve_heap(o, r, graph, t):\n round = 0\n visited = set([])\n queue = [(-1000, [], o, r)]\n while queue:\n score, moves, obstacles, robot = heap.heappop(queue)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n score = fitness_fun_heap(graph, obstacles, robot, t, len(moves))\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n return new_moves\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n heap.heappush(queue, (score, new_moves, newobstacles, newrobot)\n )\n\n\ndef solve_brute_force(o, r, graph, t):\n num_of_solutions = 0\n all_solutions = []\n round = 0\n visited = set([])\n queue = [([], o, r)]\n while queue:\n moves, obstacles, robot = queue.pop(0)\n obstacles.sort()\n st = '#'.join(obstacles), robot\n if st not in visited:\n visited.add(st)\n pm = possible_moves(obstacles, robot, graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles, newrobot = make_moves(obstacles, robot, graph,\n [move])\n if t == newrobot:\n all_solutions.append(new_moves)\n round = round + 1\n if round % 100000 == 0:\n print('Visited = ' + str(len(visited)))\n queue.append((new_moves, newobstacles, newrobot))\n print('Number of solutions: ' + str(len(all_solutions)))\n best = min(all_solutions, key=lambda x: len(x))\n return best\n", "step-5": "import heapq as heap\nimport networkx as nx\nimport copy\nimport random\ndef remove_jumps(moves):\n\n res = []\n\n for move in moves:\n if move[2] > 1:\n move[3].reverse()\n res.extend(make_moves_from_path(move[3]))\n else:\n res.append(move)\n\n return res\n\n\ndef make_moves_from_path(path):\n\n moves = []\n p = path[:]\n\n for i in range(len(p)-1):\n moves.append((p[i+1], p[i], 1, [p[i+1], p[i]]))\n return moves\n\n\ndef find_nearest_hole(o,r,graph, start):\n visited, queue = [], [(start, [start])]\n results = []\n\n while queue:\n (node, search_path) = queue.pop(0)\n\n if node not in visited:\n visited.append(node)\n\n adjacent = graph.adj[node]\n\n for neighbor in adjacent:\n if neighbor in o:\n if neighbor not in visited:\n queue.append((neighbor, search_path + [neighbor]))\n else:\n if neighbor != r:\n results.append(search_path + [neighbor])\n\n moves = []\n for res in results:\n\n moves.append((res[0], res[-1], len(res)-1, res))\n return moves\n\ndef move_robot(o,r,graph,node_from,node_to):\n obstacles = o[:]\n robot = r\n if not node_from == r:\n raise RuntimeError('node_from is not robot ' + node_from)\n\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n robot = node_to\n return (obstacles,robot)\n\ndef move_obstacle(o,r,graph,node_from,node_to):\n obstacles = o[:]\n robot = r\n if node_from not in obstacles:\n raise RuntimeError('node_from is not obstacle ' + node_from)\n if node_to in obstacles:\n raise RuntimeError('node_to is obstacle ' + node_to)\n\n if node_to == robot:\n raise RuntimeError('node_to is robot' + node_to)\n\n obstacles.append(node_to)\n obstacles.remove(node_from)\n\n return(obstacles,robot)\n\ndef make_move(o,r,graph,node_from,node_to):\n\n if node_from == None:\n return (o, r)\n\n if( r == node_from):\n return move_robot(o,r,graph,node_from,node_to)\n if ( node_from in o):\n return move_obstacle(o,r,graph,node_from,node_to)\n\n raise RuntimeError('Cant move from ' + node_from)\n\ndef make_moves(o,r,graph,moves):\n obstacles= o[:]\n robot = r\n for move in moves:\n obstacles,robot = make_move(obstacles,robot,graph,move[0],move[1])\n return (obstacles,robot)\n\ndef is_hole(o, r, node):\n if (node not in o):\n return True\n return False\n\ndef possible_robot_moves(o, r, graph):\n moves=[]\n robot_node = r\n robot_neighbors = graph.adj[r]\n\n for neighbor in robot_neighbors:\n if is_hole(o,r,neighbor):\n moves.append((robot_node, neighbor, 1, [robot_node, neighbor]))\n return moves\n\ndef possible_obstacle_moves(o,r,graph,obstacle):\n obstacle_neighbors = graph.adj[obstacle]\n moves = []\n\n for neighbor in obstacle_neighbors:\n if is_hole(o,r,neighbor) and neighbor != r:\n moves.append((obstacle, neighbor, 1, [obstacle, neighbor]))\n else:\n if neighbor != r:\n nh = find_nearest_hole(o, r, graph, neighbor)\n if len(nh) > 0:\n moves.extend(find_nearest_hole(o,r,graph, neighbor))\n\n return moves\n\ndef possible_obstacles_moves(o,r,graph):\n moves = []\n for obstacle in o:\n moves.extend(possible_obstacle_moves(o,r,graph,obstacle))\n return moves\n\ndef possible_moves(o,r,graph):\n moves = []\n moves.extend(possible_robot_moves(o,r,graph))\n moves.extend(possible_obstacles_moves(o,r,graph))\n return moves\n\n\ndef color(o,r,graph,node,target,start):\n if (node in o and node == target):\n return 'c'\n if node in o:\n return 'r'\n if node == r:\n return 'b'\n if node == start:\n return 'y'\n if node == target:\n return 'g'\n return 'w'\n\n\ndef create_state(o, r):\n\n o.sort()\n return '-'.join(o) + ' ___ R = ' + r\n\n#__________________________________________________________________________________\n\ndef fitness_fun_heap(graph, obstacles, robot, target, num_of_moves):\n shortest = nx.shortest_path(graph,robot,target)\n score = -len(shortest) - num_of_moves\n\n for obstacle in obstacles:\n if obstacle in shortest:\n score = score - 1\n\n return -score\n\n\n\ndef solve_heap(o,r,graph,t):\n round = 0\n visited = set([])\n queue= [(-1000,[],o,r)]\n while queue:\n score,moves,obstacles,robot = heap.heappop(queue)\n obstacles.sort()\n st = ('#'.join(obstacles),robot)\n if ( st not in visited ):\n visited.add(st)\n score = fitness_fun_heap(graph,obstacles,robot,t,len(moves))\n pm = possible_moves(obstacles,robot,graph)\n\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles,newrobot = make_moves(obstacles,robot,graph,[move])\n if t == newrobot:\n print(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n return new_moves\n\n round = round+1\n if (round % 100000 == 0):\n print (\"Visited = \" + str(len(visited)))\n heap.heappush(queue,(score,new_moves,newobstacles,newrobot))\n\n\n\n\n\ndef solve_brute_force(o,r,graph,t):\n num_of_solutions = 0\n all_solutions = []\n\n round = 0\n visited = set([])\n queue = [([],o,r)]\n while queue:\n moves,obstacles,robot = queue.pop(0)\n obstacles.sort()\n st = ('#'.join(obstacles),robot)\n if ( st not in visited ):\n visited.add(st)\n\n pm = possible_moves(obstacles,robot,graph)\n for move in pm:\n new_moves = moves[:]\n new_moves.append(move)\n newobstacles,newrobot = make_moves(obstacles,robot,graph,[move])\n if t == newrobot:\n all_solutions.append(new_moves)\n\n round = round+1\n\n if (round % 100000 == 0):\n print (\"Visited = \" + str(len(visited)))\n queue.append((new_moves,newobstacles,newrobot))\n\n\n print('Number of solutions: ' + str(len(all_solutions)))\n\n best = min(all_solutions, key = lambda x : len(x))\n\n return best\n", "step-ids": [ 7, 11, 12, 16, 19 ] }
[ 7, 11, 12, 16, 19 ]
# -*- coding: utf-8 -*- ########### SVN repository information ################### # $Date: $ # $Author: $ # $Revision: $ # $URL: $ # $Id: $ ########### SVN repository information ################### ''' *GSASIIfpaGUI: Fundamental Parameters Routines* =============================================== This module contains routines for getting Fundamental Parameters Approach (FPA) input, setting up for running the NIST XRD Fundamental Parameters Code, plotting the convolutors and computing a set of peaks generated by that code. ''' from __future__ import division, print_function import wx import os.path import numpy as np import NIST_profile as FP import GSASIIpath import GSASIIctrlGUI as G2G import GSASIIdataGUI as G2gd import GSASIIplot as G2plt import GSASIImath as G2mth import GSASIIpwd as G2pwd simParms = {} '''Parameters to set range for pattern simulation ''' parmDict = {'numWave':2} '''Parameter dict used for reading Topas-style values. These are converted to SI units and placed into :data:`NISTparms` ''' NISTparms = {} '''Parameters in a nested dict, with an entry for each concolutor. Entries in those dicts have values in SI units (of course). NISTparms can be can be input directly or can be from created from :data:`parmDict` by :func:`XferFPAsettings` ''' BraggBrentanoParms = [ ('divergence', 0.5, 'Bragg-Brentano divergence angle (degrees)'), ('soller_angle', 2.0, 'Soller slit axial divergence (degrees)'), ('Rs', 220, 'Diffractometer radius (mm)'), ('filament_length', 12., 'X-ray tube line focus length (mm)'), ('sample_length', 12., 'Illuminated sample length in axial direction (mm)'), ('receiving_slit_length', 12., 'Length of receiving slit in axial direction (mm)'), ('LAC_cm', 0.,'Linear absorption coef. adjusted for packing density (cm-1)'), ('sample_thickness', 1., 'Depth of sample (mm)'), ('convolution_steps', 8, 'Number of Fourier-space bins per two-theta step'), ('tube-tails_width', 0.04,'Tube filament width, in projection at takeoff angle (mm)'), ('tube-tails_L-tail', -1.,'Left-side tube tails width, in projection (mm)'), ('tube-tails_R-tail', 1.,'Right-side tube tails width, in projection (mm)'), ('tube-tails_rel-I', 0.001,'Tube tails fractional intensity (no units)'), ] '''FPA dict entries used in :func:`MakeTopasFPASizer`. Tuple contains a dict key, a default value and a description. These are the parameters needed for all Bragg Brentano instruments ''' BBPointDetector = [ ('receiving_slit_width', 0.2, 'Width of receiving slit (mm)'),] '''Additional FPA dict entries used in :func:`MakeTopasFPASizer` needed for Bragg Brentano instruments with point detectors. ''' BBPSDDetector = [ ('lpsd_th2_angular_range', 3.0, 'Angular range observed by PSD (degrees 2Theta)'), ('lpsd_equitorial_divergence', 0.1, 'Equatorial divergence of the primary beam (degrees)'),] '''Additional FPA dict entries used in :func:`MakeTopasFPASizer` needed for Bragg Brentano instruments with linear (1-D) PSD detectors. ''' Citation = '''MH Mendenhall, K Mullen && JP Cline. (2015) J. Res. of NIST 120, 223-251. doi:10.6028/jres.120.014. ''' def SetCu2Wave(): '''Set the parameters to the two-line Cu K alpha 1+2 spectrum ''' parmDict['wave'] = {i:v for i,v in enumerate((1.540596,1.544493))} parmDict['int'] = {i:v for i,v in enumerate((0.653817, 0.346183))} parmDict['lwidth'] = {i:v for i,v in enumerate((0.501844,0.626579))} SetCu2Wave() # use these as default def MakeTopasFPASizer(G2frame,FPdlg,mode,SetButtonStatus): '''Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. Parameter input is modeled after Topas input parameters. :param wx.Window FPdlg: Frame or Dialog where GUI will appear :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or (linear) position sensitive detector :param dict parmDict: dict to place parameters. If empty, default values from globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in the array. :returns: a sizer with the GUI controls ''' def _onOK(event): XferFPAsettings(parmDict) SetButtonStatus(done=True) # done=True triggers the simulation FPdlg.Destroy() def _onClose(event): SetButtonStatus() FPdlg.Destroy() def _onAddWave(event): parmDict['numWave'] += 1 wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus) def _onRemWave(event): parmDict['numWave'] -= 1 wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus) def _onSetCu5Wave(event): parmDict['wave'] = {i:v for i,v in enumerate((1.534753,1.540596,1.541058,1.54441,1.544721))} parmDict['int'] = {i:v for i,v in enumerate((0.0159, 0.5791, 0.0762, 0.2417, 0.0871))} parmDict['lwidth'] = {i:v for i,v in enumerate((3.6854, 0.437, 0.6, 0.52, 0.62))} parmDict['numWave'] = 5 wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus) def _onSetCu2Wave(event): SetCu2Wave() parmDict['numWave'] = 2 wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus) def _onSetPoint(event): wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,'BBpoint',SetButtonStatus) def _onSetPSD(event): wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,'BBPSD',SetButtonStatus) def PlotTopasFPA(event): XferFPAsettings(parmDict) ttArr = np.arange(max(0.5, simParms['plotpos']-simParms['calcwid']), simParms['plotpos']+simParms['calcwid'], simParms['step']) intArr = np.zeros_like(ttArr) NISTpk = setupFPAcalc() try: center_bin_idx,peakObj = doFPAcalc( NISTpk,ttArr,simParms['plotpos'],simParms['calcwid'], simParms['step']) except Exception as err: msg = "Error computing convolution, revise input" print(msg) print(err) return G2plt.PlotFPAconvolutors(G2frame,NISTpk) pkPts = len(peakObj.peak) pkMax = peakObj.peak.max() startInd = center_bin_idx-(pkPts//2) #this should be the aligned start of the new data # scale peak so max I=10,000 and add into intensity array if startInd < 0: intArr[:startInd+pkPts] += 10000 * peakObj.peak[-startInd:]/pkMax elif startInd > len(intArr): return elif startInd+pkPts >= len(intArr): offset = pkPts - len( intArr[startInd:] ) intArr[startInd:startInd+pkPts-offset] += 10000 * peakObj.peak[:-offset]/pkMax else: intArr[startInd:startInd+pkPts] += 10000 * peakObj.peak/pkMax G2plt.PlotXY(G2frame, [(ttArr, intArr)], labelX=r'$2\theta, deg$', labelY=r'Intensity (arbitrary)', Title='FPA peak', newPlot=True, lines=True) if FPdlg.GetSizer(): FPdlg.GetSizer().Clear(True) numWave = parmDict['numWave'] if mode == 'BBpoint': itemList = BraggBrentanoParms+BBPointDetector elif mode == 'BBPSD': itemList = BraggBrentanoParms+BBPSDDetector else: raise Exception('Unknown mode in MakeTopasFPASizer: '+mode) MainSizer = wx.BoxSizer(wx.VERTICAL) MainSizer.Add((-1,5)) waveSizer = wx.FlexGridSizer(cols=numWave+1,hgap=3,vgap=5) for lbl,prm,defVal in zip( (u'Wavelength (\u212b)','Rel. Intensity',u'Lorentz Width\n(\u212b/1000)'), ('wave','int','lwidth'), (0.0, 1.0, 0.1), ): text = wx.StaticText(FPdlg,wx.ID_ANY,lbl,style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) waveSizer.Add(text,0,wx.EXPAND) if prm not in parmDict: parmDict[prm] = {} for i in range(numWave): if i not in parmDict[prm]: parmDict[prm][i] = defVal ctrl = G2G.ValidatedTxtCtrl(FPdlg,parmDict[prm],i,size=(90,-1)) waveSizer.Add(ctrl,1,wx.ALIGN_CENTER_VERTICAL,1) MainSizer.Add(waveSizer) MainSizer.Add((-1,5)) btnsizer = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(FPdlg, wx.ID_ANY,'Add col') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onAddWave) btn = wx.Button(FPdlg, wx.ID_ANY,'Remove col') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onRemWave) btn = wx.Button(FPdlg, wx.ID_ANY,'CuKa1+2') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onSetCu2Wave) btn = wx.Button(FPdlg, wx.ID_ANY,'CuKa-5wave') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onSetCu5Wave) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,5)) btnsizer = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(FPdlg, wx.ID_ANY,'Point Dect.') btn.Enable(not mode == 'BBpoint') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onSetPoint) btn = wx.Button(FPdlg, wx.ID_ANY,'PSD') btn.Enable(not mode == 'BBPSD') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onSetPSD) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,5)) prmSizer = wx.FlexGridSizer(cols=3,hgap=3,vgap=5) text = wx.StaticText(FPdlg,wx.ID_ANY,'label',style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) prmSizer.Add(text,0,wx.EXPAND) text = wx.StaticText(FPdlg,wx.ID_ANY,'value',style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) prmSizer.Add(text,0,wx.EXPAND) text = wx.StaticText(FPdlg,wx.ID_ANY,'explanation',style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) prmSizer.Add(text,0,wx.EXPAND) for lbl,defVal,text in itemList: prmSizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,lbl),1,wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL,1) if lbl not in parmDict: parmDict[lbl] = defVal ctrl = G2G.ValidatedTxtCtrl(FPdlg,parmDict,lbl,size=(70,-1)) prmSizer.Add(ctrl,1,wx.ALL|wx.ALIGN_CENTER_VERTICAL,1) txt = wx.StaticText(FPdlg,wx.ID_ANY,text,size=(400,-1)) txt.Wrap(380) prmSizer.Add(txt) MainSizer.Add(prmSizer) MainSizer.Add((-1,4),1,wx.EXPAND,1) btnsizer = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,PlotTopasFPA) btnsizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,' at ')) if 'plotpos' not in simParms: simParms['plotpos'] = simParms['minTT'] ctrl = G2G.ValidatedTxtCtrl(FPdlg,simParms,'plotpos',size=(70,-1)) btnsizer.Add(ctrl) btnsizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,' deg.')) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,4),1,wx.EXPAND,1) btnsizer = wx.BoxSizer(wx.HORIZONTAL) OKbtn = wx.Button(FPdlg, wx.ID_OK) OKbtn.SetDefault() btnsizer.Add(OKbtn) Cbtn = wx.Button(FPdlg, wx.ID_CLOSE,"Cancel") btnsizer.Add(Cbtn) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,4),1,wx.EXPAND,1) # bindings for close of window OKbtn.Bind(wx.EVT_BUTTON,_onOK) Cbtn.Bind(wx.EVT_BUTTON,_onClose) FPdlg.SetSizer(MainSizer) MainSizer.Layout() MainSizer.Fit(FPdlg) FPdlg.SetMinSize(FPdlg.GetSize()) FPdlg.SendSizeEvent() def XferFPAsettings(InpParms): '''convert Topas-type parameters to SI units for NIST and place in a dict sorted according to use in each convoluter :param dict InpParms: a dict with Topas-like parameters, as set in :func:`MakeTopasFPASizer` :returns: a nested dict with global parameters and those for each convolution ''' wavenums = range(InpParms['numWave']) source_wavelengths_m = 1.e-10 * np.array([InpParms['wave'][i] for i in wavenums]) la = [InpParms['int'][i] for i in wavenums] source_intensities = np.array(la)/max(la) source_lor_widths_m = 1.e-10 * 1.e-3 * np.array([InpParms['lwidth'][i] for i in wavenums]) source_gauss_widths_m = 1.e-10 * 1.e-3 * np.array([0.001 for i in wavenums]) NISTparms["emission"] = {'emiss_wavelengths' : source_wavelengths_m, 'emiss_intensities' : source_intensities, 'emiss_gauss_widths' : source_gauss_widths_m, 'emiss_lor_widths' : source_lor_widths_m, 'crystallite_size_gauss' : 1.e-9 * InpParms.get('Size_G',1e6), 'crystallite_size_lor' : 1.e-9 * InpParms.get('Size_L',1e6)} if InpParms['filament_length'] == InpParms['receiving_slit_length']: # workaround: InpParms['receiving_slit_length'] *= 1.00001 # avoid bug when slit lengths are identical NISTparms["axial"] = { 'axDiv':"full", 'slit_length_source' : 1e-3*InpParms['filament_length'], 'slit_length_target' : 1e-3*InpParms['receiving_slit_length'], 'length_sample' : 1e-3 * InpParms['sample_length'], 'n_integral_points' : 10, 'angI_deg' : InpParms['soller_angle'], 'angD_deg': InpParms['soller_angle'] } if InpParms.get('LAC_cm',0) > 0: NISTparms["absorption"] = { 'absorption_coefficient': InpParms['LAC_cm']*100, #like LaB6, in m^(-1) 'sample_thickness': 1e-3 * InpParms['sample_thickness'], } elif "absorption" in NISTparms: del NISTparms["absorption"] if InpParms.get('lpsd_equitorial_divergence',0) > 0 and InpParms.get( 'lpsd_th2_angular_range',0) > 0: PSDdetector_length_mm=np.arcsin(np.pi*InpParms['lpsd_th2_angular_range']/180. )*InpParms['Rs'] # mm NISTparms["si_psd"] = { 'equatorial_divergence_deg': InpParms['lpsd_equitorial_divergence'], 'si_psd_window_bounds': (0.,PSDdetector_length_mm/1000.) } elif "si_psd" in NISTparms: del NISTparms["si_psd"] if InpParms.get('Specimen_Displacement'): NISTparms["displacement"] = {'specimen_displacement': 1e-3 * InpParms['Specimen_Displacement']} elif "displacement" in NISTparms: del NISTparms["displacement"] if InpParms.get('receiving_slit_width'): NISTparms["receiver_slit"] = {'slit_width':1e-3*InpParms['receiving_slit_width']} elif "receiver_slit" in NISTparms: del NISTparms["receiver_slit"] if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get( 'tube-tails_rel-I',0) > 0: NISTparms["tube_tails"] = { 'main_width' : 1e-3 * InpParms.get('tube-tails_width', 0.), 'tail_left' : -1e-3 * InpParms.get('tube-tails_L-tail',0.), 'tail_right' : 1e-3 * InpParms.get('tube-tails_R-tail',0.), 'tail_intens' : InpParms.get('tube-tails_rel-I',0.),} elif "tube_tails" in NISTparms: del NISTparms["tube_tails"] # set Global parameters max_wavelength = source_wavelengths_m[np.argmax(source_intensities)] NISTparms[""] = { 'equatorial_divergence_deg' : InpParms['divergence'], 'dominant_wavelength' : max_wavelength, 'diffractometer_radius' : 1e-3* InpParms['Rs'], 'oversampling' : InpParms['convolution_steps'], } def setupFPAcalc(): '''Create a peak profile object using the NIST XRD Fundamental Parameters Code. :returns: a profile object that can provide information on each convolution or compute the composite peak shape. ''' p=FP.FP_profile(anglemode="twotheta", output_gaussian_smoother_bins_sigma=1.0, oversampling=NISTparms.get('oversampling',10)) p.debug_cache=False #set parameters for each convolver for key in NISTparms: if key: p.set_parameters(convolver=key,**NISTparms[key]) else: p.set_parameters(**NISTparms[key]) return p def doFPAcalc(NISTpk,ttArr,twotheta,calcwid,step): '''Compute a single peak using a NIST profile object :param object NISTpk: a peak profile computational object from the NIST XRD Fundamental Parameters Code, typically established from a call to :func:`SetupFPAcalc` :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees) :param float twotheta: nominal center of peak (degrees) :param float calcwid: width to perform convolution (degrees) :param float step: step size ''' # find closest point to twotheta (may be outside limits of the array) center_bin_idx=min(ttArr.searchsorted(twotheta),len(ttArr)-1) NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step, twotheta_window_center_deg=ttArr[center_bin_idx], twotheta_approx_window_fullwidth_deg=calcwid, ) NISTpk.set_parameters(twotheta0_deg=twotheta) return center_bin_idx,NISTpk.compute_line_profile() def MakeSimSizer(G2frame, dlg): '''Create a GUI to get simulation with parameters for Fundamental Parameters fitting. :param wx.Window dlg: Frame or Dialog where GUI will appear :returns: a sizer with the GUI controls ''' def _onOK(event): msg = '' if simParms['minTT']-simParms['calcwid']/1.5 < 0.1: msg += 'First peak minus half the calc width is too low' if simParms['maxTT']+simParms['calcwid']/1.5 > 175: if msg: msg += '\n' msg += 'Last peak plus half the calc width is too high' if simParms['npeaks'] < 8: if msg: msg += '\n' msg += 'At least 8 peaks are needed' if msg: G2G.G2MessageBox(dlg,msg,'Bad input, try again') return # compute "obs" pattern ttArr = np.arange(max(0.5, simParms['minTT']-simParms['calcwid']/1.5), simParms['maxTT']+simParms['calcwid']/1.5, simParms['step']) intArr = np.zeros_like(ttArr) peaklist = np.linspace(simParms['minTT'],simParms['maxTT'], simParms['npeaks'],endpoint=True) peakSpacing = (peaklist[-1]-peaklist[0])/(len(peaklist)-1) NISTpk = setupFPAcalc() minPtsHM = len(intArr) # initialize points above half-max maxPtsHM = 0 for num,twoth_peak in enumerate(peaklist): try: center_bin_idx,peakObj = doFPAcalc( NISTpk,ttArr,twoth_peak,simParms['calcwid'], simParms['step']) except: if msg: msg += '\n' msg = "Error computing convolution, revise input" continue if num == 0: G2plt.PlotFPAconvolutors(G2frame,NISTpk) pkMax = peakObj.peak.max() pkPts = len(peakObj.peak) minPtsHM = min(minPtsHM,sum(peakObj.peak >= 0.5*pkMax)) # points above half-max maxPtsHM = max(maxPtsHM,sum(peakObj.peak >= 0.5*pkMax)) # points above half-max startInd = center_bin_idx-(pkPts//2) #this should be the aligned start of the new data # scale peak so max I=10,000 and add into intensity array if startInd < 0: intArr[:startInd+pkPts] += 10000 * peakObj.peak[-startInd:]/pkMax elif startInd > len(intArr): break elif startInd+pkPts >= len(intArr): offset = pkPts - len( intArr[startInd:] ) intArr[startInd:startInd+pkPts-offset] += 10000 * peakObj.peak[:-offset]/pkMax else: intArr[startInd:startInd+pkPts] += 10000 * peakObj.peak/pkMax # check if peaks are too closely spaced if maxPtsHM*simParms['step'] > peakSpacing/4: if msg: msg += '\n' msg += 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'.format( maxPtsHM*simParms['step'], peakSpacing) # check if too few points across Hmax if minPtsHM < 10: if msg: msg += '\n' msg += 'There are only {} points above the half-max. 10 are needed. Dropping step size.'.format(minPtsHM) simParms['step'] *= 0.5 if msg: G2G.G2MessageBox(dlg,msg,'Bad input, try again') wx.CallAfter(MakeSimSizer,G2frame, dlg) return # pattern has been computed successfully dlg.Destroy() wx.CallAfter(FitFPApeaks,ttArr, intArr, peaklist, maxPtsHM) # do peakfit outside event callback def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM): '''Perform a peak fit to the FP simulated pattern ''' plswait = wx.Dialog(G2frame,style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add((1,1),1,wx.ALL|wx.EXPAND,1) txt = wx.StaticText(plswait,wx.ID_ANY, 'Fitting peaks...\nPlease wait...', style=wx.ALIGN_CENTER) vbox.Add(txt,0,wx.ALL|wx.EXPAND) vbox.Add((1,1),1,wx.ALL|wx.EXPAND,1) plswait.SetSizer(vbox) plswait.Layout() plswait.CenterOnParent() plswait.Show() # post "please wait" wx.BeginBusyCursor() # pick out one or two most intense wavelengths ints = list(NISTparms['emission']['emiss_intensities']) Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)]*1e10 if len(ints) > 1: ints[np.argmax(ints)] = -1 Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)]*1e10 else: Lam2 = None histId = G2frame.AddSimulatedPowder(ttArr,intArr, 'NIST Fundamental Parameters simulation', Lam1,Lam2) controls = G2frame.GPXtree.GetItemPyData( G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Controls')) controldat = controls.get('data', {'deriv type':'analytic','min dM/M':0.001,}) #fil Parms,Parms2 = G2frame.GPXtree.GetItemPyData( G2gd.GetGPXtreeItemId(G2frame,histId,'Instrument Parameters')) peakData = G2frame.GPXtree.GetItemPyData( G2gd.GetGPXtreeItemId(G2frame,histId,'Peak List')) # set background to 0 with one term = 0; disable refinement bkg1,bkg2 = bkg = G2frame.GPXtree.GetItemPyData( G2gd.GetGPXtreeItemId(G2frame,histId,'Background')) bkg1[1]=False bkg1[2]=0 bkg1[3]=0.0 limits = G2frame.GPXtree.GetItemPyData( G2gd.GetGPXtreeItemId(G2frame,histId,'Limits')) # approximate asym correction try: Parms['SH/L'][1] = 0.25 * ( NISTparms['axial']['length_sample']+ NISTparms['axial']['slit_length_source'] ) / NISTparms['']['diffractometer_radius'] except: pass for pos in peaklist: i = ttArr.searchsorted(pos) area = sum(intArr[max(0,i-maxPtsHM):min(len(intArr),i+maxPtsHM)]) peakData['peaks'].append(G2mth.setPeakparms(Parms,Parms2,pos,area)) histData = G2frame.GPXtree.GetItemPyData(histId) # refine peak positions only bxye = np.zeros(len(histData[1][1])) peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'], bkg,limits[1], Parms,Parms2,histData[1],bxye,[], False,controldat,None)[0] # refine peak areas as well for pk in peakData['peaks']: pk[1] = True peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'], bkg,limits[1], Parms,Parms2,histData[1],bxye,[], False,controldat)[0] # refine profile function for p in ('U', 'V', 'W', 'X', 'Y'): Parms[p][2] = True peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'], bkg,limits[1], Parms,Parms2,histData[1],bxye,[], False,controldat)[0] # add in asymmetry Parms['SH/L'][2] = True peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'], bkg,limits[1], Parms,Parms2,histData[1],bxye,[], False,controldat)[0] # reset "initial" profile for p in Parms: if len(Parms[p]) == 3: Parms[p][0] = Parms[p][1] Parms[p][2] = False wx.EndBusyCursor() plswait.Destroy() # remove "please wait" # save Iparms pth = G2G.GetExportPath(G2frame) fldlg = wx.FileDialog(G2frame, 'Set name to save GSAS-II instrument parameters file', pth, '', 'instrument parameter files (*.instprm)|*.instprm',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT) try: if fldlg.ShowModal() == wx.ID_OK: filename = fldlg.GetPath() # make sure extension is .instprm filename = os.path.splitext(filename)[0]+'.instprm' File = open(filename,'w') File.write("#GSAS-II instrument parameter file; do not add/delete items!\n") for item in Parms: File.write(item+':'+str(Parms[item][1])+'\n') File.close() print ('Instrument parameters saved to: '+filename) finally: fldlg.Destroy() #GSASIIpath.IPyBreak() def _onClose(event): dlg.Destroy() def SetButtonStatus(done=False): OKbtn.Enable(bool(NISTparms)) saveBtn.Enable(bool(NISTparms)) if done: _onOK(None) def _onSetFPA(event): # Create a non-modal dialog for Topas-style FP input. FPdlg = wx.Dialog(dlg,wx.ID_ANY,'FPA parameters', style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) MakeTopasFPASizer(G2frame,FPdlg,'BBpoint',SetButtonStatus) FPdlg.CenterOnParent() FPdlg.Raise() FPdlg.Show() def _onSaveFPA(event): filename = G2G.askSaveFile(G2frame,'','.NISTfpa', 'dict of NIST FPA values',dlg) if not filename: return fp = open(filename,'w') fp.write('# parameters to be used in the NIST XRD Fundamental Parameters program\n') fp.write('{\n') for key in sorted(NISTparms): fp.write(" '"+key+"' : "+str(NISTparms[key])+",") if not key: fp.write(' # global parameters') fp.write('\n') fp.write('}\n') fp.close() def _onReadFPA(event): filename = G2G.GetImportFile(G2frame, message='Read file with dict of values for NIST Fundamental Parameters', parent=dlg, wildcard='dict of NIST FPA values|*.NISTfpa') if not filename: return if not filename[0]: return try: txt = open(filename[0],'r').read() NISTparms.clear() array = np.array d = eval(txt) NISTparms.update(d) except Exception as err: G2G.G2MessageBox(dlg, u'Error reading file {}:{}\n'.format(filename,err), 'Bad dict input') #GSASIIpath.IPyBreak() SetButtonStatus() if dlg.GetSizer(): dlg.GetSizer().Clear(True) MainSizer = wx.BoxSizer(wx.VERTICAL) MainSizer.Add(wx.StaticText(dlg,wx.ID_ANY, 'Fit Profile Parameters to Peaks from Fundamental Parameters', style=wx.ALIGN_CENTER),0,wx.EXPAND) MainSizer.Add((-1,5)) prmSizer = wx.FlexGridSizer(cols=2,hgap=3,vgap=5) text = wx.StaticText(dlg,wx.ID_ANY,'value',style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) prmSizer.Add(text,0,wx.EXPAND) text = wx.StaticText(dlg,wx.ID_ANY,'explanation',style=wx.ALIGN_CENTER) text.SetBackgroundColour(wx.WHITE) prmSizer.Add(text,0,wx.EXPAND) for key,defVal,text in ( ('minTT',3.,'Location of first peak in 2theta (deg)'), ('maxTT',123.,'Location of last peak in 2theta (deg)'), ('step',0.01,'Pattern step size (deg 2theta)'), ('npeaks',13.,'Number of peaks'), ('calcwid',2.,'Range to compute each peak (deg 2theta)'), ): if key not in simParms: simParms[key] = defVal ctrl = G2G.ValidatedTxtCtrl(dlg,simParms,key,size=(70,-1)) prmSizer.Add(ctrl,1,wx.ALL|wx.ALIGN_CENTER_VERTICAL,1) txt = wx.StaticText(dlg,wx.ID_ANY,text,size=(300,-1)) txt.Wrap(280) prmSizer.Add(txt) MainSizer.Add(prmSizer) btnsizer = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(dlg, wx.ID_ANY,'Input FP vals') btnsizer.Add(btn) btn.Bind(wx.EVT_BUTTON,_onSetFPA) saveBtn = wx.Button(dlg, wx.ID_ANY,'Save FPA dict') btnsizer.Add(saveBtn) saveBtn.Bind(wx.EVT_BUTTON,_onSaveFPA) readBtn = wx.Button(dlg, wx.ID_ANY,'Read FPA dict') btnsizer.Add(readBtn) readBtn.Bind(wx.EVT_BUTTON,_onReadFPA) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,4),1,wx.EXPAND,1) txt = wx.StaticText(dlg,wx.ID_ANY, 'If you use this, please cite: '+Citation, size=(350,-1)) txt.Wrap(340) MainSizer.Add(txt,0,wx.ALIGN_CENTER) btnsizer = wx.BoxSizer(wx.HORIZONTAL) OKbtn = wx.Button(dlg, wx.ID_OK) OKbtn.SetDefault() btnsizer.Add(OKbtn) Cbtn = wx.Button(dlg, wx.ID_CLOSE,"Cancel") btnsizer.Add(Cbtn) MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0) MainSizer.Add((-1,4),1,wx.EXPAND,1) # bindings for close of window OKbtn.Bind(wx.EVT_BUTTON,_onOK) Cbtn.Bind(wx.EVT_BUTTON,_onClose) SetButtonStatus() dlg.SetSizer(MainSizer) MainSizer.Layout() MainSizer.Fit(dlg) dlg.SetMinSize(dlg.GetSize()) dlg.SendSizeEvent() dlg.Raise() def GetFPAInput(G2frame): dlg = wx.Dialog(G2frame,wx.ID_ANY,'FPA input', style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) MakeSimSizer(G2frame,dlg) dlg.CenterOnParent() dlg.Show() return
normal
{ "blob_id": "3b1426e0f29093e1e462765bcf1d351a064b9639", "index": 142, "step-1": "<mask token>\n\n\ndef SetCu2Wave():\n \"\"\"Set the parameters to the two-line Cu K alpha 1+2 spectrum\n \"\"\"\n parmDict['wave'] = {i: v for i, v in enumerate((1.540596, 1.544493))}\n parmDict['int'] = {i: v for i, v in enumerate((0.653817, 0.346183))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((0.501844, 0.626579))}\n\n\n<mask token>\n\n\ndef MakeTopasFPASizer(G2frame, FPdlg, mode, SetButtonStatus):\n \"\"\"Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. \n Parameter input is modeled after Topas input parameters.\n\n :param wx.Window FPdlg: Frame or Dialog where GUI will appear\n :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or \n (linear) position sensitive detector\n :param dict parmDict: dict to place parameters. If empty, default values from \n globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in \n the array. \n :returns: a sizer with the GUI controls\n \n \"\"\"\n\n def _onOK(event):\n XferFPAsettings(parmDict)\n SetButtonStatus(done=True)\n FPdlg.Destroy()\n\n def _onClose(event):\n SetButtonStatus()\n FPdlg.Destroy()\n\n def _onAddWave(event):\n parmDict['numWave'] += 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onRemWave(event):\n parmDict['numWave'] -= 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu5Wave(event):\n parmDict['wave'] = {i: v for i, v in enumerate((1.534753, 1.540596,\n 1.541058, 1.54441, 1.544721))}\n parmDict['int'] = {i: v for i, v in enumerate((0.0159, 0.5791, \n 0.0762, 0.2417, 0.0871))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((3.6854, 0.437, \n 0.6, 0.52, 0.62))}\n parmDict['numWave'] = 5\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu2Wave(event):\n SetCu2Wave()\n parmDict['numWave'] = 2\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetPoint(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBpoint',\n SetButtonStatus)\n\n def _onSetPSD(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBPSD',\n SetButtonStatus)\n\n def PlotTopasFPA(event):\n XferFPAsettings(parmDict)\n ttArr = np.arange(max(0.5, simParms['plotpos'] - simParms['calcwid'\n ]), simParms['plotpos'] + simParms['calcwid'], simParms['step'])\n intArr = np.zeros_like(ttArr)\n NISTpk = setupFPAcalc()\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr, simParms[\n 'plotpos'], simParms['calcwid'], simParms['step'])\n except Exception as err:\n msg = 'Error computing convolution, revise input'\n print(msg)\n print(err)\n return\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkPts = len(peakObj.peak)\n pkMax = peakObj.peak.max()\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n return\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset] += 10000 * peakObj.peak[\n :-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts] += 10000 * peakObj.peak / pkMax\n G2plt.PlotXY(G2frame, [(ttArr, intArr)], labelX='$2\\\\theta, deg$',\n labelY='Intensity (arbitrary)', Title='FPA peak', newPlot=True,\n lines=True)\n if FPdlg.GetSizer():\n FPdlg.GetSizer().Clear(True)\n numWave = parmDict['numWave']\n if mode == 'BBpoint':\n itemList = BraggBrentanoParms + BBPointDetector\n elif mode == 'BBPSD':\n itemList = BraggBrentanoParms + BBPSDDetector\n else:\n raise Exception('Unknown mode in MakeTopasFPASizer: ' + mode)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((-1, 5))\n waveSizer = wx.FlexGridSizer(cols=numWave + 1, hgap=3, vgap=5)\n for lbl, prm, defVal in zip((u'Wavelength (Å)', 'Rel. Intensity',\n u'Lorentz Width\\n(Å/1000)'), ('wave', 'int', 'lwidth'), (0.0, 1.0, 0.1)\n ):\n text = wx.StaticText(FPdlg, wx.ID_ANY, lbl, style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n waveSizer.Add(text, 0, wx.EXPAND)\n if prm not in parmDict:\n parmDict[prm] = {}\n for i in range(numWave):\n if i not in parmDict[prm]:\n parmDict[prm][i] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict[prm], i, size=(90, -1))\n waveSizer.Add(ctrl, 1, wx.ALIGN_CENTER_VERTICAL, 1)\n MainSizer.Add(waveSizer)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Add col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onAddWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Remove col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onRemWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa1+2')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu2Wave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa-5wave')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu5Wave)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Point Dect.')\n btn.Enable(not mode == 'BBpoint')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPoint)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'PSD')\n btn.Enable(not mode == 'BBPSD')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPSD)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=5)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'label', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER\n )\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for lbl, defVal, text in itemList:\n prmSizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, lbl), 1, wx.\n ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 1)\n if lbl not in parmDict:\n parmDict[lbl] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict, lbl, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(FPdlg, wx.ID_ANY, text, size=(400, -1))\n txt.Wrap(380)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, PlotTopasFPA)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' at '))\n if 'plotpos' not in simParms:\n simParms['plotpos'] = simParms['minTT']\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, simParms, 'plotpos', size=(70, -1))\n btnsizer.Add(ctrl)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' deg.'))\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(FPdlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(FPdlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n FPdlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(FPdlg)\n FPdlg.SetMinSize(FPdlg.GetSize())\n FPdlg.SendSizeEvent()\n\n\ndef XferFPAsettings(InpParms):\n \"\"\"convert Topas-type parameters to SI units for NIST and place in a dict sorted\n according to use in each convoluter\n\n :param dict InpParms: a dict with Topas-like parameters, as set in \n :func:`MakeTopasFPASizer`\n :returns: a nested dict with global parameters and those for each convolution\n \"\"\"\n wavenums = range(InpParms['numWave'])\n source_wavelengths_m = 1e-10 * np.array([InpParms['wave'][i] for i in\n wavenums])\n la = [InpParms['int'][i] for i in wavenums]\n source_intensities = np.array(la) / max(la)\n source_lor_widths_m = 1e-10 * 0.001 * np.array([InpParms['lwidth'][i] for\n i in wavenums])\n source_gauss_widths_m = 1e-10 * 0.001 * np.array([(0.001) for i in\n wavenums])\n NISTparms['emission'] = {'emiss_wavelengths': source_wavelengths_m,\n 'emiss_intensities': source_intensities, 'emiss_gauss_widths':\n source_gauss_widths_m, 'emiss_lor_widths': source_lor_widths_m,\n 'crystallite_size_gauss': 1e-09 * InpParms.get('Size_G', 1000000.0),\n 'crystallite_size_lor': 1e-09 * InpParms.get('Size_L', 1000000.0)}\n if InpParms['filament_length'] == InpParms['receiving_slit_length']:\n InpParms['receiving_slit_length'] *= 1.00001\n NISTparms['axial'] = {'axDiv': 'full', 'slit_length_source': 0.001 *\n InpParms['filament_length'], 'slit_length_target': 0.001 * InpParms\n ['receiving_slit_length'], 'length_sample': 0.001 * InpParms[\n 'sample_length'], 'n_integral_points': 10, 'angI_deg': InpParms[\n 'soller_angle'], 'angD_deg': InpParms['soller_angle']}\n if InpParms.get('LAC_cm', 0) > 0:\n NISTparms['absorption'] = {'absorption_coefficient': InpParms[\n 'LAC_cm'] * 100, 'sample_thickness': 0.001 * InpParms[\n 'sample_thickness']}\n elif 'absorption' in NISTparms:\n del NISTparms['absorption']\n if InpParms.get('lpsd_equitorial_divergence', 0) > 0 and InpParms.get(\n 'lpsd_th2_angular_range', 0) > 0:\n PSDdetector_length_mm = np.arcsin(np.pi * InpParms[\n 'lpsd_th2_angular_range'] / 180.0) * InpParms['Rs']\n NISTparms['si_psd'] = {'equatorial_divergence_deg': InpParms[\n 'lpsd_equitorial_divergence'], 'si_psd_window_bounds': (0.0, \n PSDdetector_length_mm / 1000.0)}\n elif 'si_psd' in NISTparms:\n del NISTparms['si_psd']\n if InpParms.get('Specimen_Displacement'):\n NISTparms['displacement'] = {'specimen_displacement': 0.001 *\n InpParms['Specimen_Displacement']}\n elif 'displacement' in NISTparms:\n del NISTparms['displacement']\n if InpParms.get('receiving_slit_width'):\n NISTparms['receiver_slit'] = {'slit_width': 0.001 * InpParms[\n 'receiving_slit_width']}\n elif 'receiver_slit' in NISTparms:\n del NISTparms['receiver_slit']\n if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(\n 'tube-tails_rel-I', 0) > 0:\n NISTparms['tube_tails'] = {'main_width': 0.001 * InpParms.get(\n 'tube-tails_width', 0.0), 'tail_left': -0.001 * InpParms.get(\n 'tube-tails_L-tail', 0.0), 'tail_right': 0.001 * InpParms.get(\n 'tube-tails_R-tail', 0.0), 'tail_intens': InpParms.get(\n 'tube-tails_rel-I', 0.0)}\n elif 'tube_tails' in NISTparms:\n del NISTparms['tube_tails']\n max_wavelength = source_wavelengths_m[np.argmax(source_intensities)]\n NISTparms[''] = {'equatorial_divergence_deg': InpParms['divergence'],\n 'dominant_wavelength': max_wavelength, 'diffractometer_radius': \n 0.001 * InpParms['Rs'], 'oversampling': InpParms['convolution_steps']}\n\n\ndef setupFPAcalc():\n \"\"\"Create a peak profile object using the NIST XRD Fundamental \n Parameters Code. \n \n :returns: a profile object that can provide information on \n each convolution or compute the composite peak shape. \n \"\"\"\n p = FP.FP_profile(anglemode='twotheta',\n output_gaussian_smoother_bins_sigma=1.0, oversampling=NISTparms.get\n ('oversampling', 10))\n p.debug_cache = False\n for key in NISTparms:\n if key:\n p.set_parameters(convolver=key, **NISTparms[key])\n else:\n p.set_parameters(**NISTparms[key])\n return p\n\n\ndef doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step):\n \"\"\"Compute a single peak using a NIST profile object\n\n :param object NISTpk: a peak profile computational object from the \n NIST XRD Fundamental Parameters Code, typically established from\n a call to :func:`SetupFPAcalc`\n :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)\n :param float twotheta: nominal center of peak (degrees)\n :param float calcwid: width to perform convolution (degrees)\n :param float step: step size\n \"\"\"\n center_bin_idx = min(ttArr.searchsorted(twotheta), len(ttArr) - 1)\n NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,\n twotheta_window_center_deg=ttArr[center_bin_idx],\n twotheta_approx_window_fullwidth_deg=calcwid)\n NISTpk.set_parameters(twotheta0_deg=twotheta)\n return center_bin_idx, NISTpk.compute_line_profile()\n\n\ndef MakeSimSizer(G2frame, dlg):\n \"\"\"Create a GUI to get simulation with parameters for Fundamental \n Parameters fitting. \n\n :param wx.Window dlg: Frame or Dialog where GUI will appear\n\n :returns: a sizer with the GUI controls \n \n \"\"\"\n\n def _onOK(event):\n msg = ''\n if simParms['minTT'] - simParms['calcwid'] / 1.5 < 0.1:\n msg += 'First peak minus half the calc width is too low'\n if simParms['maxTT'] + simParms['calcwid'] / 1.5 > 175:\n if msg:\n msg += '\\n'\n msg += 'Last peak plus half the calc width is too high'\n if simParms['npeaks'] < 8:\n if msg:\n msg += '\\n'\n msg += 'At least 8 peaks are needed'\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n return\n ttArr = np.arange(max(0.5, simParms['minTT'] - simParms['calcwid'] /\n 1.5), simParms['maxTT'] + simParms['calcwid'] / 1.5, simParms[\n 'step'])\n intArr = np.zeros_like(ttArr)\n peaklist = np.linspace(simParms['minTT'], simParms['maxTT'],\n simParms['npeaks'], endpoint=True)\n peakSpacing = (peaklist[-1] - peaklist[0]) / (len(peaklist) - 1)\n NISTpk = setupFPAcalc()\n minPtsHM = len(intArr)\n maxPtsHM = 0\n for num, twoth_peak in enumerate(peaklist):\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr,\n twoth_peak, simParms['calcwid'], simParms['step'])\n except:\n if msg:\n msg += '\\n'\n msg = 'Error computing convolution, revise input'\n continue\n if num == 0:\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkMax = peakObj.peak.max()\n pkPts = len(peakObj.peak)\n minPtsHM = min(minPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n maxPtsHM = max(maxPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n break\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset\n ] += 10000 * peakObj.peak[:-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts\n ] += 10000 * peakObj.peak / pkMax\n if maxPtsHM * simParms['step'] > peakSpacing / 4:\n if msg:\n msg += '\\n'\n msg += (\n 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'\n .format(maxPtsHM * simParms['step'], peakSpacing))\n if minPtsHM < 10:\n if msg:\n msg += '\\n'\n msg += (\n 'There are only {} points above the half-max. 10 are needed. Dropping step size.'\n .format(minPtsHM))\n simParms['step'] *= 0.5\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n wx.CallAfter(MakeSimSizer, G2frame, dlg)\n return\n dlg.Destroy()\n wx.CallAfter(FitFPApeaks, ttArr, intArr, peaklist, maxPtsHM)\n\n def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM):\n \"\"\"Perform a peak fit to the FP simulated pattern\n \"\"\"\n plswait = wx.Dialog(G2frame, style=wx.DEFAULT_DIALOG_STYLE | wx.\n RESIZE_BORDER)\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n txt = wx.StaticText(plswait, wx.ID_ANY,\n 'Fitting peaks...\\nPlease wait...', style=wx.ALIGN_CENTER)\n vbox.Add(txt, 0, wx.ALL | wx.EXPAND)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n plswait.SetSizer(vbox)\n plswait.Layout()\n plswait.CenterOnParent()\n plswait.Show()\n wx.BeginBusyCursor()\n ints = list(NISTparms['emission']['emiss_intensities'])\n Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n if len(ints) > 1:\n ints[np.argmax(ints)] = -1\n Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n else:\n Lam2 = None\n histId = G2frame.AddSimulatedPowder(ttArr, intArr,\n 'NIST Fundamental Parameters simulation', Lam1, Lam2)\n controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, G2frame.root, 'Controls'))\n controldat = controls.get('data', {'deriv type': 'analytic',\n 'min dM/M': 0.001})\n Parms, Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId\n (G2frame, histId, 'Instrument Parameters'))\n peakData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Peak List'))\n bkg1, bkg2 = bkg = G2frame.GPXtree.GetItemPyData(G2gd.\n GetGPXtreeItemId(G2frame, histId, 'Background'))\n bkg1[1] = False\n bkg1[2] = 0\n bkg1[3] = 0.0\n limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Limits'))\n try:\n Parms['SH/L'][1] = 0.25 * (NISTparms['axial']['length_sample'] +\n NISTparms['axial']['slit_length_source']) / NISTparms[''][\n 'diffractometer_radius']\n except:\n pass\n for pos in peaklist:\n i = ttArr.searchsorted(pos)\n area = sum(intArr[max(0, i - maxPtsHM):min(len(intArr), i +\n maxPtsHM)])\n peakData['peaks'].append(G2mth.setPeakparms(Parms, Parms2, pos,\n area))\n histData = G2frame.GPXtree.GetItemPyData(histId)\n bxye = np.zeros(len(histData[1][1]))\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False,\n controldat, None)[0]\n for pk in peakData['peaks']:\n pk[1] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in ('U', 'V', 'W', 'X', 'Y'):\n Parms[p][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n Parms['SH/L'][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in Parms:\n if len(Parms[p]) == 3:\n Parms[p][0] = Parms[p][1]\n Parms[p][2] = False\n wx.EndBusyCursor()\n plswait.Destroy()\n pth = G2G.GetExportPath(G2frame)\n fldlg = wx.FileDialog(G2frame,\n 'Set name to save GSAS-II instrument parameters file', pth, '',\n 'instrument parameter files (*.instprm)|*.instprm', wx.FD_SAVE |\n wx.FD_OVERWRITE_PROMPT)\n try:\n if fldlg.ShowModal() == wx.ID_OK:\n filename = fldlg.GetPath()\n filename = os.path.splitext(filename)[0] + '.instprm'\n File = open(filename, 'w')\n File.write(\n '#GSAS-II instrument parameter file; do not add/delete items!\\n'\n )\n for item in Parms:\n File.write(item + ':' + str(Parms[item][1]) + '\\n')\n File.close()\n print('Instrument parameters saved to: ' + filename)\n finally:\n fldlg.Destroy()\n\n def _onClose(event):\n dlg.Destroy()\n\n def SetButtonStatus(done=False):\n OKbtn.Enable(bool(NISTparms))\n saveBtn.Enable(bool(NISTparms))\n if done:\n _onOK(None)\n\n def _onSetFPA(event):\n FPdlg = wx.Dialog(dlg, wx.ID_ANY, 'FPA parameters', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeTopasFPASizer(G2frame, FPdlg, 'BBpoint', SetButtonStatus)\n FPdlg.CenterOnParent()\n FPdlg.Raise()\n FPdlg.Show()\n\n def _onSaveFPA(event):\n filename = G2G.askSaveFile(G2frame, '', '.NISTfpa',\n 'dict of NIST FPA values', dlg)\n if not filename:\n return\n fp = open(filename, 'w')\n fp.write(\n '# parameters to be used in the NIST XRD Fundamental Parameters program\\n'\n )\n fp.write('{\\n')\n for key in sorted(NISTparms):\n fp.write(\" '\" + key + \"' : \" + str(NISTparms[key]) + ',')\n if not key:\n fp.write(' # global parameters')\n fp.write('\\n')\n fp.write('}\\n')\n fp.close()\n\n def _onReadFPA(event):\n filename = G2G.GetImportFile(G2frame, message=\n 'Read file with dict of values for NIST Fundamental Parameters',\n parent=dlg, wildcard='dict of NIST FPA values|*.NISTfpa')\n if not filename:\n return\n if not filename[0]:\n return\n try:\n txt = open(filename[0], 'r').read()\n NISTparms.clear()\n array = np.array\n d = eval(txt)\n NISTparms.update(d)\n except Exception as err:\n G2G.G2MessageBox(dlg, u'Error reading file {}:{}\\n'.format(\n filename, err), 'Bad dict input')\n SetButtonStatus()\n if dlg.GetSizer():\n dlg.GetSizer().Clear(True)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add(wx.StaticText(dlg, wx.ID_ANY,\n 'Fit Profile Parameters to Peaks from Fundamental Parameters',\n style=wx.ALIGN_CENTER), 0, wx.EXPAND)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=5)\n text = wx.StaticText(dlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(dlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for key, defVal, text in (('minTT', 3.0,\n 'Location of first peak in 2theta (deg)'), ('maxTT', 123.0,\n 'Location of last peak in 2theta (deg)'), ('step', 0.01,\n 'Pattern step size (deg 2theta)'), ('npeaks', 13.0,\n 'Number of peaks'), ('calcwid', 2.0,\n 'Range to compute each peak (deg 2theta)')):\n if key not in simParms:\n simParms[key] = defVal\n ctrl = G2G.ValidatedTxtCtrl(dlg, simParms, key, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, text, size=(300, -1))\n txt.Wrap(280)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(dlg, wx.ID_ANY, 'Input FP vals')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetFPA)\n saveBtn = wx.Button(dlg, wx.ID_ANY, 'Save FPA dict')\n btnsizer.Add(saveBtn)\n saveBtn.Bind(wx.EVT_BUTTON, _onSaveFPA)\n readBtn = wx.Button(dlg, wx.ID_ANY, 'Read FPA dict')\n btnsizer.Add(readBtn)\n readBtn.Bind(wx.EVT_BUTTON, _onReadFPA)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, 'If you use this, please cite: ' +\n Citation, size=(350, -1))\n txt.Wrap(340)\n MainSizer.Add(txt, 0, wx.ALIGN_CENTER)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(dlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(dlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n SetButtonStatus()\n dlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(dlg)\n dlg.SetMinSize(dlg.GetSize())\n dlg.SendSizeEvent()\n dlg.Raise()\n\n\ndef GetFPAInput(G2frame):\n dlg = wx.Dialog(G2frame, wx.ID_ANY, 'FPA input', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeSimSizer(G2frame, dlg)\n dlg.CenterOnParent()\n dlg.Show()\n return\n", "step-2": "<mask token>\n\n\ndef SetCu2Wave():\n \"\"\"Set the parameters to the two-line Cu K alpha 1+2 spectrum\n \"\"\"\n parmDict['wave'] = {i: v for i, v in enumerate((1.540596, 1.544493))}\n parmDict['int'] = {i: v for i, v in enumerate((0.653817, 0.346183))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((0.501844, 0.626579))}\n\n\nSetCu2Wave()\n\n\ndef MakeTopasFPASizer(G2frame, FPdlg, mode, SetButtonStatus):\n \"\"\"Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. \n Parameter input is modeled after Topas input parameters.\n\n :param wx.Window FPdlg: Frame or Dialog where GUI will appear\n :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or \n (linear) position sensitive detector\n :param dict parmDict: dict to place parameters. If empty, default values from \n globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in \n the array. \n :returns: a sizer with the GUI controls\n \n \"\"\"\n\n def _onOK(event):\n XferFPAsettings(parmDict)\n SetButtonStatus(done=True)\n FPdlg.Destroy()\n\n def _onClose(event):\n SetButtonStatus()\n FPdlg.Destroy()\n\n def _onAddWave(event):\n parmDict['numWave'] += 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onRemWave(event):\n parmDict['numWave'] -= 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu5Wave(event):\n parmDict['wave'] = {i: v for i, v in enumerate((1.534753, 1.540596,\n 1.541058, 1.54441, 1.544721))}\n parmDict['int'] = {i: v for i, v in enumerate((0.0159, 0.5791, \n 0.0762, 0.2417, 0.0871))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((3.6854, 0.437, \n 0.6, 0.52, 0.62))}\n parmDict['numWave'] = 5\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu2Wave(event):\n SetCu2Wave()\n parmDict['numWave'] = 2\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetPoint(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBpoint',\n SetButtonStatus)\n\n def _onSetPSD(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBPSD',\n SetButtonStatus)\n\n def PlotTopasFPA(event):\n XferFPAsettings(parmDict)\n ttArr = np.arange(max(0.5, simParms['plotpos'] - simParms['calcwid'\n ]), simParms['plotpos'] + simParms['calcwid'], simParms['step'])\n intArr = np.zeros_like(ttArr)\n NISTpk = setupFPAcalc()\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr, simParms[\n 'plotpos'], simParms['calcwid'], simParms['step'])\n except Exception as err:\n msg = 'Error computing convolution, revise input'\n print(msg)\n print(err)\n return\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkPts = len(peakObj.peak)\n pkMax = peakObj.peak.max()\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n return\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset] += 10000 * peakObj.peak[\n :-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts] += 10000 * peakObj.peak / pkMax\n G2plt.PlotXY(G2frame, [(ttArr, intArr)], labelX='$2\\\\theta, deg$',\n labelY='Intensity (arbitrary)', Title='FPA peak', newPlot=True,\n lines=True)\n if FPdlg.GetSizer():\n FPdlg.GetSizer().Clear(True)\n numWave = parmDict['numWave']\n if mode == 'BBpoint':\n itemList = BraggBrentanoParms + BBPointDetector\n elif mode == 'BBPSD':\n itemList = BraggBrentanoParms + BBPSDDetector\n else:\n raise Exception('Unknown mode in MakeTopasFPASizer: ' + mode)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((-1, 5))\n waveSizer = wx.FlexGridSizer(cols=numWave + 1, hgap=3, vgap=5)\n for lbl, prm, defVal in zip((u'Wavelength (Å)', 'Rel. Intensity',\n u'Lorentz Width\\n(Å/1000)'), ('wave', 'int', 'lwidth'), (0.0, 1.0, 0.1)\n ):\n text = wx.StaticText(FPdlg, wx.ID_ANY, lbl, style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n waveSizer.Add(text, 0, wx.EXPAND)\n if prm not in parmDict:\n parmDict[prm] = {}\n for i in range(numWave):\n if i not in parmDict[prm]:\n parmDict[prm][i] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict[prm], i, size=(90, -1))\n waveSizer.Add(ctrl, 1, wx.ALIGN_CENTER_VERTICAL, 1)\n MainSizer.Add(waveSizer)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Add col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onAddWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Remove col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onRemWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa1+2')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu2Wave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa-5wave')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu5Wave)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Point Dect.')\n btn.Enable(not mode == 'BBpoint')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPoint)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'PSD')\n btn.Enable(not mode == 'BBPSD')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPSD)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=5)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'label', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER\n )\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for lbl, defVal, text in itemList:\n prmSizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, lbl), 1, wx.\n ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 1)\n if lbl not in parmDict:\n parmDict[lbl] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict, lbl, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(FPdlg, wx.ID_ANY, text, size=(400, -1))\n txt.Wrap(380)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, PlotTopasFPA)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' at '))\n if 'plotpos' not in simParms:\n simParms['plotpos'] = simParms['minTT']\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, simParms, 'plotpos', size=(70, -1))\n btnsizer.Add(ctrl)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' deg.'))\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(FPdlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(FPdlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n FPdlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(FPdlg)\n FPdlg.SetMinSize(FPdlg.GetSize())\n FPdlg.SendSizeEvent()\n\n\ndef XferFPAsettings(InpParms):\n \"\"\"convert Topas-type parameters to SI units for NIST and place in a dict sorted\n according to use in each convoluter\n\n :param dict InpParms: a dict with Topas-like parameters, as set in \n :func:`MakeTopasFPASizer`\n :returns: a nested dict with global parameters and those for each convolution\n \"\"\"\n wavenums = range(InpParms['numWave'])\n source_wavelengths_m = 1e-10 * np.array([InpParms['wave'][i] for i in\n wavenums])\n la = [InpParms['int'][i] for i in wavenums]\n source_intensities = np.array(la) / max(la)\n source_lor_widths_m = 1e-10 * 0.001 * np.array([InpParms['lwidth'][i] for\n i in wavenums])\n source_gauss_widths_m = 1e-10 * 0.001 * np.array([(0.001) for i in\n wavenums])\n NISTparms['emission'] = {'emiss_wavelengths': source_wavelengths_m,\n 'emiss_intensities': source_intensities, 'emiss_gauss_widths':\n source_gauss_widths_m, 'emiss_lor_widths': source_lor_widths_m,\n 'crystallite_size_gauss': 1e-09 * InpParms.get('Size_G', 1000000.0),\n 'crystallite_size_lor': 1e-09 * InpParms.get('Size_L', 1000000.0)}\n if InpParms['filament_length'] == InpParms['receiving_slit_length']:\n InpParms['receiving_slit_length'] *= 1.00001\n NISTparms['axial'] = {'axDiv': 'full', 'slit_length_source': 0.001 *\n InpParms['filament_length'], 'slit_length_target': 0.001 * InpParms\n ['receiving_slit_length'], 'length_sample': 0.001 * InpParms[\n 'sample_length'], 'n_integral_points': 10, 'angI_deg': InpParms[\n 'soller_angle'], 'angD_deg': InpParms['soller_angle']}\n if InpParms.get('LAC_cm', 0) > 0:\n NISTparms['absorption'] = {'absorption_coefficient': InpParms[\n 'LAC_cm'] * 100, 'sample_thickness': 0.001 * InpParms[\n 'sample_thickness']}\n elif 'absorption' in NISTparms:\n del NISTparms['absorption']\n if InpParms.get('lpsd_equitorial_divergence', 0) > 0 and InpParms.get(\n 'lpsd_th2_angular_range', 0) > 0:\n PSDdetector_length_mm = np.arcsin(np.pi * InpParms[\n 'lpsd_th2_angular_range'] / 180.0) * InpParms['Rs']\n NISTparms['si_psd'] = {'equatorial_divergence_deg': InpParms[\n 'lpsd_equitorial_divergence'], 'si_psd_window_bounds': (0.0, \n PSDdetector_length_mm / 1000.0)}\n elif 'si_psd' in NISTparms:\n del NISTparms['si_psd']\n if InpParms.get('Specimen_Displacement'):\n NISTparms['displacement'] = {'specimen_displacement': 0.001 *\n InpParms['Specimen_Displacement']}\n elif 'displacement' in NISTparms:\n del NISTparms['displacement']\n if InpParms.get('receiving_slit_width'):\n NISTparms['receiver_slit'] = {'slit_width': 0.001 * InpParms[\n 'receiving_slit_width']}\n elif 'receiver_slit' in NISTparms:\n del NISTparms['receiver_slit']\n if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(\n 'tube-tails_rel-I', 0) > 0:\n NISTparms['tube_tails'] = {'main_width': 0.001 * InpParms.get(\n 'tube-tails_width', 0.0), 'tail_left': -0.001 * InpParms.get(\n 'tube-tails_L-tail', 0.0), 'tail_right': 0.001 * InpParms.get(\n 'tube-tails_R-tail', 0.0), 'tail_intens': InpParms.get(\n 'tube-tails_rel-I', 0.0)}\n elif 'tube_tails' in NISTparms:\n del NISTparms['tube_tails']\n max_wavelength = source_wavelengths_m[np.argmax(source_intensities)]\n NISTparms[''] = {'equatorial_divergence_deg': InpParms['divergence'],\n 'dominant_wavelength': max_wavelength, 'diffractometer_radius': \n 0.001 * InpParms['Rs'], 'oversampling': InpParms['convolution_steps']}\n\n\ndef setupFPAcalc():\n \"\"\"Create a peak profile object using the NIST XRD Fundamental \n Parameters Code. \n \n :returns: a profile object that can provide information on \n each convolution or compute the composite peak shape. \n \"\"\"\n p = FP.FP_profile(anglemode='twotheta',\n output_gaussian_smoother_bins_sigma=1.0, oversampling=NISTparms.get\n ('oversampling', 10))\n p.debug_cache = False\n for key in NISTparms:\n if key:\n p.set_parameters(convolver=key, **NISTparms[key])\n else:\n p.set_parameters(**NISTparms[key])\n return p\n\n\ndef doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step):\n \"\"\"Compute a single peak using a NIST profile object\n\n :param object NISTpk: a peak profile computational object from the \n NIST XRD Fundamental Parameters Code, typically established from\n a call to :func:`SetupFPAcalc`\n :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)\n :param float twotheta: nominal center of peak (degrees)\n :param float calcwid: width to perform convolution (degrees)\n :param float step: step size\n \"\"\"\n center_bin_idx = min(ttArr.searchsorted(twotheta), len(ttArr) - 1)\n NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,\n twotheta_window_center_deg=ttArr[center_bin_idx],\n twotheta_approx_window_fullwidth_deg=calcwid)\n NISTpk.set_parameters(twotheta0_deg=twotheta)\n return center_bin_idx, NISTpk.compute_line_profile()\n\n\ndef MakeSimSizer(G2frame, dlg):\n \"\"\"Create a GUI to get simulation with parameters for Fundamental \n Parameters fitting. \n\n :param wx.Window dlg: Frame or Dialog where GUI will appear\n\n :returns: a sizer with the GUI controls \n \n \"\"\"\n\n def _onOK(event):\n msg = ''\n if simParms['minTT'] - simParms['calcwid'] / 1.5 < 0.1:\n msg += 'First peak minus half the calc width is too low'\n if simParms['maxTT'] + simParms['calcwid'] / 1.5 > 175:\n if msg:\n msg += '\\n'\n msg += 'Last peak plus half the calc width is too high'\n if simParms['npeaks'] < 8:\n if msg:\n msg += '\\n'\n msg += 'At least 8 peaks are needed'\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n return\n ttArr = np.arange(max(0.5, simParms['minTT'] - simParms['calcwid'] /\n 1.5), simParms['maxTT'] + simParms['calcwid'] / 1.5, simParms[\n 'step'])\n intArr = np.zeros_like(ttArr)\n peaklist = np.linspace(simParms['minTT'], simParms['maxTT'],\n simParms['npeaks'], endpoint=True)\n peakSpacing = (peaklist[-1] - peaklist[0]) / (len(peaklist) - 1)\n NISTpk = setupFPAcalc()\n minPtsHM = len(intArr)\n maxPtsHM = 0\n for num, twoth_peak in enumerate(peaklist):\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr,\n twoth_peak, simParms['calcwid'], simParms['step'])\n except:\n if msg:\n msg += '\\n'\n msg = 'Error computing convolution, revise input'\n continue\n if num == 0:\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkMax = peakObj.peak.max()\n pkPts = len(peakObj.peak)\n minPtsHM = min(minPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n maxPtsHM = max(maxPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n break\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset\n ] += 10000 * peakObj.peak[:-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts\n ] += 10000 * peakObj.peak / pkMax\n if maxPtsHM * simParms['step'] > peakSpacing / 4:\n if msg:\n msg += '\\n'\n msg += (\n 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'\n .format(maxPtsHM * simParms['step'], peakSpacing))\n if minPtsHM < 10:\n if msg:\n msg += '\\n'\n msg += (\n 'There are only {} points above the half-max. 10 are needed. Dropping step size.'\n .format(minPtsHM))\n simParms['step'] *= 0.5\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n wx.CallAfter(MakeSimSizer, G2frame, dlg)\n return\n dlg.Destroy()\n wx.CallAfter(FitFPApeaks, ttArr, intArr, peaklist, maxPtsHM)\n\n def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM):\n \"\"\"Perform a peak fit to the FP simulated pattern\n \"\"\"\n plswait = wx.Dialog(G2frame, style=wx.DEFAULT_DIALOG_STYLE | wx.\n RESIZE_BORDER)\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n txt = wx.StaticText(plswait, wx.ID_ANY,\n 'Fitting peaks...\\nPlease wait...', style=wx.ALIGN_CENTER)\n vbox.Add(txt, 0, wx.ALL | wx.EXPAND)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n plswait.SetSizer(vbox)\n plswait.Layout()\n plswait.CenterOnParent()\n plswait.Show()\n wx.BeginBusyCursor()\n ints = list(NISTparms['emission']['emiss_intensities'])\n Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n if len(ints) > 1:\n ints[np.argmax(ints)] = -1\n Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n else:\n Lam2 = None\n histId = G2frame.AddSimulatedPowder(ttArr, intArr,\n 'NIST Fundamental Parameters simulation', Lam1, Lam2)\n controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, G2frame.root, 'Controls'))\n controldat = controls.get('data', {'deriv type': 'analytic',\n 'min dM/M': 0.001})\n Parms, Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId\n (G2frame, histId, 'Instrument Parameters'))\n peakData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Peak List'))\n bkg1, bkg2 = bkg = G2frame.GPXtree.GetItemPyData(G2gd.\n GetGPXtreeItemId(G2frame, histId, 'Background'))\n bkg1[1] = False\n bkg1[2] = 0\n bkg1[3] = 0.0\n limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Limits'))\n try:\n Parms['SH/L'][1] = 0.25 * (NISTparms['axial']['length_sample'] +\n NISTparms['axial']['slit_length_source']) / NISTparms[''][\n 'diffractometer_radius']\n except:\n pass\n for pos in peaklist:\n i = ttArr.searchsorted(pos)\n area = sum(intArr[max(0, i - maxPtsHM):min(len(intArr), i +\n maxPtsHM)])\n peakData['peaks'].append(G2mth.setPeakparms(Parms, Parms2, pos,\n area))\n histData = G2frame.GPXtree.GetItemPyData(histId)\n bxye = np.zeros(len(histData[1][1]))\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False,\n controldat, None)[0]\n for pk in peakData['peaks']:\n pk[1] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in ('U', 'V', 'W', 'X', 'Y'):\n Parms[p][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n Parms['SH/L'][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in Parms:\n if len(Parms[p]) == 3:\n Parms[p][0] = Parms[p][1]\n Parms[p][2] = False\n wx.EndBusyCursor()\n plswait.Destroy()\n pth = G2G.GetExportPath(G2frame)\n fldlg = wx.FileDialog(G2frame,\n 'Set name to save GSAS-II instrument parameters file', pth, '',\n 'instrument parameter files (*.instprm)|*.instprm', wx.FD_SAVE |\n wx.FD_OVERWRITE_PROMPT)\n try:\n if fldlg.ShowModal() == wx.ID_OK:\n filename = fldlg.GetPath()\n filename = os.path.splitext(filename)[0] + '.instprm'\n File = open(filename, 'w')\n File.write(\n '#GSAS-II instrument parameter file; do not add/delete items!\\n'\n )\n for item in Parms:\n File.write(item + ':' + str(Parms[item][1]) + '\\n')\n File.close()\n print('Instrument parameters saved to: ' + filename)\n finally:\n fldlg.Destroy()\n\n def _onClose(event):\n dlg.Destroy()\n\n def SetButtonStatus(done=False):\n OKbtn.Enable(bool(NISTparms))\n saveBtn.Enable(bool(NISTparms))\n if done:\n _onOK(None)\n\n def _onSetFPA(event):\n FPdlg = wx.Dialog(dlg, wx.ID_ANY, 'FPA parameters', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeTopasFPASizer(G2frame, FPdlg, 'BBpoint', SetButtonStatus)\n FPdlg.CenterOnParent()\n FPdlg.Raise()\n FPdlg.Show()\n\n def _onSaveFPA(event):\n filename = G2G.askSaveFile(G2frame, '', '.NISTfpa',\n 'dict of NIST FPA values', dlg)\n if not filename:\n return\n fp = open(filename, 'w')\n fp.write(\n '# parameters to be used in the NIST XRD Fundamental Parameters program\\n'\n )\n fp.write('{\\n')\n for key in sorted(NISTparms):\n fp.write(\" '\" + key + \"' : \" + str(NISTparms[key]) + ',')\n if not key:\n fp.write(' # global parameters')\n fp.write('\\n')\n fp.write('}\\n')\n fp.close()\n\n def _onReadFPA(event):\n filename = G2G.GetImportFile(G2frame, message=\n 'Read file with dict of values for NIST Fundamental Parameters',\n parent=dlg, wildcard='dict of NIST FPA values|*.NISTfpa')\n if not filename:\n return\n if not filename[0]:\n return\n try:\n txt = open(filename[0], 'r').read()\n NISTparms.clear()\n array = np.array\n d = eval(txt)\n NISTparms.update(d)\n except Exception as err:\n G2G.G2MessageBox(dlg, u'Error reading file {}:{}\\n'.format(\n filename, err), 'Bad dict input')\n SetButtonStatus()\n if dlg.GetSizer():\n dlg.GetSizer().Clear(True)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add(wx.StaticText(dlg, wx.ID_ANY,\n 'Fit Profile Parameters to Peaks from Fundamental Parameters',\n style=wx.ALIGN_CENTER), 0, wx.EXPAND)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=5)\n text = wx.StaticText(dlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(dlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for key, defVal, text in (('minTT', 3.0,\n 'Location of first peak in 2theta (deg)'), ('maxTT', 123.0,\n 'Location of last peak in 2theta (deg)'), ('step', 0.01,\n 'Pattern step size (deg 2theta)'), ('npeaks', 13.0,\n 'Number of peaks'), ('calcwid', 2.0,\n 'Range to compute each peak (deg 2theta)')):\n if key not in simParms:\n simParms[key] = defVal\n ctrl = G2G.ValidatedTxtCtrl(dlg, simParms, key, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, text, size=(300, -1))\n txt.Wrap(280)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(dlg, wx.ID_ANY, 'Input FP vals')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetFPA)\n saveBtn = wx.Button(dlg, wx.ID_ANY, 'Save FPA dict')\n btnsizer.Add(saveBtn)\n saveBtn.Bind(wx.EVT_BUTTON, _onSaveFPA)\n readBtn = wx.Button(dlg, wx.ID_ANY, 'Read FPA dict')\n btnsizer.Add(readBtn)\n readBtn.Bind(wx.EVT_BUTTON, _onReadFPA)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, 'If you use this, please cite: ' +\n Citation, size=(350, -1))\n txt.Wrap(340)\n MainSizer.Add(txt, 0, wx.ALIGN_CENTER)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(dlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(dlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n SetButtonStatus()\n dlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(dlg)\n dlg.SetMinSize(dlg.GetSize())\n dlg.SendSizeEvent()\n dlg.Raise()\n\n\ndef GetFPAInput(G2frame):\n dlg = wx.Dialog(G2frame, wx.ID_ANY, 'FPA input', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeSimSizer(G2frame, dlg)\n dlg.CenterOnParent()\n dlg.Show()\n return\n", "step-3": "<mask token>\nsimParms = {}\n<mask token>\nparmDict = {'numWave': 2}\n<mask token>\nNISTparms = {}\n<mask token>\nBraggBrentanoParms = [('divergence', 0.5,\n 'Bragg-Brentano divergence angle (degrees)'), ('soller_angle', 2.0,\n 'Soller slit axial divergence (degrees)'), ('Rs', 220,\n 'Diffractometer radius (mm)'), ('filament_length', 12.0,\n 'X-ray tube line focus length (mm)'), ('sample_length', 12.0,\n 'Illuminated sample length in axial direction (mm)'), (\n 'receiving_slit_length', 12.0,\n 'Length of receiving slit in axial direction (mm)'), ('LAC_cm', 0.0,\n 'Linear absorption coef. adjusted for packing density (cm-1)'), (\n 'sample_thickness', 1.0, 'Depth of sample (mm)'), ('convolution_steps',\n 8, 'Number of Fourier-space bins per two-theta step'), (\n 'tube-tails_width', 0.04,\n 'Tube filament width, in projection at takeoff angle (mm)'), (\n 'tube-tails_L-tail', -1.0,\n 'Left-side tube tails width, in projection (mm)'), ('tube-tails_R-tail',\n 1.0, 'Right-side tube tails width, in projection (mm)'), (\n 'tube-tails_rel-I', 0.001, 'Tube tails fractional intensity (no units)')]\n<mask token>\nBBPointDetector = [('receiving_slit_width', 0.2,\n 'Width of receiving slit (mm)')]\n<mask token>\nBBPSDDetector = [('lpsd_th2_angular_range', 3.0,\n 'Angular range observed by PSD (degrees 2Theta)'), (\n 'lpsd_equitorial_divergence', 0.1,\n 'Equatorial divergence of the primary beam (degrees)')]\n<mask token>\nCitation = \"\"\"MH Mendenhall, K Mullen && JP Cline. (2015) J. Res. of NIST 120, 223-251. doi:10.6028/jres.120.014.\n\"\"\"\n\n\ndef SetCu2Wave():\n \"\"\"Set the parameters to the two-line Cu K alpha 1+2 spectrum\n \"\"\"\n parmDict['wave'] = {i: v for i, v in enumerate((1.540596, 1.544493))}\n parmDict['int'] = {i: v for i, v in enumerate((0.653817, 0.346183))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((0.501844, 0.626579))}\n\n\nSetCu2Wave()\n\n\ndef MakeTopasFPASizer(G2frame, FPdlg, mode, SetButtonStatus):\n \"\"\"Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. \n Parameter input is modeled after Topas input parameters.\n\n :param wx.Window FPdlg: Frame or Dialog where GUI will appear\n :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or \n (linear) position sensitive detector\n :param dict parmDict: dict to place parameters. If empty, default values from \n globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in \n the array. \n :returns: a sizer with the GUI controls\n \n \"\"\"\n\n def _onOK(event):\n XferFPAsettings(parmDict)\n SetButtonStatus(done=True)\n FPdlg.Destroy()\n\n def _onClose(event):\n SetButtonStatus()\n FPdlg.Destroy()\n\n def _onAddWave(event):\n parmDict['numWave'] += 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onRemWave(event):\n parmDict['numWave'] -= 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu5Wave(event):\n parmDict['wave'] = {i: v for i, v in enumerate((1.534753, 1.540596,\n 1.541058, 1.54441, 1.544721))}\n parmDict['int'] = {i: v for i, v in enumerate((0.0159, 0.5791, \n 0.0762, 0.2417, 0.0871))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((3.6854, 0.437, \n 0.6, 0.52, 0.62))}\n parmDict['numWave'] = 5\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu2Wave(event):\n SetCu2Wave()\n parmDict['numWave'] = 2\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetPoint(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBpoint',\n SetButtonStatus)\n\n def _onSetPSD(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBPSD',\n SetButtonStatus)\n\n def PlotTopasFPA(event):\n XferFPAsettings(parmDict)\n ttArr = np.arange(max(0.5, simParms['plotpos'] - simParms['calcwid'\n ]), simParms['plotpos'] + simParms['calcwid'], simParms['step'])\n intArr = np.zeros_like(ttArr)\n NISTpk = setupFPAcalc()\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr, simParms[\n 'plotpos'], simParms['calcwid'], simParms['step'])\n except Exception as err:\n msg = 'Error computing convolution, revise input'\n print(msg)\n print(err)\n return\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkPts = len(peakObj.peak)\n pkMax = peakObj.peak.max()\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n return\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset] += 10000 * peakObj.peak[\n :-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts] += 10000 * peakObj.peak / pkMax\n G2plt.PlotXY(G2frame, [(ttArr, intArr)], labelX='$2\\\\theta, deg$',\n labelY='Intensity (arbitrary)', Title='FPA peak', newPlot=True,\n lines=True)\n if FPdlg.GetSizer():\n FPdlg.GetSizer().Clear(True)\n numWave = parmDict['numWave']\n if mode == 'BBpoint':\n itemList = BraggBrentanoParms + BBPointDetector\n elif mode == 'BBPSD':\n itemList = BraggBrentanoParms + BBPSDDetector\n else:\n raise Exception('Unknown mode in MakeTopasFPASizer: ' + mode)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((-1, 5))\n waveSizer = wx.FlexGridSizer(cols=numWave + 1, hgap=3, vgap=5)\n for lbl, prm, defVal in zip((u'Wavelength (Å)', 'Rel. Intensity',\n u'Lorentz Width\\n(Å/1000)'), ('wave', 'int', 'lwidth'), (0.0, 1.0, 0.1)\n ):\n text = wx.StaticText(FPdlg, wx.ID_ANY, lbl, style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n waveSizer.Add(text, 0, wx.EXPAND)\n if prm not in parmDict:\n parmDict[prm] = {}\n for i in range(numWave):\n if i not in parmDict[prm]:\n parmDict[prm][i] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict[prm], i, size=(90, -1))\n waveSizer.Add(ctrl, 1, wx.ALIGN_CENTER_VERTICAL, 1)\n MainSizer.Add(waveSizer)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Add col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onAddWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Remove col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onRemWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa1+2')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu2Wave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa-5wave')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu5Wave)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Point Dect.')\n btn.Enable(not mode == 'BBpoint')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPoint)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'PSD')\n btn.Enable(not mode == 'BBPSD')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPSD)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=5)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'label', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER\n )\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for lbl, defVal, text in itemList:\n prmSizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, lbl), 1, wx.\n ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 1)\n if lbl not in parmDict:\n parmDict[lbl] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict, lbl, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(FPdlg, wx.ID_ANY, text, size=(400, -1))\n txt.Wrap(380)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, PlotTopasFPA)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' at '))\n if 'plotpos' not in simParms:\n simParms['plotpos'] = simParms['minTT']\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, simParms, 'plotpos', size=(70, -1))\n btnsizer.Add(ctrl)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' deg.'))\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(FPdlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(FPdlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n FPdlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(FPdlg)\n FPdlg.SetMinSize(FPdlg.GetSize())\n FPdlg.SendSizeEvent()\n\n\ndef XferFPAsettings(InpParms):\n \"\"\"convert Topas-type parameters to SI units for NIST and place in a dict sorted\n according to use in each convoluter\n\n :param dict InpParms: a dict with Topas-like parameters, as set in \n :func:`MakeTopasFPASizer`\n :returns: a nested dict with global parameters and those for each convolution\n \"\"\"\n wavenums = range(InpParms['numWave'])\n source_wavelengths_m = 1e-10 * np.array([InpParms['wave'][i] for i in\n wavenums])\n la = [InpParms['int'][i] for i in wavenums]\n source_intensities = np.array(la) / max(la)\n source_lor_widths_m = 1e-10 * 0.001 * np.array([InpParms['lwidth'][i] for\n i in wavenums])\n source_gauss_widths_m = 1e-10 * 0.001 * np.array([(0.001) for i in\n wavenums])\n NISTparms['emission'] = {'emiss_wavelengths': source_wavelengths_m,\n 'emiss_intensities': source_intensities, 'emiss_gauss_widths':\n source_gauss_widths_m, 'emiss_lor_widths': source_lor_widths_m,\n 'crystallite_size_gauss': 1e-09 * InpParms.get('Size_G', 1000000.0),\n 'crystallite_size_lor': 1e-09 * InpParms.get('Size_L', 1000000.0)}\n if InpParms['filament_length'] == InpParms['receiving_slit_length']:\n InpParms['receiving_slit_length'] *= 1.00001\n NISTparms['axial'] = {'axDiv': 'full', 'slit_length_source': 0.001 *\n InpParms['filament_length'], 'slit_length_target': 0.001 * InpParms\n ['receiving_slit_length'], 'length_sample': 0.001 * InpParms[\n 'sample_length'], 'n_integral_points': 10, 'angI_deg': InpParms[\n 'soller_angle'], 'angD_deg': InpParms['soller_angle']}\n if InpParms.get('LAC_cm', 0) > 0:\n NISTparms['absorption'] = {'absorption_coefficient': InpParms[\n 'LAC_cm'] * 100, 'sample_thickness': 0.001 * InpParms[\n 'sample_thickness']}\n elif 'absorption' in NISTparms:\n del NISTparms['absorption']\n if InpParms.get('lpsd_equitorial_divergence', 0) > 0 and InpParms.get(\n 'lpsd_th2_angular_range', 0) > 0:\n PSDdetector_length_mm = np.arcsin(np.pi * InpParms[\n 'lpsd_th2_angular_range'] / 180.0) * InpParms['Rs']\n NISTparms['si_psd'] = {'equatorial_divergence_deg': InpParms[\n 'lpsd_equitorial_divergence'], 'si_psd_window_bounds': (0.0, \n PSDdetector_length_mm / 1000.0)}\n elif 'si_psd' in NISTparms:\n del NISTparms['si_psd']\n if InpParms.get('Specimen_Displacement'):\n NISTparms['displacement'] = {'specimen_displacement': 0.001 *\n InpParms['Specimen_Displacement']}\n elif 'displacement' in NISTparms:\n del NISTparms['displacement']\n if InpParms.get('receiving_slit_width'):\n NISTparms['receiver_slit'] = {'slit_width': 0.001 * InpParms[\n 'receiving_slit_width']}\n elif 'receiver_slit' in NISTparms:\n del NISTparms['receiver_slit']\n if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(\n 'tube-tails_rel-I', 0) > 0:\n NISTparms['tube_tails'] = {'main_width': 0.001 * InpParms.get(\n 'tube-tails_width', 0.0), 'tail_left': -0.001 * InpParms.get(\n 'tube-tails_L-tail', 0.0), 'tail_right': 0.001 * InpParms.get(\n 'tube-tails_R-tail', 0.0), 'tail_intens': InpParms.get(\n 'tube-tails_rel-I', 0.0)}\n elif 'tube_tails' in NISTparms:\n del NISTparms['tube_tails']\n max_wavelength = source_wavelengths_m[np.argmax(source_intensities)]\n NISTparms[''] = {'equatorial_divergence_deg': InpParms['divergence'],\n 'dominant_wavelength': max_wavelength, 'diffractometer_radius': \n 0.001 * InpParms['Rs'], 'oversampling': InpParms['convolution_steps']}\n\n\ndef setupFPAcalc():\n \"\"\"Create a peak profile object using the NIST XRD Fundamental \n Parameters Code. \n \n :returns: a profile object that can provide information on \n each convolution or compute the composite peak shape. \n \"\"\"\n p = FP.FP_profile(anglemode='twotheta',\n output_gaussian_smoother_bins_sigma=1.0, oversampling=NISTparms.get\n ('oversampling', 10))\n p.debug_cache = False\n for key in NISTparms:\n if key:\n p.set_parameters(convolver=key, **NISTparms[key])\n else:\n p.set_parameters(**NISTparms[key])\n return p\n\n\ndef doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step):\n \"\"\"Compute a single peak using a NIST profile object\n\n :param object NISTpk: a peak profile computational object from the \n NIST XRD Fundamental Parameters Code, typically established from\n a call to :func:`SetupFPAcalc`\n :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)\n :param float twotheta: nominal center of peak (degrees)\n :param float calcwid: width to perform convolution (degrees)\n :param float step: step size\n \"\"\"\n center_bin_idx = min(ttArr.searchsorted(twotheta), len(ttArr) - 1)\n NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,\n twotheta_window_center_deg=ttArr[center_bin_idx],\n twotheta_approx_window_fullwidth_deg=calcwid)\n NISTpk.set_parameters(twotheta0_deg=twotheta)\n return center_bin_idx, NISTpk.compute_line_profile()\n\n\ndef MakeSimSizer(G2frame, dlg):\n \"\"\"Create a GUI to get simulation with parameters for Fundamental \n Parameters fitting. \n\n :param wx.Window dlg: Frame or Dialog where GUI will appear\n\n :returns: a sizer with the GUI controls \n \n \"\"\"\n\n def _onOK(event):\n msg = ''\n if simParms['minTT'] - simParms['calcwid'] / 1.5 < 0.1:\n msg += 'First peak minus half the calc width is too low'\n if simParms['maxTT'] + simParms['calcwid'] / 1.5 > 175:\n if msg:\n msg += '\\n'\n msg += 'Last peak plus half the calc width is too high'\n if simParms['npeaks'] < 8:\n if msg:\n msg += '\\n'\n msg += 'At least 8 peaks are needed'\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n return\n ttArr = np.arange(max(0.5, simParms['minTT'] - simParms['calcwid'] /\n 1.5), simParms['maxTT'] + simParms['calcwid'] / 1.5, simParms[\n 'step'])\n intArr = np.zeros_like(ttArr)\n peaklist = np.linspace(simParms['minTT'], simParms['maxTT'],\n simParms['npeaks'], endpoint=True)\n peakSpacing = (peaklist[-1] - peaklist[0]) / (len(peaklist) - 1)\n NISTpk = setupFPAcalc()\n minPtsHM = len(intArr)\n maxPtsHM = 0\n for num, twoth_peak in enumerate(peaklist):\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr,\n twoth_peak, simParms['calcwid'], simParms['step'])\n except:\n if msg:\n msg += '\\n'\n msg = 'Error computing convolution, revise input'\n continue\n if num == 0:\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkMax = peakObj.peak.max()\n pkPts = len(peakObj.peak)\n minPtsHM = min(minPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n maxPtsHM = max(maxPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n break\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset\n ] += 10000 * peakObj.peak[:-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts\n ] += 10000 * peakObj.peak / pkMax\n if maxPtsHM * simParms['step'] > peakSpacing / 4:\n if msg:\n msg += '\\n'\n msg += (\n 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'\n .format(maxPtsHM * simParms['step'], peakSpacing))\n if minPtsHM < 10:\n if msg:\n msg += '\\n'\n msg += (\n 'There are only {} points above the half-max. 10 are needed. Dropping step size.'\n .format(minPtsHM))\n simParms['step'] *= 0.5\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n wx.CallAfter(MakeSimSizer, G2frame, dlg)\n return\n dlg.Destroy()\n wx.CallAfter(FitFPApeaks, ttArr, intArr, peaklist, maxPtsHM)\n\n def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM):\n \"\"\"Perform a peak fit to the FP simulated pattern\n \"\"\"\n plswait = wx.Dialog(G2frame, style=wx.DEFAULT_DIALOG_STYLE | wx.\n RESIZE_BORDER)\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n txt = wx.StaticText(plswait, wx.ID_ANY,\n 'Fitting peaks...\\nPlease wait...', style=wx.ALIGN_CENTER)\n vbox.Add(txt, 0, wx.ALL | wx.EXPAND)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n plswait.SetSizer(vbox)\n plswait.Layout()\n plswait.CenterOnParent()\n plswait.Show()\n wx.BeginBusyCursor()\n ints = list(NISTparms['emission']['emiss_intensities'])\n Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n if len(ints) > 1:\n ints[np.argmax(ints)] = -1\n Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n else:\n Lam2 = None\n histId = G2frame.AddSimulatedPowder(ttArr, intArr,\n 'NIST Fundamental Parameters simulation', Lam1, Lam2)\n controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, G2frame.root, 'Controls'))\n controldat = controls.get('data', {'deriv type': 'analytic',\n 'min dM/M': 0.001})\n Parms, Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId\n (G2frame, histId, 'Instrument Parameters'))\n peakData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Peak List'))\n bkg1, bkg2 = bkg = G2frame.GPXtree.GetItemPyData(G2gd.\n GetGPXtreeItemId(G2frame, histId, 'Background'))\n bkg1[1] = False\n bkg1[2] = 0\n bkg1[3] = 0.0\n limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Limits'))\n try:\n Parms['SH/L'][1] = 0.25 * (NISTparms['axial']['length_sample'] +\n NISTparms['axial']['slit_length_source']) / NISTparms[''][\n 'diffractometer_radius']\n except:\n pass\n for pos in peaklist:\n i = ttArr.searchsorted(pos)\n area = sum(intArr[max(0, i - maxPtsHM):min(len(intArr), i +\n maxPtsHM)])\n peakData['peaks'].append(G2mth.setPeakparms(Parms, Parms2, pos,\n area))\n histData = G2frame.GPXtree.GetItemPyData(histId)\n bxye = np.zeros(len(histData[1][1]))\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False,\n controldat, None)[0]\n for pk in peakData['peaks']:\n pk[1] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in ('U', 'V', 'W', 'X', 'Y'):\n Parms[p][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n Parms['SH/L'][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in Parms:\n if len(Parms[p]) == 3:\n Parms[p][0] = Parms[p][1]\n Parms[p][2] = False\n wx.EndBusyCursor()\n plswait.Destroy()\n pth = G2G.GetExportPath(G2frame)\n fldlg = wx.FileDialog(G2frame,\n 'Set name to save GSAS-II instrument parameters file', pth, '',\n 'instrument parameter files (*.instprm)|*.instprm', wx.FD_SAVE |\n wx.FD_OVERWRITE_PROMPT)\n try:\n if fldlg.ShowModal() == wx.ID_OK:\n filename = fldlg.GetPath()\n filename = os.path.splitext(filename)[0] + '.instprm'\n File = open(filename, 'w')\n File.write(\n '#GSAS-II instrument parameter file; do not add/delete items!\\n'\n )\n for item in Parms:\n File.write(item + ':' + str(Parms[item][1]) + '\\n')\n File.close()\n print('Instrument parameters saved to: ' + filename)\n finally:\n fldlg.Destroy()\n\n def _onClose(event):\n dlg.Destroy()\n\n def SetButtonStatus(done=False):\n OKbtn.Enable(bool(NISTparms))\n saveBtn.Enable(bool(NISTparms))\n if done:\n _onOK(None)\n\n def _onSetFPA(event):\n FPdlg = wx.Dialog(dlg, wx.ID_ANY, 'FPA parameters', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeTopasFPASizer(G2frame, FPdlg, 'BBpoint', SetButtonStatus)\n FPdlg.CenterOnParent()\n FPdlg.Raise()\n FPdlg.Show()\n\n def _onSaveFPA(event):\n filename = G2G.askSaveFile(G2frame, '', '.NISTfpa',\n 'dict of NIST FPA values', dlg)\n if not filename:\n return\n fp = open(filename, 'w')\n fp.write(\n '# parameters to be used in the NIST XRD Fundamental Parameters program\\n'\n )\n fp.write('{\\n')\n for key in sorted(NISTparms):\n fp.write(\" '\" + key + \"' : \" + str(NISTparms[key]) + ',')\n if not key:\n fp.write(' # global parameters')\n fp.write('\\n')\n fp.write('}\\n')\n fp.close()\n\n def _onReadFPA(event):\n filename = G2G.GetImportFile(G2frame, message=\n 'Read file with dict of values for NIST Fundamental Parameters',\n parent=dlg, wildcard='dict of NIST FPA values|*.NISTfpa')\n if not filename:\n return\n if not filename[0]:\n return\n try:\n txt = open(filename[0], 'r').read()\n NISTparms.clear()\n array = np.array\n d = eval(txt)\n NISTparms.update(d)\n except Exception as err:\n G2G.G2MessageBox(dlg, u'Error reading file {}:{}\\n'.format(\n filename, err), 'Bad dict input')\n SetButtonStatus()\n if dlg.GetSizer():\n dlg.GetSizer().Clear(True)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add(wx.StaticText(dlg, wx.ID_ANY,\n 'Fit Profile Parameters to Peaks from Fundamental Parameters',\n style=wx.ALIGN_CENTER), 0, wx.EXPAND)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=5)\n text = wx.StaticText(dlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(dlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for key, defVal, text in (('minTT', 3.0,\n 'Location of first peak in 2theta (deg)'), ('maxTT', 123.0,\n 'Location of last peak in 2theta (deg)'), ('step', 0.01,\n 'Pattern step size (deg 2theta)'), ('npeaks', 13.0,\n 'Number of peaks'), ('calcwid', 2.0,\n 'Range to compute each peak (deg 2theta)')):\n if key not in simParms:\n simParms[key] = defVal\n ctrl = G2G.ValidatedTxtCtrl(dlg, simParms, key, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, text, size=(300, -1))\n txt.Wrap(280)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(dlg, wx.ID_ANY, 'Input FP vals')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetFPA)\n saveBtn = wx.Button(dlg, wx.ID_ANY, 'Save FPA dict')\n btnsizer.Add(saveBtn)\n saveBtn.Bind(wx.EVT_BUTTON, _onSaveFPA)\n readBtn = wx.Button(dlg, wx.ID_ANY, 'Read FPA dict')\n btnsizer.Add(readBtn)\n readBtn.Bind(wx.EVT_BUTTON, _onReadFPA)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, 'If you use this, please cite: ' +\n Citation, size=(350, -1))\n txt.Wrap(340)\n MainSizer.Add(txt, 0, wx.ALIGN_CENTER)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(dlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(dlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n SetButtonStatus()\n dlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(dlg)\n dlg.SetMinSize(dlg.GetSize())\n dlg.SendSizeEvent()\n dlg.Raise()\n\n\ndef GetFPAInput(G2frame):\n dlg = wx.Dialog(G2frame, wx.ID_ANY, 'FPA input', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeSimSizer(G2frame, dlg)\n dlg.CenterOnParent()\n dlg.Show()\n return\n", "step-4": "<mask token>\nfrom __future__ import division, print_function\nimport wx\nimport os.path\nimport numpy as np\nimport NIST_profile as FP\nimport GSASIIpath\nimport GSASIIctrlGUI as G2G\nimport GSASIIdataGUI as G2gd\nimport GSASIIplot as G2plt\nimport GSASIImath as G2mth\nimport GSASIIpwd as G2pwd\nsimParms = {}\n<mask token>\nparmDict = {'numWave': 2}\n<mask token>\nNISTparms = {}\n<mask token>\nBraggBrentanoParms = [('divergence', 0.5,\n 'Bragg-Brentano divergence angle (degrees)'), ('soller_angle', 2.0,\n 'Soller slit axial divergence (degrees)'), ('Rs', 220,\n 'Diffractometer radius (mm)'), ('filament_length', 12.0,\n 'X-ray tube line focus length (mm)'), ('sample_length', 12.0,\n 'Illuminated sample length in axial direction (mm)'), (\n 'receiving_slit_length', 12.0,\n 'Length of receiving slit in axial direction (mm)'), ('LAC_cm', 0.0,\n 'Linear absorption coef. adjusted for packing density (cm-1)'), (\n 'sample_thickness', 1.0, 'Depth of sample (mm)'), ('convolution_steps',\n 8, 'Number of Fourier-space bins per two-theta step'), (\n 'tube-tails_width', 0.04,\n 'Tube filament width, in projection at takeoff angle (mm)'), (\n 'tube-tails_L-tail', -1.0,\n 'Left-side tube tails width, in projection (mm)'), ('tube-tails_R-tail',\n 1.0, 'Right-side tube tails width, in projection (mm)'), (\n 'tube-tails_rel-I', 0.001, 'Tube tails fractional intensity (no units)')]\n<mask token>\nBBPointDetector = [('receiving_slit_width', 0.2,\n 'Width of receiving slit (mm)')]\n<mask token>\nBBPSDDetector = [('lpsd_th2_angular_range', 3.0,\n 'Angular range observed by PSD (degrees 2Theta)'), (\n 'lpsd_equitorial_divergence', 0.1,\n 'Equatorial divergence of the primary beam (degrees)')]\n<mask token>\nCitation = \"\"\"MH Mendenhall, K Mullen && JP Cline. (2015) J. Res. of NIST 120, 223-251. doi:10.6028/jres.120.014.\n\"\"\"\n\n\ndef SetCu2Wave():\n \"\"\"Set the parameters to the two-line Cu K alpha 1+2 spectrum\n \"\"\"\n parmDict['wave'] = {i: v for i, v in enumerate((1.540596, 1.544493))}\n parmDict['int'] = {i: v for i, v in enumerate((0.653817, 0.346183))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((0.501844, 0.626579))}\n\n\nSetCu2Wave()\n\n\ndef MakeTopasFPASizer(G2frame, FPdlg, mode, SetButtonStatus):\n \"\"\"Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. \n Parameter input is modeled after Topas input parameters.\n\n :param wx.Window FPdlg: Frame or Dialog where GUI will appear\n :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or \n (linear) position sensitive detector\n :param dict parmDict: dict to place parameters. If empty, default values from \n globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in \n the array. \n :returns: a sizer with the GUI controls\n \n \"\"\"\n\n def _onOK(event):\n XferFPAsettings(parmDict)\n SetButtonStatus(done=True)\n FPdlg.Destroy()\n\n def _onClose(event):\n SetButtonStatus()\n FPdlg.Destroy()\n\n def _onAddWave(event):\n parmDict['numWave'] += 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onRemWave(event):\n parmDict['numWave'] -= 1\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu5Wave(event):\n parmDict['wave'] = {i: v for i, v in enumerate((1.534753, 1.540596,\n 1.541058, 1.54441, 1.544721))}\n parmDict['int'] = {i: v for i, v in enumerate((0.0159, 0.5791, \n 0.0762, 0.2417, 0.0871))}\n parmDict['lwidth'] = {i: v for i, v in enumerate((3.6854, 0.437, \n 0.6, 0.52, 0.62))}\n parmDict['numWave'] = 5\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetCu2Wave(event):\n SetCu2Wave()\n parmDict['numWave'] = 2\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, mode, SetButtonStatus)\n\n def _onSetPoint(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBpoint',\n SetButtonStatus)\n\n def _onSetPSD(event):\n wx.CallAfter(MakeTopasFPASizer, G2frame, FPdlg, 'BBPSD',\n SetButtonStatus)\n\n def PlotTopasFPA(event):\n XferFPAsettings(parmDict)\n ttArr = np.arange(max(0.5, simParms['plotpos'] - simParms['calcwid'\n ]), simParms['plotpos'] + simParms['calcwid'], simParms['step'])\n intArr = np.zeros_like(ttArr)\n NISTpk = setupFPAcalc()\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr, simParms[\n 'plotpos'], simParms['calcwid'], simParms['step'])\n except Exception as err:\n msg = 'Error computing convolution, revise input'\n print(msg)\n print(err)\n return\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkPts = len(peakObj.peak)\n pkMax = peakObj.peak.max()\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n return\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset] += 10000 * peakObj.peak[\n :-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts] += 10000 * peakObj.peak / pkMax\n G2plt.PlotXY(G2frame, [(ttArr, intArr)], labelX='$2\\\\theta, deg$',\n labelY='Intensity (arbitrary)', Title='FPA peak', newPlot=True,\n lines=True)\n if FPdlg.GetSizer():\n FPdlg.GetSizer().Clear(True)\n numWave = parmDict['numWave']\n if mode == 'BBpoint':\n itemList = BraggBrentanoParms + BBPointDetector\n elif mode == 'BBPSD':\n itemList = BraggBrentanoParms + BBPSDDetector\n else:\n raise Exception('Unknown mode in MakeTopasFPASizer: ' + mode)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((-1, 5))\n waveSizer = wx.FlexGridSizer(cols=numWave + 1, hgap=3, vgap=5)\n for lbl, prm, defVal in zip((u'Wavelength (Å)', 'Rel. Intensity',\n u'Lorentz Width\\n(Å/1000)'), ('wave', 'int', 'lwidth'), (0.0, 1.0, 0.1)\n ):\n text = wx.StaticText(FPdlg, wx.ID_ANY, lbl, style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n waveSizer.Add(text, 0, wx.EXPAND)\n if prm not in parmDict:\n parmDict[prm] = {}\n for i in range(numWave):\n if i not in parmDict[prm]:\n parmDict[prm][i] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict[prm], i, size=(90, -1))\n waveSizer.Add(ctrl, 1, wx.ALIGN_CENTER_VERTICAL, 1)\n MainSizer.Add(waveSizer)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Add col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onAddWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Remove col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onRemWave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa1+2')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu2Wave)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'CuKa-5wave')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetCu5Wave)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Point Dect.')\n btn.Enable(not mode == 'BBpoint')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPoint)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'PSD')\n btn.Enable(not mode == 'BBPSD')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetPSD)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=5)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'label', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(FPdlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER\n )\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for lbl, defVal, text in itemList:\n prmSizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, lbl), 1, wx.\n ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 1)\n if lbl not in parmDict:\n parmDict[lbl] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, parmDict, lbl, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(FPdlg, wx.ID_ANY, text, size=(400, -1))\n txt.Wrap(380)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, PlotTopasFPA)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' at '))\n if 'plotpos' not in simParms:\n simParms['plotpos'] = simParms['minTT']\n ctrl = G2G.ValidatedTxtCtrl(FPdlg, simParms, 'plotpos', size=(70, -1))\n btnsizer.Add(ctrl)\n btnsizer.Add(wx.StaticText(FPdlg, wx.ID_ANY, ' deg.'))\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(FPdlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(FPdlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n FPdlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(FPdlg)\n FPdlg.SetMinSize(FPdlg.GetSize())\n FPdlg.SendSizeEvent()\n\n\ndef XferFPAsettings(InpParms):\n \"\"\"convert Topas-type parameters to SI units for NIST and place in a dict sorted\n according to use in each convoluter\n\n :param dict InpParms: a dict with Topas-like parameters, as set in \n :func:`MakeTopasFPASizer`\n :returns: a nested dict with global parameters and those for each convolution\n \"\"\"\n wavenums = range(InpParms['numWave'])\n source_wavelengths_m = 1e-10 * np.array([InpParms['wave'][i] for i in\n wavenums])\n la = [InpParms['int'][i] for i in wavenums]\n source_intensities = np.array(la) / max(la)\n source_lor_widths_m = 1e-10 * 0.001 * np.array([InpParms['lwidth'][i] for\n i in wavenums])\n source_gauss_widths_m = 1e-10 * 0.001 * np.array([(0.001) for i in\n wavenums])\n NISTparms['emission'] = {'emiss_wavelengths': source_wavelengths_m,\n 'emiss_intensities': source_intensities, 'emiss_gauss_widths':\n source_gauss_widths_m, 'emiss_lor_widths': source_lor_widths_m,\n 'crystallite_size_gauss': 1e-09 * InpParms.get('Size_G', 1000000.0),\n 'crystallite_size_lor': 1e-09 * InpParms.get('Size_L', 1000000.0)}\n if InpParms['filament_length'] == InpParms['receiving_slit_length']:\n InpParms['receiving_slit_length'] *= 1.00001\n NISTparms['axial'] = {'axDiv': 'full', 'slit_length_source': 0.001 *\n InpParms['filament_length'], 'slit_length_target': 0.001 * InpParms\n ['receiving_slit_length'], 'length_sample': 0.001 * InpParms[\n 'sample_length'], 'n_integral_points': 10, 'angI_deg': InpParms[\n 'soller_angle'], 'angD_deg': InpParms['soller_angle']}\n if InpParms.get('LAC_cm', 0) > 0:\n NISTparms['absorption'] = {'absorption_coefficient': InpParms[\n 'LAC_cm'] * 100, 'sample_thickness': 0.001 * InpParms[\n 'sample_thickness']}\n elif 'absorption' in NISTparms:\n del NISTparms['absorption']\n if InpParms.get('lpsd_equitorial_divergence', 0) > 0 and InpParms.get(\n 'lpsd_th2_angular_range', 0) > 0:\n PSDdetector_length_mm = np.arcsin(np.pi * InpParms[\n 'lpsd_th2_angular_range'] / 180.0) * InpParms['Rs']\n NISTparms['si_psd'] = {'equatorial_divergence_deg': InpParms[\n 'lpsd_equitorial_divergence'], 'si_psd_window_bounds': (0.0, \n PSDdetector_length_mm / 1000.0)}\n elif 'si_psd' in NISTparms:\n del NISTparms['si_psd']\n if InpParms.get('Specimen_Displacement'):\n NISTparms['displacement'] = {'specimen_displacement': 0.001 *\n InpParms['Specimen_Displacement']}\n elif 'displacement' in NISTparms:\n del NISTparms['displacement']\n if InpParms.get('receiving_slit_width'):\n NISTparms['receiver_slit'] = {'slit_width': 0.001 * InpParms[\n 'receiving_slit_width']}\n elif 'receiver_slit' in NISTparms:\n del NISTparms['receiver_slit']\n if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(\n 'tube-tails_rel-I', 0) > 0:\n NISTparms['tube_tails'] = {'main_width': 0.001 * InpParms.get(\n 'tube-tails_width', 0.0), 'tail_left': -0.001 * InpParms.get(\n 'tube-tails_L-tail', 0.0), 'tail_right': 0.001 * InpParms.get(\n 'tube-tails_R-tail', 0.0), 'tail_intens': InpParms.get(\n 'tube-tails_rel-I', 0.0)}\n elif 'tube_tails' in NISTparms:\n del NISTparms['tube_tails']\n max_wavelength = source_wavelengths_m[np.argmax(source_intensities)]\n NISTparms[''] = {'equatorial_divergence_deg': InpParms['divergence'],\n 'dominant_wavelength': max_wavelength, 'diffractometer_radius': \n 0.001 * InpParms['Rs'], 'oversampling': InpParms['convolution_steps']}\n\n\ndef setupFPAcalc():\n \"\"\"Create a peak profile object using the NIST XRD Fundamental \n Parameters Code. \n \n :returns: a profile object that can provide information on \n each convolution or compute the composite peak shape. \n \"\"\"\n p = FP.FP_profile(anglemode='twotheta',\n output_gaussian_smoother_bins_sigma=1.0, oversampling=NISTparms.get\n ('oversampling', 10))\n p.debug_cache = False\n for key in NISTparms:\n if key:\n p.set_parameters(convolver=key, **NISTparms[key])\n else:\n p.set_parameters(**NISTparms[key])\n return p\n\n\ndef doFPAcalc(NISTpk, ttArr, twotheta, calcwid, step):\n \"\"\"Compute a single peak using a NIST profile object\n\n :param object NISTpk: a peak profile computational object from the \n NIST XRD Fundamental Parameters Code, typically established from\n a call to :func:`SetupFPAcalc`\n :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)\n :param float twotheta: nominal center of peak (degrees)\n :param float calcwid: width to perform convolution (degrees)\n :param float step: step size\n \"\"\"\n center_bin_idx = min(ttArr.searchsorted(twotheta), len(ttArr) - 1)\n NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,\n twotheta_window_center_deg=ttArr[center_bin_idx],\n twotheta_approx_window_fullwidth_deg=calcwid)\n NISTpk.set_parameters(twotheta0_deg=twotheta)\n return center_bin_idx, NISTpk.compute_line_profile()\n\n\ndef MakeSimSizer(G2frame, dlg):\n \"\"\"Create a GUI to get simulation with parameters for Fundamental \n Parameters fitting. \n\n :param wx.Window dlg: Frame or Dialog where GUI will appear\n\n :returns: a sizer with the GUI controls \n \n \"\"\"\n\n def _onOK(event):\n msg = ''\n if simParms['minTT'] - simParms['calcwid'] / 1.5 < 0.1:\n msg += 'First peak minus half the calc width is too low'\n if simParms['maxTT'] + simParms['calcwid'] / 1.5 > 175:\n if msg:\n msg += '\\n'\n msg += 'Last peak plus half the calc width is too high'\n if simParms['npeaks'] < 8:\n if msg:\n msg += '\\n'\n msg += 'At least 8 peaks are needed'\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n return\n ttArr = np.arange(max(0.5, simParms['minTT'] - simParms['calcwid'] /\n 1.5), simParms['maxTT'] + simParms['calcwid'] / 1.5, simParms[\n 'step'])\n intArr = np.zeros_like(ttArr)\n peaklist = np.linspace(simParms['minTT'], simParms['maxTT'],\n simParms['npeaks'], endpoint=True)\n peakSpacing = (peaklist[-1] - peaklist[0]) / (len(peaklist) - 1)\n NISTpk = setupFPAcalc()\n minPtsHM = len(intArr)\n maxPtsHM = 0\n for num, twoth_peak in enumerate(peaklist):\n try:\n center_bin_idx, peakObj = doFPAcalc(NISTpk, ttArr,\n twoth_peak, simParms['calcwid'], simParms['step'])\n except:\n if msg:\n msg += '\\n'\n msg = 'Error computing convolution, revise input'\n continue\n if num == 0:\n G2plt.PlotFPAconvolutors(G2frame, NISTpk)\n pkMax = peakObj.peak.max()\n pkPts = len(peakObj.peak)\n minPtsHM = min(minPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n maxPtsHM = max(maxPtsHM, sum(peakObj.peak >= 0.5 * pkMax))\n startInd = center_bin_idx - pkPts // 2\n if startInd < 0:\n intArr[:startInd + pkPts] += 10000 * peakObj.peak[-startInd:\n ] / pkMax\n elif startInd > len(intArr):\n break\n elif startInd + pkPts >= len(intArr):\n offset = pkPts - len(intArr[startInd:])\n intArr[startInd:startInd + pkPts - offset\n ] += 10000 * peakObj.peak[:-offset] / pkMax\n else:\n intArr[startInd:startInd + pkPts\n ] += 10000 * peakObj.peak / pkMax\n if maxPtsHM * simParms['step'] > peakSpacing / 4:\n if msg:\n msg += '\\n'\n msg += (\n 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'\n .format(maxPtsHM * simParms['step'], peakSpacing))\n if minPtsHM < 10:\n if msg:\n msg += '\\n'\n msg += (\n 'There are only {} points above the half-max. 10 are needed. Dropping step size.'\n .format(minPtsHM))\n simParms['step'] *= 0.5\n if msg:\n G2G.G2MessageBox(dlg, msg, 'Bad input, try again')\n wx.CallAfter(MakeSimSizer, G2frame, dlg)\n return\n dlg.Destroy()\n wx.CallAfter(FitFPApeaks, ttArr, intArr, peaklist, maxPtsHM)\n\n def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM):\n \"\"\"Perform a peak fit to the FP simulated pattern\n \"\"\"\n plswait = wx.Dialog(G2frame, style=wx.DEFAULT_DIALOG_STYLE | wx.\n RESIZE_BORDER)\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n txt = wx.StaticText(plswait, wx.ID_ANY,\n 'Fitting peaks...\\nPlease wait...', style=wx.ALIGN_CENTER)\n vbox.Add(txt, 0, wx.ALL | wx.EXPAND)\n vbox.Add((1, 1), 1, wx.ALL | wx.EXPAND, 1)\n plswait.SetSizer(vbox)\n plswait.Layout()\n plswait.CenterOnParent()\n plswait.Show()\n wx.BeginBusyCursor()\n ints = list(NISTparms['emission']['emiss_intensities'])\n Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n if len(ints) > 1:\n ints[np.argmax(ints)] = -1\n Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)\n ] * 10000000000.0\n else:\n Lam2 = None\n histId = G2frame.AddSimulatedPowder(ttArr, intArr,\n 'NIST Fundamental Parameters simulation', Lam1, Lam2)\n controls = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, G2frame.root, 'Controls'))\n controldat = controls.get('data', {'deriv type': 'analytic',\n 'min dM/M': 0.001})\n Parms, Parms2 = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId\n (G2frame, histId, 'Instrument Parameters'))\n peakData = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Peak List'))\n bkg1, bkg2 = bkg = G2frame.GPXtree.GetItemPyData(G2gd.\n GetGPXtreeItemId(G2frame, histId, 'Background'))\n bkg1[1] = False\n bkg1[2] = 0\n bkg1[3] = 0.0\n limits = G2frame.GPXtree.GetItemPyData(G2gd.GetGPXtreeItemId(\n G2frame, histId, 'Limits'))\n try:\n Parms['SH/L'][1] = 0.25 * (NISTparms['axial']['length_sample'] +\n NISTparms['axial']['slit_length_source']) / NISTparms[''][\n 'diffractometer_radius']\n except:\n pass\n for pos in peaklist:\n i = ttArr.searchsorted(pos)\n area = sum(intArr[max(0, i - maxPtsHM):min(len(intArr), i +\n maxPtsHM)])\n peakData['peaks'].append(G2mth.setPeakparms(Parms, Parms2, pos,\n area))\n histData = G2frame.GPXtree.GetItemPyData(histId)\n bxye = np.zeros(len(histData[1][1]))\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False,\n controldat, None)[0]\n for pk in peakData['peaks']:\n pk[1] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in ('U', 'V', 'W', 'X', 'Y'):\n Parms[p][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n Parms['SH/L'][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ', peakData['peaks'], bkg,\n limits[1], Parms, Parms2, histData[1], bxye, [], False, controldat\n )[0]\n for p in Parms:\n if len(Parms[p]) == 3:\n Parms[p][0] = Parms[p][1]\n Parms[p][2] = False\n wx.EndBusyCursor()\n plswait.Destroy()\n pth = G2G.GetExportPath(G2frame)\n fldlg = wx.FileDialog(G2frame,\n 'Set name to save GSAS-II instrument parameters file', pth, '',\n 'instrument parameter files (*.instprm)|*.instprm', wx.FD_SAVE |\n wx.FD_OVERWRITE_PROMPT)\n try:\n if fldlg.ShowModal() == wx.ID_OK:\n filename = fldlg.GetPath()\n filename = os.path.splitext(filename)[0] + '.instprm'\n File = open(filename, 'w')\n File.write(\n '#GSAS-II instrument parameter file; do not add/delete items!\\n'\n )\n for item in Parms:\n File.write(item + ':' + str(Parms[item][1]) + '\\n')\n File.close()\n print('Instrument parameters saved to: ' + filename)\n finally:\n fldlg.Destroy()\n\n def _onClose(event):\n dlg.Destroy()\n\n def SetButtonStatus(done=False):\n OKbtn.Enable(bool(NISTparms))\n saveBtn.Enable(bool(NISTparms))\n if done:\n _onOK(None)\n\n def _onSetFPA(event):\n FPdlg = wx.Dialog(dlg, wx.ID_ANY, 'FPA parameters', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeTopasFPASizer(G2frame, FPdlg, 'BBpoint', SetButtonStatus)\n FPdlg.CenterOnParent()\n FPdlg.Raise()\n FPdlg.Show()\n\n def _onSaveFPA(event):\n filename = G2G.askSaveFile(G2frame, '', '.NISTfpa',\n 'dict of NIST FPA values', dlg)\n if not filename:\n return\n fp = open(filename, 'w')\n fp.write(\n '# parameters to be used in the NIST XRD Fundamental Parameters program\\n'\n )\n fp.write('{\\n')\n for key in sorted(NISTparms):\n fp.write(\" '\" + key + \"' : \" + str(NISTparms[key]) + ',')\n if not key:\n fp.write(' # global parameters')\n fp.write('\\n')\n fp.write('}\\n')\n fp.close()\n\n def _onReadFPA(event):\n filename = G2G.GetImportFile(G2frame, message=\n 'Read file with dict of values for NIST Fundamental Parameters',\n parent=dlg, wildcard='dict of NIST FPA values|*.NISTfpa')\n if not filename:\n return\n if not filename[0]:\n return\n try:\n txt = open(filename[0], 'r').read()\n NISTparms.clear()\n array = np.array\n d = eval(txt)\n NISTparms.update(d)\n except Exception as err:\n G2G.G2MessageBox(dlg, u'Error reading file {}:{}\\n'.format(\n filename, err), 'Bad dict input')\n SetButtonStatus()\n if dlg.GetSizer():\n dlg.GetSizer().Clear(True)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add(wx.StaticText(dlg, wx.ID_ANY,\n 'Fit Profile Parameters to Peaks from Fundamental Parameters',\n style=wx.ALIGN_CENTER), 0, wx.EXPAND)\n MainSizer.Add((-1, 5))\n prmSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=5)\n text = wx.StaticText(dlg, wx.ID_ANY, 'value', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n text = wx.StaticText(dlg, wx.ID_ANY, 'explanation', style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text, 0, wx.EXPAND)\n for key, defVal, text in (('minTT', 3.0,\n 'Location of first peak in 2theta (deg)'), ('maxTT', 123.0,\n 'Location of last peak in 2theta (deg)'), ('step', 0.01,\n 'Pattern step size (deg 2theta)'), ('npeaks', 13.0,\n 'Number of peaks'), ('calcwid', 2.0,\n 'Range to compute each peak (deg 2theta)')):\n if key not in simParms:\n simParms[key] = defVal\n ctrl = G2G.ValidatedTxtCtrl(dlg, simParms, key, size=(70, -1))\n prmSizer.Add(ctrl, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, text, size=(300, -1))\n txt.Wrap(280)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(dlg, wx.ID_ANY, 'Input FP vals')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON, _onSetFPA)\n saveBtn = wx.Button(dlg, wx.ID_ANY, 'Save FPA dict')\n btnsizer.Add(saveBtn)\n saveBtn.Bind(wx.EVT_BUTTON, _onSaveFPA)\n readBtn = wx.Button(dlg, wx.ID_ANY, 'Read FPA dict')\n btnsizer.Add(readBtn)\n readBtn.Bind(wx.EVT_BUTTON, _onReadFPA)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n txt = wx.StaticText(dlg, wx.ID_ANY, 'If you use this, please cite: ' +\n Citation, size=(350, -1))\n txt.Wrap(340)\n MainSizer.Add(txt, 0, wx.ALIGN_CENTER)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(dlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(dlg, wx.ID_CLOSE, 'Cancel')\n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1, 4), 1, wx.EXPAND, 1)\n OKbtn.Bind(wx.EVT_BUTTON, _onOK)\n Cbtn.Bind(wx.EVT_BUTTON, _onClose)\n SetButtonStatus()\n dlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(dlg)\n dlg.SetMinSize(dlg.GetSize())\n dlg.SendSizeEvent()\n dlg.Raise()\n\n\ndef GetFPAInput(G2frame):\n dlg = wx.Dialog(G2frame, wx.ID_ANY, 'FPA input', style=wx.\n DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n MakeSimSizer(G2frame, dlg)\n dlg.CenterOnParent()\n dlg.Show()\n return\n", "step-5": "# -*- coding: utf-8 -*-\n########### SVN repository information ###################\n# $Date: $\n# $Author: $\n# $Revision: $\n# $URL: $\n# $Id: $\n########### SVN repository information ###################\n'''\n*GSASIIfpaGUI: Fundamental Parameters Routines*\n===============================================\n\nThis module contains routines for getting Fundamental Parameters \nApproach (FPA) input, setting up for running the NIST XRD Fundamental \nParameters Code, plotting the convolutors and computing a set of peaks\ngenerated by that code. \n\n'''\nfrom __future__ import division, print_function\nimport wx\nimport os.path\nimport numpy as np\n\nimport NIST_profile as FP\n\nimport GSASIIpath\nimport GSASIIctrlGUI as G2G\nimport GSASIIdataGUI as G2gd\nimport GSASIIplot as G2plt\nimport GSASIImath as G2mth\nimport GSASIIpwd as G2pwd\n\nsimParms = {}\n'''Parameters to set range for pattern simulation\n'''\n\nparmDict = {'numWave':2}\n'''Parameter dict used for reading Topas-style values. These are \nconverted to SI units and placed into :data:`NISTparms`\n'''\n\nNISTparms = {}\n'''Parameters in a nested dict, with an entry for each concolutor. Entries in \nthose dicts have values in SI units (of course). NISTparms can be \ncan be input directly or can be from created from :data:`parmDict`\nby :func:`XferFPAsettings`\n'''\n\nBraggBrentanoParms = [\n ('divergence', 0.5, 'Bragg-Brentano divergence angle (degrees)'),\n ('soller_angle', 2.0, 'Soller slit axial divergence (degrees)'),\n ('Rs', 220, 'Diffractometer radius (mm)'),\n ('filament_length', 12., 'X-ray tube line focus length (mm)'),\n ('sample_length', 12., 'Illuminated sample length in axial direction (mm)'),\n ('receiving_slit_length', 12., 'Length of receiving slit in axial direction (mm)'),\n ('LAC_cm', 0.,'Linear absorption coef. adjusted for packing density (cm-1)'),\n ('sample_thickness', 1., 'Depth of sample (mm)'),\n ('convolution_steps', 8, 'Number of Fourier-space bins per two-theta step'),\n ('tube-tails_width', 0.04,'Tube filament width, in projection at takeoff angle (mm)'),\n ('tube-tails_L-tail', -1.,'Left-side tube tails width, in projection (mm)'), \n ('tube-tails_R-tail', 1.,'Right-side tube tails width, in projection (mm)'),\n ('tube-tails_rel-I', 0.001,'Tube tails fractional intensity (no units)'),\n ]\n'''FPA dict entries used in :func:`MakeTopasFPASizer`. Tuple contains\na dict key, a default value and a description. These are the parameters\nneeded for all Bragg Brentano instruments\n'''\n\nBBPointDetector = [\n ('receiving_slit_width', 0.2, 'Width of receiving slit (mm)'),]\n'''Additional FPA dict entries used in :func:`MakeTopasFPASizer` \nneeded for Bragg Brentano instruments with point detectors.\n'''\n\nBBPSDDetector = [\n ('lpsd_th2_angular_range', 3.0, 'Angular range observed by PSD (degrees 2Theta)'),\n ('lpsd_equitorial_divergence', 0.1, 'Equatorial divergence of the primary beam (degrees)'),]\n'''Additional FPA dict entries used in :func:`MakeTopasFPASizer` \nneeded for Bragg Brentano instruments with linear (1-D) PSD detectors.\n'''\n\nCitation = '''MH Mendenhall, K Mullen && JP Cline. (2015) J. Res. of NIST 120, 223-251. doi:10.6028/jres.120.014.\n'''\n \ndef SetCu2Wave():\n '''Set the parameters to the two-line Cu K alpha 1+2 spectrum\n '''\n parmDict['wave'] = {i:v for i,v in enumerate((1.540596,1.544493))}\n parmDict['int'] = {i:v for i,v in enumerate((0.653817, 0.346183))}\n parmDict['lwidth'] = {i:v for i,v in enumerate((0.501844,0.626579))}\nSetCu2Wave() # use these as default\n\ndef MakeTopasFPASizer(G2frame,FPdlg,mode,SetButtonStatus):\n '''Create a GUI with parameters for the NIST XRD Fundamental Parameters Code. \n Parameter input is modeled after Topas input parameters.\n\n :param wx.Window FPdlg: Frame or Dialog where GUI will appear\n :param str mode: either 'BBpoint' or 'BBPSD' for Bragg-Brentano point detector or \n (linear) position sensitive detector\n :param dict parmDict: dict to place parameters. If empty, default values from \n globals BraggBrentanoParms, BBPointDetector & BBPSDDetector will be placed in \n the array. \n :returns: a sizer with the GUI controls\n \n '''\n def _onOK(event):\n XferFPAsettings(parmDict)\n SetButtonStatus(done=True) # done=True triggers the simulation\n FPdlg.Destroy()\n def _onClose(event):\n SetButtonStatus()\n FPdlg.Destroy()\n def _onAddWave(event):\n parmDict['numWave'] += 1 \n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus)\n def _onRemWave(event):\n parmDict['numWave'] -= 1 \n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus)\n def _onSetCu5Wave(event):\n parmDict['wave'] = {i:v for i,v in enumerate((1.534753,1.540596,1.541058,1.54441,1.544721))}\n parmDict['int'] = {i:v for i,v in enumerate((0.0159, 0.5791, 0.0762, 0.2417, 0.0871))}\n parmDict['lwidth'] = {i:v for i,v in enumerate((3.6854, 0.437, 0.6, 0.52, 0.62))}\n parmDict['numWave'] = 5\n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus)\n def _onSetCu2Wave(event):\n SetCu2Wave()\n parmDict['numWave'] = 2\n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,mode,SetButtonStatus)\n def _onSetPoint(event):\n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,'BBpoint',SetButtonStatus)\n def _onSetPSD(event):\n wx.CallAfter(MakeTopasFPASizer,G2frame,FPdlg,'BBPSD',SetButtonStatus)\n def PlotTopasFPA(event):\n XferFPAsettings(parmDict)\n ttArr = np.arange(max(0.5,\n simParms['plotpos']-simParms['calcwid']),\n simParms['plotpos']+simParms['calcwid'],\n simParms['step'])\n intArr = np.zeros_like(ttArr)\n NISTpk = setupFPAcalc()\n try:\n center_bin_idx,peakObj = doFPAcalc(\n NISTpk,ttArr,simParms['plotpos'],simParms['calcwid'],\n simParms['step'])\n except Exception as err:\n msg = \"Error computing convolution, revise input\"\n print(msg)\n print(err)\n return\n G2plt.PlotFPAconvolutors(G2frame,NISTpk)\n pkPts = len(peakObj.peak)\n pkMax = peakObj.peak.max()\n startInd = center_bin_idx-(pkPts//2) #this should be the aligned start of the new data\n # scale peak so max I=10,000 and add into intensity array\n if startInd < 0:\n intArr[:startInd+pkPts] += 10000 * peakObj.peak[-startInd:]/pkMax\n elif startInd > len(intArr):\n return\n elif startInd+pkPts >= len(intArr):\n offset = pkPts - len( intArr[startInd:] )\n intArr[startInd:startInd+pkPts-offset] += 10000 * peakObj.peak[:-offset]/pkMax\n else:\n intArr[startInd:startInd+pkPts] += 10000 * peakObj.peak/pkMax\n G2plt.PlotXY(G2frame, [(ttArr, intArr)],\n labelX=r'$2\\theta, deg$',\n labelY=r'Intensity (arbitrary)',\n Title='FPA peak', newPlot=True, lines=True)\n\n if FPdlg.GetSizer(): FPdlg.GetSizer().Clear(True)\n numWave = parmDict['numWave']\n if mode == 'BBpoint':\n itemList = BraggBrentanoParms+BBPointDetector\n elif mode == 'BBPSD':\n itemList = BraggBrentanoParms+BBPSDDetector\n else:\n raise Exception('Unknown mode in MakeTopasFPASizer: '+mode)\n \n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add((-1,5))\n waveSizer = wx.FlexGridSizer(cols=numWave+1,hgap=3,vgap=5)\n for lbl,prm,defVal in zip(\n (u'Wavelength (\\u212b)','Rel. Intensity',u'Lorentz Width\\n(\\u212b/1000)'),\n ('wave','int','lwidth'),\n (0.0, 1.0, 0.1),\n ):\n text = wx.StaticText(FPdlg,wx.ID_ANY,lbl,style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n waveSizer.Add(text,0,wx.EXPAND)\n if prm not in parmDict: parmDict[prm] = {}\n for i in range(numWave):\n if i not in parmDict[prm]: parmDict[prm][i] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg,parmDict[prm],i,size=(90,-1))\n waveSizer.Add(ctrl,1,wx.ALIGN_CENTER_VERTICAL,1)\n MainSizer.Add(waveSizer)\n MainSizer.Add((-1,5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY,'Add col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onAddWave)\n btn = wx.Button(FPdlg, wx.ID_ANY,'Remove col')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onRemWave)\n btn = wx.Button(FPdlg, wx.ID_ANY,'CuKa1+2')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onSetCu2Wave)\n btn = wx.Button(FPdlg, wx.ID_ANY,'CuKa-5wave')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onSetCu5Wave)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,5))\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY,'Point Dect.')\n btn.Enable(not mode == 'BBpoint')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onSetPoint)\n btn = wx.Button(FPdlg, wx.ID_ANY,'PSD')\n btn.Enable(not mode == 'BBPSD')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onSetPSD)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,5))\n \n prmSizer = wx.FlexGridSizer(cols=3,hgap=3,vgap=5)\n text = wx.StaticText(FPdlg,wx.ID_ANY,'label',style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text,0,wx.EXPAND)\n text = wx.StaticText(FPdlg,wx.ID_ANY,'value',style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text,0,wx.EXPAND)\n text = wx.StaticText(FPdlg,wx.ID_ANY,'explanation',style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text,0,wx.EXPAND)\n for lbl,defVal,text in itemList:\n prmSizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,lbl),1,wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL,1)\n if lbl not in parmDict: parmDict[lbl] = defVal\n ctrl = G2G.ValidatedTxtCtrl(FPdlg,parmDict,lbl,size=(70,-1))\n prmSizer.Add(ctrl,1,wx.ALL|wx.ALIGN_CENTER_VERTICAL,1)\n txt = wx.StaticText(FPdlg,wx.ID_ANY,text,size=(400,-1))\n txt.Wrap(380)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n MainSizer.Add((-1,4),1,wx.EXPAND,1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(FPdlg, wx.ID_ANY, 'Plot peak')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,PlotTopasFPA)\n btnsizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,' at '))\n if 'plotpos' not in simParms: simParms['plotpos'] = simParms['minTT']\n ctrl = G2G.ValidatedTxtCtrl(FPdlg,simParms,'plotpos',size=(70,-1))\n btnsizer.Add(ctrl)\n btnsizer.Add(wx.StaticText(FPdlg,wx.ID_ANY,' deg.')) \n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,4),1,wx.EXPAND,1)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(FPdlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(FPdlg, wx.ID_CLOSE,\"Cancel\") \n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,4),1,wx.EXPAND,1)\n # bindings for close of window\n OKbtn.Bind(wx.EVT_BUTTON,_onOK)\n Cbtn.Bind(wx.EVT_BUTTON,_onClose)\n FPdlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(FPdlg)\n FPdlg.SetMinSize(FPdlg.GetSize())\n FPdlg.SendSizeEvent()\n\ndef XferFPAsettings(InpParms):\n '''convert Topas-type parameters to SI units for NIST and place in a dict sorted\n according to use in each convoluter\n\n :param dict InpParms: a dict with Topas-like parameters, as set in \n :func:`MakeTopasFPASizer`\n :returns: a nested dict with global parameters and those for each convolution\n '''\n wavenums = range(InpParms['numWave'])\n source_wavelengths_m = 1.e-10 * np.array([InpParms['wave'][i] for i in wavenums])\n la = [InpParms['int'][i] for i in wavenums]\n source_intensities = np.array(la)/max(la)\n source_lor_widths_m = 1.e-10 * 1.e-3 * np.array([InpParms['lwidth'][i] for i in wavenums])\n source_gauss_widths_m = 1.e-10 * 1.e-3 * np.array([0.001 for i in wavenums])\n \n NISTparms[\"emission\"] = {'emiss_wavelengths' : source_wavelengths_m,\n 'emiss_intensities' : source_intensities,\n 'emiss_gauss_widths' : source_gauss_widths_m,\n 'emiss_lor_widths' : source_lor_widths_m,\n 'crystallite_size_gauss' : 1.e-9 * InpParms.get('Size_G',1e6),\n 'crystallite_size_lor' : 1.e-9 * InpParms.get('Size_L',1e6)}\n \n if InpParms['filament_length'] == InpParms['receiving_slit_length']: # workaround: \n InpParms['receiving_slit_length'] *= 1.00001 # avoid bug when slit lengths are identical\n NISTparms[\"axial\"] = {\n 'axDiv':\"full\", 'slit_length_source' : 1e-3*InpParms['filament_length'],\n 'slit_length_target' : 1e-3*InpParms['receiving_slit_length'],\n 'length_sample' : 1e-3 * InpParms['sample_length'], \n 'n_integral_points' : 10,\n 'angI_deg' : InpParms['soller_angle'],\n 'angD_deg': InpParms['soller_angle']\n }\n if InpParms.get('LAC_cm',0) > 0:\n NISTparms[\"absorption\"] = {\n 'absorption_coefficient': InpParms['LAC_cm']*100, #like LaB6, in m^(-1)\n 'sample_thickness': 1e-3 * InpParms['sample_thickness'],\n }\n elif \"absorption\" in NISTparms:\n del NISTparms[\"absorption\"]\n\n if InpParms.get('lpsd_equitorial_divergence',0) > 0 and InpParms.get(\n 'lpsd_th2_angular_range',0) > 0:\n PSDdetector_length_mm=np.arcsin(np.pi*InpParms['lpsd_th2_angular_range']/180.\n )*InpParms['Rs'] # mm\n NISTparms[\"si_psd\"] = {\n 'equatorial_divergence_deg': InpParms['lpsd_equitorial_divergence'],\n 'si_psd_window_bounds': (0.,PSDdetector_length_mm/1000.)\n }\n elif \"si_psd\" in NISTparms:\n del NISTparms[\"si_psd\"]\n \n if InpParms.get('Specimen_Displacement'):\n NISTparms[\"displacement\"] = {'specimen_displacement': 1e-3 * InpParms['Specimen_Displacement']}\n elif \"displacement\" in NISTparms:\n del NISTparms[\"displacement\"]\n\n if InpParms.get('receiving_slit_width'):\n NISTparms[\"receiver_slit\"] = {'slit_width':1e-3*InpParms['receiving_slit_width']}\n elif \"receiver_slit\" in NISTparms:\n del NISTparms[\"receiver_slit\"]\n\n if InpParms.get('tube-tails_width', 0) > 0 and InpParms.get(\n 'tube-tails_rel-I',0) > 0:\n NISTparms[\"tube_tails\"] = {\n 'main_width' : 1e-3 * InpParms.get('tube-tails_width', 0.),\n 'tail_left' : -1e-3 * InpParms.get('tube-tails_L-tail',0.),\n 'tail_right' : 1e-3 * InpParms.get('tube-tails_R-tail',0.),\n 'tail_intens' : InpParms.get('tube-tails_rel-I',0.),}\n elif \"tube_tails\" in NISTparms:\n del NISTparms[\"tube_tails\"]\n\n # set Global parameters\n max_wavelength = source_wavelengths_m[np.argmax(source_intensities)]\n NISTparms[\"\"] = {\n 'equatorial_divergence_deg' : InpParms['divergence'],\n 'dominant_wavelength' : max_wavelength,\n 'diffractometer_radius' : 1e-3* InpParms['Rs'],\n 'oversampling' : InpParms['convolution_steps'],\n }\ndef setupFPAcalc():\n '''Create a peak profile object using the NIST XRD Fundamental \n Parameters Code. \n \n :returns: a profile object that can provide information on \n each convolution or compute the composite peak shape. \n '''\n p=FP.FP_profile(anglemode=\"twotheta\",\n output_gaussian_smoother_bins_sigma=1.0,\n oversampling=NISTparms.get('oversampling',10))\n p.debug_cache=False\n #set parameters for each convolver\n for key in NISTparms:\n if key:\n p.set_parameters(convolver=key,**NISTparms[key])\n else:\n p.set_parameters(**NISTparms[key])\n return p\n \ndef doFPAcalc(NISTpk,ttArr,twotheta,calcwid,step):\n '''Compute a single peak using a NIST profile object\n\n :param object NISTpk: a peak profile computational object from the \n NIST XRD Fundamental Parameters Code, typically established from\n a call to :func:`SetupFPAcalc`\n :param np.Array ttArr: an evenly-spaced grid of two-theta points (degrees)\n :param float twotheta: nominal center of peak (degrees)\n :param float calcwid: width to perform convolution (degrees)\n :param float step: step size\n '''\n # find closest point to twotheta (may be outside limits of the array)\n center_bin_idx=min(ttArr.searchsorted(twotheta),len(ttArr)-1)\n NISTpk.set_optimized_window(twotheta_exact_bin_spacing_deg=step,\n twotheta_window_center_deg=ttArr[center_bin_idx],\n twotheta_approx_window_fullwidth_deg=calcwid,\n )\n NISTpk.set_parameters(twotheta0_deg=twotheta)\n return center_bin_idx,NISTpk.compute_line_profile()\n\ndef MakeSimSizer(G2frame, dlg):\n '''Create a GUI to get simulation with parameters for Fundamental \n Parameters fitting. \n\n :param wx.Window dlg: Frame or Dialog where GUI will appear\n\n :returns: a sizer with the GUI controls \n \n '''\n def _onOK(event):\n msg = ''\n if simParms['minTT']-simParms['calcwid']/1.5 < 0.1:\n msg += 'First peak minus half the calc width is too low'\n if simParms['maxTT']+simParms['calcwid']/1.5 > 175:\n if msg: msg += '\\n'\n msg += 'Last peak plus half the calc width is too high'\n if simParms['npeaks'] < 8:\n if msg: msg += '\\n'\n msg += 'At least 8 peaks are needed'\n if msg:\n G2G.G2MessageBox(dlg,msg,'Bad input, try again')\n return\n # compute \"obs\" pattern\n ttArr = np.arange(max(0.5,\n simParms['minTT']-simParms['calcwid']/1.5),\n simParms['maxTT']+simParms['calcwid']/1.5,\n simParms['step'])\n intArr = np.zeros_like(ttArr)\n peaklist = np.linspace(simParms['minTT'],simParms['maxTT'],\n simParms['npeaks'],endpoint=True)\n peakSpacing = (peaklist[-1]-peaklist[0])/(len(peaklist)-1)\n NISTpk = setupFPAcalc()\n minPtsHM = len(intArr) # initialize points above half-max\n maxPtsHM = 0\n for num,twoth_peak in enumerate(peaklist):\n try:\n center_bin_idx,peakObj = doFPAcalc(\n NISTpk,ttArr,twoth_peak,simParms['calcwid'],\n simParms['step'])\n except:\n if msg: msg += '\\n'\n msg = \"Error computing convolution, revise input\"\n continue\n if num == 0: G2plt.PlotFPAconvolutors(G2frame,NISTpk)\n pkMax = peakObj.peak.max()\n pkPts = len(peakObj.peak)\n minPtsHM = min(minPtsHM,sum(peakObj.peak >= 0.5*pkMax)) # points above half-max\n maxPtsHM = max(maxPtsHM,sum(peakObj.peak >= 0.5*pkMax)) # points above half-max\n startInd = center_bin_idx-(pkPts//2) #this should be the aligned start of the new data\n # scale peak so max I=10,000 and add into intensity array\n if startInd < 0:\n intArr[:startInd+pkPts] += 10000 * peakObj.peak[-startInd:]/pkMax\n elif startInd > len(intArr):\n break\n elif startInd+pkPts >= len(intArr):\n offset = pkPts - len( intArr[startInd:] )\n intArr[startInd:startInd+pkPts-offset] += 10000 * peakObj.peak[:-offset]/pkMax\n else:\n intArr[startInd:startInd+pkPts] += 10000 * peakObj.peak/pkMax\n # check if peaks are too closely spaced\n if maxPtsHM*simParms['step'] > peakSpacing/4:\n if msg: msg += '\\n'\n msg += 'Maximum FWHM ({}) is too large compared to the peak spacing ({}). Decrease number of peaks or increase data range.'.format(\n maxPtsHM*simParms['step'], peakSpacing)\n # check if too few points across Hmax\n if minPtsHM < 10:\n if msg: msg += '\\n'\n msg += 'There are only {} points above the half-max. 10 are needed. Dropping step size.'.format(minPtsHM)\n simParms['step'] *= 0.5\n if msg:\n G2G.G2MessageBox(dlg,msg,'Bad input, try again')\n wx.CallAfter(MakeSimSizer,G2frame, dlg)\n return\n # pattern has been computed successfully\n dlg.Destroy()\n wx.CallAfter(FitFPApeaks,ttArr, intArr, peaklist, maxPtsHM) # do peakfit outside event callback\n\n def FitFPApeaks(ttArr, intArr, peaklist, maxPtsHM):\n '''Perform a peak fit to the FP simulated pattern\n '''\n plswait = wx.Dialog(G2frame,style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\n vbox = wx.BoxSizer(wx.VERTICAL)\n vbox.Add((1,1),1,wx.ALL|wx.EXPAND,1)\n txt = wx.StaticText(plswait,wx.ID_ANY,\n 'Fitting peaks...\\nPlease wait...',\n style=wx.ALIGN_CENTER)\n vbox.Add(txt,0,wx.ALL|wx.EXPAND)\n vbox.Add((1,1),1,wx.ALL|wx.EXPAND,1)\n plswait.SetSizer(vbox)\n plswait.Layout()\n plswait.CenterOnParent()\n plswait.Show() # post \"please wait\"\n wx.BeginBusyCursor()\n # pick out one or two most intense wavelengths\n ints = list(NISTparms['emission']['emiss_intensities'])\n Lam1 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)]*1e10\n if len(ints) > 1: \n ints[np.argmax(ints)] = -1\n Lam2 = NISTparms['emission']['emiss_wavelengths'][np.argmax(ints)]*1e10\n else:\n Lam2 = None\n histId = G2frame.AddSimulatedPowder(ttArr,intArr,\n 'NIST Fundamental Parameters simulation',\n Lam1,Lam2)\n controls = G2frame.GPXtree.GetItemPyData(\n G2gd.GetGPXtreeItemId(G2frame,G2frame.root,'Controls'))\n controldat = controls.get('data',\n {'deriv type':'analytic','min dM/M':0.001,}) #fil\n Parms,Parms2 = G2frame.GPXtree.GetItemPyData(\n G2gd.GetGPXtreeItemId(G2frame,histId,'Instrument Parameters'))\n peakData = G2frame.GPXtree.GetItemPyData(\n G2gd.GetGPXtreeItemId(G2frame,histId,'Peak List'))\n # set background to 0 with one term = 0; disable refinement\n bkg1,bkg2 = bkg = G2frame.GPXtree.GetItemPyData(\n G2gd.GetGPXtreeItemId(G2frame,histId,'Background'))\n bkg1[1]=False\n bkg1[2]=0\n bkg1[3]=0.0\n limits = G2frame.GPXtree.GetItemPyData(\n G2gd.GetGPXtreeItemId(G2frame,histId,'Limits'))\n # approximate asym correction\n try:\n Parms['SH/L'][1] = 0.25 * (\n NISTparms['axial']['length_sample']+\n NISTparms['axial']['slit_length_source']\n ) / NISTparms['']['diffractometer_radius']\n except:\n pass\n \n for pos in peaklist:\n i = ttArr.searchsorted(pos)\n area = sum(intArr[max(0,i-maxPtsHM):min(len(intArr),i+maxPtsHM)])\n peakData['peaks'].append(G2mth.setPeakparms(Parms,Parms2,pos,area))\n histData = G2frame.GPXtree.GetItemPyData(histId)\n # refine peak positions only\n bxye = np.zeros(len(histData[1][1]))\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'],\n bkg,limits[1],\n Parms,Parms2,histData[1],bxye,[],\n False,controldat,None)[0]\n # refine peak areas as well\n for pk in peakData['peaks']:\n pk[1] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'],\n bkg,limits[1],\n Parms,Parms2,histData[1],bxye,[],\n False,controldat)[0]\n # refine profile function\n for p in ('U', 'V', 'W', 'X', 'Y'):\n Parms[p][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'],\n bkg,limits[1],\n Parms,Parms2,histData[1],bxye,[],\n False,controldat)[0]\n # add in asymmetry\n Parms['SH/L'][2] = True\n peakData['sigDict'] = G2pwd.DoPeakFit('LSQ',peakData['peaks'],\n bkg,limits[1],\n Parms,Parms2,histData[1],bxye,[],\n False,controldat)[0]\n # reset \"initial\" profile\n for p in Parms:\n if len(Parms[p]) == 3:\n Parms[p][0] = Parms[p][1]\n Parms[p][2] = False\n wx.EndBusyCursor()\n plswait.Destroy() # remove \"please wait\"\n # save Iparms\n pth = G2G.GetExportPath(G2frame)\n fldlg = wx.FileDialog(G2frame, 'Set name to save GSAS-II instrument parameters file', pth, '', \n 'instrument parameter files (*.instprm)|*.instprm',wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)\n try:\n if fldlg.ShowModal() == wx.ID_OK:\n filename = fldlg.GetPath()\n # make sure extension is .instprm\n filename = os.path.splitext(filename)[0]+'.instprm'\n File = open(filename,'w')\n File.write(\"#GSAS-II instrument parameter file; do not add/delete items!\\n\")\n for item in Parms:\n File.write(item+':'+str(Parms[item][1])+'\\n')\n File.close()\n print ('Instrument parameters saved to: '+filename)\n finally:\n fldlg.Destroy()\n #GSASIIpath.IPyBreak()\n \n def _onClose(event):\n dlg.Destroy()\n def SetButtonStatus(done=False):\n OKbtn.Enable(bool(NISTparms))\n saveBtn.Enable(bool(NISTparms))\n if done: _onOK(None)\n def _onSetFPA(event):\n # Create a non-modal dialog for Topas-style FP input.\n FPdlg = wx.Dialog(dlg,wx.ID_ANY,'FPA parameters',\n style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)\n MakeTopasFPASizer(G2frame,FPdlg,'BBpoint',SetButtonStatus)\n FPdlg.CenterOnParent()\n FPdlg.Raise()\n FPdlg.Show() \n def _onSaveFPA(event):\n filename = G2G.askSaveFile(G2frame,'','.NISTfpa',\n 'dict of NIST FPA values',dlg)\n if not filename: return\n fp = open(filename,'w')\n fp.write('# parameters to be used in the NIST XRD Fundamental Parameters program\\n')\n fp.write('{\\n')\n for key in sorted(NISTparms):\n fp.write(\" '\"+key+\"' : \"+str(NISTparms[key])+\",\")\n if not key: fp.write(' # global parameters')\n fp.write('\\n')\n fp.write('}\\n')\n fp.close()\n def _onReadFPA(event):\n filename = G2G.GetImportFile(G2frame,\n message='Read file with dict of values for NIST Fundamental Parameters',\n parent=dlg,\n wildcard='dict of NIST FPA values|*.NISTfpa')\n if not filename: return\n if not filename[0]: return\n try:\n txt = open(filename[0],'r').read()\n NISTparms.clear()\n array = np.array\n d = eval(txt)\n NISTparms.update(d)\n except Exception as err:\n G2G.G2MessageBox(dlg,\n u'Error reading file {}:{}\\n'.format(filename,err),\n 'Bad dict input')\n #GSASIIpath.IPyBreak()\n SetButtonStatus()\n\n if dlg.GetSizer(): dlg.GetSizer().Clear(True)\n MainSizer = wx.BoxSizer(wx.VERTICAL)\n MainSizer.Add(wx.StaticText(dlg,wx.ID_ANY,\n 'Fit Profile Parameters to Peaks from Fundamental Parameters',\n style=wx.ALIGN_CENTER),0,wx.EXPAND)\n MainSizer.Add((-1,5))\n prmSizer = wx.FlexGridSizer(cols=2,hgap=3,vgap=5)\n text = wx.StaticText(dlg,wx.ID_ANY,'value',style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text,0,wx.EXPAND)\n text = wx.StaticText(dlg,wx.ID_ANY,'explanation',style=wx.ALIGN_CENTER)\n text.SetBackgroundColour(wx.WHITE)\n prmSizer.Add(text,0,wx.EXPAND)\n for key,defVal,text in (\n ('minTT',3.,'Location of first peak in 2theta (deg)'),\n ('maxTT',123.,'Location of last peak in 2theta (deg)'),\n ('step',0.01,'Pattern step size (deg 2theta)'),\n ('npeaks',13.,'Number of peaks'),\n ('calcwid',2.,'Range to compute each peak (deg 2theta)'),\n ):\n if key not in simParms: simParms[key] = defVal\n ctrl = G2G.ValidatedTxtCtrl(dlg,simParms,key,size=(70,-1))\n prmSizer.Add(ctrl,1,wx.ALL|wx.ALIGN_CENTER_VERTICAL,1)\n txt = wx.StaticText(dlg,wx.ID_ANY,text,size=(300,-1))\n txt.Wrap(280)\n prmSizer.Add(txt)\n MainSizer.Add(prmSizer)\n\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n btn = wx.Button(dlg, wx.ID_ANY,'Input FP vals')\n btnsizer.Add(btn)\n btn.Bind(wx.EVT_BUTTON,_onSetFPA)\n saveBtn = wx.Button(dlg, wx.ID_ANY,'Save FPA dict')\n btnsizer.Add(saveBtn)\n saveBtn.Bind(wx.EVT_BUTTON,_onSaveFPA)\n readBtn = wx.Button(dlg, wx.ID_ANY,'Read FPA dict')\n btnsizer.Add(readBtn)\n readBtn.Bind(wx.EVT_BUTTON,_onReadFPA)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,4),1,wx.EXPAND,1)\n txt = wx.StaticText(dlg,wx.ID_ANY,\n 'If you use this, please cite: '+Citation,\n size=(350,-1))\n txt.Wrap(340)\n MainSizer.Add(txt,0,wx.ALIGN_CENTER)\n btnsizer = wx.BoxSizer(wx.HORIZONTAL)\n OKbtn = wx.Button(dlg, wx.ID_OK)\n OKbtn.SetDefault()\n btnsizer.Add(OKbtn)\n Cbtn = wx.Button(dlg, wx.ID_CLOSE,\"Cancel\") \n btnsizer.Add(Cbtn)\n MainSizer.Add(btnsizer, 0, wx.ALIGN_CENTER, 0)\n MainSizer.Add((-1,4),1,wx.EXPAND,1)\n # bindings for close of window\n OKbtn.Bind(wx.EVT_BUTTON,_onOK)\n Cbtn.Bind(wx.EVT_BUTTON,_onClose)\n SetButtonStatus()\n dlg.SetSizer(MainSizer)\n MainSizer.Layout()\n MainSizer.Fit(dlg)\n dlg.SetMinSize(dlg.GetSize())\n dlg.SendSizeEvent()\n dlg.Raise()\n \ndef GetFPAInput(G2frame):\n dlg = wx.Dialog(G2frame,wx.ID_ANY,'FPA input',\n style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)\n MakeSimSizer(G2frame,dlg)\n dlg.CenterOnParent()\n dlg.Show()\n return\n \n", "step-ids": [ 7, 8, 9, 10, 11 ] }
[ 7, 8, 9, 10, 11 ]
import configparser # CONFIG config = configparser.ConfigParser() config.read('dwh.cfg') # DISTRIBUTION SCHEMA schema = ("""CREATE SCHEMA IF NOT EXISTS public; SET search_path TO public;""") # DROP TABLES staging_events_table_drop = ("DROP TABLE IF EXISTS staging_events;") staging_songs_table_drop = ("DROP TABLE IF EXISTS staging_songs;") songplay_table_drop = ("DROP TABLE IF EXISTS songplay;") users_table_drop = ("DROP TABLE IF EXISTS users;") song_table_drop = ("DROP TABLE IF EXISTS song;") artist_table_drop = ("DROP TABLE IF EXISTS artist;") time_table_drop = ("DROP TABLE IF EXISTS time;") # CREATE STAGING TABLES staging_events_table_create = ("""CREATE TABLE staging_events( artist VARCHAR, auth VARCHAR, first_name VARCHAR, gender CHAR(16), item_in_session INTEGER, last_name VARCHAR, length FLOAT, level VARCHAR(10), location VARCHAR, method VARCHAR(4), page VARCHAR(16), registration VARCHAR, session_id INTEGER, song VARCHAR, status INTEGER, ts BIGINT, user_agent VARCHAR, user_id INTEGER);""") staging_songs_table_create = ("""CREATE TABLE staging_songs( song_id VARCHAR, num_songs INTEGER, artist_id VARCHAR, artist_latitude VARCHAR, artist_longitude VARCHAR, artist_location VARCHAR, artist_name VARCHAR, title VARCHAR, duration FLOAT, year INTEGER);""") # CREATE FACT TABLE songplay_table_create = ("""CREATE TABLE songplay ( songplay_id INTEGER IDENTITY(0,1) sortkey, start_time TIMESTAMP, user_id INTEGER, level VARCHAR(10), song_id VARCHAR distkey, artist_id VARCHAR, session_id INTEGER, location VARCHAR, user_agent VARCHAR);""") # CREATE DIMENSION TABLES users_table_create = ("""CREATE TABLE users ( user_id INTEGER sortkey distkey, first_name VARCHAR, last_name VARCHAR, gender CHAR(16), level VARCHAR(10));""") song_table_create = ("""CREATE TABLE song ( song_id VARCHAR sortkey distkey, title VARCHAR, artist_id VARCHAR, year INTEGER, duration FLOAT);""") artist_table_create = ("""CREATE TABLE artist ( artist_id VARCHAR sortkey distkey, artist_name VARCHAR, artist_location VARCHAR, artist_latitude VARCHAR, artist_longitude VARCHAR);""") time_table_create = ("""CREATE TABLE time ( start_time TIMESTAMP sortkey distkey, hour INTEGER, day INTEGER, week INTEGER, month INTEGER, year INTEGER, weekday INTEGER);""") # COPY FROM S3 INTO STAGING TABLES staging_events_copy = ("""COPY staging_events FROM 's3://udacity-dend/log_data' CREDENTIALS 'aws_iam_role={}' COMPUPDATE OFF REGION 'us-west-2' FORMAT AS JSON 's3://udacity-dend/log_json_path.json'; """).format("IAM ARN") #limiting data due to execution time - remove prefix /A/A/ to copy entire file staging_songs_copy = ("""COPY staging_songs FROM 's3://udacity-dend/song_data' CREDENTIALS 'aws_iam_role={}' COMPUPDATE OFF REGION 'us-west-2' JSON 'auto' truncatecolumns; """).format("IAM ARN") # INSERT FROM STAGING TO FINAL TABLES songplay_table_insert =("""INSERT INTO songplay(start_time, user_id, level, song_id, artist_id, session_id,location, user_agent) SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time, se.user_id, se.level, ss.song_id, ss.artist_id, se.session_id, se.location, se.user_agent FROM staging_events se, staging_songs ss WHERE se.page = 'NextSong' AND se.artist = ss.artist_name AND se.length = ss.duration""") users_table_insert = ("""INSERT INTO users (user_id, first_name, last_name, gender, level) SELECT se.user_id, se.first_name, se.last_name, se.gender, se.level FROM staging_events se""") song_table_insert = ("""INSERT INTO song (song_id, title, artist_id, year, duration) SELECT ss.song_id, ss.title, ss.artist_id, ss.year, ss.duration FROM staging_songs ss""") artist_table_insert = ("""INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude) SELECT ss.artist_id, ss.artist_name, ss.artist_location, ss.artist_latitude, ss.artist_longitude FROM staging_songs ss""") time_table_insert = ("""INSERT INTO time(start_time, hour, day, week, month, year, weekday) SELECT start_time, EXTRACT(hour from start_time), EXTRACT(day from start_time), EXTRACT(week from start_time), EXTRACT(month from start_time), EXTRACT(year from start_time), EXTRACT(dayofweek from start_time) FROM songplay""") #TEST QUERIES test1 = ("""SELECT * FROM songplay LIMIT 1; """) test2 = ("""SELECT * FROM users LIMIT 1; """) test3 = ("""SELECT * FROM song LIMIT 1; """) test4 = ("""SELECT * FROM artist LIMIT 1; """) test5 = ("""SELECT * FROM time LIMIT 1; """) # QUERY LISTS create_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, users_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, users_table_drop, song_table_drop, artist_table_drop, time_table_drop] copy_table_queries = [staging_events_copy, staging_songs_copy] insert_table_queries = [songplay_table_insert, users_table_insert, song_table_insert, artist_table_insert, time_table_insert] test_queries = [test1, test2, test3, test4, test5]
normal
{ "blob_id": "65b7a14c54cd988185bac54fd8a31330966f8ba9", "index": 1916, "step-1": "<mask token>\n", "step-2": "<mask token>\nconfig.read('dwh.cfg')\n<mask token>\n", "step-3": "<mask token>\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\nschema = \"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\"\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nusers_table_drop = 'DROP TABLE IF EXISTS users;'\nsong_table_drop = 'DROP TABLE IF EXISTS song;'\nartist_table_drop = 'DROP TABLE IF EXISTS artist;'\ntime_table_drop = 'DROP TABLE IF EXISTS time;'\nstaging_events_table_create = \"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\"\nstaging_songs_table_create = \"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\"\nsongplay_table_create = \"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\"\nusers_table_create = \"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\"\nsong_table_create = \"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\"\nartist_table_create = \"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\"\ntime_table_create = \"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\"\nstaging_events_copy = (\n \"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\"\n .format('IAM ARN'))\nstaging_songs_copy = (\n \"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\"\n .format('IAM ARN'))\nsongplay_table_insert = \"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\"\nusers_table_insert = \"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\"\nsong_table_insert = \"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\"\nartist_table_insert = \"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\"\ntime_table_insert = \"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\"\ntest1 = 'SELECT * FROM songplay LIMIT 1; '\ntest2 = 'SELECT * FROM users LIMIT 1; '\ntest3 = 'SELECT * FROM song LIMIT 1; '\ntest4 = 'SELECT * FROM artist LIMIT 1; '\ntest5 = 'SELECT * FROM time LIMIT 1; '\ncreate_table_queries = [staging_events_table_create,\n staging_songs_table_create, songplay_table_create, users_table_create,\n song_table_create, artist_table_create, time_table_create]\ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, users_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\ninsert_table_queries = [songplay_table_insert, users_table_insert,\n song_table_insert, artist_table_insert, time_table_insert]\ntest_queries = [test1, test2, test3, test4, test5]\n", "step-4": "import configparser\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\nschema = \"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\"\nstaging_events_table_drop = 'DROP TABLE IF EXISTS staging_events;'\nstaging_songs_table_drop = 'DROP TABLE IF EXISTS staging_songs;'\nsongplay_table_drop = 'DROP TABLE IF EXISTS songplay;'\nusers_table_drop = 'DROP TABLE IF EXISTS users;'\nsong_table_drop = 'DROP TABLE IF EXISTS song;'\nartist_table_drop = 'DROP TABLE IF EXISTS artist;'\ntime_table_drop = 'DROP TABLE IF EXISTS time;'\nstaging_events_table_create = \"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\"\nstaging_songs_table_create = \"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\"\nsongplay_table_create = \"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\"\nusers_table_create = \"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\"\nsong_table_create = \"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\"\nartist_table_create = \"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\"\ntime_table_create = \"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\"\nstaging_events_copy = (\n \"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\"\n .format('IAM ARN'))\nstaging_songs_copy = (\n \"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\"\n .format('IAM ARN'))\nsongplay_table_insert = \"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\"\nusers_table_insert = \"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\"\nsong_table_insert = \"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\"\nartist_table_insert = \"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\"\ntime_table_insert = \"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\"\ntest1 = 'SELECT * FROM songplay LIMIT 1; '\ntest2 = 'SELECT * FROM users LIMIT 1; '\ntest3 = 'SELECT * FROM song LIMIT 1; '\ntest4 = 'SELECT * FROM artist LIMIT 1; '\ntest5 = 'SELECT * FROM time LIMIT 1; '\ncreate_table_queries = [staging_events_table_create,\n staging_songs_table_create, songplay_table_create, users_table_create,\n song_table_create, artist_table_create, time_table_create]\ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop,\n songplay_table_drop, users_table_drop, song_table_drop,\n artist_table_drop, time_table_drop]\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\ninsert_table_queries = [songplay_table_insert, users_table_insert,\n song_table_insert, artist_table_insert, time_table_insert]\ntest_queries = [test1, test2, test3, test4, test5]\n", "step-5": "import configparser\n\n\n# CONFIG\nconfig = configparser.ConfigParser()\nconfig.read('dwh.cfg')\n\n# DISTRIBUTION SCHEMA\nschema = (\"\"\"CREATE SCHEMA IF NOT EXISTS public;\n SET search_path TO public;\"\"\")\n\n# DROP TABLES\n\nstaging_events_table_drop = (\"DROP TABLE IF EXISTS staging_events;\") \nstaging_songs_table_drop = (\"DROP TABLE IF EXISTS staging_songs;\") \nsongplay_table_drop = (\"DROP TABLE IF EXISTS songplay;\") \nusers_table_drop = (\"DROP TABLE IF EXISTS users;\")\nsong_table_drop = (\"DROP TABLE IF EXISTS song;\")\nartist_table_drop = (\"DROP TABLE IF EXISTS artist;\") \ntime_table_drop = (\"DROP TABLE IF EXISTS time;\") \n\n# CREATE STAGING TABLES\n\nstaging_events_table_create = (\"\"\"CREATE TABLE staging_events(\n artist VARCHAR,\n auth VARCHAR,\n first_name VARCHAR,\n gender CHAR(16),\n item_in_session INTEGER,\n last_name VARCHAR,\n length FLOAT,\n level VARCHAR(10),\n location VARCHAR,\n method VARCHAR(4),\n page VARCHAR(16),\n registration VARCHAR,\n session_id INTEGER,\n song VARCHAR,\n status INTEGER,\n ts BIGINT,\n user_agent VARCHAR,\n user_id INTEGER);\"\"\") \n\nstaging_songs_table_create = (\"\"\"CREATE TABLE staging_songs(\n song_id VARCHAR,\n num_songs INTEGER,\n artist_id VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR,\n artist_location VARCHAR,\n artist_name VARCHAR,\n title VARCHAR,\n duration FLOAT,\n year INTEGER);\"\"\")\n\n# CREATE FACT TABLE\nsongplay_table_create = (\"\"\"CREATE TABLE songplay (\n songplay_id INTEGER IDENTITY(0,1) sortkey,\n start_time TIMESTAMP, \n user_id INTEGER,\n level VARCHAR(10),\n song_id VARCHAR distkey,\n artist_id VARCHAR,\n session_id INTEGER,\n location VARCHAR,\n user_agent VARCHAR);\"\"\") \n\n# CREATE DIMENSION TABLES\nusers_table_create = (\"\"\"CREATE TABLE users (\n user_id INTEGER sortkey distkey,\n first_name VARCHAR,\n last_name VARCHAR,\n gender CHAR(16),\n level VARCHAR(10));\"\"\")\n\nsong_table_create = (\"\"\"CREATE TABLE song (\n song_id VARCHAR sortkey distkey,\n title VARCHAR,\n artist_id VARCHAR,\n year INTEGER,\n duration FLOAT);\"\"\")\n\n\nartist_table_create = (\"\"\"CREATE TABLE artist (\n artist_id VARCHAR sortkey distkey,\n artist_name VARCHAR,\n artist_location VARCHAR,\n artist_latitude VARCHAR,\n artist_longitude VARCHAR);\"\"\") \n\ntime_table_create = (\"\"\"CREATE TABLE time (\n start_time TIMESTAMP sortkey distkey,\n hour INTEGER,\n day INTEGER,\n week INTEGER,\n month INTEGER,\n year INTEGER,\n weekday INTEGER);\"\"\") \n\n# COPY FROM S3 INTO STAGING TABLES\n\nstaging_events_copy = (\"\"\"COPY staging_events\n FROM 's3://udacity-dend/log_data'\n CREDENTIALS 'aws_iam_role={}' \n COMPUPDATE OFF REGION 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n \"\"\").format(\"IAM ARN\")\n\n#limiting data due to execution time - remove prefix /A/A/ to copy entire file\nstaging_songs_copy = (\"\"\"COPY staging_songs \n FROM 's3://udacity-dend/song_data'\n CREDENTIALS 'aws_iam_role={}'\n COMPUPDATE OFF REGION 'us-west-2'\n JSON 'auto' truncatecolumns;\n \"\"\").format(\"IAM ARN\")\n\n# INSERT FROM STAGING TO FINAL TABLES\n\nsongplay_table_insert =(\"\"\"INSERT INTO songplay(start_time, user_id, level, \n song_id, artist_id, session_id,location, user_agent)\n SELECT DISTINCT TIMESTAMP 'epoch' + ts/1000 *INTERVAL '1second' as start_time,\n se.user_id, \n se.level, \n ss.song_id,\n ss.artist_id,\n se.session_id,\n se.location,\n se.user_agent\n FROM staging_events se, staging_songs ss\n WHERE se.page = 'NextSong'\n AND se.artist = ss.artist_name\n AND se.length = ss.duration\"\"\")\n\nusers_table_insert = (\"\"\"INSERT INTO users (user_id, first_name, last_name, gender, level)\n SELECT \n se.user_id, \n se.first_name, \n se.last_name,\n se.gender,\n se.level\n FROM staging_events se\"\"\")\n\nsong_table_insert = (\"\"\"INSERT INTO song (song_id, title, artist_id, year, duration)\n SELECT \n ss.song_id, \n ss.title, \n ss.artist_id,\n ss.year,\n ss.duration\n FROM staging_songs ss\"\"\")\n\nartist_table_insert = (\"\"\"INSERT INTO artist (artist_id, artist_name, artist_location, artist_latitude, artist_longitude)\n SELECT \n ss.artist_id,\n ss.artist_name, \n ss.artist_location, \n ss.artist_latitude,\n ss.artist_longitude\n FROM staging_songs ss\"\"\")\n\ntime_table_insert = (\"\"\"INSERT INTO time(start_time, hour, day, week, month, year, weekday)\n SELECT start_time, \n EXTRACT(hour from start_time),\n EXTRACT(day from start_time),\n EXTRACT(week from start_time),\n EXTRACT(month from start_time),\n EXTRACT(year from start_time),\n EXTRACT(dayofweek from start_time)\n FROM songplay\"\"\")\n\n\n#TEST QUERIES\n\ntest1 = (\"\"\"SELECT * FROM songplay LIMIT 1; \"\"\")\ntest2 = (\"\"\"SELECT * FROM users LIMIT 1; \"\"\")\ntest3 = (\"\"\"SELECT * FROM song LIMIT 1; \"\"\")\ntest4 = (\"\"\"SELECT * FROM artist LIMIT 1; \"\"\")\ntest5 = (\"\"\"SELECT * FROM time LIMIT 1; \"\"\")\n\n# QUERY LISTS\n\ncreate_table_queries = [staging_events_table_create, staging_songs_table_create, songplay_table_create, users_table_create, \n song_table_create, artist_table_create, time_table_create]\n \ndrop_table_queries = [staging_events_table_drop, staging_songs_table_drop, songplay_table_drop, users_table_drop, \n song_table_drop, artist_table_drop, time_table_drop]\n\ncopy_table_queries = [staging_events_copy, staging_songs_copy]\n\n\ninsert_table_queries = [songplay_table_insert, users_table_insert, song_table_insert, artist_table_insert, time_table_insert]\n\n\ntest_queries = [test1, test2, test3, test4, test5]", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import nox @nox.session(python=["3.9", "3.8", "3.7", "3.6"], venv_backend="conda", venv_params=["--use-local"]) def test(session): """Add tests """ session.install() session.run("pytest") @nox.session(python=["3.9", "3.8", "3.7", "3.6"]) def lint(session): """Lint the code with flake8. """ session.install("flake8") session.run("flake8", "")
normal
{ "blob_id": "9aecf297ed36784d69e2be6fada31f7c1ac37500", "index": 4778, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\[email protected](python=['3.9', '3.8', '3.7', '3.6'], venv_backend='conda',\n venv_params=['--use-local'])\ndef test(session):\n \"\"\"Add tests\n \"\"\"\n session.install()\n session.run('pytest')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\[email protected](python=['3.9', '3.8', '3.7', '3.6'], venv_backend='conda',\n venv_params=['--use-local'])\ndef test(session):\n \"\"\"Add tests\n \"\"\"\n session.install()\n session.run('pytest')\n\n\[email protected](python=['3.9', '3.8', '3.7', '3.6'])\ndef lint(session):\n \"\"\"Lint the code with flake8.\n \"\"\"\n session.install('flake8')\n session.run('flake8', '')\n", "step-4": "import nox\n\n\[email protected](python=['3.9', '3.8', '3.7', '3.6'], venv_backend='conda',\n venv_params=['--use-local'])\ndef test(session):\n \"\"\"Add tests\n \"\"\"\n session.install()\n session.run('pytest')\n\n\[email protected](python=['3.9', '3.8', '3.7', '3.6'])\ndef lint(session):\n \"\"\"Lint the code with flake8.\n \"\"\"\n session.install('flake8')\n session.run('flake8', '')\n", "step-5": "import nox\n\[email protected](python=[\"3.9\", \"3.8\", \"3.7\", \"3.6\"], venv_backend=\"conda\", venv_params=[\"--use-local\"])\ndef test(session):\n \"\"\"Add tests\n \"\"\"\n session.install()\n session.run(\"pytest\")\n\[email protected](python=[\"3.9\", \"3.8\", \"3.7\", \"3.6\"])\ndef lint(session):\n \"\"\"Lint the code with flake8.\n \"\"\"\n session.install(\"flake8\")\n session.run(\"flake8\", \"\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- """ Created on Wed Aug 18 16:11:44 2021 @author: ignacio """ import matplotlib.pyplot as plt from numpy.linalg import inv as invertir from time import perf_counter import numpy as np def matriz_laplaciana(N, t=np.single): # funcion obtenida de clase e=np.eye(N)-np.eye(N,N,1) return t(e+e.T) Ns = [2, 5, 10,12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200, 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000] corridas = 10 for corrida in range(corridas): tiempo = [] memoria = [] name = (f"single{corrida}.txt") fid = open(name,"w") for i in Ns: print(f"i = {i}") A = matriz_laplaciana(i) t1 = perf_counter() invertir(A) t2 = perf_counter() dt = t2 - t1 size = 3 * (i**2) * 32 tiempo.append(dt) memoria.append(size) fid.write(f"{i} {dt} {size}\n") print(f"Tiempo transcurrido = {dt} s") print(f"Mmoria usada = {size} bytes") fid.flush() fid.close() dim = [] tim = [] mem = [] for n in range(10): dimension = [] time = [] memory = [] with open(f"single{n}.txt", "r") as f: lineas = [linea.split() for linea in f] for i in lineas: dimension.append(int(i[0])) time.append(float(i[1])) memory.append(int(i[2])) dim.append(dimension) tim.append(time) mem.append(memory) #Grafico superior plt.subplot(2, 1, 1) plt.plot(dim[0],tim[0],"-o") plt.plot(dim[0],tim[1],"-o") plt.plot(dim[0],tim[2],"-o") plt.plot(dim[0],tim[3],"-o") plt.plot(dim[0],tim[4],"-o") plt.plot(dim[0],tim[5],"-o") plt.plot(dim[0],tim[6],"-o") plt.plot(dim[0],tim[7],"-o") plt.plot(dim[0],tim[8],"-o") plt.plot(dim[0],tim[9],"-o") plt.yscale('log') plt.xscale('log') xticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000] xtext = ["", "", "", "", "", "", "", "", "", "", ""] yticks = [0.1/1000, 1/1000, 10/1000, 0.1, 1, 10, 60, 600] ytext = ["0.1 ms", "1 ms", "10 ms", "0.1 s", "1 s", "10 s", "1 min", "10 min"] plt.yticks(yticks, ytext) plt.xticks(xticks, xtext) plt.title("Rendimiento caso1_single") plt.ylabel("Tiempo transcurrido (s)") plt.grid(True) #Grafico inferior plt.subplot(2, 1, 2) plt.plot(Ns,memoria,'-ob') plt.yscale('log') plt.xscale('log') xticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000] xtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000] yticks = [1000,10000, 100000, 1000000, 10000000, 100000000, 1000000000, 100000000000] ytext = ["1 KB ", "10 KB", "100 KB", "1 MB", "10 MB", "100 MB", "1 GB", "10 GB"] plt.axhline(y=4000000000, linestyle="--",color="black") # RAM 4 GB plt.yticks(yticks, ytext) plt.xticks(xticks, xtext, rotation=45) plt.xlabel("Tamaño matriz N") plt.ylabel("Uso memoria (bytes)") plt.grid(True) plt.savefig("Rendimiento caso1_single.png")
normal
{ "blob_id": "86345702bcd423bc31e29b1d28aa9c438629297d", "index": 7331, "step-1": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\n<mask token>\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\n<mask token>\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\n<mask token>\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\n<mask token>\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n", "step-3": "<mask token>\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\nNs = [2, 5, 10, 12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200,\n 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\ncorridas = 10\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\ndim = []\ntim = []\nmem = []\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = ['', '', '', '', '', '', '', '', '', '', '']\nyticks = [0.1 / 1000, 1 / 1000, 10 / 1000, 0.1, 1, 10, 60, 600]\nytext = ['0.1 ms', '1 ms', '10 ms', '0.1 s', '1 s', '10 s', '1 min', '10 min']\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nyticks = [1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, \n 100000000000]\nytext = ['1 KB ', '10 KB', '100 KB', '1 MB', '10 MB', '100 MB', '1 GB', '10 GB'\n ]\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n", "step-4": "<mask token>\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv as invertir\nfrom time import perf_counter\nimport numpy as np\n\n\ndef matriz_laplaciana(N, t=np.single):\n e = np.eye(N) - np.eye(N, N, 1)\n return t(e + e.T)\n\n\nNs = [2, 5, 10, 12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200,\n 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\ncorridas = 10\nfor corrida in range(corridas):\n tiempo = []\n memoria = []\n name = f'single{corrida}.txt'\n fid = open(name, 'w')\n for i in Ns:\n print(f'i = {i}')\n A = matriz_laplaciana(i)\n t1 = perf_counter()\n invertir(A)\n t2 = perf_counter()\n dt = t2 - t1\n size = 3 * i ** 2 * 32\n tiempo.append(dt)\n memoria.append(size)\n fid.write(f'{i} {dt} {size}\\n')\n print(f'Tiempo transcurrido = {dt} s')\n print(f'Mmoria usada = {size} bytes')\n fid.flush()\nfid.close()\ndim = []\ntim = []\nmem = []\nfor n in range(10):\n dimension = []\n time = []\n memory = []\n with open(f'single{n}.txt', 'r') as f:\n lineas = [linea.split() for linea in f]\n for i in lineas:\n dimension.append(int(i[0]))\n time.append(float(i[1]))\n memory.append(int(i[2]))\n dim.append(dimension)\n tim.append(time)\n mem.append(memory)\nplt.subplot(2, 1, 1)\nplt.plot(dim[0], tim[0], '-o')\nplt.plot(dim[0], tim[1], '-o')\nplt.plot(dim[0], tim[2], '-o')\nplt.plot(dim[0], tim[3], '-o')\nplt.plot(dim[0], tim[4], '-o')\nplt.plot(dim[0], tim[5], '-o')\nplt.plot(dim[0], tim[6], '-o')\nplt.plot(dim[0], tim[7], '-o')\nplt.plot(dim[0], tim[8], '-o')\nplt.plot(dim[0], tim[9], '-o')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = ['', '', '', '', '', '', '', '', '', '', '']\nyticks = [0.1 / 1000, 1 / 1000, 10 / 1000, 0.1, 1, 10, 60, 600]\nytext = ['0.1 ms', '1 ms', '10 ms', '0.1 s', '1 s', '10 s', '1 min', '10 min']\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext)\nplt.title('Rendimiento caso1_single')\nplt.ylabel('Tiempo transcurrido (s)')\nplt.grid(True)\nplt.subplot(2, 1, 2)\nplt.plot(Ns, memoria, '-ob')\nplt.yscale('log')\nplt.xscale('log')\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\nyticks = [1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, \n 100000000000]\nytext = ['1 KB ', '10 KB', '100 KB', '1 MB', '10 MB', '100 MB', '1 GB', '10 GB'\n ]\nplt.axhline(y=4000000000, linestyle='--', color='black')\nplt.yticks(yticks, ytext)\nplt.xticks(xticks, xtext, rotation=45)\nplt.xlabel('Tamaño matriz N')\nplt.ylabel('Uso memoria (bytes)')\nplt.grid(True)\nplt.savefig('Rendimiento caso1_single.png')\n", "step-5": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 18 16:11:44 2021\r\n\r\n@author: ignacio\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.linalg import inv as invertir\r\nfrom time import perf_counter\r\nimport numpy as np\r\n\r\ndef matriz_laplaciana(N, t=np.single): # funcion obtenida de clase\r\n e=np.eye(N)-np.eye(N,N,1)\r\n return t(e+e.T)\r\n\r\n\r\nNs = [2, 5, 10,12, 15, 20, 30, 40, 45, 50, 55, 60, 75, 100, 125, 160, 200, 250, 350, 500, 600, 800, 1000, 2000, 5000, 10000]\r\n\r\ncorridas = 10\r\n\r\nfor corrida in range(corridas):\r\n \r\n tiempo = []\r\n memoria = []\r\n \r\n name = (f\"single{corrida}.txt\")\r\n\r\n fid = open(name,\"w\")\r\n \r\n for i in Ns:\r\n\r\n print(f\"i = {i}\") \r\n \r\n A = matriz_laplaciana(i)\r\n \r\n t1 = perf_counter()\r\n\r\n invertir(A)\r\n \r\n t2 = perf_counter()\r\n\r\n dt = t2 - t1\r\n \r\n size = 3 * (i**2) * 32\r\n\r\n tiempo.append(dt) \r\n memoria.append(size)\r\n \r\n fid.write(f\"{i} {dt} {size}\\n\")\r\n \r\n print(f\"Tiempo transcurrido = {dt} s\")\r\n print(f\"Mmoria usada = {size} bytes\")\r\n\r\n fid.flush()\r\n \r\n \r\nfid.close()\r\n\r\n\r\n\r\ndim = []\r\ntim = []\r\nmem = []\r\n\r\nfor n in range(10):\r\n dimension = []\r\n time = []\r\n memory = []\r\n with open(f\"single{n}.txt\", \"r\") as f:\r\n lineas = [linea.split() for linea in f]\r\n \r\n for i in lineas:\r\n dimension.append(int(i[0]))\r\n time.append(float(i[1]))\r\n memory.append(int(i[2]))\r\n \r\n dim.append(dimension)\r\n tim.append(time)\r\n mem.append(memory)\r\n\r\n#Grafico superior\r\n\r\nplt.subplot(2, 1, 1)\r\nplt.plot(dim[0],tim[0],\"-o\")\r\nplt.plot(dim[0],tim[1],\"-o\")\r\nplt.plot(dim[0],tim[2],\"-o\")\r\nplt.plot(dim[0],tim[3],\"-o\")\r\nplt.plot(dim[0],tim[4],\"-o\")\r\nplt.plot(dim[0],tim[5],\"-o\")\r\nplt.plot(dim[0],tim[6],\"-o\")\r\nplt.plot(dim[0],tim[7],\"-o\")\r\nplt.plot(dim[0],tim[8],\"-o\")\r\nplt.plot(dim[0],tim[9],\"-o\")\r\n \r\nplt.yscale('log')\r\nplt.xscale('log')\r\n\r\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\nxtext = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\r\n\r\nyticks = [0.1/1000, 1/1000, 10/1000, 0.1, 1, 10, 60, 600]\r\nytext = [\"0.1 ms\", \"1 ms\", \"10 ms\", \"0.1 s\", \"1 s\", \"10 s\", \"1 min\", \"10 min\"]\r\n\r\nplt.yticks(yticks, ytext)\r\nplt.xticks(xticks, xtext)\r\n\r\nplt.title(\"Rendimiento caso1_single\")\r\nplt.ylabel(\"Tiempo transcurrido (s)\")\r\nplt.grid(True)\r\n\r\n#Grafico inferior \r\n\r\nplt.subplot(2, 1, 2)\r\n\r\nplt.plot(Ns,memoria,'-ob')\r\n\r\nplt.yscale('log')\r\nplt.xscale('log')\r\n\r\nxticks = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\nxtext = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000]\r\n\r\nyticks = [1000,10000, 100000, 1000000, 10000000, 100000000, 1000000000, 100000000000]\r\nytext = [\"1 KB \", \"10 KB\", \"100 KB\", \"1 MB\", \"10 MB\", \"100 MB\", \"1 GB\", \"10 GB\"]\r\n\r\nplt.axhline(y=4000000000, linestyle=\"--\",color=\"black\") # RAM 4 GB\r\n\r\nplt.yticks(yticks, ytext)\r\nplt.xticks(xticks, xtext, rotation=45)\r\n\r\nplt.xlabel(\"Tamaño matriz N\")\r\nplt.ylabel(\"Uso memoria (bytes)\")\r\nplt.grid(True)\r\nplt.savefig(\"Rendimiento caso1_single.png\")", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
""" TestRail API Categories """ from . import _category from ._session import Session class TestRailAPI(Session): """Categories""" @property def attachments(self) -> _category.Attachments: """ https://www.gurock.com/testrail/docs/api/reference/attachments Use the following API methods to upload, retrieve and delete attachments. """ return _category.Attachments(self) @property def cases(self) -> _category.Cases: """ https://www.gurock.com/testrail/docs/api/reference/cases Use the following API methods to request details about test cases and to create or modify test cases. """ return _category.Cases(self) @property def case_fields(self) -> _category.CaseFields: """ https://www.gurock.com/testrail/docs/api/reference/case-fields Use the following API methods to request details about custom fields for test cases. """ return _category.CaseFields(self) @property def case_types(self) -> _category.CaseTypes: """ https://www.gurock.com/testrail/docs/api/reference/case-types Use the following API methods to request details about case type. """ return _category.CaseTypes(self) @property def configurations(self) -> _category.Configurations: """ https://www.gurock.com/testrail/docs/api/reference/configurations Use the following API methods to request details about configurations and to create or modify configurations. """ return _category.Configurations(self) @property def milestones(self) -> _category.Milestones: """ https://www.gurock.com/testrail/docs/api/reference/milestones Use the following API methods to request details about milestones and to create or modify milestones. """ return _category.Milestones(self) @property def plans(self) -> _category.Plans: """ https://www.gurock.com/testrail/docs/api/reference/plans Use the following API methods to request details about test plans and to create or modify test plans. """ return _category.Plans(self) @property def priorities(self) -> _category.Priorities: """ https://www.gurock.com/testrail/docs/api/reference/priorities Use the following API methods to request details about priorities. """ return _category.Priorities(self) @property def projects(self) -> _category.Projects: """ https://www.gurock.com/testrail/docs/api/reference/projects Use the following API methods to request details about projects and to create or modify projects """ return _category.Projects(self) @property def reports(self) -> _category.Reports: """ https://www.gurock.com/testrail/docs/api/reference/reports Use the following methods to get and run reports that have been made accessible to the API. """ return _category.Reports(self) @property def results(self) -> _category.Results: """ https://www.gurock.com/testrail/docs/api/reference/results Use the following API methods to request details about test results and to add new test results. """ return _category.Results(self) @property def result_fields(self) -> _category.ResultFields: """ https://www.gurock.com/testrail/docs/api/reference/result-fields Use the following API methods to request details about custom fields for test results. """ return _category.ResultFields(self) @property def runs(self) -> _category.Runs: """ https://www.gurock.com/testrail/docs/api/reference/runs Use the following API methods to request details about test runs and to create or modify test runs. """ return _category.Runs(self) @property def sections(self) -> _category.Sections: """ https://www.gurock.com/testrail/docs/api/reference/sections Use the following API methods to request details about sections and to create or modify sections. Sections are used to group and organize test cases in test suites. """ return _category.Sections(self) @property def shared_steps(self) -> _category.SharedSteps: """ https://www.gurock.com/testrail/docs/api/reference/api-shared-steps Use the following API methods to request details about shared steps. """ return _category.SharedSteps(self) @property def statuses(self) -> _category.Statuses: """ https://www.gurock.com/testrail/docs/api/reference/statuses Use the following API methods to request details about test statuses. """ return _category.Statuses(self) @property def suites(self) -> _category.Suites: """ https://www.gurock.com/testrail/docs/api/reference/suites Use the following API methods to request details about test suites and to create or modify test suites. """ return _category.Suites(self) @property def templates(self) -> _category.Template: """ https://www.gurock.com/testrail/docs/api/reference/templates Use the following API methods to request details about templates (field layouts for cases/results) """ return _category.Template(self) @property def tests(self) -> _category.Tests: """ https://www.gurock.com/testrail/docs/api/reference/tests Use the following API methods to request details about tests. """ return _category.Tests(self) @property def users(self) -> _category.Users: """ https://www.gurock.com/testrail/docs/api/reference/users Use the following API methods to request details about users. """ return _category.Users(self)
normal
{ "blob_id": "c2467e94a2ad474f0413e7ee3863aa134bf9c51f", "index": 3399, "step-1": "<mask token>\n\n\nclass TestRailAPI(Session):\n <mask token>\n\n @property\n def attachments(self) ->_category.Attachments:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/attachments\n Use the following API methods to upload, retrieve and delete attachments.\n \"\"\"\n return _category.Attachments(self)\n\n @property\n def cases(self) ->_category.Cases:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/cases\n Use the following API methods to request details about test cases and\n to create or modify test cases.\n \"\"\"\n return _category.Cases(self)\n\n @property\n def case_fields(self) ->_category.CaseFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-fields\n Use the following API methods to request details about custom fields\n for test cases.\n \"\"\"\n return _category.CaseFields(self)\n\n @property\n def case_types(self) ->_category.CaseTypes:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-types\n Use the following API methods to request details about case type.\n \"\"\"\n return _category.CaseTypes(self)\n <mask token>\n\n @property\n def milestones(self) ->_category.Milestones:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/milestones\n Use the following API methods to request details about milestones and\n to create or modify milestones.\n \"\"\"\n return _category.Milestones(self)\n\n @property\n def plans(self) ->_category.Plans:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/plans\n Use the following API methods to request details about test plans and\n to create or modify test plans.\n \"\"\"\n return _category.Plans(self)\n\n @property\n def priorities(self) ->_category.Priorities:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/priorities\n Use the following API methods to request details about priorities.\n \"\"\"\n return _category.Priorities(self)\n\n @property\n def projects(self) ->_category.Projects:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/projects\n Use the following API methods to request details about projects and\n to create or modify projects\n \"\"\"\n return _category.Projects(self)\n\n @property\n def reports(self) ->_category.Reports:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/reports\n Use the following methods to get and run reports that have been\n made accessible to the API.\n \"\"\"\n return _category.Reports(self)\n <mask token>\n <mask token>\n\n @property\n def runs(self) ->_category.Runs:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/runs\n Use the following API methods to request details about test runs and\n to create or modify test runs.\n \"\"\"\n return _category.Runs(self)\n\n @property\n def sections(self) ->_category.Sections:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/sections\n Use the following API methods to request details about sections and\n to create or modify sections.\n Sections are used to group and organize test cases in test suites.\n \"\"\"\n return _category.Sections(self)\n\n @property\n def shared_steps(self) ->_category.SharedSteps:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/api-shared-steps\n Use the following API methods to request details about shared steps.\n \"\"\"\n return _category.SharedSteps(self)\n\n @property\n def statuses(self) ->_category.Statuses:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/statuses\n Use the following API methods to request details about test statuses.\n \"\"\"\n return _category.Statuses(self)\n\n @property\n def suites(self) ->_category.Suites:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/suites\n Use the following API methods to request details about test suites and\n to create or modify test suites.\n \"\"\"\n return _category.Suites(self)\n\n @property\n def templates(self) ->_category.Template:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/templates\n Use the following API methods to request details about templates\n (field layouts for cases/results)\n \"\"\"\n return _category.Template(self)\n\n @property\n def tests(self) ->_category.Tests:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/tests\n Use the following API methods to request details about tests.\n \"\"\"\n return _category.Tests(self)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TestRailAPI(Session):\n <mask token>\n\n @property\n def attachments(self) ->_category.Attachments:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/attachments\n Use the following API methods to upload, retrieve and delete attachments.\n \"\"\"\n return _category.Attachments(self)\n\n @property\n def cases(self) ->_category.Cases:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/cases\n Use the following API methods to request details about test cases and\n to create or modify test cases.\n \"\"\"\n return _category.Cases(self)\n\n @property\n def case_fields(self) ->_category.CaseFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-fields\n Use the following API methods to request details about custom fields\n for test cases.\n \"\"\"\n return _category.CaseFields(self)\n\n @property\n def case_types(self) ->_category.CaseTypes:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-types\n Use the following API methods to request details about case type.\n \"\"\"\n return _category.CaseTypes(self)\n\n @property\n def configurations(self) ->_category.Configurations:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/configurations\n Use the following API methods to request details about configurations and\n to create or modify configurations.\n \"\"\"\n return _category.Configurations(self)\n\n @property\n def milestones(self) ->_category.Milestones:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/milestones\n Use the following API methods to request details about milestones and\n to create or modify milestones.\n \"\"\"\n return _category.Milestones(self)\n\n @property\n def plans(self) ->_category.Plans:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/plans\n Use the following API methods to request details about test plans and\n to create or modify test plans.\n \"\"\"\n return _category.Plans(self)\n\n @property\n def priorities(self) ->_category.Priorities:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/priorities\n Use the following API methods to request details about priorities.\n \"\"\"\n return _category.Priorities(self)\n\n @property\n def projects(self) ->_category.Projects:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/projects\n Use the following API methods to request details about projects and\n to create or modify projects\n \"\"\"\n return _category.Projects(self)\n\n @property\n def reports(self) ->_category.Reports:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/reports\n Use the following methods to get and run reports that have been\n made accessible to the API.\n \"\"\"\n return _category.Reports(self)\n\n @property\n def results(self) ->_category.Results:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/results\n Use the following API methods to request details about test results and\n to add new test results.\n \"\"\"\n return _category.Results(self)\n\n @property\n def result_fields(self) ->_category.ResultFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/result-fields\n Use the following API methods to request details about custom fields\n for test results.\n \"\"\"\n return _category.ResultFields(self)\n\n @property\n def runs(self) ->_category.Runs:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/runs\n Use the following API methods to request details about test runs and\n to create or modify test runs.\n \"\"\"\n return _category.Runs(self)\n\n @property\n def sections(self) ->_category.Sections:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/sections\n Use the following API methods to request details about sections and\n to create or modify sections.\n Sections are used to group and organize test cases in test suites.\n \"\"\"\n return _category.Sections(self)\n\n @property\n def shared_steps(self) ->_category.SharedSteps:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/api-shared-steps\n Use the following API methods to request details about shared steps.\n \"\"\"\n return _category.SharedSteps(self)\n\n @property\n def statuses(self) ->_category.Statuses:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/statuses\n Use the following API methods to request details about test statuses.\n \"\"\"\n return _category.Statuses(self)\n\n @property\n def suites(self) ->_category.Suites:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/suites\n Use the following API methods to request details about test suites and\n to create or modify test suites.\n \"\"\"\n return _category.Suites(self)\n\n @property\n def templates(self) ->_category.Template:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/templates\n Use the following API methods to request details about templates\n (field layouts for cases/results)\n \"\"\"\n return _category.Template(self)\n\n @property\n def tests(self) ->_category.Tests:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/tests\n Use the following API methods to request details about tests.\n \"\"\"\n return _category.Tests(self)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TestRailAPI(Session):\n <mask token>\n\n @property\n def attachments(self) ->_category.Attachments:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/attachments\n Use the following API methods to upload, retrieve and delete attachments.\n \"\"\"\n return _category.Attachments(self)\n\n @property\n def cases(self) ->_category.Cases:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/cases\n Use the following API methods to request details about test cases and\n to create or modify test cases.\n \"\"\"\n return _category.Cases(self)\n\n @property\n def case_fields(self) ->_category.CaseFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-fields\n Use the following API methods to request details about custom fields\n for test cases.\n \"\"\"\n return _category.CaseFields(self)\n\n @property\n def case_types(self) ->_category.CaseTypes:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-types\n Use the following API methods to request details about case type.\n \"\"\"\n return _category.CaseTypes(self)\n\n @property\n def configurations(self) ->_category.Configurations:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/configurations\n Use the following API methods to request details about configurations and\n to create or modify configurations.\n \"\"\"\n return _category.Configurations(self)\n\n @property\n def milestones(self) ->_category.Milestones:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/milestones\n Use the following API methods to request details about milestones and\n to create or modify milestones.\n \"\"\"\n return _category.Milestones(self)\n\n @property\n def plans(self) ->_category.Plans:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/plans\n Use the following API methods to request details about test plans and\n to create or modify test plans.\n \"\"\"\n return _category.Plans(self)\n\n @property\n def priorities(self) ->_category.Priorities:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/priorities\n Use the following API methods to request details about priorities.\n \"\"\"\n return _category.Priorities(self)\n\n @property\n def projects(self) ->_category.Projects:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/projects\n Use the following API methods to request details about projects and\n to create or modify projects\n \"\"\"\n return _category.Projects(self)\n\n @property\n def reports(self) ->_category.Reports:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/reports\n Use the following methods to get and run reports that have been\n made accessible to the API.\n \"\"\"\n return _category.Reports(self)\n\n @property\n def results(self) ->_category.Results:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/results\n Use the following API methods to request details about test results and\n to add new test results.\n \"\"\"\n return _category.Results(self)\n\n @property\n def result_fields(self) ->_category.ResultFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/result-fields\n Use the following API methods to request details about custom fields\n for test results.\n \"\"\"\n return _category.ResultFields(self)\n\n @property\n def runs(self) ->_category.Runs:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/runs\n Use the following API methods to request details about test runs and\n to create or modify test runs.\n \"\"\"\n return _category.Runs(self)\n\n @property\n def sections(self) ->_category.Sections:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/sections\n Use the following API methods to request details about sections and\n to create or modify sections.\n Sections are used to group and organize test cases in test suites.\n \"\"\"\n return _category.Sections(self)\n\n @property\n def shared_steps(self) ->_category.SharedSteps:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/api-shared-steps\n Use the following API methods to request details about shared steps.\n \"\"\"\n return _category.SharedSteps(self)\n\n @property\n def statuses(self) ->_category.Statuses:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/statuses\n Use the following API methods to request details about test statuses.\n \"\"\"\n return _category.Statuses(self)\n\n @property\n def suites(self) ->_category.Suites:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/suites\n Use the following API methods to request details about test suites and\n to create or modify test suites.\n \"\"\"\n return _category.Suites(self)\n\n @property\n def templates(self) ->_category.Template:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/templates\n Use the following API methods to request details about templates\n (field layouts for cases/results)\n \"\"\"\n return _category.Template(self)\n\n @property\n def tests(self) ->_category.Tests:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/tests\n Use the following API methods to request details about tests.\n \"\"\"\n return _category.Tests(self)\n\n @property\n def users(self) ->_category.Users:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/users\n Use the following API methods to request details about users.\n \"\"\"\n return _category.Users(self)\n", "step-4": "<mask token>\n\n\nclass TestRailAPI(Session):\n \"\"\"Categories\"\"\"\n\n @property\n def attachments(self) ->_category.Attachments:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/attachments\n Use the following API methods to upload, retrieve and delete attachments.\n \"\"\"\n return _category.Attachments(self)\n\n @property\n def cases(self) ->_category.Cases:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/cases\n Use the following API methods to request details about test cases and\n to create or modify test cases.\n \"\"\"\n return _category.Cases(self)\n\n @property\n def case_fields(self) ->_category.CaseFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-fields\n Use the following API methods to request details about custom fields\n for test cases.\n \"\"\"\n return _category.CaseFields(self)\n\n @property\n def case_types(self) ->_category.CaseTypes:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-types\n Use the following API methods to request details about case type.\n \"\"\"\n return _category.CaseTypes(self)\n\n @property\n def configurations(self) ->_category.Configurations:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/configurations\n Use the following API methods to request details about configurations and\n to create or modify configurations.\n \"\"\"\n return _category.Configurations(self)\n\n @property\n def milestones(self) ->_category.Milestones:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/milestones\n Use the following API methods to request details about milestones and\n to create or modify milestones.\n \"\"\"\n return _category.Milestones(self)\n\n @property\n def plans(self) ->_category.Plans:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/plans\n Use the following API methods to request details about test plans and\n to create or modify test plans.\n \"\"\"\n return _category.Plans(self)\n\n @property\n def priorities(self) ->_category.Priorities:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/priorities\n Use the following API methods to request details about priorities.\n \"\"\"\n return _category.Priorities(self)\n\n @property\n def projects(self) ->_category.Projects:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/projects\n Use the following API methods to request details about projects and\n to create or modify projects\n \"\"\"\n return _category.Projects(self)\n\n @property\n def reports(self) ->_category.Reports:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/reports\n Use the following methods to get and run reports that have been\n made accessible to the API.\n \"\"\"\n return _category.Reports(self)\n\n @property\n def results(self) ->_category.Results:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/results\n Use the following API methods to request details about test results and\n to add new test results.\n \"\"\"\n return _category.Results(self)\n\n @property\n def result_fields(self) ->_category.ResultFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/result-fields\n Use the following API methods to request details about custom fields\n for test results.\n \"\"\"\n return _category.ResultFields(self)\n\n @property\n def runs(self) ->_category.Runs:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/runs\n Use the following API methods to request details about test runs and\n to create or modify test runs.\n \"\"\"\n return _category.Runs(self)\n\n @property\n def sections(self) ->_category.Sections:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/sections\n Use the following API methods to request details about sections and\n to create or modify sections.\n Sections are used to group and organize test cases in test suites.\n \"\"\"\n return _category.Sections(self)\n\n @property\n def shared_steps(self) ->_category.SharedSteps:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/api-shared-steps\n Use the following API methods to request details about shared steps.\n \"\"\"\n return _category.SharedSteps(self)\n\n @property\n def statuses(self) ->_category.Statuses:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/statuses\n Use the following API methods to request details about test statuses.\n \"\"\"\n return _category.Statuses(self)\n\n @property\n def suites(self) ->_category.Suites:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/suites\n Use the following API methods to request details about test suites and\n to create or modify test suites.\n \"\"\"\n return _category.Suites(self)\n\n @property\n def templates(self) ->_category.Template:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/templates\n Use the following API methods to request details about templates\n (field layouts for cases/results)\n \"\"\"\n return _category.Template(self)\n\n @property\n def tests(self) ->_category.Tests:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/tests\n Use the following API methods to request details about tests.\n \"\"\"\n return _category.Tests(self)\n\n @property\n def users(self) ->_category.Users:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/users\n Use the following API methods to request details about users.\n \"\"\"\n return _category.Users(self)\n", "step-5": "\"\"\"\nTestRail API Categories\n\"\"\"\n\nfrom . import _category\nfrom ._session import Session\n\n\nclass TestRailAPI(Session):\n \"\"\"Categories\"\"\"\n\n @property\n def attachments(self) -> _category.Attachments:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/attachments\n Use the following API methods to upload, retrieve and delete attachments.\n \"\"\"\n return _category.Attachments(self)\n\n @property\n def cases(self) -> _category.Cases:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/cases\n Use the following API methods to request details about test cases and\n to create or modify test cases.\n \"\"\"\n return _category.Cases(self)\n\n @property\n def case_fields(self) -> _category.CaseFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-fields\n Use the following API methods to request details about custom fields\n for test cases.\n \"\"\"\n return _category.CaseFields(self)\n\n @property\n def case_types(self) -> _category.CaseTypes:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/case-types\n Use the following API methods to request details about case type.\n \"\"\"\n return _category.CaseTypes(self)\n\n @property\n def configurations(self) -> _category.Configurations:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/configurations\n Use the following API methods to request details about configurations and\n to create or modify configurations.\n \"\"\"\n return _category.Configurations(self)\n\n @property\n def milestones(self) -> _category.Milestones:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/milestones\n Use the following API methods to request details about milestones and\n to create or modify milestones.\n \"\"\"\n return _category.Milestones(self)\n\n @property\n def plans(self) -> _category.Plans:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/plans\n Use the following API methods to request details about test plans and\n to create or modify test plans.\n \"\"\"\n return _category.Plans(self)\n\n @property\n def priorities(self) -> _category.Priorities:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/priorities\n Use the following API methods to request details about priorities.\n \"\"\"\n return _category.Priorities(self)\n\n @property\n def projects(self) -> _category.Projects:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/projects\n Use the following API methods to request details about projects and\n to create or modify projects\n \"\"\"\n return _category.Projects(self)\n\n @property\n def reports(self) -> _category.Reports:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/reports\n Use the following methods to get and run reports that have been\n made accessible to the API.\n \"\"\"\n return _category.Reports(self)\n\n @property\n def results(self) -> _category.Results:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/results\n Use the following API methods to request details about test results and\n to add new test results.\n \"\"\"\n return _category.Results(self)\n\n @property\n def result_fields(self) -> _category.ResultFields:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/result-fields\n Use the following API methods to request details about custom fields\n for test results.\n \"\"\"\n return _category.ResultFields(self)\n\n @property\n def runs(self) -> _category.Runs:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/runs\n Use the following API methods to request details about test runs and\n to create or modify test runs.\n \"\"\"\n return _category.Runs(self)\n\n @property\n def sections(self) -> _category.Sections:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/sections\n Use the following API methods to request details about sections and\n to create or modify sections.\n Sections are used to group and organize test cases in test suites.\n \"\"\"\n return _category.Sections(self)\n\n @property\n def shared_steps(self) -> _category.SharedSteps:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/api-shared-steps\n Use the following API methods to request details about shared steps.\n \"\"\"\n return _category.SharedSteps(self)\n\n @property\n def statuses(self) -> _category.Statuses:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/statuses\n Use the following API methods to request details about test statuses.\n \"\"\"\n return _category.Statuses(self)\n\n @property\n def suites(self) -> _category.Suites:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/suites\n Use the following API methods to request details about test suites and\n to create or modify test suites.\n \"\"\"\n return _category.Suites(self)\n\n @property\n def templates(self) -> _category.Template:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/templates\n Use the following API methods to request details about templates\n (field layouts for cases/results)\n \"\"\"\n return _category.Template(self)\n\n @property\n def tests(self) -> _category.Tests:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/tests\n Use the following API methods to request details about tests.\n \"\"\"\n return _category.Tests(self)\n\n @property\n def users(self) -> _category.Users:\n \"\"\"\n https://www.gurock.com/testrail/docs/api/reference/users\n Use the following API methods to request details about users.\n \"\"\"\n return _category.Users(self)\n", "step-ids": [ 17, 20, 21, 22, 24 ] }
[ 17, 20, 21, 22, 24 ]
#!/usr/bin/python2 import gmpy2 p = 24659183668299994531 q = 28278904334302413829 e = 11 c = 589000442361955862116096782383253550042 t = (p-1)*(q-1) n = p*q # returns d such that e * d == 1 modulo t, or 0 if no such y exists. d = gmpy2.invert(e,t) # Decryption m = pow(c,d,n) print "Solved ! m = %d" % m
normal
{ "blob_id": "61c2a6499dd8de25045733f9061d660341501314", "index": 8334, "step-1": "#!/usr/bin/python2\nimport gmpy2\n\np = 24659183668299994531\nq = 28278904334302413829\ne = 11\nc = 589000442361955862116096782383253550042\nt = (p-1)*(q-1)\nn = p*q\n\n# returns d such that e * d == 1 modulo t, or 0 if no such y exists.\nd = gmpy2.invert(e,t)\n\n# Decryption\nm = pow(c,d,n)\nprint \"Solved ! m = %d\" % m\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import numpy as np np.set_printoptions(precision = 1) pi = np.pi def convertRadian(theta): radian = (theta) * (np.pi) / 180 return radian def mkMatrix(radian, alpha, dis): matrix = np.matrix([[np.cos(radian),(-1)*np.sin(radian)*np.cos(alpha), np.sin(radian)*np.sin(alpha), a1 * np.cos(radian)], [np.sin(radian), np.cos(radian)*np.cos(alpha), (-1)*np.cos(radian)*np.sin(alpha), a1 * np.sin(radian)], [0,np.sin(alpha), np.cos(alpha), dis], [0,0,0,1]]) return matrix #nao robot DH parameters #link1 a1 = 0 alpha1 = convertRadian(90) d1 = 0 # link2 a2 = 105/1000 # convert to meters alpha2 = convertRadian(90) d2 = 15/1000 # link3 a3 = 0 alpha3 = convertRadian(-90) d3 = 0 # link4 a4 = 55.95/1000 alpha4 = convertRadian(90) d4 = 0 # link5 a5 = 0 alpha5 = 0 d5 = 55.75/1000 # input theta angles and convert them directly to radians radian1 = convertRadian(input("Enter theta 1: ")) radian2 = convertRadian(input("Enter theta 2: ")) radian3 = convertRadian(input("Enter theta 3: ")) radian4 = convertRadian(input("Enter theta 4: ")) # compute them place them in their respective places # link1 homogeneous transformation 4x4 A1 = mkMatrix(radian1, alpha1, d1) # link2 homogeneous transformation 4x4 A2 = mkMatrix(radian2, alpha2, d2) # link3 homogeneous transformation 4x4 A3 = mkMatrix(radian3, alpha3, d3) # link4 homogeneous transformation 4x4 A4 = mkMatrix(radian4, alpha3, d4) # link5 homogeneous transformation 4x4 A5 = mkMatrix(0, alpha5, d5) print "A1: \n", A1 print "\nA2: \n", A2 print "\nA3: \n", A3 print "\nA4: \n", A4 print "\nA5: \n", A5 # save the matrix returned # print the matrix finalMatrix = A1*A2*A3*A4 print "\nFinal matrix\n", finalMatrix
normal
{ "blob_id": "47c6f9767b97469fe7e97ab3b69650265a8021d8", "index": 6257, "step-1": "import numpy as np\n\nnp.set_printoptions(precision = 1)\npi = np.pi\n\ndef convertRadian(theta):\n radian = (theta) * (np.pi) / 180\n return radian\n\ndef mkMatrix(radian, alpha, dis):\n matrix = np.matrix([[np.cos(radian),(-1)*np.sin(radian)*np.cos(alpha), np.sin(radian)*np.sin(alpha), a1 * np.cos(radian)],\n [np.sin(radian), np.cos(radian)*np.cos(alpha), (-1)*np.cos(radian)*np.sin(alpha), a1 * np.sin(radian)],\n [0,np.sin(alpha), np.cos(alpha), dis],\n [0,0,0,1]])\n return matrix\n\n#nao robot DH parameters\n#link1\na1 = 0\nalpha1 = convertRadian(90)\nd1 = 0\n\n# link2\na2 = 105/1000 # convert to meters\nalpha2 = convertRadian(90)\nd2 = 15/1000\n\n# link3\na3 = 0\nalpha3 = convertRadian(-90)\nd3 = 0\n\n# link4\na4 = 55.95/1000\nalpha4 = convertRadian(90)\nd4 = 0\n\n# link5\na5 = 0\nalpha5 = 0\nd5 = 55.75/1000\n\n\n\n# input theta angles and convert them directly to radians\nradian1 = convertRadian(input(\"Enter theta 1: \"))\nradian2 = convertRadian(input(\"Enter theta 2: \"))\nradian3 = convertRadian(input(\"Enter theta 3: \"))\nradian4 = convertRadian(input(\"Enter theta 4: \"))\n\n# compute them place them in their respective places\n\n\n# link1 homogeneous transformation 4x4\nA1 = mkMatrix(radian1, alpha1, d1)\n\n# link2 homogeneous transformation 4x4\nA2 = mkMatrix(radian2, alpha2, d2)\n\n# link3 homogeneous transformation 4x4\nA3 = mkMatrix(radian3, alpha3, d3)\n\n# link4 homogeneous transformation 4x4\nA4 = mkMatrix(radian4, alpha3, d4)\n\n# link5 homogeneous transformation 4x4\nA5 = mkMatrix(0, alpha5, d5)\n\nprint \"A1: \\n\", A1\nprint \"\\nA2: \\n\", A2\nprint \"\\nA3: \\n\", A3\nprint \"\\nA4: \\n\", A4\nprint \"\\nA5: \\n\", A5\n\n# save the matrix returned\n# print the matrix\nfinalMatrix = A1*A2*A3*A4\n\nprint \"\\nFinal matrix\\n\", finalMatrix\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
#Program to convert temp in degree Celsius to temp in degree Fahrenheit celsius=input("Enter temperature in Celsius") celsius=int(celsius) fah=(celsius*9/5)+32 print("Temp in ",celsius,"celsius=",fah," Fahrenheit")
normal
{ "blob_id": "e1172cadeb8b2ce036d8431cef78cfe19bda0cb8", "index": 2161, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Temp in ', celsius, 'celsius=', fah, ' Fahrenheit')\n", "step-3": "celsius = input('Enter temperature in Celsius')\ncelsius = int(celsius)\nfah = celsius * 9 / 5 + 32\nprint('Temp in ', celsius, 'celsius=', fah, ' Fahrenheit')\n", "step-4": "#Program to convert temp in degree Celsius to temp in degree Fahrenheit\ncelsius=input(\"Enter temperature in Celsius\")\ncelsius=int(celsius)\nfah=(celsius*9/5)+32\nprint(\"Temp in \",celsius,\"celsius=\",fah,\" Fahrenheit\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import pylab,numpy as np from numpy import sin from matplotlib.patches import FancyArrowPatch fig=pylab.figure() w=1 h=1 th=3.14159/25. x=np.r_[0,0,w,w,0] y=np.r_[0,h,h-w*sin(th),0-w*sin(th),0] pylab.plot(x,y) x=np.r_[0,0,w/2.0,w/2.0,0] y=np.r_[0,h/6.0,h/6.0-w/2.0*sin(th),0-w/2.0*sin(th),0] pylab.plot(x,y,'--') pylab.text(w/4.0,h/12.0-w/4.0*sin(th)-h/30.,'$A_{a,subcool}$',ha='center',va='center') h0=h-w/2.0*sin(th)-h/6.0 x=np.r_[w/2.0,w/2.0,w,w,w/2.0] y=np.r_[0+h0,h/6.0+h0,h/6.0-w/2.0*sin(th)+h0,0-w/2.0*sin(th)+h0,0+h0] pylab.plot(x,y,'--') pylab.text(0.75*w,h-h/12.0-0.75*w*sin(th)-h/30.,'$A_{a,superheat}$',ha='center',va='center') pylab.text(0.5*w,h/2.0-0.5*w*sin(th),'$A_{a,two-phase}$',ha='center',va='center') ##Add the circuits for y0 in [h/12.,h/12.+h/6.,h/12.+2*h/6.,h/12.+3*h/6.,h/12.+4*h/6.,h/12.+5*h/6.]: pylab.plot(np.r_[0,w],np.r_[y0,y0-w*sin(th)],'k',lw=4) pylab.gca().add_patch(FancyArrowPatch((w+w/10.,h-h/12.0-(w+w/10.)*sin(th)),(w,h-h/12.0-w*sin(th)),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8)) pylab.gca().add_patch(FancyArrowPatch((0,h/12.0),(-w/10.,h/12.0-(-w/10.)*sin(th)),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8)) pylab.gca().axis('equal') pylab.gca().axis('off') pylab.show()
normal
{ "blob_id": "c485466a736fa0a4f183092e561a27005c01316d", "index": 8616, "step-1": "<mask token>\n", "step-2": "<mask token>\npylab.plot(x, y)\n<mask token>\npylab.plot(x, y, '--')\npylab.text(w / 4.0, h / 12.0 - w / 4.0 * sin(th) - h / 30.0,\n '$A_{a,subcool}$', ha='center', va='center')\n<mask token>\npylab.plot(x, y, '--')\npylab.text(0.75 * w, h - h / 12.0 - 0.75 * w * sin(th) - h / 30.0,\n '$A_{a,superheat}$', ha='center', va='center')\npylab.text(0.5 * w, h / 2.0 - 0.5 * w * sin(th), '$A_{a,two-phase}$', ha=\n 'center', va='center')\nfor y0 in [h / 12.0, h / 12.0 + h / 6.0, h / 12.0 + 2 * h / 6.0, h / 12.0 +\n 3 * h / 6.0, h / 12.0 + 4 * h / 6.0, h / 12.0 + 5 * h / 6.0]:\n pylab.plot(np.r_[0, w], np.r_[y0, y0 - w * sin(th)], 'k', lw=4)\npylab.gca().add_patch(FancyArrowPatch((w + w / 10.0, h - h / 12.0 - (w + w /\n 10.0) * sin(th)), (w, h - h / 12.0 - w * sin(th)), arrowstyle='-|>', fc\n ='k', ec='k', mutation_scale=20, lw=0.8))\npylab.gca().add_patch(FancyArrowPatch((0, h / 12.0), (-w / 10.0, h / 12.0 -\n -w / 10.0 * sin(th)), arrowstyle='-|>', fc='k', ec='k', mutation_scale=\n 20, lw=0.8))\npylab.gca().axis('equal')\npylab.gca().axis('off')\npylab.show()\n", "step-3": "<mask token>\nfig = pylab.figure()\nw = 1\nh = 1\nth = 3.14159 / 25.0\nx = np.r_[0, 0, w, w, 0]\ny = np.r_[0, h, h - w * sin(th), 0 - w * sin(th), 0]\npylab.plot(x, y)\nx = np.r_[0, 0, w / 2.0, w / 2.0, 0]\ny = np.r_[0, h / 6.0, h / 6.0 - w / 2.0 * sin(th), 0 - w / 2.0 * sin(th), 0]\npylab.plot(x, y, '--')\npylab.text(w / 4.0, h / 12.0 - w / 4.0 * sin(th) - h / 30.0,\n '$A_{a,subcool}$', ha='center', va='center')\nh0 = h - w / 2.0 * sin(th) - h / 6.0\nx = np.r_[w / 2.0, w / 2.0, w, w, w / 2.0]\ny = np.r_[0 + h0, h / 6.0 + h0, h / 6.0 - w / 2.0 * sin(th) + h0, 0 - w / \n 2.0 * sin(th) + h0, 0 + h0]\npylab.plot(x, y, '--')\npylab.text(0.75 * w, h - h / 12.0 - 0.75 * w * sin(th) - h / 30.0,\n '$A_{a,superheat}$', ha='center', va='center')\npylab.text(0.5 * w, h / 2.0 - 0.5 * w * sin(th), '$A_{a,two-phase}$', ha=\n 'center', va='center')\nfor y0 in [h / 12.0, h / 12.0 + h / 6.0, h / 12.0 + 2 * h / 6.0, h / 12.0 +\n 3 * h / 6.0, h / 12.0 + 4 * h / 6.0, h / 12.0 + 5 * h / 6.0]:\n pylab.plot(np.r_[0, w], np.r_[y0, y0 - w * sin(th)], 'k', lw=4)\npylab.gca().add_patch(FancyArrowPatch((w + w / 10.0, h - h / 12.0 - (w + w /\n 10.0) * sin(th)), (w, h - h / 12.0 - w * sin(th)), arrowstyle='-|>', fc\n ='k', ec='k', mutation_scale=20, lw=0.8))\npylab.gca().add_patch(FancyArrowPatch((0, h / 12.0), (-w / 10.0, h / 12.0 -\n -w / 10.0 * sin(th)), arrowstyle='-|>', fc='k', ec='k', mutation_scale=\n 20, lw=0.8))\npylab.gca().axis('equal')\npylab.gca().axis('off')\npylab.show()\n", "step-4": "import pylab, numpy as np\nfrom numpy import sin\nfrom matplotlib.patches import FancyArrowPatch\nfig = pylab.figure()\nw = 1\nh = 1\nth = 3.14159 / 25.0\nx = np.r_[0, 0, w, w, 0]\ny = np.r_[0, h, h - w * sin(th), 0 - w * sin(th), 0]\npylab.plot(x, y)\nx = np.r_[0, 0, w / 2.0, w / 2.0, 0]\ny = np.r_[0, h / 6.0, h / 6.0 - w / 2.0 * sin(th), 0 - w / 2.0 * sin(th), 0]\npylab.plot(x, y, '--')\npylab.text(w / 4.0, h / 12.0 - w / 4.0 * sin(th) - h / 30.0,\n '$A_{a,subcool}$', ha='center', va='center')\nh0 = h - w / 2.0 * sin(th) - h / 6.0\nx = np.r_[w / 2.0, w / 2.0, w, w, w / 2.0]\ny = np.r_[0 + h0, h / 6.0 + h0, h / 6.0 - w / 2.0 * sin(th) + h0, 0 - w / \n 2.0 * sin(th) + h0, 0 + h0]\npylab.plot(x, y, '--')\npylab.text(0.75 * w, h - h / 12.0 - 0.75 * w * sin(th) - h / 30.0,\n '$A_{a,superheat}$', ha='center', va='center')\npylab.text(0.5 * w, h / 2.0 - 0.5 * w * sin(th), '$A_{a,two-phase}$', ha=\n 'center', va='center')\nfor y0 in [h / 12.0, h / 12.0 + h / 6.0, h / 12.0 + 2 * h / 6.0, h / 12.0 +\n 3 * h / 6.0, h / 12.0 + 4 * h / 6.0, h / 12.0 + 5 * h / 6.0]:\n pylab.plot(np.r_[0, w], np.r_[y0, y0 - w * sin(th)], 'k', lw=4)\npylab.gca().add_patch(FancyArrowPatch((w + w / 10.0, h - h / 12.0 - (w + w /\n 10.0) * sin(th)), (w, h - h / 12.0 - w * sin(th)), arrowstyle='-|>', fc\n ='k', ec='k', mutation_scale=20, lw=0.8))\npylab.gca().add_patch(FancyArrowPatch((0, h / 12.0), (-w / 10.0, h / 12.0 -\n -w / 10.0 * sin(th)), arrowstyle='-|>', fc='k', ec='k', mutation_scale=\n 20, lw=0.8))\npylab.gca().axis('equal')\npylab.gca().axis('off')\npylab.show()\n", "step-5": "import pylab,numpy as np\r\nfrom numpy import sin\r\nfrom matplotlib.patches import FancyArrowPatch\r\n\r\nfig=pylab.figure()\r\nw=1\r\nh=1\r\nth=3.14159/25.\r\nx=np.r_[0,0,w,w,0]\r\ny=np.r_[0,h,h-w*sin(th),0-w*sin(th),0]\r\npylab.plot(x,y)\r\n\r\nx=np.r_[0,0,w/2.0,w/2.0,0]\r\ny=np.r_[0,h/6.0,h/6.0-w/2.0*sin(th),0-w/2.0*sin(th),0]\r\npylab.plot(x,y,'--')\r\npylab.text(w/4.0,h/12.0-w/4.0*sin(th)-h/30.,'$A_{a,subcool}$',ha='center',va='center')\r\n\r\nh0=h-w/2.0*sin(th)-h/6.0\r\nx=np.r_[w/2.0,w/2.0,w,w,w/2.0]\r\ny=np.r_[0+h0,h/6.0+h0,h/6.0-w/2.0*sin(th)+h0,0-w/2.0*sin(th)+h0,0+h0]\r\npylab.plot(x,y,'--')\r\npylab.text(0.75*w,h-h/12.0-0.75*w*sin(th)-h/30.,'$A_{a,superheat}$',ha='center',va='center')\r\n\r\npylab.text(0.5*w,h/2.0-0.5*w*sin(th),'$A_{a,two-phase}$',ha='center',va='center')\r\n\r\n##Add the circuits\r\nfor y0 in [h/12.,h/12.+h/6.,h/12.+2*h/6.,h/12.+3*h/6.,h/12.+4*h/6.,h/12.+5*h/6.]:\r\n pylab.plot(np.r_[0,w],np.r_[y0,y0-w*sin(th)],'k',lw=4)\r\n \r\npylab.gca().add_patch(FancyArrowPatch((w+w/10.,h-h/12.0-(w+w/10.)*sin(th)),(w,h-h/12.0-w*sin(th)),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8))\r\npylab.gca().add_patch(FancyArrowPatch((0,h/12.0),(-w/10.,h/12.0-(-w/10.)*sin(th)),arrowstyle='-|>',fc='k',ec='k',mutation_scale=20,lw=0.8))\r\n \r\npylab.gca().axis('equal')\r\npylab.gca().axis('off')\r\npylab.show()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
arr = [] for i in range(5): arr.append(int(input())) print(min(arr[0], arr[1], arr[2]) + min(arr[3], arr[4]) - 50)
normal
{ "blob_id": "8745855d86dcdabe55f8d1622b66b3613dbfe3e1", "index": 4015, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(5):\n arr.append(int(input()))\nprint(min(arr[0], arr[1], arr[2]) + min(arr[3], arr[4]) - 50)\n", "step-3": "arr = []\nfor i in range(5):\n arr.append(int(input()))\nprint(min(arr[0], arr[1], arr[2]) + min(arr[3], arr[4]) - 50)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from flask import Blueprint, request from ecdsa import SigningKey, NIST384p import base64, codecs from cryptography.fernet import Fernet ecdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app') f = Fernet(Fernet.generate_key()) sk = SigningKey.generate(curve=NIST384p) vk = sk.get_verifying_key() @ecdsa_app.get('/create_pkey') def private_key(): #reverse = bytes.fromhex(sk.to_string().hex()) return {"status":"success", "result":sk.to_string().hex()} @ecdsa_app.post('/op') def check_op(): input = request.get_json() operators = ['+', '-', '*', '/', '**', '//', '%'] finaloutput = {} if input['data']['op'] in operators: finaloutput['status'] = 'success' finaloutput['message'] = 'successfully verified' finaloutput['result'] = str(input['data']) else: finaloutput['status'] = 'failure' finaloutput['message'] = 'invalid operator' return finaloutput @ecdsa_app.post('/verify_signature') def signature_verify(): input = request.get_json() token = f.encrypt(str(input['data']).encode()) #reverse_signature = bytes.fromhex(input["signature"]) signature_ = sk.sign(token) finaloutput = {} try: if (vk.verify(signature_, token)): finaloutput['status'] = 'success' finaloutput['message'] = 'successfully verified' except: finaloutput['status'] = 'failure' finaloutput['message'] = 'signature is invalid' return finaloutput @ecdsa_app.post('/verify') def verify_fun(): data = request.get_json() output = check_operator_verify(data) finaloutput ={} if output: finaloutput['status'] = 'success' finaloutput['message'] = 'successfully verified' else: finaloutput['status'] = 'failure' finaloutput['message'] = 'invalid operator or signature is invalid' return finaloutput def check_operator_verify(input): try: operators = ['+', '-', '*', '/', '**', '//', '%'] if input['data']['op'] in operators: token = f.encrypt(str(input['data']).encode()) reverse_signature = bytes.fromhex(input["signature"]) return (vk.verify(reverse_signature, token)) except: pass
normal
{ "blob_id": "4eb7abb24451f3f895d0731de7b29a85d90c1539", "index": 8246, "step-1": "<mask token>\n\n\n@ecdsa_app.get('/create_pkey')\ndef private_key():\n return {'status': 'success', 'result': sk.to_string().hex()}\n\n\n@ecdsa_app.post('/op')\ndef check_op():\n input = request.get_json()\n operators = ['+', '-', '*', '/', '**', '//', '%']\n finaloutput = {}\n if input['data']['op'] in operators:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n finaloutput['result'] = str(input['data'])\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator'\n return finaloutput\n\n\n<mask token>\n\n\n@ecdsa_app.post('/verify')\ndef verify_fun():\n data = request.get_json()\n output = check_operator_verify(data)\n finaloutput = {}\n if output:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator or signature is invalid'\n return finaloutput\n\n\ndef check_operator_verify(input):\n try:\n operators = ['+', '-', '*', '/', '**', '//', '%']\n if input['data']['op'] in operators:\n token = f.encrypt(str(input['data']).encode())\n reverse_signature = bytes.fromhex(input['signature'])\n return vk.verify(reverse_signature, token)\n except:\n pass\n", "step-2": "<mask token>\n\n\n@ecdsa_app.get('/create_pkey')\ndef private_key():\n return {'status': 'success', 'result': sk.to_string().hex()}\n\n\n@ecdsa_app.post('/op')\ndef check_op():\n input = request.get_json()\n operators = ['+', '-', '*', '/', '**', '//', '%']\n finaloutput = {}\n if input['data']['op'] in operators:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n finaloutput['result'] = str(input['data'])\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator'\n return finaloutput\n\n\n@ecdsa_app.post('/verify_signature')\ndef signature_verify():\n input = request.get_json()\n token = f.encrypt(str(input['data']).encode())\n signature_ = sk.sign(token)\n finaloutput = {}\n try:\n if vk.verify(signature_, token):\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n except:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'signature is invalid'\n return finaloutput\n\n\n@ecdsa_app.post('/verify')\ndef verify_fun():\n data = request.get_json()\n output = check_operator_verify(data)\n finaloutput = {}\n if output:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator or signature is invalid'\n return finaloutput\n\n\ndef check_operator_verify(input):\n try:\n operators = ['+', '-', '*', '/', '**', '//', '%']\n if input['data']['op'] in operators:\n token = f.encrypt(str(input['data']).encode())\n reverse_signature = bytes.fromhex(input['signature'])\n return vk.verify(reverse_signature, token)\n except:\n pass\n", "step-3": "<mask token>\necdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app')\nf = Fernet(Fernet.generate_key())\nsk = SigningKey.generate(curve=NIST384p)\nvk = sk.get_verifying_key()\n\n\n@ecdsa_app.get('/create_pkey')\ndef private_key():\n return {'status': 'success', 'result': sk.to_string().hex()}\n\n\n@ecdsa_app.post('/op')\ndef check_op():\n input = request.get_json()\n operators = ['+', '-', '*', '/', '**', '//', '%']\n finaloutput = {}\n if input['data']['op'] in operators:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n finaloutput['result'] = str(input['data'])\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator'\n return finaloutput\n\n\n@ecdsa_app.post('/verify_signature')\ndef signature_verify():\n input = request.get_json()\n token = f.encrypt(str(input['data']).encode())\n signature_ = sk.sign(token)\n finaloutput = {}\n try:\n if vk.verify(signature_, token):\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n except:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'signature is invalid'\n return finaloutput\n\n\n@ecdsa_app.post('/verify')\ndef verify_fun():\n data = request.get_json()\n output = check_operator_verify(data)\n finaloutput = {}\n if output:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator or signature is invalid'\n return finaloutput\n\n\ndef check_operator_verify(input):\n try:\n operators = ['+', '-', '*', '/', '**', '//', '%']\n if input['data']['op'] in operators:\n token = f.encrypt(str(input['data']).encode())\n reverse_signature = bytes.fromhex(input['signature'])\n return vk.verify(reverse_signature, token)\n except:\n pass\n", "step-4": "from flask import Blueprint, request\nfrom ecdsa import SigningKey, NIST384p\nimport base64, codecs\nfrom cryptography.fernet import Fernet\necdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app')\nf = Fernet(Fernet.generate_key())\nsk = SigningKey.generate(curve=NIST384p)\nvk = sk.get_verifying_key()\n\n\n@ecdsa_app.get('/create_pkey')\ndef private_key():\n return {'status': 'success', 'result': sk.to_string().hex()}\n\n\n@ecdsa_app.post('/op')\ndef check_op():\n input = request.get_json()\n operators = ['+', '-', '*', '/', '**', '//', '%']\n finaloutput = {}\n if input['data']['op'] in operators:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n finaloutput['result'] = str(input['data'])\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator'\n return finaloutput\n\n\n@ecdsa_app.post('/verify_signature')\ndef signature_verify():\n input = request.get_json()\n token = f.encrypt(str(input['data']).encode())\n signature_ = sk.sign(token)\n finaloutput = {}\n try:\n if vk.verify(signature_, token):\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n except:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'signature is invalid'\n return finaloutput\n\n\n@ecdsa_app.post('/verify')\ndef verify_fun():\n data = request.get_json()\n output = check_operator_verify(data)\n finaloutput = {}\n if output:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator or signature is invalid'\n return finaloutput\n\n\ndef check_operator_verify(input):\n try:\n operators = ['+', '-', '*', '/', '**', '//', '%']\n if input['data']['op'] in operators:\n token = f.encrypt(str(input['data']).encode())\n reverse_signature = bytes.fromhex(input['signature'])\n return vk.verify(reverse_signature, token)\n except:\n pass\n", "step-5": "from flask import Blueprint, request\nfrom ecdsa import SigningKey, NIST384p\nimport base64, codecs\nfrom cryptography.fernet import Fernet\n\necdsa_app = Blueprint('ecdsa_app', __name__, url_prefix='/ecdsa_app')\nf = Fernet(Fernet.generate_key())\n\nsk = SigningKey.generate(curve=NIST384p)\nvk = sk.get_verifying_key()\n\n\n\n\n@ecdsa_app.get('/create_pkey')\ndef private_key():\n #reverse = bytes.fromhex(sk.to_string().hex()) \n return {\"status\":\"success\", \"result\":sk.to_string().hex()}\n\n@ecdsa_app.post('/op')\ndef check_op():\n input = request.get_json()\n operators = ['+', '-', '*', '/', '**', '//', '%']\n finaloutput = {}\n if input['data']['op'] in operators:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n finaloutput['result'] = str(input['data'])\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator'\n return finaloutput\n\n@ecdsa_app.post('/verify_signature')\ndef signature_verify():\n\n input = request.get_json()\n token = f.encrypt(str(input['data']).encode())\n #reverse_signature = bytes.fromhex(input[\"signature\"])\n signature_ = sk.sign(token)\n finaloutput = {}\n try:\n if (vk.verify(signature_, token)):\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n except:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'signature is invalid'\n\n return finaloutput\n\n\n@ecdsa_app.post('/verify')\ndef verify_fun():\n data = request.get_json()\n output = check_operator_verify(data)\n finaloutput ={}\n if output:\n finaloutput['status'] = 'success'\n finaloutput['message'] = 'successfully verified'\n else:\n finaloutput['status'] = 'failure'\n finaloutput['message'] = 'invalid operator or signature is invalid'\n return finaloutput\n\ndef check_operator_verify(input):\n try:\n operators = ['+', '-', '*', '/', '**', '//', '%']\n if input['data']['op'] in operators:\n token = f.encrypt(str(input['data']).encode())\n reverse_signature = bytes.fromhex(input[\"signature\"])\n return (vk.verify(reverse_signature, token))\n except:\n pass\n\n ", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
from django.db import models class Book(models.Model): title = models.TextField(max_length=32, blank=False, null=False) # from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager # # # class UserAccountManager(BaseUserManager): # def create_user(self, email, firstname,lastname, phonenumber, password=None,): # # if not email: # raise ValueError('Users must have an email address') # email = self.normalize_email(email) # user = self.model(email=email, name=firstname) # user.set_password(password) # user.save() # # class UserAccount(AbstractBaseUser, PermissionsMixin): # email = models.EmailField(max_length=255, unique=True) # firstname = models.CharField(max_length=255) # lastname = models.CharField(max_length=255) # is_active = models.BooleanField(default=True) # is_staff = models.BooleanField(default=True) # # objects = UserAccountManager() # # USERNAME_FILED = 'email' # REQUIRED_FIELDS = ['firstname','lastname','phonenumber'] # # def get_full_name(self): # return self.firstname + " " + self.lastname # # def get_short_name(self): # return self.firstname # # def __str__(self): # return self.email
normal
{ "blob_id": "8286407987301ace7af97d6acdcf6299ce3d8525", "index": 5440, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Book(models.Model):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Book(models.Model):\n title = models.TextField(max_length=32, blank=False, null=False)\n", "step-4": "from django.db import models\n\n\nclass Book(models.Model):\n title = models.TextField(max_length=32, blank=False, null=False)\n", "step-5": "from django.db import models\n\n\nclass Book(models.Model):\n title = models.TextField(max_length=32, blank=False, null=False)\n\n# from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager\n#\n#\n# class UserAccountManager(BaseUserManager):\n# def create_user(self, email, firstname,lastname, phonenumber, password=None,):\n#\n# if not email:\n# raise ValueError('Users must have an email address')\n# email = self.normalize_email(email)\n# user = self.model(email=email, name=firstname)\n# user.set_password(password)\n# user.save()\n#\n# class UserAccount(AbstractBaseUser, PermissionsMixin):\n# email = models.EmailField(max_length=255, unique=True)\n# firstname = models.CharField(max_length=255)\n# lastname = models.CharField(max_length=255)\n# is_active = models.BooleanField(default=True)\n# is_staff = models.BooleanField(default=True)\n#\n# objects = UserAccountManager()\n#\n# USERNAME_FILED = 'email'\n# REQUIRED_FIELDS = ['firstname','lastname','phonenumber']\n#\n# def get_full_name(self):\n# return self.firstname + \" \" + self.lastname\n#\n# def get_short_name(self):\n# return self.firstname\n#\n# def __str__(self):\n# return self.email\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- """ Created on Wed Jul 15 19:27:59 2020 @author: Dan """ import numpy as np def shift(v,i,j): if i <= j: return v store = v[i] for k in range(0, i-j-1): v[i-k] = v[i-k-1] v[j] = store return v def insertion(v): for i in range(1, len(v)): j = i while v[i] < v[j-1] and j > 0: j = j-1 shift(v,i,j) return v # v = np.random.randint(1,50,20) v = [5,5,1,4,5,8] print(v) sorted = insertion(v) print(sorted)
normal
{ "blob_id": "35288c9ad4d3550003e3c2f9e9034f4bce1df830", "index": 3626, "step-1": "<mask token>\n\n\ndef shift(v, i, j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i - j - 1):\n v[i - k] = v[i - k - 1]\n v[j] = store\n return v\n\n\ndef insertion(v):\n for i in range(1, len(v)):\n j = i\n while v[i] < v[j - 1] and j > 0:\n j = j - 1\n shift(v, i, j)\n return v\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef shift(v, i, j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i - j - 1):\n v[i - k] = v[i - k - 1]\n v[j] = store\n return v\n\n\ndef insertion(v):\n for i in range(1, len(v)):\n j = i\n while v[i] < v[j - 1] and j > 0:\n j = j - 1\n shift(v, i, j)\n return v\n\n\n<mask token>\nprint(v)\n<mask token>\nprint(sorted)\n", "step-3": "<mask token>\n\n\ndef shift(v, i, j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i - j - 1):\n v[i - k] = v[i - k - 1]\n v[j] = store\n return v\n\n\ndef insertion(v):\n for i in range(1, len(v)):\n j = i\n while v[i] < v[j - 1] and j > 0:\n j = j - 1\n shift(v, i, j)\n return v\n\n\nv = [5, 5, 1, 4, 5, 8]\nprint(v)\nsorted = insertion(v)\nprint(sorted)\n", "step-4": "<mask token>\nimport numpy as np\n\n\ndef shift(v, i, j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i - j - 1):\n v[i - k] = v[i - k - 1]\n v[j] = store\n return v\n\n\ndef insertion(v):\n for i in range(1, len(v)):\n j = i\n while v[i] < v[j - 1] and j > 0:\n j = j - 1\n shift(v, i, j)\n return v\n\n\nv = [5, 5, 1, 4, 5, 8]\nprint(v)\nsorted = insertion(v)\nprint(sorted)\n", "step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 15 19:27:59 2020\n\n@author: Dan\n\"\"\"\n\nimport numpy as np\n\ndef shift(v,i,j):\n if i <= j:\n return v\n store = v[i]\n for k in range(0, i-j-1):\n v[i-k] = v[i-k-1]\n v[j] = store\n return v\n\ndef insertion(v):\n for i in range(1, len(v)):\n j = i\n while v[i] < v[j-1] and j > 0:\n j = j-1\n shift(v,i,j)\n return v\n\n# v = np.random.randint(1,50,20)\nv = [5,5,1,4,5,8]\nprint(v)\nsorted = insertion(v)\nprint(sorted)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
import logging import random from pyage.core.address import Addressable from pyage.core.agent.agent import AbstractAgent from pyage.core.inject import Inject, InjectOptional logger = logging.getLogger(__name__) class AggregateAgent(Addressable, AbstractAgent): @Inject("aggregated_agents:_AggregateAgent__agents") @InjectOptional("locator") def __init__(self, name=None): self.name = name super(AggregateAgent, self).__init__() for agent in self.__agents.values(): agent.parent = self self.steps = 0 def step(self): for agent in self.__agents.values(): agent.step() self.steps += 1 def remove_agent(self, agent): del self.__agents[agent.get_address()] self.locator.remove_agent(agent) agent.parent = None return agent def add_agent(self, agent): agent.parent = self self.__agents[agent.get_address()] = agent def get_agents(self): return self.__agents.values() def get_fitness(self): try: return max(agent.get_fitness() for agent in self.__agents.values()) except ValueError: return None def get_best_genotype(self): return max(self.__agents.values(), key=lambda a: a.get_fitness()).get_best_genotype() def move(self, agent): allowed_moves = self.locator.get_allowed_moves(agent) if allowed_moves: self.locator.remove_agent(agent) destination = get_random_move(allowed_moves) self.locator.add_agent(agent, destination) logger.debug("%s moved to %s" % (agent, destination)) def get_neighbour(self, agent): return self.locator.get_neighbour(agent) def aggregate_agents_factory(*args): def factory(): agents = {} for name in args: agent = AggregateAgent(name) agents[agent.get_address()] = agent return agents return factory def get_random_move(allowed_moves): destination = random.sample(allowed_moves, 1)[0] return destination
normal
{ "blob_id": "85903f0c6bd4c896379c1357a08ae3bfa19d5415", "index": 7065, "step-1": "<mask token>\n\n\nclass AggregateAgent(Addressable, AbstractAgent):\n\n @Inject('aggregated_agents:_AggregateAgent__agents')\n @InjectOptional('locator')\n def __init__(self, name=None):\n self.name = name\n super(AggregateAgent, self).__init__()\n for agent in self.__agents.values():\n agent.parent = self\n self.steps = 0\n\n def step(self):\n for agent in self.__agents.values():\n agent.step()\n self.steps += 1\n\n def remove_agent(self, agent):\n del self.__agents[agent.get_address()]\n self.locator.remove_agent(agent)\n agent.parent = None\n return agent\n\n def add_agent(self, agent):\n agent.parent = self\n self.__agents[agent.get_address()] = agent\n <mask token>\n\n def get_fitness(self):\n try:\n return max(agent.get_fitness() for agent in self.__agents.values())\n except ValueError:\n return None\n <mask token>\n <mask token>\n\n def get_neighbour(self, agent):\n return self.locator.get_neighbour(agent)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass AggregateAgent(Addressable, AbstractAgent):\n\n @Inject('aggregated_agents:_AggregateAgent__agents')\n @InjectOptional('locator')\n def __init__(self, name=None):\n self.name = name\n super(AggregateAgent, self).__init__()\n for agent in self.__agents.values():\n agent.parent = self\n self.steps = 0\n\n def step(self):\n for agent in self.__agents.values():\n agent.step()\n self.steps += 1\n\n def remove_agent(self, agent):\n del self.__agents[agent.get_address()]\n self.locator.remove_agent(agent)\n agent.parent = None\n return agent\n\n def add_agent(self, agent):\n agent.parent = self\n self.__agents[agent.get_address()] = agent\n\n def get_agents(self):\n return self.__agents.values()\n\n def get_fitness(self):\n try:\n return max(agent.get_fitness() for agent in self.__agents.values())\n except ValueError:\n return None\n\n def get_best_genotype(self):\n return max(self.__agents.values(), key=lambda a: a.get_fitness()\n ).get_best_genotype()\n\n def move(self, agent):\n allowed_moves = self.locator.get_allowed_moves(agent)\n if allowed_moves:\n self.locator.remove_agent(agent)\n destination = get_random_move(allowed_moves)\n self.locator.add_agent(agent, destination)\n logger.debug('%s moved to %s' % (agent, destination))\n\n def get_neighbour(self, agent):\n return self.locator.get_neighbour(agent)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass AggregateAgent(Addressable, AbstractAgent):\n\n @Inject('aggregated_agents:_AggregateAgent__agents')\n @InjectOptional('locator')\n def __init__(self, name=None):\n self.name = name\n super(AggregateAgent, self).__init__()\n for agent in self.__agents.values():\n agent.parent = self\n self.steps = 0\n\n def step(self):\n for agent in self.__agents.values():\n agent.step()\n self.steps += 1\n\n def remove_agent(self, agent):\n del self.__agents[agent.get_address()]\n self.locator.remove_agent(agent)\n agent.parent = None\n return agent\n\n def add_agent(self, agent):\n agent.parent = self\n self.__agents[agent.get_address()] = agent\n\n def get_agents(self):\n return self.__agents.values()\n\n def get_fitness(self):\n try:\n return max(agent.get_fitness() for agent in self.__agents.values())\n except ValueError:\n return None\n\n def get_best_genotype(self):\n return max(self.__agents.values(), key=lambda a: a.get_fitness()\n ).get_best_genotype()\n\n def move(self, agent):\n allowed_moves = self.locator.get_allowed_moves(agent)\n if allowed_moves:\n self.locator.remove_agent(agent)\n destination = get_random_move(allowed_moves)\n self.locator.add_agent(agent, destination)\n logger.debug('%s moved to %s' % (agent, destination))\n\n def get_neighbour(self, agent):\n return self.locator.get_neighbour(agent)\n\n\ndef aggregate_agents_factory(*args):\n\n def factory():\n agents = {}\n for name in args:\n agent = AggregateAgent(name)\n agents[agent.get_address()] = agent\n return agents\n return factory\n\n\n<mask token>\n", "step-4": "<mask token>\nlogger = logging.getLogger(__name__)\n\n\nclass AggregateAgent(Addressable, AbstractAgent):\n\n @Inject('aggregated_agents:_AggregateAgent__agents')\n @InjectOptional('locator')\n def __init__(self, name=None):\n self.name = name\n super(AggregateAgent, self).__init__()\n for agent in self.__agents.values():\n agent.parent = self\n self.steps = 0\n\n def step(self):\n for agent in self.__agents.values():\n agent.step()\n self.steps += 1\n\n def remove_agent(self, agent):\n del self.__agents[agent.get_address()]\n self.locator.remove_agent(agent)\n agent.parent = None\n return agent\n\n def add_agent(self, agent):\n agent.parent = self\n self.__agents[agent.get_address()] = agent\n\n def get_agents(self):\n return self.__agents.values()\n\n def get_fitness(self):\n try:\n return max(agent.get_fitness() for agent in self.__agents.values())\n except ValueError:\n return None\n\n def get_best_genotype(self):\n return max(self.__agents.values(), key=lambda a: a.get_fitness()\n ).get_best_genotype()\n\n def move(self, agent):\n allowed_moves = self.locator.get_allowed_moves(agent)\n if allowed_moves:\n self.locator.remove_agent(agent)\n destination = get_random_move(allowed_moves)\n self.locator.add_agent(agent, destination)\n logger.debug('%s moved to %s' % (agent, destination))\n\n def get_neighbour(self, agent):\n return self.locator.get_neighbour(agent)\n\n\ndef aggregate_agents_factory(*args):\n\n def factory():\n agents = {}\n for name in args:\n agent = AggregateAgent(name)\n agents[agent.get_address()] = agent\n return agents\n return factory\n\n\ndef get_random_move(allowed_moves):\n destination = random.sample(allowed_moves, 1)[0]\n return destination\n", "step-5": "import logging\nimport random\nfrom pyage.core.address import Addressable\nfrom pyage.core.agent.agent import AbstractAgent\nfrom pyage.core.inject import Inject, InjectOptional\n\nlogger = logging.getLogger(__name__)\n\n\nclass AggregateAgent(Addressable, AbstractAgent):\n @Inject(\"aggregated_agents:_AggregateAgent__agents\")\n @InjectOptional(\"locator\")\n def __init__(self, name=None):\n self.name = name\n super(AggregateAgent, self).__init__()\n for agent in self.__agents.values():\n agent.parent = self\n self.steps = 0\n\n def step(self):\n for agent in self.__agents.values():\n agent.step()\n self.steps += 1\n\n def remove_agent(self, agent):\n del self.__agents[agent.get_address()]\n self.locator.remove_agent(agent)\n agent.parent = None\n return agent\n\n def add_agent(self, agent):\n agent.parent = self\n self.__agents[agent.get_address()] = agent\n\n def get_agents(self):\n return self.__agents.values()\n\n def get_fitness(self):\n try:\n return max(agent.get_fitness() for agent in self.__agents.values())\n except ValueError:\n return None\n\n def get_best_genotype(self):\n return max(self.__agents.values(), key=lambda a: a.get_fitness()).get_best_genotype()\n\n def move(self, agent):\n allowed_moves = self.locator.get_allowed_moves(agent)\n if allowed_moves:\n self.locator.remove_agent(agent)\n destination = get_random_move(allowed_moves)\n self.locator.add_agent(agent, destination)\n logger.debug(\"%s moved to %s\" % (agent, destination))\n\n def get_neighbour(self, agent):\n return self.locator.get_neighbour(agent)\n\n\ndef aggregate_agents_factory(*args):\n def factory():\n agents = {}\n for name in args:\n agent = AggregateAgent(name)\n agents[agent.get_address()] = agent\n return agents\n\n return factory\n\n\ndef get_random_move(allowed_moves):\n destination = random.sample(allowed_moves, 1)[0]\n return destination", "step-ids": [ 7, 10, 11, 13, 15 ] }
[ 7, 10, 11, 13, 15 ]
from collections import Counter import numpy as np import random import torch import BidModel from douzero.env.game import GameEnv env_version = "3.2" env_url = "http://od.vcccz.com/hechuan/env.py" Card2Column = {3: 0, 4: 1, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6, 10: 7, 11: 8, 12: 9, 13: 10, 14: 11, 17: 12} NumOnes2Array = {0: np.array([0, 0, 0, 0]), 1: np.array([1, 0, 0, 0]), 2: np.array([1, 1, 0, 0]), 3: np.array([1, 1, 1, 0]), 4: np.array([1, 1, 1, 1])} deck = [] for i in range(3, 15): deck.extend([i for _ in range(4)]) deck.extend([17 for _ in range(4)]) deck.extend([20, 30]) class Env: """ Doudizhu multi-agent wrapper """ def __init__(self, objective): """ Objective is wp/adp/logadp. It indicates whether considers bomb in reward calculation. Here, we use dummy agents. This is because, in the orignial game, the players are `in` the game. Here, we want to isolate players and environments to have a more gym style interface. To achieve this, we use dummy players to play. For each move, we tell the corresponding dummy player which action to play, then the player will perform the actual action in the game engine. """ self.objective = objective # Initialize players # We use three dummy player for the target position self.players = {} for position in ['landlord', 'landlord_up', 'landlord_down']: self.players[position] = DummyAgent(position) # Initialize the internal environment self._env = GameEnv(self.players) self.total_round = 0 self.force_bid = 0 self.infoset = None def reset(self, model, device, flags=None): """ Every time reset is called, the environment will be re-initialized with a new deck of cards. This function is usually called when a game is over. """ self._env.reset() # Randomly shuffle the deck if model is None: _deck = deck.copy() np.random.shuffle(_deck) card_play_data = {'landlord': _deck[:20], 'landlord_up': _deck[20:37], 'landlord_down': _deck[37:54], 'three_landlord_cards': _deck[17:20], } for key in card_play_data: card_play_data[key].sort() self._env.card_play_init(card_play_data) self.infoset = self._game_infoset return get_obs(self.infoset) else: self.total_round += 1 bid_done = False card_play_data = [] landlord_cards = [] last_bid = 0 bid_count = 0 player_ids = {} bid_info = None bid_obs_buffer = [] multiply_obs_buffer = [] bid_limit = 3 force_bid = False while not bid_done: bid_limit -= 1 bid_obs_buffer.clear() multiply_obs_buffer.clear() _deck = deck.copy() np.random.shuffle(_deck) card_play_data = [ _deck[:17], _deck[17:34], _deck[34:51], ] for i in range(3): card_play_data[i].sort() landlord_cards = _deck[51:54] landlord_cards.sort() bid_info = np.array([[-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]) bidding_player = random.randint(0, 2) # bidding_player = 0 # debug first_bid = -1 last_bid = -1 bid_count = 0 if bid_limit <= 0: force_bid = True for r in range(3): bidding_obs = _get_obs_for_bid(bidding_player, bid_info, card_play_data[bidding_player]) with torch.no_grad(): action = model.forward("bidding", torch.tensor(bidding_obs["z_batch"], device=device), torch.tensor(bidding_obs["x_batch"], device=device), flags=flags) if bid_limit <= 0: wr = BidModel.predict_env(card_play_data[bidding_player]) if wr >= 0.7: action = {"action": 1} # debug bid_limit += 1 bid_obs_buffer.append({ "x_batch": bidding_obs["x_batch"][action["action"]], "z_batch": bidding_obs["z_batch"][action["action"]], "pid": bidding_player }) if action["action"] == 1: last_bid = bidding_player bid_count += 1 if first_bid == -1: first_bid = bidding_player for p in range(3): if p == bidding_player: bid_info[r][p] = 1 else: bid_info[r][p] = 0 else: bid_info[r] = [0, 0, 0] bidding_player = (bidding_player + 1) % 3 one_count = np.count_nonzero(bid_info == 1) if one_count == 0: continue elif one_count > 1: r = 3 bidding_player = first_bid bidding_obs = _get_obs_for_bid(bidding_player, bid_info, card_play_data[bidding_player]) with torch.no_grad(): action = model.forward("bidding", torch.tensor(bidding_obs["z_batch"], device=device), torch.tensor(bidding_obs["x_batch"], device=device), flags=flags) bid_obs_buffer.append({ "x_batch": bidding_obs["x_batch"][action["action"]], "z_batch": bidding_obs["z_batch"][action["action"]], "pid": bidding_player }) if action["action"] == 1: last_bid = bidding_player bid_count += 1 for p in range(3): if p == bidding_player: bid_info[r][p] = 1 else: bid_info[r][p] = 0 break card_play_data[last_bid].extend(landlord_cards) card_play_data = {'landlord': card_play_data[last_bid], 'landlord_up': card_play_data[(last_bid - 1) % 3], 'landlord_down': card_play_data[(last_bid + 1) % 3], 'three_landlord_cards': landlord_cards, } card_play_data["landlord"].sort() player_ids = { 'landlord': last_bid, 'landlord_up': (last_bid - 1) % 3, 'landlord_down': (last_bid + 1) % 3, } player_positions = { last_bid: 'landlord', (last_bid - 1) % 3: 'landlord_up', (last_bid + 1) % 3: 'landlord_down' } for bid_obs in bid_obs_buffer: bid_obs.update({"position": player_positions[bid_obs["pid"]]}) # Initialize the cards self._env.card_play_init(card_play_data) multiply_map = [ np.array([1, 0, 0]), np.array([0, 1, 0]), np.array([0, 0, 1]) ] for pos in ["landlord", "landlord_up", "landlord_down"]: pid = player_ids[pos] self._env.info_sets[pos].player_id = pid self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) % 3, pid, (pid + 1) % 3]] self._env.bid_count = bid_count # multiply_obs = _get_obs_for_multiply(pos, self._env.info_sets[pos].bid_info, card_play_data[pos], # landlord_cards) # action = model.forward(pos, torch.tensor(multiply_obs["z_batch"], device=device), # torch.tensor(multiply_obs["x_batch"], device=device), flags=flags) # multiply_obs_buffer.append({ # "x_batch": multiply_obs["x_batch"][action["action"]], # "z_batch": multiply_obs["z_batch"][action["action"]], # "position": pos # }) action = {"action": 0} self._env.info_sets[pos].multiply_info = multiply_map[action["action"]] self._env.multiply_count[pos] = action["action"] self.infoset = self._game_infoset if force_bid: self.force_bid += 1 if self.total_round % 100 == 0: print("发牌情况: %i/%i %.1f%%" % (self.force_bid, self.total_round, self.force_bid / self.total_round * 100)) self.force_bid = 0 self.total_round = 0 return get_obs(self.infoset), { "bid_obs_buffer": bid_obs_buffer, "multiply_obs_buffer": multiply_obs_buffer } def step(self, action): """ Step function takes as input the action, which is a list of integers, and output the next obervation, reward, and a Boolean variable indicating whether the current game is finished. It also returns an empty dictionary that is reserved to pass useful information. """ assert action in self.infoset.legal_actions self.players[self._acting_player_position].set_action(action) self._env.step() self.infoset = self._game_infoset done = False reward = 0.0 if self._game_over: done = True reward = { "play": { "landlord": self._get_reward("landlord"), "landlord_up": self._get_reward("landlord_up"), "landlord_down": self._get_reward("landlord_down") }, "bid": { "landlord": self._get_reward_bidding("landlord")*2, "landlord_up": self._get_reward_bidding("landlord_up"), "landlord_down": self._get_reward_bidding("landlord_down") } } obs = None else: obs = get_obs(self.infoset) return obs, reward, done, {} def _get_reward(self, pos): """ This function is called in the end of each game. It returns either 1/-1 for win/loss, or ADP, i.e., every bomb will double the score. """ winner = self._game_winner bomb_num = self._game_bomb_num self_bomb_num = self._env.pos_bomb_num[pos] if winner == 'landlord': if self.objective == 'adp': return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +self._env.multiply_count[pos]) /8 elif self.objective == 'logadp': return (1.0 - self._env.step_count * 0.0033) * 1.3**self_bomb_num * 2**self._env.multiply_count[pos] / 4 else: return 1.0 - self._env.step_count * 0.0033 else: if self.objective == 'adp': return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +self._env.multiply_count[pos]) /8 elif self.objective == 'logadp': return (-1.0 + self._env.step_count * 0.0033) * 1.3**self_bomb_num * 2**self._env.multiply_count[pos] / 4 else: return -1.0 + self._env.step_count * 0.0033 def _get_reward_bidding(self, pos): """ This function is called in the end of each game. It returns either 1/-1 for win/loss, or ADP, i.e., every bomb will double the score. """ winner = self._game_winner bomb_num = self._game_bomb_num if winner == 'landlord': return 1.0 * 2**(self._env.bid_count-1) / 8 else: return -1.0 * 2**(self._env.bid_count-1) / 8 @property def _game_infoset(self): """ Here, inforset is defined as all the information in the current situation, incuding the hand cards of all the players, all the historical moves, etc. That is, it contains perferfect infomation. Later, we will use functions to extract the observable information from the views of the three players. """ return self._env.game_infoset @property def _game_bomb_num(self): """ The number of bombs played so far. This is used as a feature of the neural network and is also used to calculate ADP. """ return self._env.get_bomb_num() @property def _game_winner(self): """ A string of landlord/peasants """ return self._env.get_winner() @property def _acting_player_position(self): """ The player that is active. It can be landlord, landlod_down, or landlord_up. """ return self._env.acting_player_position @property def _game_over(self): """ Returns a Boolean """ return self._env.game_over class DummyAgent(object): """ Dummy agent is designed to easily interact with the game engine. The agent will first be told what action to perform. Then the environment will call this agent to perform the actual action. This can help us to isolate environment and agents towards a gym like interface. """ def __init__(self, position): self.position = position self.action = None def act(self, infoset): """ Simply return the action that is set previously. """ assert self.action in infoset.legal_actions return self.action def set_action(self, action): """ The environment uses this function to tell the dummy agent what to do. """ self.action = action def get_obs(infoset, use_general=True): """ This function obtains observations with imperfect information from the infoset. It has three branches since we encode different features for different positions. This function will return dictionary named `obs`. It contains several fields. These fields will be used to train the model. One can play with those features to improve the performance. `position` is a string that can be landlord/landlord_down/landlord_up `x_batch` is a batch of features (excluding the hisorical moves). It also encodes the action feature `z_batch` is a batch of features with hisorical moves only. `legal_actions` is the legal moves `x_no_action`: the features (exluding the hitorical moves and the action features). It does not have the batch dim. `z`: same as z_batch but not a batch. """ if use_general: if infoset.player_position not in ["landlord", "landlord_up", "landlord_down"]: raise ValueError('') return _get_obs_general(infoset, infoset.player_position) else: if infoset.player_position == 'landlord': return _get_obs_landlord(infoset) elif infoset.player_position == 'landlord_up': return _get_obs_landlord_up(infoset) elif infoset.player_position == 'landlord_down': return _get_obs_landlord_down(infoset) else: raise ValueError('') def _get_one_hot_array(num_left_cards, max_num_cards): """ A utility function to obtain one-hot endoding """ one_hot = np.zeros(max_num_cards) if num_left_cards > 0: one_hot[num_left_cards - 1] = 1 return one_hot def _cards2array(list_cards): """ A utility function that transforms the actions, i.e., A list of integers into card matrix. Here we remove the six entries that are always zero and flatten the the representations. """ if len(list_cards) == 0: return np.zeros(54, dtype=np.int8) matrix = np.zeros([4, 13], dtype=np.int8) jokers = np.zeros(2, dtype=np.int8) counter = Counter(list_cards) for card, num_times in counter.items(): if card < 20: matrix[:, Card2Column[card]] = NumOnes2Array[num_times] elif card == 20: jokers[0] = 1 elif card == 30: jokers[1] = 1 return np.concatenate((matrix.flatten('F'), jokers)) # def _action_seq_list2array(action_seq_list): # """ # A utility function to encode the historical moves. # We encode the historical 15 actions. If there is # no 15 actions, we pad the features with 0. Since # three moves is a round in DouDizhu, we concatenate # the representations for each consecutive three moves. # Finally, we obtain a 5x162 matrix, which will be fed # into LSTM for encoding. # """ # action_seq_array = np.zeros((len(action_seq_list), 54)) # for row, list_cards in enumerate(action_seq_list): # action_seq_array[row, :] = _cards2array(list_cards) # # action_seq_array = action_seq_array.reshape(5, 162) # return action_seq_array def _action_seq_list2array(action_seq_list, new_model=True): """ A utility function to encode the historical moves. We encode the historical 15 actions. If there is no 15 actions, we pad the features with 0. Since three moves is a round in DouDizhu, we concatenate the representations for each consecutive three moves. Finally, we obtain a 5x162 matrix, which will be fed into LSTM for encoding. """ if new_model: position_map = {"landlord": 0, "landlord_up": 1, "landlord_down": 2} action_seq_array = np.ones((len(action_seq_list), 54)) * -1 # Default Value -1 for not using area for row, list_cards in enumerate(action_seq_list): if list_cards != []: action_seq_array[row, :54] = _cards2array(list_cards[1]) else: action_seq_array = np.zeros((len(action_seq_list), 54)) for row, list_cards in enumerate(action_seq_list): if list_cards != []: action_seq_array[row, :] = _cards2array(list_cards[1]) action_seq_array = action_seq_array.reshape(5, 162) return action_seq_array # action_seq_array = np.zeros((len(action_seq_list), 54)) # for row, list_cards in enumerate(action_seq_list): # if list_cards != []: # action_seq_array[row, :] = _cards2array(list_cards[1]) # return action_seq_array def _process_action_seq(sequence, length=15, new_model=True): """ A utility function encoding historical moves. We encode 15 moves. If there is no 15 moves, we pad with zeros. """ sequence = sequence[-length:].copy() if new_model: sequence = sequence[::-1] if len(sequence) < length: empty_sequence = [[] for _ in range(length - len(sequence))] empty_sequence.extend(sequence) sequence = empty_sequence return sequence def _get_one_hot_bomb(bomb_num): """ A utility function to encode the number of bombs into one-hot representation. """ one_hot = np.zeros(15) one_hot[bomb_num] = 1 return one_hot def _get_obs_landlord(infoset): """ Obttain the landlord features. See Table 4 in https://arxiv.org/pdf/2106.06135.pdf """ num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) landlord_up_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_up'], 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_down'], 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array( infoset.played_cards['landlord_up']) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array( infoset.played_cards['landlord_down']) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((my_handcards_batch, other_handcards_batch, last_action_batch, landlord_up_played_cards_batch, landlord_down_played_cards_batch, landlord_up_num_cards_left_batch, landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch)) x_no_action = np.hstack((my_handcards, other_handcards, last_action, landlord_up_played_cards, landlord_down_played_cards, landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq( infoset.card_play_action_seq, 15, False), False) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': 'landlord', 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def _get_obs_landlord_up(infoset): """ Obttain the landlord_up features. See Table 5 in https://arxiv.org/pdf/2106.06135.pdf """ num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) last_landlord_action = _cards2array( infoset.last_move_dict['landlord']) last_landlord_action_batch = np.repeat( last_landlord_action[np.newaxis, :], num_legal_actions, axis=0) landlord_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord'], 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_played_cards = _cards2array( infoset.played_cards['landlord']) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) last_teammate_action = _cards2array( infoset.last_move_dict['landlord_down']) last_teammate_action_batch = np.repeat( last_teammate_action[np.newaxis, :], num_legal_actions, axis=0) teammate_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_down'], 17) teammate_num_cards_left_batch = np.repeat( teammate_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) teammate_played_cards = _cards2array( infoset.played_cards['landlord_down']) teammate_played_cards_batch = np.repeat( teammate_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((my_handcards_batch, other_handcards_batch, landlord_played_cards_batch, teammate_played_cards_batch, last_action_batch, last_landlord_action_batch, last_teammate_action_batch, landlord_num_cards_left_batch, teammate_num_cards_left_batch, bomb_num_batch, my_action_batch)) x_no_action = np.hstack((my_handcards, other_handcards, landlord_played_cards, teammate_played_cards, last_action, last_landlord_action, last_teammate_action, landlord_num_cards_left, teammate_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq( infoset.card_play_action_seq, 15, False), False) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': 'landlord_up', 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def _get_obs_landlord_down(infoset): """ Obttain the landlord_down features. See Table 5 in https://arxiv.org/pdf/2106.06135.pdf """ num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) last_landlord_action = _cards2array( infoset.last_move_dict['landlord']) last_landlord_action_batch = np.repeat( last_landlord_action[np.newaxis, :], num_legal_actions, axis=0) landlord_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord'], 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_played_cards = _cards2array( infoset.played_cards['landlord']) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) last_teammate_action = _cards2array( infoset.last_move_dict['landlord_up']) last_teammate_action_batch = np.repeat( last_teammate_action[np.newaxis, :], num_legal_actions, axis=0) teammate_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_up'], 17) teammate_num_cards_left_batch = np.repeat( teammate_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) teammate_played_cards = _cards2array( infoset.played_cards['landlord_up']) teammate_played_cards_batch = np.repeat( teammate_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_played_cards = _cards2array( infoset.played_cards['landlord']) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((my_handcards_batch, other_handcards_batch, landlord_played_cards_batch, teammate_played_cards_batch, last_action_batch, last_landlord_action_batch, last_teammate_action_batch, landlord_num_cards_left_batch, teammate_num_cards_left_batch, bomb_num_batch, my_action_batch)) x_no_action = np.hstack((my_handcards, other_handcards, landlord_played_cards, teammate_played_cards, last_action, last_landlord_action, last_teammate_action, landlord_num_cards_left, teammate_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq( infoset.card_play_action_seq, 15, False), False) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': 'landlord_down', 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def _get_obs_landlord_withbid(infoset): """ Obttain the landlord features. See Table 4 in https://arxiv.org/pdf/2106.06135.pdf """ num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) landlord_up_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_up'], 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_down'], 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array( infoset.played_cards['landlord_up']) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array( infoset.played_cards['landlord_down']) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((my_handcards_batch, other_handcards_batch, last_action_batch, landlord_up_played_cards_batch, landlord_down_played_cards_batch, landlord_up_num_cards_left_batch, landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch)) x_no_action = np.hstack((my_handcards, other_handcards, last_action, landlord_up_played_cards, landlord_down_played_cards, landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq( infoset.card_play_action_seq, 15, False), False) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': 'landlord', 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def _get_obs_general1(infoset, position): num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) position_map = { "landlord": [1, 0, 0], "landlord_up": [0, 1, 0], "landlord_down": [0, 0, 1] } position_info = np.array(position_map[position]) position_info_batch = np.repeat(position_info[np.newaxis, :], num_legal_actions, axis=0) bid_info = np.array(infoset.bid_info).flatten() bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions, axis=0) multiply_info = np.array(infoset.multiply_info) multiply_info_batch = np.repeat(multiply_info[np.newaxis, :], num_legal_actions, axis=0) three_landlord_cards = _cards2array(infoset.three_landlord_cards) three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) landlord_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord'], 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_up'], 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_down'], 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) other_handcards_left_list = [] for pos in ["landlord", "landlord_up", "landlord_up"]: if pos != position: other_handcards_left_list.extend(infoset.all_handcards[pos]) landlord_played_cards = _cards2array( infoset.played_cards['landlord']) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array( infoset.played_cards['landlord_up']) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array( infoset.played_cards['landlord_down']) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((position_info_batch, # 3 my_handcards_batch, # 54 other_handcards_batch, # 54 three_landlord_cards_batch, # 54 last_action_batch, # 54 landlord_played_cards_batch, # 54 landlord_up_played_cards_batch, # 54 landlord_down_played_cards_batch, # 54 landlord_num_cards_left_batch, # 20 landlord_up_num_cards_left_batch, # 17 landlord_down_num_cards_left_batch, # 17 bomb_num_batch, # 15 bid_info_batch, # 12 multiply_info_batch, # 3 my_action_batch)) # 54 x_no_action = np.hstack((position_info, my_handcards, other_handcards, three_landlord_cards, last_action, landlord_played_cards, landlord_up_played_cards, landlord_down_played_cards, landlord_num_cards_left, landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num, bid_info, multiply_info)) z = _action_seq_list2array(_process_action_seq( infoset.card_play_action_seq, 32)) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': position, 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def _get_obs_general(infoset, position): num_legal_actions = len(infoset.legal_actions) my_handcards = _cards2array(infoset.player_hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_handcards = _cards2array(infoset.other_hand_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) position_map = { "landlord": [1, 0, 0], "landlord_up": [0, 1, 0], "landlord_down": [0, 0, 1] } position_info = np.array(position_map[position]) position_info_batch = np.repeat(position_info[np.newaxis, :], num_legal_actions, axis=0) bid_info = np.array(infoset.bid_info).flatten() bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions, axis=0) multiply_info = np.array(infoset.multiply_info) multiply_info_batch = np.repeat(multiply_info[np.newaxis, :], num_legal_actions, axis=0) three_landlord_cards = _cards2array(infoset.three_landlord_cards) three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array(infoset.last_move) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j, action in enumerate(infoset.legal_actions): my_action_batch[j, :] = _cards2array(action) landlord_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord'], 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_up'], 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array( infoset.num_cards_left_dict['landlord_down'], 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) other_handcards_left_list = [] for pos in ["landlord", "landlord_up", "landlord_up"]: if pos != position: other_handcards_left_list.extend(infoset.all_handcards[pos]) landlord_played_cards = _cards2array( infoset.played_cards['landlord']) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array( infoset.played_cards['landlord_up']) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array( infoset.played_cards['landlord_down']) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb( infoset.bomb_num) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) num_cards_left = np.hstack(( landlord_num_cards_left, # 20 landlord_up_num_cards_left, # 17 landlord_down_num_cards_left)) x_batch = np.hstack(( bid_info_batch, # 12 multiply_info_batch)) # 3 x_no_action = np.hstack(( bid_info, multiply_info)) z =np.vstack(( num_cards_left, my_handcards, # 54 other_handcards, # 54 three_landlord_cards, # 54 landlord_played_cards, # 54 landlord_up_played_cards, # 54 landlord_down_played_cards, # 54 _action_seq_list2array(_process_action_seq(infoset.card_play_action_seq, 32)) )) _z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) my_action_batch = my_action_batch[:,np.newaxis,:] z_batch = np.zeros([len(_z_batch),40,54],int) for i in range(0,len(_z_batch)): z_batch[i] = np.vstack((my_action_batch[i],_z_batch[i])) obs = { 'position': position, 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), } return obs def gen_bid_legal_actions(player_id, bid_info): self_bid_info = bid_info[:, [(player_id - 1) % 3, player_id, (player_id + 1) % 3]] curr_round = -1 for r in range(4): if -1 in self_bid_info[r]: curr_round = r break bid_actions = [] if curr_round != -1: self_bid_info[curr_round] = [0, 0, 0] bid_actions.append(np.array(self_bid_info).flatten()) self_bid_info[curr_round] = [0, 1, 0] bid_actions.append(np.array(self_bid_info).flatten()) return np.array(bid_actions) def _get_obs_for_bid_legacy(player_id, bid_info, hand_cards): all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] num_legal_actions = 2 my_handcards = _cards2array(hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_cards = [] other_cards.extend(all_cards) for card in hand_cards: other_cards.remove(card) other_handcards = _cards2array(other_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) position_info = np.array([0, 0, 0]) position_info_batch = np.repeat(position_info[np.newaxis, :], num_legal_actions, axis=0) bid_legal_actions = gen_bid_legal_actions(player_id, bid_info) bid_info = bid_legal_actions[0] bid_info_batch = bid_legal_actions multiply_info = np.array([0, 0, 0]) multiply_info_batch = np.repeat(multiply_info[np.newaxis, :], num_legal_actions, axis=0) three_landlord_cards = _cards2array([]) three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array([]) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j in range(2): my_action_batch[j, :] = _cards2array([]) landlord_num_cards_left = _get_one_hot_array(0, 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_num_cards_left = _get_one_hot_array(0, 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array(0, 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_played_cards = _cards2array([]) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array([]) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array([]) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb(0) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((position_info_batch, my_handcards_batch, other_handcards_batch, three_landlord_cards_batch, last_action_batch, landlord_played_cards_batch, landlord_up_played_cards_batch, landlord_down_played_cards_batch, landlord_num_cards_left_batch, landlord_up_num_cards_left_batch, landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch, multiply_info_batch, my_action_batch)) x_no_action = np.hstack((position_info, my_handcards, other_handcards, three_landlord_cards, last_action, landlord_played_cards, landlord_up_played_cards, landlord_down_played_cards, landlord_num_cards_left, landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq([], 32)) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': "", 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': bid_legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), "bid_info_batch": bid_info_batch.astype(np.int8), "multiply_info": multiply_info.astype(np.int8) } return obs def _get_obs_for_bid(player_id, bid_info, hand_cards): all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] num_legal_actions = 2 my_handcards = _cards2array(hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) bid_legal_actions = gen_bid_legal_actions(player_id, bid_info) bid_info = bid_legal_actions[0] bid_info_batch = np.hstack([bid_legal_actions for _ in range(5)]) x_batch = np.hstack((my_handcards_batch, bid_info_batch)) x_no_action = np.hstack((my_handcards)) obs = { 'position': "", 'x_batch': x_batch.astype(np.float32), 'z_batch': np.array([0,0]), 'legal_actions': bid_legal_actions, 'x_no_action': x_no_action.astype(np.int8), "bid_info_batch": bid_info_batch.astype(np.int8) } return obs def _get_obs_for_multiply(position, bid_info, hand_cards, landlord_cards): all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] num_legal_actions = 3 my_handcards = _cards2array(hand_cards) my_handcards_batch = np.repeat(my_handcards[np.newaxis, :], num_legal_actions, axis=0) other_cards = [] other_cards.extend(all_cards) for card in hand_cards: other_cards.remove(card) other_handcards = _cards2array(other_cards) other_handcards_batch = np.repeat(other_handcards[np.newaxis, :], num_legal_actions, axis=0) position_map = { "landlord": [1, 0, 0], "landlord_up": [0, 1, 0], "landlord_down": [0, 0, 1] } position_info = np.array(position_map[position]) position_info_batch = np.repeat(position_info[np.newaxis, :], num_legal_actions, axis=0) bid_info = np.array(bid_info).flatten() bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions, axis=0) multiply_info = np.array([0, 0, 0]) multiply_info_batch = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) three_landlord_cards = _cards2array(landlord_cards) three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :], num_legal_actions, axis=0) last_action = _cards2array([]) last_action_batch = np.repeat(last_action[np.newaxis, :], num_legal_actions, axis=0) my_action_batch = np.zeros(my_handcards_batch.shape) for j in range(num_legal_actions): my_action_batch[j, :] = _cards2array([]) landlord_num_cards_left = _get_one_hot_array(0, 20) landlord_num_cards_left_batch = np.repeat( landlord_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_up_num_cards_left = _get_one_hot_array(0, 17) landlord_up_num_cards_left_batch = np.repeat( landlord_up_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_down_num_cards_left = _get_one_hot_array(0, 17) landlord_down_num_cards_left_batch = np.repeat( landlord_down_num_cards_left[np.newaxis, :], num_legal_actions, axis=0) landlord_played_cards = _cards2array([]) landlord_played_cards_batch = np.repeat( landlord_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_up_played_cards = _cards2array([]) landlord_up_played_cards_batch = np.repeat( landlord_up_played_cards[np.newaxis, :], num_legal_actions, axis=0) landlord_down_played_cards = _cards2array([]) landlord_down_played_cards_batch = np.repeat( landlord_down_played_cards[np.newaxis, :], num_legal_actions, axis=0) bomb_num = _get_one_hot_bomb(0) bomb_num_batch = np.repeat( bomb_num[np.newaxis, :], num_legal_actions, axis=0) x_batch = np.hstack((position_info_batch, my_handcards_batch, other_handcards_batch, three_landlord_cards_batch, last_action_batch, landlord_played_cards_batch, landlord_up_played_cards_batch, landlord_down_played_cards_batch, landlord_num_cards_left_batch, landlord_up_num_cards_left_batch, landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch, multiply_info_batch, my_action_batch)) x_no_action = np.hstack((position_info, my_handcards, other_handcards, three_landlord_cards, last_action, landlord_played_cards, landlord_up_played_cards, landlord_down_played_cards, landlord_num_cards_left, landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num)) z = _action_seq_list2array(_process_action_seq([], 32)) z_batch = np.repeat( z[np.newaxis, :, :], num_legal_actions, axis=0) obs = { 'position': "", 'x_batch': x_batch.astype(np.float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions': multiply_info_batch, 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8), "bid_info": bid_info.astype(np.int8), "multiply_info_batch": multiply_info.astype(np.int8) } return obs
normal
{ "blob_id": "4015078ee9640c4558a4f29ebbb89f9098a31014", "index": 5720, "step-1": "<mask token>\n\n\nclass Env:\n <mask token>\n\n def __init__(self, objective):\n \"\"\"\n Objective is wp/adp/logadp. It indicates whether considers\n bomb in reward calculation. Here, we use dummy agents.\n This is because, in the orignial game, the players\n are `in` the game. Here, we want to isolate\n players and environments to have a more gym style\n interface. To achieve this, we use dummy players\n to play. For each move, we tell the corresponding\n dummy player which action to play, then the player\n will perform the actual action in the game engine.\n \"\"\"\n self.objective = objective\n self.players = {}\n for position in ['landlord', 'landlord_up', 'landlord_down']:\n self.players[position] = DummyAgent(position)\n self._env = GameEnv(self.players)\n self.total_round = 0\n self.force_bid = 0\n self.infoset = None\n\n def reset(self, model, device, flags=None):\n \"\"\"\n Every time reset is called, the environment\n will be re-initialized with a new deck of cards.\n This function is usually called when a game is over.\n \"\"\"\n self._env.reset()\n if model is None:\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = {'landlord': _deck[:20], 'landlord_up': _deck[\n 20:37], 'landlord_down': _deck[37:54],\n 'three_landlord_cards': _deck[17:20]}\n for key in card_play_data:\n card_play_data[key].sort()\n self._env.card_play_init(card_play_data)\n self.infoset = self._game_infoset\n return get_obs(self.infoset)\n else:\n self.total_round += 1\n bid_done = False\n card_play_data = []\n landlord_cards = []\n last_bid = 0\n bid_count = 0\n player_ids = {}\n bid_info = None\n bid_obs_buffer = []\n multiply_obs_buffer = []\n bid_limit = 3\n force_bid = False\n while not bid_done:\n bid_limit -= 1\n bid_obs_buffer.clear()\n multiply_obs_buffer.clear()\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = [_deck[:17], _deck[17:34], _deck[34:51]]\n for i in range(3):\n card_play_data[i].sort()\n landlord_cards = _deck[51:54]\n landlord_cards.sort()\n bid_info = np.array([[-1, -1, -1], [-1, -1, -1], [-1, -1, -\n 1], [-1, -1, -1]])\n bidding_player = random.randint(0, 2)\n first_bid = -1\n last_bid = -1\n bid_count = 0\n if bid_limit <= 0:\n force_bid = True\n for r in range(3):\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n if bid_limit <= 0:\n wr = BidModel.predict_env(card_play_data[\n bidding_player])\n if wr >= 0.7:\n action = {'action': 1}\n bid_limit += 1\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n if first_bid == -1:\n first_bid = bidding_player\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n else:\n bid_info[r] = [0, 0, 0]\n bidding_player = (bidding_player + 1) % 3\n one_count = np.count_nonzero(bid_info == 1)\n if one_count == 0:\n continue\n elif one_count > 1:\n r = 3\n bidding_player = first_bid\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n break\n card_play_data[last_bid].extend(landlord_cards)\n card_play_data = {'landlord': card_play_data[last_bid],\n 'landlord_up': card_play_data[(last_bid - 1) % 3],\n 'landlord_down': card_play_data[(last_bid + 1) % 3],\n 'three_landlord_cards': landlord_cards}\n card_play_data['landlord'].sort()\n player_ids = {'landlord': last_bid, 'landlord_up': (last_bid - \n 1) % 3, 'landlord_down': (last_bid + 1) % 3}\n player_positions = {last_bid: 'landlord', ((last_bid - 1) % 3):\n 'landlord_up', ((last_bid + 1) % 3): 'landlord_down'}\n for bid_obs in bid_obs_buffer:\n bid_obs.update({'position': player_positions[bid_obs['pid']]})\n self._env.card_play_init(card_play_data)\n multiply_map = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.\n array([0, 0, 1])]\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n pid = player_ids[pos]\n self._env.info_sets[pos].player_id = pid\n self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) %\n 3, pid, (pid + 1) % 3]]\n self._env.bid_count = bid_count\n action = {'action': 0}\n self._env.info_sets[pos].multiply_info = multiply_map[action\n ['action']]\n self._env.multiply_count[pos] = action['action']\n self.infoset = self._game_infoset\n if force_bid:\n self.force_bid += 1\n if self.total_round % 100 == 0:\n print('发牌情况: %i/%i %.1f%%' % (self.force_bid, self.\n total_round, self.force_bid / self.total_round * 100))\n self.force_bid = 0\n self.total_round = 0\n return get_obs(self.infoset), {'bid_obs_buffer': bid_obs_buffer,\n 'multiply_obs_buffer': multiply_obs_buffer}\n <mask token>\n\n def _get_reward(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n self_bomb_num = self._env.pos_bomb_num[pos]\n if winner == 'landlord':\n if self.objective == 'adp':\n return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num\n + self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (1.0 - self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[\n pos] / 4\n else:\n return 1.0 - self._env.step_count * 0.0033\n elif self.objective == 'adp':\n return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +\n self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (-1.0 + self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[pos\n ] / 4\n else:\n return -1.0 + self._env.step_count * 0.0033\n\n def _get_reward_bidding(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n if winner == 'landlord':\n return 1.0 * 2 ** (self._env.bid_count - 1) / 8\n else:\n return -1.0 * 2 ** (self._env.bid_count - 1) / 8\n\n @property\n def _game_infoset(self):\n \"\"\"\n Here, inforset is defined as all the information\n in the current situation, incuding the hand cards\n of all the players, all the historical moves, etc.\n That is, it contains perferfect infomation. Later,\n we will use functions to extract the observable\n information from the views of the three players.\n \"\"\"\n return self._env.game_infoset\n\n @property\n def _game_bomb_num(self):\n \"\"\"\n The number of bombs played so far. This is used as\n a feature of the neural network and is also used to\n calculate ADP.\n \"\"\"\n return self._env.get_bomb_num()\n\n @property\n def _game_winner(self):\n \"\"\" A string of landlord/peasants\n \"\"\"\n return self._env.get_winner()\n <mask token>\n <mask token>\n\n\nclass DummyAgent(object):\n \"\"\"\n Dummy agent is designed to easily interact with the\n game engine. The agent will first be told what action\n to perform. Then the environment will call this agent\n to perform the actual action. This can help us to\n isolate environment and agents towards a gym like\n interface.\n \"\"\"\n\n def __init__(self, position):\n self.position = position\n self.action = None\n\n def act(self, infoset):\n \"\"\"\n Simply return the action that is set previously.\n \"\"\"\n assert self.action in infoset.legal_actions\n return self.action\n\n def set_action(self, action):\n \"\"\"\n The environment uses this function to tell\n the dummy agent what to do.\n \"\"\"\n self.action = action\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Env:\n \"\"\"\n Doudizhu multi-agent wrapper\n \"\"\"\n\n def __init__(self, objective):\n \"\"\"\n Objective is wp/adp/logadp. It indicates whether considers\n bomb in reward calculation. Here, we use dummy agents.\n This is because, in the orignial game, the players\n are `in` the game. Here, we want to isolate\n players and environments to have a more gym style\n interface. To achieve this, we use dummy players\n to play. For each move, we tell the corresponding\n dummy player which action to play, then the player\n will perform the actual action in the game engine.\n \"\"\"\n self.objective = objective\n self.players = {}\n for position in ['landlord', 'landlord_up', 'landlord_down']:\n self.players[position] = DummyAgent(position)\n self._env = GameEnv(self.players)\n self.total_round = 0\n self.force_bid = 0\n self.infoset = None\n\n def reset(self, model, device, flags=None):\n \"\"\"\n Every time reset is called, the environment\n will be re-initialized with a new deck of cards.\n This function is usually called when a game is over.\n \"\"\"\n self._env.reset()\n if model is None:\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = {'landlord': _deck[:20], 'landlord_up': _deck[\n 20:37], 'landlord_down': _deck[37:54],\n 'three_landlord_cards': _deck[17:20]}\n for key in card_play_data:\n card_play_data[key].sort()\n self._env.card_play_init(card_play_data)\n self.infoset = self._game_infoset\n return get_obs(self.infoset)\n else:\n self.total_round += 1\n bid_done = False\n card_play_data = []\n landlord_cards = []\n last_bid = 0\n bid_count = 0\n player_ids = {}\n bid_info = None\n bid_obs_buffer = []\n multiply_obs_buffer = []\n bid_limit = 3\n force_bid = False\n while not bid_done:\n bid_limit -= 1\n bid_obs_buffer.clear()\n multiply_obs_buffer.clear()\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = [_deck[:17], _deck[17:34], _deck[34:51]]\n for i in range(3):\n card_play_data[i].sort()\n landlord_cards = _deck[51:54]\n landlord_cards.sort()\n bid_info = np.array([[-1, -1, -1], [-1, -1, -1], [-1, -1, -\n 1], [-1, -1, -1]])\n bidding_player = random.randint(0, 2)\n first_bid = -1\n last_bid = -1\n bid_count = 0\n if bid_limit <= 0:\n force_bid = True\n for r in range(3):\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n if bid_limit <= 0:\n wr = BidModel.predict_env(card_play_data[\n bidding_player])\n if wr >= 0.7:\n action = {'action': 1}\n bid_limit += 1\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n if first_bid == -1:\n first_bid = bidding_player\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n else:\n bid_info[r] = [0, 0, 0]\n bidding_player = (bidding_player + 1) % 3\n one_count = np.count_nonzero(bid_info == 1)\n if one_count == 0:\n continue\n elif one_count > 1:\n r = 3\n bidding_player = first_bid\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n break\n card_play_data[last_bid].extend(landlord_cards)\n card_play_data = {'landlord': card_play_data[last_bid],\n 'landlord_up': card_play_data[(last_bid - 1) % 3],\n 'landlord_down': card_play_data[(last_bid + 1) % 3],\n 'three_landlord_cards': landlord_cards}\n card_play_data['landlord'].sort()\n player_ids = {'landlord': last_bid, 'landlord_up': (last_bid - \n 1) % 3, 'landlord_down': (last_bid + 1) % 3}\n player_positions = {last_bid: 'landlord', ((last_bid - 1) % 3):\n 'landlord_up', ((last_bid + 1) % 3): 'landlord_down'}\n for bid_obs in bid_obs_buffer:\n bid_obs.update({'position': player_positions[bid_obs['pid']]})\n self._env.card_play_init(card_play_data)\n multiply_map = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.\n array([0, 0, 1])]\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n pid = player_ids[pos]\n self._env.info_sets[pos].player_id = pid\n self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) %\n 3, pid, (pid + 1) % 3]]\n self._env.bid_count = bid_count\n action = {'action': 0}\n self._env.info_sets[pos].multiply_info = multiply_map[action\n ['action']]\n self._env.multiply_count[pos] = action['action']\n self.infoset = self._game_infoset\n if force_bid:\n self.force_bid += 1\n if self.total_round % 100 == 0:\n print('发牌情况: %i/%i %.1f%%' % (self.force_bid, self.\n total_round, self.force_bid / self.total_round * 100))\n self.force_bid = 0\n self.total_round = 0\n return get_obs(self.infoset), {'bid_obs_buffer': bid_obs_buffer,\n 'multiply_obs_buffer': multiply_obs_buffer}\n\n def step(self, action):\n \"\"\"\n Step function takes as input the action, which\n is a list of integers, and output the next obervation,\n reward, and a Boolean variable indicating whether the\n current game is finished. It also returns an empty\n dictionary that is reserved to pass useful information.\n \"\"\"\n assert action in self.infoset.legal_actions\n self.players[self._acting_player_position].set_action(action)\n self._env.step()\n self.infoset = self._game_infoset\n done = False\n reward = 0.0\n if self._game_over:\n done = True\n reward = {'play': {'landlord': self._get_reward('landlord'),\n 'landlord_up': self._get_reward('landlord_up'),\n 'landlord_down': self._get_reward('landlord_down')}, 'bid':\n {'landlord': self._get_reward_bidding('landlord') * 2,\n 'landlord_up': self._get_reward_bidding('landlord_up'),\n 'landlord_down': self._get_reward_bidding('landlord_down')}}\n obs = None\n else:\n obs = get_obs(self.infoset)\n return obs, reward, done, {}\n\n def _get_reward(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n self_bomb_num = self._env.pos_bomb_num[pos]\n if winner == 'landlord':\n if self.objective == 'adp':\n return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num\n + self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (1.0 - self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[\n pos] / 4\n else:\n return 1.0 - self._env.step_count * 0.0033\n elif self.objective == 'adp':\n return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +\n self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (-1.0 + self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[pos\n ] / 4\n else:\n return -1.0 + self._env.step_count * 0.0033\n\n def _get_reward_bidding(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n if winner == 'landlord':\n return 1.0 * 2 ** (self._env.bid_count - 1) / 8\n else:\n return -1.0 * 2 ** (self._env.bid_count - 1) / 8\n\n @property\n def _game_infoset(self):\n \"\"\"\n Here, inforset is defined as all the information\n in the current situation, incuding the hand cards\n of all the players, all the historical moves, etc.\n That is, it contains perferfect infomation. Later,\n we will use functions to extract the observable\n information from the views of the three players.\n \"\"\"\n return self._env.game_infoset\n\n @property\n def _game_bomb_num(self):\n \"\"\"\n The number of bombs played so far. This is used as\n a feature of the neural network and is also used to\n calculate ADP.\n \"\"\"\n return self._env.get_bomb_num()\n\n @property\n def _game_winner(self):\n \"\"\" A string of landlord/peasants\n \"\"\"\n return self._env.get_winner()\n\n @property\n def _acting_player_position(self):\n \"\"\"\n The player that is active. It can be landlord,\n landlod_down, or landlord_up.\n \"\"\"\n return self._env.acting_player_position\n\n @property\n def _game_over(self):\n \"\"\" Returns a Boolean\n \"\"\"\n return self._env.game_over\n\n\nclass DummyAgent(object):\n \"\"\"\n Dummy agent is designed to easily interact with the\n game engine. The agent will first be told what action\n to perform. Then the environment will call this agent\n to perform the actual action. This can help us to\n isolate environment and agents towards a gym like\n interface.\n \"\"\"\n\n def __init__(self, position):\n self.position = position\n self.action = None\n\n def act(self, infoset):\n \"\"\"\n Simply return the action that is set previously.\n \"\"\"\n assert self.action in infoset.legal_actions\n return self.action\n\n def set_action(self, action):\n \"\"\"\n The environment uses this function to tell\n the dummy agent what to do.\n \"\"\"\n self.action = action\n\n\ndef get_obs(infoset, use_general=True):\n \"\"\"\n This function obtains observations with imperfect information\n from the infoset. It has three branches since we encode\n different features for different positions.\n\n This function will return dictionary named `obs`. It contains\n several fields. These fields will be used to train the model.\n One can play with those features to improve the performance.\n\n `position` is a string that can be landlord/landlord_down/landlord_up\n\n `x_batch` is a batch of features (excluding the hisorical moves).\n It also encodes the action feature\n\n `z_batch` is a batch of features with hisorical moves only.\n\n `legal_actions` is the legal moves\n\n `x_no_action`: the features (exluding the hitorical moves and\n the action features). It does not have the batch dim.\n\n `z`: same as z_batch but not a batch.\n \"\"\"\n if use_general:\n if infoset.player_position not in ['landlord', 'landlord_up',\n 'landlord_down']:\n raise ValueError('')\n return _get_obs_general(infoset, infoset.player_position)\n elif infoset.player_position == 'landlord':\n return _get_obs_landlord(infoset)\n elif infoset.player_position == 'landlord_up':\n return _get_obs_landlord_up(infoset)\n elif infoset.player_position == 'landlord_down':\n return _get_obs_landlord_down(infoset)\n else:\n raise ValueError('')\n\n\n<mask token>\n\n\ndef _cards2array(list_cards):\n \"\"\"\n A utility function that transforms the actions, i.e.,\n A list of integers into card matrix. Here we remove\n the six entries that are always zero and flatten the\n the representations.\n \"\"\"\n if len(list_cards) == 0:\n return np.zeros(54, dtype=np.int8)\n matrix = np.zeros([4, 13], dtype=np.int8)\n jokers = np.zeros(2, dtype=np.int8)\n counter = Counter(list_cards)\n for card, num_times in counter.items():\n if card < 20:\n matrix[:, Card2Column[card]] = NumOnes2Array[num_times]\n elif card == 20:\n jokers[0] = 1\n elif card == 30:\n jokers[1] = 1\n return np.concatenate((matrix.flatten('F'), jokers))\n\n\n<mask token>\n\n\ndef _process_action_seq(sequence, length=15, new_model=True):\n \"\"\"\n A utility function encoding historical moves. We\n encode 15 moves. If there is no 15 moves, we pad\n with zeros.\n \"\"\"\n sequence = sequence[-length:].copy()\n if new_model:\n sequence = sequence[::-1]\n if len(sequence) < length:\n empty_sequence = [[] for _ in range(length - len(sequence))]\n empty_sequence.extend(sequence)\n sequence = empty_sequence\n return sequence\n\n\ndef _get_one_hot_bomb(bomb_num):\n \"\"\"\n A utility function to encode the number of bombs\n into one-hot representation.\n \"\"\"\n one_hot = np.zeros(15)\n one_hot[bomb_num] = 1\n return one_hot\n\n\n<mask token>\n\n\ndef _get_obs_landlord_up(infoset):\n \"\"\"\n Obttain the landlord_up features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_down']\n )\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_down'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_up', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_down(infoset):\n \"\"\"\n Obttain the landlord_down features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_up'])\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_up'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_down', 'x_batch': x_batch.astype(np.\n float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions':\n infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8)}\n return obs\n\n\n<mask token>\n\n\ndef _get_obs_general(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n other_handcards_left_list = []\n for pos in ['landlord', 'landlord_up', 'landlord_up']:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n num_cards_left = np.hstack((landlord_num_cards_left,\n landlord_up_num_cards_left, landlord_down_num_cards_left))\n x_batch = np.hstack((bid_info_batch, multiply_info_batch))\n x_no_action = np.hstack((bid_info, multiply_info))\n z = np.vstack((num_cards_left, my_handcards, other_handcards,\n three_landlord_cards, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 32))))\n _z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n my_action_batch = my_action_batch[:, np.newaxis, :]\n z_batch = np.zeros([len(_z_batch), 40, 54], int)\n for i in range(0, len(_z_batch)):\n z_batch[i] = np.vstack((my_action_batch[i], _z_batch[i]))\n obs = {'position': position, 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Env:\n \"\"\"\n Doudizhu multi-agent wrapper\n \"\"\"\n\n def __init__(self, objective):\n \"\"\"\n Objective is wp/adp/logadp. It indicates whether considers\n bomb in reward calculation. Here, we use dummy agents.\n This is because, in the orignial game, the players\n are `in` the game. Here, we want to isolate\n players and environments to have a more gym style\n interface. To achieve this, we use dummy players\n to play. For each move, we tell the corresponding\n dummy player which action to play, then the player\n will perform the actual action in the game engine.\n \"\"\"\n self.objective = objective\n self.players = {}\n for position in ['landlord', 'landlord_up', 'landlord_down']:\n self.players[position] = DummyAgent(position)\n self._env = GameEnv(self.players)\n self.total_round = 0\n self.force_bid = 0\n self.infoset = None\n\n def reset(self, model, device, flags=None):\n \"\"\"\n Every time reset is called, the environment\n will be re-initialized with a new deck of cards.\n This function is usually called when a game is over.\n \"\"\"\n self._env.reset()\n if model is None:\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = {'landlord': _deck[:20], 'landlord_up': _deck[\n 20:37], 'landlord_down': _deck[37:54],\n 'three_landlord_cards': _deck[17:20]}\n for key in card_play_data:\n card_play_data[key].sort()\n self._env.card_play_init(card_play_data)\n self.infoset = self._game_infoset\n return get_obs(self.infoset)\n else:\n self.total_round += 1\n bid_done = False\n card_play_data = []\n landlord_cards = []\n last_bid = 0\n bid_count = 0\n player_ids = {}\n bid_info = None\n bid_obs_buffer = []\n multiply_obs_buffer = []\n bid_limit = 3\n force_bid = False\n while not bid_done:\n bid_limit -= 1\n bid_obs_buffer.clear()\n multiply_obs_buffer.clear()\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = [_deck[:17], _deck[17:34], _deck[34:51]]\n for i in range(3):\n card_play_data[i].sort()\n landlord_cards = _deck[51:54]\n landlord_cards.sort()\n bid_info = np.array([[-1, -1, -1], [-1, -1, -1], [-1, -1, -\n 1], [-1, -1, -1]])\n bidding_player = random.randint(0, 2)\n first_bid = -1\n last_bid = -1\n bid_count = 0\n if bid_limit <= 0:\n force_bid = True\n for r in range(3):\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n if bid_limit <= 0:\n wr = BidModel.predict_env(card_play_data[\n bidding_player])\n if wr >= 0.7:\n action = {'action': 1}\n bid_limit += 1\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n if first_bid == -1:\n first_bid = bidding_player\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n else:\n bid_info[r] = [0, 0, 0]\n bidding_player = (bidding_player + 1) % 3\n one_count = np.count_nonzero(bid_info == 1)\n if one_count == 0:\n continue\n elif one_count > 1:\n r = 3\n bidding_player = first_bid\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n break\n card_play_data[last_bid].extend(landlord_cards)\n card_play_data = {'landlord': card_play_data[last_bid],\n 'landlord_up': card_play_data[(last_bid - 1) % 3],\n 'landlord_down': card_play_data[(last_bid + 1) % 3],\n 'three_landlord_cards': landlord_cards}\n card_play_data['landlord'].sort()\n player_ids = {'landlord': last_bid, 'landlord_up': (last_bid - \n 1) % 3, 'landlord_down': (last_bid + 1) % 3}\n player_positions = {last_bid: 'landlord', ((last_bid - 1) % 3):\n 'landlord_up', ((last_bid + 1) % 3): 'landlord_down'}\n for bid_obs in bid_obs_buffer:\n bid_obs.update({'position': player_positions[bid_obs['pid']]})\n self._env.card_play_init(card_play_data)\n multiply_map = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.\n array([0, 0, 1])]\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n pid = player_ids[pos]\n self._env.info_sets[pos].player_id = pid\n self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) %\n 3, pid, (pid + 1) % 3]]\n self._env.bid_count = bid_count\n action = {'action': 0}\n self._env.info_sets[pos].multiply_info = multiply_map[action\n ['action']]\n self._env.multiply_count[pos] = action['action']\n self.infoset = self._game_infoset\n if force_bid:\n self.force_bid += 1\n if self.total_round % 100 == 0:\n print('发牌情况: %i/%i %.1f%%' % (self.force_bid, self.\n total_round, self.force_bid / self.total_round * 100))\n self.force_bid = 0\n self.total_round = 0\n return get_obs(self.infoset), {'bid_obs_buffer': bid_obs_buffer,\n 'multiply_obs_buffer': multiply_obs_buffer}\n\n def step(self, action):\n \"\"\"\n Step function takes as input the action, which\n is a list of integers, and output the next obervation,\n reward, and a Boolean variable indicating whether the\n current game is finished. It also returns an empty\n dictionary that is reserved to pass useful information.\n \"\"\"\n assert action in self.infoset.legal_actions\n self.players[self._acting_player_position].set_action(action)\n self._env.step()\n self.infoset = self._game_infoset\n done = False\n reward = 0.0\n if self._game_over:\n done = True\n reward = {'play': {'landlord': self._get_reward('landlord'),\n 'landlord_up': self._get_reward('landlord_up'),\n 'landlord_down': self._get_reward('landlord_down')}, 'bid':\n {'landlord': self._get_reward_bidding('landlord') * 2,\n 'landlord_up': self._get_reward_bidding('landlord_up'),\n 'landlord_down': self._get_reward_bidding('landlord_down')}}\n obs = None\n else:\n obs = get_obs(self.infoset)\n return obs, reward, done, {}\n\n def _get_reward(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n self_bomb_num = self._env.pos_bomb_num[pos]\n if winner == 'landlord':\n if self.objective == 'adp':\n return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num\n + self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (1.0 - self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[\n pos] / 4\n else:\n return 1.0 - self._env.step_count * 0.0033\n elif self.objective == 'adp':\n return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +\n self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (-1.0 + self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[pos\n ] / 4\n else:\n return -1.0 + self._env.step_count * 0.0033\n\n def _get_reward_bidding(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n if winner == 'landlord':\n return 1.0 * 2 ** (self._env.bid_count - 1) / 8\n else:\n return -1.0 * 2 ** (self._env.bid_count - 1) / 8\n\n @property\n def _game_infoset(self):\n \"\"\"\n Here, inforset is defined as all the information\n in the current situation, incuding the hand cards\n of all the players, all the historical moves, etc.\n That is, it contains perferfect infomation. Later,\n we will use functions to extract the observable\n information from the views of the three players.\n \"\"\"\n return self._env.game_infoset\n\n @property\n def _game_bomb_num(self):\n \"\"\"\n The number of bombs played so far. This is used as\n a feature of the neural network and is also used to\n calculate ADP.\n \"\"\"\n return self._env.get_bomb_num()\n\n @property\n def _game_winner(self):\n \"\"\" A string of landlord/peasants\n \"\"\"\n return self._env.get_winner()\n\n @property\n def _acting_player_position(self):\n \"\"\"\n The player that is active. It can be landlord,\n landlod_down, or landlord_up.\n \"\"\"\n return self._env.acting_player_position\n\n @property\n def _game_over(self):\n \"\"\" Returns a Boolean\n \"\"\"\n return self._env.game_over\n\n\nclass DummyAgent(object):\n \"\"\"\n Dummy agent is designed to easily interact with the\n game engine. The agent will first be told what action\n to perform. Then the environment will call this agent\n to perform the actual action. This can help us to\n isolate environment and agents towards a gym like\n interface.\n \"\"\"\n\n def __init__(self, position):\n self.position = position\n self.action = None\n\n def act(self, infoset):\n \"\"\"\n Simply return the action that is set previously.\n \"\"\"\n assert self.action in infoset.legal_actions\n return self.action\n\n def set_action(self, action):\n \"\"\"\n The environment uses this function to tell\n the dummy agent what to do.\n \"\"\"\n self.action = action\n\n\ndef get_obs(infoset, use_general=True):\n \"\"\"\n This function obtains observations with imperfect information\n from the infoset. It has three branches since we encode\n different features for different positions.\n\n This function will return dictionary named `obs`. It contains\n several fields. These fields will be used to train the model.\n One can play with those features to improve the performance.\n\n `position` is a string that can be landlord/landlord_down/landlord_up\n\n `x_batch` is a batch of features (excluding the hisorical moves).\n It also encodes the action feature\n\n `z_batch` is a batch of features with hisorical moves only.\n\n `legal_actions` is the legal moves\n\n `x_no_action`: the features (exluding the hitorical moves and\n the action features). It does not have the batch dim.\n\n `z`: same as z_batch but not a batch.\n \"\"\"\n if use_general:\n if infoset.player_position not in ['landlord', 'landlord_up',\n 'landlord_down']:\n raise ValueError('')\n return _get_obs_general(infoset, infoset.player_position)\n elif infoset.player_position == 'landlord':\n return _get_obs_landlord(infoset)\n elif infoset.player_position == 'landlord_up':\n return _get_obs_landlord_up(infoset)\n elif infoset.player_position == 'landlord_down':\n return _get_obs_landlord_down(infoset)\n else:\n raise ValueError('')\n\n\ndef _get_one_hot_array(num_left_cards, max_num_cards):\n \"\"\"\n A utility function to obtain one-hot endoding\n \"\"\"\n one_hot = np.zeros(max_num_cards)\n if num_left_cards > 0:\n one_hot[num_left_cards - 1] = 1\n return one_hot\n\n\ndef _cards2array(list_cards):\n \"\"\"\n A utility function that transforms the actions, i.e.,\n A list of integers into card matrix. Here we remove\n the six entries that are always zero and flatten the\n the representations.\n \"\"\"\n if len(list_cards) == 0:\n return np.zeros(54, dtype=np.int8)\n matrix = np.zeros([4, 13], dtype=np.int8)\n jokers = np.zeros(2, dtype=np.int8)\n counter = Counter(list_cards)\n for card, num_times in counter.items():\n if card < 20:\n matrix[:, Card2Column[card]] = NumOnes2Array[num_times]\n elif card == 20:\n jokers[0] = 1\n elif card == 30:\n jokers[1] = 1\n return np.concatenate((matrix.flatten('F'), jokers))\n\n\n<mask token>\n\n\ndef _process_action_seq(sequence, length=15, new_model=True):\n \"\"\"\n A utility function encoding historical moves. We\n encode 15 moves. If there is no 15 moves, we pad\n with zeros.\n \"\"\"\n sequence = sequence[-length:].copy()\n if new_model:\n sequence = sequence[::-1]\n if len(sequence) < length:\n empty_sequence = [[] for _ in range(length - len(sequence))]\n empty_sequence.extend(sequence)\n sequence = empty_sequence\n return sequence\n\n\ndef _get_one_hot_bomb(bomb_num):\n \"\"\"\n A utility function to encode the number of bombs\n into one-hot representation.\n \"\"\"\n one_hot = np.zeros(15)\n one_hot[bomb_num] = 1\n return one_hot\n\n\ndef _get_obs_landlord(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n last_action_batch, landlord_up_played_cards_batch,\n landlord_down_played_cards_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards, last_action,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_up(infoset):\n \"\"\"\n Obttain the landlord_up features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_down']\n )\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_down'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_up', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_down(infoset):\n \"\"\"\n Obttain the landlord_down features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_up'])\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_up'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_down', 'x_batch': x_batch.astype(np.\n float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions':\n infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_withbid(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n last_action_batch, landlord_up_played_cards_batch,\n landlord_down_played_cards_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards, last_action,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_general1(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n other_handcards_left_list = []\n for pos in ['landlord', 'landlord_up', 'landlord_up']:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num, bid_info, multiply_info))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': position, 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_general(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n other_handcards_left_list = []\n for pos in ['landlord', 'landlord_up', 'landlord_up']:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n num_cards_left = np.hstack((landlord_num_cards_left,\n landlord_up_num_cards_left, landlord_down_num_cards_left))\n x_batch = np.hstack((bid_info_batch, multiply_info_batch))\n x_no_action = np.hstack((bid_info, multiply_info))\n z = np.vstack((num_cards_left, my_handcards, other_handcards,\n three_landlord_cards, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 32))))\n _z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n my_action_batch = my_action_batch[:, np.newaxis, :]\n z_batch = np.zeros([len(_z_batch), 40, 54], int)\n for i in range(0, len(_z_batch)):\n z_batch[i] = np.vstack((my_action_batch[i], _z_batch[i]))\n obs = {'position': position, 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef gen_bid_legal_actions(player_id, bid_info):\n self_bid_info = bid_info[:, [(player_id - 1) % 3, player_id, (player_id +\n 1) % 3]]\n curr_round = -1\n for r in range(4):\n if -1 in self_bid_info[r]:\n curr_round = r\n break\n bid_actions = []\n if curr_round != -1:\n self_bid_info[curr_round] = [0, 0, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n self_bid_info[curr_round] = [0, 1, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n return np.array(bid_actions)\n\n\ndef _get_obs_for_bid_legacy(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_info = np.array([0, 0, 0])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = bid_legal_actions\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array([])\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(2):\n my_action_batch[j, :] = _cards2array([])\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n z_batch.astype(np.float32), 'legal_actions': bid_legal_actions,\n 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8),\n 'bid_info_batch': bid_info_batch.astype(np.int8), 'multiply_info':\n multiply_info.astype(np.int8)}\n return obs\n\n\ndef _get_obs_for_bid(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = np.hstack([bid_legal_actions for _ in range(5)])\n x_batch = np.hstack((my_handcards_batch, bid_info_batch))\n x_no_action = np.hstack(my_handcards)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n np.array([0, 0]), 'legal_actions': bid_legal_actions, 'x_no_action':\n x_no_action.astype(np.int8), 'bid_info_batch': bid_info_batch.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_for_multiply(position, bid_info, hand_cards, landlord_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 3\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n three_landlord_cards = _cards2array(landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(num_legal_actions):\n my_action_batch[j, :] = _cards2array([])\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n z_batch.astype(np.float32), 'legal_actions': multiply_info_batch,\n 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8),\n 'bid_info': bid_info.astype(np.int8), 'multiply_info_batch':\n multiply_info.astype(np.int8)}\n return obs\n", "step-4": "from collections import Counter\nimport numpy as np\nimport random\nimport torch\nimport BidModel\nfrom douzero.env.game import GameEnv\nenv_version = '3.2'\nenv_url = 'http://od.vcccz.com/hechuan/env.py'\nCard2Column = {(3): 0, (4): 1, (5): 2, (6): 3, (7): 4, (8): 5, (9): 6, (10):\n 7, (11): 8, (12): 9, (13): 10, (14): 11, (17): 12}\nNumOnes2Array = {(0): np.array([0, 0, 0, 0]), (1): np.array([1, 0, 0, 0]),\n (2): np.array([1, 1, 0, 0]), (3): np.array([1, 1, 1, 0]), (4): np.array\n ([1, 1, 1, 1])}\ndeck = []\nfor i in range(3, 15):\n deck.extend([i for _ in range(4)])\ndeck.extend([(17) for _ in range(4)])\ndeck.extend([20, 30])\n\n\nclass Env:\n \"\"\"\n Doudizhu multi-agent wrapper\n \"\"\"\n\n def __init__(self, objective):\n \"\"\"\n Objective is wp/adp/logadp. It indicates whether considers\n bomb in reward calculation. Here, we use dummy agents.\n This is because, in the orignial game, the players\n are `in` the game. Here, we want to isolate\n players and environments to have a more gym style\n interface. To achieve this, we use dummy players\n to play. For each move, we tell the corresponding\n dummy player which action to play, then the player\n will perform the actual action in the game engine.\n \"\"\"\n self.objective = objective\n self.players = {}\n for position in ['landlord', 'landlord_up', 'landlord_down']:\n self.players[position] = DummyAgent(position)\n self._env = GameEnv(self.players)\n self.total_round = 0\n self.force_bid = 0\n self.infoset = None\n\n def reset(self, model, device, flags=None):\n \"\"\"\n Every time reset is called, the environment\n will be re-initialized with a new deck of cards.\n This function is usually called when a game is over.\n \"\"\"\n self._env.reset()\n if model is None:\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = {'landlord': _deck[:20], 'landlord_up': _deck[\n 20:37], 'landlord_down': _deck[37:54],\n 'three_landlord_cards': _deck[17:20]}\n for key in card_play_data:\n card_play_data[key].sort()\n self._env.card_play_init(card_play_data)\n self.infoset = self._game_infoset\n return get_obs(self.infoset)\n else:\n self.total_round += 1\n bid_done = False\n card_play_data = []\n landlord_cards = []\n last_bid = 0\n bid_count = 0\n player_ids = {}\n bid_info = None\n bid_obs_buffer = []\n multiply_obs_buffer = []\n bid_limit = 3\n force_bid = False\n while not bid_done:\n bid_limit -= 1\n bid_obs_buffer.clear()\n multiply_obs_buffer.clear()\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = [_deck[:17], _deck[17:34], _deck[34:51]]\n for i in range(3):\n card_play_data[i].sort()\n landlord_cards = _deck[51:54]\n landlord_cards.sort()\n bid_info = np.array([[-1, -1, -1], [-1, -1, -1], [-1, -1, -\n 1], [-1, -1, -1]])\n bidding_player = random.randint(0, 2)\n first_bid = -1\n last_bid = -1\n bid_count = 0\n if bid_limit <= 0:\n force_bid = True\n for r in range(3):\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n if bid_limit <= 0:\n wr = BidModel.predict_env(card_play_data[\n bidding_player])\n if wr >= 0.7:\n action = {'action': 1}\n bid_limit += 1\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n if first_bid == -1:\n first_bid = bidding_player\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n else:\n bid_info[r] = [0, 0, 0]\n bidding_player = (bidding_player + 1) % 3\n one_count = np.count_nonzero(bid_info == 1)\n if one_count == 0:\n continue\n elif one_count > 1:\n r = 3\n bidding_player = first_bid\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info,\n card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward('bidding', torch.tensor(\n bidding_obs['z_batch'], device=device), torch.\n tensor(bidding_obs['x_batch'], device=device),\n flags=flags)\n bid_obs_buffer.append({'x_batch': bidding_obs['x_batch'\n ][action['action']], 'z_batch': bidding_obs[\n 'z_batch'][action['action']], 'pid': bidding_player})\n if action['action'] == 1:\n last_bid = bidding_player\n bid_count += 1\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n break\n card_play_data[last_bid].extend(landlord_cards)\n card_play_data = {'landlord': card_play_data[last_bid],\n 'landlord_up': card_play_data[(last_bid - 1) % 3],\n 'landlord_down': card_play_data[(last_bid + 1) % 3],\n 'three_landlord_cards': landlord_cards}\n card_play_data['landlord'].sort()\n player_ids = {'landlord': last_bid, 'landlord_up': (last_bid - \n 1) % 3, 'landlord_down': (last_bid + 1) % 3}\n player_positions = {last_bid: 'landlord', ((last_bid - 1) % 3):\n 'landlord_up', ((last_bid + 1) % 3): 'landlord_down'}\n for bid_obs in bid_obs_buffer:\n bid_obs.update({'position': player_positions[bid_obs['pid']]})\n self._env.card_play_init(card_play_data)\n multiply_map = [np.array([1, 0, 0]), np.array([0, 1, 0]), np.\n array([0, 0, 1])]\n for pos in ['landlord', 'landlord_up', 'landlord_down']:\n pid = player_ids[pos]\n self._env.info_sets[pos].player_id = pid\n self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) %\n 3, pid, (pid + 1) % 3]]\n self._env.bid_count = bid_count\n action = {'action': 0}\n self._env.info_sets[pos].multiply_info = multiply_map[action\n ['action']]\n self._env.multiply_count[pos] = action['action']\n self.infoset = self._game_infoset\n if force_bid:\n self.force_bid += 1\n if self.total_round % 100 == 0:\n print('发牌情况: %i/%i %.1f%%' % (self.force_bid, self.\n total_round, self.force_bid / self.total_round * 100))\n self.force_bid = 0\n self.total_round = 0\n return get_obs(self.infoset), {'bid_obs_buffer': bid_obs_buffer,\n 'multiply_obs_buffer': multiply_obs_buffer}\n\n def step(self, action):\n \"\"\"\n Step function takes as input the action, which\n is a list of integers, and output the next obervation,\n reward, and a Boolean variable indicating whether the\n current game is finished. It also returns an empty\n dictionary that is reserved to pass useful information.\n \"\"\"\n assert action in self.infoset.legal_actions\n self.players[self._acting_player_position].set_action(action)\n self._env.step()\n self.infoset = self._game_infoset\n done = False\n reward = 0.0\n if self._game_over:\n done = True\n reward = {'play': {'landlord': self._get_reward('landlord'),\n 'landlord_up': self._get_reward('landlord_up'),\n 'landlord_down': self._get_reward('landlord_down')}, 'bid':\n {'landlord': self._get_reward_bidding('landlord') * 2,\n 'landlord_up': self._get_reward_bidding('landlord_up'),\n 'landlord_down': self._get_reward_bidding('landlord_down')}}\n obs = None\n else:\n obs = get_obs(self.infoset)\n return obs, reward, done, {}\n\n def _get_reward(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n self_bomb_num = self._env.pos_bomb_num[pos]\n if winner == 'landlord':\n if self.objective == 'adp':\n return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num\n + self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (1.0 - self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[\n pos] / 4\n else:\n return 1.0 - self._env.step_count * 0.0033\n elif self.objective == 'adp':\n return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +\n self._env.multiply_count[pos]) / 8\n elif self.objective == 'logadp':\n return (-1.0 + self._env.step_count * 0.0033\n ) * 1.3 ** self_bomb_num * 2 ** self._env.multiply_count[pos\n ] / 4\n else:\n return -1.0 + self._env.step_count * 0.0033\n\n def _get_reward_bidding(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n if winner == 'landlord':\n return 1.0 * 2 ** (self._env.bid_count - 1) / 8\n else:\n return -1.0 * 2 ** (self._env.bid_count - 1) / 8\n\n @property\n def _game_infoset(self):\n \"\"\"\n Here, inforset is defined as all the information\n in the current situation, incuding the hand cards\n of all the players, all the historical moves, etc.\n That is, it contains perferfect infomation. Later,\n we will use functions to extract the observable\n information from the views of the three players.\n \"\"\"\n return self._env.game_infoset\n\n @property\n def _game_bomb_num(self):\n \"\"\"\n The number of bombs played so far. This is used as\n a feature of the neural network and is also used to\n calculate ADP.\n \"\"\"\n return self._env.get_bomb_num()\n\n @property\n def _game_winner(self):\n \"\"\" A string of landlord/peasants\n \"\"\"\n return self._env.get_winner()\n\n @property\n def _acting_player_position(self):\n \"\"\"\n The player that is active. It can be landlord,\n landlod_down, or landlord_up.\n \"\"\"\n return self._env.acting_player_position\n\n @property\n def _game_over(self):\n \"\"\" Returns a Boolean\n \"\"\"\n return self._env.game_over\n\n\nclass DummyAgent(object):\n \"\"\"\n Dummy agent is designed to easily interact with the\n game engine. The agent will first be told what action\n to perform. Then the environment will call this agent\n to perform the actual action. This can help us to\n isolate environment and agents towards a gym like\n interface.\n \"\"\"\n\n def __init__(self, position):\n self.position = position\n self.action = None\n\n def act(self, infoset):\n \"\"\"\n Simply return the action that is set previously.\n \"\"\"\n assert self.action in infoset.legal_actions\n return self.action\n\n def set_action(self, action):\n \"\"\"\n The environment uses this function to tell\n the dummy agent what to do.\n \"\"\"\n self.action = action\n\n\ndef get_obs(infoset, use_general=True):\n \"\"\"\n This function obtains observations with imperfect information\n from the infoset. It has three branches since we encode\n different features for different positions.\n\n This function will return dictionary named `obs`. It contains\n several fields. These fields will be used to train the model.\n One can play with those features to improve the performance.\n\n `position` is a string that can be landlord/landlord_down/landlord_up\n\n `x_batch` is a batch of features (excluding the hisorical moves).\n It also encodes the action feature\n\n `z_batch` is a batch of features with hisorical moves only.\n\n `legal_actions` is the legal moves\n\n `x_no_action`: the features (exluding the hitorical moves and\n the action features). It does not have the batch dim.\n\n `z`: same as z_batch but not a batch.\n \"\"\"\n if use_general:\n if infoset.player_position not in ['landlord', 'landlord_up',\n 'landlord_down']:\n raise ValueError('')\n return _get_obs_general(infoset, infoset.player_position)\n elif infoset.player_position == 'landlord':\n return _get_obs_landlord(infoset)\n elif infoset.player_position == 'landlord_up':\n return _get_obs_landlord_up(infoset)\n elif infoset.player_position == 'landlord_down':\n return _get_obs_landlord_down(infoset)\n else:\n raise ValueError('')\n\n\ndef _get_one_hot_array(num_left_cards, max_num_cards):\n \"\"\"\n A utility function to obtain one-hot endoding\n \"\"\"\n one_hot = np.zeros(max_num_cards)\n if num_left_cards > 0:\n one_hot[num_left_cards - 1] = 1\n return one_hot\n\n\ndef _cards2array(list_cards):\n \"\"\"\n A utility function that transforms the actions, i.e.,\n A list of integers into card matrix. Here we remove\n the six entries that are always zero and flatten the\n the representations.\n \"\"\"\n if len(list_cards) == 0:\n return np.zeros(54, dtype=np.int8)\n matrix = np.zeros([4, 13], dtype=np.int8)\n jokers = np.zeros(2, dtype=np.int8)\n counter = Counter(list_cards)\n for card, num_times in counter.items():\n if card < 20:\n matrix[:, Card2Column[card]] = NumOnes2Array[num_times]\n elif card == 20:\n jokers[0] = 1\n elif card == 30:\n jokers[1] = 1\n return np.concatenate((matrix.flatten('F'), jokers))\n\n\ndef _action_seq_list2array(action_seq_list, new_model=True):\n \"\"\"\n A utility function to encode the historical moves.\n We encode the historical 15 actions. If there is\n no 15 actions, we pad the features with 0. Since\n three moves is a round in DouDizhu, we concatenate\n the representations for each consecutive three moves.\n Finally, we obtain a 5x162 matrix, which will be fed\n into LSTM for encoding.\n \"\"\"\n if new_model:\n position_map = {'landlord': 0, 'landlord_up': 1, 'landlord_down': 2}\n action_seq_array = np.ones((len(action_seq_list), 54)) * -1\n for row, list_cards in enumerate(action_seq_list):\n if list_cards != []:\n action_seq_array[row, :54] = _cards2array(list_cards[1])\n else:\n action_seq_array = np.zeros((len(action_seq_list), 54))\n for row, list_cards in enumerate(action_seq_list):\n if list_cards != []:\n action_seq_array[row, :] = _cards2array(list_cards[1])\n action_seq_array = action_seq_array.reshape(5, 162)\n return action_seq_array\n\n\ndef _process_action_seq(sequence, length=15, new_model=True):\n \"\"\"\n A utility function encoding historical moves. We\n encode 15 moves. If there is no 15 moves, we pad\n with zeros.\n \"\"\"\n sequence = sequence[-length:].copy()\n if new_model:\n sequence = sequence[::-1]\n if len(sequence) < length:\n empty_sequence = [[] for _ in range(length - len(sequence))]\n empty_sequence.extend(sequence)\n sequence = empty_sequence\n return sequence\n\n\ndef _get_one_hot_bomb(bomb_num):\n \"\"\"\n A utility function to encode the number of bombs\n into one-hot representation.\n \"\"\"\n one_hot = np.zeros(15)\n one_hot[bomb_num] = 1\n return one_hot\n\n\ndef _get_obs_landlord(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n last_action_batch, landlord_up_played_cards_batch,\n landlord_down_played_cards_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards, last_action,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_up(infoset):\n \"\"\"\n Obttain the landlord_up features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_down']\n )\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_down'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_up', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_down(infoset):\n \"\"\"\n Obttain the landlord_down features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n last_landlord_action = _cards2array(infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(last_landlord_action[np.newaxis,\n :], num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n last_teammate_action = _cards2array(infoset.last_move_dict['landlord_up'])\n last_teammate_action_batch = np.repeat(last_teammate_action[np.newaxis,\n :], num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n teammate_num_cards_left_batch = np.repeat(teammate_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n teammate_played_cards = _cards2array(infoset.played_cards['landlord_up'])\n teammate_played_cards_batch = np.repeat(teammate_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n landlord_played_cards_batch, teammate_played_cards_batch,\n last_action_batch, last_landlord_action_batch,\n last_teammate_action_batch, landlord_num_cards_left_batch,\n teammate_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards,\n landlord_played_cards, teammate_played_cards, last_action,\n last_landlord_action, last_teammate_action, landlord_num_cards_left,\n teammate_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord_down', 'x_batch': x_batch.astype(np.\n float32), 'z_batch': z_batch.astype(np.float32), 'legal_actions':\n infoset.legal_actions, 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8)}\n return obs\n\n\ndef _get_obs_landlord_withbid(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((my_handcards_batch, other_handcards_batch,\n last_action_batch, landlord_up_played_cards_batch,\n landlord_down_played_cards_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, my_action_batch))\n x_no_action = np.hstack((my_handcards, other_handcards, last_action,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_up_num_cards_left, landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 15, False), False)\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': 'landlord', 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_general1(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n other_handcards_left_list = []\n for pos in ['landlord', 'landlord_up', 'landlord_up']:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num, bid_info, multiply_info))\n z = _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': position, 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_general(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n landlord_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(infoset.\n num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n other_handcards_left_list = []\n for pos in ['landlord', 'landlord_up', 'landlord_up']:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n landlord_played_cards = _cards2array(infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array(infoset.played_cards['landlord_up']\n )\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array(infoset.played_cards[\n 'landlord_down'])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(infoset.bomb_num)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n num_cards_left = np.hstack((landlord_num_cards_left,\n landlord_up_num_cards_left, landlord_down_num_cards_left))\n x_batch = np.hstack((bid_info_batch, multiply_info_batch))\n x_no_action = np.hstack((bid_info, multiply_info))\n z = np.vstack((num_cards_left, my_handcards, other_handcards,\n three_landlord_cards, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n _action_seq_list2array(_process_action_seq(infoset.\n card_play_action_seq, 32))))\n _z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n my_action_batch = my_action_batch[:, np.newaxis, :]\n z_batch = np.zeros([len(_z_batch), 40, 54], int)\n for i in range(0, len(_z_batch)):\n z_batch[i] = np.vstack((my_action_batch[i], _z_batch[i]))\n obs = {'position': position, 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32), 'legal_actions': infoset.\n legal_actions, 'x_no_action': x_no_action.astype(np.int8), 'z': z.\n astype(np.int8)}\n return obs\n\n\ndef gen_bid_legal_actions(player_id, bid_info):\n self_bid_info = bid_info[:, [(player_id - 1) % 3, player_id, (player_id +\n 1) % 3]]\n curr_round = -1\n for r in range(4):\n if -1 in self_bid_info[r]:\n curr_round = r\n break\n bid_actions = []\n if curr_round != -1:\n self_bid_info[curr_round] = [0, 0, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n self_bid_info[curr_round] = [0, 1, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n return np.array(bid_actions)\n\n\ndef _get_obs_for_bid_legacy(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_info = np.array([0, 0, 0])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = bid_legal_actions\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n three_landlord_cards = _cards2array([])\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(2):\n my_action_batch[j, :] = _cards2array([])\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n z_batch.astype(np.float32), 'legal_actions': bid_legal_actions,\n 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8),\n 'bid_info_batch': bid_info_batch.astype(np.int8), 'multiply_info':\n multiply_info.astype(np.int8)}\n return obs\n\n\ndef _get_obs_for_bid(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = np.hstack([bid_legal_actions for _ in range(5)])\n x_batch = np.hstack((my_handcards_batch, bid_info_batch))\n x_no_action = np.hstack(my_handcards)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n np.array([0, 0]), 'legal_actions': bid_legal_actions, 'x_no_action':\n x_no_action.astype(np.int8), 'bid_info_batch': bid_info_batch.\n astype(np.int8)}\n return obs\n\n\ndef _get_obs_for_multiply(position, bid_info, hand_cards, landlord_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12,\n 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 3\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n position_map = {'landlord': [1, 0, 0], 'landlord_up': [0, 1, 0],\n 'landlord_down': [0, 0, 1]}\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n bid_info = np.array(bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :], num_legal_actions,\n axis=0)\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n three_landlord_cards = _cards2array(landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis,\n :], num_legal_actions, axis=0)\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(num_legal_actions):\n my_action_batch[j, :] = _cards2array([])\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(landlord_num_cards_left[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(landlord_up_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(landlord_down_num_cards_left\n [np.newaxis, :], num_legal_actions, axis=0)\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(landlord_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(landlord_up_played_cards[np.\n newaxis, :], num_legal_actions, axis=0)\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(landlord_down_played_cards\n [np.newaxis, :], num_legal_actions, axis=0)\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(bomb_num[np.newaxis, :], num_legal_actions,\n axis=0)\n x_batch = np.hstack((position_info_batch, my_handcards_batch,\n other_handcards_batch, three_landlord_cards_batch,\n last_action_batch, landlord_played_cards_batch,\n landlord_up_played_cards_batch, landlord_down_played_cards_batch,\n landlord_num_cards_left_batch, landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch, bomb_num_batch, bid_info_batch,\n multiply_info_batch, my_action_batch))\n x_no_action = np.hstack((position_info, my_handcards, other_handcards,\n three_landlord_cards, last_action, landlord_played_cards,\n landlord_up_played_cards, landlord_down_played_cards,\n landlord_num_cards_left, landlord_up_num_cards_left,\n landlord_down_num_cards_left, bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(z[np.newaxis, :, :], num_legal_actions, axis=0)\n obs = {'position': '', 'x_batch': x_batch.astype(np.float32), 'z_batch':\n z_batch.astype(np.float32), 'legal_actions': multiply_info_batch,\n 'x_no_action': x_no_action.astype(np.int8), 'z': z.astype(np.int8),\n 'bid_info': bid_info.astype(np.int8), 'multiply_info_batch':\n multiply_info.astype(np.int8)}\n return obs\n", "step-5": "from collections import Counter\nimport numpy as np\nimport random\nimport torch\nimport BidModel\n\nfrom douzero.env.game import GameEnv\n\nenv_version = \"3.2\"\nenv_url = \"http://od.vcccz.com/hechuan/env.py\"\nCard2Column = {3: 0, 4: 1, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6, 10: 7,\n 11: 8, 12: 9, 13: 10, 14: 11, 17: 12}\n\nNumOnes2Array = {0: np.array([0, 0, 0, 0]),\n 1: np.array([1, 0, 0, 0]),\n 2: np.array([1, 1, 0, 0]),\n 3: np.array([1, 1, 1, 0]),\n 4: np.array([1, 1, 1, 1])}\n\ndeck = []\nfor i in range(3, 15):\n deck.extend([i for _ in range(4)])\ndeck.extend([17 for _ in range(4)])\ndeck.extend([20, 30])\n\n\nclass Env:\n \"\"\"\n Doudizhu multi-agent wrapper\n \"\"\"\n\n def __init__(self, objective):\n \"\"\"\n Objective is wp/adp/logadp. It indicates whether considers\n bomb in reward calculation. Here, we use dummy agents.\n This is because, in the orignial game, the players\n are `in` the game. Here, we want to isolate\n players and environments to have a more gym style\n interface. To achieve this, we use dummy players\n to play. For each move, we tell the corresponding\n dummy player which action to play, then the player\n will perform the actual action in the game engine.\n \"\"\"\n self.objective = objective\n\n # Initialize players\n # We use three dummy player for the target position\n self.players = {}\n for position in ['landlord', 'landlord_up', 'landlord_down']:\n self.players[position] = DummyAgent(position)\n\n # Initialize the internal environment\n self._env = GameEnv(self.players)\n self.total_round = 0\n self.force_bid = 0\n self.infoset = None\n\n def reset(self, model, device, flags=None):\n \"\"\"\n Every time reset is called, the environment\n will be re-initialized with a new deck of cards.\n This function is usually called when a game is over.\n \"\"\"\n self._env.reset()\n\n # Randomly shuffle the deck\n if model is None:\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = {'landlord': _deck[:20],\n 'landlord_up': _deck[20:37],\n 'landlord_down': _deck[37:54],\n 'three_landlord_cards': _deck[17:20],\n }\n for key in card_play_data:\n card_play_data[key].sort()\n self._env.card_play_init(card_play_data)\n self.infoset = self._game_infoset\n return get_obs(self.infoset)\n else:\n self.total_round += 1\n bid_done = False\n card_play_data = []\n landlord_cards = []\n last_bid = 0\n bid_count = 0\n player_ids = {}\n bid_info = None\n bid_obs_buffer = []\n multiply_obs_buffer = []\n bid_limit = 3\n force_bid = False\n while not bid_done:\n bid_limit -= 1\n bid_obs_buffer.clear()\n multiply_obs_buffer.clear()\n _deck = deck.copy()\n np.random.shuffle(_deck)\n card_play_data = [\n _deck[:17],\n _deck[17:34],\n _deck[34:51],\n ]\n for i in range(3):\n card_play_data[i].sort()\n landlord_cards = _deck[51:54]\n landlord_cards.sort()\n bid_info = np.array([[-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1],\n [-1, -1, -1]])\n bidding_player = random.randint(0, 2)\n # bidding_player = 0 # debug\n first_bid = -1\n last_bid = -1\n bid_count = 0\n if bid_limit <= 0:\n force_bid = True\n for r in range(3):\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info, card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward(\"bidding\", torch.tensor(bidding_obs[\"z_batch\"], device=device),\n torch.tensor(bidding_obs[\"x_batch\"], device=device), flags=flags)\n if bid_limit <= 0:\n wr = BidModel.predict_env(card_play_data[bidding_player])\n if wr >= 0.7:\n action = {\"action\": 1} # debug\n bid_limit += 1\n\n bid_obs_buffer.append({\n \"x_batch\": bidding_obs[\"x_batch\"][action[\"action\"]],\n \"z_batch\": bidding_obs[\"z_batch\"][action[\"action\"]],\n \"pid\": bidding_player\n })\n if action[\"action\"] == 1:\n last_bid = bidding_player\n bid_count += 1\n if first_bid == -1:\n first_bid = bidding_player\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n else:\n bid_info[r] = [0, 0, 0]\n bidding_player = (bidding_player + 1) % 3\n one_count = np.count_nonzero(bid_info == 1)\n if one_count == 0:\n continue\n elif one_count > 1:\n r = 3\n bidding_player = first_bid\n bidding_obs = _get_obs_for_bid(bidding_player, bid_info, card_play_data[bidding_player])\n with torch.no_grad():\n action = model.forward(\"bidding\", torch.tensor(bidding_obs[\"z_batch\"], device=device),\n torch.tensor(bidding_obs[\"x_batch\"], device=device), flags=flags)\n bid_obs_buffer.append({\n \"x_batch\": bidding_obs[\"x_batch\"][action[\"action\"]],\n \"z_batch\": bidding_obs[\"z_batch\"][action[\"action\"]],\n \"pid\": bidding_player\n })\n if action[\"action\"] == 1:\n last_bid = bidding_player\n bid_count += 1\n for p in range(3):\n if p == bidding_player:\n bid_info[r][p] = 1\n else:\n bid_info[r][p] = 0\n break\n card_play_data[last_bid].extend(landlord_cards)\n card_play_data = {'landlord': card_play_data[last_bid],\n 'landlord_up': card_play_data[(last_bid - 1) % 3],\n 'landlord_down': card_play_data[(last_bid + 1) % 3],\n 'three_landlord_cards': landlord_cards,\n }\n card_play_data[\"landlord\"].sort()\n player_ids = {\n 'landlord': last_bid,\n 'landlord_up': (last_bid - 1) % 3,\n 'landlord_down': (last_bid + 1) % 3,\n }\n player_positions = {\n last_bid: 'landlord',\n (last_bid - 1) % 3: 'landlord_up',\n (last_bid + 1) % 3: 'landlord_down'\n }\n for bid_obs in bid_obs_buffer:\n bid_obs.update({\"position\": player_positions[bid_obs[\"pid\"]]})\n\n # Initialize the cards\n self._env.card_play_init(card_play_data)\n multiply_map = [\n np.array([1, 0, 0]),\n np.array([0, 1, 0]),\n np.array([0, 0, 1])\n ]\n for pos in [\"landlord\", \"landlord_up\", \"landlord_down\"]:\n pid = player_ids[pos]\n self._env.info_sets[pos].player_id = pid\n self._env.info_sets[pos].bid_info = bid_info[:, [(pid - 1) % 3, pid, (pid + 1) % 3]]\n self._env.bid_count = bid_count\n # multiply_obs = _get_obs_for_multiply(pos, self._env.info_sets[pos].bid_info, card_play_data[pos],\n # landlord_cards)\n # action = model.forward(pos, torch.tensor(multiply_obs[\"z_batch\"], device=device),\n # torch.tensor(multiply_obs[\"x_batch\"], device=device), flags=flags)\n # multiply_obs_buffer.append({\n # \"x_batch\": multiply_obs[\"x_batch\"][action[\"action\"]],\n # \"z_batch\": multiply_obs[\"z_batch\"][action[\"action\"]],\n # \"position\": pos\n # })\n action = {\"action\": 0}\n self._env.info_sets[pos].multiply_info = multiply_map[action[\"action\"]]\n self._env.multiply_count[pos] = action[\"action\"]\n self.infoset = self._game_infoset\n if force_bid:\n self.force_bid += 1\n if self.total_round % 100 == 0:\n print(\"发牌情况: %i/%i %.1f%%\" % (self.force_bid, self.total_round, self.force_bid / self.total_round * 100))\n self.force_bid = 0\n self.total_round = 0\n return get_obs(self.infoset), {\n \"bid_obs_buffer\": bid_obs_buffer,\n \"multiply_obs_buffer\": multiply_obs_buffer\n }\n\n def step(self, action):\n \"\"\"\n Step function takes as input the action, which\n is a list of integers, and output the next obervation,\n reward, and a Boolean variable indicating whether the\n current game is finished. It also returns an empty\n dictionary that is reserved to pass useful information.\n \"\"\"\n assert action in self.infoset.legal_actions\n self.players[self._acting_player_position].set_action(action)\n self._env.step()\n self.infoset = self._game_infoset\n done = False\n reward = 0.0\n if self._game_over:\n done = True\n reward = {\n \"play\": {\n \"landlord\": self._get_reward(\"landlord\"),\n \"landlord_up\": self._get_reward(\"landlord_up\"),\n \"landlord_down\": self._get_reward(\"landlord_down\")\n },\n \"bid\": {\n \"landlord\": self._get_reward_bidding(\"landlord\")*2,\n \"landlord_up\": self._get_reward_bidding(\"landlord_up\"),\n \"landlord_down\": self._get_reward_bidding(\"landlord_down\")\n }\n }\n obs = None\n else:\n obs = get_obs(self.infoset)\n return obs, reward, done, {}\n\n def _get_reward(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n self_bomb_num = self._env.pos_bomb_num[pos]\n if winner == 'landlord':\n if self.objective == 'adp':\n return (1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +self._env.multiply_count[pos]) /8\n elif self.objective == 'logadp':\n return (1.0 - self._env.step_count * 0.0033) * 1.3**self_bomb_num * 2**self._env.multiply_count[pos] / 4\n else:\n return 1.0 - self._env.step_count * 0.0033\n else:\n if self.objective == 'adp':\n return (-1.1 - self._env.step_count * 0.0033) * 1.3 ** (bomb_num +self._env.multiply_count[pos]) /8\n elif self.objective == 'logadp':\n return (-1.0 + self._env.step_count * 0.0033) * 1.3**self_bomb_num * 2**self._env.multiply_count[pos] / 4\n else:\n return -1.0 + self._env.step_count * 0.0033\n\n def _get_reward_bidding(self, pos):\n \"\"\"\n This function is called in the end of each\n game. It returns either 1/-1 for win/loss,\n or ADP, i.e., every bomb will double the score.\n \"\"\"\n winner = self._game_winner\n bomb_num = self._game_bomb_num\n if winner == 'landlord':\n return 1.0 * 2**(self._env.bid_count-1) / 8\n else:\n return -1.0 * 2**(self._env.bid_count-1) / 8\n\n @property\n def _game_infoset(self):\n \"\"\"\n Here, inforset is defined as all the information\n in the current situation, incuding the hand cards\n of all the players, all the historical moves, etc.\n That is, it contains perferfect infomation. Later,\n we will use functions to extract the observable\n information from the views of the three players.\n \"\"\"\n return self._env.game_infoset\n\n @property\n def _game_bomb_num(self):\n \"\"\"\n The number of bombs played so far. This is used as\n a feature of the neural network and is also used to\n calculate ADP.\n \"\"\"\n return self._env.get_bomb_num()\n\n @property\n def _game_winner(self):\n \"\"\" A string of landlord/peasants\n \"\"\"\n return self._env.get_winner()\n\n @property\n def _acting_player_position(self):\n \"\"\"\n The player that is active. It can be landlord,\n landlod_down, or landlord_up.\n \"\"\"\n return self._env.acting_player_position\n\n @property\n def _game_over(self):\n \"\"\" Returns a Boolean\n \"\"\"\n return self._env.game_over\n\n\nclass DummyAgent(object):\n \"\"\"\n Dummy agent is designed to easily interact with the\n game engine. The agent will first be told what action\n to perform. Then the environment will call this agent\n to perform the actual action. This can help us to\n isolate environment and agents towards a gym like\n interface.\n \"\"\"\n\n def __init__(self, position):\n self.position = position\n self.action = None\n\n def act(self, infoset):\n \"\"\"\n Simply return the action that is set previously.\n \"\"\"\n assert self.action in infoset.legal_actions\n return self.action\n\n def set_action(self, action):\n \"\"\"\n The environment uses this function to tell\n the dummy agent what to do.\n \"\"\"\n self.action = action\n\n\ndef get_obs(infoset, use_general=True):\n \"\"\"\n This function obtains observations with imperfect information\n from the infoset. It has three branches since we encode\n different features for different positions.\n\n This function will return dictionary named `obs`. It contains\n several fields. These fields will be used to train the model.\n One can play with those features to improve the performance.\n\n `position` is a string that can be landlord/landlord_down/landlord_up\n\n `x_batch` is a batch of features (excluding the hisorical moves).\n It also encodes the action feature\n\n `z_batch` is a batch of features with hisorical moves only.\n\n `legal_actions` is the legal moves\n\n `x_no_action`: the features (exluding the hitorical moves and\n the action features). It does not have the batch dim.\n\n `z`: same as z_batch but not a batch.\n \"\"\"\n if use_general:\n if infoset.player_position not in [\"landlord\", \"landlord_up\", \"landlord_down\"]:\n raise ValueError('')\n return _get_obs_general(infoset, infoset.player_position)\n else:\n if infoset.player_position == 'landlord':\n return _get_obs_landlord(infoset)\n elif infoset.player_position == 'landlord_up':\n return _get_obs_landlord_up(infoset)\n elif infoset.player_position == 'landlord_down':\n return _get_obs_landlord_down(infoset)\n else:\n raise ValueError('')\n\n\ndef _get_one_hot_array(num_left_cards, max_num_cards):\n \"\"\"\n A utility function to obtain one-hot endoding\n \"\"\"\n one_hot = np.zeros(max_num_cards)\n if num_left_cards > 0:\n one_hot[num_left_cards - 1] = 1\n\n return one_hot\n\n\ndef _cards2array(list_cards):\n \"\"\"\n A utility function that transforms the actions, i.e.,\n A list of integers into card matrix. Here we remove\n the six entries that are always zero and flatten the\n the representations.\n \"\"\"\n if len(list_cards) == 0:\n return np.zeros(54, dtype=np.int8)\n\n matrix = np.zeros([4, 13], dtype=np.int8)\n jokers = np.zeros(2, dtype=np.int8)\n counter = Counter(list_cards)\n for card, num_times in counter.items():\n if card < 20:\n matrix[:, Card2Column[card]] = NumOnes2Array[num_times]\n elif card == 20:\n jokers[0] = 1\n elif card == 30:\n jokers[1] = 1\n return np.concatenate((matrix.flatten('F'), jokers))\n\n\n# def _action_seq_list2array(action_seq_list):\n# \"\"\"\n# A utility function to encode the historical moves.\n# We encode the historical 15 actions. If there is\n# no 15 actions, we pad the features with 0. Since\n# three moves is a round in DouDizhu, we concatenate\n# the representations for each consecutive three moves.\n# Finally, we obtain a 5x162 matrix, which will be fed\n# into LSTM for encoding.\n# \"\"\"\n# action_seq_array = np.zeros((len(action_seq_list), 54))\n# for row, list_cards in enumerate(action_seq_list):\n# action_seq_array[row, :] = _cards2array(list_cards)\n# # action_seq_array = action_seq_array.reshape(5, 162)\n# return action_seq_array\n\ndef _action_seq_list2array(action_seq_list, new_model=True):\n \"\"\"\n A utility function to encode the historical moves.\n We encode the historical 15 actions. If there is\n no 15 actions, we pad the features with 0. Since\n three moves is a round in DouDizhu, we concatenate\n the representations for each consecutive three moves.\n Finally, we obtain a 5x162 matrix, which will be fed\n into LSTM for encoding.\n \"\"\"\n\n if new_model:\n position_map = {\"landlord\": 0, \"landlord_up\": 1, \"landlord_down\": 2}\n action_seq_array = np.ones((len(action_seq_list), 54)) * -1 # Default Value -1 for not using area\n for row, list_cards in enumerate(action_seq_list):\n if list_cards != []:\n action_seq_array[row, :54] = _cards2array(list_cards[1])\n else:\n action_seq_array = np.zeros((len(action_seq_list), 54))\n for row, list_cards in enumerate(action_seq_list):\n if list_cards != []:\n action_seq_array[row, :] = _cards2array(list_cards[1])\n action_seq_array = action_seq_array.reshape(5, 162)\n return action_seq_array\n\n # action_seq_array = np.zeros((len(action_seq_list), 54))\n # for row, list_cards in enumerate(action_seq_list):\n # if list_cards != []:\n # action_seq_array[row, :] = _cards2array(list_cards[1])\n # return action_seq_array\n\n\ndef _process_action_seq(sequence, length=15, new_model=True):\n \"\"\"\n A utility function encoding historical moves. We\n encode 15 moves. If there is no 15 moves, we pad\n with zeros.\n \"\"\"\n sequence = sequence[-length:].copy()\n if new_model:\n sequence = sequence[::-1]\n if len(sequence) < length:\n empty_sequence = [[] for _ in range(length - len(sequence))]\n empty_sequence.extend(sequence)\n sequence = empty_sequence\n return sequence\n\n\ndef _get_one_hot_bomb(bomb_num):\n \"\"\"\n A utility function to encode the number of bombs\n into one-hot representation.\n \"\"\"\n one_hot = np.zeros(15)\n one_hot[bomb_num] = 1\n return one_hot\n\n\ndef _get_obs_landlord(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n landlord_up_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array(\n infoset.played_cards['landlord_up'])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array(\n infoset.played_cards['landlord_down'])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((my_handcards_batch,\n other_handcards_batch,\n last_action_batch,\n landlord_up_played_cards_batch,\n landlord_down_played_cards_batch,\n landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch,\n bomb_num_batch,\n my_action_batch))\n x_no_action = np.hstack((my_handcards,\n other_handcards,\n last_action,\n landlord_up_played_cards,\n landlord_down_played_cards,\n landlord_up_num_cards_left,\n landlord_down_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq(\n infoset.card_play_action_seq, 15, False), False)\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': 'landlord',\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\ndef _get_obs_landlord_up(infoset):\n \"\"\"\n Obttain the landlord_up features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n last_landlord_action = _cards2array(\n infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(\n last_landlord_action[np.newaxis, :],\n num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_played_cards = _cards2array(\n infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_teammate_action = _cards2array(\n infoset.last_move_dict['landlord_down'])\n last_teammate_action_batch = np.repeat(\n last_teammate_action[np.newaxis, :],\n num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_down'], 17)\n teammate_num_cards_left_batch = np.repeat(\n teammate_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n teammate_played_cards = _cards2array(\n infoset.played_cards['landlord_down'])\n teammate_played_cards_batch = np.repeat(\n teammate_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((my_handcards_batch,\n other_handcards_batch,\n landlord_played_cards_batch,\n teammate_played_cards_batch,\n last_action_batch,\n last_landlord_action_batch,\n last_teammate_action_batch,\n landlord_num_cards_left_batch,\n teammate_num_cards_left_batch,\n bomb_num_batch,\n my_action_batch))\n x_no_action = np.hstack((my_handcards,\n other_handcards,\n landlord_played_cards,\n teammate_played_cards,\n last_action,\n last_landlord_action,\n last_teammate_action,\n landlord_num_cards_left,\n teammate_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq(\n infoset.card_play_action_seq, 15, False), False)\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': 'landlord_up',\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\ndef _get_obs_landlord_down(infoset):\n \"\"\"\n Obttain the landlord_down features. See Table 5 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n last_landlord_action = _cards2array(\n infoset.last_move_dict['landlord'])\n last_landlord_action_batch = np.repeat(\n last_landlord_action[np.newaxis, :],\n num_legal_actions, axis=0)\n landlord_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_played_cards = _cards2array(\n infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_teammate_action = _cards2array(\n infoset.last_move_dict['landlord_up'])\n last_teammate_action_batch = np.repeat(\n last_teammate_action[np.newaxis, :],\n num_legal_actions, axis=0)\n teammate_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_up'], 17)\n teammate_num_cards_left_batch = np.repeat(\n teammate_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n teammate_played_cards = _cards2array(\n infoset.played_cards['landlord_up'])\n teammate_played_cards_batch = np.repeat(\n teammate_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_played_cards = _cards2array(\n infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((my_handcards_batch,\n other_handcards_batch,\n landlord_played_cards_batch,\n teammate_played_cards_batch,\n last_action_batch,\n last_landlord_action_batch,\n last_teammate_action_batch,\n landlord_num_cards_left_batch,\n teammate_num_cards_left_batch,\n bomb_num_batch,\n my_action_batch))\n x_no_action = np.hstack((my_handcards,\n other_handcards,\n landlord_played_cards,\n teammate_played_cards,\n last_action,\n last_landlord_action,\n last_teammate_action,\n landlord_num_cards_left,\n teammate_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq(\n infoset.card_play_action_seq, 15, False), False)\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': 'landlord_down',\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\ndef _get_obs_landlord_withbid(infoset):\n \"\"\"\n Obttain the landlord features. See Table 4 in\n https://arxiv.org/pdf/2106.06135.pdf\n \"\"\"\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n landlord_up_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array(\n infoset.played_cards['landlord_up'])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array(\n infoset.played_cards['landlord_down'])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((my_handcards_batch,\n other_handcards_batch,\n last_action_batch,\n landlord_up_played_cards_batch,\n landlord_down_played_cards_batch,\n landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch,\n bomb_num_batch,\n my_action_batch))\n x_no_action = np.hstack((my_handcards,\n other_handcards,\n last_action,\n landlord_up_played_cards,\n landlord_down_played_cards,\n landlord_up_num_cards_left,\n landlord_down_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq(\n infoset.card_play_action_seq, 15, False), False)\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': 'landlord',\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\n\ndef _get_obs_general1(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n position_map = {\n \"landlord\": [1, 0, 0],\n \"landlord_up\": [0, 1, 0],\n \"landlord_down\": [0, 0, 1]\n }\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n landlord_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards_left_list = []\n for pos in [\"landlord\", \"landlord_up\", \"landlord_up\"]:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n\n landlord_played_cards = _cards2array(\n infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array(\n infoset.played_cards['landlord_up'])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array(\n infoset.played_cards['landlord_down'])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((position_info_batch, # 3\n my_handcards_batch, # 54\n other_handcards_batch, # 54\n three_landlord_cards_batch, # 54\n last_action_batch, # 54\n landlord_played_cards_batch, # 54\n landlord_up_played_cards_batch, # 54\n landlord_down_played_cards_batch, # 54\n landlord_num_cards_left_batch, # 20\n landlord_up_num_cards_left_batch, # 17\n landlord_down_num_cards_left_batch, # 17\n bomb_num_batch, # 15\n bid_info_batch, # 12\n multiply_info_batch, # 3\n my_action_batch)) # 54\n x_no_action = np.hstack((position_info,\n my_handcards,\n other_handcards,\n three_landlord_cards,\n last_action,\n landlord_played_cards,\n landlord_up_played_cards,\n landlord_down_played_cards,\n landlord_num_cards_left,\n landlord_up_num_cards_left,\n landlord_down_num_cards_left,\n bomb_num,\n bid_info,\n multiply_info))\n z = _action_seq_list2array(_process_action_seq(\n infoset.card_play_action_seq, 32))\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': position,\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\ndef _get_obs_general(infoset, position):\n num_legal_actions = len(infoset.legal_actions)\n my_handcards = _cards2array(infoset.player_hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards = _cards2array(infoset.other_hand_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n position_map = {\n \"landlord\": [1, 0, 0],\n \"landlord_up\": [0, 1, 0],\n \"landlord_down\": [0, 0, 1]\n }\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bid_info = np.array(infoset.bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n multiply_info = np.array(infoset.multiply_info)\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n three_landlord_cards = _cards2array(infoset.three_landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array(infoset.last_move)\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j, action in enumerate(infoset.legal_actions):\n my_action_batch[j, :] = _cards2array(action)\n\n landlord_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord'], 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_up'], 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(\n infoset.num_cards_left_dict['landlord_down'], 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n other_handcards_left_list = []\n for pos in [\"landlord\", \"landlord_up\", \"landlord_up\"]:\n if pos != position:\n other_handcards_left_list.extend(infoset.all_handcards[pos])\n\n landlord_played_cards = _cards2array(\n infoset.played_cards['landlord'])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array(\n infoset.played_cards['landlord_up'])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array(\n infoset.played_cards['landlord_down'])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(\n infoset.bomb_num)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n num_cards_left = np.hstack((\n landlord_num_cards_left, # 20\n landlord_up_num_cards_left, # 17\n landlord_down_num_cards_left))\n\n x_batch = np.hstack((\n bid_info_batch, # 12\n multiply_info_batch)) # 3\n x_no_action = np.hstack((\n bid_info,\n multiply_info))\n z =np.vstack((\n num_cards_left,\n my_handcards, # 54\n other_handcards, # 54\n three_landlord_cards, # 54\n landlord_played_cards, # 54\n landlord_up_played_cards, # 54\n landlord_down_played_cards, # 54\n _action_seq_list2array(_process_action_seq(infoset.card_play_action_seq, 32))\n ))\n\n _z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n my_action_batch = my_action_batch[:,np.newaxis,:]\n z_batch = np.zeros([len(_z_batch),40,54],int)\n for i in range(0,len(_z_batch)):\n z_batch[i] = np.vstack((my_action_batch[i],_z_batch[i]))\n obs = {\n 'position': position,\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': infoset.legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n }\n return obs\n\ndef gen_bid_legal_actions(player_id, bid_info):\n self_bid_info = bid_info[:, [(player_id - 1) % 3, player_id, (player_id + 1) % 3]]\n curr_round = -1\n for r in range(4):\n if -1 in self_bid_info[r]:\n curr_round = r\n break\n bid_actions = []\n if curr_round != -1:\n self_bid_info[curr_round] = [0, 0, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n self_bid_info[curr_round] = [0, 1, 0]\n bid_actions.append(np.array(self_bid_info).flatten())\n return np.array(bid_actions)\n\n\ndef _get_obs_for_bid_legacy(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12,\n 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n position_info = np.array([0, 0, 0])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = bid_legal_actions\n\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.repeat(multiply_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n three_landlord_cards = _cards2array([])\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(2):\n my_action_batch[j, :] = _cards2array([])\n\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((position_info_batch,\n my_handcards_batch,\n other_handcards_batch,\n three_landlord_cards_batch,\n last_action_batch,\n landlord_played_cards_batch,\n landlord_up_played_cards_batch,\n landlord_down_played_cards_batch,\n landlord_num_cards_left_batch,\n landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch,\n bomb_num_batch,\n bid_info_batch,\n multiply_info_batch,\n my_action_batch))\n x_no_action = np.hstack((position_info,\n my_handcards,\n other_handcards,\n three_landlord_cards,\n last_action,\n landlord_played_cards,\n landlord_up_played_cards,\n landlord_down_played_cards,\n landlord_num_cards_left,\n landlord_up_num_cards_left,\n landlord_down_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': \"\",\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': bid_legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n \"bid_info_batch\": bid_info_batch.astype(np.int8),\n \"multiply_info\": multiply_info.astype(np.int8)\n }\n return obs\n\ndef _get_obs_for_bid(player_id, bid_info, hand_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12,\n 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 2\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bid_legal_actions = gen_bid_legal_actions(player_id, bid_info)\n bid_info = bid_legal_actions[0]\n bid_info_batch = np.hstack([bid_legal_actions for _ in range(5)])\n\n x_batch = np.hstack((my_handcards_batch,\n bid_info_batch))\n x_no_action = np.hstack((my_handcards))\n obs = {\n 'position': \"\",\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': np.array([0,0]),\n 'legal_actions': bid_legal_actions,\n 'x_no_action': x_no_action.astype(np.int8),\n \"bid_info_batch\": bid_info_batch.astype(np.int8)\n }\n return obs\n\ndef _get_obs_for_multiply(position, bid_info, hand_cards, landlord_cards):\n all_cards = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,\n 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12,\n 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30]\n num_legal_actions = 3\n my_handcards = _cards2array(hand_cards)\n my_handcards_batch = np.repeat(my_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n other_cards = []\n other_cards.extend(all_cards)\n for card in hand_cards:\n other_cards.remove(card)\n other_handcards = _cards2array(other_cards)\n other_handcards_batch = np.repeat(other_handcards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n position_map = {\n \"landlord\": [1, 0, 0],\n \"landlord_up\": [0, 1, 0],\n \"landlord_down\": [0, 0, 1]\n }\n position_info = np.array(position_map[position])\n position_info_batch = np.repeat(position_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bid_info = np.array(bid_info).flatten()\n bid_info_batch = np.repeat(bid_info[np.newaxis, :],\n num_legal_actions, axis=0)\n\n multiply_info = np.array([0, 0, 0])\n multiply_info_batch = np.array([[1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]])\n\n three_landlord_cards = _cards2array(landlord_cards)\n three_landlord_cards_batch = np.repeat(three_landlord_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n last_action = _cards2array([])\n last_action_batch = np.repeat(last_action[np.newaxis, :],\n num_legal_actions, axis=0)\n\n my_action_batch = np.zeros(my_handcards_batch.shape)\n for j in range(num_legal_actions):\n my_action_batch[j, :] = _cards2array([])\n\n landlord_num_cards_left = _get_one_hot_array(0, 20)\n landlord_num_cards_left_batch = np.repeat(\n landlord_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_num_cards_left = _get_one_hot_array(0, 17)\n landlord_up_num_cards_left_batch = np.repeat(\n landlord_up_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_num_cards_left = _get_one_hot_array(0, 17)\n landlord_down_num_cards_left_batch = np.repeat(\n landlord_down_num_cards_left[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_played_cards = _cards2array([])\n landlord_played_cards_batch = np.repeat(\n landlord_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_up_played_cards = _cards2array([])\n landlord_up_played_cards_batch = np.repeat(\n landlord_up_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n landlord_down_played_cards = _cards2array([])\n landlord_down_played_cards_batch = np.repeat(\n landlord_down_played_cards[np.newaxis, :],\n num_legal_actions, axis=0)\n\n bomb_num = _get_one_hot_bomb(0)\n bomb_num_batch = np.repeat(\n bomb_num[np.newaxis, :],\n num_legal_actions, axis=0)\n\n x_batch = np.hstack((position_info_batch,\n my_handcards_batch,\n other_handcards_batch,\n three_landlord_cards_batch,\n last_action_batch,\n landlord_played_cards_batch,\n landlord_up_played_cards_batch,\n landlord_down_played_cards_batch,\n landlord_num_cards_left_batch,\n landlord_up_num_cards_left_batch,\n landlord_down_num_cards_left_batch,\n bomb_num_batch,\n bid_info_batch,\n multiply_info_batch,\n my_action_batch))\n x_no_action = np.hstack((position_info,\n my_handcards,\n other_handcards,\n three_landlord_cards,\n last_action,\n landlord_played_cards,\n landlord_up_played_cards,\n landlord_down_played_cards,\n landlord_num_cards_left,\n landlord_up_num_cards_left,\n landlord_down_num_cards_left,\n bomb_num))\n z = _action_seq_list2array(_process_action_seq([], 32))\n z_batch = np.repeat(\n z[np.newaxis, :, :],\n num_legal_actions, axis=0)\n obs = {\n 'position': \"\",\n 'x_batch': x_batch.astype(np.float32),\n 'z_batch': z_batch.astype(np.float32),\n 'legal_actions': multiply_info_batch,\n 'x_no_action': x_no_action.astype(np.int8),\n 'z': z.astype(np.int8),\n \"bid_info\": bid_info.astype(np.int8),\n \"multiply_info_batch\": multiply_info.astype(np.int8)\n }\n return obs\n", "step-ids": [ 13, 24, 32, 36, 37 ] }
[ 13, 24, 32, 36, 37 ]
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Base PXE Interface Methods """ from ironic_lib import metrics_utils from oslo_log import log as logging from ironic.common import exception from ironic.common.i18n import _ from ironic.common import pxe_utils as pxe_utils from ironic.drivers.modules import deploy_utils LOG = logging.getLogger(__name__) METRICS = metrics_utils.get_metrics_logger(__name__) REQUIRED_PROPERTIES = { 'deploy_kernel': _("UUID (from Glance) of the deployment kernel. " "Required."), 'deploy_ramdisk': _("UUID (from Glance) of the ramdisk that is " "mounted at boot time. Required."), } OPTIONAL_PROPERTIES = { 'force_persistent_boot_device': _("True to enable persistent behavior " "when the boot device is set during " "deploy and cleaning operations. " "Defaults to False. Optional."), } RESCUE_PROPERTIES = { 'rescue_kernel': _('UUID (from Glance) of the rescue kernel. This value ' 'is required for rescue mode.'), 'rescue_ramdisk': _('UUID (from Glance) of the rescue ramdisk with agent ' 'that is used at node rescue time. This value is ' 'required for rescue mode.'), } COMMON_PROPERTIES = REQUIRED_PROPERTIES.copy() COMMON_PROPERTIES.update(OPTIONAL_PROPERTIES) COMMON_PROPERTIES.update(RESCUE_PROPERTIES) class PXEBaseMixin(object): def get_properties(self): """Return the properties of the interface. :returns: dictionary of <property name>:<property description> entries. """ return COMMON_PROPERTIES @METRICS.timer('PXEBaseMixin.clean_up_ramdisk') def clean_up_ramdisk(self, task): """Cleans up the boot of ironic ramdisk. This method cleans up the PXE environment that was setup for booting the deploy or rescue ramdisk. It unlinks the deploy/rescue kernel/ramdisk in the node's directory in tftproot and removes it's PXE config. :param task: a task from TaskManager. :param mode: Label indicating a deploy or rescue operation was carried out on the node. Supported values are 'deploy' and 'rescue'. Defaults to 'deploy', indicating deploy operation was carried out. :returns: None """ node = task.node mode = deploy_utils.rescue_or_deploy_mode(node) try: images_info = pxe_utils.get_image_info(node, mode=mode) except exception.MissingParameterValue as e: LOG.warning('Could not get %(mode)s image info ' 'to clean up images for node %(node)s: %(err)s', {'mode': mode, 'node': node.uuid, 'err': e}) else: pxe_utils.clean_up_pxe_env(task, images_info) @METRICS.timer('PXEBaseMixin.validate_rescue') def validate_rescue(self, task): """Validate that the node has required properties for rescue. :param task: a TaskManager instance with the node being checked :raises: MissingParameterValue if node is missing one or more required parameters """ pxe_utils.parse_driver_info(task.node, mode='rescue')
normal
{ "blob_id": "d56fa4ea999d8af887e5f68296bfb20ad535e6ad", "index": 6748, "step-1": "<mask token>\n\n\nclass PXEBaseMixin(object):\n\n def get_properties(self):\n \"\"\"Return the properties of the interface.\n\n :returns: dictionary of <property name>:<property description> entries.\n \"\"\"\n return COMMON_PROPERTIES\n\n @METRICS.timer('PXEBaseMixin.clean_up_ramdisk')\n def clean_up_ramdisk(self, task):\n \"\"\"Cleans up the boot of ironic ramdisk.\n\n This method cleans up the PXE environment that was setup for booting\n the deploy or rescue ramdisk. It unlinks the deploy/rescue\n kernel/ramdisk in the node's directory in tftproot and removes it's PXE\n config.\n\n :param task: a task from TaskManager.\n :param mode: Label indicating a deploy or rescue operation\n was carried out on the node. Supported values are 'deploy' and\n 'rescue'. Defaults to 'deploy', indicating deploy operation was\n carried out.\n :returns: None\n \"\"\"\n node = task.node\n mode = deploy_utils.rescue_or_deploy_mode(node)\n try:\n images_info = pxe_utils.get_image_info(node, mode=mode)\n except exception.MissingParameterValue as e:\n LOG.warning(\n 'Could not get %(mode)s image info to clean up images for node %(node)s: %(err)s'\n , {'mode': mode, 'node': node.uuid, 'err': e})\n else:\n pxe_utils.clean_up_pxe_env(task, images_info)\n\n @METRICS.timer('PXEBaseMixin.validate_rescue')\n def validate_rescue(self, task):\n \"\"\"Validate that the node has required properties for rescue.\n\n :param task: a TaskManager instance with the node being checked\n :raises: MissingParameterValue if node is missing one or more required\n parameters\n \"\"\"\n pxe_utils.parse_driver_info(task.node, mode='rescue')\n", "step-2": "<mask token>\nCOMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)\nCOMMON_PROPERTIES.update(RESCUE_PROPERTIES)\n\n\nclass PXEBaseMixin(object):\n\n def get_properties(self):\n \"\"\"Return the properties of the interface.\n\n :returns: dictionary of <property name>:<property description> entries.\n \"\"\"\n return COMMON_PROPERTIES\n\n @METRICS.timer('PXEBaseMixin.clean_up_ramdisk')\n def clean_up_ramdisk(self, task):\n \"\"\"Cleans up the boot of ironic ramdisk.\n\n This method cleans up the PXE environment that was setup for booting\n the deploy or rescue ramdisk. It unlinks the deploy/rescue\n kernel/ramdisk in the node's directory in tftproot and removes it's PXE\n config.\n\n :param task: a task from TaskManager.\n :param mode: Label indicating a deploy or rescue operation\n was carried out on the node. Supported values are 'deploy' and\n 'rescue'. Defaults to 'deploy', indicating deploy operation was\n carried out.\n :returns: None\n \"\"\"\n node = task.node\n mode = deploy_utils.rescue_or_deploy_mode(node)\n try:\n images_info = pxe_utils.get_image_info(node, mode=mode)\n except exception.MissingParameterValue as e:\n LOG.warning(\n 'Could not get %(mode)s image info to clean up images for node %(node)s: %(err)s'\n , {'mode': mode, 'node': node.uuid, 'err': e})\n else:\n pxe_utils.clean_up_pxe_env(task, images_info)\n\n @METRICS.timer('PXEBaseMixin.validate_rescue')\n def validate_rescue(self, task):\n \"\"\"Validate that the node has required properties for rescue.\n\n :param task: a TaskManager instance with the node being checked\n :raises: MissingParameterValue if node is missing one or more required\n parameters\n \"\"\"\n pxe_utils.parse_driver_info(task.node, mode='rescue')\n", "step-3": "<mask token>\nLOG = logging.getLogger(__name__)\nMETRICS = metrics_utils.get_metrics_logger(__name__)\nREQUIRED_PROPERTIES = {'deploy_kernel': _(\n 'UUID (from Glance) of the deployment kernel. Required.'),\n 'deploy_ramdisk': _(\n 'UUID (from Glance) of the ramdisk that is mounted at boot time. Required.'\n )}\nOPTIONAL_PROPERTIES = {'force_persistent_boot_device': _(\n 'True to enable persistent behavior when the boot device is set during deploy and cleaning operations. Defaults to False. Optional.'\n )}\nRESCUE_PROPERTIES = {'rescue_kernel': _(\n 'UUID (from Glance) of the rescue kernel. This value is required for rescue mode.'\n ), 'rescue_ramdisk': _(\n 'UUID (from Glance) of the rescue ramdisk with agent that is used at node rescue time. This value is required for rescue mode.'\n )}\nCOMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()\nCOMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)\nCOMMON_PROPERTIES.update(RESCUE_PROPERTIES)\n\n\nclass PXEBaseMixin(object):\n\n def get_properties(self):\n \"\"\"Return the properties of the interface.\n\n :returns: dictionary of <property name>:<property description> entries.\n \"\"\"\n return COMMON_PROPERTIES\n\n @METRICS.timer('PXEBaseMixin.clean_up_ramdisk')\n def clean_up_ramdisk(self, task):\n \"\"\"Cleans up the boot of ironic ramdisk.\n\n This method cleans up the PXE environment that was setup for booting\n the deploy or rescue ramdisk. It unlinks the deploy/rescue\n kernel/ramdisk in the node's directory in tftproot and removes it's PXE\n config.\n\n :param task: a task from TaskManager.\n :param mode: Label indicating a deploy or rescue operation\n was carried out on the node. Supported values are 'deploy' and\n 'rescue'. Defaults to 'deploy', indicating deploy operation was\n carried out.\n :returns: None\n \"\"\"\n node = task.node\n mode = deploy_utils.rescue_or_deploy_mode(node)\n try:\n images_info = pxe_utils.get_image_info(node, mode=mode)\n except exception.MissingParameterValue as e:\n LOG.warning(\n 'Could not get %(mode)s image info to clean up images for node %(node)s: %(err)s'\n , {'mode': mode, 'node': node.uuid, 'err': e})\n else:\n pxe_utils.clean_up_pxe_env(task, images_info)\n\n @METRICS.timer('PXEBaseMixin.validate_rescue')\n def validate_rescue(self, task):\n \"\"\"Validate that the node has required properties for rescue.\n\n :param task: a TaskManager instance with the node being checked\n :raises: MissingParameterValue if node is missing one or more required\n parameters\n \"\"\"\n pxe_utils.parse_driver_info(task.node, mode='rescue')\n", "step-4": "<mask token>\nfrom ironic_lib import metrics_utils\nfrom oslo_log import log as logging\nfrom ironic.common import exception\nfrom ironic.common.i18n import _\nfrom ironic.common import pxe_utils as pxe_utils\nfrom ironic.drivers.modules import deploy_utils\nLOG = logging.getLogger(__name__)\nMETRICS = metrics_utils.get_metrics_logger(__name__)\nREQUIRED_PROPERTIES = {'deploy_kernel': _(\n 'UUID (from Glance) of the deployment kernel. Required.'),\n 'deploy_ramdisk': _(\n 'UUID (from Glance) of the ramdisk that is mounted at boot time. Required.'\n )}\nOPTIONAL_PROPERTIES = {'force_persistent_boot_device': _(\n 'True to enable persistent behavior when the boot device is set during deploy and cleaning operations. Defaults to False. Optional.'\n )}\nRESCUE_PROPERTIES = {'rescue_kernel': _(\n 'UUID (from Glance) of the rescue kernel. This value is required for rescue mode.'\n ), 'rescue_ramdisk': _(\n 'UUID (from Glance) of the rescue ramdisk with agent that is used at node rescue time. This value is required for rescue mode.'\n )}\nCOMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()\nCOMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)\nCOMMON_PROPERTIES.update(RESCUE_PROPERTIES)\n\n\nclass PXEBaseMixin(object):\n\n def get_properties(self):\n \"\"\"Return the properties of the interface.\n\n :returns: dictionary of <property name>:<property description> entries.\n \"\"\"\n return COMMON_PROPERTIES\n\n @METRICS.timer('PXEBaseMixin.clean_up_ramdisk')\n def clean_up_ramdisk(self, task):\n \"\"\"Cleans up the boot of ironic ramdisk.\n\n This method cleans up the PXE environment that was setup for booting\n the deploy or rescue ramdisk. It unlinks the deploy/rescue\n kernel/ramdisk in the node's directory in tftproot and removes it's PXE\n config.\n\n :param task: a task from TaskManager.\n :param mode: Label indicating a deploy or rescue operation\n was carried out on the node. Supported values are 'deploy' and\n 'rescue'. Defaults to 'deploy', indicating deploy operation was\n carried out.\n :returns: None\n \"\"\"\n node = task.node\n mode = deploy_utils.rescue_or_deploy_mode(node)\n try:\n images_info = pxe_utils.get_image_info(node, mode=mode)\n except exception.MissingParameterValue as e:\n LOG.warning(\n 'Could not get %(mode)s image info to clean up images for node %(node)s: %(err)s'\n , {'mode': mode, 'node': node.uuid, 'err': e})\n else:\n pxe_utils.clean_up_pxe_env(task, images_info)\n\n @METRICS.timer('PXEBaseMixin.validate_rescue')\n def validate_rescue(self, task):\n \"\"\"Validate that the node has required properties for rescue.\n\n :param task: a TaskManager instance with the node being checked\n :raises: MissingParameterValue if node is missing one or more required\n parameters\n \"\"\"\n pxe_utils.parse_driver_info(task.node, mode='rescue')\n", "step-5": "# 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\"\"\"\nBase PXE Interface Methods\n\"\"\"\n\nfrom ironic_lib import metrics_utils\nfrom oslo_log import log as logging\n\nfrom ironic.common import exception\nfrom ironic.common.i18n import _\nfrom ironic.common import pxe_utils as pxe_utils\nfrom ironic.drivers.modules import deploy_utils\nLOG = logging.getLogger(__name__)\n\nMETRICS = metrics_utils.get_metrics_logger(__name__)\n\nREQUIRED_PROPERTIES = {\n 'deploy_kernel': _(\"UUID (from Glance) of the deployment kernel. \"\n \"Required.\"),\n 'deploy_ramdisk': _(\"UUID (from Glance) of the ramdisk that is \"\n \"mounted at boot time. Required.\"),\n}\nOPTIONAL_PROPERTIES = {\n 'force_persistent_boot_device': _(\"True to enable persistent behavior \"\n \"when the boot device is set during \"\n \"deploy and cleaning operations. \"\n \"Defaults to False. Optional.\"),\n}\nRESCUE_PROPERTIES = {\n 'rescue_kernel': _('UUID (from Glance) of the rescue kernel. This value '\n 'is required for rescue mode.'),\n 'rescue_ramdisk': _('UUID (from Glance) of the rescue ramdisk with agent '\n 'that is used at node rescue time. This value is '\n 'required for rescue mode.'),\n}\nCOMMON_PROPERTIES = REQUIRED_PROPERTIES.copy()\nCOMMON_PROPERTIES.update(OPTIONAL_PROPERTIES)\nCOMMON_PROPERTIES.update(RESCUE_PROPERTIES)\n\n\nclass PXEBaseMixin(object):\n\n def get_properties(self):\n \"\"\"Return the properties of the interface.\n\n :returns: dictionary of <property name>:<property description> entries.\n \"\"\"\n return COMMON_PROPERTIES\n\n @METRICS.timer('PXEBaseMixin.clean_up_ramdisk')\n def clean_up_ramdisk(self, task):\n \"\"\"Cleans up the boot of ironic ramdisk.\n\n This method cleans up the PXE environment that was setup for booting\n the deploy or rescue ramdisk. It unlinks the deploy/rescue\n kernel/ramdisk in the node's directory in tftproot and removes it's PXE\n config.\n\n :param task: a task from TaskManager.\n :param mode: Label indicating a deploy or rescue operation\n was carried out on the node. Supported values are 'deploy' and\n 'rescue'. Defaults to 'deploy', indicating deploy operation was\n carried out.\n :returns: None\n \"\"\"\n node = task.node\n mode = deploy_utils.rescue_or_deploy_mode(node)\n try:\n images_info = pxe_utils.get_image_info(node, mode=mode)\n except exception.MissingParameterValue as e:\n LOG.warning('Could not get %(mode)s image info '\n 'to clean up images for node %(node)s: %(err)s',\n {'mode': mode, 'node': node.uuid, 'err': e})\n else:\n pxe_utils.clean_up_pxe_env(task, images_info)\n\n @METRICS.timer('PXEBaseMixin.validate_rescue')\n def validate_rescue(self, task):\n \"\"\"Validate that the node has required properties for rescue.\n\n :param task: a TaskManager instance with the node being checked\n :raises: MissingParameterValue if node is missing one or more required\n parameters\n \"\"\"\n pxe_utils.parse_driver_info(task.node, mode='rescue')\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
try: a=100 b=a/0 print(b) except ZeroDivisionError as z: print("Error= ",z)
normal
{ "blob_id": "9dead39e41fd0f3cff43501c659050885a50fec3", "index": 4521, "step-1": "<mask token>\n", "step-2": "try:\n a = 100\n b = a / 0\n print(b)\nexcept ZeroDivisionError as z:\n print('Error= ', z)\n", "step-3": "try:\r\n a=100\r\n b=a/0\r\n print(b)\r\nexcept ZeroDivisionError as z:\r\n print(\"Error= \",z)", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from collections import Counter from collections import deque import os def wc(argval): bool = False if("|" in argval): bool = True del argval[len(argval)-1] hf=open("commandoutput.txt","r+") open("commandoutput.txt","w").close() hf=open("commandoutput.txt","w") numoflines = 0 numofwords = 0 numofchars = 0 if len(argval)==2 and os.path.exists(argval[1]): filename=argval[1] fname = filename with open(fname, 'r') as f: for line in f: if not line.isspace(): words = line.split() numoflines += 1 numofwords += len(words) numofchars += len(line) if(bool): hf.write("line count= %d, word count= %d, charcount= %d"%(numoflines,numofwords,numofchars)) else: print("line count= %d, word count= %d, charcount= %d, filename=%s"%(numoflines,numofwords,numofchars,filename)) hf.write("line count= %d, word count= %d, charcount= %d"%(numoflines,numofwords,numofchars)) hf.close() elif len(argval)==3 and os.path.exists(argval[2]): filename=argval[2] #print "wc soemthing" fname = filename with open(fname, 'r') as f: #print "wc soemthing2" for line in f: if not line.isspace(): words = line.split() numoflines += 1 numofwords += len(words) numofchars += len(line) if(bool): hf.write("line count= %d, word count= %d, charcount= %d"%(numoflines,numofwords,numofchars)) else: print("line count= %d, word count= %d, charcount= %d, filename=%s"%(numoflines,numofwords,numofchars,filename)) hf.close() else: print("source file not found")
normal
{ "blob_id": "e9a4ea69a4bd9b75b8eb8092b140691aab763ae4", "index": 2963, "step-1": "from collections import Counter\nfrom collections import deque\nimport os\ndef wc(argval):\n bool = False\n if(\"|\" in argval):\n bool = True\n del argval[len(argval)-1] \n hf=open(\"commandoutput.txt\",\"r+\")\n open(\"commandoutput.txt\",\"w\").close()\n hf=open(\"commandoutput.txt\",\"w\") \n numoflines = 0\n numofwords = 0\n numofchars = 0\n if len(argval)==2 and os.path.exists(argval[1]):\n filename=argval[1]\n fname = filename\n with open(fname, 'r') as f:\n for line in f:\n if not line.isspace():\n words = line.split()\n numoflines += 1\n numofwords += len(words)\n numofchars += len(line)\n if(bool):\n hf.write(\"line count= %d, word count= %d, charcount= %d\"%(numoflines,numofwords,numofchars))\n else:\n print(\"line count= %d, word count= %d, charcount= %d, filename=%s\"%(numoflines,numofwords,numofchars,filename))\t\n\t hf.write(\"line count= %d, word count= %d, charcount= %d\"%(numoflines,numofwords,numofchars))\n\thf.close()\n elif len(argval)==3 and os.path.exists(argval[2]):\n filename=argval[2]\n #print \"wc soemthing\"\n fname = filename\n with open(fname, 'r') as f:\n #print \"wc soemthing2\"\n for line in f:\n if not line.isspace():\n words = line.split()\n numoflines += 1\n numofwords += len(words)\n numofchars += len(line)\n if(bool):\n hf.write(\"line count= %d, word count= %d, charcount= %d\"%(numoflines,numofwords,numofchars))\n else:\n print(\"line count= %d, word count= %d, charcount= %d, filename=%s\"%(numoflines,numofwords,numofchars,filename))\n\thf.close()\n else:\n print(\"source file not found\")\n\n\n\n\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# -*- coding: utf-8 -*- """ This module provides a function for splitting datasets.""" from skmultilearn.model_selection import IterativeStratification def iterative_train_test(X, y, test_size): """ Iteratively splits data with stratification. This function is based on the iterative_train_test_split function from the skmultilearn.model_selection package, but uses pandas dataframes as input and output. Parameters ---------- X : pandas dataframe Data samples. y : array or sparse matrix Indicator matrix. test_size : float [0,1] The proportion of the dataset to include in the test split, the rest will be put in the train set. Returns ------- X_train : pandas dataframe Training samples. y_train : array or sparse matrix Indicator matrix of the training samples. X_test : pandas dataframe Test samples. y_test : array or sparse matrix Indicator matrix of the test samples. """ stratifier = IterativeStratification(n_splits=2, order=2, sample_distribution_per_fold=[test_size, 1.0-test_size]) train_indexes, test_indexes = next(stratifier.split(X, y)) X_train, y_train = X.iloc[train_indexes], y[train_indexes] X_test, y_test = X.iloc[test_indexes], y[test_indexes] return X_train, y_train, X_test, y_test
normal
{ "blob_id": "c4c068c7b50d1811f224701ad7e95d88f6734230", "index": 2867, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef iterative_train_test(X, y, test_size):\n \"\"\"\n Iteratively splits data with stratification.\n\n This function is based on the iterative_train_test_split function from the\n skmultilearn.model_selection package, but uses pandas dataframes as input and output.\n\n Parameters\n ----------\n X : pandas dataframe\n Data samples.\n y : array or sparse matrix\n Indicator matrix.\n test_size : float [0,1]\n The proportion of the dataset to include in the test split, the rest will be put in the train set.\n\n Returns\n -------\n X_train : pandas dataframe\n Training samples.\n y_train : array or sparse matrix\n Indicator matrix of the training samples.\n X_test : pandas dataframe\n Test samples.\n y_test : array or sparse matrix\n Indicator matrix of the test samples.\n\n \"\"\"\n stratifier = IterativeStratification(n_splits=2, order=2,\n sample_distribution_per_fold=[test_size, 1.0 - test_size])\n train_indexes, test_indexes = next(stratifier.split(X, y))\n X_train, y_train = X.iloc[train_indexes], y[train_indexes]\n X_test, y_test = X.iloc[test_indexes], y[test_indexes]\n return X_train, y_train, X_test, y_test\n", "step-3": "<mask token>\nfrom skmultilearn.model_selection import IterativeStratification\n\n\ndef iterative_train_test(X, y, test_size):\n \"\"\"\n Iteratively splits data with stratification.\n\n This function is based on the iterative_train_test_split function from the\n skmultilearn.model_selection package, but uses pandas dataframes as input and output.\n\n Parameters\n ----------\n X : pandas dataframe\n Data samples.\n y : array or sparse matrix\n Indicator matrix.\n test_size : float [0,1]\n The proportion of the dataset to include in the test split, the rest will be put in the train set.\n\n Returns\n -------\n X_train : pandas dataframe\n Training samples.\n y_train : array or sparse matrix\n Indicator matrix of the training samples.\n X_test : pandas dataframe\n Test samples.\n y_test : array or sparse matrix\n Indicator matrix of the test samples.\n\n \"\"\"\n stratifier = IterativeStratification(n_splits=2, order=2,\n sample_distribution_per_fold=[test_size, 1.0 - test_size])\n train_indexes, test_indexes = next(stratifier.split(X, y))\n X_train, y_train = X.iloc[train_indexes], y[train_indexes]\n X_test, y_test = X.iloc[test_indexes], y[test_indexes]\n return X_train, y_train, X_test, y_test\n", "step-4": "# -*- coding: utf-8 -*-\n\"\"\" This module provides a function for splitting datasets.\"\"\"\n\nfrom skmultilearn.model_selection import IterativeStratification\n\ndef iterative_train_test(X, y, test_size):\n \"\"\"\n Iteratively splits data with stratification.\n\n This function is based on the iterative_train_test_split function from the\n skmultilearn.model_selection package, but uses pandas dataframes as input and output.\n\n Parameters\n ----------\n X : pandas dataframe\n Data samples.\n y : array or sparse matrix\n Indicator matrix.\n test_size : float [0,1]\n The proportion of the dataset to include in the test split, the rest will be put in the train set.\n\n Returns\n -------\n X_train : pandas dataframe\n Training samples.\n y_train : array or sparse matrix\n Indicator matrix of the training samples.\n X_test : pandas dataframe\n Test samples.\n y_test : array or sparse matrix\n Indicator matrix of the test samples.\n\n \"\"\"\n stratifier = IterativeStratification(n_splits=2, order=2, sample_distribution_per_fold=[test_size, 1.0-test_size])\n train_indexes, test_indexes = next(stratifier.split(X, y))\n\n X_train, y_train = X.iloc[train_indexes], y[train_indexes]\n X_test, y_test = X.iloc[test_indexes], y[test_indexes]\n\n return X_train, y_train, X_test, y_test\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django.contrib import admin from django.contrib.admin.sites import AdminSite from obp.models import * from django.utils.html import format_html from jet.admin import CompactInline #from django.utils.translation import ugettext_lazy as _ from jet.dashboard import modules from jet.dashboard.dashboard import Dashboard, AppIndexDashboard # Register your models here. #admin.site.register(Special_offers) #admin.site.register(Stock) #admin.site.register(Product_order) class ProductCompositionInline(admin.TabularInline): model = Product_composition class OrderInline(admin.TabularInline): model = Product_order class Client_OrderInline(admin.TabularInline): model = Order class MyAdminSite(AdminSite): site_header = 'Pizza-Day' index_template = "admin/index.html" @admin.register(Product) class ProductAdmin(admin.ModelAdmin): #Создание ценового фильтра class PriceListFilter(admin.SimpleListFilter): title = 'Цена' parameter_name = 'цена' #Название фильтров def lookups(self, request, model_admin): return ( ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), ('4', 'от 450'), ) #Запрос на выборку def queryset(self, request, queryset): if self.value() == '1': return queryset.filter(price__gte= 0, price__lte=199) if self.value() == '2': return queryset.filter(price__gte = 200, price__lte = 299) return go() if self.value() == '3': return queryset.filter(price__gte = 300, price__lte = 449) if self.value() == '4': return queryset.filter(price__gte=200, price__lte=299) #Отображаемые поля list_display = ('get_image_html', 'id', 'section_id', 'title', 'getSize', 'getPrice' ) list_displat_links = ('') inlines = [ ProductCompositionInline ] #Поле по которому можно сделать поиск search_fields = ['title'] #Список фильтраций list_filter = ['section_id', PriceListFilter] #Получение html блока с рисунком товара def get_image_html(self, obj): return format_html('<img src = "{}" style = "height: 30px; border-radius: 5px;"></img>', obj.image.url) get_image_html.short_description = "Фото товара" #Получение цены def getPrice(self, obj): try: object = Stock.objects.get( id = obj.id , status = True) return format_html("<del>{} грн.</del> <span>{} грн. </span>".format(obj.price, object.value) ) except: pass #else: return format_html("<span>" + str( obj.price ) + " грн." + "</span>") getPrice.short_description = "Цена" #Получение строки веса + его еденицу измерения def getSize(self, obj): return str( obj.size ) + obj.unitSize getSize.short_description = "Вес" @admin.register(Order) class OrderAdmin(admin.ModelAdmin): class PriceListFilter(admin.SimpleListFilter): title = 'Цена' parameter_name = 'цена' def lookups(self, request, model_admin): return ( ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), ('4', 'от 450'), ) def queryset(self, request, queryset): if self.value() == '1': return queryset.filter(price__gte= 0, price__lte=199) if self.value() == '2': return queryset.filter(price__gte = 200, price__lte = 299) if self.value() == '3': return queryset.filter(price__gte = 300, price__lte = 449) if self.value() == '4': return queryset.filter(price__gte=200, price__lte=299) list_display = ('id', 'dateTimeOrder', 'price', 'status' ) list_filter = ['dateTimeOrder', PriceListFilter, "status"] list_editable = ["status"] inlines = [ OrderInline ] @admin.register(Client) class ClientAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'phone_number' ) inlines = [ Client_OrderInline ] @admin.register(Section) class SectionAdmin(admin.ModelAdmin): list_display = ('id', 'title') class StockAdmin(admin.ModelAdmin): list_display = ("product_id", "value", "status" ) search_fields = ['product_id__title'] list_filter = ['status'] admin_site = MyAdminSite(name='myadmin') admin_site.register(Product, ProductAdmin) admin_site.register(Client, ClientAdmin) admin_site.register(Order, OrderAdmin) admin_site.register(Section, SectionAdmin) admin_site.register(Stock, StockAdmin) admin_site.register(Product_comment) admin_site.register(Client_Auth) admin_site.register(Special_offers) admin_site.register(Product_rating) # # # class CustomIndexDashboard(Dashboard): # columns = 3 # # def init_with_context(self, context): # self.available_children.append(modules.LinkList) # self.children.append(modules.LinkList( # _('Support'), # children=[ # { # 'title': _('Django documentation'), # 'url': 'http://docs.djangoproject.com/', # 'external': True, # }, # { # 'title': _('Django "django-users" mailing list'), # 'url': 'http://groups.google.com/group/django-users', # 'external': True, # }, # { # 'title': _('Django irc channel'), # 'url': 'irc://irc.freenode.net/django', # 'external': True, # }, # ], # column=0, # order=0 # ))
normal
{ "blob_id": "d301ffa790d6444519e354a2b6f8d65f67d380c0", "index": 1739, "step-1": "<mask token>\n\n\nclass Client_OrderInline(admin.TabularInline):\n <mask token>\n\n\nclass MyAdminSite(AdminSite):\n site_header = 'Pizza-Day'\n index_template = 'admin/index.html'\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n return go()\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = ('get_image_html', 'id', 'section_id', 'title',\n 'getSize', 'getPrice')\n list_displat_links = ''\n inlines = [ProductCompositionInline]\n search_fields = ['title']\n list_filter = ['section_id', PriceListFilter]\n\n def get_image_html(self, obj):\n return format_html(\n '<img src = \"{}\" style = \"height: 30px; border-radius: 5px;\"></img>'\n , obj.image.url)\n get_image_html.short_description = 'Фото товара'\n\n def getPrice(self, obj):\n try:\n object = Stock.objects.get(id=obj.id, status=True)\n return format_html('<del>{} грн.</del> <span>{} грн. </span>'.\n format(obj.price, object.value))\n except:\n pass\n return format_html('<span>' + str(obj.price) + ' грн.' + '</span>')\n getPrice.short_description = 'Цена'\n\n def getSize(self, obj):\n return str(obj.size) + obj.unitSize\n getSize.short_description = 'Вес'\n\n\[email protected](Order)\nclass OrderAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = 'id', 'dateTimeOrder', 'price', 'status'\n list_filter = ['dateTimeOrder', PriceListFilter, 'status']\n list_editable = ['status']\n inlines = [OrderInline]\n\n\[email protected](Client)\nclass ClientAdmin(admin.ModelAdmin):\n list_display = 'id', 'name', 'phone_number'\n inlines = [Client_OrderInline]\n\n\[email protected](Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = 'id', 'title'\n\n\nclass StockAdmin(admin.ModelAdmin):\n list_display = 'product_id', 'value', 'status'\n search_fields = ['product_id__title']\n list_filter = ['status']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Client_OrderInline(admin.TabularInline):\n model = Order\n\n\nclass MyAdminSite(AdminSite):\n site_header = 'Pizza-Day'\n index_template = 'admin/index.html'\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n return go()\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = ('get_image_html', 'id', 'section_id', 'title',\n 'getSize', 'getPrice')\n list_displat_links = ''\n inlines = [ProductCompositionInline]\n search_fields = ['title']\n list_filter = ['section_id', PriceListFilter]\n\n def get_image_html(self, obj):\n return format_html(\n '<img src = \"{}\" style = \"height: 30px; border-radius: 5px;\"></img>'\n , obj.image.url)\n get_image_html.short_description = 'Фото товара'\n\n def getPrice(self, obj):\n try:\n object = Stock.objects.get(id=obj.id, status=True)\n return format_html('<del>{} грн.</del> <span>{} грн. </span>'.\n format(obj.price, object.value))\n except:\n pass\n return format_html('<span>' + str(obj.price) + ' грн.' + '</span>')\n getPrice.short_description = 'Цена'\n\n def getSize(self, obj):\n return str(obj.size) + obj.unitSize\n getSize.short_description = 'Вес'\n\n\[email protected](Order)\nclass OrderAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = 'id', 'dateTimeOrder', 'price', 'status'\n list_filter = ['dateTimeOrder', PriceListFilter, 'status']\n list_editable = ['status']\n inlines = [OrderInline]\n\n\[email protected](Client)\nclass ClientAdmin(admin.ModelAdmin):\n list_display = 'id', 'name', 'phone_number'\n inlines = [Client_OrderInline]\n\n\[email protected](Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = 'id', 'title'\n\n\nclass StockAdmin(admin.ModelAdmin):\n list_display = 'product_id', 'value', 'status'\n search_fields = ['product_id__title']\n list_filter = ['status']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass OrderInline(admin.TabularInline):\n <mask token>\n\n\nclass Client_OrderInline(admin.TabularInline):\n model = Order\n\n\nclass MyAdminSite(AdminSite):\n site_header = 'Pizza-Day'\n index_template = 'admin/index.html'\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n return go()\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = ('get_image_html', 'id', 'section_id', 'title',\n 'getSize', 'getPrice')\n list_displat_links = ''\n inlines = [ProductCompositionInline]\n search_fields = ['title']\n list_filter = ['section_id', PriceListFilter]\n\n def get_image_html(self, obj):\n return format_html(\n '<img src = \"{}\" style = \"height: 30px; border-radius: 5px;\"></img>'\n , obj.image.url)\n get_image_html.short_description = 'Фото товара'\n\n def getPrice(self, obj):\n try:\n object = Stock.objects.get(id=obj.id, status=True)\n return format_html('<del>{} грн.</del> <span>{} грн. </span>'.\n format(obj.price, object.value))\n except:\n pass\n return format_html('<span>' + str(obj.price) + ' грн.' + '</span>')\n getPrice.short_description = 'Цена'\n\n def getSize(self, obj):\n return str(obj.size) + obj.unitSize\n getSize.short_description = 'Вес'\n\n\[email protected](Order)\nclass OrderAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = 'id', 'dateTimeOrder', 'price', 'status'\n list_filter = ['dateTimeOrder', PriceListFilter, 'status']\n list_editable = ['status']\n inlines = [OrderInline]\n\n\[email protected](Client)\nclass ClientAdmin(admin.ModelAdmin):\n list_display = 'id', 'name', 'phone_number'\n inlines = [Client_OrderInline]\n\n\[email protected](Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = 'id', 'title'\n\n\nclass StockAdmin(admin.ModelAdmin):\n list_display = 'product_id', 'value', 'status'\n search_fields = ['product_id__title']\n list_filter = ['status']\n\n\n<mask token>\n", "step-4": "from django.contrib import admin\nfrom django.contrib.admin.sites import AdminSite\nfrom obp.models import *\nfrom django.utils.html import format_html\nfrom jet.admin import CompactInline\nfrom jet.dashboard import modules\nfrom jet.dashboard.dashboard import Dashboard, AppIndexDashboard\n\n\nclass ProductCompositionInline(admin.TabularInline):\n model = Product_composition\n\n\nclass OrderInline(admin.TabularInline):\n model = Product_order\n\n\nclass Client_OrderInline(admin.TabularInline):\n model = Order\n\n\nclass MyAdminSite(AdminSite):\n site_header = 'Pizza-Day'\n index_template = 'admin/index.html'\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n return go()\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = ('get_image_html', 'id', 'section_id', 'title',\n 'getSize', 'getPrice')\n list_displat_links = ''\n inlines = [ProductCompositionInline]\n search_fields = ['title']\n list_filter = ['section_id', PriceListFilter]\n\n def get_image_html(self, obj):\n return format_html(\n '<img src = \"{}\" style = \"height: 30px; border-radius: 5px;\"></img>'\n , obj.image.url)\n get_image_html.short_description = 'Фото товара'\n\n def getPrice(self, obj):\n try:\n object = Stock.objects.get(id=obj.id, status=True)\n return format_html('<del>{} грн.</del> <span>{} грн. </span>'.\n format(obj.price, object.value))\n except:\n pass\n return format_html('<span>' + str(obj.price) + ' грн.' + '</span>')\n getPrice.short_description = 'Цена'\n\n def getSize(self, obj):\n return str(obj.size) + obj.unitSize\n getSize.short_description = 'Вес'\n\n\[email protected](Order)\nclass OrderAdmin(admin.ModelAdmin):\n\n\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n\n def lookups(self, request, model_admin):\n return ('1', 'до 199'), ('2', '200 - 299'), ('3', '300 - 449'), (\n '4', 'от 450')\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte=0, price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte=200, price__lte=299)\n if self.value() == '3':\n return queryset.filter(price__gte=300, price__lte=449)\n if self.value() == '4':\n return queryset.filter(price__gte=200, price__lte=299)\n list_display = 'id', 'dateTimeOrder', 'price', 'status'\n list_filter = ['dateTimeOrder', PriceListFilter, 'status']\n list_editable = ['status']\n inlines = [OrderInline]\n\n\[email protected](Client)\nclass ClientAdmin(admin.ModelAdmin):\n list_display = 'id', 'name', 'phone_number'\n inlines = [Client_OrderInline]\n\n\[email protected](Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = 'id', 'title'\n\n\nclass StockAdmin(admin.ModelAdmin):\n list_display = 'product_id', 'value', 'status'\n search_fields = ['product_id__title']\n list_filter = ['status']\n\n\nadmin_site = MyAdminSite(name='myadmin')\nadmin_site.register(Product, ProductAdmin)\nadmin_site.register(Client, ClientAdmin)\nadmin_site.register(Order, OrderAdmin)\nadmin_site.register(Section, SectionAdmin)\nadmin_site.register(Stock, StockAdmin)\nadmin_site.register(Product_comment)\nadmin_site.register(Client_Auth)\nadmin_site.register(Special_offers)\nadmin_site.register(Product_rating)\n", "step-5": "from django.contrib import admin\nfrom django.contrib.admin.sites import AdminSite\nfrom obp.models import *\nfrom django.utils.html import format_html\nfrom jet.admin import CompactInline\n#from django.utils.translation import ugettext_lazy as _\nfrom jet.dashboard import modules\nfrom jet.dashboard.dashboard import Dashboard, AppIndexDashboard\n# Register your models here.\n\n#admin.site.register(Special_offers)\n#admin.site.register(Stock)\n#admin.site.register(Product_order)\nclass ProductCompositionInline(admin.TabularInline):\n model = Product_composition\n\nclass OrderInline(admin.TabularInline):\n model = Product_order\n\nclass Client_OrderInline(admin.TabularInline):\n model = Order\n\nclass MyAdminSite(AdminSite):\n site_header = 'Pizza-Day'\n index_template = \"admin/index.html\"\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n #Создание ценового фильтра\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n #Название фильтров\n def lookups(self, request, model_admin):\n return (\n ('1', 'до 199'),\n ('2', '200 - 299'),\n ('3', '300 - 449'),\n ('4', 'от 450'),\n )\n #Запрос на выборку\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte= 0,\n price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte = 200,\n price__lte = 299)\n return go()\n if self.value() == '3':\n return queryset.filter(price__gte = 300,\n price__lte = 449)\n if self.value() == '4':\n return queryset.filter(price__gte=200,\n price__lte=299)\n #Отображаемые поля\n list_display = ('get_image_html', 'id', 'section_id', 'title', 'getSize', 'getPrice' )\n\n list_displat_links = ('')\n\n inlines = [\n ProductCompositionInline\n ]\n #Поле по которому можно сделать поиск\n search_fields = ['title']\n #Список фильтраций\n list_filter = ['section_id', PriceListFilter]\n\n #Получение html блока с рисунком товара\n def get_image_html(self, obj):\n return format_html('<img src = \"{}\" style = \"height: 30px; border-radius: 5px;\"></img>', obj.image.url)\n get_image_html.short_description = \"Фото товара\"\n\n #Получение цены\n def getPrice(self, obj):\n\n try:\n object = Stock.objects.get( id = obj.id , status = True)\n return format_html(\"<del>{} грн.</del> <span>{} грн. </span>\".format(obj.price, object.value) )\n except:\n pass\n #else:\n return format_html(\"<span>\" + str( obj.price ) + \" грн.\" + \"</span>\")\n getPrice.short_description = \"Цена\"\n\n #Получение строки веса + его еденицу измерения\n def getSize(self, obj):\n return str( obj.size ) + obj.unitSize\n getSize.short_description = \"Вес\"\n\n\[email protected](Order)\nclass OrderAdmin(admin.ModelAdmin):\n class PriceListFilter(admin.SimpleListFilter):\n title = 'Цена'\n parameter_name = 'цена'\n def lookups(self, request, model_admin):\n return (\n ('1', 'до 199'),\n ('2', '200 - 299'),\n ('3', '300 - 449'),\n ('4', 'от 450'),\n )\n\n def queryset(self, request, queryset):\n if self.value() == '1':\n return queryset.filter(price__gte= 0,\n price__lte=199)\n if self.value() == '2':\n return queryset.filter(price__gte = 200,\n price__lte = 299)\n if self.value() == '3':\n return queryset.filter(price__gte = 300,\n price__lte = 449)\n if self.value() == '4':\n return queryset.filter(price__gte=200,\n price__lte=299)\n\n list_display = ('id', 'dateTimeOrder', 'price', 'status' )\n list_filter = ['dateTimeOrder', PriceListFilter, \"status\"]\n list_editable = [\"status\"]\n\n inlines = [\n OrderInline\n ]\n\[email protected](Client)\nclass ClientAdmin(admin.ModelAdmin):\n list_display = ('id', 'name', 'phone_number' )\n inlines = [\n Client_OrderInline\n ]\n\[email protected](Section)\nclass SectionAdmin(admin.ModelAdmin):\n list_display = ('id', 'title')\n\n\nclass StockAdmin(admin.ModelAdmin):\n list_display = (\"product_id\", \"value\", \"status\" )\n search_fields = ['product_id__title']\n list_filter = ['status']\n\nadmin_site = MyAdminSite(name='myadmin')\nadmin_site.register(Product, ProductAdmin)\nadmin_site.register(Client, ClientAdmin)\nadmin_site.register(Order, OrderAdmin)\nadmin_site.register(Section, SectionAdmin)\nadmin_site.register(Stock, StockAdmin)\nadmin_site.register(Product_comment)\nadmin_site.register(Client_Auth)\nadmin_site.register(Special_offers)\nadmin_site.register(Product_rating)\n\n\n\n# \n#\n# class CustomIndexDashboard(Dashboard):\n# columns = 3\n#\n# def init_with_context(self, context):\n# self.available_children.append(modules.LinkList)\n# self.children.append(modules.LinkList(\n# _('Support'),\n# children=[\n# {\n# 'title': _('Django documentation'),\n# 'url': 'http://docs.djangoproject.com/',\n# 'external': True,\n# },\n# {\n# 'title': _('Django \"django-users\" mailing list'),\n# 'url': 'http://groups.google.com/group/django-users',\n# 'external': True,\n# },\n# {\n# 'title': _('Django irc channel'),\n# 'url': 'irc://irc.freenode.net/django',\n# 'external': True,\n# },\n# ],\n# column=0,\n# order=0\n# ))\n", "step-ids": [ 16, 17, 18, 24, 25 ] }
[ 16, 17, 18, 24, 25 ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 6 10:05:25 2019 @author: MCA """ import smtplib, ssl from email import encoders from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart import os,sys import time def loadFiles(subdir, filetype): """ example: dirs = ["dir1", "dir2"] file_type = ".dat" files, keys, data = loadFiles(dirs[0], file_type) """ dirname = os.path.dirname(__file__) path = os.path.join(dirname, (subdir+"/")) files_path = [] fileNamesFiltered = [] for root, dirs, files in os.walk(path): for i, filename in enumerate(files): if filename[(len(filename))-len(filetype):] == filetype: # print(filename) filename_path = path + filename files_path.append(filename_path) fileNamesFiltered.append(filename) return fileNamesFiltered def sendMail(filename): smtp_server = "smtp.seznam.cz" port = 25 # For starttls sender_email = "[email protected]" #password = input("Type your password and press enter: ") password = "xxxx" # Create a secure SSL context context = ssl.create_default_context() receiver_email=sender_email #compose an email message = MIMEMultipart("alternative") message["Subject"] = ("analysis status check: "+ str(filename)) message["From"] = sender_email message["To"] = receiver_email text = "analysis status check" part1 = MIMEText(text, "plain") message.attach(part1) #send file # filename = file try: with open(filename, "rb") as attachment: # Add file as application/octet-stream # Email client can usually download this automatically as attachment file = MIMEBase("application", "octet-stream") file.set_payload(attachment.read()) encoders.encode_base64(file) file.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) message.attach(file) except: print("file not found") # Try to log in to server and send email try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(sender_email, password) print("logged in") # TODO: Send email here server.sendmail(sender_email, receiver_email, message.as_string()) print("mail sent") except Exception as e: # Print any error messages to stdout print(e) finally: server.quit() #-------------------------------------------------------------------------------------- if __name__ == "__main__": run = True directory = "/folder/folder" fileType = ".xxx" name = "xxxxxx_xxx__xxx.xxx" while run == True: names = loadFiles(directory, fileType) print("running") if name in names: print("file found:", name) f = open(name, "r") for line in f: if "THE ANALYSIS HAS" in line: sendMail(name) print("file sent") run = False print("done") sys.exit() time.sleep(300)
normal
{ "blob_id": "b310c35b781e3221e2dacc7717ed77e20001bafa", "index": 5109, "step-1": "<mask token>\n\n\ndef loadFiles(subdir, filetype):\n \"\"\"\n example:\n dirs = [\"dir1\", \"dir2\"]\n file_type = \".dat\"\n files, keys, data = loadFiles(dirs[0], file_type)\n \n \"\"\"\n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, subdir + '/')\n files_path = []\n fileNamesFiltered = []\n for root, dirs, files in os.walk(path):\n for i, filename in enumerate(files):\n if filename[len(filename) - len(filetype):] == filetype:\n filename_path = path + filename\n files_path.append(filename_path)\n fileNamesFiltered.append(filename)\n return fileNamesFiltered\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef loadFiles(subdir, filetype):\n \"\"\"\n example:\n dirs = [\"dir1\", \"dir2\"]\n file_type = \".dat\"\n files, keys, data = loadFiles(dirs[0], file_type)\n \n \"\"\"\n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, subdir + '/')\n files_path = []\n fileNamesFiltered = []\n for root, dirs, files in os.walk(path):\n for i, filename in enumerate(files):\n if filename[len(filename) - len(filetype):] == filetype:\n filename_path = path + filename\n files_path.append(filename_path)\n fileNamesFiltered.append(filename)\n return fileNamesFiltered\n\n\ndef sendMail(filename):\n smtp_server = 'smtp.seznam.cz'\n port = 25\n sender_email = '[email protected]'\n password = 'xxxx'\n context = ssl.create_default_context()\n receiver_email = sender_email\n message = MIMEMultipart('alternative')\n message['Subject'] = 'analysis status check: ' + str(filename)\n message['From'] = sender_email\n message['To'] = receiver_email\n text = 'analysis status check'\n part1 = MIMEText(text, 'plain')\n message.attach(part1)\n try:\n with open(filename, 'rb') as attachment:\n file = MIMEBase('application', 'octet-stream')\n file.set_payload(attachment.read())\n encoders.encode_base64(file)\n file.add_header('Content-Disposition',\n f'attachment; filename= {filename}')\n message.attach(file)\n except:\n print('file not found')\n try:\n server = smtplib.SMTP(smtp_server, port)\n server.ehlo()\n server.starttls(context=context)\n server.ehlo()\n server.login(sender_email, password)\n print('logged in')\n server.sendmail(sender_email, receiver_email, message.as_string())\n print('mail sent')\n except Exception as e:\n print(e)\n finally:\n server.quit()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef loadFiles(subdir, filetype):\n \"\"\"\n example:\n dirs = [\"dir1\", \"dir2\"]\n file_type = \".dat\"\n files, keys, data = loadFiles(dirs[0], file_type)\n \n \"\"\"\n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, subdir + '/')\n files_path = []\n fileNamesFiltered = []\n for root, dirs, files in os.walk(path):\n for i, filename in enumerate(files):\n if filename[len(filename) - len(filetype):] == filetype:\n filename_path = path + filename\n files_path.append(filename_path)\n fileNamesFiltered.append(filename)\n return fileNamesFiltered\n\n\ndef sendMail(filename):\n smtp_server = 'smtp.seznam.cz'\n port = 25\n sender_email = '[email protected]'\n password = 'xxxx'\n context = ssl.create_default_context()\n receiver_email = sender_email\n message = MIMEMultipart('alternative')\n message['Subject'] = 'analysis status check: ' + str(filename)\n message['From'] = sender_email\n message['To'] = receiver_email\n text = 'analysis status check'\n part1 = MIMEText(text, 'plain')\n message.attach(part1)\n try:\n with open(filename, 'rb') as attachment:\n file = MIMEBase('application', 'octet-stream')\n file.set_payload(attachment.read())\n encoders.encode_base64(file)\n file.add_header('Content-Disposition',\n f'attachment; filename= {filename}')\n message.attach(file)\n except:\n print('file not found')\n try:\n server = smtplib.SMTP(smtp_server, port)\n server.ehlo()\n server.starttls(context=context)\n server.ehlo()\n server.login(sender_email, password)\n print('logged in')\n server.sendmail(sender_email, receiver_email, message.as_string())\n print('mail sent')\n except Exception as e:\n print(e)\n finally:\n server.quit()\n\n\nif __name__ == '__main__':\n run = True\n directory = '/folder/folder'\n fileType = '.xxx'\n name = 'xxxxxx_xxx__xxx.xxx'\n while run == True:\n names = loadFiles(directory, fileType)\n print('running')\n if name in names:\n print('file found:', name)\n f = open(name, 'r')\n for line in f:\n if 'THE ANALYSIS HAS' in line:\n sendMail(name)\n print('file sent')\n run = False\n print('done')\n sys.exit()\n time.sleep(300)\n", "step-4": "<mask token>\nimport smtplib, ssl\nfrom email import encoders\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nimport os, sys\nimport time\n\n\ndef loadFiles(subdir, filetype):\n \"\"\"\n example:\n dirs = [\"dir1\", \"dir2\"]\n file_type = \".dat\"\n files, keys, data = loadFiles(dirs[0], file_type)\n \n \"\"\"\n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, subdir + '/')\n files_path = []\n fileNamesFiltered = []\n for root, dirs, files in os.walk(path):\n for i, filename in enumerate(files):\n if filename[len(filename) - len(filetype):] == filetype:\n filename_path = path + filename\n files_path.append(filename_path)\n fileNamesFiltered.append(filename)\n return fileNamesFiltered\n\n\ndef sendMail(filename):\n smtp_server = 'smtp.seznam.cz'\n port = 25\n sender_email = '[email protected]'\n password = 'xxxx'\n context = ssl.create_default_context()\n receiver_email = sender_email\n message = MIMEMultipart('alternative')\n message['Subject'] = 'analysis status check: ' + str(filename)\n message['From'] = sender_email\n message['To'] = receiver_email\n text = 'analysis status check'\n part1 = MIMEText(text, 'plain')\n message.attach(part1)\n try:\n with open(filename, 'rb') as attachment:\n file = MIMEBase('application', 'octet-stream')\n file.set_payload(attachment.read())\n encoders.encode_base64(file)\n file.add_header('Content-Disposition',\n f'attachment; filename= {filename}')\n message.attach(file)\n except:\n print('file not found')\n try:\n server = smtplib.SMTP(smtp_server, port)\n server.ehlo()\n server.starttls(context=context)\n server.ehlo()\n server.login(sender_email, password)\n print('logged in')\n server.sendmail(sender_email, receiver_email, message.as_string())\n print('mail sent')\n except Exception as e:\n print(e)\n finally:\n server.quit()\n\n\nif __name__ == '__main__':\n run = True\n directory = '/folder/folder'\n fileType = '.xxx'\n name = 'xxxxxx_xxx__xxx.xxx'\n while run == True:\n names = loadFiles(directory, fileType)\n print('running')\n if name in names:\n print('file found:', name)\n f = open(name, 'r')\n for line in f:\n if 'THE ANALYSIS HAS' in line:\n sendMail(name)\n print('file sent')\n run = False\n print('done')\n sys.exit()\n time.sleep(300)\n", "step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 6 10:05:25 2019\n\n@author: MCA\n\"\"\"\n\n\nimport smtplib, ssl\n\nfrom email import encoders\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\n\nimport os,sys\nimport time\n\ndef loadFiles(subdir, filetype):\n \"\"\"\n example:\n dirs = [\"dir1\", \"dir2\"]\n file_type = \".dat\"\n files, keys, data = loadFiles(dirs[0], file_type)\n \n \"\"\" \n \n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, (subdir+\"/\"))\n files_path = []\n fileNamesFiltered = []\n for root, dirs, files in os.walk(path): \n for i, filename in enumerate(files):\n if filename[(len(filename))-len(filetype):] == filetype:\n# print(filename)\n filename_path = path + filename\n files_path.append(filename_path)\n fileNamesFiltered.append(filename)\n \n \n return fileNamesFiltered\n\n\n\ndef sendMail(filename):\n smtp_server = \"smtp.seznam.cz\"\n port = 25 # For starttls\n sender_email = \"[email protected]\"\n #password = input(\"Type your password and press enter: \")\n password = \"xxxx\"\n \n # Create a secure SSL context\n context = ssl.create_default_context()\n receiver_email=sender_email\n \n \n #compose an email\n message = MIMEMultipart(\"alternative\")\n message[\"Subject\"] = (\"analysis status check: \"+ str(filename))\n message[\"From\"] = sender_email\n message[\"To\"] = receiver_email\n \n text = \"analysis status check\"\n part1 = MIMEText(text, \"plain\")\n message.attach(part1)\n \n \n #send file\n# filename = file\n try:\n with open(filename, \"rb\") as attachment:\n # Add file as application/octet-stream\n # Email client can usually download this automatically as attachment\n file = MIMEBase(\"application\", \"octet-stream\")\n file.set_payload(attachment.read())\n encoders.encode_base64(file)\n file.add_header(\n \"Content-Disposition\",\n f\"attachment; filename= {filename}\",\n )\n message.attach(file)\n except:\n print(\"file not found\")\n \n # Try to log in to server and send email\n try:\n server = smtplib.SMTP(smtp_server,port)\n server.ehlo() # Can be omitted\n server.starttls(context=context) # Secure the connection\n server.ehlo() # Can be omitted\n server.login(sender_email, password)\n print(\"logged in\")\n # TODO: Send email here\n server.sendmail(sender_email, receiver_email, message.as_string())\n print(\"mail sent\")\n except Exception as e:\n # Print any error messages to stdout\n print(e)\n finally:\n server.quit() \n\n\n#--------------------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n run = True\n directory = \"/folder/folder\"\n fileType = \".xxx\"\n name = \"xxxxxx_xxx__xxx.xxx\"\n \n while run == True:\n \n names = loadFiles(directory, fileType)\n print(\"running\")\n if name in names:\n print(\"file found:\", name)\n f = open(name, \"r\")\n for line in f:\n if \"THE ANALYSIS HAS\" in line: \n sendMail(name)\n print(\"file sent\")\n run = False\n print(\"done\")\n sys.exit()\n time.sleep(300)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
#!/usr/bin/env python3 import argparse import os import sys,shutil from shutil import make_archive import pathlib from phpManager import execute,execute_outputfile from datetime import date,datetime import re import pymysql import tarfile def append_log(log,message): f = open(log, "a+") today = datetime.now() f.write("%s %s \n" % (today.strftime("%Y-%m-%d %H:%M:%S"), message)) f.close() def get_root_pass(): with open("/root/.my.cnf") as fp: lines = fp.read().splitlines() for line in lines: grep = re.findall(r'password', line) if grep: pwrd = line.split('"')[1] return pwrd def get_db_name(argv): try: pwrd = get_root_pass() db = pymysql.connect("localhost","root",pwrd,"secure_vps") cursor = db.cursor() cursor.execute("select id,db_name from provision where provision_name='%s'" % argv) data = cursor.fetchone() db.close() return data except pymysql.err.OperationalError as err: print (' An error has occurred \n', err) except pymysql.err.InternalError as err: print (' An error has occurred \n', err) def backup_db(argv): data = get_db_name(argv) db_name = data[1] try: sqldir = '/home/kusanagi/'+argv+'/sql_backup/' p = pathlib.Path(sqldir) if not p.exists(): p.mkdir(mode=0o755, parents=True, exist_ok=True) shutil.chown(sqldir,'kusanagi','kusanagi') except BaseException as error: print(error) pwrd = get_root_pass() log = '/home/kusanagi/'+argv+'/log/backup.log' mess = 'Backed up database '+db_name append_log(log,mess) cmd = 'mysqldump --single-transaction -p'+pwrd+' --databases '+db_name+' | gzip > '+sqldir+db_name+'.sql.gz' execute_outputfile(cmd,log) def update_backup_record(argv,backup_type,result): pwrd = get_root_pass() data = get_db_name(argv) provi_id = data[0] log = '/home/kusanagi/'+argv+'/log/backup.log' db = pymysql.connect("localhost","root",pwrd,"secure_vps") cursor = db.cursor() cursor.execute("select id from logs where provision_id=%d and status=0 and backup_type=%d" % (provi_id,backup_type)) res = cursor.fetchone() record_id = res[0] if result: cursor.execute("update logs set status=1,message='Done' where provision_id=%d and id=%d" % (provi_id,record_id)) else: cursor.execute("update logs set status=-1,message='Failed. See %s' where provision_id=%d and id=%d" % (log,provi_id,record_id)) db.commit() db.close() def compress_provision_dir(argv,chdir=''): date = datetime.now() today = date.strftime("%Y-%m-%d") if chdir: tarname = chdir+argv+'.'+today else: tarname = '/home/kusanagi/backup/'+argv+'.'+today source_dir = '/home/kusanagi/'+argv shutil.make_archive(tarname,"gztar",source_dir) return tarname def local_backup(argv): append_log('/home/kusanagi/'+argv+'/log/backup.log', '--- Local backup') backup_db(argv) tarname = compress_provision_dir(argv) tar_file=pathlib.Path(tarname+'.tar.gz') if tar_file.exists(): update_backup_record(argv,0,1) else: update_backup_record(argv,0,0) def check_ssh_conn(argv,remote_user,remote_host,remote_port,remote_pass): cmd = 'sshpass -p "'+remote_pass+'" ssh -o StrictHostKeyChecking=no -p '+remote_port+' -q '+remote_user+'@'+remote_host+' exit;echo $?' res = execute(cmd) log = '/home/kusanagi/'+argv+'/log/backup.log' if int(res) == 0: #print('Connect OK \n') pass else: append_log(log, 'Remote connection failed. Can not issue remote backup') update_backup_record(argv,1,0) sys.exit(1) def remote_backup(argv, remote_user, remote_host, remote_port, remote_pass, remote_dest): log = '/home/kusanagi/'+argv+'/log/backup.log' append_log(log, '--- Remote backup') check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass) backup_db(argv) tarname = compress_provision_dir(argv,'/home/kusanagi/') conf_ssh = '/etc/ssh/ssh_config' with open(conf_ssh) as fp: lines = fp.read().splitlines() for line in lines: grep = re.findall(remote_host, line) if grep: break if not grep: #configure stricthostkey ssh f = open(conf_ssh,"a+") f.write('Host %s\n\tStrictHostKeyChecking no\n' % remote_host) f.close() cmd = 'sshpass -p "'+remote_pass+'" rsync --remove-source-files -azhe \'ssh -p'+remote_port+'\' '+tarname+'.tar.gz '+remote_user+'@'+remote_host+':'+remote_dest+' 2>> '+log+' ; echo $?' res = execute(cmd) if int(res) == 0: update_backup_record(argv,1,1) else: update_backup_record(argv,1,0) def drive_backup(argv,drive_dir): log = '/home/kusanagi/'+argv+'/log/backup.log' append_log(log,'--- Backup to Google Drive') backup_db(argv) tarname = compress_provision_dir(argv,'/home/kusanagi/') cmd = 'rclone copy '+tarname+'.tar.gz GGD1:'+drive_dir+ ' 2>> '+log+' ; echo $?' res = execute(cmd) if int(res) == 0: update_backup_record(argv,2,1) else: update_backup_record(argv,2,0) os.remove(tarname+'.tar.gz') def get_options(argv): parser = argparse.ArgumentParser() parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive']) parser.add_argument('options', nargs=argparse.REMAINDER) return parser.parse_args(argv) def main(): args=get_options(sys.argv[1:]) #pwrd = get_root_pass() options = ' '.join(map(str, args.options)) if args.mode == 'local': local_backup(*args.options) elif args.mode == 'remote': remote_backup(*args.options) else: drive_backup(*args.options) if __name__ == '__main__': main()
normal
{ "blob_id": "e09af436f2fb37d16427aa0b1416d6f2d59ad6c4", "index": 214, "step-1": "<mask token>\n\n\ndef append_log(log, message):\n f = open(log, 'a+')\n today = datetime.now()\n f.write('%s %s \\n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message))\n f.close()\n\n\ndef get_root_pass():\n with open('/root/.my.cnf') as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall('password', line)\n if grep:\n pwrd = line.split('\"')[1]\n return pwrd\n\n\n<mask token>\n\n\ndef backup_db(argv):\n data = get_db_name(argv)\n db_name = data[1]\n try:\n sqldir = '/home/kusanagi/' + argv + '/sql_backup/'\n p = pathlib.Path(sqldir)\n if not p.exists():\n p.mkdir(mode=493, parents=True, exist_ok=True)\n shutil.chown(sqldir, 'kusanagi', 'kusanagi')\n except BaseException as error:\n print(error)\n pwrd = get_root_pass()\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n mess = 'Backed up database ' + db_name\n append_log(log, mess)\n cmd = ('mysqldump --single-transaction -p' + pwrd + ' --databases ' +\n db_name + ' | gzip > ' + sqldir + db_name + '.sql.gz')\n execute_outputfile(cmd, log)\n\n\n<mask token>\n\n\ndef compress_provision_dir(argv, chdir=''):\n date = datetime.now()\n today = date.strftime('%Y-%m-%d')\n if chdir:\n tarname = chdir + argv + '.' + today\n else:\n tarname = '/home/kusanagi/backup/' + argv + '.' + today\n source_dir = '/home/kusanagi/' + argv\n shutil.make_archive(tarname, 'gztar', source_dir)\n return tarname\n\n\ndef local_backup(argv):\n append_log('/home/kusanagi/' + argv + '/log/backup.log', '--- Local backup'\n )\n backup_db(argv)\n tarname = compress_provision_dir(argv)\n tar_file = pathlib.Path(tarname + '.tar.gz')\n if tar_file.exists():\n update_backup_record(argv, 0, 1)\n else:\n update_backup_record(argv, 0, 0)\n\n\ndef check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass):\n cmd = ('sshpass -p \"' + remote_pass +\n '\" ssh -o StrictHostKeyChecking=no -p ' + remote_port + ' -q ' +\n remote_user + '@' + remote_host + ' exit;echo $?')\n res = execute(cmd)\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n if int(res) == 0:\n pass\n else:\n append_log(log, 'Remote connection failed. Can not issue remote backup'\n )\n update_backup_record(argv, 1, 0)\n sys.exit(1)\n\n\ndef remote_backup(argv, remote_user, remote_host, remote_port, remote_pass,\n remote_dest):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Remote backup')\n check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass)\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n conf_ssh = '/etc/ssh/ssh_config'\n with open(conf_ssh) as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(remote_host, line)\n if grep:\n break\n if not grep:\n f = open(conf_ssh, 'a+')\n f.write('Host %s\\n\\tStrictHostKeyChecking no\\n' % remote_host)\n f.close()\n cmd = ('sshpass -p \"' + remote_pass +\n '\" rsync --remove-source-files -azhe \\'ssh -p' + remote_port + \"' \" +\n tarname + '.tar.gz ' + remote_user + '@' + remote_host + ':' +\n remote_dest + ' 2>> ' + log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 1, 1)\n else:\n update_backup_record(argv, 1, 0)\n\n\ndef drive_backup(argv, drive_dir):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Backup to Google Drive')\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n cmd = ('rclone copy ' + tarname + '.tar.gz GGD1:' + drive_dir + ' 2>> ' +\n log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 2, 1)\n else:\n update_backup_record(argv, 2, 0)\n os.remove(tarname + '.tar.gz')\n\n\ndef get_options(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive'])\n parser.add_argument('options', nargs=argparse.REMAINDER)\n return parser.parse_args(argv)\n\n\ndef main():\n args = get_options(sys.argv[1:])\n options = ' '.join(map(str, args.options))\n if args.mode == 'local':\n local_backup(*args.options)\n elif args.mode == 'remote':\n remote_backup(*args.options)\n else:\n drive_backup(*args.options)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef append_log(log, message):\n f = open(log, 'a+')\n today = datetime.now()\n f.write('%s %s \\n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message))\n f.close()\n\n\ndef get_root_pass():\n with open('/root/.my.cnf') as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall('password', line)\n if grep:\n pwrd = line.split('\"')[1]\n return pwrd\n\n\ndef get_db_name(argv):\n try:\n pwrd = get_root_pass()\n db = pymysql.connect('localhost', 'root', pwrd, 'secure_vps')\n cursor = db.cursor()\n cursor.execute(\n \"select id,db_name from provision where provision_name='%s'\" % argv\n )\n data = cursor.fetchone()\n db.close()\n return data\n except pymysql.err.OperationalError as err:\n print(' An error has occurred \\n', err)\n except pymysql.err.InternalError as err:\n print(' An error has occurred \\n', err)\n\n\ndef backup_db(argv):\n data = get_db_name(argv)\n db_name = data[1]\n try:\n sqldir = '/home/kusanagi/' + argv + '/sql_backup/'\n p = pathlib.Path(sqldir)\n if not p.exists():\n p.mkdir(mode=493, parents=True, exist_ok=True)\n shutil.chown(sqldir, 'kusanagi', 'kusanagi')\n except BaseException as error:\n print(error)\n pwrd = get_root_pass()\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n mess = 'Backed up database ' + db_name\n append_log(log, mess)\n cmd = ('mysqldump --single-transaction -p' + pwrd + ' --databases ' +\n db_name + ' | gzip > ' + sqldir + db_name + '.sql.gz')\n execute_outputfile(cmd, log)\n\n\n<mask token>\n\n\ndef compress_provision_dir(argv, chdir=''):\n date = datetime.now()\n today = date.strftime('%Y-%m-%d')\n if chdir:\n tarname = chdir + argv + '.' + today\n else:\n tarname = '/home/kusanagi/backup/' + argv + '.' + today\n source_dir = '/home/kusanagi/' + argv\n shutil.make_archive(tarname, 'gztar', source_dir)\n return tarname\n\n\ndef local_backup(argv):\n append_log('/home/kusanagi/' + argv + '/log/backup.log', '--- Local backup'\n )\n backup_db(argv)\n tarname = compress_provision_dir(argv)\n tar_file = pathlib.Path(tarname + '.tar.gz')\n if tar_file.exists():\n update_backup_record(argv, 0, 1)\n else:\n update_backup_record(argv, 0, 0)\n\n\ndef check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass):\n cmd = ('sshpass -p \"' + remote_pass +\n '\" ssh -o StrictHostKeyChecking=no -p ' + remote_port + ' -q ' +\n remote_user + '@' + remote_host + ' exit;echo $?')\n res = execute(cmd)\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n if int(res) == 0:\n pass\n else:\n append_log(log, 'Remote connection failed. Can not issue remote backup'\n )\n update_backup_record(argv, 1, 0)\n sys.exit(1)\n\n\ndef remote_backup(argv, remote_user, remote_host, remote_port, remote_pass,\n remote_dest):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Remote backup')\n check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass)\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n conf_ssh = '/etc/ssh/ssh_config'\n with open(conf_ssh) as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(remote_host, line)\n if grep:\n break\n if not grep:\n f = open(conf_ssh, 'a+')\n f.write('Host %s\\n\\tStrictHostKeyChecking no\\n' % remote_host)\n f.close()\n cmd = ('sshpass -p \"' + remote_pass +\n '\" rsync --remove-source-files -azhe \\'ssh -p' + remote_port + \"' \" +\n tarname + '.tar.gz ' + remote_user + '@' + remote_host + ':' +\n remote_dest + ' 2>> ' + log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 1, 1)\n else:\n update_backup_record(argv, 1, 0)\n\n\ndef drive_backup(argv, drive_dir):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Backup to Google Drive')\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n cmd = ('rclone copy ' + tarname + '.tar.gz GGD1:' + drive_dir + ' 2>> ' +\n log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 2, 1)\n else:\n update_backup_record(argv, 2, 0)\n os.remove(tarname + '.tar.gz')\n\n\ndef get_options(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive'])\n parser.add_argument('options', nargs=argparse.REMAINDER)\n return parser.parse_args(argv)\n\n\ndef main():\n args = get_options(sys.argv[1:])\n options = ' '.join(map(str, args.options))\n if args.mode == 'local':\n local_backup(*args.options)\n elif args.mode == 'remote':\n remote_backup(*args.options)\n else:\n drive_backup(*args.options)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef append_log(log, message):\n f = open(log, 'a+')\n today = datetime.now()\n f.write('%s %s \\n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message))\n f.close()\n\n\ndef get_root_pass():\n with open('/root/.my.cnf') as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall('password', line)\n if grep:\n pwrd = line.split('\"')[1]\n return pwrd\n\n\ndef get_db_name(argv):\n try:\n pwrd = get_root_pass()\n db = pymysql.connect('localhost', 'root', pwrd, 'secure_vps')\n cursor = db.cursor()\n cursor.execute(\n \"select id,db_name from provision where provision_name='%s'\" % argv\n )\n data = cursor.fetchone()\n db.close()\n return data\n except pymysql.err.OperationalError as err:\n print(' An error has occurred \\n', err)\n except pymysql.err.InternalError as err:\n print(' An error has occurred \\n', err)\n\n\ndef backup_db(argv):\n data = get_db_name(argv)\n db_name = data[1]\n try:\n sqldir = '/home/kusanagi/' + argv + '/sql_backup/'\n p = pathlib.Path(sqldir)\n if not p.exists():\n p.mkdir(mode=493, parents=True, exist_ok=True)\n shutil.chown(sqldir, 'kusanagi', 'kusanagi')\n except BaseException as error:\n print(error)\n pwrd = get_root_pass()\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n mess = 'Backed up database ' + db_name\n append_log(log, mess)\n cmd = ('mysqldump --single-transaction -p' + pwrd + ' --databases ' +\n db_name + ' | gzip > ' + sqldir + db_name + '.sql.gz')\n execute_outputfile(cmd, log)\n\n\ndef update_backup_record(argv, backup_type, result):\n pwrd = get_root_pass()\n data = get_db_name(argv)\n provi_id = data[0]\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n db = pymysql.connect('localhost', 'root', pwrd, 'secure_vps')\n cursor = db.cursor()\n cursor.execute(\n 'select id from logs where provision_id=%d and status=0 and backup_type=%d'\n % (provi_id, backup_type))\n res = cursor.fetchone()\n record_id = res[0]\n if result:\n cursor.execute(\n \"update logs set status=1,message='Done' where provision_id=%d and id=%d\"\n % (provi_id, record_id))\n else:\n cursor.execute(\n \"update logs set status=-1,message='Failed. See %s' where provision_id=%d and id=%d\"\n % (log, provi_id, record_id))\n db.commit()\n db.close()\n\n\ndef compress_provision_dir(argv, chdir=''):\n date = datetime.now()\n today = date.strftime('%Y-%m-%d')\n if chdir:\n tarname = chdir + argv + '.' + today\n else:\n tarname = '/home/kusanagi/backup/' + argv + '.' + today\n source_dir = '/home/kusanagi/' + argv\n shutil.make_archive(tarname, 'gztar', source_dir)\n return tarname\n\n\ndef local_backup(argv):\n append_log('/home/kusanagi/' + argv + '/log/backup.log', '--- Local backup'\n )\n backup_db(argv)\n tarname = compress_provision_dir(argv)\n tar_file = pathlib.Path(tarname + '.tar.gz')\n if tar_file.exists():\n update_backup_record(argv, 0, 1)\n else:\n update_backup_record(argv, 0, 0)\n\n\ndef check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass):\n cmd = ('sshpass -p \"' + remote_pass +\n '\" ssh -o StrictHostKeyChecking=no -p ' + remote_port + ' -q ' +\n remote_user + '@' + remote_host + ' exit;echo $?')\n res = execute(cmd)\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n if int(res) == 0:\n pass\n else:\n append_log(log, 'Remote connection failed. Can not issue remote backup'\n )\n update_backup_record(argv, 1, 0)\n sys.exit(1)\n\n\ndef remote_backup(argv, remote_user, remote_host, remote_port, remote_pass,\n remote_dest):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Remote backup')\n check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass)\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n conf_ssh = '/etc/ssh/ssh_config'\n with open(conf_ssh) as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(remote_host, line)\n if grep:\n break\n if not grep:\n f = open(conf_ssh, 'a+')\n f.write('Host %s\\n\\tStrictHostKeyChecking no\\n' % remote_host)\n f.close()\n cmd = ('sshpass -p \"' + remote_pass +\n '\" rsync --remove-source-files -azhe \\'ssh -p' + remote_port + \"' \" +\n tarname + '.tar.gz ' + remote_user + '@' + remote_host + ':' +\n remote_dest + ' 2>> ' + log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 1, 1)\n else:\n update_backup_record(argv, 1, 0)\n\n\ndef drive_backup(argv, drive_dir):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Backup to Google Drive')\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n cmd = ('rclone copy ' + tarname + '.tar.gz GGD1:' + drive_dir + ' 2>> ' +\n log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 2, 1)\n else:\n update_backup_record(argv, 2, 0)\n os.remove(tarname + '.tar.gz')\n\n\ndef get_options(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive'])\n parser.add_argument('options', nargs=argparse.REMAINDER)\n return parser.parse_args(argv)\n\n\ndef main():\n args = get_options(sys.argv[1:])\n options = ' '.join(map(str, args.options))\n if args.mode == 'local':\n local_backup(*args.options)\n elif args.mode == 'remote':\n remote_backup(*args.options)\n else:\n drive_backup(*args.options)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import argparse\nimport os\nimport sys, shutil\nfrom shutil import make_archive\nimport pathlib\nfrom phpManager import execute, execute_outputfile\nfrom datetime import date, datetime\nimport re\nimport pymysql\nimport tarfile\n\n\ndef append_log(log, message):\n f = open(log, 'a+')\n today = datetime.now()\n f.write('%s %s \\n' % (today.strftime('%Y-%m-%d %H:%M:%S'), message))\n f.close()\n\n\ndef get_root_pass():\n with open('/root/.my.cnf') as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall('password', line)\n if grep:\n pwrd = line.split('\"')[1]\n return pwrd\n\n\ndef get_db_name(argv):\n try:\n pwrd = get_root_pass()\n db = pymysql.connect('localhost', 'root', pwrd, 'secure_vps')\n cursor = db.cursor()\n cursor.execute(\n \"select id,db_name from provision where provision_name='%s'\" % argv\n )\n data = cursor.fetchone()\n db.close()\n return data\n except pymysql.err.OperationalError as err:\n print(' An error has occurred \\n', err)\n except pymysql.err.InternalError as err:\n print(' An error has occurred \\n', err)\n\n\ndef backup_db(argv):\n data = get_db_name(argv)\n db_name = data[1]\n try:\n sqldir = '/home/kusanagi/' + argv + '/sql_backup/'\n p = pathlib.Path(sqldir)\n if not p.exists():\n p.mkdir(mode=493, parents=True, exist_ok=True)\n shutil.chown(sqldir, 'kusanagi', 'kusanagi')\n except BaseException as error:\n print(error)\n pwrd = get_root_pass()\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n mess = 'Backed up database ' + db_name\n append_log(log, mess)\n cmd = ('mysqldump --single-transaction -p' + pwrd + ' --databases ' +\n db_name + ' | gzip > ' + sqldir + db_name + '.sql.gz')\n execute_outputfile(cmd, log)\n\n\ndef update_backup_record(argv, backup_type, result):\n pwrd = get_root_pass()\n data = get_db_name(argv)\n provi_id = data[0]\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n db = pymysql.connect('localhost', 'root', pwrd, 'secure_vps')\n cursor = db.cursor()\n cursor.execute(\n 'select id from logs where provision_id=%d and status=0 and backup_type=%d'\n % (provi_id, backup_type))\n res = cursor.fetchone()\n record_id = res[0]\n if result:\n cursor.execute(\n \"update logs set status=1,message='Done' where provision_id=%d and id=%d\"\n % (provi_id, record_id))\n else:\n cursor.execute(\n \"update logs set status=-1,message='Failed. See %s' where provision_id=%d and id=%d\"\n % (log, provi_id, record_id))\n db.commit()\n db.close()\n\n\ndef compress_provision_dir(argv, chdir=''):\n date = datetime.now()\n today = date.strftime('%Y-%m-%d')\n if chdir:\n tarname = chdir + argv + '.' + today\n else:\n tarname = '/home/kusanagi/backup/' + argv + '.' + today\n source_dir = '/home/kusanagi/' + argv\n shutil.make_archive(tarname, 'gztar', source_dir)\n return tarname\n\n\ndef local_backup(argv):\n append_log('/home/kusanagi/' + argv + '/log/backup.log', '--- Local backup'\n )\n backup_db(argv)\n tarname = compress_provision_dir(argv)\n tar_file = pathlib.Path(tarname + '.tar.gz')\n if tar_file.exists():\n update_backup_record(argv, 0, 1)\n else:\n update_backup_record(argv, 0, 0)\n\n\ndef check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass):\n cmd = ('sshpass -p \"' + remote_pass +\n '\" ssh -o StrictHostKeyChecking=no -p ' + remote_port + ' -q ' +\n remote_user + '@' + remote_host + ' exit;echo $?')\n res = execute(cmd)\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n if int(res) == 0:\n pass\n else:\n append_log(log, 'Remote connection failed. Can not issue remote backup'\n )\n update_backup_record(argv, 1, 0)\n sys.exit(1)\n\n\ndef remote_backup(argv, remote_user, remote_host, remote_port, remote_pass,\n remote_dest):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Remote backup')\n check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass)\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n conf_ssh = '/etc/ssh/ssh_config'\n with open(conf_ssh) as fp:\n lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(remote_host, line)\n if grep:\n break\n if not grep:\n f = open(conf_ssh, 'a+')\n f.write('Host %s\\n\\tStrictHostKeyChecking no\\n' % remote_host)\n f.close()\n cmd = ('sshpass -p \"' + remote_pass +\n '\" rsync --remove-source-files -azhe \\'ssh -p' + remote_port + \"' \" +\n tarname + '.tar.gz ' + remote_user + '@' + remote_host + ':' +\n remote_dest + ' 2>> ' + log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 1, 1)\n else:\n update_backup_record(argv, 1, 0)\n\n\ndef drive_backup(argv, drive_dir):\n log = '/home/kusanagi/' + argv + '/log/backup.log'\n append_log(log, '--- Backup to Google Drive')\n backup_db(argv)\n tarname = compress_provision_dir(argv, '/home/kusanagi/')\n cmd = ('rclone copy ' + tarname + '.tar.gz GGD1:' + drive_dir + ' 2>> ' +\n log + ' ; echo $?')\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv, 2, 1)\n else:\n update_backup_record(argv, 2, 0)\n os.remove(tarname + '.tar.gz')\n\n\ndef get_options(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive'])\n parser.add_argument('options', nargs=argparse.REMAINDER)\n return parser.parse_args(argv)\n\n\ndef main():\n args = get_options(sys.argv[1:])\n options = ' '.join(map(str, args.options))\n if args.mode == 'local':\n local_backup(*args.options)\n elif args.mode == 'remote':\n remote_backup(*args.options)\n else:\n drive_backup(*args.options)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#!/usr/bin/env python3\nimport argparse\nimport os\nimport sys,shutil\nfrom shutil import make_archive\nimport pathlib\nfrom phpManager import execute,execute_outputfile\nfrom datetime import date,datetime\nimport re\nimport pymysql\nimport tarfile\n\n\ndef append_log(log,message):\n f = open(log, \"a+\")\n today = datetime.now()\n f.write(\"%s %s \\n\" % (today.strftime(\"%Y-%m-%d %H:%M:%S\"), message))\n f.close()\n\ndef get_root_pass():\n with open(\"/root/.my.cnf\") as fp: lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(r'password', line)\n if grep:\n pwrd = line.split('\"')[1]\n return pwrd\n\ndef get_db_name(argv):\n try:\n pwrd = get_root_pass()\n db = pymysql.connect(\"localhost\",\"root\",pwrd,\"secure_vps\")\n cursor = db.cursor()\n cursor.execute(\"select id,db_name from provision where provision_name='%s'\" % argv)\n data = cursor.fetchone()\n db.close()\n return data\n except pymysql.err.OperationalError as err:\n print (' An error has occurred \\n', err)\n except pymysql.err.InternalError as err:\n print (' An error has occurred \\n', err)\n\ndef backup_db(argv):\n\n data = get_db_name(argv)\n db_name = data[1]\n try:\n sqldir = '/home/kusanagi/'+argv+'/sql_backup/'\n p = pathlib.Path(sqldir)\n if not p.exists():\n p.mkdir(mode=0o755, parents=True, exist_ok=True)\n shutil.chown(sqldir,'kusanagi','kusanagi')\n except BaseException as error:\n print(error)\n pwrd = get_root_pass()\n\n log = '/home/kusanagi/'+argv+'/log/backup.log'\n mess = 'Backed up database '+db_name\n append_log(log,mess)\n\n cmd = 'mysqldump --single-transaction -p'+pwrd+' --databases '+db_name+' | gzip > '+sqldir+db_name+'.sql.gz'\n execute_outputfile(cmd,log)\n\ndef update_backup_record(argv,backup_type,result):\n\n pwrd = get_root_pass()\n data = get_db_name(argv)\n provi_id = data[0]\n log = '/home/kusanagi/'+argv+'/log/backup.log'\n\n db = pymysql.connect(\"localhost\",\"root\",pwrd,\"secure_vps\")\n cursor = db.cursor()\n cursor.execute(\"select id from logs where provision_id=%d and status=0 and backup_type=%d\" % (provi_id,backup_type))\n res = cursor.fetchone()\n record_id = res[0]\n\n if result:\n cursor.execute(\"update logs set status=1,message='Done' where provision_id=%d and id=%d\" % (provi_id,record_id))\n else:\n cursor.execute(\"update logs set status=-1,message='Failed. See %s' where provision_id=%d and id=%d\" % (log,provi_id,record_id))\n\n db.commit()\n db.close()\n\ndef compress_provision_dir(argv,chdir=''):\n date = datetime.now()\n today = date.strftime(\"%Y-%m-%d\")\n if chdir:\n tarname = chdir+argv+'.'+today\n else:\n tarname = '/home/kusanagi/backup/'+argv+'.'+today\n source_dir = '/home/kusanagi/'+argv\n shutil.make_archive(tarname,\"gztar\",source_dir)\n return tarname\n\ndef local_backup(argv):\n \n append_log('/home/kusanagi/'+argv+'/log/backup.log', '--- Local backup')\n backup_db(argv)\n tarname = compress_provision_dir(argv)\n\n tar_file=pathlib.Path(tarname+'.tar.gz')\n if tar_file.exists():\n update_backup_record(argv,0,1)\n else:\n update_backup_record(argv,0,0)\n\ndef check_ssh_conn(argv,remote_user,remote_host,remote_port,remote_pass):\n cmd = 'sshpass -p \"'+remote_pass+'\" ssh -o StrictHostKeyChecking=no -p '+remote_port+' -q '+remote_user+'@'+remote_host+' exit;echo $?'\n res = execute(cmd)\n log = '/home/kusanagi/'+argv+'/log/backup.log'\n if int(res) == 0:\n #print('Connect OK \\n')\n pass\n else:\n append_log(log, 'Remote connection failed. Can not issue remote backup')\n update_backup_record(argv,1,0)\n sys.exit(1)\n\ndef remote_backup(argv, remote_user, remote_host, remote_port, remote_pass, remote_dest):\n\n log = '/home/kusanagi/'+argv+'/log/backup.log'\n append_log(log, '--- Remote backup')\n check_ssh_conn(argv, remote_user, remote_host, remote_port, remote_pass)\n backup_db(argv)\n tarname = compress_provision_dir(argv,'/home/kusanagi/')\n \n conf_ssh = '/etc/ssh/ssh_config'\n with open(conf_ssh) as fp: lines = fp.read().splitlines()\n for line in lines:\n grep = re.findall(remote_host, line)\n if grep:\n break\n if not grep:\n #configure stricthostkey ssh\n f = open(conf_ssh,\"a+\")\n f.write('Host %s\\n\\tStrictHostKeyChecking no\\n' % remote_host)\n f.close()\n \n cmd = 'sshpass -p \"'+remote_pass+'\" rsync --remove-source-files -azhe \\'ssh -p'+remote_port+'\\' '+tarname+'.tar.gz '+remote_user+'@'+remote_host+':'+remote_dest+' 2>> '+log+' ; echo $?'\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv,1,1)\n else:\n update_backup_record(argv,1,0)\n\n\ndef drive_backup(argv,drive_dir):\n \n log = '/home/kusanagi/'+argv+'/log/backup.log'\n append_log(log,'--- Backup to Google Drive')\n backup_db(argv)\n tarname = compress_provision_dir(argv,'/home/kusanagi/')\n cmd = 'rclone copy '+tarname+'.tar.gz GGD1:'+drive_dir+ ' 2>> '+log+' ; echo $?'\n res = execute(cmd)\n if int(res) == 0:\n update_backup_record(argv,2,1)\n else:\n update_backup_record(argv,2,0)\n os.remove(tarname+'.tar.gz')\n \ndef get_options(argv):\n parser = argparse.ArgumentParser()\n parser.add_argument('mode', type=str, choices=['local', 'remote', 'drive'])\n parser.add_argument('options', nargs=argparse.REMAINDER)\n return parser.parse_args(argv)\n\ndef main():\n \n args=get_options(sys.argv[1:])\n #pwrd = get_root_pass()\n options = ' '.join(map(str, args.options))\n if args.mode == 'local':\n local_backup(*args.options)\n elif args.mode == 'remote':\n remote_backup(*args.options)\n else:\n drive_backup(*args.options)\n\nif __name__ == '__main__':\n main()\n\n", "step-ids": [ 10, 11, 13, 14, 15 ] }
[ 10, 11, 13, 14, 15 ]
''' Find the greatest product of five consecutive digits in the 1000-digit number. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 ''' from time import time s = '73167176531330624919225119674426574742355349194934\ 96983520312774506326239578318016984801869478851843\ 85861560789112949495459501737958331952853208805511\ 12540698747158523863050715693290963295227443043557\ 66896648950445244523161731856403098711121722383113\ 62229893423380308135336276614282806444486645238749\ 30358907296290491560440772390713810515859307960866\ 70172427121883998797908792274921901699720888093776\ 65727333001053367881220235421809751254540594752243\ 52584907711670556013604839586446706324415722155397\ 53697817977846174064955149290862569321978468622482\ 83972241375657056057490261407972968652414535100474\ 82166370484403199890008895243450658541227588666881\ 16427171479924442928230863465674813919123162824586\ 17866458359124566529476545682848912883142607690042\ 24219022671055626321111109370544217506941658960408\ 07198403850962455444362981230987879927244284909188\ 84580156166097919133875499200524063689912560717606\ 05886116467109405077541002256983155200055935729725\ 71636269561882670428252483600823257530420752963450' n = 0 i = 0 while i < len(s) - 4: p = 1 if not int(s[i]): i += 5 continue for j in xrange(i, i+5): p = p * int(s[j]) if not p: i += 5 continue elif p > n: n = p i += 1 print n
normal
{ "blob_id": "db20a77778392c84bab50f6d4002dd11b73967b9", "index": 9214, "step-1": "'''\nFind the greatest product of five consecutive digits in the 1000-digit number.\n\n73167176531330624919225119674426574742355349194934\n96983520312774506326239578318016984801869478851843\n85861560789112949495459501737958331952853208805511\n12540698747158523863050715693290963295227443043557\n66896648950445244523161731856403098711121722383113\n62229893423380308135336276614282806444486645238749\n30358907296290491560440772390713810515859307960866\n70172427121883998797908792274921901699720888093776\n65727333001053367881220235421809751254540594752243\n52584907711670556013604839586446706324415722155397\n53697817977846174064955149290862569321978468622482\n83972241375657056057490261407972968652414535100474\n82166370484403199890008895243450658541227588666881\n16427171479924442928230863465674813919123162824586\n17866458359124566529476545682848912883142607690042\n24219022671055626321111109370544217506941658960408\n07198403850962455444362981230987879927244284909188\n84580156166097919133875499200524063689912560717606\n05886116467109405077541002256983155200055935729725\n71636269561882670428252483600823257530420752963450\n'''\n\nfrom time import time\n\ns = '73167176531330624919225119674426574742355349194934\\\n96983520312774506326239578318016984801869478851843\\\n85861560789112949495459501737958331952853208805511\\\n12540698747158523863050715693290963295227443043557\\\n66896648950445244523161731856403098711121722383113\\\n62229893423380308135336276614282806444486645238749\\\n30358907296290491560440772390713810515859307960866\\\n70172427121883998797908792274921901699720888093776\\\n65727333001053367881220235421809751254540594752243\\\n52584907711670556013604839586446706324415722155397\\\n53697817977846174064955149290862569321978468622482\\\n83972241375657056057490261407972968652414535100474\\\n82166370484403199890008895243450658541227588666881\\\n16427171479924442928230863465674813919123162824586\\\n17866458359124566529476545682848912883142607690042\\\n24219022671055626321111109370544217506941658960408\\\n07198403850962455444362981230987879927244284909188\\\n84580156166097919133875499200524063689912560717606\\\n05886116467109405077541002256983155200055935729725\\\n71636269561882670428252483600823257530420752963450'\n\nn = 0\ni = 0\nwhile i < len(s) - 4:\n p = 1\n if not int(s[i]):\n i += 5\n continue\n\n for j in xrange(i, i+5):\n p = p * int(s[j])\n if not p: \n i += 5\n continue\n elif p > n: n = p\n\n i += 1\n\nprint n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
""" Django settings for geobombay project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP BASE_DIR = os.path.dirname(os.path.dirname(__file__)) DATA_DIR = os.path.join(BASE_DIR, 'data') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ try: SECRET_KEY except NameError: SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') try: SECRET_KEY = open(SECRET_FILE).read().strip() except IOError: try: from random import choice SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)]) secret = file(SECRET_FILE, 'w') secret.write(SECRET_KEY) secret.close() except IOError: Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( #'suit', #Django Suit, skin for the admin 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'cts', 'wards', 'bmc', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'geobombay.urls' WSGI_APPLICATION = 'geobombay.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geobombay' } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets', 'collected-static') # Additional locations of static files STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets', 'static'), # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.core.context_processors.request', ) #Global map / leaflet settings (for django-leaflet plugin we use for admin) LEAFLET_CONFIG = { 'DEFAULT_CENTER': (19, 72.85521,), 'DEFAULT_ZOOM': 11, } try: from local_settings import * except: pass
normal
{ "blob_id": "32ca107fde4c98b61d85f6648f30c7601b31c7f3", "index": 3182, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n from random import choice\n SECRET_KEY = ''.join([choice(\n 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in\n range(50)])\n secret = file(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception(\n 'Please create a %s file with random characters to generate your secret key!'\n % SECRET_FILE)\n<mask token>\ntry:\n from local_settings import *\nexcept:\n pass\n", "step-3": "<mask token>\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nDATA_DIR = os.path.join(BASE_DIR, 'data')\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n from random import choice\n SECRET_KEY = ''.join([choice(\n 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in\n range(50)])\n secret = file(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception(\n 'Please create a %s file with random characters to generate your secret key!'\n % SECRET_FILE)\nDEBUG = True\nTEMPLATE_DEBUG = True\nALLOWED_HOSTS = []\nINSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth',\n 'django.contrib.contenttypes', 'django.contrib.sessions',\n 'django.contrib.messages', 'django.contrib.staticfiles',\n 'django.contrib.gis', 'leaflet', 'cts', 'wards', 'bmc')\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware')\nROOT_URLCONF = 'geobombay.urls'\nWSGI_APPLICATION = 'geobombay.wsgi.application'\nDATABASES = {'default': {'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'geobombay'}}\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'assets', 'collected-static')\nSTATICFILES_DIRS = os.path.join(BASE_DIR, 'assets', 'static'),\nTEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates'),\nTEMPLATE_CONTEXT_PROCESSORS = TCP + ('django.core.context_processors.request',)\nLEAFLET_CONFIG = {'DEFAULT_CENTER': (19, 72.85521), 'DEFAULT_ZOOM': 11}\ntry:\n from local_settings import *\nexcept:\n pass\n", "step-4": "<mask token>\nimport os\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nDATA_DIR = os.path.join(BASE_DIR, 'data')\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n from random import choice\n SECRET_KEY = ''.join([choice(\n 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in\n range(50)])\n secret = file(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception(\n 'Please create a %s file with random characters to generate your secret key!'\n % SECRET_FILE)\nDEBUG = True\nTEMPLATE_DEBUG = True\nALLOWED_HOSTS = []\nINSTALLED_APPS = ('django.contrib.admin', 'django.contrib.auth',\n 'django.contrib.contenttypes', 'django.contrib.sessions',\n 'django.contrib.messages', 'django.contrib.staticfiles',\n 'django.contrib.gis', 'leaflet', 'cts', 'wards', 'bmc')\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware')\nROOT_URLCONF = 'geobombay.urls'\nWSGI_APPLICATION = 'geobombay.wsgi.application'\nDATABASES = {'default': {'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'geobombay'}}\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'assets', 'collected-static')\nSTATICFILES_DIRS = os.path.join(BASE_DIR, 'assets', 'static'),\nTEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates'),\nTEMPLATE_CONTEXT_PROCESSORS = TCP + ('django.core.context_processors.request',)\nLEAFLET_CONFIG = {'DEFAULT_CENTER': (19, 72.85521), 'DEFAULT_ZOOM': 11}\ntry:\n from local_settings import *\nexcept:\n pass\n", "step-5": "\"\"\"\nDjango settings for geobombay project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nDATA_DIR = os.path.join(BASE_DIR, 'data')\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n from random import choice\n SECRET_KEY = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n secret = file(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)\n\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n #'suit', #Django Suit, skin for the admin\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.gis',\n 'leaflet',\n 'cts',\n 'wards',\n 'bmc',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'geobombay.urls'\n\nWSGI_APPLICATION = 'geobombay.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.contrib.gis.db.backends.postgis',\n 'NAME': 'geobombay'\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'assets', 'collected-static')\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'assets', 'static'),\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'templates'),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n\n#Global map / leaflet settings (for django-leaflet plugin we use for admin)\nLEAFLET_CONFIG = {\n 'DEFAULT_CENTER': (19, 72.85521,),\n 'DEFAULT_ZOOM': 11,\n}\n\ntry:\n from local_settings import *\nexcept:\n pass\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from snake.snake import Snake # Start application if __name__ == '__main__': s = Snake() s.run()
normal
{ "blob_id": "efed5c113e085e5b41d9169901c18c06111b9077", "index": 8894, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-3": "from snake.snake import Snake\nif __name__ == '__main__':\n s = Snake()\n s.run()\n", "step-4": "from snake.snake import Snake\n\n# Start application\nif __name__ == '__main__':\n s = Snake()\n s.run()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
n=int(input("Enter any int number:\n")) x=1 while(x<13): print(n ," x ", x ," = ", n*x) x=x+1
normal
{ "blob_id": "a6c07146f1cbc766cd464dab620d1fb075759c12", "index": 4213, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile x < 13:\n print(n, ' x ', x, ' = ', n * x)\n x = x + 1\n", "step-3": "n = int(input('Enter any int number:\\n'))\nx = 1\nwhile x < 13:\n print(n, ' x ', x, ' = ', n * x)\n x = x + 1\n", "step-4": "n=int(input(\"Enter any int number:\\n\"))\n\nx=1\nwhile(x<13):\n print(n ,\" x \", x ,\" = \", n*x)\n x=x+1\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from pyloom import * import random import string alphabet = string.ascii_letters def random_string(N): return ''.join([random.choice(alphabet) for _ in range(N)]) class TestBloomFilter(object): def test_setup(self): bf = BloomFilter(1000) assert 10 == bf._num_hashes assert 14380 == bf._num_bits assert 14380 == len(bf._bitarray) # and initially all bits are False assert 0 == bf._bitarray.count() # test again with a different false positive rate bf = BloomFilter(1000, error=0.01) assert 7 == bf._num_hashes assert 9583 == bf._num_bits assert 9583 == len(bf._bitarray) # and initially all bits are False assert 0 == bf._bitarray.count() def test_add_contains(self): bf = BloomFilter(1000, error=0.01) keys1 = [random_string(10) for _ in range(1000)] keys2 = [random_string(10) for _ in range(1000)] for k in keys1: bf.add(k) assert k in bf class TestScalableBloomFilter(object): def test_scaling(self): S, N, E = 1000, 10000, 0.01 # create a bloom filter with initial capacity of S sbf = ScalableBloomFilter(S, E, 2) keys1 = {random_string(10) for _ in range(N)} keys2 = {random_string(10) for _ in range(N)} for k in keys1: sbf.add(k) assert k in sbf error = 0 total = 0 for k in keys2: if k in keys1: continue total += 1 if k in sbf: error += 1 error_rate = error / total assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (error_rate, E)
normal
{ "blob_id": "24e486edc6f80e0b7d58b5df898e6d34f53111c8", "index": 4389, "step-1": "<mask token>\n\n\nclass TestBloomFilter(object):\n\n def test_setup(self):\n bf = BloomFilter(1000)\n assert 10 == bf._num_hashes\n assert 14380 == bf._num_bits\n assert 14380 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n bf = BloomFilter(1000, error=0.01)\n assert 7 == bf._num_hashes\n assert 9583 == bf._num_bits\n assert 9583 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n\n def test_add_contains(self):\n bf = BloomFilter(1000, error=0.01)\n keys1 = [random_string(10) for _ in range(1000)]\n keys2 = [random_string(10) for _ in range(1000)]\n for k in keys1:\n bf.add(k)\n assert k in bf\n\n\nclass TestScalableBloomFilter(object):\n\n def test_scaling(self):\n S, N, E = 1000, 10000, 0.01\n sbf = ScalableBloomFilter(S, E, 2)\n keys1 = {random_string(10) for _ in range(N)}\n keys2 = {random_string(10) for _ in range(N)}\n for k in keys1:\n sbf.add(k)\n assert k in sbf\n error = 0\n total = 0\n for k in keys2:\n if k in keys1:\n continue\n total += 1\n if k in sbf:\n error += 1\n error_rate = error / total\n assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (\n error_rate, E)\n", "step-2": "<mask token>\n\n\ndef random_string(N):\n return ''.join([random.choice(alphabet) for _ in range(N)])\n\n\nclass TestBloomFilter(object):\n\n def test_setup(self):\n bf = BloomFilter(1000)\n assert 10 == bf._num_hashes\n assert 14380 == bf._num_bits\n assert 14380 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n bf = BloomFilter(1000, error=0.01)\n assert 7 == bf._num_hashes\n assert 9583 == bf._num_bits\n assert 9583 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n\n def test_add_contains(self):\n bf = BloomFilter(1000, error=0.01)\n keys1 = [random_string(10) for _ in range(1000)]\n keys2 = [random_string(10) for _ in range(1000)]\n for k in keys1:\n bf.add(k)\n assert k in bf\n\n\nclass TestScalableBloomFilter(object):\n\n def test_scaling(self):\n S, N, E = 1000, 10000, 0.01\n sbf = ScalableBloomFilter(S, E, 2)\n keys1 = {random_string(10) for _ in range(N)}\n keys2 = {random_string(10) for _ in range(N)}\n for k in keys1:\n sbf.add(k)\n assert k in sbf\n error = 0\n total = 0\n for k in keys2:\n if k in keys1:\n continue\n total += 1\n if k in sbf:\n error += 1\n error_rate = error / total\n assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (\n error_rate, E)\n", "step-3": "<mask token>\nalphabet = string.ascii_letters\n\n\ndef random_string(N):\n return ''.join([random.choice(alphabet) for _ in range(N)])\n\n\nclass TestBloomFilter(object):\n\n def test_setup(self):\n bf = BloomFilter(1000)\n assert 10 == bf._num_hashes\n assert 14380 == bf._num_bits\n assert 14380 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n bf = BloomFilter(1000, error=0.01)\n assert 7 == bf._num_hashes\n assert 9583 == bf._num_bits\n assert 9583 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n\n def test_add_contains(self):\n bf = BloomFilter(1000, error=0.01)\n keys1 = [random_string(10) for _ in range(1000)]\n keys2 = [random_string(10) for _ in range(1000)]\n for k in keys1:\n bf.add(k)\n assert k in bf\n\n\nclass TestScalableBloomFilter(object):\n\n def test_scaling(self):\n S, N, E = 1000, 10000, 0.01\n sbf = ScalableBloomFilter(S, E, 2)\n keys1 = {random_string(10) for _ in range(N)}\n keys2 = {random_string(10) for _ in range(N)}\n for k in keys1:\n sbf.add(k)\n assert k in sbf\n error = 0\n total = 0\n for k in keys2:\n if k in keys1:\n continue\n total += 1\n if k in sbf:\n error += 1\n error_rate = error / total\n assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (\n error_rate, E)\n", "step-4": "from pyloom import *\nimport random\nimport string\nalphabet = string.ascii_letters\n\n\ndef random_string(N):\n return ''.join([random.choice(alphabet) for _ in range(N)])\n\n\nclass TestBloomFilter(object):\n\n def test_setup(self):\n bf = BloomFilter(1000)\n assert 10 == bf._num_hashes\n assert 14380 == bf._num_bits\n assert 14380 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n bf = BloomFilter(1000, error=0.01)\n assert 7 == bf._num_hashes\n assert 9583 == bf._num_bits\n assert 9583 == len(bf._bitarray)\n assert 0 == bf._bitarray.count()\n\n def test_add_contains(self):\n bf = BloomFilter(1000, error=0.01)\n keys1 = [random_string(10) for _ in range(1000)]\n keys2 = [random_string(10) for _ in range(1000)]\n for k in keys1:\n bf.add(k)\n assert k in bf\n\n\nclass TestScalableBloomFilter(object):\n\n def test_scaling(self):\n S, N, E = 1000, 10000, 0.01\n sbf = ScalableBloomFilter(S, E, 2)\n keys1 = {random_string(10) for _ in range(N)}\n keys2 = {random_string(10) for _ in range(N)}\n for k in keys1:\n sbf.add(k)\n assert k in sbf\n error = 0\n total = 0\n for k in keys2:\n if k in keys1:\n continue\n total += 1\n if k in sbf:\n error += 1\n error_rate = error / total\n assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (\n error_rate, E)\n", "step-5": "from pyloom import *\n\nimport random\nimport string\n\nalphabet = string.ascii_letters\n\n\ndef random_string(N):\n return ''.join([random.choice(alphabet) for _ in range(N)])\n\n\nclass TestBloomFilter(object):\n def test_setup(self):\n bf = BloomFilter(1000)\n assert 10 == bf._num_hashes\n assert 14380 == bf._num_bits\n assert 14380 == len(bf._bitarray)\n\n # and initially all bits are False\n assert 0 == bf._bitarray.count()\n\n # test again with a different false positive rate\n bf = BloomFilter(1000, error=0.01)\n assert 7 == bf._num_hashes\n assert 9583 == bf._num_bits\n assert 9583 == len(bf._bitarray)\n\n # and initially all bits are False\n assert 0 == bf._bitarray.count()\n\n def test_add_contains(self):\n bf = BloomFilter(1000, error=0.01)\n keys1 = [random_string(10) for _ in range(1000)]\n keys2 = [random_string(10) for _ in range(1000)]\n\n for k in keys1:\n bf.add(k)\n assert k in bf\nclass TestScalableBloomFilter(object):\n def test_scaling(self):\n S, N, E = 1000, 10000, 0.01\n\n # create a bloom filter with initial capacity of S\n sbf = ScalableBloomFilter(S, E, 2)\n keys1 = {random_string(10) for _ in range(N)}\n keys2 = {random_string(10) for _ in range(N)}\n\n for k in keys1:\n sbf.add(k)\n assert k in sbf\n\n error = 0\n total = 0\n for k in keys2:\n if k in keys1:\n continue\n\n total += 1\n if k in sbf:\n error += 1\n\n error_rate = error / total\n assert error_rate <= 2 * 0.01, 'Error rate is %.3f when it should be %.3f' % (error_rate, E)\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
# Filename : var.py #整数 i = 5 print(i) i = i + 1 print(i) #浮点数 i = 1.1 print(i) #python的弱语言特性,可以随时改变变量的类型 i = 'change i to a string ' print(i) s = 'hello'#单引号 print(s) s = "hello"#双引号 print(s) #三引号为多行字符串 s = '''This is a "multi-line" string. This is the second line.''' print(s) s = '\''#斜杠用于转义 print(s) #r或R开头的字符串表示自然字符串,后面的斜杠不转义 s = r'\n' print(s) s = '这是一个行\ 连接符的例子' print(s) #斜杠在这里是行连接符,可以把一行中太长的代码分为多行不影响实际意义 #强烈建议坚持在每个物理行只写一句逻辑行。仅仅当逻辑行太长的时候,在多于一个物理行写一个逻辑行 #有一种暗示的假设,可以使你不需要使用反斜杠。这种情况出现在逻辑行中使用了圆括号、方括号或波形括号的时候。这被称为暗示的行连接 i = \ 55 print(i) #同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块,错误的缩进会引发错误 print('value is',i) print('value is',i)
normal
{ "blob_id": "bea7853d1f3eac50825bc6eb10438f3f656d6d04", "index": 1947, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(i)\n<mask token>\nprint(i)\n<mask token>\nprint(i)\n<mask token>\nprint(i)\n<mask token>\nprint(s)\n<mask token>\nprint(s)\n<mask token>\nprint(s)\n<mask token>\nprint(s)\n<mask token>\nprint(s)\n<mask token>\nprint(s)\n<mask token>\nprint(i)\nprint('value is', i)\nprint('value is', i)\n", "step-3": "i = 5\nprint(i)\ni = i + 1\nprint(i)\ni = 1.1\nprint(i)\ni = 'change i to a string '\nprint(i)\ns = 'hello'\nprint(s)\ns = 'hello'\nprint(s)\ns = \"\"\"This is a \"multi-line\" string.\nThis is the second line.\"\"\"\nprint(s)\ns = \"'\"\nprint(s)\ns = '\\\\n'\nprint(s)\ns = '这是一个行连接符的例子'\nprint(s)\ni = 55\nprint(i)\nprint('value is', i)\nprint('value is', i)\n", "step-4": "# Filename : var.py\n\n#整数\ni = 5\nprint(i)\ni = i + 1\nprint(i)\n\n#浮点数\ni = 1.1\nprint(i)\n\n#python的弱语言特性,可以随时改变变量的类型\ni = 'change i to a string '\nprint(i)\n\n\ns = 'hello'#单引号\nprint(s)\ns = \"hello\"#双引号\nprint(s)\n\n#三引号为多行字符串\ns = '''This is a \"multi-line\" string.\nThis is the second line.'''\nprint(s)\n\ns = '\\''#斜杠用于转义\nprint(s)\n#r或R开头的字符串表示自然字符串,后面的斜杠不转义\ns = r'\\n'\nprint(s)\n\ns = '这是一个行\\\n连接符的例子'\nprint(s)\n\n#斜杠在这里是行连接符,可以把一行中太长的代码分为多行不影响实际意义\n#强烈建议坚持在每个物理行只写一句逻辑行。仅仅当逻辑行太长的时候,在多于一个物理行写一个逻辑行\n#有一种暗示的假设,可以使你不需要使用反斜杠。这种情况出现在逻辑行中使用了圆括号、方括号或波形括号的时候。这被称为暗示的行连接\ni = \\\n55\nprint(i)\n\n#同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块,错误的缩进会引发错误\nprint('value is',i)\nprint('value is',i)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import tornado.options import serial import time from datetime import timedelta import cv2 import time from datetime import datetime #for webcam users camera=cv2.VideoCapture(0) #for picam users #import picam #camera=picam.OpenCVCapture() #if you prefer to change the resolution of the image otherwise comment below 2 lines ret = camera.set(3,320) #width ret = camera.set(4,240) #height #ret=camera.set(10,0.6) face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml') clients = [] f=open("/home/pi/visitor_project/register.txt","a") class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def open(self): print 'A Client Is Connected' clients.append(self) def on_message(self, message): print 'Incoming status', message #a=message.split("!") if message=='who': count=0 list1=[] a="" f=open("/home/pi/visitor_project/register.txt","r") for line in f.readlines(): if len(line) != 1 : list1.append(line) #count=count+1 f.close() a=''.join(map(str,list1)) self.write_message(a) def on_close(self): print 'Client Closed the Connecttion ' clients.remove(self) def send_message_to_clients(msg): for client in clients: client.write_message(msg) def function_second(): ret, image=camera.read() # gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) # faces = face_cascade.detectMultiScale(gray, 1.3, 4) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30,30), flags=cv2.CASCADE_SCALE_IMAGE) print "Found "+str(len(faces))+" face(s)" #Draw a rectangle around every found face for (x,y,w,h) in faces: cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) if len(faces)>=1: send_message_to_clients(str(len(faces))+" Visitors") cv2.imwrite('/home/pi/visitor_project/result.jpg',image) gt=datetime.now().strftime('%Y-%m-%d- %H:%M:%S - ') m="log-"+gt+str(len(faces))+" Visitors" f.write("\n"+m) tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=1), function_second) if __name__ == "__main__": tornado.options.parse_command_line() application=tornado.web.Application(handlers=[ (r"/ws",WSHandler), (r'/visitor_project/(.*)',tornado.web.StaticFileHandler,{'path':'/home/pi/visitor_project'}) ]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(3030) tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=1), function_second) tornado.ioloop.IOLoop.instance().start()
normal
{ "blob_id": "1e9afe6435285da6c6efb678177587d7ba5a01b2", "index": 1397, "step-1": "import tornado.httpserver\nimport tornado.websocket\nimport tornado.ioloop\nimport tornado.web\nimport tornado.options\nimport serial\nimport time\nfrom datetime import timedelta\nimport cv2\nimport time\nfrom datetime import datetime\n\n\n#for webcam users\ncamera=cv2.VideoCapture(0)\n\n#for picam users\n#import picam\n#camera=picam.OpenCVCapture()\n\n\n#if you prefer to change the resolution of the image otherwise comment below 2 lines\nret = camera.set(3,320) #width \nret = camera.set(4,240) #height\n\n#ret=camera.set(10,0.6)\n\nface_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml')\n\nclients = []\nf=open(\"/home/pi/visitor_project/register.txt\",\"a\") \n \n\n\n \n \nclass WSHandler(tornado.websocket.WebSocketHandler):\n \n def check_origin(self, origin):\n return True\n \n \n def open(self):\n print 'A Client Is Connected'\n clients.append(self)\n \n\n def on_message(self, message):\n \n print 'Incoming status', message\n #a=message.split(\"!\")\n \n \n \n\n\n if message=='who':\n count=0\n list1=[]\n a=\"\"\n f=open(\"/home/pi/visitor_project/register.txt\",\"r\")\n for line in f.readlines():\n \n if len(line) != 1 :\n \n \n list1.append(line)\n \n \n \n \n \n #count=count+1\n \n \n f.close()\n a=''.join(map(str,list1))\n self.write_message(a)\n \n\n\n def on_close(self):\n print 'Client Closed the Connecttion '\n clients.remove(self)\n \ndef send_message_to_clients(msg):\n for client in clients:\n client.write_message(msg)\n\n\n \n \ndef function_second():\n \n \n \n ret, image=camera.read()\n \n \n # gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)\n\n\n # faces = face_cascade.detectMultiScale(gray, 1.3, 4)\n \n faces = face_cascade.detectMultiScale(gray, \n\t\t\t\tscaleFactor=1.3, \n\t\t\t\tminNeighbors=3, \n\t\t\t\tminSize=(30,30), \n\t\t\t\tflags=cv2.CASCADE_SCALE_IMAGE) \n print \"Found \"+str(len(faces))+\" face(s)\"\n \n#Draw a rectangle around every found face\n for (x,y,w,h) in faces:\n cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)\n \n \n\t\n if len(faces)>=1:\n send_message_to_clients(str(len(faces))+\" Visitors\")\n cv2.imwrite('/home/pi/visitor_project/result.jpg',image)\n gt=datetime.now().strftime('%Y-%m-%d- %H:%M:%S - ')\n m=\"log-\"+gt+str(len(faces))+\" Visitors\"\n \n f.write(\"\\n\"+m)\n \n tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=1),\n function_second) \n\nif __name__ == \"__main__\":\n \n tornado.options.parse_command_line()\n application=tornado.web.Application(handlers=[\n\n(r\"/ws\",WSHandler),\n\n\n(r'/visitor_project/(.*)',tornado.web.StaticFileHandler,{'path':'/home/pi/visitor_project'})\n\n])\n \n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(3030)\n tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=1),\n function_second)\n tornado.ioloop.IOLoop.instance().start()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import ga.ga as ga import os import datetime def ga_optimise(synth, param_count, target, output_dir, iterations = 10, pop_size = 500): fs = ga.ga_optimise(compute_population_fitnesses = ga.compute_population_fitnesses, target = target, synth = synth, param_count = param_count, iterations = iterations, pop_size = pop_size, crossovers = param_count / 5, mutation_rate = 0.5, log = True, data_folder = output_dir) return fs if __name__ == '__main__': vst_synth = "../mda DX10.vst" vst_param_count = 15 target_dir = "../runs/" + datetime.datetime.now().strftime("%Y%m%d%H%M%s") + "/" os.mkdir(target_dir) print "Generating set of target sounds from 32 presets on "+vst_synth # first generate the target sounds # which are the 32 presets from the synth for i in range(0, 32): filename = target_dir + "preset_"+str(i)+".wav" print "Target "+str(i)+": "+filename ga.render_preset(vst_synth, i, filename) for i in range(0, 32): filename = target_dir + "preset_"+str(i)+".wav" print "Looking for target: "+filename target_mfccs = ga.wav_to_mfcc(filename) data_folder = target_dir + "_preset_"+str(i) + "/" try: os.mkdir(data_folder) except: print "data folder already there." ga.string_to_file("synth: "+vst_synth + "\npreset: "+str(i), data_folder + "details.txt") ga_optimise(vst_synth, vst_param_count, target_mfccs, data_folder) # targets = ga.get_files_in_dir(test_dir, filter = "wav") # for target in targets: # print "Looking for "+target # target_mfccs = ga.wav_to_mfcc("test.wav") # data_folder = "data/data_"+target+"/" # try: # os.mkdir(data_folder) # except: # print "data folder already there." # ga_optimise(vst_synth, vst_param_count, target_mfccs, data_folder)
normal
{ "blob_id": "4bc9896847e4ab92a01dfcf674362140cc31ef4f", "index": 5587, "step-1": "import ga.ga as ga\nimport os\nimport datetime\n\n\ndef ga_optimise(synth, param_count, target, output_dir, iterations = 10, pop_size = 500):\n\tfs = ga.ga_optimise(compute_population_fitnesses = ga.compute_population_fitnesses, \n\t\t\t\ttarget = target, \n\t\t\t\tsynth = synth, \n\t\t\t\tparam_count = param_count, \n\t\t\t\titerations = iterations, \n\t\t\t\tpop_size = pop_size, \n\t\t\t\tcrossovers = param_count / 5, \n\t\t\t\tmutation_rate = 0.5, \n\t\t\t\tlog = True, \n\t\t\t\tdata_folder = output_dir)\n\treturn fs\n\n\nif __name__ == '__main__':\n\tvst_synth = \"../mda DX10.vst\"\n\tvst_param_count = 15\n\ttarget_dir = \"../runs/\" + datetime.datetime.now().strftime(\"%Y%m%d%H%M%s\") + \"/\"\n\tos.mkdir(target_dir)\n\tprint \"Generating set of target sounds from 32 presets on \"+vst_synth\n\t# first generate the target sounds\n\t# which are the 32 presets from the synth\n\tfor i in range(0, 32):\n\t\tfilename = target_dir + \"preset_\"+str(i)+\".wav\"\n\t\tprint \"Target \"+str(i)+\": \"+filename\n\t\tga.render_preset(vst_synth, i, filename)\n\n\tfor i in range(0, 32):\n\t\tfilename = target_dir + \"preset_\"+str(i)+\".wav\"\n\t\tprint \"Looking for target: \"+filename\n\t\ttarget_mfccs = ga.wav_to_mfcc(filename)\n\t\tdata_folder = target_dir + \"_preset_\"+str(i) + \"/\"\t\t\n\t\ttry:\n\t\t\tos.mkdir(data_folder)\n\t\texcept:\n\t\t\tprint \"data folder already there.\"\n\t\tga.string_to_file(\"synth: \"+vst_synth + \"\\npreset: \"+str(i), data_folder + \"details.txt\")\n\t\tga_optimise(vst_synth, vst_param_count, target_mfccs, data_folder)\n\t\t\n\n\t# targets = ga.get_files_in_dir(test_dir, filter = \"wav\")\n\t# for target in targets:\n\t# \tprint \"Looking for \"+target\n\t# \ttarget_mfccs = ga.wav_to_mfcc(\"test.wav\")\n\t# \tdata_folder = \"data/data_\"+target+\"/\"\n\t# \ttry:\n\t# \t\tos.mkdir(data_folder)\n\t# \texcept:\n\t# \t\tprint \"data folder already there.\"\n\t# \tga_optimise(vst_synth, vst_param_count, target_mfccs, data_folder)\n\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import pickle import numpy as np import math class AdaBoostClassifier: '''A simple AdaBoost Classifier.''' def __init__(self, weak_classifier, n_weakers_limit): '''Initialize AdaBoostClassifier Args: weak_classifier: The class of weak classifier, which is recommend to be sklearn.tree.DecisionTreeClassifier. n_weakers_limit: The maximum number of weak classifier the model can use. ''' self.weakClassifier = weak_classifier self.iteration = n_weakers_limit def is_good_enough(self): '''Optional''' pass def calculateError(self, y, predictY, weights): """ 函数作用:计算误差 :param y:列表,标签 :param predictY:列表,元素是预测值 :param weights:列表,权重值 :return:误差 """ error = 0 for i in range(len(y)): if y[i] != predictY[i]: error += weights[i] return error def fit(self,X,y): '''Build a boosted classifier from the training set (X, y). Args: X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features). y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1). ''' row, col = X.shape weightArray = [(1 / row)] * row self.alphaList = [] self.finalClassifierList = [] for i in range(self.iteration): clf = self.weakClassifier(max_depth=2) clf.fit(X,y,weightArray) predictY = clf.predict(X) error = self.calculateError(y, predictY, weightArray) if error > 0.5: break else: self.finalClassifierList.append(clf) alpha = 0.5 * math.log((1-error) / error) self.alphaList.append(alpha) aYH = alpha * y * predictY * (-1) tempWeights = weightArray * np.exp(aYH) tempSum = np.sum(tempWeights) weightArray = tempWeights / tempSum def predict_scores(self, X): '''Calculate the weighted sum score of the whole base classifiers for given samples. Args: X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features). Returns: An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1). ''' pass def predict(self, X, threshold=0): '''Predict the catagories for geven samples. Args: X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features). threshold: The demarcation number of deviding the samples into two parts. Returns: An ndarray consists of predicted labels, which shape should be (n_samples,1). ''' predictYList = [] for i in range(len(self.finalClassifierList)): tempY = self.finalClassifierList[i].predict(X) predictYList.append(tempY) predicYArray = np.transpose(np.array(predictYList)) alphaArray = np.array(self.alphaList) temp = predicYArray * alphaArray predictY = np.sum(temp, axis = 1) for i in range(len(predictY)): if predictY[i] > threshold: predictY[i] = 1 else: predictY[i] = -1 return predictY @staticmethod def save(model, filename): with open(filename, "wb") as f: pickle.dump(model, f) @staticmethod def load(filename): with open(filename, "rb") as f: return pickle.load(f)
normal
{ "blob_id": "905d8be76ef245a2b8fcfb3f806f8922d351ecf0", "index": 8877, "step-1": "<mask token>\n\n\nclass AdaBoostClassifier:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def predict(self, X, threshold=0):\n \"\"\"Predict the catagories for geven samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n \"\"\"\n predictYList = []\n for i in range(len(self.finalClassifierList)):\n tempY = self.finalClassifierList[i].predict(X)\n predictYList.append(tempY)\n predicYArray = np.transpose(np.array(predictYList))\n alphaArray = np.array(self.alphaList)\n temp = predicYArray * alphaArray\n predictY = np.sum(temp, axis=1)\n for i in range(len(predictY)):\n if predictY[i] > threshold:\n predictY[i] = 1\n else:\n predictY[i] = -1\n return predictY\n <mask token>\n\n @staticmethod\n def load(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n", "step-2": "<mask token>\n\n\nclass AdaBoostClassifier:\n <mask token>\n <mask token>\n\n def is_good_enough(self):\n \"\"\"Optional\"\"\"\n pass\n <mask token>\n\n def fit(self, X, y):\n \"\"\"Build a boosted classifier from the training set (X, y).\n\n Args:\n X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features).\n y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1).\n \"\"\"\n row, col = X.shape\n weightArray = [1 / row] * row\n self.alphaList = []\n self.finalClassifierList = []\n for i in range(self.iteration):\n clf = self.weakClassifier(max_depth=2)\n clf.fit(X, y, weightArray)\n predictY = clf.predict(X)\n error = self.calculateError(y, predictY, weightArray)\n if error > 0.5:\n break\n else:\n self.finalClassifierList.append(clf)\n alpha = 0.5 * math.log((1 - error) / error)\n self.alphaList.append(alpha)\n aYH = alpha * y * predictY * -1\n tempWeights = weightArray * np.exp(aYH)\n tempSum = np.sum(tempWeights)\n weightArray = tempWeights / tempSum\n\n def predict_scores(self, X):\n \"\"\"Calculate the weighted sum score of the whole base classifiers for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n\n Returns:\n An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1).\n \"\"\"\n pass\n\n def predict(self, X, threshold=0):\n \"\"\"Predict the catagories for geven samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n \"\"\"\n predictYList = []\n for i in range(len(self.finalClassifierList)):\n tempY = self.finalClassifierList[i].predict(X)\n predictYList.append(tempY)\n predicYArray = np.transpose(np.array(predictYList))\n alphaArray = np.array(self.alphaList)\n temp = predicYArray * alphaArray\n predictY = np.sum(temp, axis=1)\n for i in range(len(predictY)):\n if predictY[i] > threshold:\n predictY[i] = 1\n else:\n predictY[i] = -1\n return predictY\n\n @staticmethod\n def save(model, filename):\n with open(filename, 'wb') as f:\n pickle.dump(model, f)\n\n @staticmethod\n def load(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n", "step-3": "<mask token>\n\n\nclass AdaBoostClassifier:\n <mask token>\n <mask token>\n\n def is_good_enough(self):\n \"\"\"Optional\"\"\"\n pass\n\n def calculateError(self, y, predictY, weights):\n \"\"\"\n\t\t函数作用:计算误差\n :param y:列表,标签\n :param predictY:列表,元素是预测值\n :param weights:列表,权重值\n :return:误差\n \"\"\"\n error = 0\n for i in range(len(y)):\n if y[i] != predictY[i]:\n error += weights[i]\n return error\n\n def fit(self, X, y):\n \"\"\"Build a boosted classifier from the training set (X, y).\n\n Args:\n X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features).\n y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1).\n \"\"\"\n row, col = X.shape\n weightArray = [1 / row] * row\n self.alphaList = []\n self.finalClassifierList = []\n for i in range(self.iteration):\n clf = self.weakClassifier(max_depth=2)\n clf.fit(X, y, weightArray)\n predictY = clf.predict(X)\n error = self.calculateError(y, predictY, weightArray)\n if error > 0.5:\n break\n else:\n self.finalClassifierList.append(clf)\n alpha = 0.5 * math.log((1 - error) / error)\n self.alphaList.append(alpha)\n aYH = alpha * y * predictY * -1\n tempWeights = weightArray * np.exp(aYH)\n tempSum = np.sum(tempWeights)\n weightArray = tempWeights / tempSum\n\n def predict_scores(self, X):\n \"\"\"Calculate the weighted sum score of the whole base classifiers for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n\n Returns:\n An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1).\n \"\"\"\n pass\n\n def predict(self, X, threshold=0):\n \"\"\"Predict the catagories for geven samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n \"\"\"\n predictYList = []\n for i in range(len(self.finalClassifierList)):\n tempY = self.finalClassifierList[i].predict(X)\n predictYList.append(tempY)\n predicYArray = np.transpose(np.array(predictYList))\n alphaArray = np.array(self.alphaList)\n temp = predicYArray * alphaArray\n predictY = np.sum(temp, axis=1)\n for i in range(len(predictY)):\n if predictY[i] > threshold:\n predictY[i] = 1\n else:\n predictY[i] = -1\n return predictY\n\n @staticmethod\n def save(model, filename):\n with open(filename, 'wb') as f:\n pickle.dump(model, f)\n\n @staticmethod\n def load(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n", "step-4": "<mask token>\n\n\nclass AdaBoostClassifier:\n <mask token>\n\n def __init__(self, weak_classifier, n_weakers_limit):\n \"\"\"Initialize AdaBoostClassifier\n\n Args:\n weak_classifier: The class of weak classifier, which is recommend to be sklearn.tree.DecisionTreeClassifier.\n n_weakers_limit: The maximum number of weak classifier the model can use.\n \"\"\"\n self.weakClassifier = weak_classifier\n self.iteration = n_weakers_limit\n\n def is_good_enough(self):\n \"\"\"Optional\"\"\"\n pass\n\n def calculateError(self, y, predictY, weights):\n \"\"\"\n\t\t函数作用:计算误差\n :param y:列表,标签\n :param predictY:列表,元素是预测值\n :param weights:列表,权重值\n :return:误差\n \"\"\"\n error = 0\n for i in range(len(y)):\n if y[i] != predictY[i]:\n error += weights[i]\n return error\n\n def fit(self, X, y):\n \"\"\"Build a boosted classifier from the training set (X, y).\n\n Args:\n X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features).\n y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1).\n \"\"\"\n row, col = X.shape\n weightArray = [1 / row] * row\n self.alphaList = []\n self.finalClassifierList = []\n for i in range(self.iteration):\n clf = self.weakClassifier(max_depth=2)\n clf.fit(X, y, weightArray)\n predictY = clf.predict(X)\n error = self.calculateError(y, predictY, weightArray)\n if error > 0.5:\n break\n else:\n self.finalClassifierList.append(clf)\n alpha = 0.5 * math.log((1 - error) / error)\n self.alphaList.append(alpha)\n aYH = alpha * y * predictY * -1\n tempWeights = weightArray * np.exp(aYH)\n tempSum = np.sum(tempWeights)\n weightArray = tempWeights / tempSum\n\n def predict_scores(self, X):\n \"\"\"Calculate the weighted sum score of the whole base classifiers for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n\n Returns:\n An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1).\n \"\"\"\n pass\n\n def predict(self, X, threshold=0):\n \"\"\"Predict the catagories for geven samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n \"\"\"\n predictYList = []\n for i in range(len(self.finalClassifierList)):\n tempY = self.finalClassifierList[i].predict(X)\n predictYList.append(tempY)\n predicYArray = np.transpose(np.array(predictYList))\n alphaArray = np.array(self.alphaList)\n temp = predicYArray * alphaArray\n predictY = np.sum(temp, axis=1)\n for i in range(len(predictY)):\n if predictY[i] > threshold:\n predictY[i] = 1\n else:\n predictY[i] = -1\n return predictY\n\n @staticmethod\n def save(model, filename):\n with open(filename, 'wb') as f:\n pickle.dump(model, f)\n\n @staticmethod\n def load(filename):\n with open(filename, 'rb') as f:\n return pickle.load(f)\n", "step-5": "import pickle\nimport numpy as np\nimport math\n\nclass AdaBoostClassifier:\n '''A simple AdaBoost Classifier.'''\n\n def __init__(self, weak_classifier, n_weakers_limit):\n '''Initialize AdaBoostClassifier\n\n Args:\n weak_classifier: The class of weak classifier, which is recommend to be sklearn.tree.DecisionTreeClassifier.\n n_weakers_limit: The maximum number of weak classifier the model can use.\n '''\n self.weakClassifier = weak_classifier\n self.iteration = n_weakers_limit\n\n def is_good_enough(self):\n '''Optional'''\n pass\n\n def calculateError(self, y, predictY, weights):\n \"\"\"\n\t\t函数作用:计算误差\n :param y:列表,标签\n :param predictY:列表,元素是预测值\n :param weights:列表,权重值\n :return:误差\n \"\"\"\n error = 0\n for i in range(len(y)):\n if y[i] != predictY[i]:\n error += weights[i]\n return error\n\n def fit(self,X,y):\n '''Build a boosted classifier from the training set (X, y).\n\n Args:\n X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features).\n y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1).\n '''\n row, col = X.shape\n weightArray = [(1 / row)] * row\n self.alphaList = []\n self.finalClassifierList = []\n for i in range(self.iteration):\n clf = self.weakClassifier(max_depth=2)\n clf.fit(X,y,weightArray)\n predictY = clf.predict(X)\n error = self.calculateError(y, predictY, weightArray)\n if error > 0.5:\n break\n else:\n self.finalClassifierList.append(clf)\n alpha = 0.5 * math.log((1-error) / error)\n self.alphaList.append(alpha)\n aYH = alpha * y * predictY * (-1)\n tempWeights = weightArray * np.exp(aYH)\n tempSum = np.sum(tempWeights)\n weightArray = tempWeights / tempSum\n\n def predict_scores(self, X):\n '''Calculate the weighted sum score of the whole base classifiers for given samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n\n Returns:\n An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1).\n '''\n\n pass\n\n def predict(self, X, threshold=0):\n '''Predict the catagories for geven samples.\n\n Args:\n X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features).\n threshold: The demarcation number of deviding the samples into two parts.\n\n Returns:\n An ndarray consists of predicted labels, which shape should be (n_samples,1).\n '''\n predictYList = []\n for i in range(len(self.finalClassifierList)):\n tempY = self.finalClassifierList[i].predict(X)\n predictYList.append(tempY)\n predicYArray = np.transpose(np.array(predictYList))\n alphaArray = np.array(self.alphaList)\n temp = predicYArray * alphaArray\n predictY = np.sum(temp, axis = 1)\n for i in range(len(predictY)):\n if predictY[i] > threshold:\n predictY[i] = 1\n else:\n predictY[i] = -1\n return predictY\n\n @staticmethod\n def save(model, filename):\n with open(filename, \"wb\") as f:\n pickle.dump(model, f)\n\n @staticmethod\n def load(filename):\n with open(filename, \"rb\") as f:\n return pickle.load(f)\n", "step-ids": [ 3, 7, 8, 9, 12 ] }
[ 3, 7, 8, 9, 12 ]
from sklearn.model_selection import train_test_split from azureml.core import Run from sklearn.ensemble import RandomForestClassifier import pandas as pd import argparse import os import joblib import numpy as np # Get the experiment run context run = Run.get_context() # Get arguments parser = argparse.ArgumentParser() parser.add_argument('--in_n_estimator', type=int, default=8) parser.add_argument('--in_criterion', type=str, default="gini") parser.add_argument('--in_max_depth', type=int, default=2) args = parser.parse_args() in_n_estimators = args.in_n_estimator in_criterion = args.in_criterion in_max_depth = args.in_max_depth # read prepared data df = pd.read_csv("prepared_data.csv") columns = df.iloc[1:2, :-1].columns x = df[columns] y = df.iloc[:, -1:] # split data into train and test x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=2) # “gini”, “entropy” model = RandomForestClassifier(n_estimators=in_n_estimators, criterion=in_criterion, max_depth=in_max_depth) model.fit(x_train, y_train) accuracy = model.score(x_test, y_test) run.log("Accuracy", float(accuracy)) os.makedirs('outputs', exist_ok=True) joblib.dump(model, 'outputs/model_forest.joblib')
normal
{ "blob_id": "66c2d73c100f7fc802e66f2762c92664e4b93fcd", "index": 5736, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('--in_n_estimator', type=int, default=8)\nparser.add_argument('--in_criterion', type=str, default='gini')\nparser.add_argument('--in_max_depth', type=int, default=2)\n<mask token>\nmodel.fit(x_train, y_train)\n<mask token>\nrun.log('Accuracy', float(accuracy))\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(model, 'outputs/model_forest.joblib')\n", "step-3": "<mask token>\nrun = Run.get_context()\nparser = argparse.ArgumentParser()\nparser.add_argument('--in_n_estimator', type=int, default=8)\nparser.add_argument('--in_criterion', type=str, default='gini')\nparser.add_argument('--in_max_depth', type=int, default=2)\nargs = parser.parse_args()\nin_n_estimators = args.in_n_estimator\nin_criterion = args.in_criterion\nin_max_depth = args.in_max_depth\ndf = pd.read_csv('prepared_data.csv')\ncolumns = df.iloc[1:2, :-1].columns\nx = df[columns]\ny = df.iloc[:, -1:]\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25,\n random_state=2)\nmodel = RandomForestClassifier(n_estimators=in_n_estimators, criterion=\n in_criterion, max_depth=in_max_depth)\nmodel.fit(x_train, y_train)\naccuracy = model.score(x_test, y_test)\nrun.log('Accuracy', float(accuracy))\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(model, 'outputs/model_forest.joblib')\n", "step-4": "from sklearn.model_selection import train_test_split\nfrom azureml.core import Run\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport argparse\nimport os\nimport joblib\nimport numpy as np\nrun = Run.get_context()\nparser = argparse.ArgumentParser()\nparser.add_argument('--in_n_estimator', type=int, default=8)\nparser.add_argument('--in_criterion', type=str, default='gini')\nparser.add_argument('--in_max_depth', type=int, default=2)\nargs = parser.parse_args()\nin_n_estimators = args.in_n_estimator\nin_criterion = args.in_criterion\nin_max_depth = args.in_max_depth\ndf = pd.read_csv('prepared_data.csv')\ncolumns = df.iloc[1:2, :-1].columns\nx = df[columns]\ny = df.iloc[:, -1:]\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25,\n random_state=2)\nmodel = RandomForestClassifier(n_estimators=in_n_estimators, criterion=\n in_criterion, max_depth=in_max_depth)\nmodel.fit(x_train, y_train)\naccuracy = model.score(x_test, y_test)\nrun.log('Accuracy', float(accuracy))\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(model, 'outputs/model_forest.joblib')\n", "step-5": "from sklearn.model_selection import train_test_split\nfrom azureml.core import Run\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport argparse\nimport os\nimport joblib\nimport numpy as np\n\n\n# Get the experiment run context\nrun = Run.get_context()\n\n# Get arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--in_n_estimator', type=int, default=8)\nparser.add_argument('--in_criterion', type=str, default=\"gini\")\nparser.add_argument('--in_max_depth', type=int, default=2)\n\nargs = parser.parse_args()\nin_n_estimators = args.in_n_estimator\nin_criterion = args.in_criterion\nin_max_depth = args.in_max_depth\n\n\n# read prepared data\ndf = pd.read_csv(\"prepared_data.csv\")\ncolumns = df.iloc[1:2, :-1].columns\nx = df[columns]\ny = df.iloc[:, -1:]\n\n# split data into train and test\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=2)\n\n# “gini”, “entropy”\nmodel = RandomForestClassifier(n_estimators=in_n_estimators, criterion=in_criterion, max_depth=in_max_depth)\n\nmodel.fit(x_train, y_train)\n\naccuracy = model.score(x_test, y_test)\nrun.log(\"Accuracy\", float(accuracy))\n\nos.makedirs('outputs', exist_ok=True)\njoblib.dump(model, 'outputs/model_forest.joblib')\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import os from xml.dom import minidom import numpy as np def get_branches_dir(root_dir): branches_dir = [] folds = os.listdir(root_dir) while folds: branch_dir = root_dir + '/' + folds.pop() branches_dir.append(branch_dir) return branches_dir def tolist(xml, detname): try: data = minidom.parse(xml) except: print('parse error') ErrorFiles.append(xml) return detectors = data.documentElement date = detectors.getElementsByTagName('date')[0].childNodes[0].data time = detectors.getElementsByTagName('time')[0].childNodes[0].data dets = detectors.getElementsByTagName('detector') laneVolume = 0 laneOccupancy = 0 laneSpeed = 0 for det in dets: try: detectorID = det.getElementsByTagName('detector-Id')[0] except IndexError: continue # print"\ndetector-Id: %s" % detectorID.childNodes[0].data if detectorID.childNodes[0].data in detname: lanes = det.getElementsByTagName('lane') for lane in lanes: # laneNumber = lane.getElementsByTagName('lane-Number')[0] laneStatus = lane.getElementsByTagName('lane-Status')[0] if laneStatus.childNodes[0].data == "OK": try: laneVolume += int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data) laneOccupancy += int(lane.getElementsByTagName('lane-Occupancy')[0].childNodes[0].data) * int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data) laneSpeed += int(lane.getElementsByTagName('lane-Speed')[0].childNodes[0].data) * int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data) except IndexError: break else: break if laneVolume > 0: for i in range(0, len(detname)): if detectorID.childNodes[0].data == detname[i]: c = i detectorData[c][0].append(date) detectorData[c][1].append(time) detectorData[c][2].append(laneVolume) detectorData[c][3].append(laneOccupancy/float(laneVolume)) detectorData[c][4].append(laneSpeed/float(laneVolume)) month_dir = 'C:/Users/ccrxf/PycharmProjects/FDA/07' os.chdir(month_dir) # change the current working directory to path. day_dir = get_branches_dir(month_dir) detNames = ['MI255E000.0D', 'MI270S013.6D', 'MI070E210.0D', 'MI070E243.9D', 'MI044E250.8D', 'MI044E246.6D'] ErrorFiles = [] for dayFile in day_dir: detectorData = [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]] xmlFiles = get_branches_dir(dayFile) for xml in xmlFiles: if not os.path.isdir(xml): print(xml) tolist(xml, detNames) for i in range(0, len(detNames)): m = np.array(detectorData[i]) os.chdir('C:/Users/ccrxf/PycharmProjects/FDA/npfiles/'+detNames[i]) np.save(detectorData[0][0][0]+'.npy', m)
normal
{ "blob_id": "2b7bb02a25504e7481d3bc637ea09bcf9addb990", "index": 7699, "step-1": "<mask token>\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detname):\n try:\n data = minidom.parse(xml)\n except:\n print('parse error')\n ErrorFiles.append(xml)\n return\n detectors = data.documentElement\n date = detectors.getElementsByTagName('date')[0].childNodes[0].data\n time = detectors.getElementsByTagName('time')[0].childNodes[0].data\n dets = detectors.getElementsByTagName('detector')\n laneVolume = 0\n laneOccupancy = 0\n laneSpeed = 0\n for det in dets:\n try:\n detectorID = det.getElementsByTagName('detector-Id')[0]\n except IndexError:\n continue\n if detectorID.childNodes[0].data in detname:\n lanes = det.getElementsByTagName('lane')\n for lane in lanes:\n laneStatus = lane.getElementsByTagName('lane-Status')[0]\n if laneStatus.childNodes[0].data == 'OK':\n try:\n laneVolume += int(lane.getElementsByTagName(\n 'lane-Volume')[0].childNodes[0].data)\n laneOccupancy += int(lane.getElementsByTagName(\n 'lane-Occupancy')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n laneSpeed += int(lane.getElementsByTagName(\n 'lane-Speed')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n except IndexError:\n break\n else:\n break\n if laneVolume > 0:\n for i in range(0, len(detname)):\n if detectorID.childNodes[0].data == detname[i]:\n c = i\n detectorData[c][0].append(date)\n detectorData[c][1].append(time)\n detectorData[c][2].append(laneVolume)\n detectorData[c][3].append(laneOccupancy / float(laneVolume))\n detectorData[c][4].append(laneSpeed / float(laneVolume))\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detname):\n try:\n data = minidom.parse(xml)\n except:\n print('parse error')\n ErrorFiles.append(xml)\n return\n detectors = data.documentElement\n date = detectors.getElementsByTagName('date')[0].childNodes[0].data\n time = detectors.getElementsByTagName('time')[0].childNodes[0].data\n dets = detectors.getElementsByTagName('detector')\n laneVolume = 0\n laneOccupancy = 0\n laneSpeed = 0\n for det in dets:\n try:\n detectorID = det.getElementsByTagName('detector-Id')[0]\n except IndexError:\n continue\n if detectorID.childNodes[0].data in detname:\n lanes = det.getElementsByTagName('lane')\n for lane in lanes:\n laneStatus = lane.getElementsByTagName('lane-Status')[0]\n if laneStatus.childNodes[0].data == 'OK':\n try:\n laneVolume += int(lane.getElementsByTagName(\n 'lane-Volume')[0].childNodes[0].data)\n laneOccupancy += int(lane.getElementsByTagName(\n 'lane-Occupancy')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n laneSpeed += int(lane.getElementsByTagName(\n 'lane-Speed')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n except IndexError:\n break\n else:\n break\n if laneVolume > 0:\n for i in range(0, len(detname)):\n if detectorID.childNodes[0].data == detname[i]:\n c = i\n detectorData[c][0].append(date)\n detectorData[c][1].append(time)\n detectorData[c][2].append(laneVolume)\n detectorData[c][3].append(laneOccupancy / float(laneVolume))\n detectorData[c][4].append(laneSpeed / float(laneVolume))\n\n\n<mask token>\nos.chdir(month_dir)\n<mask token>\nfor dayFile in day_dir:\n detectorData = [[[], [], [], [], []], [[], [], [], [], []], [[], [], [],\n [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [\n ], []]]\n xmlFiles = get_branches_dir(dayFile)\n for xml in xmlFiles:\n if not os.path.isdir(xml):\n print(xml)\n tolist(xml, detNames)\n for i in range(0, len(detNames)):\n m = np.array(detectorData[i])\n os.chdir('C:/Users/ccrxf/PycharmProjects/FDA/npfiles/' + detNames[i])\n np.save(detectorData[0][0][0] + '.npy', m)\n", "step-3": "<mask token>\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detname):\n try:\n data = minidom.parse(xml)\n except:\n print('parse error')\n ErrorFiles.append(xml)\n return\n detectors = data.documentElement\n date = detectors.getElementsByTagName('date')[0].childNodes[0].data\n time = detectors.getElementsByTagName('time')[0].childNodes[0].data\n dets = detectors.getElementsByTagName('detector')\n laneVolume = 0\n laneOccupancy = 0\n laneSpeed = 0\n for det in dets:\n try:\n detectorID = det.getElementsByTagName('detector-Id')[0]\n except IndexError:\n continue\n if detectorID.childNodes[0].data in detname:\n lanes = det.getElementsByTagName('lane')\n for lane in lanes:\n laneStatus = lane.getElementsByTagName('lane-Status')[0]\n if laneStatus.childNodes[0].data == 'OK':\n try:\n laneVolume += int(lane.getElementsByTagName(\n 'lane-Volume')[0].childNodes[0].data)\n laneOccupancy += int(lane.getElementsByTagName(\n 'lane-Occupancy')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n laneSpeed += int(lane.getElementsByTagName(\n 'lane-Speed')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n except IndexError:\n break\n else:\n break\n if laneVolume > 0:\n for i in range(0, len(detname)):\n if detectorID.childNodes[0].data == detname[i]:\n c = i\n detectorData[c][0].append(date)\n detectorData[c][1].append(time)\n detectorData[c][2].append(laneVolume)\n detectorData[c][3].append(laneOccupancy / float(laneVolume))\n detectorData[c][4].append(laneSpeed / float(laneVolume))\n\n\nmonth_dir = 'C:/Users/ccrxf/PycharmProjects/FDA/07'\nos.chdir(month_dir)\nday_dir = get_branches_dir(month_dir)\ndetNames = ['MI255E000.0D', 'MI270S013.6D', 'MI070E210.0D', 'MI070E243.9D',\n 'MI044E250.8D', 'MI044E246.6D']\nErrorFiles = []\nfor dayFile in day_dir:\n detectorData = [[[], [], [], [], []], [[], [], [], [], []], [[], [], [],\n [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [\n ], []]]\n xmlFiles = get_branches_dir(dayFile)\n for xml in xmlFiles:\n if not os.path.isdir(xml):\n print(xml)\n tolist(xml, detNames)\n for i in range(0, len(detNames)):\n m = np.array(detectorData[i])\n os.chdir('C:/Users/ccrxf/PycharmProjects/FDA/npfiles/' + detNames[i])\n np.save(detectorData[0][0][0] + '.npy', m)\n", "step-4": "import os\nfrom xml.dom import minidom\nimport numpy as np\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detname):\n try:\n data = minidom.parse(xml)\n except:\n print('parse error')\n ErrorFiles.append(xml)\n return\n detectors = data.documentElement\n date = detectors.getElementsByTagName('date')[0].childNodes[0].data\n time = detectors.getElementsByTagName('time')[0].childNodes[0].data\n dets = detectors.getElementsByTagName('detector')\n laneVolume = 0\n laneOccupancy = 0\n laneSpeed = 0\n for det in dets:\n try:\n detectorID = det.getElementsByTagName('detector-Id')[0]\n except IndexError:\n continue\n if detectorID.childNodes[0].data in detname:\n lanes = det.getElementsByTagName('lane')\n for lane in lanes:\n laneStatus = lane.getElementsByTagName('lane-Status')[0]\n if laneStatus.childNodes[0].data == 'OK':\n try:\n laneVolume += int(lane.getElementsByTagName(\n 'lane-Volume')[0].childNodes[0].data)\n laneOccupancy += int(lane.getElementsByTagName(\n 'lane-Occupancy')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n laneSpeed += int(lane.getElementsByTagName(\n 'lane-Speed')[0].childNodes[0].data) * int(lane\n .getElementsByTagName('lane-Volume')[0].\n childNodes[0].data)\n except IndexError:\n break\n else:\n break\n if laneVolume > 0:\n for i in range(0, len(detname)):\n if detectorID.childNodes[0].data == detname[i]:\n c = i\n detectorData[c][0].append(date)\n detectorData[c][1].append(time)\n detectorData[c][2].append(laneVolume)\n detectorData[c][3].append(laneOccupancy / float(laneVolume))\n detectorData[c][4].append(laneSpeed / float(laneVolume))\n\n\nmonth_dir = 'C:/Users/ccrxf/PycharmProjects/FDA/07'\nos.chdir(month_dir)\nday_dir = get_branches_dir(month_dir)\ndetNames = ['MI255E000.0D', 'MI270S013.6D', 'MI070E210.0D', 'MI070E243.9D',\n 'MI044E250.8D', 'MI044E246.6D']\nErrorFiles = []\nfor dayFile in day_dir:\n detectorData = [[[], [], [], [], []], [[], [], [], [], []], [[], [], [],\n [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [\n ], []]]\n xmlFiles = get_branches_dir(dayFile)\n for xml in xmlFiles:\n if not os.path.isdir(xml):\n print(xml)\n tolist(xml, detNames)\n for i in range(0, len(detNames)):\n m = np.array(detectorData[i])\n os.chdir('C:/Users/ccrxf/PycharmProjects/FDA/npfiles/' + detNames[i])\n np.save(detectorData[0][0][0] + '.npy', m)\n", "step-5": "import os\nfrom xml.dom import minidom\nimport numpy as np\n\n\ndef get_branches_dir(root_dir):\n branches_dir = []\n folds = os.listdir(root_dir)\n while folds:\n branch_dir = root_dir + '/' + folds.pop()\n branches_dir.append(branch_dir)\n return branches_dir\n\n\ndef tolist(xml, detname):\n try:\n data = minidom.parse(xml)\n except:\n print('parse error')\n ErrorFiles.append(xml)\n return\n\n detectors = data.documentElement\n date = detectors.getElementsByTagName('date')[0].childNodes[0].data\n time = detectors.getElementsByTagName('time')[0].childNodes[0].data\n dets = detectors.getElementsByTagName('detector')\n laneVolume = 0\n laneOccupancy = 0\n laneSpeed = 0\n for det in dets:\n try:\n detectorID = det.getElementsByTagName('detector-Id')[0]\n except IndexError:\n continue\n # print\"\\ndetector-Id: %s\" % detectorID.childNodes[0].data\n if detectorID.childNodes[0].data in detname:\n lanes = det.getElementsByTagName('lane')\n for lane in lanes:\n # laneNumber = lane.getElementsByTagName('lane-Number')[0]\n laneStatus = lane.getElementsByTagName('lane-Status')[0]\n if laneStatus.childNodes[0].data == \"OK\":\n try:\n laneVolume += int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data)\n laneOccupancy += int(lane.getElementsByTagName('lane-Occupancy')[0].childNodes[0].data) * int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data)\n laneSpeed += int(lane.getElementsByTagName('lane-Speed')[0].childNodes[0].data) * int(lane.getElementsByTagName('lane-Volume')[0].childNodes[0].data)\n except IndexError:\n break\n else:\n break\n\n if laneVolume > 0:\n for i in range(0, len(detname)):\n if detectorID.childNodes[0].data == detname[i]:\n c = i\n detectorData[c][0].append(date)\n detectorData[c][1].append(time)\n detectorData[c][2].append(laneVolume)\n detectorData[c][3].append(laneOccupancy/float(laneVolume))\n detectorData[c][4].append(laneSpeed/float(laneVolume))\n\n\nmonth_dir = 'C:/Users/ccrxf/PycharmProjects/FDA/07'\nos.chdir(month_dir) # change the current working directory to path.\nday_dir = get_branches_dir(month_dir)\ndetNames = ['MI255E000.0D', 'MI270S013.6D', 'MI070E210.0D', 'MI070E243.9D', 'MI044E250.8D', 'MI044E246.6D']\nErrorFiles = []\nfor dayFile in day_dir:\n detectorData = [[[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]\n xmlFiles = get_branches_dir(dayFile)\n for xml in xmlFiles:\n if not os.path.isdir(xml):\n print(xml)\n tolist(xml, detNames)\n\n for i in range(0, len(detNames)):\n m = np.array(detectorData[i])\n os.chdir('C:/Users/ccrxf/PycharmProjects/FDA/npfiles/'+detNames[i])\n np.save(detectorData[0][0][0]+'.npy', m)\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
from collections.abc import Iterator import json import click def print_json(obj, err=False): if isinstance(obj, Iterator): obj = list(obj) click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False), err=err) def show_fields(*fields): def show(obj, verbose=False): if verbose: return obj about = {} for entry in fields: if isinstance(entry, str): entry = (entry,) name, *subpath = entry try: value = obj[name] except KeyError: continue for sp in subpath: if value is None: break elif callable(sp): value = sp(value) elif isinstance(value, list): value = [v and v[sp] for v in value] else: value = value[sp] about[name] = value return about return show repo_info = show_fields( ("owner", "login"), "name", "url", "html_url", "clone_url", "git_url", "ssh_url", "full_name", "description", "homepage", "private", "default_branch", "created_at", "updated_at", "pushed_at", "fork", "forks_count", "watchers_count", "size", "subscribers_count", "stargazers_count", "id", "language", "network_count", "open_issues_count", ("parent", "full_name"), ("source", "full_name"), ) gist_info = show_fields( "id", "url", "git_push_url", ("files", lambda files: { fname: {k:v for k,v in about.items() if k != 'content'} for fname, about in files.items() }), "public", "html_url", ("owner", "login"), "description", "created_at", "updated_at", "comments", ("fork_of", "id"), ("forks", "id"), ) issue_info = show_fields( ("assignees", "login"), "closed_at", ("closed_by", "login"), "comments", "created_at", "html_url", "id", ("labels", "name"), "locked", ("milestone", "title"), "number", "state", "title", "updated_at", "url", ("user", "login"), "repository_url", ### pull_request )
normal
{ "blob_id": "d340ac979f57cf4650131665e4fa5b9923f22a3e", "index": 6691, "step-1": "<mask token>\n\n\ndef print_json(obj, err=False):\n if isinstance(obj, Iterator):\n obj = list(obj)\n click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False\n ), err=err)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef print_json(obj, err=False):\n if isinstance(obj, Iterator):\n obj = list(obj)\n click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False\n ), err=err)\n\n\ndef show_fields(*fields):\n\n def show(obj, verbose=False):\n if verbose:\n return obj\n about = {}\n for entry in fields:\n if isinstance(entry, str):\n entry = entry,\n name, *subpath = entry\n try:\n value = obj[name]\n except KeyError:\n continue\n for sp in subpath:\n if value is None:\n break\n elif callable(sp):\n value = sp(value)\n elif isinstance(value, list):\n value = [(v and v[sp]) for v in value]\n else:\n value = value[sp]\n about[name] = value\n return about\n return show\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef print_json(obj, err=False):\n if isinstance(obj, Iterator):\n obj = list(obj)\n click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False\n ), err=err)\n\n\ndef show_fields(*fields):\n\n def show(obj, verbose=False):\n if verbose:\n return obj\n about = {}\n for entry in fields:\n if isinstance(entry, str):\n entry = entry,\n name, *subpath = entry\n try:\n value = obj[name]\n except KeyError:\n continue\n for sp in subpath:\n if value is None:\n break\n elif callable(sp):\n value = sp(value)\n elif isinstance(value, list):\n value = [(v and v[sp]) for v in value]\n else:\n value = value[sp]\n about[name] = value\n return about\n return show\n\n\nrepo_info = show_fields(('owner', 'login'), 'name', 'url', 'html_url',\n 'clone_url', 'git_url', 'ssh_url', 'full_name', 'description',\n 'homepage', 'private', 'default_branch', 'created_at', 'updated_at',\n 'pushed_at', 'fork', 'forks_count', 'watchers_count', 'size',\n 'subscribers_count', 'stargazers_count', 'id', 'language',\n 'network_count', 'open_issues_count', ('parent', 'full_name'), (\n 'source', 'full_name'))\ngist_info = show_fields('id', 'url', 'git_push_url', ('files', lambda files:\n {fname: {k: v for k, v in about.items() if k != 'content'} for fname,\n about in files.items()}), 'public', 'html_url', ('owner', 'login'),\n 'description', 'created_at', 'updated_at', 'comments', ('fork_of', 'id'\n ), ('forks', 'id'))\nissue_info = show_fields(('assignees', 'login'), 'closed_at', ('closed_by',\n 'login'), 'comments', 'created_at', 'html_url', 'id', ('labels', 'name'\n ), 'locked', ('milestone', 'title'), 'number', 'state', 'title',\n 'updated_at', 'url', ('user', 'login'), 'repository_url')\n", "step-4": "from collections.abc import Iterator\nimport json\nimport click\n\n\ndef print_json(obj, err=False):\n if isinstance(obj, Iterator):\n obj = list(obj)\n click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False\n ), err=err)\n\n\ndef show_fields(*fields):\n\n def show(obj, verbose=False):\n if verbose:\n return obj\n about = {}\n for entry in fields:\n if isinstance(entry, str):\n entry = entry,\n name, *subpath = entry\n try:\n value = obj[name]\n except KeyError:\n continue\n for sp in subpath:\n if value is None:\n break\n elif callable(sp):\n value = sp(value)\n elif isinstance(value, list):\n value = [(v and v[sp]) for v in value]\n else:\n value = value[sp]\n about[name] = value\n return about\n return show\n\n\nrepo_info = show_fields(('owner', 'login'), 'name', 'url', 'html_url',\n 'clone_url', 'git_url', 'ssh_url', 'full_name', 'description',\n 'homepage', 'private', 'default_branch', 'created_at', 'updated_at',\n 'pushed_at', 'fork', 'forks_count', 'watchers_count', 'size',\n 'subscribers_count', 'stargazers_count', 'id', 'language',\n 'network_count', 'open_issues_count', ('parent', 'full_name'), (\n 'source', 'full_name'))\ngist_info = show_fields('id', 'url', 'git_push_url', ('files', lambda files:\n {fname: {k: v for k, v in about.items() if k != 'content'} for fname,\n about in files.items()}), 'public', 'html_url', ('owner', 'login'),\n 'description', 'created_at', 'updated_at', 'comments', ('fork_of', 'id'\n ), ('forks', 'id'))\nissue_info = show_fields(('assignees', 'login'), 'closed_at', ('closed_by',\n 'login'), 'comments', 'created_at', 'html_url', 'id', ('labels', 'name'\n ), 'locked', ('milestone', 'title'), 'number', 'state', 'title',\n 'updated_at', 'url', ('user', 'login'), 'repository_url')\n", "step-5": "from collections.abc import Iterator\nimport json\nimport click\n\ndef print_json(obj, err=False):\n if isinstance(obj, Iterator):\n obj = list(obj)\n click.echo(json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False),\n err=err)\n\ndef show_fields(*fields):\n def show(obj, verbose=False):\n if verbose:\n return obj\n about = {}\n for entry in fields:\n if isinstance(entry, str):\n entry = (entry,)\n name, *subpath = entry\n try:\n value = obj[name]\n except KeyError:\n continue\n for sp in subpath:\n if value is None:\n break\n elif callable(sp):\n value = sp(value)\n elif isinstance(value, list):\n value = [v and v[sp] for v in value]\n else:\n value = value[sp]\n about[name] = value\n return about\n return show\n\nrepo_info = show_fields(\n (\"owner\", \"login\"),\n \"name\",\n \"url\",\n \"html_url\",\n \"clone_url\",\n \"git_url\",\n \"ssh_url\",\n \"full_name\",\n \"description\",\n \"homepage\",\n \"private\",\n \"default_branch\",\n \"created_at\",\n \"updated_at\",\n \"pushed_at\",\n \"fork\",\n \"forks_count\",\n \"watchers_count\",\n \"size\",\n \"subscribers_count\",\n \"stargazers_count\",\n \"id\",\n \"language\",\n \"network_count\",\n \"open_issues_count\",\n (\"parent\", \"full_name\"),\n (\"source\", \"full_name\"),\n)\n\ngist_info = show_fields(\n \"id\",\n \"url\",\n \"git_push_url\",\n (\"files\", lambda files: {\n fname: {k:v for k,v in about.items() if k != 'content'}\n for fname, about in files.items()\n }),\n \"public\",\n \"html_url\",\n (\"owner\", \"login\"),\n \"description\",\n \"created_at\",\n \"updated_at\",\n \"comments\",\n (\"fork_of\", \"id\"),\n (\"forks\", \"id\"),\n)\n\nissue_info = show_fields(\n (\"assignees\", \"login\"),\n \"closed_at\",\n (\"closed_by\", \"login\"),\n \"comments\",\n \"created_at\",\n \"html_url\",\n \"id\",\n (\"labels\", \"name\"),\n \"locked\",\n (\"milestone\", \"title\"),\n \"number\",\n \"state\",\n \"title\",\n \"updated_at\",\n \"url\",\n (\"user\", \"login\"),\n \"repository_url\",\n ### pull_request\n)\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
REDIRECT_MAP = { '90':'19904201', '91':'19903329', '92':'19899125', '93':'19901043', '94':'19903192', '95':'19899788', '97':'19904423', '98':'19906163', '99':'19905540', '100':'19907871', '101':'19908147', '102':'19910103', '103':'19909980', '104':'19911813', '105':'19911767', '106':'19913625', '107':'19913832', '108':'19915603', '109':'19915707', '110':'19915705', '111':'19915558', '112':'19917330', '113':'19917085', '114':'19918316', '115':'19919617', '116':'19918555', '117':'19919779', '118':'19920594', '119':'19920805', '120':'19921503', '121':'19923032', '122':'19922349', '123':'19923894', '124':'19924058', '125':'19924651', '126':'19929744', '127':'19929743', '128':'19929742', '129':'19929184', '130':'19929183', '131':'19928163', '132':'19927463', '133':'19927462', '134':'19927461', '135':'19926742', '136':'19926741', '137':'19926738', '138':'19930143', '139':'19930827', '140':'19931617', '141':'19931616', '142':'19932324', '143':'19932321', '144':'19932320', '145':'19932845', '146':'19932843', '147':'19932842', '148':'19932839', '149':'19933621', '150':'19933618', '151':'19934526', '152':'19934525', '153':'19934524', '154':'19935167', '155':'19935165', '156':'19936598', '157':'19936596', '158':'19936594', '160':'19937949', '161':'19937662', '162':'19937662', '163':'19937662', '164':'19937662', '165':'19937662', '166':'19940346', '167':'19939390', '168':'19938892', '169':'19938886', '170':'19938874', '171':'19938181', '172':'19938179', '173':'19938177', '174':'19937662', '175':'19937662', '176':'800073144', '177':'800073141', '178':'800070989', '179':'800070987', '180':'800070985', '181':'800068840', '182':'800068838', '183':'800068837', '184':'800068835', '185':'800073405', '186':'800075467', '187':'800075466', '188':'800077797', '189':'800077792', '190':'800077788', '191':'800080302', '192':'800080300', '193':'800080299', '194':'800080297', '195':'800080295', '196':'800080294', '197':'800082560', '198':'800082559', '199':'800082558', '200':'800085053', '201':'800085057', '202':'800085055', '203':'800087660', '204':'800087637', '205':'800087636', '206':'800090260', '207':'800090259', '208':'800090256', '209':'800090252', '210':'800090248', '211':'800095783', '212':'800093475', '213':'800093472', '214':'800093469', '215':'800093465', '216':'800097835', '217':'800097830', '218':'800097828', '219':'800102815', '220':'800100696', '221':'800107510', '222':'800105566', '223':'800105187', '224':'800105182', '225':'800105176', '226':'800105171', '227':'800110082', '228':'800110080', '229':'800110077', '230':'800107893', '231':'800112573', '232':'800112572', '233':'800112570', '234':'800115083', '235':'800115080', '236':'800117652', '237':'800136223', '238':'800135715', '239':'800135712', '240':'800127734', '241':'800125056', '242':'800125055', '243':'800125054', '244':'800122499', '245':'800122497', '246':'800120063', '247':'800120060', '248':'800118016', '249':'800118015', '250':'800138744', '251':'800138741', '252':'800138440', '253':'800156510', '254':'800156507', '255':'800159343', '256':'800200950', '257':'800200946', '258':'800180350', '259':'800180348', '260':'800162155', '261':'800162153', '262':'800159803', '263':'800205850', '264':'800205839', '265':'800210303', '266':'800210302', '267':'800212467', '268':'800212465', '269':'800212462', '270':'800215849', '271':'800218413', '272':'800220590', '273':'800220585', '274':'800220581', '275':'800220568', '276':'800223836', '277':'800223835', '278':'800226881', '279':'800226876', '280':'800226875', '281':'800229066', '282':'800229064', '283':'800232046', '284':'800232043', '285':'800234330', '286':'800234329', '287':'800234328', '288':'800239516', '289':'800236806', '290':'800242231', '291':'800242196', '292':'800242177', '293':'800245005', '294':'800247477', '295':'800247307', '296':'800247092', '297':'800250315', '298':'800250206', '299':'800250198', '300':'800252661', '301':'800252745', '302':'800252731', '303':'800255314', '304':'800255226', '305':'800261560', '306':'800264399', '307':'800264337', '308':'800262863', '309':'800267317', '310':'800268635', '311':'800270225', '312':'800272621', '313':'800272861', '314':'800275290', '315':'800275287', '316':'800275259', '317':'800277905', '318':'800277897', '319':'800277966', '320':'800280886', '321':'800280734', '322':'800280721', '323':'800283469', '324':'800283455', '325':'800291555', '326':'800291531', '327':'800288739', '328':'800286042', '329':'800286032', '330':'800294431', '331':'800294423', '332':'800294394', '333':'800297383', '334':'800299835', '335':'800302625', '336':'800305630', '337':'800305626', '338':'800308225', '339':'800307935', '340':'800308160', '341':'800308242', '342':'800310811', '343':'800310657', '344':'800310651', '345':'800312843', '346':'800313657', '347':'800313593', '348':'800313385', '349':'800315870', '350':'800315874', '351':'800315004', '352':'800315980', '353':'800317852', '354':'800317851', '355':'800317843', '356':'800317841', '357':'800320232', '358':'800322836', '359':'800322833', '360':'800325648', '361':'800325641', '362':'800328374', '363':'800328368', '364':'800330891', '365':'800330882', '366':'800330878', '367':'800336505', '368':'800336491', '369':'800338571', '370':'800341852', '371':'800339471', '372':'800344570', '373':'800344561', '374':'800344557', '375':'800347295', '376':'800348755', '377':'800350263', '378':'800350259', '379':'800353149', '380':'800351527', '381':'800355911', '382':'800355907', '383':'800358602', '384':'800358597', '385':'800357146', '386':'800360127', '387':'800364368', '388':'800364364', '389':'800364360', '390':'800369266', '391':'800367438', '392':'800367435', '393':'800365869', '394':'800376494', '395':'800376495', '396':'800376499', '397':'800376508', '398':'800376564', '399':'800376527', '400':'800376534', '401':'800376542', '402':'800376553', '403':'800376547', '404':'800373150', '405':'800373145', '406':'800372444', '407':'800372437', '408':'800372425', '409':'800379488', '410':'800382132', '411':'800382127', '412':'800382125', '413':'800386300', '414':'800384980', '415':'800384977', '416':'800387613', '417':'800387609', '418':'800390598', '419':'800390595', '420':'800390593', '421':'800391756', '422':'800393267', '423':'800396025', '424':'800399068', '425':'800401344', '426':'800404124', '427':'800408946', '428':'800407272', '429':'800407265', '430':'800411526', '431':'800411522', '432':'800414380', '433':'800413104', '434':'800413099', '435':'800415905', '436':'800415900', '437':'800417356', '438':'800420038', '439':'800420034', '440':'800420028', '441':'800422801', '442':'800421597', '443':'800421594', '444':'800427313', '445':'800427308', '446':'800427302', '447':'800427296', '448':'800428813', '449':'800430293', '450':'800430281', '451':'800430273', '452':'800434255', '453':'800434253', '454':'800434251', '455':'800434249', '456':'800434246', '457':'800431774', '458':'800443507', '459':'800442246', '460':'800440771', '461':'800439363', '462':'800439359', '463':'800436898', '464':'800434258', '465':'800446256', '466':'800450435', '467':'800450429', '468':'800450424', '469':'800452914', '470':'800452909', '471':'800452023', '472':'800452016', '473':'800455755', '474':'800455748', '475':'800457050', '476':'800458494', '477':'800461157', '478':'800459620', '479':'800464361', '480':'800464980', '481':'800462270', '482':'800465908', '483':'800465407', '484':'800465404', '485':'800467476', '486':'800467755', '487':'800468407', '488':'800468843', '489':'800469869', '490':'800469867', '491':'800470232', '492':'800470228', '493':'800470224', '494':'800470783', '495':'800471280', '496':'800471274', '497':'800471270', '498':'800471737', '499':'800472257', '500':'800472252', '501':'800472248', '502':'800472239', '503':'800472826', '504':'800473392', '505':'800473387', '506':'800473386', '507':'800474131', '508':'800474822', '509':'800476516', '510':'800476512', '511':'800477305', '512':'800477304', '513':'800477299', '514':'800477851', '515':'800478313', '516':'800478309', '517':'800478779', '518':'800479288', '519':'800479679', '520':'800480262', '521':'800480257', '522':'800483194', '523':'800482720', '524':'800482271', '525':'800481660', '526':'800481208', '527':'800480699', '528':'800483203', '529':'800483712', '530':'800484088', '531':'800484085', '532':'800484667', '533':'800485151', '534':'800485686', '535':'800487288', '536':'800487265', '537':'800487264', '538':'800487254', '539':'800487654', '540':'800488015', '541':'800488014', '542':'800488638', '543':'800488635', '544':'800489081', '545':'800489074', '546':'800489725', '547':'800489722', '548':'800490703', '549':'800490702', '550':'800492228', '551':'800494213', '552':'800494039', '553':'800494442', '554':'800494426', '555':'800495547', '556':'800495446', '557':'800496750', '558':'800498164', '559':'800498748', '560':'800499418', '561':'800499229', '562':'800500847', '563':'800500844', '564':'800500802', '565':'800501840', '566':'800501597', '567':'800502796', '568':'800502789', '569':'800503614', '570':'800504092', '571':'800503911', '572':'800508001', '573':'800507103', '574':'800506285', '575':'800505846', '576':'800505807', '577':'800505069', '578':'800509304', '579':'800509218', '580':'800508912', '581':'800509464', '582':'800510151', '583':'800511800', '584':'800511318', '585':'800512405', '586':'800512403', '587':'800513304', '588':'800513305', '589':'800513635', '590':'800513633', '591':'800514762', '592':'800514759', '593':'800515655', '594':'800515656', '595':'800516480', '596':'800516479', '597':'800516478', '598':'800517736', '599':'800517735', '600':'800517733', '601':'800517148', '602':'800517143', '603':'800517138', '604':'800519296', '605':'800519292', '606':'800520855', '607':'800520857', '608':'800520736', '609':'800521674', '610':'800522862', '611':'800523828', '612':'800523825', '613':'800524526', '614':'800524868', '615':'800525568', '616':'800525566', '617':'800525848', '618':'800525847', '619':'800525845', '620':'800526925', '621':'800526923', '622':'800526922', '623':'800528032', '624':'800527784', '625':'800527783', '626':'800529243', '627':'800528930', '628':'800528927', '629':'800530217', '630':'800530215', '631':'800530212', '632':'800531040', '633':'800530845', '634':'800530842', '635':'800531892', '636':'800532956', '637':'800532952', '638':'800533102', '639':'800534375', '640':'800534368', '641':'800534363', '642':'800535420', '643':'800535415', '644':'800535410', '645':'800536088', '646':'800536085', '647':'800536084', '648':'800537422', '649':'800537419', '650':'800537413', '651':'800565995', '652':'800565992', '653':'800563301', '654':'800563298', '655':'800562019', '656':'800562018', '657':'800560957', '658':'800560954', '659':'800560953', '660':'800560950', '661':'800567960', '662':'800567958', '663':'800567957', '664':'800566950', '665':'800566948', '666':'800566947', '667':'800568961', '668':'800568959', '669':'800568957', '670':'800569778', '671':'800569776', '672':'800569775', '673':'800570677', '674':'800570673', '675':'800570647', '676':'800571691', '677':'800571690', '678':'800571688', '679':'800573679', '680':'800573678', '681':'800573673', '682':'800572880', '683':'800572878', '684':'800572876', '685':'800574667', '686':'800574666', '687':'800574665', '688':'800575627', '689':'800575624', '690':'800575622', '691':'800576864', '692':'800576861', '693':'800576858', '694':'800577693', '695':'800578651', '696':'800578648', '697':'800578653', '698':'800580339', '699':'800581315', '700':'800582094', '701':'800583021', '702':'800590020', '703':'800590019', '704':'800590018', '705':'800589231', '706':'800589226', '707':'800588877', '708':'800587042', '709':'800587039', '710':'800586085', '711':'800584924', '712':'800583934', '713':'800590941', '714':'800590940', '715':'800590939', '716':'800592923', '717':'800592921', '718':'800592920', '719':'800591918', '720':'800591917', '721':'800591915', '722':'800593832', '723':'800593829', '724':'800593824', '725':'800593890', '726':'800594956', '727':'800594880', '728':'800594877', '729':'800594876', '730':'800595884', '731':'800595883', '732':'800595882', '733':'800595879', '734':'800596854', '735':'800597955', '736':'800597961', '737':'800597957', '738':'800597954', '739':'800597951', '740':'800598913', '741':'800600005', '742':'800600003', '743':'800600000', '744':'800600977', '745':'800600975', '746':'800600973', '747':'800601974', '748':'800603879', '749':'800603052', '750':'800603050', '751':'800604977', '752':'800605959', '753':'800607128', '754':'800608295', '755':'800608294', '756':'800608293', '757':'800609876', '758':'800610697', '759':'800611768', '760':'800611766', '761':'800611764', '762':'800612811', '763':'800612809', '764':'800612806', '765':'800615487', '766':'800613824', '767':'800613823', '768':'800617427', '769':'800617740', '770':'800618987', '771':'800618794', '772':'800620463', '773':'800620507', '774':'800621873', '775':'800621866', '776':'800621485', '777':'800623063', '778':'800622785', '779':'800624082', '780':'800624606', '781':'800624605', '782':'800624602', '783':'800626006', '784':'800626004', '785':'800625998', '786':'800625995', '787':'800625959', '788':'800625684', '789':'800627159', '790':'800627541', '791':'800628537', '792':'800628472', '793':'800628440', '794':'800628412', '795':'800628391', '796':'800629230', '797':'800629175', '798':'800630245', '799':'800630236', '800':'800631787', '801':'800631425', '802':'800631385', '803':'800631379', '804':'800631339', '805':'800631299', '806':'800631198', '807':'800630886', '808':'800633920', '809':'800633720', '810':'800633520', '811':'800634419', '812':'800635301', '813':'800635068', '814':'800635957', '815':'800638994', '816':'800638105', '817':'800637068', '818':'800636754', '819':'800636749', '820':'800636075', '821':'800639448', '822':'800639234', '823':'800639026', '824':'800640408', '825':'800640396', '826':'800640985', '827':'800640977', '828':'800645321', '829':'800644531', '830':'800644235', '831':'800643606', '832':'800642400', '833':'800641879', '834':'800645756', '835':'800647017', '836':'800648350', '837':'800648289', '838':'800648124', '839':'800647488', '840':'800649911', '841':'800649906', '842':'800649535', '843':'800649521', '844':'800649507', '845':'800649438', '846':'800649411', '847':'800650580', '848':'800652017', '849':'800652004', '850':'800651999', '851':'800651955', '852':'800651790', '853':'800651264', '854':'800651159', '855':'800652276', '856':'800652260', '857':'800654483', '858':'800654117', '859':'800654927', '860':'800656751', '861':'800656720', '862':'800656504', '863':'800656476', '864':'800655926', '865':'800658883', '866':'800659871', '867':'800659855', '868':'800657502', '869':'800662419', '870':'800663417', '871':'800661565', '872':'800664542', '873':'800665790', '874':'800667640', '875':'800668511', '876':'800668354', '877':'800668932', '878':'800668884', '879':'800668870', '880':'800668846', '881':'800670519', '882':'800670755', '883':'800670804', '884':'800670005', '885':'800669956', '886':'800671522', '887':'800670997', '888':'800676274', '889':'800674751', '890':'800674396', '891':'800674387', '892':'800674369', '893':'800674171', '894':'800674165', '895':'800673904', '896':'800673894', '897':'800673042', '898':'800672682', '899':'800673037', '900':'800674363', '901':'800671334', '902':'800676404', '903':'800677203', '904':'800678281', '905':'800677753', '906':'800678579', '907':'800678543', '908':'800682417', '909':'800680556', '910':'800680572', '911':'800681753', '912':'800683728', '913':'800683445', '914':'800684755', '915':'800685559', '916':'800685994', '917':'800686991', '918':'800688325', '919':'800688988', '920':'800688986', '921':'800688811', '922':'800688784', '923':'800690794', '924':'800690777', '925':'800690766', '926':'800691744', '927':'800691714', '928':'800691608', '929':'800691675', '930':'800692072', '931':'800692888', '932':'800692853', '933':'800694793', '934':'800695410', '935':'800696421', '936':'800696417', '937':'800696404', '938':'800696380', '939':'800695901', '940':'800696527', '941':'800696521', '942':'800696516', '943':'800697754', '944':'800698640', '945':'800700044', '946':'800700030', '947':'800700001', '948':'800699969', '949':'800700477', '950':'800700332', '951':'800701388', '952':'800701378', '953':'800702260', '954':'800702167', '955':'800702170', '956':'800703184', '957':'800703189', '958':'800704417', '959':'800704334', '960':'800704331', '961':'800705315', '962':'800705310', '963':'800706319', '964':'800706317', '965':'800707543', '966':'800707540', '967':'800707378', '968':'800707376', '969':'800707372', '970':'800709165', '971':'800709918', '972':'800709909', '973':'800709913', '974':'800709590', '975':'800709592', '976':'800711385', '977':'800711436', '978':'800711448', '979':'800712704', '980':'800712684', '981':'800712697', '982':'800713805', '983':'800713786', '984':'800715143', '985':'800715140', '986':'800717742', '987':'800717725', '988':'800717083', '989':'800719807', '990':'800719797', '991':'800721331', '992':'800721317', '993':'800722269', '994':'800722253', '995':'800722190', '996':'800723313', '997':'800723082', } REDIRECT_MAP_CATEGORIES = { '27':'438046136', '28':'438046133', '29':'438046135', '30':'438046134', '31':'438046128', '32':'438046127', '33':'438046130', '34':'438046131', '35':'438046132', '36':'438046129', }
normal
{ "blob_id": "fb92912e1a752f3766f9439f75ca28379e23823f", "index": 3600, "step-1": "<mask token>\n", "step-2": "REDIRECT_MAP = {'90': '19904201', '91': '19903329', '92': '19899125', '93':\n '19901043', '94': '19903192', '95': '19899788', '97': '19904423', '98':\n '19906163', '99': '19905540', '100': '19907871', '101': '19908147',\n '102': '19910103', '103': '19909980', '104': '19911813', '105':\n '19911767', '106': '19913625', '107': '19913832', '108': '19915603',\n '109': '19915707', '110': '19915705', '111': '19915558', '112':\n '19917330', '113': '19917085', '114': '19918316', '115': '19919617',\n '116': '19918555', '117': '19919779', '118': '19920594', '119':\n '19920805', '120': '19921503', '121': '19923032', '122': '19922349',\n '123': '19923894', '124': '19924058', '125': '19924651', '126':\n '19929744', '127': '19929743', '128': '19929742', '129': '19929184',\n '130': '19929183', '131': '19928163', '132': '19927463', '133':\n '19927462', '134': '19927461', '135': '19926742', '136': '19926741',\n '137': '19926738', '138': '19930143', '139': '19930827', '140':\n '19931617', '141': '19931616', '142': '19932324', '143': '19932321',\n '144': '19932320', '145': '19932845', '146': '19932843', '147':\n '19932842', '148': '19932839', '149': '19933621', '150': '19933618',\n '151': '19934526', '152': '19934525', '153': '19934524', '154':\n '19935167', '155': '19935165', '156': '19936598', '157': '19936596',\n '158': '19936594', '160': '19937949', '161': '19937662', '162':\n '19937662', '163': '19937662', '164': '19937662', '165': '19937662',\n '166': '19940346', '167': '19939390', '168': '19938892', '169':\n '19938886', '170': '19938874', '171': '19938181', '172': '19938179',\n '173': '19938177', '174': '19937662', '175': '19937662', '176':\n '800073144', '177': '800073141', '178': '800070989', '179': '800070987',\n '180': '800070985', '181': '800068840', '182': '800068838', '183':\n '800068837', '184': '800068835', '185': '800073405', '186': '800075467',\n '187': '800075466', '188': '800077797', '189': '800077792', '190':\n '800077788', '191': '800080302', '192': '800080300', '193': '800080299',\n '194': '800080297', '195': '800080295', '196': '800080294', '197':\n '800082560', '198': '800082559', '199': '800082558', '200': '800085053',\n '201': '800085057', '202': '800085055', '203': '800087660', '204':\n '800087637', '205': '800087636', '206': '800090260', '207': '800090259',\n '208': '800090256', '209': '800090252', '210': '800090248', '211':\n '800095783', '212': '800093475', '213': '800093472', '214': '800093469',\n '215': '800093465', '216': '800097835', '217': '800097830', '218':\n '800097828', '219': '800102815', '220': '800100696', '221': '800107510',\n '222': '800105566', '223': '800105187', '224': '800105182', '225':\n '800105176', '226': '800105171', '227': '800110082', '228': '800110080',\n '229': '800110077', '230': '800107893', '231': '800112573', '232':\n '800112572', '233': '800112570', '234': '800115083', '235': '800115080',\n '236': '800117652', '237': '800136223', '238': '800135715', '239':\n '800135712', '240': '800127734', '241': '800125056', '242': '800125055',\n '243': '800125054', '244': '800122499', '245': '800122497', '246':\n '800120063', '247': '800120060', '248': '800118016', '249': '800118015',\n '250': '800138744', '251': '800138741', '252': '800138440', '253':\n '800156510', '254': '800156507', '255': '800159343', '256': '800200950',\n '257': '800200946', '258': '800180350', '259': '800180348', '260':\n '800162155', '261': '800162153', '262': '800159803', '263': '800205850',\n '264': '800205839', '265': '800210303', '266': '800210302', '267':\n '800212467', '268': '800212465', '269': '800212462', '270': '800215849',\n '271': '800218413', '272': '800220590', '273': '800220585', '274':\n '800220581', '275': '800220568', '276': '800223836', '277': '800223835',\n '278': '800226881', '279': '800226876', '280': '800226875', '281':\n '800229066', '282': '800229064', '283': '800232046', '284': '800232043',\n '285': '800234330', '286': '800234329', '287': '800234328', '288':\n '800239516', '289': '800236806', '290': '800242231', '291': '800242196',\n '292': '800242177', '293': '800245005', '294': '800247477', '295':\n '800247307', '296': '800247092', '297': '800250315', '298': '800250206',\n '299': '800250198', '300': '800252661', '301': '800252745', '302':\n '800252731', '303': '800255314', '304': '800255226', '305': '800261560',\n '306': '800264399', '307': '800264337', '308': '800262863', '309':\n '800267317', '310': '800268635', '311': '800270225', '312': '800272621',\n '313': '800272861', '314': '800275290', '315': '800275287', '316':\n '800275259', '317': '800277905', '318': '800277897', '319': '800277966',\n '320': '800280886', '321': '800280734', '322': '800280721', '323':\n '800283469', '324': '800283455', '325': '800291555', '326': '800291531',\n '327': '800288739', '328': '800286042', '329': '800286032', '330':\n '800294431', '331': '800294423', '332': '800294394', '333': '800297383',\n '334': '800299835', '335': '800302625', '336': '800305630', '337':\n '800305626', '338': '800308225', '339': '800307935', '340': '800308160',\n '341': '800308242', '342': '800310811', '343': '800310657', '344':\n '800310651', '345': '800312843', '346': '800313657', '347': '800313593',\n '348': '800313385', '349': '800315870', '350': '800315874', '351':\n '800315004', '352': '800315980', '353': '800317852', '354': '800317851',\n '355': '800317843', '356': '800317841', '357': '800320232', '358':\n '800322836', '359': '800322833', '360': '800325648', '361': '800325641',\n '362': '800328374', '363': '800328368', '364': '800330891', '365':\n '800330882', '366': '800330878', '367': '800336505', '368': '800336491',\n '369': '800338571', '370': '800341852', '371': '800339471', '372':\n '800344570', '373': '800344561', '374': '800344557', '375': '800347295',\n '376': '800348755', '377': '800350263', '378': '800350259', '379':\n '800353149', '380': '800351527', '381': '800355911', '382': '800355907',\n '383': '800358602', '384': '800358597', '385': '800357146', '386':\n '800360127', '387': '800364368', '388': '800364364', '389': '800364360',\n '390': '800369266', '391': '800367438', '392': '800367435', '393':\n '800365869', '394': '800376494', '395': '800376495', '396': '800376499',\n '397': '800376508', '398': '800376564', '399': '800376527', '400':\n '800376534', '401': '800376542', '402': '800376553', '403': '800376547',\n '404': '800373150', '405': '800373145', '406': '800372444', '407':\n '800372437', '408': '800372425', '409': '800379488', '410': '800382132',\n '411': '800382127', '412': '800382125', '413': '800386300', '414':\n '800384980', '415': '800384977', '416': '800387613', '417': '800387609',\n '418': '800390598', '419': '800390595', '420': '800390593', '421':\n '800391756', '422': '800393267', '423': '800396025', '424': '800399068',\n '425': '800401344', '426': '800404124', '427': '800408946', '428':\n '800407272', '429': '800407265', '430': '800411526', '431': '800411522',\n '432': '800414380', '433': '800413104', '434': '800413099', '435':\n '800415905', '436': '800415900', '437': '800417356', '438': '800420038',\n '439': '800420034', '440': '800420028', '441': '800422801', '442':\n '800421597', '443': '800421594', '444': '800427313', '445': '800427308',\n '446': '800427302', '447': '800427296', '448': '800428813', '449':\n '800430293', '450': '800430281', '451': '800430273', '452': '800434255',\n '453': '800434253', '454': '800434251', '455': '800434249', '456':\n '800434246', '457': '800431774', '458': '800443507', '459': '800442246',\n '460': '800440771', '461': '800439363', '462': '800439359', '463':\n '800436898', '464': '800434258', '465': '800446256', '466': '800450435',\n '467': '800450429', '468': '800450424', '469': '800452914', '470':\n '800452909', '471': '800452023', '472': '800452016', '473': '800455755',\n '474': '800455748', '475': '800457050', '476': '800458494', '477':\n '800461157', '478': '800459620', '479': '800464361', '480': '800464980',\n '481': '800462270', '482': '800465908', '483': '800465407', '484':\n '800465404', '485': '800467476', '486': '800467755', '487': '800468407',\n '488': '800468843', '489': '800469869', '490': '800469867', '491':\n '800470232', '492': '800470228', '493': '800470224', '494': '800470783',\n '495': '800471280', '496': '800471274', '497': '800471270', '498':\n '800471737', '499': '800472257', '500': '800472252', '501': '800472248',\n '502': '800472239', '503': '800472826', '504': '800473392', '505':\n '800473387', '506': '800473386', '507': '800474131', '508': '800474822',\n '509': '800476516', '510': '800476512', '511': '800477305', '512':\n '800477304', '513': '800477299', '514': '800477851', '515': '800478313',\n '516': '800478309', '517': '800478779', '518': '800479288', '519':\n '800479679', '520': '800480262', '521': '800480257', '522': '800483194',\n '523': '800482720', '524': '800482271', '525': '800481660', '526':\n '800481208', '527': '800480699', '528': '800483203', '529': '800483712',\n '530': '800484088', '531': '800484085', '532': '800484667', '533':\n '800485151', '534': '800485686', '535': '800487288', '536': '800487265',\n '537': '800487264', '538': '800487254', '539': '800487654', '540':\n '800488015', '541': '800488014', '542': '800488638', '543': '800488635',\n '544': '800489081', '545': '800489074', '546': '800489725', '547':\n '800489722', '548': '800490703', '549': '800490702', '550': '800492228',\n '551': '800494213', '552': '800494039', '553': '800494442', '554':\n '800494426', '555': '800495547', '556': '800495446', '557': '800496750',\n '558': '800498164', '559': '800498748', '560': '800499418', '561':\n '800499229', '562': '800500847', '563': '800500844', '564': '800500802',\n '565': '800501840', '566': '800501597', '567': '800502796', '568':\n '800502789', '569': '800503614', '570': '800504092', '571': '800503911',\n '572': '800508001', '573': '800507103', '574': '800506285', '575':\n '800505846', '576': '800505807', '577': '800505069', '578': '800509304',\n '579': '800509218', '580': '800508912', '581': '800509464', '582':\n '800510151', '583': '800511800', '584': '800511318', '585': '800512405',\n '586': '800512403', '587': '800513304', '588': '800513305', '589':\n '800513635', '590': '800513633', '591': '800514762', '592': '800514759',\n '593': '800515655', '594': '800515656', '595': '800516480', '596':\n '800516479', '597': '800516478', '598': '800517736', '599': '800517735',\n '600': '800517733', '601': '800517148', '602': '800517143', '603':\n '800517138', '604': '800519296', '605': '800519292', '606': '800520855',\n '607': '800520857', '608': '800520736', '609': '800521674', '610':\n '800522862', '611': '800523828', '612': '800523825', '613': '800524526',\n '614': '800524868', '615': '800525568', '616': '800525566', '617':\n '800525848', '618': '800525847', '619': '800525845', '620': '800526925',\n '621': '800526923', '622': '800526922', '623': '800528032', '624':\n '800527784', '625': '800527783', '626': '800529243', '627': '800528930',\n '628': '800528927', '629': '800530217', '630': '800530215', '631':\n '800530212', '632': '800531040', '633': '800530845', '634': '800530842',\n '635': '800531892', '636': '800532956', '637': '800532952', '638':\n '800533102', '639': '800534375', '640': '800534368', '641': '800534363',\n '642': '800535420', '643': '800535415', '644': '800535410', '645':\n '800536088', '646': '800536085', '647': '800536084', '648': '800537422',\n '649': '800537419', '650': '800537413', '651': '800565995', '652':\n '800565992', '653': '800563301', '654': '800563298', '655': '800562019',\n '656': '800562018', '657': '800560957', '658': '800560954', '659':\n '800560953', '660': '800560950', '661': '800567960', '662': '800567958',\n '663': '800567957', '664': '800566950', '665': '800566948', '666':\n '800566947', '667': '800568961', '668': '800568959', '669': '800568957',\n '670': '800569778', '671': '800569776', '672': '800569775', '673':\n '800570677', '674': '800570673', '675': '800570647', '676': '800571691',\n '677': '800571690', '678': '800571688', '679': '800573679', '680':\n '800573678', '681': '800573673', '682': '800572880', '683': '800572878',\n '684': '800572876', '685': '800574667', '686': '800574666', '687':\n '800574665', '688': '800575627', '689': '800575624', '690': '800575622',\n '691': '800576864', '692': '800576861', '693': '800576858', '694':\n '800577693', '695': '800578651', '696': '800578648', '697': '800578653',\n '698': '800580339', '699': '800581315', '700': '800582094', '701':\n '800583021', '702': '800590020', '703': '800590019', '704': '800590018',\n '705': '800589231', '706': '800589226', '707': '800588877', '708':\n '800587042', '709': '800587039', '710': '800586085', '711': '800584924',\n '712': '800583934', '713': '800590941', '714': '800590940', '715':\n '800590939', '716': '800592923', '717': '800592921', '718': '800592920',\n '719': '800591918', '720': '800591917', '721': '800591915', '722':\n '800593832', '723': '800593829', '724': '800593824', '725': '800593890',\n '726': '800594956', '727': '800594880', '728': '800594877', '729':\n '800594876', '730': '800595884', '731': '800595883', '732': '800595882',\n '733': '800595879', '734': '800596854', '735': '800597955', '736':\n '800597961', '737': '800597957', '738': '800597954', '739': '800597951',\n '740': '800598913', '741': '800600005', '742': '800600003', '743':\n '800600000', '744': '800600977', '745': '800600975', '746': '800600973',\n '747': '800601974', '748': '800603879', '749': '800603052', '750':\n '800603050', '751': '800604977', '752': '800605959', '753': '800607128',\n '754': '800608295', '755': '800608294', '756': '800608293', '757':\n '800609876', '758': '800610697', '759': '800611768', '760': '800611766',\n '761': '800611764', '762': '800612811', '763': '800612809', '764':\n '800612806', '765': '800615487', '766': '800613824', '767': '800613823',\n '768': '800617427', '769': '800617740', '770': '800618987', '771':\n '800618794', '772': '800620463', '773': '800620507', '774': '800621873',\n '775': '800621866', '776': '800621485', '777': '800623063', '778':\n '800622785', '779': '800624082', '780': '800624606', '781': '800624605',\n '782': '800624602', '783': '800626006', '784': '800626004', '785':\n '800625998', '786': '800625995', '787': '800625959', '788': '800625684',\n '789': '800627159', '790': '800627541', '791': '800628537', '792':\n '800628472', '793': '800628440', '794': '800628412', '795': '800628391',\n '796': '800629230', '797': '800629175', '798': '800630245', '799':\n '800630236', '800': '800631787', '801': '800631425', '802': '800631385',\n '803': '800631379', '804': '800631339', '805': '800631299', '806':\n '800631198', '807': '800630886', '808': '800633920', '809': '800633720',\n '810': '800633520', '811': '800634419', '812': '800635301', '813':\n '800635068', '814': '800635957', '815': '800638994', '816': '800638105',\n '817': '800637068', '818': '800636754', '819': '800636749', '820':\n '800636075', '821': '800639448', '822': '800639234', '823': '800639026',\n '824': '800640408', '825': '800640396', '826': '800640985', '827':\n '800640977', '828': '800645321', '829': '800644531', '830': '800644235',\n '831': '800643606', '832': '800642400', '833': '800641879', '834':\n '800645756', '835': '800647017', '836': '800648350', '837': '800648289',\n '838': '800648124', '839': '800647488', '840': '800649911', '841':\n '800649906', '842': '800649535', '843': '800649521', '844': '800649507',\n '845': '800649438', '846': '800649411', '847': '800650580', '848':\n '800652017', '849': '800652004', '850': '800651999', '851': '800651955',\n '852': '800651790', '853': '800651264', '854': '800651159', '855':\n '800652276', '856': '800652260', '857': '800654483', '858': '800654117',\n '859': '800654927', '860': '800656751', '861': '800656720', '862':\n '800656504', '863': '800656476', '864': '800655926', '865': '800658883',\n '866': '800659871', '867': '800659855', '868': '800657502', '869':\n '800662419', '870': '800663417', '871': '800661565', '872': '800664542',\n '873': '800665790', '874': '800667640', '875': '800668511', '876':\n '800668354', '877': '800668932', '878': '800668884', '879': '800668870',\n '880': '800668846', '881': '800670519', '882': '800670755', '883':\n '800670804', '884': '800670005', '885': '800669956', '886': '800671522',\n '887': '800670997', '888': '800676274', '889': '800674751', '890':\n '800674396', '891': '800674387', '892': '800674369', '893': '800674171',\n '894': '800674165', '895': '800673904', '896': '800673894', '897':\n '800673042', '898': '800672682', '899': '800673037', '900': '800674363',\n '901': '800671334', '902': '800676404', '903': '800677203', '904':\n '800678281', '905': '800677753', '906': '800678579', '907': '800678543',\n '908': '800682417', '909': '800680556', '910': '800680572', '911':\n '800681753', '912': '800683728', '913': '800683445', '914': '800684755',\n '915': '800685559', '916': '800685994', '917': '800686991', '918':\n '800688325', '919': '800688988', '920': '800688986', '921': '800688811',\n '922': '800688784', '923': '800690794', '924': '800690777', '925':\n '800690766', '926': '800691744', '927': '800691714', '928': '800691608',\n '929': '800691675', '930': '800692072', '931': '800692888', '932':\n '800692853', '933': '800694793', '934': '800695410', '935': '800696421',\n '936': '800696417', '937': '800696404', '938': '800696380', '939':\n '800695901', '940': '800696527', '941': '800696521', '942': '800696516',\n '943': '800697754', '944': '800698640', '945': '800700044', '946':\n '800700030', '947': '800700001', '948': '800699969', '949': '800700477',\n '950': '800700332', '951': '800701388', '952': '800701378', '953':\n '800702260', '954': '800702167', '955': '800702170', '956': '800703184',\n '957': '800703189', '958': '800704417', '959': '800704334', '960':\n '800704331', '961': '800705315', '962': '800705310', '963': '800706319',\n '964': '800706317', '965': '800707543', '966': '800707540', '967':\n '800707378', '968': '800707376', '969': '800707372', '970': '800709165',\n '971': '800709918', '972': '800709909', '973': '800709913', '974':\n '800709590', '975': '800709592', '976': '800711385', '977': '800711436',\n '978': '800711448', '979': '800712704', '980': '800712684', '981':\n '800712697', '982': '800713805', '983': '800713786', '984': '800715143',\n '985': '800715140', '986': '800717742', '987': '800717725', '988':\n '800717083', '989': '800719807', '990': '800719797', '991': '800721331',\n '992': '800721317', '993': '800722269', '994': '800722253', '995':\n '800722190', '996': '800723313', '997': '800723082'}\nREDIRECT_MAP_CATEGORIES = {'27': '438046136', '28': '438046133', '29':\n '438046135', '30': '438046134', '31': '438046128', '32': '438046127',\n '33': '438046130', '34': '438046131', '35': '438046132', '36': '438046129'}\n", "step-3": "REDIRECT_MAP = {\n '90':'19904201',\n '91':'19903329',\n '92':'19899125',\n '93':'19901043',\n '94':'19903192',\n '95':'19899788',\n '97':'19904423',\n '98':'19906163',\n '99':'19905540',\n '100':'19907871',\n '101':'19908147',\n '102':'19910103',\n '103':'19909980',\n '104':'19911813',\n '105':'19911767',\n '106':'19913625',\n '107':'19913832',\n '108':'19915603',\n '109':'19915707',\n '110':'19915705',\n '111':'19915558',\n '112':'19917330',\n '113':'19917085',\n '114':'19918316',\n '115':'19919617',\n '116':'19918555',\n '117':'19919779',\n '118':'19920594',\n '119':'19920805',\n '120':'19921503',\n '121':'19923032',\n '122':'19922349',\n '123':'19923894',\n '124':'19924058',\n '125':'19924651',\n '126':'19929744',\n '127':'19929743',\n '128':'19929742',\n '129':'19929184',\n '130':'19929183',\n '131':'19928163',\n '132':'19927463',\n '133':'19927462',\n '134':'19927461',\n '135':'19926742',\n '136':'19926741',\n '137':'19926738',\n '138':'19930143',\n '139':'19930827',\n '140':'19931617',\n '141':'19931616',\n '142':'19932324',\n '143':'19932321',\n '144':'19932320',\n '145':'19932845',\n '146':'19932843',\n '147':'19932842',\n '148':'19932839',\n '149':'19933621',\n '150':'19933618',\n '151':'19934526',\n '152':'19934525',\n '153':'19934524',\n '154':'19935167',\n '155':'19935165',\n '156':'19936598',\n '157':'19936596',\n '158':'19936594',\n '160':'19937949',\n '161':'19937662',\n '162':'19937662',\n '163':'19937662',\n '164':'19937662',\n '165':'19937662',\n '166':'19940346',\n '167':'19939390',\n '168':'19938892',\n '169':'19938886',\n '170':'19938874',\n '171':'19938181',\n '172':'19938179',\n '173':'19938177',\n '174':'19937662',\n '175':'19937662',\n '176':'800073144',\n '177':'800073141',\n '178':'800070989',\n '179':'800070987',\n '180':'800070985',\n '181':'800068840',\n '182':'800068838',\n '183':'800068837',\n '184':'800068835',\n '185':'800073405',\n '186':'800075467',\n '187':'800075466',\n '188':'800077797',\n '189':'800077792',\n '190':'800077788',\n '191':'800080302',\n '192':'800080300',\n '193':'800080299',\n '194':'800080297',\n '195':'800080295',\n '196':'800080294',\n '197':'800082560',\n '198':'800082559',\n '199':'800082558',\n '200':'800085053',\n '201':'800085057',\n '202':'800085055',\n '203':'800087660',\n '204':'800087637',\n '205':'800087636',\n '206':'800090260',\n '207':'800090259',\n '208':'800090256',\n '209':'800090252',\n '210':'800090248',\n '211':'800095783',\n '212':'800093475',\n '213':'800093472',\n '214':'800093469',\n '215':'800093465',\n '216':'800097835',\n '217':'800097830',\n '218':'800097828',\n '219':'800102815',\n '220':'800100696',\n '221':'800107510',\n '222':'800105566',\n '223':'800105187',\n '224':'800105182',\n '225':'800105176',\n '226':'800105171',\n '227':'800110082',\n '228':'800110080',\n '229':'800110077',\n '230':'800107893',\n '231':'800112573',\n '232':'800112572',\n '233':'800112570',\n '234':'800115083',\n '235':'800115080',\n '236':'800117652',\n '237':'800136223',\n '238':'800135715',\n '239':'800135712',\n '240':'800127734',\n '241':'800125056',\n '242':'800125055',\n '243':'800125054',\n '244':'800122499',\n '245':'800122497',\n '246':'800120063',\n '247':'800120060',\n '248':'800118016',\n '249':'800118015',\n '250':'800138744',\n '251':'800138741',\n '252':'800138440',\n '253':'800156510',\n '254':'800156507',\n '255':'800159343',\n '256':'800200950',\n '257':'800200946',\n '258':'800180350',\n '259':'800180348',\n '260':'800162155',\n '261':'800162153',\n '262':'800159803',\n '263':'800205850',\n '264':'800205839',\n '265':'800210303',\n '266':'800210302',\n '267':'800212467',\n '268':'800212465',\n '269':'800212462',\n '270':'800215849',\n '271':'800218413',\n '272':'800220590',\n '273':'800220585',\n '274':'800220581',\n '275':'800220568',\n '276':'800223836',\n '277':'800223835',\n '278':'800226881',\n '279':'800226876',\n '280':'800226875',\n '281':'800229066',\n '282':'800229064',\n '283':'800232046',\n '284':'800232043',\n '285':'800234330',\n '286':'800234329',\n '287':'800234328',\n '288':'800239516',\n '289':'800236806',\n '290':'800242231',\n '291':'800242196',\n '292':'800242177',\n '293':'800245005',\n '294':'800247477',\n '295':'800247307',\n '296':'800247092',\n '297':'800250315',\n '298':'800250206',\n '299':'800250198',\n '300':'800252661',\n '301':'800252745',\n '302':'800252731',\n '303':'800255314',\n '304':'800255226',\n '305':'800261560',\n '306':'800264399',\n '307':'800264337',\n '308':'800262863',\n '309':'800267317',\n '310':'800268635',\n '311':'800270225',\n '312':'800272621',\n '313':'800272861',\n '314':'800275290',\n '315':'800275287',\n '316':'800275259',\n '317':'800277905',\n '318':'800277897',\n '319':'800277966',\n '320':'800280886',\n '321':'800280734',\n '322':'800280721',\n '323':'800283469',\n '324':'800283455',\n '325':'800291555',\n '326':'800291531',\n '327':'800288739',\n '328':'800286042',\n '329':'800286032',\n '330':'800294431',\n '331':'800294423',\n '332':'800294394',\n '333':'800297383',\n '334':'800299835',\n '335':'800302625',\n '336':'800305630',\n '337':'800305626',\n '338':'800308225',\n '339':'800307935',\n '340':'800308160',\n '341':'800308242',\n '342':'800310811',\n '343':'800310657',\n '344':'800310651',\n '345':'800312843',\n '346':'800313657',\n '347':'800313593',\n '348':'800313385',\n '349':'800315870',\n '350':'800315874',\n '351':'800315004',\n '352':'800315980',\n '353':'800317852',\n '354':'800317851',\n '355':'800317843',\n '356':'800317841',\n '357':'800320232',\n '358':'800322836',\n '359':'800322833',\n '360':'800325648',\n '361':'800325641',\n '362':'800328374',\n '363':'800328368',\n '364':'800330891',\n '365':'800330882',\n '366':'800330878',\n '367':'800336505',\n '368':'800336491',\n '369':'800338571',\n '370':'800341852',\n '371':'800339471',\n '372':'800344570',\n '373':'800344561',\n '374':'800344557',\n '375':'800347295',\n '376':'800348755',\n '377':'800350263',\n '378':'800350259',\n '379':'800353149',\n '380':'800351527',\n '381':'800355911',\n '382':'800355907',\n '383':'800358602',\n '384':'800358597',\n '385':'800357146',\n '386':'800360127',\n '387':'800364368',\n '388':'800364364',\n '389':'800364360',\n '390':'800369266',\n '391':'800367438',\n '392':'800367435',\n '393':'800365869',\n '394':'800376494',\n '395':'800376495',\n '396':'800376499',\n '397':'800376508',\n '398':'800376564',\n '399':'800376527',\n '400':'800376534',\n '401':'800376542',\n '402':'800376553',\n '403':'800376547',\n '404':'800373150',\n '405':'800373145',\n '406':'800372444',\n '407':'800372437',\n '408':'800372425',\n '409':'800379488',\n '410':'800382132',\n '411':'800382127',\n '412':'800382125',\n '413':'800386300',\n '414':'800384980',\n '415':'800384977',\n '416':'800387613',\n '417':'800387609',\n '418':'800390598',\n '419':'800390595',\n '420':'800390593',\n '421':'800391756',\n '422':'800393267',\n '423':'800396025',\n '424':'800399068',\n '425':'800401344',\n '426':'800404124',\n '427':'800408946',\n '428':'800407272',\n '429':'800407265',\n '430':'800411526',\n '431':'800411522',\n '432':'800414380',\n '433':'800413104',\n '434':'800413099',\n '435':'800415905',\n '436':'800415900',\n '437':'800417356',\n '438':'800420038',\n '439':'800420034',\n '440':'800420028',\n '441':'800422801',\n '442':'800421597',\n '443':'800421594',\n '444':'800427313',\n '445':'800427308',\n '446':'800427302',\n '447':'800427296',\n '448':'800428813',\n '449':'800430293',\n '450':'800430281',\n '451':'800430273',\n '452':'800434255',\n '453':'800434253',\n '454':'800434251',\n '455':'800434249',\n '456':'800434246',\n '457':'800431774',\n '458':'800443507',\n '459':'800442246',\n '460':'800440771',\n '461':'800439363',\n '462':'800439359',\n '463':'800436898',\n '464':'800434258',\n '465':'800446256',\n '466':'800450435',\n '467':'800450429',\n '468':'800450424',\n '469':'800452914',\n '470':'800452909',\n '471':'800452023',\n '472':'800452016',\n '473':'800455755',\n '474':'800455748',\n '475':'800457050',\n '476':'800458494',\n '477':'800461157',\n '478':'800459620',\n '479':'800464361',\n '480':'800464980',\n '481':'800462270',\n '482':'800465908',\n '483':'800465407',\n '484':'800465404',\n '485':'800467476',\n '486':'800467755',\n '487':'800468407',\n '488':'800468843',\n '489':'800469869',\n '490':'800469867',\n '491':'800470232',\n '492':'800470228',\n '493':'800470224',\n '494':'800470783',\n '495':'800471280',\n '496':'800471274',\n '497':'800471270',\n '498':'800471737',\n '499':'800472257',\n '500':'800472252',\n '501':'800472248',\n '502':'800472239',\n '503':'800472826',\n '504':'800473392',\n '505':'800473387',\n '506':'800473386',\n '507':'800474131',\n '508':'800474822',\n '509':'800476516',\n '510':'800476512',\n '511':'800477305',\n '512':'800477304',\n '513':'800477299',\n '514':'800477851',\n '515':'800478313',\n '516':'800478309',\n '517':'800478779',\n '518':'800479288',\n '519':'800479679',\n '520':'800480262',\n '521':'800480257',\n '522':'800483194',\n '523':'800482720',\n '524':'800482271',\n '525':'800481660',\n '526':'800481208',\n '527':'800480699',\n '528':'800483203',\n '529':'800483712',\n '530':'800484088',\n '531':'800484085',\n '532':'800484667',\n '533':'800485151',\n '534':'800485686',\n '535':'800487288',\n '536':'800487265',\n '537':'800487264',\n '538':'800487254',\n '539':'800487654',\n '540':'800488015',\n '541':'800488014',\n '542':'800488638',\n '543':'800488635',\n '544':'800489081',\n '545':'800489074',\n '546':'800489725',\n '547':'800489722',\n '548':'800490703',\n '549':'800490702',\n '550':'800492228',\n '551':'800494213',\n '552':'800494039',\n '553':'800494442',\n '554':'800494426',\n '555':'800495547',\n '556':'800495446',\n '557':'800496750',\n '558':'800498164',\n '559':'800498748',\n '560':'800499418',\n '561':'800499229',\n '562':'800500847',\n '563':'800500844',\n '564':'800500802',\n '565':'800501840',\n '566':'800501597',\n '567':'800502796',\n '568':'800502789',\n '569':'800503614',\n '570':'800504092',\n '571':'800503911',\n '572':'800508001',\n '573':'800507103',\n '574':'800506285',\n '575':'800505846',\n '576':'800505807',\n '577':'800505069',\n '578':'800509304',\n '579':'800509218',\n '580':'800508912',\n '581':'800509464',\n '582':'800510151',\n '583':'800511800',\n '584':'800511318',\n '585':'800512405',\n '586':'800512403',\n '587':'800513304',\n '588':'800513305',\n '589':'800513635',\n '590':'800513633',\n '591':'800514762',\n '592':'800514759',\n '593':'800515655',\n '594':'800515656',\n '595':'800516480',\n '596':'800516479',\n '597':'800516478',\n '598':'800517736',\n '599':'800517735',\n '600':'800517733',\n '601':'800517148',\n '602':'800517143',\n '603':'800517138',\n '604':'800519296',\n '605':'800519292',\n '606':'800520855',\n '607':'800520857',\n '608':'800520736',\n '609':'800521674',\n '610':'800522862',\n '611':'800523828',\n '612':'800523825',\n '613':'800524526',\n '614':'800524868',\n '615':'800525568',\n '616':'800525566',\n '617':'800525848',\n '618':'800525847',\n '619':'800525845',\n '620':'800526925',\n '621':'800526923',\n '622':'800526922',\n '623':'800528032',\n '624':'800527784',\n '625':'800527783',\n '626':'800529243',\n '627':'800528930',\n '628':'800528927',\n '629':'800530217',\n '630':'800530215',\n '631':'800530212',\n '632':'800531040',\n '633':'800530845',\n '634':'800530842',\n '635':'800531892',\n '636':'800532956',\n '637':'800532952',\n '638':'800533102',\n '639':'800534375',\n '640':'800534368',\n '641':'800534363',\n '642':'800535420',\n '643':'800535415',\n '644':'800535410',\n '645':'800536088',\n '646':'800536085',\n '647':'800536084',\n '648':'800537422',\n '649':'800537419',\n '650':'800537413',\n '651':'800565995',\n '652':'800565992',\n '653':'800563301',\n '654':'800563298',\n '655':'800562019',\n '656':'800562018',\n '657':'800560957',\n '658':'800560954',\n '659':'800560953',\n '660':'800560950',\n '661':'800567960',\n '662':'800567958',\n '663':'800567957',\n '664':'800566950',\n '665':'800566948',\n '666':'800566947',\n '667':'800568961',\n '668':'800568959',\n '669':'800568957',\n '670':'800569778',\n '671':'800569776',\n '672':'800569775',\n '673':'800570677',\n '674':'800570673',\n '675':'800570647',\n '676':'800571691',\n '677':'800571690',\n '678':'800571688',\n '679':'800573679',\n '680':'800573678',\n '681':'800573673',\n '682':'800572880',\n '683':'800572878',\n '684':'800572876',\n '685':'800574667',\n '686':'800574666',\n '687':'800574665',\n '688':'800575627',\n '689':'800575624',\n '690':'800575622',\n '691':'800576864',\n '692':'800576861',\n '693':'800576858',\n '694':'800577693',\n '695':'800578651',\n '696':'800578648',\n '697':'800578653',\n '698':'800580339',\n '699':'800581315',\n '700':'800582094',\n '701':'800583021',\n '702':'800590020',\n '703':'800590019',\n '704':'800590018',\n '705':'800589231',\n '706':'800589226',\n '707':'800588877',\n '708':'800587042',\n '709':'800587039',\n '710':'800586085',\n '711':'800584924',\n '712':'800583934',\n '713':'800590941',\n '714':'800590940',\n '715':'800590939',\n '716':'800592923',\n '717':'800592921',\n '718':'800592920',\n '719':'800591918',\n '720':'800591917',\n '721':'800591915',\n '722':'800593832',\n '723':'800593829',\n '724':'800593824',\n '725':'800593890',\n '726':'800594956',\n '727':'800594880',\n '728':'800594877',\n '729':'800594876',\n '730':'800595884',\n '731':'800595883',\n '732':'800595882',\n '733':'800595879',\n '734':'800596854',\n '735':'800597955',\n '736':'800597961',\n '737':'800597957',\n '738':'800597954',\n '739':'800597951',\n '740':'800598913',\n '741':'800600005',\n '742':'800600003',\n '743':'800600000',\n '744':'800600977',\n '745':'800600975',\n '746':'800600973',\n '747':'800601974',\n '748':'800603879',\n '749':'800603052',\n '750':'800603050',\n '751':'800604977',\n '752':'800605959',\n '753':'800607128',\n '754':'800608295',\n '755':'800608294',\n '756':'800608293',\n '757':'800609876',\n '758':'800610697',\n '759':'800611768',\n '760':'800611766',\n '761':'800611764',\n '762':'800612811',\n '763':'800612809',\n '764':'800612806',\n '765':'800615487',\n '766':'800613824',\n '767':'800613823',\n '768':'800617427',\n '769':'800617740',\n '770':'800618987',\n '771':'800618794',\n '772':'800620463',\n '773':'800620507',\n '774':'800621873',\n '775':'800621866',\n '776':'800621485',\n '777':'800623063',\n '778':'800622785',\n '779':'800624082',\n '780':'800624606',\n '781':'800624605',\n '782':'800624602',\n '783':'800626006',\n '784':'800626004',\n '785':'800625998',\n '786':'800625995',\n '787':'800625959',\n '788':'800625684',\n '789':'800627159',\n '790':'800627541',\n '791':'800628537',\n '792':'800628472',\n '793':'800628440',\n '794':'800628412',\n '795':'800628391',\n '796':'800629230',\n '797':'800629175',\n '798':'800630245',\n '799':'800630236',\n '800':'800631787',\n '801':'800631425',\n '802':'800631385',\n '803':'800631379',\n '804':'800631339',\n '805':'800631299',\n '806':'800631198',\n '807':'800630886',\n '808':'800633920',\n '809':'800633720',\n '810':'800633520',\n '811':'800634419',\n '812':'800635301',\n '813':'800635068',\n '814':'800635957',\n '815':'800638994',\n '816':'800638105',\n '817':'800637068',\n '818':'800636754',\n '819':'800636749',\n '820':'800636075',\n '821':'800639448',\n '822':'800639234',\n '823':'800639026',\n '824':'800640408',\n '825':'800640396',\n '826':'800640985',\n '827':'800640977',\n '828':'800645321',\n '829':'800644531',\n '830':'800644235',\n '831':'800643606',\n '832':'800642400',\n '833':'800641879',\n '834':'800645756',\n '835':'800647017',\n '836':'800648350',\n '837':'800648289',\n '838':'800648124',\n '839':'800647488',\n '840':'800649911',\n '841':'800649906',\n '842':'800649535',\n '843':'800649521',\n '844':'800649507',\n '845':'800649438',\n '846':'800649411',\n '847':'800650580',\n '848':'800652017',\n '849':'800652004',\n '850':'800651999',\n '851':'800651955',\n '852':'800651790',\n '853':'800651264',\n '854':'800651159',\n '855':'800652276',\n '856':'800652260',\n '857':'800654483',\n '858':'800654117',\n '859':'800654927',\n '860':'800656751',\n '861':'800656720',\n '862':'800656504',\n '863':'800656476',\n '864':'800655926',\n '865':'800658883',\n '866':'800659871',\n '867':'800659855',\n '868':'800657502',\n '869':'800662419',\n '870':'800663417',\n '871':'800661565',\n '872':'800664542',\n '873':'800665790',\n '874':'800667640',\n '875':'800668511',\n '876':'800668354',\n '877':'800668932',\n '878':'800668884',\n '879':'800668870',\n '880':'800668846',\n '881':'800670519',\n '882':'800670755',\n '883':'800670804',\n '884':'800670005',\n '885':'800669956',\n '886':'800671522',\n '887':'800670997',\n '888':'800676274',\n '889':'800674751',\n '890':'800674396',\n '891':'800674387',\n '892':'800674369',\n '893':'800674171',\n '894':'800674165',\n '895':'800673904',\n '896':'800673894',\n '897':'800673042',\n '898':'800672682',\n '899':'800673037',\n '900':'800674363',\n '901':'800671334',\n '902':'800676404',\n '903':'800677203',\n '904':'800678281',\n '905':'800677753',\n '906':'800678579',\n '907':'800678543',\n '908':'800682417',\n '909':'800680556',\n '910':'800680572',\n '911':'800681753',\n '912':'800683728',\n '913':'800683445',\n '914':'800684755',\n '915':'800685559',\n '916':'800685994',\n '917':'800686991',\n '918':'800688325',\n '919':'800688988',\n '920':'800688986',\n '921':'800688811',\n '922':'800688784',\n '923':'800690794',\n '924':'800690777',\n '925':'800690766',\n '926':'800691744',\n '927':'800691714',\n '928':'800691608',\n '929':'800691675',\n '930':'800692072',\n '931':'800692888',\n '932':'800692853',\n '933':'800694793',\n '934':'800695410',\n '935':'800696421',\n '936':'800696417',\n '937':'800696404',\n '938':'800696380',\n '939':'800695901',\n '940':'800696527',\n '941':'800696521',\n '942':'800696516',\n '943':'800697754',\n '944':'800698640',\n '945':'800700044',\n '946':'800700030',\n '947':'800700001',\n '948':'800699969',\n '949':'800700477',\n '950':'800700332',\n '951':'800701388',\n '952':'800701378',\n '953':'800702260',\n '954':'800702167',\n '955':'800702170',\n '956':'800703184',\n '957':'800703189',\n '958':'800704417',\n '959':'800704334',\n '960':'800704331',\n '961':'800705315',\n '962':'800705310',\n '963':'800706319',\n '964':'800706317',\n '965':'800707543',\n '966':'800707540',\n '967':'800707378',\n '968':'800707376',\n '969':'800707372',\n '970':'800709165',\n '971':'800709918',\n '972':'800709909',\n '973':'800709913',\n '974':'800709590',\n '975':'800709592',\n '976':'800711385',\n '977':'800711436',\n '978':'800711448',\n '979':'800712704',\n '980':'800712684',\n '981':'800712697',\n '982':'800713805',\n '983':'800713786',\n '984':'800715143',\n '985':'800715140',\n '986':'800717742',\n '987':'800717725',\n '988':'800717083',\n '989':'800719807',\n '990':'800719797',\n '991':'800721331',\n '992':'800721317',\n '993':'800722269',\n '994':'800722253',\n '995':'800722190',\n '996':'800723313',\n '997':'800723082',\n}\n\nREDIRECT_MAP_CATEGORIES = {\n '27':'438046136',\n '28':'438046133',\n '29':'438046135',\n '30':'438046134',\n '31':'438046128',\n '32':'438046127',\n '33':'438046130',\n '34':'438046131',\n '35':'438046132',\n '36':'438046129',\n}\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
from extras.plugins import PluginTemplateExtension from .models import BGPSession from .tables import BGPSessionTable class DeviceBGPSession(PluginTemplateExtension): model = 'dcim.device' def left_page(self): if self.context['config'].get('device_ext_page') == 'left': return self.x_page() return '' def right_page(self): if self.context['config'].get('device_ext_page') == 'right': return self.x_page() return '' def full_width_page(self): if self.context['config'].get('device_ext_page') == 'full_width': return self.x_page() return '' def x_page(self): obj = self.context['object'] sess = BGPSession.objects.filter(device=obj) sess_table = BGPSessionTable(sess) return self.render('netbox_bgp/device_extend.html', extra_context={ 'related_session_table': sess_table}) template_extensions = [DeviceBGPSession]
normal
{ "blob_id": "be566041402dc1705aa9d644edc44de8792fbb3c", "index": 4850, "step-1": "<mask token>\n\n\nclass DeviceBGPSession(PluginTemplateExtension):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass DeviceBGPSession(PluginTemplateExtension):\n <mask token>\n\n def left_page(self):\n if self.context['config'].get('device_ext_page') == 'left':\n return self.x_page()\n return ''\n\n def right_page(self):\n if self.context['config'].get('device_ext_page') == 'right':\n return self.x_page()\n return ''\n <mask token>\n\n def x_page(self):\n obj = self.context['object']\n sess = BGPSession.objects.filter(device=obj)\n sess_table = BGPSessionTable(sess)\n return self.render('netbox_bgp/device_extend.html', extra_context={\n 'related_session_table': sess_table})\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass DeviceBGPSession(PluginTemplateExtension):\n model = 'dcim.device'\n\n def left_page(self):\n if self.context['config'].get('device_ext_page') == 'left':\n return self.x_page()\n return ''\n\n def right_page(self):\n if self.context['config'].get('device_ext_page') == 'right':\n return self.x_page()\n return ''\n\n def full_width_page(self):\n if self.context['config'].get('device_ext_page') == 'full_width':\n return self.x_page()\n return ''\n\n def x_page(self):\n obj = self.context['object']\n sess = BGPSession.objects.filter(device=obj)\n sess_table = BGPSessionTable(sess)\n return self.render('netbox_bgp/device_extend.html', extra_context={\n 'related_session_table': sess_table})\n\n\ntemplate_extensions = [DeviceBGPSession]\n", "step-4": "from extras.plugins import PluginTemplateExtension\nfrom .models import BGPSession\nfrom .tables import BGPSessionTable\n\n\nclass DeviceBGPSession(PluginTemplateExtension):\n model = 'dcim.device'\n\n def left_page(self):\n if self.context['config'].get('device_ext_page') == 'left':\n return self.x_page()\n return ''\n\n def right_page(self):\n if self.context['config'].get('device_ext_page') == 'right':\n return self.x_page()\n return ''\n\n def full_width_page(self):\n if self.context['config'].get('device_ext_page') == 'full_width':\n return self.x_page()\n return ''\n\n def x_page(self):\n obj = self.context['object']\n sess = BGPSession.objects.filter(device=obj)\n sess_table = BGPSessionTable(sess)\n return self.render('netbox_bgp/device_extend.html', extra_context={\n 'related_session_table': sess_table})\n\n\ntemplate_extensions = [DeviceBGPSession]\n", "step-5": null, "step-ids": [ 1, 4, 7, 8 ] }
[ 1, 4, 7, 8 ]
def fib(limit): a, b = 0, 1 yield a yield b while b < limit: a, b = b, a + b yield b print sum(x for x in fib(4000000) if not x % 2) # 4613732
normal
{ "blob_id": "1c7635917e398c30e4a232f76b2c02a51e165a63", "index": 4147, "step-1": "def fib(limit):\n a, b = 0, 1\n yield a\n yield b\n while b < limit:\n a, b = b, a + b\n yield b\n\n\nprint sum(x for x in fib(4000000) if not x % 2) # 4613732\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
import xadmin from xadmin import views from .models import EmailVerifyRecord, Banner class BaseMyAdminView(object): ''' enable_themes 启动更改主题 use_bootswatch 启用网上主题 ''' enable_themes = True use_bootswatch = True class GlobalSettings(object): ''' site_title 左上角名称 site_footer 底部名称 menu_style 更改左边样式 ''' site_title = "学习网后台管理系统" site_footer = "学习网" menu_style = "accordion" class EmailVerifyRecordAdmin(object): list_display = ['email', 'code', 'send_type', 'send_time'] search_fields = ['email', 'code', 'send_type'] list_filter = ['email', 'code', 'send_type', 'send_time'] class BannerAdmin(object): list_disply = ['title', 'image', 'url', 'index', 'add_time'] search_fields = ['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index', 'add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner, BannerAdmin) xadmin.site.register(views.BaseAdminView, BaseMyAdminView) xadmin.site.register(views.CommAdminView, GlobalSettings)
normal
{ "blob_id": "d7b830890400203ee45c9ec59611c0b20ab6bfc7", "index": 8496, "step-1": "<mask token>\n\n\nclass BaseMyAdminView(object):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)\n", "step-4": "import xadmin\nfrom xadmin import views\nfrom .models import EmailVerifyRecord, Banner\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)\n", "step-5": "import xadmin\nfrom xadmin import views\n\nfrom .models import EmailVerifyRecord, Banner\n\n\nclass BaseMyAdminView(object):\n '''\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n '''\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n '''\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n '''\n site_title = \"学习网后台管理系统\"\n site_footer = \"学习网\"\n menu_style = \"accordion\"\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)", "step-ids": [ 8, 10, 11, 12, 13 ] }
[ 8, 10, 11, 12, 13 ]
from random import choice, random, randrange from math import fsum import os import numpy as np def mat17(N, ATOM_TYPES, ndenmax=0.04302, ndenmin=0.0000013905, xmax=51.2, xmin=25.6, ymax=51.2, ymin=25.6, zmax=51.2, zmin=25.6, epmax=513.264, epmin=1.2580, sigmax=6.549291, sigmin=1.052342, qmax=0.0, qmin=0.0): #epmax DEFINED WRT TO X-Y-Z LIMITS? #max number density based on that of pure Iron #max unit cell dimensions based on PCN-777 cages size #max LJ parameters (for now using 1.5x highest values in GenericMOFs) #max charge... UFF? #ATOM_TYPES = 4 if type(N) != int: print 'N must be an integer.' Ntag = str(N) ntag = str(ndenmax) xtag = str(xmax) ytag = str(xmax) ztag = str(xmax) eptag = str(xmax) sigtag = str(xmax) qtag = str(xmax) top_path = ('materials' + '_' + Ntag + '.' + ntag + '_' + xtag + '.' + ytag + '.' + ztag + '_' + eptag + '.' + sigtag + '_' + qtag) if not os.path.exists(top_path): os.mkdir(top_path) # def drange(start, stop, step): # r = start # while r < stop: # yield r # r+= step # nden0 = drange(1, ndenmax*10000, ndenp*10000) # ndendim = [nden for nden in nden0] # x0 = drange(0, xmax + xp, xp) # xdim = [x for x in x0] # y0 = drange(0, ymax + yp, yp) # ydim = [y for y in y0] # z0 = drange(0, zmax + zp, zp) # zdim = [z for z in z0] # ep0 = drange(0, epmax + epp, epp) # epdim = [ep for ep in ep0] # sig0 = drange(0, sigmax + sigp, sigp) # sigdim = [sig for sig in sig0] #open mat_stats.txt, to track material data mat_stats = open(os.path.abspath(top_path)+ '/mat_stats.txt', 'w') mat_stat_heading = ('\nBOUNDARIES\nNumber of particles: ' + Ntag + '\nnumber density: ' + ntag + '\nx-coordinate: ' + xtag + '\ny-coordinate: ' + ytag + '\nz-coordinate: ' + ztag + '\nEpsilon: ' + eptag + '\nSigma: ' + sigtag + '\nCharge: ' + qtag + '\n\n' + '#name number density xdim ydim '+ 'zdim total particles net charge\n') mat_stats.write(mat_stat_heading) #MAT-XXX loop... for i in range(N + 1): mat_name = 'MAT-' + str(i) #make MAT-XXX directory os.mkdir(top_path+'/'+mat_name) #open .cif file cif_file = open(os.path.abspath(top_path) + '/'+mat_name + '/' + mat_name+'.cif', 'w') #open force_field_mixing_rules.def mixing_rules = open(os.path.abspath(top_path) + '/'+mat_name + '/force_field_mixing_rules.def', 'w') #open pseudo_atoms.def pseudo_atoms = open(os.path.abspath(top_path) + '/'+mat_name + '/pseudo_atoms.def', 'w') #open force_field.def force_field = open(os.path.abspath(top_path) + '/'+mat_name + '/force_field.def', 'w') #nden_ = choice(ndendim)/10000. #xdim_ = choice(xdim) #ydim_ = choice(ydim) #zdim_ = choice(zdim) #nden_ = randrange(0.0001, ndenmax, 1) #xdim_ = randrange(15., xmax, 0.1) #ydim_ = randrange(15., ymax, 0.1) #zdim_ = randrange(15., zmax, 0.1) #N_ = xdim_ * ydim_ * zdim_ * nden_ #n_ = int(N_) nden_ = round(random() * (ndenmax - ndenmin) + ndenmin, 6) xdim_ = round(random() * (xmax - xmin) + xmin, 4) ydim_ = round(random() * (ymax - ymin) + ymin, 4) zdim_ = round(random() * (zmax - zmin) + zmin, 4) N_ = xdim_ * ydim_ * zdim_ * nden_ n_ = int(N_) cif_heading = ('material' + str(i) + '\n\nloop_\n' + '_symmetry_equiv_pos_as_xyz\n' + ' x,y,z\n' + '_cell_length_a ' + str(xdim_) + '\n_cell_length_b ' + str(ydim_) + '\n_cell_length_c ' + str(zdim_) + '\n_cell_angle_alpha 90.0000\n' + '_cell_angle_beta 90.0000\n' + '_cell_angle_gamma 90.0000\n' + 'loop_\n' + '_atom_site_label\n' + '_atom_site_type_symbol\n' + '_atom_site_fract_x\n' + '_atom_site_fract_y\n' + '_atom_site_fract_z\n' + '_atom_site_charge\n') cif_file.write(cif_heading) # mixing_heading = ('# general rule for shifted vs truncated\nshifted\n' + # '# general rule for tailcorrections\nno\n' + # '# number of defined interactions\n' + str(108) + #check these + XXX values # '\n# type interaction\n') mixing_heading = ('# general rule for shifted vs truncated\n' + 'shifted\n' + '# general rule tailcorrections\n' + 'no\n' + '# number of defined interactions\n' + str(ATOM_TYPES + 8) + '\n' + '# type interaction, parameters. IMPORTANT: define shortest matches first, so that more specific ones overwrites these\n') mixing_rules.write(mixing_heading) pseudo_heading = ('#number of pseudo atoms\n' + str(ATOM_TYPES + 8) + '\n#type print as chem oxidation' + ' mass charge polarization ' + 'B-factor radii connectivity anisotropic' + ' anisotrop-type tinker-type\n') pseudo_atoms.write(pseudo_heading) ##make charges #q = [] #for k in range(n_ + 1): # q.append(0) #for l in range(5*(n_ + 1)): # m = choice(range(n_ + 1)) # n = choice(range(n_ + 1)) # if m == n: # n = choice(range(n_ + 1)) # dq = random() * qmax # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax: # q[m] = float(float(q[m]) + dq) # q[n] = float(float(q[n]) - dq) # if q[m] > qmax or q[n] < -1 * qmax: # q[m] = q[m] - dq # q[n] = q[n] + dq #for o in range(5*(n_ + 1)): # m = choice(range(n_ + 1)) # n = choice(range(n_ + 1)) # if m == n: # n = choice(range(n_ + 1)) # dq = random() * qmax # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax: # q[m] = float(float(q[m]) + dq) # q[n] = float(float(q[n]) - dq) # if q[m] > qmax or q[n] < -1 * qmax: # q[m] = q[m] - dq # q[n] = q[n] + dq #p = choice(range(n_ + 1)) #q[p] = q[p] - sum(q) #if sum(q) != 0.000000000000000000000: # for l in range(5*(n_ + 1)): # m = choice(range(n_ + 1)) # n = choice(range(n_ + 1)) # if m == n: # n = choice(range(n_ + 1)) # dq = random() * qmax # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax: # q[m] = float(float(q[m]) + dq) # q[n] = float(float(q[n]) - dq) # if q[m] > qmax or q[n] < -1 * qmax: # q[m] = q[m] - dq # q[n] = q[n] + dq # for o in range(5*(n_ + 1)): # m = choice(range(n_ + 1)) # n = choice(range(n_ + 1)) # if m == n: # n = choice(range(n_ + 1)) # dq = random() * qmax # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax: # q[m] = float(float(q[m]) + dq) # q[n] = float(float(q[n]) - dq) # if q[m] > qmax or q[n] < -1 * qmax: # q[m] = q[m] - dq # q[n] = q[n] + dq # p = choice(range(n_ + 1)) # q[p] = q[p] - sum(q) #LJ parameters ep = [] sig = [] q = [] for i in range(ATOM_TYPES): epsilon = round(random() * (epmax - epmin) + epmin, 4) ep.append(epsilon) sigma = round(random() * (sigmax -sigmin) + sigmin, 4) sig.append(sigma) charge = 0 q.append(charge) ep_ = np.asarray(ep) sig_ = np.asarray(sig) q_ = np.asarray(q) ID_ = np.asarray(range(0,ATOM_TYPES)) ep = ep_.reshape(-1,1) sig = sig_.reshape(-1,1) q = q_.reshape(-1,1) ID = ID_.reshape(-1,1) atoms = np.hstack((ID, ep, sig, q)) n_atoms = np.empty([0, 4]) for i in range(n_): atomtype = choice(range(ATOM_TYPES)) n_atoms = np.vstack([n_atoms, atoms[atomtype, :]]) IDs = n_atoms[:,0] for i in range(ATOM_TYPES): if i in IDs: charge = round(random() * (qmax - qmin) + qmin, 4) weight_i = list(IDs).count(i) k = choice(IDs) weight_k = list(IDs).count(k) for j in range(n_): if n_atoms[j,0] == i: n_atoms[j,3] = n_atoms[j,3] + charge * int(weight_k) atoms[i,3] = n_atoms[j,3] + charge * int(weight_k) if n_atoms[j,0] == k: n_atoms[j,3] = n_atoms[j,3] - charge * int(weight_i) atoms[k,3] = n_atoms[j,3] - charge * int(weight_i) # for i in range(100): # atoms[i,3] = round(atoms[i,3], 4) # for i in range(n_): # n_atoms[i,3] = round(n_atoms[i,3], 4) # net_charge = sum(n_atoms[:,3]) # if net_charge != 0: # atomID = choice(range(100)) # weight = list(IDs).count(atomID) # atoms[atomID,3] = atoms[atomID,3] - net_charge/weight # for i in range(n_): # if n_atoms[i,0] == atomID: # n_atoms[atomID,3] = n_atoms[atomID,3] - net_charge/weight mat_charge = str(sum(n_atoms[:,3])) cif_file.write('#NET CHARGE: ' + mat_charge + '\n') mat_X_stats = (mat_name + ' ' + str(nden_) + ' ' + str(xdim_) + ' ' + str(ydim_) + ' ' + str(zdim_) + ' ' + str(n_) + ' ' + mat_charge + '\n') mat_stats.write(mat_X_stats) eps = n_atoms[:,1] sigs = n_atoms[:,2] qs = n_atoms[:,3] #writing mixing_rules, pseudo_atoms... for i in range(ATOM_TYPES): atom_X_pseudo = ('A_' + str(int(atoms[i,0])) + ' yes C C 0 ' + '12.0 ' + str(atoms[i,3]) + ' 0.0 0.0 ' + '1.0 1.00 0 0 absolute 0\n') pseudo_atoms.write(atom_X_pseudo) atom_X_mixing = ('A_' + str(int(atoms[i,0])) + ' ' + 'lennard-jones ' + str(atoms[i,1]) + ' ' + str(atoms[i,2]) + '\n') mixing_rules.write(atom_X_mixing) #writing cif... for i in range(n_): #FIX THIS TO ALLOW FOR NON-INT VALUES? x = choice(range(int(xdim_ + 1))) y = choice(range(int(ydim_ + 1))) z = choice(range(int(zdim_ + 1))) atom_X_cif = ('A_' + str(int(n_atoms[i,0])) + ' ' + 'C ' + str(round(x/xdim_, 4)) + ' ' + str(round(y/ydim_, 4)) + ' ' + str(round(z/zdim_, 4)) + ' ' + str(n_atoms[i,3]) + '\n') cif_file.write(atom_X_cif) # #ep = choice(epdim) # #sig = choice(sigdim) # epval = ep[atomtype] # sigval = sig[atomtype] # charge = q[n_] # #if charge < 0: # atom_X_cif = ('A' + str(atomtype) + ' ' + 'C ' + # str(x/xdim_) + ' ' + str(y/ydim_) + # ' ' + str(z/zdim_) + ' ' + # str(charge) + '\n') # cif_file.write(atom_X_cif) # for k in range(100): # if k != atomtype: # atom_X_pseudo = ('A' + str(k) + ' yes C C 0 12.0 0' + # ' 0.0 0.0 1.0 1.00 0 ' + # '0 absolute 0\n') # if k == atomtype: # atom_X_pseudo = ('A' + str(k) + ' yes C C 0 12.0 ' + # str(q[n_]) + ' 0.0 0.0 1.0 1.00 0 ' + # '0 absolute 0\n') # # pseudo_atoms.write(atom_X_pseudo) # # atom_X_mixing = ('A' + str(k) + ' LENNARD_JONES ' + # str(ep[k]) + ' ' + str(sig[k]) + '\n') # mixing_rules.write(atom_X_mixing) #if charge >= 0: # atom_X_cif = ('A' + str(atomtype) + ' ' + str(x) + ' ' + # str(y) + ' ' + str(z) + ' ' + # str(charge) + '\n') #cif_file.write(atom_X_cif) #for i in range(100): # atom_X_mixing = ('A' + str(i) + ' LENNARD_JONES ' + # str(ep[i]) + ' ' + str(sig[i]) + '\n') # mixing_rules.write(atom_X_mixing) # # atom_X_pseudo = ('A' + str(i) + ' yes C C 0 12.0 ' + # str(q[i]) + ' 0.0 0.0 1.0 1.00 0 ' + # '0 absolute 0\n') ## pseudo_atoms.write(atom_X_pseudo) #SUPPORTED ADSORBATES # name pseudo-atoms # N2 : N_n2; N_com # CO2 : C_co2; O_co2 # methane : CH4_sp3 # helium : He # hydrogen : H_h2; H_com # H2 : H_h2; H_com #adsorbate_mixing = ('N_n2 LENNARD_JONES 36.0 3.31\n' + # 'N_com none\n' + # 'C_co2 LENNARD_JONES 27.0 2.80\n' + # 'O_co2 LENNARD_JONES 79.0 3.05\n' + # 'CH4_sp3 LENNARD_JONES 158.5 3.72\n' + # 'He LENNARD_JONES 10.9 2.64\n' + # 'H_h2 none\n' + # 'H_com LENNARD_JONES 36.7 2.958\n' + # '# general mixing rule for Lennard-Jones\n' + # 'Lorentz-Berthlot') adsorbate_mixing = ('N_n2 lennard-jones 36.0 3.31\n' + 'N_com none\n' + 'C_co2 lennard-jones 27.0 2.80\n' + 'O_co2 lennard-jones 79.0 3.05\n' + 'CH4_sp3 lennard-jones 158.5 3.72\n' + 'He lennard-jones 10.9 2.64\n' + 'H_h2 none\n' + 'H_com lennard-jones 36.7 2.958\n' + '# general mixing rule for Lennard-Jones\n' + 'Lorentz-Berthelot') mixing_rules.write(adsorbate_mixing) adsorbate_pseudo = ('N_n2 yes N N 0 14.00674 -0.4048' + ' 0.0 1.0 0.7 0 0 relative 0\n' + 'N_com no N - 0 0.0 0.8096' + ' 0.0 1.0 0.7 0 0 relative 0\n' + 'C_co2 yes C C 0 12.0 0.70' + ' 0.0 1.0 0.720 0 0 relative 0\n' + 'O_co2 yes O O 0 15.9994 -0.35' + ' 0.0 1.0 0.68 0 0 relative 0\n' + 'CH4_sp3 yes C C 0 16.04246 0.0' + ' 0.0 1.0 1.00 0 0 relative 0\n' + 'He yes He He 0 4.002602 0.0' + ' 0.0 1.0 1.0 0 0 relative 0\n' + 'H_h2 yes H H 0 1.00794 0.468' + ' 0.0 1.0 0.7 0 0 relative 0\n' + 'H_com no H H 0 0.0 - 0.936' + ' 0.0 1.0 0.7 0 0 relative 0\n') pseudo_atoms.write(adsorbate_pseudo) force_field_rules = ('# rules to overwrite\n0\n' + '# number of defined interactions\n0\n' + '# mixing rules to overwrite\n0') force_field.write(force_field_rules) cif_file.close() mixing_rules.close() pseudo_atoms.close() force_field.close() mat_stats.close()
normal
{ "blob_id": "ba72af921a9562d748bcd65f1837ea8eb5da5697", "index": 150, "step-1": "from random import choice, random, randrange\nfrom math import fsum\nimport os\nimport numpy as np\n\ndef mat17(N, ATOM_TYPES, ndenmax=0.04302, ndenmin=0.0000013905, xmax=51.2, xmin=25.6, ymax=51.2, ymin=25.6,\nzmax=51.2, zmin=25.6, epmax=513.264, epmin=1.2580, sigmax=6.549291, sigmin=1.052342, qmax=0.0, qmin=0.0):\n#epmax DEFINED WRT TO X-Y-Z LIMITS?\n#max number density based on that of pure Iron\n#max unit cell dimensions based on PCN-777 cages size\n#max LJ parameters (for now using 1.5x highest values in GenericMOFs)\n#max charge... UFF?\n\n #ATOM_TYPES = 4\n\n if type(N) != int:\n print 'N must be an integer.'\n \n Ntag = str(N)\n ntag = str(ndenmax)\n xtag = str(xmax)\n ytag = str(xmax)\n ztag = str(xmax)\n eptag = str(xmax)\n sigtag = str(xmax)\n qtag = str(xmax)\n \n top_path = ('materials' + '_' + Ntag + '.' + ntag + '_' + xtag + '.' + ytag\n\t\t + '.' + ztag + '_' + eptag + '.' + sigtag + '_' + qtag)\n \n if not os.path.exists(top_path):\n os.mkdir(top_path) \n\n# def drange(start, stop, step):\n# r = start\n# while r < stop:\n# yield r\n# r+= step\n \n# nden0 = drange(1, ndenmax*10000, ndenp*10000)\n# ndendim = [nden for nden in nden0]\n \n# x0 = drange(0, xmax + xp, xp)\n# xdim = [x for x in x0]\n \n# y0 = drange(0, ymax + yp, yp)\n# ydim = [y for y in y0]\n \n# z0 = drange(0, zmax + zp, zp)\n# zdim = [z for z in z0]\n \n# ep0 = drange(0, epmax + epp, epp)\n# epdim = [ep for ep in ep0]\n# sig0 = drange(0, sigmax + sigp, sigp)\n# sigdim = [sig for sig in sig0] \n\n\n #open mat_stats.txt, to track material data \n mat_stats = open(os.path.abspath(top_path)+ '/mat_stats.txt', 'w')\n mat_stat_heading = ('\\nBOUNDARIES\\nNumber of particles: ' + Ntag +\n \t'\\nnumber density: ' + ntag + '\\nx-coordinate: ' +\n\t\t\txtag + '\\ny-coordinate: ' + ytag + '\\nz-coordinate: ' +\n\t\t\t ztag + '\\nEpsilon: ' + eptag + '\\nSigma: ' + sigtag \n\t\t\t+ '\\nCharge: ' + qtag + '\\n\\n' +\n\t\t\t'#name number density xdim ydim '+\n\t\t\t'zdim total particles net charge\\n')\n mat_stats.write(mat_stat_heading)\n \n #MAT-XXX loop...\n for i in range(N + 1):\n \n mat_name = 'MAT-' + str(i)\n\n \n\t#make MAT-XXX directory\n\tos.mkdir(top_path+'/'+mat_name)\n\t\n\t#open .cif file\n cif_file = open(os.path.abspath(top_path) + '/'+mat_name + '/' + \n\t\t\tmat_name+'.cif', 'w')\n\t\n\t#open force_field_mixing_rules.def\n\tmixing_rules = open(os.path.abspath(top_path) + '/'+mat_name +\n\t\t\t'/force_field_mixing_rules.def', 'w')\n \n\t#open pseudo_atoms.def\n pseudo_atoms = open(os.path.abspath(top_path) + '/'+mat_name + \n\t\t\t'/pseudo_atoms.def', 'w')\n\t\n\t#open force_field.def\n force_field = open(os.path.abspath(top_path) + '/'+mat_name +\n\t\t\t'/force_field.def', 'w')\n\n \t#nden_ = choice(ndendim)/10000.\n #xdim_ = choice(xdim)\n #ydim_ = choice(ydim)\n #zdim_ = choice(zdim)\n #nden_ = randrange(0.0001, ndenmax, 1)\n #xdim_ = randrange(15., xmax, 0.1)\n\t#ydim_ = randrange(15., ymax, 0.1)\n #zdim_ = randrange(15., zmax, 0.1)\n #N_ = xdim_ * ydim_ * zdim_ * nden_\n #n_ = int(N_) \n nden_ = round(random() * (ndenmax - ndenmin) + ndenmin, 6)\n\txdim_ = round(random() * (xmax - xmin) + xmin, 4)\n ydim_ = round(random() * (ymax - ymin) + ymin, 4)\n zdim_ = round(random() * (zmax - zmin) + zmin, 4)\n N_ = xdim_ * ydim_ * zdim_ * nden_\n n_ = int(N_)\n\n cif_heading = ('material' + str(i) + \n\t\t\t'\\n\\nloop_\\n' +\n\t\t\t'_symmetry_equiv_pos_as_xyz\\n' +\n\t\t\t' x,y,z\\n' +\n\t\t\t'_cell_length_a ' + str(xdim_) +\n\t\t\t'\\n_cell_length_b ' + str(ydim_) +\n\t\t\t'\\n_cell_length_c ' + str(zdim_) + \n\t\t\t'\\n_cell_angle_alpha 90.0000\\n' +\n\t\t\t'_cell_angle_beta 90.0000\\n' +\n\t\t\t'_cell_angle_gamma 90.0000\\n' +\n\t\t\t'loop_\\n' +\n\t\t\t'_atom_site_label\\n' +\n\t\t\t'_atom_site_type_symbol\\n' +\n\t\t\t'_atom_site_fract_x\\n' +\n\t\t\t'_atom_site_fract_y\\n' +\n\t\t\t'_atom_site_fract_z\\n' +\n\t\t\t'_atom_site_charge\\n')\n\tcif_file.write(cif_heading)\n\n# mixing_heading = ('# general rule for shifted vs truncated\\nshifted\\n' +\n#\t\t\t'# general rule for tailcorrections\\nno\\n' +\n#\t\t\t'# number of defined interactions\\n' + str(108) + #check these + XXX values\n#\t\t\t'\\n# type interaction\\n')\n\n mixing_heading = ('# general rule for shifted vs truncated\\n' +\n 'shifted\\n' +\n '# general rule tailcorrections\\n' +\n 'no\\n' +\n '# number of defined interactions\\n' +\n str(ATOM_TYPES + 8) + '\\n' +\n '# type interaction, parameters. IMPORTANT: define shortest matches first, so that more specific ones overwrites these\\n')\n mixing_rules.write(mixing_heading)\n \n pseudo_heading = ('#number of pseudo atoms\\n' + str(ATOM_TYPES + 8) + \n\t\t\t'\\n#type print as chem oxidation' +\n\t\t\t' mass charge polarization ' +\n\t\t\t'B-factor radii connectivity anisotropic' +\n\t\t\t' anisotrop-type tinker-type\\n')\n pseudo_atoms.write(pseudo_heading)\n \n ##make charges\n #q = []\n \t#for k in range(n_ + 1):\n # q.append(0)\n #for l in range(5*(n_ + 1)):\n # m = choice(range(n_ + 1))\n # n = choice(range(n_ + 1))\n # if m == n:\n # n = choice(range(n_ + 1))\n # dq = random() * qmax\n # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax:\n # q[m] = float(float(q[m]) + dq)\n # q[n] = float(float(q[n]) - dq)\n # if q[m] > qmax or q[n] < -1 * qmax:\n # q[m] = q[m] - dq\n # q[n] = q[n] + dq\n #for o in range(5*(n_ + 1)):\n # m = choice(range(n_ + 1))\n # n = choice(range(n_ + 1))\n # if m == n:\n # n = choice(range(n_ + 1))\n # dq = random() * qmax\n # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax:\n # q[m] = float(float(q[m]) + dq)\n # q[n] = float(float(q[n]) - dq)\n # if q[m] > qmax or q[n] < -1 * qmax:\n # q[m] = q[m] - dq\n # q[n] = q[n] + dq\n #p = choice(range(n_ + 1))\n #q[p] = q[p] - sum(q)\n #if sum(q) != 0.000000000000000000000:\n # for l in range(5*(n_ + 1)):\n # m = choice(range(n_ + 1))\n # n = choice(range(n_ + 1))\n # if m == n:\n # n = choice(range(n_ + 1))\n # dq = random() * qmax\n # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax:\n # q[m] = float(float(q[m]) + dq)\n # q[n] = float(float(q[n]) - dq)\n # if q[m] > qmax or q[n] < -1 * qmax:\n # q[m] = q[m] - dq\n # q[n] = q[n] + dq\n # for o in range(5*(n_ + 1)):\n # m = choice(range(n_ + 1))\n # n = choice(range(n_ + 1))\n # if m == n:\n # n = choice(range(n_ + 1))\n # dq = random() * qmax\n # if q[m] + dq <= qmax and q[n] - dq >= -1 * qmax:\n # q[m] = float(float(q[m]) + dq)\n # q[n] = float(float(q[n]) - dq)\n # if q[m] > qmax or q[n] < -1 * qmax:\n # q[m] = q[m] - dq\n # q[n] = q[n] + dq\n # p = choice(range(n_ + 1))\n # q[p] = q[p] - sum(q)\n\t\n #LJ parameters\n\n\tep = []\n\tsig = []\n q = []\n for i in range(ATOM_TYPES):\n epsilon = round(random() * (epmax - epmin) + epmin, 4)\n ep.append(epsilon)\n sigma = round(random() * (sigmax -sigmin) + sigmin, 4)\n sig.append(sigma)\n charge = 0\n q.append(charge)\n \n ep_ = np.asarray(ep)\n sig_ = np.asarray(sig)\n q_ = np.asarray(q)\n ID_ = np.asarray(range(0,ATOM_TYPES))\n\n ep = ep_.reshape(-1,1)\n sig = sig_.reshape(-1,1)\n q = q_.reshape(-1,1)\n ID = ID_.reshape(-1,1)\n\n atoms = np.hstack((ID, ep, sig, q))\n\n n_atoms = np.empty([0, 4])\n for i in range(n_):\n atomtype = choice(range(ATOM_TYPES))\n n_atoms = np.vstack([n_atoms, atoms[atomtype, :]])\n \n IDs = n_atoms[:,0]\n\n for i in range(ATOM_TYPES):\n if i in IDs:\n charge = round(random() * (qmax - qmin) + qmin, 4)\n weight_i = list(IDs).count(i)\n k = choice(IDs)\n weight_k = list(IDs).count(k)\n for j in range(n_):\n if n_atoms[j,0] == i:\n n_atoms[j,3] = n_atoms[j,3] + charge * int(weight_k)\n\t\t\tatoms[i,3] = n_atoms[j,3] + charge * int(weight_k)\n if n_atoms[j,0] == k:\n n_atoms[j,3] = n_atoms[j,3] - charge * int(weight_i)\n atoms[k,3] = n_atoms[j,3] - charge * int(weight_i)\n\n# for i in range(100):\n# atoms[i,3] = round(atoms[i,3], 4)\n\n# for i in range(n_):\n# n_atoms[i,3] = round(n_atoms[i,3], 4)\n\n\n\n# net_charge = sum(n_atoms[:,3])\n# if net_charge != 0:\n# atomID = choice(range(100))\n# weight = list(IDs).count(atomID)\n# atoms[atomID,3] = atoms[atomID,3] - net_charge/weight\n# for i in range(n_):\n# if n_atoms[i,0] == atomID:\n# n_atoms[atomID,3] = n_atoms[atomID,3] - net_charge/weight\n\n\n mat_charge = str(sum(n_atoms[:,3]))\n\tcif_file.write('#NET CHARGE: ' + mat_charge + '\\n')\n\tmat_X_stats = (mat_name + ' ' + str(nden_) + ' ' + str(xdim_) + ' ' + str(ydim_) +\n\t\t\t' ' + str(zdim_) + ' ' + str(n_) + ' ' + \n\t\t\tmat_charge + '\\n')\n\tmat_stats.write(mat_X_stats)\n\t\n eps = n_atoms[:,1]\n sigs = n_atoms[:,2]\n qs = n_atoms[:,3]\n\t\n\t#writing mixing_rules, pseudo_atoms...\n for i in range(ATOM_TYPES):\n\n atom_X_pseudo = ('A_' + str(int(atoms[i,0])) + ' yes C C 0 ' +\n '12.0 ' + str(atoms[i,3]) + ' 0.0 0.0 ' +\n '1.0 1.00 0 0 absolute 0\\n')\n pseudo_atoms.write(atom_X_pseudo)\n\n atom_X_mixing = ('A_' + str(int(atoms[i,0])) + ' ' +\n 'lennard-jones ' + str(atoms[i,1]) + ' '\n + str(atoms[i,2]) + '\\n')\n mixing_rules.write(atom_X_mixing) \n\n\t#writing cif...\n\n for i in range(n_):\n#FIX THIS TO ALLOW FOR NON-INT VALUES?\n x = choice(range(int(xdim_ + 1)))\n y = choice(range(int(ydim_ + 1)))\n z = choice(range(int(zdim_ + 1)))\n \n atom_X_cif = ('A_' + str(int(n_atoms[i,0])) + ' ' + 'C ' + \n str(round(x/xdim_, 4)) + ' ' + str(round(y/ydim_, 4)) + \n ' ' + str(round(z/zdim_, 4)) + ' ' +\n str(n_atoms[i,3]) + '\\n') \n cif_file.write(atom_X_cif)\n\n\n\n # #ep = choice(epdim)\n # #sig = choice(sigdim)\n # epval = ep[atomtype]\n # sigval = sig[atomtype]\n # charge = q[n_]\n # #if charge < 0:\n # atom_X_cif = ('A' + str(atomtype) + ' ' + 'C ' + \n\t#\t\t\tstr(x/xdim_) + ' ' + str(y/ydim_) + \n\t#\t\t\t' ' + str(z/zdim_) + ' ' +\n\t#\t\t\tstr(charge) + '\\n') \n # cif_file.write(atom_X_cif)\n # for k in range(100):\n # if k != atomtype:\n # atom_X_pseudo = ('A' + str(k) + ' yes C C 0 12.0 0' +\n\t#\t\t\t ' 0.0 0.0 1.0 1.00 0 ' +\n\t#\t\t\t '0 absolute 0\\n')\n # if k == atomtype:\n # atom_X_pseudo = ('A' + str(k) + ' yes C C 0 12.0 ' +\n\t#\t\t\t str(q[n_]) + ' 0.0 0.0 1.0 1.00 0 ' +\n\t#\t\t\t '0 absolute 0\\n')\n # \n # pseudo_atoms.write(atom_X_pseudo)\n # \n # atom_X_mixing = ('A' + str(k) + ' LENNARD_JONES ' +\n\t#\t\t\t str(ep[k]) + ' ' + str(sig[k]) + '\\n')\n # mixing_rules.write(atom_X_mixing)\n\n \n\n #if charge >= 0:\n # atom_X_cif = ('A' + str(atomtype) + ' ' + str(x) + ' ' +\n\t\t#\t\tstr(y) + ' ' + str(z) + ' ' +\n\t\t#\t\tstr(charge) + '\\n')\n\t\t#cif_file.write(atom_X_cif)\n \t\n #for i in range(100):\n\n # atom_X_mixing = ('A' + str(i) + ' LENNARD_JONES ' +\n\t#\t\t\tstr(ep[i]) + ' ' + str(sig[i]) + '\\n')\n # mixing_rules.write(atom_X_mixing)\n#\n # atom_X_pseudo = ('A' + str(i) + ' yes C C 0 12.0 ' +\n#\t\t\t\tstr(q[i]) + ' 0.0 0.0 1.0 1.00 0 ' +\n#\t\t\t\t'0 absolute 0\\n')\n ## pseudo_atoms.write(atom_X_pseudo)\n \n#SUPPORTED ADSORBATES\n# name pseudo-atoms\n# N2 : N_n2; N_com\n# CO2 : C_co2; O_co2\n# methane : CH4_sp3\n# helium : He\n# hydrogen : H_h2; H_com\n# H2 : H_h2; H_com\n\n #adsorbate_mixing = ('N_n2 LENNARD_JONES 36.0 3.31\\n' +\n\t#\t\t'N_com none\\n' +\n\t#\t\t'C_co2 LENNARD_JONES 27.0 2.80\\n' +\n\t#\t\t'O_co2 LENNARD_JONES 79.0 3.05\\n' +\n\t#\t\t'CH4_sp3 LENNARD_JONES 158.5 3.72\\n' +\n\t#\t\t'He LENNARD_JONES 10.9 2.64\\n' +\n\t#\t\t'H_h2 none\\n' +\n\t#\t\t'H_com LENNARD_JONES 36.7 2.958\\n' +\n\t#\t\t'# general mixing rule for Lennard-Jones\\n' +\n\t#\t\t'Lorentz-Berthlot')\n adsorbate_mixing = ('N_n2 lennard-jones 36.0 3.31\\n' +\n 'N_com none\\n' +\n 'C_co2 lennard-jones 27.0 2.80\\n' +\n 'O_co2 lennard-jones 79.0 3.05\\n' +\n 'CH4_sp3 lennard-jones 158.5 3.72\\n' +\n 'He lennard-jones 10.9 2.64\\n' +\n 'H_h2 none\\n' +\n 'H_com lennard-jones 36.7 2.958\\n' +\n '# general mixing rule for Lennard-Jones\\n' +\n 'Lorentz-Berthelot')\n mixing_rules.write(adsorbate_mixing)\n\n adsorbate_pseudo = ('N_n2 yes N N 0 14.00674 -0.4048' +\n\t\t\t' 0.0 1.0 0.7 0 0 relative 0\\n' +\n\t\t\t'N_com no N - 0 0.0 0.8096' +\n\t\t\t' 0.0 1.0 0.7 0 0 relative 0\\n' +\n\t\t\t'C_co2 yes C C 0 12.0 0.70' +\n\t\t\t' 0.0 1.0 0.720 0 0 relative 0\\n' +\n\t\t\t'O_co2 yes O O 0 15.9994 -0.35' +\n\t\t\t' 0.0 1.0 0.68 0 0 relative 0\\n' +\n\t\t\t'CH4_sp3 yes C C 0 16.04246 0.0' +\n\t\t\t' 0.0 1.0 1.00 0 0 relative 0\\n' +\n\t\t\t'He yes He He 0 4.002602 0.0' +\n\t\t\t' 0.0 1.0 1.0 0 0 relative 0\\n' +\n\t\t\t'H_h2 yes H H 0 1.00794 0.468' +\n\t\t\t' 0.0 1.0 0.7 0 0 relative 0\\n' +\n\t\t\t'H_com no H H 0 0.0 - 0.936' +\n\t\t\t' 0.0 1.0 0.7 0 0 relative 0\\n')\n pseudo_atoms.write(adsorbate_pseudo)\n \n force_field_rules = ('# rules to overwrite\\n0\\n' +\n\t\t\t\t'# number of defined interactions\\n0\\n' +\n\t\t\t\t'# mixing rules to overwrite\\n0')\n\tforce_field.write(force_field_rules)\n \n cif_file.close()\n mixing_rules.close()\n pseudo_atoms.close()\n force_field.close()\n mat_stats.close()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
from django.contrib import admin # Register your models here. from registration.models import FbAuth class AllFieldsAdmin(admin.ModelAdmin): """ A model admin that displays all field in admin excpet Many to many and pk field """ def __init__(self, model, admin_site): self.list_display = [field.name for field in model._meta.fields if field.name not in ["id"]] super(AllFieldsAdmin, self).__init__(model, admin_site) admin.site.register(FbAuth)
normal
{ "blob_id": "821afa85eb783b4bf1018800f598a3294c4cbcfb", "index": 9532, "step-1": "<mask token>\n\n\nclass AllFieldsAdmin(admin.ModelAdmin):\n <mask token>\n\n def __init__(self, model, admin_site):\n self.list_display = [field.name for field in model._meta.fields if \n field.name not in ['id']]\n super(AllFieldsAdmin, self).__init__(model, admin_site)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass AllFieldsAdmin(admin.ModelAdmin):\n \"\"\"\n A model admin that displays all field in admin excpet Many to many and pk field\n \"\"\"\n\n def __init__(self, model, admin_site):\n self.list_display = [field.name for field in model._meta.fields if \n field.name not in ['id']]\n super(AllFieldsAdmin, self).__init__(model, admin_site)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass AllFieldsAdmin(admin.ModelAdmin):\n \"\"\"\n A model admin that displays all field in admin excpet Many to many and pk field\n \"\"\"\n\n def __init__(self, model, admin_site):\n self.list_display = [field.name for field in model._meta.fields if \n field.name not in ['id']]\n super(AllFieldsAdmin, self).__init__(model, admin_site)\n\n\nadmin.site.register(FbAuth)\n", "step-4": "from django.contrib import admin\nfrom registration.models import FbAuth\n\n\nclass AllFieldsAdmin(admin.ModelAdmin):\n \"\"\"\n A model admin that displays all field in admin excpet Many to many and pk field\n \"\"\"\n\n def __init__(self, model, admin_site):\n self.list_display = [field.name for field in model._meta.fields if \n field.name not in ['id']]\n super(AllFieldsAdmin, self).__init__(model, admin_site)\n\n\nadmin.site.register(FbAuth)\n", "step-5": "from django.contrib import admin\n\n# Register your models here.\nfrom registration.models import FbAuth\n\n\nclass AllFieldsAdmin(admin.ModelAdmin):\n\n \"\"\"\n A model admin that displays all field in admin excpet Many to many and pk field\n \"\"\"\n\n def __init__(self, model, admin_site):\n self.list_display = [field.name for field in model._meta.fields\n if field.name not in [\"id\"]]\n super(AllFieldsAdmin, self).__init__(model, admin_site)\n\nadmin.site.register(FbAuth)", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
from csv import reader, writer from collections import OrderedDict as OrdDic import sqlite3 from jsmin import jsmin from glob import glob from csscompressor import compress from threading import Timer from glob import glob import os import shutil import logging import json class MinifyFilesPre: def __init__(self, merge=False): file_names = glob("resources/static/js_files/*.js") file_names.remove("resources/static/js_files/full_version.js") self.file_names = file_names self.merge = merge self.js = "" def save(self): """combines several js files together, with optional minification""" with open("resources/static/js_files/full_version.js", 'w', newline="\n") as w: w.write(self.js) def js_merge(self): """saves minified version to a single one""" if self.merge: js = "" for file_name in self.file_names: try: js += jsmin(open(file_name, newline="\n").read()) except FileNotFoundError: print(f"The file {file_name} could not be found") self.js = jsmin(js) else: for file_name in self.file_names: js = jsmin(open(file_name, newline="\n").read()) open(file_name, 'w', newline="\n").write(js) @staticmethod def min_js_file(file_name): js = jsmin(open(file_name, newline="\n").read()) open(file_name, 'w', newline="\n").write(js) @staticmethod def min_css_file(file_name): css = compress(open(file_name, newline="\n").read()) open(file_name[:-4] + '.min.css', 'w', newline="\n").write(css) @staticmethod def get_js_files(): file_names = glob("resources/static/js_files/*.js") file_names.remove("resources/static/js_files/full_version.js") class DbManager: def __init__(self, fname=None, tname=None): if fname: self.FILE_NAME = fname else: self.FILE_NAME = 'resources/static/LOG_Temp.db' if tname: self.TABLE_NAME = tname else: self.TABLE_NAME = "'LOG_RETURNS'" def query_data(self, conditions, entries): try: with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() condition_order = ['logID', 'returnType', 'sender', 'reciever', 'logTime', 'dutyOfficer', 'net', 'serials'] cond_list = [] cond_string_list = [] for cond in condition_order: val = "" try: val = conditions[cond] except KeyError: val = "" if "|" in val: i = 0 dep = list() for sub_val in val.split("|"): i+=1 cond_list.append(f"%{sub_val}%") cond_string_list.append("("+f"lower({cond}) LIKE ?"+ f" OR lower({cond}) LIKE ?"*(i-1)+")") else: for sub_val in val.split(", "): cond_string_list.append(f"lower({cond}) LIKE ?") sub_val = f"%{sub_val.lower()}%" cond_list.append(sub_val) if conditions['other']: cond = "serials" val = conditions['other'] if "|" in val: i = 0 for sub_val in val.split("|"): i+=1 cond_list.append(f"%{sub_val}%") cond_string_list.append("("+f"lower({cond}) LIKE ?"+ f" OR lower({cond}) LIKE ?"*(i-1)+")") else: for sub_val in val.split(", "): cond_string_list.append(f"lower({cond}) LIKE ?") sub_val = f"%{sub_val.lower()}%" cond_list.append(sub_val) if conditions['logTimeFrom']: if conditions['logTimeTo']: cond_string_list.append("logTime>= ? AND logTime<= ?") cond_list.append(conditions['logTimeFrom']) cond_list.append(conditions['logTimeTo']) else: cond_string_list.append("logTime>= ?") cond_list.append(conditions['logTimeFrom']) elif conditions['logTimeTo']: cond_string_list.append("logTime <= ?") cond_list.append(conditions['logTimeTo']) cond_string = ' AND '.join(cond_string_list) print(cond_string) print(cond_list) results = c.execute(f"SELECT * FROM {self.TABLE_NAME} WHERE " f"{cond_string}" f" ORDER BY logID DESC LIMIT {entries}", cond_list) return results except sqlite3.OperationalError as e: print(e) def create_db(self, ret=False): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() # Create table try: c.execute(f'''CREATE TABLE {self.TABLE_NAME} ( `logID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `returnType` text, `sender` text, `reciever` text, `logTime` integer, `dutyOfficer` text, `net` TEXT, `serials` text );''') conn.commit() except sqlite3.OperationalError: print("The Db already exists") if ret: return self.read_return() def count_records(self): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() results = c.execute(f"SELECT COUNT('LogID') FROM {self.TABLE_NAME}") return results def create_game_table(self, ret=False): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() # Create table try: c.execute(f'''CREATE TABLE `{self.TABLE_NAME}` ( `GameID` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, `Name` TEXT DEFAULT '?', `Rank` TEXT DEFAULT '?', `Pl` TEXT DEFAULT '?', `Score` INTEGER DEFAULT 0, `Time` INTEGER );''') conn.commit() except sqlite3.OperationalError: print("The Db already exists") if ret: return self.read_return() def new_return(self, lst): try: with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() c.execute( 'INSERT INTO ' + self.TABLE_NAME + ' VALUES (NULL,' + '?, ' * (len(lst) - 1) + '?)', lst) except sqlite3.OperationalError as e: print(e) """ if 'no such table' in str(e): if "game" in str(self.FILE_NAME): print("MEME") self.create_game_table() else: self.create_db() self.new_return(lst) """ def delete_return_byID(self, id): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() c.execute(f"DELETE FROM {self.TABLE_NAME} WHERE logID = {id}") def read_return(self, entries=None): try: with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() if entries: results = c.execute(f"SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}") else: # should not be used but just here just in case results = c.execute(f'SELECT * FROM {self.TABLE_NAME}') return results except sqlite3.OperationalError as e: if 'no such table' in str(e): DbManager.create_db(self) def read_game_score(self, entries=None): try: with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() if entries: results = c.execute(f"SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC LIMIT {entries}") else: # should not be used but just here just in case results = c.execute(f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC') return results except sqlite3.OperationalError as e: if 'no such table' in str(e): DbManager.create_game_table(self) def find_index(self, log_id): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() sql_str = ("""SELECT * FROM """ + self.TABLE_NAME + """ WHERE logID=?""") x = c.execute(sql_str, [str(log_id)]) return x def get_first_index(self): with sqlite3.connect(self.FILE_NAME) as conn: i="" c = conn.cursor() sqlStr = ("""SELECT logID FROM """ + self.TABLE_NAME + """ WHERE logID = (SELECT MAX(logID) FROM """ + self.TABLE_NAME + ")") x = c.execute(sqlStr) for i in x: i = int(list(i)[0]) try: return i except UnboundLocalError: return "" def update_record(self, lst, logID): with sqlite3.connect(self.FILE_NAME) as conn: c = conn.cursor() rowData = """returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?""" c.execute( 'UPDATE ' + self.TABLE_NAME + ' SET ' + rowData + ' WHERE logID=' + logID, lst) class File: @staticmethod def db_connect(sets): try: fname = sets['DB_FILE_NAME'] except KeyError: fname = None try: tname = sets['DB_TABLE_NAME'] except KeyError: tname = None conn = DbManager(fname=fname, tname=tname) return conn @staticmethod def generate_css_min(): MinifyFilesPre.min_css_file('resources/static/styles/main.css') @staticmethod def pre_merge(merge=False): if merge: tmp_file = MinifyFilesPre() tmp_file.js_merge() tmp_file.save() else: MinifyFilesPre.get_js_files() @staticmethod def get_first(self): return self.get_first_index() @staticmethod def save_dic(dic): """ Saves the given dictionary of serials to a file """ json.dump(dic, open("resources/files/serials.csv", "w")) # w = writer(open("resources/files/serials.csv", "w", newline="\n")) # w.writerow(['Return Name', 'Serials']) # for name, serials in dic.items(): # lst = [] # if name == "Return Name": # lst.append(name) # lst.append(serials) # else: # for serial in serials: # if serial == "Return Name": # lst.append(serials) # else: # inner_lst = [] # for cont in serials[serial]: # if cont == "options": # inner_lst.append(cont + ";;@@;;" + # ";;##;;".join( # serials # [serial] # ["options"])) # else: # inner_lst.append( # cont + ";;@@;;" + serials[serial][cont]) # lst.append(serial + ';;:::;;' + ";;!!!;;".join(inner_lst)) # w.writerow([(name), (';;,,,;;'.join(lst))]) @staticmethod def read_dic(): """ reads the dictionary of serials """ # should return the original format dic = OrdDic() dic.update(json.load(open("resources/files/serials.csv", "r"))) # OLD CODE # logging.log(logging.INFO, "File path: "+os.path.realpath(__file__)) # r = reader(open("resources/files/serials.csv", "r", newline="\n")) # i = 0 # for row in r: # if i: # inner_dic = OrdDic() # for serial in row[1].split(';;,,,;;'): # serial = serial.split(';;:::;;') # sub_dic = OrdDic() # for sub_serial in serial[1].split(';;!!!;;'): # sub_serial = sub_serial.split(";;@@;;") # if sub_serial[0] == 'options': # options = sub_serial[1].split(";;##;;") # sub_dic.update({sub_serial[0]: options}) # else: # sub_dic.update( # {sub_serial[0]: sub_serial[1]}) # inner_dic.update({serial[0]: sub_dic}) # # lst = row[1].split('\\') # dic.update({row[0]: inner_dic}) # else: # i += 1 # # print(" * Read Dictionary") return dic @staticmethod def read_legacy(): """ Depreciated reads the dictionary and returns it in the legacy format """ serials = File.read_dic() final_dic = OrdDic() for name, dic in serials.items(): inner_dic = OrdDic() for serial in dic: inner_dic.update({serial: dic[serial]['desc']}) final_dic.update({name: inner_dic}) return final_dic @staticmethod def read_locations(): """ reads the file containing the locations """ r = open("resources/files/locations.txt", "r", newline="\n") locations = r.read().split("\n") return locations @staticmethod def save_Locations(lst): lst = '\n'.join(lst) w = open("resources/files/locations.txt", "w", newline="\n") w.write(lst) @staticmethod def save_callsigns(lst): lst = '\n'.join(lst) w = open("resources/files/callsigns.txt", "w", newline="\n") w.write(lst) @staticmethod def read_callsigns(): """ reads the file containing the callsigns """ r = open("resources/files/callsigns.txt", "r", newline="\n") callsigns = r.read().split("\n") return callsigns @staticmethod def read_settings(): """ reads the settings from file """ settings = OrdDic() settings.update(json.load(open("resources/files/settings.txt", "r"))) ## OLD WAY BELOW #r = open("resources/files/settings.txt", "r", newline="\n") # for option in r.read().split('\n'): # try: # #option = option.split('\\') # #settings.update({option[0]: option[1]}) # # settings.update(json.loads(option)) # except IndexError: # pass return settings @staticmethod def save_settings(dic): """ saves the given settings (dictionary) to file """ json.dump(dic, open("resources/files/settings.txt", "w")) # LEGACY # with open("resources/files/settings.txt", "w", newline="\n") as w: # for sett, val in dic.items(): # w.write(sett + '\\' + val + '\n') @staticmethod def save_log(self, log, update=False): """ Saves the log to file """ main_keys = [ 'name', 'sender', 'receiver', 'time', 'duty', 'net' ] # print(test) lst = [] for key in main_keys: # print(key) lst.append(log[key]) log.pop(key) # LEGACY # inn_lst = [] # for serial, val in log.items(): # if not (serial in main_keys): # inn_lst.append(serial + '\\' + val) # lst.append('||'.join(inn_lst)) lst.append(json.dumps(log)) # print(lst) if update: self.update_record(lst, log['logID']) else: self.new_return(lst) @staticmethod def load_log_query(Db, query): x = list(Db.query_data(query, 100)) local_log = list() for row in x: row = list(row) try: ret = OrdDic() ret.update({'logID': row[0]}) ret.update({'name': row[1]}) ret.update({'sender': row[2]}) ret.update({'receiver': row[3]}) ret.update({'time': row[4]}) ret.update({'duty': row[5]}) ret.update({'net': row[6]}) ret.update(json.loads(row[7])) # LEGACY # for serial_data in row[7:]: # try: # for serial in serial_data.split('||'): # ser, val = serial.split('\\') # val = "" + val # ret.update({ser: str(val)}) # except AttributeError: # print('The Db structure is incorrect') local_log.append(ret) except TypeError: print("none value in db") return local_log @staticmethod def load_log(Db, log_id=None): """ loads the log file """ # try: # r = reader(open("resources/static/logs.csv", "r")) # except FileNotFoundError: # w = open("resources/static/logs.csv", 'w') # w.close() # r = reader(open("resources/static/logs.csv", "r")) if log_id: row = Db.find_index(log_id).fetchone() local_log = list() ret = None try: ret = OrdDic() ret.update({'logID': row[0]}) ret.update({'name': row[1]}) ret.update({'sender': row[2]}) ret.update({'receiver': row[3]}) ret.update({'time': fix_time(row[4])}) ret.update({'duty': row[5]}) ret.update({'net': row[6]}) ret.update(json.loads(row[7])) # LEGACY # for serial_data in row[7:]: # try: # for serial in serial_data.split('||'): # ser, val = serial.split('\\') # val = "" + val # ret.update({ser: str(val)}) # except AttributeError: # print('The Db structure is incorrect') except TypeError: pass # This is handled upon return (it returns None type) return ret else: try: x = list(Db.read_return(entries=100)) except TypeError: x = "" local_log = list() for row in x: row = list(row) try: ret = OrdDic() ret.update({'logID': row[0]}) ret.update({'name': row[1]}) ret.update({'sender': row[2]}) ret.update({'receiver': row[3]}) ret.update({'time': fix_time(row[4])}) ret.update({'duty': row[5]}) ret.update({'net': row[6]}) ret.update(json.loads(row[7])) # LEGACY # for serial_data in row[7:]: # try: # for serial in serial_data.split('||'): # ser, val = serial.split('\\') # val = "" + val # ret.update({ser: str(val)}) # except AttributeError: # print('The Db structure is incorrect') local_log.append(ret) except TypeError: print("none value in db") return local_log @staticmethod def delete_log_byID(Db, id): Db.delete_return_byID(id) def fix_time(dtg): if len(str(dtg)) == 6: return str(dtg) else: return str(f'0{dtg}') class SaveTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False def copytree(src, dst, symlinks=False, ignore=None): for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) def backup(): files = glob("/Volumes/*") rem = ["/Volumes/student", "/Volumes/com.apple.TimeMachine.localsnapshots", "/Volumes/Macintosh HD", "Blah"] for path in rem: try: files.remove(path) except ValueError: pass usb = None for path in files: if "CP" in path: usb = os.path.join(path, "Backup") break else: usb = None print("No Backup USB found") if usb: # save to usb print("Saving...", end=" ") save(os.path.join(usb, "files"), "resources/files") save(os.path.join(usb, "db"), "resources/static/db") print("Saved") def save(dest, src): if not os.path.exists(dest): os.makedirs(dest) copytree(src, dest) if __name__ == '__main__': pass # File.pre_merge() # settings = File.read_settings() # File.save_settings(settings) # File.read_locations() # File.read_callsigns() # File.save_dic() # File.read_dic() # x = file() # x.save()
normal
{ "blob_id": "38bd9e5b2147838b6061925d72b989c83343f1c2", "index": 9800, "step-1": "<mask token>\n\n\nclass DbManager:\n\n def __init__(self, fname=None, tname=None):\n if fname:\n self.FILE_NAME = fname\n else:\n self.FILE_NAME = 'resources/static/LOG_Temp.db'\n if tname:\n self.TABLE_NAME = tname\n else:\n self.TABLE_NAME = \"'LOG_RETURNS'\"\n\n def query_data(self, conditions, entries):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n condition_order = ['logID', 'returnType', 'sender',\n 'reciever', 'logTime', 'dutyOfficer', 'net', 'serials']\n cond_list = []\n cond_string_list = []\n for cond in condition_order:\n val = ''\n try:\n val = conditions[cond]\n except KeyError:\n val = ''\n if '|' in val:\n i = 0\n dep = list()\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['other']:\n cond = 'serials'\n val = conditions['other']\n if '|' in val:\n i = 0\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['logTimeFrom']:\n if conditions['logTimeTo']:\n cond_string_list.append('logTime>= ? AND logTime<= ?')\n cond_list.append(conditions['logTimeFrom'])\n cond_list.append(conditions['logTimeTo'])\n else:\n cond_string_list.append('logTime>= ?')\n cond_list.append(conditions['logTimeFrom'])\n elif conditions['logTimeTo']:\n cond_string_list.append('logTime <= ?')\n cond_list.append(conditions['logTimeTo'])\n cond_string = ' AND '.join(cond_string_list)\n print(cond_string)\n print(cond_list)\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} WHERE {cond_string} ORDER BY logID DESC LIMIT {entries}'\n , cond_list)\n return results\n except sqlite3.OperationalError as e:\n print(e)\n\n def create_db(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE {self.TABLE_NAME} (\n `logID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `returnType`\ttext,\n `sender`\ttext,\n `reciever`\ttext,\n `logTime`\tinteger,\n `dutyOfficer`\ttext,\n `net`\tTEXT,\n `serials`\ttext\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n <mask token>\n <mask token>\n\n def new_return(self, lst):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute('INSERT INTO ' + self.TABLE_NAME +\n ' VALUES (NULL,' + '?, ' * (len(lst) - 1) + '?)', lst)\n except sqlite3.OperationalError as e:\n print(e)\n \"\"\"\n if 'no such table' in str(e):\n if \"game\" in str(self.FILE_NAME):\n print(\"MEME\")\n self.create_game_table()\n else:\n self.create_db()\n self.new_return(lst)\n \"\"\"\n <mask token>\n\n def read_return(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}'\n )\n else:\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME}')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_db(self)\n <mask token>\n\n def find_index(self, log_id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n sql_str = 'SELECT * FROM ' + self.TABLE_NAME + ' WHERE logID=?'\n x = c.execute(sql_str, [str(log_id)])\n return x\n <mask token>\n\n def update_record(self, lst, logID):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n rowData = (\n 'returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?'\n )\n c.execute('UPDATE ' + self.TABLE_NAME + ' SET ' + rowData +\n ' WHERE logID=' + logID, lst)\n\n\nclass File:\n\n @staticmethod\n def db_connect(sets):\n try:\n fname = sets['DB_FILE_NAME']\n except KeyError:\n fname = None\n try:\n tname = sets['DB_TABLE_NAME']\n except KeyError:\n tname = None\n conn = DbManager(fname=fname, tname=tname)\n return conn\n\n @staticmethod\n def generate_css_min():\n MinifyFilesPre.min_css_file('resources/static/styles/main.css')\n\n @staticmethod\n def pre_merge(merge=False):\n if merge:\n tmp_file = MinifyFilesPre()\n tmp_file.js_merge()\n tmp_file.save()\n else:\n MinifyFilesPre.get_js_files()\n\n @staticmethod\n def get_first(self):\n return self.get_first_index()\n\n @staticmethod\n def save_dic(dic):\n \"\"\" Saves the given dictionary of serials to a file \"\"\"\n json.dump(dic, open('resources/files/serials.csv', 'w'))\n\n @staticmethod\n def read_dic():\n \"\"\" reads the dictionary of serials \"\"\"\n dic = OrdDic()\n dic.update(json.load(open('resources/files/serials.csv', 'r')))\n return dic\n\n @staticmethod\n def read_legacy():\n \"\"\" Depreciated reads the dictionary and returns it in the legacy format \"\"\"\n serials = File.read_dic()\n final_dic = OrdDic()\n for name, dic in serials.items():\n inner_dic = OrdDic()\n for serial in dic:\n inner_dic.update({serial: dic[serial]['desc']})\n final_dic.update({name: inner_dic})\n return final_dic\n\n @staticmethod\n def read_locations():\n \"\"\" reads the file containing the locations \"\"\"\n r = open('resources/files/locations.txt', 'r', newline='\\n')\n locations = r.read().split('\\n')\n return locations\n\n @staticmethod\n def save_Locations(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/locations.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def save_callsigns(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/callsigns.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def read_callsigns():\n \"\"\" reads the file containing the callsigns \"\"\"\n r = open('resources/files/callsigns.txt', 'r', newline='\\n')\n callsigns = r.read().split('\\n')\n return callsigns\n\n @staticmethod\n def read_settings():\n \"\"\" reads the settings from file \"\"\"\n settings = OrdDic()\n settings.update(json.load(open('resources/files/settings.txt', 'r')))\n return settings\n\n @staticmethod\n def save_settings(dic):\n \"\"\" saves the given settings (dictionary) to file \"\"\"\n json.dump(dic, open('resources/files/settings.txt', 'w'))\n\n @staticmethod\n def save_log(self, log, update=False):\n \"\"\" Saves the log to file \"\"\"\n main_keys = ['name', 'sender', 'receiver', 'time', 'duty', 'net']\n lst = []\n for key in main_keys:\n lst.append(log[key])\n log.pop(key)\n lst.append(json.dumps(log))\n if update:\n self.update_record(lst, log['logID'])\n else:\n self.new_return(lst)\n\n @staticmethod\n def load_log_query(Db, query):\n x = list(Db.query_data(query, 100))\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': row[4]})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def load_log(Db, log_id=None):\n \"\"\" loads the log file \"\"\"\n if log_id:\n row = Db.find_index(log_id).fetchone()\n local_log = list()\n ret = None\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n except TypeError:\n pass\n return ret\n else:\n try:\n x = list(Db.read_return(entries=100))\n except TypeError:\n x = ''\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def delete_log_byID(Db, id):\n Db.delete_return_byID(id)\n\n\n<mask token>\n\n\nclass SaveTimer(object):\n\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass MinifyFilesPre:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass DbManager:\n\n def __init__(self, fname=None, tname=None):\n if fname:\n self.FILE_NAME = fname\n else:\n self.FILE_NAME = 'resources/static/LOG_Temp.db'\n if tname:\n self.TABLE_NAME = tname\n else:\n self.TABLE_NAME = \"'LOG_RETURNS'\"\n\n def query_data(self, conditions, entries):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n condition_order = ['logID', 'returnType', 'sender',\n 'reciever', 'logTime', 'dutyOfficer', 'net', 'serials']\n cond_list = []\n cond_string_list = []\n for cond in condition_order:\n val = ''\n try:\n val = conditions[cond]\n except KeyError:\n val = ''\n if '|' in val:\n i = 0\n dep = list()\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['other']:\n cond = 'serials'\n val = conditions['other']\n if '|' in val:\n i = 0\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['logTimeFrom']:\n if conditions['logTimeTo']:\n cond_string_list.append('logTime>= ? AND logTime<= ?')\n cond_list.append(conditions['logTimeFrom'])\n cond_list.append(conditions['logTimeTo'])\n else:\n cond_string_list.append('logTime>= ?')\n cond_list.append(conditions['logTimeFrom'])\n elif conditions['logTimeTo']:\n cond_string_list.append('logTime <= ?')\n cond_list.append(conditions['logTimeTo'])\n cond_string = ' AND '.join(cond_string_list)\n print(cond_string)\n print(cond_list)\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} WHERE {cond_string} ORDER BY logID DESC LIMIT {entries}'\n , cond_list)\n return results\n except sqlite3.OperationalError as e:\n print(e)\n\n def create_db(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE {self.TABLE_NAME} (\n `logID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `returnType`\ttext,\n `sender`\ttext,\n `reciever`\ttext,\n `logTime`\tinteger,\n `dutyOfficer`\ttext,\n `net`\tTEXT,\n `serials`\ttext\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def count_records(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n results = c.execute(f\"SELECT COUNT('LogID') FROM {self.TABLE_NAME}\"\n )\n return results\n\n def create_game_table(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE `{self.TABLE_NAME}` (\n `GameID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Name`\tTEXT DEFAULT '?',\n `Rank`\tTEXT DEFAULT '?',\n `Pl`\tTEXT DEFAULT '?',\n `Score`\tINTEGER DEFAULT 0,\n `Time`\tINTEGER\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def new_return(self, lst):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute('INSERT INTO ' + self.TABLE_NAME +\n ' VALUES (NULL,' + '?, ' * (len(lst) - 1) + '?)', lst)\n except sqlite3.OperationalError as e:\n print(e)\n \"\"\"\n if 'no such table' in str(e):\n if \"game\" in str(self.FILE_NAME):\n print(\"MEME\")\n self.create_game_table()\n else:\n self.create_db()\n self.new_return(lst)\n \"\"\"\n\n def delete_return_byID(self, id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute(f'DELETE FROM {self.TABLE_NAME} WHERE logID = {id}')\n\n def read_return(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}'\n )\n else:\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME}')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_db(self)\n\n def read_game_score(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC LIMIT {entries}'\n )\n else:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_game_table(self)\n\n def find_index(self, log_id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n sql_str = 'SELECT * FROM ' + self.TABLE_NAME + ' WHERE logID=?'\n x = c.execute(sql_str, [str(log_id)])\n return x\n\n def get_first_index(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n i = ''\n c = conn.cursor()\n sqlStr = ('SELECT logID FROM ' + self.TABLE_NAME +\n ' WHERE logID = (SELECT MAX(logID) FROM ' + self.\n TABLE_NAME + ')')\n x = c.execute(sqlStr)\n for i in x:\n i = int(list(i)[0])\n try:\n return i\n except UnboundLocalError:\n return ''\n\n def update_record(self, lst, logID):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n rowData = (\n 'returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?'\n )\n c.execute('UPDATE ' + self.TABLE_NAME + ' SET ' + rowData +\n ' WHERE logID=' + logID, lst)\n\n\nclass File:\n\n @staticmethod\n def db_connect(sets):\n try:\n fname = sets['DB_FILE_NAME']\n except KeyError:\n fname = None\n try:\n tname = sets['DB_TABLE_NAME']\n except KeyError:\n tname = None\n conn = DbManager(fname=fname, tname=tname)\n return conn\n\n @staticmethod\n def generate_css_min():\n MinifyFilesPre.min_css_file('resources/static/styles/main.css')\n\n @staticmethod\n def pre_merge(merge=False):\n if merge:\n tmp_file = MinifyFilesPre()\n tmp_file.js_merge()\n tmp_file.save()\n else:\n MinifyFilesPre.get_js_files()\n\n @staticmethod\n def get_first(self):\n return self.get_first_index()\n\n @staticmethod\n def save_dic(dic):\n \"\"\" Saves the given dictionary of serials to a file \"\"\"\n json.dump(dic, open('resources/files/serials.csv', 'w'))\n\n @staticmethod\n def read_dic():\n \"\"\" reads the dictionary of serials \"\"\"\n dic = OrdDic()\n dic.update(json.load(open('resources/files/serials.csv', 'r')))\n return dic\n\n @staticmethod\n def read_legacy():\n \"\"\" Depreciated reads the dictionary and returns it in the legacy format \"\"\"\n serials = File.read_dic()\n final_dic = OrdDic()\n for name, dic in serials.items():\n inner_dic = OrdDic()\n for serial in dic:\n inner_dic.update({serial: dic[serial]['desc']})\n final_dic.update({name: inner_dic})\n return final_dic\n\n @staticmethod\n def read_locations():\n \"\"\" reads the file containing the locations \"\"\"\n r = open('resources/files/locations.txt', 'r', newline='\\n')\n locations = r.read().split('\\n')\n return locations\n\n @staticmethod\n def save_Locations(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/locations.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def save_callsigns(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/callsigns.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def read_callsigns():\n \"\"\" reads the file containing the callsigns \"\"\"\n r = open('resources/files/callsigns.txt', 'r', newline='\\n')\n callsigns = r.read().split('\\n')\n return callsigns\n\n @staticmethod\n def read_settings():\n \"\"\" reads the settings from file \"\"\"\n settings = OrdDic()\n settings.update(json.load(open('resources/files/settings.txt', 'r')))\n return settings\n\n @staticmethod\n def save_settings(dic):\n \"\"\" saves the given settings (dictionary) to file \"\"\"\n json.dump(dic, open('resources/files/settings.txt', 'w'))\n\n @staticmethod\n def save_log(self, log, update=False):\n \"\"\" Saves the log to file \"\"\"\n main_keys = ['name', 'sender', 'receiver', 'time', 'duty', 'net']\n lst = []\n for key in main_keys:\n lst.append(log[key])\n log.pop(key)\n lst.append(json.dumps(log))\n if update:\n self.update_record(lst, log['logID'])\n else:\n self.new_return(lst)\n\n @staticmethod\n def load_log_query(Db, query):\n x = list(Db.query_data(query, 100))\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': row[4]})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def load_log(Db, log_id=None):\n \"\"\" loads the log file \"\"\"\n if log_id:\n row = Db.find_index(log_id).fetchone()\n local_log = list()\n ret = None\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n except TypeError:\n pass\n return ret\n else:\n try:\n x = list(Db.read_return(entries=100))\n except TypeError:\n x = ''\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def delete_log_byID(Db, id):\n Db.delete_return_byID(id)\n\n\n<mask token>\n\n\nclass SaveTimer(object):\n\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass MinifyFilesPre:\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def min_js_file(file_name):\n js = jsmin(open(file_name, newline='\\n').read())\n open(file_name, 'w', newline='\\n').write(js)\n\n @staticmethod\n def min_css_file(file_name):\n css = compress(open(file_name, newline='\\n').read())\n open(file_name[:-4] + '.min.css', 'w', newline='\\n').write(css)\n <mask token>\n\n\nclass DbManager:\n\n def __init__(self, fname=None, tname=None):\n if fname:\n self.FILE_NAME = fname\n else:\n self.FILE_NAME = 'resources/static/LOG_Temp.db'\n if tname:\n self.TABLE_NAME = tname\n else:\n self.TABLE_NAME = \"'LOG_RETURNS'\"\n\n def query_data(self, conditions, entries):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n condition_order = ['logID', 'returnType', 'sender',\n 'reciever', 'logTime', 'dutyOfficer', 'net', 'serials']\n cond_list = []\n cond_string_list = []\n for cond in condition_order:\n val = ''\n try:\n val = conditions[cond]\n except KeyError:\n val = ''\n if '|' in val:\n i = 0\n dep = list()\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['other']:\n cond = 'serials'\n val = conditions['other']\n if '|' in val:\n i = 0\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['logTimeFrom']:\n if conditions['logTimeTo']:\n cond_string_list.append('logTime>= ? AND logTime<= ?')\n cond_list.append(conditions['logTimeFrom'])\n cond_list.append(conditions['logTimeTo'])\n else:\n cond_string_list.append('logTime>= ?')\n cond_list.append(conditions['logTimeFrom'])\n elif conditions['logTimeTo']:\n cond_string_list.append('logTime <= ?')\n cond_list.append(conditions['logTimeTo'])\n cond_string = ' AND '.join(cond_string_list)\n print(cond_string)\n print(cond_list)\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} WHERE {cond_string} ORDER BY logID DESC LIMIT {entries}'\n , cond_list)\n return results\n except sqlite3.OperationalError as e:\n print(e)\n\n def create_db(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE {self.TABLE_NAME} (\n `logID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `returnType`\ttext,\n `sender`\ttext,\n `reciever`\ttext,\n `logTime`\tinteger,\n `dutyOfficer`\ttext,\n `net`\tTEXT,\n `serials`\ttext\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def count_records(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n results = c.execute(f\"SELECT COUNT('LogID') FROM {self.TABLE_NAME}\"\n )\n return results\n\n def create_game_table(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE `{self.TABLE_NAME}` (\n `GameID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Name`\tTEXT DEFAULT '?',\n `Rank`\tTEXT DEFAULT '?',\n `Pl`\tTEXT DEFAULT '?',\n `Score`\tINTEGER DEFAULT 0,\n `Time`\tINTEGER\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def new_return(self, lst):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute('INSERT INTO ' + self.TABLE_NAME +\n ' VALUES (NULL,' + '?, ' * (len(lst) - 1) + '?)', lst)\n except sqlite3.OperationalError as e:\n print(e)\n \"\"\"\n if 'no such table' in str(e):\n if \"game\" in str(self.FILE_NAME):\n print(\"MEME\")\n self.create_game_table()\n else:\n self.create_db()\n self.new_return(lst)\n \"\"\"\n\n def delete_return_byID(self, id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute(f'DELETE FROM {self.TABLE_NAME} WHERE logID = {id}')\n\n def read_return(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}'\n )\n else:\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME}')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_db(self)\n\n def read_game_score(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC LIMIT {entries}'\n )\n else:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_game_table(self)\n\n def find_index(self, log_id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n sql_str = 'SELECT * FROM ' + self.TABLE_NAME + ' WHERE logID=?'\n x = c.execute(sql_str, [str(log_id)])\n return x\n\n def get_first_index(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n i = ''\n c = conn.cursor()\n sqlStr = ('SELECT logID FROM ' + self.TABLE_NAME +\n ' WHERE logID = (SELECT MAX(logID) FROM ' + self.\n TABLE_NAME + ')')\n x = c.execute(sqlStr)\n for i in x:\n i = int(list(i)[0])\n try:\n return i\n except UnboundLocalError:\n return ''\n\n def update_record(self, lst, logID):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n rowData = (\n 'returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?'\n )\n c.execute('UPDATE ' + self.TABLE_NAME + ' SET ' + rowData +\n ' WHERE logID=' + logID, lst)\n\n\nclass File:\n\n @staticmethod\n def db_connect(sets):\n try:\n fname = sets['DB_FILE_NAME']\n except KeyError:\n fname = None\n try:\n tname = sets['DB_TABLE_NAME']\n except KeyError:\n tname = None\n conn = DbManager(fname=fname, tname=tname)\n return conn\n\n @staticmethod\n def generate_css_min():\n MinifyFilesPre.min_css_file('resources/static/styles/main.css')\n\n @staticmethod\n def pre_merge(merge=False):\n if merge:\n tmp_file = MinifyFilesPre()\n tmp_file.js_merge()\n tmp_file.save()\n else:\n MinifyFilesPre.get_js_files()\n\n @staticmethod\n def get_first(self):\n return self.get_first_index()\n\n @staticmethod\n def save_dic(dic):\n \"\"\" Saves the given dictionary of serials to a file \"\"\"\n json.dump(dic, open('resources/files/serials.csv', 'w'))\n\n @staticmethod\n def read_dic():\n \"\"\" reads the dictionary of serials \"\"\"\n dic = OrdDic()\n dic.update(json.load(open('resources/files/serials.csv', 'r')))\n return dic\n\n @staticmethod\n def read_legacy():\n \"\"\" Depreciated reads the dictionary and returns it in the legacy format \"\"\"\n serials = File.read_dic()\n final_dic = OrdDic()\n for name, dic in serials.items():\n inner_dic = OrdDic()\n for serial in dic:\n inner_dic.update({serial: dic[serial]['desc']})\n final_dic.update({name: inner_dic})\n return final_dic\n\n @staticmethod\n def read_locations():\n \"\"\" reads the file containing the locations \"\"\"\n r = open('resources/files/locations.txt', 'r', newline='\\n')\n locations = r.read().split('\\n')\n return locations\n\n @staticmethod\n def save_Locations(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/locations.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def save_callsigns(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/callsigns.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def read_callsigns():\n \"\"\" reads the file containing the callsigns \"\"\"\n r = open('resources/files/callsigns.txt', 'r', newline='\\n')\n callsigns = r.read().split('\\n')\n return callsigns\n\n @staticmethod\n def read_settings():\n \"\"\" reads the settings from file \"\"\"\n settings = OrdDic()\n settings.update(json.load(open('resources/files/settings.txt', 'r')))\n return settings\n\n @staticmethod\n def save_settings(dic):\n \"\"\" saves the given settings (dictionary) to file \"\"\"\n json.dump(dic, open('resources/files/settings.txt', 'w'))\n\n @staticmethod\n def save_log(self, log, update=False):\n \"\"\" Saves the log to file \"\"\"\n main_keys = ['name', 'sender', 'receiver', 'time', 'duty', 'net']\n lst = []\n for key in main_keys:\n lst.append(log[key])\n log.pop(key)\n lst.append(json.dumps(log))\n if update:\n self.update_record(lst, log['logID'])\n else:\n self.new_return(lst)\n\n @staticmethod\n def load_log_query(Db, query):\n x = list(Db.query_data(query, 100))\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': row[4]})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def load_log(Db, log_id=None):\n \"\"\" loads the log file \"\"\"\n if log_id:\n row = Db.find_index(log_id).fetchone()\n local_log = list()\n ret = None\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n except TypeError:\n pass\n return ret\n else:\n try:\n x = list(Db.read_return(entries=100))\n except TypeError:\n x = ''\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def delete_log_byID(Db, id):\n Db.delete_return_byID(id)\n\n\n<mask token>\n\n\nclass SaveTimer(object):\n\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass MinifyFilesPre:\n\n def __init__(self, merge=False):\n file_names = glob('resources/static/js_files/*.js')\n file_names.remove('resources/static/js_files/full_version.js')\n self.file_names = file_names\n self.merge = merge\n self.js = ''\n\n def save(self):\n \"\"\"combines several js files together, with optional minification\"\"\"\n with open('resources/static/js_files/full_version.js', 'w', newline\n ='\\n') as w:\n w.write(self.js)\n\n def js_merge(self):\n \"\"\"saves minified version to a single one\"\"\"\n if self.merge:\n js = ''\n for file_name in self.file_names:\n try:\n js += jsmin(open(file_name, newline='\\n').read())\n except FileNotFoundError:\n print(f'The file {file_name} could not be found')\n self.js = jsmin(js)\n else:\n for file_name in self.file_names:\n js = jsmin(open(file_name, newline='\\n').read())\n open(file_name, 'w', newline='\\n').write(js)\n\n @staticmethod\n def min_js_file(file_name):\n js = jsmin(open(file_name, newline='\\n').read())\n open(file_name, 'w', newline='\\n').write(js)\n\n @staticmethod\n def min_css_file(file_name):\n css = compress(open(file_name, newline='\\n').read())\n open(file_name[:-4] + '.min.css', 'w', newline='\\n').write(css)\n\n @staticmethod\n def get_js_files():\n file_names = glob('resources/static/js_files/*.js')\n file_names.remove('resources/static/js_files/full_version.js')\n\n\nclass DbManager:\n\n def __init__(self, fname=None, tname=None):\n if fname:\n self.FILE_NAME = fname\n else:\n self.FILE_NAME = 'resources/static/LOG_Temp.db'\n if tname:\n self.TABLE_NAME = tname\n else:\n self.TABLE_NAME = \"'LOG_RETURNS'\"\n\n def query_data(self, conditions, entries):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n condition_order = ['logID', 'returnType', 'sender',\n 'reciever', 'logTime', 'dutyOfficer', 'net', 'serials']\n cond_list = []\n cond_string_list = []\n for cond in condition_order:\n val = ''\n try:\n val = conditions[cond]\n except KeyError:\n val = ''\n if '|' in val:\n i = 0\n dep = list()\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['other']:\n cond = 'serials'\n val = conditions['other']\n if '|' in val:\n i = 0\n for sub_val in val.split('|'):\n i += 1\n cond_list.append(f'%{sub_val}%')\n cond_string_list.append('(' +\n f'lower({cond}) LIKE ?' + \n f' OR lower({cond}) LIKE ?' * (i - 1) + ')')\n else:\n for sub_val in val.split(', '):\n cond_string_list.append(f'lower({cond}) LIKE ?')\n sub_val = f'%{sub_val.lower()}%'\n cond_list.append(sub_val)\n if conditions['logTimeFrom']:\n if conditions['logTimeTo']:\n cond_string_list.append('logTime>= ? AND logTime<= ?')\n cond_list.append(conditions['logTimeFrom'])\n cond_list.append(conditions['logTimeTo'])\n else:\n cond_string_list.append('logTime>= ?')\n cond_list.append(conditions['logTimeFrom'])\n elif conditions['logTimeTo']:\n cond_string_list.append('logTime <= ?')\n cond_list.append(conditions['logTimeTo'])\n cond_string = ' AND '.join(cond_string_list)\n print(cond_string)\n print(cond_list)\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} WHERE {cond_string} ORDER BY logID DESC LIMIT {entries}'\n , cond_list)\n return results\n except sqlite3.OperationalError as e:\n print(e)\n\n def create_db(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE {self.TABLE_NAME} (\n `logID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `returnType`\ttext,\n `sender`\ttext,\n `reciever`\ttext,\n `logTime`\tinteger,\n `dutyOfficer`\ttext,\n `net`\tTEXT,\n `serials`\ttext\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def count_records(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n results = c.execute(f\"SELECT COUNT('LogID') FROM {self.TABLE_NAME}\"\n )\n return results\n\n def create_game_table(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n try:\n c.execute(\n f\"\"\"CREATE TABLE `{self.TABLE_NAME}` (\n `GameID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Name`\tTEXT DEFAULT '?',\n `Rank`\tTEXT DEFAULT '?',\n `Pl`\tTEXT DEFAULT '?',\n `Score`\tINTEGER DEFAULT 0,\n `Time`\tINTEGER\n );\"\"\"\n )\n conn.commit()\n except sqlite3.OperationalError:\n print('The Db already exists')\n if ret:\n return self.read_return()\n\n def new_return(self, lst):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute('INSERT INTO ' + self.TABLE_NAME +\n ' VALUES (NULL,' + '?, ' * (len(lst) - 1) + '?)', lst)\n except sqlite3.OperationalError as e:\n print(e)\n \"\"\"\n if 'no such table' in str(e):\n if \"game\" in str(self.FILE_NAME):\n print(\"MEME\")\n self.create_game_table()\n else:\n self.create_db()\n self.new_return(lst)\n \"\"\"\n\n def delete_return_byID(self, id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute(f'DELETE FROM {self.TABLE_NAME} WHERE logID = {id}')\n\n def read_return(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}'\n )\n else:\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME}')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_db(self)\n\n def read_game_score(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC LIMIT {entries}'\n )\n else:\n results = c.execute(\n f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC')\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_game_table(self)\n\n def find_index(self, log_id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n sql_str = 'SELECT * FROM ' + self.TABLE_NAME + ' WHERE logID=?'\n x = c.execute(sql_str, [str(log_id)])\n return x\n\n def get_first_index(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n i = ''\n c = conn.cursor()\n sqlStr = ('SELECT logID FROM ' + self.TABLE_NAME +\n ' WHERE logID = (SELECT MAX(logID) FROM ' + self.\n TABLE_NAME + ')')\n x = c.execute(sqlStr)\n for i in x:\n i = int(list(i)[0])\n try:\n return i\n except UnboundLocalError:\n return ''\n\n def update_record(self, lst, logID):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n rowData = (\n 'returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?'\n )\n c.execute('UPDATE ' + self.TABLE_NAME + ' SET ' + rowData +\n ' WHERE logID=' + logID, lst)\n\n\nclass File:\n\n @staticmethod\n def db_connect(sets):\n try:\n fname = sets['DB_FILE_NAME']\n except KeyError:\n fname = None\n try:\n tname = sets['DB_TABLE_NAME']\n except KeyError:\n tname = None\n conn = DbManager(fname=fname, tname=tname)\n return conn\n\n @staticmethod\n def generate_css_min():\n MinifyFilesPre.min_css_file('resources/static/styles/main.css')\n\n @staticmethod\n def pre_merge(merge=False):\n if merge:\n tmp_file = MinifyFilesPre()\n tmp_file.js_merge()\n tmp_file.save()\n else:\n MinifyFilesPre.get_js_files()\n\n @staticmethod\n def get_first(self):\n return self.get_first_index()\n\n @staticmethod\n def save_dic(dic):\n \"\"\" Saves the given dictionary of serials to a file \"\"\"\n json.dump(dic, open('resources/files/serials.csv', 'w'))\n\n @staticmethod\n def read_dic():\n \"\"\" reads the dictionary of serials \"\"\"\n dic = OrdDic()\n dic.update(json.load(open('resources/files/serials.csv', 'r')))\n return dic\n\n @staticmethod\n def read_legacy():\n \"\"\" Depreciated reads the dictionary and returns it in the legacy format \"\"\"\n serials = File.read_dic()\n final_dic = OrdDic()\n for name, dic in serials.items():\n inner_dic = OrdDic()\n for serial in dic:\n inner_dic.update({serial: dic[serial]['desc']})\n final_dic.update({name: inner_dic})\n return final_dic\n\n @staticmethod\n def read_locations():\n \"\"\" reads the file containing the locations \"\"\"\n r = open('resources/files/locations.txt', 'r', newline='\\n')\n locations = r.read().split('\\n')\n return locations\n\n @staticmethod\n def save_Locations(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/locations.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def save_callsigns(lst):\n lst = '\\n'.join(lst)\n w = open('resources/files/callsigns.txt', 'w', newline='\\n')\n w.write(lst)\n\n @staticmethod\n def read_callsigns():\n \"\"\" reads the file containing the callsigns \"\"\"\n r = open('resources/files/callsigns.txt', 'r', newline='\\n')\n callsigns = r.read().split('\\n')\n return callsigns\n\n @staticmethod\n def read_settings():\n \"\"\" reads the settings from file \"\"\"\n settings = OrdDic()\n settings.update(json.load(open('resources/files/settings.txt', 'r')))\n return settings\n\n @staticmethod\n def save_settings(dic):\n \"\"\" saves the given settings (dictionary) to file \"\"\"\n json.dump(dic, open('resources/files/settings.txt', 'w'))\n\n @staticmethod\n def save_log(self, log, update=False):\n \"\"\" Saves the log to file \"\"\"\n main_keys = ['name', 'sender', 'receiver', 'time', 'duty', 'net']\n lst = []\n for key in main_keys:\n lst.append(log[key])\n log.pop(key)\n lst.append(json.dumps(log))\n if update:\n self.update_record(lst, log['logID'])\n else:\n self.new_return(lst)\n\n @staticmethod\n def load_log_query(Db, query):\n x = list(Db.query_data(query, 100))\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': row[4]})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def load_log(Db, log_id=None):\n \"\"\" loads the log file \"\"\"\n if log_id:\n row = Db.find_index(log_id).fetchone()\n local_log = list()\n ret = None\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n except TypeError:\n pass\n return ret\n else:\n try:\n x = list(Db.read_return(entries=100))\n except TypeError:\n x = ''\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n ret.update(json.loads(row[7]))\n local_log.append(ret)\n except TypeError:\n print('none value in db')\n return local_log\n\n @staticmethod\n def delete_log_byID(Db, id):\n Db.delete_return_byID(id)\n\n\ndef fix_time(dtg):\n if len(str(dtg)) == 6:\n return str(dtg)\n else:\n return str(f'0{dtg}')\n\n\nclass SaveTimer(object):\n\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\n\n<mask token>\n", "step-5": "from csv import reader, writer\nfrom collections import OrderedDict as OrdDic\nimport sqlite3\nfrom jsmin import jsmin\nfrom glob import glob\nfrom csscompressor import compress\nfrom threading import Timer\nfrom glob import glob\nimport os\nimport shutil\nimport logging\nimport json\n\nclass MinifyFilesPre:\n def __init__(self, merge=False):\n\n file_names = glob(\"resources/static/js_files/*.js\")\n file_names.remove(\"resources/static/js_files/full_version.js\")\n self.file_names = file_names\n self.merge = merge\n self.js = \"\"\n\n def save(self):\n \"\"\"combines several js files together, with optional minification\"\"\"\n with open(\"resources/static/js_files/full_version.js\", 'w', newline=\"\\n\") as w:\n w.write(self.js)\n\n def js_merge(self):\n \"\"\"saves minified version to a single one\"\"\"\n if self.merge:\n js = \"\"\n for file_name in self.file_names:\n try:\n js += jsmin(open(file_name, newline=\"\\n\").read())\n except FileNotFoundError:\n print(f\"The file {file_name} could not be found\")\n self.js = jsmin(js)\n\n else:\n for file_name in self.file_names:\n js = jsmin(open(file_name, newline=\"\\n\").read())\n open(file_name, 'w', newline=\"\\n\").write(js)\n\n @staticmethod\n def min_js_file(file_name):\n js = jsmin(open(file_name, newline=\"\\n\").read())\n open(file_name, 'w', newline=\"\\n\").write(js)\n\n @staticmethod\n def min_css_file(file_name):\n css = compress(open(file_name, newline=\"\\n\").read())\n open(file_name[:-4] + '.min.css', 'w', newline=\"\\n\").write(css)\n\n @staticmethod\n def get_js_files():\n file_names = glob(\"resources/static/js_files/*.js\")\n file_names.remove(\"resources/static/js_files/full_version.js\")\n\n\nclass DbManager:\n\n def __init__(self, fname=None, tname=None):\n if fname:\n self.FILE_NAME = fname\n else:\n self.FILE_NAME = 'resources/static/LOG_Temp.db'\n\n if tname:\n self.TABLE_NAME = tname\n else:\n self.TABLE_NAME = \"'LOG_RETURNS'\"\n\n\n def query_data(self, conditions, entries):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n condition_order = ['logID',\n 'returnType',\n 'sender',\n 'reciever',\n 'logTime',\n 'dutyOfficer',\n 'net',\n 'serials']\n\n cond_list = []\n cond_string_list = []\n for cond in condition_order:\n val = \"\"\n try:\n val = conditions[cond]\n except KeyError:\n val = \"\"\n\n\n if \"|\" in val:\n i = 0\n dep = list()\n for sub_val in val.split(\"|\"):\n i+=1\n cond_list.append(f\"%{sub_val}%\")\n\n cond_string_list.append(\"(\"+f\"lower({cond}) LIKE ?\"+ f\" OR lower({cond}) LIKE ?\"*(i-1)+\")\")\n\n else:\n for sub_val in val.split(\", \"):\n cond_string_list.append(f\"lower({cond}) LIKE ?\")\n sub_val = f\"%{sub_val.lower()}%\"\n cond_list.append(sub_val)\n\n\n if conditions['other']:\n cond = \"serials\"\n val = conditions['other']\n if \"|\" in val:\n i = 0\n for sub_val in val.split(\"|\"):\n i+=1\n cond_list.append(f\"%{sub_val}%\")\n\n cond_string_list.append(\"(\"+f\"lower({cond}) LIKE ?\"+ f\" OR lower({cond}) LIKE ?\"*(i-1)+\")\")\n\n else:\n for sub_val in val.split(\", \"):\n cond_string_list.append(f\"lower({cond}) LIKE ?\")\n sub_val = f\"%{sub_val.lower()}%\"\n cond_list.append(sub_val)\n\n if conditions['logTimeFrom']:\n if conditions['logTimeTo']:\n cond_string_list.append(\"logTime>= ? AND logTime<= ?\")\n cond_list.append(conditions['logTimeFrom'])\n cond_list.append(conditions['logTimeTo'])\n else:\n cond_string_list.append(\"logTime>= ?\")\n cond_list.append(conditions['logTimeFrom'])\n elif conditions['logTimeTo']:\n cond_string_list.append(\"logTime <= ?\")\n cond_list.append(conditions['logTimeTo'])\n\n cond_string = ' AND '.join(cond_string_list)\n\n print(cond_string)\n print(cond_list)\n\n results = c.execute(f\"SELECT * FROM {self.TABLE_NAME} WHERE \"\n f\"{cond_string}\"\n f\" ORDER BY logID DESC LIMIT {entries}\", cond_list)\n return results\n\n except sqlite3.OperationalError as e:\n print(e)\n\n def create_db(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n # Create table\n try:\n c.execute(f'''CREATE TABLE {self.TABLE_NAME} (\n `logID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `returnType`\ttext,\n `sender`\ttext,\n `reciever`\ttext,\n `logTime`\tinteger,\n `dutyOfficer`\ttext,\n `net`\tTEXT,\n `serials`\ttext\n );''')\n\n conn.commit()\n\n except sqlite3.OperationalError:\n print(\"The Db already exists\")\n\n if ret:\n return self.read_return()\n\n def count_records(self):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n results = c.execute(f\"SELECT COUNT('LogID') FROM {self.TABLE_NAME}\")\n return results\n\n\n def create_game_table(self, ret=False):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n # Create table\n try:\n c.execute(f'''CREATE TABLE `{self.TABLE_NAME}` (\n `GameID`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,\n `Name`\tTEXT DEFAULT '?',\n `Rank`\tTEXT DEFAULT '?',\n `Pl`\tTEXT DEFAULT '?',\n `Score`\tINTEGER DEFAULT 0,\n `Time`\tINTEGER\n );''')\n\n conn.commit()\n\n except sqlite3.OperationalError:\n print(\"The Db already exists\")\n\n if ret:\n return self.read_return()\n\n\n def new_return(self, lst):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute(\n 'INSERT INTO ' + self.TABLE_NAME + ' VALUES (NULL,' +\n '?, ' * (len(lst) - 1) + '?)',\n lst)\n except sqlite3.OperationalError as e:\n print(e)\n \"\"\"\n if 'no such table' in str(e):\n if \"game\" in str(self.FILE_NAME):\n print(\"MEME\")\n self.create_game_table()\n else:\n self.create_db()\n self.new_return(lst)\n \"\"\"\n\n\n def delete_return_byID(self, id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n c.execute(f\"DELETE FROM {self.TABLE_NAME} WHERE logID = {id}\")\n\n\n def read_return(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(f\"SELECT * FROM {self.TABLE_NAME} ORDER BY logID DESC LIMIT {entries}\")\n else:\n # should not be used but just here just in case\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME}')\n\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_db(self)\n\n def read_game_score(self, entries=None):\n try:\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n if entries:\n results = c.execute(f\"SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC LIMIT {entries}\")\n else:\n # should not be used but just here just in case\n results = c.execute(f'SELECT * FROM {self.TABLE_NAME} ORDER BY Score DESC')\n\n return results\n except sqlite3.OperationalError as e:\n if 'no such table' in str(e):\n DbManager.create_game_table(self)\n\n\n def find_index(self, log_id):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n sql_str = (\"\"\"SELECT * FROM \"\"\" +\n self.TABLE_NAME +\n \"\"\" WHERE logID=?\"\"\")\n x = c.execute(sql_str, [str(log_id)])\n return x\n\n\n def get_first_index(self):\n\n with sqlite3.connect(self.FILE_NAME) as conn:\n i=\"\"\n c = conn.cursor()\n sqlStr = (\"\"\"SELECT logID FROM \"\"\" +\n self.TABLE_NAME +\n \"\"\" WHERE logID = (SELECT MAX(logID) FROM \"\"\" +\n self.TABLE_NAME + \")\")\n x = c.execute(sqlStr)\n for i in x:\n i = int(list(i)[0])\n try:\n return i\n except UnboundLocalError:\n return \"\"\n\n def update_record(self, lst, logID):\n with sqlite3.connect(self.FILE_NAME) as conn:\n c = conn.cursor()\n rowData = \"\"\"returnType=?, sender=?, reciever=?, logTime=?, dutyOfficer=?, net=?, serials=?\"\"\"\n c.execute(\n 'UPDATE ' + self.TABLE_NAME + ' SET ' + rowData + ' WHERE logID=' + logID,\n lst)\n\n\nclass File:\n\n @staticmethod\n def db_connect(sets):\n try:\n fname = sets['DB_FILE_NAME']\n except KeyError:\n fname = None\n\n try:\n tname = sets['DB_TABLE_NAME']\n except KeyError:\n tname = None\n\n conn = DbManager(fname=fname, tname=tname)\n return conn\n\n\n @staticmethod\n def generate_css_min():\n MinifyFilesPre.min_css_file('resources/static/styles/main.css')\n\n @staticmethod\n def pre_merge(merge=False):\n\n if merge:\n tmp_file = MinifyFilesPre()\n tmp_file.js_merge()\n tmp_file.save()\n else:\n MinifyFilesPre.get_js_files()\n\n @staticmethod\n def get_first(self):\n return self.get_first_index()\n\n @staticmethod\n def save_dic(dic):\n \"\"\" Saves the given dictionary of serials to a file \"\"\"\n json.dump(dic, open(\"resources/files/serials.csv\", \"w\"))\n\n\n # w = writer(open(\"resources/files/serials.csv\", \"w\", newline=\"\\n\"))\n # w.writerow(['Return Name', 'Serials'])\n # for name, serials in dic.items():\n # lst = []\n # if name == \"Return Name\":\n # lst.append(name)\n # lst.append(serials)\n # else:\n # for serial in serials:\n # if serial == \"Return Name\":\n # lst.append(serials)\n # else:\n # inner_lst = []\n # for cont in serials[serial]:\n # if cont == \"options\":\n # inner_lst.append(cont + \";;@@;;\" +\n # \";;##;;\".join(\n # serials\n # [serial]\n # [\"options\"]))\n # else:\n # inner_lst.append(\n # cont + \";;@@;;\" + serials[serial][cont])\n # lst.append(serial + ';;:::;;' + \";;!!!;;\".join(inner_lst))\n # w.writerow([(name), (';;,,,;;'.join(lst))])\n\n @staticmethod\n def read_dic():\n \"\"\" reads the dictionary of serials \"\"\"\n # should return the original format\n dic = OrdDic()\n dic.update(json.load(open(\"resources/files/serials.csv\", \"r\")))\n\n\n # OLD CODE\n # logging.log(logging.INFO, \"File path: \"+os.path.realpath(__file__))\n # r = reader(open(\"resources/files/serials.csv\", \"r\", newline=\"\\n\"))\n # i = 0\n # for row in r:\n # if i:\n # inner_dic = OrdDic()\n # for serial in row[1].split(';;,,,;;'):\n # serial = serial.split(';;:::;;')\n # sub_dic = OrdDic()\n # for sub_serial in serial[1].split(';;!!!;;'):\n # sub_serial = sub_serial.split(\";;@@;;\")\n # if sub_serial[0] == 'options':\n # options = sub_serial[1].split(\";;##;;\")\n # sub_dic.update({sub_serial[0]: options})\n # else:\n # sub_dic.update(\n # {sub_serial[0]: sub_serial[1]})\n # inner_dic.update({serial[0]: sub_dic})\n # # lst = row[1].split('\\\\')\n # dic.update({row[0]: inner_dic})\n # else:\n # i += 1\n # # print(\" * Read Dictionary\")\n return dic\n\n @staticmethod\n def read_legacy():\n \"\"\" Depreciated reads the dictionary and returns it in the legacy format \"\"\"\n serials = File.read_dic()\n final_dic = OrdDic()\n for name, dic in serials.items():\n inner_dic = OrdDic()\n for serial in dic:\n inner_dic.update({serial: dic[serial]['desc']})\n final_dic.update({name: inner_dic})\n return final_dic\n\n @staticmethod\n def read_locations():\n \"\"\" reads the file containing the locations \"\"\"\n r = open(\"resources/files/locations.txt\", \"r\", newline=\"\\n\")\n locations = r.read().split(\"\\n\")\n return locations\n\n @staticmethod\n def save_Locations(lst):\n lst = '\\n'.join(lst)\n w = open(\"resources/files/locations.txt\", \"w\", newline=\"\\n\")\n w.write(lst)\n\n @staticmethod\n def save_callsigns(lst):\n lst = '\\n'.join(lst)\n w = open(\"resources/files/callsigns.txt\", \"w\", newline=\"\\n\")\n w.write(lst)\n\n @staticmethod\n def read_callsigns():\n \"\"\" reads the file containing the callsigns \"\"\"\n r = open(\"resources/files/callsigns.txt\", \"r\", newline=\"\\n\")\n callsigns = r.read().split(\"\\n\")\n return callsigns\n\n @staticmethod\n def read_settings():\n \"\"\" reads the settings from file \"\"\"\n \n settings = OrdDic()\n settings.update(json.load(open(\"resources/files/settings.txt\", \"r\")))\n\n ## OLD WAY BELOW\n\n #r = open(\"resources/files/settings.txt\", \"r\", newline=\"\\n\")\n # for option in r.read().split('\\n'):\n # try:\n # #option = option.split('\\\\')\n # #settings.update({option[0]: option[1]})\n # # settings.update(json.loads(option))\n # except IndexError:\n # pass\n return settings\n\n @staticmethod\n def save_settings(dic):\n \"\"\" saves the given settings (dictionary) to file \"\"\"\n json.dump(dic, open(\"resources/files/settings.txt\", \"w\"))\n\n # LEGACY\n # with open(\"resources/files/settings.txt\", \"w\", newline=\"\\n\") as w:\n # for sett, val in dic.items():\n # w.write(sett + '\\\\' + val + '\\n')\n\n @staticmethod\n def save_log(self, log, update=False):\n \"\"\" Saves the log to file \"\"\"\n\n main_keys = [\n 'name',\n 'sender',\n 'receiver',\n 'time',\n 'duty',\n 'net'\n ]\n\n # print(test)\n\n lst = []\n for key in main_keys:\n # print(key)\n lst.append(log[key])\n log.pop(key)\n \n # LEGACY\n # inn_lst = []\n # for serial, val in log.items():\n # if not (serial in main_keys):\n # inn_lst.append(serial + '\\\\' + val)\n\n # lst.append('||'.join(inn_lst))\n\n lst.append(json.dumps(log))\n\n # print(lst)\n\n if update:\n self.update_record(lst, log['logID'])\n\n else:\n self.new_return(lst)\n\n @staticmethod\n def load_log_query(Db, query):\n\n x = list(Db.query_data(query, 100))\n\n local_log = list()\n for row in x:\n row = list(row)\n try:\n ret = OrdDic()\n\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': row[4]})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n\n ret.update(json.loads(row[7]))\n\n # LEGACY\n # for serial_data in row[7:]:\n # try:\n # for serial in serial_data.split('||'):\n # ser, val = serial.split('\\\\')\n # val = \"\" + val\n # ret.update({ser: str(val)})\n # except AttributeError:\n # print('The Db structure is incorrect')\n local_log.append(ret)\n\n except TypeError:\n print(\"none value in db\")\n return local_log\n\n @staticmethod\n def load_log(Db, log_id=None):\n \"\"\" loads the log file \"\"\"\n # try:\n # r = reader(open(\"resources/static/logs.csv\", \"r\"))\n # except FileNotFoundError:\n # w = open(\"resources/static/logs.csv\", 'w')\n # w.close()\n # r = reader(open(\"resources/static/logs.csv\", \"r\"))\n\n if log_id:\n row = Db.find_index(log_id).fetchone()\n local_log = list()\n ret = None\n try:\n ret = OrdDic()\n\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n\n ret.update(json.loads(row[7]))\n\n # LEGACY\n # for serial_data in row[7:]:\n # try:\n # for serial in serial_data.split('||'):\n # ser, val = serial.split('\\\\')\n # val = \"\" + val\n # ret.update({ser: str(val)})\n # except AttributeError:\n # print('The Db structure is incorrect')\n\n except TypeError:\n pass # This is handled upon return (it returns None type)\n\n return ret\n\n else:\n try:\n x = list(Db.read_return(entries=100))\n except TypeError:\n x = \"\"\n\n local_log = list()\n for row in x:\n row = list(row)\n\n try:\n ret = OrdDic()\n\n ret.update({'logID': row[0]})\n ret.update({'name': row[1]})\n ret.update({'sender': row[2]})\n ret.update({'receiver': row[3]})\n ret.update({'time': fix_time(row[4])})\n ret.update({'duty': row[5]})\n ret.update({'net': row[6]})\n\n ret.update(json.loads(row[7]))\n\n # LEGACY\n # for serial_data in row[7:]:\n # try:\n # for serial in serial_data.split('||'):\n # ser, val = serial.split('\\\\')\n # val = \"\" + val\n # ret.update({ser: str(val)})\n # except AttributeError:\n # print('The Db structure is incorrect')\n local_log.append(ret)\n\n except TypeError:\n print(\"none value in db\")\n\n return local_log\n\n @staticmethod\n def delete_log_byID(Db, id):\n Db.delete_return_byID(id)\n\ndef fix_time(dtg):\n if len(str(dtg)) == 6:\n return str(dtg)\n else:\n return str(f'0{dtg}')\n\n\nclass SaveTimer(object):\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\ndef copytree(src, dst, symlinks=False, ignore=None):\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n shutil.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n\ndef backup():\n files = glob(\"/Volumes/*\")\n\n rem = [\"/Volumes/student\", \"/Volumes/com.apple.TimeMachine.localsnapshots\", \"/Volumes/Macintosh HD\", \"Blah\"]\n\n for path in rem:\n try:\n files.remove(path)\n except ValueError:\n pass\n\n\n usb = None\n for path in files:\n if \"CP\" in path:\n usb = os.path.join(path, \"Backup\")\n break\n else:\n usb = None\n print(\"No Backup USB found\")\n\n if usb:\n # save to usb\n print(\"Saving...\", end=\" \")\n save(os.path.join(usb, \"files\"), \"resources/files\")\n save(os.path.join(usb, \"db\"), \"resources/static/db\")\n print(\"Saved\")\n\ndef save(dest, src):\n if not os.path.exists(dest):\n os.makedirs(dest)\n copytree(src, dest)\n\nif __name__ == '__main__':\n pass\n\n # File.pre_merge()\n\n # settings = File.read_settings()\n # File.save_settings(settings)\n # File.read_locations()\n # File.read_callsigns()\n # File.save_dic()\n # File.read_dic()\n\n # x = file()\n # x.save()\n", "step-ids": [ 31, 37, 39, 44, 50 ] }
[ 31, 37, 39, 44, 50 ]
import numpy as np import h5py def rotate_z(theta, x): theta = np.expand_dims(theta, 1) outz = np.expand_dims(x[:, :, 2], 2) sin_t = np.sin(theta) cos_t = np.cos(theta) xx = np.expand_dims(x[:, :, 0], 2) yy = np.expand_dims(x[:, :, 1], 2) outx = cos_t * xx - sin_t * yy outy = sin_t * xx + cos_t * yy return np.concatenate([outx, outy, outz], axis=2) def augment(x): bs = x.shape[0] # rotation min_rot, max_rot = -0.1, 0.1 thetas = np.random.uniform(min_rot, max_rot, [bs, 1]) * np.pi rotated = rotate_z(thetas, x) # scaling min_scale, max_scale = 0.8, 1.25 scale = np.random.rand(bs, 1, 3) * (max_scale - min_scale) + min_scale return rotated * scale def standardize(x): clipper = np.mean(np.abs(x), (1, 2), keepdims=True) z = np.clip(x, -100 * clipper, 100 * clipper) mean = np.mean(z, (1, 2), keepdims=True) std = np.std(z, (1, 2), keepdims=True) return (z - mean) / std class ModelFetcher(object): def __init__( self, fname, batch_size, down_sample=10, do_standardize=True, do_augmentation=False, ): self.fname = fname self.batch_size = batch_size self.down_sample = down_sample with h5py.File(fname, "r") as f: self._train_data = np.array(f["tr_cloud"]) self._train_label = np.array(f["tr_labels"]) self._test_data = np.array(f["test_cloud"]) self._test_label = np.array(f["test_labels"]) self.num_classes = np.max(self._train_label) + 1 self.num_train_batches = len(self._train_data) // self.batch_size self.num_test_batches = len(self._test_data) // self.batch_size self.prep1 = standardize if do_standardize else lambda x: x self.prep2 = ( (lambda x: augment(self.prep1(x))) if do_augmentation else self.prep1 ) assert ( len(self._train_data) > self.batch_size ), "Batch size larger than number of training examples" # select the subset of points to use throughout beforehand self.perm = np.random.permutation(self._train_data.shape[1])[ :: self.down_sample ] def train_data(self): rng_state = np.random.get_state() np.random.shuffle(self._train_data) np.random.set_state(rng_state) np.random.shuffle(self._train_label) return self.next_train_batch() def next_train_batch(self): start = 0 end = self.batch_size N = len(self._train_data) perm = self.perm batch_card = len(perm) * np.ones(self.batch_size, dtype=np.int32) while end < N: yield self.prep2( self._train_data[start:end, perm] ), batch_card, self._train_label[start:end] start = end end += self.batch_size def test_data(self): return self.next_test_batch() def next_test_batch(self): start = 0 end = self.batch_size N = len(self._test_data) batch_card = (self._train_data.shape[1] // self.down_sample) * np.ones( self.batch_size, dtype=np.int32 ) while end < N: yield self.prep1( self._test_data[start:end, 1 :: self.down_sample] ), batch_card, self._test_label[start:end] start = end end += self.batch_size
normal
{ "blob_id": "855bfc9420a5d5031cc673231cc7993ac67df076", "index": 5515, "step-1": "<mask token>\n\n\nclass ModelFetcher(object):\n <mask token>\n\n def train_data(self):\n rng_state = np.random.get_state()\n np.random.shuffle(self._train_data)\n np.random.set_state(rng_state)\n np.random.shuffle(self._train_label)\n return self.next_train_batch()\n <mask token>\n <mask token>\n\n def next_test_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._test_data)\n batch_card = self._train_data.shape[1] // self.down_sample * np.ones(\n self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep1(self._test_data[start:end, 1::self.down_sample]\n ), batch_card, self._test_label[start:end]\n start = end\n end += self.batch_size\n", "step-2": "<mask token>\n\n\nclass ModelFetcher(object):\n\n def __init__(self, fname, batch_size, down_sample=10, do_standardize=\n True, do_augmentation=False):\n self.fname = fname\n self.batch_size = batch_size\n self.down_sample = down_sample\n with h5py.File(fname, 'r') as f:\n self._train_data = np.array(f['tr_cloud'])\n self._train_label = np.array(f['tr_labels'])\n self._test_data = np.array(f['test_cloud'])\n self._test_label = np.array(f['test_labels'])\n self.num_classes = np.max(self._train_label) + 1\n self.num_train_batches = len(self._train_data) // self.batch_size\n self.num_test_batches = len(self._test_data) // self.batch_size\n self.prep1 = standardize if do_standardize else lambda x: x\n self.prep2 = (lambda x: augment(self.prep1(x))\n ) if do_augmentation else self.prep1\n assert len(self._train_data\n ) > self.batch_size, 'Batch size larger than number of training examples'\n self.perm = np.random.permutation(self._train_data.shape[1])[::self\n .down_sample]\n\n def train_data(self):\n rng_state = np.random.get_state()\n np.random.shuffle(self._train_data)\n np.random.set_state(rng_state)\n np.random.shuffle(self._train_label)\n return self.next_train_batch()\n\n def next_train_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._train_data)\n perm = self.perm\n batch_card = len(perm) * np.ones(self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep2(self._train_data[start:end, perm]\n ), batch_card, self._train_label[start:end]\n start = end\n end += self.batch_size\n\n def test_data(self):\n return self.next_test_batch()\n\n def next_test_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._test_data)\n batch_card = self._train_data.shape[1] // self.down_sample * np.ones(\n self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep1(self._test_data[start:end, 1::self.down_sample]\n ), batch_card, self._test_label[start:end]\n start = end\n end += self.batch_size\n", "step-3": "<mask token>\n\n\ndef rotate_z(theta, x):\n theta = np.expand_dims(theta, 1)\n outz = np.expand_dims(x[:, :, 2], 2)\n sin_t = np.sin(theta)\n cos_t = np.cos(theta)\n xx = np.expand_dims(x[:, :, 0], 2)\n yy = np.expand_dims(x[:, :, 1], 2)\n outx = cos_t * xx - sin_t * yy\n outy = sin_t * xx + cos_t * yy\n return np.concatenate([outx, outy, outz], axis=2)\n\n\ndef augment(x):\n bs = x.shape[0]\n min_rot, max_rot = -0.1, 0.1\n thetas = np.random.uniform(min_rot, max_rot, [bs, 1]) * np.pi\n rotated = rotate_z(thetas, x)\n min_scale, max_scale = 0.8, 1.25\n scale = np.random.rand(bs, 1, 3) * (max_scale - min_scale) + min_scale\n return rotated * scale\n\n\n<mask token>\n\n\nclass ModelFetcher(object):\n\n def __init__(self, fname, batch_size, down_sample=10, do_standardize=\n True, do_augmentation=False):\n self.fname = fname\n self.batch_size = batch_size\n self.down_sample = down_sample\n with h5py.File(fname, 'r') as f:\n self._train_data = np.array(f['tr_cloud'])\n self._train_label = np.array(f['tr_labels'])\n self._test_data = np.array(f['test_cloud'])\n self._test_label = np.array(f['test_labels'])\n self.num_classes = np.max(self._train_label) + 1\n self.num_train_batches = len(self._train_data) // self.batch_size\n self.num_test_batches = len(self._test_data) // self.batch_size\n self.prep1 = standardize if do_standardize else lambda x: x\n self.prep2 = (lambda x: augment(self.prep1(x))\n ) if do_augmentation else self.prep1\n assert len(self._train_data\n ) > self.batch_size, 'Batch size larger than number of training examples'\n self.perm = np.random.permutation(self._train_data.shape[1])[::self\n .down_sample]\n\n def train_data(self):\n rng_state = np.random.get_state()\n np.random.shuffle(self._train_data)\n np.random.set_state(rng_state)\n np.random.shuffle(self._train_label)\n return self.next_train_batch()\n\n def next_train_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._train_data)\n perm = self.perm\n batch_card = len(perm) * np.ones(self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep2(self._train_data[start:end, perm]\n ), batch_card, self._train_label[start:end]\n start = end\n end += self.batch_size\n\n def test_data(self):\n return self.next_test_batch()\n\n def next_test_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._test_data)\n batch_card = self._train_data.shape[1] // self.down_sample * np.ones(\n self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep1(self._test_data[start:end, 1::self.down_sample]\n ), batch_card, self._test_label[start:end]\n start = end\n end += self.batch_size\n", "step-4": "import numpy as np\nimport h5py\n\n\ndef rotate_z(theta, x):\n theta = np.expand_dims(theta, 1)\n outz = np.expand_dims(x[:, :, 2], 2)\n sin_t = np.sin(theta)\n cos_t = np.cos(theta)\n xx = np.expand_dims(x[:, :, 0], 2)\n yy = np.expand_dims(x[:, :, 1], 2)\n outx = cos_t * xx - sin_t * yy\n outy = sin_t * xx + cos_t * yy\n return np.concatenate([outx, outy, outz], axis=2)\n\n\ndef augment(x):\n bs = x.shape[0]\n min_rot, max_rot = -0.1, 0.1\n thetas = np.random.uniform(min_rot, max_rot, [bs, 1]) * np.pi\n rotated = rotate_z(thetas, x)\n min_scale, max_scale = 0.8, 1.25\n scale = np.random.rand(bs, 1, 3) * (max_scale - min_scale) + min_scale\n return rotated * scale\n\n\ndef standardize(x):\n clipper = np.mean(np.abs(x), (1, 2), keepdims=True)\n z = np.clip(x, -100 * clipper, 100 * clipper)\n mean = np.mean(z, (1, 2), keepdims=True)\n std = np.std(z, (1, 2), keepdims=True)\n return (z - mean) / std\n\n\nclass ModelFetcher(object):\n\n def __init__(self, fname, batch_size, down_sample=10, do_standardize=\n True, do_augmentation=False):\n self.fname = fname\n self.batch_size = batch_size\n self.down_sample = down_sample\n with h5py.File(fname, 'r') as f:\n self._train_data = np.array(f['tr_cloud'])\n self._train_label = np.array(f['tr_labels'])\n self._test_data = np.array(f['test_cloud'])\n self._test_label = np.array(f['test_labels'])\n self.num_classes = np.max(self._train_label) + 1\n self.num_train_batches = len(self._train_data) // self.batch_size\n self.num_test_batches = len(self._test_data) // self.batch_size\n self.prep1 = standardize if do_standardize else lambda x: x\n self.prep2 = (lambda x: augment(self.prep1(x))\n ) if do_augmentation else self.prep1\n assert len(self._train_data\n ) > self.batch_size, 'Batch size larger than number of training examples'\n self.perm = np.random.permutation(self._train_data.shape[1])[::self\n .down_sample]\n\n def train_data(self):\n rng_state = np.random.get_state()\n np.random.shuffle(self._train_data)\n np.random.set_state(rng_state)\n np.random.shuffle(self._train_label)\n return self.next_train_batch()\n\n def next_train_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._train_data)\n perm = self.perm\n batch_card = len(perm) * np.ones(self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep2(self._train_data[start:end, perm]\n ), batch_card, self._train_label[start:end]\n start = end\n end += self.batch_size\n\n def test_data(self):\n return self.next_test_batch()\n\n def next_test_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._test_data)\n batch_card = self._train_data.shape[1] // self.down_sample * np.ones(\n self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep1(self._test_data[start:end, 1::self.down_sample]\n ), batch_card, self._test_label[start:end]\n start = end\n end += self.batch_size\n", "step-5": "import numpy as np\nimport h5py\n\n\ndef rotate_z(theta, x):\n theta = np.expand_dims(theta, 1)\n outz = np.expand_dims(x[:, :, 2], 2)\n sin_t = np.sin(theta)\n cos_t = np.cos(theta)\n xx = np.expand_dims(x[:, :, 0], 2)\n yy = np.expand_dims(x[:, :, 1], 2)\n outx = cos_t * xx - sin_t * yy\n outy = sin_t * xx + cos_t * yy\n return np.concatenate([outx, outy, outz], axis=2)\n\n\ndef augment(x):\n bs = x.shape[0]\n # rotation\n min_rot, max_rot = -0.1, 0.1\n thetas = np.random.uniform(min_rot, max_rot, [bs, 1]) * np.pi\n rotated = rotate_z(thetas, x)\n # scaling\n min_scale, max_scale = 0.8, 1.25\n scale = np.random.rand(bs, 1, 3) * (max_scale - min_scale) + min_scale\n return rotated * scale\n\n\ndef standardize(x):\n clipper = np.mean(np.abs(x), (1, 2), keepdims=True)\n z = np.clip(x, -100 * clipper, 100 * clipper)\n mean = np.mean(z, (1, 2), keepdims=True)\n std = np.std(z, (1, 2), keepdims=True)\n return (z - mean) / std\n\n\nclass ModelFetcher(object):\n def __init__(\n self,\n fname,\n batch_size,\n down_sample=10,\n do_standardize=True,\n do_augmentation=False,\n ):\n\n self.fname = fname\n self.batch_size = batch_size\n self.down_sample = down_sample\n\n with h5py.File(fname, \"r\") as f:\n self._train_data = np.array(f[\"tr_cloud\"])\n self._train_label = np.array(f[\"tr_labels\"])\n self._test_data = np.array(f[\"test_cloud\"])\n self._test_label = np.array(f[\"test_labels\"])\n\n self.num_classes = np.max(self._train_label) + 1\n\n self.num_train_batches = len(self._train_data) // self.batch_size\n self.num_test_batches = len(self._test_data) // self.batch_size\n\n self.prep1 = standardize if do_standardize else lambda x: x\n self.prep2 = (\n (lambda x: augment(self.prep1(x))) if do_augmentation else self.prep1\n )\n\n assert (\n len(self._train_data) > self.batch_size\n ), \"Batch size larger than number of training examples\"\n\n # select the subset of points to use throughout beforehand\n self.perm = np.random.permutation(self._train_data.shape[1])[\n :: self.down_sample\n ]\n\n def train_data(self):\n rng_state = np.random.get_state()\n np.random.shuffle(self._train_data)\n np.random.set_state(rng_state)\n np.random.shuffle(self._train_label)\n return self.next_train_batch()\n\n def next_train_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._train_data)\n perm = self.perm\n batch_card = len(perm) * np.ones(self.batch_size, dtype=np.int32)\n while end < N:\n yield self.prep2(\n self._train_data[start:end, perm]\n ), batch_card, self._train_label[start:end]\n start = end\n end += self.batch_size\n\n def test_data(self):\n return self.next_test_batch()\n\n def next_test_batch(self):\n start = 0\n end = self.batch_size\n N = len(self._test_data)\n batch_card = (self._train_data.shape[1] // self.down_sample) * np.ones(\n self.batch_size, dtype=np.int32\n )\n while end < N:\n yield self.prep1(\n self._test_data[start:end, 1 :: self.down_sample]\n ), batch_card, self._test_label[start:end]\n start = end\n end += self.batch_size\n", "step-ids": [ 3, 6, 8, 10, 11 ] }
[ 3, 6, 8, 10, 11 ]
import requests response = requests.get( 'https://any-api.com:8443/https://rbaskets.in/api/version') print(response.text)
normal
{ "blob_id": "ab36b3d418be67080e2efaba15edc1354386e191", "index": 6888, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(response.text)\n", "step-3": "<mask token>\nresponse = requests.get(\n 'https://any-api.com:8443/https://rbaskets.in/api/version')\nprint(response.text)\n", "step-4": "import requests\nresponse = requests.get(\n 'https://any-api.com:8443/https://rbaskets.in/api/version')\nprint(response.text)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" Version information for NetworkX, created during installation. Do not add this file to the repository. """ import datetime version = '2.3' date = 'Thu Apr 11 20:57:18 2019' # Was NetworkX built from a development version? If so, remember that the major # and minor versions reference the "target" (rather than "current") release. dev = False # Format: (name, major, min, revision) version_info = ('networkx', '2', '3', None) # Format: a 'datetime.datetime' instance date_info = datetime.datetime(2019, 4, 11, 20, 57, 18) # Format: (vcs, vcs_tuple) vcs_info = (None, (None, None))
normal
{ "blob_id": "814191a577db279389975e5a02e72cd817254275", "index": 9444, "step-1": "<mask token>\n", "step-2": "<mask token>\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\ndev = False\nversion_info = 'networkx', '2', '3', None\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\nvcs_info = None, (None, None)\n", "step-3": "<mask token>\nimport datetime\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\ndev = False\nversion_info = 'networkx', '2', '3', None\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\nvcs_info = None, (None, None)\n", "step-4": "\"\"\"\nVersion information for NetworkX, created during installation.\n\nDo not add this file to the repository.\n\n\"\"\"\n\nimport datetime\n\nversion = '2.3'\ndate = 'Thu Apr 11 20:57:18 2019'\n\n# Was NetworkX built from a development version? If so, remember that the major\n# and minor versions reference the \"target\" (rather than \"current\") release.\ndev = False\n\n# Format: (name, major, min, revision)\nversion_info = ('networkx', '2', '3', None)\n\n# Format: a 'datetime.datetime' instance\ndate_info = datetime.datetime(2019, 4, 11, 20, 57, 18)\n\n# Format: (vcs, vcs_tuple)\nvcs_info = (None, (None, None))\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from migen import * from migen.fhdl import verilog class Alignment_Corrector(Module): def __init__(self): self.din=din=Signal(32) self.aligned=aligned=Signal() self.dout=dout=Signal(32) self.correction_done=Signal() # # # first_half=Signal(16) first_half1=Signal(16) second_half=Signal(16) self.submodules.fsm=FSM(reset_state="IDLE") self.fsm.act("IDLE", If(aligned, NextState("INIT"), ) ) self.fsm.act("INIT", NextState("DONE"), NextValue(first_half,din[16:]), NextValue(self.correction_done,1) ) self.fsm.act("DONE", dout.eq(Cat(first_half,din[:16])), NextValue(first_half,din[16:]), NextState("DONE") ) #example = Alignment_Corrector() #verilog.convert(example, {example.din, example.dout, example.aligned, example.correction_done}).write("alignment_corrector.v") """ def tb(dut): yield for i in range(10): yield dut.din.eq(0x62cfa9d274) yield dut.aligned.eq(1) yield yield dut.din.eq(0x9d30562d8b) yield dut=Alignment_Corrector() run_simulation(dut,tb(dut),vcd_name="alignment_tb.vcd") """
normal
{ "blob_id": "f3eed00a58491f36778b3a710d2f46be093d6eda", "index": 6320, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Alignment_Corrector(Module):\n <mask token>\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Alignment_Corrector(Module):\n\n def __init__(self):\n self.din = din = Signal(32)\n self.aligned = aligned = Signal()\n self.dout = dout = Signal(32)\n self.correction_done = Signal()\n first_half = Signal(16)\n first_half1 = Signal(16)\n second_half = Signal(16)\n self.submodules.fsm = FSM(reset_state='IDLE')\n self.fsm.act('IDLE', If(aligned, NextState('INIT')))\n self.fsm.act('INIT', NextState('DONE'), NextValue(first_half, din[\n 16:]), NextValue(self.correction_done, 1))\n self.fsm.act('DONE', dout.eq(Cat(first_half, din[:16])), NextValue(\n first_half, din[16:]), NextState('DONE'))\n\n\n<mask token>\n", "step-4": "from migen import *\nfrom migen.fhdl import verilog\n\n\nclass Alignment_Corrector(Module):\n\n def __init__(self):\n self.din = din = Signal(32)\n self.aligned = aligned = Signal()\n self.dout = dout = Signal(32)\n self.correction_done = Signal()\n first_half = Signal(16)\n first_half1 = Signal(16)\n second_half = Signal(16)\n self.submodules.fsm = FSM(reset_state='IDLE')\n self.fsm.act('IDLE', If(aligned, NextState('INIT')))\n self.fsm.act('INIT', NextState('DONE'), NextValue(first_half, din[\n 16:]), NextValue(self.correction_done, 1))\n self.fsm.act('DONE', dout.eq(Cat(first_half, din[:16])), NextValue(\n first_half, din[16:]), NextState('DONE'))\n\n\n<mask token>\n", "step-5": "from migen import *\nfrom migen.fhdl import verilog\n\nclass Alignment_Corrector(Module):\n\tdef __init__(self):\n\t\tself.din=din=Signal(32)\n\t\tself.aligned=aligned=Signal()\n\t\tself.dout=dout=Signal(32)\n\t\tself.correction_done=Signal()\n\t\t#\t#\t#\n\t\tfirst_half=Signal(16)\n\t\tfirst_half1=Signal(16)\n\t\tsecond_half=Signal(16)\n\t\tself.submodules.fsm=FSM(reset_state=\"IDLE\")\n\t\tself.fsm.act(\"IDLE\",\n\t\t\tIf(aligned, \n\t\t\t\tNextState(\"INIT\"),\n\t\t\t)\n\t\t)\n\t\tself.fsm.act(\"INIT\",\n\t\t\tNextState(\"DONE\"),\n\t\t\tNextValue(first_half,din[16:]),\n\t\t\tNextValue(self.correction_done,1)\n\t\t)\n\t\tself.fsm.act(\"DONE\",\n\t\t\tdout.eq(Cat(first_half,din[:16])),\n\t\t\tNextValue(first_half,din[16:]),\n\t\t\tNextState(\"DONE\")\n\n\t\t)\n\t\n#example = Alignment_Corrector()\n#verilog.convert(example, {example.din, example.dout, example.aligned, example.correction_done}).write(\"alignment_corrector.v\")\n\n\n\n\t\n\"\"\"\ndef tb(dut):\n\tyield\t\n\tfor i in range(10):\n\t\tyield dut.din.eq(0x62cfa9d274) \n\t\tyield dut.aligned.eq(1)\n\t\tyield\n\t\tyield dut.din.eq(0x9d30562d8b)\n\t\tyield\n\ndut=Alignment_Corrector()\nrun_simulation(dut,tb(dut),vcd_name=\"alignment_tb.vcd\")\n\"\"\"\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# -*- coding: utf-8 -*- import requests import json import boto3 from lxml.html import parse CardTitlePrefix = "Greeting" def build_speechlet_response(title, output, reprompt_text, should_end_session): """ Build a speechlet JSON representation of the title, output text, reprompt text & end of session """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'card': { 'type': 'Simple', 'title': CardTitlePrefix + " - " + title, 'content': output }, 'reprompt': { 'outputSpeech': { 'type': 'PlainText', 'text': reprompt_text } }, 'shouldEndSession': should_end_session } def build_response(session_attributes, speechlet_response): """ Build the full response JSON from the speechlet response """ return { 'version': '1.0', 'sessionAttributes': session_attributes, 'response': speechlet_response } def get_welcome_response(): welcome_response= "Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda." print(welcome_response); session_attributes = {} card_title = "Hello" speech_output = welcome_response; # If the user either does not reply to the welcome message or says something # that is not understood, they will be prompted again with this text. reprompt_text = "I'm sorry - I didn't understand. You should say give me latest motions." should_end_session = True return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session)) def replace_with_longform_name(name): if name == "LASD": longformName = "Los Angeles County Sheriff's Department" elif name == "DMH": longformName = "Department of Mental Health" else: longformName = name; return longformName; def get_next_motions_response(session): print("Initial session attributes are "+str(session['attributes'])); if "result_number" not in session['attributes']: print("Second session attributes are "+str(session['attributes'])); session['attributes']['result_number'] = 1; print("Value is "+str(session['attributes']['result_number'])); print("Final session attributes are "+str(session['attributes'])) result_number = session['attributes']['result_number']; host = "http://api.lacounty.gov"; url = host + "/searchAPIWeb/searchapi?type=bcsearch&database=OMD&" \ "SearchTerm=1&title=1&content=1&PStart=" + str(result_number) +"&PEnd=" + str(result_number) +"&_=1509121047612" response = requests.get(url); #print(response.text); data = json.loads(response.text) alexaResponse = ""; if(result_number == 1): alexaResponse = "Here is the latest correspondence before the L.A. board (both upcoming and past): " alexaResponse += str(result_number)+": From the "+replace_with_longform_name(data["results"][0]["department"])+ ", " alexaResponse += "on "+data["results"][0]["date"]+", " alexaResponse += data["results"][0]["title"]+"... " alexaResponse += "You can say text me link or next item" session['attributes']['result_number'] = result_number + 1; session['attributes']['result_url'] = data["results"][0]["url"]; #text_url_to_number(session); reprompt_text = "I'm sorry - I didn't understand. You should say text me link or next item" card_title = "LA Board Latest Motions Message"; greeting_string = alexaResponse; return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, False)) def get_next_agenda_response(session): print("Initial session attributes are "+str(session['attributes'])); host = "http://bos.lacounty.gov/Board-Meeting/Board-Agendas"; url = host; page = parse(url) nodes = page.xpath("//div[a[text()='View Agenda']]"); latest_agenda_node = nodes[0]; headline = latest_agenda_node.find("ul").xpath("string()").strip(); print(headline); agenda_url = latest_agenda_node.find("a[@href]").attrib['href']; print("http://bos.lacounty.gov"+agenda_url) agenda_heading = headline; #session['attributes']['result_url'] session['attributes']['result_url'] = "http://bos.lacounty.gov"+agenda_url; card_title = "Agenda"; greeting_string = "I have a link for the "+agenda_heading+". Say text me and I'll send it to you."; reprompt = "Say text me to receive a link to the agenda." return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt, False)) def text_url_to_number(session, intent): if "phone_number" not in session['attributes'] and "value" not in intent['slots']['phoneNumber']: greeting_string = "Say your nine digit phone number, including the area code"; card_title = "What's your phone number?"; reprompt_text = "I didn't understand. Please say your nine digit mobile phone number." return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, False)) else: number = intent['slots']['phoneNumber']['value']; if "result_url" not in session['attributes']: session['attributes']['result_url'] = 'http://portal.lacounty.gov/wps/portal/omd'; url = session['attributes']['result_url']; session['attributes']['phone_number'] = number; sns_client = boto3.client('sns') response = sns_client.publish( PhoneNumber='1'+str(number), Message="Thank you for using the LA Board of Supervisors Skill. Here's your URL: "+url ) greeting_string = "Sent text message to "+ " ".join(number); card_title = "Sent motion URL via text message"; reprompt_text = "I didn't understand. Please say your nine digit mobile phone number." return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, True)) def on_session_started(session_started_request, session): """ Called when the session starts """ #session.attributes['result_number'] = 1 session['attributes'] = {} print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId']) def handle_session_end_request(): card_title = "County of LA Board of Supervisors Skill- Thanks" speech_output = "Thank you for using the County of LA Board of Supervisors Skill. See you next time!" should_end_session = True return build_response({}, build_speechlet_response(card_title, speech_output, None, should_end_session)); def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response() def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch to your skill's intent handlers if intent_name == "GetLatestAgendaIntent": return get_next_agenda_response(session) elif intent_name == "GetLatestMotionsIntent": return get_next_motions_response(session) elif intent_name == "GetNextMotionIntent": return get_next_motions_response(session) elif intent_name == "SetPhoneNumberIntent": return text_url_to_number(session, intent); elif intent_name == "AMAZON.HelpIntent": return get_welcome_response() elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent": return handle_session_end_request() else: raise ValueError("Invalid intent") def lambda_handler(event, context): print("Test!") print("event.session.application.applicationId=" + event['session']['application']['applicationId']) if event['session']['new']: on_session_started({'requestId': event['request']['requestId']}, event['session']) if event['request']['type'] == "LaunchRequest": return on_launch(event['request'], event['session']) elif event['request']['type'] == "IntentRequest": return on_intent(event['request'], event['session']) elif event['request']['type'] == "SessionEndedRequest": return handle_session_end_request()
normal
{ "blob_id": "237277e132c8223c6048be9b754516635ab720e2", "index": 8964, "step-1": "<mask token>\n\n\ndef build_response(session_attributes, speechlet_response):\n \"\"\"\n Build the full response JSON from the speechlet response\n \"\"\"\n return {'version': '1.0', 'sessionAttributes': session_attributes,\n 'response': speechlet_response}\n\n\ndef get_welcome_response():\n welcome_response = (\n 'Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda.'\n )\n print(welcome_response)\n session_attributes = {}\n card_title = 'Hello'\n speech_output = welcome_response\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say give me latest motions.\"\n )\n should_end_session = True\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\n<mask token>\n\n\ndef get_next_motions_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n if 'result_number' not in session['attributes']:\n print('Second session attributes are ' + str(session['attributes']))\n session['attributes']['result_number'] = 1\n print('Value is ' + str(session['attributes']['result_number']))\n print('Final session attributes are ' + str(session['attributes']))\n result_number = session['attributes']['result_number']\n host = 'http://api.lacounty.gov'\n url = (host +\n '/searchAPIWeb/searchapi?type=bcsearch&database=OMD&SearchTerm=1&title=1&content=1&PStart='\n + str(result_number) + '&PEnd=' + str(result_number) +\n '&_=1509121047612')\n response = requests.get(url)\n data = json.loads(response.text)\n alexaResponse = ''\n if result_number == 1:\n alexaResponse = (\n 'Here is the latest correspondence before the L.A. board (both upcoming and past): '\n )\n alexaResponse += str(result_number\n ) + ': From the ' + replace_with_longform_name(data['results'][0][\n 'department']) + ', '\n alexaResponse += 'on ' + data['results'][0]['date'] + ', '\n alexaResponse += data['results'][0]['title'] + '... '\n alexaResponse += 'You can say text me link or next item'\n session['attributes']['result_number'] = result_number + 1\n session['attributes']['result_url'] = data['results'][0]['url']\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say text me link or next item\"\n )\n card_title = 'LA Board Latest Motions Message'\n greeting_string = alexaResponse\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt_text, False))\n\n\n<mask token>\n\n\ndef text_url_to_number(session, intent):\n if 'phone_number' not in session['attributes'] and 'value' not in intent[\n 'slots']['phoneNumber']:\n greeting_string = (\n 'Say your nine digit phone number, including the area code')\n card_title = \"What's your phone number?\"\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, False))\n else:\n number = intent['slots']['phoneNumber']['value']\n if 'result_url' not in session['attributes']:\n session['attributes']['result_url'\n ] = 'http://portal.lacounty.gov/wps/portal/omd'\n url = session['attributes']['result_url']\n session['attributes']['phone_number'] = number\n sns_client = boto3.client('sns')\n response = sns_client.publish(PhoneNumber='1' + str(number),\n Message=\n \"Thank you for using the LA Board of Supervisors Skill. Here's your URL: \"\n + url)\n greeting_string = 'Sent text message to ' + ' '.join(number)\n card_title = 'Sent motion URL via text message'\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, True))\n\n\n<mask token>\n\n\ndef handle_session_end_request():\n card_title = 'County of LA Board of Supervisors Skill- Thanks'\n speech_output = (\n 'Thank you for using the County of LA Board of Supervisors Skill. See you next time!'\n )\n should_end_session = True\n return build_response({}, build_speechlet_response(card_title,\n speech_output, None, should_end_session))\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they want \"\"\"\n print('on_launch requestId=' + launch_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n print('on_intent requestId=' + intent_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n if intent_name == 'GetLatestAgendaIntent':\n return get_next_agenda_response(session)\n elif intent_name == 'GetLatestMotionsIntent':\n return get_next_motions_response(session)\n elif intent_name == 'GetNextMotionIntent':\n return get_next_motions_response(session)\n elif intent_name == 'SetPhoneNumberIntent':\n return text_url_to_number(session, intent)\n elif intent_name == 'AMAZON.HelpIntent':\n return get_welcome_response()\n elif intent_name == 'AMAZON.CancelIntent' or intent_name == 'AMAZON.StopIntent':\n return handle_session_end_request()\n else:\n raise ValueError('Invalid intent')\n\n\ndef lambda_handler(event, context):\n print('Test!')\n print('event.session.application.applicationId=' + event['session'][\n 'application']['applicationId'])\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == 'LaunchRequest':\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == 'IntentRequest':\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == 'SessionEndedRequest':\n return handle_session_end_request()\n", "step-2": "<mask token>\n\n\ndef build_response(session_attributes, speechlet_response):\n \"\"\"\n Build the full response JSON from the speechlet response\n \"\"\"\n return {'version': '1.0', 'sessionAttributes': session_attributes,\n 'response': speechlet_response}\n\n\ndef get_welcome_response():\n welcome_response = (\n 'Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda.'\n )\n print(welcome_response)\n session_attributes = {}\n card_title = 'Hello'\n speech_output = welcome_response\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say give me latest motions.\"\n )\n should_end_session = True\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef replace_with_longform_name(name):\n if name == 'LASD':\n longformName = \"Los Angeles County Sheriff's Department\"\n elif name == 'DMH':\n longformName = 'Department of Mental Health'\n else:\n longformName = name\n return longformName\n\n\ndef get_next_motions_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n if 'result_number' not in session['attributes']:\n print('Second session attributes are ' + str(session['attributes']))\n session['attributes']['result_number'] = 1\n print('Value is ' + str(session['attributes']['result_number']))\n print('Final session attributes are ' + str(session['attributes']))\n result_number = session['attributes']['result_number']\n host = 'http://api.lacounty.gov'\n url = (host +\n '/searchAPIWeb/searchapi?type=bcsearch&database=OMD&SearchTerm=1&title=1&content=1&PStart='\n + str(result_number) + '&PEnd=' + str(result_number) +\n '&_=1509121047612')\n response = requests.get(url)\n data = json.loads(response.text)\n alexaResponse = ''\n if result_number == 1:\n alexaResponse = (\n 'Here is the latest correspondence before the L.A. board (both upcoming and past): '\n )\n alexaResponse += str(result_number\n ) + ': From the ' + replace_with_longform_name(data['results'][0][\n 'department']) + ', '\n alexaResponse += 'on ' + data['results'][0]['date'] + ', '\n alexaResponse += data['results'][0]['title'] + '... '\n alexaResponse += 'You can say text me link or next item'\n session['attributes']['result_number'] = result_number + 1\n session['attributes']['result_url'] = data['results'][0]['url']\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say text me link or next item\"\n )\n card_title = 'LA Board Latest Motions Message'\n greeting_string = alexaResponse\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt_text, False))\n\n\ndef get_next_agenda_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n host = 'http://bos.lacounty.gov/Board-Meeting/Board-Agendas'\n url = host\n page = parse(url)\n nodes = page.xpath(\"//div[a[text()='View Agenda']]\")\n latest_agenda_node = nodes[0]\n headline = latest_agenda_node.find('ul').xpath('string()').strip()\n print(headline)\n agenda_url = latest_agenda_node.find('a[@href]').attrib['href']\n print('http://bos.lacounty.gov' + agenda_url)\n agenda_heading = headline\n session['attributes']['result_url'\n ] = 'http://bos.lacounty.gov' + agenda_url\n card_title = 'Agenda'\n greeting_string = ('I have a link for the ' + agenda_heading +\n \". Say text me and I'll send it to you.\")\n reprompt = 'Say text me to receive a link to the agenda.'\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt, False))\n\n\ndef text_url_to_number(session, intent):\n if 'phone_number' not in session['attributes'] and 'value' not in intent[\n 'slots']['phoneNumber']:\n greeting_string = (\n 'Say your nine digit phone number, including the area code')\n card_title = \"What's your phone number?\"\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, False))\n else:\n number = intent['slots']['phoneNumber']['value']\n if 'result_url' not in session['attributes']:\n session['attributes']['result_url'\n ] = 'http://portal.lacounty.gov/wps/portal/omd'\n url = session['attributes']['result_url']\n session['attributes']['phone_number'] = number\n sns_client = boto3.client('sns')\n response = sns_client.publish(PhoneNumber='1' + str(number),\n Message=\n \"Thank you for using the LA Board of Supervisors Skill. Here's your URL: \"\n + url)\n greeting_string = 'Sent text message to ' + ' '.join(number)\n card_title = 'Sent motion URL via text message'\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, True))\n\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n session['attributes'] = {}\n print('on_session_started requestId=' + session_started_request[\n 'requestId'] + ', sessionId=' + session['sessionId'])\n\n\ndef handle_session_end_request():\n card_title = 'County of LA Board of Supervisors Skill- Thanks'\n speech_output = (\n 'Thank you for using the County of LA Board of Supervisors Skill. See you next time!'\n )\n should_end_session = True\n return build_response({}, build_speechlet_response(card_title,\n speech_output, None, should_end_session))\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they want \"\"\"\n print('on_launch requestId=' + launch_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n print('on_intent requestId=' + intent_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n if intent_name == 'GetLatestAgendaIntent':\n return get_next_agenda_response(session)\n elif intent_name == 'GetLatestMotionsIntent':\n return get_next_motions_response(session)\n elif intent_name == 'GetNextMotionIntent':\n return get_next_motions_response(session)\n elif intent_name == 'SetPhoneNumberIntent':\n return text_url_to_number(session, intent)\n elif intent_name == 'AMAZON.HelpIntent':\n return get_welcome_response()\n elif intent_name == 'AMAZON.CancelIntent' or intent_name == 'AMAZON.StopIntent':\n return handle_session_end_request()\n else:\n raise ValueError('Invalid intent')\n\n\ndef lambda_handler(event, context):\n print('Test!')\n print('event.session.application.applicationId=' + event['session'][\n 'application']['applicationId'])\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == 'LaunchRequest':\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == 'IntentRequest':\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == 'SessionEndedRequest':\n return handle_session_end_request()\n", "step-3": "<mask token>\nCardTitlePrefix = 'Greeting'\n\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n \"\"\"\n Build a speechlet JSON representation of the title, output text, \n reprompt text & end of session\n \"\"\"\n return {'outputSpeech': {'type': 'PlainText', 'text': output}, 'card':\n {'type': 'Simple', 'title': CardTitlePrefix + ' - ' + title,\n 'content': output}, 'reprompt': {'outputSpeech': {'type':\n 'PlainText', 'text': reprompt_text}}, 'shouldEndSession':\n should_end_session}\n\n\ndef build_response(session_attributes, speechlet_response):\n \"\"\"\n Build the full response JSON from the speechlet response\n \"\"\"\n return {'version': '1.0', 'sessionAttributes': session_attributes,\n 'response': speechlet_response}\n\n\ndef get_welcome_response():\n welcome_response = (\n 'Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda.'\n )\n print(welcome_response)\n session_attributes = {}\n card_title = 'Hello'\n speech_output = welcome_response\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say give me latest motions.\"\n )\n should_end_session = True\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef replace_with_longform_name(name):\n if name == 'LASD':\n longformName = \"Los Angeles County Sheriff's Department\"\n elif name == 'DMH':\n longformName = 'Department of Mental Health'\n else:\n longformName = name\n return longformName\n\n\ndef get_next_motions_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n if 'result_number' not in session['attributes']:\n print('Second session attributes are ' + str(session['attributes']))\n session['attributes']['result_number'] = 1\n print('Value is ' + str(session['attributes']['result_number']))\n print('Final session attributes are ' + str(session['attributes']))\n result_number = session['attributes']['result_number']\n host = 'http://api.lacounty.gov'\n url = (host +\n '/searchAPIWeb/searchapi?type=bcsearch&database=OMD&SearchTerm=1&title=1&content=1&PStart='\n + str(result_number) + '&PEnd=' + str(result_number) +\n '&_=1509121047612')\n response = requests.get(url)\n data = json.loads(response.text)\n alexaResponse = ''\n if result_number == 1:\n alexaResponse = (\n 'Here is the latest correspondence before the L.A. board (both upcoming and past): '\n )\n alexaResponse += str(result_number\n ) + ': From the ' + replace_with_longform_name(data['results'][0][\n 'department']) + ', '\n alexaResponse += 'on ' + data['results'][0]['date'] + ', '\n alexaResponse += data['results'][0]['title'] + '... '\n alexaResponse += 'You can say text me link or next item'\n session['attributes']['result_number'] = result_number + 1\n session['attributes']['result_url'] = data['results'][0]['url']\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say text me link or next item\"\n )\n card_title = 'LA Board Latest Motions Message'\n greeting_string = alexaResponse\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt_text, False))\n\n\ndef get_next_agenda_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n host = 'http://bos.lacounty.gov/Board-Meeting/Board-Agendas'\n url = host\n page = parse(url)\n nodes = page.xpath(\"//div[a[text()='View Agenda']]\")\n latest_agenda_node = nodes[0]\n headline = latest_agenda_node.find('ul').xpath('string()').strip()\n print(headline)\n agenda_url = latest_agenda_node.find('a[@href]').attrib['href']\n print('http://bos.lacounty.gov' + agenda_url)\n agenda_heading = headline\n session['attributes']['result_url'\n ] = 'http://bos.lacounty.gov' + agenda_url\n card_title = 'Agenda'\n greeting_string = ('I have a link for the ' + agenda_heading +\n \". Say text me and I'll send it to you.\")\n reprompt = 'Say text me to receive a link to the agenda.'\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt, False))\n\n\ndef text_url_to_number(session, intent):\n if 'phone_number' not in session['attributes'] and 'value' not in intent[\n 'slots']['phoneNumber']:\n greeting_string = (\n 'Say your nine digit phone number, including the area code')\n card_title = \"What's your phone number?\"\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, False))\n else:\n number = intent['slots']['phoneNumber']['value']\n if 'result_url' not in session['attributes']:\n session['attributes']['result_url'\n ] = 'http://portal.lacounty.gov/wps/portal/omd'\n url = session['attributes']['result_url']\n session['attributes']['phone_number'] = number\n sns_client = boto3.client('sns')\n response = sns_client.publish(PhoneNumber='1' + str(number),\n Message=\n \"Thank you for using the LA Board of Supervisors Skill. Here's your URL: \"\n + url)\n greeting_string = 'Sent text message to ' + ' '.join(number)\n card_title = 'Sent motion URL via text message'\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, True))\n\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n session['attributes'] = {}\n print('on_session_started requestId=' + session_started_request[\n 'requestId'] + ', sessionId=' + session['sessionId'])\n\n\ndef handle_session_end_request():\n card_title = 'County of LA Board of Supervisors Skill- Thanks'\n speech_output = (\n 'Thank you for using the County of LA Board of Supervisors Skill. See you next time!'\n )\n should_end_session = True\n return build_response({}, build_speechlet_response(card_title,\n speech_output, None, should_end_session))\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they want \"\"\"\n print('on_launch requestId=' + launch_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n print('on_intent requestId=' + intent_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n if intent_name == 'GetLatestAgendaIntent':\n return get_next_agenda_response(session)\n elif intent_name == 'GetLatestMotionsIntent':\n return get_next_motions_response(session)\n elif intent_name == 'GetNextMotionIntent':\n return get_next_motions_response(session)\n elif intent_name == 'SetPhoneNumberIntent':\n return text_url_to_number(session, intent)\n elif intent_name == 'AMAZON.HelpIntent':\n return get_welcome_response()\n elif intent_name == 'AMAZON.CancelIntent' or intent_name == 'AMAZON.StopIntent':\n return handle_session_end_request()\n else:\n raise ValueError('Invalid intent')\n\n\ndef lambda_handler(event, context):\n print('Test!')\n print('event.session.application.applicationId=' + event['session'][\n 'application']['applicationId'])\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == 'LaunchRequest':\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == 'IntentRequest':\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == 'SessionEndedRequest':\n return handle_session_end_request()\n", "step-4": "import requests\nimport json\nimport boto3\nfrom lxml.html import parse\nCardTitlePrefix = 'Greeting'\n\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n \"\"\"\n Build a speechlet JSON representation of the title, output text, \n reprompt text & end of session\n \"\"\"\n return {'outputSpeech': {'type': 'PlainText', 'text': output}, 'card':\n {'type': 'Simple', 'title': CardTitlePrefix + ' - ' + title,\n 'content': output}, 'reprompt': {'outputSpeech': {'type':\n 'PlainText', 'text': reprompt_text}}, 'shouldEndSession':\n should_end_session}\n\n\ndef build_response(session_attributes, speechlet_response):\n \"\"\"\n Build the full response JSON from the speechlet response\n \"\"\"\n return {'version': '1.0', 'sessionAttributes': session_attributes,\n 'response': speechlet_response}\n\n\ndef get_welcome_response():\n welcome_response = (\n 'Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda.'\n )\n print(welcome_response)\n session_attributes = {}\n card_title = 'Hello'\n speech_output = welcome_response\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say give me latest motions.\"\n )\n should_end_session = True\n return build_response(session_attributes, build_speechlet_response(\n card_title, speech_output, reprompt_text, should_end_session))\n\n\ndef replace_with_longform_name(name):\n if name == 'LASD':\n longformName = \"Los Angeles County Sheriff's Department\"\n elif name == 'DMH':\n longformName = 'Department of Mental Health'\n else:\n longformName = name\n return longformName\n\n\ndef get_next_motions_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n if 'result_number' not in session['attributes']:\n print('Second session attributes are ' + str(session['attributes']))\n session['attributes']['result_number'] = 1\n print('Value is ' + str(session['attributes']['result_number']))\n print('Final session attributes are ' + str(session['attributes']))\n result_number = session['attributes']['result_number']\n host = 'http://api.lacounty.gov'\n url = (host +\n '/searchAPIWeb/searchapi?type=bcsearch&database=OMD&SearchTerm=1&title=1&content=1&PStart='\n + str(result_number) + '&PEnd=' + str(result_number) +\n '&_=1509121047612')\n response = requests.get(url)\n data = json.loads(response.text)\n alexaResponse = ''\n if result_number == 1:\n alexaResponse = (\n 'Here is the latest correspondence before the L.A. board (both upcoming and past): '\n )\n alexaResponse += str(result_number\n ) + ': From the ' + replace_with_longform_name(data['results'][0][\n 'department']) + ', '\n alexaResponse += 'on ' + data['results'][0]['date'] + ', '\n alexaResponse += data['results'][0]['title'] + '... '\n alexaResponse += 'You can say text me link or next item'\n session['attributes']['result_number'] = result_number + 1\n session['attributes']['result_url'] = data['results'][0]['url']\n reprompt_text = (\n \"I'm sorry - I didn't understand. You should say text me link or next item\"\n )\n card_title = 'LA Board Latest Motions Message'\n greeting_string = alexaResponse\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt_text, False))\n\n\ndef get_next_agenda_response(session):\n print('Initial session attributes are ' + str(session['attributes']))\n host = 'http://bos.lacounty.gov/Board-Meeting/Board-Agendas'\n url = host\n page = parse(url)\n nodes = page.xpath(\"//div[a[text()='View Agenda']]\")\n latest_agenda_node = nodes[0]\n headline = latest_agenda_node.find('ul').xpath('string()').strip()\n print(headline)\n agenda_url = latest_agenda_node.find('a[@href]').attrib['href']\n print('http://bos.lacounty.gov' + agenda_url)\n agenda_heading = headline\n session['attributes']['result_url'\n ] = 'http://bos.lacounty.gov' + agenda_url\n card_title = 'Agenda'\n greeting_string = ('I have a link for the ' + agenda_heading +\n \". Say text me and I'll send it to you.\")\n reprompt = 'Say text me to receive a link to the agenda.'\n return build_response(session['attributes'], build_speechlet_response(\n card_title, greeting_string, reprompt, False))\n\n\ndef text_url_to_number(session, intent):\n if 'phone_number' not in session['attributes'] and 'value' not in intent[\n 'slots']['phoneNumber']:\n greeting_string = (\n 'Say your nine digit phone number, including the area code')\n card_title = \"What's your phone number?\"\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, False))\n else:\n number = intent['slots']['phoneNumber']['value']\n if 'result_url' not in session['attributes']:\n session['attributes']['result_url'\n ] = 'http://portal.lacounty.gov/wps/portal/omd'\n url = session['attributes']['result_url']\n session['attributes']['phone_number'] = number\n sns_client = boto3.client('sns')\n response = sns_client.publish(PhoneNumber='1' + str(number),\n Message=\n \"Thank you for using the LA Board of Supervisors Skill. Here's your URL: \"\n + url)\n greeting_string = 'Sent text message to ' + ' '.join(number)\n card_title = 'Sent motion URL via text message'\n reprompt_text = (\n \"I didn't understand. Please say your nine digit mobile phone number.\"\n )\n return build_response(session['attributes'],\n build_speechlet_response(card_title, greeting_string,\n reprompt_text, True))\n\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n session['attributes'] = {}\n print('on_session_started requestId=' + session_started_request[\n 'requestId'] + ', sessionId=' + session['sessionId'])\n\n\ndef handle_session_end_request():\n card_title = 'County of LA Board of Supervisors Skill- Thanks'\n speech_output = (\n 'Thank you for using the County of LA Board of Supervisors Skill. See you next time!'\n )\n should_end_session = True\n return build_response({}, build_speechlet_response(card_title,\n speech_output, None, should_end_session))\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they want \"\"\"\n print('on_launch requestId=' + launch_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n print('on_intent requestId=' + intent_request['requestId'] +\n ', sessionId=' + session['sessionId'])\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n if intent_name == 'GetLatestAgendaIntent':\n return get_next_agenda_response(session)\n elif intent_name == 'GetLatestMotionsIntent':\n return get_next_motions_response(session)\n elif intent_name == 'GetNextMotionIntent':\n return get_next_motions_response(session)\n elif intent_name == 'SetPhoneNumberIntent':\n return text_url_to_number(session, intent)\n elif intent_name == 'AMAZON.HelpIntent':\n return get_welcome_response()\n elif intent_name == 'AMAZON.CancelIntent' or intent_name == 'AMAZON.StopIntent':\n return handle_session_end_request()\n else:\n raise ValueError('Invalid intent')\n\n\ndef lambda_handler(event, context):\n print('Test!')\n print('event.session.application.applicationId=' + event['session'][\n 'application']['applicationId'])\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == 'LaunchRequest':\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == 'IntentRequest':\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == 'SessionEndedRequest':\n return handle_session_end_request()\n", "step-5": "# -*- coding: utf-8 -*-\nimport requests\nimport json\nimport boto3\nfrom lxml.html import parse\n\nCardTitlePrefix = \"Greeting\"\n\ndef build_speechlet_response(title, output, reprompt_text, should_end_session):\n \"\"\"\n Build a speechlet JSON representation of the title, output text, \n reprompt text & end of session\n \"\"\"\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': output\n },\n 'card': {\n 'type': 'Simple',\n 'title': CardTitlePrefix + \" - \" + title,\n 'content': output\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n \ndef build_response(session_attributes, speechlet_response):\n \"\"\"\n Build the full response JSON from the speechlet response\n \"\"\"\n return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\ndef get_welcome_response():\n welcome_response= \"Welcome to the L.A. Board of Supervisors Skill. You can say, give me recent motions or give me the latest agenda.\"\n print(welcome_response);\n\n session_attributes = {}\n card_title = \"Hello\"\n speech_output = welcome_response;\n # If the user either does not reply to the welcome message or says something\n # that is not understood, they will be prompted again with this text.\n reprompt_text = \"I'm sorry - I didn't understand. You should say give me latest motions.\"\n should_end_session = True\n return build_response(session_attributes, build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))\n\ndef replace_with_longform_name(name):\n\n if name == \"LASD\":\n longformName = \"Los Angeles County Sheriff's Department\"\n elif name == \"DMH\":\n longformName = \"Department of Mental Health\"\n else:\n longformName = name;\n\n return longformName;\n\n\ndef get_next_motions_response(session):\n \n print(\"Initial session attributes are \"+str(session['attributes']));\n\n if \"result_number\" not in session['attributes']:\n print(\"Second session attributes are \"+str(session['attributes']));\n session['attributes']['result_number'] = 1;\n print(\"Value is \"+str(session['attributes']['result_number']));\n print(\"Final session attributes are \"+str(session['attributes']))\n\n result_number = session['attributes']['result_number'];\n host = \"http://api.lacounty.gov\";\n\n url = host + \"/searchAPIWeb/searchapi?type=bcsearch&database=OMD&\" \\\n \"SearchTerm=1&title=1&content=1&PStart=\" + str(result_number) +\"&PEnd=\" + str(result_number) +\"&_=1509121047612\"\n\n response = requests.get(url);\n #print(response.text);\n data = json.loads(response.text)\n\n alexaResponse = \"\";\n if(result_number == 1):\n alexaResponse = \"Here is the latest correspondence before the L.A. board (both upcoming and past): \"\n\n alexaResponse += str(result_number)+\": From the \"+replace_with_longform_name(data[\"results\"][0][\"department\"])+ \", \"\n alexaResponse += \"on \"+data[\"results\"][0][\"date\"]+\", \"\n alexaResponse += data[\"results\"][0][\"title\"]+\"... \"\n \n alexaResponse += \"You can say text me link or next item\"\n \n session['attributes']['result_number'] = result_number + 1;\n session['attributes']['result_url'] = data[\"results\"][0][\"url\"];\n \n #text_url_to_number(session);\n reprompt_text = \"I'm sorry - I didn't understand. You should say text me link or next item\"\n \n card_title = \"LA Board Latest Motions Message\";\n greeting_string = alexaResponse;\n return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, False))\n \ndef get_next_agenda_response(session):\n \n print(\"Initial session attributes are \"+str(session['attributes']));\n \n host = \"http://bos.lacounty.gov/Board-Meeting/Board-Agendas\";\n url = host;\n page = parse(url)\n nodes = page.xpath(\"//div[a[text()='View Agenda']]\");\n latest_agenda_node = nodes[0];\n headline = latest_agenda_node.find(\"ul\").xpath(\"string()\").strip();\n \n print(headline);\n agenda_url = latest_agenda_node.find(\"a[@href]\").attrib['href'];\n print(\"http://bos.lacounty.gov\"+agenda_url)\n \n agenda_heading = headline;\n #session['attributes']['result_url']\n session['attributes']['result_url'] = \"http://bos.lacounty.gov\"+agenda_url;\n card_title = \"Agenda\";\n greeting_string = \"I have a link for the \"+agenda_heading+\". Say text me and I'll send it to you.\";\n reprompt = \"Say text me to receive a link to the agenda.\"\n\n return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt, False))\n \n \ndef text_url_to_number(session, intent):\n \n if \"phone_number\" not in session['attributes'] and \"value\" not in intent['slots']['phoneNumber']:\n greeting_string = \"Say your nine digit phone number, including the area code\";\n card_title = \"What's your phone number?\";\n reprompt_text = \"I didn't understand. Please say your nine digit mobile phone number.\"\n return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, False))\n else:\n number = intent['slots']['phoneNumber']['value'];\n if \"result_url\" not in session['attributes']:\n session['attributes']['result_url'] = 'http://portal.lacounty.gov/wps/portal/omd';\n \n url = session['attributes']['result_url'];\n session['attributes']['phone_number'] = number;\n \n sns_client = boto3.client('sns')\n response = sns_client.publish(\n PhoneNumber='1'+str(number), \n Message=\"Thank you for using the LA Board of Supervisors Skill. Here's your URL: \"+url\n )\n greeting_string = \"Sent text message to \"+ \" \".join(number);\n card_title = \"Sent motion URL via text message\";\n reprompt_text = \"I didn't understand. Please say your nine digit mobile phone number.\"\n return build_response(session['attributes'], build_speechlet_response(card_title, greeting_string, reprompt_text, True))\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n \n #session.attributes['result_number'] = 1\n session['attributes'] = {}\n print(\"on_session_started requestId=\" + session_started_request['requestId']\n + \", sessionId=\" + session['sessionId'])\n\ndef handle_session_end_request():\n card_title = \"County of LA Board of Supervisors Skill- Thanks\"\n speech_output = \"Thank you for using the County of LA Board of Supervisors Skill. See you next time!\"\n should_end_session = True\n return build_response({}, build_speechlet_response(card_title, speech_output, None, should_end_session));\n \ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they want \"\"\"\n print(\"on_launch requestId=\" + launch_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # Dispatch to your skill's launch\n return get_welcome_response()\n \ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n \n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n # Dispatch to your skill's intent handlers\n if intent_name == \"GetLatestAgendaIntent\":\n return get_next_agenda_response(session)\n elif intent_name == \"GetLatestMotionsIntent\":\n return get_next_motions_response(session)\n elif intent_name == \"GetNextMotionIntent\":\n return get_next_motions_response(session)\n elif intent_name == \"SetPhoneNumberIntent\":\n return text_url_to_number(session, intent);\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n raise ValueError(\"Invalid intent\")\n\ndef lambda_handler(event, context):\n print(\"Test!\")\n \n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n \n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return handle_session_end_request()\n", "step-ids": [ 8, 11, 13, 14, 15 ] }
[ 8, 11, 13, 14, 15 ]