{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport requests\nfrom IPython.display import Image as Ima\nfrom IPython.display import clear_output, display\nfrom PIL import Image as Im\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\nimport joblib\nimport matplotlib.pyplot as plt\nimport json\nimport base64\nimport shutil\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ndir_name = \"/kaggle/input/ai-village-ctf\"\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# A helper function for tracking flags. You could do it yourself, but why?\n\ndef add_flag(challenge_id: str, flag: str) -> str:\n    try:\n        submission_path = \"/kaggle/working/submission.csv\"\n        template_path = f\"{dir_name}/submission.csv\"\n        if not os.path.isfile(submission_path) :\n            shutil.copyfile(template_path, submission_path)\n        flags = pd.read_csv(submission_path, index_col=\"challenge_id\")\n        valid = flags.index.to_list()\n        if challenge_id in valid:\n            flags.at[challenge_id] = flag\n            flags.to_csv(submission_path)\n            print(\"Flag saved. If you want to update the scoreboard, click 'submit' on the right. Remember that you can only update your score on the scoreboard 50 times per day\")\n        else:\n            print(\"Invalid challenge_id\")\n    except:\n        print(\"We had trouble saving that flag. Keep a copy of it and contact the CTF organizers.\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math\n\n# **Just use DBSCAN and PCA to get the clusters and the dimensions for each task.**","metadata":{}},{"cell_type":"markdown","source":"# Math Challenge 1 (id: math_1) -- 100 Points\n\nHow many clusters are in the clusters1.npy, clusters2.npy, and clusters3.npy? The key is the number of clusters in order, with no spaces. These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"from sklearn.cluster import DBSCAN\n\ncl1 = np.load('../input/ai-village-ctf/math/clusters1.npy')\ncl2 = np.load('../input/ai-village-ctf/math/clusters2.npy')\ncl3 = np.load('../input/ai-village-ctf/math/clusters3.npy')\n\nclustering = DBSCAN(eps=3, min_samples=2).fit(cl1)\nprint(f'The number of clusters is {len([x for x in np.unique(clustering.labels_) if x != -1])}')\n\nclustering = DBSCAN(eps=3, min_samples=2).fit(cl2)\nprint(f'The number of clusters is {len([x for x in np.unique(clustering.labels_) if x != -1])}')\n\nclustering = DBSCAN(eps=3, min_samples=2).fit(cl3)\nprint(f'The number of clusters is {len([x for x in np.unique(clustering.labels_) if x != -1])}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_1\", \"submission\": \"523\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_1\", \"P53KN21HAYB03VIOC8PMNRH2Z9A{JNS9PNLOW630W01UXWE4WVAL1WWL6TR6YF96}KTCDDFVEGU7T23A476NG7FGFH0DI3LTDLA4IDEHH70VSE2V4SCCK7IFHSZUI4OG\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 2 (id: math_2) -- 200 Points\n\nWhat's the dimensionality of the data in first_dim1.npy, first_dim2.npy, and first_dim3.npy? The key is the number of dimensions in order, with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"from sklearn.decomposition import PCA\n\ndm1 = np.load('../input/ai-village-ctf/math/first_dim1.npy')\ndm2 = np.load('../input/ai-village-ctf/math/first_dim2.npy')\ndm3 = np.load('../input/ai-village-ctf/math/first_dim3.npy')\n\npca = PCA(n_components='mle')\npca.fit(dm1)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(dm2)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(dm3)\nprint(f'The number of dimensions is {pca.n_components_}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_2\", \"submission\": \"354\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_2\", \"HKOJNPGIYOP0FN9K49PFXBX1VL}EPIO0JBLA6Y849LT3JX5B4FSCX6CRAN0MF9GDA6952IHJ4ZFC5TZRSSJORFCBXLHH4G3TAPKTZURMKX1GZXXX9{ML7WFOAP9SVFPZ\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 3 (id: math_3) -- 300 Points\n\nWhat's the dimensionality of the data in second_dim1.npy, second_dim2.npy, and second_dim3.npy? The key is the number of the dimensionality in order, with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"from sklearn.decomposition import PCA\n\ndm1 = np.load('../input/ai-village-ctf/math/second_dim1.npy')\ndm2 = np.load('../input/ai-village-ctf/math/second_dim2.npy')\ndm3 = np.load('../input/ai-village-ctf/math/second_dim3.npy')\n\npca = PCA(n_components='mle')\npca.fit(dm1)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(dm2)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(dm3)\nprint(f'The number of dimensions is {pca.n_components_}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_3\", \"submission\": \"474\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_3\", \"3QLRLHF9ZH93FBHDUW5OJ6UOX}{11L35ADMPMKR5Z44J7JO2KNC0H86HPLWW1TYRYDILJJLAMIH_3RWMD0SHAVVIQEIK2TOA74DA3PEY4DRDPGFVJP7L5TDXCVTME2GD\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Math Challenge 4 (id: math_4) -- 400 Points\n\nWhat's the dimensionality of the clusters in clusters1.npy? The key is the dimensions ordered by cluster size (smallest to largest), with no spaces.  These files are available in the input directory under `math`.","metadata":{}},{"cell_type":"code","source":"cl1 = np.load('../input/ai-village-ctf/math/clusters1.npy')\ncl1 = pd.DataFrame(cl1)\n\ncl1['cluster'] = DBSCAN(eps=3, min_samples=2).fit_predict(cl1)\n\npca = PCA(n_components='mle')\npca.fit(cl1[cl1['cluster'] == 0].iloc[:, :-1])\nprint(cl1[cl1['cluster'] == 0].iloc[:, :-1].shape)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(cl1[cl1['cluster'] == 1].iloc[:, :-1])\nprint(cl1[cl1['cluster'] == 1].iloc[:, :-1].shape)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(cl1[cl1['cluster'] == 2].iloc[:, :-1])\nprint(cl1[cl1['cluster'] == 2].iloc[:, :-1].shape)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components=0.99, svd_solver='full')\npca.fit(cl1[cl1['cluster'] == 3].iloc[:, :-1])\nprint(cl1[cl1['cluster'] == 3].iloc[:, :-1].shape)\nprint(f'The number of dimensions is {pca.n_components_}')\n\npca = PCA(n_components='mle')\npca.fit(cl1[cl1['cluster'] == 4].iloc[:, :-1])\nprint(cl1[cl1['cluster'] == 4].iloc[:, :-1].shape)\nprint(f'The number of dimensions is {pca.n_components_}')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Submission Helper\n\ntry:\n    r = requests.post(\"http://flags.fly.dev:5000/score\", json=json.dumps({\"challenge_id\": \"math_4\", \"submission\": \"54312\"}))\n    print(r.text)\nexcept requests.exceptions.ConnectionError:\n    print(\"Connection problems. Contact the CTF organizers.\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"add_flag(\"math_4\", \"PX1TQHGV2QFMWEO3FVMJ8FMVLNMHL8WQVA6}PBY78HMOJ9KOPC3TMEIX5HXJ6NI20HI5AFRM8V55QV2UNSVXK1MC8QKL2Y59S7G{M9K4YRSQVJ22AFYTQWWOA475ISZF\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}