diff --git "a/1426.jsonl" "b/1426.jsonl"
new file mode 100644--- /dev/null
+++ "b/1426.jsonl"
@@ -0,0 +1,403 @@
+{"seq_id": "636071317", "text": "# Copyright (c) 2018, INRIA\n# Copyright (c) 2018, University of Lille\n# All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nimport pytest\nimport datetime\nfrom powerapi.report_model.hwpc_model import HWPCModel, BadInputData\n\n@pytest.fixture()\ndef hwpc_model():\n \"\"\"\n :return: HWPCModel\n \"\"\"\n return HWPCModel()\n\n##############################################################################\n# Tests #\n##############################################################################\n\n####################\n# MongoDB\n####################\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"_id\": \"fake-id\",\n \"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"groups\": {}})\n]\n)\ndef test_convert_hwpc_report_from_mongodb_work(hwpc_model, json_input):\n \"\"\"\n Test working input for HWPCReport from_mongodb\n :param json_input: Data in input\n \"\"\"\n hwpc_model.from_mongodb(json_input)\n assert True\n\n\n####################\n# CsvDB\n####################\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0,\n \"cpu\": 0,\n \"event1\": 1000,\n \"event2\": 2000}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0,\n \"cpu\": 0}),\n]\n)\ndef test_convert_hwpc_report_from_csvdb_work(hwpc_model, json_input):\n \"\"\"\n :param json_input: Data in input\n \"\"\"\n hwpc_model.from_mongodb(json_input)\n assert True\n\n\n@pytest.mark.parametrize(\"json_input\", [\n ({\"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\"}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"socket\": 0}),\n ({\"timestamp\": datetime.datetime.now().timestamp(),\n \"sensor\": \"fake-sensor\",\n \"target\": \"fake-target\",\n \"cpu\": 0}),\n]\n)\ndef test_hwpc_report_from_csvdb_fail(hwpc_model, json_input):\n \"\"\"\n :param json_input: Data in input\n \"\"\"\n with pytest.raises(BadInputData):\n hwpc_model.from_csvdb(\"fake-name\", json_input)\n", "sub_path": "tests/unit/report_model/test_hwpc_report_model.py", "file_name": "test_hwpc_report_model.py", "file_ext": "py", "file_size_in_byte": 4028, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "powerapi.report_model.hwpc_model.HWPCModel", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 33, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 49, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 49, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 51, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 71, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 71, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 72, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 72, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 79, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 118, "usage_type": "call"}, {"api_name": "powerapi.report_model.hwpc_model.BadInputData", "line_number": 118, "usage_type": "argument"}, {"api_name": "pytest.mark.parametrize", "line_number": 94, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 94, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 97, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 97, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 99, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 99, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 101, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 101, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 104, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 108, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 108, "usage_type": "attribute"}]}
+{"seq_id": "212777789", "text": "# Copyright 2021 UW-IT, University of Washington\n# SPDX-License-Identifier: Apache-2.0\n\nfrom django.conf import settings\n\n\ndef SameSiteMiddleware(get_response):\n def middleware(request):\n # See:\n # https://blog.chromium.org/2019/10/developers-get-ready-for-new.html\n # https://github.com/django/django/pull/11894\n # https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients\n # https://www.chromium.org/updates/same-site/incompatible-clients\n\n # TLDR: Chrome (and soon Firefox and Safari) require that you set\n # SameSite=None\n # in order to have a cookie set cross-domain. The old behavior of\n # SameSite\n # being 'None' by default is no more. The new default is 'Lax'.\n # The issue is that we can't just set SameSite=None and be\n # done with it,\n # because some older browsers will break with this. Therefore we devise\n # a two-cookie approach: one that does the new behavior of setting\n # SameSite=None, and the second is the \"legacy\" cookie which relies on\n # the old-default's behavior. If we receive only the legacy cookie in\n # a request, we know we're dealing with one of those older browsers,\n # and we can repair the lost cookie before proceeding to process the\n # request.\n cookie = settings.SESSION_COOKIE_NAME\n legacy = \"{}_legacy\".format(cookie)\n\n if legacy in request.COOKIES:\n if cookie not in request.COOKIES:\n request.COOKIES[cookie] = request.COOKIES[legacy]\n del request.COOKIES[legacy]\n\n response = get_response(request)\n\n if cookie in response.cookies:\n response.cookies[legacy] = response.cookies[cookie].value\n # set Expiry, Path, etc.\n response.cookies[legacy].update(response.cookies[cookie])\n response.cookies[cookie]['samesite'] = 'None'\n if settings.SESSION_COOKIE_SECURE and not \\\n response.cookies[cookie].get('secure', False):\n # Fix Django's silly `delete_cookie()` behavior which doesn't\n # set `secure` correctly.\n response.cookies[cookie]['secure'] = True\n\n return response\n\n return middleware\n", "sub_path": "cohort_manager/middleware/same_site_middleware.py", "file_name": "same_site_middleware.py", "file_ext": "py", "file_size_in_byte": 2283, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.settings.SESSION_COOKIE_NAME", "line_number": 29, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 29, "usage_type": "name"}, {"api_name": "django.conf.settings.SESSION_COOKIE_SECURE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 44, "usage_type": "name"}]}
+{"seq_id": "561167796", "text": "from django.shortcuts import render,HttpResponse,HttpResponseRedirect\nfrom django.conf import settings\nfrom shop.models import Order\nfrom django.contrib.auth.decorators import login_required\n\n@login_required(login_url='/')\ndef my_orders(request):\n order=Order.objects.filter(contact=request.user)\n template_name = \"myorders.html\"\n return render(request, template_name, {'order':order})\n\n@login_required(login_url='/')\ndef cancel_orders(request,order_id):\n\n order=Order.objects.filter(contact=request.user,id=int(order_id))\n if order:\n os=OrderStatus()\n os.order=order[0]\n os.status=\"Cancelled\"\n os.save()\n return HttpResponseRedirect(\"/accounts/myorders/\")\n\n", "sub_path": "accounts/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 690, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "shop.models.Order.objects.filter", "line_number": 8, "usage_type": "call"}, {"api_name": "shop.models.Order.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "shop.models.Order", "line_number": 8, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 10, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 6, "usage_type": "call"}, {"api_name": "shop.models.Order.objects.filter", "line_number": 15, "usage_type": "call"}, {"api_name": "shop.models.Order.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "shop.models.Order", "line_number": 15, "usage_type": "name"}, {"api_name": "django.shortcuts.HttpResponseRedirect", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 12, "usage_type": "call"}]}
+{"seq_id": "520520382", "text": "# -*- coding: latin_1 -*-\r\n\r\nimport psycopg2\r\nimport os\r\nimport datetime\r\nimport platform\r\nimport sys\r\n\r\nsys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))\r\nfrom shared.sendmail import send_mail\r\nfrom shared.printAndLog import printAndLog\r\n\r\nimport shared.databrugisconf as DBRUC\r\nimport shared.ordoconf as OCONF\r\n\r\n################################################################################\r\n\r\nif __name__ == \"__main__\":\r\n wfstepId = OCONF.getWorkflowID() \r\n mode = OCONF.getExecMode()\r\n dlevel = OCONF.getDebugLevel()\r\n OCONF.tokenFileWriteRunning(wfstepId)\r\n try:\r\n logFileName = \"{}-{}.log\".format(os.path.basename(__file__).replace('.py', ''),datetime.date.today().strftime('%d_%m_%Y'))\r\n with open(os.path.join(DBRUC._mailDir, logFileName), 'a') as logFile:\r\n dbName = DBRUC._db_dbname\r\n printAndLog( \"{} running\".format(wfstepId),logFile)\r\n printAndLog(\"Startup queryFDW\", logFile)\r\n \r\n conn_s = \"dbname='{}' user='{}' host='{}' password='{}'\".format(dbName,\r\n DBRUC._db_user,\r\n DBRUC._prod_db_host,\r\n DBRUC._db_password)\r\n \r\n if dlevel == 'V':\r\n printAndLog(\"Connection string {}\".format(conn_s), logFile)\r\n if mode == \"EMUL\":\r\n printAndLog(\"EMULATION MODE\", logFile)\r\n OCONF.tokenFileWriteDone(wfstepId) \r\n exit()\r\n conn = psycopg2.connect(conn_s)\r\n \r\n if dlevel == 'V':\r\n printAndLog(\"After connect\", logFile)\r\n \r\n cur = conn.cursor()\r\n cur.execute(\"SELECT commonbrugis.wf_intextintra_1synchro()\")\r\n conn.commit()\r\n\r\n printAndLog( \"{} done\".format(wfstepId),logFile)\r\n if DBRUC._sendMail:\r\n nodename = platform.node()\r\n send_mail('%s - %s - log - %s' % (nodename, os.path.basename(__file__), str(datetime.datetime.today())), logFile.read())\r\n OCONF.tokenFileWriteDone(wfstepId) \r\n except:\r\n OCONF.tokenFileWriteFail(wfstepId)\r\n \r\n \r\n", "sub_path": "bdm_ordo/env_prod/queryFDW.py", "file_name": "queryFDW.py", "file_ext": "py", "file_size_in_byte": 2347, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.path.append", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "os.pardir", "line_number": 9, "usage_type": "attribute"}, {"api_name": "shared.ordoconf.getWorkflowID", "line_number": 19, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 19, "usage_type": "name"}, {"api_name": "shared.ordoconf.getExecMode", "line_number": 20, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 20, "usage_type": "name"}, {"api_name": "shared.ordoconf.getDebugLevel", "line_number": 21, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 21, "usage_type": "name"}, {"api_name": "shared.ordoconf.tokenFileWriteRunning", "line_number": 22, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 22, "usage_type": "name"}, {"api_name": "os.path.basename", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 24, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf._mailDir", "line_number": 25, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 25, "usage_type": "name"}, {"api_name": "shared.databrugisconf._db_dbname", "line_number": 26, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 26, "usage_type": "name"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 27, "usage_type": "call"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 28, "usage_type": "call"}, {"api_name": "shared.databrugisconf._db_user", "line_number": 31, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 31, "usage_type": "name"}, {"api_name": "shared.databrugisconf._prod_db_host", "line_number": 32, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 32, "usage_type": "name"}, {"api_name": "shared.databrugisconf._db_password", "line_number": 33, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 33, "usage_type": "name"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 36, "usage_type": "call"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 38, "usage_type": "call"}, {"api_name": "shared.ordoconf.tokenFileWriteDone", "line_number": 39, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 39, "usage_type": "name"}, {"api_name": "psycopg2.connect", "line_number": 41, "usage_type": "call"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 44, "usage_type": "call"}, {"api_name": "shared.printAndLog.printAndLog", "line_number": 50, "usage_type": "call"}, {"api_name": "shared.databrugisconf._sendMail", "line_number": 51, "usage_type": "attribute"}, {"api_name": "shared.databrugisconf", "line_number": 51, "usage_type": "name"}, {"api_name": "platform.node", "line_number": 52, "usage_type": "call"}, {"api_name": "shared.sendmail.send_mail", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "datetime.datetime.today", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "attribute"}, {"api_name": "shared.ordoconf.tokenFileWriteDone", "line_number": 54, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 54, "usage_type": "name"}, {"api_name": "shared.ordoconf.tokenFileWriteFail", "line_number": 56, "usage_type": "call"}, {"api_name": "shared.ordoconf", "line_number": 56, "usage_type": "name"}]}
+{"seq_id": "651961062", "text": "import argparse\nimport h5py\nimport merge\nimport numpy as np\nimport mpi_init\nimport subfind_data\nimport volume_read\nimport halo_properties as hp\n\n\ndef measure_profile_properties(mpi, path, snap, extent=5.0, R200scale=True, Nbins=25):\n \"\"\"\n Compute various profiles and quantities for halos above given mass\n\n Arguments:\n -mpi : MPI environment class instance\n -path : Path to simulation of interest\n -snap : Snapshot of interest\n -extent : Extent of the radial profiles\n -R200scale : BOOLEAN - if True: profiles extend EXTENT * R200, else [Mpc]\n -Nbins : NUmber of bins in the radial profile\n \"\"\"\n\n # First, rebuild the Subfind table for this snapshot\n subfind_table = subfind_data.build_table(mpi, sim=path, snap=snap)\n\n # Load the entire volume\n volume = volume_read.entire_snapshot_read(mpi, sim=path, snap=snap)\n\n # Read specified datasets, compute desired quantities, clean up\n required_datasets = [\n \"PartType1/Coordinates\",\n \"PartType1/Masses\",\n \"PartType1/Velocities\",\n ]\n volume.read_datasets(mpi, required_datasets)\n volume.tag_subhalo_particles(mpi, subfind_table)\n\n # Now select halos of interest\n subfind_table.select_halos(mpi, cut=1.0e12)\n if not mpi.Rank:\n print(\" > Found {0:d} halo(s)\".format(len(subfind_table.tags)), flush=True)\n\n # Initiate halo class, distribute required particles to tasks, store\n h = hp.halo(volume, Nbins=Nbins)\n\n h.halo_data_store(mpi, subfind_table, volume, Extent=extent, R200scale=R200scale)\n del subfind_table, volume\n\n # Now loop over haloes that were sent to my task\n hk = sorted(h.halo_data.keys())\n if not mpi.Rank:\n print(\" > Computing halo properties\", flush=True)\n for j in range(0, len(hk), 1):\n if not mpi.Rank:\n print(\" -{0}\".format(hk[j]), flush=True)\n\n h.set_up_halo(mpi, hk[j])\n\n # Compute mass profiles\n h.compute_mass_profiles(mpi)\n\n # Velocities and non-thermal pressure profiles\n h.compute_velocities_and_non_thermal_pressure(mpi)\n\n # Centre of mass offset\n h.compute_centre_of_mass_offset(mpi)\n\n # Compute NFW concentration - 1 parameter fit\n h.compute_concentration(mpi)\n\n # DM surface pressure\n h.compute_DM_surface_pressure(mpi)\n\n # Cumulative shape measurements\n h.compute_shape(mpi, aperture=\"500\", ptype=\"DM\")\n h.compute_shape(mpi, aperture=\"200\", ptype=\"DM\")\n h.compute_shape(mpi, aperture=\"Vir\", ptype=\"DM\")\n\n # Dark matter shape profile\n h.compute_shape_profile(mpi, ptype=\"DM\")\n\n # Store halo properties in HDF5 file\n h.save(mpi)\n\n # Now merge files\n mpi.comm.Barrier()\n if not mpi.Rank:\n ftag = \"{0}_Snap{1:03d}_z{2:d}p{3:02d}\".format(\n h.fname,\n h.snap,\n int(h.redshift),\n int(100.0 * (h.redshift - int(h.redshift))),\n )\n merge.merge_outputs(ftag)\n mpi.comm.Barrier()\n del h\n return\n\n\nif __name__ == \"__main__\":\n\n # Parse command-line options -- deals with missing arguments!\n parser = argparse.ArgumentParser(\n description=\"TNG analysis script to produce radial profiles\"\n )\n parser.add_argument(\n \"start\", action=\"store\", type=int, help=\"First snapshot to process\"\n )\n parser.add_argument(\n \"final\", action=\"store\", type=int, help=\"Final snapshot to process\"\n )\n inputs = parser.parse_args()\n\n # Simulation of interest\n paths = [\"/n/hernquistfs3/IllustrisTNG/Runs/L75n910TNG_DM/output\"]\n\n # Snapshots of interest\n snapshots = np.arange(inputs.final - inputs.start + 1) + inputs.start\n\n # Initialize MPI environment\n mpi = mpi_init.mpi()\n\n # Loop over sims and snapshots measuring profiles\n for x in paths:\n for y in snapshots:\n if not mpi.Rank:\n print(\"--- SNAPSHOT {0:03d} ---\".format(y), flush=True)\n measure_profile_properties(mpi, x, y)\n", "sub_path": "Examples/DMO100.py", "file_name": "DMO100.py", "file_ext": "py", "file_size_in_byte": 4027, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "subfind_data.build_table", "line_number": 25, "usage_type": "call"}, {"api_name": "volume_read.entire_snapshot_read", "line_number": 28, "usage_type": "call"}, {"api_name": "halo_properties.halo", "line_number": 45, "usage_type": "call"}, {"api_name": "merge.merge_outputs", "line_number": 95, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 119, "usage_type": "call"}, {"api_name": "mpi_init.mpi", "line_number": 122, "usage_type": "call"}]}
+{"seq_id": "206999191", "text": "# -*-coding:Utf-8 -*\n\n#########################################################################\n#\n#Programme en python permettant d'exploiter les résultats d'analyse\n#d'un écoulement de liquide dans une conduite grâce au programme TracTrac\n#exploité sur Matlab. La matrice 'Pts' fut exportée en .csv\n#\n##########################################################################\n\n\n#-- importation des bibliothèques --\n\nimport numpy as np\nimport csv\nimport matplotlib.pyplot as plt\n\n#-- Variables --\n\n#largeur de la conduite en pixel et subdivision en intervalles de cette largeur\nlargeur=1000\nsubdi=20\nfichier_entree=\"resultats-matlab/tractrac120.csv\"\nfichier_sortie=\"resultats-python/res120-max.csv\"\n\n#-- Programme --\n\n\n#Creation d'une matrice \"results\" à partir du fichier .csv\n#Chaque ligne correspond à une particule à un certain moment\nresults = []\nwith open(fichier_entree) as csvfile:\n reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)\n for row in reader:\n results.append(row)\n\n\ninter=largeur//subdi\n\n#Matrice 'réduction' de 2 colonnes et n lignes correspondants à la matrice résults\nreduction = np.zeros(shape=(len(results),2))\n\n#Matrice 'somme' de 2 lignes et n colonnes correspondants aux intervalles\nsomme = np.zeros(shape=(2,inter))\n\n#Matrice finale\nfinal = np.zeros(shape=(inter))\n\n#On réduit la matrice résults de 11 colonnes pour n'en faire plus que 2\n#Ces deux colonnes restantes correspondent à la position verticale et la vitesse\ni=0\nfor x in results:\n reduction[i][0]=x[3]\n reduction[i][1]=x[4]\n i+=1\n\n#On calcule la variable position qui correspond à la postion de la particule en pixel divisé\n#par la subdivision en intervalles.\n#Ainsi, la ligne 0 de la matrice correspond aux nombres de particules détectées pour toutes les images pour chaque intervalle\n#La ligne 1 correspond à la somme des vitesses pour les particules d'un intervalle donné.\ni=0\nfor x in reduction:\n position=reduction[i][0]//subdi\n position=int(position)\n somme[1][position-1]+=reduction[i][1]\n somme[0][position-1]+=1\n i+=1\n\n#La matrice finale correspond à la moyenne des vitesses. On fait la somme totale des vitesses divisé par le nombre de particules\n#pour chaque intervalle. On vérifie qu'il n'y a pas de division par 0 (s'il y a 0 particules détectées).\ni=0\nfor i in range(inter):\n if float(somme[0][i])==0.0:\n continue\n \n final[i]=abs(float(somme[1][i])/float(somme[0][i]))\n i+=1\n\n\nprint(final)\n\n#On sauvegarde la matrice finale dans un .csv\nnp.savetxt(fichier_sortie, final, delimiter=\",\", fmt='%1.4f')\n\n#On affiche le résultat\nplt.plot(final)\nplt.show()", "sub_path": "ecoulement_fluide.py", "file_name": "ecoulement_fluide.py", "file_ext": "py", "file_size_in_byte": 2644, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "csv.reader", "line_number": 33, "usage_type": "call"}, {"api_name": "csv.QUOTE_NONNUMERIC", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 83, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 87, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 87, "usage_type": "name"}]}
+{"seq_id": "542800730", "text": "import tornado.web\nimport json\nfrom decorators.handleException import handleException\nfrom decorators.checkAuthentication import checkAuthentication\nfrom utils.logger import Logger\nfrom handlers import base\nfrom exceptions import exceptions\nfrom services.pedirCuentaService import PedirCuentaService \n\nlogger = Logger('pedirCuentaHandler')\n\nclass PedirCuentaHandler(base.BaseHandler):\n\n @tornado.web.asynchronous\n @handleException\n def options(self, restaurante):\n self.finish()\n \n @tornado.web.asynchronous\n @handleException\n @checkAuthentication\n def post(self, restaurante):\n logger.debug('post')\n try:\n data = json.loads(self.request.body)\n logger.debug('body:{}'.format(data))\n # idsPedidos = data['cuenta']['ids_pedidos']\n idRestaurante = data['cuenta']['id_restaurante']\n idMesa = data['cuenta']['id_mesa']\n pedidos = data['cuenta']['pedidos']\n # if not isinstance(idsPedidos, list):\n # raise Exception('idsPedidos no es un array')\n \n except Exception as e:\n logger.error('Body incorrecto, exception: : {}'.format(e) + ' body: {}'.format(self.request.body))\n raise exceptions.BadRequest(3001)\n svc = PedirCuentaService()\n svc.pedirCuenta(idRestaurante, idMesa)\n # logger.debug('pedidos:{}'.format(pedidos))\n svc.actualizarPedidos(pedidos, 'finalizado')\n self.finish({})", "sub_path": "byewait/src/handlers/pedirCuentaHandler.py", "file_name": "pedirCuentaHandler.py", "file_ext": "py", "file_size_in_byte": 1492, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "utils.logger.Logger", "line_number": 10, "usage_type": "call"}, {"api_name": "handlers.base.BaseHandler", "line_number": 12, "usage_type": "attribute"}, {"api_name": "handlers.base", "line_number": 12, "usage_type": "name"}, {"api_name": "tornado.web.web", "line_number": 14, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 14, "usage_type": "name"}, {"api_name": "decorators.handleException.handleException", "line_number": 15, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "call"}, {"api_name": "exceptions.exceptions.BadRequest", "line_number": 36, "usage_type": "call"}, {"api_name": "exceptions.exceptions", "line_number": 36, "usage_type": "name"}, {"api_name": "services.pedirCuentaService.PedirCuentaService", "line_number": 37, "usage_type": "call"}, {"api_name": "tornado.web.web", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 19, "usage_type": "name"}, {"api_name": "decorators.handleException.handleException", "line_number": 20, "usage_type": "name"}, {"api_name": "decorators.checkAuthentication.checkAuthentication", "line_number": 21, "usage_type": "name"}]}
+{"seq_id": "288447105", "text": "# -*- coding: utf-8 -*-\n# Author : Manki Baek\n# e-mail : Manki.Baek@seculayer.co.kr\n# Powered by Seculayer © 2021 Service Model Team, R&D Center.\n\nfrom datetime import datetime\nimport json\nimport os\n\nfrom mlps.core.apeflow.interface.model.ModelAbstract import ModelAbstract\nfrom mlps.core.apeflow.api.algorithms.gs.GSAlgAbstract import GSAlgAbstract\nfrom mlps.core.RestManager import RestManager\n\n\nclass GSModel(ModelAbstract):\n def __init__(self, param_dict, ext_data=None):\n ModelAbstract.__init__(self, param_dict, ext_data)\n self.model: GSAlgAbstract = self._build()\n\n def learn(self, dataset):\n start_time = datetime.now()\n self.model.learn(dataset)\n learn_time_sec = (datetime.now() - start_time).total_seconds()\n\n if json.loads(os.environ[\"TF_CONFIG\"])[\"task\"][\"index\"] == \"0\":\n if self.model.learn_result_callback is None:\n eps = len(dataset[\"x\"]) / learn_time_sec\n learn_result = None\n else:\n eps = self.model.learn_result_callback.get_eps()\n learn_result = self.model.learn_result_callback.get_learn_result()\n\n RestManager.update_eps(self.param_dict['job_key'], eps)\n if learn_result is not None:\n RestManager.update_learn_result(self.param_dict['job_key'], learn_result)\n\n self.model.saved_model()\n", "sub_path": "mlps/core/apeflow/interface/model/GSModel.py", "file_name": "GSModel.py", "file_ext": "py", "file_size_in_byte": 1384, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "mlps.core.apeflow.interface.model.ModelAbstract.ModelAbstract", "line_number": 15, "usage_type": "name"}, {"api_name": "mlps.core.apeflow.interface.model.ModelAbstract.ModelAbstract.__init__", "line_number": 17, "usage_type": "call"}, {"api_name": "mlps.core.apeflow.interface.model.ModelAbstract.ModelAbstract", "line_number": 17, "usage_type": "name"}, {"api_name": "mlps.core.apeflow.api.algorithms.gs.GSAlgAbstract.GSAlgAbstract", "line_number": 18, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 21, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 21, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 25, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 25, "usage_type": "attribute"}, {"api_name": "mlps.core.RestManager.RestManager.update_eps", "line_number": 33, "usage_type": "call"}, {"api_name": "mlps.core.RestManager.RestManager", "line_number": 33, "usage_type": "name"}, {"api_name": "mlps.core.RestManager.RestManager.update_learn_result", "line_number": 35, "usage_type": "call"}, {"api_name": "mlps.core.RestManager.RestManager", "line_number": 35, "usage_type": "name"}]}
+{"seq_id": "327564295", "text": "# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/lib/python2.7/site-packages/pyjznet/server.py\n# Compiled at: 2014-12-11 04:16:10\nfrom __future__ import print_function\nfrom geventwebsocket import WebSocketServer, WebSocketApplication, Resource\nimport sys, logging\nfrom . import pools\nfrom . import processors\nfrom . import listeners\nfrom . import messages\nroot = logging.getLogger()\nroot.setLevel(logging.DEBUG)\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nroot.addHandler(ch)\n\nclass Server(object):\n\n def __init__(self):\n self.rpc_services = []\n self._send_msg_pool = pools.SendMessagePool()\n self._receive_msg_pool = pools.ReceiveMessagePool()\n self.message_builder = messages.MessageBuilder()\n\n def add_rpc_service(self, name, rpc_service):\n self.rpc_services.append((name, rpc_service))\n\n def start(self, host='127.0.0.1', port=8000):\n send_msg_pool = self._send_msg_pool\n receive_msg_pool = self._receive_msg_pool\n message_builder = self.message_builder\n send_msg_pool.add_listener(object, listeners.SendMessageHandler())\n\n class WSApplication(WebSocketApplication):\n\n def on_open(self):\n print('Connection opened')\n\n def on_close(self, reason):\n print('Connection closed')\n\n def on_message(self, message):\n print('got message', message)\n receive_msg_pool.offer_messages(message_builder.create_messages(self, message))\n\n msg_processor = processors.MessageProcessor(receive_msg_pool, send_msg_pool)\n msg_processor.add_rpc_services(self.rpc_services)\n msg_processor.start()\n ws_server = WebSocketServer((\n host, port), Resource({'/': WSApplication, '/websocket': WSApplication}))\n print('start to listen at http://%s:%d' % (host, port))\n ws_server.serve_forever()", "sub_path": "pycfiles/jznet-0.0.1.linux-x86_64.tar/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 2137, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 16, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 17, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 18, "usage_type": "call"}, {"api_name": "geventwebsocket.WebSocketApplication", "line_number": 39, "usage_type": "name"}, {"api_name": "geventwebsocket.WebSocketServer", "line_number": 54, "usage_type": "call"}, {"api_name": "geventwebsocket.Resource", "line_number": 55, "usage_type": "call"}]}
+{"seq_id": "5025918", "text": "from typing import Iterable\nfrom datetime import datetime\nfrom uuid import UUID\nfrom record import RelocationRecord, JobRecord\n\n\ndef _format_job_id(job_id: UUID) -> str:\n return str(job_id)\n\n\ndef _format_time(time: datetime) -> str:\n return time.isoformat()\n\n\ndef format_job_id(job_id: UUID) -> dict:\n return {'jobId': _format_job_id(job_id)}\n\n\ndef format_job_status(job: JobRecord) -> dict:\n \"\"\"\n >>> import datetime\n >>> job = JobRecord(1, datetime.datetime.utcnow(), ['a', 'b'])\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'pending', 'uploaded': {'pending': ['a', 'b'], 'complete': [], 'failed': []}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'in-progress', 'uploaded': {'pending': ['b'], 'complete': [], 'failed': ['a']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a', 'A')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': None, 'status': 'in-progress', 'uploaded': {'pending': ['b'], 'complete': ['A'], 'failed': []}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'b')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': ['A'], 'failed': ['b']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': [], 'failed': ['a', 'b']}}\n\n >>> job.commit(datetime.datetime.utcnow(), 'a', 'A')\n >>> job.commit(datetime.datetime.utcnow(), 'b', 'B')\n >>> format_job_status(job) # doctest: +ELLIPSIS\n {'id': '1', 'created': '2...', 'finished': '2...', 'status': 'complete', 'uploaded': {'pending': [], 'complete': ['A', 'B'], 'failed': []}}\n \"\"\"\n pending = [reloc.url_old for reloc in filter(lambda r: r.is_pending, job.relocation)]\n failed = [reloc.url_old for reloc in filter(lambda r: r.is_failed, job.relocation)]\n complete = [reloc.url_new for reloc in filter(lambda r: r.is_stored, job.relocation)]\n\n if not pending:\n finished_time = _format_time(job.update_time)\n job_state = \"complete\"\n else:\n finished_time = None\n if complete or failed:\n job_state = 'in-progress'\n else:\n job_state = 'pending'\n\n status = {\n \"id\": _format_job_id(job.id),\n \"created\": _format_time(job.create_time),\n \"finished\": finished_time,\n \"status\": job_state,\n \"uploaded\": {\n \"pending\": pending,\n \"complete\": complete,\n \"failed\": failed\n }\n }\n\n return status\n\n\ndef format_uploaded_list(relocation: Iterable[RelocationRecord]) -> dict:\n \"\"\"\n >>> reolc = RelocationRecord('a')\n >>> reolc.commit(0)\n >>> format_uploaded_list([reolc])\n {'uploaded': []}\n\n >>> reolc.commit(1, 'A')\n >>> format_uploaded_list([reolc])\n {'uploaded': ['A']}\n \"\"\"\n uploaded = {\n \"uploaded\": []\n }\n\n for reloc in filter(lambda r: r.is_stored, relocation):\n uploaded['uploaded'].append(reloc.url_new)\n\n return uploaded\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n", "sub_path": "response_format.py", "file_name": "response_format.py", "file_ext": "py", "file_size_in_byte": 3413, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "uuid.UUID", "line_number": 7, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 11, "usage_type": "name"}, {"api_name": "uuid.UUID", "line_number": 15, "usage_type": "name"}, {"api_name": "record.JobRecord", "line_number": 19, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 76, "usage_type": "name"}, {"api_name": "record.RelocationRecord", "line_number": 76, "usage_type": "name"}, {"api_name": "doctest.testmod", "line_number": 99, "usage_type": "call"}]}
+{"seq_id": "237808121", "text": "from social.forms import *\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom users.models import Membership\nfrom project.models import Project\nfrom users.models import User\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.context_processors import request\nfrom django.core.exceptions import ValidationError\nfrom social.models import Request\nfrom project.views import manage_project\nfrom django.views.decorators.cache import cache_control\n\n# Create your views here.\n\n#@login_required\n#def request_invite_user(request):\n \n@login_required\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\ndef my_join_request(request):\n if request.method == 'POST': \n r = get_object_or_404(Request,to_user_id=request.user.id, project_id = request.POST['project'])\n message = \"\"\n if(request.POST['button'] == 'accept'):\n p = get_object_or_404(Project,pk=request.POST['project'])\n membership = Membership(user=request.user, project=p)\n membership.save()\n message = \"La solicitud ha sido aceptada\" \n else:\n message = \"La solicitud ha sido rechazada\" \n r.delete()\n return render_to_response('social/my_join_request.html',\n {'message':message},\n context_instance=RequestContext(request))\n else:\n join_request = Request.objects.filter(to_user_id=request.user.id)\n return render_to_response('social/my_join_request.html',\n {'join_request':join_request},\n context_instance=RequestContext(request))\n\n@login_required\n@cache_control(no_cache=True, must_revalidate=True, no_store=True)\ndef request_join_project(request,project_id):\n p = get_object_or_404(Project,pk=project_id)\n if request.method == 'POST':\n users = request.POST.getlist('to_user')\n for u in users:\n user = get_object_or_404(User,pk=u)\n if Request.objects.filter(from_user_id=request.user.id, to_user_id=user.id,project_id=project_id).count() == 0:\n r = Request(to_user = user, from_user=request.user,project=p)\n r.save()\n return manage_project(request) \n else:\n memberships = Membership.objects.filter(project_id=project_id)\n users = []\n for membership in memberships:\n users.append(membership.user)\n join_requests = Request.objects.filter(from_user_id=request.user.id, project_id=project_id) \n for r in join_requests:\n users.append(r.to_user) \n form = RequestForm(users=users)\n return render_to_response('social/request_join_project.html',\n {'form':form},\n context_instance=RequestContext(request))\n ", "sub_path": "src/GPDS/social/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3018, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.core.context_processors.request.method", "line_number": 23, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 23, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 24, "usage_type": "call"}, {"api_name": "social.models.Request", "line_number": 24, "usage_type": "argument"}, {"api_name": "django.core.context_processors.request.user", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 24, "usage_type": "name"}, {"api_name": "django.core.context_processors.request.POST", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request.POST", "line_number": 26, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 26, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 27, "usage_type": "call"}, {"api_name": "project.models.Project", "line_number": 27, "usage_type": "argument"}, {"api_name": "django.core.context_processors.request.POST", "line_number": 27, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 27, "usage_type": "name"}, {"api_name": "users.models.Membership", "line_number": 28, "usage_type": "call"}, {"api_name": "django.core.context_processors.request.user", "line_number": 28, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 28, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 34, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 36, "usage_type": "call"}, {"api_name": "django.core.context_processors.request", "line_number": 36, "usage_type": "argument"}, {"api_name": "social.models.Request.objects.filter", "line_number": 38, "usage_type": "call"}, {"api_name": "social.models.Request.objects", "line_number": 38, "usage_type": "attribute"}, {"api_name": "social.models.Request", "line_number": 38, "usage_type": "name"}, {"api_name": "django.core.context_processors.request.user", "line_number": 38, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 38, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 39, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 41, "usage_type": "call"}, {"api_name": "django.core.context_processors.request", "line_number": 41, "usage_type": "argument"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 20, "usage_type": "name"}, {"api_name": "django.views.decorators.cache.cache_control", "line_number": 21, "usage_type": "call"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 46, "usage_type": "call"}, {"api_name": "project.models.Project", "line_number": 46, "usage_type": "argument"}, {"api_name": "django.core.context_processors.request.method", "line_number": 47, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 47, "usage_type": "name"}, {"api_name": "users.models", "line_number": 48, "usage_type": "name"}, {"api_name": "django.core.context_processors.request.POST.getlist", "line_number": 48, "usage_type": "call"}, {"api_name": "django.core.context_processors.request.POST", "line_number": 48, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 48, "usage_type": "name"}, {"api_name": "users.models", "line_number": 49, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 50, "usage_type": "call"}, {"api_name": "users.models.User", "line_number": 50, "usage_type": "argument"}, {"api_name": "social.models.Request.objects.filter", "line_number": 51, "usage_type": "call"}, {"api_name": "social.models.Request.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "social.models.Request", "line_number": 51, "usage_type": "name"}, {"api_name": "django.core.context_processors.request.user", "line_number": 51, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 51, "usage_type": "name"}, {"api_name": "social.models.Request", "line_number": 52, "usage_type": "call"}, {"api_name": "django.core.context_processors.request.user", "line_number": 52, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 52, "usage_type": "name"}, {"api_name": "project.views.manage_project", "line_number": 54, "usage_type": "call"}, {"api_name": "django.core.context_processors.request", "line_number": 54, "usage_type": "argument"}, {"api_name": "users.models.Membership.objects.filter", "line_number": 56, "usage_type": "call"}, {"api_name": "users.models.Membership.objects", "line_number": 56, "usage_type": "attribute"}, {"api_name": "users.models.Membership", "line_number": 56, "usage_type": "name"}, {"api_name": "users.models", "line_number": 57, "usage_type": "name"}, {"api_name": "users.models.append", "line_number": 59, "usage_type": "call"}, {"api_name": "users.models", "line_number": 59, "usage_type": "name"}, {"api_name": "social.models.Request.objects.filter", "line_number": 60, "usage_type": "call"}, {"api_name": "social.models.Request.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "social.models.Request", "line_number": 60, "usage_type": "name"}, {"api_name": "django.core.context_processors.request.user", "line_number": 60, "usage_type": "attribute"}, {"api_name": "django.core.context_processors.request", "line_number": 60, "usage_type": "name"}, {"api_name": "users.models.append", "line_number": 62, "usage_type": "call"}, {"api_name": "users.models", "line_number": 62, "usage_type": "name"}, {"api_name": "users.models", "line_number": 63, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 64, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 66, "usage_type": "call"}, {"api_name": "django.core.context_processors.request", "line_number": 66, "usage_type": "argument"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 43, "usage_type": "name"}, {"api_name": "django.views.decorators.cache.cache_control", "line_number": 44, "usage_type": "call"}]}
+{"seq_id": "238235904", "text": "import os\nimport datetime\nimport logging\nimport subprocess\nimport time\n\nlog_dir = '/var/log/iptables.log'\ncurrent_size = os.path.getsize(log_dir)\n\ndef run_command(command):\n try:\n process = subprocess.Popen(command, shell = True, stdout = subprocess.PIPE)\n process.wait()\n return process.stdout.readline().rstrip()\n except Exception as e:\n logger.error(e)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n# create a file handler\nhandler = logging.FileHandler('monitor_tcp_app.log')\nhandler.setLevel(logging.INFO)\n# create a logging format\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(handler)\n# add the handlers to console\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.DEBUG)\nconsole.setFormatter(formatter)\nlogger.addHandler(console)\n\nwhile True:\n if os.path.getsize(log_dir) != current_size:\n logger.info(\"Found new log, start monitor TCP\")\n current_datetime = datetime.datetime.now().strftime(\"%y-%m-%d-%H-%M\")\n # monitor tcp in 60 min\n tcpdump_command = \"timeout 60 tcpdump -i port1 -w /root/log_tcp_%s.pcap\" % (current_datetime)\n result_tcp = run_command(tcpdump_command)\n logger.info(\"Saved PCAP to /root/log/log_tcp_%s.pcap\" % (current_datetime))\n current_size = os.path.getsize(log_dir)", "sub_path": "monitor_tcp.py", "file_name": "monitor_tcp.py", "file_ext": "py", "file_size_in_byte": 1436, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "os.path.getsize", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "subprocess.Popen", "line_number": 12, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 12, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 19, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 21, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 22, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 37, "usage_type": "attribute"}, {"api_name": "os.path.getsize", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}]}
+{"seq_id": "515070113", "text": "from math import radians, cos, sin, asin, sqrt\r\nimport json\r\n\r\ncountry_list = ['Germany',\r\n 'France',\r\n 'Netherlands',\r\n 'Belgium',\r\n 'Switzerland',\r\n 'Austria',\r\n 'Italy',\r\n 'Spain',\r\n 'Portugal',\r\n 'United Kingdom',\r\n 'Ireland',\r\n 'Poland',\r\n 'Czech Republic',\r\n 'Croatia',\r\n 'Slovenia',\r\n 'Slovakia',\r\n 'Hungary',\r\n 'Romania',\r\n 'Serbia',\r\n 'Bosnia',\r\n 'Albania',\r\n 'Bulgaria',\r\n 'Mazedonia',\r\n 'Greece',\r\n 'Turkey',\r\n 'Sweden',\r\n 'Norway',\r\n 'Denmark']\r\n\r\nwith open('city_list2.json', 'r', encoding='utf-8') as data_file:\r\n data = json.load(data_file)\r\n\r\ndef haversine(lat1, lon1, lat2, lon2):\r\n \r\n # convert decimal degrees to radians\r\n lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])\r\n\r\n # haversine formula\r\n dlat = lat2 - lat1\r\n dlon = lon2 - lon1\r\n a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2\r\n c = 2 * asin(sqrt(a)) \r\n r = 6371000 # Radius of earth in meters. Use 3956 for miles\r\n return c * r\r\n\r\nfor Origin in data:\r\n if Origin['country'] in country_list:\r\n if Origin['geocoding']['latitude'] != 0.0 and Origin['geocoding']['longitude'] != 0:\r\n print(Origin['name'])\r\n for Destination in data:\r\n if Destination['country'] in country_list:\r\n if Destination['geocoding']['latitude'] != 0.0 and Destination['geocoding']['longitude'] != 0:\r\n latitude1 = Origin['geocoding']['latitude']\r\n longitude1 = Origin['geocoding']['longitude']\r\n latitude2 = Destination['geocoding']['latitude']\r\n longitude2 = Destination['geocoding']['longitude']\r\n haversine_distance = haversine(latitude1, longitude1, latitude2, longitude2)\r\n Origin['distances']['haversine'].update({'{}'.format(Destination['name']): int(haversine_distance)})\r\n \r\ndef writeToJSONFile(path, fileName, data):\r\n filePathNameWExt = './' + path + '/' + fileName + '.json'\r\n with open(filePathNameWExt, 'w') as fp:\r\n json.dump(data, fp)\r\n\r\nwriteToJSONFile('./','city_list2',data)\r\n", "sub_path": "Haversine4DataBase.py", "file_name": "Haversine4DataBase.py", "file_ext": "py", "file_size_in_byte": 2552, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "json.load", "line_number": 34, "usage_type": "call"}, {"api_name": "math.radians", "line_number": 39, "usage_type": "argument"}, {"api_name": "math.sin", "line_number": 44, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 44, "usage_type": "call"}, {"api_name": "math.asin", "line_number": 45, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 45, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 66, "usage_type": "call"}]}
+{"seq_id": "369996223", "text": "import logging\n\nfrom .config import get_config_value, get_config_value_as_list\nfrom .validator import (JiraValidator, RegExpValidator, VersionsValidator)\n\nlog = logging.getLogger()\n\n\ndef validate_todos(todos, issue_pattern, version_pattern, version, versions):\n log.info('Validating %d todos.', len(todos))\n\n validators = []\n\n issue_validator = RegExpValidator(issue_pattern)\n validators.append(issue_validator)\n\n if get_config_value('jira_server', 'url'):\n jira_validator = JiraValidator(issue_pattern,\n get_config_value('jira_server', 'url'),\n get_config_value('jira_server', 'username'),\n get_config_value('jira_server', 'password'),\n get_config_value('jira_server', 'token'),\n get_config_value_as_list('statuses', 'all'),\n get_config_value('issue_filter', 'field'),\n get_config_value_as_list('issue_filter', 'values'))\n issue_validator.set_dependent_validator(jira_validator)\n\n if version_pattern is not None:\n version_validator = RegExpValidator(version_pattern)\n validators.append(version_validator)\n\n if versions is not None and version is not None:\n version_validator.set_dependent_validator(VersionsValidator(versions, version))\n\n invalid_todos = []\n amount_ignored = 0\n for todo in todos:\n validate_todo(validators, todo)\n if not todo.is_valid:\n invalid_todos.append(todo)\n amount_ignored += todo.is_ignored\n\n if not invalid_todos:\n log.info('All todos are fine.')\n return\n\n log.error('------------------------------------------------------------------------------')\n log.error('Found %d invalid todo(s) (%d of them ignored).', len(invalid_todos), amount_ignored)\n log.error('------------------------------------------------------------------------------')\n for invalid_todo in invalid_todos:\n invalid_todo.print()\n log.error('------------------------------------------------------------------------------')\n\n\ndef validate_todo(validators, todo):\n for validator in validators:\n if validator.validate(todo):\n return\n\n todo.mark_as_invalid('Todo is not conform to any validator.')\n", "sub_path": "src/inspectortodo/todo_validation.py", "file_name": "todo_validation.py", "file_ext": "py", "file_size_in_byte": 2431, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "validator.RegExpValidator", "line_number": 14, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 17, "usage_type": "call"}, {"api_name": "validator.JiraValidator", "line_number": 18, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 19, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 20, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 21, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 22, "usage_type": "call"}, {"api_name": "config.get_config_value_as_list", "line_number": 23, "usage_type": "call"}, {"api_name": "config.get_config_value", "line_number": 24, "usage_type": "call"}, {"api_name": "config.get_config_value_as_list", "line_number": 25, "usage_type": "call"}, {"api_name": "validator.RegExpValidator", "line_number": 29, "usage_type": "call"}, {"api_name": "validator.VersionsValidator", "line_number": 33, "usage_type": "call"}, {"api_name": "validator.validate", "line_number": 57, "usage_type": "call"}]}
+{"seq_id": "131242265", "text": "import requests\n\n\ndef download(url, params=None, retries=3):\n\n try:\n response = requests.get(url, params=params, headers=headers)\n except requests.exceptions.HTTPError as e:\n if 500 <= requests.status_codes < 600 and retries > 0:\n return download(url, params, retries - 1)\n else:\n print(requests.status_codes)\n print(requests.reason)\n print(requests.headers)\n return response\n\n\nurl = 'https://www.google.com/search'\n\nheaders = {\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36\"\n}\n\nresult = download(url, params={\"q\": \"파이썬\"})\n\nresult.url\nresult.content.decode('utf-8')\n", "sub_path": "crawler/day02/code/web_crawler_2.py", "file_name": "web_crawler_2.py", "file_ext": "py", "file_size_in_byte": 741, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 8, "usage_type": "attribute"}, {"api_name": "requests.status_codes", "line_number": 9, "usage_type": "attribute"}, {"api_name": "requests.status_codes", "line_number": 12, "usage_type": "attribute"}, {"api_name": "requests.reason", "line_number": 13, "usage_type": "attribute"}, {"api_name": "requests.headers", "line_number": 14, "usage_type": "attribute"}]}
+{"seq_id": "200472322", "text": "from datetime import datetime, timedelta\n\nfrom celery.utils.log import get_task_logger\nfrom pytz import utc\n\nfrom dataworkspace.apps.explorer.models import QueryLog, PlaygroundSQL\nfrom dataworkspace.cel import celery_app\n\n\nlogger = get_task_logger(__name__)\n\n\n@celery_app.task()\ndef truncate_querylogs(days):\n qs = QueryLog.objects.filter(run_at__lt=datetime.now() - timedelta(days=days))\n logger.info('Deleting %s QueryLog objects older than %s days.', qs.count, days)\n qs.delete()\n logger.info('Done deleting QueryLog objects.')\n\n\n@celery_app.task()\ndef cleanup_playground_sql_table():\n older_than = timedelta(days=14)\n oldest_date_to_retain = datetime.now(tz=utc) - older_than\n\n logger.info(\n \"Cleaning up Data Explorer PlaygroundSQL rows older than %s\",\n oldest_date_to_retain,\n )\n\n count = 0\n for play_sql in PlaygroundSQL.objects.filter(created_at__lte=oldest_date_to_retain):\n play_sql.delete()\n count += 1\n\n logger.info(\"Delete %s PlaygroundSQL rows\", count)\n", "sub_path": "dataworkspace/dataworkspace/apps/explorer/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 1028, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "celery.utils.log.get_task_logger", "line_number": 10, "usage_type": "call"}, {"api_name": "dataworkspace.apps.explorer.models.QueryLog.objects.filter", "line_number": 15, "usage_type": "call"}, {"api_name": "dataworkspace.apps.explorer.models.QueryLog.objects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "dataworkspace.apps.explorer.models.QueryLog", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 15, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 15, "usage_type": "call"}, {"api_name": "dataworkspace.cel.celery_app.task", "line_number": 13, "usage_type": "call"}, {"api_name": "dataworkspace.cel.celery_app", "line_number": 13, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 24, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 24, "usage_type": "name"}, {"api_name": "pytz.utc", "line_number": 24, "usage_type": "name"}, {"api_name": "dataworkspace.apps.explorer.models.PlaygroundSQL.objects.filter", "line_number": 32, "usage_type": "call"}, {"api_name": "dataworkspace.apps.explorer.models.PlaygroundSQL.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "dataworkspace.apps.explorer.models.PlaygroundSQL", "line_number": 32, "usage_type": "name"}, {"api_name": "dataworkspace.cel.celery_app.task", "line_number": 21, "usage_type": "call"}, {"api_name": "dataworkspace.cel.celery_app", "line_number": 21, "usage_type": "name"}]}
+{"seq_id": "250958161", "text": "from django.shortcuts import render, get_object_or_404\nfrom .models import Variation\n\ndef product_detail(request, id = None):\n\tinstance = get_object_or_404(Variation, id=id)\n\tcontext = {\n\t\t\"title\": \"Detalles\",\n\t\t\"instance\": instance,\n\t}\n\treturn render(request, \"test_detail.html\", context)\n", "sub_path": "products/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 290, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.shortcuts.get_object_or_404", "line_number": 5, "usage_type": "call"}, {"api_name": "models.Variation", "line_number": 5, "usage_type": "argument"}, {"api_name": "django.shortcuts.render", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "431834784", "text": "from matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\nfrom __future__ import print_function \nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom scipy.spatial.distance import cdist\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef softmax_stable(Z):\n \"\"\"\n Compute softmax values for each sets of scores in Z.\n each row of Z is a set of scores. \n \"\"\"\n e_Z = np.exp(Z - np.max(Z, axis = 1, keepdims = True))\n A = e_Z / e_Z.sum(axis = 1, keepdims = True)\n return A\n\ndef crossentropy_loss(Yhat, y):\n \"\"\"\n Yhat: a numpy array of shape (Npoints, nClasses) -- predicted output \n y: a numpy array of shape (Npoints) -- ground truth. We don't need to use \n the one-hot vector here since most of elements are zeros. When programming \n in numpy, we need to use the corresponding indexes only.\n \"\"\"\n id0 = range(Yhat.shape[0])\n return -np.mean(np.log(Yhat[id0, y]))\n\n\ndef mlp_init(d0, d1, d2):\n \"\"\" \n Initialize W1, b1, W2, b2 \n d0: dimension of input data \n d1: number of hidden unit \n d2: number of output unit = number of classes\n \"\"\"\n W1 = 0.01*np.random.randn(d0, d1)\n b1 = np.zeros(d1)\n W2 = 0.01*np.random.randn(d1, d2)\n b2 = np.zeros(d2)\n return (W1, b1, W2, b2)\n\ndef mlp_predict(X, W1, b1, W2, b2):\n \"\"\"\n Suppose that the network has been trained, predict class of new points. \n X: data matrix, each ROW is one data point.\n W1, b1, W2, b2: learned weight matrices and biases \n \"\"\"\n Z1 = X.dot(W1) + b1 # shape (N, d1)\n A1 = np.maximum(Z1, 0) # shape (N, d1)\n Z2 = A1.dot(W2) + b2 # shape (N, d2)\n return np.argmax(Z2, axis=1)\n\ndef mlp_fit(X, y, W1, b1, W2, b2, eta):\n loss_hist = []\n for i in xrange(10000):\n # feedforward \n Z1 = X.dot(W1) + b1 # shape (N, d1)\n A1 = np.maximum(Z1, 0) # shape (N, d1)\n Z2 = A1.dot(W2) + b2 # shape (N, d2)\n Yhat = softmax_stable(Z2) # shape (N, d2)\n \n if i %1000 == 0: # print loss after each 1000 iterations\n loss = crossentropy_loss(Yhat, y)\n print(\"iter %d, loss: %f\" %(i, loss))\n loss_hist.append(loss)\n\n # back propagation\n id0 = range(Yhat.shape[0])\n Yhat[id0, y] -=1 \n E2 = Yhat/N # shape (N, d2)\n dW2 = np.dot(A1.T, E2) # shape (d1, d2)\n db2 = np.sum(E2, axis = 0) # shape (d2,)\n E1 = np.dot(E2, W2.T) # shape (N, d1)\n E1[Z1 <= 0] = 0 # gradient of ReLU, shape (N, d1)\n dW1 = np.dot(X.T, E1) # shape (d0, d1)\n db1 = np.sum(E1, axis = 0) # shape (d1,)\n\n # Gradient Descent update\n W1 += -eta*dW1\n b1 += -eta*db1\n W2 += -eta*dW2\n b2 += -eta*db2\n return (W1, b1, W2, b2, loss_hist)\n\nd0 = 2\nd1 = h = 500 # size of hidden layer\nd2 = C = 3\neta = 1 # learning rate\n# initialize parameters randomly\n(W1, b1, W2, b2) = mlp_init(d0, d1, d2)\n(W1, b1, W2, b2, loss_hist) =mlp_fit(X, y, W1, b1, W2, b2, eta)\n\ny_pred = mlp_predict(X, W1, b1, W2, b2)\nacc = 100*np.mean(y_pred == y)\nprint('training accuracy: %.2f %%' % acc)", "sub_path": "Basic-ML/multiplayer_neural_network/neural_network.py", "file_name": "neural_network.py", "file_ext": "py", "file_size_in_byte": 3184, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "matplotlib.rc", "line_number": 2, "usage_type": "call"}, {"api_name": "matplotlib.rc", "line_number": 3, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 39, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 41, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 74, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 97, "usage_type": "call"}]}
+{"seq_id": "323614876", "text": "\"\"\"\nMain\n=====\n\"\"\"\n\nimport click\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.parsers.plaintext import PlaintextParser\n\nfrom .textrank import alt_extract, get_summarizer\n\n\n@click.command()\n@click.argument('url')\n@click.option('--max-sent', default=10, help='The maximum number of sentences')\n@click.option('--language', default='english', help='Article language')\ndef main(url, max_sent, language='english'):\n tokenizer = Tokenizer(language)\n article = alt_extract(url)\n parser = PlaintextParser.from_string(article, tokenizer)\n return click.echo(get_summarizer(parser, max_sent, language))\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "ExplainToMe/__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 650, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sumy.nlp.tokenizers.Tokenizer", "line_number": 18, "usage_type": "call"}, {"api_name": "textrank.alt_extract", "line_number": 19, "usage_type": "call"}, {"api_name": "sumy.parsers.plaintext.PlaintextParser.from_string", "line_number": 20, "usage_type": "call"}, {"api_name": "sumy.parsers.plaintext.PlaintextParser", "line_number": 20, "usage_type": "name"}, {"api_name": "click.echo", "line_number": 21, "usage_type": "call"}, {"api_name": "textrank.get_summarizer", "line_number": 21, "usage_type": "call"}, {"api_name": "click.command", "line_number": 13, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 14, "usage_type": "call"}, {"api_name": "click.option", "line_number": 15, "usage_type": "call"}, {"api_name": "click.option", "line_number": 16, "usage_type": "call"}]}
+{"seq_id": "210096284", "text": "import pygame\nfrom block import Block, Vector, Colors, digits\nfrom random import randint\n\ndef check_click(mouse_pos, grid):\n for line in grid:\n for i in line:\n cond_min = mouse_pos[0] > i.x and mouse_pos[1] > i.y\n cond_max = mouse_pos[0] < i.x + i.size and mouse_pos[1] < i.y + i.size\n if cond_min and cond_max:\n if i.visible is False:\n i.color = Colors.active\n i.draw(W)\n print('Drawed №', i.__id__)\n i.visible = True\n return\n else:\n i.color = Colors.empty\n i.draw(W)\n print('Deleted №', i.__id__)\n i.visible = False\n return\ndef gen_grid(width, height):\n grid = []\n line = []\n coords = Vector(0,0)\n size = 1\n count = 0\n for h in range(height):\n coords.x = 0\n for w in range(width):\n block = Block(count, coords.x, coords.y)\n line.append(block)\n coords.x += size\n count += 1\n coords.y += size\n grid.append(line)\n return grid\ndef check_win(grid, win_num=0):\n for line in grid:\n for i in line:\n if bool(digits[win_num][i.__id__]) != i.visible:\n return False\n print('YOU WIN!')\n return True\n\n\nnum = int(input('Enter digit for drawing (0-3): '))\n\n\npygame.init()\nW = pygame.display.set_mode((300, 500))\npygame.display.set_caption(\"Plates\")\n\ngrid = gen_grid(3, 5)\nplay = True\n\nwhile play:\n pygame.time.delay(300)\n\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n play = False\n\n if e.type == pygame.MOUSEBUTTONDOWN:\n mouse_pos = e.pos\n # print(mouse_pos[0])\n check_click(mouse_pos, grid)\n check_win(grid, num)\n\n\n\n # for line in grid:\n # for i in line:\n # pass\n # i.draw(W)\n pygame.display.update()\n\n\npygame.quit()\n", "sub_path": "__main__.py", "file_name": "__main__.py", "file_ext": "py", "file_size_in_byte": 2028, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "block.Colors.active", "line_number": 12, "usage_type": "attribute"}, {"api_name": "block.Colors", "line_number": 12, "usage_type": "name"}, {"api_name": "block.Colors.empty", "line_number": 18, "usage_type": "attribute"}, {"api_name": "block.Colors", "line_number": 18, "usage_type": "name"}, {"api_name": "block.Vector", "line_number": 26, "usage_type": "call"}, {"api_name": "block.Block", "line_number": 32, "usage_type": "call"}, {"api_name": "block.digits", "line_number": 42, "usage_type": "name"}, {"api_name": "pygame.init", "line_number": 51, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 53, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 53, "usage_type": "attribute"}, {"api_name": "pygame.time.delay", "line_number": 59, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 59, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.display.update", "line_number": 77, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 77, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 80, "usage_type": "call"}]}
+{"seq_id": "401071450", "text": "#!/usr/bin/env python\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n\"\"\"\nExample to show managing rule entities under a ServiceBus Subscription, including\n - Create a rule\n - Create a rule with sql filter\n - Get rule properties and runtime information\n - Update a rule\n - Delete a rule\n - List rules under the given ServiceBus Subscription\n\"\"\"\n\nimport os\nimport uuid\nfrom azure.servicebus.management import (\n ServiceBusAdministrationClient,\n SqlRuleFilter\n)\n\nCONNECTION_STR = os.environ['SERVICEBUS_CONNECTION_STR']\nTOPIC_NAME = os.environ['SERVICEBUS_TOPIC_NAME']\nSUBSCRIPTION_NAME = os.environ['SERVICEBUS_SUBSCRIPTION_NAME']\nRULE_NAME = \"sb_mgmt_rule\" + str(uuid.uuid4())\nRULE_WITH_SQL_FILTER_NAME = \"sb_sql_rule\" + str(uuid.uuid4())\n\n\ndef create_rule(servicebus_mgmt_client):\n print(\"-- Create Rule\")\n servicebus_mgmt_client.create_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule {} is created.\".format(RULE_NAME))\n print(\"\")\n\n print(\"-- Create Rule with SQL Filter\")\n sql_filter_parametrized = SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value\",\n \"@param2\": 1\n }\n )\n servicebus_mgmt_client.create_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_WITH_SQL_FILTER_NAME, filter=sql_filter_parametrized)\n print(\"Rule {} is created.\".format(RULE_WITH_SQL_FILTER_NAME))\n print(\"\")\n\n\ndef delete_rule(servicebus_mgmt_client):\n print(\"-- Delete Rule\")\n servicebus_mgmt_client.delete_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule {} is deleted.\".format(RULE_NAME))\n servicebus_mgmt_client.delete_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_WITH_SQL_FILTER_NAME)\n print(\"Rule {} is deleted.\".format(RULE_WITH_SQL_FILTER_NAME))\n print(\"\")\n\n\ndef list_rules(servicebus_mgmt_client):\n print(\"-- List Rules\")\n for rule_properties in servicebus_mgmt_client.list_rules(TOPIC_NAME, SUBSCRIPTION_NAME):\n print(\"Rule Name:\", rule_properties.name)\n print(\"\")\n\n\ndef get_and_update_rule(servicebus_mgmt_client):\n print(\"-- Get and Update Rule\")\n rule_properties = servicebus_mgmt_client.get_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n print(\"Rule Name:\", rule_properties.name)\n print(\"Please refer to RuleProperties for complete available properties.\")\n print(\"\")\n\n # update by updating the properties in the model\n rule_properties.filter = SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value2\",\n \"@param2\": 2\n }\n )\n servicebus_mgmt_client.update_rule(TOPIC_NAME, SUBSCRIPTION_NAME, rule_properties)\n\n # update by passing keyword arguments\n rule_properties = servicebus_mgmt_client.get_rule(TOPIC_NAME, SUBSCRIPTION_NAME, RULE_NAME)\n servicebus_mgmt_client.update_rule(\n TOPIC_NAME,\n SUBSCRIPTION_NAME,\n rule_properties,\n filter=SqlRuleFilter(\n \"property1 = @param1 AND property2 = @param2\",\n parameters={\n \"@param1\": \"value3\",\n \"@param2\": 3\n }\n )\n )\n\n\nwith ServiceBusAdministrationClient.from_connection_string(CONNECTION_STR) as servicebus_mgmt_client:\n create_rule(servicebus_mgmt_client)\n list_rules(servicebus_mgmt_client)\n get_and_update_rule(servicebus_mgmt_client)\n delete_rule(servicebus_mgmt_client)\n", "sub_path": "sdk/servicebus/azure-servicebus/samples/sync_samples/mgmt_rule.py", "file_name": "mgmt_rule.py", "file_ext": "py", "file_size_in_byte": 3724, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.environ", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 27, "usage_type": "attribute"}, {"api_name": "uuid.uuid4", "line_number": 28, "usage_type": "call"}, {"api_name": "uuid.uuid4", "line_number": 29, "usage_type": "call"}, {"api_name": "azure.servicebus.management.SqlRuleFilter", "line_number": 39, "usage_type": "call"}, {"api_name": "azure.servicebus.management.SqlRuleFilter", "line_number": 75, "usage_type": "call"}, {"api_name": "azure.servicebus.management.SqlRuleFilter", "line_number": 90, "usage_type": "call"}, {"api_name": "azure.servicebus.management.ServiceBusAdministrationClient.from_connection_string", "line_number": 100, "usage_type": "call"}, {"api_name": "azure.servicebus.management.ServiceBusAdministrationClient", "line_number": 100, "usage_type": "name"}]}
+{"seq_id": "148474368", "text": "import sys\nimport numpy as np\nimport cv2\nfrom torch.utils import data\nimport torch\nimport glob\nimport random\nimport os\n\nclass MRLEyeDataset(data.Dataset):\n def __init__(self, data_dir, set_type='all', augmentation=True):\n self.EYE_IMAGE_SHAPE = (112, 112)\n self.data_dir = data_dir\n self.set_type = set_type\n assert self.set_type in ['train', 'val', 'all'], f'Set_type should belong to either \"train\"/\"val\"/\"all\" '\n # Train set belong to s0001 ---> s0025, val set belong to s0026->s0037, all set belong to s0001 --> s0037\n self.files = self.__load_files()\n\n def __load_files(self):\n files = []\n if self.set_type == \"train\":\n folder_indice = list(range(1, 26))\n elif self.set_type == \"val\":\n folder_indice = list(range(26, 38))\n else:\n folder_indice = list(range(1, 38))\n for i in folder_indice:\n files_part_i = glob.glob(f'{self.data_dir}/s{i:04}/*.png')\n files += files_part_i\n random.shuffle(files)\n print(f'Len files : {len(files)}')\n return files\n\n def __len__(self):\n return len(self.files)\n\n def __getitem__(self, index):\n f = self.files[index]\n # Eye image\n eye = cv2.imread(f)\n eye = cv2.resize(eye, self.EYE_IMAGE_SHAPE)\n # print(\"eye shape: \", eye.shape)\n # Label\n eyestate_label = int(os.path.basename(f).split(\"_\")[4])\n return eye, torch.FloatTensor([eyestate_label])\n\nif __name__ == \"__main__\":\n mrl = MLREyeDataset('data/mrleye')\n ", "sub_path": "data/mrl.py", "file_name": "mrl.py", "file_ext": "py", "file_size_in_byte": 1579, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "torch.utils.data.Dataset", "line_number": 10, "usage_type": "attribute"}, {"api_name": "torch.utils.data", "line_number": 10, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 28, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 30, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 45, "usage_type": "call"}]}
+{"seq_id": "464931260", "text": "\"\"\" PALMIA: \r\n# Yksittäinen ruokaitemi, HTML koodista\r\nclass=\"meal-name invidual-restaurant-meal-name\"\r\n\r\n# Päivämäärän merkintä\r\ndata-date=\"2021-11-9\"\r\n\r\n# Suomenkielinen, ruotsiksi id=\"3\"\r\ndata-language-id=\"2\"\r\n\r\n# Jokaisessa Kasvislounaassa sekä Lounas ja Lounaan Lisukkeet\r\nclass=\"invidual-restaurant-meal-paragraph\"\r\n #Pelkkä \"Lounas\" teksti\r\n class=\"meal-of-day invidual-restaurant-meal-of-day\"\r\n\r\ndata-meal=\"UyQ-KpQHSUKn_ccO_dpEIw\" \"\"\"\r\n\r\nimport requests\r\nimport bs4\r\nfrom datetime import datetime\r\n\r\ndef päivän_ruokalista():\r\n\r\n # Kerro nykyinen päivä numerona 0 maanantai - 6 sunnuntai\r\n päivä = datetime.today().weekday()\r\n #print(päivä)\r\n \r\n \"\"\" koulu = str(input(\"Kirjoita koulun nimi: \")).lower()\r\n koulu = koulu.replace(\" \", \"-\") \"\"\"\r\n \r\n\r\n res = requests.get(f\"https://ruoka.palmia.fi/fi/ravintola/koulu/alppilan-lukio/\")\r\n soup = bs4.BeautifulSoup(res.text, \"lxml\")\r\n\r\n # Päivän ruoka listaksi, josta korjataan ylimääräiset välit pois\r\n\r\n ruoka= []\r\n \r\n d = soup.select(\".menu-list-day.invidual-restaurant-menu-list-day\")\r\n s = (d[päivä].getText())\r\n ruoka.append(s)\r\n ruoka = [s.replace(\"\\n\\n\\n\\n\\n\", \"\\n\") for s in ruoka]\r\n print(ruoka[0])\r\n\r\npäivän_ruokalista()\r\n\r\n", "sub_path": "RUOKALISTA PALMIA.py", "file_name": "RUOKALISTA PALMIA.py", "file_ext": "py", "file_size_in_byte": 1268, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "datetime.datetime.today", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 25, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 32, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 33, "usage_type": "call"}]}
+{"seq_id": "212719516", "text": "import sklearn.metrics\nfrom sklearn.metrics import log_loss\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom sklearn.feature_selection import RFE\nimport tensorflow as tf\n\n# Load data\ntrain = pd.read_csv('train.csv')\ntest = pd.read_csv('test.csv')\ndf = pd.concat([train, test])\n\ncheck = df.head(1)\n# Define our features and target\nfeatures = list(set(train.columns) - set(['Friends', 'ID']))\ntarget = 'Friends'\n\n# Encode our categorical data\ncategorical = ['Person A', 'Person B', 'Interaction Type', 'Moon Phase During Interaction']\nle = preprocessing.LabelEncoder()\n\nfor feature in categorical:\n df[feature] = le.fit_transform(df[feature])\n\n# Split data\nX = df[df[target].notnull()]\ny = df[df[target].isnull()]\nX[target] = X[target].astype(int)\n\nxtr, xte, ytr, yte = train_test_split(X[features], X[target], test_size=0.5, shuffle = False, random_state=False)\nxtr, validX, ytr, validY = train_test_split(xtr, ytr, test_size=0.5, shuffle = False, random_state= False)\n\nresults = []\nepochs = [10,20,30]\nbatches = [10,20,30]\n\n\ndef Hypereval(model):\n # evaluate the model\n bestAcc = 0\n bestEpoch = 0\n bestBatch = 0\n for batch in batches:\n for epoch in epochs:\n model.fit(xtr, ytr, epochs=epoch, batch_size=batch)\n scores = model.evaluate(validX, validY)\n for i in range(len(scores)):\n print(\"\\n%s: %f%%\" % (model.metrics_names[i], scores[i]))\n if scores[1] > bestAcc:\n bestAcc = scores[1]\n bestEpoch = epoch\n bestBatch = batch\n\n print(\"Best Acc \", bestAcc)\n print(\"Best Epoch \", bestEpoch)\n print(\"Best Batch \", bestBatch)\n return bestEpoch, bestBatch\n\n\n\ndef findRFE():\n labels = []\n acc = []\n filteredFeat = []\n\n for i in range(6):\n model = sklearn.linear_model.LogisticRegression()\n\n rfe = RFE(model, i+1)\n rfe = rfe.fit(xtr, ytr)\n\n print(\"\\n\", \"rfe\", i+1)\n print(rfe.support_)\n labels.append(rfe.support_)\n print(rfe.score(xte, yte))\n acc.append(rfe.score(xte, yte))\n\n # prob = rfe.predict_proba(xte)\n # loss1 = log_loss(yte, prob)\n #\n # print(\"Loss is \", loss1, \"\\n\")\n\n labels = np.asarray(labels)\n acc = np.asarray(acc)\n bestacc = np.argmax(acc)\n\n bestLabel = labels[bestacc]\n\n if bestLabel[0]:\n filteredFeat.append('Person A')\n if bestLabel[1]:\n filteredFeat.append('Person B')\n if bestLabel[2]:\n filteredFeat.append('Years of Knowing')\n if bestLabel[3]:\n filteredFeat.append('Interaction Duration')\n if bestLabel[4]:\n filteredFeat.append('Interaction Type')\n if bestLabel[5]:\n filteredFeat.append('Moon Phase During Interaction')\n return filteredFeat\n\nfiltFeat = findRFE()\n\n\n\nxtr, xte, ytr, yte = train_test_split(X[filtFeat], X[target], test_size=0.5, shuffle = False, random_state=False)\nxtr, validX, ytr, validY = train_test_split(xtr, ytr, test_size=0.5, shuffle = False, random_state= False)\n\nmodel1 = Sequential()\nmodel1.add(Dense(1, activation='sigmoid', input_dim=len(filtFeat)))\nmodel1.compile(optimizer='SGD',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n\nbestEpoch, bestBatch = Hypereval(model1)\nmodel1.fit(xte, yte, epochs=bestEpoch, batch_size=bestBatch )\nyhatSubmit = np.around(model1.predict(y[filtFeat]))\n\nscores = model1.evaluate(xte, yte)\n\nfor i in range(len(scores)):\n print(\"\\nFinal %s: %f%%\" % (model1.metrics_names[i], scores[i]))\n\nprint(filtFeat)\nyhatSubmit = yhatSubmit.astype(int)\nprint(yhatSubmit)\n\n\nids = list(range(1, yhatSubmit.shape[0] + 1))\ndf = pd.DataFrame(data={'ID': ids, 'Friends': yhatSubmit.flatten()})\ndf.to_csv('deep_answerOrigRFE.csv', index=False)\n", "sub_path": "deeplearningRFEOrig.py", "file_name": "deeplearningRFEOrig.py", "file_ext": "py", "file_size_in_byte": 3875, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "pandas.concat", "line_number": 15, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 24, "usage_type": "call"}, {"api_name": "sklearn.preprocessing", "line_number": 24, "usage_type": "name"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 34, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 35, "usage_type": "call"}, {"api_name": "sklearn.metrics.linear_model.LogisticRegression", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.metrics.linear_model", "line_number": 71, "usage_type": "attribute"}, {"api_name": "sklearn.metrics", "line_number": 71, "usage_type": "name"}, {"api_name": "sklearn.feature_selection.RFE", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 89, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 111, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 112, "usage_type": "call"}, {"api_name": "keras.models.Sequential", "line_number": 114, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 115, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 123, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 136, "usage_type": "call"}]}
+{"seq_id": "640725375", "text": "import multiprocessing\nimport time\n\nclass LoadingManager(object):\n \"\"\"\n This class is responsible for spinning up, spinning down, and coordinating loading processes on\n a single node.\n \"\"\"\n\n def __init__(self, loader, num_processes, node_number, total_nodes):\n self.loader = []\n self.processes = []\n\n begin_loader_id = num_processes * node_number\n total_loaders = num_processes * total_nodes\n\n for pnum in xrange(num_processes):\n proc = multiprocessing.Process(target=loader, args=(begin_loader_id+pnum, total_loaders))\n self.processes.append(proc)\n\n self.node_number = node_number\n\n\n def run(self):\n for index, proc in enumerate(self.processes):\n proc.start()\n for proc in self.processes:\n proc.join()\n", "sub_path": "TBC/core/LoadingManager.py", "file_name": "LoadingManager.py", "file_ext": "py", "file_size_in_byte": 821, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "multiprocessing.Process", "line_number": 18, "usage_type": "call"}]}
+{"seq_id": "623802658", "text": "# -------------------------------------------------------------------------\n#\n# Part of the CodeChecker project, under the Apache License v2.0 with\n# LLVM Exceptions. See LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n#\n# -------------------------------------------------------------------------\n\n\"\"\"\nThis module tests the correctness of the OutputParser and PListConverter, which\nused in sequence transform a Clang Tidy output file to a plist file.\n\"\"\"\nimport copy\nimport os\nimport unittest\n\nimport io\n\nimport codechecker_analyzer.analyzers.clangtidy.output_converter as \\\n tidy_out_conv\n\nOLD_PWD = None\n\n\ndef setup_module():\n \"\"\"Setup the test tidy reprs for the test classes in the module.\"\"\"\n global OLD_PWD\n OLD_PWD = os.getcwd()\n os.chdir(os.path.join(os.path.dirname(__file__), 'tidy_output_test_files'))\n\n # tidy1.out Message/Note representation\n tidy1_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [tidy_out_conv.Note(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'Division by zero')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test.cpp'),\n 8, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy2.out Message/Note representation\n tidy2_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 5, 7,\n \"unused variable 'y'\",\n 'clang-diagnostic-unused-variable'),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 7,\n \"Left side of '||' is false\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 3,\n 'Taking false branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero')\n ]),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero'),\n ]\n\n # tidy2_v6.out Message/Note representation\n tidy2_v6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 7,\n \"Left side of '||' is false\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 16,\n \"Assuming 'x' is 0\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 9, 3,\n 'Taking false branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'Division by zero')\n ]),\n tidy_out_conv.Message(\n os.path.abspath('files/test2.cpp'),\n 13, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero'),\n ]\n\n # tidy3.out Message/Note representation\n tidy3_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test3.cpp'),\n 4, 12,\n 'use nullptr',\n 'modernize-use-nullptr',\n [tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 4, 12,\n 'nullptr')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test3.hh'),\n 6, 6,\n \"Dereference of null pointer (loaded from variable 'x')\",\n 'clang-analyzer-core.NullDereference',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 4, 3,\n \"'x' initialized to a null pointer value\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 6, 11,\n \"Assuming 'argc' is > 3\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 6, 3,\n 'Taking true branch'),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 7, 9,\n \"Passing null pointer value via 1st parameter 'x'\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.cpp'),\n 7, 5,\n \"Calling 'bar'\"),\n tidy_out_conv.Note(\n os.path.abspath('files/test3.hh'),\n 6, 6,\n \"Dereference of null pointer (loaded from variable 'x')\")\n ])\n ]\n\n # tidy5.out Message/Note representation\n tidy5_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 3, 26,\n 'identifier after literal will be treated '\n 'as a reserved user-defined literal suffix in C++11',\n 'clang-diagnostic-c++11-compat-reserved-user-defined-literal',\n None, None),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'Division by zero',\n 'clang-analyzer-core.DivideZero',\n None,\n [tidy_out_conv.Note(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'Division by zero')]),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy5_v6.out Message/Note representation\n tidy5_v6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 3, 26,\n 'invalid suffix on literal; C++11 requires a space '\n 'between literal and identifier',\n 'clang-diagnostic-reserved-user-defined-literal',\n None, None),\n tidy_out_conv.Message(\n os.path.abspath('files/test4.cpp'),\n 10, 12,\n 'remainder by zero is undefined',\n 'clang-diagnostic-division-by-zero')\n ]\n\n # tidy6.out Message/Note representation\n tidy6_repr = [\n tidy_out_conv.Message(\n os.path.abspath('files/test5.cpp'),\n 10, 9,\n 'no matching function for call to \\'get_type\\'',\n 'clang-diagnostic-error',\n None,\n [\n tidy_out_conv.Note(\n os.path.abspath('files/test5.cpp'),\n 2, 18,\n 'candidate template ignored: substitution failure '\n '[with T = int *]: type \\'int *\\' cannot be used prior to '\n '\\'::\\' because it has no members'),\n tidy_out_conv.Note(\n os.path.abspath('files/test5.cpp'),\n 5, 6,\n 'candidate template ignored: substitution failure '\n '[with T = int]: array size is negative'),\n ]\n )]\n\n TidyOutputParserTestCase.tidy1_repr = tidy1_repr\n TidyOutputParserTestCase.tidy2_repr = tidy2_repr\n TidyOutputParserTestCase.tidy2_v6_repr = tidy2_v6_repr\n TidyOutputParserTestCase.tidy3_repr = tidy3_repr\n TidyOutputParserTestCase.tidy5_repr = tidy5_repr\n TidyOutputParserTestCase.tidy6_repr = tidy6_repr\n TidyOutputParserTestCase.tidy5_v6_repr = tidy5_v6_repr\n TidyPListConverterTestCase.tidy1_repr = tidy1_repr\n TidyPListConverterTestCase.tidy2_repr = tidy2_repr\n TidyPListConverterTestCase.tidy3_repr = tidy3_repr\n\n\ndef teardown_module():\n \"\"\"Restore environment after tests have ran.\"\"\"\n global OLD_PWD\n os.chdir(OLD_PWD)\n\n\nclass TidyOutputParserTestCase(unittest.TestCase):\n \"\"\"\n Tests the output of the OutputParser, which converts a Clang Tidy output\n file to zero or more tidy_output_converter.Message.\n \"\"\"\n\n def setUp(self):\n \"\"\"Setup the OutputParser.\"\"\"\n self.parser = tidy_out_conv.OutputParser()\n\n def test_absolute_path(self):\n \"\"\"Test for absolute paths in Messages.\"\"\"\n for tfile in ['abs.out', 'tidy1.out']:\n messages = self.parser.parse_messages_from_file(tfile)\n self.assertNotEqual(len(messages), 0)\n for message in messages:\n self.assertTrue(os.path.isabs(message.path))\n\n def test_empty1(self):\n \"\"\"Test an empty ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('empty1.out')\n self.assertEqual(messages, [])\n\n def test_empty2(self):\n \"\"\"Test a ClangTidy output file that only contains empty lines.\"\"\"\n messages = self.parser.parse_messages_from_file('empty2.out')\n self.assertEqual(messages, [])\n\n def test_tidy1(self):\n \"\"\"Test the generated Messages of tidy1.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy1.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy1_v6(self):\n \"\"\"Test the generated Messages of tidy1.out ClangTidy v6 output\n file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy1_v6.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy2(self):\n \"\"\"Test the generated Messages of tidy2.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy2.out')\n self.assertEqual(len(messages), len(self.tidy2_repr))\n for message in messages:\n self.assertIn(message, self.tidy2_repr)\n\n def test_tidy2_v6(self):\n \"\"\"Test the generated Messages of tidy2.out ClangTidy v6 output\n file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy2_v6.out')\n self.assertEqual(len(messages), len(self.tidy2_v6_repr))\n for message in messages:\n self.assertIn(message, self.tidy2_v6_repr)\n\n def test_tidy3(self):\n \"\"\"Test the generated Messages of tidy3.out ClangTidy output file.\"\"\"\n messages = self.parser.parse_messages_from_file('tidy3.out')\n self.assertEqual(len(messages), len(self.tidy3_repr))\n for message in messages:\n self.assertIn(message, self.tidy3_repr)\n\n def test_tidy4(self):\n \"\"\"\n Test the generated Messages of tidy4.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy4.out')\n self.assertEqual(len(messages), len(self.tidy1_repr))\n for message in messages:\n self.assertIn(message, self.tidy1_repr)\n\n def test_tidy5(self):\n \"\"\"\n Test the grenerated Messages of tidy5.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy5.out')\n for message in messages:\n self.assertIn(message, self.tidy5_repr)\n\n def test_tidy5_v6(self):\n \"\"\"\n Test the grenerated Messages of tidy5_v6.out ClangTidy output file.\n This is an uncomplete file which is equal with tidy1.out except it's\n missing the last two lines.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy5_v6.out')\n for message in messages:\n self.assertIn(message, self.tidy5_v6_repr)\n\n def test_tidy6(self):\n \"\"\"\n Test the generated Messages of tidy6.out ClangTidy output file.\n \"\"\"\n messages = self.parser.parse_messages_from_file('tidy6.out')\n for message in messages:\n self.assertIn(message, self.tidy6_repr)\n\n\nclass TidyPListConverterTestCase(unittest.TestCase):\n \"\"\"\n Test the output of the PListConverter, which converts Messages to plist\n format.\n \"\"\"\n\n def setUp(self):\n \"\"\"Setup the PListConverter.\"\"\"\n self.plist_conv = tidy_out_conv.PListConverter()\n\n def test_empty(self):\n \"\"\"Test for empty Messages.\"\"\"\n orig_plist = copy.deepcopy(self.plist_conv.plist)\n\n self.plist_conv.add_messages([])\n self.assertDictEqual(orig_plist, self.plist_conv.plist)\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('empty.plist', 'rb') as pfile:\n exp = pfile.read()\n print(exp.decode('utf-8'))\n print(output.getvalue().decode('utf-8'))\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy1(self):\n \"\"\"Test for the tidy1.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy1_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test.cpp'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy1.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy2(self):\n \"\"\"Test for the tidy2.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy2_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test2.cpp'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy2.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n\n def test_tidy3(self):\n \"\"\"Test for the tidy3.plist file.\"\"\"\n self.plist_conv.add_messages(self.tidy3_repr)\n\n # use relative path for this test\n self.plist_conv.plist['files'][0] = 'files/test3.cpp'\n self.plist_conv.plist['files'][1] = 'files/test3.hh'\n\n output = io.BytesIO()\n self.plist_conv.write(output)\n\n with open('tidy3.plist', 'rb') as pfile:\n exp = pfile.read()\n self.assertEqual(exp, output.getvalue())\n\n output.close()\n", "sub_path": "analyzer/tests/unit/test_tidy_output_converter.py", "file_name": "test_tidy_output_converter.py", "file_ext": "py", "file_size_in_byte": 15019, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.getcwd", "line_number": 28, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 29, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 33, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 33, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 39, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 39, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 43, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 43, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 52, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 57, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 57, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 64, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 64, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 68, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 68, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 72, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 72, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path", "line_number": 73, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 77, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 77, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 86, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 86, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 93, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 93, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path", "line_number": 94, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 97, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 97, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path", "line_number": 98, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 101, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 101, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 105, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 105, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path", "line_number": 106, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 110, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 110, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 119, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 119, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 124, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 124, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 125, "usage_type": "call"}, {"api_name": "os.path", "line_number": 125, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 128, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 128, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path", "line_number": 129, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 135, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 135, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path", "line_number": 136, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 139, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 139, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 140, "usage_type": "call"}, {"api_name": "os.path", "line_number": 140, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 143, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 143, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 144, "usage_type": "call"}, {"api_name": "os.path", "line_number": 144, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 147, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 147, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 148, "usage_type": "call"}, {"api_name": "os.path", "line_number": 148, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 151, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 151, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 152, "usage_type": "call"}, {"api_name": "os.path", "line_number": 152, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 155, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 155, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path", "line_number": 156, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 164, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 164, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 171, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 171, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 172, "usage_type": "call"}, {"api_name": "os.path", "line_number": 172, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 177, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 177, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 178, "usage_type": "call"}, {"api_name": "os.path", "line_number": 178, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 181, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 181, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path", "line_number": 182, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 190, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 190, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 191, "usage_type": "call"}, {"api_name": "os.path", "line_number": 191, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 197, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 197, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 198, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Message", "line_number": 206, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 206, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 207, "usage_type": "call"}, {"api_name": "os.path", "line_number": 207, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 213, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 213, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 214, "usage_type": "call"}, {"api_name": "os.path", "line_number": 214, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.Note", "line_number": 219, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 219, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path", "line_number": 220, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 242, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 245, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.OutputParser", "line_number": 253, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 253, "usage_type": "name"}, {"api_name": "os.path.isabs", "line_number": 261, "usage_type": "call"}, {"api_name": "os.path", "line_number": 261, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 350, "usage_type": "attribute"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter.PListConverter", "line_number": 358, "usage_type": "call"}, {"api_name": "codechecker_analyzer.analyzers.clangtidy.output_converter", "line_number": 358, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 362, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 367, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 385, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 401, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 418, "usage_type": "call"}]}
+{"seq_id": "439045847", "text": "import wx\r\nimport wx.lib.stattext as statTex\r\nimport conf.config as config\r\nimport utils.charActivitiesUtils as nGUtils\r\nimport utils.bottomMenu as bottomMenu\r\nfrom os.path import join\r\n\r\nclass imageCharMatch(wx.Panel):\r\n def __init__(self, parent, id, mainWin, mainPanel, currentLesson):\r\n if wx.Platform != \"__WXGTK__\":\r\n statText = wx.StaticText\r\n else:\r\n statText = statTex.GenStaticText\r\n self.mainWin = mainWin\r\n self.mainPanel = mainPanel\r\n self.currentLesson = currentLesson\r\n self.buttonPressed = 20\r\n self.question = ''\r\n self.eventQueue = []\r\n\r\n self.question, self.answerList, self.answerImageList = nGUtils.nextImageMatchQuestion(self.currentLesson)\r\n self.checkNumberSet()\r\n\r\n self.fontSize = config.fontSize[4]\r\n if currentLesson == 'aaa': self.fontSize = config.fontSize[4]\r\n if currentLesson == 'kaKha': self.fontSize = config.fontSize[4]\r\n if currentLesson == 'oneTwo': self.fontSize = config.fontSize[5]\r\n if currentLesson == 'time': self.fontSize = config.fontSize[4]\r\n\r\n self.displayPanel = wx.Panel(parent, -1, (0, 0), (800, 600))\r\n self.displayPanel.SetBackgroundColour(config.backgroundColour)\r\n\r\n questionImg = wx.Bitmap(self.answerImageList[self.answerList.index(self.question)], wx.BITMAP_TYPE_PNG)\r\n self.questionImage = wx.StaticBitmap(self.displayPanel, 1, questionImg, (40,80), (questionImg.GetWidth(), questionImg.GetHeight()))\r\n\r\n displayImg = wx.Bitmap(join(config.coreImagesPath, 'divider.png'), wx.BITMAP_TYPE_PNG)\r\n self.displayImage = wx.StaticBitmap(self.displayPanel, -1, displayImg, (240,80), (displayImg.GetWidth(), displayImg.GetHeight()))\r\n\r\n self.displayText1 = statText(self.displayPanel, 1, self.answerList[0], (280, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText1.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText1.SetBackgroundColour(config.backgroundColour)\r\n self.displayText1.Bind(wx.EVT_LEFT_DOWN, self.OnAns1, id=1)\r\n\r\n self.displayText2 = statText(self.displayPanel, 2, self.answerList[1], (440, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText2.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText2.SetBackgroundColour(config.backgroundColour)\r\n self.displayText2.Bind(wx.EVT_LEFT_DOWN, self.OnAns2, id=2)\r\n\r\n self.displayText3 = statText(self.displayPanel, 3, self.answerList[2], (620, 70), style = wx.ALIGN_CENTRE)\r\n self.displayText3.SetFont(wx.Font(self.fontSize, wx.SWISS, wx.NORMAL, wx.NORMAL, False, config.fontName))\r\n self.displayText3.SetBackgroundColour(config.backgroundColour)\r\n self.displayText3.Bind(wx.EVT_LEFT_DOWN, self.OnAns3, id=3)\r\n\r\n answerImg = wx.Bitmap(join(config.coreImagesPath, 'ansBlank.png'), wx.BITMAP_TYPE_PNG)\r\n self.answerImage = wx.StaticBitmap(self.displayPanel, -1, answerImg, (160,300), (180,140))\r\n self.answerImage.SetBackgroundColour(config.backgroundColour)\r\n\r\n nextQuestionImg = wx.Bitmap(join(config.buttonsPath,'nextQuestion.png'), wx.BITMAP_TYPE_PNG)\r\n self.nextQuestionButton = wx.BitmapButton(self.displayPanel, 4, nextQuestionImg, (460,320), style = wx.NO_BORDER)\r\n self.nextQuestionButton.SetBackgroundColour(config.backgroundColour)\r\n self.nextQuestionButton.Bind(wx.EVT_BUTTON, self.OnNextQuestion, id=4)\r\n\r\n bottomMenu.bottomMenu([self.displayPanel], parent, self.mainWin, 'threeButton', self.mainPanel)\r\n \r\n def OnNextQuestion(self, event=None):\r\n if len(self.eventQueue) != 0:\r\n self.eventQueue[0].SetBackgroundColour(config.backgroundColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n self.eventQueue = []\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'ansBlank.png'), wx.BITMAP_TYPE_PNG))\r\n self.questionImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'blank.png'), wx.BITMAP_TYPE_PNG))\r\n self.question, self.answerList, self.answerImageList = nGUtils.nextImageMatchQuestion(self.currentLesson)\r\n self.questionImage.SetBitmap(wx.Bitmap(self.answerImageList[self.answerList.index(self.question)], wx.BITMAP_TYPE_PNG))\r\n self.checkNumberSet()\r\n self.displayText1.SetLabel(self.answerList[0])\r\n self.displayText2.SetLabel(self.answerList[1])\r\n self.displayText3.SetLabel(self.answerList[2])\r\n\r\n def OnAns1(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 0\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def OnAns2(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 1\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def OnAns3(self, event):\r\n self.eventQueue.append(event.GetEventObject())\r\n self.buttonPressed = 2\r\n self.changeBackgroundColour()\r\n answer = self.checkAnswer()\r\n self.displayResult(answer)\r\n\r\n def changeBackgroundColour(self):\r\n if len(self.eventQueue) == 1:\r\n self.eventQueue[0].SetBackgroundColour(config.fillColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n elif len(self.eventQueue) == 2:\r\n self.eventQueue[0].SetBackgroundColour(config.backgroundColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n self.eventQueue.pop(0)\r\n self.eventQueue[0].SetBackgroundColour(config.fillColour)\r\n self.eventQueue[0].SetLabel(self.eventQueue[0].GetLabel())\r\n\r\n def checkAnswer(self):\r\n answer = ''\r\n if self.question == self.answerList[self.buttonPressed]:\r\n answer = \"Right\"\r\n else:\r\n answer = \"Wrong\"\r\n return answer\r\n\r\n def displayResult(self, answer):\r\n if answer == \"Right\":\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'right.png'), wx.BITMAP_TYPE_PNG))\r\n else:\r\n self.answerImage.SetBitmap(wx.Bitmap(join(config.coreImagesPath, 'wrong.png'), wx.BITMAP_TYPE_PNG))\r\n \r\n## This function is to check for double printing of chars like && in Linux.\r\n## The function is kept here to solve problems occuring only in specific modules like this one.\r\n def checkNumberSet(self):\r\n if wx.Platform == \"__WXGTK__\":\r\n for i in range(len(self.answerList)):\r\n if self.answerList[i] == '&&':\r\n self.answerList[i] = self.answerList[i][0]\r\n else:\r\n pass\r\n", "sub_path": "eBarnamala/activities/imageCharMatch.py", "file_name": "imageCharMatch.py", "file_ext": "py", "file_size_in_byte": 6848, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "wx.Panel", "line_number": 8, "usage_type": "attribute"}, {"api_name": "wx.Platform", "line_number": 10, "usage_type": "attribute"}, {"api_name": "wx.StaticText", "line_number": 11, "usage_type": "attribute"}, {"api_name": "wx.lib.stattext.GenStaticText", "line_number": 13, "usage_type": "attribute"}, {"api_name": "wx.lib.stattext", "line_number": 13, "usage_type": "name"}, {"api_name": "utils.charActivitiesUtils.nextImageMatchQuestion", "line_number": 21, "usage_type": "call"}, {"api_name": "utils.charActivitiesUtils", "line_number": 21, "usage_type": "name"}, {"api_name": "conf.config.fontSize", "line_number": 24, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 24, "usage_type": "name"}, {"api_name": "conf.config.fontSize", "line_number": 25, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 25, "usage_type": "name"}, {"api_name": "conf.config.fontSize", "line_number": 26, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 26, "usage_type": "name"}, {"api_name": "conf.config.fontSize", "line_number": 27, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 27, "usage_type": "name"}, {"api_name": "conf.config.fontSize", "line_number": 28, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 28, "usage_type": "name"}, {"api_name": "wx.Panel", "line_number": 30, "usage_type": "call"}, {"api_name": "conf.config.backgroundColour", "line_number": 31, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 31, "usage_type": "name"}, {"api_name": "wx.Bitmap", "line_number": 33, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 33, "usage_type": "attribute"}, {"api_name": "wx.StaticBitmap", "line_number": 34, "usage_type": "call"}, {"api_name": "wx.Bitmap", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 36, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 36, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 36, "usage_type": "attribute"}, {"api_name": "wx.StaticBitmap", "line_number": 37, "usage_type": "call"}, {"api_name": "wx.ALIGN_CENTRE", "line_number": 39, "usage_type": "attribute"}, {"api_name": "wx.Font", "line_number": 40, "usage_type": "call"}, {"api_name": "wx.SWISS", "line_number": 40, "usage_type": "attribute"}, {"api_name": "wx.NORMAL", "line_number": 40, "usage_type": "attribute"}, {"api_name": "conf.config.fontName", "line_number": 40, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 40, "usage_type": "name"}, {"api_name": "conf.config.backgroundColour", "line_number": 41, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 41, "usage_type": "name"}, {"api_name": "wx.EVT_LEFT_DOWN", "line_number": 42, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTRE", "line_number": 44, "usage_type": "attribute"}, {"api_name": "wx.Font", "line_number": 45, "usage_type": "call"}, {"api_name": "wx.SWISS", "line_number": 45, "usage_type": "attribute"}, {"api_name": "wx.NORMAL", "line_number": 45, "usage_type": "attribute"}, {"api_name": "conf.config.fontName", "line_number": 45, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 45, "usage_type": "name"}, {"api_name": "conf.config.backgroundColour", "line_number": 46, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 46, "usage_type": "name"}, {"api_name": "wx.EVT_LEFT_DOWN", "line_number": 47, "usage_type": "attribute"}, {"api_name": "wx.ALIGN_CENTRE", "line_number": 49, "usage_type": "attribute"}, {"api_name": "wx.Font", "line_number": 50, "usage_type": "call"}, {"api_name": "wx.SWISS", "line_number": 50, "usage_type": "attribute"}, {"api_name": "wx.NORMAL", "line_number": 50, "usage_type": "attribute"}, {"api_name": "conf.config.fontName", "line_number": 50, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 50, "usage_type": "name"}, {"api_name": "conf.config.backgroundColour", "line_number": 51, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 51, "usage_type": "name"}, {"api_name": "wx.EVT_LEFT_DOWN", "line_number": 52, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 54, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 54, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 54, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 54, "usage_type": "attribute"}, {"api_name": "wx.StaticBitmap", "line_number": 55, "usage_type": "call"}, {"api_name": "conf.config.backgroundColour", "line_number": 56, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 56, "usage_type": "name"}, {"api_name": "wx.Bitmap", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "conf.config.buttonsPath", "line_number": 58, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 58, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 58, "usage_type": "attribute"}, {"api_name": "wx.BitmapButton", "line_number": 59, "usage_type": "call"}, {"api_name": "wx.NO_BORDER", "line_number": 59, "usage_type": "attribute"}, {"api_name": "conf.config.backgroundColour", "line_number": 60, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 60, "usage_type": "name"}, {"api_name": "wx.EVT_BUTTON", "line_number": 61, "usage_type": "attribute"}, {"api_name": "utils.bottomMenu.bottomMenu", "line_number": 63, "usage_type": "call"}, {"api_name": "utils.bottomMenu", "line_number": 63, "usage_type": "name"}, {"api_name": "conf.config.backgroundColour", "line_number": 67, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 67, "usage_type": "name"}, {"api_name": "wx.Bitmap", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 70, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 70, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 70, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 71, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 71, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 71, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 71, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 71, "usage_type": "attribute"}, {"api_name": "utils.charActivitiesUtils.nextImageMatchQuestion", "line_number": 72, "usage_type": "call"}, {"api_name": "utils.charActivitiesUtils", "line_number": 72, "usage_type": "name"}, {"api_name": "wx.Bitmap", "line_number": 73, "usage_type": "call"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 73, "usage_type": "attribute"}, {"api_name": "conf.config.fillColour", "line_number": 102, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 102, "usage_type": "name"}, {"api_name": "conf.config.backgroundColour", "line_number": 105, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 105, "usage_type": "name"}, {"api_name": "conf.config.fillColour", "line_number": 108, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 108, "usage_type": "name"}, {"api_name": "wx.Bitmap", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 121, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 121, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 121, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 121, "usage_type": "attribute"}, {"api_name": "wx.Bitmap", "line_number": 123, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 123, "usage_type": "call"}, {"api_name": "conf.config.coreImagesPath", "line_number": 123, "usage_type": "attribute"}, {"api_name": "conf.config", "line_number": 123, "usage_type": "name"}, {"api_name": "wx.BITMAP_TYPE_PNG", "line_number": 123, "usage_type": "attribute"}, {"api_name": "wx.Platform", "line_number": 128, "usage_type": "attribute"}]}
+{"seq_id": "111061673", "text": "import streamlit as st\nimport folium\nimport numpy as np\nimport pandas as pd\nfrom streamlit_folium import folium_static\n\ndef create_test_df():\n data = {\"id\": range(10000),\n \"year\": np.random.choice(range(2018, 2021), 10000),\n \"type\": np.random.choice([\"type_a\", \"type_b\", \"type_c\"], 10000),\n \"latitude\": np.random.uniform(low=10, high=20, size=10000),\n \"longitude\": np.random.uniform(low=10, high=20, size=10000)}\n\n # Respects order\n return pd.DataFrame(data, columns=[\"id\", \"year\", \"type\", \"latitude\", \"longitude\"])\n\n\ndef _plot_dot(point, map_element, color_col, radius=4, weight=1, color='black'):\n color_dict = {2018: \"blue\", 2019: \"orange\", 2020: \"red\"}\n\n folium.CircleMarker(location=[point[\"latitude\"], point[\"longitude\"]], radius=radius, weight=weight,\n color=color, fill=True,\n fill_color=color_dict[point[color_col]],\n fill_opacity=0.9,\n tooltip=f'id: {str(point[\"id\"])}'\n f'
'f'year: {str(point[\"year\"])}'\n f'
'f'type: {str(point[\"type\"])}',\n popup=f'id: {str(point[\"id\"])}'\n f'
'f'year: {str(point[\"year\"])}'\n f'
'f'type: {str(point[\"type\"])}'\n ).add_to(map_element)\n\n\ndef generate_map(df):\n map_element = folium.Map(location=[15, 15], zoom_start=6, tiles='cartodbpositron')\n\n df.apply(_plot_dot, axis=1, args=[map_element, \"year\"])\n\n return map_element\n\nif __name__ == \"__main__\":\n st.title(\"Complex Example\")\n\n df = create_test_df()\n\n option = st.selectbox('Select year?', df['year'].unique())\n st.write('You selected: ', option)\n\n dict_years = {}\n for year in df['year'].unique():\n dict_years[year] = generate_map(df[df[\"year\"] == year])\n\n folium_static(dict_years[option])\n\n", "sub_path": "examples/streamlit_folium_complex_example.py", "file_name": "streamlit_folium_complex_example.py", "file_ext": "py", "file_size_in_byte": 2016, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.random.choice", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 9, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 10, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pandas.DataFrame", "line_number": 15, "usage_type": "call"}, {"api_name": "folium.CircleMarker", "line_number": 21, "usage_type": "call"}, {"api_name": "folium.Map", "line_number": 35, "usage_type": "call"}, {"api_name": "streamlit.title", "line_number": 42, "usage_type": "call"}, {"api_name": "streamlit.selectbox", "line_number": 46, "usage_type": "call"}, {"api_name": "streamlit.write", "line_number": 47, "usage_type": "call"}, {"api_name": "streamlit_folium.folium_static", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "141944570", "text": "from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom .views import EmployeeViewSet\n\n#User URL's\nempUrls = [\n url('list/', EmployeeViewSet.list),\n url('create/', EmployeeViewSet.post),\n url('matchFace/', EmployeeViewSet.match_face)\n]\n\nurlpatterns = [\n url('emp/', include(empUrls)),\n]", "sub_path": "backend/backend/app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 320, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "views.EmployeeViewSet.list", "line_number": 7, "usage_type": "attribute"}, {"api_name": "views.EmployeeViewSet", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "views.EmployeeViewSet.post", "line_number": 8, "usage_type": "attribute"}, {"api_name": "views.EmployeeViewSet", "line_number": 8, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "views.EmployeeViewSet.match_face", "line_number": 9, "usage_type": "attribute"}, {"api_name": "views.EmployeeViewSet", "line_number": 9, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "179027562", "text": "import os\nimport time\nimport string\nimport pickle\nimport json\nimport re\nfrom operator import itemgetter\n\nfrom nltk.corpus import stopwords as sw\nfrom nltk.corpus import wordnet as wn\nfrom nltk import wordpunct_tokenize\nfrom nltk import WordNetLemmatizer\nfrom nltk import sent_tokenize\nfrom nltk import pos_tag\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.linear_model import LogisticRegression\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics import classification_report as clsr\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n#from sklearn.cross_validation import train_test_split as tts\nfrom sklearn.model_selection import train_test_split as tts\n\nimport sys\nreload(sys)\nsys.path \n\n# Notes1.- Other is positive(1) - Aurora is negative(0)\n\n# Notes2.- The underlying C implementation uses a random number generator to select features when fitting the model. It is thus not uncommon to have slightly different results for the same input data\n\nhttp_re = re.compile(r'\\s+http://[^\\s]*')\nremove_ellipsis_re = re.compile(r'\\.\\.\\.')\nat_sign_re = re.compile(r'\\@\\S+')\npunct_re = re.compile(r\"[\\\"'\\[\\],.:;()\\-&!]\")\nprice_re = re.compile(r\"\\d+\\.\\d\\d\")\nnumber_re = re.compile(r\"\\d+\")\n\n# converts to lower case and clean up the text\ndef normalize_tweet(tweet):\n t = tweet.lower()\n #t = re.sub(price_re, 'PRICE', t)\n t = re.sub(remove_ellipsis_re, '', t)\n t = re.sub(http_re, ' LINK', t)\n t = re.sub(punct_re, '', t)\n t = re.sub(at_sign_re, '@', t)\n t = re.sub(number_re, 'NUM', t)\n #t = re.sub(r\"\\n\", \" \", t) # remove newlines from text\n t = re.sub(r'[^\\w]', ' ', t)\n return t\n\n\ndef identity(arg):\n \"\"\"\n Simple identity function works as a passthrough.\n \"\"\"\n return arg\n\nclass NLTKPreprocessor(BaseEstimator, TransformerMixin):\n \"\"\"\n Transforms input data by using NLTK tokenization, lemmatization, and\n other normalization and filtering techniques.\n \"\"\"\n\n def __init__(self, stopwords=None, punct=None, lower=True, strip=True):\n \"\"\"\n Instantiates the preprocessor, which make load corpora, models, or do\n other time-intenstive NLTK data loading.\n \"\"\"\n self.lower = lower\n self.strip = strip\n self.stopwords = set(stopwords) if stopwords else set(sw.words('english'))\n self.punct = set(punct) if punct else set(string.punctuation)\n self.lemmatizer = WordNetLemmatizer()\n\n def fit(self, X, y=None):\n \"\"\"\n Fit simply returns self, no other information is needed.\n \"\"\"\n return self\n\n def inverse_transform(self, X):\n \"\"\"\n No inverse transformation\n \"\"\"\n return X\n\n def transform(self, X):\n \"\"\"\n Actually runs the preprocessing on each document.\n \"\"\"\n return [\n list(self.tokenize(doc)) for doc in X\n ]\n\n def tokenize(self, document):\n \"\"\"\n Returns a normalized, lemmatized list of tokens from a document by\n applying segmentation (breaking into sentences), then word/punctuation\n tokenization, and finally part of speech tagging. It uses the part of\n speech tags to look up the lemma in WordNet, and returns the lowercase\n version of all the words, removing stopwords and punctuation.\n \"\"\"\n # Break the document into sentences\n\t#print(\"Document is %s\" % document)\n\n try:\n sents = sent_tokenize(document)\n except ValueError:\n sents = \"ERROR\"\n if sents!= \"ERROR\":\n for sent in sents:\n try:\n sent = normalize_tweet(sent)\n for token, tag in pos_tag(wordpunct_tokenize(sent)):\n token = token.lower() if self.lower else token\n token = token.strip() if self.strip else token\n token = token.strip('_') if self.strip else token\n token = token.strip('*') if self.strip else token\n token = token.rstrip('?:!.,;\"!@')\n if token in self.stopwords or all(char in self.punct for char in token):\n continue\n lemma = self.lemmatize(token, tag)\n yield lemma\n except ValueError:\n pass\n\n def lemmatize(self, token, tag):\n \"\"\"\n Converts the Penn Treebank tag to a WordNet POS tag, then uses that\n tag to perform much more accurate WordNet lemmatization.\n \"\"\"\n tag = {\n 'N': wn.NOUN,\n 'V': wn.VERB,\n 'R': wn.ADV,\n 'J': wn.ADJ\n }.get(tag[0], wn.NOUN)\n\n return self.lemmatizer.lemmatize(token, tag)\n\n\n", "sub_path": "Tweet_Classification_Auroras/Solution_Supervised_SVM/svm_model/classification_module.py", "file_name": "classification_module.py", "file_ext": "py", "file_size_in_byte": 5054, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 39, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 40, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 41, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 42, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 43, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 44, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 50, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 51, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 52, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 53, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 54, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 56, "usage_type": "call"}, {"api_name": "sklearn.base.BaseEstimator", "line_number": 66, "usage_type": "name"}, {"api_name": "sklearn.base.TransformerMixin", "line_number": 66, "usage_type": "name"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 79, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 79, "usage_type": "name"}, {"api_name": "string.punctuation", "line_number": 80, "usage_type": "attribute"}, {"api_name": "nltk.WordNetLemmatizer", "line_number": 81, "usage_type": "call"}, {"api_name": "nltk.sent_tokenize", "line_number": 115, "usage_type": "call"}, {"api_name": "nltk.pos_tag", "line_number": 122, "usage_type": "call"}, {"api_name": "nltk.wordpunct_tokenize", "line_number": 122, "usage_type": "call"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 141, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 141, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.VERB", "line_number": 142, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 142, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADV", "line_number": 143, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 143, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.ADJ", "line_number": 144, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 144, "usage_type": "name"}, {"api_name": "nltk.corpus.wordnet.NOUN", "line_number": 145, "usage_type": "attribute"}, {"api_name": "nltk.corpus.wordnet", "line_number": 145, "usage_type": "name"}]}
+{"seq_id": "634833900", "text": "\"\"\"Update all the get-pip.py scripts.\"\"\"\n\nimport itertools\nimport operator\nimport re\nfrom base64 import b85encode\nfrom functools import lru_cache\nfrom io import BytesIO\nfrom pathlib import Path, PosixPath\nfrom typing import Dict, Iterable, List, Tuple\nfrom zipfile import ZipFile\n\nimport requests\nfrom cachecontrol import CacheControl\nfrom cachecontrol.caches.file_cache import FileCache\nfrom packaging.specifiers import SpecifierSet\nfrom packaging.version import Version\nfrom rich.console import Console\n\nSCRIPT_CONSTRAINTS = {\n \"default\": {\n \"pip\": \"\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n \"2.6\": {\n \"pip\": \"<10\",\n \"setuptools\": \"<37\",\n \"wheel\": \"<0.30\",\n },\n \"2.7\": {\n \"pip\": \"<21.0\",\n \"setuptools\": \"<45\",\n \"wheel\": \"\",\n },\n \"3.2\": {\n \"pip\": \"<8\",\n \"setuptools\": \"<30\",\n \"wheel\": \"<0.30\",\n },\n \"3.3\": {\n \"pip\": \"<18\",\n \"setuptools\": \"\",\n \"wheel\": \"<0.30\",\n },\n \"3.4\": {\n \"pip\": \"<19.2\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n \"3.5\": {\n \"pip\": \"<21.0\",\n \"setuptools\": \"\",\n \"wheel\": \"\",\n },\n}\n\nMOVED_SCRIPTS = {\n # legacy: current\n \"get-pip.py\": \"get-pip.py\", # redirect users of the file in the repository root.\n \"2.6/get-pip.py\": \"pip/2.6/get-pip.py\",\n \"2.7/get-pip.py\": \"pip/2.7/get-pip.py\",\n \"3.2/get-pip.py\": \"pip/3.2/get-pip.py\",\n \"3.3/get-pip.py\": \"pip/3.3/get-pip.py\",\n \"3.4/get-pip.py\": \"pip/3.4/get-pip.py\",\n \"3.5/get-pip.py\": \"pip/3.5/get-pip.py\",\n}\n\n\ndef get_all_pip_versions() -> Dict[Version, Tuple[str, str]]:\n data = requests.get(\"https://pypi.python.org/pypi/pip/json\").json()\n\n versions = sorted(Version(s) for s in data[\"releases\"].keys())\n\n retval = {}\n for version in versions:\n wheels = [\n (file[\"url\"], file[\"md5_digest\"])\n for file in data[\"releases\"][str(version)]\n if file[\"url\"].endswith(\".whl\")\n ]\n if not wheels:\n continue\n assert len(wheels) == 1, (version, wheels)\n retval[version] = wheels[0]\n return retval\n\n\ndef determine_latest(versions: Iterable[Version], *, constraint: str):\n assert sorted(versions) == list(versions)\n return list(SpecifierSet(constraint).filter(versions))[-1]\n\n\n@lru_cache\ndef get_ordered_templates() -> List[Tuple[Version, Path]]:\n \"\"\"Get an ordered list of templates, based on the max version they support.\n\n This looks at the templates directory, trims the \"pre-\" from the files,\n and returns a sorted list of (version, template_path) tuples.\n \"\"\"\n all_templates = list(Path(\"./templates\").iterdir())\n\n fallback = None\n ordered_templates = []\n for template in all_templates:\n # `moved.py` isn't one of the templates to be used here.\n if template.name == \"moved.py\":\n continue\n if template.name == \"default.py\":\n fallback = template\n continue\n assert template.name.startswith(\"pre-\")\n\n version_str = template.name[4:-3] # \"pre-{version}.py\"\n version = Version(version_str)\n ordered_templates.append((version, template))\n\n # Use the epoch mechanism, to force the fallback to the end.\n assert fallback is not None\n assert fallback.name == \"default.py\"\n ordered_templates.append((Version(\"1!0\"), fallback))\n\n # Order the (version, template) tuples, by increasing version numbers.\n return sorted(ordered_templates, key=operator.itemgetter(0))\n\n\ndef determine_template(version: Version):\n ordered_templates = get_ordered_templates()\n for template_version, template in ordered_templates:\n if version < template_version:\n return template\n else:\n assert template.name == \"default.py\"\n return template\n\n\ndef download_wheel(url: str, expected_md5: str) -> bytes:\n session = requests.session()\n cached_session = CacheControl(session, cache=FileCache(\".web_cache\"))\n\n response = cached_session.get(url)\n return response.content\n\n\ndef populated_script_constraints(original_constraints):\n \"\"\"Yields the original constraints, with `minimum_supported_version` added.\n\n For `M.N/get-pip.py`, it would be \"(M, N)\".\n\n For the \"default\" get-pip.py, it would be \"(M, N+1)\" where M.N is the\n highest version in the rest of the mapping.\n\n Also, the yield order is defined as \"default\" and then versions in\n increasing order.\n \"\"\"\n sorted_python_versions = sorted(set(original_constraints) - {\"default\"})\n for variant in itertools.chain([\"default\"], sorted_python_versions):\n if variant == \"default\":\n major, minor = map(int, sorted_python_versions[-1].split(\".\"))\n minor += 1\n else:\n major, minor = map(int, variant.split(\".\"))\n\n mapping = original_constraints[variant].copy()\n mapping[\"minimum_supported_version\"] = f\"({major}, {minor})\"\n\n yield variant, mapping\n\n\ndef repack_wheel(data: bytes):\n \"\"\"Remove the .dist-info, so that this is no longer a valid wheel.\"\"\"\n new_data = BytesIO()\n with ZipFile(BytesIO(data)) as existing_zip:\n with ZipFile(new_data, mode=\"w\") as new_zip:\n for zipinfo in existing_zip.infolist():\n if re.search(r\"pip-.+\\.dist-info/\", zipinfo.filename):\n continue\n new_zip.writestr(zipinfo, existing_zip.read(zipinfo))\n\n return new_data.getvalue()\n\n\ndef encode_wheel_contents(data: bytes) -> str:\n zipdata = b85encode(data).decode(\"utf8\")\n\n chunked = []\n for i in range(0, len(zipdata), 79):\n chunked.append(zipdata[i : i + 79])\n\n return \"\\n\".join(chunked)\n\n\ndef determine_destination(base: str, variant: str) -> Path:\n public = Path(base)\n if not public.exists():\n public.mkdir()\n\n if variant == \"default\":\n return public / \"get-pip.py\"\n\n retval = public / variant / \"get-pip.py\"\n if not retval.parent.exists():\n retval.parent.mkdir()\n\n return retval\n\n\ndef generate_one(variant, mapping, *, console, pip_versions):\n # Determing the correct wheel to download\n pip_version = determine_latest(pip_versions.keys(), constraint=mapping[\"pip\"])\n wheel_url, wheel_hash = pip_versions[pip_version]\n\n console.log(f\" Downloading [green]{PosixPath(wheel_url).name}\")\n original_wheel = download_wheel(wheel_url, wheel_hash)\n repacked_wheel = repack_wheel(original_wheel)\n encoded_wheel = encode_wheel_contents(repacked_wheel)\n\n # Generate the script, by rendering the template\n template = determine_template(pip_version)\n console.log(f\" Rendering [yellow]{template}\")\n rendered_template = template.read_text().format(\n zipfile=encoded_wheel,\n installed_version=pip_version,\n pip_version=mapping[\"pip\"],\n setuptools_version=mapping[\"setuptools\"],\n wheel_version=mapping[\"wheel\"],\n minimum_supported_version=mapping[\"minimum_supported_version\"],\n )\n # Write the script to the correct location\n destination = determine_destination(\"public\", variant)\n console.log(f\" Writing [blue]{destination}\")\n destination.write_text(rendered_template)\n\n\ndef generate_moved(destination: str, *, location: str, console: Console):\n template = Path(\"templates\") / \"moved.py\"\n assert template.exists()\n\n rendered_template = template.read_text().format(location=location)\n console.log(f\" Writing [blue]{destination}[reset]\")\n console.log(f\" Points users to [cyan]{location}[reset]\")\n Path(destination).write_text(rendered_template)\n\n\ndef main() -> None:\n console = Console()\n with console.status(\"Fetching pip versions...\"):\n pip_versions = get_all_pip_versions()\n console.log(f\"Found {len(pip_versions)} available pip versions.\")\n console.log(f\"Latest version: {max(pip_versions)}\")\n\n with console.status(\"Generating scripts...\") as status:\n for variant, mapping in populated_script_constraints(SCRIPT_CONSTRAINTS):\n status.update(f\"Working on [magenta]{variant}\")\n console.log(f\"[magenta]{variant}\")\n\n generate_one(variant, mapping, console=console, pip_versions=pip_versions)\n\n if MOVED_SCRIPTS:\n console.log(\"[magenta]Generating 'moved' scripts...\")\n with console.status(\"Generating 'moved' scripts...\") as status:\n for legacy, current in MOVED_SCRIPTS.items():\n status.update(f\"Working on [magenta]{legacy}\")\n generate_moved(legacy, console=console, location=current)\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "scripts/generate.py", "file_name": "generate.py", "file_ext": "py", "file_size_in_byte": 8608, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 71, "usage_type": "call"}, {"api_name": "packaging.version.Version", "line_number": 73, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 70, "usage_type": "name"}, {"api_name": "packaging.version.Version", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 70, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 89, "usage_type": "name"}, {"api_name": "packaging.version.Version", "line_number": 89, "usage_type": "name"}, {"api_name": "packaging.specifiers.SpecifierSet", "line_number": 91, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 101, "usage_type": "call"}, {"api_name": "packaging.version.Version", "line_number": 115, "usage_type": "call"}, {"api_name": "packaging.version.Version", "line_number": 121, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 124, "usage_type": "call"}, {"api_name": "functools.lru_cache", "line_number": 94, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 95, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 95, "usage_type": "name"}, {"api_name": "packaging.version.Version", "line_number": 95, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 95, "usage_type": "name"}, {"api_name": "packaging.version.Version", "line_number": 127, "usage_type": "name"}, {"api_name": "requests.session", "line_number": 138, "usage_type": "call"}, {"api_name": "cachecontrol.CacheControl", "line_number": 139, "usage_type": "call"}, {"api_name": "cachecontrol.caches.file_cache.FileCache", "line_number": 139, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 157, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 172, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 173, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 173, "usage_type": "call"}, {"api_name": "zipfile.ZipFile", "line_number": 174, "usage_type": "call"}, {"api_name": "re.search", "line_number": 176, "usage_type": "call"}, {"api_name": "base64.b85encode", "line_number": 184, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 194, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 193, "usage_type": "name"}, {"api_name": "pathlib.PosixPath", "line_number": 213, "usage_type": "call"}, {"api_name": "rich.console.Console", "line_number": 235, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 236, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 242, "usage_type": "call"}, {"api_name": "rich.console.Console", "line_number": 246, "usage_type": "call"}]}
+{"seq_id": "335603879", "text": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ResourceOperation(Model):\n \"\"\"Individual resource operation information.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param resource_name: Name of the resource as specified in the artifacts.\n For ARM resources, this is the name of the resource specified in the\n template.\n :type resource_name: str\n :ivar operation_id: Unique identifier of the operation. For ARM resources,\n this is the operationId obtained from ARM service.\n :vartype operation_id: str\n :param resource_type: Type of the resource as specified in the artifacts.\n For ARM resources, this is the type of the resource specified in the\n template.\n :type resource_type: str\n :ivar provisioning_state: State of the resource deployment. For ARM\n resources, this is the current provisioning state of the resource.\n :vartype provisioning_state: str\n :ivar status_message: Descriptive information of the resource operation.\n :vartype status_message: str\n :ivar status_code: Http status code of the operation.\n :vartype status_code: str\n \"\"\"\n\n _validation = {\n 'operation_id': {'readonly': True},\n 'provisioning_state': {'readonly': True},\n 'status_message': {'readonly': True},\n 'status_code': {'readonly': True},\n }\n\n _attribute_map = {\n 'resource_name': {'key': 'resourceName', 'type': 'str'},\n 'operation_id': {'key': 'operationId', 'type': 'str'},\n 'resource_type': {'key': 'resourceType', 'type': 'str'},\n 'provisioning_state': {'key': 'provisioningState', 'type': 'str'},\n 'status_message': {'key': 'statusMessage', 'type': 'str'},\n 'status_code': {'key': 'statusCode', 'type': 'str'},\n }\n\n def __init__(self, *, resource_name: str=None, resource_type: str=None, **kwargs) -> None:\n super(ResourceOperation, self).__init__(**kwargs)\n self.resource_name = resource_name\n self.operation_id = None\n self.resource_type = resource_type\n self.provisioning_state = None\n self.status_message = None\n self.status_code = None\n", "sub_path": "azure-mgmt-deploymentmanager/azure/mgmt/deploymentmanager/models/resource_operation_py3.py", "file_name": "resource_operation_py3.py", "file_ext": "py", "file_size_in_byte": 2655, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "msrest.serialization.Model", "line_number": 15, "usage_type": "name"}]}
+{"seq_id": "101120847", "text": "# coding=utf-8\n# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\n\nfrom azure.core.async_paging import AsyncItemPaged\n\n\nclass AnalyzeHealthcareEntitiesResultAsync(AsyncItemPaged):\n def __init__(self, *args, **kwargs):\n self.model_version = kwargs.pop('model_version')\n self.statistics = kwargs.pop('statistics')\n super(AnalyzeHealthcareEntitiesResultAsync, self).__init__(*args, **kwargs)\n\n\nclass AnalyzeResultAsync(AsyncItemPaged):\n def __init__(self, *args, **kwargs):\n self.statistics = kwargs.pop('statistics', None)\n super(AnalyzeResultAsync, self).__init__(*args, **kwargs)\n", "sub_path": "sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py", "file_name": "_async_paging.py", "file_ext": "py", "file_size_in_byte": 721, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "azure.core.async_paging.AsyncItemPaged", "line_number": 10, "usage_type": "name"}, {"api_name": "azure.core.async_paging.AsyncItemPaged", "line_number": 17, "usage_type": "name"}]}
+{"seq_id": "288781796", "text": "'''\n\nThis programme calculates the time difference between reported milestones\n\nOutput document:\n1) excel workbook with all project milestone information for each project\n\nSee instructions below.\n\nNote: all master data is taken from the data file. Make sure this is up to date and that all relevant data is in\nthe import statement.\n\n'''\n\n#TODO solve problem re filtering in excel when values have + sign in front of the them\n\nfrom openpyxl import Workbook\nfrom analysis.engine_functions import project_time_difference, all_milestones_dict\nfrom analysis.data import list_of_masters_all, bc_index, baseline_bc_stamp, root_path\n\n\ndef put_into_wb_all_single(function):\n '''\n\n Function that places all individual milestone data into excel wb.\n\n project_name_list: list of project to return data for\n t_data: dictionary containing milestone data for projects.\n dictionary structure is {'project name': {'milestone name': datetime.date: 'notes'}}\n td_data: dictionary containing time_delta milestone data for projects.\n dictionary structure is {'project name': {'milestone name': 'time delta info'}}\n td_data_two: dictionary containing second time_delta data for projects.\n same structure as for td_data.\n wb: blank excel wb\n\n '''\n\n '''get all milestone data'''\n p_current_milestones = function(list_of_masters_all[0].projects, list_of_masters_all[0])\n p_last_milestones = function(list_of_masters_all[1].projects, list_of_masters_all[1])\n\n '''calculate time current and last quarter'''\n first_diff_data = project_time_difference(p_current_milestones, p_last_milestones)\n\n wb = Workbook()\n\n for x, project_name in enumerate(list_of_masters_all[0].projects):\n '''worksheet is created for each project'''\n ws = wb.create_sheet(project_name[:29], x) # creating worksheets. name restricted to 30 characters\n ws.title = project_name[:29] # title of worksheet.\n\n row_num = 2\n for i, milestone in enumerate(first_diff_data[project_name].keys()):\n ws.cell(row=row_num + i, column=1).value = project_name\n ws.cell(row=row_num + i, column=2).value = milestone\n try:\n milestone_date = tuple(p_current_milestones[project_name][milestone])[0]\n ws.cell(row=row_num + i, column=3).value = milestone_date\n ws.cell(row=row_num + i, column=3).number_format = 'dd/mm/yy'\n except KeyError:\n ws.cell(row=row_num + i, column=3).value = 0\n\n try:\n value = first_diff_data[project_name][milestone]\n try:\n if int(value) > 0:\n ws.cell(row=row_num + i, column=4).value = '+' + str(value) + ' (days)'\n elif int(value) < 0:\n ws.cell(row=row_num + i, column=4).value = str(value) + ' (days)'\n elif int(value) == 0:\n ws.cell(row=row_num + i, column=4).value = value\n except ValueError:\n ws.cell(row=row_num + i, column=4).value = value\n except KeyError:\n ws.cell(row=row_num + i, column=4).value = 0\n\n p_oldest_milestones = function([project_name], list_of_masters_all[bc_index[project_name][2]])\n second_diff_data = project_time_difference(p_current_milestones, p_oldest_milestones)\n\n try:\n value = second_diff_data[project_name][milestone]\n try:\n if int(value) > 0:\n ws.cell(row=row_num + i, column=5).value = '+' + str(value) + ' (days)'\n elif int(value) < 0:\n ws.cell(row=row_num + i, column=5).value = str(value) + ' (days)'\n elif int(value) == 0:\n ws.cell(row=row_num + i, column=5).value = value\n except ValueError:\n ws.cell(row=row_num + i, column=5).value = value\n except KeyError:\n ws.cell(row=row_num + i, column=5).value = 0\n\n try:\n milestone_date = tuple(p_current_milestones[project_name][milestone])[0]\n ws.cell(row=row_num + i, column=6).value = p_current_milestones[project_name][milestone][milestone_date] # provided notes\n except IndexError:\n ws.cell(row=row_num + i, column=6).value = 0\n\n ws.cell(row=1, column=1).value = 'Project'\n ws.cell(row=1, column=2).value = 'Milestone'\n ws.cell(row=1, column=3).value = 'Date'\n ws.cell(row=1, column=4).value = '3/m change (days)'\n ws.cell(row=1, column=5).value = 'baseline change (days)'\n ws.cell(row=1, column=6).value = 'Notes'\n\n ws.cell(row=1, column=8).value = 'data baseline quarter'\n ws.cell(row=2, column=8).value = baseline_bc_stamp[project_name][0][1]\n\n return wb\n\n\n''' RUNNING THE PROGRAMME'''\n\n'''\nOnly one part of programme is to be amended each quarter. place which ever quarter information being produced at \nend of output file name e.g. q4_1920. Note make sure file ends with .xlsx format\n\n'''\n\noutput = put_into_wb_all_single(all_milestones_dict)\noutput.save(root_path/'output/ind_project_milestones_q4_1920_2.xlsx')", "sub_path": "milestone_analysis/milestone_comparison_3_qrts_proj.py", "file_name": "milestone_comparison_3_qrts_proj.py", "file_ext": "py", "file_size_in_byte": 5254, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "analysis.data.list_of_masters_all", "line_number": 39, "usage_type": "name"}, {"api_name": "analysis.data.list_of_masters_all", "line_number": 40, "usage_type": "name"}, {"api_name": "analysis.engine_functions.project_time_difference", "line_number": 43, "usage_type": "call"}, {"api_name": "openpyxl.Workbook", "line_number": 45, "usage_type": "call"}, {"api_name": "analysis.data.list_of_masters_all", "line_number": 47, "usage_type": "name"}, {"api_name": "analysis.data.list_of_masters_all", "line_number": 77, "usage_type": "name"}, {"api_name": "analysis.data.bc_index", "line_number": 77, "usage_type": "name"}, {"api_name": "analysis.engine_functions.project_time_difference", "line_number": 78, "usage_type": "call"}, {"api_name": "analysis.data.baseline_bc_stamp", "line_number": 108, "usage_type": "name"}, {"api_name": "analysis.engine_functions.all_milestones_dict", "line_number": 121, "usage_type": "argument"}, {"api_name": "analysis.data.root_path", "line_number": 122, "usage_type": "name"}]}
+{"seq_id": "137191587", "text": "import logging\n\nclass TGLogger(object):\n @staticmethod\n def set_logger(name, log_dir='/tmp/'):\n logger = logging.getLogger(name)\n hdlr = logging.FileHandler(\"/tmp/%s.log\" % name)\n formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')\n hdlr.setFormatter(formatter)\n logger.addHandler(hdlr)\n logger.setLevel(logging.INFO)\n return(logger)\n", "sub_path": "tactilegraphics/logger.py", "file_name": "logger.py", "file_ext": "py", "file_size_in_byte": 378, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 6, "usage_type": "call"}, {"api_name": "logging.FileHandler", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 11, "usage_type": "attribute"}]}
+{"seq_id": "161157466", "text": "import onnx\nimport torch\n\nfrom onnx_pytorch.op_code_generators import OpCodeGenerator\n\n\nclass IdentityOpCodeGenerator(OpCodeGenerator):\n\n def __init__(self,\n onnx_ver=onnx.defs.onnx_opset_version(),\n torch_ver=torch.__version__):\n super(IdentityOpCodeGenerator, self).__init__(onnx_ver, torch_ver)\n\n def gen(self, node, value_infos, initializers):\n inputs_str, outputs_str = self.gen_input_output_string(\n node, initializers, self.rename_helper, self.tensor_inplace)\n init_str, forward_str = [], []\n nn_name = self.onnx_op\n node_name = self.rename_helper.get_node_name(node.name, node.op_type)\n init_str.append(f\"self.{node_name} = nn.{nn_name}()\")\n forward_str.append(f\"{outputs_str[0]} = self.{node_name}({inputs_str[0]})\")\n return {\"init\": init_str, \"forward\": forward_str}\n", "sub_path": "onnx_pytorch/op_code_generators/Identity.py", "file_name": "Identity.py", "file_ext": "py", "file_size_in_byte": 838, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "onnx_pytorch.op_code_generators.OpCodeGenerator", "line_number": 7, "usage_type": "name"}, {"api_name": "onnx.defs.onnx_opset_version", "line_number": 10, "usage_type": "call"}, {"api_name": "onnx.defs", "line_number": 10, "usage_type": "attribute"}, {"api_name": "torch.__version__", "line_number": 11, "usage_type": "attribute"}]}
+{"seq_id": "554151876", "text": "from flask import Blueprint, render_template\nfrom flask_login import login_required, current_user\n\nuser_profile = Blueprint('user_profile', __name__)\n\n@user_profile.route('/')\ndef index():\n return render_template('index.html')\n\n@user_profile.route('/profile')\n@login_required\ndef profile():\n firstname = current_user.firstname\n lastname = current_user.lastname\n credits = current_user.credits\n return render_template('login/profile.html', firstname=firstname, lastname=lastname, credits=credits)", "sub_path": "eCommerce/login/profile.py", "file_name": "profile.py", "file_ext": "py", "file_size_in_byte": 510, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Blueprint", "line_number": 4, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 8, "usage_type": "call"}, {"api_name": "flask_login.current_user.firstname", "line_number": 13, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 13, "usage_type": "name"}, {"api_name": "flask_login.current_user.lastname", "line_number": 14, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 14, "usage_type": "name"}, {"api_name": "flask_login.current_user.credits", "line_number": 15, "usage_type": "attribute"}, {"api_name": "flask_login.current_user", "line_number": 15, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 16, "usage_type": "call"}, {"api_name": "flask_login.login_required", "line_number": 11, "usage_type": "name"}]}
+{"seq_id": "21332452", "text": "'''\nCreated on Apr 11, 2016\n\n@author: Brandon\n'''\n\nimport pygame\nimport random\n\n\nclass TestCell:\n def __init__(self, dna = \"000\", brain = \"000\", pos = (0,0), color = (0,0,255)):\n self.dna = dna\n self.brain = brain\n \n self.pos_x = pos[0]\n self.pos_y = pos[1]\n self.color = color\n self.radius = 5\n \n def update(self, list):\n rand_x = random.randint(-9,9)\n rand_y = random.randint(-9,9)\n self.pos_x = self.pos_x + rand_x\n self.pos_y = self.pos_y + rand_y\n \n def paint(self, screen):\n pygame.draw.circle(screen, self.color, (self.pos_x, self.pos_y), self.radius)", "sub_path": "TestCell.py", "file_name": "TestCell.py", "file_ext": "py", "file_size_in_byte": 657, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "random.randint", "line_number": 22, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.draw.circle", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 28, "usage_type": "attribute"}]}
+{"seq_id": "407298852", "text": "##\n## Programación en Python\n## ===========================================================================\n##\n## Para el archivo `data.csv`, imprima el valor maximo y minimo de la columna\n## 2 por cada letra de la columa 1.\n##\n## Rta/\n## A,9,1\n## B,9,1\n## C,9,0\n## D,7,1\n## E,9,1\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nimport itertools\nfrom operator import itemgetter\ndatos = open('data.csv','r').readlines()\ndatos = [d.split('\\t') for d in datos]\nl1 = [[key,max([int(d[1]) for d in list(group)])] for key,group in itertools.groupby(sorted(datos),key=itemgetter(0))]\nl2 = [[key,min([int(d[1]) for d in list(group)])] for key,group in itertools.groupby(sorted(datos),key=itemgetter(0))]\nfor l in l1:\n for L in l2:\n if l[0] == L[0]:\n print(l[0],l[1],L[1],sep=',')\n#[print(l[0],l[1],L[1],sep=',') for l in l1 for L in l2 if l[0] == L[0]]\n", "sub_path": "03-python=1/q05=1/question.py", "file_name": "question.py", "file_ext": "py", "file_size_in_byte": 888, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "itertools.groupby", "line_number": 21, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 21, "usage_type": "call"}, {"api_name": "itertools.groupby", "line_number": 22, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 22, "usage_type": "call"}]}
+{"seq_id": "223412381", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport random\nimport json\nimport fcntl\nimport errno\nimport time\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import backend as K\n\nclass ResultsCollector(tf.keras.callbacks.Callback):\n\n def __init__(self, results_dir, sess_name, data_type, model_id, params):\n super(ResultsCollector, self).__init__()\n\n assert( os.path.exists(results_dir) )\n results_dir = os.path.abspath(results_dir)\n\n self.results_dir = results_dir\n self.results_file = os.path.join(results_dir, \"results.json\")\n self.dtype_id = data_type\n self.model_id = model_id\n self.params_id = params\n self.sess_name = sess_name\n\n try:\n lock_fd = self.__get_lock()\n\n results = None\n curr_res_set = None\n\n if not os.path.exists(self.results_file):\n print(\"Creating results file at \" + self.results_file)\n\n # Results are organized as follows\n # SESS_NAME\n # '\n # '--> MODEL_ID\n # '\n # '--> PARAMS_SET\n # '\n # '--> DATA_TYPE\n\n results = {}\n results[self.sess_name] = {}\n\n curr_sess_set = results[self.sess_name]\n curr_sess_set[self.model_id] = {}\n curr_sess_set[self.model_id][self.params_id] = {}\n curr_sess_set[self.model_id][self.params_id][self.dtype_id] = {}\n\n curr_res_set = curr_sess_set[self.model_id] \\\n [self.params_id] \\\n [self.dtype_id]\n\n else:\n print(\"Making sure results file contains an entry for \"\n + \"[\" + self.sess_name + \"]\"\n + \"[\" + self.model_id + \"]\"\n + \"[\" + self.params_id + \"]\"\n + \"[\" + self.dtype_id + \"]\")\n\n with open(self.results_file, \"r\") as results_FD:\n results = json.load(results_FD)\n\n assert( results is not None )\n\n sess_set = results.get(self.sess_name, {})\n model_id_set = sess_set.get(self.model_id, {})\n params_set = model_id_set.get(self.params_id, {})\n data_type_set = params_set.get(self.dtype_id, {})\n\n params_set[self.dtype_id] = data_type_set\n model_id_set[self.params_id] = params_set\n sess_set[self.model_id] = model_id_set\n results[self.sess_name] = sess_set\n\n curr_res_set = data_type_set\n\n assert( results is not None )\n assert( curr_res_set is not None )\n curr_res_set['epoch'] = -1\n\n # print(json.dumps(results, indent=2), \"\\n\")\n\n # Now, write back the updated results\n with open(self.results_file, \"w\") as results_FD:\n json.dump(results, results_FD, indent=2)\n\n finally:\n self.__rel_lock(lock_fd)\n \n\n\n def __get_lock(self):\n lock_file = os.path.join(self.results_dir, \"results.lock\")\n lock_fd = open(lock_file, \"w\")\n\n count = 0\n\n while True:\n try:\n fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n break\n except IOError as e:\n # raise on unrelated IOErrors\n if e.errno != errno.EAGAIN:\n raise\n else:\n # Raise an exception if waiting for > 30sec\n if count > 300:\n raise Exception(\"File not accessible for 30secs\")\n else:\n time.sleep(0.1)\n\n return lock_fd\n\n def __rel_lock(self, lock_fd):\n fcntl.flock(lock_fd, fcntl.LOCK_UN)\n lock_fd.close()\n\n\n def on_epoch_end(self, epoch, logs=None):\n try:\n lock_fd = self.__get_lock()\n \n results = None\n \n with open(self.results_file, \"r\") as results_FD:\n results = json.load(results_FD)\n \n assert( results is not None)\n \n sess_set = results[self.sess_name]\n curr_res_set = sess_set[self.model_id][self.params_id][self.dtype_id]\n\n new_val_loss = float(\"{:.5f}\".format(logs['val_loss']))\n\n # Update the model's attributes if we have a better val_loss\n if ( ('val_loss' not in curr_res_set.keys())\n or (new_val_loss <= curr_res_set['val_loss'])\n ):\n print(\"Updating results.\")\n for key in logs.keys():\n curr_res_set[key] = float(\"{:.5f}\".format(logs[key]))\n \n curr_res_set['epoch'] = epoch\n with open(self.results_file, \"w\") as results_FD:\n json.dump(results, results_FD, indent=2)\n \n finally:\n self.__rel_lock(lock_fd)\n\n#\n# Prior to tensorflow 1.14 there is discrepency between the\n# naming convention for learning rate in tensorflow and keras\n#\n# Because of this, LearningRateScheduler cannot be used with\n# tf.train.optimizers\n#\n# The following class is a workaround suggested on the Keras github\n#\n# https://github.com/tensorflow/tensorflow/issues/20999\n#\nclass MyLearningRateScheduler(tf.keras.callbacks.Callback):\n \"\"\"Learning rate scheduler.\n\n Arguments:\n schedule: a function that takes an epoch index as input\n (integer, indexed from 0) and current learning rate\n and returns a new learning rate as output (float).\n verbose: int. 0: quiet, 1: update messages.\n \"\"\"\n\n def __init__(self, schedule, verbose=0):\n super(MyLearningRateScheduler, self).__init__()\n self.schedule = schedule\n self.verbose = verbose\n\n def on_epoch_begin(self, epoch, logs=None):\n optimizer = self.model.optimizer\n\n if hasattr(optimizer, 'optimizer'):\n optimizer = optimizer.optimizer\n\n\n if not hasattr(optimizer, '_lr'):\n raise ValueError('Optimizer must have a \"_lr\" attribute.')\n\n # if not hasattr(optimizer, '_lr_t'):\n # raise ValueError('Optimizer must have a \"_lr_t\" attribute.')\n\n lr = float(K.get_value(optimizer._lr))\n print(\"Curr_lr = \", lr)\n\n try: # new API\n lr = self.schedule(epoch, lr)\n except TypeError: # old API for backward compatibility\n lr = self.schedule(epoch)\n\n if not isinstance(lr, (float, np.float32, np.float64)):\n raise ValueError('The output of the \"schedule\" function '\n 'should be float.')\n\n K.set_value(optimizer._lr, lr)\n # K.set_value(optimizer._lr_t, lr)\n # tf.assign(optimizer._lr_t, lr)\n\n if self.verbose > 0:\n print('\\nEpoch %05d: LearningRateScheduler setting learning '\n 'rate to %s.' % (epoch + 1, lr))\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n\n optimizer = self.model.optimizer\n if hasattr(optimizer, 'optimizer'):\n optimizer = optimizer.optimizer\n\n logs['lr'] = K.get_value(optimizer._lr)\n\n\nif __name__ == \"__main__\":\n res_dir = os.path.abspath(\"./results\")\n if not os.path.exists(res_dir):\n os.makedirs(res_dir)\n\n data_types = [\"3D_DATA\", \"3D_DATA_low_q\", \"3D_DATA_mixed\"]\n model_ids = [\"unet3D_dice\", \"unet3D_ce\"]\n param_sets = [\"params_1e-5_2L\", \"params_1e-3_3L_L2\", \"params_9e-4_3L_L2\"]\n\n sess_names = [\"OOP\", \"regulaize\", \"dropout\"]\n \n for model_id in model_ids:\n sess_name = sess_names[random.randint(0,2)]\n\n for params in param_sets:\n for data_type in data_types:\n # print(model_id, params, data_type)\n results = ResultsCollector(res_dir, sess_name, data_type, model_id, params)\n \n logs = {}\n logs['loss'] = random.random()\n logs['dice_coef'] = random.random()\n logs['val_loss'] = random.random()\n logs['val_dice_coef'] = random.random()\n \n results.on_epoch_end(random.randint(0, 10), logs)\n", "sub_path": "callbacks.py", "file_name": "callbacks.py", "file_ext": "py", "file_size_in_byte": 7543, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "tensorflow.keras", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 22, "usage_type": "call"}, {"api_name": "os.path", "line_number": 22, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path", "line_number": 37, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 69, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "attribute"}, {"api_name": "fcntl.flock", "line_number": 108, "usage_type": "call"}, {"api_name": "fcntl.LOCK_EX", "line_number": 108, "usage_type": "attribute"}, {"api_name": "fcntl.LOCK_NB", "line_number": 108, "usage_type": "attribute"}, {"api_name": "errno.EAGAIN", "line_number": 112, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 119, "usage_type": "call"}, {"api_name": "fcntl.flock", "line_number": 124, "usage_type": "call"}, {"api_name": "fcntl.LOCK_UN", "line_number": 124, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 135, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 154, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 170, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.backend.get_value", "line_number": 198, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 198, "usage_type": "name"}, {"api_name": "numpy.float32", "line_number": 206, "usage_type": "attribute"}, {"api_name": "numpy.float64", "line_number": 206, "usage_type": "attribute"}, {"api_name": "tensorflow.keras.backend.set_value", "line_number": 210, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 210, "usage_type": "name"}, {"api_name": "tensorflow.keras.backend.get_value", "line_number": 225, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend", "line_number": 225, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 229, "usage_type": "call"}, {"api_name": "os.path", "line_number": 229, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 230, "usage_type": "call"}, {"api_name": "os.path", "line_number": 230, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 231, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 240, "usage_type": "call"}, {"api_name": "random.random", "line_number": 248, "usage_type": "call"}, {"api_name": "random.random", "line_number": 249, "usage_type": "call"}, {"api_name": "random.random", "line_number": 250, "usage_type": "call"}, {"api_name": "random.random", "line_number": 251, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 253, "usage_type": "call"}]}
+{"seq_id": "54128277", "text": "import time\nimport random\n\nfrom nose.plugins.attrib import attr\n\nfrom emmaa.db import Query, Result, EmmaaDatabaseManager\nfrom emmaa.queries import Query as QueryObject, PathProperty\n\n\ntest_query_jsons = [{'type': 'path_property', 'path': {'type': 'Activation',\n 'subj': {'type': 'Agent', 'name': 'BRAF'},\n 'obj': {'type': 'Agent', 'name': 'ERK'}}},\n {'type': 'path_property', 'path':\n {'type': 'Phosphorylation',\n 'enz': {'type': 'Agent', 'name': 'ERK'},\n 'sub': {'type': 'Agent', 'name': 'MEK'}}}]\n\ntest_queries = [QueryObject._from_json(qj) for qj in test_query_jsons]\n\n\ndef _get_test_db():\n db = EmmaaDatabaseManager('postgresql://postgres:@localhost/emmaadb_test')\n db.drop_tables(force=True)\n db.create_tables()\n return db\n\n\n@attr('nonpublic')\ndef test_instantiation():\n db = _get_test_db()\n assert db\n return\n\n\n@attr('nonpublic')\ndef test_put_queries():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n with db.get_session() as sess:\n queries = sess.query(Query).all()\n assert len(queries) == 2, len(queries)\n\n\n@attr('nonpublic')\ndef test_get_queries():\n db = _get_test_db()\n for query in test_queries:\n db.put_queries('joshua', 1, query, ['aml', 'luad'])\n db.put_queries('test_user', 2, query, ['aml'])\n # We should only get distinct queries, independent of number of users\n queries = db.get_queries('aml')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n queries = db.get_queries('luad')\n assert len(queries) == 2, len(queries)\n assert all(isinstance(query, PathProperty) for query in queries)\n\n\ndef _get_random_result():\n return random.choice(\n [{'12': [['This is fine.', '']]}, {'34': [['This is not ok.', '']]}])\n\n\n@attr('nonpublic')\ndef test_put_results():\n db = _get_test_db()\n db.put_queries('joshua', 1, test_queries[0], ['aml', 'luad'])\n queries = db.get_queries('aml')\n results = [(query, '', _get_random_result())\n for query in queries]\n db.put_results('aml', results)\n with db.get_session() as sess:\n db_results = sess.query(Result).all()\n assert len(db_results) == len(results)\n\n\n@attr('nonpublic')\ndef test_get_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models), len(results)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n\n\n@attr('nonpublic')\ndef test_get_latest_results():\n db = _get_test_db()\n models = ['aml', 'luad']\n\n # Fill up the database.\n for query in test_queries:\n db.put_queries('joshua', 1, query, models)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Add the same statements over again\n time.sleep(10)\n for model in models:\n db.put_results(model, [(query, 'pysb', _get_random_result())\n for query in test_queries])\n\n # Try to get the results. Make sure we only get the one set.\n results = db.get_results('joshua')\n assert len(results) == len(test_queries)*len(models), len(results)\n assert all(isinstance(result, tuple) for result in results)\n assert all(result[0] in models for result in results)\n assert any(results[0][1].matches(q) for q in test_queries)\n assert all(isinstance(result[2], str) for result in results)\n assert all(isinstance(result[3], dict) for result in results)\n", "sub_path": "emmaa/tests/test_db.py", "file_name": "test_db.py", "file_ext": "py", "file_size_in_byte": 4238, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "emmaa.queries.Query._from_json", "line_number": 18, "usage_type": "call"}, {"api_name": "emmaa.queries.Query", "line_number": 18, "usage_type": "name"}, {"api_name": "emmaa.db.EmmaaDatabaseManager", "line_number": 22, "usage_type": "call"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 28, "usage_type": "call"}, {"api_name": "emmaa.db.Query", "line_number": 40, "usage_type": "argument"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 35, "usage_type": "call"}, {"api_name": "emmaa.queries.PathProperty", "line_number": 53, "usage_type": "argument"}, {"api_name": "emmaa.queries.PathProperty", "line_number": 56, "usage_type": "argument"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 44, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 60, "usage_type": "call"}, {"api_name": "emmaa.db.Result", "line_number": 73, "usage_type": "argument"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 64, "usage_type": "call"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 77, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 112, "usage_type": "call"}, {"api_name": "nose.plugins.attrib.attr", "line_number": 99, "usage_type": "call"}]}
+{"seq_id": "493499805", "text": "from flask import Flask, render_template, request, flash, url_for, redirect, make_response, session, jsonify\nimport json\nimport os\nfrom flask import request\n\nfrom webapp.utils import Levenshtein_distance\nfrom recognition.recognition import *\n\napp = Flask(__name__)\n\nwith open(os.path.join(\"static\", \"word_rus.txt\")) as fp:\n WORDS_RUS = [w.strip() for w in fp]\n\nclass Image:\n def __init__(self, img_name, img, found_img_name, found_img):\n self.img_name = img_name\n self.img = img\n self.found_img = found_img\n self.found_img_name = found_img_name\n\ndef find_nearest_word(word, words):\n if word in words:\n return word\n else:\n return min((Levenshtein_distance(w, word), w) for w in words)[1]\n\n\ndef create_response(text):\n resp = make_response(redirect(url_for(\"form\")))\n resp.set_cookie(\"value\", text)\n return resp\n\n\ndef get_words():\n return WORDS_RUS\n\n\ndef json_words():\n words = {\"words\": get_words()}\n return json.dumps(words, ensure_ascii=False)\n\n\ndef executor(*data):\n def wrapper(*functions):\n for func in functions:\n yield func(*data)\n\n return wrapper\n\n\ndef admin_only(func):\n def wrapper(*args, **kwargs):\n current_session = session.get(\"user\", 0)\n if current_session == 0:\n return func(*args, **kwargs)\n else:\n return func(*args, **kwargs)\n\n return wrapper\n\ndef search_core_image(word):\n available_words = [('рокета', 'rocket.jpg'),\n ('корабль', 'ship.png'),\n ('акула', 'shark.jpg'),\n ('кот', 'cat.jpg'),\n ('самолет', 'plane.jpg')]\n\n for k, v in available_words:\n if k == word:\n return v\n\n\ndef search_image(word):\n img_path = search_core_image(word)\n result = get_recognized_images(img_path)\n\n\n@app.route(\"/\")\ndef search_index():\n words = \", \".join(\"'%s'\" % w for w in get_words())\n return render_template(\"search/index.html\", openvariable=\"{{\", closevariable=\"}}\", words=words)\n\n\n@app.route(\"/search\")\ndef search_result():\n if request.method == 'GET':\n print(request)\n word = request.args.get('word')\n\n words = get_words()\n word = find_nearest_word(word, words)\n print(word)\n result_list = []\n result_list.append(Image('Horsehead Colombari', '/home/joby/Repo/nasa-default/recognition/img_test/space/space1.jpg',\n 'spit', '/home/joby/Repo/nasa-default/recognition/img_test/contours/contour_ship.png'))\n return render_template(\"search/result.html\", openvariable=\"{{\", closevariable=\"}}\", result_list=result_list)\n\n\n@app.route(\"/json/words\")\ndef words_autocomplete():\n return json_words()\n\n\nif __name__ == '__main__':\n app.config.from_pyfile(\"config.py\")\n app.run()", "sub_path": "webapp/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2858, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Flask", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "webapp.utils.Levenshtein_distance", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.make_response", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 29, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 29, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 40, "usage_type": "call"}, {"api_name": "flask.session.get", "line_number": 53, "usage_type": "call"}, {"api_name": "flask.session", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 81, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 86, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 86, "usage_type": "name"}, {"api_name": "flask.request", "line_number": 87, "usage_type": "argument"}, {"api_name": "flask.request.args.get", "line_number": 88, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 88, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 88, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 96, "usage_type": "call"}]}
+{"seq_id": "38948998", "text": "import asyncio\nfrom ep_sock import payload\n\n\nasync def handler(_, writer: asyncio.StreamWriter):\n send_payload: payload.Payload = payload.Payload()\n print('[S] Request Handler function does not exist')\n await send_payload.err_write(writer)\n\n\nasync def run_server(host, port, handler_func=handler, debug=False):\n print('[S] RUN_SERVER') if debug else None\n server = await asyncio.start_server(handler_func, host=host, port=port)\n async with server:\n await server.serve_forever()\n\n\nclass Server:\n def __init__(self, host, port, handler_func=handler, debug=False):\n self.host = host\n self.port = port\n self.handler_func = handler_func\n self.debug = debug\n\n async def _run(self):\n await asyncio.wait([run_server(self.host, self.port, handler_func=self.handler_func, debug=self.debug)])\n\n def run(self):\n asyncio.run(self._run())\n", "sub_path": "application/api/ep_sock/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 901, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "asyncio.StreamWriter", "line_number": 5, "usage_type": "attribute"}, {"api_name": "ep_sock.payload.Payload", "line_number": 6, "usage_type": "attribute"}, {"api_name": "ep_sock.payload", "line_number": 6, "usage_type": "name"}, {"api_name": "asyncio.start_server", "line_number": 13, "usage_type": "call"}, {"api_name": "asyncio.wait", "line_number": 26, "usage_type": "call"}, {"api_name": "asyncio.run", "line_number": 29, "usage_type": "call"}]}
+{"seq_id": "429714368", "text": "\"\"\"\n#Lesson##\n#XXXXX Exercise ##\n\"\"\"\n\n#!/usr/bin/env python3\n#import stuff here\nfrom pymongo import MongoClient\nimport logging\nimport csv\n\n\n#global variables here\nlogging.basicConfig(level=logging.DEBUG)\n#define function and classes\n\nclass MongoDBConnection():\n \"\"\"MongoDB Connection\"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n \"\"\" be sure to use the ip address not name for local windows\"\"\"\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n print(f\"Establishing a connection to {self.host} on port {self.port}\")\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n print(f\"Closing the connection to {self.host} - Have a nice day!\")\n self.connection.close()\n\n\n\ndef import_data(products_file, customers_file, rentals_file):\n# def import_data(directory_name, products_file, customers_file, rentals_file):\n \"\"\"\n This function takes a directory name three csv files as input, one with\n product data, one with customer data and the third one with rentals data and\n creates and populates a new MongoDB database with the these data.\n It returns 2 tuples: the first with a record count of the number of\n products, customers and rentals added (in that order), the second with a\n count of any errors that occurred, in the same order.\n\n Imports CSV data into a MongoDB.\n\n :param arg1: the name of the products csv file\n :param arg2: the name of the customers csv file\n :param arg3: the name of the rentals csv file\n \"\"\"\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #name the first collection we will work on\n products = db[\"products\"]\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n\n error_count = 0\n record_count = 0\n #open the first csv to import into the db\n #could this be made its own function?? probably!\n try:\n with open(products_file) as products_csv, \\\n open(customers_file) as customers_csv, \\\n open(rentals_file) as rentals_csv:\n products_contents = csv.reader(products_csv, delimiter=',', quotechar='\"')\n customers_contents = csv.reader(customers_csv, delimiter=',', quotechar='\"')\n rentals_contents = csv.reader(rentals_csv, delimiter=',', quotechar='\"')\n\n #this probably won't work, we need to change the data to a dict\n # yup! you were right!\n # CONVERT ROW DATA TO DICT\n\n for row in products_contents:\n # this could be made into a func couldn't it?\n logging.info(f'IMPORTING PRODUCTS DATA')\n convert_to_dict = {'product_id': row[0],\n 'description': row[1],\n 'product_type': row[2],\n 'quantity_available': row[3]}\n try:\n result = products.insert_one(convert_to_dict)\n # who needs comments when your logging explains it all LOL\n logging.info(f'Adding {convert_to_dict} to the products collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the products collection!')\n error_count += 1\n for row in customers_contents:\n logging.info(f'IMPORTING CUSTOMERS DATA')\n convert_to_dict = {'user_id': row[0],\n 'name': row[1],\n 'address': row[2],\n 'zip_code': row[3],\n 'phone_number': row[4],\n 'email': row[5]}\n try:\n result = customers.insert_one(convert_to_dict)\n logging.info(f'Adding {convert_to_dict} to the customers collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the customers collection!')\n error_count += 1\n for row in rentals_contents:\n logging.info(f'IMPORTING RENTALS DATA')\n convert_to_dict = {'product_id': row[0],\n 'user_id': row[1]}\n try:\n result = rentals.insert_one(convert_to_dict)\n logging.info(f'Adding {convert_to_dict} to the rentals collection')\n record_count += 1\n except Exception as e:\n logging.error(f'Error adding {convert_to_dict} to the rentals collection!')\n error_count += 1\n except Exception as e:\n logging.error(f'Hm, we had an error here?')\n logging.error(e)\n\n print(f' the number of records in the products collection is: {db.products.count()}')\n print(f' the number of records in the customers collection is: {db.customers.count()}')\n print(f' the number of records in the rentals collection is: {db.rentals.count()}')\n return (record_count, error_count)\n\ndef show_available_products():\n \"\"\"\n Returns a Python dictionary of products listed as available with\n the following fields:\n\n product_id.\n description.\n product_type.\n quantity_available.\n \"\"\"\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #name the first collection we will work on\n products = db[\"products\"]\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n\n for name in products.find():\n logging.debug(f\"{name.get('product_id')} : {name.get('quantity_available')}\")\n try:\n if int(name.get('quantity_available')) > 0:\n print(f\"{name.get('product_id')}: {name.get('description')} is available!\")\n except ValueError as e:\n logging.debug(f\"skipping {name.get('product_id')} due to error\")\n logging.error(e)\n\n\ndef show_rentals(product_id):\n \"\"\"\n Returns a Python dictionary with the following user information from\n users that have rented products matching product_id:\n\n user_id.\n name.\n address.\n phone_number.\n email.\n\n :param arg1: The product_id to search for\n \"\"\"\n # gosh, I'm repeating myself a lot here with these Mongo commands. could\n # be simplified into its own function, yes??\n mongo = MongoDBConnection()\n\n with mongo:\n #connect to Mongo\n db = mongo.connection.hp_norton\n\n #the collections we will be using\n customers = db[\"customers\"]\n rentals = db[\"rentals\"]\n customer_list = []\n customer_dict ={}\n for rented_item in rentals.find():\n logging.debug(f\"Does {product_id} match {rented_item.get('product_id')}?\")\n try:\n if rented_item.get('product_id') == product_id:\n logging.debug(f'found a match!')\n customer_list.append(rented_item.get('user_id'))\n logging.debug(f\"Adding {rented_item.get('user_id')} to list\")\n except ValueError as e:\n logging.debug(f\"skipping {rented_item.get('product_id')} due to error\")\n logging.error(e)\n\n for name in customers.find():\n logging.debug(f\"comparing found user id to the customer list\")\n logging.debug(f\"looking for {name.get('user_id')} in {customer_list}\")\n try:\n if name.get('user_id') in customer_list:\n logging.debug(f\"found {name.get('name')} in the list!\")\n customer_dict[name.get('user_id')] = [name.get('user_id'),\n name.get('name'),\n name.get('address'),\n name.get('phone_number'),\n name.get('email')]\n except ValueError as e:\n logging.debug(f\"skipping {name.get('name')} due to error\")\n logging.error(e)\n return customer_dict\n\n\n#for testing\nif __name__==\"__main__\":\n import_data('products.csv', 'customers.csv', 'rentals.csv')\n", "sub_path": "students/ericstreit/lessons/lesson05/assignment/database.py", "file_name": "database.py", "file_ext": "py", "file_size_in_byte": 8757, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.basicConfig", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 14, "usage_type": "attribute"}, {"api_name": "pymongo.MongoClient", "line_number": 27, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 72, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 73, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 74, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 82, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 90, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 93, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 96, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 105, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 108, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 111, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 116, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 119, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 122, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 123, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 152, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 157, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 158, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 188, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 191, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 193, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 195, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 196, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 199, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 200, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 203, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 210, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 211, "usage_type": "call"}]}
+{"seq_id": "101015758", "text": "from datetime import datetime\r\nimport requests\r\nimport string\r\nimport urllib3\r\nimport json\r\nimport xlrd\r\nimport pandas as pd\r\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\r\n\r\nwith open('fortigateinventory.txt') as devices_file:\r\n firewalls = devices_file.readlines()\r\n\r\nwith open('api-call.txt') as api_file:\r\n apiaction = api_file.readlines()\r\n\r\ndf = pd.read_excel('addresses.xls', sheet_name='Sheet1')\r\n\r\nname = df['name'].values.tolist()\r\nstart = df['start-ip'].values.tolist()\r\nend = df['end-ip'].values.tolist()\r\n\r\ndate = datetime.now().strftime(\"%y-%m-%d-%M\")\r\ndate1 = datetime.now().strftime(\"%B %d, %Y\")\r\n\r\nfor line in firewalls:\r\n line = line.strip(\"\\n\")\r\n hostname = line.split(\",\")[0]\r\n ipaddr = line.split(\",\")[1]\r\n port = line.split(\",\")[2]\r\n token = line.split(\",\")[3]\r\n vdom = line.split(\",\")[4]\r\n\r\n for line in apiaction:\r\n line = line.strip(\"\\n\")\r\n context = line.split(\",\")[0]\r\n option = line.split(\",\")[1]\r\n i = 0\r\n for i, (a, b, c) in enumerate(zip(name, start, end)):\r\n namevar = a\r\n startvar = b\r\n endvar = c\r\n data1 = {\"name\": namevar, \"type\": \"ipmask\", \"start-ip\": startvar, \"end-ip\": endvar}\r\n i += 1\r\n api_url = r'https://'+ipaddr+':'+port+'/api/v2/cmdb/'+context+'/'+option+'/?access_token='+token\r\n print('Performing API Request to '+ hostname)\r\n r = requests.post(api_url, data=json.dumps(data1), verify=False)\r\n\r\nprint('*' * 20)\r\nprint('Job Completed!!')\r\nprint('*' * 20)", "sub_path": "FortigateAPI_Module-POST-from-EXCEL_FortiOS-6.0.py", "file_name": "FortigateAPI_Module-POST-from-EXCEL_FortiOS-6.0.py", "file_ext": "py", "file_size_in_byte": 1573, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "urllib3.disable_warnings", "line_number": 8, "usage_type": "call"}, {"api_name": "urllib3.exceptions", "line_number": 8, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 16, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 22, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 22, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 46, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 46, "usage_type": "call"}]}
+{"seq_id": "231709752", "text": "import sys\nimport traceback\nfrom contextlib import contextmanager\n\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization as crypt_serialization\nfrom cryptography.hazmat.primitives.asymmetric import rsa\n\nfrom six import reraise\n\n\ndef generate_key_pair():\n \"\"\"\n This method generates a keypair and returns it as a tuple\n of (public, private) keys.\n The public key format is OpenSSH and private key format is PEM.\n \"\"\"\n key_pair = rsa.generate_private_key(\n backend=default_backend(),\n public_exponent=65537,\n key_size=2048)\n private_key = key_pair.private_bytes(\n crypt_serialization.Encoding.PEM,\n crypt_serialization.PrivateFormat.PKCS8,\n crypt_serialization.NoEncryption()).decode('utf-8')\n public_key = key_pair.public_key().public_bytes(\n crypt_serialization.Encoding.OpenSSH,\n crypt_serialization.PublicFormat.OpenSSH).decode('utf-8')\n return public_key, private_key\n\n\ndef filter_by(prop_name, kwargs, objs):\n \"\"\"\n Utility method for filtering a list of objects by a property.\n If the given property has a non empty value in kwargs, then\n the list of objs is filtered by that value. Otherwise, the\n list of objs is returned as is.\n \"\"\"\n prop_val = kwargs.pop(prop_name, None)\n if prop_val:\n match = (o for o in objs if getattr(o, prop_name) == prop_val)\n return match\n return objs\n\n\ndef generic_find(filter_names, kwargs, objs):\n \"\"\"\n Utility method for filtering a list of objects by a list of filters.\n \"\"\"\n matches = objs\n for name in filter_names:\n matches = filter_by(name, kwargs, matches)\n\n # All kwargs should have been popped at this time.\n if len(kwargs) > 0:\n raise TypeError(\n \"Unrecognised parameters for search: %s. Supported attributes: %s\"\n % (kwargs, filter_names))\n\n return matches\n\n\n@contextmanager\ndef cleanup_action(cleanup_func):\n \"\"\"\n Context manager to carry out a given\n cleanup action after carrying out a set\n of tasks, or when an exception occurs.\n If any errors occur during the cleanup\n action, those are ignored, and the original\n traceback is preserved.\n\n :params func: This function is called if\n an exception occurs or at the end of the\n context block. If any exceptions raised\n by func are ignored.\n Usage:\n with cleanup_action(lambda e: print(\"Oops!\")):\n do_something()\n \"\"\"\n try:\n yield\n except Exception:\n ex_class, ex_val, ex_traceback = sys.exc_info()\n try:\n cleanup_func()\n except Exception as e:\n print(\"Error during exception cleanup: {0}\".format(e))\n traceback.print_exc()\n reraise(ex_class, ex_val, ex_traceback)\n try:\n cleanup_func()\n except Exception as e:\n print(\"Error during cleanup: {0}\".format(e))\n traceback.print_exc()\n", "sub_path": "cloudbridge/cloud/base/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 2983, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key", "line_number": 18, "usage_type": "call"}, {"api_name": "cryptography.hazmat.primitives.asymmetric.rsa", "line_number": 18, "usage_type": "name"}, {"api_name": "cryptography.hazmat.backends.default_backend", "line_number": 19, "usage_type": "call"}, {"api_name": "cryptography.hazmat.primitives.serialization.Encoding", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cryptography.hazmat.primitives.serialization", "line_number": 23, "usage_type": "name"}, {"api_name": "cryptography.hazmat.primitives.serialization.PrivateFormat", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cryptography.hazmat.primitives.serialization", "line_number": 24, "usage_type": "name"}, {"api_name": "cryptography.hazmat.primitives.serialization.NoEncryption", "line_number": 25, "usage_type": "call"}, {"api_name": "cryptography.hazmat.primitives.serialization", "line_number": 25, "usage_type": "name"}, {"api_name": "cryptography.hazmat.primitives.serialization.Encoding", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cryptography.hazmat.primitives.serialization", "line_number": 27, "usage_type": "name"}, {"api_name": "cryptography.hazmat.primitives.serialization.PublicFormat", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cryptography.hazmat.primitives.serialization", "line_number": 28, "usage_type": "name"}, {"api_name": "sys.exc_info", "line_number": 84, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 89, "usage_type": "call"}, {"api_name": "six.reraise", "line_number": 90, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 95, "usage_type": "call"}, {"api_name": "contextlib.contextmanager", "line_number": 63, "usage_type": "name"}]}
+{"seq_id": "292790499", "text": "\"\"\"\n博客资源\n\"\"\"\nimport re\nfrom datetime import datetime\nfrom flask import request, g\nfrom flask_restful import Resource\nfrom . import restful_api\nfrom .. import multi_auth, token_auth\nfrom app.exts import db\nfrom app.models.blog import Blog\n\n\nclass BlogResource(Resource):\n # decorators = [multi_auth.login_required]\n\n def get(self):\n blog_id = request.args.get('blog_id')\n blog = Blog.query.filter_by(id=blog_id).first()\n blog_json = {\n 'id': blog.id,\n 'title': blog.title,\n 'content': blog.content,\n 'summary': blog.summary,\n 'cover': blog.cover,\n 'reads_count': blog.reads_count,\n 'comments_count': blog.comments_count,\n 'updated': blog.updated.strftime('%Y-%m-%d %H:%M:%S')\n }\n return {\n \"blog\":blog_json\n }\n\n @token_auth.login_required\n def post(self):\n post_args = request.get_json()\n raw_content = post_args.get('content')\n\n title_index = raw_content.find('\\n')\n if title_index == -1:\n title = '无标题'\n else:\n raw_title = raw_content[:title_index]\n title = re.sub(r'\\#*', '', raw_title)\n\n cover_catch = re.findall(r'\\!\\[cover\\]\\(.*\\)', raw_content)\n if len(cover_catch) == 0:\n cover = \"\"\n else:\n cover = cover_catch[0][9:-1]\n\n new_blog = Blog(\n user_id=g.auth_user.id,\n title=title,\n content=raw_content,\n cover=cover,\n updated=datetime.utcnow()\n )\n db.session.add(new_blog)\n db.session.commit()\n\n return {\n\n }\n\n @token_auth.login_required\n def put(self):\n post_args = request.get_json()\n blog_id = post_args.get('blog_id')\n raw_content = post_args.get('content')\n\n title_index = raw_content.find('\\n')\n if title_index == -1:\n title = '无标题'\n else:\n raw_title = raw_content[:title_index]\n title = re.sub(r'\\#*', '', raw_title)\n\n cover_catch = re.findall(r'\\!\\[cover\\]\\(.*\\)', raw_content)\n if len(cover_catch) == 0:\n cover = \"\"\n else:\n cover = cover_catch[0][9:-1]\n\n update_blog = Blog.query.filter_by(id=blog_id).update(dict(\n title=title,\n content=raw_content,\n cover=cover,\n updated=datetime.utcnow()\n ))\n db.session.commit()\n\n return {\n\n }\n\n @token_auth.login_required\n def delete(self):\n blog_id = request.args.get('blog_id')\n blog = Blog.query.filter_by(id=blog_id).first()\n db.session.delete(blog)\n db.session.commit()\n return {}\n\n\nrestful_api.add_resource(BlogResource, '/blog')\n", "sub_path": "app/api/v_1_0/blog.py", "file_name": "blog.py", "file_ext": "py", "file_size_in_byte": 2939, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "flask_restful.Resource", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 18, "usage_type": "name"}, {"api_name": "app.models.blog.Blog.query.filter_by", "line_number": 19, "usage_type": "call"}, {"api_name": "app.models.blog.Blog.query", "line_number": 19, "usage_type": "attribute"}, {"api_name": "app.models.blog.Blog", "line_number": 19, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 44, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 46, "usage_type": "call"}, {"api_name": "app.models.blog.Blog", "line_number": 52, "usage_type": "call"}, {"api_name": "flask.g.auth_user", "line_number": 53, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 53, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 57, "usage_type": "name"}, {"api_name": "app.exts.db.session.add", "line_number": 59, "usage_type": "call"}, {"api_name": "app.exts.db.session", "line_number": 59, "usage_type": "attribute"}, {"api_name": "app.exts.db", "line_number": 59, "usage_type": "name"}, {"api_name": "app.exts.db.session.commit", "line_number": 60, "usage_type": "call"}, {"api_name": "app.exts.db.session", "line_number": 60, "usage_type": "attribute"}, {"api_name": "app.exts.db", "line_number": 60, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 68, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 68, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 77, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 79, "usage_type": "call"}, {"api_name": "app.models.blog.Blog.query.filter_by", "line_number": 85, "usage_type": "call"}, {"api_name": "app.models.blog.Blog.query", "line_number": 85, "usage_type": "attribute"}, {"api_name": "app.models.blog.Blog", "line_number": 85, "usage_type": "name"}, {"api_name": "datetime.datetime.utcnow", "line_number": 89, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 89, "usage_type": "name"}, {"api_name": "app.exts.db.session.commit", "line_number": 91, "usage_type": "call"}, {"api_name": "app.exts.db.session", "line_number": 91, "usage_type": "attribute"}, {"api_name": "app.exts.db", "line_number": 91, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 99, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 99, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 99, "usage_type": "name"}, {"api_name": "app.models.blog.Blog.query.filter_by", "line_number": 100, "usage_type": "call"}, {"api_name": "app.models.blog.Blog.query", "line_number": 100, "usage_type": "attribute"}, {"api_name": "app.models.blog.Blog", "line_number": 100, "usage_type": "name"}, {"api_name": "app.exts.db.session.delete", "line_number": 101, "usage_type": "call"}, {"api_name": "app.exts.db.session", "line_number": 101, "usage_type": "attribute"}, {"api_name": "app.exts.db", "line_number": 101, "usage_type": "name"}, {"api_name": "app.exts.db.session.commit", "line_number": 102, "usage_type": "call"}, {"api_name": "app.exts.db.session", "line_number": 102, "usage_type": "attribute"}, {"api_name": "app.exts.db", "line_number": 102, "usage_type": "name"}]}
+{"seq_id": "49922194", "text": "#!/usr/bin/env python3\n'''\nSeth Hinson & Patrick McCabe\nCSCI 340 Project Two, Spring 2020\nRound Robbin Simulator\n'''\nimport sys, os, random\nfrom page import *\nfrom job import *\nfrom termcolor import colored\n\ndef printParams():\n \n print(colored('Memory Size: ' + str(sys.argv[1]), 'magenta'))\n \n print(colored('Page Size: ' + str(sys.argv[2]), 'magenta'))\n \n print(colored('Random Seed: ' + str(os.environ['RANDOM_SEED']), 'magenta'))\n \n print(colored('Number of jobs: ' + str(sys.argv[3]), 'magenta'))\n \n print(colored('Runtime (min-max) timesteps: ' + str(sys.argv[4]) + '-' + str(sys.argv[5]), 'magenta'))\n \n print(colored('Memory (min-max): ' + str(sys.argv[6]) + '-' + str(sys.argv[7]), 'magenta'))\n\ndef createJobs():\n\n numberOfJobs = int(sys.argv[3])\n \n runtimeMin = int(sys.argv[4])\n \n runtimeMax = int(sys.argv[5])\n \n memoryMin = int(sys.argv[6]) // int(sys.argv[2])\n \n memoryMax = int(sys.argv[7]) // int(sys.argv[2])\n \n jobs = []\n\n for i in range(numberOfJobs):\n\n runtime = random.randint(runtimeMin, runtimeMax) \n \n memory = random.randint(memoryMin, memoryMax) * int(sys.argv[2])\n \n jobs.append( job(i + 1, runtime, memory))\n \n print(colored('\\nJob Queue:', 'blue'))\n \n print(colored('Job #\\tRuntime\\tMemory', 'blue'))\n \n for jb in jobs:\n \n print(colored(str(jb),'blue')) \n \n return jobs\n\ndef jobsAreRunning(activeJobs):\n\n for job in activeJobs:\n \n if (job.getStatus() == 'Running' or job.getStatus() == 'Starting'):\n \n return True\n \n return False\n\ndef simulator(jobs):\n\n print(colored('\\nSimulator Starting:\\n', 'green'))\n \n numSteps = 0\n\n while (jobsAreRunning(jobs)):\n \n numSteps += 1\n \n if(numSteps == 1):\n \n for i in range(len(jobs)):\n \n print('Job ' + str(i + 1) + ' Starting')\n \n print('Job 1 Running')\n \n jobs[0].setStatus('Running')\n \n jobs[0].run()\n \n else:\n \n runningJob = numSteps % (len(jobs)) \n \n if(runningJob == 0):\n \n runningJob = len(jobs)\n\n noRun = True\n \n while(noRun):\n #print('Running Job: ' + str(runningJob)) debug for running job out of bounds\n if(jobs[runningJob - 1].isComplete()):\n \n runningJob = (runningJob + 1) % len(jobs)\n \n if(runningJob == 0):\n \n runningJob = len(jobs)\n \n else:\n\n jobs[runningJob - 1].setStatus('Running')\n\n jobs[runningJob - 1].run()\n \n print('Job ' + str(runningJob) + ' Running')\n \n if(jobs[runningJob - 1].isComplete()):\n \n print('Job ' + str(runningJob) + ' Completed')\n \n noRun = False\n'''\nTo do list:\n1. Page table output\n2. Job info @ end\n3. Make pretty \n4. Document\n5. Profit\n'''\ndef main():\n \n random.seed(os.environ['RANDOM_SEED'])\n \n if len(sys.argv) != 8:\n \n print(colored('Invalid number of arguments', 'red'))\n \n print(colored('Proper usage: ./projecttwo.py ', 'red'))\n \n else:\n \n print(colored('\\nProper number of arguments passed!\\n', 'green'))\n \n #print(colored(str(sys.argv[1]), 'green')) used for debugging sys.argv input\n \n printParams()\n \n jobQ = createJobs()\n \n simulator(jobQ)\n\n\nmain()", "sub_path": "ProjectTwo/projecttwo.py", "file_name": "projecttwo.py", "file_ext": "py", "file_size_in_byte": 3937, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "termcolor.colored", "line_number": 14, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 14, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 16, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 16, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 18, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 20, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 22, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 22, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 24, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 24, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 28, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 30, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 32, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 34, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 36, "usage_type": "attribute"}, {"api_name": "random.randint", "line_number": 42, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 44, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 44, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 48, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 50, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 54, "usage_type": "call"}, {"api_name": "job.getStatus", "line_number": 62, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 70, "usage_type": "call"}, {"api_name": "random.seed", "line_number": 133, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 133, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 135, "usage_type": "attribute"}, {"api_name": "termcolor.colored", "line_number": 137, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 139, "usage_type": "call"}, {"api_name": "termcolor.colored", "line_number": 143, "usage_type": "call"}]}
+{"seq_id": "349211015", "text": "import itertools\nimport logging\n\nfrom django.db.models import Q\nfrom usaspending_api.awards.v2.filters.filter_helpers import combine_date_range_queryset, total_obligation_queryset\nfrom usaspending_api.awards.v2.filters.location_filter_geocode import geocode_filter_locations\nfrom usaspending_api.common.exceptions import InvalidParameterException\nfrom usaspending_api.references.models import PSC\nfrom usaspending_api.search.filters.postgres.psc import PSCCodes\nfrom usaspending_api.search.filters.postgres.tas import TasCodes, TreasuryAccounts\nfrom usaspending_api.search.helpers.matview_filter_helpers import build_award_ids_filter\nfrom usaspending_api.search.models import SubawardView\nfrom usaspending_api.search.v2 import elasticsearch_helper\nfrom usaspending_api.settings import API_MAX_DATE, API_MIN_DATE, API_SEARCH_MIN_DATE\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef subaward_download(filters):\n \"\"\" Used by the Custom download\"\"\"\n return subaward_filter(filters, for_downloads=True)\n\n\n# TODO: Performance when multiple false values are initially provided\ndef subaward_filter(filters, for_downloads=False):\n queryset = SubawardView.objects.all()\n\n recipient_scope_q = Q(recipient_location_country_code=\"USA\") | Q(recipient_location_country_name=\"UNITED STATES\")\n pop_scope_q = Q(pop_country_code=\"USA\") | Q(pop_country_name=\"UNITED STATES\")\n\n for key, value in filters.items():\n\n if value is None:\n raise InvalidParameterException(\"Invalid filter: \" + key + \" has null as its value.\")\n\n key_list = [\n \"keywords\",\n \"elasticsearch_keyword\",\n \"time_period\",\n \"award_type_codes\",\n \"prime_and_sub_award_types\",\n \"agencies\",\n \"legal_entities\",\n \"recipient_search_text\",\n \"recipient_scope\",\n \"recipient_locations\",\n \"recipient_type_names\",\n \"place_of_performance_scope\",\n \"place_of_performance_locations\",\n \"award_amounts\",\n \"award_ids\",\n \"program_numbers\",\n \"naics_codes\",\n PSCCodes.underscore_name,\n \"contract_pricing_type_codes\",\n \"set_aside_type_codes\",\n \"extent_competed_type_codes\",\n TasCodes.underscore_name,\n TreasuryAccounts.underscore_name,\n ]\n\n if key not in key_list:\n raise InvalidParameterException(\"Invalid filter: \" + key + \" does not exist.\")\n\n if key == \"keywords\":\n\n def keyword_parse(keyword):\n # keyword_ts_vector & award_ts_vector are Postgres TS_vectors.\n # keyword_ts_vector = recipient_name + psc_description + subaward_description\n # award_ts_vector = piid + fain + uri + subaward_number\n filter_obj = Q(keyword_ts_vector=keyword) | Q(award_ts_vector=keyword)\n # Commenting out until NAICS is associated with subawards in DAIMS 1.3.1\n # if keyword.isnumeric():\n # filter_obj |= Q(naics_code__contains=keyword)\n if len(keyword) == 4 and PSC.objects.filter(code__iexact=keyword).exists():\n filter_obj |= Q(product_or_service_code__iexact=keyword)\n\n return filter_obj\n\n filter_obj = Q()\n for keyword in value:\n filter_obj |= keyword_parse(keyword)\n potential_duns = list(filter((lambda x: len(x) > 7 and len(x) < 10), value))\n if len(potential_duns) > 0:\n filter_obj |= Q(recipient_unique_id__in=potential_duns) | Q(\n parent_recipient_unique_id__in=potential_duns\n )\n\n queryset = queryset.filter(filter_obj)\n\n elif key == \"elasticsearch_keyword\":\n keyword = value\n transaction_ids = elasticsearch_helper.get_download_ids(keyword=keyword, field=\"transaction_id\")\n # flatten IDs\n transaction_ids = list(itertools.chain.from_iterable(transaction_ids))\n logger.info(\"Found {} transactions based on keyword: {}\".format(len(transaction_ids), keyword))\n transaction_ids = [str(transaction_id) for transaction_id in transaction_ids]\n queryset = queryset.filter(latest_transaction_id__isnull=False)\n\n # Prepare a SQL snippet to include in the predicate for searching an array of transaction IDs\n sql_fragment = '\"subaward_view\".\"latest_transaction_id\" = ANY(\\'{{{}}}\\'::int[])' # int[] -> int array type\n queryset = queryset.extra(where=[sql_fragment.format(\",\".join(transaction_ids))])\n\n elif key == \"time_period\":\n min_date = API_SEARCH_MIN_DATE\n if for_downloads:\n min_date = API_MIN_DATE\n queryset &= combine_date_range_queryset(value, SubawardView, min_date, API_MAX_DATE)\n\n elif key == \"award_type_codes\":\n queryset = queryset.filter(prime_award_type__in=value)\n\n elif key == \"prime_and_sub_award_types\":\n award_types = value.get(\"sub_awards\")\n if award_types:\n queryset = queryset.filter(award_type__in=award_types)\n\n elif key == \"agencies\":\n # TODO: Make function to match agencies in award filter throwing dupe error\n funding_toptier = Q()\n funding_subtier = Q()\n awarding_toptier = Q()\n awarding_subtier = Q()\n for v in value:\n type = v[\"type\"]\n tier = v[\"tier\"]\n name = v[\"name\"]\n if type == \"funding\":\n if tier == \"toptier\":\n funding_toptier |= Q(funding_toptier_agency_name=name)\n elif tier == \"subtier\":\n if \"toptier_name\" in v:\n funding_subtier |= Q(funding_subtier_agency_name=name) & Q(\n funding_toptier_agency_name=v[\"toptier_name\"]\n )\n else:\n funding_subtier |= Q(funding_subtier_agency_name=name)\n\n elif type == \"awarding\":\n if tier == \"toptier\":\n awarding_toptier |= Q(awarding_toptier_agency_name=name)\n elif tier == \"subtier\":\n if \"toptier_name\" in v:\n awarding_subtier |= Q(awarding_subtier_agency_name=name) & Q(\n awarding_toptier_agency_name=v[\"toptier_name\"]\n )\n else:\n awarding_subtier |= Q(awarding_subtier_agency_name=name)\n\n awarding_queryfilter = Q()\n funding_queryfilter = Q()\n\n # Since these are Q filters, no DB hits for boolean checks\n if funding_toptier:\n funding_queryfilter |= funding_toptier\n if funding_subtier:\n funding_queryfilter |= funding_subtier\n if awarding_toptier:\n awarding_queryfilter |= awarding_toptier\n if awarding_subtier:\n awarding_queryfilter |= awarding_subtier\n\n queryset = queryset.filter(funding_queryfilter & awarding_queryfilter)\n\n elif key == \"legal_entities\":\n # This filter key has effectively become obsolete by recipient_search_text\n msg = 'API request included \"{}\" key. No filtering will occur with provided value \"{}\"'\n logger.info(msg.format(key, value))\n\n elif key == \"recipient_search_text\":\n\n def recip_string_parse(recipient_string):\n upper_recipient_string = recipient_string.upper()\n\n # recipient_name_ts_vector is a postgres TS_Vector\n filter_obj = Q(recipient_name_ts_vector=upper_recipient_string)\n if len(upper_recipient_string) == 9 and upper_recipient_string[:5].isnumeric():\n filter_obj |= Q(recipient_unique_id=upper_recipient_string)\n return filter_obj\n\n filter_obj = Q()\n for recipient in value:\n filter_obj |= recip_string_parse(recipient)\n queryset = queryset.filter(filter_obj)\n\n elif key == \"recipient_scope\":\n if value == \"domestic\":\n queryset = queryset.filter(recipient_scope_q)\n elif value == \"foreign\":\n queryset = queryset.exclude(recipient_scope_q)\n else:\n raise InvalidParameterException(\"Invalid filter: recipient_scope type is invalid.\")\n\n elif key == \"recipient_locations\":\n queryset = queryset.filter(geocode_filter_locations(\"recipient_location\", value))\n\n elif key == \"recipient_type_names\":\n if len(value) != 0:\n queryset = queryset.filter(business_categories__overlap=value)\n\n elif key == \"place_of_performance_scope\":\n if value == \"domestic\":\n queryset = queryset.filter(pop_scope_q)\n elif value == \"foreign\":\n queryset = queryset.exclude(pop_scope_q)\n else:\n raise InvalidParameterException(\"Invalid filter: place_of_performance_scope is invalid.\")\n\n elif key == \"place_of_performance_locations\":\n queryset = queryset.filter(geocode_filter_locations(\"pop\", value))\n\n elif key == \"award_amounts\":\n queryset &= total_obligation_queryset(value, SubawardView, filters)\n\n elif key == \"award_ids\":\n queryset = build_award_ids_filter(queryset, value, (\"piid\", \"fain\"))\n\n elif key == PSCCodes.underscore_name:\n q = PSCCodes.build_tas_codes_filter(value)\n queryset = queryset.filter(q) if q else queryset\n\n # add \"naics_codes\" (column naics) after NAICS are mapped to subawards\n elif key in (\"program_numbers\", \"contract_pricing_type_codes\"):\n filter_to_col = {\n \"program_numbers\": \"cfda_number\",\n \"contract_pricing_type_codes\": \"type_of_contract_pricing\",\n }\n in_query = [v for v in value]\n if len(in_query) != 0:\n queryset &= SubawardView.objects.filter(**{\"{}__in\".format(filter_to_col[key]): in_query})\n\n elif key in (\"set_aside_type_codes\", \"extent_competed_type_codes\"):\n or_queryset = Q()\n filter_to_col = {\"set_aside_type_codes\": \"type_set_aside\", \"extent_competed_type_codes\": \"extent_competed\"}\n in_query = [v for v in value]\n for v in value:\n or_queryset |= Q(**{\"{}__exact\".format(filter_to_col[key]): in_query})\n queryset = queryset.filter(or_queryset)\n\n # Because these two filters OR with each other, we need to know about the presense of both filters to know what to do\n # This filter was picked arbitrarily to be the one that checks for the other\n elif key == TasCodes.underscore_name:\n q = TasCodes.build_tas_codes_filter(queryset, value)\n if TreasuryAccounts.underscore_name in filters.keys():\n q |= TreasuryAccounts.build_tas_codes_filter(queryset, filters[TreasuryAccounts.underscore_name])\n queryset = queryset.filter(q)\n\n elif key == TreasuryAccounts.underscore_name and TasCodes.underscore_name not in filters.keys():\n queryset = queryset.filter(TreasuryAccounts.build_tas_codes_filter(queryset, value))\n\n return queryset\n", "sub_path": "usaspending_api/awards/v2/filters/sub_award.py", "file_name": "sub_award.py", "file_ext": "py", "file_size_in_byte": 11525, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.getLogger", "line_number": 17, "usage_type": "call"}, {"api_name": "usaspending_api.search.models.SubawardView.objects.all", "line_number": 27, "usage_type": "call"}, {"api_name": "usaspending_api.search.models.SubawardView.objects", "line_number": 27, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.models.SubawardView", "line_number": 27, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 29, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 30, "usage_type": "call"}, {"api_name": "usaspending_api.common.exceptions.InvalidParameterException", "line_number": 35, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes.underscore_name", "line_number": 55, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes", "line_number": 55, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes.underscore_name", "line_number": 59, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes", "line_number": 59, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.underscore_name", "line_number": 60, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts", "line_number": 60, "usage_type": "name"}, {"api_name": "usaspending_api.common.exceptions.InvalidParameterException", "line_number": 64, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 72, "usage_type": "call"}, {"api_name": "usaspending_api.references.models.PSC.objects.filter", "line_number": 76, "usage_type": "call"}, {"api_name": "usaspending_api.references.models.PSC.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "usaspending_api.references.models.PSC", "line_number": 76, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 77, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 81, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 86, "usage_type": "call"}, {"api_name": "usaspending_api.search.v2.elasticsearch_helper.get_download_ids", "line_number": 94, "usage_type": "call"}, {"api_name": "usaspending_api.search.v2.elasticsearch_helper", "line_number": 94, "usage_type": "name"}, {"api_name": "itertools.chain.from_iterable", "line_number": 96, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 96, "usage_type": "attribute"}, {"api_name": "usaspending_api.settings.API_SEARCH_MIN_DATE", "line_number": 106, "usage_type": "name"}, {"api_name": "usaspending_api.settings.API_MIN_DATE", "line_number": 108, "usage_type": "name"}, {"api_name": "usaspending_api.awards.v2.filters.filter_helpers.combine_date_range_queryset", "line_number": 109, "usage_type": "call"}, {"api_name": "usaspending_api.search.models.SubawardView", "line_number": 109, "usage_type": "argument"}, {"api_name": "usaspending_api.settings.API_MAX_DATE", "line_number": 109, "usage_type": "argument"}, {"api_name": "django.db.models.Q", "line_number": 121, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 122, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 123, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 124, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 131, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 134, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 138, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 142, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 145, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 149, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 151, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 152, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 177, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 179, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 182, "usage_type": "call"}, {"api_name": "usaspending_api.common.exceptions.InvalidParameterException", "line_number": 193, "usage_type": "call"}, {"api_name": "usaspending_api.awards.v2.filters.location_filter_geocode.geocode_filter_locations", "line_number": 196, "usage_type": "call"}, {"api_name": "usaspending_api.common.exceptions.InvalidParameterException", "line_number": 208, "usage_type": "call"}, {"api_name": "usaspending_api.awards.v2.filters.location_filter_geocode.geocode_filter_locations", "line_number": 211, "usage_type": "call"}, {"api_name": "usaspending_api.awards.v2.filters.filter_helpers.total_obligation_queryset", "line_number": 214, "usage_type": "call"}, {"api_name": "usaspending_api.search.models.SubawardView", "line_number": 214, "usage_type": "argument"}, {"api_name": "usaspending_api.search.helpers.matview_filter_helpers.build_award_ids_filter", "line_number": 217, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes.underscore_name", "line_number": 219, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes", "line_number": 219, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes.build_tas_codes_filter", "line_number": 220, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.psc.PSCCodes", "line_number": 220, "usage_type": "name"}, {"api_name": "usaspending_api.search.models.SubawardView.objects.filter", "line_number": 231, "usage_type": "call"}, {"api_name": "usaspending_api.search.models.SubawardView.objects", "line_number": 231, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.models.SubawardView", "line_number": 231, "usage_type": "name"}, {"api_name": "django.db.models.Q", "line_number": 234, "usage_type": "call"}, {"api_name": "django.db.models.Q", "line_number": 238, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes.underscore_name", "line_number": 243, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes", "line_number": 243, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes.build_tas_codes_filter", "line_number": 244, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes", "line_number": 244, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.underscore_name", "line_number": 245, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts", "line_number": 245, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.build_tas_codes_filter", "line_number": 246, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts", "line_number": 246, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.underscore_name", "line_number": 246, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.underscore_name", "line_number": 249, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts", "line_number": 249, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes.underscore_name", "line_number": 249, "usage_type": "attribute"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TasCodes", "line_number": 249, "usage_type": "name"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts.build_tas_codes_filter", "line_number": 250, "usage_type": "call"}, {"api_name": "usaspending_api.search.filters.postgres.tas.TreasuryAccounts", "line_number": 250, "usage_type": "name"}]}
+{"seq_id": "374050754", "text": "import argparse\nimport json\nimport csv\n\nimport yaml\nfrom backlog.base import BacklogAPI\n\ndef main():\n \"\"\"argparse tutorial 10\n\n Backlog APIを叩いてみるCLIツールを作る\n\n python-backlogの使用方法は以下のリンクを参照。\n http://blog.serverworks.co.jp/tech/2019/09/06/post-73944/\n\n API Keyの発行は以下のURLから\n https://.backlog.jp/EditApiSettings.action\n \"\"\"\n\n # https://docs.python.org/ja/3/library/argparse.html#argumentparser-objects\n parser = argparse.ArgumentParser(\n description=\"\"\"This is argparse tutorial - 10\n \n 簡易版Backlog CLIのようなもの\n \"\"\"\n )\n\n # 受け入れる引数の宣言\n parser.add_argument(\n '-c',\n '--conf',\n dest='conf',\n type=argparse.FileType('r'),\n default=open('conf.yml'),\n metavar='conf_file. (default: conf.yml)',\n # help='conf file'\n )\n\n parser.add_argument(\n '-p',\n '--project',\n dest='project',\n type=str,\n metavar='PROJECT_ID_OR_KEY',\n required=True,\n # help='Project id or key'\n )\n\n # パース+ロジック\n args = parser.parse_args()\n\n conf = yaml.load(args.conf, Loader=yaml.CLoader)\n check_conf(conf)\n\n backlog_client = backlog_get_client(\n space=conf['space'],\n api_key=conf['api_key']\n )\n\n # 戻り値はBacklog API V2の仕様に順序\n # https://developer.nulab.com/ja/docs/backlog/api/2/get-wiki-page-list/\n wikis = backlog_list_wikis(\n client=backlog_client,\n project=args.project\n )\n\n print(json.dumps(wikis))\n\n return 0\n\n\n\ndef backlog_get_client(space: str, api_key: str):\n \"\"\"Return Backlog API Client\n \n :param space: backlog space (backlog.jpのサブドメイン))\n :type space: str\n :param api_key: backlog api key\n :type api_key: str\n :return: Backlog API Client object\n :rtype: backlog.base.BacklogAPI\n \"\"\"\n return BacklogAPI(\n space=space,\n api_key=api_key\n )\n\n\ndef backlog_list_wikis(client: BacklogAPI, project: str):\n \"\"\"プロジェクト配下のwikiをリストする\n\n :param client: API Client\n :type client: BacklogAPI\n :param project: プロジェクトIDもくしはプロジェクトキー\n :type project: str\n \"\"\"\n return client.wiki.list(\n projectIdOrKey=project\n )\n\n\ndef check_conf(conf: dict):\n \"\"\"confの内容をチェック\n \n :param conf: 'space', 'api_key' の2つのキーが存在することを期待する\n :type conf: dict\n \"\"\"\n if not ('space' in conf.keys()):\n raise Exception('conf object does not have \"space\" key.')\n \n if not ('api_key' in conf.keys()):\n raise Exception('conf object does not have \"api_key\" key.')\n \n return True\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "10_example_cli_using_backlog_api/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 2877, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 21, "usage_type": "call"}, {"api_name": "argparse.FileType", "line_number": 33, "usage_type": "call"}, {"api_name": "yaml.load", "line_number": 52, "usage_type": "call"}, {"api_name": "yaml.CLoader", "line_number": 52, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 67, "usage_type": "call"}, {"api_name": "backlog.base.BacklogAPI", "line_number": 83, "usage_type": "call"}, {"api_name": "backlog.base.BacklogAPI", "line_number": 89, "usage_type": "name"}]}
+{"seq_id": "441343747", "text": "#!/bin/env python3\n# -*- coding: utf-8 -*-\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# A copy of the GNU General Public License is available at\n# http://www.gnu.org/licenses/gpl-3.0.html\n\n\"\"\"Perform assembly based on debruijn graph.\"\"\"\n\nimport argparse\nimport os\nimport sys\nimport statistics\nimport random\nimport math\nfrom random import randint\n\nimport pickle\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nrandom.seed(9001)\n\n__author__ = \"ROBILLARD Nicolas\"\n__copyright__ = \"Universite Paris Diderot\"\n__credits__ = [\"ROBILLARD Nicolas\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"ROBILLARD Nicolas\"\n__email__ = \"nicolas.robillard@ymail.com\"\n__status__ = \"alpha test\"\n\ndef isfile(path):\n \"\"\"Check if path is an existing file.\n :Parameters:\n path: Path to the file\n \"\"\"\n if not os.path.isfile(path):\n if os.path.isdir(path):\n msg = \"{0} is a directory\".format(path)\n else:\n msg = \"{0} does not exist.\".format(path)\n raise argparse.ArgumentTypeError(msg)\n return path\n\ndef get_arguments():\n \"\"\"Retrieves the arguments of the program.\n Returns: An object that contains the arguments\n \"\"\"\n # Parsing arguments\n parser = argparse.ArgumentParser(description=__doc__, usage=\n \"{0} -h\"\n .format(sys.argv[0]))\n parser.add_argument('-i', dest='fastq_file', type=isfile,\n required=True, help=\"Fastq file\")\n parser.add_argument('-k', dest='kmer_size', type=int,\n default=22, help=\"K-mer size (default 22)\")\n parser.add_argument('-o', dest='output_file', type=str,\n default=os.curdir + os.sep + \"contigs.fasta\",\n help=\"Output contigs in fasta file\")\n parser.add_argument('-f', dest='graphimg_file', type=str,\n help=\"Save graph as image (png)\")\n return parser.parse_args()\n\ndef read_fastq(fastq_file):\n \"\"\"Read fasta file\n ---\n Read a fastq file to import sequences\\n\n Argument:\n - fastq_file (argparse) : fastq file make in arguments of program\\n\n Return:\n - Generator of sequnces in fastq\n \"\"\"\n with open(fastq_file, 'r', encoding ='utf-8') as fastq:\n lines = fastq.readlines()\n for i in range(len(lines)):\n if lines[i].startswith(\"@\"):\n yield lines[i+1][:-1]\n\ndef cut_kmer(read, kmer_size):\n \"\"\"Cut sequence in k-mers\n ---\n Take a sequences and cut it into k-mers a specified lenght\\n\n Arguments:\n - read (str): sequence of letters\n - kmer_size (int): size of k-mers wanted (give in argparse)\\n\n Return:\n - Generator of k-mers\n \"\"\"\n nb_kmers = len(read) - kmer_size + 1\n for i in range(nb_kmers):\n kmer = read[i:i + kmer_size]\n yield kmer\n\ndef build_kmer_dict(fastq_file, kmer_size):\n \"\"\"Build dictionnary of k-mers\n ---\n Arguments:\n - fastq_file (argparse): fastq file choosen\n - kmer_size (argparse): lenght of k-mers choosen\\n\n Return:\n - kmer_dict (dict): dictionnary of k-mers in the fastq file\n \"\"\"\n kmers_dict = {}\n for seq in read_fastq(fastq_file):\n for kmer in cut_kmer(seq, kmer_size):\n if kmer not in kmers_dict.keys():\n kmers_dict[kmer]=seq.find(kmer)\n else:\n break\n return kmers_dict\n\ndef build_graph(kmer_dict):\n \"\"\"Produce a directed graph\n ---\n Argument:\n - kmer_dict (dict): dictonnary of k-mers\\n\n Return:\n - graph (nx.DiGraph): directed graph for the k-mers\n \"\"\"\n graph = nx.DiGraph()\n for kmer in kmer_dict.keys():\n graph.add_edge(kmer[:-1],kmer[1:],weight=kmer_dict[kmer])\n return graph\n\ndef remove_paths(graph, path_list, delete_entry_node, delete_sink_node):\n \"\"\"Remove paths in a graph\n ---\n Arguments:\n - graph (nx.Graph): De Bruijn's Graph by Network X\n - path_list (list): list of path between two nodes in graph\n - delete_entry_node (bool): indicate if the entry node need to be deleted\n - delete_sink_node (bool): indicate if the last node need to be deleted\\n\n Return:\n - graph (nx.Graph): graph simplified of low informative nodes\n \"\"\"\n if delete_entry_node is True and delete_sink_node is True:\n graph.remove_nodes_from([node for path in path_list for node in path])\n elif delete_entry_node is True and delete_sink_node is False:\n graph.remove_nodes_from([node for path in path_list for node in path[:-1]])\n elif delete_entry_node is False and delete_sink_node is True:\n graph.remove_nodes_from([node for path in path_list for node in path[1:]])\n else:\n graph.remove_nodes_from([node for path in path_list for node in path[1:-1]])\n return graph\n\ndef std(data):\n \"\"\"Calcul of the standard deviation in a sample\n ---\n Argument:\n - data (list): list of nodes\\n\n Return:\n - Standard deviation (int): standard deviation of the data\n \"\"\"\n mean = sum(data)/len(data)\n ech_mean = sum((l-mean)**2 for l in data) / (len(data)-1)\n return math.sqrt(ech_mean)\n\n\ndef select_best_path(graph, path_list, path_length, weight_avg_list,\n delete_entry_node=False, delete_sink_node=False):\n \"\"\"Select the best path in list of path\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - path_list (list): list of path in the graph\n - path_lenght (list): list of the lenght of paths in path_list\n - weight_avg_list (list): average weight of paths in path_list\n - delete_entry_node (bool): indicate if the entry node need to be deleted\n - delete_sink_node (bool): indicate if the last node need to be deleted\\n\n Return:\n - graph (nx.DiGraph): simplified graph\n \"\"\"\n if std(weight_avg_list) > 0:\n index_keep = weight_avg_list.index(max(weight_avg_list))\n elif std(weight_avg_list) ==0 and std(path_length) > 0:\n index_keep = path_length.index(max(path_length))\n else:\n index_keep = randint(0,len(path_list))\n del path_list[index_keep]\n remove_paths(graph, path_list, delete_entry_node, delete_sink_node)\n return graph\n\ndef path_average_weight(graph, path):\n \"\"\"Calcul of the mean of weights in a path\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - path (list): list of nodes in a path\\n\n Return:\n - mean weight of the path (int)\n \"\"\"\n return statistics.mean([d[\"weight\"] for (u, v, d) in graph.subgraph(path).edges(data=True)])\n\ndef solve_bubble(graph, ancestor_node, descendant_node):\n \"\"\"Resolve the bubble in a graph\n ---\n Select the path with the higher weight or the higher lenght in a bubble\n and remove all others paths\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\n - ancestor_node (node): upstream node in the graph\n - descendent_node (node): downstream node in the graph\\n\n Return:\n - graph (DiGraph): De Bruijn Graph without bubbles\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_list = []\n for path in nx.all_simple_paths(graph, ancestor_node,descendant_node):\n path_list.append(path)\n path_lenght.append(len(path))\n weight_avg_list.append(path_average_weight(graph, path))\n select_best_path(graph, path_list, path_lenght, weight_avg_list)\n return graph\n\ndef simplify_bubbles(graph):\n \"\"\" Simplify bubbles\n ---\n Simplfy bubble in a graph to have the more informative path\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's Graph by Network X\\n\n Return:\n - graph (nx.DiGraph): simplified De Bruijn's graph without bubbles\n \"\"\"\n bubble = False\n for node in graph.nodes:\n if node in graph.nodes():\n list_nodes = list(graph.predecessors(node))\n if len(list_nodes) >1:\n for i, npre in enumerate(list_nodes):\n for j in range(i+1,len(list_nodes)):\n node_ancestor = nx.lowest_common_ancestor(graph, npre, list_nodes[j])\n if node_ancestor is not None:\n bubble = True\n break\n if bubble:\n graph = simplify_bubbles(solve_bubble(graph, node_ancestor, node))\n return graph\n\ndef solve_entry_tips(graph, starting_nodes):\n \"\"\"Resolve the entry in a graph\n ---\n Select the entry node of the graph with higher weight or the higher\n lenght of path and remove others.\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn Graph by Network X\n - starting_nodes (list): list of possible entry nodes\\n\n Return:\n - graph (nx.DiGraph): De Bruijn's graph with the one entry node\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_path = []\n for nodes in graph.nodes:\n nodes_pred = list(graph.predecessors(nodes))\n if len(nodes_pred) > 1:\n for entries in starting_nodes:\n path_list += list(nx.all_simple_paths(graph, entries, nodes))\n if len(path_list) > 0:\n for path in path_list:\n path_lenght.append(len(path))\n weight_avg_path.append(path_average_weight(graph, path))\n graph = select_best_path(graph, path_list, path_lenght, weight_avg_path,\n delete_entry_node=True)\n return graph\n\ndef solve_out_tips(graph, ending_nodes):\n \"\"\"Resolve the output in a graph\n ---\n Select the output node of the graph with higher weight or\n the higher lenght of path and remove others.\\n\n Arguments:\n - graph (nx.DiGraph): De Bruijn Graph by Network X\n - ending_nodes (list): list of possible outputs nodes\\n\n Return:\n - graph (nx.DiGraph): De Bruijn's graph with the one output node\n \"\"\"\n path_list = []\n path_lenght = []\n weight_avg_path = []\n for nodes in graph.nodes:\n successors = list(graph.successors(nodes))\n if len(successors) > 1:\n for outputs in ending_nodes:\n path_list += list(nx.all_simple_paths(graph, nodes, outputs))\n if len(path_list) > 0:\n for path in path_list:\n path_lenght.append(len(path))\n weight_avg_path.append(path_average_weight(graph, path))\n graph = select_best_path(graph, path_list, path_lenght,\n weight_avg_path, delete_sink_node=True)\n return graph\n\ndef get_starting_nodes(graph):\n \"\"\"Get the starting node\n ---\n Select all starting nodes in a graph\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's graph\\n\n Return:\n - starting_nodes (list): list of starting nodes in the graph\n \"\"\"\n starting_nodes = []\n for nodes in graph:\n if len(list(graph.predecessors(nodes))) == 0:\n starting_nodes.append(nodes)\n return starting_nodes\n\ndef get_sink_nodes(graph):\n \"\"\"Get the ending node\n ---\n Select all ending nodes in a graph\\n\n Argument:\n - graph (nx.DiGraph): De Bruijn's graph\\n\n Return:\n - sink_nodes (list): list of ending nodes in the graph\n \"\"\"\n sink_nodes = []\n for nodes in graph:\n if len(list(graph.successors(nodes))) == 0:\n sink_nodes.append(nodes)\n return sink_nodes\n\ndef concat_path(path_list):\n \"\"\"Concantenate list of k-mers\n ---\n Argument:\n - path_list (list): list of k-mers\\n\n Return:\n - path_str (str): string of the path with k-mers\n \"\"\"\n path_str=path_list[0]\n for i in path_list[1:]:\n path_str += i[-1]\n return path_str\n\ndef get_contigs(graph, starting_nodes, ending_nodes):\n \"\"\"Build contigs between two nodes\n ---\n Arguments:\n - graph (nx.DiGraph): De Bruijn's graph\n - starting_nodes (list): list of starting nodes in a graph\n - ending_nodes (list): list of ending nodes in a graph\\n\n Return:\n - contigs (list): list of sequences (str) possible in the graph\n \"\"\"\n contigs = []\n for start_node in starting_nodes:\n for end_node in ending_nodes:\n if nx.has_path(graph, start_node,end_node):\n for simple_path in nx.all_simple_paths(graph,start_node,end_node):\n path = concat_path(simple_path)\n contigs.append((path,len(path)))\n return contigs\n\ndef save_contigs(contigs_list, output_file):\n \"\"\"Save contigs in a fasta file\n ---\n Arguments:\n - contigs_list (list): list of contigs in a graph\n - output_file (str): name of the fasta file return\\n\n Return:\n - fasta (fasta file): write fasta file for contigs\n \"\"\"\n with open(f\"{output_file}.fasta\", \"w\", encoding='utf-8') as fasta:\n # extract number of contig and contig\n for index,contig in enumerate(contigs_list):\n # write a fasta file\n fasta.write(\">contig_\" + str(index) + \" len=\" + str(contig[1]) +\n \"\\n\" + fill(contig[0]) + \"\\n\")\n return fasta\n\ndef fill(text, width=80):\n \"\"\"Split text with a line return to respect fasta format\"\"\"\n return os.linesep.join(text[i:i+width] for i in range(0, len(text), width))\n\ndef draw_graph(graph, graphimg_file):\n \"\"\"Draw the graph\n \"\"\"\n fig, ax = plt.subplots()\n elarge = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] > 3]\n\n esmall = [(u, v) for (u, v, d) in graph.edges(data=True) if d['weight'] <= 3]\n pos = nx.random_layout(graph)\n nx.draw_networkx_nodes(graph, pos, node_size=6)\n nx.draw_networkx_edges(graph, pos, edgelist=elarge, width=6)\n nx.draw_networkx_edges(graph, pos, edgelist=esmall, width=6, alpha=0.5,\n edge_color='b', style='dashed')\n plt.savefig(graphimg_file)\n\n\ndef save_graph(graph, graph_file):\n \"\"\"Save the graph with pickle\n \"\"\"\n with open(graph_file, \"wt\") as save:\n pickle.dump(graph, save)\n\n\n#==============================================================\n# Main program\n#==============================================================\ndef main():\n \"\"\"\n Main program function\n \"\"\"\n # Get arguments\n args = get_arguments()\n # Build k-mers dictionnary and the graph with it\n print(f\"Get sequences and dictionnary of k-mers in ... {args.fastq_file}\")\n kmer_dictionnary = build_kmer_dict(args.fastq_file, args.kmer_size)\n print(\"Build De Bruijn's graph ...\")\n graph = build_graph(kmer_dictionnary)\n # Simplify the graph with remove of bubles\n graph = simplify_bubbles(graph)\n # Determine the starting node\n starting_nodes = get_starting_nodes(graph)\n #Determine the ending node\n sink_nodes = get_sink_nodes(graph)\n # Clear the graph of non informative entries\n graph = solve_entry_tips(graph, starting_nodes)\n # Clear the graph of non informative outputs\n graph = solve_out_tips(graph, sink_nodes)\n #Get contigs from the graph and save it in fasta file\n print(\"Get contigs and build the fasta file ...\")\n contigs = get_contigs(graph, starting_nodes, sink_nodes)\n save_contigs(contigs, args.output_file)\n # Fonctions de dessin du graphe\n # A decommenter si vous souhaitez visualiser un petit\n # graphe\n # Plot the graph\n if args.graphimg_file:\n draw_graph(graph, args.graphimg_file)\n # Save the graph in file\n if args.graph_file:\n save_graph(graph, args.graph_file)\n\nif __name__ == '__main__':\n main()\n", "sub_path": "debruijn/debruijn.py", "file_name": "debruijn.py", "file_ext": "py", "file_size_in_byte": 15712, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "random.seed", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentTypeError", "line_number": 49, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 57, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 59, "usage_type": "attribute"}, {"api_name": "os.curdir", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 65, "usage_type": "attribute"}, {"api_name": "networkx.DiGraph", "line_number": 127, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 163, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 185, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 199, "usage_type": "call"}, {"api_name": "networkx.all_simple_paths", "line_number": 216, "usage_type": "call"}, {"api_name": "networkx.lowest_common_ancestor", "line_number": 239, "usage_type": "call"}, {"api_name": "networkx.all_simple_paths", "line_number": 265, "usage_type": "call"}, {"api_name": "networkx.all_simple_paths", "line_number": 292, "usage_type": "call"}, {"api_name": "networkx.has_path", "line_number": 357, "usage_type": "call"}, {"api_name": "networkx.all_simple_paths", "line_number": 358, "usage_type": "call"}, {"api_name": "os.linesep.join", "line_number": 382, "usage_type": "call"}, {"api_name": "os.linesep", "line_number": 382, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 387, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 387, "usage_type": "name"}, {"api_name": "networkx.random_layout", "line_number": 391, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_nodes", "line_number": 392, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edges", "line_number": 393, "usage_type": "call"}, {"api_name": "networkx.draw_networkx_edges", "line_number": 394, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 396, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 396, "usage_type": "name"}, {"api_name": "pickle.dump", "line_number": 403, "usage_type": "call"}]}
+{"seq_id": "381338278", "text": "import numpy as np\nimport hidden_prints\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm import tqdm\n\n\nclass WeightedKNN:\n def __init__(self):\n pass\n\n @staticmethod\n def get_component_alphas(proj, cover, delta=0.1):\n \"\"\"Assigns image's latent space projection to cover's intervals.\n Projection is assigned to an interval if\n dist(proj, interval_midpoint) < interval_length*(1+delta)/2.\n\n :param proj: Projection of an image onto latent space's single\n component.\n :type proj: float\n :param cover: Cover of latent space's single component.\n :type cover: list\n :param delta: Parameter scaling intervals' lengths.\n :type delta: float\n\n :return: Indices of cover intervals onto which image was\n projected.\n :rtype: tuple\n \"\"\"\n\n alphas = []\n if proj < cover[0][1]:\n alphas.append(0)\n for i in range(1, len(cover)-1):\n midpoint = (cover[i][0] + cover[i][1])/2\n if abs(proj - midpoint) < abs(cover[i][1] - cover[i][0])*(1+delta)/2:\n alphas.append(i)\n if proj > cover[-1][0]:\n alphas.append(len(cover)-1)\n\n return tuple(alphas)\n \n def get_alphas(self, x, covers, latent_space):\n \"\"\"Assigns all images' latent space projections to covers'\n intervals.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param covers: Covers of latent space's components.\n :type covers: list\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n\n :return: Interval assignments of images' projections.\n :rtype: list\n \"\"\"\n \n with hidden_prints.HiddenPrints():\n x_latent = latent_space.transform(x)\n \n return [[self.get_component_alphas(img_latent[i], covers[i])\n for i in range(len(img_latent))] for img_latent in x_latent]\n\n @staticmethod\n def get_cover_preimages(x, covers, latent_space, n=0):\n \"\"\"Calculates cover preimages of latent space's nth component.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param covers: Covers of latent space's components.\n :type covers: list\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n :param n: Index of latent space's component.\n :type n: int\n\n :return preimage_ids: Ids of images split into preimages.\n :rtype preimage_ids: list\n \"\"\"\n\n n_intervals = len(covers[0])\n x_latent = latent_space.transform(x)\n preimage_ids = []\n\n for i in range(n_intervals):\n interval = covers[n][i]\n interval_ids = []\n\n for j, projection in enumerate(x_latent[:, n]):\n if projection > interval[0]:\n if projection < interval[1]:\n interval_ids.append(j)\n preimage_ids.append(interval_ids)\n\n return preimage_ids\n\n @staticmethod\n def fit_knns(x, preimages, k, n=0):\n \"\"\"Trains numerous KNN models on intervals' preimages.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param preimages: Preimages of intervals covering\n latent space's nth component.\n :type preimages: list\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param n: Index of latent space's component.\n :type n: int\n\n :return knns: KNNs trained on intervals' preimages.\n :rtype knns: dict\n \"\"\"\n\n knns = {}\n n_intervals = len(preimages)\n\n for i in range(n_intervals):\n knn = NearestNeighbors(n_neighbors=k, metric='euclidean')\n knn.fit(x[preimages[i]])\n knns.update({(n, tuple([i])): [knn, x[preimages[i]], np.array(preimages[i])]})\n if i > 0:\n knn = NearestNeighbors(n_neighbors=k, metric='euclidean')\n union = list(set(preimages[i]) | set(preimages[i-1]))\n knn.fit(x[union])\n knns.update({(n, tuple([i-1, i])): [knn, x[union], np.array(union)]})\n \n return knns\n\n @staticmethod\n def get_nearest_neighbours(x, alphas, knns, k, n=0):\n \"\"\"Calculates nearest neighbours of x's images.\n\n :param x: Images.\n :type x: numpy.ndarray\n :param alphas: Interval assignments of images' projections.\n :type alphas: list\n :param knns: Trained KNN models.\n :type knns: dict\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param n: Index of latent space's component.\n :type n: int\n\n :return nn_ids: Ids of images' k nearest neighbours.\n :rtype nn_ids: list\n :return nn_dists: Distances of images to their k nearest\n neighbours.\n :rtype nn_dists: list\n \"\"\"\n\n nn_ids = []\n nn_dists = []\n n_images = x.shape[0]\n\n for i in tqdm(range(n_images), desc='[wknn]'):\n nn_comp_ids = []\n nn_comp_dists = []\n\n nn = knns.get((n, alphas[i][n]))\n\n if len(nn[2]) > k:\n knn = nn[0].kneighbors([x[i]])\n ids = nn[2][knn[1]]\n nn_comp_ids.append(ids.squeeze())\n nn_comp_dists.append(knn[0].squeeze())\n else:\n ids = nn[2]\n dists = np.linalg.norm(x[i] - nn[1], axis=1)\n nn_comp_ids.append(ids)\n nn_comp_dists.append(dists)\n\n nn_ids.append(nn_comp_ids)\n nn_dists.append(nn_comp_dists)\n \n return nn_ids, nn_dists\n\n @staticmethod\n def get_weighted_representation(x_binary, nn_ids, nn_dists, k, mu=1e-05):\n \"\"\"Calculates weighted KNN representations.\n\n :param x_binary: Binary representation of images on which KNNs\n were trained.\n :type x_binary: numpy.ndarray\n :param nn_ids: Ids of images' k nearest neighbours.\n :type nn_ids: list\n :param nn_dists: Distances of images to their k nearest\n neighbours.\n :type nn_dists: list\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param mu: Parameter that ensures that there will be no\n division by 0.\n :type mu: float\n\n :return: Weighted KNN representation.\n :rtype: numpy.ndarray\n \"\"\"\n\n n_features = x_binary.shape[1]\n n_images = len(nn_ids)\n\n weighted_rep = np.zeros((n_images, n_features))\n\n for i in range(n_images):\n weights = nn_dists[i][0]\n weights = 1./(weights + mu)\n weights = np.asarray(weights / sum(weights)).reshape(1, k)\n features = weights.dot(x_binary[nn_ids[i][0], :].astype(float))\n weighted_rep[i] = features\n\n return np.asarray(weighted_rep)\n\n def fit_transform(self, k, x_test, x_train, x_train_binary, latent_space, covers):\n \"\"\"Generates a weighted KNN representation of x_test\n based on KNN models trained on x_train.\n\n :param k: Number of nearest neighbours in KNN.\n :type k: int\n :param x_test: Images without representation.\n :type x_test: numpy.ndarray\n :param x_train: Images with binary representation.\n :type x_train: numpy.ndarray\n :param x_train_binary: Binary representation of images.\n :type x_train_binary: numpy.ndarray\n :param latent_space: Latent space projector.\n :type latent_space: latent_space.LatentSpace\n :param covers: Covers of latent space's components.\n :type covers: list\n\n :return: Weighted KNN representation of x_test.\n :rtype: numpy.ndarray\n \"\"\"\n alphas = self.get_alphas(x_test, covers, latent_space)\n \n preimages = self.get_cover_preimages(x_train, covers, latent_space)\n knns = self.fit_knns(x_train, preimages, k)\n \n nn_ids, nn_dists = self.get_nearest_neighbours(x_test, alphas, knns, k)\n\n return self.get_weighted_representation(x_train_binary, nn_ids, nn_dists, k)\n", "sub_path": "weighted_knn.py", "file_name": "weighted_knn.py", "file_ext": "py", "file_size_in_byte": 8176, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "hidden_prints.HiddenPrints", "line_number": 57, "usage_type": "call"}, {"api_name": "sklearn.neighbors.NearestNeighbors", "line_number": 118, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 120, "usage_type": "call"}, {"api_name": "sklearn.neighbors.NearestNeighbors", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 125, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 168, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 168, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 202, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 211, "usage_type": "call"}]}
+{"seq_id": "452108362", "text": "from statistics import median\nfrom typing import Dict, List\n\nimport ccxt\nimport tqdm\n\nfrom modules.exchange import Price\nfrom modules.settings import settings\nfrom .coinone import coinone\nfrom .gopax import gopax\n\nEXCHANGE = settings.get('EXCHANGE', {\n \"BLACKLIST\": [],\n \"WHITELIST\": [],\n})\n\nEXCHANGE_BLACKLIST = EXCHANGE.get('BLACKLIST', [])\nEXCHANGE_WHITELIST = EXCHANGE.get('WHITELIST', None)\n\nDENOM = settings['UPDATER']['DENOM']\n\n# Inserting lite implementation of gopax API to ccxt\nsetattr(ccxt, \"gopax\", gopax)\nccxt.exchanges.append(\"gopax\")\n\n# replace coinone exchange with custom lite implementation to support LUNA/KRW pair\nsetattr(ccxt, \"coinone\", coinone)\n\n\n# noinspection PyBroadException\ndef filter_exchanges(currencies, from_exchanges) -> Dict[str, List[ccxt.Exchange]]:\n \"\"\"\n filtering exchanges, has fetch_ticker for luna/currency\n :return:\n filtered exchanges\n \"\"\"\n\n exchanges: Dict[str, List[ccxt.Exchange]] = {}\n\n for currency in currencies:\n symbol = f\"{DENOM}/{currency}\"\n exchanges[symbol] = []\n\n print(\"Checking available exchanges --\")\n\n exchange_tqdm = tqdm.tqdm(from_exchanges, \"Checking available exchanges\", disable=None)\n for exchange_id in exchange_tqdm:\n exchange_tqdm.set_description_str(f\"Checking '{exchange_id}' \")\n\n if exchange_id in EXCHANGE_BLACKLIST:\n continue\n\n try:\n exchange = getattr(ccxt, exchange_id)()\n markets = exchange.fetch_markets()\n if type(markets) == dict:\n markets = list(markets.values())\n\n if len(markets) == 0 or type(markets) != list or type(markets[0]) != dict:\n print(markets)\n print(\"Internal Error: Markets type mismatched on \", exchange_id)\n raise TypeError\n\n for market in markets:\n if 'symbol' not in market:\n print(market)\n print(\"Internal Error: Market type mismatched on \", exchange_id)\n raise TypeError\n\n symbol = market['symbol']\n if symbol in exchanges and hasattr(exchange, 'fetch_ticker'):\n exchanges[symbol].append(exchange)\n\n except Exception:\n pass\n\n return exchanges\n\n\ndef get_prices_data(exchanges: Dict[str, List[ccxt.Exchange]], sdr_rates, currencies) -> List[Price]:\n \"\"\"\n fetch add exchanges and calulcating additional values.\n :param exchanges: ccxt exchange object list to query\n :param sdr_rates: sdr rate information\n :param currencies: currencies ticker names to get\n :return: price list dictionary\n \"\"\"\n prices, sdr_prices, unfetched_currencies = fetch_all_exchanges(exchanges, sdr_rates, currencies)\n\n if not sdr_prices: # in case of no data fetched\n return []\n\n # calculate LUNA/SDR price\n sdr_price = median(sdr_prices)\n prices.append(Price(\"SDR\", sdr_price, dispersion=0))\n\n # fill unfetched prices in\n for currency in unfetched_currencies:\n sdr_rate = sdr_rates[currency]\n prices.append(Price(currency, (sdr_price / sdr_rate)))\n\n # calc. dispersion\n for price in prices:\n if price.currency == \"SDR\":\n continue\n\n sdr_rate = sdr_rates[price.currency]\n price.dispersion = 1 - ((sdr_price - (1 / price.raw_price / sdr_rate)) / sdr_price)\n\n return prices\n\n\ndef fetch_all_exchanges(exchanges: Dict[str, List[ccxt.Exchange]], sdr_rates: Dict[str, float],\n currencies: List[str]) -> (List[float]):\n prices: List[Price] = []\n sdr_prices: List[float] = []\n\n unfetched_currencies: List[str] = []\n\n success_count = 0\n failed_exchanges: List[str] = []\n\n currency_tqdm = tqdm.tqdm(currencies, \"Fetching\", disable=None)\n for currency in currency_tqdm:\n currency_tqdm.set_description_str(f\"Currency '{currency}'\")\n\n symbol = f\"{DENOM}/{currency}\"\n values: List[float] = []\n\n sdr_rate = sdr_rates.get(currency, 0)\n\n exchange_tqdm = tqdm.tqdm(exchanges[symbol], disable=None)\n for exchange in exchange_tqdm:\n exchange_tqdm.set_description_str(f\"Updating from '{exchange.id}'\")\n\n # noinspection PyBroadException\n try:\n last = float(exchange.fetch_ticker(symbol)['last'])\n values.append(last) # LUNA/CURRENCY <=> CURRENCY/LUNA\n\n if sdr_rate:\n sdr_prices.append(last * sdr_rate)\n\n success_count += 1\n\n except Exception:\n failed_exchanges.append(\"%s(%s)\" % (exchange.id, symbol))\n\n if values:\n prices.append(Price(currency, median(values)))\n else:\n unfetched_currencies.append(currency)\n\n # result logging\n print(\"\")\n print(f\"Success: {success_count}, Fail: {len(failed_exchanges)} [{failed_exchanges}]\")\n\n return prices, sdr_prices, unfetched_currencies\n", "sub_path": "priceserver/modules/exchange/ccxt.py", "file_name": "ccxt.py", "file_ext": "py", "file_size_in_byte": 4945, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "modules.settings.settings.get", "line_number": 12, "usage_type": "call"}, {"api_name": "modules.settings.settings", "line_number": 12, "usage_type": "name"}, {"api_name": "modules.settings.settings", "line_number": 20, "usage_type": "name"}, {"api_name": "gopax.gopax", "line_number": 23, "usage_type": "argument"}, {"api_name": "ccxt.exchanges.append", "line_number": 24, "usage_type": "call"}, {"api_name": "ccxt.exchanges", "line_number": 24, "usage_type": "attribute"}, {"api_name": "coinone.coinone", "line_number": 27, "usage_type": "argument"}, {"api_name": "typing.Dict", "line_number": 38, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 38, "usage_type": "name"}, {"api_name": "ccxt.Exchange", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 46, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 31, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 31, "usage_type": "name"}, {"api_name": "ccxt.Exchange", "line_number": 31, "usage_type": "attribute"}, {"api_name": "typing.Dict", "line_number": 80, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 80, "usage_type": "name"}, {"api_name": "ccxt.Exchange", "line_number": 80, "usage_type": "attribute"}, {"api_name": "statistics.median", "line_number": 94, "usage_type": "call"}, {"api_name": "modules.exchange.Price", "line_number": 95, "usage_type": "call"}, {"api_name": "modules.exchange.Price", "line_number": 100, "usage_type": "call"}, {"api_name": "modules.exchange.Price", "line_number": 80, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 113, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 113, "usage_type": "name"}, {"api_name": "ccxt.Exchange", "line_number": 113, "usage_type": "attribute"}, {"api_name": "typing.List", "line_number": 114, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 115, "usage_type": "name"}, {"api_name": "modules.exchange.Price", "line_number": 115, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 116, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 118, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 121, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 123, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 128, "usage_type": "name"}, {"api_name": "tqdm.tqdm", "line_number": 132, "usage_type": "call"}, {"api_name": "modules.exchange.Price", "line_number": 150, "usage_type": "call"}, {"api_name": "statistics.median", "line_number": 150, "usage_type": "call"}]}
+{"seq_id": "220361555", "text": "from datetime import datetime, timedelta\n\nimport yfinance as yf\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nNUMBER_OF_ENTRIES_A_DAY = 7\n\n\ndef is_stock_elevating(stock_token: str, start: str, time_delta_in_days: int) -> bool:\n \"\"\"\n returns a boolean whether the stock is elevating in time_delta_in_days from the start\n :param stock_token:\n :param start: start date of evaluation\n :param time_delta_in_days: how many days from start of evaluation should be included\n :return: True if Stock of stock_token is elevating else false\n \"\"\"\n ticker = yf.Ticker(stock_token)\n # calculate end\n date_parts = start.split('-')\n date_parts[2] = str(int(date_parts[2]) + time_delta_in_days).zfill(2)\n end = '-'.join(date_parts)\n\n dataframe = ticker.history(start=start, end=end, interval='1h')\n m, b = calculate_best_fitting_line(range(dataframe.shape[0]), dataframe['Close'].values)\n print(f'm={m} , b={b}')\n if m > 0:\n return True\n return False\n\n\ndef average_slopes_of_stock(stock_token: str, start_datetime: datetime, max_days: int = 10, plot_data: bool = False) -> \\\n np.ndarray or None:\n \"\"\"\n List of average slopes of the stock from the start in 1 to max_days-1 days intervals\n :param start_datetime: start datetime\n :param plot_data: True if the data and best fitting line should be ploted\n :param stock_token: the specific stock token\n :param max_days: how many days after start you want to have the average slopes\n :return: List of average slopes\n \"\"\"\n ticker = yf.Ticker(stock_token)\n # calculate start and end date\n timedelta_max_days = timedelta(days=max_days)\n end_datetime = start_datetime + timedelta_max_days\n start = start_datetime.strftime('%Y-%m-%d')\n end = end_datetime.strftime('%Y-%m-%d')\n # get tickers history\n dataframe = ticker.history(start=start, end=end, interval='1h')\n close = dataframe['Close'].values\n if len(close) > 0:\n # calculate best fitting line from start in interval_day steps\n elevations = np.zeros(17)\n i = 0\n for interval_day in range(1, max_days - 1):\n number_of_entries = int(interval_day * NUMBER_OF_ENTRIES_A_DAY)\n interval_close = close[0:number_of_entries]\n if i <= 16:\n m, b = calculate_best_fitting_line(range(len(interval_close)), interval_close, plot_data)\n if np.isnan(m):\n return None\n elevations[i] = m\n i += 1\n if elevations[0] != np.nan:\n return elevations\n return None\n\n\ndef calculate_best_fitting_line(x, y, plot_data: bool = False) -> (int, int):\n \"\"\"\n Calculates the best fitting line of points in dataframe\n :param y: Y-Coordinates\n :param x: X-Coordinates\n :param plot_data: whether the data and line should be plotted (default = False)\n :return: Gradient and y axis intercept\n \"\"\"\n # y = dataframe['Close']\n # x = range(dataframe.shape[0])\n try:\n m, b = np.polyfit(x, y, 1)\n except:\n return 0, 0\n if plot_data:\n plot_line_with_data_points(x, y, m, b)\n return m, b\n\n\ndef plot_line_with_data_points(x, y, m, b) -> None:\n \"\"\"\n Plots all datapoints x and y with a line crated from m and b\n :param x: x coordinates\n :param y: y coordinates\n :param m: Gradient of line\n :param b: y axis intercept of Line\n :return:None\n \"\"\"\n plt.plot(x, y, 'o')\n plt.plot(x, m * x + b)\n plt.show()\n\n\ndef plot_dataframe(dataframe) -> None:\n \"\"\"\n Plots the ['Close'] coordinates of the dataframe\n :param dataframe:\n :return: None\n \"\"\"\n dataframe['Close'].plot()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Adjusted\")\n plt.show()\n\n\ndef plot_stock(stock_token: str, start: str, end: str) -> None:\n \"\"\"\n Plots a stock from a start date to the end date\n :param stock_token: token of stock which should be ploted\n :param start: start date in format \"YYYY-MM-DD\"\n :param end: end date in format \"YYYY-MM-DD\"\n :return: None\n \"\"\"\n ticker = yf.Ticker(stock_token)\n dataframe = ticker.history(start=start, end=end)\n plot_dataframe(dataframe)\n\n\nif __name__ == '__main__':\n print(is_stock_elevating('TSLA', \"2021-02-01\", 25))\n print(is_stock_elevating('CLOV', \"2021-02-01\", 25))\n start_datetime = datetime.fromisoformat(\"2021-02-01\")\n stocks_slope = average_slopes_of_stock('TSLA', start_datetime, 8, plot_data=True)\n print(stocks_slope)\n", "sub_path": "retrieval/Financial.py", "file_name": "Financial.py", "file_ext": "py", "file_size_in_byte": 4489, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "yfinance.Ticker", "line_number": 18, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "name"}, {"api_name": "yfinance.Ticker", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.polyfit", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 109, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 109, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 111, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 111, "usage_type": "name"}, {"api_name": "yfinance.Ticker", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.datetime.fromisoformat", "line_number": 130, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 130, "usage_type": "name"}]}
+{"seq_id": "281598534", "text": "# Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport base\nimport json\n\nfrom API.common import console, paths, utils\n\n\nclass Application(base.ApplicationBase):\n '''\n IoT.js application.\n '''\n def __init__(self, options):\n super(self.__class__, self).__init__('iotjs', 'iotjs', options)\n\n def get_image(self):\n '''\n Return the path to the binary.\n '''\n return utils.join(paths.IOTJS_BUILD_PATH, 'iotjs') % self.buildtype\n\n def get_image_stack(self):\n '''\n Return the path to the stack binary.\n '''\n return utils.join(paths.IOTJS_BUILD_STACK_PATH, 'iotjs') % self.buildtype\n\n def get_target_profile_mapfile(self):\n '''\n Return the path to the target profile map file.\n '''\n return paths.IOTJS_TARGET_MAP_FILE_PATH\n\n def get_minimal_profile_mapfile(self):\n '''\n Return the path to the minimal profile map file.\n '''\n return paths.IOTJS_MINIMAL_MAP_FILE_PATH\n\n def get_home_dir(self):\n '''\n Return the path to the application files.\n '''\n return paths.IOTJS_APPS_PATH\n\n def get_install_dir(self):\n '''\n Return the path to where the application files should be copied.\n '''\n return utils.join(paths.NUTTX_APPS_SYSTEM_PATH, 'iotjs')\n\n def get_test_dir(self):\n '''\n Return the path to the application test files.\n '''\n return paths.IOTJS_TEST_PATH\n\n def get_config_file(self):\n '''\n Return the path to OS configuration file.\n '''\n return utils.join(paths.CONFIG_PATH, 'iotjs.config')\n\n def get_romfs_file(self):\n '''\n Return the path of the generated ROMFS image.\n '''\n utils.generate_romfs(paths.IOTJS_PATH, paths.IOTJS_TEST_PATH)\n\n return utils.join(paths.IOTJS_PATH, 'nsh_romfsimg.h')\n\n def __apply_heap_patches(self, device, revert=False):\n '''\n Apply memstat patches to measure the memory consumption of IoT.js\n '''\n if device.get_type() in ['stm32f4dis', 'artik053']:\n iotjs_memstat_patch = utils.join(paths.PATCHES_PATH, 'iotjs-memstat.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_memstat_patch, revert)\n\n libtuv_memstat_patch = utils.join(paths.PATCHES_PATH, 'libtuv-memstat.diff')\n utils.patch(paths.IOTJS_LIBTUV_PATH, libtuv_memstat_patch, revert)\n utils.execute(paths.IOTJS_LIBTUV_PATH, 'git', ['add', '-u'])\n\n jerry_memstat_patch = utils.join(paths.PATCHES_PATH, 'jerry-memstat.diff')\n utils.patch(paths.IOTJS_JERRY_PATH, jerry_memstat_patch, revert)\n utils.execute(paths.IOTJS_JERRY_PATH, 'git', ['add', '-u'])\n\n def __apply_stack_patches(self, device, revert=False):\n '''\n Apply stack patch to measure the stack consumption of IoT.js\n '''\n if device.get_type() == 'rpi2':\n iotjs_stack_patch = utils.join(paths.PATCHES_PATH, 'iotjs-stack.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_stack_patch, revert)\n\n if device.get_type() == 'stm32f4dis':\n iotjs_stack_nuttx_patch = utils.join(paths.PATCHES_PATH, 'iotjs-stack-nuttx.diff')\n utils.patch(paths.IOTJS_PATH, iotjs_stack_nuttx_patch, revert)\n\n def build(self, device):\n '''\n Build IoT.js for the target device/OS and for Raspberry Pi 2.\n '''\n\n # prebuild the OS\n os = device.get_os()\n os.prebuild(self)\n\n utils.rmtree(paths.IOTJS_MAP_DIR_PATH)\n utils.mkdir(paths.IOTJS_MAP_DIR_PATH)\n\n build_flags = [\n '--clean',\n '--buildtype=%s' % self.buildtype,\n '--target-arch=arm',\n '--target-os=%s' % os.get_name(),\n ]\n\n # Step 1: Set the appropriate build flags for the targets.\n if device.get_type() == 'stm32f4dis':\n build_flags.append('--target-board=%s' % device.get_type())\n build_flags.append('--jerry-heaplimit=56')\n build_flags.append('--no-parallel-build')\n build_flags.append('--nuttx-home=%s' % paths.NUTTX_PATH)\n\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'nuttx.profile')\n mapfile = utils.join(paths.NUTTX_PATH, \"arch/arm/src/nuttx.map\")\n\n elif device.get_type() == 'rpi2':\n build_flags.append('--target-board=%s' % device.get_type())\n\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'rpi2-linux.profile')\n mapfile = utils.join(paths.IOTJS_BUILD_PATH % self.buildtype, \"../iotjs.map\")\n\n elif device.get_type() == 'artik053':\n profile = utils.join(paths.IOTJS_TEST_PROFILES_PATH, 'tizenrt.profile')\n mapfile = utils.join(paths.TIZENRT_BUILD_PATH, \"output/bin/tinyara.map\")\n\n else:\n console.fail('Non-minimal IoT.js build failed, unsupported '\n 'device (%s)!' % device.get_type())\n\n # Step 2: Create minimal profile build for the binary size measurement.\n build_flags.append('--profile=%s' % paths.IOTJS_MINIMAL_PROFILE_PATH)\n\n # Note: IoT.js is built by TizenRT in case of artik053.\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n os.build(self, self.buildtype, build_flags, 'all')\n utils.copy_file(mapfile, paths.IOTJS_MINIMAL_MAP_FILE_PATH)\n\n # Step 3: Create target specific profile build for the binary size measurement.\n os.prebuild(self)\n\n build_flags = build_flags[:-1]\n build_flags.append('--profile=%s' % profile)\n\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n os.build(self, self.buildtype, build_flags, 'all')\n utils.copy_file(mapfile, paths.IOTJS_TARGET_MAP_FILE_PATH)\n\n # Step 4: Create target specific profile with patches for the tests.\n self.__apply_heap_patches(device)\n\n if device.get_type() in ['stm32f4dis', 'artik053']:\n self.__apply_stack_patches(device)\n\n os.prebuild(self)\n\n build_flags_heap = list(build_flags)\n build_flags_heap.append('--jerry-memstat')\n if device.get_type() == 'rpi2':\n build_flags_heap.append('--compile-flag=-g')\n build_flags_heap.append('--jerry-compile-flag=-g')\n\n if device.get_type() in ['stm32f4dis', 'rpi2']:\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags_heap)\n\n os.build(self, self.buildtype, build_flags_heap, 'all')\n\n # Revert all the memstat patches from the project.\n self.__apply_heap_patches(device, revert=True)\n\n # Build the application to stack consumption check\n if device.get_type() == 'rpi2':\n self.__apply_stack_patches(device)\n build_flags.append('--builddir=%s' % paths.IOTJS_BUILD_STACK_DIR)\n utils.execute(paths.IOTJS_PATH, 'tools/build.py', build_flags)\n\n self.__apply_stack_patches(device, revert=True)\n\n\n def __in_dictlist(self, key, value, dictlist):\n for this in dictlist:\n if this[key] == value:\n return this\n return {}\n\n def __add_test_to_skip(self, os_name, test, reason):\n skip_os = test['skip'] if 'skip' in test else []\n\n if not ('all' and os_name) in skip_os:\n test['reason'] = reason\n skip_os.append(os_name)\n test['skip'] = skip_os\n\n def skip_test(self, test, os_name):\n '''\n Determine if a test should be skipped.\n '''\n skip_list = test.get('skip', [])\n\n for i in ['all', os_name, 'stable']:\n if i in skip_list:\n return True\n\n return False\n\n def read_testsets(self, device):\n '''\n Read all the tests\n '''\n\n # Read testsets\n testsets_file = utils.join(paths.IOTJS_TEST_PATH, 'testsets.json')\n testsets = {}\n\n with open(testsets_file, 'r') as testsets_p:\n testsets = json.load(testsets_p)\n\n # Read skip file\n skip_file = utils.join(paths.PROJECT_ROOT, 'API/testrunner/iotjs-skiplist.json')\n skip_list = self.get_skiplist(skip_file)\n skip_tests = skip_list[device.get_type()]['testfiles']\n skip_testsets = skip_list[device.get_type()]['testsets']\n\n os = device.get_os()\n os_name = os.get_name()\n\n # Update testset\n for testset in testsets:\n skip_testset = self.__in_dictlist('name', testset, skip_testsets)\n\n if skip_testset:\n for test in testsets[testset]:\n self.__add_test_to_skip(os_name, test, skip_testset['reason'])\n\n else:\n for skip_test in skip_tests:\n target_test = self.__in_dictlist('name', skip_test['name'], testsets[testset])\n\n if target_test:\n self.__add_test_to_skip(os_name, target_test, skip_test['reason'])\n\n return testsets\n", "sub_path": "API/application/iotjs.py", "file_name": "iotjs.py", "file_ext": "py", "file_size_in_byte": 9660, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "base.ApplicationBase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "API.common.utils.join", "line_number": 32, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 32, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_BUILD_PATH", "line_number": 32, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 32, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 38, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 38, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_BUILD_STACK_PATH", "line_number": 38, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 38, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TARGET_MAP_FILE_PATH", "line_number": 44, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 44, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_MINIMAL_MAP_FILE_PATH", "line_number": 50, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 50, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_APPS_PATH", "line_number": 56, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 56, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 62, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 62, "usage_type": "name"}, {"api_name": "API.common.paths.NUTTX_APPS_SYSTEM_PATH", "line_number": 62, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 62, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PATH", "line_number": 68, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 68, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 74, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 74, "usage_type": "name"}, {"api_name": "API.common.paths.CONFIG_PATH", "line_number": 74, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 74, "usage_type": "name"}, {"api_name": "API.common.utils.generate_romfs", "line_number": 80, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 80, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 80, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 80, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PATH", "line_number": 80, "usage_type": "attribute"}, {"api_name": "API.common.utils.join", "line_number": 82, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 82, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 82, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 82, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 89, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 89, "usage_type": "name"}, {"api_name": "API.common.paths.PATCHES_PATH", "line_number": 89, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 89, "usage_type": "name"}, {"api_name": "API.common.utils.patch", "line_number": 90, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 90, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 90, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 90, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 92, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 92, "usage_type": "name"}, {"api_name": "API.common.paths.PATCHES_PATH", "line_number": 92, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 92, "usage_type": "name"}, {"api_name": "API.common.utils.patch", "line_number": 93, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 93, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_LIBTUV_PATH", "line_number": 93, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 93, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 94, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 94, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_LIBTUV_PATH", "line_number": 94, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 94, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 96, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 96, "usage_type": "name"}, {"api_name": "API.common.paths.PATCHES_PATH", "line_number": 96, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 96, "usage_type": "name"}, {"api_name": "API.common.utils.patch", "line_number": 97, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 97, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_JERRY_PATH", "line_number": 97, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 97, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 98, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 98, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_JERRY_PATH", "line_number": 98, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 98, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 105, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 105, "usage_type": "name"}, {"api_name": "API.common.paths.PATCHES_PATH", "line_number": 105, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 105, "usage_type": "name"}, {"api_name": "API.common.utils.patch", "line_number": 106, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 106, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 106, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 106, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 109, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 109, "usage_type": "name"}, {"api_name": "API.common.paths.PATCHES_PATH", "line_number": 109, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 109, "usage_type": "name"}, {"api_name": "API.common.utils.patch", "line_number": 110, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 110, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 110, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 110, "usage_type": "name"}, {"api_name": "API.common.utils.rmtree", "line_number": 121, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 121, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_MAP_DIR_PATH", "line_number": 121, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 121, "usage_type": "name"}, {"api_name": "API.common.utils.mkdir", "line_number": 122, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 122, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_MAP_DIR_PATH", "line_number": 122, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 122, "usage_type": "name"}, {"api_name": "API.common.paths.NUTTX_PATH", "line_number": 136, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 136, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 138, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 138, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PROFILES_PATH", "line_number": 138, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 138, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 139, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 139, "usage_type": "name"}, {"api_name": "API.common.paths.NUTTX_PATH", "line_number": 139, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 139, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 144, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 144, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PROFILES_PATH", "line_number": 144, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 144, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 145, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 145, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_BUILD_PATH", "line_number": 145, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 145, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 148, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 148, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PROFILES_PATH", "line_number": 148, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 148, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 149, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 149, "usage_type": "name"}, {"api_name": "API.common.paths.TIZENRT_BUILD_PATH", "line_number": 149, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 149, "usage_type": "name"}, {"api_name": "API.common.console.fail", "line_number": 152, "usage_type": "call"}, {"api_name": "API.common.console", "line_number": 152, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_MINIMAL_PROFILE_PATH", "line_number": 156, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 156, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 160, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 160, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 160, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 160, "usage_type": "name"}, {"api_name": "API.common.utils.copy_file", "line_number": 163, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 163, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_MINIMAL_MAP_FILE_PATH", "line_number": 163, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 163, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 172, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 172, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 172, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 172, "usage_type": "name"}, {"api_name": "API.common.utils.copy_file", "line_number": 175, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 175, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TARGET_MAP_FILE_PATH", "line_number": 175, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 175, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 192, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 192, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 192, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 192, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_BUILD_STACK_DIR", "line_number": 202, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 202, "usage_type": "name"}, {"api_name": "API.common.utils.execute", "line_number": 203, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 203, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_PATH", "line_number": 203, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 203, "usage_type": "name"}, {"api_name": "API.common.utils.join", "line_number": 240, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 240, "usage_type": "name"}, {"api_name": "API.common.paths.IOTJS_TEST_PATH", "line_number": 240, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 240, "usage_type": "name"}, {"api_name": "json.load", "line_number": 244, "usage_type": "call"}, {"api_name": "API.common.utils.join", "line_number": 247, "usage_type": "call"}, {"api_name": "API.common.utils", "line_number": 247, "usage_type": "name"}, {"api_name": "API.common.paths.PROJECT_ROOT", "line_number": 247, "usage_type": "attribute"}, {"api_name": "API.common.paths", "line_number": 247, "usage_type": "name"}]}
+{"seq_id": "408207275", "text": "from __future__ import annotations\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Dict, List, Iterable, Optional\n from chessmaker.typings import Piece\n\nfrom chessmaker import Color, Controller, Direction, Ply, Vector2\nfrom chessmaker.info_elements import InfoElement, InfoText\nfrom chessmaker.actions import DestroyAction\nfrom ....packs.standard import Chess\nfrom ....packs.standard.helpers import next_color, find_pieces, threatened, print_color, OFFSETS, players_without_pieces\nfrom ....packs.standard.pieces import Bishop, King, Knight, Pawn, Queen, Rook\n\nKING_COLOR = {\n Color.RED: Color.ORANGE,\n Color.BLUE: Color.PURPLE,\n Color.ORANGE: Color.ORANGE,\n Color.PURPLE: Color.PURPLE,\n}\n\nOPPONENTS = {\n Color.RED: [Color.BLUE, Color.PURPLE],\n Color.ORANGE: [Color.BLUE, Color.PURPLE],\n Color.BLUE: [Color.RED, Color.ORANGE],\n Color.PURPLE: [Color.RED, Color.ORANGE],\n}\n\n\nclass Duos(Chess, Controller):\n name = 'Duos'\n colors = [\n Color.ORANGE,\n Color.PURPLE,\n Color.RED,\n Color.BLUE,\n ]\n\n def init_board(self, board: Dict[Vector2, Piece]) -> None:\n for color, direction, row in zip([Color.RED, Color.BLUE], [Direction.NORTH, Direction.SOUTH], [7, 0]):\n board[Vector2(row, 0)] = Rook(color, direction)\n board[Vector2(row, 1)] = Knight(color, direction)\n board[Vector2(row, 2)] = Bishop(color, direction)\n board[Vector2(row, 3)] = Queen(color, direction)\n board[Vector2(row, 6)] = Knight(color, direction)\n\n for color, direction, row in zip([Color.ORANGE, Color.PURPLE], [Direction.NORTH, Direction.SOUTH], [7, 0]):\n board[Vector2(row, 4)] = King(color, direction)\n board[Vector2(row, 5)] = Bishop(color, direction)\n board[Vector2(row, 7)] = Rook(color, direction)\n\n for color, direction, row in zip([Color.ORANGE, Color.PURPLE], [Direction.NORTH, Direction.SOUTH], [6, 1]):\n for col in range(8):\n board[Vector2(row, col)] = Pawn(color, direction)\n\n def get_info(self, color: Optional[Color]) -> List[InfoElement]:\n result = []\n\n for king_color in [Color.ORANGE, Color.PURPLE]:\n # Check if their king is in check.\n king_position, king = next(find_pieces(self.game.board, King, king_color))\n if threatened(self.game, king_position, OPPONENTS[king_color]):\n result.append(InfoText(f'{print_color(king_color)} is in check!'))\n\n result.append(InfoText(f'Current Turn: {print_color(next_color(self.game, list(players_without_pieces(self.game))))}'))\n\n return result\n\n def get_plies(self, color: Color, from_pos: Vector2, to_pos: Vector2) -> Iterable[Ply]:\n board = self.game.board\n piece = board[from_pos]\n\n # Make sure it is their piece and their turn.\n if color != piece.color or color != next_color(self.game, list(players_without_pieces(self.game))):\n return\n\n # Check for pawn promotion.\n if isinstance(piece, Pawn) and (\n (to_pos.row == 0 and piece.color in [Color.RED, Color.ORANGE])\n or (to_pos.row == 7 and piece.color in [Color.BLUE, Color.PURPLE])\n ):\n plies = pawn_promotions(piece, from_pos, to_pos)\n else:\n plies = piece.get_plies(from_pos, to_pos, self.game.game_data)\n\n for ply in plies:\n # Make sure they are not capturing their teammate's piece.\n captures = filter(lambda action: isinstance(action, DestroyAction), ply.actions)\n if any(board[capture.pos].color not in OPPONENTS[color] for capture in captures):\n continue\n\n # The owner of their team's king needs to sure they are not in check after each ply is complete.\n if color == KING_COLOR[color]:\n state = self.game.next_state(color, ply)\n king_position, king = next(find_pieces(state.board, King, color))\n if threatened(self.game, king_position, OPPONENTS[color], state):\n continue\n\n yield ply\n\n def after_ply(self) -> None:\n color = next_color(self.game, list(players_without_pieces(self.game)))\n if color not in [Color.ORANGE, Color.PURPLE]:\n return\n\n king_position, king = next(find_pieces(self.game.board, King, color))\n\n if not self._has_legal_move(color):\n if threatened(self.game, king_position, OPPONENTS[color]):\n self.game.winner(OPPONENTS[color], 'Checkmate')\n else:\n self.game.winner([], 'Stalemate')\n\n def _is_legal(self, from_pos: Vector2, to_pos: Vector2) -> bool:\n if to_pos.row >= self.board_size.row or to_pos.row < 0 or to_pos.col >= self.board_size.col or to_pos.col < 0:\n return False\n\n piece = self.game.board[from_pos]\n plies = piece.get_plies(from_pos, to_pos, self.game.game_data)\n\n for ply in plies:\n # Capturing your teammate is not legal.\n captures = filter(lambda action: isinstance(action, DestroyAction), ply.actions) # TODO: Extract function.\n if any(self.game.board[capture.pos].color not in OPPONENTS[piece.color] for capture in captures):\n continue\n\n state = self.game.next_state(piece.color, ply)\n\n king_position, king = next(find_pieces(state.board, King, piece.color))\n\n if not threatened(self.game, king_position, OPPONENTS[piece.color], state):\n return True\n\n return False\n\n def _has_legal_move(self, color: Color) -> bool:\n for pos, piece in find_pieces(self.game.board, color=color):\n if isinstance(piece, Pawn):\n if piece.direction == Direction.NORTH and (\n self._is_legal(pos, pos + Vector2(0, -1))\n or self._is_legal(pos, pos + Vector2(0, -2))\n or self._is_legal(pos, pos + Vector2(1, -1))\n or self._is_legal(pos, pos + Vector2(-1, -1))\n ):\n return True\n\n if piece.direction == Direction.SOUTH and (\n self._is_legal(pos, pos + Vector2(0, 1))\n or self._is_legal(pos, pos + Vector2(0, 2))\n or self._is_legal(pos, pos + Vector2(1, 1))\n or self._is_legal(pos, pos + Vector2(-1, 1))\n ):\n return True\n\n if isinstance(piece, Rook) or isinstance(piece, Queen):\n for i in range(8):\n if self._is_legal(pos, Vector2(pos.row, i)) or self._is_legal(pos, Vector2(i, pos.col)):\n return True\n\n if isinstance(piece, Knight):\n if (\n self._is_legal(pos, pos + Vector2(1, 2))\n or self._is_legal(pos, pos + Vector2(2, 1))\n or self._is_legal(pos, pos + Vector2(1, -2))\n or self._is_legal(pos, pos + Vector2(2, -1))\n or self._is_legal(pos, pos + Vector2(-1, 2))\n or self._is_legal(pos, pos + Vector2(-2, 1))\n or self._is_legal(pos, pos + Vector2(-1, -2))\n or self._is_legal(pos, pos + Vector2(-2, -1))\n ):\n return True\n\n if isinstance(piece, Bishop) or isinstance(piece, Queen):\n for i in range(-7, 8):\n if self._is_legal(pos, pos + Vector2(i, i)) or self._is_legal(pos, pos + Vector2(i, i)):\n return True\n\n if isinstance(piece, King):\n for offset in OFFSETS.values():\n if self._is_legal(pos, pos + offset):\n return True\n\n return False\n", "sub_path": "app/chessmaker/packs/party/controllers/duos.py", "file_name": "duos.py", "file_ext": "py", "file_size_in_byte": 7833, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "typing.TYPE_CHECKING", "line_number": 3, "usage_type": "name"}, {"api_name": "chessmaker.Color.RED", "line_number": 15, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 15, "usage_type": "name"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 16, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 16, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 17, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 17, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 18, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 18, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 15, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 16, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.RED", "line_number": 22, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 22, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 23, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 23, "usage_type": "name"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 24, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 24, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 25, "usage_type": "name"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 22, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 23, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 23, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.RED", "line_number": 24, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 24, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.RED", "line_number": 25, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 25, "usage_type": "attribute"}, {"api_name": "packs.standard.Chess", "line_number": 29, "usage_type": "name"}, {"api_name": "chessmaker.Controller", "line_number": 29, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 32, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 32, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 33, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 33, "usage_type": "name"}, {"api_name": "chessmaker.Color.RED", "line_number": 34, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 34, "usage_type": "name"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 35, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 38, "usage_type": "name"}, {"api_name": "chessmaker.Vector2", "line_number": 38, "usage_type": "name"}, {"api_name": "chessmaker.typings.Piece", "line_number": 38, "usage_type": "name"}, {"api_name": "chessmaker.Color.RED", "line_number": 39, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 39, "usage_type": "name"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 39, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction.NORTH", "line_number": 39, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction", "line_number": 39, "usage_type": "name"}, {"api_name": "chessmaker.Direction.SOUTH", "line_number": 39, "usage_type": "attribute"}, {"api_name": "chessmaker.Vector2", "line_number": 40, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Rook", "line_number": 40, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 41, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Knight", "line_number": 41, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 42, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Bishop", "line_number": 42, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 43, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Queen", "line_number": 43, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 44, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Knight", "line_number": 44, "usage_type": "call"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 46, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 46, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction.NORTH", "line_number": 46, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction", "line_number": 46, "usage_type": "name"}, {"api_name": "chessmaker.Direction.SOUTH", "line_number": 46, "usage_type": "attribute"}, {"api_name": "chessmaker.Vector2", "line_number": 47, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 47, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 48, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Bishop", "line_number": 48, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 49, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Rook", "line_number": 49, "usage_type": "call"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 51, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 51, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction.NORTH", "line_number": 51, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction", "line_number": 51, "usage_type": "name"}, {"api_name": "chessmaker.Direction.SOUTH", "line_number": 51, "usage_type": "attribute"}, {"api_name": "chessmaker.Vector2", "line_number": 53, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Pawn", "line_number": 53, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 55, "usage_type": "name"}, {"api_name": "chessmaker.Color", "line_number": 55, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 58, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 58, "usage_type": "attribute"}, {"api_name": "packs.standard.helpers.find_pieces", "line_number": 60, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 60, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.threatened", "line_number": 61, "usage_type": "call"}, {"api_name": "chessmaker.info_elements.InfoText", "line_number": 62, "usage_type": "call"}, {"api_name": "packs.standard.helpers.print_color", "line_number": 62, "usage_type": "call"}, {"api_name": "chessmaker.info_elements.InfoText", "line_number": 64, "usage_type": "call"}, {"api_name": "packs.standard.helpers.print_color", "line_number": 64, "usage_type": "call"}, {"api_name": "packs.standard.helpers.next_color", "line_number": 64, "usage_type": "call"}, {"api_name": "packs.standard.helpers.players_without_pieces", "line_number": 64, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 55, "usage_type": "name"}, {"api_name": "chessmaker.info_elements.InfoElement", "line_number": 55, "usage_type": "name"}, {"api_name": "chessmaker.Color", "line_number": 68, "usage_type": "name"}, {"api_name": "chessmaker.Vector2", "line_number": 68, "usage_type": "name"}, {"api_name": "packs.standard.helpers.next_color", "line_number": 73, "usage_type": "call"}, {"api_name": "packs.standard.helpers.players_without_pieces", "line_number": 73, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Pawn", "line_number": 77, "usage_type": "argument"}, {"api_name": "chessmaker.Color.RED", "line_number": 78, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 78, "usage_type": "name"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 78, "usage_type": "attribute"}, {"api_name": "chessmaker.Color.BLUE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 79, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "chessmaker.actions.DestroyAction", "line_number": 87, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.find_pieces", "line_number": 94, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 94, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.threatened", "line_number": 95, "usage_type": "call"}, {"api_name": "typing.Iterable", "line_number": 68, "usage_type": "name"}, {"api_name": "chessmaker.Ply", "line_number": 68, "usage_type": "name"}, {"api_name": "packs.standard.helpers.next_color", "line_number": 101, "usage_type": "call"}, {"api_name": "packs.standard.helpers.players_without_pieces", "line_number": 101, "usage_type": "call"}, {"api_name": "chessmaker.Color.ORANGE", "line_number": 102, "usage_type": "attribute"}, {"api_name": "chessmaker.Color", "line_number": 102, "usage_type": "name"}, {"api_name": "chessmaker.Color.PURPLE", "line_number": 102, "usage_type": "attribute"}, {"api_name": "packs.standard.helpers.find_pieces", "line_number": 105, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 105, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.threatened", "line_number": 108, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 113, "usage_type": "name"}, {"api_name": "chessmaker.actions.DestroyAction", "line_number": 122, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.find_pieces", "line_number": 128, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 128, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.threatened", "line_number": 130, "usage_type": "call"}, {"api_name": "chessmaker.Color", "line_number": 135, "usage_type": "name"}, {"api_name": "packs.standard.helpers.find_pieces", "line_number": 136, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Pawn", "line_number": 137, "usage_type": "argument"}, {"api_name": "chessmaker.Direction.NORTH", "line_number": 138, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction", "line_number": 138, "usage_type": "name"}, {"api_name": "chessmaker.Vector2", "line_number": 139, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 140, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 141, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 142, "usage_type": "call"}, {"api_name": "chessmaker.Direction.SOUTH", "line_number": 146, "usage_type": "attribute"}, {"api_name": "chessmaker.Direction", "line_number": 146, "usage_type": "name"}, {"api_name": "chessmaker.Vector2", "line_number": 147, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 148, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 149, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 150, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Rook", "line_number": 154, "usage_type": "argument"}, {"api_name": "packs.standard.pieces.Queen", "line_number": 154, "usage_type": "argument"}, {"api_name": "chessmaker.Vector2", "line_number": 156, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Knight", "line_number": 159, "usage_type": "argument"}, {"api_name": "chessmaker.Vector2", "line_number": 161, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 162, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 163, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 164, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 165, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 166, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 167, "usage_type": "call"}, {"api_name": "chessmaker.Vector2", "line_number": 168, "usage_type": "call"}, {"api_name": "packs.standard.pieces.Bishop", "line_number": 172, "usage_type": "argument"}, {"api_name": "packs.standard.pieces.Queen", "line_number": 172, "usage_type": "argument"}, {"api_name": "chessmaker.Vector2", "line_number": 174, "usage_type": "call"}, {"api_name": "packs.standard.pieces.King", "line_number": 177, "usage_type": "argument"}, {"api_name": "packs.standard.helpers.OFFSETS.values", "line_number": 178, "usage_type": "call"}, {"api_name": "packs.standard.helpers.OFFSETS", "line_number": 178, "usage_type": "name"}]}
+{"seq_id": "404141609", "text": "import json\n\nfrom math import isnan\nfrom itertools import compress\nfrom hashlib import md5\nfrom numbers import Number\nfrom typing import Optional, Tuple, Sequence, Any, List, Iterable, Dict\n\nfrom coba.pipes import Source, HttpSource\nfrom coba.config import CobaConfig, CobaException\n\nfrom coba.simulations.core import Context, Action, Interaction, Simulation, ClassificationSimulation, RegressionSimulation\n\nclass OpenmlSource(Source[Tuple[Sequence[Context], Sequence[Action]]]):\n\n def __init__(self, id:int, problem_type:str = \"classification\", nominal_as_str:bool=False, md5_checksum:str = None):\n \n assert problem_type in [\"classification\", \"regression\"]\n \n self._data_id = id\n self._md5_checksum = md5_checksum\n self._problem_type = problem_type \n self._nominal_as_str = nominal_as_str\n self._cached_urls = []\n\n #add flag to allow regression simulations\n #if a known exception happens still cache the query results\n\n def read(self) -> Tuple[Sequence[Sequence[Any]], Sequence[Any]]:\n \n #placing some of these at the top would cause circular references\n from coba.encodings import Encoder, NumericEncoder, OneHotEncoder, StringEncoder\n from coba.pipes import Encode, Transpose\n\n try:\n data_id = self._data_id\n md5_checksum = self._md5_checksum\n\n dataset_description = self._get_dataset_description(data_id)\n\n if dataset_description['status'] == 'deactivated':\n raise CobaException(f\"Openml {data_id} has been deactivated. This is often due to flags on the data.\")\n \n feature_descriptions = self._get_feature_descriptions(data_id)\n\n headers : List[str] = []\n encoders: List[Encoder] = []\n ignored : List[bool] = []\n target : str = \"\"\n\n for tipe in feature_descriptions:\n\n headers.append(tipe['name'].lower())\n ignored.append(tipe['is_ignore'] == 'true' or tipe['is_row_identifier'] == 'true')\n\n if tipe['is_target'] == 'true':\n target = tipe['name'].lower()\n \n if tipe['data_type'] == 'numeric':\n encoders.append(NumericEncoder()) \n elif tipe['data_type'] == 'nominal':\n if self._nominal_as_str:\n encoders.append(StringEncoder())\n else:\n encoders.append(OneHotEncoder(singular_if_binary=True))\n else:\n ignored[-1] = True\n encoders.append(StringEncoder())\n\n if target != \"\":\n target_encoder = encoders[headers.index(target)]\n problem_encoder = NumericEncoder if self._problem_type == \"regression\" else (OneHotEncoder,StringEncoder)\n\n if target == \"\" or not isinstance(target_encoder, problem_encoder):\n target = self._get_target_for_problem_type(data_id)\n ignored[headers.index(target)] = False\n\n if self._problem_type == \"classification\":\n target_encoder = StringEncoder() if self._nominal_as_str else OneHotEncoder(singular_if_binary=False)\n encoders[headers.index(target)] = target_encoder\n\n file_rows = self._get_dataset_rows(dataset_description[\"file_id\"], target, md5_checksum)\n is_sparse = isinstance(file_rows[0], tuple) and len(file_rows[0]) == 2\n\n if is_sparse:\n file_headers = [ header.lower() for header in file_rows.pop(0)[1]]\n else:\n file_headers = [ header.lower() for header in file_rows.pop(0)]\n\n file_cols = list(Transpose().filter(file_rows))\n\n for ignored_header in compress(headers, ignored):\n if ignored_header in file_headers:\n file_cols.pop(file_headers.index(ignored_header))\n file_headers.remove(ignored_header)\n\n file_encoders = [ encoders[headers.index(file_header)] for file_header in file_headers]\n\n if is_sparse:\n label_col = file_cols[file_headers.index(target)]\n \n dense_label_col = ['0']*len(file_rows)\n \n for index, value in zip(label_col[0], label_col[1]):\n dense_label_col[index] = value\n\n file_cols[file_headers.index(target)] = (tuple(range(len(file_rows))), tuple(dense_label_col))\n\n file_cols = list(Encode(file_encoders).filter(file_cols))\n label_col = file_cols.pop(file_headers.index(target))\n feature_rows = list(Transpose().filter(file_cols))\n\n if is_sparse:\n label_col = label_col[1]\n\n no_missing_values = [ not any(isinstance(val,Number) and isnan(val) for val in row) for row in feature_rows ]\n\n if not any(no_missing_values):\n raise CobaException(f\"Every example in openml {data_id} has a missing value. The simulation is being ignored.\")\n\n feature_rows = list(compress(feature_rows, no_missing_values))\n label_col = list(compress(label_col, no_missing_values)) \n \n return feature_rows, label_col\n\n except KeyboardInterrupt:\n #we don't want to clear the cache in the case of a KeyboardInterrupt\n raise\n \n except CobaException:\n raise\n\n except Exception:\n #if something unexpected went wrong clear the\n #cache just in case it was corrupted somehow\n \n for key in self._cached_urls:\n CobaConfig.Cacher.rmv(key)\n \n raise\n\n def _get_url(self, url:str, checksum:str=None) -> bytes:\n \n if url in CobaConfig.Cacher:\n bites = CobaConfig.Cacher.get(url)\n else:\n\n api_key = CobaConfig.Api_Keys['openml']\n response = HttpSource(url + (f'?api_key={api_key}' if api_key else '')).read()\n\n if response.status_code == 412:\n if 'please provide api key' in response.text:\n message = (\n \"An API Key is needed to access openml's rest API. A key can be obtained by creating an \"\n \"openml account at openml.org. Once a key has been obtained it should be placed within \"\n \"~/.coba as { \\\"api_keys\\\" : { \\\"openml\\\" : \\\"\\\", } }.\")\n raise CobaException(message) from None\n\n if 'authentication failed' in response.text:\n message = (\n \"The API Key you provided no longer seems to be valid. You may need to create a new one\"\n \"longing into your openml account and regenerating a key. After regenerating the new key \"\n \"should be placed in ~/.coba as { \\\"api_keys\\\" : { \\\"openml\\\" : \\\"\\\", } }.\")\n raise CobaException(message) from None\n\n if response.status_code == 404:\n message = (\n \"We're sorry but we were unable to find the requested dataset on openml. The most likely cause \"\n \"for this is openml not providing the requested dataset in a format that COBA can process.\")\n raise CobaException(message) from None\n\n if \"Usually due to high server load\" in response.text:\n message = (\n \"Openml has experienced an error that they believe is the result of high server loads.\"\n \"Openml recommends that you try again in a few seconds. Additionally, if not already \"\n \"done, consider setting up a DiskCache in coba config to reduce the number of openml \"\n \"calls in the future.\")\n raise CobaException(message) from None\n\n if '' == response.text:\n raise CobaException(\"Openml experienced an unexpected error. Please try requesting the data again.\") from None\n\n bites = response.content\n\n if url not in CobaConfig.Cacher:\n self._cached_urls.append(url)\n CobaConfig.Cacher.put(url,bites)\n\n if checksum is not None and md5(bites).hexdigest() != checksum:\n \n #if the cache has become corrupted we need to clear it\n CobaConfig.Cacher.rmv(url)\n\n message = (\n f\"The response from {url} did not match the given checksum {checksum}. This could be the result \"\n \"of network errors or the file becoming corrupted. Please consider downloading the file again. \"\n \"If the error persists you may want to manually download and reference the file.\")\n raise CobaException(message) from None\n\n return bites.decode('utf-8')\n\n def _get_dataset_description(self, data_id:int) -> Dict[str,Any]:\n\n description_txt = self._get_url(f'https://www.openml.org/api/v1/json/data/{data_id}')\n description_obj = json.loads(description_txt)[\"data_set_description\"]\n\n return description_obj\n\n def _get_feature_descriptions(self, data_id:int) -> Sequence[Dict[str,Any]]:\n \n types_txt = self._get_url(f'https://www.openml.org/api/v1/json/data/features/{data_id}')\n types_obj = json.loads(types_txt)[\"data_features\"][\"feature\"]\n\n return types_obj\n\n def _get_dataset_rows(self, file_id:str, target:str, md5_checksum:str) -> Any:\n from coba.pipes import ArffReader, CsvReader, Encode, Transpose\n \n csv_url = f\"http://www.openml.org/data/v1/get_csv/{file_id}\"\n arff_url = f\"http://www.openml.org/data/v1/download/{file_id}\"\n\n if arff_url in CobaConfig.Cacher:\n text = self._get_url(arff_url, md5_checksum)\n return list(ArffReader(skip_encoding=[target]).filter(text.splitlines()))\n\n try:\n text = self._get_url(csv_url, md5_checksum)\n return list(CsvReader().filter(text.splitlines()))\n \n except:\n text = self._get_url(arff_url, md5_checksum)\n return list(ArffReader(skip_encoding=[target]).filter(text.splitlines()))\n\n def _get_target_for_problem_type(self, data_id:int):\n\n text = self._get_url(f'https://www.openml.org/api/v1/json/task/list/data_id/{data_id}')\n tasks = json.loads(text).get(\"tasks\",{}).get(\"task\",[])\n\n task_type = 1 if self._problem_type == \"classification\" else 2\n\n for task in tasks:\n if task[\"task_type_id\"] == task_type: #aka, classification task\n for input in task['input']:\n if input['name'] == 'target_feature':\n return input['value'] #just take the first one\n\n raise CobaException(f\"Openml {data_id} does not appear to be a {self._problem_type} dataset\")\n\nclass OpenmlSimulation(Simulation):\n \"\"\"A simulation created from openml data with features and labels.\n\n OpenmlSimulation turns labeled observations from a classification data set,\n into interactions. For each interaction the feature set becomes the context and \n all possible labels become the actions. Rewards for each interaction are created by \n assigning a reward of 1 for taking the correct action (i.e., choosing the correct\n label) and a reward of 0 for taking any other action (i.e., choosing any of the\n incorrect lables).\n \"\"\"\n\n def __init__(self, id: int, simulation_type:str = \"classification\", nominal_as_str:bool = False, md5_checksum: str = None) -> None:\n self._source = OpenmlSource(id, simulation_type, nominal_as_str, md5_checksum)\n self._interactions: Optional[Sequence[Interaction]] = None\n\n def read(self) -> Iterable[Interaction]:\n \"\"\"Read the interactions in this simulation.\"\"\"\n\n features,labels = self._source.read()\n\n if isinstance(labels[0],Number):\n return RegressionSimulation(features,labels).read()\n else:\n return ClassificationSimulation(features,labels).read()\n \n\n def __repr__(self) -> str:\n return f'{{\"OpenmlSimulation\":{self._source._data_id}}}'\n", "sub_path": "coba/simulations/openml.py", "file_name": "openml.py", "file_ext": "py", "file_size_in_byte": 12391, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "coba.pipes.Source", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 14, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 14, "usage_type": "name"}, {"api_name": "coba.simulations.core.Context", "line_number": 14, "usage_type": "name"}, {"api_name": "coba.simulations.core.Action", "line_number": 14, "usage_type": "name"}, {"api_name": "coba.config.CobaException", "line_number": 42, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 46, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 47, "usage_type": "name"}, {"api_name": "coba.encodings.Encoder", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 48, "usage_type": "name"}, {"api_name": "coba.encodings.NumericEncoder", "line_number": 60, "usage_type": "call"}, {"api_name": "coba.encodings.StringEncoder", "line_number": 63, "usage_type": "call"}, {"api_name": "coba.encodings.OneHotEncoder", "line_number": 65, "usage_type": "call"}, {"api_name": "coba.encodings.StringEncoder", "line_number": 68, "usage_type": "call"}, {"api_name": "coba.encodings.NumericEncoder", "line_number": 72, "usage_type": "name"}, {"api_name": "coba.encodings.OneHotEncoder", "line_number": 72, "usage_type": "name"}, {"api_name": "coba.encodings.StringEncoder", "line_number": 72, "usage_type": "name"}, {"api_name": "coba.encodings.StringEncoder", "line_number": 79, "usage_type": "call"}, {"api_name": "coba.encodings.OneHotEncoder", "line_number": 79, "usage_type": "call"}, {"api_name": "coba.pipes.Transpose", "line_number": 90, "usage_type": "call"}, {"api_name": "itertools.compress", "line_number": 92, "usage_type": "call"}, {"api_name": "coba.pipes.Encode", "line_number": 109, "usage_type": "call"}, {"api_name": "coba.pipes.Transpose", "line_number": 111, "usage_type": "call"}, {"api_name": "numbers.Number", "line_number": 116, "usage_type": "argument"}, {"api_name": "math.isnan", "line_number": 116, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 119, "usage_type": "call"}, {"api_name": "itertools.compress", "line_number": 121, "usage_type": "call"}, {"api_name": "itertools.compress", "line_number": 122, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 130, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Cacher.rmv", "line_number": 138, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 138, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 138, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 29, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 29, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 144, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 144, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Cacher.get", "line_number": 145, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 145, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 145, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Api_Keys", "line_number": 148, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 148, "usage_type": "name"}, {"api_name": "coba.pipes.HttpSource", "line_number": 149, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 157, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 164, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 170, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 178, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 181, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 185, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 185, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Cacher.put", "line_number": 187, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 187, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 187, "usage_type": "name"}, {"api_name": "hashlib.md5", "line_number": 189, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher.rmv", "line_number": 192, "usage_type": "call"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 192, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 192, "usage_type": "name"}, {"api_name": "coba.config.CobaException", "line_number": 198, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 205, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 202, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 202, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 212, "usage_type": "call"}, {"api_name": "typing.Sequence", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 209, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 209, "usage_type": "name"}, {"api_name": "coba.config.CobaConfig.Cacher", "line_number": 222, "usage_type": "attribute"}, {"api_name": "coba.config.CobaConfig", "line_number": 222, "usage_type": "name"}, {"api_name": "coba.pipes.ArffReader", "line_number": 224, "usage_type": "call"}, {"api_name": "coba.pipes.CsvReader", "line_number": 228, "usage_type": "call"}, {"api_name": "coba.pipes.ArffReader", "line_number": 232, "usage_type": "call"}, {"api_name": "typing.Any", "line_number": 216, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 237, "usage_type": "call"}, {"api_name": "coba.config.CobaException", "line_number": 247, "usage_type": "call"}, {"api_name": "coba.simulations.core.Simulation", "line_number": 249, "usage_type": "name"}, {"api_name": "{'Encoder': 'coba.encodings.Encoder', 'NumericEncoder': 'coba.encodings.NumericEncoder', 'OneHotEncoder': 'coba.encodings.OneHotEncoder', 'StringEncoder': 'coba.encodings.StringEncoder', 'Encode': 'coba.pipes.Encode', 'Transpose': 'coba.pipes.Transpose', 'ArffReader': 'coba.pipes.ArffReader', 'CsvReader': 'coba.pipes.CsvReader'}", "line_number": 261, "usage_type": "call"}, {"api_name": "typing.Optional", "line_number": 262, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 262, "usage_type": "name"}, {"api_name": "coba.simulations.core.Interaction", "line_number": 262, "usage_type": "name"}, {"api_name": "numbers.Number", "line_number": 269, "usage_type": "argument"}, {"api_name": "coba.simulations.core.RegressionSimulation", "line_number": 270, "usage_type": "call"}, {"api_name": "coba.simulations.core.ClassificationSimulation", "line_number": 272, "usage_type": "call"}, {"api_name": "typing.Iterable", "line_number": 264, "usage_type": "name"}, {"api_name": "coba.simulations.core.Interaction", "line_number": 264, "usage_type": "name"}]}
+{"seq_id": "398685755", "text": "import re\nimport time\nimport requests\nfrom lxml import etree\nfrom kuaishou.analyze_num import Analy\n\nanaly = Analy()\n\nfor i in range(157494640, 157494660):\n time.sleep(1)\n keyword = str(i)\n\n url = 'https://live.kuaishou.com/search/?keyword=%s' % (keyword)\n\n headers = {\n \"Host\": \"live.kuaishou.com\",\n \"Connection\": \"keep-alive\",\n \"Cache-Control\": \"max-age=0\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Referer\": \"https://live.kuaishou.com/search/?keyword=%E4%B8%B9%E4%B8%B9\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Cookie\": \"did=web_89670e2b3c892184a0452f79ea15f9b4; didv=1557212874570; clientid=3; client_key=65890b29; needLoginToWatchHD=1; Hm_lvt_86a27b7db2c5c0ae37fee4a8a35033ee=1557212874,1557283015; __lfcc=1; kuaishou.live.bfb1s=ac5f27b3b62895859c4c1622f49856a4\"\n }\n\n res = requests.get(url=url, headers=headers)\n # print(res.text)\n\n con1 = re.findall(r'相关用户', res.text)\n\n if con1:\n con = etree.HTML(res.text)\n\n user_name = con.xpath('//div[@class=\"profile-card-user-info-detail\"]//h4//text()')[0].strip()\n print(user_name)\n\n fan = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[0].replace('粉丝', '')\n fans = analy.parsingChar(fan)\n print('fans', fans)\n\n follow = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[1].replace('关注', '')\n follows = analy.parsingChar(follow)\n print('follows', follows)\n\n photo = con.xpath('//p[@class=\"profile-card-user-info-counts\"]/text()')[0].split()[2].replace('作品', '')\n photos = analy.parsingChar(photo)\n print('photos', photos)\n\n profile = con.xpath('//div[@class=\"profile-card-user-info-detail\"]//h4/a/@href')[0].replace(r'/profile/', '')\n print('profile', profile)\n print('*' * 30)\n else:\n print(keyword)\n print('ID 为空号...')", "sub_path": "ergodic_all_to_get_id.py", "file_name": "ergodic_all_to_get_id.py", "file_ext": "py", "file_size_in_byte": 2232, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "kuaishou.analyze_num.Analy", "line_number": 7, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 28, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 31, "usage_type": "call"}, {"api_name": "lxml.etree.HTML", "line_number": 34, "usage_type": "call"}, {"api_name": "lxml.etree", "line_number": 34, "usage_type": "name"}]}
+{"seq_id": "366460429", "text": "#! /home/kazushi/anaconda3/bin/python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nfrom mpl_toolkits.axes_grid1.colorbar import colorbar\n\nclass BNDL:\n def load(self,fname):\n fp=open(fname,\"r\")\n fp.readline()\n dat=fp.readline()\n Xa=list(map(float,dat.strip().split(\",\")))\n print(\"Xa=\",Xa)\n\n fp.readline()\n dat=fp.readline()\n dx=list(map(float,dat.strip().split(\",\")))\n print(\"dx=\",dx)\n\n fp.readline()\n dat=fp.readline()\n Nd=list(map(int,dat.strip().split(\",\")))\n print(\"Nd=\",Nd)\n\n fp.readline()\n dat=fp.readline()\n dat=list(map(float,dat.strip().split(\",\")))\n f1=dat[0]\n df=dat[1]\n Nf=int(dat[2])\n print(\"f1,df,Nf=\",f1,df,Nf)\n #Nf=int(Nf/2)\n\n fp.readline()\n amp=[]\n for row in fp:\n dat=row.strip().split(\",\")\n z=float(dat[0])+1j*float(dat[1])\n amp.append(z)\n amp=np.array(amp)\n Nx=Nd[0]\n Ny=Nd[1]\n #amp=amp.astype(np.float)\n print(np.size(amp))\n print(Nx*Ny*Nf)\n amp=np.reshape(amp,[Nx,Ny,Nf])\n print(np.shape(amp))\n self.amp=amp\n self.Nx=Nx\n self.Ny=Ny\n self.Nf=Nf\n self.dky=1/dx[1]/Ny;\n self.ky=np.arange(Ny)*self.dky\n self.freq=np.arange(Nf)*df+f1;\n self.df=df;\n self.Xa=Xa\n self.dx=dx\n self.xcod=np.arange(Nx)*dx[0]+Xa[0]\n self.ycod=np.arange(Ny)*dx[1]+Xa[1]\n fp.close()\n def get_index(self,val,axis):\n if axis==0:\n indx=np.argmin(np.abs(self.xcod-val))\n if axis==1:\n indx=np.argmin(np.abs(self.ycod-val))\n if axis==2:\n indx=np.argmin(np.abs(self.freq-val))\n return(indx)\n def get_cod(self,indx,axis):\n cod=0.0;\n if axis==0:\n indx=indx%self.Nx;\n cod=self.xcod[indx]\n if axis==1:\n indx=indx%self.Ny;\n cod=self.ycod[indx]\n if axis==2:\n indx=indx%self.Nf;\n cod=self.freq[indx]\n return(cod)\n def get_domain(self,axis):\n x=-self.xcod\n y=-self.ycod\n f= self.freq\n if axis==0:\n ext=[f[0],f[-1],y[0],y[-1]]\n if axis==1:\n ext=[f[0],f[-1],y[0],y[-1]]\n if axis==2:\n ext=[y[0],y[-1],x[0],x[-1]]\n return(ext)\n def stack(self,ax):\n S=np.mean(self.amp,axis=ax)\n return(S)\n\n\n\nif __name__==\"__main__\":\n\n dir_name=\"./Scopes\"\n\n fname=\"scopes_win.fft\"\n fname=dir_name+\"/\"+fname\n bndl=BNDL()\n bndl.load(fname)\n\n ext=bndl.get_domain(2);\n\n fsz=12\n fig1=plt.figure(figsize=(6,6.5))\n\n fs=[0.6, 0.7, 0.8, 1.0]\n mV=1.e03\n hd=[\"(a) \",\"(b) \",\"(c) \",\"(d) \"];\n ax=[];\n # Snapshots\n for k in range(4):\n ax.append(fig1.add_subplot(2,2,k+1))\n ax[k].tick_params(labelsize=fsz)\n axdiv=make_axes_locatable(ax[k])\n cax=axdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n indx=bndl.get_index(fs[k],2);\n ff=bndl.get_cod(indx,2);\n Phi=np.angle(bndl.amp[:,:,indx]);\n ima=ax[k].imshow(Phi,cmap=\"jet\",interpolation=\"none\",extent=ext,vmin=-np.pi,vmax=np.pi,aspect=\"equal\")\n cba=colorbar(ima,cax=cax)\n\n txtf=\"f=\"+str(fs[k])+\"[MHz]\"\n ax[k].set_title(hd[k]+txtf,loc=\"center\")\n\n ax[2].set_xlabel(\"x [mm]\",fontsize=12)\n ax[3].set_xlabel(\"x [mm]\",fontsize=12)\n ax[0].set_ylabel(\"y [mm]\",fontsize=12)\n ax[2].set_ylabel(\"y [mm]\",fontsize=12)\n\n\n fig2=plt.figure(figsize=(6,3.5))\n fig3=plt.figure(figsize=(6,3.5))\n bx=[]\n bx.append(fig2.add_subplot(111))\n bx.append(fig3.add_subplot(111))\n\n\n # Mean B-scan\n S=bndl.stack(0)\n ext2=bndl.get_domain(0)\n imb0=bx[0].imshow(np.abs(S*mV),extent=ext2,interpolation=\"bilinear\",aspect=\"auto\",cmap=\"jet\",origin=\"lower\")\n bxdiv=make_axes_locatable(bx[0])\n cbx=bxdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n cb0=colorbar(imb0,cax=cbx)\n\n # B-scan at xcod \n xcod=0\n indx=bndl.get_index(xcod,0);\n xcod=bndl.get_cod(indx,0)\n imb1=bx[1].imshow(np.abs(bndl.amp[indx,:,:]*mV),extent=ext2,interpolation=\"bilinear\",aspect=\"auto\",cmap=\"jet\",origin=\"lower\")\n bxdiv=make_axes_locatable(bx[1])\n cbx=bxdiv.append_axes(\"right\",size=\"7%\",pad=\"2%\")\n cb0=colorbar(imb1,cax=cbx)\n\n for k in range(2):\n bx[k].tick_params(labelsize=fsz)\n bx[k].set_xlim([0,2.5])\n bx[k].set_xlabel(\"freq [MHz]\",fontsize=fsz);\n bx[k].set_ylabel(\"x [mm]\",fontsize=fsz);\n plt.show()\n fig1.savefig(\"fsnap.png\",bbox_inches=\"tight\")\n fig2.savefig(\"spctrg_mean.png\",bbox_inches=\"tight\")\n fig2.savefig(\"spctrg.png\",bbox_inches=\"tight\")\n\n", "sub_path": "Alminium2MHz/wavef.py", "file_name": "wavef.py", "file_ext": "py", "file_size_in_byte": 4800, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.array", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.size", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 110, "usage_type": "name"}, {"api_name": "mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.angle", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 125, "usage_type": "attribute"}, {"api_name": "mpl_toolkits.axes_grid1.colorbar.colorbar", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "numpy.abs", "line_number": 147, "usage_type": "call"}, {"api_name": "mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable", "line_number": 148, "usage_type": "call"}, {"api_name": "mpl_toolkits.axes_grid1.colorbar.colorbar", "line_number": 150, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 156, "usage_type": "call"}, {"api_name": "mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable", "line_number": 157, "usage_type": "call"}, {"api_name": "mpl_toolkits.axes_grid1.colorbar.colorbar", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 166, "usage_type": "name"}]}
+{"seq_id": "597626221", "text": "import argparse\nimport basf2_mva\n\n# +\ndef get_variables():\n \n my_var=[ 'Btag_d1_R2', 'Btag_d1_thrustBm', 'Btag_d1_thrustOm',\n 'Btag_d1_cosTBTO' ,'Btag_d1_cosTBz', 'Btag_d1_KSFWVariables_hso00',\n 'Btag_d1_KSFWVariables_hso01' ,'Btag_d1_KSFWVariables_hso02',\n 'Btag_d1_KSFWVariables_hso03', 'Btag_d1_KSFWVariables_hso04',\n 'Btag_d1_KSFWVariables_hso10', 'Btag_d1_KSFWVariables_hso12',\n 'Btag_d1_KSFWVariables_hso14' ,'Btag_d1_KSFWVariables_hso20',\n 'Btag_d1_KSFWVariables_hso22', 'Btag_d1_KSFWVariables_hso24',\n 'Btag_d1_KSFWVariables_hoo0', 'Btag_d1_KSFWVariables_hoo1',\n 'Btag_d1_KSFWVariables_hoo2' ,'Btag_d1_KSFWVariables_hoo3',\n 'Btag_d1_KSFWVariables_hoo4',\n 'Btag_d1_px', 'Btag_d1_py', 'Btag_d1_pz', 'Btag_d1_pt'\n ]\n#'Btag_d1_px' 'Btag_d1_py' 'Btag_d1_pz' 'Btag_d1_pt'\n \n# 'Btag_d1_R2', 'Btag_d1_thrustOm',\n# 'Btag_d1_cosTBTO', 'Btag_d1_cosTBz' ,'Btag_d1_KSFWVariables_hso00',\n# 'Btag_d1_KSFWVariables_hso01', 'Btag_d1_KSFWVariables_hso02',\n# 'Btag_d1_KSFWVariables_hso03', 'Btag_d1_KSFWVariables_hso04',\n# 'Btag_d1_KSFWVariables_hso10', 'Btag_d1_KSFWVariables_hso12',\n# 'Btag_d1_KSFWVariables_hso14', 'Btag_d1_KSFWVariables_hso20',\n# 'Btag_d1_KSFWVariables_hso22', 'Btag_d1_KSFWVariables_hso24',\n# 'Btag_d1_KSFWVariables_hoo0', 'Btag_d1_KSFWVariables_hoo1',\n# 'Btag_d1_KSFWVariables_hoo2', 'Btag_d1_KSFWVariables_hoo3',\n# 'Btag_d1_KSFWVariables_hoo4' \n \n#'Bsig_d0_R2' , 'Bsig_d0_thrustOm', 'Bsig_d0_cosTBTO',\n# 'Bsig_d0_cosTBz', 'Bsig_d0_KSFWVariables_hso00',\n# 'Bsig_d0_KSFWVariables_hso01' ,'Bsig_d0_KSFWVariables_hso02',\n# 'Bsig_d0_KSFWVariables_hso03', 'Bsig_d0_KSFWVariables_hso04',\n# 'Bsig_d0_KSFWVariables_hso10', 'Bsig_d0_KSFWVariables_hso12',\n# 'Bsig_d0_KSFWVariables_hso14', 'Bsig_d0_KSFWVariables_hso20',\n# 'Bsig_d0_KSFWVariables_hso22', 'Bsig_d0_KSFWVariables_hso24',\n# 'Bsig_d0_KSFWVariables_hoo0', 'Bsig_d0_KSFWVariables_hoo1',\n# 'Bsig_d0_KSFWVariables_hoo2', 'Bsig_d0_KSFWVariables_hoo3',\n# 'Bsig_d0_KSFWVariables_hoo4'\n\n\n #ksfw_variables = [f'KSFWVariables{arg}' for arg in ksfw_args]\n #cleo_cones = [f'CleoConeCS{i}' for i in range(1,10)]\n # cs_variables = ['cosThetaCMS','foxWolframR1','foxWolframR2','foxWolframR3','foxWolframR4', \n # 'sphericity', 'aplanarity', 'thrust', 'thrustAxisCosTheta', 'cosTBTO', 'cosTBz' ]\n # cs_variables += cleo_cones\n # veto_variables = ['mu_0_isFromJpsiMu','mu_1_isFromJpsiMu', 'mu_0_isInD', 'mu_1_isInD', 'isFromJpsiMuRad']\n # kin_variables = ['pCMS', 'mu_0_pCMS', 'mu_1_pCMS','pCMSDaughterSum','pCMSDaughterDiff']\n # lt_variables = ['extraInfoMuPCMS', 'extraInfoEPCMS', 'extraInfoMuCosTheta', 'extraInfoECosTheta']\n #dt_variables = ['DeltaT', 'DeltaTErr']\n #train_variables = ['cosAngleBetweenMomentumAndVertexVectorInXYPlane',\n # 'cosAngleBetweenMomentumAndVertexVector', 'cosToThrustOfEvent',\n # 'missingMass2OfEvent', 'cosThetaBetweenParticleAndNominalB', 'chiProb']\n # train_variables += cs_variables\n #train_variables += m\n # train_variables += kin_variables\n #train_variables += veto_variables\n #train_variables += dt_variables\n \n return my_var\n\n\n# -\n\ndef get_specific_settings(model: str):\n sp = None\n if model == 'fisher':\n sp = basf2_mva.TMVAOptionsClassification()\n sp.m_method = \"Fisher\"\n sp.m_type = \"Fisher\"\n sp.m_config = (\"H:V:CreateMVAPdfs:VarTransform=N:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10\")\n sp.transform2probability = False;\n elif model == 'svm':\n sp = basf2_mva.TMVAOptionsClassification()\n sp.m_method = \"SVM\"\n sp.m_type = \"SVM\"\n sp.m_config = (\"H:V:VarTransform=N\")\n sp.transform2probability = False;\n elif model == 'fbdt':\n sp = basf2_mva.FastBDTOptions() # here we use the FastBDT method\n sp.m_nTrees = 200 # number of trees in the FastBDT forest(200)\n sp.m_nLevels = 3 # depth of the trees(3)\n sp.m_shrinkage = 0.1 # shrinkage during boosting(0.1)\n sp.m_nCuts = 4 # number of cuts for each tree(4)\n sp.transform2probability = False;\n else:\n raise Exception(f'Model {model} is not supported!')\n return sp\n\ndef train(trainData: list, testData: list, model: str, \n tm_variable: str, output_weights_name: str, tree: str='my_ttree'):\n # Global/General options\n go = basf2_mva.GeneralOptions()\n go.m_datafiles = basf2_mva.vector(*trainData) # training sample\n go.m_treename = tree # ntuple tree name\n go.m_identifier = output_weights_name # name of the file with the trianing info\n train_variables = get_variables()\n go.m_variables = basf2_mva.vector(*train_variables) # input variables\n go.m_target_variable = tm_variable # target for training\n go.m_weight_variable = \"\"\n sp = get_specific_settings(model)\n basf2_mva.teacher(go,sp)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Script to split train test\")\n parser.add_argument('--train', nargs='+', help=\"Input MC file names for train\")\n parser.add_argument('--test', nargs='+', help=\"Input MC file names for test\")\n parser.add_argument('-tm', '--tm_variable', type=str, \n default = 'Btag_d1_isSignal', help=\"TM variable, 'Btag_d1_isSignal'\")\n parser.add_argument('-tag','--tag_name', type=str, default='mva', help=\"Tag name for output files\")\n parser.add_argument('-t','--tree', type=str, default='my_ttree', help=\"Tree to use\")\n parser.add_argument('-m', '--model', type=str, default='fbdt', \n choices=['fisher', 'fbdt', 'svm'], help=\"Model to use\")\n args = parser.parse_args()\n\n output_weights_name = f'./{args.model}_{args.tag_name}.xml'\n\n train(args.train, args.test, args.model, tm_variable=args.tm_variable, \n output_weights_name=output_weights_name)\n\n #Btag_d1_isSignal\n \n \n #outputPdf = f'evaluation-{xmlname}.tex'\n #os.system('$BELLE2_RELEASE_DIR/mva/tools/basf2_mva_evaluate.py -w notebooks/tmp/ '+\n # f'-id {go.m_identifier} MyTMVAfbdt.xml -tree {go.m_treename} -train {trainData[0]} -data {testData[0]} -out {outputPdf}')\n #os.system('~/code/4leptons/notebooks/tmp/; pdflatex latex.tex; cd ../../')\n", "sub_path": "Machine Learning/trainMVA.py", "file_name": "trainMVA.py", "file_ext": "py", "file_size_in_byte": 6205, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "basf2_mva.TMVAOptionsClassification", "line_number": 70, "usage_type": "call"}, {"api_name": "basf2_mva.TMVAOptionsClassification", "line_number": 76, "usage_type": "call"}, {"api_name": "basf2_mva.FastBDTOptions", "line_number": 82, "usage_type": "call"}, {"api_name": "basf2_mva.GeneralOptions", "line_number": 95, "usage_type": "call"}, {"api_name": "basf2_mva.vector", "line_number": 96, "usage_type": "call"}, {"api_name": "basf2_mva.vector", "line_number": 100, "usage_type": "call"}, {"api_name": "basf2_mva.teacher", "line_number": 104, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 108, "usage_type": "call"}]}
+{"seq_id": "423548000", "text": "##### Writer : \"Atia\"\n\n\n###### Importign the Library\nimport os\nimport pandas as pd\nimport numpy as np\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 20)\nimport matplotlib.pyplot as plt\n\nos.chdir(\"/Users/macbook/Documents/pyhton/portfolio/Two_Line_Diagram\")\n\n#### reading the reference list\npath = \"renamed.xlsx\"\ndd = pd.read_excel(path)\nd = dd[[\"city\", \"source\", \"tag\", \"new_tag\"]]\n\n#### Find all the unique values in new_tag_dimension\ndimensions = d.new_tag.unique()\n\n\ndef lineplot (dim):\n d[\"binary\"] = np.where(d[\"new_tag\"] == dim, d[\"tag\"], \"other_tags\")\n df = d[[\"source\", \"binary\"]]\n tab = pd.pivot_table(df, index=\"source\", columns=\"binary\", aggfunc=len)\n tab = tab.fillna(0)\n\n tab[\"sum\"] = tab.sum(axis=1)\n\n #####make a copy for normalizaiton\n tab_Nor = tab.copy()\n tab = tab.drop(['other_tags', \"sum\"], axis=1)\n tab[\"sum\"] = round(tab.sum(axis=1), 2)\n tab = tab.fillna(0)\n\n list = tab_Nor.columns.to_list()\n for i in range(len(tab_Nor)):\n for j in range(len(list) - 1):\n tab_Nor.iloc[i, j] = round(((tab_Nor.iloc[i, j] / tab_Nor.iloc[i, -1]) * 100), 2)\n\n tab_Nor = tab_Nor.drop([\"sum\", 'other_tags'], axis=1)\n tab_Nor[\"sum\"] = round(tab_Nor.sum(axis=1), 2)\n tab_Nor = tab_Nor.fillna(0)\n tab_Nor = tab_Nor.drop([\"sum\"], axis=1)\n tab_Nor= tab_Nor.transpose()\n\n\n #############################################\n ###### with respect to internal percentages\n\n da = d[d[\"new_tag\"] == dim]\n da = da[[\"source\", \"tag\"]]\n tab2 = pd.pivot_table(da, index=\"source\", columns=\"tag\", aggfunc=len)\n tab2 = tab2.fillna(0)\n\n tab2[\"sum\"] = tab2.sum(axis=1)\n list2 = tab2.columns.to_list()\n\n for i in range(len(tab2)):\n for j in range(len(list2) - 1):\n tab2.iloc[i, j] = (round(((tab2.iloc[i, j] / tab2.iloc[i, -1]) * 100), 2))\n\n tab2 = tab2.drop([\"sum\"], axis=1)\n tab2_n= tab2.transpose()\n\n\n\n\n index_list = tab_Nor.index.values.tolist()\n\n # # Plotting the bars\n plt.rcParams['font.family'] = \"sans-serif\"\n\n fig, axs = plt.subplots(2, figsize=(12,16))\n\n\n\n # Create a bar with first data,\n\n\n\n axs[0].plot(tab_Nor ['Official Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#3ca3bf',\n\n # with label the first value in first_name\n label= 'Official Websites',\n linewidth=2.0)\n\n\n axs[0].plot(tab_Nor['Personal Blogs'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#f68b37',\n\n # with label the first value in first_name\n label='Personal Blogs',\n linewidth=2.0\n )\n\n # Create a bar with second data,\n axs[0].plot(tab_Nor['Third Party Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#735698',\n\n # with label the first value in first_name\n label='Third Party Websites',\n linewidth=2.0\n )\n\n\n axs[0].set_xticklabels(index_list, rotation=45, fontsize=10, ha='right')\n\n axs[0].set_ylabel('Image Frequency', fontsize=10, labelpad=10)\n axs[0].set_title('The Frequency of %s Attributes Compared to All Data ' %dim, fontsize=12, pad=20,\n fontname='Times New Roman')\n axs[0].set_xlabel('Image Attributes', fontsize=10, labelpad=10)\n axs[0].xaxis.grid()\n\n\n ##### Ajusting the legend\n axs[0].legend(['Official Websites', 'Personal Blogs', 'Third Party Websites'])\n axs[0].legend(prop={\"size\": 4}, borderpad=.5, labelspacing=1.5)\n\n axs[0].legend(loc='upper left', bbox_to_anchor=(0.01, .99), ncol=3,\n borderaxespad=.2, prop={\"size\": 4})\n\n\n ########################\n ########################\n # Create the second image\n axs[1].plot(tab2_n['Official Websites'],\n\n alpha=0.8,\n # with color\n color='#3ca3bf',\n\n # with label the first value in first_name\n label= 'Official Websites',\n linewidth=2.0\n )\n\n axs[1].plot(tab2_n['Personal Blogs'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#f68b37',\n\n # with label the first value in first_name\n label='Personal Blogs',\n linewidth=2.0\n )\n\n # Create a bar with second data,\n axs[1].plot(tab2_n['Third Party Websites'],\n\n # with alpha 0.5\n alpha=0.8,\n # with color\n color='#735698',\n\n # with label the first value in first_name\n label='Third Party Websites',\n linewidth=2.0\n )\n\n axs[1].set_xticklabels(index_list, rotation=45, fontsize=9, ha='right')\n\n axs[1].set_ylabel('Image Frequency', fontsize=12, labelpad=10)\n axs[1].set_title('The Frequency of %s Attributes Compared to Each other' %dim, fontsize=11, pad=20,\n fontname='Times New Roman')\n axs[1].set_xlabel('Image Attributes', fontsize=12, labelpad=10)\n axs[1].xaxis.grid()\n\n\n ##### Ajusting the legend\n axs[1].legend(['Official Websites', 'Personal Blogs', 'Third Party Websites'])\n axs[1].legend(prop={\"size\": 10}, borderpad=.5, labelspacing=1.5)\n\n axs[1].legend(loc='upper left', bbox_to_anchor=(0.01, .99), ncol=3,\n borderaxespad=.2, prop={\"size\": 10})\n ######## arrancing the xticks\n plt.subplots_adjust( wspace=0.3, hspace=.6,bottom=.15 )\n\n\n ##### saving the files\n file = ('%s Line plot.png' % dim)\n path = \"pictures\"\n figname = os.path.join(path, file)\n\n if os.path.exists(figname):\n os.remove(figname)\n\n plt.savefig(figname, dpi= 180)\n # plt.show()\n\n\n\nfor i in dimensions:\n lineplot(i)", "sub_path": "Two_Line_Diagram/Two_line_graph.py", "file_name": "Two_line_graph.py", "file_ext": "py", "file_size_in_byte": 5868, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "pandas.set_option", "line_number": 8, "usage_type": "call"}, {"api_name": "pandas.set_option", "line_number": 9, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.read_excel", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 24, "usage_type": "call"}, {"api_name": "pandas.pivot_table", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.pivot_table", "line_number": 54, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 73, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 75, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 75, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 193, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 193, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path", "line_number": 199, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path", "line_number": 201, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 202, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 204, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 204, "usage_type": "name"}]}
+{"seq_id": "429078553", "text": "import os\nfrom options.test_options import TestOptions\nfrom data import CreateDataLoader\nfrom models import create_model\nfrom util.visualizer import save_images\nfrom util import html\n\n\"\"\"\nCopyright (C) 2018 NVIDIA Corporation. All rights reserved.\nLicensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).\n\"\"\"\n#from __future__ import print_function\n#from utils import get_config, get_data_loader_folder, pytorch03_to_pytorch04, load_inception\n#from trainer import MUNIT_Trainer, UNIT_Trainer\nfrom torch import nn\nfrom scipy.stats import entropy\nimport torch.nn.functional as F\n#import argparse\n#from torch.autograd import Variable\n#from data import ImageFolder\nimport numpy as np\n#import torchvision.utils as vutils\ntry:\n from itertools import izip as zip\nexcept ImportError: # will be 3.x series\n pass\nimport sys\nimport torch\nimport os\nfrom torchvision.models.inception import inception_v3\nfrom tqdm import tqdm\nfrom torch.autograd import Variable\nfrom scipy import linalg\n\ndef read_stats_file(filepath):\n \"\"\"read mu, sigma from .npz\"\"\"\n if filepath.endswith('.npz'):\n f = np.load(filepath)\n m, s = f['mu'][:], f['sigma'][:]\n f.close()\n else:\n raise Exception('ERROR! pls pass in correct npz file %s' % filepath)\n return m, s\n\ndef calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):\n \"\"\"Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n Stable version by Dougal J. Sutherland.\n Params:\n -- mu1 : Numpy array containing the activations of a layer of the\n inception net (like returned by the function 'get_predictions')\n for generated samples.\n -- mu2 : The sample mean over activations, precalculated on an\n representative data set.\n -- sigma1: The covariance matrix over activations for generated samples.\n -- sigma2: The covariance matrix over activations, precalculated on an\n representative data set.\n Returns:\n -- : The Frechet Distance.\n \"\"\"\n\n mu1 = np.atleast_1d(mu1)\n mu2 = np.atleast_1d(mu2)\n\n sigma1 = np.atleast_2d(sigma1)\n sigma2 = np.atleast_2d(sigma2)\n\n assert mu1.shape == mu2.shape, \\\n 'Training and test mean vectors have different lengths %s, %s' % (mu1.shape, mu2.shape)\n assert sigma1.shape == sigma2.shape, \\\n 'Training and test covariances have different dimensions %s, %s' % (sigma1.shape, sigma2.shape)\n diff = mu1 - mu2\n # Product might be almost singular\n covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)\n if not np.isfinite(covmean).all():\n msg = ('fid calculation produces singular product; '\n 'adding %s to diagonal of cov estimates') % eps\n print(msg)\n offset = np.eye(sigma1.shape[0]) * eps\n covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))\n # Numerical error might give slight imaginary component\n if np.iscomplexobj(covmean):\n if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):\n m = np.max(np.abs(covmean.imag))\n raise ValueError('Imaginary component {}'.format(m))\n covmean = covmean.real\n tr_covmean = np.trace(covmean)\n return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean\n\nclass ScoreModel:\n def __init__(self, mode, cuda=True,\n stats_file='', mu1=0, sigma1=0):\n \"\"\"\n Computes the inception score of the generated images\n cuda -- whether or not to run on GPU\n mode -- image passed in inceptionV3 is normalized by mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]\n and in range of [-1, 1]\n 1: image passed in is normalized by mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n 2: image passed in is normalized by mean=[0.500, 0.500, 0.500], std=[0.500, 0.500, 0.500]\n \"\"\"\n # load mu, sigma for calc FID\n self.calc_fid = False\n if stats_file:\n self.calc_fid = True\n self.mu1, self.sigma1 = read_stats_file(stats_file)\n elif type(mu1) == type(sigma1) == np.ndarray:\n self.calc_fid = True\n self.mu1, self.sigma1 = mu1, sigma1\n\n # Set up dtype\n if cuda:\n self.dtype = torch.cuda.FloatTensor\n else:\n if torch.cuda.is_available():\n print(\"WARNING: You have a CUDA device, so you should probably set cuda=True\")\n self.dtype = torch.FloatTensor\n\n # setup image normalization mode\n self.mode = mode\n if self.mode == 1:\n transform_input = True\n elif self.mode == 2:\n transform_input = False\n else:\n raise Exception(\"ERR: unknown input img type, pls specify norm method!\")\n self.inception_model = inception_v3(pretrained=True, transform_input=transform_input).type(self.dtype)\n self.inception_model.eval()\n # self.up = nn.Upsample(size=(299, 299), mode='bilinear', align_corners=False).type(self.dtype)\n\n # remove inception_model.fc to get pool3 output 2048 dim vector\n self.fc = self.inception_model.fc\n self.inception_model.fc = nn.Sequential()\n\n # wrap with nn.DataParallel\n self.inception_model = nn.DataParallel(self.inception_model)\n self.fc = nn.DataParallel(self.fc)\n\n def __forward(self, x):\n \"\"\"\n x should be N x 3 x 299 x 299\n and should be in range [-1, 1]\n \"\"\"\n x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)\n x = self.inception_model(x)\n pool3_ft = x.data.cpu().numpy()\n\n x = self.fc(x)\n preds = F.softmax(x, 1).data.cpu().numpy()\n return pool3_ft, preds\n\n @staticmethod\n def __calc_is(preds, n_split, return_each_score=False):\n \"\"\"\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = preds.shape[0]\n # Now compute the mean kl-div\n split_scores = []\n for k in range(n_split):\n part = preds[k * (n_img // n_split): (k + 1) * (n_img // n_split), :]\n py = np.mean(part, axis=0)\n scores = []\n for i in range(part.shape[0]):\n pyx = part[i, :]\n scores.append(entropy(pyx, py))\n split_scores.append(np.exp(np.mean(scores)))\n if n_split == 1 and return_each_score:\n return scores, 0\n return np.mean(split_scores), np.std(split_scores)\n\n @staticmethod\n def __calc_stats(pool3_ft):\n mu = np.mean(pool3_ft, axis=0)\n sigma = np.cov(pool3_ft, rowvar=False)\n return mu, sigma\n\n def get_score_image_tensor(self, imgs_nchw, mu1=0, sigma1=0,\n n_split=10, batch_size=1, return_stats=False,\n return_each_score=False):\n \"\"\"\n param:\n imgs_nchw -- Pytorch Tensor, size=(N,C,H,W), in range of [-1, 1]\n batch_size -- batch size for feeding into Inception v3\n n_splits -- number of splits\n return:\n is_mean, is_std, fid\n mu, sigma of dataset\n\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = imgs_nchw.shape[0]\n\n assert batch_size > 0\n assert n_img > batch_size\n\n pool3_ft = np.zeros((n_img, 2048))\n preds = np.zeros((n_img, 1000))\n for i in tqdm(range(np.int32(np.ceil(1.0 * n_img / batch_size)))):\n batch_size_i = min((i+1) * batch_size, n_img) - i * batch_size\n batchv = Variable(imgs_nchw[i * batch_size:i * batch_size + batch_size_i, ...].type(self.dtype))\n pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv)\n\n # if want to return stats\n # or want to calc fid\n if return_stats or \\\n type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n mu2, sigma2 = self.__calc_stats(pool3_ft)\n\n if self.calc_fid:\n mu1 = self.mu1\n sigma1 = self.sigma1\n\n is_mean, is_std = self.__calc_is(preds, n_split, return_each_score)\n\n fid = -1\n if type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2)\n\n if return_stats:\n return is_mean, is_std, fid, mu2, sigma2\n else:\n return is_mean, is_std, fid\n\n def get_score_dataset(self, dataset, mu1=0, sigma1=0,\n n_split=10, batch_size=32, return_stats=False,\n return_each_score=False):\n \"\"\"\n get score from a dataset\n param:\n dataset -- pytorch dataset, img in range of [-1, 1]\n batch_size -- batch size for feeding into Inception v3\n n_splits -- number of splits\n return:\n is_mean, is_std, fid\n mu, sigma of dataset\n\n regularly, return (is_mean, is_std)\n if n_split==1 and return_each_score==True:\n return (scores, 0)\n # scores is a list with len(scores) = n_img = preds.shape[0]\n \"\"\"\n\n n_img = len(dataset)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)\n\n pool3_ft = np.zeros((n_img, 2048))\n preds = np.zeros((n_img, 1000))\n for i, batch in tqdm(enumerate(dataloader, 0)):\n batch = batch.type(self.dtype)\n batchv = Variable(batch)\n batch_size_i = batch.size()[0]\n pool3_ft[i * batch_size:i * batch_size + batch_size_i], preds[i * batch_size:i * batch_size + batch_size_i] = self.__forward(batchv)\n\n # if want to return stats\n # or want to calc fid\n if return_stats or \\\n type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n mu2, sigma2 = self.__calc_stats(pool3_ft)\n\n if self.calc_fid:\n mu1 = self.mu1\n sigma1 = self.sigma1\n\n is_mean, is_std = self.__calc_is(preds, n_split, return_each_score)\n\n fid = -1\n if type(mu1) == type(sigma1) == np.ndarray or self.calc_fid:\n fid = calculate_frechet_distance(mu1, sigma1, mu2, sigma2)\n\n if return_stats:\n return is_mean, is_std, fid, mu2, sigma2\n else:\n return is_mean, is_std, fid\n\nif __name__ == '__main__':\n opt = TestOptions().parse()\n # hard-code some parameters for test\n opt.num_threads = 1 # test code only supports num_threads = 1\n opt.batch_size = 1 # test code only supports batch_size = 1\n opt.serial_batches = True # no shuffle\n opt.no_flip = True # no flip\n opt.display_id = -1 # no visdom display\n data_loader = CreateDataLoader(opt)\n dataset = data_loader.load_data()\n model = create_model(opt)\n model.setup(opt)\n # create a website\n web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.epoch))\n webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.epoch))\n # test with eval mode. This only affects layers like batchnorm and dropout.\n # pix2pix: we use batchnorm and dropout in the original pix2pix. You can experiment it with and without eval() mode.\n # CycleGAN: It should not affect CycleGAN as CycleGAN uses instancenorm without dropout.\n if opt.eval:\n model.eval()\n\n if opt.compute_fid:\n img_list_tensor1 = []\n img_list_tensor2 = []\n IS = []\n all_preds = []\n # if opt.compute_CIS:\n # CIS = []\n\n\n for i, data in enumerate(dataset):\n if i >= opt.num_test:\n break\n model.set_input(data)\n model.test()\n visuals = model.get_current_visuals()\n img_path = model.get_image_paths()\n # get AtoB\n is_AtoB = model.get_AtoB()\n if i % 5 == 0:\n print('processing (%04d)-th image... %s' % (i, img_path))\n save_images(webpage, visuals, img_path, aspect_ratio=opt.aspect_ratio, width=opt.display_winsize)\n\n # 计算IS和CIS\n # 评估指标Inception Score\n\n # if opt.compute_CIS:\n # cur_preds = [] # clear cur_preds in each loop\n\n\n\n if opt.compute_fid:\n if opt.model=='cycle_gan':\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n img_list_tensor2.append(visuals['fake_A']) if is_AtoB else img_list_tensor2.append(\n visuals['fake_B'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n elif opt.model=='insta_gan' or opt.model=='dense_gan':\n if opt.netG == 'star':\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A_img'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A_img']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B_img'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A_img'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n img_list_tensor2.append(visuals['fake_A_img']) if is_AtoB else img_list_tensor2.append(\n visuals['fake_B_img'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n else:\n is_fid_model = ScoreModel(mode=2, cuda=True)\n\n # img_list_tensor1.append(visuals['real_A_img'])\n # real_A_seg = visuals['real_A_seg']\n # real_A_seg_channel3 = torch.cat([real_A_seg, real_A_seg, real_A_seg], dim=1)\n # img_list_tensor1.append(real_A_seg_channel3)\n\n img_list_tensor1.append(visuals['real_A_img']) if is_AtoB else img_list_tensor1.append(\n visuals['real_B_img'])\n #img_list_tensor1.append(visuals['real_A_img'])\n #img_list_tensor1.append(visuals['real_B_img'])\n # real_B_seg = visuals['real_B_seg']\n # real_B_seg_channel3 = torch.cat([real_B_seg, real_B_seg, real_B_seg], dim=1)\n # img_list_tensor1.append(real_B_seg_channel3)\n\n # img_list_tensor2.append(visuals['fake_A_img'])\n # fake_A_seg = visuals['fake_A_seg']\n # fake_A_seg_channel3 = torch.cat([fake_A_seg, fake_A_seg, fake_A_seg], dim=1)\n # img_list_tensor2.append(fake_A_seg_channel3)\n\n\n img_list_tensor2.append(visuals['fake_A_img']) if is_AtoB else img_list_tensor2.append(visuals['fake_B_img'])\n #img_list_tensor2.append(visuals['fake_A_img'])\n #img_list_tensor2.append(visuals['fake_B_img'])\n # fake_B_seg = visuals['fake_B_seg']\n # fake_B_seg_channel3 = torch.cat([fake_B_seg, fake_B_seg, fake_B_seg], dim=1)\n # img_list_tensor2.append(fake_B_seg_channel3)\n\n\n else:\n pass\n\n\n\n\n\n\n\n img_list_tensor1 = torch.cat(img_list_tensor1, dim=0)\n img_list_tensor2 = torch.cat(img_list_tensor2, dim=0)\n\n if opt.compute_fid:\n print('Calculating 1st stat ...')\n is_mean1, is_std1, _, mu1, sigma1 = \\\n is_fid_model.get_score_image_tensor(img_list_tensor1, n_split=10, return_stats=True)\n\n print('Calculating 2nd stat ...')\n is_mean2, is_std2, fid = is_fid_model.get_score_image_tensor(img_list_tensor2,\n mu1=mu1, sigma1=sigma1,\n n_split=10)\n\n print('1st IS score =', is_mean1, ',', is_std1)\n print('2nd IS score =', is_mean2, ',', is_std2)\n print('FID =', fid)\n\n # save the website\n webpage.save()\n\n", "sub_path": "test_fid.py", "file_name": "test_fid.py", "file_ext": "py", "file_size_in_byte": 18198, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.load", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.atleast_1d", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.atleast_1d", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.atleast_2d", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.atleast_2d", "line_number": 68, "usage_type": "call"}, {"api_name": "scipy.linalg.sqrtm", "line_number": 76, "usage_type": "call"}, {"api_name": "scipy.linalg", "line_number": 76, "usage_type": "name"}, {"api_name": "numpy.isfinite", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 81, "usage_type": "call"}, {"api_name": "scipy.linalg.sqrtm", "line_number": 82, "usage_type": "call"}, {"api_name": "scipy.linalg", "line_number": 82, "usage_type": "name"}, {"api_name": "numpy.iscomplexobj", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.allclose", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.diagonal", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.trace", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.trace", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 108, "usage_type": "attribute"}, {"api_name": "torch.cuda", "line_number": 114, "usage_type": "attribute"}, {"api_name": "torch.cuda.is_available", "line_number": 116, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 116, "usage_type": "attribute"}, {"api_name": "torch.FloatTensor", "line_number": 118, "usage_type": "attribute"}, {"api_name": "torchvision.models.inception.inception_v3", "line_number": 128, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 134, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 134, "usage_type": "name"}, {"api_name": "torch.nn.DataParallel", "line_number": 137, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 137, "usage_type": "name"}, {"api_name": "torch.nn.DataParallel", "line_number": 138, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 138, "usage_type": "name"}, {"api_name": "torch.nn.functional.interpolate", "line_number": 145, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 145, "usage_type": "name"}, {"api_name": "torch.nn.functional.softmax", "line_number": 150, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 150, "usage_type": "name"}, {"api_name": "numpy.mean", "line_number": 167, "usage_type": "call"}, {"api_name": "scipy.stats.entropy", "line_number": 171, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.std", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 180, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 206, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 207, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.int32", "line_number": 208, "usage_type": "call"}, {"api_name": "numpy.ceil", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 210, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 216, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 226, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 254, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 254, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 256, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 257, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 258, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 267, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 277, "usage_type": "attribute"}, {"api_name": "options.test_options.TestOptions", "line_number": 286, "usage_type": "call"}, {"api_name": "data.CreateDataLoader", "line_number": 293, "usage_type": "call"}, {"api_name": "models.create_model", "line_number": 295, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 298, "usage_type": "call"}, {"api_name": "os.path", "line_number": 298, "usage_type": "attribute"}, {"api_name": "util.html.HTML", "line_number": 299, "usage_type": "call"}, {"api_name": "util.html", "line_number": 299, "usage_type": "name"}, {"api_name": "util.visualizer.save_images", "line_number": 326, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 425, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 426, "usage_type": "call"}]}
+{"seq_id": "245869075", "text": "\n# model.py file\n\nimport csv\nimport cv2\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\n# Read in recorded data from csv file\nlines = []\nwith open('track12/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n lines.append(line)\n\nlines = lines[1:]\nfrom sklearn.model_selection import train_test_split\nimport sklearn\nfrom sklearn.utils import shuffle\nshuffle(lines)\n# Split recorded into training and validation sets 80:20\ntrain_samples, valid_samples = train_test_split(lines, test_size=0.2)\n\n#Steering correction to apply for image frames from left or right camera perspective\ncorrection = 0.18\n\ndef augmentData(images, measurements):\n aug_images, aug_measurements = [], []\n for image, meas in zip(images, measurements):\n aug_images.append(image)\n aug_images.append(cv2.flip(image,1))\n aug_measurements.append(meas)\n aug_measurements.append(meas*-1.0)\n return (aug_images, aug_measurements)\n\n# Batch generator to generate data during training/validation\ndef generator(samples, batch_size=100):\n num_samples = len(samples)\n while 1: #loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0,num_samples,batch_size):\n end = offset+batch_size\n if (offset+batch_size)>num_samples:\n end = num_samples\n batch_samples = samples[offset:end]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n name = 'track12/IMG/' + batch_sample[0].split('/')[-1]\n center_image = cv2.imread(name)\n center_image = cv2.cvtColor(center_image, cv2.COLOR_BGR2RGB)\n center_angle = float(batch_sample[3])\n\n name = 'track12/IMG/' + batch_sample[1].split('/')[-1]\n left_image = cv2.imread(name)\n left_image = cv2.cvtColor(left_image, cv2.COLOR_BGR2RGB)\n left_angle = center_angle + correction\n\n name = 'track12/IMG/' + batch_sample[2].split('/')[-1]\n right_image = cv2.imread(name)\n right_image = cv2.cvtColor(right_image, cv2.COLOR_BGR2RGB)\n right_angle = center_angle - correction\n\n images.extend([center_image, left_image, right_image])\n angles.extend([center_angle, left_angle, right_angle])\n\n X_train = np.asarray(images)\n y_train = np.asarray(angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\ndef resize(image):\n from keras.backend import tf as ktf\n return ktf.image.resize_images(image, (66,200))\n \nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras import backend as K\nfrom keras.models import Model\nfrom keras.backend import tf as ktf\n\n# Network architecture\nmodel = Sequential()\nmodel.add(Lambda(lambda x: (x/127.5) - 1.0, input_shape=(160,320,3), name='norm'))\n# Crop image to region of interest\nmodel.add(Cropping2D(cropping=((70,20),(0,0))))\nmodel.add(Lambda(resize, name = 'resize'))\nmodel.add(Convolution2D(24,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(36,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(48,5,5,subsample=(2,2),activation=\"relu\"))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\"))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\"))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1))\n\nmodel.compile(loss='mse', optimizer='adam')\n\ndef visualizeOutput(model, layer_name, image):\n layer_model = Model(input=model.input, output=model.get_layer(layer_name).output)\n image = np.expand_dims(image, axis=0)\n layer_output = layer_model.predict(image)\n print('Features shape: ', layer_output.shape)\n #plot\n plt.imshow(layer_output.squeeze())\n plt.show()\n\ntrain_generator = generator(train_samples)\nvalid_generator = generator(valid_samples)\nprint('Num train samples: ', len(train_samples))\n# Run training and validation model\nmodel.fit_generator(train_generator, samples_per_epoch = len(train_samples)*3, validation_data = valid_generator, nb_val_samples=len(valid_samples)*3, nb_epoch=10)\n\nmodel.save('model.h5')\n", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 4513, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "matplotlib.use", "line_number": 8, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 14, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 22, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.flip", "line_number": 33, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 54, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 59, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 63, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.asarray", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 71, "usage_type": "call"}, {"api_name": "sklearn.utils.shuffle", "line_number": 72, "usage_type": "call"}, {"api_name": "sklearn.utils", "line_number": 72, "usage_type": "attribute"}, {"api_name": "keras.backend.tf.image.resize_images", "line_number": 76, "usage_type": "call"}, {"api_name": "keras.backend.tf.image", "line_number": 76, "usage_type": "attribute"}, {"api_name": "keras.backend.tf", "line_number": 76, "usage_type": "name"}, {"api_name": "keras.models.Sequential", "line_number": 87, "usage_type": "call"}, {"api_name": "keras.layers.Lambda", "line_number": 88, "usage_type": "call"}, {"api_name": "keras.layers.Cropping2D", "line_number": 90, "usage_type": "call"}, {"api_name": "keras.layers.Lambda", "line_number": 91, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 92, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 93, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 94, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 95, "usage_type": "call"}, {"api_name": "keras.layers.convolutional.Convolution2D", "line_number": 96, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 97, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 98, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 99, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 100, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 103, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 104, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 110, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}]}
+{"seq_id": "258879723", "text": "\"\"\"\nconvert Pytorch IR, dtype into Tensorflow Op, dtype\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport torch\n\nimport tensorflow as tf\n\nimport numpy as np\n\nfrom .convolution import convolution\nfrom .gemm import gemm\nfrom .normalization import batch_norm\nfrom .math import math_ops\nfrom .activations import activation\nfrom .pool import pool\nfrom .cast import cast\nfrom .dropout import dropout\nfrom .shape import shape_ops\nfrom .recurrent import recurrent\n\n_DTYPE_MAP = {\n # floating point\n torch.float16: tf.float16,\n torch.half: tf.float16,\n torch.float32: tf.float32,\n torch.float: tf.float32,\n torch.double: tf.float64,\n torch.float64: tf.float64,\n # integer\n torch.uint8: tf.uint8,\n torch.int8: tf.int8,\n torch.int16: tf.int16,\n torch.short: tf.int16,\n torch.int32: tf.int32,\n torch.int: tf.int32,\n torch.int64: tf.int64,\n torch.long: tf.int64,\n # boolean\n torch.bool: tf.bool,\n # ScalarType\n # from https://github.com/pytorch/pytorch/blob/master/c10/core/ScalarType.h\n 0: tf.uint8,\n 1: tf.int8,\n 2: tf.int16,\n 3: tf.int32,\n 4: tf.int64,\n 5: tf.float16,\n 6: tf.float32,\n 7: tf.float64,\n 11: tf.bool,\n}\n\ndef dtype_map(dtype):\n if isinstance(dtype, np.dtype):\n return tf.as_dtype(dtype)\n return _DTYPE_MAP[dtype]\n\n_OP_MAP = {\n # prim ops\n \"prim::Constant\": lambda x: x,\n \"prim::NumToTensor\": lambda x: x, # is it realy need to convert to tensor?\n \"prim::ListConstruct\": lambda *x: list(x),\n \"prim::ListUnpack\": lambda x: x,\n \"prim::TupleConstruct\": lambda *x: tuple(x),\n \"prim::TupleUnpack\": lambda x: x,\n # basic math operations\n \"aten::add\": math_ops(\"aten::add\"),\n \"aten::add_\": math_ops(\"aten::add\"),\n \"aten::mul\": math_ops(\"aten::mul\"),\n \"aten::mul_\": math_ops(\"aten::mul\"),\n \"aten::sub\": math_ops(\"aten::sub\"),\n \"aten::div\": math_ops(\"aten::div\"),\n \"aten::floor\": math_ops(\"aten::floor\"),\n \"aten::ceil\": math_ops(\"aten::ceil\"),\n \"aten::log_softmax\": math_ops(\"aten::log_softmax\"),\n \"aten::nll_loss\": math_ops(\"aten::nll_loss\"),\n \"aten::addmm\": gemm(\"aten::addmm\"),\n \"aten::matmul\": gemm(\"aten::matmul\"),\n # activations\n \"aten::relu\": activation(\"aten::relu\"),\n \"aten::relu_\": activation(\"aten::relu\"),\n \"aten::leaky_relu_\": activation(\"aten::leaky_relu_\"),\n \"aten::tanh\": activation(\"aten::tanh\"),\n \"aten::tanh_\": activation(\"aten::tanh\"),\n \"aten::hardtanh_\": activation(\"aten::hardtanh_\"),\n \"aten::sigmoid\": activation(\"aten::sigmoid\"),\n \"aten::sigmoid_\": activation(\"aten::sigmoid\"),\n \"aten::softmax\": activation(\"aten::softmax\"),\n # shape related\n \"aten::view\": shape_ops(\"aten::view\"),\n \"aten::flatten\": shape_ops(\"aten::flatten\"),\n \"aten::size\": shape_ops(\"aten::size\"),\n \"aten::t\": shape_ops(\"aten::t\"),\n \"aten::constant_pad_nd\": shape_ops(\"aten::constant_pad_nd\"),\n \"aten::slice\": shape_ops(\"aten::slice\"),\n \"aten::select\": shape_ops(\"aten::select\"),\n \"aten::chunk\": shape_ops(\"aten::chunk\"),\n # type, device placement casting\n \"aten::Int\": cast(\"aten::Int\"),\n \"aten::to\": cast(\"aten::to\"),\n # convolutions\n \"aten::_convolution\": convolution(\"aten::_convolution\"),\n # recurrents\n \"aten::lstm\": recurrent(\"aten::lstm\"),\n \"aten::rnn_tanh\": recurrent(\"aten::rnn_tanh\"),\n \"aten::rnn_relu\": recurrent(\"aten::rnn_relu\"),\n \"aten::gru\": recurrent(\"aten::gru\"),\n # pooling & unpooling (upsample included)\n \"aten::max_pool2d\": pool(\"aten::max_pool2d\"),\n \"aten::adaptive_avg_pool2d\": pool(\"aten::adaptive_avg_pool2d\"),\n \"aten::upsample_nearest2d\": pool(\"aten::upsample_nearest2d\"),\n # normalizations\n \"aten::batch_norm\": batch_norm(\"aten::batch_norm\"),\n # dropouts\n \"aten::dropout\": dropout(\"aten::dropout\"),\n \"aten::feature_dropout\": dropout(\"aten::dropout\"),\n # embeddings\n \"aten::embedding\": lambda *x: tf.nn.embedding_lookup(x[0], x[1]),\n # misc torch ops\n \"aten::detach\": tf.stop_gradient,\n \"aten::zeros\": lambda *x: tf.zeros(x[0], dtype_map(x[1])),\n \"aten::ones\": lambda *x: tf.ones(x[0], dtype_map(x[1])),\n}\n\ndef op_map(ir):\n assert isinstance(ir, torch.Node), \"Must be torch.Node\"\n kind = ir.kind()\n if kind in _OP_MAP:\n return _OP_MAP[kind]\n raise KeyError(\"%s is not in opmap\" % kind)\n", "sub_path": "conversion/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 4383, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.float16", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torch.half", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.float32", "line_number": 29, "usage_type": "attribute"}, {"api_name": "torch.float", "line_number": 30, "usage_type": "attribute"}, {"api_name": "torch.double", "line_number": 31, "usage_type": "attribute"}, {"api_name": "torch.float64", "line_number": 32, "usage_type": "attribute"}, {"api_name": "torch.uint8", "line_number": 34, "usage_type": "attribute"}, {"api_name": "torch.int8", "line_number": 35, "usage_type": "attribute"}, {"api_name": "torch.int16", "line_number": 36, "usage_type": "attribute"}, {"api_name": "torch.short", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.int32", "line_number": 38, "usage_type": "attribute"}, {"api_name": "torch.int", "line_number": 39, "usage_type": "attribute"}, {"api_name": "torch.int64", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.long", "line_number": 41, "usage_type": "attribute"}, {"api_name": "torch.bool", "line_number": 43, "usage_type": "attribute"}, {"api_name": "tensorflow.float16", "line_number": 27, "usage_type": "attribute"}, {"api_name": "tensorflow.float16", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.float64", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.float64", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tensorflow.uint8", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tensorflow.int8", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.int16", "line_number": 36, "usage_type": "attribute"}, {"api_name": "tensorflow.int16", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 39, "usage_type": "attribute"}, {"api_name": "tensorflow.int64", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tensorflow.int64", "line_number": 41, "usage_type": "attribute"}, {"api_name": "tensorflow.bool", "line_number": 43, "usage_type": "attribute"}, {"api_name": "tensorflow.uint8", "line_number": 46, "usage_type": "attribute"}, {"api_name": "tensorflow.int8", "line_number": 47, "usage_type": "attribute"}, {"api_name": "tensorflow.int16", "line_number": 48, "usage_type": "attribute"}, {"api_name": "tensorflow.int32", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.int64", "line_number": 50, "usage_type": "attribute"}, {"api_name": "tensorflow.float16", "line_number": 51, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 52, "usage_type": "attribute"}, {"api_name": "tensorflow.float64", "line_number": 53, "usage_type": "attribute"}, {"api_name": "tensorflow.bool", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.dtype", "line_number": 58, "usage_type": "attribute"}, {"api_name": "tensorflow.as_dtype", "line_number": 59, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 71, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 72, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 73, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 74, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 75, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 76, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 77, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 78, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 79, "usage_type": "call"}, {"api_name": "math.math_ops", "line_number": 80, "usage_type": "call"}, {"api_name": "gemm.gemm", "line_number": 81, "usage_type": "call"}, {"api_name": "gemm.gemm", "line_number": 82, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 84, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 85, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 86, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 87, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 88, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 89, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 90, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 91, "usage_type": "call"}, {"api_name": "activations.activation", "line_number": 92, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 94, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 95, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 96, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 97, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 98, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 99, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 100, "usage_type": "call"}, {"api_name": "shape.shape_ops", "line_number": 101, "usage_type": "call"}, {"api_name": "cast.cast", "line_number": 103, "usage_type": "call"}, {"api_name": "cast.cast", "line_number": 104, "usage_type": "call"}, {"api_name": "convolution.convolution", "line_number": 106, "usage_type": "call"}, {"api_name": "recurrent.recurrent", "line_number": 108, "usage_type": "call"}, {"api_name": "recurrent.recurrent", "line_number": 109, "usage_type": "call"}, {"api_name": "recurrent.recurrent", "line_number": 110, "usage_type": "call"}, {"api_name": "recurrent.recurrent", "line_number": 111, "usage_type": "call"}, {"api_name": "pool.pool", "line_number": 113, "usage_type": "call"}, {"api_name": "pool.pool", "line_number": 114, "usage_type": "call"}, {"api_name": "pool.pool", "line_number": 115, "usage_type": "call"}, {"api_name": "normalization.batch_norm", "line_number": 117, "usage_type": "call"}, {"api_name": "dropout.dropout", "line_number": 119, "usage_type": "call"}, {"api_name": "dropout.dropout", "line_number": 120, "usage_type": "call"}, {"api_name": "tensorflow.nn.embedding_lookup", "line_number": 122, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 122, "usage_type": "attribute"}, {"api_name": "tensorflow.stop_gradient", "line_number": 124, "usage_type": "attribute"}, {"api_name": "tensorflow.zeros", "line_number": 125, "usage_type": "call"}, {"api_name": "tensorflow.ones", "line_number": 126, "usage_type": "call"}, {"api_name": "torch.Node", "line_number": 130, "usage_type": "attribute"}]}
+{"seq_id": "38410477", "text": "import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n'''\n形态学操作是根据图像形状进行的简单操作。一般情况下对二值化图像进行的操作。\n需要输入两个参数,一个是原始图像,第二个被称为结构化元素或核,它是用来决定操作的性质的。\n两个基本的形态学操作是腐蚀和膨胀。\n\n 腐蚀:用最小值替换中心像素。除白噪声很有用,也可以用来断开两个连在一块的物体等\n 膨胀:用最大值替换中心像素。增加图像中的白色区域(前景),也可以用来连接两个分开的物体。\n\n\n结构化元素\n 1.使用 Numpy 构建结构化元素,它是正方形的。\n 2. cv2.getStructuringElement(shape, ksize, anchor=None)。你只需要告诉他你需要的核的形状和大小。构建一个椭圆形/圆形的核\n - shape:\n cv2.MORPH_RECT 矩形\n cv2.MORPH_ELLIPSE 椭圆\n cv2.MORPH_CROSS 十字\n'''\n\n\n# 腐蚀\ndef erode_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow(\"binary\", binary)\n\n # 得到结构元素\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n dst = cv.erode(binary, kernel)\n cv.imshow(\"erode_image\", dst)\n\n\n# 膨胀\ndef dilate_demo(image):\n print(image.shape)\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)\n cv.imshow(\"binary\", binary)\n\n # 得到结构元素\n kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))\n dst = cv.dilate(binary, kernel)\n cv.imshow(\"dilate_image\", dst)\n\n\ndef main():\n # 读取图片\n img = cv.imread(\"../code_images/bin2.jpg\")\n\n # 创建窗口,窗口尺寸自动调整\n # cv.namedWindow(\"lena\", cv.WINDOW_AUTOSIZE)\n\n # 显示图片\n cv.imshow(\"lena\", img)\n\n erode_demo(img)\n dilate_demo(img)\n\n # 等待键盘输入\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "code/case_21_erode_dilate.py", "file_name": "case_21_erode_dilate.py", "file_ext": "py", "file_size_in_byte": 2149, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "cv2.cvtColor", "line_number": 27, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 27, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 28, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 28, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 29, "usage_type": "call"}, {"api_name": "cv2.getStructuringElement", "line_number": 32, "usage_type": "call"}, {"api_name": "cv2.MORPH_RECT", "line_number": 32, "usage_type": "attribute"}, {"api_name": "cv2.erode", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 34, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 40, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 41, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 41, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 41, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 42, "usage_type": "call"}, {"api_name": "cv2.getStructuringElement", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.MORPH_RECT", "line_number": 45, "usage_type": "attribute"}, {"api_name": "cv2.dilate", "line_number": 46, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 65, "usage_type": "call"}]}
+{"seq_id": "310760448", "text": "from django.core.exceptions import ImproperlyConfigured\n\nclass DebugCmd(object):\n def __init__(self, name, verbose_name, fn, params=None):\n self.name = name\n self.verbose_name = verbose_name\n if hasattr(fn, '__call__'): \n self.fn = fn \n self.doc = fn.__doc__\n else:\n raise ImproperlyConfigured('Debug cmd must have a callable intead of %s' % str(fn))\n self.params = params\n\n def __repr__(self):\n return '#'.join(['DebugCmd', self.name, str(self.params)])\n", "sub_path": "debug_toolbar/utils/debug_cmd.py", "file_name": "debug_cmd.py", "file_ext": "py", "file_size_in_byte": 536, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.core.exceptions.ImproperlyConfigured", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "365012307", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# Copyright 2013 Herve BREDIN (bredin@limsi.fr)\n\n# This file is part of PyAnnote.\n#\n# PyAnnote is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# PyAnnote is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with PyAnnote. If not, see .\n\n\nimport scipy.io.wavfile\nimport yaafelib\nfrom pyannote.core.feature import SlidingWindowFeature\nfrom pyannote.core.segment import SlidingWindow\nimport numpy as np\n\n\nclass YaafeFrame(SlidingWindow):\n \"\"\"Yaafe frames\n\n Parameters\n ----------\n blockSize : int, optional\n Window size (in number of samples). Default is 512.\n stepSize : int, optional\n Step size (in number of samples). Default is 256.\n sampleRate : int, optional\n Sample rate (number of samples per second). Default is 16000.\n\n References\n ----------\n http://yaafe.sourceforge.net/manual/quickstart.html\n\n \"\"\"\n def __init__(self, blockSize=512, stepSize=256, sampleRate=16000):\n\n duration = 1. * blockSize / sampleRate\n step = 1. * stepSize / sampleRate\n start = -0.5 * duration\n\n super(YaafeFrame, self).__init__(\n duration=duration, step=step, start=start\n )\n\n\nclass YaafeFeatureExtractor(object):\n \"\"\"\n\n Parameters\n ----------\n sample_rate : int, optional\n Defaults to 16000 (i.e. 16kHz)\n block_size : int, optional\n Defaults to 512.\n step_size : int, optional\n Defaults to 256.\n\n \"\"\"\n\n def __init__(\n self, sample_rate=16000, block_size=512, step_size=256\n ):\n\n super(YaafeFeatureExtractor, self).__init__()\n\n self.sample_rate = sample_rate\n self.block_size = block_size\n self.step_size = step_size\n\n def get_flow_and_stack(self, **kwargs):\n raise NotImplementedError(\n 'get_flow_and_stack method must be implemented'\n )\n\n def extract(self, wav):\n \"\"\"Extract features\n\n Parameters\n ----------\n wav : string\n Path to wav file.\n\n Returns\n -------\n features : SlidingWindowFeature\n\n \"\"\"\n\n # hack\n data_flow, stack = self.get_flow_and_stack()\n\n engine = yaafelib.Engine()\n engine.load(data_flow)\n\n sample_rate, raw_audio = scipy.io.wavfile.read(wav)\n assert sample_rate == self.sample_rate, \"sample rate mismatch\"\n\n audio = np.array(raw_audio, dtype=np.float64, order='C').reshape(1, -1)\n\n features = engine.processAudio(audio)\n data = np.hstack([features[name] for name in stack])\n\n sliding_window = YaafeFrame(\n blockSize=self.block_size, stepSize=self.step_size,\n sampleRate=self.sample_rate)\n\n return SlidingWindowFeature(data, sliding_window)\n\n\nclass YaafeMFCC(YaafeFeatureExtractor):\n\n \"\"\"\n | e | energy\n | c1 |\n | c2 | coefficients\n | c3 |\n | ... |\n | Δe | energy first derivative\n | Δc1 |\n x = | Δc2 | coefficients first derivatives\n | Δc3 |\n | ... |\n | ΔΔe | energy second derivative\n | ΔΔc1 |\n | ΔΔc2 | coefficients second derivatives\n | ΔΔc3 |\n | ... |\n\n\n Parameters\n ----------\n\n sample_rate : int, optional\n Defaults to 16000 (i.e. 16kHz)\n block_size : int, optional\n Defaults to 512.\n step_size : int, optional\n Defaults to 256.\n\n e : bool, optional\n Energy. Defaults to True.\n coefs : int, optional\n Number of coefficients. Defaults to 11.\n De : bool, optional\n Keep energy first derivative. Defaults to False.\n D : bool, optional\n Add first order derivatives. Defaults to False.\n DDe : bool, optional\n Keep energy second derivative. Defaults to False.\n DD : bool, optional\n Add second order derivatives. Defaults to False.\n\n Notes\n -----\n Default Yaafe values:\n * fftWindow = Hanning\n * melMaxFreq = 6854.0\n * melMinFreq = 130.0\n * melNbFilters = 40\n\n \"\"\"\n\n def __init__(\n self, sample_rate=16000, block_size=512, step_size=256,\n e=True, coefs=11, De=False, DDe=False, D=False, DD=False,\n ):\n\n super(YaafeMFCC, self).__init__(\n sample_rate=sample_rate,\n block_size=block_size,\n step_size=step_size\n )\n\n self.e = e\n self.coefs = coefs\n self.De = De\n self.DDe = DDe\n self.D = D\n self.DD = DD\n\n def get_flow_and_stack(self):\n\n feature_plan = yaafelib.FeaturePlan(sample_rate=self.sample_rate)\n stack = []\n\n # --- coefficients\n # 0 if energy is kept\n # 1 if energy is removed\n definition = (\n \"mfcc: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d\" % (\n 0 if self.e else 1,\n self.coefs + self.e * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc')\n\n # --- 1st order derivatives\n if self.D or self.De:\n definition = (\n \"mfcc_d: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d > Derivate DOrder=1\" % (\n 0 if self.De else 1,\n self.D * self.coefs + self.De * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc_d')\n\n # --- 2nd order derivatives\n if self.DD or self.DDe:\n definition = (\n \"mfcc_dd: \"\n \"MFCC CepsIgnoreFirstCoeff=%d CepsNbCoeffs=%d \"\n \"blockSize=%d stepSize=%d > Derivate DOrder=2\" % (\n 0 if self.DDe else 1,\n self.DD * self.coefs + self.DDe * 1,\n self.block_size, self.step_size\n )\n )\n assert feature_plan.addFeature(definition)\n stack.append('mfcc_dd')\n\n # --- prepare the Yaafe engine\n data_flow = feature_plan.getDataFlow()\n\n return data_flow, stack\n", "sub_path": "pyannote/features/audio/yaafe.py", "file_name": "yaafe.py", "file_ext": "py", "file_size_in_byte": 6788, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pyannote.core.segment.SlidingWindow", "line_number": 29, "usage_type": "name"}, {"api_name": "yaafelib.Engine", "line_number": 103, "usage_type": "call"}, {"api_name": "scipy.io.wavfile.io.wavfile.read", "line_number": 106, "usage_type": "call"}, {"api_name": "scipy.io.wavfile.io", "line_number": 106, "usage_type": "attribute"}, {"api_name": "scipy.io.wavfile", "line_number": 106, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 109, "usage_type": "attribute"}, {"api_name": "numpy.hstack", "line_number": 112, "usage_type": "call"}, {"api_name": "pyannote.core.feature.SlidingWindowFeature", "line_number": 118, "usage_type": "call"}, {"api_name": "yaafelib.FeaturePlan", "line_number": 194, "usage_type": "call"}]}
+{"seq_id": "13013036", "text": "from django import template\nfrom django.template.defaultfilters import stringfilter\n\nregister = template.Library()\n\n\n@register.filter(name='domain')\n@stringfilter\ndef cut_email_domain(value):\n if '@' not in value:\n return '[email not stated]'\n return value.partition('@')[2]\n", "sub_path": "test_django/authors/templatetags/email_domain.py", "file_name": "email_domain.py", "file_ext": "py", "file_size_in_byte": 288, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.template.Library", "line_number": 4, "usage_type": "call"}, {"api_name": "django.template", "line_number": 4, "usage_type": "name"}, {"api_name": "django.template.defaultfilters.stringfilter", "line_number": 8, "usage_type": "name"}]}
+{"seq_id": "509683109", "text": "import cv2\nimport numpy as np\n\n\ndef strokeEdges(src,dst,blurKsize=7,edgeKsize=5):\n\tif blurKsize>=3:\n\t\tblurredSrc=cv2.medianBlur(src,blurKsize)\n\t\tgraySrc=cv2.cvtColor(blurredSrc,cv2.COLOR_BGR2GRAY)\n\telse:\n\t\tgraySrc=cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)\n\tcv2.Laplacian(graySrc,cv2.CV_8U,graySrc,ksize=edgeKsize)\n\tnormalizedInverseAlpha=(1.0/255)*(255-graySrc)\n\tchannels=cv2.split(src)\n\tfor channel in channels:\n\t\tchannel[:]=channel*normalizedInverseAlpha\n\tcv2.merge(channels,dst)\n\n\nclass VConvolutionFilter(object):\n\t\"\"\"A filter that applies a convolution to V (or all of BGR)\"\"\"\n\n\tdef __init__(self,kernel):\n\t\tself._kernel=kernel\n\n\tdef apply(self,src,dst):\n\t\t\"\"\"Apply the filter with a BGR or gray source/destination\"\"\"\n\t\tcv2.filter2D(src,-1,self._kernel,dst)\n\n#锐化过滤器:核权重和为1\nclass SharpenFilter(VConvolutionFilter):\n\t\"\"\"A sharpen filter with a 1-pixel radius.\"\"\"\n\n\tdef __init__(self):\n\t\tkernel=np.array([[-1,-1,-1],\n\t\t\t\t\t\t [-1,9,-1],\n\t\t\t\t\t\t [-1,-1,-1]])\n\t\tVConvolutionFilter.__init__(self,kernel)\n\n#边缘检测过滤器:核权重和为0\nclass FindEdgesFilter(VConvolutionFilter):\n\t\"\"\"An edge-finding filter with a 1-pixel radius\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[-1, -1, -1],\n\t\t\t\t\t\t [-1, 8, -1],\n\t\t\t\t\t\t [-1, -1, -1]])\n\t\tVConvolutionFilter.__init__(self, kernel)\n\n\n#模糊过滤器:核权重和为1,且周围权重全为正数\nclass BlurFilter(VConvolutionFilter):\n\t\"\"\"A blur filter with a 2-pixel radius\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04],\n\t\t\t\t\t\t [0.04,0.04,0.04,0.04,0.04]])\n\t\tVConvolutionFilter.__init__(self, kernel)\n\n\n#浮雕效果过滤器\nclass EmbossFilter(VConvolutionFilter):\n\t\"\"\"An emboss filter with a 1-pixel radius.\"\"\"\n\n\tdef __init__(self):\n\t\tkernel = np.array([[-2, -1, 0],\n\t\t\t\t\t\t [-1, 1, 1],\n\t\t\t\t\t\t [0, 1, 2]])\n\t\tVConvolutionFilter.__init__(self, kernel)", "sub_path": "test/filters.py", "file_name": "filters.py", "file_ext": "py", "file_size_in_byte": 1964, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "cv2.medianBlur", "line_number": 7, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 8, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 10, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 10, "usage_type": "attribute"}, {"api_name": "cv2.Laplacian", "line_number": 11, "usage_type": "call"}, {"api_name": "cv2.CV_8U", "line_number": 11, "usage_type": "attribute"}, {"api_name": "cv2.split", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.merge", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.filter2D", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 44, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 68, "usage_type": "call"}]}
+{"seq_id": "623508163", "text": "import re\nimport itertools\n\nfirst_word = ''\nsecond_word = ''\nrules = list()\nhand = open('000140.ant')\nfor line in hand:\n line = line.rstrip()\n if re.search('s[0-9]$', line):\n rules.append(line)\nprint(rules)\nfor a, b in itertools.combinations(rules, 2):\n if re.search('^amod', a) and re.search('^nmod', b):\n first_word = re.findall('\\((.*?)\\-', a)\n print(first_word)\n second_word = re.findall('\\, (.*?)\\-', b)\n print(second_word)\n", "sub_path": "lexxe.py", "file_name": "lexxe.py", "file_ext": "py", "file_size_in_byte": 473, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "re.search", "line_number": 10, "usage_type": "call"}, {"api_name": "itertools.combinations", "line_number": 13, "usage_type": "call"}, {"api_name": "re.search", "line_number": 14, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 15, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 17, "usage_type": "call"}]}
+{"seq_id": "481960070", "text": "#!/usr/bin/env python\nimport rospy\nimport time\nimport argparse\nimport csv\nfrom p3dx_navigation.msg import Wifidata\nfrom geometry_msgs.msg import PoseStamped, Point, Quaternion\n\nsub_ssid = []\nsub_rssi = []\nmax_rssi = -100\npermitRead = False\nPositionX = []\nPositionY = []\nSSID1 = []\nSSID2 = []\nSSID3 = []\nSSID4 = []\nSSID5 = []\nRSSI1 = []\nRSSI2 = []\nRSSI3 = []\nRSSI4 = []\nRSSI5 = []\nrow = []\npresubssid = ''\nprePositionX = 0\nprePositionY = 0\nnum = 0\n\n\n\n\"\"\"class RosNode(object):\n def wait_for_subscriber(self, pub, timeout):\n timeout_t = time.time() + timeout\n while pub.get_num_connections() == 0 and timeout_t > time.time():\n self.sleep(0.01)\n\n def sleep(self, duration):\n rospy.rostime.wallsleep(duration)\n\"\"\"\n\nclass WifiPosReaderNode:\n def __init__(self):\n # self.__pub = rospy.Publisher(\"/goal\", PoseStamped, queue_size=100)\n self.__pub = rospy.Publisher(\"/move_base_simple/goal\", PoseStamped, queue_size=100)\n rospy.init_node(\"wifiposreader_node\")\n rospy.Subscriber(\"wifi_state\", Wifidata, self.wifi_callback)\n\n def readCSV(self, csv_file):\n # super(WifiPosReaderNode, self).wait_for_subscriber(self.__pub, timeout=1.0) #timeout=5.0\n global row, PositionX, PositionY, SSID1, SSID2, SSID3, SSID4, SSID5, RSSI1, RSSI2, RSSI3, RSSI4, RSSI5\n\n with open(csv_file, 'r') as f:\n reader = csv.reader(f)\n header = next(reader)\n for row in reader:\n if rospy.is_shutdown():\n break;\n # rospy.loginfo(row)\n PositionX.append(float(row[0]))\n PositionY.append(float(row[1]))\n SSID1.append(row[2])\n RSSI1.append(int(row[3]))\n SSID2.append(row[4])\n RSSI2.append(int(row[5]))\n SSID3.append(row[6])\n RSSI3.append(int(row[7]))\n SSID4.append(row[8])\n RSSI4.append(int(row[9]))\n SSID5.append(row[10])\n RSSI5.append(int(row[11]))\n print(\"CSV file was read\")\n\n def wifi_callback(self, wifi_state):\n global sub_ssid, sub_rssi, max_rssi, presubssid, prePositionX, prePositionY, num\n maxPosX = 0\n maxPosY = 0\n permitPub = False\n rate = rospy.Rate(10) # 10hz\n wifi = wifi_state\n sub_ssid = wifi.ssid[:]\n sub_rssi = wifi.rssi[:]\n max_rssi = -100\n print(\"received wifistate\")\n print(sub_ssid)\n print(sub_rssi)\n\n i = 0\n for i in range(len(SSID1)):\n if SSID1[i] == sub_ssid[0] and RSSI1[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI1[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n if sub_rssi[0] > -45 and sub_rssi[0] - sub_rssi[1] > 3:\n permitPub = True\n elif sub_rssi[0] > -50 and sub_rssi[0] - sub_rssi[1] > 2:\n permitPub = True\n elif sub_rssi[0] > -55 and sub_rssi[0] - sub_rssi[1] > 1:\n permitPub = True\n else:\n permitPub = False\n\n if permitPub == False:\n print(\"not found\")\n for i in range(len(SSID2)):\n if SSID2[i] == sub_ssid[0] and RSSI2[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI2[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n permitPub = True\n\n \"\"\"\n if permitPub == False:\n print(\"Not matching\")\n for i in range(len(SSID1)):\n if SSID1[i] == sub_ssid[1] and RSSI1[i] > max_rssi:\n maxPosX = PositionX[i]\n maxPosY = PositionY[i]\n max_rssi = RSSI1[i]\n rospy.loginfo(maxPosX)\n rospy.loginfo(maxPosY)\n rospy.loginfo(max_rssi)\n print(\"updated max\")\n permitPub = True\n \"\"\"\n\n \"\"\"\n if permitPub == False:\n print(\"Not matching\")\n \"\"\"\n\n \"\"\"\n if permitPub:\n if sub_rssi[] #??????\n \"\"\"\n\n distance = ((maxPosX - prePositionX) * (maxPosX - prePositionX)) + ((maxPosY - prePositionY) * (maxPosY - prePositionY)) #distance of 2points(published point and publishing point)\n print(distance)\n\n if distance < 16: #distance to the second power\n permitPub = False\n print(\"Too near the point set\")\n\n\n \"\"\"\n if presubssid == sub_ssid[0] or distance < 9: #distance to the second power\n permitPub = False\n print(\"Too near the point set\")\n \"\"\"\n\n\n if permitPub:\n goal = self.__parse_row(row, maxPosX, maxPosY)\n self.__pub.publish(goal)\n print(\"published\")\n prePositionX = maxPosX\n prePositionY = maxPosY\n rate.sleep()\n num = num + 1\n rospy.loginfo(num)\n elif permitPub == False:\n print(\"Not publishing\")\n\n presubssid = sub_ssid[0]\n\n\n def __parse_row(self, row, x, y):\n frame = row[-1]\n\n goal = PoseStamped()\n goal.pose.position.x = x\n goal.pose.position.y = y\n goal.pose.position.z = 0\n goal.pose.orientation.x = 0\n goal.pose.orientation.y = 0\n goal.pose.orientation.z = 0.9993610636\n goal.pose.orientation.w = 0.0357416366999439\n goal.header.frame_id = frame\n goal.header.stamp = rospy.Time.now()\n\n return goal\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"wifipos_reader node publish goals from csv file.\")\n parser.add_argument(\"csv\", metavar=\"file\", type=str, help=\"name of csv file to read\")\n args = parser.parse_args()\n node = WifiPosReaderNode()\n\n try:\n node.readCSV(args.csv)\n except rospy.ROSInterruptException:\n pass\n\n rospy.spin()\n", "sub_path": "p3dx_navigation/scripts/wifipos_reader2.py", "file_name": "wifipos_reader2.py", "file_ext": "py", "file_size_in_byte": 6308, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "rospy.Publisher", "line_number": 46, "usage_type": "call"}, {"api_name": "geometry_msgs.msg.PoseStamped", "line_number": 46, "usage_type": "argument"}, {"api_name": "rospy.init_node", "line_number": 47, "usage_type": "call"}, {"api_name": "rospy.Subscriber", "line_number": 48, "usage_type": "call"}, {"api_name": "p3dx_navigation.msg.Wifidata", "line_number": 48, "usage_type": "argument"}, {"api_name": "csv.reader", "line_number": 55, "usage_type": "call"}, {"api_name": "rospy.is_shutdown", "line_number": 58, "usage_type": "call"}, {"api_name": "rospy.Rate", "line_number": 80, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 95, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 96, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 97, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 115, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 116, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 117, "usage_type": "call"}, {"api_name": "rospy.loginfo", "line_number": 169, "usage_type": "call"}, {"api_name": "geometry_msgs.msg.PoseStamped", "line_number": 179, "usage_type": "call"}, {"api_name": "rospy.Time.now", "line_number": 188, "usage_type": "call"}, {"api_name": "rospy.Time", "line_number": 188, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 193, "usage_type": "call"}, {"api_name": "rospy.ROSInterruptException", "line_number": 200, "usage_type": "attribute"}, {"api_name": "rospy.spin", "line_number": 203, "usage_type": "call"}]}
+{"seq_id": "18770691", "text": "#!/usr/bin/env python\n\n\"\"\"Write JSON index for a directory.\"\"\"\n\nimport os\nimport sys\nimport json\nimport argparse\n\nEPILOG = \"\"\"\nThe index is a list of names of .json files in the directory, excluding the index file\nitself (if it is in the directory).\n\"\"\"\n\n\ndef main(args):\n # use os.path.isfile or os.path.isdir to avoid directories\n files = [filename for filename in os.listdir(args.directory)\n if filename.endswith('.json')]\n if args.output == '-':\n writer = sys.stdout\n else:\n out = args.output or args.directory + os.sep + 'index.json'\n writer = open(out, 'w')\n dirpath = os.path.abspath(args.directory)\n outdir, outfile = os.path.split(os.path.abspath(out))\n if dirpath == outdir and outfile in files:\n files.remove(outfile)\n json.dump(files, writer, indent=2, sort_keys=True)\n\n\ndef get_args():\n formatter = argparse.RawDescriptionHelpFormatter\n p = argparse.ArgumentParser(\n description=__doc__,\n epilog=EPILOG,\n formatter_class=formatter)\n p.add_argument('directory', nargs='?', type=str, default='.',\n help='directory to index, default is current directory')\n p.add_argument('--output', type=str,\n help=('output file, or \"-\" for stdout, default \"index.json\" ' +\n 'in indexed directory'))\n args = p.parse_args()\n return args\n\nif __name__ == \"__main__\":\n main(get_args())\n", "sub_path": "scripts/index.py", "file_name": "index.py", "file_ext": "py", "file_size_in_byte": 1459, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.listdir", "line_number": 18, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.sep", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.split", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 26, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 29, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 33, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 34, "usage_type": "call"}]}
+{"seq_id": "649731268", "text": "import sqlite3\r\n\r\n#define connection and cursor\r\n\r\nconnection = sqlite3.connect (\"store transactions.db\")\r\n\r\ncursor = connection.cursor()\r\n\r\n# create stores table\r\n\r\ncommand1 = \"\"\"CREATE TABLE IF NOT EXISTS\r\nstores(store_id INTEGER PRIMARY KEY, location TEXT)\"\"\"\r\n\r\ncursor.execute(command1)\r\n\r\n# create purchase table\r\n\r\ncommand2 = \"\"\"CREATE TABLE IF NOT EXISTS\r\npurchases(purchase_id INTEGER PRIMARY KEY, store_id INTEGER, total_cost FLOAT,\r\nFOREIGN KEY(store_id) REFERENCES stores(store_id))\"\"\"\r\n\r\ncursor.execute(command2)\r\n\r\n# add to stores\r\n\r\ncursor.execute (\"INSERT INTO stores VALUES ( 21, 'Washington, DC')\")\r\ncursor.execute (\"INSERT INTO stores VALUES ( 22, 'Rockville, MD')\")\r\ncursor.execute (\"INSERT INTO stores VALUES ( 23, 'Bowie, MD')\")\r\n\r\n# add to purchases\r\n\r\ncursor.execute (\"INSERT INTO purchases VALUES (54, 21, 15.49)\")\r\ncursor.execute (\"INSERT INTO purchases VALUES (77, 43, 21.12)\")\r\n\r\n# get results\r\n\r\ncursor.execute(\"SELECT * FROM purchases\")\r\n\r\nresults = cursor.fetchall()\r\nprint (results)\r\n\r\n\r\n", "sub_path": "store_transaction.py", "file_name": "store_transaction.py", "file_ext": "py", "file_size_in_byte": 1020, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sqlite3.connect", "line_number": 5, "usage_type": "call"}]}
+{"seq_id": "604767334", "text": "# Program to convert an xml\n# file to json file\n \nimport sys\n# import json module and xmltodict\n# module provided by python\nimport json\nimport xmltodict\n \n \n# open the input xml file and read\n# data in form of python dictionary \n# using xmltodict module\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\nprint(\"Input \",input_file,\" Output \",output_file)\nwith open(input_file) as xml_file:\n \n data_dict = xmltodict.parse(xml_file.read())\n xml_file.close()\n \n # generate the object using json.dumps() \n # corresponding to json data\n \n json_data = json.dumps(data_dict)\n \n out = open(output_file, \"w\")\n out.write('{\"corners\": [')\n #print(data_dict[\"PcGts\"][\"Page\"][\"TextRegion\"])\n beforesort = []\n for arr in data_dict[\"PcGts\"][\"Page\"][\"TextRegion\"]:\n points = arr[\"Coords\"][\"@points\"].split()\n for xy in points:\n beforesort.append(xy)\n beforesort.sort()\n first = 1\n for xy in beforesort:\n if first:\n out.write(\"[\"+xy+\"]\")\n first = 0\n else:\n out.write(\",[\"+xy+\"]\")\n out.write(']}')\n", "sub_path": "data/convertToJson.py", "file_name": "convertToJson.py", "file_ext": "py", "file_size_in_byte": 1102, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.argv", "line_number": 14, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 15, "usage_type": "attribute"}, {"api_name": "xmltodict.parse", "line_number": 19, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 25, "usage_type": "call"}]}
+{"seq_id": "641292255", "text": "from numpy import arccos, arctan, array, cos, cross, dot, pi, sin, sqrt, tan\nfrom numpy.linalg import norm\nfrom datetime import datetime, timedelta\n\nμ = 3.986004418e5 #km^3/s^2\n\n# Solve Kepler's equation\ndef solveKepler(M,e):\n E = M\n dE = pi\n while dE > 1e-6:\n E0 = E\n E = M + e*sin(E)\n dE = abs(E-E0)\n return E\n\n# Rotation Matrices\ndef Rx(θ):\n mat = array([\n [1, 0, 0],\n [0, cos(θ), sin(θ)],\n [0, -sin(θ), cos(θ)]]\n )\n return mat\n\ndef Ry(θ):\n mat = array([\n [cos(θ), 0, -sin(θ)],\n [0, 1, 0],\n [sin(θ), 0, cos(θ)]]\n )\n return mat\n\ndef Rz(θ):\n mat = array([\n [cos(θ), sin(θ), 0],\n [-sin(θ), cos(θ), 0],\n [0, 0, 1]]\n )\n return mat\n\ndef pvt2kepler(pvt):\n # convert pvt to elements...\n assert isinstance(pvt[6], datetime), \"pvt[6] is not a valid datetime object\"\n t0 = pvt[6]\n \n r_ = array(pvt[0:3])\n v_ = array(pvt[3:6])\n\n r = norm(r_)\n \n h_ = cross(r_,v_)\n h = norm(h_)\n e_ = cross(v_,h_)/μ - r_/r\n e = norm(e_)\n\n p = h*h/μ\n\n a = p /(1-e*e)\n a = norm(a)\n\n i = arccos(h_[2]/h)\n\n Ω=0\n n_ = [-h_[1],h_[0],0]\n n = norm(n_)\n if n_[1] >= 0:\n Ω = arccos(n_[0]/n)\n if n_[1] < 0:\n Ω = 2*pi - arccos(n_[0]/n)\n\n ω = arccos(dot(n_,e_) / (n*e))\n if e_[2] < 0:\n ω = 2*pi - ω\n \n \n υ = arccos(dot(e_,r_)/(e*r))\n if dot(r_,v_) < 0:\n υ = 2*pi - υ\n\n # [a(km) e i(rad) Ω(rad) ω(rad) υ(rad)]\n elements = [a, e, i, Ω, ω, υ, t0]\n return elements\n\ndef kepler2pvt(elements):\n [a, e, i, Ω, ω, υ, t0] = elements\n assert isinstance(t0, datetime), \"elements[6] is not a valid datetime object\"\n\n E = 2*arctan(tan(υ/2)/sqrt((1+e)/(1-e)))\n\n r = a*(1-e*cos(E))\n\n o_ = r*array([cos(υ), sin(υ), 0])\n oDot_ = sqrt(μ*a)/r*array([-sin(E), sqrt(1-e*e)*cos(E), 0])\n\n # Convert to ICRF\n r_ = Rz(-Ω) @ Rx(-i) @ Rz(-ω) @ o_\n v_ = Rz(-Ω) @ Rx(-i) @ Rz(-ω) @ oDot_\n\n return [r_[0],r_[1],r_[2],v_[0],v_[1],v_[2],t0]\n\n\n# Propagate elements by dt seconds\ndef prop(dt, elements):\n [a, e, i, Ω, ω, υ, t0] = elements\n assert isinstance(t0, datetime), \"elements[6] is not a valid datetime object\"\n\n n = sqrt(μ/(a*a*a))\n E = arctan(sqrt(1-e*e)*sin(υ)/(e+cos(υ)))\n M = E - e*sin(E)\n M = M + n*(dt)\n\n # Kepler's equation\n E = solveKepler(M,e)\n\n υ = 2*arctan(sqrt((1+e)/(1-e))*tan(E/2))\n #print(υ)\n\n # New epoch\n dt = timedelta(0,dt)\n t1 = t0 + dt\n \n return [a, e, i, Ω, ω, υ, t1]", "sub_path": "kepler2/challenge/kepler.py", "file_name": "kepler.py", "file_ext": "py", "file_size_in_byte": 2708, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.pi", "line_number": 10, "usage_type": "name"}, {"api_name": "numpy.sin", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 30, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 35, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 37, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 37, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 44, "usage_type": "argument"}, {"api_name": "numpy.array", "line_number": 47, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.cross", "line_number": 52, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.cross", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 60, "usage_type": "call"}, {"api_name": "numpy.arccos", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.linalg.norm", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.arccos", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 70, "usage_type": "name"}, {"api_name": "numpy.arccos", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.arccos", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 74, "usage_type": "name"}, {"api_name": "numpy.arccos", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 79, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "argument"}, {"api_name": "numpy.arctan", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.tan", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 89, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 91, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 106, "usage_type": "argument"}, {"api_name": "numpy.sqrt", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.arctan", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 109, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.arctan", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.tan", "line_number": 116, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 120, "usage_type": "call"}]}
+{"seq_id": "528953449", "text": "import datetime\r\nimport json\r\nimport logging\r\nimport logging.handlers\r\nimport paho.mqtt.client as mqtt\r\nimport pyrebase\r\nimport time\r\nimport threading\r\nimport yaml\r\n\r\n# logging configuration\r\nLOG_FILENAME = '/opt/dmars/mqtt_subscriber_to_firebase.log'\r\n\r\nroot_logger=logging.getLogger()\r\nroot_logger.setLevel(logging.DEBUG)\r\nfile_handler = logging.FileHandler(LOG_FILENAME, 'w', 'utf-8')\r\nfile_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s:%(message)s'))\r\n# Create the rotating file handler. Limit the size to 1000000Bytes ~ 1MB .\r\nrotating_file_handler = logging.handlers.RotatingFileHandler(\r\n LOG_FILENAME, maxBytes=1000000, backupCount=5)\r\n# Add the handlers to the logger\r\nroot_logger.addHandler(file_handler)\r\nroot_logger.addHandler(rotating_file_handler)\r\n\r\n# read configurations\r\nwith open(r'/opt/dmars/firebase_config.yml') as file:\r\n firebase_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\nwith open(r'/opt/dmars/basestation_config.yml') as file:\r\n basestation_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\nwith open(r'/opt/dmars/mqtt_config.yml') as file:\r\n mqtt_config = yaml.load(file, Loader=yaml.FullLoader)\r\n\r\npyrebase_config = {\r\n \"apiKey\": firebase_config['api_key'],\r\n \"authDomain\": firebase_config['auth_domain'],\r\n \"databaseURL\": firebase_config['database_url'],\r\n \"storageBucket\": firebase_config['storage_bucket'],\r\n \"serviceAccount\": firebase_config['service_account']\r\n}\r\n\r\nnode_ids_recognized = set()\r\n\r\n# Firebase: initialize app with config\r\nfirebase = pyrebase.initialize_app(pyrebase_config)\r\n\r\n# Firebase: authenticate a user\r\nauth = firebase.auth()\r\nuser = auth.sign_in_with_email_and_password(firebase_config['email'], firebase_config['password'])\r\n\r\ndb = firebase.database()\r\n\r\ndef handle_firebase_token_refresh():\r\n global user\r\n logging.debug('Refreshing Firebase token...')\r\n user = auth.refresh(user['refreshToken'])\r\n\r\n# need to refresh the firebase token every hour\r\ndef handle_firebase_token_refresh_thread():\r\n logging.debug('handling scheduled firebase token refresh')\r\n handle_firebase_token_refresh()\r\n # 1800 seconds = 30 minutes\r\n threading.Timer(1800, handle_firebase_token_refresh_thread).start()\r\n\r\ndef send_metadata_to_firebase(message):\r\n root_name = basestation_config['root_name']\r\n environment = basestation_config['environment']\r\n version = basestation_config['version']\r\n node_id = message['node_id']\r\n metadata = 'metadata'\r\n\r\n metadata_message = {\r\n \"base-station-id\": basestation_config['base_station_id'],\r\n \"source-id\": basestation_config['source_id'],\r\n \"element\": basestation_config['element'],\r\n \"location\": message['location']\r\n }\r\n\r\n\r\n db.child(root_name) \\\r\n .child(environment) \\\r\n .child(version) \\\r\n .child(metadata) \\\r\n .child(node_id) \\\r\n .set(metadata_message, user['idToken'])\r\n\r\n\r\ndef send_data_to_firebase(message):\r\n logging.debug('Sending event to Firebase...')\r\n\r\n if message['node_id'] not in node_ids_recognized:\r\n send_metadata_to_firebase(message)\r\n node_ids_recognized.add(message['node_id'])\r\n\r\n # Create using push\r\n # We are going to use this option as each send must have a unique ID.\r\n root_name = basestation_config['root_name']\r\n environment = basestation_config['environment']\r\n version = basestation_config['version']\r\n data = 'data'\r\n\r\n telemetry = {\r\n \"node-id\": message['node_id'],\r\n \"data-type\": message['data_type'],\r\n \"measurement-unit\": message['measurement_unit'],\r\n \"timestamp\": datetime.datetime.now().timestamp(),\r\n \"value\": message['value']\r\n }\r\n\r\n db.child(root_name) \\\r\n .child(environment) \\\r\n .child(version) \\\r\n .child(data) \\\r\n .push(telemetry, user['idToken'])\r\n\r\nclient = mqtt.Client()\r\nclient.connect(mqtt_config['address'],mqtt_config['port'])\r\n\r\nhandle_firebase_token_refresh_thread()\r\n\r\ndef on_connect(client, userdata, flags, rc):\r\n logging.debug('Connected to a broker!')\r\n logging.debug('Subscribing to topic: %s', mqtt_config['topic'])\r\n client.subscribe(mqtt_config['topic'])\r\n\r\ndef on_message(client, userdata, message):\r\n decoded_message = message.payload.decode()\r\n logging.debug('%s', decoded_message)\r\n\r\n send_data_to_firebase(json.loads(decoded_message))\r\n\r\nwhile True:\r\n client.on_connect = on_connect\r\n client.on_message = on_message\r\n client.loop_forever()", "sub_path": "src/mqtt_subscriber_to_firebase.py", "file_name": "mqtt_subscriber_to_firebase.py", "file_ext": "py", "file_size_in_byte": 4361, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 16, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 17, "usage_type": "call"}, {"api_name": "logging.handlers.RotatingFileHandler", "line_number": 19, "usage_type": "call"}, {"api_name": "logging.handlers", "line_number": 19, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 27, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 27, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 30, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 30, "usage_type": "attribute"}, {"api_name": "yaml.load", "line_number": 33, "usage_type": "call"}, {"api_name": "yaml.FullLoader", "line_number": 33, "usage_type": "attribute"}, {"api_name": "pyrebase.initialize_app", "line_number": 46, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 56, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 61, "usage_type": "call"}, {"api_name": "threading.Timer", "line_number": 64, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 90, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 107, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 107, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client.Client", "line_number": 117, "usage_type": "call"}, {"api_name": "paho.mqtt.client", "line_number": 117, "usage_type": "name"}, {"api_name": "logging.debug", "line_number": 123, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 124, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 129, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 131, "usage_type": "call"}]}
+{"seq_id": "313405567", "text": "from functools import wraps\n\nfrom py2store.base import Store\nfrom py2store.persisters.couchdb_w_couchdb import CouchDbPersister\nfrom py2store.util import lazyprop\n\n\nclass CouchDbStore(Store):\n def clear(self):\n super(CouchDbStore, self).clear()\n\n @wraps(CouchDbPersister.__init__)\n def __init__(self, *args, **kwargs):\n persister = CouchDbPersister(*args, **kwargs)\n super().__init__(persister)\n\n\nclass CouchDbTupleKeyStore(CouchDbStore):\n \"\"\"\n CouchDbStore using tuple keys.\n\n >>> s = CouchDbTupleKeyStore(key_fields=('_id', 'user'))\n >>> k = (1234, 'user')\n >>> v = {'name': 'bob', 'age': 42}\n >>> if k in s: # deleting all docs in tmp\n ... del s[k]\n >>> assert (k in s) == False # see that key is not in store (and testing __contains__)\n >>> orig_length = len(s)\n >>> s[k] = v\n >>> assert len(s) == orig_length + 1\n >>> assert k in list(s)\n >>> assert s[k] == v\n >>> assert s.get(k) == v\n >>> assert v in list(s.values())\n >>> assert (k in s) == True # testing __contains__ again\n >>> del s[k]\n >>> assert len(s) == orig_length\n \"\"\"\n\n @lazyprop\n def _key_fields(self):\n return self.store._key_fields\n\n def _id_of_key(self, k):\n return {field: field_val for field, field_val in zip(self._key_fields, k)}\n\n def _key_of_id(self, _id):\n return tuple(_id[x] for x in self._key_fields)\n\n\ndef test_couchdb_store(s=CouchDbStore(), k=None, v=None):\n if k is None:\n k = {'_id': 'foo'}\n if v is None:\n v = {'val': 'bar'}\n if k in s: # deleting all docs in tmp\n del s[k]\n assert (k in s) is False # see that key is not in store (and testing __contains__)\n orig_length = len(s)\n s[k] = v\n assert len(s) == orig_length + 1\n assert k in list(s)\n assert s[k] == v\n assert s.get(k) == v\n assert v in list(s.values())\n assert (k in s) is True # testing __contains__ again\n del s[k]\n assert len(s) == 0\n\n # tuple as key test\n s = CouchDbTupleKeyStore(key_fields=('_id', 'user'))\n k = (1234, 'user')\n v = {'name': 'bob', 'age': 42}\n if k in s: # deleting all docs in tmp\n del s[k]\n assert (k in s) is False # see that key is not in store (and testing __contains__)\n orig_length = len(s)\n s[k] = v\n assert len(s) == orig_length + 1\n assert k in list(s)\n assert s[k] == v\n assert s.get(k) == v\n assert v in list(s.values())\n assert (k in s) is True # testing __contains__ again\n del s[k]\n assert len(s) == orig_length\n\n\nif __name__ == '__main__':\n test_couchdb_store()\n", "sub_path": "py2store/stores/couchdb_store.py", "file_name": "couchdb_store.py", "file_ext": "py", "file_size_in_byte": 2602, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "py2store.base.Store", "line_number": 8, "usage_type": "name"}, {"api_name": "py2store.persisters.couchdb_w_couchdb.CouchDbPersister", "line_number": 14, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 12, "usage_type": "call"}, {"api_name": "py2store.persisters.couchdb_w_couchdb.CouchDbPersister.__init__", "line_number": 12, "usage_type": "attribute"}, {"api_name": "py2store.persisters.couchdb_w_couchdb.CouchDbPersister", "line_number": 12, "usage_type": "name"}, {"api_name": "py2store.util.lazyprop", "line_number": 40, "usage_type": "name"}]}
+{"seq_id": "255151759", "text": "from datetime import datetime, timezone\n\nimport hypothesis.strategies as strategies\nimport pytest\nfrom hypothesis import given\n\nfrom quart.wrappers.response import Response\n\n\n@pytest.mark.asyncio\nasync def test_response_body() -> None:\n response = Response(b'Body')\n assert b'Body' == (await response.get_data()) # type: ignore\n # Fetch again to ensure it isn't exhausted\n assert b'Body' == (await response.get_data()) # type: ignore\n\n\ndef test_response_cache_control() -> None:\n response = Response(b'Body')\n response.cache_control.max_age = 2\n assert response.headers['Cache-Control'] == 'max-age=2'\n response.cache_control.no_cache = True\n assert response.headers['Cache-Control'] == 'max-age=2,no-cache'\n\n\n@given(\n value=strategies.datetimes(\n timezones=strategies.just(timezone.utc), min_value=datetime(1900, 1, 1),\n ),\n)\n@pytest.mark.parametrize('header', ['date', 'expires', 'last_modified', 'retry_after'])\ndef test_datetime_headers(header: str, value: datetime) -> None:\n response = Response(b'Body')\n value = value.replace(microsecond=0)\n setattr(response, header, value)\n assert response.headers.get(header.title().replace('_', '-'))\n assert getattr(response, header) == value\n", "sub_path": "tests/wrappers/test_response.py", "file_name": "test_response.py", "file_ext": "py", "file_size_in_byte": 1245, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "quart.wrappers.response.Response", "line_number": 12, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 10, "usage_type": "attribute"}, {"api_name": "quart.wrappers.response.Response", "line_number": 19, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "name"}, {"api_name": "quart.wrappers.response.Response", "line_number": 33, "usage_type": "call"}, {"api_name": "hypothesis.given", "line_number": 26, "usage_type": "call"}, {"api_name": "hypothesis.strategies.datetimes", "line_number": 27, "usage_type": "call"}, {"api_name": "hypothesis.strategies", "line_number": 27, "usage_type": "name"}, {"api_name": "hypothesis.strategies.just", "line_number": 28, "usage_type": "call"}, {"api_name": "hypothesis.strategies", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.timezone.utc", "line_number": 28, "usage_type": "attribute"}, {"api_name": "datetime.timezone", "line_number": 28, "usage_type": "name"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 31, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 31, "usage_type": "attribute"}]}
+{"seq_id": "200531385", "text": "'''Extract long-term probabilistic prediction result'''\nimport numpy as np\nnp.random.seed(1337)\nimport keras\nfrom keras.models import load_model\nimport h5py\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import np_utils\nimport pandas as pd\nimport os\nimport csv\nimport os.path\nimport math\nfrom time import *\n#from function_time_demo import *\nfrom pandas import read_csv\nfrom sklearn.preprocessing import MinMaxScaler\nimport time as tttt\nimport datetime\n#from interpolate_9_5_ccx_function import *\nimport sys\n#from micaps_function import *\nimport datetime as dt\ndef local2utc(local_st):\n\t'''convert local time to UTC'''\n\ttime_struct = tttt.mktime(local_st.timetuple())\n\tutc_st = dt.datetime.utcfromtimestamp(time_struct)\n\treturn utc_st\ndef utc2local(utc_st):\n\t'''convert UTC to local time'''\n\tnow_stamp = tttt.time()\n\tlocal_time = dt.datetime.fromtimestamp(now_stamp)\n\tutc_time = dt.datetime.utcfromtimestamp(now_stamp)\n\toffset = local_time - utc_time\n\tlocal_st = utc_st + offset\n\treturn local_st\n\n# create a log file\nname = os.path.dirname(__file__)\na = os.path.abspath(name)\nabsu = a+'/'\nfsock = open(absu+'4_10_p_error.log', 'a')\nsys.stderr = fsock\nsa = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\nef = open(absu+'4_10_p_error.log', 'a')\nef.write('*****************'+str(sa)+'*****************'+'\\n')\nef.close()\nstart = tttt.clock()\nsa = tttt.strftime(\"%Y%m%d%H\", tttt.localtime())\n#print('begin:',tttt.strftime(\"%Y%m%d%H\", tttt.localtime()))\nlocaltime = tttt.asctime(tttt.localtime(tttt.time()))\ntime_now = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\n\n# get time\ninital_time = tttt.strftime(\"%Y%m%d%H%M\", tttt.localtime())\ntoday = datetime.date.today()\nyesterday = today - datetime.timedelta(days = 1)\n#if int(inital_time[-4:]) < 420 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'00'\n#elif int(inital_time[-4:]) < 1720 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'12'\n#elif int(inital_time[-4:]) >= 1720 and int(inital_time[-4:-2])%6 == 0:\n#\tqibao = str(today)[:4]+str(today)[5:7]+str(today)[8:10]+'00'\n#else:\n#\tquit()\nif int(inital_time[-4:]) < 520 :\n\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'00'\nelif int(inital_time[-4:]) < 1720:\n\tqibao = str(yesterday)[:4]+str(yesterday)[5:7]+str(yesterday)[8:10]+'12'\nelse:\n\tqibao = str(today)[:4]+str(today)[5:7]+str(today)[8:10]+'00'\n#print('#',qibao)\n#qibao = '2018030512'\naaa = str(qibao)\nbbb = dt.datetime(int(aaa[:4]),int(aaa[4:6]), int(aaa[6:8]), int(aaa[8:10]))\ntimeaaa = utc2local(bbb)\nqibao_local = str(timeaaa)[:4]+str(timeaaa)[5:7]+str(timeaaa)[8:10]+str(timeaaa)[11:13]\n#qibao = '2017080412'#test\nte = str(inital_time)[:4]+'-'+str(inital_time)[4:6]+'-'+str(inital_time)[6:8]+\\\n'-'+str(inital_time)[8:10]\ninital_time_list = pd.date_range(te,periods = 40,freq = '6h').tolist()\n\n# create standard time series\ntime_list = []\nfor i in range(len(inital_time_list)):\n\ttime_list.append(str(inital_time_list[i])[:4]+str(inital_time_list[i])[5:7]+\\\n\tstr(inital_time_list[i])[8:10]+str(inital_time_list[i])[11:13])\n\n# read path from file\ndir_f = open(absu+'4_10_p.txt','r')\ndir_ff = dir_f.readlines()\npool_name = dir_ff[0].strip('\\n')\nover_name = dir_ff[1].strip('\\n')\nos.system('mkdir '+eval(over_name)+inital_time[:-2])\n\n# extract\ntry:\n\tfor i in range(len(time_list)):\n\t\tos.system('cp '+eval(pool_name)+qibao_local+'/'+time_list[i]+'finish.txt'+\\\n\t\t' '+eval(over_name)+inital_time[:-2]+'/')\nexcept:\n\t#print(time_list[i])\n\tpass\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "sub_path": "fjfog_v1.1_contain_EN_annotation/4_10_p/4_10_p.py", "file_name": "4_10_p.py", "file_ext": "py", "file_size_in_byte": 3591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.random.seed", "line_number": 3, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 3, "usage_type": "attribute"}, {"api_name": "time.mktime", "line_number": 27, "usage_type": "call"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 28, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 33, "usage_type": "attribute"}, {"api_name": "datetime.datetime.utcfromtimestamp", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 34, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 44, "usage_type": "attribute"}, {"api_name": "time.strftime", "line_number": 45, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 45, "usage_type": "call"}, {"api_name": "time.clock", "line_number": 49, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 50, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 50, "usage_type": "call"}, {"api_name": "time.asctime", "line_number": 52, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 52, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 53, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 53, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 56, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 56, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 57, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 57, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 58, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "call"}, {"api_name": "pandas.date_range", "line_number": 82, "usage_type": "call"}, {"api_name": "os.system", "line_number": 95, "usage_type": "call"}, {"api_name": "os.system", "line_number": 100, "usage_type": "call"}]}
+{"seq_id": "264594162", "text": "import sys\nfrom threading import Thread\nfrom PyQt5 import QtSvg\nfrom PyQt5.QtCore import pyqtSlot, QProcess, Qt, QRect\nfrom PyQt5.QtGui import QKeySequence, QTextCursor, QPainter, QColor, QTextFormat\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QTextEdit, QFileDialog, QAction, QPlainTextEdit, QGridLayout, QDialog, QLabel, QMainWindow, QMdiArea, QMdiSubWindow, QShortcut, QTabWidget\nimport xml.etree.ElementTree as ET\nfrom io import StringIO, BytesIO\nimport syntax\n\nfrom ViewerWindow import ViewerWindow\nfrom ScriptWindow import ScriptWindow\nfrom OutputWindow import OutputWindow\n#from dataframe_viewer import DataFrameViewer\n#from pandasgui import show as DataFrameViewer\nfrom guipandas.widgets.dataframe_viewer import DataFrameViewer\n\nimport pandas as pd\n\ndef register_all_namespaces(filename):\n namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])\n for ns in namespaces:\n ET.register_namespace(ns, namespaces[ns])\n\nclass MainWindow(QMainWindow):\n count = 0\n linecount = 0\n maxLine = 100\n\n def __init__(self, parent = None):\n super(MainWindow, self).__init__(parent)\n self.item0 = BytesIO()\n\n self.mdi = QMdiArea()\n self.setCentralWidget(self.mdi)\n bar = self.menuBar()\n\n file = bar.addMenu(\"File\")\n file.addAction(\"New\")\n file.addAction(\"cascade\")\n file.addAction(\"Tiled\")\n file.triggered[QAction].connect(self.windowaction)\n self.setWindowTitle(\"Camphor\")\n\n MainWindow.count += 1\n self.output_window = OutputWindow()\n self.mdi.addSubWindow(self.output_window)\n\n MainWindow.count += 1\n self.script_window = ScriptWindow()\n self.mdi.addSubWindow(self.script_window)\n\n MainWindow.count += 1\n self.viewer_window = ViewerWindow()\n self.mdi.addSubWindow(self.viewer_window)\n\n #MainWindow.count += 1\n #self.spread_sheet = SpreadSheetWidget()\n #self.mdi.addSubWindow(self.spread_sheet)\n\n headers = [\"000\", \"001\", \"002\"]\n tableData0 = [\n ['abc',100,200],\n ['fff',130,260],\n ['jjj',190,300],\n ['ppp',700,500],\n ['yyy',800,900]\n ]\n\n #model = MyTableModel(tableData0, headers)\n table_df = pd.DataFrame(tableData0, columns=headers)\n\n MainWindow.count += 1\n self.dataframe_viewer = DataFrameViewer(table_df)\n self.mdi.addSubWindow(self.dataframe_viewer)\n\n # QProcess object for external app\n self.process = QProcess(self)\n self.process.readyReadStandardOutput.connect(lambda: self.dataReady(\"std\"))\n self.process.readyReadStandardError.connect(lambda: self.dataReady(\"error\"))\n self.process.finished.connect(lambda: self.update_svg())\n\n #Connect Slots\n self.script_window.button_exec.clicked.connect(lambda: self.run_script())\n self.script_window.button_read.clicked.connect(lambda: self.read_svg())\n #self.viewer_window.button_save.clicked.connect(lambda: self.save_svg())\n\n #Assign Shortcuts\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+R\"), self)\n self.shortcut_update.activated.connect(lambda: self.run_script())\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+O\"), self)\n self.shortcut_update.activated.connect(lambda: self.read_svg())\n self.shortcut_update = QShortcut(QKeySequence(\"Ctrl+S\"), self)\n self.shortcut_update.activated.connect(lambda: self.save_svg())\n\n def windowaction(self, q):\n if q.text() == \"cascade\":\n self.mdi.cascadeSubWindows()\n\n if q.text() == \"Tiled\":\n self.mdi.tileSubWindows()\n\n @pyqtSlot()\n def read_svg(self):\n print(\"READ\")\n self.script_window.fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')\n if self.script_window.fname[0]:\n # import script metadata\n svg_tree = ET.parse(self.script_window.fname[0])\n root = svg_tree.getroot()\n for metadata in root.findall(\"{http://www.w3.org/2000/svg}metadata\"):\n for metadatum in metadata:\n if metadatum.tag == \"{https://korintje.com}script\":\n self.script_window.edit.setPlainText(metadatum.text)\n break\n self.run_script()\n\n # Parse original .svg\n print(self.script_window.fname[0])\n original_svg_tree = ET.parse(self.script_window.fname[0])\n original_root = original_svg_tree.getroot()\n for og in original_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"{http://www.inkscape.org/namespaces/inkscape}groupmode\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}groupmode\"] == \"layer\":\n if \"{http://www.inkscape.org/namespaces/inkscape}label\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}label\"] == \"Layer_mpl\":\n original_root.remove(og)\n register_all_namespaces(self.script_window.fname[0])\n original_svg_tree.write(\"bkg_temp.svg\", encoding=\"UTF-8\", xml_declaration=True)\n self.update_bkg(\"bkg_temp.svg\")\n\n @pyqtSlot()\n def run_script(self):\n self.output_window.stdout.clear()\n script = self.script_window.edit.toPlainText()\n self.process.start('python',['-c', script])\n self.viewer_window.button_save.clicked.connect(lambda: self.save_svg())\n\n @pyqtSlot()\n def update_svg(self):\n self.viewer_window.view.load(\"temp.svg\")\n\n @pyqtSlot()\n def dataReady(self,err_or_std):\n cursor = self.output_window.stdout.textCursor()\n cursor.movePosition(cursor.End)\n if err_or_std == \"std\":\n message = self.process.readAllStandardOutput().data().decode(\"utf8\")\n self.output_window.stdout.setTextColor(QColor(48, 255, 48))\n else: #if err_or_std == \"error\":\n message = self.process.readAllStandardError().data().decode(\"utf8\")\n self.output_window.stdout.setTextColor(QColor(255, 48, 48))\n self.output_window.stdout.insertPlainText(message)\n cursor.insertBlock()\n #self.output_window.setTopLevelWindow()\n\n @pyqtSlot()\n def update_bkg(self, filename):\n self.viewer_window.bkg.load(filename)\n\n @pyqtSlot()\n def save_svg(self):\n self.run_script()\n # Parse original .svg\n if self.script_window.fname[0]:\n print(self.script_window.fname[0])\n original_svg_tree = ET.parse(self.script_window.fname[0])\n original_root = original_svg_tree.getroot()\n for og in original_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"{http://www.inkscape.org/namespaces/inkscape}groupmode\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}groupmode\"] == \"layer\":\n if \"{http://www.inkscape.org/namespaces/inkscape}label\" in og.attrib and og.attrib[\"{http://www.inkscape.org/namespaces/inkscape}label\"] == \"Layer_mpl\":\n original_root.remove(og)\n\n # Insert modified .svg into the original .svg\n modified_svg_tree = ET.parse(\"temp.svg\")\n modified_root = modified_svg_tree.getroot()\n for mg in modified_root.findall(\"{http://www.w3.org/2000/svg}g\"):\n if \"id\" in mg.attrib and mg.attrib[\"id\"] == \"figure_1\":\n mg.set(\"inkscape:groupmode\", \"layer\")\n mg.set(\"inkscape:label\", \"Layer_mpl\")\n original_root.append(mg)\n print(\"done\")\n\n # Update the script in the metadata\n for metadata in original_root.findall(\"{http://www.w3.org/2000/svg}metadata\"):\n for metadatum in metadata:\n print(metadatum.tag)\n if metadatum.tag == \"{https://korintje.com}script\":\n metadatum.text = self.script_window.edit.toPlainText()\n print(metadatum.text)\n break\n\n register_all_namespaces(self.script_window.fname[0])\n original_svg_tree.write(\"mod_test2.svg\", encoding=\"UTF-8\", xml_declaration=True)\n\ndef main():\n app = QApplication(sys.argv)\n ex = MainWindow()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 8401, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "xml.etree.ElementTree.iterparse", "line_number": 21, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 21, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.register_namespace", "line_number": 23, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 23, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 25, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 32, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMdiArea", "line_number": 34, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 42, "usage_type": "name"}, {"api_name": "OutputWindow.OutputWindow", "line_number": 46, "usage_type": "call"}, {"api_name": "ScriptWindow.ScriptWindow", "line_number": 50, "usage_type": "call"}, {"api_name": "ViewerWindow.ViewerWindow", "line_number": 54, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 71, "usage_type": "call"}, {"api_name": "guipandas.widgets.dataframe_viewer.DataFrameViewer", "line_number": 74, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.QProcess", "line_number": 78, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QShortcut", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QKeySequence", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QShortcut", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QKeySequence", "line_number": 91, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QShortcut", "line_number": 93, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QKeySequence", "line_number": 93, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getOpenFileName", "line_number": 106, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 106, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 109, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 109, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 120, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 120, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 103, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 130, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 137, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 147, "usage_type": "call"}, {"api_name": "PyQt5.QtGui.QColor", "line_number": 150, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 141, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 155, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 165, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 165, "usage_type": "name"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 173, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 173, "usage_type": "name"}, {"api_name": "PyQt5.QtCore.pyqtSlot", "line_number": 159, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 195, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 195, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 198, "usage_type": "call"}]}
+{"seq_id": "91958688", "text": "#!/usr/bin/env python3\n#\n# Copyright (c) 2018-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport argparse\nimport platform\nimport re\nfrom pathlib import Path\n\n\ndef is_linux() -> bool:\n return platform.system() == \"Linux\"\n\n\ndef valid_typeshed(typeshed_path: str) -> str:\n path = Path(typeshed_path).absolute() / \"stdlib\"\n if path.is_dir():\n return typeshed_path\n raise ValueError(\n \"The provided typeshed directory is not in the expected format: \\\n It does not contain a 'stdlib' directory.\"\n )\n\n\ndef valid_version(version: str) -> str:\n pattern = re.compile(r\"^[0-9]+\\.[0-9]+\\.[0-9]+$\")\n if pattern.match(version):\n return version\n raise ValueError(\"Invalid version format.\")\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser(description=\"Build a PyPi Package.\")\n parser.add_argument(\"--typeshed-path\", type=valid_typeshed, required=True)\n parser.add_argument(\"--version\", type=valid_version, required=True)\n\n _ = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "scripts/build_pypi_package.py", "file_name": "build_pypi_package.py", "file_ext": "py", "file_size_in_byte": 1150, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "platform.system", "line_number": 15, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 19, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 29, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 36, "usage_type": "call"}]}
+{"seq_id": "482524614", "text": "'''\nThe purpose of this Helper file is to have all the utility functions necessary \nfor the recommendation engine so that the main ipynb file can be short and clutter free.\nThis also provides a chance to decouple the codes so that if anything needs to be modified,\nit can be done without having to rerun the main ipynb files.\n'''\n#importing all required libraries\nimport pandas as pd\nimport re\nimport nltk\nimport spacy\nimport en_core_web_sm\nnlp = en_core_web_sm.load()\nfrom spacy.matcher import PhraseMatcher\nimport os\nimport matplotlib.pyplot as plt\n\n\n'''\nThe import_dataset function imports the UpdatedResumeDataSet4.csv file\ncontaining the Resumes and the broad category it belings to.\nWe are randomly generating First Names and Last Names add adding it to the\ndataset for the purpose of our analyses.\n'''\ndef import_dataset():\n df_in = pd.read_csv('UpdatedResumeDataSet4.csv' ,encoding='utf-8')\n #generate random names\n from random import shuffle, seed\n from faker.providers.person.en import Provider\n\n first_names = list(set(Provider.first_names))\n last_names = list(set(Provider.last_names)) ##generates only 473 last names \n last_names = last_names*3 #so its is multipled 3 times to make more. There maybe some repetitions but its ok\n fn = first_names[0:962] #we need only 962 first names\n ln = last_names[0:962] #we need only 962 last names\n #Add the name columns to the df_in dataframe\n df_in['First_Name']=fn\n df_in['Last_Name']=ln\n return df_in\n'''\nclean_resume cleans the Resume column of the dataset\nThis is a text cleaning function that is capable of\nremoving commonly seen special characters\nextra whitespaces,typos,\n'''\ndef clean_resume(text):\n import re\n text = re.sub('http\\S+\\s*', ' ', text) # remove URLs\n text = re.sub('RT|cc', ' ', text) # remove RT and cc\n text = re.sub('#\\S+', '', text) # remove hashtags\n text = re.sub('@\\S+', ' ', text) # remove mentions\n text = re.sub('[%s]' % re.escape(\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"), ' ', text) # remove punctuations\n text = re.sub(r'[^\\x00-\\x7f]',r' ', text) \n text = re.sub('\\s+', ' ', text) # remove extra whitespace\n text = re.sub('machine learning', 'ML', text)\n text = re.sub('Machine Learning', 'ML', text)\n text = re.sub('Deep Learning', 'DL', text)\n text = re.sub('data', 'Data', text)\n text = re.sub('Hr', 'HR', text)\n text = re.sub('4HANA', 'HANA', text)\n text = re.sub('JAVA','Java',text)\n text = re.sub('Reduce', 'MapReduce', text)\n text = re.sub('TESTING', 'Selenium', text)\n text = re.sub('learnerEducation', 'Junior', text)\n text = re.sub('Exprience', 'experience', text)\n return text\n\n#We were unable to subset or iterate the df_in using the values in the 'Category' column\n#The following code will help fix that issue\ndef fix_subset(df_in):\n skills=[]\n name=[]\n category=[]\n for i in range(0,962):\n category.append(df_in.Category[i])\n skills.append(df_in.cleaned_resume[i])\n fname = df_in.First_Name[i]\n lname = df_in.Last_Name[i]\n name.append(fname+' '+lname)\n df_data = pd.DataFrame.from_records({'Name':name,'Category':category,'Resume':skills})\n return df_data\n\n'''\nCompared to using regular expressions on raw text, spaCy’s rule-based matcher engines \nand components not only let you find the words and phrases you’re looking for \n– they also give you access to the tokens within the document and their relationships.\n This means you can easily access and analyze the surrounding tokens, merge spans into single tokens\n or add entries to the named entities \n source: https://spacy.io/usage/rule-based-matching#matcher\n'''\n#matching phrases from the keywords using spacy\ndef match_keywords(skills,keywords):\n phrase_matcher = PhraseMatcher(nlp.vocab,attr=\"LOWER\")\n kw = [nlp.make_doc(skills) for text in keywords ]\n phrase_matcher.add(\"keywords\",None,*kw)\n doc = nlp(skills)\n matches = phrase_matcher(doc)\n found = []\n for match_id,start,end in matches:\n found += doc[start:end]\n return found\n'''\nSkill_profile function works in tandem with the match_keywords function\nOnce the PhraseMatcher finds occurances of the input keywords in the resumes,\nit returns a list containing the word occurances.\n\nWe use this to build a skill profile, by counting the number of times each keyword \nis found in a particular resume. The 'name' is the name of the candidate\nextracted from the df_data sataset.\n''' \n#build an skill set profile from the matched phrases text\ndef skill_profile(found,name,keywords):\n #print('building a profile for '+name) #for debugging purposes\n keyword_dict=dict.fromkeys(keywords,0)\n keyword_dict['Name']=name\n #print(keyword_dict)\n for i in found:\n j=str(i)\n if j in keywords:\n keyword_dict[j]+=1\n return keyword_dict\n\n'''\nThe helper_function() calls the match_keywords and the skill_profile\nfunctions in order to get each candidate's skill profile based on the \nrequirement given by the client\n'''\ndef helper_function(df_data,keywords):\n skill_count_list = []\n for i in range(0,len(df_data)):\n skills = df_data.Resume[i]\n name = df_data.Name[i]\n found = match_keywords(skills,keywords)\n skill_count=skill_profile(found,name,keywords)\n skill_count_list.append(skill_count)\n return skill_count_list\n'''plot_skillset_profile plots a horizontal stacked barchart \nusing the skill set count and names of the candidates to \nhelp us visually understand which candidate is releavnt to our\nrequirement\n'''\ndef plot_skillset_profile(df_plot):\n import matplotlib.pyplot as plt\n plt.rcParams.update({'font.size': 10})\n ax = df_plot[:200].plot.barh(title=\"Resume keywords by category\", legend=True, figsize=(20,150), stacked=True)\n labels = []\n for j in df_plot[:200].columns:\n for i in df_plot[:200].index:\n label = str(j)+\": \" + str(df_plot[:200].loc[i][j])\n labels.append(label)\n patches = ax.patches\n for label, rect in zip(labels, patches):\n width = rect.get_width()\n if width > 0:\n x = rect.get_x()\n y = rect.get_y()\n height = rect.get_height()\n ax.text(x + width/2., y + height/2., label, ha='center',va='center',color =\"white\",weight='bold')\n return plt.show()\n\n'''\nThe experience_chunk and the experience_idx functions\nattempt to get a gist of the experience profile of any\ncandidate the client is interested in\n'''\ndef experience_chunks(df_data,name):\n candidate_skills=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n sents = nltk.sent_tokenize(candidate_skills)\n chunk_style = \"chunk:{}\"\n parser = nltk.RegexpParser(chunk_style)\n for i in sents:\n words = nltk.word_tokenize(i)\n pos = nltk.pos_tag(words)\n chunks = parser.parse(pos)\n for i in chunks.subtrees():\n if i.label()==\"chunk\":\n print(i.leaves())\n\ndef experience_idx(df_data,name):\n candidate_skills=[]\n exp_profile=[]\n words=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n words = nltk.word_tokenize(candidate_skills)\n for idx,word in enumerate(words):\n if word == 'experience' and words[idx+1]=='Less':\n profile = [words[idx-2],words[idx-1],word,words[idx+1],words[idx+2],words[idx+3],words[idx+4]]\n exp_profile.append(profile)\n elif word == 'experience':\n profile = [words[idx-2],words[idx-1],word,words[idx+1],words[idx+2]]\n exp_profile.append(profile)\n print(exp_profile)\n\n'''\nThe recommendations functions gives the top 10\ncandidates of each skill set the client requires\n'''\ndef recommendations(df_skills,keywords):\n candidate_list =[]\n for i in keywords:\n temp_df = df_skills.nlargest(10,i)\n tmp_names = temp_df['Name']\n for name in tmp_names:\n skills_dict = {'Skill':i,'Candidates':name}\n candidate_list.append(skills_dict)\n #df_reco = pd.DataFrame(candidate_list,index=range(0,len(candidate_list)))\n return candidate_list \n\n'''\nthe find_common_words functions helps find the buzzwords present in the resumes\nThis can be very useful for training models,for searching skill sets,understanding\nthe skillsets in each industry in general\n'''\nfrom nltk.corpus import stopwords\nfrom nltk import WordNetLemmatizer\nimport string\ndef find_common_words(df_resume):\n oneSetOfStopWords = set(stopwords.words('english')+['``',\"''\"])\n totalWords =[]\n Sentences = df_resume['Resume'].values\n cleanedSentences = \"\"\n lem=WordNetLemmatizer()\n noise=['Details', 'Exprience', 'months', 'company', 'description', '1', 'year','36',\n 'Even','offered','frauds','hiding','compared','per','students','web','well',\n 'Chat','effective','leadership','Nov','member','along','January','Less', 'Skill','Maharashtra',\n '6','I','project','like', 'India','Pradesh','January','Jan','February','Feb','March','Mar','April','Apr',\n 'May','June','Jun','Jul','July','Aug','August','Sep','September','Oct','October','Nov','November',\n 'Dec','December','using','monthsCompany','B','C', 'Mumbai', 'Pune', 'Arts', 'A', 'application','24',\n 'various', 'Responsibilities','Nagpur','development','Management','Technologies','The',\n 'Company','University','British','Designed','Board','new','time','E','May','Ltd','Team',\n 'M','Development','etc','Used','2','Council','team','School','Working','work','Developed',\n 'Made','given','2016','Sri','required','Learning','Skills','related','involved','3','My',\n '4','Trust','2015','across','This','Lanka','Windows','Adichunchanagiri','Bahadarpur','Gorbanjara',\n 'Indira','Priyadarshini','Gandhi','shreekiaspack', '3staragroproducts','luckystationery','ALAMURI',\n 'HINDI','Madhya','36','providing','2014','university','board','State','Jalgaon','From','Nashik','Kisan',\n 'In','Sr','College','Parola','Dist','www','requirement','com','Higher','State','e','In','used','co','SYSTEM',\n 'gives','CURRICULUM','S','OF','LTD','turn','Bengaluru','Karnataka','LifeKonnect','Co','insurance','civil',\n 'Aurus','Participated','gathering','meetings','Reviewed','met','February','2006','different','indent',\n '0','S','understanding','writing','Nanded','R','K','KVA','10','28','30','agreed','providing','Timely',\n '2nd','level','Dubai','7','8','e','Helping','300','Su','QATAR','17','5','9','11','12','13','14','15',\n '26','INDIA','5','Thai','27','10','allow','2012','2008','Sr','Pvt','2900s','12D','Asha','2000','2003',\n 'ount','Delhi','process','OF','16','30','v10','v11','v12','Pvt','within','9','5','map','Map','Size',\n 'used','Unit','9','5','help','also','Inc','yes','June','good','Tech','Like','House','CBSE','Nov','Based',\n '05','07','Asst','To','2010','Pia','Hiralal','Your','2009','2017','Hard','2011','basically','even','P','done',\n 'Smt','2004','Apeksha','Naharkar','Thanks','Regards','Talreja','Hindi','Bajaj','Chandrapur','32','alleviate',\n 'continued','Savitribai','ANGEL','BOARD','INSTITUTE','Good','Kranti','ountabilities','Thakur','And','P','mumbai','com',\n 'Quick','SURYA','kranti','maharastra','PRAKASH','MUMBAI','RAJDEVI','whether', 'Of', 'By', 'ept', 'admin', 'At', 'provide', \n 'As', 'via', 'For', 'With', 'For', 'During', 'On','Of','24x7','201','20','31','7Education','1year','one','800','3000','2D',\n '3D', '3DEducation', '2007', '120','96', '48', '2013', 'Two', '625', '5000', '2000A', '450', '110V', '55', '33', '22','18', \n '101', '11gEducation', '01','2019', '3years','017', '2018', '20656', '2005']\n for i in range(0,len(df_resume)):\n cleanedText = clean_resume(Sentences[i])\n cleanedSentences += cleanedText\n cleanwords = nltk.word_tokenize(cleanedText)\n requiredWords=[lem.lemmatize(x) for x in cleanwords]\n for word in requiredWords:\n if word not in oneSetOfStopWords and word not in string.punctuation and word not in noise:\n totalWords.append(word)\n \n wordfreqdist = nltk.FreqDist(totalWords)\n mostcommon = wordfreqdist.most_common(200)\n return mostcommon\n\n'''\nThe plot_common_skills functions helps us visualize the \nbuzzwords in the resume using a wordcount - word barchart\n'''\ndef plot_common_skills(common_words,category):\n import plotly.express as px \n skill=[]\n count=[]\n for i in common_words:\n skill.append(i[0])\n count.append(i[1])\n fig = px.histogram(x=skill,y=count, template='simple_white',title= category+' buzzwords')\n fig.update_xaxes(categoryorder='total descending').update_xaxes(title='Buzzwords',tickangle = 45)\n fig.update_yaxes(title='Word count')\n return fig.show()\n'''\nThe experience_rake method extracts import phrases from the candidate's\nresume using the RAKE library.\nThese phrases are then evaluated to see if any words of interest are present.\nIn our case, we would like to know the experience,skills,trainings etc\n'''\nimport RAKE\nimport operator\ndef experience_rake(df_data,name,keywords):\n candidate_skills=[]\n phrases=[]\n for i in range(0,len(df_data)):\n if df_data.Name[i] == name:\n candidate_skills = str(df_data.Resume[i])\n r = RAKE.Rake('SmartStoplist.txt')\n keyphrases = r.run(candidate_skills)\n for phrase,score in keyphrases:\n if score > 3:\n phrases.append(phrase)\n for i in phrases:\n words = i.split(\" \")\n for j in keywords:\n if j.lower() in words:\n print(i)\n\n\n\n", "sub_path": "RecommendationHelper_Final.py", "file_name": "RecommendationHelper_Final.py", "file_ext": "py", "file_size_in_byte": 13875, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "en_core_web_sm.load", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 26, "usage_type": "call"}, {"api_name": "faker.providers.person.en.Provider.first_names", "line_number": 31, "usage_type": "attribute"}, {"api_name": "faker.providers.person.en.Provider", "line_number": 31, "usage_type": "name"}, {"api_name": "faker.providers.person.en.Provider.last_names", "line_number": 32, "usage_type": "attribute"}, {"api_name": "faker.providers.person.en.Provider", "line_number": 32, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 48, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 49, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 50, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 51, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 52, "usage_type": "call"}, {"api_name": "re.escape", "line_number": 52, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 53, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 54, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 55, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 56, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 57, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 58, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 59, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 60, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 61, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 62, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 63, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 64, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 65, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_records", "line_number": 80, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 80, "usage_type": "attribute"}, {"api_name": "spacy.matcher.PhraseMatcher", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams.update", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.rcParams", "line_number": 144, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "nltk.sent_tokenize", "line_number": 171, "usage_type": "call"}, {"api_name": "nltk.RegexpParser", "line_number": 173, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 175, "usage_type": "call"}, {"api_name": "nltk.pos_tag", "line_number": 176, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 189, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords.words", "line_number": 223, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 223, "usage_type": "name"}, {"api_name": "nltk.WordNetLemmatizer", "line_number": 227, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 259, "usage_type": "call"}, {"api_name": "string.punctuation", "line_number": 262, "usage_type": "attribute"}, {"api_name": "nltk.FreqDist", "line_number": 265, "usage_type": "call"}, {"api_name": "plotly.express.histogram", "line_number": 280, "usage_type": "call"}, {"api_name": "plotly.express", "line_number": 280, "usage_type": "name"}, {"api_name": "RAKE.Rake", "line_number": 298, "usage_type": "call"}]}
+{"seq_id": "151742459", "text": "import sys, getopt, urllib.parse, requests, time\n\nclass KiwiRequest:\n \n api_url = \"https://api.skypicker.com/flights\"\n bookingapi_url= \"http://128.199.48.38:8080/booking\"\n \n def __init__(self):\n #set Defaults parameters\n self.params = {'v':'3','partner':'picky','partner_market':'us','bags':'0','typeFlight':'oneway'}\n \n #make the api call and return the booking ID of the best flight du to the params\n def procces_request(self):\n \n request_url = self.api_url\n #required fields\n if set(['dateFrom','flyFrom','to']).issubset(set(self.params.keys())): \n response = requests.get(request_url,params = self.params)\n try: \n json = response.json()\n if response.status_code == requests.codes.ok:\n #parse json a make the booking api call\n if(json[\"data\"] is not None):\n flight = json[\"data\"][0]\n payload = {\n \"booking_token\":flight[\"booking_token\"], \n \"bags\":self.params[\"bags\"],\n \"currency\":\"EUR\",\n \"passengers\": [{\n \"firstName\":\"David\",\n \"lastName\":\"Ling\",\n \"email\":\"david.ling@post.cz\",\n \"documentID\":\"123456789\",\n \"birthday\":\"1997-08-25T15:33:00\",\n \"title\":\"Mr\"\n }]\n }\n response = requests.post(self.bookingapi_url,json=payload)\n if(response.status_code == requests.codes.ok):\n json = response.json()\n return json[\"pnr\"] \n except:\n return 0\n return 0\n\n \n \ndef main():\n\n #--cheapest --fastest colision\n type_arg = False \n \n #try to take parameters from command line\n try:\n opts, args = getopt.getopt(sys.argv[1:],\"\",[\"date=\",\"from=\",\"to=\",\"return=\",\"bags=\",\"one-way\",\"cheapest\",\"fastest\"])\n except:\n return 0\n \n #new KiwiRequest instance\n request = KiwiRequest() \n \n #loop through arguments and add them to request parameters\n for opt,arg in opts:\n if opt == \"--date\":\n #Convert yyyy-mm-dd format to dd%2Fmm%2Fyyyy format\n date = time.strptime(arg,\"%Y-%m-%d\")\n request.params['dateFrom'] = request.params['dateTo'] = urllib.parse.quote(time.strftime(\"%d/%m/%Y\",date))\n elif opt == \"--from\":\n request.params['flyFrom'] = arg\n elif opt == \"--to\":\n request.params['to'] = arg\n elif opt == \"--return\":\n request.params['daysInDestinationTo'] = request.params['daysInDestinationFrom'] = arg\n request.params['typeFlight'] = 'round'\n elif opt == \"--bags\":\n request.params['bags'] = arg\n elif opt == \"--fastest\":\n #--fastest and --cheapest together\n if type_arg:\n return 0\n else:\n request.params[\"sort\"] = \"duration\"\n type_arg = True\n elif opt == \"--cheapest\":\n #--fastest and --cheapest together\n if type_arg:\n return 0\n \n\n #make the api call\n return request.procces_request()\n \nprint(main())\n \n ", "sub_path": "book_flight.py", "file_name": "book_flight.py", "file_ext": "py", "file_size_in_byte": 3526, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 18, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 21, "usage_type": "attribute"}, {"api_name": "requests.post", "line_number": 38, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 39, "usage_type": "attribute"}, {"api_name": "getopt.getopt", "line_number": 55, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 55, "usage_type": "attribute"}, {"api_name": "time.strptime", "line_number": 66, "usage_type": "call"}, {"api_name": "urllib.parse.parse.quote", "line_number": 67, "usage_type": "call"}, {"api_name": "urllib.parse.parse", "line_number": 67, "usage_type": "attribute"}, {"api_name": "urllib.parse", "line_number": 67, "usage_type": "name"}, {"api_name": "time.strftime", "line_number": 67, "usage_type": "call"}]}
+{"seq_id": "617813215", "text": "# coding: utf-8\n\n\"\"\"\nManagementInterface.py\n\n The Clear BSD License\n\n Copyright (c) – 2016, NetApp, Inc. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\n NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nfrom pprint import pformat\nfrom six import iteritems\n\n\nclass ManagementInterface(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n def __init__(self):\n \"\"\"\n ManagementInterface - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n \"\"\"\n self.swagger_types = {\n 'interface_name': 'str', # (required parameter)\n 'channel': 'int', # (required parameter)\n 'speed': 'int', # (required parameter)\n 'ip': 'int', # (required parameter)\n 'alias': 'str', # (required parameter)\n 'mac_addr': 'str', # (required parameter)\n 'gateway_ip': 'int', # (required parameter)\n 'subnet_mask': 'int', # (required parameter)\n 'bootp_used': 'bool', # (required parameter)\n 'rlogin_enabled': 'bool', # (required parameter)\n 'reserved1': 'str', \n 'setup_error': 'bool', # (required parameter)\n 'reserved2': 'str', \n 'interface_ref': 'str', # (required parameter)\n 'link_status': 'str', # (required parameter)\n 'ipv4_enabled': 'bool', # (required parameter)\n 'ipv4_address': 'str', # (required parameter)\n 'ipv4_subnet_mask': 'str', # (required parameter)\n 'ipv4_address_config_method': 'str', # (required parameter)\n 'ipv6_enabled': 'bool', # (required parameter)\n 'ipv6_local_address': 'IpV6AddressData', # (required parameter)\n 'ipv6_port_static_routable_address': 'IpV6AddressData', # (required parameter)\n 'ipv6_port_routable_addresses': 'list[IpV6AddressData]', # (required parameter)\n 'ipv6_address_config_method': 'str', # (required parameter)\n 'full_duplex': 'bool', # (required parameter)\n 'supported_speed_settings': 'list[str]', # (required parameter)\n 'configured_speed_setting': 'str', # (required parameter)\n 'current_speed': 'str', # (required parameter)\n 'physical_location': 'Location', # (required parameter)\n 'ipv4_gateway_address': 'str', \n 'controller_ref': 'str', \n 'controller_slot': 'int', \n 'dns_properties': 'ControllerDNSProperties', \n 'ntp_properties': 'ControllerNTPProperties', \n 'id': 'str'\n }\n\n self.attribute_map = {\n 'interface_name': 'interfaceName', # (required parameter)\n 'channel': 'channel', # (required parameter)\n 'speed': 'speed', # (required parameter)\n 'ip': 'ip', # (required parameter)\n 'alias': 'alias', # (required parameter)\n 'mac_addr': 'macAddr', # (required parameter)\n 'gateway_ip': 'gatewayIp', # (required parameter)\n 'subnet_mask': 'subnetMask', # (required parameter)\n 'bootp_used': 'bootpUsed', # (required parameter)\n 'rlogin_enabled': 'rloginEnabled', # (required parameter)\n 'reserved1': 'reserved1', \n 'setup_error': 'setupError', # (required parameter)\n 'reserved2': 'reserved2', \n 'interface_ref': 'interfaceRef', # (required parameter)\n 'link_status': 'linkStatus', # (required parameter)\n 'ipv4_enabled': 'ipv4Enabled', # (required parameter)\n 'ipv4_address': 'ipv4Address', # (required parameter)\n 'ipv4_subnet_mask': 'ipv4SubnetMask', # (required parameter)\n 'ipv4_address_config_method': 'ipv4AddressConfigMethod', # (required parameter)\n 'ipv6_enabled': 'ipv6Enabled', # (required parameter)\n 'ipv6_local_address': 'ipv6LocalAddress', # (required parameter)\n 'ipv6_port_static_routable_address': 'ipv6PortStaticRoutableAddress', # (required parameter)\n 'ipv6_port_routable_addresses': 'ipv6PortRoutableAddresses', # (required parameter)\n 'ipv6_address_config_method': 'ipv6AddressConfigMethod', # (required parameter)\n 'full_duplex': 'fullDuplex', # (required parameter)\n 'supported_speed_settings': 'supportedSpeedSettings', # (required parameter)\n 'configured_speed_setting': 'configuredSpeedSetting', # (required parameter)\n 'current_speed': 'currentSpeed', # (required parameter)\n 'physical_location': 'physicalLocation', # (required parameter)\n 'ipv4_gateway_address': 'ipv4GatewayAddress', \n 'controller_ref': 'controllerRef', \n 'controller_slot': 'controllerSlot', \n 'dns_properties': 'dnsProperties', \n 'ntp_properties': 'ntpProperties', \n 'id': 'id'\n }\n\n self._interface_name = None\n self._channel = None\n self._speed = None\n self._ip = None\n self._alias = None\n self._mac_addr = None\n self._gateway_ip = None\n self._subnet_mask = None\n self._bootp_used = None\n self._rlogin_enabled = None\n self._reserved1 = None\n self._setup_error = None\n self._reserved2 = None\n self._interface_ref = None\n self._link_status = None\n self._ipv4_enabled = None\n self._ipv4_address = None\n self._ipv4_subnet_mask = None\n self._ipv4_address_config_method = None\n self._ipv6_enabled = None\n self._ipv6_local_address = None\n self._ipv6_port_static_routable_address = None\n self._ipv6_port_routable_addresses = None\n self._ipv6_address_config_method = None\n self._full_duplex = None\n self._supported_speed_settings = None\n self._configured_speed_setting = None\n self._current_speed = None\n self._physical_location = None\n self._ipv4_gateway_address = None\n self._controller_ref = None\n self._controller_slot = None\n self._dns_properties = None\n self._ntp_properties = None\n self._id = None\n\n @property\n def interface_name(self):\n \"\"\"\n Gets the interface_name of this ManagementInterface.\n Name of the Ethernet port, as reported by the controller.\n\n :return: The interface_name of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._interface_name\n\n @interface_name.setter\n def interface_name(self, interface_name):\n \"\"\"\n Sets the interface_name of this ManagementInterface.\n Name of the Ethernet port, as reported by the controller.\n\n :param interface_name: The interface_name of this ManagementInterface.\n :type: str\n \"\"\"\n self._interface_name = interface_name\n\n @property\n def channel(self):\n \"\"\"\n Gets the channel of this ManagementInterface.\n The channel number of this Ethernet interface.\n\n :return: The channel of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._channel\n\n @channel.setter\n def channel(self, channel):\n \"\"\"\n Sets the channel of this ManagementInterface.\n The channel number of this Ethernet interface.\n\n :param channel: The channel of this ManagementInterface.\n :type: int\n \"\"\"\n self._channel = channel\n\n @property\n def speed(self):\n \"\"\"\n Gets the speed of this ManagementInterface.\n The speed of the interface, as currently configured, in Mbit/sec.\n\n :return: The speed of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._speed\n\n @speed.setter\n def speed(self, speed):\n \"\"\"\n Sets the speed of this ManagementInterface.\n The speed of the interface, as currently configured, in Mbit/sec.\n\n :param speed: The speed of this ManagementInterface.\n :type: int\n \"\"\"\n self._speed = speed\n\n @property\n def ip(self):\n \"\"\"\n Gets the ip of this ManagementInterface.\n The 32-bit IP protocol address assigned to the interface.\n\n :return: The ip of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._ip\n\n @ip.setter\n def ip(self, ip):\n \"\"\"\n Sets the ip of this ManagementInterface.\n The 32-bit IP protocol address assigned to the interface.\n\n :param ip: The ip of this ManagementInterface.\n :type: int\n \"\"\"\n self._ip = ip\n\n @property\n def alias(self):\n \"\"\"\n Gets the alias of this ManagementInterface.\n An ASCII string that identifies the alias name for the interface; this name is presumed to be associated with the IP protocol address.\n\n :return: The alias of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._alias\n\n @alias.setter\n def alias(self, alias):\n \"\"\"\n Sets the alias of this ManagementInterface.\n An ASCII string that identifies the alias name for the interface; this name is presumed to be associated with the IP protocol address.\n\n :param alias: The alias of this ManagementInterface.\n :type: str\n \"\"\"\n self._alias = alias\n\n @property\n def mac_addr(self):\n \"\"\"\n Gets the mac_addr of this ManagementInterface.\n An ASCII string representation of the globally-unique 48-bit MAC address assigned to the Ethernet interface.\n\n :return: The mac_addr of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._mac_addr\n\n @mac_addr.setter\n def mac_addr(self, mac_addr):\n \"\"\"\n Sets the mac_addr of this ManagementInterface.\n An ASCII string representation of the globally-unique 48-bit MAC address assigned to the Ethernet interface.\n\n :param mac_addr: The mac_addr of this ManagementInterface.\n :type: str\n \"\"\"\n self._mac_addr = mac_addr\n\n @property\n def gateway_ip(self):\n \"\"\"\n Gets the gateway_ip of this ManagementInterface.\n IP address of the gateway.\n\n :return: The gateway_ip of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._gateway_ip\n\n @gateway_ip.setter\n def gateway_ip(self, gateway_ip):\n \"\"\"\n Sets the gateway_ip of this ManagementInterface.\n IP address of the gateway.\n\n :param gateway_ip: The gateway_ip of this ManagementInterface.\n :type: int\n \"\"\"\n self._gateway_ip = gateway_ip\n\n @property\n def subnet_mask(self):\n \"\"\"\n Gets the subnet_mask of this ManagementInterface.\n Network subnet mask.\n\n :return: The subnet_mask of this ManagementInterface.\n :rtype: int\n :required/optional: required\n \"\"\"\n return self._subnet_mask\n\n @subnet_mask.setter\n def subnet_mask(self, subnet_mask):\n \"\"\"\n Sets the subnet_mask of this ManagementInterface.\n Network subnet mask.\n\n :param subnet_mask: The subnet_mask of this ManagementInterface.\n :type: int\n \"\"\"\n self._subnet_mask = subnet_mask\n\n @property\n def bootp_used(self):\n \"\"\"\n Gets the bootp_used of this ManagementInterface.\n Bootpserver used to get network parameters.\n\n :return: The bootp_used of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._bootp_used\n\n @bootp_used.setter\n def bootp_used(self, bootp_used):\n \"\"\"\n Sets the bootp_used of this ManagementInterface.\n Bootpserver used to get network parameters.\n\n :param bootp_used: The bootp_used of this ManagementInterface.\n :type: bool\n \"\"\"\n self._bootp_used = bootp_used\n\n @property\n def rlogin_enabled(self):\n \"\"\"\n Gets the rlogin_enabled of this ManagementInterface.\n True if rlogin sessions are allowed.\n\n :return: The rlogin_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._rlogin_enabled\n\n @rlogin_enabled.setter\n def rlogin_enabled(self, rlogin_enabled):\n \"\"\"\n Sets the rlogin_enabled of this ManagementInterface.\n True if rlogin sessions are allowed.\n\n :param rlogin_enabled: The rlogin_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._rlogin_enabled = rlogin_enabled\n\n @property\n def reserved1(self):\n \"\"\"\n Gets the reserved1 of this ManagementInterface.\n\n\n :return: The reserved1 of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._reserved1\n\n @reserved1.setter\n def reserved1(self, reserved1):\n \"\"\"\n Sets the reserved1 of this ManagementInterface.\n\n\n :param reserved1: The reserved1 of this ManagementInterface.\n :type: str\n \"\"\"\n self._reserved1 = reserved1\n\n @property\n def setup_error(self):\n \"\"\"\n Gets the setup_error of this ManagementInterface.\n Set to true if there is a configuration error.\n\n :return: The setup_error of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._setup_error\n\n @setup_error.setter\n def setup_error(self, setup_error):\n \"\"\"\n Sets the setup_error of this ManagementInterface.\n Set to true if there is a configuration error.\n\n :param setup_error: The setup_error of this ManagementInterface.\n :type: bool\n \"\"\"\n self._setup_error = setup_error\n\n @property\n def reserved2(self):\n \"\"\"\n Gets the reserved2 of this ManagementInterface.\n\n\n :return: The reserved2 of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._reserved2\n\n @reserved2.setter\n def reserved2(self, reserved2):\n \"\"\"\n Sets the reserved2 of this ManagementInterface.\n\n\n :param reserved2: The reserved2 of this ManagementInterface.\n :type: str\n \"\"\"\n self._reserved2 = reserved2\n\n @property\n def interface_ref(self):\n \"\"\"\n Gets the interface_ref of this ManagementInterface.\n The unique identifier for a given instance of this structure.\n\n :return: The interface_ref of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._interface_ref\n\n @interface_ref.setter\n def interface_ref(self, interface_ref):\n \"\"\"\n Sets the interface_ref of this ManagementInterface.\n The unique identifier for a given instance of this structure.\n\n :param interface_ref: The interface_ref of this ManagementInterface.\n :type: str\n \"\"\"\n self._interface_ref = interface_ref\n\n @property\n def link_status(self):\n \"\"\"\n Gets the link_status of this ManagementInterface.\n The status of the network link for this interface.\n\n :return: The link_status of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._link_status\n\n @link_status.setter\n def link_status(self, link_status):\n \"\"\"\n Sets the link_status of this ManagementInterface.\n The status of the network link for this interface.\n\n :param link_status: The link_status of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"none\", \"up\", \"down\", \"failed\", \"__UNDEFINED\"]\n if link_status not in allowed_values:\n raise ValueError(\n \"Invalid value for `link_status`, must be one of {0}\"\n .format(allowed_values)\n )\n self._link_status = link_status\n\n @property\n def ipv4_enabled(self):\n \"\"\"\n Gets the ipv4_enabled of this ManagementInterface.\n True if IPV4 is enabled for this interface; otherwise false.\n\n :return: The ipv4_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._ipv4_enabled\n\n @ipv4_enabled.setter\n def ipv4_enabled(self, ipv4_enabled):\n \"\"\"\n Sets the ipv4_enabled of this ManagementInterface.\n True if IPV4 is enabled for this interface; otherwise false.\n\n :param ipv4_enabled: The ipv4_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._ipv4_enabled = ipv4_enabled\n\n @property\n def ipv4_address(self):\n \"\"\"\n Gets the ipv4_address of this ManagementInterface.\n The IPV4 address for the interface.\n\n :return: The ipv4_address of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_address\n\n @ipv4_address.setter\n def ipv4_address(self, ipv4_address):\n \"\"\"\n Sets the ipv4_address of this ManagementInterface.\n The IPV4 address for the interface.\n\n :param ipv4_address: The ipv4_address of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_address = ipv4_address\n\n @property\n def ipv4_subnet_mask(self):\n \"\"\"\n Gets the ipv4_subnet_mask of this ManagementInterface.\n The IPV4 subnet mask for the interface.\n\n :return: The ipv4_subnet_mask of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_subnet_mask\n\n @ipv4_subnet_mask.setter\n def ipv4_subnet_mask(self, ipv4_subnet_mask):\n \"\"\"\n Sets the ipv4_subnet_mask of this ManagementInterface.\n The IPV4 subnet mask for the interface.\n\n :param ipv4_subnet_mask: The ipv4_subnet_mask of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_subnet_mask = ipv4_subnet_mask\n\n @property\n def ipv4_address_config_method(self):\n \"\"\"\n Gets the ipv4_address_config_method of this ManagementInterface.\n The method by which the IPV4 address information is configured.\n\n :return: The ipv4_address_config_method of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv4_address_config_method\n\n @ipv4_address_config_method.setter\n def ipv4_address_config_method(self, ipv4_address_config_method):\n \"\"\"\n Sets the ipv4_address_config_method of this ManagementInterface.\n The method by which the IPV4 address information is configured.\n\n :param ipv4_address_config_method: The ipv4_address_config_method of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"configDhcp\", \"configStatic\", \"__UNDEFINED\"]\n if ipv4_address_config_method not in allowed_values:\n raise ValueError(\n \"Invalid value for `ipv4_address_config_method`, must be one of {0}\"\n .format(allowed_values)\n )\n self._ipv4_address_config_method = ipv4_address_config_method\n\n @property\n def ipv6_enabled(self):\n \"\"\"\n Gets the ipv6_enabled of this ManagementInterface.\n True if IPV6 is enabled for this interface; otherwise false.\n\n :return: The ipv6_enabled of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._ipv6_enabled\n\n @ipv6_enabled.setter\n def ipv6_enabled(self, ipv6_enabled):\n \"\"\"\n Sets the ipv6_enabled of this ManagementInterface.\n True if IPV6 is enabled for this interface; otherwise false.\n\n :param ipv6_enabled: The ipv6_enabled of this ManagementInterface.\n :type: bool\n \"\"\"\n self._ipv6_enabled = ipv6_enabled\n\n @property\n def ipv6_local_address(self):\n \"\"\"\n Gets the ipv6_local_address of this ManagementInterface.\n The IPV6 local address for the interface and associated data.\n\n :return: The ipv6_local_address of this ManagementInterface.\n :rtype: IpV6AddressData\n :required/optional: required\n \"\"\"\n return self._ipv6_local_address\n\n @ipv6_local_address.setter\n def ipv6_local_address(self, ipv6_local_address):\n \"\"\"\n Sets the ipv6_local_address of this ManagementInterface.\n The IPV6 local address for the interface and associated data.\n\n :param ipv6_local_address: The ipv6_local_address of this ManagementInterface.\n :type: IpV6AddressData\n \"\"\"\n self._ipv6_local_address = ipv6_local_address\n\n @property\n def ipv6_port_static_routable_address(self):\n \"\"\"\n Gets the ipv6_port_static_routable_address of this ManagementInterface.\n The IPV6 static routable address for the interface and associated data.\n\n :return: The ipv6_port_static_routable_address of this ManagementInterface.\n :rtype: IpV6AddressData\n :required/optional: required\n \"\"\"\n return self._ipv6_port_static_routable_address\n\n @ipv6_port_static_routable_address.setter\n def ipv6_port_static_routable_address(self, ipv6_port_static_routable_address):\n \"\"\"\n Sets the ipv6_port_static_routable_address of this ManagementInterface.\n The IPV6 static routable address for the interface and associated data.\n\n :param ipv6_port_static_routable_address: The ipv6_port_static_routable_address of this ManagementInterface.\n :type: IpV6AddressData\n \"\"\"\n self._ipv6_port_static_routable_address = ipv6_port_static_routable_address\n\n @property\n def ipv6_port_routable_addresses(self):\n \"\"\"\n Gets the ipv6_port_routable_addresses of this ManagementInterface.\n The set of IPV6 port routable addresses for the interface.\n\n :return: The ipv6_port_routable_addresses of this ManagementInterface.\n :rtype: list[IpV6AddressData]\n :required/optional: required\n \"\"\"\n return self._ipv6_port_routable_addresses\n\n @ipv6_port_routable_addresses.setter\n def ipv6_port_routable_addresses(self, ipv6_port_routable_addresses):\n \"\"\"\n Sets the ipv6_port_routable_addresses of this ManagementInterface.\n The set of IPV6 port routable addresses for the interface.\n\n :param ipv6_port_routable_addresses: The ipv6_port_routable_addresses of this ManagementInterface.\n :type: list[IpV6AddressData]\n \"\"\"\n self._ipv6_port_routable_addresses = ipv6_port_routable_addresses\n\n @property\n def ipv6_address_config_method(self):\n \"\"\"\n Gets the ipv6_address_config_method of this ManagementInterface.\n The method by which the IPV6 address information is configured for the interface.\n\n :return: The ipv6_address_config_method of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._ipv6_address_config_method\n\n @ipv6_address_config_method.setter\n def ipv6_address_config_method(self, ipv6_address_config_method):\n \"\"\"\n Sets the ipv6_address_config_method of this ManagementInterface.\n The method by which the IPV6 address information is configured for the interface.\n\n :param ipv6_address_config_method: The ipv6_address_config_method of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"configStatic\", \"configStateless\", \"__UNDEFINED\"]\n if ipv6_address_config_method not in allowed_values:\n raise ValueError(\n \"Invalid value for `ipv6_address_config_method`, must be one of {0}\"\n .format(allowed_values)\n )\n self._ipv6_address_config_method = ipv6_address_config_method\n\n @property\n def full_duplex(self):\n \"\"\"\n Gets the full_duplex of this ManagementInterface.\n If set to true, the interface is operating in full duplex mode; otherwise, it is operating in half-duplex mode.\n\n :return: The full_duplex of this ManagementInterface.\n :rtype: bool\n :required/optional: required\n \"\"\"\n return self._full_duplex\n\n @full_duplex.setter\n def full_duplex(self, full_duplex):\n \"\"\"\n Sets the full_duplex of this ManagementInterface.\n If set to true, the interface is operating in full duplex mode; otherwise, it is operating in half-duplex mode.\n\n :param full_duplex: The full_duplex of this ManagementInterface.\n :type: bool\n \"\"\"\n self._full_duplex = full_duplex\n\n @property\n def supported_speed_settings(self):\n \"\"\"\n Gets the supported_speed_settings of this ManagementInterface.\n Support speed setting for interface\n\n :return: The supported_speed_settings of this ManagementInterface.\n :rtype: list[str]\n :required/optional: required\n \"\"\"\n return self._supported_speed_settings\n\n @supported_speed_settings.setter\n def supported_speed_settings(self, supported_speed_settings):\n \"\"\"\n Sets the supported_speed_settings of this ManagementInterface.\n Support speed setting for interface\n\n :param supported_speed_settings: The supported_speed_settings of this ManagementInterface.\n :type: list[str]\n \"\"\"\n self._supported_speed_settings = supported_speed_settings\n\n @property\n def configured_speed_setting(self):\n \"\"\"\n Gets the configured_speed_setting of this ManagementInterface.\n Configured setting for the interface.\n\n :return: The configured_speed_setting of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._configured_speed_setting\n\n @configured_speed_setting.setter\n def configured_speed_setting(self, configured_speed_setting):\n \"\"\"\n Sets the configured_speed_setting of this ManagementInterface.\n Configured setting for the interface.\n\n :param configured_speed_setting: The configured_speed_setting of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"speedNone\", \"speedAutoNegotiated\", \"speed10MbitHalfDuplex\", \"speed10MbitFullDuplex\", \"speed100MbitHalfDuplex\", \"speed100MbitFullDuplex\", \"speed1000MbitHalfDuplex\", \"speed1000MbitFullDuplex\", \"__UNDEFINED\"]\n if configured_speed_setting not in allowed_values:\n raise ValueError(\n \"Invalid value for `configured_speed_setting`, must be one of {0}\"\n .format(allowed_values)\n )\n self._configured_speed_setting = configured_speed_setting\n\n @property\n def current_speed(self):\n \"\"\"\n Gets the current_speed of this ManagementInterface.\n Current speed of the interface.\n\n :return: The current_speed of this ManagementInterface.\n :rtype: str\n :required/optional: required\n \"\"\"\n return self._current_speed\n\n @current_speed.setter\n def current_speed(self, current_speed):\n \"\"\"\n Sets the current_speed of this ManagementInterface.\n Current speed of the interface.\n\n :param current_speed: The current_speed of this ManagementInterface.\n :type: str\n \"\"\"\n allowed_values = [\"speedUnknown\", \"speed1gig\", \"speed2gig\", \"speed4gig\", \"speed10gig\", \"speed15gig\", \"speed3gig\", \"speed10meg\", \"speed100meg\", \"speed2pt5Gig\", \"speed5gig\", \"speed20gig\", \"speed30gig\", \"speed60gig\", \"speed8gig\", \"speed6gig\", \"speed40gig\", \"speed16gig\", \"speed56gig\", \"speed12gig\", \"speed25gig\", \"speed32gig\", \"speed100gig\", \"__UNDEFINED\"]\n if current_speed not in allowed_values:\n raise ValueError(\n \"Invalid value for `current_speed`, must be one of {0}\"\n .format(allowed_values)\n )\n self._current_speed = current_speed\n\n @property\n def physical_location(self):\n \"\"\"\n Gets the physical_location of this ManagementInterface.\n The physical location of the Ethernet interface. The parent reference in Location identifies the physical component (e.g., controller or host card) where the interface circuitry is located, and the position field is a firmware-assigned 1-relative number signifying \\\"1st ethernet interface relative to the parent,\\\" \\\"2nd ethernet interface relative to the parent,\\\" etc. This \\\"interface number\\\" is independent of the interface's channel association.\n\n :return: The physical_location of this ManagementInterface.\n :rtype: Location\n :required/optional: required\n \"\"\"\n return self._physical_location\n\n @physical_location.setter\n def physical_location(self, physical_location):\n \"\"\"\n Sets the physical_location of this ManagementInterface.\n The physical location of the Ethernet interface. The parent reference in Location identifies the physical component (e.g., controller or host card) where the interface circuitry is located, and the position field is a firmware-assigned 1-relative number signifying \\\"1st ethernet interface relative to the parent,\\\" \\\"2nd ethernet interface relative to the parent,\\\" etc. This \\\"interface number\\\" is independent of the interface's channel association.\n\n :param physical_location: The physical_location of this ManagementInterface.\n :type: Location\n \"\"\"\n self._physical_location = physical_location\n\n @property\n def ipv4_gateway_address(self):\n \"\"\"\n Gets the ipv4_gateway_address of this ManagementInterface.\n\n\n :return: The ipv4_gateway_address of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._ipv4_gateway_address\n\n @ipv4_gateway_address.setter\n def ipv4_gateway_address(self, ipv4_gateway_address):\n \"\"\"\n Sets the ipv4_gateway_address of this ManagementInterface.\n\n\n :param ipv4_gateway_address: The ipv4_gateway_address of this ManagementInterface.\n :type: str\n \"\"\"\n self._ipv4_gateway_address = ipv4_gateway_address\n\n @property\n def controller_ref(self):\n \"\"\"\n Gets the controller_ref of this ManagementInterface.\n\n\n :return: The controller_ref of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._controller_ref\n\n @controller_ref.setter\n def controller_ref(self, controller_ref):\n \"\"\"\n Sets the controller_ref of this ManagementInterface.\n\n\n :param controller_ref: The controller_ref of this ManagementInterface.\n :type: str\n \"\"\"\n self._controller_ref = controller_ref\n\n @property\n def controller_slot(self):\n \"\"\"\n Gets the controller_slot of this ManagementInterface.\n\n\n :return: The controller_slot of this ManagementInterface.\n :rtype: int\n :required/optional: optional\n \"\"\"\n return self._controller_slot\n\n @controller_slot.setter\n def controller_slot(self, controller_slot):\n \"\"\"\n Sets the controller_slot of this ManagementInterface.\n\n\n :param controller_slot: The controller_slot of this ManagementInterface.\n :type: int\n \"\"\"\n self._controller_slot = controller_slot\n\n @property\n def dns_properties(self):\n \"\"\"\n Gets the dns_properties of this ManagementInterface.\n\n\n :return: The dns_properties of this ManagementInterface.\n :rtype: ControllerDNSProperties\n :required/optional: optional\n \"\"\"\n return self._dns_properties\n\n @dns_properties.setter\n def dns_properties(self, dns_properties):\n \"\"\"\n Sets the dns_properties of this ManagementInterface.\n\n\n :param dns_properties: The dns_properties of this ManagementInterface.\n :type: ControllerDNSProperties\n \"\"\"\n self._dns_properties = dns_properties\n\n @property\n def ntp_properties(self):\n \"\"\"\n Gets the ntp_properties of this ManagementInterface.\n\n\n :return: The ntp_properties of this ManagementInterface.\n :rtype: ControllerNTPProperties\n :required/optional: optional\n \"\"\"\n return self._ntp_properties\n\n @ntp_properties.setter\n def ntp_properties(self, ntp_properties):\n \"\"\"\n Sets the ntp_properties of this ManagementInterface.\n\n\n :param ntp_properties: The ntp_properties of this ManagementInterface.\n :type: ControllerNTPProperties\n \"\"\"\n self._ntp_properties = ntp_properties\n\n @property\n def id(self):\n \"\"\"\n Gets the id of this ManagementInterface.\n\n\n :return: The id of this ManagementInterface.\n :rtype: str\n :required/optional: optional\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"\n Sets the id of this ManagementInterface.\n\n\n :param id: The id of this ManagementInterface.\n :type: str\n \"\"\"\n self._id = id\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n if self is None:\n return None\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if self is None or other is None:\n return None\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n\n", "sub_path": "netapp/santricity/models/v2/management_interface.py", "file_name": "management_interface.py", "file_ext": "py", "file_size_in_byte": 36722, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "six.iteritems", "line_number": 992, "usage_type": "call"}, {"api_name": "pprint.pformat", "line_number": 1016, "usage_type": "call"}]}
+{"seq_id": "533704191", "text": "\"\"\"\nTrain the ESIM model on the preprocessed SNLI dataset.\n\"\"\"\n# Aurelien Coet, 2018.\n\nimport os\nimport argparse\nimport pickle\nimport torch\nimport json\nimport time\nimport matplotlib.pyplot as plt\nimport torch.nn as nn\nimport sys\nsys.path.insert(0, \"../../\")\nfrom torch.utils.data import DataLoader\nfrom esim.data import NLIDataset\nfrom esim.utils import correct_predictions\nfrom esim.model import ESIM\nfrom utils import train, validate\n\ndef test(model, num_classes, dataloader, print_Confusion=False):\n \"\"\"\n Test the accuracy of a model on some labelled test dataset.\n\n Args:\n model: The torch module on which testing must be performed.\n dataloader: A DataLoader object to iterate over some dataset.\n\n Returns:\n batch_time: The average time to predict the classes of a batch.\n total_time: The total time to process the whole dataset.\n accuracy: The accuracy of the model on the input data.\n \"\"\"\n # Switch the model to eval mode.\n model.eval()\n device = model.device\n\n time_start = time.time()\n batch_time = 0.0\n correct_preds = 0.0\n\n confusion = torch.zeros(num_classes, num_classes, dtype=torch.long)\n\n # Deactivate autograd for evaluation.\n with torch.no_grad():\n for batch in dataloader:\n batch_start = time.time()\n\n # Move input and output data to the GPU if one is used.\n premises = batch[\"premise\"].to(device)\n premises_lengths = batch[\"premise_length\"].to(device)\n hypotheses = batch[\"hypothesis\"].to(device)\n hypotheses_lengths = batch[\"hypothesis_length\"].to(device)\n labels = batch[\"label\"].to(device)\n\n _, probs = model(premises,\n premises_lengths,\n hypotheses,\n hypotheses_lengths)\n\n _, pred = probs.max(dim=1)\n for j in range(pred.size()[0]):\n confusion[pred[j], labels[j]] += 1\n\n correct_preds += correct_predictions(probs, labels)\n batch_time += time.time() - batch_start\n\n batch_time /= len(dataloader)\n total_time = time.time() - time_start\n accuracy = correct_preds / (len(dataloader.dataset))\n\n if print_Confusion == True:\n print(\"Confusion matrix:\")\n print(confusion)\n print(\"Report precision, recall, and f1:\")\n for i in range(confusion.size()[0]):\n p = confusion[i, i].item() / confusion[i, :].sum().item()\n r = confusion[i, i].item() / confusion[:, i].sum().item()\n f1 = 2 * p * r / (p + r)\n print(\"Label {}: {:.3f}, {:.3f}, {:.3f}\".format(i, p, r, f1))\n\n p = confusion[1, 1].item() / confusion[:, 1].sum().item()\n r = confusion[1, 1].item() / confusion[1, :].sum().item()\n f1 = 2 * p * r / (p + r)\n #print(\"Report precision, recall, and f1:\" , p, r, f1)\n return batch_time, total_time, f1, accuracy\n\n\ndef main(train_file,\n valid_file,\n test_file,\n embeddings_file,\n target_dir,\n hidden_size=300,\n dropout=0.5,\n num_classes=2,\n epochs=64,\n batch_size=32,\n lr=0.0004,\n patience=5,\n max_grad_norm=10.0,\n checkpoint=None,\n proportion=1,\n output=None):\n \"\"\"\n Train the ESIM model on the SNLI dataset.\n\n Args:\n train_file: A path to some preprocessed data that must be used\n to train the model.\n valid_file: A path to some preprocessed data that must be used\n to validate the model.\n embeddings_file: A path to some preprocessed word embeddings that\n must be used to initialise the model.\n target_dir: The path to a directory where the trained model must\n be saved.\n hidden_size: The size of the hidden layers in the model. Defaults\n to 300.\n dropout: The dropout rate to use in the model. Defaults to 0.5.\n num_classes: The number of classes in the output of the model.\n Defaults to 3.\n epochs: The maximum number of epochs for training. Defaults to 64.\n batch_size: The size of the batches for training. Defaults to 32.\n lr: The learning rate for the optimizer. Defaults to 0.0004.\n patience: The patience to use for early stopping. Defaults to 5.\n checkpoint: A checkpoint from which to continue training. If None,\n training starts from scratch. Defaults to None.\n \"\"\"\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n print(20 * \"=\", \" Preparing for training \", 20 * \"=\")\n\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n\n # -------------------- Data loading ------------------- #\n print(\"\\t* Loading training data...\")\n with open(train_file, \"rb\") as pkl:\n train_data = NLIDataset(pickle.load(pkl), proportion, isRandom=True)#training data will be shuffled first, then we will get random data of different proportion\n\n train_loader = DataLoader(train_data, shuffle=False, batch_size=batch_size)\n\n\n print(\"\\t* Loading validation data...\")\n with open(valid_file, \"rb\") as pkl:\n valid_data = NLIDataset(pickle.load(pkl))\n\n valid_loader = DataLoader(valid_data, shuffle=False, batch_size=batch_size)\n\n print(\"\\t* Loading test data...\")\n with open(test_file, \"rb\") as pkl:\n test_data = NLIDataset(pickle.load(pkl))\n\n test_loader = DataLoader(test_data, shuffle=False, batch_size=batch_size)\n\n # -------------------- Model definition ------------------- #\n print(\"\\t* Building model...\")\n with open(embeddings_file, \"rb\") as pkl:\n embeddings = torch.tensor(pickle.load(pkl), dtype=torch.float)\\\n .to(device)\n\n model = ESIM(embeddings.shape[0],\n embeddings.shape[1],\n hidden_size,\n embeddings=embeddings,\n dropout=dropout,\n num_classes=num_classes,\n device=device).to(device)\n\n # -------------------- Preparation for training ------------------- #\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,\n mode=\"max\",\n factor=0.5,\n patience=0)\n\n best_score = 0.0\n start_epoch = 1\n\n # Data for loss curves plot.\n epochs_count = []\n train_losses = []\n valid_losses = []\n\n # Continuing training from a checkpoint if one was given as argument.\n if checkpoint:\n checkpoint = torch.load(checkpoint)\n start_epoch = checkpoint[\"epoch\"] + 1\n best_score = checkpoint[\"best_score\"]\n\n print(\"\\t* Training will continue on existing model from epoch {}...\"\n .format(start_epoch))\n\n model.load_state_dict(checkpoint[\"model\"])\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n epochs_count = checkpoint[\"epochs_count\"]\n train_losses = checkpoint[\"train_losses\"]\n valid_losses = checkpoint[\"valid_losses\"]\n\n # Compute loss and accuracy before starting (or resuming) training.\n\n _, valid_loss, valid_accuracy = validate(model,\n valid_loader,\n criterion)\n print(\"\\t* Validation loss before training: {:.4f}, accuracy: {:.4f}%\"\n .format(valid_loss, (valid_accuracy*100)))\n\n # -------------------- Training epochs ------------------- #\n print(\"\\n\",\n 20 * \"=\",\n \"Training ESIM model on device: {}\".format(device),\n 20 * \"=\")\n\n patience_counter = 0\n for epoch in range(start_epoch, epochs+1):\n epochs_count.append(epoch)\n\n print(\"* Training epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = train(model,\n train_loader,\n optimizer,\n criterion,\n epoch,\n max_grad_norm)\n\n train_losses.append(epoch_loss)\n print(\"-> Training time: {:.4f}s, loss = {:.4f}, accuracy: {:.4f}%\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n\n print(\"* Validation for epoch {}:\".format(epoch))\n epoch_time, epoch_loss, epoch_accuracy = validate(model,\n valid_loader,\n criterion)\n\n valid_losses.append(epoch_loss)\n print(\"-> Valid. time: {:.4f}s, loss: {:.4f}, accuracy: {:.4f}%\\n\"\n .format(epoch_time, epoch_loss, (epoch_accuracy*100)))\n\n # Update the optimizer's learning rate with the scheduler.\n scheduler.step(epoch_accuracy)\n\n print(\"* Testing for epoch {}:\".format(epoch))\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader)\n print(\n \"-> Average batch processing time: {:.4f}s, total test time: {:.4f}s, f1: {:.4f}, accuracy: {:.4f}%\".format(\n batch_time, total_time, f1, (accuracy * 100)))\n print(20 * \"====\")\n\n\n # Early stopping on validation accuracy.\n if epoch > 2:\n if epoch_accuracy <= best_score:\n patience_counter += 1\n else:\n best_score = epoch_accuracy\n patience_counter = 0\n # Save the best model. The optimizer is not saved to avoid having\n # a checkpoint file that is too heavy to be shared. To resume\n # training from the best model, use the 'esim_*.pth.tar'\n # checkpoints instead.\n torch.save({\"epoch\": epoch,\n \"model\": model.state_dict(),\n \"best_score\": best_score,\n \"epochs_count\": epochs_count,\n \"train_losses\": train_losses,\n \"valid_losses\": valid_losses},\n os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n \n if patience_counter >= patience:\n print(\"-> Early stopping: patience limit reached, stopping...\")\n checkpoint = torch.load(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n # Retrieving model parameters from checkpoint.\n vocab_size = checkpoint[\"model\"][\"_word_embedding.weight\"].size(0)\n embedding_dim = checkpoint[\"model\"]['_word_embedding.weight'].size(1)\n hidden_size = checkpoint[\"model\"][\"_projection.0.weight\"].size(0)\n num_classes = checkpoint[\"model\"][\"_classification.4.weight\"].size(0)\n print(\"\\t* Final test...\")\n model = ESIM(vocab_size,\n embedding_dim,\n hidden_size,\n num_classes=num_classes,\n device=device).to(device)\n model.load_state_dict(checkpoint[\"model\"])\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader, print_Confusion=True)\n print(\"-> Final f1, accuracy: {:.4f}, {:.4f}%\".format(f1, accuracy * 100))\n os.remove(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n break\n if epoch == 15:\n checkpoint = torch.load(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n # Retrieving model parameters from checkpoint.\n vocab_size = checkpoint[\"model\"][\"_word_embedding.weight\"].size(0)\n embedding_dim = checkpoint[\"model\"]['_word_embedding.weight'].size(1)\n hidden_size = checkpoint[\"model\"][\"_projection.0.weight\"].size(0)\n num_classes = checkpoint[\"model\"][\"_classification.4.weight\"].size(0)\n print(\"\\t* Final test...\")\n model = ESIM(vocab_size,\n embedding_dim,\n hidden_size,\n num_classes=num_classes,\n device=device).to(device)\n model.load_state_dict(checkpoint[\"model\"])\n batch_time, total_time, f1, accuracy = test(model, num_classes, test_loader, print_Confusion=True)\n print(\"-> Final f1, accuracy: {:.4f}, {:.4f}%\".format(f1, accuracy * 100))\n os.remove(os.path.join(target_dir, output + \"_\" + str(proportion) + \"_best.pth.tar\"))\n\n\n\nif __name__ == \"__main__\":\n default_config = \"../../config/training/url_training.json\"\n\n parser = argparse.ArgumentParser(description=\"Train the ESIM model on PI\")\n parser.add_argument(\"--config\",\n default=default_config,\n help=\"Path to a json configuration file\")\n parser.add_argument(\"--checkpoint\",\n default=None,\n help=\"Path to a checkpoint file to resume training\")\n parser.add_argument(\"--proportion\", default=1, type=float,\n help=\"{Proportion of training data}\")\n parser.add_argument(\"--output\",\n default='100', type=str,\n help=\"where to Save model\")\n args = parser.parse_args()\n\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n if args.config == default_config:\n config_path = os.path.join(script_dir, args.config)\n else:\n config_path = args.config\n\n with open(os.path.normpath(config_path), 'r') as config_file:\n config = json.load(config_file)\n\n main(os.path.normpath(os.path.join(script_dir, config[\"train_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"valid_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"test_data\"])),\n os.path.normpath(os.path.join(script_dir, config[\"embeddings\"])),\n os.path.normpath(os.path.join(script_dir, config[\"target_dir\"])),\n config[\"hidden_size\"],\n config[\"dropout\"],\n config[\"num_classes\"],\n config[\"epochs\"],\n config[\"batch_size\"],\n config[\"lr\"],\n config[\"patience\"],\n config[\"max_gradient_norm\"],\n args.checkpoint,\n args.proportion,\n args.output)\n", "sub_path": "ESIM/scripts/training/main_url.py", "file_name": "main_url.py", "file_ext": "py", "file_size_in_byte": 14640, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "sys.path.insert", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.no_grad", "line_number": 46, "usage_type": "call"}, {"api_name": "time.time", "line_number": 48, "usage_type": "call"}, {"api_name": "esim.utils.correct_predictions", "line_number": 66, "usage_type": "call"}, {"api_name": "time.time", "line_number": 67, "usage_type": "call"}, {"api_name": "time.time", "line_number": 70, "usage_type": "call"}, {"api_name": "torch.device", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 130, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 130, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 134, "usage_type": "call"}, {"api_name": "os.path", "line_number": 134, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 135, "usage_type": "call"}, {"api_name": "esim.data.NLIDataset", "line_number": 140, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 142, "usage_type": "call"}, {"api_name": "esim.data.NLIDataset", "line_number": 147, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 147, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 149, "usage_type": "call"}, {"api_name": "esim.data.NLIDataset", "line_number": 153, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 153, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 160, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 160, "usage_type": "call"}, {"api_name": "torch.float", "line_number": 160, "usage_type": "attribute"}, {"api_name": "esim.model.ESIM", "line_number": 163, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 172, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 172, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 173, "usage_type": "attribute"}, {"api_name": "torch.optim.lr_scheduler.ReduceLROnPlateau", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 174, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 189, "usage_type": "call"}, {"api_name": "utils.validate", "line_number": 204, "usage_type": "call"}, {"api_name": "utils.train", "line_number": 221, "usage_type": "call"}, {"api_name": "utils.validate", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 264, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path", "line_number": 274, "usage_type": "attribute"}, {"api_name": "esim.model.ESIM", "line_number": 281, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 289, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 289, "usage_type": "call"}, {"api_name": "os.path", "line_number": 289, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 292, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 292, "usage_type": "call"}, {"api_name": "os.path", "line_number": 292, "usage_type": "attribute"}, {"api_name": "esim.model.ESIM", "line_number": 299, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 307, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 307, "usage_type": "call"}, {"api_name": "os.path", "line_number": 307, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 314, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 328, "usage_type": "call"}, {"api_name": "os.path", "line_number": 328, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 328, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 331, "usage_type": "call"}, {"api_name": "os.path", "line_number": 331, "usage_type": "attribute"}, {"api_name": "os.path.normpath", "line_number": 335, "usage_type": "call"}, {"api_name": "os.path", "line_number": 335, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 336, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 338, "usage_type": "call"}, {"api_name": "os.path", "line_number": 338, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 338, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 339, "usage_type": "call"}, {"api_name": "os.path", "line_number": 339, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 339, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 340, "usage_type": "call"}, {"api_name": "os.path", "line_number": 340, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 340, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 341, "usage_type": "call"}, {"api_name": "os.path", "line_number": 341, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 341, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 342, "usage_type": "call"}, {"api_name": "os.path", "line_number": 342, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 342, "usage_type": "call"}]}
+{"seq_id": "302701777", "text": "#from selenium.webdriver.support.ui import Select\nfrom selenium import webdriver\nimport time\n#import math\nimport os\n\ntry: \n link = \"http://suninjuly.github.io/file_input.html\"\n browser = webdriver.Chrome()\n browser.get(link)\n\n first_name_input=browser.find_element_by_css_selector(\"input[name='firstname']\")\n first_name_input.send_keys(\"Ali\")\n last_name_input=browser.find_element_by_css_selector(\"input[name='lastname']\")\n last_name_input.send_keys(\"Baba\")\n email_input=browser.find_element_by_css_selector(\"input[name='email']\")\n email_input.send_keys(\"email\")\n file_input=browser.find_element_by_css_selector(\"input#file\")\n\n # получаем путь к директории текущего исполняемого файла\n current_dir = os.path.abspath(os.path.dirname(__file__))\n\n # добавляем к этому пути имя файла\n file_path = os.path.join(current_dir, 'lesson2_2_step8_file.txt')\n\n file_input.send_keys(file_path)\n\n submit_button=browser.find_element_by_css_selector(\".btn\")\n submit_button.click()\n\n \nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(10)\n # закрываем браузер после всех манипуляций\n browser.quit()\n", "sub_path": "Scripts/Module2/lesson2_2_step8.py", "file_name": "lesson2_2_step8.py", "file_ext": "py", "file_size_in_byte": 1354, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "selenium.webdriver.Chrome", "line_number": 9, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 9, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 24, "usage_type": "call"}, {"api_name": "os.path", "line_number": 24, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 34, "usage_type": "call"}]}
+{"seq_id": "155632907", "text": "#!/usr/bin/env python3\n__author__ = 'dimv36'\nfrom argparse import ArgumentParser\nfrom os.path import abspath, curdir, exists\nfrom sys import argv\nfrom time import localtime, strftime\nfrom polib import pofile\n\nEMAIL = 'support@rusbitech.ru'\nTRANSLATOR = 'Dmitry Voronin'\n\n\ndef find_translated_message(msgid, old_po):\n for old_entry in old_po:\n if old_entry.msgid == msgid:\n return old_entry.msgstr\n return None\n\n\ndef update_metadata(new_po_file):\n metadata = new_po_file.metadata\n now = strftime('%Y-%m-%d %H:%M+0400', localtime())\n metadata['Report-Msgid-Bugs-To'] = EMAIL\n metadata['POT-Creation-Date'] = now\n metadata['PO-Revision-Date'] = now\n metadata['Last-Translator'] = '%s <%s>' % (TRANSLATOR, EMAIL)\n metadata['Language-Team'] = 'Russian <%s>' % EMAIL\n\n\ndef update_po(old_po_file_path, new_po_file_path, updated_po_file_path):\n was_update = False\n old_po = pofile(old_po_file_path)\n new_po = pofile(new_po_file_path)\n updated_po_file_path = abspath(updated_po_file_path)\n for new_entry in new_po.untranslated_entries():\n msgstr = find_translated_message(new_entry.msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n for new_entry in new_po.fuzzy_entries():\n msgstr = find_translated_message(new_entry.msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n new_entry.flags.remove('fuzzy')\n was_update = True\n for new_entry in new_po.translated_entries():\n msgid = new_entry.msgid\n msgstr = new_entry.msgstr\n if 'column' in msgid:\n msgstr = find_translated_message(msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n if msgstr is not None:\n if 'колон' in msgstr or 'Колон' in msgstr:\n msgstr = find_translated_message(msgid, old_po)\n if msgstr is not None:\n new_entry.msgstr = msgstr\n was_update = True\n if was_update:\n update_metadata(new_po)\n print('Done. New po was saved to %s' % updated_po_file_path)\n new_po.save(updated_po_file_path)\n\n\ndef get_statistic(po_file_path):\n try:\n po = pofile(po_file_path)\n print('***** Message statistic for \\'%s\\' *****' % po_file_path)\n print('translated: %d, fuzzy: %d, untranslated: %d' % (len(po.translated_entries()),\n len(po.fuzzy_entries()), len(po.untranslated_entries())))\n except OSError:\n print('Error when open file \\'%s\\': No such file' % po_file_path)\n\n\ndef check_is_path_exist(file_path):\n file_path = abspath(file_path)\n if not exists(file_path):\n print('Error: file \\'%s\\' does not exist' % abspath(file_path))\n exit(1)\n return file_path\n\n\nif __name__ == '__main__':\n arg_parser = ArgumentParser(prog=argv[0], add_help=False)\n\n subparsers = arg_parser.add_subparsers(dest='commands')\n\n update_po_parser = subparsers.add_parser('update-po')\n update_po_parser.add_argument('--old-po', action='store', required=True, help='Add path to old po file')\n update_po_parser.add_argument('--new-po', action='store', required=True, help='Add path to new po file')\n update_po_parser.add_argument('--save-as', action='store', help='Save updated po as',\n default=abspath(curdir + '/update.po'))\n\n statistic_po_parser = subparsers.add_parser('get-statistic')\n statistic_po_parser.add_argument('--po-file', action='store', required=True, help='Get statistic about po file')\n\n args = arg_parser.parse_args(argv[1:])\n if args.commands is not None:\n command = args.commands\n if command == 'update-po':\n old_po = args.old_po\n new_po = args.new_po\n save_po = args.save_as\n if old_po is not None and new_po is not None:\n old_po = check_is_path_exist(old_po)\n new_po = check_is_path_exist(new_po)\n update_po(old_po, new_po, save_po)\n else:\n update_po_parser.print_help()\n elif command == 'get-statistic':\n po_file = args.po_file\n if po_file is not None:\n po_file = check_is_path_exist(po_file)\n get_statistic(po_file)\n else:\n statistic_po_parser.print_help()\n else:\n arg_parser.print_help()\n", "sub_path": "poedit.py", "file_name": "poedit.py", "file_ext": "py", "file_size_in_byte": 4549, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "time.strftime", "line_number": 22, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 22, "usage_type": "call"}, {"api_name": "polib.pofile", "line_number": 32, "usage_type": "call"}, {"api_name": "polib.pofile", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 34, "usage_type": "call"}, {"api_name": "polib.pofile", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 77, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 79, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 85, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 85, "usage_type": "name"}, {"api_name": "os.path.abspath", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.curdir", "line_number": 93, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 98, "usage_type": "name"}]}
+{"seq_id": "253329478", "text": "# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom common.forms import BaseForm\nfrom .models import Lab\n\n\nclass LabBaseForm(BaseForm):\n\n def clean(self):\n data = super(LabBaseForm, self).clean()\n if 'investigator' in data:\n if 'members' in data and set(data['investigator']) & set(data['members']):\n self._errors[\"members\"] = self.error_class(['field value \\'investigator\\' should not interfere with the field values \\'members\\''])\n del data['members']\n if 'guests' in data and set(data['investigator']) & set(data['guests']):\n self._errors[\"guests\"] = self.error_class(['field value \\'investigator\\' should not interfere with the field values \\'guests\\''])\n del data['guests']\n return data\n\n\nclass LabForm(LabBaseForm):\n \"\"\"\n Form for create/edit laboratory\n \"\"\"\n class Meta:\n model = Lab\n fields = ('name', 'investigator', 'members', 'guests')\n\n def __init__(self, *args, **kwargs):\n super(LabForm, self).__init__(*args, **kwargs)\n self.fields['investigator'].widget.attrs['data-dependent'] = 'members,guests'\n self.fields['members'].widget.attrs['data-dependent'] = 'investigator,guests'\n self.fields['guests'].widget.attrs['data-dependent'] = 'members,investigator'\n self.user = self.initial['user']\n del self.initial['user']\n\n def clean(self):\n data = super(LabForm, self).clean()\n\n if self.instance.id and self.instance.is_member(self.user):\n if 'investigator' in self.changed_data and self.instance.investigator != data['investigator']:\n self._errors['investigator'] = self.error_class([_('You have not permission change lab\\'s investigator')])\n del data['investigator']\n return data\n", "sub_path": "apps/labs/forms.py", "file_name": "forms.py", "file_ext": "py", "file_size_in_byte": 1893, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "common.forms.BaseForm", "line_number": 9, "usage_type": "name"}, {"api_name": "models.Lab", "line_number": 28, "usage_type": "name"}, {"api_name": "django.utils.translation.ugettext_lazy", "line_number": 44, "usage_type": "call"}]}
+{"seq_id": "278567547", "text": "import json\nimport click\nfrom ..inspecting import InvalidProjectError, inspect_project\n\n\n@click.command()\ndef cli():\n \"\"\"Extract template variables from a project\"\"\"\n try:\n data = inspect_project()\n except InvalidProjectError as e:\n raise click.UsageError(str(e))\n click.echo(json.dumps(data, indent=4, sort_keys=True))\n", "sub_path": "src/pyrepo/commands/inspect.py", "file_name": "inspect.py", "file_ext": "py", "file_size_in_byte": 346, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "inspecting.inspect_project", "line_number": 10, "usage_type": "call"}, {"api_name": "inspecting.InvalidProjectError", "line_number": 11, "usage_type": "name"}, {"api_name": "click.UsageError", "line_number": 12, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 13, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 13, "usage_type": "call"}, {"api_name": "click.command", "line_number": 6, "usage_type": "call"}]}
+{"seq_id": "280296008", "text": "import logging\n\nch = logging.StreamHandler()\n# ch.setLevel(logging.DEBUG)\nch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n\ndef get_logger(name):\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n logger.addHandler(ch)\n # logger.info('avc')\n return logger\n", "sub_path": "wvv/util/log.py", "file_name": "log.py", "file_ext": "py", "file_size_in_byte": 329, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.StreamHandler", "line_number": 3, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 5, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 8, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 9, "usage_type": "attribute"}]}
+{"seq_id": "563379694", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport os\nfrom skimage.feature import local_binary_pattern\n\nMETHOD = 'uniform'\nscript_path = os.path.dirname(os.path.realpath(__file__))\n\n# settings for LBP\nradius = 2\nn_points = 2 * radius\ndataset = {}\n\n########################################\n#membaca dataset dan menyimpan ke dictionary\n\nmaps_path = r\"D:\\Teknik Informatika\\CV\\citra02\\citra02\\dataset\"\n# maps_path = os.path.join(script_path, \"dataset\")\nlistds = os.listdir(maps_path)\nnumber_files = len(listds)\n\nos.chdir(maps_path)\narr = os.listdir()\n\nj = 31\nfor i in range(number_files):\n\t\n\timage_name = arr[i]\n\timage = cv2.imread(image_name, 0)\n\tlbp = local_binary_pattern(image, n_points, radius, METHOD)\n\n\thist, _ = np.histogram(lbp, density=True, bins=6, range=(0,6))\n\n\n\tif(j==41):\n\t\tj+=1\n\telif(j==58):\n\t\tj+=2\n\n\tnrp = '21031810' + str(j)\n\n\tdataset.update({nrp : hist})\n\tj+=1\n\nj=31\n\n###############################################\n#membandingkan fitur\n\ndef match(counts):\n\tbest_score = 10\n\tbest_name = None\n\tfor key,value in dataset.items():\n\t\tscore = 0\n\t\tfor o in range(6):\n\t\t\tscore+=abs(value[o]-counts[o])\n\t\tif score < best_score:\n\t\t\tbest_score = score\n\t\t\tbest_name = key\n\treturn best_name\n\n\n# maps_path = os.path.join(script_path, \"testing01\")\nmaps_path = r\"D:\\Teknik Informatika\\CV\\citra02\\citra02\\testing02\"\nlistds = os.listdir(maps_path)\nnumber_files = len(listds)\nos.chdir(maps_path)\narr = os.listdir()\n\ncounterOfStatus = 0\nfor i in range(number_files):\n\timage_name = arr[i]\n\timage = cv2.imread(image_name, 0)\n\tlbp = local_binary_pattern(image, n_points, radius, METHOD)\n\n\thist, _ = np.histogram(lbp, density=True, bins=6, range=(0,6))\n\n\tif(j==41):\n\t\tj+=1\n\telif(j==58):\n\t\tj+=2\n\n\tnrp = '21031810' + str(j)\n\n\tstatus = \"Keluaran Tidak Cocok\"\n\tif(nrp == match(hist)):\n\t\tstatus = \"Keluaran Cocok\"\n\t\tcounterOfStatus+=1\n\n\tprint('Gambar : ' + image_name + '/NRP : ' + nrp)\n\tprint('Hasil : ' + match(hist) + '/Status : '+status)\n\tprint()\n\tj+=1\n\nprint('Hasil yang cocok = '+ str(counterOfStatus))\nprint('Hasil yang tidak cocok = '+ str(27 - counterOfStatus))", "sub_path": "run_testing_project.py", "file_name": "run_testing_project.py", "file_ext": "py", "file_size_in_byte": 2075, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.dirname", "line_number": 8, "usage_type": "call"}, {"api_name": "os.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 8, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 20, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 23, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 30, "usage_type": "call"}, {"api_name": "skimage.feature.local_binary_pattern", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 33, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 66, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 68, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 74, "usage_type": "call"}, {"api_name": "skimage.feature.local_binary_pattern", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.histogram", "line_number": 77, "usage_type": "call"}]}
+{"seq_id": "285245959", "text": "\"\"\"\nMount/unmount a ``kernel`` client.\n\"\"\"\nimport contextlib\nimport logging\n\nfrom teuthology import misc\nfrom cephfs.kernel_mount import KernelMount\n\nlog = logging.getLogger(__name__)\n\n@contextlib.contextmanager\ndef task(ctx, config):\n \"\"\"\n Mount/unmount a ``kernel`` client.\n\n The config is optional and defaults to mounting on all clients. If\n a config is given, it is expected to be a list of clients to do\n this operation on. This lets you e.g. set up one client with\n ``ceph-fuse`` and another with ``kclient``.\n\n Example that mounts all clients::\n\n tasks:\n - ceph:\n - kclient:\n - interactive:\n\n Example that uses both ``kclient` and ``ceph-fuse``::\n\n tasks:\n - ceph:\n - ceph-fuse: [client.0]\n - kclient: [client.1]\n - interactive:\n\n :param ctx: Context\n :param config: Configuration\n \"\"\"\n log.info('Mounting kernel clients...')\n assert config is None or isinstance(config, list), \\\n \"task kclient got invalid config\"\n\n if config is None:\n config = ['client.{id}'.format(id=id_)\n for id_ in misc.all_roles_of_type(ctx.cluster, 'client')]\n clients = list(misc.get_clients(ctx=ctx, roles=config))\n\n test_dir = misc.get_testdir(ctx)\n\n # Assemble mon addresses\n remotes_and_roles = ctx.cluster.remotes.items()\n roles = [roles for (remote_, roles) in remotes_and_roles]\n ips = [remote_.ssh.get_transport().getpeername()[0]\n for (remote_, _) in remotes_and_roles]\n mons = misc.get_mons(roles, ips).values()\n\n mounts = {}\n for id_, remote in clients:\n kernel_mount = KernelMount(mons, test_dir, id_, remote)\n mounts[id_] = kernel_mount\n\n kernel_mount.mount()\n\n ctx.mounts = mounts\n try:\n yield mounts\n finally:\n log.info('Unmounting kernel clients...')\n for mount in mounts.values():\n mount.umount()\n", "sub_path": "tasks/kclient.py", "file_name": "kclient.py", "file_ext": "py", "file_size_in_byte": 1933, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.getLogger", "line_number": 10, "usage_type": "call"}, {"api_name": "teuthology.misc.all_roles_of_type", "line_number": 46, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 46, "usage_type": "name"}, {"api_name": "teuthology.misc.get_clients", "line_number": 47, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 47, "usage_type": "name"}, {"api_name": "teuthology.misc.get_testdir", "line_number": 49, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 49, "usage_type": "name"}, {"api_name": "teuthology.misc.get_mons", "line_number": 56, "usage_type": "call"}, {"api_name": "teuthology.misc", "line_number": 56, "usage_type": "name"}, {"api_name": "cephfs.kernel_mount.KernelMount", "line_number": 60, "usage_type": "call"}, {"api_name": "contextlib.contextmanager", "line_number": 12, "usage_type": "attribute"}]}
+{"seq_id": "194570972", "text": "\"\"\"Main collection of views.\"\"\"\nimport os\nfrom flask import Blueprint, jsonify, render_template, url_for\nfrom flask import current_app as app\n\n\n# Blue print for the main display\nhome_blueprint = Blueprint(\n 'home',\n __name__,\n template_folder='templates',\n static_folder='static'\n)\n\n\n@home_blueprint.route('/', methods=['GET'])\ndef home():\n \"\"\"Main home page.\"\"\"\n return render_template(\n 'main.html',\n )\n\n\n# Cache Buster for static files\n@home_blueprint.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n", "sub_path": "app/flask_app/views/home/home.py", "file_name": "home.py", "file_ext": "py", "file_size_in_byte": 910, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "flask.Blueprint", "line_number": 8, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.current_app.root_path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 34, "usage_type": "name"}, {"api_name": "os.stat", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 37, "usage_type": "call"}]}
+{"seq_id": "511297265", "text": "from inspect import signature\nfrom functools import wraps\n\n\ndef hoping(*iargs, **ikwargs):\n \"\"\"\n Implement the expected parameter type checking, note that it is a decorator usage\n \"\"\"\n\n def decorate(func):\n sig = signature(func)\n bound_types = sig.bind_partial(*iargs, **ikwargs).arguments\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n bound_values = sig.bind(*args, **kwargs)\n for name, value in bound_values.arguments.items():\n if name in bound_types:\n if not isinstance(value, bound_types[name]):\n raise TypeError(\"Args's type who names [ {} ] should be {}\".format(name, bound_types[name]))\n return func(*args, **kwargs)\n\n return wrapper\n\n return decorate\n", "sub_path": "src/decorator.py", "file_name": "decorator.py", "file_ext": "py", "file_size_in_byte": 800, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "inspect.signature", "line_number": 11, "usage_type": "call"}, {"api_name": "functools.wraps", "line_number": 14, "usage_type": "call"}]}
+{"seq_id": "163677807", "text": "import multiprocessing as mp\nimport binascii\n\n\ndef create_processes(filename, offset, interleave, L):\n processes = []\n parent_conns = []\n for c in range(3):\n parent_conn, child_conn = mp.Pipe()\n p = mp.Process(target=get_msg, args=(child_conn, filename, c, offset, interleave, L))\n p.start()\n processes.append(p)\n parent_conns.append(parent_conn)\n return processes, parent_conns\n\ndef get_msg(conn, filename, c, offset, interleave, L):\n pixel_counter = 0\n if c != 2:\n L = L // 3\n else:\n l = L // 3\n L = (L // 3) + L % 3\n counter = 0\n msg = \"\"\n interleave_counter = 1\n while len(msg) < L:\n read = conn.recv()\n for byte in read:\n if counter == c:\n pixel_counter += 1\n if pixel_counter > offset:\n interleave_counter -= 1\n if interleave_counter == 0:\n interleave_counter = interleave * 1\n byte = list(format(byte, '08b'))\n msg += byte[7]\n conn.send(byte[7])\n if len(msg) == L:\n break\n counter += 1\n if counter == 3:\n counter = 0\n conn.send('stop')\n", "sub_path": "alumnos/57031-porollan-santiago/TP2/steganography/decode.py", "file_name": "decode.py", "file_ext": "py", "file_size_in_byte": 1307, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "multiprocessing.Pipe", "line_number": 9, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 10, "usage_type": "call"}]}
+{"seq_id": "430456773", "text": "import json\nfrom tqdm import tqdm\nfrom googleapiclient.discovery import build\nimport config\n\ndef google_search(search_term, api_key, cse_id, **kwargs):\n service = build(\"customsearch\", \"v1\", developerKey=api_key)\n res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()\n return res['items']\n\nif __name__ == '__main__':\n my_api_key = config.api_key\n my_cse_id = config.cse_id\n my_search_topic = config.target_topic\n\n total_page_number = config.google_search_maximum_page_number\n results = []\n\n for page_number in tqdm(range(total_page_number)):\n current_result = google_search(my_search_topic, my_api_key, my_cse_id, num=10, start=page_number*10+1)\n results += current_result\n \n with open('google_search.json', 'w') as dump_file:\n json.dump(results, dump_file)\n", "sub_path": "cse.py", "file_name": "cse.py", "file_ext": "py", "file_size_in_byte": 832, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "googleapiclient.discovery.build", "line_number": 7, "usage_type": "call"}, {"api_name": "config.api_key", "line_number": 12, "usage_type": "attribute"}, {"api_name": "config.cse_id", "line_number": 13, "usage_type": "attribute"}, {"api_name": "config.target_topic", "line_number": 14, "usage_type": "attribute"}, {"api_name": "config.google_search_maximum_page_number", "line_number": 16, "usage_type": "attribute"}, {"api_name": "tqdm.tqdm", "line_number": 19, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 24, "usage_type": "call"}]}
+{"seq_id": "415585542", "text": "# by amounra 0216 : http://www.aumhaa.com\n# written against Live 9.6 release on 021516\n\nfrom __future__ import absolute_import, print_function\n\nimport Live\n\nimport math\nimport sys\nfrom re import *\nfrom itertools import imap, chain, starmap\n\nfrom aumhaa.v2.base import initialize_debug\n\ndebug = initialize_debug()\n\n\ndef get_devices(track):\n\n\tdef dig(container_device):\n\t\tcontained_devices = []\n\t\tif container_device.can_have_chains:\n\t\t\tfor chain in container_device.chains:\n\t\t\t\tfor chain_device in chain.devices:\n\t\t\t\t\tfor item in dig(chain_device):\n\t\t\t\t\t\tcontained_devices.append(item)\n\t\telse:\n\t\t\tcontained_devices.append(container_device)\n\t\treturn contained_devices\n\t\n\n\tdevices = []\n\tfor device in track.devices:\n\t\tfor item in dig(device):\n\t\t\tdevices.append(item)\n\t\t\t#self.log_message('appending ' + str(item))\n\treturn devices\n\t\n\n", "sub_path": "aumhaa/v2/base/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 830, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "aumhaa.v2.base.initialize_debug", "line_number": 15, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 23, "usage_type": "name"}, {"api_name": "itertools.chain.devices", "line_number": 24, "usage_type": "attribute"}, {"api_name": "itertools.chain", "line_number": 24, "usage_type": "name"}]}
+{"seq_id": "398441494", "text": "from django.shortcuts import render, get_object_or_404, get_list_or_404, redirect, render_to_response\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.views.generic import ListView, DetailView\n\n\nfrom django.contrib.auth.models import User, Group\nfrom module_content.models import Module, Lecture\nfrom student.models import Student, AssignmentSubmit\nfrom todo.models import List, Item\nfrom usermodule.models import UserModule\n\nclass ModuleProgressView(ListView):\n template_name = 'module_progress/module_progress.html'\n context_object_name = 'student'\n\n\n def get_context_data(self, **kwargs):\n context = super(ModuleProgressView, self).get_context_data(**kwargs)\n self.module = get_object_or_404(Module, code=self.kwargs['code'])\n current_user = get_object_or_404(User, email=self.request.user.email)\n file_submit = AssignmentSubmit.objects.filter(student=current_user.student_profile).filter(module=self.module)\n list_lists = List.objects.filter(module=self.module).filter(user=self.request.user)\n item_completed = Item.objects.filter(list__in=list_lists, completed=1)\n objectives_remain = Item.objects.filter(list__in=list_lists, completed=0).count()\n current_user_module = UserModule.objects.filter(user=self.request.user, module=self.module)\n if not current_user_module:\n temp = UserModule(user=current_user, module=self.module)\n temp.save()\n temp.content_views +=1\n temp.objectives_remains = objectives_remain\n temp.save()\n else:\n current_user.user_module.content_views += 1\n current_user.user_module.objectives_remains = objectives_remain\n current_user.user_module.save()\n item_uncompleted = Item.objects.filter(list__in=list_lists, completed=0)\n context.update({\n 'module' : self.module,\n 'assignment_list' : file_submit,\n 'lists' : list_lists,\n 'items' : item_completed,\n 'remediation' : item_uncompleted,\n 'current_user' : current_user,\n })\n return context\n\n def get_queryset(self):\n current_user = get_object_or_404(User, email=self.request.user.email)\n self.module = get_object_or_404(Module, code=self.kwargs['code'])\n current_user_module = UserModule.objects.filter(user=self.request.user, module=self.module)\n if not current_user_module:\n temp = UserModule(user=current_user, module=self.module)\n temp.save()\n return current_user\n", "sub_path": "module_progress/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2629, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.views.generic.ListView", "line_number": 13, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 20, "usage_type": "call"}, {"api_name": "module_content.models.Module", "line_number": 20, "usage_type": "argument"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 21, "usage_type": "argument"}, {"api_name": "student.models.AssignmentSubmit.objects.filter", "line_number": 22, "usage_type": "call"}, {"api_name": "student.models.AssignmentSubmit.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "student.models.AssignmentSubmit", "line_number": 22, "usage_type": "name"}, {"api_name": "todo.models.List.objects.filter", "line_number": 23, "usage_type": "call"}, {"api_name": "todo.models.List.objects", "line_number": 23, "usage_type": "attribute"}, {"api_name": "todo.models.List", "line_number": 23, "usage_type": "name"}, {"api_name": "todo.models.Item.objects.filter", "line_number": 24, "usage_type": "call"}, {"api_name": "todo.models.Item.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "todo.models.Item", "line_number": 24, "usage_type": "name"}, {"api_name": "todo.models.Item.objects.filter", "line_number": 25, "usage_type": "call"}, {"api_name": "todo.models.Item.objects", "line_number": 25, "usage_type": "attribute"}, {"api_name": "todo.models.Item", "line_number": 25, "usage_type": "name"}, {"api_name": "usermodule.models.UserModule.objects.filter", "line_number": 26, "usage_type": "call"}, {"api_name": "usermodule.models.UserModule.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "usermodule.models.UserModule", "line_number": 26, "usage_type": "name"}, {"api_name": "usermodule.models.UserModule", "line_number": 28, "usage_type": "call"}, {"api_name": "todo.models.Item.objects.filter", "line_number": 37, "usage_type": "call"}, {"api_name": "todo.models.Item.objects", "line_number": 37, "usage_type": "attribute"}, {"api_name": "todo.models.Item", "line_number": 37, "usage_type": "name"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 49, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User", "line_number": 49, "usage_type": "argument"}, {"api_name": "django.shortcuts.get_object_or_404", "line_number": 50, "usage_type": "call"}, {"api_name": "module_content.models.Module", "line_number": 50, "usage_type": "argument"}, {"api_name": "usermodule.models.UserModule.objects.filter", "line_number": 51, "usage_type": "call"}, {"api_name": "usermodule.models.UserModule.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "usermodule.models.UserModule", "line_number": 51, "usage_type": "name"}, {"api_name": "usermodule.models.UserModule", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "120654011", "text": "# -*- coding: utf-8 -*-\nfrom http import HTTPStatus\n\nimport flask\n\nfrom src.exceptions.response_exceptions import ConflictException, NotFoundException, BadRequestException\nfrom src.services.pokemons import PokemonService, PokemonRequest\n\n\npokemons_bp = flask.Blueprint('pokemons', __name__, url_prefix='/api/v1/pokemons')\n\n@pokemons_bp.route('/', methods=['GET'])\ndef get_pokemon(name):\n pokemon = PokemonService.get_pokemon(name)\n\n return flask.jsonify(pokemon), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('', methods=['GET'])\ndef get_all_pokemons():\n request = PokemonRequest()\n\n if 'name' in flask.request.args:\n request.name = flask.request.args.get('name') \n if 'types' in flask.request.args:\n request.types = flask.request.args.get('types') \n if 'caught' in flask.request.args:\n request.caught = flask.request.args.get('caught') == 'true'\n if 'abilities' in flask.request.args:\n request.abilities = flask.request.args.get('abilities') \n if 'hidden_abilities' in flask.request.args:\n request.hidden_abilities = flask.request.args.get('hidden_abilities') == 'true'\n if 'order_by' in flask.request.args:\n request.order_by = flask.request.args.get('order_by')\n if 'descending' in flask.request.args:\n request.descending = flask.request.args.get('descending')\n\n pokemons = PokemonService.get_all_pokemons(request)\n\n return flask.jsonify(pokemons), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('/', methods=['POST'])\ndef save_pokemon(name):\n pokemon = PokemonService.get_all_pokemons({ name })\n if pokemon:\n raise ConflictException('This pokemon has been already saved')\n\n payload = flask.request.get_json(cache=False)\n\n saved = PokemonService.insert_pokemon(payload)\n\n return flask.jsonify(saved), HTTPStatus.OK.value\n\n\n@pokemons_bp.route('/', methods=['PUT', 'PATCH'])\ndef update_pokemon(pokemon_id):\n\n pokemon = PokemonService.get_by_id(pokemon_id)\n if not pokemon:\n raise NotFoundException('This pokemon doesn\\'t belong to your team yeat')\n\n payload = flask.request.get_json()\n if not payload:\n raise BadRequestException()\n\n saved = PokemonService.update_pokemon(pokemon_id, payload)\n\n return flask.jsonify(saved.to_dict()), HTTPStatus.OK.value\n", "sub_path": "back/src/blueprints/pokemons.py", "file_name": "pokemons.py", "file_ext": "py", "file_size_in_byte": 2320, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Blueprint", "line_number": 10, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService.get_pokemon", "line_number": 14, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 14, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 16, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 16, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 16, "usage_type": "name"}, {"api_name": "src.services.pokemons.PokemonRequest", "line_number": 21, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 24, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 28, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 28, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 29, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 30, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 30, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 31, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 32, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 32, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 33, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 34, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 34, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 35, "usage_type": "attribute"}, {"api_name": "flask.request.args.get", "line_number": 36, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 36, "usage_type": "attribute"}, {"api_name": "src.services.pokemons.PokemonService.get_all_pokemons", "line_number": 38, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 38, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 40, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 40, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 40, "usage_type": "name"}, {"api_name": "src.services.pokemons.PokemonService.get_all_pokemons", "line_number": 45, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 45, "usage_type": "name"}, {"api_name": "src.exceptions.response_exceptions.ConflictException", "line_number": 47, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 49, "usage_type": "attribute"}, {"api_name": "src.services.pokemons.PokemonService.insert_pokemon", "line_number": 51, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 51, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 53, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 53, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 53, "usage_type": "name"}, {"api_name": "src.services.pokemons.PokemonService.get_by_id", "line_number": 59, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 59, "usage_type": "name"}, {"api_name": "src.exceptions.response_exceptions.NotFoundException", "line_number": 61, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 63, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 63, "usage_type": "attribute"}, {"api_name": "src.exceptions.response_exceptions.BadRequestException", "line_number": 65, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService.update_pokemon", "line_number": 67, "usage_type": "call"}, {"api_name": "src.services.pokemons.PokemonService", "line_number": 67, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 69, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 69, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 69, "usage_type": "name"}]}
+{"seq_id": "87039992", "text": "import pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\n#Reading users file:\nu_users = ['id', 'user_id', 'joke_id']\nusers = pd.read_csv('c:\\\\Users\\\\hambekar\\\\Downloads\\\\joke_user.csv', sep=',', names=u_users, encoding='latin-1')\n\n#Reading ratings file:\nr_ratings = ['id', 'rating']\nratings = pd.read_csv('c:\\\\Users\\\\hambekar\\\\Downloads\\\\joke_rating.csv', sep=',', names=r_ratings, encoding='latin-1')\n\nusers['id']=users['id'].transform(float)\nratings['id']=ratings['id'].transform(float)\n\n\nratings = pd.merge(users, ratings, on='id')\n\n#ratings_df = pd.DataFrame(ratings.groupby('joke_id')['joke_id'].mean())\nratings['number_of_ratings'] = ratings.groupby('joke_id')['rating'].count()\nratings['number_of_ratings'].hist(bins=60)\n\nsns.jointplot(x='rating', y='number_of_ratings', data=ratings)\n\nprint(ratings)\n\nexit(0)\n\nn_users = users.user_id.unique().shape[0]\nn_items = users.joke_id.unique().shape[0]\n\ndata_matrix = np.zeros((n_users, n_items))\n\ndata_matrix = np.zeros((n_users, n_items))\nfor line in ratings.itertuples():\n data_matrix[line[1]-1, line[2]-1] = line[0]\n #print(line)\n\nfrom sklearn.metrics.pairwise import pairwise_distances\nuser_similarity = pairwise_distances(data_matrix, metric='cosine')\nitem_similarity = pairwise_distances(data_matrix.T, metric='cosine')\n\nuser_prediction = predict(data_matrix, user_similarity, type='user')\nitem_prediction = predict(data_matrix, item_similarity, type='item')\n\nprint(user_prediction)\nprint(item_prediction)\n", "sub_path": "funny-jokes-ratings.py", "file_name": "funny-jokes-ratings.py", "file_ext": "py", "file_size_in_byte": 1523, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.read_csv", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 19, "usage_type": "call"}, {"api_name": "seaborn.jointplot", "line_number": 25, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 36, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.pairwise_distances", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.pairwise_distances", "line_number": 43, "usage_type": "call"}]}
+{"seq_id": "493113077", "text": "# -*- coding: UTF-8 -*-\n\nfrom pyAudioAnalysis import audioBasicIO\nfrom pyAudioAnalysis import audioFeatureExtraction\nimport numpy as np\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.mixture import GaussianMixture\n\n# python speech feature\n\nmy_dir = ['common', 'throat']\nmy_file = ['1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav', '10.wav',\n 'from-net-1.wav',\n 'from-net-2.wav', 'from-net-3.wav'\n ]\n# my_file = ['from-net-1.wav',\n# 'from-net-2.wav', 'from-net-3.wav']\n# my_file = ['train.wav']\n\nframe_length = 0.07\nstep_length = 0.035\n\ndata_matrix = []\nlabel_matrix = []\nn = 0\nn = int(n)\nfor f_dir in my_dir:\n n += 1\n for f_file in my_file:\n [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/mono_train/\" + f_dir + \"/\" + f_file)\n # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n F = audioFeatureExtraction.stFeatureExtraction(x, Fs, frame_length * Fs, step_length * Fs)\n f = F[8:21, ]\n f = f.T\n data_matrix.append(f)\n label = np.empty(f.shape[0], dtype=int)\n label = np.full(label.shape, n)\n label_matrix.append(label)\ndata_matrix = np.concatenate(data_matrix, 0)\nlabel_matrix = np.concatenate(label_matrix, 0)\n\n# data_matrix = data_matrix\n# label_matrix = label_matrix\nprint(data_matrix.shape)\nprint(label_matrix.shape)\n\n# data_matrix_new = SelectKBest(f_regression, k=9).fit_transform(data_matrix, label_matrix)\n\nnp.savetxt(fname=\"data_matrix.csv\", X=data_matrix, delimiter=',')\nnp.savetxt(\"label_matrix.csv\", label_matrix, delimiter=',')\n\n# clf_svm = svm.SVC(gamma='scale', decision_function_shape='ovo')\n# clf_svm.fit(data_matrix, label_matrix)\n\nclf_svm = Pipeline([\n (\"scaler\", StandardScaler()),\n # (\"svm_clf\", SVC(kernel=\"poly\", C=1000))\n # (\"svm_clf\", SVC(kernel='rbf', gamma='scale', C=5, decision_function_shape='ovo'))\n (\"svm_clf\", SVC(kernel='poly', gamma='scale', C=100, decision_function_shape='ovo'))\n # (\"gmm_clf\", GaussianMixture(n_components=2, covariance_type='full'))\n])\n\n# clf_svm = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=0)\nclf_svm.fit(data_matrix, label_matrix)\n\n\n# RandomForest\n\n# 预测\n\n\ndef max_list(lt):\n temp = 0\n for i in lt:\n if lt.count(i) > temp:\n max_str = i\n temp = lt.count(i)\n return str(max_str)\n\n\n# pre_dir = ['common', 'throat']\n# pre_file = ['1.wav', '2.wav', '3.wav', '4.wav', '5.wav', '6.wav', '7.wav', '8.wav', '9.wav',\n# '10.wav', '11.wav', '12.wav', '13.wav', '14.wav', '15.wav', 'xsb-common.wav.wav', ]\n# counter = current = 0\n#\n# result_matrix = []\n# for p_dir in pre_dir:\n# # current += 1\n# result_matrix.append(p_dir)\n# result_matrix.append(':')\n# for p_file in pre_file:\n# [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/mono_test/\" + p_dir + '/' + p_file)\n# F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.050 * Fs, 0.025 * Fs)\n# # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n# f = F[8:21, ].T\n# result = clf_svm.predict(f)\n# result_in = result.tolist()\n# result_matrix.append(max_list(result_in))\n# print(result_matrix)\n\npre_file = ['common1.wav', 'common2.wav', 'common3.wav', 'common4.wav', 'common5.wav',\n 'common6.wav', 'common7.wav', 'common8.wav', 'common9.wav', 'common10.wav',\n 't1.wav', 't2.wav', 't3.wav', 't4.wav', 't5.wav',\n 't6.wav', 't7.wav', 't8.wav', 't9.wav', 't10.wav',\n 't11.wav', 't12.wav', 't13.wav', 't14.wav', 't15.wav']\n\nresult_matrix = []\nfor p_file in pre_file:\n [Fs, x] = audioBasicIO.readAudioFile(\"D:/ML/data/SVM/\" + p_file)\n F = audioFeatureExtraction.stFeatureExtraction(x, Fs, frame_length * Fs, step_length * Fs)\n # F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 256, 80)\n f = F[8:21, ].T\n result = clf_svm.predict(f)\n result_in = result.tolist()\n # result_matrix.append(p_file)\n result_matrix.append(max_list(result_in))\nprint(result_matrix)\n", "sub_path": "Test Code/speak_reg/throat.py", "file_name": "throat.py", "file_ext": "py", "file_size_in_byte": 4125, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pyAudioAnalysis.audioBasicIO.readAudioFile", "line_number": 32, "usage_type": "call"}, {"api_name": "pyAudioAnalysis.audioBasicIO", "line_number": 32, "usage_type": "name"}, {"api_name": "pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction", "line_number": 34, "usage_type": "call"}, {"api_name": "pyAudioAnalysis.audioFeatureExtraction", "line_number": 34, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 39, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 51, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 52, "usage_type": "call"}, {"api_name": "sklearn.pipeline.Pipeline", "line_number": 57, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 58, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 61, "usage_type": "call"}, {"api_name": "pyAudioAnalysis.audioBasicIO.readAudioFile", "line_number": 111, "usage_type": "call"}, {"api_name": "pyAudioAnalysis.audioBasicIO", "line_number": 111, "usage_type": "name"}, {"api_name": "pyAudioAnalysis.audioFeatureExtraction.stFeatureExtraction", "line_number": 112, "usage_type": "call"}, {"api_name": "pyAudioAnalysis.audioFeatureExtraction", "line_number": 112, "usage_type": "name"}]}
+{"seq_id": "539729387", "text": "import asyncio\nimport websockets\nfrom geolocation import Geolocation\nimport json\n\ngeolocation = Geolocation()\ngeolocation.connect_to_base()\n\n'''Класс Websocket'''\nclass Websocket():\n\n timeout = 1 \n client_imei = []\n USERS = set()\n host = \"127.0.0.1\"\n port = 3000\n\n async def addUser(self, websocket):\n self.USERS.add(websocket) \n\n async def removeUser(self,websocket):\n self.USERS.remove(websocket) \n\n def start(self): \n start_ws = websockets.serve(self.main, self.host, self.port) \n asyncio.get_event_loop().run_until_complete(start_ws)\n asyncio.get_event_loop().run_forever() \n\n '''Опрос базы данных и отправка клиенту локации тс с запрошенными imei с интервалом timeout'''\n async def worker(self, websocket, path): \n while True: \n await websocket.send(json.dumps(geolocation.get_geo(self.client_imei))) \n await asyncio.sleep(self.timeout) \n\n '''Прослушивание запросов от клиента'''\n async def recv(self, websocket, path): \n try:\n client_imei = await websocket.recv() \n self.client_imei = json.loads(client_imei)\n await self.recv(websocket, path)\n except: \n await self.removeUser(websocket)\n\n '''Запуск параллельной работы прослушивания ws и регулярной отправки сообщений'''\n async def main(self, websocket, path):\n await self.addUser(websocket) \n task1 = asyncio.get_event_loop().create_task(self.worker(websocket, path))\n task2 = asyncio.get_event_loop().create_task(self.recv(websocket, path)) \n await task1\n await task2 ", "sub_path": "backend/websocket.py", "file_name": "websocket.py", "file_ext": "py", "file_size_in_byte": 1962, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "geolocation.Geolocation", "line_number": 6, "usage_type": "call"}, {"api_name": "geolocation.connect_to_base", "line_number": 7, "usage_type": "call"}, {"api_name": "websockets.serve", "line_number": 25, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 26, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 27, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}, {"api_name": "geolocation.get_geo", "line_number": 32, "usage_type": "call"}, {"api_name": "asyncio.sleep", "line_number": 33, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 39, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 47, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 48, "usage_type": "call"}]}
+{"seq_id": "41393817", "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n\nX = []\nwith open(\"three.txt\") as fd:\n lines = fd.readlines()\n for line in lines:\n three = line.split()\n three = list(map(int, three))\n X.append(three)\n\nwith open(\"eight.txt\") as fd:\n lines = fd.readlines()\n for line in lines:\n three = line.split()\n three = list(map(int, three))\n X.append(three)\n\ny = []\nfor i in range(256):\n elem = 0\n for j in range(400):\n elem += X[j][i]\n y.append(elem/400)\n#y = np.array(y)\nX = np.array(X)\ny = np.mean(X.T, axis=1)\nX = X - y\n# S = np.dot(X.T,X)\n# S = np.divide(S,399)\nS = np.cov(X.T)\nw, v = np.linalg.eig(S)\nprint(w[:2])\nv1 = v[:,0]\nv2 = v[:,1]\n# v1 = np.divide(v1,(np.amax(v1)/255.0))\n# v2 = np.divide(v2,(np.amax(v2)/255.0))\nimg = v1.reshape(16,16,order='F')\nplt.imshow(img, cmap=\"gray\")\nplt.show()\nimg = v2.reshape(16,16,order='F')\nplt.imshow(img, cmap=\"gray\")\nplt.show()", "sub_path": "HW8/Q4.py", "file_name": "Q4.py", "file_ext": "py", "file_size_in_byte": 934, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.array", "line_number": 27, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.cov", "line_number": 32, "usage_type": "call"}, {"api_name": "numpy.linalg.eig", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 33, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}]}
+{"seq_id": "534019667", "text": "import sys\nfrom PCMtoXYZ import *\nfrom PyQt5.QtWidgets import QApplication, QDialog\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\nfrom MainUI import Ui_GUI\nfrom Popup1 import Ui_Complete\nfrom Popup2 import Ui_Err\nimport os\n\n###TestVariables###\npcmlocation = \"Z:\\MS\\TPY PCM\\MS2.pcm\"\nDirLocation = \"Z:\\MS\\TPY PCM\"\nPrefix = \"conf\"\n\ndef xyzgen(path, genname):\n if not os.path.exists(path):\n os.makedirs(path)\n open(path+'\\\\'+genname+'.xyz', 'w+')\n\nclass ProgramDesign(QDialog, Ui_GUI):\n def __init__(self):\n super().__init__()\n self.ui = Ui_GUI()\n self.ui.setupUi(self)\n self.show()\n self.ui.SaveButton.clicked.connect(self.mainftn)\n self.ui.ExitButton.clicked.connect(self.closeftn)\n self.ui.Choosefile.clicked.connect(self.chooseftn)\n self.ui.OutputB.clicked.connect(self.outputftn)\n\n\n def mainftn(self):\n global pcmlocation, DirLocation, Prefix\n# DirLocation = self.ui.OutputBox.toPlainText()\n Prefix = self.ui.PrefixBox.toPlainText()\n if pcmlocation == '' or DirLocation == '' or Prefix == '':\n global errpopup\n errpopup = Errorpopup()\n else:\n f = open(pcmlocation, \"r\")\n contents = f.readlines()\n numconf = 1\n for line in contents:\n string = line.split()\n if string[0] == '{PCM':\n Filename = Prefix+str(numconf)\n path = DirLocation + '\\\\' + str(Filename)\n xyzgen(path, Filename)\n flag = 1\n numconf = numconf + 1\n elif flag == 1:\n flag = 2\n numatom = string[1]\n xyzfile = open(path+'\\\\'+Filename+'.xyz', 'a')\n xyzfile.write(str(numatom))\n xyzfile.write('\\n\\n')\n elif string[0] == 'AT':\n xyzfile.write(PCM_XYZ(int(string[2]))+' ')\n xyzfile.write(string[3]+' '+string[4]+' '+string[5]+'\\n')\n f.close()\n global ui2\n ui2 = Completepopup()\n\n def chooseftn(self):\n Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n global pcmlocation\n pcmlocation = askopenfilename()\n self.ui.PCMBox.setPlainText(pcmlocation)\n\n def outputftn(self):\n Tk().withdraw()\n global DirLocation\n DirLocation = filedialog.askdirectory()\n self.ui.OutputBox.setPlainText(DirLocation)\n\n\n def closeftn(self):\n ui.close()\n\nclass Completepopup(QDialog, Ui_Complete):\n def __init__(self):\n super().__init__()\n self.ui = Ui_Complete()\n self.ui.setupUi(self)\n self.show()\n self.ui.OKButton.clicked.connect(self.closeftn)\n\n def closeftn(self):\n ui2.close()\n\n\nclass Errorpopup(QDialog, Ui_Err):\n def __init__(self):\n super().__init__()\n self.ui = Ui_Err()\n self.ui.setupUi(self)\n self.show()\n self.ui.OKButton_2.clicked.connect(self.closeftn)\n\n def closeftn(self):\n errpopup.close()\n\n\napp = QApplication(sys.argv)\n#GUI = QDialog()\nui = ProgramDesign()\n#ui.setupUi(GUI)\nui.show()\n#ui2 = Completepopup()\n#ui2.show()\nsys.exit(app.exec_())\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3346, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "os.path.exists", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 19, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 22, "usage_type": "name"}, {"api_name": "MainUI.Ui_GUI", "line_number": 22, "usage_type": "name"}, {"api_name": "MainUI.Ui_GUI", "line_number": 25, "usage_type": "call"}, {"api_name": "tkinter.filedialog.askopenfilename", "line_number": 69, "usage_type": "call"}, {"api_name": "tkinter.filedialog.askdirectory", "line_number": 75, "usage_type": "call"}, {"api_name": "tkinter.filedialog", "line_number": 75, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 82, "usage_type": "name"}, {"api_name": "Popup1.Ui_Complete", "line_number": 82, "usage_type": "name"}, {"api_name": "Popup1.Ui_Complete", "line_number": 85, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QDialog", "line_number": 94, "usage_type": "name"}, {"api_name": "Popup2.Ui_Err", "line_number": 94, "usage_type": "name"}, {"api_name": "Popup2.Ui_Err", "line_number": 97, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 106, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 106, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 113, "usage_type": "call"}]}
+{"seq_id": "652937292", "text": "import os\r\nimport openpyxl\r\n#=====================================================================\r\n# READ EXCELS FILE USING EXTERNAL PYTHON LIBRARY\r\n#=====================================================================\r\nprint(\"[database] loading\")\r\nfrom openpyxl import load_workbook\r\nwb = load_workbook(filename='13.xlsx', read_only=True)\r\nws = wb['Sheet1']\r\n\r\n#=====================================================================\r\n# CONVERT EXCEL TO ARRAYS\r\n#=====================================================================\r\nprint(\"[database] converting\")\r\ndef iter_rows(ws):\r\n for row in ws.iter_rows():\r\n yield [cell.value for cell in row]\r\ntabel = list(iter_rows(ws))\r\n\r\n#=====================================================================\r\n# REFORMATING ARRAYS - INFORMATION ROWS FINDER\r\n#=====================================================================\r\nc_utc_JST=0\r\nc_steps=0\r\nc_pulse=0\r\nc_calory=0\r\nc_transType=0\r\ndef find_row(tabel):\r\n count=0\r\n print(\"[database] finding necesseries data\")\r\n while(1):\r\n if (count==len(tabel[0])):\r\n global c_transType\r\n global c_steps\r\n global c_pulse\r\n global c_calory\r\n global c_utc_JST\r\n break\r\n if (tabel[0][count]==\"steps\"):\r\n c_steps=count\r\n if (tabel[0][count]==\"pulse\"):\r\n c_pulse=count\r\n if (tabel[0][count]==\"calory\"):\r\n c_calory=count\r\n if (tabel[0][count]==\"utc_JST\"):\r\n c_utc_JST=count\r\n if (tabel[0][count]==\"transType\"):\r\n c_transType=count\r\n count+=1\r\nfind_row(tabel)\r\n\r\n#=====================================================================\r\n# KIND OF INPUT DATA START PARAMETERS\r\n#=====================================================================\r\nname=\"Hans (Hanjara Cahya Adhyatma)\"\r\ngender=\"male\"\r\nage=22\r\nweigh=60\r\nheigh=170\r\npulse=0\r\navcnt=0\r\ni=0\r\nelevator=0\r\nwalking=0\r\nstay=0\r\nstair=0\r\nstp=0\r\nclr=0.0\r\nn=0\r\nperson=[]\r\ndatabase=[]\r\nall_pulse=[]\r\nall_stair=[]\r\nall_elevator=[]\r\nall_walking=[]\r\nall_stp=[]\r\nall_stay=[]\r\nall_clr=[]\r\n#=====================================================================\r\n# INFORMATION FILTERING\r\n#=====================================================================\r\nprint(\"[database] collecting necesseries data\")\r\nfor row in ws.rows:\r\n if(tabel[i][c_transType]==\"7(エレベータ降り中)\") or \\\r\n (tabel[i][c_transType]==\"6(エレベータ昇り中)\"):\r\n all_elevator.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n elevator+=1\r\n if(tabel[i][c_transType]==\"2(歩行中)\"):\r\n all_walking.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n walking+=1\r\n if(tabel[i][c_transType]==\"1(静止中)\"):\r\n all_stay.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n stay+=1\r\n if(tabel[i][c_transType]==\"5(階段降り中)\"):\r\n all_stair.extend([[tabel[i][c_utc_JST], tabel[i][c_transType]]])\r\n stair+=1\r\n if(tabel[i][c_steps] != 0) and \\\r\n (tabel[i][c_steps] != None) and \\\r\n (tabel[i][c_steps] != \"steps\"):\r\n all_stp.extend([[tabel[i][c_utc_JST], tabel[i][c_steps]]])\r\n stp+=int(tabel[i][c_steps])\r\n if(tabel[i][c_calory] != 0) and \\\r\n (tabel[i][c_calory] != None) and \\\r\n (tabel[i][c_calory] != \"calory\") and \\\r\n (tabel[i][c_calory] != \"\"):\r\n all_clr.extend([[tabel[i][c_utc_JST], tabel[i][c_calory]]])\r\n clr+=float(tabel[i][c_calory])\r\n if(tabel[i][c_pulse] != 0) and \\\r\n (tabel[i][c_pulse] != None) and \\\r\n (tabel[i][c_pulse] != \"pulse\"):\r\n all_pulse.extend([[tabel[i][c_utc_JST], tabel[i][c_pulse]]])\r\n pulse+=int(tabel[i][c_pulse])\r\n avcnt+=1\r\n i+=1 \r\n \r\n#=====================================================================\r\n# INFORMATION PRINTING\r\n#=====================================================================\r\n\r\nprint()\r\nprint(\"Name \\t\",name)\r\nprint(\"Gender \\t\",gender)\r\nprint(age, \"\\t years old\")\r\nprint(weigh, \"\\t kg\")\r\nprint(heigh, \"\\t cm\")\r\nprint(round(pulse/avcnt, 2), \"\\t bpm\")\r\nprint(stair,\"\\t times detected using stairs\")\r\nprint(elevator,\"\\t times detected using elevator\")\r\nprint(walking, \"\\t times detected walking\")\r\nprint(stp,\"\\t total steps\")\r\nprint(stay, \"\\t times detected stay\")\r\nprint(round(clr, 2),\"\\t kcal burned total?\")\r\n\"\"\"\r\nglobal name\r\nglobal gender\r\nglobal age\r\nglobal weigh\r\nglobal heigh\r\nglobal pulse\r\nglobal avcnt\r\nglobal stair\r\nglobal elevator\r\nglobal walking\r\nglobal stp\r\nglobal stay\r\nglobal clr\r\n\"\"\"\r\n#=====================================================================\r\n# new NECESSERIES database\r\n#=====================================================================\r\nprint(\"[database] save collected data\")\r\nperson=[name,gender,age,weigh,heigh,round(pulse/avcnt, 2),stair,elevator,walking,stp,stay,round(clr, 2)]\r\ndatabase=[person,gender,age,weigh,heigh,all_pulse,all_stair,all_elevator,all_walking,all_stp,all_stay,all_clr]\r\n\"\"\"\r\nit=0\r\nwhile(1):\r\n if (it==len(database[9])):\r\n break\r\n print(database[9][it])\r\n it+=1\r\n\"\"\"\r\nprint(\"[database] finish\")", "sub_path": "HealthCare/expertknowladge/read_xl.py", "file_name": "read_xl.py", "file_ext": "py", "file_size_in_byte": 4798, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "openpyxl.load_workbook", "line_number": 8, "usage_type": "call"}]}
+{"seq_id": "515298487", "text": "import matplotlib.pyplot as plt\n\n# Measurements from block-size.data\nbsize = [\n ('Bamboo-SL',[\n (16.159, 10.15),\n (46.159, 10.76),\n (67.320, 12.25),\n (101.170, 16.63),\n (117.174, 21.69),\n (128.625, 26.85),\n (132.803, 30.55),\n (136.484, 36.5),\n (138.231, 45.44),\n (144.888, 51.7)\n ], '-o', 'coral'),\n ('Model-SL',[\n (16.519,5.53),\n (46.159,7.50),\n (67.32,9.86),\n (101.170,19.475),\n (128.625,26.33),\n (132.803,33.99),\n (136.484,44.74),\n ], '-s', 'steelblue')]\n\ndef do_plot():\n f = plt.figure(1, figsize=(7,5))\n plt.clf()\n ax = f.add_subplot(1, 1, 1)\n for name, entries, style, color in bsize:\n throughput = []\n latency = []\n for t, l in entries:\n throughput.append(t)\n latency.append(l)\n ax.plot(throughput, latency, style, color=color, label='%s' % name, markersize=8, alpha=0.8)\n plt.legend(loc='best', fancybox=True,frameon=False,framealpha=0.8)\n plt.grid(linestyle='--', alpha=0.3)\n plt.ylabel('Latency (ms)')\n plt.xlabel('Throughput (KTx/s)')\n plt.tight_layout()\n plt.ylim([0,60])\n plt.savefig('model-implementation.pdf', format='pdf')\n plt.show()\n\nif __name__ == '__main__':\n do_plot()\n", "sub_path": "plot/model/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 1300, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.pyplot.figure", "line_number": 28, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 28, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 41, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 41, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}]}
+{"seq_id": "483211656", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os.path as osPath\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom convert_data import ConvertData\nfrom extarct_tags import TagExtraction\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic #%d:\" % topic_idx)\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-n_top_words - 1:-1]]))\n print()\n\ntagExtraction = TagExtraction('product', 'tags.json')\nconverter = ConvertData('product')\n\ntags = tagExtraction.read_tags()\nrecords = tagExtraction.read_records()\nrecords = {record['id']: [record['productname'], record['description'], record['directoryname']] for record in records}\n\nvectors_id = converter.read_vectors()\nids = list(vectors_id.keys())\nvectors = list(vectors_id.values())\n\nlda = LatentDirichletAllocation(n_topics=100)\nlda_vectors = lda.fit_transform(vectors)\nprint_top_words(lda, tags, 20)\n\ncls = KMeans(n_clusters=500).fit(lda_vectors)\nlabels = cls.labels_\nlabel_map = dict(zip(ids, labels))\n\ntagExtraction = TagExtraction('product', 'tags.json')\ntags = tagExtraction.read_tags()\nrecords = tagExtraction.read_records()\nrecords = {record['id']: [record['productname'], record['description']] for record in records}\n\noutput = {}\nfor k, v in label_map.items():\n if v in output:\n output[v].append(k)\n else:\n output[v] = [k]\n\n\ndef dump_cluster(label, tags, records):\n with open(osPath.join(osPath.dirname(osPath.abspath(__file__)), 'product', 'clusters', str(label) + '_tags.json'),\n 'w',\n encoding='utf-8') as f:\n f.write(json.dumps(tags, ensure_ascii=False))\n\n with open(\n osPath.join(osPath.dirname(osPath.abspath(__file__)), 'product', 'clusters', str(label) + '_records.json'),\n 'w',\n encoding='utf-8') as f:\n f.write(json.dumps(records, ensure_ascii=False))\n\n\nfor k, v in output.items():\n print(k, len(v))\n\n sum = np.zeros(len(vectors[0]))\n for id in v:\n na = np.array(vectors_id[id], dtype=np.float64)\n na[na != 0] = 1\n sum += na\n sum = sum.tolist()\n\n _tags = [(tag, count) for tag, count in zip(tags, sum) if count != 0]\n _records = [[id] + records[id] for id in v]\n # _records = [[id] + records[id] + [[(index, value) for index,value in enumerate(vectors_id[id]) if value != 0]] for id in v]\n # _records = [vectors_id[id] for id in v]\n dump_cluster(k, sorted(_tags, key=lambda x: x[1], reverse=True), _records)\n # print([tags[index] for index, count in enumerate(sum) if count > len(v)*0.2])\n\n\n\n# while(True):\n# productId = input('productId\\n')\n# label = label_map[productId]\n# indexs = [index for index, item in enumerate(labels) if item == label]\n# for index in indexs:\n# print(records[ids[index]])\n", "sub_path": "training.py", "file_name": "training.py", "file_ext": "py", "file_size_in_byte": 2953, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "extarct_tags.TagExtraction", "line_number": 19, "usage_type": "call"}, {"api_name": "convert_data.ConvertData", "line_number": 20, "usage_type": "call"}, {"api_name": "sklearn.decomposition.LatentDirichletAllocation", "line_number": 30, "usage_type": "call"}, {"api_name": "sklearn.cluster.KMeans", "line_number": 34, "usage_type": "call"}, {"api_name": "extarct_tags.TagExtraction", "line_number": 38, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 52, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "name"}, {"api_name": "os.path.dirname", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 58, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 61, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 69, "usage_type": "attribute"}]}
+{"seq_id": "476683910", "text": "import itertools\nimport json\nfrom random import choice, randint, shuffle\nfrom threading import Thread\nfrom time import sleep, time\n\nimport requests\nimport urllib3\nfrom couchbase import experimental, subdocument\nfrom couchbase.bucket import Bucket\nfrom couchbase.exceptions import (\n ConnectError,\n CouchbaseError,\n HTTPError,\n KeyExistsError,\n NotFoundError,\n TemporaryFailError,\n TimeoutError,\n)\nfrom decorator import decorator\nfrom txcouchbase.connection import Connection as TxConnection\n\nfrom logger import logger\n\nexperimental.enable()\n\n\n@decorator\ndef quiet(method, *args, **kwargs):\n try:\n return method(*args, **kwargs)\n except (ConnectError, CouchbaseError, HTTPError, KeyExistsError,\n NotFoundError, TimeoutError) as e:\n logger.warn('{}, error: {}, args: {}'.format(method, e, args))\n\n\n@decorator\ndef backoff(method, *args, **kwargs):\n while True:\n try:\n return method(*args, **kwargs)\n except TemporaryFailError:\n sleep(1)\n\n\n@decorator\ndef timeit(method, *args, **kwargs) -> int:\n t0 = time()\n method(*args, **kwargs)\n return time() - t0\n\n\nclass CBAsyncGen:\n\n TIMEOUT = 60 # seconds\n\n def __init__(self, use_ssl=False, **kwargs):\n self.client = TxConnection(quiet=True, **kwargs)\n self.client.timeout = self.TIMEOUT\n\n def create(self, key: str, doc: dict):\n return self.client.set(key, doc)\n\n def read(self, key: str):\n return self.client.get(key)\n\n def update(self, key: str, doc: dict):\n return self.client.set(key, doc)\n\n def delete(self, key: str):\n return self.client.delete(key)\n\n\nclass CBGen(CBAsyncGen):\n\n NODES_UPDATE_INTERVAL = 15\n\n TIMEOUT = 10 # seconds\n\n def __init__(self, use_ssl=False, **kwargs):\n connection_string = 'couchbase://{}/{}?password={}'\n\n if use_ssl:\n connection_string = connection_string.replace('couchbase',\n 'couchbases')\n connection_string += '&certpath=root.pem'\n\n connection_string = connection_string.format(kwargs['host'],\n kwargs['bucket'],\n kwargs['password'])\n\n self.client = Bucket(connection_string=connection_string)\n self.client.timeout = self.TIMEOUT\n\n self.session = requests.Session()\n self.session.auth = (kwargs['username'], kwargs['password'])\n self.server_nodes = ['{}:{}'.format(kwargs['host'],\n kwargs.get('port', 8091))]\n self.nodes_url = 'http://{}:{}/pools/default/buckets/{}/nodes'.format(\n kwargs['host'],\n kwargs.get('port', 8091),\n kwargs['bucket'],\n )\n\n def start_updater(self):\n self.t = Thread(target=self._get_list_of_servers)\n self.t.daemon = True\n self.t.start()\n\n def _get_list_of_servers(self):\n while True:\n try:\n nodes = self.session.get(self.nodes_url).json()\n except Exception as e:\n logger.warn('Failed to get list of servers: {}'.format(e))\n continue\n self.server_nodes = [n['hostname'] for n in nodes['servers']]\n sleep(self.NODES_UPDATE_INTERVAL)\n\n @quiet\n @backoff\n def create(self, *args, **kwargs):\n super().create(*args, **kwargs)\n\n @quiet\n @timeit\n def read(self, *args, **kwargs):\n super().read(*args, **kwargs)\n\n @quiet\n @backoff\n @timeit\n def update(self, *args, **kwargs):\n super().update(*args, **kwargs)\n\n @quiet\n def delete(self, *args, **kwargs):\n super().delete(*args, **kwargs)\n\n @timeit\n def view_query(self, ddoc, view, query):\n node = choice(self.server_nodes).replace('8091', '8092')\n url = 'http://{}/{}/_design/{}/_view/{}?{}'.format(\n node, self.client.bucket, ddoc, view, query.encoded\n )\n self.session.get(url=url)\n\n @quiet\n @timeit\n def n1ql_query(self, query):\n tuple(self.client.n1ql_query(query))\n\n\nclass SubDocGen(CBGen):\n\n @quiet\n @timeit\n def read(self, key: str, field: str):\n self.client.lookup_in(key, subdocument.get(path=field))\n\n @quiet\n @timeit\n def update(self, key: str, field: str, doc: dict):\n new_field_value = doc[field]\n self.client.mutate_in(key, subdocument.upsert(path=field,\n value=new_field_value))\n\n @quiet\n @timeit\n def read_xattr(self, key: str, field: str):\n self.client.lookup_in(key, subdocument.get(path=field,\n xattr=True))\n\n @quiet\n @timeit\n def update_xattr(self, key: str, field: str, doc: dict):\n self.client.mutate_in(key, subdocument.upsert(path=field,\n value=doc,\n xattr=True,\n create_parents=True))\n\n\nclass FtsGen(CBGen):\n\n QUERY_TEMPLATE = {\"ctl\": {\"timeout\": 0}, \"query\": {}, \"size\": 10}\n\n def __init__(self, master_node, settings, auth=None):\n\n self.master_node = master_node\n self.query_port = settings.port\n self.auth = auth\n self.requests = requests.Session()\n self.http_pool = self.new_http_pool()\n\n self.settings = settings\n self.query_nodes = self.get_nodes()\n self.nodes_list_size = len(self.query_nodes)\n self.query_list = []\n self.header = {'Content-Type': 'application/json'}\n self.bool_map = {'conjuncts': 'must', 'disjuncts': 'should'}\n self.query_list_size = 0\n\n self.prepare_query_list()\n\n def new_http_pool(self):\n basic_auth = '{}:{}'.format(self.auth.username, self.auth.password)\n headers = urllib3.make_headers(keep_alive=True, basic_auth=basic_auth)\n headers.update({'Content-Type': 'application/json'})\n\n return urllib3.PoolManager(headers=headers)\n\n @property\n def query_template(self):\n return self.QUERY_TEMPLATE\n\n def get_nodes(self):\n nodes = []\n cluster_map = requests.get(url='http://{}:8091/pools/default'.format(self.master_node),\n auth=self.auth).json()\n for node in cluster_map['nodes']:\n if 'fts' in node['services']:\n url = node['hostname'].split(\":\")[0]\n nodes.append(url)\n return nodes\n\n def form_url(self, full_query):\n url = \"http://{}:{}/api/index/{}/query\".format(self.next_node(),\n self.query_port,\n self.settings.name)\n return {'url': url,\n 'auth': self.auth,\n 'headers': self.header,\n 'data': json.dumps(full_query)\n }\n\n @staticmethod\n def process_lines(line):\n if len(line) == 0:\n raise Exception('Empty line')\n value = line.strip().split()\n if len(value) == 2:\n return line.strip().split()\n else:\n return line.strip(), None\n\n @staticmethod\n def process_conj_disj(ttypes):\n index = 0\n keytypes = []\n while index < len(ttypes):\n count = int(ttypes[index])\n keytypes += count * [ttypes[index + 1]]\n index += 2\n return itertools.cycle(keytypes)\n\n def prepare_query_list(self):\n if self.settings.query_file:\n with open(self.settings.query_file, 'r') as tfile:\n for line in tfile:\n temp_query = {}\n tosearch, freq = FtsGen.process_lines(line.strip())\n query_type = self.settings.type\n if query_type in ['2_conjuncts', '2_disjuncts', '1_conjuncts_2_disjuncts']:\n from collections import defaultdict\n keytypes = FtsGen.process_conj_disj(query_type.split('_'))\n temp_query = defaultdict(list)\n tbool = {v: {k: None} for k, v in self.bool_map.items()}\n\n for terms in line.split():\n\n tmp_key = next(keytypes)\n temp_query[tmp_key].append({\"field\": self.settings.field,\n \"term\": terms})\n\n if query_type == '1_conjuncts_2_disjuncts':\n for k, v in self.bool_map.items():\n tbool[v][k] = temp_query[k]\n temp_query = tbool\n\n elif query_type == 'fuzzy':\n temp_query['fuzziness'] = int(freq)\n temp_query['term'] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == 'numeric':\n if freq.strip() == 'max_min':\n temp_query['max'], temp_query['min'] = \\\n [float(k) for k in tosearch.split(':')]\n elif freq.strip() == 'max':\n temp_query['max'] = float(tosearch)\n else:\n temp_query['min'] = float(tosearch)\n temp_query['inclusive_max'] = False\n temp_query['inclusive_min'] = False\n temp_query['field'] = self.settings.field\n\n elif query_type in ['match', 'match_phrase']:\n tosearch = line.strip()\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == 'ids':\n tosearch = [tosearch]\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n elif query_type == \"facet\":\n\n start_date, end_date = freq.split(':')\n temp_query[\"query\"] = \"text:{}\".format(tosearch)\n temp_query[\"boost\"] = 1\n self.query_template['fields'] = [\"*\"]\n self.query_template[\"facets\"] = {self.settings.field:\n {\"size\": self.settings.query_size,\n \"field\": self.settings.field,\n \"date_ranges\": [{\"name\": \"end\",\n \"end\": end_date},\n {\"name\": \"start\",\n \"start\": start_date}]}}\n else:\n temp_query[query_type] = tosearch\n temp_query['field'] = self.settings.field\n\n self.query_template['query'] = temp_query\n self.query_template['size'] = self.settings.query_size\n self.query_list.append(self.form_url(self.query_template))\n\n self.query_list_size = len(self.query_list)\n shuffle(self.query_list)\n\n def next(self):\n return self.requests.post, self.query_list[randint(0, self.query_list_size - 1)]\n\n def next_node(self):\n return self.query_nodes[randint(0, self.nodes_list_size - 1)]\n\n def execute_query(self, query):\n return self.http_pool.request('POST', query['url'], body=query['data'])\n\n\nclass ElasticGen(FtsGen):\n\n QUERY_TEMPLATE = {\"query\": {}, \"size\": 10}\n\n def form_url(self, full_query):\n url = \"http://{}:9200/{}/_search\".format(self.next_node(), self.settings.name)\n return {'url': url,\n 'auth': None,\n 'headers': self.header,\n 'data': json.dumps(full_query)\n }\n\n def get_nodes(self):\n nodes = []\n cluster_map = requests.get(url='http://{}:9200/_nodes'.format(self.master_node)).json()\n for node in cluster_map['nodes'].values():\n url = node[\"ip\"]\n nodes.append(url)\n return nodes\n\n def prepare_query_list(self):\n if self.settings.query_file:\n with open(self.settings.query_file, 'r') as tfile:\n for line in tfile:\n term, freq = ElasticGen.process_lines(line.strip())\n tmp_query = {}\n tmp_query_txt = {}\n query_type = self.settings.type\n if query_type == 'fuzzy':\n tmp_fuzzy = {\n 'fuzziness': int(freq),\n 'value': term,\n }\n tmp_query_txt[self.settings.field] = tmp_fuzzy\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type == 'ids':\n tmp_query_txt['values'] = [term]\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type in ['match', 'match_phrase']:\n tmp_query_txt[self.settings.field] = line.strip()\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type == 'range':\n trange = {}\n if freq.strip() == 'max_min':\n trange['gte'], trange['lte'] = [float(k) for k in term.split(':')]\n elif freq.strip() == 'max':\n trange['gte'] = float(term)\n else:\n trange['lte'] = float(term)\n tmp_query_txt[self.settings.field] = trange\n tmp_query[query_type] = tmp_query_txt\n\n elif query_type in ['2_conjuncts', '2_disjuncts', '1_conjuncts_2_disjuncts']:\n tbool = {v: [] for k, v in self.bool_map.items()}\n keytypes = ElasticGen.process_conj_disj(query_type.split('_'))\n for term in line.strip().split():\n key = self.bool_map[next(keytypes)]\n tbool[key].append({'term': {self.settings.field: term}})\n tmp_query_txt = tbool\n tmp_query['bool'] = tmp_query_txt\n\n elif query_type == 'facet':\n start_date, end_date = freq.split(':')\n tmp_query = {\"term\": {\"text\": term}}\n self.query_template['size'] = self.settings.query_size\n self.query_template['aggs'] = {\n \"perf_elastic_index\": {\n \"date_range\": {\n \"field\": self.settings.field,\n \"format\": \"YYYY-MM-DD\",\n \"ranges\": [\n {\n \"from\": start_date,\n \"to\": end_date,\n },\n ]\n },\n \"aggs\": {\n \"terms_count\": {\"terms\": {\"field\": \"text\"}},\n },\n },\n }\n\n else:\n tmp_query_txt[self.settings.field] = term\n tmp_query[query_type] = tmp_query_txt\n\n self.query_template['query'] = tmp_query\n self.query_list.append(self.form_url(self.query_template))\n self.query_list_size = len(self.query_list)\n shuffle(self.query_list)\n", "sub_path": "spring/cbgen.py", "file_name": "cbgen.py", "file_ext": "py", "file_size_in_byte": 16144, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "couchbase.experimental.enable", "line_number": 25, "usage_type": "call"}, {"api_name": "couchbase.experimental", "line_number": 25, "usage_type": "name"}, {"api_name": "couchbase.exceptions.ConnectError", "line_number": 32, "usage_type": "name"}, {"api_name": "couchbase.exceptions.CouchbaseError", "line_number": 32, "usage_type": "name"}, {"api_name": "couchbase.exceptions.HTTPError", "line_number": 32, "usage_type": "name"}, {"api_name": "couchbase.exceptions.KeyExistsError", "line_number": 32, "usage_type": "name"}, {"api_name": "couchbase.exceptions.NotFoundError", "line_number": 33, "usage_type": "name"}, {"api_name": "couchbase.exceptions.TimeoutError", "line_number": 33, "usage_type": "name"}, {"api_name": "logger.logger.warn", "line_number": 34, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 34, "usage_type": "name"}, {"api_name": "decorator.decorator", "line_number": 28, "usage_type": "name"}, {"api_name": "couchbase.exceptions.TemporaryFailError", "line_number": 42, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 43, "usage_type": "call"}, {"api_name": "decorator.decorator", "line_number": 37, "usage_type": "name"}, {"api_name": "time.time", "line_number": 48, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "decorator.decorator", "line_number": 46, "usage_type": "name"}, {"api_name": "txcouchbase.connection.Connection", "line_number": 58, "usage_type": "call"}, {"api_name": "couchbase.bucket.Bucket", "line_number": 92, "usage_type": "call"}, {"api_name": "requests.Session", "line_number": 95, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 106, "usage_type": "call"}, {"api_name": "logger.logger.warn", "line_number": 115, "usage_type": "call"}, {"api_name": "logger.logger", "line_number": 115, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 118, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 142, "usage_type": "call"}, {"api_name": "couchbase.subdocument.get", "line_number": 159, "usage_type": "call"}, {"api_name": "couchbase.subdocument", "line_number": 159, "usage_type": "name"}, {"api_name": "couchbase.subdocument.upsert", "line_number": 165, "usage_type": "call"}, {"api_name": "couchbase.subdocument", "line_number": 165, "usage_type": "name"}, {"api_name": "couchbase.subdocument.get", "line_number": 171, "usage_type": "call"}, {"api_name": "couchbase.subdocument", "line_number": 171, "usage_type": "name"}, {"api_name": "couchbase.subdocument.upsert", "line_number": 177, "usage_type": "call"}, {"api_name": "couchbase.subdocument", "line_number": 177, "usage_type": "name"}, {"api_name": "requests.Session", "line_number": 192, "usage_type": "call"}, {"api_name": "urllib3.make_headers", "line_number": 207, "usage_type": "call"}, {"api_name": "urllib3.PoolManager", "line_number": 210, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 218, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 233, "usage_type": "call"}, {"api_name": "itertools.cycle", "line_number": 254, "usage_type": "call"}, {"api_name": "{'defaultdict': 'collections.defaultdict'}.process_conj_disj", "line_number": 265, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 266, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 329, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 332, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 335, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 350, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 355, "usage_type": "call"}, {"api_name": "random.shuffle", "line_number": 434, "usage_type": "call"}]}
+{"seq_id": "183771419", "text": "import time\n\nimport pytest\n\nfrom pages.cart_page import CartPage\nfrom pages.login_page import LoginPage\nfrom pages.product_page import ProductPage\n\n\n@pytest.fixture\ndef setup(browser):\n link = \"http://selenium1py.pythonanywhere.com/ru/accounts/login/\"\n page = LoginPage(browser, link)\n page.open()\n email = str(time.time()) + \"@fakemail.org\"\n page.register_new_user(email, \"123password123\")\n page.should_be_authorized_user()\n\n@pytest.mark.parametrize('link', [\"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer0\"])\nclass TestUserAddToCartFromProductPage(object):\n def test_user_cant_see_success_message(self, browser, link, setup):\n link = link\n page = ProductPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n @pytest.mark.need_review\n def test_user_can_add_product_to_cart(self, browser, link, setup):\n link = link\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.solve_quiz_and_get_code()\n page.should_be_added_to_cart()\n\n\n@pytest.mark.need_review\ndef test_guest_can_add_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer0\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.solve_quiz_and_get_code()\n page.should_be_added_to_cart()\n\n\n@pytest.mark.xfail\ndef test_guest_cant_see_success_message_after_adding_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.should_not_be_success_message()\n\n\n@pytest.mark.xfail\ndef test_message_disappeared_after_adding_product_to_cart(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_cart()\n page.should_not_be_appeared_success_message()\n\n\ndef test_guest_should_see_login_link_on_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\n@pytest.mark.need_review\ndef test_guest_can_go_to_login_page_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.go_to_login_page()\n\n\n@pytest.mark.need_review\ndef test_guest_cant_see_product_in_cart_opened_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.go_to_cart()\n cart_page = CartPage(browser, browser.current_url)\n cart_page.should_be_empty_cart()\n cart_page.should_be_empty_cart_message()", "sub_path": "test_product_page.py", "file_name": "test_product_page.py", "file_ext": "py", "file_size_in_byte": 2963, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pages.login_page.LoginPage", "line_number": 13, "usage_type": "call"}, {"api_name": "time.time", "line_number": 15, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 10, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 23, "usage_type": "call"}, {"api_name": "pages.product_page.ProductPage", "line_number": 30, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 27, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 19, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 40, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 50, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 59, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 67, "usage_type": "call"}, {"api_name": "pages.product_page.ProductPage", "line_number": 75, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 72, "usage_type": "attribute"}, {"api_name": "pages.product_page.ProductPage", "line_number": 83, "usage_type": "call"}, {"api_name": "pages.cart_page.CartPage", "line_number": 86, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 80, "usage_type": "attribute"}]}
+{"seq_id": "576153263", "text": "from youtube2notion.youtube2notion import Youtube2notion\nimport click\n\n\n@click.command()\n@click.argument('video_id')\n@click.option('--output-dir', '-o', 'output_dir', required=False, type=str)\n@click.option(\n '--notion-token-v2', '-t', 'notion_token_v2', required=False, type=str)\n@click.option(\n '--notion-page-url', '-p', 'notion_page_url', required=False, type=str)\n@click.option(\n '--text_language', '-l', 'text_language', required=False, type=str)\ndef youtube2notion(video_id: str, output_dir, notion_token_v2, notion_page_url, text_language):\n if not output_dir:\n output_dir = './tmp/%s/' % video_id\n\n click.echo('video_id: %s' % video_id)\n click.echo('output_dir: %s' % output_dir)\n click.echo('notion_token_v2: %s' % notion_token_v2)\n click.echo('notion_page_url: %s' % notion_page_url)\n click.echo('text_language: %s' % text_language)\n\n y2n = Youtube2notion(\n video_id=video_id,\n output_dir=output_dir,\n notion_token_v2=notion_token_v2,\n notion_page_url=notion_page_url,\n text_language=text_language)\n\n try:\n y2n.execute()\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n youtube2notion()\n", "sub_path": "youtube2notion.py", "file_name": "youtube2notion.py", "file_ext": "py", "file_size_in_byte": 1208, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "click.echo", "line_number": 18, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 19, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 20, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 21, "usage_type": "call"}, {"api_name": "click.echo", "line_number": 22, "usage_type": "call"}, {"api_name": "youtube2notion.youtube2notion.Youtube2notion", "line_number": 24, "usage_type": "call"}, {"api_name": "click.command", "line_number": 5, "usage_type": "call"}, {"api_name": "click.argument", "line_number": 6, "usage_type": "call"}, {"api_name": "click.option", "line_number": 7, "usage_type": "call"}, {"api_name": "click.option", "line_number": 8, "usage_type": "call"}, {"api_name": "click.option", "line_number": 10, "usage_type": "call"}, {"api_name": "click.option", "line_number": 12, "usage_type": "call"}, {"api_name": "youtube2notion.youtube2notion", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "218781597", "text": "import requests\nimport bs4\n\nENTRY_URL = \"http://oa.intranet.htisec.net/names.nsf?Login\"\nMAIN_URL = \"http://oa.intranet.htisec.net/htisec/crdd.nsf/0/B061277A869828E0482580C000171342?opendocument\"\nID_FILE = \"id.txt\"\n\ndef files_lookup(tgt_dir, pattern, recur_list=False, sub_folder=False, most_recent=True):\n filepath_arr = []\n\n for fi in os.listdir(tgt_dir):\n full_path = os.path.join(tgt_dir, fi)\n if sub_folder and os.path.isdir(full_path):\n filepath_arr += files_lookup(full_path, pattern, recur_list, sub_folder, most_recent)\n if fnmatch.fnmatch(fi, pattern):\n filepath_arr.append(full_path)\n\n filepath_arr.sort(reverse=most_recent)\n if recur_list:\n return filepath_arr\n else:\n return filepath_arr[0]\n\ndef html_content():\n with open(ID_FILE, 'rU') as f: \n username = f.readline().strip()\n password = f.readline().strip()\n\n session = requests.Session()\n res = session.post(ENTRY_URL, { \"Username\":username, \"Password\":password})\n res = session.get(MAIN_URL)\n return res.text\n\ndef find_diff(html):\n \n return\n\ndef main():\n html = html_content()\n with open(\"list.html\", 'wb') as f:\n f.write(html.encode('utf8'))\n find_diff(html)\n\n\n return\n\nif __name__ == \"__main__\":\n print (\"Loading director list\")\n\n try:\n main()\n except KeyboardInterrupt:\n print (\"Ctrl+C pressed. Stopping...\")", "sub_path": "director_list/director_list.py", "file_name": "director_list.py", "file_ext": "py", "file_size_in_byte": 1427, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.Session", "line_number": 29, "usage_type": "call"}]}
+{"seq_id": "221057847", "text": "from rest_framework import serializers\nfrom .models import *\n# from django.contrib.auth.models import User\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth.models import Group, Permission\nfrom rest_framework.serializers import (\n CharField,\n EmailField,\n HyperlinkedIdentityField,\n ModelSerializer,\n SerializerMethodField,\n ValidationError\n)\nfrom django.contrib.auth import get_user_model\n# from accounts.models import User\nUser = get_user_model()\n\nclass UserCreateSerializer(ModelSerializer):\n email = EmailField(label='Email Address')\n # email2 = EmailField(label='Confirm Email')\n\n class Meta:\n model = User\n fields = [\n 'first_name',\n 'last_name',\n 'username',\n 'email',\n # 'email2',\n 'password',\n\n ]\n extra_kwargs = {\"password\":\n {\"write_only\": True}\n }\n\n def validate(self, data):\n # email = data['email']\n # user_qs = User.objects.filter(email=email)\n # if user_qs.exists():\n # raise ValidationError(\"This user has already registered.\")\n return data\n\n def validate_email(self, value):\n data = self.get_initial()\n email1 = data.get(\"email1\")\n # email2 = value\n # if email1 != email2:\n # raise ValidationError(\"Emails must match.\")\n\n user_qs = User.objects.filter(email=email1)\n if user_qs.exists():\n raise ValidationError(\"This user has already registered.\")\n\n return value\n\n def create(self, validated_data):\n first_name = validated_data['first_name']\n last_name = validated_data['last_name']\n username = validated_data['username']\n email = validated_data['email']\n password = validated_data['password']\n\n user_obj = User(\n first_name=first_name,\n last_name=last_name,\n username=username,\n email=email\n )\n user_obj.set_password(password)\n user_obj.save()\n return validated_data\n\nclass UserLoginSerializer(serializers.ModelSerializer):\n token = serializers.CharField(allow_blank=True, read_only=True)\n username = serializers.CharField()\n email = serializers.EmailField(label='Email Address')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'password',\n 'token',\n ]\n\n extra_kwargs = {\"password\":\n {\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n\nclass TenantSerializer(serializers.ModelSerializer):\n\t# house = HouseNumberSerializer(read_only=True)\n\tclass Meta:\n\t\tmodel = Tenant\n\t\tfields = '__all__'\n\n\nclass BuildingSerializer(serializers.ModelSerializer):\n class Meta:\n model = Building\n fields = '__all__'\n\n \nclass HouseNumberSerializer(serializers.ModelSerializer):\n tenant = TenantSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n class Meta:\n model = HouseNumber\n fields = '__all__'\n\nclass RentPaidSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass RentPaidCreateSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass RentPaidListSerializer(serializers.ModelSerializer):\n\ttenant = TenantSerializer(read_only=True)\n\tclass Meta:\n\t\tmodel = RentPaid\n\t\tfields = '__all__'\n\nclass DeactivateTenantSerializer(serializers.ModelSerializer):\n class Meta:\n model = Tenant\n fields = [\n 'not_active',\n # 'date_left',\n ]\n\n\nclass UserSerializer(serializers.ModelSerializer):\n # snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())\n class Meta:\n model = User\n # fields = ('id', 'username')\n fields = '__all__'\n\nclass HouseOccupancySerializer(serializers.ModelSerializer):\n tenant = TenantSerializer(read_only=True)\n house = HouseNumberSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n \n class Meta:\n model = HouseOccupancy\n fields = '__all__'\n\nclass VendorSerializer(serializers.ModelSerializer):\n class Meta:\n model = Vendor\n fields = '__all__'\n\nclass ExpenseSerializer(serializers.ModelSerializer):\n payee = VendorSerializer(read_only=True)\n building = BuildingSerializer(read_only=True)\n\n class Meta:\n model = Expense\n fields = '__all__'\n\n\nclass MerchantSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Merchant\n fields = '__all__'", "sub_path": "rntapp/serializers.py", "file_name": "serializers.py", "file_ext": "py", "file_size_in_byte": 4743, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.contrib.auth.get_user_model", "line_number": 17, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 19, "usage_type": "name"}, {"api_name": "rest_framework.serializers.EmailField", "line_number": 20, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ValidationError", "line_number": 54, "usage_type": "call"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 75, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 75, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 76, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 76, "usage_type": "name"}, {"api_name": "rest_framework.serializers.CharField", "line_number": 77, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 77, "usage_type": "name"}, {"api_name": "rest_framework.serializers.EmailField", "line_number": 78, "usage_type": "call"}, {"api_name": "rest_framework.serializers", "line_number": 78, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 97, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 97, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 104, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 104, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 110, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 110, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 117, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 117, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 122, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 122, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 127, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 127, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 133, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 133, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 142, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 142, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 149, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 149, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 158, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 158, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 163, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 163, "usage_type": "name"}, {"api_name": "rest_framework.serializers.ModelSerializer", "line_number": 172, "usage_type": "attribute"}, {"api_name": "rest_framework.serializers", "line_number": 172, "usage_type": "name"}]}
+{"seq_id": "184544925", "text": "import sys\nfrom collections import Counter, OrderedDict\n\ndata = sys.stdin.read().replace(\" \", \"\")\n\nprint(\"### 10 most frequent letters ###\")\nprint(str(Counter(data).most_common(10)) + \"\\n\")\n\n\nprint(\"### 10 most frequent bi-patterns ###\")\nbi_pattern_list = []\nfor i in range(len(data) - 2):\n bi_pattern_list.append(data[i] + data[i+1])\n\nprint(str(Counter(bi_pattern_list).most_common(10)) + \"\\n\")\n\n\nprint(\"### 10 most frequent tri-patterns ###\")\ntri_pattern_list = []\nfor i in range(len(data) - 3):\n tri_pattern_list.append(data[i] + data[i+1] + data[i+2])\n\nprint(str(Counter(tri_pattern_list).most_common(10)) + \"\\n\")\n\nprint(\"### 10 most frequent quad-patterns ###\")\nquad_pattern_list = []\nfor i in range(len(data) - 4):\n quad_pattern_list.append(data[i] + data[i+1] + data[i+2] + data[i+3])\n\nprint(str(Counter(quad_pattern_list).most_common(10)) + \"\\n\")\n\nprint(\"### most frequent doubles ###\")\ndo_pattern_list = []\nfor i in range(len(data) - 2):\n if(data[i] == data[i+1]):\n do_pattern_list.append(data[i] + data[i+1])\n\nprint(str(Counter(do_pattern_list).most_common()) + \"\\n\")\n", "sub_path": "overthewire/krypton/freq_analyser.py", "file_name": "freq_analyser.py", "file_ext": "py", "file_size_in_byte": 1097, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.stdin.read", "line_number": 4, "usage_type": "call"}, {"api_name": "sys.stdin", "line_number": 4, "usage_type": "attribute"}, {"api_name": "collections.Counter", "line_number": 7, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 15, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 30, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "342581620", "text": "import unicodedata\nimport random\nimport time\nimport math\n\nfrom text_generation.config import ALL_LETTERS, N_LETTERS, SAMPLE_LENGTH\nimport torch\nfrom torch.autograd import Variable\n\n\ndef unicode_to_ascii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in ALL_LETTERS\n )\n\n\ndef read_lines(filename):\n program = open(filename).read().split('--------')\n while '' in program:\n program.remove('')\n return [unicode_to_ascii(line) for line in program]\n\n\ndef read_prose_lines(filename):\n text = open(filename).read().split('.')\n only_long = filter(lambda line: len(line) > 10, text)\n stripped = [line.strip() for line in only_long]\n return [unicode_to_ascii(line) for line in stripped]\n\n\ndef random_choice(l):\n return l[random.randint(0, len(l) - 1)]\n\n\ndef create_input_tensor(line):\n length = SAMPLE_LENGTH if len(line) > SAMPLE_LENGTH else len(line)\n tensor = torch.zeros(length, 1, N_LETTERS)\n for li in range(length):\n letter = line[li]\n tensor[li][0][ALL_LETTERS.find(letter)] = 1\n return tensor\n\n\ndef create_target_tensor(line):\n length = SAMPLE_LENGTH if len(line) > SAMPLE_LENGTH else len(line)\n letter_indexes = [ALL_LETTERS.find(line[li]) for li in range(1,\n length)]\n letter_indexes.append(N_LETTERS - 1)\n return torch.LongTensor(letter_indexes)\n\n\ndef random_training_set(line, sample_length=500, volatile=False):\n length = sample_length if len(line) > sample_length else len(line)\n if length > sample_length:\n random_idx = torch.randint(0, length - sample_length - 1)\n line = line[random_idx : random_idx + sample_length + 1]\n input_line_tensor = Variable(create_input_tensor(line), volatile=volatile)\n target_line_tensor = Variable(create_target_tensor(line), volatile=volatile)\n\n return input_line_tensor, target_line_tensor", "sub_path": "text_generation/utils/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 1920, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "unicodedata.normalize", "line_number": 13, "usage_type": "call"}, {"api_name": "unicodedata.category", "line_number": 14, "usage_type": "call"}, {"api_name": "text_generation.config.ALL_LETTERS", "line_number": 15, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 34, "usage_type": "call"}, {"api_name": "text_generation.config.SAMPLE_LENGTH", "line_number": 38, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 39, "usage_type": "call"}, {"api_name": "text_generation.config.N_LETTERS", "line_number": 39, "usage_type": "argument"}, {"api_name": "text_generation.config.ALL_LETTERS.find", "line_number": 42, "usage_type": "call"}, {"api_name": "text_generation.config.ALL_LETTERS", "line_number": 42, "usage_type": "name"}, {"api_name": "text_generation.config.SAMPLE_LENGTH", "line_number": 47, "usage_type": "name"}, {"api_name": "text_generation.config.ALL_LETTERS.find", "line_number": 48, "usage_type": "call"}, {"api_name": "text_generation.config.ALL_LETTERS", "line_number": 48, "usage_type": "name"}, {"api_name": "text_generation.config.N_LETTERS", "line_number": 50, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.randint", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 60, "usage_type": "call"}]}
+{"seq_id": "457867260", "text": "# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Usage(Model):\n \"\"\"The usage data for a usage request.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param unit: The unit of the metric. Possible values include: 'Count',\n 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',\n 'Milliseconds'\n :type unit: str or ~azure.mgmt.cosmosdb.models.UnitType\n :ivar name: The name information for the metric.\n :vartype name: ~azure.mgmt.cosmosdb.models.MetricName\n :ivar quota_period: The quota period used to summarize the usage values.\n :vartype quota_period: str\n :ivar limit: Maximum value for this metric\n :vartype limit: long\n :ivar current_value: Current value for this metric\n :vartype current_value: long\n \"\"\"\n\n _validation = {\n 'name': {'readonly': True},\n 'quota_period': {'readonly': True},\n 'limit': {'readonly': True},\n 'current_value': {'readonly': True},\n }\n\n _attribute_map = {\n 'unit': {'key': 'unit', 'type': 'str'},\n 'name': {'key': 'name', 'type': 'MetricName'},\n 'quota_period': {'key': 'quotaPeriod', 'type': 'str'},\n 'limit': {'key': 'limit', 'type': 'long'},\n 'current_value': {'key': 'currentValue', 'type': 'long'},\n }\n\n def __init__(self, *, unit=None, **kwargs) -> None:\n super(Usage, self).__init__(**kwargs)\n self.unit = unit\n self.name = None\n self.quota_period = None\n self.limit = None\n self.current_value = None\n", "sub_path": "src/cosmosdb-preview/azext_cosmosdb_preview/vendored_sdks/azure_mgmt_cosmosdb/models/usage_py3.py", "file_name": "usage_py3.py", "file_ext": "py", "file_size_in_byte": 2038, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "msrest.serialization.Model", "line_number": 15, "usage_type": "name"}]}
+{"seq_id": "416851586", "text": "import pandas as pd\nimport numpy as np\nimport json\nimport sys\nfrom GPfates import GPfates\n\nimport time\ncheckpoints = {}\n\n# ____________________________________________________________________________\n# Load data ####\np = json.load(open(\"/input/params.json\", \"r\"))\nend_n = json.load(open(\"/input/end_n.json\"))[0]\nexpression = pd.read_csv(\"/input/expression.csv\", index_col=0, header=0)\nexpression = expression[(expression > p[\"log_expression_cutoff\"]).sum(1) >= p[\"min_cells_expression_cutoff\"]]\n\nif expression.shape[0] == 0:\n raise ValueError(\"Expression preprocessing filtered out all cells\")\n\ncheckpoints[\"method_afterpreproc\"] = time.time()\n\n# ____________________________________________________________________________\n# Infer trajectory ####\ncellinfo = pd.DataFrame({\"cell_id\":expression.index.tolist()}, index = expression.index.tolist())\nm = GPfates.GPfates(cellinfo, expression.T)\n\n# dimensionality reduction\nm.dimensionality_reduction()\nm.store_dr(dims=range(p[\"ndim\"])) # store the dr in the sample table (m.s), so it can be used in the gplvm\n\n# infer pseudotime\nm.infer_pseudotime(s_columns=[\"bgplvm_\" + str(i) for i in range(p[\"ndim\"])]) # use the first two components to infer pseudotime\n\n# model different fates\nm.model_fates(C=end_n)\n\ncheckpoints[\"method_aftermethod\"] = time.time()\n\n# ____________________________________________________________________________\n# Process and save output ####\n# pseudotime\npseudotime = m.s.pseudotime.reset_index()\npseudotime.columns = [\"cell_id\", \"pseudotime\"]\npseudotime.to_csv(\"/output/pseudotime.csv\", index=False)\n\n# milestone network\nmilestone_network = pd.DataFrame({\n \"from\":\"M0\",\n \"to\":[\"M\" + str(i+1) for i in range(end_n)],\n \"length\":1,\n \"directed\":True\n})\nmilestone_network.to_csv(\"/output/milestone_network.csv\", index=False)\n\n# dimred\ndimred = pd.DataFrame(m.dr_models[\"bgplvm\"].X.mean[:,:].tolist())\ndimred[\"cell_id\"] = m.s.pseudotime.index.tolist()\ndimred.to_csv(\"/output/dimred.csv\", index=False)\n\n# progressions\nprogressions = pd.DataFrame(m.fate_model.phi)\nprogressions[\"cell_id\"] = m.s.pseudotime.index.tolist()\nprogressions = progressions.melt(id_vars = [\"cell_id\"], var_name = \"to\", value_name = \"percentage\")\nprogressions[\"to\"] = [\"M\" + str(i+1) for i in progressions[\"to\"]]\nprogressions[\"from\"] = \"M0\"\nprogressions.to_csv(\"/output/progressions.csv\", index=False)\n\n# divergence regions\ndivergence_regions = pd.DataFrame({\n \"milestone_id\": [\"M0\"] + [\"M\" + str(i+1) for i in range(end_n)],\n \"divergence_id\": \"A\",\n \"is_start\": [True] + [False for i in range(end_n)]\n})\ndivergence_regions.to_csv(\"/output/divergence_regions.csv\", index=False)\n\n# timings\njson.dump(checkpoints, open(\"/output/timings.json\", \"w\"))\n", "sub_path": "containers/gpfates/run.py", "file_name": "run.py", "file_ext": "py", "file_size_in_byte": 2866, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "json.load", "line_number": 12, "usage_type": "call"}, {"api_name": "json.load", "line_number": 13, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 14, "usage_type": "call"}, {"api_name": "time.time", "line_number": 20, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 24, "usage_type": "call"}, {"api_name": "GPfates.GPfates.GPfates", "line_number": 25, "usage_type": "call"}, {"api_name": "GPfates.GPfates", "line_number": 25, "usage_type": "name"}, {"api_name": "time.time", "line_number": 37, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 56, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 61, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 69, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 77, "usage_type": "call"}]}
+{"seq_id": "406137094", "text": "from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom buddysapp.forms import UserForm, DispensaryForm\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\n\n# Create your views here.\ndef home(request):\n return redirect(dispensary_home)\n\n@login_required(login_url='/dispensary/sign-in/')\ndef dispensary_home(request):\n return render(request, 'dispensary/home.html', {})\n\ndef dispensary_sign_up(request):\n user_form = UserForm()\n dispensary_form = DispensaryForm()\n\n if request.method == \"POST\":\n user_form = UserForm(request.POST)\n dispensary_form = DispensaryForm(request.POST, request.FILES)\n\n if user_form.is_valid() and dispensary_form.is_valid():\n new_user = User.objects.create_user(**user_form.cleaned_data)\n new_dispensary = dispensary_form.save(commit=False)\n new_dispensary.user = new_user\n new_dispensary.save()\n\n login(request, authenticate(\n username = user_form.cleaned_data[\"username\"],\n password = user_form.cleaned_data[\"password\"]\n ))\n\n return redirect(dispensary_home)\n\n return render(request, 'dispensary/signup.html', {\n \"user_form\": user_form,\n \"dispensary_form\": dispensary_form\n })\n", "sub_path": "buddysapp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 1349, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.shortcuts.redirect", "line_number": 9, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 13, "usage_type": "call"}, {"api_name": "django.contrib.auth.decorators.login_required", "line_number": 11, "usage_type": "call"}, {"api_name": "buddysapp.forms.UserForm", "line_number": 16, "usage_type": "call"}, {"api_name": "buddysapp.forms.DispensaryForm", "line_number": 17, "usage_type": "call"}, {"api_name": "buddysapp.forms.UserForm", "line_number": 20, "usage_type": "call"}, {"api_name": "buddysapp.forms.DispensaryForm", "line_number": 21, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects.create_user", "line_number": 24, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 24, "usage_type": "name"}, {"api_name": "django.contrib.auth.login", "line_number": 29, "usage_type": "call"}, {"api_name": "django.contrib.auth.authenticate", "line_number": 29, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 34, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 36, "usage_type": "call"}]}
+{"seq_id": "247643017", "text": "##\n# Copyright (c) 2015, Derek Ruths, David Jurgens\n#\n# All rights reserved. See LICENSE file for details\n##\nimport argparse\nimport json\nimport os, os.path\nimport gzip\nimport time\n\nfrom slp.build_dataset import posts2dataset\nfrom slp.sparse_dataset import SparseDataset\nfrom slp.spatial_label_propagation import SpatialLabelPropagation\n\ndef train(args):\n parser = argparse.ArgumentParser(prog='geoinf train',description='train a geoinference method on a specific dataset')\n parser.add_argument('-f','--force',help='overwrite the output model directory if it already exists')\n parser.add_argument('method_name',help='the method to use')\n parser.add_argument('method_settings',help='a json file containing method-specific configurations')\n parser.add_argument('dataset_dir',help='a directory containing a geoinference dataset')\n parser.add_argument('model_dir',help='a (non-existing) directory where the trained model will be stored')\n parser.add_argument('--location-source', nargs=1,\n help='specifies the source of ground-truth locations')\n\n args = parser.parse_args(args)\n\n if os.path.exists(args.model_dir):\n question = \"Would you like to remove the existing model directory %s?\" % args.model_dir\n if input(question+' (y/n): ').lower().strip() == \"y\":\n print(\"Removing existing model directory...\")\n os.system(\"rm -r %s\" % args.model_dir)\n else:\n raise Exception('dataset directory %s exists' % args.model_dir)\n\n print('creating directory %s' % args.model_dir)\n os.mkdir(args.model_dir)\n\n # # confirm that the output directory doesn't exist\n # if os.path.exists(args.model_dir) and not args.force:\n # raise Exception('output model_dir cannot exist')\n\n # load the method\n # method = get_method_by_name(args.method_name)\n\n # load the data\n with open(args.method_settings,'r') as fh:\n settings = json.load(fh)\n\n location_source = args.location_source\n if location_source:\n location_source = location_source[0]\n print('Using %s as the source of ground truth location'\n % location_source)\n settings['location_source'] = location_source\n\n\n\n # load the dataset\n ds = None #Dataset(args.dataset_dir)\n if not location_source is None:\n ds = SparseDataset(args.dataset_dir, default_location_source=location_source, settings=settings)\n else:\n ds = SparseDataset(args.dataset_dir, settings=settings)\n\n\n # load the method\n # method = get_method_by_name(args.method_name)\n # method_inst = method()\n method_inst = SpatialLabelPropagation(settings)\n\n print(\"Starting\")\n start_time = time.time()\n method_inst.train_model(settings,ds,args.model_dir)\n end_time = time.time()\n print('Trained model %s on dataset %s in %f seconds'\n % (args.method_name, args.dataset_dir, end_time - start_time))\n\n # drop some metadata into the run method\n # run the method\n # gi_inst = method()\n # gi_inst.train(settings,ds,args.model_dir)\n\n return\n\ndef build_dataset(args):\n parser = argparse.ArgumentParser(prog='geoinf build_dataset',description='build a new dataset')\n parser.add_argument('dataset_dir',help='the directory to put the dataset in')\n parser.add_argument('posts_file',help='the posts.json.gz file to use')\n parser.add_argument('user_id_field',help='the field name holding the user id of the post author')\n parser.add_argument('mention_field',help='the field name holding the list of user ids mentioned in a post (or the friends of a user, those they follow)')\n parser.add_argument('follow_field',help='the field name holding the list of user ids following the given user', nargs='?', type=str, default=None)\n\n args = parser.parse_args(args)\n\n uid_field_name = args.user_id_field.split('.')[::-1]\n mention_field_name = args.mention_field.split('.')[::-1]\n posts2dataset(args.dataset_dir,args.posts_file, args.user_id_field, args.mention_field, args.follow_field)\n\n # done\n\ndef main():\n parser = argparse.ArgumentParser(prog='geoinf',description='run a spatial label propagation method on a dataset')\n parser.add_argument('action',choices=['train','build_dataset'],\n help='indicate whether to train the model or create a dataset')\n parser.add_argument('action_args',nargs=argparse.REMAINDER,\n help='arguments specific to the chosen action')\n\n args = parser.parse_args()\n\n try:\n if args.action == 'train':\n train(args.action_args)\n elif args.action == 'build_dataset':\n build_dataset(args.action_args)\n else:\n raise Exception('unknown action: %s' % args.action)\n\n except Exception as e:\n print(e)\n\n # done!\n\nif __name__ == '__main__':\n main()\n\n\n", "sub_path": "canadian_user_identification/spatial_label_propagation/slp/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 4895, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 17, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "os.system", "line_number": 32, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 37, "usage_type": "call"}, {"api_name": "json.load", "line_number": 48, "usage_type": "call"}, {"api_name": "slp.sparse_dataset.SparseDataset", "line_number": 62, "usage_type": "call"}, {"api_name": "slp.sparse_dataset.SparseDataset", "line_number": 64, "usage_type": "call"}, {"api_name": "slp.spatial_label_propagation.SpatialLabelPropagation", "line_number": 70, "usage_type": "call"}, {"api_name": "time.time", "line_number": 73, "usage_type": "call"}, {"api_name": "time.time", "line_number": 75, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 87, "usage_type": "call"}, {"api_name": "slp.build_dataset.posts2dataset", "line_number": 98, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 103, "usage_type": "call"}, {"api_name": "argparse.REMAINDER", "line_number": 106, "usage_type": "attribute"}]}
+{"seq_id": "368256848", "text": "# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nfrom karbor.common import constants\nfrom karbor.context import RequestContext\nfrom karbor.resource import Resource\nfrom karbor.services.protection.bank_plugin import Bank\nfrom karbor.services.protection.bank_plugin import BankPlugin\nfrom karbor.services.protection.bank_plugin import BankSection\nfrom karbor.services.protection import client_factory\nfrom karbor.services.protection.protection_plugins. \\\n image.image_protection_plugin import GlanceProtectionPlugin\nfrom karbor.services.protection.protection_plugins.image \\\n import image_plugin_schemas\nfrom karbor.tests import base\nimport mock\nfrom oslo_config import cfg\nfrom oslo_config import fixture\n\n\nclass FakeBankPlugin(BankPlugin):\n def update_object(self, key, value):\n return\n\n def get_object(self, key):\n return\n\n def list_objects(self, prefix=None, limit=None, marker=None,\n sort_dir=None):\n return\n\n def delete_object(self, key):\n return\n\n def get_owner_id(self):\n return\n\n\nfake_bank = Bank(FakeBankPlugin())\nfake_bank_section = BankSection(bank=fake_bank, section=\"fake\")\n\nResourceNode = collections.namedtuple(\n \"ResourceNode\",\n [\"value\",\n \"child_nodes\"]\n)\n\n\nImage = collections.namedtuple(\n \"Image\",\n [\"disk_format\",\n \"container_format\",\n \"status\"]\n)\n\n\ndef call_hooks(operation, checkpoint, resource, context, parameters, **kwargs):\n def noop(*args, **kwargs):\n pass\n\n hooks = (\n 'on_prepare_begin',\n 'on_prepare_finish',\n 'on_main',\n 'on_complete',\n )\n for hook_name in hooks:\n hook = getattr(operation, hook_name, noop)\n hook(checkpoint, resource, context, parameters, **kwargs)\n\n\nclass CheckpointCollection(object):\n def __init__(self):\n super(CheckpointCollection, self).__init__()\n self.bank_section = fake_bank_section\n\n def get_resource_bank_section(self, resource_id):\n return self.bank_section\n\n\nclass GlanceProtectionPluginTest(base.TestCase):\n def setUp(self):\n super(GlanceProtectionPluginTest, self).setUp()\n\n plugin_config = cfg.ConfigOpts()\n plugin_config_fixture = self.useFixture(fixture.Config(plugin_config))\n plugin_config_fixture.load_raw_values(\n group='image_backup_plugin',\n poll_interval=0,\n )\n plugin_config_fixture.load_raw_values(\n group='image_backup_plugin',\n backup_image_object_size=65536,\n )\n self.plugin = GlanceProtectionPlugin(plugin_config)\n cfg.CONF.set_default('glance_endpoint',\n 'http://127.0.0.1:9292',\n 'glance_client')\n\n self.cntxt = RequestContext(user_id='demo',\n project_id='abcd',\n auth_token='efgh')\n self.glance_client = client_factory.ClientFactory.create_client(\n \"glance\", self.cntxt)\n self.checkpoint = CheckpointCollection()\n\n def test_get_options_schema(self):\n options_schema = self.plugin.get_options_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema, image_plugin_schemas.OPTIONS_SCHEMA)\n\n def test_get_restore_schema(self):\n options_schema = self.plugin.get_restore_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema, image_plugin_schemas.RESTORE_SCHEMA)\n\n def test_get_saved_info_schema(self):\n options_schema = self.plugin.get_saved_info_schema(\n constants.IMAGE_RESOURCE_TYPE)\n self.assertEqual(options_schema,\n image_plugin_schemas.SAVED_INFO_SCHEMA)\n\n @mock.patch('karbor.services.protection.protection_plugins.image.'\n 'image_protection_plugin.utils.status_poll')\n @mock.patch('karbor.services.protection.clients.glance.create')\n def test_create_backup(self, mock_glance_create, mock_status_poll):\n resource = Resource(id=\"123\",\n type=constants.IMAGE_RESOURCE_TYPE,\n name='fake')\n\n fake_bank_section.update_object = mock.MagicMock()\n\n protect_operation = self.plugin.get_protect_operation(resource)\n mock_glance_create.return_value = self.glance_client\n\n self.glance_client.images.get = mock.MagicMock()\n self.glance_client.images.return_value = Image(\n disk_format=\"\",\n container_format=\"\",\n status=\"active\"\n )\n\n fake_bank_section.update_object = mock.MagicMock()\n self.glance_client.images.data = mock.MagicMock()\n self.glance_client.images.data.return_value = []\n mock_status_poll.return_value = True\n call_hooks(protect_operation, self.checkpoint, resource, self.cntxt,\n {})\n\n def test_delete_backup(self):\n resource = Resource(id=\"123\",\n type=constants.IMAGE_RESOURCE_TYPE,\n name='fake')\n\n fake_bank_section.list_objects = mock.MagicMock()\n fake_bank_section.list_objects.return_value = [\"data_1\", \"data_2\"]\n fake_bank_section.delete_object = mock.MagicMock()\n delete_operation = self.plugin.get_delete_operation(resource)\n call_hooks(delete_operation, self.checkpoint, resource, self.cntxt,\n {})\n\n def test_get_supported_resources_types(self):\n types = self.plugin.get_supported_resources_types()\n self.assertEqual([constants.IMAGE_RESOURCE_TYPE], types)\n", "sub_path": "karbor/tests/unit/protection/test_glance_protection_plugin.py", "file_name": "test_glance_protection_plugin.py", "file_ext": "py", "file_size_in_byte": 6139, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "karbor.services.protection.bank_plugin.BankPlugin", "line_number": 31, "usage_type": "name"}, {"api_name": "karbor.services.protection.bank_plugin.Bank", "line_number": 49, "usage_type": "call"}, {"api_name": "karbor.services.protection.bank_plugin.BankSection", "line_number": 50, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 52, "usage_type": "call"}, {"api_name": "collections.namedtuple", "line_number": 59, "usage_type": "call"}, {"api_name": "karbor.tests.base.TestCase", "line_number": 91, "usage_type": "attribute"}, {"api_name": "karbor.tests.base", "line_number": 91, "usage_type": "name"}, {"api_name": "oslo_config.cfg.ConfigOpts", "line_number": 95, "usage_type": "call"}, {"api_name": "oslo_config.cfg", "line_number": 95, "usage_type": "name"}, {"api_name": "oslo_config.fixture.Config", "line_number": 96, "usage_type": "call"}, {"api_name": "oslo_config.fixture", "line_number": 96, "usage_type": "name"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_protection_plugin.GlanceProtectionPlugin", "line_number": 105, "usage_type": "call"}, {"api_name": "oslo_config.cfg.CONF.set_default", "line_number": 106, "usage_type": "call"}, {"api_name": "oslo_config.cfg.CONF", "line_number": 106, "usage_type": "attribute"}, {"api_name": "oslo_config.cfg", "line_number": 106, "usage_type": "name"}, {"api_name": "karbor.context.RequestContext", "line_number": 110, "usage_type": "call"}, {"api_name": "karbor.services.protection.client_factory.ClientFactory.create_client", "line_number": 113, "usage_type": "call"}, {"api_name": "karbor.services.protection.client_factory.ClientFactory", "line_number": 113, "usage_type": "attribute"}, {"api_name": "karbor.services.protection.client_factory", "line_number": 113, "usage_type": "name"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 119, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 119, "usage_type": "name"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas.OPTIONS_SCHEMA", "line_number": 120, "usage_type": "attribute"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas", "line_number": 120, "usage_type": "name"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 124, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 124, "usage_type": "name"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas.RESTORE_SCHEMA", "line_number": 125, "usage_type": "attribute"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas", "line_number": 125, "usage_type": "name"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 129, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 129, "usage_type": "name"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas.SAVED_INFO_SCHEMA", "line_number": 131, "usage_type": "attribute"}, {"api_name": "karbor.services.protection.protection_plugins.image.image_plugin_schemas", "line_number": 131, "usage_type": "name"}, {"api_name": "karbor.resource.Resource", "line_number": 137, "usage_type": "call"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 138, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 138, "usage_type": "name"}, {"api_name": "mock.MagicMock", "line_number": 141, "usage_type": "call"}, {"api_name": "mock.MagicMock", "line_number": 146, "usage_type": "call"}, {"api_name": "mock.MagicMock", "line_number": 153, "usage_type": "call"}, {"api_name": "mock.MagicMock", "line_number": 154, "usage_type": "call"}, {"api_name": "mock.patch", "line_number": 133, "usage_type": "call"}, {"api_name": "mock.patch", "line_number": 135, "usage_type": "call"}, {"api_name": "karbor.resource.Resource", "line_number": 161, "usage_type": "call"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 162, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 162, "usage_type": "name"}, {"api_name": "mock.MagicMock", "line_number": 165, "usage_type": "call"}, {"api_name": "mock.MagicMock", "line_number": 167, "usage_type": "call"}, {"api_name": "karbor.common.constants.IMAGE_RESOURCE_TYPE", "line_number": 174, "usage_type": "attribute"}, {"api_name": "karbor.common.constants", "line_number": 174, "usage_type": "name"}]}
+{"seq_id": "173651295", "text": "import os\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.ticker import MultipleLocator\n\n\nparser = argparse.ArgumentParser(description='Argument parser')\nparser.add_argument(\"--solution_path\", help=\"Path where the output files are stored\", required = True, type=str)\nparser.add_argument(\"--file_name\", help=\"Name of the file\", required = True, type=str)\nargs = parser.parse_args()\n\ndef main():\n\t\n\t\t\n\tfile = open(args.solution_path + '/' + args.file_name,\"r\") \n\t\t\n\t# Read the first line which contains the width and the height of the paper roll\n\tfirst_line = file.readline().strip().split(\" \")\n\t\n\twidth = int(first_line[0])\n\theight = int(first_line[1])\n\n\t# Read the second line which contains the number of necessary pieces of paper to cut off\n\tsecond_line = file.readline().strip().split(\" \")\n\t\n\tnumber_of_pieces = int(second_line[0])\n\t\n\t# Read all the remaining lines which contains the horizontal and vertical dimensionof the i-th piece of paper\n\tremaining_lines = file.readlines()\n\t# To remove empty lines\n\tremaining_lines = [line.strip() for line in remaining_lines if line.strip()]\n\t\n\tpieces = []\n\t\n\tfor i,line in enumerate(remaining_lines):\n\t\tline = line.split()\n\t\tpieces.append([int(line[0]),int(line[1]),int(line[2]),int(line[3])])\n\n\t\t\n\tfig = plt.figure(figsize=(5 + (width//8) ,5 + (height//8)))\n\tax = fig.gca(title = \"Plot of the solution\")\n\tfor i in range(number_of_pieces):\n\t\tcolor = [\"#\"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])]\n\t\tsq = Rectangle((pieces[i][2],pieces[i][3]),pieces[i][0],pieces[i][1],fill = True,color=color[0], alpha=.3 )\n\t\tax.add_patch(sq)\n\tplt.plot()\n\tplt.show()\n\t\t\n\t\n\tfile.close() \n\t\t\nif __name__ == \"__main__\":\n\tmain()", "sub_path": "SMT/src/solution_grid.py", "file_name": "solution_grid.py", "file_ext": "py", "file_size_in_byte": 1765, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 43, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 43, "usage_type": "name"}, {"api_name": "random.choice", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 50, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 50, "usage_type": "name"}]}
+{"seq_id": "213410359", "text": "\nimport pandas as pd\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import Perceptron,LogisticRegression\nfrom sklearn.metrics import accuracy_score\nfrom matplotlib.colors import ListedColormap\nimport matplotlib.pyplot as plt\n\n\ndef plot_decision_regions(X, y, classifier,test_idx=None, resolution=0.02):\n # setup marker generator and color map\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n # plot the decision surface\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\n np.arange(x2_min, x2_max, resolution))\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n # plot class examples\n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0],y=X[y == cl, 1],alpha=0.8, c=colors[idx],\n marker=markers[idx], label=cl, edgecolor='black')\n\n # highlight test samples\n if test_idx:\n # plot all samples\n X_test, y_test = X[test_idx, :], y[test_idx]\n plt.scatter(X_test[:, 0], X_test[:, 1], c='', edgecolor='black', alpha=1.0,\n linewidth=1, marker='o', s=100, label='test set')\n\ndef load_iris_data():\n iris = datasets.load_iris()\n X = iris.data[:, [2, 3]]\n y = iris.target\n print('Class labels:', np.unique(y))\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1, stratify = y)\n\n print('Labels counts in y_train:', np.bincount(y_train))\n print('Labels counts in y_test:', np.bincount(y_test))\n\n sc = StandardScaler()\n sc.fit(X_train) #Using the fit method, StandardScaler estimated the parameters\n # μ (sample mean) and σ (standard deviation) for each feature dimension from the training data.\n X_train_std = sc.transform(X_train)\n X_test_std = sc.transform(X_test)\n\n return X_train_std,X_test_std,y_train, y_test\n\ndef test_ppn(X_train_std,X_test_std,y_train, y_test):\n ppn = Perceptron(max_iter=40, eta0=0.1, random_state=1)\n ppn.fit(X_train_std, y_train)\n\n y_pred = ppn.predict(X_test_std)\n print('Misclassified samples: %d' % (y_test != y_pred).sum())\n print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))\n\n X_combined_std = np.vstack((X_train_std, X_test_std))\n y_combined = np.hstack((y_train, y_test))\n plot_decision_regions(X=X_combined_std,y = y_combined,classifier = ppn,test_idx = range(105, 150))\n plt.xlabel('petal length [standardized]')\n plt.ylabel('petal width [standardized]')\n plt.legend(loc='upper left')\n plt.show()\n\nclass Logistic_regression():\n def __init__(self,eta=0.0001,n_iter=1000):\n self.max_iter=n_iter\n self.eta=eta\n self.w_initialized = False\n self.shuffle = True\n self.cost_ = []\n\n def fit(self,x,y_gt):\n x_1 = np.hstack((x, np.ones((x.shape[0], 1))))\n self.w_=np.random.random(x_1.shape[-1])\n\n for iter in range(self.max_iter):\n hidden=self.net_input(x_1)\n y_pred=self.activation(hidden)\n dw_=self.eta*np.dot(x_1.T ,y_gt-y_pred)\n print(dw_)\n if np.sum(abs(dw_))<10e-9:\n break\n self.w_+=dw_\n self.cost_.append(-(y_gt*(np.log(y_pred)+(1-y_gt)*np.log(1-y_pred))))\n\n def partial_fit(self, X, y):\n if not self.w_initialized:\n self._initialize_weights(X.shape[1])\n if y.ravel().shape[0] > 1:\n for xi, target in zip(X, y):\n self._update_weights(xi, target)\n else:\n self._update_weights(X, y)\n return self\n\n def predict(self,x):\n x = np.hstack((x,np.ones((x.shape[0],1))))\n y_pred = self.activation(self.net_input(x))\n return np.array([1 if i > 0.5 else 0 for i in y_pred])\n\n def net_input(self,x):\n return np.dot(x,self.w_)#np.sum(x * self.w_, axis=1)\n\n def activation(self, X):\n return 1/(1+np.exp(-np.clip(X, -250, 250)))\n\n def _initialize_weights(self, m):\n self.w_ = np.random.random(1 + m)\n self.w_initialized = True\n\n def _shuffle(self, X, y):\n r = np.random.permutation(len(y))\n return X[r], y[r]\n\ndef plot_sigmoid():\n def sigmoid(z):\n return 1.0 / (1.0 + np.exp(-z))\n\n z = np.arange(-7, 7, 0.1)\n phi_z = sigmoid(z)\n plt.plot(z, phi_z)\n plt.axvline(0.0, color='k')\n plt.ylim(-0.1, 1.1)\n plt.xlabel('z')\n plt.ylabel('$\\phi (z)$') # y axis ticks and gridline\n plt.yticks([0.0, 0.5, 1.0])\n ax = plt.gca()\n ax.yaxis.grid(True)\n plt.show()\n\nX_train_std,X_test_std,y_train, y_test= load_iris_data()\n\n\n\nweights, params = [], []\nfor c in np.arange(-5, 5):\n lr = LogisticRegression(C=10.**c, random_state=1,\n solver='lbfgs',\n multi_class='ovr')\n lr.fit(X_train_std, y_train)\n weights.append(lr.coef_[1])\n params.append(10.**c)\n\nweights = np.array(weights)\nplt.plot(params, weights[:, 0],\n label='petal length')\nplt.plot(params, weights[:, 1], linestyle='--',\n label='petal width')\nplt.ylabel('weight coefficient')\nplt.xlabel('C')\nplt.legend(loc='upper left')\nplt.xscale('log')\n#plt.savefig('images/03_08.png', dpi=300)\nplt.show()", "sub_path": "ch03/sklearn_utils.py", "file_name": "sklearn_utils.py", "file_ext": "py", "file_size_in_byte": 5631, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.colors.ListedColormap", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.contourf", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 26, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 37, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 37, "usage_type": "name"}, {"api_name": "sklearn.datasets.load_iris", "line_number": 41, "usage_type": "call"}, {"api_name": "sklearn.datasets", "line_number": 41, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 44, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.bincount", "line_number": 49, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.StandardScaler", "line_number": 51, "usage_type": "call"}, {"api_name": "sklearn.linear_model.Perceptron", "line_number": 60, "usage_type": "call"}, {"api_name": "sklearn.metrics.accuracy_score", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "numpy.hstack", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 85, "usage_type": "attribute"}, {"api_name": "numpy.dot", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 95, "usage_type": "call"}, {"api_name": "numpy.hstack", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.clip", "line_number": 116, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 119, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 119, "usage_type": "attribute"}, {"api_name": "numpy.random.permutation", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 123, "usage_type": "attribute"}, {"api_name": "numpy.exp", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 132, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 132, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axvline", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 133, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 137, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 137, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gca", "line_number": 138, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 138, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 140, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 140, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 147, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 148, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 156, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 156, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 158, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 158, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 160, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 160, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 161, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xscale", "line_number": 163, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 163, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 165, "usage_type": "name"}]}
+{"seq_id": "223244728", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nLibrary for demonstrating simple collaborative filtering\n@author: barry shepherd\n\"\"\"\n\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport time\nfrom statistics import mean\nfrom math import sqrt\n\n# convert the transaction data (long data) into a ratings matrix (wide data)\n# assume the first two columns are user and item names (which may be strings or integers and may not be contiguous)\n# also generate two lookup tables to map user and item names into indexes for accessing the ratings matrix\ndef makeratingsmatrix(trans):\n trans = trans.iloc[:,0:3] # keep only first 3 columns\n trans.columns = ['user','item','rating']\n # create the mappings between user and item names (as in raw data) and the matrix row and column indexes\n unames = np.sort(trans['user'].unique())\n inames = np.sort(trans['item'].unique())\n umap = dict(zip(unames,[i for i in range(len(unames))]))\n imap = dict(zip(inames,[i for i in range(len(inames))]))\n # create the ratings matrix, use average if multiple raings exist for same (user,item)\n #users = trans.pivot(index='user', columns='item', values='rating').values # fast, but no averaging, rows & cols are alphnum order\n users = pd.pivot_table(trans, index=['user'], columns=['item'], values=['rating'],aggfunc=[mean]).values # slower\n return [users, umap, imap]\n\ndef head(arr,r=10,c=10):\n nr, nc = arr.shape\n with np.printoptions(threshold=np.inf):\n if type(arr) == np.ndarray:\n print(arr[0:min(r,nr),0:min(c,nc)])\n else:\n print(arr.iloc[0:min(r,nr),0:min(c,nc)])\n\ndef sparsity(arr):\n return float(np.isnan(arr).sum()*100)/np.prod(arr.shape)\n #return (1.0 - ( count_nonzero(arr) / float(arr.size) ))\n\ndef wtavg(vals, weights):\n xy = vals * weights\n weights = weights[np.isnan(xy) == False] \n #if len(weights) == 0 : return np.nan\n if sum(weights) == 0 : return np.nan\n vals = vals[np.isnan(xy)==False]\n return sum(vals * weights)/sum(weights)\n \ndef pearsonsim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n if(len(x)==0): return np.nan\n mx=mean(x)\n my=mean(y)\n rt = sqrt(sum((x-mx)**2)*sum((y-my)**2))\n if (rt == 0): return np.nan #math.isnan(rt)==True or \n return sum((x-mx)*(y-my))/rt\n \ndef cosinesim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n if(len(x)==0): return np.nan\n rt = sqrt(sum(x**2)*sum(y**2))\n return sum(x*y)/rt\n\ndef euclidsim(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n z=(y-x)**2\n sz=sqrt(sum(z))\n return 1/(1+sz)\n\ndef euclidsimF(x,y):\n xy = x*y\n x = x[np.isnan(xy)==False]\n y = y[np.isnan(xy)==False]\n z=(y-x)**2\n return 1/(1+sum(z))\n\ndef getitemsimsmatrix(ratsmatrix,simfun):\n r,c = ratsmatrix.shape\n matrx = list([])\n for col1 in range(0,c):\n simrow = [0]*col1\n for col2 in range(col1,c):\n simrow.append(simfun(ratsmatrix[:,col1],ratsmatrix[:,col2]))\n matrx.append(simrow)\n matrx = np.array(matrx)\n matrx = matrx + matrx.T - np.diag(np.diag(matrx))\n return matrx\n \ndef predictrating_UU(targetrats, ratsmatrix, targetitemindx, simfun):\n return predictratings_UU(targetrats, ratsmatrix, doitems=[targetitemindx], simfun=simfun)[0]\n\ndef predictratings_UU(targetrats, ratsmatrix, doitems, simfun=pearsonsim):\n sims = list([])\n for row in ratsmatrix: sims.append(simfun(row,targetrats))\n sims = np.array(sims)\n with np.errstate(invalid='ignore'): sims[sims < 0] = np.nan\n rats = list([])\n for col in doitems: rats.append(wtavg(ratsmatrix[:,col],sims)) # assumes target rating is NA (if target in usersA)\n return np.array(rats)\n\ndef predictrating_II(targetrats, itemsims, targetitemid):\n return predictratings_II(targetrats, itemsims, doitems=[targetitemid])[0]\n\ndef predictratings_II(targetrats,itemsims,doitems):\n seenitems = np.isnan(targetrats)==False\n rats = list([])\n for row in doitems:\n rats.append(wtavg(targetrats[seenitems],itemsims[row,seenitems])) \n return np.array(rats)\n\ndef getRecommendations_UU(targetrats, ratsmatrix, imap, simfun=pearsonsim,topN=5):\n itemnames=list(imap.keys())\n unseenitemids = np.where(np.isnan(targetrats)==True)[0]\n ratsA = predictratings_UU(targetrats, ratsmatrix, doitems=unseenitemids, simfun=simfun)\n rats = pd.DataFrame(ratsA,index=[itemnames[i] for i in unseenitemids],columns=['predrating'])\n rats = rats.sort_values(ascending = False, by=['predrating'])\n return rats[0:min(topN,len(rats))]\n \ndef getRecommendations_II(targetrats, itemsims, imap, topN=5):\n itemnames=list(imap.keys()) \n unseenitemids = np.where(np.isnan(targetrats)==True)[0]\n ratsA = predictratings_II(targetrats,itemsims,doitems=unseenitemids)\n rats = pd.DataFrame(ratsA,index=[itemnames[i] for i in unseenitemids],columns=['predrating'])\n rats = rats.sort_values(ascending = False, by=['predrating'])\n return rats[0:min(topN,len(rats))]\n\n# compute prediction errors (predicted rating - actual rating) for the test events (events ~ 'user,item,rating')\ndef computeErrs_UU(testevents, ratsmatrix, uids, iids, simfun=cosinesim):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n testitemindx = iids[testevent[1]]\n pred = predictrating_UU(ratsmatrix[testuserindx,],ratsmatrix,testitemindx,simfun=simfun)\n res.append(pred-testevent[2])\n return np.array(res)\n\ndef computeErrs_II(testevents, ratsmatrix, uids, iids, itemsims):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n testitemindx = iids[testevent[1]]\n pred = predictrating_II(ratsmatrix[testuserindx,],itemsims,testitemindx)\n res.append(pred-testevent[2])\n return np.array(res)\n\n# returns the percentage ranking for each test event\n# if itemsims is supplied then do item-based CF, else do user-based CF\ndef computePR(testevents, ratsmatrix, uids, iids, itemsims=False, simfun=cosinesim):\n res = list([])\n for testevent in testevents:\n print('.', end = '')\n testuserindx = uids[testevent[0]]\n if (type(itemsims) == bool):\n recs = getRecommendations_UU(ratsmatrix[testuserindx,], ratsmatrix, iids, simfun=simfun, topN=100000)\n else:\n recs = getRecommendations_II(ratsmatrix[testuserindx,], itemsims, iids, topN=100000)\n rkpc = ((recs.index.get_loc(testevent[1]) + 1)*100)/len(recs)\n res.append(rkpc)\n return np.array(res)\n\n \n\n", "sub_path": "Workshop1/demolib-arrays-v9.py", "file_name": "demolib-arrays-v9.py", "file_ext": "py", "file_size_in_byte": 6674, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.sort", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.sort", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.pivot_table", "line_number": 28, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 28, "usage_type": "name"}, {"api_name": "numpy.printoptions", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.inf", "line_number": 33, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 34, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 40, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 47, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 55, "usage_type": "attribute"}, {"api_name": "statistics.mean", "line_number": 56, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 57, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 59, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 66, "usage_type": "attribute"}, {"api_name": "math.sqrt", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 73, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.errstate", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 104, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 107, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 113, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 121, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.isnan", "line_number": 129, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 131, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 169, "usage_type": "call"}]}
+{"seq_id": "325800756", "text": "import fnmatch\nimport re\nimport itertools\n\nfrom .. import config\nfrom ..types import Origin\nfrom ..dao.containerutil import FileReference, create_containerreference_from_filereference, create_filereference_from_dictionary\nfrom ..web.errors import APIValidationException, InputValidationException\n\nfrom . import gears\nfrom .jobs import Job\nfrom .mappers import RulesMapper\nfrom .queue import Queue\n\nlog = config.log\n\n# {\n# '_id': 'SOME_ID',\n# 'project_id': 'SOME_PROJECT',\n\n# Algorithm to run if all sets of rules match\n# 'alg': 'my-gear-name',\n#\n# At least one match from this array must succeed, or array must be empty\n# 'any': [],\n#\n# There should be no matches in this array\n# 'not': [],\n#\n# All matches from array must succeed, or array must be empty\n# 'all': [\n# {\n# 'type': 'file.type', # Match the file's type\n# 'value': 'dicom'\n# },\n# {\n# 'type': 'file.name', # Match a shell glob for the file name\n# 'value': '*.dcm'\n# },\n# {\n# 'type': 'file.modality', # Match the file's modaliy\n# 'value': 'MR'\n# },\n# {\n# 'type': 'file.classification', # Match any of the file's classification\n# 'value': 'diffusion'\n# },\n# {\n# 'type': 'container.has-type', # Match the container having any file (including this one) with this type\n# 'value': 'bvec'\n# },\n# {\n# 'type': 'container.has-classification', # Match the container having any file (including this one) with this classification\n# 'value': 'functional'\n# }\n# ]\n# }\n\n\ndef get_base_rules():\n \"\"\"\n Fetch the install-global gear rules from the database\n \"\"\"\n\n # rule_doc = config.db.singletons.find_one({'_id': 'rules'}) or {}\n # return rule_doc.get('rule_list', [])\n return []\n\ndef _log_file_key_error(file_, container, error):\n log.warning('file ' + file_.get('name', '?') + ' in container ' + str(container.get('_id', '?')) + ' ' + error)\n\ndef eval_match(match_type, match_param, file_, container, regex=False):\n \"\"\"\n Given a match entry, return if the match succeeded.\n \"\"\"\n\n def match(value):\n if regex:\n return re.match(match_param, value, flags=re.IGNORECASE) is not None\n elif match_type == 'file.name':\n return fnmatch.fnmatch(value.lower(), match_param.lower())\n else:\n return match_param.lower() == value.lower()\n\n # Match the file's type\n if match_type == 'file.type':\n file_type = file_.get('type')\n if file_type:\n return match(file_type)\n else:\n _log_file_key_error(file_, container, 'has no type')\n return False\n\n # Match the file's modality\n if match_type == 'file.modality':\n file_modality = file_.get('modality')\n if file_modality:\n return match(file_modality)\n else:\n return False\n\n # Match a shell glob for the file name\n elif match_type == 'file.name':\n return match(file_['name'])\n\n # Match any of the file's classification\n elif match_type == 'file.classification':\n if match_param:\n classification_values = list(itertools.chain.from_iterable(file_.get('classification', {}).itervalues()))\n return any(match(value) for value in classification_values)\n else:\n return False\n\n # Match the container having any file (including this one) with this type\n elif match_type == 'container.has-type':\n for c_file in container['files']:\n c_file_type = c_file.get('type')\n if c_file_type and match(c_file_type):\n return True\n\n return False\n\n # Match the container having any file (including this one) with this classification\n elif match_type == 'container.has-classification':\n if match_param:\n for c_file in container['files']:\n classification_values = list(itertools.chain.from_iterable(c_file.get('classification', {}).itervalues()))\n if any(match(value) for value in classification_values):\n return True\n\n return False\n\n raise Exception('Unimplemented match type ' + match_type)\n\ndef eval_rule(rule, file_, container):\n \"\"\"\n Decide if a rule should spawn a job.\n \"\"\"\n\n # Are there matches in the 'not' set?\n for match in rule.not_:\n if eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n return False\n\n # Are there matches in the 'any' set?\n must_match = len(rule.any_) > 0\n has_match = False\n\n for match in rule.any_:\n if eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n has_match = True\n break\n\n # If there were matches in the 'any' array and none of them succeeded\n if must_match and not has_match:\n return False\n\n # Are there matches in the 'all' set?\n for match in rule.all_:\n if not eval_match(match['type'], match['value'], file_, container, regex=match.get('regex')):\n return False\n\n return True\n\ndef queue_job_legacy(gear_id, input_, fixed_inputs=None):\n \"\"\"\n Tie together logic used from the no-manifest, single-file era.\n Takes a single FileReference instead of a map.\n \"\"\"\n\n gear = gears.get_gear(gear_id)\n gear = gears.filter_optional_inputs(gear)\n fixed_input_keys = [fixed_input['input'] for fixed_input in fixed_inputs] if fixed_inputs else []\n\n if gears.count_file_inputs(gear) - len(fixed_input_keys) != 1:\n # This shouldn't happen if the handler is correctly validating the POST and PUT methods for rules\n log.error(\"Legacy gear enqueue attempt of \" + gear_id + \" failed: must have exactly 1 non-fixed input from the manifest, it has {} non-fixed inputs\".format(gears.count_file_inputs(gear) - len(fixed_input_keys)))\n return\n\n for x in gear['gear']['inputs'].keys():\n if gear['gear']['inputs'][x]['base'] == 'file' and x not in fixed_input_keys:\n input_name = x\n\n inputs = {\n input_name: input_\n }\n\n if fixed_inputs:\n for fixed_input in fixed_inputs:\n inputs[fixed_input['input']] = FileReference(type=fixed_input['type'], id=str(fixed_input['id']),\n name=fixed_input['name'])\n\n gear_name = gear['gear']['name']\n destination = create_containerreference_from_filereference(input_)\n job = Job(gear, inputs, destination=destination, tags=['auto', gear_name])\n return job\n\ndef find_type_in_container(container, type_):\n for c_file in container['files']:\n if type_ == c_file['type']:\n return c_file\n return None\n\ndef create_potential_jobs(db, container, container_type, file_, rule_failure_callback=None):\n \"\"\"\n Check all rules that apply to this file, and creates the jobs that should be run.\n Jobs are created but not enqueued.\n Returns list of potential job objects containing job ready to be inserted and rule.\n rule_failure_callback will be called for each rule evauation that fails for any reason\n \"\"\"\n\n potential_jobs = []\n\n # Skip if virus scan feature enabled and the file is quarantined\n if config.get_feature('virus_scan', False):\n virus_scan_state = file_.get('virus_scan', {}).get('state')\n if virus_scan_state and virus_scan_state != 'clean':\n log.info('Skipping rule evaluation for %s: %s %s - file is not clean',\n container_type, container['_id'], file_['name'])\n return []\n\n # Get configured rules for this project\n rules = get_rules_for_container(db, container)\n\n # Add hardcoded rules that cannot be removed or changed\n for hardcoded_rule in get_base_rules():\n rules.append(hardcoded_rule)\n\n for rule in rules:\n try:\n if eval_rule(rule, file_, container):\n gear_id = rule.gear_id\n\n input_ = FileReference(type=container_type, id=str(container['_id']), name=file_['name'])\n job = queue_job_legacy(gear_id, input_, fixed_inputs=rule.fixed_inputs)\n\n if 'config' in rule:\n job.config = rule.config\n\n if 'compute_provider_id' in rule:\n job.compute_provider_id = rule['compute_provider_id']\n\n if 'compute_provider_id' in rule:\n job.compute_provider_id = rule['compute_provider_id']\n\n potential_jobs.append({\n 'job': job,\n 'rule': rule.to_dict()\n })\n except Exception as exc_val: # pylint: disable=broad-except\n log.exception('Unable to evaluate rule %s(name=%s)', rule['_id'], rule.get('name'))\n if rule_failure_callback:\n rule_failure_callback(rule, exc_val)\n\n return potential_jobs\n\ndef create_jobs(db, container_before, container_after, container_type, replaced_files=None, rule_failure_callback=None):\n \"\"\"\n Given a before and after set of file attributes, enqueue a list of jobs that would only be possible\n after the changes.\n Returns the algorithm names that were queued.\n \"\"\"\n if container_type == 'collection':\n return []\n\n # A list of FileContainerReferences that have been completely replaced\n # Jobs with these as inputs should get enqueue even if they are in the jobs_before list\n if not replaced_files:\n replaced_files = []\n\n jobs_before, jobs_after, potential_jobs = [], [], []\n\n files_before = container_before.get('files', [])\n files_after = container_after.get('files', [])\n\n for f in files_before:\n jobs_before.extend(create_potential_jobs(db, container_before, container_type, f, rule_failure_callback=rule_failure_callback))\n\n for f in files_after:\n jobs_after.extend(create_potential_jobs(db, container_after, container_type, f, rule_failure_callback=rule_failure_callback))\n\n # Using a uniqueness constraint, create a list of the set difference of jobs_after \\ jobs_before\n # (members of jobs_after that are not in jobs_before)\n for ja in jobs_after:\n replaced_file_name = ''\n\n replaced_file_in_job_inputs = False\n list_of_inputs = [i for i in ja['job'].inputs.itervalues()]\n for replaced_file in replaced_files:\n if replaced_file in list_of_inputs:\n replaced_file_name = replaced_file.name\n replaced_file_in_job_inputs = True\n break\n\n if replaced_file_in_job_inputs:\n # one of the replaced files is an input\n log.info('Scheduling job for %s=%s via rule=<%s>, replaced_file=<%s>.',\n container_type, container_before['_id'], ja['rule'].get('name'), replaced_file_name)\n potential_jobs.append(ja)\n else:\n should_enqueue_job = True\n for jb in jobs_before:\n if ja['job'].intention_equals(jb['job']):\n log.info('Ignoring rule: <%s> for %s=%s - Job has already been queued!',\n ja['rule'].get('name'), container_type, container_before['_id'])\n should_enqueue_job = False\n break # this job matched in both before and after, ignore\n if should_enqueue_job:\n log.info('Scheduling job for %s=%s via rule=<%s>.',\n container_type, container_before['_id'], ja['rule'].get('name'))\n potential_jobs.append(ja)\n\n\n spawned_jobs = []\n origin ={\n 'type': str(Origin.system),\n 'id': None\n }\n\n for pj in potential_jobs:\n job_map = pj['job'].map()\n try:\n # This can raise if we somehow ended up with an invalid provider\n job = Queue.enqueue_job(job_map, origin)\n job.insert()\n spawned_jobs.append(pj['rule']['gear_id'])\n except Exception as exc_val: # pylint: disable=broad-except\n rule = pj.get('rule', {})\n log.exception('Unable to evaluate rule %s(name=%s)', rule.get('_id'), rule.get('name'))\n if rule_failure_callback:\n rule_failure_callback(rule, exc_val)\n\n return spawned_jobs\n\n\n# TODO: consider moving to a module that has a variety of hierarchy-management helper functions\ndef get_rules_for_container(db, container):\n \"\"\"\n Recursively walk the hierarchy until the project object is found.\n \"\"\"\n\n if 'session' in container:\n session = db.sessions.find_one({'_id': container['session']})\n return get_rules_for_container(db, session)\n elif 'project' in container:\n project = db.projects.find_one({'_id': container['project']})\n return get_rules_for_container(db, project)\n else:\n rules_mapper = RulesMapper()\n # Assume container is a project, or a collection (which currently cannot have a rules property)\n result = list(rules_mapper.find_all(project_id=str(container['_id']), disabled={'$ne': True}))\n\n if not result:\n return []\n else:\n return result\n\ndef copy_site_rules_for_project(project_id):\n \"\"\"\n Copy and insert all site-level rules for project.\n\n Note: Assumes project exists and caller has access.\n \"\"\"\n\n rules_mapper = RulesMapper()\n site_rules = rules_mapper.find_all(project_id='site')\n\n for rule in site_rules:\n rule_copy = rule.copy()\n rule_copy.project_id = str(project_id)\n rules_mapper.insert(rule_copy)\n\n\ndef validate_regexes(rule):\n invalid_patterns = set()\n for match in rule.get('all', []) + rule.get('any', []) + rule.get('not', []):\n if match.get('regex'):\n pattern = match['value']\n try:\n re.compile(pattern)\n except re.error:\n invalid_patterns.add(pattern)\n if invalid_patterns:\n raise APIValidationException(\n reason='Cannot compile regex patterns',\n patterns=sorted(invalid_patterns)\n )\n\n\ndef validate_auto_update(rule_config, gear_id, update_gear_is_latest, current_gear_is_latest, fixed_inputs):\n if rule_config:\n raise InputValidationException(\"Gear rule cannot be auto-updated with a config\")\n if fixed_inputs:\n raise InputValidationException(\"Gear rule cannot be auto-updated with fixed inputs\")\n # Can only change gear_id to latest id\n # (Really only happens if updating auto_update and gear_id at once)\n elif gear_id:\n if not update_gear_is_latest:\n raise InputValidationException(\"Cannot manually change gear version of gear rule that is auto-updated\")\n elif not current_gear_is_latest:\n raise InputValidationException(\"Gear rule cannot be auto-updated unless it is uses the latest version of the gear\")\n\n\ndef validate_fixed_inputs(geardoc, fixed_inputs):\n \"\"\"\n Validates the fixed inputs for a rule given a gear doc\n The fixed inputs must:\n - add up to one less than the number of required gear inputs\n - all be valid inputs for the gear\n - exist\n \"\"\"\n fixed_inputs = fixed_inputs if fixed_inputs else []\n if gears.count_file_inputs(gears.filter_optional_inputs(geardoc)) - len(fixed_inputs) != 1:\n raise InputValidationException(\"Rule must have exactly 1 non-fixed gear value\")\n for fixed_input in fixed_inputs:\n if not geardoc['gear']['inputs'].get(fixed_input['input']):\n raise InputValidationException(\"Unrecognized gear input cannot be fixed for the rule\")\n # Check to see that each fixed input actually exists\n create_filereference_from_dictionary(fixed_input).get_file()\n\n", "sub_path": "api/jobs/rules.py", "file_name": "rules.py", "file_ext": "py", "file_size_in_byte": 15822, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "re.match", "line_number": 79, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 79, "usage_type": "attribute"}, {"api_name": "fnmatch.fnmatch", "line_number": 81, "usage_type": "call"}, {"api_name": "itertools.chain.from_iterable", "line_number": 109, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 109, "usage_type": "attribute"}, {"api_name": "itertools.chain.from_iterable", "line_number": 127, "usage_type": "call"}, {"api_name": "itertools.chain", "line_number": 127, "usage_type": "attribute"}, {"api_name": "dao.containerutil.FileReference", "line_number": 190, "usage_type": "call"}, {"api_name": "dao.containerutil.create_containerreference_from_filereference", "line_number": 194, "usage_type": "call"}, {"api_name": "jobs.Job", "line_number": 195, "usage_type": "call"}, {"api_name": "dao.containerutil.FileReference", "line_number": 234, "usage_type": "call"}, {"api_name": "types.Origin.system", "line_number": 316, "usage_type": "attribute"}, {"api_name": "types.Origin", "line_number": 316, "usage_type": "name"}, {"api_name": "queue.Queue.enqueue_job", "line_number": 324, "usage_type": "call"}, {"api_name": "queue.Queue", "line_number": 324, "usage_type": "name"}, {"api_name": "mappers.RulesMapper", "line_number": 349, "usage_type": "call"}, {"api_name": "mappers.RulesMapper", "line_number": 365, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 380, "usage_type": "call"}, {"api_name": "re.error", "line_number": 381, "usage_type": "attribute"}, {"api_name": "web.errors.APIValidationException", "line_number": 384, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 392, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 394, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 399, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 401, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 414, "usage_type": "call"}, {"api_name": "web.errors.InputValidationException", "line_number": 417, "usage_type": "call"}, {"api_name": "dao.containerutil.create_filereference_from_dictionary", "line_number": 419, "usage_type": "call"}]}
+{"seq_id": "365044088", "text": "import sys\nimport os\nimport json\nimport pickle\nimport pprint\nsys.path.append('../')\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom bleu import bleu\nfrom cider import cider\n\nfrom base import framework\nimport encoder.pca\nimport decoder.att_rnn_rl\nimport d.full_sc\nimport model.util\n\nDEC = 'decoder'\nDIS = 'discriminator'\n\nclass ModelConfig(framework.GanModelConfig):\n def __init__(self):\n super(ModelConfig, self).__init__()\n\n self.subcfgs[DEC] = decoder.att_rnn_rl.Config()\n self.subcfgs[DIS] = d.full_sc.Config()\n\n self.strategy = 'beam'\n\n self.d_late_fusion = False\n self.d_quality_alpha = .8\n self.g_baseline = 'greedy'\n\n\ndef gen_cfg(**kwargs):\n cfg = ModelConfig()\n cfg.trn_batch_size = 64\n cfg.tst_batch_size = 64\n cfg.val_iter = -1\n cfg.monitor_iter = 100\n\n cfg.g_num_epoch = kwargs['g_num_epoch']\n cfg.g_base_lr = kwargs['g_lr']\n cfg.g_freeze = kwargs['g_freeze']\n cfg.g_freeze_epoch = kwargs['g_freeze_epoch']\n\n cfg.d_num_epoch = kwargs['d_num_epoch']\n cfg.d_base_lr = kwargs['d_lr']\n cfg.d_iter = kwargs['d_iter']\n cfg.d_val_acc = kwargs['d_val_acc']\n cfg.d_buffer_size = kwargs['d_buffer_size']\n cfg.d_late_fusion = kwargs['d_late_fusion']\n cfg.d_quality_alpha = kwargs['d_quality_alpha']\n cfg.g_baseline = kwargs['g_baseline']\n\n dec_cfg = cfg.subcfgs[DEC]\n dec_cfg.dim_embed = kwargs['dim_embed']\n dec_cfg.dim_att_ft = kwargs['dim_att_ft']\n dec_cfg.dropin = kwargs['g_dropin']\n dec_cfg.dropout = kwargs['g_dropout']\n dec_cfg.max_step = kwargs['max_step']\n dec_cfg.beam_width = kwargs['beam_width']\n dec_cfg.tied_key_val = kwargs['tied_key_val']\n dec_cfg.val_proj = kwargs['val_proj']\n dec_cfg.num_sample = kwargs['num_sample']\n\n cell_cfg = dec_cfg.subcfgs[decoder.att_rnn_rl.CELL]\n cell_cfg.dim_embed = kwargs['dim_embed']\n cell_cfg.dim_hidden = kwargs['dim_hidden']\n cell_cfg.dim_key = kwargs['dim_key']\n cell_cfg.dim_val = kwargs['dim_val']\n cell_cfg.num_att_ft = kwargs['num_att_ft']\n cell_cfg.dim_boom = kwargs['dim_boom']\n\n att_cfg = cell_cfg.subcfgs[decoder.att_rnn_rl.ATT]\n att_cfg.dim_hidden = kwargs['dim_hidden']\n att_cfg.dim_key = kwargs['dim_key']\n att_cfg.dim_val = kwargs['dim_val']\n att_cfg.num_att_ft = kwargs['num_att_ft']\n att_cfg.sim = kwargs['sim']\n\n dis_cfg = cfg.subcfgs[DIS]\n dis_cfg.dim_kernel = kwargs['dim_kernel']\n dis_cfg.num_kernel = kwargs['num_kernel']\n dis_cfg.noise = kwargs['d_noise']\n dis_cfg.dim_ft = kwargs['dim_ft']\n\n sent_enc_cfg = dis_cfg.subcfgs[d.simple.SE]\n sent_enc_cfg.cell = kwargs['cell']\n sent_enc_cfg.dim_embed = kwargs['dim_embed']\n sent_enc_cfg.dim_hidden = kwargs['dim_hidden']\n sent_enc_cfg.dropin = kwargs['d_noise']\n\n return cfg\n\n\nclass Model(nn.Module):\n def __init__(self, config):\n super(Model, self).__init__()\n\n self._config = config\n dec_cfg = self._config.subcfgs[DEC]\n dis_cfg = self._config.subcfgs[DIS]\n\n self.decoder = decoder.att_rnn_rl.Decoder(dec_cfg)\n self.discriminator = d.full_sc.Discriminator(dis_cfg)\n\n self.op2monitor = {}\n\n def forward(self, mode, **kwargs):\n if mode == 'g_trn':\n log_probs = kwargs['log_probs']\n log_masks = kwargs['log_masks']\n rewards = kwargs['rewards']\n\n b = rewards.size(0)\n loss = -rewards.view(b, 1) * log_probs\n loss = torch.sum(loss * log_masks) / torch.sum(log_masks)\n\n self.op2monitor['reward'] = rewards.mean()\n self.op2monitor['loss'] = loss\n\n return loss\n elif mode == 'd_trn':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n y = kwargs['y']\n\n loss, loss_img, loss_sent, dist2img, dist2sent = self.discriminator('trn', fts, sents, lens, y=y)\n if self._config.d_late_fusion:\n alpha = self._config.d_quality_alpha\n return alpha * loss_img + (1. - alpha) * loss_sent\n else:\n return loss\n elif mode == 'g_sample':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('sample', init_state, att_fts, att_masks)\n elif mode == 'd_eval':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n\n return self.discriminator('eval', fts, sents, lens, \n greedy_sents=kwargs['greedy_sents'], greedy_lens=kwargs['greedy_lens'])\n elif mode == 'd_val':\n fts = kwargs['fts']\n sents = kwargs['sents']\n lens = kwargs['lens']\n \n return self.discriminator('val', fts, sents, lens)\n elif mode == 'g_val':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('val', init_state, att_fts, att_masks)\n elif mode == 'g_tst':\n att_fts = kwargs['att_fts']\n att_masks = kwargs['att_masks']\n\n cell_config = self._config.subcfgs[DEC].subcfgs[decoder.att_rnn_rl.CELL]\n b = att_fts.size(0)\n init_state = torch.zeros(b, cell_config.dim_hidden).cuda()\n init_state = (init_state, init_state)\n\n return self.decoder('tst', init_state, att_fts, att_masks, strategy=kwargs['strategy'])\n\n def g_trainable_params(self):\n params = []\n for name, param in self.named_parameters():\n if name.startswith('encoder') or name.startswith('decoder'):\n print(name)\n params.append(param)\n return params\n\n def d_trainable_params(self):\n params = []\n for name, param in self.named_parameters():\n if name.startswith('discriminator'):\n print(name)\n params.append(param)\n return params\n\n\nPathCfg = model.util.AttPathCfg\n\n\nclass TrnTst(framework.GanTrnTst):\n def __init__(self, model_cfg, path_cfg, gpuids):\n super(TrnTst, self).__init__(model_cfg, path_cfg, gpuids)\n\n self.int2str = model.util.CaptionInt2str(path_cfg.word_file)\n\n def g_feed_data_forward_backward(self, data):\n # 1. sample from g\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n sample_out_wids, log_probs, greedy_out_wids = self.model('g_sample', att_fts=att_fts, att_masks=att_masks)\n\n # 2. eval d to get reward\n EOS = 1\n\n b, num_sample, _ = sample_out_wids.size()\n sample_out_wids = sample_out_wids.view(b*num_sample, -1)\n lens = []\n for sample in sample_out_wids:\n for k, wid in enumerate(sample):\n if wid == EOS:\n lens.append(k) # exclude EOS\n break\n else:\n lens.append(k+1)\n lens = torch.LongTensor(lens).cuda()\n data['samples'] = sample_out_wids.data.cpu().numpy()\n data['sample_lens'] = lens.data.cpu().tolist()\n\n greedy_lens = []\n for greedy in greedy_out_wids:\n for k, wid in enumerate(greedy):\n if wid == EOS:\n greedy_lens.append(k) # exclude EOS\n break\n else:\n greedy_lens.append(k+1)\n \n fts = torch.Tensor(data['fts']).cuda()\n log_p, log_p_img, log_p_sent, greedy_p, greedy_p_img, greedy_p_sent = \\\n self.model('d_eval', \n fts=fts, \n sents=sample_out_wids.transpose(0, 1), \n lens=lens, \n greedy_sents=greedy_out_wids.transpose(0, 1), \n greedy_lens=greedy_lens)\n if self.model_cfg.d_late_fusion:\n alpha = self.model_cfg.d_quality_alpha\n log_p = alpha * log_p_img + (1. - self.model_cfg.d_quality_alpha) * log_p_sent\n greedy_p = greedy_p_img + greedy_p_sent\n log_p = log_p.view(b, num_sample)\n if self.model_cfg.g_baseline == 'greedy':\n rewards = log_p - greedy_p.unsqueeze(1)\n elif self.model_cfg.g_baseline == 'mean':\n rewards = log_p - log_p.mean(dim=1, keepdim=True)\n rewards = rewards.view(b*num_sample)\n\n # 3. train by surrogate loss\n log_probs = log_probs.view(b*num_sample, -1)\n log_masks = torch.zeros_like(log_probs)\n for i, sample in enumerate(sample_out_wids):\n for j, wid in enumerate(sample):\n if wid == EOS:\n log_masks[i, :j+1] = 1.\n log_masks = log_masks.cuda()\n\n loss = self.model(\n 'g_trn', log_probs=log_probs, log_masks=log_masks, rewards=rewards)\n loss.backward()\n\n def g_feed_data_forward(self, data):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n sample_out_wids, log_probs, greedy_out_wids = self.model('g_sample', att_fts=att_fts, att_masks=att_masks)\n\n EOS = 1\n b, num_sample, _ = sample_out_wids.size()\n sample_out_wids = sample_out_wids.view(b*num_sample, -1)\n lens = []\n for sample in sample_out_wids:\n for k, wid in enumerate(sample):\n if wid == EOS:\n lens.append(k) # exclude EOS\n break\n else:\n lens.append(k+1)\n lens = torch.LongTensor(lens).cuda()\n data['samples'] = sample_out_wids.data.cpu().numpy()\n data['sample_lens'] = lens.data.cpu().tolist()\n\n def d_feed_data_forward_backward(self, data):\n fts = torch.Tensor(data['fts']).cuda()\n captionids = torch.LongTensor(data['samples']).transpose(0, 1).cuda()\n lens = torch.LongTensor(data['sample_lens']).cuda()\n b = lens.size(0)\n y = torch.zeros(b, dtype=torch.long).cuda()\n loss = self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n captionids = model.util.pad_sequence(data['pos_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['pos_lens']).cuda()\n y = torch.ones(b, dtype=torch.long).cuda()\n loss += self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n captionids = model.util.pad_sequence(data['neg_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['neg_lens']).cuda()\n y = torch.zeros(b, dtype=torch.long).cuda()\n loss += self.model('d_trn', fts=fts, sents=captionids, lens=lens, y=y)\n\n loss.backward()\n\n # return acc\n def d_validation(self, buffer):\n hit = 0.\n hit_img = 0.\n hit_sent = 0.\n cnt = 0\n for data in buffer:\n fts = torch.Tensor(data['fts']).cuda()\n b, f = fts.size()\n num_sample = self.model_cfg.subcfgs[DEC].num_sample\n captionids = torch.LongTensor(data['samples']).transpose(0, 1).cuda()\n lens = torch.LongTensor(data['sample_lens']).cuda()\n predicts, predicts_img, predicts_sent = self.model('d_val', fts=fts, sents=captionids, lens=lens)\n hit += torch.sum(predicts[:, 0] > predicts[:, 1]).item()\n hit_img += torch.sum(predicts_img[:, 0] > predicts_img[:, 1]).item()\n hit_sent += torch.sum(predicts_sent[:, 0] > predicts_sent[:, 1]).item()\n cnt += lens.size(0)\n\n captionids = model.util.pad_sequence(data['pos_captionids'])\n captionids = torch.LongTensor(captionids).cuda()\n lens = torch.LongTensor(data['pos_lens']).cuda()\n predicts, predicts_img, predicts_sent = self.model('d_val', fts=fts, sents=captionids, lens=lens)\n hit += torch.sum(predicts[:, 1] > predicts[:, 0]).item()\n hit_img += torch.sum(predicts_img[:, 1] > predicts_img[:, 0]).item()\n hit_sent += torch.sum(predicts_sent[:, 1] > predicts_sent[:, 0]).item()\n cnt += lens.size(0)\n\n return hit / cnt\n\n # return metric dictionary\n def g_validation(self):\n vid2predicts = {}\n for data in self.tst_reader.yield_batch(self.model_cfg.tst_batch_size):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n\n with torch.no_grad():\n out_wids = self.model('g_val', att_fts=att_fts, att_masks=att_masks)\n\n out_wids = out_wids.data.cpu().numpy()\n for i, sent in enumerate(out_wids):\n vid = data['vids'][i]\n vid2predicts[vid] = self.int2str(np.expand_dims(sent, 0))\n\n metrics = {}\n\n bleu_scorer = bleu.Bleu(4)\n bleu_score, _ = bleu_scorer.compute_score(self.tst_reader.vid2captions, vid2predicts)\n for i in range(4):\n metrics['bleu%d'%(i+1)] = bleu_score[i]\n\n cider_scorer = cider.Cider()\n cider_score, _ = cider_scorer.compute_score(self.tst_reader.vid2captions, vid2predicts)\n metrics['cider'] = cider_score\n\n return metrics\n\n def g_predict_in_tst(self):\n vid2predict = {}\n for data in self.tst_reader.yield_batch(self.model_cfg.tst_batch_size):\n att_fts = torch.Tensor(data['att_fts']).cuda()\n att_masks = torch.ones(att_fts.size()[:-1]).cuda()\n\n if self.model_cfg.strategy == 'beam':\n with torch.no_grad():\n beam_cum_log_probs, beam_pres, beam_ends, out_wids = self.model(\n 'g_tst', att_fts=att_fts, att_masks=att_masks, strategy='beam')\n beam_cum_log_probs = beam_cum_log_probs.data.cpu().numpy()\n beam_pres = beam_pres.data.cpu().numpy()\n beam_ends = beam_ends.data.cpu().numpy()\n out_wids = out_wids.data.cpu().numpy()\n\n if self.model_cfg.pool_size == 1:\n candidates = model.util.beamsearch_recover_captions(\n out_wids, beam_cum_log_probs, beam_pres, beam_ends)\n\n for i, candidate in enumerate(candidates):\n vid = data['vids'][i]\n sent = np.array(candidate, dtype=np.int)\n predict = self.int2str(np.expand_dims(sent, 0))[0]\n vid2predict[str(vid)] = predict\n else:\n candidate_scores = model.util.beamsearch_recover_multiple_captions(\n out_wids, beam_cum_log_probs, beam_pres, beam_ends, self.model_cfg.pool_size)\n\n for i, candidate_score in enumerate(candidate_scores):\n vid = data['vids'][i]\n out = []\n for d in candidate_score:\n sent = np.array(d['sent'])\n predict = self.int2str(np.expand_dims(sent, 0))[0]\n score = float(d['score'])\n out.append({\n 'sent': predict,\n 'score': score,\n }) \n vid2predict[str(vid)] = out\n\n with open(self.path_cfg.predict_file, 'w') as fout:\n json.dump(vid2predict, fout)\n", "sub_path": "model/vead_gan_sc.py", "file_name": "vead_gan_sc.py", "file_ext": "py", "file_size_in_byte": 14186, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.path.append", "line_number": 6, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 6, "usage_type": "attribute"}, {"api_name": "base.framework.GanModelConfig", "line_number": 23, "usage_type": "attribute"}, {"api_name": "base.framework", "line_number": 23, "usage_type": "name"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl.Config", "line_number": 27, "usage_type": "call"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 27, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 27, "usage_type": "name"}, {"api_name": "d.full_sc.full_sc.Config", "line_number": 28, "usage_type": "call"}, {"api_name": "d.full_sc.full_sc", "line_number": 28, "usage_type": "attribute"}, {"api_name": "d.full_sc", "line_number": 28, "usage_type": "name"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 69, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 69, "usage_type": "name"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 77, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 77, "usage_type": "name"}, {"api_name": "d.full_sc.simple", "line_number": 90, "usage_type": "attribute"}, {"api_name": "d.full_sc", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 99, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 99, "usage_type": "name"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl.Decoder", "line_number": 107, "usage_type": "call"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 107, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 107, "usage_type": "name"}, {"api_name": "d.full_sc.full_sc.Discriminator", "line_number": 108, "usage_type": "call"}, {"api_name": "d.full_sc.full_sc", "line_number": 108, "usage_type": "attribute"}, {"api_name": "d.full_sc", "line_number": 108, "usage_type": "name"}, {"api_name": "torch.sum", "line_number": 120, "usage_type": "call"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 142, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 142, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 144, "usage_type": "call"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 165, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 165, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 167, "usage_type": "call"}, {"api_name": "decoder.att_rnn_rl.att_rnn_rl", "line_number": 175, "usage_type": "attribute"}, {"api_name": "decoder.att_rnn_rl", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.zeros", "line_number": 177, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 199, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 199, "usage_type": "name"}, {"api_name": "base.framework.GanTrnTst", "line_number": 202, "usage_type": "attribute"}, {"api_name": "base.framework", "line_number": 202, "usage_type": "name"}, {"api_name": "model.util.util.CaptionInt2str", "line_number": 206, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 206, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 206, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 211, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 227, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 240, "usage_type": "call"}, {"api_name": "torch.zeros_like", "line_number": 261, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 273, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 274, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 288, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 293, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 294, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 295, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 297, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 297, "usage_type": "attribute"}, {"api_name": "model.util.util.pad_sequence", "line_number": 300, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 300, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 300, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 301, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 302, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 303, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 303, "usage_type": "attribute"}, {"api_name": "model.util.util.pad_sequence", "line_number": 306, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 306, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 306, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 307, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 308, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 309, "usage_type": "call"}, {"api_name": "torch.long", "line_number": 309, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 321, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 324, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 325, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 327, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 328, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 329, "usage_type": "call"}, {"api_name": "model.util.util.pad_sequence", "line_number": 332, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 332, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 332, "usage_type": "name"}, {"api_name": "torch.LongTensor", "line_number": 333, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 334, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 336, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 337, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 338, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 347, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 348, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 350, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 356, "usage_type": "call"}, {"api_name": "bleu.bleu.Bleu", "line_number": 360, "usage_type": "call"}, {"api_name": "bleu.bleu", "line_number": 360, "usage_type": "name"}, {"api_name": "cider.cider.Cider", "line_number": 365, "usage_type": "call"}, {"api_name": "cider.cider", "line_number": 365, "usage_type": "name"}, {"api_name": "torch.Tensor", "line_number": 374, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 375, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 378, "usage_type": "call"}, {"api_name": "model.util.util.beamsearch_recover_captions", "line_number": 387, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 387, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 387, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 392, "usage_type": "call"}, {"api_name": "numpy.int", "line_number": 392, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 393, "usage_type": "call"}, {"api_name": "model.util.util.beamsearch_recover_multiple_captions", "line_number": 396, "usage_type": "call"}, {"api_name": "model.util.util", "line_number": 396, "usage_type": "attribute"}, {"api_name": "model.util", "line_number": 396, "usage_type": "name"}, {"api_name": "d.full_sc", "line_number": 402, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 403, "usage_type": "call"}, {"api_name": "d.full_sc", "line_number": 403, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 404, "usage_type": "call"}, {"api_name": "d.full_sc", "line_number": 405, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 413, "usage_type": "call"}]}
+{"seq_id": "653685987", "text": "##############################################################################\n#\n# Copyright (c) 2003, 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Functional tests for File.\n\n$Id: ftests.py 25177 2004-06-02 13:17:31Z jim $\n\"\"\"\nimport unittest\nfrom xml.sax.saxutils import escape\nfrom StringIO import StringIO\n\nfrom zope.app.tests.functional import BrowserTestCase\nfrom zope.app.file.file import File\n\nclass FileTest(BrowserTestCase):\n\n content = u'File ' \n\n def addFile(self):\n file = File(self.content)\n root = self.getRootFolder()\n root['file'] = file\n self.commit()\n\n def testAddForm(self):\n response = self.publish(\n '/+/zope.app.file.File=',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Add a File' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_('Object Name' in body)\n self.assert_('\"Add\"' in body)\n self.checkForBrokenLinks(body, '/+/zope.app.file.File=',\n 'mgr:mgrpw')\n\n def testAdd(self):\n response = self.publish(\n '/+/zope.app.file.File=',\n form={'type_name': u'zope.app.file.File',\n 'field.contents.data': StringIO('A file'),\n 'field.contents.mimeType': u'',\n 'field.contents.encoding': u'',\n 'add_input_name': u'file',\n 'UPDATE_SUBMIT': u'Add'},\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 302)\n self.assertEqual(response.getHeader('Location'),\n 'http://localhost/@@contents.html')\n root = self.getRootFolder()\n self.assert_('file' in root)\n file = root['file']\n self.assertEqual(file.data, 'A file')\n\n def testEditForm(self):\n self.addFile()\n response = self.publish(\n '/file/fileedit.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Change a text file' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_(escape(self.content) in body)\n self.checkForBrokenLinks(body, '/file/@@fileedit.html', 'mgr:mgrpw')\n\n def testEdit(self):\n self.addFile()\n response = self.publish(\n '/file/fileedit.html',\n form={'field.contents.data': 'A File
',\n 'field.contents.mimeType': 'text/plain',\n 'field.contents.encoding': '',\n 'UPDATE_SUBMIT': u'Change'},\n basic='mgr:mgrpw')\n\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Change a text file' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.assert_(escape(u'A File
') in body)\n root = self.getRootFolder()\n file = root['file']\n self.assertEqual(file.open('r').read(), 'A File
')\n self.assertEqual(file.getMimeType(), 'text/plain')\n\n def testUploadForm(self):\n self.addFile()\n response = self.publish(\n '/file/@@fileupload.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Encoding Type' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.failIf(escape(self.content) in body)\n self.checkForBrokenLinks(body, '/file/@@fileupload.html', 'mgr:mgrpw')\n\n def testUpload(self):\n self.addFile()\n response = self.publish(\n '/file/@@fileupload.html',\n basic='mgr:mgrpw',\n form={'field.contents.data': StringIO('New file'),\n 'field.contents.mimeType': u'',\n 'field.contents.encoding': u'',\n 'add_input_name': u'file',\n 'UPDATE_SUBMIT': u'Add'})\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('Encoding Type' in body)\n self.assert_('Content Type' in body)\n self.assert_('Data' in body)\n self.failIf(escape(u'New File
') in body)\n root = self.getRootFolder()\n file = root['file']\n self.assertEqual(file.open('r').read(), 'New file
')\n self.assertEqual(file.getMimeType(), 'text/plain')\n \n def testIndex(self):\n self.addFile()\n response = self.publish(\n '/file/@@index.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assertEqual(body, self.content)\n self.checkForBrokenLinks(body, '/file/@@index.html', 'mgr:mgrpw')\n\n def testPreview(self):\n self.addFile()\n response = self.publish(\n '/file/@@preview.html',\n basic='mgr:mgrpw')\n self.assertEqual(response.getStatus(), 200)\n body = response.getBody()\n self.assert_('
\n \n \n \n \n ''', \"html.parser\")\n\n cls.css_select_soup = BeautifulSoup(\n '''\n \n \n \n \n Here is my styled paragraph
\n \n \n \n ''', \"html.parser\")\n\n\n\n ##Directly defined tags, to compare with BS output.\n\n #a generic anchor tag for append testing\n cls.an_append_tag = cls.soup.new_tag(\"a\")\n cls.an_append_tag.string = \"Foo\"\n cls.an_appended_tag = cls.soup.new_tag(\"a\")\n cls.an_appended_tag.string = \"FooBar\"\n\n #a generic anchor tag\n cls.a_tag = cls.soup.new_tag(\"a\") \n cls.a_tag.string = \"An anchor tag\"\n\n #First, second, third anchor\n cls.a_tag_first = cls.soup.new_tag(\"a\") \n cls.a_tag_first.string = \"First anchor tag\"\n\n cls.a_tag_second = cls.soup.new_tag(\"a\") \n cls.a_tag_second.string = \"Second anchor tag\"\n\n cls.a_tag_third = cls.soup.new_tag(\"a\") \n cls.a_tag_third.string = \"Third anchor tag\"\n\n #a-tag with id\n cls.a_tag_id = cls.soup.new_tag(\"a\", id=\"my_link\") \n\n #p-tag with class attribute\n cls.p_tag_css = cls.soup.new_tag(\"p\", **{'class':'my_CSS_class'})\n cls.p_tag_css.string = \"Here is my styled paragraph\"\n\n #tag with no name\n cls.no_name_tag = cls.soup.new_tag(\"\")\n\n\n def test_soup_contents(self):\n ''' Test the contents attribute, which returns the contents of a tag. \n Note the line break elements\n A string should throw error on contents'''\n\n tags = [\"\\n\", self.a_tag_first, \"\\n\", self.a_tag_second, \"\\n\", self.a_tag_third, \"\\n\"]\n\n self.assertEqual(self.a_nested_soup.p.p.p.p.contents, tags)\n self.assertEqual(self.a_nested_soup.p.p.p.p.a.contents, [self.a_tag_first.string])\n\n with self.assertRaises(AttributeError):\n self.assertEqual(self.a_nested_soup.p.p.p.p.a.string.contents, 0) \n\n \n def test_soup_string(self):\n ''' Test the string attribute for finding the string in a tag '''\n \n markup = 'A tag string'\n string = 'A tag string'\n string_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(string_soup.a.string, string)\n\n def test_soup_stringless(self):\n ''' Test soup constructor for nonexisting string '''\n \n markup = \"\"\n stringless_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(stringless_soup.a.string, None)\n\n def test_soup_strings(self):\n ''' Test soup constructor for strings '''\n \n markup = 'String0String1String2'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = [\"String0\", \"String1\", \"String2\"]\n\n soup_strings = []\n for string in soup.strings:\n soup_strings.append(string)\n\n self.assertEqual(soup_strings, strings)\n\n with self.assertRaises(IndexError):\n soup_strings[3]\n\n def test_soup_no_strings(self):\n '''Test soup constructor for strings without strings'''\n\n markup = ''\n no_strings_soup = BeautifulSoup(markup, \"html.parser\")\n strings = []\n for string in no_strings_soup.strings:\n strings.append(string)\n self.assertEqual(strings, [])\n\n\n def test_soup_head(self):\n ''' Test attribute navigation for head tag '''\n \n markup = 'head testparagraph
'\n\n head_content_markup = ['head test']\n soup = BeautifulSoup(markup, \"html.parser\")\n \n head_tag = soup.new_tag(\"head\")\n head_tag.string = \"head test\"\n \n self.assertEqual(soup.head, head_tag)\n self.assertEqual(soup.head.contents, head_tag.contents)\n\n def test_soup_headless(self):\n ''' Test attribute navigation without head tag '''\n \n markup = 'paragraph
'\n headless_soup = BeautifulSoup(markup, \"html.parser\")\n \n self.assertEqual(headless_soup.head, None)\n\n def test_soup_title(self):\n ''' Test attribute navigation for title tag '''\n \n markup = 'A title'\n title_soup = BeautifulSoup(markup, \"html.parser\")\n\n title_tag = title_soup.new_tag(\"title\")\n title_tag.string = 'A title'\n \n self.assertEqual(title_soup.title, title_tag)\n self.assertEqual(title_soup.title.string, title_tag.string)\n\n def test_soup_titleless(self):\n ''' Test attribute navigation for nonexisting title tag '''\n \n markup = 'asddsa'\n title_soup = BeautifulSoup(markup, \"html.parser\")\n self.assertEqual(title_soup.title, None)\n \n \n def test_soup_children(self):\n ''' The children attribute returns a generator, for iterating over children\n Note that the children attribute returns linebreaks'''\n \n tags = [\"\\n\", self.a_tag_first, \"\\n\", self.a_tag_second, \"\\n\", self.a_tag_third, \"\\n\"]\n\n index = 0\n for c in self.a_nested_soup.p.p.p.p.children:\n self.assertEqual(c, tags[index])\n index += 1 \n\n\n def test_soup_descendants(self):\n ''' The descentants attribute returns the all descentants of a tag, including strings '''\n \n markup = 'bold tag 1bold tag 2'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n a1 = soup.new_tag(\"a\")\n b1 = soup.new_tag(\"b\")\n b1.string = \"bold tag 1\"\n\n b2 = soup.new_tag(\"b\")\n b2.string = \"bold tag 2\"\n\n a1.append(b1)\n a1.append(b2)\n\n desc = [a1, b1, b1.string, b2, b2.string]\n\n index = 0\n for c in soup.descendants:\n self.assertEqual(c, desc[index])\n index += 1\n\n def test_soup_stripped_strings(self):\n ''' Test stripped_strings, which should remove whitespaces and linebreaks before and after strings '''\n \n markup = '''\n String0 \n String1 String2\n '''\n \n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = [\"String0\", \"String1\", \"String2\"]\n\n soup_strings = []\n for string in soup.stripped_strings:\n soup_strings.append(string)\n\n self.assertEqual(strings, soup_strings)\n\n with self.assertRaises(IndexError):\n strings[3]\n\n def test_soup_stripped_strings_empty(self):\n ''' Test stripping an soup with just whitespace'''\n\n markup = ''' \n '''\n soup = BeautifulSoup(markup, \"html.parser\")\n\n strings = []\n for string in soup.stripped_strings:\n strings.append(string)\n\n self.assertEqual(strings, [])\n\n def test_parent(self):\n '''Parent attribute finds the direct parent. This applies to strings as well.\n The parent of a soup is None'''\n\n markup = 'bold tag 1bold tag 2'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n self.assertEqual(soup.a.b.parent, soup.a)\n self.assertEqual(soup.a.parent, soup)\n self.assertEqual(soup.parent, None)\n\n self.assertEqual(soup.a.b.string.parent, soup.a.b)\n\n def test_parents(self):\n '''The parents attribute finds all parents of a given tag'''\n\n markup = 'bold tag 1bold tag 2'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n parents = [soup.a.b, soup.a, soup]\n\n ##Small irragularity here, parents does not go as high as None, although\n ##the documentation states that it should.\n\n index = 0\n for c in soup.a.b.string.parents:\n self.assertEqual(c, parents[index])\n index += 1\n \n def test_find(self):\n '''Tests finding tags with a given name '''\n\n self.assertEqual(self.a_simple_soup.find(\"a\"), self.a_tag)\n self.assertEqual(self.a_simple_soup.p.find(\"a\"), self.a_tag)\n self.assertEqual(self.a_nested_soup.find(\"a\"), self.a_tag_first)\n\n def test_find_empty(self):\n ''' Test finding a tag with empty string name '''\n\n self.assertEqual(self.a_nested_soup.find(\"\"), None) #finds html tag\n #self.assertEqual(self.a_nested_soup.find(\"\"), self.a_nested_soup) #this fails also\n\n def test_find_fail(self):\n '''Test not finding a tag '''\n\n self.assertEqual(self.a_nested_soup.find(\"b\"), None)\n\n def test_find_all(self):\n '''Find all tags, returns a list'''\n\n result = [self.a_tag_first,self.a_tag_second,self.a_tag_third]\n self.assertEqual(self.a_nested_soup.find_all(\"a\"), result)\n\n def test_find_all_not_found(self):\n '''Search for non-existing tags'''\n\n self.assertEqual(self.a_nested_soup.find_all(\"b\"), []) \n self.assertEqual(self.a_nested_soup.find_all(\"\"), []) #finds nothing\n\n def test_css_select(self):\n '''Find tags based on CSS selectors, returns a list'''\n\n self.assertEqual(self.css_select_soup.select(\".my_CSS_class\"), [self.p_tag_css])\n self.assertEqual(self.css_select_soup.select(\"a#my_link\"), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('a[id=\"my_link\"]'), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('#my_link'), [self.a_tag_id])\n self.assertEqual(self.css_select_soup.select('a[id~=\"my_link\"]'), [self.a_tag_id])\n\n def test_css_select_empty(self):\n ''' Test the select function with an empty string '''\n self.assertEqual(self.css_select_soup.select(\"\"), None) \n #Crashes with IndexError\n\n def test_find_next(self):\n '''Use find_next to find the next anchor tag, until there are no more'''\n\n self.assertEqual(self.a_nested_soup.a, self.a_tag_first)\n self.assertEqual(self.a_nested_soup.a.find_next(), self.a_tag_second)\n self.assertEqual(self.a_nested_soup.a.find_next().find_next(), self.a_tag_third)\n self.assertEqual(self.a_nested_soup.a.find_next().find_next().find_next(), None)\n\n def test_find_all_next(self):\n '''Find all following tags using two different usages of find_all_next'''\n\n self.next_tags = [self.a_tag_second, self.a_tag_third]\n self.first_link = self.a_nested_soup.a\n \n self.assertEqual(self.first_link.find_all_next(), self.next_tags)\n self.assertEqual(self.first_link.find_all_next(\"a\"), self.next_tags)\n self.assertEqual(self.first_link.find_all_next(\"b\"), [])\n \n def test_find_previous(self):\n '''Finds the previous tag of a given name '''\n\n self.assertEqual(self.a_simple_soup.a.find_previous(\"html\"), self.a_simple_soup.html)\n\n def test_find_all_previous(self):\n '''Finds all the previous tags of a given name '''\n\n result = [self.a_nested_soup.p.p.p.p, self.a_nested_soup.p.p.p ,self.a_nested_soup.p.p, self.a_nested_soup.p]\n self.assertEqual(self.a_nested_soup.a.find_all_previous(\"p\"), result)\n\n '''find previous which is not parent '''\n self.assertEqual(self.a_nested_soup.a.find_all_previous(\"head\"), [self.a_nested_soup.head])\n\n def test_find_parent(self):\n ''' Finds the parent of a given name'''\n\n self.assertEqual(self.a_nested_soup.a.find_parent(\"p\"), self.a_nested_soup.p.p.p.p)\n self.assertEqual(self.a_nested_soup.p.p.p.p.find_parent(\"p\"), self.a_nested_soup.p.p.p)\n\n\n \n def test_find_parents(self):\n '''Finds all the parents with a given name '''\n \n p_lvl1 = self.a_nested_soup.p\n p_lvl2 = self.a_nested_soup.p.p\n p_lvl3 = self.a_nested_soup.p.p.p\n p_lvl4 = self.a_nested_soup.p.p.p.p\n\n self.assertEqual(self.a_nested_soup.a.find_parents(\"p\"), [p_lvl4, p_lvl3, p_lvl2, p_lvl1])\n self.assertEqual(self.a_nested_soup.p.find_parents(\"body\"), [self.a_nested_soup.body])\n\n \n\n def test_append(self):\n ''' Test the append function by appending an Bar tag'''\n \n soup = BeautifulSoup(\"Foo\", \"html.parser\")\n tag = soup.new_tag(\"b\")\n tag.string = \"Bar\"\n\n soup.a.append(tag)\n\n self.assertEqual(soup.a.b, tag)\n self.assertEqual(\"FooBar\", str(soup.a)) \n \n ''' Test the append function by appending empty string '''\n \n soup_2 = BeautifulSoup(\"Foo\", \"html.parser\")\n soup_2_app = BeautifulSoup(\"Foo\", \"html.parser\")\n soup_2.append(\"\")\n self.assertEqual(soup_2.contents, soup_2_app.contents + [\"\"])\n\n\n def test_append_raise(self):\n ''' Assert that append without argument raises a TypeError due to too few arguments '''\n \n append_raise_soup = BeautifulSoup(\"Foo\", \"html.parser\")\n with self.assertRaises(TypeError):\n append_raise_soup.a.append()\n\n def test_insert_before(self):\n ''' Insert_before() test with a Don't tag inserted before string '''\n \n soup = BeautifulSoup(\"Don'tstop\", \"html.parser\")\n b_soup = BeautifulSoup(\"stop\", \"html.parser\")\n \n tag = soup.new_tag(\"i\")\n tag.string = \"Don't\"\n \n b_soup.b.string.insert_before(tag)\n \n self.assertEqual(soup, b_soup)\n\n ''' Insert_before test with string argument before tag. '''\n soup_2 = BeautifulSoup(\"tester soup\", \"html.parser\")\n b_soup_2 = BeautifulSoup(\"Footester soup\", \"html.parser\")\n \n soup_2.b.insert_before(\"Foo\")\n self.assertEqual(soup_2, b_soup_2)\n\n def test_insert_before_raise(self):\n ''' Insert_before() without argument test.'''\n \n soup = BeautifulSoup(\"testing soup\", \"html.parser\")\n with self.assertRaises(TypeError):\n soup.insert_before()\n\n def test_insert_after(self):\n ''' Insert_after() test with an stop tag after string '''\n \n soup = BeautifulSoup(\"Don't \", \"html.parser\")\n soup_r = BeautifulSoup(\"Don't stop\", \"html.parser\")\n \n tag = soup.new_tag(\"i\")\n tag.string = \"stop\"\n \n soup.b.string.insert_after(tag)\n \n self.assertEqual(soup, soup_r)\n\n ''' Insert_after() test with an string argument after tag. '''\n soup_2 = BeautifulSoup(\"Don't\", \"html.parser\")\n soup_2_r = BeautifulSoup(\"Don'tTestThis\", \"html.parser\")\n soup_2.b.insert_after(\"TestThis\")\n \n self.assertEqual(soup_2, soup_2_r)\n\n \n \n def test_insert_after_raise(self): \n ''' Insert_after () test with no argument, to raise exception. '''\n\n soup = BeautifulSoup(\"Don't \", \"html.parser\")\n with self.assertRaises(TypeError):\n soup.insert_after()\n\n def test_clear(self):\n ''' Clear the contents of a HTML tag. '''\n \n markup = 'I linked to example.com'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear()\n \n cleared_markup = ''\n cleared_soup = BeautifulSoup(cleared_markup, \"html.parser\")\n\n self.assertEqual(soup, cleared_soup)\n\n def test_clear_empty(self):\n ''' Clear the contents of an empty HTML tag. '''\n \n markup = ''\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear()\n \n self.assertEqual(soup, soup_2)\n\n def test_clear_with_arg(self):\n ''' Call clear with argument, works just as clear(). '''\n \n markup = ''\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n soup.a.clear(\"argument\")\n \n self.assertEqual(soup, soup_2)\n\n def test_extract(self):\n ''' Extract a tag and see if it is correctly returned, and that the original is changed accordingly '''\n \n markup = 'I linked to example.com'\n extracted_markup = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n extracted_soup = BeautifulSoup(extracted_markup, \"html.parser\")\n\n tag = soup.new_tag(\"i\")\n tag.string = \"example.com\"\n \n extracted_tag = soup.i.extract()\n \n self.assertEqual(extracted_tag.parent, None)\n self.assertEqual(extracted_tag, tag)\n self.assertEqual(soup, extracted_soup)\n\n def test_extract_raises(self):\n ''' Test extracting a non-existing tag, ensuring that the original isn't changed. '''\n \n markup = 'I linked to example.com'\n extr_soup = BeautifulSoup(markup, \"html.parser\")\n extr_null_soup = extr_soup.extract()\n \n self.assertEqual(extr_soup, extr_null_soup)\n\n def test_extract_with_arg(self):\n ''' Test extracting by calling extract() with a random argument. '''\n \n markup = 'I linked to example.com'\n extr_arg_soup = BeautifulSoup(markup, \"html.parser\")\n with self.assertRaises(TypeError):\n extr_arg_soup_extracted = extr_arg_soup.extract(\"arg\")\n\n def test_decompose(self):\n ''' Test the decompose function by removing and destroying a tag. '''\n \n markup = 'I linked to example.com'\n markup_decomposed = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n dec_soup = BeautifulSoup(markup_decomposed, \"html.parser\")\n\n soup.i.decompose()\n \n self.assertEqual(soup, dec_soup)\n\n def test_decompose_empty(self):\n ''' Test the decompose function by removing an empty tag. '''\n \n markup = 'I linked to '\n markup_decomposed = 'I linked to '\n \n soup = BeautifulSoup(markup, \"html.parser\")\n dec_soup = BeautifulSoup(markup_decomposed, \"html.parser\")\n\n soup.i.decompose()\n \n self.assertEqual(soup, dec_soup)\n\n def test_decmpose_arg(self):\n ''' Test the decompose function by calling decompose with arg. '''\n \n markup = 'I linked to test '\n markup_decomposed = 'I linked to '\n dec_soup = BeautifulSoup(markup, \"html.parser\")\n \n with self.assertRaises(TypeError):\n dec_soup.i.decompose(\"test_arg\")\n\n def test_replace_with(self):\n ''' Test the replace with function '''\n \n markup = 'I linked to example.com'\n rep_markup = 'I linked to new_example.com'\n \n soup = BeautifulSoup(markup, \"html.parser\")\n rep_soup = BeautifulSoup(rep_markup, \"html.parser\")\n \n new_tag = soup.new_tag(\"b\")\n new_tag.string = \"new_example.com\"\n\n soup.a.i.replace_with(new_tag)\n \n self.assertEqual(soup, rep_soup)\n\n def test_replace_tag_with_string(self):\n ''' Test replacing tag with string '''\n \n markup = 'I linked to example.com'\n rep_markup = 'I linked to testText'\n \n soup = BeautifulSoup(markup, \"html.parser\")\n rep_soup = BeautifulSoup(rep_markup, \"html.parser\")\n\n soup.i.replace_with(\"testText\")\n \n self.assertEqual(soup, rep_soup)\n self.assertEqual(str(soup), str(rep_soup))\n\n #soup.a.contents <--- this gives a list containing 2 elements, one for each string.\n\n def test_replace_with_no_tag(self):\n ''' Test replace_with() called without argument. '''\n \n markup = 'example.com'\n no_soup = BeautifulSoup(markup, \"html.parser\")\n a_tag = no_soup.a\n \n with self.assertRaises(AttributeError):\n a_tag.i.replace_with()\n\n def test_wrap(self):\n ''' Test wrap() by wrapping a b tag around an a tag '''\n\n markup = 'Text to be wrapped'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n wr_markup = 'Text to be wrapped'\n wr_soup = BeautifulSoup(wr_markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n\n soup.a.wrap(tag)\n\n self.assertEqual(soup, wr_soup)\n\n def test_wrap_with_string(self):\n ''' Test wrap() by wrapping a b tag around an a tag, where b contains a string'''\n\n markup = 'Text to be wrapped'\n\n soup = BeautifulSoup(markup, \"html.parser\")\n\n wr_markup = 'stringText to be wrapped'\n wr_soup = BeautifulSoup(wr_markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n tag.string = \"string\"\n\n soup.a.wrap(tag)\n\n self.assertEqual(soup, wr_soup) \n\n def test_unwrap(self):\n ''' Test unwrapping and compare to soup after unwrapping.'''\n \n markup = 'I linked to example.com'\n soup = BeautifulSoup(markup, \"html.parser\")\n\n unwrapped_markup = 'I linked to example.com'\n unwrapped_soup = BeautifulSoup(unwrapped_markup, \"html.parser\")\n \n soup.a.i.unwrap()\n \n #The soups are not equal, but as strings they are equal\n self.assertEqual(str(soup), str(unwrapped_soup))\n self.assertEqual(soup, unwrapped_soup)\n\n #soup.a.string <-- This is None at this point\n #soup.a.contents <--- this gives a list containing 2 elements, one for each string.\n\n def test_unwrap_with_arg(self):\n ''' Test unwrap() with arg. '''\n \n markup = 'I linked to example.com'\n unwrap_soup = BeautifulSoup(markup, \"html.parser\")\n a_tag = unwrap_soup.a\n \n with self.assertRaises(TypeError):\n a_tag.i.unwrap(\"a\")\n\n \n def test_unwrap_no_tag(self):\n ''' Test unwrap() on non-exisiting tag. '''\n \n markup = 'htadsasdtp/example.codssdd'\n unwrap_soup = BeautifulSoup(markup, \"html.parser\")\n \n with self.assertRaises(ValueError):\n unwrap_soup.unwrap()\n \n\n def test_wrap_unwrap(self):\n ''' Test wrapping and then unwrapping '''\n\n markup = 'Text to be wrapped'\n soup = BeautifulSoup(markup, \"html.parser\")\n soup_2 = BeautifulSoup(markup, \"html.parser\")\n\n tag = soup.new_tag(\"b\")\n\n soup.a.wrap(tag)\n soup.b.unwrap()\n\n self.assertEqual(soup, soup_2)\n\n def test_no_name_tag(self):\n ''' test returning a name of a tag with no name'''\n\n self.assertEqual(self.no_name_tag.name, \"\")\n\n \n\nif __name__ == '__main__':\n unittest.main()\n\n", "sub_path": "source/unittest_tests.py", "file_name": "unittest_tests.py", "file_ext": "py", "file_size_in_byte": 22882, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "unittest.TestCase", "line_number": 17, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 23, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 32, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 45, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 66, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 132, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 139, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 146, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 163, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 176, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 188, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 196, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 208, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 228, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 255, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 273, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 286, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 298, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 410, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 421, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 422, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 430, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 437, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 438, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 448, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 449, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 457, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 464, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 465, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 475, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 476, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 486, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 494, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 499, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 507, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 508, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 518, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 519, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 531, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 532, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 547, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 556, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 566, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 567, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 579, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 580, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 591, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 602, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 603, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 618, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 619, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 632, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 642, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 645, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 658, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 661, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 674, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 677, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 692, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 703, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 713, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 714, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 731, "usage_type": "call"}]}
+{"seq_id": "57162057", "text": "import unittest\nfrom code.world import World\nfrom main import read_world_data, read_images\nimport pygame\nimport code\nfrom code.fighter import Fighter\nfrom code.terrain_objects import Item, TerrainObject\n\n# Get necessary things for the test\n\nhealth_box_img = pygame.image.load('static/img/icons/health_box.png').convert_alpha()\nitem_boxes = {\n 'Health': health_box_img\n}\nlevel = 1\nimg_list = read_images()\nworld_data = read_world_data(level)\nworld = code.world.World()\n\n\nclass TestWorld(unittest.TestCase):\n \"\"\"\n Tests whether in world.py certain objects (e.g., player) are an instance of a certain class (e.g., Fighter)\n \"\"\"\n\n def test_process_data(self):\n \"\"\"\n Test whether in world.py certain objects (e.g., player) are an instance of a certain class (e.g., Fighter)\n \"\"\"\n player, enemy_group, decoration_group, water_group, item_box_group, exit_group = \\\n world.process_data(world_data, img_list, item_boxes)\n # check whether player is an instance of the Fighter class\n self.assertIsInstance(player, Fighter)\n # test whether all enemies are an instance of Fighter class\n self.assertTrue(all([isinstance(enemy, Fighter) for enemy in enemy_group.sprites()]))\n # test whether all decoration is an instance of Decoration class\n self.assertTrue(all([isinstance(decoration, TerrainObject) for decoration in decoration_group.sprites()]))\n # test whether all water is an instance of Water class\n self.assertTrue(all([isinstance(water, TerrainObject) for water in water_group.sprites()]))\n # test whether all item boxes are an instance of Item class\n self.assertTrue(all([isinstance(item_box, Item) for item_box in item_box_group.sprites()]))\n # test whether all exits are an instance of Exit class\n self.assertTrue(all([isinstance(exit, TerrainObject) for exit in exit_group.sprites()]))\n\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "test_package/test_world.py", "file_name": "test_world.py", "file_ext": "py", "file_size_in_byte": 1970, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pygame.image.load", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 11, "usage_type": "attribute"}, {"api_name": "main.read_images", "line_number": 16, "usage_type": "call"}, {"api_name": "main.read_world_data", "line_number": 17, "usage_type": "call"}, {"api_name": "code.world.World", "line_number": 18, "usage_type": "call"}, {"api_name": "code.world", "line_number": 18, "usage_type": "attribute"}, {"api_name": "unittest.TestCase", "line_number": 21, "usage_type": "attribute"}, {"api_name": "code.fighter.Fighter", "line_number": 33, "usage_type": "argument"}, {"api_name": "code.fighter.Fighter", "line_number": 35, "usage_type": "argument"}, {"api_name": "code.terrain_objects.TerrainObject", "line_number": 37, "usage_type": "argument"}, {"api_name": "code.terrain_objects.TerrainObject", "line_number": 39, "usage_type": "argument"}, {"api_name": "code.terrain_objects.Item", "line_number": 41, "usage_type": "argument"}, {"api_name": "code.terrain_objects.TerrainObject", "line_number": 43, "usage_type": "argument"}, {"api_name": "unittest.main", "line_number": 47, "usage_type": "call"}]}
+{"seq_id": "81441915", "text": "import os\nimport sys\nimport json\nimport numpy as np\nimport time\nimport torch\nimport utils\nimport glob\nimport random\nimport logging\nimport argparse\nimport torch.nn as nn\nimport genotypes\nimport torch.utils\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\nimport copy\nfrom torch.autograd import Variable\nfrom model import NetworkImageNet as Network\n\n\nparser = argparse.ArgumentParser(\"training imagenet\")\nparser.add_argument('--mode', type=str, default='eval', help='location of the data corpus')\nparser.add_argument('--data', type=str, default='/public/data1/datasets/imagenet2012', help='location of the data corpus')\nparser.add_argument('--workers', type=int, default=16, help='number of workers to load dataset')\nparser.add_argument('--batch_size', type=int, default=256, help='batch size')\nparser.add_argument('--learning_rate', type=float, default=0.1, help='init learning rate')\nparser.add_argument('--momentum', type=float, default=0.9, help='momentum')\nparser.add_argument('--weight_decay', type=float, default=3e-5, help='weight decay')\nparser.add_argument('--report_freq', type=float, default=100, help='report frequency')\nparser.add_argument('--epochs', type=int, default=250, help='num of training epochs')\nparser.add_argument('--init_channels', type=int, default=48, help='num of init channels')\nparser.add_argument('--layers', type=int, default=14, help='total number of layers')\nparser.add_argument('--auxiliary', action='store_true', default=False, help='use auxiliary tower')\nparser.add_argument('--auxiliary_weight', type=float, default=0.4, help='weight for auxiliary loss')\nparser.add_argument('--drop_path_prob', type=float, default=0, help='drop path probability')\nparser.add_argument('--save', type=str, default='/tmp/checkpoints/', help='experiment name')\nparser.add_argument('--seed', type=int, default=0, help='random seed')\nparser.add_argument('--arch', type=str, default=None, help='which architecture to use')\nparser.add_argument('--grad_clip', type=float, default=5., help='gradient clipping')\nparser.add_argument('--label_smooth', type=float, default=0.1, help='label smoothing')\nparser.add_argument('--lr_scheduler', type=str, default='linear', help='lr scheduler, linear or cosine')\nparser.add_argument('--tmp_data_dir', type=str, default='/tmp/cache/', help='temp data dir')\nparser.add_argument('--note', type=str, default='try', help='note for this run')\n\n\nparser.add_argument('--base_path', type=str, default='EXP', help='which architecture to use')\nparser.add_argument('--genotype_name', type=str, default=None, help='which architecture to use')\nparser.add_argument('--from_scratch', action='store_true', default=False, help='path to ckpt file for re-trained weight')\nparser.add_argument('--load_file', type=str, default=None, help='path to ckpt file for re-trained weight')\n\n\nargs, unparsed = parser.parse_known_args()\n\n#args.save = '{}eval-{}-{}'.format(args.save, args.note, time.strftime(\"%Y%m%d-%H%M%S\"))\n#utils.create_exp_dir(args.save, scripts_to_save=glob.glob('*.py'))\n\nlog_format = '%(asctime)s %(message)s'\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format=log_format, datefmt='%m/%d %I:%M:%S %p')\n#fh = logging.FileHandler(os.path.join(args.save, 'log.txt'))\n#fh.setFormatter(logging.Formatter(log_format))\n#logging.getLogger().addHandler(fh)\n\nCLASSES = 1000\n\nclass CrossEntropyLabelSmooth(nn.Module):\n\n def __init__(self, num_classes, epsilon):\n super(CrossEntropyLabelSmooth, self).__init__()\n self.num_classes = num_classes\n self.epsilon = epsilon\n self.logsoftmax = nn.LogSoftmax(dim=1)\n\n def forward(self, inputs, targets):\n log_probs = self.logsoftmax(inputs)\n targets = torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1)\n targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes\n loss = (-targets * log_probs).mean(0).sum()\n return loss\n\ndef get_genotype(genotype_path, name):\n genotype_file = os.path.join(genotype_path, '%s.txt'%name)\n tmp_dict = json.load(open(genotype_file,'r'))\n genotype = genotypes.Genotype(**tmp_dict)\n return genotype\n\ndef main():\n if not torch.cuda.is_available():\n logging.info('No GPU device available')\n sys.exit(1)\n np.random.seed(args.seed)\n cudnn.benchmark = True\n torch.manual_seed(args.seed)\n cudnn.enabled=True\n torch.cuda.manual_seed(args.seed)\n logging.info(\"args = %s\", args)\n logging.info(\"unparsed_args = %s\", unparsed)\n num_gpus = torch.cuda.device_count() \n\n if not os.path.exists(args.base_path):\n os.makedirs(args.base_path)\n ckpt_dir = os.path.join(args.base_path, \"ImageNet\")\n if not os.path.exists(ckpt_dir):\n os.makedirs(ckpt_dir)\n\n # ckpt_dir_1 = os.path.join(args.base_path, \"ImageNet-1\")\n # if not os.path.exists(ckpt_dir):\n # os.makedirs(ckpt_dir_1)\n\n\n # print(arhs.arch)\n if args.arch is not None:\n genotype = eval(\"genotypes.%s\" % args.arch)\n elif args.base_path is not None and args.genotype_name is not None:\n genotype_path = os.path.join(args.base_path, 'results_of_7q/genotype')\n genotype = get_genotype(genotype_path, args.genotype_name)\n else:\n raise(ValueError(\"the parser input arch, genotype_path, genotype_name should not be all None\"))\n# print(genotype)\n\n# genotype = eval(\"genotypes.%s\" % args.arch)\n print('---------Genotype---------')\n logging.info(genotype)\n print('--------------------------') \n model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)\n if num_gpus > 1:\n model = nn.DataParallel(model)\n model = model.cuda()\n else:\n model = model.cuda()\n logging.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n\n criterion = nn.CrossEntropyLoss()\n criterion = criterion.cuda()\n criterion_smooth = CrossEntropyLabelSmooth(CLASSES, args.label_smooth)\n criterion_smooth = criterion_smooth.cuda()\n\n optimizer = torch.optim.SGD(\n model.parameters(),\n args.learning_rate,\n momentum=args.momentum,\n weight_decay=args.weight_decay\n )\n# data_dir = os.path.join(args.tmp_data_dir, 'imagenet')\n# traindir = os.path.join(data_dir, 'train')\n# validdir = os.path.join(data_dir, 'val')\n traindir = os.path.join(args.data, 'ILSVRC2012_img_train')\n validdir = os.path.join(args.data, 'ILSVRC2012_img_val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n valid_data = dset.ImageFolder(\n validdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]))\n train_data = dset.ImageFolder(\n traindir,\n transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ColorJitter(\n brightness=0.4,\n contrast=0.4,\n saturation=0.4,\n hue=0.2),\n transforms.ToTensor(),\n normalize,\n ]))\n\n train_queue = torch.utils.data.DataLoader(\n train_data, batch_size=args.batch_size, shuffle=True, pin_memory=True, num_workers=args.workers)\n\n valid_queue = torch.utils.data.DataLoader(\n valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=args.workers)\n\n best_acc_top1 = 0\n best_acc_top5 = 0\n\n ckpt_file = None\n start_epoch = 0\n if not args.from_scratch:\n # check wheter have pre-trained models\n if args.load_file is not None and os.path.exists(args.load_file):\n ckpt_file = args.load_file\n else:\n # deal with negative names\n files = os.listdir(ckpt_dir)\n for f in files:\n tmp = f.split('.')\n if len(tmp) > 2: continue\n tmp = int(tmp[0].split('_')[1])\n if tmp > start_epoch: \n start_epoch = tmp\n ckpt_file = os.path.join(ckpt_dir, f)\n if ckpt_file is not None:\n logging.info('====== Load ckpt ======')\n logging.info(\"Loading from %s\"%ckpt_file)\n\n \n start_epoch = 249\n \n\n # if num_gpus > 1:\n # model.module.load_state_dict(checkpoint['state_dict'])\n # else:\n # model.load_state_dict(checkpoint['state_dict'])\n # start_epoch = int(checkpoint['epoch']) + 1\n # optimizer.load_state_dict(checkpoint['optimizer'])\n # best_acc_top1 = float(checkpoint['best_acc_top1'])\n # logging.info(\"Training Start at %d\"%start_epoch)\n logging.info(\"Training Start at %d\"%start_epoch)\n sat= torch.load(ckpt_file)\n # print(type(sat))\n # if num_gpus > 1:\n # model.load_state_dict(sat)\n # else:\n # model = model.cuda()\n # new_stat={}\n # for k,v in sat.items():\n # # \"module.stem0.0.weight\"\n # new_k = k#[7:]\n # new_stat[new_k] =copy.deepcopy(v)\n \n model.load_state_dict(sat)\n\n\n# scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.decay_period, gamma=args.gamma, last_epoch=start_epoch)\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, float(args.epochs))\n \n for epoch in range(start_epoch, args.epochs):\n if args.lr_scheduler == 'cosine':\n scheduler.step()\n current_lr = scheduler.get_lr()[0]\n elif args.lr_scheduler == 'linear':\n current_lr = adjust_lr(optimizer, epoch)\n else:\n print('Wrong lr type, exit')\n sys.exit(1)\n logging.info('Epoch: %d lr %e', epoch, current_lr)\n if epoch < 5 and args.batch_size > 256:\n for param_group in optimizer.param_groups:\n param_group['lr'] = current_lr * (epoch + 1) / 5.0\n logging.info('Warming-up Epoch: %d, LR: %e', epoch, current_lr * (epoch + 1) / 5.0)\n if num_gpus > 1:\n model.module.drop_path_prob = args.drop_path_prob * epoch / args.epochs\n else:\n model.drop_path_prob = args.drop_path_prob * epoch / args.epochs\n epoch_start = time.time()\n train_acc, train_obj = train(train_queue, model, criterion_smooth, optimizer)\n logging.info('Train_acc: %f', train_acc)\n\n valid_acc_top1, valid_acc_top5, valid_obj = infer(valid_queue, model, criterion)\n logging.info('Valid_acc_top1: %f', valid_acc_top1)\n logging.info('Valid_acc_top5: %f', valid_acc_top5)\n epoch_duration = time.time() - epoch_start\n logging.info('Epoch time: %ds.', epoch_duration)\n # save current epoch model, and remove previous model\n try:\n last_model = os.path.join(ckpt_dir, 'weights_%d.pt'%(epoch-1))\n os.remove(last_model)\n except:\n pass\n ckpt = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'best_acc_top1': best_acc_top1,\n 'optimizer' : optimizer.state_dict(),\n }\n utils.save(model, os.path.join(ckpt_dir, 'weights_%d.pt'%(epoch)))\n\n if valid_acc_top1 > best_acc_top1:\n try:\n last_model = os.path.join(ckpt_dir, 'weights_%.3f.pt'%(best_acc_top1))\n os.remove(last_model)\n except:\n pass\n ckpt = {\n 'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'best_acc_top1': best_acc_top1,\n 'optimizer' : optimizer.state_dict(),\n }\n utils.save(model, os.path.join(ckpt_dir, 'weights_%.3f.pt'%(valid_acc_top1)))\n best_acc_top1 = valid_acc_top1\n best_acc_top5 = valid_acc_top5\n\n# is_best = False\n# if valid_acc_top5 > best_acc_top5:\n# best_acc_top5 = valid_acc_top5\n# if valid_acc_top1 > best_acc_top1:\n# best_acc_top1 = valid_acc_top1\n# is_best = True\n# utils.save_checkpoint({\n# 'epoch': epoch + 1,\n# 'state_dict': model.state_dict(),\n# 'best_acc_top1': best_acc_top1,\n# 'optimizer' : optimizer.state_dict(),\n# }, is_best, args.save) \n print(\"the best acc: %f(Top1); %f(Top5)\"%(best_acc_top1, best_acc_top5))\n \ndef adjust_lr(optimizer, epoch):\n # Smaller slope for the last 5 epochs because lr * 1/250 is relatively large\n if args.epochs - epoch > 5:\n lr = args.learning_rate * (args.epochs - 5 - epoch) / (args.epochs - 5)\n else:\n lr = args.learning_rate * (args.epochs - epoch) / ((args.epochs - 5) * 5)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr \n\ndef train(train_queue, model, criterion, optimizer):\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n batch_time = utils.AvgrageMeter()\n model.train()\n\n for step, (input, target) in enumerate(train_queue):\n target = target.cuda(non_blocking=True)\n input = input.cuda(non_blocking=True)\n b_start = time.time()\n optimizer.zero_grad()\n logits, logits_aux = model(input)\n loss = criterion(logits, target)\n if args.auxiliary:\n loss_aux = criterion(logits_aux, target)\n loss += args.auxiliary_weight*loss_aux\n\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)\n optimizer.step()\n batch_time.update(time.time() - b_start)\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n objs.update(loss.data.item(), n)\n top1.update(prec1.data.item(), n)\n top5.update(prec5.data.item(), n)\n\n if step % args.report_freq == 0:\n end_time = time.time()\n if step == 0:\n duration = 0\n start_time = time.time()\n else:\n duration = end_time - start_time\n start_time = time.time()\n logging.info('TRAIN Step: %03d Objs: %e R1: %f R5: %f Duration: %ds BTime: %.3fs', \n step, objs.avg, top1.avg, top5.avg, duration, batch_time.avg)\n # break\n return top1.avg, objs.avg\n\n\ndef infer(valid_queue, model, criterion):\n objs = utils.AvgrageMeter()\n top1 = utils.AvgrageMeter()\n top5 = utils.AvgrageMeter()\n model.eval()\n\n for step, (input, target) in enumerate(valid_queue):\n input = input.cuda()\n target = target.cuda(non_blocking=True)\n with torch.no_grad():\n logits, _ = model(input)\n loss = criterion(logits, target)\n\n prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))\n n = input.size(0)\n objs.update(loss.data.item(), n)\n top1.update(prec1.data.item(), n)\n top5.update(prec5.data.item(), n)\n\n if step % args.report_freq == 0:\n end_time = time.time()\n if step == 0:\n duration = 0\n start_time = time.time()\n else:\n duration = end_time - start_time\n start_time = time.time()\n logging.info('VALID Step: %03d Objs: %e R1: %f R5: %f Duration: %ds', step, objs.avg, top1.avg, top5.avg, duration)\n # break\n return top1.avg, top5.avg, objs.avg\n\n\ndef eval_arch(genotype_file, ckpt_path):\n if not torch.cuda.is_available():\n logging.info('no gpu device available')\n sys.exit(1)\n\n np.random.seed(args.seed)\n cudnn.benchmark = True\n torch.manual_seed(args.seed)\n cudnn.enabled=True\n torch.cuda.manual_seed(args.seed)\n logging.info(\"args = %s\", args)\n\n# tmp_dict = json.load(open(genotype_file,'r'))\n if args.arch is not None:\n genotype = eval(\"genotypes.%s\" % args.arch)\n# genotype = genotypes.Genotype(**tmp_dict)\n\n print(genotype)\n model = Network(args.init_channels, CLASSES, args.layers, args.auxiliary, genotype)\n model.drop_path_prob = 0.\n num_gpus = torch.cuda.device_count() \n if num_gpus > 1:\n model = nn.DataParallel(model).cuda()\n else:\n model = model.cuda()\n logging.info(\"param size = %fMB\", utils.count_parameters_in_MB(model))\n model.load_state_dict(torch.load(ckpt_path), strict=False)\n\n criterion = nn.CrossEntropyLoss()\n criterion = criterion.cuda()\n criterion_smooth = CrossEntropyLabelSmooth(CLASSES, args.label_smooth)\n criterion_smooth = criterion_smooth.cuda()\n\n validdir = os.path.join(args.data, 'ILSVRC2012_img_val')\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n valid_data = dset.ImageFolder(\n validdir,\n transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ]))\n valid_queue = torch.utils.data.DataLoader(\n valid_data, batch_size=args.batch_size, shuffle=False, pin_memory=True, num_workers=4)\n\n valid_acc_top1, valid_acc_top5, valid_obj = infer(valid_queue, model, criterion)\n logging.info('valid_acc_top1 %f', valid_acc_top1)\n logging.info('valid_acc_top5 %f', valid_acc_top5)\n\n\nif __name__ == '__main__':\n if args.mode == 'train':\n main()\n elif args.mode == 'eval':\n if args.arch is not None:\n genotype = eval(\"genotypes.%s\" % args.arch)\n else:\n base_dir = args.base_path\n genotype_path = os.path.join(base_dir, 'results_of_7q/genotype')\n genotype_names = [args.genotype_name]\n genotype_file = os.path.join(genotype_path, '%s.txt'%(genotype_names[0]))\n ckpt_path = args.load_file\n\n eval_arch('', ckpt_path)\n else:\n raise(ValueError(\"Not Implement mode for %s\"%args.mode))\n\n", "sub_path": "cnn/train_imagenet.py", "file_name": "train_imagenet.py", "file_ext": "py", "file_size_in_byte": 17753, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 23, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 60, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 60, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 60, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 68, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.LogSoftmax", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 74, "usage_type": "name"}, {"api_name": "torch.zeros_like", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 84, "usage_type": "call"}, {"api_name": "os.path", "line_number": 84, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 85, "usage_type": "call"}, {"api_name": "genotypes.Genotype", "line_number": 86, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 90, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 91, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 93, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 94, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.manual_seed", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.backends.cudnn.enabled", "line_number": 96, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.cuda.manual_seed", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 97, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 98, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.cuda.device_count", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 100, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 103, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 106, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 117, "usage_type": "call"}, {"api_name": "os.path", "line_number": 117, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 125, "usage_type": "call"}, {"api_name": "model.NetworkImageNet", "line_number": 127, "usage_type": "call"}, {"api_name": "torch.nn.DataParallel", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 129, "usage_type": "name"}, {"api_name": "model.cuda", "line_number": 130, "usage_type": "call"}, {"api_name": "model.cuda", "line_number": 132, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 133, "usage_type": "call"}, {"api_name": "utils.count_parameters_in_MB", "line_number": 133, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 135, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 135, "usage_type": "name"}, {"api_name": "torch.optim.SGD", "line_number": 140, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 140, "usage_type": "attribute"}, {"api_name": "model.parameters", "line_number": 141, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 149, "usage_type": "call"}, {"api_name": "os.path", "line_number": 149, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 151, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 151, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 152, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 152, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 154, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 154, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 155, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 155, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 156, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 156, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 157, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 157, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 160, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 160, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 162, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 162, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomResizedCrop", "line_number": 163, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 163, "usage_type": "name"}, {"api_name": "torchvision.transforms.RandomHorizontalFlip", "line_number": 164, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 164, "usage_type": "name"}, {"api_name": "torchvision.transforms.ColorJitter", "line_number": 165, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 165, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 170, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 170, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 174, "usage_type": "attribute"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 177, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 177, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 191, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 198, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 200, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 201, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 215, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 216, "usage_type": "call"}, {"api_name": "model.load_state_dict", "line_number": 228, "usage_type": "call"}, {"api_name": "torch.optim.lr_scheduler.CosineAnnealingLR", "line_number": 232, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 232, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 242, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 243, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 247, "usage_type": "call"}, {"api_name": "model.module", "line_number": 249, "usage_type": "attribute"}, {"api_name": "model.drop_path_prob", "line_number": 251, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 252, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 254, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 257, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 258, "usage_type": "call"}, {"api_name": "time.time", "line_number": 259, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 260, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 263, "usage_type": "call"}, {"api_name": "os.path", "line_number": 263, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 264, "usage_type": "call"}, {"api_name": "model.state_dict", "line_number": 269, "usage_type": "call"}, {"api_name": "utils.save", "line_number": 273, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 273, "usage_type": "call"}, {"api_name": "os.path", "line_number": 273, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 277, "usage_type": "call"}, {"api_name": "os.path", "line_number": 277, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 278, "usage_type": "call"}, {"api_name": "model.state_dict", "line_number": 283, "usage_type": "call"}, {"api_name": "utils.save", "line_number": 287, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 287, "usage_type": "call"}, {"api_name": "os.path", "line_number": 287, "usage_type": "attribute"}, {"api_name": "utils.AvgrageMeter", "line_number": 316, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 317, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 318, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 319, "usage_type": "call"}, {"api_name": "model.train", "line_number": 320, "usage_type": "call"}, {"api_name": "time.time", "line_number": 325, "usage_type": "call"}, {"api_name": "torch.nn.utils.clip_grad_norm_", "line_number": 334, "usage_type": "call"}, {"api_name": "torch.nn.utils", "line_number": 334, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 334, "usage_type": "name"}, {"api_name": "model.parameters", "line_number": 334, "usage_type": "call"}, {"api_name": "time.time", "line_number": 336, "usage_type": "call"}, {"api_name": "utils.accuracy", "line_number": 337, "usage_type": "call"}, {"api_name": "time.time", "line_number": 344, "usage_type": "call"}, {"api_name": "time.time", "line_number": 347, "usage_type": "call"}, {"api_name": "time.time", "line_number": 350, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 351, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 358, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 359, "usage_type": "call"}, {"api_name": "utils.AvgrageMeter", "line_number": 360, "usage_type": "call"}, {"api_name": "model.eval", "line_number": 361, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 366, "usage_type": "call"}, {"api_name": "utils.accuracy", "line_number": 370, "usage_type": "call"}, {"api_name": "time.time", "line_number": 377, "usage_type": "call"}, {"api_name": "time.time", "line_number": 380, "usage_type": "call"}, {"api_name": "time.time", "line_number": 383, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 384, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 390, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 390, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 391, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 392, "usage_type": "call"}, {"api_name": "numpy.random.seed", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 394, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn.benchmark", "line_number": 395, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 395, "usage_type": "name"}, {"api_name": "torch.manual_seed", "line_number": 396, "usage_type": "call"}, {"api_name": "torch.backends.cudnn.enabled", "line_number": 397, "usage_type": "attribute"}, {"api_name": "torch.backends.cudnn", "line_number": 397, "usage_type": "name"}, {"api_name": "torch.cuda.manual_seed", "line_number": 398, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 398, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 399, "usage_type": "call"}, {"api_name": "model.NetworkImageNet", "line_number": 407, "usage_type": "call"}, {"api_name": "model.drop_path_prob", "line_number": 408, "usage_type": "attribute"}, {"api_name": "torch.cuda.device_count", "line_number": 409, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 409, "usage_type": "attribute"}, {"api_name": "torch.nn.DataParallel", "line_number": 411, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 411, "usage_type": "name"}, {"api_name": "model.cuda", "line_number": 413, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 414, "usage_type": "call"}, {"api_name": "utils.count_parameters_in_MB", "line_number": 414, "usage_type": "call"}, {"api_name": "model.load_state_dict", "line_number": 415, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 415, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 417, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 417, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 422, "usage_type": "call"}, {"api_name": "os.path", "line_number": 422, "usage_type": "attribute"}, {"api_name": "torchvision.transforms.Normalize", "line_number": 423, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 423, "usage_type": "name"}, {"api_name": "torchvision.datasets.ImageFolder", "line_number": 424, "usage_type": "call"}, {"api_name": "torchvision.datasets", "line_number": 424, "usage_type": "name"}, {"api_name": "torchvision.transforms.Compose", "line_number": 426, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 426, "usage_type": "name"}, {"api_name": "torchvision.transforms.Resize", "line_number": 427, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 427, "usage_type": "name"}, {"api_name": "torchvision.transforms.CenterCrop", "line_number": 428, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 428, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 429, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 429, "usage_type": "name"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 432, "usage_type": "call"}, {"api_name": "torch.utils", "line_number": 432, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 436, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 437, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 448, "usage_type": "call"}, {"api_name": "os.path", "line_number": 448, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 450, "usage_type": "call"}, {"api_name": "os.path", "line_number": 450, "usage_type": "attribute"}]}
+{"seq_id": "367410182", "text": "#\n# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.\n#\n\nimport os\nfrom subprocess import Popen, PIPE\nimport psutil\n\nfrom sandesh.nodeinfo.cpuinfo.ttypes import SysMemInfo, SysCpuInfo, CpuLoadAvg\n\n\ndef _run_cmd(cmd):\n proc = Popen(cmd, shell=True, stdout=PIPE, close_fds=True)\n return int(proc.communicate()[0])\n\n\nclass LinuxSysMemCpuUsageData(object):\n def __init__(self, last_cpu, last_time):\n self.last_cpu = last_cpu\n self.last_time = last_time\n\n def get_num_socket(self):\n return _run_cmd('lscpu | grep \"Socket(s):\" '\n '| awk \\'{print $2}\\'')\n\n def get_num_cpu(self):\n return _run_cmd('lscpu | grep \"^CPU(s):\" '\n '| awk \\'{print $2}\\'')\n\n def get_num_core_per_socket(self):\n return _run_cmd('lscpu | grep \"Core(s) per socket:\" '\n '| awk \\'{print $4}\\'')\n\n def get_num_thread_per_core(self):\n return _run_cmd('lscpu | grep \"Thread(s) per core:\" '\n '| awk \\'{print $4}\\'')\n\n def get_sys_mem_info(self, node_type):\n virtmem_info = psutil.virtual_memory()\n sys_mem_info = SysMemInfo()\n sys_mem_info.total = virtmem_info.total / 1024\n sys_mem_info.used = virtmem_info.used / 1024\n sys_mem_info.free = virtmem_info.free / 1024\n sys_mem_info.buffers = virtmem_info.buffers / 1024\n sys_mem_info.cached = virtmem_info.cached / 1024\n sys_mem_info.node_type = node_type\n return sys_mem_info\n\n def get_sys_cpu_info(self, node_type):\n cpu_load_avg = self._get_sys_cpu_load_avg()\n sys_cpu_info = SysCpuInfo()\n sys_cpu_info.one_min_avg = cpu_load_avg.one_min_avg\n sys_cpu_info.five_min_avg = cpu_load_avg.five_min_avg\n sys_cpu_info.fifteen_min_avg = cpu_load_avg.fifteen_min_avg\n sys_cpu_info.cpu_share = self._get_sys_cpu_share()\n sys_cpu_info.node_type = node_type\n return sys_cpu_info\n\n def _get_sys_cpu_load_avg(self):\n load_avg = os.getloadavg()\n cpu_load_avg = CpuLoadAvg()\n cpu_load_avg.one_min_avg = load_avg[0]\n cpu_load_avg.five_min_avg = load_avg[1]\n cpu_load_avg.fifteen_min_avg = load_avg[2]\n return cpu_load_avg\n\n def _get_sys_cpu_share(self):\n last_cpu = self.last_cpu\n last_time = self.last_time\n\n current_cpu = psutil.cpu_times()\n current_time = 0.00\n for i in range(0, len(current_cpu) - 1):\n current_time += current_cpu[i]\n\n # tracking system/user time only\n interval_time = 0\n if last_cpu and (last_time != 0):\n sys_time = current_cpu.system - last_cpu.system\n usr_time = current_cpu.user - last_cpu.user\n interval_time = current_time - last_time\n\n self.last_cpu = current_cpu\n self.last_time = current_time\n\n if interval_time == 0:\n return 0\n\n sys_percent = 100 * sys_time / interval_time\n usr_percent = 100 * usr_time / interval_time\n cpu_share = round((sys_percent + usr_percent) / self.get_num_cpu(), 2)\n return cpu_share\n", "sub_path": "src/nodemgr/common/linux_sys_mem_cpu.py", "file_name": "linux_sys_mem_cpu.py", "file_ext": "py", "file_size_in_byte": 3137, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "subprocess.Popen", "line_number": 13, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 13, "usage_type": "name"}, {"api_name": "psutil.virtual_memory", "line_number": 39, "usage_type": "call"}, {"api_name": "sandesh.nodeinfo.cpuinfo.ttypes.SysMemInfo", "line_number": 40, "usage_type": "call"}, {"api_name": "sandesh.nodeinfo.cpuinfo.ttypes.SysCpuInfo", "line_number": 51, "usage_type": "call"}, {"api_name": "os.getloadavg", "line_number": 60, "usage_type": "call"}, {"api_name": "sandesh.nodeinfo.cpuinfo.ttypes.CpuLoadAvg", "line_number": 61, "usage_type": "call"}, {"api_name": "psutil.cpu_times", "line_number": 71, "usage_type": "call"}]}
+{"seq_id": "619422734", "text": "from flask import Flask, jsonify, send_from_directory, request, Blueprint\nimport datetime\nimport stormberry.util\nfrom stormberry.util import weather_list_to_dict_list\nfrom stormberry.server.util import get_repository\nimport json\n\nweather_blueprint = Blueprint('weather_blueprint', __name__)\n\n@weather_blueprint.route('/latest-reading')\ndef latest_reading():\n repo = get_repository()\n latest = repo.get_latest()\n return jsonify(latest.dict)\n\n@weather_blueprint.route('/since/')\ndef weather_since(start_date):\n repo = get_repository()\n\n readings = repo.get_between(start_date)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/since//until/')\ndef weather_between(start_date, end_date):\n repo = get_repository()\n\n readings = repo.get_between(start_date, end_date)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-hour')\ndef weather_past_hour():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(hours=1)\n\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-day')\ndef weather_past_day():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(days=1)\n\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n@weather_blueprint.route('/past-week')\ndef weather_past_week():\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(days=7)\n repo = get_repository()\n datestr = ago.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n readings = repo.get_between(datestr)\n return jsonify(weather_list_to_dict_list(readings))\n\n", "sub_path": "src/stormberry/server/api/weather/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 1854, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "flask.Blueprint", "line_number": 8, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 14, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 18, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 21, "usage_type": "call"}, {"api_name": "stormberry.util.weather_list_to_dict_list", "line_number": 21, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 28, "usage_type": "call"}, {"api_name": "stormberry.util.weather_list_to_dict_list", "line_number": 28, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 32, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 32, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 33, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 35, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 38, "usage_type": "call"}, {"api_name": "stormberry.util.weather_list_to_dict_list", "line_number": 38, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 42, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 43, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 45, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 48, "usage_type": "call"}, {"api_name": "stormberry.util.weather_list_to_dict_list", "line_number": 48, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 52, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 53, "usage_type": "call"}, {"api_name": "stormberry.server.util.get_repository", "line_number": 54, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 58, "usage_type": "call"}, {"api_name": "stormberry.util.weather_list_to_dict_list", "line_number": 58, "usage_type": "call"}]}
+{"seq_id": "409709433", "text": "# Create your views here.\r\nfrom .Neural import *\r\nfrom .Robot import Track\r\nfrom .Robot import Truck\r\nfrom .Robot import Manipulator\r\nfrom api.models import Status\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework.response import Response\r\n\r\n\r\n\r\nclass Robot(APIView):\r\n a = ''\r\n\r\n\r\n def get(self, request):\r\n # main loop\r\n while True:\r\n status = str(Status.objects.all()).split()[2][0]\r\n success, img = cap.read()\r\n\r\n blob = cv2.dnn.blobFromImage(img,1/255,(whT,whT),[0,0,0],1,crop=False) # ? to blob conv\r\n net.setInput(blob)\r\n\r\n layerNames = net.getLayerNames()\r\n outputNames = [layerNames[i[0]-1] for i in net.getUnconnectedOutLayers()]\r\n\r\n outputs = net.forward(outputNames)\r\n Neural.findObjects(outputs, img) # Используем нейронку\r\n if not Manipulator.busy: # Если манипулятор\r\n # свободен\r\n Track.findBottle(Neural.n_ame) # Ищем бутылку\r\n if Track.bottlefound and Truck.IsTurnedToTheTarget() and Neural.BottleRange > 35: # Если бутыла\r\n # найдена, тележка направлена на нёё и расстояние между тележкой и обьектом >35 см\r\n Truck.Move(Neural.BottleRange) # Двигаемся к обьекту\r\n if Neural.n_ame == 'BOTTLE' and Neural.BottleRange < 35: # Если расстояние\r\n # меньше 35 см, берем предмет\r\n Manipulator.Lock()\r\n Manipulator.busy = True\r\n if Manipulator.busy: # Если манипулятор занят\r\n Track.findHuman(Neural.n_ame) # Поиск человека\r\n if Manipulator.busy and Track.humanfound and Truck.IsTurnedToTheTarget():\r\n Truck.Move(Neural.HumanRange)\r\n if Neural.n_ame == 'PERSON' and Neural.BottleRange < 35 and Wannamore.dontwant:\r\n Manipulator.Unlock()\r\n Manipulator.busy = False\r\n while True:\r\n print('Робот доставил обьект. Хотите продолжить? (yes или no)')\r\n a = input('Введите ответ: ')\r\n if a == 'yes' or a == 'YES' or a == 'Yes' or a == 'y' or a == 'Y':\r\n status = '1'\r\n Wannamore.dontwant = False\r\n break\r\n elif a == 'no' or a == 'NO' or a == 'No' or a == 'n':\r\n status = '0'\r\n break\r\n else:\r\n print('Некорректный ввод')\r\n #print(str(Status.objects.all()).split()[2][0])\r\n if status == '0':\r\n break\r\n cv2.imshow('Image', img)\r\n if cv2.waitKey(25) & 0xFF == ord('q'):\r\n break\r\n return Response({\"good\"})", "sub_path": "robot/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 3081, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "rest_framework.views.APIView", "line_number": 12, "usage_type": "name"}, {"api_name": "api.models.Status.objects.all", "line_number": 19, "usage_type": "call"}, {"api_name": "api.models.Status.objects", "line_number": 19, "usage_type": "attribute"}, {"api_name": "api.models.Status", "line_number": 19, "usage_type": "name"}, {"api_name": "Neural.findObjects", "line_number": 29, "usage_type": "call"}, {"api_name": "Robot.Manipulator.busy", "line_number": 30, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator", "line_number": 30, "usage_type": "name"}, {"api_name": "Robot.Track.findBottle", "line_number": 32, "usage_type": "call"}, {"api_name": "Robot.Track", "line_number": 32, "usage_type": "name"}, {"api_name": "Neural.n_ame", "line_number": 32, "usage_type": "attribute"}, {"api_name": "Robot.Track.bottlefound", "line_number": 33, "usage_type": "attribute"}, {"api_name": "Robot.Track", "line_number": 33, "usage_type": "name"}, {"api_name": "Robot.Truck.IsTurnedToTheTarget", "line_number": 33, "usage_type": "call"}, {"api_name": "Robot.Truck", "line_number": 33, "usage_type": "name"}, {"api_name": "Neural.BottleRange", "line_number": 33, "usage_type": "attribute"}, {"api_name": "Robot.Truck.Move", "line_number": 35, "usage_type": "call"}, {"api_name": "Robot.Truck", "line_number": 35, "usage_type": "name"}, {"api_name": "Neural.BottleRange", "line_number": 35, "usage_type": "attribute"}, {"api_name": "Neural.n_ame", "line_number": 36, "usage_type": "attribute"}, {"api_name": "Neural.BottleRange", "line_number": 36, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator.Lock", "line_number": 38, "usage_type": "call"}, {"api_name": "Robot.Manipulator", "line_number": 38, "usage_type": "name"}, {"api_name": "Robot.Manipulator.busy", "line_number": 39, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator", "line_number": 39, "usage_type": "name"}, {"api_name": "Robot.Manipulator.busy", "line_number": 40, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator", "line_number": 40, "usage_type": "name"}, {"api_name": "Robot.Track.findHuman", "line_number": 41, "usage_type": "call"}, {"api_name": "Robot.Track", "line_number": 41, "usage_type": "name"}, {"api_name": "Neural.n_ame", "line_number": 41, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator.busy", "line_number": 42, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator", "line_number": 42, "usage_type": "name"}, {"api_name": "Robot.Track.humanfound", "line_number": 42, "usage_type": "attribute"}, {"api_name": "Robot.Track", "line_number": 42, "usage_type": "name"}, {"api_name": "Robot.Truck.IsTurnedToTheTarget", "line_number": 42, "usage_type": "call"}, {"api_name": "Robot.Truck", "line_number": 42, "usage_type": "name"}, {"api_name": "Robot.Truck.Move", "line_number": 43, "usage_type": "call"}, {"api_name": "Robot.Truck", "line_number": 43, "usage_type": "name"}, {"api_name": "Neural.HumanRange", "line_number": 43, "usage_type": "attribute"}, {"api_name": "Neural.n_ame", "line_number": 44, "usage_type": "attribute"}, {"api_name": "Neural.BottleRange", "line_number": 44, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator.Unlock", "line_number": 45, "usage_type": "call"}, {"api_name": "Robot.Manipulator", "line_number": 45, "usage_type": "name"}, {"api_name": "Robot.Manipulator.busy", "line_number": 46, "usage_type": "attribute"}, {"api_name": "Robot.Manipulator", "line_number": 46, "usage_type": "name"}, {"api_name": "rest_framework.response.Response", "line_number": 65, "usage_type": "call"}]}
+{"seq_id": "460499442", "text": "import gpandas as gpd\nimport datetime\nimport os\n\n\ntry:\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\nexcept:\n pass\n\n\nfecha = datetime.datetime.now().strftime(\"%d/%m\")\n\n\ndef main():\n recipients = 'Emilio Bravo Maturana '\n titulo = f'Progreso al {fecha} (aviso automatizado)'\n html = populate_data_on_mail()\n \n send_mail(recipients, titulo, html)\n \n\ndef populate_data_on_mail():\n \n progress = gpd.read_gexcel('1My0exuCahxoaY78Aybw1NQQgA9C4DWFtEt34eQzVO5Q')[['Centro', 'Progress']].groupby(['Centro']).mean().round().astype(int)['Progress']\n progress_percent = (progress.astype(str) + '%').replace('0%','.')\n\n with open('mail_template.txt', 'r') as f:\n template = f.read()\n\n for centro in progress_percent.index:\n template = template.replace(f'#{centro}%#', str(progress_percent[centro]))\n for centro in progress.index:\n template = template.replace(f'#{centro}#', str(progress[centro]))\n \n return template\n\n\ndef send_mail(recipients, titulo, html):\n\n email = f'''From: Servidor SENDA \nTo: {recipients}\nSubject: {titulo}\nContent-Type: text/html\n\n {html}\n\n'''\n\n with open(\"progress_mail.txt\", \"w\") as text_file:\n text_file.write(email)\n\n os.system('sendmail -t < progress_mail.txt')\n\n \nif __name__ == \"__main__\":\n main()\n\n\n\n\n", "sub_path": "py/mail_progress.py", "file_name": "mail_progress.py", "file_ext": "py", "file_size_in_byte": 1388, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.chdir", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 7, "usage_type": "call"}, {"api_name": "os.path", "line_number": 7, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 12, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 12, "usage_type": "attribute"}, {"api_name": "gpandas.read_gexcel", "line_number": 25, "usage_type": "call"}, {"api_name": "os.system", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "442699013", "text": "import argparse\nimport json\nimport requests\nfrom multiprocessing import Pool\n\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\nimport numpy as np\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--use_thin_client', type=int)\n parser.add_argument('--web_app_port', default='9210')\n parser.add_argument('--serving_uri', required=True)\n parser.add_argument('--model_name', required=True, nargs='+')\n args = parser.parse_args()\n\nstatic_folder = 'thin_static' if args.use_thin_client else 'rich_static'\nprint(static_folder)\napp = Flask(__name__, static_url_path='/static/', static_folder=static_folder)\nCORS(app)\n\n\ndef build_body(b64_img):\n return {\n 'instances': [\n {'image_bytes': {'b64': b64_img}}\n ]\n }\n\n\ndef decode_response(response, encoding_dict):\n prediction = json.loads(response.text)['predictions'][0]\n cls_idx = np.argmax(prediction)\n return encoding_dict[cls_idx]\n\n\ndef call_serving(args):\n b64_img, uri, encoding_dict = args\n body = build_body(b64_img)\n response = requests.post(uri, json=body)\n return decode_response(response, encoding_dict)\n\n\n@app.route('/init-client', methods=['GET'])\ndef init_client():\n global serving_uris, encoding_dicts\n return jsonify({'servingUris': serving_uris, 'encodingDicts': encoding_dicts})\n\n\n@app.route('/predict', methods=['POST'])\ndef get_prediction():\n global serving_uris, encoding_dicts\n b64_img = request.get_json()\n predictions = Pool(2).imap(call_serving, zip([b64_img] * len(serving_uris), serving_uris, encoding_dicts))\n return jsonify(' '.join(predictions))\n\n\n\n@app.route('/')\ndef main_page():\n return app.send_static_file('index.html')\n\n\nif __name__ == '__main__':\n serving_uris = []\n encoding_dicts = []\n\n for model_name in args.model_name:\n serving_uri = args.serving_uri.format(model_name=model_name)\n serving_uris.append(serving_uri)\n\n with open(f'/tmp/{model_name}.json', 'r') as f:\n encoding_dicts.append(json.load(f))\n\n args = parser.parse_args()\n app.run(host='0.0.0.0', port=args.web_app_port)\n", "sub_path": "visual_attribution/web_app/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 2157, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 12, "usage_type": "call"}, {"api_name": "flask.Flask", "line_number": 21, "usage_type": "call"}, {"api_name": "flask_cors.CORS", "line_number": 22, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 35, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 49, "usage_type": "call"}, {"api_name": "flask.request.get_json", "line_number": 55, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 55, "usage_type": "name"}, {"api_name": "multiprocessing.Pool", "line_number": 56, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 57, "usage_type": "call"}, {"api_name": "json.load", "line_number": 75, "usage_type": "call"}]}
+{"seq_id": "150258406", "text": "import datetime\n\ndef last_dow_noon(dow, d):\n hours_ahead = d.hour - 12\n if hours_ahead < 0:\n hours_ahead += 24\n last_noon = d - datetime.timedelta(hours=hours_ahead, minutes=d.minute, seconds=d.second, microseconds=d.microsecond)\n days_ahead = last_noon.weekday() - dow\n if days_ahead < 0:\n days_ahead += 7\n return last_noon - datetime.timedelta(days=days_ahead)\n", "sub_path": "twitter_models/helpers.py", "file_name": "helpers.py", "file_ext": "py", "file_size_in_byte": 375, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "datetime.timedelta", "line_number": 7, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "531993569", "text": "\"\"\"\n\nCreated by: Nathan Starkweather\nCreated on: 02/11/2016\nCreated in: PyCharm Community Edition\n\n\n\"\"\"\nimport goffice.client\n\n__author__ = 'Nathan Starkweather'\n\nimport logging\nimport os\n\nimport lxml.etree\n\nlogger = logging.getLogger(__name__)\ninfo = logger.info\ndebug = logger.debug\nwarn = logger.warn\nfatal = logger.fatal\nlog = logger.log\n\n\n# Util #\n\n\ndef _local_curdir():\n return os.path.abspath(os.path.dirname(__file__))\n\n\ndef _join_local_curdir(*paths):\n return os.path.join(_local_curdir(), *paths)\n\n\ndef load_keypath(key_file):\n rv = _join_local_curdir(\"data\", \".auth\", key_file)\n debug(\"returning key path: %s\", rv)\n return rv\n\n\ndef _load_default_keypath():\n return load_keypath(\"_exp_auth_key_store.json\")\n\n\ndef open_client():\n from goffice.client import GClient, authorize_client, authorize_credentials\n from oauth2client.file import Storage\n\n keypath = _load_default_keypath()\n s = Storage(keypath)\n try:\n cr = s.locked_get()\n except Exception:\n cr = None\n if cr is None:\n cr = authorize_credentials(keypath.replace(\"_store\", ''))\n s.locked_put(cr)\n\n return GClient(cr)\n\n\n# noinspection PyUnresolvedReferences\ndef test():\n from goffice.client import GClient\n import goffice\n g = goffice.authorize_client(load_keypath(\"_exp_auth_key_encr.json\"), \"081089\")\n # import gspread\n #\n # c = gspread.Client(GClient(\"081089\").session.auth)\n # c.login()\n # print(c.get_spreadsheets_feed())\n content = g.get_workbooks()\n print(content)\n import tempfile\n import io\n tree = lxml.etree.parse(io.BytesIO(content))\n\n with tempfile.NamedTemporaryFile(\"wb\", delete=False) as f:\n tree.submit(f, pretty_print=True)\n import subprocess\n subprocess.Popen(\"notepad.exe %s\" % f.name)\n import time\n time.sleep(.5)\n os.remove(f.name)\n\nif __name__ == '__main__':\n test()\n", "sub_path": "db_stuff/google_loader.py", "file_name": "google_loader.py", "file_ext": "py", "file_size_in_byte": 1892, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "oauth2client.file.Storage", "line_number": 52, "usage_type": "call"}, {"api_name": "goffice.client.authorize_credentials", "line_number": 58, "usage_type": "call"}, {"api_name": "goffice.client.GClient", "line_number": 61, "usage_type": "call"}, {"api_name": "goffice.authorize_client", "line_number": 68, "usage_type": "call"}, {"api_name": "lxml.etree.etree.parse", "line_number": 78, "usage_type": "call"}, {"api_name": "lxml.etree.etree", "line_number": 78, "usage_type": "attribute"}, {"api_name": "lxml.etree", "line_number": 78, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 78, "usage_type": "call"}, {"api_name": "tempfile.NamedTemporaryFile", "line_number": 80, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 83, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 85, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 86, "usage_type": "call"}]}
+{"seq_id": "439909917", "text": "from pathlib import Path\n\nfrom mlblocks import MLPipeline, add_pipelines_path, add_primitives_path\nfrom mlblocks import load_pipeline as _load_pipeline\n\nadd_primitives_path(Path(__file__).parents[2].joinpath('blocks', 'primitives'))\nadd_pipelines_path(Path(__file__).parents[2].joinpath('blocks', 'pipelines'))\n\n\nPIPELINES = [\n 'ballet_rf_regressor',\n 'ballet_elasticnet',\n 'train_mean',\n 'leaderboard_mean',\n]\nDEFAULT_PIPELINE = 'ballet_rf_regressor'\n\n\ndef load_pipeline(name: str = DEFAULT_PIPELINE) -> MLPipeline:\n if name not in PIPELINES:\n raise ValueError(f'Pipeline {name!r} is not supported')\n return MLPipeline(_load_pipeline(name))\n", "sub_path": "src/fragile_families/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 667, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "mlblocks.add_primitives_path", "line_number": 6, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 6, "usage_type": "call"}, {"api_name": "mlblocks.add_pipelines_path", "line_number": 7, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 7, "usage_type": "call"}, {"api_name": "mlblocks.MLPipeline", "line_number": 22, "usage_type": "call"}, {"api_name": "mlblocks.load_pipeline", "line_number": 22, "usage_type": "call"}, {"api_name": "mlblocks.MLPipeline", "line_number": 19, "usage_type": "name"}]}
+{"seq_id": "231524381", "text": "#import matplotlib.pyplot as plt\n'''\n\t@ In this python code, the following are executed:\n\t@ Load the entire original images of evaluation dataset to a listdir\n\t@ Preprocess the original images to 224x224x3 RGB images\n\t@ Save new images to .hkl format files correspondingly\n\n'''\nimport numpy as np\nimport scipy.io\nimport cv2\nimport os\nimport hickle as hkl\n\n# Load the data\n\ndata_dir= '/nas/lhoang/data/evaluation/'# Path to original images\nsaved_dir='/nas/lhoang/data/hkl_file/' # Path to saved hkl files\nfn = os.listdir(data_dir) # load file names into a list\n\nfns = [data_dir+ name for name in fn]# concatenate the directory path with the file names\n\t\t\t\t\t\t\t\t\t # (i.e. /homes/lhoang/.../IMG0001.JPEG)\nnumpy = True\n\nfor i in range(len(fns)):\n\tif i%2000==0:\n\t\tprint('%d/%d' % (i,len(fns))) # Print out (2000/500000)\n\tname = fn[i].replace('.JPEG','')+'.hkl' # Remove the .JPEG extension and concatenate with .hkl extension\n\t\t\t\t\t\t\t\t\t\t\t# (i.e., IMG0001.JPEG -> IMG0001.hkl)\n\tname = saved_dir+name \t\t\t\t # Concatenate the saved directory with the hkl file\n\timg = cv2.imread(fns[i])\n\t#print img.shape\n\theight, width, channels = img.shape # Take the size of height, width and channles of an image\n\tnew_height = int((height*256)/min(img.shape[:2])) # Resize the image to 256x256\n\tnew_width = int((width*256)/min(img.shape[:2])) # Method is CUBIC\n\timg_new = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC).astype(np.float32)\n\t#cropping\n\theight, width, channels = img_new.shape\n\tstart_height = int((height-224)/2)\n\tstart_width = int((width-224)/2)\n\timg = img_new[start_height:start_height+224,start_width:start_width+224]\n\timg[:,:,0] -= 103.939\n\timg[:,:,1] -= 116.779\n\timg[:,:,2] -= 123.68\n\timg\t\t\t= img.transpose((2,0,1))\n\t# new image has the shape of (224,224,3)\n\timg = np.expand_dims(img, axis =0) # now the shape of the image is (1,224,224,3)\n\t#img = np.swapaxes(img, 1,2)\n\t#img = np.swapaxes(img, 1,3) # swap the axes to new shape (1,3,224,224)\n\t\t\t\t\t\t\t\t# This is neccesary to leverage the existing code in\n\t\t\t\t\t\t\t\t# Ares simulator. We will take other approaches if needed\n\thkl.dump(img, name, mode = 'w' ) # Save the new image to a .hkl name\n\n\n\n\t# array_image_data = np.expand_dims(array_image_data,axis=0)\n\t# print (\"shape after the expansion:\",array_image_data.shape)\n\t# array_image_data = preprocess_input(array_image_data)\n\t# print (\"Final shape:\",array_image_data.shape)\n", "sub_path": "image_preprocess_2.py", "file_name": "image_preprocess_2.py", "file_ext": "py", "file_size_in_byte": 2406, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.listdir", "line_number": 19, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 31, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.INTER_CUBIC", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 36, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 47, "usage_type": "call"}, {"api_name": "hickle.dump", "line_number": 52, "usage_type": "call"}]}
+{"seq_id": "528100031", "text": "from flask import Flask, render_template, request, flash, redirect, url_for, jsonify\nfrom sqlalchemy import Column, String, Integer, Sequence, Date, ForeignKey, between, and_\nfrom wtforms import Form, TextField, validators, StringField, SubmitField, IntegerField\nimport time\nimport flask_sqlalchemy\nimport flask_restless\nimport flask_bootstrap\nfrom datetime import datetime, timedelta\nimport requests\nimport json\n\napp = Flask(__name__)\n\nflask_bootstrap.Bootstrap(app)\n\napp.config.from_pyfile('config.py')\n\ndb = flask_sqlalchemy.SQLAlchemy(app)\n\nmanager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)\n\ndateRegex = \"^(([0-9])|([0-2][0-9])|([3][0-1]))\\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\-\\d{2}$\"\n\nclass AlchemyEncoder(json.JSONEncoder):\n\n def default(self, obj):\n if isinstance(obj.__class__, DeclarativeMeta):\n fields = {}\n for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:\n data = obj.__getattribute__(field)\n try:\n json.dumps(data)\n fields[field] = data\n except TypeError:\n fields[field] = None\n return fields\n\n return json.JSONEncoder.default(self, obj)\n\n\n\nclass SurveyRequestForm(Form):\n development = TextField(\"Development Name: \", validators=[validators.required()])\n client = TextField(\"Client Name: \", validators=[validators.required()])\n location = TextField(\"Location Name: \", validators=[validators.required()])\n sRange = TextField(\"Range: \", validators=[validators.required(), validators.length(min=2, max=2, message=\"Min and max length 2\")])\n section = IntegerField(\"Section: \", validators=[validators.required(message=\"Must be integer value\"), validators.number_range(min=1, max=100000, message=\"Must be integer between 1 and 100000\")])\n township = TextField(\"Township: \", validators=[validators.required()])\n requestedBy = TextField(\"Requested By: \", validators=[validators.required()])\n\ndef _getDate():\n return datetime.now().date()\n\n#fields need to be all lowercase and same name as db\nclass SurveyRequest(db.Model):\n __tablename__ = 'surveyrequest'\n jobno = db.Column(Integer, Sequence('job_id_seq'), primary_key=True)\n development = db.Column(String)\n client = db.Column(String)\n contractdate = db.Column(Date, default=_getDate)\n location = db.Column(String)\n range = db.Column(String)\n section = db.Column(Integer)\n township = db.Column(String)\n daterequested = db.Column(Date, default=_getDate)\n requestedby = db.Column(String)\n completiondate = db.Column(Date, nullable=True)\n istwosetsdrawings = db.Column(String, nullable=True)\n restakecount = db.Column(Integer)\n\nclass Task(db.Model):\n __tablename__ = 'task'\n taskno = db.Column(Integer, Sequence('task_id_seq'), primary_key=True)\n description = db.Column(String)\n\nclass FieldBook(db.Model):\n __tablename__ = 'fieldbook'\n fieldbookno = db.Column(Integer, Sequence('fieldbook_id_seq'), primary_key=True)\n bookpath = db.Column(String)\n\nclass Crew(db.Model):\n __tablename__ = 'crew'\n crewno = db.Column(Integer, Sequence('crew_id_seq'), primary_key=True)\n\nclass Employee(db.Model):\n __tablename__ = 'employee'\n employeeno = db.Column(Integer, Sequence('employee_id_seq'), primary_key=True)\n firstname = db.Column(String)\n lastname = db.Column(String)\n crewno = db.Column(Integer, ForeignKey('crew.crewno'))\n\nclass Assigned(db.Model):\n __tablename__ = 'assigned'\n assignno = db.Column(Integer, Sequence('assigned_id_seq'), primary_key=True)\n crewno = db.Column(Integer, ForeignKey('crew.crewno'))\n taskno = db.Column(Integer, ForeignKey('task.taskno'))\n workdate = db.Column(Date)\n notes = db.Column(String)\n\nclass SurveyPlan(db.Model):\n __tablename__ = 'surveyplan'\n planno = db.Column(Integer, Sequence('plan_id_seq'), primary_key=True)\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n taskno = db.Column(Integer, ForeignKey('task.taskno'))\n notes = db.Column(String)\n\nclass Schedule(db.Model):\n __tablename__ = 'schedule'\n scheduleno = db.Column(Integer, Sequence('schedule_id_seq'), primary_key=True)\n planno = db.Column(Integer, ForeignKey('surveyplan.planno'))\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n assignno = db.Column(Integer, ForeignKey('assigned.assignno'))\n employeeno = db.Column(Integer, ForeignKey('employee.employeeno'))\n scheduledate = db.Column(Date)\n\nclass SurveyReport(db.Model):\n __tablename__ = 'surveyreport'\n reportno = db.Column(Integer, Sequence('report_id_seq'), primary_key=True)\n jobno = db.Column(Integer, ForeignKey('surveyrequest.jobno'))\n scheduleno = db.Column(Integer, ForeignKey('schedule.scheduleno'))\n iscompleted = db.Column(String)\n fieldbookno = db.Column(Integer, ForeignKey('fieldbook.fieldbookno'))\n beginningpageno = db.Column(Integer)\n employeeno = db.Column(Integer, ForeignKey('employee.employeeno'))\n\n@app.route('/home')\ndef home():\n return render_template('index.html')\n\n@app.route('/requestsurvey', methods=['GET', 'POST'])\ndef requestSurvey():\n form = SurveyRequestForm(request.form)\n\n if request.method == 'POST':\n\n if form.validate():\n\n data = {'development': request.form['development'],\n 'client': request.form['client'],\n 'location': request.form['location'],\n 'range': request.form['sRange'],\n 'section': request.form['section'],\n 'township': request.form['township'],\n 'requestedby': request.form['requestedBy'],\n 'restakecount': 0\n }\n response = requests.post('http://localhost:5000/api/surveyrequest', json=data)\n if response.status_code == requests.codes.created:\n time.sleep(3)\n\n return redirect(url_for('home'))\n return render_template('requestSurvey.html', form=form)\n\n@app.route('/plansurvey', methods=['GET', 'POST'])\ndef planSurvey():\n jobs = SurveyRequest.query.filter_by(completiondate=None)\n tasks = Task.query.all()\n if request.method == 'POST':\n data = request.get_json()\n jobno = data['jobno']\n for task in data['tasks']:\n plan = SurveyPlan(jobno=jobno, taskno=task['taskno'], notes=task['tasknotes'])\n db.session.add(plan)\n db.session.commit()\n\n return render_template('planSurvey.html', jobs=jobs, tasks=tasks)\n\n@app.route('/schedulesurvey', methods=['GET', 'POST'])\ndef scheduleSurvey():\n #surveyplans that have not been scheduled\n plans = db.session.query(SurveyPlan).join(Schedule, Schedule.planno == SurveyPlan.planno, isouter=True)\n #jobs in each plan\n jobs = []\n for plan in plans:\n jobs.append(SurveyRequest.query.get(plan.jobno))\n\n crews = Crew.query.all()\n\n if request.method == 'POST':\n assign = Assigned(crewno=request.form['crewno'],\n workdate=request.form['workdate'],\n notes=request.form['crewnotes']\n )\n db.session.add(assign)\n db.session.flush()\n assignno = assign.assignno\n db.session.commit()\n date = _getDate()\n schedule = Schedule(\n planno=request.form['planno'],\n jobno=request.form['jobno'],\n assignno=assignno,\n employeeno=request.form['employeeno'],\n scheduledate= date\n )\n db.session.add(schedule)\n db.session.commit()\n return render_template('scheduleSurvey.html', jobs=jobs, plans=plans, crews=crews)\n\n@app.route('/getjobsurveyplan', methods=['GET'])\ndef getjobSurveyPlan():\n jobno = request.args.get('jobno')\n unscheduled_plans = db.session.query(SurveyPlan).join(Schedule, Schedule.planno == SurveyPlan.planno, isouter=True)\n plans = None\n for plan in unscheduled_plans:\n plans = SurveyPlan.query.filter_by(jobno=jobno)\n\n json_plans = []\n for plan in plans:\n json_plans.append({\n 'planno': str(plan.planno),\n 'jobno': str(plan.jobno),\n 'taskno': str(plan.taskno),\n 'notes': str(plan.notes)\n })\n\n return jsonify(json_plans)\n\n@app.route('/fieldworkreport', methods=['GET', 'POST'])\ndef fieldworkReport():\n #getting all the jobs that have a schedule but have no fieldwork and those that are incomplete\n scheduleNoFieldWork = db.session.query(Schedule).join(SurveyReport, Schedule.scheduleno == SurveyReport.scheduleno, isouter=True)\n incompleteFieldWork = SurveyReport.query.filter_by(iscompleted='N')\n jobs = []\n for schedule in scheduleNoFieldWork:\n jobs.append(SurveyRequest.query.get(schedule.jobno))\n for work in incompleteFieldWork:\n jobs.append(SurveyRequest.query.get(work.jobno))\n\n if request.method == 'POST':\n pass\n\n\n return render_template('fieldreport.html', jobs=jobs)\n\n@app.route('/weeklyinfo', methods=['GET'])\ndef weeklyinfo():\n\n today = _getDate()\n today = datetime.strftime(today, '%d-%b-%y')\n week_after = datetime.now() + timedelta(days=7)\n week_after = datetime.strftime(week_after, '%d-%b-%y')\n scheduledetails = []\n allinfo = db.session.query(SurveyRequest, Task, SurveyPlan, Assigned, Schedule).filter(\n SurveyRequest.jobno == Schedule.jobno).filter(\n Assigned.assignno == Schedule.assignno).filter(\n Assigned.workdate >= today, Assigned.workdate <= week_after).filter(\n SurveyPlan.jobno == SurveyRequest.jobno).filter(\n Task.taskno == Assigned.taskno).all()\n\n biglistinfo = []\n for x in allinfo:\n for y in x:\n biglistinfo.append(y)\n\n\n schedule = {'jobno': None,\n 'tasks': [],\n 'development': None,\n 'restakecount': None}\n\n for b in biglistinfo:\n if isinstance(b, SurveyRequest):\n if b.jobno != schedule['jobno']:\n schedule['jobno'] = b.jobno\n schedule['development'] = b.development\n schedule['restakecount'] = b.restakecount\n scheduledetails.append(schedule)\n\n for b in biglistinfo:\n if isinstance(b, Task):\n for schedule in scheduledetails:\n if not any(t['taskno'] == b.taskno for t in schedule['tasks']):\n schedule['tasks'].append({'taskno': b.taskno, 'taskdesc': b.description})\n\n for b in biglistinfo:\n if isinstance(b, SurveyPlan):\n for schedule in scheduledetails:\n if any(t['taskno'] == b.taskno for t in schedule['tasks']):\n for t in schedule['tasks']:\n if t['taskno'] == b.taskno:\n if b.notes is None:\n t['notes'] = \"\"\n else:\n t['notes'] = b.notes\n\n for b in biglistinfo:\n if isinstance(b, Assigned):\n for schedule in scheduledetails:\n if any(t['taskno'] == b.taskno for t in schedule['tasks']):\n for t in schedule['tasks']:\n if t['taskno'] == b.taskno:\n t['crewno'] = b.crewno\n if b.notes is None:\n t['assignnotes'] = \"\"\n else:\n t['assignnotes'] = b.notes\n\n return jsonify(scheduledetails)\n\n@app.route('/weeklyschedule', methods=['GET'])\ndef weeklyschedule():\n today = _getDate()\n today = datetime.strftime(today, '%d-%b-%y')\n week_after = datetime.now() + timedelta(days=7)\n week_after = datetime.strftime(week_after, '%d-%b-%y')\n\n\n\n return render_template('weeklySchedule.html', start=today, end=week_after)\n\n\n\n\n\n\n\n\nmanager.create_api(SurveyRequest, methods=['GET', 'POST', 'PATCH', 'DELETE'])\nmanager.create_api(Task, methods=['GET', 'POST', 'PATCH', 'DELETE'])\nmanager.create_api(Assigned, methods=['GET', 'POST'])\nmanager.create_api(Schedule, methods=['GET', 'POST'])\nmanager.create_api(Crew, methods=['GET'])\nmanager.create_api(SurveyPlan, methods=['GET'])\nmanager.create_api(SurveyReport, methods=['GET', 'POST'])\n", "sub_path": "app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 12350, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Flask", "line_number": 12, "usage_type": "call"}, {"api_name": "flask_bootstrap.Bootstrap", "line_number": 14, "usage_type": "call"}, {"api_name": "flask_sqlalchemy.SQLAlchemy", "line_number": 18, "usage_type": "call"}, {"api_name": "flask_restless.APIManager", "line_number": 20, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 24, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 32, "usage_type": "call"}, {"api_name": "json.JSONEncoder.default", "line_number": 38, "usage_type": "call"}, {"api_name": "json.JSONEncoder", "line_number": 38, "usage_type": "attribute"}, {"api_name": "wtforms.Form", "line_number": 42, "usage_type": "name"}, {"api_name": "wtforms.TextField", "line_number": 43, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 43, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 43, "usage_type": "name"}, {"api_name": "wtforms.TextField", "line_number": 44, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 44, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 44, "usage_type": "name"}, {"api_name": "wtforms.TextField", "line_number": 45, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 45, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 45, "usage_type": "name"}, {"api_name": "wtforms.TextField", "line_number": 46, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 46, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 46, "usage_type": "name"}, {"api_name": "wtforms.validators.length", "line_number": 46, "usage_type": "call"}, {"api_name": "wtforms.IntegerField", "line_number": 47, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 47, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 47, "usage_type": "name"}, {"api_name": "wtforms.validators.number_range", "line_number": 47, "usage_type": "call"}, {"api_name": "wtforms.TextField", "line_number": 48, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 48, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 48, "usage_type": "name"}, {"api_name": "wtforms.TextField", "line_number": 49, "usage_type": "call"}, {"api_name": "wtforms.validators.required", "line_number": 49, "usage_type": "call"}, {"api_name": "wtforms.validators", "line_number": 49, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 52, "usage_type": "name"}, {"api_name": "sqlalchemy.Integer", "line_number": 57, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 57, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 58, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 59, "usage_type": "argument"}, {"api_name": "sqlalchemy.Date", "line_number": 60, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 61, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 62, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 63, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 64, "usage_type": "argument"}, {"api_name": "sqlalchemy.Date", "line_number": 65, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 66, "usage_type": "argument"}, {"api_name": "sqlalchemy.Date", "line_number": 67, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 68, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 69, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 73, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 74, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 78, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 78, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 79, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 83, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 83, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 87, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 87, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 88, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 89, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 90, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 90, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 94, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 94, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 95, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 95, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 96, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 96, "usage_type": "call"}, {"api_name": "sqlalchemy.Date", "line_number": 97, "usage_type": "argument"}, {"api_name": "sqlalchemy.String", "line_number": 98, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 102, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 102, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 103, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 103, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 104, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 104, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 105, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 109, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 109, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 110, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 110, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 111, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 111, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 112, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 112, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 113, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 113, "usage_type": "call"}, {"api_name": "sqlalchemy.Date", "line_number": 114, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 118, "usage_type": "argument"}, {"api_name": "sqlalchemy.Sequence", "line_number": 118, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 119, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 119, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 120, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 120, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 121, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 122, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 122, "usage_type": "call"}, {"api_name": "sqlalchemy.Integer", "line_number": 123, "usage_type": "argument"}, {"api_name": "sqlalchemy.Integer", "line_number": 124, "usage_type": "argument"}, {"api_name": "sqlalchemy.ForeignKey", "line_number": 124, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 128, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 132, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 132, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 134, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 134, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 138, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 138, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 139, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 139, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 140, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 140, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 141, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 141, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 142, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 142, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 143, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 143, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 144, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 144, "usage_type": "name"}, {"api_name": "requests.post", "line_number": 147, "usage_type": "call"}, {"api_name": "requests.codes", "line_number": 148, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 149, "usage_type": "call"}, {"api_name": "flask.redirect", "line_number": 151, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 151, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 152, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 158, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 158, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 159, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 159, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 166, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 179, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 179, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 180, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 180, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 181, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 181, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 182, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 182, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 190, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 190, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 191, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 191, "usage_type": "name"}, {"api_name": "flask.request.form", "line_number": 193, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 193, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 198, "usage_type": "call"}, {"api_name": "flask.request.args.get", "line_number": 202, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 202, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 202, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 217, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 230, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 230, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 234, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 240, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 240, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 241, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 241, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 241, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 242, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 242, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 299, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 304, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 304, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 305, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 305, "usage_type": "name"}, {"api_name": "datetime.timedelta", "line_number": 305, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 306, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 306, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 310, "usage_type": "call"}]}
+{"seq_id": "229251584", "text": "import requests\nimport re\n\n#a = input()\n#b = input()\n\na = \"https://stepic.org/media/attachments/lesson/24472/sample0.html\"\nb = \"https://stepic.org/media/attachments/lesson/24472/sample2.html\"\n\naRequest = requests.get(a)\n\nlinks = re.findall(r'href=[\\'\"]?([^\\'\" >]+)',aRequest.text,flags=re.IGNORECASE)\n\ncLinks = []\nfor link in links:\n cLinks.extend(re.findall(r'href=[\\'\"]?([^\\'\" >]+)',requests.get(link).text,flags=re.IGNORECASE))\n\nif b in cLinks:\n print(\"Yes\")\nelse:\n print(\"No\")\n", "sub_path": "week 3/3.4.6.py", "file_name": "3.4.6.py", "file_ext": "py", "file_size_in_byte": 490, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 10, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 12, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 12, "usage_type": "attribute"}, {"api_name": "re.findall", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 16, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 16, "usage_type": "attribute"}]}
+{"seq_id": "434567707", "text": "############\r\n# Funcional e OO\r\n# Prof. Neylson\r\n# Gerson Vasconcelos Neto\r\n# aula 04 - python\r\n###########\r\n\r\nimport pandas as pd # Trabalhar com dataframes\r\nimport numpy as np # Cálculo e estatística\r\nimport matplotlib.pyplot as plt # Gráficos\r\nimport seaborn as sns # Gráficos também\r\n\r\npnad = pd.read_csv('https://raw.githubusercontent.com/neylsoncrepalde/introducao_ao_python/master/pes_2012.csv')\r\n\r\n\r\npnad.shape # tamanho do banco\r\n\r\npnad.columns # nomes das variáveis\r\n\r\npnad.head() # primeiros casos\r\n\r\npnad.dtypes # qual que é o type de cada variável\r\n\r\npnad['V0101'].head() # fazendo um head() de um subset\r\npnad.V0101.head() # fazendo um head() de um subset\r\n\r\npnad.UF.head()\r\npnad.UF.dtype # retorna como type objeto\r\npnad.UF = pnad.UF.astype('category') # mudando para uma variável categórica\r\n\r\n\r\n###########\r\n# Sexo\r\n\r\npnad.V0302.head()\r\npnad['sexo'] = pnad.V0302.astype('category') # atribuir como categórica para uma variável sexo\r\npnad.V0302.dtype\r\npnad.Sexo.dtype\r\n\r\n##########\r\n# Cor\r\n\r\npnad.V0404.head()\r\npnad.V0404.value_counts() # frequência\r\n\r\n# substituir nessa variável os sem declaração para NaN\r\n\r\n# só o subset\r\npnad.loc[9,'V8005'] # usar os labels\r\npnad.iloc[2,2] # usar o índice [pnad.columns]\r\n\r\n# substituindo\r\n\r\npnad.loc[pnad['V0404'] == 'Sem declaração', 'V0404'] = np.nan\r\n# selecionar na V0404 apenas os casos em que a V0404 serão 'Sem declaração' e transformá-los em NaN\r\n\r\npnad['V0404'] = pnad['V0404'].astype('category')\r\npnad.V0404.dtype\r\n\r\n\r\n#########\r\n# Renda de todos os trabalhos - V4720\r\n\r\npnad['V4720'].astype('float') # nao consegui porque tem uma sem declaração no meio\r\n\r\npnad.loc[pnad['V4720'] == 'Sem declaração', 'V4720'] = np.nan\r\npnad['renda'] = pnad['V4720'].astype('float') # atribui a uma nova variável em float\r\n\r\npnad.renda.describe() # estatísticas descritivas\r\n\r\n###################\r\n# analisando distribuição de sexo\r\n\r\npnad.sexo.value_counts()\r\n(pnad.sexo.value_counts() / pnad.sexo.value_counts().sum())*100 # em porcentagem\r\n# mas não estão fidedignas porque não está levando em conta o peso amostral dos indivíduos\r\n# análise viesada\r\n\r\n# Idade\r\n\r\npnad.V8005.describe() # estatísticas descritivas\r\npnad.V8005.mean() # média (está viesada)\r\npnad.V8005.var() # variância\r\npnad.V8005.std() # desvio padrão\r\n\r\nnp.average(pnad.V8005, weights = pnad.V4729) # levando em consideração o peso amostral (a V4729 são os pesos)\r\n\r\n##############\r\n# cor \r\n\r\n# distribuição de frequência\r\npd.crosstab(index = pnad.V0404, columns = 'Counts') # a diferença da value_counts é a ordenação\r\n\r\n# distribuição de porcentagens (parametro para percentual = normalize)\r\npd.crosstab(index = pnad.V0404, columns = '%',\r\n normalize = True) * 100\r\n\r\n# tabela cruzada entre sexo e cor\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo)\r\n\r\n# em porcentagem pelas linhas (margins = mostra os totais)\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'index') * 100\r\n\r\n# em porcentagem pelas colunas (margins = mostra os totais)\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'columns') * 100\r\n\r\n# percetuais da tabela inteira\r\npd.crosstab(index = pnad.V0404, columns = pnad.sexo,\r\n margins = True, normalize = 'all') * 100\r\n\r\n####################\r\n# sexo em gráficos\r\n\r\n# sns é do seaborn e plt é do matplotlib \r\nsns.countplot(x = pnad.sexo)\r\nplt.title('Distribuição de sexo no Brasil - 2012')\r\nplt.xlabel('Sexo')\r\nplt.ylabel('Frequência')\r\nplt.show()\r\n\r\n# grafico deitado\r\nsns.countplot(y = pnad.sexo)\r\nplt.title('Distribuição de sexo no Brasil - 2012')\r\nplt.ylabel('Sexo')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n \r\n# cor / raça\r\n\r\nsns.set(color_codes = True) # usando as paletas de cores do seaborn\r\nsns.countplot(y = pnad.V0404)\r\nplt.ylabel('Cor/Raça')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n\r\n# tudo em vermelho\r\n\r\nsns.set(color_codes = True) # usando as paletas de cores do seaborn\r\nsns.countplot(y = pnad.V0404, color = 'r')\r\nplt.ylabel('Cor/Raça')\r\nplt.xlabel('Frequência')\r\nplt.show()\r\n\r\n# visualizando variáveis numéricas\r\n\r\n# histograma\r\nsns.distplot(pnad.renda.dropna(), kde = False) # dropna para tirar as NaNs para poder plotar o gráfico\r\nplt.show()\r\n\r\n\r\n# densidade\r\nsns.distplot(pnad.renda.dropna(), hist = False)\r\nplt.show()\r\n\r\n\r\n# modificando algumas coisas\r\nfig, ax = plt.subplots() # axys\r\nfig.set_size_inches(8, 6)\r\nsns.distplot(pnad.renda.dropna(), hist = False)\r\nplt.show()\r\n\r\n# cruzar uma numérica e uma categórica\r\nsns.boxplot(x = 'V0404', y = 'V8005', data = pnad)\r\nplt.show()\r\n\r\n# cruzar duas variáveis numéricas\r\n# gráfico de dispersão\r\n\r\nplt.scatter(x = pnad.renda, y = pnad.V8005)\r\nplt.show()\r\n\r\n# scatter e a histograma de cada variável\r\nsns.jointplot(x = pnad.renda, y = pnad.V8005)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n", "sub_path": "aula_pyOO_4.py", "file_name": "aula_pyOO_4.py", "file_ext": "py", "file_size_in_byte": 4961, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.read_csv", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.average", "line_number": 86, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 92, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 95, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 99, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 102, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 106, "usage_type": "call"}, {"api_name": "pandas.crosstab", "line_number": 110, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 121, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 121, "usage_type": "name"}, {"api_name": "seaborn.countplot", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "seaborn.set", "line_number": 132, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 133, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 134, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 134, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 135, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 135, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 136, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 136, "usage_type": "name"}, {"api_name": "seaborn.set", "line_number": 140, "usage_type": "call"}, {"api_name": "seaborn.countplot", "line_number": 141, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 142, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 142, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 143, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 143, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 149, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 150, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 154, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 155, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 155, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 159, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 159, "usage_type": "name"}, {"api_name": "seaborn.distplot", "line_number": 161, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 162, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 162, "usage_type": "name"}, {"api_name": "seaborn.boxplot", "line_number": 165, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 166, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 166, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 171, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 171, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 172, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 172, "usage_type": "name"}, {"api_name": "seaborn.jointplot", "line_number": 175, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 176, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 176, "usage_type": "name"}]}
+{"seq_id": "23582443", "text": "import time\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nimport tflib as lib\r\nimport tflib.ops.linear\r\nimport tflib.ops.conv2d\r\nimport tflib.ops.batchnorm\r\nimport tflib.ops.deconv2d\r\nimport xplot\r\nimport datetime\r\nimport os\r\nimport random\r\nimport shutil\r\nimport copy\r\nimport collections\r\nfrom defaultlist import defaultlist\r\n\r\nimport utils\r\n\r\nfrom mpi4py import MPI\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.misc import imsave\r\n\r\nimport _selector as box_selector\r\n\r\n\r\ndef Batchnorm(name, axes, inputs, is_train=tf.Variable(True, trainable=False),\r\n decay=0.9, epsilon=0.00001, act=tf.identity): # NCHW format\r\n\tif ((axes == [0, 2, 3]) or (axes == [0, 1, 2])):\r\n\t\tif axes == [0, 1, 2]: # NHW\r\n\t\t\tinputs = tf.expand_dims(inputs, 1)\r\n\t\t# axes = [0,2,3]\r\n\t\t# Old (working but pretty slow) implementation:\r\n\t\t##########\r\n\r\n\t\t# inputs = tf.transpose(inputs, [0,2,3,1])\r\n\r\n\t\t# mean, var = tf.nn.moments(inputs, [0,1,2], keep_dims=False)\r\n\t\t# offset = lib.param(name+'.offset', np.zeros(mean.get_shape()[-1], dtype='float32'))\r\n\t\t# scale = lib.param(name+'.scale', np.ones(var.get_shape()[-1], dtype='float32'))\r\n\t\t# result = tf.nn.batch_normalization(inputs, mean, var, offset, scale, 1e-4)\r\n\r\n\t\t# return tf.transpose(result, [0,3,1,2])\r\n\r\n\t\t# New (super fast but untested) implementation:\r\n\t\tinputs = tf.transpose(inputs, [0, 2, 3, 1]) # NCHW -> NHWC\r\n\r\n\tx_shape = inputs.get_shape()\r\n\tparams_shape = x_shape[-1:]\r\n\r\n\tfrom tensorflow.python.training import moving_averages\r\n\tfrom tensorflow.python.ops import control_flow_ops\r\n\r\n\twith tf.variable_scope(name) as vs:\r\n\t\taxis = list(range(len(x_shape) - 1))\r\n\r\n\t\t## 2.\r\n\t\t# if tf.__version__ > '0.12.1':\r\n\t\t#\t moving_mean_init = tf.zeros_initializer()\r\n\t\t# else:\r\n\t\t#\t moving_mean_init = tf.zeros_initializer\r\n\r\n\t\toffset = lib.param(name + '.offset', np.zeros(params_shape, dtype='float32'))\r\n\t\tscale = lib.param(name + '.scale', tf.random_normal(params_shape, mean=1.0, stddev=0.002))\r\n\r\n\t\tmoving_mean = lib.param(name + '.moving_mean', np.zeros(params_shape, dtype='float32'), trainable=False)\r\n\t\tmoving_variance = lib.param(name + '.moving_variance', np.ones(params_shape, dtype='float32'), trainable=False)\r\n\r\n\t\t## 3.\r\n\t\t# These ops will only be preformed when training.\r\n\t\tmean, variance = tf.nn.moments(inputs, axis)\r\n\r\n\t\tdef mean_var_with_update():\r\n\t\t\ttry: # TF12\r\n\t\t\t\tupdate_moving_mean = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_mean, mean, decay, zero_debias=False) # if zero_debias=True, has bias\r\n\t\t\t\tupdate_moving_variance = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_variance, variance, decay, zero_debias=False) # if zero_debias=True, has bias\r\n\t\t\t# print(\"TF12 moving\")\r\n\t\t\texcept Exception as e: # TF11\r\n\t\t\t\tupdate_moving_mean = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_mean, mean, decay)\r\n\t\t\t\tupdate_moving_variance = moving_averages.assign_moving_average(\r\n\t\t\t\t\tmoving_variance, variance, decay)\r\n\t\t\t# print(\"TF11 moving\")\r\n\t\t\twith tf.control_dependencies([update_moving_mean, update_moving_variance]):\r\n\t\t\t\treturn tf.identity(mean), tf.identity(variance)\r\n\r\n\t\tm, v = tf.cond(is_train, mean_var_with_update, lambda: (moving_mean, moving_variance))\r\n\t\tresult = act(tf.nn.batch_normalization(inputs, m, v, offset, scale, epsilon))\r\n\r\n\t\tif ((axes == [0, 2, 3]) or (axes == [0, 1, 2])):\r\n\t\t\tresult = tf.transpose(result, [0, 3, 1, 2]) # NHWC -> NCHW\r\n\r\n\t\treturn result\r\n\r\n\r\ndef Scaling(input, factor):\r\n\tinput = tf.keras.backend.resize_images(input, factor, factor, \"channels_first\")\r\n\treturn input\r\n\r\n\r\nclass Mask1:\r\n\r\n\tdef __init__(self, config):\r\n\r\n\t\tself.global_config = config\r\n\t\tself.config = config.get_section('mask1')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.step = 0\r\n\r\n\t\tself.load_path = self.config['load_path']\r\n\t\tself.log_time = self.config['log_every_n_steps']\r\n\t\tself.test_time = self.config['test_steps']\r\n\t\tself.summary_time = self.config['summary_every_n_steps']\r\n\t\tself.Isloadcheckpoint = self.config['isloadcheckpoint']\r\n\r\n\t\tself.path = self.global_config.get_value('cvmodel', 'path')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.lr = self.config['lr']\r\n\t\tself.beta1 = self.config['beta1']\r\n\t\tself.beta2 = self.config['beta2']\r\n\t\tself.lr_a = self.config['lr_a']\r\n\t\tself.beta1_a = self.config['beta1_a']\r\n\t\tself.beta2_a = self.config['beta2_a']\r\n\t\tself.lambda_STN_pixel = self.config['lambda_stn_pixel']\r\n\t\tself.lambda_STN_mask = self.config['lambda_stn_mask']\r\n\t\tself.lambda_Connect = self.config['lambda_connect']\r\n\t\tself.show_lambda_STN_pixel = self.config['show_lambda_stn_pixel']\r\n\t\tself.show_lambda_STN_mask = self.config['show_lambda_stn_mask']\r\n\t\tself.show_lambda_Connect = self.config['show_lambda_connect']\r\n\t\tself.num_box = self.config['num_box']\r\n\t\tself.mask_threshold = self.config['mask_threshold']\r\n\t\tself.CV_BATCH_SIZE = self.config['cv_batch_size']\r\n\t\tself.shuffle_times = self.config['shuffle_times']\r\n\t\tself.pad_b_width = self.config['pad_b_width']\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.BATCH_SIZE = self.global_config.get_value('cvmodel', 'batch_size')\r\n\t\tself.HEIGHT = self.global_config.get_value('cvmodel', 'height')\r\n\t\tself.WIDTH = self.global_config.get_value('cvmodel', 'width')\r\n\t\tself.CHANNELS = self.global_config.get_value('cvmodel', 'channels')\r\n\t\tself.MASK_CHANNELS = self.global_config.get_value('cvmodel', 'mask_channels')\r\n\t\tself.B_HEIGHT = self.global_config.get_value('cvmodel', 'b_height')\r\n\t\tself.B_WIDTH = self.global_config.get_value('cvmodel', 'b_width')\r\n\t\tself.old_B_WIDTH = self.global_config.get_value('cvmodel', 'old_b_width')\r\n\t\tself.box_num_cover = self.global_config.get_value('cvmodel', 'box_num_cover')\r\n\t\tself.warning_path = self.global_config.get_value('cvmodel', 'warning_path')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.dynamic_object_instance_box_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_instance_box_maxnum')\r\n\t\tself.dynamic_object_class_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_class_maxnum')\r\n\t\tself.dynamic_object_instance_maxnum = \\\r\n\t\t\tself.global_config.get_value('cvmodel', 'dynamic_object_instance_maxnum')\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.used_gpu = self.config['used_gpu']\r\n\t\tself.devices = ['gpu:%d' % i for i in range(self.used_gpu)]\r\n\t\tself.shared_device = self.devices[0]\r\n\t\tself.gpu_batch_size = self.CV_BATCH_SIZE // self.used_gpu\r\n\r\n\t\tassert (self.CV_BATCH_SIZE % self.used_gpu == 0)\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.my_seed = self.global_config.get_value('main', 'mpi_seed')\r\n\t\tself.num_gpus = self.global_config.get_value('main', 'num_gpus')\r\n\r\n\t\tassert (self.used_gpu <= self.num_gpus)\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.box_selector = box_selector.Selector(\r\n\t\t\tshape=(self.old_B_WIDTH, self.B_HEIGHT),\r\n\t\t\tI_channels=self.CHANNELS,\r\n\t\t\tM_classes=self.dynamic_object_class_maxnum,\r\n\t\t\tmask_threshold=self.mask_threshold\r\n\t\t)\r\n\r\n\t\t# --------------\r\n\r\n\t\t# MPI\r\n\t\tself.comm = MPI.COMM_WORLD\r\n\r\n\t\tself.mpi_rank = self.comm.Get_rank()\r\n\t\tself.mpi_size = self.comm.Get_size()\r\n\r\n\t\t# --------------\r\n\r\n\t\tself.selection_booster_num = self.config['selection_booster_num']\r\n\t\tself.s_mpi_size = min(self.mpi_size, self.selection_booster_num)\r\n\t\tself.cpu_batch_size = self.BATCH_SIZE // self.s_mpi_size\r\n\r\n\t\tassert (self.BATCH_SIZE % self.s_mpi_size == 0)\r\n\r\n\t\t# --------------\r\n\r\n\r\n\t\tif (self.mpi_rank == 0):\r\n\r\n\t\t\tself.graph = tf.Graph()\r\n\t\t\twith self.graph.as_default():\r\n\r\n\t\t\t\ttf.set_random_seed(self.my_seed)\r\n\t\t\t\tself.create_network()\r\n\r\n\t\t\t\tconfig = tf.ConfigProto(allow_soft_placement = True)\r\n\t\t\t\tconfig.gpu_options.allow_growth = True\r\n\r\n\t\t\t\tself.sess = tf.Session(config=config)\r\n\t\t\t\tself.sess.run(tf.global_variables_initializer())\r\n\r\n\t\t\t\tself.saver = tf.train.Saver()\r\n\r\n\t\t\t\tif self.Isloadcheckpoint:\r\n\t\t\t\t\tcheckpoint = tf.train.get_checkpoint_state(self.load_path)\r\n\t\t\t\t\tprint('------------------')\r\n\t\t\t\t\tprint('mpi_rank: ', self.mpi_rank)\r\n\t\t\t\t\tif checkpoint and checkpoint.model_checkpoint_path:\r\n\t\t\t\t\t\tprint('Mask1 load_path: ', checkpoint.model_checkpoint_path)\r\n\t\t\t\t\t\tself.saver.restore(self.sess, checkpoint.model_checkpoint_path)\r\n\t\t\t\t\t\tprint(\"Mask1 successfully loaded: \", checkpoint.model_checkpoint_path)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tprint(\"Could not find old mask1 network weights\")\r\n\t\t\t\t\tprint('------------------')\r\n\r\n\t\t\t\tif tf.gfile.Exists(self.path + 'summary_mask1_train/'):\r\n\t\t\t\t\ttf.gfile.DeleteRecursively(self.path + 'summary_mask1_train/')\r\n\t\t\t\tif tf.gfile.Exists(self.path + 'summary_mask1_test/'):\r\n\t\t\t\t\ttf.gfile.DeleteRecursively(self.path + 'summary_mask1_test/')\r\n\t\t\t\tself.train_writer = tf.summary.FileWriter(self.path + 'summary_mask1_train/', graph=self.sess.graph)\r\n\t\t\t\tself.test_writer = tf.summary.FileWriter(self.path + 'summary_mask1_test/', graph=self.sess.graph)\r\n\r\n\tdef newsinglePerception(self, I, name, inchannel=3, is_train=None):\r\n\r\n\t\t# similar to the paper learn object from pixels\r\n\t\tX1 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.1', inchannel, 32, 5, I, stride=2)\r\n\t\tX1 = Batchnorm('AttentionNet' + name + '.BN1', [0, 2, 3], X1, is_train)\r\n\t\tX1 = tf.nn.relu(X1)\r\n\t\tX2 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.2', 32, 32, 3, X1, stride=2)\r\n\t\tX2 = Batchnorm('AttentionNet' + name + '.BN2', [0, 2, 3], X2, is_train)\r\n\t\tX2 = tf.nn.relu(X2)\r\n\t\tX3 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.3', 32, 32, 3, X2, stride=1)\r\n\t\tX3 = Batchnorm('AttentionNet' + name + '.BN3', [0, 2, 3], X3, is_train)\r\n\t\tX3 = tf.nn.relu(X3)\r\n\t\t# X4=multiF\r\n\t\tmultiF = tf.concat([I, Scaling(X1, 2), Scaling(X2, 4), Scaling(X3, 4)], 1)\r\n\r\n\t\tX4 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.4', inchannel + 32 + 32 + 32, 16, 1, multiF, stride=1)\r\n\t\tX4 = Batchnorm('AttentionNet' + name + '.BN4', [0, 2, 3], X4, is_train)\r\n\t\tX4 = tf.nn.relu(X4)\r\n\t\tX5 = lib.ops.conv2d.Conv2D('AttentionNet' + name + '.5', 16, 1, 3, X4, stride=1)\r\n\t\tX5 = Batchnorm('AttentionNet' + name + '.BN5', [0, 2, 3], X5, is_train)\r\n\t\toutput = X5\r\n\t\treturn output\r\n\r\n\tdef Mask_AttentionNet(self, I, Mask, inchannel=3, inheight=80, inwidth=80, object_maxnum=6, is_train=None,\r\n\t batch_size=16):\r\n\r\n\t\t# Mask: [batch_size * 2, height, width]\r\n\t\t# I: [batch_size * 2, channel, height, width]\r\n\t\t# M: [batch_size * 2, object_maxnum, height, width]\r\n\r\n\t\tMask = tf.expand_dims(Mask, 1)\r\n\r\n\t\t# trick, could use I instead of I * Mask\r\n\t\tM = self.newsinglePerception(I * Mask, 'mask_o0', inchannel, is_train)\r\n\r\n\t\tfor i in range(1, object_maxnum):\r\n\t\t\tM = tf.concat([M, self.newsinglePerception(I * Mask, 'mask_o' + str(i), inchannel, is_train)], 1)\r\n\r\n\t\tM = tf.nn.softmax(M, 1) * Mask\r\n\r\n\t\tEntropyLoss = -tf.reduce_mean(\r\n\t\t\ttf.reduce_sum(M[: batch_size, :, :, :] * tf.log(tf.clip_by_value(M[: batch_size, :, :, :], 1e-10, 1.0)),\r\n\t\t\t axis=1))\r\n\r\n\t\treturn I, Mask, M, EntropyLoss\r\n\r\n\tdef AgentCoordinates(self, agentmask, inheight, inwidth, batch_size):\r\n\t\t# co_agent: [bacthsize,2]\r\n\r\n\t\tPmap = tf.reduce_sum(agentmask, axis=[1, 2])\r\n\t\tPmap = tf.clip_by_value(Pmap, 1e-10, 1e10)\r\n\r\n\t\tXmap = tf.tile(tf.reshape(tf.range(inheight), [1, inheight, 1]), [batch_size, 1, inwidth])\r\n\t\tYmap = tf.tile(tf.reshape(tf.range(inwidth), [1, 1, inwidth]), [batch_size, inheight, 1])\r\n\r\n\t\tx_agent = tf.reduce_sum(agentmask * tf.cast(Xmap, tf.float32), axis=[1, 2]) / Pmap\r\n\t\ty_agent = tf.reduce_sum(agentmask * tf.cast(Ymap, tf.float32), axis=[1, 2]) / Pmap\r\n\r\n\t\treturn tf.stack([x_agent, y_agent], 1)\r\n\r\n\tdef Tailor_STN_loss(self, ndx, ndy, I, agentmask, batch_size, inheight, inwidth, pre_height, pre_width):\r\n\r\n\t\t# ndx:-dx,ndy:-dy [batch_size]\r\n\t\t# I:[batch_size, channel, height, width]\r\n\t\t# agentmask:[batch_size, height, width]\r\n\r\n\t\tpadI = tf.pad(I, [[0, 0], [0, 0], [pre_height, pre_height],\r\n\t\t [pre_width, pre_width]], \"CONSTANT\", constant_values=-1.0)\r\n\t\tpadMa = tf.pad(agentmask, [[0, 0], [pre_height, pre_height],\r\n\t\t [pre_width, pre_width]], \"CONSTANT\", constant_values=0.0)\r\n\r\n\t\tbatch_idx = tf.tile(tf.reshape(tf.range(0, batch_size), [batch_size, 1, 1]), [1, inheight, inwidth])\r\n\t\t# -dx+|dx|\r\n\t\tx_idx = tf.tile(tf.reshape(tf.range(0, inheight), [1, inheight, 1]), [batch_size, 1, inwidth]) + tf.reshape(\r\n\t\t\tndx + pre_height, [-1, 1, 1])\r\n\t\ty_idx = tf.tile(tf.reshape(tf.range(0, inwidth), [1, 1, inwidth]), [batch_size, inheight, 1]) + tf.reshape(\r\n\t\t\tndy + pre_width, [-1, 1, 1])\r\n\r\n\t\t# Pred_Ia:[batch_size, agent_horizon, agent_horizon, 3 ]\r\n\t\t# Pred_agentmask:[batch_size, agent_horizon, agent_horizon,1]\r\n\t\tindices = tf.stack([batch_idx, x_idx, y_idx], 3)\r\n\r\n\t\tpadI_tr = tf.transpose(padI, [0, 2, 3, 1])\r\n\t\tPred_Ia = tf.gather_nd(padI_tr, indices)\r\n\r\n\t\tindices = tf.stack([batch_idx, x_idx, y_idx], 3)\r\n\t\tPred_agentmask = tf.gather_nd(padMa, indices)\r\n\r\n\t\treturn Pred_Ia, tf.expand_dims(Pred_agentmask, 3)\r\n\r\n\tdef AgentImage_STN_loss(self, dco, I, agentmask, inheight, inwidth, batch_size, pre_height, pre_width):\r\n\t\t# interpolate\r\n\r\n\t\t# dco dx,dy [batch_size,2]\r\n\t\t# x:max_x-dx\r\n\t\t# y:max_y-dy\r\n\r\n\t\tx = pre_height - 1 - dco[:, 0]\r\n\t\ty = pre_width - 1 - dco[:, 1]\r\n\r\n\t\tx0 = tf.cast(tf.floor(x), 'int32')\r\n\t\tx1 = x0 + 1\r\n\t\ty0 = tf.cast(tf.floor(y), 'int32')\r\n\t\ty1 = y0 + 1\r\n\r\n\t\tzero = tf.zeros([], dtype='int32')\r\n\t\tmax_x = tf.cast(pre_height - 1, 'int32')\r\n\t\tmax_y = tf.cast(pre_width - 1, 'int32')\r\n\r\n\t\tx0_f = tf.cast(x0, 'float32')\r\n\t\tx1_f = tf.cast(x1, 'float32')\r\n\t\ty0_f = tf.cast(y0, 'float32')\r\n\t\ty1_f = tf.cast(y1, 'float32')\r\n\r\n\t\tx0 = tf.clip_by_value(x0, zero, 2 * max_x)\r\n\t\tx1 = tf.clip_by_value(x1, zero, 2 * max_x)\r\n\t\ty0 = tf.clip_by_value(y0, zero, 2 * max_y)\r\n\t\ty1 = tf.clip_by_value(y1, zero, 2 * max_y)\r\n\r\n\t\tw1 = tf.reshape(((x1_f - x) * (y1_f - y)), [-1, 1, 1, 1])\r\n\t\tw2 = tf.reshape(((x1_f - x) * (y - y0_f)), [-1, 1, 1, 1])\r\n\t\tw3 = tf.reshape(((x - x0_f) * (y1_f - y)), [-1, 1, 1, 1])\r\n\t\tw4 = tf.reshape(((x - x0_f) * (y - y0_f)), [-1, 1, 1, 1])\r\n\r\n\t\tPred_Ia1, Pred_agentmask1 = self.Tailor_STN_loss(x0 - max_x, y0 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia2, Pred_agentmask2 = self.Tailor_STN_loss(x0 - max_x, y1 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia3, Pred_agentmask3 = self.Tailor_STN_loss(x1 - max_x, y0 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia4, Pred_agentmask4 = self.Tailor_STN_loss(x1 - max_x, y1 - max_y, I, agentmask, batch_size, inheight,\r\n\t\t inwidth, pre_height, pre_width)\r\n\t\tPred_Ia = tf.add_n([w1 * Pred_Ia1, w2 * Pred_Ia2, w3 * Pred_Ia3, w4 * Pred_Ia4])\r\n\t\tPred_agentmask = tf.add_n(\r\n\t\t\t[w1 * Pred_agentmask1, w2 * Pred_agentmask2, w3 * Pred_agentmask3, w4 * Pred_agentmask4])\r\n\r\n\t\treturn Pred_Ia, Pred_agentmask\r\n\r\n\tdef STN_loss(self, Ibox, next_Ibox, M_d_objects, M_next_d_objects, object_maxnum=6,\r\n\t inchannel=3, inheight=80, inwidth=80, batch_size=16, show_lambda_pixel=1, show_lambda_mask=1):\r\n\r\n\t\tdef Pixel_diff_loss(Ibox_d_object_1, M_d_object_1, Ibox_d_object_2, M_d_object_2):\r\n\t\t\t# Ibox_d_object_1, Ibox_d_object_2: [New_batch_size, inheight * 3, inwidth * 3, inchannel]\r\n\t\t\t# M_d_object_1, M_d_object_2: [New_batch_size, inheight * 3, inwidth * 3, 1]\r\n\r\n\t\t\tIbox_d_object_2 = tf.stop_gradient(Ibox_d_object_2)\r\n\r\n\t\t\ttmp_Pmap = tf.maximum(M_d_object_1, M_d_object_2)\r\n\r\n\t\t\tM_d_object_1_sigmoid = tf.sigmoid((M_d_object_1 - 0.5) * 20)\r\n\t\t\tM_d_object_2_sigmoid = tf.sigmoid((M_d_object_2 - 0.5) * 20)\r\n\r\n\t\t\tPixel_loss = tf.reduce_mean(tf.reduce_sum(tf.square(Ibox_d_object_1 - Ibox_d_object_2) * tmp_Pmap,\r\n\t\t\t axis=[1, 2, 3]))\r\n\r\n\t\t\tMask_loss = tf.reduce_mean(tf.reduce_sum(tf.square(M_d_object_1_sigmoid - M_d_object_2_sigmoid),\r\n\t\t\t axis=[1, 2, 3]))\r\n\r\n\t\t\treturn Pixel_loss, Mask_loss\r\n\r\n\t\ttmp_Ibox = tf.tile(tf.expand_dims(Ibox, 1), [1, object_maxnum, 1, 1, 1])\r\n\t\ttmp_next_Ibox = tf.tile(tf.expand_dims(next_Ibox, 1), [1, object_maxnum, 1, 1, 1])\r\n\r\n\t\tNew_batch_size = batch_size * object_maxnum\r\n\t\t# ------------\r\n\t\ttmp_Ibox = tf.reshape(tmp_Ibox, [New_batch_size, inchannel, inheight, inwidth])\r\n\t\ttmp_next_Ibox = tf.reshape(tmp_next_Ibox, [New_batch_size, inchannel, inheight, inwidth])\r\n\t\t# ------------\r\n\t\ttmp_M_d_objects = tf.reshape(M_d_objects, [New_batch_size, inheight, inwidth])\r\n\t\ttmp_M_d_objects_next = tf.reshape(M_next_d_objects, [New_batch_size, inheight, inwidth])\r\n\t\t# ------------\r\n\r\n\t\tco_agent = self.AgentCoordinates(tmp_M_d_objects, inheight=inheight, inwidth=inwidth,\r\n\t\t batch_size=New_batch_size)\r\n\t\tco_agent_next = self.AgentCoordinates(tmp_M_d_objects_next, inheight=inheight, inwidth=inwidth,\r\n\t\t batch_size=New_batch_size)\r\n\t\tCalc_delt = co_agent_next - co_agent\r\n\r\n\t\t# tmp_Ibox, tmp_next_Ibox: [New_batch_size, inchannel, inheight, inwidth] ->\r\n\t\t# [New_batch_size, inchannel, inheight * 3, inwidth * 3]\r\n\t\t# tmp_M_d_objects, tmp_M_d_objects_next: [New_batch_size, inheight, inwidth] ->\r\n\t\t# [New_batch_size, inheight * 3, inwidth * 3]\r\n\r\n\t\t# ------------\r\n\r\n\t\ttmp_Ibox = tf.pad(tmp_Ibox, [[0, 0], [0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=-1.0)\r\n\t\ttmp_next_Ibox = tf.pad(tmp_next_Ibox, [[0, 0], [0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=-1.0)\r\n\t\ttmp_M_d_objects = tf.pad(tmp_M_d_objects, [[0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=0.0)\r\n\t\ttmp_M_d_objects_next = tf.pad(tmp_M_d_objects_next, [[0, 0], [inheight, inheight],\r\n\t\t [inwidth, inwidth]], \"CONSTANT\", constant_values=0.0)\r\n\r\n\t\t# ------------\r\n\r\n\t\tCalc_Ibox, Calc_M_d_objects = self.AgentImage_STN_loss(Calc_delt, tmp_Ibox, tmp_M_d_objects,\r\n\t\t inheight=inheight * 3, inwidth=inwidth * 3,\r\n\t\t batch_size=New_batch_size,\r\n\t\t pre_height=inheight, pre_width=inwidth)\r\n\r\n\t\t# Calc_Ibox: [New_batch_size, inheight * 3, inwidth * 3, inchannel]\r\n\t\t# Calc_M_d_objects: [New_batch_size, inheight * 3, inwidth * 3, 1]\r\n\r\n\t\tCalc_M_d_objects_next = tf.expand_dims(tmp_M_d_objects_next, 3)\r\n\t\tCalc_Ibox_next = tf.transpose(tmp_next_Ibox, [0, 2, 3, 1])\r\n\r\n\t\tPixel_loss, Mask_loss = Pixel_diff_loss(Calc_Ibox, Calc_M_d_objects, Calc_Ibox_next, Calc_M_d_objects_next)\r\n\r\n\t\tPixel_loss = Pixel_loss * object_maxnum / inheight / inwidth / inchannel * show_lambda_pixel\r\n\r\n\t\tMask_loss = Mask_loss * object_maxnum / inheight / inwidth * show_lambda_mask\r\n\r\n\t\toutput_M_d_objects = Calc_M_d_objects[:, inheight: inheight * 2, inwidth: inwidth * 2]\r\n\r\n\t\treturn Pixel_loss, Mask_loss, output_M_d_objects\r\n\r\n\tdef Gaussian_blur(self, M_d_objects, inheight=80, inwidth=80, object_maxnum=6, batch_size=16):\r\n\t\t'''\r\n\t\tstandard kernel 5 * 5:\r\n\t\t\t1 4 7 4 1\r\n\t\t\t4 16 26 16 4\r\n\t\t\t7 26 41 26 7 * 1. / 273\r\n\t\t\t4 16 26 16 4\r\n\t\t\t1 4 7 4 1\r\n\r\n\t\tstandard kernel 3 * 3:\r\n\t\t\t1 2 1\r\n\t\t\t2 4 2 * 1. / 16\r\n\t\t\t1 2 1\r\n\t\t'''\r\n\r\n\t\t# M_d_objects: [batch_size, object_maxnum, inheight, inwidth]\r\n\r\n\t\ttmp_M_d_objects = tf.reshape(M_d_objects, [batch_size * object_maxnum, 1, inheight, inwidth])\r\n\r\n\t\tsobel_x = tf.constant([[1, 4, 7, 4, 1], [4, 16, 26, 16, 4], [7, 26, 41, 26, 7],\r\n\t\t [4, 16, 26, 16, 4], [1, 4, 7, 4, 1]], 'float32') / 273\r\n\t\tsobel_x = tf.reshape(sobel_x, [5, 5, 1, 1])\r\n\r\n\t\t# sobel_x = tf.constant([[1, 2, 1], [2, 4, 2], [1, 2, 1]], 'float32') / 16\r\n\t\t# sobel_x = tf.reshape(sobel_x, [3, 3, 1, 1])\r\n\r\n\t\tresult = tf.nn.convolution(tmp_M_d_objects, filter=sobel_x, padding=\"SAME\", data_format=\"NCHW\")\r\n\r\n\t\tresult = tf.reshape(result, [batch_size, object_maxnum, inheight, inwidth])\r\n\r\n\t\treturn result\r\n\r\n\tdef Connection_loss(self, M_d_objects, object_maxnum=6,\r\n\t inchannel=3, inheight=80, inwidth=80, batch_size=16, show_lambda=1):\r\n\r\n\t\tdef Pixel_inter_loss(M_d_object_1, M_d_object_2):\r\n\t\t\t'''\r\n\t\t\tPmap_1 = tf.reduce_sum(M_d_object_1, axis=[1, 2])\r\n\t\t\tPmap_2 = tf.reduce_sum(M_d_object_2, axis=[1, 2])\r\n\r\n\t\t\tres = tf.reduce_sum(M_d_object_1 * M_d_object_2, axis=[1, 2]) * \\\r\n\t\t\t (tf.square(Pmap_1 + Pmap_2) - tf.square(Pmap_1 - Pmap_2))\r\n\r\n\t\t\tres = tf.reduce_mean(res / tf.clip_by_value(tf.square(Pmap_1 + Pmap_2), 1., 1e10))\r\n\r\n\t\t\treturn res\r\n\t\t\t'''\r\n\r\n\t\t\tres = tf.reduce_sum(tf.minimum(M_d_object_1, M_d_object_2), axis=[1, 2])\r\n\r\n\t\t\tres = tf.reduce_mean(res)\r\n\r\n\t\t\treturn res\r\n\r\n\t\t# tmp_M_d_objects: [batch_size, object_maxnum, inheight, inwidth]\r\n\r\n\t\ttmp_M_d_objects = self.Gaussian_blur(M_d_objects, inheight=inheight, inwidth=inwidth,\r\n\t\t object_maxnum=object_maxnum, batch_size=batch_size)\r\n\r\n\t\tConnect_loss = []\r\n\r\n\t\tfor i in range(object_maxnum):\r\n\t\t\tfor j in range(i + 1, object_maxnum):\r\n\t\t\t\tConnect_loss.append(Pixel_inter_loss(tmp_M_d_objects[:, i], tmp_M_d_objects[:, j]))\r\n\r\n\t\tConnect_loss = tf.reduce_sum(Connect_loss)\r\n\r\n\t\tConnect_loss = Connect_loss / inheight / inwidth * show_lambda\r\n\r\n\t\treturn Connect_loss, tmp_M_d_objects\r\n\r\n\tdef create_loss(self, input_Ibox, input_next_Ibox, input_dmask, input_next_dmask):\r\n\r\n\t\tIbox = 2 * (input_Ibox / 255. - .5)\r\n\t\tnext_Ibox = 2 * (input_next_Ibox / 255. - .5)\r\n\r\n\t\t# Ibox, next_Ibox: [gpu_batch_size, b_width, b_height, channel] -->\r\n\t\t# [gpu_batch_size, channel, b_height, b_width]\r\n\t\t# dmask, next_dmask: [gpu_batch_size, b_width, b_height] -->\r\n\t\t# [gpu_batch_size, b_height, b_width]\r\n\r\n\t\tIbox = tf.transpose(Ibox, [0, 3, 2, 1])\r\n\t\tnext_Ibox = tf.transpose(next_Ibox, [0, 3, 2, 1])\r\n\r\n\t\tdmask = tf.transpose(input_dmask, [0, 2, 1])\r\n\t\tnext_dmask = tf.transpose(input_next_dmask, [0, 2, 1])\r\n\r\n\t\t# ---------------------\r\n\t\t# M_d_objects: [gpu_batch_size, num_objects, b_height, b_width]\r\n\r\n\t\tmulti_Ibox, multi_dmask, M_d_objects_both, EL = \\\r\n\t\t\tself.Mask_AttentionNet(tf.concat([Ibox, next_Ibox], 0), tf.concat([dmask, next_dmask], 0),\r\n\t\t\t inchannel=self.CHANNELS, inheight=self.B_HEIGHT, inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum, is_train=self.is_train,\r\n\t\t\t batch_size=self.gpu_batch_size)\r\n\r\n\t\tM_d_objects = M_d_objects_both[: self.gpu_batch_size]\r\n\t\tM_next_d_objects = M_d_objects_both[self.gpu_batch_size:]\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tSTN_pixel_loss, STN_mask_loss, output_M_d_objects = \\\r\n\t\t\tself.STN_loss(Ibox, next_Ibox, M_d_objects, M_next_d_objects,\r\n\t\t\t inchannel=self.CHANNELS,\r\n\t\t\t inheight=self.B_HEIGHT,\r\n\t\t\t inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum,\r\n\t\t\t batch_size=self.gpu_batch_size,\r\n\t\t\t show_lambda_pixel=self.show_lambda_STN_pixel,\r\n\t\t\t show_lambda_mask=self.show_lambda_STN_mask)\r\n\r\n\t\t# Calc_M_d_objects: [gpu_batch_size, object_maxnum, b_height, b_width]\r\n\t\tCalc_M_d_objects = tf.reshape(output_M_d_objects, [self.gpu_batch_size, self.dynamic_object_class_maxnum,\r\n\t\t self.B_HEIGHT, self.B_WIDTH])\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tConnection_loss, Gaussian_M_d_objects_both = \\\r\n\t\t\tself.Connection_loss(M_d_objects_both,\r\n\t\t\t inchannel=self.CHANNELS,\r\n\t\t\t inheight=self.B_HEIGHT,\r\n\t\t\t inwidth=self.B_WIDTH,\r\n\t\t\t object_maxnum=self.dynamic_object_class_maxnum,\r\n\t\t\t batch_size=self.gpu_batch_size * 2,\r\n\t\t\t show_lambda=self.show_lambda_Connect)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\tTotal_loss = self.lambda_STN_pixel * STN_pixel_loss\r\n\r\n\t\tloss_list = (Total_loss, STN_pixel_loss, STN_mask_loss, Connection_loss)\r\n\t\tsummary_list = (Ibox, next_Ibox, M_d_objects, M_next_d_objects, dmask, next_dmask,\r\n\t\t Gaussian_M_d_objects_both, Calc_M_d_objects)\r\n\t\ttest_list = (Ibox, next_Ibox, M_d_objects, M_next_d_objects)\r\n\r\n\t\treturn loss_list, summary_list, test_list\r\n\r\n\tdef create_network(self):\r\n\r\n\t\t# =======Construct graph=======\r\n\t\t# need all float32\r\n\t\t# input image : 0-255, [batch_size, width, height, 3]\r\n\r\n\t\tself.is_train = tf.placeholder(tf.bool)\r\n\t\tself.input_Ibox = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH,\r\n\t\t self.B_HEIGHT, self.CHANNELS])\r\n\t\tself.input_next_Ibox = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH,\r\n\t\t self.B_HEIGHT, self.CHANNELS])\r\n\t\tself.input_dmask = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH, self.B_HEIGHT])\r\n\t\tself.input_next_dmask = tf.placeholder(tf.float32, shape=[self.CV_BATCH_SIZE, self.B_WIDTH, self.B_HEIGHT])\r\n\r\n\t\t# ---------------------\r\n\r\n\t\twith tf.device(self.shared_device):\r\n\r\n\t\t\topt = tf.train.AdamOptimizer(learning_rate=self.lr)\r\n\r\n\t\t\tif (len(self.devices) == 1):\r\n\r\n\t\t\t\tloss_list, summary_list, test_list = \\\r\n\t\t\t\t\tself.create_loss(self.input_Ibox, self.input_next_Ibox, self.input_dmask, self.input_next_dmask)\r\n\t\t\t\tTotal_loss = loss_list[0]\r\n\r\n\t\t\t\tself.train_total_op = opt.minimize(Total_loss)\r\n\t\t\telse:\r\n\t\t\t\ttower_grads, tmp_loss_list, tmp_summary_list, tmp_test_list = [], [], [], []\r\n\t\t\t\twith tf.variable_scope(tf.get_variable_scope()):\r\n\t\t\t\t\tfor i, dev_id in enumerate(self.devices):\r\n\t\t\t\t\t\tl = i * self.gpu_batch_size\r\n\t\t\t\t\t\tr = (i + 1) * self.gpu_batch_size\r\n\r\n\t\t\t\t\t\twith tf.device(dev_id):\r\n\t\t\t\t\t\t\twith tf.name_scope('tower_{}'.format(i)):\r\n\t\t\t\t\t\t\t\tt_loss_list, t_summary_list, test_list = \\\r\n\t\t\t\t\t\t\t\t\tself.create_loss(self.input_Ibox[l: r], self.input_next_Ibox[l: r],\r\n\t\t\t\t\t\t\t\t\t self.input_dmask[l: r], self.input_next_dmask[l: r])\r\n\t\t\t\t\t\t\t\tTotal_loss = t_loss_list[0]\r\n\r\n\t\t\t\t\t\t\t\t# Reuse variables for the next tower.\r\n\t\t\t\t\t\t\t\ttf.get_variable_scope().reuse_variables()\r\n\r\n\t\t\t\t\t\t\t\tgrads = opt.compute_gradients(Total_loss)\r\n\t\t\t\t\t\t\t\ttower_grads.append(grads)\r\n\r\n\t\t\t\t\t\t\t\ttmp_loss_list.append(t_loss_list)\r\n\t\t\t\t\t\t\t\ttmp_summary_list.append(t_summary_list)\r\n\t\t\t\t\t\t\t\ttmp_test_list.append(test_list)\r\n\r\n\t\t\t\tgrads = utils.average_gradients(tower_grads)\r\n\t\t\t\tapply_gradient_op = opt.apply_gradients(grads)\r\n\t\t\t\tself.train_total_op = apply_gradient_op\r\n\r\n\t\t\t\tloss_list = utils.reduce_mean_tf_data_flow(tmp_loss_list)\r\n\t\t\t\tsummary_list = utils.concat_tf_data_flow(tmp_summary_list)\r\n\t\t\t\ttest_list = utils.concat_tf_data_flow(tmp_test_list)\r\n\r\n\t\t\tself.Total_loss, self.STN_pixel_loss, self.STN_mask_loss, self.Connection_loss = loss_list\r\n\t\t\tIbox, next_Ibox, M_d_objects, M_next_d_objects, dmask, next_dmask, \\\r\n\t\t\tGaussian_M_d_objects_both, Calc_M_d_objects = summary_list\r\n\t\t\tself.Ibox_1, self.Ibox_2, self.M_d_objects_1, self.M_d_objects_2 = test_list\r\n\r\n\t\t# ---------------------\r\n\r\n\t\ttf.summary.scalar('STN_pixel_loss', self.STN_pixel_loss)\r\n\t\ttf.summary.scalar('STN_mask_loss', self.STN_mask_loss)\r\n\t\ttf.summary.scalar('Connect_loss', self.Connection_loss)\r\n\t\ttf.summary.scalar('TotalLoss', self.Total_loss)\r\n\r\n\t\ttf.summary.image('Image_box', tf.transpose(Ibox, [0, 2, 3, 1]))\r\n\t\ttf.summary.image('Image_next_box', tf.transpose(next_Ibox, [0, 2, 3, 1]))\r\n\t\ttf.summary.image('dmask', tf.expand_dims(dmask, 3))\r\n\t\ttf.summary.image('next_dmask', tf.expand_dims(next_dmask, 3))\r\n\t\ttf.summary.image('Image_box_mask', tf.transpose(Ibox, [0, 2, 3, 1]) * tf.expand_dims(dmask, 3))\r\n\t\ttf.summary.image('Image_next_box_mask', tf.transpose(next_Ibox, [0, 2, 3, 1]) * tf.expand_dims(next_dmask, 3))\r\n\r\n\t\tfor i in range(self.dynamic_object_class_maxnum):\r\n\t\t\ttmp = tf.expand_dims(M_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('M_object_' + str(i), tmp)\r\n\t\t\ttf.summary.image('I_object_' + str(i), tf.cast(tmp >= 0.5, tf.float32) * tf.transpose(Ibox, [0, 2, 3, 1]))\r\n\r\n\t\t\ttmp = tf.expand_dims(M_next_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('M_object_next_' + str(i), tmp)\r\n\t\t\ttf.summary.image('I_object_next_' + str(i),\r\n\t\t\t tf.cast(tmp >= 0.5, tf.float32) * tf.transpose(next_Ibox, [0, 2, 3, 1]))\r\n\r\n\t\t\ttmp = tf.expand_dims(Gaussian_M_d_objects_both[: self.CV_BATCH_SIZE, i, :, :], 3)\r\n\t\t\ttf.summary.image('Gaussian_M_object_' + str(i), tmp)\r\n\r\n\t\t\ttmp = tf.expand_dims(Calc_M_d_objects[:, i, :, :], 3)\r\n\t\t\ttf.summary.image('Moved_M_object_' + str(i), tmp)\r\n\r\n\t\tself.summary_op = tf.summary.merge_all()\r\n\r\n\tdef data_batch_alignment(self, t_data, batch_size, pad_value):\r\n\r\n\t\tt_data_shape_num = len(t_data.shape)\r\n\t\tt_data_num = t_data.shape[0]\r\n\t\tt_data_num_fix = ((t_data_num - 1) // batch_size + 1) * batch_size\r\n\r\n\t\tpad_list = [[0, t_data_num_fix - t_data_num]] + [[0, 0]] * (t_data_shape_num - 1)\r\n\r\n\t\tt_data = np.pad(t_data, pad_list, 'constant', constant_values=pad_value)\r\n\r\n\t\treturn t_data\r\n\r\n\tdef evaluation(self, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask, bbox_coor, is_train):\r\n\r\n\t\tdef recover_batch(data):\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num, object_maxnum, b_height, b_width] ->\r\n\t\t\t# [each_batch_num, object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num, channel, b_height, b_width] ->\r\n\t\t\t# [each_batch_num, channel, b_height, old_b_width]\r\n\t\t\tdata = np.concatenate([data[:, :, :, : self.old_B_WIDTH],\r\n\t\t\t data[:, :, :, self.old_B_WIDTH + self.pad_b_width:]], axis=0)\r\n\t\t\treturn data\r\n\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\r\n\t\tt_1 = time.time()\r\n\r\n\t\tt_data = []\r\n\t\tt_bbox = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\t\t\t# t_copy: [each_batch_num, old_b_width, b_height, channel * 2 + 2]\r\n\t\t\tt_copy = [Ibox[i].copy(), next_Ibox[i].copy(),\r\n\t\t\t np.expand_dims(dynamics_mask[i], 3), np.expand_dims(next_dynamics_mask[i], 3)]\r\n\t\t\tt_copy = np.concatenate(t_copy, axis=3)\r\n\t\t\tt_data.append(t_copy)\r\n\t\t\tt_bbox.append(bbox_coor[i])\r\n\r\n\t\tt_data = np.concatenate(t_data, axis=0)\r\n\t\tt_data = self.data_batch_alignment(t_data, 2 * self.CV_BATCH_SIZE, 0.)\r\n\r\n\t\tt_bbox = np.concatenate(t_bbox, axis=0)\r\n\r\n\t\t# t_data: [t_data_num_fix, old_b_width, b_height, channel * 2 + 2] ->\r\n\t\t# [t_data_num_fix // 2, b_width, b_height, channel * 2 + 2]\r\n\r\n\t\tt_data_num = t_data.shape[0]\r\n\r\n\t\tt_data_pad = np.pad(t_data[: t_data_num // 2], [[0, 0],\r\n\t\t [0, self.pad_b_width], [0, 0], [0, 0]], 'constant')\r\n\t\tt_data = np.concatenate([t_data_pad, t_data[t_data_num // 2:]], axis=1)\r\n\r\n\t\t# t_data_num: sum_batch_box\r\n\t\t# self.CV_BATCH_SIZE | t_data_num_fix\r\n\t\t# t_data: [t_data_num_fix, b_width, b_height, channel * 2 + 2]\r\n\t\t# t_bbox: [t_data_num, 4]\r\n\r\n\t\tres = defaultlist(list)\r\n\r\n\t\tfor i in range(t_data.shape[0] // self.CV_BATCH_SIZE):\r\n\r\n\t\t\tl = i * self.CV_BATCH_SIZE\r\n\t\t\tr = (i + 1) * self.CV_BATCH_SIZE\r\n\t\t\ttmp = self.CHANNELS * 2\r\n\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\t# tmp_Ibox_1, tmp_Ibox_2, tmp_mask_1, tmp_mask_2\r\n\t\t\t\tt_res = self.sess.run([self.Ibox_1, self.Ibox_2, self.M_d_objects_1, self.M_d_objects_2],\r\n\t\t\t\t feed_dict={\r\n\t\t\t\t\t\t self.input_Ibox: t_data[l: r, :, :, :self.CHANNELS],\r\n\t\t\t\t\t\t self.input_next_Ibox: t_data[l: r, :, :, self.CHANNELS: tmp],\r\n\t\t\t\t\t\t self.input_dmask: t_data[l: r, :, :, tmp],\r\n\t\t\t\t\t\t self.input_next_dmask: t_data[l: r, :, :, tmp + 1],\r\n\t\t\t\t\t\t self.is_train: is_train\r\n\t\t\t\t\t })\r\n\r\n\t\t\tfor x, item in enumerate(t_res):\r\n\t\t\t\tres[x].append(item)\r\n\r\n\t\tevaluation_data = []\r\n\r\n\t\tfor item in res:\r\n\t\t\titem_1 = np.concatenate(item, axis=0)\r\n\t\t\titem_2 = recover_batch(item_1)\r\n\t\t\tevaluation_data.append(item_2)\r\n\r\n\t\tt_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2 = evaluation_data\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Testing mask1:', time.time() - t_1)\r\n\r\n\t\treturn t_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2, t_bbox\r\n\r\n\tdef box_choose_K(self, t_dynamics_instances, K):\r\n\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [M_classes, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\r\n\t\treturn_Ibox, return_Ibox_next, return_mask, return_mask_next, return_bbox, return_label, return_Md, \\\r\n\t\treturn_C, return_next_C, return_Ms = t_dynamics_instances\r\n\r\n\t\t'''\r\n\t\tprint('return_Ibox', return_Ibox.shape)\r\n\t\tprint('return_Ibox_next', return_Ibox_next.shape)\r\n\t\tprint('return_mask', return_mask.shape)\r\n\t\tprint('return_mask_next', return_mask_next.shape)\r\n\t\tprint('return_bbox', return_bbox.shape)\r\n\t\tprint('return_label', return_label.shape)\r\n\t\tprint('return_Md', return_Md.shape)\r\n\t\t'''\r\n\r\n\t\tselected_num = return_Ibox.shape[0]\r\n\r\n\t\t'''\r\n\t\tif (selected_num > K):\r\n\t\t\tt_copy = (return_Ibox[: K], return_Ibox_next[: K], return_mask[: K], return_mask_next[: K],\r\n\t\t\t return_bbox[: K], return_label[: K], return_C[: K], return_next_C[: K], return_Ms[: K])\r\n\t\telse:\r\n\t\t\tt_copy = (return_Ibox, return_Ibox_next, return_mask, return_mask_next, return_bbox, return_label,\r\n\t\t\t return_C, return_next_C, return_Ms)\r\n\t\t'''\r\n\r\n\t\tif (selected_num > K):\r\n\t\t\tt_copy = (return_label[: K], return_C[: K], return_next_C[: K], return_Ms[: K])\r\n\t\telse:\r\n\t\t\tt_copy = (return_label, return_C, return_next_C, return_Ms)\r\n\r\n\t\tres = []\r\n\r\n\t\tfor item in t_copy:\r\n\t\t\tres.append(self.data_batch_alignment(item, K, 0))\r\n\r\n\t\tres.append(return_Md)\r\n\r\n\t\treturn res, selected_num\r\n\r\n\tdef folder_prepare(self, selection_path):\r\n\t\tfolder = os.path.exists(selection_path)\r\n\t\tif (folder):\r\n\t\t\tshutil.rmtree(selection_path)\r\n\t\tos.makedirs(selection_path)\r\n\r\n\tdef show_selection(self, I, nextI, wmask, next_wmask, batch_cache, batch_dynamics_instances):\r\n\r\n\t\t# batch_dynamics_instances: [batch_examples]\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [M_classes, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\t\t# wmask, next_wmask: [width, height]\r\n\r\n\t\tsave_start = self.mpi_rank * self.cpu_batch_size\r\n\r\n\t\tfor i in range(self.cpu_batch_size):\r\n\r\n\t\t\tt_Ibox, t_Ibox_next, t_mask, t_mask_next, t_bbox, t_label, t_Md, t_C, t_next_C, t_Ms = \\\r\n\t\t\t\tbatch_dynamics_instances[i]\r\n\r\n\t\t\tt_wmask, t_next_wmask = wmask[i], next_wmask[i]\r\n\r\n\t\t\tt_I, t_next_I = I[i], nextI[i]\r\n\r\n\t\t\tt_selected_num = t_Ibox.shape[0]\r\n\r\n\t\t\tselection_path = '../../tmp/' + self.path + 'selection_' + str(save_start + i) + '/'\r\n\r\n\t\t\tself.folder_prepare(selection_path)\r\n\r\n\t\t\tfor j in range(t_selected_num):\r\n\t\t\t\timsave(selection_path + 'Ibox_' + str(j) + '.jpg', np.transpose(t_Ibox[j], [1, 0, 2]))\r\n\t\t\t\timsave(selection_path + 'Ibox_next_' + str(j) + '.jpg', np.transpose(t_Ibox_next[j], [1, 0, 2]))\r\n\t\t\t\timsave(selection_path + 'mask_' + str(j) + '.jpg', np.transpose(t_mask[j], [1, 0]))\r\n\t\t\t\timsave(selection_path + 'mask_next_' + str(j) + '.jpg', np.transpose(t_mask_next[j], [1, 0]))\r\n\t\t\t\timsave(selection_path + 'Ms_' + str(j) + '.jpg', np.transpose(t_Ms[j], [1, 0]))\r\n\r\n\t\t\tnp.savetxt(selection_path + 'bbox.txt', t_bbox, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'label.txt', t_label, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'C.txt', t_C, fmt='%d ')\r\n\t\t\tnp.savetxt(selection_path + 'next_C.txt', t_next_C, fmt='%d ')\r\n\r\n\t\t\tfor j in range(self.dynamic_object_class_maxnum):\r\n\t\t\t\timsave(selection_path + 'Md_' + str(j) + '.jpg', np.transpose(t_Md[j], [1, 0]))\r\n\r\n\t\t\timsave(selection_path + 'wmask_' + '.jpg', np.transpose(t_wmask, [1, 0]))\r\n\t\t\timsave(selection_path + 'wmask_next_' + '.jpg', np.transpose(t_next_wmask, [1, 0]))\r\n\r\n\t\t\timsave(selection_path + 'I_true' + '.jpg', np.transpose(t_I, [1, 0, 2]))\r\n\t\t\timsave(selection_path + 'next_I_true' + '.jpg', np.transpose(t_next_I, [1, 0, 2]))\r\n\r\n\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\tI_input, nextI_input = I[i], nextI[i]\r\n\t\t\tIb_input, nextIb_input, Mb_input, nextMb_input, XY_input, label_input = \\\r\n\t\t\t\tbatch_cache[i]\r\n\t\t\tselection_path = '../../tmp/' + self.path + 'selection_' + str(save_start + i) + '/'\r\n\t\t\timsave(selection_path + 'I.jpg', I_input)\r\n\t\t\timsave(selection_path + 'nextI.jpg', nextI_input)\r\n\t\t\tnp.save(selection_path + 'I_input.npy', I_input)\r\n\t\t\tnp.save(selection_path + 'nextI_input.npy', nextI_input)\r\n\t\t\tnp.save(selection_path + 'Ib_input.npy', Ib_input)\r\n\t\t\tnp.save(selection_path + 'nextIb_input.npy', nextIb_input)\r\n\t\t\tnp.save(selection_path + 'Mb_input.npy', Mb_input)\r\n\t\t\tnp.save(selection_path + 'nextMb_input.npy', nextMb_input)\r\n\t\t\tnp.save(selection_path + 'XY_input.npy', XY_input)\r\n\t\t\tnp.save(selection_path + 'label_input', label_input)\r\n\r\n\tdef selection(self, I, bgimage, nextI, Ibox, next_Ibox, wmask, next_wmask, evaluation_data,\r\n\t is_train, is_show=False):\r\n\r\n\t\tdef Transmit_numpy(item_list, mpi_id=0, tag=10):\r\n\t\t\t# list(x) for x in (tmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label) and x is numpy\r\n\t\t\t#\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t\t# tmp_bbox: [each_batch_num * object_maxnum, 4]\r\n\t\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\tutils.Transmit_numpy(list(item_list[i]), mpi_id=mpi_id, tag=tag)\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\r\n\t\tt_1 = time.time()\r\n\r\n\t\t# open selection booster\r\n\t\tutils.Transmit_normal(True, mpi_upper=self.s_mpi_size, tag=14)\r\n\r\n\t\t# transmit is_show\r\n\t\tutils.Transmit_normal(is_show, mpi_upper=self.s_mpi_size, tag=18)\r\n\r\n\t\tt_res_Ibox_1, t_res_Ibox_2, t_res_mask_1, t_res_mask_2, t_bbox = evaluation_data\r\n\r\n\t\tt_stamp = 0\r\n\t\tbatch_cache = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\t\t\tt_instance_num = Ibox[i].shape[0]\r\n\t\t\tt_num = t_stamp + t_instance_num\r\n\r\n\t\t\t# object_maxnum: self.dynamic_object_class_maxnum\r\n\t\t\t# tmp_mask, tmp_mask_next: [each_batch_num, object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num, channel, b_height, old_b_width]\r\n\t\t\t# tmp_bbox: [each_batch_num, 4]\r\n\r\n\t\t\ttmp_mask, tmp_mask_next = t_res_mask_1[t_stamp: t_num], t_res_mask_2[t_stamp: t_num]\r\n\t\t\ttmp_Ibox, tmp_Ibox_next = t_res_Ibox_1[t_stamp: t_num], t_res_Ibox_2[t_stamp: t_num]\r\n\t\t\ttmp_bbox = t_bbox[t_stamp: t_num]\r\n\r\n\t\t\tt_stamp = t_num\r\n\r\n\t\t\t# ---------------------\r\n\r\n\t\t\t# tmp_mask, tmp_mask_next -> [each_batch_num * object_maxnum, b_height, old_b_width]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next -> [each_batch_num * object_maxnum, channel, b_height, old_b_width]\r\n\t\t\t# tmp_bbox -> [each_batch_num * object_maxnum, 4]\r\n\t\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\r\n\t\t\ttmp_object_maxnum = self.dynamic_object_class_maxnum\r\n\r\n\t\t\ttmp_mask = np.reshape(tmp_mask, [t_instance_num * tmp_object_maxnum,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_mask_next = np.reshape(tmp_mask_next, [t_instance_num * tmp_object_maxnum,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_Ibox = np.reshape(np.tile(np.expand_dims(tmp_Ibox, 1), (1, tmp_object_maxnum, 1, 1, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, self.CHANNELS,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_Ibox_next = np.reshape(np.tile(np.expand_dims(tmp_Ibox_next, 1), (1, tmp_object_maxnum, 1, 1, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, self.CHANNELS,\r\n\t\t\t self.B_HEIGHT, self.old_B_WIDTH])\r\n\t\t\ttmp_bbox = np.reshape(np.tile(np.expand_dims(tmp_bbox, 1), (1, tmp_object_maxnum, 1)),\r\n\t\t\t [t_instance_num * tmp_object_maxnum, 4])\r\n\t\t\ttmp_label = np.tile(np.arange(tmp_object_maxnum), t_instance_num)\r\n\r\n\t\t\t# tmp_mask, tmp_mask_next -> [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t\t# tmp_Ibox, tmp_Ibox_next -> [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\r\n\t\t\ttmp_mask = np.transpose(tmp_mask, [0, 2, 1])\r\n\t\t\ttmp_mask_next = np.transpose(tmp_mask_next, [0, 2, 1])\r\n\t\t\ttmp_Ibox = np.transpose(tmp_Ibox, [0, 3, 2, 1])\r\n\t\t\ttmp_Ibox_next = np.transpose(tmp_Ibox_next, [0, 3, 2, 1])\r\n\r\n\t\t\t# ---------------------\r\n\t\t\tbatch_cache.append((tmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label))\r\n\r\n\t\t# Function = self.box_selector.get_selection\r\n\t\t#\r\n\t\t# Input:\r\n\t\t# I, nextI: [width, height, channel]\r\n\t\t# tmp_Ibox, tmp_Ibox_next: [each_batch_num * object_maxnum, old_b_width, b_height, channel]\r\n\t\t# tmp_mask, tmp_mask_next: [each_batch_num * object_maxnum, old_b_width, b_height]\r\n\t\t# tmp_bbox: [each_batch_num * object_maxnum, 4]\r\n\t\t# tmp_label: [each_batch_num * object_maxnum]\r\n\t\t# Output:\r\n\t\t# return_Ibox, return_Ibox_next: [selected_num, old_b_width, b_height, channel]\r\n\t\t# return_mask, return_mask_next: [selected_num, old_b_width, b_height]\r\n\t\t# return_bbox: [selected_num, 4]\r\n\t\t# return_label: [selected_num]\r\n\t\t# return_Md: [object_maxnum, width, height]\r\n\t\t# return_C, return_next_C: [selected_num, 2]\r\n\t\t# return_Ms: [selected_num, width, height]\r\n\t\t#\r\n\t\t# dynamic selected_num is not ok.\r\n\r\n\t\t#print('Selecting_1:', time.time() - t_1)\r\n\r\n\t\tfor mpi_id in range(1, self.s_mpi_size):\r\n\t\t\tl = mpi_id * self.cpu_batch_size\r\n\t\t\tr = (mpi_id + 1) * self.cpu_batch_size\r\n\t\t\tutils.Transmit_numpy([I[l: r], nextI[l: r],\r\n\t\t\t wmask[l: r], next_wmask[l: r]], mpi_id=mpi_id, tag=19)\r\n\t\t\tTransmit_numpy(batch_cache[l: r], mpi_id=mpi_id, tag=15)\r\n\r\n\t\t#print('Selecting_2:', time.time() - t_1)\r\n\r\n\t\tres_list = []\r\n\t\tshow_instances_cpu_size = []\r\n\t\tmerge_selection_num_list = []\r\n\r\n\t\tfor j in range(self.s_mpi_size):\r\n\r\n\t\t\tif (j == 0):\r\n\t\t\t\tbatch_dynamics_instances_K = defaultlist(list)\r\n\t\t\t\tselection_num_list = []\r\n\t\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\t\ttmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label = batch_cache[i]\r\n\t\t\t\t\tt_dynamics_instances = self.box_selector.get_selection(I[i], nextI[i], tmp_Ibox, tmp_Ibox_next,\r\n\t\t\t\t\t tmp_mask, tmp_mask_next, tmp_bbox, tmp_label,\r\n\t\t\t\t\t self.warning_path)\r\n\t\t\t\t\tt_dynamics_instances_K, box_selected_num = \\\r\n\t\t\t\t\t\tself.box_choose_K(t_dynamics_instances, self.dynamic_object_instance_box_maxnum)\r\n\t\t\t\t\t# (return_label, return_C, return_next_C, return_Ms, return_Md)\r\n\t\t\t\t\tfor t_stamp_K, item in enumerate(t_dynamics_instances_K):\r\n\t\t\t\t\t\tbatch_dynamics_instances_K[t_stamp_K].append(item)\r\n\t\t\t\t\tselection_num_list.append(box_selected_num)\r\n\t\t\t\t\tif (is_show):\r\n\t\t\t\t\t\tshow_instances_cpu_size.append(t_dynamics_instances)\r\n\r\n\t\t\t\tres = []\r\n\t\t\t\tfor item in batch_dynamics_instances_K:\r\n\t\t\t\t\tres.append(np.array(item))\r\n\r\n\t\t\t\t#print('Selecting_3:', time.time() - t_1)\r\n\t\t\telse:\r\n\t\t\t\tres = utils.Receive_numpy(source=j, tag=16)\r\n\t\t\t\tselection_num_list = self.comm.recv(source=j, tag=17)\r\n\r\n\t\t\tres_list.append(res)\r\n\t\t\tmerge_selection_num_list.append(selection_num_list)\r\n\r\n\t\tmerge_res = utils.concat_np_data_list_flow(res_list)\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Selecting:', time.time() - t_1)\r\n\t\t\tprint('Mean number of selection in a batch :', np.mean(merge_selection_num_list))\r\n\t\t\tprint('Max number of selection in a batch :', np.max(merge_selection_num_list))\r\n\t\t\txplot.plot('Mean_number_of_selection', np.mean(merge_selection_num_list))\r\n\t\t\txplot.plot('Max_number_of_selection', np.max(merge_selection_num_list))\r\n\r\n\t\tif (is_show):\r\n\t\t\tr = self.cpu_batch_size\r\n\t\t\tself.show_selection(I[:r], nextI[:r], wmask[:r], next_wmask[:r], batch_cache[:r], show_instances_cpu_size)\r\n\r\n\t\treturn merge_res\r\n\r\n\tdef evaluate_to_selection(self, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor, is_train, is_show=False):\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\t# Evaluation\r\n\r\n\t\tevaluation_data = \\\r\n\t\t\tself.evaluation(Ibox, next_Ibox, dynamics_mask, next_dynamics_mask, bbox_coor, is_train)\r\n\r\n\t\t# ---------------------\r\n\r\n\t\t# Selection\r\n\r\n\t\t# selected_num: self.dynamic_object_instance_box_maxnum\r\n\t\t# dynamics_mask_label: [batch, selected_num]\r\n\t\t# dynamics_mask_C, dynamics_mask_next_C: [batch, selected_num, 2]\r\n\t\t# dynamics_filter_box: [batch, selected_num, width, height]\r\n\t\t# dynamics_multi_mask: [batch, object_maxnum, width, height]\r\n\r\n\t\tres = self.selection(I, bgimage, nextI, Ibox, next_Ibox, wmask, next_wmask, evaluation_data,\r\n\t\t is_train, is_show=is_show)\r\n\r\n\t\treturn res\r\n\r\n\tdef save_to_file(self, file_name, contents):\r\n\t\tfh = open(file_name, 'w')\r\n\t\tfh.write(contents)\r\n\t\tfh.close()\r\n\r\n\tdef train_to_mask1(self, train_list, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor, is_train):\r\n\r\n\t\t# I, nextI, bgimage: [batch, width, height, channel]\r\n\t\t# Ibox, next_Ibox: [list(batch), num_select_box, old_b_width, b_height, channel]\r\n\t\t# dynamics_mask, next_dynamics_mask: [list(batch), num_select_box, old_b_width, b_height]\r\n\t\t# wmask, next_wmask: [batch, width, height]\r\n\t\t# bbox_coor: [list(batch), num_select_box, 4] (width_1, width_2, height_1, height_2)\r\n\t\t#\r\n\t\t# CV_BATCH_SIZE | BATCH_SIZE * num_box\r\n\r\n\t\tt_shuffle = []\r\n\t\tbox_num_list = []\r\n\r\n\t\tfor i in range(self.BATCH_SIZE):\r\n\r\n\t\t\tt_copy = [Ibox[i].copy(), next_Ibox[i].copy(),\r\n\t\t\t np.expand_dims(dynamics_mask[i], 3), np.expand_dims(next_dynamics_mask[i], 3)]\r\n\t\t\tt_copy = np.concatenate(t_copy, axis=3)\r\n\r\n\t\t\t# t_copy: [each_batch_num, old_b_width, b_height, channel * 2 + 2]\r\n\r\n\t\t\tbox_num = Ibox[i].shape[0]\r\n\t\t\tbox_num_list.append(box_num)\r\n\r\n\t\t\t# ---------------------\r\n\r\n\t\t\tt_index = collections.defaultdict(list)\r\n\t\t\tpre_index = collections.defaultdict(int)\r\n\t\t\tchoose_index = collections.defaultdict(list)\r\n\r\n\t\t\tfor j in range(box_num):\r\n\t\t\t\trandom_flag = True\r\n\t\t\t\tkey_1 = bbox_coor[i][j, 1] - bbox_coor[i][j, 0]\r\n\t\t\t\tt_index[key_1].append(j)\r\n\t\t\t\tif (j + 1 < box_num):\r\n\t\t\t\t\tkey_2 = bbox_coor[i][j + 1, 1] - bbox_coor[i][j + 1, 0]\r\n\t\t\t\t\tif (key_1 == key_2):\r\n\t\t\t\t\t\trandom_flag = False\r\n\t\t\t\tif (random_flag):\r\n\t\t\t\t\tindex_start = pre_index[key_1]\r\n\t\t\t\t\tindex_end = len(t_index[key_1])\r\n\t\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\t\tnp.random.shuffle(t_index[key_1][index_start: index_end])\r\n\t\t\t\t\tif (index_start + 1 < index_end):\r\n\t\t\t\t\t\tchoose_index[key_1].extend([x for x in range(index_start, index_end - 1)])\r\n\t\t\t\t\tpre_index[key_1] = index_end\r\n\r\n\t\t\tt_num_scale = len(choose_index)\r\n\t\t\tassert (t_num_scale > 0)\r\n\r\n\t\t\tt_box_type_list = []\r\n\t\t\tfor key in choose_index.keys():\r\n\t\t\t\tt_box_type_list.append(key)\r\n\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\tnp.random.shuffle(choose_index[key])\r\n\r\n\t\t\tt_index_stamp = collections.defaultdict(int)\r\n\r\n\t\t\tfor j in range(self.num_box // 2):\r\n\r\n\t\t\t\t# expected to be t_num_scale (3 or 4) * 3 types and self.num_box to be 24 or 18\r\n\t\t\t\tseed_1 = j % (t_num_scale * 3)\r\n\t\t\t\tseed_2 = seed_1 % t_num_scale\r\n\t\t\t\tseed_3 = seed_1 / t_num_scale\r\n\r\n\t\t\t\tkey = t_box_type_list[seed_2]\r\n\r\n\t\t\t\tt_index_1 = t_index_stamp[key]\r\n\t\t\t\tt_index_2 = choose_index[key][t_index_1]\r\n\t\t\t\tt_index_3 = t_index[key][t_index_2]\r\n\t\t\t\tt_index_4 = t_index[key][t_index_2 + 1]\r\n\r\n\t\t\t\tif (t_index_1 + 1 >= len(choose_index[key])):\r\n\t\t\t\t\tt_index_stamp[key] = 0\r\n\t\t\t\t\tfor k in range(self.shuffle_times):\r\n\t\t\t\t\t\tnp.random.shuffle(choose_index[key])\r\n\t\t\t\t\t'''\r\n\t\t\t\t\tprint('warning!')\r\n\t\t\t\t\tprint('box_assert')\r\n\t\t\t\t\tprint(key)\r\n\t\t\t\t\tprint(choose_index[key])\r\n\t\t\t\t\tprint(box_num)\r\n\t\t\t\t\timsave(self.warning_path + 'I_' + '.jpg', np.transpose(I[i], [1, 0, 2]))\r\n\t\t\t\t\timsave(self.warning_path + 'I_next_' + '.jpg', np.transpose(nextI[i], [1, 0, 2]))\r\n\t\t\t\t\tself.save_to_file(self.warning_path + 'box_assert.txt', str(datetime.datetime.now()))\r\n\t\t\t\t\t'''\r\n\t\t\t\telse:\r\n\t\t\t\t\tt_index_stamp[key] += 1\r\n\r\n\t\t\t\tbox_same_flag = np.all(bbox_coor[i][t_index_3] == bbox_coor[i][t_index_4])\r\n\t\t\t\tinstance_1 = t_copy[t_index_3].copy()\r\n\t\t\t\tinstance_2 = t_copy[t_index_4].copy()\r\n\r\n\t\t\t\tinstance_1 = np.pad(instance_1, [[0, self.pad_b_width], [0, 0], [0, 0]], 'constant')\r\n\r\n\t\t\t\t# instance_1: [old_b_width + pad_b_width, b_height, channel * 2 + 2]\r\n\t\t\t\t# instance_2: [old_b_width, b_height, channel * 2 + 2]\r\n\r\n\t\t\t\t'''\r\n\t\t\t\tif (box_same_flag):\r\n\t\t\t\t\tprint('warning!')\r\n\t\t\t\t\tprint('box_assert')\r\n\t\t\t\t\tprint(key)\r\n\t\t\t\t\tprint(choose_index[key])\r\n\t\t\t\t\tprint(box_num)\r\n\t\t\t\t\timsave(self.warning_path + 'I_' + '.jpg', np.transpose(I[i], [1, 0, 2]))\r\n\t\t\t\t\timsave(self.warning_path + 'I_next_' + '.jpg', np.transpose(nextI[i], [1, 0, 2]))\r\n\t\t\t\t\tself.save_to_file(self.warning_path + 'box_assert.txt', str(datetime.datetime.now()))\r\n\t\t\t\t'''\r\n\r\n\t\t\t\tif (seed_3 == 0 or box_same_flag):\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1, instance_2 * 0.], axis=0))\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1 * 0., instance_2], axis=0))\r\n\t\t\t\telse:\r\n\t\t\t\t\ttmp = instance_2.copy()\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS: self.CHANNELS * 2] = 0.\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS * 2 + 1:] = 0.\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([instance_1, tmp], axis=0))\r\n\r\n\t\t\t\t\ttmp = instance_1.copy()\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS: self.CHANNELS * 2] = 0.\r\n\t\t\t\t\ttmp[:, :, self.CHANNELS * 2 + 1:] = 0.\r\n\t\t\t\t\tt_shuffle.append(np.concatenate([tmp, instance_2], axis=0))\r\n\r\n\t\tt_shuffle = np.array(t_shuffle)\r\n\t\tfor k in range(self.shuffle_times):\r\n\t\t\tnp.random.shuffle(t_shuffle)\r\n\r\n\t\tif (self.mpi_rank == 0 and is_train):\r\n\t\t\tprint('Mean number of box in a batch :', np.mean(box_num_list))\r\n\r\n\t\tres = []\r\n\r\n\t\tfor i in range(t_shuffle.shape[0] // self.CV_BATCH_SIZE):\r\n\t\t\tl = i * self.CV_BATCH_SIZE\r\n\t\t\tr = (i + 1) * self.CV_BATCH_SIZE\r\n\t\t\ttmp = self.CHANNELS * 2\r\n\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\tt_res = self.sess.run(train_list, feed_dict={\r\n\t\t\t\t\tself.input_Ibox: t_shuffle[l: r, :, :, :self.CHANNELS],\r\n\t\t\t\t\tself.input_next_Ibox: t_shuffle[l: r, :, :, self.CHANNELS: tmp],\r\n\t\t\t\t\tself.input_dmask: t_shuffle[l: r, :, :, tmp],\r\n\t\t\t\t\tself.input_next_dmask: t_shuffle[l: r, :, :, tmp + 1],\r\n\t\t\t\t\tself.is_train: is_train\r\n\t\t\t\t})\r\n\r\n\t\t\tres.append(t_res)\r\n\r\n\t\treturn res\r\n\r\n\tdef update(self, I, bgimage, nextI, Ibox, next_Ibox, dynamics_mask, next_dynamics_mask,\r\n\t wmask, next_wmask, bbox_coor,\r\n\t test_obset, test_bgimageset, test_nextobset, test_batch_num,\r\n\t box_get_proposal=None):\r\n\r\n\t\tt_1 = time.time()\r\n\t\tcost = self.train_to_mask1([self.train_total_op, self.Total_loss],\r\n\t\t I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t is_train=True)\r\n\t\tif (self.mpi_rank == 0):\r\n\t\t\tprint('Training mask1:', time.time() - t_1)\r\n\r\n\t\tself.step += 1\r\n\r\n\t\txplot.plot('mask1_cost', np.mean(np.array(cost)[:, 1]))\r\n\r\n\t\tif self.step % self.log_time == 0:\r\n\t\t\twith self.graph.as_default():\r\n\t\t\t\tself.saver.save(self.sess, self.path + 'saved_mask1_networks/', global_step=self.step)\r\n\r\n\t\tif self.step % self.summary_time == 0:\r\n\t\t\tsummary_str = self.train_to_mask1(self.summary_op, I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t\t is_train=True)\r\n\r\n\t\t\tself.train_writer.add_summary(summary_str[0], self.step)\r\n\t\t\tself.train_writer.flush()\r\n\r\n\t\tif self.step % self.test_time == 0:\r\n\r\n\t\t\ttest_Ibox, test_next_Ibox, test_dynamics_mask, test_next_dynamics_mask, test_wmask, test_next_wmask, \\\r\n\t\t\ttest_bbox_coor = [], [], [], [], [], [], []\r\n\r\n\t\t\tfor i in range(test_batch_num):\r\n\t\t\t\tt_Ibox, t_next_Ibox, t_dynamics_mask, t_next_dynamics_mask, t_wmask, t_next_wmask, t_bbox_coor = \\\r\n\t\t\t\t\tbox_get_proposal(test_obset[i], test_nextobset[i], test_bgimageset[i])\r\n\r\n\t\t\t\ttest_Ibox.append(t_Ibox)\r\n\t\t\t\ttest_next_Ibox.append(t_next_Ibox)\r\n\t\t\t\ttest_dynamics_mask.append(t_dynamics_mask)\r\n\t\t\t\ttest_next_dynamics_mask.append(t_next_dynamics_mask)\r\n\t\t\t\ttest_wmask.append(t_wmask)\r\n\t\t\t\ttest_next_wmask.append(t_next_wmask)\r\n\t\t\t\ttest_bbox_coor.append(t_bbox_coor)\r\n\r\n\t\t\ttest_closses = []\r\n\t\t\tfor i in range(test_batch_num):\r\n\t\t\t\ttest_closs = self.train_to_mask1([self.Total_loss],\r\n\t\t\t\t test_obset[i], test_bgimageset[i], test_nextobset[i],\r\n\t\t\t\t test_Ibox[i], test_next_Ibox[i],\r\n\t\t\t\t test_dynamics_mask[i], test_next_dynamics_mask[i],\r\n\t\t\t\t test_wmask[i], test_next_wmask[i], test_bbox_coor[i],\r\n\t\t\t\t is_train=False)\r\n\t\t\t\ttest_closses.append(np.mean(test_closs))\r\n\r\n\t\t\tsummary_str = self.train_to_mask1(self.summary_op,\r\n\t\t\t test_obset[i], test_bgimageset[i], test_nextobset[i],\r\n\t\t\t test_Ibox[i], test_next_Ibox[i],\r\n\t\t\t test_dynamics_mask[i], test_next_dynamics_mask[i],\r\n\t\t\t test_wmask[i], test_next_wmask[i], test_bbox_coor[i],\r\n\t\t\t is_train=False)\r\n\r\n\t\t\tself.test_writer.add_summary(summary_str[0], self.step)\r\n\t\t\tself.test_writer.flush()\r\n\r\n\t\t\ttrain_ccost = self.train_to_mask1([self.Total_loss], I, bgimage, nextI, Ibox, next_Ibox,\r\n\t\t\t dynamics_mask, next_dynamics_mask, wmask, next_wmask, bbox_coor,\r\n\t\t\t is_train=True)\r\n\r\n\t\t\txplot.plot('Train_mask1_C_loss', np.mean(train_ccost))\r\n\r\n\t\t\txplot.plot('Test_mask1_C_loss', np.mean(test_closses))\r\n\r\n\tdef worker_update(self):\r\n\r\n\t\tdef selection_booster():\r\n\r\n\t\t\tdef Receive_numpy(source=0, tag=15):\r\n\t\t\t\tt_data = []\r\n\t\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\t\ttmp_data = utils.Receive_numpy(source=source, tag=tag)\r\n\t\t\t\t\tt_data.append(tmp_data)\r\n\t\t\t\treturn t_data\r\n\r\n\t\t\tis_show = self.comm.recv(source=0, tag=18)\r\n\r\n\t\t\tdata = utils.Receive_numpy(source=0, tag=19)\r\n\t\t\tI, nextI, wmask, next_wmask = data\r\n\r\n\t\t\tdata = Receive_numpy(source=0, tag=15)\r\n\t\t\tbatch_cache = data\r\n\r\n\t\t\tbatch_dynamics_instances_K = defaultlist(list)\r\n\t\t\tshow_instances_cpu_size = []\r\n\t\t\tselection_num_list = []\r\n\r\n\t\t\tfor i in range(self.cpu_batch_size):\r\n\t\t\t\ttmp_Ibox, tmp_Ibox_next, tmp_mask, tmp_mask_next, tmp_bbox, tmp_label = batch_cache[i]\r\n\t\t\t\tt_dynamics_instances = self.box_selector.get_selection(I[i], nextI[i], tmp_Ibox, tmp_Ibox_next,\r\n\t\t\t\t tmp_mask, tmp_mask_next, tmp_bbox, tmp_label)\r\n\t\t\t\tt_dynamics_instances_K, box_selected_num = \\\r\n\t\t\t\t\tself.box_choose_K(t_dynamics_instances, self.dynamic_object_instance_box_maxnum)\r\n\t\t\t\t# (return_label, return_C, return_next_C, return_Ms, return_Md)\r\n\t\t\t\tfor t_stamp_K, item in enumerate(t_dynamics_instances_K):\r\n\t\t\t\t\tbatch_dynamics_instances_K[t_stamp_K].append(item)\r\n\t\t\t\tselection_num_list.append(box_selected_num)\r\n\t\t\t\tif (is_show):\r\n\t\t\t\t\tshow_instances_cpu_size.append(t_dynamics_instances)\r\n\r\n\t\t\tres = []\r\n\t\t\tfor item in batch_dynamics_instances_K:\r\n\t\t\t\tres.append(np.array(item))\r\n\r\n\t\t\tutils.Transmit_numpy(res, mpi_id=0, tag=16)\r\n\t\t\tself.comm.send(selection_num_list, dest=0, tag=17)\r\n\r\n\t\t\tif (is_show):\r\n\t\t\t\tself.show_selection(I, nextI, wmask, next_wmask, batch_cache, show_instances_cpu_size)\r\n\r\n\t\t#self.step += 1\r\n\r\n\t\t# selection booster\r\n\t\tis_running_selection = self.comm.recv(source=0, tag=14)\r\n\r\n\t\tif (self.mpi_rank < self.s_mpi_size):\r\n\r\n\t\t\twhile (is_running_selection):\r\n\t\t\t\tselection_booster()\r\n\t\t\t\tis_running_selection = self.comm.recv(source=0, tag=14)\r\n\r\n", "sub_path": "monsterkong/mask17.py", "file_name": "mask17.py", "file_ext": "py", "file_size_in_byte": 57510, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "tensorflow.Variable", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.identity", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 57, "usage_type": "call"}, {"api_name": "tflib.param", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 66, "usage_type": "call"}, {"api_name": "tflib.param", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 67, "usage_type": "call"}, {"api_name": "tflib.param", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 69, "usage_type": "call"}, {"api_name": "tflib.param", "line_number": 70, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 70, "usage_type": "call"}, {"api_name": "tensorflow.nn.moments", "line_number": 74, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 74, "usage_type": "attribute"}, {"api_name": "tensorflow.python.training.moving_averages.assign_moving_average", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.python.training.moving_averages", "line_number": 78, "usage_type": "name"}, {"api_name": "tensorflow.python.training.moving_averages.assign_moving_average", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.python.training.moving_averages", "line_number": 80, "usage_type": "name"}, {"api_name": "tensorflow.python.training.moving_averages.assign_moving_average", "line_number": 84, "usage_type": "call"}, {"api_name": "tensorflow.python.training.moving_averages", "line_number": 84, "usage_type": "name"}, {"api_name": "tensorflow.python.training.moving_averages.assign_moving_average", "line_number": 86, "usage_type": "call"}, {"api_name": "tensorflow.python.training.moving_averages", "line_number": 86, "usage_type": "name"}, {"api_name": "tensorflow.control_dependencies", "line_number": 89, "usage_type": "call"}, {"api_name": "tensorflow.identity", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.cond", "line_number": 92, "usage_type": "call"}, {"api_name": "tensorflow.nn.batch_normalization", "line_number": 93, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 93, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 96, "usage_type": "call"}, {"api_name": "tensorflow.keras.backend.resize_images", "line_number": 102, "usage_type": "call"}, {"api_name": "tensorflow.keras", "line_number": 102, "usage_type": "attribute"}, {"api_name": "_selector.Selector", "line_number": 185, "usage_type": "call"}, {"api_name": "mpi4py.MPI.COMM_WORLD", "line_number": 195, "usage_type": "attribute"}, {"api_name": "mpi4py.MPI", "line_number": 195, "usage_type": "name"}, {"api_name": "tensorflow.Graph", "line_number": 213, "usage_type": "call"}, {"api_name": "tensorflow.set_random_seed", "line_number": 216, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 219, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 222, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 223, "usage_type": "call"}, {"api_name": "tensorflow.train.Saver", "line_number": 225, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 225, "usage_type": "attribute"}, {"api_name": "tensorflow.train.get_checkpoint_state", "line_number": 228, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 228, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.Exists", "line_number": 239, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 239, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.DeleteRecursively", "line_number": 240, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 240, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.Exists", "line_number": 241, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 241, "usage_type": "attribute"}, {"api_name": "tensorflow.gfile.DeleteRecursively", "line_number": 242, "usage_type": "call"}, {"api_name": "tensorflow.gfile", "line_number": 242, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 243, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 243, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 244, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 244, "usage_type": "attribute"}, {"api_name": "tflib.ops.conv2d.Conv2D", "line_number": 249, "usage_type": "call"}, {"api_name": "tflib.ops", "line_number": 249, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 251, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 251, "usage_type": "attribute"}, {"api_name": "tflib.ops.conv2d.Conv2D", "line_number": 252, "usage_type": "call"}, {"api_name": "tflib.ops", "line_number": 252, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 254, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 254, "usage_type": "attribute"}, {"api_name": "tflib.ops.conv2d.Conv2D", "line_number": 255, "usage_type": "call"}, {"api_name": "tflib.ops", "line_number": 255, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 257, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 257, "usage_type": "attribute"}, {"api_name": "tensorflow.concat", "line_number": 259, "usage_type": "call"}, {"api_name": "tflib.ops.conv2d.Conv2D", "line_number": 261, "usage_type": "call"}, {"api_name": "tflib.ops", "line_number": 261, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.relu", "line_number": 263, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 263, "usage_type": "attribute"}, {"api_name": "tflib.ops.conv2d.Conv2D", "line_number": 264, "usage_type": "call"}, {"api_name": "tflib.ops", "line_number": 264, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 276, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 282, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax", "line_number": 284, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 284, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 286, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 287, "usage_type": "call"}, {"api_name": "tensorflow.log", "line_number": 287, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 287, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 295, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 296, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 298, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 298, "usage_type": "call"}, {"api_name": "tensorflow.range", "line_number": 298, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 299, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 299, "usage_type": "call"}, {"api_name": "tensorflow.range", "line_number": 299, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 301, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 301, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 301, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_sum", "line_number": 302, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 302, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 302, "usage_type": "attribute"}, {"api_name": "tensorflow.stack", "line_number": 304, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 312, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 314, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.range", "line_number": 317, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 319, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 319, "usage_type": "call"}, {"api_name": "tensorflow.range", "line_number": 319, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 321, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 321, "usage_type": "call"}, {"api_name": "tensorflow.range", "line_number": 321, "usage_type": "call"}, {"api_name": "tensorflow.stack", "line_number": 326, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 328, "usage_type": "call"}, {"api_name": "tensorflow.gather_nd", "line_number": 329, "usage_type": "call"}, {"api_name": "tensorflow.stack", "line_number": 331, "usage_type": "call"}, {"api_name": "tensorflow.gather_nd", "line_number": 332, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 334, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 346, "usage_type": "call"}, {"api_name": "tensorflow.floor", "line_number": 346, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 348, "usage_type": "call"}, {"api_name": "tensorflow.floor", "line_number": 348, "usage_type": "call"}, {"api_name": "tensorflow.zeros", "line_number": 351, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 352, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 353, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 355, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 356, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 357, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 358, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 360, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 361, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 362, "usage_type": "call"}, {"api_name": "tensorflow.clip_by_value", "line_number": 363, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 365, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 366, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 367, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 368, "usage_type": "call"}, {"api_name": "tensorflow.add_n", "line_number": 378, "usage_type": "call"}, {"api_name": "tensorflow.add_n", "line_number": 379, "usage_type": "call"}, {"api_name": "tensorflow.stop_gradient", "line_number": 391, "usage_type": "call"}, {"api_name": "tensorflow.maximum", "line_number": 393, "usage_type": "call"}, {"api_name": "tensorflow.sigmoid", "line_number": 395, "usage_type": "call"}, {"api_name": "tensorflow.sigmoid", "line_number": 396, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 398, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 398, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 398, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 401, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 401, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 401, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 406, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 406, "usage_type": "call"}, {"api_name": "tensorflow.tile", "line_number": 407, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 407, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 411, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 412, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 414, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 415, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 431, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 433, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 435, "usage_type": "call"}, {"api_name": "tensorflow.pad", "line_number": 437, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 450, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 451, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 480, "usage_type": "call"}, {"api_name": "tensorflow.constant", "line_number": 482, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 484, "usage_type": "call"}, {"api_name": "tensorflow.nn.convolution", "line_number": 489, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 489, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 491, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 511, "usage_type": "call"}, {"api_name": "tensorflow.minimum", "line_number": 511, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 513, "usage_type": "call"}, {"api_name": "tensorflow.reduce_sum", "line_number": 528, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 544, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 545, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 547, "usage_type": "call"}, {"api_name": "tensorflow.transpose", "line_number": 548, "usage_type": "call"}, {"api_name": "tensorflow.concat", "line_number": 554, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 575, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 606, "usage_type": "call"}, {"api_name": "tensorflow.bool", "line_number": 606, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 607, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 607, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 609, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 609, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 611, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 611, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 612, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 612, "usage_type": "attribute"}, {"api_name": "tensorflow.device", "line_number": 616, "usage_type": "call"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 618, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 618, "usage_type": "attribute"}, {"api_name": "tensorflow.variable_scope", "line_number": 629, "usage_type": "call"}, {"api_name": "tensorflow.get_variable_scope", "line_number": 629, "usage_type": "call"}, {"api_name": "tensorflow.device", "line_number": 634, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 635, "usage_type": "call"}, {"api_name": "tensorflow.get_variable_scope", "line_number": 642, "usage_type": "call"}, {"api_name": "utils.average_gradients", "line_number": 651, "usage_type": "call"}, {"api_name": "utils.reduce_mean_tf_data_flow", "line_number": 655, "usage_type": "call"}, {"api_name": "utils.concat_tf_data_flow", "line_number": 656, "usage_type": "call"}, {"api_name": "utils.concat_tf_data_flow", "line_number": 657, "usage_type": "call"}, {"api_name": "tensorflow.summary.scalar", "line_number": 666, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 666, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 667, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 667, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 668, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 668, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.scalar", "line_number": 669, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 669, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.image", "line_number": 671, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 671, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 671, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 672, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 672, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 672, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 673, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 673, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 673, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 674, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 674, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 674, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 675, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 675, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 675, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 675, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 676, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 676, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 676, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 676, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 679, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 680, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 680, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.image", "line_number": 681, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 681, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 681, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 681, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 681, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 683, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 684, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 684, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.image", "line_number": 685, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 685, "usage_type": "attribute"}, {"api_name": "tensorflow.cast", "line_number": 686, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 686, "usage_type": "attribute"}, {"api_name": "tensorflow.transpose", "line_number": 686, "usage_type": "call"}, {"api_name": "tensorflow.expand_dims", "line_number": 688, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 689, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 689, "usage_type": "attribute"}, {"api_name": "tensorflow.expand_dims", "line_number": 691, "usage_type": "call"}, {"api_name": "tensorflow.summary.image", "line_number": 692, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 692, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.merge_all", "line_number": 694, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 694, "usage_type": "attribute"}, {"api_name": "numpy.pad", "line_number": 704, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 715, "usage_type": "call"}, {"api_name": "time.time", "line_number": 723, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 731, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 732, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 736, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 739, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 746, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 748, "usage_type": "call"}, {"api_name": "defaultlist.defaultlist", "line_number": 755, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 780, "usage_type": "call"}, {"api_name": "time.time", "line_number": 787, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 840, "usage_type": "call"}, {"api_name": "os.path", "line_number": 840, "usage_type": "attribute"}, {"api_name": "shutil.rmtree", "line_number": 842, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 843, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 875, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 875, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 876, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 876, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 877, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 877, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 878, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 878, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 879, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 879, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 881, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 882, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 883, "usage_type": "call"}, {"api_name": "numpy.savetxt", "line_number": 884, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 887, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 887, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 889, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 889, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 890, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 890, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 892, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 892, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 893, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 893, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 900, "usage_type": "call"}, {"api_name": "scipy.misc.imsave", "line_number": 901, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 902, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 903, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 904, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 905, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 906, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 907, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 908, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 909, "usage_type": "call"}, {"api_name": "utils.Transmit_numpy", "line_number": 922, "usage_type": "call"}, {"api_name": "time.time", "line_number": 928, "usage_type": "call"}, {"api_name": "utils.Transmit_normal", "line_number": 931, "usage_type": "call"}, {"api_name": "utils.Transmit_normal", "line_number": 934, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 965, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 967, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 969, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 969, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 969, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 972, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 972, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 972, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 975, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 975, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 975, "usage_type": "call"}, {"api_name": "numpy.tile", "line_number": 977, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 977, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 982, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 983, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 984, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 985, "usage_type": "call"}, {"api_name": "utils.Transmit_numpy", "line_number": 1014, "usage_type": "call"}, {"api_name": "defaultlist.defaultlist", "line_number": 1027, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1045, "usage_type": "call"}, {"api_name": "utils.Receive_numpy", "line_number": 1049, "usage_type": "call"}, {"api_name": "utils.concat_np_data_list_flow", "line_number": 1055, "usage_type": "call"}, {"api_name": "time.time", "line_number": 1058, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1059, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1060, "usage_type": "call"}, {"api_name": "xplot.plot", "line_number": 1061, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1061, "usage_type": "call"}, {"api_name": "xplot.plot", "line_number": 1062, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1062, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 1123, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1124, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1133, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1134, "usage_type": "call"}, {"api_name": "collections.defaultdict", "line_number": 1135, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 1149, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 1149, "usage_type": "attribute"}, {"api_name": "numpy.random.shuffle", "line_number": 1161, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 1161, "usage_type": "attribute"}, {"api_name": "collections.defaultdict", "line_number": 1163, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 1182, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 1182, "usage_type": "attribute"}, {"api_name": "numpy.all", "line_number": 1196, "usage_type": "call"}, {"api_name": "numpy.pad", "line_number": 1200, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1218, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1219, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1224, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1229, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1231, "usage_type": "call"}, {"api_name": "numpy.random.shuffle", "line_number": 1233, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 1233, "usage_type": "attribute"}, {"api_name": "numpy.mean", "line_number": 1236, "usage_type": "call"}, {"api_name": "time.time", "line_number": 1263, "usage_type": "call"}, {"api_name": "time.time", "line_number": 1269, "usage_type": "call"}, {"api_name": "xplot.plot", "line_number": 1273, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1273, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1273, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1312, "usage_type": "call"}, {"api_name": "xplot.plot", "line_number": 1328, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1328, "usage_type": "call"}, {"api_name": "xplot.plot", "line_number": 1330, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 1330, "usage_type": "call"}, {"api_name": "utils.Receive_numpy", "line_number": 1339, "usage_type": "call"}, {"api_name": "utils.Receive_numpy", "line_number": 1345, "usage_type": "call"}, {"api_name": "defaultlist.defaultlist", "line_number": 1351, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1370, "usage_type": "call"}, {"api_name": "utils.Transmit_numpy", "line_number": 1372, "usage_type": "call"}]}
+{"seq_id": "467778819", "text": "\n# coding: utf-8\n\n# In[1]:\n\nfrom mongoengine.context_managers import switch_collection\nfrom mongoengine import connect\nfrom mongoengine.errors import ValidationError\n\n\n# In[2]:\n\npdb\n\n\n# In[3]:\n\nfrom flpd_helper.documents import resolution_mapping\n\n\n# In[4]:\n\nfrom flpd_helper import (\n DB_NAME,\n get_names,\n documents,\n main_collections,\n)\n\n\n# In[5]:\n\nfrom flpd_helper.documents import Accident, Citation\n\n\n# In[6]:\n\n(\n main_collection_names, \n validated_collection_names, \n mapped_collection_names,\n) = get_names()\n\n\n# In[7]:\n\nclient = connect(DB_NAME)\ndatabase = client.get_database(DB_NAME)\n\n\n# In[8]:\n\ndestination_collections = tuple(\n database.get_collection(name)\n for name in mapped_collection_names\n)\nsource_collections = tuple(\n database.get_collection(name)\n for name in validated_collection_names\n)\nassert all([len(collection) == 2 \n for collection \n in (destination_collections, source_collections)])\n\n\n# In[9]:\n\n# clear collections\nfor collection in destination_collections:\n collection.delete_many({})\n\n\n# In[10]:\n\nmixed_type_keys = (\n (\n 'district_code',\n 'report_area_description',\n 'zone_code',\n 'geoy',\n 'geox',\n 'time_reported',\n 'road_type_code',\n ),\n (\n 'geoy',\n 'geox',\n 'street_number',\n 'zone_code',\n 'reporting_area_desc',\n 'district_code',\n 'age',\n ),\n)\n# using a comprehension to create the mapping means only having to add values \n# to collections in mixed_type_keys\n# as validation errors are thrown during the call to save on mongoengine.Document subclass instances\nfalse_value_updates = tuple(dict(zip(keys, (None, ) * len(keys)))\n for keys in mixed_type_keys)\n\n\n# In[11]:\n\ndestination_documents = (Accident, Citation)\n\n\n# In[12]:\n\niter_items = zip(\n source_collections,\n destination_collections,\n destination_documents,\n documents.safe_keys,\n false_value_updates\n)\nfor item in iter_items:\n (\n validated_collection,\n destination_collection,\n destination_document,\n document_safe_keys,\n false_value_update\n ) = item\n for src_document in validated_collection.find({}):\n # update keys on src_document\n _src_document = dict([\n (new_key, src_document[old_key])\n for old_key, new_key \n in document_safe_keys\n ])\n # cast, for example, int to string if str is expected yet value is an int\n for old_key, new_key in document_safe_keys:\n type_recaster = resolution_mapping[validated_collection.name][old_key] if old_key in resolution_mapping[validated_collection.name] else lambda x: x\n try:\n _src_document[new_key] = type_recaster(_src_document[new_key])\n except TypeError:\n # because a custom type recaster returns a function\n # to match the api for instantiating mongoengine.Field classes\n _src_document[new_key] = type_recaster()(_src_document[new_key]) \n except ValueError as e:\n try:\n assert false_value_update.get(new_key, None) is None\n except AssertionError as e:\n print(AssertionError(e))\n print(new_key, old_key)\n print(\"Add a key to `mixed_type_keys`.\")\n for old_key, new_key in document_safe_keys:\n new_key_value = _src_document[new_key]\n if all((\n new_key in false_value_update,\n all((\n not new_key_value, \n new_key_value != 0, \n new_key_value != '0', \n )),\n )):\n _src_document[new_key] = false_value_update[new_key]\n with switch_collection(\n destination_document, \n destination_collection.name\n ) as Document:\n new_document = Document(**_src_document)\n try:\n new_document.save()\n except ValidationError as e:\n print(ValidationError(e))\n import pdb\n pdb.set_trace()\n\n\n# In[13]:\n\n# 4 to 6 of main_collections are valid_* collections\nfor item in destination_collections + tuple(main_collections[4:6]):\n print(': '.join((item.name, str(item.count()))))\nassert all([validated.count() == mapped.count() for validated, mapped \n in zip(source_collections, destination_collections)])\n\n", "sub_path": "notebooks/unify_data_types_in_validated_collections.py", "file_name": "unify_data_types_in_validated_collections.py", "file_ext": "py", "file_size_in_byte": 4647, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flpd_helper.get_names", "line_number": 42, "usage_type": "call"}, {"api_name": "mongoengine.connect", "line_number": 47, "usage_type": "call"}, {"api_name": "flpd_helper.DB_NAME", "line_number": 47, "usage_type": "argument"}, {"api_name": "flpd_helper.DB_NAME", "line_number": 48, "usage_type": "argument"}, {"api_name": "flpd_helper.documents.Accident", "line_number": 104, "usage_type": "name"}, {"api_name": "flpd_helper.documents.Citation", "line_number": 104, "usage_type": "name"}, {"api_name": "flpd_helper.documents.safe_keys", "line_number": 113, "usage_type": "attribute"}, {"api_name": "flpd_helper.documents", "line_number": 113, "usage_type": "name"}, {"api_name": "flpd_helper.documents.resolution_mapping", "line_number": 133, "usage_type": "name"}, {"api_name": "mongoengine.context_managers.switch_collection", "line_number": 158, "usage_type": "call"}, {"api_name": "mongoengine.errors.ValidationError", "line_number": 165, "usage_type": "name"}, {"api_name": "mongoengine.errors.ValidationError", "line_number": 166, "usage_type": "call"}, {"api_name": "pdb.set_trace", "line_number": 168, "usage_type": "call"}, {"api_name": "flpd_helper.main_collections", "line_number": 174, "usage_type": "name"}]}
+{"seq_id": "235950387", "text": "# coding:utf-8\n\nfrom flask.views import View\nfrom flask import request, make_response, current_app\nfrom werkzeug.wrappers import Response as ResponseBase\nfrom validater import validate\nfrom validater import ProxyDict\nfrom . import ResourceException, abort, exporters\n\n\nclass Resource(View):\n\n \"\"\"Resource代表一个资源\n\n - schema_inputs is a dict of scheams for validate inputs.\n it's key is method name\n - schema_outputs is a dict of scheams for validate outputs.\n it's key is method name\n - output_types is a list of custom type of outputs\n , the custom type object will be proxy by validater.ProxyDict\n - before_request_funcs is a list of functions\n - after_request_funcs is a list of functions\n - handle_error_func is a functions\n \"\"\"\n\n schema_inputs = {}\n schema_outputs = {}\n output_types = []\n before_request_funcs = []\n after_request_funcs = []\n handle_error_func = None\n\n @classmethod\n def _before_request(cls):\n \"\"\"before_request\"\"\"\n for fn in cls.before_request_funcs:\n rv = fn()\n if rv is not None:\n return rv\n return None\n\n @classmethod\n def _after_request(cls, rv, code, headers):\n for fn in cls.after_request_funcs:\n rv, code, headers = fn(rv, code, headers)\n return rv, code, headers\n\n @classmethod\n def _handle_error(cls, ex):\n if cls.handle_error_func:\n rv = cls.handle_error_func(ex)\n if rv is not None:\n return rv\n if isinstance(ex, ResourceException):\n if ex.code >= 500 and not current_app.debug:\n return {\"error\": \"interal server error\"}, ex.code\n else:\n return ex.error, ex.code\n else:\n raise ex\n\n @classmethod\n def after_request(cls, f):\n \"\"\"decorater\"\"\"\n cls.after_request_funcs.append(f)\n return f\n\n @classmethod\n def before_request(cls, f):\n \"\"\"decorater\"\"\"\n cls.before_request_funcs.append(f)\n return f\n\n @classmethod\n def error_handler(cls, f):\n \"\"\"decorater\"\"\"\n cls.handle_error_func = f\n return f\n\n def dispatch_request(self, *args, **kwargs):\n \"\"\"preproccess request and dispatch request\n \"\"\"\n act = request.endpoint.split('@')\n if len(act) > 1:\n meth_name = request.method.lower() + \"_\" + act[1]\n else:\n meth_name = request.method.lower()\n if not hasattr(self, meth_name) and request.method == 'HEAD':\n meth_name = \"get\"\n request.resource = self.__class__.__name__\n request.action = meth_name\n try:\n # before_request\n rv = self._before_request()\n if rv is None:\n rv = self.full_dispatch_request(*args, **kwargs)\n except Exception as ex:\n rv = self._handle_error(ex)\n rv, code, headers = unpack(rv)\n rv, code, headers = self._after_request(rv, code, headers)\n if rv is None:\n return make_response(\"\", code, headers)\n elif isinstance(rv, (ResponseBase, basestring)):\n return make_response(rv, code, headers)\n else:\n mediatype = request.accept_mimetypes.best_match(\n exporters.keys(), default='application/json')\n export = exporters[mediatype]\n return export(rv, code, headers)\n\n def full_dispatch_request(self, *args, **kwargs):\n \"\"\"actual dispatch request, validate inputs and outputs\n \"\"\"\n fn = getattr(self, request.action, None)\n if fn is None:\n abort(404, 'Unimplemented action %r' % fn.name)\n inputs = self.__class__.schema_inputs.get(request.action)\n outputs = self.__class__.schema_outputs.get(request.action)\n output_types = self.__class__.output_types\n method = request.method.lower()\n if inputs is not None:\n if method in [\"get\", \"delete\"]:\n data = request.args.copy()\n elif method in [\"post\", \"put\"]:\n if request.headers[\"Content-Type\"] == 'application/json':\n try:\n data = request.get_json()\n except:\n abort(400, \"Invalid json content\")\n else:\n data = request.form.copy()\n else:\n data = {}\n (errors, values) = validate(data, inputs)\n if errors:\n abort(400, dict(errors))\n else:\n rv = fn(**values)\n else:\n rv = fn()\n if outputs is not None:\n if output_types and isinstance(rv, tuple(output_types)):\n (errors, values) = validate(ProxyDict(rv, output_types), outputs)\n else:\n (errors, values) = validate(rv, outputs)\n if errors:\n abort(500, dict(errors))\n else:\n rv = values\n return rv\n\n\ndef unpack(rv):\n \"\"\"convert rv to tuple(data, code, headers)\n\n :param rv: data or tuple that contain code and headers\n \"\"\"\n status = headers = None\n if isinstance(rv, tuple):\n rv, status, headers = rv + (None,) * (3 - len(rv))\n if isinstance(status, (dict, list)):\n headers, status = status, None\n return (rv, status, headers)\n", "sub_path": "flask_restaction/resource.py", "file_name": "resource.py", "file_ext": "py", "file_size_in_byte": 5404, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.views.View", "line_number": 11, "usage_type": "name"}, {"api_name": "flask.current_app.debug", "line_number": 55, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 55, "usage_type": "name"}, {"api_name": "flask.request.endpoint.split", "line_number": 83, "usage_type": "call"}, {"api_name": "flask.request.endpoint", "line_number": 83, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 83, "usage_type": "name"}, {"api_name": "flask.request.method.lower", "line_number": 85, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 85, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 85, "usage_type": "name"}, {"api_name": "flask.request.method.lower", "line_number": 87, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 87, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 87, "usage_type": "name"}, {"api_name": "flask.request.method", "line_number": 88, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 88, "usage_type": "name"}, {"api_name": "flask.request.resource", "line_number": 90, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 90, "usage_type": "name"}, {"api_name": "flask.request.action", "line_number": 91, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 91, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 102, "usage_type": "call"}, {"api_name": "werkzeug.wrappers.Response", "line_number": 103, "usage_type": "name"}, {"api_name": "flask.make_response", "line_number": 104, "usage_type": "call"}, {"api_name": "flask.request.accept_mimetypes.best_match", "line_number": 106, "usage_type": "call"}, {"api_name": "flask.request.accept_mimetypes", "line_number": 106, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 106, "usage_type": "name"}, {"api_name": "flask.request.action", "line_number": 114, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 114, "usage_type": "name"}, {"api_name": "flask.request.action", "line_number": 117, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 117, "usage_type": "name"}, {"api_name": "flask.request.action", "line_number": 118, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 118, "usage_type": "name"}, {"api_name": "flask.request.method.lower", "line_number": 120, "usage_type": "call"}, {"api_name": "flask.request.method", "line_number": 120, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 120, "usage_type": "name"}, {"api_name": "flask.request.args.copy", "line_number": 123, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 123, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 123, "usage_type": "name"}, {"api_name": "flask.request.headers", "line_number": 125, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 125, "usage_type": "name"}, {"api_name": "flask.request.get_json", "line_number": 127, "usage_type": "call"}, {"api_name": "flask.request", "line_number": 127, "usage_type": "name"}, {"api_name": "flask.request.form.copy", "line_number": 131, "usage_type": "call"}, {"api_name": "flask.request.form", "line_number": 131, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 131, "usage_type": "name"}, {"api_name": "validater.validate", "line_number": 134, "usage_type": "call"}, {"api_name": "validater.validate", "line_number": 143, "usage_type": "call"}, {"api_name": "validater.ProxyDict", "line_number": 143, "usage_type": "call"}, {"api_name": "validater.validate", "line_number": 145, "usage_type": "call"}]}
+{"seq_id": "402079586", "text": "# Python 2 / 3 compatibility\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport os.path\nimport re\n\n\n# Constants from rrdbotd and rrdbot-create.\nDEFAULT_CONFIG_DIR = \"/etc/rrdbot\"\n\nCONFIG_GENERAL = b\"general\"\nCONFIG_RAW = b\"raw\"\nCONFIG_POLL = b\"poll\"\nCONFIG_INTERVAL = b\"interval\"\nCONFIG_TIMEOUT = b\"timeout\"\nCONFIG_SOURCE = b\"source\"\nCONFIG_REFERENCE = b\"reference\"\nCONFIG_CREATE = b\"create\"\nCONFIG_CF = b\"cf\"\nCONFIG_ARCHIVE = b\"archive\"\nCONFIG_TYPE = b\"type\"\nCONFIG_MIN = b\"min\"\nCONFIG_MAX = b\"max\"\n\nVAL_UNKNOWN = b\"U\"\nVAL_ABSOLUTE = b\"ABSOLUTE\"\nVAL_GAUGE = b\"GAUGE\"\nVAL_COUNTER = b\"COUNTER\"\nVAL_DERIVE = b\"DERIVE\"\n\n\nclass ConfigurationError(Exception):\n pass\n\n\nclass RRDBotConfigItem(object):\n # pylint: disable=too-few-public-methods\n\n __slots__ = (\"name\", \"source\", \"reference\", \"type\", \"min\", \"max\")\n\n def __init__(self, name, source):\n self.name = name\n self.source = source\n self.reference = None\n self.type = VAL_ABSOLUTE\n self.min = VAL_UNKNOWN\n self.max = VAL_UNKNOWN\n\n @property\n def key(self):\n return (self.source, self.reference)\n\n\nclass RRDBotConfigFile(object):\n # pylint: disable=too-few-public-methods\n\n __slots__ = (\"filepath\", \"raw_file_templates\", \"items\")\n\n def __init__(self, filepath):\n self.filepath = filepath\n self.raw_file_templates = set()\n self.items = {}\n\n\n# See rrdbot/common/config-parser.c cfg_parse_dir, parse_dir_internal\ndef cfg_parse_dir(rrdbot_conf_dir):\n configs = []\n\n logger = logging.getLogger()\n logger.debug(\"Searching %s for configuration files\", rrdbot_conf_dir)\n for directory, dummy_subdirectories, files in os.walk(rrdbot_conf_dir):\n logger.debug(\"Searching directory %s\", directory)\n for filename in files:\n filepath = os.path.join(directory, filename)\n logger.debug(\"Reading %s\", filepath)\n config = RRDBotConfigFile(filepath)\n try:\n with open(filepath, \"rb\") as config_file:\n cfg_parse_file(config_file, config)\n configs.append(config)\n except EnvironmentError as ex:\n logger.warning(\n \"Failed to read config file %s : %s\", filepath, ex\n )\n except ConfigurationError as ex:\n logger.warning(\"%s\", ex)\n else:\n logger.debug(\" Raw file templates:\")\n for raw_file_template in sorted(config.raw_file_templates):\n logger.debug(\" %s\", raw_file_template)\n logger.debug(\" Items:\")\n for field in sorted(config.items.keys()):\n item = config.items[field]\n if item.reference is None:\n continue\n logger.debug(\n \" %s type=%s min=%s max=%s\",\n item.reference, item.type, item.min, item.max\n )\n\n return configs\n\n\n# See rrdbot/common/config-parser.c cfg_parse_file\ndef cfg_parse_file(config_file, config):\n header = name = value = None\n\n for index, line in enumerate(config_file):\n line = line.rstrip()\n\n # Continuation line (had spaces at start)\n if line and line[:1].isspace():\n if not value:\n raise ConfigurationError(\n \"Invalid continuation in config %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n\n # Continuations are separated by spaces\n # NB: config-parser.c does not handle this properly\n value += b\" \" + line.lstrip()\n continue\n\n # No continuation hand off value if necessary\n if name and value:\n config_value(header, name, value, config)\n\n name = value = None\n\n # Empty lines / comments at start / comments without continuation\n if not line or line.startswith(b\"#\"):\n continue\n\n # A header\n if line.startswith(b\"[\"):\n index = line.find(b\"]\", 1)\n if index == -1 or index == 1:\n raise ConfigurationError(\n \"Invalid config header %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n header = line[1:index].strip()\n continue\n\n # Look for the break between name = value on the same line\n match = re.search(b\"[:=]\", line)\n if match is None:\n raise ConfigurationError(\n \"Invalid config line %s:%d : %s\" % \\\n (index+1, config_file.name, line)\n )\n name = line[:match.start()].strip()\n value = line[match.end():].strip()\n\n if name and value:\n config_value(header, name, value, config)\n\n\n# See rrdbot/daemon/config.c cfg_value, config_value\n# tools/rrdbot-create.c cfg_value\ndef config_value(header, name, value, config):\n # pylint: disable=too-many-return-statements,too-many-branches\n\n logger = logging.getLogger()\n\n if header == CONFIG_GENERAL:\n if name == CONFIG_RAW:\n config.raw_file_templates.add(value.decode(\"latin-1\"))\n\n elif header == CONFIG_POLL:\n if name == CONFIG_INTERVAL:\n return\n\n if name == CONFIG_TIMEOUT:\n return\n\n # Parse out suffix\n if b\".\" not in name:\n return\n\n name, suffix = name.split(b\".\", 1)\n\n # If it starts with \"field.reference\"\n if suffix == CONFIG_SOURCE:\n # Parse out the field\n parse_item(name, value, config)\n\n # If it starts with \"field.reference\"\n if suffix == CONFIG_REFERENCE:\n # Parse out the field\n parse_item_reference(name, value, config)\n\n\n elif header == CONFIG_CREATE:\n if name == CONFIG_CF:\n return\n\n if name == CONFIG_ARCHIVE:\n return\n\n # Try and see if the field has a suffix\n if b\".\" not in name:\n return # Ignore unknown options\n\n name, suffix = name.split(b\".\", 1)\n\n if name not in config.items:\n logger.warning(\"%s: Field %s not found\", config.filepath, name)\n return\n\n if suffix == CONFIG_TYPE:\n value = value.upper()\n if value in [VAL_ABSOLUTE, VAL_COUNTER, VAL_GAUGE, VAL_DERIVE]:\n config.items[name].type = value\n else:\n logger.warning(\n \"%s: Invalid field type: %s\", config.filepath, value\n )\n return\n\n elif suffix == CONFIG_MIN:\n value = value.upper()\n if value != VAL_UNKNOWN:\n try:\n value = int(value)\n except ValueError:\n logger.warning(\n \"%s: Invalid field min: %s\", config.filepath, value\n )\n return\n config.items[name].min = value\n\n elif suffix == CONFIG_MAX:\n value = value.upper()\n if value != VAL_UNKNOWN:\n try:\n value = int(value)\n except ValueError:\n logger.warning(\n \"%s: Invalid field max: %s\", config.filepath, value\n )\n return\n config.items[name].max = value\n\n # Ignore unknown options\n\n\n# See rrdbot/daemon/config.c parse_item\ndef parse_item(field, uri, config):\n # Don't parse URI, we can't do it completely from here anyway\n if field not in config.items:\n config.items[field] = RRDBotConfigItem(field, uri)\n\n\n# See rrdbot/daemon/config.c parse_item_reference\ndef parse_item_reference(field, reference, config):\n if field not in config.items:\n logger = logging.getLogger()\n logger.warning(\"%s: Field %s not found\", config.filepath, field)\n else:\n config.items[field].reference = reference\n", "sub_path": "rrdbot/config.py", "file_name": "config.py", "file_ext": "py", "file_size_in_byte": 8088, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 73, "usage_type": "call"}, {"api_name": "os.path.walk", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "name"}, {"api_name": "os.path.path.join", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 78, "usage_type": "name"}, {"api_name": "re.search", "line_number": 150, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 168, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 262, "usage_type": "call"}]}
+{"seq_id": "429662345", "text": "import numpy as np\nfrom scipy.spatial.distance import cosine, hamming\nfrom scipy.stats import pearsonr\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef cosine_sim_closest(X, x_query, n=1):\n lim = n + 1\n sim = cosine_similarity(X, x_query.reshape(1, -1)).ravel()\n ind = np.argpartition(sim, -lim)[-lim:]\n ind = ind[np.argsort(sim[ind])]\n return ind[:-1], sim[ind[:-1]]\n\n\ndef cosine_sim_top(X, x_query, tol=0.95):\n sim = cosine_similarity(X, x_query.reshape(1, -1)).ravel()\n lim = sum(sim > tol)\n ind = np.argpartition(sim, -lim)[-lim:]\n ind = ind[np.argsort(sim[ind])]\n return ind[:-1], sim[ind[:-1]]\n\n\ndef inv_cosine(xi, xj):\n dij = cosine(xi, xj)\n val = 1.0 / dij\n return val\n\n\ndef inv_hamming(xi, xj):\n dij = hamming(xi, xj)\n val = 1.0 / dij\n return val\n\n\ndef pearson(xi, xj):\n return pearsonr(xi, xj)[0]\n\n\ndef inv_pearson(xi, xj):\n return 1.0 / pearson(xi, xj)\n\n\ndef diversity(plist, dist_f, norm_f):\n \"\"\" diversity of a playlist\n\n Common choices for dist_f are inverse cosine similarity, inverse\n Pearson correlation, or Hamming distance\n \"\"\"\n n = len(plist)\n sum_d = np.sum([dist_f(plist[i], plist[j])\n for i in range(n) for j in range(i + 1, n)])\n\n p_norm = norm_f(plist)\n val = sum_d / (p_norm * (p_norm - 1))\n\n return val\n\n\ndef dcg_from_ranking(y_true, ranking):\n \"\"\"Discounted cumulative gain (DCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n DCG @k : float\n \"\"\"\n y_true = np.asarray(y_true)\n ranking = np.asarray(ranking)\n rel = y_true[ranking]\n gains = 2 ** rel - 1\n discounts = np.log2(np.arange(len(ranking)) + 2)\n return np.sum(gains / discounts)\n\ndef NDCG_1(y_true, ranking):\n \"\"\"Normalized discounted cumulative gain (NDCG) at rank k\n Parameters\n ----------\n y_true : array-like, shape = [n_samples]\n Ground truth (true relevance labels).\n ranking : array-like, shape = [k]\n Document indices, i.e.,\n ranking[0] is the index of top-ranked document,\n ranking[1] is the index of second-ranked document,\n ...\n k : int\n Rank.\n Returns\n -------\n NDCG @k : float\n \"\"\"\n y_true = np.array(y_true)\n ranking = np.array(ranking)\n k = len(ranking)\n best_ranking = np.argsort(y_true)[::-1]\n best = dcg_from_ranking(y_true, best_ranking)\n return dcg_from_ranking(y_true, ranking) / best\n\n\ndef IDCG(true, pred):\n n_common = len(set(true).intersection(set(pred)))\n return 1 + np.sum([1.0 / np.log2(i) for i in range(2, n_common + 1)])\n\ndef DCG(true, pred):\n\n relevant = set(true).intersection(set(pred))\n n_common = len(set(true).intersection(set(pred)))\n if n_common == 0:\n return 0.0\n else:\n ranks = [i for i,p in enumerate(pred) if p in relevant]\n score = 0.0\n for order, rank in enumerate(ranks):\n score += float(rank)/float(len(pred)) / np.log2((order + 2))\n return score\n\n\ndef NDCG(true, pred):\n return DCG(true, pred) / IDCG(true, pred)\n\n\ndef recall(true, pred):\n \"\"\"\n pred: a single prediction playlist\n true: ground truth\n\n \"\"\"\n return len(set(true).intersection(set(pred))) / float(len(set(true)))\n\n\ndef recommended_song_click(true, pred):\n \"\"\"\n pred: list of predictions\n true: ground truth\n \"\"\"\n cnt = 1\n for predictions in pred:\n if true in predictions:\n break\n else:\n cnt += 1\n\n return cnt / 10 * 1.0\n\ndef r_precision(true, pred):\n \"\"\"\n pred: a single, ranked prediction playlist\n true: ground truth\n \"\"\"\n gt_length = len(true)\n top_preds = pred[:gt_length]\n return len(set(true).intersection(set(top_preds))) / float(len(true))\n", "sub_path": "src/data/metrics.py", "file_name": "metrics.py", "file_ext": "py", "file_size_in_byte": 4046, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 9, "usage_type": "call"}, {"api_name": "numpy.argpartition", "line_number": 10, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 11, "usage_type": "call"}, {"api_name": "sklearn.metrics.pairwise.cosine_similarity", "line_number": 16, "usage_type": "call"}, {"api_name": "numpy.argpartition", "line_number": 18, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 19, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.cosine", "line_number": 24, "usage_type": "call"}, {"api_name": "scipy.spatial.distance.hamming", "line_number": 30, "usage_type": "call"}, {"api_name": "scipy.stats.pearsonr", "line_number": 36, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 50, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 76, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.argsort", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.log2", "line_number": 122, "usage_type": "call"}]}
+{"seq_id": "482504594", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport threading\nfrom pymidi import server as pymidi_server\n\n# Maps pymidi note identifiers to their more conventional names.\nMIDI_NOTE_NAMES = {\n 'Cn1': 'C-1',\n 'Csn1': 'C#-1',\n 'Dn1': 'D-1',\n 'Dsn1': 'D#-1',\n 'En1': 'E-1',\n 'Fn1': 'F-1',\n 'Fsn1': 'F#-1',\n 'Gn1': 'G-1',\n 'Gsn1': 'G#-1',\n 'An1': 'A-1',\n 'Asn1': 'A#-1',\n 'Bn1': 'B-1',\n 'C0': 'C0',\n 'Cs0': 'C#0',\n 'D0': 'D0',\n 'Ds0': 'D#0',\n 'E0': 'E0',\n 'F0': 'F0',\n 'Fs0': 'F#0',\n 'G0': 'G0',\n 'Gs0': 'G#0',\n 'A0': 'A0',\n 'As0': 'A#0',\n 'B0': 'B0',\n 'C1': 'C1',\n 'Cs1': 'C#1',\n 'D1': 'D1',\n 'Ds1': 'D#1',\n 'E1': 'E1',\n 'F1': 'F1',\n 'Fs1': 'F#1',\n 'G1': 'G1',\n 'Gs1': 'G#1',\n 'A1': 'A1',\n 'As1': 'A#1',\n 'B1': 'B1',\n 'C2': 'C2',\n 'Cs2': 'C#2',\n 'D2': 'D2',\n 'Ds2': 'D#2',\n 'E2': 'E2',\n 'F2': 'F2',\n 'Fs2': 'F#2',\n 'G2': 'G2',\n 'Gs2': 'G#2',\n 'A2': 'A2',\n 'As2': 'A#2',\n 'B2': 'B2',\n 'C3': 'C3',\n 'Cs3': 'C#3',\n 'D3': 'D3',\n 'Ds3': 'D#3',\n 'E3': 'E3',\n 'F3': 'F3',\n 'Fs3': 'F#3',\n 'G3': 'G3',\n 'Gs3': 'G#3',\n 'A3': 'A3',\n 'As3': 'A#3',\n 'B3': 'B3',\n 'C4': 'C4',\n 'Cs4': 'C#4',\n 'D4': 'D4',\n 'Ds4': 'D#4',\n 'E4': 'E4',\n 'F4': 'F4',\n 'Fs4': 'F#4',\n 'G4': 'G4',\n 'Gs4': 'G#4',\n 'A4': 'A4',\n 'As4': 'A#4',\n 'B4': 'B4',\n 'C5': 'C5',\n 'Cs5': 'C#5',\n 'D5': 'D5',\n 'Ds5': 'D#5',\n 'E5': 'E5',\n 'F5': 'F5',\n 'Fs5': 'F#5',\n 'G5': 'G5',\n 'Gs5': 'G#5',\n 'A5': 'A5',\n 'As5': 'A#5',\n 'B5': 'B5',\n 'C6': 'C6',\n 'Cs6': 'C#6',\n 'D6': 'D6',\n 'Ds6': 'D#6',\n 'E6': 'E6',\n 'F6': 'F6',\n 'Fs6': 'F#6',\n 'G6': 'G6',\n 'Gs6': 'G#6',\n 'A6': 'A6',\n 'As6': 'A#6',\n 'B6': 'B6',\n 'C7': 'C7',\n 'Cs7': 'C#7',\n 'D7': 'D7',\n 'Ds7': 'D#7',\n 'E7': 'E7',\n 'F7': 'F7',\n 'Fs7': 'F#7',\n 'G7': 'G7',\n 'Gs7': 'G#7',\n 'A7': 'A7',\n 'As7': 'A#7',\n 'B7': 'B7',\n 'C8': 'C8',\n 'Cs8': 'C#8',\n 'D8': 'D8',\n 'Ds8': 'D#8',\n 'E8': 'E8',\n 'F8': 'F8',\n 'Fs8': 'F#8',\n 'G8': 'G8',\n 'Gs8': 'G#8',\n 'A8': 'A8',\n 'As8': 'A#8',\n 'B8': 'B8',\n 'C9': 'C9',\n 'Cs9': 'C#9',\n 'D9': 'D9',\n 'Ds9': 'D#9',\n 'E9': 'E9',\n 'F9': 'F9',\n 'Fs9': 'F#9',\n 'G9': 'G9',\n}\n\n# Convenience aliases for pymidi commands\nCOMMAND_NOTE_ON = 'note_on'\nCOMMAND_NOTE_OFF = 'note_off'\nCOMMAND_CONTROL_MODE_CHANGE = 'control_mode_change'\nSUPPORTED_COMMANDS = (COMMAND_NOTE_ON, COMMAND_NOTE_OFF, COMMAND_CONTROL_MODE_CHANGE)\n\n\nclass MidiFunctions(object):\n \"\"\"Defines things that can be controlled over midi.\n\n Instances of this class are simple containers which contain the\n constant `.name` value. The name of a MidiFunction is stable value\n that may be used in a MidiMapping (see later).\n\n The `ALL_FUNCTIONS` global contains all registered/available functions\n in the system. You can think of it like an enum.\n \"\"\"\n ALL_FUNCTIONS = {}\n\n def __init__(self, name, help_text=''):\n self.name = name\n self.help_text = help_text\n\n def __str__(self):\n return self.name\n\n @classmethod\n def add(cls, name, **kwargs):\n assert name not in cls.ALL_FUNCTIONS\n obj = cls(name, **kwargs)\n cls.ALL_FUNCTIONS[name] = obj\n setattr(cls, name, obj)\n\n\nMidiFunctions.add('playlist_next',\n help_text='Advance to the next item in the current playlist.')\nMidiFunctions.add('playlist_previous',\n help_text='Go to previous item in the current playlist.')\nMidiFunctions.add('playlist_pause',\n help_text='Pause the current playlist.')\nMidiFunctions.add('playlist_play',\n help_text='Pause the current playlist.')\nMidiFunctions.add('playlist_stay',\n help_text='Loop/repeat the current item in the playlist.')\nMidiFunctions.add('playlist_stop',\n help_text='Stop playback of the current playlist.')\nMidiFunctions.add('playlist_goto_1',\n help_text='Go to playlist position 1.')\nMidiFunctions.add('playlist_goto_2',\n help_text='Go to playlist position 2.')\nMidiFunctions.add('playlist_goto_3',\n help_text='Go to playlist position 3.')\nMidiFunctions.add('playlist_goto_4',\n help_text='Go to playlist position 4.')\nMidiFunctions.add('playlist_goto_5',\n help_text='Go to playlist position 5.')\nMidiFunctions.add('playlist_goto_6',\n help_text='Go to playlist position 6.')\nMidiFunctions.add('playlist_goto_7',\n help_text='Go to playlist position 7.')\nMidiFunctions.add('playlist_goto_8',\n help_text='Go to playlist position 8.')\nMidiFunctions.add('playlist_goto_9',\n help_text='Go to playlist position 9.')\nMidiFunctions.add('playlist_goto_10',\n help_text='Go to playlist position 10.')\nMidiFunctions.add('playlist_goto_11',\n help_text='Go to playlist position 11.')\nMidiFunctions.add('playlist_goto_12',\n help_text='Go to playlist position 12.')\nMidiFunctions.add('playlist_goto_13',\n help_text='Go to playlist position 13.')\nMidiFunctions.add('playlist_goto_14',\n help_text='Go to playlist position 14.')\nMidiFunctions.add('playlist_goto_15',\n help_text='Go to playlist position 15.')\nMidiFunctions.add('playlist_goto_16',\n help_text='Go to playlist position 16.')\nMidiFunctions.add('set_bpm',\n help_text='Set the global bpm based on note velocity or controller value.')\n\n\nclass MidiMapping(object):\n \"\"\"Maps MIDI commands to a special functions.\n\n Mappings will typically be one-to-one with MIDI devices, because the layout\n and configuration of physical keys and control surfaces varies widely.\n\n The internal representation is a map, from 2- or 3-tuple command, to desired\n MidiFunction instance. 2-tuple commands will match any velocity or value;\n 3-tuple commands only match the specified velocity or value.\n\n Example internal representation:\n {\n ('note_on', 'C3'): MidiFunctions('playlist_next'),\n ('note_on', 'C4'): MidiFunctions('playlist_previous'),\n ('control_mode_change', 22, 127): MidiFunctions('set_bpm'),\n }\n\n Equivalent JSON representation:\n {\n \"name\": \"KontrolPad\",\n \"mappings\": [\n {\n \"command\": [\"note_on\", \"C3\"],\n \"function\": \"playlist_next\"\n },\n {\n \"command\": [\"note_on\", \"C4\"],\n \"function\": \"playlist_previous\"\n },\n {\n \"command\": [\"control_mode_change\", 22, 127],\n \"function\": \"set_bpm\"\n }\n ]\n }\n \"\"\"\n def __init__(self, name, mappings=None):\n self.name = name\n self.mappings = mappings or {}\n\n def __eq__(self, other):\n if not isinstance(other, MidiMapping):\n return False\n return (self.name, self.mappings) == (other.name, other.mappings)\n\n def get_function(self, command):\n # Try an exact match (with velocity/value) first.\n exact_match = self.mappings.get(command)\n if exact_match or len(command) < 3:\n return exact_match\n\n # Try a partial match (ignore velocity/value).\n match = self.mappings.get(command[:2])\n return match\n\n def to_json(self):\n mappings_list = []\n for command, function in self.mappings.iteritems():\n mappings_list.append({\n 'command': command,\n 'function': function.name,\n })\n return {\n 'name': self.name,\n 'mappings': mappings_list,\n }\n\n @classmethod\n def from_json(cls, obj):\n \"\"\"Creates an instance from a parsed JSON object.\n\n Entries for unknown commands or unknown functions will be ignored.\n Structural errors will throw a KeyError.\n \"\"\"\n name = obj['name']\n mapping_list = obj['mappings']\n mapping_dict = {}\n for item in mapping_list:\n command = item['command']\n if command[0] not in SUPPORTED_COMMANDS:\n continue\n function = MidiFunctions.ALL_FUNCTIONS.get(item['function'])\n if not function:\n continue\n mapping_dict[tuple(command)] = function\n return cls(name, mapping_dict)\n\n\nclass MidiHandler(pymidi_server.Handler):\n def __init__(self, manager):\n self.manager = manager\n\n def on_peer_connected(self, peer):\n self.manager.on_midi_peer_connected(peer)\n\n def on_peer_disconnected(self, peer):\n self.manager.on_midi_peer_disconnected(peer)\n\n def on_midi_commands(self, peer, commands):\n self.manager.on_midi_commands(peer, commands)\n\n\nclass MidiManager(object):\n \"\"\"Binds a pymidi server to the dance floor controller.\"\"\"\n def __init__(self, port, controller, default_midi_mapping=None):\n self.controller = controller\n self.midi_server = pymidi_server.Server(port=port)\n self.midi_handler = MidiHandler(self)\n self.midi_server.add_handler(self.midi_handler)\n self.logger = logging.getLogger(self.__class__.__name__)\n self.midi_peers_to_mappings = {}\n self.logger.info('Midi enabled, port={}'.format(port))\n self.default_midi_mapping = default_midi_mapping or MidiMapping(name='default')\n\n def get_midi_mapping(self, peer):\n \"\"\"Returns the midi mapping for this peer.\"\"\"\n return self.midi_peers_to_mappings.get(peer.ssrc, self.default_midi_mapping)\n\n def command_to_tuple(self, cmd):\n \"\"\"Canonicalizes a pymidi command to its internal representation.\"\"\"\n if cmd.command in (COMMAND_NOTE_ON, COMMAND_NOTE_OFF):\n command = cmd.command\n note_name = MIDI_NOTE_NAMES.get(cmd.params.key, cmd.params.key)\n value = cmd.params.velocity\n if command == COMMAND_NOTE_ON and value == 0:\n # MIDI protocol specifies note on with velocity zero as a logical\n # note off; make the translation here.\n command = COMMAND_NOTE_OFF\n return (command, note_name, value)\n elif cmd.command == COMMAND_CONTROL_MODE_CHANGE:\n return (cmd.command, cmd.params.controller, cmd.params.value)\n return None\n\n def on_midi_peer_connected(self, peer):\n self.logger.info('Peer connected: {}'.format(peer))\n self.midi_peers_to_mappings[peer.ssrc] = self.default_midi_mapping\n\n def on_midi_peer_disconnected(self, peer):\n self.logger.info('Peer disconnected: {}'.format(peer))\n del self.midi_peers_to_mappings[peer.ssrc]\n\n def on_midi_commands(self, peer, commands):\n commands = map(self.command_to_tuple, commands)\n\n # Pass all midi messages through to the current processor.\n processor = self.controller.processor\n if processor and hasattr(processor, 'handle_midi_command'):\n for command in commands:\n processor.handle_midi_command(command)\n\n # Handle any special command bindings.\n mapping = self.get_midi_mapping(peer)\n for command in commands:\n function = mapping.get_function(command)\n if function:\n self.execute_midi_function(function, command)\n\n def execute_midi_function(self, midi_function, command):\n self.logger.info('MIDI function: {}'.format(midi_function))\n playlist = self.controller.playlist\n\n if midi_function == MidiFunctions.playlist_next:\n playlist.advance()\n elif midi_function == MidiFunctions.playlist_previous:\n playlist.previous()\n elif midi_function == MidiFunctions.playlist_stop:\n playlist.stop_playlist()\n elif midi_function == MidiFunctions.playlist_play:\n playlist.start_playlist()\n elif midi_function == MidiFunctions.playlist_stay:\n playlist.stay()\n elif midi_function == MidiFunctions.playlist_goto_1:\n playlist.go_to(1)\n elif midi_function == MidiFunctions.playlist_goto_2:\n playlist.go_to(2)\n elif midi_function == MidiFunctions.playlist_goto_3:\n playlist.go_to(3)\n elif midi_function == MidiFunctions.playlist_goto_4:\n playlist.go_to(4)\n elif midi_function == MidiFunctions.playlist_goto_5:\n playlist.go_to(5)\n elif midi_function == MidiFunctions.playlist_goto_6:\n playlist.go_to(6)\n elif midi_function == MidiFunctions.playlist_goto_7:\n playlist.go_to(7)\n elif midi_function == MidiFunctions.playlist_goto_8:\n playlist.go_to(8)\n elif midi_function == MidiFunctions.playlist_goto_9:\n playlist.go_to(9)\n elif midi_function == MidiFunctions.playlist_goto_10:\n playlist.go_to(10)\n elif midi_function == MidiFunctions.playlist_goto_11:\n playlist.go_to(11)\n elif midi_function == MidiFunctions.playlist_goto_12:\n playlist.go_to(12)\n elif midi_function == MidiFunctions.playlist_goto_13:\n playlist.go_to(13)\n elif midi_function == MidiFunctions.playlist_goto_14:\n playlist.go_to(14)\n elif midi_function == MidiFunctions.playlist_goto_15:\n playlist.go_to(15)\n elif midi_function == MidiFunctions.playlist_goto_16:\n playlist.go_to(16)\n elif midi_function == MidiFunctions.set_bpm:\n value = command.params.value\n bpm = 90\n bpm += float(value) / 127.0 * 80\n self.controller.set_bpm(bpm)\n\n def run_server(self):\n thr = threading.Thread(target=self.midi_server.serve_forever)\n thr.daemon = True\n self.logger.info('Starting midi server thread')\n thr.start()\n", "sub_path": "floor/controller/midi.py", "file_name": "midi.py", "file_ext": "py", "file_size_in_byte": 13892, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "pymidi.server.Handler", "line_number": 312, "usage_type": "attribute"}, {"api_name": "pymidi.server", "line_number": 312, "usage_type": "name"}, {"api_name": "pymidi.server.Server", "line_number": 330, "usage_type": "call"}, {"api_name": "pymidi.server", "line_number": 330, "usage_type": "name"}, {"api_name": "logging.getLogger", "line_number": 333, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 434, "usage_type": "call"}]}
+{"seq_id": "227253942", "text": "import pygame, sys\nfrom pygame.locals import *\nimport math\nimport Map\nfrom Map import Hexagon\nfrom Character import Character\nimport Tiles\nimport random\nfrom Menu import GameMenu, StatsScreen\n\nscreenWidth = 1250\nscreenHeight = 1250\n\nteal = (0,128,128)\nwhite = (255,255,255)\nblack = (0,0,0)\nred = (255,0,0)\ngreen = (0,255,0)\nblue = (0,0,255)\n\ncolors = [white, black, red, green, blue]\n\ndef create_stats_screen(location, character):\n pygame.draw.rect(gameDisplay, red, (*location, 300, 400))\n healthLabel = myFont.render(\"Hp: {}\".format(character.hp), 1, white)\n attackLabel = myFont.render(\"Attack: {}\".format(character.attack), 1, white)\n defenseLabel = myFont.render(\"Defense: {}\".format(character.defense), 1, white)\n movementSpeedLabel = myFont.render(\"Movement Speed: {}\".format(character.movementSpeed), 1, white)\n\n x,y = location\n labelCoordinates = [(x, y+ i*20) for i in range(4)]\n labels = [healthLabel, attackLabel, defenseLabel, movementSpeedLabel]\n for label, labelCoordinate in zip(labels, labelCoordinates):\n gameDisplay.blit(label, labelCoordinate)\n\ndef draw_map(map, display):\n display.fill(black)\n def render_tile(tile):\n pygame.draw.polygon(gameDisplay, tile.color, tile.vertices)\n #TODO Check convert alpha and colorkey to ignore the white\n #tileImage = pygame.image.load(tile.tilePic)\n #tileImage.set_colorkey((255,255,255))\n #gameDisplay.blit(tileImage.convert_alpha(),(tile.xPixel - tileImage.get_rect().size[0] / 2, tile.yPixel - tileImage.get_rect().size[1] / 2) )\n if tile.inhabited:\n gameDisplay.blit(tile.character.image.convert_alpha(), (tile.xPixel - tile.character.image.get_rect().size[0] / 2, tile.yPixel - tile.character.image.get_rect().size[1] / 2))\n\n for tile in map.tiles:\n render_tile(tile)\n map.hasChanged = False\n\n\n\npygame.init()\nclock = pygame.time.Clock()\ngameDisplay = pygame.display.set_mode((screenWidth, screenHeight), pygame.RESIZABLE)\n\nmyFont = pygame.font.SysFont(\"freesansbold.ttf\", 20)\n\ncar = Character('racecar.png')\nmario = Character('MarioPixel.png')\nraphael = Character(\"raphael.png\")\n\ngameDisplay.fill(black)\nhexagonMap = Map.map()\nhexagonMap.place_char(car, hexagonMap.tiles[0])\nhexagonMap.place_char(mario, hexagonMap.tiles[1])\nhexagonMap.place_char(raphael, hexagonMap.tiles[2])\n\ndraw_map(hexagonMap, gameDisplay)\n\n\ndef mouseOnWindowOption(mousePosition, openWindows):\n for window in openWindows:\n for optionsBox in window.optionBoxes:\n if optionsBox.x < mousePosition < optionsBox.width and optionsBox.y > mousePosition > optionsBox.height:\n return optionsBox.action()\n\n return None\n\n\n\nopenWindows = set()\n\ndef open_window(window, gameDisplay):\n openWindows.add(window)\n gameDisplay.blit(window, (window.x, window.y))\n\ndef close_window(window):\n openWindows.remove(window)\n draw_map(hexagonMap, gameDisplay)\n\nstatsScreen = StatsScreen(mario, 700, 0, 500, 500)\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, black)\n return textSurface, textSurface.get_rect()\n\n\ndef game_intro():\n pass\n\ncharacterSelected = False\nmovingChar = False\n\n\n\n\nwhile True:\n\n if hexagonMap.hasChanged:\n draw_map(hexagonMap, gameDisplay)\n if openWindows:\n for window in openWindows:\n gameDisplay.blit(window, (window.x,window.y))\n\n for event in pygame.event.get():\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n if mouseOnWindowOption(pos,openWindows):\n mouseOnWindowOption()\n\n\n tileSelected = [hexagon for hexagon in hexagonMap.tiles if (hexagon.xCoord, hexagon.yCoord) == Map.pixel_to_offset(pos)][0] if Map.pixel_to_offset(pos) in Map.map.fullMapCoords else hexagonMap.tiles[0]\n\n if event.button == 1:\n if movingChar:\n movingChar = False\n hexagonMap.move_char(movingFrom, tileSelected)\n\n elif tileSelected.inhabited:\n movingFrom = tileSelected\n movingChar = True\n\n if event.button == 3:\n if tileSelected.inhabited and statsScreen not in openWindows:\n statsScreen.character = tileSelected.character\n open_window(statsScreen, gameDisplay)\n elif statsScreen in openWindows:\n close_window(statsScreen)\n\n\n\n\n\n\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n\n pygame.display.update()\n", "sub_path": "Game Code.py", "file_name": "Game Code.py", "file_ext": "py", "file_size_in_byte": 4580, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pygame.draw.rect", "line_number": 24, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 24, "usage_type": "attribute"}, {"api_name": "pygame.draw.polygon", "line_number": 39, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 39, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 53, "usage_type": "call"}, {"api_name": "pygame.time.Clock", "line_number": 54, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 54, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pygame.RESIZABLE", "line_number": 55, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 57, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 57, "usage_type": "attribute"}, {"api_name": "Character.Character", "line_number": 59, "usage_type": "call"}, {"api_name": "Character.Character", "line_number": 60, "usage_type": "call"}, {"api_name": "Character.Character", "line_number": 61, "usage_type": "call"}, {"api_name": "Map.map", "line_number": 64, "usage_type": "call"}, {"api_name": "Menu.StatsScreen", "line_number": 92, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 116, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 116, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 118, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 119, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 119, "usage_type": "attribute"}, {"api_name": "Map.pixel_to_offset", "line_number": 124, "usage_type": "call"}, {"api_name": "Map.map", "line_number": 124, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 148, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 149, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 152, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 152, "usage_type": "attribute"}]}
+{"seq_id": "491020603", "text": "#! /usr/bin/env python3\n#\n# Disassembler for 6800 microprocessor.\n# Copyright (c) 2013-2015 by Jeff Tranter \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport argparse\nimport signal\n\n# Avoids an error when output piped, e.g. to \"less\"\nsignal.signal(signal.SIGPIPE, signal.SIG_DFL)\n\n# Addressing modes. Used as indices into opcode table.\nimplied = 0 # e.g. inca\nimmediate = 1 # e.g. ldaa #$12\ndirect = 2 # e.g. ldaa $12\nindexed = 3 # e.g. ldaa $12,x\nextended = 4 # e.g. ldaa $1234\nrelative = 5 # e.g. bra $1234\n\n\n# Lookup table - given addressing mode, returns length of instruction in bytes.\nlengthTable = [\n 1, # 0 - implied\n 2, # 1 - immediate\n 2, # 2 - direct\n 2, # 3 - indexed\n 3, # 4 - extended\n 2, # 5 - relative\n]\n\n# Lookup table - given opcode byte as index, return mnemonic of instruction and addressing mode.\n# Invalid opcodes are listed as \"???\".\nopcodeTable = [\n [\"???\", implied], # 00\n [\"nop\", implied], # 01\n [\"???\", implied], # 02\n [\"???\", implied], # 03\n [\"???\", implied], # 04\n [\"???\", implied], # 05\n [\"tap\", implied], # 06\n [\"tpa\", implied], # 07\n [\"inx\", implied], # 08\n [\"dex\", implied], # 09\n [\"clv\", implied], # 0A\n [\"sev\", implied], # 0B\n [\"clc\", implied], # 0C\n [\"sec\", implied], # 0D\n [\"cli\", implied], # 0E\n [\"sei\", implied], # 0F\n\n [\"sba\", implied], # 10\n [\"cba\", implied], # 11\n [\"???\", implied], # 12\n [\"???\", implied], # 13\n [\"nba\", implied], # 14\n [\"???\", implied], # 15\n [\"tab\", implied], # 16\n [\"tba\", implied], # 17\n [\"???\", implied], # 18\n [\"daa\", implied], # 19\n [\"???\", implied], # 1A\n [\"aba\", implied], # 1B\n [\"???\", implied], # 1C\n [\"???\", implied], # 1D\n [\"???\", implied], # 1E\n [\"???\", implied], # 1F\n\n [\"bra\", relative], # 20\n [\"???\", implied], # 21\n [\"bhi\", relative], # 22\n [\"bls\", relative], # 23\n [\"bcc\", relative], # 24\n [\"bcs\", relative], # 25\n [\"bne\", relative], # 26\n [\"beq\", relative], # 27\n [\"bvc\", relative], # 28\n [\"bvs\", relative], # 29\n [\"bpl\", relative], # 2A\n [\"bmi\", relative], # 2B\n [\"bge\", relative], # 2C\n [\"blt\", relative], # 2D\n [\"bgt\", relative], # 2E\n [\"ble\", relative], # 2F\n\n [\"tsx\", implied], # 30\n [\"ins\", implied], # 31\n [\"pula\", implied], # 32\n [\"pulb\", implied], # 33\n [\"des\", implied], # 34\n [\"txs\", implied], # 35\n [\"psha\", implied], # 36\n [\"pshb\", implied], # 37\n [\"???\", implied], # 38\n [\"rts\", implied], # 39\n [\"???\", implied], # 3A\n [\"rti\", implied], # 3B\n [\"???\", implied], # 3C\n [\"???\", implied], # 3D\n [\"wai\", implied], # 3E\n [\"swi\", implied], # 3F\n\n [\"nega\", implied], # 40\n [\"???\", implied], # 41\n [\"???\", implied], # 42\n [\"com\", implied], # 43\n [\"lsra\", implied], # 44\n [\"???\", implied], # 45\n [\"rora\", implied], # 46\n [\"asra\", implied], # 47\n [\"asla\", implied], # 48\n [\"rola\", implied], # 49\n [\"deca\", implied], # 4A\n [\"???\", implied], # 4B\n [\"inca\", implied], # 4C\n [\"tsta\", implied], # 4D\n [\"???\", implied], # 4E\n [\"clra\", implied], # 4F\n\n [\"neg\", implied], # 50\n [\"???\", implied], # 51\n [\"???\", implied], # 52\n [\"comb\", implied], # 53\n [\"lsrb\", implied], # 54\n [\"???\", implied], # 55\n [\"rorb\", implied], # 56\n [\"asrb\", implied], # 57\n [\"aslb\", implied], # 58\n [\"rolb\", implied], # 59\n [\"decb\", implied], # 5A\n [\"???\", implied], # 5B\n [\"incb\", implied], # 5C\n [\"tstb\", implied], # 5D\n [\"???\", implied], # 5E\n [\"clrb\", implied], # 5F\n\n [\"neg\", indexed], # 60\n [\"???\", implied], # 61\n [\"???\", implied], # 62\n [\"com\", indexed], # 63\n [\"lsr\", indexed], # 64\n [\"???\", implied], # 65\n [\"ror\", indexed], # 66\n [\"asr\", indexed], # 67\n [\"asl\", indexed], # 68\n [\"rol\", indexed], # 69\n [\"dec\", indexed], # 6A\n [\"???\", implied], # 6B\n [\"inc\", indexed], # 6C\n [\"tst\", indexed], # 6D\n [\"jmp\", indexed], # 6E\n [\"clr\", indexed], # 6F\n\n [\"neg\", extended], # 70\n [\"???\", implied], # 71\n [\"???\", implied], # 72\n [\"com\", extended], # 73\n [\"lsr\", extended], # 74\n [\"???\", implied], # 75\n [\"ror\", extended], # 76\n [\"asr\", extended], # 77\n [\"asl\", extended], # 78\n [\"rol\", extended], # 79\n [\"dec\", extended], # 7A\n [\"???\", implied], # 7B\n [\"inc\", extended], # 7C\n [\"tst\", extended], # 7D\n [\"jmp\", extended], # 7E\n [\"clr\", extended], # 7F\n\n [\"sub\", immediate], # 80\n [\"cmp\", immediate], # 81\n [\"sbc\", immediate], # 82\n [\"???\", implied], # 83\n [\"and\", immediate], # 84\n [\"bit\", immediate], # 85\n [\"lda\", immediate], # 86\n [\"???\", implied], # 87 STA #\n [\"eor\", immediate], # 88\n [\"adc\", immediate], # 89\n [\"ora\", immediate], # 8A\n [\"add\", immediate], # 8B\n [\"cpx\", immediate], # 8C\n [\"bsr\", immediate], # 8D\n [\"lds\", immediate], # 8E\n [\"???\", implied], # 8F STS #\n\n [\"sub\", direct], # 90\n [\"cmp\", direct], # 91\n [\"sbc\", direct], # 92\n [\"???\", implied], # 93\n [\"and\", direct], # 94\n [\"bit\", direct], # 95\n [\"lda\", direct], # 96\n [\"sta\", direct], # 97\n [\"eor\", direct], # 98\n [\"adc\", direct], # 99\n [\"ora\", direct], # 9A\n [\"add\", direct], # 9B\n [\"cpx\", direct], # 9C\n [\"???\", implied], # 9D HCF\n [\"lds\", direct], # 9E\n [\"sts\", direct], # 9F\n\n [\"sub\", indexed], # A0\n [\"cmp\", indexed], # A1\n [\"sbc\", indexed], # A2\n [\"???\", implied], # A3\n [\"and\", indexed], # A4\n [\"bit\", indexed], # A5\n [\"ldaa\", indexed], # A6\n [\"staa\", indexed], # A7\n [\"eora\", indexed], # A8\n [\"adca\", indexed], # A9\n [\"oraa\", indexed], # AA\n [\"adda\", indexed], # AB\n [\"cpx\", indexed], # AC\n [\"jsr\", indexed], # AD\n [\"lds\", indexed], # AE\n [\"sts\", indexed], # AF\n\n [\"suba\", extended], # B0\n [\"cmpa\", extended], # B1\n [\"sbca\", extended], # B2\n [\"???\", implied], # B3\n [\"anda\", extended], # B4\n [\"bita\", extended], # B5\n [\"ldaa\", extended], # B6\n [\"staa\", extended], # B7\n [\"eora\", extended], # B8\n [\"adca\", extended], # B9\n [\"oraa\", extended], # BA\n [\"adda\", extended], # BB\n [\"cpx\", extended], # BC\n [\"jsr\", extended], # BD\n [\"lds\", extended], # BE\n [\"sts\", extended], # BF\n\n [\"subb\", immediate], # C0\n [\"cmpb\", immediate], # C1\n [\"sbcb\", immediate], # C2\n [\"???\", implied], # C3\n [\"andb\", immediate], # C4\n [\"bitb\", immediate], # C5\n [\"ldab\", immediate], # C6\n [\"???\", implied], # C7 STA #\n [\"eorb\", immediate], # C8\n [\"adcb\", immediate], # C9\n [\"orab\", immediate], # CA\n [\"addb\", immediate], # CB\n [\"???\", implied], # CC\n [\"???\", implied], # CD\n [\"ldx\", immediate], # CE\n [\"???\", implied], # CF STX #\n\n [\"subb\", direct], # D0\n [\"cmpb\", direct], # D1\n [\"sbcb\", direct], # D2\n [\"???\", implied], # D3\n [\"andb\", direct], # D4\n [\"bitb\", direct], # D5\n [\"ldab\", direct], # D6\n [\"stab\", direct], # D7\n [\"eorb\", direct], # D8\n [\"adcb\", direct], # D9\n [\"orab\", direct], # DA\n [\"addb\", direct], # DB\n [\"???\", implied], # DC\n [\"???\", implied], # DD HCF\n [\"ldx\", direct], # DE\n [\"stx\", direct], # DF\n\n [\"subb\", indexed], # E0\n [\"cmpb\", indexed], # E1\n [\"sbcb\", indexed], # E2\n [\"???\", implied], # E3\n [\"andb\", indexed], # E4\n [\"bitb\", indexed], # E5\n [\"ldab\", indexed], # E6\n [\"stab\", indexed], # E7\n [\"eorb\", indexed], # E8\n [\"adcb\", indexed], # E9\n [\"orab\", indexed], # EA\n [\"addb\", indexed], # EB\n [\"???\", implied], # EC\n [\"???\", implied], # ED\n [\"ldx\", indexed], # EE\n [\"stx\", indexed], # EF\n\n [\"subb\", extended], # F0\n [\"cmpb\", extended], # F1\n [\"sbcb\", extended], # F2\n [\"???\", implied], # F3\n [\"andb\", extended], # F4\n [\"bitb\", extended], # F5\n [\"ldab\", extended], # F6\n [\"stab\", extended], # F7\n [\"eorb\", extended], # F8\n [\"adcb\", extended], # F9\n [\"orab\", extended], # FA\n [\"addb\", extended], # FB\n [\"???\", implied], # FC\n [\"???\", implied], # FD\n [\"ldx\", extended], # FE\n [\"stx\", extended], # FF\n]\n\n# Indicates if uppercase option is in effect.\nupperOption = False\n\n# Functions\n\n\ndef isprint(c):\n \"Return if character is printable ASCII\"\n if c >= '@' and c <= '~':\n return True\n else:\n return False\n\n\ndef case(s):\n \"Return string or uppercase version of string if option is set.\"\n global upperOption\n if upperOption:\n return s.upper()\n else:\n return s\n\n\ndef formatByte(data):\n \"Format an 8-bit byte using the current display format (e.g. hex or octal)\"\n global args\n if args.format == 4: # Octal\n return \"%03o\" % data\n else: # Hex\n return \"%02X\" % data\n\n\ndef formatAddress(data):\n \"Format a 16-bit address using the current display format (e.g. hex or octal)\"\n global args\n if args.format == 4: # Octal\n return \"%06o\" % data\n else: # Hex\n return \"%04X\" % data\n\n# Parse command line options\nparser = argparse.ArgumentParser()\nparser.add_argument(\"filename\", help=\"Binary file to disassemble\")\nparser.add_argument(\"-n\", \"--nolist\", help=\"Don't list instruction bytes (make output suitable for assembler)\", action=\"store_true\")\nparser.add_argument(\"-u\", \"--uppercase\", help=\"Use uppercase for mnemonics\", action=\"store_true\")\nparser.add_argument(\"-a\", \"--address\", help=\"Specify decimal starting address (defaults to 0)\", default=0, type=int)\nparser.add_argument(\"-f\", \"--format\", help=\"Use number format: 1=$1234 2=1234h 3=1234 4=177777 (default 1)\", default=1, type=int, choices=range(1, 5))\nparser.add_argument(\"-i\", \"--invalid\", help=\"Show invalid opcodes as ??? rather than constants\", action=\"store_true\")\nargs = parser.parse_args()\n\n# Get filename from command line arguments.\nfilename = args.filename\n\n# Current instruction address. Silently force it to be in valid range.\naddress = args.address & 0xffff\n\n# Set uppercase output option.\nupperOption = args.uppercase\n\n# Contains a line of output\nline = \"\"\n\n# Open input file.\n# Display error and exit if filename does not exist.\ntry:\n f = open(filename, \"rb\")\nexcept FileNotFoundError:\n print(\"error: input file '%s' not found.\" % filename, file=sys.stderr)\n sys.exit(1)\n\n# Print initial origin address\nif args.nolist is False:\n if args.format == 1:\n print(\"%04X %s $%04X\" % (address, case(\".org\"), address))\n elif args.format == 2:\n print(\"%04X %s %04X%s\" % (address, case(\".org\"), address, case(\"h\")))\n elif args.format == 3:\n print(\"%04X %s %04X\" % (address, case(\".org\"), address))\n else:\n print(\"%06o %s %06o\" % (address, case(\".org\"), address))\nelse:\n if args.format == 1:\n print(\" %s $%04X\" % (case(\".org\"), address))\n elif args.format == 2:\n print(\" %s %04X%s\" % (case(\".org\"), address, case(\"h\")))\n elif args.format == 3:\n print(\" %s %04X\" % (case(\".org\"), address))\n else:\n print(\" %s %06o\" % (case(\".org\"), address))\n\nwhile True:\n try:\n b = f.read(1) # Get binary byte from file\n\n if len(b) == 0: # EOF\n if args.nolist is False:\n if args.format == 4:\n print(\"%06o %s\" % (address, case(\"end\"))) # Exit if end of file reached.\n else:\n print(\"%04X %s\" % (address, case(\"end\"))) # Exit if end of file reached.\n break\n\n if args.nolist is False:\n line = \"%s \" % formatAddress(address) # Print current address\n\n op = ord(b) # Get opcode byte\n\n mnem = case(opcodeTable[op][0]) # Get mnemonic\n\n mode = opcodeTable[op][1] # Get addressing mode\n\n n = lengthTable[mode] # Look up number of instruction bytes\n\n # Handle special case of immediate instructions that are three\n # bytes long.\n if mnem in set([\"cpx\", \"ldx\", \"lds\"]):\n n = 3\n\n # Print instruction bytes\n if n == 1:\n if args.nolist is False:\n if args.format == 4:\n line += \"%03o \" % op\n else:\n line += \"%02X \" % op\n elif n == 2:\n try: # Possible to get exception here if EOF reached.\n op1 = ord(f.read(1))\n except TypeError:\n op1 = 0 # Fake it to recover from EOF\n if args.nolist is False:\n if args.format == 4:\n line += \"%03o %03o \" % (op, op1)\n else:\n line += \"%02X %02X \" % (op, op1)\n elif n == 3:\n try: # Possible to get exception here if EOF reached.\n op1 = ord(f.read(1))\n op2 = ord(f.read(1))\n except TypeError:\n op1 = 0 # Fake it to recover from EOF\n op2 = 0\n if args.nolist is False:\n line += \"%s %s %s \" % (formatByte(op), formatByte(op1), formatByte(op2))\n if args.nolist is True:\n line += \" \"\n\n # Special check for invalid op code.\n if mnem == \"???\" and not args.invalid:\n if isprint(chr(op)):\n line += \"%s '%c'\" % (case(\".byte\"), op)\n else:\n if args.format == 1:\n line += \"%s $%s\" % (case(\".byte\"), formatByte(op))\n elif args.format == 2:\n line += \"%s %s%s\" % (case(\".byte\"), formatByte(op), case(\"h\"))\n else:\n line += \"%s %s\" % (case(\".byte\"), formatByte(op))\n else:\n line += mnem\n if len(mnem) == 3:\n line += \" \"\n\n if mode == implied:\n pass\n\n elif mode == immediate:\n if (n == 2):\n if isprint(chr(op1)):\n line += \" #'%c'\" % op1\n else:\n if args.format == 1:\n line += \" #$%s\" % formatByte(op1)\n elif args.format == 2:\n line += \" #%s%s\" % (formatByte(op1), case(\"h\"))\n else:\n line += \" #%s\" % formatByte(op1)\n elif (n == 3):\n if args.format == 1:\n line += \" #$%s%s\" % (formatByte(op1), formatByte(op2))\n elif args.format == 2:\n line += \" #%s%s%s\" % (formatByte(op1), formatByte(op2), case(\"h\"))\n else:\n line += \" #%s%s\" % (formatByte(op1), formatByte(op2))\n\n elif mode == direct:\n if args.format == 1:\n line += \" $%s\" % formatByte(op1)\n elif args.format == 2:\n line += \" %s%s\" % (formatByte(op1), case(\"h\"))\n else:\n line += \" %s\" % formatByte(op1)\n\n elif mode == indexed:\n if args.format == 1:\n line += \" $%s,%s\" % (formatByte(op1), case(\"x\"))\n elif args.format == 2:\n line += \" %s%s,%s\" % (formatByte(op1), case(\"h\"), case(\"x\"))\n else:\n line += \" %s,%s\" % (formatByte(op1), case(\"x\"))\n\n elif mode == extended:\n if args.format == 1:\n line += \" $%s%s\" % (formatByte(op1), formatByte(op2))\n elif args.format == 2:\n line += \" %s%s%s\" % (formatByte(op1), formatByte(op2), case(\"h\"))\n else:\n line += \" %s%s\" % (formatByte(op1), formatByte(op2))\n\n elif mode == relative:\n if op1 < 128:\n dest = address + op1 + 2\n else:\n dest = address - (256 - op1) + 2\n if dest < 0:\n dest = 65536 + dest\n if args.format == 1:\n line += \" $%s\" % formatAddress(dest)\n elif args.format == 2:\n line += \" %s%s\" % (formatAddress(dest), case(\"h\"))\n else:\n line += \" %s%s\" % (formatAddress(dest), formatByte(op1))\n\n else:\n print(\"Internal error: unknown addressing mode:\", mode, file=sys.stderr)\n sys.exit(1)\n\n # Update address\n address += n\n\n # Check for address exceeding 0xFFFF, if so wrap around.\n if address > 0xffff:\n address = address & 0xffff\n\n # Finished a line of disassembly\n print(line)\n line = \"\"\n\n except KeyboardInterrupt:\n print(\"Interrupted by Control-C\", file=sys.stderr)\n if args.format == 4:\n print(\"%s %s\" % (formatAddress(address), case(\"end\"))) # Exit if end of file reached.\n else:\n print(\"%s %s\" % (formatAddress(address), case(\"end\"))) # Exit if end of file reached.\n break\n", "sub_path": "disasm/disasm6800.py", "file_name": "disasm6800.py", "file_ext": "py", "file_size_in_byte": 18433, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "signal.signal", "line_number": 23, "usage_type": "call"}, {"api_name": "signal.SIGPIPE", "line_number": 23, "usage_type": "attribute"}, {"api_name": "signal.SIG_DFL", "line_number": 23, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 361, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 387, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 388, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 544, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 545, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 559, "usage_type": "attribute"}]}
+{"seq_id": "362001239", "text": "##modified from https://github.com/zhixuhao/unet\nfrom __future__ import print_function\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np \nimport os\nimport glob\nimport skimage.io as io\nimport skimage.transform as trans\n\nSky = [128,128,128]\nBuilding = [128,0,0]\nPole = [192,192,128]\nRoad = [128,64,128]\nPavement = [60,40,222]\nTree = [128,128,0]\nSignSymbol = [192,128,128]\nFence = [64,64,128]\nCar = [64,0,128]\nPedestrian = [64,64,0]\nBicyclist = [0,128,192]\nUnlabelled = [0,0,0]\n\nCOLOR_DICT = np.array([Sky, Building, Pole, Road, Pavement,\n Tree, SignSymbol, Fence, Car, Pedestrian, Bicyclist, Unlabelled])\n\n\ndef adjustData(img,mask,flag_multi_class,num_class):\n if(flag_multi_class):\n img = img / 255\n mask = mask[:,:,:,0] if(len(mask.shape) == 4) else mask[:,:,0]\n new_mask = np.zeros(mask.shape + (num_class,))\n for i in range(num_class):\n #for one pixel in the image, find the class in mask and convert it into one-hot vector\n #index = np.where(mask == i)\n #index_mask = (index[0],index[1],index[2],np.zeros(len(index[0]),dtype = np.int64) + i) if (len(mask.shape) == 4) else (index[0],index[1],np.zeros(len(index[0]),dtype = np.int64) + i)\n #new_mask[index_mask] = 1\n new_mask[mask == i,i] = 1\n new_mask = np.reshape(new_mask,(new_mask.shape[0],new_mask.shape[1]*new_mask.shape[2],new_mask.shape[3])) if flag_multi_class else np.reshape(new_mask,(new_mask.shape[0]*new_mask.shape[1],new_mask.shape[2]))\n mask = new_mask\n elif(np.max(img) > 1):\n img = img / 255\n mask = mask /255\n mask[mask > 0.5] = 1\n mask[mask <= 0.5] = 0\n return (img,mask)\n\n\n\ndef trainGenerator(batch_size,train_path,image_folder,mask_folder,aug_dict,image_color_mode = \"grayscale\",\n mask_color_mode = \"grayscale\",image_save_prefix = \"image\",mask_save_prefix = \"mask\",\n flag_multi_class = False,num_class = 2,save_to_dir = None,target_size = (256,256),seed = 1):\n '''\n can generate image and mask at the same time\n use the same seed for image_datagen and mask_datagen to ensure the transformation for image and mask is the same\n if you want to visualize the results of generator, set save_to_dir = \"your path\"\n '''\n image_datagen = ImageDataGenerator(**aug_dict)\n mask_datagen = ImageDataGenerator(**aug_dict)\n image_generator = image_datagen.flow_from_directory(\n train_path,\n classes = [image_folder],\n class_mode = None,\n color_mode = image_color_mode,\n target_size = target_size,\n batch_size = batch_size,\n save_to_dir = save_to_dir,\n save_prefix = image_save_prefix,\n seed = seed)\n mask_generator = mask_datagen.flow_from_directory(\n train_path,\n classes = [mask_folder],\n class_mode = None,\n color_mode = mask_color_mode,\n target_size = target_size,\n batch_size = batch_size,\n save_to_dir = save_to_dir,\n save_prefix = mask_save_prefix,\n seed = seed)\n train_generator = zip(image_generator, mask_generator)\n for (img,mask) in train_generator:\n img,mask = adjustData(img,mask,flag_multi_class,num_class)\n yield (img,mask)\n\n\n\ndef testGenerator(test_path, strtstr, target_size = (256,256),flag_multi_class = False,as_gray = True):\n dir = os.path.expanduser(test_path)\n count = 0\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n filename, ext = os.path.splitext(os.path.basename(d))\n #print(filename,ext)\n if filename.startswith(strtstr):\n #img = io.imread(d,as_gray = as_gray)\n #print('file read: ',filename)\n# for i in range(num_image):\n img = io.imread(d,as_gray = as_gray)\n img = img / 255\n img = trans.resize(img,target_size)\n img = np.reshape(img,img.shape+(1,)) if (not flag_multi_class) else img\n img = np.reshape(img,(1,)+img.shape)\n## if(count > 2):\n## break;\n## else:\n## count += 1\n yield img\n\n\ndef geneTrainNpy(image_path,mask_path,flag_multi_class = False,num_class = 2,image_prefix = \"image\",mask_prefix = \"mask\",image_as_gray = True,mask_as_gray = True):\n image_name_arr = glob.glob(os.path.join(image_path,\"%s*.png\"%image_prefix))\n image_arr = []\n mask_arr = []\n for index,item in enumerate(image_name_arr):\n img = io.imread(item,as_gray = image_as_gray)\n img = np.reshape(img,img.shape + (1,)) if image_as_gray else img\n mask = io.imread(item.replace(image_path,mask_path).replace(image_prefix,mask_prefix),as_gray = mask_as_gray)\n mask = np.reshape(mask,mask.shape + (1,)) if mask_as_gray else mask\n img,mask = adjustData(img,mask,flag_multi_class,num_class)\n image_arr.append(img)\n mask_arr.append(mask)\n image_arr = np.array(image_arr)\n mask_arr = np.array(mask_arr)\n return image_arr,mask_arr\n\n\ndef labelVisualize(num_class,color_dict,img):\n img = img[:,:,0] if len(img.shape) == 3 else img\n img_out = np.zeros(img.shape + (3,))\n for i in range(num_class):\n img_out[img == i,:] = color_dict[i]\n return img_out / 255\n\n\n#def saveResult(save_path,filename,npyfile,flag_multi_class = False,num_class = 2):\ndef saveResult(save_path,npyfile,pref,flag_multi_class = False,num_class = 2):\n full = np.zeros((1536, 2048))\n dim = 256\n col = 0\n row = 0\n## io.imsave(os.path.join(save_path,\".tif\"),img)\n for i,item in enumerate(npyfile):\n img = item[:,:,0]\n## #print(img)\n flname = pref+str(i)\n io.imsave(os.path.join(save_path,\"%s.tif\"%flname),img)\n #if you want to combine the image slices, uncomment below\n## full[col * dim: (col + 1) * dim, row * dim: (row + 1) * dim] = img\n## if row >= (2048/dim)-1 :\n## row = 0\n## col += 1\n## else:\n## row += 1\n## if col >= (1536/dim) :\n## print('all images saved')\n## break\n## io.imsave(os.path.join(save_path,\"%d_full.png\"%filename),full)\n## return full\n print(\"Results saved for: \",save_path)\n\n##\n##def saveResult(save_path,npyfile,flag_multi_class = False,num_class = 2):\n## for i,item in enumerate(npyfile):\n## img = item[:,:,0]\n## io.imsave(os.path.join(save_path,\"%d_predict.tif\"%i),img)\n\n", "sub_path": "UNet/data.py", "file_name": "data.py", "file_ext": "py", "file_size_in_byte": 6455, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.array", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 31, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 40, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.ImageDataGenerator", "line_number": 57, "usage_type": "call"}, {"api_name": "keras.preprocessing.image.ImageDataGenerator", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path.expanduser", "line_number": 87, "usage_type": "call"}, {"api_name": "os.path", "line_number": 87, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path", "line_number": 90, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 91, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 97, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 97, "usage_type": "name"}, {"api_name": "skimage.transform.resize", "line_number": 99, "usage_type": "call"}, {"api_name": "skimage.transform", "line_number": 99, "usage_type": "name"}, {"api_name": "numpy.reshape", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 101, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 110, "usage_type": "call"}, {"api_name": "os.path", "line_number": 110, "usage_type": "attribute"}, {"api_name": "skimage.io.imread", "line_number": 114, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 114, "usage_type": "name"}, {"api_name": "numpy.reshape", "line_number": 115, "usage_type": "call"}, {"api_name": "skimage.io.imread", "line_number": 116, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 116, "usage_type": "name"}, {"api_name": "numpy.reshape", "line_number": 117, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 136, "usage_type": "call"}, {"api_name": "skimage.io.imsave", "line_number": 145, "usage_type": "call"}, {"api_name": "skimage.io", "line_number": 145, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 145, "usage_type": "call"}, {"api_name": "os.path", "line_number": 145, "usage_type": "attribute"}]}
+{"seq_id": "490885384", "text": "# -------------------------------------------------------------------------------\n# Licence:\n# Copyright (c) 2012-2017 Luzzi Valerio \n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n#\n#\n# Name: datatypes.py\n# Purpose:\n#\n# Author: Luzzi Valerio\n#\n# Created: 27/07/2017\n# -------------------------------------------------------------------------------\nimport datetime\nimport numpy as np\nimport xlrd, xlwt\nimport json\n\nfrom .stime import strftime, ctod\nfrom .strings import *\n\n\ndef parseInt(text):\n \"\"\"\n parseInt\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^[-+]?\\d+$\"\"\"\n PATTERN = \"\"\"(?P(%s))\"\"\" % (PATTERN1)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return int(res)\n return None\n\n\ndef parseFloat(text):\n \"\"\"\n parseFloat\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^[-+]?(?:(\\d+|\\d+\\.\\d*|\\d*\\.\\d+)(e[-+]?\\d+)?)$\"\"\"\n PATTERN = \"\"\"(?P(%s))\"\"\" % (PATTERN1)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return float(res)\n return None\n\n\ndef parseDate(text):\n \"\"\"\n parseDate\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^\\d{1,2}-\\d{1,2}-(\\d{4,4}|\\d{2,2})$\"\"\" # 1-1-2017\n PATTERN2 = \"\"\"^\\d{1,2}(\\/)\\d{1,2}(\\/)(\\d{4,4}|\\d{2,2})$\"\"\" # 1/1/2017\n PATTERN3 = \"\"\"^\\d{4,4}-\\d{1,2}-\\d{1,2}$\"\"\" # 2017-01-01\n PATTERN = \"\"\"(?P(%s)|(%s)|(%s))\"\"\" % (PATTERN1, PATTERN2, PATTERN3)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return strftime(\"%Y-%m-%d\", res)\n return None\n\n\ndef parseDatetime(text):\n \"\"\"\n parseDatetime\n \"\"\"\n if isstring(text):\n PATTERN1 = \"\"\"^\\d{1,2}-\\d{1,2}-(\\d{4,4}|\\d{2,2})(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN2 = \"\"\"^\\d{1,2}(\\/)\\d{1,2}(\\/)(\\d{4,4}|\\d{2,2})(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN3 = \"\"\"^\\d{4,4}-\\d{1,2}-\\d{1,2}(\\s\\d{1,2}(:|\\.)\\d{2,2}((:|\\.)\\d\\d)?)?$\"\"\"\n PATTERN = \"\"\"(?P(%s)|(%s)|(%s))\"\"\" % (PATTERN1, PATTERN2, PATTERN3)\n text = text.strip()\n g = re.match(PATTERN, text, re.IGNORECASE | re.MULTILINE)\n if g:\n res = g.groupdict()[\"target\"]\n return strftime(\"%Y-%m-%d %H:%M:%S\", res)\n return None\n\n\ndef parseBool(text):\n \"\"\"\n parseBool\n \"\"\"\n if isstring(text):\n text = text.lower()\n if text in (\"true\", \"1\", \"on\"):\n return True\n return False\n\n return True if text else False\n\n\ndef parseColor(text, out=\"hex\"):\n \"\"\"\n parseColor - TODO\n \"\"\"\n if isstring(text):\n\n if xlwt.Style.colour_map.has_key(text):\n return \"%06x\" % xlwt.Style.colour_map[text]\n\n elif len(listify(text.replace(r'[\\s;]', \",\"), \",\")) == 3:\n rgb = listify(text.replace(r'[\\s;]', \",\"), \",\")\n return \"#%02x%02x%02x\" % tuple(val(rgb))\n\n elif len(listify(text.replace(r'[\\s;]', \",\"), \",\")) == 4:\n rgba = listify(text.replace(r'[\\s;]', \",\"), \",\")\n (r, g, b, a) = val(rgba)\n a = int(a * 255) if a <= 1.0 else a\n return \"#%02x%02x%02x%02x\" % (r, g, b, a)\n\n\n return \"000000\"\n\n\ndef parseJSON(text):\n \"\"\"\n parseJSON - load json txt into obj\n \"\"\"\n if isinstance(text, (tuple, list, dict)):\n return text\n if isstring(text):\n return json.loads(text)\n return None\n\ndef isquery(text):\n pattern = r'^\\s*((SELECT|PRAGMA|INSERT|DELETE|REPLACE|UPDATE|CREATE).*)'\n res = re.match(pattern, text, re.IGNORECASE)\n return True if res else False\n\n\ndef isarray(value):\n return isinstance(value, (tuple, list, np.ndarray))\n\n\ndef isfloat(text):\n return not parseDate(text) is None\n\n\ndef isdate(text):\n if isinstance(text, (datetime.date,)):\n return True\n return not parseDate(text) is None\n\n\ndef isdatetime(text):\n if isinstance(text, (datetime.datetime,)):\n return True\n return not parseDatetime(text) is None\n\n\ndef parseValue(value, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n parseValue - parse values from string\n \"\"\"\n if value is None:\n return None\n if isstring(value) and value in nodata:\n return None\n elif isstring(value) and re.match(r'^(GEOMFROM|POINT).*', value, re.I | re.M):\n return value\n elif isdate(value):\n return strftime(\"%Y-%m-%d\", value)\n elif isdatetime(value):\n return strftime(\"%Y-%m-%d %H:%M:%S\", value)\n elif isfloat(value):\n return value\n elif isstring(value):\n return value\n elif isarray(value):\n return [parseValue(item) for item in value]\n return None\n\n\nSQLTYPES = {\n 9999: \"\",\n 9998: \"EMPTY\",\n 1: \"TEXT\",\n 2: \"DATETIME\",\n 3: \"DATE\",\n 4: \"TIME\",\n 5: \"FLOAT\",\n 6: \"INTEGER\",\n 7: \"GEOMETRY\",\n \"\": 9999,\n \"EMPTY\": 9998,\n \"TEXT\": 1,\n \"DATETIME\": 2,\n \"DATE\": 3,\n \"TIME\": 4,\n \"FLOAT\": 5,\n \"INTEGER\": 6,\n \"GEOMETRY\": 7\n}\n\nXLRDTYPES = {\n xlrd.XL_CELL_EMPTY: 9999,\n xlrd.XL_CELL_BLANK: 9999,\n xlrd.XL_CELL_TEXT: 1,\n xlrd.XL_CELL_DATE: 2,\n xlrd.XL_CELL_NUMBER: 5,\n xlrd.XL_CELL_BOOLEAN: 6\n}\n\n\ndef sqltype(cvalue, ctype=xlrd.XL_CELL_TEXT, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n Type symbol\tType number\tPython value\n XL_CELL_EMPTY\t0\tempty string u''\n XL_CELL_TEXT\t1\ta Unicode string\n XL_CELL_NUMBER\t2\tfloat\n XL_CELL_DATE\t3\tfloat\n XL_CELL_BOOLEAN\t4\tint; 1 means TRUE, 0 means FALSE\n XL_CELL_ERROR\t5\tint representing internal Excel codes; for a text representation, refer to the supplied dictionary error_text_from_code\n XL_CELL_BLANK\t6\tempty string u''. Note: this type will appear only when open_workbook(..., formatting_info=True) is used.\n \"\"\"\n if isarray(cvalue):\n if not isarray(ctype):\n ctype = [ctype] * len(cvalue)\n return [sqltype(cv, ct, nodata) for cv, ct in zip(cvalue, ctype)]\n if isinstance(cvalue, xlrd.sheet.Cell):\n return sqltype(cvalue.value, cvalue.ctype, nodata)\n if ctype == xlrd.XL_CELL_EMPTY:\n return 'EMPTY'\n elif ctype == xlrd.XL_CELL_TEXT and cvalue in nodata:\n return ''\n elif ctype == xlrd.XL_CELL_TEXT and isdate(cvalue):\n return 'DATE'\n elif ctype == xlrd.XL_CELL_TEXT and isdatetime(cvalue):\n return 'DATETIME'\n elif ctype == xlrd.XL_CELL_TEXT and parseInt(cvalue):\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_TEXT and parseFloat(cvalue) != None:\n return 'FLOAT'\n elif ctype == xlrd.XL_CELL_TEXT:\n return 'TEXT'\n elif ctype == xlrd.XL_CELL_NUMBER and int(cvalue) == cvalue:\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_NUMBER:\n return 'FLOAT'\n elif ctype == xlrd.XL_CELL_DATE:\n return 'DATETIME'\n elif ctype == xlrd.XL_CELL_BOOLEAN:\n return 'INTEGER'\n elif ctype == xlrd.XL_CELL_ERROR:\n return ''\n elif ctype == xlrd.XL_CELL_BLANK:\n return ''\n else:\n return 'TEXT'\n\n\ndef xlsvalue(cell, nodata=(\"\", \"Na\", \"NaN\", \"-\", \"--\", \"N/A\")):\n \"\"\"\n Type symbol\tType number\tPython value\n XL_CELL_EMPTY\t0\tempty string u''\n XL_CELL_TEXT\t1\ta Unicode string\n XL_CELL_NUMBER\t2\tfloat\n XL_CELL_DATE\t3\tfloat\n XL_CELL_BOOLEAN\t4\tint; 1 means TRUE, 0 means FALSE\n XL_CELL_ERROR\t5\tint representing internal Excel codes; for a text representation, refer to the supplied dictionary error_text_from_code\n XL_CELL_BLANK\t6\tempty string u''. Note: this type will appear only when open_workbook(..., formatting_info=True) is used.\n \"\"\"\n if isarray(cell):\n return [xlsvalue(item, nodata) for item in cell]\n\n cvalue, ctype = cell.value, cell.ctype\n if ctype == xlrd.XL_CELL_EMPTY:\n return None\n elif ctype == xlrd.XL_CELL_TEXT and cvalue in nodata:\n return None\n elif ctype == xlrd.XL_CELL_TEXT and isdate(cvalue.strip()):\n return parseDate(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and isdatetime(cvalue.strip()):\n return parseDatetime(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and parseInt(cvalue):\n return parseInt(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT and parseFloat(cvalue.strip()) != None:\n return parseFloat(cvalue)\n elif ctype == xlrd.XL_CELL_TEXT:\n return cvalue\n elif ctype == xlrd.XL_CELL_NUMBER:\n return cvalue\n elif ctype == xlrd.XL_CELL_DATE:\n return ctod(cell)\n elif ctype == xlrd.XL_CELL_BOOLEAN:\n return cvalue\n elif ctype == xlrd.XL_CELL_ERROR:\n return None\n elif ctype == xlrd.XL_CELL_BLANK:\n return None\n else:\n return None\n\n\ndef main():\n pass\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "Python27/Lib/site-packages/gecosistema_lite/datatypes.py", "file_name": "datatypes.py", "file_ext": "py", "file_size_in_byte": 9441, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "stime.strftime", "line_number": 77, "usage_type": "call"}, {"api_name": "stime.strftime", "line_number": 94, "usage_type": "call"}, {"api_name": "xlwt.Style.colour_map.has_key", "line_number": 117, "usage_type": "call"}, {"api_name": "xlwt.Style", "line_number": 117, "usage_type": "attribute"}, {"api_name": "xlwt.Style", "line_number": 118, "usage_type": "attribute"}, {"api_name": "json.loads", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.ndarray", "line_number": 151, "usage_type": "attribute"}, {"api_name": "datetime.date", "line_number": 159, "usage_type": "attribute"}, {"api_name": "datetime.datetime", "line_number": 165, "usage_type": "attribute"}, {"api_name": "stime.strftime", "line_number": 181, "usage_type": "call"}, {"api_name": "stime.strftime", "line_number": 183, "usage_type": "call"}, {"api_name": "xlrd.XL_CELL_EMPTY", "line_number": 215, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_BLANK", "line_number": 216, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 217, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_DATE", "line_number": 218, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_NUMBER", "line_number": 219, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_BOOLEAN", "line_number": 220, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 224, "usage_type": "attribute"}, {"api_name": "xlrd.sheet", "line_number": 239, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_EMPTY", "line_number": 241, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 243, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 245, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 247, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 249, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 251, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 253, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_NUMBER", "line_number": 255, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_NUMBER", "line_number": 257, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_DATE", "line_number": 259, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_BOOLEAN", "line_number": 261, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_ERROR", "line_number": 263, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_BLANK", "line_number": 265, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_EMPTY", "line_number": 286, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 288, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 290, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 292, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 294, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 296, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_TEXT", "line_number": 298, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_NUMBER", "line_number": 300, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_DATE", "line_number": 302, "usage_type": "attribute"}, {"api_name": "stime.ctod", "line_number": 303, "usage_type": "call"}, {"api_name": "xlrd.XL_CELL_BOOLEAN", "line_number": 304, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_ERROR", "line_number": 306, "usage_type": "attribute"}, {"api_name": "xlrd.XL_CELL_BLANK", "line_number": 308, "usage_type": "attribute"}]}
+{"seq_id": "384128569", "text": "import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport json\r\n\r\n#Paramétrage des variables\r\nwebsite = \"https://gist.github.com/paulmillr/2657075\"\r\nhead = {'Authorization': 'token {}'.format('4ff5d101d25d4057916fcfeaa3d704041cd591e5')}\r\n\r\n\r\ndef _handle_request_result_and_build_soup(request_result):\r\n if request_result.status_code == 200:\r\n html_doc = request_result.content\r\n soup = BeautifulSoup(html_doc, \"html.parser\")\r\n return soup\r\n\r\n\r\ndef get_top_contributors(url_page):\r\n res = requests.get(url_page)\r\n soup = _handle_request_result_and_build_soup(res)\r\n listcontrib = []\r\n for i in range(1, 257):\r\n number = \"#\" + str(i)\r\n namecontrib = soup.find(text=number).parent.findNext('td').text\r\n listcontrib.append(namecontrib)\r\n return listcontrib\r\n\r\n\r\ndef real_user_name(longname):\r\n position = longname.find(\"(\")\r\n return(longname[:position - 1])\r\n\r\n\r\ndef get_mean_stars_users(listcontrib):\r\n #Initialisation des variables\r\n dico_mean_stars = {}\r\n list_stars_mean = []\r\n #Récupération de la liste formatée des users et insertion dans un dictionnaire\r\n listcontrib_user_name = list(map(real_user_name,listcontrib))\r\n dico_mean_stars[\"login\"] = listcontrib_user_name\r\n #Récupération de la moyenne de stars de tous les repos de chaque user\r\n for i in range(len(listcontrib_user_name)):\r\n sum_stars = 0\r\n mean_stars = 0\r\n get_nbrepo = requests.get(\"https://api.github.com/users/\" + str(listcontrib_user_name[i]), headers=head)\r\n nb_repo = json.loads(get_nbrepo.content).get(\"public_repos\")\r\n # Prise en compte du cas où l'utilisateur n'a pas de repo\r\n if nb_repo == 0:\r\n mean_stars = 0\r\n else:\r\n page = 1\r\n get_repo = requests.get(\"https://api.github.com/users/\" + listcontrib_user_name[i] +\r\n \"/repos?perpage=100&page=\" + str(page), headers=head)\r\n repo_page = json.loads(get_repo.content)\r\n #On cherche à calculaer la somme de tous les stars en prenant en comtpe la pagination\r\n while repo_page != []: #le contenu du get est une liste vide lorsque la page ne contient pas de repos\r\n for j in range(len(repo_page)):\r\n sum_stars += repo_page[j].get(\"stargazers_count\")\r\n page += 1\r\n get_repo = requests.get(\"https://api.github.com/users/\" + listcontrib_user_name[i] +\r\n \"/repos?perpage=100&page=\" + str(page), headers=head)\r\n repo_page = json.loads(get_repo.content)\r\n mean_stars = sum_stars/nb_repo\r\n list_stars_mean.append(mean_stars)\r\n #Mise en place dans le dictionnaire des moyennes de stars de chaque utilisateur\r\n dico_mean_stars[\"mean\"] = list_stars_mean\r\n df_users_stars_mean = pd.DataFrame.from_dict(dico_mean_stars)\r\n print(df_users_stars_mean.sort_values([\"mean\"], ascending=False))\r\n\r\n\r\nlistcontrib = get_top_contributors(website)\r\nget_mean_stars_users(listcontrib)\r\n", "sub_path": "crawling_api_github.py", "file_name": "crawling_api_github.py", "file_ext": "py", "file_size_in_byte": 3097, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "bs4.BeautifulSoup", "line_number": 14, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 45, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 46, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 52, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 54, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 60, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 62, "usage_type": "call"}, {"api_name": "pandas.DataFrame.from_dict", "line_number": 67, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 67, "usage_type": "attribute"}]}
+{"seq_id": "84992731", "text": "__author__ = 'prakhardogra'\n\nfrom pymongo import MongoClient\nimport os.path\nimport json\nimport pprint\nfrom download_all import download_both\n\nalltweets = []\n\nfolder_path = \"/home/prakhardogra/PycharmProjects/project4/\"\n\nfilename = os.path.join(folder_path, 'all_tweets.json')\n\ndef get_tweets():\n\n client = MongoClient()\n\n db = client.test3\n\n c = db.tweets1\n\n tweets = c.find({},{\"text\":1,\"_id\":0})\n\n list = []\n hashlist = []\n\n for tweet in tweets:\n for word in tweet[\"text\"].split(\" \"):\n if \"@\" in word: #check for user mention\n if \".\" in word:\n word = word.replace('.','')\n if \":\" in word:\n word = word.replace(':','')\n if \",\" in word:\n word = word.replace(',','')\n if \"'s\" in word:\n word = word.replace(\"'s\",'')\n if \"?\" in word:\n word = word.replace('?','')\n if \")\" in word:\n word = word.replace(')','')\n if word.lower() not in list:\n if \"w/\" not in word:\n list.append(word.lower())\n if \"#\" in word: #check for hashtag\n if \".\" in word:\n word = word.replace('.','')\n if \":\" in word:\n word = word.replace(':','')\n if \",\" in word:\n word = word.replace(',','')\n if \"'s\" in word:\n word = word.replace(\"'s\",'')\n if \"?\" in word:\n word = word.replace('?','')\n if \")\" in word:\n word = word.replace(')','')\n if word.lower() not in list:\n if \"w/\" not in word:\n list.append(word.lower())\n hashlist.append(word.lower())\n\n print (list)\n\n with open(filename, 'w') as f:\n for word in list:\n if \"@\" in word:\n tweets = download_both(word)\n for tweet in tweets:\n if tweet['user']['listed_count'] == 0:\n tweet['user']['listed_count'] = 1\n alltweets.append({\"text\":tweet['text'],\"ratio\":tweet['user']['followers_count']/tweet['user']['listed_count'],\"fac\":tweet['favorite_count'],\"rc\":tweet['retweet_count'],\"hashtags\":tweet['entities']['hashtags']})\n if \"#\" in word:\n\n tweets = download_both(word)\n for tweet in tweets:\n if tweet.user.listed_count == 0:\n tweet.user.listed_count = 1\n alltweets.append({\"text\":tweet.text,\"fac\":tweet.favorite_count,\"ratio\":(tweet.user.followers_count)/(tweet.user.listed_count),\"rc\":tweet.retweet_count,\"hashtags\":hashlist})\n json.dump(alltweets, f)\n\n return list\n", "sub_path": "processing_tweets.py", "file_name": "processing_tweets.py", "file_ext": "py", "file_size_in_byte": 2940, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.path.join", "line_number": 13, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 13, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 13, "usage_type": "name"}, {"api_name": "pymongo.MongoClient", "line_number": 17, "usage_type": "call"}, {"api_name": "download_all.download_both", "line_number": 69, "usage_type": "call"}, {"api_name": "download_all.download_both", "line_number": 76, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 81, "usage_type": "call"}]}
+{"seq_id": "72705959", "text": "from django.contrib import admin\n\nfrom .models import (Car, Review,)\nfrom .forms import ReviewAdminForm\n\n\n@admin.register(Car)\nclass CarAdmin(admin.ModelAdmin):\n list_display = ['brand', 'model', 'review_count']\n list_filter = ['brand', 'model']\n search_fields = ['brand', 'model']\n ordering = ['-id']\n\n\n@admin.register(Review)\nclass ReviewAdmin(admin.ModelAdmin):\n form = ReviewAdminForm\n list_display = ['car', 'title']\n list_filter = ['car__brand']\n search_fields = ['car__brand', 'title']\n ordering = ['-id']\n\n", "sub_path": "site-form-works/car_admin/app/admin.py", "file_name": "admin.py", "file_ext": "py", "file_size_in_byte": 541, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.contrib.admin.ModelAdmin", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 8, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 7, "usage_type": "call"}, {"api_name": "models.Car", "line_number": 7, "usage_type": "argument"}, {"api_name": "django.contrib.admin", "line_number": 7, "usage_type": "name"}, {"api_name": "django.contrib.admin.ModelAdmin", "line_number": 16, "usage_type": "attribute"}, {"api_name": "django.contrib.admin", "line_number": 16, "usage_type": "name"}, {"api_name": "forms.ReviewAdminForm", "line_number": 17, "usage_type": "name"}, {"api_name": "django.contrib.admin.register", "line_number": 15, "usage_type": "call"}, {"api_name": "models.Review", "line_number": 15, "usage_type": "argument"}, {"api_name": "django.contrib.admin", "line_number": 15, "usage_type": "name"}]}
+{"seq_id": "31414936", "text": "import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nnum_input = 6\nnum_output = 3\nnum_hidden1 = 16\nnum_hidden2 = 16\nk_folds = 10\nN_EPOCHS = 500\n\nCROSS_VALIDATION_ACTIVE = True\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\n\nsession = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\nX = tf.placeholder(tf.float32, shape=[None, num_input], name='X')\ny = tf.placeholder(tf.float32, shape=[None, num_output], name='y')\n\n#y_dumb = tf.placeholder(tf.float32, shape=[None, num_output], name='y_dumb')\ndata_csv = pd.read_csv('./out_re.csv')\ndataX = data_csv[['in1','in2','in3','in4','in5','in6']]\ndatay = data_csv[['out1','out2','out3']]\ndata = data_csv[['in1','in2','in3','in4','in5','in6','out1','out2','out3']]\nX_in = []\ny_in = []\n\ndef shuffle_data():\n global data,dataX,datay,X_in,y_in\n data = data.sample(frac=1).reset_index(drop=True)\n dataX = data[['in1','in2','in3','in4','in5','in6']]\n datay = data[['out1','out2','out3']]\n\n X_in_df = dataX.values\n y_in_df = datay.values\n X_in = X_in_df.tolist()\n y_in = y_in_df.tolist()\n\nshuffle_data()\n\nFOLDS_SIZE = len(X_in) // k_folds\n\nrmse_a = []\npred_list = []\n\ndef cost_func(layer, my_y_true):\n ret = tf.sqrt(tf.reduce_mean(tf.square(layer - my_y_true)))\n return ret\n\n\n# Neural Network Structure\ninputs = X\n\n# Input Layer\ninput_layer = inputs\n#input_layer = tf.Variable(inputs)\n\n# Hidden Layer #1\nh1 = tf.layers.dense(inputs=input_layer, \n units=num_hidden1,\n use_bias=True,\n activation=tf.nn.elu)\n \n# Hidden Layer #2\nh2 = tf.layers.dense(inputs=h1, \n units=num_hidden2,\n use_bias=True,\n activation=tf.nn.elu)\n \n# Output Layer\noutput_layer = tf.layers.dense(inputs=h2, \n units=num_output,\n use_bias=True,\n activation=None)\n\ncost = cost_func(output_layer,y)\n#session.run(output_layer)\n#feed_dict_train = {x: X_train,y_true:y_train}\n\noptimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(cost)\nsession.run(tf.global_variables_initializer())\n\ndef train():\n global rmse_a\n\n feed_dict_train = {X: X_train, y:y_train}\n\n \n _, cost_error = session.run([optimizer,cost], feed_dict=feed_dict_train)\n\n rmse_a += [cost_error]\n\ndef predict():\n global pred_list\n feed_dict_test = {X: X_test, y:y_test}\n pred_cost = session.run(cost,feed_dict=feed_dict_test)\n pred_list += [pred_cost]\n print (\"Test Error : \" , pred_cost )\n\n\n\nfor epoch in range(N_EPOCHS):\n print (\"EPOCH :\", epoch+1)\n \n cur_st = 0\n if CROSS_VALIDATION_ACTIVE :\n shuffle_data()\n while True:\n VALIDATION_L = cur_st\n VALIDATION_R = min(cur_st + FOLDS_SIZE,len(X_in))\n #print (VALIDATION_L, VALIDATION_R)\n #print (type(X_in))\n X_train_l = X_in[:VALIDATION_L] + X_in[VALIDATION_R:]\n y_train_l = y_in[:VALIDATION_L] + y_in[VALIDATION_R:]\n X_test_l = X_in[VALIDATION_L:VALIDATION_R]\n y_test_l = y_in[VALIDATION_L:VALIDATION_R]\n #print (\"-->\",len(X_train),len(X_test) )\n\n X_train = np.array(X_train_l)\n y_train = np.array(y_train_l)\n X_test = np.array(X_test_l)\n y_test = np.array(y_test_l)\n\n train()\n predict()\n\n cur_st += FOLDS_SIZE\n if cur_st >= len(X_in):\n break\n else :\n VALIDATION_NUM = (int) (0.2*len(X_in))\n print (VALIDATION_NUM)\n X_train = X_in[:VALIDATION_NUM]\n y_train = y_in[:VALIDATION_NUM]\n X_test = X_in[VALIDATION_NUM:]\n y_test = y_in[VALIDATION_NUM:]\n train()\n predict()\n\nprint (rmse_a[-1])\nprint (pred_list[-1])\nplt.plot(list(enumerate(range(len(rmse_a)))),rmse_a)\n#plt.plot(list(enumerate(range(len(pred_list)))),pred_list)\nplt.show()\n'''\ndef cross_val(k, _X, _y):\n print (_X)\n try:\n if _X.shape[0] != _y.shape[0]:\n raise ValueError('The size of input and output is not the same !',(_X.shape[0],_y.shape[0]))\n except(ValueError):\n exit('Please check the input and output') \n return _X, _y \n\ndef test_my_cross_val():\n print ('oraoraoraora')\n #cross_val(10, X, y)\n#print (dataX.values)\n#cross_val(10, X, y)\n\nfeed_dict = {X : dataX.values, y : datay.values}\n\nsession.run(tf.global_variables_initializer())\n\nsession.run(test_my_cross_val, feed_dict=feed_dict)\n'''\n'''\nfeed_dict = {X : X_in, y : y_in}\nsession.run(tf.global_variables_initializer(), feed_dict=feed_dict)\n'''", "sub_path": "testing_ground/pred/cross_validation_gpu.py", "file_name": "cross_validation_gpu.py", "file_ext": "py", "file_size_in_byte": 4643, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "tensorflow.GPUOptions", "line_number": 15, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 17, "usage_type": "call"}, {"api_name": "tensorflow.ConfigProto", "line_number": 17, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 19, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 20, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 23, "usage_type": "call"}, {"api_name": "tensorflow.sqrt", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.layers.dense", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 64, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.dense", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 67, "usage_type": "attribute"}, {"api_name": "tensorflow.nn", "line_number": 70, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.dense", "line_number": 73, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 73, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 82, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 82, "usage_type": "attribute"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 122, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 144, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 144, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 146, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 146, "usage_type": "name"}]}
+{"seq_id": "64922827", "text": "from flask import g, url_for, current_app\nfrom flask_restful import Resource, reqparse\nfrom .. import db\nfrom ..models import Post, Permission, Comment\nfrom . import restful\nfrom .decorators import permission_required\n\n\nclass CommentsView(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', default=1, type=int, location='args')\n super().__init__()\n\n def get(self):\n page = self.parser.parse_args().get('page')\n pagination = Comment.query.order_by(Comment.timestamp.desc()).paginate(\n page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n prev = None\n if pagination.has_prev:\n prev = url_for('api.comments_view', page=page - 1)\n next = None\n if pagination.has_next:\n next = url_for('api.comments_view', page=page + 1)\n return {\n 'comments': [comment.to_json() for comment in comments],\n 'prev': prev,\n 'next': next,\n 'count': pagination.total\n }\n\n\nclass CommentView(Resource):\n def get(self, id):\n comment = Comment.query.get_or_404(id)\n return comment.to_json()\n\n\nclass PostCommentsView(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', default=1, type=int, location='args')\n self.parser.add_argument('body', type=str, location='json')\n super().__init__()\n\n def get(self, id):\n post = Post.query.get_or_404(id)\n page = self.parser.parse_args().get('page')\n pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(\n page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n prev = None\n if pagination.has_prev:\n prev = url_for('api.post_comments_view', id=id, page=page - 1)\n next = None\n if pagination.has_next:\n next = url_for('api.post_comments_view', id=id, page=page + 1)\n return {\n 'comments': [comment.to_json() for comment in comments],\n 'prev': prev,\n 'next': next,\n 'count': pagination.total\n }\n\n @permission_required(Permission.COMMENT)\n def post(self, id):\n args = self.parser.parse_args()\n post = Post.query.get_or_404(id)\n comment = Comment.from_json(args)\n comment.author = g.current_user\n comment.post = post\n db.session.add(comment)\n db.session.commit()\n return comment.to_json(), 201, \\\n {'Location': url_for('api.comment_view', id=comment.id)}\n\n\nrestful.add_resource(CommentsView, '/comments/', endpoint='comments_view')\nrestful.add_resource(CommentView, '/comments/', endpoint='comment_view')\nrestful.add_resource(PostCommentsView, '/posts//comments/', endpoint='post_comments_view')", "sub_path": "app/api/comments.py", "file_name": "comments.py", "file_ext": "py", "file_size_in_byte": 3016, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask_restful.Resource", "line_number": 9, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 11, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 11, "usage_type": "name"}, {"api_name": "models.Comment.query.order_by", "line_number": 17, "usage_type": "call"}, {"api_name": "models.Comment.query", "line_number": 17, "usage_type": "attribute"}, {"api_name": "models.Comment", "line_number": 17, "usage_type": "name"}, {"api_name": "models.Comment.timestamp.desc", "line_number": 17, "usage_type": "call"}, {"api_name": "models.Comment.timestamp", "line_number": 17, "usage_type": "attribute"}, {"api_name": "flask.current_app.config", "line_number": 18, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 18, "usage_type": "name"}, {"api_name": "flask.url_for", "line_number": 23, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 26, "usage_type": "call"}, {"api_name": "flask_restful.Resource", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Comment.query.get_or_404", "line_number": 37, "usage_type": "call"}, {"api_name": "models.Comment.query", "line_number": 37, "usage_type": "attribute"}, {"api_name": "models.Comment", "line_number": 37, "usage_type": "name"}, {"api_name": "flask_restful.Resource", "line_number": 41, "usage_type": "name"}, {"api_name": "flask_restful.reqparse.RequestParser", "line_number": 43, "usage_type": "call"}, {"api_name": "flask_restful.reqparse", "line_number": 43, "usage_type": "name"}, {"api_name": "models.Post.query.get_or_404", "line_number": 49, "usage_type": "call"}, {"api_name": "models.Post.query", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 49, "usage_type": "name"}, {"api_name": "models.Comment.timestamp.asc", "line_number": 51, "usage_type": "call"}, {"api_name": "models.Comment.timestamp", "line_number": 51, "usage_type": "attribute"}, {"api_name": "models.Comment", "line_number": 51, "usage_type": "name"}, {"api_name": "flask.current_app.config", "line_number": 52, "usage_type": "attribute"}, {"api_name": "flask.current_app", "line_number": 52, "usage_type": "name"}, {"api_name": "flask.url_for", "line_number": 57, "usage_type": "call"}, {"api_name": "flask.url_for", "line_number": 60, "usage_type": "call"}, {"api_name": "models.Post.query.get_or_404", "line_number": 71, "usage_type": "call"}, {"api_name": "models.Post.query", "line_number": 71, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 71, "usage_type": "name"}, {"api_name": "models.Comment.from_json", "line_number": 72, "usage_type": "call"}, {"api_name": "models.Comment", "line_number": 72, "usage_type": "name"}, {"api_name": "flask.g.current_user", "line_number": 73, "usage_type": "attribute"}, {"api_name": "flask.g", "line_number": 73, "usage_type": "name"}, {"api_name": "flask.url_for", "line_number": 78, "usage_type": "call"}, {"api_name": "decorators.permission_required", "line_number": 68, "usage_type": "call"}, {"api_name": "models.Permission.COMMENT", "line_number": 68, "usage_type": "attribute"}, {"api_name": "models.Permission", "line_number": 68, "usage_type": "name"}]}
+{"seq_id": "180326896", "text": "## ---------------------------------------------------------------------------\n## Licensed to the Apache Software Foundation (ASF) under one or more\n## contributor license agreements. See the NOTICE file distributed with\n## this work for additional information regarding copyright ownership.\n## The ASF licenses this file to You under the Apache License, Version 2.0\n## (the \"License\"); you may not use this file except in compliance with\n## the License. You may obtain a copy of the License at\n##\n## http://www.apache.org/licenses/LICENSE-2.0\n##\n## Unless required by applicable law or agreed to in writing, software\n## distributed under the License is distributed on an \"AS IS\" BASIS,\n## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n## See the License for the specific language governing permissions and\n## limitations under the License.\n## ---------------------------------------------------------------------------\n\n# Put the 活动行名单.xlsx file in the project root directory,will be generated in the root directory name_split.csv file\n\nimport csv\nimport openpyxl\n\n # First, define a CSV file\nhead =[\"Email\",\"FirstName\",\"LastName\"]\nwith open(\"./name_split.csv\",\"a+\",encoding=\"utf-8\",newline=\"\") as f:\n csvf=csv.writer(f)\n csvf.writerow(head)\n\n\n# Open the EXECL file\ncollect=openpyxl.load_workbook(\"./活动行名单.xlsx\")\n\n# Gets the active table object\ncollect_active=collect.active\n\nfor cell in collect_active['C']:\n if cell.row!=1:\n email=cell.value\n cell_row=cell.row\n name=collect_active.cell(cell_row,2).value\n\n # Judge whether it is a Chinese name\n if '\\u4e00' <= name <='\\u9fff':\n name_list=list(name)\n firstName=name_list[0]\n lastName=\"\"\n for i in name_list[1:]:\n lastName=lastName+i\n else:\n firstName=name\n lastName=\"\"\n\n # Write data to a CSV file\n data=[\n (email,firstName,lastName)\n ]\n with open(\"./name_split.csv\",\"a+\",encoding=\"utf-8\",newline=\"\") as f:\n csvf=csv.writer(f)\n csvf.writerows(data)\n\n ", "sub_path": "script/name_split.py", "file_name": "name_split.py", "file_ext": "py", "file_size_in_byte": 2098, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "csv.writer", "line_number": 26, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 31, "usage_type": "call"}, {"api_name": "csv.writer", "line_number": 58, "usage_type": "call"}]}
+{"seq_id": "484219903", "text": "from __future__ import print_function, division \nimport sys\nimport math\nimport heapq\nimport random \nimport numpy as np \nimport matplotlib.pyplot as plt\nsys.dont_write_bytecode = True\n\n# import main_no_prune as main\nimport main\nimport node \n# import univ\nimport utils \nimport obstacles as obs\n\n\ndef getRandomNode(x_lim, y_lim, curr_node, goal_node, goal_probability=0.5):\n\tprob = np.random.sample()\n\t\n\t# exploration\n\tif prob > goal_probability:\n\t\tx_lim_low, x_lim_high = x_lim\n\t\ty_lim_low, y_lim_high = y_lim\n\t\n\t# heading towards to goal\n\telse:\n\t\tgn_x, gn_y = goal_node.getXYCoords()\n\t\tcn_x, cn_y = curr_node.getXYCoords()\n\n\t\tif (gn_y - cn_y) > 0:\n\t\t\ty_lim_low = cn_y\n\t\t\ty_lim_high = gn_y + ((y_lim[1] - gn_y) / 3)\n\t\telse:\n\t\t\ty_lim_low = gn_y - ((gn_y - y_lim[0]) / 3)\n\t\t\ty_lim_high = cn_y\n\n\t\tif (gn_x - cn_x) > 0:\n\t\t\tx_lim_low = cn_x\n\t\t\tx_lim_high = gn_x + ((x_lim[1] - gn_x) / 3)\n\t\telse:\n\t\t\tx_lim_low = gn_x - ((gn_x - x_lim[0]) / 3)\n\t\t\tx_lim_high = cn_x\n\n\trn_x = np.random.uniform(low=x_lim_low, high=x_lim_high)\n\trn_y = np.random.uniform(low=y_lim_low, high=y_lim_high)\n\n\treturn node.Node(current_coords=(rn_x, rn_y), parent_coords=None, distance=0)\n\n\ndef getStepNode(closest_node, rand_node, step_size):\n\t# dist = utils.euclideanDistance(point_1=closest_node.getXYCoords(), point_2=rand_node.getXYCoords())\n\n\tcn_x, cn_y = closest_node.getXYCoords()\n\trn_x, rn_y = rand_node.getXYCoords()\n\n\t# slope = (rn_y - cn_y) / (rn_x - cn_x)\n\ttheta = np.arctan2((rn_y - cn_y), (rn_x - cn_x))\n\n\t# intercept = cn_y - (slope * cn_x)\n\n\tsn_x = cn_x + (step_size * np.cos(theta))\n\tsn_y = cn_y + (step_size * np.sin(theta))\n\n\treturn node.Node(current_coords=(sn_x, sn_y), parent_coords=(cn_x, cn_y), distance=step_size)\n\n\ndef hitsObstacle(start_node, goal_node, step_size=0.1):\n\tsn_x, sn_y = start_node.getXYCoords()\n\tgn_x, gn_y = goal_node.getXYCoords()\n\n\ttheta = np.arctan2((gn_y - sn_y), (gn_x - sn_x))\n\n\tnn_x, nn_y = sn_x, sn_y\n\twhile (utils.euclideanDistance(point_1=(nn_x, nn_y), point_2=(gn_x, gn_y)) > 0.001):\n\t\t# next node\n\t\tnn_x = nn_x + (step_size * np.cos(theta))\n\t\tnn_y = nn_y + (step_size * np.sin(theta))\n\n\t\tif obs.withinObstacleSpace(point=(nn_x, nn_y), radius=main.DRONE_RADIUS, clearance=main.DRONE_RADIUS / 2):\n\t\t\treturn True\n\n\treturn False\n\n\ndef findClosestNode(rrt_nodes, rand_node):\n\tclosest_dist = 99999\n\tclosest_node = None\n\n\tfor rrt_node in rrt_nodes:\n\t\tnode_dist = utils.euclideanDistance(point_1=rrt_node.getXYCoords(), point_2=rand_node.getXYCoords())\n\n\t\tif node_dist < closest_dist:\n\t\t\tclosest_dist = node_dist\n\t\t\tclosest_node = rrt_node\n\n\treturn (closest_node, closest_dist)\n\n\ndef backtrack(rrt_nodes, goal_node):\n\tpath = []\n\n\ttemp_node = goal_node\n\twhile (temp_node.parent_coords is not None):\n\t\tpath.insert(0, temp_node)\n\t\ttemp_node = rrt_nodes[temp_node.parent_coords]\n\n\tpath.insert(0, temp_node)\n\n\treturn path\n\n\ndef prunePath(path_list):\n\tpass", "sub_path": "Code/rrt.py", "file_name": "rrt.py", "file_ext": "py", "file_size_in_byte": 2861, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.dont_write_bytecode", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.random.sample", "line_number": 19, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 45, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 45, "usage_type": "attribute"}, {"api_name": "numpy.random.uniform", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 46, "usage_type": "attribute"}, {"api_name": "node.Node", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 63, "usage_type": "call"}, {"api_name": "node.Node", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.arctan2", "line_number": 72, "usage_type": "call"}, {"api_name": "utils.euclideanDistance", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 78, "usage_type": "call"}, {"api_name": "obstacles.withinObstacleSpace", "line_number": 80, "usage_type": "call"}, {"api_name": "main.DRONE_RADIUS", "line_number": 80, "usage_type": "attribute"}, {"api_name": "utils.euclideanDistance", "line_number": 91, "usage_type": "call"}]}
+{"seq_id": "261002223", "text": "import cv2\nimport sys\n\nimage='../../images/'+sys.argv[1]\n\nimg=cv2.imread(image, cv2.IMREAD_UNCHANGED)\n\nsobx=cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)\n\ntmp=sys.argv[1]\next=sys.argv[2]\nname=tmp[:len(tmp)-len(ext)-1]\noutput=name+'_sobx'+'.'+ext\ntarget='../../images/'+output\n\nif cv2.imwrite(target, sobx): print(output, end='')\nelse: print('failed',end='')\n", "sub_path": "filters/img_grad_py/sobx.py", "file_name": "sobx.py", "file_ext": "py", "file_size_in_byte": 351, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.argv", "line_number": 4, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 6, "usage_type": "call"}, {"api_name": "cv2.IMREAD_UNCHANGED", "line_number": 6, "usage_type": "attribute"}, {"api_name": "cv2.Sobel", "line_number": 8, "usage_type": "call"}, {"api_name": "cv2.CV_64F", "line_number": 8, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 10, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 11, "usage_type": "attribute"}, {"api_name": "cv2.imwrite", "line_number": 16, "usage_type": "call"}]}
+{"seq_id": "220949921", "text": "from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Aspect\n\nfrom dictionary.serializers import AspectSerializer\n\nASPECT_URL = reverse('dictionary:aspect-list')\n\n\ndef detail_url(aspect_id):\n \"\"\"Return aspect detail URL\"\"\"\n return reverse('dictionary:aspect-detail', args=[aspect_id])\n\n\ndef sample_aspect(name='vulg'):\n \"\"\"Create and return sample aspect\"\"\"\n return Aspect.objects.create(name=name)\n\n\nclass PublicAspectApiTest(TestCase):\n \"\"\"Test unauthenticated Aspect API access\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_auth_not_required(self):\n \"\"\"Test that authentication is not required for GET method\"\"\"\n res = self.client.get(ASPECT_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n\n def test_retrieve_aspect(self):\n \"\"\"Test retrieving a list of aspects\"\"\"\n sample_aspect(name='dok')\n sample_aspect(name='not')\n\n res = self.client.get(ASPECT_URL)\n\n asp = Aspect.objects.all().order_by('-name')\n serializer = AspectSerializer(asp, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_view_aspect_detail(self):\n \"\"\"Test viewing a aspect detail\"\"\"\n asp = sample_aspect(name='ksiaz')\n\n url = detail_url(asp.id)\n res = self.client.get(url)\n\n serializer = AspectSerializer(asp)\n self.assertEqual(res.data, serializer.data)\n\n\nclass PrivateAspectApiTest(TestCase):\n \"\"\"Test the authorized user Aspect API\"\"\"\n\n def setUp(self):\n self.user = get_user_model().objects.create_user(\n 'test@test.pl',\n 'pass1234'\n )\n self.client = APIClient()\n self.client.force_authenticate(self.user)\n\n def test_create_aspect_successful(self):\n \"\"\"Test create a new aspect\"\"\"\n payload = {'name': 'vulg'}\n self.client.post(ASPECT_URL, payload)\n\n exists = Aspect.objects.filter(\n name=payload['name']\n ).exists()\n self.assertTrue(exists)\n\n def test_partial_update_aspect(self):\n \"\"\"Test update a aspect with patch\"\"\"\n asp = sample_aspect(name='reg')\n\n payload = {\n 'name': 'vulg',\n }\n\n url = detail_url(asp.id)\n self.client.patch(url, payload)\n\n asp.refresh_from_db()\n self.assertEqual(asp.name, payload['name'])\n\n def test_full_update_aspect(self):\n \"\"\"Test updating a aspect with put\"\"\"\n asp = sample_aspect(name='not')\n\n payload = {\n 'name': 'yes',\n }\n\n url = detail_url(asp.id)\n self.client.put(url, payload)\n\n asp.refresh_from_db()\n self.assertEqual(asp.name, payload['name'])\n", "sub_path": "app/dictionary/tests/test_aspect.py", "file_name": "test_aspect.py", "file_ext": "py", "file_size_in_byte": 2923, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.urls.reverse", "line_number": 12, "usage_type": "call"}, {"api_name": "django.urls.reverse", "line_number": 17, "usage_type": "call"}, {"api_name": "core.models.Aspect.objects.create", "line_number": 22, "usage_type": "call"}, {"api_name": "core.models.Aspect.objects", "line_number": 22, "usage_type": "attribute"}, {"api_name": "core.models.Aspect", "line_number": 22, "usage_type": "name"}, {"api_name": "django.test.TestCase", "line_number": 25, "usage_type": "name"}, {"api_name": "rest_framework.test.APIClient", "line_number": 29, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 35, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 35, "usage_type": "name"}, {"api_name": "core.models.Aspect.objects.all", "line_number": 44, "usage_type": "call"}, {"api_name": "core.models.Aspect.objects", "line_number": 44, "usage_type": "attribute"}, {"api_name": "core.models.Aspect", "line_number": 44, "usage_type": "name"}, {"api_name": "dictionary.serializers.AspectSerializer", "line_number": 45, "usage_type": "call"}, {"api_name": "rest_framework.status.HTTP_200_OK", "line_number": 46, "usage_type": "attribute"}, {"api_name": "rest_framework.status", "line_number": 46, "usage_type": "name"}, {"api_name": "dictionary.serializers.AspectSerializer", "line_number": 56, "usage_type": "call"}, {"api_name": "django.test.TestCase", "line_number": 60, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 64, "usage_type": "call"}, {"api_name": "rest_framework.test.APIClient", "line_number": 68, "usage_type": "call"}, {"api_name": "core.models.Aspect.objects.filter", "line_number": 76, "usage_type": "call"}, {"api_name": "core.models.Aspect.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "core.models.Aspect", "line_number": 76, "usage_type": "name"}]}
+{"seq_id": "536084419", "text": "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\n\nimport torch\nimport torch.nn.functional as F\nfrom fairseq import metrics, utils\nfrom fairseq.criterions import FairseqCriterion, register_criterion\nimport random\n\ndef label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):\n if target.dim() == lprobs.dim() - 1:\n target = target.unsqueeze(-1)\n nll_loss = -lprobs.gather(dim=-1, index=target)\n smooth_loss = -lprobs.sum(dim=-1, keepdim=True)\n if ignore_index is not None:\n pad_mask = target.eq(ignore_index)\n nll_loss.masked_fill_(pad_mask, 0.)\n smooth_loss.masked_fill_(pad_mask, 0.)\n else:\n nll_loss = nll_loss.squeeze(-1)\n smooth_loss = smooth_loss.squeeze(-1)\n if reduce:\n nll_loss = nll_loss.sum()\n smooth_loss = smooth_loss.sum()\n eps_i = epsilon / lprobs.size(-1)\n loss = (1. - epsilon) * nll_loss + eps_i * smooth_loss\n return loss, nll_loss\n\n\n@register_criterion('cross_entropy_dirty_s')\nclass CrossEntropyDirtyS(FairseqCriterion):\n\n def __init__(self, task, sentence_avg, label_smoothing,threshold,sensword):\n super().__init__(task)\n self.sentence_avg = sentence_avg\n self.eps = label_smoothing\n self.threshold = threshold\n self.sensword = sensword\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add criterion-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--label-smoothing', default=0., type=float, metavar='D',\n help='epsilon for label smoothing, 0 means no label smoothing')\n parser.add_argument('--threshold', default=1.2, type=float, metavar='D',\n help='the threshold of dirty sentences')\n parser.add_argument('--sensword', default='sentence', type=str, metavar='D',\n help='the threshold of dirty sentences')\n # fmt: on\n\n def forward(self, model, sample, reduce=True):\n \"\"\"Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) the loss\n 2) the sample size, which is used as the denominator for the gradient\n 3) logging outputs to display while training\n \"\"\"\n\n if model.training:\n with torch.no_grad():\n ss = self.task.source_dictionary.encode_line(\n '你 真 漂亮', \n add_if_not_exist=False\n ).long().to(sample['net_input']['prev_output_tokens'])\n ss_len = torch.tensor([len(ss)]).long().to(sample['net_input']['prev_output_tokens'])\n xx = self.task.target_dictionary.encode_line(\n \"you are so beautiful .\", \n add_if_not_exist=False\n ).long().to(sample['net_input']['prev_output_tokens'])\n sample['target'] = torch.cat(tuple(xx[None,:] for i in range(10)),0).to(xx)\n xx[0],xx[1:] = 2, xx[:-1].clone()\n \n sample['net_input']['src_tokens'] = torch.cat(tuple(ss[None,:] for i in range(10)),0).to(ss)\n sample['net_input']['src_lengths'] = torch.cat(tuple(ss_len for i in range(10)),0).to(ss_len)\n sample['net_input']['prev_output_tokens'] = torch.cat(tuple(xx[None,:] for i in range(10)),0).to(xx)\n\n # print(xx)\n # print(sample['net_input'].keys())\n # print(sample['net_input']['prev_output_tokens'][0])\n # print(self.task.target_dictionary.string(sample['net_input']['prev_output_tokens'][0]))\n # print(sample['net_input']['prev_output_tokens'].shape)\n # print(sample['target'][0])\n # print(sample['target'].shape)\n # assert False\n noised_logits, noised_extra = model(**sample[\"net_input\"])\n input_logits, extra = model(**sample['net_input'])\n input_logits1, extra1 = model(**sample['net_input'])\n b,s = input_logits.shape[:2]\n mask_dirty = torch.ones(b,s).to(input_logits)\n\n for i in range(noised_logits.shape[0]):\n if self.sensword == 'sentence':\n print(1),\n\n elif self.sensword == 'word':\n klkl = self._get_symm_kl_except_first(noised_logits[i,:,:],input_logits[i,:,:],input_logits1[i,:,:])\n\n if klkl.data>self.threshold:\n mask_dirty[i,:] = 0\n\n klkl = self._get_symm_kl_list(noised_logits[i,:,:],input_logits[i,:,:])\n kl_res = klkl.sum(-1)\n print(kl_res,kl_res.sum() / noised_logits.size(1))\n\n mask_dirty[i] = (kl_res < 3).float()\n klkl = klkl.sum()\n\n\n src_token = sample['net_input']['src_tokens'][i]\n src_str = self.task.source_dictionary.string(src_token)\n\n tgt_token = sample['target'][i]\n tgt_str = self.task.target_dictionary.string(tgt_token)\n\n if mask_dirty[i].min() == 0:\n print(src_str)\n print(tgt_str)\n # print(mask_dirty[i])\n tgt_l = tgt_str.split(' ')\n ss = ''\n for i,j in zip(tgt_l,mask_dirty[i][:-1]):\n if j == 0:\n ss += ' --'+ i +'--'\n else:\n ss += ' '+i\n print(ss)\n\n # print(mask_dirty)\n # print(self.threshold)\n input_logits = mask_dirty[:,:,None] * input_logits\n\n assert False\n loss, nll_loss = self.compute_loss(model, (input_logits, extra), sample, reduce=reduce)\n sample_size = sample['target'].size(0) if self.sentence_avg else sample['ntokens']\n logging_output = {\n 'loss': loss.data,\n 'nll_loss': nll_loss.data,\n 'ntokens': sample['ntokens'],\n 'nsentences': sample['target'].size(0),\n 'sample_size': sample_size,\n }\n return loss, sample_size, logging_output\n\n def _get_symm_kl_except_first(self,noised_logits:torch.Tensor, input_logits:torch.Tensor,input_logits1:torch.Tensor):\n word_num = noised_logits.size(0) - 1\n klkl0 = self._get_symm_kl_list(noised_logits,input_logits)\n klkl0 = klkl0[1:,:].sum().data / word_num\n print('sentence1',klkl0)\n klkl1 = self._get_symm_kl_list(noised_logits,input_logits1)\n klkl1 = klkl1[1:,:].sum().data / word_num\n print('sentence1',klkl1)\n klkl2 = self._get_symm_kl_list(input_logits,input_logits1)\n klkl2 = klkl2[1:,:].sum().data / word_num\n print('sentence1',klkl2)\n print('sentence1',(klkl2+klkl0+klkl1)/3)\n return (klkl2+klkl0+klkl1)/3\n\n\n\n def _get_symm_kl_list(self, noised_logits:torch.Tensor, input_logits:torch.Tensor):\n # noised_logits, logits_index = noised_logits.topk(25,-1)\n # input_logits = input_logits.gather(1,logits_index)\n\n # input_logits = input_logits.topk(1000,-1)[0]\n\n return (\n F.kl_div(\n F.log_softmax(noised_logits, dim=-1, dtype=torch.float32),\n F.softmax(input_logits, dim=-1, dtype=torch.float32),\n None,\n False,\n None\n )\n + F.kl_div(\n F.log_softmax(input_logits, dim=-1, dtype=torch.float32),\n F.softmax(noised_logits, dim=-1, dtype=torch.float32),\n None,\n False,\n None\n )\n ) \n\n def _get_symm_kl(self, noised_logits, input_logits):\n # print(noised_logits.shape,input_logits.shape)\n return (\n F.kl_div(\n F.log_softmax(noised_logits, dim=-1, dtype=torch.float32),\n F.softmax(input_logits, dim=-1, dtype=torch.float32),\n None,\n None,\n \"sum\"\n )\n + F.kl_div(\n F.log_softmax(input_logits, dim=-1, dtype=torch.float32),\n F.softmax(noised_logits, dim=-1, dtype=torch.float32),\n None,\n None,\n \"sum\"\n )\n ) / noised_logits.size(0)\n\n def compute_loss(self, model, net_output, sample, reduce=True):\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1))\n target = model.get_targets(sample, net_output).view(-1, 1)\n loss, nll_loss = label_smoothed_nll_loss(\n lprobs, target, self.eps, ignore_index=self.padding_idx, reduce=reduce,\n )\n return loss, nll_loss\n\n @staticmethod\n def reduce_metrics(logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get('loss', 0) for log in logging_outputs)\n nll_loss_sum = sum(log.get('nll_loss', 0) for log in logging_outputs)\n ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)\n sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)\n\n metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('nll_loss', nll_loss_sum / ntokens / math.log(2), ntokens, round=3)\n metrics.log_derived('ppl', lambda meters: utils.get_perplexity(meters['nll_loss'].avg))\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n", "sub_path": "fairseq/criterions/drc/dirty_s_personal_sen.py", "file_name": "dirty_s_personal_sen.py", "file_ext": "py", "file_size_in_byte": 10068, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "fairseq.criterions.FairseqCriterion", "line_number": 35, "usage_type": "name"}, {"api_name": "torch.no_grad", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.tensor", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 76, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 79, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.ones", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.Tensor", "line_number": 150, "usage_type": "attribute"}, {"api_name": "torch.Tensor", "line_number": 166, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 173, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 174, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 174, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 174, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.softmax", "line_number": 175, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 175, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 175, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 180, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 180, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 181, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 181, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 181, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.softmax", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 182, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 182, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 192, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 193, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 193, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.softmax", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 194, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.kl_div", "line_number": 199, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 199, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 200, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 200, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 200, "usage_type": "attribute"}, {"api_name": "torch.nn.functional.softmax", "line_number": 201, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 201, "usage_type": "name"}, {"api_name": "torch.float32", "line_number": 201, "usage_type": "attribute"}, {"api_name": "fairseq.metrics.log_scalar", "line_number": 225, "usage_type": "call"}, {"api_name": "fairseq.metrics", "line_number": 225, "usage_type": "name"}, {"api_name": "math.log", "line_number": 225, "usage_type": "call"}, {"api_name": "fairseq.metrics.log_scalar", "line_number": 226, "usage_type": "call"}, {"api_name": "fairseq.metrics", "line_number": 226, "usage_type": "name"}, {"api_name": "math.log", "line_number": 226, "usage_type": "call"}, {"api_name": "fairseq.metrics.log_derived", "line_number": 227, "usage_type": "call"}, {"api_name": "fairseq.metrics", "line_number": 227, "usage_type": "name"}, {"api_name": "fairseq.utils.get_perplexity", "line_number": 227, "usage_type": "call"}, {"api_name": "fairseq.utils", "line_number": 227, "usage_type": "name"}, {"api_name": "fairseq.criterions.register_criterion", "line_number": 34, "usage_type": "call"}]}
+{"seq_id": "9295395", "text": "import logging\nimport nltk\nimport numpy as np\nimport hydro_serving_grpc as hs\nimport os\n\n# update searching path for nltk\nnltk.data.path = [\"/model/files/nltk_data\"] + nltk.data.path\n\n\ndef tokenize(x):\n\tsentences = np.array(x.string_val)\n\tsentences = sentences.reshape([dim.size for dim in x.tensor_shape.dim])\n\n\ttokenized = np.copy(sentences)\n\tfor index, sentence in enumerate(sentences):\n\t\ttokenized[index] = \" \".join(nltk.word_tokenize(str(sentence[0], encoding=\"utf-8\").lower()))\n\t\n\ttokenized = hs.TensorProto(\n\t\tdtype=hs.DT_STRING,\n\t\tstring_val=tokenized.flatten(),\n\t\ttensor_shape=hs.TensorShapeProto(dim=[hs.TensorShapeProto.Dim(size=-1), hs.TensorShapeProto.Dim(size=1)]))\n\treturn hs.PredictResponse(outputs={\"input_data\": tokenized})\n", "sub_path": "examples/seq2seq/tokenize/src/func_main.py", "file_name": "func_main.py", "file_ext": "py", "file_size_in_byte": 742, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "nltk.data", "line_number": 8, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 12, "usage_type": "call"}, {"api_name": "numpy.copy", "line_number": 15, "usage_type": "call"}, {"api_name": "nltk.word_tokenize", "line_number": 17, "usage_type": "call"}, {"api_name": "hydro_serving_grpc.TensorProto", "line_number": 19, "usage_type": "call"}, {"api_name": "hydro_serving_grpc.DT_STRING", "line_number": 20, "usage_type": "attribute"}, {"api_name": "hydro_serving_grpc.TensorShapeProto", "line_number": 22, "usage_type": "call"}, {"api_name": "hydro_serving_grpc.TensorShapeProto.Dim", "line_number": 22, "usage_type": "call"}, {"api_name": "hydro_serving_grpc.PredictResponse", "line_number": 23, "usage_type": "call"}]}
+{"seq_id": "283414854", "text": "import os\nimport torch\nimport albumentations as A\nimport albumentations.pytorch as AP\nimport cv2\nfrom tqdm import tqdm\nimport numpy as np\nfrom time import time\n\nfrom models import RetinaFace\nfrom layers.functions.prior_box import PriorBox\nfrom utils.nms.py_cpu_nms import py_cpu_nms\nfrom utils.box_utils import decode\nfrom data.config import cfg_mnet as cfg\n\ntransformerr = A.Compose(\n [\n A.Normalize(),\n AP.ToTensorV2()\n ],\n)\n\ndef transform(img):\n out = transformerr(image=img)\n return out['image']\n\ndef check_keys(model, pretrained_state_dict):\n ckpt_keys = set(pretrained_state_dict.keys())\n model_keys = set(model.state_dict().keys())\n used_pretrained_keys = model_keys & ckpt_keys\n unused_pretrained_keys = ckpt_keys - model_keys\n missing_keys = model_keys - ckpt_keys\n print('Missing keys:{}'.format(len(missing_keys)))\n print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))\n print('Used keys:{}'.format(len(used_pretrained_keys)))\n assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'\n return True\n\n\ndef remove_prefix(state_dict, prefix):\n ''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''\n print('remove prefix \\'{}\\''.format(prefix))\n f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x\n return {f(key): value for key, value in state_dict.items()}\n\ndef load_model(model, pretrained_path, load_to_cpu):\n print('Loading pretrained model from {}'.format(pretrained_path))\n if load_to_cpu:\n print('Load to cpu')\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n else:\n device = torch.cuda.current_device()\n pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))\n state_dict = pretrained_dict['state_dict']\n # state_dict = model.filter_state_dict_with_prefix(state_dict, 'student_model.model', True)\n print(state_dict.keys())\n model.migrate(state_dict, force=True)\n return model\n\n# def load_model(model, pretrained_path, device='cuda'):\n# print('Loading pretrained model from {}'.format(pretrained_path))\n# if device == 'cpu':\n# print('load to cpu')\n# pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n# else:\n# device = torch.cuda.current_device()\n# pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))\n# if \"state_dict\" in pretrained_dict.keys():\n# pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')\n# else:\n# pretrained_dict = remove_prefix(pretrained_dict, 'module.')\n# check_keys(model, pretrained_dict)\n# model.load_state_dict(pretrained_dict, strict=False)\n# return model\n\ndevice = 'cpu'\npriorbox = PriorBox(cfg, image_size=(96, 96))\npriors = priorbox.forward()\npriors = priors.to(device)\nprior_data = priors.data\n\ndef calculate_box(loc, conf):\n scores = conf[:, 1]\n ind = scores.argmax()\n boxes = decode(loc, prior_data, cfg['variance'])\n scores = scores[ind:ind+1]\n boxes = boxes[ind:ind+1]\n dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n return dets\n\ndef detect_iris(img, net):\n img = transform(img).unsqueeze(0)\n img = img.to(device)\n loc, conf = net(img) # forward pass\n loc = loc.squeeze(0).data.cpu()\n conf = conf.squeeze(0).data.cpu().numpy()\n split_index = loc.shape[0] // 2\n loc_left, loc_right = loc[:split_index], loc[split_index:]\n conf_left, conf_right = conf[:split_index], conf[split_index:]\n return calculate_box(loc_left, conf_left), calculate_box(loc_right, conf_right)\n\n# def detect_iris(img, net):\n# img = transform(img).unsqueeze(0)\n# img = img.to(device)\n\n# loc, conf = net(img) # forward pass\n\n# scores = conf.squeeze(0).data.cpu().numpy()[:, 1]\n# ind = scores.argmax()\n\n# boxes = decode(loc.data.squeeze(0), prior_data, cfg['variance'])\n# boxes = boxes.cpu().numpy()\n# scores = scores[ind:ind+1]\n# boxes = boxes[ind:ind+1]\n\n# dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)\n\n# return dets\n\n\ndef filter_iris_box(dets, threshold):\n widths = dets[:, 2] - dets[:, 0]\n heights = dets[:, 3] - dets[:, 1]\n mask = (heights / widths) > threshold\n dets = dets[mask]\n return dets\n\n\ndef filter_conf(dets, threshold):\n return dets[dets[:, 4] > threshold]\n\ndef paint_bbox(image, bboxes):\n for b in bboxes:\n text = \"{:.4f}\".format(b[4])\n b = list(map(int, b))\n cv2.rectangle(image, (b[0], b[1]), (b[2], b[3]), (0, 0, 255), 2)\n cx = b[0]\n cy = b[1] - 12\n cv2.putText(image, text, (cx, cy),\n cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255))\n\nif __name__ == '__main__':\n # net_path = os.path.join('weights_negpos', 'mobilenet0.25_Final.pth')\n # net_path = os.path.join('weights_negpos_cleaned', 'mobilenet0.25_Final.pth')\n # net_path = 'distill_logs/version_0/checkpoints/checkpoint-epoch=52-val_loss=7.4488.ckpt'\n # net_path = 'multi_ratio_prior_box_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=5.1367.ckpt'\n # net_path = 'test_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=4.4232.ckpt'\n net_path = 'logs/fpn_logs/version_0/checkpoints/checkpoint-epoch=99-val_loss=4.4232.ckpt'\n net = RetinaFace(cfg=cfg, phase = 'test')\n net = load_model(net, net_path, device)\n # net = net.cuda()\n net.eval()\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # label_predict\n open_open = 0\n open_close = 0\n close_open = 0\n close_close = 0\n conf_threshold = 0.80625\n width_height_threshold = 0.4875 \n\n rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputrgb', 'Open')\n out_open_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'open_open')\n out_close_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'open_close')\n if not os.path.isdir(out_open_image_dir):\n os.makedirs(out_open_image_dir)\n if not os.path.isdir(out_close_image_dir):\n os.makedirs(out_close_image_dir)\n listdir = os.listdir(rgb_image_dir)\n listdir = listdir[:len(listdir) // 2 * 2]\n for image_file_one, image_file_two in tqdm(zip(listdir[::2], listdir[1::2])):\n image_one = cv2.imread(os.path.join(rgb_image_dir, image_file_one))\n image_two = cv2.imread(os.path.join(rgb_image_dir, image_file_two))\n image = np.concatenate([image_one, image_two], axis=0)\n one_dets, two_dets = detect_iris(image, net)\n one_dets = filter_iris_box(one_dets, width_height_threshold)\n one_dets = filter_conf(one_dets, conf_threshold)\n two_dets = filter_iris_box(one_dets, width_height_threshold)\n two_dets = filter_conf(two_dets, conf_threshold)\n\n if one_dets.shape[0] > 0:\n open_open += 1\n # paint_bbox(image, dets)\n else:\n open_close += 1\n # paint_bbox(image, dets)\n\n if two_dets.shape[0] > 0:\n open_open += 1\n # paint_bbox(image, dets)\n else:\n open_close += 1\n # paint_bbox(image, dets)\n\n rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputrgb', 'Close')\n out_open_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'close_open')\n out_close_image_dir = os.path.join('../datasets', 'out', 'outputrgb', 'close_close')\n if not os.path.isdir(out_open_image_dir):\n os.makedirs(out_open_image_dir)\n if not os.path.isdir(out_close_image_dir):\n os.makedirs(out_close_image_dir)\n listdir = os.listdir(rgb_image_dir)\n listdir = listdir[:len(listdir) // 2 * 2]\n for image_file_one, image_file_two in tqdm(zip(listdir[::2], listdir[1::2])):\n image_one = cv2.imread(os.path.join(rgb_image_dir, image_file_one))\n image_two = cv2.imread(os.path.join(rgb_image_dir, image_file_two))\n image = np.concatenate([image_one, image_two], axis=0)\n one_dets, two_dets = detect_iris(image, net)\n one_dets = filter_iris_box(one_dets, width_height_threshold)\n one_dets = filter_conf(one_dets, conf_threshold)\n two_dets = filter_iris_box(one_dets, width_height_threshold)\n two_dets = filter_conf(two_dets, conf_threshold)\n\n if one_dets.shape[0] > 0:\n close_open += 1\n # paint_bbox(image, dets)\n else:\n close_close += 1\n # paint_bbox(image, dets)\n\n if two_dets.shape[0] > 0:\n close_open += 1\n # paint_bbox(image, dets)\n else:\n close_close += 1\n # paint_bbox(image, dets)\n print(open_open, open_close, close_open, close_close)\n # print('Accuracy with open: {}'.format(match/total))\n\n\n # rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputir', 'Open')\n # out_open_image_dir = os.path.join('../datasets', 'out', 'outputir', 'open_open')\n # out_close_image_dir = os.path.join('../datasets', 'out', 'outputir', 'open_close')\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # if not os.path.isdir(out_close_image_dir):\n # os.makedirs(out_close_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # for image_file in tqdm(listdir):\n # image = cv2.imread(os.path.join(rgb_image_dir, image_file))\n # dets = detect_iris(image, net)\n # dets = filter_iris_box(dets, width_height_threshold)\n # bboxes = dets[dets[:, 4] > conf_threshold]\n # if bboxes.shape[0] > 0:\n # # print('Predicted Open')\n # open_open += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # else:\n # # print('Predicted Close')\n # open_close += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_close_image_dir, image_file), image)\n # # paint_bbox(image, dets)\n\n # rgb_image_dir = os.path.join('../datasets', 'eyestate_label', 'outputir', 'Close')\n # out_open_image_dir = os.path.join('../datasets', 'out', 'outputir', 'close_open')\n # out_close_image_dir = os.path.join('../datasets', 'out', 'outputir', 'close_close')\n # if not os.path.isdir(out_open_image_dir):\n # os.makedirs(out_open_image_dir)\n # if not os.path.isdir(out_close_image_dir):\n # os.makedirs(out_close_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # listdir = os.listdir(rgb_image_dir)\n # for image_file in tqdm(listdir):\n # image = cv2.imread(os.path.join(rgb_image_dir, image_file))\n # dets = detect_iris(image, net)\n # dets = filter_iris_box(dets, width_height_threshold)\n # dets = dets[dets[:, 4] > conf_threshold]\n # if dets.shape[0] > 0:\n # # print('Predicted Open')\n # close_open += 1\n # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # else:\n # # print('Predicted Close')\n # close_close += 1\n # # cv2.imwrite(os.path.join(out_close_image_dir, image_file), image)\n # # paint_bbox(image, dets)\n # # cv2.imwrite(os.path.join(out_open_image_dir, image_file), image)\n # print(open_open, open_close, close_open, close_close)\n # # print('Accuracy with open: {}'.format(match/total))\n", "sub_path": "benchmark.py", "file_name": "benchmark.py", "file_ext": "py", "file_size_in_byte": 11591, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "albumentations.Compose", "line_number": 16, "usage_type": "call"}, {"api_name": "albumentations.Normalize", "line_number": 18, "usage_type": "call"}, {"api_name": "albumentations.pytorch.ToTensorV2", "line_number": 19, "usage_type": "call"}, {"api_name": "albumentations.pytorch", "line_number": 19, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 50, "usage_type": "call"}, {"api_name": "torch.cuda.current_device", "line_number": 52, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 52, "usage_type": "attribute"}, {"api_name": "torch.load", "line_number": 53, "usage_type": "call"}, {"api_name": "layers.functions.prior_box.PriorBox", "line_number": 77, "usage_type": "call"}, {"api_name": "data.config.cfg_mnet", "line_number": 77, "usage_type": "argument"}, {"api_name": "utils.box_utils.decode", "line_number": 85, "usage_type": "call"}, {"api_name": "data.config.cfg_mnet", "line_number": 85, "usage_type": "name"}, {"api_name": "numpy.hstack", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.newaxis", "line_number": 88, "usage_type": "attribute"}, {"api_name": "numpy.float32", "line_number": 88, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 136, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 139, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_DUPLEX", "line_number": 140, "usage_type": "attribute"}, {"api_name": "models.RetinaFace", "line_number": 149, "usage_type": "call"}, {"api_name": "data.config.cfg_mnet", "line_number": 149, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 163, "usage_type": "call"}, {"api_name": "os.path", "line_number": 163, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 164, "usage_type": "call"}, {"api_name": "os.path", "line_number": 164, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path", "line_number": 166, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 167, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 168, "usage_type": "call"}, {"api_name": "os.path", "line_number": 168, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 169, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 170, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 172, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 173, "usage_type": "call"}, {"api_name": "os.path", "line_number": 173, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 196, "usage_type": "call"}, {"api_name": "os.path", "line_number": 196, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 197, "usage_type": "call"}, {"api_name": "os.path", "line_number": 197, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 198, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 199, "usage_type": "call"}, {"api_name": "os.path", "line_number": 199, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 201, "usage_type": "call"}, {"api_name": "os.path", "line_number": 201, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 202, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 203, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 205, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 206, "usage_type": "call"}, {"api_name": "os.path", "line_number": 206, "usage_type": "attribute"}, {"api_name": "cv2.imread", "line_number": 207, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 207, "usage_type": "call"}, {"api_name": "os.path", "line_number": 207, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 208, "usage_type": "call"}]}
+{"seq_id": "596658238", "text": "from os import makedirs\nfrom os.path import join, isdir\nimport pytest\nfrom shutil import copyfile\n\nimport matplotlib.pyplot as plt\nfrom numpy import array, linspace, ones, pi, zeros\n\nfrom pyleecan.Classes.import_all import *\n\ntry:\n from pyleecan.Functions.GMSH.gen_3D_mesh import gen_3D_mesh\nexcept ImportError as error:\n gen_3D_mesh = error\nfrom Tests import save_plot_path\nfrom Tests.Plot.LamWind import wind_mat\nfrom pyleecan.Functions.load import load\nfrom pyleecan.Classes.InputCurrent import InputCurrent\nfrom pyleecan.Classes.MagFEMM import MagFEMM\nfrom pyleecan.Classes.Simu1 import Simu1\nfrom pyleecan.Classes.Output import Output\nfrom pyleecan.Classes.SlotUD2 import SlotUD2\nfrom pyleecan.Classes.OptiDesignVarInterval import OptiDesignVarInterval\nfrom pyleecan.Classes.OptiObjective import OptiObjective\nfrom pyleecan.Classes.OptiProblem import OptiProblem\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.Classes.ImportGenVectLin import ImportGenVectLin\nfrom pyleecan.Classes.OptiGenAlgNsga2Deap import OptiGenAlgNsga2Deap\n\nimport numpy as np\nimport random\nfrom pyleecan.Functions.load import load\nfrom pyleecan.definitions import DATA_DIR\n\n# Gather results in the same folder\nsave_path = join(save_plot_path, \"ICEM_2020\")\nif not isdir(save_path):\n makedirs(save_path)\n\n\n\"\"\"This test gather all the images/project for the ICEM 2020 publication:\n\"Design optimization of innovative electrical machines topologies based\non Pyleecan open-source object-oriented software\"\n\"\"\"\n\n\n@pytest.mark.long_5s\n@pytest.mark.long_1m\n@pytest.mark.MagFEMM\n@pytest.mark.SCIM\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_FEMM_sym():\n \"\"\"Figure 9: Check that the FEMM can handle symmetry\n From pyleecan/Tests/Validation/Simulation/test_EM_SCIM_NL_006.py\n \"\"\"\n SCIM_006 = load(join(DATA_DIR, \"Machine\", \"SCIM_006.json\"))\n simu = Simu1(name=\"test_ICEM_2020\", machine=SCIM_006)\n simu.machine.name = \"fig_09_FEMM_sym\"\n\n # Definition of the enforced output of the electrical module\n N0 = 1500\n Is = ImportMatrixVal(value=array([[20, -10, -10]]))\n Ir = ImportMatrixVal(value=zeros((1, 28)))\n Nt_tot = 1\n Na_tot = 4096\n simu.input = InputCurrent(\n Is=Is,\n Ir=Ir, # zero current for the rotor\n OP=OPdq(N0=N0),\n Nt_tot=Nt_tot,\n Na_tot=Na_tot,\n angle_rotor_initial=0.2244,\n )\n\n # Definition of the magnetic simulation\n # 2 sym + antiperiodicity = 1/4 Lamination\n simu.mag = MagFEMM(\n type_BH_stator=2, type_BH_rotor=2, is_periodicity_a=True, is_fast_draw=False\n )\n # Stop after magnetic computation\n simu.force = None\n simu.struct = None\n # Run simulation\n out = Output(simu=simu)\n simu.run()\n\n # FEMM files (mesh and results) are available in Results folder\n copyfile(\n join(out.path_result, \"Femm\", \"fig_09_FEMM_sym_model.ans\"),\n join(save_path, \"fig_09_FEMM_sym_model.ans\"),\n )\n copyfile(\n join(out.path_result, \"Femm\", \"fig_09_FEMM_sym_model.fem\"),\n join(save_path, \"fig_09_FEMM_sym_model.fem\"),\n )\n\n\n@pytest.mark.GMSH\ndef test_gmsh_mesh_dict():\n \"\"\"Figure 10: Generate a 3D mesh with Gmsh by setting the\n number of element on each lines\n \"\"\"\n if isinstance(gen_3D_mesh, ImportError):\n raise ImportError(\"Fail to import gen_3D_mesh (gmsh package missing)\")\n\n # Stator definition\n stator = LamSlotWind(\n Rint=0.1325,\n Rext=0.2,\n Nrvd=0,\n L1=0.35,\n Kf1=0.95,\n is_internal=False,\n is_stator=True,\n )\n stator.slot = SlotW10(\n Zs=36, H0=1e-3, H1=1.5e-3, H2=30e-3, W0=12e-3, W1=14e-3, W2=12e-3\n )\n\n # Plot, check and save\n stator.plot(is_lam_only=True, is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_10_ref_lamination.png\"))\n fig.savefig(join(save_path, \"fig_10_ref_lamination.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 4\n\n # Definition of the number of each element on each line\n mesh_dict = {\n \"0\": 5, # Yoke_Side_Right\n \"1\": 5, # Yoke_Side_Left\n \"2\": 5, # Yoke_Arc\n \"3\": 2,\n \"4\": 8,\n \"5\": 1,\n \"6\": 1,\n \"7\": 1,\n \"8\": 2, # bore_arc_bot\n \"9\": 2, # bore_arc_top\n \"10\": 1,\n \"11\": 1,\n \"12\": 1,\n \"13\": 8,\n \"14\": 2,\n }\n gen_3D_mesh(\n lamination=stator,\n save_path=join(save_path, \"fig_10_gmsh_mesh_dict.msh\"),\n mesh_size=7e-3,\n user_mesh_dict=mesh_dict,\n is_rect=True,\n Nlayer=18,\n display=False,\n )\n # To see the resulting mesh, gmsh_mesh_dict.msh need to be\n # opened in Gmsh\n\n\n@pytest.mark.skip\n@pytest.mark.GMSH\ndef test_SlotMulti_sym():\n \"\"\"Figure 11: Genera\n te a 3D mesh with GMSH for a lamination\n with several slot types and notches\n \"\"\"\n\n if isinstance(gen_3D_mesh, ImportError):\n raise ImportError(\"Fail to import gen_3D_mesh (gmsh package missing)\")\n\n plt.close(\"all\")\n # Rotor definition\n rotor = LamSlotMulti(\n Rint=0.2, Rext=0.7, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n\n # Reference Slot\n Zs = 8\n Slot1 = SlotW10(\n Zs=Zs, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=Zs, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 4 of each in alternance\n slot_list = list()\n for ii in range(Zs // 2):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n rotor.slot_list = slot_list\n # Set slot position as linspace\n rotor.alpha = linspace(0, 2 * pi, 8, endpoint=False) + pi / Zs\n\n # Set evenly distributed notches\n slot3 = SlotW10(Zs=Zs // 2, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=2 * pi / Zs)\n rotor.notch = [notch]\n\n # Plot, check and save\n rotor.plot(sym=4, is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_11_SlotMulti_sym.png\"))\n fig.savefig(join(save_path, \"fig_11_SlotMulti_sym.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 1\n\n # Generate the gmsh equivalent\n gen_3D_mesh(\n lamination=rotor,\n save_path=join(save_path, \"fig_11_gmsh_SlotMulti.msh\"),\n sym=4,\n mesh_size=20e-3,\n Nlayer=20,\n display=False,\n )\n # To see the resulting mesh, gmsh_SlotMulti.msh need to be\n # opened in Gmsh\n\n\n@pytest.mark.MachineUD\ndef test_MachineUD():\n \"\"\"Figure 12: Check that you can plot a machine with 4 laminations\"\"\"\n machine = MachineUD()\n machine.name = \"Machine with 4 laminations\"\n\n # Main geometry parameter\n Rext = 170e-3 # Exterior radius of outter lamination\n W1 = 30e-3 # Width of first lamination\n A1 = 2.5e-3 # Width of the first airgap\n W2 = 20e-3\n A2 = 10e-3\n W3 = 20e-3\n A3 = 2.5e-3\n W4 = 60e-3\n\n # Outer stator\n lam1 = LamSlotWind(Rext=Rext, Rint=Rext - W1, is_internal=False, is_stator=True)\n lam1.slot = SlotW22(\n Zs=12, W0=2 * pi / 12 * 0.75, W2=2 * pi / 12 * 0.75, H0=0, H2=W1 * 0.65\n )\n lam1.winding = WindingUD(qs=3, p=3)\n lam1.winding.init_as_CW2LT()\n # External Rotor\n lam2 = LamSlot(\n Rext=lam1.Rint - A1, Rint=lam1.Rint - A1 - W2, is_internal=True, is_stator=False\n )\n lam2.slot = SlotW10(Zs=22, W0=25e-3, W1=25e-3, W2=15e-3, H0=0, H1=0, H2=W2 * 0.75)\n # Internal Rotor\n lam3 = LamSlot(\n Rext=lam2.Rint - A2,\n Rint=lam2.Rint - A2 - W3,\n is_internal=False,\n is_stator=False,\n )\n lam3.slot = SlotW10(\n Zs=22, W0=17.5e-3, W1=17.5e-3, W2=12.5e-3, H0=0, H1=0, H2=W3 * 0.75\n )\n # Inner stator\n lam4 = LamSlotWind(\n Rext=lam3.Rint - A3, Rint=lam3.Rint - A3 - W4, is_internal=True, is_stator=True\n )\n lam4.slot = SlotW10(Zs=12, W0=25e-3, W1=25e-3, W2=1e-3, H0=0, H1=0, H2=W4 * 0.75)\n lam4.winding = WindingUD(qs=3, p=3)\n lam4.winding.init_as_CW2LT()\n # Machine definition\n machine.lam_list = [lam1, lam2, lam3, lam4]\n machine.shaft = Shaft(Drsh=lam4.Rint * 2)\n\n # Plot, check and save\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_12_MachineUD.png\"))\n fig.savefig(join(save_path, \"fig_12_MachineUD.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 61\n\n machine.frame = None\n machine.name = None\n\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_12_MachineUD_no_frame_no_name.png\"))\n fig.savefig(join(save_path, \"fig_12_MachineUD_no_frame_no_name.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 61\n\n\ndef test_SlotMulti_rotor():\n \"\"\"Figure 13: Check that you can plot a LamSlotMulti rotor (two slots kind + notches)\"\"\"\n plt.close(\"all\")\n # Lamination main dimensions definition\n rotor = LamSlotMulti(Rint=0.2, Rext=0.7, is_internal=True, is_stator=False)\n\n # Reference slot definition\n Slot1 = SlotW10(\n Zs=10, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=12, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 5 of each in alternance\n slot_list = list()\n for ii in range(5):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n\n # Two slots in the list are modified (bigger than the others)\n rotor.slot_list = slot_list\n rotor.slot_list[0].H2 = 300e-3\n rotor.slot_list[7].H2 = 300e-3\n # Set slots position\n rotor.alpha = array([0, 29, 60, 120, 150, 180, 210, 240, 300, 330]) * pi / 180\n\n # Evenly distributed Notch definition\n slot3 = SlotW10(Zs=12, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=15 * pi / 180)\n rotor.notch = [notch]\n\n # Plot, check and save\n rotor.plot(is_show_fig=False, is_clean_plot=True, edgecolor=\"k\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_rotor.png\"))\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_rotor.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 2\n\n\ndef test_SlotMulti_stator():\n \"\"\"Figure 13: Check that you can plot a LamSlotMulti stator (two slots kind + notches)\"\"\"\n plt.close(\"all\")\n # Lamination main dimensions definition\n stator = LamSlotMulti(Rint=0.2, Rext=0.7, is_internal=False, is_stator=True)\n\n # Reference slot definition\n Slot1 = SlotW10(\n Zs=10, W0=50e-3, H0=30e-3, W1=100e-3, H1=30e-3, H2=100e-3, W2=120e-3\n )\n Slot2 = SlotW22(Zs=12, W0=pi / 12, H0=50e-3, W2=pi / 6, H2=125e-3)\n\n # Reference slot are duplicated to get 5 of each in alternance\n slot_list = list()\n for ii in range(5):\n slot_list.append(SlotW10(init_dict=Slot1.as_dict()))\n slot_list.append(SlotW22(init_dict=Slot2.as_dict()))\n\n # Two slots in the list are modified (bigger than the others)\n stator.slot_list = slot_list\n stator.slot_list[0].H2 = 300e-3\n stator.slot_list[7].H2 = 300e-3\n # Set slots position\n stator.alpha = array([0, 29, 60, 120, 150, 180, 210, 240, 300, 330]) * pi / 180\n\n # Evenly distributed Notch definition\n slot3 = SlotW10(Zs=12, W0=40e-3, W1=40e-3, W2=40e-3, H0=0, H1=0, H2=25e-3)\n notch = NotchEvenDist(notch_shape=slot3, alpha=15 * pi / 180)\n stator.notch = [notch]\n\n # Plot, check and save\n stator.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_stator.png\"))\n fig.savefig(join(save_path, \"fig_13_LamSlotMulti_stator.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 2\n\n\n@pytest.mark.SlotUD\ndef test_SlotUD():\n \"\"\"Figure 14: User Defined slot \"snowflake\" \"\"\"\n\n plt.close(\"all\")\n # Enfore first point on rotor bore\n Rrotor = abs(0.205917893677990 - 0.107339745962156j)\n machine = MachineSRM()\n machine.name = \"User-Defined Slot\"\n # Stator definintion\n machine.stator = LamSlotWind(\n Rint=Rrotor + 5e-3, Rext=Rrotor + 120e-3, is_internal=False, is_stator=True\n )\n machine.stator.slot = SlotW21(\n Zs=36, W0=7e-3, H0=10e-3, H1=0, H2=70e-3, W1=30e-3, W2=0.1e-3\n )\n machine.stator.winding = WindingUD(qs=3, p=3, coil_pitch=5)\n machine.stator.winding.init_as_DWL(nlay=2)\n\n # Rotor definition\n machine.rotor = LamSlot(Rint=0.02, Rext=Rrotor, is_internal=True, is_stator=False)\n machine.rotor.axial_vent = [\n VentilationTrap(Zh=6, Alpha0=0, D0=0.025, H0=0.025, W1=0.015, W2=0.04)\n ]\n # Complex coordinates of half the snowflake slot\n point_list = [\n 0.205917893677990 - 0.107339745962156j,\n 0.187731360198517 - 0.0968397459621556j,\n 0.203257639640145 - 0.0919474411167423j,\n 0.199329436409870 - 0.0827512886940357j,\n 0.174740979141750 - 0.0893397459621556j,\n 0.143564064605510 - 0.0713397459621556j,\n 0.176848674296337 - 0.0616891108675446j,\n 0.172822394854708 - 0.0466628314259158j,\n 0.146001886779019 - 0.0531173140978201j,\n 0.155501886779019 - 0.0366628314259158j,\n 0.145109581933606 - 0.0306628314259158j,\n 0.127109581933606 - 0.0618397459621556j,\n 0.0916025403784439 - 0.0413397459621556j,\n 0.134949327895761 - 0.0282609076372691j,\n 0.129324972242779 - 0.0100025773880714j,\n 0.0690858798800485 - 0.0283397459621556j,\n 0.0569615242270663 - 0.0213397459621556j,\n ]\n machine.rotor.slot = SlotUD(Zs=6)\n machine.rotor.slot.set_from_point_list(is_sym=True, point_list=point_list)\n\n # Plot, check and save\n machine.plot(is_show_fig=False, is_clean_plot=True)\n fig = plt.gcf()\n assert len(fig.axes[0].patches) == 85\n fig.savefig(join(save_path, \"fig_14_SlotUD.png\"))\n fig.savefig(join(save_path, \"fig_14_SlotUD.svg\"), format=\"svg\")\n\n\ndef test_WindingUD():\n \"\"\"Figure 16: User-defined Winding\n From pyleecan/Tests/Plot/LamWind/test_Slot_12_plot.py\n \"\"\"\n plt.close(\"all\")\n machine = MachineDFIM()\n machine.name = \"User Defined Winding\"\n # Rotor definition\n machine.rotor = LamSlotWind(\n Rint=0.2, Rext=0.5, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n machine.rotor.axial_vent = [\n VentilationPolar(Zh=6, Alpha0=0, W1=pi / 6, D0=100e-3, H0=0.3)\n ]\n machine.rotor.slot = SlotW12(Zs=6, R2=35e-3, H0=20e-3, R1=17e-3, H1=130e-3)\n machine.rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n machine.rotor.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n # Stator definion\n machine.stator = LamSlotWind(\n Rint=0.51,\n Rext=0.8,\n is_internal=False,\n is_stator=True,\n L1=0.9,\n Nrvd=2,\n Wrvd=0.05,\n )\n machine.stator.slot = SlotW12(Zs=18, R2=25e-3, H0=30e-3, R1=0, H1=150e-3)\n machine.stator.winding.Lewout = 60e-3\n machine.stator.winding = WindingUD(qs=3, p=3, coil_pitch=1)\n machine.stator.winding.init_as_DWL(nlay=2)\n machine.stator.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n\n # Shaft & frame\n machine.shaft = Shaft(Drsh=machine.rotor.Rint * 2, Lshaft=1)\n machine.frame = Frame(Rint=0.8, Rext=0.9, Lfra=1)\n\n # Plot, check and save\n machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_16_WindingUD.png\"))\n fig.savefig(join(save_path, \"fig_16_WindingUD.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 77\n\n\ndef test_WindingUD_layer():\n \"\"\"Figure 17: User-defined Winding with uneven winding layer\"\"\"\n plt.close(\"all\")\n # Rotor definition\n rotor = LamSlotWind(\n Rint=0.2, Rext=0.5, is_internal=True, is_stator=False, L1=0.9, Nrvd=2, Wrvd=0.05\n )\n rotor.axial_vent = [VentilationCirc(Zh=6, Alpha0=0, D0=100e-3, H0=0.3)]\n rotor.slot = SlotW11(\n Zs=6, H0=15e-3, W0=60e-3, W1=100e-3, W2=100e-3, H1=20e-3, H2=200e-3\n )\n rotor.slot = rotor.slot.convert_to_SlotUD2()\n assert isinstance(rotor.slot, SlotUD2)\n key = \"Nrad=2, Ntan=2\"\n Top, Bottom = rotor.slot.active_surf.split_line(0, 100, is_join=True)\n Bottom_Left, Bottom_Right = Bottom.split_line(\n 0.320 - 100j, 0.320 + 100j, is_join=True\n )\n Top_Left, Top_Right = Top.split_line(0.410 - 100j, 0.410 + 100j, is_join=True)\n rotor.slot.split_active_surf_dict = {\n key: [Bottom_Right, Bottom_Left, Top_Right, Top_Left]\n }\n rotor.winding = WindingUD(wind_mat=wind_mat, qs=4, p=4, Lewout=60e-3)\n rotor.mat_type.mag = MatMagnetics(Wlam=0.5e-3)\n\n # For testing the _set_split_active_surf_dict method\n rotor.save(join(save_path, \"Fig17_rotor_wind_layer.json\"))\n rotor = load(join(save_path, \"Fig17_rotor_wind_layer.json\"))\n\n # Plot, check and save\n rotor.plot(is_show_fig=False, is_clean_plot=True, edgecolor=\"k\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_17_WindingUD_layer.png\"))\n fig.savefig(join(save_path, \"fig_17_WindingUD_layer.svg\"), format=\"svg\")\n assert len(fig.axes[0].patches) == 34\n\n\ndef test_BoreFlower(is_show_fig=False):\n \"\"\"Figure 18: LamHole with uneven bore shape\n From pyleecan/Tests/Plot/LamHole/test_Hole_50_plot.py\n \"\"\"\n # Rotor definition\n rotor = LamHole(is_internal=True, Rint=0.021, Rext=0.075, is_stator=False, L1=0.7)\n rotor.hole = list()\n rotor.hole.append(\n HoleM50(\n Zh=8,\n W0=50e-3,\n W1=0,\n W2=1e-3,\n W3=1e-3,\n W4=20.6e-3,\n H0=17.3e-3,\n H1=3e-3,\n H2=0.5e-3,\n H3=6.8e-3,\n H4=0,\n )\n )\n # Rotor axial ventilation ducts\n rotor.axial_vent = list()\n rotor.axial_vent.append(VentilationCirc(Zh=8, Alpha0=0, D0=5e-3, H0=40e-3))\n rotor.axial_vent.append(VentilationCirc(Zh=8, Alpha0=pi / 8, D0=7e-3, H0=40e-3))\n # Remove a magnet\n rotor.hole[0].magnet_1 = None\n # Rotor bore shape\n rotor.bore = BoreFlower(N=8, Rarc=0.05, alpha=pi / 8)\n rotor.yoke = BoreFlower(N=8, Rarc=0.05 / 4, alpha=pi / 8)\n\n # Plot, check and save\n fig, _ = rotor.plot(is_show_fig=is_show_fig)\n fig.savefig(join(save_path, \"fig_18_BoreFlower.png\"))\n fig.savefig(join(save_path, \"fig_18_BoreFlower.svg\"), format=\"svg\")\n # 2 for lam + 3*8 for holes + 16 vents\n assert len(fig.axes[0].patches) == 42\n fig, _ = rotor.plot(is_show_fig=is_show_fig, sym=8)\n fig.savefig(join(save_path, \"fig_18_BoreFlower_sym.png\"))\n fig.savefig(join(save_path, \"fig_18_BoreFlower_sym.svg\"), format=\"svg\")\n # 1 for lam + 3*1 for holes + 3 vents\n assert len(fig.axes[0].patches) == 7\n\n\n@pytest.mark.SPMSM\n@pytest.mark.MagFEMM\n@pytest.mark.long_5s\n@pytest.mark.SingleOP\n@pytest.mark.periodicity\ndef test_ecc_FEMM():\n \"\"\"Figure 19: transfrom_list in FEMM for eccentricities\"\"\"\n SPMSM_015 = load(join(DATA_DIR, \"Machine\", \"SPMSM_015.json\"))\n simu = Simu1(name=\"test_ICEM_2020_ecc\", machine=SPMSM_015)\n simu.machine.name = \"fig_19_Transform_list\"\n\n # Modify stator Rext to get more convincing translation\n SPMSM_015.stator.Rext = SPMSM_015.stator.Rext * 0.9\n gap = SPMSM_015.comp_width_airgap_mec()\n\n # Definition of the enforced output of the electrical module\n N0 = 3000\n Is = ImportMatrixVal(value=array([[0, 0, 0]]))\n time = ImportGenVectLin(start=0, stop=0, num=1, endpoint=True)\n angle = ImportGenVectLin(start=0, stop=2 * 2 * pi / 9, num=2043, endpoint=False)\n simu.input = InputCurrent(\n Is=Is,\n Ir=None, # No winding on the rotor\n OP=OPdq(N0=N0),\n time=time,\n angle=angle,\n angle_rotor_initial=0,\n )\n\n # Definition of the magnetic simulation (is_mmfr=False => no flux from the magnets)\n simu.mag = MagFEMM(\n type_BH_stator=0,\n type_BH_rotor=0,\n is_sliding_band=False, # Ecc => No sliding band\n is_periodicity_a=False,\n is_mmfs=False,\n is_get_meshsolution=True,\n is_fast_draw=False,\n )\n simu.force = None\n simu.struct = None\n\n # Set two transformations\n # First rotate 3rd Magnet\n transform_list = [\n {\"type\": \"rotate\", \"value\": 0.08, \"label\": \"MagnetRotorRadial_S_R0_T0_S3\"}\n ]\n # Then Translate the rotor\n transform_list.append({\"type\": \"translate\", \"value\": gap * 0.75, \"label\": \"Rotor\"})\n simu.mag.transform_list = transform_list\n\n # Run the simulation\n out = Output(simu=simu)\n simu.run()\n\n # FEMM files (mesh and results) are available in Results folder\n copyfile(\n join(out.path_result, \"Femm\", \"fig_19_Transform_list_model.ans\"),\n join(save_path, \"fig_19_Transform_list_model.ans\"),\n )\n copyfile(\n join(out.path_result, \"Femm\", \"fig_19_Transform_list_model.fem\"),\n join(save_path, \"fig_19_Transform_list_model.fem\"),\n )\n # Plot, check, save\n out.mag.meshsolution.plot_mesh(\n save_path=join(save_path, \"fig_19_transform_list.png\"), is_show_fig=False\n )\n\n\n@pytest.mark.skip\n@pytest.mark.long_5s\n@pytest.mark.SPMSM\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_Optimization_problem():\n \"\"\"\n Figure19: Machine topology before optimization\n Figure20: Individuals in the fitness space\n Figure21: Pareto Front in the fitness space\n Figure22: Topology to maximize first torque harmonic\n Figure22: Topology to minimize second torque harmonic\n\n WARNING: The computation takes 6 hours on a single 3GHz CPU core.\n The algorithm uses randomization at different steps so\n the results won't be exactly the same as the one in the publication\n \"\"\"\n # ------------------ #\n # DEFAULT SIMULATION #\n # ------------------ #\n\n # First, we need to define a default simulation.\n # This simulation will the base of every simulation during the optimization process\n\n # Load the machine\n SPMSM_001 = load(join(DATA_DIR, \"Machine\", \"SPMSM_001.json\"))\n\n # Definition of the enforced output of the electrical module\n Na_tot = 1024 # Angular steps\n Nt_tot = 32 # Time step\n Is = ImportMatrixVal(\n value=np.array(\n [\n [1.73191211247099e-15, 24.4948974278318, -24.4948974278318],\n [-0.925435413499285, 24.9445002597334, -24.0190648462341],\n [-1.84987984757817, 25.3673918959653, -23.5175120483872],\n [-2.77234338398183, 25.7631194935712, -22.9907761095894],\n [-3.69183822565029, 26.1312592975275, -22.4394210718773],\n [-4.60737975447626, 26.4714170945114, -21.8640373400352],\n [-5.51798758565886, 26.7832286350338, -21.2652410493749],\n [-6.42268661752422, 27.0663600234871, -20.6436734059628],\n [-7.32050807568877, 27.3205080756888, -20.0000000000000],\n [-8.21049055044714, 27.5454006435389, -19.3349100930918],\n [-9.09168102627374, 27.7407969064430, -18.6491158801692],\n [-9.96313590233562, 27.9064876291883, -17.9433517268527],\n [-10.8239220029239, 28.0422953859991, -17.2183733830752],\n [-11.6731175767218, 28.1480747505277, -16.4749571738058],\n [-12.5098132838389, 28.2237124515809, -15.7138991677421],\n [-13.3331131695549, 28.2691274944141, -14.9360143248592],\n [-14.1421356237309, 28.2842712474619, -14.1421356237310],\n [-14.9360143248592, 28.2691274944141, -13.3331131695549],\n [-15.7138991677420, 28.2237124515809, -12.5098132838389],\n [-16.4749571738058, 28.1480747505277, -11.6731175767219],\n [-17.2183733830752, 28.0422953859991, -10.8239220029240],\n [-17.9433517268527, 27.9064876291883, -9.96313590233564],\n [-18.6491158801692, 27.7407969064430, -9.09168102627375],\n [-19.3349100930918, 27.5454006435389, -8.21049055044716],\n [-20, 27.3205080756888, -7.32050807568879],\n [-20.6436734059628, 27.0663600234871, -6.42268661752424],\n [-21.2652410493749, 26.7832286350338, -5.51798758565888],\n [-21.8640373400352, 26.4714170945114, -4.60737975447627],\n [-22.4394210718772, 26.1312592975275, -3.69183822565031],\n [-22.9907761095894, 25.7631194935712, -2.77234338398184],\n [-23.5175120483872, 25.3673918959653, -1.84987984757819],\n [-24.0190648462341, 24.9445002597334, -0.925435413499304],\n ]\n )\n )\n N0 = 400\n Ir = ImportMatrixVal(value=np.zeros((Nt_tot, 28)))\n\n SPMSM_001.name = (\n \"Default SPMSM machine\" # Rename the machine to have the good plot title\n )\n\n # Definition of the simulation\n simu = Simu1(name=\"test_Optimization_problem\", machine=SPMSM_001)\n\n simu.input = InputCurrent(\n Is=Is,\n Ir=Ir, # zero current for the rotor\n OP=OPdq(N0=N0),\n Nt_tot=Nt_tot,\n Na_tot=Na_tot,\n angle_rotor_initial=0.39,\n )\n\n # Definition of the magnetic simulation\n simu.mag = MagFEMM(\n type_BH_stator=2,\n type_BH_rotor=2,\n is_periodicity_a=True,\n )\n\n simu.struct = None\n\n # Default Output\n output = Output(simu=simu)\n\n # Modify magnet width and the slot opening height\n output.simu.machine.stator.slot.H0 = 0.001\n output.simu.machine.rotor.slot.magnet[0].Wmag *= 0.98\n\n # FIG21 Display default machine\n output.simu.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_21_Machine_topology_before_optimization.png\"))\n fig.savefig(\n join(save_path, \"fig_21_Machine_topology_before_optimization.svg\"), format=\"svg\"\n )\n plt.close(\"all\")\n # -------------------- #\n # OPTIMIZATION PROBLEM #\n # -------------------- #\n\n # Objective functions\n \"\"\"Return the average torque opposite (opposite to be maximized)\"\"\"\n tem_av = \"lambda output: -abs(output.mag.Tem_av)\"\n\n \"\"\"Return the torque ripple \"\"\"\n Tem_rip_pp = \"lambda output: abs(output.mag.Tem_rip_pp)\"\n\n my_objs = [\n OptiObjective(\n name=\"Maximization of the average torque\",\n symbol=\"Tem_av\",\n unit=\"N.m\",\n keeper=tem_av,\n ),\n OptiObjective(\n name=\"Minimization of the torque ripple\",\n symbol=\"Tem_rip_pp\",\n unit=\"N.m\",\n keeper=Tem_rip_pp,\n ),\n ]\n\n # Design variables\n my_vars = [\n OptiDesignVarInterval(\n name=\"Stator slot opening\",\n symbol=\"W0\",\n unit=\"m\",\n space=[\n 0.2 * output.simu.machine.stator.slot.W2,\n output.simu.machine.stator.slot.W2,\n ],\n get_value=\"lambda space: random.uniform(*space)\",\n setter=\"simu.machine.stator.slot.W0\",\n ),\n OptiDesignVarInterval(\n name=\"Rotor magnet width\",\n symbol=\"Wmag\",\n unit=\"m\",\n space=[\n 0.5 * output.simu.machine.rotor.slot.W0,\n 0.99 * output.simu.machine.rotor.slot.W0,\n ], # May generate error in FEMM\n get_value=\"lambda space: random.uniform(*space)\",\n setter=\"simu.machine.rotor.slot.magnet[0].Wmag\",\n ),\n ]\n\n # Problem creation\n my_prob = OptiProblem(output=output, design_var=my_vars, obj_func=my_objs)\n\n # Solve problem with NSGA-II\n solver = OptiGenAlgNsga2Deap(problem=my_prob, size_pop=12, nb_gen=40, p_mutate=0.5)\n res = solver.solve()\n\n # ------------- #\n # PLOTS RESULTS #\n # ------------- #\n\n res.plot_generation(x_symbol=\"Tem_av\", y_symbol=\"Tem_rip_pp\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"fig_20_Individuals_in_fitness_space.png\"))\n fig.savefig(\n join(save_path, \"fig_20_Individuals_in_fitness_space.svg\"), format=\"svg\"\n )\n\n res.plot_pareto(x_symbol=\"Tem_av\", y_symbol=\"Tem_rip_pp\")\n fig = plt.gcf()\n fig.savefig(join(save_path, \"Pareto_front_in_fitness_space.png\"))\n fig.savefig(join(save_path, \"Pareto_front_in_fitness_space.svg\"), format=\"svg\")\n\n # Extraction of best topologies for every objective\n pareto_index = (\n res.get_pareto_index()\n ) # Extract individual index in the pareto front\n\n idx_1 = pareto_index[0] # First objective\n idx_2 = pareto_index[0] # Second objective\n\n Tem_av = res[\"Tem_av\"].result\n Tem_rip_pp = res[\"Tem_rip_pp\"].result\n\n for i in pareto_index:\n # First objective\n if Tem_av[i] < Tem_av[idx_1]:\n idx_1 = i\n # Second objective\n if Tem_rip_pp[i] < Tem_rip_pp[idx_2]:\n idx_2 = i\n\n # Get corresponding simulations\n simu1 = res.get_simu(idx_1)\n simu2 = res.get_simu(idx_2)\n\n # Rename machine to modify the title\n name1 = \"Machine that maximizes the average torque ({:.3f} Nm)\".format(\n abs(Tem_av[idx_1])\n )\n simu1.machine.name = name1\n name2 = \"Machine that minimizes the torque ripple ({:.4f}Nm)\".format(\n abs(Tem_rip_pp[idx_2])\n )\n simu2.machine.name = name2\n\n # plot the machine\n simu1.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_maximize_average_torque.png\"), format=\"png\"\n )\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_maximize_average_torque.svg\"), format=\"svg\"\n )\n\n simu2.machine.plot(is_show_fig=False)\n fig = plt.gcf()\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_minimize_torque_ripple.png\"), format=\"png\"\n )\n fig.savefig(\n join(save_path, \"fig_21_Topology_to_minimize_torque_ripple.svg\"), format=\"svg\"\n )\n\n\nif __name__ == \"__main__\":\n # test_WindingUD_layer()\n # test_FEMM_sym()\n # test_gmsh_mesh_dict()\n # test_SlotMulti_sym()\n test_MachineUD()\n # test_WindingUD()\n # test_ecc_FEMM()\n # test_WindingUD_layer()\n print(\"Done\")\n", "sub_path": "Tests/Plot/test_ICEM_2020.py", "file_name": "test_ICEM_2020.py", "file_ext": "py", "file_size_in_byte": 29935, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pyleecan.Functions.GMSH.gen_3D_mesh.gen_3D_mesh", "line_number": 14, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 36, "usage_type": "call"}, {"api_name": "Tests.save_plot_path", "line_number": 36, "usage_type": "argument"}, {"api_name": "os.path.isdir", "line_number": 37, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 38, "usage_type": "call"}, {"api_name": "pyleecan.Functions.load.load", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 57, "usage_type": "call"}, {"api_name": "pyleecan.definitions.DATA_DIR", "line_number": 57, "usage_type": "argument"}, {"api_name": "pyleecan.Classes.Simu1.Simu1", "line_number": 58, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportMatrixVal.ImportMatrixVal", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 63, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportMatrixVal.ImportMatrixVal", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 64, "usage_type": "call"}, {"api_name": "pyleecan.Classes.InputCurrent.InputCurrent", "line_number": 67, "usage_type": "call"}, {"api_name": "pyleecan.Classes.MagFEMM.MagFEMM", "line_number": 78, "usage_type": "call"}, {"api_name": "pyleecan.Classes.Output.Output", "line_number": 85, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 89, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 90, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 93, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 94, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 95, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 47, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 48, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 49, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 50, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 51, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pyleecan.Functions.GMSH.gen_3D_mesh.gen_3D_mesh", "line_number": 104, "usage_type": "argument"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 124, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 125, "usage_type": "call"}, {"api_name": "pyleecan.Functions.GMSH.gen_3D_mesh.gen_3D_mesh", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 148, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pyleecan.Functions.GMSH.gen_3D_mesh.gen_3D_mesh", "line_number": 167, "usage_type": "argument"}, {"api_name": "matplotlib.pyplot.close", "line_number": 170, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 170, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 181, "usage_type": "name"}, {"api_name": "numpy.linspace", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 190, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 199, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 199, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 200, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 201, "usage_type": "call"}, {"api_name": "pyleecan.Functions.GMSH.gen_3D_mesh.gen_3D_mesh", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 207, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 159, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 236, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 268, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 268, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 269, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 270, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 277, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 277, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 278, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 279, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 217, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 285, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 285, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 293, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 306, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 306, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 310, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 315, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 315, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 316, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 317, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 323, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 331, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 344, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 344, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 348, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 353, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 353, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 354, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 355, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 363, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 363, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 408, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 408, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 410, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 411, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 359, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 418, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 418, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 426, "usage_type": "name"}, {"api_name": "Tests.Plot.LamWind.wind_mat", "line_number": 429, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 453, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 453, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 454, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 455, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 461, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 461, "usage_type": "name"}, {"api_name": "pyleecan.Classes.SlotUD2.SlotUD2", "line_number": 471, "usage_type": "argument"}, {"api_name": "Tests.Plot.LamWind.wind_mat", "line_number": 481, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 485, "usage_type": "call"}, {"api_name": "pyleecan.Functions.load.load", "line_number": 486, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 486, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 490, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 490, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 491, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 492, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 521, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 525, "usage_type": "name"}, {"api_name": "numpy.pi", "line_number": 526, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 530, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 531, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 535, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 536, "usage_type": "call"}, {"api_name": "pyleecan.Functions.load.load", "line_number": 548, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 548, "usage_type": "call"}, {"api_name": "pyleecan.definitions.DATA_DIR", "line_number": 548, "usage_type": "argument"}, {"api_name": "pyleecan.Classes.Simu1.Simu1", "line_number": 549, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportMatrixVal.ImportMatrixVal", "line_number": 558, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 558, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportGenVectLin.ImportGenVectLin", "line_number": 559, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportGenVectLin.ImportGenVectLin", "line_number": 560, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 560, "usage_type": "name"}, {"api_name": "pyleecan.Classes.InputCurrent.InputCurrent", "line_number": 561, "usage_type": "call"}, {"api_name": "pyleecan.Classes.MagFEMM.MagFEMM", "line_number": 571, "usage_type": "call"}, {"api_name": "pyleecan.Classes.Output.Output", "line_number": 593, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 597, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 598, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 599, "usage_type": "call"}, {"api_name": "shutil.copyfile", "line_number": 601, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 602, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 603, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 607, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 541, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 542, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 543, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 544, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 545, "usage_type": "attribute"}, {"api_name": "pyleecan.Functions.load.load", "line_number": 636, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 636, "usage_type": "call"}, {"api_name": "pyleecan.definitions.DATA_DIR", "line_number": 636, "usage_type": "argument"}, {"api_name": "pyleecan.Classes.ImportMatrixVal.ImportMatrixVal", "line_number": 641, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 642, "usage_type": "call"}, {"api_name": "pyleecan.Classes.ImportMatrixVal.ImportMatrixVal", "line_number": 680, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 680, "usage_type": "call"}, {"api_name": "pyleecan.Classes.Simu1.Simu1", "line_number": 687, "usage_type": "call"}, {"api_name": "pyleecan.Classes.InputCurrent.InputCurrent", "line_number": 689, "usage_type": "call"}, {"api_name": "pyleecan.Classes.MagFEMM.MagFEMM", "line_number": 699, "usage_type": "call"}, {"api_name": "pyleecan.Classes.Output.Output", "line_number": 708, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 716, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 716, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 717, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 719, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.close", "line_number": 721, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 721, "usage_type": "name"}, {"api_name": "pyleecan.Classes.OptiObjective.OptiObjective", "line_number": 734, "usage_type": "call"}, {"api_name": "pyleecan.Classes.OptiObjective.OptiObjective", "line_number": 740, "usage_type": "call"}, {"api_name": "pyleecan.Classes.OptiDesignVarInterval.OptiDesignVarInterval", "line_number": 750, "usage_type": "call"}, {"api_name": "pyleecan.Classes.OptiDesignVarInterval.OptiDesignVarInterval", "line_number": 761, "usage_type": "call"}, {"api_name": "pyleecan.Classes.OptiProblem.OptiProblem", "line_number": 775, "usage_type": "call"}, {"api_name": "pyleecan.Classes.OptiGenAlgNsga2Deap.OptiGenAlgNsga2Deap", "line_number": 778, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 786, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 786, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 787, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 789, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 793, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 793, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 794, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 795, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 832, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 832, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 834, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 837, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.gcf", "line_number": 841, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 841, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 843, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 846, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 611, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 612, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 613, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 614, "usage_type": "attribute"}, {"api_name": "pytest.mark", "line_number": 615, "usage_type": "attribute"}]}
+{"seq_id": "280510418", "text": "# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-x86_64/egg/reviewboard/webapi/tests/test_hosting_service_account.py\n# Compiled at: 2020-02-11 04:03:57\nfrom __future__ import unicode_literals\nfrom django.utils import six\nfrom reviewboard.hostingsvcs.models import HostingServiceAccount\nfrom reviewboard.webapi.resources import resources\nfrom reviewboard.webapi.tests.base import BaseWebAPITestCase\nfrom reviewboard.webapi.tests.mimetypes import hosting_service_account_item_mimetype, hosting_service_account_list_mimetype\nfrom reviewboard.webapi.tests.mixins import BasicTestsMetaclass\nfrom reviewboard.webapi.tests.urls import get_hosting_service_account_item_url, get_hosting_service_account_list_url\n\ndef _compare_item(self, item_rsp, account):\n self.assertEqual(item_rsp[b'id'], account.id)\n self.assertEqual(item_rsp[b'username'], account.username)\n self.assertEqual(item_rsp[b'service'], account.service.hosting_service_id)\n\n\n@six.add_metaclass(BasicTestsMetaclass)\nclass ResourceListTests(BaseWebAPITestCase):\n \"\"\"Testing the HostingServiceAccountResource list APIs.\"\"\"\n sample_api_url = b'hosting-services-accounts/'\n resource = resources.hosting_service_account\n fixtures = [b'test_users']\n basic_post_use_admin = True\n compare_item = _compare_item\n\n def setup_http_not_allowed_list_test(self, user):\n return get_hosting_service_account_list_url()\n\n def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):\n if populate_items:\n if with_local_site:\n local_site = self.get_local_site(name=local_site_name)\n else:\n local_site = None\n accounts = [\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob', local_site=local_site)]\n else:\n accounts = []\n return (\n get_hosting_service_account_list_url(local_site_name),\n hosting_service_account_list_mimetype,\n accounts)\n\n def test_get_with_service(self):\n \"\"\"Testing the GET hosting-service-accounts/ API with service=\"\"\"\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n account = HostingServiceAccount.objects.create(service_name=b'github', username=b'bob')\n rsp = self.api_get(get_hosting_service_account_list_url(), query={b'service': b'github'}, expected_mimetype=hosting_service_account_list_mimetype)\n self.assertEqual(rsp[b'stat'], b'ok')\n self.assertEqual(len(rsp[b'hosting_service_accounts']), 1)\n self.compare_item(rsp[b'hosting_service_accounts'][0], account)\n\n def test_get_with_username(self):\n \"\"\"Testing the GET hosting-service-accounts/ API with username=\"\"\"\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'frank')\n rsp = self.api_get(get_hosting_service_account_list_url(), query={b'username': b'bob'}, expected_mimetype=hosting_service_account_list_mimetype)\n self.assertEqual(rsp[b'stat'], b'ok')\n self.assertEqual(len(rsp[b'hosting_service_accounts']), 1)\n self.compare_item(rsp[b'hosting_service_accounts'][0], account)\n\n def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):\n if post_valid_data:\n post_data = {b'username': b'bob', b'service_id': b'googlecode'}\n else:\n post_data = {}\n return (\n get_hosting_service_account_list_url(local_site_name),\n hosting_service_account_item_mimetype,\n post_data, [])\n\n def check_post_result(self, user, rsp):\n HostingServiceAccount.objects.get(pk=rsp[b'hosting_service_account'][b'id'])\n\n\n@six.add_metaclass(BasicTestsMetaclass)\nclass ResourceItemTests(BaseWebAPITestCase):\n \"\"\"Testing the HostingServiceAccountResource item APIs.\"\"\"\n fixtures = [\n b'test_users']\n sample_api_url = b'hosting-service-accounts//'\n resource = resources.hosting_service_account\n compare_item = _compare_item\n\n def setup_http_not_allowed_item_test(self, user):\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob')\n return get_hosting_service_account_item_url(account.pk)\n\n def setup_basic_get_test(self, user, with_local_site, local_site_name):\n if with_local_site:\n local_site = self.get_local_site(name=local_site_name)\n else:\n local_site = None\n account = HostingServiceAccount.objects.create(service_name=b'googlecode', username=b'bob', local_site=local_site)\n return (\n get_hosting_service_account_item_url(account, local_site_name),\n hosting_service_account_item_mimetype,\n account)", "sub_path": "pycfiles/ReviewBoard-3.0.17-py2.7/test_hosting_service_account.py", "file_name": "test_hosting_service_account.py", "file_ext": "py", "file_size_in_byte": 4978, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "reviewboard.webapi.tests.base.BaseWebAPITestCase", "line_number": 23, "usage_type": "name"}, {"api_name": "reviewboard.webapi.resources.resources.hosting_service_account", "line_number": 26, "usage_type": "attribute"}, {"api_name": "reviewboard.webapi.resources.resources", "line_number": 26, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_list_url", "line_number": 32, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 41, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 41, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_list_url", "line_number": 45, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mimetypes.hosting_service_account_list_mimetype", "line_number": 46, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 51, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 51, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 51, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 52, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 52, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 52, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_list_url", "line_number": 53, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mimetypes.hosting_service_account_list_mimetype", "line_number": 53, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 60, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 60, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 60, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 61, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 61, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 61, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_list_url", "line_number": 62, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mimetypes.hosting_service_account_list_mimetype", "line_number": 62, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_list_url", "line_number": 73, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mimetypes.hosting_service_account_item_mimetype", "line_number": 74, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.get", "line_number": 78, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 78, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 78, "usage_type": "name"}, {"api_name": "django.utils.six.add_metaclass", "line_number": 22, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mixins.BasicTestsMetaclass", "line_number": 22, "usage_type": "argument"}, {"api_name": "django.utils.six", "line_number": 22, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.base.BaseWebAPITestCase", "line_number": 82, "usage_type": "name"}, {"api_name": "reviewboard.webapi.resources.resources.hosting_service_account", "line_number": 87, "usage_type": "attribute"}, {"api_name": "reviewboard.webapi.resources.resources", "line_number": 87, "usage_type": "name"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 91, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 91, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 91, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_item_url", "line_number": 92, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects.create", "line_number": 99, "usage_type": "call"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount.objects", "line_number": 99, "usage_type": "attribute"}, {"api_name": "reviewboard.hostingsvcs.models.HostingServiceAccount", "line_number": 99, "usage_type": "name"}, {"api_name": "reviewboard.webapi.tests.urls.get_hosting_service_account_item_url", "line_number": 101, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mimetypes.hosting_service_account_item_mimetype", "line_number": 102, "usage_type": "name"}, {"api_name": "django.utils.six.add_metaclass", "line_number": 81, "usage_type": "call"}, {"api_name": "reviewboard.webapi.tests.mixins.BasicTestsMetaclass", "line_number": 81, "usage_type": "argument"}, {"api_name": "django.utils.six", "line_number": 81, "usage_type": "name"}]}
+{"seq_id": "64758368", "text": "import requests\nimport HTMLTestRunner\nimport BeautifulReport\n#反射\nclass MyRequest:\n def __init__(self,url,method='get',data=None,headers=None,is_json=False):\n method = method.lower()\n self.url = url\n self.data = data\n self.headers = headers\n self.is_json = is_json\n if hasattr(self,method):\n getattr(self,method)()\n\n def get(self):\n try:\n req = requests.get(self.url,self.data,headers=self.headers).json()\n except Exception as e:\n self.response = {\"error\":\"接口请求出错%s\"%e}\n else:\n self.response = req\n\n def post(self):\n try:\n if self.is_json:\n req = requests.post(self.url, json=self.data, headers=self.headers).json()\n else:\n req = requests.post(self.url, self.data, headers=self.headers).json()\n except Exception as e:\n self.response = {\"error\":\"接口请求出错%s\"%e}\n else:\n self.response = req\n\n\nif __name__ == '__main__':\n import jsonpath\n login = MyRequest('http://127.0.0.1:5000/login1',data={'username':'chenjie','password':'123456'})\n # sessionid = login.response.get('session_id')\n result = jsonpath.jsonpath(login.response,'$..session_id')\n if result:\n print('登录成功')\n else:\n print('登录失败')\n print(login.response)\n\n\n\n # data = {'sessionid':sessionid,'money':10000}\n # m = MyRequest('http://127.0.0.1:5000/pay',data=data)\n # print(m.response)\n", "sub_path": "day7/my_request.py", "file_name": "my_request.py", "file_ext": "py", "file_size_in_byte": 1538, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 17, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 26, "usage_type": "call"}, {"api_name": "requests.post", "line_number": 28, "usage_type": "call"}, {"api_name": "jsonpath.jsonpath", "line_number": 39, "usage_type": "call"}]}
+{"seq_id": "319218070", "text": "import pymongo\nfrom pymongo import MongoClient\nfrom bson import ObjectId\nimport json\nimport os\n\ndbURL = os.environ.get('COVIDDB')\nif dbURL == None:\n print(\"Database URL Not Found!\");\n\nclient = MongoClient(dbURL)\n\ndb = client.get_database('hackcovid')\ntestimonials = db.testimonials\n\ndef create(data):\n data['user'] = ObjectId(data['uid'])\n newTestimonial = testimonials.insert_one(data)\n try:\n id = newTestimonial.inserted_id\n return {\n 'status': 200,\n 'id': id\n }\n except Exception as e:\n return {\n 'status': 500,\n 'error': \"Server Error\"\n }\n\ndef get(query):\n allTestimonials = testimonials.find(query).sort('rdate', pymongo.DESCENDING).limit(5)\n return {\n 'count': allTestimonials.count(),\n 'data': allTestimonials\n }", "sub_path": "covidConnect/api/testimonialMongo.py", "file_name": "testimonialMongo.py", "file_ext": "py", "file_size_in_byte": 836, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.environ.get", "line_number": 7, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 7, "usage_type": "attribute"}, {"api_name": "pymongo.MongoClient", "line_number": 11, "usage_type": "call"}, {"api_name": "bson.ObjectId", "line_number": 17, "usage_type": "call"}, {"api_name": "pymongo.DESCENDING", "line_number": 32, "usage_type": "attribute"}]}
+{"seq_id": "304507680", "text": "'''handler for loading reel objects created by the ndnp handler'''\n\nimport csv\nimport logging\nimport os\nfrom rdflib import Graph, Literal, URIRef\nfrom classes import pcdm\nfrom classes.exceptions import ConfigException\nfrom namespaces import carriers, dcterms, rdf\n\n#============================================================================\n# DATA LOADING FUNCTION\n#============================================================================\n\ndef load(repo, batch_config):\n return Batch(repo, batch_config)\n\n#============================================================================\n# CSV BATCH CLASS\n#============================================================================\n\nclass Batch():\n\n '''iterator class representing the set of resources to be loaded'''\n\n def __init__(self, repo, batch_config):\n self.logger = logging.getLogger(\n __name__ + '.' + self.__class__.__name__\n )\n self.collection = pcdm.Collection()\n self.collection.uri = URIRef(batch_config.get('COLLECTION'))\n\n # check that the supplied collection exists and get title\n response = repo.get(\n self.collection.uri, headers={'Accept': 'application/rdf+xml'}\n )\n if response.status_code == 200:\n coll_graph = Graph().parse(data=response.text)\n self.collection.title = str(self.collection.uri)\n for (subj, pred, obj) in coll_graph:\n if str(pred) == \"http://purl.org/dc/elements/1.1/title\":\n self.collection.title = obj\n else:\n raise ConfigException(\n \"Collection URI {0} could not be reached.\".format(\n self.collection.uri\n )\n )\n self.collections = [self.collection]\n self.path = batch_config.get('LOCAL_PATH')\n self.files = [os.path.join(self.path, f) for f in os.listdir(self.path)]\n self.length = len(self.files)\n self.num = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.num < self.length:\n reel = Reel(self.files[self.num])\n reel.collections = self.collections\n self.num += 1\n return reel\n else:\n self.logger.info('Processing complete!')\n raise StopIteration()\n\n#============================================================================\n# NDNP REEL OBJECT\n#============================================================================\n\nclass Reel(pcdm.Item):\n\n '''class representing an NDNP reel'''\n\n def __init__(self, csvfile):\n super(Reel, self).__init__()\n self.id = os.path.splitext(os.path.basename(csvfile))[0]\n self.title = 'Reel Number {0}'.format(self.id)\n self.sequence_attr = ('Frame', 'sequence')\n self.path = csvfile\n\n with open(self.path, 'r') as f:\n reader = csv.DictReader(f)\n self.components = [\n Frame(self, row['sequence'], row['uri']) for row in reader\n ]\n\n self.graph.add(\n (self.uri, dcterms.title, Literal(self.title)))\n self.graph.add(\n (self.uri, dcterms.identifier, Literal(self.id)))\n self.graph.add(\n (self.uri, rdf.type, carriers.hd))\n\n#============================================================================\n# NDNP FRAME OBJECT\n#============================================================================\n\nclass Frame(pcdm.Component):\n\n '''class referencing an existing page object for purpose of reel creation'''\n\n def __init__(self, reel, sequence, uri):\n super(Frame, self).__init__()\n\n self.sequence = sequence\n self.uri = URIRef(uri)\n\n self.title = \"{0}, frame {1}\".format(reel.title, self.sequence)\n self.ordered = True\n", "sub_path": "handler/reel.py", "file_name": "reel.py", "file_ext": "py", "file_size_in_byte": 3839, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 27, "usage_type": "call"}, {"api_name": "classes.pcdm.Collection", "line_number": 30, "usage_type": "call"}, {"api_name": "classes.pcdm", "line_number": 30, "usage_type": "name"}, {"api_name": "rdflib.URIRef", "line_number": 31, "usage_type": "call"}, {"api_name": "rdflib.Graph", "line_number": 38, "usage_type": "call"}, {"api_name": "classes.exceptions.ConfigException", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 51, "usage_type": "call"}, {"api_name": "classes.pcdm.Item", "line_number": 72, "usage_type": "attribute"}, {"api_name": "classes.pcdm", "line_number": 72, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 78, "usage_type": "call"}, {"api_name": "csv.DictReader", "line_number": 84, "usage_type": "call"}, {"api_name": "namespaces.dcterms.title", "line_number": 90, "usage_type": "attribute"}, {"api_name": "namespaces.dcterms", "line_number": 90, "usage_type": "name"}, {"api_name": "rdflib.Literal", "line_number": 90, "usage_type": "call"}, {"api_name": "namespaces.dcterms.identifier", "line_number": 92, "usage_type": "attribute"}, {"api_name": "namespaces.dcterms", "line_number": 92, "usage_type": "name"}, {"api_name": "rdflib.Literal", "line_number": 92, "usage_type": "call"}, {"api_name": "namespaces.rdf.type", "line_number": 94, "usage_type": "attribute"}, {"api_name": "namespaces.rdf", "line_number": 94, "usage_type": "name"}, {"api_name": "namespaces.carriers.hd", "line_number": 94, "usage_type": "attribute"}, {"api_name": "namespaces.carriers", "line_number": 94, "usage_type": "name"}, {"api_name": "classes.pcdm.Component", "line_number": 100, "usage_type": "attribute"}, {"api_name": "classes.pcdm", "line_number": 100, "usage_type": "name"}, {"api_name": "rdflib.URIRef", "line_number": 108, "usage_type": "call"}]}
+{"seq_id": "246619690", "text": "# -*- coding: utf-8 -*- #\n# Copyright 2015 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Resource definitions for cloud platform apis.\"\"\"\n\nimport enum\n\n\nBASE_URL = 'https://run.googleapis.com/v1/'\nDOCS_URL = 'https://cloud.google.com/run/'\n\n\nclass Collections(enum.Enum):\n \"\"\"Collections for all supported apis.\"\"\"\n\n NAMESPACES = (\n 'namespaces',\n 'namespaces/{namespacesId}',\n {},\n [u'namespacesId'],\n True\n )\n NAMESPACES_CONFIGURATIONS = (\n 'namespaces.configurations',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/configurations/{configurationsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_DOMAINMAPPINGS = (\n 'namespaces.domainmappings',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/domainmappings/{domainmappingsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_REVISIONS = (\n 'namespaces.revisions',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/revisions/{revisionsId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_ROUTES = (\n 'namespaces.routes',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/routes/{routesId}',\n },\n [u'name'],\n True\n )\n NAMESPACES_SERVICES = (\n 'namespaces.services',\n '{+name}',\n {\n '':\n 'namespaces/{namespacesId}/services/{servicesId}',\n },\n [u'name'],\n True\n )\n PROJECTS = (\n 'projects',\n 'projects/{projectsId}',\n {},\n [u'projectsId'],\n True\n )\n PROJECTS_LOCATIONS = (\n 'projects.locations',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_CONFIGURATIONS = (\n 'projects.locations.configurations',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/configurations/'\n '{configurationsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_DOMAINMAPPINGS = (\n 'projects.locations.domainmappings',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/domainmappings/'\n '{domainmappingsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_REVISIONS = (\n 'projects.locations.revisions',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/revisions/'\n '{revisionsId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_ROUTES = (\n 'projects.locations.routes',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/routes/'\n '{routesId}',\n },\n [u'name'],\n True\n )\n PROJECTS_LOCATIONS_SERVICES = (\n 'projects.locations.services',\n '{+name}',\n {\n '':\n 'projects/{projectsId}/locations/{locationsId}/services/'\n '{servicesId}',\n },\n [u'name'],\n True\n )\n\n def __init__(self, collection_name, path, flat_paths, params,\n enable_uri_parsing):\n self.collection_name = collection_name\n self.path = path\n self.flat_paths = flat_paths\n self.params = params\n self.enable_uri_parsing = enable_uri_parsing\n", "sub_path": "google-cloud-sdk/lib/googlecloudsdk/third_party/apis/run/v1/resources.py", "file_name": "resources.py", "file_ext": "py", "file_size_in_byte": 3907, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "enum.Enum", "line_number": 24, "usage_type": "attribute"}]}
+{"seq_id": "592813237", "text": "from django.http.response import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render\n\nfrom .models import Post\nfrom .forms import PostForm\nfrom django.utils import timezone\n\n\ndef index(request):\n latest_post_list = Post.objects.order_by('-pub_date')[:5]\n \n if request.method == \"POST\":\n form = PostForm(request.POST)\n if form.is_valid():\n post = form.save(commit=False)\n post.pub_date = timezone.now()\n form.save()\n return HttpResponseRedirect('/#testimonials')\n else:\n form = PostForm()\n return render(request, 'base.html', {'form': form, 'latest_post_list': latest_post_list,})\n \n", "sub_path": "feirasjc/feirapage/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 688, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "models.Post.objects.order_by", "line_number": 10, "usage_type": "call"}, {"api_name": "models.Post.objects", "line_number": 10, "usage_type": "attribute"}, {"api_name": "models.Post", "line_number": 10, "usage_type": "name"}, {"api_name": "forms.PostForm", "line_number": 13, "usage_type": "call"}, {"api_name": "django.utils.timezone.now", "line_number": 16, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 16, "usage_type": "name"}, {"api_name": "django.http.response.HttpResponseRedirect", "line_number": 18, "usage_type": "call"}, {"api_name": "forms.PostForm", "line_number": 20, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "563061762", "text": "def forecast(country,\n data,\n ftype='poly1',\n samples=10000,\n startdate=None,\n enddate=None,\n limit=0,\n targetdate=None,\n tune=2000,\n chains=20,\n cpu_cores=4,\n return_inis=False,\n **kwargs):\n \n \"\"\"\n do monte carlo fit of posterior (gives also the point max estimate)\n\n :param country: Country name, if there is \"countries\" column in the data - else use \"World or \"\" for all data\n :param data: dataframe with \"dates\" (datetime) and \"cases\" columns - coses is the number of daily new cases\n :param ftype: 'polyN' where N is a number between 0 and a few (don't try more than 10 or so - becomes quite slow)\n or 'exp' for exponential\n :param samples: number of samples to use\n :param startdate: start date of the data to use as datetime.date\n :param enddate: end date of the data to use as datetime.date\n :param limit: take start date to be where cumulative count exceeds limit\n :param targetdate: datetime.date for prediction\n import datetime\n targetdate = datetime.datetime.strptime('2020-06-30','%Y-%m-%d').date()\n :param return_inis: don't run but return initial parameters\n :param **kwargs: model params if wanted to use like intercept=[int_mean,int_std]\n :return: fitresults\n \"\"\"\n \n import pymc3 as pm\n import datetime\n import pandas as pd\n\n from .utils import calculateStats, modelfit_eval_dates\n from .models import poly_model, exp_model, logistic_model\n \n if isinstance(startdate, str):\n startdate = pd.to_datetime(startdate)\n\n if country==\"World\" or country==\"all\" or len(country)==0:\n temp = data.sort_values('dates')\n temp['cases'] = temp.groupby(['dates'])['cases'].transform('sum')\n temp['deaths'] = temp.groupby(['dates'])['deaths'].transform('sum')\n temp.drop_duplicates(subset=['dates'], inplace=True)\n \n else:\n temp = data[data.countries == country].sort_values('dates')\n\n temp['cumcases']=temp.cases.cumsum().values\n if startdate == None:\n startdate = temp[temp.cumcases > limit].dates.dt.date.min()\n\n if enddate == None:\n enddate = temp[temp.cases > 0].dates.dt.date.max()\n \n temp_new = temp[(temp.dates.dt.date>=startdate) & (temp.dates.dt.date<=enddate)]\n intercept = next((value for key, value in kwargs.items() if key == 'intercept'), None)\n if intercept is None:\n intercept = temp_new.cumcases.values.min()\n kwargs['intercept'] = [intercept, intercept / 10 + 20]\n\n try:\n x0 = temp_new.dates.dt.date - startdate\n except:\n x0 = temp_new.dates - startdate\n\n x = x0.dt.days\n y = temp_new.cumcases.values\n\n if targetdate == None:\n xTarget = None\n else:\n xTarget = (targetdate - startdate).days\n\n log = 'lin'\n \n if ftype=='exp':\n slope = next((value for key, value in kwargs.items() if key == 'slope'), None)\n if slope is None:\n a10 = (y.max() - y[0]) / x.max()\n kwargs['slope'] = [a10 / 2, a10 / 4 + 10]\n if return_inis:\n return kwargs\n model, varnames, modelfun = exp_model(x, y, **kwargs)\n log = 'log'\n \n elif 'poly' in ftype:\n order = int(ftype[4:])\n a1 = next((value for key, value in kwargs.items() if key == 'a1'), None)\n if not a1:\n a10 = (y.max() - y[0]) / x.max()\n kwargs['a1'] = [a10, a10 / 4 + 20]\n if return_inis:\n return kwargs\n model, varnames, modelfun = poly_model(x, y, order, **kwargs)\n\n elif 'logis' in ftype or 'scurve' in ftype or 'sigmoid' in ftype:\n peak = next((value for key, value in kwargs.items() if key == 'peak'), None)\n if peak is None:\n peak0 = y.max() * 1.5\n kwargs['peak'] = [peak0, peak0 / 4]\n shifted = next((value for key, value in kwargs.items() if key == 'shifted'), None)\n if shifted is None:\n kwargs['shifted'] = [x[temp_new.cases.idxmax()], x.max() / 5]\n if return_inis:\n return kwargs\n model, varnames, modelfun = logistic_model(x, y, **kwargs)\n else:\n return None\n\n with model:\n step = pm.Slice()\n trace = pm.sample(samples, step=step, tune=tune, chains=chains, cores=cpu_cores) # , step, tune=2500, cores=10)\n\n varstats = []\n for va in varnames + ['sigma']:\n stats = calculateStats(trace[va]) # mean 2, std 3, 20% 5, 80% 7\n varstats.append([stats[2], stats[3], stats[5], stats[7]])\n\n sigma = sum(calculateStats(trace['sigma'])[2:4]) # mean + std\n\n plotstrs = ['%s COVID-19 cases %s model'%(country, ftype),\n '%s to %s'%(datetime.datetime.strftime(startdate, '%d.%m.%Y'),\n datetime.datetime.strftime(enddate, '%d.%m.%Y')),\n 'cumulative cases']\n df = modelfit_eval_dates(y, x, temp_new.dates,\n modelfun,\n varstats[0:-1],\n sigma=sigma,\n target=xTarget,\n plotstrs=plotstrs,\n log=log,\n varnames=varnames)\n\n for va in varnames + ['sigma']:\n stats = calculateStats(trace[va])\n df.loc[va + '_mean'] = stats[2]\n df.loc[va + '_std'] = stats[3]\n #df.loc[va + '_20%'] = stats[5]\n #df.loc[va + '_80%'] = stats[7]\n\n return df", "sub_path": "forecast.py", "file_name": "forecast.py", "file_ext": "py", "file_size_in_byte": 5514, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.to_datetime", "line_number": 42, "usage_type": "call"}, {"api_name": "models.exp_model", "line_number": 88, "usage_type": "call"}, {"api_name": "models.poly_model", "line_number": 99, "usage_type": "call"}, {"api_name": "models.logistic_model", "line_number": 111, "usage_type": "call"}, {"api_name": "pymc3.Slice", "line_number": 116, "usage_type": "call"}, {"api_name": "pymc3.sample", "line_number": 117, "usage_type": "call"}, {"api_name": "utils.calculateStats", "line_number": 121, "usage_type": "call"}, {"api_name": "utils.calculateStats", "line_number": 124, "usage_type": "call"}, {"api_name": "datetime.datetime.strftime", "line_number": 127, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 127, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strftime", "line_number": 128, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 128, "usage_type": "attribute"}, {"api_name": "utils.modelfit_eval_dates", "line_number": 130, "usage_type": "call"}, {"api_name": "utils.calculateStats", "line_number": 140, "usage_type": "call"}]}
+{"seq_id": "390881458", "text": "\"\"\"\n[user, user_avg_item, item]\n\"\"\"\n\nimport torch\nfrom torch import log, unsqueeze\nimport torch.nn as nn\nfrom torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\nimport numpy as np\nimport time\n\nclass _ATTR_NETWORK(nn.Module):\n def __init__(self, vocab_obj, args, device):\n super(_ATTR_NETWORK, self).__init__()\n\n self.m_device = device\n \n self.m_vocab_size = vocab_obj.vocab_size\n self.m_user_num = vocab_obj.user_num\n self.m_item_num = vocab_obj.item_num\n\n self.m_attr_embed_size = args.attr_emb_size\n self.m_user_embed_size = args.user_emb_size\n self.m_item_embed_size = args.item_emb_size\n\n self.m_attn_head_num = args.attn_head_num\n self.m_attn_layer_num = args.attn_layer_num\n\n self.m_output_hidden_size = args.output_hidden_size\n\n self.m_attn_linear_size = args.attn_linear_size\n\n # self.m_attr_embedding = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_user_embedding = nn.Embedding(self.m_user_num, self.m_user_embed_size)\n self.m_item_embedding = nn.Embedding(self.m_item_num, self.m_item_embed_size)\n\n encoder_layers = TransformerEncoderLayer(self.m_attr_embed_size, self.m_attn_head_num, self.m_attn_linear_size)\n self.m_attn = TransformerEncoder(encoder_layers, self.m_attn_layer_num)\n\n self.m_attr_embedding_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n # self.m_attr_embedding_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.m_output_attr_embedding_user = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_output_attr_embedding_item = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.m_output_attr_embedding_user_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_output_attr_embedding_item_x = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n\n self.f_init_weight()\n\n self = self.to(self.m_device)\n\n def f_init_weight(self):\n initrange = 0.1\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_user.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_item.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_user_x.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_output_attr_embedding_item_x.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_user_embedding.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_item_embedding.weight, -initrange, initrange)\n\n def f_generate_mask(self, length):\n max_len = length.max().item()\n # print(\"max_len\", max_len)\n mask = torch.arange(0, max_len).expand(len(length), max_len).to(length.device)\n mask = mask < length.unsqueeze(1)\n\n mask = ~mask\n\n return mask\n\n def f_get_avg_attr(self, attr, attr_lens):\n ### attr_user_embed: batch_size*seq_len*embed_size\n attr_embed = self.m_attr_embedding_x(attr) \n\n attr_mask = self.f_generate_mask(attr_lens)\n attr_mask = ~attr_mask\n attr_mask = attr_mask.unsqueeze(-1)\n\n masked_attr_embed = attr_embed*attr_mask\n\n attr_x = masked_attr_embed.sum(1)/attr_mask.sum(1)\n\n return attr_x\n\n def f_get_avg_attr_user(self, attr_item, item_lens): \n ### attr_user: user_num*item_num*embed_size\n ### item_mask: user_num*item_num\n\n # print(\"attr_item\", attr_item.size())\n # print(\"item_mask\", item_mask.size())\n\n # t0 = time.time()\n\n item_mask = self.f_generate_mask(item_lens)\n item_mask = ~item_mask\n\n attr_user = torch.zeros((*item_mask.size(), attr_item.size(-1)), device=attr_item.device)\n\n # print('step 0 {} seconds'.format(time.time() - t0))\n\n ### item_mask: user_num*item_num\n item_mask = item_mask.bool()\n # item_mask = item_mask.unsqueeze(-1)\n attr_user[item_mask] = attr_item\n\n attr_user = torch.sum(attr_user, dim=1)\n # attr_user = attr_user_mean/torch.sum(item_mask, dim=1, keepdim=True)\n\n # print('avg user {} seconds'.format(time.time() - t0))\n \n return attr_user, item_mask\n\n def f_get_logits(self, embed, attr):\n logits = torch.matmul(embed, attr.unsqueeze(-1))\n logits = logits.squeeze(-1)\n\n return logits\n \n def forward(self, ref_attr_item_user, ref_attr_len_item_user, ref_item_len_user, ref_attr_user_item, ref_attr_len_user_item, ref_user_len_item, user_ids, item_ids, pos_targets, pos_lens, neg_targets, neg_lens):\n\n attr_x_item_user = self.f_get_avg_attr(ref_attr_item_user, ref_attr_len_item_user)\n user_x, user_mask = self.f_get_avg_attr_user(attr_x_item_user, ref_item_len_user)\n\n attr_x_user_item = self.f_get_avg_attr(ref_attr_user_item, ref_attr_len_user_item)\n item_x, item_mask = self.f_get_avg_attr_user(attr_x_user_item, ref_user_len_item)\n\n # x = (user_x+item_x)/torch.sum(user_mask+item_mask, dim=1, keepdim=True)\n\n user_embed = self.m_user_embedding(user_ids) \n item_embed = self.m_item_embedding(item_ids)\n \n neg_attr_embed_user = self.m_output_attr_embedding_user(neg_targets)\n neg_attr_embed_item = self.m_output_attr_embedding_item(neg_targets)\n neg_attr_embed_user_x = self.m_output_attr_embedding_user_x(neg_targets)\n neg_attr_embed_item_x = self.m_output_attr_embedding_item_x(neg_targets)\n\n neg_logits_user = torch.matmul(neg_attr_embed_user, user_embed.unsqueeze(-1))\n neg_logits_user = neg_logits_user.squeeze(-1)\n\n neg_logits_item = torch.matmul(neg_attr_embed_item, item_embed.unsqueeze(-1))\n neg_logits_item = neg_logits_item.squeeze(-1)\n\n neg_logits_user_x = torch.matmul(neg_attr_embed_user_x, user_x.unsqueeze(-1))\n neg_logits_user_x = neg_logits_user_x.squeeze(-1)\n\n neg_logits_item_x = torch.matmul(neg_attr_embed_item_x, item_x.unsqueeze(-1))\n neg_logits_item_x = neg_logits_item_x.squeeze(-1)\n\n neg_logits = neg_logits_user+neg_logits_item+neg_logits_user_x+neg_logits_item_x\n \n neg_mask = self.f_generate_mask(neg_lens)\n neg_mask = ~neg_mask\n\n ### targets: batch_size*pos_num\n ### pos_embed: batch_size*pos_num*embed_size\n\n pos_attr_embed_user = self.m_output_attr_embedding_user(pos_targets)\n pos_attr_embed_item = self.m_output_attr_embedding_item(pos_targets)\n pos_attr_embed_user_x = self.m_output_attr_embedding_user_x(pos_targets)\n pos_attr_embed_item_x = self.m_output_attr_embedding_item_x(pos_targets)\n\n ### user_item_output: batch_size*ouput_size\n ### neg_logits: batch_size*neg_num\n pos_logits_user = torch.matmul(pos_attr_embed_user, user_embed.unsqueeze(-1))\n pos_logits_user = pos_logits_user.squeeze(-1)\n\n pos_logits_item = torch.matmul(pos_attr_embed_item, item_embed.unsqueeze(-1))\n pos_logits_item = pos_logits_item.squeeze(-1)\n\n pos_logits_user_x = torch.matmul(pos_attr_embed_user_x, user_x.unsqueeze(-1))\n pos_logits_user_x = pos_logits_user_x.squeeze(-1)\n\n pos_logits_item_x = torch.matmul(pos_attr_embed_item_x, item_x.unsqueeze(-1))\n pos_logits_item_x = pos_logits_item_x.squeeze(-1)\n \n pos_logits = pos_logits_user+pos_logits_item+pos_logits_user_x+pos_logits_item_x\n\n pos_mask = self.f_generate_mask(pos_lens)\n pos_mask = ~pos_mask\n\n logits = torch.cat([pos_logits, neg_logits], dim=-1)\n\n mask = torch.cat([pos_mask, neg_mask], dim=-1)\n\n new_targets = torch.cat([torch.ones_like(pos_targets), torch.zeros_like(neg_targets)], dim=1)\n\n new_targets = new_targets*mask\n\n return logits, mask, new_targets\n\n def f_eval_forward(self, ref_attr_item_user, ref_attr_len_item_user, ref_item_len_user, ref_attr_user_item, ref_attr_len_user_item, ref_user_len_item, user_ids, item_ids):\n\n ### attr_x_item_user: batch_size*embedding\n attr_x_item_user = self.f_get_avg_attr(ref_attr_item_user, ref_attr_len_item_user)\n user_x, user_mask = self.f_get_avg_attr_user(attr_x_item_user, ref_item_len_user)\n\n attr_x_user_item = self.f_get_avg_attr(ref_attr_user_item, ref_attr_len_user_item)\n item_x, item_mask = self.f_get_avg_attr_user(attr_x_user_item, ref_user_len_item)\n\n # x = (user_x+item_x)/torch.sum(user_mask+item_mask, dim=1, keepdim=True)\n\n user_embed = self.m_user_embedding(user_ids)\n item_embed = self.m_item_embedding(item_ids)\n\n logits_user = torch.matmul(user_embed, self.m_output_attr_embedding_user.weight.t())\n\n logits_item = torch.matmul(item_embed, self.m_output_attr_embedding_item.weight.t())\n\n logits_user_x = torch.matmul(user_x, self.m_output_attr_embedding_user_x.weight.t())\n\n logits_item_x = torch.matmul(item_x, self.m_output_attr_embedding_item_x.weight.t())\n\n logits = logits_user+logits_item+logits_user_x+logits_item_x\n\n return logits", "sub_path": "set2set/model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 9194, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.nn.Module", "line_number": 14, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 14, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 36, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.modules.transformer.TransformerEncoderLayer", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.nn.modules.transformer.TransformerEncoder", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn.Embedding", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 45, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 45, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 49, "usage_type": "name"}, {"api_name": "torch.nn.init.uniform_", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform_", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 60, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform_", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 62, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform_", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform_", "line_number": 66, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 66, "usage_type": "attribute"}, {"api_name": "torch.nn.init.uniform_", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "attribute"}, {"api_name": "torch.arange", "line_number": 73, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 106, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 115, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 123, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 146, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 149, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 152, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 173, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 176, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 179, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 182, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.zeros_like", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 216, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.matmul", "line_number": 220, "usage_type": "call"}]}
+{"seq_id": "161374934", "text": "import matplotlib.pyplot as plt\r\ndef twodrand():\r\n f = open ( 'input2' , 'r')\r\n l = []\r\n l = [ line.split() for line in f]\r\n x=[]\r\n y=[] \r\n n=len(l) \r\n for i in range(n-1):\r\n a=float(l[i][0])\r\n b=float(l[i][1])\r\n x.append(a)\r\n y.append(b)\r\n plt.plot(x,y,'ro')\r\n plt.xlabel(\"x values\")\r\n plt.ylabel(\"y values\")\r\n plt.title(\"scatter plot for ex2b\")\r\n\r\n\r\ntwodrand()\r\n ", "sub_path": "Python/Lab 4/ex22.py", "file_name": "ex22.py", "file_ext": "py", "file_size_in_byte": 442, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 14, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 14, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}]}
+{"seq_id": "354072035", "text": "from flask import Flask, render_template, request, make_response\nimport json\nfrom datetime import datetime\n\nIPLIST_PATH = \"/opt/localnet/portal/known_ips.json\" # change this\n\napp = Flask(__name__)\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef catch_all(path):\n if path == \"hotspot-detect.html\":\n # We can assume it's an Apple client\n with open(IPLIST_PATH, \"r\") as f:\n ip_list = json.load(f)\n if request.remote_addr in ip_list:\n return render_template(\"ios_success.html\")\n else:\n return render_template('information.html')\n elif path == \"registered.html\":\n with open(IPLIST_PATH, \"r\") as f:\n ip_list = json.load(f)\n ip_list[request.remote_addr] = datetime.now().isoformat()\n with open(IPLIST_PATH, \"w\") as f:\n json.dump(ip_list, f)\n return render_template(\"registered.html\")\n return \"blocked.\"\n\nif __name__ == '__main__':\n app.run(debug=True)", "sub_path": "captive_portal/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 990, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Flask", "line_number": 7, "usage_type": "call"}, {"api_name": "json.load", "line_number": 15, "usage_type": "call"}, {"api_name": "flask.request.remote_addr", "line_number": 16, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 16, "usage_type": "name"}, {"api_name": "flask.render_template", "line_number": 17, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 19, "usage_type": "call"}, {"api_name": "json.load", "line_number": 22, "usage_type": "call"}, {"api_name": "flask.request.remote_addr", "line_number": 23, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 23, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 23, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 23, "usage_type": "name"}, {"api_name": "json.dump", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.render_template", "line_number": 26, "usage_type": "call"}]}
+{"seq_id": "639932128", "text": "# @Time : 2019/6/15 7:56\n# @Author : Xu Huipeng\n# @Blog : https://brycexxx.github.io/\n\nfrom typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def generateTrees(self, n: int) -> List[TreeNode]:\n def dfs(first: int, last: int) -> List[TreeNode]:\n res = []\n for val in range(first, last):\n for l_tree in dfs(first, val):\n for r_tree in dfs(val + 1, last):\n root = TreeNode(val)\n root.left, root.right = l_tree, r_tree\n res += root\n return res or [None]\n\n return dfs(1, n + 1)\n\n def generateTrees1(self, n: int) -> List[TreeNode]:\n def generate(first, last):\n trees = []\n for root in range(first, last + 1):\n for left in generate(first, root - 1):\n for right in generate(root + 1, last):\n node = TreeNode(root)\n node.left = left\n node.right = right\n # 秀,逗号形成列表\n trees += node,\n return trees or [None]\n\n return generate(1, n)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.generateTrees1(3))\n", "sub_path": "generateTrees.py", "file_name": "generateTrees.py", "file_ext": "py", "file_size_in_byte": 1417, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "typing.List", "line_number": 18, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 17, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 30, "usage_type": "name"}]}
+{"seq_id": "557362926", "text": "from django.conf.urls import url\nfrom blog import views\n\n\nurlpatterns = [\n url('',views.PostListView.as_view(),name='post_list'),\n url('about/',views.AboutView.as_view(),name='about'),\n\n url('post/()',views.PostDetailView.as_view(),name='post_detail'),\n url('post/new/',views.CreatePostView.as_view(),name='post_new'),\n url('post/edit()',views.PostUpdateView.as_view(),name='post_edit'),\n url('post/remove/()',views.PostDeleteView.as_view(),name='post_remove'),\n url('drafts/',views.DraftListView.as_view(),name='post_draft_list'),\n url('post/comment/()',views.add_comment_to_post,name='add_comment_to_post'),\n url('comment/approve/()',views.comment_approve,name='comment_approve'),\n url('post/publish/()',views.post_publish,name='post_publish'),\n url('comment/remove/()',views.comment_remove,name='comment_remove'),\n]\n", "sub_path": "mysite/blog/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 908, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.urls.url", "line_number": 6, "usage_type": "call"}, {"api_name": "blog.views.PostListView.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "blog.views.PostListView", "line_number": 6, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 6, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "blog.views.AboutView.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "blog.views.AboutView", "line_number": 7, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "blog.views.PostDetailView.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "blog.views.PostDetailView", "line_number": 9, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "blog.views.CreatePostView.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "blog.views.CreatePostView", "line_number": 10, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 10, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "blog.views.PostUpdateView.as_view", "line_number": 11, "usage_type": "call"}, {"api_name": "blog.views.PostUpdateView", "line_number": 11, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 11, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "blog.views.PostDeleteView.as_view", "line_number": 12, "usage_type": "call"}, {"api_name": "blog.views.PostDeleteView", "line_number": 12, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 12, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "blog.views.DraftListView.as_view", "line_number": 13, "usage_type": "call"}, {"api_name": "blog.views.DraftListView", "line_number": 13, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 13, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "blog.views.add_comment_to_post", "line_number": 14, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 14, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "blog.views.comment_approve", "line_number": 15, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 15, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 16, "usage_type": "call"}, {"api_name": "blog.views.post_publish", "line_number": 16, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 16, "usage_type": "name"}, {"api_name": "django.conf.urls.url", "line_number": 17, "usage_type": "call"}, {"api_name": "blog.views.comment_remove", "line_number": 17, "usage_type": "attribute"}, {"api_name": "blog.views", "line_number": 17, "usage_type": "name"}]}
+{"seq_id": "492454126", "text": "import requests\nfrom bs4 import BeautifulSoup\n\ndef trade_spider(max_pages):\n page = 1\n while page <= max_pages:\n url = 'http://online.stepashka.com/filmy/#/page/' + str(page)\n source_code = requests.get(url) #all website code\n plain_text = source_code.text #links,images,texts from website page\n soup = BeautifulSoup(plain_text)\n for link in soup.findAll('div', {'class': 'video-title'}):\n # href = link.get('href')\n a_tag = link.a\n print(a_tag['href'])\n page += 1\n\n\ndef get_single_item_data(item_url):\n source_code = requests.get(item_url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text)\n for item_name in soup.findAll('div', {'class' : 'alternative-title'}):\n print(item_name.string)\n for link in soup.findAll('a'):\n href = link.get('href')\n print(href)\n\n\ntrade_spider(1)\n\n", "sub_path": "web2.1.py", "file_name": "web2.1.py", "file_ext": "py", "file_size_in_byte": 920, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 10, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 19, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "367804835", "text": "# -*- coding: utf-8 -*-\n\nimport json\nimport urllib\nimport asyncio\nimport argparse\nimport sys\nfrom aiohttp import ClientSession\n\nparser = argparse.ArgumentParser(description='Process arguments.')\nparser.add_argument('-i', '--id', type=str, required=True, help='id name')\nparser.add_argument('-k', '--key', type=str, required=True, help='keywords file')\n\n\nasync def get_app_list(bid, keyword, country, rank):\n\n itunes_url = 'http://itunes.apple.com/search?entity=macSoftware&term={}&country={}'.format(keyword, country)\n async with ClientSession() as session:\n async with session.get(itunes_url) as response:\n r = await response.text()\n j = json.loads(r)\n results = j[\"results\"]\n pos = 0\n for item in results:\n pos += 1\n t_id = item[\"trackId\"]\n if t_id == bid:\n break\n\n r_country = dict()\n r_country[country] = pos\n rank.setdefault(urllib.parse.unquote(keyword), []).append(r_country)\n\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n print(args)\n bid = args.id\n key_file = args.key\n if not bid or len(bid) == 0 or not key_file or len(key_file) == 0:\n sys.exit(0)\n\n loop = asyncio.get_event_loop()\n tasks = []\n result = dict()\n with open(key_file, encoding='utf-8') as fr:\n\n search_dict = json.loads(fr.read())\n for i in search_dict[\"items\"]:\n country_name = i['country']\n key_list = i[\"keys\"]\n for key in key_list:\n tasks.append(get_app_list(bid, urllib.parse.quote(key), country_name, result))\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n print(result)\n", "sub_path": "MyTool/mac_search.py", "file_name": "mac_search.py", "file_ext": "py", "file_size_in_byte": 1760, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 10, "usage_type": "call"}, {"api_name": "aiohttp.ClientSession", "line_number": 18, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 21, "usage_type": "call"}, {"api_name": "urllib.parse.unquote", "line_number": 32, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 32, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 42, "usage_type": "call"}, {"api_name": "asyncio.get_event_loop", "line_number": 44, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 49, "usage_type": "call"}, {"api_name": "urllib.parse.quote", "line_number": 54, "usage_type": "call"}, {"api_name": "urllib.parse", "line_number": 54, "usage_type": "attribute"}, {"api_name": "asyncio.wait", "line_number": 55, "usage_type": "call"}]}
+{"seq_id": "140253189", "text": "import scrapy\nfrom book.items import book_tag\nimport time\n\n\nclass tag_spider(scrapy.Spider):\n name = \"tag_spider\"\n\n def start_requests(self):\n urls = [\n 'https://book.douban.com/tag/?view=type&icn=index-sorttags-all'\n ]\n for url in urls:\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n # body = response.body\n td = response.xpath(\"//table[@class='tagCol']//td\")\n for s2 in td.getall():\n date = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n tag = book_tag()\n str = scrapy.Selector(text=s2)\n tag['tag_name'] = str.xpath(\"//a/text()\").get()\n tag['spider_url'] = str.xpath(\"//a/@href\").get()\n tag['tag_count'] = str.xpath(\"//b/text()\").get()[1:-1]\n tag['create_time'] = date\n tag['last_update_time'] = date\n yield tag\n", "sub_path": "book/book/spiders/tag_spider.py", "file_name": "tag_spider.py", "file_ext": "py", "file_size_in_byte": 928, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "scrapy.Spider", "line_number": 6, "usage_type": "attribute"}, {"api_name": "scrapy.Request", "line_number": 14, "usage_type": "call"}, {"api_name": "time.strftime", "line_number": 20, "usage_type": "call"}, {"api_name": "time.localtime", "line_number": 20, "usage_type": "call"}, {"api_name": "book.items.book_tag", "line_number": 21, "usage_type": "call"}, {"api_name": "scrapy.Selector", "line_number": 22, "usage_type": "call"}]}
+{"seq_id": "442024258", "text": "# coding=utf-8\n\n'''\n:author pyx0622@gmail.com\n:date 2016.08.13\n:desc 山东临沂租赁点抓取脚本\n\n 由百度 place api 获得 POI 经纬度,再根据叮嗒出行的经纬度列表接口,由这些经纬度查询所有公共自行车租赁点\n\n'''\nimport random\nimport time\nimport traceback\n\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import ObjectDict\n\nfrom scripts.parser import Parser\n\n# 临沂\nCITY_ID = 37013\nSID = 3\n\n\nclass DingdaParser(Parser):\n \"\"\"\n 数据来自叮嗒出行客户端\n \"\"\"\n\n @gen.coroutine\n def get_regions(self):\n regions = yield self.region_ps.get_regions(conds={\n \"cid\": CITY_ID\n })\n raise gen.Return(regions)\n\n @gen.coroutine\n def get_stations(self):\n regions = yield self.get_regions()\n for region in regions:\n for q in self.const.BAIDU_POI_Q:\n for page_num in range(0, 40):\n baidu_poi_list = yield self.infra_ps.get_city_poi(q, region.pname, region.rname, page_num, coord_type = 3)\n\n for item in baidu_poi_list.results:\n if not item.get(\"location\"):\n continue\n dingda_list = yield self.infra_ps.get_dingda_nearby(item.get(\"location\",{}).get(\"lng\", \"\"),\n item.get(\"location\",{}).get(\"lat\", \"\"))\n if dingda_list.data and dingda_list.data.stationLists:\n for item in dingda_list.data.stationLists:\n station = ObjectDict()\n station['code'] = str(item.get('id'))\n station['status'] = self.const.STATUS_INUSE\n # station['type'] = \"\"\n # station['total'] = \"\"\n station['name'] = item['name']\n # station['address'] = \"\"\n # station['district'] = \"\"\n station['longitude'] = item[\"longitude\"]\n station['latitude'] = item[\"latitude\"]\n # station['service_time'] = \"\"\n # station['is_24'] = \"\"\n # station['is_duty'] = \"\"\n print(station)\n yield self.update_station(station)\n\n x = int(random.random() * 10)\n print(x)\n yield self.async_sleep(x)\n\n print (\"end\")\n\n raise gen.Return(True)\n\n @gen.coroutine\n def update_station(self, item):\n\n \"\"\"\n 增加或更新数据库中租赁点信息\n :param station:\n :return:\n \"\"\"\n station = yield self.station_ps.get_station(conds={\n \"code\": item.code,\n \"cid\": CITY_ID,\n \"sid\": SID,\n })\n\n if station:\n # 存在,则更新\n self.station_ps.update_station(\n conds={\n \"id\": station.id\n },\n fields={\n \"status\": item.status,\n # \"total\": item.total,\n \"name\": item.name,\n # \"address\": item.address,\n # \"district\": item.district,\n # \"district_id\": item.district_id,\n \"longitude\": item.longitude,\n \"latitude\": item.latitude\n }\n )\n else:\n # 不存在,则增加\n yield self.station_ps.add_station(fields={\n \"code\": item.code,\n \"cid\": CITY_ID,\n \"sid\": SID,\n \"status\": item.status,\n # \"total\": item.total,\n \"name\": item.name,\n # \"address\": item.address,\n # \"district\": item.district,\n # \"district_id\": item.district_id,\n \"longitude\": item.longitude,\n \"latitude\": item.latitude\n })\n\n @gen.coroutine\n def async_sleep(self, timeout):\n # Sleep without blocking the IOLoop\n yield gen.Task(IOLoop.instance().add_timeout, time.time() + timeout)\n\n @gen.coroutine\n def runner(self):\n try:\n yield self.get_stations()\n except Exception as e:\n self.logger.error(traceback.format_exc())\n # 增加抓取记录 log\n yield self.scraplog_ps.add_scrap_log(fields={\n \"cid\": CITY_ID,\n \"status\": self.const.STATUS_UNUSE,\n })\n\n # 增加抓取记录 log\n yield self.scraplog_ps.add_scrap_log(fields={\n \"cid\": CITY_ID,\n \"status\": self.const.STATUS_INUSE,\n })\n\n IOLoop.instance().stop()\n\n\nif __name__ == \"__main__\":\n jp = DingdaParser()\n jp.runner()\n IOLoop.instance().start()\n", "sub_path": "scripts/bikestation/dingda_app/shandong_linyi.py", "file_name": "shandong_linyi.py", "file_ext": "py", "file_size_in_byte": 5047, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "scripts.parser.Parser", "line_number": 26, "usage_type": "name"}, {"api_name": "tornado.gen.Return", "line_number": 36, "usage_type": "call"}, {"api_name": "tornado.gen", "line_number": 36, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 31, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 31, "usage_type": "name"}, {"api_name": "tornado.util.ObjectDict", "line_number": 53, "usage_type": "call"}, {"api_name": "random.random", "line_number": 69, "usage_type": "call"}, {"api_name": "tornado.gen.Return", "line_number": 75, "usage_type": "call"}, {"api_name": "tornado.gen", "line_number": 75, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 38, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 38, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 77, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 77, "usage_type": "name"}, {"api_name": "tornado.gen.Task", "line_number": 127, "usage_type": "call"}, {"api_name": "tornado.gen", "line_number": 127, "usage_type": "name"}, {"api_name": "tornado.ioloop.IOLoop.instance", "line_number": 127, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 127, "usage_type": "name"}, {"api_name": "time.time", "line_number": 127, "usage_type": "call"}, {"api_name": "tornado.gen.coroutine", "line_number": 124, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 124, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 134, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop.instance", "line_number": 147, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 147, "usage_type": "name"}, {"api_name": "tornado.gen.coroutine", "line_number": 129, "usage_type": "attribute"}, {"api_name": "tornado.gen", "line_number": 129, "usage_type": "name"}, {"api_name": "tornado.ioloop.IOLoop.instance", "line_number": 153, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 153, "usage_type": "name"}]}
+{"seq_id": "317292879", "text": "import os\nimport csv\nimport json\nfrom datetime import datetime\n\nannot_base_dir = '/vision/u/bingbin/EPIC_KITCHENS_2018/annotations/'\nobj_base_dir = '/vision/u/bingbin/EPIC_KITCHENS_2018/object_detection_images/'\nepic_frame_format = '{:010d}.jpg'\n\ndef get_full_path(subset, pid, vid, frame):\n return os.path.join(obj_base_dir, subset, pid, vid, epic_frame_format.format(int(frame)))\n\ndef noun_categories():\n fcsv = '/sailhome/bingbin/VOG/dataset/EPIC/annotations/EPIC_noun_classes.csv'\n data = [line for line in csv.reader(open(fcsv, 'r'))]\n header = data[0]\n data = data[1:]\n cats = []\n for line in data:\n cats.append({\n 'id': int(line[0])+1,\n 'name': line[1],\n 'supercategory': line[1]\n })\n return cats\n\ndef parse_list(bboxes_str):\n bboxes = bboxes_str.split('),')\n ret = []\n for bbox in bboxes:\n bbox = bbox.replace('(', '').replace(')', '')\n bbox = bbox.replace('[', '').replace(']', '')\n bbox = bbox.replace(' ', '')\n bbox = [int(each) for each in bbox.split(',') if each]\n if bbox:\n ret += bbox,\n return ret\n\ndef to_COCO_format(fin, fout, subset):\n with open(fin, 'r') as handle:\n data = [line for line in csv.reader(handle)]\n header = data[0]\n data = data[1:]\n print('data: type:{} / len:{}'.format(type(data), len(data)))\n\n now = str(datetime.now())\n\n annotations = []\n images = []\n licenses = []\n uid = 0\n for [noun_cls, noun, pid, vid, frame, bboxes] in data:\n full_path = get_full_path(subset, pid, vid, frame)\n # print(full_path)\n if not os.path.exists(full_path):\n continue\n\n bboxes = parse_list(bboxes)\n if not bboxes:\n continue\n\n for bbox in bboxes:\n xmin, ymin = bbox[:2]\n xmax = xmin + bbox[2]\n ymax = ymin + bbox[3]\n seg = [xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]\n\n area = bbox[2] * bbox[3]\n if area < 1:\n continue\n\n annotations.append({\n 'area': bbox[2] * bbox[3],\n 'bbox': bbox,\n 'category_id': int(noun_cls)+1,\n 'id': uid,\n 'image_id': int(frame),\n 'iscrowd': 0,\n 'segmentation': [seg],\n })\n images.append({\n 'id': int(frame),\n 'width': 1920, # TODO: are EPIC images uni size?\n 'height': 1080,\n 'file_name': full_path,\n 'license': 'license placeholder',\n 'flickr_url': 'flickr_url placeholder',\n 'coco_url': 'coco_url placeholder',\n 'date_captured': now\n })\n licenses.append({\n 'id': uid+1,\n 'name': 'name placeholder',\n 'url': 'url placeholder'\n })\n uid += 1\n print('#bbox:', uid)\n\n info = {\n 'year': 2018,\n 'version': 'v1',\n 'description': 'placeholder for COCO info',\n 'contributor': 'BB (not really)',\n 'url': '',\n 'data_created': now\n }\n\n categories = noun_categories()\n\n with open(fout, 'w') as handle:\n json.dump({\n 'info':info,\n 'images':images,\n 'licenses':licenses,\n 'annotations':annotations,\n 'categories':categories\n }, handle)\n\nif __name__ == '__main__':\n fin = os.path.join(annot_base_dir, 'EPIC_train_object_labels.csv')\n fout = os.path.join(annot_base_dir, 'coco_train_object_labels_exists.json')\n to_COCO_format(fin, fout, 'train')\n", "sub_path": "utils_epic.py", "file_name": "utils_epic.py", "file_ext": "py", "file_size_in_byte": 3244, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.join", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "csv.reader", "line_number": 15, "usage_type": "call"}, {"api_name": "csv.reader", "line_number": 41, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 46, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 46, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 121, "usage_type": "call"}, {"api_name": "os.path", "line_number": 121, "usage_type": "attribute"}]}
+{"seq_id": "92179243", "text": "import pigpio\nimport logging\n\n################################################################\n# CLASS DEFINITION: CD4094\n\nclass CD4094():\n def __init__(self, pins=[17,27,22,23], channels=8):\n logging.info('[CD4094] Initializing new CD4094 instance.')\n logging.debug('[CD4094] Spinning up pigpio instance.')\n self.pi = pigpio.pi()\n self.pins = pins\n\n if len(self.pins) == 4:\n self.strobePin, self.dataPin, self.clockPin, self.enablePin = self.pins\n else:\n raise Exception('pins argument expects a list of 4 GPIO pins: strobe, data, clock, and enable.')\n \n if self.strobePin < 1 or self.strobePin > 40 or self.dataPin < 1 or self.dataPin > 40 or self.clockPin < 1 or self.clockPin > 40 or self.enablePin < 1 or self.enablePin > 40:\n raise Exception('GPIO pins must be positive integers from 1-40.')\n\n if channels is None or type(channels) != int:\n raise Exception('channels must be an integer')\n elif channels <= 0:\n raise Exception('channels must be greater than 0')\n\n self.channels = channels\n\n #logging.debug('[CD4094] Initializing pins.')\n for pin in self.pins:\n self.pi.set_mode(pin, pigpio.OUTPUT)\n self.pi.write(pin, 0)\n self.reset()\n self.enable()\n\n def enable(self):\n #logging.debug('[CD4094] Enabling output.')\n self.pi.write(self.enablePin, 1)\n\n def disable(self):\n #logging.debug('[CD4094] Disabling output.')\n self.pi.write(self.enablePin, 0)\n\n def reset(self):\n #logging.debug('[CD4094] Resetting state.')\n self.pi.write(self.dataPin, 0)\n for i in range(self.channels):\n self.pi.write(self.clockPin, 1)\n self.pi.write(self.clockPin, 0)\n self.pi.write(self.strobePin, 1)\n self.pi.write(self.strobePin, 0)\n\n def update(self, data):\n #logging.debug('[CD4094] Updating state: %s' % repr(data))\n for i in range(self.channels):\n try:\n bit = data[self.channels - i - 1] & 0b1\n except:\n bit = 0\n self.pi.write(self.dataPin, bit)\n self.pi.write(self.clockPin, 1)\n self.pi.write(self.clockPin, 0)\n self.pi.write(self.strobePin, 1)\n self.pi.write(self.strobePin, 0)\n\n def stop(self):\n logging.info('[CD4094] Stopping.')\n self.disable()\n self.reset()", "sub_path": "CD4094/CD4094.py", "file_name": "CD4094.py", "file_ext": "py", "file_size_in_byte": 2234, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.info", "line_number": 9, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 10, "usage_type": "call"}, {"api_name": "pigpio.pi", "line_number": 11, "usage_type": "call"}, {"api_name": "pigpio.OUTPUT", "line_number": 31, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 67, "usage_type": "call"}]}
+{"seq_id": "12091422", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as f\nimport numpy as np\n\n\nclass Uniform:\n\n def __init__(self, args):\n self.args = args\n self.device = torch.device('cpu')\n self.noise_distrib = torch.distributions.one_hot_categorical.OneHotCategorical(\n torch.tensor([1 / self.args.noise_dim for _ in range(self.args.noise_dim)]))\n\n def sample(self, state, test_mode):\n return self.noise_distrib.sample().to(self.device)\n\n def update_returns(self, state, noise, returns, test_mode, t):\n pass\n\n def to(self, device):\n self.device = device\n\n\nclass RNN(nn.Module):\n\n def __init__(self, input_shape, args):\n super(RNN, self).__init__()\n self.args = args\n\n self.fc1 = nn.Linear(input_shape, args.rnn_hidden_dim)\n # self.rnn = nn.GRUCell(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.rnn = nn.GRU(\n input_size=args.rnn_hidden_dim,\n num_layers=1,\n hidden_size=args.rnn_hidden_dim,\n batch_first=True,\n )\n\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def init_hidden(self):\n # make hidden states on same device as model\n return self.fc1.weight.new(1, self.args.rnn_hidden_dim).zero_()\n\n def forward(self, obs, hidden_state):\n if len(hidden_state.shape) == 2:\n hidden_state = hidden_state.unsqueeze(0)\n\n obs_c = obs.view(-1, obs.shape[-1])\n x = f.relu(self.fc1(obs_c))\n x = x.reshape(obs.shape[0], obs.shape[1], -1)\n\n h_in = hidden_state\n gru_out, _ = self.rnn(x, h_in)\n gru_out_c = gru_out.reshape(-1, gru_out.shape[-1])\n q = self.fc2(gru_out_c)\n q = q.reshape(obs.shape[0], obs.shape[1], -1)\n\n return q, gru_out\n\n\nclass MLP(nn.Module):\n\n def __init__(self, args):\n super(MLP, self).__init__()\n self.args = args\n self.fc = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def forward(self, hidden_state):\n q = self.fc(hidden_state)\n return q\n\n\nclass MLP_2(nn.Module):\n\n def __init__(self, args):\n super(MLP_2, self).__init__()\n self.args = args\n self.fc_1 = nn.Linear(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.fc_2 = nn.Linear(args.rnn_hidden_dim, args.n_actions)\n\n def forward(self, hidden_state):\n h1 = f.relu(self.fc_1(hidden_state))\n q = self.fc_2(h1)\n return q\n\n\nclass Critic(nn.Module):\n\n def __init__(self, input_shape, args):\n super(Critic, self).__init__()\n self.args = args\n self.fc1 = nn.Linear(input_shape, args.critic_dim)\n self.fc2 = nn.Linear(args.critic_dim, args.critic_dim)\n self.fc3 = nn.Linear(args.critic_dim, 1)\n\n def forward(self, inputs):\n x = f.relu(self.fc1(inputs))\n x = f.relu(self.fc2(x))\n q = self.fc3(x)\n return q\n", "sub_path": "CDS_GRF/network/base_net.py", "file_name": "base_net.py", "file_ext": "py", "file_size_in_byte": 2899, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "torch.device", "line_number": 11, "usage_type": "call"}, {"api_name": "torch.distributions.one_hot_categorical.OneHotCategorical", "line_number": 12, "usage_type": "call"}, {"api_name": "torch.distributions", "line_number": 12, "usage_type": "attribute"}, {"api_name": "torch.tensor", "line_number": 13, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 25, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 25, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 40, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 51, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 51, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 63, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 63, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 68, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 68, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 75, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 75, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 80, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 80, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 81, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 84, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 89, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 89, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 94, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 95, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 95, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 99, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 99, "usage_type": "name"}, {"api_name": "torch.nn.functional.relu", "line_number": 100, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 100, "usage_type": "name"}]}
+{"seq_id": "221671365", "text": "#!/usr/bin/env python\n\"\"\" \"\"\"\n\n# Script information for the file.\n__author__ = \"Philippe T. Pinard\"\n__email__ = \"philippe.pinard@gmail.com\"\n__version__ = \"0.1\"\n__copyright__ = \"Copyright (c) 2014 Philippe T. Pinard\"\n__license__ = \"GPL v3\"\n\n# Standard library modules.\nimport unittest\nimport logging\nfrom io import BytesIO\nimport xml.etree.ElementTree as etree\n\n# Third party modules.\n\n# Local modules.\nfrom pymontecarlo.fileformat.options.options import OptionsReader, OptionsWriter\n\nfrom pymontecarlo.options.options import Options\nfrom pymontecarlo.options.detector import BackscatteredElectronEnergyDetector\nfrom pymontecarlo.options.limit import ShowersLimit\nfrom pymontecarlo.options.model import ELASTIC_CROSS_SECTION\n\nfrom pymontecarlo.program.test_config import DummyProgram\n\n# Globals and constants variables.\n\nclass TestOptionsReader(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n\n self.reader = OptionsReader()\n\n etree.register_namespace('mc', 'http://pymontecarlo.sf.net')\n source = BytesIO(b'dummy1000')\n self.element = etree.parse(source).getroot()\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n\n def testcan_parse(self):\n self.assertTrue(self.reader.can_parse(self.element))\n\n def testparse(self):\n self.reader.parse(self.element)\n obj = self.reader.get()\n\n self.assertEqual(\"Test\", obj.name)\n self.assertEqual('51d62e0261f2449eb41a74e4cb4501e0', obj.uuid)\n\n self.assertEqual(1, len(obj.programs))\n self.assertEqual('dummy', list(obj.programs.aliases())[0])\n\n self.assertAlmostEqual(1234, obj.beam.energy_eV, 4)\n\n self.assertEqual(1, len(obj.detectors))\n det = obj.detectors['bse']\n self.assertAlmostEqual(0, det.limits_eV[0], 4)\n self.assertAlmostEqual(1234, det.limits_eV[1], 4)\n self.assertEqual(1000, det.channels)\n\n self.assertEqual(1, len(obj.limits))\n limits = list(obj.limits.iterclass(ShowersLimit))\n self.assertEqual(1, len(limits))\n self.assertEqual(5678, limits[0].showers)\n\n self.assertEqual(1, len(obj.models))\n models = list(obj.models.iterclass(ELASTIC_CROSS_SECTION))\n self.assertEqual(1, len(models))\n self.assertEqual(ELASTIC_CROSS_SECTION.rutherford, models[0])\n\nclass TestOptionsWriter(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n\n self.writer = OptionsWriter()\n\n self.obj = Options(name=\"Test\")\n\n self.obj.programs.add(DummyProgram())\n\n self.obj.beam.energy_eV = 1234\n\n self.obj.detectors['bse'] = BackscatteredElectronEnergyDetector(1000, (0, 1234))\n self.obj.limits.add(ShowersLimit(5678))\n self.obj.models.add(ELASTIC_CROSS_SECTION.rutherford)\n\n def tearDown(self):\n unittest.TestCase.tearDown(self)\n\n def testcan_convert(self):\n self.assertTrue(self.writer.can_convert(self.obj))\n\n def testconvert(self):\n self.writer.convert(self.obj)\n element = self.writer.get()\n\n self.assertEqual('Test', element.get('name'))\n\n self.assertEqual(self.obj.uuid, element.get('uuid'))\n\n children = list(element.find('programs'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('beam'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('geometry'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('detectors'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('limits'))\n self.assertEqual(1, len(children))\n\n children = list(element.find('models'))\n self.assertEqual(1, len(children))\n\n def testconvert2(self):\n uuid = self.obj.uuid\n self.writer.convert(self.obj)\n element = self.writer.get()\n self.assertEqual(uuid, element.get('uuid'))\n\nif __name__ == '__main__': # pragma: no cover\n logging.getLogger().setLevel(logging.DEBUG)\n unittest.main()\n", "sub_path": "pymontecarlo/fileformat/options/test_options.py", "file_name": "test_options.py", "file_ext": "py", "file_size_in_byte": 4924, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "unittest.TestCase", "line_number": 31, "usage_type": "attribute"}, {"api_name": "unittest.TestCase.setUp", "line_number": 34, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 34, "usage_type": "attribute"}, {"api_name": "pymontecarlo.fileformat.options.options.OptionsReader", "line_number": 36, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.register_namespace", "line_number": 38, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 38, "usage_type": "name"}, {"api_name": "io.BytesIO", "line_number": 39, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree.parse", "line_number": 40, "usage_type": "call"}, {"api_name": "xml.etree.ElementTree", "line_number": 40, "usage_type": "name"}, {"api_name": "unittest.TestCase.tearDown", "line_number": 43, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 43, "usage_type": "attribute"}, {"api_name": "pymontecarlo.options.limit.ShowersLimit", "line_number": 67, "usage_type": "argument"}, {"api_name": "pymontecarlo.options.model.ELASTIC_CROSS_SECTION", "line_number": 72, "usage_type": "argument"}, {"api_name": "pymontecarlo.options.model.ELASTIC_CROSS_SECTION.rutherford", "line_number": 74, "usage_type": "attribute"}, {"api_name": "pymontecarlo.options.model.ELASTIC_CROSS_SECTION", "line_number": 74, "usage_type": "name"}, {"api_name": "unittest.TestCase", "line_number": 76, "usage_type": "attribute"}, {"api_name": "unittest.TestCase.setUp", "line_number": 79, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 79, "usage_type": "attribute"}, {"api_name": "pymontecarlo.fileformat.options.options.OptionsWriter", "line_number": 81, "usage_type": "call"}, {"api_name": "pymontecarlo.options.options.Options", "line_number": 83, "usage_type": "call"}, {"api_name": "pymontecarlo.program.test_config.DummyProgram", "line_number": 85, "usage_type": "call"}, {"api_name": "pymontecarlo.options.detector.BackscatteredElectronEnergyDetector", "line_number": 89, "usage_type": "call"}, {"api_name": "pymontecarlo.options.limit.ShowersLimit", "line_number": 90, "usage_type": "call"}, {"api_name": "pymontecarlo.options.model.ELASTIC_CROSS_SECTION.rutherford", "line_number": 91, "usage_type": "attribute"}, {"api_name": "pymontecarlo.options.model.ELASTIC_CROSS_SECTION", "line_number": 91, "usage_type": "name"}, {"api_name": "unittest.TestCase.tearDown", "line_number": 94, "usage_type": "call"}, {"api_name": "unittest.TestCase", "line_number": 94, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 132, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 132, "usage_type": "attribute"}, {"api_name": "unittest.main", "line_number": 133, "usage_type": "call"}]}
+{"seq_id": "194464445", "text": "from ._builtin import Page, WaitPage\nfrom .models import Constants, MovieSelection\nfrom .forms import MovieForm, MovieResultForm\nfrom django.forms import modelformset_factory\nimport time\n\nMovieFormset = modelformset_factory(MovieSelection, form=MovieForm, fields=('isChecked',), extra=0)\nRemainingMovie = modelformset_factory(MovieSelection, form=MovieResultForm, fields=('embeddedVideo',), extra=0)\n\nclass Consent(Page):\n pass\n\nclass Introduction(Page):\n def before_next_page(self):\n # user has 60 minutes to complete as many pages as possible\n if self.player.id_in_group == 1:\n self.player.isSelecting = True\n else:\n self.player.isSelecting = False\n\nclass ParticipantInfo(Page):\n template_name = 'volleying/ParticipantInfo.html'\n form_model = 'player'\n form_fields = ['first_name']\n\n def error_message(self, values):\n if len(values[\"first_name\"]) == 0:\n return 'Please enter your name'\n\nclass WelcomeInstructions(Page):\n def before_next_page(self):\n self.player.participant.vars['expiry'] = time.time() + 120\n\nclass ChatWaitPage(WaitPage):\n template_name = 'volleying/WaitForChat.html'\n \n def after_all_players_arrive(self):\n self.is_displayed = True\n\nclass Chat(Page):\n def get_timeout_seconds(self):\n return 90\n\nclass Instructions(Page):\n\n def get_timeout_seconds(self):\n return 45\n \nclass WaitForOtherPlayer(WaitPage):\n template_name = 'volleying/WaitPage.html'\n\ndef sort_movies(movie):\n return movie.key\n\nclass Volley(Page):\n form_model = 'group'\n template_name = 'volleying/Volley.html'\n\n def vars_for_template(self):\n remaining_movies = self.player.group.get_remaining_movies()\n\n question_formset = MovieFormset(queryset=MovieSelection.objects.filter(group__exact=self.player.group).filter(isRemaining__exact=True))\n for (form, model) in zip(question_formset, remaining_movies):\n form.setLabel(model.description)\n\n return {\n 'movie_formset': question_formset\n }\n \n def before_next_page(self):\n self.group.numberVolleys +=1\n self.player.isSelecting = False\n self.player.get_others_in_group()[0].isSelecting = True\n self.group.volley = self.group.volley + \"[\" + \" \".join(self.group.get_remaining_movie_names()) + \"] \"\n\n all_movies = MovieSelection.objects.filter(group__exact=self.player.group)\n remaining_movies = all_movies.filter(isRemaining__exact=True)\n\n submitted_data = self.form.data\n \n movies_by_id = {mov.pk: mov for mov in remaining_movies}\n \n for i in range(len(remaining_movies)):\n input_prefix = 'form-%d-' % i\n mov_id1 = int(submitted_data[input_prefix + 'id'])\n isChecked = submitted_data.get(input_prefix + 'isChecked')\n\n mov = movies_by_id[mov_id1]\n\n if isChecked:\n mov.isChecked = True\n\n if not self.group.eliminateNegative:\n if not mov.isChecked:\n mov.isRemaining = False\n else: \n mov.isRemaining = True\n mov.isChecked = False\n else:\n if mov.isChecked:\n mov.isRemaining = False\n mov.isChecked = True\n\n mov.save()\n\n if self.timeout_happened:\n self.player.get_partner().timed_out = True\n self.player.timed_out = True\n\n def get_timeout_seconds(self):\n return 120\n \n def error_message(self, values):\n remaining_movies = self.player.group.get_remaining_movies()\n submitted_data = self.form.data\n num_checked = 0\n\n for i in range(len(remaining_movies)):\n input_prefix = 'form-%d-' % i\n isChecked = submitted_data.get(input_prefix + 'isChecked')\n\n if isChecked:\n num_checked+=1 \n\n if (len(remaining_movies) == num_checked):\n return 'You cannot select every movie trailer'\n elif (num_checked == 0):\n return 'You must select at least one movie trailer'\n else:\n pass\n\nclass VolleyPlayer1(Volley):\n def is_displayed(self):\n return (not self.player.timed_out) and self.group.volleying() and (self.player.id_in_group == 1)\n\nclass VolleyPlayer2(Volley):\n def is_displayed(self):\n return (not self.player.timed_out) and self.group.volleying() and (self.player.id_in_group == 2)\n\nclass TrailerIntro(Page):\n timeout_seconds = 15\n\n def vars_for_template(self):\n self.player.madeFinalDecision = not self.player.isSelecting\n self.player.selectedMovie = self.player.group.last_movie_name()\n\n return {\n \"finalMovie\": self.player.selectedMovie\n }\n\n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n self.player.selectedMovie = self.player.group.last_movie_name()\n\n\nclass Results(Page):\n def get_timeout_seconds(self):\n return 200\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def vars_for_template(self):\n remaining_movies = self.player.group.get_remaining_movies()\n question_formset = RemainingMovie(queryset=MovieSelection.objects.filter(group__exact=self.player.group).filter(isRemaining__exact=True))\n\n for (form, model) in zip(question_formset, remaining_movies):\n form.generateVideoHtml(model.embeddedVideo)\n\n return {\n 'movie_formset': question_formset\n }\n \nclass FollowUpQuestions(Page):\n form_model = 'player'\n form_fields = ['satisfied_trailer', 'satisfied_process', 'satisfied_treated', 'willing_to', 'comment']\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n if self.timeout_happened:\n self.player.timed_out = True\n\nclass ManipulationChecks(Page):\n form_fields = ['manip_question']\n\nclass Demographics(Page):\n form_model = 'player'\n form_fields = ['sonaID', 'age', 'race', 'gender']\n \n def is_displayed(self):\n return not self.player.timed_out\n\n def before_next_page(self):\n if self.timeout_happened:\n self.player.timed_out = True\n\nclass Conclusion(Page):\n pass\n\n\npage_sequence = [\n Consent,\n Introduction,\n ParticipantInfo,\n WelcomeInstructions,\n ChatWaitPage,\n Chat,\n Instructions,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n VolleyPlayer1,\n WaitForOtherPlayer,\n VolleyPlayer2,\n WaitForOtherPlayer,\n TrailerIntro,\n Results,\n FollowUpQuestions,\n Demographics,\n Conclusion\n]\n", "sub_path": "volleying/pages.py", "file_name": "pages.py", "file_ext": "py", "file_size_in_byte": 7165, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.forms.modelformset_factory", "line_number": 7, "usage_type": "call"}, {"api_name": "models.MovieSelection", "line_number": 7, "usage_type": "argument"}, {"api_name": "forms.MovieForm", "line_number": 7, "usage_type": "name"}, {"api_name": "django.forms.modelformset_factory", "line_number": 8, "usage_type": "call"}, {"api_name": "models.MovieSelection", "line_number": 8, "usage_type": "argument"}, {"api_name": "forms.MovieResultForm", "line_number": 8, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 10, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 13, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 21, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 30, "usage_type": "name"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "_builtin.WaitPage", "line_number": 34, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 40, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 44, "usage_type": "name"}, {"api_name": "_builtin.WaitPage", "line_number": 49, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 55, "usage_type": "name"}, {"api_name": "models.MovieSelection.objects.filter", "line_number": 62, "usage_type": "call"}, {"api_name": "models.MovieSelection.objects", "line_number": 62, "usage_type": "attribute"}, {"api_name": "models.MovieSelection", "line_number": 62, "usage_type": "name"}, {"api_name": "models.MovieSelection.objects.filter", "line_number": 76, "usage_type": "call"}, {"api_name": "models.MovieSelection.objects", "line_number": 76, "usage_type": "attribute"}, {"api_name": "models.MovieSelection", "line_number": 76, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 140, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 158, "usage_type": "name"}, {"api_name": "models.MovieSelection.objects.filter", "line_number": 167, "usage_type": "call"}, {"api_name": "models.MovieSelection.objects", "line_number": 167, "usage_type": "attribute"}, {"api_name": "models.MovieSelection", "line_number": 167, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 176, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 187, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 190, "usage_type": "name"}, {"api_name": "_builtin.Page", "line_number": 201, "usage_type": "name"}]}
+{"seq_id": "493172646", "text": "import requests\r\nimport json\r\n\r\nurl = 'https://reqres.in/api/users/2'\r\n\r\nfile = open('C:\\\\Users\\\\Arman\\\\PycharmProjects\\\\requests\\\\file\\\\createUser.json')\r\njson_input = file.read()\r\njson_request = json.loads(json_input)\r\nresponse = requests.put(url, json_request)\r\nprint(response, ' - ', response.content)\r\n\r\n\r\n", "sub_path": "apiTesting/PutUser.py", "file_name": "PutUser.py", "file_ext": "py", "file_size_in_byte": 311, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "json.loads", "line_number": 8, "usage_type": "call"}, {"api_name": "requests.put", "line_number": 9, "usage_type": "call"}]}
+{"seq_id": "185079723", "text": "from nokia import NokiaAuth\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nfrom dash_app import dash_app\nimport dash_core_components as dcc\nfrom lib.withingsAPI import withings_connected, connect_withings_link\nfrom oura import OuraOAuth2Client\nfrom lib.withingsAPI import save_withings_token\nimport configparser\nimport re\nimport time\n\nfrom nokia import NokiaAuth, NokiaApi\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nclient_id = config.get('withings', 'client_id')\nclient_secret = config.get('withings', 'client_secret')\nredirect_uri = config.get('withings', 'redirect_uri')\n\nauth_client = NokiaAuth(client_id, client_secret, callback_uri=redirect_uri)\n\nlayout = html.Div(id='withings-auth-canvas', children=[\n html.Div(id='withings-token-refresh', style={'display': 'none'}),\n dcc.Loading(html.Div(id='withings-auth-layout'))\n])\n\n\ndef test_withings_connection():\n time.sleep(3)\n if not withings_connected():\n return html.Div(style={'textAlign': 'center'}, className='twelve columns', children=[\n html.A(html.Button('Connect'),\n href=connect_withings_link(auth_client))\n ])\n else:\n return html.I('Withings Connected!')\n\n\ndef generate_withings_auth():\n return [\n html.Div(id='authorize-withings-container', className='twelve columns maincontainer',\n children=[\n html.H4('Withings Connection'),\n html.Div(id='withings-auth', children=[test_withings_connection()]\n ), ])]\n\n\n# Callback for authorizing withings tokens\n@dash_app.callback(Output('withings-token-refresh', 'children'),\n [Input('url', 'search')],\n [State('url', 'pathname')])\ndef update_tokens(token, pathname):\n if 'withings' in pathname:\n dash_app.server.logger.debug(\n '*******************************************************************************************************************')\n if token:\n auth_code = re.findall('=(?<=\\=)(.*?)(?=\\&)', token)[0]\n dash_app.server.logger.debug(\n 'AUTH CODE = {}'.format(auth_code))\n\n creds = auth_client.get_credentials(auth_code)\n dash_app.server.logger.debug(\n 'CREDS = {}'.format(creds))\n\n save_withings_token(creds)\n\n\n# Main Dashboard Generation Callback\n@dash_app.callback(\n Output('withings-auth-layout', 'children'),\n [Input('withings-auth-canvas', 'children')]\n)\ndef settings_dashboard(dummy):\n return generate_withings_auth()\n", "sub_path": "pages/authorize/withings.py", "file_name": "withings.py", "file_ext": "py", "file_size_in_byte": 2618, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "configparser.ConfigParser", "line_number": 15, "usage_type": "call"}, {"api_name": "nokia.NokiaAuth", "line_number": 22, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 24, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 25, "usage_type": "call"}, {"api_name": "dash_core_components.Loading", "line_number": 26, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 26, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 31, "usage_type": "call"}, {"api_name": "lib.withingsAPI.withings_connected", "line_number": 32, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 33, "usage_type": "call"}, {"api_name": "dash_html_components.A", "line_number": 34, "usage_type": "call"}, {"api_name": "dash_html_components.Button", "line_number": 34, "usage_type": "call"}, {"api_name": "lib.withingsAPI.connect_withings_link", "line_number": 35, "usage_type": "call"}, {"api_name": "dash_html_components.I", "line_number": 38, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 43, "usage_type": "call"}, {"api_name": "dash_html_components.H4", "line_number": 45, "usage_type": "call"}, {"api_name": "dash_html_components.Div", "line_number": 46, "usage_type": "call"}, {"api_name": "dash_app.dash_app.server.logger.debug", "line_number": 56, "usage_type": "call"}, {"api_name": "dash_app.dash_app.server", "line_number": 56, "usage_type": "attribute"}, {"api_name": "dash_app.dash_app", "line_number": 56, "usage_type": "name"}, {"api_name": "re.findall", "line_number": 59, "usage_type": "call"}, {"api_name": "dash_app.dash_app.server.logger.debug", "line_number": 60, "usage_type": "call"}, {"api_name": "dash_app.dash_app.server", "line_number": 60, "usage_type": "attribute"}, {"api_name": "dash_app.dash_app", "line_number": 60, "usage_type": "name"}, {"api_name": "dash_app.dash_app.server.logger.debug", "line_number": 64, "usage_type": "call"}, {"api_name": "dash_app.dash_app.server", "line_number": 64, "usage_type": "attribute"}, {"api_name": "dash_app.dash_app", "line_number": 64, "usage_type": "name"}, {"api_name": "lib.withingsAPI.save_withings_token", "line_number": 67, "usage_type": "call"}, {"api_name": "dash_app.dash_app.callback", "line_number": 51, "usage_type": "call"}, {"api_name": "dash_app.dash_app", "line_number": 51, "usage_type": "name"}, {"api_name": "dash.dependencies.Output", "line_number": 51, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 52, "usage_type": "call"}, {"api_name": "dash.dependencies.State", "line_number": 53, "usage_type": "call"}, {"api_name": "dash_app.dash_app.callback", "line_number": 71, "usage_type": "call"}, {"api_name": "dash_app.dash_app", "line_number": 71, "usage_type": "name"}, {"api_name": "dash.dependencies.Output", "line_number": 72, "usage_type": "call"}, {"api_name": "dash.dependencies.Input", "line_number": 73, "usage_type": "call"}]}
+{"seq_id": "37340776", "text": "from azure.storage import CloudStorageAccount\r\nfrom azure.storage.blob import BlockBlobService, PageBlobService, AppendBlobService\r\nimport os\r\nimport config\r\n\r\n'''\r\nFurther reference:\r\n # 1. connect to the current blob\r\n https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python-legacy\r\n 2. advanced properties\r\n https://github.com/Azure-Samples/storage-blob-python-getting-started/blob/master/blob_advanced_samples.py\r\n 3. create metadata and etc\r\n https://github.com/Azure/azure-storage-python/blob/master/samples/blob/block_blob_usage.py\r\n 4. Quickstart with blobs\r\n https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python\r\n'''\r\n\r\n# 0. Setup account\r\nif config.IS_EMULATED:\r\n account = CloudStorageAccount(is_emulated=True)\r\nelse:\r\n account_name = config.STORAGE_ACCOUNT_NAME\r\n account_key = config.STORAGE_ACCOUNT_KEY\r\n account = CloudStorageAccount(account_name, account_key)\r\n\r\n\r\n# 1. Create the BlockBlockService that the system uses to call the Blob service for the storage account.\r\nblock_blob_service = account.create_block_blob_service()\r\n\r\n# 2. List the blobs in the container.\r\nprint(\"\\nList blobs in the container\")\r\ngenerator = block_blob_service.list_blobs('test01')\r\nfor blob in generator:\r\n print(\"\\t Blob name: \" + blob.name)\r\n\r\n# 3. Set metadata to blob\r\nmetadata = {'val1': 'foo', 'val2':'blah'}\r\nblock_blob_service.set_blob_metadata('test01', 'a dopo.txt', metadata)\r\n\r\n# 4. Explore the metadata of the blobs and properties\r\nprint('1. get blob properties')\r\nblob = block_blob_service.get_blob_properties('test01', 'a dopo.txt')\r\nprint(blob.name)\r\nprint(blob.properties.last_modified)\r\nprint(blob.metadata['val2'])\r\n\r\n'''\r\nfor key in blob.metadata:\r\n print(blob.metadata['val2'])\r\n'''", "sub_path": "explore_blob.py", "file_name": "explore_blob.py", "file_ext": "py", "file_size_in_byte": 1803, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "config.IS_EMULATED", "line_number": 19, "usage_type": "attribute"}, {"api_name": "azure.storage.CloudStorageAccount", "line_number": 20, "usage_type": "call"}, {"api_name": "config.STORAGE_ACCOUNT_NAME", "line_number": 22, "usage_type": "attribute"}, {"api_name": "config.STORAGE_ACCOUNT_KEY", "line_number": 23, "usage_type": "attribute"}, {"api_name": "azure.storage.CloudStorageAccount", "line_number": 24, "usage_type": "call"}]}
+{"seq_id": "544447615", "text": "from django.contrib.auth.models import User\nfrom django.db import migrations\n\nfrom ..models import Tag, Article\n\n\ndef create_data(*args):\n admin = User.objects.create_superuser(username='admin', email='admin@example.com', password='password')\n admin.save()\n\n tag1 = Tag(name='Journeys')\n tag2 = Tag(name='Food')\n tag3 = Tag(name='Sports')\n tag4 = Tag(name='Good day')\n tag5 = Tag(name='Awesome day')\n Tag.objects.bulk_create([tag1, tag2, tag3, tag4, tag5])\n\n article1 = Article(author=admin, title='My First Article')\n article2 = Article(author=admin, title='New Recipe')\n article3 = Article(author=admin, title='Snowboarding with my friends')\n article4 = Article(author=admin, title='My Collection of Rarest Vinyls')\n article5 = Article(author=admin, title='Going Camping!')\n article6 = Article(author=admin, title='My Promotion')\n Article.objects.bulk_create([article1, article2, article3, article4, article5, article6])\n\n tag1.articles.set([article3, article5])\n tag2.articles.set([article2])\n tag3.articles.set([article3])\n tag4.articles.set([article2, article4])\n tag5.articles.set([article1, article6])\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.RunPython(create_data),\n ]\n", "sub_path": "blog/src/blog/migrations/0002_create_test_data.py", "file_name": "0002_create_test_data.py", "file_ext": "py", "file_size_in_byte": 1340, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.contrib.auth.models.User.objects.create_superuser", "line_number": 8, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.User.objects", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.models.User", "line_number": 8, "usage_type": "name"}, {"api_name": "models.Tag", "line_number": 11, "usage_type": "call"}, {"api_name": "models.Tag", "line_number": 12, "usage_type": "call"}, {"api_name": "models.Tag", "line_number": 13, "usage_type": "call"}, {"api_name": "models.Tag", "line_number": 14, "usage_type": "call"}, {"api_name": "models.Tag", "line_number": 15, "usage_type": "call"}, {"api_name": "models.Tag.objects.bulk_create", "line_number": 16, "usage_type": "call"}, {"api_name": "models.Tag.objects", "line_number": 16, "usage_type": "attribute"}, {"api_name": "models.Tag", "line_number": 16, "usage_type": "name"}, {"api_name": "models.Article", "line_number": 18, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 19, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 20, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 21, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 22, "usage_type": "call"}, {"api_name": "models.Article", "line_number": 23, "usage_type": "call"}, {"api_name": "models.Article.objects.bulk_create", "line_number": 24, "usage_type": "call"}, {"api_name": "models.Article.objects", "line_number": 24, "usage_type": "attribute"}, {"api_name": "models.Article", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.migrations.Migration", "line_number": 33, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 33, "usage_type": "name"}, {"api_name": "django.db.migrations.RunPython", "line_number": 39, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 39, "usage_type": "name"}]}
+{"seq_id": "370435605", "text": "import cv2\nimport numpy as np\nfrom matplotlib.pyplot import plot, show, draw, clf, hist, figure\nimport time\nimport sys\n\ndef avg_hist(hist, length):\n val = 0\n count = 0\n for i in range(length):\n count += hist[i]\n val += i * hist[i]\n return val/count\n\ndef std_dev_hist(hist, length):\n avg = avg_hist(hist, length)\n count = 0\n sqerr = 0\n for i in range(length):\n count += hist[i]\n sqerr += hist[i] * (avg-i)**2\n return (sqerr / count)**0.5\n\ndef lp_filter_array(new, old, alpha=0.05):\n res = []\n for x in range(len(new)):\n res.append(new[x]*alpha + old[x]*(1.0 - alpha))\n return res\n\ndef clamp(n, minn, maxn):\n return max(min(maxn, n), minn) \n \ncap = cv2.VideoCapture(\"./bitbuckets.mp4\")\n# cap = cv2.VideoCapture(\"./dropshot.mp4\")\noutput = cv2.VideoWriter(\"./output.mp4\", int(cap.get(cv2.CAP_PROP_FOURCC)),\n int(cap.get(cv2.CAP_PROP_FPS)), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))\n\nprint(\"FourCC: {0}\".format(int(cap.get(cv2.CAP_PROP_FOURCC))))\nprint(\"FPS: {0}\".format(int(cap.get(cv2.CAP_PROP_FPS))))\nprint(\"OpenCV Version: {0}\".format(cv2.__version__))\n\noldtime = time.time()\nfps = 0.0\n\n# avg_vals = [70,180,220] #for dropshot\n# avg_stds = [10, 20, 10]\navg_vals = [80,60,180] #for bitbuckets\navg_stds = [5, 15, 20]\nupper = np.array([int(avg_vals[x] + 2.5*avg_stds[x]) for x in range(3)])\nlower = np.array([int(avg_vals[x] - 2.5*avg_stds[x]) for x in range(3)])\n\n#plus_avg = avg_stds\n#med_avg = avg_vals\n#minus_avg = avg_stds\n\nhue_l=[80]\nsat_l=[60]\nvals_l=[180]\n\nwhile(True):\n ret, frame = cap.read()\n frame = cv2.pyrDown(frame)\n\n hsv = cv2.blur(cv2.cvtColor(frame, cv2.COLOR_BGR2HSV), (5,5))\n\n # cv2.imshow('hsv', hsv)\n\n hsvthresh = cv2.inRange(hsv, lower, upper)\n mask = cv2.bitwise_and(hsv, hsv, mask=hsvthresh)\n\n cv2.imshow('thresh', hsvthresh)\n cv2.imshow('mask', mask)\n\n im2, contours, hierarchy = cv2.findContours(hsvthresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\n goalx = -1\n goaly = -1\n\n for contour in contours:\n moments = cv2.moments(contour)\n\n if moments['m00'] > 0:\n area = cv2.contourArea(contour)\n perim = cv2.arcLength(contour, True)\n\n if area < 100:\n continue\n\n hull = cv2.convexHull(contour)\n hullarea = cv2.contourArea(hull)\n rect = cv2.minAreaRect(contour)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n boxarea = cv2.contourArea(box)\n\n aspect = rect[1][1]/rect[1][0]\n\n adjusted_rect = rect\n adjusted_rect = ((rect[0][0], rect[0][1]-rect[1][0]*0.15), (adjusted_rect[1][0] * 0.40, adjusted_rect[1][1] * 0.40), rect[2])\n adjusted_box = cv2.boxPoints(adjusted_rect)\n adjusted_box = np.int0(adjusted_box)\n adjusted_mask = np.zeros(hsvthresh.shape,np.uint8)\n cv2.drawContours(adjusted_mask,[adjusted_box],0,255,-1)\n adjusted_mask = cv2.bitwise_not(adjusted_mask, adjusted_mask)\n\n mask = np.zeros(hsvthresh.shape,np.uint8)\n cv2.drawContours(mask,[contour],0,255,-1)\n # pixelpoints = np.transpose(np.nonzero(mask))\n # cv2.imshow('points', mask)\n adjusted_mask = cv2.bitwise_and(adjusted_mask, mask)\n # cv2.imshow('adjusted', cv2.bitwise_xor(adjusted_mask, mask))\n present = not(np.bitwise_xor(adjusted_mask,mask).any())\n\n if present and aspect > 0.4 and aspect < 2.5 and hullarea > 500:\n goalx = moments['m10']/moments['m00']\n goaly = moments['m01']/moments['m00']\n cv2.drawContours(frame,[adjusted_box],0,(0,0,255),2)\n cv2.putText(frame, 'AREA:{0:.2f}'.format(hullarea), (10,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n hist_hue = cv2.calcHist([hsv],[0],mask,[180],[0,180])\n hist_sat = cv2.calcHist([hsv],[1],mask,[256],[0,256])\n hist_val = cv2.calcHist([hsv],[2],mask,[256],[0,256])\n\n # compute cumulative histogram\n hist_hue_cs = np.cumsum(hist_hue)\n hist_hue_cs = hist_hue_cs / hist_hue_cs[179]\n hist_sat_cs = np.cumsum(hist_sat)\n hist_sat_cs = hist_sat_cs / hist_sat_cs[255]\n hist_val_cs = np.cumsum(hist_val)\n hist_val_cs = hist_val_cs / hist_val_cs[255]\n \n # compute the quantiles\n #low=0.18\n #med=0.5\n #high=0.84\n #hue_low = np.amin(np.where(hist_hue_cs >=low))\n #sat_low = np.amin(np.where(hist_sat_cs >=low))\n #val_low = np.amin(np.where(hist_val_cs >=low))\n #hue_med = np.amin(np.where(hist_hue_cs >=med))\n #sat_med = np.amin(np.where(hist_sat_cs >=med))\n #val_med = np.amin(np.where(hist_val_cs >=med))\n #hue_high = np.amin(np.where(hist_hue_cs >=high))\n #sat_high = np.amin(np.where(hist_sat_cs >=high))\n #val_high = np.amin(np.where(hist_val_cs >=high))\n ## unfortunately this command does not work with mask\n ## p25, p50, p75 = np.percentile(img, (25,50,75))\n \n ## compute the boundaries and keep them wide\n #hue_plus = max(hue_high-hue_med, 5)\n #hue_minus = max(hue_med-hue_low, 5)\n #sat_plus = max(sat_high-sat_med, 10)\n #sat_minus = max(sat_med-sat_low, 10)\n #val_plus = max(val_high-val_med, 10)\n #val_minus = max(val_med-val_low, 10)\n\n #plus_avg = lp_filter_array([hue_plus, sat_plus, val_plus], plus_avg, 0.05)\n #med_avg = lp_filter_array([hue_med, sat_med, val_med], med_avg, 0.05)\n #minus_avg = lp_filter_array([hue_minus, sat_minus, val_minus], minus_avg, 0.05)\n\n #upper = np.array([int(med_avg[0] + 2.5*plus_avg[0]), int(med_avg[1] + 2.5*plus_avg[1]), int(med_avg[2] + 2.5*plus_avg[2] ) ])\n #lower = np.array([int(med_avg[0] - 2.5*minus_avg[1]), int(med_avg[1] - 2.5*minus_avg[1]), int(med_avg[2] - 2.5*minus_avg[2] ) ])\n #print(upper, lower)\n \n\n avg_vals = lp_filter_array(\n [clamp(avg_hist(hist_hue, 180)[0], 82, 98), \n clamp(avg_hist(hist_sat, 256)[0] , 60, 95),\n clamp(avg_hist(hist_val, 256)[0], 150, 230)],\n avg_vals)\n avg_stds = lp_filter_array(\n [max(std_dev_hist(hist_hue, 180)[0], 5),\n max(std_dev_hist(hist_sat, 256)[0], 10),\n max(std_dev_hist(hist_val, 256)[0], 15)],\n avg_stds)\n upper = np.array([int(avg_vals[x] + 2.5*avg_stds[x]) for x in range(3)])\n lower = np.array([int(avg_vals[x] - 2.5*avg_stds[x]) for x in range(3)])\n print (avg_vals, avg_stds)\n \n hue_l.append(avg_vals[0])\n sat_l.append(avg_vals[1])\n vals_l.append(avg_vals[2])\n \n #clf()\n #plot(hist_hue, color='r')\n #plot(hist_sat, color='g')\n #plot(hist_val, color='b')\n #show(block=False)\n \n for p in range(len(hull)):\n p1 = (hull[p-1][0][0],hull[p-1][0][1])\n p2 = (hull[p][0][0], hull[p][0][1])\n cv2.line(frame, p1, p2, (255,0,0), 2)\n\n cv2.putText(frame, 'X:{0:.2f}'.format(goalx), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n cv2.putText(frame, 'Y:{0:.2f}'.format(goaly), (10,35), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2, cv2.LINE_AA)\n cv2.imshow('frame', frame)\n output.write(frame)\n\n currtime = time.time()\n fps = 0.9 * fps + 0.1 * (1 / (currtime - oldtime))\n #print \"Framerate: {0}\".format(fps)\n oldtime = currtime\n\n if cv2.waitKey(5) & 0xFF == ord('q'):\n break\n\nfigure()\nhist(np.asarray(hue_l))\nfigure()\nhist(np.asarray(sat_l))\nfigure()\nhist(np.asarray(vals_l))\nshow();\n\n# reasonable values for average hue, sat and vals are\n# 77-101 max at 93 limit 82-98\n# 62-105 max at 72 limit 60-95\n# 150-230 max at 190 limit 150-230\n# Start was [80,60,180]\n\ncap.release()\noutput.release()\ncv2.destroyAllWindows()\n", "sub_path": "2017 Pipeline/tower4uu.py", "file_name": "tower4uu.py", "file_ext": "py", "file_size_in_byte": 8528, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "matplotlib.pyplot.hist", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 16, "usage_type": "argument"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 21, "usage_type": "name"}, {"api_name": "cv2.VideoCapture", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.VideoWriter", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.CAP_PROP_FOURCC", "line_number": 35, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FPS", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_WIDTH", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FRAME_HEIGHT", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FOURCC", "line_number": 38, "usage_type": "attribute"}, {"api_name": "cv2.CAP_PROP_FPS", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.__version__", "line_number": 40, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 42, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 49, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 50, "usage_type": "call"}, {"api_name": "cv2.pyrDown", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.blur", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 64, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 64, "usage_type": "attribute"}, {"api_name": "cv2.inRange", "line_number": 68, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 71, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 72, "usage_type": "call"}, {"api_name": "cv2.findContours", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.RETR_LIST", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cv2.CHAIN_APPROX_SIMPLE", "line_number": 74, "usage_type": "attribute"}, {"api_name": "cv2.moments", "line_number": 80, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 83, "usage_type": "call"}, {"api_name": "cv2.arcLength", "line_number": 84, "usage_type": "call"}, {"api_name": "cv2.convexHull", "line_number": 89, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 90, "usage_type": "call"}, {"api_name": "cv2.minAreaRect", "line_number": 91, "usage_type": "call"}, {"api_name": "cv2.boxPoints", "line_number": 92, "usage_type": "call"}, {"api_name": "numpy.int0", "line_number": 93, "usage_type": "call"}, {"api_name": "cv2.contourArea", "line_number": 94, "usage_type": "call"}, {"api_name": "cv2.boxPoints", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.int0", "line_number": 101, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 102, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 102, "usage_type": "attribute"}, {"api_name": "cv2.drawContours", "line_number": 103, "usage_type": "call"}, {"api_name": "cv2.bitwise_not", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.uint8", "line_number": 106, "usage_type": "attribute"}, {"api_name": "cv2.drawContours", "line_number": 107, "usage_type": "call"}, {"api_name": "cv2.bitwise_and", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.bitwise_xor", "line_number": 112, "usage_type": "call"}, {"api_name": "cv2.drawContours", "line_number": 117, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 118, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 118, "usage_type": "attribute"}, {"api_name": "cv2.calcHist", "line_number": 119, "usage_type": "call"}, {"api_name": "cv2.calcHist", "line_number": 120, "usage_type": "call"}, {"api_name": "cv2.calcHist", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 124, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 126, "usage_type": "call"}, {"api_name": "numpy.cumsum", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 174, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 175, "usage_type": "call"}, {"api_name": "cv2.line", "line_number": 191, "usage_type": "call"}, {"api_name": "cv2.putText", "line_number": 193, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 193, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 193, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 194, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_SIMPLEX", "line_number": 194, "usage_type": "attribute"}, {"api_name": "cv2.LINE_AA", "line_number": 194, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 195, "usage_type": "call"}, {"api_name": "time.time", "line_number": 198, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 203, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 206, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 207, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 207, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 208, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 209, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 209, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 210, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 211, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 212, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 222, "usage_type": "call"}]}
+{"seq_id": "430303935", "text": "'''\nCreated on Jul 9, 2012\n\n@author: iuri\n'''\nimport sys\n\nfrom twisted.internet.defer import inlineCallbacks, returnValue\nfrom twisted.internet import reactor\nfrom twisted.internet.endpoints import TCP4ClientEndpoint\n\nfrom txthoonk.client import ThoonkPubFactory, ThoonkSubFactory\nfrom twisted.python import log\n\nREDIS_HOST, REDIS_PORT = (\"localhost\", 6379)\n\n\n@inlineCallbacks\ndef getThoonkSubscriber():\n endpoint = TCP4ClientEndpoint(reactor, REDIS_HOST, REDIS_PORT)\n sub = yield endpoint.connect(ThoonkSubFactory())\n returnValue(sub)\n\n@inlineCallbacks\ndef getThoonkPublisher(db=15):\n endpoint = TCP4ClientEndpoint(reactor, REDIS_HOST, REDIS_PORT)\n pub = yield endpoint.connect(ThoonkPubFactory(db=db))\n returnValue(pub)\n\n\ndef newfeed(*args):\n log.msg(\"newfeed: %r\" % [args])\n\ndef delfeed(*args):\n log.msg(\"delfeed: %r\" % [args])\n\ndef publish(*args):\n log.msg(\"publish: %r\" % [args])\n\ndef retract(*args):\n log.msg(\"retract: %r\" % [args])\n\ndef edit(*args):\n log.msg(\"edit: %r\" % [args])\n\n@inlineCallbacks\ndef runTest01():\n pub = yield getThoonkPublisher()\n sub = yield getThoonkSubscriber()\n\n feed_name = \"test\"\n #flush redis\n yield pub.redis.flushdb()\n\n # setup handlers\n id_ = yield sub.register_handler(\"newfeed\", newfeed)\n log.msg(\"handler for newfeed id: %r\" % id_)\n\n id_ = yield sub.register_handler(\"delfeed\", delfeed)\n log.msg(\"handler for delfeed id: %r\" % id_)\n\n\n feed = yield pub.feed(feed_name)\n for chan, handler in zip([feed.channel_publish,\n feed.channel_edit,\n feed.channel_retract],\n [publish,\n edit,\n retract]):\n id_ = yield sub.register_handler(chan, handler)\n log.msg(\"handler for %r id: %r\" % (chan, id_))\n\n # publish without id \n new_item_id = yield feed.publish(\"new item\")\n\n # publish with id\n another_item_id = \"someid\"\n yield feed.publish(\"another item\", another_item_id)\n\n # publish with same id\n yield feed.publish(\"replace item\", another_item_id)\n\n # retract ids\n yield feed.retract(new_item_id)\n yield feed.retract(another_item_id)\n\n yield pub.delete_feed(feed_name)\n\n\n@inlineCallbacks\ndef runTest02():\n pub = yield getThoonkPublisher(12)\n #sub = yield getThoonkSubscriber()\n\n feed_name = \"test2\"\n yield pub.redis.flushdb()\n\n feed = yield pub.feed(feed_name)\n\n # set config\n yield feed.set_config({\"max_length\": 1})\n\n @inlineCallbacks\n def publish(array):\n for a in array:\n log.msg(\"publishing: %r\" % a)\n yield feed.publish(a)\n log.msg(\"published: %r\" % a)\n\n @inlineCallbacks\n def get_items():\n ids = yield feed.get_ids()\n for id_ in ids:\n item = yield feed.get_id(id_)\n log.msg(\"got item: %r\" % item)\n\n import string\n reactor.callLater(0, publish, string.ascii_lowercase)\n reactor.callLater(0, publish, string.ascii_uppercase)\n reactor.callLater(0.5, get_items)\n\ndef main(*args):\n log.startLogging(sys.stdout)\n reactor.callLater(0, runTest01) #@UndefinedVariable\n reactor.callLater(0.5, runTest02) #@UndefinedVariable\n reactor.callLater(1.5, reactor.stop) #@UndefinedVariable\n\n reactor.run() #@UndefinedVariable\n\nif __name__ == '__main__':\n main(sys.argv)\n", "sub_path": "examples/feedpubsub.py", "file_name": "feedpubsub.py", "file_ext": "py", "file_size_in_byte": 3387, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "twisted.internet.endpoints.TCP4ClientEndpoint", "line_number": 20, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 20, "usage_type": "argument"}, {"api_name": "txthoonk.client.ThoonkSubFactory", "line_number": 21, "usage_type": "call"}, {"api_name": "twisted.internet.defer.returnValue", "line_number": 22, "usage_type": "call"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 18, "usage_type": "name"}, {"api_name": "twisted.internet.endpoints.TCP4ClientEndpoint", "line_number": 26, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 26, "usage_type": "argument"}, {"api_name": "txthoonk.client.ThoonkPubFactory", "line_number": 27, "usage_type": "call"}, {"api_name": "twisted.internet.defer.returnValue", "line_number": 28, "usage_type": "call"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 24, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 32, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 32, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 35, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 35, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 38, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 38, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 41, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 41, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 44, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 44, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 57, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 57, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 60, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 60, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 71, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 71, "usage_type": "name"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 46, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 106, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 106, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 108, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 108, "usage_type": "name"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 103, "usage_type": "name"}, {"api_name": "twisted.python.log.msg", "line_number": 115, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 115, "usage_type": "name"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 110, "usage_type": "name"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 118, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 118, "usage_type": "name"}, {"api_name": "string.ascii_lowercase", "line_number": 118, "usage_type": "attribute"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 119, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 119, "usage_type": "name"}, {"api_name": "string.ascii_uppercase", "line_number": 119, "usage_type": "attribute"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 120, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 120, "usage_type": "name"}, {"api_name": "twisted.internet.defer.inlineCallbacks", "line_number": 90, "usage_type": "name"}, {"api_name": "twisted.python.log.startLogging", "line_number": 123, "usage_type": "call"}, {"api_name": "twisted.python.log", "line_number": 123, "usage_type": "name"}, {"api_name": "sys.stdout", "line_number": 123, "usage_type": "attribute"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 124, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 124, "usage_type": "name"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 125, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 125, "usage_type": "name"}, {"api_name": "twisted.internet.reactor.callLater", "line_number": 126, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 126, "usage_type": "name"}, {"api_name": "twisted.internet.reactor.stop", "line_number": 126, "usage_type": "attribute"}, {"api_name": "twisted.internet.reactor.run", "line_number": 128, "usage_type": "call"}, {"api_name": "twisted.internet.reactor", "line_number": 128, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 131, "usage_type": "attribute"}]}
+{"seq_id": "149495279", "text": "import graphene\nimport pdb\n\nfrom profiles.models.Profile import Profile\nfrom profiles.schema import ProfileNode\nfrom organization.models.Organization import Organization\nfrom user.schema import get_user\n\n\nclass CreateProfile(graphene.relay.ClientIDMutation):\n profile = graphene.Field(ProfileNode)\n\n class Input:\n organizations = graphene.List(graphene.Int)\n biography = graphene.String()\n\n def mutate_and_get_payload(self, info, **input):\n # get user here\n user = get_user(info) or None\n\n if not user:\n raise Exception(\"User does not exist.\")\n\n profile = Profile(\n user=user,\n biography=input.get(\"biography\")\n )\n\n profile.save()\n\n for id in input.get(\"organizations\"):\n print(\"orgid %s\" % id)\n organization = Organization.objects.filter(id=id).first()\n profile.organizations.add(organization)\n\n profile.save()\n\n return CreateProfile(profile=profile)\n", "sub_path": "services/cms/profiles/schema/CreateProfile.py", "file_name": "CreateProfile.py", "file_ext": "py", "file_size_in_byte": 1004, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "graphene.relay", "line_number": 10, "usage_type": "attribute"}, {"api_name": "graphene.Field", "line_number": 11, "usage_type": "call"}, {"api_name": "profiles.schema.ProfileNode", "line_number": 11, "usage_type": "argument"}, {"api_name": "graphene.List", "line_number": 14, "usage_type": "call"}, {"api_name": "graphene.Int", "line_number": 14, "usage_type": "attribute"}, {"api_name": "graphene.String", "line_number": 15, "usage_type": "call"}, {"api_name": "user.schema", "line_number": 19, "usage_type": "name"}, {"api_name": "user.schema.get_user", "line_number": 19, "usage_type": "call"}, {"api_name": "user.schema", "line_number": 21, "usage_type": "name"}, {"api_name": "profiles.models.Profile.Profile", "line_number": 24, "usage_type": "call"}, {"api_name": "user.schema", "line_number": 25, "usage_type": "name"}, {"api_name": "organization.models.Organization", "line_number": 33, "usage_type": "name"}, {"api_name": "organization.models.Organization.Organization.objects.filter", "line_number": 33, "usage_type": "call"}, {"api_name": "organization.models.Organization.Organization.objects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "organization.models.Organization.Organization", "line_number": 33, "usage_type": "name"}, {"api_name": "organization.models.Organization", "line_number": 34, "usage_type": "argument"}]}
+{"seq_id": "396195735", "text": "\"\"\"\r\nCRYPTO CSV PRE-PROCESSING:\r\n\t-> READ DATA TO ARRAYS\r\n\t-> CHECK DATA TYPES\r\n\t-> SET TO 2 DECIMAL PLACES\r\n\t-> PLOT SINGLE CHART\r\n\t-> PLOTTING VALUES\r\n\t-> WRITE LISTS BACK INTO CSV \r\n\"\"\"\r\n\r\nimport csv, time, sys\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\nimport datetime as dt\r\n\r\n\r\nfile1 = \"crypto/BTC.csv\"\r\n\r\nDATE2 = []\r\n\r\n\r\n#########################\r\n## READ DATA TO ARRAYS ##\r\n#########################\r\n#column_names = [\"DATE\", \"BTC_OPEN\", \"ETH_OPEN\"]\r\ndf = pd.read_csv(file1)#, names=column_names)\r\n#print(df)\r\n\r\nDATE = df.DATE.to_list()\r\nBTC_OPEN = df.BTC_OPEN.to_list()\r\nETH_OPEN = df.ETH_OPEN.to_list()\r\n\r\n## Remove time from String ##\r\nfor i in DATE:\r\n\tDATE2.append(i.split(' ')[0])\r\nDATE = DATE2\r\n\r\n\r\n\"\"\"\r\n######################\r\n## CHECK DATA TYPES ##\r\n######################\r\nprint(type(DATE[12]))\t\t\t\t\t# check random value type\r\nprint(type(BTC_OPEN[12]))\t\t\t\t# check type is now float (2 decimal)\r\nprint(type(ETH_OPEN[12]))\t\t\t\t# check type is now float (2 decimal)\r\n\r\n## CONVERT ARRAY TO FLOAT - UNECESSARY ##\r\n#list(np.float_(BTC_OPEN))\r\n#list(np.float_(ETH_OPEN))\r\n\"\"\"\r\n\r\n#############################\r\n## SET TO 2 DECIMAL PLACES ##\r\n#############################\r\nBTC_OPEN = list(np.around(np.array(BTC_OPEN),2))\r\nETH_OPEN = list(np.around(np.array(ETH_OPEN),2))\r\n\r\n\r\n\"\"\"\r\n#######################\r\n## PLOT SINGLE CHART ##\r\n#######################\r\nx = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in DATE]\r\ny = range(len(x))\r\ny = BTC_OPEN\r\n\r\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\r\nplt.gca().xaxis.set_major_locator(mdates.DayLocator())\r\nplt.plot(x,y)\r\nplt.gcf().autofmt_xdate()\r\n\"\"\"\r\n\r\n#\"\"\"\r\n#####################\r\n## PLOTTING VALUES ##\r\n#####################\r\n#t = np.arange(0.01, 48.0, 0.01) \t\t# Set the range to number of rows?\r\nx = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in DATE]\t# X-Axis\r\ndata1 = BTC_OPEN\t\t\t\t\t\t\t\t\t\t\t\t# 1st Y-Axis \r\ndata2 = ETH_OPEN\t\t\t\t\t\t\t\t\t\t\t\t# 2nd Y-Axis \r\n\r\n\r\nfig, ax1 = plt.subplots()\r\n\r\ncolor = 'tab:red'\r\nax1.set_xlabel('time')\r\nax1.set_ylabel('BTC_OPEN', color=color)\r\nax1.plot(x, data1, color=color)\r\nax1.tick_params(axis='y', labelcolor=color)\r\n\r\nax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\r\n\r\ncolor = 'tab:blue'\r\nax2.set_ylabel('ETH_OPEN', color=color)\r\nax2.plot(x, data2, color=color)\r\nax2.tick_params(axis='y', labelcolor=color)\r\n\r\nfig.tight_layout() \t\t# otherwise the right y-label is slightly clipped\r\n\r\nprint(\"Show Plot\")\r\nplt.show()\r\n#\"\"\"\r\n\r\n###############################\r\n## WRITE LISTS BACK INTO CSV ##\r\n###############################\r\ndf = pd.read_csv(file1) ## 1.csv is the csv file I want to import. \r\n\r\n#a = [0.001, 5, 38, 70, 101, 140, 190]\r\n#b = [35, 65, 100, 160, 170, 200]\r\n\r\ndf['DATE'] \t\t= DATE\r\ndf['BTC_OPEN'] \t= BTC_OPEN\r\ndf['ETH_OPEN'] \t= ETH_OPEN\r\n\r\ndf.to_csv(file1)\r\n\r\n\r\nprint(\"Executed Successfully...\")\r\nsys.exit(0)\t", "sub_path": "files/csv/csv2.py", "file_name": "csv2.py", "file_ext": "py", "file_size_in_byte": 2938, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.read_csv", "line_number": 29, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 58, "usage_type": "call"}, {"api_name": "numpy.around", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 59, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 81, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 81, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 86, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 86, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 104, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 104, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 110, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 123, "usage_type": "call"}]}
+{"seq_id": "650983141", "text": "import time\nfrom collections import OrderedDict\nfrom Options.TrainOptions import TrainOptions\nfrom torch.autograd import Variable\nimport torch.utils.data as data\nfrom utils import *\nimport torch\nimport CNN\nfrom Model_Configue import *\nimport FMCC_Dataset\nimport torch.nn as nn\nopt =TrainOptions().parse()\nif opt.Model == 'CNN_KWS_Model':\n configue = CNN_Model\n model = CNN.CNN_KWS_Model(configue)\nif len(opt.gpu_ids) > 0:\n model.cuda()\n GPU_Mode =1\nelse :\n GPU_Mode = 0\noptimizer = torch.optim.SGD(model.parameters(),lr=opt.lr,momentum=0.9)\n\ntrain_set = FMCC_Dataset.FMCC_Dataset(opt.train_label_path,opt.train_data_path,opt.word_path,opt.lexicon_path)\ntrain_loader = data.DataLoader(train_set,batch_size= opt.batchsize,shuffle=True)\n\ncriterion = nn.CrossEntropyLoss()\nmax_acc = 0\nfor epoch_idx in range(opt.epoch):\n print('Epoch {}/{}'.format(epoch_idx,opt.epoch-1))\n print('--'*10)\n since = time.time()\n model.train()\n if opt.Decay_Style == 'exp':\n optimizer = exp_lr_scheduler(optimizer=optimizer,epoch=epoch_idx,init_lr=opt.lr,lr_dacay_epoch=opt.epoch_decay,Decay_Weight=opt.Decay_Weight)\n elif opt.Decay_Style == 'linear':\n optimizer = linear_lr_scheduler(optimizer=optimizer,epoch=epoch_idx,init_lr=opt.lr,lr_dacay_epoch=opt.epoch_decay,max_epoch=opt.epoch)\n running_loss = 0.0\n running_corrects = 0\n counter = 0\n for data in train_loader:\n input = data['data']\n label = data['label']\n if GPU_Mode:\n input,label = Variable(input.float().cuda()),Variable(label.long().cuda())\n else:\n input,label = Variable(input),Variable(label.long())\n optimizer.zero_grad()\n out = model(input)\n loss = criterion(out,label)\n loss.backward()\n optimizer.step()\n running_loss +=loss.item()\n _,predicts = torch.max(out.data,1)\n\n running_corrects+= torch.sum(predicts==label.data)\n if counter %5000 ==0:\n print('Reached iteration',counter)\n counter +=1\n epoch_loss =running_loss/len(train_set)\n epoch_acc = (1.0*running_corrects.item())/len(train_set)\n print('{} Loss: {:.4f} Acc: {:.4f}'.format(opt.phase,epoch_loss,epoch_acc))\n\n time_elapsed = time.time()-since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed//60,time_elapsed%60))\n\n if epoch_idx % opt.Save_Fre==0:\n save_name = opt.name+'__model'+str(epoch_idx)+'.pt'\n save_name = os.path.join(opt.checkpoints_dir, opt.name,save_name)\n torch.save(model.state_dict(),save_name)\n\n\n\n", "sub_path": "train.py", "file_name": "train.py", "file_ext": "py", "file_size_in_byte": 2565, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "Options.TrainOptions.TrainOptions", "line_number": 12, "usage_type": "call"}, {"api_name": "CNN.CNN_KWS_Model", "line_number": 15, "usage_type": "call"}, {"api_name": "torch.optim.SGD", "line_number": 21, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 21, "usage_type": "attribute"}, {"api_name": "FMCC_Dataset.FMCC_Dataset", "line_number": 23, "usage_type": "call"}, {"api_name": "torch.utils.data.DataLoader", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 24, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 26, "usage_type": "name"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.utils.data", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.utils.data", "line_number": 41, "usage_type": "name"}, {"api_name": "torch.utils.data", "line_number": 42, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 44, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 55, "usage_type": "call"}, {"api_name": "time.time", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 69, "usage_type": "call"}]}
+{"seq_id": "609268334", "text": "import time\nfrom typing import Iterator\n\nimport openai\n\nfrom gptcache.adapter.adapter import adapt\nfrom gptcache.utils.response import get_message_from_openai_answer, get_stream_message_from_openai_answer\n\n\nclass ChatCompletion:\n \"\"\"Openai ChatCompletion Wrapper\"\"\"\n\n @classmethod\n def create(cls, *args, **kwargs):\n def llm_handler(*llm_args, **llm_kwargs):\n return openai.ChatCompletion.create(*llm_args, **llm_kwargs)\n\n def cache_data_convert(cache_data):\n if kwargs.get(\"stream\", False):\n return construct_stream_resp_from_cache(cache_data)\n return construct_resp_from_cache(cache_data)\n\n def update_cache_callback(llm_data, update_cache_func):\n if not isinstance(llm_data, Iterator):\n update_cache_func(get_message_from_openai_answer(llm_data))\n return llm_data\n else:\n\n def hook_openai_data(it):\n total_answer = \"\"\n for item in it:\n total_answer += get_stream_message_from_openai_answer(item)\n yield item\n update_cache_func(total_answer)\n\n return hook_openai_data(llm_data)\n\n return adapt(\n llm_handler, cache_data_convert, update_cache_callback, *args, **kwargs\n )\n\n\ndef construct_resp_from_cache(return_message):\n return {\n \"gptcache\": True,\n \"choices\": [\n {\n \"message\": {\"role\": \"assistant\", \"content\": return_message},\n \"finish_reason\": \"stop\",\n \"index\": 0,\n }\n ],\n \"created\": int(time.time()),\n \"usage\": {\"completion_tokens\": 0, \"prompt_tokens\": 0, \"total_tokens\": 0},\n \"object\": \"chat.completion\",\n }\n\n\ndef construct_stream_resp_from_cache(return_message):\n created = int(time.time())\n return [\n {\n \"choices\": [\n {\"delta\": {\"role\": \"assistant\"}, \"finish_reason\": None, \"index\": 0}\n ],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n {\n \"choices\": [\n {\n \"delta\": {\"content\": return_message},\n \"finish_reason\": None,\n \"index\": 0,\n }\n ],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n {\n \"gptcache\": True,\n \"choices\": [{\"delta\": {}, \"finish_reason\": \"stop\", \"index\": 0}],\n \"created\": created,\n \"object\": \"chat.completion.chunk\",\n },\n ]\n", "sub_path": "openai/venv/lib/python3.10/site-packages/gptcache/adapter/openai.py", "file_name": "openai.py", "file_ext": "py", "file_size_in_byte": 2662, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "openai.ChatCompletion.create", "line_number": 16, "usage_type": "call"}, {"api_name": "openai.ChatCompletion", "line_number": 16, "usage_type": "attribute"}, {"api_name": "typing.Iterator", "line_number": 24, "usage_type": "argument"}, {"api_name": "gptcache.utils.response.get_message_from_openai_answer", "line_number": 25, "usage_type": "call"}, {"api_name": "gptcache.utils.response.get_stream_message_from_openai_answer", "line_number": 32, "usage_type": "call"}, {"api_name": "gptcache.adapter.adapter.adapt", "line_number": 38, "usage_type": "call"}, {"api_name": "time.time", "line_number": 53, "usage_type": "call"}, {"api_name": "time.time", "line_number": 60, "usage_type": "call"}]}
+{"seq_id": "494204490", "text": "# -*- coding: utf-8 -*-\nfrom django.shortcuts import render_to_response, redirect\nfrom django.contrib import auth\nfrom django.core.context_processors import csrf\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.db import connection\n\nfrom TestingApp.forms import ErrorForm, DateForm\n\nimport datetime\n\n\ndef remarks(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/remarks/',\n 'button': 'Показати'\n }\n args.update(csrf(request))\n finish = datetime.datetime.now().date()\n start = finish - datetime.timedelta(days=30)\n if request.POST:\n date_form = DateForm(request.POST)\n if date_form.is_valid():\n start = date_form.cleaned_data['start']\n finish = date_form.cleaned_data['finish']\n else:\n date_form = DateForm()\n query = \"\"\"\n SELECT remark.idRemark, remark.Title, remark.CreationDate, remark.CorrectionDate,\n remark.Description, programmer.AllName, tester.AllName, version.Title, remark.IsError FROM testing.remark\n LEFT JOIN testing.programmer ON remark.ProgrammerId = programmer.id\n LEFT JOIN testing.tester ON remark.TesterId = tester.id\n LEFT JOIN testing.version ON remark.VersionId = version.idVersion\n WHERE remark.CustomerId = %s AND remark.CreationDate >= '%s' AND remark.CreationDate <= '%s'\n ORDER BY remark.idRemark\"\"\" % (\n menu.person_id,\n start,\n finish\n )\n cursor = connection.cursor()\n cursor.execute(query)\n records = cursor.fetchall()\n records = [[col for col in record] for record in records]\n for record in records:\n last_col = record[len(record) - 1]\n if last_col:\n record[len(record) - 1] = 'Помилка'\n else:\n record[len(record) - 1] = 'Доробка'\n args['records'] = records\n args['date_form'] = date_form\n return render_to_response(\n 'remarks.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\ndef error(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 1)\n customer = menu.person_id if request.user.groups.all()[0].name == 'customer' else 'NULL'\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/error/',\n 'button': 'Створити'\n }\n args.update(csrf(request))\n if request.POST:\n error_form = ErrorForm(request.POST)\n if error_form.is_valid():\n cursor = connection.cursor()\n query = \"\"\"\n INSERT INTO `testing`.`remark` (`Title`, `CreationDate`, `Description`, `CustomerId`, `IsError`)\n VALUES (\"%s\", '%s', \"%s\", %s, %s)\"\"\" % (\n error_form.cleaned_data['title'],\n datetime.datetime.now().date(),\n error_form.cleaned_data['description'],\n customer,\n error_form.cleaned_data['choice']\n )\n cursor.execute(query)\n return redirect('/')\n else:\n error_form = ErrorForm()\n args['error_form'] = error_form\n return render_to_response(\n 'error.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\ndef delete_remark(request, del_id):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n cursor = connection.cursor()\n cursor.execute(\"\"\"SELECT TesterId FROM remark WHERE idRemark=%s\"\"\" % del_id)\n record = cursor.fetchall()\n if record[0][0]:\n menu = check_user(request, 1)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'message': 'Видалення заборонене, тому що зауваження опрацьовується тестувальником.'\n }\n return render_to_response(\n 'denied.html',\n args\n )\n query = \"\"\"DELETE FROM `testing`.`remark` WHERE `idRemark`=%s\"\"\" % del_id\n cursor.execute(query)\n return redirect('/')\n\n\ndef escape(s):\n return s.replace(\"'\", r\"\\'\")\n\n\ndef change_remark(request, change_id):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group,\n 'action': '/change-remark/%s/' % change_id,\n 'button': 'Змінити'\n }\n args.update(csrf(request))\n if request.POST:\n error_form = ErrorForm(request.POST)\n if error_form.is_valid():\n cursor = connection.cursor()\n query = \"\"\"\n UPDATE `testing`.`remark`\n SET `Title`=\"%s\", `Description`='%s', `CreationDate`='%s', `IsError`=%s\n WHERE `idRemark`=%s\"\"\" % (\n error_form.cleaned_data['title'],\n escape(error_form.cleaned_data['description']),\n datetime.datetime.now().date(),\n error_form.cleaned_data['choice'],\n change_id\n )\n cursor.execute(query)\n return redirect('/')\n else:\n cursor = connection.cursor()\n query = \"\"\"\n SELECT remark.Title, remark.Description, remark.IsError\n FROM `testing`.`remark` WHERE `idRemark`=%s\"\"\" % change_id\n cursor.execute(query)\n remark = cursor.fetchall()\n title, description, is_error = remark[0]\n initial = {\n 'title': title,\n 'description': description,\n 'choice': is_error\n }\n error_form = ErrorForm(initial=initial)\n args['error_form'] = error_form\n return render_to_response(\n 'error.html',\n args,\n context_instance=RequestContext(request)\n )\n\n\nclass Item:\n def __init__(self, name, link):\n self.name = name\n self.link = link\n self.current = False\n\n\nclass Menu:\n def __init__(self, lst, group, page, person_id):\n self.list = lst\n self.group = group\n self.page = page\n self.person_id = person_id\n\n\ndef check_user(request, current):\n user = request.user\n lst = []\n if user.customer:\n lst.append(Item('Мої зауваження', 'remarks'))\n lst.append(Item('Створити зауваження', 'error'))\n text = 'клієнта'\n page = 'remarks/'\n person_id = user.customer.id\n elif user.cto:\n lst.append(Item('Зауваження', 'cto-remarks'))\n lst.append(Item('Версії', 'versions'))\n lst.append(Item('Створити нову версію', 'add-version'))\n lst.append(Item('Навантаження на тестувальників', 'tester-load'))\n text = 'технічного директора'\n page = 'cto-remarks/'\n person_id = user.cto.id\n elif user.tester:\n lst.append(Item('Мої зауваження', 'tester'))\n lst.append(Item('Створити зауваження', 'error'))\n lst.append(Item('Навантаження на програмістів', 'programmer-load'))\n text = 'тестувальника'\n page = 'tester/'\n person_id = user.tester.id\n else:\n lst.append(Item('Мої зауваження', 'programmer'))\n text = 'програміста'\n page = 'programmer/'\n person_id = user.programmer.id\n lst.append(Item('Статистика версій', 'version-stat'))\n lst[current].current = True\n return Menu(lst, text, page, person_id)\n\n\ndef index(request):\n if request.user == AnonymousUser():\n return redirect('/auth/login/')\n menu = check_user(request, 0)\n return redirect(menu.page)\n\n\ndef version_stat(request):\n if request.user == AnonymousUser():\n return redirect('/')\n menu = check_user(request, 0)\n menu = check_user(request, len(menu.list) - 1)\n args = {\n 'items': menu.list,\n 'username': auth.get_user(request).username,\n 'group': menu.group\n }\n args.update(csrf(request))\n finish = datetime.datetime.now().date()\n start = finish - datetime.timedelta(days=30)\n if request.POST:\n date_form = DateForm(request.POST)\n if date_form.is_valid():\n start = date_form.cleaned_data['start']\n finish = date_form.cleaned_data['finish']\n else:\n date_form = DateForm()\n cursor = connection.cursor()\n query = \"\"\"SELECT version.idVersion, version.Title, t4.test_count, t2.prog_count\n FROM\n (SELECT t1.idVersion, COUNT(t1.ProgrammerId) AS prog_count\n FROM\n (SELECT idVersion, ProgrammerId\n FROM testing.version\n LEFT JOIN testing.remark ON version.idVersion = remark.VersionId\n GROUP BY version.idVersion, remark.ProgrammerId) AS t1\n GROUP BY t1.idVersion) AS t2\n JOIN\n (SELECT t3.idVersion, COUNT(t3.TesterId) AS test_count\n FROM\n (SELECT idVersion, TesterId\n FROM testing.version\n LEFT JOIN testing.remark ON version.idVersion = remark.VersionId\n GROUP BY version.idVersion, remark.TesterId) AS t3\n GROUP BY t3.idVersion) AS t4\n ON t2.idVersion = t4.idVersion\n JOIN testing.version ON t2.idVersion = version.idVersion\n WHERE version.ReleaseDate >= '%s' AND version.ReleaseDate <= '%s'\"\"\" % (\n start,\n finish\n )\n cursor.execute(query)\n records = cursor.fetchall()\n args['records'] = records\n args['button'] = 'Показати'\n args['date_form'] = date_form\n args['head'] = ['№', 'Назва версії', 'Тестувальники', 'Програмісти']\n args['title'] = 'Кількість працівників, які створювали версію'\n return render_to_response(\n 'loading.html',\n args,\n context_instance=RequestContext(request)\n )\n", "sub_path": "TestingApp/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 10410, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 15, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 16, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user", "line_number": 20, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 20, "usage_type": "name"}, {"api_name": "django.core.context_processors.csrf", "line_number": 25, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 26, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 26, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 27, "usage_type": "call"}, {"api_name": "TestingApp.forms.DateForm", "line_number": 29, "usage_type": "call"}, {"api_name": "TestingApp.forms.DateForm", "line_number": 34, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 47, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 47, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 59, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 62, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 67, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 68, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user", "line_number": 73, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 73, "usage_type": "name"}, {"api_name": "django.core.context_processors.csrf", "line_number": 78, "usage_type": "call"}, {"api_name": "TestingApp.forms.ErrorForm", "line_number": 80, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 82, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 82, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 87, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 87, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 93, "usage_type": "call"}, {"api_name": "TestingApp.forms.ErrorForm", "line_number": 95, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 97, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 100, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 105, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 106, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 107, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 107, "usage_type": "name"}, {"api_name": "django.contrib.auth.get_user", "line_number": 114, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 114, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 118, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 124, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 132, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 133, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user", "line_number": 137, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 137, "usage_type": "name"}, {"api_name": "django.core.context_processors.csrf", "line_number": 142, "usage_type": "call"}, {"api_name": "TestingApp.forms.ErrorForm", "line_number": 144, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 146, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 146, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 153, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 153, "usage_type": "attribute"}, {"api_name": "django.shortcuts.redirect", "line_number": 158, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 160, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 160, "usage_type": "name"}, {"api_name": "TestingApp.forms.ErrorForm", "line_number": 172, "usage_type": "call"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 174, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 177, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 231, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 232, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 234, "usage_type": "call"}, {"api_name": "django.contrib.auth.models.AnonymousUser", "line_number": 238, "usage_type": "call"}, {"api_name": "django.shortcuts.redirect", "line_number": 239, "usage_type": "call"}, {"api_name": "django.contrib.auth.get_user", "line_number": 244, "usage_type": "call"}, {"api_name": "django.contrib.auth", "line_number": 244, "usage_type": "name"}, {"api_name": "django.core.context_processors.csrf", "line_number": 247, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 248, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 248, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 249, "usage_type": "call"}, {"api_name": "TestingApp.forms.DateForm", "line_number": 251, "usage_type": "call"}, {"api_name": "TestingApp.forms.DateForm", "line_number": 256, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 257, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 257, "usage_type": "name"}, {"api_name": "django.shortcuts.render_to_response", "line_number": 288, "usage_type": "call"}, {"api_name": "django.template.RequestContext", "line_number": 291, "usage_type": "call"}]}
+{"seq_id": "203082897", "text": "import base64\nimport datetime\nimport json\nfrom django.contrib.auth import get_user_model\nfrom django.db import connection\nfrom django.utils import timezone\nfrom validators.uuid import uuid\n\nfrom apps.controlled_substance.models import Stock, StockAssignment, USED, OUT\nfrom apps.controlled_substance.utils import add_log, mark_stock_entry_used, \\\n unmark_used_stock_entry\nfrom apps.custom_user.utils import validate_email\nfrom apps.incidents.models import Incident\nfrom apps.incidents.models import IncidentNotes, StatusHistory\nfrom apps.incidents.models import IncidentStatus\nfrom apps.incidents.models import IncidentTemplate\nfrom helper_functions import replace_null, create_client\n\nPATIENT_FIELD = ['email', 'phone', 'dob', 'sex', 'name', 'address', 'suburb', 'state', 'country', 'postcode']\n\nspecial_validation_case = {\n \"field_52ca456962ba8\": {\n \"repeating\": False,\n \"special\": True,\n \"fields\": {\n \"lat\": {\n \"Type\": 'number',\n \"Required\": True,\n \"Values\": ''\n },\n \"long\": {\n \"Type\": 'number',\n \"Required\": True,\n \"Values\": ''\n },\n \"accuracy\": {\n \"Type\": 'number',\n \"Required\": True,\n \"Values\": ''\n }\n }\n },\n \"incident_id\": {\n \"Type\": 'UUID',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"incident_pk\": {\n \"Type\": 'number',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"dt_created\": {\n \"Type\": 'date_time_picker',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"incident_status\": {\n \"repeating\": False,\n \"special\": True,\n \"fields\": {\n \"incident_status_id\": {\n \"Type\": 'number',\n \"Required\": False,\n \"Values\": [1, 2, 3, 4, 5, 6, 7, 8, 9]\n }\n }\n },\n \"assigned_to\": {\n \"Type\": 'UUID',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"reporter_name\": {\n \"Type\": 'text',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"reporter_phone\": {\n \"Type\": 'text',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"controlled_substance_stock_assignment_id\": {\n \"Type\": 'UUID',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n },\n \"drug_administered_by\": {\n \"Type\": 'UUID',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n }\n}\n\nNOTES_FIELD_ADDITION = {\n \"note_id\": {\n \"Type\": 'number',\n \"Required\": False,\n \"Values\": '',\n \"repeating\": False\n }\n}\n\nMEDIA_FIELD = ['media_reference', 'media_type']\n\nTEMPORARY_EXCLUDED_FIELDS = ['blood_pressure_diastolic',\n 'blood_pressure_systolic',\n 'dose_administered',\n 'heart_rate',\n 'pain_score',\n 'patient_age',\n 'respiration_rate',\n 'field_52d4798f6d229']\n\nTEMPORARY_SANITIZE_FIELD = ['field_52ca447762ba2', 'incident_role']\n\ndef get_template():\n template = IncidentTemplate.objects.get(pk=1)\n return template.json\n\n\ndef audit_incident(incident, resort, assigned, current_assigned, changed, incident_json):\n cursor = connection.cursor()\n\n cursor.execute(\"\"\"INSERT INTO incidents_incidentaudit (\n incident_id,\n resort_id,\n assigned_to_id,\n prev_assigned_to_id,\n changed_by_id,\n incident_data,\n dt_created\n ) VALUES (\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n now()\n )\n \"\"\", [incident.incident_pk, resort.resort_pk, assigned.user_pk, current_assigned.user_pk, changed.user_pk, json.dumps(incident_json)])\n cursor.close()\n\n return True\n\n\ndef incident_note(incident_json, user, incident):\n notes = incident_json.get('notes', [])\n\n incident_notes = list(IncidentNotes.objects.filter(incident=incident).values_list('note_id', flat=True))\n\n if notes and notes is not None and incident_json:\n for note in notes:\n if note:\n if note.get('note_id') is None:\n try:\n note_date = datetime.datetime.strptime(note.get('field_52ca448dg94ja4'), \"%Y-%m-%d %H:%M:%S\")\n except:\n note_date = datetime.datetime.now()\n\n try:\n user = get_user_model().objects.get(user_id=note.get('field_52ca448dg94ja5'))\n except:\n user = user\n\n new_note = IncidentNotes(incident=incident, note=note.get('field_52ca448dg94ja3'),\n note_date=note_date, user=user)\n new_note.save()\n note['note_id'] = new_note.note_id\n else:\n try:\n incident_notes.remove(note.get('note_id'))\n except:\n pass\n\n note_data = IncidentNotes.objects.get(note_id=note.get('note_id'))\n\n note_data.note = note.get('field_52ca448dg94ja3')\n note_data.note_date = datetime.datetime.strptime(note.get('field_52ca448dg94ja4'),\n \"%Y-%m-%d %H:%M:%S\")\n note_data.save()\n\n IncidentNotes.objects.filter(pk__in=incident_notes).delete()\n\n return notes\n\n\ndef status_history(incident, status, user, date=None):\n if date is None:\n date = timezone.now()\n\n new_status = StatusHistory(incident=incident, status=status, user=user, status_date=date)\n new_status.save()\n\n return new_status\n\n\ndef incident_status_option(selected_status):\n incident_status = IncidentStatus.objects.all()\n options = []\n\n for status in incident_status:\n a = dict()\n if status.order == selected_status:\n a['key'] = status.key\n a['value'] = status.order\n a['color'] = status.color\n options.append(a)\n\n return options\n\n\ndef incident_status_option_for_status_report(selected_status):\n incident_status = IncidentStatus.objects.all()\n\n status_resp = dict()\n for status in incident_status:\n if status.order == selected_status:\n status_resp['status_label'] = status.key\n status_resp['status_id'] = status.order\n\n return status_resp\n\n\ndef get_extra_incident_info(config, incident_json, incident_pk, purpose, data_key):\n data = {}\n\n try:\n injuries_json = config['DashboardItems']['field_52d4798f6d229']['Questions']['field_52d4798f6d227'][\n 'RepeatingQuestions']\n patient_history_json = config['DashboardItems']['field_52ca41790a16c']['Questions']\n treatment_info = config['DashboardItems']['field_52ca42230a171']['Questions']\n\n injury_location_values = injuries_json['injury_location']['Values']\n body_part_values = injuries_json['body_part']['Values']\n injury_type_values = injuries_json['injury_type']['Values']\n activity_values = patient_history_json['field_52ca3dc8ac437']['Values']\n treatments = treatment_info['field_52ca445d62ba1']['Values']\n\n except:\n pass\n\n if purpose == 'list':\n try:\n location = incident_json['field_52ca456962ba8']\n data['location'] = location\n except:\n data['location'] = {\"lat\": \"\",\n \"long\": \"\",\n \"accuracy\": \"\"}\n\n try:\n photos = incident_json['field_52d47a654d1aa']\n photo_list = []\n for photo in photos:\n photo_list.append(photo['photo'])\n data['images'] = photo_list\n except:\n data['images'] = []\n\n try:\n treatment_given = []\n treatment_detail = incident_json['field_52ca445d62ba1']\n for treatment in treatment_detail:\n for treatment_val in treatments:\n if treatment_val.keys()[0] == treatment:\n treatment_given.append({treatment: treatment_val[treatment]})\n data['treatment'] = treatment_given\n except:\n data['treatment'] = []\n\n patient = get_patient_info(incident_pk, data_key)\n\n data['patient'] = {\n 'name': patient['name'],\n 'phone': patient['phone'],\n 'sex': patient['sex']\n }\n\n injury_data = []\n try:\n injury_info = incident_json['field_52d4798f6d227']\n for index, injury in enumerate(injury_info):\n temp_injury_data = {}\n try:\n injury_location_key = injury['injury_location']\n for injury_location in injury_location_values:\n if injury_location.keys()[0] == injury_location_key:\n temp_injury_data.update({'injury_location': injury_location[injury_location_key]})\n except:\n temp_injury_data.update({'injury_location': \"\"})\n\n try:\n body_part_key = injury['body_part']\n for body_part in body_part_values:\n if body_part.keys()[0] == body_part_key:\n temp_injury_data.update({'body_part': body_part[body_part_key]})\n except:\n temp_injury_data.update({'body_part': \"\"})\n\n try:\n injury_type_key = injury['injury_type']\n for injury_type in injury_type_values:\n if injury_type.keys()[0] == injury_type_key:\n temp_injury_data.update({'injury_type': injury_type[injury_type_key]})\n except:\n temp_injury_data.update({'injury_type': \"\"})\n\n injury_data.append(temp_injury_data)\n\n if not injury_data:\n raise Exception\n\n except:\n injury_data.append({\n \"body_part\": \"\",\n \"injury_location\": \"\",\n \"injury_type\": \"\"\n })\n\n try:\n activity_key = incident_json['field_52ca3dc8ac437']\n for activity in activity_values:\n if activity.keys()[0] == activity_key:\n data['activity'] = activity[activity_key]\n except:\n data['activity'] = \"\"\n\n data['injury'] = injury_data\n\n return replace_null(data)\n\n\ndef get_extra_incident_info_status_report(config, incident_json):\n try:\n injuries_json = config['DashboardItems']['field_52d4798f6d229']['Questions']['field_52d4798f6d227'][\n 'RepeatingQuestions']\n injury_location_values = injuries_json['injury_location']['Values']\n body_part_values = injuries_json['body_part']['Values']\n injury_type_values = injuries_json['injury_type']['Values']\n\n area_name_values = config['DashboardItems']['field_52ca41c50a16f']['Questions']['field_554f7cbb3d784']['Values']\n\n run_name_field = None\n for field, value in incident_json.iteritems():\n if field.startswith('field_551c8bbb3d785_'):\n run_name_values = config['DashboardItems']['field_52ca41c50a16f']['Questions'][field]['Values']\n run_name_field = field\n\n referred_to_values = config['DashboardItems']['field_52ca42770a179']['Questions']['field_52d48077a16be']['Values']\n except:\n pass\n\n response_data = {}\n\n # get injury information\n injury_data = []\n try:\n injury_info = incident_json['field_52d4798f6d227']\n for index, injury in enumerate(injury_info):\n temp_injury_data = {}\n try:\n injury_location_key = injury['injury_location']\n for injury_location in injury_location_values:\n if injury_location.keys()[0] == injury_location_key:\n temp_injury_data.update({'injury_location': injury_location[injury_location_key]})\n except:\n temp_injury_data.update({'injury_location': \"\"})\n\n try:\n body_part_key = injury['body_part']\n for body_part in body_part_values:\n if body_part.keys()[0] == body_part_key:\n temp_injury_data.update({'body_part': body_part[body_part_key]})\n except:\n temp_injury_data.update({'body_part': \"\"})\n\n try:\n injury_type_key = injury['injury_type']\n for injury_type in injury_type_values:\n if injury_type.keys()[0] == injury_type_key:\n temp_injury_data.update({'injury_type': injury_type[injury_type_key]})\n except:\n temp_injury_data.update({'injury_type': \"\"})\n\n injury_data.append(temp_injury_data)\n\n if not injury_data:\n raise Exception\n\n except:\n injury_data.append({\n \"body_part\": \"\",\n \"injury_location\": \"\",\n \"injury_type\": \"\"\n })\n response_data.update({\"injury\": injury_data})\n\n # get location information\n location = {}\n try:\n area_name_key = incident_json['field_554f7cbb3d784']\n for area in area_name_values:\n if area.keys()[0] == area_name_key:\n location.update({'area_name': area[area_name_key]})\n else:\n location.update({'area_name': \"\"})\n except:\n location.update({'area_name': \"\"})\n\n try:\n run_name_key = incident_json[run_name_field]\n for run in run_name_values:\n if run.keys()[0] == run_name_key:\n location.update({'run_name': run[run_name_key]})\n else:\n location.update({'run_name': \"\"})\n except:\n location.update({'run_name': \"\"})\n response_data.update({\"location\": location})\n\n # get referred to information\n try:\n referred_to_key = incident_json['field_52d48077a16be']\n for referred_to in referred_to_values:\n if referred_to.keys()[0] == referred_to_key:\n response_data.update({\"referred_to\": referred_to[referred_to_key]})\n else:\n response_data.update({\"referred_to\": \"\"})\n except:\n response_data.update({\"referred_to\": \"\"})\n\n return response_data\n\n\ndef dictfetchall(cursor):\n \"Returns all rows from a cursor as a dict\"\n desc = cursor.description\n return [\n dict(zip([col[0] for col in desc], row))\n for row in cursor.fetchall()\n ]\n\n\n# get encypted data key from the data\ndef get_data_key(resort):\n client = create_client()\n response = client.decrypt(CiphertextBlob=base64.b64decode(resort.enc_data_key))\n\n return base64.b64encode(response['Plaintext'])\n\n\ndef get_patient_info(incident_pk, data_key):\n cursor = connection.cursor()\n\n cursor.execute(\"\"\"SELECT\n pgp_sym_decrypt(name, keys.datakey) AS name,\n sex,\n pgp_sym_decrypt(address, keys.datakey) AS address,\n pgp_sym_decrypt(suburb, keys.datakey) AS suburb,\n pgp_sym_decrypt(state, keys.datakey) AS state,\n pgp_sym_decrypt(postcode, keys.datakey) AS postcode,\n country,\n pgp_sym_decrypt(phone, keys.datakey) AS phone,\n pgp_sym_decrypt(email, keys.datakey) AS email,\n pgp_sym_decrypt(dob, keys.datakey) AS dob\nFROM incidents_patients\nCROSS JOIN (SELECT %s::TEXT As datakey) As keys\nWHERE incidents_patients.incident_id = %s;\"\"\", [data_key, incident_pk])\n\n data = dictfetchall(cursor)\n cursor.close()\n\n return replace_null(data[0])\n\n\ndef merge_patient_data_for_update(incident_pk, incident_data, new_incident, data_key):\n patient_data_available = False\n patient_data = None\n\n incident_data_patient_field = {\n 'email': incident_data.get('email'),\n 'phone': incident_data.get('phone'),\n 'dob': incident_data.get('dob'),\n 'sex': incident_data.get('sex'),\n 'name': incident_data.get('name'),\n 'address': incident_data.get('address'),\n 'suburb': incident_data.get('suburb'),\n 'state': incident_data.get('state'),\n 'country': incident_data.get('country'),\n 'postcode': incident_data.get('postcode')\n }\n\n if new_incident:\n patient_data = incident_data_patient_field\n else:\n for field in PATIENT_FIELD:\n if field in incident_data:\n patient_data_available = True\n break\n if patient_data_available:\n patient_data = get_patient_info(incident_pk, data_key)\n patient_data.update({k: v for k, v in incident_data_patient_field.iteritems() if v is not None})\n\n incident_data.pop('email', None)\n incident_data.pop('phone', None)\n incident_data.pop('dob', None)\n incident_data.pop('sex', None)\n incident_data.pop('name', None)\n incident_data.pop('address', None)\n incident_data.pop('suburb', None)\n incident_data.pop('state', None)\n incident_data.pop('country', None)\n incident_data.pop('postcode', None)\n\n return patient_data, incident_data\n\n\ndef update_patient(incident_json, incident_pk, created, data_key):\n cursor = connection.cursor()\n\n if created:\n\n patient_data, incident_data = merge_patient_data_for_update(incident_pk, incident_json, True, data_key)\n\n cursor.execute(\"\"\"INSERT INTO incidents_patients (\n patient_id,\n incident_id,\n name,\n sex,\n address,\n suburb,\n state,\n postcode,\n country,\n phone,\n email,\n dob\n )\n SELECT\n v.patient_id,\n v.incident_id,\n pgp_sym_encrypt(v.name, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As name,\n v.sex,\n pgp_sym_encrypt(v.address, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As address,\n pgp_sym_encrypt(v.suburb, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As suburb,\n pgp_sym_encrypt(v.state,keys.datakey, 'compress-algo=1, cipher-algo=aes256') As state,\n pgp_sym_encrypt(v.postcode, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As postcode,\n v.country,\n pgp_sym_encrypt(v.phone,keys.datakey, 'compress-algo=1, cipher-algo=aes256') As phone,\n pgp_sym_encrypt(v.email, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As email,\n pgp_sym_encrypt(v.dob, keys.datakey, 'compress-algo=1, cipher-algo=aes256') As dob\n FROM (\n VALUES (\n uuid_generate_v4(),\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s\n )\n ) AS v (\n patient_id,\n incident_id,\n name,\n sex,\n address,\n suburb,\n state,\n postcode,\n country,\n phone,\n email,\n dob\n )\nCROSS JOIN (SELECT %s::TEXT As datakey) As keys;\"\"\", [incident_pk, patient_data['name'], patient_data['sex'], patient_data['address'], patient_data['suburb'],\n patient_data['state'], patient_data['postcode'], patient_data['country'], patient_data['phone'],\n patient_data['email'], patient_data['dob'], data_key])\n\n else:\n patient_data, incident_data = merge_patient_data_for_update(incident_pk, incident_json, False, data_key)\n\n if patient_data is not None:\n cursor.execute(\"\"\"UPDATE incidents_patients SET\n name = pgp_sym_encrypt(v.name, keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n sex = v.sex,\n address = pgp_sym_encrypt(v.address, keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n suburb = pgp_sym_encrypt(v.suburb, keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n state = pgp_sym_encrypt(v.state,keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n postcode = pgp_sym_encrypt(v.postcode, keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n country = v.country,\n phone = pgp_sym_encrypt(v.phone,keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n email = pgp_sym_encrypt(v.email, keys.datakey, 'compress-algo=1, cipher-algo=aes256'),\n dob = pgp_sym_encrypt(v.dob, keys.datakey, 'compress-algo=1, cipher-algo=aes256')\n FROM (\n VALUES (\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s,\n %s\n )\n ) AS v (\n name,\n sex,\n address,\n suburb,\n state,\n postcode,\n country,\n phone,\n email,\n dob\n )\nCROSS JOIN (SELECT %s::TEXT As datakey) As keys\nWHERE incidents_patients.incident_id = %s;\"\"\", [patient_data['name'], patient_data['sex'], patient_data['address'],\n patient_data['suburb'], patient_data['state'], patient_data['postcode'],\n patient_data['country'], patient_data['phone'], patient_data['email'],\n patient_data['dob'], data_key, incident_pk])\n\n cursor.execute(\"UPDATE incidents_incident SET incident_data = %s WHERE incident_pk = %s\",\n [json.dumps(incident_data), incident_pk])\n cursor.close()\n\n return incident_data\n\n\ndef get_incident_data(incident_pk):\n cursor = connection.cursor()\n cursor.execute(\"SELECT incident_data FROM incidents_incident WHERE incident_pk = %s;\", [incident_pk])\n data = cursor.fetchone()\n cursor.close()\n if data[0] is None:\n return None\n return replace_null(data[0])\n\n\ndef update_incident_data(incident_pk, json_data):\n cursor = connection.cursor()\n cursor.execute(\"UPDATE incidents_incident SET incident_data = %s WHERE incident_pk = %s;\",\n [json.dumps(json_data), incident_pk])\n cursor.close()\n\n return json_data\n\n\n# Functions for print incident API which merges incident_config with incident_data\n\n# This handles the \"Questions\"\ndef handle_question(incident_data, incident_config):\n for question_key, question_val in incident_config.iteritems():\n type = question_val.get('Type', '')\n if type == 'select' or type == 'radio' or type == 'gender' or \\\n type == 'arrows' or type == 'radio_button':\n try:\n question_val['selected'] = {'key': incident_data.get(question_key, ''), 'value':\n next(d for i, d in enumerate(question_val['Values']) if incident_data.get(question_key, '') in d)[\n incident_data.get(question_key, '')]}\n except:\n question_val['selected'] = {\"key\": \"\", \"value\": \"\"}\n\n elif type == 'multi_select':\n try:\n temp = []\n incident_val = incident_data.get(question_key)\n for index, value in enumerate(incident_val):\n temp.append(next(d for i, d in enumerate(question_val['Values']) if incident_val[index] in d)[\n incident_val[index]])\n question_val['selected'] = temp\n except:\n question_val['selected'] = []\n\n elif type == 'repeater':\n try:\n question_val['selected'] = handle_repeating_question(incident_data.get(question_key, ''),\n question_val.get('RepeatingQuestions', ''))\n except:\n question_val['selected'] = []\n else:\n try:\n question_val['selected'] = incident_data.get(question_key, '')\n except:\n question_val['selected'] = ''\n\n return incident_config\n\n\n# This handles the \"RepeatingQuestions\"\ndef handle_repeating_question(incident_data, incident_config):\n for val in incident_data:\n for key, value in incident_config.iteritems():\n type = value.get('Type', '')\n if type == 'select' or type == 'radio' or type == 'gender' or \\\n type == 'arrows' or type == 'radio_button':\n try:\n val[key] = {'key': val.get(key, ''),\n 'value': next(d for i, d in enumerate(value['Values']) if val.get(key, '') in d)[\n val.get(key, '')]}\n except:\n val[key] = {\"key\": \"\", \"value\": \"\"}\n else:\n try:\n val[key] = val.get(key, '')\n except:\n val[key] = ''\n\n return incident_data\n\n\ndef merge_incident(incident_json, resort):\n main_json = resort.incident_template['DashboardItems']\n for incident_key, incident_val in main_json.iteritems():\n if incident_val.has_key(\"Questions\"):\n incident_val['Questions'] = handle_question(incident_json, incident_val.get('Questions', ''))\n elif incident_val.has_key(\"RepeatingQuestions\"):\n incident_val['selected'] = handle_repeating_question(incident_json.get(incident_key, ''),\n incident_val.get('RepeatingQuestions', ''))\n return main_json\n\n\ndef get_full_incident(incident_pk):\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM incidents_incident WHERE incident_pk = %s;\", [incident_pk])\n data = dictfetchall(cursor)\n cursor.close()\n\n return data[0]\n\ndef clean_data(resort, data):\n template = resort.incident_template['DashboardItems']\n keys = ['address', 'assigned_to', 'country', 'dob', 'dt_created', 'email', 'incident_id', 'incident_pk',\n 'incident_status', 'name', 'phone', 'postcode', 'sex', 'state', 'suburb']\n for key, value in template.iteritems():\n keys.append(key)\n if 'Questions' in value:\n for kKey, vValue in value['Questions'].iteritems():\n keys.append(kKey)\n if 'Questions' in vValue:\n for kkKey, vvValue in vValue['Questions'].iteritems():\n keys.append(kkKey)\n elif 'RepeatingQuestions' in vValue:\n for kkKey, vvValue in vValue['RepeatingQuestions'].iteritems():\n keys.append(kkKey)\n elif 'RepeatingQuestions' in value:\n for kKey, vValue in value['RepeatingQuestions'].iteritems():\n keys.append(kKey)\n if 'Questions' in vValue:\n for kkKey, vvValue in vValue['Questions'].iteritems():\n keys.append(kkKey)\n elif 'RepeatingQuestions' in vValue:\n for kkKey, vvValue in vValue['RepeatingQuestions'].iteritems():\n keys.append(kkKey)\n newData = {}\n for key, value in data.iteritems():\n if key in keys:\n newData[key] = value\n return newData\n\ndef merge_incident_data(incident_data, update_data):\n if incident_data is not None:\n for k, v in update_data.iteritems():\n if (k in incident_data and isinstance(incident_data[k], dict) and isinstance(update_data[k], dict)):\n merge_incident_data(incident_data[k], update_data[k])\n else:\n incident_data[k] = update_data[k]\n else:\n return update_data\n return incident_data\n\n\ndef get_incident_sequence(resort):\n today_datetime = datetime.date.today()\n if today_datetime.month < resort.season_start_date.month:\n startDate = datetime.date(today_datetime.year - 1, resort.season_start_date.month, resort.season_start_date.day)\n elif today_datetime.month == resort.season_start_date.month:\n if today_datetime.day < resort.season_start_date.day:\n startDate = datetime.date(today_datetime.year - 1, resort.season_start_date.month,\n resort.season_start_date.day)\n else:\n startDate = datetime.date(today_datetime.year, resort.season_start_date.month, resort.season_start_date.day)\n else:\n startDate = datetime.date(today_datetime.year, resort.season_start_date.month, resort.season_start_date.day)\n endDate = startDate + datetime.timedelta(days=365)\n # Backup of original filtering used for incident filtering\n # incident_count = Incident.objects.filter(dt_created__gte=startDate, dt_created__lte=endDate, resort=resort).latest('dt_modified')\n try:\n last_incident = Incident.objects.filter(dt_created__gte=startDate, dt_created__lte=endDate,\n resort=resort).exclude(incident_status__order=9).latest(\n 'incident_sequence')\n return last_incident.incident_sequence + 1\n except:\n return 1\n\n\ndef process_values_for_drug_administered(values):\n final_list = []\n for each_value in values:\n try:\n int(each_value.keys()[0])\n final_list.append(each_value.keys()[0])\n except:\n int(each_value.keys()[1])\n final_list.append(each_value.keys()[1])\n\n return final_list\n\n\n# Incoming incident data validation\ndef create_or_retrieve_validation_conditions(resort):\n incident_template_merged = {}\n for each_key, each_value in resort.incident_template['DashboardItems'].iteritems():\n if each_value.has_key('Questions'):\n for key, value in each_value['Questions'].iteritems():\n if value.has_key('RepeatingQuestions'):\n temp_dict = {}\n for key2, value2 in value['RepeatingQuestions'].iteritems():\n if key2 == 'drug_administered':\n temp_dict.update({key2: {\"Type\": value2['Type'], \"Required\": value2['Required'],\n \"Values\": process_values_for_drug_administered(value2['Values']) if\n value2['Values'] else \"\", \"repeating\": False}})\n else:\n temp_dict.update({key2: {\"Type\": value2['Type'], \"Required\": value2['Required'],\n \"Values\": [c.keys()[0] for c in value2['Values']] if value2[\n 'Values'] else \"\", \"repeating\": False}})\n if each_key == 'notes':\n temp_dict.update(NOTES_FIELD_ADDITION)\n incident_template_merged.update({key: {\"fields\": temp_dict, \"repeating\": True}})\n else:\n incident_template_merged.update({key: {\"Type\": value['Type'], \"Required\": value['Required'],\n \"Values\": [c.keys()[0] for c in value['Values']],\n \"repeating\": False}})\n elif each_value.has_key('RepeatingQuestions'):\n temp_dict = {}\n for key1, value1 in each_value['RepeatingQuestions'].iteritems():\n temp_dict.update({key1: {\"Type\": value1['Type'], \"Required\": value1['Required'],\n \"Values\": [c.keys()[0] for c in value1['Values']] if value1['Values'] else \"\",\n \"repeating\": False}})\n if each_key == 'notes':\n temp_dict.update(NOTES_FIELD_ADDITION)\n incident_template_merged.update({each_key: {\"fields\": temp_dict, \"repeating\": True}})\n\n # Merge two dictionary\n z = incident_template_merged.copy()\n z.update(special_validation_case)\n return z\n\n\nMISSING_FIELD = 0\nINVALID_DATA = 1\nKEY_NOT_FOUND = 2\nCUSTOM_MESSAGE = 3\n\n\ndef validation_message(message_type, key, value_type=None, custom_message=None):\n message = {}\n if message_type == MISSING_FIELD:\n message = {key: \"field is missing\"}\n elif message_type == INVALID_DATA:\n message = {key: \"must be %s\" % value_type}\n elif message_type == KEY_NOT_FOUND:\n message = {key: \"key not found\"}\n elif message_type == CUSTOM_MESSAGE:\n message = {key: custom_message}\n return message\n\n\ndef field_data_validation_correction(data, field_type, values, key):\n if field_type in ['arrows', 'radio', 'select', 'gender', 'radio_button']:\n if (isinstance(data, str) or isinstance(data, unicode)) and data:\n if not (data in values):\n if data.lower() in values:\n return True, \"\", data.lower()\n else:\n return False, validation_message(INVALID_DATA, key,\n \"one of the \" + ','.join(map(str, values))), data\n else:\n return True, \"\", data\n elif (data is None) or (not data):\n return True, \"\", \"\"\n else:\n return False, validation_message(INVALID_DATA, key, 'string'), data\n\n elif field_type in ['height', 'weight', 'range', 'distance', 'length', 'altitude', 'decimal', 'temperature']:\n if not (isinstance(data, int) or isinstance(data, float)):\n try:\n if data is None:\n return True, \"\", None\n else:\n return True, \"\", float(data)\n except:\n return False, validation_message(INVALID_DATA, key, \"integer or float\"), data\n else:\n return True, \"\", data\n\n # elif field_type in []:\n # if not isinstance(data, int):\n # return validation_message(INVALID_DATA, key, \"integer\")\n\n # elif field_type in []:\n # if isinstance(data, float):\n # if not (len(str(data).rsplit('.')[-1]) == 1):\n # return validation_message(INVALID_DATA, key, \"single decimal place\")\n # elif isinstance(data, int):\n # pass\n # else:\n # return validation_message(INVALID_DATA, key, \"float\")\n\n elif field_type in ['patient_age', 'number']:\n if not isinstance(data, int):\n try:\n if data is None:\n return True, \"\", None\n else:\n return True, \"\", int(data)\n except:\n return False, validation_message(INVALID_DATA, key, \"int\"), data\n else:\n return True, \"\", data\n\n elif field_type in ['UUID']:\n if not uuid(data):\n return False, validation_message(INVALID_DATA, key, \"UUID\"), data\n else:\n return True, \"\", data\n\n elif field_type in ['date_picker']:\n try:\n if data and data != \"-1\":\n datetime_data = data[:10]\n datetime.datetime.strptime(datetime_data, '%Y-%m-%d')\n return True, \"\", datetime_data\n else:\n return True, \"\", \"\"\n except:\n return False, validation_message(INVALID_DATA, key, 'of the format YYYY-MM-DD'), data\n\n elif field_type in ['date_time_picker']:\n try:\n if data and data != \"-1\":\n datetime_data = data[:19]\n datetime.datetime.strptime(datetime_data, '%Y-%m-%d %H:%M:%S')\n return True, \"\", datetime_data\n else:\n return True, \"\", \"\"\n except:\n return False, validation_message(INVALID_DATA, key, 'of the format YYYY-MM-DD HH:MM:SS'), data\n\n elif field_type in ['file', 'image', 'message', 'signature', 'text', 'textarea']:\n if not (isinstance(data, str) or isinstance(data, unicode)):\n if data is None:\n return True, \"\", \"\"\n else:\n return False, validation_message(INVALID_DATA, key, 'string'), data\n else:\n return True, \"\", data\n\n elif field_type in ['email']:\n try:\n if (data is None) or (not data):\n return True, \"\", \"\"\n else:\n email_name, domain_part = data.strip().rsplit('@', 1)\n email = '@'.join([email_name.lower(), domain_part.lower()])\n if not validate_email(email):\n return False, validation_message(INVALID_DATA, key, 'email format'), data\n else:\n return True, \"\", email\n except:\n return False, validation_message(INVALID_DATA, key, 'valid email format'), data\n\n elif field_type in ['multi_select']:\n missing_values = []\n\n try:\n if data:\n for data_id, each_value in enumerate(data):\n if type(each_value) == str:\n pass\n else:\n data[data_id] = str(each_value)\n elif (data == \"\") or (data is None) or (data == {}):\n return True, \"\", []\n except:\n if key in TEMPORARY_SANITIZE_FIELD:\n return True, \"\", []\n else:\n return False, validation_message(INVALID_DATA, key, 'array of string'), data\n\n for value in data:\n if (not (value in values)) and value:\n missing_values.append(value)\n if missing_values:\n return False, validation_message(CUSTOM_MESSAGE, key, custom_message='%s is not valid choice' % ','.join(\n map(str, missing_values))), data\n else:\n return True, \"\", data\n elif field_type in ['hidden']:\n return True, \"\", data\n else:\n return False, validation_message(CUSTOM_MESSAGE, key, custom_message='%s type not found' % field_type), data\n\n\ndef incident_data_correction_validation(incoming_data, validation_conditions):\n \"\"\"\n corrects where possible and validates incoming incident data\n :param incoming_data: incoming incident data\n :param validation_conditions: validation conditions to check\n :type incoming_data: dict\n :type validation_conditions: dict\n :return: corrected_data incoming incident data after correction\n \"\"\"\n corrected_data = incoming_data\n validation_error = {}\n missing_fields = []\n missing_fields_with_data = []\n\n for key, value in corrected_data.iteritems():\n if validation_conditions.has_key(key):\n\n # special case of validation and correction for location and incident status\n if validation_conditions[key].has_key('special'):\n fields = validation_conditions[key]['fields']\n\n # Location data validation and correction\n if key == 'field_52ca456962ba8':\n for k, v in value.iteritems():\n if fields.has_key(k):\n try:\n if v is not None and v:\n value[k] = float(v)\n elif not v:\n value[k] = None\n except:\n validation_error.update(validation_message(INVALID_DATA, k, 'integer (or) float'))\n else:\n validation_error.update(\n validation_message(CUSTOM_MESSAGE, k, custom_message='not found in location'))\n\n # Incident status data validation and correction\n elif key == 'incident_status':\n try:\n incident_status_id = int(value['incident_status_id'])\n if not (incident_status_id in fields['incident_status_id']['Values']):\n validation_error.update(\n validation_message(INVALID_DATA, 'incident_status_id', 'between 1 and 9'))\n else:\n value['incident_status_id'] = incident_status_id\n except KeyError:\n validation_error.update(validation_message(MISSING_FIELD, 'incident_status_id'))\n except ValueError:\n validation_error.update(validation_message(INVALID_DATA, 'incident_status_id', 'integer'))\n\n # validation for non-repeating field\n elif not validation_conditions[key]['repeating']:\n valid, message, final_value = field_data_validation_correction(value,\n validation_conditions[key]['Type'],\n validation_conditions[key]['Values'],\n key)\n # if its not valid value then pass on the validation message\n if not valid:\n validation_error.update(message)\n # if its valid value then update its value to the final_data which is cleaned version of original data\n else:\n corrected_data[key] = final_value\n\n # validation for repeating field\n elif validation_conditions[key]['repeating']:\n\n if type(value) == list:\n for idx, each_value in enumerate(value):\n if each_value and (each_value is not None):\n try:\n for key2, value2 in each_value.iteritems():\n\n # special media field validation\n if key2 in MEDIA_FIELD:\n if value2:\n if not (isinstance(value2, str) or isinstance(value2, unicode)):\n validation_error.update(validation_message(INVALID_DATA, key, 'string'))\n elif (not value2) or (value2 is None):\n corrected_data[key][idx][key2] = \"\"\n elif key2 in special_validation_case:\n valid, message, final_value = field_data_validation_correction(value2,\n special_validation_case[key2]['Type'],\n special_validation_case[key2]['Values'],\n key2\n )\n if not valid:\n validation_error.update(message)\n else:\n corrected_data[key][idx][key2] = final_value\n elif key2.startswith('drug_administered_by_'):\n valid, message, final_value = field_data_validation_correction(value2,\n special_validation_case['drug_administered_by']['Type'],\n special_validation_case['drug_administered_by']['Values'],\n key2\n )\n if not valid:\n validation_error.update(message)\n else:\n corrected_data[key][idx][key2] = final_value\n elif key in validation_conditions and key2 in validation_conditions[key]['fields']:\n valid, message, final_value = field_data_validation_correction(value2,\n validation_conditions[key]['fields'][key2]['Type'],\n validation_conditions[key]['fields'][key2]['Values'],\n key2\n )\n # if its not valid value then pass on the validation message\n if not valid:\n validation_error.update(message)\n # if its valid value then update its value to the final_data which is cleaned version of original data\n else:\n corrected_data[key][idx][key2] = final_value\n except AttributeError:\n validation_error.update(validation_message(INVALID_DATA, key, 'set of dictionary'))\n else:\n corrected_data[key][idx] = {}\n\n elif (not value) or (value is None):\n corrected_data[key] = []\n else:\n validation_error.update(validation_message(INVALID_DATA, key, 'array'))\n else:\n if key not in TEMPORARY_EXCLUDED_FIELDS:\n missing_fields.append(key)\n missing_fields_with_data.append({key: value})\n\n if missing_fields:\n for val in missing_fields:\n corrected_data.pop(val, None)\n\n return corrected_data, validation_error, missing_fields_with_data\n\n\ndef validate_incident_data(incoming_data, resort):\n validation_conditions = create_or_retrieve_validation_conditions(resort)\n incoming_data, validation_error, missing_fields_with_data = incident_data_correction_validation(incoming_data,\n validation_conditions)\n\n return incoming_data, validation_error, missing_fields_with_data\n\n\ndef check_drug_administered(incoming_data, incident, user):\n updated_drug_administered = []\n\n if 'field_52d4800164f2e' in incoming_data:\n for id, value in enumerate(incoming_data['field_52d4800164f2e']):\n extra_data = {}\n if not ('controlled_substance_stock_assignment_id' in value):\n for key, val in value.iteritems():\n if key.startswith('drug_administered_by_'):\n stock = Stock.objects.get(controlled_substance_stock_id=val)\n stock_assignment = StockAssignment.objects.get(controlled_substance_stock=stock)\n\n if stock.current_status != USED:\n stock.current_status = USED\n stock.save()\n stock_assignment.controlled_substance_stock_assignment_status = USED\n stock_assignment.incident_id = incident\n stock_assignment.dt_used = timezone.now()\n stock_assignment.save()\n\n status, message = mark_stock_entry_used(incident.resort, stock)\n\n # create log entry\n log_entry = 'Item %s : %s %s of %s was used by %s on incident %s' % (str(stock.controlled_substance_stock_pk),\n str(stock.volume),\n stock.controlled_substance.units,\n stock.controlled_substance.controlled_substance_name,\n stock_assignment.user.name,\n str(incident.incident_sequence) if incident.resort.use_sequential_incident_id else str(incident.incident_pk))\n add_log(log_entry=log_entry, resort=incident.resort, user=user)\n else:\n log_entry = 'Tried to allocate item %d : %d %s of %s to %s on incident %d but item already used.' % (\n stock.controlled_substance_stock_pk, stock.volume, stock.controlled_substance.units,\n stock.controlled_substance.controlled_substance_name, user.name,\n incident.incident_sequence if incident.resort.use_sequential_incident_id else incident.incident_pk)\n add_log(log_entry=log_entry, resort=incident.resort, user=user)\n continue\n\n extra_data = {'controlled_substance_stock_assignment_id': str(\n stock_assignment.controlled_substance_stock_assignment_id)}\n if extra_data:\n value.update(extra_data)\n updated_drug_administered.append(value)\n elif 'controlled_substance_stock_assignment_id' in value:\n stock_assignment = StockAssignment.objects.get(controlled_substance_stock_assignment_id=value['controlled_substance_stock_assignment_id'])\n\n if str(stock_assignment.controlled_substance_stock.controlled_substance_stock_id) != value['drug_administered_by_'+ value['drug_administered']]:\n\n new_stock = Stock.objects.get(controlled_substance_stock_id=value['drug_administered_by_'+ value['drug_administered']])\n new_stock_assignment = StockAssignment.objects.get(controlled_substance_stock=new_stock)\n\n if new_stock.current_status != USED:\n new_stock.current_status = USED\n new_stock.save()\n new_stock_assignment.controlled_substance_stock_assignment_status = USED\n new_stock_assignment.incident_id = incident\n new_stock_assignment.dt_used = timezone.now()\n new_stock_assignment.save()\n\n status, message = mark_stock_entry_used(incident.resort, new_stock)\n\n # create log entry\n log_entry = 'Item %s : %s %s of %s was used by %s on incident %s' % (str(new_stock.controlled_substance_stock_pk),\n str(new_stock.volume),\n new_stock.controlled_substance.units,\n new_stock.controlled_substance.controlled_substance_name,\n new_stock_assignment.user.name,\n str(incident.incident_sequence) if incident.resort.use_sequential_incident_id else str(incident.incident_pk))\n add_log(log_entry=log_entry, resort=incident.resort, user=user)\n else:\n incident_data = get_incident_data(incident.incident_pk)\n\n for id1, value1 in enumerate(incident_data['field_52d4800164f2e']):\n for key1, val1 in value1.iteritems():\n if (key1 == \"controlled_substance_stock_assignment_id\") and (str(value1[key1]) == value['controlled_substance_stock_assignment_id']):\n updated_drug_administered.append(value1)\n\n log_entry = 'Tried to allocate item %d : %d %s of %s to %s on incident %d but item already used.' % (\n new_stock.controlled_substance_stock_pk, new_stock.volume, new_stock.controlled_substance.units,\n new_stock.controlled_substance.controlled_substance_name, user.name,\n incident.incident_sequence if incident.resort.use_sequential_incident_id else incident.incident_pk)\n add_log(log_entry=log_entry, resort=incident.resort, user=user)\n\n continue\n\n stock = stock_assignment.controlled_substance_stock\n stock.current_status = OUT\n stock.save()\n log_entry = \"Item %s : %s %s of %s assigned to %s was removed from incident %s by %s\" % (str(stock.controlled_substance_stock_pk),\n str(stock.volume),\n stock.controlled_substance.units,\n stock.controlled_substance.controlled_substance_name,\n stock_assignment.user.name,\n str(incident.incident_sequence) if incident.resort.use_sequential_incident_id else str(incident.incident_pk),\n user.name)\n\n add_log(log_entry=log_entry, resort=incident.resort, user=user)\n stock_assignment.controlled_substance_stock_assignment_status = OUT\n stock_assignment.incident_id = None\n stock_assignment.dt_used = None\n stock_assignment.save()\n\n unmark_used_stock_entry(incident.resort, stock)\n\n extra_data = {'controlled_substance_stock_assignment_id': str(\n new_stock_assignment.controlled_substance_stock_assignment_id)}\n if extra_data:\n value.update(extra_data)\n updated_drug_administered.append(value)\n else:\n updated_drug_administered.append(value)\n\n if updated_drug_administered:\n incoming_data['field_52d4800164f2e'] = updated_drug_administered\n return incoming_data\n\n\n# For encrypting and decrypting data\n# class AESCipher(object):\n#\n# def __init__(self, key, enc_key=None):\n# self.bs = 16\n# self.key = key\n# self.enc_key = enc_key\n#\n# def encrypt(self, raw):\n# raw = self._pad(raw)\n# iv = Random.new().read(AES.block_size)\n# cipher = AES.new(self.key, AES.MODE_CBC, iv)\n# return base64.b64encode(iv + cipher.encrypt(raw) + \"*-*-*\" + self.enc_key)\n#\n# def decrypt(self, enc):\n# enc = base64.b64decode(enc)\n# iv = enc[:AES.block_size]\n# enc_key = enc[AES.block_size:].split(\"*-*-*\")[1]\n# cipher = AES.new(self.key, AES.MODE_CBC, iv)\n# return self._unpad(cipher.decrypt(enc[AES.block_size:].split(\"*-*-*\")[0])).decode('utf-8'), enc_key\n#\n# def _pad(self, s):\n# return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)\n#\n# @staticmethod\n# def _unpad(s):\n# return s[:-ord(s[len(s)-1:])]\n", "sub_path": "project/apps/incidents/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 57425, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "apps.incidents.models.IncidentTemplate.objects.get", "line_number": 127, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentTemplate.objects", "line_number": 127, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentTemplate", "line_number": 127, "usage_type": "name"}, {"api_name": "django.db.connection.cursor", "line_number": 132, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 132, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 151, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes.objects.filter", "line_number": 160, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes.objects", "line_number": 160, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentNotes", "line_number": 160, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 167, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 167, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 169, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 169, "usage_type": "attribute"}, {"api_name": "django.contrib.auth.get_user_model", "line_number": 172, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes", "line_number": 176, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes.objects.get", "line_number": 186, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes.objects", "line_number": 186, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentNotes", "line_number": 186, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 189, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 189, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentNotes.objects.filter", "line_number": 193, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentNotes.objects", "line_number": 193, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentNotes", "line_number": 193, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 200, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 200, "usage_type": "name"}, {"api_name": "apps.incidents.models.StatusHistory", "line_number": 202, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentStatus.objects.all", "line_number": 209, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentStatus.objects", "line_number": 209, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentStatus", "line_number": 209, "usage_type": "name"}, {"api_name": "apps.incidents.models.IncidentStatus.objects.all", "line_number": 224, "usage_type": "call"}, {"api_name": "apps.incidents.models.IncidentStatus.objects", "line_number": 224, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.IncidentStatus", "line_number": 224, "usage_type": "name"}, {"api_name": "helper_functions.replace_null", "line_number": 341, "usage_type": "call"}, {"api_name": "helper_functions.create_client", "line_number": 457, "usage_type": "call"}, {"api_name": "base64.b64decode", "line_number": 458, "usage_type": "call"}, {"api_name": "base64.b64encode", "line_number": 460, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 464, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 464, "usage_type": "name"}, {"api_name": "helper_functions.replace_null", "line_number": 484, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 530, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 530, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 643, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 650, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 650, "usage_type": "name"}, {"api_name": "helper_functions.replace_null", "line_number": 656, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 660, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 660, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 662, "usage_type": "call"}, {"api_name": "django.db.connection.cursor", "line_number": 743, "usage_type": "call"}, {"api_name": "django.db.connection", "line_number": 743, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 793, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 793, "usage_type": "attribute"}, {"api_name": "datetime.date", "line_number": 795, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 798, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 801, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 803, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 804, "usage_type": "call"}, {"api_name": "apps.incidents.models.Incident.objects.filter", "line_number": 808, "usage_type": "call"}, {"api_name": "apps.incidents.models.Incident.objects", "line_number": 808, "usage_type": "attribute"}, {"api_name": "apps.incidents.models.Incident", "line_number": 808, "usage_type": "name"}, {"api_name": "validators.uuid.uuid", "line_number": 942, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 951, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 951, "usage_type": "attribute"}, {"api_name": "datetime.datetime.strptime", "line_number": 962, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 962, "usage_type": "attribute"}, {"api_name": "apps.custom_user.utils.validate_email", "line_number": 985, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.Stock.objects.get", "line_number": 1173, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.Stock.objects", "line_number": 1173, "usage_type": "attribute"}, {"api_name": "apps.controlled_substance.models.Stock", "line_number": 1173, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects.get", "line_number": 1174, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects", "line_number": 1174, "usage_type": "attribute"}, {"api_name": "apps.controlled_substance.models.StockAssignment", "line_number": 1174, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1176, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1177, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1179, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 1181, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 1181, "usage_type": "name"}, {"api_name": "apps.controlled_substance.utils.mark_stock_entry_used", "line_number": 1184, "usage_type": "call"}, {"api_name": "apps.controlled_substance.utils.add_log", "line_number": 1193, "usage_type": "call"}, {"api_name": "apps.controlled_substance.utils.add_log", "line_number": 1199, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects.get", "line_number": 1208, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects", "line_number": 1208, "usage_type": "attribute"}, {"api_name": "apps.controlled_substance.models.StockAssignment", "line_number": 1208, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.Stock.objects.get", "line_number": 1212, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.Stock.objects", "line_number": 1212, "usage_type": "attribute"}, {"api_name": "apps.controlled_substance.models.Stock", "line_number": 1212, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects.get", "line_number": 1213, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.StockAssignment.objects", "line_number": 1213, "usage_type": "attribute"}, {"api_name": "apps.controlled_substance.models.StockAssignment", "line_number": 1213, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1215, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1216, "usage_type": "name"}, {"api_name": "apps.controlled_substance.models.USED", "line_number": 1218, "usage_type": "name"}, {"api_name": "django.utils.timezone.now", "line_number": 1220, "usage_type": "call"}, {"api_name": "django.utils.timezone", "line_number": 1220, "usage_type": "name"}, {"api_name": "apps.controlled_substance.utils.mark_stock_entry_used", "line_number": 1223, "usage_type": "call"}, {"api_name": "apps.controlled_substance.utils.add_log", "line_number": 1232, "usage_type": "call"}, {"api_name": "apps.controlled_substance.utils.add_log", "line_number": 1245, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.OUT", "line_number": 1250, "usage_type": "name"}, {"api_name": "apps.controlled_substance.utils.add_log", "line_number": 1260, "usage_type": "call"}, {"api_name": "apps.controlled_substance.models.OUT", "line_number": 1261, "usage_type": "name"}, {"api_name": "apps.controlled_substance.utils.unmark_used_stock_entry", "line_number": 1266, "usage_type": "call"}]}
+{"seq_id": "630407329", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nAn implementation of the policyValueNet in PyTorch\nTested in PyTorch 0.2.0 and 0.3.0\n@author: Junxiao Song\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport numpy as np\n\n\ndef set_learning_rate(optimizer, lr):\n \"\"\"Sets the learning rate to the given value\"\"\"\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\nclass Net(nn.Module):\n \"\"\"policy-value network module\"\"\"\n #nn.BatchNorm1d(n_hidden_1)\n def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):\n super(Net, self).__init__()\n self.layer1 = nn.Sequential(nn.Linear(in_dim, n_hidden_1),\n nn.ReLU())\n self.layer2 = nn.Sequential(nn.Linear(n_hidden_1, n_hidden_2),\n nn.ReLU())\n self.layer3 = nn.Sequential(nn.Linear(n_hidden_2, out_dim),\n # nn.Sigmoid())\n nn.ReLU())\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n return x\n\n\nclass PolicyValueNet():\n \"\"\"policy-value network \"\"\"\n def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim,\n model_file=None, use_gpu=True):\n self.use_gpu = torch.cuda.is_available()\n self.in_dim = in_dim\n self.n_hidden_1 = n_hidden_1\n self.n_hidden_2 = n_hidden_2\n self.out_dim = out_dim\n\n self.l2_const = 1e-4 # coef of l2 penalty\n # the policy value net module\n if self.use_gpu:\n self.policy_value_net = Net(in_dim, n_hidden_1,n_hidden_2,out_dim).cuda()\n else:\n self.policy_value_net = Net(in_dim, n_hidden_1,n_hidden_2,out_dim)\n self.optimizer = optim.Adam(self.policy_value_net.parameters(),\n weight_decay=self.l2_const)\n\n if model_file:\n net_params = torch.load(model_file)\n self.policy_value_net.load_state_dict(net_params)\n\n def policy_value(self, state_batch):\n \"\"\"\n input: a batch of states\n output: a batch of action probabilities and state values\n \"\"\"\n if self.use_gpu:\n state_batch = Variable(torch.FloatTensor(state_batch).cuda())\n log_act_probs = self.policy_value_net(state_batch)\n act_probs = log_act_probs.data.cpu().numpy().flatten()\n\n return act_probs\n else:\n state_batch = Variable(torch.FloatTensor(state_batch))\n log_act_probs = self.policy_value_net(state_batch)\n act_probs = log_act_probs.data.numpy().flatten()\n\n return act_probs\n\n def train_step(self, state_batch, mcts_probs, lr):\n \"\"\"perform a training step\"\"\"\n # wrap in Variable\n if self.use_gpu:\n state_batch = Variable(torch.FloatTensor(state_batch).cuda())\n mcts_probs = Variable(torch.FloatTensor(mcts_probs).cuda())\n else:\n state_batch = Variable(torch.FloatTensor(state_batch))\n mcts_probs = Variable(torch.FloatTensor(mcts_probs))\n\n # zero the parameter gradients\n self.optimizer.zero_grad()\n # set learning rate\n set_learning_rate(self.optimizer, lr)\n\n # forward\n log_act_probs = self.policy_value_net(state_batch)\n # define the loss = (z - v)^2 - pi^T * log(p) + c||theta||^2\n # Note: the L2 penalty is incorporated in optimizer\n policy_loss = torch.sum(torch.abs(mcts_probs-log_act_probs.squeeze()))\n loss = policy_loss\n # backward and optimize\n loss.backward()\n self.optimizer.step()\n # calc policy entropy, for monitoring only\n\n # return loss.data[0], entropy.data[0]\n # for pytorch version >= 0.5 please use the following line instead.\n return loss.item(), 0\n\n def get_policy_param(self):\n net_params = self.policy_value_net.state_dict()\n return net_params\n\n def save_model(self, model_file):\n \"\"\" save model params to file \"\"\"\n net_params = self.get_policy_param() # get model params\n torch.save(net_params, model_file)\n", "sub_path": "model.py", "file_name": "model.py", "file_ext": "py", "file_size_in_byte": 4245, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.nn.Module", "line_number": 22, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 22, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 27, "usage_type": "call"}, {"api_name": "torch.nn.ReLU", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 29, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 29, "usage_type": "call"}, {"api_name": "torch.nn.ReLU", "line_number": 30, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 30, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 31, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 31, "usage_type": "call"}, {"api_name": "torch.nn.ReLU", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.cuda.is_available", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 46, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.load", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 71, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 77, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 87, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 88, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.FloatTensor", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.sum", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.abs", "line_number": 102, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 120, "usage_type": "call"}]}
+{"seq_id": "37141996", "text": "#!/usr/bin/env python3\n\nfrom time import sleep\nimport serial\nfrom sys import argv as args\n\n\ntry:\n port = args[1]\nexcept:\n port = \"/dev/ttyUSB0\"\n\ntry:\n baud = args[2]\nexcept:\n baud = 115200\n\nser = serial.Serial(port, baud) # Establish the connection on a specific port\n# ser.ReadIntervalTimeout=0\nwhile True:\n try:\n dicks = ser.readline().decode('utf-8')\n except:\n dicks = ser.readline()\n \n print(dicks,end='') # Read the newest output from the Arduino\n #sleep(.1) # Delay for one tenth of a second\n # ser.\n", "sub_path": "LED2/ESP8266_Master/monitor.py", "file_name": "monitor.py", "file_ext": "py", "file_size_in_byte": 569, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.argv", "line_number": 9, "usage_type": "name"}, {"api_name": "sys.argv", "line_number": 14, "usage_type": "name"}, {"api_name": "serial.Serial", "line_number": 18, "usage_type": "call"}]}
+{"seq_id": "541341690", "text": "import requests\nimport string\nfrom bs4 import BeautifulSoup\nurl = \"https://www.ps.kz/domains/lists/free?letter=%s&period=all\"\nsigns = list(string.ascii_uppercase) + list(string.digits)\nfor sign in signs:\n\tresponse = requests.get(url % sign)\n\tsoup = BeautifulSoup(response.content,\"html.parser\")\n\tdomain_table = soup.find(\"table\", { \"class\" : \"table table-bordered\" })\n\tlinks = domain_table.find_all('a')\n\tfor link in links:\n\t\tif '.kz' in link.text:\n\t\t\toutput = open('sites/%s.txt' % (len(link.text) - 3),'a')\n\t\t\toutput.write(link.text + \"\\n\")\n\t\t\toutput.close()\n", "sub_path": "sites.py", "file_name": "sites.py", "file_ext": "py", "file_size_in_byte": 561, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "string.ascii_uppercase", "line_number": 5, "usage_type": "attribute"}, {"api_name": "string.digits", "line_number": 5, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 8, "usage_type": "call"}]}
+{"seq_id": "203897536", "text": "from history_tool import History, AddHistoryMixIn\nfrom typing import Union\n\n\nclass NegativeValue(Exception):\n pass\n\n\nclass BalanceTooLow(Exception):\n pass\n\n\nclass Account(AddHistoryMixIn):\n\n def __init__(self, id, balance :Union[int, float] = 0, client_name :str = '') -> None:\n super().__init__()\n self.client_name = client_name\n self.id = id\n if balance < 0:\n raise NegativeValue(\"You can't deposit a negative value or equal to zero.\")\n self.balance = balance\n self.add_history(\n message=f\"Account {id} opened with balance {balance}\"\n )\n self.active = True\n\n def deposit(self, value :Union[int, float]) -> None:\n self.add_history(\n message=f\"Deposit of {value}\"\n )\n if value <= 0:\n raise NegativeValue(\"You can't deposit a negative value or equal to zero.\")\n self.balance += value\n\n def withdrawal(self, value :Union[int, float]) -> None:\n if self.balance - value < 0:\n self.add_history(\n message=f\"Withdrawal {value} failed. BalanceTooLow\"\n )\n raise BalanceTooLow(\"You don't have enough money on your account.\")\n self.add_history(\n message=f\"Withdrawal {value}\"\n )\n self.balance -= value\n\n def close(self) -> Union[int, float]:\n self.active = False\n self.add_history(\n message=f\"Account {self.id} closed. Returned {self.balance} cash\",\n )\n return self.balance", "sub_path": "account.py", "file_name": "account.py", "file_ext": "py", "file_size_in_byte": 1534, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "history_tool.AddHistoryMixIn", "line_number": 13, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 15, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 27, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Union", "line_number": 46, "usage_type": "name"}]}
+{"seq_id": "473496196", "text": "import spacy_universal_sentence_encoder\nfrom quickdraw import QuickDrawData\nnlp = spacy_universal_sentence_encoder.load_model('en_use_lg')\nqd = QuickDrawData()\nfrom quickdraw import QuickDrawDataGroup\nimport datetime\ndef doodle(text):\n doc_1 = nlp(text)\n score = {}\n for a in list(qd.drawing_names):\n doc_2 = nlp(a)\n score[a] = doc_1.similarity(doc_2)\n cat = sorted(score)\n doodle_cat = \"bird\"\n ants = QuickDrawDataGroup(doodle_cat)\n ant = ants.get_drawing()\n name = datetime.datetime.now().strftime(\"%Y_%m_%d-%I:%M:%S_%p\")\n ant.image.save(f\"frontend/src/assets/doodle/{name}.jpg\")\n\nimport os\nimport cv2\nfrom PIL import Image\n\nclass doodle_2_vid():\n def __init__(self) -> None:\n pass\n def find_mean_shape(self, path):\n mean_height = 0\n mean_width = 0\n\n num_of_images = len(os.listdir(path))\n\n for file in os.listdir(path):\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\"png\"):\n im = Image.open(os.path.join(path, file))\n width, height = im.size\n mean_width += width\n mean_height += height\n\n mean_width = int(mean_width / num_of_images)\n mean_height = int(mean_height / num_of_images)\n return mean_height, mean_width\n\n\n def resize(self, path):\n mean_height, mean_width = self.find_mean_shape(path)\n\n for file in os.listdir(path):\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\"png\"):\n\n im = Image.open(os.path.join(path, file))\n os.remove(os.path.join(path, file))\n\n width, height = im.size\n print(width, height)\n\n imResize = im.resize((mean_width, mean_height), Image.ANTIALIAS)\n imResize.save(os.path.join(path, file), \"JPEG\", quality=100)\n\n print(im.filename.split(\"\\\\\")[-1], \" is resized\")\n\n\n def generate_video(self, in_path, out_path):\n image_folder = in_path\n video_name = os.path.join(out_path, \"doodle.avi\")\n\n self.resize(image_folder)\n images = [\n img\n for img in os.listdir(image_folder)\n if img.endswith(\".jpg\") or img.endswith(\".jpeg\") or img.endswith(\"png\")\n ]\n\n print(images)\n\n frame = cv2.imread(os.path.join(image_folder, images[0]))\n\n height, width, layers = frame.shape\n # fourcc = cv2.VideoWriter_fourcc(*'FMP4')\n video = cv2.VideoWriter(video_name, 0, 1, (width, height))\n\n for image in images:\n video.write(cv2.imread(os.path.join(image_folder, image)))\n\n cv2.destroyAllWindows()\n video.release()\n output = \"generated\"\n os.popen(\"ffmpeg -y -i 'frontend/src/assets/video/doodle.avi' -ac 2 -b:v 2000k -c:a aac -c:v libx264 -b:a 160k -vprofile high -bf 0 -strict experimental -f mp4 'frontend/src/assets/video/doodle.mp4'\")\n\n# generate_video(\"images\", \"video\")\n\n\n# doodle(\"dog running ground\")", "sub_path": "backend/doodle_generator.py", "file_name": "doodle_generator.py", "file_ext": "py", "file_size_in_byte": 3016, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "spacy_universal_sentence_encoder.load_model", "line_number": 3, "usage_type": "call"}, {"api_name": "quickdraw.QuickDrawData", "line_number": 4, "usage_type": "call"}, {"api_name": "quickdraw.QuickDrawDataGroup", "line_number": 15, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 17, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 31, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 33, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 35, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 35, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 35, "usage_type": "call"}, {"api_name": "os.path", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 48, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 51, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 51, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 52, "usage_type": "call"}, {"api_name": "os.path", "line_number": 52, "usage_type": "attribute"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 57, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 57, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 65, "usage_type": "call"}, {"api_name": "os.path", "line_number": 65, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 70, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "cv2.VideoWriter", "line_number": 80, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 83, "usage_type": "call"}, {"api_name": "os.path", "line_number": 83, "usage_type": "attribute"}, {"api_name": "cv2.destroyAllWindows", "line_number": 85, "usage_type": "call"}, {"api_name": "os.popen", "line_number": 88, "usage_type": "call"}]}
+{"seq_id": "78474161", "text": "\nimport time\nimport numpy as np\n\n\nfrom .update_d.update_d import update_d\nfrom .utils.dictionary import get_lambda_max\nfrom .utils.dictionary import get_max_error_dict\n\nfrom .update_z.distributed_sparse_encoder import DistributedSparseEncoder\n\n\nDEFAULT_DICOD_KWARGS = dict(max_iter=int(1e8), timeout=None)\n\n\ndef dicodile(X, D_hat, reg=.1, z_positive=True, n_iter=100, strategy='greedy',\n n_seg='auto', tol=1e-3, dicod_kwargs={}, stopping_pobj=None,\n w_world='auto', n_workers=4, hostfile=None, eps=1e-5,\n window=False, raise_on_increase=True, random_state=None,\n name=\"DICODILE\", verbose=0):\n\n lmbd_max = get_lambda_max(X, D_hat).max()\n if verbose > 5:\n print(\"[DEBUG:DICODILE] Lambda_max = {}\".format(lmbd_max))\n\n # Scale reg and tol\n reg_ = reg * lmbd_max\n tol = (1 - reg) * lmbd_max * tol\n\n params = DEFAULT_DICOD_KWARGS.copy()\n params.update(dicod_kwargs)\n params.update(dict(\n strategy=strategy, n_seg=n_seg, z_positive=z_positive, tol=tol,\n random_state=random_state, reg=reg_, timing=False, soft_lock='border',\n return_ztz=False, freeze_support=False, warm_start=True, debug=False\n ))\n\n encoder = DistributedSparseEncoder(n_workers, w_world=w_world,\n hostfile=hostfile, verbose=verbose-1)\n encoder.init_workers(X, D_hat, reg_, params)\n\n n_atoms, n_channels, *_ = D_hat.shape\n\n # Initialize constants for computations of the dictionary gradient.\n constants = {}\n constants['n_channels'] = n_channels\n constants['XtX'] = np.dot(X.ravel(), X.ravel())\n\n # monitor cost function\n times = [encoder.t_init]\n pobj = [encoder.get_cost()]\n t_start = time.time()\n\n # Initial step_size\n step_size = 1\n\n for ii in range(n_iter): # outer loop of coordinate descent\n if verbose == 1:\n msg = '.' if ((ii + 1) % 10 != 0) else '+\\n'\n print(msg, end='', flush=True)\n elif verbose > 1:\n print('[INFO:{}] - CD iterations {} / {} ({:.0f}s)'\n .format(name, ii, n_iter, time.time() - t_start))\n\n if verbose > 5:\n print('[DEBUG:{}] lambda = {:.3e}'.format(name, reg_))\n\n # Compute z update\n t_start_update_z = time.time()\n encoder.process_z_hat()\n times.append(time.time() - t_start_update_z)\n\n # monitor cost function\n pobj.append(encoder.get_cost())\n if verbose > 5:\n print('[DEBUG:{}] Objective (z) : {:.3e} ({:.0f}s)'\n .format(name, pobj[-1], times[-1]))\n\n z_nnz = encoder.get_z_nnz()\n if np.all(z_nnz == 0):\n import warnings\n warnings.warn(\"Regularization parameter `reg` is too large \"\n \"and all the activations are zero. No atoms has\"\n \" been learned.\", UserWarning)\n break\n\n # Compute D update\n t_start_update_d = time.time()\n constants['ztz'], constants['ztX'] = \\\n encoder.get_sufficient_statistics()\n step_size *= 100\n D_hat, step_size = update_d(X, None, D_hat,\n constants=constants, window=window,\n step_size=step_size, max_iter=100,\n eps=1e-5, verbose=verbose, momentum=False)\n times.append(time.time() - t_start_update_d)\n # Update the dictionary D_hat in the encoder\n encoder.set_worker_D(D_hat)\n\n # If an atom is un-used, replace it by the chunk of the residual with\n # the largest un-captured variance.\n null_atom_indices = np.where(z_nnz == 0)[0]\n if len(null_atom_indices) > 0:\n k0 = null_atom_indices[0]\n z_hat = encoder.get_z_hat()\n D_hat[k0] = get_max_error_dict(X, z_hat, D_hat, window=window)[0]\n if verbose > 1:\n print('[INFO:{}] Resampled atom {}'.format(name, k0))\n\n # Update the dictionary D_hat in the encoder\n encoder.set_worker_D(D_hat)\n\n # monitor cost function\n pobj.append(encoder.get_cost())\n if verbose > 5:\n print('[DEBUG:{}] Objective (d) : {:.3e} ({:.0f}s)'\n .format(name, pobj[-1], times[-1]))\n\n # Only check that the cost is always going down when the regularization\n # parameter is fixed.\n dz = (pobj[-3] - pobj[-2]) / min(pobj[-3], pobj[-2])\n du = (pobj[-2] - pobj[-1]) / min(pobj[-2], pobj[-1])\n if (dz < eps or du < eps):\n if dz < 0 and raise_on_increase:\n raise RuntimeError(\n \"The z update have increased the objective value by {}.\"\n .format(dz)\n )\n if du < -1e-10 and dz > 1e-12 and raise_on_increase:\n raise RuntimeError(\n \"The d update have increased the objective value by {}.\"\n \"(dz={})\".format(du, dz)\n )\n if dz < eps and du < eps:\n if verbose == 1:\n print(\"\")\n print(\"[INFO:{}] Converged after {} iteration, (dz, du) \"\n \"= {:.3e}, {:.3e}\".format(name, ii + 1, dz, du))\n break\n\n if stopping_pobj is not None and pobj[-1] < stopping_pobj:\n break\n\n encoder.process_z_hat()\n z_hat = encoder.get_z_hat()\n pobj.append(encoder.get_cost())\n\n runtime = np.sum(times)\n encoder.release_workers()\n print(\"[INFO:{}] Finished in {:.0f}s\".format(name, runtime))\n return pobj, times, D_hat, z_hat\n", "sub_path": "dicodile/dicodile.py", "file_name": "dicodile.py", "file_ext": "py", "file_size_in_byte": 5609, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "utils.dictionary.get_lambda_max", "line_number": 22, "usage_type": "call"}, {"api_name": "update_z.distributed_sparse_encoder.DistributedSparseEncoder", "line_number": 38, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 47, "usage_type": "call"}, {"api_name": "time.time", "line_number": 52, "usage_type": "call"}, {"api_name": "time.time", "line_number": 63, "usage_type": "call"}, {"api_name": "time.time", "line_number": 69, "usage_type": "call"}, {"api_name": "time.time", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 80, "usage_type": "call"}, {"api_name": "warnings.warn", "line_number": 82, "usage_type": "call"}, {"api_name": "time.time", "line_number": 88, "usage_type": "call"}, {"api_name": "update_d.update_d.update_d", "line_number": 92, "usage_type": "call"}, {"api_name": "time.time", "line_number": 96, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 102, "usage_type": "call"}, {"api_name": "utils.dictionary.get_max_error_dict", "line_number": 106, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 148, "usage_type": "call"}]}
+{"seq_id": "154718501", "text": "import Sending\nimport csv\nimport math\nimport numpy as np\nfrom timeit import default_timer as timer\nfrom numba import vectorize\n@vectorize([\"float32(float32, float32)\"], target='cuda')\ndef readcsv(filename):\t\n file = open(filename, \"r\")\n reader = csv.reader(file, delimiter=\";\")\n rownum = 0\t\n a = []\n\n for row in reader:\n a.append (row)\n rownum += 1\n\n return a\n@vectorize([\"float32(float32, float32)\"], target='cuda')\ndef seperate(b):\n n=[]\n for i in b:\n for j in i:\n l=j.split(',')\n n.append(l)\n return n\nb=readcsv('C:\\\\Users\\\\akhil\\\\Downloads\\\\chikku\\\\Dataset\\\\MainDataSet.csv')\ntemp=len(b)\nprint(b[0])\ns=seperate(b)\ntotal_entered=0\ntotal_completed=0\nl=[]\n\"\"\"for i in [8,0,1,3,7,4]:\n li=[]\n for j in range(1,temp):\n if(s[j][i] not in li):\n li.append(s[j][i])\n li.sort()\n l.append(li)\ndist={'Andhra Pradesh':['ANANTAPUR', 'CHITTOOR', 'EAST GODAVARI', 'GUNTUR', 'KADAPA', 'KRISHNA',\n 'KURNOOL', 'PRAKASAM', 'SPSR NELLORE', 'SRIKAKULAM', 'VISAKHAPATANAM',\n 'VIZIANAGARAM', 'WEST GODAVARI'],\n 'Andaman and Nicobar Islands':['NICOBARS', 'NORTH AND MIDDLE ANDAMAN', 'SOUTH ANDAMANS'],\n 'Arunachal Pradesh':['ANJAW', 'CHANGLANG', 'DIBANG VALLEY', 'EAST KAMENG', 'EAST SIANG',\n 'KURUNG KUMEY', 'LOHIT', 'LONGDING', 'LOWER DIBANG VALLEY',\n 'LOWER SUBANSIRI', 'NAMSAI', 'PAPUM PARE', 'TAWANG', 'TIRAP',\n 'UPPER SIANG', 'UPPER SUBANSIRI', 'WEST KAMENG', 'WEST SIANG'],\n 'Assam':['BAKSA', 'BARPETA', 'BONGAIGAON', 'CACHAR', 'CHIRANG', 'DARRANG', 'DHEMAJI',\n 'DHUBRI', 'DIBRUGARH', 'DIMA HASAO', 'GOALPARA', 'GOLAGHAT', 'HAILAKANDI',\n 'JORHAT', 'KAMRUP', 'KAMRUP METRO', 'KARBI ANGLONG', 'KARIMGANJ', 'KOKRAJHAR',\n 'LAKHIMPUR', 'MARIGAON', 'NAGAON', 'NALBARI', 'SIVASAGAR', 'SONITPUR', 'TINSUKIA', 'UDALGURI'],\n 'Bihar':['ARARIA', 'ARWAL', 'AURANGABAD', 'BANKA', 'BEGUSARAI', 'BHAGALPUR', 'BHOJPUR'\n , 'BUXAR', 'DARBHANGA', 'GAYA', 'GOPALGANJ', 'JAMUI', 'JEHANABAD', 'KAIMUR (BHABUA)',\n 'KATIHAR', 'KHAGARIA', 'KISHANGANJ', 'LAKHISARAI', 'MADHEPURA', 'MADHUBANI', 'MUNGER',\n 'MUZAFFARPUR', 'NALANDA', 'NAWADA', 'PASHCHIM CHAMPARAN', 'PATNA', 'PURBI CHAMPARAN',\n 'PURNIA', 'ROHTAS', 'SAHARSA', 'SAMASTIPUR', 'SARAN', 'SHEIKHPURA', 'SHEOHAR', 'SITAMARHI',\n 'SIWAN', 'SUPAUL', 'VAISHALI'],\n 'Chhattisgarh':['BALOD', 'BALODA BAZAR', 'BALRAMPUR', 'BASTAR', 'BEMETARA', 'BIJAPUR', 'BILASPUR',\n 'DANTEWADA', 'DHAMTARI', 'DURG', 'GARIYABAND', 'JANJGIR-CHAMPA', 'JASHPUR', 'KABIRDHAM',\n 'KANKER', 'KONDAGAON', 'KORBA', 'KOREA', 'MAHASAMUND', 'MUNGELI', 'NARAYANPUR', 'RAIGARH',\n 'RAIPUR', 'RAJNANDGAON', 'SUKMA', 'SURAJPUR', 'SURGUJA'],\n 'Dadra and Nagar Haveli':['DADRA AND NAGAR HAVELI'],\n 'Goa':['NORTH GOA', 'SOUTH GOA'],\n 'Gujarat':['AHMADABAD', 'AMRELI', 'ANAND', 'BANAS KANTHA', 'BHARUCH', 'BHAVNAGAR', 'DANG', 'DOHAD',\n 'GANDHINAGAR', 'JAMNAGAR', 'JUNAGADH', 'KACHCHH', 'KHEDA', 'MAHESANA', 'NARMADA', 'NAVSARI',\n 'PANCH MAHALS', 'PATAN', 'PORBANDAR', 'RAJKOT', 'SABAR KANTHA', 'SURAT', 'SURENDRANAGAR', 'TAPI',\n 'VADODARA', 'VALSAD'],\n 'Chandigarh':['CHANDIGARH'],\n 'Haryana':['AMBALA', 'BHIWANI', 'FARIDABAD', 'FATEHABAD', 'GURGAON', 'HISAR', 'JHAJJAR', 'JIND', 'KAITHAL',\n 'KARNAL', 'KURUKSHETRA', 'MAHENDRAGARH', 'MEWAT', 'PALWAL', 'PANCHKULA', 'PANIPAT', 'REWARI',\n 'ROHTAK', 'SIRSA', 'SONIPAT', 'YAMUNANAGAR'],\n 'Himachal Pradesh':['BILASPUR', 'CHAMBA', 'HAMIRPUR', 'KANGRA', 'KINNAUR', 'KULLU', 'LAHUL AND SPITI',\n 'MANDI', 'SHIMLA', 'SIRMAUR', 'SOLAN', 'UNA'],\n 'Jammu and Kashmir':['ANANTNAG', 'BADGAM', 'BANDIPORA', 'BARAMULLA', 'DODA', 'GANDERBAL', 'JAMMU', 'KARGIL',\n 'KATHUA', 'KISHTWAR', 'KULGAM', 'KUPWARA', 'LEH LADAKH', 'POONCH', 'PULWAMA', 'RAJAURI',\n 'RAMBAN', 'REASI', 'SAMBA', 'SHOPIAN', 'SRINAGAR', 'UDHAMPUR'],\n 'Jharkhand':['BOKARO', 'CHATRA', 'DEOGHAR', 'DHANBAD', 'DUMKA', 'EAST SINGHBUM', 'GARHWA', 'GIRIDIH', 'GODDA',\n 'GUMLA', 'HAZARIBAGH', 'JAMTARA', 'KHUNTI', 'KODERMA', 'LATEHAR', 'LOHARDAGA', 'PAKUR', 'PALAMU',\n 'RAMGARH', 'RANCHI', 'SAHEBGANJ', 'SARAIKELA KHARSAWAN', 'SIMDEGA', 'WEST SINGHBHUM'],\n 'Karnataka':['BAGALKOT', 'BANGALORE RURAL', 'BELGAUM', 'BELLARY', 'BENGALURU URBAN', 'BIDAR', 'BIJAPUR',\n 'CHAMARAJANAGAR', 'CHIKBALLAPUR', 'CHIKMAGALUR', 'CHITRADURGA', 'DAKSHIN KANNAD', 'DAVANGERE',\n 'DHARWAD', 'GADAG', 'GULBARGA', 'HASSAN', 'HAVERI', 'KODAGU', 'KOLAR', 'KOPPAL', 'MANDYA',\n 'MYSORE', 'RAICHUR', 'RAMANAGARA', 'SHIMOGA', 'TUMKUR', 'UDUPI', 'UTTAR KANNAD', 'YADGIR'],\n 'Kerala':['ALAPPUZHA', 'ERNAKULAM', 'IDUKKI', 'KANNUR', 'KASARAGOD', 'KOLLAM', 'KOTTAYAM', 'KOZHIKODE',\n 'MALAPPURAM', 'PALAKKAD', 'PATHANAMTHITTA', 'THIRUVANANTHAPURAM', 'THRISSUR', 'WAYANAD'],\n 'Madhya Pradesh':['AGAR MALWA', 'ALIRAJPUR', 'ANUPPUR', 'ASHOKNAGAR', 'BALAGHAT', 'BARWANI', 'BETUL',\n 'BHIND', 'BHOPAL', 'BURHANPUR', 'CHHATARPUR', 'CHHINDWARA', 'DAMOH', 'DATIA', 'DEWAS',\n 'DHAR', 'DINDORI', 'GUNA', 'GWALIOR', 'HARDA', 'HOSHANGABAD', 'INDORE', 'JABALPUR',\n 'JHABUA', 'KATNI', 'KHANDWA', 'KHARGONE', 'MANDLA', 'MANDSAUR', 'MORENA', 'NARSINGHPUR',\n 'NEEMUCH', 'PANNA', 'RAISEN', 'RAJGARH', 'RATLAM', 'REWA', 'SAGAR', 'SATNA', 'SEHORE', 'SEONI',\n 'SHAHDOL', 'SHAJAPUR', 'SHEOPUR', 'SHIVPURI', 'SIDHI', 'SINGRAULI', 'TIKAMGARH', 'UJJAIN',\n 'UMARIA', 'VIDISHA'],\n 'Maharashtra':['AHMEDNAGAR', 'AKOLA', 'AMRAVATI', 'AURANGABAD', 'BEED', 'BHANDARA', 'BULDHANA', 'CHANDRAPUR',\n 'DHULE', 'GADCHIROLI', 'GONDIA', 'HINGOLI', 'JALGAON', 'JALNA', 'KOLHAPUR', 'LATUR', 'MUMBAI',\n 'NAGPUR', 'NANDED', 'NANDURBAR', 'NASHIK', 'OSMANABAD', 'PALGHAR', 'PARBHANI', 'PUNE', 'RAIGAD',\n 'RATNAGIRI', 'SANGLI', 'SATARA', 'SINDHUDURG', 'SOLAPUR', 'THANE', 'WARDHA', 'WASHIM', 'YAVATMAL'],\n 'Manipur':['BISHNUPUR', 'CHANDEL', 'CHURACHANDPUR', 'IMPHAL EAST', 'IMPHAL WEST', 'SENAPATI', 'TAMENGLONG', 'THOUBAL', 'UKHRUL'],\n 'Meghalaya':['EAST GARO HILLS', 'EAST JAINTIA HILLS', 'EAST KHASI HILLS', 'NORTH GARO HILLS', 'RI BHOI', 'SOUTH GARO HILLS',\n 'SOUTH WEST GARO HILLS', 'SOUTH WEST KHASI HILLS', 'WEST GARO HILLS', 'WEST JAINTIA HILLS', 'WEST KHASI HILLS'],\n 'Mizoram':['EAST GARO HILLS', 'EAST JAINTIA HILLS', 'EAST KHASI HILLS', 'NORTH GARO HILLS', 'RI BHOI', 'SOUTH GARO HILLS',\n 'SOUTH WEST GARO HILLS', 'SOUTH WEST KHASI HILLS', 'WEST GARO HILLS', 'WEST JAINTIA HILLS', 'WEST KHASI HILLS'],\n 'Nagaland':['DIMAPUR', 'KIPHIRE', 'KOHIMA', 'LONGLENG', 'MOKOKCHUNG', 'MON', 'PEREN', 'PHEK', 'TUENSANG', 'WOKHA', 'ZUNHEBOTO'],\n 'Odisha':['ANUGUL', 'BALANGIR', 'BALESHWAR', 'BARGARH', 'BHADRAK', 'BOUDH', 'CUTTACK', 'DEOGARH', 'DHENKANAL', 'GAJAPATI', 'GANJAM',\n 'JAGATSINGHAPUR', 'JAJAPUR', 'JHARSUGUDA', 'KALAHANDI', 'KANDHAMAL', 'KENDRAPARA', 'KENDUJHAR', 'KHORDHA', 'KORAPUT', 'MALKANGIRI',\n 'MAYURBHANJ', 'NABARANGPUR', 'NAYAGARH', 'NUAPADA', 'PURI', 'RAYAGADA', 'SAMBALPUR', 'SONEPUR', 'SUNDARGARH'], \n 'Puducherry':['KARAIKAL', 'MAHE', 'PONDICHERRY', 'YANAM'],\n 'Punjab':['AMRITSAR', 'BARNALA', 'BATHINDA', 'FARIDKOT', 'FATEHGARH SAHIB', 'FAZILKA', 'FIROZEPUR', 'GURDASPUR', 'HOSHIARPUR', 'JALANDHAR',\n 'KAPURTHALA', 'LUDHIANA', 'MANSA', 'MOGA', 'MUKTSAR', 'NAWANSHAHR', 'PATHANKOT', 'PATIALA', 'RUPNAGAR', 'S.A.S NAGAR', 'SANGRUR',\n 'TARN TARAN'],\n 'Rajasthan':['AJMER', 'ALWAR', 'BANSWARA', 'BARAN', 'BARMER', 'BHARATPUR', 'BHILWARA', 'BIKANER', 'BUNDI', 'CHITTORGARH', 'CHURU', 'DAUSA',\n 'DHOLPUR', 'DUNGARPUR', 'GANGANAGAR', 'HANUMANGARH', 'JAIPUR', 'JAISALMER', 'JALORE', 'JHALAWAR', 'JHUNJHUNU', 'JODHPUR', 'KARAULI',\n 'KOTA', 'NAGAUR', 'PALI', 'PRATAPGARH', 'RAJSAMAND', 'SAWAI MADHOPUR', 'SIKAR', 'SIROHI', 'TONK', 'UDAIPUR'],\n 'Sikkim':['EAST DISTRICT', 'NORTH DISTRICT', 'SOUTH DISTRICT', 'WEST DISTRICT'],\n 'Tamil Nadu':['ARIYALUR', 'COIMBATORE', 'CUDDALORE', 'DHARMAPURI', 'DINDIGUL', 'ERODE', 'KANCHIPURAM', 'KANNIYAKUMARI', 'KARUR',\n 'KRISHNAGIRI', 'MADURAI', 'NAGAPATTINAM', 'NAMAKKAL', 'PERAMBALUR', 'PUDUKKOTTAI', 'RAMANATHAPURAM', 'SALEM', 'SIVAGANGA',\n 'THANJAVUR', 'THE NILGIRIS', 'THENI', 'THIRUVALLUR', 'THIRUVARUR', 'TIRUCHIRAPPALLI', 'TIRUNELVELI', 'TIRUPPUR', 'TIRUVANNAMALAI',\n 'TUTICORIN', 'VELLORE', 'VILLUPURAM', 'VIRUDHUNAGAR'],\n 'Telangana':['ADILABAD', 'HYDERABAD', 'KARIMNAGAR', 'KHAMMAM', 'MAHBUBNAGAR', 'MEDAK', 'NALGONDA', 'NIZAMABAD', 'RANGAREDDI', 'WARANGAL'],\n 'Tripura':['DHALAI', 'GOMATI', 'KHOWAI', 'NORTH TRIPURA', 'SEPAHIJALA', 'SOUTH TRIPURA', 'UNAKOTI', 'WEST TRIPURA'],\n 'Uttar Pradesh':['AGRA', 'ALIGARH', 'ALLAHABAD', 'AMBEDKAR NAGAR', 'AMETHI', 'AMROHA', 'AURAIYA', 'AZAMGARH', 'BAGHPAT', 'BAHRAICH', 'BALLIA',\n 'BALRAMPUR', 'BANDA', 'BARABANKI', 'BAREILLY', 'BASTI', 'BIJNOR', 'BUDAUN', 'BULANDSHAHR', 'CHANDAULI', 'CHITRAKOOT', 'DEORIA',\n 'ETAH', 'ETAWAH', 'FAIZABAD', 'FARRUKHABAD', 'FATEHPUR', 'FIROZABAD', 'GAUTAM BUDDHA NAGAR', 'GHAZIABAD', 'GHAZIPUR', 'GONDA',\n 'GORAKHPUR', 'HAMIRPUR', 'HAPUR', 'HARDOI', 'HATHRAS', 'JALAUN', 'JAUNPUR', 'JHANSI', 'KANNAUJ', 'KANPUR DEHAT', 'KANPUR NAGAR',\n 'KASGANJ', 'KAUSHAMBI', 'KHERI', 'KUSHI NAGAR', 'LALITPUR', 'LUCKNOW', 'MAHARAJGANJ', 'MAHOBA', 'MAINPURI', 'MATHURA', 'MAU',\n 'MEERUT', 'MIRZAPUR', 'MORADABAD', 'MUZAFFARNAGAR', 'PILIBHIT', 'PRATAPGARH', 'RAE BARELI', 'RAMPUR', 'SAHARANPUR', 'SAMBHAL',\n 'SANT KABEER NAGAR', 'SANT RAVIDAS NAGAR', 'SHAHJAHANPUR', 'SHAMLI', 'SHRAVASTI', 'SIDDHARTH NAGAR', 'SITAPUR', 'SONBHADRA',\n 'SULTANPUR', 'UNNAO', 'VARANASI'],\n 'Uttarakhand':['ALMORA', 'BAGESHWAR', 'CHAMOLI', 'CHAMPAWAT', 'DEHRADUN', 'HARIDWAR', 'NAINITAL', 'PAURI GARHWAL', 'PITHORAGARH', 'RUDRA PRAYAG',\n 'TEHRI GARHWAL', 'UDAM SINGH NAGAR','UTTAR KASHI'],\n 'West Bengal':['24 PARAGANAS NORTH', '24 PARAGANAS SOUTH', 'BANKURA', 'BARDHAMAN', 'BIRBHUM', 'COOCHBEHAR', 'DARJEELING', 'DINAJPUR DAKSHIN',\n 'DINAJPUR UTTAR','HOOGHLY', 'HOWRAH', 'JALPAIGURI', 'MALDAH', 'MEDINIPUR EAST', 'MEDINIPUR WEST', 'MURSHIDABAD', 'NADIA', 'PURULIA']}\n#print(len(l[1]))\nrules=[]\nnorules=[]\nfile1=open('Rules1.csv','w+')\nfile2=open('NoRules1.csv','w+')\nco=0\ncond=[]\nfor s_soil in ['well drained loam soil']:\n com=len(l[0])-co\n print(com)\n #print(s_state+' Started \\n')\n for s_state in l[1]:\n for s_district in dist[s_state]:\n #print(s_soil)\n for s_season in l[3]:\n for s_water in l[4]:\n for i in range(1,temp):\n if((s_soil==s[i][8] and s_state==s[i][0] and s_district==s[i][1] and s_season==s[i][3] and s_water==s[i][7]) and [s_soil,s_state,s_district,s_season,s_water,s[i][4]] not in rules):\n rules.append([s_soil,s_state,s_district,s_season,s_water,s[i][4]])\n cond.append(([s_soil,s_state,s_district,s_season,s_water]))\n file1.write(s[i][8]+','+s[i][0]+','+s[i][1]+','+s[i][3]+','+s[i][7]+','+s[i][4]+'\\n')\n print(s_soil,s_state,s_district,s_season,s_water,s[i][4],1)\n \n co=co+1\n#print('\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n ')\nfor s_soil in ['well drained loam soil']:\n com=len(l[0])-co\n print(com)\n #print(s_state+' Started \\n')\n for s_state in l[1]:\n for s_district in dist[s_state]:\n #print(s_soil)\n for s_season in l[3]:\n for s_water in l[4]:\n for s_crop in l[5]:\n if([s_soil,s_state,s_district,s_season,s_water,s_crop] not in rules and [s_soil,s_state,s_district,s_season,s_water,s_crop] not in norules\n and [s_soil,s_state,s_district,s_season,s_water] not in cond):\n norules.append([s_soil,s_state,s_district,s_season,s_water,s_crop])\n cond.append(([s_soil,s_state,s_district,s_season,s_water]))\n file2.write(s_soil+','+s_state+','+s_district+','+s_season+','+s_water+','+s_crop+'\\n')\n print(s_soil,s_state,s_district,s_season,s_water,s_crop,2)\n \n co=co+1\n\nfile1.close()\nfile2.close()\n\"\"\"\n#Rules generation completed now claculating accuracy error rate\nnew=[]\ntp=0\nno=0\nfn=0\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_TruePositive.csv','w+')\n#file2=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_Some_NoValuesTP.csv','w+')\n#file3=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_NoCropvaluesFN.csv','w+')\n#file4=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_AllValues.csv','w+')\nsize=int(input(\"Enter number of rows to be tested:\"))\nfor i in range(998,temp):\n Soil=s[i][8]\n State=s[i][0]\n District=s[i][1]\n Season=s[i][3]\n Water=s[i][7]\n crop=s[i][4]\n if(i==998+size+1):\n break\n if([Soil,State,District,Season,Water,crop] not in new):\n new.append([Soil,State,District,Season,Water,crop])\n l=Sending.Collect_crops(State,District,Season,Soil,Water)\n #Sending_information.show_crops(l,m,h)\n low_year=Sending.Collect_Data(l,State,District,Season,Soil,Water)\n low_year=Sending.Best_Crop(low_year)\n l=list(low_year.keys())\n l=l[0]\n if(l==crop and l!='no crops Found'):\n tp=tp+1\n print(i,Soil,State,District,Season,Water,crop,l,'yes',1111,tp)\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'yes'+'\\n')\n #file1.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'yes'+'\\n')\n elif(l=='no crops Found'):\n fn=fn+1\n print(i,Soil,State,District,Season,Water,crop,l,'no crops Found',2222,fn)\n #file3.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no crops Found'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no crops Found'+'\\n')\n else:\n tp=tp+1\n print(i,Soil,State,District,Season,Water,crop,l,'no',3333,tp)\n #file2.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'no'+'\\n')\n#file1.close()\n#file2.close()\n#file3.close()\nb=readcsv('C:\\\\Users\\\\akhil\\\\Downloads\\\\chikku\\\\Dataset\\\\NoRules.csv')\ntemp=len(b)\nprint(b[0])\ns=seperate(b)\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_FalsePositive.csv','w+')\n#file2=open('C://Users//akhil//Downloads//chikku//testing//sum//Some_TrueNegative.csv','w+')\nfp=0\ntn=0\nfor i in range(998,temp):\n Soil=s[i][0]\n State=s[i][1]\n District=s[i][2]\n Season=s[i][3]\n Water=s[i][4]\n crop=s[i][5]\n if(i==998+size+1):\n break\n if([Soil,State,District,Season,Water,crop] not in new):\n new.append([Soil,State,District,Season,Water,crop])\n l=Sending.Collect_crops(State,District,Season,Soil,Water)\n #Sending_information.show_crops(l,m,h)\n low_year=Sending.Collect_Data(l,State,District,Season,Soil,Water)\n low_year=Sending.Best_Crop(low_year)\n l=list(low_year.keys())\n l=l[0]\n if(l!='no crops Found'):\n fp=fp+1\n print(i,Soil,State,District,Season,Water,crop,l,'yes',4444,fp)\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'FalsePositive'+'Correct'+'\\n')\n #file1.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'FalsePositive'+'Correct'+'\\n')\n elif(l=='no crops Found'):\n tn=tn+1\n print(i,Soil,State,District,Season,Water,crop,l,'no crops Found',5555,tn)\n #file2.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'TrueNegative'+'\\n')\n #file4.write(Soil+','+State+','+District+','+Season+','+Water+','+crop+','+l+','+'TrueNegative'+'\\n')\n#file1.close()\n#file2.close()\n#file3.close()\n#file4.close()\nprint(tp,fn,'\\n',fp,tn)\nerr=(fp+fn)/(tp+fn+fp+tn)\nacc=(tp+tn)/(tp+fn+fp+tn)\nsn=tp/(tp+fn)\nsp=tn/tn+fp\nprec=tp/tp+fp\nfpr=fp/tn+fp\nmcc=(tp*tn)-(fp*fn)/math.sqrt((tp+fp)*(tp+fn)*(tn+fp)*(tn+fn))\nf_0=(1.25*prec*sn)/(1.25*prec+sn)\nf_1=(2*prec*sn)/(prec+sn)\nf_2=(5*prec*sn)/(4*prec+sn)\n#file1=open('C://Users//akhil//Downloads//chikku//testing//sum//Result.csv','w+')\n#file1.write('Error rate'+','+str(err)+'\\n')\nprint('Error rate',err)\n#file1.write('Accuracy'+','+str(acc)+'\\n')\nprint('Accuracy',acc)\n#file1.write('Sensitivity (or) True Positivity rate (or) Recall'+','+str(sn)+'\\n')\nprint('Sensitivity \\nTrue Positivity rate \\nRecall',sn)\n#file1.write('Specificity (or) True Negative rate'+','+str(sp)+'\\n')\nprint('Specificity \\nTrue Negative rate',sp)\n#file1.write('Precision (or) Positive Predicted Value'+','+str(prec)+'\\n')\nprint('Precision \\nPositive Predicted Value',prec)\n#file1.write('False positive rate'+','+str(fpr)+'\\n')\nprint('False positive rate',fpr)\n#file1.write('Matthews correlation coefficient'+','+str(mcc)+'\\n')\nprint('Matthews correlation coefficient',mcc)\n#file1.write('F_0.5'+','+str(f_0)+'\\n')\nprint('F_0.5',f_0)\n#file1.write('F_1'+','+str(f_1)+'\\n')\nprint('F_1',f_1)\n#file1.write('F_2'+','+str(f_2)+'\\n')\nprint('F_2',f_2)\n#file1.close()\n", "sub_path": "testing/Testing - some.py", "file_name": "Testing - some.py", "file_ext": "py", "file_size_in_byte": 19315, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "csv.reader", "line_number": 10, "usage_type": "call"}, {"api_name": "numba.vectorize", "line_number": 7, "usage_type": "call"}, {"api_name": "numba.vectorize", "line_number": 19, "usage_type": "call"}, {"api_name": "Sending.Collect_crops", "line_number": 201, "usage_type": "call"}, {"api_name": "Sending.Collect_Data", "line_number": 203, "usage_type": "call"}, {"api_name": "Sending.Best_Crop", "line_number": 204, "usage_type": "call"}, {"api_name": "Sending.Collect_crops", "line_number": 244, "usage_type": "call"}, {"api_name": "Sending.Collect_Data", "line_number": 246, "usage_type": "call"}, {"api_name": "Sending.Best_Crop", "line_number": 247, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 271, "usage_type": "call"}]}
+{"seq_id": "315569724", "text": "\"\"\"Setup module.\"\"\"\nimport logging\nfrom pathlib import Path\n\nfrom setuptools import find_packages, setup # type: ignore\n\n\ndef main() -> None:\n \"\"\"Run setup.\"\"\"\n # run setup\n setup(\n name='pybotics',\n packages=find_packages(),\n url='https://github.com/nnadeau/pybotics',\n license='MIT',\n author='Nicholas Nadeau',\n author_email='nicholas.nadeau@gmail.com',\n description='Python Toolbox for Robotics',\n long_description=get_long_description(),\n long_description_content_type='text/markdown',\n use_scm_version=True,\n setup_requires=[\n 'setuptools',\n 'setuptools_scm'\n ],\n install_requires=get_requirements(), # type: ignore\n tests_require=['pytest'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Education',\n 'Intended Audience :: End Users/Desktop',\n 'Intended Audience :: Manufacturing',\n 'Intended Audience :: Science/Research',\n 'Topic :: Education',\n 'Topic :: Scientific/Engineering',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Scientific/Engineering :: Human Machine Interfaces',\n 'Topic :: Scientific/Engineering :: Mathematics',\n 'Topic :: Scientific/Engineering :: Physics',\n 'Topic :: Utilities',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords=[\n 'python',\n 'robot',\n 'robotics',\n 'research',\n 'automation',\n 'kinematics',\n 'geometry',\n ]\n )\n\n\ndef get_long_description() -> str:\n \"\"\"Get description text.\"\"\"\n # description init\n description = ''\n\n # add README\n path = Path(__file__).parent / 'README.md'\n logging.info('README path: {}'.format(path.resolve()))\n with open(str(path)) as f:\n description += '\\n'\n description += f.read()\n\n # add changelog\n path = Path(__file__).parent / 'CHANGELOG.md'\n logging.info('CHANGELOG path: {}'.format(path.resolve()))\n with open(str(path)) as f:\n description += '\\n'\n description += f.read()\n\n return description\n\n\n# don't want to import typing... so ignore type\ndef get_requirements(): # type: ignore\n \"\"\"Get requirements list.\"\"\"\n # requirements\n requirements_path = Path(__file__).parent / 'requirements.txt'\n logging.info('Requirements path: {}'.format(requirements_path.resolve()))\n with open(str(requirements_path)) as f:\n requirements = f.read().splitlines()\n return requirements\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n main()\n", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 3077, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "setuptools.setup", "line_number": 11, "usage_type": "call"}, {"api_name": "setuptools.find_packages", "line_number": 13, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 67, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 68, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 74, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 75, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 87, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 88, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 95, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 95, "usage_type": "attribute"}]}
+{"seq_id": "47644618", "text": "# -*- coding: utf-8 -*-\n\n# source:\n# https://github.com/madzak/python-json-logger/blob/master/src/pythonjsonlogger/jsonlogger.py\n# and Remy's contribution of RabbitMQHandler\n\n# Copyright (c) 2011, Zakaria Zajac\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport logging\nimport json\nimport re\nimport datetime\nimport traceback\nimport pika\nimport time\nimport os\nfrom inspect import istraceback\n\n# Support order in python 2.7 and 3\ntry:\n from collections import OrderedDict\nexcept ImportError:\n pass\n\nVERSION = '0.0.8'\nAPI_VERSION = '1.0.8'\n\n# defaults vars\nAMQP_URL = 'amqp://guest:guest@localhost'\nAMQP_EXCHANGE = 'amq.topic'\n\n# import AMQP variables from environment\ntry:\n AMQP_URL = str(os.environ['AMQP_URL'])\n AMQP_EXCHANGE = str(os.environ['AMQP_EXCHANGE'])\n print('Env vars for AMQP connection succesfully imported')\n print('URL: %s' % AMQP_URL)\n print('AMQP_EXCHANGE: %s' % AMQP_EXCHANGE)\n\nexcept KeyError as e:\n print(' Cannot retrieve environment variables for AMQP connection, using default url: %s, exchange: %s' % (\n AMQP_URL, AMQP_EXCHANGE))\n\n# skip natural LogRecord attributes\n# http://docs.python.org/library/logging.html#logrecord-attributes\nRESERVED_ATTRS = (\n 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',\n 'funcName', 'levelname', 'levelno', 'lineno', 'module',\n 'msecs', 'message', 'msg', 'name', 'pathname', 'process',\n 'processName', 'relativeCreated', 'stack_info', 'thread', 'threadName')\n\nRESERVED_ATTR_HASH = dict(zip(RESERVED_ATTRS, RESERVED_ATTRS))\n\n\ndef merge_record_extra(record, target, reserved=RESERVED_ATTR_HASH):\n \"\"\"\n Merges extra attributes from LogRecord object into target dictionary\n :param record: logging.LogRecord\n :param target: dict to update\n :param reserved: dict or list with reserved keys to skip\n \"\"\"\n for key, value in record.__dict__.items():\n # this allows to have numeric keys\n if (key not in reserved\n and not (hasattr(key, \"startswith\")\n and key.startswith('_'))):\n target[key] = value\n return target\n\n\nclass JsonFormatter(logging.Formatter):\n \"\"\"\n A custom formatter to format logging records as json strings.\n extra values will be formatted as str() if nor supported by\n json default encoder\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n :param json_default: a function for encoding non-standard objects\n as outlined in http://docs.python.org/2/library/json.html\n :param json_encoder: optional custom encoder\n :param prefix: an optional string prefix added at the beginning of\n the formatted string\n \"\"\"\n self.json_default = kwargs.pop(\"json_default\", None)\n self.json_encoder = kwargs.pop(\"json_encoder\", None)\n self.prefix = kwargs.pop(\"prefix\", \"\")\n # super(JsonFormatter, self).__init__(*args, **kwargs)\n logging.Formatter.__init__(self, *args, **kwargs)\n if not self.json_encoder and not self.json_default:\n def _default_json_handler(obj):\n '''Prints dates in ISO format'''\n if isinstance(obj, (datetime.date, datetime.time)):\n return obj.isoformat()\n elif istraceback(obj):\n tb = ''.join(traceback.format_tb(obj))\n return tb.strip()\n elif isinstance(obj, Exception):\n return \"Exception: %s\" % str(obj)\n return str(obj)\n\n self.json_default = _default_json_handler\n self._required_fields = self.parse()\n self._skip_fields = dict(zip(self._required_fields,\n self._required_fields))\n self._skip_fields.update(RESERVED_ATTR_HASH)\n\n def parse(self):\n \"\"\"Parses format string looking for substitutions\"\"\"\n standard_formatters = re.compile(r'\\((.+?)\\)', re.IGNORECASE)\n return standard_formatters.findall(self._fmt)\n\n def add_fields(self, log_record, record, message_dict):\n \"\"\"\n Override this method to implement custom logic for adding fields.\n \"\"\"\n for field in self._required_fields:\n log_record[field] = record.__dict__.get(field)\n log_record.update(message_dict)\n\n merge_record_extra(record, log_record, reserved=self._skip_fields)\n\n def process_log_record(self, log_record):\n \"\"\"\n Override this method to implement custom logic\n on the possibly ordered dictionary.\n \"\"\"\n return log_record\n\n def jsonify_log_record(self, log_record):\n \"\"\"Returns a json string of the log record.\"\"\"\n return json.dumps(log_record,\n default=self.json_default,\n cls=self.json_encoder)\n\n def format(self, record):\n \"\"\"Formats a log record and serializes to json\"\"\"\n message_dict = {}\n if isinstance(record.msg, dict):\n message_dict = record.msg\n record.message = None\n else:\n record.message = record.getMessage()\n # only format time if needed\n if \"asctime\" in self._required_fields:\n record.asctime = self.formatTime(record, self.datefmt)\n\n # Display formatted exception, but allow overriding it in the\n # user-supplied dict.\n if record.exc_info and not message_dict.get('exc_info'):\n message_dict['exc_info'] = self.formatException(record.exc_info)\n if not message_dict.get('exc_info') and record.exc_text:\n message_dict['exc_info'] = record.exc_text\n\n try:\n log_record = OrderedDict()\n log_record['component'] = record.name\n log_record['_api_version'] = API_VERSION\n except NameError:\n log_record = {}\n\n self.add_fields(log_record, record, message_dict)\n log_record = self.process_log_record(log_record)\n\n return \"%s%s\" % (self.prefix, self.jsonify_log_record(log_record))\n\n\nclass RabbitMQHandler(logging.Handler):\n \"\"\"\n A handler that acts as a RabbitMQ publisher\n Example setup::\n handler = RabbitMQHandler('amqp://guest:guest@localhost')\n \"\"\"\n\n def __init__(self, url, name, exchange=\"amq.topic\"):\n logging.Handler.__init__(self)\n self.url = url\n self.connection = pika.BlockingConnection(pika.URLParameters(self.url))\n self.channel = self.connection.channel()\n self.exchange = exchange\n self.name = name\n self.createLock()\n\n def emit(self, record):\n\n self.acquire()\n\n routing_key = \".\".join([\"log\", record.levelname.lower(), self.name])\n\n try:\n self.channel.basic_publish(\n exchange=self.exchange,\n routing_key=routing_key,\n body=self.format(record),\n properties=pika.BasicProperties(\n content_type='application/json'\n )\n )\n\n except (pika.exceptions.ConnectionClosed, BrokenPipeError):\n\n print(\"Log handler connection closed. Reconnecting..\")\n\n self.connection = pika.BlockingConnection(pika.URLParameters(self.url))\n self.channel = self.connection.channel()\n\n # send retry\n self.channel.basic_publish(\n exchange=self.exchange,\n routing_key=routing_key,\n body=self.format(record),\n properties=pika.BasicProperties(\n content_type='application/json'\n )\n )\n\n finally:\n self.release()\n\n def close(self):\n\n self.acquire()\n\n try:\n self.channel.close()\n except (AttributeError, pika.exceptions.ConnectionClosed):\n pass\n\n try:\n self.connection.close()\n except (AttributeError, pika.exceptions.ConnectionClosed):\n pass\n\n finally:\n self.release()\n\n self.connection, self.channel = None, None\n\n\nif __name__ == \"__main__\":\n\n rabbitmq_handler = RabbitMQHandler(AMQP_URL, \"MyComponent\")\n json_formatter = JsonFormatter()\n rabbitmq_handler.setFormatter(json_formatter)\n\n logger = logging.getLogger(__name__)\n logger.addHandler(rabbitmq_handler)\n logger.setLevel(logging.DEBUG)\n\n sh = logging.StreamHandler()\n logger.addHandler(sh)\n\n while True:\n logger.critical(\"This is a critical message\")\n time.sleep(1)\n logger.error(\"This is an error\")\n time.sleep(1)\n logger.warning(\"This is a warning\")\n time.sleep(1)\n logger.info(\"This is an info\")\n time.sleep(1)\n logger.debug(\"This is a debug\")\n", "sub_path": "event_bus_utils/rmq_handler.py", "file_name": "rmq_handler.py", "file_ext": "py", "file_size_in_byte": 9954, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.environ", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 52, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 88, "usage_type": "attribute"}, {"api_name": "logging.Formatter.__init__", "line_number": 107, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 107, "usage_type": "attribute"}, {"api_name": "datetime.date", "line_number": 111, "usage_type": "attribute"}, {"api_name": "datetime.time", "line_number": 111, "usage_type": "attribute"}, {"api_name": "inspect.istraceback", "line_number": 113, "usage_type": "call"}, {"api_name": "traceback.format_tb", "line_number": 114, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 128, "usage_type": "call"}, {"api_name": "re.IGNORECASE", "line_number": 128, "usage_type": "attribute"}, {"api_name": "json.dumps", "line_number": 150, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 174, "usage_type": "call"}, {"api_name": "logging.Handler", "line_number": 186, "usage_type": "attribute"}, {"api_name": "logging.Handler.__init__", "line_number": 194, "usage_type": "call"}, {"api_name": "logging.Handler", "line_number": 194, "usage_type": "attribute"}, {"api_name": "pika.BlockingConnection", "line_number": 196, "usage_type": "call"}, {"api_name": "pika.URLParameters", "line_number": 196, "usage_type": "call"}, {"api_name": "pika.BasicProperties", "line_number": 213, "usage_type": "call"}, {"api_name": "pika.exceptions", "line_number": 218, "usage_type": "attribute"}, {"api_name": "pika.BlockingConnection", "line_number": 222, "usage_type": "call"}, {"api_name": "pika.URLParameters", "line_number": 222, "usage_type": "call"}, {"api_name": "pika.BasicProperties", "line_number": 230, "usage_type": "call"}, {"api_name": "pika.exceptions", "line_number": 244, "usage_type": "attribute"}, {"api_name": "pika.exceptions", "line_number": 249, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 264, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 266, "usage_type": "attribute"}, {"api_name": "logging.StreamHandler", "line_number": 268, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 273, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 275, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 277, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 279, "usage_type": "call"}]}
+{"seq_id": "285606746", "text": "import json\nimport traceback\nfrom http import HTTPStatus\n\nfrom elasticsearch import TransportError\n\nfrom jassrealtime.webapi.handlers.base_handler import BaseHandler\n\nfrom jassrealtime.core.master_factory_list import get_master_document_corpus_list\nfrom jassrealtime.document.document_corpus import DocumentAlreadyExistsException, CorpusNotFoundException, \\\n DocumentNotFoundException\nfrom jassrealtime.security.security_selector import get_autorisation\nfrom jassrealtime.webapi.handlers.parameter_names import *\nfrom jassrealtime.core.settings_utils import get_env_id\n\nMAX_DOCUMENT_SIZE = 1000\n\n\nclass DocumentFolderHandler(BaseHandler):\n def post(self, corpusId):\n try:\n body = json.loads(self.request.body.decode(\"utf-8\"))\n\n language = body.get(\"language\")\n if not language:\n self.write_and_set_status({MESSAGE: \"Missing required parameters\"})\n self.set_status(HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n\n docId = body.get(\"id\") # Note: 'get' defaults to None when key does not exist\n text = body.get(\"text\", \"\")\n title = body.get(\"title\", \"\")\n source = body.get(\"source\", \"\")\n\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n if not language in corpus.languages:\n self.write_and_set_status({MESSAGE: \"Document language do not correspond to corpus language\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n docId = corpus.add_text_document(text, title, language, docId, source)\n\n self.write_and_set_status({\"id\": docId},\n HTTPStatus.OK)\n except DocumentAlreadyExistsException:\n self.write_and_set_status({MESSAGE: \"Document with the same id already exists\"},\n HTTPStatus.CONFLICT)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def options(self, corpusId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n def get(self, corpusId):\n \"\"\"Get documents from corpus according to pagination\"\"\"\n try:\n fromIndexArgument = self.get_query_argument(\"from\")\n fromIndex = int(fromIndexArgument)\n if fromIndex < 0:\n self.write_and_set_status({MESSAGE: \"'from' must cannot be less than zero\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n sizeArgument = self.get_query_argument(\"size\")\n size = int(sizeArgument)\n\n if size < 1:\n self.write_and_set_status({MESSAGE: \"'size' cannot be less than 1\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n return\n\n size = min(size, MAX_DOCUMENT_SIZE)\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n filterTitle = self.get_query_argument(\"filterTitle\", default=None)\n filterSource = self.get_query_argument(\"filterSource\", default=None)\n filterJoin = self.get_query_argument(\"filterJoin\", default=None)\n sortBy = self.get_query_argument(\"sortBy\", default=None)\n sortOrder = self.get_query_argument(\"sortOrder\", default=None)\n documents = corpus.get_text_documents(fromIndex, size, sortBy, sortOrder, filterTitle, filterSource,\n filterJoin)\n\n self.write_and_set_status({\"documents\": documents},\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except ValueError as ve:\n self.write_and_set_status({MESSAGE: \"Invalid 'from' or 'size' parameter\"},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n except TransportError as te:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"ES TransportError\", TRACE: trace},\n te.status_code)\n except Exception as e:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n\nclass DocumentHandler(BaseHandler):\n def get(self, corpusId, documentId):\n \"\"\"Get a single document from corpus\"\"\"\n try:\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n document = corpus.get_text_document(documentId)\n\n if document is None:\n raise DocumentNotFoundException(documentId)\n\n self.write_and_set_status(document,\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except DocumentNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified document not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def delete(self, corpusId, documentId):\n \"\"\"Delete a single document an optionally its annotations\"\"\"\n try:\n delete_annotations_argument = self.get_query_argument(\"deleteAnnotations\", None)\n if not delete_annotations_argument:\n self.missing_required_field(\"deleteAnnotations\")\n return\n\n delete_annotations = 'true' == delete_annotations_argument\n\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n document = corpus.delete_document(documentId, delete_annotations)\n self.write_and_set_status(document,\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except DocumentNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified document not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n\n def options(self, corpusId, documentId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n\nclass DocumentIdsHandler(BaseHandler):\n def options(self, corpusId):\n self.write_and_set_status(None, HTTPStatus.OK)\n\n def get(self, corpusId):\n try:\n envId = get_env_id()\n authorization = get_autorisation(envId, None, None)\n corpus = get_master_document_corpus_list(envId, authorization).get_corpus(corpusId)\n\n documentIds = corpus.get_document_ids()\n\n self.write_and_set_status({\"ids\": documentIds},\n HTTPStatus.OK)\n except CorpusNotFoundException:\n self.write_and_set_status({MESSAGE: \"Specified corpus not found\"},\n HTTPStatus.NOT_FOUND)\n except Exception:\n trace = traceback.format_exc().splitlines()\n self.write_and_set_status({MESSAGE: \"Internal server error\", TRACE: trace},\n HTTPStatus.INTERNAL_SERVER_ERROR)\n", "sub_path": "jassrealtime/webapi/handlers/document.py", "file_name": "document.py", "file_ext": "py", "file_size_in_byte": 8551, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "jassrealtime.webapi.handlers.base_handler.BaseHandler", "line_number": 19, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 22, "usage_type": "call"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 27, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 27, "usage_type": "name"}, {"api_name": "jassrealtime.core.settings_utils.get_env_id", "line_number": 30, "usage_type": "call"}, {"api_name": "jassrealtime.security.security_selector.get_autorisation", "line_number": 31, "usage_type": "call"}, {"api_name": "jassrealtime.core.master_factory_list.get_master_document_corpus_list", "line_number": 38, "usage_type": "call"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 41, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 41, "usage_type": "name"}, {"api_name": "http.HTTPStatus.OK", "line_number": 47, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 47, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.DocumentAlreadyExistsException", "line_number": 48, "usage_type": "name"}, {"api_name": "http.HTTPStatus.CONFLICT", "line_number": 50, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 50, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 52, "usage_type": "call"}, {"api_name": "http.HTTPStatus.INTERNAL_SERVER_ERROR", "line_number": 54, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 54, "usage_type": "name"}, {"api_name": "http.HTTPStatus.OK", "line_number": 57, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 57, "usage_type": "name"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 66, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 66, "usage_type": "name"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 74, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 74, "usage_type": "name"}, {"api_name": "jassrealtime.core.settings_utils.get_env_id", "line_number": 79, "usage_type": "call"}, {"api_name": "jassrealtime.security.security_selector.get_autorisation", "line_number": 80, "usage_type": "call"}, {"api_name": "jassrealtime.core.master_factory_list.get_master_document_corpus_list", "line_number": 82, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 92, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 92, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.CorpusNotFoundException", "line_number": 93, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 95, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 95, "usage_type": "name"}, {"api_name": "http.HTTPStatus.UNPROCESSABLE_ENTITY", "line_number": 98, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 98, "usage_type": "name"}, {"api_name": "elasticsearch.TransportError", "line_number": 99, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 100, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 104, "usage_type": "call"}, {"api_name": "http.HTTPStatus.INTERNAL_SERVER_ERROR", "line_number": 106, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 106, "usage_type": "name"}, {"api_name": "jassrealtime.webapi.handlers.base_handler.BaseHandler", "line_number": 109, "usage_type": "name"}, {"api_name": "jassrealtime.core.settings_utils.get_env_id", "line_number": 113, "usage_type": "call"}, {"api_name": "jassrealtime.security.security_selector.get_autorisation", "line_number": 114, "usage_type": "call"}, {"api_name": "jassrealtime.core.master_factory_list.get_master_document_corpus_list", "line_number": 115, "usage_type": "call"}, {"api_name": "jassrealtime.document.document_corpus.DocumentNotFoundException", "line_number": 119, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 122, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 122, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.CorpusNotFoundException", "line_number": 123, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 125, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 125, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.DocumentNotFoundException", "line_number": 126, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 128, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 128, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 130, "usage_type": "call"}, {"api_name": "http.HTTPStatus.INTERNAL_SERVER_ERROR", "line_number": 132, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 132, "usage_type": "name"}, {"api_name": "jassrealtime.core.settings_utils.get_env_id", "line_number": 144, "usage_type": "call"}, {"api_name": "jassrealtime.security.security_selector.get_autorisation", "line_number": 145, "usage_type": "call"}, {"api_name": "jassrealtime.core.master_factory_list.get_master_document_corpus_list", "line_number": 146, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 149, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 149, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.CorpusNotFoundException", "line_number": 150, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 152, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 152, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.DocumentNotFoundException", "line_number": 153, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 155, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 155, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 157, "usage_type": "call"}, {"api_name": "http.HTTPStatus.INTERNAL_SERVER_ERROR", "line_number": 159, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 159, "usage_type": "name"}, {"api_name": "http.HTTPStatus.OK", "line_number": 162, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 162, "usage_type": "name"}, {"api_name": "jassrealtime.webapi.handlers.base_handler.BaseHandler", "line_number": 165, "usage_type": "name"}, {"api_name": "http.HTTPStatus.OK", "line_number": 167, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 167, "usage_type": "name"}, {"api_name": "jassrealtime.core.settings_utils.get_env_id", "line_number": 171, "usage_type": "call"}, {"api_name": "jassrealtime.security.security_selector.get_autorisation", "line_number": 172, "usage_type": "call"}, {"api_name": "jassrealtime.core.master_factory_list.get_master_document_corpus_list", "line_number": 173, "usage_type": "call"}, {"api_name": "http.HTTPStatus.OK", "line_number": 178, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 178, "usage_type": "name"}, {"api_name": "jassrealtime.document.document_corpus.CorpusNotFoundException", "line_number": 179, "usage_type": "name"}, {"api_name": "http.HTTPStatus.NOT_FOUND", "line_number": 181, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 181, "usage_type": "name"}, {"api_name": "traceback.format_exc", "line_number": 183, "usage_type": "call"}, {"api_name": "http.HTTPStatus.INTERNAL_SERVER_ERROR", "line_number": 185, "usage_type": "attribute"}, {"api_name": "http.HTTPStatus", "line_number": 185, "usage_type": "name"}]}
+{"seq_id": "96308756", "text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport os, sys, cgi\n\nprint('Content-Type: text/json\\r\\n')\n\n# Log HTTP request\nREQUEST_METHOD = os.getenv('REQUEST_METHOD')\n#if REQUEST_METHOD:\ntry:\n sys.stderr.write(REQUEST_METHOD + ' ' + os.environ['SCRIPT_NAME'] + '?' + os.environ['QUERY_STRING'] + '\\n')\n #if REQUEST_METHOD == 'POST':\n # sys.stderr.write(sys.stdin.read() + '\\n')\n form = cgi.FieldStorage()\n for key in form.keys():\n sys.stderr.write(key + '=' + form[key].value + '\\n')\n access_token = form['client_id'].value + '?' + form['client_secret'].value # Trick: Use access_token to pass client_id and client_secret\nexcept:\n import traceback\n sys.stderr.write(traceback.format_exc())\n access_token = 'http://192.168.1.10:8123?password'\n\n# Print content\nprint('{\\\n\"access_token\": \"' + access_token + '\",\\\n\"expires_in\": 3600,\\\n\"token_type\": \"Bearer\",\\\n\"scope\": null,\\\n\"refresh_token\": \"a9f97c43a88c2f2c8270c53d4f1f2d5abc626e62\"\\\n}')\n", "sub_path": "hagenie/access.py", "file_name": "access.py", "file_ext": "py", "file_size_in_byte": 945, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "os.getenv", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 12, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 12, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "attribute"}, {"api_name": "cgi.FieldStorage", "line_number": 15, "usage_type": "call"}, {"api_name": "sys.stderr.write", "line_number": 17, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 17, "usage_type": "attribute"}, {"api_name": "sys.stderr.write", "line_number": 21, "usage_type": "call"}, {"api_name": "sys.stderr", "line_number": 21, "usage_type": "attribute"}, {"api_name": "traceback.format_exc", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "519104049", "text": "import Grabber\nimport IO\nimport multiprocessing\nimport os\nfrom IO import SongList, Logger\nfrom multiprocessing import Value\n\n\ndef cleanup(args):\n print(\"At exit triggered\")\n args[1].clear()\n args[1].update(args[0])\n args[1].close()\n args[2].close()\n\n\nif __name__ == '__main__':\n import ctypes\n import atexit\n\n # This reads the settings file which the container executable for this should assert exists. In the case it\n # doesn't exist, this program will crash before it can even do anything. Make sure the settings file exists\n # in the same directory as this script and make sure it is formatted as such (python dictionary type):\n # {'songlist': %path of songlist.txt%, 'log': %path of log.txt%, 'root': %root music directory%, 'defaults':{'source': 'yt', '-o': True}}\n settings = IO.initialize()\n\n # The next two lines assert that songlist file and the log file exist. This is important and if they don't, ensure\n # that both the files exist in the directories as specified by the settings.txt file.\n assert(os.path.exists(settings['log']))\n assert(os.path.exists(settings['songlist']))\n\n # The next two lines initialize the logger and the songlist classes which may be used various times throughout this\n # script. The program crashes if the log or songlist files are unwritable/unreadable as the errors aren't handled.\n logger = Logger(open(settings['log'], 'r+'))\n songlist = SongList(open(settings['songlist'], 'r+'))\n\n # Initialize the webbrowser that will be passed to each song to retrive the offliberty URL. This could be done by\n # the song each time but that increases overhead slightly and risks the webdriver not being terminated as it should\n # when the process is terminated. So instead the webdriver/webbrowser will be initialized once and passed along each time.\n\n songs = songlist.get_songs()\n songs = list(filter(lambda x: x.strip() != \"\", songs))\n\n logger.clear()\n # songlist.clear()\n\n # register cleanup atexit now that all necessary variables have been initialized:4\n print(songs)\n atexit.register(cleanup, [songs, songlist, logger])\n print(\"Atexit registered.\")\n # exit()\n\n # cross_globals = [__name__, settings, logger, driver]\n\n if len(songs) != 0:\n logger.log(str(len(songs)) + \" items found in songlist.txt. Attempting to download\")\n count = 0\n total = len(songs)\n logger.close()\n for song in songs:\n # Initialize the shared state variable that will be shared with the following subprocess \"sub\"\n skipped = Value(ctypes.c_bool, True)\n\n # Start Grab as a subprocess\n sub = multiprocessing.Process(target=Grabber.grab, args=(settings, song, skipped))\n sub.start()\n sub.join(90)\n\n try:\n logger = Logger(open(settings['log'], 'a'))\n except:\n pass\n\n # Terminate thread if it is still alive after the 90 second timeout\n if sub.is_alive() and skipped.value:\n sub.terminate()\n sub.join()\n logger = \"\"\n try:\n logger = Logger(open(settings['log'], 'a'))\n except:\n logger.close()\n logger = Logger(open(settings['log'], 'a'))\n message = \"Stalled trying to download \" + song + \". Skipping the current song.\"\n logger.log(message)\n elif skipped.value:\n message = \"The song was skipped due to an error.\"\n logger.log(message)\n else:\n message = \"The song was successfully downloaded.\"\n logger.log(message)\n count += 1\n songs.remove(song)\n logger.log(\"\")\n logger.flush()\n logger.log(\"Successfully downloaded \" + str(count) + \"/\" + str(total) + \" songs.\")\n else:\n logger.log(\"No items found in songlist.txt. Terminating program\")\n", "sub_path": "musicgrabber/Wrapper.py", "file_name": "Wrapper.py", "file_ext": "py", "file_size_in_byte": 4029, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "IO.initialize", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 29, "usage_type": "call"}, {"api_name": "os.path", "line_number": 29, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 30, "usage_type": "call"}, {"api_name": "os.path", "line_number": 30, "usage_type": "attribute"}, {"api_name": "IO.Logger", "line_number": 34, "usage_type": "call"}, {"api_name": "IO.SongList", "line_number": 35, "usage_type": "call"}, {"api_name": "atexit.register", "line_number": 49, "usage_type": "call"}, {"api_name": "multiprocessing.Value", "line_number": 62, "usage_type": "call"}, {"api_name": "ctypes.c_bool", "line_number": 62, "usage_type": "attribute"}, {"api_name": "multiprocessing.Process", "line_number": 65, "usage_type": "call"}, {"api_name": "Grabber.grab", "line_number": 65, "usage_type": "attribute"}, {"api_name": "IO.Logger", "line_number": 70, "usage_type": "call"}, {"api_name": "IO.Logger", "line_number": 80, "usage_type": "call"}, {"api_name": "IO.Logger", "line_number": 83, "usage_type": "call"}]}
+{"seq_id": "296505682", "text": "from selenium import webdriver\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.chrome.options import Options\r\n\r\nchrome_driver_path = \"C:/Users/ADMIN/Documents/KiemThu/chromedriver.exe\"\r\nchrome_options = Options()\r\n\r\nchrome_options.add_argument(\"--window-size=500,500\")\r\n\r\ndriver = webdriver.Chrome(chrome_driver_path, chrome_options=chrome_options)\r\n\r\ndriver.get(\"http://practice.automationtesting.in/\")\r\n# get current url\r\nprint(driver.page_source)\r\n\r\ndriver.quit()", "sub_path": "Bai6.py", "file_name": "Bai6.py", "file_ext": "py", "file_size_in_byte": 492, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "selenium.webdriver.chrome.options.Options", "line_number": 6, "usage_type": "call"}, {"api_name": "selenium.webdriver.Chrome", "line_number": 10, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 10, "usage_type": "name"}]}
+{"seq_id": "192983286", "text": "from bs4 import BeautifulSoup\nfrom urllib.request import Request, urlopen\nfrom urllib.error import HTTPError,URLError\nimport requests\nimport subprocess\nimport pickle\nimport argparse\nimport json\nimport threading\nimport sys\n\n# class crawlingThread (threading.Thread):\n# def __init__(self, url, movies_data):\n# threading.Thread.__init__(self)\n# self.url = url\n# self.movies_data = movies_data\n# #self.counter = counter\n# def run(self):\n# print(\"Starting \", url)\n# # Acquire lock to synchronize thread\n# #threadLock.acquire()\n# update_movie_list(self.url, self.movies_data)\n# # Release lock for the next thread\n# #threadLock.release()\n# #print \"Exiting \" + self.name\n\n\n# # Returns all movies and it's page url\n# def update_movie_list(url, movies_data):\n# cont = requests.get(url)\n\n# if cont.status_code == 200:\n# soup = BeautifulSoup(cont.content, 'html.parser')\n# movielinks = soup.find_all(\"a\", class_=\"movielink\")\n\n# import pdb\n# pdb.set_trace()\n\n# for movie in movielinks:\n# movies_data.append((movie.string, movie['href']))\n\n# print('nice')\n\n\nclass myThread (threading.Thread):\n def __init__(self, movie, movies):\n threading.Thread.__init__(self)\n self.movie = movie\n self.movies = movies\n #self.counter = counter\n def run(self):\n #print(\"Starting \", self.movie)\n # Acquire lock to synchronize thread\n #threadLock.acquire()\n update_movies_torrent_url(self.movie, self.movies)\n # Release lock for the next thread\n #threadLock.release()\n #print \"Exiting \" + self.name\n\n\n# Returns all movies and it's torrent url\ndef update_movies_torrent_url(movie, movies):\n #print(url)\n cont = requests.get(movie[1])\n\n if cont.status_code == 200:\n soup = BeautifulSoup(cont.content, 'html.parser')\n torrent_urls = soup.find_all('a', id=\"dt\")\n movies[movie[0]] = torrent_urls[0]['href']\n\n\n# Returns all movies and it's page url\ndef get_movie_list(url):\n cont = requests.get(url)\n\n if cont.status_code == 200:\n soup = BeautifulSoup(cont.content, 'html.parser')\n movielinks = soup.find_all(\"a\", class_=\"movielink\")\n\n movies_data = []\n for movie in movielinks:\n movies_data.append((movie.string, movie['href']))\n\n return movies_data\n\n\n# Saves torrent file of from given url\ndef get_movie_torrent(url):\n torrent_file = url.rsplit('/', 1)[1]\n print(\"downloading \", url)\n try:\n #headers = { 'User-Agent': 'Mozilla/5.0' }\n r = requests.get(url, headers='', stream=True)\n with open(torrent_file, 'wb') as f:\n for chunk in r.iter_content(chunk_size=32*1024):\n if chunk:\n f.write(chunk)\n f.flush()\n except requests.exceptions.RequestException as e:\n print('\\n' + OutColors.LR + str(e))\n sys.exit(1);\n\n\ndef search_movie(movie_name, movies):\n # Look for exact movie name match\n if movie_name in movies:\n print('Movie Name:{0}'.format(movie_name))\n print('Movie Torrent:{0}'.format(movies[movie_name]))\n return\n\n # Look for movie name as a keyword in list of movies (keys)\n movie_list = list(movies.keys())\n movies_found = [movie for movie in movie_list if movie_name.lower() in movie.lower()]\n\n return movies_found\n #for movie in movies_found:\n #print('Found:{0} - {1}'.format(movie, movies[movie]))\n\n\nif __name__ == '__main__':\n\n movie_resolution = '1080p'\n pages = 200\n # movies read from movies.json\n movies = {}\n #threadLock = threading.Lock()\n\n movie_name = ''\n\n parser = argparse.ArgumentParser(description='Happy Movie Watching!')\n parser.add_argument('-m', help='provide movie name')\n parser.add_argument('-u', help='update movies')\n parser.add_argument('--resolution', help='provide movie resolution')\n\n args = parser.parse_args()\n\n if args.m:\n movie_name = args.m\n\n if args.resolution:\n movie_resolution = args.resolution\n\n try:\n with open('movies.json', 'r') as f:\n movies = json.load(f)\n except IOError as e:\n print(\"warning: 'movies.json' not found\")\n\n if movie_name:\n print('Searching for {0}...'.format(movie_name))\n found_movies = search_movie(movie_name, movies)\n for count, movie in enumerate(found_movies):\n print('{0} - {1} ### {2}'.format(count +1 , movie, movies[movie]))\n sys.exit()\n\n movies_data = []\n #crawling_threads = []\n for page in list(range(1, pages+1)):\n url = 'https://yifymovie.re/search/0/{0}/All/0/latest/60/page/{1}/'.format(movie_resolution, page)\n\n # Get the list of tuples (movie name, url which contains link to torrent file)\n\n #threads_id = crawlingThread(url, movies_data)\n #threads_id.start()\n #threads_id.join()\n #crawling_threads.append(threads_id)\n movies_per_page = get_movie_list(url)\n print('Crawling {0} - {1} movies'.format(url, len(movies_per_page)))\n if not movies_per_page:\n print(\"Crawling is done.\")\n break\n\n movies_data += movies_per_page;\n #print(movies_data)\n\n #for thread in crawling_threads:\n #thread.join()\n\n data_len = len(movies_data)\n threads = []\n for count, movie in enumerate(movies_data):\n if movie[0] not in movies:\n print(\"Retrieving torrent url {0}/{1} - {2}...\".format(count+1, data_len, movie[0]))\n threads_id = myThread(movie, movies)\n threads_id.start()\n threads.append(threads_id)\n\n for thread in threads:\n thread.join()\n\n # we found new movies from website\n if movies:\n try:\n print(\"Saving {0} movies in movies.json...\".format(len(movies)))\n with open('movies.json', 'w') as f:\n json.dump(movies, f)\n except IOError as e:\n print(\"warning:failed to dump 'movies.json'\")\n\n #import pdb\n #pdb.set_trace()", "sub_path": "GetMovies.py", "file_name": "GetMovies.py", "file_ext": "py", "file_size_in_byte": 6135, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "threading.Thread", "line_number": 45, "usage_type": "attribute"}, {"api_name": "threading.Thread.__init__", "line_number": 47, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 47, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 64, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 67, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 74, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 77, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 93, "usage_type": "call"}, {"api_name": "requests.exceptions", "line_number": 99, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 101, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 130, "usage_type": "call"}, {"api_name": "json.load", "line_number": 145, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 154, "usage_type": "call"}, {"api_name": "json.dump", "line_number": 196, "usage_type": "call"}]}
+{"seq_id": "488603402", "text": "from multiprocessing.connection import Listener\nfrom mss import mss\nimport pickle\nimport socket\n\n\nif __name__ == '__main__':\n localIP = socket.gethostbyname(socket.gethostname())\n print(\"local ip : \",localIP)\n s = Listener((localIP,58888))\n while True:\n\n conn = s.accept()\n print('Accept a new connection')\n\n conn.send(pickle.dumps(mss().shot()))\n conn.close()\n print('Closed the connection')\n", "sub_path": "work/sceencapture/server.py", "file_name": "server.py", "file_ext": "py", "file_size_in_byte": 440, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "socket.gethostbyname", "line_number": 8, "usage_type": "call"}, {"api_name": "socket.gethostname", "line_number": 8, "usage_type": "call"}, {"api_name": "multiprocessing.connection.Listener", "line_number": 10, "usage_type": "call"}, {"api_name": "pickle.dumps", "line_number": 16, "usage_type": "call"}, {"api_name": "mss.mss", "line_number": 16, "usage_type": "call"}]}
+{"seq_id": "603261004", "text": "#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport codecs\r\nimport simplejson\r\nimport sys\r\n\r\n\r\nclass TagsFile:\r\n def __init__(self, filenameorlist):\r\n if isinstance(filenameorlist, list):\r\n self.tracks = filenameorlist\r\n else:\r\n with open(filenameorlist) as tags:\r\n tagsjson = simplejson.load(tags)\r\n self._process_saturated_tags(tagsjson)\r\n\r\n def _process_saturated_tags(self, tagsjson):\r\n self.tracks = []\r\n saturated_tags = {}\r\n\r\n for track in tagsjson:\r\n for tag_field, value in track.iteritems():\r\n if value == []:\r\n # This is, strangely, how the M-TAGS format erases values\r\n del saturated_tags[tag_field]\r\n else:\r\n saturated_tags[tag_field] = value\r\n\r\n self.tracks.append(saturated_tags.copy())\r\n\r\n def desaturate(self):\r\n desaturated = []\r\n if self.tracks:\r\n last_saturated_tags = {}\r\n for track in self.tracks:\r\n current_desaturated = {}\r\n for tag_field, value in track.iteritems():\r\n if tag_field in last_saturated_tags:\r\n if value != last_saturated_tags[tag_field]:\r\n current_desaturated[tag_field] = value\r\n else:\r\n current_desaturated[tag_field] = value\r\n for tag_field, value in last_saturated_tags.iteritems():\r\n if tag_field not in track:\r\n current_desaturated[tag_field] = []\r\n last_saturated_tags = track\r\n desaturated.append(current_desaturated)\r\n return desaturated\r\n\r\n def write(self, filename):\r\n with codecs.open(filename, 'w', encoding='utf-8-sig') as fp:\r\n simplejson.dump(self.desaturate(), fp,\r\n ensure_ascii=False, sort_keys=True, indent=3, separators=(',', ' : '))\r\n fp.write('\\n')\r\n", "sub_path": "ExtractFeatures/Data/euphonogenizer/mtags.py", "file_name": "mtags.py", "file_ext": "py", "file_size_in_byte": 1756, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "simplejson.load", "line_number": 15, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 52, "usage_type": "call"}, {"api_name": "simplejson.dump", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "220565718", "text": "# -*- coding: utf-8 -*-\n\n# -----------------------------------------------\n# インポート\n# -----------------------------------------------\nimport pygame\nfrom obj.obj import ObjBase\n\n# -----------------------------------------------\n# 定義\n# -----------------------------------------------\n# 獲得スコア\nscore = 100\n\n# オブジェクトスピード\nobjSpeed = 10\n\n# -----------------------------------------------\n# 星表示\n# -----------------------------------------------\nclass Star(ObjBase):\n def __init__(self, parent, x, y, player):\n super().__init__(parent, player, score, 'img/obj/star.png', 'se/switch1.wav')\n \n # 初期位置\n self.rect.center = (x, y)\n\n # 初期回転角度\n self.angl = 0\n\n # アプデ時に表示するサーフェスとその位置\n def DrawnSur(self):\n r = self.rect\n self.angl += 10\n \n # 一旦一時サーフェスに書き出し\n temp = pygame.Surface((r.width, r.height), pygame.SRCALPHA)\n temp.blit(self.sur, (0, 0))\n\n # 回転\n temp = pygame.transform.rotate(temp, self.angl)\n\n # 回転でレクトが変わるので補正\n ofstX = (r.width - temp.get_width()) / 2\n ofstY = (r.height - temp.get_height()) / 2\n r.x -= objSpeed\n\n # 書き出すサーフェスと位置を返す\n return temp, ((r.x + ofstX, r.y + ofstY))\n\n# -----------------------------------------------\n# 単体テスト\n# -----------------------------------------------\nif __name__ == '__main__':\n # 初期化\n pygame.init()\n pygame.mixer.init()\n\n # 画面生成\n pygame.display.set_mode((800, 600), 0, 32)\n screen = pygame.display.get_surface()\n pygame.display.set_caption('Star')\n\n class Dummy():\n def __init__(self):\n self.rect = pygame.Rect(0,0,1,1)\n self.score = 0\n dum = Dummy()\n star = Star(screen, 400, 300, dum, dum.score)\n\n while True:\n star.Update()\n \n ", "sub_path": "obj/star.py", "file_name": "star.py", "file_ext": "py", "file_size_in_byte": 2006, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "obj.obj.ObjBase", "line_number": 21, "usage_type": "name"}, {"api_name": "pygame.Surface", "line_number": 37, "usage_type": "call"}, {"api_name": "pygame.SRCALPHA", "line_number": 37, "usage_type": "attribute"}, {"api_name": "pygame.transform.rotate", "line_number": 41, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 41, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.mixer.init", "line_number": 57, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 57, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 60, "usage_type": "attribute"}, {"api_name": "pygame.display.get_surface", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 62, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 62, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 66, "usage_type": "call"}]}
+{"seq_id": "62145308", "text": "import streamlit as st\r\n\r\nfrom Pages.feature_analysis_page import FeatureAnalysisPage\r\nfrom Pages.introduction_page import IntroductionPage\r\nfrom Pages.models_analysis_page import ModelsAnalysisPage\r\nfrom Pages.predictor_page import PredictorPage\r\n\r\n# to run:\r\nfrom Pages.university_rating_analysis import UniversityRatingAnalysisPage\r\n\r\nif __name__ == '__main__':\r\n st.sidebar.title(\"Graduate Admission Prediction\")\r\n menu = st.sidebar.radio('Navigation', ('Introduction', \"Feature Analysis\", \"Models Analysis\",\r\n \"University Rating Analysis\",\"Predictor\"))\r\n st.sidebar.title(\"Details\")\r\n st.sidebar.info(\r\n \"Author: Zvi Berger and Liel Shuker\")\r\n st.sidebar.info(\r\n \"This Project is based on the paper - 'A Comparison of Regression Models for Predicting Graduate Admission'\")\r\n st.sidebar.info(\r\n \"[The paper](https://drive.google.com/file/d/17su4WNKIwrOA5WUXXS3qIPStu3eLfEfv/view?usp=sharing)\")\r\n st.sidebar.info(\r\n \"[Kaggle Dataset](https://www.kaggle.com/mohansacharya/datasets)\")\r\n st.sidebar.info(\"[Presentation](https://drive.google.com/file/d/1ZDnPhr3IassR4w9k2XWj2hxxtXuPciyS/view?usp=sharing)\")\r\n st.sidebar.info(\"[Github](https://github.com/BergerZvika/Data-Analysis-university-rating-prediction)\")\r\n\r\n introduction = IntroductionPage()\r\n feature_analysis = FeatureAnalysisPage()\r\n predictor = PredictorPage()\r\n models_analysis = ModelsAnalysisPage()\r\n university_rating = UniversityRatingAnalysisPage()\r\n\r\n if menu == 'Introduction':\r\n introduction.show_page()\r\n\r\n if menu == 'Feature Analysis':\r\n feature_analysis.show_page()\r\n\r\n if menu == 'Predictor':\r\n predictor.show_page()\r\n\r\n if menu == \"Models Analysis\":\r\n models_analysis.show_page()\r\n\r\n if menu == \"University Rating Analysis\":\r\n university_rating.show_page()\r\n\r\n\r\n\r\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 1902, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "streamlit.sidebar.title", "line_number": 12, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 12, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.radio", "line_number": 13, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 13, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.title", "line_number": 15, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 15, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 16, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 16, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 18, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 18, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 20, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 20, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 22, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 22, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 24, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 24, "usage_type": "attribute"}, {"api_name": "streamlit.sidebar.info", "line_number": 25, "usage_type": "call"}, {"api_name": "streamlit.sidebar", "line_number": 25, "usage_type": "attribute"}, {"api_name": "Pages.introduction_page.IntroductionPage", "line_number": 27, "usage_type": "call"}, {"api_name": "Pages.feature_analysis_page.FeatureAnalysisPage", "line_number": 28, "usage_type": "call"}, {"api_name": "Pages.predictor_page.PredictorPage", "line_number": 29, "usage_type": "call"}, {"api_name": "Pages.models_analysis_page.ModelsAnalysisPage", "line_number": 30, "usage_type": "call"}, {"api_name": "Pages.university_rating_analysis.UniversityRatingAnalysisPage", "line_number": 31, "usage_type": "call"}]}
+{"seq_id": "258406729", "text": "from django.core.mail import send_mail\nimport requests\nfrom urllib import quote_plus\nfrom datetime import datetime\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nfrom artist.models import Artist, ArtistRating\nfrom event.models import Event\n\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n for artist in Artist.objects.all():\n url = u'http://api.bandsintown.com/artists/{}/events.json?api_version=2.0&app_id=liveinconvert'\\\n .format(quote_plus(artist.name.encode('utf-8')))\n\n ret = requests.get(url)\n if ret.status_code != 200:\n continue\n\n data = ret.json()\n if type(data) == dict:\n continue\n\n for event in data:\n if event['venue']['country'] != 'Switzerland':\n continue\n\n event_obj, created = Event.objects.update_or_create(bandsintown_id=event['id'], defaults={\n 'name': event['title'],\n 'artist': artist,\n 'location': event['venue']['name'],\n 'date_time': datetime.strptime(event['datetime'], '%Y-%m-%dT%H:%M:%S'),\n 'bandsintown_id': event['id'],\n })\n\n if created:\n for rating in artist.artistrating_set.filter(rating=ArtistRating.LIKE):\n send_mail(u'New Concert for {}'.format(artist.name),\n u'{} {} {}'.format(event_obj.name, event_obj.artist, event_obj.date_time),\n settings.EMAIL_SENDER, [rating.user.email], fail_silently=False)\n", "sub_path": "event/management/commands/bandsintown.py", "file_name": "bandsintown.py", "file_ext": "py", "file_size_in_byte": 1699, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 14, "usage_type": "name"}, {"api_name": "artist.models", "line_number": 16, "usage_type": "name"}, {"api_name": "artist.models.Artist.objects.all", "line_number": 16, "usage_type": "call"}, {"api_name": "artist.models.Artist.objects", "line_number": 16, "usage_type": "attribute"}, {"api_name": "artist.models.Artist", "line_number": 16, "usage_type": "name"}, {"api_name": "urllib.quote_plus", "line_number": 18, "usage_type": "call"}, {"api_name": "artist.models.name.encode", "line_number": 18, "usage_type": "call"}, {"api_name": "artist.models.name", "line_number": 18, "usage_type": "attribute"}, {"api_name": "artist.models", "line_number": 18, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 20, "usage_type": "call"}, {"api_name": "event.models", "line_number": 28, "usage_type": "name"}, {"api_name": "event.models", "line_number": 29, "usage_type": "name"}, {"api_name": "event.models.Event.objects.update_or_create", "line_number": 32, "usage_type": "call"}, {"api_name": "event.models.Event.objects", "line_number": 32, "usage_type": "attribute"}, {"api_name": "event.models.Event", "line_number": 32, "usage_type": "name"}, {"api_name": "event.models", "line_number": 32, "usage_type": "name"}, {"api_name": "event.models", "line_number": 33, "usage_type": "name"}, {"api_name": "artist.models", "line_number": 34, "usage_type": "name"}, {"api_name": "event.models", "line_number": 35, "usage_type": "name"}, {"api_name": "datetime.datetime.strptime", "line_number": 36, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 36, "usage_type": "name"}, {"api_name": "event.models", "line_number": 36, "usage_type": "name"}, {"api_name": "event.models", "line_number": 37, "usage_type": "name"}, {"api_name": "artist.models.artistrating_set.filter", "line_number": 41, "usage_type": "call"}, {"api_name": "artist.models.artistrating_set", "line_number": 41, "usage_type": "attribute"}, {"api_name": "artist.models", "line_number": 41, "usage_type": "name"}, {"api_name": "artist.models.ArtistRating.LIKE", "line_number": 41, "usage_type": "attribute"}, {"api_name": "artist.models.ArtistRating", "line_number": 41, "usage_type": "name"}, {"api_name": "django.core.mail.send_mail", "line_number": 42, "usage_type": "call"}, {"api_name": "artist.models.name", "line_number": 42, "usage_type": "attribute"}, {"api_name": "artist.models", "line_number": 42, "usage_type": "name"}, {"api_name": "django.conf.settings.EMAIL_SENDER", "line_number": 44, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 44, "usage_type": "name"}]}
+{"seq_id": "486741880", "text": "import matplotlib.pyplot as plt\n\n\ndef linspace(start, stop, num):\n return [start + (stop - start) / (num - 1) * k for k in range(num)]\n\n\ndef zeros(rows, cols):\n return [[0 for j in range(cols)] for i in range(rows)]\n\n\nd = 100 # Pixel density \nn = 32 # Maximum number of iterations\nmaxN = -1\n\nx = linspace(-2.5, 1.5, 4 * d + 1)\ny = linspace(-1.5, 1.5, 3 * d + 1)\n\nT = zeros(len(y), len(x))\n\nfor i, b in enumerate(y):\n for j, a in enumerate(x):\n # Mandelbrot set: c(a, b), z(0, 0)\n c = complex(a, b)\n z = complex(0, 0)\n \n # Julia Set: Constant c, z(a,b)\n # c = complex('(0.285+0.01j)')\n # c = complex('(-0.8+0.156j)')\n # z = complex(a, b)\n for k in range(n):\n z = z * z + c\n if complex.__abs__(z) >= 2:\n T[i][j] = k + 1\n if k > maxN:\n maxN = k\n break\n\nplt.imshow(T, cmap=plt.cm.twilight_shifted)\nplt.show()\n#plt.savefig('mandelbrot.png', dpi=200)\nprint('maxN = {}'.format(maxN))", "sub_path": "mandelbrot/mandelbrotComplex.py", "file_name": "mandelbrotComplex.py", "file_ext": "py", "file_size_in_byte": 1034, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.pyplot.imshow", "line_number": 39, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 39, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 39, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.show", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}]}
+{"seq_id": "438305222", "text": "import numpy as np\nimport os\nimport pytest\nimport subprocess\n\nfrom karabo_data.utils import QuickView\n\n\ndef test_summary_on_data_file():\n testdatapath = \"data/example_data/R0126-AGG01-S00002.h5\"\n if os.path.exists(testdatapath):\n # next line assumes that the have installed the package\n output = str(subprocess.check_output(\"euxfel_h5tool.py {}\".format(\n testdatapath), shell=True))\n print(output)\n assert \"Size: 665.596177 MB\" in output\n assert \"Entries: 10\" in output\n assert \"First Train: 1362168960\" in output\n else:\n pytest.skip(\"test data file not available ()\".format(testdatapath))\n\n\ndef test_cbf_conversion():\n testdatapath = \"data/example_data/R0126-AGG01-S00002.h5\"\n if os.path.exists(testdatapath):\n # Test that the help message pops up when the command is malformed\n command = \"euxfel_h5tool.py convert-cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert \"Usage:\" in output\n\n # Test that the cbf file is correctly created for index 0\n command = (\"euxfel_h5tool.py convert-cbf {}\"\n \"0 out.cbf\".format(testdatapath))\n expected_output = \"Convert {} index 0 to out.cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test that the cbf file is correctly created for an arbitrary index\n command = (\"euxfel_h5tool.py convert-cbf {}\"\n \"42 out.cbf\".format(testdatapath))\n expected_output = \"Convert {} index 42 to out.cbf\".format(testdatapath)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test graceful fail for inexisting file\n command = \"euxfel_h5tool.py convert-cbf non_existing_data.h5 0 out.cbf\"\n expected_output = \"non_exisiting_data.h5: Could not be opened.\"\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output == output\n\n # Test graceful fail for index out of range\n maxint_64 = 9223372036854775808\n command = (\"euxfel_h5tool.py convert-cbf non_existing_data.h5\"\n \"{} out.cbf\".format(maxint_64))\n expected_output = \"Index ({}) out of range\".format(maxint_64)\n output = str(subprocess.check_output(command), shell=True)\n print(output)\n assert expected_output in output\n\n # Clean up\n os.remove(\"out.cbf\")\n\n else:\n pytest.skip(\"test data file not available ()\".format(testdatapath))\n\n\ndef test_init_quick_view():\n qv = QuickView()\n\n assert qv.data is None\n qv.data = np.empty((1,1,1), dtype=np.int8)\n assert len(qv) == 1\n assert qv.pos == 0\n\n with pytest.raises(TypeError) as info:\n qv.data = 4\n\n with pytest.raises(TypeError) as info:\n qv.data = np.empty((1,1,1,1), dtype=np.int8)\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-v\"])\n print(\"Run 'py.test -v -s' to see more output\")\n", "sub_path": "karabo_data/tests/test_utils.py", "file_name": "test_utils.py", "file_ext": "py", "file_size_in_byte": 3153, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.exists", "line_number": 11, "usage_type": "call"}, {"api_name": "os.path", "line_number": 11, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 13, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 28, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 36, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 44, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 51, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 60, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 65, "usage_type": "call"}, {"api_name": "pytest.skip", "line_number": 68, "usage_type": "call"}, {"api_name": "karabo_data.utils.QuickView", "line_number": 72, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 75, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 79, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 82, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 83, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 83, "usage_type": "attribute"}, {"api_name": "pytest.main", "line_number": 87, "usage_type": "call"}]}
+{"seq_id": "483113793", "text": "import requests\r\nimport pygal\r\nfrom pygal.style import LightColorizedStyle as LCS, LightenStyle as LS\r\n# 执行API调用并存储响应\r\n# 将响应对象存储在r中\r\nURL = 'https://api.github.com/search/repositories?q=language:python&sort=star'\r\nr = requests.get(URL)\r\n\r\n\r\n# 状态码为200表示请求成功\r\ndef get_status_code(r):\r\n \"\"\"r是一个响应对象\"\"\"\r\n return r.status_code\r\n\r\n\r\nprint(\"Status code:\", get_status_code(r))\r\nresponse_dict = r.json()\r\nprint(\"Total repositories:\", response_dict['total_count'])\r\n\r\n# 研究有关仓库的信息,所有仓库在items对应的值里,也是一个一个字典\r\nrepo_dicts = response_dict['items']\r\nprint(\"Number of items:\", len(repo_dicts))\r\nnames = [repo_dict['name'] for repo_dict in repo_dicts]\r\nstars = [repo_dict['stargazers_count'] for repo_dict in repo_dicts]\r\n\r\n# 定制图标外观(改进)\r\nmy_config = pygal.Config()\r\nmy_config.x_label_rotation = 45\r\nmy_config.show_legend = False\r\nmy_config.title_font_size = 24\r\nmy_config.label_font_size = 14 # 副标签\r\nmy_config.major_label_font_size = 18 # 主标签\r\nmy_config.truncate_label = 15 # 将较长的项目名缩短为15个字符\r\nmy_config.show_y_guides = False\r\nmy_config.width = 1000\r\n# 可视化\r\nmy_style = LS('#333366', base_style=LCS)\r\n# chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)\r\nchart = pygal.Bar(my_config, style=my_style)\r\nchart.title = 'Most-Starred Python Projects on GitHub'\r\nchart.x_labels = names\r\n\r\n# 自定义工具提示标签,根据value生成高度\r\nplot_dicts = []\r\nfor repo_dict in repo_dicts:\r\n if repo_dict['description'] != None:\r\n plot_dict = {'value': repo_dict['stargazers_count'],\r\n 'label': repo_dict['description'],\r\n 'xlink': repo_dict['html_url'],\r\n }\r\n else:\r\n plot_dict = {'value': repo_dict['stargazers_count'],\r\n 'label': \"No information\",\r\n 'xlink': repo_dict['html_url'],\r\n }\r\n plot_dicts.append(plot_dict)\r\n\r\n\r\nchart.add('', plot_dicts)\r\nchart.render_to_file('python_repos.svg')", "sub_path": "python_work/DataVisualizaton/API/python_repos.py", "file_name": "python_repos.py", "file_ext": "py", "file_size_in_byte": 2132, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 7, "usage_type": "call"}, {"api_name": "pygal.Config", "line_number": 27, "usage_type": "call"}, {"api_name": "pygal.style.LightenStyle", "line_number": 37, "usage_type": "call"}, {"api_name": "pygal.style.LightColorizedStyle", "line_number": 37, "usage_type": "name"}, {"api_name": "pygal.Bar", "line_number": 39, "usage_type": "call"}]}
+{"seq_id": "104531696", "text": "\"\"\"Steps for features of Onezone login page.\n\"\"\"\n__author__ = \"Jakub Liput\"\n__copyright__ = \"Copyright (C) 2016 ACK CYFRONET AGH\"\n__license__ = \"This software is released under the MIT license cited in \" \\\n \"LICENSE.txt\"\n\nimport re\nfrom selenium.webdriver.support.ui import WebDriverWait as wait\nfrom pytest_bdd import given, when, then, parsers\nfrom tests.utils.acceptance_utils import list_parser\nfrom pytest_selenium_multi.pytest_selenium_multi import select_browser\n\n\n@given(parsers.re(\"users? of (?P.*) opened Onezone URL\"))\ndef g_visit_onezone(base_url, selenium, browser_id_list):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n oz_url = base_url\n driver.get(oz_url)\n\n\n@then(parsers.parse('user of {browser_id} should see login button '\n 'for {provider_name}'))\ndef login_provider_buttons(selenium, browser_id, provider_name):\n driver = select_browser(selenium, browser_id)\n assert driver.find_element_by_css_selector(\n '.login-box a.login-icon-box.{name}'.format(name=provider_name)\n )\n\n\ndef _click_login_provider_button(driver, provider_name):\n driver.find_element_by_css_selector(\n '.login-box a.login-icon-box.{:s}'.format(provider_name)\n ).click()\n\n\n@given(parsers.re('users? of (?P.*) clicked on the '\n '\"(?P.*)\" login button'))\ndef g_click_login_provider_button(selenium, browser_id_list, provider_name):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n _click_login_provider_button(driver, provider_name)\n\n\n@when(parsers.re('users? of (?P.*) clicks on the '\n '\"(?P.*)\" login button'))\ndef w_click_login_provider_button(selenium, browser_id_list, provider_name):\n for browser_id in list_parser(browser_id_list):\n driver = select_browser(selenium, browser_id)\n _click_login_provider_button(driver, provider_name)\n\n\n@then(parsers.re('user of (?P.+) should be '\n 'redirected to (?P.+) page'))\ndef being_redirected_to_page(page, selenium, browser_id):\n driver = select_browser(selenium, browser_id)\n wait(driver, 5).until(lambda s: re.match(r'https?://.*?(/#)?(/.*)', s.current_url).group(2) == page)\n\n\n@given(parsers.re('users? of (?P.*) logged '\n 'as (?P.*)'))\ndef log_to_user_in_each_browser(selenium, browser_id_list,\n user_id_list):\n for browser_id, user_id in zip(list_parser(browser_id_list),\n list_parser(user_id_list)):\n driver = select_browser(selenium, browser_id)\n driver.find_element_by_link_text(user_id).click()\n", "sub_path": "tests/gui/steps/onezone_before_login.py", "file_name": "onezone_before_login.py", "file_ext": "py", "file_size_in_byte": 2845, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "tests.utils.acceptance_utils.list_parser", "line_number": 17, "usage_type": "call"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 18, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 18, "usage_type": "argument"}, {"api_name": "pytest_bdd.given", "line_number": 15, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.re", "line_number": 15, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 15, "usage_type": "name"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 26, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 26, "usage_type": "argument"}, {"api_name": "pytest_bdd.then", "line_number": 23, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.parse", "line_number": 23, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 23, "usage_type": "name"}, {"api_name": "tests.utils.acceptance_utils.list_parser", "line_number": 41, "usage_type": "call"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 42, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 42, "usage_type": "argument"}, {"api_name": "pytest_bdd.given", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.re", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 38, "usage_type": "name"}, {"api_name": "tests.utils.acceptance_utils.list_parser", "line_number": 49, "usage_type": "call"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 50, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 50, "usage_type": "argument"}, {"api_name": "pytest_bdd.when", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.re", "line_number": 46, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 46, "usage_type": "name"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 57, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 57, "usage_type": "argument"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 58, "usage_type": "call"}, {"api_name": "re.match", "line_number": 58, "usage_type": "call"}, {"api_name": "pytest_bdd.then", "line_number": 54, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.re", "line_number": 54, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 54, "usage_type": "name"}, {"api_name": "tests.utils.acceptance_utils.list_parser", "line_number": 65, "usage_type": "call"}, {"api_name": "tests.utils.acceptance_utils.list_parser", "line_number": 66, "usage_type": "call"}, {"api_name": "pytest_selenium_multi.pytest_selenium_multi.select_browser", "line_number": 67, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.ui", "line_number": 67, "usage_type": "argument"}, {"api_name": "pytest_bdd.given", "line_number": 61, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers.re", "line_number": 61, "usage_type": "call"}, {"api_name": "pytest_bdd.parsers", "line_number": 61, "usage_type": "name"}]}
+{"seq_id": "223452271", "text": "import pytest\nfrom flask import jsonify\n\nfrom apistrap import Swagger\nfrom apistrap.errors import SwaggerExtensionError\n\n\ndef test_swagger_extension_definition_conflict():\n with pytest.raises(ValueError):\n swagger = Swagger()\n swagger.add_definition(\"name\", {\"foo\": \"bar\"})\n swagger.add_definition(\"name\", {\"baz\": \"bar\"})\n\n\ndef test_getters():\n swagger = Swagger()\n swagger.title = \"Title\"\n swagger.description = \"Description\"\n assert swagger.title == \"Title\"\n assert swagger.description == \"Description\"\n\n\ndef test_spec_url(app, client):\n swagger = Swagger()\n\n swagger.spec_url = \"/myspecurl.json\"\n assert swagger.spec_url == \"/myspecurl.json\"\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/myspecurl.json\")\n assert response.status_code == 200\n assert \"paths\" in response.json\n\n\ndef test_spec_url_reset(app, client):\n swagger = Swagger()\n\n swagger.spec_url = None\n assert swagger.spec_url is None\n\n swagger.spec_url = \"/myspecurl.json\"\n assert swagger.spec_url == \"/myspecurl.json\"\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/myspecurl.json\")\n assert response.status_code == 200\n assert \"paths\" in response.json\n\n\ndef test_spec_url_cannot_be_set_after_init(app):\n swagger = Swagger(app)\n with pytest.raises(SwaggerExtensionError):\n swagger.spec_url = \"whatever\"\n\n\ndef test_disable_spec_url(app, client):\n swagger = Swagger()\n\n swagger.spec_url = None\n assert swagger.spec_url is None\n\n swagger.init_app(app)\n\n @app.route(\"/\")\n @swagger.autodoc()\n def view():\n return jsonify()\n\n response = client.get(\"/swagger.json\")\n assert response.status_code == 404\n\n\ndef test_disable_ui(app, client):\n swagger = Swagger()\n swagger.ui_url = None\n assert swagger.ui_url is None\n swagger.init_app(app)\n\n response = client.get(\"/apidocs/\")\n assert response.status_code == 404\n\n\ndef test_ui_url_cannot_be_set_after_init(app):\n swagger = Swagger(app)\n with pytest.raises(SwaggerExtensionError):\n swagger.ui_url = None\n\n\ndef test_set_ui_url(app, client):\n swagger = Swagger()\n\n swagger.ui_url = \"/docs/\"\n assert swagger.ui_url == \"/docs/\"\n\n swagger.init_app(app)\n\n response = client.get(\"/docs/\")\n assert response.status_code == 200\n", "sub_path": "tests/test_swagger_extension.py", "file_name": "test_swagger_extension.py", "file_ext": "py", "file_size_in_byte": 2478, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pytest.raises", "line_number": 9, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 10, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 16, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 24, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 34, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 42, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 55, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 63, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 64, "usage_type": "call"}, {"api_name": "apistrap.errors.SwaggerExtensionError", "line_number": 64, "usage_type": "argument"}, {"api_name": "apistrap.Swagger", "line_number": 69, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 79, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 86, "usage_type": "call"}, {"api_name": "apistrap.Swagger", "line_number": 96, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 97, "usage_type": "call"}, {"api_name": "apistrap.errors.SwaggerExtensionError", "line_number": 97, "usage_type": "argument"}, {"api_name": "apistrap.Swagger", "line_number": 102, "usage_type": "call"}]}
+{"seq_id": "270134370", "text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n#images are 28x28, (784px total)\n#pixel values are int from 0~255 indicating lightness or darkness\n\n#train dataset has 785 col. first col is label, digit drawn by the user\n#Rest of the col contain pixel-values of associated image\n#each pixel col has name like pexelx where x is from 0~783 inclusive.\n#\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n#params\ntraining_epochs = 1000\nbatch_size = 100\nlearning_rate = 0.001\nnode_n = 256\n\nnb_classes = 10\n\n#28 * 28 = 784\nX = tf.placeholder(tf.float32, [None, 784])\n# 0~9 digits, 10 classes\nY = tf.placeholder(tf.float32, [None, nb_classes])\n\n#layer1\nW1 = tf.Variable(tf.random_normal([784, node_n]))\nb1 = tf.Variable(tf.random_normal([node_n]))\nlayer1 = tf.nn.relu(tf.matmul(X, W1) + b1)\n\n#layer2\nW2 = tf.Variable(tf.random_normal([node_n, node_n]))\nb2 = tf.Variable(tf.random_normal([node_n]))\nlayer2 = tf.nn.relu(tf.matmul(layer1, W2) + b2)\n\n#layer3\nW3 = tf.Variable(tf.random_normal([node_n,10]))\nb3 = tf.Variable(tf.random_normal([nb_classes]))\n#Hypothesis using softmax\nhypothesis = (tf.matmul(layer2, W3) + b3)\n\n#cross-entropy of onehot Y\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=hypothesis, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n# testing\nis_correct = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y,1))\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\n\n\nwith tf.Session() as sess:\n #init TF variable\n sess.run(tf.global_variables_initializer())\n #training cycle\n for epoch in range(training_epochs):\n avg_cost = 0\n total_batch = int(mnist.train.num_examples / batch_size )\n\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n c, _ = sess.run([cost, optimizer], feed_dict={X: batch_xs, Y:batch_ys})\n avg_cost += c / total_batch\n print('Epoch:', '%04d' % (epoch + 1), 'cost = ', '{:.9f}'.format(avg_cost))\n\n #Creates batches of 100 because there is no need for all data to be on memory\n batch_xs, batch_ys = mnist.train.next_batch(100)\n\n print(\"acc: \", accuracy.eval(session=sess, feed_dict={X: mnist.test.images, Y: mnist.test.labels}))\n #predict 1 sample\n r = random.randint(0, mnist.test.num_examples-1)\n print(\"Label: \", sess.run(tf.argmax(mnist.test.labels[r:r + 1], 1)))\n print(\"prediction: \", sess.run(tf.argmax(hypothesis, 1), feed_dict={X: mnist.test.images[r:r + 1]}))\n\n plt.imshow( \n mnist.test.images[r:r + 1].reshape(28, 28),\n cmap='Greys',\n interpolation='nearest')\n plt.show()\n", "sub_path": "relu_mnist.py", "file_name": "relu_mnist.py", "file_ext": "py", "file_size_in_byte": 2777, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "tensorflow.examples.tutorials.mnist.input_data.read_data_sets", "line_number": 17, "usage_type": "call"}, {"api_name": "tensorflow.examples.tutorials.mnist.input_data", "line_number": 17, "usage_type": "name"}, {"api_name": "tensorflow.placeholder", "line_number": 28, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 35, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 35, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 38, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 39, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tensorflow.matmul", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 43, "usage_type": "call"}, {"api_name": "tensorflow.Variable", "line_number": 44, "usage_type": "call"}, {"api_name": "tensorflow.random_normal", "line_number": 44, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 46, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.nn.softmax_cross_entropy_with_logits", "line_number": 49, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 49, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 50, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 50, "usage_type": "attribute"}, {"api_name": "tensorflow.equal", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 53, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.cast", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 54, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 59, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 76, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 77, "usage_type": "call"}, {"api_name": "tensorflow.argmax", "line_number": 78, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 80, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 80, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 84, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 84, "usage_type": "name"}]}
+{"seq_id": "384511806", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nfrom GetDataLoaders import get_dataloaders, get_short_dataloaders\nfrom architectures.Resnets import resnet50_cifar as resnet50\nfrom architectures.ContrastiveLoss import ContrastiveLoss\nimport torch\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch import nn\nimport time\nfrom torch import optim\nfrom tqdm import tqdm\nfrom torch.optim.lr_scheduler import ExponentialLR\n\n\n# In[2]:\n\n\n'''\n# we skip the probs for now\ngama = 2.0\nwith open(os.path.join(\"./PUprobs\", 'prob.dat'), 'r') as file_input:\n train_prob_str = file_input.readlines()\n train_prob = [float(i_prob_str.rstrip('\\n')) for i_prob_str in train_prob_str]\n print(len(train_prob)/4.0)\n train_weight = [1.0 if 0==i%4 else 1-train_prob[i]**gama for i in range(len(train_prob))]\n'''\n\n\n# In[3]:\n\n\nuse_cuda = torch.cuda.is_available()\ndevice = \"cuda\" if use_cuda else \"cpu\"\nbatch_size = 32\nlr = 1e-3\n\nnum_epochs = 200\n'''\nmomentum = 0.9\nnesterov = True\nLambdas = {'CE':1.0, 'MSE':1.0, 'NCE':1.0}\nLUT_lr = [(90,0.01), (130,0.001), (190,0.0001), (210,0.00001), (230,0.0001), (245,0.00001)]\n'''\nweight_decay = 1e-6\nloaders = get_dataloaders('imagenet', batch_size=batch_size, num_workers=2, unsupervised=True, simclr=True)\ntau = 0.1\ngamma = 2\ndecay_lr = 1e-6\naccumulation_steps = 4 \n\n\n# In[4]:\n\n\n'''\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torchvision\n\n# functions to show an image\n\n\ndef imshow(img):\n img = img / 2 + 0.5 # unnormalize\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.show()\n\n\n# get some random training images\ndataiter = iter(loaders['train_loader'])\nimagesi, imagesj = dataiter.next()\n\n# show images\nimshow(torchvision.utils.make_grid(imagesi))\nimshow(torchvision.utils.make_grid(imagesj))\n'''\n\n\n# In[5]:\n\n\nfeature_net = resnet50(128).to(device)\noptimizer = optim.Adam(feature_net.parameters(), lr=lr, weight_decay=weight_decay)\nscheduler = ExponentialLR(optimizer, gamma=decay_lr)\n\n\nNetworks = {'feature':feature_net}\nOptimizers = {'feature':optimizer}\n\nContrastiveCriterion = ContrastiveLoss(tau=tau, normalize=True)\nCriterions = {'CE': nn.CrossEntropyLoss(reduction='none'), 'MSE':nn.MSELoss() }\n\n\n# In[6]:\n\n\nfeature_net\n\n\n# In[7]:\n\n\ndef train_validate(data_loader, epoch, train=True):\n \n mode = \"Train\" if train else \"Valid\"\n if train is True:\n for key in Networks:\n Networks[key].train()\n Networks[key].zero_grad()\n else:\n for key in Networks:\n Networks[key].eval()\n \n \n losses = {'mse':[], 'nce':[]}\n \n \n overallloss = None\n \n \n start_time = time.time()\n tqdm_bar = tqdm(data_loader)\n \n for batch_idx, batch in enumerate(tqdm_bar):\n datai, dataj = batch\n \n datai, dataj = datai.to(device), dataj.to(device)\n if train is False:\n with torch.no_grad():\n _, featuresi = Networks['feature'](datai)\n _, featuresj = Networks['feature'](dataj)\n loss_nce = ContrastiveCriterion(featuresi, featuresj)\n else:\n _, featuresi = Networks['feature'](datai)\n _, featuresj = Networks['feature'](dataj)\n loss_nce = ContrastiveCriterion(featuresi, featuresj)\n \n loss_nce = loss_nce / accumulation_steps\n\n if train is True:\n loss_nce.backward()\n if (batch_idx + 1) % accumulation_steps == 0:\n for key in Optimizers:\n Optimizers[key].step()\n Networks[key].zero_grad()\n\n #calculate rotation invariance by MSE\n with torch.no_grad():\n features_mean = featuresi + featuresj \n features_mean = torch.mul(features_mean, 0.5)\n loss_mse = Criterions['MSE'](featuresi, features_mean)\n loss_mse += Criterions['MSE'](featuresj, features_mean) \n \n losses['mse'].append(loss_mse.item())\n losses['nce'].append(loss_nce.item())\n tqdm_bar.set_description('{} Epoch: [{}] Loss: NCE {:.4f}, MSE {:.4f}'.format(mode, epoch, loss_nce.item(), loss_mse.item()))\n \n \n end_time = time.time()\n print(\"Time for epoch pass {}\".format(end_time-start_time))\n overallloss = {'mse': float(np.mean(losses['mse'])), 'nce':float(np.mean(losses['nce']))}\n print('{} set: Average loss: MSE {:.4f}, NT-Xent {:.4f}\\n'.format(mode, overallloss['mse'], overallloss['nce']))\n return overallloss\n\n\n\ndef run_main_loop(loaders, num_epochs, starting_epoch=1):\n writer = SummaryWriter('./logs/AlexNet_SimCLR')\n save_path = \"weights/AlexNet_Decoupling_Contrastive_SimCLR.pth\"\n best_loss = np.Inf\n for epoch in range(starting_epoch, starting_epoch+num_epochs):\n \n \n train_loss = train_validate(loaders['train_loader'], epoch, train=True)\n val_loss = train_validate(loaders['valid_loader'], epoch, train=False)\n scheduler.step()\n \n writer.add_scalar('MSELoss/train', train_loss['mse'], epoch)\n writer.add_scalar('NT-XENTLoss/train', train_loss['nce'], epoch)\n writer.add_scalar('MSELoss/Valid', val_loss['mse'], epoch)\n writer.add_scalar('NT-XENTLoss/Valid', val_loss['nce'], epoch)\n writer.add_scalar('LR', Optimizers['feature'].param_groups[0]['lr'], epoch+1)\n \n \n \n if (epoch)%10 == 0 :\n best_loss = val_loss['nce']\n #save model\n states = {\n 'epoch': epoch + 1,\n 'best_loss': best_loss,\n 'scheduler': scheduler.state_dict()\n }\n for key in Networks:\n states[key+\"net\"] = Networks[key].state_dict()\n for key in Optimizers:\n states[key+\"optimizer\"] = Optimizers[key].state_dict()\n torch.save(states, save_path)\n print('Model Saved')\n\n\n# In[8]:\n\n\nrun_main_loop(loaders, num_epochs)\n\n\n# In[ ]:\n\n\nsave_path = \"weights/AlexNet_Decoupling_Contrastive_SimCLR_Features.pth\"\nstates = {\n 'epoch':200,\n 'scheduler': scheduler.state_dict()\n }\nfor key in Networks:\n states[key+\"net\"] = Networks[key].state_dict()\nfor key in Optimizers:\n states[key+\"optimizer\"] = Optimizers[key].state_dict()\ntorch.save(states, save_path)\n\n\n# In[ ]:\n\n\n\n\n", "sub_path": "SimCLR-failure/pythonexports/pretraining-SimCLR.py", "file_name": "pretraining-SimCLR.py", "file_ext": "py", "file_size_in_byte": 6334, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.cuda.is_available", "line_number": 38, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 38, "usage_type": "attribute"}, {"api_name": "GetDataLoaders.get_dataloaders", "line_number": 51, "usage_type": "call"}, {"api_name": "architectures.Resnets.resnet50_cifar", "line_number": 89, "usage_type": "call"}, {"api_name": "torch.optim.Adam", "line_number": 90, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 90, "usage_type": "name"}, {"api_name": "torch.optim.lr_scheduler.ExponentialLR", "line_number": 91, "usage_type": "call"}, {"api_name": "architectures.ContrastiveLoss.ContrastiveLoss", "line_number": 97, "usage_type": "call"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 98, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 98, "usage_type": "name"}, {"api_name": "torch.nn.MSELoss", "line_number": 98, "usage_type": "call"}, {"api_name": "time.time", "line_number": 128, "usage_type": "call"}, {"api_name": "tqdm.tqdm", "line_number": 129, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 136, "usage_type": "call"}, {"api_name": "torch.no_grad", "line_number": 155, "usage_type": "call"}, {"api_name": "torch.mul", "line_number": 157, "usage_type": "call"}, {"api_name": "time.time", "line_number": 166, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 168, "usage_type": "call"}, {"api_name": "torch.utils.tensorboard.SummaryWriter", "line_number": 175, "usage_type": "call"}, {"api_name": "numpy.Inf", "line_number": 177, "usage_type": "attribute"}, {"api_name": "torch.save", "line_number": 205, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 227, "usage_type": "call"}]}
+{"seq_id": "212258496", "text": "# -*- coding: utf-8 -*-\n'''\nRandom Forest classifier\n'''\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\n\nfrom ...core.routes import register\nfrom .base import BaseMl\nfrom sklearn.ensemble import RandomForestClassifier\n\n@register('ml.forest')\nclass ForestMl(BaseMl):\n '''Random forest\nParameters (not implemented yet) :\nclassifier : if not specified, create a new classifier.\ndata : if not specified, get most recent data from the chain.\naction : if not specified, a new classifier will be created \n and used on available data\n if 'fit' : classifier is created but not used\n if 'predict': previous classifier is used\nUsage : \n#create clusters\nbaf.process('cluster.ward')\n#load new data\nbaf.load('data.simple',(...))\n#train classifier and use \nbaf.process('ml.forest')\n\nTODO: Allow reuse of classifiers.\n '''\n init_kwargs = ('n_estimators', 'classifier', 'data', 'action')\n run_kwargs = ()\n #max_depth\n init_method = RandomForestClassifier.__init__\n run_method = RandomForestClassifier.fit_transform\n\n def __init__(self, *args, **kwargs):\n super(ForestMl, self).__init__(*args, **kwargs)\n self.action = kwargs.get('action',None)\n\n if self.action != \"predict\":\n n_estimators = kwargs.get('n_estimators', 10)\n self.classifier = RandomForestClassifier(n_estimators=n_estimators)\n self._data['classifier'] = self.classifier\n else:\n self.classifier = None\n\n def _get_classifier(self):\n if self.classifier:\n return self.classifier\n else:\n classifier = self.get('classifier')\n self.classifier = classifier\n return classifier\n\n def fit(self, caller, *args, **kwargs):\n '''Train a classifier from tagged data'''\n classifier = self._get_classifier()\n\n vectorizer_result = caller.get('vectorizer_result')\n clusters = caller.get(\"clusterizer_result\")\n classifier.fit(vectorizer_result.toarray(), clusters)\n\n return classifier\n\n def predict(self, caller, *args, **kwargs):\n '''Use classifier on new data'''\n classifier = self._get_classifier()\n vectorizer = caller.get_chain('vectorizer')\n\n #New data\n data_source = caller.get_chain(\"data_source\")\n new_vectorizer_result = vectorizer.transform(data_source.get_data())\n\n result = self.classifier.predict(new_vectorizer_result.toarray())\n return result\n\n def run(self, caller, *args, **kwargs):\n super(ForestMl, self).run(caller,*args, **kwargs)\n\n if self.action in (None, 'fit'):\n result = self.fit(caller, *args, **kwargs)\n self.update(\n result = result,\n classifier = result\n )\n\n if self.action in (None, 'predict'):\n result = self.predict(caller, *args, **kwargs)\n self.update(\n result=result,\n classifier_result=result\n )\n\n return self\n\n\n\n", "sub_path": "bakfu/classify/ml/forest.py", "file_name": "forest.py", "file_ext": "py", "file_size_in_byte": 3078, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "base.BaseMl", "line_number": 15, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier.__init__", "line_number": 37, "usage_type": "attribute"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 37, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier.fit_transform", "line_number": 38, "usage_type": "attribute"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 38, "usage_type": "name"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 46, "usage_type": "call"}, {"api_name": "core.routes.register", "line_number": 14, "usage_type": "call"}]}
+{"seq_id": "469311998", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('logistics_api', '0007_auto_20160331_1334'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Logistics_user',\n fields=[\n ('contact_num', models.IntegerField(default=0, serialize=False, primary_key=True)),\n ('email_id', models.CharField(max_length=80)),\n ('name', models.CharField(max_length=50)),\n ('password', models.CharField(max_length=30)),\n ],\n ),\n migrations.RemoveField(\n model_name='orders',\n name='date',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='trip_id',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='user_id',\n ),\n migrations.RemoveField(\n model_name='trip',\n name='user_id',\n ),\n migrations.AddField(\n model_name='driver',\n name='trip_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Trip', null=True),\n ),\n migrations.AlterField(\n model_name='driver',\n name='name',\n field=models.CharField(max_length=30),\n ),\n migrations.AlterField(\n model_name='orders',\n name='contact_num',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Logistics_user', null=True),\n ),\n migrations.AlterField(\n model_name='trip',\n name='order_id',\n field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, to='logistics_api.Orders', null=True),\n ),\n migrations.DeleteModel(\n name='User',\n ),\n ]\n", "sub_path": "logistics_api/migrations/0008_auto_20160403_1233.py", "file_name": "0008_auto_20160403_1233.py", "file_ext": "py", "file_size_in_byte": 1996, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "django.db.migrations.Migration", "line_number": 8, "usage_type": "attribute"}, {"api_name": "django.db.migrations", "line_number": 8, "usage_type": "name"}, {"api_name": "django.db.migrations.CreateModel", "line_number": 15, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 15, "usage_type": "name"}, {"api_name": "django.db.models.IntegerField", "line_number": 18, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 18, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 19, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 19, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 20, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 20, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 21, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 21, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 24, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 24, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 28, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 28, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 32, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 32, "usage_type": "name"}, {"api_name": "django.db.migrations.RemoveField", "line_number": 36, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 36, "usage_type": "name"}, {"api_name": "django.db.migrations.AddField", "line_number": 40, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 40, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 43, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 43, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 43, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 45, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 45, "usage_type": "name"}, {"api_name": "django.db.models.CharField", "line_number": 48, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 48, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 50, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 50, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 53, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 53, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 53, "usage_type": "name"}, {"api_name": "django.db.migrations.AlterField", "line_number": 55, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 55, "usage_type": "name"}, {"api_name": "django.db.models.ForeignKey", "line_number": 58, "usage_type": "call"}, {"api_name": "django.db.models", "line_number": 58, "usage_type": "name"}, {"api_name": "django.db.db", "line_number": 58, "usage_type": "attribute"}, {"api_name": "django.db", "line_number": 58, "usage_type": "name"}, {"api_name": "django.db.migrations.DeleteModel", "line_number": 60, "usage_type": "call"}, {"api_name": "django.db.migrations", "line_number": 60, "usage_type": "name"}]}
+{"seq_id": "56184289", "text": "import arcade\n\n# screen dimension variables\nWIDTH = 600\nHEIGHT = 600\n\n# pacman variables\npac_x = 300\npac_y = 200\npac_rad = 20\ninit_arc_angle = 0\nfinal_arc_angle = 360\n# is pacman in contact with perimeter walls, can pacman move U,D,L,R\npac_stop = [False]*4\npac_poss_motion = [True]*4\n# pacman as a circle (0) or arc(1)\npacman_character = 1\n\n# arrow key variables\nup_pressed = False\ndown_pressed = False\nleft_pressed = False\nright_pressed = False\npac_speed_x = 0\npac_speed_y = 0\ntime = 0\n\n# maze/wall variables\nperim_wall_pos1 = 300\nperim_wall_pos2 = 20\nperim_wall_width = 600\nperim_wall_height = 40\ncurrent_wall_distance = []\n\n\ndef on_update(delta_time):\n global pacman_character, time, pac_stop\n\n wall_outer_side = pac_stop_perim()\n\n # pac_move(wall_outerside)\n\n # change pacman's outfit (open mouth to closed mouth and vice versa)\n time += delta_time\n if time > 0.075:\n if pac_stop:\n pacman_character = 0\n elif pacman_character == 0:\n pacman_character = 1\n elif pacman_character == 1:\n pacman_character = 0\n time = 0\n\n\ndef pac_move():\n global final_arc_angle, time, pacman_character, up_pressed, down_pressed, left_pressed, right_pressed, pac_x, pac_y, pac_rad, pac_speed_x, init_arc_angle\n global pac_speed_y, perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height, current_wall_distance\n global WIDTH, HEIGHT, pac_stop, pac_poss_motion\n # set pac speeds depending on keys pressed\n if up_pressed:\n pac_speed_y = 2.5\n elif down_pressed:\n pac_speed_y = -2.5\n elif left_pressed:\n pac_speed_x = -2.5\n elif right_pressed:\n pac_speed_x = 2.5\n\n for i in range(len(pac_stop)):\n if pac_stop[i] == False:\n # check if any keys are pressed and stop all other motions accordingly\n if up_pressed:\n pac_speed_x = 0\n elif down_pressed:\n pac_speed_x = 0\n\n if left_pressed:\n pac_speed_y = 0\n elif right_pressed:\n pac_speed_y = 0\n\n # else:\n # check if pacman can still move in direction pressed\n\n if pac_stop[i]:\n # do not allow pacman to move past walls\n # do not pass top\n if pac_poss_motion[0] == False:\n if pac_speed_y > 0:\n pac_speed_y = 0\n # else:\n # pac_stop =\n # do not pass bottom\n elif pac_poss_motion[1] == False:\n if pac_speed_y < 0:\n pac_speed_y = 0\n\n # do not pass left\n if pac_poss_motion[2] == False:\n if pac_speed_x < 0:\n pac_speed_x = 0\n # do not pass right\n if pac_poss_motion[3] == False:\n if pac_speed_x > 0:\n pac_speed_x = 0\n\n if up_pressed:\n init_arc_angle = 135\n final_arc_angle = 405\n elif down_pressed:\n init_arc_angle = 315\n final_arc_angle = 585\n if left_pressed:\n init_arc_angle = 225\n final_arc_angle = 495\n elif right_pressed:\n init_arc_angle = 45\n final_arc_angle = 315\n # move pacman\n pac_x += pac_speed_x\n pac_y += pac_speed_y\n\n\n\ndef pac_stop_perim():\n global final_arc_angle, time, pacman_character, up_pressed, down_pressed, left_pressed, right_pressed, pac_x, pac_y, pac_rad, pac_speed_x, init_arc_angle\n global pac_speed_y, perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height, current_wall_distance\n global WIDTH, HEIGHT, pac_stop, pac_poss_motion\n # calculate distance from pacman to base wall, it touching make him stop moving\n d_to_base = pac_y - (perim_wall_pos2 + perim_wall_height // 2 - pac_rad)\n d_to_left = pac_x - (perim_wall_pos2 + perim_wall_height // 2 - pac_rad)\n d_to_right = (perim_wall_pos1 + perim_wall_width // 2 - pac_rad) - pac_x\n d_to_top = (perim_wall_pos1 + perim_wall_width // 2 - pac_rad) - pac_y\n\n # set the pacman distance\n current_wall_distance = [0] * 4\n current_wall_distance[0] = d_to_base\n current_wall_distance[1] = d_to_left\n current_wall_distance[2] = d_to_right\n current_wall_distance[3] = d_to_top\n\n # reset variables\n # pac_poss_motion = [True]*4\n pac_stop = [False]*4\n # set the index at 4; not touching\n current_wall_index = 4\n\n # check if pacman in contact with wall, and store the wall\n if d_to_base <= pac_rad + perim_wall_height // 2:\n pac_stop[0] = True\n elif d_to_top <= pac_rad + perim_wall_height // 2:\n pac_stop[1] = True\n if d_to_left <= pac_rad + perim_wall_height // 2:\n pac_stop[2] = True\n elif d_to_right <= pac_rad + perim_wall_height // 2:\n pac_stop[3] = True\n\n # for\n\n # if touching, return values\n return pac_stop[current_wall_index]\n\n\n\ndef on_draw():\n global pac_x, pac_y, pacman_character, perim_walls, wall_dimension, WIDTH, HEIGHT\n global perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height\n arcade.start_render()\n\n # base wall\n draw_perim_walls(perim_wall_pos1, perim_wall_pos2, perim_wall_width, perim_wall_height)\n # left_wall\n draw_perim_walls(perim_wall_pos2, perim_wall_pos1, perim_wall_height, perim_wall_width)\n #top wall\n draw_perim_walls(perim_wall_pos1, HEIGHT - perim_wall_pos2, perim_wall_width, perim_wall_height)\n # right wall\n draw_perim_walls(WIDTH - perim_wall_pos2, perim_wall_pos1, perim_wall_height, perim_wall_width)\n\n # Draw pacman, alternating\n if pacman_character == 1:\n draw_pacman_open(pac_x, pac_y)\n else:\n draw_pacman_closed(pac_x, pac_y)\n\n\ndef draw_perim_walls(perim_wall_basex, perim_wall_basey, width, height):\n # draw a peremiter wall\n arcade.draw_rectangle_filled(perim_wall_basex, perim_wall_basey, width, height, arcade.color.BLUE)\n\n\ndef draw_pacman_closed(x, y):\n global pac_rad\n arcade.draw_circle_filled(x, y, pac_rad, arcade.color.YELLOW)\n\n\ndef draw_pacman_open(x, y):\n global pac_rad, init_arc_angle, final_arc_angle\n arcade.draw_arc_filled(x, y, pac_rad, pac_rad, arcade.color.YELLOW, init_arc_angle, final_arc_angle)\n\n\ndef on_key_press(key, modifiers):\n global up_pressed, down_pressed, left_pressed, right_pressed\n # create a key list\n key_pressed_list = [0] * 4\n\n # check if any key is pressed, if it is set that direction to true (move in 1 direction)\n if key == arcade.key.UP:\n up_pressed = True\n key_pressed_list[0] = 1\n elif key == arcade.key.DOWN:\n down_pressed = True\n key_pressed_list[1] = 1\n elif key == arcade.key.LEFT:\n left_pressed = True\n key_pressed_list[2] = 1\n elif key == arcade.key.RIGHT:\n right_pressed = True\n key_pressed_list[3] = 1\n key_pressed_boolean = [up_pressed, down_pressed, left_pressed, right_pressed]\n\n # turn off all keys which are not pressed, account for no on key released\n for i in range(len(key_pressed_list)):\n if key_pressed_list[i] == 0:\n key_pressed_boolean[i] = False\n up_pressed = key_pressed_boolean[0]\n down_pressed = key_pressed_boolean[1]\n left_pressed = key_pressed_boolean[2]\n right_pressed = key_pressed_boolean[3]\n\n\ndef setup():\n global WIDTH, HEIGHT, wall_rows, wall_columns, perim_walls\n arcade.open_window(WIDTH, HEIGHT, \"My Arcade Game\")\n arcade.set_background_color(arcade.color.BLACK)\n arcade.schedule(on_update, 1 / 60)\n\n # Override arcade window methods\n window = arcade.get_window()\n window.on_draw = on_draw\n window.on_key_press = on_key_press\n\n arcade.run()\n\n\nif __name__ == '__main__':\n setup()", "sub_path": "Working/pac_man_final/pac_mouth_test.py", "file_name": "pac_mouth_test.py", "file_ext": "py", "file_size_in_byte": 7697, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "arcade.start_render", "line_number": 168, "usage_type": "call"}, {"api_name": "arcade.draw_rectangle_filled", "line_number": 188, "usage_type": "call"}, {"api_name": "arcade.color", "line_number": 188, "usage_type": "attribute"}, {"api_name": "arcade.draw_circle_filled", "line_number": 193, "usage_type": "call"}, {"api_name": "arcade.color", "line_number": 193, "usage_type": "attribute"}, {"api_name": "arcade.draw_arc_filled", "line_number": 198, "usage_type": "call"}, {"api_name": "arcade.color", "line_number": 198, "usage_type": "attribute"}, {"api_name": "arcade.key", "line_number": 207, "usage_type": "attribute"}, {"api_name": "arcade.key", "line_number": 210, "usage_type": "attribute"}, {"api_name": "arcade.key", "line_number": 213, "usage_type": "attribute"}, {"api_name": "arcade.key", "line_number": 216, "usage_type": "attribute"}, {"api_name": "arcade.open_window", "line_number": 233, "usage_type": "call"}, {"api_name": "arcade.set_background_color", "line_number": 234, "usage_type": "call"}, {"api_name": "arcade.color", "line_number": 234, "usage_type": "attribute"}, {"api_name": "arcade.schedule", "line_number": 235, "usage_type": "call"}, {"api_name": "arcade.get_window", "line_number": 238, "usage_type": "call"}, {"api_name": "arcade.run", "line_number": 242, "usage_type": "call"}]}
+{"seq_id": "591579563", "text": "from __future__ import unicode_literals\n# -*- coding: UTF-8 -*-\nfrom collections import Counter\nimport numpy as np\nimport copy\nimport cv2\nimport redis\nimport sys\n\n\n# 色抽出\ndef extract_color(src, hue_threshould_maximum, hue_threshould_minimum):\n hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)\n hue, saturation, lightness = cv2.split(hsv)\n\n if hue_threshould_minimum > hue_threshould_maximum:\n ret, hue_dest = cv2.threshold(hue, hue_threshould_minimum, 255, cv2.THRESH_BINARY)\n ret, hue_dest_inv = cv2.threshold(hue, hue_threshould_maximum, 255, cv2.THRESH_BINARY_INV)\n\n dest = cv2.bitwise_or(hue_dest, hue_dest_inv)\n\n else:\n ret, dest = cv2.threshold(hue, hue_threshould_minimum, 255, cv2.THRESH_TOZERO)\n ret, dest = cv2.threshold(dest, hue_threshould_maximum, 255, cv2.THRESH_TOZERO_INV)\n\n ret, dest = cv2.threshold(dest, 0, 255, cv2.THRESH_BINARY)\n\n return dest\n\n\n# 背景との差分取得\ndef difference(img, backimg, width):\n dst_img = copy.copy(img)\n # 背景画像との差分を算出\n img_diff = cv2.absdiff(img, backimg)\n img_diffm = cv2.threshold(img_diff, 0, 255, cv2.THRESH_BINARY)[1]\n # グレースケール変換&2値化\n gray = cv2.cvtColor(img_diffm, cv2.COLOR_BGR2GRAY)\n image = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n # ラベリング\n nLavels, lavelImage = cv2.connectedComponents(image)\n # ラベリング結果から0であるところは黒で塗りつぶす\n dst_img[np.where(lavelImage == 0)] = [0, 0, 0]\n return dst_img\n\n\nif __name__ == '__main__':\n database = redis.StrictRedis(host=\"localhost\", port=\"6379\", db=0)\n # cap = cv2.VideoCapture(0)\n # mirror = True\n # size = None\n hsv_color = np.array([[5, 170], [40, 20], [170, 150], [165, 145], [75, 55], [130, 110]])\n backimg = cv2.imread(\"./images/background.jpg\", 1)\n frame = cv2.imread(\"./images/image.jpg\", 1)\n height, width, channel = backimg.shape[:3]\n img_dst = difference(frame, backimg, width)\n for i in range(6):\n labels, labeled_image = cv2.connectedComponents(extract_color(img_dst, hsv_color[i][0], hsv_color[i][1]))\n label_list = list(labeled_image[labeled_image > 0].flatten())\n\n if len(label_list) == 0:\n continue\n # sys.exit('Failed to image encoding.')\n\n most_label = Counter(label_list).most_common()[0][0]\n\n vvec, hvec = (np.where(labeled_image == most_label))\n x = int(np.mean(hvec))\n y = int(np.mean(vvec))\n value = [x, y]\n database.set(\"car\" + str(i), value)\n print(\"x座標 : y座標 \" + str(database.get(\"car\" + str(i))))\n cv2.circle(frame, (int(x), int(y)), 10, (255, 255, 255))\n cv2.imshow('window', frame)\n cv2.imwrite(\"./images/result.jpg\", frame)\n cv2.imwrite(\"./images/debug.jpg\", img_dst)\n cv2.waitKey(0)\n # cap.release()\n cv2.destroyAllWindows()\n", "sub_path": "sailab/capture.py", "file_name": "capture.py", "file_ext": "py", "file_size_in_byte": 2933, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "cv2.cvtColor", "line_number": 13, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2HSV", "line_number": 13, "usage_type": "attribute"}, {"api_name": "cv2.split", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 17, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY_INV", "line_number": 18, "usage_type": "attribute"}, {"api_name": "cv2.bitwise_or", "line_number": 20, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 23, "usage_type": "call"}, {"api_name": "cv2.THRESH_TOZERO", "line_number": 23, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 24, "usage_type": "call"}, {"api_name": "cv2.THRESH_TOZERO_INV", "line_number": 24, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 26, "usage_type": "attribute"}, {"api_name": "copy.copy", "line_number": 33, "usage_type": "call"}, {"api_name": "cv2.absdiff", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.threshold", "line_number": 36, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 36, "usage_type": "attribute"}, {"api_name": "cv2.cvtColor", "line_number": 38, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 38, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.THRESH_OTSU", "line_number": 39, "usage_type": "attribute"}, {"api_name": "cv2.connectedComponents", "line_number": 41, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 43, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 48, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 54, "usage_type": "call"}, {"api_name": "cv2.connectedComponents", "line_number": 58, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 67, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 69, "usage_type": "call"}, {"api_name": "cv2.circle", "line_number": 73, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 75, "usage_type": "call"}, {"api_name": "cv2.imwrite", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 77, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 79, "usage_type": "call"}]}
+{"seq_id": "90524647", "text": "import json\nimport os\nimport operator\nfrom django.http import HttpResponse\nfrom tweepy import OAuthHandler, API\nfrom slackclient import SlackClient\nfrom os import environ\nfrom django.views.decorators.csrf import csrf_exempt\n# from django.http import HttpResponse\n\noauth_token = environ.get('oauth_token', None)\nbot_oauth_token = environ.get('bot_oauth_token', None)\nslack_client = SlackClient(oauth_token)\nslack_bot = SlackClient(bot_oauth_token)\n\n\ndef get_trending():\n consumer_key = environ.get('consumer_key', None)\n consumer_secret = environ.get('consumer_secret', None)\n access_token = environ.get('access_token', None)\n access_token_secret = environ.get('access_token_secret', None)\n\n auth = OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = API(auth)\n\n woe_id = 1\n trends = api.trends_place(woe_id)\n\n trends = json.loads(json.dumps(trends, indent=1))\n trend_temp = []\n for trend in trends[0][\"trends\"]:\n trend_temp.append((trend[\"name\"]))\n\n trending = ', \\n'.join(trend_temp[:10])\n return trending\n\n\ndef get_channel(request):\n ch_event = json.loads(request.body)\n channel = ch_event['event']['channel']\n event_text = ch_event['event']['text']\n if \"trend\" in event_text or \"twitter\" in event_text:\n slack_bot.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=get_trending(),\n icon_emoji=':robot_face:'\n )\n else:\n slack_bot.api_call(\n \"chat.postMessage\",\n channel=channel,\n text=\"Sorry your request cannot be processed\",\n icon_emoji=':robot_face:'\n )\n\n return \"\"\n\n\n@csrf_exempt\ndef slack(request):\n req = json.loads(request.body)\n token = req['token']\n if os.environ.get(\"verification_token\") == token:\n get_channel(request)\n # challenge = req['challenge']\n else:\n word = \"\"\n # challenge = \"wala\"\n\n return HttpResponse(request)\n # return HttpResponse(challenge, content_type=\"text/plain\")\n", "sub_path": "hello/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 2087, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.environ.get", "line_number": 11, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 11, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 12, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 12, "usage_type": "name"}, {"api_name": "slackclient.SlackClient", "line_number": 13, "usage_type": "call"}, {"api_name": "slackclient.SlackClient", "line_number": 14, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 18, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 18, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 19, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 19, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 20, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 20, "usage_type": "name"}, {"api_name": "os.environ.get", "line_number": 21, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 21, "usage_type": "name"}, {"api_name": "tweepy.OAuthHandler", "line_number": 23, "usage_type": "call"}, {"api_name": "tweepy.API", "line_number": 25, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 30, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 30, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 40, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 63, "usage_type": "call"}, {"api_name": "os.environ.get", "line_number": 65, "usage_type": "call"}, {"api_name": "os.environ", "line_number": 65, "usage_type": "attribute"}, {"api_name": "django.http.HttpResponse", "line_number": 72, "usage_type": "call"}, {"api_name": "django.views.decorators.csrf.csrf_exempt", "line_number": 61, "usage_type": "name"}]}
+{"seq_id": "584226998", "text": "from commonvariables import *\r\nimport pygame\r\nimport gamegraphics\r\nimport sys\r\n\r\nclass BackgroundProperties:\r\n\tdef __init__(self, img):\r\n\t\tself.bg = img\r\n\t\tself.bg.set_alpha(50)\r\n\r\nclass TitleProperties:\r\n\tdef __init__(self):\r\n\t\tself.title = ['Better Luck Next Time!', 'You Nailed It!']\r\n\t\tself.loc = [(15,10),(30,10)]\r\n\t\tself.size = 60\r\n\t\tself.color = game_colors['red']\r\n\r\nclass ImageProperties:\r\n\tdef __init__(self, pokemon_img):\r\n\t\toriginal_size = pokemon_img.get_size()\r\n\t\tscale = 2\r\n\t\tself.exposed_img = pygame.transform.scale(pokemon_img,(original_size[0]*scale,original_size[1]*3))\r\n\t\tself.loc = (30,30)\r\n\r\nclass PokemonProperties:\r\n\tdef __init__(self, pokemonname, pokemon_type):\r\n\t\tself.name = pokemonname\r\n\t\tself.types = pokemon_type\r\n\t\tself.label = \"Type(s)\"\r\n\t\tself.name_loc = (50,45)\r\n\t\tself.label_loc = (50,55)\r\n\t\tself.label_color = game_colors['pink']\r\n\t\tself.name_color = game_colors['blue']\r\n\t\tself.type_color = game_colors['green']\r\n\t\tself.name_size = 60\r\n\t\tself.label_size = 30\r\n\r\nclass FooterProperties:\r\n\tdef __init__(self):\r\n\t\tself.msg = \"Press SPACE to continue\"\r\n\t\tself.color = game_colors['black']\r\n\t\tself.size = 30\r\n\t\tself.loc = (35,95)\r\n\r\nclass FinishScreen:\r\n\tdef __init__(self, properties):\r\n\t\tself.title_properties = TitleProperties()\r\n\t\tself.bg_properties = BackgroundProperties(properties.bg_img)\r\n\t\tself.image_properties = ImageProperties(properties.pokemon_img)\r\n\t\tself.pokemon_properties = PokemonProperties(properties.name, properties.types)\r\n\t\tself.footer_properties = FooterProperties()\r\n\t\tself.canvas = pygame.display.set_mode(SCREEN_SIZE,pygame.FULLSCREEN)\r\n\t\tself.graphics = gamegraphics.GraphicsManager()\r\n\r\n\tdef reveal(self, status):\r\n\t\tself.show_background()\r\n\t\tself.show_title(status)\r\n\t\tself.show_image()\r\n\t\tself.show_pokemon_details()\r\n\t\tself.show_footer()\r\n\t\tpygame.display.update()\r\n\t\tis_running = True\t\t\r\n\t\twhile is_running:\r\n\t\t\tfor event in pygame.event.get():\r\n\t\t\t\tif event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):\r\n\t\t\t\t\tis_running = False\r\n\t\t\t\t\tstatus = 0\r\n\t\t\t\telif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\r\n\t\t\t\t\tis_running = False\r\n\t\treturn status\r\n\r\n\r\n\tdef show_background(self):\r\n\t\tself.canvas.fill((255,255,255))\r\n\t\tself.canvas.blit(self.bg_properties.bg,self.bg_properties.bg.get_rect())\r\n\r\n\tdef show_title(self, status):\t\r\n\t\tif status == 0:\r\n\t\t\tself.graphics.display_text(self.canvas,self.title_properties.title[0],self.title_properties.loc[0],\r\n\t\t\t\tself.title_properties.size,self.title_properties.color)\r\n\t\telse:\r\n\t\t\tself.graphics.display_text(self.canvas,self.title_properties.title[1],self.title_properties.loc[1],\r\n\t\t\t\tself.title_properties.size,self.title_properties.color)\r\n\r\n\tdef show_image(self):\r\n\t\tself.graphics.display_image(self.canvas, self.image_properties.exposed_img, self.image_properties.loc)\r\n\r\n\tdef show_pokemon_details(self):\r\n\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.name, self.pokemon_properties.name_loc,\r\n\t\t\tself.pokemon_properties.name_size, self.pokemon_properties.name_color)\r\n\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.label, self.pokemon_properties.label_loc,\r\n\t\t\tself.pokemon_properties.label_size, self.pokemon_properties.label_color)\r\n\t\tfor i in range(len(self.pokemon_properties.types)):\r\n\t\t\tloc = (self.pokemon_properties.label_loc[0], self.pokemon_properties.label_loc[1]+((i+1)*6))\r\n\t\t\tself.graphics.display_text(self.canvas, self.pokemon_properties.types[i], loc,\r\n\t\t\t\tself.pokemon_properties.label_size, self.pokemon_properties.type_color)\r\n\r\n\tdef show_footer(self):\r\n\t\tself.graphics.display_text(self.canvas, self.footer_properties.msg, self.footer_properties.loc,\r\n\t\t\tself.footer_properties.size, self.footer_properties.color)", "sub_path": "PokemonHangman/NewCode/finish.py", "file_name": "finish.py", "file_ext": "py", "file_size_in_byte": 3744, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pygame.transform.scale", "line_number": 22, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 22, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 52, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 52, "usage_type": "attribute"}, {"api_name": "pygame.FULLSCREEN", "line_number": 52, "usage_type": "attribute"}, {"api_name": "gamegraphics.GraphicsManager", "line_number": 53, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 61, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 64, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 64, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.K_ESCAPE", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.KEYDOWN", "line_number": 68, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 68, "usage_type": "attribute"}]}
+{"seq_id": "150293365", "text": "import redis\nfrom django.contrib.sessions.backends.base import SessionBase, CreateError\n\nfrom establishment.misc.settings_with_default import SettingsWithDefault\n\nsettings = SettingsWithDefault(\"REDIS_CONNECTION_SESSION\",\n HOST=\"localhost\",\n PORT=6379,\n SOCKET_TIMEOUT=0.2,\n RETRY_ON_TIMEOUT=True,\n DB=0,\n PASSWORD=None,\n PREFIX=\"session\",\n UNIX_DOMAIN_SOCKET_PATH=None,\n URL=None,\n POOL=None,\n SENTINEL_LIST=None,\n SENTINEL_MASTER_ALIAS=None\n )\n\n\nclass RedisConnectionType:\n SENTINEL = \"sentinel\"\n URL = \"url\"\n HOST = \"host\"\n UNIX_SOCKET = \"unix_socket\"\n\n\nclass RedisConnection:\n _redis_cache = {}\n\n def __init__(self, session_key):\n self.session_key = session_key\n self.connection_key = \"\"\n self.settings = settings\n\n if settings.SENTINEL_LIST is not None:\n self.connection_type = RedisConnectionType.SENTINEL\n else:\n if settings.POOL is not None:\n server_key, server = self.get_server(session_key, settings.POOL)\n self.connection_key = str(server_key)\n self.settings = SettingsWithDefault(fallback_settings=settings)\n\n if settings.URL is not None:\n self.connection_type = RedisConnectionType.URL\n elif settings.HOST is not None:\n self.connection_type = RedisConnectionType.HOST\n elif settings.UNIX_DOMAIN_SOCKET_PATH is not None:\n self.connection_type = RedisConnectionType.UNIX_SOCKET\n\n self.connection_key += self.connection_type\n\n @staticmethod\n def get_server(key, servers_pool):\n \"\"\"\n Assign a redis server pseudo-randomly, proportionally to server weights,\n consistently producing the same result for the same key.\n :param key:\n :param servers_pool:\n :return:\n \"\"\"\n total_weight = sum([server.get(\"weight\", 1) for server in servers_pool])\n\n import hashlib\n position = int(hashlib.sha256(key).hexdigest(), 16) % total_weight\n\n partial_weight_sum = 0\n for server_key, server in enumerate(servers_pool):\n current_weight = server.get(\"weight\", 1)\n if partial_weight_sum <= position < (partial_weight_sum + current_weight):\n return server_key, server\n partial_weight_sum += current_weight\n\n return server_key, server\n\n def create_connection(self):\n settings = self.settings\n\n if self.connection_type == RedisConnectionType.SENTINEL:\n from redis.sentinel import Sentinel\n return Sentinel(\n settings.SENTINEL_LIST,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=getattr(settings, \"db\", 0),\n password=getattr(settings, \"password\", None)\n ).master_for(settings.SENTINEL_MASTER_ALIAS)\n\n if self.connection_type == RedisConnectionType.URL:\n return redis.StrictRedis.from_url(settings.URL, socket_timeout=settings.SOCKET_TIMEOUT)\n\n if self.connection_type == RedisConnectionType.HOST:\n return redis.StrictRedis(\n host=settings.HOST,\n port=settings.PORT,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=settings.DB,\n password=settings.PASSWORD\n )\n\n if self.connection_type == RedisConnectionType.UNIX_SOCKET:\n return redis.StrictRedis(\n unix_socket_path=settings.UNIX_DOMAIN_SOCKET_PATH,\n socket_timeout=settings.SOCKET_TIMEOUT,\n retry_on_timeout=settings.RETRY_ON_TIMEOUT,\n db=settings.DB,\n password=settings.PASSWORD,\n )\n\n def get(self):\n if self.connection_key not in self._redis_cache:\n self._redis_cache[self.connection_key] = self.create_connection()\n\n return self._redis_cache[self.connection_key]\n\n\nclass UselessByteWrapper(str):\n def __init__(self, bytes):\n self.bytes = bytes\n\n def encode(self, encoding, errors=None):\n return self.bytes\n\n\nclass SessionStore(SessionBase):\n def __init__(self, session_key=None):\n super().__init__(session_key)\n self.server = RedisConnection(session_key).get()\n\n @classmethod\n def clear_expired(cls):\n # Redis already has expiration built-in\n pass\n\n def load(self):\n try:\n self._get_or_create_session_key()\n session_data = self.server.get(self.get_redis_key_name())\n return self.decode(session_data.decode(\"utf-8\"))\n except Exception as e:\n self._session_key = None\n return {}\n\n def exists(self, session_key=None):\n return self.server.exists(self.get_redis_key_name(session_key))\n\n def create(self):\n for _ in range(5):\n self._session_key = self._get_new_session_key()\n\n try:\n self.save(must_create=True)\n except CreateError:\n # Key wasn't unique. Try again.\n continue\n self.modified = True\n return\n\n raise RuntimeError(\"Failed to create key\")\n\n def save(self, must_create=False):\n # Make sure the session key exists\n self._get_or_create_session_key()\n\n if must_create and self.exists(self._get_or_create_session_key()):\n raise CreateError\n\n data = self.encode(self._get_session(no_load=must_create))\n\n self.server.setex(self.get_redis_key_name(), self.get_expiry_age(), data)\n\n def delete(self, session_key=None):\n try:\n self.server.delete(self.get_redis_key_name(session_key))\n except:\n pass\n\n def get_redis_key_name(self, session_key=None):\n \"\"\"\n Return the key name in redis, adding the prefix if it exists\n @return string\n \"\"\"\n session_key = session_key or self._session_key\n prefix = settings.PREFIX and (settings.PREFIX + \":\")\n return (prefix or \"\") + session_key\n", "sub_path": "session/redis_session.py", "file_name": "redis_session.py", "file_ext": "py", "file_size_in_byte": 6524, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "establishment.misc.settings_with_default.SettingsWithDefault", "line_number": 6, "usage_type": "call"}, {"api_name": "establishment.misc.settings_with_default.SettingsWithDefault", "line_number": 43, "usage_type": "call"}, {"api_name": "hashlib.sha256", "line_number": 66, "usage_type": "call"}, {"api_name": "redis.sentinel.Sentinel", "line_number": 82, "usage_type": "call"}, {"api_name": "redis.StrictRedis.from_url", "line_number": 91, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 91, "usage_type": "attribute"}, {"api_name": "redis.StrictRedis", "line_number": 94, "usage_type": "call"}, {"api_name": "redis.StrictRedis", "line_number": 104, "usage_type": "call"}, {"api_name": "django.contrib.sessions.backends.base.SessionBase", "line_number": 127, "usage_type": "name"}, {"api_name": "{'hashlib': 'hashlib', 'Sentinel': 'redis.sentinel.Sentinel'}", "line_number": 130, "usage_type": "call"}, {"api_name": "django.contrib.sessions.backends.base.CreateError", "line_number": 155, "usage_type": "name"}, {"api_name": "django.contrib.sessions.backends.base.CreateError", "line_number": 168, "usage_type": "name"}]}
+{"seq_id": "66019458", "text": "import logging\nimport requests\n\nfrom django.conf import settings\nlog = logging.getLogger(__name__)\n\n\ndef _get_json(response):\n try:\n return response.json()\n except:\n return {}\n\n\nclass PlpApiClient(object):\n \"\"\"\n API client for communication with PLP.\n Checks that settings are setup, otherwise logs errors\n Returns data for supported actions\n \"\"\"\n def __init__(self):\n self.base_url = getattr(settings, \"PLP_URL\", None)\n self.api_key = getattr(settings, \"PLP_API_KEY\", None)\n if self.base_url is None or self.api_key is None:\n self._request = self._dummy\n\n def normalize_url(self, url, lms_url):\n if url.startswith(\"http://\") or url.startswith(\"https://\"):\n return url\n return lms_url.strip(\"/\") + url\n\n def push_grade_api_result(self, path, local_csv_url, local_csv_err_url):\n \"\"\"\n Returns url with requests CSV grade sheet\n \"\"\"\n lms_url = getattr(settings, \"LMS_ROOT_URL\", None)\n if not lms_url:\n log.error(\"Undefined LMS_ROOT_URL. Can't return to PLP CSV file absolute url\")\n return\n\n data = {\"url\": self.normalize_url(local_csv_url, lms_url)}\n if local_csv_err_url:\n data[\"url_err\"] = self.normalize_url(local_csv_err_url, lms_url)\n\n return self._request(path, data)\n\n\n def push_course_user_group_changed(self, course_id, username, group_name):\n data = {}\n data['course_id'] = str(course_id)\n data['username'] = username\n data['group_name'] = group_name\n self._request('api/user-add-group', data)\n\n def _request(self, path, data):\n headers = {'x-plp-api-key': self.api_key}#, 'Content-Type': 'application/json'}\n request_url = \"{}/{}/\".format(\n self.base_url.strip(\"/\"),\n path.strip(\"/\")\n )\n plp_response = requests.post(request_url, data=data, headers=headers)\n if plp_response.ok:\n return _get_json(plp_response)\n else:\n message = \"PlpApiClient error: request ({}, {});\".format(request_url, str(data))\n message += \"response ({}, {})\".format(plp_response.status_code, _get_json(plp_response))\n log.error(message)\n return {}\n\n def _dummy(self, *args, **kwargs):\n \"\"\"\n If settings are not setup we log every attempt to call PLP\n but do nothing\n \"\"\"\n message = \"Tried to use PlpApiClient, but settings are incorrect. \" \\\n \"You have to configure PLP_URL and PLP_API_KEY to use PlpApiClient.\"\n log.error(message)\n return {}\n", "sub_path": "open_edx_api_extension/api_client.py", "file_name": "api_client.py", "file_ext": "py", "file_size_in_byte": 2643, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 5, "usage_type": "call"}, {"api_name": "django.conf.settings", "line_number": 22, "usage_type": "argument"}, {"api_name": "django.conf.settings", "line_number": 23, "usage_type": "argument"}, {"api_name": "django.conf.settings", "line_number": 36, "usage_type": "argument"}, {"api_name": "requests.post", "line_number": 61, "usage_type": "call"}]}
+{"seq_id": "454001180", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\n\n\ndef squared_l2_norm(x):\n flattened = x.view(x.unsqueeze(0).shape[0], -1)\n return (flattened ** 2).sum(1)\n\n\ndef l2_norm(x):\n return squared_l2_norm(x).sqrt()\n\n\ndef car_trades_loss(model,\n x_natural,\n y,\n idx,\n contrast_idx,\n criterion_car,\n optimizer,\n car_beta,\n step_size=0.003,\n epsilon=0.031,\n perturb_steps=10,\n trades_beta=1.0,\n distance='l_inf',\n tol=10e-8):\n\n # define KL-loss\n criterion_kl = nn.KLDivLoss(reduction='sum')\n model.eval()\n batch_size = len(x_natural)\n norm = distance.split('_')[1]\n\n # random start\n delta = torch.rand_like(x_natural) * 2 * epsilon - epsilon\n if distance != 'l_inf': # projected into feasible set if needed\n normVal = torch.norm(delta.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n mask = normVal <= epsilon\n scaling = epsilon / normVal\n scaling[mask] = 1\n delta = delta * scaling.view(batch_size, 1, 1, 1)\n\n x_adv = x_natural.detach() + delta.detach()\n\n # PGD with KL loss\n for _ in range(perturb_steps):\n x_adv.requires_grad_(True)\n with torch.enable_grad():\n _, logit_adv = model(x_adv)\n _, logit_natural = model(x_natural)\n loss_kl = criterion_kl(F.log_softmax(logit_adv, dim=1),\n F.softmax(logit_natural, dim=1))\n updates = torch.autograd.grad(loss_kl, [x_adv])[0]\n if distance == 'l_inf':\n updates = torch.sign(updates)\n else:\n normVal = torch.norm(updates.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n updates = updates / normVal.view(batch_size, 1, 1, 1)\n\n updates = updates * step_size\n x_adv = x_adv.detach() + updates.detach()\n\n # projection\n delta = x_adv - x_natural\n if distance == 'l_inf':\n delta = torch.clamp(delta, -epsilon, epsilon)\n else:\n normVal = torch.norm(delta.view(batch_size, -1), int(norm), 1)\n normVal = torch.max(normVal, torch.ones_like(norm) * 1e-6)\n mask = normVal <= epsilon\n scaling = epsilon / normVal\n scaling[mask] = 1\n delta = delta * scaling.view(batch_size, 1, 1, 1)\n\n x_adv = torch.clamp(x_natural+delta, 0.0, 1.0)\n\n model.train()\n x_adv = Variable(torch.clamp(x_adv, 0.0, 1.0), requires_grad=False)\n\n # zero gradient\n optimizer.zero_grad()\n # calculate robust loss\n feats_adv, logit_adv = model(x_adv)\n feats_natural, logit_natural = model(x_natural)\n loss_natural = F.cross_entropy(logit_natural, y)\n\n loss_robust = (1.0 / batch_size) * criterion_kl(F.log_softmax(logit_adv, dim=1),\n F.softmax(logit_natural, dim=1))\n loss_car = criterion_car(feats_natural, feats_adv, idx, contrast_idx)\n loss = loss_natural + trades_beta * loss_robust + car_beta * loss_car\n return loss, loss_natural, loss_robust, loss_car\n", "sub_path": "car_trades.py", "file_name": "car_trades.py", "file_ext": "py", "file_size_in_byte": 3366, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.nn.KLDivLoss", "line_number": 33, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 33, "usage_type": "name"}, {"api_name": "torch.rand_like", "line_number": 39, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 41, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 42, "usage_type": "call"}, {"api_name": "torch.enable_grad", "line_number": 53, "usage_type": "call"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 56, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.functional.softmax", "line_number": 57, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 57, "usage_type": "name"}, {"api_name": "torch.autograd.grad", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.autograd", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.sign", "line_number": 60, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 62, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 63, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 72, "usage_type": "call"}, {"api_name": "torch.norm", "line_number": 74, "usage_type": "call"}, {"api_name": "torch.max", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.ones_like", "line_number": 75, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 81, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.clamp", "line_number": 84, "usage_type": "call"}, {"api_name": "torch.nn.functional.cross_entropy", "line_number": 91, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 91, "usage_type": "name"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 93, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 93, "usage_type": "name"}, {"api_name": "torch.nn.functional.softmax", "line_number": 94, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 94, "usage_type": "name"}]}
+{"seq_id": "369573124", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport subprocess\nimport socket\nfrom redis import Redis\nimport pymysql\nfrom check import config\n\n\ndef check_redis():\n \"\"\"\n 检查redis连接情况\n :return: \n \"\"\"\n ip = config.REDIS['ip']\n port = int(config.REDIS['port'])\n database = int(config.REDIS['database'])\n try:\n redis = Redis(ip, port, db=database)\n ping = redis.ping()\n if ping:\n print('check_redis : ok')\n else:\n print('check_redis : fail')\n except Exception as ex:\n print('check_redis : fail')\n print(\"error_message:\", ex)\n\n\ndef check_thrift():\n \"\"\"\n 检查thrift是否启动\n :return: \n \"\"\"\n ip = config.CORE_THRIFT['ip']\n port = int(config.CORE_THRIFT['port'])\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(3)\n try:\n s.connect((ip, port))\n s.close()\n print('check_thrift : ok')\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_thrift:fail\")\n\n\ndef check_port():\n \"\"\"\n 检查端口是否正常监听\n :return: \n \"\"\"\n port = int(config.CORE_THRIFT['port'])\n command = \"netstat -anp | grep \" + str(port) + \" |awk '{print $6}' |head -1\"\n try:\n result = subprocess.getoutput(command)\n if 'LISTEN' in result:\n print('check_port : ok')\n else:\n print('check_port : fail')\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_thrift:\", ex)\n\n\ndef check_log_file():\n \"\"\"\n 检查日志文件是否有错误\n :return: \n \"\"\"\n log_file = config.LOG_FILE_PATH\n no_error = True\n with open(log_file, encoding='utf-8') as f:\n for line_no, line in enumerate(f):\n if '[ERROR]' in line:\n print('lineNo:{} message:{}'.format(line_no, line),end='')\n no_error = False\n break\n\n if no_error:\n print(\"check_log_file: ok\")\n else:\n print('check_log_file: fail')\n\n\ndef check_database():\n \"\"\"\n 检查数据库连接配置\n :return: \n \"\"\"\n ip = config.MYSQL['ip']\n port = int(config.MYSQL['port'])\n database = config.MYSQL['database']\n user = config.MYSQL['user']\n password = config.MYSQL['password']\n\n db = pymysql.connect(host=ip, port=port, user=user, password=password, database=database)\n try:\n cursor = db.cursor()\n cursor.execute(\"select version()\")\n print(\"check_database: ok\")\n except Exception as ex:\n print(\"error_message:\", ex)\n print(\"check_database: fail\")\n db.close()\n\n\nif __name__ == '__main__':\n check_thrift()\n check_redis()\n check_port()\n check_log_file()\n check_database()\n", "sub_path": "check/prodct_check.py", "file_name": "prodct_check.py", "file_ext": "py", "file_size_in_byte": 2759, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "check.config.REDIS", "line_number": 16, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 16, "usage_type": "name"}, {"api_name": "check.config.REDIS", "line_number": 17, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 17, "usage_type": "name"}, {"api_name": "check.config.REDIS", "line_number": 18, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 18, "usage_type": "name"}, {"api_name": "redis.Redis", "line_number": 20, "usage_type": "call"}, {"api_name": "redis.ping", "line_number": 21, "usage_type": "call"}, {"api_name": "check.config.CORE_THRIFT", "line_number": 36, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 36, "usage_type": "name"}, {"api_name": "check.config.CORE_THRIFT", "line_number": 37, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 37, "usage_type": "name"}, {"api_name": "socket.socket", "line_number": 38, "usage_type": "call"}, {"api_name": "socket.AF_INET", "line_number": 38, "usage_type": "attribute"}, {"api_name": "socket.SOCK_STREAM", "line_number": 38, "usage_type": "attribute"}, {"api_name": "check.config.CORE_THRIFT", "line_number": 54, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 54, "usage_type": "name"}, {"api_name": "subprocess.getoutput", "line_number": 57, "usage_type": "call"}, {"api_name": "check.config.LOG_FILE_PATH", "line_number": 72, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 72, "usage_type": "name"}, {"api_name": "check.config.MYSQL", "line_number": 92, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 92, "usage_type": "name"}, {"api_name": "check.config.MYSQL", "line_number": 93, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 93, "usage_type": "name"}, {"api_name": "check.config.MYSQL", "line_number": 94, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 94, "usage_type": "name"}, {"api_name": "check.config.MYSQL", "line_number": 95, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 95, "usage_type": "name"}, {"api_name": "check.config.MYSQL", "line_number": 96, "usage_type": "attribute"}, {"api_name": "check.config", "line_number": 96, "usage_type": "name"}, {"api_name": "pymysql.connect", "line_number": 98, "usage_type": "call"}]}
+{"seq_id": "247578035", "text": "#absence.py\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author Falko Benthin\n@Date 17.01.2014\n@brief reads and writes absence file, absent is a timestamp (int), when seheiah recognise the byebye command. Absent==0 means, the monitored person is at home \n\"\"\"\n\nimport os,time\nimport logging\nimport logdb\nimport readConfig as rc\n\nclass Absence():\n\t\n\tdef __init__(self):\n\t\tself.absenceFileName = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), rc.config.get('absencefile','absenceFile'))\n\t\t#intervals to considering in seconds\n\t\"\"\"\n\tsets absence\n\t\"\"\"\n\tdef set(self,absent):\n\t\ttry:\n\t\t\tabsenceFile = open(self.absenceFileName, \"r+\")\n\t\t\tif (absent == 0): #when home\n\t\t\t\ttry:\n\t\t\t\t\tstarttime = int(absenceFile.read())\n\t\t\t\texcept IOError:\n\t\t\t\t\tlogging.error(\"couldn't read from file\" + self.absenceFileName)\n\t\t\t\t#logging to database\n\t\t\t\tdb = logdb.logDB()\n\t\t\t\tdb.addAbsence(starttime,int(time.time()))\n\t\t\t\tdb.closeDB()\n\t\t\ttry:\n\t\t\t\tabsenceFile.seek(0)\n\t\t\t\tabsenceFile.write(str(absent))\n\t\t\t\tabsenceFile.truncate()\n\t\t\texcept IOError:\n\t\t\t\tlogging.error(\"couldn't write to file \" + self.absenceFileName)\n\t\t\tfinally:\n\t\t\t\tabsenceFile.close()\n\t\texcept IOError:\n\t\t\tlogging.error(\"couldn't open file \" + self.absenceFileName)\n\t\n\t#checks via file, if subject at home\n\tdef get(self):\n\t\ttry:\n\t\t\tabsenceFile = open(self.absenceFileName, \"r\")\n\t\t\ttry:\n\t\t\t\tabsenceValue = int(absenceFile.read())\n\t\t\texcept IOError:\n\t\t\t\tlogging.error(\"couldn't read from file\" + self.absenceFileName)\n\t\t\tfinally:\n\t\t\t\tabsenceFile.close()\n\t\texcept IOError:\n\t\t\tlogging.error(\"file \" + self.absenceFileName + \" doesn't exists\")\n\t\treturn bool(absenceValue)\n\n", "sub_path": "program/absence.py", "file_name": "absence.py", "file_ext": "py", "file_size_in_byte": 1621, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.join", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path", "line_number": 18, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 18, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 18, "usage_type": "call"}, {"api_name": "readConfig.config.get", "line_number": 18, "usage_type": "call"}, {"api_name": "readConfig.config", "line_number": 18, "usage_type": "attribute"}, {"api_name": "logging.error", "line_number": 30, "usage_type": "call"}, {"api_name": "logdb.logDB", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 33, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 40, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 44, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 53, "usage_type": "call"}, {"api_name": "logging.error", "line_number": 57, "usage_type": "call"}]}
+{"seq_id": "186653311", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 30 14:22:35 2018\n\n@author: taneljoon\n\"\"\"\n\n\n# importing libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# importing data\npath = ('/Users/taneljoon/Documents/Python/Machine_Learning_udemy/'\n'Part 8 - Deep Learning/Section 39 - Artificial Neural Networks (ANN)/'\n'Churn_Modelling.csv')\ndataset = pd.read_csv(path)\n\nX = dataset.iloc[:,3:13].values # first : is that we take lines, next ho many\nY = dataset.iloc[:,13].values\n \n# categorise the data - we use the sklearn library\n# for country & sex\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:,1] = labelencoder_X_1.fit_transform(X[:,1])\nlabelencoder_X_2 = LabelEncoder()\nX[:,2] = labelencoder_X_2.fit_transform(X[:,2])\n# we will use dummy encoding - if is France 0/1, if is Spain 0/1\nonehotencoder = OneHotEncoder(categorical_features = [1]) # 1 is the index\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:,1:]\n \n# splitting the dataset to the training set and test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 0)\n\n# Fitting the XGBoost to the training set\nfrom xgboost import XGBClassifier\nclassifier = XGBClassifier()\nclassifier.fit(X_train, Y_train)\n\n\ny_pred = classifier.predict(X_test)\n# this works better\n#for ii in range(0,len(y_pred)):\n# y_pred[ii] = round(y_pred[ii],0)\n\n# Making a confusion matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(Y_test, y_pred)\n\n# Applying k_fold_cross_validation\nfrom sklearn.model_selection import cross_val_score\naccuracies = cross_val_score(estimator = classifier, X = X_train, y = Y_train, cv = 10)\n# we take average of accuracies vector\naccuracies.mean()\naccuracies.std()", "sub_path": "ML/xgboost.py", "file_name": "xgboost.py", "file_ext": "py", "file_size_in_byte": 1891, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pandas.read_csv", "line_number": 19, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 27, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 29, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.OneHotEncoder", "line_number": 32, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 38, "usage_type": "call"}, {"api_name": "xgboost.XGBClassifier", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.metrics.confusion_matrix", "line_number": 53, "usage_type": "call"}, {"api_name": "sklearn.model_selection.cross_val_score", "line_number": 57, "usage_type": "call"}]}
+{"seq_id": "231804810", "text": "import numpy as np\nimport cv2 as cv\nimport PIL\nfrom cv2 import aruco\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport pandas as pd\nimport os\n\ndef callback(x):\n pass\n\n\npath = os.path.join(os.getcwd(), 'camera_calibration/data/test/edited/')\n\naruco_dict = aruco.Dictionary_get(aruco.DICT_6X6_250)\ncv.namedWindow('thresh')\ncv.createTrackbar('L', 'thresh', 0, 255, callback)\ncv.createTrackbar('U', 'thresh', 0, 255, callback)\ndef generate():\n fig = plt.figure()\n nx = 4\n ny = 3\n for i in range(1, nx * ny + 1):\n ax = fig.add_subplot(ny, nx, i)\n img = aruco.drawMarker(aruco_dict, i, 700)\n plt.imshow(img, cmap=mpl.cm.gray, interpolation=\"nearest\")\n ax.axis(\"off\")\n\n plt.savefig(\"data/markers.png\")\n plt.show()\n\nsource = 0\ncapture = cv.VideoCapture(source)\nwith np.load(path + 'output/data.npz') as file:\n mtx, dist, r_m, t_m = [file[i] for i in ('mtx', 'dist', 'rotation', 'translation')]\n\nwhile capture.isOpened():\n L = cv.getTrackbarPos('L', 'thresh')\n U = cv.getTrackbarPos('U', 'thresh')\n\n retain, frame = capture.read()\n if retain:\n gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n ret, thresh = cv.threshold(gray, L, U, cv.THRESH_BINARY)\n\n parameters = aruco.DetectorParameters_create()\n corners, ids, rejected = aruco.detectMarkers(thresh, aruco_dict, parameters=parameters)\n\n if len(corners) > 0:\n cv.aruco.drawDetectedMarkers(frame, corners, ids)\n if ids is not None:\n rvecs, tvecs, _ = cv.aruco.estimatePoseSingleMarkers(corners, 0.1, mtx, dist, r_m, t_m)\n for i in range(len(ids)):\n cv.aruco.drawAxis(frame, mtx, dist, rvecs[i], tvecs[i], 0.1)\n\n cv.imshow('frame', frame)\n cv.imshow('thresh', thresh)\n key = cv.waitKey(1)\n if key == 27 or 0xFF == ord('q'):\n break\n\n\ncapture.release()\ncv.destroyAllWindows()", "sub_path": "CV/code/opencv/aruco.py", "file_name": "aruco.py", "file_ext": "py", "file_size_in_byte": 1934, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.join", "line_number": 14, "usage_type": "call"}, {"api_name": "os.path", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 14, "usage_type": "call"}, {"api_name": "cv2.aruco.Dictionary_get", "line_number": 16, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 16, "usage_type": "name"}, {"api_name": "cv2.aruco.DICT_6X6_250", "line_number": 16, "usage_type": "attribute"}, {"api_name": "cv2.namedWindow", "line_number": 17, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 18, "usage_type": "call"}, {"api_name": "cv2.createTrackbar", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "cv2.aruco.drawMarker", "line_number": 26, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 26, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 27, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 27, "usage_type": "name"}, {"api_name": "matplotlib.cm", "line_number": 27, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "cv2.VideoCapture", "line_number": 34, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 35, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 39, "usage_type": "call"}, {"api_name": "cv2.getTrackbarPos", "line_number": 40, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 44, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2GRAY", "line_number": 44, "usage_type": "attribute"}, {"api_name": "cv2.threshold", "line_number": 45, "usage_type": "call"}, {"api_name": "cv2.THRESH_BINARY", "line_number": 45, "usage_type": "attribute"}, {"api_name": "cv2.aruco.DetectorParameters_create", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 47, "usage_type": "name"}, {"api_name": "cv2.aruco.detectMarkers", "line_number": 48, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 48, "usage_type": "name"}, {"api_name": "cv2.aruco.drawDetectedMarkers", "line_number": 51, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 51, "usage_type": "attribute"}, {"api_name": "cv2.aruco.estimatePoseSingleMarkers", "line_number": 53, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 53, "usage_type": "attribute"}, {"api_name": "cv2.aruco.drawAxis", "line_number": 55, "usage_type": "call"}, {"api_name": "cv2.aruco", "line_number": 55, "usage_type": "attribute"}, {"api_name": "cv2.imshow", "line_number": 57, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 58, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 59, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 65, "usage_type": "call"}]}
+{"seq_id": "100435696", "text": "#!/usr/bin/env python\nimport numpy as np\nfrom netCDF4 import Dataset\nfrom datetime import datetime, timedelta\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.filters import gaussian_filter\nfrom mpl_toolkits.basemap import Basemap\n\nimport sys\nfrom mpl_toolkits import basemap\nimport spharm\nimport os\nfrom hyperdiffusion import del4_filter, apply_des_filter\nimport namelist as NL # <---- IMPORTANT! Namelist containing constants and other model parameters\n\n\nclass Model:\n \"\"\"\n Class for storing/plotting flow fields for a homogeneous (constant density), \n non-divergent, and incompressible fluid on a sphere and integrating them forward \n with the barotropic vorticity equation.\n \"\"\"\n \n def __init__(self, ics, forcing=None):\n \"\"\"\n Initializes the model.\n \n Requires:\n ics -----> Dictionary of linearized fields and space/time dimensions\n keys: u_bar, v_bar, u_prime, v_prime, lats, lons, start_time\n forcing -> a 2D array (same shape as model fields) containing a\n vorticity tendency [s^-2] to be imposed at each integration time step\n \"\"\"\n # 1) STORE SPACE/TIME VARIABLES (DIMENSIONS)\n # Get the latitudes and longitudes (as lists)\n self.lats = ics['lats']\n self.lons = ics['lons']\n self.start_time = ics['start_time'] # datetime\n self.curtime = self.start_time\n \n \n # 2) GENERATE/STORE NONDIVERGENT INITIAL STATE\n # Set up the spherical harmonic transform object\n self.s = spharm.Spharmt(self.nlons(), self.nlats(), rsphere=NL.Re,\n gridtype='regular', legfunc='computed')\n # Truncation for the spherical transformation\n if NL.M is None:\n self.ntrunc = self.nlats()\n else:\n self.ntrunc = NL.M\n # Use the object to get the initial conditions\n # First convert to vorticity using spharm object\n vortb_spec, div_spec = self.s.getvrtdivspec(ics['u_bar'], ics['v_bar'])\n vortp_spec, div_spec = self.s.getvrtdivspec(ics['u_prime'], ics['v_prime'])\n div_spec = np.zeros(vortb_spec.shape) # Only want NON-DIVERGENT part of wind \n # Re-convert this to u-v winds to get the non-divergent component\n # of the wind field\n self.ub, self.vb = self.s.getuv(vortb_spec, div_spec) # MEAN WINDS\n self.up, self.vp = self.s.getuv(vortp_spec, div_spec) # PERTURBATION WINDS\n # Use these winds to get the streamfunction (psi) and \n # velocity potential (chi)\n self.psib,chi = self.s.getpsichi(self.ub, self.vb) # MEAN STREAMFUNCTION\n self.psip,chi = self.s.getpsichi(self.up, self.vp) # PERTURBATION STREAMFUNCTION\n # Convert the spectral vorticity to grid\n self.vort_bar = self.s.spectogrd(vortb_spec) # MEAN RELATIVE VORTICITY\n self.vortp = self.s.spectogrd(vortp_spec) # PERTURBATION RELATIVE VORTICITY\n self.tot_ke = []\n self.expected_ke = np.sum(np.power(self.ub + self.up, 2) + np.power(self.vb + self.vp, 2)) \n \n # 3) STORE A COUPLE MORE VARIABLES\n # Map projections for plotting\n self.bmaps = create_basemaps(self.lons, self.lats)\n # Get the vorticity tendency forcing (if any) for integration\n self.forcing = forcing\n self.topography(ics['lats'], ics['lons'], planet=NL.topo) \n \n #==== Some simple dimensional functions ========================================== \n def nlons(self):\n return len(self.lons)\n def nlats(self):\n return len(self.lats)\n \n def topography(self, lats, lons, planet='Earth'):\n if planet == 'Earth':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n \n # Mask out oceans\n idx = np.where(topo_elev < 0)\n topo_elev[idx[0], idx[1]] = 0\n \n # Interpolate topography data to the known grid\n elif planet == 'Mars':\n d = np.load('mars.npz')\n topo_lat = d['lats'][:,0][::-1]\n topo_lon = d['lons'][0,1:]+180\n topo_elev = d['data'][:,1:][::-1,:] \n elif planet == 'flat':\n d = Dataset('elev.0.25-deg.nc')\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n topo_elev[:,:] = 0\n elif planet == 'isolated_mountain':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n \n # Mask out oceans\n idx = np.where(topo_elev < 4000)\n topo_elev[idx[0], idx[1]] = 0\n elif planet == 'block':\n # From: http://research.jisao.washington.edu/data/elevation/\n d = Dataset('elev.0.25-deg.nc')\n #print(d.variables.keys())\n topo_lat = np.flipud(d['lat'])\n topo_lon = d['lon'][:]\n topo_elev = np.flipud(d['data'][0])\n #print(topo_lat.shape, topo_lon.shape, topo_elev.shape)\n # Mask out oceans\n #idx = np.where(topo_elev < 4000)\n topo_elev[:, :] = 0\n idx = np.where((topo_lon > 30) & (topo_lon < 60))\n topo_elev[:, idx[0]] = 1000\n \n new_lon, new_lat = np.meshgrid(self.lons, self.lats)\n self.topo = basemap.interp(topo_elev, topo_lon, topo_lat, new_lon, new_lat, order=1)\n ##plt.title(\"Terrain\")\n #plt.pcolormesh(new_lon, new_lat, self.topo)\n #cb = plt.colorbar()\n #cb.ax.set_ylabel(\"Elevation [m]\")\n #plt.ylabel(\"Latitude\")\n #plt.xlabel(\"Longitude\")\n #plt.show()\n self.topo = gaussian_filter(self.topo, NL.smooth_topo)\n #plt.title(\"Terrain\")\n #plt.pcolormesh(new_lon, new_lat, self.topo)\n #cb = plt.colorbar()\n #cb.ax.set_ylabel(\"Elevation [m]\")\n #plt.ylabel(\"Latitude\")\n #plt.xlabel(\"Longitude\")\n #plt.show()\n \n #stop \n #==== Primary function: model integrator ========================================= \n def integrate(self):\n \"\"\" \n Integrates the barotropic model using spherical harmonics.\n Simulation configuration is set in namelist.py\n \"\"\"\n # Create a radian grid\n lat_list_r = [x * np.pi/180. for x in self.lats]\n lon_list_r = [x * np.pi/180. for x in self.lons]\n\n # Meshgrid\n lons,lats = np.meshgrid(self.lons, self.lats)\n lamb, theta = np.meshgrid(lon_list_r, lat_list_r)\n\n # Need these for derivatives later\n dlamb = np.gradient(lamb)[1]\n dtheta = np.gradient(theta)[0]\n\n # Plot Initial Conditions\n if NL.plot_freq != 0:\n self.plot_figures(0)\n\n # Now loop through the timesteps\n for n in range(NL.ntimes):\n \n #if n > 1000:\n # self.topo[:,:] = 0\n # Leapfrog:\n if NL.integration_method == 'leapfrog':\n vort_tend = self.gettend(self.vortp, dlamb, dtheta, theta, n)\n print(np.max(vort_tend), np.min(vort_tend))\n if n == 0:\n # First step just do forward difference\n # Vorticity at next time is just vort + vort_tend * dt\n vortp_next = self.vortp + vort_tend * NL.dt\n else:\n # Otherwise do leapfrog\n vortp_next = vortp_prev + vort_tend * 2 * NL.dt\n\n elif NL.integration_method == 'rk4':\n h = NL.dt\n # runge kutta requires 4 estimates of the tendency equation \n vortp = self.vortp\n\n k1 = self.gettend(vortp, dlamb, dtheta, theta, n)\n# print(\"k1:\",np.max(k1), np.min(k1))\n k2 = self.gettend(vortp + 0.5 * h * k1, dlamb, dtheta, theta, n)\n# print(\"k2:\",np.max(k2), np.min(k2))\n k3 = self.gettend(vortp + 0.5 * h * k2, dlamb, dtheta, theta, n)\n# print(\"k3:\",np.max(k3), np.min(k3))\n k4 = self.gettend(vortp + h * k3, dlamb, dtheta, theta, n)\n# print(\"k4:\",np.max(k4), np.min(k4))\n vortp_next = vortp + h*(k1 + 2*k2 + 2*k3 + k4)/6.\n# print(\"VORTP NEXT:\",np.max(vortp_next), np.min(vortp_next))\n \n if np.isnan(vortp_next).any():\n print(\"BOOM.\")\n print(\"Looks like your model blew up. Change the dt or try a different model!\")\n print(\"The barotropic model will exit now.\")\n sys.exit()\n\n # First go back to spectral space\n vortp_spec = self.s.grdtospec(vortp_next)\n div_spec = np.zeros(np.shape(vortp_spec)) # Divergence is zero in barotropic vorticity\n\n # Now use the spharm methods to update the u and v grid\n self.up, self.vp = self.s.getuv(vortp_spec, div_spec)\n self.psip, chi = self.s.getpsichi(self.up, self.vp)\n\n # Update the vorticity\n self.vortp = self.s.spectogrd(vortp_spec)\n\n # Invert this new vort to get the new psi (or rather, uv winds)\n self.tot_ke.append(np.sum(np.power(self.up+self.ub,2) + np.power(self.vp+self.vb,2)))\n # Change vort_now to vort_prev\n # and if not first step, add Robert filter to dampen out crazy modes\n if NL.integration_method == 'leapfrog':\n if n == 0:\n vortp_prev = self.vortp\n else:\n vortp_prev = (1.-2.*NL.r)*self.vortp + NL.r*(vortp_next + vortp_prev)\n\n # Update the current time \n cur_fhour = (n+1) * NL.dt / 3600.\n self.curtime = self.start_time + timedelta(hours = cur_fhour)\n\n # Make figure(s) every hours\n if NL.plot_freq!=0 and cur_fhour % NL.plot_freq == 0:\n # Go from psi to geopotential\n print(\"Plotting hour\", cur_fhour)\n self.plot_figures(int(cur_fhour))\n \n def gettend(self,vortp, dlamb, dtheta, theta, n):\n # self.psip, self.psib, self.vortp, self.vort_bar\n # \n # Here we actually compute vorticity tendency\n # Compute tendency with beta as only forcing\n vort_tend = -2. * NL.omega/(NL.Re**2) * d_dlamb(self.psip + self.psib, dlamb) - \\\n Jacobian(self.psip+self.psib, vortp+self.vort_bar, theta, dtheta, dlamb)\n \n # Apply hyperdiffusion if requested for smoothing\n if NL.diff_opt=='del4':\n vort_tend -= del4_filter(vortp, self.lats, self.lons)\n elif NL.diff_opt=='des':\n vort_tend = apply_des_filter(self.s, vortp, vort_tend, self.ntrunc,\n t = (n+1) * NL.dt / 3600.).squeeze()\n \n # Now add any imposed vorticity tendency forcing\n print(n, NL.forcing_time)\n if NL.use_forcing is True and n < NL.forcing_time:\n vort_tend += self.forcing\n\n # Now add any geographical vorticity tendency forcing\n f = 2 * NL.omega * np.sin(theta)\n vort_tend += -((f) * \\\n Jacobian(self.psip+self.psib, self.topo, theta, dtheta, dlamb)) / \\\n NL.fluid_height \n return vort_tend\n\n\n #==== Plotting utilities =========================================================\n def plot_figures(self, n, winds='total', vorts='total', psis='pert', showforcing=True,\n vortlevs=np.array([-10,-8,-6,-4,-2,2,4,6,8,10])*1e-5,\n windlevs=np.arange(20,61,4), hgtlevs=np.linspace(-500,500,26),\n forcelevs=np.array([-15,-12,-9,-6,-3,3,6,9,12,15])*1e-10):\n \"\"\"\n Make global and regional plots of the flow.\n \n Requires:\n n ------------------> timestep number\n winds, vorts, psis -> are we plotting the 'mean', 'pert', or 'total' field?\n showforcing --------> if True, contour the vorticity tendency forcing\n *levs --------------> contour/fill levels for the respective variables\n \"\"\"\n # What wind component(s) are we plotting?\n if winds=='pert': u = self.up; v = self.vp\n elif winds=='mean': u = self.ub; v = self.vb\n else: u = self.up+self.ub; v = self.vp+self.vb\n # What vorticity component(s) are we plotting?\n if vorts=='pert': vort = self.vortp\n elif vorts=='mean': vort = self.vort_bar\n else: vort = self.vortp + self.vort_bar\n # What streamfunction component(s) are we plotting?\n if psis=='pert': psi = self.psip\n elif psis=='mean': psi = self.psib\n else: psi = self.psip + self.psib\n\n # MAKE GLOBAL ZETA & WIND BARB MAP\n fig, ax = plt.subplots(figsize=(10,8))\n fig.subplots_adjust(bottom=0.2, left=0.05, right=0.95)\n \n xx, yy = self.bmaps['global_x'], self.bmaps['global_y']\n plt.pcolormesh(xx, yy, self.topo, alpha=1, cmap='gist_earth', vmin=np.min(self.topo), vmax=np.max(self.topo))\n cs = ax.contourf(xx, yy, vort, vortlevs, cmap=plt.cm.RdBu_r, extend='both', alpha=0.5)\n plt.xlim(xx.min(), xx.max())\n plt.ylim(yy.min(), yy.max())\n if NL.topo == 'Earth':\n self.bmaps['global'].drawcoastlines()\n parallels = np.arange(-70.,81,10.)\n meridians = np.arange(10.,351.,20.)\n self.bmaps['global'].drawmeridians(meridians,labels=[True,False,False,True])\n self.bmaps['global'].drawparallels(parallels,labels=[True,False,False,True])\n ax.quiver(xx[::2,::2], yy[::2,::2], u[::2,::2], v[::2,::2])\n # Plot the forcing\n if showforcing and self.forcing is not None:\n ax.contour(xx, yy, self.forcing, forcelevs, linewidths=2, colors='darkorchid')\n ax.set_title('relative vorticity [s$^{-1}$] and winds [m s$^{-1}$] at %03d hours' % n)\n # Colorbar\n cax = fig.add_axes([0.05, 0.12, 0.9, 0.03])\n plt.colorbar(cs, cax=cax, orientation='horizontal')\n # Save figure\n if not os.path.isdir(NL.figdir+'/global'): os.makedirs(NL.figdir+'/global')\n plt.savefig('{}/global/zeta_wnd_{:03d}.png'.format(NL.figdir,n), bbox_inches='tight')\n plt.close()\n\n # MAKE REGIONAL HEIGHT & WIND SPEED MAP\n phi = np.divide(psi * NL.omega, NL.g)\n fig, ax = plt.subplots(figsize=(10,6))\n fig.subplots_adjust(bottom=0.2, left=0.05, right=0.95)\n xx, yy = self.bmaps['regional_x'], self.bmaps['regional_y']\n # Calculate wind speed\n wspd = np.sqrt(u**2 + v**2)\n cs = ax.contourf(xx, yy, wspd, windlevs, cmap=plt.cm.viridis, extend='max')\n self.bmaps['regional'].drawcoastlines()\n self.bmaps['regional'].drawcountries()\n self.bmaps['regional'].drawstates()\n hgtconts = ax.contour(xx, yy, phi, hgtlevs, colors='k')\n # Plot the forcing\n if showforcing and self.forcing is not None:\n ax.contour(xx, yy, self.forcing, forcelevs, linewidths=2, colors='darkorchid')\n ax.set_title('geopotential height [m] and wind speed [m s$^{-1}$] at %03d hours' % n)\n # Colorbar\n cax = fig.add_axes([0.05, 0.12, 0.9, 0.03])\n plt.colorbar(cs, cax=cax, orientation='horizontal')\n # Save figure\n if not os.path.isdir(NL.figdir+'/regional'): os.makedirs(NL.figdir+'/regional')\n plt.savefig('{}/regional/hgt_wspd_{:03d}.png'.format(NL.figdir,n), bbox_inches='tight')\n plt.close()\n \n \n###########################################################################################################\n##### Other Utilities #####################################################################################\n###########################################################################################################\n\n\ndef create_basemaps(lons,lats):\n \"\"\" Setup global and regional basemaps for eventual plotting \"\"\"\n print(\"Creating basemaps for plotting\")\n\n long, latg = np.meshgrid(lons,lats)\n\n # Set up a global map\n bmap_globe = Basemap(projection='merc',llcrnrlat=-70, urcrnrlat=70,\n llcrnrlon=0,urcrnrlon=360,lat_ts=20,resolution='c')\n xg,yg = bmap_globe(long,latg)\n \n # Set up a regional map (currently Pacific and N. America)\n bmap_reg = Basemap(projection='merc',llcrnrlat=0,urcrnrlat=65,llcrnrlon=80, \n urcrnrlon=290, lat_ts=20,resolution='l')\n xr,yr = bmap_reg(long,latg)\n\n return {'global' : bmap_globe, \n 'global_x' : xg, \n 'global_y' : yg,\n 'regional' : bmap_reg,\n 'regional_x' : xr, \n 'regional_y' : yr, \n }\n\ndef d_dlamb(field,dlamb):\n \"\"\" Finds a finite-difference approximation to gradient in\n the lambda (longitude) direction\"\"\"\n out = np.divide(np.gradient(field)[1],dlamb) \n return out\n\ndef d_dtheta(field,dtheta):\n \"\"\" Finds a finite-difference approximation to gradient in\n the theta (latitude) direction \"\"\"\n out = np.divide(np.gradient(field)[0],dtheta)\n return out\n\ndef Jacobian(A,B,theta,dtheta,dlamb):\n \"\"\" Returns the Jacobian of two fields in spherical coordinates \"\"\"\n term1 = d_dlamb(A,dlamb) * d_dtheta(B,dtheta)\n term2 = d_dlamb(B,dlamb) * d_dtheta(A,dtheta)\n return 1./(NL.Re**2 * np.cos(theta)) * (term1 - term2)\n\n###########################################################################################################\n\ndef test_case():\n \"\"\"\n Runs an example case: extratropical zonal jets with superimposed sinusoidal NH vorticity\n perturbations and a gaussian vorticity tendency forcing.\n \"\"\"\n from time import time\n start = time()\n \n # 1) LET'S CREATE SOME INITIAL CONDITIONS\n lons = np.arange(0, 360.1, 2.5)\n lats = np.arange(-87.5, 88, 2.5)[::-1]\n lamb, theta = np.meshgrid(lons * np.pi/180., lats * np.pi/180.)\n # Mean state: zonal extratropical jets\n ubar = NL.mag * np.cos(theta) - 30 * np.cos(theta)**3 + 300 * np.sin(theta)**2 * np.cos(theta)**6\n vbar = np.zeros(np.shape(ubar))\n # Initial perturbation: sinusoidal vorticity perturbations\n theta0 = np.deg2rad(NL.pert_center_lat) # center lat = 45 N\n thetaW = np.deg2rad(NL.pert_width) #15\n vort_pert = 0.5*NL.A*np.cos(theta)*np.exp(-((theta-theta0)/thetaW)**2)*np.cos(NL.m*lamb)\n \n # Get U' and V' from this vorticity perturbation\n s = spharm.Spharmt(len(lons), len(lats), gridtype='regular', legfunc='computed', rsphere=NL.Re)\n uprime, vprime = s.getuv(s.grdtospec(vort_pert), np.zeros(np.shape(s.grdtospec(vort_pert))))\n # Full initial conditions dictionary:\n ics = {'u_bar' : ubar,\n 'v_bar' : vbar,\n 'u_prime': uprime,\n 'v_prime': vprime,\n 'lons' : lons,\n 'lats' : lats,\n 'start_time' : datetime(2017,1,1,0)}\n\n # 2) LET'S ALSO FEED IN A GAUSSIAN NH RWS FORCING (CAN BE USED TO CREATE SYNTEHTIC HURRICANES)\n amplitude = NL.forcing_amp # s^-2\n forcing = np.zeros(np.shape(ubar))\n x, y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\n d = np.sqrt(x*x+y*y)\n sigma, mu = 0.5, 0.0\n g = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) # GAUSSIAN CURVE\n source_lat = NL.forcing_lat; source_lon = NL.forcing_lon # The location of the forcing\n lat_i = np.where(lats==source_lat)[0][0]\n lon_i = np.where(lons==source_lon)[0][0]\n if NL.use_forcing == True:\n forcing[lat_i:lat_i+10, lon_i:lon_i+10] = g*amplitude\n else:\n forcing[:,:] = 0\n\n # 3) INTEGRATE!\n model = Model(ics, forcing=forcing)\n model.integrate()\n print('TOTAL INTEGRATION TIME: {:.02f} minutes'.format((time()-start)/60.))\n plt.plot((NL.dt * np.arange(len(model.tot_ke)))/3600., (1 - model.tot_ke/model.expected_ke) * 100)\n #plt.plot(np.arange(len(model.tot_ke)), model.tot_ke, 'o-')\n plt.title('Model Kinetic Energy Error vs. Time Step')\n plt.xlabel(\"Model Time [hr]\")\n plt.ylabel(u'Model Kinetic Energy Error [%]')\n print(\"Expected Kinetic Energy [m^2/s^2]:\", model.expected_ke)\n plt.savefig(NL.figdir + '/model_ke_ts.png', bbox_inches='tight')\n\nif __name__ == '__main__':\n test_case()\n", "sub_path": "barotropic_spectral.py", "file_name": "barotropic_spectral.py", "file_ext": "py", "file_size_in_byte": 20695, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "spharm.Spharmt", "line_number": 44, "usage_type": "call"}, {"api_name": "namelist.Re", "line_number": 44, "usage_type": "attribute"}, {"api_name": "namelist.M", "line_number": 47, "usage_type": "attribute"}, {"api_name": "namelist.M", "line_number": 50, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 68, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 68, "usage_type": "call"}, {"api_name": "namelist.topo", "line_number": 75, "usage_type": "attribute"}, {"api_name": "netCDF4.Dataset", "line_number": 86, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 88, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 93, "usage_type": "call"}, {"api_name": "numpy.load", "line_number": 98, "usage_type": "call"}, {"api_name": "netCDF4.Dataset", "line_number": 103, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 104, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 106, "usage_type": "call"}, {"api_name": "netCDF4.Dataset", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 112, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 114, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 117, "usage_type": "call"}, {"api_name": "netCDF4.Dataset", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.flipud", "line_number": 125, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 133, "usage_type": "call"}, {"api_name": "mpl_toolkits.basemap.interp", "line_number": 134, "usage_type": "call"}, {"api_name": "mpl_toolkits.basemap", "line_number": 134, "usage_type": "name"}, {"api_name": "scipy.ndimage.filters.gaussian_filter", "line_number": 142, "usage_type": "call"}, {"api_name": "namelist.smooth_topo", "line_number": 142, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 159, "usage_type": "attribute"}, {"api_name": "numpy.pi", "line_number": 160, "usage_type": "attribute"}, {"api_name": "numpy.meshgrid", "line_number": 163, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 164, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 167, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 168, "usage_type": "call"}, {"api_name": "namelist.plot_freq", "line_number": 171, "usage_type": "attribute"}, {"api_name": "namelist.ntimes", "line_number": 175, "usage_type": "attribute"}, {"api_name": "namelist.integration_method", "line_number": 180, "usage_type": "attribute"}, {"api_name": "numpy.max", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 182, "usage_type": "call"}, {"api_name": "namelist.dt", "line_number": 186, "usage_type": "attribute"}, {"api_name": "namelist.dt", "line_number": 189, "usage_type": "attribute"}, {"api_name": "namelist.integration_method", "line_number": 191, "usage_type": "attribute"}, {"api_name": "namelist.dt", "line_number": 192, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 207, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 215, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 225, "usage_type": "call"}, {"api_name": "numpy.power", "line_number": 225, "usage_type": "call"}, {"api_name": "namelist.integration_method", "line_number": 228, "usage_type": "attribute"}, {"api_name": "namelist.r", "line_number": 232, "usage_type": "attribute"}, {"api_name": "namelist.dt", "line_number": 235, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 236, "usage_type": "call"}, {"api_name": "namelist.plot_freq", "line_number": 239, "usage_type": "attribute"}, {"api_name": "namelist.omega", "line_number": 249, "usage_type": "attribute"}, {"api_name": "namelist.Re", "line_number": 249, "usage_type": "attribute"}, {"api_name": "namelist.diff_opt", "line_number": 253, "usage_type": "attribute"}, {"api_name": "hyperdiffusion.del4_filter", "line_number": 254, "usage_type": "call"}, {"api_name": "namelist.diff_opt", "line_number": 255, "usage_type": "attribute"}, {"api_name": "hyperdiffusion.apply_des_filter", "line_number": 256, "usage_type": "call"}, {"api_name": "namelist.dt", "line_number": 257, "usage_type": "attribute"}, {"api_name": "namelist.forcing_time", "line_number": 260, "usage_type": "attribute"}, {"api_name": "namelist.use_forcing", "line_number": 261, "usage_type": "attribute"}, {"api_name": "namelist.forcing_time", "line_number": 261, "usage_type": "attribute"}, {"api_name": "namelist.omega", "line_number": 265, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 265, "usage_type": "call"}, {"api_name": "namelist.fluid_height", "line_number": 268, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 274, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 276, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 300, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 300, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.pcolormesh", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 304, "usage_type": "name"}, {"api_name": "numpy.min", "line_number": 304, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 304, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 305, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 305, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlim", "line_number": 306, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 306, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylim", "line_number": 307, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 307, "usage_type": "name"}, {"api_name": "namelist.topo", "line_number": 308, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 310, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 311, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 321, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 321, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 323, "usage_type": "call"}, {"api_name": "os.path", "line_number": 323, "usage_type": "attribute"}, {"api_name": "namelist.figdir", "line_number": 323, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 323, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 324, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 324, "usage_type": "name"}, {"api_name": "namelist.figdir", "line_number": 324, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 325, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 325, "usage_type": "name"}, {"api_name": "numpy.divide", "line_number": 328, "usage_type": "call"}, {"api_name": "namelist.omega", "line_number": 328, "usage_type": "attribute"}, {"api_name": "namelist.g", "line_number": 328, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 329, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 329, "usage_type": "name"}, {"api_name": "numpy.sqrt", "line_number": 333, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.cm", "line_number": 334, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 334, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.colorbar", "line_number": 345, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 345, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 347, "usage_type": "call"}, {"api_name": "os.path", "line_number": 347, "usage_type": "attribute"}, {"api_name": "namelist.figdir", "line_number": 347, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 347, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 348, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 348, "usage_type": "name"}, {"api_name": "namelist.figdir", "line_number": 348, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.close", "line_number": 349, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 349, "usage_type": "name"}, {"api_name": "numpy.meshgrid", "line_number": 361, "usage_type": "call"}, {"api_name": "mpl_toolkits.basemap.Basemap", "line_number": 364, "usage_type": "call"}, {"api_name": "mpl_toolkits.basemap.Basemap", "line_number": 369, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 384, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 384, "usage_type": "call"}, {"api_name": "numpy.divide", "line_number": 390, "usage_type": "call"}, {"api_name": "numpy.gradient", "line_number": 390, "usage_type": "call"}, {"api_name": "namelist.Re", "line_number": 397, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 397, "usage_type": "call"}, {"api_name": "time.time", "line_number": 407, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 410, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 411, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 412, "usage_type": "call"}, {"api_name": "numpy.pi", "line_number": 412, "usage_type": "attribute"}, {"api_name": "namelist.mag", "line_number": 414, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 414, "usage_type": "call"}, {"api_name": "numpy.sin", "line_number": 414, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 415, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 415, "usage_type": "call"}, {"api_name": "numpy.deg2rad", "line_number": 417, "usage_type": "call"}, {"api_name": "namelist.pert_center_lat", "line_number": 417, "usage_type": "attribute"}, {"api_name": "numpy.deg2rad", "line_number": 418, "usage_type": "call"}, {"api_name": "namelist.pert_width", "line_number": 418, "usage_type": "attribute"}, {"api_name": "namelist.A", "line_number": 419, "usage_type": "attribute"}, {"api_name": "numpy.cos", "line_number": 419, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 419, "usage_type": "call"}, {"api_name": "namelist.m", "line_number": 419, "usage_type": "attribute"}, {"api_name": "spharm.Spharmt", "line_number": 422, "usage_type": "call"}, {"api_name": "namelist.Re", "line_number": 422, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 423, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 431, "usage_type": "call"}, {"api_name": "namelist.forcing_amp", "line_number": 434, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 435, "usage_type": "call"}, {"api_name": "numpy.shape", "line_number": 435, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 436, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 436, "usage_type": "call"}, {"api_name": "numpy.sqrt", "line_number": 437, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 439, "usage_type": "call"}, {"api_name": "namelist.forcing_lat", "line_number": 440, "usage_type": "attribute"}, {"api_name": "namelist.forcing_lon", "line_number": 440, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 441, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 442, "usage_type": "call"}, {"api_name": "namelist.use_forcing", "line_number": 443, "usage_type": "attribute"}, {"api_name": "time.time", "line_number": 451, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 452, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 452, "usage_type": "name"}, {"api_name": "namelist.dt", "line_number": 452, "usage_type": "attribute"}, {"api_name": "numpy.arange", "line_number": 452, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 454, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 454, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 455, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 455, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 458, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 458, "usage_type": "name"}, {"api_name": "namelist.figdir", "line_number": 458, "usage_type": "attribute"}]}
+{"seq_id": "321999050", "text": "import time\nimport json\nimport requests\nimport Blinker\nimport Beeper\n\nclass Scheduler(object):\n\n def __init__(self):\n global light\n global beep\n light = Blinker.Blinker()\n beep = Beeper.Beeper()\n\n def getTime(self):\n busStop = json.load(open('bus.json'))\n url = 'https://svc.metrotransit.org/NexTrip/' + busStop['Stop'] + '?format=json'\n rTJson = requests.get(url).json()\n rTStr = str(rTJson[0]['DepartureText'])\n if \"Min\" in rTStr:\n return int(filter(str.isdigit, rTStr))\n else:\n return 20\n\n def put20Minutes(self):\n light.turnOff()\n time.sleep(30)\n\n def put10Minutes(self):\n t_end = time.time() + 30\n while time.time() < t_end:\n light.turnOn()\n\n def put6Minutes(self):\n light.turnOff()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkSlow()\n\n def put4Minutes(self):\n light.turnOff()\n beep.quickBeep()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkFast()\n\n def put3Minutes(self):\n light.turnOff()\n t_end = time.time() + 30\n while time.time() < t_end:\n light.blinkFast()\n", "sub_path": "Scheduler.py", "file_name": "Scheduler.py", "file_ext": "py", "file_size_in_byte": 1264, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "Blinker.Blinker", "line_number": 12, "usage_type": "call"}, {"api_name": "Beeper.Beeper", "line_number": 13, "usage_type": "call"}, {"api_name": "json.load", "line_number": 16, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 18, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 27, "usage_type": "call"}, {"api_name": "time.time", "line_number": 30, "usage_type": "call"}, {"api_name": "time.time", "line_number": 31, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "time.time", "line_number": 37, "usage_type": "call"}, {"api_name": "time.time", "line_number": 43, "usage_type": "call"}, {"api_name": "time.time", "line_number": 44, "usage_type": "call"}, {"api_name": "time.time", "line_number": 49, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}]}
+{"seq_id": "302090387", "text": "import requests\nimport json\n\nMERAKI_ORG = '681155'\nMERAKI_URL = f'https://api.meraki.com/api/v1/organizations/{MERAKI_ORG}/networks'\nMERAKI_X_AUTH = '6bec40cf957de430a6f1f2baa056b99a4fac9ea0'\n\n# payload is an empty dictionary\npayload = {}\n\n# define the necessary headers for Meraki\nheaders = {'X-Cisco-Meraki-API-Key': MERAKI_X_AUTH,\n 'Accept': 'application/json',\n 'Content-type': 'application/json'\n }\n\n# create a variable to store the response of upcoming request\nresponse = requests.request('GET', url=MERAKI_URL, headers=headers, data=payload)\n\n# print the status code and the response itself\nprint(response.status_code)\n\n# print out the resulting networks\nprint(json.dumps(response.json(), indent=2))\n\n", "sub_path": "devasc/8_enterprise netmgmt_platforms_apis/meraki_get_networks.py", "file_name": "meraki_get_networks.py", "file_ext": "py", "file_size_in_byte": 738, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.request", "line_number": 18, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 24, "usage_type": "call"}]}
+{"seq_id": "442952514", "text": "import os\n\nimport numpy as np\nimport tables as tb\n\nfrom pytest import mark\n\nfrom . rwf_io import rwf_writer\n\n\n@mark.parametrize(\"group_name\", (None, 'RD', 'BLR'))\ndef test_rwf_writer(config_tmpdir, group_name):\n\n nevt = 3\n nsensor = 3\n nsample = 10\n table_name = 'testwf'\n\n ofile = os.path.join(config_tmpdir, 'testRWF.h5')\n\n test_data = np.random.randint(10, size = (nevt, nsensor, nsample))\n\n with tb.open_file(ofile, \"w\") as h5out:\n rwf_writer_ = rwf_writer(h5out,\n group_name = group_name,\n table_name = table_name,\n n_sensors = nsensor,\n waveform_length = nsample)\n\n for evt in test_data:\n rwf_writer_(evt)\n\n with tb.open_file(ofile) as h5test:\n if group_name is None:\n group = h5test.root\n else:\n group = getattr(h5test.root, group_name)\n\n\n assert table_name in group\n\n table = getattr(group, table_name)\n assert table.shape == (nevt, nsensor, nsample)\n assert np.all(test_data == table.read())\n", "sub_path": "invisible_cities/io/rwf_io_test.py", "file_name": "rwf_io_test.py", "file_ext": "py", "file_size_in_byte": 1208, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.join", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 21, "usage_type": "attribute"}, {"api_name": "tables.open_file", "line_number": 23, "usage_type": "call"}, {"api_name": "rwf_io.rwf_writer", "line_number": 24, "usage_type": "call"}, {"api_name": "tables.open_file", "line_number": 33, "usage_type": "call"}, {"api_name": "numpy.all", "line_number": 44, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 11, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 11, "usage_type": "name"}]}
+{"seq_id": "163658034", "text": "try:\n from django.conf.urls import patterns, url\nexcept ImportError:\n from django.conf.urls.defaults import patterns, url\n\n\nurlpatterns = patterns('',\n url(r'^$', 'cropduster.views.index', name='cropduster-index'),\n url(r'^crop/', 'cropduster.views.crop', name='cropduster-crop'),\n url(r'^upload/', 'cropduster.views.upload', name='cropduster-upload'),\n url(r'^standalone/', 'cropduster.standalone.views.index', name='cropduster-standalone'),\n)\n", "sub_path": "cropduster/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 463, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.urls.defaults.patterns", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.defaults.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.defaults.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.defaults.url", "line_number": 10, "usage_type": "call"}, {"api_name": "django.conf.urls.defaults.url", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "131641787", "text": "import pytest\nimport pandas as pd\nfrom collections import OrderedDict\nimport os.path\n\nfrom .luck import luck_factor\n\n\nSCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\nclass Case(object):\n def __init__(self, coins, symbol, start_date, end_date, expected):\n self.coins = coins\n self.symbol = symbol\n self.start_date = start_date\n self.end_date = end_date\n self.expected = expected\n\n\nCOINS = pd.read_csv(os.path.join(SCRIPT_DIR, 'coins.csv'))\nCOINS['datetime'] = pd.to_datetime(COINS['date'])\nCOINS.set_index('datetime', inplace=True)\n\n\nTEST_CASES = OrderedDict([\n (\n \"test_case_0\",\n Case(\n coins=pd.DataFrame(\n data=[\n ['BTC', 15404.8, 17513.9, '2017-12-11'],\n ['BTC', 16571.6, 17781.8, '2017-12-12'],\n ['BTC', 16039.7, 17653.1, '2017-12-13']],\n columns=['symbol', 'low', 'high', 'date'],\n index=pd.to_datetime(['2017-12-11', '2017-12-12', '2017-12-13'])\n ),\n symbol='BTC',\n start_date='2017-12-11',\n end_date='2017-12-13',\n expected=1.342650014778795\n )\n ),\n (\n \"test_case_1\",\n Case(\n coins=COINS,\n symbol='BTC',\n start_date='2017-12-11',\n end_date='2017-12-13',\n expected=1.342650014778795\n )\n ),\n (\n \"test_case_2\",\n Case(\n coins=COINS,\n symbol='PPT',\n start_date='2017-09-01',\n end_date='2018-01-10',\n expected=363502397080.77655\n )\n ),\n (\n \"test_case_3\",\n Case(\n coins=COINS,\n symbol='LTC',\n start_date='2017-09-11',\n end_date='2017-12-30',\n expected=110822.93933259304\n )\n ),\n (\n \"test_case_4\",\n Case(\n coins=COINS,\n symbol='ADA',\n start_date='2017-08-11',\n end_date='2017-12-30',\n expected=32104531.358640753\n )\n ),\n (\n \"test_case_5\",\n Case(\n coins=COINS,\n symbol='FUN',\n start_date='2018-04-01',\n end_date='2018-05-01',\n expected=18.464747305540669\n )\n )\n])\n\n\n@pytest.mark.parametrize(\n 'test_case',\n TEST_CASES.values(),\n ids=list(TEST_CASES.keys())\n)\ndef test_luck_factor(test_case):\n factor = luck_factor(\n test_case.coins,\n test_case.symbol,\n test_case.start_date,\n test_case.end_date)\n assert pytest.approx(factor, rel=1e-3) == test_case.expected\n", "sub_path": "hw3_luck/test_public.py", "file_name": "test_public.py", "file_ext": "py", "file_size_in_byte": 2652, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.path.abspath", "line_number": 9, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 9, "usage_type": "name"}, {"api_name": "os.path.path.dirname", "line_number": 9, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path", "line_number": 21, "usage_type": "name"}, {"api_name": "pandas.to_datetime", "line_number": 22, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 26, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 36, "usage_type": "call"}, {"api_name": "luck.luck_factor", "line_number": 103, "usage_type": "call"}, {"api_name": "pytest.approx", "line_number": 108, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 97, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 97, "usage_type": "attribute"}]}
+{"seq_id": "243181223", "text": "from random import randint\nimport math\nimport os\nimport matplotlib.pyplot as plt\n\ndef clear(i):\n print(' \\n' * i)\n\nprint(\"Press Enter to play\")\n\nbalance = 100 ##give player 100 coins\nbet = 0\ncombo = 0\ncnt = 0\n\nst_balance = []\nst_bet = []\nst_reward = []\nst_combo = []\n\nwhile True:\n while True:\n cnt = cnt+1 \n bet = int(input('Place your bet. Remaining coins: ' + str(balance)) or 0)\n \n \n if balance - int(bet) < 0:\n bet=int(input('Insufficient coins. Your balance: ' + str(balance)) or 0) \n else: \n balance = balance - bet\n break\n \n if bet == 0:\n continue\n \n a = randint(1,3)\n b = randint(1,3)\n c = randint(1,3)\n\n## a = 1 \n## b = 1\n## c = 1\n##for debugging\n clear(100)\n print(a, b, c, sep=\",\")\n\n if a == b and a==c:\n combo = combo + 1\n reward = int(bet *10 + (pow((combo - 1),2) * bet))\n balance = balance + reward\n print(\"Congrats... JackPot!!!\")\n if combo > 1:\n print('Combo count: '+str(combo))\n print(\"Now you have \"+str(balance)+\" coins\") \n else:\n print(\"Now you have \"+str(balance)+\" coins\")\n combo = 0\n reward = 0\n \n ##stats[cnt] = [balance, bet, reward, combo]\n\n st_balance.append(balance)\n st_bet.append(bet)\n st_reward.append(reward)\n st_combo.append(combo)\n \n if balance == 0:\n print('Sorry, but you have just lost this game :(')\n x_axis = list(range(0, len(st_balance), 1))\n plt.xlabel('Time')\n plt.ylabel('Your Balance')\n plt.grid(True)\n plt.plot(x_axis, st_balance, 'r')\n plt.axis([0, len(x_axis), 0, max(st_balance)*1.5 ])\n \n plt.show()\n break\n ##print('combo: '+ str(combo)) # for debugging\n", "sub_path": "jackpot.py", "file_name": "jackpot.py", "file_ext": "py", "file_size_in_byte": 1863, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "random.randint", "line_number": 36, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 37, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 70, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 70, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.grid", "line_number": 72, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 72, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 73, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 73, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.axis", "line_number": 74, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 74, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 76, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 76, "usage_type": "name"}]}
+{"seq_id": "161434575", "text": "from game_env import Game\r\nfrom game_net import DeepQNetwork\r\nimport numpy as np\r\n\r\ntrain_steps = 50000\r\n\r\n\r\ndef train_game():\r\n step = 0\r\n scores = []\r\n for episode in range(train_steps):\r\n if step%1000 == 0:\r\n print(\"step:\", step)\r\n score = 0\r\n observation = game.init_map()\r\n print(\"初始地图:\", observation)\r\n moves = []\r\n while(True):\r\n is_done = False\r\n action = RL.choose_action(observation, train=True)\r\n moves.append(action)\r\n print(\"action:\",action)\r\n print(\"observation:\",observation)\r\n # RL take action and get next observation and reward\r\n observation_, reward, is_done = game.move(action)\r\n if reward >= 0:\r\n score += reward\r\n\r\n print(\"observation_:\",observation_, \"reward:\",reward, \"is_done:\",is_done)\r\n RL.store_transition(observation, action, reward, observation_)\r\n if (step > 200) and (step % 5 == 0):\r\n RL.learn()\r\n\r\n # swap observation\r\n observation = observation_\r\n\r\n # break while loop when end of this episode\r\n if is_done:\r\n print(\"moves:\", moves, \"score:\", score)\r\n scores.append(score)\r\n break\r\n step += 1\r\n import matplotlib.pyplot as plt\r\n plt.plot(np.arange(len(scores)), scores)\r\n plt.ylabel('Scores')\r\n plt.xlabel('training steps')\r\n plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n game = Game()\r\n # print(game.init_map())\r\n # print(game.init_map())\r\n RL = DeepQNetwork(n_actions=9,\r\n map_w=4,\r\n map_h=4,\r\n learning_rate=0.01,\r\n reward_decay=0.9,\r\n e_greedy=0.9,\r\n replace_target_iter=300,\r\n memory_size=2000,\r\n e_greedy_increment=0.2,\r\n output_graph=False\r\n )\r\n train_game()\r\n RL.plot_cost()\r\n # print(game.init_map())", "sub_path": "game_ai_4_4/run_this.py", "file_name": "run_this.py", "file_ext": "py", "file_size_in_byte": 2110, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.pyplot.plot", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 44, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 44, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "game_env.Game", "line_number": 50, "usage_type": "call"}, {"api_name": "game_net.DeepQNetwork", "line_number": 53, "usage_type": "call"}]}
+{"seq_id": "97757247", "text": "import tornado.web\nimport tornado.httpserver\nimport tornado.ioloop\n\nimport tornado.options\n\nimport handler.realtime_plant_performance_handler as RealtimePlantHandler\nimport handler.realtime_plant_turbine_handler as RealtimeAllTurbineHandler\nimport handler.realtime_u2_turbine_handler as RealtimeU2TuebineHandler\nimport handler.RedisInfoMonitor_handler as RedisHandler\n\nclient = list() \n \nclass aboutHandler(tornado.web.RequestHandler):\n\n def get(self):\n self.render(\"about.html\") \n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", RealtimePlantHandler.realtimeHandler), \n (r\"/realtime_plant_turbine/\", RealtimeAllTurbineHandler.realtimeHandler),\n (r\"/realtime_u2_turbine/\", RealtimeU2TuebineHandler.realtimeHandler),\n \n (r\"/RedisInfoMonitor/\", RedisHandler.RedisInfoHandler),\n (r\"/about/\", aboutHandler)\n ]\n \n settings = {\n 'template_path': 'templates',\n 'static_path': 'static'\n }\n tornado.web.Application.__init__(self, handlers, **settings)\n\nif __name__ == '__main__':\n tornado.options.parse_command_line()\n \n app = Application()\n server = tornado.httpserver.HTTPServer(app)\n server.listen(8000)\n tornado.ioloop.IOLoop.instance().start()\n \n\n", "sub_path": "ReadExcelData/app.py", "file_name": "app.py", "file_ext": "py", "file_size_in_byte": 1358, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "tornado.web.web", "line_number": 14, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 14, "usage_type": "name"}, {"api_name": "tornado.web.web", "line_number": 19, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 19, "usage_type": "name"}, {"api_name": "handler.realtime_plant_performance_handler.realtimeHandler", "line_number": 22, "usage_type": "attribute"}, {"api_name": "handler.realtime_plant_performance_handler", "line_number": 22, "usage_type": "name"}, {"api_name": "handler.realtime_plant_turbine_handler.realtimeHandler", "line_number": 23, "usage_type": "attribute"}, {"api_name": "handler.realtime_plant_turbine_handler", "line_number": 23, "usage_type": "name"}, {"api_name": "handler.realtime_u2_turbine_handler.realtimeHandler", "line_number": 24, "usage_type": "attribute"}, {"api_name": "handler.realtime_u2_turbine_handler", "line_number": 24, "usage_type": "name"}, {"api_name": "handler.RedisInfoMonitor_handler.RedisInfoHandler", "line_number": 26, "usage_type": "attribute"}, {"api_name": "handler.RedisInfoMonitor_handler", "line_number": 26, "usage_type": "name"}, {"api_name": "tornado.web.web.Application.__init__", "line_number": 34, "usage_type": "call"}, {"api_name": "tornado.web.web", "line_number": 34, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 34, "usage_type": "name"}, {"api_name": "tornado.web.options.parse_command_line", "line_number": 37, "usage_type": "call"}, {"api_name": "tornado.web.options", "line_number": 37, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 37, "usage_type": "name"}, {"api_name": "tornado.web.httpserver.HTTPServer", "line_number": 40, "usage_type": "call"}, {"api_name": "tornado.web.httpserver", "line_number": 40, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 40, "usage_type": "name"}, {"api_name": "tornado.web.ioloop.IOLoop.instance", "line_number": 42, "usage_type": "call"}, {"api_name": "tornado.web.ioloop", "line_number": 42, "usage_type": "attribute"}, {"api_name": "tornado.web", "line_number": 42, "usage_type": "name"}]}
+{"seq_id": "144157679", "text": "import sys\nimport os\n\nfrom zope.interface import implements\nfrom twisted.web import error as web_error\nfrom twisted.internet import error\nfrom twisted.web._newclient import ResponseDone\nfrom twisted.python import failure\n\nfrom feat.agencies.database import Connection, ChangeListener\nfrom feat.common import log, defer, time\nfrom feat.agencies import common\n\nfrom feat.agencies.interface import *\nfrom feat.interface.view import *\n\n\nfrom feat import extern\n# Add feat/extern/paisley to the load path\nsys.path.insert(0, os.path.join(extern.__path__[0], 'paisley'))\nfrom paisley.changes import ChangeNotifier\nfrom paisley.client import CouchDB\n\n\nDEFAULT_DB_HOST = \"localhost\"\nDEFAULT_DB_PORT = 5984\nDEFAULT_DB_NAME = \"feat\"\n\n\nclass Database(common.ConnectionManager, log.LogProxy, ChangeListener):\n\n implements(IDbConnectionFactory, IDatabaseDriver)\n\n log_category = \"database\"\n\n def __init__(self, host, port, db_name):\n common.ConnectionManager.__init__(self)\n log.LogProxy.__init__(self, log.FluLogKeeper())\n ChangeListener.__init__(self, self)\n\n self.semaphore = defer.DeferredSemaphore(1)\n self.paisley = None\n self.db_name = None\n self.host = None\n self.port = None\n self.notifier = None\n\n self.retry = 0\n self.reconnector = None\n\n self._configure(host, port, db_name)\n\n def reconfigure(self, host, port, name):\n if self.notifier.isRunning():\n self.notifier.stop()\n self._configure(host, port, name)\n self._setup_notifier()\n\n def show_status(self):\n eta = self.reconnector and self.reconnector.active() and \\\n time.left(self.reconnector.getTime())\n return \"Database\", self.is_connected(), self.host, self.port, eta\n\n ### IDbConnectionFactory\n\n def get_connection(self):\n return Connection(self)\n\n ### IDatabaseDriver\n\n def open_doc(self, doc_id):\n return self._paisley_call(self.paisley.openDoc, self.db_name, doc_id)\n\n def save_doc(self, doc, doc_id=None):\n return self._paisley_call(self.paisley.saveDoc,\n self.db_name, doc, doc_id)\n\n def delete_doc(self, doc_id, revision):\n return self._paisley_call(self.paisley.deleteDoc,\n self.db_name, doc_id, revision)\n\n def create_db(self):\n return self._paisley_call(self.paisley.createDB,\n self.db_name)\n\n def listen_changes(self, doc_ids, callback):\n d = ChangeListener.listen_changes(self, doc_ids, callback)\n d.addCallback(defer.bridge_param, self._setup_notifier)\n return d\n\n def cancel_listener(self, listener_id):\n ChangeListener.cancel_listener(self, listener_id)\n return self._setup_notifier()\n\n def query_view(self, factory, **options):\n factory = IViewFactory(factory)\n d = self._paisley_call(self.paisley.openView,\n self.db_name, DESIGN_DOC_ID, factory.name,\n **options)\n d.addCallback(self._parse_view_result)\n return d\n\n ### paisleys ChangeListener interface\n\n def changed(self, change):\n # The change parameter is just an ugly effect of json unserialization\n # of the couchdb output. It can be many different things, hence the\n # strange logic above.\n if \"changes\" in change:\n doc_id = change['id']\n for line in change['changes']:\n # The changes are analized when there is not http request\n # pending. Otherwise it can result in race condition problem.\n self.semaphore.run(self._trigger_change, doc_id, line['rev'])\n else:\n self.info('Bizare notification received from CouchDB: %r', change)\n\n def connectionLost(self, reason):\n if reason.check(error.ConnectionDone):\n # expected just pass\n return\n elif reason.check(ResponseDone):\n self.debug(\"CouchDB closed the notification listener. This might \"\n \"indicate missconfiguration. Take look at it\")\n return\n elif reason.check(error.ConnectionRefusedError):\n self.retry += 1\n wait = min(2**(self.retry - 1), 300)\n self.debug('CouchDB refused connection for %d time. '\n 'This indicates missconfiguration or temporary '\n 'network problem. Will try to reconnect in %d seconds.',\n self.retry, wait)\n self.reconnector = time.callLater(wait, self._setup_notifier)\n self._on_disconnected()\n return\n else:\n # FIXME handle disconnection when network is down\n self._on_disconnected()\n self.warning('Connection to db lost with reason: %r', reason)\n return self._setup_notifier()\n\n ### private\n\n def _configure(self, host, port, name):\n self._cancel_reconnector()\n self.host, self.port = host, port\n self.paisley = CouchDB(host, port)\n self.db_name = name\n self.notifier = ChangeNotifier(self.paisley, self.db_name)\n self.notifier.addListener(self)\n\n # ping database to figure trigger changing state to connected\n d = self._paisley_call(self.paisley.listDB)\n d.addErrback(failure.Failure.trap, NotConnectedError)\n\n def _parse_view_result(self, resp):\n assert \"rows\" in resp\n\n for row in resp[\"rows\"]:\n yield row[\"key\"], row[\"value\"]\n\n def _setup_notifier(self):\n doc_ids = self._extract_doc_ids()\n self.log('Setting up the notifier passing. Doc_ids: %r.',\n doc_ids)\n if self.notifier.isRunning():\n self.notifier.stop()\n if len(doc_ids) == 0:\n # Don't run listner if it is not needed,\n # cancel reconnector if one is running.\n if self.reconnector and self.reconnector.active():\n self.reconnector.cancel()\n self.reconnector = None\n return\n\n d = self.notifier.start(\n heartbeat=1000)\n d.addCallback(self._connected)\n d.addErrback(self.connectionLost)\n d.addErrback(failure.Failure.trap, NotConnectedError)\n return d\n\n def _connected(self, _):\n self.debug('Established persistent connection for receiving '\n 'notifications.')\n self._on_connected()\n self._cancel_reconnector()\n\n def _cancel_reconnector(self):\n if self.reconnector:\n if self.reconnector.active():\n self.reconnector.cancel()\n self.reconnector = None\n self.retry = 0\n\n def _paisley_call(self, method, *args, **kwargs):\n # It is necessarry to acquire the lock to perform the http request\n # because we need to be sure that we are not in the middle of sth\n # while analizing the change notification\n d = self.semaphore.run(method, *args, **kwargs)\n d.addCallback(defer.bridge_param, self._on_connected)\n d.addErrback(self._error_handler)\n return d\n\n def _error_handler(self, failure):\n exception = failure.value\n msg = failure.getErrorMessage()\n if isinstance(exception, web_error.Error):\n status = int(exception.status)\n if status == 409:\n raise ConflictError(msg)\n elif status == 404:\n raise NotFoundError(msg)\n else:\n self.info(exception.response)\n raise NotImplementedError(\n 'Behaviour for response code %d not define yet, FIXME!' %\n status)\n elif failure.check(error.ConnectionRefusedError):\n self._on_disconnected()\n raise NotConnectedError(\"Database connection refused.\")\n else:\n failure.raiseException()\n", "sub_path": "src/feat/agencies/net/database.py", "file_name": "database.py", "file_ext": "py", "file_size_in_byte": 7945, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "sys.path.insert", "line_number": 20, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "feat.extern.__path__", "line_number": 20, "usage_type": "attribute"}, {"api_name": "feat.extern", "line_number": 20, "usage_type": "name"}, {"api_name": "feat.agencies.common.ConnectionManager", "line_number": 30, "usage_type": "attribute"}, {"api_name": "feat.agencies.common", "line_number": 30, "usage_type": "name"}, {"api_name": "feat.common.log.LogProxy", "line_number": 30, "usage_type": "attribute"}, {"api_name": "feat.common.log", "line_number": 30, "usage_type": "name"}, {"api_name": "feat.agencies.database.ChangeListener", "line_number": 30, "usage_type": "name"}, {"api_name": "zope.interface.implements", "line_number": 32, "usage_type": "call"}, {"api_name": "feat.agencies.common.ConnectionManager.__init__", "line_number": 37, "usage_type": "call"}, {"api_name": "feat.agencies.common.ConnectionManager", "line_number": 37, "usage_type": "attribute"}, {"api_name": "feat.agencies.common", "line_number": 37, "usage_type": "name"}, {"api_name": "feat.common.log.LogProxy.__init__", "line_number": 38, "usage_type": "call"}, {"api_name": "feat.common.log.LogProxy", "line_number": 38, "usage_type": "attribute"}, {"api_name": "feat.common.log", "line_number": 38, "usage_type": "name"}, {"api_name": "feat.common.log.FluLogKeeper", "line_number": 38, "usage_type": "call"}, {"api_name": "feat.agencies.database.ChangeListener.__init__", "line_number": 39, "usage_type": "call"}, {"api_name": "feat.agencies.database.ChangeListener", "line_number": 39, "usage_type": "name"}, {"api_name": "feat.common.defer.DeferredSemaphore", "line_number": 41, "usage_type": "call"}, {"api_name": "feat.common.defer", "line_number": 41, "usage_type": "name"}, {"api_name": "feat.common.time.left", "line_number": 61, "usage_type": "call"}, {"api_name": "feat.common.time", "line_number": 61, "usage_type": "name"}, {"api_name": "feat.agencies.database.Connection", "line_number": 67, "usage_type": "call"}, {"api_name": "feat.agencies.database.ChangeListener.listen_changes", "line_number": 87, "usage_type": "call"}, {"api_name": "feat.agencies.database.ChangeListener", "line_number": 87, "usage_type": "name"}, {"api_name": "feat.common.defer.bridge_param", "line_number": 88, "usage_type": "attribute"}, {"api_name": "feat.common.defer", "line_number": 88, "usage_type": "name"}, {"api_name": "feat.agencies.database.ChangeListener.cancel_listener", "line_number": 92, "usage_type": "call"}, {"api_name": "feat.agencies.database.ChangeListener", "line_number": 92, "usage_type": "name"}, {"api_name": "twisted.internet.error.ConnectionDone", "line_number": 119, "usage_type": "attribute"}, {"api_name": "twisted.internet.error", "line_number": 119, "usage_type": "name"}, {"api_name": "twisted.web._newclient.ResponseDone", "line_number": 122, "usage_type": "argument"}, {"api_name": "twisted.internet.error.ConnectionRefusedError", "line_number": 126, "usage_type": "attribute"}, {"api_name": "twisted.internet.error", "line_number": 126, "usage_type": "name"}, {"api_name": "feat.common.time.callLater", "line_number": 133, "usage_type": "call"}, {"api_name": "feat.common.time", "line_number": 133, "usage_type": "name"}, {"api_name": "paisley.client.CouchDB", "line_number": 147, "usage_type": "call"}, {"api_name": "paisley.changes.ChangeNotifier", "line_number": 149, "usage_type": "call"}, {"api_name": "twisted.python.failure.Failure", "line_number": 154, "usage_type": "attribute"}, {"api_name": "twisted.python.failure", "line_number": 154, "usage_type": "name"}, {"api_name": "twisted.python.failure.Failure", "line_number": 180, "usage_type": "attribute"}, {"api_name": "twisted.python.failure", "line_number": 180, "usage_type": "name"}, {"api_name": "feat.common.defer.bridge_param", "line_number": 201, "usage_type": "attribute"}, {"api_name": "feat.common.defer", "line_number": 201, "usage_type": "name"}, {"api_name": "twisted.python.failure.value", "line_number": 206, "usage_type": "attribute"}, {"api_name": "twisted.python.failure", "line_number": 206, "usage_type": "name"}, {"api_name": "twisted.python.failure.getErrorMessage", "line_number": 207, "usage_type": "call"}, {"api_name": "twisted.python.failure", "line_number": 207, "usage_type": "name"}, {"api_name": "twisted.web.error.Error", "line_number": 208, "usage_type": "attribute"}, {"api_name": "twisted.web.error", "line_number": 208, "usage_type": "name"}, {"api_name": "twisted.python.failure.check", "line_number": 219, "usage_type": "call"}, {"api_name": "twisted.python.failure", "line_number": 219, "usage_type": "name"}, {"api_name": "twisted.internet.error.ConnectionRefusedError", "line_number": 219, "usage_type": "attribute"}, {"api_name": "twisted.internet.error", "line_number": 219, "usage_type": "name"}, {"api_name": "twisted.python.failure.raiseException", "line_number": 223, "usage_type": "call"}, {"api_name": "twisted.python.failure", "line_number": 223, "usage_type": "name"}]}
+{"seq_id": "223058857", "text": "import theano\nimport numpy as np\nfrom utils import pdf\nimport theano.tensor as T\nfrom lasagne.random import get_rng\nfrom lasagne.layers.base import Layer\nfrom lasagne import layers, updates\nfrom lasagne.init import Constant, GlorotUniform, Normal\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\nfrom lasagne.nonlinearities import rectify, identity, softmax, sigmoid\n\nclass DenseLayer(Layer):\n def __init__(self, incoming, num_units, W=Normal(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DenseLayer, self).__init__(incoming, **kwargs)\n\n self.name = 'Dense'\n self.mode = 'none'\n self.p, self.num_units, num_inputs = p, num_units, int(np.prod(self.input_shape[1:]))\n self.nonlinearity = (identity if nonlinearity is None else nonlinearity)\n self.W = self.add_param(W, (num_inputs, num_units), name=\"W\")\n self.W = updates.norm_constraint(self.W, 3)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.num_inputs = int(np.prod(self.input_shape[1:]))\n\n if b is None:\n self.b = None\n else:\n self.b = self.add_param(b, (num_units,), name=\"b\", regularizable=False)\n\n def get_output_shape_for(self, input_shape):\n return (input_shape[0], self.num_units)\n\n def get_output_for(self, input, deterministic=False, **kwargs):\n if input.ndim > 2:\n input = input.flatten(2)\n\n return self.get_output_for_(input, deterministic)\n\n def get_output_for_(self, input, deterministic):\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def eval_reg(self):\n return 0\n\n def get_p(self):\n return -1\n\nclass DenseBinaryDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=Normal(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DenseBinaryDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self.name = 'Dense + DropOut'\n self.num_updates = 0\n\n def get_output_for_(self, input, deterministic):\n input_shape = input.shape if any(s is None for s in self.input_shape) else self.input_shape\n\n if not (deterministic or self.p == 0):\n input /= (1 - self.p)\n input *= self._srng.binomial(input_shape, p=1 - self.p, dtype=input.dtype)\n\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.p\n\nclass DensePreGaussianDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DensePreGaussianDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.alpha = T.sqrt(p / (1 - p))\n self.name = 'DenseGaussianDropOut'\n\n def get_output_for_(self, input, deterministic):\n if not (deterministic or self.p == 0):\n input *= self._srng.normal(input.shape, avg=1.0, std=self.alpha)\n\n return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.alpha.eval()\n\nclass DensePosGaussianDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify, p=0.5, **kwargs):\n super(DensePosGaussianDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p, **kwargs)\n self._srng = RandomStreams(get_rng().randint(1, 2147462579))\n self.alpha = T.sqrt(p / (1 - p))\n self.name = 'DensePosGaussianDropOut'\n\n def get_output_for_(self, input, deterministic):\n if not (deterministic or self.p == 0):\n mu, sigma = T.dot(input, self.W), T.sqrt(self.alpha * T.dot(input * input, self.W * self.W))\n activation = self._srng.normal(mu.shape, avg=mu, std=sigma)\n else:\n activation = T.dot(input, self.W)\n\n return self.nonlinearity(activation + self.b.dimshuffle('x', 0))\n\n def get_p(self):\n return self.alpha.eval()\n\nclass DenseVarDropOut(DenseLayer):\n def __init__(self, incoming, num_units, W=GlorotUniform(), b=Constant(0.), nonlinearity=rectify,\n p=0.5, mode='layer', restr='sigmoid'):\n super(DenseVarDropOut, self).__init__(incoming, num_units, W, b, nonlinearity, p)\n\n self.name, self.mode = 'Var', mode\n\n if restr not in ['sigmoid', 'rectify', 'exp']:\n raise Exception('alpha_restriction should be: sigmoid, rectify, exp instead of %s' % mode)\n if restr == 'sigmoid':\n self.bound_function, self.reverse_bf = lambda x: 1.0 * T.nnet.sigmoid(x), lambda x: np.log(x / (1 - x)) * (1.0/1.0)\n if restr == 'rectify':\n self.bound_function, self.reverse_bf = T.nnet.relu, lambda x: x\n if restr == 'exp':\n self.bound_function, self.reverse_bf = np.exp, np.log\n\n if mode not in ['fixing', 'model', 'layer', 'features', 'neurons', 'weights']:\n raise Exception('mode should be: fixing, layer, features, neuron, weights instead of %s' % mode)\n alpha = Constant(self.reverse_bf(p / (1 - p)))\n if mode == 'fixing':\n self.alpha = self.add_param(alpha, (), name=\"alpha_fixing\", trainable=False)\n if mode == 'model':\n if self.input_layer.name == 'Input' or self.input_layer.mode == 'fixing':\n self.alpha = self.add_param(alpha, (), name=\"alpha_model\")\n else:\n self.alpha = self.input_layer.alpha\n if mode == 'layer':\n self.alpha = self.add_param(alpha, (), name=\"alpha_layer\")\n alpha = Normal(0.1, self.reverse_bf(p / (1 - p)))\n if mode == 'features':\n self.alpha = self.add_param(alpha, (self.num_inputs, ), name=\"alpha_features\")\n if mode == 'neurons':\n self.alpha = self.add_param(alpha, (self.num_units, ), name=\"alpha_neurons\")\n if mode == 'weights':\n self.alpha = self.add_param(alpha, (self.num_inputs, self.num_units), name=\"alpha_weights\")\n\n def get_output_for_(self, input, deterministic):\n self.input = input\n if deterministic:\n activation = T.dot(input, self.W)\n else:\n alpha = self.bound_function(self.alpha)\n if self.mode == 'features':\n mu, sigma = T.dot(input, self.W), T.sqrt(T.dot(input * input, (alpha * (self.W * self.W).T).T))\n else:\n mu, sigma = T.dot(input, self.W), T.sqrt(T.dot(input * input, alpha * self.W * self.W))\n\n activation = mu + sigma * self._srng.normal(mu.shape, avg=0, std=1)\n\n activation = activation + self.b.dimshuffle('x', 0)\n return self.nonlinearity(activation)\n\n def eval_reg(self):\n alpha = self.bound_function(self.alpha)\n regf = lambda a: -(0.5 * T.log1p(np.exp(-T.log(a))) - (0.03 + 1.0 / (1.0 + T.exp(-(1.5 * (np.log(a) + 1.3)))) * 0.64))\n\n if self.mode in ['fixing', 'model', 'layer']:\n reg = regf(alpha) * self.num_units * self.num_inputs\n if self.mode == 'features':\n reg = regf(alpha).sum() * self.num_units\n if self.mode == 'neurons':\n reg = regf(alpha).sum() * self.num_inputs\n if self.mode == 'weights':\n reg = regf(alpha).sum()\n\n return - reg\n\n def get_p(self):\n alpha = self.alpha.get_value()\n alpha = self.bound_function(alpha)\n p = alpha\n\n return p if isinstance(p, np.float64) or isinstance(p, np.ndarray) else p.eval()\n\nclass Conv2DLayer(layers.Conv2DLayer):\n def __init__(self, incoming, num_filters, filter_size, max_norm=3, **kwargs):\n super(Conv2DLayer, self).__init__(incoming, num_filters, filter_size, **kwargs)\n self.W = updates.norm_constraint(self.W, max_norm=max_norm)\n\nclass MaxPool2DLayer(layers.MaxPool2DLayer):\n pass\n\nclass InputLayer(layers.InputLayer):\n pass\n\n", "sub_path": "nets/layers.py", "file_name": "layers.py", "file_ext": "py", "file_size_in_byte": 8003, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "lasagne.layers.base.Layer", "line_number": 12, "usage_type": "name"}, {"api_name": "lasagne.init.Normal", "line_number": 13, "usage_type": "call"}, {"api_name": "lasagne.init.Constant", "line_number": 13, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.rectify", "line_number": 13, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 18, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.identity", "line_number": 19, "usage_type": "name"}, {"api_name": "lasagne.updates.norm_constraint", "line_number": 21, "usage_type": "call"}, {"api_name": "lasagne.updates", "line_number": 21, "usage_type": "name"}, {"api_name": "theano.sandbox.rng_mrg.MRG_RandomStreams", "line_number": 22, "usage_type": "call"}, {"api_name": "lasagne.random.get_rng", "line_number": 22, "usage_type": "call"}, {"api_name": "numpy.prod", "line_number": 23, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 40, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 40, "usage_type": "name"}, {"api_name": "lasagne.init.Normal", "line_number": 49, "usage_type": "call"}, {"api_name": "lasagne.init.Constant", "line_number": 49, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.rectify", "line_number": 49, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 61, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 61, "usage_type": "name"}, {"api_name": "lasagne.init.GlorotUniform", "line_number": 67, "usage_type": "call"}, {"api_name": "lasagne.init.Constant", "line_number": 67, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.rectify", "line_number": 67, "usage_type": "name"}, {"api_name": "theano.sandbox.rng_mrg.MRG_RandomStreams", "line_number": 69, "usage_type": "call"}, {"api_name": "lasagne.random.get_rng", "line_number": 69, "usage_type": "call"}, {"api_name": "theano.tensor.sqrt", "line_number": 70, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 70, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 77, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 77, "usage_type": "name"}, {"api_name": "lasagne.init.GlorotUniform", "line_number": 83, "usage_type": "call"}, {"api_name": "lasagne.init.Constant", "line_number": 83, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.rectify", "line_number": 83, "usage_type": "name"}, {"api_name": "theano.sandbox.rng_mrg.MRG_RandomStreams", "line_number": 85, "usage_type": "call"}, {"api_name": "lasagne.random.get_rng", "line_number": 85, "usage_type": "call"}, {"api_name": "theano.tensor.sqrt", "line_number": 86, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 86, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 91, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 91, "usage_type": "name"}, {"api_name": "theano.tensor.sqrt", "line_number": 91, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 94, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 94, "usage_type": "name"}, {"api_name": "lasagne.init.GlorotUniform", "line_number": 102, "usage_type": "call"}, {"api_name": "lasagne.init.Constant", "line_number": 102, "usage_type": "call"}, {"api_name": "lasagne.nonlinearities.rectify", "line_number": 102, "usage_type": "name"}, {"api_name": "theano.tensor.nnet.sigmoid", "line_number": 111, "usage_type": "call"}, {"api_name": "theano.tensor.nnet", "line_number": 111, "usage_type": "attribute"}, {"api_name": "theano.tensor", "line_number": 111, "usage_type": "name"}, {"api_name": "numpy.log", "line_number": 111, "usage_type": "call"}, {"api_name": "theano.tensor.nnet", "line_number": 113, "usage_type": "attribute"}, {"api_name": "theano.tensor", "line_number": 113, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 115, "usage_type": "attribute"}, {"api_name": "numpy.log", "line_number": 115, "usage_type": "attribute"}, {"api_name": "lasagne.init.Constant", "line_number": 119, "usage_type": "call"}, {"api_name": "lasagne.init.Normal", "line_number": 129, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 140, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 140, "usage_type": "name"}, {"api_name": "theano.tensor.dot", "line_number": 144, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 144, "usage_type": "name"}, {"api_name": "theano.tensor.sqrt", "line_number": 144, "usage_type": "call"}, {"api_name": "theano.tensor.dot", "line_number": 146, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 146, "usage_type": "name"}, {"api_name": "theano.tensor.sqrt", "line_number": 146, "usage_type": "call"}, {"api_name": "theano.tensor.log1p", "line_number": 155, "usage_type": "call"}, {"api_name": "theano.tensor", "line_number": 155, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 155, "usage_type": "call"}, {"api_name": "theano.tensor.log", "line_number": 155, "usage_type": "call"}, {"api_name": "theano.tensor.exp", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 155, "usage_type": "call"}, {"api_name": "numpy.float64", "line_number": 173, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 173, "usage_type": "attribute"}, {"api_name": "lasagne.layers.Conv2DLayer", "line_number": 175, "usage_type": "attribute"}, {"api_name": "lasagne.layers", "line_number": 175, "usage_type": "name"}, {"api_name": "lasagne.updates.norm_constraint", "line_number": 178, "usage_type": "call"}, {"api_name": "lasagne.updates", "line_number": 178, "usage_type": "name"}, {"api_name": "lasagne.layers.MaxPool2DLayer", "line_number": 180, "usage_type": "attribute"}, {"api_name": "lasagne.layers", "line_number": 180, "usage_type": "name"}, {"api_name": "lasagne.layers.InputLayer", "line_number": 183, "usage_type": "attribute"}, {"api_name": "lasagne.layers", "line_number": 183, "usage_type": "name"}]}
+{"seq_id": "69891277", "text": "# coding:iso-8859-9 Türkçe\r\n# p_31601.py: Sıfır yoğuşmalı -3/+3 dağılımlı tesadüfi gauss histogramı örneği.\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\n#from p_315 import Renk\r\n\r\ngaussSayıları = np.random.normal (size=10000)\r\n\r\nmp.title (\"Gauss Histogram'ı\")\r\nmp.xlabel (\"Gauss Sayıları\")\r\nmp.ylabel (\"Sayıların Tekrarlanma Sıklığı\")\r\nmp.hist (gaussSayıları)\r\n\r\nmp.show()\r\n#-------------------------------------------------------------------------------------------------------\r\n\r\nmp.style.use (\"dark_background\")\r\n\r\nmp.title (\"Gauss Histogram'ı\")\r\nmp.xlabel (\"Gauss Sayıları\")\r\nmp.ylabel (\"Sayıların Tekrarlanma Sıklığı\")\r\nn, kutular, yamalar = mp.hist (gaussSayıları)\r\n\r\nmp.show()\r\n\r\nprint (\"Y=n (kutu boyu-tekrar sıklığı) ve toplam frekans:\\n\", n, \" +=\", sum(n), sep=\"\")\r\nprint (\"\\nX=kutular:\\n\", kutular, sep=\"\")\r\nprint (\"kutular arası fark (kutu genişliği):\", (kutular [1] - kutular [0]) )\r\nprint (\"\\nyamalar:\", yamalar)\r\nfor i in range (len (yamalar)): print (\"yama[\", i, \"]: \", yamalar [i], sep=\"\")\r\n\r\n\r\n\"\"\"Çıktı:\r\n>python p_31601.py\r\nY=n (kutu boyu-tekrar sıklığı) ve toplam frekans:\r\n[ 19. 159. 639. 1844. 2871. 2518. 1393. 459. 89. 9.] +=10000.0\r\n\r\nX=kutular:\r\n[-3.64670043 -2.89409171 -2.14148299 -1.38887427 -0.63626555 0.11634317\r\n 0.86895189 1.62156061 2.37416933 3.12677805 3.87938677]\r\nkutular arası fark (kutu genişliği): 0.7526087198614606\r\n\r\nyamalar: \r\nyama[0]: Rectangle(xy=(-3.6467, 0), width=0.752609, height=19, angle=0)\r\nyama[1]: Rectangle(xy=(-2.89409, 0), width=0.752609, height=159, angle=0)\r\nyama[2]: Rectangle(xy=(-2.14148, 0), width=0.752609, height=639, angle=0)\r\nyama[3]: Rectangle(xy=(-1.38887, 0), width=0.752609, height=1844, angle=0)\r\nyama[4]: Rectangle(xy=(-0.636266, 0), width=0.752609, height=2871, angle=0)\r\nyama[5]: Rectangle(xy=(0.116343, 0), width=0.752609, height=2518, angle=0)\r\nyama[6]: Rectangle(xy=(0.868952, 0), width=0.752609, height=1393, angle=0)\r\nyama[7]: Rectangle(xy=(1.62156, 0), width=0.752609, height=459, angle=0)\r\nyama[8]: Rectangle(xy=(2.37417, 0), width=0.752609, height=89, angle=0)\r\nyama[9]: Rectangle(xy=(3.12678, 0), width=0.752609, height=9, angle=0)\r\n\"\"\"", "sub_path": "Bernd Klein (520) ile Python/p_31601.py", "file_name": "p_31601.py", "file_ext": "py", "file_size_in_byte": 2232, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.random.normal", "line_number": 8, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 8, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.title", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 10, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 13, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 13, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 15, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 15, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.style.use", "line_number": 18, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.style", "line_number": 18, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot", "line_number": 18, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 20, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 20, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 21, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 21, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 22, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 22, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.hist", "line_number": 23, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 23, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 25, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 25, "usage_type": "name"}]}
+{"seq_id": "377290999", "text": "import os\nimport gensim.downloader as api\nfrom gensim.models.doc2vec import Doc2Vec\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nimport pandas as pd\n\nfrom modAL.uncertainty import uncertainty_sampling, margin_sampling, entropy_sampling\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\nROOT = os.path.abspath( os.path.dirname( __file__ ) )\nDATA_PATH = os.path.join( ROOT, '..', 'data' )\n\nfrom sio_server import Server\n\nt_path = os.path.abspath(os.path.join(DATA_PATH, \"processed\", \"t-davidson_processed.pkl\"))\np_path = os.path.abspath(os.path.join(DATA_PATH, \"processed\", \"personal_processed.pkl\"))\n\ndef main():\n t_davidson = pd.read_pickle(t_path)\n personal = pd.read_pickle(p_path)\n #%% ----------------------------------------------------------------word embeddings\n print(\"downloading pre-trained GloVe model...\")\n glove = api.load('glove-twitter-25')\n print(\"done.\")\n #%% ----------------------------------------------------------------doc2vec\n doc2vec = Doc2Vec(vector_size=50, min_count=2, epochs=10)\n #%% ----------------------------------------------------------------tfidf\n tfidf = TfidfVectorizer(\n ngram_range=(1, 3),\n max_features=8000,\n min_df=1,\n max_df=0.75\n )\n #%% ----------------------------------------------------------------\n options = {\n 'classifiers': [\n {'name': 'Logistic Regression', 'classifier': LogisticRegression(class_weight='balanced', solver='liblinear', random_state=42)},\n {'name': 'Linear SVM', 'classifier': SVC(class_weight='balanced', kernel='linear', probability=True, random_state=42)},\n {'name': 'Random Forest', 'classifier': RandomForestClassifier(class_weight='balanced', random_state=42, n_jobs= -1)},\n {'name': 'K Nearest Neighbors', 'classifier': KNeighborsClassifier(n_neighbors=2, n_jobs= -1)}],\n 'datasets': [\n {'name': 'T Davidson Hate Speech/Offensive Language',\n 'df': t_davidson,\n 'targets': [\n {'val': 0,'name': 'hate speech'},\n {'val': 1,'name': 'offensive language'},\n {'val': 2,'name': 'neither'}]\n },\n {'name': 'Project Dataset',\n 'df': personal,\n 'targets': [\n {'val': 0,'name': 'non-malicious'},\n {'val': 1,'name': 'malicious'}]\n }],\n 'vectorizers': [\n {'name': 'TF IDF Vectorizer', 'vectorizer': tfidf},\n {'name': 'GloVe Word Embeddings', 'vectorizer': glove},\n {'name': 'Doc2Vec Paragraph Embeddings', 'vectorizer': doc2vec}],\n 'features': [\n {'name': 'text', 'cols': [('tweet', 'tweet')]},\n {'name': 'user', 'cols': [('user_is_verified', 'bool'),\n ('user_posts', 'numeric'),\n ('user_likes','numeric'),\n ('user_followers', 'numeric'),\n ('user_friends', 'numeric')]},\n {'name': 'stats', 'cols': [('emoji_count', 'numeric'),\n ('polarity', 'numeric'),\n ('subjectivity', 'numeric'),\n ('hashtag_count', 'numeric'),\n ('mentions_count', 'numeric'),\n ('words_count', 'numeric'),\n ('char_count', 'numeric'),\n ('url_count', 'numeric'),\n ('is_retweet', 'bool'),\n ('tweet_likes', 'numeric'),\n ('tweet_retweets', 'numeric'),\n ('tweet_is_quote', 'bool')]}],\n 'query_strategies': [\n {'name': 'Uncertainty Sampling', 'strategy': uncertainty_sampling},\n {'name': 'Entropy Sampling', 'strategy': entropy_sampling},\n {'name': 'Margin Sampling', 'strategy': margin_sampling}],\n }\n Server(options=options).run()\n\nif __name__ == '__main__': main()", "sub_path": "backend/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 4341, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "os.path.abspath", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path", "line_number": 15, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 15, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path", "line_number": 16, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "pandas.read_pickle", "line_number": 24, "usage_type": "call"}, {"api_name": "pandas.read_pickle", "line_number": 25, "usage_type": "call"}, {"api_name": "gensim.downloader.load", "line_number": 28, "usage_type": "call"}, {"api_name": "gensim.downloader", "line_number": 28, "usage_type": "name"}, {"api_name": "gensim.models.doc2vec.Doc2Vec", "line_number": 31, "usage_type": "call"}, {"api_name": "sklearn.feature_extraction.text.TfidfVectorizer", "line_number": 33, "usage_type": "call"}, {"api_name": "sklearn.linear_model.LogisticRegression", "line_number": 42, "usage_type": "call"}, {"api_name": "sklearn.svm.SVC", "line_number": 43, "usage_type": "call"}, {"api_name": "sklearn.ensemble.RandomForestClassifier", "line_number": 44, "usage_type": "call"}, {"api_name": "sklearn.neighbors.KNeighborsClassifier", "line_number": 45, "usage_type": "call"}, {"api_name": "modAL.uncertainty.uncertainty_sampling", "line_number": 84, "usage_type": "name"}, {"api_name": "modAL.uncertainty.entropy_sampling", "line_number": 85, "usage_type": "name"}, {"api_name": "modAL.uncertainty.margin_sampling", "line_number": 86, "usage_type": "name"}, {"api_name": "sio_server.Server", "line_number": 88, "usage_type": "call"}]}
+{"seq_id": "247089853", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom layers import Conv3x3, Conv1x1, ConvT_UNet\n\n\nclass UNet(nn.Module):\n \"\"\"\n 设down4的输出边长为u,我算出image的边长为16u+124, 输出边长为16u-60\n 故输入边长应为16u+124,其中u为>=4的整数\n 推荐输入边长为510,则对应的输出边长为418\n \"\"\"\n\n class UNetDoubleConv(nn.Module):\n\n def __init__(self, in_ch: int, out_ch: int, bn: bool = True, acv: str = 'relu'):\n super().__init__()\n self.conv1 = Conv3x3(in_ch=in_ch, out_ch=out_ch, bn=bn, acv=acv)\n self.conv2 = Conv3x3(in_ch=out_ch, out_ch=out_ch, bn=bn, acv=acv)\n\n def forward(self, x):\n # x = self.pad(x)\n x = self.conv1(x)\n x = self.conv2(x)\n return x\n\n class UNetEncoderBlock(nn.Module):\n\n def __init__(self, in_ch, out_ch, pool: bool = True):\n super().__init__()\n self.down = nn.MaxPool2d(kernel_size=2) if pool else nn.Identity()\n self.conv = UNet.UNetDoubleConv(in_ch, out_ch)\n\n def forward(self, x):\n x = self.down(x)\n x = self.conv(x)\n return x\n\n class UNetDecoderBlock(nn.Module):\n\n def __init__(self, in_ch, out_ch, mode='bilinear'):\n super().__init__()\n mode = mode.lower()\n if mode in ['bilinear', 'interpolation']:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n else:\n self.up = ConvT_UNet(in_ch=in_ch // 2, out_ch=in_ch // 2, mag=2)\n self.conv = UNet.UNetDoubleConv(in_ch, out_ch)\n\n def forward(self, x0, shortcut):\n # x0和shortcut的通道数相等,加起来等于in_ch\n x0 = self.up(x0)\n dh = shortcut.size()[2] - x0.size()[2]\n dw = shortcut.size()[3] - x0.size()[3]\n\n pad = [dw // 2, dw - dw // 2, dh // 2, dh - dh // 2] # 顺序:左右上下\n x0 = F.pad(x0, pad=pad) # 把x0补充或裁剪到和shortcut一样尺寸\n\n x = torch.cat([shortcut, x0], dim=1)\n x = self.conv(x)\n\n return x\n\n def __init__(self, image_ch=3, out_classes=1):\n super().__init__()\n\n self.en0 = UNet.UNetEncoderBlock(in_ch=image_ch, out_ch=64, pool=False)\n self.en1 = UNet.UNetEncoderBlock(in_ch=64, out_ch=128)\n self.en2 = UNet.UNetEncoderBlock(in_ch=128, out_ch=256)\n self.en3 = UNet.UNetEncoderBlock(in_ch=256, out_ch=512)\n self.en4 = UNet.UNetEncoderBlock(in_ch=512, out_ch=512)\n\n self.de1 = UNet.UNetDecoderBlock(in_ch=1024, out_ch=256)\n self.de2 = UNet.UNetDecoderBlock(in_ch=512, out_ch=128)\n self.de3 = UNet.UNetDecoderBlock(in_ch=256, out_ch=64)\n self.de4 = UNet.UNetDecoderBlock(in_ch=128, out_ch=64)\n self.conv1x1 = Conv1x1(in_ch=64, out_ch=out_classes, acv='sigmoid') # 合并特征通道,同时纠正relu带来的偏置\n\n def forward(self, image):\n x0 = self.en0(image)\n x1 = self.en1(x0)\n x2 = self.en2(x1)\n x3 = self.en3(x2)\n x4 = self.en4(x3)\n x = self.de1(x4, x3)\n x = self.de2(x, x2)\n x = self.de3(x, x1)\n x = self.de4(x, x0)\n x = self.conv1x1(x)\n return x\n", "sub_path": "model_diy.py", "file_name": "model_diy.py", "file_ext": "py", "file_size_in_byte": 3318, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "torch.nn.Module", "line_number": 8, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 8, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 15, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 15, "usage_type": "name"}, {"api_name": "layers.Conv3x3", "line_number": 19, "usage_type": "call"}, {"api_name": "layers.Conv3x3", "line_number": 20, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 32, "usage_type": "name"}, {"api_name": "torch.nn.Identity", "line_number": 32, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 40, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 40, "usage_type": "name"}, {"api_name": "torch.nn.Upsample", "line_number": 46, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 46, "usage_type": "name"}, {"api_name": "layers.ConvT_UNet", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn.functional.pad", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 60, "usage_type": "call"}, {"api_name": "layers.Conv1x1", "line_number": 78, "usage_type": "call"}]}
+{"seq_id": "51449139", "text": "# Copyright (c) 2021.\n# Chunyan Zhang\n\nimport numpy as np\nfrom nltk.tokenize import TweetTokenizer\nfrom wordsegment import segment, load\nimport pandas as pd\nimport re, pickle, os\nimport random\nimport logging\n# K-fold splits\nfrom sklearn.model_selection import train_test_split\n\nlogging.basicConfig(level=logging.INFO, filename=\"log.txt\",\n format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(funcName)s - %(levelname)s: %(message)s')\nprint(\"log is saving into log.txt ...\")\n\ndata_path = \"C:/cyzhang/project/twitter_projects/Twitter-Occupation-Prediction/Twi_data/\"\nuser_label_data_csv_file = data_path + 'known_user_label_2.jsonl'\nraw_data_pkl_file = './data/crawled_data.pkl'\nsplit_data_file = './data/crawled_data_splits.pkl'\n\nnum_splits = 10\n\nfrom config import dir_name, vaccine_file_list\n\n################################################################################\n############################ Create training data ##############################\n################################################################################\nimport ast\n\ndef generate_label_tweets():\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweet_dict = {}\n for line in open(user_label_data_csv_file, 'r', encoding='utf-8'):\n record = ast.literal_eval(line)\n tweet_dict[record['id']] = [record['label_3class'], record['description'], record['name']]\n\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\n\n################################################################################\n############################## Text Preprocessing ##############################\n################################################################################\ndef text_preprocess(text, tknzr):\n FLAGS = re.MULTILINE | re.DOTALL\n # Different regex parts for smiley faces\n eyes = r\"[8:=;]\"\n nose = r\"['`\\-]?\"\n\n # function so code less repetitive\n def re_sub(pattern, repl):\n return re.sub(pattern, repl, text, flags=FLAGS)\n\n text = re_sub(r\"https?:\\/\\/\\S+\\b|www\\.(\\w+\\.)+\\S*\", \"\")\n text = re_sub(r\"/\", \" / \")\n text = re_sub(r\"@\\w+\", \"\")\n text = re_sub(r\"{}{}[)dD]+|[)dD]+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}p+\".format(eyes, nose), \"\")\n text = re_sub(r\"{}{}\\(+|\\)+{}{}\".format(eyes, nose, nose, eyes), \"\")\n text = re_sub(r\"{}{}[\\/|l*]\".format(eyes, nose), \"\")\n text = re_sub(r\"<3\", \"\")\n text = re_sub(r\"[-+]?[.\\d]*[\\d]+[:,.\\d]*\", \"\")\n text = re_sub(r\"([!?.]){2,}\", r\"\\1 \")\n text = re_sub(r\"\\b(\\S*?)(.)\\2{2,}\\b\", r\"\\1\\2 \")\n text = re_sub(r\"#\\S+\", lambda hashtag: \" \".join(segment(hashtag.group()[1:]))) # segment hastags\n\n tokens = tknzr.tokenize(text.lower())\n return \" \".join(tokens)\n\n\ndef concat_data():\n path = os.path.dirname(os.path.abspath(__file__)) + \"/data/\"\n with open(raw_data_pkl_file, \"rb\") as f:\n id2entities = pickle.load(f)\n\n ########## Lookup Tables ##########\n labels = sorted(list(set([entity[0] for entity in id2entities.values()])))\n num_classes = len(labels)\n\n label_lookup = np.zeros((num_classes, num_classes), int)\n np.fill_diagonal(label_lookup, 1)\n ###################################\n\n text_data, context_data, label_data = [], [], []\n label_dict = {}\n for i, label in enumerate(labels):\n label_dict[label] = i\n\n load()\n tknzr = TweetTokenizer(reduce_len=True, preserve_case=False, strip_handles=False)\n print(\"Preprocessing tweets.....\")\n for _id in id2entities:\n if id2entities[_id][0] in label_dict.keys():\n text_data.append(text_preprocess(id2entities[_id][1], tknzr))\n context_data.append(text_preprocess(id2entities[_id][2], tknzr))\n\n label_data.append(label_lookup[label_dict[id2entities[_id][0]]])\n\n assert len(text_data) == len(context_data) == len(label_data)\n\n return text_data, context_data, label_data\n\n\n################################################################################\n############################## K-fold Data Split ###############################\n################################################################################\ndef kfold_splits(text_data, context_data, label_data, k):\n kfold_text, kfold_context, kfold_label = [], [], []\n for i in range(k):\n _text_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n _context_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n _label_data = {\"train\": {}, \"valid\": {}, \"test\": {}}\n kfold_text.append(_text_data)\n kfold_context.append(_context_data)\n kfold_label.append(_label_data)\n\n random_state = np.random.randint(0, 10000)\n from sklearn.model_selection import StratifiedKFold\n kf = StratifiedKFold(n_splits=k, shuffle=True, random_state=random_state)\n # kf = KFold(n_splits=k, shuffle=True, random_state=0)\n\n kfold_index = 0\n for rest_index, test_index in kf.split(text_data, np.array(label_data)[:, 0]):\n train_index, valid_index, _, _ = train_test_split(rest_index, np.zeros_like(rest_index), test_size=0.05)\n\n kfold_text[kfold_index][\"train\"] = [text_data[index] for index in train_index]\n kfold_text[kfold_index][\"test\"] = [text_data[index] for index in test_index]\n kfold_text[kfold_index][\"valid\"] = [text_data[index] for index in valid_index]\n\n kfold_context[kfold_index][\"train\"] = [context_data[index] for index in train_index]\n kfold_context[kfold_index][\"test\"] = [context_data[index] for index in test_index]\n kfold_context[kfold_index][\"valid\"] = [context_data[index] for index in valid_index]\n\n kfold_label[kfold_index][\"train\"] = [label_data[index] for index in train_index]\n kfold_label[kfold_index][\"test\"] = [label_data[index] for index in test_index]\n kfold_label[kfold_index][\"valid\"] = [label_data[index] for index in valid_index]\n\n assert len(kfold_text[kfold_index][\"train\"]) == len(kfold_context[kfold_index][\"train\"]) == len(\n kfold_label[kfold_index][\"train\"])\n assert len(kfold_text[kfold_index][\"valid\"]) == len(kfold_context[kfold_index][\"valid\"]) == len(\n kfold_label[kfold_index][\"valid\"])\n assert len(kfold_text[kfold_index][\"test\"]) == len(kfold_context[kfold_index][\"test\"]) == len(\n kfold_label[kfold_index][\"test\"])\n\n train_length = len(kfold_text[kfold_index][\"train\"])\n valid_length = len(kfold_text[kfold_index][\"valid\"])\n test_length = len(kfold_text[kfold_index][\"test\"])\n\n kfold_index += 1\n\n print(\"Input Data Splitted: %s (train) / %s (valid) / %s (test)\" % (train_length, valid_length, test_length))\n\n return kfold_text, kfold_context, kfold_label\n\n\ndef generate_label_tweets_ourdata():\n global raw_data_pkl_file, split_data_file\n raw_data_pkl_file = './data/our_data/crawled_data.pkl'\n split_data_file = './data/our_data/crawled_data_splits.pkl'\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweets_count = 0\n tweet_dict = {}\n for file in vaccine_file_list:\n print(\"{}\".format(file))\n logging.warning(\"{}\".format(file))\n empty_bio_count = 0\n total_count = 0\n covid_file_dir = os.path.join(dir_name, file)\n if not os.path.exists(covid_file_dir):\n print('{} not exsits.'.format(covid_file_dir))\n logging.warning('{} not exsits.'.format(covid_file_dir))\n continue\n\n tweet_file = os.path.join(dir_name, file, 'vaccine_tweets.csv')\n\n if not os.path.exists(tweet_file):\n print('{} not exsits.'.format(tweet_file))\n logging.warning('{} not exsits.'.format(tweet_file))\n continue\n\n for line in open(tweet_file, 'r', encoding='utf-8'):\n tweets_count += 1\n record = ast.literal_eval(line)\n user_id = record['includes']['users'][0]['id']\n bio = record['includes']['users'][0]['description']\n count = 0\n if user_id in tweet_dict:\n count = tweet_dict[user_id][3]+1\n tweet_dict[user_id][3] += 1\n user_id = '{}_{}'.format(user_id, count)\n\n if len(bio) == 0:\n bio = record['data']['text']\n empty_bio_count += 1\n tweet_dict[user_id] = ['label', bio, record['includes']['users'][0]['name'], count]\n total_count += 1\n print('empty bio:{}, total:{}, percent:{:.2%}'.format(empty_bio_count, total_count, empty_bio_count / total_count))\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\ndef generate_label_tweets_ourdata_origin():\n global raw_data_pkl_file, split_data_file\n raw_data_pkl_file = './data/our_data/crawled_data.pkl'\n split_data_file = './data/our_data/crawled_data_splits.pkl'\n if os.path.isfile(raw_data_pkl_file):\n return\n\n tweets_count = 0\n empty_bio_count = 0\n total_count = 0\n tweet_dict = {}\n tweet_dir = \"D:/twitter_data/origin_tweets/\"\n tweet_file_list = [\"Sampled_Stream_detail_20200715_0720_origin/twitter_sample_origin-20200715141905.csv\",\n \"Sampled_Stream_detail_20200811_0815_origin/twitter_sample_origin-20200811233217.csv\",\n \"Sampled_Stream_detail_20200914_0917_origin/twitter_sample_origin-20200916100506.csv\",\n \"Sampled_Stream_detail_20201105_1110_origin/twitter_sample_origin-20201109062630.csv\",\n \"Sampled_Stream_detail_20201210_1214_origin/twitter_sample_origin-20201214190040.csv\",\n \"Sampled_Stream_detail_20210410_0416_origin/twitter_sample_origin-20210410123126.csv\"\n ]\n tweet_file = tweet_dir + tweet_file_list[5]\n\n for line in open(tweet_file, 'r', encoding='utf-8'):\n tweets_count += 1\n record = ast.literal_eval(line)\n user_id = record['includes']['users'][0]['id']\n bio = record['includes']['users'][0]['description']\n count = 0\n if user_id in tweet_dict:\n count = tweet_dict[user_id][3]+1\n tweet_dict[user_id][3] += 1\n user_id = '{}_{}'.format(user_id, count)\n\n if len(bio) == 0:\n bio = record['data']['text']\n empty_bio_count += 1\n tweet_dict[user_id] = ['label', bio, record['includes']['users'][0]['name'], count]\n total_count += 1\n\n print('empty bio:{}, total:{}, percent:{:.2%}'.format(empty_bio_count, total_count, empty_bio_count / total_count))\n with open(raw_data_pkl_file, 'wb') as fp:\n pickle.dump(tweet_dict, fp)\n\ndef process_training_data():\n generate_label_tweets()\n _text, _ctxt, _label = concat_data()\n print(\"Splitting data into 10 folds.....\")\n _text_split, _ctxt_split, _label_split = kfold_splits(_text, _ctxt, _label, num_splits)\n\n path = os.path.dirname(os.path.abspath(__file__)) + \"/data/\"\n if not os.path.exists(path):\n os.makedirs(path)\n with open(split_data_file, \"wb\") as f:\n print(\"Creating pickle files for each split to \" + split_data_file)\n pickle.dump({\"text_data\": _text_split, \"context_data\": _ctxt_split, \"label_data\": _label_split}, f)\n\ndef process_our_data():\n text_fold0, context_fold0, label_fold0 = [], [], []\n text_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n context_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n label_fold0.append({\"train\": {}, \"valid\": {}, \"test\": {}})\n # 将标注数据集分为训练集和验证集\n generate_label_tweets()\n _text, _ctxt, _label = concat_data()\n from sklearn.model_selection import ShuffleSplit # or StratifiedShuffleSplit\n sss = ShuffleSplit(n_splits=1, test_size=0.1)\n train_index, val_index = next(sss.split(_text, _label))\n text_fold0[0][\"train\"] = [_text[index] for index in train_index]\n context_fold0[0][\"train\"] = [_ctxt[index] for index in train_index]\n label_fold0[0][\"train\"] = [_label[index] for index in train_index]\n text_fold0[0][\"valid\"] = [_text[index] for index in val_index]\n context_fold0[0][\"valid\"] = [_ctxt[index] for index in val_index]\n label_fold0[0][\"valid\"] = [_label[index] for index in val_index]\n\n #处理vaccine tweet用generate_label_tweets_ourdata,处理origin tweet用generate_label_tweets_ourdata_origin\n #generate_label_tweets_ourdata()\n generate_label_tweets_ourdata_origin()\n _text, _ctxt, _label = concat_data()\n text_fold0[0][\"test\"] = _text\n context_fold0[0][\"test\"] = _ctxt\n label_fold0[0][\"test\"] = _label\n\n with open(split_data_file, \"wb\") as f:\n print(\"Creating pickle files for each split to \" + split_data_file)\n pickle.dump({\"text_data\": text_fold0, \"context_data\": context_fold0, \"label_data\": label_fold0}, f)\n\nif __name__ == \"__main__\":\n #f = open('./data/our_data/crawled_data_splits.pkl', \"rb\")\n #id2entities = pickle.load(f)\n #process_training_data()\n process_our_data()", "sub_path": "1. data_mining/occupation_predictor/data_preprocess.py", "file_name": "data_preprocess.py", "file_ext": "py", "file_size_in_byte": 12975, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.basicConfig", "line_number": 14, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 14, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "ast.literal_eval", "line_number": 38, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 42, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 49, "usage_type": "attribute"}, {"api_name": "re.DOTALL", "line_number": 49, "usage_type": "attribute"}, {"api_name": "re.sub", "line_number": 56, "usage_type": "call"}, {"api_name": "wordsegment.segment", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 76, "usage_type": "call"}, {"api_name": "os.path", "line_number": 76, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 76, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 84, "usage_type": "call"}, {"api_name": "numpy.fill_diagonal", "line_number": 85, "usage_type": "call"}, {"api_name": "wordsegment.load", "line_number": 93, "usage_type": "call"}, {"api_name": "nltk.tokenize.TweetTokenizer", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 121, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 121, "usage_type": "attribute"}, {"api_name": "sklearn.model_selection.StratifiedKFold", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 127, "usage_type": "call"}, {"api_name": "sklearn.model_selection.train_test_split", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 164, "usage_type": "call"}, {"api_name": "os.path", "line_number": 164, "usage_type": "attribute"}, {"api_name": "config.vaccine_file_list", "line_number": 169, "usage_type": "name"}, {"api_name": "logging.warning", "line_number": 171, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "config.dir_name", "line_number": 174, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 175, "usage_type": "call"}, {"api_name": "os.path", "line_number": 175, "usage_type": "attribute"}, {"api_name": "logging.warning", "line_number": 177, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 180, "usage_type": "call"}, {"api_name": "config.dir_name", "line_number": 180, "usage_type": "argument"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path", "line_number": 182, "usage_type": "attribute"}, {"api_name": "logging.warning", "line_number": 184, "usage_type": "call"}, {"api_name": "ast.literal_eval", "line_number": 189, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 205, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 211, "usage_type": "call"}, {"api_name": "os.path", "line_number": 211, "usage_type": "attribute"}, {"api_name": "ast.literal_eval", "line_number": 230, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 247, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 255, "usage_type": "call"}, {"api_name": "os.path", "line_number": 255, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 255, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 256, "usage_type": "call"}, {"api_name": "os.path", "line_number": 256, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 257, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 260, "usage_type": "call"}, {"api_name": "sklearn.model_selection.ShuffleSplit", "line_number": 271, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 290, "usage_type": "call"}]}
+{"seq_id": "567383197", "text": "\"\"\"\npyFLUT.data\n-----------\n\nThis module implements the parent data class for ULF and HDF5\nimplementing the\nplot capabilities and other common features.\n\nMichele Vascellari: Michele.Vascellari@vtc.tu.freiberg.de 2015 (c)\n\"\"\"\nfrom __future__ import division\nfrom builtins import zip\nfrom builtins import range\nfrom builtins import object\nfrom past.utils import old_div\nfrom six import string_types\n\nimport collections\nimport operator\nimport h5py\nimport numpy as np\nimport scipy.interpolate\nimport pyFLUT.definition as definition\nimport tabulate\n\n\ndef join(datas, axis=0):\n \"\"\"\n Join two or more Data classes using concatenate function in numpy.\n The classes must have the same input and output variables and the\n same size in all the dimensions, except the one concatenate,\n defined by the axis.\n\n Parameters\n ----------\n datas: list\n List of Data classes to join.\n axis: int, str, optional\n Axis for concatenate the data. It can be the number of axis or\n the name of the input variable.\n\n Returns\n -------\n New pyFLUT.data.Data instance\n \"\"\"\n return Data.join(datas, axis)\n\n\nclass Data(object):\n \"\"\"\n Data class.\n It us used for storing multi-dimensional arrays (based on numpy),\n manipulate, storing, plot and lookup.\n\n Attributes\n ----------\n data: np.ndarray (n0, n1, ..., nM, N)\n Data matrix\n input_dict: collections.OrderedDict\n Input dictionary, contains the ordered input variables and their\n grid values\n output_dict: collections.OrderedDict\n Output dictionary, contains the output variables and their\n indices corrsponding to the last dimensio of data\n\n Methods\n -------\n plotdata(x, y, parameters_to_plot, index, ax, legend, **kwargs)\n contourdata(x, y, z, levels, type, parameters_to_plot, index, ax,\n colorbar, return_cp, **kwargs)\n squeeze() lookup(input_values, variable)\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Parameters\n ----------\n kwargs: optional argument for inizializing the class\n input_dict: dict\n Input dictionary defining the input variables.\n I.e ``{'v0':np.array([...]), 'v1':np.array([...])}, ...,\n 'vM': np.array([...])}``\n output_dict: collections.ordered\n Ordered dictionary reporting the index of the variables\n contained in data. The index corresponds to the index of\n output variables in `data'.\n data: numpy.ndarray(n0, n1, ..., nM, N)\n Data array containing the values of the dataset.\n `n0`, `n1`, ... `nM` are the length of the input variables\n defined in `input_dict`. `M` is the number of output\n variables\n\n Examples\n --------\n The `Data` object can be defined as follows::\n\n >>>> import pyFLUT.data\n >>> input_dict = collections.OrderedDict(zip(['Z', 'yc'],\n [np.linspace(0, 1, 51),\n np.linspace(0, 1, 21)]))\n >>> output_dict = collections.OrderedDict(\n zip(['T', 'CO', 'CO2'], range(3)))\n >>> data = np.random.rand(51, 21, 3)\n >>> d = pyFLUT.data.Data(input_dict=input_dict,\n output_dict=output_dict, data=data)\n\n The input and output dictionaries are defined using OrderedDict.\n It is mandatory for the `input_dict`, while is reccomanded for\n the output.\n Data are organized in the data array and they can be accessed::\n\n >>> T = d['T']\n >>> print(T.shape)\n (51, 21)\n >>> d.input_variables()\n ['Z', 'yc']\n >>> d.input_variable_values('Z')\n array([ 0. , 0.02, 0.04, 0.06, ..., 1])\n >>> d.input_variable_index('yc')\n 1\n >>> len(d.input_variable_values('Z'))\n 51\n >>> d.output_variable_index('T')\n 0\n >>> d.output_variables\n ['T', 'CO', 'CO2', 'Z', 'yc']\n\n The input variables ``Z`` and ``yc`` are also included among\n the output variables.\n This correspond to the cartesian mesh grid of the input\n variables.\n \"\"\"\n if 'output_dict' and 'input_dict' and 'data' in kwargs:\n self.output_dict = kwargs['output_dict']\n self.input_dict = kwargs['input_dict']\n self.data = kwargs['data']\n else:\n raise ValueError(\n \"Data input argument {} do not \"\n \"exist\".format(kwargs))\n self.add_variables_to_data(include_last=True)\n self.regular_grid = [True for _ in self._input_dict]\n\n @classmethod\n def read_h5(cls, file_h5):\n \"\"\"\n Read a binary file using hdf5 format. This is not the format\n used by ``flameletConfig``.\n\n Parameters\n ----------\n file_h5: str\n name of h5 file\n \"\"\"\n h5 = h5py.File(file_h5, 'r')\n # input_dict\n input_dict_0 = {}\n order = {}\n for var, val in h5['/input_dict'].items():\n input_dict_0[var] = h5['/input_dict'][var]['Values'].value\n order[var] = h5['/input_dict'][var]['Index'].value\n input_dict = collections.OrderedDict()\n for i in range(len(input_dict_0)):\n var = list(order.keys())[list(order.values()).index(i)]\n input_dict[var] = input_dict_0[var]\n # output_dict\n output_dict = {}\n for var, i in h5['/output_dict'].items():\n output_dict[var] = h5['/output_dict/' + var].value\n output_dict = collections.OrderedDict(\n sorted(list(output_dict.items()), key=operator.itemgetter(1)))\n data = h5['data'].value\n h5.close()\n return cls(input_dict=input_dict,\n output_dict=output_dict,\n data=data)\n\n # TODO input_dict and output_dict can be modified\n # find a method to avoid that!\n @property\n def input_dict(self):\n return self._input_dict\n\n @input_dict.setter\n def input_dict(self, input_dict):\n if isinstance(input_dict, collections.OrderedDict):\n if not all(\n isinstance(v, np.ndarray)\n for v in input_dict.values()):\n raise ValueError(\n 'Values of input_dict should be numpy arrays')\n if not all(\n (np.alltrue(np.diff(v) > 0)\n for v in input_dict.values()\n if len(v) > 0)):\n raise ValueError(\n 'Values of input_dict should be monotonic')\n self._input_dict = input_dict.copy()\n else:\n raise TypeError(\n 'input_dict should be defined as OrderedDict')\n\n @property\n def output_dict(self):\n return self._output_dict\n\n @output_dict.setter\n def output_dict(self, output_dict):\n if isinstance(output_dict, list):\n output_dict = collections.OrderedDict(\n [(v, i) for i, v in enumerate(output_dict)])\n elif not isinstance(output_dict, collections.OrderedDict):\n msg = (\n 'Output dict should be a list or OrderedDict'\n )\n raise TypeError(msg)\n self._output_dict = output_dict.copy()\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, data):\n if not isinstance(data, np.ndarray):\n raise TypeError('data has to be a np.ndarray')\n shape = data.shape\n shape_inp = tuple(len(val)\n for val in self.input_dict.values())\n if not shape[:-1] == shape_inp:\n msg = (\n 'Data shape {} not consistent with input_dict {}'\n ).format(shape, shape_inp)\n raise ValueError(msg)\n if not shape[-1] == len(self.output_dict):\n msg = (\n 'Data shape {} not consistent with output_dict {}'\n ).format(shape, len(self.output_dict))\n raise ValueError(msg)\n self._data = data\n\n def __getitem__(self, item):\n \"\"\"\n Extract the data array for the given item\n\n Parameters\n ----------\n item: str\n It should be defined in ``output_dict``\n\n Returns\n -------\n type:\n numpy.ndarray\n \"\"\"\n if item in self.output_dict:\n return self.data[..., self.output_dict[item]]\n else:\n raise ValueError('Item {} not in output_dict'.format(item))\n\n def __setitem__(self, key, value):\n \"\"\"\n Include a new variable to the data structure\n\n Parameters\n ----------\n key: str\n Name of the new properties. It will be added to\n ``output_dict``\n value: numpy.ndarray(N0, N1, N2, ..., Nm)\n New data added to the data structure and stored with the\n key `key`.\n The dimensions `N0`, `N1`,... `Nm` of the `value` should\n correspond to the length of the `m` input variables.\n\n Examples\n --------\n A new variable `New` is added to the dataset, using a random\n dataset generated with `numpy.random.rand`::\n\n >>> d['Random'] = np.random.rand(*[len(v)\n for v in d.input_dict.values()])\n\n It is possible to access to new data, simply by::\n\n >>> print(d['Random'])\n\n It is also possible to create new variables from the existing\n ones::\n\n >>> d['rhoT'] = d['rho'] * d['T']\n \"\"\"\n if isinstance(key, int):\n self._data[..., key] = value\n elif isinstance(key, string_types):\n if key in self._output_dict:\n self._data[..., self._output_dict[key]] = value\n else:\n l = len(self)\n self._output_dict[key] = l\n self.data = np.insert(self.data, l, value, axis=-1)\n else:\n message = \"Key {} should be a int or a string\".format(key)\n raise ValueError(message)\n # definition.error_message(ValueError, self.__setitem__,\n # message)\n\n def __delitem__(self, item):\n if item in self:\n n = self._output_dict.pop(item)\n self.data = np.delete(self.data, n, -1)\n\n def __len__(self):\n \"\"\"\n Return the number of output variables defined in the dataset\n\n Returns\n -------\n length: int\n\n \"\"\"\n return len(self._output_dict)\n\n def plotdata(self, x, y, **kwargs):\n \"\"\"\n Plot data using lines. Matplotlib is used for plotting\n\n Parameters\n ----------\n x: str\n Variable plotted in the x axis\n y: str\n Variable plotted in the y axis\n parameters_to_plot: {'var0':[v00, v01, ..., v0n],\n 'var1':[v10, v11, vn1], ...}\n Define which parameters are used for the plots.\n `var0`, `var1` are input variables defined in `input_dict`\n `[v00, v01, ..., v0n]` are the values plotted of the\n variabe `var0`. If `index` is `True` they are the inde of\n `var0` defined in `input_dict[var0]`, otherwise they\n represent the real values plotted.\n Alternatively the parameters can be directly passed as\n input. See example.\n index: bool, default False\n Use index values in `parameters_to_plot` if `True`,\n otherwise use real values.\n ax: matplotlib.axes, optional\n Use the given axes for plotting\n legend: bool, default True\n Show legend\n kwargs:\n Additional arguments passed to `matplotlib.pyplot.plot`\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n\n Examples\n --------\n ::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0)\n >>> ax.figure.show()\n\n\n plots the variable `CO` as function of `Z` using constant\n values of `Tf` of `1000` and `2000`,\n and `t` equals to `0`.\n\n If the `index` option is used::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n index=True)\n >>> ax.figure.show()\n\n plots the variable `CO` as function of `Z` using indices `0`\n and `5` of parameter `Tf` and `1` of `t`.\n\n Legend can be show or not::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n legend=False)\n\n Additional parameters to ``matplotlib.pyplot.plot`` can be\n passed using kwargs::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0,\n linewidth=3)\n\n The option `linewidth=3` is passed to the plot function.\n See matplotlib.plot for more argument to pass.\n\n The returned `axes` object can be used for externally\n manipulating the plot.\n For example it is possible to plot more than one variables\n passing the axes object::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000, 2000], t=0,\n label='CO')\n >>> d.plotdata('Z', 'CO2', Tf=[1000,2000], t=0, ax=ax,\n label='CO2')\n >>> ax.set_ylabel('Mass fraction')\n >>> ax.set_xlim([0, 0.2])\n >>> ax.figure.show()\n\n This example shows how to plot `CO` and `CO2` on the same axes.\n Default labels are modified\n by user defined ones (note that overwriting default labels can\n create problems when more than one line is plotted).\n Finally the ax object is used for changing the y label and the x\n axis::\n\n >>> ax = d.plotdata('Z', 'CO', Tf=[1000,2000], t=0, marker='*',\n linestyle='dashed')\n\n This example shows how to plot dashed lines with `*` symbols.\n\n It is possible to pass the parameters to plot directly as input\n parameters without using\n the dictionary. The following two commands are equivalent:\n\n >>> ax = d.plotdata('Z', 'CO',\n parameters_to_plot={'Tf':[2000], 't':[0]}, label='CO')\n >>> ax = d.plotdata('Z', 'CO', Tf= [2000], t=[0] label='CO')\n\n See Also\n --------\n contourdata\n \"\"\"\n from matplotlib.pyplot import subplots\n\n ax = kwargs.pop('ax', None)\n if not ax:\n fg, ax = subplots()\n legend = kwargs.pop('legend', True)\n index = kwargs.pop('index', False)\n parameters_to_plot = kwargs.pop('parameters_to_plot', {})\n n_parameters = len(self._input_dict) - 1\n if not parameters_to_plot:\n parameters_to_plot = {var: kwargs.pop(var)\n for var in self._input_dict.keys()\n if var in kwargs}\n\n # check dimensions\n if n_parameters != len(parameters_to_plot):\n definition.error_message(ValueError, self.plotdata,\n \"Define a number of \"\n \"parameters_to_plot = size flut\")\n\n # check what is the variable to plot\n # this variable does not exist in parameters_to_plot\n\n if parameters_to_plot:\n for ind, variable in enumerate(self._input_dict.keys()):\n if variable not in list(parameters_to_plot.keys()):\n main_var = variable\n main_index = ind\n main_len = len(self._input_dict[variable])\n break\n\n if not index:\n points = np.empty((main_len, len(self._input_dict)))\n points[:, main_index] = self.input_variable_values(\n main_var)\n\n for par, values in parameters_to_plot.items():\n if isinstance(values, (float, int)):\n parameters_to_plot[par] = [values]\n\n param_grid = np.meshgrid(\n *[values for values in parameters_to_plot.values()],\n **{'indexing': 'ij'})\n\n for ind, _ in enumerate(param_grid[0].ravel()):\n label = ''\n if index:\n xvalues = self.__getitem__(x)\n yvalues = self.__getitem__(y)\n for i_var, variable in enumerate(\n parameters_to_plot.keys()):\n if index:\n axis = self.input_variable_index(variable)\n ind_par = param_grid[i_var].ravel()[ind]\n parameter = self._input_dict[variable][ind_par]\n xvalues = np.expand_dims(\n np.take(xvalues, ind_par, axis=axis),\n axis=axis)\n yvalues = np.expand_dims(\n np.take(yvalues, ind_par, axis=axis),\n axis=axis)\n else:\n parameter = param_grid[i_var].ravel()[ind]\n points[:, self.input_variable_index(\n variable)] = parameter\n label = label + \"{}={} \".format(variable, parameter)\n\n if index:\n xvalues = xvalues.squeeze()\n yvalues = yvalues.squeeze()\n else:\n xvalues = self.getvalue(points, x)\n yvalues = self.getvalue(points, y)\n plotarg = kwargs.copy()\n if 'label' not in plotarg:\n plotarg['label'] = label\n ax.plot(xvalues, yvalues, **plotarg)\n else:\n plotarg = kwargs.copy()\n if 'label' not in plotarg:\n plotarg['label'] = '...'\n ax.plot(self.__getitem__(x), self.__getitem__(y), **plotarg)\n\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n\n if legend:\n ax.legend(loc=0)\n return ax\n\n def parameters_grid(self):\n \"\"\"\n Create a grid using the inout variables.\n\n :return: grid parameters using numpy.meshgrid\n \"\"\"\n return np.meshgrid(*[v\n for v in self._input_dict.values()],\n **{'indexing': 'ij'})\n\n def add_variables_to_data(self, include_last=False):\n \"\"\"\n Add input_dict to data using meshgrid\n\n Parameters\n ----------\n include_last: bool, dafault False\n If it is `True` the last input variable is also added\n \"\"\"\n grid = self.parameters_grid()\n if include_last:\n iterator = zip(self._input_dict, grid)\n else:\n iterator = zip(list(self._input_dict)[:-1], grid[:-1])\n for variable, g in iterator:\n self[variable] = g\n\n def contourdata(self, x, y, z, **kwargs):\n \"\"\"\n Plot data using contours. Matplotlib is used for plotting.\n\n Parameters\n ----------\n x: str\n Variable plotted in the x axis\n y: str\n Variable plotted in the y axis\n z: str\n Variable which contour is plotted\n levels: int, array_like, default 20\n Levels used for representing the contour lines or surface.\n It is used only if `type` is `contour' or `contourf`.\n If is a int represents the number of levels automatically\n chosen by matplotlib. User-defined levels can be passed\n using an `array_like`\n type: str {'contourf', 'contour', 'pcolor', 'pcolormesh'},\n default 'contourf'\n Defines which kind of matplotlib methods is used for\n plotting the contour.\n * `contourf`: a filled contour is plotted\n * `contour`: a isolines are plotted\n * `pcolor': pseudocolor plot (slow)\n * `pcolormesh': pseudocolor plot (fast)\n parameters_to_plot: {'var0':v0, 'var1':v1, ...}\n Define which parameters are fixed for the plots.\n `var0`, `var1`, `varn` are input variables defined in\n `input_dict`\n `v0`, `v1`, `vn` are the values plotted of the variable\n `var0`. If `index` is `True`\n they are the index of `var0` defined in `input_dict[var0]`,\n otherwise they represent the real values plotted.\n If the number of input parameters is 2, `parameters_to_plot`\n is not required.\n Parameters can be directly used as input, without using the\n variable parameters_to_plot\n index bool, default False\n Use index values in `parameters_to_plot` if `True`,\n otherwise use real values.\n ax: matplotlib.axes, optional\n Use the given axes for plotting\n kwargs:\n Additional arguments passed to `matplotlib.pyplot`\n\n Returns\n -------\n ax: matplotlib.pyplot.axes\n\n Examples\n --------\n ::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000)\n >>> ax.figure.show()\n\n plots the contour of `CO` in `Z`-`yc` plane using a constant\n value of `Tf` of `1000`.\n By default `matplotlib.pyplot.contourf` is used.\n\n A different plot method can be specified using `type`::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n type='pcolormesh')\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n type='contour')\n\n\n If the `index` option is used::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n index=True)\n\n The contour is plotted for the 3rd index of `Tf`,\n corresponding to::\n\n >>> print(d.input_variable_values['Tf'][3])\n\n Colorbar can be show or not::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n colorbar=False)\n\n The number of contour levels can be set::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000, levels=20)\n\n Otherwise it is possible to define the levels passing an array::\n\n >>> levels = np.linspace(0.1, 0.2, 12)\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000,\n levels=levels)\n\n The returned `ax` object can be used for adding more plots to\n the figure::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000, alpha=0.5)\n >>> ax.plot([0, 1], [0,1])\n >>> ax.set_xlim([0, 1])\n\n In the example a line is added to the contour plot and the x\n axis range is set between 0 and 1.\n\n Parameters can be directly used as input. The two commands are\n equivalent::\n\n >>> ax = d.contourdata('Z', 'yc', 'CO',\n parameters_to_plot={'Tf':1000})\n >>> ax = d.contourdata('Z', 'yc', 'CO', Tf=1000)\n\n\n See Also\n --------\n plotdata\n \"\"\"\n from matplotlib.pyplot import subplots\n\n index = kwargs.pop('index', False)\n type = kwargs.pop('type', 'contourf')\n ax = kwargs.pop('ax', None)\n colorbar = kwargs.pop('colorbar', True)\n return_cp = kwargs.pop('return_cp', False)\n levels = kwargs.pop('levels', 20)\n parameters_to_plot = kwargs.pop('parameters_to_plot', None)\n if not parameters_to_plot:\n parameters_to_plot = {var: kwargs.pop(var)\n for var in self._input_dict.keys()\n if var in kwargs}\n\n if self._data.ndim == 2:\n definition.error_message(IOError, self.contourdata,\n \"No of dimension is 1 no contour \"\n \"plot is possible\")\n elif self._data.ndim == 3:\n # 2D data no parameters_to_plot are necessary\n xvalues, yvalues, zvalues = [\n self.__getitem__(i) for i in [x, y, z]]\n label = ''\n else:\n new_shape = [len(values)\n for variable, values\n in self._input_dict.items()\n if variable not in parameters_to_plot]\n\n if index:\n values_to_plot = [self.__getitem__(i)\n for i in [x, y, z]]\n for parameter, value in parameters_to_plot.items():\n axis = self.input_variable_index(parameter)\n values_to_plot = [np.expand_dims(np.take(values,\n value,\n axis=axis),\n axis=axis)\n for values in values_to_plot]\n xvalues, yvalues, zvalues = [\n values.squeeze() for values in values_to_plot]\n label = ''.join('{}={}\\t'.format(var,\n self._input_dict[var][\n val])\n for var, val in\n parameters_to_plot.items())[:-1]\n else:\n gridpoints = np.meshgrid(\n *[values if var not in parameters_to_plot\n else parameters_to_plot[var]\n for var, values in self._input_dict.items()],\n **{'indexing': 'ij'})\n points = np.empty(\n (len(gridpoints[0].ravel()), len(self._input_dict)))\n for i, _ in enumerate(self._input_dict.keys()):\n points[:, i] = gridpoints[i].ravel()\n xvalues, yvalues, zvalues = [\n self.getvalue(points, i).reshape(new_shape)\n for i in [x, y, z]]\n label = ''.join('{}={}\\t'.format(var, val)\n for var, val in\n parameters_to_plot.items())[:-1]\n\n if not ax:\n fg, ax = subplots()\n else:\n fg = ax.figure\n\n if hasattr(ax, type):\n contour = getattr(ax, type)\n args = [xvalues, yvalues, zvalues]\n if type not in ['pcolor', 'pcolormesh']:\n args.append(levels)\n cf = contour(*args, **kwargs)\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n if colorbar:\n cb = fg.colorbar(cf, ax=ax)\n if colorbar:\n cb.set_label(z)\n else:\n cb.set_label(colorbar)\n else:\n cb = None\n ax.set_title(label)\n if return_cp:\n return ax, cf, cb\n else:\n return ax\n\n def interpolate_variable(self, variable):\n \"\"\"\n Define an interpolation class function for the given variable.\n\n Parameters\n ----------\n variable: str\n interpolated variable, it should be defined in `output_dict`\n\n Returns\n -------\n funct: scipy.interpolate.interp1d\n\n See Also\n --------\n Data.getvalue\n scipy.interpolate.interp1d\n\n Examples\n --------\n A interpolation function for the variable `T` is calculated::\n\n >>> T_ip = d.interpolate_variable('T')\n >>> print(T_ip([0.2, 0.15]))\n\n The function `T_ip` accept as input an array of the same length\n of the input_dict.\n \"\"\"\n def funct(x):\n if isinstance(x, list):\n x = np.array(x)\n if x.ndim == 1:\n x = np.expand_dims(x, axis=0)\n elif x.ndim > 2:\n definition.error_message(ValueError,\n self.interpolate_variable,\n \"Number of dimensions >2\")\n # check if one or more dimensions need to be removed\n columns = []\n for i, val in enumerate(self._input_dict.values()):\n x[:, i][x[:, i] < val.min()] = val.min()\n x[:, i][x[:, i] > val.max()] = val.max()\n if len(val) > 1:\n columns.append(i)\n x = np.take(x, columns, axis=1).squeeze()\n y = F(x)\n return np.array([y]) if y.shape == () else y\n\n method = 'linear'\n grid_input = [value for value in self._input_dict.values()\n if len(value) > 1]\n squeezed_var = np.squeeze(self.__getitem__(variable))\n if len(grid_input) > 1:\n F = scipy.interpolate.RegularGridInterpolator(\n grid_input,\n squeezed_var,\n method=method,\n bounds_error=False)\n else:\n F = scipy.interpolate.interp1d(grid_input[0],\n squeezed_var,\n kind=method,\n bounds_error=False)\n return funct\n\n def lookup(self, input_values, variable):\n \"\"\"\n Return the interpolated value of the of the given variable for\n the input_values\n\n Parameters\n ----------\n input_values: array_like(n_inp, n_points)\n Input values for the interpolation. The dimensions of the\n array are:\n * `n_inp`: number of input variables in the `input_dict`\n * `n_points`: number of input points for the interpolation\n variable: str:\n Name of the interpolated variables\n\n Returns\n -------\n interpolated_values: numpy.ndarray(n_points)\n Array of interpolated values of the `variable`\n\n Examples\n --------\n\n Considering the input variables::\n\n >>> d.input_variables()\n ['Z', 'yc']\n\n The first variable is `Z` and the second is `yc`::\n\n >>> points = [[0, 1], [0.5, 1], [1,1]]\n >>> T_ip = d.getvalue(points, 'T'\n >>> print(T_ip)\n array([ 1249. , 1343.7731, 678. ])\n\n \"\"\"\n F = self.interpolate_variable(variable)\n return F(input_values)\n\n def getvalue(self, input_values, variable):\n \"\"\"\n Return the interpolated value of the of the given variable for\n the input_values. The method is replace by lookup\n\n See Also\n --------\n lookup\n\n .. note:: Deprecated in pyFLUT 2.0\n `getvalue` will be replaced in pyFLUT 2.0 and replaced by\n `lookup`\n \"\"\"\n return self.lookup(input_values=input_values, variable=variable)\n\n def write_ascii(self, file_ascii):\n \"\"\"\n Export data in ASCII file\n\n Parameters\n ----------\n file_ascii: str\n name of the output ASCII file\n\n Examples\n --------\n Dataset can be exported as follows::\n\n >>> d.write_ascii('results.txt')\n\n The format of the file is the following::\n\n $ cat results.txt\n AR C C2H C2H2 C2H3 C2H4 C2H5 C2H6 C3H7 C3H8 CH CH2\n 0.0 0.0 0.0 0.24085096 0.0 0.079229316999999994\n 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0\n ...\n\n \"\"\"\n import csv\n # TODO allows to work for more than 2D tables\n with open(file_ascii, 'w') as f:\n wr = csv.writer(f, delimiter=' ')\n # write header\n # write input parameters\n for index, (var, values) in enumerate(\n self._input_dict.items()):\n # wr.writerow('# Input {}: {}'.format(index, var))\n # wr.writerow(values)\n f.write('# Input {}: {}\\n'.format(index, var))\n wr.writerow(values)\n wr.writerow(['#'] + list(self._output_dict.keys()))\n for data_row in self._data.reshape(-1, self._data.shape[-1]):\n wr.writerow(data_row)\n\n def write_vtk(self, file_vtk, output_variables=None):\n from pyevtk.hl import gridToVTK\n if len(self._input_dict) == 3:\n if not output_variables:\n output_variables = self.output_variables\n return gridToVTK(\"structured\", *list(self._input_dict.values()),\n pointData={var: self.__getitem__(var).T\n for var in output_variables})\n else:\n definition.error_message(ValueError, self.write_vtk,\n \"Export to VTK supported only \"\n \"for 3D dataset\")\n\n def write_bin(self, file_h5, compression=\"gzip\"):\n \"\"\"\n Write a binary file using hdf5 format. This is not the format\n used by ``flameletConfig``.\n\n Parameters\n ----------\n file_h5: str\n name of h5 file\n compression: str {'gzip', ...'}\n Type of compression used\n\n See Also\n --------\n h5py.create_dataset\n \"\"\"\n h5 = h5py.File(file_h5, 'w')\n # input_dict\n h5.create_group('input_dict')\n for i, (var, val) in enumerate(self._input_dict.items()):\n h5['/input_dict'].create_group(var)\n h5['/input_dict/' + var].create_dataset('Values', data=val)\n h5['/input_dict/' + var].create_dataset('Index', data=i)\n # output_dict\n h5.create_group('output_dict')\n for var, i in self._output_dict.items():\n h5['/output_dict'].create_dataset(var, data=i)\n\n h5.create_dataset('data', data=self._data,\n compression=compression)\n h5.close()\n\n @property\n def input_variables(self):\n \"\"\"\n Return a list of the input variables\n\n Returns\n -------\n inp_variables: list\n \"\"\"\n return list(self._input_dict.keys())\n\n def input_variable_index(self, variable):\n \"\"\"\n Return the index of the given input variable\n\n Parameters\n ----------\n variable: str\n name of the input variable\n\n Returns\n -------\n index: int\n index of the input variable\n \"\"\"\n return list(self._input_dict.keys()).index(variable)\n\n def input_variable_values(self, variable):\n \"\"\"\n Return the array of the given input variable\n\n Parameters\n ----------\n variable:str\n name of the input variable\n\n Returns\n -------\n input_array: numpy.ndarray\n Numpy array contaning the values of the input parameter\n \"\"\"\n return self._input_dict[variable]\n\n def __contains__(self, key):\n return key in self.output_dict\n\n @property\n def output_variables(self):\n \"\"\"\n Return the list of the output variables\n\n Returns\n -------\n out_variables: list\n list of the output variables\n\n \"\"\"\n return list(self._output_dict.keys())\n\n def output_variable_index(self, variable):\n \"\"\"\n Return the index of the given output variable\n\n Parameters\n ----------\n variable: str\n name of the output variable\n\n Returns\n -------\n index: int\n index of the output variable\n \"\"\"\n return self._output_dict[variable]\n\n def squeeze(self):\n \"\"\"\n Squeeze the dimensions of the data object\n \"\"\"\n input_dict = collections.OrderedDict()\n for var, vals in self._input_dict.items():\n if len(vals) > 1:\n # self._input_dict.pop(var)\n input_dict[var] = vals\n self.input_dict = input_dict\n self.data = np.squeeze(self._data)\n\n def __copy__(self):\n # cls = self.__class__\n # results = cls.__new__(cls)\n # results.__dict__.update(self.__dict__)\n # return results\n return Data(input_dict=self._input_dict, data=self._data,\n output_dict=self._output_dict)\n\n def __str__(self):\n return tabulate.tabulate(\n [[var, val.min(), val.max(), len(val)]\n for var, val in self._input_dict.items()],\n headers=['Variable', 'Min', 'Max', 'N'])\n\n def __repr__(self):\n return super(Data, self).__repr__() + '\\n\\n' + self.__str__()\n\n def gradient(self, variable, along=None, method='central',\n velocity=None):\n \"\"\"\n Calculate gradient\n\n Parameters\n ----------\n variable: str\n variable whose gradient is calculated\n along: str, None, default=None\n along which variable calculate gradient. If None use the\n last input_dict variable.\n method: str, default='central'\n method used for the gradient: 'central', 'upwind' are\n allowed.\n velocity: str, None, default=None\n velocity variable, use onlu with 'upwind'\n\n Returns\n -------\n np.array: gradient dY/dX with Y=variable and X=along\n\n \"\"\"\n if not along:\n along = self.input_variables()[-1]\n elif along not in self._input_dict:\n definition.error_message(IOError, self.gradient,\n \"Along has to be\"\n \" an input variable\")\n axis = list(self._input_dict.keys()).index(along)\n len_along = len(self._input_dict[along])\n x = self[along]\n y = self[variable]\n if method == 'central':\n mask_p_list = (\n [1], list(range(2, len_along)), [len_along - 1])\n mask_n_list = ([0], list(range(0, len_along - 2)),\n [len_along - 2])\n grad = [\n old_div((np.take(y, mask_p, axis=axis) -\n np.take(y, mask_n, axis=axis)),\n (np.take(x, mask_p, axis=axis) -\n np.take(x, mask_n, axis=axis)))\n for mask_p, mask_n in zip(mask_p_list, mask_n_list)]\n grad = np.concatenate(grad, axis=axis)\n elif method == 'upwind':\n if not velocity:\n definition.error_message(IOError, self.gradient,\n \"Define a velocity for\"\n \" upwind method\")\n elif velocity not in self._output_dict:\n definition.error_message(IOError, self.gradient,\n \"Defined velocity not in the \"\n \"output dictionary\")\n if len(self._input_dict) > 1:\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works NOW only for\"\n \" 1D data\")\n U = self[velocity]\n index_vel_pos = np.where(U >= 0)[0]\n if np.alltrue(np.diff(index_vel_pos == 1)):\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D\"\n \" data with two distinct\"\n \" regions\")\n index_vel_neg = np.where(U < 0)[0]\n if np.alltrue(np.diff(index_vel_neg == 1)):\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D data\"\n \" with two distinct regions\")\n if index_vel_pos.max() > index_vel_neg.min():\n definition.error_message(NotImplemented, self.gradient,\n \"Upwind works only for 1D data\"\n \" with two distinct regions \"\n \"It is assumed to have\"\n \" positive velocity on\"\n \" the left\")\n grad = []\n mask_p_list = np.concatenate([[1], index_vel_pos[1:],\n index_vel_neg[1:],\n index_vel_neg[-1:]])\n mask_n_list = np.concatenate([[0], index_vel_pos[:-1],\n index_vel_neg[:-1],\n index_vel_neg[-2:-1]])\n grad = old_div((y[mask_p_list] - y[mask_n_list]),\n (x[mask_p_list] - x[mask_n_list]))\n return grad\n\n def extract_values(self, variables=None, **kwargs):\n \"\"\"\n Extract values from the data object.\n\n Parameters\n ----------\n variables: list, str (default:None)\n List or single variable to export. If None export all\n the variables\n use_index: bool (default: False)\n Flag for using index or real values for extracting\n properties\n input_variables: float, int\n Input variables as defined in input_dict. Use float or int\n if use_index is False or True\n return_dict: bool (default: False)\n Output is returned as dictionary\n\n Returns\n -------\n float, np.array\n Extracted single value or array of values for multiple\n variables\n\n Examples\n --------\n Extract ``T`` for a given set of values (the input variables are\n ``X`` and ``Y``)::\n\n >>>> data.input_variables()\n ['X', 'Y']\n >>>> T = data.extract_value(X=0.5, Y=0.5, variables='T')\n >>>> print(T)\n 523.00\n\n Now the input variable ``Y`` is not defined. The first value of\n ``Y`` is assumed ::\n\n >>>> T = data.extract_value(X=0.5, variables='T')\n >>>> print(T)\n 350.00\n\n Now use ``use_index`` ::\n\n >>>> T = data.extract_value(X=2, Y=0, variables='T')\n >>>> print(T)\n 400.00\n >>>> T = data.extract_value(X=2, variables='T')\n >>>> print(T)\n 400.00\n\n Now extract more variables ::\n\n >>>> data.extract_value(X=2, Y=0, variables=['T', 'rho'])\n [400, 0.23]\n\n \"\"\"\n use_index = kwargs.get('use_index', False)\n return_dict = kwargs.get('return_dict', False)\n # print('use_index=', use_index)\n # variables = kwargs.get('variables', None)\n points = len(self._input_dict) * [0]\n for var, val in self._input_dict.items():\n if use_index:\n inp_val = kwargs.get(var, 0)\n # set index , default is 0\n else:\n # set value, default is first\n inp_val = kwargs.get(var, self._input_dict[var][0])\n points[list(self.input_dict).index(var)] = inp_val\n # print('points', points)\n if use_index:\n data = self._data[tuple(points)]\n # print('self.data shape', self.data.shape)\n # print('data shape', data.shape)\n if isinstance(variables, list):\n variable_indices = [self._output_dict[v]\n for v in variables\n if v in self._output_dict]\n elif isinstance(variables, str):\n variable_indices = self._output_dict[variables]\n else:\n variable_indices = list(self._output_dict.values())\n data = np.take(data, variable_indices)\n else:\n if not variables:\n variables = self.output_variables\n # print('variables', variables)\n if isinstance(variables, list):\n # return np.array([self.getvalue(points, v) for v in\n # variables]).squeeze()\n data = np.array([self.getvalue(points, v)\n for v in variables]).squeeze()\n elif isinstance(variables, string_types):\n # return self.getvalue(points, variables)[0]\n data = self.getvalue(points, variables)[0]\n\n if return_dict:\n if isinstance(variables, (list, np.ndarray)):\n return collections.OrderedDict(list(zip(variables, data)))\n else:\n return {variables: data}\n else:\n return data\n\n @property\n def shape(self):\n return self.data.shape\n\n @property\n def ndim(self):\n return self.data.ndim\n\n @classmethod\n def join(cls, datas, axis=0):\n \"\"\"\n Join two or more Data classes using concatenate function in\n numpy. The classes must have the same input and output\n variables and the same size in all the dimensions, except the\n one concatenate, defined by the axis.\n\n Parameters\n ----------\n datas: list\n List of Data classes to join.\n axis: int, str, optional\n Axis for concatenate the data. It can be the number of axis\n or the name of the input variable.\n\n Returns\n -------\n New pyFLUT.data.Data instance\n \"\"\"\n # TODO return same datatype as original\n if isinstance(axis, string_types):\n axis_name = axis\n axis = datas[0].input_variable_index(axis)\n else:\n axis_name = datas[0].input_variables()[axis]\n data = np.concatenate([d.data for d in datas], axis=axis)\n input_dict = collections.OrderedDict()\n for var in datas[0].input_dict.keys():\n if axis_name == var:\n input_dict[var] = np.concatenate(\n [d.input_dict[var] for d in datas])\n else:\n input_dict[var] = datas[0].input_dict[var]\n output_dict = datas[0].output_dict\n\n return cls(input_dict=input_dict, output_dict=output_dict,\n data=data)\n", "sub_path": "pyFLUT/data.py", "file_name": "data.py", "file_ext": "py", "file_size_in_byte": 46293, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "builtins.object", "line_number": 49, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 155, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 162, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 163, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 170, "usage_type": "call"}, {"api_name": "operator.itemgetter", "line_number": 171, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 186, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 188, "usage_type": "attribute"}, {"api_name": "numpy.alltrue", "line_number": 193, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 193, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 210, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 212, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 225, "usage_type": "attribute"}, {"api_name": "six.string_types", "line_number": 295, "usage_type": "argument"}, {"api_name": "numpy.insert", "line_number": 301, "usage_type": "call"}, {"api_name": "numpy.delete", "line_number": 311, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 434, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 446, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 446, "usage_type": "name"}, {"api_name": "numpy.empty", "line_number": 462, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 470, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 485, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 486, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 488, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 489, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 526, "usage_type": "call"}, {"api_name": "builtins.zip", "line_number": 541, "usage_type": "call"}, {"api_name": "builtins.zip", "line_number": 543, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 678, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 678, "usage_type": "name"}, {"api_name": "numpy.expand_dims", "line_number": 697, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 697, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 710, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 715, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 727, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 783, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 785, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 787, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 787, "usage_type": "name"}, {"api_name": "numpy.take", "line_number": 797, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 799, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 804, "usage_type": "call"}, {"api_name": "scipy.interpolate.interpolate.RegularGridInterpolator", "line_number": 806, "usage_type": "call"}, {"api_name": "scipy.interpolate.interpolate", "line_number": 806, "usage_type": "attribute"}, {"api_name": "scipy.interpolate", "line_number": 806, "usage_type": "name"}, {"api_name": "scipy.interpolate.interpolate.interp1d", "line_number": 812, "usage_type": "call"}, {"api_name": "scipy.interpolate.interpolate", "line_number": 812, "usage_type": "attribute"}, {"api_name": "scipy.interpolate", "line_number": 812, "usage_type": "name"}, {"api_name": "csv.writer", "line_number": 899, "usage_type": "call"}, {"api_name": "pyevtk.hl.gridToVTK", "line_number": 917, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 921, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 921, "usage_type": "name"}, {"api_name": "h5py.File", "line_number": 941, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 1036, "usage_type": "call"}, {"api_name": "numpy.squeeze", "line_number": 1042, "usage_type": "call"}, {"api_name": "{'subplots': 'matplotlib.pyplot.subplots', 'csv': 'csv', 'gridToVTK': 'pyevtk.hl.gridToVTK'}", "line_number": 1049, "usage_type": "call"}, {"api_name": "tabulate.tabulate", "line_number": 1053, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1087, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1087, "usage_type": "name"}, {"api_name": "builtins.range", "line_number": 1096, "usage_type": "call"}, {"api_name": "builtins.range", "line_number": 1097, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 1100, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 1100, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 1101, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 1102, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 1103, "usage_type": "call"}, {"api_name": "builtins.zip", "line_number": 1104, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1105, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1108, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1108, "usage_type": "name"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1112, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1112, "usage_type": "name"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1116, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1116, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 1120, "usage_type": "call"}, {"api_name": "numpy.alltrue", "line_number": 1121, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 1121, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1122, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1122, "usage_type": "name"}, {"api_name": "numpy.where", "line_number": 1126, "usage_type": "call"}, {"api_name": "numpy.alltrue", "line_number": 1127, "usage_type": "call"}, {"api_name": "numpy.diff", "line_number": 1127, "usage_type": "call"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1128, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1128, "usage_type": "name"}, {"api_name": "pyFLUT.definition.error_message", "line_number": 1132, "usage_type": "call"}, {"api_name": "pyFLUT.definition", "line_number": 1132, "usage_type": "name"}, {"api_name": "numpy.concatenate", "line_number": 1139, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1142, "usage_type": "call"}, {"api_name": "past.utils.old_div", "line_number": 1145, "usage_type": "call"}, {"api_name": "numpy.take", "line_number": 1232, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1240, "usage_type": "call"}, {"api_name": "six.string_types", "line_number": 1242, "usage_type": "argument"}, {"api_name": "numpy.ndarray", "line_number": 1247, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 1248, "usage_type": "call"}, {"api_name": "builtins.zip", "line_number": 1248, "usage_type": "call"}, {"api_name": "six.string_types", "line_number": 1283, "usage_type": "argument"}, {"api_name": "numpy.concatenate", "line_number": 1288, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 1289, "usage_type": "call"}, {"api_name": "numpy.concatenate", "line_number": 1292, "usage_type": "call"}]}
+{"seq_id": "195193404", "text": "from collections.abc import MutableSequence\nfrom typing import Any\n\nimport proto\n\nfrom google.ads.googleads.v14.enums.types.customer_match_upload_key_type import (\n CustomerMatchUploadKeyTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_crm_data_source_type import (\n UserListCrmDataSourceTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator import (\n UserListDateRuleItemOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator import (\n UserListFlexibleRuleOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_logical_rule_operator import (\n UserListLogicalRuleOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator import (\n UserListNumberRuleItemOperatorEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_prepopulation_status import (\n UserListPrepopulationStatusEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_rule_type import (\n UserListRuleTypeEnum,\n)\nfrom google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator import (\n UserListStringRuleItemOperatorEnum,\n)\n\nclass BasicUserListInfo(proto.Message):\n actions: MutableSequence[UserListActionInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n actions: MutableSequence[UserListActionInfo] = ...\n ) -> None: ...\n\nclass CrmBasedUserListInfo(proto.Message):\n app_id: str\n upload_key_type: CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType\n data_source_type: UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n app_id: str = ...,\n upload_key_type: CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType = ...,\n data_source_type: UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType = ...\n ) -> None: ...\n\nclass FlexibleRuleOperandInfo(proto.Message):\n rule: UserListRuleInfo\n lookback_window_days: int\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule: UserListRuleInfo = ...,\n lookback_window_days: int = ...\n ) -> None: ...\n\nclass FlexibleRuleUserListInfo(proto.Message):\n inclusive_rule_operator: UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator\n inclusive_operands: MutableSequence[FlexibleRuleOperandInfo]\n exclusive_operands: MutableSequence[FlexibleRuleOperandInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n inclusive_rule_operator: UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator = ...,\n inclusive_operands: MutableSequence[FlexibleRuleOperandInfo] = ...,\n exclusive_operands: MutableSequence[FlexibleRuleOperandInfo] = ...\n ) -> None: ...\n\nclass LogicalUserListInfo(proto.Message):\n rules: MutableSequence[UserListLogicalRuleInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rules: MutableSequence[UserListLogicalRuleInfo] = ...\n ) -> None: ...\n\nclass LogicalUserListOperandInfo(proto.Message):\n user_list: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n user_list: str = ...\n ) -> None: ...\n\nclass RuleBasedUserListInfo(proto.Message):\n prepopulation_status: UserListPrepopulationStatusEnum.UserListPrepopulationStatus\n flexible_rule_user_list: FlexibleRuleUserListInfo\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n prepopulation_status: UserListPrepopulationStatusEnum.UserListPrepopulationStatus = ...,\n flexible_rule_user_list: FlexibleRuleUserListInfo = ...\n ) -> None: ...\n\nclass SimilarUserListInfo(proto.Message):\n seed_user_list: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n seed_user_list: str = ...\n ) -> None: ...\n\nclass UserListActionInfo(proto.Message):\n conversion_action: str\n remarketing_action: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n conversion_action: str = ...,\n remarketing_action: str = ...\n ) -> None: ...\n\nclass UserListDateRuleItemInfo(proto.Message):\n operator: UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator\n value: str\n offset_in_days: int\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator = ...,\n value: str = ...,\n offset_in_days: int = ...\n ) -> None: ...\n\nclass UserListLogicalRuleInfo(proto.Message):\n operator: UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator\n rule_operands: MutableSequence[LogicalUserListOperandInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator = ...,\n rule_operands: MutableSequence[LogicalUserListOperandInfo] = ...\n ) -> None: ...\n\nclass UserListNumberRuleItemInfo(proto.Message):\n operator: UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator\n value: float\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator = ...,\n value: float = ...\n ) -> None: ...\n\nclass UserListRuleInfo(proto.Message):\n rule_type: UserListRuleTypeEnum.UserListRuleType\n rule_item_groups: MutableSequence[UserListRuleItemGroupInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule_type: UserListRuleTypeEnum.UserListRuleType = ...,\n rule_item_groups: MutableSequence[UserListRuleItemGroupInfo] = ...\n ) -> None: ...\n\nclass UserListRuleItemGroupInfo(proto.Message):\n rule_items: MutableSequence[UserListRuleItemInfo]\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n rule_items: MutableSequence[UserListRuleItemInfo] = ...\n ) -> None: ...\n\nclass UserListRuleItemInfo(proto.Message):\n name: str\n number_rule_item: UserListNumberRuleItemInfo\n string_rule_item: UserListStringRuleItemInfo\n date_rule_item: UserListDateRuleItemInfo\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n name: str = ...,\n number_rule_item: UserListNumberRuleItemInfo = ...,\n string_rule_item: UserListStringRuleItemInfo = ...,\n date_rule_item: UserListDateRuleItemInfo = ...\n ) -> None: ...\n\nclass UserListStringRuleItemInfo(proto.Message):\n operator: UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator\n value: str\n def __init__(\n self,\n mapping: Any | None = ...,\n *,\n ignore_unknown_fields: bool = ...,\n operator: UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator = ...,\n value: str = ...\n ) -> None: ...\n", "sub_path": "google-stubs/ads/googleads/v14/common/types/user_lists.pyi", "file_name": "user_lists.pyi", "file_ext": "pyi", "file_size_in_byte": 7603, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "proto.Message", "line_number": 34, "usage_type": "attribute"}, {"api_name": "collections.abc.MutableSequence", "line_number": 35, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 38, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 41, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 44, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.customer_match_upload_key_type.CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType", "line_number": 46, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.customer_match_upload_key_type.CustomerMatchUploadKeyTypeEnum", "line_number": 46, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_crm_data_source_type.UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType", "line_number": 47, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_crm_data_source_type.UserListCrmDataSourceTypeEnum", "line_number": 47, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 50, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.customer_match_upload_key_type.CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType", "line_number": 54, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.customer_match_upload_key_type.CustomerMatchUploadKeyTypeEnum", "line_number": 54, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_crm_data_source_type.UserListCrmDataSourceTypeEnum.UserListCrmDataSourceType", "line_number": 55, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_crm_data_source_type.UserListCrmDataSourceTypeEnum", "line_number": 55, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 58, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 63, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 70, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator.UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator", "line_number": 71, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator.UserListFlexibleRuleOperatorEnum", "line_number": 71, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 72, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 73, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 76, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator.UserListFlexibleRuleOperatorEnum.UserListFlexibleRuleOperator", "line_number": 79, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_flexible_rule_operator.UserListFlexibleRuleOperatorEnum", "line_number": 79, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 80, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 81, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 84, "usage_type": "attribute"}, {"api_name": "collections.abc.MutableSequence", "line_number": 85, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 88, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 91, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 94, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 98, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 104, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_prepopulation_status.UserListPrepopulationStatusEnum.UserListPrepopulationStatus", "line_number": 105, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_prepopulation_status.UserListPrepopulationStatusEnum", "line_number": 105, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 109, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_prepopulation_status.UserListPrepopulationStatusEnum.UserListPrepopulationStatus", "line_number": 112, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_prepopulation_status.UserListPrepopulationStatusEnum", "line_number": 112, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 116, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 120, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 126, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 131, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 138, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator.UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator", "line_number": 139, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator.UserListDateRuleItemOperatorEnum", "line_number": 139, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 144, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator.UserListDateRuleItemOperatorEnum.UserListDateRuleItemOperator", "line_number": 147, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_date_rule_item_operator.UserListDateRuleItemOperatorEnum", "line_number": 147, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 152, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_logical_rule_operator.UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator", "line_number": 153, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_logical_rule_operator.UserListLogicalRuleOperatorEnum", "line_number": 153, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 154, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 157, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_logical_rule_operator.UserListLogicalRuleOperatorEnum.UserListLogicalRuleOperator", "line_number": 160, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_logical_rule_operator.UserListLogicalRuleOperatorEnum", "line_number": 160, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 161, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 164, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator", "line_number": 165, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator.UserListNumberRuleItemOperatorEnum", "line_number": 165, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 169, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator.UserListNumberRuleItemOperatorEnum.UserListNumberRuleItemOperator", "line_number": 172, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_number_rule_item_operator.UserListNumberRuleItemOperatorEnum", "line_number": 172, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 176, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_rule_type.UserListRuleTypeEnum.UserListRuleType", "line_number": 177, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_rule_type.UserListRuleTypeEnum", "line_number": 177, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 178, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 181, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_rule_type.UserListRuleTypeEnum.UserListRuleType", "line_number": 184, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_rule_type.UserListRuleTypeEnum", "line_number": 184, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 185, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 188, "usage_type": "attribute"}, {"api_name": "collections.abc.MutableSequence", "line_number": 189, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 192, "usage_type": "name"}, {"api_name": "collections.abc.MutableSequence", "line_number": 195, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 198, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 205, "usage_type": "name"}, {"api_name": "proto.Message", "line_number": 214, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator", "line_number": 215, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator.UserListStringRuleItemOperatorEnum", "line_number": 215, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 219, "usage_type": "name"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator.UserListStringRuleItemOperatorEnum.UserListStringRuleItemOperator", "line_number": 222, "usage_type": "attribute"}, {"api_name": "google.ads.googleads.v14.enums.types.user_list_string_rule_item_operator.UserListStringRuleItemOperatorEnum", "line_number": 222, "usage_type": "name"}]}
+{"seq_id": "47976013", "text": "import numpy as np\nfrom ROI_Arrival import ROI_Arrival,ROI_Location\n#prefined imports\nimport sys,time,winsound\nimport numpy as np\nfrom PyQt5.QtWidgets import (QApplication, QPushButton,QWidget,QGridLayout,\n QSizePolicy,QLineEdit,\n QMainWindow,QAction,QVBoxLayout\n ,QDockWidget,QListView,\n QAbstractItemView,QLabel,QFileDialog,QTextEdit,\n QInputDialog,QSlider,QMdiArea,QMdiSubWindow,\n QMessageBox)\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtCore import Qt\n#import numpy as np\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\n\nclass ROI_Viewer(QMainWindow):\n done=False\n def __init__(self,list_time,list_channel,sync_time,calibration):\n super().__init__()\n self.num_sync=sync_time.size\n self.num_pulses=list_time.size\n self.list_time,self.list_channel=list_time,list_channel\n self.sync_time,self.calibration=sync_time,calibration\n self.sync_delta=sync_time[2]-sync_time[1]\n self.lower,self.upper=9.5,10.9\n self.font1=QFont()\n self.font1.setPointSize(12)\n self.size_policy=QSizePolicy.Expanding\n self.menu()\n self.showMaximized()\n self.setWindowTitle('ROI Timing Arrival')\n self.geometry()\n# self.process()\n self.show()\n \n def menu(self):\n self.menuFile=self.menuBar().addMenu('&File')\n self.save_file=QAction('&Save Spectrum')\n self.save_file.triggered.connect(self.save_spectrum)\n self.save_file.setShortcut('CTRL+S')\n self.save_file.setEnabled(False)\n \n # self.save_roi=QAction('&Save ROI')\n # self.save_roi.triggered.connect(self.save_roi_csv)\n # self.save_roi.setEnabled(True)\n self.menuFile.addActions([self.save_file])\n \n def geometry(self):\n r1_label=QLabel(r'Region 1-2 divider: [us]')\n r1_label.setFont(self.font1)\n r2_label=QLabel(r'Region 2-3 divider: [us]')\n r2_label.setFont(self.font1)\n \n self.r_1_slider=QSlider(Qt.Horizontal)\n self.r_1_slider.setSizePolicy(self.size_policy,self.size_policy)\n self.r_1_slider.setMinimum(0)\n self.r_1_slider.setMaximum(self.sync_delta-1)\n self.r_1_slider.setSingleStep(1)\n self.r_1_slider.setTickInterval(50)\n self.r_1_slider.setValue(100)\n self.r_1_slider.setTickPosition(QSlider.TicksBelow)\n self.r_1_slider.valueChanged.connect(self.update_r_1)\n self.r_1_slider.setFont(self.font1)\n \n self.r_2_slider=QSlider(Qt.Horizontal)\n self.r_2_slider.setSizePolicy(self.size_policy,self.size_policy)\n self.r_2_slider.setMinimum(101)\n self.r_2_slider.setMaximum(self.sync_delta)\n self.r_2_slider.setSingleStep(1)\n self.r_2_slider.setTickInterval(50)\n self.r_2_slider.setValue(101)\n self.r_2_slider.setTickPosition(QSlider.TicksBelow)\n self.r_2_slider.valueChanged.connect(self.update_r_2)\n self.r_2_slider.setFont(self.font1)\n \n self.r_1_label=QLabel(self)\n self.r_1_label.setSizePolicy(self.size_policy,self.size_policy)\n self.r_1_label.setText(str(self.r_1_slider.value()))\n self.r_1_label.setFont(self.font1)\n self.r_2_label=QLabel(self)\n self.r_2_label.setSizePolicy(self.size_policy,self.size_policy)\n self.r_2_label.setText(str(self.r_2_slider.value())) \n self.r_2_label.setFont(self.font1)\n \n self.processer=QPushButton('Process',self)\n self.processer.clicked.connect(self.process)\n self.processer.setFont(self.font1)\n \n lower_label=QLabel('Lower ROI: [MeV]',self)\n lower_label.setFont(self.font1)\n upper_label=QLabel('Upper ROI: [MeV]',self)\n upper_label.setFont(self.font1)\n \n self.lower_text=QLineEdit(self)\n self.lower_text.setFont(self.font1)\n self.lower_text.setText(str(self.lower))\n self.upper_text=QLineEdit(self)\n self.upper_text.setFont(self.font1)\n self.upper_text.setText(str(self.upper))\n \n self.time_plot=QWidget()\n self.time_figure=Figure()\n self.time_canvas=FigureCanvas(self.time_figure)\n self.time_toolbar=NavigationToolbar(self.time_canvas,self)\n layout=QVBoxLayout()\n layout.addWidget(self.time_toolbar)\n layout.addWidget(self.time_canvas)\n self.time_plot.setLayout(layout)\n self.time_ax=self.time_canvas.figure.subplots()\n self.time_ax.set_title('Time')\n \n main_=QWidget()\n layout=QGridLayout(self)\n layout.addWidget(r1_label,0,0)\n layout.addWidget(self.r_1_slider,0,1)\n layout.addWidget(self.r_1_label,0,2)\n layout.addWidget(lower_label,0,3)\n layout.addWidget(self.lower_text,0,4)\n layout.addWidget(upper_label,1,3)\n layout.addWidget(self.upper_text,1,4)\n layout.addWidget(r2_label,1,0)\n layout.addWidget(self.r_2_slider,1,1)\n layout.addWidget(self.r_2_label,1,2)\n layout.addWidget(self.processer,2,0)\n layout.addWidget(self.time_plot,3,0,1,5)\n main_.setLayout(layout)\n self.setCentralWidget(main_)\n \n def update_r_1(self):\n self.r_2_slider.setMinimum(self.r_1_slider.value()+1)\n self.r_1_label.setText(str(self.r_1_slider.value()))\n \n def update_r_2(self):\n self.r_2_label.setText(str(self.r_2_slider.value()))\n\n def process(self):\n self.save_file.setEnabled(True)\n # self.save_roi.setEnabled(True)\n s1=time.time()\n delt=(self.sync_time[2]-self.sync_time[1])\n self.lower=float(self.lower_text.text())\n self.upper=float(self.upper_text.text())\n self.arrival,self.height,self.raw=ROI_Arrival(self.sync_time,self.list_time,\n self.num_sync,self.list_channel,\n self.num_pulses,self.lower,\n self.upper,self.calibration)\n num_bins=int(delt/4)\n bins=np.linspace(0,delt,num_bins)\n self.bins=bins\n s=len(self.arrival)\n self.output=ROI_Location(self.arrival,bins,num_bins,s)\n r1,r2,r3=0,0,0\n print('Process ROI Arrivals in {:.3f}s'.format(time.time()-s1))\n for i in range(num_bins):\n if bins[i]<=self.r_1_slider.value():\n r1+=self.output[i]\n elif bins[i]>self.r_1_slider.value() and bins[i]<=self.r_2_slider.value():\n r2+=self.output[i]\n else:\n r3+=self.output[i]\n \n self.time_ax.clear()\n self.time_ax.plot(bins,self.output,'r*')\n self.time_ax.axvline(self.r_1_slider.value(),label='Region 1-2 divider at {:.2f}'.format(self.r_1_slider.value()))\n self.time_ax.axvline(self.r_2_slider.value(),label='Region 2-3 divider at {:.2f}'.format(self.r_2_slider.value()))\n# self.time_ax.set_yscale('log')\n self.time_ax.set_ylabel('Counts',fontsize=18)\n self.time_ax.set_xlabel(r'Arrival Time [$\\mu s$]',fontsize=18)\n self.time_canvas.draw()\n self.done=True\n self.percentages=[r1/(r1+r2+r3)*100,\n r2/(r1+r2+r3)*100,\n r3/(r1+r2+r3)*100]\n QMessageBox.information(self,\n 'ROI Perecentages','''Region 1:{:.2f}%\\nRegion 2:{:.2f}%\\nRegion 3:{:.2f}%'''.format(\n r1/(r1+r2+r3)*100,\n r2/(r1+r2+r3)*100,r3/(r1+r2+r3)*100),\n QMessageBox.Ok)\n# print('Region 1 total ROI percentage: {:.2f}%'.format(r1/(r1+r2+r3)*100))\n# print('Region 2 total ROI percentage: {:.2f}%'.format(r2/(r1+r2+r3)*100))\n# print('Region 3 total ROI percentage: {:.2f}%'.format(r3/(r1+r2+r3)*100))\n \n def save_spectrum(self):\n name=QFileDialog.getSaveFileName(self,'File Name','',\n 'Text File (*.txt);;Comma Seperated File (*.csv)')\n if name[0]!=' ':\n f=open(name[0],'w')\n f.write('%{:.2f},{:.2f},{:.2f}\\n'.format(*self.percentages))\n for i in range(len(self.bins)):\n f.write('{:.6f},{}\\n'.format(self.bins[i],self.output[i]))\n f.close()\n \n # def save_roi_csv(self):\n # name,ok=QFileDialog.getSaveFileName(self,'Safe File Name','',\n # 'Comma Seperated File (*.csv)')\n # if ok:\n # f=open(name,'w')\n # f.write('Pulse_Height(MeV),Time(s)\\n')\n # print(len(self.height))\n # for i in range(len(self.height)):\n # f.write('{:.3f},{:.3f}\\n'.format(self.height[i],self.raw[i]*1e-6))\n # f.close()\n # print('All finished')", "sub_path": "ROI_Arrival_Viewer.py", "file_name": "ROI_Arrival_Viewer.py", "file_ext": "py", "file_size_in_byte": 9050, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 20, "usage_type": "name"}, {"api_name": "PyQt5.QtGui.QFont", "line_number": 30, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QSizePolicy.Expanding", "line_number": 32, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QSizePolicy", "line_number": 32, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QAction", "line_number": 42, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 53, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 55, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QSlider", "line_number": 58, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.Horizontal", "line_number": 58, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 58, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QSlider.TicksBelow", "line_number": 65, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QSlider", "line_number": 65, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QSlider", "line_number": 69, "usage_type": "call"}, {"api_name": "PyQt5.QtCore.Qt.Horizontal", "line_number": 69, "usage_type": "attribute"}, {"api_name": "PyQt5.QtCore.Qt", "line_number": 69, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QSlider.TicksBelow", "line_number": 76, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QSlider", "line_number": 76, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 80, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 84, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QPushButton", "line_number": 89, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 93, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLabel", "line_number": 95, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 98, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QLineEdit", "line_number": 101, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 105, "usage_type": "call"}, {"api_name": "matplotlib.figure.Figure", "line_number": 106, "usage_type": "call"}, {"api_name": "matplotlib.backends.backend_qt5agg.FigureCanvas", "line_number": 107, "usage_type": "call"}, {"api_name": "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "line_number": 108, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QVBoxLayout", "line_number": 109, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QWidget", "line_number": 116, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QGridLayout", "line_number": 117, "usage_type": "call"}, {"api_name": "time.time", "line_number": 143, "usage_type": "call"}, {"api_name": "ROI_Arrival.ROI_Arrival", "line_number": 147, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 152, "usage_type": "call"}, {"api_name": "ROI_Arrival.ROI_Location", "line_number": 155, "usage_type": "call"}, {"api_name": "time.time", "line_number": 157, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.information", "line_number": 178, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 178, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QMessageBox.Ok", "line_number": 182, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMessageBox", "line_number": 182, "usage_type": "name"}, {"api_name": "PyQt5.QtWidgets.QFileDialog.getSaveFileName", "line_number": 188, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QFileDialog", "line_number": 188, "usage_type": "name"}]}
+{"seq_id": "51703447", "text": "# Import libraries\nimport requests\nimport urllib.request\nimport time\nimport datetime\nfrom bs4 import BeautifulSoup\n\n# Set the URL you want to webscrape from\n#url = 'http://web.mta.info/developers/turnstile.html'\nurl = 'https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Fallzahlen.html'\n\n# Connect to the URL\nresponse = requests.get(url)\n#print (response)\n\n# Parse HTML and save to BeautifulSoup object¶\nsoup = BeautifulSoup(response.text, \"html.parser\")\n#print(soup)\n\n#print (soup.findAll('td'))\n\ndata = []\ntable = soup.find('table')\n#rows = table.findAll('tr')\n#for row in rows:\n# print(row)\n#\n# cols = row.findAll('td')[6]\n# print(cols)\n#\n# country = cols[0].string\n# number = cols[1].string\n# diff = cols[2].string\n# np100t = cols[3].string\n# dead = cols[4].string\n# #remarks = cols[5].string\n#\n# #entry = (country, number, diff, np100t, dead, remarks)\n# entry = (country, number, diff, np100t, dead)\n# print (entry)\n\ndt_date = datetime.datetime.now()\ndate = datetime.date.today()\n#print (\"The Current date is:\" ,dt_date)\n#print(\"In specified format:\", dt_date.isoformat())\nfilename='RKI_Corona_'+dt_date.isoformat()\n#this file contais all data from the RKI table\nfilename3='RKI_Corona_'+dt_date.isoformat()+'ALL'\nf1=open(filename, 'w')\nf3=open(filename3, 'w')\n\nrows = table.find_all('tr')\n#print(rows)\nfor row in rows:\n cols = row.findAll('td')\n if len(cols) > 0:\n country = cols[0].text.strip()\n number = cols[1].text.strip()\n diff = cols[2].text.strip()\n np100t = cols[3].text.strip()\n inc7 = cols[4].text.strip()\n dead = cols[5].text.strip()\n f1.write(\"%s, %s, %s, %s, %s, %s\\n\" % (date, country, number, diff, np100t, dead))\n f3.write(\"%s, %s, %s, %s, %s, %s, %s\\n\" % (date, country, number, diff, np100t, inc7, dead))\n #cols = [ele.text.strip() for ele in cols]\n #data.append([ele for ele in cols if ele])\n\nf1.close()\nf3.close()\n\nprint(filename)\nf2=open(\"file_of_the_day\", 'w')\nf2.write(\"%s\\n\" % filename)\nf2.close\n", "sub_path": "rki_get_data.py", "file_name": "rki_get_data.py", "file_ext": "py", "file_size_in_byte": 2046, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "requests.get", "line_number": 13, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 42, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 42, "usage_type": "attribute"}, {"api_name": "datetime.date.today", "line_number": 43, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 43, "usage_type": "attribute"}]}
+{"seq_id": "210891007", "text": "#\n# build the source distribution for tor_async_couchdb-*.*.*.tar.gz\n#\n# >git clone https://github.com/simonsdave/tor-async-couchdb.git\n# >cd tor-async-couchdb\n# >source cfg4dev\n# >python setup.py sdist --formats=gztar\n#\n# update pypitest with both meta data and source distribution (FYI ...\n# use of pandoc is as per https://github.com/pypa/pypi-legacy/issues/148#issuecomment-226939424\n# since PyPI requires long description in RST but the repo's readme is in\n# markdown)\n#\n# >pandoc README.md -o README.rst\n# >twine upload dist/* -r testpypi\n#\n# you will be able to find the package at\n#\n# https://test.pypi.org/project/tor-async-couchdb\n#\n# use the uploaded package\n#\n# >pip install -i https://testpypi.python.org/pypi tor_async_couchdb\n#\nimport re\nfrom setuptools import setup\n\n#\n# this approach used below to determine ```version``` was inspired by\n# https://github.com/kennethreitz/requests/blob/master/setup.py#L31\n#\n# why this complexity? wanted version number to be available in the\n# a runtime.\n#\n# the code below assumes the distribution is being built with the\n# current directory being the directory in which setup.py is stored\n# which should be totally fine 99.9% of the time. not going to add\n# the coode complexity to deal with other scenarios\n#\nreg_ex_pattern = r\"__version__\\s*=\\s*['\\\"](?P[^'\\\"]*)['\\\"]\"\nreg_ex = re.compile(reg_ex_pattern)\nversion = \"\"\nwith open(\"tor_async_couchdb/__init__.py\", \"r\") as fd:\n for line in fd:\n match = reg_ex.match(line)\n if match:\n version = match.group(\"version\")\n break\nif not version:\n raise Exception(\"Can't locate tor_async_couchdb's version number\")\n\n\ndef _long_description():\n try:\n with open('README.rst', 'r') as f:\n return f.read()\n except IOError:\n # simple fix to avoid failure on 'source cfg4dev'\n return \"a long description\"\n\n\n# list of valid classifiers @ https://pypi.python.org/pypi?%3Aaction=list_classifiers\n_classifiers = [\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n]\n\n_author = \"Dave Simons\"\n_author_email = \"simonsdave@gmail.com\"\n\n_keywords = [\n 'tornado',\n 'couchdb',\n]\n\nsetup(\n name=\"tor_async_couchdb\",\n packages=[\n \"tor_async_couchdb\",\n ],\n install_requires=[\n \"python-keyczar==0.716\",\n \"requests>=2.7.0\",\n ],\n version=version,\n description=\"Tornado Async Client for CouchDB\",\n long_description=_long_description(),\n author=_author,\n author_email=_author_email,\n maintainer=_author,\n maintainer_email=_author_email,\n license=\"MIT\",\n url=\"https://github.com/simonsdave/tor-async-couchdb\",\n download_url=\"https://github.com/simonsdave/tor-async-couchdb/tarball/v%s\" % version,\n keywords=_keywords,\n classifiers=_classifiers,\n)\n", "sub_path": "setup.py", "file_name": "setup.py", "file_ext": "py", "file_size_in_byte": 3175, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "re.compile", "line_number": 41, "usage_type": "call"}, {"api_name": "setuptools.setup", "line_number": 83, "usage_type": "call"}]}
+{"seq_id": "486098361", "text": "import json\n\nfrom db import models, ForeignKey, createsession, engine, attach_session\nfrom auth import User\nfrom core import defaults, error\nfrom accounts import Currency, Account, Movement\n\nfrom datetime import datetime\n\nfrom sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound\nfrom sqlalchemy import Column, String, Numeric, DateTime, Text, Boolean, Integer\n\nimport urllib2\nimport blockchain.formatstrings as blc\n\nclass CurrencyWallet(models.Model):\n\tcurrency = ForeignKey(Currency)\n\tidentifier = Column(String(100))\n\tpassword = Column(String(100))\n\tdefaultrate = Column(Numeric(20, 10))\n\n\t@attach_session\n\tdef get_rate(self, session):\n\t\tstock = self.currency.stock\n\n\t\turl = blc['getbalance'].format(identifier=identifier, password=password)\n\n\t\tresponse = urllib2.urlopen(url)\n\t\tdata = json.loads(response.read())\n\n\t\tif 'error' in data:\n\t\t\traise Exception(data['error'])\n\n\t\tif 'balance' in data:\n\t\t\tbalance = Decimal(data['balance'])\n\t\telse:\n\t\t\traise Exception('No balance.')\n\n\t\trate = (balance / Decimal('1e8')) / stock\n\n\t\tif rate == Decimal(0):\n\t\t\trate = self.defaultrate\n\n\t\treturn rate\n\n\t@staticmethod\n\t@attach_session\n\tdef getinfo(currency, session):\n\t\tif isinstance(currency, str):\n\t\t\ttry:\n\t\t\t\tcurrency = session.query(Currency).filter_by(name=currency).one()\n\t\t\texcept NoResultFound:\n\t\t\t\traise Exception('Invalid currency.')\n\n\t\ttry:\n\t\t\twalletinfo = session.query(CurrencyWallet).filter_by(currency=currency).one()\n\t\texcept NoResultFound:\n\t\t\traise Exception('No wallet info found.')\n\t\texcept MultipleResultsFound:\n\t\t\traise Exception('Wallet info error.')\n\n\t\tresponse = {\n\t\t\t\"currency\": currency.name,\n\t\t\t\"identifier\": walletinfo.identifier,\n\t\t\t\"password\": walletinfo.password,\n\t\t\t\"defaultrate\": walletinfo.defaultrate\n\t\t}\n\n\t\treturn response\n\n\nclass AccountWallet(models.Model):\n\taccount = Column(String(255))\n\taddress = Column(String(50))\n\nclass IncomingTransactions(models.Model):\n\ttxhash = Column(String(255))\n\taccount = Column(String(255))\n\nclass MovementQueue(models.Model):\n\ttimestamp = Column(DateTime)\n\tmovement = ForeignKey(Movement)\n\torig = Column(String(255))\n\tdest = Column(String(255))\n\tuser = ForeignKey(User)\n\tstatus = Column(String(50))\n\n\t@staticmethod\n\t@attach_session\n\tdef next(status, session):\n\t\ttry:\n\t\t\titem = session.query(MovementQueue).filter_by(status=status).order_by('-timestamp').first()\n\t\texcept NoResultFound:\n\t\t\treturn None\n\n\t\treturn item\n\n\t@staticmethod\n\t@attach_session\n\tdef put(status, movement, orig, dest, user, session):\n\n\t\tif isinstance(orig, Account):\n\t\t\torig = orig.name\n\n\t\tif isinstance(dest, Account):\n\t\t\tdest = dest.name\n\n\t\titem = MovementQueue(timestamp=movement.timestamp, movement=movement, orig=orig, dest=dest, user=user, status=status)\n\t\tsession.add(item)\n\t\tpass", "sub_path": "modules/blockchain/models.py", "file_name": "models.py", "file_ext": "py", "file_size_in_byte": 2727, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "db.models.Model", "line_number": 16, "usage_type": "attribute"}, {"api_name": "db.models", "line_number": 16, "usage_type": "name"}, {"api_name": "db.ForeignKey", "line_number": 17, "usage_type": "call"}, {"api_name": "accounts.Currency", "line_number": 17, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 18, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 18, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 19, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 20, "usage_type": "call"}, {"api_name": "sqlalchemy.Numeric", "line_number": 20, "usage_type": "call"}, {"api_name": "blockchain.formatstrings", "line_number": 26, "usage_type": "name"}, {"api_name": "urllib2.urlopen", "line_number": 28, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 29, "usage_type": "call"}, {"api_name": "db.attach_session", "line_number": 22, "usage_type": "name"}, {"api_name": "accounts.Currency", "line_number": 51, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.exc.NoResultFound", "line_number": 52, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.exc.NoResultFound", "line_number": 57, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.exc.MultipleResultsFound", "line_number": 59, "usage_type": "name"}, {"api_name": "db.attach_session", "line_number": 47, "usage_type": "name"}, {"api_name": "db.models.Model", "line_number": 72, "usage_type": "attribute"}, {"api_name": "db.models", "line_number": 72, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 73, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 74, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 74, "usage_type": "call"}, {"api_name": "db.models.Model", "line_number": 76, "usage_type": "attribute"}, {"api_name": "db.models", "line_number": 76, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 77, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 77, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 78, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 78, "usage_type": "call"}, {"api_name": "db.models.Model", "line_number": 80, "usage_type": "attribute"}, {"api_name": "db.models", "line_number": 80, "usage_type": "name"}, {"api_name": "sqlalchemy.Column", "line_number": 81, "usage_type": "call"}, {"api_name": "sqlalchemy.DateTime", "line_number": 81, "usage_type": "argument"}, {"api_name": "db.ForeignKey", "line_number": 82, "usage_type": "call"}, {"api_name": "accounts.Movement", "line_number": 82, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 83, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 83, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 84, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 84, "usage_type": "call"}, {"api_name": "db.ForeignKey", "line_number": 85, "usage_type": "call"}, {"api_name": "auth.User", "line_number": 85, "usage_type": "argument"}, {"api_name": "sqlalchemy.Column", "line_number": 86, "usage_type": "call"}, {"api_name": "sqlalchemy.String", "line_number": 86, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.exc.NoResultFound", "line_number": 93, "usage_type": "name"}, {"api_name": "db.attach_session", "line_number": 89, "usage_type": "name"}, {"api_name": "accounts.Account", "line_number": 102, "usage_type": "argument"}, {"api_name": "accounts.Account", "line_number": 105, "usage_type": "argument"}, {"api_name": "db.attach_session", "line_number": 99, "usage_type": "name"}]}
+{"seq_id": "181603569", "text": "import json\nimport time\nPOPULATION_SIZE = 40\nMUTATION_RATE = 0.1\nCROSSOVER_RATE = 0.9\nTOURNAMENT_SELECTION_SIZE = 3\nNUMB_OF_ELITE_SCHEDULES = 4\nSPLIT_VAR = 4\nNUMB_OF_GENERATION = 35\n\ndef run():\n\n from data import Data\n from genetic_algorithm import GeneticAlgorithm\n from population import Population\n from utils import get_random_number\n\n generation_number = 0\n data = Data()\n param = []\n param.append([POPULATION_SIZE,MUTATION_RATE,CROSSOVER_RATE,TOURNAMENT_SELECTION_SIZE,0,NUMB_OF_ELITE_SCHEDULES])\n \n start = time.time()\n\n # Creation de la population initiale\n _genetic_algorithm = GeneticAlgorithm(data=data, param=param[0])\n _population = Population(size=POPULATION_SIZE, data=data)\n\n while _population.schedules[0]._fitness != 1.0:\n generation_number += 1\n \n # Calcul la fitness de chaque emploi du temps dans la population\n for schedule in _population.schedules:\n schedule._fitness = schedule.calculate_fitness()\n \n # Tri la population et evolution de cette population\n _population.sort_by_fitness()\n _population = _genetic_algorithm.evolve(population=_population)\n \n for schedule in _population.schedules:\n schedule._fitness = schedule.calculate_fitness()\n \n _population.sort_by_fitness()\n print(\"fitness : {}\".format(_population.schedules[0]._fitness))\n\n end = time.time()\n print(\"Nombre de générations : {} Temps d'exécution : {} s\".format(generation_number, end-start))\n print(_population.schedules[0])\n return (generation_number,end-start)\n\n# Methode pour obtenir un csv avec les resultats utiles a l'analyse de l'algorithme\ndef data_analysis(nb_of_exec,name_of_the_csv):\n with open(\"analyse/\"+name_of_the_csv,\"w+\") as f:\n f.write(\"nbRun;nbGeneration;timeExec\\n\")\n for i in range(nb_of_exec):\n print(i)\n res_tuple = run()\n string = str(i)+\";\"+str(res_tuple[0])+\";\"+str(res_tuple[1])+\"\\n\"\n f.write(string) \n\nif __name__ == '__main__' and __package__ is None:\n run()", "sub_path": "Scheduling/main_sequentiel_local.py", "file_name": "main_sequentiel_local.py", "file_ext": "py", "file_size_in_byte": 2063, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "data.Data", "line_number": 19, "usage_type": "call"}, {"api_name": "time.time", "line_number": 23, "usage_type": "call"}, {"api_name": "genetic_algorithm.GeneticAlgorithm", "line_number": 26, "usage_type": "call"}, {"api_name": "population.Population", "line_number": 27, "usage_type": "call"}, {"api_name": "time.time", "line_number": 46, "usage_type": "call"}]}
+{"seq_id": "169094284", "text": "import pandas as pd\nfrom scipy import misc\nimport argparse\nfrom matplotlib.pyplot import imshow\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport scipy.io\nimport scipy.misc\nimport os, sys\nimport shutil\nimport fnmatch\nimport math\nimport random, shutil\nfrom PIL import Image\nimport numpy as np\nimport tensorflow as tf\nfrom keras import backend as K\nfrom keras.layers import Input, Lambda, Conv2D\nfrom keras.models import load_model, Model\nfrom keras import optimizers, initializers\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopping\n\nfrom yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes\nfrom retrain_yolo import process_data,process_data_pil,process_data_pil_wide,get_classes,get_anchors,get_detector_mask,train,draw\nfrom yad2k.models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes,preprocess_true_boxes_true_box, yolo_loss, yolo_body, yolo_eval\n\n\ndef predict_any(sess , model, image_file, anchors, class_names, max_boxes, score_threshold, iou_threshold):\n \n # Get head of model\n yolo_outputs_ = yolo_head(model.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n \n # Preprocess your image\n model_image_size = model.inputs[0].get_shape().as_list()[-3:-1]\n image, image_data = preprocess_image(image_file, model_image_size = model_image_size )\n \n img=plt.imread(image_file)\n img_shape_ = img.shape[0:2]\n print( \"Reshaping input image \"+str( img_shape_) +\" to model input shape \"+str(model_image_size) )\n if img_shape_[0]>img_shape_[1]:\n print( \"Wrong input size \",str( img_shape_), \" Exiting\" )\n return (0,0,0)\n # Get the Tensors\n boxes, scores, classes = yolo_eval(yolo_outputs_, [float(i) for i in list(img_shape_)],\n max_boxes,\n score_threshold,\n iou_threshold) \n\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model.input: image_data,\n input_image_shape: [image_data.shape[2], image_data.shape[3]],\n K.learning_phase(): 0\n })\n\n # Print predictions info\n print('Found {} boxes for {}'.format(len(out_boxes), image_file))\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file.split('/')[-1]), quality=90)\n # Display the results in the notebook\n plt.figure()\n\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file.split('/')[-1]))\n plt.imshow(output_image)\n\n return out_scores, out_boxes, out_classes\n\n# Wrap the Yolo model with other model for training: You can select how to wrpait and if you wnat to do transfer learning\n# Create model around yolo model \n# Use freeze_body for doing transfer learning on 1st training stage \ndef create_model(anchors, class_names, load_pretrained=True, freeze_body=True, regularization_rate = 0.01):\n '''\n returns the body of the model and the model\n\n # Params:\n\n load_pretrained: whether or not to load the pretrained model or initialize all weights\n\n freeze_body: whether or not to freeze all weights except for the last layer's\n\n # Returns:\n\n model_body: YOLOv2 with new output layer\n\n model: YOLOv2 with custom loss Lambda layer\n\n '''\n\n detectors_mask_shape = (13, 13, 5, 1)\n matching_boxes_shape = (13, 13, 5, 5)\n\n # Create model input layers.\n image_input = Input(shape=(416, 416, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n # Create model body.\n yolo_model = yolo_body(image_input, len(anchors), len(class_names))\n topless_yolo = Model(yolo_model.input, yolo_model.layers[-2].output)\n\n if load_pretrained:\n # Save topless yolo:\n topless_yolo_path = os.path.join('model_data', 'yolo_topless.h5')\n if not os.path.exists(topless_yolo_path):\n print(\"CREATING TOPLESS WEIGHTS FILE\")\n yolo_path = os.path.join('model_data', 'yolo.h5')\n model_body = load_model(yolo_path)\n model_body = Model(model_body.inputs, model_body.layers[-2].output)\n model_body.save_weights(topless_yolo_path)\n topless_yolo.load_weights(topless_yolo_path)\n\n if freeze_body:\n for layer in topless_yolo.layers:\n layer.trainable = False\n final_layer = Conv2D(len(anchors)*(5+len(class_names)), (1, 1), activation='linear')(topless_yolo.output)\n \n # Implement regularization\n if regularization_rate: # if we want regularization\n for layer in topless_yolo.layers:\n if hasattr(layer, 'kernel_regularizer'):\n layer.kernel_regularizer = regularization_rate\n \n model_body = Model(image_input, final_layer)\n\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n\n model = Model(\n [model_body.input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n\n return model_body, model\n\ndef create_model_wide(sess,anchors, class_names, load_pretrained=True, freeze_body=True, regularization_rate = 0.01,\n initialize_weights = False):\n '''\n returns the body of the model and the model\n\n # Params:\n\n load_pretrained: whether or not to load the pretrained model or initialize all weights\n\n freeze_body: whether or not to freeze all weights except for the last layer's\n\n # Returns:\n\n model_body: YOLOv2 with new output layer\n\n model: YOLOv2 with custom loss Lambda layer\n\n '''\n\n detectors_mask_shape = (13, 19, 5, 1)\n matching_boxes_shape = (13, 19, 5, 5)\n\n # Create model input layers.\n image_input = Input(shape=(416, 608, 3))\n boxes_input = Input(shape=(None, 5))\n detectors_mask_input = Input(shape=detectors_mask_shape)\n matching_boxes_input = Input(shape=matching_boxes_shape)\n\n # Create model body.\n yolo_model = yolo_body(image_input, len(anchors), len(class_names))\n topless_yolo = Model(yolo_model.input, yolo_model.layers[-2].output)\n \n if load_pretrained:\n # Save topless yolo:\n topless_yolo_path = os.path.join('model_data', 'yolo_topless.h5')\n if not os.path.exists(topless_yolo_path):\n print(\"CREATING TOPLESS WEIGHTS FILE\")\n yolo_path = os.path.join('model_data', 'yolo.h5')\n model_body = load_model(yolo_path)\n model_body = Model(model_body.inputs, model_body.layers[-2].output)\n model_body.save_weights(topless_yolo_path)\n topless_yolo.load_weights(topless_yolo_path)\n\n if freeze_body:\n for layer in topless_yolo.layers:\n layer.trainable = False\n final_layer = Conv2D(len(anchors)*(5+len(class_names)), (1, 1), activation='linear')(topless_yolo.output)\n \n model_body = Model(image_input, final_layer)\n \n # Implement regularization\n if regularization_rate: # if we want regularization\n for layer in model_body.layers:\n if hasattr(layer, 'kernel_regularizer'):\n layer.kernel_regularizer = regularization_rate\n \n # Implement initialize_weights\n if initialize_weights: # if we want initialize\n for layer in model_body.layers:\n if hasattr(layer, 'kernel_initializer'):\n layer.kernel_initializer = initializers.get(\"glorot_uniform\")\n layer.kernel.initializer.run(session=sess)\n \n# print(model_body.output)\n # Place model loss on CPU to reduce GPU memory usage.\n with tf.device('/cpu:0'):\n # TODO: Replace Lambda with custom Keras layer for loss.\n model_loss = Lambda(\n yolo_loss,\n output_shape=(1, ),\n name='yolo_loss',\n arguments={'anchors': anchors,\n 'num_classes': len(class_names)})([\n model_body.output, boxes_input,\n detectors_mask_input, matching_boxes_input\n ])\n\n model = Model(\n [model_body.input, boxes_input, detectors_mask_input,\n matching_boxes_input], model_loss)\n\n return model_body, model\n\ndef get_batch(list_filenames, batch_size,boxes_dir, class_idx,classes_path,anchors_path): \n # Get anchors and classes names\n class_names = get_classes(classes_path)\n anchors = get_anchors(anchors_path)\n Img_db = pd.read_csv(boxes_dir, header = 0)\n while True:\n for batches in range(len(list_filenames) // batch_size):\n images_list = []\n boxes_list = []\n image_data = None\n boxes = None\n for image_sample in list_filenames[batches*batch_size:min(len(list_filenames),(batches+1)*batch_size)]:\n \n# images_list.append( mpimg.imread(image_sample) )\n images_list.append( Image.open( image_sample ) )\n \n # Write the labels and boxes\n # Original boxes stored as 1D list of class, x_min, y_min, x_max, y_max.\n labels_boxes = []\n # print(Img_db[Img_db['image_filename']==image_sample.split(\"/\")[-1]].as_matrix())\n for box_matched in Img_db[Img_db['image_filename']==image_sample.split(\"/\")[-1]].as_matrix():\n labels_boxes.append( [class_idx[box_matched[-2]], *box_matched[2:6]] )\n boxes_list.append(np.asarray(labels_boxes))\n \n # Check if image is fliped and portrait it\n if images_list[-1].width= iou_eval_threshold and preds[0] == grounds[0] ):\n true_positives += 1\n labels_boxes_pred[i][0]=100\n labels_boxes_ground[j][0]=200\n\n # Precision and recall\n positive_detections += labels_boxes_pred.shape[0]\n positive_samples += labels_boxes_ground.shape[0]\n \n \n# print(true_positives,positive_samples,positive_detections)\n \n if(positive_detections!=0 and positive_samples!=0 ):\n precision = float(true_positives) / float(positive_detections)\n recall = float(true_positives) / float(positive_samples)\n\n print( \" mean precision = \",precision,\" , mean recall = \",recall )\n print( \" Final F1 score = \",2*precision*recall/(precision+recall) )\n\ndef nexar_eval_test(sess , model, image_files, boxes_dir, anchors,class_idx, class_names, max_boxes, score_threshold,\n iou_threshold=0.5, plot_result = False ):\n ## Evaluate all images in the the image_files list (Test images) and save the results to an Excel files with results\n # Resturns a Pandas Dataframe as a table with all the outputs boxes, confidences, etc\n \n # Define output dict\n results = { 'image_filename': [],'x0':[],'y0':[],'x1':[],'y1':[],'label':[],'confidence':[] }\n # Get head of model\n yolo_outputs_ = yolo_head(model.output, anchors, len(class_names))\n input_image_shape = K.placeholder(shape=(2, ))\n # Get the database\n# Test_img_db = pd.read_csv(boxes_dir, header = 0)\n \n # Get input image size\n img=plt.imread(image_files[0])\n img_shape_ = img.shape[0:2]\n \n # Get model input size\n model_image_size = model.inputs[0].get_shape().as_list()[-3:-1]\n \n # Get the Tensors\n boxes, scores, classes = yolo_eval(yolo_outputs_, [float(i) for i in list(img_shape_)],\n max_boxes,\n score_threshold,\n iou_threshold)\n\n for image_file in image_files: # Loop over all the files\n ## Get models output\n # Preprocess your image\n image, image_data = preprocess_image(image_file, model_image_size = model_image_size )\n # Run the session with the correct tensors and choose the correct placeholders in the feed_dict.\n out_boxes, out_scores, out_classes = sess.run(\n [boxes, scores, classes],\n feed_dict={\n model.input: image_data,\n input_image_shape: [image_data.shape[2], image_data.shape[3]],\n K.learning_phase(): 0\n })\n if plot_result:\n # Plot in comparison: Detection\n # Generate colors for drawing bounding boxes.\n colors = generate_colors(class_names)\n # Draw bounding boxes on the image file\n draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)\n # Save the predicted bounding box on the image\n image.save(os.path.join(\"out\", image_file.split('/')[-1]), quality=90)\n # Display the results in the notebook\n output_image = scipy.misc.imread(os.path.join(\"out\", image_file.split('/')[-1]))\n plt.imshow(output_image)\n plt.show()\n # control\n input(\"Press a Enter to continue...\")\n \n # Save to results AND Swap x and y dimensions: they are ok for ploting but not for submiting\n # order is x0,y0,x1,y1\n for i in range(0,out_boxes.shape[0]):\n results['image_filename'].append( image_file.split('/')[-1] )\n results['x0'].append( out_boxes[i,1] )\n results['y0'].append( out_boxes[i,0] )\n results['x1'].append( out_boxes[i,3] )\n results['y1'].append( out_boxes[i,2] )\n results['label'].append( class_names[ out_classes[i] ] )\n results['confidence'].append( out_scores[i] )\n # To Pandas and Excel\n df = pd.DataFrame(data=results)\n df=df[[ 'image_filename','x0','y0','x1','y1','label','confidence' ]]\n \n return df\ndef preprocess_true_boxes_true_box(true_boxes, anchors, image_size):\n \"\"\"Find detector in YOLO where ground truth box should appear.\n\n Parameters\n ----------\n true_boxes : array\n List of ground truth boxes in form of relative x, y, w, h, class.\n Relative coordinates are in the range [0, 1] indicating a percentage\n of the original image dimensions.\n anchors : array\n List of anchors in form of w, h.\n Anchors are assumed to be in the range [0, conv_size] where conv_size\n is the spatial dimension of the final convolutional features.\n image_size : array-like\n List of image dimensions in form of h, w in pixels.\n\n Returns\n -------\n detectors_mask : array\n 0/1 mask for detectors in [conv_height, conv_width, num_anchors, 1]\n that should be compared with a matching ground truth box.\n matching_true_boxes: array\n Same shape as detectors_mask with the corresponding ground truth box\n adjusted for comparison with predicted parameters at training time.\n \"\"\"\n height, width = image_size\n num_anchors = len(anchors)\n # Downsampling factor of 5x 2-stride max_pools == 32.\n # TODO: Remove hardcoding of downscaling calculations.\n assert height % 32 == 0, 'Image sizes in YOLO_v2 must be multiples of 32.'\n assert width % 32 == 0, 'Image sizes in YOLO_v2 must be multiples of 32.'\n conv_height = height // 32\n conv_width = width // 32\n# print(conv_width,conv_height)\n num_box_params = true_boxes.shape[1]\n detectors_mask = np.zeros(\n (conv_height, conv_width, num_anchors, 1), dtype=np.float32)\n matching_true_boxes = np.zeros(\n (conv_height, conv_width, num_anchors, num_box_params),\n dtype=np.float32)\n# print(detectors_mask.shape)\n for box in true_boxes:\n # scale box to convolutional feature spatial dimensions\n box_class = box[4:5]\n box = box[0:4] * np.array(\n [conv_width, conv_height, conv_width, conv_height])\n i = np.floor(box[1]).astype('int')\n j = np.floor(box[0]).astype('int')\n best_iou = 0\n best_anchor = 0\n for k, anchor in enumerate(anchors):\n # Find IOU between box shifted to origin and anchor box.\n box_maxes = box[2:4] / 2.\n box_mins = -box_maxes\n anchor_maxes = (anchor / 2.)\n anchor_mins = -anchor_maxes\n \n intersect_mins = np.maximum(box_mins, anchor_mins)\n intersect_maxes = np.minimum(box_maxes, anchor_maxes)\n intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_area = intersect_wh[0] * intersect_wh[1]\n box_area = box[2] * box[3]\n anchor_area = anchor[0] * anchor[1]\n iou = intersect_area / (box_area + anchor_area - intersect_area)\n if iou > best_iou:\n best_iou = iou\n best_anchor = k\n\n if best_iou > 0:\n detectors_mask[i, j, best_anchor] = 1\n adjusted_box = np.array(\n [\n box[0] - j, box[1] - i,\n# np.log(box[2] / anchors[best_anchor][0]),\n# np.log(box[3] / anchors[best_anchor][1]), box_class\n box[2],\n box[3], box_class\n ],\n dtype=np.float32)\n matching_true_boxes[i, j, best_anchor] = adjusted_box\n return detectors_mask, matching_true_boxes\n", "sub_path": "src/nexar_yolo_utils2.py", "file_name": "nexar_yolo_utils2.py", "file_ext": "py", "file_size_in_byte": 27719, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "yad2k.models.keras_yolo.yolo_head", "line_number": 31, "usage_type": "call"}, {"api_name": "keras.backend.placeholder", "line_number": 32, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 32, "usage_type": "name"}, {"api_name": "yolo_utils.preprocess_image", "line_number": 36, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imread", "line_number": 38, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 38, "usage_type": "name"}, {"api_name": "yad2k.models.keras_yolo.yolo_eval", "line_number": 45, "usage_type": "call"}, {"api_name": "keras.backend.learning_phase", "line_number": 56, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 56, "usage_type": "name"}, {"api_name": "yolo_utils.generate_colors", "line_number": 62, "usage_type": "call"}, {"api_name": "yolo_utils.draw_boxes", "line_number": 64, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 68, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 68, "usage_type": "name"}, {"api_name": "scipy.misc.imread", "line_number": 70, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 70, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 70, "usage_type": "call"}, {"api_name": "os.path", "line_number": 70, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 71, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 71, "usage_type": "name"}, {"api_name": "keras.layers.Input", "line_number": 100, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 101, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 102, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 103, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.yolo_body", "line_number": 106, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 107, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 111, "usage_type": "call"}, {"api_name": "os.path", "line_number": 111, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 112, "usage_type": "call"}, {"api_name": "os.path", "line_number": 112, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 114, "usage_type": "call"}, {"api_name": "os.path", "line_number": 114, "usage_type": "attribute"}, {"api_name": "keras.models.load_model", "line_number": 115, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 116, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 123, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 131, "usage_type": "call"}, {"api_name": "tensorflow.device", "line_number": 134, "usage_type": "call"}, {"api_name": "keras.layers.Lambda", "line_number": 136, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.yolo_loss", "line_number": 137, "usage_type": "argument"}, {"api_name": "keras.models.Model", "line_number": 146, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 175, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 176, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 177, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 178, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.yolo_body", "line_number": 181, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 186, "usage_type": "call"}, {"api_name": "os.path", "line_number": 186, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 187, "usage_type": "call"}, {"api_name": "os.path", "line_number": 187, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 189, "usage_type": "call"}, {"api_name": "os.path", "line_number": 189, "usage_type": "attribute"}, {"api_name": "keras.models.load_model", "line_number": 190, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 191, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 198, "usage_type": "call"}, {"api_name": "keras.models.Model", "line_number": 200, "usage_type": "call"}, {"api_name": "keras.initializers.get", "line_number": 212, "usage_type": "call"}, {"api_name": "keras.initializers", "line_number": 212, "usage_type": "name"}, {"api_name": "tensorflow.device", "line_number": 217, "usage_type": "call"}, {"api_name": "keras.layers.Lambda", "line_number": 219, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.yolo_loss", "line_number": 220, "usage_type": "argument"}, {"api_name": "keras.models.Model", "line_number": 229, "usage_type": "call"}, {"api_name": "retrain_yolo.get_classes", "line_number": 237, "usage_type": "call"}, {"api_name": "retrain_yolo.get_anchors", "line_number": 238, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 239, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 249, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 249, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 257, "usage_type": "call"}, {"api_name": "PIL.Image.TRANSPOSE", "line_number": 261, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 261, "usage_type": "name"}, {"api_name": "retrain_yolo.process_data_pil", "line_number": 268, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.preprocess_true_boxes", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 278, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 281, "usage_type": "call"}, {"api_name": "retrain_yolo.get_classes", "line_number": 285, "usage_type": "call"}, {"api_name": "retrain_yolo.get_anchors", "line_number": 286, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 287, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 297, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 297, "usage_type": "name"}, {"api_name": "numpy.asarray", "line_number": 305, "usage_type": "call"}, {"api_name": "PIL.Image.TRANSPOSE", "line_number": 310, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 310, "usage_type": "name"}, {"api_name": "retrain_yolo.process_data_pil_wide", "line_number": 317, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.preprocess_true_boxes_true_box", "line_number": 326, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.preprocess_true_boxes", "line_number": 329, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 333, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 336, "usage_type": "call"}, {"api_name": "yad2k.models.keras_yolo.yolo_head", "line_number": 373, "usage_type": "call"}, {"api_name": "keras.backend.placeholder", "line_number": 374, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 374, "usage_type": "name"}, {"api_name": "pandas.read_csv", "line_number": 376, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imread", "line_number": 379, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 379, "usage_type": "name"}, {"api_name": "yad2k.models.keras_yolo.yolo_eval", "line_number": 387, "usage_type": "call"}, {"api_name": "yolo_utils.preprocess_image", "line_number": 401, "usage_type": "call"}, {"api_name": "keras.backend.learning_phase", "line_number": 411, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 411, "usage_type": "name"}, {"api_name": "numpy.insert", "line_number": 414, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 422, "usage_type": "call"}, {"api_name": "yolo_utils.preprocess_image", "line_number": 427, "usage_type": "call"}, {"api_name": "yolo_utils.generate_colors", "line_number": 431, "usage_type": "call"}, {"api_name": "yolo_utils.draw_boxes", "line_number": 434, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 434, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 436, "usage_type": "call"}, {"api_name": "os.path", "line_number": 436, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 438, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 438, "usage_type": "name"}, {"api_name": "scipy.misc.imread", "line_number": 439, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 439, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 439, "usage_type": "call"}, {"api_name": "os.path", "line_number": 439, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 440, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 440, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 441, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 441, "usage_type": "name"}, {"api_name": "yolo_utils.generate_colors", "line_number": 447, "usage_type": "call"}, {"api_name": "yolo_utils.draw_boxes", "line_number": 449, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 451, "usage_type": "call"}, {"api_name": "os.path", "line_number": 451, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 453, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 453, "usage_type": "name"}, {"api_name": "scipy.misc.imread", "line_number": 454, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 454, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 454, "usage_type": "call"}, {"api_name": "os.path", "line_number": 454, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 455, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 455, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 456, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 456, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 457, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 457, "usage_type": "name"}, {"api_name": "yad2k.models.keras_yolo.yolo_head", "line_number": 492, "usage_type": "call"}, {"api_name": "keras.backend.placeholder", "line_number": 493, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 493, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imread", "line_number": 498, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 498, "usage_type": "name"}, {"api_name": "yad2k.models.keras_yolo.yolo_eval", "line_number": 505, "usage_type": "call"}, {"api_name": "yolo_utils.preprocess_image", "line_number": 513, "usage_type": "call"}, {"api_name": "keras.backend.learning_phase", "line_number": 520, "usage_type": "call"}, {"api_name": "keras.backend", "line_number": 520, "usage_type": "name"}, {"api_name": "yolo_utils.generate_colors", "line_number": 525, "usage_type": "call"}, {"api_name": "yolo_utils.draw_boxes", "line_number": 527, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 529, "usage_type": "call"}, {"api_name": "os.path", "line_number": 529, "usage_type": "attribute"}, {"api_name": "scipy.misc.imread", "line_number": 531, "usage_type": "call"}, {"api_name": "scipy.misc", "line_number": 531, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 531, "usage_type": "call"}, {"api_name": "os.path", "line_number": 531, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 532, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 532, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 533, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 533, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 548, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 587, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 588, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 589, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 591, "usage_type": "attribute"}, {"api_name": "numpy.array", "line_number": 596, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 598, "usage_type": "call"}, {"api_name": "numpy.floor", "line_number": 599, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 609, "usage_type": "call"}, {"api_name": "numpy.minimum", "line_number": 610, "usage_type": "call"}, {"api_name": "numpy.maximum", "line_number": 611, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 622, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 630, "usage_type": "attribute"}]}
+{"seq_id": "92464240", "text": "import requests\nfrom lxml import html\nfrom urllib.parse import urljoin\n\nclass ImageSender:\n @staticmethod\n def send_image(bot, chat, url, xpath, name, name_xpath=None):\n response = requests.get(url)\n parsed_body = html.fromstring(response.text)\n image = parsed_body.xpath(xpath)\n if name_xpath:\n name = parsed_body.xpath(name_xpath)\n image = urljoin(response.url, image[0])\n bot.sendPhotoUrl(chat, image, name)\n", "sub_path": "tools/imageSender.py", "file_name": "imageSender.py", "file_ext": "py", "file_size_in_byte": 470, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "lxml.html.fromstring", "line_number": 9, "usage_type": "call"}, {"api_name": "lxml.html", "line_number": 9, "usage_type": "name"}, {"api_name": "urllib.parse.urljoin", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "567383722", "text": "# -*- coding: utf-8 -*-\n\nimport sqlite3 as db\nimport codecs\nimport random\nimport re\nimport os\n\ncon = db.connect('chat_bot_t.db')\ncur = con.cursor()\nanswer = \"hello\"\ndef GetAnswer( msg ):\n\tglobal answer\n\tmsg = msg.lower()\n\twordList = list()\n\tfor word in msg.split():\n\t\twordList.append(word)\n\n\tcur.execute(\"SELECT * FROM answers\")\n\tresults = cur.fetchall()\n\tresults = list(results)\n\tnum = -1\n\tnumq = -1\n\tfor z in results:\n\t\tnum += 1\n\t\tz = list(z)\n\t\tindex = 0\n\t\tfor k in wordList:\n\t\t\tif(z[0].find(k) != -1):\n\t\t\t\tindex +=1\n\t\tresults[num] = list(results[num])\n\t\tresults[num].append(index)\n\n\tmaxval = max(map(lambda x: x[2], results))\n\tfor z in results:\n\t\tif(z[2] == maxval):\n\t\t\tif(maxval == 0):\n\t\t\t\tAns = results[random.randint(0, num + 1)][1]\n\t\t\telse:\n\t\t\t\tAns = z[1]\n\t\t\tcur.execute(\"INSERT INTO answers VALUES('\"+answer+\"','\"+msg+\"')\")\n\t\t\tcon.commit()\n\t\t\tanswer = Ans\n\t\t\treturn Ans\n", "sub_path": "hellbox_bot.py", "file_name": "hellbox_bot.py", "file_ext": "py", "file_size_in_byte": 879, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sqlite3.connect", "line_number": 9, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "269512061", "text": "# Copyright 2020 DeepMind Technologies Limited.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Configuration for Prisoner's Dilemma in the Matrix.\n\nExample video: https://youtu.be/bQkEKc1zNuE\n\nSee _Running with Scissors in the Matrix_ for a general description of the\ngame dynamics. Here the payoff matrix represents the Prisoner's Dilemma game.\n`K = 2` resources represent \"cooperate\" and \"defect\" pure strategies.\n\nPlayers have the default `11 x 11` (off center) observation window.\n\"\"\"\n\nimport copy\nfrom typing import Any, Dict, Iterable, Sequence, Tuple\n\nfrom ml_collections import config_dict\nfrom meltingpot.python.utils.substrates import colors\nfrom meltingpot.python.utils.substrates import game_object_utils\nfrom meltingpot.python.utils.substrates import shapes\n\nPrefabConfig = game_object_utils.PrefabConfig\n\n# The number of resources must match the (square) size of the matrix.\nNUM_RESOURCES = 2\n\n# This color is green.\nRESOURCE1_COLOR = (30, 225, 185, 255)\nRESOURCE1_HIGHLIGHT_COLOR = (98, 234, 206, 255)\nRESOURCE1_COLOR_DATA = (RESOURCE1_COLOR, RESOURCE1_HIGHLIGHT_COLOR)\n# This color is red.\nRESOURCE2_COLOR = (225, 30, 70, 255)\nRESOURCE2_HIGHLIGHT_COLOR = (234, 98, 126, 255)\nRESOURCE2_COLOR_DATA = (RESOURCE2_COLOR, RESOURCE2_HIGHLIGHT_COLOR)\n\n# The procedural generator replaces all 'a' chars in the default map with chars\n# representing specific resources, i.e. with either '1' or '2'.\nDEFAULT_ASCII_MAP = \"\"\"\nWWWWWWWWWWWWWWWWWWWWWWWWW\nWPPPP W W PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nW W\nW 11 W\nW 11 W\nW aa W\nW WW W 222 W\nWW 1a W 222 W\nWWW 1a WWWWWWWWW W\nW 1a 111 WWW\nW 111 W\nW aa W W\nW 22 W WW W\nW 22 Waaa W\nW 222 W\nW W\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP PPPPW\nWPPPP W PPPPW\nWWWWWWWWWWWWWWWWWWWWWWWWW\n\"\"\"\n\n_resource_names = [\n \"resource_class1\",\n \"resource_class2\",\n]\n\n# `prefab` determines which prefab game object to use for each `char` in the\n# ascii map.\nCHAR_PREFAB_MAP = {\n \"a\": {\"type\": \"choice\", \"list\": _resource_names},\n \"1\": _resource_names[0],\n \"2\": _resource_names[1],\n \"P\": \"spawn_point\",\n \"W\": \"wall\",\n}\n\n_COMPASS = [\"N\", \"E\", \"S\", \"W\"]\n\nWALL = {\n \"name\": \"wall\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"wall\",\n \"stateConfigs\": [{\n \"state\": \"wall\",\n \"layer\": \"upperPhysical\",\n \"sprite\": \"Wall\",\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [\"Wall\"],\n \"spriteShapes\": [shapes.WALL],\n \"palettes\": [{\"*\": (95, 95, 95, 255),\n \"&\": (100, 100, 100, 255),\n \"@\": (109, 109, 109, 255),\n \"#\": (152, 152, 152, 255)}],\n \"noRotates\": [False]\n }\n },\n {\n \"component\": \"BeamBlocker\",\n \"kwargs\": {\n \"beamType\": \"gameInteraction\"\n }\n },\n ]\n}\n\nSPAWN_POINT = {\n \"name\": \"spawnPoint\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"spawnPoint\",\n \"stateConfigs\": [{\n \"state\": \"spawnPoint\",\n \"layer\": \"alternateLogic\",\n \"groups\": [\"spawnPoints\"]\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n ]\n}\n\n# PLAYER_COLOR_PALETTES is a list with each entry specifying the color to use\n# for the player at the corresponding index.\nNUM_PLAYERS_UPPER_BOUND = 32\nPLAYER_COLOR_PALETTES = []\nfor idx in range(NUM_PLAYERS_UPPER_BOUND):\n PLAYER_COLOR_PALETTES.append(shapes.get_palette(colors.palette[idx]))\n\n# Primitive action components.\n# pylint: disable=bad-whitespace\n# pyformat: disable\nNOOP = {\"move\": 0, \"turn\": 0, \"interact\": 0}\nFORWARD = {\"move\": 1, \"turn\": 0, \"interact\": 0}\nSTEP_RIGHT = {\"move\": 2, \"turn\": 0, \"interact\": 0}\nBACKWARD = {\"move\": 3, \"turn\": 0, \"interact\": 0}\nSTEP_LEFT = {\"move\": 4, \"turn\": 0, \"interact\": 0}\nTURN_LEFT = {\"move\": 0, \"turn\": -1, \"interact\": 0}\nTURN_RIGHT = {\"move\": 0, \"turn\": 1, \"interact\": 0}\nINTERACT = {\"move\": 0, \"turn\": 0, \"interact\": 1}\n# pyformat: enable\n# pylint: enable=bad-whitespace\n\nACTION_SET = (\n NOOP,\n FORWARD,\n BACKWARD,\n STEP_LEFT,\n STEP_RIGHT,\n TURN_LEFT,\n TURN_RIGHT,\n INTERACT,\n)\n\nTARGET_SPRITE_SELF = {\n \"name\": \"Self\",\n \"shape\": shapes.CUTE_AVATAR,\n \"palette\": shapes.get_palette((50, 100, 200)),\n \"noRotate\": True,\n}\n\n\ndef create_scene():\n \"\"\"Creates the global scene.\"\"\"\n scene = {\n \"name\": \"scene\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": \"scene\",\n \"stateConfigs\": [{\n \"state\": \"scene\",\n }],\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n },\n },\n {\n \"component\": \"TheMatrix\",\n \"kwargs\": {\n \"zero_initial_inventory\": True,\n \"matrix\": [\n # row player chooses a row of this matrix.\n # C D\n [3, 0], # C\n [4, 1], # D\n ],\n \"columnPlayerMatrix\": [\n # column player chooses a column of this matrix.\n # C D\n [3, 4], # C\n [0, 1], # D\n ],\n }\n },\n ]\n }\n return scene\n\n\ndef create_resource_prefab(resource_id, color_data):\n \"\"\"Creates resource prefab with provided `resource_id` (num) and color.\"\"\"\n resource_name = \"resource_class{}\".format(resource_id)\n resource_prefab = {\n \"name\": resource_name,\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": resource_name,\n \"stateConfigs\": [\n {\"state\": resource_name + \"_wait\",\n \"groups\": [\"resourceWaits\"]},\n {\"state\": resource_name,\n \"layer\": \"lowerPhysical\",\n \"sprite\": resource_name + \"_sprite\"},\n ]\n },\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n },\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [resource_name + \"_sprite\"],\n \"spriteShapes\": [shapes.BUTTON],\n \"palettes\": [{\"*\": color_data[0],\n \"#\": color_data[1],\n \"x\": (0, 0, 0, 0)}],\n \"noRotates\": [False]\n },\n },\n {\n \"component\": \"Resource\",\n \"kwargs\": {\n \"resourceClass\": resource_id,\n \"visibleType\": resource_name,\n \"waitState\": resource_name + \"_wait\",\n \"groupToRespawn\": \"resourceWaits\",\n \"regenerationRate\": 0.005,\n \"regenerationDelay\": 50\n },\n },\n {\n \"component\": \"Destroyable\",\n \"kwargs\": {\n \"visibleType\": resource_name,\n \"waitState\": resource_name + \"_wait\",\n \"initialHealth\": 1,\n },\n },\n ]\n }\n return resource_prefab\n\n\ndef create_prefabs() -> PrefabConfig:\n \"\"\"Returns the prefabs.\n\n Prefabs are a dictionary mapping names to template game objects that can\n be cloned and placed in multiple locations accoring to an ascii map.\n \"\"\"\n prefabs = {\n \"wall\": WALL,\n \"spawn_point\": SPAWN_POINT,\n }\n prefabs[\"resource_class1\"] = create_resource_prefab(1, RESOURCE1_COLOR_DATA)\n prefabs[\"resource_class2\"] = create_resource_prefab(2, RESOURCE2_COLOR_DATA)\n return prefabs\n\n\ndef create_avatar_object(player_idx: int,\n target_sprite_self: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Create an avatar object that always sees itself as blue.\"\"\"\n # Lua is 1-indexed.\n lua_index = player_idx + 1\n\n # Setup the self vs other sprite mapping.\n source_sprite_self = \"Avatar\" + str(lua_index)\n custom_sprite_map = {source_sprite_self: target_sprite_self[\"name\"]}\n\n live_state_name = \"player{}\".format(lua_index)\n avatar_object = {\n \"name\": \"avatar\",\n \"components\": [\n {\n \"component\": \"StateManager\",\n \"kwargs\": {\n \"initialState\": live_state_name,\n \"stateConfigs\": [\n {\"state\": live_state_name,\n \"layer\": \"upperPhysical\",\n \"sprite\": source_sprite_self,\n \"contact\": \"avatar\",\n \"groups\": [\"players\"]},\n\n {\"state\": \"playerWait\",\n \"groups\": [\"playerWaits\"]},\n ]\n }\n },\n {\n \"component\": \"Transform\",\n \"kwargs\": {\n \"position\": (0, 0),\n \"orientation\": \"N\"\n }\n },\n {\n \"component\": \"Appearance\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"spriteNames\": [source_sprite_self],\n \"spriteShapes\": [shapes.CUTE_AVATAR],\n \"palettes\": [shapes.get_palette(colors.palette[player_idx])],\n \"noRotates\": [True]\n }\n },\n {\n \"component\": \"AdditionalSprites\",\n \"kwargs\": {\n \"renderMode\": \"ascii_shape\",\n \"customSpriteNames\": [target_sprite_self[\"name\"]],\n \"customSpriteShapes\": [target_sprite_self[\"shape\"]],\n \"customPalettes\": [target_sprite_self[\"palette\"]],\n \"customNoRotates\": [target_sprite_self[\"noRotate\"]],\n }\n },\n {\n \"component\": \"Avatar\",\n \"kwargs\": {\n \"index\": lua_index,\n \"aliveState\": live_state_name,\n \"waitState\": \"playerWait\",\n \"speed\": 1.0,\n \"spawnGroup\": \"spawnPoints\",\n \"actionOrder\": [\"move\", \"turn\", \"interact\"],\n \"actionSpec\": {\n \"move\": {\"default\": 0, \"min\": 0, \"max\": len(_COMPASS)},\n \"turn\": {\"default\": 0, \"min\": -1, \"max\": 1},\n \"interact\": {\"default\": 0, \"min\": 0, \"max\": 1},\n },\n \"view\": {\n \"left\": 5,\n \"right\": 5,\n \"forward\": 9,\n \"backward\": 1,\n \"centered\": False\n },\n \"spriteMap\": custom_sprite_map,\n # The following kwarg makes it possible to get rewarded even\n # on frames when an avatar is \"dead\". It is needed for in the\n # matrix games in order to correctly handle the case of two\n # players getting hit simultaneously by the same beam.\n \"skipWaitStateRewards\": False,\n }\n },\n {\n \"component\": \"GameInteractionZapper\",\n \"kwargs\": {\n \"cooldownTime\": 32,\n \"beamLength\": 3,\n \"beamRadius\": 1,\n \"framesTillRespawn\": 200,\n \"numResources\": NUM_RESOURCES,\n \"reset_winner_inventory\": False,\n \"reset_loser_inventory\": True,\n \"losingPlayerDies\": True,\n }\n },\n {\n \"component\": \"ReadyToShootObservation\",\n \"kwargs\": {\n \"zapperComponent\": \"GameInteractionZapper\",\n }\n },\n {\n \"component\": \"InventoryObserver\",\n \"kwargs\": {\n }\n },\n {\n \"component\": \"Taste\",\n \"kwargs\": {\n \"mostTastyResourceClass\": -1, # -1 indicates no preference.\n }\n },\n {\n \"component\": \"InteractionTaste\",\n \"kwargs\": {\n \"mostTastyResourceClass\": -1, # -1 indicates no preference.\n \"zeroDefaultInteractionReward\": True,\n \"extraReward\": 1.0,\n }\n },\n {\n \"component\": \"LocationObserver\",\n \"kwargs\": {\n \"objectIsAvatar\": True,\n \"alsoReportOrientation\": True\n }\n },\n {\n \"component\": \"AvatarMetricReporter\",\n \"kwargs\": {\n \"metrics\": [\n {\n # Report the inventories of both players involved in\n # an interaction on this frame formatted as\n # (self inventory, partner inventory).\n \"name\": \"INTERACTION_INVENTORIES\",\n \"type\": \"tensor.DoubleTensor\",\n \"shape\": (2, NUM_RESOURCES),\n \"component\": \"GameInteractionZapper\",\n \"variable\": \"latest_interaction_inventories\",\n },\n ]\n }\n },\n ]\n }\n\n return avatar_object\n\n\ndef create_avatar_objects(num_players: int) -> Sequence[PrefabConfig]:\n \"\"\"Returns all game objects for the map.\n\n Args:\n num_players: number of players to create avatars for.\n \"\"\"\n avatar_objects = []\n for player_idx in range(num_players):\n avatar = create_avatar_object(player_idx, TARGET_SPRITE_SELF)\n avatar_objects.append(avatar)\n return avatar_objects\n\n\ndef create_lab2d_settings(\n num_players: int,\n ascii_map_string: str,\n settings_overrides: Iterable[Tuple[str, Any]] = ()) -> Dict[str, Any]:\n \"\"\"Returns the lab2d settings.\n\n Args:\n num_players: (int) the number of players.\n ascii_map_string: ascii map.\n settings_overrides: (key, value) overrides for default settings.\n \"\"\"\n settings = {\n \"levelName\": \"the_matrix\",\n \"levelDirectory\": \"meltingpot/lua/levels\",\n \"numPlayers\": num_players,\n \"episodeLengthFrames\": 1000,\n \"spriteSize\": 8,\n \"simulation\": {\n \"map\": ascii_map_string,\n \"gameObjects\": create_avatar_objects(num_players=num_players),\n \"scene\": copy.deepcopy(create_scene()),\n \"prefabs\": create_prefabs(),\n \"charPrefabMap\": CHAR_PREFAB_MAP,\n }\n }\n settings.update(settings_overrides)\n return settings\n\n\ndef get_config(factory=create_lab2d_settings):\n \"\"\"Default config for prisoners dilemma in the matrix.\"\"\"\n config = config_dict.ConfigDict()\n\n # Basic configuration.\n config.num_players = 8\n config.lab2d_settings = factory(config.num_players, DEFAULT_ASCII_MAP)\n\n # Action set configuration.\n config.action_set = ACTION_SET\n # Observation format configuration.\n config.individual_observation_names = [\n \"RGB\",\n \"INVENTORY\",\n \"READY_TO_SHOOT\",\n \"POSITION\",\n \"ORIENTATION\",\n \"INTERACTION_INVENTORIES\",\n ]\n config.global_observation_names = [\n \"WORLD.RGB\",\n ]\n\n return config\n", "sub_path": "meltingpot/python/configs/substrates/prisoners_dilemma_in_the_matrix.py", "file_name": "prisoners_dilemma_in_the_matrix.py", "file_ext": "py", "file_size_in_byte": 16992, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "meltingpot.python.utils.substrates.game_object_utils.PrefabConfig", "line_number": 33, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.game_object_utils", "line_number": 33, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.WALL", "line_number": 119, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 119, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.get_palette", "line_number": 165, "usage_type": "call"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 165, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.colors.palette", "line_number": 165, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.colors", "line_number": 165, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.CUTE_AVATAR", "line_number": 194, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 194, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.get_palette", "line_number": 195, "usage_type": "call"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 195, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.BUTTON", "line_number": 275, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 275, "usage_type": "name"}, {"api_name": "typing.Dict", "line_number": 322, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 322, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.CUTE_AVATAR", "line_number": 363, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 363, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.shapes.get_palette", "line_number": 364, "usage_type": "call"}, {"api_name": "meltingpot.python.utils.substrates.shapes", "line_number": 364, "usage_type": "name"}, {"api_name": "meltingpot.python.utils.substrates.colors.palette", "line_number": 364, "usage_type": "attribute"}, {"api_name": "meltingpot.python.utils.substrates.colors", "line_number": 364, "usage_type": "name"}, {"api_name": "typing.Sequence", "line_number": 475, "usage_type": "name"}, {"api_name": "typing.Iterable", "line_number": 491, "usage_type": "name"}, {"api_name": "typing.Tuple", "line_number": 491, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 491, "usage_type": "name"}, {"api_name": "copy.deepcopy", "line_number": 508, "usage_type": "call"}, {"api_name": "typing.Dict", "line_number": 491, "usage_type": "name"}, {"api_name": "ml_collections.config_dict.ConfigDict", "line_number": 519, "usage_type": "call"}, {"api_name": "ml_collections.config_dict", "line_number": 519, "usage_type": "name"}]}
+{"seq_id": "244921922", "text": "import os\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport collections\nimport itertools as it\nimport random\nimport pdb\n\nclass DeepQNetwork(object):\n\n def __init__(self, lr, n_actions, name, fc1_dims=512, LSTM_DIM=256,\n input_dims=(210, 160, 4), chkpt_dir=\"tmp/dqn\"):\n self.lr = lr\n self.name = name\n config = tf.ConfigProto()\n config.gpu_options.visible_device_list = \"2,3\"\n #config.gpu_options.allow_growth = True\n #config.gpu_options.per_process_gpu_memory_fraction = 0.5\n self.LSTM_DIM = LSTM_DIM\n self.n_actions = n_actions\n self.fc1_dims = fc1_dims\n self.chkpt_dir = chkpt_dir\n self.input_dims = input_dims\n self.sess = tf.Session(config=config)\n self.build_network()\n self.sess.run(tf.global_variables_initializer())\n self.checkpoint_file = os.path.join(chkpt_dir, \"deepqnet.ckpt\")\n self.saver = tf.train.Saver(max_to_keep=100)\n self.params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,\n scope=self.name)\n self.write_op = tf.summary.merge_all()\n #dirname = os.path.dirname(__file__)\n #self.log = os.path.join(*[dirname, 'tmp', 'log_dir', self.name])\n #if os.path.isdir(self.log):\n # print(\"output_results: \", str(self.log))\n #else:\n #os.mkdir(self.log)\n self.make_log_dir()\n self.writer = tf.summary.FileWriter(self.log, self.sess.graph)\n\n def make_log_dir(self):\n path = '/home/azlaans/aienvs'\n self.log = os.path.join(*[path, 'test', 'tmp', 'log_dir', 'single', self.name])\n if os.path.isdir(self.log):\n print('Log_Dir exists for tensorboard summary')\n else:\n os.mkdir(self.log)\n print('Lod_Dir created for tensorboard summary', self.log)\n \n\n def build_network(self):\n\n with tf.variable_scope(self.name):\n self.states = tf.placeholder(tf.float32, shape=[None, *self.input_dims],\n name='states') \n self.actions = tf.placeholder(tf.float32, shape=[None, self.n_actions],\n name='action_taken')\n self.q_target = tf.placeholder(tf.float32, shape=[None],\n name='q_value')\n self.seq_len = tf.placeholder(tf.int32, name='sequence_length')\n self.batch_size = tf.placeholder(tf.int32, name='batch_size')\n\n # Create placeholders to input the hidden state values\n c_in = tf.placeholder(tf.float32, [None, self.LSTM_DIM], name='cell_state')\n h_in = tf.placeholder(tf.float32, [None, self.LSTM_DIM], name='h_state')\n self.state_in = tf.nn.rnn_cell.LSTMStateTuple(c_in, h_in)\n\n #self._reward = tf.placeholder(tf.float32, shape=[], name='Reward/Time_step')\n #self.reward_sum = tf.summary.scalar('Reward/Time_step', self._reward)\n\n #self._waitingtime = tf.placeholder(tf.float32, shape=[], name='TotalWaitingTime/Time_step')\n #self.waitingtime_sum = tf.summary.scalar('TotalWaitingTime/Time_step', self._waitingtime)\n\n #self._delay = tf.placeholder(tf.float32, shape=[], name='TotalDelay/Time_step')\n #self.delay_sum = tf.summary.scalar('TotalDelay/Time_step', self._delay)\n\n conv1 = tf.layers.conv2d(inputs=self.states, filters=16,\n kernel_size=(8, 8), strides=(4,4), name='conv1', padding='VALID',\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2),use_bias=True, bias_initializer=tf.constant_initializer(0.1))\n # TensorShape([Dimension(None), Dimension(44), Dimension(39), Dimension(32)])\n\n conv1_activated = tf.nn.relu(conv1)\n\n conv2 = tf.layers.conv2d(inputs=conv1_activated, filters=32,\n kernel_size=(4, 4), strides=(2,2), name='conv2', padding='VALID',\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2), use_bias=True, bias_initializer=tf.constant_initializer(0.1))\n # TensorShape([Dimension(None), Dimension(21), Dimension(18), Dimension(64)])\n\n conv2_activated = tf.nn.relu(conv2)\n\n #conv3 = tf.layers.conv2d(inputs=conv2_activated, filters=64,\n # kernel_size=(3, 3), strides=1, name='conv3',\n #kernel_initializer=tf.contrib.layers.variance_scaling_initializer(factor=2))\n #conv3_activated = tf.nn.relu(conv3)\n\n n_input = conv2_activated.get_shape().as_list()[1]*conv2_activated.get_shape().as_list()[2]*conv2_activated.get_shape().as_list()[3]\n \n conv2_activated = tf.reshape(conv2_activated, [-1, n_input])\n \n conv2_activated = tf.reshape(conv2_activated, [self.batch_size, self.seq_len, n_input])\n \n lstm_cell = tf.nn.rnn_cell.LSTMCell(self.LSTM_DIM, initializer=tf.contrib.layers.xavier_initializer())\n outputs, self.cell_state = tf.nn.dynamic_rnn(lstm_cell, conv2_activated, initial_state=self.state_in, dtype=tf.float32, sequence_length=self.seq_len)\n\n var1 = tf.get_variable('weights', (self.LSTM_DIM, self.n_actions), initializer=tf.contrib.layers.xavier_initializer(), trainable=True, \n regularizer=tf.contrib.layers.l2_regularizer(0.01))\n var2 = tf.get_variable('biases', (self.n_actions,), trainable=True, initializer=tf.constant_initializer(0.1))\n\n h = outputs[:,-1,:] \n\n self.Q_values = tf.matmul(h, var1) + var2\n tf.summary.histogram('Q_value', self.Q_values)\n\n self.q = tf.reduce_sum(tf.multiply(self.Q_values, self.actions), axis=1)\n\n self.loss = tf.reduce_mean(tf.square(self.q_target - self.q))\n \n self.loss_sum = tf.summary.scalar(\"Loss\", self.loss)\n\n self.train_op = tf.train.AdamOptimizer(self.lr).minimize(self.loss)\n\n if self.name == 'q_eval':\n for var in tf.trainable_variables():\n c = var.name[:-2]\n with tf.name_scope(c):\n self.variable_summaries(var)\n\n def variable_summaries(self, var):\n \"\"\"Attach a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.histogram('histogram', var)\n\n def load_checkpoint(self, filename):\n print('... loading checkpoint ...')\n self.saver.restore(self.sess, filename)\n\n def save_checkpoint(self, epi_num):\n print('... Saving Checkpoint ...')\n #self.epi_num = epi_num\n #dir_name = os.path.join(self.chkpt_dir, str(self.epi_num))\n #if os.path.isdir(dir_name):\n # print(\"directory exists \", str(dirname))\n #else:\n # os.mkdir(dir_name)\n #filename = \"deepQnet_\" + str(epi_num)\n self.saver.save(self.sess, self.checkpoint_file, global_step=epi_num)\n\nclass Agent(object):\n def __init__(self, alpha, gamma, mem_size, epsilon, batch_size, num_agents, act_per_agent,\n replace_target=3000, input_dims=(210, 160, 4), q_next_dir=\"tmp/q_next\", q_eval_dir=\"tmp/q_eval\", test= False):\n self.num_agents = num_agents\n self.act_per_agent = act_per_agent\n self.input_dims = input_dims\n self.n_actions = self.act_per_agent**(self.num_agents)\n self.action_space = [i for i in range(self.act_per_agent)]\n self.gamma = gamma\n self.seq_length = 10\n self.LSTM_DIM = 256\n self.mem_size = mem_size\n self.mem_cntr = 0\n self.epsilon = epsilon\n self.batch_size = batch_size\n self.replace_target = replace_target \n \n self.q_eval = DeepQNetwork(alpha, self.n_actions, input_dims=input_dims,\n name='q_eval', chkpt_dir=q_eval_dir)\n\n #self.q_next = DeepQNetwork(alpha, self.n_actions, input_dims=input_dims,\n #name='q_next', chkpt_dir=q_next_dir)\n\n if test==False:\n self.create_memory()\n else:\n self.test_initialiser()\n \n self.all_list = []\n for j in it.product(tuple(self.action_space), repeat = self.num_agents):\n self.all_list.append(j) \n\n def create_memory(self):\n self.state_memory = np.zeros((self.mem_size, *self.input_dims)) \n self.new_state_memory = np.zeros((self.mem_size, *self.input_dims))\n self.action_memory = np.zeros((self.mem_size, self.n_actions),\n dtype=np.int8)\n self.reward_memory = np.zeros(self.mem_size)\n self.terminal_memory = np.zeros(self.mem_size, dtype=np.int8)\n c_init = np.zeros((1, self.LSTM_DIM), np.float32)\n h_init = np.zeros((1, self.LSTM_DIM), np.float32)\n self.state_out = (c_init, h_init)\n\n def action_hot_encoder(self, actions, all_list):\n action = np.zeros((self.n_actions))\n value_list = tuple(actions.values())\n for key, val in enumerate(all_list):\n if val == value_list:\n action[key] = 1.\n break\n return action\n\n def action_decoder(self, encoded_action, all_list):\n index = (list(np.where(encoded_action==1.))[0])[0]\n decoded_action = collections.OrderedDict()\n for i in range(len(encoded_action)):\n try:\n decoded_action[str(i)] = all_list[index][i]\n except:\n break\n return decoded_action\n\n def store_transition(self, state, action, reward, state_, terminal):\n index = self.mem_cntr % self.mem_size\n self.state_memory[index] = state\n self.reward = reward\n self.action_memory[index] = self.action_hot_encoder(action, self.all_list)\n self.reward_memory[index] = reward['result']\n self.new_state_memory[index] = state_\n self.terminal_memory[index] = terminal\n if self.mem_cntr >= self.mem_size:\n self.epsilon = 0.01\n \n def upgrade(self):\n self.mem_cntr +=1\n \n def choose_action(self, state):\n rand = np.random.random()\n if rand < self.epsilon:\n value_list = []\n for i in range(self.num_agents):\n value_list.append(np.random.choice(self.action_space))\n value_list = tuple(value_list)\n action = np.zeros((self.n_actions))\n for key, val in enumerate(self.all_list):\n if val == value_list:\n action[key] = 1.\n break\n action = self.action_decoder(action, self.all_list)\n else:\n actions, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n action = np.argmax(actions)\n action_ht = np.zeros((self.n_actions))\n action_ht[action] = 1. \n action = self.action_decoder(action_ht, self.all_list)\n return action\n\n def RandomSequenceSampling(self):\n batch_length = self.batch_size*self.seq_length\n state_batch = np.zeros((batch_length, *self.input_dims))\n next_state_batch = np.zeros((batch_length, *self.input_dims))\n reward_batch = []\n action_batch = []\n terminal_batch = []\n indices = np.arange(self.seq_length-1, self.mem_size)\n for b in np.arange(0, batch_length, self.seq_length):\n i = random.choice(indices)\n while (sum(self.terminal_memory[i+1-self.seq_length:i+1]) > 0 and self.terminal_memory[i] != 1):\n i = random.choice(indices)\n state_batch[b:b+self.seq_length] = self.get_sequence(i, self.state_memory)\n action_batch.append(self.action_memory[i])\n reward_batch.append(self.reward_memory[i])\n next_state_batch[b:b+self.seq_length] = self.get_sequence(i, self.new_state_memory)\n terminal_batch.append(self.terminal_memory[i])\n return state_batch, np.asarray(action_batch), np.asarray(reward_batch), next_state_batch, np.asarray(terminal_batch)\n\n def get_sequence(self, index, collection):\n stop = index + 1 \n start = stop - self.seq_length \n if start < 0 and stop >= 0:\n try:\n seq = np.vstack((collection[start:], collection[:stop]))\n except ValueError:\n seq = np.append(collection[start:], collection[:stop])\n else:\n seq = collection[start:stop]\n\n if len(seq.shape) != len(collection.shape):\n seq = np.reshape(seq, (-1,))\n return seq\n\n def learn(self):\n if self.mem_cntr % self.replace_target == 0:\n self.update_graph()\n\n state_batch, action_batch, reward_batch, next_state_batch, terminal_batch = self.RandomSequenceSampling() \n\n state = (np.zeros((self.batch_size, self.LSTM_DIM)),np.zeros((self.batch_size, self.LSTM_DIM)))\n\n q_eval = self.q_eval.sess.run(self.q_eval.Q_values,\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.state_in: state,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size})\n\n q_eval_next = self.q_eval.sess.run(self.q_eval.Q_values,\n feed_dict={self.q_eval.states: next_state_batch,\n self.q_eval.state_in: state,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size})\n\n index_best_action = np.argmax(q_eval_next, axis=1)\n\n q_next = self.q_next.sess.run(self.q_next.Q_values,\n feed_dict={self.q_next.states: next_state_batch,\n self.q_next.state_in: state,\n self.q_next.seq_len: self.seq_length,\n self.q_next.batch_size: self.batch_size})\n\n idx = np.arange(self.batch_size)\n q_target = reward_batch + \\\n self.gamma*(q_next[idx, index_best_action])*(1 - terminal_batch)\n \n _ = self.q_eval.sess.run(self.q_eval.train_op,\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.actions: action_batch,\n self.q_eval.q_target: q_target,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size,\n self.q_eval.state_in: state,\n self.q_eval._reward: self.reward['result'],\n self.q_eval._waitingtime: self.reward['total_waiting'],\n self.q_eval._delay: self.reward['total_delay']})\n\n if self.mem_cntr % 400==0:\n summary1, _ = self.q_eval.sess.run([self.q_eval.write_op, self.q_eval.train_op],\n feed_dict={self.q_eval.states: state_batch,\n self.q_eval.actions: action_batch,\n self.q_eval.q_target: q_target,\n self.q_eval.seq_len: self.seq_length,\n self.q_eval.batch_size: self.batch_size,\n self.q_eval.state_in: state,\n self.q_eval._reward: self.reward['result'],\n self.q_eval._waitingtime: self.reward['total_waiting'],\n self.q_eval._delay: self.reward['total_delay']})\n self.q_eval.writer.add_summary(summary1)\n self.q_eval.writer.flush()\n\n def test(self, state):\n actions, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n action = np.argmax(actions)\n action_ht = np.zeros((self.n_actions))\n action_ht[action] = 1.\t\n return self.action_decoder(action_ht, self.all_list) \n\n def get_qval(self, state):\n q_values, lstm_state = self.q_eval.sess.run([self.q_eval.Q_values, self.q_eval.cell_state],\n feed_dict={self.q_eval.states: state,\n self.q_eval.state_in: self.state_out,\n self.q_eval.seq_len: 1,\n self.q_eval.batch_size: 1})\n lstm_c, lstm_h = lstm_state\n self.state_out = (lstm_c[:1, :], lstm_h[:1, :])\n return q_values\n \n def test_initialiser(self):\n c_init = np.zeros((1, self.LSTM_DIM), np.float32)\n h_init = np.zeros((1, self.LSTM_DIM), np.float32)\n self.state_out = (c_init, h_init)\n\n def reset(self):\n self.state_out = (np.zeros(self.state_out[0].shape),np.zeros(self.state_out[1].shape))\n \n def save_models(self, episode_number):\n self.episode_number = episode_number\n self.q_eval.save_checkpoint(epi_num = self.episode_number)\n self.q_next.save_checkpoint(epi_num = self.episode_number)\n\n def load_models(self, filename):\n self.q_eval.load_checkpoint(filename)\n #self.q_next.load_checkpoint()\n\n def update_graph(self):\n t_params = self.q_next.params\n e_params = self.q_eval.params\n\n for t, e in zip(t_params, e_params):\n self.q_eval.sess.run(tf.assign(t, e))\n", "sub_path": "implementation/imp_DQRN.py", "file_name": "imp_DQRN.py", "file_ext": "py", "file_size_in_byte": 18997, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "tensorflow.ConfigProto", "line_number": 16, "usage_type": "call"}, {"api_name": "tensorflow.Session", "line_number": 25, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 27, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 28, "usage_type": "call"}, {"api_name": "os.path", "line_number": 28, "usage_type": "attribute"}, {"api_name": "tensorflow.train.Saver", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tensorflow.get_collection", "line_number": 30, "usage_type": "call"}, {"api_name": "tensorflow.GraphKeys", "line_number": 30, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.merge_all", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 32, "usage_type": "attribute"}, {"api_name": "tensorflow.summary.FileWriter", "line_number": 40, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 40, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 48, "usage_type": "call"}, {"api_name": "tensorflow.variable_scope", "line_number": 54, "usage_type": "call"}, {"api_name": "tensorflow.placeholder", "line_number": 55, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 55, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 57, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 57, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 59, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 59, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 61, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 61, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 62, "usage_type": "call"}, {"api_name": "tensorflow.int32", "line_number": 62, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 65, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 65, "usage_type": "attribute"}, {"api_name": "tensorflow.placeholder", "line_number": 66, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 66, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.rnn_cell.LSTMStateTuple", "line_number": 67, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 67, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.conv2d", "line_number": 78, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 78, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.layers.variance_scaling_initializer", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 80, "usage_type": "attribute"}, {"api_name": "tensorflow.constant_initializer", "line_number": 80, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 83, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 83, "usage_type": "attribute"}, {"api_name": "tensorflow.layers.conv2d", "line_number": 85, "usage_type": "call"}, {"api_name": "tensorflow.layers", "line_number": 85, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.layers.variance_scaling_initializer", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 87, "usage_type": "attribute"}, {"api_name": "tensorflow.constant_initializer", "line_number": 87, "usage_type": "call"}, {"api_name": "tensorflow.nn.relu", "line_number": 90, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 90, "usage_type": "attribute"}, {"api_name": "tensorflow.reshape", "line_number": 99, "usage_type": "call"}, {"api_name": "tensorflow.reshape", "line_number": 101, "usage_type": "call"}, {"api_name": "tensorflow.nn.rnn_cell.LSTMCell", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.layers.xavier_initializer", "line_number": 103, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 103, "usage_type": "attribute"}, {"api_name": "tensorflow.nn.dynamic_rnn", "line_number": 104, "usage_type": "call"}, {"api_name": "tensorflow.nn", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.float32", "line_number": 104, "usage_type": "attribute"}, {"api_name": "tensorflow.get_variable", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.contrib.layers.xavier_initializer", "line_number": 106, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 106, "usage_type": "attribute"}, {"api_name": "tensorflow.contrib.layers.l2_regularizer", "line_number": 107, "usage_type": "call"}, {"api_name": "tensorflow.contrib", "line_number": 107, "usage_type": "attribute"}, {"api_name": "tensorflow.get_variable", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.constant_initializer", "line_number": 108, "usage_type": "call"}, {"api_name": "tensorflow.matmul", "line_number": 112, "usage_type": "call"}, {"api_name": "tensorflow.summary.histogram", "line_number": 113, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 113, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_sum", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.multiply", "line_number": 115, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 117, "usage_type": "call"}, {"api_name": "tensorflow.summary.scalar", "line_number": 119, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 119, "usage_type": "attribute"}, {"api_name": "tensorflow.train.AdamOptimizer", "line_number": 121, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 121, "usage_type": "attribute"}, {"api_name": "tensorflow.trainable_variables", "line_number": 124, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 126, "usage_type": "call"}, {"api_name": "tensorflow.name_scope", "line_number": 131, "usage_type": "call"}, {"api_name": "tensorflow.reduce_mean", "line_number": 132, "usage_type": "call"}, {"api_name": "tensorflow.summary.histogram", "line_number": 133, "usage_type": "call"}, {"api_name": "tensorflow.summary", "line_number": 133, "usage_type": "attribute"}, {"api_name": "itertools.product", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 183, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 184, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 185, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 186, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 187, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 188, "usage_type": "call"}, {"api_name": "numpy.int8", "line_number": 188, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 189, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 189, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 190, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 190, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 194, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 203, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 204, "usage_type": "call"}, {"api_name": "numpy.random.random", "line_number": 227, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 227, "usage_type": "attribute"}, {"api_name": "numpy.random.choice", "line_number": 231, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 231, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 233, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 247, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 248, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 255, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 256, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 261, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 262, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 264, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 277, "usage_type": "call"}, {"api_name": "numpy.append", "line_number": 279, "usage_type": "call"}, {"api_name": "numpy.reshape", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 293, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 307, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 315, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 352, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 353, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 368, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 368, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 369, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 369, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 373, "usage_type": "call"}, {"api_name": "tensorflow.assign", "line_number": 389, "usage_type": "call"}]}
+{"seq_id": "132716567", "text": "from django.contrib import admin\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n\n path('watchmoon', views.watchmoon, name=\"watchmoon\"),\n path('watchsunset', views.watchsunset, name=\"watchsunset\"),\n path('watchgallery', views.watchgallery, name=\"watchgallery\"),\n path('playbedroom', views.playbedroom, name=\"playbedroom\"),\n path('readletters', views.readletters, name=\"readletters\"),\n path('playmusic', views.playmusic, name=\"playmusic\"),\n path('timeline', views.timeline, name=\"timeline\"),\n\n]\n", "sub_path": "activity/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 532, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 11, "usage_type": "call"}, {"api_name": "django.urls.path", "line_number": 12, "usage_type": "call"}]}
+{"seq_id": "102751821", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport doc2vec\nfrom gensim import models\n\nmodel = models.Doc2Vec.load('doc2vec.model')\n\n# 似た文章を探す\n# id : メールアドレス\ndef search_similar_texts(id, num): \n most_similar_texts = model.docvecs.most_similar(id)\n similar_list = []\n i = 0\n for similar_text in most_similar_texts:\n similar_list.append(most_similar_texts[i])\n i += 1\n if((i+1)>num):\n break\n return similar_list\n \nif __name__ == '__main__':\n print('文字列入力:')\n search_str = input()\n search_similar_texts(search_str)\n", "sub_path": "takenaka/bot/doc2vec_search.py", "file_name": "doc2vec_search.py", "file_ext": "py", "file_size_in_byte": 612, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "gensim.models.Doc2Vec.load", "line_number": 7, "usage_type": "call"}, {"api_name": "gensim.models.Doc2Vec", "line_number": 7, "usage_type": "attribute"}, {"api_name": "gensim.models", "line_number": 7, "usage_type": "name"}]}
+{"seq_id": "380338001", "text": "#C:\\Users\\saurabhj\\OneDrive\\Documents\\Python Scripts\\RL\n#https://github.com/saurabhjadhav1911/RL.git\nfrom colorama import Fore, Back, Style\nimport colorama\ncolorama.init()\nfrom misc import *\nimport serial\nimport multiprocessing\nimport time\nimport traceback\n\nvalue = 0\nlav = 0\nnf = 0\ncolor = Fore.GREEN\n\n\nclass Env():\n \"\"\"docstring for Env\"\"\"\n\n def __init__(self, config):\n print(color + 'Env created')\n self.config = config\n self.ser = self.get_Serial()\n self.default_action = config['Env_config']['default_action']\n self.data = \"\"\n\n def get_Serial(self):\n return serial.Serial(\n self.config['Serial_config']['port'],\n baudrate=self.config['Serial_config']['baud'],\n timeout=self.config['Serial_config']['timeout'])\n\n def reset(self):\n self.action(self.default_action)\n return self.read_state()\n\n def action(self, act):\n line = \"G \" + \" \".join(map(str, act))\n print(color, line)\n #self.serial.write(line)\n\n def run(self, q, r, agent_obs_que, agent_reward_que, agent_action_que):\n #ser=serial.Serial(config['Serial_config']['port'],baudrate=config['Serial_config']['baud'],timeout=config['Serial_config']['timeout'])\n print(color, \"Serial communicatoion started\")\n while True:\n self.read_write_state(q, r)\n\n def read_write_state(self, q, r):\n global value, lav\n flag = False\n while r.empty() is False:\n flag = True\n arr = \" \".join(map(str, r.get()))\n arr += \"|\"\n #unicode(s, \"utf-8\")\n if (self.config['Env_config']['show_obs']):\n\n print(color, self.config['Env_config']['show_obs'], arr)\n self.ser.write(arr.encode())\n\n if (self.ser.inWaiting() > 0):\n c, timestamp = self.ser.read(), time.time()\n #print(color,c)\n try:\n c = str(c, 'utf-8')\n if c is '|':\n\n #dta=data\n #nf+=1\n lav = value\n\n if self.config['Env_config']['Env_vector_size'] > 1:\n value = list(map(int, self.data.split()))\n else:\n value = int(self.data)\n #if lav is not value:\n value.append(timestamp)\n if (self.config['Env_config']['show_obs']):\n print(color, self.config['Env_config']['show_obs'],\n self.data)\n q.put(value)\n #v=q.get()\n self.data = \"\"\n else:\n self.data += c\n except Exception as e:\n exc_traceback = traceback.format_exc()\n print(color, exc_traceback)\n #pass\n def test_run(self, q, r):\n #ser=serial.Serial(config['Serial_config']['port'],baudrate=config['Serial_config']['baud'],timeout=config['Serial_config']['timeout'])\n while True:\n self.read_write_state(q, r)\n\n\n############################ testing Env ############################\n\n\ndef Env_process_target(recieve_que, send_que, config):\n print(color, 'Env process start')\n env = Env(config)\n env.run(recieve_que, send_que)\n\n\ndef Test_process_target(recieve_que, send_que, config):\n\n print(color, 'Test process start')\n generate_step(recieve_que, send_que, config)\n\n\ndef main():\n multiprocessing.freeze_support()\n\n config = read_config('config_crawler.json')\n config = arg_parser(config)\n save_config(config, 'config_crawler.json')\n #initialise communicatoions between processes\n send_que = multiprocessing.Queue()\n recieve_que = multiprocessing.Queue()\n\n #process initialisation\n\n env_process = multiprocessing.Process(\n target=Env_process_target, args=(recieve_que, send_que, config))\n test_process = multiprocessing.Process(\n target=Test_process_target, args=(recieve_que, send_que, config))\n\n env_process.start()\n test_process.start()\n #con.start()\n test_process.join()\n env_process.join()\n #prod.join()\n\n\nif __name__ == '__main__':\n main()\n", "sub_path": "RL_SPIDER/Env.py", "file_name": "Env.py", "file_ext": "py", "file_size_in_byte": 4223, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "colorama.init", "line_number": 5, "usage_type": "call"}, {"api_name": "colorama.Fore.GREEN", "line_number": 15, "usage_type": "attribute"}, {"api_name": "colorama.Fore", "line_number": 15, "usage_type": "name"}, {"api_name": "serial.Serial", "line_number": 29, "usage_type": "call"}, {"api_name": "time.time", "line_number": 63, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 88, "usage_type": "call"}, {"api_name": "multiprocessing.freeze_support", "line_number": 113, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 119, "usage_type": "call"}, {"api_name": "multiprocessing.Queue", "line_number": 120, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 124, "usage_type": "call"}, {"api_name": "multiprocessing.Process", "line_number": 126, "usage_type": "call"}]}
+{"seq_id": "275317402", "text": "#!/usr/bin/env python3\n\nimport sys\nimport os\nimport difflib\nimport re\nimport shutil\nfrom jinja2 import Environment, PackageLoader\nimport subprocess\nfrom builtins import FileNotFoundError, NotADirectoryError\nimport concurrent.futures\nfrom bs4 import BeautifulSoup\n\nNUM_PROC = 7\n\n\nclass ERRaceClassifier(object):\n\n CLASSIFICATION = {\n 'rs': 'HIGH',\n 'ru': 'NORMAL',\n 'rk': 'LOW'\n }\n\n RACE_PARENT_RE = re.compile('(.*race[0-9]+)_race[0-9]+')\n\n def __init__(self, website_dir):\n\n self.website_dir = website_dir\n self._cache = {}\n\n def inject_classification(self, race_data, namespace):\n\n handle = race_data['handle']\n\n if 'race' not in handle:\n race_data['er_classification'] = 'PARSE_ERROR'\n race_data['er_classification_details'] = ''\n return\n \n id = handle[handle.rindex('race')+4:]\n\n parent = race_data['origin']\n\n if parent is None:\n\n match = self.RACE_PARENT_RE.match(handle)\n if match is None:\n parent = 'base'\n else:\n parent = match.group(1)\n\n if not parent in self._cache:\n\n varlist_path = os.path.join(self.website_dir, parent, 'varlist')\n\n if not os.path.exists(varlist_path):\n\n try:\n cmd = '$WEBERA_DIR/R4/er-classify.sh %s %s' % \\\n (os.path.join(self.website_dir, parent), namespace)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n except subprocess.CalledProcessError as e:\n print('Failed running %s' % cmd)\n\n try:\n with open(varlist_path, 'r') as fp:\n self._cache[parent] = BeautifulSoup(fp, 'html5lib')\n except FileNotFoundError:\n self._cache[parent] = None\n\n soup = self._cache.get(parent, None)\n\n if soup is not None:\n\n try:\n race_row = soup\\\n .find('a', href='race?id=%s' % id)\\\n .find_parent('tr')\\\n .previous_sibling.previous_sibling\n\n classification = self.CLASSIFICATION[race_row['class'][0][:2]]\n details = race_row.find_all('td')[-1].text\n details = details.strip()\n\n race_data['er_classification'] = classification\n race_data['er_classification_details'] = details\n except: #Exception as e:\n #raise e\n race_data['er_classification'] = 'PARSE_ERROR'\n race_data['er_classification_details'] = ''\n else:\n race_data['er_classification'] = 'UNKNOWN'\n race_data['er_classification_details'] = ''\n\n# Please look away, and allow me to be a bit quick-and-dirty for a moment\n\nmemlist_cache = {}\n\ndef get_memory_stats(race_dir, key):\n\n if race_dir not in memlist_cache:\n\n memlist_file = os.path.join(race_dir, 'memlist')\n if not os.path.exists(memlist_file) or os.stat(memlist_file).st_size == 0:\n print('Warning,', memlist_file, 'is missing')\n memlist_cache[race_dir] = {}\n\n else:\n\n RE_memory_location = re.compile('(Variable|Attribute)([a-zA-Z\\.0-9\\[\\]\\(\\)\\-_:/\\$]*) | ')\n RE_value = re.compile('Uncovered races: \\([a-z ]+\\) ([0-9]+)(.*?)
Covered races: ([0-9]+)(.*?)
')\n\n result = {}\n\n with open(memlist_file, 'rb') as fp:\n\n last_location = None\n\n for line in fp.readlines():\n line = line.decode('utf8', 'ignore')\n\n if last_location is None:\n match = RE_memory_location.search(line)\n if match is not None:\n last_location = match.group(2)\n\n else:\n match = RE_value.search(line)\n if match is not None:\n result[last_location] = {\n 'num_uncovered': int(match.group(1)),\n 'num_covered': int(match.group(3)),\n 'uncovered': match.group(2),\n 'covered': match.group(4)\n }\n else:\n print('Warning, could not find information for location', last_location)\n\n last_location = None\n\n memlist_cache[race_dir] = result\n\n return memlist_cache[race_dir].get(key, None)\n\nRE_value_with_memory = re.compile('\\[.*\\]|event action [0-9]+|IO_[0-9]+|:0x[abcdef\\-0-9]+|:[0-9]+|0x[abcdef0-9]+|x_x[0-9]+')\n\ndef anon(value, known_ids=[]):\n return RE_value_with_memory.sub('[??]', str(value)) if value not in known_ids else 'ID'\n\ndef abstract_memory_equal(handle, m1, m2):\n\n # start: Some fixes to the approximation\n\n # (b) id numbers (such as timer ids) can be stored as values, and naturally differ from execution to execution\n\n def get_known_ids(mem):\n ids = []\n for k,v in mem.items():\n if 'Timer:' in k:\n ids.append(k.split(':')[1])\n\n return ids\n\n known_ids = get_known_ids(m1)\n known_ids.extend(get_known_ids(m2))\n\n # Memory adresses are not equal in the two memory \"diffs\". We approximate their equality by stripping out\n # memory locations, and converting them into anon_memory_location=value strings.\n # We then check set equality\n\n memory1 = ['%s=%s' % (anon(location), anon(value, known_ids)) for location, value in m1.items()]\n\n # start: Some fixes to the approximation\n\n # (a) in some cases we observe registered event actions (which we execute) in the reordered sequence\n # but not in the original sequence. This is purely an anomaly in our instrumentation.\n\n ignore_memory2_keys = []\n for k,v in m2.items():\n if 'event action' in k and '-1' not in k and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1:\n ignore_memory2_keys.append(k)\n\n # end: fixes\n\n memory2 = ['%s=%s' % (anon(location), anon(value, known_ids)) for location, value in m2.items() if k not in ignore_memory2_keys]\n\n #if not set(memory1) == set(memory2):\n #print('\\n\\nMISS', \"\\n\", handle, \"\\n\", memory1, \"\\n\\n\", memory2, \"\\n\\n\", set(memory1) == set(memory2), \"\\n\\n\",\n # [v for v in memory1 if v not in memory2], \"\\n\\n\",\n # [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2], \"\\n\\n\",\n # [v for v in memory2 if v not in memory1], \"\\n\\n\",\n #[k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1], \"\\n\\n\")\n\n\n print(memory1, \"\\n\\n\", memory2, \"\\n\\n\", set(memory1) == set(memory2), \"\\n\\n\", [v for v in memory1 if v not in memory2], \"\\n\\n\", [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2], \"\\n\\n\", [v for v in memory2 if v not in memory1], \"\\n\\n\", [k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1])\n\n return (set(memory1) == set(memory2),\n [v for v in memory1 if v not in memory2],\n [v for v in memory2 if v not in memory1],\n [k for k,v in m1.items() if '%s=%s' % (anon(k), anon(v, known_ids)) not in memory2],\n [k for k,v in m2.items() if k not in ignore_memory2_keys and '%s=%s' % (anon(k), anon(v, known_ids)) not in memory1])\n\ndef create_if_missing_event_action_code(base_dir, namespace, *args):\n\n to_be_added = []\n\n for event_action_id in args:\n\n code_file = os.path.join(base_dir, 'varlist-%s.code' % event_action_id)\n if not os.path.exists(code_file) or os.stat(code_file).st_size == 0:\n to_be_added.append(event_action_id)\n\n if len(to_be_added) > 0:\n try:\n cmd = '$WEBERA_DIR/R4/er-code-file.sh %s %s %s' % (base_dir, namespace, ' '.join(to_be_added))\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n except subprocess.CalledProcessError as e:\n print('Failed running %s' % cmd)\n\n\ndef get_or_create_event_action_memory(base_dir, memory, event_action_id):\n\n RE_operation = re.compile('(read|write|value|start) <.*>(.*)')\n\n code_file = os.path.join(base_dir, 'varlist-%s.code' % event_action_id)\n line_num = 0\n with open(code_file, 'rb') as fp:\n\n last_location = None\n known_ids = []\n\n for line in fp:\n line_num += 1\n line = line.decode('utf8', 'ignore')\n\n match = RE_operation.search(line)\n\n if match is None:\n continue\n\n operation = match.group(1)\n location_or_value = match.group(2)\n\n if operation == 'write':\n\n if 'CachedResource' in location_or_value:\n # Cached resources never have a value\n memory[location_or_value] = \"?\"\n\n elif 'Timer:' in location_or_value:\n known_ids.append(location_or_value.split(':')[1])\n memory['TIMER'] = memory.get('TIMER', 0) + 1\n\n else:\n last_location = location_or_value\n\n elif operation == 'value' and last_location is not None:\n if location_or_value in known_ids:\n location_or_value = '??'\n\n memory[last_location] = location_or_value\n last_location = None\n\n elif operation == 'start' and 'event action -1' not in location_or_value:\n # Approximation, is it always safe to filter out event action -1?\n # TODO: Figure out why these are added non-deterministically in some cases\n memory[location_or_value] = memory.get(location_or_value, 0) + 1\n last_location = None\n\n elif operation == 'read':\n last_location = None\n\n if line_num == 0:\n print('Warning,', code_file, 'is empty!')\n\n return memory\n\ndef get_abstract_memory(base_dir, namespace, event_handler1, event_handler2):\n\n if not event_handler1 or not event_handler2:\n return {}\n\n race_first_id, race_first_descriptor = event_handler1\n race_second_id, race_second_descriptor = event_handler2\n\n create_if_missing_event_action_code(base_dir, namespace, race_first_id, race_second_id)\n\n memory = get_or_create_event_action_memory(base_dir, {}, race_first_id)\n memory = get_or_create_event_action_memory(base_dir, memory, race_second_id)\n\n return memory\n\n\nclass RaceParseException(Exception):\n pass\n\n\nclass HashableDict(dict):\n\n def __init__(self, *args, **kwargs):\n self.ignore_properties = kwargs.pop('_ignore_properties', None)\n\n if self.ignore_properties is None:\n self.ignore_properties = []\n\n super(HashableDict, self).__init__(*args, **kwargs)\n\n def __cmp__(self, other):\n t = self.__hash__()\n o = other.__hash__()\n\n if t == o:\n return 0\n elif t < o:\n return -1\n else:\n return 1\n\n def __eq__(self, other):\n return self.__hash__() == other.__hash__()\n\n def __hash__(self):\n return hash(tuple(sorted([item for item in self.items() if item[0] not in self.ignore_properties])))\n\n\ndef parse_race(base_dir, handle):\n \"\"\"\n Outputs data\n \"\"\"\n\n handle_dir = os.path.join(base_dir, handle)\n\n # ERRORS\n\n errors_file = os.path.join(handle_dir, 'out.errors.log')\n if not os.path.exists(errors_file):\n errors_file = os.path.join(handle_dir, 'errors.log')\n\n errors = []\n exceptions = []\n new_events = []\n\n num_new_events = 0\n num_skipped_events = 0\n\n try:\n fp = open(errors_file, 'rb')\n except (FileNotFoundError, NotADirectoryError):\n raise RaceParseException()\n\n with fp:\n while True:\n header = fp.readline().decode('utf8', 'ignore')\n\n if header == '':\n break # EOF reached\n\n event_action_id, module, description, length = header.split(';')\n length = int(length)\n\n if length == 0:\n details = ''\n else:\n details = fp.read(length).decode('utf8', 'ignore')\n\n container = errors\n t = 'error'\n\n if 'JavaScript_Interpreter' in module:\n if 'An exception occured' in description and \\\n any([buildin_exception_indicator in details for buildin_exception_indicator in [\n 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'\n ]]):\n\n container = exceptions\n t = 'exception'\n\n elif 'console.log' in module:\n if 'ERROR' in description and \\\n any([buildin_exception_indicator in details for buildin_exception_indicator in [\n 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError'\n ]]):\n\n container = exceptions\n t = 'exception'\n else:\n continue\n\n if 'Non-executed event action' in description:\n new_events.append(details)\n num_new_events += 1\n\n if 'JavaScript_Interpreter' in module and 'Event action skipped after timeout.' in description:\n num_skipped_events += 1\n\n if 'JavaScript_Interpreter' in module and 'Event action executed from pending schedule.' in description:\n num_skipped_events -= 1\n\n container.append(HashableDict(\n event_action_id=event_action_id,\n type=t,\n module=module,\n description=description,\n details=details,\n _ignore_properties=['event_action_id', 'type']\n ))\n\n # STDOUT\n\n stdout_file = os.path.join(handle_dir, 'stdout')\n if not os.path.exists(stdout_file):\n stdout_file = os.path.join(handle_dir, 'stdout.txt')\n\n with open(stdout_file, 'rb') as fp:\n stdout = fp.read().decode('utf8', 'ignore')\n\n result_match = re.compile('Result: ([A-Z]+)').search(stdout)\n state_match = re.compile('HTML-hash: ([0-9]+)').search(stdout)\n\n if result_match is None:\n print('Warning, result not found in file:', stdout_file)\n\n if state_match is None:\n print('Warning, state not found in file:', stdout_file)\n\n # Origin\n\n origin = None\n origin_file = os.path.join(handle_dir, 'origin')\n\n if os.path.exists(origin_file):\n with open(origin_file, 'rb') as fp:\n origin = str(fp.read().decode('utf8', 'ignore')).strip()\n\n # SCHEDULE\n\n schedule_file = os.path.join(handle_dir, 'new_schedule.data')\n if not os.path.isfile(schedule_file):\n schedule_file = os.path.join(handle_dir, 'new_wave_schedule.data')\n\n output_schedule_file = os.path.join(handle_dir, 'out.schedule.data')\n if not os.path.isfile(output_schedule_file):\n output_schedule_file = os.path.join(handle_dir, 'schedule.data')\n\n schedule = []\n raceFirst = \"\"\n raceFirstIndex = -1\n raceSecond = \"\"\n raceSecondIndex = -1\n\n with open(schedule_file, 'rb') as fp:\n\n index = 0\n for line in fp.readlines():\n line = line.decode('utf8', 'ignore')\n\n if line == '':\n continue\n\n if '' in line or '' in line:\n event_action_id = -1\n event_action_descriptor = line\n\n # This is a hack,\n # If se see , then the next line should be saved as the first racing event\n # and if we see , then the next line should be saved as the second racing event.\n\n if '' in line:\n raceFirst = None\n\n if '' in line:\n raceSecond = None\n\n else:\n event_action_id, event_action_descriptor = line.split(';', 1)\n\n # If any race is marked as None, then we should update it now\n\n if raceFirst is None:\n raceFirst = (event_action_id, event_action_descriptor)\n raceFirstIndex = index\n\n if raceSecond is None:\n raceSecond = (event_action_id, event_action_descriptor)\n raceSecondIndex = index\n\n index += 1\n\n output_race_first = None\n output_race_second = None\n\n with open(output_schedule_file, 'rb') as fp:\n\n lines = fp.readlines()\n\n try:\n # subtract 1 for the missing marker\n output_race_first = lines[raceFirstIndex-1].decode('utf8', 'ignore').split(';', 1)\n\n # subtract 2 for and markers\n output_race_second = lines[raceSecondIndex-2].decode('utf8', 'ignore').split(';', 1)\n\n except IndexError:\n output_race_first = None\n output_race_second = None\n\n index = 0\n for line in lines:\n line = line.decode('utf8', 'ignore')\n\n if line == '':\n continue\n\n if index == raceFirstIndex:\n\n schedule.append(HashableDict(\n event_action_id=-1,\n type='schedule',\n event_action_descriptor=\"\",\n _ignore_properties=['event_action_id', 'type']\n ))\n\n if index == raceSecondIndex:\n\n schedule.append(HashableDict(\n event_action_id=-1,\n type='schedule',\n event_action_descriptor=\"\",\n _ignore_properties=['event_action_id', 'type']\n ))\n\n event_action_id, event_action_descriptor = line.split(';', 1)\n\n schedule.append(HashableDict(\n event_action_id=event_action_id,\n type='schedule',\n event_action_descriptor=event_action_descriptor,\n _ignore_properties=['event_action_id', 'type']\n ))\n\n index += 1\n\n # ZIP ERRORS AND SCHEDULE\n\n zip_errors_schedule = []\n current_event_action_id = None\n\n buckets = {}\n\n for s in schedule:\n if s['event_action_id'] == -1:\n continue\n\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in errors:\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in exceptions:\n bucket = buckets.get(s['event_action_id'], [])\n bucket.append(s)\n buckets[s['event_action_id']] = bucket\n\n for s in schedule:\n if s['event_action_id'] == -1:\n zip_errors_schedule.append(s)\n continue\n\n try:\n zip_errors_schedule.extend(buckets[s['event_action_id']])\n del buckets[s['event_action_id']]\n except:\n print(\"Error applying event action\", s['event_action_id'], \"to zipped schedule\")\n\n for bucket in buckets:\n zip_errors_schedule.extend(buckets[bucket])\n\n return {\n 'handle': handle,\n 'errors': errors,\n 'exceptions': exceptions,\n 'schedule': schedule,\n 'zip_errors_schedule': zip_errors_schedule,\n 'result': result_match.group(1) if result_match is not None else 'ERROR',\n 'html_state': state_match.group(1) if state_match is not None else 'ERROR',\n 'race_dir': handle_dir,\n 'origin': origin,\n 'raceFirst': raceFirst,\n 'raceSecond': raceSecond,\n 'output_race_first': output_race_first,\n 'output_race_second': output_race_second,\n 'new_events': new_events,\n 'num_new_events': num_new_events,\n 'num_skipped_events': num_skipped_events\n }\n\n\ndef parse_er_log(base_dir):\n\n result = {\n 'races_total': -1,\n 'races_success': -1,\n 'races_failure': -1,\n 'execution_time': 0,\n 'stdout': ''\n }\n\n try:\n fp = open(os.path.join(base_dir, 'runner', 'stdout.txt'), 'rb')\n except (FileNotFoundError, NotADirectoryError):\n return result\n\n with fp:\n stdout = fp.read().decode('utf8', 'ignore')\n result['stdout'] = stdout\n\n if 'WARNING: Stopped iteration' in stdout:\n print('Warning, iteration max reached.')\n\n result_match = re.compile('Tried ([0-9]+) schedules. ([0-9]+) generated, ([0-9]+)').search(stdout)\n\n if result_match is not None:\n result['races_total'] = int(result_match.group(2))\n result['races_success'] = int(result_match.group(3))\n result['races_failure'] = int(result_match.group(2)) - int(result_match.group(3))\n else:\n print('FAIL')\n print(stdout)\n\n time_match = re.compile('real ([0-9]+)\\.[0-9]+').search(stdout)\n\n if time_match is not None:\n result['execution_time'] = int(time_match.group(1))\n\n return result\n\n\ndef generate_comparison_file(record_file, replay_file, comparison_file):\n try:\n cmd = 'compare -metric RMSE %s %s %s' % (record_file, replay_file, comparison_file)\n print(cmd)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n type = 'normal'\n except subprocess.CalledProcessError as e:\n if e.returncode == 2:\n return 'error', -1\n\n stdout = e.output\n type = 'normal'\n\n if b'image widths or heights differ' in stdout:\n # do a subimage search\n\n try:\n cmd = 'compare -metric RMSE -subimage-search %s %s %s' % (record_file, replay_file, comparison_file)\n print(cmd)\n stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n type = 'subimage'\n except subprocess.CalledProcessError as e:\n if e.returncode == 2:\n return 'error', -1\n\n stdout = e.output\n type = 'subimage'\n\n match = re.compile(b'([0-9]+\\.?[0-9]*) \\([0-9]+\\.?[0-9]*\\)').search(stdout)\n\n if match is None:\n return 'error', -1\n\n return type, float(match.group(1))\n\n\ndef cimage_human(type, distance):\n if type == 'normal' and distance == 0:\n return 'EXACT'\n elif type == 'normal' and distance != 0:\n return 'DIFFER'\n elif type == 'subimage':\n return 'SUBSET'\n else:\n return 'ERROR'\n\n\ndef compare_race(base_data, race_data, namespace):\n \"\"\"\n Outputs comparison\n \"\"\"\n\n # Compare image\n\n cimage_meta = os.path.join(race_data['race_dir'], 'comparison.txt')\n\n if not os.path.isfile(cimage_meta):\n\n file1 = os.path.join(base_data['race_dir'], 'out.screenshot.png')\n if not os.path.exists(file1):\n file1 = os.path.join(base_data['race_dir'], 'screenshot.png')\n\n file2 = os.path.join(race_data['race_dir'], 'out.screenshot.png')\n if not os.path.exists(file2):\n file2 = os.path.join(race_data['race_dir'], 'screenshot.png')\n\n match_type, distance = generate_comparison_file(\n file1,\n file2,\n os.path.join(race_data['race_dir'], 'comparison.png'))\n\n cimage = {\n 'distance': float(distance),\n 'match_type': match_type,\n 'human': cimage_human(match_type, distance)\n }\n\n with open(cimage_meta, 'w') as fp:\n fp.writelines([\n str(cimage['distance']),\n cimage['match_type']\n ])\n\n else:\n\n with open(cimage_meta, 'r') as fp:\n line = fp.readline()\n match = re.compile('^(\\-?[0-9]+\\.?[0-9]*)([a-z]+)$').search(line)\n\n cimage = {\n 'distance': float(match.group(1)),\n 'match_type': match.group(2),\n 'human': cimage_human(match.group(2), float(match.group(1)))\n }\n\n def remove_new_event_action(base_list, race_list):\n # Remove \"new event action\" error at the end of error reports if they both have it\n # Often, this is not an error, just a side effect of the system, and this side effect\n # is different from execution to execution. Filter it away\n if len(base_list) > 0 and len(race_list) > 0:\n\n if base_list[-1]['type'] == 'error' and race_list[-1]['type'] == 'error' and \\\n 'event action observed' in base_list[-1]['description'] and \\\n 'event action observed' in race_list[-1]['description']:\n\n return base_list[:-1], race_list[:-1]\n\n return base_list, race_list\n\n # Errors diff\n\n base_errors = base_data['errors']\n race_errors = race_data['errors']\n\n base_errors, race_errors = remove_new_event_action(base_errors, race_errors)\n\n diff = difflib.SequenceMatcher(None, base_errors, race_errors)\n opcodes = diff.get_opcodes()\n opcodes_human = []\n\n for opcode in opcodes:\n tag, i1, i2, j1, j2 = opcode\n\n opcodes_human.append({\n 'base': base_errors[i1:i2],\n 'tag': tag,\n 'race': race_errors[j1:j2]\n })\n\n errors_distance = sum(1 for opcode in opcodes if opcode[0] != 'equal')\n\n # Exceptions diff\n\n base_exceptions = base_data['exceptions']\n race_exceptions = race_data['exceptions']\n\n exceptions_diff = difflib.SequenceMatcher(None, base_exceptions, race_exceptions)\n exceptions_opcodes = exceptions_diff.get_opcodes()\n exceptions_opcodes_human = []\n\n for opcode in exceptions_opcodes:\n tag, i1, i2, j1, j2 = opcode\n\n exceptions_opcodes_human.append({\n 'base': base_exceptions[i1:i2],\n 'tag': tag,\n 'race': race_exceptions[j1:j2]\n })\n\n exceptions_distance = sum(1 for opcode in exceptions_opcodes if opcode[0] != 'equal')\n\n exceptions_set_comparison = \\\n set(['%s%s' % (base_exception['description'], base_exception['details']) for base_exception in base_exceptions]) == \\\n set(['%s%s' % (base_exception['description'], base_exception['details']) for base_exception in race_exceptions])\n\n # Race and Errors Diff\n\n base_zip = base_data['zip_errors_schedule']\n race_zip = race_data['zip_errors_schedule']\n\n base_zip, race_zip = remove_new_event_action(base_zip, race_zip)\n\n zip_diff = difflib.SequenceMatcher(None, base_zip, race_zip)\n zip_opcodes = zip_diff.get_opcodes()\n zip_opcodes_human = []\n\n unequal_seen = False\n\n for zip_opcode in zip_opcodes:\n tag, i1, i2, j1, j2 = zip_opcode\n\n if not unequal_seen and tag != 'equal':\n unequal_seen = True\n first_unequal = True\n else:\n first_unequal = False\n\n zip_opcodes_human.append({\n 'base': base_zip[i1:i2],\n 'tag': tag,\n 'race': race_zip[j1:j2],\n 'first_unequal': first_unequal\n })\n\n # R4 race classification\n\n html_state_match = base_data['html_state'] == race_data['html_state']\n visual_state_match = cimage.get('human', 'FAIL') == 'EXACT'\n\n classification = 'NORMAL'\n classification_details = \"\"\n\n # Low triggers\n\n # High triggers (classifiers)\n\n if not exceptions_set_comparison:\n classification = 'HIGH'\n classification_details += 'R4_EXCEPTIONS '\n\n if not visual_state_match and not html_state_match:\n classification = 'HIGH'\n classification_details += 'R4_DOM_AND_RENDER_MISMATCH '\n\n if 'initialization race' in race_data['er_classification_details']:\n classification = 'HIGH'\n classification_details += 'ER_INITIALIZATION_RACE '\n\n if 'readyStateChange race' in race_data['er_classification_details']:\n classification = 'HIGH'\n classification_details += 'ER_READYSTATECHANGE_RACE '\n\n # Low Triggers (strong update)\n\n if 'LATE_EVENT_ATTACH' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_LATE_EVENT_ATTACH '\n\n if 'COOKIE_OR_CLASSNAME' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_COOKIE_OR_CLASSNAME '\n\n if 'MAYBE_LAZY_INIT' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_MAYBE_LAZY_INIT '\n\n if 'ONLY_LOCAL_WRITE' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_ONLY_LOCAL_WRITE '\n\n if 'NO_EVENT_ATTACHED' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_NO_EVENT_ATTACHED '\n\n if 'WRITE_SAME_VALUE' in race_data['er_classification_details']:\n classification = 'LOW'\n classification_details += 'ER_WRITE_SAME_VALUE '\n\n if classification != 'LOW' and race_data['er_classification'] == 'LOW':\n print('Error: Unknown classification', race_data['er_classification_details'])\n\n schedule_distance = race_data['num_new_events'] + race_data['num_skipped_events']\n\n return {\n 'schedule_distance': schedule_distance,\n 'exceptions_diff': exceptions_opcodes,\n 'exceptions_diff_human': exceptions_opcodes_human,\n 'exceptions_diff_distance': exceptions_distance,\n 'errors_diff': opcodes,\n 'errors_diff_human': opcodes_human,\n 'errors_diff_distance': errors_distance,\n 'zip_diff': zip_opcodes,\n 'zip_diff_human': zip_opcodes_human,\n 'zip_diff_has_unequal': unequal_seen,\n 'html_state_match': html_state_match,\n 'visual_state_match': cimage,\n 'is_equal': base_data['html_state'] == race_data['html_state'] and schedule_distance == 0 and exceptions_distance == 0,\n 'r4_classification': classification,\n 'r4_classification_details': classification_details\n }\n\n\ndef output_race_report(website, race, jinja, output_dir, input_dir):\n \"\"\"\n Outputs filename of written report\n \"\"\"\n\n record_file = os.path.join(output_dir, 'record.png')\n replay_file = os.path.join(output_dir, '%s-replay.png' % race['handle'])\n comparison_file = os.path.join(output_dir, '%s-comparison.png' % race['handle'])\n\n try:\n if not os.path.isfile(record_file):\n path = os.path.join(input_dir, website, 'base', 'out.screenshot.png')\n if not os.path.exists(path):\n path = os.path.join(input_dir, website, 'base', 'screenshot.png')\n\n shutil.copy(path, record_file)\n\n except FileNotFoundError:\n pass\n\n try:\n path = os.path.join(input_dir, website, race['handle'], 'out.screenshot.png')\n if not os.path.exists(path):\n path = os.path.join(input_dir, website, race['handle'], 'screenshot.png')\n shutil.copy(path, replay_file)\n except FileNotFoundError:\n pass\n\n try:\n shutil.copy(os.path.join(input_dir, website, race['handle'], 'comparison.png'), comparison_file)\n except FileNotFoundError:\n try:\n shutil.copy(os.path.join(input_dir, website, race['handle'], 'comparison-0.png'), comparison_file)\n except FileNotFoundError:\n pass\n\n with open(os.path.join(output_dir, '%s.html' % race['handle']), 'w') as fp:\n\n fp.write(jinja.get_template('race.html').render(\n website=website,\n race=race\n ))\n\n\ndef output_race_index(website, parsed_races, er_log, jinja, output_dir, input_dir):\n\n try:\n os.mkdir(output_dir)\n except OSError:\n pass # folder exists\n\n for race in parsed_races:\n output_race_report(website, race, jinja, output_dir, input_dir)\n\n with open(os.path.join(output_dir, 'index.html'), 'w') as fp:\n\n fp.write(jinja.get_template('race_index.html').render(\n website=website,\n parsed_races=parsed_races,\n er_log=er_log\n ))\n\ndef output_website_index(website_index, output_dir, input_dir):\n\n jinja = Environment(loader=PackageLoader('templates', ''))\n\n try:\n os.mkdir(output_dir)\n except OSError:\n pass # folder exists\n\n summary = {\n 'race_result': {\n 'equal': 0,\n 'diff': 0,\n 'timeout': 0,\n 'error': 0\n },\n 'execution_result': {\n 'total': 0,\n 'success': 0,\n 'failure': 0\n },\n 'er_classification_result': {\n 'high': 0,\n 'normal': 0,\n 'low': 0,\n 'unknown': 0\n },\n 'r4_classification_result': {\n 'high': 0,\n 'normal': 0,\n 'low': 0\n },\n 'execution_time': 0,\n }\n\n items = []\n\n for item in website_index:\n\n if item is None:\n continue\n\n summary['race_result']['equal'] += item['summary']['equal']\n summary['race_result']['diff'] += item['summary']['diff']\n summary['race_result']['timeout'] += item['summary']['timeout']\n summary['race_result']['error'] += item['summary']['error']\n\n summary['execution_result']['total'] += item['er_log']['races_total']\n summary['execution_result']['success'] += item['er_log']['races_success']\n summary['execution_result']['failure'] += item['er_log']['races_failure']\n\n summary['execution_time'] += item['er_log']['execution_time']\n\n summary['er_classification_result']['high'] += item['summary']['er_high']\n summary['er_classification_result']['normal'] += item['summary']['er_normal']\n summary['er_classification_result']['low'] += item['summary']['er_low']\n summary['er_classification_result']['unknown'] += item['summary']['er_unknown']\n summary['r4_classification_result']['high'] += item['summary']['r4_high']\n summary['r4_classification_result']['normal'] += item['summary']['r4_normal']\n summary['r4_classification_result']['low'] += item['summary']['r4_low']\n\n items.append(item)\n\n with open(os.path.join(output_dir, 'index.html'), 'w') as fp:\n\n fp.write(jinja.get_template('index.html').render(\n website_index=items,\n summary=summary\n ))\n\ndef process_race(website_dir, race_data, base_data, er_race_classifier, namespace):\n\n er_race_classifier.inject_classification(race_data, namespace)\n\n comparison = compare_race(base_data, race_data, namespace)\n\n return {\n 'handle': race_data['handle'],\n 'base_data': base_data,\n 'race_data': race_data,\n 'comparison': comparison\n }\n\n\ndef process(job):\n\n website, analysis_dir, output_dir, namespace = job\n\n print (\"PROCESSING\", website)\n\n website_dir = os.path.join(analysis_dir, website)\n parsed_races = []\n\n ## Get a list of races ##\n\n races = os.listdir(website_dir)\n\n try:\n races.remove('base')\n races.remove('record')\n except ValueError:\n print('Error, missing base or record directory in output dir for %s' % website)\n return None\n\n ignore_files = ['runner', 'record.png', 'arcs.log', 'out.schedule.data', 'new_schedule.data', 'stdout.txt', 'out.ER_actionlog', 'out.log.network.data', 'out.log.time.data', 'out.log.random.data', 'out.status.data']\n\n races = [race for race in races if not race.startswith('_') and not race in ignore_files]\n\n ## Parse each race ##\n\n er_race_classifier = ERRaceClassifier(website_dir)\n er_log = parse_er_log(website_dir)\n\n for race in races:\n\n try:\n race_data = parse_race(website_dir, race)\n except RaceParseException:\n print(\"Error parsing %s :: %s\" % (website, race))\n\n try:\n base_data = parse_race(website_dir, race_data['origin'])\n except RaceParseException:\n print(\"Error parsing %s :: %s (base)\" % website)\n break\n\n parsed_races.append(process_race(website_dir, race_data, base_data, er_race_classifier, namespace))\n\n classifiers = ['R4_EXCEPTIONS', 'R4_DOM_AND_RENDER_MISMATCH', 'ER_INITIALIZATION_RACE', 'ER_READYSTATECHANGE_RACE']\n\n er_tags = ['ER_LATE_EVENT_ATTACH', 'ER_COOKIE_OR_CLASSNAME', 'ER_MAYBE_LAZY_INIT', 'ER_ONLY_LOCAL_WRITE',\n 'ER_NO_EVENT_ATTACHED', 'ER_WRITE_SAME_VALUE']\n\n\n\n r4_tags = ['R4_AD_HOC_SYNC_PENDING_EVENTS',\n 'R4_DOM_TIMER_AD_HOC_SYNC[EARLY]', 'R4_DOM_TIMER_AD_HOC_SYNC[DELAY]', 'R4_EVENTS_COMMUTE',\n 'R4_SPAWN_TIMER_AD_HOC[DELAY]', 'R4_SPAWN_TIMER_AD_HOC[EARLY]', 'R4_CONTINUATION_AD_HOC']\n\n r4_classifiers = ['R4_EXCEPTIONS', 'R4_DOM_AND_RENDER_MISMATCH']\n er_classifiers = ['ER_INITIALIZATION_RACE', 'ER_READYSTATECHANGE_RACE']\n\n tags = ['ER_LATE_EVENT_ATTACH', 'ER_COOKIE_OR_CLASSNAME', 'ER_MAYBE_LAZY_INIT', 'ER_ONLY_LOCAL_WRITE',\n 'ER_NO_EVENT_ATTACHED', 'ER_WRITE_SAME_VALUE', 'R4_AD_HOC_SYNC_PENDING_EVENTS',\n 'R4_DOM_TIMER_AD_HOC_SYNC[EARLY]', 'R4_DOM_TIMER_AD_HOC_SYNC[DELAY]', 'R4_EVENTS_COMMUTE',\n 'R4_SPAWN_TIMER_AD_HOC[DELAY]', 'R4_SPAWN_TIMER_AD_HOC[EARLY]', 'R4_CONTINUATION_AD_HOC']\n\n data = [website,\n str(len(parsed_races)),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'LOW'])),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'NORMAL'])),\n str(len([1 for race in parsed_races if race['comparison']['r4_classification'] == 'HIGH']))]\n\n def filter_classifiers(details):\n return [c for c in details.split(' ') if c not in classifiers]\n\n def only_classifiers(details):\n return [c for c in details.split(' ') if c in classifiers]\n\n\n #for tag in tags:\n # if tag in classifiers:\n # data.append(str(len([1 for race in parsed_races if tag in only_classifiers(race['comparison']['r4_classification_details']) and len(only_classifiers(race['comparison']['r4_classification_details'])) == 1])))\n # else:\n # data.append(str(len([1 for race in parsed_races if tag in filter_classifiers(race['comparison']['r4_classification_details']) and len(filter_classifiers(race['comparison']['r4_classification_details'])) == 1])))\n\n # classified by R4\n for tag in r4_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags)])))\n\n # classified by ER\n for tag in er_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags)])))\n\n for tag in tags:\n data.append(str(len([1 for race in parsed_races if tag in race['comparison']['r4_classification_details']])))\n\n # filtered by ER\n data.append(str(len([1 for race in parsed_races if\n any([tag in er_tags for tag in race['comparison']['r4_classification_details'].split(' ')])])))\n\n # filtered by R4\n data.append(str(len([1 for race in parsed_races if\n any([tag in r4_tags for tag in race['comparison']['r4_classification_details'].split(' ')])])))\n\n # classified by R4 only\n for tag in r4_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags) and not \\\n any(t in race['comparison']['r4_classification_details'] for t in er_classifiers)])\\\n))\n\n # classified by ER only\n for tag in er_classifiers:\n data.append(str(len([1 for race in parsed_races if \\\n tag in race['comparison']['r4_classification_details'] and not \\\n any(t in race['comparison']['r4_classification_details'] for t in tags) and not \\\n any(t in race['comparison']['r4_classification_details'] for t in r4_classifiers)])\\\n))\n\n\n # ER classifies as high\n data.append(str(len([race for race in parsed_races if race['race_data']['er_classification'] == 'HIGH'])))\n\n ## Output statistics\n print(','.join(data))\n\n ## Generate HTML files ##\n\n jinja = Environment(loader=PackageLoader('templates', ''))\n\n website_output_dir = os.path.join(output_dir, website)\n output_race_index(website, parsed_races, er_log, jinja, website_output_dir, analysis_dir)\n\n ## End ##\n\n summary = {\n 'equal': len([race for race in parsed_races if race['race_data']['result'] == 'FINISHED' and race['comparison']['is_equal']]),\n 'diff': len([race for race in parsed_races if race['race_data']['result'] == 'FINISHED' and not race['comparison']['is_equal']]),\n 'timeout': len([race for race in parsed_races if race['race_data']['result'] == 'TIMEOUT']),\n 'error': len([race for race in parsed_races if race['race_data']['result'] == 'ERROR']),\n 'er_high': len([race for race in parsed_races if race['race_data']['er_classification'] == 'HIGH']),\n 'er_normal': len([race for race in parsed_races if race['race_data']['er_classification'] == 'NORMAL']),\n 'er_low': len([race for race in parsed_races if race['race_data']['er_classification'] == 'LOW']),\n 'er_unknown': len([race for race in parsed_races if race['race_data']['er_classification'] in ['UNKNOWN', 'PARSE_ERROR']]),\n 'r4_high': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'HIGH']),\n 'r4_normal': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'NORMAL']),\n 'r4_low': len([race for race in parsed_races if race['comparison']['r4_classification'] == 'LOW'])\n }\n\n return {\n 'website': website,\n 'er_log': er_log,\n 'summary': summary\n }\n\ndef main():\n\n try:\n analysis_dir = sys.argv[1]\n output_dir = sys.argv[2]\n except IndexError:\n print('Usage: %s ' % sys.argv[0])\n sys.exit(1)\n\n websites = os.listdir(analysis_dir)\n\n with concurrent.futures.ProcessPoolExecutor(NUM_PROC) as executor:\n website_index = executor.map(process, [(websites[index], analysis_dir, output_dir, str(8001+index)) for index in range(0, len(websites))])\n #website_index = [process([website, analysis_dir, output_dir, \"8001\"]) for website in websites]\n output_website_index(website_index, output_dir, analysis_dir)\n\nif __name__ == '__main__':\n main()\n", "sub_path": "R4/utils/batch-report/report-wave.py", "file_name": "report-wave.py", "file_ext": "py", "file_size_in_byte": 42979, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "re.compile", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 57, "usage_type": "call"}, {"api_name": "os.path", "line_number": 57, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 62, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 62, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 63, "usage_type": "attribute"}, {"api_name": "bs4.BeautifulSoup", "line_number": 68, "usage_type": "call"}, {"api_name": "builtins.FileNotFoundError", "line_number": 69, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 104, "usage_type": "call"}, {"api_name": "os.path", "line_number": 104, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 105, "usage_type": "call"}, {"api_name": "os.path", "line_number": 105, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 105, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 111, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 112, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 210, "usage_type": "call"}, {"api_name": "os.path", "line_number": 210, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 211, "usage_type": "call"}, {"api_name": "os.path", "line_number": 211, "usage_type": "attribute"}, {"api_name": "os.stat", "line_number": 211, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 217, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 217, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 218, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 332, "usage_type": "call"}, {"api_name": "os.path", "line_number": 332, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 336, "usage_type": "call"}, {"api_name": "os.path", "line_number": 336, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 337, "usage_type": "call"}, {"api_name": "os.path", "line_number": 337, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 338, "usage_type": "call"}, {"api_name": "os.path", "line_number": 338, "usage_type": "attribute"}, {"api_name": "builtins.FileNotFoundError", "line_number": 349, "usage_type": "name"}, {"api_name": "builtins.NotADirectoryError", "line_number": 349, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 411, "usage_type": "call"}, {"api_name": "os.path", "line_number": 411, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 412, "usage_type": "call"}, {"api_name": "os.path", "line_number": 412, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 413, "usage_type": "call"}, {"api_name": "os.path", "line_number": 413, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 418, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 419, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 430, "usage_type": "call"}, {"api_name": "os.path", "line_number": 430, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 432, "usage_type": "call"}, {"api_name": "os.path", "line_number": 432, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 438, "usage_type": "call"}, {"api_name": "os.path", "line_number": 438, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 439, "usage_type": "call"}, {"api_name": "os.path", "line_number": 439, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 440, "usage_type": "call"}, {"api_name": "os.path", "line_number": 440, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 442, "usage_type": "call"}, {"api_name": "os.path", "line_number": 442, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 443, "usage_type": "call"}, {"api_name": "os.path", "line_number": 443, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 444, "usage_type": "call"}, {"api_name": "os.path", "line_number": 444, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 614, "usage_type": "call"}, {"api_name": "os.path", "line_number": 614, "usage_type": "attribute"}, {"api_name": "builtins.FileNotFoundError", "line_number": 615, "usage_type": "name"}, {"api_name": "builtins.NotADirectoryError", "line_number": 615, "usage_type": "name"}, {"api_name": "re.compile", "line_number": 625, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 635, "usage_type": "call"}, {"api_name": "subprocess.check_output", "line_number": 647, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 647, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 649, "usage_type": "attribute"}, {"api_name": "subprocess.check_output", "line_number": 662, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 662, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 664, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 671, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 697, "usage_type": "call"}, {"api_name": "os.path", "line_number": 697, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 699, "usage_type": "call"}, {"api_name": "os.path", "line_number": 699, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 701, "usage_type": "call"}, {"api_name": "os.path", "line_number": 701, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 702, "usage_type": "call"}, {"api_name": "os.path", "line_number": 702, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 703, "usage_type": "call"}, {"api_name": "os.path", "line_number": 703, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 705, "usage_type": "call"}, {"api_name": "os.path", "line_number": 705, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 706, "usage_type": "call"}, {"api_name": "os.path", "line_number": 706, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 707, "usage_type": "call"}, {"api_name": "os.path", "line_number": 707, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 712, "usage_type": "call"}, {"api_name": "os.path", "line_number": 712, "usage_type": "attribute"}, {"api_name": "re.compile", "line_number": 730, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 759, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 779, "usage_type": "call"}, {"api_name": "difflib.SequenceMatcher", "line_number": 805, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 910, "usage_type": "call"}, {"api_name": "os.path", "line_number": 910, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 911, "usage_type": "call"}, {"api_name": "os.path", "line_number": 911, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 912, "usage_type": "call"}, {"api_name": "os.path", "line_number": 912, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 915, "usage_type": "call"}, {"api_name": "os.path", "line_number": 915, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 916, "usage_type": "call"}, {"api_name": "os.path", "line_number": 916, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 917, "usage_type": "call"}, {"api_name": "os.path", "line_number": 917, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 918, "usage_type": "call"}, {"api_name": "os.path", "line_number": 918, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 920, "usage_type": "call"}, {"api_name": "builtins.FileNotFoundError", "line_number": 922, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 926, "usage_type": "call"}, {"api_name": "os.path", "line_number": 926, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 927, "usage_type": "call"}, {"api_name": "os.path", "line_number": 927, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 928, "usage_type": "call"}, {"api_name": "os.path", "line_number": 928, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 929, "usage_type": "call"}, {"api_name": "builtins.FileNotFoundError", "line_number": 930, "usage_type": "name"}, {"api_name": "shutil.copy", "line_number": 934, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 934, "usage_type": "call"}, {"api_name": "os.path", "line_number": 934, "usage_type": "attribute"}, {"api_name": "builtins.FileNotFoundError", "line_number": 935, "usage_type": "name"}, {"api_name": "shutil.copy", "line_number": 937, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 937, "usage_type": "call"}, {"api_name": "os.path", "line_number": 937, "usage_type": "attribute"}, {"api_name": "builtins.FileNotFoundError", "line_number": 938, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 941, "usage_type": "call"}, {"api_name": "os.path", "line_number": 941, "usage_type": "attribute"}, {"api_name": "os.mkdir", "line_number": 952, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 959, "usage_type": "call"}, {"api_name": "os.path", "line_number": 959, "usage_type": "attribute"}, {"api_name": "jinja2.Environment", "line_number": 969, "usage_type": "call"}, {"api_name": "jinja2.PackageLoader", "line_number": 969, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 972, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1030, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1030, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 1057, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1057, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 1062, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 1181, "usage_type": "call"}, {"api_name": "jinja2.PackageLoader", "line_number": 1181, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 1183, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1183, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 1211, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 1212, "usage_type": "attribute"}, {"api_name": "sys.argv", "line_number": 1214, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 1215, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 1217, "usage_type": "call"}, {"api_name": "concurrent.futures.futures.ProcessPoolExecutor", "line_number": 1219, "usage_type": "call"}, {"api_name": "concurrent.futures.futures", "line_number": 1219, "usage_type": "attribute"}, {"api_name": "concurrent.futures", "line_number": 1219, "usage_type": "name"}]}
+{"seq_id": "513010036", "text": "# -*- coding: utf-8 -*-\r\n\r\n# Copyright 2015 www.suishouguan.com\r\n#\r\n# Licensed under the Private License (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# https://github.com/samuelbaizg/ssguan/blob/master/LICENSE\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport platform\r\n\r\nfrom tornado.ioloop import IOLoop, PeriodicCallback\r\n\r\nfrom ssguan.ignitor.base import context\r\nfrom ssguan.ignitor.orm.model import Model\r\nfrom ssguan.ignitor.sched import logger\r\nfrom ssguan.ignitor.sched.cronjob import CronJob\r\nfrom ssguan.ignitor.sched.error import SchedRunningError\r\nfrom ssguan.ignitor.utility import kind, parallel, reflect\r\n\r\n\r\nclass Scheduler(object):\r\n \r\n _lock = parallel.create_rlock(process=False)\r\n \r\n def __new__(cls, node): \r\n with cls._lock:\r\n if not hasattr(cls, '_instances'):\r\n cls._instances = {}\r\n if not node in cls._instances:\r\n orig = super(Scheduler, cls) \r\n instance = orig.__new__(cls)\r\n instance._node = node\r\n instance._periodic_callback = None\r\n cls._instances[node] = instance \r\n return cls._instances[node]\r\n \r\n def start(self, interval, io_loop=None):\r\n if self.is_running():\r\n raise SchedRunningError()\r\n func = reflect.wrap_func(self.run_once, Model.NULL_USER_ID)\r\n self._periodic_callback = PeriodicCallback(func, interval * 1000) \r\n self._periodic_callback.start()\r\n if io_loop is None:\r\n io_loop = IOLoop.current()\r\n logger.info(\"Scheduler %s is running per %d seconds.\" % (self._node, interval))\r\n io_loop.start()\r\n \r\n def stop(self):\r\n if self.is_running():\r\n self._periodic_callback.stop()\r\n self._periodic_callback = None\r\n else:\r\n self._periodic_callback = None\r\n \r\n def is_running(self):\r\n state = False\r\n if self._periodic_callback is None:\r\n state = False\r\n else:\r\n state = self._periodic_callback.is_running()\r\n return state\r\n \r\n def run_all(self, caller, broken=None):\r\n query = CronJob.all() \r\n query.filter(\"job_node =\", self._node) \r\n query.filter(\"next_run_time <=\", kind.utcnow())\r\n if broken is not None:\r\n query.filter(\"broken =\", broken)\r\n cronjobs = query.fetch()\r\n for cronjob in cronjobs:\r\n cronjob.run_once(caller)\r\n \r\n def run_once(self, job_id, caller):\r\n cronjob = CronJob.get_by_key(job_id)\r\n cronjob.run_once(caller)\r\n\r\ndef create_cronjob(job_name, job_desc, job_runner, job_node, job_group=None, run_params=None, broken=False, logged=True, singleton=True, fire_year='*', fire_month=1, fire_day=1, fire_week='*', fire_dayofweek='*', fire_hour=0, fire_minute=0, fire_second=0, start_time=None, end_time=None, timezone=kind.tz_utc()):\r\n cronjob = CronJob(job_name=job_name, job_runner=job_runner)\r\n cronjob.job_desc = job_desc\r\n cronjob.job_node = job_node\r\n cronjob.job_group = job_group\r\n cronjob.run_params = run_params\r\n cronjob.broken = broken\r\n cronjob.logged = logged\r\n cronjob.singleton = singleton\r\n cronjob.fire_year = fire_year\r\n cronjob.fire_month = fire_month\r\n cronjob.fire_day = fire_day\r\n cronjob.fire_week = fire_week\r\n cronjob.fire_dayofweek = fire_dayofweek\r\n cronjob.fire_hour = fire_hour\r\n cronjob.fire_minute = fire_minute\r\n cronjob.fire_second = fire_second\r\n cronjob.start_time = start_time\r\n cronjob.end_time = end_time\r\n cronjob.timezone = timezone\r\n cronjob.previous_run_time = None\r\n if not broken:\r\n cronjob.next_run_time = cronjob.get_next_fire_time(None, kind.utcnow())\r\n else:\r\n cronjob.next_run_time = None\r\n cronjob.create(context.get_user_id())\r\n return cronjob\r\n\r\ndef get_cronjob(job_id=None, job_name=None):\r\n cronjob = None\r\n if job_id is not None:\r\n cronjob = CronJob.get_by_key(job_id) \r\n if cronjob is None and job_name is not None:\r\n cronjob = CronJob.get_by_name(job_name)\r\n return cronjob\r\n \r\ndef break_cronjob(job_id, broken):\r\n cronjob = CronJob.get_by_key(job_id)\r\n cronjob.broken = broken\r\n cronjob = cronjob.update(context.get_user_id())\r\n return cronjob\r\n \r\ndef delete_cronjob(job_id):\r\n cronjob = CronJob.get_by_key(job_id)\r\n return cronjob.delete(context.get_user_id())\r\n\r\ndef fetch_cronjobs(job_name=None, job_node=None, job_group=None, broken=None):\r\n query = CronJob.all()\r\n if job_name is not None:\r\n query.filter(\"job_name like\", '%%%s%%' % job_name)\r\n if job_node is not None:\r\n query.filter(\"job_node =\", job_node)\r\n if job_group is not None:\r\n query.filter(\"job_group =\", job_group)\r\n if broken is not None:\r\n query.filter(\"broken =\", broken)\r\n return query.fetch()\r\n\r\ndef start(node, interval=1, io_loop=None):\r\n node = platform.node() if node is None else node\r\n scheduler = Scheduler(node)\r\n scheduler.start(interval, io_loop=io_loop)\r\n\r\n\r\n\r\n", "sub_path": "ssguan/ignitor/sched/scheduler.py", "file_name": "scheduler.py", "file_ext": "py", "file_size_in_byte": 5494, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "ssguan.ignitor.utility.parallel.create_rlock", "line_number": 31, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.parallel", "line_number": 31, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.error.SchedRunningError", "line_number": 47, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.reflect.wrap_func", "line_number": 48, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.reflect", "line_number": 48, "usage_type": "name"}, {"api_name": "ssguan.ignitor.orm.model.Model.NULL_USER_ID", "line_number": 48, "usage_type": "attribute"}, {"api_name": "ssguan.ignitor.orm.model.Model", "line_number": 48, "usage_type": "name"}, {"api_name": "tornado.ioloop.PeriodicCallback", "line_number": 49, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop.current", "line_number": 52, "usage_type": "call"}, {"api_name": "tornado.ioloop.IOLoop", "line_number": 52, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.logger.info", "line_number": 53, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.logger", "line_number": 53, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.all", "line_number": 72, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 72, "usage_type": "name"}, {"api_name": "ssguan.ignitor.utility.kind.utcnow", "line_number": 74, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.kind", "line_number": 74, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.get_by_key", "line_number": 82, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 82, "usage_type": "name"}, {"api_name": "ssguan.ignitor.utility.kind.tz_utc", "line_number": 85, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.kind", "line_number": 85, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 86, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.kind.utcnow", "line_number": 107, "usage_type": "call"}, {"api_name": "ssguan.ignitor.utility.kind", "line_number": 107, "usage_type": "name"}, {"api_name": "ssguan.ignitor.base.context.get_user_id", "line_number": 110, "usage_type": "call"}, {"api_name": "ssguan.ignitor.base.context", "line_number": 110, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.get_by_key", "line_number": 116, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 116, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.get_by_name", "line_number": 118, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 118, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.get_by_key", "line_number": 122, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 122, "usage_type": "name"}, {"api_name": "ssguan.ignitor.base.context.get_user_id", "line_number": 124, "usage_type": "call"}, {"api_name": "ssguan.ignitor.base.context", "line_number": 124, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.get_by_key", "line_number": 128, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 128, "usage_type": "name"}, {"api_name": "ssguan.ignitor.base.context.get_user_id", "line_number": 129, "usage_type": "call"}, {"api_name": "ssguan.ignitor.base.context", "line_number": 129, "usage_type": "name"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob.all", "line_number": 132, "usage_type": "call"}, {"api_name": "ssguan.ignitor.sched.cronjob.CronJob", "line_number": 132, "usage_type": "name"}, {"api_name": "platform.node", "line_number": 144, "usage_type": "call"}]}
+{"seq_id": "121197133", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nfrom dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative\nfrom pymavlink import mavutil # Needed for command message definitions\nimport time\nimport math\n\nimport argparse\n\nparser = argparse.ArgumentParser(description = 'Control Copter and send commands in guided mode')\nparser.add_argument('--connect',\n help = 'Vehicle connection target string. If not specified, SITL will automatically start and be used') \nargs = parser.parse_args()\n\nconnection_string = args.connect\nsitl = None\n\n#Start SITL if no connection string specified\nif not connection_string:\n import dronekit_sitl\n sitl = dronekit_sitl.start_default()\n connection_string = sitl.connection_string()\n\n# Connect to the vehicle\nprint('Connecting to vehicle on: %s' % connection_string)\nvehicle = connect(connection_string, wait_ready = True)\n\n\"\"\"\nArms vehicle and takes off to specified altitude\n\"\"\"\ndef arm_and_takeoff(aTargetAltitude):\n print(\"Basic pre-arm checks\")\n # Ensures user does not try to arm until autopilot is ready\n while not vehicle.is_armable:\n print(\"Waiting for vehicle to initialize...\")\n time.sleep(1)\n \n print(\"Arming motors\")\n # Copter should arm in guided mode\n vehicle.mode = VehicleMode(\"GUIDED\")\n vehicle.armed = True\n\n while not vehicle.armed:\n print(\"Waiting for vehicle to arm...\")\n time.sleep(1)\n\n print(\"Vehicle is taking off!\")\n # Take off to specified altitude\n vehicle.simple_takeoff(aTargetAltitude)\n\n \"\"\"\n Wait until vehicle has reached specified altitude before processing next command\n Any command directly after Vehicle.simple_takeoff will execute immediately \n \"\"\"\n while True:\n print(\"Altitude: \", vehicle.location.global_relative_frame.alt)\n if vehicle.location.global_relative_frame.alt >= aTargetAltitude * 0.95:\n print(\"Reached target altitude\")\n break\n time.sleep(1)\n \n# Arm and take off to altitude of 5 meters\narm_and_takeoff(5)\n\n\"\"\"\nReturns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the \nspecified `original_location`. The returned LocationGlobal has the same `alt` value\nas `original_location`.\n\nThe function is useful when you want to move the vehicle around specifying locations relative to \nthe current vehicle position.\n\nThe algorithm is relatively accurate over small distances (10m within 1km) except close to the poles.\n\"\"\"\n\ndef get_location_metres(original_location, dNorth, dEast):\n # 'Spherical' radius of earth\n earth_radius = 6378137.0\n # Coordinate offsets in radians\n dLat = dNorth/earth_radius\n dLon = dEast/(earth_radius * math.cos(math.pi * original_location.lat/180))\n\n # New position in decimal degrees\n newLat = original_location.lat + (dLat * 180/math.pi)\n newLon = original_location.lon + (dLon * 180/math.pi)\n if type(original_location) is LocationGlobal:\n targetlocation = LocationGlobal(newLat, newLon, original_location.alt)\n elif type(original_location) is LocationGlobalRelative:\n targetlocation = LocationGlobalRelative(newLat, newLon, original_location.alt)\n else:\n raise Exception(\"Invalid Location object passed\")\n\n return targetlocation\n\n\"\"\"\nReturns the ground distance in metres between two LocationGlobal objects.\n\nThis method is an approximation, and will not be accurate over large distances and close to the \nearth's poles.\n\"\"\"\ndef get_distance_metres(aLocation1, aLocation2):\n dLat = aLocation2.lat - aLocation1.lat\n dLon = aLocation2.lon - aLocation1.lon\n return math.sqrt((dLat * dLat) + (dLon * dLon)) * 1.113195e5\n\n\"\"\"\nReturns the bearing between the two LocationGlobal objects passed as parameters.\nThis method is an approximation, and may not be accurate over long distances and\nclose earths poles.\n\"\"\"\ndef get_bearing(aLocation1, aLocation2):\n off_x = aLocation2.lon - aLocation1.lon\n off_y = aLocation2.lat - aLocation1.lat\n bearing = 90.00 + math.atan2(-off_y, off_x) * 57.2957795\n if bearing < 0:\n bearing += 360.00\n return bearing\n\n\"\"\"\nSend SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal.\n\"\"\"\ndef goto_position_target_global_int(aLocation):\n\n msg = vehicle.message_factory.set_position_target_global_int_encode(\n 0, # time_boot_ms (not used)\n 0, 0, # target system, target component\n mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, # frame\n 0b0000111111111000, # type_mask (only speeds enabled)\n int(aLocation.lat*1e7), # lat_int - X Position in WGS84 frame in 1e7 * meters\n int(aLocation.lon*1e7), # lon_int - Y Position in WGS84 frame in 1e7 * meters\n int(aLocation.alt), # alt - Altitude in meters in AMSL altitude, not WGS84 if absolute or relative, above terrain if GLOBAL_TERRAIN_ALT_INT\n 0, 0, 0, # X,Y,Z velocity in NED frame in m/s\n 0, 0, 0, # afx, afy, afz acceleration (not supported yet, ignored in GCS_Mavlink)\n 0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink) \n # send command to vehicle\n print(msg)\n vehicle.send_mavlink(msg)\n\n\"\"\"\nMoves the vehicle to a postiion dNorth meters North and dEast meters East\nof the current position.\nThe method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for \nthe target position. This allows it to be called with different position-setting commands.\nThis method reports the distance to target every two seconds\n\"\"\"\ndef goto(dNorth, dEast, gotoFunction = vehicle.simple_goto):\n currentLocation = vehicle.location.global_relative_frame\n targetLocation = get_location_metres(currentLocation, dNorth, dEast)\n targetDistance = get_distance_metres(currentLocation, targetLocation)\n gotoFunction(targetLocation)\n\n #Stop action if we are no longer in guided mode\n while vehicle.mode.name == \"GUIDED\":\n remainingDistance = get_distance_metres(vehicle.location.global_relative_frame, targetLocation)\n print(\"Distance to target: \", remainingDistance)\n if remainingDistance <= targetDistance*0.01:\n print(\"Target reached\")\n break\n time.sleep(2)\n\nprint(\"Fly straight line path to 30 yard line\")\nprint(\"Setting groundspeed to 5 m/s\")\nvehicle.groundspeed = 5\ngoto(27.41,0,goto_position_target_global_int)\n\nprint(\"Setting LAND mode...\")\nvehicle.mode = VehicleMode(\"LAND\")\n\nprint(\"Close vehicle object\")\nvehicle.close()\n\nif sitl is not None:\n sitl.stop()\n\nprint(\"Mission Complete\")\n\n", "sub_path": "Showcase1/DistanceTravel.py", "file_name": "DistanceTravel.py", "file_ext": "py", "file_size_in_byte": 6650, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 13, "usage_type": "call"}, {"api_name": "dronekit_sitl.start_default", "line_number": 24, "usage_type": "call"}, {"api_name": "dronekit.connect", "line_number": 29, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 39, "usage_type": "call"}, {"api_name": "dronekit.VehicleMode", "line_number": 43, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 48, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 63, "usage_type": "call"}, {"api_name": "math.cos", "line_number": 84, "usage_type": "call"}, {"api_name": "math.pi", "line_number": 84, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 87, "usage_type": "attribute"}, {"api_name": "math.pi", "line_number": 88, "usage_type": "attribute"}, {"api_name": "dronekit.LocationGlobal", "line_number": 89, "usage_type": "name"}, {"api_name": "dronekit.LocationGlobal", "line_number": 90, "usage_type": "call"}, {"api_name": "dronekit.LocationGlobalRelative", "line_number": 91, "usage_type": "name"}, {"api_name": "dronekit.LocationGlobalRelative", "line_number": 92, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 107, "usage_type": "call"}, {"api_name": "math.atan2", "line_number": 117, "usage_type": "call"}, {"api_name": "pymavlink.mavutil.mavlink", "line_number": 130, "usage_type": "attribute"}, {"api_name": "pymavlink.mavutil", "line_number": 130, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 162, "usage_type": "call"}, {"api_name": "dronekit.VehicleMode", "line_number": 170, "usage_type": "call"}]}
+{"seq_id": "70698122", "text": "import requests\nfrom bs4 import BeautifulSoup\nfrom openpyxl import load_workbook\n\n# 타겟 URL을 읽어서 HTML를 받아오고,\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}\ndata = requests.get('https://movie.naver.com/movie/sdb/rank/rmovie.nhn?sel=pnt&date=20190909', headers=headers)\n\nsoup = BeautifulSoup\n# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦\n# soup이라는 변수에 \"파싱 용이해진 html\"이 담긴 상태가 됨\n# 이제 코딩을 통해 필요한 부분을 추출하면 된다.\n\n# HTML을 BeautifulSoup이라는 라이브러리를 활용해 검색하기 용이한 상태로 만듦\nsoup = BeautifulSoup(data.text, 'html.parser')\n\n# select를 이용해서, tr들을 불러오기\nmovies = soup.select('#old_content > table > tbody > tr')\n\nmovie_table = load_workbook('prac01.xlsx')\nmovie_sheet = movie_table['prac']\n\n# movies (tr들) 의 반복문을 돌리기\nrow = 2\nnum = 1\nfor movie in movies:\n # movie 안에 a 가 있으면,\n a_tag = movie.select_one('td.title > div > a')\n if a_tag is not None:\n # a의 text를 찍어본다.\n movie_title = a_tag.text\n point = movie.select('td.point')[0].text\n\n movie_sheet.cell(row=row, column=1, value=num)\n movie_sheet.cell(row=row, column=2, value=movie_title)\n movie_sheet.cell(row=row, column=3, value=point)\n row += 1\n num += 1\n\n movie_table.save('movie.xlsx')\n", "sub_path": "movieScrapToExel.py", "file_name": "movieScrapToExel.py", "file_ext": "py", "file_size_in_byte": 1552, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "requests.get", "line_number": 8, "usage_type": "call"}, {"api_name": "bs4.BeautifulSoup", "line_number": 10, "usage_type": "name"}, {"api_name": "bs4.BeautifulSoup", "line_number": 16, "usage_type": "call"}, {"api_name": "openpyxl.load_workbook", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "321532467", "text": "import os\nimport sys\nimport re\nimport json\nimport urllib.request\n\n\ndef getTrend():\n client_id = \"st9xvPkKYLgT7c3bdZVa\"\n client_secret = \"4NTYUN_MVb\"\n encText = urllib.parse.quote(\"자취생 간단 요리 레시피\")\n url = \"https://openapi.naver.com/v1/search/blog?query=\" + encText # json 결과\n request = urllib.request.Request(url)\n request.add_header(\"X-Naver-Client-Id\", client_id)\n request.add_header(\"X-Naver-Client-Secret\", client_secret)\n response = urllib.request.urlopen(request)\n rescode = response.getcode()\n if(rescode == 200):\n response_body = response.read().decode('utf-8')\n dict = json.loads(response_body)\n dict = dict['items']\n \n trend=[]\n for i in dict:\n tmp={}\n title_tmp = re.sub('(<([^>]+)>)', '', i['title'])\n title_tmp = re.sub('["lg;]', '', title_tmp)\n tmp['title']=title_tmp\n tmp['link']=i['link']\n trend.append(tmp)\n return trend\n else:\n return rescode\n", "sub_path": "exec/analysis/service/TrendingService.py", "file_name": "TrendingService.py", "file_ext": "py", "file_size_in_byte": 1043, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "urllib.request.parse.quote", "line_number": 11, "usage_type": "call"}, {"api_name": "urllib.request.parse", "line_number": 11, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 11, "usage_type": "name"}, {"api_name": "urllib.request.request.Request", "line_number": 13, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 13, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 13, "usage_type": "name"}, {"api_name": "urllib.request.request.urlopen", "line_number": 16, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 16, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 16, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 20, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 26, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 27, "usage_type": "call"}]}
+{"seq_id": "620221238", "text": "'''\nCreated on Feb 21, 2018\n\n@author: Anthony Bell\n'''\nimport os\nimport datetime\nimport socket\nfrom sqlalchemy.ext.declarative.api import declarative_base\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import sessionmaker\n\nfrom model.Device import Device\nfrom model.MinuteData import MinuteData\nfrom model.HourData import HourData\nfrom model.DailyData import DailyData\nfrom model.Notification import Notification\nfrom model.Emailer import Emailer\n\nclass Database(object):\n '''\n The Database class is a convenience class for\n interacting with the sqlite3 database.\n This class acts primarily as a wrapper for SQLAlchemy with the addition\n of some application specific helper functions.\n '''\n\n\n def __init__(self, params=None):\n '''\n Constructor\n Establishes session to sqlite database\n\n Args:\n None\n\n Returns:\n Database object\n '''\n Base = declarative_base()\n basedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')\n self.engine = create_engine('sqlite:///'+os.path.join(basedir, 'TrickleTerminators.db'))\n self.session = sessionmaker(expire_on_commit=False, autoflush=False)\n self.session.configure(bind=self.engine)\n Base.metadata.create_all(self.engine)\n self.s = self.session()\n self.emailer = Emailer(recipients=['anthony.bell.us@ieee.org'])\n\n #Getter functions\n def get_devices(self):\n '''\n Returns all devices in the database\n\n Args:\n None\n\n Returns:\n None\n '''\n return self.s.query(Device)\n\n def get_hour_data(self):\n '''\n Gets all the hourly data from the database\n\n Args:\n None\n\n Returns:\n list of HourData objects\n '''\n return self.s.query(HourData)\n\n def get_current_hour(self, device):\n '''\n Gets the flow data for the current hour for the specified device\n\n Args:\n Device (str): name of the device to be queried\n\n Returns:\n HourData table entry for the current flow data of the device\n '''\n query = self.s.query(HourData).filter(HourData.device == device).order_by(desc(HourData.timestamp)).limit(1).all()\n return query\n\n def get_current_day(self, device):\n '''\n Gets the flow data for the current day for the specified device\n\n Args:\n Device (str): name of the device to be queried\n\n Returns:\n DailyData table entry for the current flow data of the device\n '''\n query = self.s.query(DailyData).filter(DailyData.device == device).order_by(desc(DailyData.timestamp)).limit(1).all()\n return query\n\n def get_daily_data(self):\n '''\n Gets all the daily data from the database\n\n Args:\n None\n\n Returns:\n list of DailyData objects\n '''\n return self.s.query(HourData)\n\n def get_minute_data(self):\n '''\n Gets all the minute by minute data from the database\n\n Args:\n None\n\n Returns:\n list of MinuteData objects\n '''\n return self.s.query(MinuteData)\n\n def get_device(self, device):\n '''\n Gets the device specified by the given name\n\n Args:\n device (str): the name of the device that is being requested\n\n Returns:\n Device object\n '''\n _device = self.s.query(Device).filter(Device.device == device).first()\n return _device\n\n def get_notifications(self):\n return self.s.query(Notification)\n\n\n #Setter functions\n def set_next_id(self):\n '''\n Sets the stored_id values so that database collisions do not occur, call on startup\n\n Args:\n None\n\n Returns:\n None\n '''\n try:\n DailyData.stored_id = self.s.query(DailyData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n HourData.stored_id = self.s.query(HourData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n MinuteData.stored_id = self.s.query(MinuteData).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n Device.stored_id = self.s.query(Device).order_by('id').all()[-1].id + 1\n except:\n pass\n try:\n Notification.stored_id = self.s.query(Notification).order_by('id').all()[-1].id + 1\n except:\n pass\n\n\n #Helper functions\n def update_hourly_data(self, device):\n '''\n Updates the database with the current flow for the past hour for a given device\n\n Args:\n Device (str): name of the device to be updated\n\n Returns:\n hourly_flow (int): total flow for the previous hour\n '''\n past_hour = datetime.datetime.now() - datetime.timedelta(hours=1)\n minute_entries = self.s.query(MinuteData).filter(MinuteData.device == device).filter(MinuteData.minute > past_hour)\n hourly_flow = 0\n for entry in minute_entries:\n hourly_flow += entry.flow\n self.s.add(HourData(device, hourly_flow))\n _device = self.s.query(Device).filter(Device.device == device).first()\n if _device.max_flow <= hourly_flow:\n pass #Shut off valve and update db\n self.s.commit()\n return hourly_flow\n\n def update_daily_data(self, device):\n '''\n Updates the database with the current flow for the past 24 hours for a given device\n\n Args:\n Device (str): name of the device to be updated\n\n Returns:\n None\n '''\n past_day = datetime.datetime.now() - datetime.timedelta(days=1)\n minute_entries = self.s.query(MinuteData).filter(MinuteData.device == device).filter(MinuteData.minute > past_day)\n daily_flow = 0\n for entry in minute_entries:\n daily_flow += entry.flow\n self.s.add(DailyData(device, daily_flow))\n self.s.commit()\n\n\n def add_minute_data(self, device, flow=0):\n '''\n Adds minute flow data to the database and updates hourly and daily data\n\n Args:\n device (str): device for which data is being logged\n flow (int): Flow data for the device (default = 0)\n\n Returns:\n hourly_flow (int): flow for the last hour\n '''\n self.s.add(MinuteData(device, flow))\n hourly_flow = self.update_hourly_data(device)\n self.update_daily_data(device)\n self.s.commit()\n return hourly_flow\n\n def add_notification(self, device, message):\n '''\n Adds a notification to the database\n\n Args:\n device (str): device for which notification is being logged\n message (str): notification message\n\n Returns:\n None\n '''\n if message == \"burst\":\n _message = \"There has been a burst at \" + device\n elif message == \"flow\":\n _message = device + \" has exceeded the maximum flow allowed\"\n elif message == \"remove\":\n _message = device + \" has been removed\"\n elif message == \"add\":\n _message = device + \" has been added\"\n self.s.add(Notification(device, _message))\n self.s.commit()\n self.emailer.send_message(template=message, message=_message)\n\n def add_device(self, name, ip=\"0.0.0.0\"):\n '''\n Adds a device to the database\n\n Args:\n name (str): the name of the device being added\n ip (str): the ip address of the device being added\n\n Returns:\n None\n '''\n _exists = self.s.query(Device).filter(Device.device == name).all()\n if _exists:\n return None\n self.s.rollback()\n new_device = Device(name=name,ip=ip)\n self.s.add(new_device)\n self.s.commit()\n self.add_notification(name, \"add\")\n\n def remove_device(self, name):\n '''\n Removes a device from the database\n\n Args:\n name (str): the name of the device being removed\n\n Returns:\n None\n '''\n query = self.s.query(Device).fliter(Device.device == name)\n query.delete()\n s.commit()\n\n def update_device(self, device, flow=None, status=None):\n '''\n Updates the flow settings for a specified device\n\n Args:\n device (str): the name of the device being updated\n flow (int): the maximum flow value in L/Hr\n status (str): the status of the device (\"on\" or \"off\")\n\n Returns:\n None\n '''\n _device = self.s.query(Device).filter(Device.device == device).first()\n if flow is not None:\n _device.max_flow = flow\n self.s.commit()\n if status is not None:\n _device.status = status\n self.s.commit()\n\n def close(self):\n '''\n Closes the database\n\n Args:\n None\n\n Returns:\n None\n '''\n self.s.close()\n", "sub_path": "model/Database.py", "file_name": "Database.py", "file_ext": "py", "file_size_in_byte": 9168, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "sqlalchemy.ext.declarative.api.declarative_base", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 41, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "sqlalchemy.orm.sessionmaker", "line_number": 43, "usage_type": "call"}, {"api_name": "model.Emailer.Emailer", "line_number": 47, "usage_type": "call"}, {"api_name": "model.Device.Device", "line_number": 60, "usage_type": "argument"}, {"api_name": "model.HourData.HourData", "line_number": 72, "usage_type": "argument"}, {"api_name": "model.HourData.HourData", "line_number": 84, "usage_type": "argument"}, {"api_name": "model.HourData.HourData.device", "line_number": 84, "usage_type": "attribute"}, {"api_name": "model.HourData.HourData.timestamp", "line_number": 84, "usage_type": "attribute"}, {"api_name": "model.DailyData.DailyData", "line_number": 97, "usage_type": "argument"}, {"api_name": "model.DailyData.DailyData.device", "line_number": 97, "usage_type": "attribute"}, {"api_name": "model.DailyData.DailyData.timestamp", "line_number": 97, "usage_type": "attribute"}, {"api_name": "model.HourData.HourData", "line_number": 110, "usage_type": "argument"}, {"api_name": "model.MinuteData.MinuteData", "line_number": 122, "usage_type": "argument"}, {"api_name": "model.Device.Device", "line_number": 134, "usage_type": "argument"}, {"api_name": "model.Device.Device.device", "line_number": 134, "usage_type": "attribute"}, {"api_name": "model.Notification.Notification", "line_number": 138, "usage_type": "argument"}, {"api_name": "model.DailyData.DailyData.stored_id", "line_number": 153, "usage_type": "attribute"}, {"api_name": "model.DailyData.DailyData", "line_number": 153, "usage_type": "name"}, {"api_name": "model.HourData.HourData.stored_id", "line_number": 157, "usage_type": "attribute"}, {"api_name": "model.HourData.HourData", "line_number": 157, "usage_type": "name"}, {"api_name": "model.MinuteData.MinuteData.stored_id", "line_number": 161, "usage_type": "attribute"}, {"api_name": "model.MinuteData.MinuteData", "line_number": 161, "usage_type": "name"}, {"api_name": "model.Device.Device.stored_id", "line_number": 165, "usage_type": "attribute"}, {"api_name": "model.Device.Device", "line_number": 165, "usage_type": "name"}, {"api_name": "model.Notification.Notification.stored_id", "line_number": 169, "usage_type": "attribute"}, {"api_name": "model.Notification.Notification", "line_number": 169, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 185, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 185, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 185, "usage_type": "call"}, {"api_name": "model.MinuteData.MinuteData", "line_number": 186, "usage_type": "argument"}, {"api_name": "model.MinuteData.MinuteData.device", "line_number": 186, "usage_type": "attribute"}, {"api_name": "model.MinuteData.MinuteData.minute", "line_number": 186, "usage_type": "attribute"}, {"api_name": "model.HourData.HourData", "line_number": 190, "usage_type": "call"}, {"api_name": "model.Device.Device", "line_number": 191, "usage_type": "argument"}, {"api_name": "model.Device.Device.device", "line_number": 191, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 207, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 207, "usage_type": "attribute"}, {"api_name": "datetime.timedelta", "line_number": 207, "usage_type": "call"}, {"api_name": "model.MinuteData.MinuteData", "line_number": 208, "usage_type": "argument"}, {"api_name": "model.MinuteData.MinuteData.device", "line_number": 208, "usage_type": "attribute"}, {"api_name": "model.MinuteData.MinuteData.minute", "line_number": 208, "usage_type": "attribute"}, {"api_name": "model.DailyData.DailyData", "line_number": 212, "usage_type": "call"}, {"api_name": "model.MinuteData.MinuteData", "line_number": 227, "usage_type": "call"}, {"api_name": "model.Notification.Notification", "line_number": 252, "usage_type": "call"}, {"api_name": "model.Device.Device", "line_number": 267, "usage_type": "argument"}, {"api_name": "model.Device.Device.device", "line_number": 267, "usage_type": "attribute"}, {"api_name": "model.Device.Device", "line_number": 271, "usage_type": "call"}, {"api_name": "model.Device.Device", "line_number": 286, "usage_type": "argument"}, {"api_name": "model.Device.Device.device", "line_number": 286, "usage_type": "attribute"}, {"api_name": "model.Device.Device", "line_number": 302, "usage_type": "argument"}, {"api_name": "model.Device.Device.device", "line_number": 302, "usage_type": "attribute"}]}
+{"seq_id": "178133246", "text": "import requests\n\nfrom .globals import bitcoin, ESPLORA_URL\n\n\ndef get_fee(tx):\n # multiply stuff by 100000000 because bitcoind returns values in btc\n inputsum = sum(\n [\n int(\n bitcoin.getrawtransaction(inp[\"txid\"], True)[\"vout\"][inp[\"vout\"]][\n \"value\"\n ]\n * 100000000\n )\n for inp in tx[\"vin\"]\n ]\n )\n outputsum = sum([int(out[\"value\"] * 100000000) for out in tx[\"vout\"]])\n\n return inputsum - outputsum\n\n\ndef get_outspends(txid):\n return call_esplora(f\"/tx/{txid}/outspends\")\n\n\ndef call_esplora(path):\n try:\n r = requests.get(ESPLORA_URL + path)\n if r.ok:\n return r.json()\n except requests.exceptions.ConnectionError:\n pass\n\n r = requests.get(\"https://mempool.space/electrs\" + path)\n r.raise_for_status()\n return r.json()\n", "sub_path": "getdata/utils.py", "file_name": "utils.py", "file_ext": "py", "file_size_in_byte": 895, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "globals.bitcoin.getrawtransaction", "line_number": 11, "usage_type": "call"}, {"api_name": "globals.bitcoin", "line_number": 11, "usage_type": "name"}, {"api_name": "requests.get", "line_number": 30, "usage_type": "call"}, {"api_name": "globals.ESPLORA_URL", "line_number": 30, "usage_type": "name"}, {"api_name": "requests.exceptions", "line_number": 33, "usage_type": "attribute"}, {"api_name": "requests.get", "line_number": 36, "usage_type": "call"}]}
+{"seq_id": "36170269", "text": "\"\"\"\nExports the Simulation class.\n\"\"\"\n\nfrom os import mkdir, chdir, path\nfrom subprocess import run\nfrom datetime import datetime\n\n\nclass Simulation:\n\t\"\"\"\n\tRun a vapour hydrated brush simulation in a standard manner. Wraps LAMMPS.\n\t\"\"\"\n\n\tdef __init__(self, command: str, dry_run: bool = False, verbose: bool = False, prefix: str = \"\"):\n\t\t\"\"\"\n\t\t:param str command: Command to run to call LAMMPS.\n\t\t:param bool dry_run: Doesn't do anything productive if true.\n\t\t:param str prefix: String to prepend to all print() output.\n\t\t\"\"\"\n\t\tself.command = command\n\t\tself.dry_run = dry_run\n\t\tself.verbose = verbose\n\t\tself.prefix = prefix\n\n\tdef _run_with_vars(self, input_filename: str, log_filename: str, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun a LAMMPS simulation in a subprocess with variables.\n\t\t:param str input_filename: Filename of the LAMMPS input file\n\t\t:param str log_filename: Filename of the log file to write to\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\twith open(log_filename, 'w') as f:\n\t\t\tcmd = self.command + ' -in {} '.format(input_filename) + ''.join(['-var {} {} '.format(k, v) for k, v in vars.items()])\n\t\t\tif self.verbose:\n\t\t\t\tprint(cmd)\n\t\t\trun(cmd, universal_newlines=True, stdout=f, shell=True)\n\n\tdef _run_in_subdir(self, subdir: str, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun a simulation in a subdirectory.\n\t\t:param str subdir: Subdirectory to run the simulation in\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\t# Create a subdirectory for every simulation. Skip simulation entirely if dir already exists\n\t\tif not path.isdir(subdir):\n\t\t\tprint(\"{} {}: Simulating {}...\".format(self.prefix, datetime.now(), subdir))\n\t\t\tif not self.dry_run:\n\t\t\t\tmkdir(subdir)\n\t\t\t\tchdir(subdir)\n\t\t\t\tself._run_with_vars('../gcmc.in', 'gcmc.log', vars)\n\t\t\t\tchdir('../')\n\t\t\t\tprint(\"{} {}: Finished {}.\".format(self.prefix, datetime.now(), subdir))\n\t\telse:\n\t\t\tprint(\"{} {}: Found existing subdir {}. Skipping.\".format(self.prefix, datetime.now(), subdir))\n\n\tdef run_gcmc(self, static_vars: dict = {}, dyn_vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tSimulate a system with the given parameters.\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\tsubdir = 'grid' + ''.join(['_{}{:.4f}'.format(k, float(v)) for k, v in dyn_vars.items()])\n\n\t\t# Combine vars dicts\n\t\tstatic_vars.update(dyn_vars)\n\n\t\tself._run_in_subdir(subdir, static_vars)\n\n\tdef run_equi(self, vars: dict = {}) -> None:\n\t\t\"\"\"\n\t\tRun equilibration.\n\t\t:param dict vars: Dictionary describing LAMMPS equal-style variables to set\n\t\t\"\"\"\n\t\tprint(\"{}: Equilibrating...\".format(datetime.now()))\n\t\tif not self.dry_run:\n\t\t\tself._run_with_vars('equi.in', 'equi.log', vars)\n\t\t\tprint(\"{}: Finished equilibration.\".format(datetime.now()))\n", "sub_path": "Simulation.py", "file_name": "Simulation.py", "file_ext": "py", "file_size_in_byte": 2789, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "subprocess.run", "line_number": 37, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 47, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 47, "usage_type": "name"}, {"api_name": "os.mkdir", "line_number": 49, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 50, "usage_type": "call"}, {"api_name": "os.chdir", "line_number": 52, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 53, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 53, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 55, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 55, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 74, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 74, "usage_type": "name"}, {"api_name": "datetime.datetime.now", "line_number": 77, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 77, "usage_type": "name"}]}
+{"seq_id": "153239998", "text": "#!/usr/bin/env python3\n\nimport sys\nimport os\nimport argparse\nimport subprocess\nimport readline\nimport pandas as pd\nimport numpy as np\nfrom plio.io.io_bae import read_gpf, save_gpf\n\n\n## Create an argument parser\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description = \"\"\"Transform points in a Socet Set Ground Point File (GPF).\nThe transformed latitude, longitude, and height values from the Tie Points are then written to a new GPF with their sigmas set equal to 1 and the \"known\" flag \nchanged from \"1\" (Tie Point) to \"3\" (XYZ Control). Non-Tie Points from the original GPF are written to the new GPF with their \"known\" flags changed to \"1.\" \nTie Points from the original GPF that were not active (\"stat\" = 0) are copied \"as-is\" into the new GPF. The output GPF preserves the order of the ground points from the original GPF.\n\nIf it is desired to update all active points in the input GPF, use the '--all-points' flag. The modified points will still have their \"known\" flag set to \"3\" (XYZ Control) in the output GPF.\n\nThe script requires the \"plio\" Python library (https://github.com/USGS-Astrogeology/plio) in order to read/write GPFs. \nThe Ames Stereo Pipeline program pc_align must be available in the user's path or somewhere else where Python can find it. \nMore information about the Ames Stereo Pipeline is available on the project's Git repository: https://github.com/NeoGeographyToolkit/StereoPipeline\"\"\")\n parser.add_argument(\"socet_gpf\",\n help = \"The name of the Socet Ground Point File to transform.\")\n parser.add_argument(\"transform_matrix\",\n help = \"\"\"Name of a pc_align-compatible transformation matrix to apply to the input GPF.\"\"\")\n parser.add_argument(\"tfm_socet_gpf\",\n help = \"\"\"Name to use for the output (transformed) ground point file. Must include \".gpf\" extension.\"\"\")\n parser.add_argument(\"--all-points\",\n action='store_true',\n help = \"This flag will force updating of all active (stat = 1) points in the input GPF, not just tie points.\")\n refshape = parser.add_mutually_exclusive_group(required=True)\n refshape.add_argument(\"--datum\",\n nargs=1,\n choices=['D_MARS', 'D_MOON', 'MOLA', 'NAD27', 'NAD83', 'WGS72', 'WGS_1984'],\n help = \"\"\"Use this datum for heights in the input GPF.\"\"\")\n refshape.add_argument(\"--radii\",\n nargs=2,\n metavar=('semi-major-axis','semi-minor-axis'),\n type=float,\n help=\"\"\"Semi-major and semi-minor axes, expressed in meters, that define the ellipsoid that heights in the input GPF are referenced to.\"\"\")\n args = parser.parse_args()\n return args\n\n\ndef run_pc_align(args):\n \"\"\"\n Use subprocess to call the external program, pc_align. Relies on\n pc_align to decide if arguments are valid or not.\n Pipe STDERR to STDOUT.\n\n\n Parameters\n ----------\n args : list\n list of arguments to be passed to pc_align\n\n \"\"\"\n \n align_args = [\"pc_align\"]\n align_args.extend(args)\n run_align = subprocess.run(align_args,check=True,stderr=subprocess.STDOUT,encoding='utf-8')\n\n return run_align\n\ndef update_gpf(gpf_df,tp_df,all_points,outname):\n \"\"\"\n Update a GPF DataFrame with new lat/long/height values from another DataFrame,\n Change point types based on user input, and set sigmas of updated points == 1 meter.\n\n\n Parameters\n ----------\n gpf_df : pd.DataFrame\n Pandas DataFrame of a Socet GPF file. Format obtained from read_gpf(),\n and subsequently indexed on point_id field.\n\n tp_df : pd.DataFrame\n Pandas DataFrame of a Socet GPF file. Format obtained from read_gpf(),\n and subsequently indexed on point_id field. Should be (at least) a \n subset of gpf_df\n\n all_points : boolean\n If True, update all active points in gpf_df, regardless of point type.\n If False, update only active tiepoints in gpf_df, and then change \n active non-tiepoints to tiepoints.\n\n outname: str\n Path to the output GPF\n\n Returns\n -------\n int : success value\n 0 = success, 1 = errors\n \n\n \"\"\"\n\n print(\"Updating GPF data frame with Transformed lat/long/z values from pc_align\")\n gpf_df.update(tp_df)\n\n print(\"Updating ground point types in output GPF\")\n\n ## Build boolean masks of gpf_df to enable selective updating of point types\n ## transformed tie point mask\n if all_points is True:\n tfm_tp_mask = (gpf_df['stat'] == 1)\n else:\n ## non-tie point mask\n non_tp_mask = ((gpf_df['stat'] == 1) & (gpf_df['known'] > 0))\n tfm_tp_mask = ((gpf_df['stat'] == 1) & (gpf_df['known'] == 0))\n ## Change non-Tie Points to Tie Point\n print(\"Changing active non-Tiepoints to Tiepoints\")\n gpf_df.loc[non_tp_mask, 'known'] = 0\n\n ## Change transformed Tie Points to XYZ Control, sigmas = 1.0, residuals = 0.0\n print(\"Changing transformed points to XYZ Control with sigmas = 1 and residuals = 0\")\n gpf_df.loc[tfm_tp_mask, 'known'] = 3\n gpf_df.loc[tfm_tp_mask, 'sig0':'sig2'] = 1.0\n gpf_df.loc[tfm_tp_mask, 'res0':'res2'] = 0.0\n\n ## Convert the 'stat' and 'known' columns to unsigned integers\n gpf_df.known = pd.to_numeric(gpf_df['known'], downcast = 'unsigned')\n gpf_df.stat = pd.to_numeric(gpf_df['stat'], downcast = 'unsigned')\n\n print(\"Writing transformed GPF to file: \" + outname)\n save_gpf(gpf_df, outname)\n\n return\n\n\ndef main(socet_gpf,tfm_socet_gpf,all_points,transform_matrix,datum,radii):\n \n if tfm_socet_gpf[-4:] != \".gpf\":\n print(\"\"\"USER ERROR: Output file name must include \".gpf\" extension\"\"\")\n sys.exit(1)\n\n ## Read in the Socet ground point file using plio's read_gpf()\n gpf_df = read_gpf(socet_gpf)\n # Set the index of the GPF dataframe to be the point_id column\n gpf_df.set_index('point_id', drop=False, inplace=True)\n\n ## If user passed \"--all-points\" option, copy *all active* points to new data frame\n ## Otherwise, copy active tie points (known == 0) only\n ## Note that DataFrame is named \"tp_df\" regardless of whether it includes only tiepoints or not\n if all_points:\n tp_df = gpf_df[(gpf_df.stat == 1)].copy()\n else:\n tp_df = gpf_df[(gpf_df.known == 0) & (gpf_df.stat == 1)].copy()\n\n tp_df.lat_Y_North = np.degrees(tp_df.lat_Y_North)\n tp_df.long_X_East = ((360 + np.degrees(tp_df.long_X_East)) % 360)\n \n ## Write out CSV (compatible with pc_align) containing lat/long/height of points to be updated\n socet_gpf_csv = ((os.path.splitext(socet_gpf)[0]) + '.csv')\n tp_df.to_csv(path_or_buf=socet_gpf_csv,\n header=False,\n index=False,\n columns=['lat_Y_North','long_X_East','ht'])\n\n gpf_align_prefix = os.path.splitext(tfm_socet_gpf)[0]\n\n ## Build arguments list and apply transformation to selected points from GPF using pc_align\n \n ## Set num-iterations = 0 and turn off max-displacement (-1) because only going to apply existing transform\n apply_tfm_args = [\"--initial-transform\",transform_matrix,\n \"--num-iterations\",\"0\",\n \"--max-displacement\",\"-1\",\n \"--save-transformed-source-points\",\n \"-o\", gpf_align_prefix ]\n ## Extend the list of arguments for pc_align to include the datum or radii as necessary\n if datum is not None:\n apply_tfm_args.extend([\"--datum\", str(datum[0])])\n elif radii is not None:\n apply_tfm_args.extend([\"--semi-major-axis\", str(radii[0]), \"--semi-minor-axis\", str(radii[1])])\n\n ## Extend the list to place point clouds at the end of the list of arguments for pc_align\n ## Note that we're specifying the same file as the reference and source clouds because pc_align requires 2 files as input,\n ## even if we're only applying a transform and not iterating\n apply_tfm_args.extend([socet_gpf_csv,socet_gpf_csv])\n\n print(apply_tfm_args)\n\n\n ## Apply transform from previous pc_align run to tie points CSV\n try:\n print(\"Calling pc_align with 0 iterations to apply transform from previous run to Tie Points from GPF\")\n run_align = run_pc_align(apply_tfm_args)\n # print(run_align.stdout)\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit(1)\n\n\n ## mergeTransformedGPFTies\n ### Ingest the transformed tie points to a pandas data frame\n t = np.genfromtxt((gpf_align_prefix + '-trans_source.csv'),delimiter=',',\n skip_header=3,dtype='unicode')\n id_list = tp_df['point_id'].tolist()\n tfm_index = pd.Index(id_list)\n tfm_tp_df = pd.DataFrame(t, index=tfm_index, columns=['lat_Y_North','long_X_East','ht'])\n tfm_tp_df = tfm_tp_df.apply(pd.to_numeric)\n\n\n ## Update the original tiepoint DataFrame with the transformed lat/long/height values from pc_align\n tp_df.update(tfm_tp_df)\n\n # ### Convert long from 0-360 to +/-180 and convert lat/long back to radians\n tp_df.lat_Y_North = np.radians(tp_df['lat_Y_North'])\n tp_df.long_X_East = np.radians(((tp_df['long_X_East'] + 180) % 360) - 180)\n\n # Apply updates to the original GPF DataFrame, and save transformed GPF file\n update_gpf(gpf_df,tp_df,all_points,tfm_socet_gpf)\n\n ## Write list of pointIDs of the transformed tiepoints to a file\n ## Included for legacy compatibility, not actually used for anything\n tp_df.to_csv(path_or_buf=((os.path.splitext(socet_gpf)[0]) + '.tiePointIds.txt'),\n sep=' ', header=False,\n index=False,\n columns=['point_id'])\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n sys.exit(main(**vars(args)))\n", "sub_path": "SurfaceFit/gpf_transform.py", "file_name": "gpf_transform.py", "file_ext": "py", "file_size_in_byte": 10005, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 15, "usage_type": "call"}, {"api_name": "argparse.RawDescriptionHelpFormatter", "line_number": 15, "usage_type": "attribute"}, {"api_name": "subprocess.run", "line_number": 65, "usage_type": "call"}, {"api_name": "subprocess.STDOUT", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pandas.to_numeric", "line_number": 126, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 127, "usage_type": "call"}, {"api_name": "plio.io.io_bae.save_gpf", "line_number": 130, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 139, "usage_type": "call"}, {"api_name": "plio.io.io_bae.read_gpf", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 154, "usage_type": "call"}, {"api_name": "numpy.degrees", "line_number": 155, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 158, "usage_type": "call"}, {"api_name": "os.path", "line_number": 158, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 164, "usage_type": "call"}, {"api_name": "os.path", "line_number": 164, "usage_type": "attribute"}, {"api_name": "subprocess.CalledProcessError", "line_number": 193, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 195, "usage_type": "call"}, {"api_name": "numpy.genfromtxt", "line_number": 200, "usage_type": "call"}, {"api_name": "pandas.Index", "line_number": 203, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 204, "usage_type": "call"}, {"api_name": "pandas.to_numeric", "line_number": 205, "usage_type": "attribute"}, {"api_name": "numpy.radians", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.radians", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 220, "usage_type": "call"}, {"api_name": "os.path", "line_number": 220, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 228, "usage_type": "call"}]}
+{"seq_id": "478474745", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom api.models import ActivityPeriods, Members\nfrom services.command.demogenerators import RandomIdGenerator, RandomNameGenerator, RandomTimeZone, RandomDate\nimport random\n\nclass Command(BaseCommand):\n help = \"Updates Database With Dummy Data\"\n\n def __init__(self):\n self.count = 0\n\n\n def handle(self, *args, **options):\n while True:\n\n '''\n Count is used to keep track of how many rows have been inserted in the models\n '''\n if self.count == 10:\n break\n '''\n Generates random datetime stamps and saves it to ActivityPeriods Model.\n '''\n try:\n start, end = RandomDate.gen_datetime()\n activity = ActivityPeriods.objects.create(start_time=start, end_time=end)\n activity.save()\n except Exception as e:\n print(e, 'Error occurred when creating data for activity ')\n\n '''\n Generates random Id, name and timezone stamps and saves it to Members Model.\n '''\n\n try:\n ids = RandomIdGenerator.get_id()\n name = RandomNameGenerator.get_male_name()\n timezone = RandomTimeZone.get_time_zone()\n\n count = ActivityPeriods.objects.count()\n activity_obj1 = ActivityPeriods.objects.get(id=random.randint(1, count))\n activity_obj2 = ActivityPeriods.objects.get(id=random.randint(1, count))\n\n member = Members.objects.create(id=ids, real_name=name, tz=timezone)\n member.activity_periods.add(activity_obj2)\n member.activity_periods.add(activity_obj1)\n member.save()\n except Exception as e:\n print(e, \"Error happened when creating data for Members. Please try again!!!\")\n\n self.count += 1\n", "sub_path": "api/management/commands/insertdummydata.py", "file_name": "insertdummydata.py", "file_ext": "py", "file_size_in_byte": 1957, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.core.management.base.BaseCommand", "line_number": 6, "usage_type": "name"}, {"api_name": "services.command.demogenerators.RandomDate.gen_datetime", "line_number": 25, "usage_type": "call"}, {"api_name": "services.command.demogenerators.RandomDate", "line_number": 25, "usage_type": "name"}, {"api_name": "api.models.ActivityPeriods.objects.create", "line_number": 26, "usage_type": "call"}, {"api_name": "api.models.ActivityPeriods.objects", "line_number": 26, "usage_type": "attribute"}, {"api_name": "api.models.ActivityPeriods", "line_number": 26, "usage_type": "name"}, {"api_name": "services.command.demogenerators.RandomIdGenerator.get_id", "line_number": 36, "usage_type": "call"}, {"api_name": "services.command.demogenerators.RandomIdGenerator", "line_number": 36, "usage_type": "name"}, {"api_name": "services.command.demogenerators.RandomNameGenerator.get_male_name", "line_number": 37, "usage_type": "call"}, {"api_name": "services.command.demogenerators.RandomNameGenerator", "line_number": 37, "usage_type": "name"}, {"api_name": "services.command.demogenerators.RandomTimeZone.get_time_zone", "line_number": 38, "usage_type": "call"}, {"api_name": "services.command.demogenerators.RandomTimeZone", "line_number": 38, "usage_type": "name"}, {"api_name": "api.models.ActivityPeriods.objects.count", "line_number": 40, "usage_type": "call"}, {"api_name": "api.models.ActivityPeriods.objects", "line_number": 40, "usage_type": "attribute"}, {"api_name": "api.models.ActivityPeriods", "line_number": 40, "usage_type": "name"}, {"api_name": "api.models.ActivityPeriods.objects.get", "line_number": 41, "usage_type": "call"}, {"api_name": "api.models.ActivityPeriods.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "api.models.ActivityPeriods", "line_number": 41, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 41, "usage_type": "call"}, {"api_name": "api.models.ActivityPeriods.objects.get", "line_number": 42, "usage_type": "call"}, {"api_name": "api.models.ActivityPeriods.objects", "line_number": 42, "usage_type": "attribute"}, {"api_name": "api.models.ActivityPeriods", "line_number": 42, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 42, "usage_type": "call"}, {"api_name": "api.models.Members.objects.create", "line_number": 44, "usage_type": "call"}, {"api_name": "api.models.Members.objects", "line_number": 44, "usage_type": "attribute"}, {"api_name": "api.models.Members", "line_number": 44, "usage_type": "name"}]}
+{"seq_id": "614683292", "text": "from __future__ import absolute_import\nfrom __future__ import print_function\n\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nimport threading\nimport logging\n\nimport readline\n\nfrom builtins import input\n\nlogger = logging.getLogger(__name__)\n\nclass CLI(object):\n input_func = input\n\n def __init__(self, options=None, namespace=None, quit_func=None):\n cls = self.__class__\n self._cli_thread = None\n self._options = options\n if namespace is None:\n namespace = dict(__lock=threading.Lock())\n self.namespace = namespace\n if not hasattr(namespace, '__lock'):\n namespace.update(dict(__lock=threading.Lock()))\n self._lock = namespace['__lock']\n self._quit_function = quit_func\n\n def set_quit_function(self, func):\n self._quit_function = func\n\n\n def run(self):\n \"\"\" allows to run an ipython shell with the CLI's context vars \"\"\"\n namespace = self.namespace\n try:\n from IPython.terminal.embed import InteractiveShellEmbed\n use_ipython = True\n logger.debug(\"CLI using ipython\")\n except ImportError:\n use_ipython = False\n logger.debug(\"CLI using basic fallback\")\n\n if use_ipython:\n shell = InteractiveShellEmbed(user_ns=namespace)\n shell()\n\n else:\n self.mini_shell(namespace=namespace)\n\n if self._quit_function:\n try:\n self._quit_function(self)\n except TypeError:\n logger.warning(\"using obsolete quit function without argument\")\n self._quit_function()\n\n def mini_shell(self, namespace):\n \"\"\" Rather lousy Python shell for debugging.\n Just in case ipython is not installed or has the wrong version\n \"\"\"\n while True:\n cmd_line = self.input_func('-->')\n upper_stripped = cmd_line.strip().upper()\n shall_quit = (upper_stripped == 'Q' or upper_stripped == 'QUIT')\n if shall_quit:\n break\n try:\n eval(compile(cmd_line, '', 'single'), namespace) # pylint: disable=W0122,C0301\n except Exception as exc: # pylint: disable=W0703\n logger.error('ERROR: %r' % exc)\n\n print(\"END OF CLI\")\n self.write_history()\n\n def write_history(self, fname=None):\n pass\n\n def run_as_thread(self, name='cli', daemon=True):\n \"\"\" start cli as a thread\n This is needed for Qt Apps, where the GUI must be called in the main thread\n \"\"\"\n self._cli_thread = cli_thread = threading.Thread(target=self.run,\n name=name)\n cli_thread.daemon = daemon\n cli_thread.start()\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n# -----------------------------------------------------------------------------\n# End of file\n# -----------------------------------------------------------------------------\n", "sub_path": "mytb/cli.py", "file_name": "cli.py", "file_ext": "py", "file_size_in_byte": 3117, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 15, "usage_type": "call"}, {"api_name": "builtins.input", "line_number": 18, "usage_type": "name"}, {"api_name": "threading.Lock", "line_number": 25, "usage_type": "call"}, {"api_name": "threading.Lock", "line_number": 28, "usage_type": "call"}, {"api_name": "IPython.terminal.embed.InteractiveShellEmbed", "line_number": 48, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 86, "usage_type": "call"}]}
+{"seq_id": "472559879", "text": "#!/usr/bin/env python3\n\nimport pygame\nimport sys\nfrom pygame.sprite import Sprite\nfrom pygame.sprite import Group\n\nclass Ship(Sprite) : \n def __init__(self, screen) : \n super().__init__()\n self.image = pygame.image.load('img/ship.bmp')\n self.rect = self.image.get_rect()\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.reset()\n self.moving_up = False\n self.moving_down = False\n def reset(self) : \n ''' reposition the ship to the center left of the screen '''\n self.rect.centery = self.screen_rect.centery\n def blitme(self) : \n ''' draw the ship on the screen object '''\n self.screen.blit(self.image, self.rect)\n def move(self, speed_factor = 1) : \n if self.moving_up and self.rect.y > 0: \n self.rect.y -= 10 * speed_factor\n if self.moving_down and self.rect.bottom < self.screen_rect.height: \n self.rect.y += 10 * speed_factor\n\nclass Target(Sprite) : \n def __init__(self, screen) : \n super().__init__()\n self.rect = pygame.Rect(0,0,100,100)\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.moving_direction = 1\n self.reset()\n def move(self, speed_factor) : \n self.check_edge()\n self.rect.y += self.moving_direction * speed_factor\n print(speed_factor)\n def draw(self) : \n self.screen.fill((0,0,0), self.rect)\n def reset(self) : \n self.rect.centery = self.screen_rect.centery\n self.rect.right = self.screen_rect.right\n def check_edge(self) : \n if self.rect.bottom > self.screen_rect.bottom or self.rect.top < 0 : \n self.moving_direction *= -1\n\nclass Bullet(Sprite) : \n def __init__(self, ship, target, screen) : \n super().__init__()\n self.rect = pygame.Rect(0,0,10,10)\n self.ship = ship\n self.target = target\n self.screen = screen\n self.screen_rect = self.screen.get_rect()\n self.reset_tries()\n\n # define an flag to check whether the bullet is out of screen\n self.out_of_screen = False\n # define an internal flag to see whether user has fired the bullet\n self.is_fire = False\n\n def fire(self) : \n self.reset()\n self.is_fire = True\n\n def reset(self) : \n self.rect.centery = self.ship.rect.centery\n self.rect.right = self.ship.rect.right\n\n def hit(self) : \n self.is_fire = False\n # a bug fix, after a hit, remove the collison status by resetting the bullets under the ship\n self.reset()\n \n def reset_tries(self) : \n self.tries_left = 3\n\n def move(self, speed_factor) : \n if self.is_fire : \n self.rect.x += 1 * speed_factor\n self.check_edge()\n\n def check_edge(self) : \n if self.rect.left >= self.screen_rect.right : \n self.out_of_screen = True\n self.tries_left -= 1\n self.is_fire = False\n\n def draw(self) : \n if self.is_fire : \n self.screen.fill((0,0,0), self.rect)\nclass Button() : \n def __init__(self, width, height, font_size, screen) : \n self.rect = pygame.Rect(0,0,width, height)\n self.font = pygame.font.SysFont(None, font_size)\n self.screen = screen\n\n def draw(self, msg, font_color, bg_color) : \n self.img = self.font.render(msg, True, font_color, bg_color)\n self.screen.blit(self.img, self.rect)\n\n# initialize pygame\npygame.init()\n\n# get the screen\nsc = pygame.display.set_mode((500,300))\n\n# initalize the object\nship = Ship(sc)\ntarget = Target(sc)\nbullet = Bullet(ship, target, sc)\n\n# flag to see whether game is active\ngame_active = False\n\n# construct buttons\n# number of tries button\ntries_button = Button(50, 50, 40, sc )\n# position the button\ntries_button.rect.y = 0\ntries_button.rect.centerx = sc.get_rect().centerx\n# start button\nstart_button = Button(100, 50, 40, sc )\nstart_button.rect.centerx = sc.get_rect().centerx\nstart_button.rect.centery = sc.get_rect().centery\n\n# initalize speed factor\nspeed_factor = 1\nspeed_up_factor = 1.1\n\nwhile True : \n events = pygame.event.get()\n for event in events : \n if event.type == pygame.QUIT : \n sys.exit()\n elif event.type == pygame.KEYDOWN : \n if event.key == pygame.K_q : \n sys.exit()\n elif event.key == pygame.K_UP : \n ship.moving_up = True\n elif event.key == pygame.K_DOWN : \n ship.moving_down = True\n elif event.key == pygame.K_SPACE : \n # introduce the bullet to the screen\n if not bullet.is_fire and bullet.tries_left > 0 : \n bullet.fire()\n elif event.type == pygame.KEYUP : \n if event.key == pygame.K_UP : \n ship.moving_up = False\n elif event.key == pygame.K_DOWN : \n ship.moving_down = False\n elif event.type == pygame.MOUSEBUTTONDOWN: \n # pygame has a 'mouse' class containing the clicked mouse positions\n mouse_x, mouse_y = pygame.mouse.get_pos()\n if start_button.rect.collidepoint(mouse_x, mouse_y) : \n bullet.reset_tries()\n game_active = True\n\n # check if player lost\n if bullet.tries_left <= 0 : \n game_active = False\n speed_factor = 1\n # repaint the screen\n sc.fill((230,230,230))\n # draw the button\n tries_button.draw(str(bullet.tries_left), (0,0,0), (230,230,230))\n # draw the start button\n if not game_active : \n start_button.draw('START', (255,255,255), (0,255,0))\n \n if game_active : \n # draw the ship based on internal flags\n ship.move(speed_factor)\n ship.blitme()\n # draw the target\n target.move(speed_factor)\n target.draw()\n # draw the bullet\n bullet.move(speed_factor)\n bullet.draw()\n # check collision \n if pygame.sprite.collide_rect(bullet, target) : \n bullet.hit()\n # increase the speed\n speed_factor *= speed_up_factor\n # refresh the screen\n pygame.display.flip()\n", "sub_path": "practice/14.03_three_bullets_various_speed/three_bullets.py", "file_name": "three_bullets.py", "file_ext": "py", "file_size_in_byte": 6189, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pygame.sprite.Sprite", "line_number": 8, "usage_type": "name"}, {"api_name": "pygame.image.load", "line_number": 11, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 11, "usage_type": "attribute"}, {"api_name": "pygame.sprite.Sprite", "line_number": 30, "usage_type": "name"}, {"api_name": "pygame.Rect", "line_number": 33, "usage_type": "call"}, {"api_name": "pygame.sprite.Sprite", "line_number": 51, "usage_type": "name"}, {"api_name": "pygame.Rect", "line_number": 54, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 98, "usage_type": "call"}, {"api_name": "pygame.font.SysFont", "line_number": 99, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 99, "usage_type": "attribute"}, {"api_name": "pygame.init", "line_number": 107, "usage_type": "call"}, {"api_name": "pygame.display.set_mode", "line_number": 110, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 110, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 136, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 138, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 139, "usage_type": "call"}, {"api_name": "pygame.KEYDOWN", "line_number": 140, "usage_type": "attribute"}, {"api_name": "pygame.K_q", "line_number": 141, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 142, "usage_type": "call"}, {"api_name": "pygame.K_UP", "line_number": 143, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 145, "usage_type": "attribute"}, {"api_name": "pygame.K_SPACE", "line_number": 147, "usage_type": "attribute"}, {"api_name": "pygame.KEYUP", "line_number": 151, "usage_type": "attribute"}, {"api_name": "pygame.K_UP", "line_number": 152, "usage_type": "attribute"}, {"api_name": "pygame.K_DOWN", "line_number": 154, "usage_type": "attribute"}, {"api_name": "pygame.MOUSEBUTTONDOWN", "line_number": 156, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 158, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 158, "usage_type": "attribute"}, {"api_name": "pygame.sprite.collide_rect", "line_number": 186, "usage_type": "call"}, {"api_name": "pygame.sprite", "line_number": 186, "usage_type": "attribute"}, {"api_name": "pygame.display.flip", "line_number": 191, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 191, "usage_type": "attribute"}]}
+{"seq_id": "396615537", "text": "import luigi\nimport os\nimport time\nimport json\n\nimport pandas as pd\n\nfrom jobmon import qmaster, central_job_monitor, job, sge\nfrom jobmon.executors import sge_exec\n\nfrom task_master import builder\nfrom task_master.process_artifact.process import PyProcess, Hook, ShellProcess\nfrom task_master.process_artifact.artifact import ModelableEntity, ComoVersion\n\nfrom db_tools.ezfuncs import query\n\nfrom super_squeeze import launch_squeeze\n\n\n# module level globals\ncode_dir = os.path.dirname(os.path.realpath(__file__))\ndata_dir = \"FILEPATH\"\nlog_dir = \"FILEPATH\"\n\nconda_bin_dir = \"FILEPATH\"\nconda_env = \"epic\"\n\ndescription = \"Exclusivity adjustment auto-mark\"\n\n\nclass DagMonitorMixins(builder.TaskBuilder):\n\n task_builder = luigi.Parameter(\n significant=False,\n dUSERt=(\n \"task_master.process_artifact.builders.JSONProcessArtifactMap?\"\n \"FILEPATH.json\".format(code_dir=code_dir)))\n\n @luigi.Task.event_handler(luigi.Event.FAILURE)\n def mourn_failure(task, exception):\n df = pd.DataFrame({\"process\": task.identity,\n \"error\": str(exception)},\n index=[0])\n df.to_csv(os.path.join(log_dir, \"failures\", task.identity + \".csv\"),\n index=False)\n\n def get_qmaster(self):\n execute = sge_exec.SGEExecutor(\n log_dir, 3, 30000, conda_bin_dir, conda_env)\n return qmaster.MonitoredQ(execute)\n\n\nclass Hook(Hook, DagMonitorMixins):\n identity = luigi.Parameter(dUSERt=\"como\")\n\n\nclass ModelableEntity(ModelableEntity, DagMonitorMixins):\n pass\n\n\nclass ComoVersion(ComoVersion, DagMonitorMixins):\n pass\n\n\nclass SevSplits(PyProcess, DagMonitorMixins):\n\n def _get_latest_mvid(self, meid):\n q = \"\"\"\n SELECT model_version_id\n FROM epi.model_version\n WHERE modelable_entity_id = {meid}\n ORDER BY date_inserted DESC LIMIT 1\n \"\"\".format(meid=meid)\n mvid = query(q, conn_def='epi').model_version_id.item()\n return mvid\n\n def execute(self):\n\n # get args\n kwargs = self.build_args[1]\n parent_meid = kwargs[\"parent_meid\"]\n env = \"prod\"\n\n # get qmaster\n q = self.get_qmaster()\n\n # submit split job\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"split_\" + (str(parent_meid)),\n runfile=os.path.join(code_dir, \"scripts\", \"FILEPATH.py\"),\n job_args=[str(parent_meid), env])\n q.queue_job(\n remote_job,\n slots=49,\n memory=98,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n # submit aggregation/save jobs\n outputs_tuples = self.builder.get_process_outputs(self.identity)\n children_meids = [task_tuple[0] for task_tuple in outputs_tuples]\n for meid in children_meids:\n mvid = self._get_latest_mvid(meid)\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"save_\" + str(mvid),\n runfile=sge.true_path(executable=\"aggregate_mvid\"),\n job_args=[str(mvid), '--env', env, '--mark_best'])\n q.queue_job(\n remote_job,\n slots=40,\n memory=80,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n\nclass Exclusivity(PyProcess, DagMonitorMixins):\n\n def execute(self):\n\n # compile submission arguments\n kwargs = self.build_args[1]\n me_map = kwargs.pop(\"me_map\")\n\n # get qmaster\n q = self.get_qmaster()\n\n # command line args for adjuster.py\n # parallelize by year\n for i in [1990, 1995, 2000, 2005, 2010, 2016]:\n ex_params = [\"--me_map\", json.dumps(me_map),\n \"--out_dir\", data_dir, \"--year_id\", str(i)]\n remote_job = job.Job(\n mon_dir=log_dir,\n runfile=os.path.join(code_dir, \"scripts\", \"run_ex_adjust.py\"),\n name=\"{proc}_{year}\".format(proc=self.identity, year=i),\n job_args=ex_params\n )\n q.queue_job(\n remote_job,\n slots=20,\n memory=40,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n outputs_tuples = self.builder.get_process_outputs(self.identity)\n result_meids = [task_tuple[0] for task_tuple in outputs_tuples]\n for meid in result_meids:\n save_params = [\n meid,\n description,\n os.path.join(data_dir, str(meid)),\n \"--best\",\n \"--file_pattern\", \"{year_id}.h5\",\n \"--h5_tablename\", \"draws\"]\n\n remote_job = job.Job(\n mon_dir=log_dir,\n name=\"save_\" + str(meid),\n runfile=sge.true_path(executable=\"save_custom_results\"),\n job_args=save_params)\n q.queue_job(\n remote_job,\n slots=40,\n memory=80,\n project=\"proj_epic\")\n q.block_till_done(poll_interval=60)\n\n\nclass SuperSqueeze(ShellProcess, DagMonitorMixins):\n\n def execute(self):\n launch_squeeze(log_dir=log_dir)\n\n\nif __name__ == \"__main__\":\n try:\n cjm = central_job_monitor.CentralJobMonitor(log_dir, persistent=False)\n time.sleep(3)\n except:\n pass\n else:\n luigi.run()\n finally:\n cjm.generate_report()\n cjm.stop_responder()\n", "sub_path": "shared_code/central_comp/non_fatal/como/severity_splits/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 5514, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.dirname", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 21, "usage_type": "call"}, {"api_name": "task_master.builder.TaskBuilder", "line_number": 31, "usage_type": "attribute"}, {"api_name": "task_master.builder", "line_number": 31, "usage_type": "name"}, {"api_name": "luigi.Parameter", "line_number": 33, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "luigi.Task.event_handler", "line_number": 39, "usage_type": "call"}, {"api_name": "luigi.Task", "line_number": 39, "usage_type": "attribute"}, {"api_name": "luigi.Event", "line_number": 39, "usage_type": "attribute"}, {"api_name": "jobmon.executors.sge_exec.SGEExecutor", "line_number": 48, "usage_type": "call"}, {"api_name": "jobmon.executors.sge_exec", "line_number": 48, "usage_type": "name"}, {"api_name": "jobmon.qmaster.MonitoredQ", "line_number": 50, "usage_type": "call"}, {"api_name": "jobmon.qmaster", "line_number": 50, "usage_type": "name"}, {"api_name": "luigi.Parameter", "line_number": 54, "usage_type": "call"}, {"api_name": "task_master.process_artifact.process.PyProcess", "line_number": 65, "usage_type": "name"}, {"api_name": "db_tools.ezfuncs.query", "line_number": 74, "usage_type": "call"}, {"api_name": "jobmon.job.Job", "line_number": 88, "usage_type": "call"}, {"api_name": "jobmon.job", "line_number": 88, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path", "line_number": 91, "usage_type": "attribute"}, {"api_name": "jobmon.job.Job", "line_number": 105, "usage_type": "call"}, {"api_name": "jobmon.job", "line_number": 105, "usage_type": "name"}, {"api_name": "jobmon.sge.true_path", "line_number": 108, "usage_type": "call"}, {"api_name": "jobmon.sge", "line_number": 108, "usage_type": "name"}, {"api_name": "task_master.process_artifact.process.PyProcess", "line_number": 118, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 132, "usage_type": "call"}, {"api_name": "jobmon.job.Job", "line_number": 134, "usage_type": "call"}, {"api_name": "jobmon.job", "line_number": 134, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 136, "usage_type": "call"}, {"api_name": "os.path", "line_number": 136, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 153, "usage_type": "call"}, {"api_name": "os.path", "line_number": 153, "usage_type": "attribute"}, {"api_name": "jobmon.job.Job", "line_number": 158, "usage_type": "call"}, {"api_name": "jobmon.job", "line_number": 158, "usage_type": "name"}, {"api_name": "jobmon.sge.true_path", "line_number": 161, "usage_type": "call"}, {"api_name": "jobmon.sge", "line_number": 161, "usage_type": "name"}, {"api_name": "task_master.process_artifact.process.ShellProcess", "line_number": 171, "usage_type": "name"}, {"api_name": "super_squeeze.launch_squeeze", "line_number": 174, "usage_type": "call"}, {"api_name": "jobmon.central_job_monitor.CentralJobMonitor", "line_number": 179, "usage_type": "call"}, {"api_name": "jobmon.central_job_monitor", "line_number": 179, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 180, "usage_type": "call"}, {"api_name": "luigi.run", "line_number": 184, "usage_type": "call"}]}
+{"seq_id": "95611641", "text": "# Copyright (c) 2019-2020 Paul Irofti \n# \n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nfrom gensr_sspg import gensr_sspg, stepsize_lin\nfrom gensr_proxgd import gensr_proxgd\nfrom gensr_cvx import gensr_cvx\n\nfrom sklearn.datasets import make_sparse_coded_signal\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom timeit import default_timer as timer\n\nimport pickle\n\nfrom reslimit import limit_memory\n\n# SETUP\nn_nonzero_coefs = 3 # sparsity (s)\nn_samples = 1 # number of signals (N)\n\nalpha = 0.5 # l2 weight\nlam = 5 # l1 weight\nmu = 0.05 # learning rate\neps = 1e-6 # precision\n\ndatasize = 2.5 * 1024 * 1024 * 1024 # limit memory usage\n\nprefix = 'sr-atoms'\n\n\n# TEST\nlimit_memory(datasize)\n\ncvx_time, prox_time, sspg_time = [], [], []\natoms = range(5, 130, 5)\n# atoms = range(20, 500, 20)\nfname = '{0}-{1}-{2}-{3}'.format(prefix, atoms.start, atoms.stop, atoms.step)\nfor n_components in atoms:\n print(\"----------\")\n print(\"atoms\", n_components)\n n_features = n_components * 4\n # Generate sparse signals using a dictionary\n sample, dictionary, codes = make_sparse_coded_signal(\n n_samples=n_samples,\n n_components=n_components,\n n_features=n_features,\n n_nonzero_coefs=n_nonzero_coefs,\n random_state=0)\n Delta = np.random.standard_normal((n_features, n_components))\n\n start = timer()\n cvx_x = gensr_cvx(sample, dictionary, Delta, alpha, lam)\n end = timer()\n cvx_time.append(end-start)\n print(\"CVX time: \", end - start)\n\n x0 = np.ones(dictionary.shape[1])\n start = timer()\n prox_x, _, prox_errs = gensr_proxgd(sample, dictionary, Delta, alpha, lam,\n x0, eps, cvx_x)\n end = timer()\n prox_time.append(end-start)\n print(\"Prox time: \", end - start)\n # print(\"Prox: Sparsity\", np.count_nonzero(Delta@prox_x),\n # \"solution\", Delta@prox_x)\n\n start = timer()\n sspg_x, _, _, sspg_errs = gensr_sspg(sample, dictionary, Delta, alpha, lam,\n None, stepsize_lin, eps, cvx_x)\n end = timer()\n sspg_time.append(end-start)\n print(\"SSPG time: \", end - start)\n # print(\"SSPG: Sparsity\", np.count_nonzero(Delta@sspg_x),\n # \"solution\", Delta@sspg_x)\n\n\nwith open('{0}.dat'.format(fname), 'wb') as fp:\n pickle.dump(cvx_time, fp)\n pickle.dump(prox_time, fp)\n pickle.dump(sspg_time, fp)\n\nplt.plot(atoms, cvx_time, 'b', label='cvx')\nplt.plot(atoms, prox_time, 'r', label='prox')\nplt.plot(atoms, sspg_time, 'g', label='sspg')\nplt.xlabel('atoms')\nplt.ylabel('time (s)')\nplt.legend()\nplt.savefig('{0}.pdf'.format(fname))\nplt.show()\n\n", "sub_path": "test_gensr.py", "file_name": "test_gensr.py", "file_ext": "py", "file_size_in_byte": 3336, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "reslimit.limit_memory", "line_number": 45, "usage_type": "call"}, {"api_name": "sklearn.datasets.make_sparse_coded_signal", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random.standard_normal", "line_number": 62, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 62, "usage_type": "attribute"}, {"api_name": "timeit.default_timer", "line_number": 64, "usage_type": "call"}, {"api_name": "gensr_cvx.gensr_cvx", "line_number": 65, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 70, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 71, "usage_type": "call"}, {"api_name": "gensr_proxgd.gensr_proxgd", "line_number": 72, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 74, "usage_type": "call"}, {"api_name": "timeit.default_timer", "line_number": 80, "usage_type": "call"}, {"api_name": "gensr_sspg.gensr_sspg", "line_number": 81, "usage_type": "call"}, {"api_name": "gensr_sspg.stepsize_lin", "line_number": 82, "usage_type": "argument"}, {"api_name": "timeit.default_timer", "line_number": 83, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 91, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 92, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 93, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 95, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 95, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 96, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 96, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 97, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 97, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 98, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 98, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 99, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 99, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 100, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 100, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 101, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 102, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 102, "usage_type": "name"}]}
+{"seq_id": "397977695", "text": "\"\"\"\r\n@author: nianhui guo\r\n@license: (C) Copyright 2020-2020, NWPU\r\n@contact: guonianhui199512@gmail.com\r\n@software: BNN\r\n@file: resent.py\r\n@time: 2020/10/17 14:22\r\n@desc:Binary Neural Network Optimization\r\n\"\"\"\r\n\r\nimport sys\r\nimport math\r\nimport random\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torchvision.transforms import transforms\r\nfrom .modules import BConv, MultiBConv, GhostSign, GhostBNSign\r\n\r\n\r\n__all__ = ['boolnet18', 'boolnet34']\r\n\r\n \r\ndef init_model(model):\r\n for m in model.modules():\r\n \r\n if isinstance(m, (nn.Conv2d)):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n \r\n if isinstance(m, BConv):\r\n m.weight.data.clamp_(-0.99, 0.99)\r\n \r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n \r\n elif isinstance(m, (BConv, MultiBConv)):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\r\n \r\n m.weight.data.mul_(1e-2)\r\n #m.weight.data.clamp_(-0.5, 0.5)\r\n \r\n if m.temperature is not None:\r\n nn.init.constant_(m.temperature, 1)\r\n \r\n elif isinstance(m, GhostSign):\r\n \r\n if m.temperature is not None:\r\n nn.init.constant_(m.temperature, 1)\r\n \r\n #if m.length_1 is not None:\r\n # nn.init.constant_(m.length_1, 1)\r\n \r\n #if m.length_2 is not None:\r\n # nn.init.constant_(m.length_2, 1)\r\n \r\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm, nn.InstanceNorm2d)):\r\n if m.weight is not None:\r\n nn.init.constant_(m.weight, 1)\r\n \r\n if m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n \r\n if m.running_mean is not None:\r\n nn.init.constant_(m.running_mean, 0)\r\n \r\n if m.running_var is not None:\r\n nn.init.constant_(m.running_var, 1) \r\n\r\n\r\ndef OR(x, y): # -1,1\r\n y_l = y.add(1).div(2) # 0,1\r\n x_l = x.add(1).div(2) # 0,1\r\n\r\n return ((x_l.add(y_l).clamp(0,1).mul(2).add(-1)))\r\n\r\ndef XOR(x, y): #-1,1/1,-1\r\n y = XNOR(x, -y)\r\n\r\n return y\r\n\r\ndef XNOR(x, y): #-1,1\r\n\r\n return x.mul(y)\r\n\r\n\r\nclass Conv1x1(nn.Module):\r\n def __init__(self,\r\n in_channels = 3,\r\n out_channels = 64,\r\n stride = 1,\r\n dilation = 1,\r\n groups = 1,\r\n bias = False):\r\n super(Conv1x1, self).__init__()\r\n \r\n self.Conv1x1 = nn.Conv2d(in_channels, out_channels, 1, stride = stride, padding = 0, groups = groups, bias = bias) \r\n \r\n def forward(self, x):\r\n return self.Conv1x1(x)\r\n \r\nclass BasicBlock(nn.Module):\r\n expansion = 1\r\n \r\n def __init__(self, in_channels = 16, out_channels = 16, stride = 1, dilation = 1, groups = 1, bias = False, downsample=None, base_width = 64, last_block = False, max_slices = 4):\r\n super(BasicBlock, self).__init__()\r\n self.max_slices = max_slices\r\n \r\n stochastic = False\r\n\r\n self.conv_slices_1 = 2**(random.randint(0,int(math.log(max_slices)/math.log(2)))) if stochastic else self.max_slices #specify an int even number to tell the slices to be used(less than max_slices)\r\n self.conv_slices_2 = 2**(random.randint(0,int(math.log(max_slices)/math.log(2)))) if stochastic else self.max_slices #specify an int even number to tell the slices to be used(less than max_slices)\r\n \r\n self.stride = stride\r\n \r\n self.in_channels = in_channels\r\n \r\n self.conv1 = MultiBConv(self.in_channels, out_channels, 3, stride, 1, dilation, groups = self.conv_slices_1, bias = bias, wb = True) \r\n self.conv2 = MultiBConv(out_channels, out_channels, 3, 1, 1, dilation, groups = self.conv_slices_2, bias = bias, wb = True)\r\n \r\n self.bn1 = nn.BatchNorm2d(out_channels)\r\n self.bn2 = nn.BatchNorm2d(out_channels)\r\n self.bn3 = nn.BatchNorm2d(out_channels)\r\n\r\n self.ghostsign1 = GhostSign(out_channels, slices = max_slices)\r\n self.ghostsign2 = GhostSign(out_channels, slices = max_slices)\r\n\r\n \r\n self.downsample = downsample\r\n \r\n self.last_block = last_block\r\n \r\n \r\n self.stride = stride\r\n \r\n def forward(self, x):\r\n N, S, C, H, W = x.size()\r\n \r\n residual = x\r\n\r\n if self.downsample is not None:\r\n residual = self.downsample(residual.view(N, -1, H, W))\r\n \r\n x = self.conv1(x)\r\n x = self.bn1(x)\r\n x = self.ghostsign1(x)\r\n x = XNOR(x, residual) \r\n \r\n \r\n z = self.conv2(x)\r\n z = self.bn2(z)\r\n \r\n if not self.last_block:\r\n z = self.ghostsign2(z)\r\n z = OR(z, residual)\r\n\r\n else:\r\n z = z + self.bn3(x.mean(1)) \r\n \r\n return z\r\n\r\nclass BoolNet(nn.Module):\r\n def __init__(self, block, layers, num_classes=10, zero_init_residual=False,\r\n\r\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\r\n\r\n max_slices = 4, binary_downsample=False):\r\n\r\n super(BoolNet, self).__init__() \r\n expansion = 1\r\n \r\n if replace_stride_with_dilation is None:\r\n # each element in the tuple indicates if we should replace\r\n # the 2x2 stride with a dilated convolution instead\r\n replace_stride_with_dilation = [False, False, False]\r\n \r\n if len(replace_stride_with_dilation) != 3:\r\n raise ValueError(\"replace_stride_with_dilation should be None \"\r\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\r\n \r\n scale = 1 \r\n self.groups = groups\r\n self.base_width = width_per_group\r\n self.binary_downsample = binary_downsample\r\n \r\n self.inplanes = 64*scale\r\n self.dilation = 1\r\n \r\n self.max_slices = max_slices\r\n \r\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias = False)\r\n\r\n self.maxpool = nn.Sequential(\r\n nn.BatchNorm2d(self.inplanes),\r\n nn.MaxPool2d(kernel_size = 3, stride = 2, padding = 1)\r\n )\r\n \r\n self.ghostbnsign = nn.Sequential(\r\n nn.BatchNorm2d(self.inplanes),\r\n GhostSign(self.inplanes, slices = max_slices)\r\n )\r\n\r\n self.layer1 = self._make_layer(block, 64*scale, layers[0], max_slices = self.max_slices)\r\n\r\n self.layer2 = self._make_layer(block, 128*scale, layers[1], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[0], max_slices = self.max_slices)\r\n\r\n self.layer3 = self._make_layer(block, 256*scale, layers[2], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[1], max_slices = self.max_slices)\r\n\r\n self.layer4 = self._make_layer(block, 512*scale, layers[3], stride=2,\r\n\r\n dilate=replace_stride_with_dilation[2], max_slices = self.max_slices)\r\n \r\n self.layer4[-1].last_block = True\r\n \r\n self.prelu2 = nn.PReLU(512* scale * block.expansion)\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n \r\n self.fc = nn.Linear(512* scale * block.expansion, num_classes)\r\n \r\n # Zero-initialize the last BN in each residual branch,\r\n\r\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\r\n\r\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\r\n\r\n if zero_init_residual:\r\n\r\n for m in self.modules():\r\n\r\n if isinstance(m, BasicBlock):\r\n \tnn.init.constant_(m.bn2.weight, 1e-8)\r\n \r\n init_model(self)\r\n \r\n self.distillation_loss = 0\r\n \r\n self.name = 'boolnet'\r\n \r\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False, max_slices = 4):\r\n\r\n downsample = None\r\n\r\n previous_dilation = self.dilation\r\n\r\n if dilate:\r\n\r\n self.dilation *= stride\r\n\r\n stride = 1\r\n\r\n if stride != 1 or self.inplanes != planes * block.expansion:\r\n if self.binary_downsample:\r\n downsample = nn.Sequential(\r\n BConv(self.inplanes*max_slices, planes * block.expansion, kernel_size = 1, stride = 1, padding = 0, groups = 1),\r\n nn.MaxPool2d(kernel_size = 2, stride = 2),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n GhostSign(planes * block.expansion, slices = max_slices)\r\n )\r\n else:\r\n downsample = nn.Sequential(\r\n nn.Conv2d(self.inplanes*max_slices, planes * block.expansion, kernel_size = 1, stride = 1, padding = 0, groups = max_slices),\r\n nn.AvgPool2d(kernel_size=2, stride=2),\r\n nn.BatchNorm2d(planes * block.expansion),\r\n GhostSign(planes * block.expansion, slices=max_slices)\r\n )\r\n\r\n layers = []\r\n\r\n layers.append(block(self.inplanes, planes, stride, previous_dilation, self.groups, False, downsample, max_slices = max_slices))\r\n \r\n self.inplanes = planes * block.expansion\r\n\r\n for _ in range(1, blocks):\r\n\r\n layers.append(block(self.inplanes, planes, 1, self.dilation, self.groups, False,\r\n None, base_width = self.base_width, max_slices = max_slices\r\n ))\r\n\r\n return nn.Sequential(*layers)\r\n \r\n def forward(self, x):\r\n out = []\r\n \r\n x = self.conv1(x)\r\n x = self.maxpool(x)\r\n x = self.ghostbnsign(x)\r\n \r\n x = self.layer1(x)\r\n x = self.layer2(x)\r\n x = self.layer3(x)\r\n x = self.layer4(x)\r\n \r\n x = self.prelu2(x)\r\n \r\n out = self.fc(self.avgpool(x).contiguous().view(x.size(0), -1))\r\n \r\n return out\r\n \r\nclass boolnet18(BoolNet):\r\n \"\"\"Constructs a resnet18 model with Binarized weight and activation. \r\n \r\n Args:\r\n num_classes(int): an int number used to identify the num of classes, default 10\r\n inflate(int): an int number used to control the width of a singel convolution layer, default 4(4*16)\r\n \"\"\"\r\n def __init__(self, block = BasicBlock, layers = [2, 2, 2, 2], num_classes = 10, max_slices = 4, binary_downsample = False):\r\n super(boolnet18, self).__init__(block = block, layers = layers, num_classes = num_classes, max_slices = max_slices, binary_downsample = binary_downsample)\r\n \r\n self.name = 'boolnet18'\r\n \r\nclass boolnet34(BoolNet):\r\n \"\"\"Constructs a resnet34 model with Binarized weight and activation. \r\n \r\n Args:\r\n num_classes(int): an int number used to identify the num of classes, default 10\r\n inflate(int): an int number used to control the width of a singel convolution layer, default 4(4*16)\r\n \r\n \"\"\"\r\n def __init__(self, block = BasicBlock, layers = [3, 4, 6, 3], num_classes = 10, max_slices = 4, binary_downsample = False):\r\n super(boolnet34, self).__init__(block = block, layers = layers, num_classes = num_classes, max_slices = max_slices, binary_downsample = binary_downsample)\r\n \r\n self.name = 'boolnet34'\r\n", "sub_path": "BaseNet_k_1/src/models/boolnet.py", "file_name": "boolnet.py", "file_ext": "py", "file_size_in_byte": 11914, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "torch.nn.Conv2d", "line_number": 27, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 27, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 28, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 28, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 28, "usage_type": "name"}, {"api_name": "modules.BConv", "line_number": 30, "usage_type": "argument"}, {"api_name": "torch.nn.init.constant_", "line_number": 34, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 34, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 34, "usage_type": "name"}, {"api_name": "modules.BConv", "line_number": 36, "usage_type": "name"}, {"api_name": "modules.MultiBConv", "line_number": 36, "usage_type": "name"}, {"api_name": "torch.nn.init.kaiming_normal_", "line_number": 37, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 37, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 37, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 43, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 43, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 43, "usage_type": "name"}, {"api_name": "modules.GhostSign", "line_number": 45, "usage_type": "argument"}, {"api_name": "torch.nn.init.constant_", "line_number": 48, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 48, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 48, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 56, "usage_type": "name"}, {"api_name": "torch.nn.GroupNorm", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.nn.InstanceNorm2d", "line_number": 56, "usage_type": "attribute"}, {"api_name": "torch.nn.init.constant_", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 58, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 58, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 61, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 61, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 61, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 64, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 64, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 64, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 67, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 67, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 67, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 86, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 86, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 96, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 96, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 101, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 101, "usage_type": "name"}, {"api_name": "random.randint", "line_number": 110, "usage_type": "call"}, {"api_name": "math.log", "line_number": 110, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 111, "usage_type": "call"}, {"api_name": "math.log", "line_number": 111, "usage_type": "call"}, {"api_name": "modules.MultiBConv", "line_number": 117, "usage_type": "call"}, {"api_name": "modules.MultiBConv", "line_number": 118, "usage_type": "call"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 120, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 120, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 121, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 121, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 122, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 122, "usage_type": "name"}, {"api_name": "modules.GhostSign", "line_number": 124, "usage_type": "call"}, {"api_name": "modules.GhostSign", "line_number": 125, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 161, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 161, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 190, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 190, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 192, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 192, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 193, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 193, "usage_type": "name"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 194, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 194, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 197, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 197, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 198, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 198, "usage_type": "name"}, {"api_name": "modules.GhostSign", "line_number": 199, "usage_type": "call"}, {"api_name": "torch.nn.PReLU", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 218, "usage_type": "name"}, {"api_name": "torch.nn.AdaptiveAvgPool2d", "line_number": 219, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 219, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 221, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 221, "usage_type": "name"}, {"api_name": "torch.nn.init.constant_", "line_number": 234, "usage_type": "call"}, {"api_name": "torch.nn.init", "line_number": 234, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 234, "usage_type": "name"}, {"api_name": "torch.nn.Sequential", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 256, "usage_type": "name"}, {"api_name": "modules.BConv", "line_number": 257, "usage_type": "call"}, {"api_name": "torch.nn.MaxPool2d", "line_number": 258, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 258, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 259, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 259, "usage_type": "name"}, {"api_name": "modules.GhostSign", "line_number": 260, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 263, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 263, "usage_type": "name"}, {"api_name": "torch.nn.Conv2d", "line_number": 264, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 264, "usage_type": "name"}, {"api_name": "torch.nn.AvgPool2d", "line_number": 265, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 265, "usage_type": "name"}, {"api_name": "torch.nn.BatchNorm2d", "line_number": 266, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 266, "usage_type": "name"}, {"api_name": "modules.GhostSign", "line_number": 267, "usage_type": "call"}, {"api_name": "torch.nn.Sequential", "line_number": 282, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 282, "usage_type": "name"}]}
+{"seq_id": "98647768", "text": "import pygame, sys\nfrom pygame.locals import *\nimport time\nimport tkinter\nfrom tkinter import *\n\n'''anything go with rect use the form (left, top, width, height)'''\n\npygame.init()\n#from this is the define for game statistics\nFPS = 60\nfpsClock = pygame.time.Clock()\n\nWINDOWSIZE = (1280,720) #window size\n\npygame.display.set_caption('Racing bet 888') #set Caption for title bar\n\nMAINMENUSCREEN = pygame.image.load('image\\mainmenu.png')\nMAINMENUSCREEN = pygame.transform.scale(MAINMENUSCREEN, WINDOWSIZE) #create background image\n\nmenuSound = pygame.mixer.Sound('soundFX\\menu.wav') #open sound\n\nDISPLAYSURFACE = pygame.display.set_mode(WINDOWSIZE) #create surface for mainmenu\ngMoney = 0\ncharacterSet = None\n\n#define font using \nfont = pygame.font.SysFont(None, 20, bold=True, italic=False) #set font for drawing\nmediumfont = pygame.font.SysFont(None, 30, bold = True, italic = False)\nbigfont = pygame.font.SysFont(None, 40, bold = True, italic = False)\n\n#end define the game statistics\n#------------------------------------------------------------------------------------------------#\n\n#drawing text on screen\ndef draw_text(text, font, color, surface, x, y): \n textobj = font.render(text, 1, color)\n textrect = textobj.get_rect()\n textrect.topleft = (x,y)\n surface.blit(textobj, textrect)\n return 1\n\n#running main menu\ndef mainMenu(money, characterSet):\n Running = True\n clicked = False\n toggleMenuSub = False\n\n while Running:\n #menuSound.play(-1) #repeat sound\n DISPLAYSURFACE.blit(MAINMENUSCREEN, (0,0)) #draw background\n draw_text(str(money), mediumfont, (255,0,0), DISPLAYSURFACE, 700, 630)\n draw_text('YOUR CURRENT SET IS: ' + str(characterSet), font, (0,0,0), DISPLAYSURFACE, 550, 200)\n #define the Buttons\n exitButton = pygame.Rect(40, 20, 100, 65)\n helpButton = pygame.Rect(55, 580, 110, 100)\n miniGameButton = pygame.Rect(200, 580, 110, 100)\n changeSetButton = pygame.Rect(350, 580, 110, 100)\n shopButton = pygame.Rect(885, 580, 90, 95)\n gameButton = pygame.Rect(1050, 580, 210, 100)\n playButton = pygame.Rect(1075, 470, 120, 40)\n changeNameButton = pygame.Rect(1075, 515, 120, 40)\n\n #GET MOUSE CLICK\n dx, dy = pygame.mouse.get_pos() #get clicked\n\n #if mouse click execute\n if exitButton.collidepoint(dx, dy):\n if clicked:\n exitConfirmScreen()\n if helpButton.collidepoint(dx, dy):\n if clicked:\n helpScreen()\n if miniGameButton.collidepoint(dx, dy):\n if clicked:\n money = miniGameScreen(money)\n if changeSetButton.collidepoint(dx, dy):\n if clicked:\n characterSet = changeSetScreen(characterSet)\n if shopButton.collidepoint(dx, dy):\n if clicked:\n money = shopScreen(money)\n if gameButton.collidepoint(dx, dy):\n if clicked:\n toggleMenuSub = not toggleMenuSub\n if playButton.collidepoint(dx, dy):\n if clicked and toggleMenuSub:\n draw_text('PRESSED', mediumfont, (0,0,0), DISPLAYSURFACE, 500, 500)\n if changeNameButton.collidepoint(dx, dy):\n if clicked and toggleMenuSub:\n draw_text('PRESSED', mediumfont, (0,0,0), DISPLAYSURFACE, 500, 500)\n clicked = False\n\n #checking exit game or input mouse click\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n clicked = True\n #if menusub is on then draw it \n if toggleMenuSub:\n drawGameMenuSub()\n\n #update screen every frame of loop\n fpsClock.tick(FPS)\n pygame.display.update() #update screen every execution\n return Running #return the running status to main\n\ndef exitConfirmScreen():\n running = True\n clicked = False\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Confirm Exit?', bigfont, (255,255,255), DISPLAYSURFACE, 500, 200)\n dx, dy = pygame.mouse.get_pos()\n\n #define and draw yes/no buttons\n yesButton = pygame.Rect(480, 300, 50, 50)\n noButton = pygame.Rect(680, 300, 50, 50)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), yesButton)\n draw_text('Yes', font, (0,0,0), DISPLAYSURFACE, 490, 320)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), noButton)\n draw_text('No', font, (0,0,0), DISPLAYSURFACE, 695, 320)\n\n if yesButton.collidepoint(dx,dy):\n if clicked:\n pygame.exit()\n sys.exit()\n elif noButton.collidepoint(dx,dy):\n if clicked:\n running = False\n\n clicked = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n if event.button == 1:\n clicked = True\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return running\n\ndef drawHelp():\n draw_text('HELP', bigfont, (255,255,255), DISPLAYSURFACE, 620, 20)\n draw_text('Welcome to Racing Bet Game', mediumfont, (255,255,255), DISPLAYSURFACE, 500, 50)\n draw_text('Nothing to see here at this time', font, (255,255,255), DISPLAYSURFACE, 550, 100)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 530, 120)\n\ndef helpScreen():\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n drawHelp()\n #check event\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n\ndef miniGameScreen(money):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Nothing to see at this time', bigfont, (255,255,255), DISPLAYSURFACE, 450, 300)\n money = miniGameEvent(money)\n draw_text('Money at this time is: ' + str(money), mediumfont, (255,255,255), DISPLAYSURFACE, 500, 400)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 530, 120)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return money\n\ndef miniGameEvent(money):\n money += 10\n return money\n\ndef changeSetScreen(selectedSet):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('CHOSE YOUR FAVORITE SET: ', bigfont, (255,255,255), DISPLAYSURFACE, 400, 50)\n draw_text('YOUR CURRENT SET IS: ' + str(selectedSet), mediumfont, (255,255,255), DISPLAYSURFACE, 450, 100) \n draw_text('Press 1 to 5 to choose set', mediumfont, (255,255,255), DISPLAYSURFACE, 480, 150)\n draw_text('Press ESC Key to return Main Menu', mediumfont, (255,255,255), DISPLAYSURFACE, 415, 200)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == ord('1'):\n selectedSet = 1\n if event.key == ord('2'):\n selectedSet = 2\n if event.key == ord('3'):\n selectedSet = 3\n if event.key == ord('4'):\n selectedSet = 4\n if event.key == ord('5'):\n selectedSet = 5\n if event.key == K_ESCAPE:\n running = False\n\n fpsClock.tick(FPS)\n pygame.display.update()\n return selectedSet\n\ndef shopScreen(money):\n running = True\n while running:\n DISPLAYSURFACE.fill((0,0,0))\n draw_text('Nothing at this time', bigfont, (255,255,255), DISPLAYSURFACE, 470, 300)\n draw_text('Money at this time is: ' + str(money), mediumfont, (255,255,255), DISPLAYSURFACE, 490, 350)\n draw_text('Press ESC Key to return Main Menu', font, (255,255,255), DISPLAYSURFACE, 490, 200)\n draw_text('Press 1 to 5 to buy', font, (255,255,255), DISPLAYSURFACE, 550, 400)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN:\n if event.key == ord('1'):\n if money < 100:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else:\n money -= 100\n if event.key == ord('2'):\n if money < 200:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 200\n if event.key == ord('3'):\n if money < 300:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else:\n money -= 300\n if event.key == ord('4'):\n if money < 400:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 400\n if event.key == ord('5'):\n if money < 500:\n draw_text('YOU DON\\'T HAVE ENOUGHT MONEY', bigfont, (255,255,255), DISPLAYSURFACE, 400, 500)\n else: \n money -= 500 \n if event.key == K_ESCAPE:\n running = False\n fpsClock.tick(FPS)\n pygame.display.update()\n return money\n\ndef drawGameMenuSub():\n subMenuArea = pygame.Rect(1060, 460, 150, 100)\n pygame.draw.rect(DISPLAYSURFACE, (255,255,255), subMenuArea)\n playButton = pygame.Rect(1075, 470, 120, 40)\n changeNameButton = pygame.Rect(1075, 515, 120, 40)\n pygame.draw.rect(DISPLAYSURFACE, (0,0,0), playButton, 3)\n pygame.draw.rect(DISPLAYSURFACE, (0,0,0), changeNameButton, 3)\n draw_text('PLAY', font, (0,0,0), DISPLAYSURFACE, 1115, 485)\n draw_text('CHANGE NAME', font, (0,0,0), DISPLAYSURFACE, 1080, 530)\n\ndef playScreen():\n pass\n\ndef changeNameScreen():\n pass\n\ndef main():\n Running = True\n while Running:\n Running = mainMenu(gMoney, characterSet)\n\nif __name__ == \"__main__\":\n main()\n\n#end of file", "sub_path": "SourceCode/mainMenu.py", "file_name": "mainMenu.py", "file_ext": "py", "file_size_in_byte": 11110, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pygame.init", "line_number": 9, "usage_type": "call"}, {"api_name": "pygame.time.Clock", "line_number": 12, "usage_type": "call"}, {"api_name": "pygame.time", "line_number": 12, "usage_type": "attribute"}, {"api_name": "pygame.display.set_caption", "line_number": 16, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 16, "usage_type": "attribute"}, {"api_name": "pygame.image.load", "line_number": 18, "usage_type": "call"}, {"api_name": "pygame.image", "line_number": 18, "usage_type": "attribute"}, {"api_name": "pygame.transform.scale", "line_number": 19, "usage_type": "call"}, {"api_name": "pygame.transform", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pygame.mixer.Sound", "line_number": 21, "usage_type": "call"}, {"api_name": "pygame.mixer", "line_number": 21, "usage_type": "attribute"}, {"api_name": "pygame.display.set_mode", "line_number": 23, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 23, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 28, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 28, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 29, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pygame.font.SysFont", "line_number": 30, "usage_type": "call"}, {"api_name": "pygame.font", "line_number": 30, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 55, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 56, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 57, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 58, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 59, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 60, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 61, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 62, "usage_type": "call"}, {"api_name": "pygame.mouse.get_pos", "line_number": 65, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 65, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 95, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 95, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 96, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 97, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 98, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 108, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 108, "usage_type": "attribute"}, {"api_name": "pygame.mouse.get_pos", "line_number": 117, "usage_type": "call"}, {"api_name": "pygame.mouse", "line_number": 117, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 120, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 121, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 122, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 122, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 124, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 124, "usage_type": "attribute"}, {"api_name": "pygame.exit", "line_number": 129, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 130, "usage_type": "call"}, {"api_name": "pygame.event.get", "line_number": 136, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 136, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 137, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 138, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 139, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 147, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 147, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 162, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 162, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 163, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 164, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 165, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 170, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 170, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 180, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 180, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 181, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 182, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 183, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 188, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 188, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 203, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 203, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 204, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 205, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 206, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 222, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 222, "usage_type": "attribute"}, {"api_name": "pygame.event.get", "line_number": 233, "usage_type": "call"}, {"api_name": "pygame.event", "line_number": 233, "usage_type": "attribute"}, {"api_name": "pygame.QUIT", "line_number": 234, "usage_type": "attribute"}, {"api_name": "pygame.quit", "line_number": 235, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 236, "usage_type": "call"}, {"api_name": "pygame.display.update", "line_number": 266, "usage_type": "call"}, {"api_name": "pygame.display", "line_number": 266, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 270, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 271, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 271, "usage_type": "attribute"}, {"api_name": "pygame.Rect", "line_number": 272, "usage_type": "call"}, {"api_name": "pygame.Rect", "line_number": 273, "usage_type": "call"}, {"api_name": "pygame.draw.rect", "line_number": 274, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 274, "usage_type": "attribute"}, {"api_name": "pygame.draw.rect", "line_number": 275, "usage_type": "call"}, {"api_name": "pygame.draw", "line_number": 275, "usage_type": "attribute"}]}
+{"seq_id": "140187056", "text": "from django.conf.urls import url\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\r\n url(r'^index/', views.index, name='index'),\r\n url(r'^register/', views.register, name='register'),\r\n url(r'^login/', views.user_login, name='login'),\r\n url(r'^logout/', views.user_logout, name='logout'),\r\n url(r'^welcome/', views.welcome, name='welcome'),\r\n url(r'^itempage/', views.itempage, name='itempage'),\r\n url(r'^search/', views.search, name='search'),\r\n url(r'^activate/(?P[0-9A-Za-z_\\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',\r\n views.activate, name='activate'),\r\n\r\n url(r'(?P.*)/$', views.category),\r\n \r\n\r\n \r\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\r\n", "sub_path": "findr/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 808, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 12, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 13, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 14, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 15, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 18, "usage_type": "call"}, {"api_name": "django.conf.urls.static.static", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.settings.MEDIA_URL", "line_number": 22, "usage_type": "attribute"}, {"api_name": "django.conf.settings", "line_number": 22, "usage_type": "name"}, {"api_name": "django.conf.settings.MEDIA_ROOT", "line_number": 22, "usage_type": "attribute"}]}
+{"seq_id": "297658772", "text": "#!/usr/bin/env python\n\n#----------------------------------#\n# ,--. ,--. ,--. #\n# | .' / ,---. ,-' '-. ,--,--. #\n# | . ' | .-. |'-. .-'' ,-. | #\n# | |\\ \\' '-' ' | | \\ '-' | #\n# `--' '--' `---' `--' `--`--' #\n# kotajacob.tk #\n# Copyright (C) 2017 Dakota Walsh #\n#----------------------------------#\n\n\"\"\"\nWal Steam\n\nUsage:\n wal_steam.py (-w | -g)\n wal_steam.py (-h | --help)\n wal_steam.py (-v | --version)\n\nOptions:\n -w use wal for colors\n -g use wpg for colors\n -h --help show this help message and exit\n -v --version show version and exit\n\"\"\"\nfrom lib.docopt import docopt # argument parsing\nfrom shutil import move # moveing files\nfrom shutil import copy # copying files\nimport os # getting paths\nimport urllib.request # downloading the zip files\nimport zipfile # extracting the zip files\nfrom distutils.dir_util import copy_tree # copytree from shutil is FUCKING GARBAGE for no reason so we use this instead\n\n# set some variables for the file locations\nROOT_DIR = os.path.expanduser(\"~/.cache/wal_steam/\")\n\nmetroUrl = \"http://metroforsteam.com/downloads/4.2.4.zip\"\nmetroPatchUrl = \"http://github.com/redsigma/UPMetroSkin/archive/master.zip\"\n\nmetroZip = os.path.join(ROOT_DIR, \"metroZip.zip\")\nmetroPatchZip = os.path.join(ROOT_DIR, \"metroPatchZip.zip\")\nmetroResource = os.path.join(ROOT_DIR, \"metroZip/\")\nmetroPatchResource = os.path.join(ROOT_DIR, \"metroPatchZip/\")\nmetroPatchCopy = os.path.join(ROOT_DIR, \"metroPatchZip/UPMetroSkin-master/Unofficial 4.2.4 Patch/Main Files [Install First]/\")\nmetroCopy = os.path.join(ROOT_DIR, \"metroZip/Metro 4.2.4/\")\n\nmetroInstallOther = os.path.expanduser(\"~/.steam/steam/skins/Metro 4.2.4 Wal_Mod/\")\nmetroInstallUbuntu = os.path.expanduser(\"~/.steam/skins/Metro 4.2.4 Wal_Mod/\")\nsteamSkins = os.path.expanduser(\"~/.steam/steam/skins/\")\nsteamSkinsUbuntu = os.path.expanduser(\"~/.steam/skins/\")\n\nnewColors = os.path.join(ROOT_DIR, \"colors.styles\")\nwpgConfig = os.path.expanduser(\"~/.wallpapers/current.css\")\nwalConfig = os.path.expanduser(\"~/.cache/wal/colors.css\")\n\n# Set metro install\nif os.path.isdir(steamSkins):\n # use \"other\" path\n metroInstall = metroInstallOther\nelif os.path.isdir(steamSkinsUbuntu):\n # use \"ubuntu\" path\n metroInstall = metroInstallUbuntu\nelse:\n # no steam found\n sys.exit(\"Error: Steam not found!\")\n\n\ndef tupToPrint(tup):\n tmp = ' '.join(map(str, tup)) # convert the tupple (rgb color) to a string ready to print\n return tmp\n\ndef checkDir(dirName):\n # check if wal_steam has been run before\n if os.path.isdir(dirName):\n return True\n else:\n return False\n\ndef makeStyle(colors):\n # create and write the colors.styles file\n print(\"Patching new colors\")\n\n try:\n os.remove(newColors) # just in case it was already there for some reason\n except FileNotFoundError:\n print(\"No file to remove\")\n f_name = open(newColors, 'w')\n\n # First write the variables we aren't changing\n f_name.write('\\\"settings.styles\\\"\\n')\n f_name.write('{\\n')\n f_name.write('\\tcolors\\n')\n f_name.write('\\t{\\n')\n f_name.write('\\t\\tnone=\\\"0 0 0 0\\\"\\n')\n f_name.write('\\t\\tFocus_T=\\\"0 114 198 30.6\\\"\\n')\n f_name.write('\\t\\twhite03=\\\"255 255 255 7.65\\\"\\n')\n f_name.write('\\t\\twhite08=\\\"255 255 255 20.4\\\"\\n')\n f_name.write('\\t\\twhite05=\\\"255 255 255 12.75\\\"\\n')\n f_name.write('\\t\\twhite10=\\\"255 255 255 25.5\\\"\\n')\n f_name.write('\\t\\twhite12=\\\"255 255 255 30.6\\\"\\n')\n # f.write('\\t\\twhite15=\\\"255 255 255 \\\"\\n') this was commented in the file...\n f_name.write('\\t\\twhite20=\\\"255 255 255 51\\\"\\n')\n f_name.write('\\t\\twhite24=\\\"255 255 255 61.2\\\"\\n')\n f_name.write('\\t\\twhite25=\\\"255 255 255 63.75\\\"\\n')\n f_name.write('\\t\\twhite35=\\\"255 255 255 89.25\\\"\\n')\n f_name.write('\\t\\twhite45=\\\"255 255 255 114.75\\\"\\n')\n f_name.write('\\t\\twhite50=\\\"255 255 255 127.5\\\"\\n')\n f_name.write('\\t\\twhite75=\\\"255 255 255 191.25\\\"\\n')\n f_name.write('\\t\\twhite=\\\"255 255 255 255\\\"\\n')\n f_name.write('\\t\\tblack03=\\\"0 0 0 7.65\\\"\\n')\n f_name.write('\\t\\tblack08=\\\"0 0 0 20.4\\\"\\n')\n f_name.write('\\t\\tblack05=\\\"0 0 0 12.75\\\"\\n')\n f_name.write('\\t\\tblack10=\\\"0 0 0 25.5\\\"\\n')\n f_name.write('\\t\\tblack12=\\\"0 0 0 30.6\\\"\\n')\n # f.write('\\t\\tblack15=\\\"0 0 0 38.25\\\"\\n') this was commented in the file too...\n f_name.write('\\t\\tblack20=\\\"0 0 0 51\\\"\\n')\n f_name.write('\\t\\tblack24=\\\"0 0 0 61.2\\\"\\n')\n f_name.write('\\t\\tblack35=\\\"0 0 0 106\\\"\\n')\n f_name.write('\\t\\tblack25=\\\"0 0 0 63.75\\\"\\n')\n f_name.write('\\t\\tblack75=\\\"0 0 0 191.25\\\"\\n')\n f_name.write('\\t\\tBlack=\\\"0 0 0 255\\\"\\n')\n f_name.write('\\t\\tScroll_blu=\\\"88 168 242 165\\\"\\n')\n f_name.write('\\t\\tScroll_blu_s=\\\"103 193 245 175\\\"\\n')\n f_name.write('\\t\\tDetailsBackground=\\\"Black45\\\"\\n')\n f_name.write('\\t\\tDetailPanels=\\\"black45\\\"\\n')\n f_name.write('\\t\\tOverlaySidePanels=\\\"255 255 255 144.75\\\"\\n')\n f_name.write('\\t\\tOverlayHover05=\\\"255 255 255 12.75\\\"\\n')\n f_name.write('\\t\\ttransparent_notification=\\\"5 5 5 229.5\\\"\\n')\n f_name.write('\\t\\tchatframe=\\\"White50\\\"\\n')\n f_name.write('\\t\\tScrollBar=\\\"86 86 86 255\\\"\\n')\n f_name.write('\\t\\tScrollBarH=\\\"110 110 110 255\\\"\\n')\n f_name.write('\\t\\tGrey1=\\\"40 40 40 255\\\"\\n')\n f_name.write('\\t\\tGrey2=\\\"48 48 48 255\\\"\\n')\n f_name.write('\\t\\tGrey3=\\\"75 75 75 255\\\"\\n')\n f_name.write('\\t\\tClientBGTransparent=\\\"43 43 43 191.25\\\"\\n')\n f_name.write('\\t\\tRed=\\\"255 0 0 255\\\"\\n')\n f_name.write('\\t\\tW10close_Red_h=\\\"232 18 35 255\\\"\\n')\n f_name.write('\\t\\tW10close_Red_p=\\\"241 112 121 255\\\"\\n')\n\n # Now for some variables we are changing\n f_name.write('\\t\\tblack45=\\\"' + tupToPrint(colors[0]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tFocus=\\\"' + tupToPrint(colors[4]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFriends_InGame=\\\"' + tupToPrint(colors[1]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFriends_Online=\\\"' + tupToPrint(colors[2]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tFrameBorder=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tGameList=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tDividers=\\\"' + tupToPrint(colors[15]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tSeperator=\\\"' + tupToPrint(colors[15]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tOverlayBackground=\\\"' + tupToPrint(colors[0]) + ' 80' + '\\\"\\n')\n f_name.write('\\t\\tOverlayPanels=\\\"' + tupToPrint(colors[0]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlayClock=\\\"' + tupToPrint(colors[15]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlaySideButtons=\\\"' + tupToPrint(colors[1]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tOverlaySideButtons_h=\\\"' + tupToPrint(colors[4]) + ' 120' + '\\\"\\n')\n f_name.write('\\t\\tTextEntry=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tHeader_Dark=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n f_name.write('\\t\\tClientBG=\\\"' + tupToPrint(colors[0]) + ' 255' + '\\\"\\n')\n\n # Final formatting stuff\n f_name.write('\\t}\\n')\n f_name.write('}\\n')\n\n f_name.close()\n copy(newColors, metroInstall)\n # cleanup by removing generated color file\n os.remove(newColors)\n print(\"Wal colors are now patched and ready to go\")\n print(\"If this is your first run you may have to \")\n print(\"enable Metro Wal Mod skin in steam then \")\n print(\"simply restart steam!\")\n\ndef hexToRgb(hexColors):\n # convert hex colors to rgb colors (takes a list)\n tmpColors = []\n rgbColors = []\n for color in hexColors: # loop through the hex colors\n # remove the optothorpe\n # use tuple and a loop to convert them to rgb\n # append new colors to our rgb list\n tmp = color.lstrip('#')\n tmpColors.append(tuple(int(tmp[i:i+2], 16) for i in (0, 2 ,4)))\n return tmpColors\n\ndef parseCss(config):\n # parse colors file and return colors in list\n print(\"Reading colors\")\n f_name = open(config, 'r')\n raw_file = f_name.readlines() # save lines into raw_file\n del raw_file[0:11] # delete elements up to the colors\n del raw_file[16] # also that last line is just a } (16 now because we removed some already)\n\n colors = []\n for line in raw_file: # loop through raw_file\n tmp = line[line.find(\"#\"):] # remove everything before the octothorpe\n tmp = tmp[:7] # remove everything after the color\n\n colors.append(tmp) # add tmp to the new list\n\n f_name.close()\n return colors\n\n##################\n# For installing #\n# Wal Steam #\n##################\n\ndef makeCache():\n os.mkdir(ROOT_DIR)\n\ndef downloadMetro():\n # download metro for steam\n # download metro for steam patch\n print(\"Downloading Metro for steam\")\n urllib.request.urlretrieve(metroUrl, metroZip)\n z = zipfile.ZipFile(metroZip, 'r')\n z.extractall(metroResource)\n z.close()\n print(\"Downloading Metro patch\")\n urllib.request.urlretrieve(metroPatchUrl, metroPatchZip)\n z = zipfile.ZipFile(metroPatchZip, 'r')\n z.extractall(metroPatchResource)\n z.close()\n\ndef installMetro():\n print(\"Installing Metro Wal\")\n copy_tree(metroPatchCopy, metroCopy) # use copy_tree not copytree, shutil copytree is broken\n copy_tree(metroCopy, metroInstall)\n print(\"Metro Wal is now installed\")\n\ndef checkInstall():\n if not checkDir(ROOT_DIR):\n # wal_steam cache missing\n # redownload and patch\n makeCache()\n downloadMetro()\n installMetro()\n else:\n # cache was found\n # check for skin\n if not checkDir(metroInstall):\n # metro install missing\n downloadMetro()\n installMetro()\n else:\n # metro install found\n print(\"Metro install found\")\n\ndef main(arguments):\n checkInstall()\n\n if (arguments['--help'] == False and arguments['--version'] == False): # determine the mode\n if (arguments['-g'] == True):\n colors = parseCss(wpgConfig) # they picked g so parse wpg\n colors = hexToRgb(colors)\n makeStyle(colors)\n else:\n colors = parseCss(walConfig) # they picked w so parse wal\n colors = hexToRgb(colors)\n makeStyle(colors)\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='Wal Steam 1.1.0') # create the flags from the comment\n main(arguments)\n", "sub_path": "wal_steam.py", "file_name": "wal_steam.py", "file_ext": "py", "file_size_in_byte": 10557, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.expanduser", "line_number": 36, "usage_type": "call"}, {"api_name": "os.path", "line_number": 36, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 41, "usage_type": "call"}, {"api_name": "os.path", "line_number": 41, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 42, "usage_type": "call"}, {"api_name": "os.path", "line_number": 42, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 43, "usage_type": "call"}, {"api_name": "os.path", "line_number": 43, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 44, "usage_type": "call"}, {"api_name": "os.path", "line_number": 44, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 45, "usage_type": "call"}, {"api_name": "os.path", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 46, "usage_type": "call"}, {"api_name": "os.path", "line_number": 46, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 49, "usage_type": "call"}, {"api_name": "os.path", "line_number": 49, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 50, "usage_type": "call"}, {"api_name": "os.path", "line_number": 50, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 51, "usage_type": "call"}, {"api_name": "os.path", "line_number": 51, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 53, "usage_type": "call"}, {"api_name": "os.path", "line_number": 53, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.path.expanduser", "line_number": 55, "usage_type": "call"}, {"api_name": "os.path", "line_number": 55, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 58, "usage_type": "call"}, {"api_name": "os.path", "line_number": 58, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path", "line_number": 61, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 75, "usage_type": "call"}, {"api_name": "os.path", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 85, "usage_type": "call"}, {"api_name": "shutil.copy", "line_number": 164, "usage_type": "call"}, {"api_name": "os.remove", "line_number": 166, "usage_type": "call"}, {"api_name": "os.mkdir", "line_number": 208, "usage_type": "call"}, {"api_name": "urllib.request.request.urlretrieve", "line_number": 214, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 214, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 214, "usage_type": "name"}, {"api_name": "zipfile.ZipFile", "line_number": 215, "usage_type": "call"}, {"api_name": "urllib.request.request.urlretrieve", "line_number": 219, "usage_type": "call"}, {"api_name": "urllib.request.request", "line_number": 219, "usage_type": "attribute"}, {"api_name": "urllib.request", "line_number": 219, "usage_type": "name"}, {"api_name": "zipfile.ZipFile", "line_number": 220, "usage_type": "call"}, {"api_name": "distutils.dir_util.copy_tree", "line_number": 226, "usage_type": "call"}, {"api_name": "distutils.dir_util.copy_tree", "line_number": 227, "usage_type": "call"}, {"api_name": "lib.docopt.docopt", "line_number": 262, "usage_type": "call"}]}
+{"seq_id": "244139502", "text": "# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\bca4abm\\tables\\trips.py\n# Compiled at: 2020-02-14 01:16:04\n# Size of source mod 2**32: 3310 bytes\nimport logging, pandas as pd\nfrom activitysim.core import inject\nfrom activitysim.core import config\nfrom bca4abm import bca4abm as bca\nlogger = logging.getLogger(__name__)\n\ndef read_merged_trips(table_name, alt_table_name, data_dir, table_settings, persons):\n trips = bca.read_csv_table(table_name=table_name, data_dir=data_dir, settings=table_settings)\n trips_alt = bca.read_csv_table(table_name=alt_table_name, data_dir=data_dir, settings=table_settings)\n trips_merged = pd.merge(trips, trips_alt, on=['household_id',\n 'person_idx',\n 'tour_idx',\n 'half_tour_idx',\n 'half_tour_seg_idx'])\n persons = persons.to_frame()[['household_id', 'person_idx']]\n persons['person_id'] = persons.index\n trips_merged = pd.merge(trips_merged, persons, on=['household_id', 'person_idx'])\n return trips_merged\n\n\n@inject.table()\ndef base_trips(data_dir, persons):\n logger.debug('reading base_trips table')\n table_settings = config.read_model_settings('tables.yaml')\n trips_merged = read_merged_trips(table_name='basetrips', alt_table_name='basetrips_buildlos',\n data_dir=data_dir,\n table_settings=table_settings,\n persons=persons)\n trips_merged['build'] = 0\n trips_merged['base'] = 1\n return trips_merged\n\n\n@inject.table()\ndef build_trips(data_dir, persons):\n logger.debug('reading build_trips table')\n table_settings = config.read_model_settings('tables.yaml')\n trips_merged = read_merged_trips(table_name='buildtrips', alt_table_name='buildtrips_baselos',\n data_dir=data_dir,\n table_settings=table_settings,\n persons=persons)\n trips_merged['build'] = 1\n trips_merged['base'] = 0\n return trips_merged\n\n\n@inject.table()\ndef disaggregate_trips(base_trips, build_trips):\n build = build_trips.to_frame()\n base = base_trips.to_frame()\n df = base.append(build, ignore_index=True, sort=False)\n df['index1'] = df.index\n return df\n\n\ninject.broadcast(cast='persons_merged', onto='disaggregate_trips',\n cast_index=True,\n onto_on='person_id')\n\n@inject.table()\ndef trips_with_demographics(disaggregate_trips, persons_merged):\n return inject.merge_tables(target=(disaggregate_trips.name), tables=[\n disaggregate_trips, persons_merged])", "sub_path": "pycfiles/bca4abm-0.5-py3.7/trips.cpython-37.py", "file_name": "trips.cpython-37.py", "file_ext": "py", "file_size_in_byte": 2514, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.getLogger", "line_number": 12, "usage_type": "call"}, {"api_name": "bca4abm.bca4abm.read_csv_table", "line_number": 15, "usage_type": "call"}, {"api_name": "bca4abm.bca4abm", "line_number": 15, "usage_type": "name"}, {"api_name": "bca4abm.bca4abm.read_csv_table", "line_number": 16, "usage_type": "call"}, {"api_name": "bca4abm.bca4abm", "line_number": 16, "usage_type": "name"}, {"api_name": "pandas.merge", "line_number": 17, "usage_type": "call"}, {"api_name": "pandas.merge", "line_number": 24, "usage_type": "call"}, {"api_name": "activitysim.core.config.read_model_settings", "line_number": 31, "usage_type": "call"}, {"api_name": "activitysim.core.config", "line_number": 31, "usage_type": "name"}, {"api_name": "activitysim.core.inject.table", "line_number": 28, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 28, "usage_type": "name"}, {"api_name": "activitysim.core.config.read_model_settings", "line_number": 44, "usage_type": "call"}, {"api_name": "activitysim.core.config", "line_number": 44, "usage_type": "name"}, {"api_name": "activitysim.core.inject.table", "line_number": 41, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 41, "usage_type": "name"}, {"api_name": "activitysim.core.inject.table", "line_number": 54, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 54, "usage_type": "name"}, {"api_name": "activitysim.core.inject.broadcast", "line_number": 63, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 63, "usage_type": "name"}, {"api_name": "activitysim.core.inject.merge_tables", "line_number": 69, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 69, "usage_type": "name"}, {"api_name": "activitysim.core.inject.table", "line_number": 67, "usage_type": "call"}, {"api_name": "activitysim.core.inject", "line_number": 67, "usage_type": "name"}]}
+{"seq_id": "147548121", "text": "#!/usr/bin/env python\n\n\"\"\"\n@Time : 18/07/28 12:59\n@Author : Bob\n@Desc : \n\"\"\"\n\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\n\nfrom djchat.routing import *\n\napplication = ProtocolTypeRouter({\n # (http->django views is added by default)\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_urlpatterns\n )\n ),\n})\n", "sub_path": "sdfh_rest/routing.py", "file_name": "routing.py", "file_ext": "py", "file_size_in_byte": 414, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "channels.routing.ProtocolTypeRouter", "line_number": 14, "usage_type": "call"}, {"api_name": "channels.auth.AuthMiddlewareStack", "line_number": 16, "usage_type": "call"}, {"api_name": "channels.routing.URLRouter", "line_number": 17, "usage_type": "call"}]}
+{"seq_id": "453583838", "text": "\"\"\"MultipleAppsProject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^courses/', include('apps.courses.urls', namespace='courses')),\n url(r'^login_reg/',include('apps.login_reg.urls', namespace='login_reg')),\n url(r'^random_word/',include('apps.random_word_generator.urls', namespace='random_word')),\n url(r'^survey/',include('apps.survey.urls',namespace='survey')),\n url(r'^timedisplay/',include('apps.timedisplay.urls',namespace='timed'))\n]\n", "sub_path": "Python/Django/MultipleAppsProject/MultipleAppsProject/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 1141, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.urls.url", "line_number": 20, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 20, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 21, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 21, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 22, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 23, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 23, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 24, "usage_type": "call"}, {"api_name": "django.conf.urls.include", "line_number": 24, "usage_type": "call"}]}
+{"seq_id": "241834516", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Make some random data to represent your r, g, b bands.\r\nny, nx = 2, 3\r\nr, g, b = [np.random.random(ny*nx).reshape((ny, nx)) for _ in range(3)]\r\n\r\nc = np.dstack([r,g,b])\r\nprint (c)\r\n\r\nplt.imshow(c, interpolation='nearest')\r\nplt.show()", "sub_path": "animacja.py", "file_name": "animacja.py", "file_ext": "py", "file_size_in_byte": 290, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.random.random", "line_number": 6, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 6, "usage_type": "attribute"}, {"api_name": "numpy.dstack", "line_number": 8, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 11, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 11, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}]}
+{"seq_id": "390223984", "text": "# -*- coding: utf-8 -*-\n\nimport logging\nfrom logging.config import dictConfig\n\ndef config(software, level):\n root = logging.getLogger()\n root.setLevel(level)\n if software == 'GoogleAppEngine':\n return\n dictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '%(asctime)s '\n '%(levelname)8s: '\n '%(message)s '\n '<%(name)s:%(filename)s:%(lineno)d>',\n 'datefmt': '%Y-%m-%d %H:%M:%S',\n }},\n 'handlers': {\n 'default': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://sys.stdout',\n 'formatter': 'default'\n },\n },\n 'root': {\n 'handlers': ['default']\n }\n })\n # chardet decode() logs TMI on DEBUG level.\n chardet_logger = logging.getLogger('chardet.charsetprober')\n chardet_logger.setLevel('WARNING')\n urllib3_logger = logging.getLogger('urllib3.connectionpool')\n urllib3_logger.setLevel('WARNING')\n werkzeug = logging.getLogger('werkzeug')\n werkzeug.setLevel('WARNING')\n if software.startswith('gunicorn/'):\n '''\n The logger of logging is about how logs are inputted.\n The handler of logging is about how logs are outputted.\n So if you want to write logs by root logger, and print them by gunicorn,\n you should register gunicorn handlers(output) on root logger(input).\n Logger class : gunicorn.glogging.Logger\n '''\n gunicorn_logger = logging.getLogger('gunicorn.error')\n root.handlers = gunicorn_logger.handlers\n root.setLevel(gunicorn_logger.level)\n", "sub_path": "apps/common/logger.py", "file_name": "logger.py", "file_ext": "py", "file_size_in_byte": 1688, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 7, "usage_type": "call"}, {"api_name": "logging.config.dictConfig", "line_number": 11, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 32, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 34, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 36, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 46, "usage_type": "call"}]}
+{"seq_id": "113192698", "text": "import json\nimport re\nimport os\nimport glob\nfrom matplotlib import pyplot as plt\n\n\ndef read_json(file_name):\n f = open(file_name, \"r\")\n json_dict = json.load(f)\n\n return json_dict['SNR'], json_dict['BER']\n\n\ndef main2():\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n fn_list = glob.glob(\"./*.json\")\n for fn in fn_list:\n snr, ber = read_json(fn)\n ax.plot(snr, ber, label=fn)\n\n ax.set_yscale(\"log\")\n ax.set_xlim([0, 30])\n ax.set_ylim([1e-5, 1])\n\n ax.set_xlabel(\"SNR\")\n ax.set_ylabel(\"BER\")\n\n ax.legend()\n ax.grid()\n\n plt.savefig(re.sub(\".py\", \"\", os.path.basename(__file__))+\".png\")\n\n\ndef main():\n snr, ber = read_json(\"./BER_MMSE\")\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n ax.plot(snr, ber)\n\n ax.set_yscale(\"log\")\n ax.set_xlim([0, 30])\n ax.set_ylim([1e-5, 1])\n\n ax.text(x=15, y=5*(1e-4),\n s=\"SNR=\" + str(int(snr[0]))+\" -> BER=\"+str(ber[0]),\n ha='center', fontsize=12)\n\n ax.text(x=15, y=2*(1e-4),\n s=\"SNR=\" + str(int(snr[-1]))+\" -> BER=\"+str(ber[-1]),\n ha='center', fontsize=12)\n\n ax.set_xlabel(\"SNR\")\n ax.set_ylabel(\"BER\")\n\n ax.grid()\n\n plt.savefig(re.sub(\".py\", \"\", os.path.basename(__file__))+\".png\")\n\nif __name__ == '__main__':\n main2()\n", "sub_path": "3教科書/MU-MIMOの基礎/src/昔の/BER_SIC/plt_BER_SIC_MMSE.py", "file_name": "plt_BER_SIC_MMSE.py", "file_ext": "py", "file_size_in_byte": 1295, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "json.load", "line_number": 10, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 16, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 16, "usage_type": "name"}, {"api_name": "glob.glob", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 34, "usage_type": "call"}, {"api_name": "os.path", "line_number": 34, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 40, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 40, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 62, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 62, "usage_type": "name"}, {"api_name": "re.sub", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path.basename", "line_number": 62, "usage_type": "call"}, {"api_name": "os.path", "line_number": 62, "usage_type": "attribute"}]}
+{"seq_id": "299705461", "text": "# coding=utf-8\r\nfrom __future__ import unicode_literals, print_function\r\nimport pymongo\r\nfrom base import SinaBaseObject\r\nimport sina_weibo\r\nimport sina_people\r\nimport sys\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\n\r\n# 类转化为字典\r\ndef class_to_dict(obj):\r\n is_list = obj.__class__ == [].__class__\r\n is_set = obj.__class__ == set().__class__\r\n\r\n if is_list or is_set:\r\n obj_arr = []\r\n for o in obj:\r\n dict1 = {}\r\n dict1.update(o.__dict__)\r\n obj_arr.append(dict1)\r\n return obj_arr\r\n else:\r\n dict1 = {}\r\n dict1.update(obj.__dict__)\r\n return dict1\r\n\r\n\r\nclass SinaStore(SinaBaseObject):\r\n def __init__(self):\r\n super(SinaStore, self).__init__()\r\n self.is_first = True\r\n\r\n self.mongo_client = pymongo.MongoClient('localhost', 27017)\r\n self.db = self.mongo_client['Weibo']\r\n self.weibo_table = self.db['try3']\r\n\r\n # 递归分解传入的类 直至到原子项\r\n def analyze_data(self, data, dict0={}):\r\n\r\n if isinstance(data, list):\r\n for _item in data:\r\n self.analyze_data(_item)\r\n elif hasattr(data, '__dict__'):\r\n for name, value in vars(data).items():\r\n try:\r\n dict0[name] = ''\r\n self.analyze_data(value, dict0=dict0[name])\r\n except:\r\n pass\r\n else:\r\n pass\r\n return data\r\n\r\n def store_in_mongodb(self, data):\r\n result = {}\r\n # 存储新浪用户类\r\n if isinstance(data, sina_people.SinaPeople):\r\n for name, value in vars(data).items():\r\n if unicode(name) != unicode('weibo_list'):\r\n if not isinstance(value, list):\r\n result[str(name)] = str(value)\r\n else:\r\n result[str(name)] = {}\r\n for index, item in enumerate(value):\r\n result[str(name)][str(index)] = {}\r\n for name2, value2 in item.items():\r\n result[str(name)][str(index)][str(name2)] = str(value2)\r\n else:\r\n result[str(name)] = {}\r\n print(type(value))\r\n for index0, item0 in enumerate(value):\r\n result[str(name)][str(index0)] = {}\r\n for name2, value2 in vars(item0).items():\r\n if not isinstance(value2, list):\r\n result[str(name)][str(index0)][str(name2)] = str(value2)\r\n else:\r\n for index, item in enumerate(value2):\r\n result[str(name)][str(index0)][str(name2)] = {}\r\n result[str(name)][str(index0)][str(name2)][str(index)] = {}\r\n for name3, value3 in item.items():\r\n result[str(name)][str(index0)][str(name2)][str(index)][str(name3)] = str(value3)\r\n\r\n # 存储新浪微博类\r\n elif isinstance(data, sina_weibo.SinaWeibo):\r\n for name, value in vars(data).items():\r\n print(name, type(value))\r\n if not isinstance(value, list):\r\n result[str(name)] = str(value)\r\n else:\r\n result[str(name)] = {}\r\n for index, item in enumerate(value):\r\n print(index, type(item))\r\n result[str(name)][str(index)] = {}\r\n for name2, value2 in item.items():\r\n result[str(name)][str(index)][str(name2)] = str(value2)\r\n\r\n elif isinstance(data, dict):\r\n result = data\r\n else:\r\n raise TypeError+\"非法类型!\"\r\n\r\n self.weibo_table.insert_one(result)\r\n\r\n def get_human_info(self):\r\n for data in self.weibo_table.find():\r\n yield data\r\n\r\n def get_stored_information(self):\r\n for data in self.weibo_table.find():\r\n yield data\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "sub_path": "wbcls/sina_store.py", "file_name": "sina_store.py", "file_ext": "py", "file_size_in_byte": 4203, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.setdefaultencoding", "line_number": 9, "usage_type": "call"}, {"api_name": "base.SinaBaseObject", "line_number": 30, "usage_type": "name"}, {"api_name": "pymongo.MongoClient", "line_number": 35, "usage_type": "call"}, {"api_name": "sina_people.SinaPeople", "line_number": 59, "usage_type": "attribute"}, {"api_name": "sina_weibo.SinaWeibo", "line_number": 86, "usage_type": "attribute"}]}
+{"seq_id": "527825840", "text": "# -*- coding: utf-8 -*-\n# @File : lagrange.py\n# @AUTH : swxs\n# @Time : 2018/7/28 14:33\n\nfrom scipy.interpolate import lagrange\n\n\ndef ployinterp_column(s, n, k=5):\n '''\n\n :param s: 列向量\n :param n: 插值的位置\n :param k: 去前后数据的个数\n :return: 插值\n '''\n y = s[list(range(n - k, n)) + list(range(n + 1, n + 1 + k))]\n y = y[y.notnull()]\n return lagrange(y.index, list(y))(n)\n\n", "sub_path": "store/Python/learn/learn_scipy/lagrange.py", "file_name": "lagrange.py", "file_ext": "py", "file_size_in_byte": 432, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "scipy.interpolate.lagrange", "line_number": 19, "usage_type": "call"}]}
+{"seq_id": "314867614", "text": "import logging\nimport random\n\nBOARD = \"board\"\nBCM = \"bcm\"\nOUT = \"out\"\nIN = \"in\"\nHIGH = \"high\"\nLOW = \"low\"\nRISING = 10\n\ndefinedPin = {}\n\nclass pwmClass(object):\n def __init__(self, pin, maxValue):\n self.pin = pin\n self.maxValue = maxValue\n\n def start(self, value):\n logging.info(\"PWM START, Pin {0} : Value {1}\".format(self.pin, value))\n\n def ChangeDutyCycle(self, frequency):\n logging.info(\"PWM Change, Pin {0} : Value {1}\".format(self.pin, frequency))\n\n\ndef output(pin, value):\n try:\n if definedPin[pin] == \"out\":\n logging.info(\"{0} : {1}\".format(pin, value))\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\n\ndef input(pin):\n try:\n if definedPin[pin] == \"in\":\n return bool(random.getrandbits(1))\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\n\ndef setmode(mode):\n logging.info(mode)\n\n\ndef setup(pin, value):\n try:\n definedPin[pin]\n raise ValueError(\"GPIO Pin {} has already been setup\".format(pin))\n except KeyError:\n definedPin[pin] = value\n logging.info(\"{0} : {1}\".format(pin, value))\n\n\ndef PWM(pin, maxValue):\n try:\n if definedPin[pin] == \"out\":\n logging.info(\"PWM Define, Pin {0}: maxValue {1}\".format(pin, maxValue))\n return pwmClass(pin, maxValue)\n else:\n raise ValueError(\"GPIO Pin {} has not been set to OUT\".format(pin))\n\n except KeyError:\n raise ValueError(\"GPIO Pin {} has not been setup\".format(pin))\n\ndef add_event_detect(pin1, pin2, callback=10, **kw):\n pass\n\n\ndef cleanup():\n logging.info(\"clean-up\")\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n\n import random\n\n\n setmode(BCM)\n setup(12, OUT)\n\n a = PWM(12, 100)\n a.start(1)\n a.ChangeDutyCycle(50)\n", "sub_path": "RaspberryEmulaters/GPIO.py", "file_name": "GPIO.py", "file_ext": "py", "file_size_in_byte": 2076, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "logging.info", "line_number": 20, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 23, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 29, "usage_type": "call"}, {"api_name": "random.getrandbits", "line_number": 40, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 49, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 58, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 64, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 77, "usage_type": "call"}, {"api_name": "logging.basicConfig", "line_number": 81, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 81, "usage_type": "attribute"}]}
+{"seq_id": "360387529", "text": "# searcher.py\nimport json\nfrom flask import Flask\nimport pymongo\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nstop_words = set(stopwords.words('english'))\nfrom math import log10\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nclass Searcher():\n\n def __init__(self):\n self.search = \"\"\n\n def tf_idf_query(self, db):\n tf_idfDict = {}\n searchQuery = self.queryWordFreqCounter(self.search)\n for word, count in searchQuery.items():\n collection = db[word].find_one({\"idf\": {\"$gt\": 0}})\n if collection != None:\n idf = collection['idf']\n tf = (1 + log10(count))\n tf_idf = tf * idf\n tf_idfDict[word]= tf_idf\n else:\n pass\n return tf_idfDict\n\n def cosine_similarity(self, db):\n scores = []\n tf_idfQueDict = self.tf_idf_query(db)\n for word, tf_idfQue in tf_idfQueDict.items():\n for collection in db[word].find({\"tf_idf\": {\"$gt\": 0}}):\n loc = collection['location']\n tf_idfDoc = collection['tf_idf']\n docLen = collection['docLen']\n score = (tf_idfQue * tf_idfDoc)/collection['docLen']\n scores.append([loc, score])\n scores = sorted(scores, key=lambda score:score[1], reverse=True)\n finalScores = Counter(score[0] for score in scores)\n [score for score in scores if finalScores[score[0]] == 1]\n return finalScores\n\n def queryWordFreqCounter(self, query):\n searchWords = []\n words = query.split()\n for word in words:\n if len(word) > 0 and word.isalnum() and word not in stop_words:\n searchWords.append(word)\n return dict(Counter(searchWords))\n\n def getSearchInput(self):\n search = \"\"\n search = input(\"Input Search:\\n\")\n self.search = search\n\n def tf(self, wordFrequency):\n return(1 + log10(wordFrequency))\n\n def results(self, db, search):\n if len(search.split()) > 1:\n return(self.cosine_similarity(db))\n else:\n scores = []\n for files in db[search].find():\n scores.append([files['location'], self.tf(files['frequency'])])\n scores = sorted(scores, key=lambda score:score[1], reverse=True)\n return scores\n\n\n\nif __name__ == \"__main__\":\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db = client[\"WEBPAGES\"]\n\n engine = Searcher()\n engine.getSearchInput()\n scores = dict(engine.results(db, engine.search))\n with open('{json file of webpage name and number from given data}') as bookkeeping:\n book = json.load(bookkeeping)\n\n print(\"========================\")\n print(\"====== Results =========\")\n counter = 1\n for key, value in scores.items():\n print(\"\\n\", counter, \". \", book[key])\n counter = counter + 1\n print(\"========================\")\n", "sub_path": "searcher.py", "file_name": "searcher.py", "file_ext": "py", "file_size_in_byte": 2978, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "nltk.corpus.stopwords.words", "line_number": 7, "usage_type": "call"}, {"api_name": "nltk.corpus.stopwords", "line_number": 7, "usage_type": "name"}, {"api_name": "math.log10", "line_number": 23, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 41, "usage_type": "call"}, {"api_name": "collections.Counter", "line_number": 51, "usage_type": "call"}, {"api_name": "math.log10", "line_number": 59, "usage_type": "call"}, {"api_name": "pymongo.MongoClient", "line_number": 74, "usage_type": "call"}, {"api_name": "json.load", "line_number": 81, "usage_type": "call"}]}
+{"seq_id": "404137811", "text": "import re\nimport yaml\nfrom django.http import HttpResponse, Http404\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom pymongo.mongo_client import MongoClient\n\nspace_nums =[\n ('yuki_plus', 1),\n ('siokya', 2),\n ('MMM37', 3),\n ('iede_02', 4),\n ('COP__', 5),\n ('kiriuru', 6),\n ('teppan38', 7),\n ('coromo_saku2', 7),\n ('cafemoca19', 7),\n ('k4n6m9', 8),\n ('miyukisum', 9),\n ('ripo_day', 10),\n ('harapeco_pymr', 10),\n ('yuki8p', 11),\n ('ringosh_', 12),\n ('ISANAinUSA', 13),\n ('rikuK993', 14),\n ('puripash', 15),\n ('MyaMyaru', 16),\n ('nurumi_p', 17),\n ('EPI_prism', 17),\n ('jyojyojyo_', 18),\n ('kinta_ex', 19),\n ('418sds', 19),\n ('koshia_rl', 20),\n ('vamddkijg', 21),\n ('VegA__AnastasiA', 22),\n ('pa_sh_pr', 23),\n ('k_y_ma_', 23),\n ('popn_mitsuki', 24),\n ('rio_tarantella', 25),\n ('kk_sub', 26),\n ('kumodoriren', 27),\n ('mtk1600', 28),\n ('kirakira_tter08', 29),\n ('sakachico', 29),\n ('l0kinann', 30),\n ('an_dan_te074', 30),\n ('ANATANO_ARATANI', 31),\n ('tekkoubondo', 32),\n ('kondokodanuki', 33),\n ('naomachi1800ml', 34),\n ('houiP', 35),\n ('Fureiya14', 36),\n ('oremaka_000', 37),\n ('azuma333', 37),\n ('sasa_0416', 38),\n ('nanaox16', 39),\n ('eifonen', 40),\n ('chiharutosayaka', 41),\n ('White_0422', 42),\n ('qEouo', 43),\n ('indigohr_25', 44),\n ('shiopoko_6o6', 45),\n ('hutarun', 46),\n ('wt_prism', 1000),\n ('ino_zip', 1000),\n ('akarin1971', 1000),\n]\n\ndef index(request, page='1', edit=None):\n page = int(page)\n cols = MongoClient().prikoso_2016.tweets\n users = []\n for name, num in sorted(space_nums, key=lambda x: x[1]): # numでソート\n # ページ外のユーザを除外\n if not 10 * (page - 1) <= num < 10 * page: # ex. page=2 ならば #10-19 を表示\n continue\n \n user = cols.find_one({'tweet.user.screen_name': name})\n if user:\n user = user['tweet']['user']\n if edit: # 編集するときは全件表示する\n pins = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'pin': {'$exists': True},\n }).sort('tweets.id')\n tweets = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'pin': {'$exists': False},\n }).sort('tweets.id')\n print(name, pins.count() + tweets.count())\n \n else: # 通常時はdisabaleされたものを除外する\n pins = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'disable': {'$exists': False},\n 'pin': {'$exists': True},\n }).sort('tweets.id')\n tweets = cols.find({\n 'tweet.user.screen_name': name,\n 'tweet.extended_entities': {'$exists': True},\n 'tweet.text': {'$not': re.compile(r'^RT ')},\n 'disable': {'$exists': False},\n 'pin': {'$exists': False},\n }).sort('tweets.id')\n\n if edit:\n users.append({\n 'space_num': num,\n 'user': user,\n 'tweets_list': [pins, tweets[:30 - pins.count()]],\n })\n else: # editモードでない時は、表示ツイート数を制限する\n users.append({\n 'space_num': num,\n 'user': user,\n 'tweets_list': [pins, tweets[:max(0, 6 - pins.count())]],\n })\n\n return render(request, 'prikoso_2016_circle_checker/index.html', {'users': users, 'edit': edit})\n\ndef disable(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$set': {'disable': True}})\n print('disabled:', id)\n return HttpResponse('')\n\ndef enable(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$unset': {'disable': ''}})\n print('enabled:', id)\n return HttpResponse('')\n\ndef pin(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$set': {'pin': True}})\n print('pinned:', id)\n return HttpResponse('')\n\ndef unpin(request):\n id = request.POST.get('id')\n cols = MongoClient().prikoso_2016.tweets\n cols.update({'tweet.id_str': id}, {'$unset': {'pin': ''}})\n print('unpinned:', id)\n return HttpResponse('')\n", "sub_path": "views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4995, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pymongo.mongo_client.MongoClient", "line_number": 71, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 85, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 91, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 100, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 107, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 125, "usage_type": "call"}, {"api_name": "pymongo.mongo_client.MongoClient", "line_number": 129, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 132, "usage_type": "call"}, {"api_name": "pymongo.mongo_client.MongoClient", "line_number": 136, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 139, "usage_type": "call"}, {"api_name": "pymongo.mongo_client.MongoClient", "line_number": 143, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 146, "usage_type": "call"}, {"api_name": "pymongo.mongo_client.MongoClient", "line_number": 150, "usage_type": "call"}, {"api_name": "django.http.HttpResponse", "line_number": 153, "usage_type": "call"}]}
+{"seq_id": "372852368", "text": "import pytest\nimport os\nimport brightway2 as bw2\n\nTEST_MODEL_NAME = \"Test_model\"\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef setup_fixtures(request):\n\n\tprint('RUNNING SETUP FIXTURE')\n\n\tif TEST_MODEL_NAME in bw2.projects:\n\t\tbw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)\n\n\tbw2.projects.set_current(TEST_MODEL_NAME)\n\tbw2.bw2setup()\n\t\n\n\tscript_path = os.path.dirname(os.path.realpath(__file__))\n\tecospold_folder = os.path.join(\"tests\", \"assets\", \"datasets\")\n\tecospold_path = os.path.join(script_path, ecospold_folder)\n\tprint(ecospold_path)\n\n\tei = bw2.SingleOutputEcospold2Importer(ecospold_path, \"Ecoinvent3_3_cutoff\")\n\tei.apply_strategies()\n\tei.statistics()\n\tei.write_database()\n\n\tbw2.projects.set_current('default')\n\t\n\tdef teardown_fixtures():\n\t\tprint('TEAR IT DOWN!!')\n\t\tbw2.projects.set_current('default')\n\t\t\n\t\tif TEST_MODEL_NAME in bw2.projects:\n\t\t\tbw2.projects.delete_project(name=TEST_MODEL_NAME, delete_dir=True)\n\t\n\trequest.addfinalizer(teardown_fixtures)\n\n\n\n\n", "sub_path": "conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 993, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "brightway2.projects", "line_number": 12, "usage_type": "attribute"}, {"api_name": "brightway2.projects.delete_project", "line_number": 13, "usage_type": "call"}, {"api_name": "brightway2.projects", "line_number": 13, "usage_type": "attribute"}, {"api_name": "brightway2.projects.set_current", "line_number": 15, "usage_type": "call"}, {"api_name": "brightway2.projects", "line_number": 15, "usage_type": "attribute"}, {"api_name": "brightway2.bw2setup", "line_number": 16, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path", "line_number": 19, "usage_type": "attribute"}, {"api_name": "os.path.realpath", "line_number": 19, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 20, "usage_type": "call"}, {"api_name": "os.path", "line_number": 20, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 21, "usage_type": "call"}, {"api_name": "os.path", "line_number": 21, "usage_type": "attribute"}, {"api_name": "brightway2.SingleOutputEcospold2Importer", "line_number": 24, "usage_type": "call"}, {"api_name": "brightway2.projects.set_current", "line_number": 29, "usage_type": "call"}, {"api_name": "brightway2.projects", "line_number": 29, "usage_type": "attribute"}, {"api_name": "brightway2.projects.set_current", "line_number": 33, "usage_type": "call"}, {"api_name": "brightway2.projects", "line_number": 33, "usage_type": "attribute"}, {"api_name": "brightway2.projects", "line_number": 35, "usage_type": "attribute"}, {"api_name": "brightway2.projects.delete_project", "line_number": 36, "usage_type": "call"}, {"api_name": "brightway2.projects", "line_number": 36, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 7, "usage_type": "call"}]}
+{"seq_id": "14236161", "text": "#\n# Updated: 22-Aug-2018\n#\n\nfrom PIL import Image\nimport os\nimport imghdr\nfrom os import listdir\nfrom os.path import isfile, join\nimport ntpath\nimport errno\n\n\ndef is_jpg(some_file):\n result = False\n if imghdr.what(some_file) == 'jpeg':\n result = True\n return result\n\n\ndef is_png(some_file):\n result = False\n if imghdr.what(some_file) == 'png':\n result = True\n return result\n\n\ndef is_valid_image(some_file):\n result = True\n try:\n im = Image.open(some_file)\n im.close()\n except IOError:\n result = False\n return result\n\n\ndef is_valid_jpg(some_file):\n result = False\n if is_valid_image(some_file) and is_jpg(some_file):\n result = True\n return result\n\n\ndef is_valid_png(some_file):\n result = False\n if is_valid_image(some_file) and is_png(some_file):\n result = True\n return result\n\n\ndef make_white_bg_transparent(img_file):\n img = Image.open(img_file)\n os.remove(img_file)\n img = img.convert(\"RGBA\")\n datas = img.getdata()\n\n newData = []\n for item in datas:\n if item[0] > 253 and item[1] > 253 and item[2] > 253:\n newData.append((255, 255, 255, 0))\n else:\n newData.append(item)\n\n img.putdata(newData)\n new_file_name = os.path.splitext(img_file)[0]+'.png'\n img.save(new_file_name, \"PNG\")\n return new_file_name\n\n\ndef convert_image_file_to_jpg(img_file):\n \"\"\"\n Creates JPEG file from any image file\n img_file : String\n The name of source file\n \"\"\"\n img = Image.open(img_file).convert('RGB')\n os.remove(img_file)\n new_file_name = os.path.splitext(img_file)[0]+'.jpg'\n img.save(new_file_name, 'jpeg')\n return new_file_name\n\n\ndef convert_image_file_to_png(img_file):\n \"\"\"\n Creates PNG file from any image file\n img_file : String\n The name of source file\n \"\"\"\n img = Image.open(img_file)\n os.remove(img_file)\n new_file_name = os.path.splitext(img_file)[0]+'.png'\n img.save(new_file_name, 'png')\n return new_file_name\n\n\ndef get_files_names_in_folder(some_folder):\n return [f for f in listdir(some_folder) if isfile(join(some_folder, f))]\n\n\ndef get_subfolders(some_folder):\n return [f for f in listdir(some_folder) if os.isdir(join(some_folder, f))]\n\n\ndef get_files_in_folder(some_folder):\n result = []\n for this_file in get_files_names_in_folder(some_folder):\n this_file_path = some_folder + \"/\" + this_file\n result.append(this_file_path)\n return result\n\n\ndef get_valid_pngs(some_folder):\n result = []\n all_files = get_files_names_in_folder(some_folder)\n for this_file in all_files:\n file_path = some_folder + \"/\" + this_file\n if is_valid_png(file_path):\n result.append(file_path)\n return result\n\n\ndef sort_images(some_folder):\n result = {'jpg': [], 'png': [], 'None': []}\n for some_file in get_files_in_folder(some_folder):\n if is_valid_image(some_file):\n if is_jpg(some_file):\n result['jpg'].append(some_file)\n else:\n if is_png(some_file):\n result['png'].append(some_file)\n else:\n result['None'].append(some_file)\n else:\n result['None'].append(some_file)\n return result\n\n\ndef get_file_name_from_path(some_path):\n return ntpath.basename(some_path)\n\n\ndef rotated_copy(original_image_file, folder_to_store, rotation_angle):\n img_pre = Image.open(original_image_file)\n img = img_pre.rotate(rotation_angle, expand=True)\n original_name_ext_cut = os.path.splitext(get_file_name_from_path(\n original_image_file))[0]\n new_img_name = folder_to_store + \\\n \"/\" + original_name_ext_cut + \\\n \"_\" + str(rotation_angle) + \".jpg\"\n img.save(new_img_name)\n return new_img_name\n\n\ndef rotated_copies(original_image_file, folder_to_store, rotation_angles):\n result = []\n for some_angle in rotation_angles:\n result.append(\n rotated_copy(\n original_image_file, folder_to_store, some_angle))\n return result\n\n\ndef mirror_top_bottom_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).transpose(Image.FLIP_TOP_BOTTOM)\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + \\\n original_name_ext_cut + \"_ft\" + \".jpg\"\n img.save(new_img_name)\n return new_img_name\n\n\ndef grayscale_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).convert('LA').convert('RGB')\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + original_name_ext_cut + \\\n \"_gs\" + \".jpg\"\n img.save(new_img_name, 'jpeg')\n return new_img_name\n\n\ndef monochrome_copy(original_image_file, folder_to_store):\n img = Image.open(original_image_file).convert('1').convert('RGB')\n original_name_ext_cut = os.path.splitext(\n get_file_name_from_path(original_image_file))[0]\n new_img_name = folder_to_store + \"/\" + original_name_ext_cut + \\\n \"_mc\" + \".jpg\"\n img.save(new_img_name, 'jpeg')\n return new_img_name\n\n\ndef resize_file(original_image_file, output_image_file, maxw, maxh):\n \"\"\"\n Creates resized image file from given one\n original_image_file : String\n The name of source file\n output_image_file : String\n The name of file to save the result\n maxw :\n Max allowed width\n maxw :\n Max allowed height\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n ratio = min(float(maxw) / int(width), float(maxh) / int(height))\n im = im.resize((int(width*ratio), int(height*ratio)), Image.ANTIALIAS)\n im.save(output_image_file, \"JPEG\")\n return output_image_file\n\n\ndef put_into_rect(original_image_file, output_image_file, rw, rh):\n im = Image.open(original_image_file)\n width, height = im.size\n ratio = min(float(rw) / int(width), float(rh) / int(height))\n im = im.resize((int(width*ratio), int(height*ratio)), Image.ANTIALIAS)\n\n resim = Image.new('RGB', (rw, rh), (255, 255, 255))\n width, height = im.size\n offset = ((rw - width) / 2, (rh - height) / 2)\n resim.paste(im, offset)\n resim.save(output_image_file, \"JPEG\")\n return output_image_file\n\n\ndef cut_area_around(original_image_file, x, y, w, h, output_file=False):\n \"\"\"\n Razor area around the dot (x, y)\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n left = max(int(round(x-(w/2))), 0)\n box_width = min(w, width-left)\n top = max(int(round(y-(h/2))), 0)\n box_height = min(h, height-top)\n croped = im.crop((left, top, box_width+left, box_height+top))\n mode_type = \"PNG\" if is_png(original_image_file) else \"JPEG\"\n dw, dh = get_dimensions(croped)\n result = croped if dw*dh > 0 else False\n if output_file and result:\n save_image(croped, output_file, mode_type)\n return result\n\n\ndef get_dimensions(image):\n \"\"\"\n Return image dimensions tuple\n Usage example:\n width, height = imm.get_dimensions(image_file)\n or\n width, height = imm.get_dimensions(image_object)\n \"\"\"\n im = image\n if isinstance(image, basestring):\n im = Image.open(image)\n return im.size\n\n\ndef save_image(image_object, file_path, mode_type=\"JPEG\"):\n \"\"\"\n Saves image object to the file.\n In will create the directory if one does not exist.\n \"\"\"\n if not os.path.exists(os.path.dirname(file_path)):\n try:\n os.makedirs(os.path.dirname(file_path))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n image_object.save(file_path, mode_type)\n\n\ndef cut_tending_area(original_image_file, x, y, w, h, output_file=False):\n \"\"\"\n Cuts rectangle area around the dot (x, y). If area boundaries are out of\n image dimenssions then area center will be moved on order to put the area\n into image.\n original_image_file : String\n The name of source file\n output_file : String [optional]\n The name of file to save the result\n It is False by default, you may leave it empty if you don't need to\n save file.\n w :\n Rectangle area width\n h :\n Rectangle area height\n \"\"\"\n im = Image.open(original_image_file)\n width, height = im.size\n result = False\n if w <= width and h <= height:\n if x < w/2:\n x = int(round(w/2))\n if x + w/2 > width:\n x = int(width - round(w/2))\n if y < h/2:\n y = int(round(h/2))\n if y + h/2 > height:\n y = int(round(height - h/2))\n box_x = int(round(x-w/2))\n box_y = int(round(y-h/2))\n croped = im.crop((box_x, box_y, box_x+w, box_y+h))\n mode_type = \"PNG\" if is_png(original_image_file) else \"JPEG\"\n if output_file:\n save_image(croped, output_file, mode_type)\n result = croped\n return result\n", "sub_path": "imm.py", "file_name": "imm.py", "file_ext": "py", "file_size_in_byte": 9106, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "imghdr.what", "line_number": 16, "usage_type": "call"}, {"api_name": "imghdr.what", "line_number": 23, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 31, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 31, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 53, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 53, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 54, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 66, "usage_type": "call"}, {"api_name": "os.path", "line_number": 66, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 77, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 77, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 90, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 90, "usage_type": "name"}, {"api_name": "os.remove", "line_number": 91, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 92, "usage_type": "call"}, {"api_name": "os.path", "line_number": 92, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 98, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 98, "usage_type": "call"}, {"api_name": "os.listdir", "line_number": 102, "usage_type": "call"}, {"api_name": "os.isdir", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 102, "usage_type": "call"}, {"api_name": "ntpath.basename", "line_number": 140, "usage_type": "call"}, {"api_name": "PIL.Image.open", "line_number": 144, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 144, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 146, "usage_type": "call"}, {"api_name": "os.path", "line_number": 146, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 165, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 165, "usage_type": "name"}, {"api_name": "PIL.Image.FLIP_TOP_BOTTOM", "line_number": 165, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 166, "usage_type": "call"}, {"api_name": "os.path", "line_number": 166, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 175, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 175, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 176, "usage_type": "call"}, {"api_name": "os.path", "line_number": 176, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 185, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 185, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 186, "usage_type": "call"}, {"api_name": "os.path", "line_number": 186, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 206, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 206, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 209, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 209, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 215, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 215, "usage_type": "name"}, {"api_name": "PIL.Image.ANTIALIAS", "line_number": 218, "usage_type": "attribute"}, {"api_name": "PIL.Image", "line_number": 218, "usage_type": "name"}, {"api_name": "PIL.Image.new", "line_number": 220, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 220, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 232, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 232, "usage_type": "name"}, {"api_name": "PIL.Image.open", "line_number": 257, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 257, "usage_type": "name"}, {"api_name": "os.path.exists", "line_number": 266, "usage_type": "call"}, {"api_name": "os.path", "line_number": 266, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 266, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 268, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 268, "usage_type": "call"}, {"api_name": "os.path", "line_number": 268, "usage_type": "attribute"}, {"api_name": "errno.EEXIST", "line_number": 270, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 291, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 291, "usage_type": "name"}]}
+{"seq_id": "303822308", "text": "\n\"\"\"Calculates how much time it will take to pay down\nan amount owed for a monthly amount paid\"\"\"\n\nimport datetime\nimport calendar\n\n\ndef time_till_repaid(total_owed=0,\n interest_rate=0.00,\n monthly_payement=1,\n show_progress=False):\n\n today = datetime.date.today()\n\n # Start date is first day of next month\n days_in_month = calendar.monthrange(today.year, today.month)[1]\n days_left_in_month = days_in_month - today.day\n\n start_date = today + datetime.timedelta(days=days_left_in_month + 1)\n\n end_date = start_date\n\n while total_owed > 0:\n\n total_owed += (interest_rate / 12) * total_owed\n total_owed -= monthly_payement\n total_owed = 0 if total_owed < 0 else round(total_owed, 2)\n\n if show_progress is True:\n print(f'{end_date}\t${total_owed:.2f}')\n\n # Increment 'end_date' by the amount of days in the month\n days_in_month = calendar.monthrange(end_date.year, end_date.month)[1]\n end_date = end_date + datetime.timedelta(days=days_in_month)\n\n # Get the difference in time between the start and end dates\n years = round((end_date - start_date).days / 365, 1)\n months = int(round(round(years - int(years), 2) * 12, 0))\n\n # Print amount of time it will take to pay the amount owed\n s_ = '' if months < 2 else 's'\n if years > 1:\n s = '' if years < 2 else 's'\n print(f'{years:.0f} year{s}, {months} month{s_}')\n else:\n print(f'{months:.0f} month{s_}')\n\n\n# Constants to plug\ntotal_owed = 10000\ninterest_rate = 0.00\nmonthly_payement = 100.50\nshow_progress = False\n\ntime_till_repaid(total_owed, interest_rate, monthly_payement, show_progress)\n", "sub_path": "Python/PythonArchive/time_till_debt_paid.py", "file_name": "time_till_debt_paid.py", "file_ext": "py", "file_size_in_byte": 1719, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "datetime.date.today", "line_number": 14, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 14, "usage_type": "attribute"}, {"api_name": "calendar.monthrange", "line_number": 17, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 20, "usage_type": "call"}, {"api_name": "calendar.monthrange", "line_number": 34, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 35, "usage_type": "call"}]}
+{"seq_id": "319076985", "text": "import pandas as pd\nimport freehead as fh\nimport numpy as np\nfrom scipy.signal import savgol_filter\nfrom collections import OrderedDict\nimport warnings\n\n\ndef prepend_nan(arr, axis=0, n=1):\n pad_shape = [s if i != axis else n for i, s in enumerate(arr.shape)]\n pad = np.full(pad_shape, np.nan, dtype=arr.dtype)\n return np.concatenate((pad, arr), axis=axis)\n\n\ndef apply_analysis_pipeline_for_all_trials(df: pd.DataFrame):\n\n warnings.filterwarnings('ignore', category=np.RankWarning)\n \n df.rename(columns={'shift_percent_approx': 'shift_percent'}, inplace=True)\n\n fh.array_apply(\n df,\n OrderedDict([\n # chosen so that to target direction is positive (right to left is positive angle in mathematics)\n ('direction_sign', lambda r: -1 if r['left_to_right'] else +1),\n ('fixation_led', lambda r: r['fixation_led'] if r['left_to_right'] else 254 - r['fixation_led']),\n (('df', 'target_led'), lambda df: df['fixation_led'] - df['direction_sign'] * df['amplitude']),\n (('df', 'starget_led'), lambda df: df['target_led'] - df['direction_sign'] * df['shift']),\n ('is_outward_response', lambda r: r['response'] == ('right' if r['left_to_right'] else 'left')),\n ('response_ward', lambda r: 'outward' if r['is_outward_response'] else 'inward'),\n ('correct_response', lambda r: None if r['shift'] == 0 else 'right' if (r['shift'] > 0) == r['left_to_right'] else 'left'),\n ('is_correct', lambda r: None if r['correct_response'] is None else r['correct_response'] == r['response']),\n ('shift_percent_uni', lambda r: r['shift_percent'] if r['left_to_right'] else -r['shift_percent']),\n # new time index for upsampling\n ('t_sacc', lambda r: np.arange(-400, 801, 5)),\n # pupil data in around saccade interval upsampled\n ('p_data_upsampled', lambda r: fh.interpolate_a_onto_b_time(r['p_data'][:, 2:5],\n 1000 * (r['p_data'][:, 0] - r['t_saccade_started']),\n r['t_sacc'], kind='linear')),\n # optotrak data upsampled\n ('o_data_upsampled', lambda r: fh.interpolate_a_onto_b_time(r['o_data'][:, 3:15],\n 1000 * (r['o_data'][:, 30] - r['t_saccade_started']),\n r['t_sacc'], kind='linear')),\n # latency of pupil signal\n ('pupil_latency', lambda r: fh.interpolate_a_onto_b_time(r['p_data'][:, 1] - r['p_data'][:, 0], 1000 * (\n r['p_data'][:, 0] - r['t_saccade_started']), r['t_sacc'], kind='linear')),\n # rotation of head rigidbody\n ('R_head_world', lambda r: r['helmet'].solve(r['o_data_upsampled'].reshape((-1, 4, 3)))[0]),\n # yaw pitch roll head rigidbody\n ('ypr_head_world', lambda r: fh.to_yawpitchroll(r['R_head_world'])),\n # reference positions of head rigidbody\n ('Ts_head_world', lambda r: r['helmet'].solve(r['o_data_upsampled'].reshape((-1, 4, 3)))[1]),\n # position of fixation led\n ('fixation_pos', lambda r: r['rig'][r['fixation_led'], :]),\n # position of target led\n ('target_pos', lambda r: r['rig'][r['target_led'], :]),\n # position of shifted target led\n ('starget_pos', lambda r: r['rig'][r['starget_led'], :]),\n # vector from eye to target position\n ('eye_to_fixation', lambda r: fh.to_unit(r['fixation_pos'] - r['Ts_head_world'][:, 3, :])),\n # vector from eye to target position\n ('eye_to_target', lambda r: fh.to_unit(r['target_pos'] - r['Ts_head_world'][:, 3, :])),\n # vector from eye to shifted target position\n ('eye_to_starget', lambda r: fh.to_unit(r['starget_pos'] - r['Ts_head_world'][:, 3, :])),\n # gaze vector in head without distortion correction\n ('gaze_in_head_distorted', lambda r: (r['R_eye_head'] @ r['p_data_upsampled'].T).T),\n # gaze vector in head with distortion correction\n ('gaze_in_head',\n lambda r: fh.normals_nonlinear_angular_transform(r['gaze_in_head_distorted'], r['nonlinear_parameters'])),\n # gaze angles in head\n ('gaze_in_head_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['gaze_in_head']))),\n # gaze vector in world\n ('gaze_in_world', lambda r: np.einsum('tij,tj->ti', r['R_head_world'], r['gaze_in_head'])),\n # gaze angles in world\n ('gaze_in_world_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['gaze_in_world']))),\n # angles from eye to target in world\n ('eye_to_target_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_target']))),\n # difference of eye to target angles and gaze in world\n ('gaze_angle_vs_target', lambda r: r['gaze_in_world_ang'] - r['eye_to_target_ang']),\n # angles from eye to shifted target in world\n ('eye_to_starget_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_starget']))),\n # difference of eye to shifted target angles and gaze in world\n ('gaze_angle_vs_starget', lambda r: r['gaze_in_world_ang'] - r['eye_to_starget_ang']),\n # angles from eye to fixation in world\n ('eye_to_fixation_ang', lambda r: np.rad2deg(fh.to_azim_elev(r['eye_to_fixation']))),\n # difference of eye to fixation angles and gaze in world\n ('gaze_angle_vs_fixation', lambda r: r['gaze_in_world_ang'] - r['eye_to_fixation_ang']),\n # time steps\n ('dt', lambda r: fh.padded_diff(r['t_sacc'])),\n # velocity of difference of eye to target angles and gaze in world\n ('gaze_angvel_vs_target', lambda r: fh.padded_diff(r['gaze_angle_vs_target']) / r['dt'][:, None]),\n ('gaze_angvel_vs_target_savgol',\n lambda r: prepend_nan(\n savgol_filter(r['gaze_angvel_vs_target'][1:, ...], 3, 1, axis=0),\n axis=0)),\n # saccade detection engbert & mergenthaler\n ('eng_merg', lambda r: fh.sacc_dec_engb_merg_horizontal(r['gaze_angle_vs_target'][:, 0],\n r['gaze_angvel_vs_target_savgol'][:, 0], 6, 5)),\n ]),\n add_inplace=True,\n print_log=True\n )\n\n df.drop(\n columns=[\n 'p_data',\n 'o_data',\n # 'helmet',\n 'o_data_upsampled',\n 'p_data_upsampled',\n 'gaze_in_head_distorted',\n ],\n inplace=True\n )\n", "sub_path": "freehead/analysis/apply_analysis_pipeline_for_all_trials.py", "file_name": "apply_analysis_pipeline_for_all_trials.py", "file_ext": "py", "file_size_in_byte": 6775, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.full", "line_number": 11, "usage_type": "call"}, {"api_name": "numpy.nan", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.concatenate", "line_number": 12, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 15, "usage_type": "attribute"}, {"api_name": "warnings.filterwarnings", "line_number": 17, "usage_type": "call"}, {"api_name": "numpy.RankWarning", "line_number": 17, "usage_type": "attribute"}, {"api_name": "freehead.array_apply", "line_number": 21, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 35, "usage_type": "call"}, {"api_name": "freehead.interpolate_a_onto_b_time", "line_number": 37, "usage_type": "call"}, {"api_name": "freehead.interpolate_a_onto_b_time", "line_number": 41, "usage_type": "call"}, {"api_name": "freehead.interpolate_a_onto_b_time", "line_number": 45, "usage_type": "call"}, {"api_name": "freehead.to_yawpitchroll", "line_number": 50, "usage_type": "call"}, {"api_name": "freehead.to_unit", "line_number": 60, "usage_type": "call"}, {"api_name": "freehead.to_unit", "line_number": 62, "usage_type": "call"}, {"api_name": "freehead.to_unit", "line_number": 64, "usage_type": "call"}, {"api_name": "freehead.normals_nonlinear_angular_transform", "line_number": 69, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 71, "usage_type": "call"}, {"api_name": "freehead.to_azim_elev", "line_number": 71, "usage_type": "call"}, {"api_name": "numpy.einsum", "line_number": 73, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 75, "usage_type": "call"}, {"api_name": "freehead.to_azim_elev", "line_number": 75, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 77, "usage_type": "call"}, {"api_name": "freehead.to_azim_elev", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 81, "usage_type": "call"}, {"api_name": "freehead.to_azim_elev", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.rad2deg", "line_number": 85, "usage_type": "call"}, {"api_name": "freehead.to_azim_elev", "line_number": 85, "usage_type": "call"}, {"api_name": "freehead.padded_diff", "line_number": 89, "usage_type": "call"}, {"api_name": "freehead.padded_diff", "line_number": 91, "usage_type": "call"}, {"api_name": "scipy.signal.savgol_filter", "line_number": 94, "usage_type": "call"}, {"api_name": "freehead.sacc_dec_engb_merg_horizontal", "line_number": 97, "usage_type": "call"}]}
+{"seq_id": "145932976", "text": "\n# -*- coding: utf-8 -*-\n\nfrom webapp2 import WSGIApplication\nfrom core.sugar import SugarRequestHandler\n\n\nclass MessageManagementHandler(SugarRequestHandler):\n\n def post(self):\n\n \"\"\"\n Obtiene los mensajes del buzón correspondiente al día recién cerrado.\n \"\"\"\n\n from core.logger import Logger\n from json import loads\n from clients.gmail_api import GmailApiClient\n\n try:\n # Obtenemos los datos de la petición.\n sender = loads(self.request.get(\"sender_account\"))\n recipients = loads(self.request.get(\"recipient_accounts\"))\n # Obtenemos los mensajes de la cuenta emisora.\n messages = self.find_messages(sender[\"email\"])\n resource = GmailApiClient(sender[\"email\"]).messages()\n if messages:\n # Por cada mensaje encontrado.\n for message in messages:\n # Creamos un mensaje.\n mssg = GmailApiClient.Message(resource.get(id=message[\"id\"]))\n # Creamos un mensaje para mappear el mensaje obtenido.\n mssg2 = GmailApiClient.MessageMapper()\n Logger.info(u\"From address: {}\".format(mssg.get_from()))\n Logger.info(u\"Sender address: {}\".format(mssg.get_sender()))\n # Seteamos los campos que nos interesan.\n mssg2.set_html_body(mssg.get_html_body())\n mssg2.set_subject(mssg.get_from() + \"$ \" + mssg.get_subject())\n mssg2.add_header(\"Return-Path\", u\"{}\".format(mssg.get_from()))\n mssg2.add_header(\"X-Env-Sender\", u\"{}\".format(mssg.get_from()))\n mssg2.from_address = u\"{}\".format(mssg.get_from())\n Logger.info(u\"New from: {}\".format(mssg2.from_address))\n # Agregamos los buzones receptores.\n for recipient in recipients:\n mssg2.add_recipient(recipient[\"email\"])\n sender_email = sender[\"email\"]\n response = GmailApiClient(sender_email).send_message(mssg2, sender_email)\n # Si obtenemos respuesta, borramos los mensajes del buzón emisor.\n if response:\n GmailApiClient(sender_email).messages().delete(\n id=message[\"id\"],\n userId=sender_email\n )\n\n except Exception as e:\n Logger.error(e)\n\n @classmethod\n def find_messages(cls, email):\n\n \"\"\"\n Obtiene la lista de mensajes recibidos en el buzón.\n :param email: Buzón de correo.\n :return: La lista de mensajes.\n \"\"\"\n\n from clients.gmail_api import GmailApiClient\n from core.logger import Logger\n\n try:\n messages = []\n resource = GmailApiClient(email).messages()\n page_token = None\n while True:\n response = resource.list(\n pageToken=page_token,\n includeSpamTrash=False,\n q=\"in:inbox is:unread\"\n )\n if \"messages\" in response:\n for message in response[\"messages\"]:\n if not any(x for x in messages if x[\"id\"] == message[\"id\"]):\n messages.append(message)\n if \"nextPageToken\" in response:\n page_token = response[\"nextPageToken\"]\n else:\n break\n except Exception as e:\n Logger.error(e)\n raise e\n return messages\n\n\nclass MessageLabelingHandler(SugarRequestHandler):\n\n def post(self):\n\n \"\"\"\n Etiqueta los mensajes del día recién cerrado.\n \"\"\"\n\n from json import loads\n from core.logger import Logger\n from clients.gmail_api import GmailApiClient\n from managers.rules import RulesManager\n\n try:\n # Obtenemos los datos de la petición.\n recipient = loads(self.request.get(\"recipient_account\"))\n messages = MessageManagementHandler.find_messages(recipient[\"email\"])\n resource = GmailApiClient(recipient[\"email\"]).messages()\n for message in messages:\n mssg = GmailApiClient.Message(resource.get(id=message[\"id\"]))\n # Por cada label existente en cada buzón receptor.\n for label in recipient[\"labels\"]:\n # Aplicamos la regla existente por cada label.\n for rule in label[\"rules\"]:\n rule = RulesManager(rule_id=rule[\"id\"]).get()\n if self.apply_rule(\n rule.rule,\n mssg.get_plain_body() if rule.field == \"body\" else\n mssg.get_from() if rule.field == \"to\" else\n mssg.get_subject(),\n message[\"id\"],\n label[\"gmail_id\"],\n resource\n ):\n break\n\n except Exception as e:\n Logger.error(e)\n\n def apply_rule(self, rule, field, message_id, label_id, resource):\n\n \"\"\"\n Busca una regla a aplicar en el subject del mensaje.\n :param rule: Regla a aplicar.\n :param field: Campo a aplicar la regla.\n :param message_id: Identificador del mensaje.\n :param label_id: Identificador de la label.\n :param resource: Recurso Gmail API.\n \"\"\"\n\n from re import MULTILINE, IGNORECASE, search\n from core.logger import Logger\n\n matches = search(rule, field, MULTILINE | IGNORECASE)\n if matches:\n Logger.info(\"Labeling message: {}\".format(message_id))\n # Modificamos el mensaje.\n resource.modify(\n id=message_id,\n body={\n \"addLabelIds\": [label_id], # Añadimos la etiqueta indicada.\n \"removeLabelIds\": [\"INBOX\"] # Quitamos el mensaje del inbox.\n }\n )\n return True\n return False\n\napp = WSGIApplication(\n routes=[\n (r\"^/tasks/message/management$\", MessageManagementHandler),\n (r\"^/tasks/message/labeling$\", MessageLabelingHandler)\n ],\n debug=True\n)\n", "sub_path": "handlers/tasks.py", "file_name": "tasks.py", "file_ext": "py", "file_size_in_byte": 6425, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "core.sugar.SugarRequestHandler", "line_number": 8, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 22, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 23, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 26, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient.Message", "line_number": 31, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 31, "usage_type": "name"}, {"api_name": "clients.gmail_api.GmailApiClient.MessageMapper", "line_number": 33, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 33, "usage_type": "name"}, {"api_name": "core.logger.Logger.info", "line_number": 34, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 34, "usage_type": "name"}, {"api_name": "core.logger.Logger.info", "line_number": 35, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 35, "usage_type": "name"}, {"api_name": "core.logger.Logger.info", "line_number": 42, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 42, "usage_type": "name"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 47, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 50, "usage_type": "call"}, {"api_name": "core.logger.Logger.error", "line_number": 56, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 56, "usage_type": "name"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 72, "usage_type": "call"}, {"api_name": "core.logger.Logger.error", "line_number": 89, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 89, "usage_type": "name"}, {"api_name": "core.sugar.SugarRequestHandler", "line_number": 94, "usage_type": "name"}, {"api_name": "json.loads", "line_number": 109, "usage_type": "call"}, {"api_name": "{'Logger': 'core.logger.Logger', 'loads': 'json.loads', 'GmailApiClient': 'clients.gmail_api.GmailApiClient'}.find_messages", "line_number": 110, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 111, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient.Message", "line_number": 113, "usage_type": "call"}, {"api_name": "clients.gmail_api.GmailApiClient", "line_number": 113, "usage_type": "name"}, {"api_name": "managers.rules.RulesManager", "line_number": 118, "usage_type": "call"}, {"api_name": "core.logger.Logger.error", "line_number": 131, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 131, "usage_type": "name"}, {"api_name": "re.search", "line_number": 147, "usage_type": "call"}, {"api_name": "re.MULTILINE", "line_number": 147, "usage_type": "name"}, {"api_name": "re.IGNORECASE", "line_number": 147, "usage_type": "name"}, {"api_name": "core.logger.Logger.info", "line_number": 149, "usage_type": "call"}, {"api_name": "core.logger.Logger", "line_number": 149, "usage_type": "name"}, {"api_name": "webapp2.WSGIApplication", "line_number": 161, "usage_type": "call"}]}
+{"seq_id": "33297059", "text": "from telegram.ext import Updater, CommandHandler\n\ndef start (update, context):\n\tupdate.message.reply_text('hola walter clavo')\n\nif __name__=='__main__':\n\n\tupdater = Updater(token='1655048016:AAFkysh83LjUHD47yEDclBupy0TXpcZ4r1s', use_context='True')\n\n\tdp = updater.dispatcher\n\tdp.add_handler(CommandHandler ('start', start))\n\n\tupdater.start_polling()\n\tupdater.idle()\n", "sub_path": "bot.py", "file_name": "bot.py", "file_ext": "py", "file_size_in_byte": 366, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "telegram.ext.Updater", "line_number": 8, "usage_type": "call"}, {"api_name": "telegram.ext.CommandHandler", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "388568440", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Ornothologist produces 6 tab-delimited UTF-8 files and one directory per query.\n# See README.md for details.\n# By: Ericka Menchen-Trevino http://www.ericka.cc/\n\n# python2/3 interoperability\nfrom __future__ import print_function\n\n# Variables to fill in\n# argument parsing, so people don't have to edit this file\nimport argparse\n\n# for URL encoding search terms\nimport urllib\n\n# using this python module to access the Twitter API https://github.com/bear/python-twitter\nimport twitter\n\n#to handle UTF-8\nimport codecs\n\n#to process tweet text\nimport re\n\n#to get timestamp\nfrom datetime import tzinfo, datetime\n\n# to be able to create directories\nimport os\n\nimport sys\n\n# read relevant keys from config file\ntry:\n with open('ornithologist.conf', 'r') as config:\n c = config.readlines()\n assert len(c) == 4, \"\"\"ornithologist.conf not in the right format. Need 'API key', 'API secret', 'Access token' and 'Access token secret', each in a single line\"\"\"\n consumer_key = c[0].strip()\n consumer_secret = c[1].strip()\n access_token_key = c[2].strip()\n access_token_secret = c[3].strip()\nexcept OSError:\n print('Config file not found. Please refer to README.', file=sys.stderr)\n\n# this is to make sure help instead of usage gets printed on error\nclass ArgumentParser(argparse.ArgumentParser):\n def error(self, message):\n print('error: %s\\n' % message, file=sys.stderr)\n self.print_help()\n sys.exit(2)\n\nparser = ArgumentParser(description='retrieves Twitter data via the Twitter API for further analysis')\nparser.add_argument('--term', dest='searchterm', help='search term', required=True)\nparser.add_argument('--file', dest='fileName', help='For file name to append, e.g. student name', required=True)\nparser.add_argument('--lang', dest='language', default='', help='e.g. \"en\", \"nl\" (default: None)')\nparser.add_argument('--before', dest='before', default='', help='get tweets before this date YYYY-MM-DD (default: now)')\nparser.add_argument('--type', dest='resultType', default='recent', help='result type: options are recent, popular, mixed, see API documentation. (default: recent)')\n\nargs = parser.parse_args()\nsearchterm = urllib.quote_plus(args.searchterm) #handle URL encoding\nfileName = args.fileName\nlanguage = args.language\nbefore = args.before\nresultType = args.resultType\n\n# Twitter authentication\napi = twitter.Api(consumer_key=consumer_key,\n consumer_secret=consumer_secret,\n access_token_key=access_token_key,\n access_token_secret=access_token_secret)\n\n#do the actual search\nstatuses = api.GetSearch(term=searchterm, result_type=resultType, include_entities=True, count=100, lang=language, until=before)\n\ncurrentTime = datetime.utcnow()\n\n#open and write a file with search-level data\nsldFileName = searchterm + \"-\" + fileName + \"-searchLevelData.txt\"\nif os.path.isfile(sldFileName) is True:\n info = codecs.open(sldFileName, encoding='utf-8', mode='a')\n info.write (\"\\n\" + searchterm + \"\\t\" + language + \"\\t\" + fileName + \"\\t\" + before + \"\\t\" + str(currentTime) + \" UTC\" + '\\t' + resultType)\nelse:\n info = codecs.open(sldFileName, encoding='utf-8', mode='w+')\n info.write(\"search term\\tlanguage\\tfile name\\tbefore\\tgathered\\tresult type\\n\" + searchterm + \"\\t\" + language + \"\\t\" + fileName + \"\\t\" + before + \"\\t\" + str(currentTime) + \" UTC\" + '\\t' + resultType)\n\n#loop through each result\nfor s in statuses:\n #take out any tabs or new lines in the tweets\n takeTabNewlines = re.compile(r'[\\t\\r\\n]')\n strip = takeTabNewlines.sub('', s.text)\n \n #get tweets to users (user begins the tweet)\n toUserSearch = re.compile(r'@(\\w*\\b)', re.U)\n toUserMatch = toUserSearch.match(strip)\n toUserList = []\n if toUserMatch:\n toUserList.append(toUserMatch.group(1))\n \n userFileName = searchterm + \"-\" + fileName + \"-userEdges.txt\"\n \n if os.path.isfile(userFileName) is True:\n userNet = codecs.open(userFileName, encoding='utf-8', mode='a')\n userNet.write(unicode(s.user.screen_name) + \"\\t\" + unicode(toUserMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n # open a file to write the to user network\n userNet = codecs.open(userFileName, encoding='utf-8', mode='w+')\n #Source is user, target is user mentioned\n userNet.write(\"Source\\tTarget\\ttweet id\\n\")\n else:\n toUserList.append('')\n \n #get retweet user\n rtSearch = re.compile(r'RT @(\\w*\\b)', re.U)\n rtMatch = rtSearch.match(strip)\n rtList = []\n rtFileName = searchterm + \"-\" + fileName + \"-rtEdges.txt\"\n if rtMatch:\n rtList.append(rtMatch.group(1))\n if os.path.isfile(rtFileName) is True:\n rt = codecs.open(rtFileName, encoding='utf-8', mode='a')\n rt.write(unicode(s.user.screen_name) + \"\\t\" + unicode(rtMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n # open a file to write the RT network\n rt = codecs.open(rtFileName, encoding='utf-8', mode='w+')\n #Source is user, target is user retweeted\n rt.write(\"Source\\tTarget\\ttweet id\\n\")\n rt.write(unicode(s.user.screen_name) + \"\\t\" + unicode(rtMatch.group(1)) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n rtList.append('')\n \n #get all user mentions\n mentionList = re.findall(r'@(\\w*\\b)', strip)\n \n #get all hashtags\n hashtagList = re.findall(r'#\\w*\\b', strip)\n \n #get all links\n linkList = re.findall(r'https?://[\\w\\./]*\\b', strip)\n \n #strip source of HTML\n tweetSource= re.sub('<[^<]+?>', '', s.source)\n \n #read in the date 'Mon Sep 08 05:43:10 +0000 2014' as a date object and output as '20140908 05:43:10'\n dateObject = datetime.strptime(s.created_at, '%a %b %d %H:%M:%S +0000 %Y')\n unixDate = dateObject.strftime('%Y-%m-%d %H:%M:%S')\n \n tweetFileName = searchterm + \"-\" + fileName + \"-tweets.txt\"\n \n if os.path.isfile(tweetFileName) is True:\n #open a file to write the tweet-level data\n t = codecs.open(tweetFileName, encoding='utf-8', mode='a')\n # write one line of data to tweet file\n t.write(unicode(currentTime) + \"\\t\" + unicode(s.id) + \"\\t\" + unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + unixDate + \"\\t\" + unicode(s.retweet_count) + \"\\t\" + str(s.favorite_count) + \"\\t\" + unicode(tweetSource) + \"\\t\" + unicode(s.lang) + \"\\t\" + unicode(s.withheld_in_countries) + \"\\t\" + unicode(strip) + \"\\t\" + ', '.join(toUserList) + \"\\t\" + ', '.join(rtList) + \"\\t\" + ', '.join(mentionList) + \"\\t\" + ', '.join(hashtagList) + \"\\t\" + ', '.join(linkList) + \"\\n\")\n else:\n t = codecs.open(tweetFileName, encoding='utf-8', mode='w+')\n # Write the header row\n t.write(\"gathered\\ttweet id\\tuser id\\tuser name\\ttime created\\tretweets\\tfavorites\\ttweet source\\tlanguage\\twithheld from\\ttweet\\tto user\\tretweet of\\tall user mentions\\thashtags\\tlinks\\n\")\n # write one line of data to tweet file\n t.write(unicode(currentTime) + \"\\t\" + unicode(s.id) + \"\\t\" + unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + unixDate + \"\\t\" + unicode(s.retweet_count) + \"\\t\" + str(s.favorite_count) + \"\\t\" + unicode(tweetSource) + \"\\t\" + unicode(s.lang) + \"\\t\" + unicode(s.withheld_in_countries) + \"\\t\" + unicode(strip) + \"\\t\" + ', '.join(toUserList) + \"\\t\" + ', '.join(rtList) + \"\\t\" + ', '.join(mentionList) + \"\\t\" + ', '.join(hashtagList) + \"\\t\" + ', '.join(linkList) + \"\\n\")\n \n hashtagFileName = searchterm + \"-\" + fileName + \"-hashtagEdges.txt\"\n \n for h in hashtagList:\n if os.path.isfile(hashtagFileName) is True:\n #open a file to write the hashtag-level data\n hash = codecs.open(hashtagFileName, encoding='utf-8', mode='a')\n hash.write(unicode(s.user.screen_name) + \"\\t\" + unicode(h) + \"\\t\" + unicode(s.id) + \"\\n\")\n else:\n #open a file to write the hashtag-level data\n hash = codecs.open(hashtagFileName, encoding='utf-8', mode='w+')\n #Source is user and target is hashtag\n hash.write(\"Source\\tTarget\\ttweet id\\n\")\n hash.write(unicode(s.user.screen_name) + \"\\t\" + unicode(h) + \"\\t\" + unicode(s.id) + \"\\n\")\n\nt.close() #save the tweet-level data file\nhash.close() #save the hashtag-level data file\n\nuserFileName = searchterm + \"-\" + fileName + \"-users.txt\"\n\nif os.path.isfile(userFileName) is True:\n u = codecs.open(userFileName, encoding='utf-8', mode='a')\n #loop through each result\n userList = []\n for s in statuses:\n #take out any tabs or new lines in the user descriptions\n takeTabNewlinesDesc = re.compile(r'[\\t\\r\\n]')\n stripDesc = takeTabNewlinesDesc.sub('', s.user.description)\n userList.append(unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + s.user.location + \"\\t\" + str(s.user.time_zone) + \"\\t\" + str(s.user.utc_offset) + \"\\t\" + str(s.user.profile_image_url) + \"\\t\" + stripDesc)\n #deduplicate the user list before printing\n userList = list(set(userList))\n u.write('\\n'.join(userList))\nelse:\n #open a file to write the user-level data to\n u = codecs.open(userFileName, encoding='utf-8', mode='w+')\n #write the header row to the file\n u.write(\"user id\\tscreen name\\tlocation\\ttime zone\\tutc offset\\tprofile image URL\\tdescription\\n\")\n #loop through each result\n userList = []\n for s in statuses:\n #take out any tabs or new lines in the user descriptions\n takeTabNewlinesDesc = re.compile(r'[\\t\\r\\n]')\n stripDesc = takeTabNewlinesDesc.sub('', s.user.description)\n userList.append(unicode(s.user.id) + \"\\t\" + unicode(s.user.screen_name) + \"\\t\" + s.user.location + \"\\t\" + str(s.user.time_zone) + \"\\t\" + str(s.user.utc_offset) + \"\\t\" + str(s.user.profile_image_url) + \"\\t\" + stripDesc)\n #deduplicate the user list before printing\n userList = list(set(userList))\n u.write('\\n'.join(userList))\n\nu.close()\n\n# directory of each tweet as a file with ID as name for NLP\n\nfor s in statuses:\n # create directory (if needed) and open a file to write each tweet to\n filename = searchterm + \"-\" + fileName + \"-\" + \"tweets\" + \"/\" + str(s.id) + \".txt\"\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n with codecs.open(filename, encoding='utf-8', mode=\"w+\") as f:\n f.write(unicode(s.text))\nf.close()\n", "sub_path": "ornithologist.py", "file_name": "ornithologist.py", "file_ext": "py", "file_size_in_byte": 10089, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "sys.stderr", "line_number": 44, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 47, "usage_type": "attribute"}, {"api_name": "sys.stderr", "line_number": 49, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 51, "usage_type": "call"}, {"api_name": "urllib.quote_plus", "line_number": 61, "usage_type": "call"}, {"api_name": "twitter.Api", "line_number": 68, "usage_type": "call"}, {"api_name": "datetime.datetime.utcnow", "line_number": 76, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 76, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 80, "usage_type": "call"}, {"api_name": "os.path", "line_number": 80, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 81, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 84, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 90, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 94, "usage_type": "call"}, {"api_name": "re.U", "line_number": 94, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 102, "usage_type": "call"}, {"api_name": "os.path", "line_number": 102, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 103, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 107, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 114, "usage_type": "call"}, {"api_name": "re.U", "line_number": 114, "usage_type": "attribute"}, {"api_name": "os.path.isfile", "line_number": 120, "usage_type": "call"}, {"api_name": "os.path", "line_number": 120, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 121, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 125, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 133, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 136, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 139, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 142, "usage_type": "call"}, {"api_name": "datetime.datetime.strptime", "line_number": 145, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 145, "usage_type": "name"}, {"api_name": "os.path.isfile", "line_number": 150, "usage_type": "call"}, {"api_name": "os.path", "line_number": 150, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 152, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 156, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 165, "usage_type": "call"}, {"api_name": "os.path", "line_number": 165, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 167, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 171, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 181, "usage_type": "call"}, {"api_name": "os.path", "line_number": 181, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 182, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 187, "usage_type": "call"}, {"api_name": "codecs.open", "line_number": 195, "usage_type": "call"}, {"api_name": "re.compile", "line_number": 202, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 216, "usage_type": "call"}, {"api_name": "os.path", "line_number": 216, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 216, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 217, "usage_type": "call"}, {"api_name": "os.path", "line_number": 217, "usage_type": "attribute"}, {"api_name": "codecs.open", "line_number": 218, "usage_type": "call"}]}
+{"seq_id": "470906609", "text": "import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nLR = 0.1\nREAL_PARAMS = [1.2 , 2.5]\nINIT_PARAMS = [[5 , 4],\n [5 , 1],\n [2 , 4.5]]\nINIT_PARAMS = INIT_PARAMS[0] # \n\nx = np.linspace(-1 , 1 , 200 , dtype = np.float32) # x data\n\n#Test (1): Visualize a simple linear function with two parameters,\n#you can change LR to 1 to see the different pattern in gradient descent.\n\n#def y_fun(a , b , x): return a * x + b\n#def tf_y_fun(a , b , x): return a * x + b\ndef y_fun(a , b , x): return np.sin(b * np.cos(a * x))\ndef tf_y_fun(a , b , x): return tf.sin(b * tf.cos(a * x))\n\nnoise = np.random.randn(200) / 10 \ny = y_fun(REAL_PARAMS[0] , REAL_PARAMS[1] , x) + noise # target\n\n# tensorflow graph\nt_variable = [[] , []]\nfor p in range(0 , 2):\n t_variable[p] = tf.Variable(initial_value = INIT_PARAMS[p] , dtype = tf.float32)\n\npred = tf_y_fun(t_variable[0] , t_variable[1] , x)\nmse = tf.reduce_mean(tf.square(y - pred))\ntrain_op = tf.train.GradientDescentOptimizer(LR).minimize(mse)\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\na_list , b_list , cost_list = [] , [] , []\nfor t in range(1000):\n a_ , b_ , mse_ = sess.run([t_variable[0] , t_variable[1] , mse])\n a_list.append(a_)\n b_list.append(b_)\n cost_list.append(mse_) # record parameter changes\n result , _ = sess.run([pred , train_op]) # training\n\n\n# visualization codes:\nprint('a = ', a_, 'b = ', b_)\nplt.figure(1)\nplt.scatter(x , y , c = 'b') # plot data\nplt.plot(x , result , 'r-' , lw=2) # plot line fitting\n\n# 3D cost figure\nfig = plt.figure(2)\nax = Axes3D(fig)\na3D , b3D = np.meshgrid(np.linspace(-2 , 7 , 30) , np.linspace(-2 , 7 , 30)) # parameter space\n#cost3D = np.array([np.mean(np.square(y_fun(a_ , b_ , x) - y)) for a_ , b_ in zip(a3D.flatten() , b3D.flatten())]).reshape(a3D.shape)\ncost3D = np.zeros(a3D.shape)\nfor i in range(0 , a3D.shape[0]):\n for j in range(0 , a3D.shape[0]):\n cost3D[i , j] = np.mean(np.square(y_fun(a3D[i , j] , b3D[i , j] , x) - y))\nax.plot_surface(a3D , b3D , cost3D , rstride = 1 , cstride = 1 , cmap = plt.get_cmap('rainbow') , alpha = 0.7)\nax.scatter(a_list[0] , b_list[0] , zs=cost_list[0] , s = 1000 , c = 'r') # initial parameter place\nax.set_xlabel('a')\nax.set_ylabel('b')\nax.plot(a_list , b_list , zs = cost_list , zdir = 'z', c = 'g' , lw = 3) # plot 3D gradient descent\nplt.show()", "sub_path": "Tensorflow_進階/03_Visualization_Gradient_Descent/visualization_gradient_descent.py", "file_name": "visualization_gradient_descent.py", "file_ext": "py", "file_size_in_byte": 2452, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "numpy.linspace", "line_number": 13, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.sin", "line_number": 20, "usage_type": "call"}, {"api_name": "numpy.cos", "line_number": 20, "usage_type": "call"}, {"api_name": "tensorflow.sin", "line_number": 21, "usage_type": "call"}, {"api_name": "tensorflow.cos", "line_number": 21, "usage_type": "call"}, {"api_name": "numpy.random.randn", "line_number": 23, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 23, "usage_type": "attribute"}, {"api_name": "tensorflow.Variable", "line_number": 29, "usage_type": "call"}, {"api_name": "tensorflow.float32", "line_number": 29, "usage_type": "attribute"}, {"api_name": "tensorflow.reduce_mean", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.square", "line_number": 32, "usage_type": "call"}, {"api_name": "tensorflow.train.GradientDescentOptimizer", "line_number": 33, "usage_type": "call"}, {"api_name": "tensorflow.train", "line_number": 33, "usage_type": "attribute"}, {"api_name": "tensorflow.Session", "line_number": 34, "usage_type": "call"}, {"api_name": "tensorflow.global_variables_initializer", "line_number": 35, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 47, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 47, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.scatter", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 49, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 49, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 52, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 52, "usage_type": "name"}, {"api_name": "mpl_toolkits.mplot3d.Axes3D", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.meshgrid", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 59, "usage_type": "call"}, {"api_name": "numpy.square", "line_number": 59, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.get_cmap", "line_number": 60, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 60, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 65, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 65, "usage_type": "name"}]}
+{"seq_id": "623008789", "text": "# Author: Christian Brodbeck \nfrom itertools import izip\nimport re\n\nimport numpy as np\n\nfrom . import stats\n\n\n# array functions: work on array, take axis argument\nnp_afuncs = {'min': np.min,\n 'max': np.max,\n 'sum': np.sum}\n# binary functions: work on two arrays\nnp_bfuncs = {'subtract': np.subtract,\n 'add': np.add}\n# unary functions: work on a single array\nnp_ufuncs = {'abs': np.abs,\n 'negative': np.negative}\n\n\nclass TContrastRel(object):\n \"Parse a contrast expression and expose methods to apply it\"\n\n def __init__(self, contrast, cells, indexes):\n \"\"\"Parse a contrast expression and expose methods to apply it\n\n Parameters\n ----------\n contrast : str\n Contrast specification.\n cells : tuple of cells\n Cells that occur in the contrast (each cell is represented by a str\n or a tuple of str).\n indexes : dict {cell: index}\n Indexes for the data of every cell.\n \"\"\"\n parse = _parse_t_contrast(contrast)\n n_buffers, cells_in_contrast = _t_contrast_rel_properties(parse)\n pcells, mcells = _t_contrast_rel_expand_cells(cells_in_contrast, cells)\n\n self.contrast = contrast\n self.indexes = indexes\n self._parsed_contrast = parse\n self._pcells = pcells\n self._mcells = mcells\n self._n_buffers = n_buffers\n\n # data buffers\n self._buffer_shape = None\n self._buffer = None\n self._y_perm = None\n\n def map(self, y):\n \"Apply contrast without retainig data buffers\"\n buff = np.empty((self._n_buffers,) + y.shape[1:])\n data = _t_contrast_rel_data(y, self.indexes, self._pcells, self._mcells)\n tmap = _t_contrast_rel(self._parsed_contrast, data, buff)\n return tmap\n\n def __call__(self, y, out, perm):\n \"Apply contrast to permutation of the data, storing and recycling data buffers\"\n buffer_shape = (self._n_buffers,) + y.shape[1:]\n if self._buffer_shape != buffer_shape:\n self._buffer = np.empty(buffer_shape)\n self._y_perm = np.empty_like(y)\n self._buffer_shape = buffer_shape\n self._y_perm[perm] = y\n data = _t_contrast_rel_data(self._y_perm, self.indexes, self._pcells, self._mcells)\n tmap = _t_contrast_rel(self._parsed_contrast, data, self._buffer, out)\n return tmap\n\n\ndef _parse_cell(cell_name):\n \"Parse a cell name for t_contrast\"\n cell = tuple(s.strip() for s in cell_name.split('|'))\n if len(cell) == 1:\n return cell[0]\n else:\n return cell\n\n\ndef _parse_t_contrast(contrast):\n \"\"\"Parse a string specifying a t-contrast into nested instruction tuples\n\n Parameters\n ----------\n contrast : str\n Contrast specification string.\n\n Returns\n -------\n compiled_contrast : tuple\n Nested tuple composed of:\n Comparisons: ``('comp', c1, c0)`` and\n Unary functions: ``('ufunc', func, arg)``\n Binary functions: ``('bfunc', func, [arg1, arg2])``\n Array functions: ``('afunc', func, [arg1, arg2, ...])``\n where ``arg1`` etc. are in turn comparisons and functions.\n \"\"\"\n depth = 0\n start = 0\n if not '(' in contrast:\n m = re.match(\"\\s*([\\w\\|*]+)\\s*([<>])\\s*([\\w\\|*]+)\", contrast)\n if m:\n c1, direction, c0 = m.groups()\n if direction == '<':\n c1, c0 = c0, c1\n c1 = _parse_cell(c1)\n c0 = _parse_cell(c0)\n return ('comp', c1, c0)\n\n for i, c in enumerate(contrast):\n if c == '(':\n if depth == 0:\n prefix = contrast[start:i]\n i_open = i + 1\n items = []\n depth += 1\n elif c == ',':\n if depth == 0:\n raise\n elif depth == 1:\n item = _parse_t_contrast(contrast[i_open:i])\n items.append(item)\n i_open = i + 1\n elif c == ')':\n depth -= 1\n if depth == 0:\n item = _parse_t_contrast(contrast[i_open:i])\n items.append(item)\n\n if contrast[i+1:].strip():\n raise ValueError(\"Expression continues after last \"\n \"parentheses closed: %s\" % contrast)\n elif prefix == '':\n if len(items) == 1:\n return items[0]\n else:\n raise ValueError(\"Multiple comparisons without \"\n \"combination expression: %s\" % contrast)\n\n m = re.match(\"\\s*(\\w+)\\s*\", prefix)\n if m is None:\n raise ValueError(\"uninterpretable prefix: %r\" % prefix)\n func = m.group(1)\n if func in np_ufuncs:\n if len(items) != 1:\n raise ValueError(\"Wrong number of input values for \"\n \"unary function: %s\" % contrast)\n return 'ufunc', np_ufuncs[func], items[0]\n elif func in np_bfuncs:\n if len(items) != 2:\n raise ValueError(\"Wrong number of input values for \"\n \"binary function: %s\" % contrast)\n return 'bfunc', np_bfuncs[func], items\n elif func in np_afuncs:\n if len(items) < 2:\n raise ValueError(\"Wrong number of input values for \"\n \"array comparison function: %s\"\n % contrast)\n return 'afunc', np_afuncs[func], items\n else:\n raise ValueError(\"Unknown function: %s\" % contrast)\n elif depth == -1:\n err = \"Invalid ')' at position %i of %r\" % (i, contrast)\n raise ValueError(err)\n\n\ndef _t_contrast_rel_properties(item):\n \"\"\"Find properties of a compiled t-contrast\n\n Parameters\n ----------\n item : tuple\n Contrast specification.\n\n Returns\n -------\n n_buffers : int\n Number of buffer maps needed.\n cells : set\n names of all cells that occur in the contrast.\n \"\"\"\n if item[0] == 'ufunc':\n needed_buffers, cells = _t_contrast_rel_properties(item[2])\n return needed_buffers + 1, cells\n elif item[0] in ('bfunc', 'afunc'):\n _, _, items_ = item\n local_buffers = len(items_)\n cells = set()\n for i, item_ in enumerate(items_):\n available_buffers = local_buffers - i - 1\n needed_buffers, cells_ = _t_contrast_rel_properties(item_)\n additional_buffers = needed_buffers - available_buffers\n if additional_buffers > 0:\n local_buffers += additional_buffers\n cells.update(cells_)\n return local_buffers, cells\n else:\n return 0, set(item[1:])\n\n\ndef _t_contrast_rel_expand_cells(cells, all_cells):\n \"\"\"Find cells that are an average of other cells\n\n Parameters\n ----------\n cells : set\n Cells occurring in the contrast.\n all_cells : tuple\n All cells in the data.\n\n Returns\n -------\n primary_cells : set\n All cells that occur directly in the data.\n mean_cells : dict\n ``{name: components}`` dictionary (components being a tuple with all\n cells to be averaged).\n \"\"\"\n # check all cells have same number of components\n ns = set(1 if isinstance(cell, str) else len(cell) for cell in all_cells)\n ns.update(1 if isinstance(cell, str) else len(cell) for cell in cells)\n if len(ns) > 1:\n msg = (\"Not all cells have the same number of components: %s\" %\n str(tuple(cells) + tuple(all_cells)))\n raise ValueError(msg)\n\n primary_cells = set()\n mean_cells = {}\n for cell in cells:\n if cell in all_cells:\n primary_cells.add(cell)\n elif isinstance(cell, str):\n if cell != '*':\n raise ValueError(\"%s not in all_cells\" % repr(cell))\n mean_cells[cell] = all_cells\n primary_cells.update(all_cells)\n elif not '*' in cell:\n msg = \"Contrast contains cell not in data: %s\" % repr(cell)\n raise ValueError(msg)\n else:\n # find cells that should be averaged (\"base\")\n base = tuple(cell_ for cell_ in all_cells if\n all(i in (i_, '*') for i, i_ in izip(cell, cell_)))\n if len(base) == 0:\n raise ValueError(\"No cells in data match %s\" % repr(cell))\n mean_cells[cell] = base\n primary_cells.update(base)\n\n return primary_cells, mean_cells\n\n\ndef _t_contrast_rel_data(y, indexes, cells, mean_cells):\n \"Create {cell: data} dictionary\"\n data = {}\n for cell in cells:\n index = indexes[cell]\n data[cell] = y[index]\n\n for name, cells_ in mean_cells.iteritems():\n cell = cells_[0]\n x = data[cell].copy()\n for cell in cells_[1:]:\n x += data[cell]\n x /= len(cells_)\n data[name] = x\n\n return data\n\n\ndef _t_contrast_rel(item, data, buff, out=None):\n \"Execute a t_contrast (recursive)\"\n if item[0] == 'ufunc':\n _, func, item_ = item\n tmap = _t_contrast_rel(item_, data, buff[1:], buff[0])\n tmap = func(tmap, tmap)\n elif item[0] == 'bfunc':\n _, func, items = item\n tmap1 = _t_contrast_rel(items[0], data, buff[2:], buff[1])\n tmap2 = _t_contrast_rel(items[1], data, buff[2:], buff[0])\n tmap = func(tmap1, tmap2, tmap2)\n elif item[0] == 'afunc':\n _, func, items_ = item\n tmaps = buff[:len(items_)]\n for i, item_ in enumerate(items_):\n _t_contrast_rel(item_, data, buff[i + 1:], tmaps[i])\n tmap = func(tmaps, axis=0, out=out)\n else:\n _, c1, c0 = item\n tmap = stats.t_1samp(data[c1] - data[c0], out)\n\n return tmap\n", "sub_path": "eelbrain/_stats/t_contrast.py", "file_name": "t_contrast.py", "file_ext": "py", "file_size_in_byte": 10099, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.min", "line_number": 11, "usage_type": "attribute"}, {"api_name": "numpy.max", "line_number": 12, "usage_type": "attribute"}, {"api_name": "numpy.sum", "line_number": 13, "usage_type": "attribute"}, {"api_name": "numpy.subtract", "line_number": 15, "usage_type": "attribute"}, {"api_name": "numpy.add", "line_number": 16, "usage_type": "attribute"}, {"api_name": "numpy.abs", "line_number": 18, "usage_type": "attribute"}, {"api_name": "numpy.negative", "line_number": 19, "usage_type": "attribute"}, {"api_name": "numpy.empty", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.empty_like", "line_number": 66, "usage_type": "call"}, {"api_name": "re.match", "line_number": 104, "usage_type": "call"}, {"api_name": "re.match", "line_number": 143, "usage_type": "call"}, {"api_name": "itertools.izip", "line_number": 246, "usage_type": "call"}]}
+{"seq_id": "457693212", "text": "from django.urls import path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom app import views\n\nurlpatterns = [\n path('product/', views.ProductList.as_view()),\n path('product//', views.ProductDetail.as_view()),\n path('product//highlight/', views.ProductDetail.as_view(), name='product-highlight'),\n path('cart/', views.CartList.as_view()),\n path('cart//', views.CartList.as_view())\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n", "sub_path": "app/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 492, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.urls.path", "line_number": 6, "usage_type": "call"}, {"api_name": "app.views.ProductList.as_view", "line_number": 6, "usage_type": "call"}, {"api_name": "app.views.ProductList", "line_number": 6, "usage_type": "attribute"}, {"api_name": "app.views", "line_number": 6, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 7, "usage_type": "call"}, {"api_name": "app.views.ProductDetail.as_view", "line_number": 7, "usage_type": "call"}, {"api_name": "app.views.ProductDetail", "line_number": 7, "usage_type": "attribute"}, {"api_name": "app.views", "line_number": 7, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 8, "usage_type": "call"}, {"api_name": "app.views.ProductDetail.as_view", "line_number": 8, "usage_type": "call"}, {"api_name": "app.views.ProductDetail", "line_number": 8, "usage_type": "attribute"}, {"api_name": "app.views", "line_number": 8, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 9, "usage_type": "call"}, {"api_name": "app.views.CartList.as_view", "line_number": 9, "usage_type": "call"}, {"api_name": "app.views.CartList", "line_number": 9, "usage_type": "attribute"}, {"api_name": "app.views", "line_number": 9, "usage_type": "name"}, {"api_name": "django.urls.path", "line_number": 10, "usage_type": "call"}, {"api_name": "app.views.CartList.as_view", "line_number": 10, "usage_type": "call"}, {"api_name": "app.views.CartList", "line_number": 10, "usage_type": "attribute"}, {"api_name": "app.views", "line_number": 10, "usage_type": "name"}, {"api_name": "rest_framework.urlpatterns.format_suffix_patterns", "line_number": 13, "usage_type": "call"}]}
+{"seq_id": "456102405", "text": "from django.conf.urls import url\n\nfrom . import views\n\napp_name = \"board\"\nurlpatterns = [\n url(r\"^$\", views.index, name=\"index\"),\n url(r\"^(?P[0-9]+)$\", views.index, name=\"paginated_index\"),\n url(r\"^thread/(?P[0-9]+)(#[0-9]+)?$\", views.thread, name=\"thread\"),\n url(r\"^reply/$\", views.reply, name=\"reply\"),\n url(r\"^new_thread/$\", views.new_thread, name=\"new_thread\"),\n]\n", "sub_path": "two_chong/board/urls.py", "file_name": "urls.py", "file_ext": "py", "file_size_in_byte": 405, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.conf.urls.url", "line_number": 7, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 8, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 9, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 10, "usage_type": "call"}, {"api_name": "django.conf.urls.url", "line_number": 11, "usage_type": "call"}]}
+{"seq_id": "20967316", "text": "import unittest\n\nfrom vector.Vector import Vector\n\n\nclass TestVectorSum(unittest.TestCase):\n def test_add(self):\n x = Vector((3, 6))\n y = Vector((2, 4))\n\n self.assertEqual((5, 10), x.add(y).coordinates(), 'Vector addition is incorrect')\n\n def test_subtract(self):\n x = Vector((3, 6))\n y = Vector((2, 4))\n\n self.assertEqual((1, 2), x.subtract(y).coordinates(), 'Vector subtraction is incorrect')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "sub_path": "exercises/matrices/test/vector/test_VectorSum.py", "file_name": "test_VectorSum.py", "file_ext": "py", "file_size_in_byte": 492, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "unittest.TestCase", "line_number": 6, "usage_type": "attribute"}, {"api_name": "vector.Vector.Vector", "line_number": 8, "usage_type": "call"}, {"api_name": "vector.Vector.Vector", "line_number": 9, "usage_type": "call"}, {"api_name": "vector.Vector.Vector", "line_number": 14, "usage_type": "call"}, {"api_name": "vector.Vector.Vector", "line_number": 15, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 21, "usage_type": "call"}]}
+{"seq_id": "252311675", "text": "import json\nimport logging\nimport random\nimport time\nfrom datetime import datetime\n\nfrom django.core.management import BaseCommand\nfrom kafka import KafkaProducer\nfrom kafka.errors import KafkaError\n\nfrom cno.settings.base import LOGGING\nfrom runner.config import KAFKA_API_VERSION, KAFKA_SERVER\nfrom simulation.constants import mano\n\nlogging.config.dictConfig(LOGGING)\nlogger = logging.getLogger(__name__)\n\n\ndef publish_metrics_for_qoe():\n # Kafka Producer Set Up\n # https://kafka-python.readthedocs.io/en/master/apidoc/KafkaProducer.html\n producer = KafkaProducer(bootstrap_servers=KAFKA_SERVER, api_version=KAFKA_API_VERSION,\n value_serializer=lambda v: json.dumps(v).encode('utf-8'))\n while True:\n # Push the metric values in batch per container ID\n prep_metric = {\n 'mano': mano,\n 'measurements':\n {\n 'working_fps': 11,\n 'output_mesh_size_bytes': 45000,\n 'output_textures_size_bytes': 25000,\n 'container_network_transmit_packets_dropped_total': random.uniform(0, 2)\n },\n 'timestamp': datetime.now().isoformat()\n }\n request = producer.send('ns.instances.prep', key=b'qoe', value=prep_metric)\n try:\n request.get(timeout=60)\n except KafkaError as ke:\n logger.error(ke)\n\n time.sleep(30)\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n publish_metrics_for_qoe()\n", "sub_path": "simulation/management/commands/publish_metrics_for_qoe.py", "file_name": "publish_metrics_for_qoe.py", "file_ext": "py", "file_size_in_byte": 1542, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.config.dictConfig", "line_number": 15, "usage_type": "call"}, {"api_name": "cno.settings.base.LOGGING", "line_number": 15, "usage_type": "argument"}, {"api_name": "logging.config", "line_number": 15, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 16, "usage_type": "call"}, {"api_name": "kafka.KafkaProducer", "line_number": 22, "usage_type": "call"}, {"api_name": "runner.config.KAFKA_SERVER", "line_number": 22, "usage_type": "name"}, {"api_name": "runner.config.KAFKA_API_VERSION", "line_number": 22, "usage_type": "name"}, {"api_name": "json.dumps", "line_number": 23, "usage_type": "call"}, {"api_name": "simulation.constants.mano", "line_number": 27, "usage_type": "name"}, {"api_name": "random.uniform", "line_number": 33, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 35, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 35, "usage_type": "name"}, {"api_name": "kafka.errors.KafkaError", "line_number": 40, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 43, "usage_type": "call"}, {"api_name": "django.core.management.BaseCommand", "line_number": 46, "usage_type": "name"}]}
+{"seq_id": "94399098", "text": "\"\"\"\nConstructing and loading dictionaries\n\"\"\"\nimport pickle as pkl\nimport numpy\nfrom collections import OrderedDict\nimport argparse\nimport time\n\ndef build_dictionary(text):\n \"\"\"\n Build a dictionary\n text: list of sentences (pre-tokenized)\n \"\"\"\n wordcount = {}\n for cc in text:\n words = cc.split()\n for w in words:\n if w not in wordcount:\n wordcount[w] = 0\n wordcount[w] += 1\n words = list(wordcount.keys())\n freqs = list(wordcount.values())\n sorted_idx = numpy.argsort(freqs)[::-1]\n\n worddict = OrderedDict()\n for i, idx in enumerate(sorted_idx):\n worddict[words[idx]] = i+2 # 0: , 1: \n\n return worddict, wordcount\n\ndef load_dictionary(loc='dictionary.pkl'):\n \"\"\"\n Load a dictionary\n \"\"\"\n with open(loc, 'rb') as f:\n worddict = pkl.load(f)\n wordcount = pkl.load(f)\n return worddict\n\ndef save_dictionary(worddict, wordcount, loc):\n \"\"\"\n Save a dictionary to the specified location \n \"\"\"\n with open(loc, 'wb') as f:\n pkl.dump(worddict, f)\n pkl.dump(wordcount, f)\n\n\ndef readFile(filename):\n sentences = []\n with open(filename) as f:\n for line in f:\n if line == '':\n continue\n \n if '.' in line:\n sentences.extend(line.split('.'))\n else:\n sentences.append(line)\n return sentences\n\n\ndef cutSentences(lsentences):\n toAdd = []\n for i, fsent in enumerate(lsentences):\n if fsent == '':\n lsentences.pop(i)\n if '. ' in fsent:\n toAdd.extend(fsent.split('. '))\n lsentences.pop(i)\n lsentences.extend(toAdd)\n \ndef removeWords(worddict, wordcount, count=30):\n klist = list(worddict.keys())\n for key in klist:\n if wordcount[key] < count:\n worddict.pop(key, None)\n return worddict\n \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-f','--sentences_file', help=\"File containing sentences\",\n default=\"/data/wiki+leboncoin_pre.txt\")\n parser.add_argument('-d','--dictionary_name', help=\"Path to save dictionary\",\n default='dictionary.pkl')\n args = parser.parse_args()\n \n print('Loading sentences file')\n t0 = time.time()\n sentences = readFile(args.sentences_file)\n print('File read in', time.time() - t0, ' sec')\n\n print(\"Creating dictionary\")\n dic, count = build_dictionary(sentences)\n print(\"Saving dictionary\")\n removeWords(dic, count)\n save_dictionary(dic, count, args.dictionary_name)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "sub_path": "training/vocab.py", "file_name": "vocab.py", "file_ext": "py", "file_size_in_byte": 2675, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "numpy.argsort", "line_number": 24, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 26, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 37, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 38, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 46, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 47, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 84, "usage_type": "call"}, {"api_name": "time.time", "line_number": 92, "usage_type": "call"}, {"api_name": "time.time", "line_number": 94, "usage_type": "call"}]}
+{"seq_id": "498040956", "text": "# Copyright 2018 HTCondor Team, Computer Sciences Department,\n# University of Wisconsin-Madison, WI.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport time\nimport itertools\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nimport htmap\nfrom htmap.options import get_base_options_dict\nfrom htmap.settings import BASE_SETTINGS\n\n# start with base settings (ignore user settings for tests)\nhtmap.settings.replace(BASE_SETTINGS)\n\n\n@pytest.fixture(scope = 'session', autouse = True)\ndef set_transplant_dir(tmpdir_factory):\n path = Path(tmpdir_factory.mktemp('htmap_transplant_dir'))\n htmap.settings['TRANSPLANT.PATH'] = path\n\n\n@pytest.fixture(\n params = [\n 'assume',\n 'transplant',\n 'docker',\n ],\n)\ndef delivery_methods(request):\n htmap.settings['DELIVERY_METHOD'] = request.param\n\n\ndef get_base_options_for_tests(map_id, map_dir, delivery, test_id = None):\n opts = get_base_options_dict(map_id, map_dir, delivery)\n opts['+htmap_test_id'] = str(test_id)\n\n return opts\n\n\nids = itertools.count()\n\n\n# todo: break this into two fixtures, one for setting htmap_dir, one for test_id and cleanup\n@pytest.fixture(scope = 'function', autouse = True)\ndef set_htmap_dir_and_clean_after(tmpdir_factory, mocker):\n \"\"\"Use a fresh HTMAP_DIR for every test.\"\"\"\n path = Path(tmpdir_factory.mktemp('htmap_dir'))\n htmap.settings['HTMAP_DIR'] = path\n\n test_id = next(ids)\n mocker.patch(\n 'htmap.options.get_base_options_dict',\n functools.partial(get_base_options_for_tests, test_id = test_id),\n )\n\n yield\n\n subprocess.run(\n [\n 'condor_rm',\n f'--constraint htmap_test_id=={test_id}',\n ],\n stdout = subprocess.DEVNULL,\n stderr = subprocess.DEVNULL,\n )\n\n\n@pytest.fixture(scope = 'session')\ndef doubler():\n def doubler(x):\n return 2 * x\n\n return doubler\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_doubler(doubler):\n mapper = htmap.htmap(doubler)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef power():\n def power(x = 0, p = 0):\n return x ** p\n\n return power\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_power(power):\n mapper = htmap.htmap(power)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef sleepy_double():\n def sleepy_double(x):\n time.sleep(5)\n return 2 * x\n\n return sleepy_double\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_sleepy_double(sleepy_double):\n mapper = htmap.htmap(sleepy_double)\n return mapper\n\n\n@pytest.fixture(scope = 'session')\ndef mapped_exception():\n @htmap.htmap\n def fail(x):\n raise Exception(str(x))\n\n return fail\n\n\ndef exception_msg(exc_info) -> str:\n return str(exc_info.value)\n", "sub_path": "tests/conftest.py", "file_name": "conftest.py", "file_ext": "py", "file_size_in_byte": 3253, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "htmap.settings.replace", "line_number": 29, "usage_type": "call"}, {"api_name": "htmap.settings.BASE_SETTINGS", "line_number": 29, "usage_type": "argument"}, {"api_name": "htmap.settings", "line_number": 29, "usage_type": "attribute"}, {"api_name": "pathlib.Path", "line_number": 34, "usage_type": "call"}, {"api_name": "htmap.settings", "line_number": 35, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 32, "usage_type": "call"}, {"api_name": "htmap.settings", "line_number": 46, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 38, "usage_type": "call"}, {"api_name": "htmap.options.get_base_options_dict", "line_number": 50, "usage_type": "call"}, {"api_name": "itertools.count", "line_number": 56, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 63, "usage_type": "call"}, {"api_name": "htmap.settings", "line_number": 64, "usage_type": "attribute"}, {"api_name": "functools.partial", "line_number": 69, "usage_type": "call"}, {"api_name": "subprocess.run", "line_number": 74, "usage_type": "call"}, {"api_name": "subprocess.DEVNULL", "line_number": 79, "usage_type": "attribute"}, {"api_name": "subprocess.DEVNULL", "line_number": 80, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 60, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 84, "usage_type": "call"}, {"api_name": "htmap.htmap", "line_number": 94, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 92, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 98, "usage_type": "call"}, {"api_name": "htmap.htmap", "line_number": 108, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 106, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 115, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 112, "usage_type": "call"}, {"api_name": "htmap.htmap", "line_number": 123, "usage_type": "call"}, {"api_name": "pytest.fixture", "line_number": 121, "usage_type": "call"}, {"api_name": "htmap.htmap", "line_number": 129, "usage_type": "attribute"}, {"api_name": "pytest.fixture", "line_number": 127, "usage_type": "call"}]}
+{"seq_id": "506233308", "text": "import pandas as pd\nimport time\nimport re\nimport requests\nimport scrapy\nfrom scrapy.http import TextResponse\nfrom scrapy_naver_news_2years.items import ScrapyNaverNews2YearsItem\n\nclass ScrapyNaverNews2YearsSpider(scrapy.Spider):\n name = 'scrapy_naver_news_2years'\n allow_domain=[\"https://news.naver.com\"]\n user_agent= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'\n categ = {#'정치': '100',\n '101':'economy',\n '102': 'soci',\n '103': 'culture',\n #'세계': '104',\n '105': 'IT'}\n\n def __init__(self, categ = 101, *args, **kwargs): \n self.categ_path = self.categ[str(categ)] + '.csv'\n print(self.categ_path)\n ScrapyNaverNews2YearsSpider.__init__(self)\n\n def start_requests(self):\n #df = pd.read_csv('article_url_1.csv')\n df = pd.read_csv(self.categ_path)\n rows = df.iloc\n date_ex = '202011'\n \n for row in rows:\n date_ = str(row['date'])\n date_ = str(date_)[0:7]\n if date_ != date_ex:\n time.sleep(2)\n #print(row['categ'], row['date'], row['last_p'])\n for page in range(1, int(row['last_p'])+1):\n url = 'https://news.naver.com/main/list.nhn?mode=LSD&mid=sec&listType=title&sid1={}&date={}&page={}'.format(row['categ'], row['date'], page)\n yield scrapy.Request(url, callback=self.parse)\n date_ex = str(date_)[0:7]\n \n def parse(self, resp):\n links = resp.xpath('//*[@id=\"main_content\"]/div[2]/ul/li/a/@href').extract()\n \n # links = [resp.urljoin(link) for link in links]\n for link in links:\n yield scrapy.Request(link, callback=self.parse_content)\n \n def parse_content(self, resp):\n item = ScrapyNaverNews2YearsItem()\n title = resp.xpath('//*[@id=\"articleTitle\"]/text() | //*[@id=\"content\"]/div[1]/div/h2/text() | \\\n //h4[@class=\"title\"]/text()')[0].extract()\n date = resp.xpath('//*[@id=\"main_content\"]/div[1]/div[3]/div/span[@class=\"t11\"]/text() | \\\n //div[@class=\"article_info\"]/span[@class=\"author\"]/em/text()|\\\n //div[@class=\"info\"]/span[1]/text()')[0].extract()\n content = resp.xpath('//*[@id=\"articleBodyContents\"]/text() | \\\n //*[@id=\"articleBodyContents\"]/strong/text() | \\\n //*[@id=\"articleBodyContents\"]/div/text() | \\\n //*[@id=\"articleBodyContents\"]/div/div/text() | \\\n //*[@id=\"articleBodyContents\"]/font/text() | \\\n //*[@id=\"articleBodyContents\"]/div[2]/ul/li/span/span/text() | \\\n //*[@id=\"newsEndContents\"]/text() | \\\n //*[@id=\"articeBody\"]/text()').extract()\n content = [text.replace('\\xa0', ' ').strip() for text in content]\n categ_num = resp.url.split('sid1=')[1].split('&')[0]\n \n item['date'] = re.findall('[0-9]{4}[.][0-9]{2}[.][0-9]{2}', date)[0]\n item['category'] = self.categ[categ_num]\n item['press_agency'] = resp.xpath('//a[@class=\"nclicks(atp_press)\"]/img/@title | //div[@class=\"press_logo\"]/a/img/@alt | \\\n //*[@id=\"pressLogo\"]/a/img/@alt')[0].extract()\n item['link'] = resp.url\n item['title'] = title.strip()\n item['content'] = '\\n'.join(content).strip()\n \n yield item", "sub_path": "01_crawling/scrapy_naver_news_2years/scrapy_naver_news_2years/spiders/spider.py", "file_name": "spider.py", "file_ext": "py", "file_size_in_byte": 3502, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "scrapy.Spider", "line_number": 9, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 27, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 35, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 39, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 47, "usage_type": "call"}, {"api_name": "scrapy_naver_news_2years.items.ScrapyNaverNews2YearsItem", "line_number": 50, "usage_type": "call"}, {"api_name": "re.findall", "line_number": 67, "usage_type": "call"}]}
+{"seq_id": "456986778", "text": "# -*- coding: utf-8 -*-\n\"\"\" module description \"\"\"\nimport sys\nimport os\nfrom pathlib import Path\n# path_of_this_module = os.path.dirname(__file__)\npath_of_this_module = Path(__file__).parent\nsys.path.append(path_of_this_module)\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5.uic import loadUi\n\n\n\n# sqlite3 操作数据库\n\nclass MainWindow(QMainWindow):\n \"\"\" 主窗口类 \"\"\"\n def __init__(self, parent=None):\n \"\"\" 构造函数 \"\"\"\n super(MainWindow, self).__init__(parent)\n loadUi(path_of_this_module.__str__() + '/' + 'MainWindow.ui', self)\n self.setAction()\n def setAction(self):\n \"\"\" 添加 UI 信号与槽 \"\"\"\n self.label.setText('Ni')\n # pushButton_Culc 计算按钮\n # self.pushButton_Culc.setText('Hello')\n\ndef main():\n \"\"\" 运行程序 \"\"\"\n myApp = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(myApp.exec())\n\nif __name__ == \"__main__\":\n \"\"\" 在本模块测试程序 \"\"\"\n os.system('cls')\n main()\n", "sub_path": "Qt/mainWindow.py", "file_name": "mainWindow.py", "file_ext": "py", "file_size_in_byte": 1038, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pathlib.Path", "line_number": 7, "usage_type": "call"}, {"api_name": "sys.path.append", "line_number": 8, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 8, "usage_type": "attribute"}, {"api_name": "PyQt5.QtWidgets.QMainWindow", "line_number": 16, "usage_type": "name"}, {"api_name": "PyQt5.uic.loadUi", "line_number": 21, "usage_type": "call"}, {"api_name": "PyQt5.QtWidgets.QApplication", "line_number": 31, "usage_type": "call"}, {"api_name": "sys.argv", "line_number": 31, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 34, "usage_type": "call"}, {"api_name": "os.system", "line_number": 38, "usage_type": "call"}]}
+{"seq_id": "26362505", "text": "#! /usr/bin/python3\n\n# Reads new emails and performs tasks if certain commands are found\n\nimport poplib\nimport smtplib\nimport ssl\nfrom urllib.request import urlopen\nimport time\nfrom datetime import datetime\nfrom subprocess import call\nimport threading\nimport traceback\n\n# Constants and Settings\nFROM_NAME = \"Raspi Notification\" # A name for the from email account\nPI_NAME = \"Raspi:\" # A name for the server, this preceeds the subject in every email\nUSER_NAME = \"\" # user@gmail.com\nPASSWORD = \"\" # account password\nSEND_TO = \"\" # reciever email\nRIP_SCRIPTS = {\"Trance\": \"/home/pi/ripTrance.sh\", \"Dubbase.FM\": \"/home/pi/ripDub.sh\"} # Genres and script locations for streamripper\n\n# A dictionary that keeps track if a rip is already in progress for that genre\nis_rip_locked = {}\n\n\n# Read new emails from an account for commands\ndef read_emails():\n done = False\n messages = \"\"\n while not done:\n try:\n # Connect to gmail and send credentials\n pop_conn = poplib.POP3_SSL(\"pop.gmail.com\")\n pop_conn.user(USER_NAME)\n pop_conn.pass_(PASSWORD)\n\n # Connect to server and get new emails\n messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]\n\n # Close server connection and exit the while loop\n pop_conn.quit()\n done = True\n except Exception as e:\n \t# In case of errors, wait a minute then try again\n error_message = \"No arguments found with exception.\"\n if e.args[0]:\n error_message = e.args[0]\n log(\"Read Email Error: \" + str(error_message))\n time.sleep(60)\n # End Read Loop\n\n # Turn the emails into a lower case string\n messages = str(messages).lower()\n\n # Look for key phrases in the emails\n # Uses multi-threading for tasks to keep things moving asyncronously during long tasks.\n\n # Reboots the computer\n if \"reboot\" in messages:\n reboot_pi()\n\n # Exits cmdMail.py\n if \"stop listening\" in messages:\n log(\"No longer listening.\")\n\n # Build and send an email\n sub = PI_NAME + \" Not listening\"\n msg = \"I am no longer listening.\"\n send_email(sub, msg)\n\n # Exit the program\n exit(0)\n\n # Returns the global IP address\n if \"home ip\" in messages:\n t = threading.Thread(target=send_ip_email)\n t.start()\n\n # Wakes a computer over LAN using external program wakeonlan, \n # copy this section and use a different name to allow multiple computers\n if \"wake liten\" in messages:\n t = threading.Thread(target=wake_on_lan, args=(\"Liten\",))\n t.start()\n\n # Rips an internet radio stream using external streamripper program\n if \"rip trance\" in messages:\n genre = \"Trance\"\n t = threading.Thread(target=rip, args=(genre,))\n t.start()\n\n # Rips an internet radio stream using external streamripper progam\n if \"rip dub\" in messages:\n # sleep for 5 seconds to prevent thread overlap with email and log functions when started simultaneously\n time.sleep(5)\n genre = \"Dubbase.FM\"\n t = threading.Thread(target=rip, args=(genre,))\n t.start()\n\n\n# Send an email on script start to notify about a reboot\ndef send_boot_mail():\n # 2 minute delay to allow drivers and internet connection to get going\n time.sleep(120)\n\n log(\"Booting up.\", True)\n\n # Build and send the email\n sub = PI_NAME + \" Startup complete\"\n msg = \"I have successfully booted up.\\n\" + get_home_ip() + \".\"\n send_email(sub, msg)\n\n\n# Send an email with the global IP address in it\ndef send_ip_email():\n log(\"IP requested.\")\n\n # Build and send the email\n sub = PI_NAME + \" Home IP\"\n msg = get_home_ip() + \".\"\n send_email(sub, msg)\n\n# Returns a string with the home global IP\ndef get_home_ip():\n return \"Home IP address: \" + str(urlopen(\"http://ipecho.net/plain\").read().decode(\"utf-8\"))\n\n# Wakes a computer up over LAN network\ndef wake_on_lan(hostname):\n log(\"Waking Liten.\")\n\n # Try waking Liten 4 times\n for x in range(4):\n call([\"wakeonlan\", \"\"])\n print()\n\n # Build and send the email\n sub = PI_NAME + \" WOL \" + str(hostname)\n msg = \"I have woken \" + str(hostname) + \".\"\n send_email(sub, msg)\n\n # Try waking Liten another 4 times\n for x in range(4):\n call([\"wakeonlan\", \"\"])\n print()\n\n\n# Starts a new streamripper of dubstep music, the script will send an email when it is done\ndef rip(genre):\n global is_rip_locked\n\n # If there is already a stream being downloaded, it will have a true value in this dictionary\n # A new stream will delete and corrupt the current one.\n if is_rip_locked[genre]:\n log(genre + \" is locked, aborting rip.\")\n\n # Build and send and email, then exit this function\n sub = PI_NAME + \" \" + genre + \" ripper stream locked\"\n msg = \"Another process is ripping \" + genre + \". So I won't start a new rip.\"\n send_email(sub, msg)\n else:\n \t# The value returned false and so a streamrip can be started\n log(\"Ripping \" + genre + \".\")\n\n # Build and send the email confirming the command\n sub = PI_NAME + \" \" + genre + \" Streamripper started\"\n msg = \"I have started the \" + genre + \" stream rip.\"\n send_email(sub, msg)\n\n # Lock the genre from being ripped multiple times\n is_rip_locked[genre] = True\n\n # Start the ripper, the thread will wait here until the rip is finished\n call([RIP_SCRIPTS[genre]])\n\n # Unlock the genre so it can be ripped again\n is_rip_locked[genre] = False\n\n log(\"Finished Ripping \" + genre + \".\")\n\n # Build and send the email when the rip is done\n sub = PI_NAME + \" \" + genre + \" Streamripper done\"\n msg = \"I just wanted to let you know that your \" + genre + \" stream is saved.\"\n send_email(sub, msg)\n\n\n# Reboot the device\ndef reboot_pi():\n log(\"Rebooting now.\")\n\n # Build and send the email confirming the command\n sub = PI_NAME + \" Rebooting\"\n msg = \"cmdMail has requested a reboot. I will be back online in a few... hopefully.\"\n send_email(sub, msg)\n\n # Wait 15 seconds for the mail to finish sending\n time.sleep(15)\n call([\"sudo reboot\"])\n\n\n# Send an email\ndef send_email(subject, message=\" \"):\n\t# Construct the email in single-string format\n eml = \"\\r\\n\".join([\"From: %s\" % FROM_NAME, \"To: %s\" % SEND_TO, \"Subject: %s\" % subject, \"\", message])\n\n # Keep trying until the email is successfully sent\n sent = False\n while not sent:\n try:\n # Log in and send, magic.\n server = smtplib.SMTP(\"smtp.gmail.com\", 587)\n server.ehlo()\n server.starttls()\n server.login(USER_NAME, PASSWORD)\n server.sendmail(FROM_NAME, [SEND_TO], eml)\n server.quit()\n # Sent ends the loop\n sent = True\n except smtplib.SMTPException as e:\n \t# In case of errors, wait a minute and then resend\n \t# Subject can help identify what function tried to send the email\n log(\"Send Email Error: \" + subject + \", \" + str(e.strerror) + \".\")\n time.sleep(60)\n # End Send Loop\n\n\n# Write a new line to the log file\ndef log(entry, on_boot=False):\n # Create a new file if log doesn't exist, otherwise append a log entry\n with open(\"/home/pi/cmdMail_log.txt\", \"a\") as f:\n\n \t# Visible separation for new boot up.\n if on_boot:\n f.write(\"\\n\\n\\n\")\n\n \t# Construct a timestamp\n d = datetime.now()\n\n # Write the line using a date/time stamp and the message\n f.write(d.strftime(\"%c\") + \" - \" + entry + \"\\n\")\n # Log File is closed\n\n\n# ENTRY POINT\ndef main():\n\tglobal is_rip_locked\n\n\t# Make the is_rip_locked dictionary\n\tfor station in RIP_SCRIPTS:\n\t is_rip_locked[station] = False\n\n\t# Ensure the user has setup the script\n\tif USER_NAME == \"\" or SEND_TO == \"\":\n\t\tlog(\"Emails variables are not setup.\")\n\t\texit(1)\n\n\t# Start by sending a boot up email.\n\tsend_boot_mail()\n\n\t# Continuously monitor email for new commands, pausing every 30 seconds\n\ttry:\n\t while True:\n\t read_emails()\n\t time.sleep(30)\n\texcept:\n\t\t# In case of an uncaught exception, get stacktrace for diag and exit.\n\t trace_string = traceback.format_exc()\n\n\t # log it locally in case internet is down\n\t log(\"Something happened, I have crashed:\\n\" + trace_string)\n\n\t # Build and send an email\n\t sub = PI_NAME + \" cmdMail crashed\"\n\t msg = \"Something went wrong with cmdMail, here is the stack trace:\\n\\n\" + trace_string\n\t send_email(sub, msg)\n\n\t # Exit the program with error code 1\n\t exit(1)\n\nmain()", "sub_path": "cmdMail.py", "file_name": "cmdMail.py", "file_ext": "py", "file_size_in_byte": 8710, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "poplib.POP3_SSL", "line_number": 34, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 50, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 77, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 83, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 89, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 95, "usage_type": "call"}, {"api_name": "threading.Thread", "line_number": 97, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 104, "usage_type": "call"}, {"api_name": "urllib.request.urlopen", "line_number": 125, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 133, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 143, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 173, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 196, "usage_type": "call"}, {"api_name": "subprocess.call", "line_number": 197, "usage_type": "call"}, {"api_name": "smtplib.SMTP", "line_number": 210, "usage_type": "call"}, {"api_name": "smtplib.SMTPException", "line_number": 218, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 222, "usage_type": "call"}, {"api_name": "datetime.datetime.now", "line_number": 236, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 236, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 263, "usage_type": "call"}, {"api_name": "traceback.format_exc", "line_number": 266, "usage_type": "call"}]}
+{"seq_id": "407774035", "text": "import pickle\nimport sys\n\nimport numpy as np\nimport pandas as pd\nfrom hyperopt import hp, tpe, Trials\nfrom hyperopt.fmin import fmin\n\nsys.path.insert(0, '..')\nfrom src.models.model import mase\nimport lightgbm as lgb\nfrom pathlib import Path\n\n\ndef cv_lgboost(model, X_base=None, y=None):\n train_index = X_base.index.year.isin([2016, 2017])\n valid_index = X_base.index.year.isin([2018])\n X_train, X_valid = X_base.iloc[train_index], X_base.iloc[valid_index]\n y_train, y_valid = y.iloc[train_index], y.iloc[valid_index]\n\n model.fit(X_train.values, y_train.values.reshape(-1, ))\n # ntree = model.best_iteration_\n preds = model.predict(X_valid.values)\n oof_scores = mase(preds, y_valid.values)\n return oof_scores\n\n\nproject_dir = Path(__file__).resolve().parents[2]\nprint(project_dir)\ndata_dict = pd.read_pickle(f'{project_dir}/data/processed/data_dict_all.pkl')\n\n# Load the data\nyear = 2019\ntgt = 'rougher.output.recovery'\nX = data_dict[year][f'X_train_tsclean'] # .drop(cols_drop,axis = 1)\ny = data_dict[year]['y_train']\nmask = data_dict[year]['mask']\nX = X.loc[mask.index, :][mask]\ny = y.loc[mask.index, :][mask]\nprint(f'2) train: {X.shape}')\ny = y.loc[X.index, tgt]\nX_filt = X.filter(regex=\"rougher|dayw|hour\", axis=1)\nprint(f'after sample() train: {X.shape}')\n# Load the feature importances\n\nfeature_subset_df = pd.read_csv(f'{project_dir}/notebooks/shap-importance-rougher-diff_deriv_normalized_with_interaction.csv')\nX_sub = X_filt.copy()\nX_sub.columns = [x.replace(\"\\\"\", \"\") for x in X_sub.columns]\n# Actual model training:\nn_array = np.arange(start=50, stop=feature_subset_df.shape[0], step=100, dtype='int')\nfor N in n_array:\n print(f'Evaluating {N} features !')\n feature_subset = feature_subset_df['feature'].head(N)\n X_sub_check = X_sub[feature_subset]\n trials = Trials()\n\n fpath = f'{project_dir}/models/{N}_feats_rougher_Trials.pkl'\n fpath_csv = f'{project_dir}/models/{N}_feats_rougher_Trials.csv'\n def objective(params):\n params = {\n # 'max_depth': int(params['max_depth']),\n 'num_leaves': int(params['num_leaves']), # int(max(2**(int(params['max_depth'])) - params['num_leaves'],0)),\n 'feature_fraction': \"{:.3f}\".format(params['feature_fraction']),\n 'bagging_fraction': '{:.3f}'.format(params['bagging_fraction']),\n 'lambda_l1': params['lambda_l1']\n # \"min_data_in_leaf\": int(params['min_data_in_leaf'])\n }\n m = lgb.LGBMRegressor(objective='mae',n_jobs=8,\n learning_rate=0.05, n_estimators=900, random_state=9,\n **params)\n print(X_sub_check.shape)\n sc = cv_lgboost(m, X_base=X_sub_check, y=y)\n print(\"Score {:.3f} params {}\".format(sc, params))\n return sc\n\n\n space = {\n # 'max_depth': hp.quniform('max_depth', 2, 8, 1),\n 'num_leaves': hp.quniform('num_leaves', 4, 50, 1),\n 'feature_fraction': hp.uniform('feature_fraction', 0.005, 0.9),\n 'bagging_fraction': hp.uniform('bagging_fraction', 0.1, 1.0),\n 'lambda_l1': hp.uniform('lambda_l1', 0.1, 80)\n # \"min_data_in_leaf\": hp.loguniform(\"min_data_in_leaf\",1,8)\n }\n best_lgbm = fmin(fn=objective,\n space=space,\n algo=tpe.suggest,\n max_evals=80,trials = trials)\n losses = [trials.trials[i]['result']['loss'] for i in range(len(trials.trials))]\n params = pd.DataFrame(trials.vals)\n params['loss'] = losses\n params.sort_values('loss', inplace=True)\n params.to_csv(fpath_csv)\n with open(fpath, 'wb') as f:\n pickle.dump(trials, f)", "sub_path": "src/models/hyperopt_model_cv2018_rougher.py", "file_name": "hyperopt_model_cv2018_rougher.py", "file_ext": "py", "file_size_in_byte": 3643, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "sys.path.insert", "line_number": 9, "usage_type": "call"}, {"api_name": "sys.path", "line_number": 9, "usage_type": "attribute"}, {"api_name": "src.models.model.mase", "line_number": 24, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 28, "usage_type": "call"}, {"api_name": "pandas.read_pickle", "line_number": 30, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 46, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 50, "usage_type": "call"}, {"api_name": "hyperopt.Trials", "line_number": 55, "usage_type": "call"}, {"api_name": "lightgbm.LGBMRegressor", "line_number": 68, "usage_type": "call"}, {"api_name": "hyperopt.hp.quniform", "line_number": 79, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 79, "usage_type": "name"}, {"api_name": "hyperopt.hp.uniform", "line_number": 80, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 80, "usage_type": "name"}, {"api_name": "hyperopt.hp.uniform", "line_number": 81, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 81, "usage_type": "name"}, {"api_name": "hyperopt.hp.uniform", "line_number": 82, "usage_type": "call"}, {"api_name": "hyperopt.hp", "line_number": 82, "usage_type": "name"}, {"api_name": "hyperopt.fmin.fmin", "line_number": 85, "usage_type": "call"}, {"api_name": "hyperopt.tpe.suggest", "line_number": 87, "usage_type": "attribute"}, {"api_name": "hyperopt.tpe", "line_number": 87, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 90, "usage_type": "call"}, {"api_name": "pickle.dump", "line_number": 95, "usage_type": "call"}]}
+{"seq_id": "626664621", "text": "import discord\nfrom discord import *\nimport asyncio\nimport tldextract\nimport requests\nimport json\nfrom urllib.parse import urlparse\nfrom utils import cprint, url_validator, load_paywalls, load_token, and_includes, or_includes, strip\nimport random\nfrom ast import literal_eval\nfrom datetime import datetime, timedelta\n\n# load paywalled sites\npaywalled_sites = load_paywalls()\n\n# load bot token\ntoken = load_token()\n\n# creates discord Client object\nclient = discord.Client()\n\n#check last rate limiter check in time\nlast_check_in = None\n\n# all responses triggered by a message are thrown in here\n@client.event\nasync def on_message(message: Message):\n \n \n\n global paywalled_sites # include list of paywalled site inside this function\n global last_check_in\n \n #rate limiter\n if message:\n try:\n #TODO: Put some random fuzz on the checkin timedelta\n #TODO: Lower the checkin time delta based on the subsequent frequency\n if not last_check_in or last_check_in < (message.created_at - timedelta(seconds = 60)):\n #grab the non-bot members\n memb_ls=[m async for m in message.guild.fetch_members(limit=None) if not m.bot]\n #grab the last ten minutes of messages, up to 600 messages\n last_check_in = message.created_at\n ten_min_ago = message.created_at - timedelta(seconds = 600)\n messages = await message.channel.history(limit = 600, after = ten_min_ago).flatten()\n #get the history of message authors who aren't bots\n human_authors_history = [m.author for m in messages if m.author in memb_ls] \n #get the unique authors\n human_author_set = set(human_authors_history)\n #if two users are talking\n prefix = None\n if len(human_author_set) == 2:\n prefix = f\"{list(human_author_set)[0].mention} and {list(human_author_set)[1].mention} are \"\n #if one user is talking to themself\n elif len(human_author_set) == 1:\n prefix = f\"{list(human_author_set)[0].mention} is \"\n if prefix:\n if len(messages) > 100:\n await message.channel.send(prefix + \"going at it. Wow!\")\n if len(messages) > 200:\n await message.channel.send(prefix + \"getting into some serious behavior.\")\n if len(messages) > 300:\n await message.channel.send(prefix + \"setting a record!\")\n if len(messages) > 400:\n await message.channel.send(prefix + \"very serious about this!\")\n if len(messages) > 500:\n await message.channel.send(prefix + \", shut up. Please.\")\n except:\n pass\n\n if message.content.startswith('!paywall'):\n # Manually link to archive.is\n # Format: `!paywall URL` will link to archive.is/URL\n words = message.content.split(\" \")\n await message.channel.send(f\"https://www.archive.is/{words[1]}\")\n\n if and_includes(message.content, 'thank', 'soros'):\n # Responds to Sal when he says 'Thanks Soros'\n # (note: not antisemitic joke, used to mock the antisemitic globalist Soros stories)\n await message.channel.send('No problemo buckaroo, anything for a fellow reptile.')\n \n if and_includes(message.content, 'who', 'horrible'):\n # You know what this does\n await message.channel.send(f\"Why, {message.author.mention} of course!\")\n\n if or_includes(message.content, 'socialis', 'communis'):\n # You know what this does\n await message.channel.send(f\"AJ is the real commie here!\")\n \n if or_includes(message.content, 'shane', 'metricity', 'the best') and (message.author != client.user):\n await message.channel.send(f\"Shane really is the best.\")\n \n if or_includes(message.content, \"suck\", \"sux\") and (message.author != client.user):\n # ya know what this does too\n await message.channel.send(\"You know what else sucks? Salex Bexman.\")\n\n if url_validator(message.content):\n # Checks if message is a valid URL and a paywalled domain. If it is, returns the archive.is link.\n raw_url = message.content\n url = tldextract.extract(message.content)\n if url.domain in paywalled_sites:\n await message.channel.send(f\"https://www.archive.is/{raw_url}\")\n \n if message.content.startswith('!add'):\n # Add new domains to list of paywalled domains\n # Format: `!add DOMAIN_1 DOMAIN_2 ... DOMAIN_n` will add DOMAIN_1 thru DOMAIN_n to list\n # of paywalled sites and respond with a confirmation message.\n new_paywalls = message.content.split(\" \")[1:]\n paywalled_sites += new_paywalls\n paywalled_sites = list(set(paywalled_sites))\n paywalled_sites = [i for i in paywalled_sites if i != \"\"]\n with open('paywalled', 'w') as file:\n sites = \"\\n\".join(paywalled_sites)\n file.write(sites)\n await message.channel.send('**Added the following domains:**' + \"\\n\" + cprint(new_paywalls))\n\n if message.content.startswith('!delete'):\n # Delete domains to list of paywalled domains\n # Format: `!add DOMAIN_1 DOMAIN_2 ... DOMAIN_n` will add DOMAIN_1 thru DOMAIN_n to list\n # of paywalled sites and respond with a confirmation message.\n new_paywalls = message.content.split(\" \")[1:]\n paywalled_sites = [i for i in paywalled_sites if i not in new_paywalls]\n with open('paywalled', 'w') as file:\n sites = \"\\n\".join(paywalled_sites)\n file.write(sites)\n await message.channel.send('**Deleted the following domains:**' + \"\\n\" + cprint(new_paywalls))\n \n if message.content.startswith(\"!list paywalls\"):\n # Displays list of all sites on the current paywall list\n await message.channel.send(\"**Paywalled sites:**\" + \"\\n\" + cprint(sorted(paywalled_sites)))\n \n if message.content.startswith(\"!test\"):\n await message.channel.send(\"Stop spamming the fucking chat with your damn tests u chode.\")\n \n if message.content.startswith(\"!gif\"):\n async with message.channel.typing(): #makes the channel say the bot is typing\n scope = 1\n melee = False\n num_gifs = 1\n parsed = message.content.split(\" \")\n if parsed[1] == 'melee':\n melee = True\n stripped = [strip(word) for word in parsed[2:]]\n else:\n stripped = [strip(word) for word in parsed[1:]]\n search = \"+\".join(stripped)\n try:\n scope_str = parsed[0][4:]\n scope = int(scope_str)\n if melee:\n num_gifs = scope\n except:\n pass\n choice = random.randint(1, scope)\n response = requests.get(f\"https://api.giphy.com/v1/gifs/search?q={search}&api_key=WiLstLIo2SInusTmGDDkhhY0tU6xKNEl&limit={num_gifs}&offset={choice}\")\n if response.status_code != 200:\n await message.channel.send(\"U stupid bruh, bad request.\")\n else:\n gifs = response.json()['data']\n gif_urls = [gif['url'] for gif in gifs]\n for url in gif_urls:\n await message.channel.send(url)\n\n if message.content.startswith(\"!calc\"):\n async with message.channel.typing(): #makes the channel say the bot is typing\n terms = \" \".join(message.content.split(\" \")[1:])\n await message.channel.send(eval(terms))\n\nif __name__ == \"__main__\":\n client.run(token)", "sub_path": "archivist.py", "file_name": "archivist.py", "file_ext": "py", "file_size_in_byte": 7776, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "utils.load_paywalls", "line_number": 14, "usage_type": "call"}, {"api_name": "utils.load_token", "line_number": 17, "usage_type": "call"}, {"api_name": "discord.Client", "line_number": 20, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 39, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 44, "usage_type": "call"}, {"api_name": "utils.and_includes", "line_number": 77, "usage_type": "call"}, {"api_name": "utils.and_includes", "line_number": 82, "usage_type": "call"}, {"api_name": "utils.or_includes", "line_number": 86, "usage_type": "call"}, {"api_name": "utils.or_includes", "line_number": 90, "usage_type": "call"}, {"api_name": "utils.or_includes", "line_number": 93, "usage_type": "call"}, {"api_name": "utils.url_validator", "line_number": 97, "usage_type": "call"}, {"api_name": "tldextract.extract", "line_number": 100, "usage_type": "call"}, {"api_name": "utils.cprint", "line_number": 115, "usage_type": "call"}, {"api_name": "utils.cprint", "line_number": 126, "usage_type": "call"}, {"api_name": "utils.cprint", "line_number": 130, "usage_type": "call"}, {"api_name": "utils.strip", "line_number": 143, "usage_type": "call"}, {"api_name": "utils.strip", "line_number": 145, "usage_type": "call"}, {"api_name": "random.randint", "line_number": 154, "usage_type": "call"}, {"api_name": "requests.get", "line_number": 155, "usage_type": "call"}]}
+{"seq_id": "95671195", "text": "\"\"\"\n mbed CMSIS-DAP debugger\n Copyright (c) 2006-2015 ARM Limited\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nfrom pyOCD.target.target import TARGET_RUNNING\nimport logging\nfrom struct import unpack\nfrom time import time\nfrom flash_builder import FLASH_PAGE_ERASE, FLASH_CHIP_ERASE, FlashBuilder\n\nDEFAULT_PAGE_PROGRAM_WEIGHT = 0.130\nDEFAULT_PAGE_ERASE_WEIGHT = 0.048\nDEFAULT_CHIP_ERASE_WEIGHT = 0.174\n\n# Program to compute the CRC of sectors. This works on cortex-m processors.\n# Code is relocatable and only needs to be on a 4 byte boundary.\n# 200 bytes of executable data below + 1024 byte crc table = 1224 bytes\n# Usage requirements:\n# -In memory reserve 0x600 for code & table\n# -Make sure data buffer is big enough to hold 4 bytes for each page that could be checked (ie. >= num pages * 4)\nanalyzer = (\n 0x2180468c, 0x2600b5f0, 0x4f2c2501, 0x447f4c2c, 0x1c2b0049, 0x425b4033, 0x40230872, 0x085a4053,\n 0x425b402b, 0x40534023, 0x402b085a, 0x4023425b, 0x085a4053, 0x425b402b, 0x40534023, 0x402b085a,\n 0x4023425b, 0x085a4053, 0x425b402b, 0x40534023, 0x402b085a, 0x4023425b, 0x085a4053, 0x425b402b,\n 0x40534023, 0xc7083601, 0xd1d2428e, 0x2b004663, 0x4663d01f, 0x46b4009e, 0x24ff2701, 0x44844d11,\n 0x1c3a447d, 0x88418803, 0x4351409a, 0xd0122a00, 0x22011856, 0x780b4252, 0x40533101, 0x009b4023,\n 0x0a12595b, 0x42b1405a, 0x43d2d1f5, 0x4560c004, 0x2000d1e7, 0x2200bdf0, 0x46c0e7f8, 0x000000b6,\n 0xedb88320, 0x00000044,\n )\n\ndef _msb( n ):\n ndx = 0\n while ( 1 < n ):\n n = ( n >> 1 )\n ndx += 1\n return ndx\n\nclass PageInfo(object):\n\n def __init__(self):\n self.erase_weight = None # Time it takes to erase a page\n self.program_weight = None # Time it takes to program a page (Not including data transfer time)\n self.size = None # Size of page\n self.crc_supported = None # Is the function computeCrcs supported?\n\nclass FlashInfo(object):\n\n def __init__(self):\n self.rom_start = None # Starting address of ROM\n self.erase_weight = None # Time it takes to perform a chip erase\n\nclass Flash(object):\n \"\"\"\n This class is responsible to flash a new binary in a target\n \"\"\"\n\n def __init__(self, target, flash_algo):\n self.target = target\n self.flash_algo = flash_algo\n if flash_algo is not None:\n self.end_flash_algo = flash_algo['load_address'] + len(flash_algo)*4\n self.begin_stack = flash_algo['begin_stack']\n self.begin_data = flash_algo['begin_data']\n self.static_base = flash_algo['static_base']\n self.page_size = flash_algo['page_size']\n else:\n self.end_flash_algo = None\n self.begin_stack = None\n self.begin_data = None\n self.static_base = None\n self.page_size = None\n\n def init(self):\n \"\"\"\n Download the flash algorithm in RAM\n \"\"\"\n self.target.halt()\n self.target.setTargetState(\"PROGRAM\")\n\n # download flash algo in RAM\n self.target.writeBlockMemoryAligned32(self.flash_algo['load_address'], self.flash_algo['instructions'])\n if self.flash_algo['analyzer_supported']:\n self.target.writeBlockMemoryAligned32(self.flash_algo['analyzer_address'], analyzer)\n\n # update core register to execute the init subroutine\n self.updateCoreRegister(0, 0, 0, 0, self.flash_algo['pc_init'])\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('init error: %i', result)\n\n return\n\n def computeCrcs(self, sectors):\n\n data = []\n\n # Convert address, size pairs into commands\n # for the crc computation algorithm to preform\n for addr, size in sectors:\n size_val = _msb(size)\n addr_val = addr // size\n # Size must be a power of 2\n assert (1 << size_val) == size\n # Address must be a multiple of size\n assert (addr % size) == 0\n val = (size_val << 0) | (addr_val << 16)\n data.append(val)\n\n self.target.writeBlockMemoryAligned32(self.begin_data, data)\n\n # update core register to execute the subroutine\n self.updateCoreRegister(self.begin_data, len(data), 0, 0, self.flash_algo['analyzer_address'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # Read back the CRCs for each section\n data = self.target.readBlockMemoryAligned32(self.begin_data, len(data))\n return data\n\n def eraseAll(self):\n \"\"\"\n Erase all the flash\n \"\"\"\n\n # update core register to execute the eraseAll subroutine\n self.updateCoreRegister(0, 0, 0, 0, self.flash_algo['pc_eraseAll'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('eraseAll error: %i', result)\n\n return\n\n def erasePage(self, flashPtr):\n \"\"\"\n Erase one page\n \"\"\"\n\n # update core register to execute the erasePage subroutine\n self.updateCoreRegister(flashPtr, 0, 0, 0, self.flash_algo['pc_erase_sector'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('erasePage error: %i', result)\n\n return\n\n def programPage(self, flashPtr, bytes):\n \"\"\"\n Flash one page\n \"\"\"\n\n # prevent security settings from locking the device\n bytes = self.overrideSecurityBits(flashPtr, bytes)\n\n # first transfer in RAM\n self.target.writeBlockMemoryUnaligned8(self.begin_data, bytes)\n\n # update core register to execute the program_page subroutine\n self.updateCoreRegister(flashPtr, self.page_size, self.begin_data, 0, self.flash_algo['pc_program_page'])\n\n # resume and wait until the breakpoint is hit\n self.target.resume()\n while(self.target.getState() == TARGET_RUNNING):\n pass\n\n # check the return code\n result = self.target.readCoreRegister('r0')\n if result != 0:\n logging.error('programPage error: %i', result)\n\n return\n\n def getPageInfo(self, addr):\n \"\"\"\n Get info about the page that contains this address\n\n Override this function if variable page sizes are supported\n \"\"\"\n info = PageInfo()\n info.erase_weight = DEFAULT_PAGE_ERASE_WEIGHT\n info.program_weight = DEFAULT_PAGE_PROGRAM_WEIGHT\n info.size = self.flash_algo['page_size']\n return info\n\n def getFlashInfo(self):\n \"\"\"\n Get info about the flash\n\n Override this function to return differnt values\n \"\"\"\n info = FlashInfo()\n info.rom_start = 0\n info.erase_weight = DEFAULT_CHIP_ERASE_WEIGHT\n info.crc_supported = self.flash_algo['analyzer_supported']\n return info\n\n def getFlashBuilder(self):\n return FlashBuilder(self, self.getFlashInfo().rom_start)\n\n def flashBlock(self, addr, data, smart_flash = True, chip_erase = None, progress_cb = None):\n \"\"\"\n Flash a block of data\n \"\"\"\n start = time()\n\n flash_start = self.getFlashInfo().rom_start\n fb = FlashBuilder(self, flash_start)\n fb.addData(addr, data)\n operation = fb.program(chip_erase, progress_cb, smart_flash)\n\n end = time()\n logging.debug(\"%f kbytes flashed in %f seconds ===> %f kbytes/s\" %(len(data)/1024, end-start, len(data)/(1024*(end - start))))\n return operation\n\n def flashBinary(self, path_file, flashPtr = 0x0000000, smart_flash = True, chip_erase = None, progress_cb = None):\n \"\"\"\n Flash a binary\n \"\"\"\n f = open(path_file, \"rb\")\n\n with open(path_file, \"rb\") as f:\n data = f.read()\n data = unpack(str(len(data)) + 'B', data)\n self.flashBlock(flashPtr, data, smart_flash, chip_erase, progress_cb)\n\n def updateCoreRegister(self, r0, r1, r2, r3, pc):\n self.target.writeCoreRegister('pc', pc)\n self.target.writeCoreRegister('r0', r0)\n self.target.writeCoreRegister('r1', r1)\n self.target.writeCoreRegister('r2', r2)\n self.target.writeCoreRegister('r3', r3)\n self.target.writeCoreRegister('r9', self.static_base)\n self.target.writeCoreRegister('sp', self.begin_stack)\n self.target.writeCoreRegister('lr', self.flash_algo['load_address'] + 1)\n return\n\n def overrideSecurityBits(self, address, data):\n return data\n", "sub_path": "pyOCD/flash/flash.py", "file_name": "flash.py", "file_ext": "py", "file_size_in_byte": 9690, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pyOCD.target.target.TARGET_RUNNING", "line_number": 102, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 108, "usage_type": "call"}, {"api_name": "pyOCD.target.target.TARGET_RUNNING", "line_number": 135, "usage_type": "name"}, {"api_name": "pyOCD.target.target.TARGET_RUNNING", "line_number": 152, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 158, "usage_type": "call"}, {"api_name": "pyOCD.target.target.TARGET_RUNNING", "line_number": 172, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 178, "usage_type": "call"}, {"api_name": "pyOCD.target.target.TARGET_RUNNING", "line_number": 198, "usage_type": "name"}, {"api_name": "logging.error", "line_number": 204, "usage_type": "call"}, {"api_name": "flash_builder.FlashBuilder", "line_number": 233, "usage_type": "call"}, {"api_name": "time.time", "line_number": 239, "usage_type": "call"}, {"api_name": "flash_builder.FlashBuilder", "line_number": 242, "usage_type": "call"}, {"api_name": "time.time", "line_number": 246, "usage_type": "call"}, {"api_name": "logging.debug", "line_number": 247, "usage_type": "call"}, {"api_name": "struct.unpack", "line_number": 258, "usage_type": "call"}]}
+{"seq_id": "225994564", "text": "__all__ = ('addon', 'data', 'lattice', 'math', 'mesh', 'modal', 'modifier', 'object', 'ray', 'screen', 'view3d')\r\n\r\nimport traceback\r\n\r\nimport bpy\r\n\r\nfrom bl_ui.space_toolsystem_common import activate_by_id as activate_tool\r\nfrom bl_ui.space_toolsystem_toolbar import VIEW3D_PT_tools_active as view3d_tools\r\n\r\n\r\nname = __name__.partition('.')[0]\r\n\r\n# TODO: create collections for these in preferences\r\nvertice_presets = [3, 6, 8, 32, 64]\r\narray_presets = [2, 4, 6, 8, 10]\r\nwidth_presets = [0.02, 0.05, 0.1]\r\nsegment_presets = [1, 2, 3, 4, 6]\r\nangle_presets = [5, 15, 30, 45, 90]\r\n\r\nnames = {\r\n 'cut': 'Cut',\r\n 'slice': 'Slice',\r\n 'inset': 'Inset',\r\n 'join': 'Join',\r\n 'make': 'Make',\r\n 'knife': 'Knife',\r\n 'snap': 'Snap',\r\n 'negative': 'Negative',\r\n 'bbox': 'Bbox',\r\n 'dot': 'Dot',\r\n 'dot_highlight': 'Highlight',\r\n 'wire': 'Wire',\r\n 'show_shape_wire': 'Show Shape Wire',\r\n 'wire_width': 'Wire Width',\r\n 'bounds': 'Show Bounds',\r\n 'allow_selection': 'Allow Selection',\r\n 'sort_modifiers': 'Sort Modifiers',\r\n 'keep_modifiers': 'Keep Modifiers',\r\n 'ngon_snap_angle': 'Ngon Snap Angle',\r\n 'auto_smooth': 'Auto Smooth',\r\n 'join_flip_z': 'Join Flip Z',\r\n 'use_multi_edit': 'Use Mult-Edit',\r\n 'make_active': 'Shift to Active',\r\n 'show_shape': 'Show Shape',\r\n 'parent_shape': 'Parent Shape',\r\n 'apply_slices': 'Apply Slices',\r\n 'make_align_z': 'Make on Z',\r\n 'offset': 'Offset',\r\n 'destructive_menu': 'Destructive Menu',\r\n 'mode_label': 'Mode Label',\r\n 'shape_label': 'Shape Label',\r\n 'operation_label': 'Operation Label',\r\n 'surface_label': 'Surface Label',\r\n 'wire_only': 'Wires Only',\r\n 'thick_wire': 'Thick Wire',\r\n 'circle_vertices': 'Circle Vertices',\r\n 'bevel_width': 'Bevel Width',\r\n 'bevel_segments': 'Bevel Segments',\r\n 'quad_bevel': 'Quad Bevel',\r\n 'straight_edges': 'Straight Corner Flow',\r\n 'inset_thickness': 'Inset Thickness',\r\n 'solidify_thickness': 'Solidify Thickness',\r\n 'array_count': 'Array Count',\r\n 'lazorcut_limit': 'Lazorcut Limit',\r\n 'quick_execute': 'Quick Execute',\r\n 'simple_trace': 'Simple Trace',\r\n 'edit_disable_modifiers': 'Disable Ctrl & Shift LMB (Edit Mode)',\r\n 'enable_surface_toggle': 'Enable Surface Toggle',\r\n 'cursor': 'Cursor',\r\n 'transform_gizmo': 'Transform Gizmo',\r\n 'reduce_opacity_editmode': 'Reduce Opacity in Edit',\r\n 'scroll_adjust_circle': 'Scroll Adjust Circle',\r\n 'cursor_axis': 'Cursor Axis'}\r\n\r\n\r\ndef active_tool():\r\n return view3d_tools.tool_active_from_context(bpy.context)\r\n\r\n\r\ndef activate_by_name(name):\r\n activate_tool(bpy.context, 'VIEW_3D', name)\r\n\r\n\r\ndef method_handler(method,\r\n arguments = tuple(),\r\n identifier = str(),\r\n exit_method = None,\r\n exit_arguments= tuple(),\r\n return_result = False,\r\n return_value = {'CANCELLED'}):\r\n '''\r\n method: method to call\r\n arguments: method arguments\r\n identifier: optional identifer for printout\r\n exit_method: optional exit method to call on exception\r\n exit_arguments: exit method arguments\r\n return_result: allows return of the method and values\r\n return_value: return value on exception\r\n '''\r\n identifier = identifier + ' ' if identifier else ''\r\n try:\r\n if return_result:\r\n return method(*arguments)\r\n else:\r\n method(*arguments)\r\n except Exception:\r\n print(F'\\n{name} {identifier}Method Failed:\\n')\r\n traceback.print_exc()\r\n\r\n if exit_method:\r\n try:\r\n if return_result:\r\n return exit_method(*exit_arguments)\r\n else:\r\n exit_method(*exit_arguments)\r\n except Exception:\r\n print(F'\\n{name} {identifier}Exit Method Failed:\\n')\r\n traceback.print_exc()\r\n\r\n if return_result:\r\n try: return return_value\r\n except Exception:\r\n print(F'\\n{name} {identifier}Exit Return Value Failed:\\n')\r\n traceback.print_exc()\r\n", "sub_path": "addon/utility/__init__.py", "file_name": "__init__.py", "file_ext": "py", "file_size_in_byte": 4061, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "bl_ui.space_toolsystem_toolbar.VIEW3D_PT_tools_active.tool_active_from_context", "line_number": 77, "usage_type": "call"}, {"api_name": "bl_ui.space_toolsystem_toolbar.VIEW3D_PT_tools_active", "line_number": 77, "usage_type": "name"}, {"api_name": "bpy.context", "line_number": 77, "usage_type": "attribute"}, {"api_name": "bl_ui.space_toolsystem_common.activate_by_id", "line_number": 81, "usage_type": "call"}, {"api_name": "bpy.context", "line_number": 81, "usage_type": "attribute"}, {"api_name": "traceback.print_exc", "line_number": 108, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 118, "usage_type": "call"}, {"api_name": "traceback.print_exc", "line_number": 124, "usage_type": "call"}]}
+{"seq_id": "321261784", "text": "from datetime import date\n\nname = input(\"Enter Name\")\nage = input(\"Enter Age\")\n\nif age.isalpha():\n print(\"Enter Age Number\")\nelse:\n final = 100 - int(age)\n current = date.today()\n print(name + \"is 100 years at \" + str(current.year + final))\n", "sub_path": "1.py", "file_name": "1.py", "file_ext": "py", "file_size_in_byte": 253, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "datetime.date.today", "line_number": 10, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 10, "usage_type": "name"}]}
+{"seq_id": "576566211", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef pie_chart(data, title = \"Non-Title\"):\n labels = []\n fracs = []\n for label, frac in data.items():\n labels.append(label)\n fracs.append(frac)\n fig, axs = plt.subplots(1, 1)\n\n # Shift the second slice using explode\n axs.pie(fracs, labels=labels, autopct='%.2f%%',shadow=True,\n explode=(0.05,) * len(labels))\n plt.title(title, fontsize=16, weight = 'bold');\n\n plt.show()\n\ndef bar_chart(data, xlable, ylabel, title):\n labels = []\n fracs = []\n for label, frac in data.items():\n labels.append(label)\n fracs.append(frac)\n\n x_pos = [i for i, _ in enumerate(labels)]\n plt.bar(x_pos, fracs, color='red')\n plt.xlabel(xlable)\n plt.ylabel(ylabel)\n plt.title(title)\n\n plt.xticks(x_pos, labels)\n", "sub_path": "code/visualization.py", "file_name": "visualization.py", "file_ext": "py", "file_size_in_byte": 872, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.pyplot.subplots", "line_number": 12, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 12, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 17, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 17, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 19, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 19, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.bar", "line_number": 29, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 29, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 30, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 30, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 31, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 31, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 32, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 32, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 34, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 34, "usage_type": "name"}]}
+{"seq_id": "536618789", "text": "from flask import Blueprint, jsonify, request, abort\nfrom ..exercises.models import Exercise\nfrom ..teams.models import Team\nfrom ..emitters.models import Emitter\nfrom .models import Report, create_job_id\nfrom .validators import ReportValidator, report_create_schema, report_edit_schema\nfrom sqlalchemy import desc\nfrom sqlalchemy.orm import contains_eager, aliased\nfrom .. import db, socketio\nfrom .tasks import generate_report\n\nreports = Blueprint('reports', __name__)\n\n\n@reports.route('/exercise//reports/list')\ndef list_reports(exercise_slug):\n\n # table aliases to facilitate sorting/etc\n # might be able to be global to avoid creating them every time, looking into it\n tx = aliased(Emitter)\n rx = aliased(Emitter)\n team = aliased(Team)\n\n # Query parameters\n offset = request.args.get('page', 1, type=int)\n sort_field = request.args.get('sort', 'team')\n sort_order = request.args.get('sortOrder', 'asc')\n\n # set up order by clause based on supplied parameter\n sorts = {\n 'team': team.name,\n 'tx': tx.name,\n 'rx': rx.name,\n 'minute': Report.minute,\n 'd_plus': Report.d_plus,\n 'hour': Report.hour,\n 'scheduleType': Report.schedule_type\n }\n sort = sorts.get(sort_field, team.name)\n\n # descending sorts\n if sort_order == 'desc':\n sort = desc(sort)\n\n page = (Report.query\n .join(Exercise)\n .filter(Exercise.slug == exercise_slug)\n .join(team, Report.team)\n .outerjoin(rx, Report.rx_emitter)\n .join(tx, Report.tx_emitter)\n .options(contains_eager(Report.team, alias=team),\n contains_eager(Report.tx_emitter, alias=tx),\n contains_eager(Report.rx_emitter, alias=rx))\n .order_by(sort)\n .paginate(page=offset, per_page=25)\n )\n\n return jsonify({'per_page': 25,\n 'current_page': offset,\n 'total': page.total,\n 'reports': [r.serialize() for r in page.items],\n 'exercise': exercise_slug})\n\n\n@reports.route('/exercise//reports/create', methods=['POST'])\ndef create_report(exercise_slug):\n v = ReportValidator(report_create_schema(exercise_slug))\n if v.validate(request.json):\n r = Report()\n v.populate_report(r)\n ex = Exercise.query.filter_by(slug=exercise_slug).first()\n ex.reports.append(r)\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-created', msg)\n return jsonify(msg), 201\n return jsonify(v.errors), 400\n\n\n@reports.route('/exercise//reports/edit', methods=['POST'])\ndef edit_report(exercise_slug):\n v = ReportValidator(report_edit_schema(exercise_slug))\n if v.validate(request.json):\n r = Report.query.get(request.json['id'])\n v.populate_report(r)\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg), 201\n return jsonify(v.errors), 400\n\n\n@reports.route('/exercise//reports/delete/')\ndef delete_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.exercise.slug != exercise_slug:\n abort(400)\n db.session.delete(r)\n db.session.commit()\n msg = {'deleted': r.id}\n socketio.emit('report-deleted', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/play/')\ndef play_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'interval' or r.exercise.slug != exercise_slug:\n abort(400)\n r.repeat_running = True\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/pause/')\ndef pause_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'interval' or r.exercise.slug != exercise_slug:\n abort(400)\n r.repeat_running = False\n r.update_schedule()\n db.session.add(r)\n db.session.commit()\n msg = r.serialize()\n socketio.emit('report-edited', msg)\n return jsonify(msg)\n\n\n@reports.route('/exercise//reports/send/')\ndef send_report(exercise_slug, report_id):\n r = Report.query.get_or_404(report_id)\n if r.schedule_type != 'ondemand' or r.exercise.slug != exercise_slug:\n abort(400)\n r.job_id = create_job_id()\n db.session.add(r)\n db.session.commit()\n generate_report.apply_async(task_id=r.job_id)\n return jsonify({})\n\n", "sub_path": "backend/app/reports/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 4909, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "flask.Blueprint", "line_number": 12, "usage_type": "call"}, {"api_name": "sqlalchemy.orm.aliased", "line_number": 20, "usage_type": "call"}, {"api_name": "emitters.models.Emitter", "line_number": 20, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.aliased", "line_number": 21, "usage_type": "call"}, {"api_name": "emitters.models.Emitter", "line_number": 21, "usage_type": "argument"}, {"api_name": "sqlalchemy.orm.aliased", "line_number": 22, "usage_type": "call"}, {"api_name": "teams.models.Team", "line_number": 22, "usage_type": "argument"}, {"api_name": "flask.request.args.get", "line_number": 25, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 25, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 25, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 26, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 26, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 26, "usage_type": "name"}, {"api_name": "flask.request.args.get", "line_number": 27, "usage_type": "call"}, {"api_name": "flask.request.args", "line_number": 27, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 27, "usage_type": "name"}, {"api_name": "models.Report.minute", "line_number": 34, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 34, "usage_type": "name"}, {"api_name": "models.Report.d_plus", "line_number": 35, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 35, "usage_type": "name"}, {"api_name": "models.Report.hour", "line_number": 36, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 36, "usage_type": "name"}, {"api_name": "models.Report.schedule_type", "line_number": 37, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 37, "usage_type": "name"}, {"api_name": "sqlalchemy.desc", "line_number": 43, "usage_type": "call"}, {"api_name": "models.Report.query.join", "line_number": 45, "usage_type": "call"}, {"api_name": "exercises.models.Exercise", "line_number": 46, "usage_type": "argument"}, {"api_name": "models.Report.query", "line_number": 45, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 45, "usage_type": "name"}, {"api_name": "exercises.models.Exercise.slug", "line_number": 47, "usage_type": "attribute"}, {"api_name": "exercises.models.Exercise", "line_number": 47, "usage_type": "name"}, {"api_name": "models.Report.team", "line_number": 48, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 48, "usage_type": "name"}, {"api_name": "models.Report.rx_emitter", "line_number": 49, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 49, "usage_type": "name"}, {"api_name": "models.Report.tx_emitter", "line_number": 50, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 50, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.contains_eager", "line_number": 51, "usage_type": "call"}, {"api_name": "models.Report.team", "line_number": 51, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 51, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.contains_eager", "line_number": 52, "usage_type": "call"}, {"api_name": "models.Report.tx_emitter", "line_number": 52, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 52, "usage_type": "name"}, {"api_name": "sqlalchemy.orm.contains_eager", "line_number": 53, "usage_type": "call"}, {"api_name": "models.Report.rx_emitter", "line_number": 53, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 53, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 58, "usage_type": "call"}, {"api_name": "validators.ReportValidator", "line_number": 67, "usage_type": "call"}, {"api_name": "validators.report_create_schema", "line_number": 67, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 68, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 68, "usage_type": "name"}, {"api_name": "models.Report", "line_number": 69, "usage_type": "call"}, {"api_name": "exercises.models.Exercise.query.filter_by", "line_number": 71, "usage_type": "call"}, {"api_name": "exercises.models.Exercise.query", "line_number": 71, "usage_type": "attribute"}, {"api_name": "exercises.models.Exercise", "line_number": 71, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 78, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 79, "usage_type": "call"}, {"api_name": "validators.ReportValidator", "line_number": 84, "usage_type": "call"}, {"api_name": "validators.report_edit_schema", "line_number": 84, "usage_type": "call"}, {"api_name": "flask.request.json", "line_number": 85, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 85, "usage_type": "name"}, {"api_name": "models.Report.query.get", "line_number": 86, "usage_type": "call"}, {"api_name": "models.Report.query", "line_number": 86, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 86, "usage_type": "name"}, {"api_name": "flask.request.json", "line_number": 86, "usage_type": "attribute"}, {"api_name": "flask.request", "line_number": 86, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 93, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 94, "usage_type": "call"}, {"api_name": "models.Report.query.get_or_404", "line_number": 99, "usage_type": "call"}, {"api_name": "models.Report.query", "line_number": 99, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 99, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 101, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 106, "usage_type": "call"}, {"api_name": "models.Report.query.get_or_404", "line_number": 111, "usage_type": "call"}, {"api_name": "models.Report.query", "line_number": 111, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 111, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 113, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 120, "usage_type": "call"}, {"api_name": "models.Report.query.get_or_404", "line_number": 125, "usage_type": "call"}, {"api_name": "models.Report.query", "line_number": 125, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 125, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 127, "usage_type": "call"}, {"api_name": "flask.jsonify", "line_number": 134, "usage_type": "call"}, {"api_name": "models.Report.query.get_or_404", "line_number": 139, "usage_type": "call"}, {"api_name": "models.Report.query", "line_number": 139, "usage_type": "attribute"}, {"api_name": "models.Report", "line_number": 139, "usage_type": "name"}, {"api_name": "flask.abort", "line_number": 141, "usage_type": "call"}, {"api_name": "models.create_job_id", "line_number": 142, "usage_type": "call"}, {"api_name": "tasks.generate_report.apply_async", "line_number": 145, "usage_type": "call"}, {"api_name": "tasks.generate_report", "line_number": 145, "usage_type": "name"}, {"api_name": "flask.jsonify", "line_number": 146, "usage_type": "call"}]}
+{"seq_id": "209588323", "text": "from glob import glob\nimport pandas as pd\nfrom multiprocessing import cpu_count, Pool\nfrom os.path import isdir, join, isfile\nfrom functools import partial\nfrom os import scandir\nfrom collections.abc import Iterable\nfrom sqlalchemy import (create_engine, engine, Column,\n Text, Table, MetaData, String,\n Boolean, DateTime, Integer,\n Float, ForeignKey, CheckConstraint, PrimaryKeyConstraint)\nfrom numpy import dtype\nfrom subprocess import Popen, PIPE\n\n\nclass DataModel:\n\n def __init__(self, file_paths_or_dataframe, files_format=None, cpu=None, **kwargs):\n\n self.extension = files_format\n self.load_function = kwargs\n self.cores = cpu\n self.data = file_paths_or_dataframe\n\n @property\n def cores(self):\n\n return self._cpu\n\n @property\n def data(self):\n\n return self._data\n\n @property\n def load_function(self):\n\n return self._load_function\n\n @property\n def extension(self):\n\n return self._extension\n\n @cores.setter\n def cores(self, cpu):\n\n if not cpu:\n self._cpu = cpu_count()\n else:\n self._cpu = cpu\n\n @data.setter\n def data(self, files_path_or_data):\n\n if isinstance(files_path_or_data, (pd.DataFrame, pd.Series)):\n self._data = files_path_or_data\n else:\n if isinstance(files_path_or_data, str):\n if isdir(files_path_or_data):\n self.input = glob(join(files_path_or_data, '*{}'.format(self.extension)))\n elif isfile(files_path_or_data):\n self.input = [files_path_or_data, ]\n elif isinstance(files_path_or_data, (list, tuple)):\n self.input = files_path_or_data\n else:\n raise Exception('file_paths_or_dataframe format is not valid')\n if self.input:\n self._data = self.__get_data()\n\n @load_function.setter\n def load_function(self, kwargs):\n func = self.__get_function()\n if not func:\n self._load_function = None\n else:\n self._load_function = partial(self.func, function=partial(self.__get_function(), **kwargs))\n\n @extension.setter\n def extension(self, format_str):\n\n if format_str is None:\n self._extension = format_str\n elif format_str.lower() in ['json', 'csv', 'xlsx', 'feather', 'parquet']:\n self._extension = '.{}'.format(format_str)\n else:\n raise Exception('extension not valid should be: ')\n\n @staticmethod\n def func(item, function):\n\n try:\n temp_data = function(item)\n if isinstance(temp_data, pd.Series):\n temp_columns = temp_data.index\n else:\n temp_columns = temp_data.columns\n # print(item)\n return temp_columns.tolist(), temp_data.values\n except (pd.errors.ParserError, pd.errors.EmptyDataError, Exception) as error:\n # Logic to catch and log errors in a multiprocessing pool to be implemented\n # pass statement is currently deemed acceptable\n pass\n\n def __convert_to_df(func):\n\n def _wrapped_convert_to_df(self):\n\n output_list = func(self)\n output_list_filtered = [*self.filter_by_type(output_list, Iterable)]\n max_index = len(output_list_filtered)-1\n check_headers = True\n index = 0\n while check_headers:\n headers = output_list_filtered[index][0]\n if headers:\n check_headers = False\n else:\n index += 1\n if index == max_index and not output_list_filtered[index][0]:\n raise Exception('No valid headers found')\n\n data_list = [data_values for columns, data_values\n in output_list_filtered if columns == headers]\n return pd.DataFrame(data_list, columns=headers)\n\n return _wrapped_convert_to_df\n\n @staticmethod\n def filter_by_type(sequence, data_type):\n for element in sequence:\n if isinstance(element, data_type):\n yield element\n\n def __wrapper_parallel_load(func):\n\n def wrapped_parallel_load(self):\n variables, function, n_cpu = func(self)\n pool = Pool(n_cpu)\n multiprocess_output = pool.map(function, variables, n_cpu)\n pool.close()\n pool.join()\n return multiprocess_output\n\n return wrapped_parallel_load\n\n @__convert_to_df\n @__wrapper_parallel_load\n def __get_data(self):\n\n return self.input, self.load_function, self.cores\n\n def split_by(self, granularity):\n \"\"\"\n Splits and remove duplicates from the loaded table based on a columns list\n :param granularity:\n Type: list\n A list of columns for keep\n :return: pandas DataFrame\n \"\"\"\n return self.data[granularity].drop_duplicates().reset_index(drop=True)\n\n def __get_function(self):\n\n functions_dict = {'.json': pd.read_json,\n '.csv': pd.read_csv,\n '.xlsx': pd.read_excel,\n '.feather': pd.read_feather,\n '.parquet': pd.read_parquet}\n if not self.extension:\n return None\n else:\n return functions_dict.get(self.extension)\n\n\nclass DatabaseManagement:\n\n dtypes_dict = {'object': String,\n 'str': String,\n 'int64': Integer,\n 'int': Integer,\n 'float64': Float,\n 'float': Float,\n 'datetime64': DateTime,\n 'bool':\tBoolean}\n\n def __init__(self, username, password, dialect,\n host, port, database_name=None):\n\n self.url = engine.url.URL(**{'password': password,\n 'username': username,\n 'drivername': dialect,\n 'host': host,\n 'port': port,\n 'database': database_name})\n self.engine = self.url\n\n self.meta = MetaData()\n\n @property\n def engine(self):\n\n return self._engine\n\n @engine.setter\n def engine(self, url):\n\n self._engine = create_engine(url)\n\n def to_sql_copy(self, table_name, from_table, columns_kwargs):\n\n if isinstance(from_table, pd.DataFrame):\n\n columns_dict_base = self.__get_parameters_dict(from_table.dtypes.to_dict(),\n columns_kwargs)\n\n for key, item in columns_dict_base.items():\n columns_dict_base[key]['type'] = self.__pandas_to_sql_types(item['type'])\n\n selectable_columns = [self.__column_parameters(items) for items in columns_dict_base.items()]\n\n object_table = Table(table_name, self.meta, *selectable_columns)\n\n if not self.engine.dialect.has_table(self.engine, table_name):\n\n self.meta.create_all(self.engine)\n\n self.__copy_to_table(table_name, from_table, '#')\n\n def __copy_to_table(self, table_name, data, delimiter):\n\n self._open_process()\n statement = \"\\COPY {} from STDIN DELIMITER '{}';\\n\".format(table_name, delimiter)\n print(statement)\n # # COPY DATA IN NEWLY CREATED TABLE\n data = data.apply(lambda col: col.str.replace(delimiter, ' ') if col.dtype == 'object' else col, axis=0)\n data_str = data.to_csv(sep=delimiter, index=False, header=False).split('\\n')[:-1]\n self.psql.stdin.write(bytes(statement, 'utf-8'))\n [self.psql.stdin.write(line) for line in map(lambda row: bytes(row+'\\n', 'utf-8'), data_str)]\n self.psql.stdin.write(bytes(\"\\.\\n\", 'utf-8'))\n\n @staticmethod\n def __get_parameters_dict(main_dict, additional_dict, level_1_key='type'):\n\n output_dict = dict(zip(main_dict.keys(),\n zip(len(main_dict)*[level_1_key, ], main_dict.values())))\n\n output_dict = {key: [value, ] for key, value in output_dict.items()}\n\n for key in output_dict.keys():\n if key in additional_dict.keys():\n for item in additional_dict.get(key).items():\n output_dict.get(key).append(item)\n\n output_dict_w_kwargs = {key: dict(value) for key, value in output_dict.items()}\n\n return output_dict_w_kwargs\n\n @staticmethod\n def __column_parameters(items):\n\n column_name, args = items\n column_type = args.get('type')\n del args['type']\n extra_constraints = []\n if 'CheckConstraint' in args.keys():\n extra_constraints.append(CheckConstraint(args['CheckConstraint']))\n del args['CheckConstraint']\n\n return Column(column_name, column_type, *extra_constraints, **args)\n\n def _open_process(self):\n\n self.psql = Popen(['psql', str(self.url)], stdout=PIPE, stdin=PIPE)\n\n def __pandas_to_sql_types(self, type_to_convert):\n\n if isinstance(type_to_convert, dtype):\n\n type_to_convert = type_to_convert\n\n elif isinstance(type_to_convert, type):\n\n type_to_convert = type_to_convert.__name__\n\n return self.dtypes_dict.get(str(type_to_convert), Text)\n\n def drop_table(self):\n pass\n\n\nif __name__ == '__main__':\n \n # THIS IS A WIP SCRIPT USED TO MOVE DATA FROM INDIVIDUAL FILES\n # TO A POSTRES DATABASE IN THE CLOUD\n # data is on disk; few 100k files; each file represents a song\n\n paths = [i.path for idx, i in enumerate(scandir(r'/Users/********/PycharmProjects/udacity/data')) if idx < 500000]\n\n # data_for_upload = DataModel(paths, 'json', **{'typ': 'series'})\n\n # data has already been harvested and consolidated into a csv\n data_for_upload = DataModel(pd.read_csv('test.csv'))\n\n artists_data = data_for_upload.split_by(['artist_id', 'song_id', 'title', 'duration', 'year'])\n\n # Initializing the DatabaseNanagement class\n # db is hosted in by AWS RDS\n\n db = DatabaseManagement('********', '********',\n 'postgresql', '*******.cvrvhtkqtojs.us-east-2.rds.amazonaws.com',\n 5432, 'postgres')\n\n # COPY 50K RECORDS IN DB IN 5s\n # CREATES TABLE IF DOESNT EXIST\n\n db.to_sql_copy(\"songs_table\", artists_data, columns_kwargs={'artist_id':{'primary_key':False},\n 'song_id':{'nullable':False},\n 'year':{'nullable': True}})\n\n", "sub_path": "main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 10767, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "multiprocessing.cpu_count", "line_number": 49, "usage_type": "call"}, {"api_name": "pandas.DataFrame", "line_number": 56, "usage_type": "attribute"}, {"api_name": "pandas.Series", "line_number": 56, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 60, "usage_type": "call"}, {"api_name": "glob.glob", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 61, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 62, "usage_type": "call"}, {"api_name": "functools.partial", "line_number": 77, "usage_type": "call"}, {"api_name": "pandas.Series", "line_number": 94, "usage_type": "attribute"}, {"api_name": "pandas.errors", "line_number": 100, "usage_type": "attribute"}, {"api_name": "collections.abc.Iterable", "line_number": 110, "usage_type": "argument"}, {"api_name": "pandas.DataFrame", "line_number": 125, "usage_type": "call"}, {"api_name": "multiprocessing.Pool", "line_number": 139, "usage_type": "call"}, {"api_name": "pandas.read_json", "line_number": 165, "usage_type": "attribute"}, {"api_name": "pandas.read_csv", "line_number": 166, "usage_type": "attribute"}, {"api_name": "pandas.read_excel", "line_number": 167, "usage_type": "attribute"}, {"api_name": "pandas.read_feather", "line_number": 168, "usage_type": "attribute"}, {"api_name": "pandas.read_parquet", "line_number": 169, "usage_type": "attribute"}, {"api_name": "sqlalchemy.String", "line_number": 178, "usage_type": "name"}, {"api_name": "sqlalchemy.String", "line_number": 179, "usage_type": "name"}, {"api_name": "sqlalchemy.Integer", "line_number": 180, "usage_type": "name"}, {"api_name": "sqlalchemy.Integer", "line_number": 181, "usage_type": "name"}, {"api_name": "sqlalchemy.Float", "line_number": 182, "usage_type": "name"}, {"api_name": "sqlalchemy.Float", "line_number": 183, "usage_type": "name"}, {"api_name": "sqlalchemy.DateTime", "line_number": 184, "usage_type": "name"}, {"api_name": "sqlalchemy.Boolean", "line_number": 185, "usage_type": "name"}, {"api_name": "sqlalchemy.engine.url.URL", "line_number": 190, "usage_type": "call"}, {"api_name": "sqlalchemy.engine.url", "line_number": 190, "usage_type": "attribute"}, {"api_name": "sqlalchemy.engine", "line_number": 190, "usage_type": "name"}, {"api_name": "sqlalchemy.MetaData", "line_number": 198, "usage_type": "call"}, {"api_name": "sqlalchemy.create_engine", "line_number": 208, "usage_type": "call"}, {"api_name": "sqlalchemy.engine.setter", "line_number": 205, "usage_type": "attribute"}, {"api_name": "sqlalchemy.engine", "line_number": 205, "usage_type": "name"}, {"api_name": "pandas.DataFrame", "line_number": 212, "usage_type": "attribute"}, {"api_name": "sqlalchemy.Table", "line_number": 222, "usage_type": "call"}, {"api_name": "sqlalchemy.CheckConstraint", "line_number": 267, "usage_type": "call"}, {"api_name": "sqlalchemy.Column", "line_number": 270, "usage_type": "call"}, {"api_name": "subprocess.Popen", "line_number": 274, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 274, "usage_type": "name"}, {"api_name": "numpy.dtype", "line_number": 278, "usage_type": "argument"}, {"api_name": "sqlalchemy.Text", "line_number": 286, "usage_type": "argument"}, {"api_name": "os.scandir", "line_number": 298, "usage_type": "call"}, {"api_name": "pandas.read_csv", "line_number": 303, "usage_type": "call"}]}
+{"seq_id": "188023117", "text": "from time import sleep\n\nfrom airflow.contrib.hooks.emr_hook import EmrHook\nfrom airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator\nfrom airflow.exceptions import AirflowException, AirflowSensorTimeout\nfrom airflow.utils import timezone\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass EmrRunStepOperator(EmrAddStepsOperator):\n \"\"\"\n An operator that adds one step to an existing EMR job_flow and then monitors it's execution.\n\n :param job_flow_id: id of the JobFlow to add step to (templated)\n :type job_flow_id: str\n :param aws_conn_id: aws connection to use\n :type aws_conn_id: str\n :param step: EMR step description (templated)\n :type step: dict\n :param poke_interval: interval to check EMR step status\n :type poke_interval: int\n :param timeout: timeout when to stop poking the step\n :type timeout: int\n \"\"\"\n\n template_fields = ['job_flow_id', 'step']\n\n NON_TERMINAL_STATES = ['PENDING', 'RUNNING', 'CONTINUE', 'CANCEL_PENDING']\n FAILED_STATE = ['CANCELLED', 'FAILED', 'INTERRUPTED']\n POKE_INTERVAL = 15 # 15 seconds\n TIMEOUT = 60 * 60 * 5 # 5 hours\n\n @apply_defaults\n def __init__(\n self,\n job_flow_id: str,\n aws_conn_id: str = 'aws_default',\n step: dict = None,\n poke_interval: int = POKE_INTERVAL,\n timeout: int = TIMEOUT,\n *args, **kwargs):\n super(EmrAddStepsOperator, self).__init__(*args, **kwargs)\n self.aws_conn_id = aws_conn_id\n self.job_flow_id = job_flow_id\n if step:\n self.step = step\n else:\n raise AirflowException('EMR step has to be provided')\n self.poke_interval = poke_interval\n self.timeout = timeout\n self.emr = None\n self.step_id = None\n\n def add_emr_step(self):\n self.log.info(f'Adding step to cluster {self.job_flow_id}')\n response = self.emr.add_job_flow_steps(JobFlowId=self.job_flow_id, Steps=self.step)\n\n if not response['ResponseMetadata']['HTTPStatusCode'] == 200:\n raise AirflowException('Adding step failed: %s' % response)\n\n self.log.info(f'Step {response[\"StepIds\"]} added to JobFlow')\n\n return response['StepIds'][0]\n\n def poke_emr_step(self):\n self.log.info(f'Poking step {self.step_id} on EMR cluster {self.job_flow_id}')\n response = self.emr.describe_step(ClusterId=self.job_flow_id, StepId=self.step_id)\n\n if not response['ResponseMetadata']['HTTPStatusCode'] == 200:\n self.log.info(f'Bad HTTP response: {response}')\n return False\n\n state = response['Step']['Status']['State']\n self.log.info(f'Step currently is in {state} state')\n\n if state in self.NON_TERMINAL_STATES:\n return True\n\n if state in self.FAILED_STATE:\n failure_message = self.failure_message_from_response(response)\n raise AirflowException('EMR step failed ' + failure_message)\n\n return False\n\n @staticmethod\n def failure_message_from_response(response):\n failure_details = response['Step']['Status'].get('FailureDetails')\n if failure_details:\n return f'for reason {failure_details.get(\"Reason\")} ' \\\n f'with message {failure_details.get(\"Message\")} ' \\\n f'and log file {failure_details.get(\"LogFile\")}'\n return ''\n\n def execute(self, context):\n self.emr = EmrHook(aws_conn_id=self.aws_conn_id).get_conn()\n\n # Add step to EMR cluster\n self.step_id = self.add_emr_step()\n\n # Monitor EMR step\n self.log.info(f'Start watching step [{self.step_id}]')\n started_at = timezone.utcnow()\n\n while self.poke_emr_step():\n if (timezone.utcnow() - started_at).total_seconds() > self.timeout:\n raise AirflowSensorTimeout('Snap. Time is OUT.')\n self.log.info(f'Sleeping for {self.poke_interval} seconds...')\n sleep(self.poke_interval)\n\n self.log.info(f\"Step [{self.step_id}] completed successfully. Exiting...\")\n", "sub_path": "aws/emr/emr_plugin/operators/emr_run_step_operator.py", "file_name": "emr_run_step_operator.py", "file_ext": "py", "file_size_in_byte": 4115, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "airflow.contrib.operators.emr_add_steps_operator.EmrAddStepsOperator", "line_number": 10, "usage_type": "name"}, {"api_name": "airflow.contrib.operators.emr_add_steps_operator.EmrAddStepsOperator", "line_number": 42, "usage_type": "argument"}, {"api_name": "airflow.exceptions.AirflowException", "line_number": 48, "usage_type": "call"}, {"api_name": "airflow.utils.decorators.apply_defaults", "line_number": 33, "usage_type": "name"}, {"api_name": "airflow.exceptions.AirflowException", "line_number": 59, "usage_type": "call"}, {"api_name": "airflow.exceptions.AirflowException", "line_number": 81, "usage_type": "call"}, {"api_name": "airflow.contrib.hooks.emr_hook.EmrHook", "line_number": 95, "usage_type": "call"}, {"api_name": "airflow.utils.timezone.utcnow", "line_number": 102, "usage_type": "call"}, {"api_name": "airflow.utils.timezone", "line_number": 102, "usage_type": "name"}, {"api_name": "airflow.utils.timezone.utcnow", "line_number": 105, "usage_type": "call"}, {"api_name": "airflow.utils.timezone", "line_number": 105, "usage_type": "name"}, {"api_name": "airflow.exceptions.AirflowSensorTimeout", "line_number": 106, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 108, "usage_type": "call"}]}
+{"seq_id": "571653336", "text": "import nltk\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nnltk.download('vader_lexicon')\nvader = SentimentIntensityAnalyzer()\nvader.lexicon.update({\n 'moon': 5,\n 'rocket': 5,\n 'skyrocket': 5,\n 'bullish': 5,\n 'bearish': -5,\n 'purchased': 2,\n 'bought': 2,\n 'buy': 2,\n 'sell': -2,\n 'sold': -2,\n 'buying': 2,\n 'selling': -2,\n 'purchasing': 2,\n 'HODL': 1,\n 'HODLing': 1,\n 'HODLING': 1,\n 'bull': 5,\n 'bear': 5,\n 'crushes': 5,\n 'beats': 3,\n 'misses': -3,\n 'trouble': -5,\n 'falls': -4,\n 'crashes': -5,\n 'inflationary': -5,\n 'inflation': -5,\n 'launch': 4,\n 'launched': 4,\n 'scarcity': -3,\n 'scarce': -3,\n 'fall': -4,\n 'rise': 4,\n 'rising': 4,\n 'falling': -5,\n 'bubble': -5,\n 'plunge': -5,\n 'plunging': -5,\n 'surge': 4,\n \"ABLE\": 5,\n \"ABUNDANCE\": 5,\n \"ABUNDANT\": 5,\n \"ACCLAIMED\": 5,\n \"ACCOMPLISH\": 5,\n \"ACCOMPLISHED\": 5,\n \"ACCOMPLISHES\": 5,\n \"ACCOMPLISHING\": 5,\n \"ACCOMPLISHMENT\": 5,\n \"ACCOMPLISHMENTS\": 5,\n \"ACHIEVE\": 5,\n \"ACHIEVED\": 5,\n \"ACHIEVEMENT\": 5,\n \"ACHIEVEMENTS\": 5,\n \"ACHIEVES\": 5,\n \"ACHIEVING\": 5,\n \"ADEQUATELY\": 5,\n \"ADVANCEMENT\": 5,\n \"ADVANCEMENTS\": 5,\n \"ADVANCES\": 5,\n \"ADVANCING\": 5,\n \"ADVANTAGE\": 5,\n \"ADVANTAGED\": 5,\n \"ADVANTAGEOUS\": 5,\n \"ADVANTAGEOUSLY\": 5,\n \"ADVANTAGES\": 5,\n \"ALLIANCE\": 5,\n \"ALLIANCES\": 5,\n \"ASSURE\": 5,\n \"ASSURED\": 5,\n \"ASSURES\": 5,\n \"ASSURING\": 5,\n \"ATTAIN\": 5,\n \"ATTAINED\": 5,\n \"ATTAINING\": 5,\n \"ATTAINMENT\": 5,\n \"ATTAINMENTS\": 5,\n \"ATTAINS\": 5,\n \"ATTRACTIVE\": 5,\n \"ATTRACTIVENESS\": 5,\n \"BEAUTIFUL\": 5,\n \"BEAUTIFULLY\": 5,\n \"BENEFICIAL\": 5,\n \"BENEFICIALLY\": 5,\n \"BENEFIT\": 5,\n \"BENEFITED\": 5,\n \"BENEFITING\": 5,\n \"BENEFITTED\": 5,\n \"BENEFITTING\": 5,\n \"BEST\": 5,\n \"BETTER\": 5,\n \"BOLSTERED\": 5,\n \"BOLSTERING\": 5,\n \"BOLSTERS\": 5,\n \"BOOM\": 5,\n \"BOOMING\": 5,\n \"BOOST\": 5,\n \"BOOSTED\": 5,\n \"BREAKTHROUGH\": 5,\n \"BREAKTHROUGHS\": 5,\n \"BRILLIANT\": 5,\n \"CHARITABLE\": 5,\n \"COLLABORATE\": 5,\n \"COLLABORATED\": 5,\n \"COLLABORATES\": 5,\n \"COLLABORATING\": 5,\n \"COLLABORATION\": 5,\n \"COLLABORATIONS\": 5,\n \"COLLABORATIVE\": 5,\n \"COLLABORATOR\": 5,\n \"COLLABORATORS\": 5,\n \"COMPLIMENT\": 5,\n \"COMPLIMENTARY\": 5,\n \"COMPLIMENTED\": 5,\n \"COMPLIMENTING\": 5,\n \"COMPLIMENTS\": 5,\n \"CONCLUSIVE\": 5,\n \"CONCLUSIVELY\": 5,\n \"CONDUCIVE\": 5,\n \"CONFIDENT\": 5,\n \"CONSTRUCTIVE\": 5,\n \"CONSTRUCTIVELY\": 5,\n \"COURTEOUS\": 5,\n \"CREATIVE\": 5,\n \"CREATIVELY\": 5,\n \"CREATIVENESS\": 5,\n \"CREATIVITY\": 5,\n \"DELIGHT\": 5,\n \"DELIGHTED\": 5,\n \"DELIGHTFUL\": 5,\n \"DELIGHTFULLY\": 5,\n \"DELIGHTING\": 5,\n \"DELIGHTS\": 5,\n \"DEPENDABILITY\": 5,\n \"DEPENDABLE\": 5,\n \"DESIRABLE\": 5,\n \"DESIRED\": 5,\n \"DESPITE\": 5,\n \"DESTINED\": 5,\n \"DILIGENT\": 5,\n \"DILIGENTLY\": 5,\n \"DISTINCTION\": 5,\n \"DISTINCTIONS\": 5,\n \"DISTINCTIVE\": 5,\n \"DISTINCTIVELY\": 5,\n \"DISTINCTIVENESS\": 5,\n \"DREAM\": 5,\n \"EASIER\": 5,\n \"EASILY\": 5,\n \"EASY\": 5,\n \"EFFECTIVE\": 5,\n \"EFFICIENCIES\": 5,\n \"EFFICIENCY\": 5,\n \"EFFICIENT\": 5,\n \"EFFICIENTLY\": 5,\n \"EMPOWER\": 5,\n \"EMPOWERED\": 5,\n \"EMPOWERING\": 5,\n \"EMPOWERS\": 5,\n \"ENABLE\": 5,\n \"ENABLED\": 5,\n \"ENABLES\": 5,\n \"ENABLING\": 5,\n \"ENCOURAGED\": 5,\n \"ENCOURAGEMENT\": 5,\n \"ENCOURAGES\": 5,\n \"ENCOURAGING\": 5,\n \"ENHANCE\": 5,\n \"ENHANCED\": 5,\n \"ENHANCEMENT\": 5,\n \"ENHANCEMENTS\": 5,\n \"ENHANCES\": 5,\n \"ENHANCING\": 5,\n \"ENJOY\": 5,\n \"ENJOYABLE\": 5,\n \"ENJOYABLY\": 5,\n \"ENJOYED\": 5,\n \"ENJOYING\": 5,\n \"ENJOYMENT\": 5,\n \"ENJOYS\": 5,\n \"ENTHUSIASM\": 5,\n \"ENTHUSIASTIC\": 5,\n \"ENTHUSIASTICALLY\": 5,\n \"EXCELLENCE\": 5,\n \"EXCELLENT\": 5,\n \"EXCELLING\": 5,\n \"EXCELS\": 5,\n \"EXCEPTIONAL\": 5,\n \"EXCEPTIONALLY\": 5,\n \"EXCITED\": 5,\n \"EXCITEMENT\": 5,\n \"EXCITING\": 5,\n \"EXCLUSIVE\": 5,\n \"EXCLUSIVELY\": 5,\n \"EXCLUSIVENESS\": 5,\n \"EXCLUSIVES\": 5,\n \"EXCLUSIVITY\": 5,\n \"EXEMPLARY\": 5,\n \"FANTASTIC\": 5,\n \"FAVORABLE\": 5,\n \"FAVORABLY\": 5,\n \"FAVORED\": 5,\n \"FAVORING\": 5,\n \"FAVORITE\": 5,\n \"FAVORITES\": 5,\n \"FRIENDLY\": 5,\n \"GAIN\": 5,\n \"GAINED\": 5,\n \"GAINING\": 5,\n \"GAINS\": 5,\n \"GOOD\": 5,\n \"GREAT\": 5,\n \"GREATER\": 5,\n \"GREATEST\": 5,\n \"GREATLY\": 5,\n \"GREATNESS\": 5,\n \"HAPPIEST\": 5,\n \"HAPPILY\": 5,\n \"HAPPINESS\": 5,\n \"HAPPY\": 5,\n \"HIGHEST\": 5,\n \"HONOR\": 5,\n \"HONORABLE\": 5,\n \"HONORED\": 5,\n \"HONORING\": 5,\n \"HONORS\": 5,\n \"IDEAL\": 5,\n \"IMPRESS\": 5,\n \"IMPRESSED\": 5,\n \"IMPRESSES\": 5,\n \"IMPRESSING\": 5,\n \"IMPRESSIVE\": 5,\n \"IMPRESSIVELY\": 5,\n \"IMPROVE\": 5,\n \"IMPROVED\": 5,\n \"IMPROVEMENT\": 5,\n \"IMPROVEMENTS\": 5,\n \"IMPROVES\": 5,\n \"IMPROVING\": 5,\n \"INCREDIBLE\": 5,\n \"INCREDIBLY\": 5,\n \"INFLUENTIAL\": 5,\n \"INFORMATIVE\": 5,\n \"INGENUITY\": 5,\n \"INNOVATE\": 5,\n \"INNOVATED\": 5,\n \"INNOVATES\": 5,\n \"INNOVATING\": 5,\n \"INNOVATION\": 5,\n \"INNOVATIONS\": 5,\n \"INNOVATIVE\": 5,\n \"INNOVATIVENESS\": 5,\n \"INNOVATOR\": 5,\n \"INNOVATORS\": 5,\n \"INSIGHTFUL\": 5,\n \"INSPIRATION\": 5,\n \"INSPIRATIONAL\": 5,\n \"INTEGRITY\": 5,\n \"INVENT\": 5,\n \"INVENTED\": 5,\n \"INVENTING\": 5,\n \"INVENTION\": 5,\n \"INVENTIONS\": 5,\n \"INVENTIVE\": 5,\n \"INVENTIVENESS\": 5,\n \"INVENTOR\": 5,\n \"INVENTORS\": 5,\n \"LEADERSHIP\": 5,\n \"LEADING\": 5,\n \"LOYAL\": 5,\n \"LUCRATIVE\": 5,\n \"MERITORIOUS\": 5,\n \"OPPORTUNITIES\": 5,\n \"OPPORTUNITY\": 5,\n \"OPTIMISTIC\": 5,\n \"OUTPERFORM\": 5,\n \"OUTPERFORMED\": 5,\n \"OUTPERFORMING\": 5,\n \"OUTPERFORMS\": 5,\n \"PERFECT\": 5,\n \"PERFECTED\": 5,\n \"PERFECTLY\": 5,\n \"PERFECTS\": 5,\n \"PLEASANT\": 5,\n \"PLEASANTLY\": 5,\n \"PLEASED\": 5,\n \"PLEASURE\": 5,\n \"PLENTIFUL\": 5,\n \"POPULAR\": 5,\n \"POPULARITY\": 5,\n \"POSITIVELY\": 5,\n \"PREEMINENCE\": 5,\n \"PREEMINENT\": 5,\n \"PREMIER\": 5,\n \"PREMIERE\": 5,\n \"PRESTIGE\": 5,\n \"PRESTIGIOUS\": 5,\n \"PROACTIVE\": 5,\n \"PROACTIVELY\": 5,\n \"PROFICIENCY\": 5,\n \"PROFICIENT\": 5,\n \"PROFICIENTLY\": 5,\n \"PROFITABILITY\": 5,\n \"PROFITABLE\": 5,\n \"PROFITABLY\": 5,\n \"PROGRESS\": 5,\n \"PROGRESSED\": 5,\n \"PROGRESSES\": 5,\n \"PROGRESSING\": 5,\n \"PROSPERED\": 5,\n \"PROSPERING\": 5,\n \"PROSPERITY\": 5,\n \"PROSPEROUS\": 5,\n \"PROSPERS\": 5,\n \"REBOUND\": 5,\n \"REBOUNDED\": 5,\n \"REBOUNDING\": 5,\n \"RECEPTIVE\": 5,\n \"REGAIN\": 5,\n \"REGAINED\": 5,\n \"REGAINING\": 5,\n \"RESOLVE\": 5,\n \"REVOLUTIONIZE\": 5,\n \"REVOLUTIONIZED\": 5,\n \"REVOLUTIONIZES\": 5,\n \"REVOLUTIONIZING\": 5,\n \"REWARD\": 5,\n \"REWARDED\": 5,\n \"REWARDING\": 5,\n \"REWARDS\": 5,\n \"SATISFACTION\": 5,\n \"SATISFACTORILY\": 5,\n \"SATISFACTORY\": 5,\n \"SATISFIED\": 5,\n \"SATISFIES\": 5,\n \"SATISFY\": 5,\n \"SATISFYING\": 5,\n \"SMOOTH\": 5,\n \"SMOOTHING\": 5,\n \"SMOOTHLY\": 5,\n \"SMOOTHS\": 5,\n \"SOLVES\": 5,\n \"SOLVING\": 5,\n \"SPECTACULAR\": 5,\n \"SPECTACULARLY\": 5,\n \"STABILITY\": 5,\n \"STABILIZATION\": 5,\n \"STABILIZATIONS\": 5,\n \"STABILIZE\": 5,\n \"STABILIZED\": 5,\n \"STABILIZES\": 5,\n \"STABILIZING\": 5,\n \"STABLE\": 5,\n \"STRENGTH\": 5,\n \"STRENGTHEN\": 5,\n \"STRENGTHENED\": 5,\n \"STRENGTHENING\": 5,\n \"STRENGTHENS\": 5,\n \"STRENGTHS\": 5,\n \"STRONG\": 5,\n \"STRONGER\": 5,\n \"STRONGEST\": 5,\n \"SUCCEED\": 5,\n \"SUCCEEDED\": 5,\n \"SUCCEEDING\": 5,\n \"SUCCEEDS\": 5,\n \"SUCCESS\": 5,\n \"SUCCESSES\": 5,\n \"SUCCESSFUL\": 5,\n \"SUCCESSFULLY\": 5,\n \"SUPERIOR\": 5,\n \"SURPASS\": 5,\n \"SURPASSED\": 5,\n \"SURPASSES\": 5,\n \"SURPASSING\": 5,\n \"TRANSPARENCY\": 5,\n \"TREMENDOUS\": 5,\n \"TREMENDOUSLY\": 5,\n \"UNMATCHED\": 5,\n \"UNPARALLELED\": 5,\n \"UNSURPASSED\": 5,\n \"UPTURN\": 5,\n \"UPTURNS\": 5,\n \"VALUABLE\": 5,\n \"VERSATILE\": 5,\n \"VERSATILITY\": 5,\n \"VIBRANCY\": 5,\n \"VIBRANT\": 5,\n \"WIN\": 5,\n \"WINNER\": 5,\n \"WINNERS\": 5,\n \"WINNING\": 5,\n \"WORTHY\": 5,\n \"PROFIT\": 5,\n \"buy\": 5,\n \"buying\": 5,\n \"buys\": 5,\n \"bought\": 5,\n \"create\": 5,\n \"creates\": 5,\n \"created\": 5,\n \"creating\": 5,\n \"value\": 5,\n \"ABANDON\": -5,\n \"ABANDONED\": -5,\n \"ABANDONING\": -5,\n \"ABANDONMENT\": -5,\n \"ABANDONMENTS\": -5,\n \"ABANDONS\": -5,\n \"ABDICATED\": -5,\n \"ABDICATES\": -5,\n \"ABDICATING\": -5,\n \"ABDICATION\": -5,\n \"ABDICATIONS\": -5,\n \"ABERRANT\": -5,\n \"ABERRATION\": -5,\n \"ABERRATIONAL\": -5,\n \"ABERRATIONS\": -5,\n \"ABETTING\": -5,\n \"ABNORMAL\": -5,\n \"ABNORMALITIES\": -5,\n \"ABNORMALITY\": -5,\n \"ABNORMALLY\": -5,\n \"ABOLISH\": -5,\n \"ABOLISHED\": -5,\n \"ABOLISHES\": -5,\n \"ABOLISHING\": -5,\n \"ABROGATE\": -5,\n \"ABROGATED\": -5,\n \"ABROGATES\": -5,\n \"ABROGATING\": -5,\n \"ABROGATION\": -5,\n \"ABROGATIONS\": -5,\n \"ABRUPT\": -5,\n \"ABRUPTLY\": -5,\n \"ABRUPTNESS\": -5,\n \"ABSENCE\": -5,\n \"ABSENCES\": -5,\n \"ABSENTEEISM\": -5,\n \"ABUSE\": -5,\n \"ABUSED\": -5,\n \"ABUSES\": -5,\n \"ABUSING\": -5,\n \"ABUSIVE\": -5,\n \"ABUSIVELY\": -5,\n \"ABUSIVENESS\": -5,\n \"ACCIDENT\": -5,\n \"ACCIDENTAL\": -5,\n \"ACCIDENTALLY\": -5,\n \"ACCIDENTS\": -5,\n \"ACCUSATION\": -5,\n \"ACCUSATIONS\": -5,\n \"ACCUSE\": -5,\n \"ACCUSED\": -5,\n \"ACCUSES\": -5,\n \"ACCUSING\": -5,\n \"ACQUIESCE\": -5,\n \"ACQUIESCED\": -5,\n \"ACQUIESCES\": -5,\n \"ACQUIESCING\": -5,\n \"ACQUIT\": -5,\n \"ACQUITS\": -5,\n \"ACQUITTAL\": -5,\n \"ACQUITTALS\": -5,\n \"ACQUITTED\": -5,\n \"ACQUITTING\": -5,\n \"ADULTERATE\": -5,\n \"ADULTERATED\": -5,\n \"ADULTERATING\": -5,\n \"ADULTERATION\": -5,\n \"ADULTERATIONS\": -5,\n \"ADVERSARIAL\": -5,\n \"ADVERSARIES\": -5,\n \"ADVERSARY\": -5,\n \"ADVERSE\": -5,\n \"ADVERSELY\": -5,\n \"ADVERSITIES\": -5,\n \"ADVERSITY\": -5,\n \"AFTERMATH\": -5,\n \"AFTERMATHS\": -5,\n \"AGAINST\": -5,\n \"AGGRAVATE\": -5,\n \"AGGRAVATED\": -5,\n \"AGGRAVATES\": -5,\n \"AGGRAVATING\": -5,\n \"AGGRAVATION\": -5,\n \"AGGRAVATIONS\": -5,\n \"ALERTED\": -5,\n \"ALERTING\": -5,\n \"ALIENATE\": -5,\n \"ALIENATED\": -5,\n \"ALIENATES\": -5,\n \"ALIENATING\": -5,\n \"ALIENATION\": -5,\n \"ALIENATIONS\": -5,\n \"ANNOY\": -5,\n \"ANNOYANCE\": -5,\n \"ANNOYANCES\": -5,\n \"ANNOYED\": -5,\n \"ANNOYING\": -5,\n \"ANNOYS\": -5,\n \"ANNUL\": -5,\n \"ANNULLED\": -5,\n \"ANNULLING\": -5,\n \"ANNULMENT\": -5,\n \"ANNULMENTS\": -5,\n \"ANNULS\": -5,\n \"ANOMALIES\": -5,\n \"ANOMALOUS\": -5,\n \"ANOMALOUSLY\": -5,\n \"ANOMALY\": -5,\n \"ANTICOMPETITIVE\": -5,\n \"ANTITRUST\": -5,\n \"ARGUE\": -5,\n \"ARGUED\": -5,\n \"ARGUING\": -5,\n \"ARGUMENT\": -5,\n \"ARGUMENTATIVE\": -5,\n \"ARGUMENTS\": -5,\n \"ARREARAGE\": -5,\n \"ARREARAGES\": -5,\n \"ARREARS\": -5,\n \"ARREST\": -5,\n \"ARRESTED\": -5,\n \"ARRESTS\": -5,\n \"ARTIFICIALLY\": -5,\n \"ASSAULT\": -5,\n \"ASSAULTED\": -5,\n \"ASSAULTING\": -5,\n \"ASSAULTS\": -5,\n \"ASSERTIONS\": -5,\n \"ATTRITION\": -5,\n \"AVERSELY\": -5,\n \"BACKDATING\": -5,\n \"BAD\": -5,\n \"BAIL\": -5,\n \"BAILOUT\": -5,\n \"BALK\": -5,\n \"BALKED\": -5,\n \"BANKRUPT\": -5,\n \"BANKRUPTCIES\": -5,\n \"BANKRUPTCY\": -5,\n \"BANKRUPTED\": -5,\n \"BANKRUPTING\": -5,\n \"BANKRUPTS\": -5,\n \"BANS\": -5,\n \"BARRED\": -5,\n \"BARRIER\": -5,\n \"BARRIERS\": -5,\n \"BOTTLENECK\": -5,\n \"BOTTLENECKS\": -5,\n \"BOYCOTT\": -5,\n \"BOYCOTTED\": -5,\n \"BOYCOTTING\": -5,\n \"BOYCOTTS\": -5,\n \"BREAK\": -5,\n \"BREAKAGE\": -5,\n \"BREAKAGES\": -5,\n \"BREAKDOWN\": -5,\n \"BREAKDOWNS\": -5,\n \"BREAKING\": -5,\n \"BREAKS\": -5,\n \"BRIBE\": -5,\n \"BRIBED\": -5,\n \"BRIBERIES\": -5,\n \"BRIBERY\": -5,\n \"BRIBES\": -5,\n \"BRIBING\": -5,\n \"BRIDGE\": -5,\n \"BROKEN\": -5,\n \"BURDEN\": -5,\n \"BURDENED\": -5,\n \"BURDENING\": -5,\n \"BURDENS\": -5,\n \"BURDENSOME\": -5,\n \"BURNED\": -5,\n \"CALAMITIES\": -5,\n \"CALAMITOUS\": -5,\n \"CALAMITY\": -5,\n \"CANCEL\": -5,\n \"CANCELED\": -5,\n \"CANCELING\": -5,\n \"CANCELLATION\": -5,\n \"CANCELLATIONS\": -5,\n \"CANCELLED\": -5,\n \"CANCELLING\": -5,\n \"CANCELS\": -5,\n \"CARELESS\": -5,\n \"CARELESSLY\": -5,\n \"CARELESSNESS\": -5,\n \"CATASTROPHE\": -5,\n \"CATASTROPHES\": -5,\n \"CATASTROPHIC\": -5,\n \"CATASTROPHICALLY\": -5,\n \"CAUTION\": -5,\n \"CAUTIONARY\": -5,\n \"CAUTIONED\": -5,\n \"CAUTIONING\": -5,\n \"CAUTIONS\": -5,\n \"CEASE\": -5,\n \"CEASED\": -5,\n \"CEASES\": -5,\n \"CEASING\": -5,\n \"CENSURE\": -5,\n \"CENSURED\": -5,\n \"CENSURES\": -5,\n \"CENSURING\": -5,\n \"CHALLENGE\": -5,\n \"CHALLENGED\": -5,\n \"CHALLENGES\": -5,\n \"CHALLENGING\": -5,\n \"CHARGEOFFS\": -5,\n \"CIRCUMVENT\": -5,\n \"CIRCUMVENTED\": -5,\n \"CIRCUMVENTING\": -5,\n \"CIRCUMVENTION\": -5,\n \"CIRCUMVENTIONS\": -5,\n \"CIRCUMVENTS\": -5,\n \"CLAIMING\": -5,\n \"CLAIMS\": -5,\n \"CLAWBACK\": -5,\n \"CLOSED\": -5,\n \"CLOSEOUT\": -5,\n \"CLOSEOUTS\": -5,\n \"CLOSING\": -5,\n \"CLOSINGS\": -5,\n \"CLOSURE\": -5,\n \"CLOSURES\": -5,\n \"COERCE\": -5,\n \"COERCED\": -5,\n \"COERCES\": -5,\n \"COERCING\": -5,\n \"COERCION\": -5,\n \"COERCIVE\": -5,\n \"COLLAPSE\": -5,\n \"COLLAPSED\": -5,\n \"COLLAPSES\": -5,\n \"COLLAPSING\": -5,\n \"COLLISION\": -5,\n \"COLLISIONS\": -5,\n \"COLLUDE\": -5,\n \"COLLUDED\": -5,\n \"COLLUDES\": -5,\n \"COLLUDING\": -5,\n \"COLLUSION\": -5,\n \"COLLUSIONS\": -5,\n \"COLLUSIVE\": -5,\n \"COMPLAIN\": -5,\n \"COMPLAINED\": -5,\n \"COMPLAINING\": -5,\n \"COMPLAINS\": -5,\n \"COMPLAINT\": -5,\n \"COMPLAINTS\": -5,\n \"COMPLICATE\": -5,\n \"COMPLICATED\": -5,\n \"COMPLICATES\": -5,\n \"COMPLICATING\": -5,\n \"COMPLICATION\": -5,\n \"COMPLICATIONS\": -5,\n \"COMPULSION\": -5,\n \"CONCEALED\": -5,\n \"CONCEALING\": -5,\n \"CONCEDE\": -5,\n \"CONCEDED\": -5,\n \"CONCEDES\": -5,\n \"CONCEDING\": -5,\n \"CONCERN\": -5,\n \"CONCERNED\": -5,\n \"CONCERNS\": -5,\n \"CONCILIATING\": -5,\n \"CONCILIATION\": -5,\n \"CONCILIATIONS\": -5,\n \"CONDEMN\": -5,\n \"CONDEMNATION\": -5,\n \"CONDEMNATIONS\": -5,\n \"CONDEMNED\": -5,\n \"CONDEMNING\": -5,\n \"CONDEMNS\": -5,\n \"CONDONE\": -5,\n \"CONDONED\": -5,\n \"CONFESS\": -5,\n \"CONFESSED\": -5,\n \"CONFESSES\": -5,\n \"CONFESSING\": -5,\n \"CONFESSION\": -5,\n \"CONFINE\": -5,\n \"CONFINED\": -5,\n \"CONFINEMENT\": -5,\n \"CONFINEMENTS\": -5,\n \"CONFINES\": -5,\n \"CONFINING\": -5,\n \"CONFISCATE\": -5,\n \"CONFISCATED\": -5,\n \"CONFISCATES\": -5,\n \"CONFISCATING\": -5,\n \"CONFISCATION\": -5,\n \"CONFISCATIONS\": -5,\n \"CONFLICT\": -5,\n \"CONFLICTED\": -5,\n \"CONFLICTING\": -5,\n \"CONFLICTS\": -5,\n \"CONFRONT\": -5,\n \"CONFRONTATION\": -5,\n \"CONFRONTATIONAL\": -5,\n \"CONFRONTATIONS\": -5,\n \"CONFRONTED\": -5,\n \"CONFRONTING\": -5,\n \"CONFRONTS\": -5,\n \"CONFUSE\": -5,\n \"CONFUSED\": -5,\n \"CONFUSES\": -5,\n \"CONFUSING\": -5,\n \"CONFUSINGLY\": -5,\n \"CONFUSION\": -5,\n \"CONSPIRACIES\": -5,\n \"CONSPIRACY\": -5,\n \"CONSPIRATOR\": -5,\n \"CONSPIRATORIAL\": -5,\n \"CONSPIRATORS\": -5,\n \"CONSPIRE\": -5,\n \"CONSPIRED\": -5,\n \"CONSPIRES\": -5,\n \"CONSPIRING\": -5,\n \"CONTEMPT\": -5,\n \"CONTEND\": -5,\n \"CONTENDED\": -5,\n \"CONTENDING\": -5,\n \"CONTENDS\": -5,\n \"CONTENTION\": -5,\n \"CONTENTIONS\": -5,\n \"CONTENTIOUS\": -5,\n \"CONTENTIOUSLY\": -5,\n \"CONTESTED\": -5,\n \"CONTESTING\": -5,\n \"CONTRACTION\": -5,\n \"CONTRACTIONS\": -5,\n \"CONTRADICT\": -5,\n \"CONTRADICTED\": -5,\n \"CONTRADICTING\": -5,\n \"CONTRADICTION\": -5,\n \"CONTRADICTIONS\": -5,\n \"CONTRADICTORY\": -5,\n \"CONTRADICTS\": -5,\n \"CONTRARY\": -5,\n \"CONTROVERSIAL\": -5,\n \"CONTROVERSIES\": -5,\n \"CONTROVERSY\": -5,\n \"CONVICT\": -5,\n \"CONVICTED\": -5,\n \"CONVICTING\": -5,\n \"CONVICTION\": -5,\n \"CONVICTIONS\": -5,\n \"CORRECTED\": -5,\n \"CORRECTING\": -5,\n \"CORRECTION\": -5,\n \"CORRECTIONS\": -5,\n \"CORRECTS\": -5,\n \"CORRUPT\": -5,\n \"CORRUPTED\": -5,\n \"CORRUPTING\": -5,\n \"CORRUPTION\": -5,\n \"CORRUPTIONS\": -5,\n \"CORRUPTLY\": -5,\n \"CORRUPTNESS\": -5,\n \"COSTLY\": -5,\n \"COUNTERCLAIM\": -5,\n})\n\n\ndef get_config():\n return vader\n", "sub_path": "services/reddit/sentiment.py", "file_name": "sentiment.py", "file_ext": "py", "file_size_in_byte": 15918, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "nltk.download", "line_number": 4, "usage_type": "call"}, {"api_name": "nltk.sentiment.vader.SentimentIntensityAnalyzer", "line_number": 5, "usage_type": "call"}]}
+{"seq_id": "238252579", "text": "import logging\n\nimport scrapy\n\nfrom steamSpider.items import Game\nfrom steamSpider.utils.basicUtils import strip_string, strip_tag\n\n\nclass GameSpider(scrapy.Spider):\n \"\"\"\n The main component of the spider that extracts info from web pages\n \"\"\"\n name = \"game\"\n # Scrape all games in the Action section\n start_urls = [\"http://store.steampowered.com/tag/en/Action/#p=0&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=1&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=2&tab=TopSellers\",\n # \"http://store.steampowered.com/tag/en/Action/#p=3&tab=TopSellers\"\n ]\n\n def parse(self, response):\n s = response.url\n if \"tag\" in s: # Search pages\n logging.info(\"Entering search page\")\n # print(response.body)\n print(\"length is: \" + str(len(response.xpath('//div[@id=\"TopSellersRows\"]//a/@href').extract())))\n for target in response.xpath('//div[@id=\"TopSellersRows\"]//a/@href').extract():\n logging.info(\"Target urls are:\" + target)\n yield scrapy.Request(target, callback=self.parse)\n elif \"app\" in s and \"agecheck\" not in s: # make sure we are not stuck at the age check page\n logging.info(\"Scraping game\")\n # print(response.body)\n\n game = Game()\n\n game['game_name'] = strip_string(response.xpath(\"//div[@class='apphub_AppName']/text()\").extract_first())\n game['developer'] = response.xpath(\"//div[@class='details_block']/a/text()\").extract()[1]\n game['release_date'] = response.xpath(\"//span[@class='date']/text()\").extract_first()\n\n # deal with Steam discount; needs to be upgraded when a single page contains more than one price\n # such as starter edition and franchise etc...\n price = response.xpath(\"//div[@class='game_purchase_price price']/text()\").extract_first()\n if price is None:\n price = response.xpath(\"//div[@class='discount_final_price']/text()\").extract_first()\n else:\n price = strip_string(price)\n game['price'] = price\n\n description = strip_string(response.xpath(\"//div[@id='game_area_description']\").extract_first())\n description = strip_tag(description)\n game['full_description'] = description\n\n # Since not all System Requirement sections are of the same format, we just store the paragraph and the\n # cleaning of string is saved when using the data; first part is minimum and the second part is\n\n req = response.xpath(\"//div[@class='sysrec_contents']//ul[@class='bb_ul']/li\").extract()\n r = \"\"\n for s in req:\n r += strip_string(strip_tag(strip_string(s)))\n game['system_requirement'] = r\n\n # Some new releases does not have user reviews, so we just put in 0 and No User Comment\n rating = response.xpath(\"//div[@class='summary column']/span/text()\").extract()\n # rater = response.xpath(\"//span[@class='responsive_hidden']/text()\").extract()\n if len(rating) == 0 or rating is None:\n game[\"rater_short\"] = game[\"rater_long\"] = \"0\"\n game[\"rating_short\"] = game[\"rating_long\"] = \"No User Comment\"\n\n else:\n game[\"rating_short\"] = strip_string(rating[0])\n game['rater_short'] = strip_string(rating[1])\n game[\"rating_long\"] = strip_string(rating[3])\n game[\"rater_long\"] = strip_string(rating[4])\n\n # Store the cover image url; can store all the image links in the\n game[\"image_url\"] = response.xpath(\"//img[@class='game_header_image_full']/@src\").extract_first()\n\n logging.info(\"Game scraped\")\n yield game\n # Will implement another crawler to find comments and store in another database\n\n elif \"sub\" in s and \"agecheck\" not in s: # deal with package page\n for target in response.xpath('//a[@class=\"tab_item_overlay\"]/@href').extract():\n logging.info(\"Target url is:\" + target)\n yield scrapy.Request(target, callback=self.parse)\n elif \"agecheck\" in s:\n logging.info(\"Redirecting from agecheck page\")\n yield scrapy.Request(response.url, callback=self.parse)\n else:\n pass\n", "sub_path": "steamSpider/spiders/gameSpider.py", "file_name": "gameSpider.py", "file_ext": "py", "file_size_in_byte": 4467, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "scrapy.Spider", "line_number": 9, "usage_type": "attribute"}, {"api_name": "logging.info", "line_number": 24, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 28, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 29, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 31, "usage_type": "call"}, {"api_name": "steamSpider.items.Game", "line_number": 34, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 36, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 46, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 49, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_tag", "line_number": 50, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 59, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_tag", "line_number": 59, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 70, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 71, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 72, "usage_type": "call"}, {"api_name": "steamSpider.utils.basicUtils.strip_string", "line_number": 73, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 78, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 84, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 85, "usage_type": "call"}, {"api_name": "logging.info", "line_number": 87, "usage_type": "call"}, {"api_name": "scrapy.Request", "line_number": 88, "usage_type": "call"}]}
+{"seq_id": "140319211", "text": "import argparse\nimport os\nimport sys\n\nfrom path import Path\n\nimport ci\nimport ci.cpp\nimport ci.conan\nimport ci.git\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--isolate-conan-user-home\",\n action=\"store_true\",\n dest=\"home_isolation\",\n default=False,\n )\n subparsers = parser.add_subparsers(title=\"subcommands\", dest=\"command\")\n\n build_and_test_parser = subparsers.add_parser(\"build-and-test\")\n build_and_test_parser.add_argument(\"--profile\", required=True)\n build_and_test_parser.add_argument(\"--coverage\", action=\"store_true\")\n\n subparsers.add_parser(\"deploy\")\n subparsers.add_parser(\"mirror\")\n\n args = parser.parse_args()\n if args.home_isolation:\n ci.conan.set_home_isolation()\n\n ci.conan.update_config()\n\n if args.command == \"build-and-test\":\n src_path = Path.getcwd()\n build_path = \".\" # ci.cpp.Builder runs ctest from the build directory\n # fmt: off\n ctest_flags = [\n \"--build-and-test\",\n src_path,\n build_path,\n \"--build-generator\", \"Ninja\",\n \"--output-on-failure\",\n \"--test-command\", \"bin/test_tconcurrent\",\n ]\n # fmt: on\n if sys.platform == \"darwin\":\n # When a macOS runner runs the tests, the ones waiting for a specific time will wait longer than requested.\n # Thus the tests fail. Funny thing is that they pass when running them by hand, on the slave...\n ctest_flags.append(\"--test-case-exclude=*[waiting]*\")\n built_path = ci.cpp.build(args.profile, coverage=args.coverage)\n ci.cpp.check(built_path, coverage=args.coverage, ctest_flags=ctest_flags)\n elif args.command == \"deploy\":\n git_tag = os.environ[\"CI_COMMIT_TAG\"]\n version = ci.version_from_git_tag(git_tag)\n ci.bump_files(version)\n ci.cpp.build_recipe(\n Path.getcwd(),\n conan_reference=f\"tconcurrent/{version}@tanker/stable\",\n upload=True,\n )\n elif args.command == \"mirror\":\n ci.git.mirror(github_url=\"git@github.com:TankerHQ/tconcurrent\")\n else:\n parser.print_help()\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n", "sub_path": "run-ci.py", "file_name": "run-ci.py", "file_ext": "py", "file_size_in_byte": 2260, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 14, "usage_type": "call"}, {"api_name": "ci.conan.set_home_isolation", "line_number": 32, "usage_type": "call"}, {"api_name": "ci.conan", "line_number": 32, "usage_type": "attribute"}, {"api_name": "ci.conan.update_config", "line_number": 34, "usage_type": "call"}, {"api_name": "ci.conan", "line_number": 34, "usage_type": "attribute"}, {"api_name": "path.Path.getcwd", "line_number": 37, "usage_type": "call"}, {"api_name": "path.Path", "line_number": 37, "usage_type": "name"}, {"api_name": "sys.platform", "line_number": 49, "usage_type": "attribute"}, {"api_name": "ci.cpp.build", "line_number": 53, "usage_type": "call"}, {"api_name": "ci.cpp", "line_number": 53, "usage_type": "attribute"}, {"api_name": "ci.cpp.check", "line_number": 54, "usage_type": "call"}, {"api_name": "ci.cpp", "line_number": 54, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 56, "usage_type": "attribute"}, {"api_name": "ci.version_from_git_tag", "line_number": 57, "usage_type": "call"}, {"api_name": "ci.bump_files", "line_number": 58, "usage_type": "call"}, {"api_name": "ci.cpp.build_recipe", "line_number": 59, "usage_type": "call"}, {"api_name": "ci.cpp", "line_number": 59, "usage_type": "attribute"}, {"api_name": "path.Path.getcwd", "line_number": 60, "usage_type": "call"}, {"api_name": "path.Path", "line_number": 60, "usage_type": "name"}, {"api_name": "ci.git.mirror", "line_number": 65, "usage_type": "call"}, {"api_name": "ci.git", "line_number": 65, "usage_type": "attribute"}, {"api_name": "sys.exit", "line_number": 68, "usage_type": "call"}]}
+{"seq_id": "412670723", "text": "import argparse\nimport torch\nimport pickle\nimport preprocess_data\nfrom model import model_FL\nfrom torch import optim\nfrom pathlib import Path\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import GridSearchCV\nfrom anomalyDetector import fit_norm_distribution_param\nfrom anomalyDetector import anomalyScore\nfrom anomalyDetector import get_precision_recall\nfrom anomalyDetector import get_precision_recall_zsx_2\nfrom anomalyDetector import get_f1\nfrom utils.eval_methods import calc_point2point\nfrom utils.distri2Th import DistriTailNoise2Th\nfrom utils.eval_methods import adjust_predicts_zsx\n\n\n# 有save-fig参数\n\nparser = argparse.ArgumentParser(description='PyTorch RNN Anomaly Detection Model')\nparser.add_argument('--prediction_window_size', type=int, default=10,\n help='prediction_window_size')\nparser.add_argument('--data', type=str, default='ecg',\n help='type of the dataset (ecg, gesture, power_demand, space_shuttle, respiration, nyc_taxi')\nparser.add_argument('--filename', type=str, default='chfdb_chf13_45590.pkl',\n help='filename of the dataset')\nparser.add_argument('--save_fig', action='store_true',\n help='save results as figures')\nparser.add_argument('--compensate', action='store_true',\n help='compensate anomaly score using anomaly score esimation')\nparser.add_argument('--beta', type=float, default=1.0,\n help='beta value for f-beta score')\n\n# 为了DistriTailNoise2Th这个函数的参数,再添加几个参数\n# DistriTailNoise2Th(testScore,difTh,avgNum,meanMulCoefficient,binNum,followNum)\nparser.add_argument('--difTh',type=float,default=-5)\nparser.add_argument('--avgNum',type=int ,default=5)\nparser.add_argument('--meanMulCoefficient',type=float,default=100)\nparser.add_argument('--binNum',type=int,default=60)\nparser.add_argument('--followNum',type=int,default=4)\n\nargs_ = parser.parse_args()\nprint('-' * 89)\nprint(\"=> loading checkpoint \")\ncheckpoint = torch.load(str(Path('save', args_.data, 'checkpoint', args_.filename).with_suffix('.pth')))\nargs = checkpoint['args']\nargs.prediction_window_size = args_.prediction_window_size\nargs.beta = args_.beta\nargs.save_fig = args_.save_fig\nargs.compensate = args_.compensate\nprint(\"=> loaded checkpoint\")\n\n# Set the random seed manually for reproducibility.\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\n\n###############################################################################\n# Load data\n###############################################################################\nTimeseriesData = preprocess_data.PickleDataLoad(data_type=args.data, filename=args.filename, augment_test_data=False)\ntrain_dataset = TimeseriesData.batchify(args, TimeseriesData.trainData[:TimeseriesData.length], bsz=1)\ntest_dataset = TimeseriesData.batchify(args, TimeseriesData.testData, bsz=1)\n\n# 注意,这个时候batchsize都是1\n# [length,1,feature_dim]\n\nfeature_dim = 8+8+8\n\n\n###############################################################################\n# Build the model\n###############################################################################\n#nfeatures = TimeseriesData.trainData.size(-1) # 10\nfeature_data = TimeseriesData.trainData.size(-1) # 10\n\n\nencoder_client_0 = model_FL.encoder_client(enc_client_dims=[[4,8],[8,8]],layer_num=2).to(args.device)\nencoder_client_1 = model_FL.encoder_client(enc_client_dims=[[3,8],[8,8]],layer_num=2).to(args.device)\nencoder_client_2 = model_FL.encoder_client(enc_client_dims=[[3,8],[8,8]],layer_num=2).to(args.device)\n\ndecoder_client_0 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,4]],layer_num=2).to(args.device)\ndecoder_client_1 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,3]],layer_num=2).to(args.device)\ndecoder_client_2 = model_FL.encoder_client(enc_client_dims=[[8,8],[8,3]],layer_num=2).to(args.device)\n\nmodel_server_0 = model_FL.model_server(rnn_type = args.model,\n enc_inp_size=feature_dim,\n rnn_inp_size=args.emsize,\n rnn_hid_size=args.nhid,\n dec_out_size=feature_dim,\n nlayers=args.nlayers,\n res_connection=args.res_connection).to(args.device)\n\n\n\nmodel_server_0.load_state_dict(checkpoint['state_dict']['model_server_0']) # 载入数据参数!\n\nencoder_client_0.load_state_dict(checkpoint['state_dict']['encoder_client_0'])\nencoder_client_1.load_state_dict(checkpoint['state_dict']['encoder_client_1'])\nencoder_client_2.load_state_dict(checkpoint['state_dict']['encoder_client_2'])\ndecoder_client_0.load_state_dict(checkpoint['state_dict']['decoder_client_0'])\ndecoder_client_1.load_state_dict(checkpoint['state_dict']['decoder_client_1'])\ndecoder_client_2.load_state_dict(checkpoint['state_dict']['decoder_client_2'])\n\ndimensions_client_0 = [0,1,2,3]\ndimensions_client_1 = [4,5,6]\ndimensions_client_2 = [7,8,9]\n\nrecover_dimensions_client_0 = [0,1,2,3,4,5,6,7]\nrecover_dimensions_client_1 = [8,9,10,11,12,13,14,15]\nrecover_dimensions_client_2 = [16,17,18,19,20,21,22,23]\n\nconfig={}\nconfig['dimensions_client_0'] = dimensions_client_0\nconfig['dimensions_client_1'] = dimensions_client_1\nconfig['dimensions_client_2'] = dimensions_client_2\n\nconfig['recover_dimensions_client_0'] = recover_dimensions_client_0\nconfig['recover_dimensions_client_1'] = recover_dimensions_client_1\nconfig['recover_dimensions_client_2'] = recover_dimensions_client_2\n\n# del checkpoint\n\nscores, predicted_scores, precisions, recalls, f_betas = list(), list(), list(), list(), list()\ntargets, mean_predictions, oneStep_predictions, Nstep_predictions = list(), list(), list(), list()\ntry:\n # For each channel in the dataset\n\n predList = []\n testScoreList = []\n \n for channel_idx in range(feature_data):\n ''' 1. Load mean and covariance if they are pre-calculated, if not calculate them. '''\n # Mean and covariance are calculated on train dataset.\n if 'means' in checkpoint.keys() and 'covs' in checkpoint.keys():\n print('=> loading pre-calculated mean and covariance')\n mean, cov = checkpoint['means'][channel_idx], checkpoint['covs'][channel_idx]\n else:\n print('=> calculating mean and covariance')\n mean, cov = fit_norm_distribution_param(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n train_dataset, channel_idx=0,config=config)\n\n ''' 2. Train anomaly score predictor using support vector regression (SVR). (Optional) '''\n # An anomaly score predictor is trained\n # given hidden layer output and the corresponding anomaly score on train dataset.\n # Predicted anomaly scores on test dataset can be used for the baseline of the adaptive threshold.\n if args.compensate: # 默认False\n # compensate anomaly score using anomaly score esimation\n print('=> training an SVR as anomaly score predictor')\n train_score, _, _, hiddens, _ = anomalyScore(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n train_dataset, mean, cov, channel_idx=0, config=config)\n score_predictor = GridSearchCV(SVR(), cv=5,\n param_grid={\"C\": [1e0, 1e1, 1e2], \"gamma\": np.logspace(-1, 1, 3)})\n score_predictor.fit(torch.cat(hiddens, dim=0).numpy(), train_score.cpu().numpy())\n else:\n score_predictor = None\n\n ''' 3. Calculate anomaly scores'''\n # Anomaly scores are calculated on the test dataset\n # given the mean and the covariance calculated on the train dataset\n print('=> calculating anomaly scores')\n \n #train_score, _, _, hiddens, _ = anomalyScore(args, model_server_0,encoder_client_0,encoder_client_1,encoder_client_2,\n # decoder_client_0,decoder_client_1,decoder_client_2,\n # train_dataset, mean, cov, channel_idx=0, config=config)\n \n score, sorted_prediction, sorted_error, _, predicted_score = anomalyScore(args, model_server_0,\n encoder_client_0,encoder_client_1,encoder_client_2,\n decoder_client_0,decoder_client_1,decoder_client_2,\n test_dataset, mean, cov,\n score_predictor=score_predictor,\n channel_idx=channel_idx,\n config=config)\n # score [length,] 异常分数,越大说明越是异常\n # sorted_prediction [time_length,10] 每个时刻的10个预测值\n # sorted_error [time_length,10] 每个时刻的预测误差\n # prediction_score 默认的话是空数组\n\n ''' 4. Evaluate the result '''\n # The obtained anomaly scores are evaluated by measuring precision, recall, and f_beta scores\n # The precision, recall, f_beta scores are are calculated repeatedly,\n # sampling the threshold from 1 to the maximum anomaly score value, either equidistantly or logarithmically.\n print('=> calculating precision, recall, and f_beta')\n # precision, recall, f_beta = get_precision_recall(args, score, num_samples=1000, beta=args.beta,\n # label=TimeseriesData.testLabel.to(args.device))\n #anomaly_temp = get_precision_recall_zsx_2(args, score, num_samples=1000, beta=args.beta,\n # label=TimeseriesData.testLabel.to(args.device))\n \n score[score<0.0] = 0.0\n\n predict = DistriTailNoise2Th(score.cpu().numpy(),args_.difTh,args_.avgNum,args_.meanMulCoefficient,args_.binNum,args_.followNum)\n predList.append(predict)\n\n testScoreList.append(score.cpu().numpy())\n\n print(\"已完成第\",channel_idx,\"维度的检测\")\n\n\n\n predList = np.array(predList)\n testScoreList = np.array(testScoreList)\n \n predListPath = Path(\"save\", args.data, \"anomalypred\")\n predListPath.mkdir(parents=True, exist_ok=True)\n torch.save(predList, str(predListPath.joinpath(args.filename.split('.')[0]+\"_predList\").with_suffix(\".pth\")))\n \n torch.save(testScoreList, str(predListPath.joinpath(args.filename.split('.')[0]+\"_testScoreList\").with_suffix(\".pth\")))\n\n lastPred = np.sum(predList,axis=0)\n lastPred = lastPred.astype(bool)\n torch.save(lastPred, str(predListPath.joinpath(args.filename.split('.')[0]+\"_lastPred\").with_suffix(\".pth\")))\n\n lastPredAdjust = adjust_predicts_zsx(lastPred,TimeseriesData.testLabel.cpu().numpy())\n torch.save(lastPredAdjust, str(predListPath.joinpath(args.filename.split('.')[0]+\"_lastPredAdjust\").with_suffix(\".pth\")))\n\n f1 = calc_point2point(lastPredAdjust,TimeseriesData.testLabel.cpu().numpy())\n ResultPath = Path(\"save\", args.data, \"Result\")\n ResultPath.mkdir(parents=True, exist_ok=True)\n torch.save(f1, str(ResultPath.joinpath(args.filename.split('.')[0]+\"_Result\").with_suffix(\".pth\")))\n print(\"f1_score=\",f1)\n\n\nexcept KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early')", "sub_path": "Anomaly_detection_VFL/RNN-Time-series-Anomaly-Detection-master_FL-selfMethod-v1.1/.ipynb_checkpoints/2_2_anomaly_detection_FL-checkpoint.py", "file_name": "2_2_anomaly_detection_FL-checkpoint.py", "file_ext": "py", "file_size_in_byte": 12047, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "argparse.ArgumentParser", "line_number": 24, "usage_type": "call"}, {"api_name": "torch.load", "line_number": 49, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 49, "usage_type": "call"}, {"api_name": "torch.manual_seed", "line_number": 58, "usage_type": "call"}, {"api_name": "torch.cuda.manual_seed", "line_number": 59, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 59, "usage_type": "attribute"}, {"api_name": "preprocess_data.PickleDataLoad", "line_number": 64, "usage_type": "call"}, {"api_name": "model.model_FL.encoder_client", "line_number": 81, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 81, "usage_type": "name"}, {"api_name": "model.model_FL.encoder_client", "line_number": 82, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 82, "usage_type": "name"}, {"api_name": "model.model_FL.encoder_client", "line_number": 83, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 83, "usage_type": "name"}, {"api_name": "model.model_FL.encoder_client", "line_number": 85, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 85, "usage_type": "name"}, {"api_name": "model.model_FL.encoder_client", "line_number": 86, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 86, "usage_type": "name"}, {"api_name": "model.model_FL.encoder_client", "line_number": 87, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 87, "usage_type": "name"}, {"api_name": "model.model_FL.model_server", "line_number": 89, "usage_type": "call"}, {"api_name": "model.model_FL", "line_number": 89, "usage_type": "name"}, {"api_name": "anomalyDetector.fit_norm_distribution_param", "line_number": 143, "usage_type": "call"}, {"api_name": "anomalyDetector.anomalyScore", "line_number": 154, "usage_type": "call"}, {"api_name": "sklearn.model_selection.GridSearchCV", "line_number": 157, "usage_type": "call"}, {"api_name": "sklearn.svm.SVR", "line_number": 157, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 158, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 159, "usage_type": "call"}, {"api_name": "anomalyDetector.anomalyScore", "line_number": 172, "usage_type": "call"}, {"api_name": "utils.distri2Th.DistriTailNoise2Th", "line_number": 196, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 205, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 206, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 208, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 210, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 212, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 214, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 216, "usage_type": "call"}, {"api_name": "utils.eval_methods.adjust_predicts_zsx", "line_number": 218, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 219, "usage_type": "call"}, {"api_name": "utils.eval_methods.calc_point2point", "line_number": 221, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 222, "usage_type": "call"}, {"api_name": "torch.save", "line_number": 224, "usage_type": "call"}]}
+{"seq_id": "142532488", "text": "import pytest\nimport pandas as pd\nfrom collections import OrderedDict as odict\n\nfrom kep.csv2df.specification import Definition, Specification\nfrom kep.csv2df.reader import text_to_list\nfrom kep.csv2df.parser import split_to_tables, parse_tables, Table\n\n\nDOC = \"\"\"Объем ВВП, млрд.рублей / Gross domestic product, bln rubles\n1999\t4823\t901\t1102\t1373\t1447\n2000\t7306\t1527\t1697\t2038\t2044\"\"\"\n\n\ndef create_table():\n rows = text_to_list(DOC)\n tables = list(split_to_tables(rows))\n return tables[0]\n\n\ndef test_split_to_tables():\n assert create_table() == \\\n Table(headers=[['Объем ВВП, млрд.рублей / Gross domestic product, bln rubles']],\n datarows=[['1999', '4823', '901', '1102', '1373', '1447'],\n ['2000', '7306', '1527', '1697', '2038', '2044']]\n )\n\n\nclass Test_Table():\n t = create_table()\n\n def test_extract_values_method_on_table_after_parsing_returns_expected_dicts(\n self):\n # prepare\n self.t.set_splitter(None)\n self.t.varname = 'GDP'\n self.t.unit = 'bln_rub'\n # run\n datapoints = list(self.t.extract_values())\n # compare\n assert datapoints[0] == {'freq': 'a',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 4823}\n assert datapoints[1] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-03-31'),\n 'value': 901}\n assert datapoints[2] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-06-30'),\n 'value': 1102}\n assert datapoints[3] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-09-30'),\n 'value': 1373}\n assert datapoints[4] == {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 1447}\n\n\nDOC2 = \"\"\"\tГод Year\tКварталы / Quarters\tЯнв. Jan.\tФев. Feb.\tМарт Mar.\tАпр. Apr.\tМай May\tИюнь June\tИюль July\tАвгуст Aug.\tСент. Sept.\tОкт. Oct.\tНояб. Nov.\tДек. Dec.\n\t\tI\tII\tIII\tIV\n1.7. Инвестиции в основной капитал1), млрд. рублей / Fixed capital investments1), bln rubles\n2015\t14555,9\t1969,7\t3020,8\t3560,2\t6005,2\t516,9\t680,7\t772,1\t812,8\t1004,2\t1203,8\t1078,4\t1209,1\t1272,7\t1703,9\t1592,7\t2708,6\n20162)\t\t2149,4\t3153,3\t3813,4\n\tГод Year\tКварталы / Quarters\tЯнв. Jan.\tФев. Feb.\tМарт Mar.\tАпр. Apr.\tМай May\tИюнь June\tИюль July\tАвгуст Aug.\tСент. Sept.\tОкт. Oct.\tНояб. Nov.\tДек. Dec.\n\t\tI\tII\tIII\tIV\nв % к соответствующему периоду предыдущего года / percent of corresponding period of previous year\n2015\t91,6\t95,2\t91,2\t87,0\t93,6\t95,9\t94,4\t95,4\t93,8\t90,1\t90,4\t88,3\t86,6\t86,3\t96,3\t93,5\t91,9\n2016\t\t95,2\t96,1\t100,3\nв % к предыдущему периоду / percent of previous period\n2015\t\t35,2\t152,1\t108,9\t160,4\t20,7\t129,1\t116,4\t104,2\t123,0\t118,2\t87,8\t105,3\t103,6\t134,3\t92,9\t163,0\n2016\t\t36,9\t147,1\t119,2\n1.7.1. Инвестиции в основной капитал организаций\"\"\"\n\n\nUNITS = odict([ # 1. MONEY\n ('млрд.рублей', 'bln_rub'),\n ('млрд. рублей', 'bln_rub'),\n # 2. RATES OF CHANGE\n ('в % к прошлому периоду', 'rog'),\n ('в % к предыдущему месяцу', 'rog'),\n ('в % к предыдущему периоду', 'rog'),\n ('в % к соответствующему периоду предыдущего года', 'yoy'),\n ('в % к соответствующему месяцу предыдущего года', 'yoy')\n])\n\n\ndef make_definition():\n boundaries = [\n dict(start='1.6. Инвестиции в основной капитал',\n end='1.6.1. Инвестиции в основной капитал организаций'),\n dict(start='1.7. Инвестиции в основной капитал',\n end='1.7.1. Инвестиции в основной капитал организаций')]\n commands = [\n dict(\n var='INVESTMENT',\n header=['Инвестиции в основной капитал'],\n unit=['bln_rub', 'yoy', 'rog'])]\n # mapper dictionary to convert text in table headers to units of\n # measurement\n units = UNITS\n return Definition(commands, units, boundaries)\n\n\ndef create_tables():\n csv_segment = text_to_list(DOC2)\n return split_to_tables(csv_segment)\n\n\nclass Test_parse_tables:\n pdef = make_definition()\n tables = create_tables()\n\n def test_parse_tables(self):\n tables = parse_tables(self.tables, self.pdef)\n # checks\n assert len(tables) == 3\n assert all([t.has_unknown_lines() for t in tables]) is False\n for t in tables:\n assert t.varname == 'INVESTMENT'\n assert [t.unit for t in tables] == ['bln_rub', 'yoy', 'rog']\n\n\nDOC3 = '\\n'.join([DOC, DOC2])\n\n\ndef make_specification():\n commands = [\n dict(\n var='GDP',\n header='Объем ВВП',\n unit='bln_rub')]\n specification = Specification(commands=commands, units=UNITS)\n boundaries1 = [\n dict(start='1.6. Инвестиции в основной капитал',\n end='1.6.1. Инвестиции в основной капитал организаций'),\n dict(start='1.7. Инвестиции в основной капитал',\n end='1.7.1. Инвестиции в основной капитал организаций')]\n commands1 = [\n dict(\n var='INVESTMENT',\n header=['Инвестиции в основной капитал'],\n unit=['bln_rub', 'yoy', 'rog'])]\n specification.append(commands1, boundaries1)\n return specification\n\n\ncontrol_values = [\n {'freq': 'a', 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('1999-12-31'),\n 'value': 4823.0},\n {'freq': 'q',\n 'label': 'GDP_bln_rub',\n 'time_index': pd.Timestamp('2000-12-31'),\n 'value': 2044.0},\n {'freq': 'a',\n 'label': 'INVESTMENT_bln_rub',\n 'time_index': pd.Timestamp('2015-12-31'),\n 'value': 14555.9},\n {'freq': 'q',\n 'label': 'INVESTMENT_rog',\n 'time_index': pd.Timestamp('2016-09-30'),\n 'value': 119.2}\n]\n\n\ndef test_specification_with_2_segments_on_valid_csv_data():\n # setting\n spec = make_specification()\n spec.attach_data(DOC3)\n # call\n values = spec.values\n # check\n for d in control_values:\n assert d in values\n\n\nif __name__ == \"__main__\":\n pytest.main([__file__])\n", "sub_path": "src/kep/csv2df/tests/test_parser_and_integration.py", "file_name": "test_parser_and_integration.py", "file_ext": "py", "file_size_in_byte": 7116, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "kep.csv2df.reader.text_to_list", "line_number": 16, "usage_type": "call"}, {"api_name": "kep.csv2df.parser.split_to_tables", "line_number": 17, "usage_type": "call"}, {"api_name": "kep.csv2df.parser.Table", "line_number": 23, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 43, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 47, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 51, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 55, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 59, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 79, "usage_type": "call"}, {"api_name": "kep.csv2df.specification.Definition", "line_number": 105, "usage_type": "call"}, {"api_name": "kep.csv2df.reader.text_to_list", "line_number": 109, "usage_type": "call"}, {"api_name": "kep.csv2df.parser.split_to_tables", "line_number": 110, "usage_type": "call"}, {"api_name": "kep.csv2df.parser.parse_tables", "line_number": 118, "usage_type": "call"}, {"api_name": "kep.csv2df.specification.Specification", "line_number": 136, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 153, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 157, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 161, "usage_type": "call"}, {"api_name": "pandas.Timestamp", "line_number": 165, "usage_type": "call"}, {"api_name": "pytest.main", "line_number": 182, "usage_type": "call"}]}
+{"seq_id": "609385824", "text": "import os\nfrom re import M\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nfrom sklearn.preprocessing import LabelEncoder\nfrom matplotlib import gridspec\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.models import Sequential, Model\nimport numpy as np\nfrom keras.layers import Input, Conv2D, MaxPooling2D, Dense, Dropout, Flatten\nfrom keras.metrics import Precision, Recall\nfrom keras.callbacks import TensorBoard, Callback\n\n\nclass KernelsCallback(Callback):\n def __init__(self, eps):\n self.eps = eps\n self.lays = [] \n \n def set_model(self, model): \n self.model = model \n for i in range(len(model.layers)):\n if 'conv' in model.layers[i].name:\n self.lays.append(i)\n \n def on_epoch_end(self, epoch, logs=None):\n for layer in self.lays: \n if epoch in self.eps:\n filters, biases = model.layers[layer].get_weights()\n \n f_min, f_max = filters.min(), filters.max()\n filters = (filters - f_min) / (f_max - f_min)\n \n out_channels = filters.shape[3]\n in_channels = filters.shape[2]\n \n for i in range(out_channels):\n f = filters[:,:,:,i] \n ind = 1\n for j in range(in_channels):\n flt = plt.subplot(1, in_channels, ind)\n flt.set_xticks([])\n flt.set_yticks([])\n plt.imshow(f[:,:,j], cmap='gray')\n plt.savefig(f'imgs/{layer+1}_{i+1}_{epoch+1}.png') \n ind += 1 \n plt.clf() \n # <слой>_<фильтр>_<эпоха>\n\n\ndef gen_rect(SIZE=50):\n img = np.zeros([SIZE, SIZE])\n x = np.random.randint(0, SIZE)\n y = np.random.randint(0, SIZE)\n w = np.random.randint(SIZE // 10, SIZE // 2)\n h = np.random.randint(SIZE // 10, SIZE // 2)\n img[x:x + w, y:y + h] = 1\n return img\n\n\ndef gen_circle(SIZE=50):\n img = np.zeros([SIZE, SIZE])\n x = np.random.randint(0, SIZE)\n y = np.random.randint(0, SIZE)\n r = np.random.randint(SIZE // 10, SIZE // 3)\n for i in range(0, SIZE):\n for j in range(0, SIZE):\n if (i-x)**2 + (j-y)**2 <= r**2:\n img[i, j] = 1\n return img\n\n\ndef gen_data(SIZE=500, IMG_SIZE=50):\n c1 = SIZE // 2\n c2 = SIZE - c1\n label_c1 = np.full([c1, 1], 'Square')\n data_c1 = np.array([gen_rect(IMG_SIZE) for i in range(c1)])\n label_c2 = np.full([c2, 1], 'Circle')\n data_c2 = np.array([gen_circle(IMG_SIZE) for i in range(c2)])\n data = np.vstack((data_c1, data_c2))\n label = np.vstack((label_c1, label_c2))\n return data, label\n\n\ndef data_preprocessing(X, Y):\n encoder = LabelEncoder()\n y = encoder.fit_transform(Y.ravel())\n\n idx = np.random.permutation(len(X))\n X, y = X[idx], y[idx]\n\n val_split = 0.1\n test_num = round((1-val_split)*len(X))\n val_num = round(test_num*(1-val_split))\n train_data, train_labels = X[:val_num], y[:val_num]\n val_data, val_labels = X[val_num:test_num], y[val_num:test_num]\n test_data, test_labels = X[test_num:], y[test_num:]\n train_data = np.expand_dims(train_data, axis=3)\n val_data = np.expand_dims(val_data, axis=3)\n test_data = np.expand_dims(test_data, axis=3)\n return (train_data, val_data, test_data), (train_labels, val_labels, test_labels)\n\n\ndef draw_results(H):\n loss = H.history['loss']\n val_loss = H.history['val_loss']\n acc = H.history['accuracy']\n val_acc = H.history['val_accuracy']\n epochs = range(1, len(loss) + 1)\n\n fig = plt.figure(figsize=(12, 6))\n gs = gridspec.GridSpec(1, 2, width_ratios=[3, 3])\n plt.subplot(gs[0])\n plt.plot(epochs, loss, 'r--', label='Training loss')\n plt.plot(epochs, val_loss, 'g--', label='Validation loss')\n plt.title('Training and validation loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n\n plt.subplot(gs[1])\n plt.plot(epochs, acc, 'r--', label='Training acc')\n plt.plot(epochs, val_acc, 'g--', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n\n plt.tight_layout()\n plt.show()\n\n\nIMG_SIZE = 50\nSIZE = 1000\nBATCH_SIZE = 15\nNUM_EPOCHS = 10\n\nFILTERS_EPOCHS = [0,5,9]\n\ndata, labels = gen_data(SIZE, IMG_SIZE)\n(train_data, val_data, test_data), (train_labels,\n val_labels, test_labels) = data_preprocessing(data, labels)\n\nmodel = Sequential([\n Input(shape=(IMG_SIZE, IMG_SIZE, 1)),\n Conv2D(8, (3, 3), padding='same', activation='relu'),\n MaxPooling2D((2, 2)),\n Conv2D(16, (3, 3), padding='same', activation='relu'),\n MaxPooling2D((2, 2)),\n Flatten(),\n Dense(128, activation='relu'),\n Dropout(0.5),\n Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\nH = model.fit(train_data, train_labels,\n batch_size=BATCH_SIZE, epochs=NUM_EPOCHS,\n verbose=2, validation_data=(val_data, val_labels), callbacks=[KernelsCallback(FILTERS_EPOCHS)])\nmodel.evaluate(test_data, test_labels, verbose=1)\n# draw_results(H)\n", "sub_path": "8383/Kireev/pr/8/task.py", "file_name": "task.py", "file_ext": "py", "file_size_in_byte": 5431, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.environ", "line_number": 3, "usage_type": "attribute"}, {"api_name": "os.environ", "line_number": 4, "usage_type": "attribute"}, {"api_name": "keras.callbacks.Callback", "line_number": 16, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 42, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 42, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.imshow", "line_number": 45, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 45, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 46, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 46, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.clf", "line_number": 48, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 48, "usage_type": "name"}, {"api_name": "numpy.zeros", "line_number": 53, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 54, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 55, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 55, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 56, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 56, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 57, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 57, "usage_type": "attribute"}, {"api_name": "numpy.zeros", "line_number": 63, "usage_type": "call"}, {"api_name": "numpy.random.randint", "line_number": 64, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 64, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 65, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 65, "usage_type": "attribute"}, {"api_name": "numpy.random.randint", "line_number": 66, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 66, "usage_type": "attribute"}, {"api_name": "numpy.full", "line_number": 77, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 78, "usage_type": "call"}, {"api_name": "numpy.full", "line_number": 79, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 80, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 81, "usage_type": "call"}, {"api_name": "numpy.vstack", "line_number": 82, "usage_type": "call"}, {"api_name": "sklearn.preprocessing.LabelEncoder", "line_number": 87, "usage_type": "call"}, {"api_name": "numpy.random.permutation", "line_number": 90, "usage_type": "call"}, {"api_name": "numpy.random", "line_number": 90, "usage_type": "attribute"}, {"api_name": "numpy.expand_dims", "line_number": 99, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 100, "usage_type": "call"}, {"api_name": "numpy.expand_dims", "line_number": 101, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 112, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 112, "usage_type": "name"}, {"api_name": "matplotlib.gridspec.GridSpec", "line_number": 113, "usage_type": "call"}, {"api_name": "matplotlib.gridspec", "line_number": 113, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 114, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 114, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 115, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 115, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 116, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 116, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 117, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 117, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 118, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 118, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 119, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 119, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 120, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 120, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplot", "line_number": 122, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 122, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 123, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 123, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 124, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 124, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.title", "line_number": 125, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 125, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xlabel", "line_number": 126, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 126, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.ylabel", "line_number": 127, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 127, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.legend", "line_number": 128, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 128, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.tight_layout", "line_number": 130, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 130, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 131, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 131, "usage_type": "name"}, {"api_name": "tensorflow.keras.models.Sequential", "line_number": 145, "usage_type": "call"}, {"api_name": "keras.layers.Input", "line_number": 146, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 147, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 148, "usage_type": "call"}, {"api_name": "keras.layers.Conv2D", "line_number": 149, "usage_type": "call"}, {"api_name": "keras.layers.MaxPooling2D", "line_number": 150, "usage_type": "call"}, {"api_name": "keras.layers.Flatten", "line_number": 151, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 152, "usage_type": "call"}, {"api_name": "keras.layers.Dropout", "line_number": 153, "usage_type": "call"}, {"api_name": "keras.layers.Dense", "line_number": 154, "usage_type": "call"}]}
+{"seq_id": "557245079", "text": "from django.http import HttpResponse\nimport cv2 \nimport numpy as np \nimport face_recognition\nimport datetime\nimport time\nfrom django.shortcuts import render\nfrom .forms import *\nfrom .models import Student,AttendanceTable\nimport os\n\ndef index(request):\n\tpath=\"attendance/images\"+\"college_pic.jpg\"\n\tprint(path)\n\treturn render(request,\"attendance/index.html\",{'path':path})\n\ndef registerStudent(request):\n\tif request.method == 'POST':\n\t\tform = RegistrationForm(request.POST, request.FILES)\n\t\tif form.is_valid():\n\t\t\tname = form.cleaned_data['name']\n\t\t\tdob = form.cleaned_data['dob']\n\t\t\tdepartment = form.cleaned_data['department']\n\t\t\tsemester = form.cleaned_data['semester']\n\t\t\troll_no = form.cleaned_data['roll_no']\n\t\t\temail = form.cleaned_data['email']\n\t\t\tphoto = form.cleaned_data['photo']\n\t\t\tform.save()\t\n\t\t\tstudents = Student.objects.all()\n\t\t\trecords = {}\n\t\t\tfor i in range(len(students)):\n\t\t\t\tt = students[i]\n\t\t\t\trecords[i+1]={'roll':t.roll_no,'name':t.name,'department':t.department,'semester':t.semester}\n\t\t\treturn render(request,\"attendance/show_student.html\",{'context':records})\n\telse:\n\t\tform = RegistrationForm()\n\treturn render(request, 'attendance/registration.html', {'form' : form})\n\n\ndef markAttendance(request):\n\tstudents = Student.objects.all()\n\timages = []\n\timagesNames = []\n\timagesRoll = []\n\twindow_width = 450\n\twindow_height = 450\n\tpath = os.getcwd()\n\tfor s in students:\n\t\tsurl = s.photo.url\n\t\tname = s.name\n\t\troll = s.roll_no\n\t\timg = cv2.imread(path+\"/\"+surl)\n\t\timages.append(img)\n\t\timagesNames.append(name)\n\t\timagesRoll.append(roll)\n\n\t\n\tdef findEncodings(imagesList):\n\t\tencodedList = []\n\t\tfor img in imagesList:\n\t\t\timg = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n\t\t\tenc = face_recognition.face_encodings(img)[0]\n\t\t\tencodedList.append(enc)\n\t\t\tprint(\"Encoding in progress\")\n\t\treturn encodedList\n\tencodeListKnown = findEncodings(images)\n\tcap = cv2.VideoCapture(0)\n\tFlag = True\n\tmarkedFlag = False\n\tname = None\n\twhile Flag:\n\t\tsuccess, img = cap.read()\n\t\t#reduce size of image - scale .25,0.25, 1/4th of image\n\t\timgS = cv2.resize(img,(0,0),None,0.25,0.25)\n\t\timgS = cv2.cvtColor(imgS,cv2.COLOR_BGR2RGB)\n\t\tcv2.putText(img,\"Press ESC to Close\",(100,100),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t#in web cam we can see many faces so find the loc of faces\n\t\tfacesCurFrame = face_recognition.face_locations(imgS)\n\t\tencodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)\n\n\n\t\tfor encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):\n\t\t\tmatches = face_recognition.compare_faces(encodeListKnown,encodeFace)\n\t\t\t#faceDis give distance of all the known face from web face\n\t\t\tfaceDis = face_recognition.face_distance(encodeListKnown,encodeFace)\n\t\t\tprint(faceDis)\n\t\t\t#index of min face\n\t\t\tmatchIndex = np.argmin(faceDis)\n\t\t\tif matches[matchIndex]:\n\t\t\t\tname = imagesNames[matchIndex].upper()\n\t\t\t\troll= imagesRoll[matchIndex]\n\t\t\t\ty1,x2,y2,x1 = faceLoc\n\t\t\t\ty1 *=4\n\t\t\t\tx1 *=4\n\t\t\t\ty2 *=4\n\t\t\t\tx2 *=4\n\t\t\t\t#scale up face loc\n\t\t\t\tcv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)\n\t\t\t\tcv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\n\t\t\t\tcv2.putText(img,\"Mr \"+name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t\t\t\n\t\t\t\tcurStudent = Student.objects.get(pk=roll)\n\t\t\t\tif not AttendanceTable.objects.filter(student__roll_no = roll,date__day=datetime.date.today().day):\n\t\t\t\t\tb = AttendanceTable(date =datetime.date.today() ,time=datetime.datetime.now().time(),student=curStudent)\n\t\t\t\t\tb.save()\n\t\t\t\t\tmarkedFlag = 1\n\t\t\t\tif markedFlag:\n\t\t\t\t\tcv2.rectangle(img,(x1,y1),(x2,y2),(0,255,0),2)\n\t\t\t\t\tcv2.rectangle(img,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)\n\t\t\t\t\tcv2.putText(img,\"Mr \"+name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,0),2)\n\t\t\t\t\tcv2.putText(img,\"Attendance Marked for Mr \"+name,(x1+6,y2-56),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)\n\t\t\t\t\tFlag = 0\n\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\tcap.release()\n\t\t\t\t\tcv2.destroyAllWindows()\n\t\t\t\t\treturn render(request,\"attendance/index.html\",{'name':name})\n\t\t\t\t# cv2.resizeWindow('Resized Window', window_width, window_height)\n\t\tcv2.imshow('Webcam',img)\n\t\tk = cv2.waitKey(1)\n\t\tif k%256 == 27:\n\t\t\tFlag = 0\n\t\t\tcap.release()\n\t\t\tcv2.destroyAllWindows()\n\t\t\treturn render(request,\"attendance/index.html\",{'name':name})\n\n\ndef showStudentList(request):\n\tstudents = Student.objects.all()\n\trecords = {}\n\tfor i in range(len(students)):\n\t\tt = students[i]\n\t\trecords[i+1]={'roll':t.roll_no,'name':t.name,'department':t.department,'semester':t.semester}\n\treturn render(request,\"attendance/show_student.html\",{'context':records})\n\ndef getStudentByID(request,id):\n\tdaysAttended = AttendanceTable.objects.filter(student__roll_no = id)\n\t\n\tctx = {\n\t\t\t\t\n\t\t\t'student': Student.objects.get(pk=id),\n\t\t}\n\tif daysAttended:\n\t\tctx['daysattended'] = len(daysAttended)\n\treturn render(request,\"attendance/display_student.html\",ctx)\n\ndef showAttendanceRecord(request):\n\tattendance = AttendanceTable.objects.all()\n\trecords = {}\n\tfor rec in range(len(attendance)):\n\t\tt = attendance[rec]\n\t\trecords[rec+1]={'date':t.date,'time':t.time,'roll':t.student.roll_no,'name':t.student.name,'department':t.student.department}\n\tprint(records)\n\treturn render(request,\"attendance/attendance_record.html\",{\"context\":records})", "sub_path": "attendance/views.py", "file_name": "views.py", "file_ext": "py", "file_size_in_byte": 5124, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "django.shortcuts.render", "line_number": 15, "usage_type": "call"}, {"api_name": "models.Student.objects.all", "line_number": 29, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 29, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 29, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 34, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 37, "usage_type": "call"}, {"api_name": "models.Student.objects.all", "line_number": 41, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 41, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 41, "usage_type": "name"}, {"api_name": "os.getcwd", "line_number": 47, "usage_type": "call"}, {"api_name": "cv2.imread", "line_number": 52, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 61, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 61, "usage_type": "attribute"}, {"api_name": "face_recognition.face_encodings", "line_number": 62, "usage_type": "call"}, {"api_name": "cv2.VideoCapture", "line_number": 67, "usage_type": "call"}, {"api_name": "cv2.resize", "line_number": 74, "usage_type": "call"}, {"api_name": "cv2.cvtColor", "line_number": 75, "usage_type": "call"}, {"api_name": "cv2.COLOR_BGR2RGB", "line_number": 75, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 76, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 76, "usage_type": "attribute"}, {"api_name": "face_recognition.face_locations", "line_number": 78, "usage_type": "call"}, {"api_name": "face_recognition.face_encodings", "line_number": 79, "usage_type": "call"}, {"api_name": "face_recognition.compare_faces", "line_number": 83, "usage_type": "call"}, {"api_name": "face_recognition.face_distance", "line_number": 85, "usage_type": "call"}, {"api_name": "numpy.argmin", "line_number": 88, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 98, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 99, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 99, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 100, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 100, "usage_type": "attribute"}, {"api_name": "models.Student.objects.get", "line_number": 102, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 102, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 102, "usage_type": "name"}, {"api_name": "models.AttendanceTable.objects.filter", "line_number": 103, "usage_type": "call"}, {"api_name": "models.AttendanceTable.objects", "line_number": 103, "usage_type": "attribute"}, {"api_name": "models.AttendanceTable", "line_number": 103, "usage_type": "name"}, {"api_name": "datetime.date.today", "line_number": 103, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 103, "usage_type": "attribute"}, {"api_name": "models.AttendanceTable", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.date.today", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.date", "line_number": 104, "usage_type": "attribute"}, {"api_name": "datetime.datetime.now", "line_number": 104, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 104, "usage_type": "attribute"}, {"api_name": "cv2.rectangle", "line_number": 108, "usage_type": "call"}, {"api_name": "cv2.rectangle", "line_number": 109, "usage_type": "call"}, {"api_name": "cv2.FILLED", "line_number": 109, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 110, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 110, "usage_type": "attribute"}, {"api_name": "cv2.putText", "line_number": 111, "usage_type": "call"}, {"api_name": "cv2.FONT_HERSHEY_COMPLEX", "line_number": 111, "usage_type": "attribute"}, {"api_name": "time.sleep", "line_number": 113, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 115, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 116, "usage_type": "call"}, {"api_name": "cv2.imshow", "line_number": 118, "usage_type": "call"}, {"api_name": "cv2.waitKey", "line_number": 119, "usage_type": "call"}, {"api_name": "cv2.destroyAllWindows", "line_number": 123, "usage_type": "call"}, {"api_name": "django.shortcuts.render", "line_number": 124, "usage_type": "call"}, {"api_name": "models.Student.objects.all", "line_number": 128, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 128, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 128, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 133, "usage_type": "call"}, {"api_name": "models.AttendanceTable.objects.filter", "line_number": 136, "usage_type": "call"}, {"api_name": "models.AttendanceTable.objects", "line_number": 136, "usage_type": "attribute"}, {"api_name": "models.AttendanceTable", "line_number": 136, "usage_type": "name"}, {"api_name": "models.Student.objects.get", "line_number": 140, "usage_type": "call"}, {"api_name": "models.Student.objects", "line_number": 140, "usage_type": "attribute"}, {"api_name": "models.Student", "line_number": 140, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 144, "usage_type": "call"}, {"api_name": "models.AttendanceTable.objects.all", "line_number": 147, "usage_type": "call"}, {"api_name": "models.AttendanceTable.objects", "line_number": 147, "usage_type": "attribute"}, {"api_name": "models.AttendanceTable", "line_number": 147, "usage_type": "name"}, {"api_name": "django.shortcuts.render", "line_number": 153, "usage_type": "call"}]}
+{"seq_id": "553786772", "text": "#!/usr/bin/env python3\n\n# from datetime import datetime\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\n# from typing import Dict\nfrom typing import Optional\nfrom typing import List\nfrom typing import Sequence\nfrom typing import TextIO\nfrom typing import Any\nfrom typing import Union\nfrom typing import cast\nfrom dataclasses import dataclass, field\n\n_header = \"\"\"\n -`\n ... .o+`\n .+++s+ .h`. `ooo/\n`+++%++ .h+++ `+oooo:\n+++o+++ .hhs++. `+oooooo:\n+s%%so%.hohhoo' 'oooooo+:\n`+ooohs+h+sh++`/: ++oooo+:\n hh+o+hoso+h+`/++++.+++++++:\n `+h+++h.+ `/++++++++++++++:\n `/+++ooooooooooooo/`\n ./ooosssso++osssssso+`\n .oossssso-````/osssss::`\n -osssssso. :ssss``to.\n :osssssss/ Mike osssl +\n /ossssssss/ 8a +sssslb\n `/ossssso+/:- -:/+ossss'.-\n `+sso+:-` `.-/+oso:\n `++:. `-/+/\n .` `/\n\"\"\"\n\n_VERSION = \"0.1.0\"\n_AUTHOR = \"Mike\"\n\n_log: logging.Logger\n# _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\n_SCRIPTNAME = os.path.basename(__file__)\n_log_file: Optional[str] = os.path.splitext(_SCRIPTNAME)[0] + \".log\"\n\n_verbose = False\n# _is_windows = os.name == 'nt'\n# _home = os.environ['USERPROFILE' if _is_windows else 'HOME']\n\n\n@dataclass\nclass Job(object):\n \"\"\"docstring for Job\"\"\"\n\n cmd: Sequence[str]\n stdout: List[str] = field(init=False, repr=False)\n stderr: List[str] = field(init=False, repr=False)\n pid: int = field(init=False)\n rc: int = field(init=False)\n\n # # NOTE: Needed it with python < 3.7\n # def __init__(self, cmd: Sequence[str]):\n # \"\"\"Create a shell command wrapper\n #\n # Args:\n # cmd (Sequence[str]): command with its arguments, first element must\n # be and executable or a path to the executable\n # \"\"\"\n # self.cmd = cmd\n\n def head(self, size: int = 10) -> List[str]:\n \"\"\"Emulate head shell util\n\n Args:\n size (int): first N elements of the stdout\n\n Returns:\n List of string with the first N elements\n \"\"\"\n if size <= 0:\n raise Exception(\"Size cannot be less than 0\")\n return self.stdout[0:size]\n\n def tail(self, size: int = 10) -> List[str]:\n \"\"\"Emulate tail shell util\n\n Args:\n size (int): last N elements of the stdout\n\n Returns:\n List of string with the last N elements\n \"\"\"\n if size <= 0:\n raise Exception(\"Size cannot be less than 0\")\n return self.stdout[::-1][0:size]\n\n def execute(self, background: bool = True, cwd: Optional[str] = None) -> int:\n \"\"\"Execute the cmd\n\n Args:\n background (bool): execute as async process\n cwd (Optional[str]): path where the cmd is execute, default to CWD\n\n Returns:\n Return-code integer of the cmd\n \"\"\"\n # Verbose always overrides background output\n background = background if not _verbose else False\n cwd = \".\" if cwd is None else cwd\n\n _log.debug(f\"Executing cmd: {self.cmd}\")\n _log.debug(\"Sending job to background\" if background else \"Running in foreground\")\n process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=cwd)\n self.pid = process.pid\n\n self.stdout = []\n self.stderr = []\n\n while True:\n stdout = cast(TextIO, process.stdout).readline()\n stderr = cast(TextIO, process.stderr).readline()\n if (stdout == \"\" and stderr == \"\") and process.poll() is not None:\n break\n elif stdout:\n stdout = stdout.strip().replace(\"\\n\", \"\")\n self.stdout.append(stdout)\n if background:\n _log.debug(stdout)\n else:\n _log.info(stdout)\n elif stderr:\n stderr = stderr.strip().replace(\"\\n\", \"\")\n self.stderr.append(stderr)\n _log.error(stderr)\n\n # self.rc = process.poll()\n self.rc = process.returncode\n\n if self.rc != 0:\n _log.error(f\"Command exited with {self.rc}\")\n\n if self.stdout is not None and len(self.stdout) > 0:\n _log.debug(f\"stdout: {self.stdout}\")\n\n if self.stderr is not None and len(self.stderr) > 0:\n _log.error(f\"stderr: {self.stderr}\")\n\n return self.rc\n\n\ndef createLogger(\n stdout_level: int = logging.INFO,\n file_level: int = logging.DEBUG,\n color: bool = True,\n filename: Optional[str] = \"dummy.log\",\n name: str = \"MainLogger\",\n):\n \"\"\"Creaters logging obj\n\n Args:\n stdout_level: logging level displayed into the terminal\n file_level: logging level saved into the logging file\n color: Enable/Disable color console output\n\n Returns:\n Logger with file and tty handlers\n\n \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(logging.DEBUG)\n\n ColorFormatter: Any = None\n Formatter: Any = None\n try:\n from colorlog import ColoredFormatter\n\n Formatter = ColoredFormatter\n ColorFormatter = ColoredFormatter\n except ImportError:\n\n class PrimitiveFormatter(logging.Formatter):\n \"\"\"Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629\"\"\"\n\n def __init__(self, fmt, log_colors=None):\n super().__init__()\n self.fmt = fmt\n\n colors = {\n \"grey\": \"\\x1b[38;21m\",\n \"green\": \"\\x1b[32m\",\n \"magenta\": \"\\x1b[35m\",\n \"purple\": \"\\x1b[35m\",\n \"blue\": \"\\x1b[38;5;39m\",\n \"yellow\": \"\\x1b[38;5;226m\",\n \"red\": \"\\x1b[38;5;196m\",\n \"bold_red\": \"\\x1b[31;1m\",\n \"reset\": \"\\x1b[0m\",\n }\n\n if log_colors is None:\n log_colors = {}\n\n log_colors[\"DEBUG\"] = log_colors[\"DEBUG\"] if \"DEBUG\" in log_colors else \"magenta\"\n log_colors[\"INFO\"] = log_colors[\"INFO\"] if \"INFO\" in log_colors else \"green\"\n log_colors[\"WARNING\"] = log_colors[\"WARNING\"] if \"WARNING\" in log_colors else \"yellow\"\n log_colors[\"ERROR\"] = log_colors[\"ERROR\"] if \"ERROR\" in log_colors else \"red\"\n log_colors[\"CRITICAL\"] = log_colors[\"CRITICAL\"] if \"CRITICAL\" in log_colors else \"bold_red\"\n\n self.FORMATS = {\n logging.DEBUG: colors[log_colors[\"DEBUG\"]] + self.fmt + colors[\"reset\"],\n logging.INFO: colors[log_colors[\"INFO\"]] + self.fmt + colors[\"reset\"],\n logging.WARNING: colors[log_colors[\"WARNING\"]] + self.fmt + colors[\"reset\"],\n logging.ERROR: colors[log_colors[\"ERROR\"]] + self.fmt + colors[\"reset\"],\n logging.CRITICAL: colors[log_colors[\"CRITICAL\"]] + self.fmt + colors[\"reset\"],\n }\n\n def format(self, record):\n log_fmt = self.FORMATS.get(record.levelno)\n formatter = logging.Formatter(log_fmt)\n return formatter.format(record)\n\n Formatter = PrimitiveFormatter\n\n # This means both 0 and 100 silence all output\n stdout_level = 100 if stdout_level == 0 else stdout_level\n\n has_color = ColorFormatter is not None and color\n\n stdout_handler = logging.StreamHandler(sys.stdout)\n stdout_handler.setLevel(stdout_level)\n logformat = \"{color}%(levelname)-8s | %(message)s\"\n logformat = logformat.format(\n color=\"%(log_color)s\" if has_color else \"\",\n # reset='%(reset)s' if has_color else '',\n )\n stdout_format = Formatter(\n logformat,\n log_colors={\n \"DEBUG\": \"purple\",\n \"INFO\": \"green\",\n \"WARNING\": \"yellow\",\n \"ERROR\": \"red\",\n \"CRITICAL\": \"red\",\n },\n )\n stdout_handler.setFormatter(stdout_format)\n\n logger.addHandler(stdout_handler)\n\n if file_level > 0 and file_level < 100 and filename is not None:\n\n with open(filename, \"a\") as log:\n log.write(_header)\n # log.write(f'\\nDate: {datetime.datetime.date()}')\n log.write(f\"\\nAuthor: {_AUTHOR}\\nVersion: {_VERSION}\\n\\n\")\n\n file_handler = logging.FileHandler(filename=filename)\n file_handler.setLevel(file_level)\n file_format = logging.Formatter(\"%(levelname)-8s | %(filename)s: [%(funcName)s] - %(message)s\")\n file_handler.setFormatter(file_format)\n\n logger.addHandler(file_handler)\n\n return logger\n\n\ndef _str_to_logging(level: Union[int, str]) -> int:\n \"\"\"Convert logging level string to a logging number\n\n Args:\n level: integer representation or a valid logging string\n - debug/verbose\n - info\n - warn/warning\n - error\n - critical\n All non valid integer or logging strings defaults to 0 logging\n\n Returns:\n logging level of the given string\n \"\"\"\n\n if isinstance(level, int):\n level = abs(level - 100)\n elif isinstance(level, str):\n try:\n level = abs(int(level) - 100)\n except Exception:\n level = cast(str, level).lower()\n if level == \"debug\" or level == \"verbose\":\n level = logging.DEBUG\n elif level == \"info\":\n level = logging.INFO\n elif level == \"warn\" or level == \"warning\":\n level = logging.WARN\n elif level == \"error\":\n level = logging.ERROR\n elif level == \"critical\":\n level = logging.CRITICAL\n else:\n level = 100\n\n return level\n\n\ndef _parseArgs():\n \"\"\"Parse CLI arguments\n\n Returns\n argparse.ArgumentParser class instance\n\n \"\"\"\n\n class NegateAction(argparse.Action):\n def __call__(self, parser, ns, values, option):\n global _protocol\n if len(option) == 2:\n setattr(ns, self.dest, True)\n else:\n setattr(ns, self.dest, option[2:4] != \"no\")\n\n class ChangeLogFile(argparse.Action):\n def __call__(self, parser, ns, values, option):\n if option[2:4] == \"no\":\n setattr(ns, self.dest, None)\n else:\n pass\n setattr(ns, self.dest, values)\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n \"--color\",\n \"--nocolor\",\n \"--no-color\",\n dest=\"color\",\n action=NegateAction,\n default=True,\n nargs=0,\n help=\"Disable colored output\",\n )\n\n parser.add_argument(\n \"--log\",\n \"--nolog\",\n \"--no-log\",\n dest=\"logfile\",\n action=ChangeLogFile,\n default=_log_file,\n nargs=\"?\",\n type=str,\n help=\"Log filename or disable log file\",\n )\n\n parser.add_argument(\n \"--version\",\n dest=\"show_version\",\n action=\"store_true\",\n help=\"Print script version and exit\",\n )\n\n parser.add_argument(\n \"--verbose\",\n dest=\"verbose\",\n action=\"store_true\",\n default=False,\n help=\"Turn on console debug messages\",\n )\n\n parser.add_argument(\n \"--quiet\",\n dest=\"quiet\",\n action=\"store_true\",\n default=False,\n help=\"Turn off all console messages\",\n )\n\n parser.add_argument(\n \"-l\",\n \"--logging\",\n dest=\"stdout_logging\",\n default=\"info\",\n type=str,\n help=\"Console logger verbosity\",\n )\n\n parser.add_argument(\n \"-f\",\n \"--file-logging\",\n dest=\"file_logging\",\n default=\"debug\",\n type=str,\n help=\"File logger verbosity\",\n )\n\n return parser.parse_args()\n\n\ndef main():\n \"\"\"Main function\n\n Returns\n exit code, 0 in success any other integer in failure\n\n \"\"\"\n global _log\n\n args = _parseArgs()\n\n if args.show_version:\n print(f\"{_header}\\nAuthor: {_AUTHOR}\\nVersion: {_VERSION}\")\n return 0\n\n stdout_level = args.stdout_logging if not args.verbose else \"debug\"\n file_level = args.file_logging if not args.verbose else \"debug\"\n\n stdout_level = stdout_level if not args.quiet else 0\n file_level = file_level if not args.quiet else 0\n\n _log = createLogger(\n stdout_level=_str_to_logging(stdout_level),\n file_level=_str_to_logging(file_level),\n color=args.color,\n filename=args.logfile,\n )\n\n # _log.debug('This is a DEBUG message')\n # _log.info('This is a INFO message')\n # _log.warning('This is a WARNing message')\n # _log.error('This is a ERROR message')\n\n errors = 0\n try:\n pass\n except (Exception, KeyboardInterrupt) as e:\n _log.exception(f\"Halting due to {str(e.__class__.__name__)} exception\")\n errors = 1\n\n return errors\n\n\nif __name__ == \"__main__\":\n exit(main())\nelse:\n _log = createLogger(\n stdout_level=_str_to_logging(\"INFO\"),\n file_level=_str_to_logging(\"DEBUG\"),\n color=True,\n filename=_log_file,\n )\n", "sub_path": "skeletons/skeleton.py", "file_name": "skeleton.py", "file_ext": "py", "file_size_in_byte": 13327, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.Logger", "line_number": 45, "usage_type": "attribute"}, {"api_name": "os.path.basename", "line_number": 47, "usage_type": "call"}, {"api_name": "os.path", "line_number": 47, "usage_type": "attribute"}, {"api_name": "typing.Optional", "line_number": 48, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 48, "usage_type": "call"}, {"api_name": "os.path", "line_number": 48, "usage_type": "attribute"}, {"api_name": "typing.Sequence", "line_number": 59, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 60, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 60, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 61, "usage_type": "name"}, {"api_name": "dataclasses.field", "line_number": 61, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 62, "usage_type": "call"}, {"api_name": "dataclasses.field", "line_number": 63, "usage_type": "call"}, {"api_name": "typing.List", "line_number": 75, "usage_type": "name"}, {"api_name": "typing.List", "line_number": 88, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 101, "usage_type": "name"}, {"api_name": "subprocess.Popen", "line_number": 117, "usage_type": "call"}, {"api_name": "subprocess.PIPE", "line_number": 117, "usage_type": "attribute"}, {"api_name": "typing.cast", "line_number": 124, "usage_type": "call"}, {"api_name": "typing.TextIO", "line_number": 124, "usage_type": "argument"}, {"api_name": "typing.cast", "line_number": 125, "usage_type": "call"}, {"api_name": "typing.TextIO", "line_number": 125, "usage_type": "argument"}, {"api_name": "dataclasses.dataclass", "line_number": 55, "usage_type": "name"}, {"api_name": "typing.Optional", "line_number": 159, "usage_type": "name"}, {"api_name": "logging.INFO", "line_number": 156, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 157, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 173, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 174, "usage_type": "attribute"}, {"api_name": "typing.Any", "line_number": 176, "usage_type": "name"}, {"api_name": "typing.Any", "line_number": 177, "usage_type": "name"}, {"api_name": "colorlog.ColoredFormatter", "line_number": 181, "usage_type": "name"}, {"api_name": "colorlog.ColoredFormatter", "line_number": 182, "usage_type": "name"}, {"api_name": "logging.Formatter", "line_number": 185, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 214, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 215, "usage_type": "attribute"}, {"api_name": "logging.WARNING", "line_number": 216, "usage_type": "attribute"}, {"api_name": "logging.ERROR", "line_number": 217, "usage_type": "attribute"}, {"api_name": "logging.CRITICAL", "line_number": 218, "usage_type": "attribute"}, {"api_name": "logging.Formatter", "line_number": 223, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 233, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 233, "usage_type": "attribute"}, {"api_name": "logging.FileHandler", "line_number": 261, "usage_type": "call"}, {"api_name": "logging.Formatter", "line_number": 263, "usage_type": "call"}, {"api_name": "typing.Union", "line_number": 271, "usage_type": "name"}, {"api_name": "typing.cast", "line_number": 293, "usage_type": "call"}, {"api_name": "logging.DEBUG", "line_number": 295, "usage_type": "attribute"}, {"api_name": "logging.INFO", "line_number": 297, "usage_type": "attribute"}, {"api_name": "logging.WARN", "line_number": 299, "usage_type": "attribute"}, {"api_name": "logging.ERROR", "line_number": 301, "usage_type": "attribute"}, {"api_name": "logging.CRITICAL", "line_number": 303, "usage_type": "attribute"}, {"api_name": "argparse.Action", "line_number": 318, "usage_type": "attribute"}, {"api_name": "argparse.Action", "line_number": 326, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 334, "usage_type": "call"}]}
+{"seq_id": "230985919", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 10 09:51:26 2018\n\n@author: Utente\n\"\"\"\n\n#old main\ndef main_simulation(N1 = 100, N2 = 100, rip = 10, p = 0.33, parent_dir = 'C:/Users/Utente/Anaconda3/Cooperazione'):\n from simul_with_err import R_simul_with_err, N_simul_with_err\n from init_simulation import init_simulation\n import statistics\n import time\n import my_print as my\n import math\n import numpy as np\n start = time.time()\n dir_name = parent_dir + '/'+ repr(N1)+'-'+repr(N2)+'-'+repr(rip)\n name = 'p'+format(p,'.2f')\n S1 = int(math.sqrt(N1))\n S2 = int(math.sqrt(N2))\n print('Calcolo il tempo medio di assorbimento...')\n # CALCOLO IL TEMPO MEDIO DI ASSORBIMENTO/CONVERGENZA A N FISSATO\n t = []\n for i in range(0,5):\n t_conv = init_simulation(N1)\n t.append(t_conv)\n t_mean = int(statistics.mean(t))\n print('t_mean = {}'.format(t_mean))\n #attenzione qui che potrebbe essere un tempo spropositato\n tot_step = int(t_mean)*10\n finish = time.time()\n t_tot = round((finish-start)/60,2)\n print('Tempo impiegato per calcolare t_conv = {}'.format(t_tot), 'min\\n')\n \n t0 = time.time()\n \n #RANDOM SIMULATION\n R_start_time = round((time.time() - start)/60,2)\n print('R_start_time = ', R_start_time)\n R_eps_S = R_simul_with_err(N1, N2,rip, p, tot_step, dir_name, R_start_time = R_start_time)\n t2 = time.time()\n t_seconda = round((t2 - t0)/60 , 2)\n print('Tempo esecuzione simulazioni random = {}'.format(t_seconda), 'min\\n')\n \n #NESTED SIMULATION\n N_start_time = round((time.time()-start)/60,2)\n print('N_start_time = ', N_start_time)\n N_eps_S = N_simul_with_err(N1, N2, rip, p, tot_step, dir_name, N_start_time = N_start_time)\n t3 = time.time()\n t_N = round((t3-t2)/60,2)\n print('Tempo esecuzione simulazioni nested = {}'.format(t_N), 'min\\n')\n \n #plot finali\n #info1 = {'tit1': 'S(eps) nested con C = 0.35', 'tit2': 'S(eps) random con C = 0.35',\n # 'xlab': 'epsilon' , 'ylab_1': 'S_1', 'ylab_2' : 'S_2'}\n #info2 = {'tit' : '(S_nest - S_rnd)/S0 in funzione di eps per C = 0.35',\n # 'ylab_3' : '(delta S1)/S0', 'ylab_4': 'delta S2'}\n #my.eps_print(R_eps_S, N_eps_S, name, dir_name, info1, info2, S1, S2)\n #u\"\\u03C4\" tau\n N_info = {'ylab' : 'Abbondanze n delle S1 specie', 'tit': 'n('+u\"\\u03C4\"+') per '}\n R_info = {'ylab' : 'Abbondanze n delle S2 specie', 'tit': 'n('+u\"\\u03C4\"+') per '}\n #kappas = np.linspace(0, 0.7, 8)\n #epsilons = []\n #for i in range(len(kappas)):\n # eps1 = (kappas[i]/(1-kappas[i]))/(p*math.sqrt(N1))\n # epsilons.append(round(eps1,4))\n epsilons = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\n my.n_plot(dir_name, format(p,'.2f'), epsilons, N_info, R_info)\n \n t_f = time.time()\n t_simul = round((t_f-start)/60,2)\n my.overview(N1, tot_step, rip, t_simul, dir_name)\n print('main eseguita con successo. \\n')\n\n#only this function needed\ndef tau_conv(N):\n from init_simulation import init_simulation\n import statistics as stat\n tau = []\n for i in range(5):\n tau_i = init_simulation(N)\n tau.append(tau_i)\n tau_mean = stat.mean(tau)\n tau_dev = stat.stdev(tau)\n print('tau_mean = ', round(tau_mean,1))\n print('tau_dev = ', round(tau_dev,1))\n tau_conv = int(round(tau_mean + 10*tau_dev, 0))\n print('tau_conv = tau_mean + 5*tau_dev = ', tau_conv, '\\n')\n \n return tau_conv", "sub_path": "Older versions/main.py", "file_name": "main.py", "file_ext": "py", "file_size_in_byte": 3451, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "time.time", "line_number": 17, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 20, "usage_type": "call"}, {"api_name": "math.sqrt", "line_number": 21, "usage_type": "call"}, {"api_name": "init_simulation.init_simulation", "line_number": 26, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 28, "usage_type": "call"}, {"api_name": "time.time", "line_number": 32, "usage_type": "call"}, {"api_name": "time.time", "line_number": 36, "usage_type": "call"}, {"api_name": "time.time", "line_number": 39, "usage_type": "call"}, {"api_name": "simul_with_err.R_simul_with_err", "line_number": 41, "usage_type": "call"}, {"api_name": "time.time", "line_number": 42, "usage_type": "call"}, {"api_name": "time.time", "line_number": 47, "usage_type": "call"}, {"api_name": "simul_with_err.N_simul_with_err", "line_number": 49, "usage_type": "call"}, {"api_name": "time.time", "line_number": 50, "usage_type": "call"}, {"api_name": "my_print.n_plot", "line_number": 69, "usage_type": "call"}, {"api_name": "time.time", "line_number": 71, "usage_type": "call"}, {"api_name": "my_print.overview", "line_number": 73, "usage_type": "call"}, {"api_name": "init_simulation.init_simulation", "line_number": 82, "usage_type": "call"}, {"api_name": "statistics.mean", "line_number": 84, "usage_type": "call"}, {"api_name": "statistics.stdev", "line_number": 85, "usage_type": "call"}]}
+{"seq_id": "364617402", "text": "# Gen v0.1\n# A generic, JSON-based asset pipeline for heterogeneous setups and\n# unusual configurations.\n#\n# This is free and unencumbered software released into the public domain.\n# For more information, please refer to \n\nimport os\nimport shutil\nimport json\nimport subprocess\nimport jinja2\nimport jinja2.meta\nimport sys\nimport imp\nimport argparse\nimport logging\nimport copy\nimport time\n\n# Helper functions\ndef in_out_file(asset_root, dist_root, f):\n return os.path.join(asset_root, f), os.path.join(dist_root, f)\ndef is_newer(i_file, o_file):\n if (not os.path.exists(o_file) or\n os.path.getmtime(i_file) > os.path.getmtime(o_file)):\n return True\n return False\n\ndef find_asset_object(assets, directory):\n directory = os.path.normpath(directory)\n # Go as long as we don't repeat ourselves.\n while directory != os.path.dirname(directory):\n for cur_asset in assets:\n if cur_asset['root'] == directory:\n return cur_asset\n # Remove the last component of the directory, effectively pointing to\n # it's parent.\n directory = os.path.dirname(directory)\n return None\n\n# Exceptions\nclass AssetRootNotFound(Exception):\n pass\n\nclass ValidationError(Exception):\n def __init__(self, msg, obj):\n super().__init__(msg)\n self.obj = obj\nclass InputTypeError(ValidationError):\n def __init__(self, obj, expected_type):\n super().__init__(\"Input object '{0}' must be type: '{1}'\"\n .format(repr(obj), str(expected_type)), obj)\n self.expected_type = expected_type\nclass InputAttributeError(ValidationError):\n def __init__(self, obj, attr):\n super().__init__(\"Input object '{0}' must have attribute: '{1}'\"\n .format(repr(obj), str(attr)), obj)\n self.attr = attr\nclass SourceNotFoundError(ValidationError):\n def __init__(self, obj, fname):\n super().__init__(\"Source file '{0}' doesn't exist.\".format(fname), obj)\n self.fname = fname\n\nclass Environment:\n def __init__(self, root, dist_root):\n \"\"\"Initialize the root and the dist root with given values.\"\"\"\n self.root = os.path.abspath(root)\n self.dist_root = os.path.abspath(dist_root)\n\nclass Output:\n def __init__(self, logger=None):\n self.log = logger or logging.getLogger(__name__)\n self.log.addHandler(logging.StreamHandler(sys.stdout))\n self.log.setLevel(logging.WARNING)\n\n def on_transform(self, in_file, out_file):\n self.log.info(os.path.relpath(in_file) + ' => ' +\n os.path.relpath(out_file))\n\n def on_skip(self, out_file):\n self.log.debug('Skipping ' + os.path.relpath(out_file))\n\n def on_command(self, args):\n self.log.info('Running: ' + ' '.join(args))\n\n def on_error(self, msg):\n self.log.error(msg)\n\n def on_remove(self, filename, **kwargs):\n adj = kwargs.get('adj', '') + ' '\n filetype = kwargs.get('filetype') or 'file'\n self.log.info(\"Removing \" + adj + filetype + ': ' + filename)\n\nclass Operations:\n def __init__(self, out=None):\n self.out = out or Output()\n\n def copy(self, input_file, output_file):\n # Make sure the destination directory exists.\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n # Copy the file\n shutil.copy(input_file, output_file)\n shutil.copystat(input_file, output_file)\n # Notify the environment\n self.out.on_transform(input_file, output_file)\n\n def file_from_content(self, input_file, content, output_file):\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n with open(output_file, \"w\") as f:\n f.write(content)\n shutil.copystat(input_file, output_file)\n self.out.on_transform(input_file, output_file)\n\n def subprocess_transform(self, prg, options, input_file, output_file):\n args = [prg, input_file, output_file]\n args[1:1] = options\n\n os.makedirs(os.path.dirname(output_file), exist_ok=True)\n\n self.out.on_command(args)\n if subprocess.call(args):\n self.out.on_transform(input_file, output_file)\n shutil.copystat(input_file, output_file)\n\nclass BaseAsset:\n def __init__(self, root, dist, inputs, ops, options, env):\n self.root = os.path.abspath(root)\n self.dist = os.path.abspath(dist)\n\n # Validate each input.\n for i in range(len(inputs)):\n try:\n self.validate(inputs[i])\n except ValidationError as e:\n # Rethrow with a modified message.\n tb = sys.exc_info()[2]\n e.args[0] = 'input[{0}]: '.format(i) + e.args[0]\n raise e.with_traceback(tb)\n except NotImplementedError:\n # If validation isn't implemented that doesn't really matter.\n # Just bail.\n break\n # If there was validation, it passed.\n self.inputs = inputs\n\n self.operations = ops\n self.options = options\n self.env = env\n\n def list_output(self):\n raise NotImplementedError\n def get_dependencies(self, fname):\n \"\"\"Return a list of files relative to self.root that fname requires.\"\"\"\n raise NotImplementedError\n def install(self, filename):\n raise NotImplementedError\n def validate(self, input_obj):\n raise NotImplementedError\n\n def install_all(self):\n \"\"\"Install all files and return what files were installed.\"\"\"\n to_install = self.list_output()\n for f in to_install:\n self.install(f)\n return to_install\n\nclass StaticAsset(BaseAsset):\n def validate(self, fname):\n # Make sure it's a string.\n if not isinstance(fname, str):\n raise InputTypeError(fname, str)\n # Make sure the file exists!\n if not os.path.exists(os.path.join(self.root, fname)):\n raise SourceNotFoundError(fname, fname)\n\n def _get_source_list(self, input_obj):\n # If we are given a directory, use all the files in that directory.\n abs_input = os.path.join(self.root, input_obj)\n if os.path.isdir(abs_input):\n files = []\n for child in os.listdir(abs_input):\n child = os.path.join(abs_input, child)\n files.extend(self._get_source_list(os.path.normpath(child)))\n return files\n # Otherwise it's just a file, easy.\n else:\n return [os.path.relpath(abs_input, self.root)]\n\n def get_dependencies(self, filename):\n return [filename]\n\n def list_output(self):\n files = []\n for i in self.inputs:\n files.extend(self._get_source_list(i))\n return files\n\n def install(self, filename):\n in_f, out_f = in_out_file(self.root, self.dist, filename)\n self.operations.copy(in_f, out_f)\n\nclass Jinja2Asset(BaseAsset):\n def validate(self, input_obj):\n # Here we expect an object with a filename and parameters.\n if not isinstance(input_obj, dict):\n raise InputTypeError(input_obj, dict)\n\n # Make sure we have a filename and that it exists.\n f = input_obj.get('filename', None)\n if f is None:\n raise InputAttributeError(input_obj, 'filename')\n if not os.path.exists(os.path.join(self.root, f)):\n raise SourceNotFoundError(input_obj, f)\n\n def get_dependencies(self, filename):\n depends = [filename]\n\n source = os.path.join(self.root, filename)\n ast = jinja2.Environment().parse(open(source).read())\n template_depends = jinja2.meta.find_referenced_templates(ast)\n for dependency in template_depends:\n if dependency:\n dependency = os.path.join(os.path.dirname(source), dependency)\n dependency = os.path.normpath(dependency)\n dependency = os.path.relpath(dependency, self.root)\n depends.extend(self.get_dependencies(dependency))\n return depends\n\n def list_output(self):\n output = []\n for i in self.inputs:\n output.append(i['filename'])\n return output\n\n def install(self, filename):\n # Set up our Jinja2 environment.\n loader = jinja2.FileSystemLoader(self.root)\n self.__jinja2env = jinja2.Environment(loader=loader)\n\n # Find the asset object based off it's filename.\n # TODO Make this process automatic in the base class.\n input_obj = None\n for i in self.inputs:\n if i['filename'] == filename:\n input_obj = i\n break\n if input_obj is None:\n raise ValueError(\"Cannot find input object with filename: '{0}'\"\n .format(filename))\n\n # The filename is relative to the asset root, but that is where Jinja2\n # looks, so it works out.\n template = self.__jinja2env.get_template(filename)\n\n if 'parameters' in input_obj:\n rendered_template = template.render(input_obj['parameters'])\n else:\n rendered_template = template.render()\n\n in_f, out_f = in_out_file(self.root, self.dist, filename)\n self.operations.file_from_content(in_f, rendered_template, out_f)\n\nclass ScssAsset(StaticAsset):\n def get_dependencies(self, filename):\n return [os.path.splitext(filename)[0] + '.scss']\n def list_output(self):\n output = super().list_output()\n for i in range(len(output)):\n output[i] = os.path.splitext(output[i])[0] + '.css'\n return output\n\n def install(self, filename):\n in_f = os.path.join(self.root, os.path.splitext(filename)[0] + '.scss')\n out_f = os.path.join(self.dist, filename)\n\n # Check for search paths provided.\n search_paths = self.options.get('search_paths', [])\n command_options = []\n for path in search_paths:\n command_options.extend(['--load-path',\n os.path.join(self.env.dist_root, path)])\n\n self.operations.subprocess_transform('scss', command_options,\n in_f, out_f)\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--assets-file', default=None,\n help=\"Specify the assets json file \" +\n \"(default ./assets.json).\")\n parser.add_argument('-w', '--watch', action=\"store_true\", default=False,\n help=\"Stay open and watch for file changes.\")\n parser.add_argument('-v', '--verbose', action=\"count\", default=0,\n help=\"Log files copied to stderr.\")\n arguments = parser.parse_args()\n\n out = Output()\n if arguments.verbose == 1:\n out.log.setLevel(logging.INFO)\n elif arguments.verbose > 1:\n out.log.setLevel(logging.DEBUG)\n\n # Parse the assets.json file.\n try:\n assets_json_filename = arguments.assets_file or 'assets.json'\n assets_json = json.load(open(assets_json_filename))\n except OSError:\n out.on_error(\"Failed to open '\" + assets_json_filename + \"'!\")\n sys.exit(1)\n\n env = Environment(os.getcwd(),\n os.path.abspath(assets_json.get('dist', 'dist/')))\n\n transformations = {'static': StaticAsset, 'jinja2': Jinja2Asset,\n 'scss': ScssAsset}\n\n while True:\n # Load up our cached modification times.\n try:\n cache = json.load(open('.gencache.json'))\n except OSError:\n cache = {}\n\n cache_to_write = copy.copy(cache)\n\n output = []\n for asset in assets_json.get('assets', []):\n # Find the asset-specific dist dir.\n asset_dist = os.path.join(env.dist_root,\n asset.get('dist', asset['root']))\n asset_dist = os.path.normpath(asset_dist)\n\n # Find our asset class!\n asset_type = transformations.get(asset['type'])\n if asset_type:\n try:\n asset_obj = asset_type\n asset_obj = asset_type(asset['root'], asset_dist,\n asset['input'], Operations(out),\n asset.get('type_options', {}), env)\n except ValidationError as e:\n out.on_error(e)\n continue\n else:\n out.on_error(\"No plugin available to handle '\" +\n asset['type'] + \"' assets.\")\n continue\n\n for f in asset_obj.list_output():\n depends = asset_obj.get_dependencies(f)\n regeneration_required = False\n for dependency in depends:\n dependency_source = os.path.join(asset['root'], dependency)\n dependency_mtime = os.path.getmtime(dependency_source)\n # If the dependency has been changed:\n if cache.get(dependency, 0) < dependency_mtime:\n # Update the cache.\n cache_to_write[dependency] = dependency_mtime\n # Make sure we regenerate the output file later.\n regeneration_required = True\n\n if regeneration_required:\n asset_obj.install(f)\n else:\n out.on_skip(f)\n output.append(os.path.join(asset_dist, f))\n\n # Write the cache.\n json.dump(cache_to_write, open('.gencache.json', 'w'))\n\n for dirname, dirs, files in os.walk(env.dist_root, topdown=False):\n for f in files:\n # Check if the file should be there.\n f = os.path.join(dirname, f)\n if f not in output:\n out.on_remove(os.path.relpath(f), adj='old')\n os.remove(os.path.join(env.dist_root, f))\n\n # Also remove empty children directories.\n for d in dirs:\n d = os.path.join(dirname, d)\n if len(os.listdir(d)) == 0:\n out.on_remove(os.path.relpath(f), adj='empty',\n filetype='directory')\n os.rmdir(d)\n\n time.sleep(.25)\n if not arguments.watch:\n break\n", "sub_path": "gen.py", "file_name": "gen.py", "file_ext": "py", "file_size_in_byte": 14437, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "os.path.join", "line_number": 23, "usage_type": "call"}, {"api_name": "os.path", "line_number": 23, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 25, "usage_type": "call"}, {"api_name": "os.path", "line_number": 25, "usage_type": "attribute"}, {"api_name": "os.path.getmtime", "line_number": 26, "usage_type": "call"}, {"api_name": "os.path", "line_number": 26, "usage_type": "attribute"}, {"api_name": "os.path.normpath", "line_number": 31, "usage_type": "call"}, {"api_name": "os.path", "line_number": 31, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 33, "usage_type": "call"}, {"api_name": "os.path", "line_number": 33, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 39, "usage_type": "call"}, {"api_name": "os.path", "line_number": 39, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 68, "usage_type": "call"}, {"api_name": "os.path", "line_number": 68, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 69, "usage_type": "call"}, {"api_name": "os.path", "line_number": 69, "usage_type": "attribute"}, {"api_name": "logging.getLogger", "line_number": 73, "usage_type": "call"}, {"api_name": "logging.StreamHandler", "line_number": 74, "usage_type": "call"}, {"api_name": "sys.stdout", "line_number": 74, "usage_type": "attribute"}, {"api_name": "logging.WARNING", "line_number": 75, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 78, "usage_type": "call"}, {"api_name": "os.path", "line_number": 78, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 79, "usage_type": "call"}, {"api_name": "os.path", "line_number": 79, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 82, "usage_type": "call"}, {"api_name": "os.path", "line_number": 82, "usage_type": "attribute"}, {"api_name": "os.makedirs", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 101, "usage_type": "call"}, {"api_name": "os.path", "line_number": 101, "usage_type": "attribute"}, {"api_name": "shutil.copy", "line_number": 103, "usage_type": "call"}, {"api_name": "shutil.copystat", "line_number": 104, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 109, "usage_type": "call"}, {"api_name": "os.path", "line_number": 109, "usage_type": "attribute"}, {"api_name": "shutil.copystat", "line_number": 112, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 119, "usage_type": "call"}, {"api_name": "os.path", "line_number": 119, "usage_type": "attribute"}, {"api_name": "subprocess.call", "line_number": 122, "usage_type": "call"}, {"api_name": "shutil.copystat", "line_number": 124, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 128, "usage_type": "call"}, {"api_name": "os.path", "line_number": 128, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 129, "usage_type": "call"}, {"api_name": "os.path", "line_number": 129, "usage_type": "attribute"}, {"api_name": "sys.exc_info", "line_number": 137, "usage_type": "call"}, {"api_name": "os.path.exists", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path", "line_number": 174, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 174, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 179, "usage_type": "call"}, {"api_name": "os.path", "line_number": 179, "usage_type": "attribute"}, {"api_name": "os.path.isdir", "line_number": 180, "usage_type": "call"}, {"api_name": "os.path", "line_number": 180, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 182, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 183, "usage_type": "call"}, {"api_name": "os.path", "line_number": 183, "usage_type": "attribute"}, {"api_name": "os.path.normpath", "line_number": 184, "usage_type": "call"}, {"api_name": "os.path", "line_number": 184, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 188, "usage_type": "call"}, {"api_name": "os.path", "line_number": 188, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path", "line_number": 213, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 213, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 219, "usage_type": "call"}, {"api_name": "os.path", "line_number": 219, "usage_type": "attribute"}, {"api_name": "jinja2.Environment", "line_number": 220, "usage_type": "call"}, {"api_name": "jinja2.meta.find_referenced_templates", "line_number": 221, "usage_type": "call"}, {"api_name": "jinja2.meta", "line_number": 221, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path", "line_number": 224, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 224, "usage_type": "call"}, {"api_name": "os.path.normpath", "line_number": 225, "usage_type": "call"}, {"api_name": "os.path", "line_number": 225, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 226, "usage_type": "call"}, {"api_name": "os.path", "line_number": 226, "usage_type": "attribute"}, {"api_name": "jinja2.FileSystemLoader", "line_number": 238, "usage_type": "call"}, {"api_name": "jinja2.Environment", "line_number": 239, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 266, "usage_type": "call"}, {"api_name": "os.path", "line_number": 266, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 270, "usage_type": "call"}, {"api_name": "os.path", "line_number": 270, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path", "line_number": 274, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 274, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 275, "usage_type": "call"}, {"api_name": "os.path", "line_number": 275, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 282, "usage_type": "call"}, {"api_name": "os.path", "line_number": 282, "usage_type": "attribute"}, {"api_name": "argparse.ArgumentParser", "line_number": 288, "usage_type": "call"}, {"api_name": "logging.INFO", "line_number": 300, "usage_type": "attribute"}, {"api_name": "logging.DEBUG", "line_number": 302, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 307, "usage_type": "call"}, {"api_name": "sys.exit", "line_number": 310, "usage_type": "call"}, {"api_name": "os.getcwd", "line_number": 312, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 313, "usage_type": "call"}, {"api_name": "os.path", "line_number": 313, "usage_type": "attribute"}, {"api_name": "json.load", "line_number": 321, "usage_type": "call"}, {"api_name": "copy.copy", "line_number": 325, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 330, "usage_type": "call"}, {"api_name": "os.path", "line_number": 330, "usage_type": "attribute"}, {"api_name": "os.path.normpath", "line_number": 332, "usage_type": "call"}, {"api_name": "os.path", "line_number": 332, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 354, "usage_type": "call"}, {"api_name": "os.path", "line_number": 354, "usage_type": "attribute"}, {"api_name": "os.path.getmtime", "line_number": 355, "usage_type": "call"}, {"api_name": "os.path", "line_number": 355, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "json.dump", "line_number": 370, "usage_type": "call"}, {"api_name": "os.walk", "line_number": 372, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 375, "usage_type": "call"}, {"api_name": "os.path", "line_number": 375, "usage_type": "attribute"}, {"api_name": "os.path.relpath", "line_number": 377, "usage_type": "call"}, {"api_name": "os.path", "line_number": 377, "usage_type": "attribute"}, {"api_name": "os.remove", "line_number": 378, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 378, "usage_type": "call"}, {"api_name": "os.path", "line_number": 378, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 382, "usage_type": "call"}, {"api_name": "os.path", "line_number": 382, "usage_type": "attribute"}, {"api_name": "os.listdir", "line_number": 383, "usage_type": "call"}, {"api_name": "os.path.relpath", "line_number": 384, "usage_type": "call"}, {"api_name": "os.path", "line_number": 384, "usage_type": "attribute"}, {"api_name": "os.rmdir", "line_number": 386, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 388, "usage_type": "call"}]}
+{"seq_id": "7279306", "text": "\"\"\"\n問題文\n正の整数Xが以下の条件を満たすとき、Xはルンルン数であると言います。\nXを(leading zeroなしで)十進数表記した際に、隣り合うどの2つの桁の値についても、差の絶対値が 1以下\n例えば、1234, 1, 334 などはルンルン数ですが、\n31415, 119, 13579 などはルンルン数ではありません。\n\n正の整数Kが与えられます。小さい方から K番目のルンルン数を求めてください。\n\n制約\n1≤K≤10^5\n入力はすべて整数である。\n\n===================\nimprovement:\n3桁のルンルン数で、上2桁が12なら、3桁目は 1 or 2 or 3 。\n小さいほうからルンルン数を列挙していくなら、そのルンルン数に末尾1桁、隣り合う数字を足してもルンルン数になる。\nこれを繰り返すことでルンルン数だけを列挙することができる。\n言われてみればこの実装で動くのは理解できるが、\n時間内にこれを思いつくことが出来なかった。悔しい。\n特にdequeを使う動きは思いつかなかった、次回に活かしたい。\n\"\"\"\n\n# === improvement ===\nfrom collections import deque\n\nK = int(input())\n\nq = deque(range(1, 10))\n\nfor i in range(K):\n x = q.popleft()\n r = x % 10\n y = 10 * x + r\n if r != 0:\n q.append(y - 1)\n q.append(y)\n if r != 9:\n q.append(y + 1)\n\nprint(x)\n", "sub_path": "ABC161/D.py", "file_name": "D.py", "file_ext": "py", "file_size_in_byte": 1416, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "collections.deque", "line_number": 29, "usage_type": "call"}]}
+{"seq_id": "618606107", "text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nimport unittest\n\nclass NewVisitorTest(unittest.TestCase) :\n def setUp(self) :\n self.browser = webdriver.Firefox()\n\n def tearDown(self) :\n self.browser.quit()\n def check_in_table(self, row_text, idtag) :\n table = self.browser.find_element_by_id(idtag)\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(row_text, [row.text for row in rows])\n\n def check_ids(self, text, idtag) :\n outputs= self.browser.find_elements_by_id(idtag)\n self.assertIn(text, [output.text for output in outputs])\n\n def waitforelement(self, id) :\n try:\n waiter = WebDriverWait(driver, 10)\n waiter.until(EC.presence_of_element_located(By.ID, id))\n finally:\n self.fail('Timedout')\n\n def box(self, id) :\n return self.browser.find_element_by_id(id)\n\n def test_can_build_a_cv(self) :\n #goes to check out cv builder\n self.browser.get('http://127.0.0.1:8000/cv/')\n \n #notices title and header mention cv builder\n self.assertIn('CV Builder', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1')\n\n\n\n\n\n #invited to enter name\n inputboxname=self.browser.find_element_by_id('namequest')\n self.assertEqual(self.browser.find_element_by_id('namequestion').text, 'Enter your full name')\n #types James Bartlett into text box\n inputboxname.send_keys('James Bartlett')\n inputboxname.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('namedis').text, 'Name: James Bartlett')\n\n\n #invited to enter email into text box\n inputboxemail = self.browser.find_element_by_id('email')\n self.assertEqual(self.browser.find_element_by_id('emailquestion').text, \"Enter your email\")\n # checks to see if a non email can be entered\n\n\n # enters james@gmail.com\n inputboxemail.send_keys('james@gmail.com')\n inputboxemail.send_keys(Keys.ENTER)\n time.sleep(1)\n # self.waitforelement('email')\n self.assertEqual(self.browser.find_element_by_id('emaildis').text, 'Email: james@gmail.com')\n inputboxemail = self.browser.find_element_by_id('email')\n inputboxemail.send_keys('jameslukebartlett@gmail.com')\n time.sleep(1)\n inputboxemail.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('emaildis').text, 'Email: jameslukebartlett@gmail.com')\n\n #invited to enter mobile number into text box\n inputboxnumber=self.browser.find_element_by_id('number')\n self.assertEqual(self.browser.find_element_by_id('telquestion').text, 'Enter your telephone number')\n #checks a non number can't be entered\n\n\n inputboxnumber.send_keys('111111111')\n inputboxnumber.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('numberdis').text, 'Number: 111111111')\n\n #types 07094534634 in\n inputboxnumber = self.browser.find_element_by_id('number')\n inputboxnumber.send_keys('07094534634')\n inputboxnumber.send_keys(Keys.ENTER)\n time.sleep(1)\n self.assertEqual(self.browser.find_element_by_id('numberdis').text, 'Number: 07094534634')\n\n # when hits enter name, email and number are displayed\n #will need to decide how i want it displayed\n #Personal profile\n\n #Invited towrite a personal profile\n inputboxprofile = self.browser.find_element_by_id('personalprof')\n self.assertEqual(self.browser.find_element_by_id('profquestion').text, 'Enter a personal profile')\n #Types looking for work have a computer sciecne degree and good teamwork skills\n inputboxprofile.send_keys('Looking for work have a computer science degree and good teamwork skills')\n submitprofile = self.browser.find_element_by_id('Profile')\n submitprofile.click()\n time.sleep(1)\n #Upon enter personal profile is displayed\n self.assertEqual(self.browser.find_element_by_id('profiledis').text, 'Looking for work have a computer science degree and good teamwork skills')\n\n inputboxprofile = self.browser.find_element_by_id('personalprof')\n inputboxprofile.send_keys('Looking to study a course to further improve my robotics. I am hard working and work well in a team')\n submitprofile = self.browser.find_element_by_id('Profile')\n submitprofile.click()\n time.sleep(1)\n #Upon enter personal profile is displayed\n self.assertEqual(self.browser.find_element_by_id('profiledis').text, 'Looking to study a course to further improve my robotics. I am hard working and work well in a team')\n\n\n #Skills\n inputboxskills=self.browser.find_element_by_id('skill')\n self.assertEqual(self.browser.find_element_by_id('Skillsquestion').text, 'Enter a skill')\n\n #Invited to enter a skill\n inputboxskills.send_keys('Java')\n inputboxskills.send_keys(Keys.ENTER)\n #Types Java\n time.sleep(1)\n\n # Upon enter java is displayed underskills\n self.check_in_table('Java', 'skillstable')\n # Invited to enter another skill\n\n\n # Types Teamwork\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Teamwork')\n inputboxskills.send_keys(Keys.ENTER)\n # Upon enter both skills entries are displayed\n time.sleep(1)\n # self.fail('Checking if it gets to this point')\n # self.check_in_table('Java', 'skillstable')\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('C')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Attention to detail')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n self.check_in_table('Attention to detail', 'skillstable')\n\n inputboxskills = self.box('skill')\n inputboxskills.send_keys('Python')\n inputboxskills.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Java', 'skillstable')\n self.check_in_table('Teamwork', 'skillstable')\n self.check_in_table('C', 'skillstable')\n self.check_in_table('Attention to detail', 'skillstable')\n self.check_in_table('Python', 'skillstable')\n\n\n\n #Invited to enter a qualification\n inputboxqualification = self.browser.find_element_by_id('qualification')\n self.assertEqual(self.browser.find_element_by_id('Qualificationquestion').text, 'Enter a proffessional qualification')\n\n #Types level 1 java\n inputboxqualification.send_keys('Level 1 Java')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('Level 2 Java')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('BCS Essentials Certificate in Artificial Intelligence')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('BSC Computer Science')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n self.check_in_table('BSC Computer Science', 'qualificationstable')\n\n inputboxqualification = self.box('qualification')\n inputboxqualification.send_keys('Level 1 Teamwork')\n inputboxqualification.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('Level 1 Java', 'qualificationstable')\n self.check_in_table('Level 2 Java', 'qualificationstable')\n self.check_in_table('BCS Essentials Certificate in Artificial Intelligence', 'qualificationstable')\n self.check_in_table('BSC Computer Science', 'qualificationstable')\n self.check_in_table('Level 1 Teamwork', 'qualificationstable')\n\n\n\n\n #Project\n inputboxprojecttitle = self.browser.find_element_by_id('projectover')\n self.assertEqual(self.browser.find_element_by_id('ProjectQuestion').text, 'Enter a project name')\n\n inputboxprojectdes = self.browser.find_element_by_id('projectdes')\n self.assertEqual(self.browser.find_element_by_id('ProjectDescription').text, 'Enter the description of the project')\n submitproject = self.browser.find_element_by_id('ProjectSub')\n\n inputboxprojecttitle.send_keys('Image filter in java')\n inputboxprojectdes.send_keys('Used matricies and arrays in java to create different ones by changing the rgb values')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n\n submitproject = self.box('ProjectSub')\n inputboxprojecttitle = self.box('projectover')\n inputboxprojectdes = self.box('projectdes')\n inputboxprojecttitle.send_keys('Moving robot')\n inputboxprojectdes.send_keys('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n self.check_ids('Moving robot', 'projecttitle')\n self.check_ids('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles', 'projectdescribe')\n\n inputboxprojecttitle = self.box('projectover')\n inputboxprojectdes = self.box('projectdes')\n submitproject = self.box('ProjectSub')\n inputboxprojecttitle.send_keys('Maze game')\n inputboxprojectdes.send_keys('A game where players move through a maze trying to collect as many coins as possible while fighting other players')\n submitproject.click()\n time.sleep(1)\n\n self.check_ids('Image filter in java', 'projecttitle')\n self.check_ids('Used matricies and arrays in java to create different ones by changing the rgb values', 'projectdescribe')\n self.check_ids('Moving robot', 'projecttitle')\n self.check_ids('Programmed a lego robot to follow a black line using color sensors and avoiding obstacles', 'projectdescribe')\n self.check_ids('Maze game', 'projecttitle')\n self.check_ids('A game where players move through a maze trying to collect as many coins as possible while fighting other players', 'projectdescribe')\n\n #Achievments\n\n # Invited to enter an achievment\n inputboxachievments=self.browser.find_element_by_id('achievment')\n self.assertEqual(self.browser.find_element_by_id('Achievmentquestion').text, 'Enter an achievment')\n\n # Types 1st place in hackathon\n inputboxachievments.send_keys('1st place in hackathon')\n # Upon enter displays ahcivment\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n # Invited to enter another achievent\n\n #Types a levels\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('a levels')\n\n # upon enter displays both ahcivments\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('Best in a level maths')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('1st Place in BAE systems CTF')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n self.check_in_table('1st Place in BAE systems CTF', 'achtable')\n\n inputboxachievments = self.box('achievment')\n inputboxachievments.send_keys('Social Secretary for filmsoc between 2019 and 2020')\n inputboxachievments.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.check_in_table('1st place in hackathon', 'achtable')\n self.check_in_table('a levels', 'achtable')\n self.check_in_table('Best in a level maths', 'achtable')\n self.check_in_table('1st Place in BAE systems CTF', 'achtable')\n self.check_in_table('Social Secretary for filmsoc between 2019 and 2020', 'achtable')\n #Work experience\n\n # Invited to enter name of company\n inputboxcompany = self.browser.find_element_by_id('placeofwork')\n self.assertEqual(self.browser.find_element_by_id('placeofworkq').text, 'Enter the place of work')\n #Enters university of brimigham\n # Invited to enter job role\n inputboxjob = self.browser.find_element_by_id('role')\n self.assertEqual(self.browser.find_element_by_id('roleq').text, 'Enter the job role')\n #Types student ambassador\n #Invited to enter date started\n inputboxstartdatew=self.browser.find_element_by_id('startdatew')\n self.assertEqual(self.browser.find_element_by_id('startdatewq').text, 'Enter the start date of the job')\n\n #Types 01/2019\n #Invited to enter date finished or present\n self.assertEqual(self.browser.find_element_by_id('enddatewq').text, 'Enter the date you finished the role')\n #Types present\n #Invited to enter job description\n inputboxenddatew=self.browser.find_element_by_id('enddatew')\n self.assertEqual(self.browser.find_element_by_id('jobdesq').text, 'Enter the job description details')\n submitworkexp = self.browser.find_element_by_id('WorkExperience')\n inputboxjobdes=self.browser.find_element_by_id('description')\n\n #Types resonsiple to showing students round builidng makeing them feel welcome and setting up events\n inputboxcompany.send_keys(\"University of Birmingham\")\n inputboxjob.send_keys(\"student ambassador\")\n inputboxstartdatew.send_keys('01/01/2019')\n inputboxenddatew.send_keys('03/08/2020')\n inputboxjobdes.send_keys(\"Responsible for showing students round building making them feel welcome and setting up events\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\", \"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n\n inputboxcompany = self.box('placeofwork')\n inputboxjob = self.box('role')\n inputboxstartdatew = self.box('startdatew')\n inputboxenddatew = self.box('enddatew')\n inputboxjobdes = self.box('description')\n submitworkexp = self.box('WorkExperience')\n\n inputboxcompany.send_keys(\"PGL\")\n inputboxjob.send_keys(\"Activity Instrustuctor / Group Leader\")\n inputboxstartdatew.send_keys('01/07/2019')\n inputboxenddatew.send_keys('01/09/2019')\n inputboxjobdes.send_keys(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\",\"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Activity Instrustuctor / Group Leader\", \"jobtitled\")\n self.check_ids(\"Company: PGL\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/07/2019 - 01/09/2019\", \"jobdatesd\")\n self.check_ids(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\", \"jobdetailsd\")\n\n inputboxcompany = self.box('placeofwork')\n inputboxjob = self.box('role')\n inputboxstartdatew = self.box('startdatew')\n inputboxenddatew = self.box('enddatew')\n inputboxjobdes = self.box('description')\n submitworkexp = self.box('WorkExperience')\n\n inputboxcompany.send_keys(\"Coder Dojo\")\n inputboxjob.send_keys(\"Mentor\")\n inputboxstartdatew.send_keys('01/10/2017')\n inputboxenddatew.send_keys('01/07/2019')\n inputboxjobdes.send_keys(\"Mentored students while they learned to code. Also set up for events and attended various promotoional activities\")\n submitworkexp.click()\n time.sleep(1)\n #Upon enter company, role, dates and job description are displayed\n self.check_ids(\"Job Role: student ambassador\",\"jobtitled\")\n self.check_ids(\"Company: University of Birmingham\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/01/2019 - 03/08/2020\", \"jobdatesd\")\n self.check_ids(\"Responsible for showing students round building making them feel welcome and setting up events\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Activity Instrustuctor / Group Leader\", \"jobtitled\")\n self.check_ids(\"Company: PGL\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/07/2019 - 01/09/2019\", \"jobdatesd\")\n self.check_ids(\"Responsbile for supervising children with thier activitys and occasionally looking after thier needes while providing a high standard of outdoor education\", \"jobdetailsd\")\n\n self.check_ids(\"Job Role: Mentor\", \"jobtitled\")\n self.check_ids(\"Company: Coder Dojo\", \"jobcompd\")\n\n self.check_ids(\"Dates: 01/10/2017 - 01/07/2019\", \"jobdatesd\")\n self.check_ids(\"Mentored students while they learned to code. Also set up for events and attended various promotoional activities\", \"jobdetailsd\")\n #Education\n\n #Invited to enter place of learning\n inputboxschool=self.browser.find_element_by_id('school')\n self.assertEqual(self.browser.find_element_by_id('schoolq').text, 'Enter the name of the school')\n\n #Enters woodhouse college\n # Invited to enter date started\n inputboxstartdates=self.browser.find_element_by_id('startdates')\n self.assertEqual(self.browser.find_element_by_id('startdatesq').text, 'Enter the date you started at the school')\n\n #Types 09/2016\n #Invited to enter date left\n inputboxenddates=self.browser.find_element_by_id('enddates')\n self.assertEqual(self.browser.find_element_by_id('enddatesq').text, 'Enter the date you finished at the school')\n\n #Types 07/2018\n #Invited to enter qualifications\n inputboxgrades = self.browser.find_element_by_id('grades')\n self.assertEqual(self.browser.find_element_by_id('gradesq').text, 'Enter the grades obtained')\n submiteducation=self.browser.find_element_by_id('EducationSubmit')\n\n #Types Maths A* FUther Maths B, Georgraphy A\n inputboxschool.send_keys('Woodhouse College')\n inputboxstartdates.send_keys('01/09/2016')\n inputboxenddates.send_keys('01/07/2018')\n inputboxgrades.send_keys('Maths A* Further Maths B Georgraphy A')\n # Upon enter school, dates and grades are displayed\n submiteducation.click()\n time.sleep(1)\n\n self.check_ids(\"School/College: Woodhouse College\", 'schoold')\n self.check_ids(\"01/09/2016 - 01/07/2018\", 'schooldatesd')\n self.check_ids(\"Maths A* Further Maths B Georgraphy A\", 'schooldetailsd')\n\n inputboxschool = self.box('school')\n inputboxstartdates = self.box('startdates')\n inputboxenddates = self.box('enddates')\n inputboxgrades = self.box('grades')\n submiteducation = self.box('EducationSubmit')\n\n inputboxschool.send_keys('University of Birmingham')\n inputboxstartdates.send_keys('01/09/2018')\n inputboxenddates.send_keys('Present')\n inputboxgrades.send_keys('BSc Computer Science, predicted 2.1')\n # Upon enter school, dates and grades are displayed\n submiteducation.click()\n time.sleep(1)\n\n self.check_ids(\"School/College: Woodhouse College\", 'schoold')\n self.check_ids(\"01/09/2016 - 01/07/2018\", 'schooldatesd')\n self.check_ids(\"Maths A* Further Maths B Georgraphy A\", 'schooldetailsd')\n\n self.check_ids(\"School/College: University of Birmingham\", 'schoold')\n self.check_ids(\"01/09/2018 - Present\", 'schooldatesd')\n self.check_ids(\"BSc Computer Science, predicted 2.1\", 'schooldetailsd')\n\n #Notes\n inputboxnotes = self.browser.find_element_by_id('Notes')\n self.assertEqual(self.browser.find_element_by_id('PostQuestion').text, 'Enter any other notes')\n\n submitnotes = self.browser.find_element_by_id('NotesSubmit')\n\n inputboxnotes.send_keys('As a reward for my hard work at a charity I was selected for a trip to europe')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n\n inputboxnotes = self.box('Notes')\n submitnotes = self.box(\"NotesSubmit\")\n inputboxnotes.send_keys('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n self.check_ids('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company', 'notesdetails')\n\n inputboxnotes = self.box('Notes')\n submitnotes = self.box(\"NotesSubmit\")\n inputboxnotes.send_keys('References from universities and previous employers are available upon request')\n submitnotes.click()\n time.sleep(1)\n\n self.check_ids('As a reward for my hard work at a charity I was selected for a trip to europe', 'notesdetails')\n self.check_ids('I am a very hard working and commited individual who has got a wide range of experience and would love to come and work for your company', 'notesdetails')\n self.check_ids('References from universities and previous employers are available upon request', 'notesdetails')\n\n\n\n\nif __name__ == '__main__' :\n unittest.main(warnings='ignore')\n", "sub_path": "functionaltests.py", "file_name": "functionaltests.py", "file_ext": "py", "file_size_in_byte": 24755, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "unittest.TestCase", "line_number": 9, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.Firefox", "line_number": 11, "usage_type": "call"}, {"api_name": "selenium.webdriver", "line_number": 11, "usage_type": "name"}, {"api_name": "selenium.webdriver.support.ui.WebDriverWait", "line_number": 26, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions.presence_of_element_located", "line_number": 27, "usage_type": "call"}, {"api_name": "selenium.webdriver.support.expected_conditions", "line_number": 27, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.by.By.ID", "line_number": 27, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.by.By", "line_number": 27, "usage_type": "name"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 51, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 51, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 52, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 64, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 64, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 65, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 70, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 71, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 71, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 72, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 82, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 82, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 83, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 89, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 89, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 90, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 104, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 112, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 123, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 123, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 125, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 135, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 135, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 137, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 145, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 145, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 146, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 154, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 154, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 155, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 164, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 164, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 165, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 181, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 181, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 182, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 188, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 188, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 189, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 196, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 196, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 197, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 205, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 205, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 206, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 215, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 215, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 216, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 238, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 249, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 262, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 280, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 280, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 281, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 291, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 291, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 292, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 299, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 299, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 300, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 308, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 308, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 309, "usage_type": "call"}, {"api_name": "selenium.webdriver.common.keys.Keys.ENTER", "line_number": 318, "usage_type": "attribute"}, {"api_name": "selenium.webdriver.common.keys.Keys", "line_number": 318, "usage_type": "name"}, {"api_name": "time.sleep", "line_number": 319, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 357, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 378, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 405, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 453, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 471, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 489, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 497, "usage_type": "call"}, {"api_name": "time.sleep", "line_number": 506, "usage_type": "call"}, {"api_name": "unittest.main", "line_number": 516, "usage_type": "call"}]}
+{"seq_id": "67537353", "text": "from __future__ import annotations\n\nimport logging\nimport ssl\nimport sys\nfrom pathlib import Path\n\nimport anyio\nimport anyio.abc\nimport paho.mqtt.client as mqtt\nimport pytest\n\nfrom asyncio_mqtt import Client, ProtocolVersion, TLSParameters, Topic, Wildcard, Will\nfrom asyncio_mqtt.types import PayloadType\n\npytestmark = pytest.mark.anyio\n\nHOSTNAME = \"test.mosquitto.org\"\nOS_PY_VERSION = sys.platform + \"_\" + \".\".join(map(str, sys.version_info[:2]))\nTOPIC_HEADER = OS_PY_VERSION + \"/tests/asyncio_mqtt/\"\n\n\nasync def test_topic_validation() -> None:\n \"\"\"Test that Topic raises Exceptions for invalid topics.\"\"\"\n with pytest.raises(TypeError):\n Topic(True) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic(1.0) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic(None) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Topic([]) # type: ignore[arg-type]\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a/b/#\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a/+/c\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"#\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"\")\n with pytest.raises(ValueError, match=\"Invalid topic: \"):\n Topic(\"a\" * 65536)\n\n\nasync def test_wildcard_validation() -> None:\n \"\"\"Test that Wildcard raises Exceptions for invalid wildcards.\"\"\"\n with pytest.raises(TypeError):\n Wildcard(True) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard(1.0) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard(None) # type: ignore[arg-type]\n with pytest.raises(TypeError):\n Wildcard([]) # type: ignore[arg-type]\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/#/c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/b+/c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a/b/#c\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"\")\n with pytest.raises(ValueError, match=\"Invalid wildcard: \"):\n Wildcard(\"a\" * 65536)\n\n\nasync def test_topic_matches() -> None:\n \"\"\"Test that Topic.matches() does and doesn't match some test wildcards.\"\"\"\n topic = Topic(\"a/b/c\")\n assert topic.matches(\"a/b/c\")\n assert topic.matches(\"a/+/c\")\n assert topic.matches(\"+/+/+\")\n assert topic.matches(\"+/#\")\n assert topic.matches(\"#\")\n assert topic.matches(\"$share/group/a/b/c\")\n assert topic.matches(\"$share/group/a/b/+\")\n assert not topic.matches(\"abc\")\n assert not topic.matches(\"a/b\")\n assert not topic.matches(\"a/b/c/d\")\n assert not topic.matches(\"a/b/z\")\n assert not topic.matches(\"$share/a/b/c\")\n assert not topic.matches(\"$test/group/a/b/c\")\n\n\nasync def test_multiple_messages_generators() -> None:\n \"\"\"Test that multiple Client.messages() generators can be used at the same time.\"\"\"\n topic = TOPIC_HEADER + \"multiple_messages_generators\"\n\n async def handler(tg: anyio.abc.TaskGroup) -> None:\n async with client.messages() as messages:\n async for message in messages:\n assert str(message.topic) == topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handler, tg)\n tg.start_soon(handler, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_filtered_messages() -> None:\n topic_header = TOPIC_HEADER + \"filtered_messages/\"\n good_topic = topic_header + \"good\"\n bad_topic = topic_header + \"bad\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(good_topic) as messages:\n async for message in messages:\n assert message.topic == good_topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic_header + \"#\")\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(bad_topic, 2)\n await client.publish(good_topic, 2)\n\n\nasync def test_client_unfiltered_messages() -> None:\n topic_header = TOPIC_HEADER + \"unfiltered_messages/\"\n topic_filtered = topic_header + \"filtered\"\n topic_unfiltered = topic_header + \"unfiltered\"\n\n async def handle_unfiltered_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.unfiltered_messages() as messages:\n async for message in messages:\n assert message.topic == topic_unfiltered\n tg.cancel_scope.cancel()\n\n async def handle_filtered_messages() -> None:\n async with client.filtered_messages(topic_filtered) as messages:\n async for message in messages:\n assert message.topic == topic_filtered\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic_header + \"#\")\n tg.start_soon(handle_filtered_messages)\n tg.start_soon(handle_unfiltered_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic_filtered, 2)\n await client.publish(topic_unfiltered, 2)\n\n\nasync def test_client_unsubscribe() -> None:\n topic_header = TOPIC_HEADER + \"unsubscribe/\"\n topic1 = topic_header + \"1\"\n topic2 = topic_header + \"2\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.unfiltered_messages() as messages:\n is_first_message = True\n async for message in messages:\n if is_first_message:\n assert message.topic == topic1\n is_first_message = False\n else:\n assert message.topic == topic2\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic1)\n await client.subscribe(topic2)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic1, 2)\n await client.unsubscribe(topic1)\n await client.publish(topic1, 2)\n await client.publish(topic2, 2)\n\n\n@pytest.mark.parametrize(\n \"protocol, length\",\n [(ProtocolVersion.V31, 22), (ProtocolVersion.V311, 0), (ProtocolVersion.V5, 0)],\n)\nasync def test_client_id(protocol: ProtocolVersion, length: int) -> None:\n client = Client(HOSTNAME, protocol=protocol)\n assert len(client.id) == length\n\n\nasync def test_client_will() -> None:\n topic = TOPIC_HEADER + \"will\"\n event = anyio.Event()\n\n async def launch_client() -> None:\n with anyio.CancelScope(shield=True) as cs:\n async with Client(HOSTNAME) as client:\n await client.subscribe(topic)\n event.set()\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n cs.cancel()\n\n async with anyio.create_task_group() as tg:\n tg.start_soon(launch_client)\n await event.wait()\n async with Client(HOSTNAME, will=Will(topic)) as client:\n client._client._sock_close() # type: ignore[attr-defined]\n\n\nasync def test_client_tls_context() -> None:\n topic = TOPIC_HEADER + \"tls_context\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8883,\n tls_context=ssl.SSLContext(protocol=ssl.PROTOCOL_TLS),\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_tls_params() -> None:\n topic = TOPIC_HEADER + \"tls_params\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8883,\n tls_params=TLSParameters(\n ca_certs=str(Path.cwd() / \"tests\" / \"mosquitto.org.crt\")\n ),\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_username_password() -> None:\n topic = TOPIC_HEADER + \"username_password\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(HOSTNAME, username=\"\", password=\"\") as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\nasync def test_client_logger() -> None:\n logger = logging.getLogger(\"asyncio-mqtt\")\n async with Client(HOSTNAME, logger=logger) as client:\n assert logger is client._client._logger # type: ignore[attr-defined]\n\n\nasync def test_client_max_concurrent_outgoing_calls(\n monkeypatch: pytest.MonkeyPatch,\n) -> None:\n topic = TOPIC_HEADER + \"max_concurrent_outgoing_calls\"\n\n class MockPahoClient(mqtt.Client):\n def subscribe(\n self,\n topic: str\n | tuple[str, mqtt.SubscribeOptions]\n | list[tuple[str, mqtt.SubscribeOptions]]\n | list[tuple[str, int]],\n qos: int = 0,\n options: mqtt.SubscribeOptions | None = None,\n properties: mqtt.Properties | None = None,\n ) -> tuple[int, int]:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().subscribe(topic, qos, options, properties)\n\n def unsubscribe(\n self, topic: str | list[str], properties: mqtt.Properties | None = None\n ) -> tuple[int, int]:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().unsubscribe(topic, properties)\n\n def publish( # noqa: PLR0913\n self,\n topic: str,\n payload: PayloadType | None = None,\n qos: int = 0,\n retain: bool = False,\n properties: mqtt.Properties | None = None,\n ) -> mqtt.MQTTMessageInfo:\n assert client._outgoing_calls_sem is not None\n assert client._outgoing_calls_sem.locked()\n return super().publish(topic, payload, qos, retain, properties)\n\n monkeypatch.setattr(mqtt, \"Client\", MockPahoClient)\n\n async with Client(HOSTNAME, max_concurrent_outgoing_calls=1) as client:\n await client.subscribe(topic)\n await client.unsubscribe(topic)\n await client.publish(topic)\n\n\nasync def test_client_websockets() -> None:\n topic = TOPIC_HEADER + \"websockets\"\n\n async def handle_messages(tg: anyio.abc.TaskGroup) -> None:\n async with client.filtered_messages(topic) as messages:\n async for message in messages:\n assert message.topic == topic\n tg.cancel_scope.cancel()\n\n async with Client(\n HOSTNAME,\n 8080,\n transport=\"websockets\",\n websocket_path=\"/\",\n websocket_headers={\"foo\": \"bar\"},\n ) as client:\n async with anyio.create_task_group() as tg:\n await client.subscribe(topic)\n tg.start_soon(handle_messages, tg)\n await anyio.wait_all_tasks_blocked()\n await client.publish(topic)\n\n\n@pytest.mark.parametrize(\"pending_calls_threshold\", [10, 20])\nasync def test_client_pending_calls_threshold(\n pending_calls_threshold: int, caplog: pytest.LogCaptureFixture\n) -> None:\n topic = TOPIC_HEADER + \"pending_calls_threshold\"\n\n async with Client(HOSTNAME) as client:\n client.pending_calls_threshold = pending_calls_threshold\n nb_publish = client.pending_calls_threshold + 1\n\n async with anyio.create_task_group() as tg:\n for _ in range(nb_publish):\n tg.start_soon(client.publish, topic)\n\n assert caplog.record_tuples == [\n (\n \"mqtt\",\n logging.WARNING,\n f\"There are {nb_publish} pending publish calls.\",\n )\n ]\n\n\n@pytest.mark.parametrize(\"pending_calls_threshold\", [10, 20])\nasync def test_client_no_pending_calls_warnings_with_max_concurrent_outgoing_calls(\n pending_calls_threshold: int,\n caplog: pytest.LogCaptureFixture,\n) -> None:\n topic = (\n TOPIC_HEADER + \"no_pending_calls_warnings_with_max_concurrent_outgoing_calls\"\n )\n\n async with Client(HOSTNAME, max_concurrent_outgoing_calls=1) as client:\n client.pending_calls_threshold = pending_calls_threshold\n nb_publish = client.pending_calls_threshold + 1\n\n async with anyio.create_task_group() as tg:\n for _ in range(nb_publish):\n tg.start_soon(client.publish, topic)\n\n assert caplog.record_tuples == []\n", "sub_path": "tests/test_client.py", "file_name": "test_client.py", "file_ext": "py", "file_size_in_byte": 14093, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "pytest.mark", "line_number": 16, "usage_type": "attribute"}, {"api_name": "sys.platform", "line_number": 19, "usage_type": "attribute"}, {"api_name": "sys.version_info", "line_number": 19, "usage_type": "attribute"}, {"api_name": "pytest.raises", "line_number": 25, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 26, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 27, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 28, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 29, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 30, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 31, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 32, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 33, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 34, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 35, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 36, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 37, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 38, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 39, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 40, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 41, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 42, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 47, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 48, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 49, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 50, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 51, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 52, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 53, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 54, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 55, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 56, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 57, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 58, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 59, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 60, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 61, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 62, "usage_type": "call"}, {"api_name": "pytest.raises", "line_number": 63, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Wildcard", "line_number": 64, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Topic", "line_number": 69, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 89, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 95, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 96, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 100, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 109, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 115, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 116, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 119, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 129, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 140, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 141, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 145, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 155, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 166, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 167, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 171, "usage_type": "call"}, {"api_name": "asyncio_mqtt.ProtocolVersion", "line_number": 182, "usage_type": "name"}, {"api_name": "asyncio_mqtt.Client", "line_number": 183, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 178, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 178, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.ProtocolVersion.V31", "line_number": 180, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.ProtocolVersion", "line_number": 180, "usage_type": "name"}, {"api_name": "asyncio_mqtt.ProtocolVersion.V311", "line_number": 180, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.ProtocolVersion.V5", "line_number": 180, "usage_type": "attribute"}, {"api_name": "anyio.Event", "line_number": 189, "usage_type": "call"}, {"api_name": "anyio.CancelScope", "line_number": 192, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Client", "line_number": 193, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 201, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Client", "line_number": 204, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Will", "line_number": 204, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 211, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 217, "usage_type": "call"}, {"api_name": "ssl.SSLContext", "line_number": 220, "usage_type": "call"}, {"api_name": "ssl.PROTOCOL_TLS", "line_number": 220, "usage_type": "attribute"}, {"api_name": "anyio.create_task_group", "line_number": 222, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 225, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 232, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 238, "usage_type": "call"}, {"api_name": "asyncio_mqtt.TLSParameters", "line_number": 241, "usage_type": "call"}, {"api_name": "pathlib.Path.cwd", "line_number": 242, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 242, "usage_type": "name"}, {"api_name": "anyio.create_task_group", "line_number": 245, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 248, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 255, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 261, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 262, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 265, "usage_type": "call"}, {"api_name": "logging.getLogger", "line_number": 270, "usage_type": "call"}, {"api_name": "asyncio_mqtt.Client", "line_number": 271, "usage_type": "call"}, {"api_name": "pytest.MonkeyPatch", "line_number": 276, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client.Client", "line_number": 280, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 280, "usage_type": "name"}, {"api_name": "paho.mqtt.client.SubscribeOptions", "line_number": 284, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 284, "usage_type": "name"}, {"api_name": "paho.mqtt.client.SubscribeOptions", "line_number": 285, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 285, "usage_type": "name"}, {"api_name": "paho.mqtt.client.SubscribeOptions", "line_number": 288, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 288, "usage_type": "name"}, {"api_name": "paho.mqtt.client.Properties", "line_number": 289, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 289, "usage_type": "name"}, {"api_name": "paho.mqtt.client.Properties", "line_number": 296, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 296, "usage_type": "name"}, {"api_name": "asyncio_mqtt.types.PayloadType", "line_number": 305, "usage_type": "name"}, {"api_name": "paho.mqtt.client.Properties", "line_number": 308, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 308, "usage_type": "name"}, {"api_name": "paho.mqtt.client.MQTTMessageInfo", "line_number": 309, "usage_type": "attribute"}, {"api_name": "paho.mqtt.client", "line_number": 309, "usage_type": "name"}, {"api_name": "paho.mqtt.client", "line_number": 314, "usage_type": "argument"}, {"api_name": "asyncio_mqtt.Client", "line_number": 316, "usage_type": "call"}, {"api_name": "anyio.abc", "line_number": 325, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 331, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 338, "usage_type": "call"}, {"api_name": "anyio.wait_all_tasks_blocked", "line_number": 341, "usage_type": "call"}, {"api_name": "pytest.LogCaptureFixture", "line_number": 347, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 351, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 355, "usage_type": "call"}, {"api_name": "logging.WARNING", "line_number": 362, "usage_type": "attribute"}, {"api_name": "pytest.mark.parametrize", "line_number": 345, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 345, "usage_type": "attribute"}, {"api_name": "pytest.LogCaptureFixture", "line_number": 371, "usage_type": "attribute"}, {"api_name": "asyncio_mqtt.Client", "line_number": 377, "usage_type": "call"}, {"api_name": "anyio.create_task_group", "line_number": 381, "usage_type": "call"}, {"api_name": "pytest.mark.parametrize", "line_number": 368, "usage_type": "call"}, {"api_name": "pytest.mark", "line_number": 368, "usage_type": "attribute"}]}
+{"seq_id": "106499390", "text": "import unicodedata\nimport string\nimport re\nimport random\nimport time\nimport datetime\nimport math\nimport socket\nhostname = socket.gethostname() # 用来得到主机的名字, 但是这是为了什么目的呢\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence#, masked_cross_entropy\nfrom masked_cross_entropy import * \n# 其实使用 packedSequence 直接规避掉这个或许会更好, 先 pack 通过 RNN 然后再次 pad\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nget_ipython().magic('matplotlib inline')\n\n\nUSE_CUDA = torch.cuda.is_available() #True\n\n\n\nPAD_token = 0\nSOS_token = 1\nEOS_token = 2\n\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.trimmed = False\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"PAD\", 1: \"SOS\", 2: \"EOS\"}\n self.n_words = 3 # Count default tokens\n\n def index_words(self, sentence):\n for word in sentence.split(' '):\n self.index_word(word)\n\n def index_word(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.word2count[word] = 1\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\n # Remove words below a certain count threshold\n def trim(self, min_count):\n if self.trimmed: return\n self.trimmed = True\n \n keep_words = []\n \n for k, v in self.word2count.items():\n if v >= min_count:\n keep_words.append(k)\n\n print('keep_words %s / %s = %.4f' % (\n len(keep_words), len(self.word2index), len(keep_words) / len(self.word2index)\n ))\n\n # Reinitialize dictionaries\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"PAD\", 1: \"SOS\", 2: \"EOS\"}\n self.n_words = 3 # Count default tokens\n\n for word in keep_words:\n self.index_word(word)\n\n# Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427\ndef unicode_to_ascii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n\n# Lowercase, trim, and remove non-letter characters\ndef normalize_string(s):\n s = unicode_to_ascii(s.lower().strip())\n s = re.sub(r\"([,.!?])\", r\" \\1 \", s)\n s = re.sub(r\"[^a-zA-Z,.!?]+\", r\" \", s)\n s = re.sub(r\"\\s+\", r\" \", s).strip()\n return s\n\n\ndef read_langs(lang1, lang2, reverse=False):\n print(\"Reading lines...\")\n\n # Read the file and split into lines\n# filename = '../data/%s-%s.txt' % (lang1, lang2)\n filename = '../data/%s-%s.txt' % (lang1, lang2)\n lines = open(filename).read().strip().split('\\n')\n\n # Split every line into pairs and normalize\n pairs = [[normalize_string(s) for s in l.split('\\t')] for l in lines]\n\n # Reverse pairs, make Lang instances\n if reverse:\n pairs = [list(reversed(p)) for p in pairs]\n input_lang = Lang(lang2)\n output_lang = Lang(lang1)\n else:\n input_lang = Lang(lang1)\n output_lang = Lang(lang2)\n\n return input_lang, output_lang, pairs\n\n\n# In[6]:\n\nMIN_LENGTH = 3\nMAX_LENGTH = 25\n\ndef filter_pairs(pairs):\n filtered_pairs = []\n for pair in pairs:\n if len(pair[0]) >= MIN_LENGTH and len(pair[0]) <= MAX_LENGTH and len(pair[1]) >= MIN_LENGTH and len(pair[1]) <= MAX_LENGTH:\n filtered_pairs.append(pair)\n return filtered_pairs\n\ndef prepare_data(lang1_name, lang2_name, reverse=False):\n input_lang, output_lang, pairs = read_langs(lang1_name, lang2_name, reverse)\n print(\"Read %d sentence pairs\" % len(pairs))\n \n pairs = filter_pairs(pairs)\n print(\"Filtered to %d pairs\" % len(pairs))\n \n print(\"Indexing words...\")\n for pair in pairs:\n input_lang.index_words(pair[0])\n output_lang.index_words(pair[1])\n \n print('Indexed %d words in input language, %d words in output' % (input_lang.n_words, output_lang.n_words))\n return input_lang, output_lang, pairs\n\ninput_lang, output_lang, pairs = prepare_data('eng', 'fra', True)\n\n\n# In[8]:\n\nprint(input_lang.word2count['the'])\nprint(input_lang.trimmed) # 并没有使用 trim 所以应该没有什么问题\n\nimport copy\ninput_lang2 = copy.deepcopy(input_lang)\ninput_lang2.trim(20)\nprint(input_lang.word2count['the'])\nprint(input_lang2.word2count['the']) # 这么 trim 过了一次之后, word2count 就失去了意义。\n\n\nMIN_COUNT = 5\n\ninput_lang.trim(MIN_COUNT)\noutput_lang.trim(MIN_COUNT)\n\n\nkeep_pairs = []\n\nfor pair in pairs:\n input_sentence = pair[0]\n output_sentence = pair[1]\n keep_input = True\n keep_output = True\n \n for word in input_sentence.split(' '):\n if word not in input_lang.word2index:\n keep_input = False\n break\n\n for word in output_sentence.split(' '):\n if word not in output_lang.word2index:\n keep_output = False\n break\n\n # Remove if pair doesn't match input and output conditions\n if keep_input and keep_output:\n keep_pairs.append(pair)\n\nprint(\"Trimmed from %d pairs to %d, %.4f of total\" % (len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))\npairs = keep_pairs\n\n\n# Return a list of indexes, one for each word in the sentence, plus EOS\ndef indexes_from_sentence(lang, sentence):\n return [lang.word2index[word] for word in sentence.split(' ')] + [EOS_token]\n\n\n# Pad a with the PAD symbol\ndef pad_seq(seq, max_length):\n seq += [PAD_token for i in range(max_length - len(seq))]\n return seq\n\ndef random_batch(batch_size):\n input_seqs = []\n target_seqs = []\n\n # Choose random pairs\n for i in range(batch_size):\n pair = random.choice(pairs)\n input_seqs.append(indexes_from_sentence(input_lang, pair[0]))\n target_seqs.append(indexes_from_sentence(output_lang, pair[1]))\n\n # Zip into pairs, sort by length (descending), unzip\n seq_pairs = sorted(zip(input_seqs, target_seqs), key=lambda p: len(p[0]), reverse=True) \n # 好简洁 返回结果是 list(tuple)\n input_seqs, target_seqs = zip(*seq_pairs) # unzip 过程如此\n \n # For input and target sequences, get array of lengths and pad with 0s to max length\n input_lengths = [len(s) for s in input_seqs]\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # Turn padded arrays into (batch_size x max_len) tensors, transpose into (max_len x batch_size)\n input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n \n if USE_CUDA:\n input_var = input_var.cuda()\n target_var = target_var.cuda()\n \n return input_var, input_lengths, target_var, target_lengths\n\n\nrandom_batch(2)\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, n_layers=1, dropout=0.1):\n super(EncoderRNN, self).__init__()\n \n self.input_size = input_size\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.dropout = dropout\n \n self.embedding = nn.Embedding(input_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=self.dropout, bidirectional=True)\n # 注意, 默认是双向 RNN, 所以output的时候是形状是 (T,B,DH) 或者 (S,DH), hidden 是 (LD, B, H)\n \n def forward(self, input_seqs, input_lengths, hidden=None):\n # Note: we run this all at once (over multiple batches of multiple sequences)\n embedded = self.embedding(input_seqs) # (T, B, H)\n packed = torch.nn.utils.rnn.pack_padded_sequence(embedded, input_lengths) # (S, H)\n outputs, hidden = self.gru(packed, hidden) # (S, DH) , (LD, B, H)\n outputs, output_lengths = torch.nn.utils.rnn.pad_packed_sequence(outputs) # unpack (back to padded)\n outputs = outputs[:, :, :self.hidden_size] + outputs[:, : ,self.hidden_size:] # Sum bidirectional outputs\n return outputs, hidden #(T,B,H), (LD,B,H)\n\n\nclass Attn(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn, self).__init__()\n \n self.method = method\n self.hidden_size = hidden_size\n \n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n\n def forward(self, hidden, encoder_outputs): # hidden(H,B), encoder_outputs(T,B,H)\n max_len = encoder_outputs.size(0)\n this_batch_size = encoder_outputs.size(1)\n\n # Create variable to store attention energies\n attn_energies = Variable(torch.zeros(this_batch_size, max_len)) # B x S\n\n if USE_CUDA:\n attn_energies = attn_energies.cuda()\n\n # For each batch of encoder outputs\n for b in range(this_batch_size):\n # Calculate energy for each encoder output\n for i in range(max_len):\n attn_energies[b, i] = self.score(hidden[:, b], encoder_outputs[i, b].unsqueeze(0))\n\n # Normalize energies to weights in range 0 to 1, resize to 1 x B x S\n return F.softmax(attn_energies, dim=-1).unsqueeze(1)\n \n def score(self, hidden, encoder_output):\n \n if self.method == 'dot':\n energy = hidden.dot(encoder_output)\n return energy\n \n elif self.method == 'general':\n energy = self.attn(encoder_output)\n energy = hidden.dot(energy)\n return energy\n \n elif self.method == 'concat':\n energy = self.attn(torch.cat((hidden, encoder_output), 1))\n energy = self.v.dot(energy)\n return energy\n \n# A different implementation of the global attention which avoids for-loop\nclass Attn2(nn.Module):\n def __init__(self, method, hidden_size):\n super(Attn2, self).__init__()\n \n self.method = method\n self.hidden_size = hidden_size\n \n if self.method == 'general':\n self.attn = nn.Linear(self.hidden_size, hidden_size)\n\n elif self.method == 'concat':\n self.attn = nn.Linear(self.hidden_size * 2, hidden_size)\n self.v = nn.Parameter(torch.FloatTensor(1, hidden_size))\n \n def forward(self, hidden, encoder_outputs):\n # hidden (LD, B, H), encoder_outputs (T, B, H)\n if self.method == 'general':\n attn_energies = torch.bmm(hidden.transpose(0,1), \n at.attn(encoder_outputs).transpose(0,1).transpose(1,2))\n if self.method == 'dot':\n attn_energies = torch.bmm(hidden.transpose(0,1), \n encoder_outputs.transpose(0,1).transpose(1,2))\n if self.mehod == 'concat':\n attn_energies = torch.stack([v]* encoder_outputs.size(1)).bmm(\n at2.attn(torch.cat((torch.stack([hidden.transpose(0,1)] * encoder_outputs.size(0)), \n encoder_outputs), dim=2)).transpose(0,1).transpose(1,2))\n F.softmax(attn_energies, dim=-1)\n\n\n# This is a buggy implementation it doesnot work at all\nclass BahdanauAttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, n_layers=1, dropout_p=0.1):\n super(BahdanauAttnDecoderRNN, self).__init__()\n \n # Define parameters\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout_p = dropout_p\n self.max_length = MAX_LENGTH\n \n # Define layers\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.dropout = nn.Dropout(dropout_p)\n self.attn = Attn('concat', hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout_p)\n self.out = nn.Linear(hidden_size, output_size)\n \n def forward(self, word_input, last_hidden, encoder_outputs):\n # Note: we run this one step at a time\n # TODO: FIX BATCHING\n \n # Get the embedding of the current input word (last output word)\n word_embedded = self.embedding(word_input).view(1, 1, -1) # S=1 x B x N\n word_embedded = self.dropout(word_embedded)\n \n # Calculate attention weights and apply to encoder outputs\n attn_weights = self.attn(last_hidden[-1], encoder_outputs)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x 1 x N\n context = context.transpose(0, 1) # 1 x B x N\n \n # Combine embedded input word and attended context, run through RNN\n rnn_input = torch.cat((word_embedded, context), 2)\n output, hidden = self.gru(rnn_input, last_hidden)\n \n # Final output layer\n output = output.squeeze(0) # B x N\n output = F.log_softmax(self.out(torch.cat((output, context), 1)))\n \n # Return final output, hidden state, and attention weights (for visualization)\n return output, hidden, attn_weights\n\n\nclass LuongAttnDecoderRNN(nn.Module):\n def __init__(self, attn_model, hidden_size, output_size, n_layers=1, dropout=0.1):\n super(LuongAttnDecoderRNN, self).__init__()\n\n # Keep for reference\n self.attn_model = attn_model\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout = dropout\n\n # Define layers\n self.embedding = nn.Embedding(output_size, hidden_size)\n self.embedding_dropout = nn.Dropout(dropout)\n self.gru = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout)\n self.concat = nn.Linear(hidden_size * 2, hidden_size)\n self.out = nn.Linear(hidden_size, output_size)\n \n # Choose attention model\n if attn_model != 'none':\n self.attn = Attn(attn_model, hidden_size)\n\n def forward(self, input_seq, last_hidden, encoder_outputs):\n # Note: we run this one step at a time\n\n # Get the embedding of the current input word (last output word)\n batch_size = input_seq.size(0) # 就是得到了 batch_size, 形状可能是 (B,1) 或者 (B)\n embedded = self.embedding(input_seq)\n embedded = self.embedding_dropout(embedded)\n embedded = embedded.view(1, batch_size, self.hidden_size) # S=1 x B x N #embedded(1,B,H)\n\n # Get current hidden state from input word and last hidden state\n rnn_output, hidden = self.gru(embedded, last_hidden) # (1,B,DH), (LD,B,H) #(1,B,H), (L,B,H)\n\n # Calculate attention from current RNN state and all encoder outputs;\n # apply to encoder outputs to get weighted average\n attn_weights = self.attn(rnn_output, encoder_outputs) #(B,1,T)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x S=1 x N # (B, 1, H)\n\n # Attentional vector using the RNN hidden state and context vector\n # concatenated together (Luong eq. 5)\n rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N #(B,H)\n context = context.squeeze(1) # B x S=1 x N -> B x N #(B,H)\n concat_input = torch.cat((rnn_output, context), 1) #(B,2H)\n concat_output = F.tanh(self.concat(concat_input)) #(B,H)\n\n # Finally predict next token (Luong eq. 6, without softmax)\n output = self.out(concat_output) #(B,O), not logsoftmaxed\n\n # Return final output, hidden state, and attention weights (for visualization)\n return output, hidden, attn_weights # (B,O), (L,B,H), (B,1,T)\n\n\nsmall_batch_size = 3\ninput_batches, input_lengths, target_batches, target_lengths = random_batch(small_batch_size)\n\nprint('input_batches', input_batches.size()) # (max_len x batch_size)\nprint('target_batches', target_batches.size()) # (max_len x batch_size)\n\n\n\n\nsmall_hidden_size = 8\nsmall_n_layers = 2\n\nencoder_test = EncoderRNN(input_lang.n_words, small_hidden_size, small_n_layers)\ndecoder_test = LuongAttnDecoderRNN('general', small_hidden_size, output_lang.n_words, small_n_layers)\n# decoder_test = BahdanauAttnDecoderRNN(small_hidden_size, output_lang.n_words, small_n_layers)\n\nif USE_CUDA:\n encoder_test.cuda()\n decoder_test.cuda()\n\n\n\nencoder_outputs, encoder_hidden = encoder_test(input_batches, input_lengths, None)\n\nprint('encoder_outputs', encoder_outputs.size()) # max_len x batch_size x hidden_size #(T,B,DH)\nprint('encoder_hidden', encoder_hidden.size()) # n_layers * 2 x batch_size x hidden_size #(LD,B,H)\n\n\n\nmax_target_length = max(target_lengths)\n\n# Prepare decoder input and outputs\ndecoder_input = Variable(torch.LongTensor([SOS_token] * small_batch_size)) #(B)\ndecoder_hidden = encoder_hidden[:decoder_test.n_layers] # Use last (forward) hidden state from encoder \n# 所以从上面可以直到事实上 LD 维度的组合方式是先Layer后Direction, forward在前面, backward 在后面 (L,B,H)\nall_decoder_outputs = Variable(torch.zeros(max_target_length, small_batch_size, decoder_test.output_size))\n#(T_o, B,O)\n\nif USE_CUDA:\n all_decoder_outputs = all_decoder_outputs.cuda()\n decoder_input = decoder_input.cuda()\n\n# Run through decoder one time step at a time\nfor t in range(max_target_length):\n decoder_output, decoder_hidden, decoder_attn = decoder_test(\n decoder_input, decoder_hidden, encoder_outputs\n ) #(B,O), (L,B,H), (B,1,H)\n all_decoder_outputs[t] = decoder_output # Store this step's outputs\n decoder_input = target_batches[t] # Next input is current target (B) teacher forcing\n\n# Test masked cross entropy loss\nloss = masked_cross_entropy(\n all_decoder_outputs.transpose(0, 1).contiguous(), #(B, T_o, O)\n target_batches.transpose(0, 1).contiguous(), #(B, T_o)\n target_lengths #(B)\n)\nprint('loss', loss.data[0])\n\n\ndef train(input_batches, input_lengths, target_batches, target_lengths, encoder, \n decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n \n # Zero gradients of both optimizers\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n loss = 0 # Added onto for each word\n\n # Run words through encoder\n encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)\n \n # Prepare input and output variables\n decoder_input = Variable(torch.LongTensor([SOS_token] * batch_size))\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n\n max_target_length = max(target_lengths)\n all_decoder_outputs = Variable(torch.zeros(max_target_length, batch_size, decoder.output_size))\n\n # Move new Variables to CUDA\n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n all_decoder_outputs = all_decoder_outputs.cuda()\n\n # Run through decoder one time step at a time\n for t in range(max_target_length):\n decoder_output, decoder_hidden, decoder_attn = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n\n all_decoder_outputs[t] = decoder_output\n decoder_input = target_batches[t] # Next input is current target\n\n # Loss calculation and backpropagation\n loss = masked_cross_entropy(\n all_decoder_outputs.transpose(0, 1).contiguous(), # -> batch x seq\n target_batches.transpose(0, 1).contiguous(), # -> batch x seq\n target_lengths\n )\n loss.backward()\n \n # Clip gradient norms\n ec = torch.nn.utils.clip_grad_norm(encoder.parameters(), clip)\n dc = torch.nn.utils.clip_grad_norm(decoder.parameters(), clip)\n\n # Update parameters with optimizers\n encoder_optimizer.step()\n decoder_optimizer.step()\n \n return loss.data[0], ec, dc\n\n\n\n# Configure models\nattn_model = 'dot'\nhidden_size = 500\nn_layers = 2\ndropout = 0.1\nbatch_size = 100\nbatch_size = 50\n\n# Configure training/optimization\nclip = 50.0\nteacher_forcing_ratio = 0.5\nlearning_rate = 0.0001\ndecoder_learning_ratio = 5.0\nn_epochs = 50000\nepoch = 0\nplot_every = 20\nprint_every = 100\nevaluate_every = 1000\n\n# Initialize models\nencoder = EncoderRNN(input_lang.n_words, hidden_size, n_layers, dropout=dropout)\ndecoder = LuongAttnDecoderRNN(attn_model, hidden_size, output_lang.n_words, n_layers, dropout=dropout)\n\n# Initialize optimizers and criterion\nencoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)\ndecoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate * decoder_learning_ratio)\ncriterion = nn.CrossEntropyLoss()\n\n# Move models to GPU\nif USE_CUDA:\n encoder.cuda()\n decoder.cuda()\n\nimport sconce\njob = sconce.Job('seq2seq-translate', {\n 'attn_model': attn_model,\n 'n_layers': n_layers,\n 'dropout': dropout,\n 'hidden_size': hidden_size,\n 'learning_rate': learning_rate,\n 'clip': clip,\n 'teacher_forcing_ratio': teacher_forcing_ratio,\n 'decoder_learning_ratio': decoder_learning_ratio,\n})\njob.plot_every = plot_every\njob.log_every = print_every\n\n# Keep track of time elapsed and running averages\nstart = time.time()\nplot_losses = []\nprint_loss_total = 0 # Reset every print_every\nplot_loss_total = 0 # Reset every plot_every\n\n\n\ndef as_minutes(s):\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\ndef time_since(since, percent):\n now = time.time()\n s = now - since\n es = s / (percent)\n rs = es - s\n return '%s (- %s)' % (as_minutes(s), as_minutes(rs))\n\n\ndef evaluate(input_seq, max_length=MAX_LENGTH):\n input_lengths = [len(input_seq)]\n input_seqs = [indexes_from_sentence(input_lang, input_seq)]\n input_batches = Variable(torch.LongTensor(input_seqs), volatile=True).transpose(0, 1)\n \n if USE_CUDA:\n input_batches = input_batches.cuda()\n \n # Set to not-training mode to disable dropout\n encoder.train(False)\n decoder.train(False)\n \n # Run through encoder\n encoder_outputs, encoder_hidden = encoder(input_batches, input_lengths, None)\n\n # Create starting vectors for decoder\n decoder_input = Variable(torch.LongTensor([SOS_token]), volatile=True) # SOS\n decoder_hidden = encoder_hidden[:decoder.n_layers] # Use last (forward) hidden state from encoder\n \n if USE_CUDA:\n decoder_input = decoder_input.cuda()\n\n # Store output words and attention states\n decoded_words = []\n decoder_attentions = torch.zeros(max_length + 1, max_length + 1)\n \n # Run through decoder\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs\n )\n decoder_attentions[di,:decoder_attention.size(2)] += decoder_attention.squeeze(0).squeeze(0).cpu().data\n\n # Choose top word from output\n topv, topi = decoder_output.data.topk(1)\n ni = topi[0][0]\n if ni == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[ni])\n \n # Next input is chosen word\n decoder_input = Variable(torch.LongTensor([ni]))\n if USE_CUDA: decoder_input = decoder_input.cuda()\n\n # Set back to training mode\n encoder.train(True)\n decoder.train(True)\n \n return decoded_words, decoder_attentions[:di+1, :len(encoder_outputs)]\n\n\n\ndef evaluate_randomly():\n [input_sentence, target_sentence] = random.choice(pairs)\n evaluate_and_show_attention(input_sentence, target_sentence)\n\n\nimport io\nimport torchvision\nfrom PIL import Image\nimport visdom\nvis = visdom.Visdom()\n\ndef show_plot_visdom():\n buf = io.BytesIO()\n plt.savefig(buf)\n buf.seek(0)\n attn_win = 'attention (%s)' % hostname\n vis.image(torchvision.transforms.ToTensor()(Image.open(buf)), win=attn_win, opts={'title': attn_win})\n\n\n\ndef show_attention(input_sentence, output_words, attentions):\n # Set up figure with colorbar\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(attentions.numpy(), cmap='bone')\n fig.colorbar(cax)\n\n # Set up axes\n ax.set_xticklabels([''] + input_sentence.split(' ') + [''], rotation=90)\n ax.set_yticklabels([''] + output_words)\n\n # Show label at every tick\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n show_plot_visdom()\n plt.show()\n plt.close()\n\n\ndef evaluate_and_show_attention(input_sentence, target_sentence=None):\n output_words, attentions = evaluate(input_sentence)\n output_sentence = ' '.join(output_words)\n print('>', input_sentence)\n if target_sentence is not None:\n print('=', target_sentence)\n print('<', output_sentence)\n \n show_attention(input_sentence, output_words, attentions)\n \n # Show input, target, output text in visdom\n win = 'evaluted (%s)' % hostname\n text = '> %s
= %s
< %s
' % (input_sentence, target_sentence, output_sentence)\n vis.text(text, win=win, opts={'title': win})\n\n\n\n# Begin!\necs = []\ndcs = []\neca = 0\ndca = 0\n\nwhile epoch < n_epochs:\n epoch += 1\n \n # Get training data for this cycle\n input_batches, input_lengths, target_batches, target_lengths = random_batch(batch_size)\n\n # Run the train function\n loss, ec, dc = train(\n input_batches, input_lengths, target_batches, target_lengths,\n encoder, decoder,\n encoder_optimizer, decoder_optimizer, criterion\n )\n\n # Keep track of loss\n print_loss_total += loss\n plot_loss_total += loss\n eca += ec\n dca += dc\n \n job.record(epoch, loss)\n\n if epoch % print_every == 0:\n print_loss_avg = print_loss_total / print_every\n print_loss_total = 0\n print_summary = '%s (%d %d%%) %.4f' % (time_since(start, epoch / n_epochs), epoch, epoch / n_epochs * 100, print_loss_avg)\n print(print_summary)\n \n if epoch % evaluate_every == 0:\n evaluate_randomly()\n\n if epoch % plot_every == 0:\n plot_loss_avg = plot_loss_total / plot_every\n plot_losses.append(plot_loss_avg)\n plot_loss_total = 0\n \n # TODO: Running average helper\n ecs.append(eca / plot_every)\n dcs.append(dca / plot_every)\n ecs_win = 'encoder grad (%s)' % hostname\n dcs_win = 'decoder grad (%s)' % hostname\n vis.line(np.array(ecs), win=ecs_win, opts={'title': ecs_win})\n vis.line(np.array(dcs), win=dcs_win, opts={'title': dcs_win})\n eca = 0\n dca = 0\n\n\ndef show_plot(points):\n plt.figure()\n fig, ax = plt.subplots()\n loc = ticker.MultipleLocator(base=0.2) # put ticks at regular intervals\n ax.yaxis.set_major_locator(loc)\n plt.plot(points)\n\nshow_plot(plot_losses)\n\n\n# In[ ]:\n\noutput_words, attentions = evaluate(\"je suis trop froid .\")\nplt.matshow(attentions.numpy())\nshow_plot_visdom()\n\nevaluate_and_show_attention(\"elle a cinq ans de moins que moi .\")\n\n\nevaluate_and_show_attention(\"elle est trop petit .\")\n\n\nevaluate_and_show_attention(\"je ne crains pas de mourir .\")\n\nevaluate_and_show_attention(\"c est un jeune directeur plein de talent .\")\n\nevaluate_and_show_attention(\"est le chien vert aujourd hui ?\")\n\nevaluate_and_show_attention(\"le chat me parle .\")\n\nevaluate_and_show_attention(\"des centaines de personnes furent arretees ici .\")\n\nevaluate_and_show_attention(\"des centaines de chiens furent arretees ici .\")\n\nevaluate_and_show_attention(\"ce fromage est prepare a partir de lait de chevre .\")\n\n\n\n\n", "sub_path": "seq2seq-translation/seq2seq-translation-batched.py", "file_name": "seq2seq-translation-batched.py", "file_ext": "py", "file_size_in_byte": 27724, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "socket.gethostname", "line_number": 9, "usage_type": "call"}, {"api_name": "torch.cuda.is_available", "line_number": 26, "usage_type": "call"}, {"api_name": "torch.cuda", "line_number": 26, "usage_type": "attribute"}, {"api_name": "unicodedata.normalize", "line_number": 83, "usage_type": "call"}, {"api_name": "unicodedata.category", "line_number": 84, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 90, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 91, "usage_type": "call"}, {"api_name": "re.sub", "line_number": 92, "usage_type": "call"}, {"api_name": "copy.deepcopy", "line_number": 155, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 209, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 225, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 226, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 238, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 238, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 247, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 247, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 248, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 248, "usage_type": "name"}, {"api_name": "torch.nn.utils.rnn.pack_padded_sequence", "line_number": 254, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 254, "usage_type": "attribute"}, {"api_name": "torch.nn.utils.rnn.pad_packed_sequence", "line_number": 256, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 256, "usage_type": "attribute"}, {"api_name": "torch.nn.Module", "line_number": 261, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 261, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 269, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 269, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 272, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 272, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 273, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 273, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 273, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 280, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 280, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 292, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 292, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 306, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 311, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 311, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 319, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 319, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 322, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 322, "usage_type": "name"}, {"api_name": "torch.nn.Parameter", "line_number": 323, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 323, "usage_type": "name"}, {"api_name": "torch.FloatTensor", "line_number": 323, "usage_type": "call"}, {"api_name": "torch.bmm", "line_number": 328, "usage_type": "call"}, {"api_name": "torch.bmm", "line_number": 331, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 334, "usage_type": "call"}, {"api_name": "torch.cat", "line_number": 335, "usage_type": "call"}, {"api_name": "torch.stack", "line_number": 335, "usage_type": "call"}, {"api_name": "torch.nn.functional.softmax", "line_number": 337, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 337, "usage_type": "name"}, {"api_name": "torch.nn.Module", "line_number": 341, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 341, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 353, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 353, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 354, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 354, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 356, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 356, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 357, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 357, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 373, "usage_type": "call"}, {"api_name": "torch.nn.functional.log_softmax", "line_number": 378, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 378, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 378, "usage_type": "call"}, {"api_name": "torch.nn.Module", "line_number": 384, "usage_type": "attribute"}, {"api_name": "torch.nn", "line_number": 384, "usage_type": "name"}, {"api_name": "torch.nn.Embedding", "line_number": 396, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 396, "usage_type": "name"}, {"api_name": "torch.nn.Dropout", "line_number": 397, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 397, "usage_type": "name"}, {"api_name": "torch.nn.GRU", "line_number": 398, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 398, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 399, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 399, "usage_type": "name"}, {"api_name": "torch.nn.Linear", "line_number": 400, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 400, "usage_type": "name"}, {"api_name": "torch.cat", "line_number": 427, "usage_type": "call"}, {"api_name": "torch.nn.functional.tanh", "line_number": 428, "usage_type": "call"}, {"api_name": "torch.nn.functional", "line_number": 428, "usage_type": "name"}, {"api_name": "torch.autograd.Variable", "line_number": 469, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 469, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 472, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 472, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 508, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 508, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 512, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 512, "usage_type": "call"}, {"api_name": "torch.nn.utils.clip_grad_norm", "line_number": 537, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 537, "usage_type": "attribute"}, {"api_name": "torch.nn.utils.clip_grad_norm", "line_number": 538, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 538, "usage_type": "attribute"}, {"api_name": "torch.optim.Adam", "line_number": 572, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 572, "usage_type": "name"}, {"api_name": "torch.optim.Adam", "line_number": 573, "usage_type": "call"}, {"api_name": "torch.optim", "line_number": 573, "usage_type": "name"}, {"api_name": "torch.nn.CrossEntropyLoss", "line_number": 574, "usage_type": "call"}, {"api_name": "torch.nn", "line_number": 574, "usage_type": "name"}, {"api_name": "sconce.Job", "line_number": 582, "usage_type": "call"}, {"api_name": "time.time", "line_number": 596, "usage_type": "call"}, {"api_name": "math.floor", "line_number": 604, "usage_type": "call"}, {"api_name": "time.time", "line_number": 609, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 619, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 619, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 632, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 632, "usage_type": "call"}, {"api_name": "torch.zeros", "line_number": 640, "usage_type": "call"}, {"api_name": "torch.autograd.Variable", "line_number": 659, "usage_type": "call"}, {"api_name": "torch.LongTensor", "line_number": 659, "usage_type": "call"}, {"api_name": "random.choice", "line_number": 671, "usage_type": "call"}, {"api_name": "visdom.Visdom", "line_number": 679, "usage_type": "call"}, {"api_name": "io.BytesIO", "line_number": 682, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.savefig", "line_number": 683, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 683, "usage_type": "name"}, {"api_name": "torchvision.transforms.ToTensor", "line_number": 686, "usage_type": "call"}, {"api_name": "torchvision.transforms", "line_number": 686, "usage_type": "attribute"}, {"api_name": "PIL.Image.open", "line_number": 686, "usage_type": "call"}, {"api_name": "PIL.Image", "line_number": 686, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 692, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 692, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 702, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 702, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 703, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 703, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 706, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 706, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.close", "line_number": 707, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 707, "usage_type": "name"}, {"api_name": "numpy.array", "line_number": 773, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 774, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.figure", "line_number": 780, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 780, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 781, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 781, "usage_type": "name"}, {"api_name": "matplotlib.ticker.MultipleLocator", "line_number": 782, "usage_type": "call"}, {"api_name": "matplotlib.ticker", "line_number": 782, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.plot", "line_number": 784, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 784, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.matshow", "line_number": 792, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 792, "usage_type": "name"}]}
+{"seq_id": "157931997", "text": "#!/usr/bin/env python3\n\"\"\"\nPrediction for HHMM\nMost recent version as of 07/28/2019\n\"\"\"\n\nimport argparse\nimport os\n# import logging\nimport sys\n### Libraries ###\nimport pickle\nimport time\nimport numpy as np\nfrom matfuncs import expm\nfrom scipy import stats\nfrom scipy import special\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\n\ndef Initialization():\n global ages_test, testTypes_test, observations_test, treatment_indx_test, censor_ages_test, death_state_test, ind, nTests, inv, n_inv, MPmatrixs, nPatients_test\n global out_path, out_folder, max_steps_em, max_steps_optim, model, autograd_optim, p, args, n_test\n global currPars, curr_parameter_vector\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--name\", help=\"name of the experiment\", default=\"prediction_hierarchical\")\n parser.add_argument(\"--min_age\", help=\"minimum age\", type=int, default=16)\n parser.add_argument(\"--dataset\", help=\"data specification: data_1000 are available\", default=\"data_1000\")\n parser.add_argument(\"--age_inv\", help=\"age interval sepecification\", default=\"inv4\")\n parser.add_argument(\"--model\", help=\"discrete or continuous model\", default=\"continuous\")\n parser.add_argument(\"--test\", help=\"boolean indicator for testing\", action='store_true')\n parser.add_argument(\"--Z_prior\", help=\"prior probability of Model 1\", type=np.float32, default=0.5)\n\n args = parser.parse_args()\n\n try:\n os.chdir(os.path.dirname(__file__))\n except:\n pass\n\n if args.test:\n out_folder = args.name + '_' + str(\n args.min_age) + '_' + args.dataset + '_' + args.age_inv + '_' + args.model + '_test'\n else:\n out_folder = args.name + '_' + str(args.min_age) + '_' + args.dataset + '_' + args.age_inv + '_' + args.model\n\n min_age = args.min_age\n do_truncate_ages = True if min_age > 16 else False\n dataset = args.dataset\n inv_indx = args.age_inv\n model = args.model\n p = args.Z_prior\n\n ##########################\n ##### Initialization #####\n ##########################\n nStates_0 = 2\n nStates_1 = 4\n nTests = 3\n\n ind = [\"Alpha\", \"Eta\", \"W\",\n \"C\"] # ind specifies which parameters need to be optimized:x [\"Alpha\", \"W\", \"Gamma\", \"Zeta\", \"Eta\", \"A\", \"C\"]\n inv_list = {\"inv14\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 53, 57, 60, 200],\n \"inv13\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 55, 60, 200],\n \"inv12\": [20, 23, 27, 30, 33, 37, 40, 43, 47, 50, 60, 200],\n \"inv11\": [20, 23, 27, 30, 33, 37, 40, 45, 50, 60, 200],\n \"inv10\": [19, 22, 25, 30, 35, 40, 45, 50, 55, 200], # expert advice\n \"inv9\": [23, 25, 30, 35, 40, 45, 50, 60, 200], # expert advice\n \"inv8\": [20, 25, 30, 35, 40, 50, 60, 200], # best AIC and Likelihood with 3000 procs.\n \"inv7\": [20, 25, 30, 40, 50, 60, 200], # best AIC with 300 procs\n \"inv6\": [23, 30, 40, 50, 60, 200],\n \"inv5\": [23, 35, 45, 60, 200],\n \"inv4\": [23, 30, 60, 200],\n \"inv3\": [29, 69, 200], # close second AIC with 300 procs\n \"inv2\": [23, 200],\n \"inv1\": [200]}\n inv = inv_list[inv_indx]\n n_inv = len(inv)\n\n if dataset == 'data_1000':\n data_location = '../../data/data_1000/'\n else:\n print(\"dataset {} is not available\".format(dataset))\n\n # load data\n testTypes = pickle.load(open(data_location + \"mcmcPatientTestTypes\", 'rb'), encoding=\"bytes\")\n observations = pickle.load(open(data_location + \"mcmcPatientObservations\", 'rb'), encoding=\"bytes\")\n ages = pickle.load(open(data_location + \"mcmcPatientAges\", 'rb'), encoding=\"bytes\")\n treatment_indx = pickle.load(open(data_location + \"mcmcPatientTreatmentIndx\", 'rb'), encoding=\"bytes\")\n censor_ages = pickle.load(open(data_location + \"mcmcPatientCensorDates\", 'rb'), encoding=\"bytes\")\n death_states = pickle.load(open(data_location + \"mcmcPatientDeathStates\", 'rb'), encoding=\"bytes\")\n\n # Testing data\n # n_test: number of testing data\n n_test = 20000\n testTypes_test = testTypes[-n_test:]\n observations_test = observations[-n_test:]\n ages_test = ages[-n_test:]\n treatment_indx_test = treatment_indx[-n_test:]\n censor_ages_test = censor_ages[-n_test:]\n death_state_test = death_states[-n_test:]\n\n # define Markov Process topology with MPmatrix. The diagonal should be zeros.\n # A one in element (i,j) indicates a possible transition between states i and j.\n MPmatrix_0 = np.zeros([nStates_0 + 1, nStates_0 + 1])\n MPmatrix_0[0, 1] = MPmatrix_0[1, 0] = MPmatrix_0[0, 2] = MPmatrix_0[1, 2] = 1\n MPmatrix_1 = np.zeros([nStates_1 + 1, nStates_1 + 1])\n MPmatrix_1[0, 1] = MPmatrix_1[1, 0] = MPmatrix_1[1, 2] = MPmatrix_1[2, 1] = MPmatrix_1[2, 3] = MPmatrix_1[:-1,\n -1] = 1\n MPmatrixs = [MPmatrix_0, MPmatrix_1]\n\n nPatients_test = len(ages_test)\n print('Number of patients for testing: ', nPatients_test)\n\n ### Set informative initial parameters\n temp = 4\n currAlpha_0 = [np.zeros([nStates_0, 4]), np.zeros([nStates_0, 4]), np.zeros([nStates_0, 2])]\n currAlpha_0[0][0, 0] = currAlpha_0[0][1, 1] = temp\n currAlpha_0[1][0, 0] = currAlpha_0[1][1, 1] = temp\n currAlpha_1 = [np.zeros([nStates_1, 4]), np.zeros([nStates_1, 4]), np.zeros([nStates_1, 2])]\n currAlpha_1[0][0, 0] = currAlpha_1[0][1, 1] = currAlpha_1[0][2, 2] = currAlpha_1[0][3, 3] = temp\n currAlpha_1[1][0, 0] = currAlpha_1[1][1, 1] = currAlpha_1[1][2, 2] = currAlpha_1[1][3, 3] = temp\n currAlpha_1[2][3, 0] = -2\n currAlpha_1[2][3, 1] = 2\n currAlpha = [currAlpha_0, currAlpha_1]\n currEta_0 = np.zeros([nStates_0, 3])\n currEta_1 = np.zeros([nStates_1, 3])\n currEta = [currEta_0, currEta_1]\n if model == \"continuous\":\n currW_0 = np.zeros([4, n_inv])\n currW_0[1, :] = -temp\n currW_0[3, :] = -temp\n currW_1 = np.zeros([9, n_inv])\n currW_1[1, :] = -temp\n currW_1[4, :] = -temp\n currW_1[7, :] = -temp\n elif model == \"discrete\":\n currW_0 = -4 * np.ones([4, n_inv])\n currW_1 = -4 * np.ones([9, n_inv])\n currW = [currW_0, currW_1]\n currC_0 = np.zeros([nStates_0, n_inv])\n currC_1 = np.zeros([nStates_1, n_inv])\n currC = [currC_0, currC_1]\n\n return 0\n\n\ndef Load_EM_res(verbose=False):\n global currPars\n with open(\"../../data/data_2400/EM_16_updated_data_inv4_continuous_240000/res\", \"rb\") as em_res:\n res = pickle.load(em_res, encoding=\"bytes\")\n currAlpha = res[2]\n currEta = res[3]\n currW = res[4]\n currC = res[5]\n currPars = [currAlpha, currEta, currW, currC]\n\n if verbose:\n print(\n \"EM results have been loaded with Pars: Alpha: {}, Eta: {}, W: {}, C:{}.\".format(currAlpha, currEta, currW,\n currC))\n return 0\n\n\ndef Compute_pos_Z_test(p, verbose=False): ### given no state Z | -\n global Z_pos\n # It is a Bernouli(p)\n\n ts = time.time()\n Z_pos = []\n for indx in range(nPatients_test):\n if indx % 100 == 99:\n print(\"{}/{} has been completed\".format(indx + 1, nPatients_test))\n loglik_0 = Loglikelihood_obs0_test(indx, 0, currPars)\n loglik_1 = Loglikelihood_obs0_test(indx, 1, currPars)\n tilde_p = np.exp(np.log(p) + loglik_1 - np.log((1 - p) * np.exp(loglik_0) + p * np.exp(loglik_1)))\n Z_pos.append(tilde_p)\n\n print('Compute the posterior of Z costs {}s'.format(time.time() - ts))\n if verbose:\n for indx in range(nPatients_test):\n print(\"Patient {}: model index probabilites: {}\".format(indx, Z_pos[indx]))\n return 0\n\n\ndef Loglikelihood_obs0_test(indx, Z, Pars, verbose=False):\n Alpha = Pars[0][Z]\n Eta = Pars[1][Z]\n W = Pars[2][Z]\n C = Pars[3][Z]\n MPmatrix = MPmatrixs[Z]\n\n patient_ages = ages_test[indx]\n patient_tests = testTypes_test[indx]\n patient_observations = observations_test[indx]\n patient_treatment_indx = treatment_indx_test[indx]\n patient_censor_age = censor_ages_test[indx]\n patient_death_state = death_state_test[indx]\n\n if len(patient_treatment_indx) == 1:\n j = patient_treatment_indx[0]\n loglik0 = Loglikelihood_group_obs0(patient_tests[:(j + 1)], patient_observations[:(j + 1)],\n patient_ages[:(j + 1)], 0, patient_censor_age, patient_death_state, Z, Alpha,\n Eta, W, C, ind, inv, verbose)\n if j < (len(patient_ages) - 1):\n loglik1 = Loglikelihood_group_obs0(patient_tests[j:-1], patient_observations[j:-1], patient_ages[j:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n else:\n loglik1 = 0\n loglik = loglik0 + loglik1\n elif len(patient_treatment_indx) > 1:\n loglik = 0\n j = patient_treatment_indx[0]\n loglik0 = Loglikelihood_group_obs0(patient_tests[:(j + 1)], patient_observations[:(j + 1)],\n patient_ages[:(j + 1)], 0, patient_censor_age, patient_death_state, Z, Alpha,\n Eta, W, C, ind, inv, verbose)\n loglik += loglik0\n for i in range(len(patient_treatment_indx) - 1):\n j = patient_treatment_indx[i]\n k = patient_treatment_indx[i + 1] + 1\n logliki = Loglikelihood_group_obs0(patient_tests[j:k], patient_observations[j:k], patient_ages[j:k], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n loglik += logliki\n j = patient_treatment_indx[-1]\n if j < (len(patient_ages) - 1):\n loglik1 = Loglikelihood_group_obs0(patient_tests[j:-1], patient_observations[j:-1], patient_ages[j:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n else:\n loglik1 = 0\n loglik += loglik1\n else:\n loglik = Loglikelihood_group_obs0(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 0,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv,\n verbose)\n return loglik\n\n\ndef Loglikelihood_group_obs0(patient_tests, patient_observations, patient_ages, patient_treatment_status, patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose=False, do_last=False):\n if Z == 0:\n nStates = 2\n else:\n nStates = 4\n MPmatrix = MPmatrixs[Z]\n\n nvisits = len(patient_ages)\n ### Initialization ###\n ### Q[s] ~ Pr[S0=s, O0]\n Q = np.zeros(nStates)\n patient_age = patient_ages[0]\n patient_test = patient_tests[0]\n patient_observation = patient_observations[0]\n if patient_treatment_status == 0:\n for s in range(nStates):\n Q[s] = np.log(ddirichlet_categorical(s, np.exp(C[:, Age2Comp(patient_age, inv)])))\n # Q[s] = np.log(C[s, Age2Comp(patient_age, inv)])\n Q[s] += np.sum(stats.poisson.logpmf(patient_test, np.exp(Eta[s, :])))\n # Q[s] += np.sum(stats.poisson.logpmf(patient_test, Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :2], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :], np.exp(Alpha[k][s, :])))\n # P(S0, O0)\n Q = np.exp(Q)\n else:\n Q[0] = 1\n log_Q = np.log(Q)\n\n ####################\n ### Forward Pass ###\n ####################\n # P_forward_matrices P(Sj-1, Sj, O0-j)\n P_forward_matrices = [np.zeros([nStates, nStates]) for patient_age in patient_ages]\n for j in range(1, nvisits):\n p_transition = ProbTransition(MPmatrix, W, patient_ages[j - 1], patient_ages[j], inv)\n log_prob_obs = np.zeros(nStates)\n for s in range(nStates):\n log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], np.exp(Eta[s, :])))\n # log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :2], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :], np.exp(Alpha[k][s, :])))\n\n log_P_forward_matrix = np.repeat(log_Q, nStates).reshape([nStates, nStates]) + np.transpose(\n np.repeat(log_prob_obs, nStates).reshape([nStates, nStates])) + np.log(p_transition[:nStates, :nStates])\n P_forward_matrix = np.exp(log_P_forward_matrix)\n #\n P_forward_matrices[j] = P_forward_matrix\n #\n Q = np.sum(P_forward_matrix, 0) / np.sum(P_forward_matrix)\n log_Q = np.log(Q)\n\n ## P(S_T, O)\n if nvisits > 1:\n PP = np.sum(P_forward_matrices[nvisits - 1], 0)\n else:\n PP = Q\n log_PP = np.log(PP)\n\n # print (\"P_forward_matrices\", P_forward_matrices)\n # print (\"log_PP\", log_PP)\n\n ## P(S_T, S_last, O)\n if do_last:\n # Add the censor statue\n if patient_censor_age < patient_ages[-1]:\n # this can happen due to some rounding errors when death is very close to last screening.\n # Just move the censor date a few month after last visit.\n patient_censor_age = patient_ages[-1] + 0.25\n p_transition = ProbTransition(MPmatrix, W, patient_ages[-1], patient_censor_age, inv)\n if patient_death_state > 0: # this means censor age is age of 'death', not end of observations.\n log_PP += np.log(p_transition[:nStates, -1])\n else: # this means censor age is age of end of observations, not 'death'. So we know they are still alive at the time the study ended.\n log_PP += np.log(1. - p_transition[:nStates, -1])\n\n # print (\"log_PP\", log_PP)\n\n return np.log(np.sum(np.exp(log_PP)))\n\n\ndef Compute_pos_last2(Pars):\n global last2s\n\n ts = time.time()\n last2s = []\n for indx in range(nPatients_test):\n last2 = last2_z(indx, Pars, verbose=False)\n # print(last2_z0.sum(), last2_z1.sum())\n last2s.append(last2)\n # print(last2s)\n print('Compute the predictive distribution of S*_I costs {}s'.format(time.time() - ts))\n return 0\n\n\ndef last2_z(indx, Pars, verbose=False):\n Alpha = Pars[0]\n Eta = Pars[1]\n W = Pars[2]\n C = Pars[3]\n Z = 1\n\n patient_ages = ages_test[indx]\n patient_tests = testTypes_test[indx]\n patient_observations = observations_test[indx]\n patient_treatment_indx = treatment_indx_test[indx]\n patient_censor_age = censor_ages_test[indx]\n patient_death_state = death_state_test[indx]\n\n if len(patient_treatment_indx) >= 1:\n j = patient_treatment_indx[-1]\n res = prob_last2_z_group(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 1,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose)\n else:\n res = prob_last2_z_group(patient_tests[:-1], patient_observations[:-1], patient_ages[:-1], 0,\n patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose)\n\n if verbose:\n print(indx, patient_treatment_indx, patient_tests[:-1], patient_observations[:-1], patient_ages[:-1],\n patient_censor_age, patient_death_state)\n\n return res\n\n\ndef prob_last2_z_group(patient_tests, patient_observations, patient_ages, patient_treatment_status, patient_censor_age, patient_death_state, Z, Alpha, Eta, W, C, ind, inv, verbose=False):\n if Z == 0:\n nStates = 2\n else:\n nStates = 4\n MPmatrix = MPmatrixs[Z]\n\n nvisits = len(patient_ages)\n ### Initialization ###\n ### Q[s] ~ Pr[S0=s, O0]\n Q = np.zeros(nStates)\n patient_age = patient_ages[0]\n patient_test = patient_tests[0]\n patient_observation = patient_observations[0]\n if patient_treatment_status == 0:\n for s in range(nStates):\n Q[s] = np.log(ddirichlet_categorical(s, np.exp(C[:, Age2Comp(patient_age, inv)])))\n # Q[s] = np.log(C[s, Age2Comp(patient_age, inv)])\n Q[s] += np.sum(stats.poisson.logpmf(patient_test, np.exp(Eta[s, :])))\n # Q[s] += np.sum(stats.poisson.logpmf(patient_test, Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :2], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # Q[s] += multinomial_logpmf(patient_observations[0][k, :], Alpha[k][s, :])\n Q[s] += np.log(ddirichlet_mutilnominal(patient_observations[0][k, :], np.exp(Alpha[k][s, :])))\n # P(S0, O0)\n Q = np.exp(Q)\n else:\n Q[0] = 1\n log_Q = np.log(Q)\n\n ####################\n ### Forward Pass ###\n ####################\n # P_forward_matrices P(Sj-1, Sj, O0-j)\n P_forward_matrices = [np.zeros([nStates, nStates]) for patient_age in patient_ages]\n for j in range(1, nvisits):\n p_transition = ProbTransition(MPmatrix, W, patient_ages[j - 1], patient_ages[j], inv)\n log_prob_obs = np.zeros(nStates)\n for s in range(nStates):\n log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], np.exp(Eta[s, :])))\n # log_prob_obs[s] += np.sum(stats.poisson.logpmf(patient_tests[j], Eta[s,:]))\n for k in range(nTests):\n if k == 2:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :2], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :2], np.exp(Alpha[k][s, :])))\n else:\n # log_prob_obs[s] += multinomial_logpmf(patient_observations[j][k, :], Alpha[k][s, :])\n log_prob_obs[s] += np.log(\n ddirichlet_mutilnominal(patient_observations[j][k, :], np.exp(Alpha[k][s, :])))\n\n log_P_forward_matrix = np.repeat(log_Q, nStates).reshape([nStates, nStates]) + np.transpose(\n np.repeat(log_prob_obs, nStates).reshape([nStates, nStates])) + np.log(p_transition[:nStates, :nStates])\n P_forward_matrix = np.exp(log_P_forward_matrix)\n P_forward_matrices[j] = P_forward_matrix\n Q = np.sum(P_forward_matrix, 0) / np.sum(P_forward_matrix)\n\n if nvisits == 1:\n Q /= Q.sum()\n\n return Q\n\n\ndef Compute_pos_last(Pars, verbose=False):\n global lasts\n\n ts = time.time()\n lasts = []\n Z = 1\n W = Pars[2]\n MPmatrix = MPmatrixs[Z]\n\n for indx in range(nPatients_test):\n last2_z1 = last2s[indx]\n patient_ages = ages_test[indx]\n\n # compute S_I+1|z=1, O*, hat_psi\n p_transition = ProbTransition(MPmatrix, W, patient_ages[-2], patient_ages[-1], inv)\n P_transition = p_transition[:-1, :-1]\n P_transition /= P_transition.sum(axis=1)[:, None]\n last_z1 = last2_z1.dot(P_transition) # dim 4\n\n if verbose:\n print(\"{}th patient, last2_z1: {}, last_z1: {}\".format(indx, last2_z1, last_z1))\n last = last_z1\n lasts.append(last_z1)\n\n if verbose:\n for indx in range(nPatients_test):\n print(\"{}th patient, state probs: {}, res: {}\".format(indx, lasts[indx], observations_test[indx][-1]))\n print(\"Computing the last state probability costs {}s\".format(time.time()-ts))\n\n\ndef ProbTransition_interval(MPmatrix, dt, W):\n '''\n 'MPmatrix' should be a square N-by-N matrix of ones and zeros that defines the intensity matrix of the markov process.\n A 1 at element ij indicates a possible transition between states i and j.\n A 0 at element ij means no possible transition between states i and j.\n\n -- Because this is a continuous time Markov Process the diagonals are forced to be zero.\n -- 'lambdas' is an array of transition intensities for the given patient at a given time interval.\n -- dt is a scalar. It is the difference in time between two observations.\n\n '''\n matrix = np.array(MPmatrix, copy=True)\n\n if model == 'continuous':\n matrix_filled = np.zeros_like(matrix, dtype=np.float32)\n matrix_filled[np.where(matrix > 0)] = np.exp(W)\n for i in range(matrix.shape[0]):\n matrix_filled[i, i] = - np.sum(matrix_filled[i, :])\n out = expm(dt * matrix_filled) # so far so good...\n elif model == 'discrete':\n n_dim = MPmatrix.shape[0]\n matrix_filled = np.zeros_like(matrix, dtype=np.float32)\n matrix_filled[np.where(matrix == 1)] = W\n np.fill_diagonal(matrix, 1)\n matrix = np.matmul(np.diag(1 + np.arange(n_dim)), matrix)\n for indx_row in range(n_dim):\n matrix_filled[np.where(matrix == 1 + indx_row)] = Softmax(matrix_filled[np.where(matrix == 1 + indx_row)])\n out = np.linalg.matrix_power(matrix_filled, int(round(dt * 12)) if int(\n round(dt * 12)) > 0 else 1) # Assume the screening interval is at least one month\n\n # Normalize the probablity matrix\n out = np.where(out < 0, 0., out)\n out = np.where(out > 1, 1., out)\n norm = np.repeat(np.sum(out, 1), out.shape[0]).reshape(out.shape)\n out = out / norm\n return out\n\n\ndef ProbTransition(MPmatrix, W, start, end, inv):\n '''\n 'matrix' should be a square N-by-N matrix of ones and zeros that defines the intensity matrix of the markov process.\n A 1 at element ij indicates a possible transition between states i and j.\n A 0 at element ij means no possible transition between states i and j.\n\n Because this is a continuous time Markov Process the diagonals are forced to be zero.\n\n hpv_status is 0,1 or -1. If -1, then status is unknown.\n treatment_status is 0 or 1.\n\n '''\n temp = start\n matrix = np.eye(MPmatrix.shape[0])\n\n while (temp < end):\n temp_component = Age2Comp(temp, inv)\n end_component = Age2Comp(end, inv)\n if temp_component < end_component:\n dt = (inv[temp_component] - temp)\n temp_W = W[:, temp_component]\n matrix = np.dot(matrix, ProbTransition_interval(MPmatrix, dt, temp_W))\n temp = inv[temp_component]\n else:\n dt = end - temp\n temp_W = W[:, temp_component]\n matrix = np.dot(matrix, ProbTransition_interval(MPmatrix, dt, temp_W))\n temp = inv[temp_component]\n\n out = matrix\n # Normalize the probability matrix\n out = np.where(out < 0, 0., out)\n out = np.where(out > 1, 1., out)\n norm = np.repeat(np.sum(out, 1), out.shape[0]).reshape(out.shape)\n out = out / norm\n return out\n\n\ndef Softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / np.sum(e_x)\n\n\ndef ddirichlet_mutilnominal(x, alpha):\n n = np.sum(x)\n alpha0 = sum(alpha)\n if n == 0:\n return 1\n else:\n return n * special.beta(alpha0, n) / np.prod(\n np.array([special.beta(alphak, xk) * xk for alphak, xk in zip(alpha, x) if xk > 0]))\n\n\ndef ddirichlet_categorical(k, alpha):\n alpha0 = sum(alpha)\n res = special.beta(alpha0, 1) / special.beta(alpha[k], 1)\n return res\n\n\ndef Age2Comp(age, inv): # This function is to specify the intensity component for the certain age(value) and certain transition index. Interval looks like [ ).\n temp = 0\n while age >= inv[temp]:\n temp += 1\n return (temp)\n\n\ndef Predict_SR(Pars, lasts):\n \"\"\"\n compute the average predictive probability given the number of tests\n :param Pars: estimated parameters\n :param lasts: estimated probability of the last state\n :return: average predictive probability for cytology, histology and HPV.\n \"\"\"\n Alpha = Pars[0]\n cytology_pred_scores = []\n histology_pred_scores = []\n hpv_pred_scores = []\n\n indx =0\n for last, patient_observations, patient_tests in zip(lasts, observations_test, testTypes_test):\n indx += 1\n if indx % 1000 == 999:\n print(\"{}/{} individuals has been completed.\".format(indx + 1, n_test))\n T_cyt = patient_tests[-1][0]\n T_hist = patient_tests[-1][1]\n T_hpv = patient_tests[-1][2]\n if T_cyt > 0:\n cyt_score = 0\n for S in range(4):\n cyt_score += ddirichlet_mutilnominal(x=patient_observations[-1][0, :], alpha=np.exp(Alpha[0])[S, :])*last[S]\n cytology_pred_scores.append(cyt_score)\n if T_hist > 0:\n hist_score = 0\n for S in range(4):\n hist_score += ddirichlet_mutilnominal(x=patient_observations[-1][1, :], alpha=np.exp(Alpha[1])[S, :])*last[S]\n histology_pred_scores.append(hist_score)\n if T_hpv > 0:\n hpv_score = 0\n for S in range(4):\n hpv_score += ddirichlet_mutilnominal(x=patient_observations[-1][2, :2], alpha=np.exp(Alpha[2])[S, :])*last[S]\n hpv_pred_scores.append(hpv_score)\n print(cytology_pred_scores)\n print(histology_pred_scores)\n print(hpv_pred_scores)\n cytology_pred_avgscore = np.mean(np.asarray(cytology_pred_scores))\n histology_pred_avgscore = np.mean(np.asarray(histology_pred_scores))\n hpv_pred_avgscore = np.mean(np.asarray(hpv_pred_scores))\n return cytology_pred_avgscore, histology_pred_avgscore, hpv_pred_avgscore\n\n\n\nif __name__ == \"__main__\":\n #################################\n ####### Initialization ##########\n #################################\n Initialization()\n\n #################################\n ######## Load EM estimates ######\n #################################\n Load_EM_res(verbose=True)\n\n #################################\n ####### HHMM Prediction #########\n #################################\n # # Compute predictive distribution of last second state given model index z\n # Compute_pos_last2(currPars)\n # # Compute predictive distribution of last state\n # Compute_pos_last(currPars, verbose=True)\n\n ################################\n ######## Save Results ##########\n ################################\n # with open(\"../../res/EM_2400/prediction_LS.pickle\", \"wb\") as res:\n # pickle.dump(lasts, res)\n\n ############################\n #######Load Results ########\n ############################\n with open(\"../../res/EM_2400/hierarchical_prediction_LS.pickle\", \"rb\") as res:\n lasts = pickle.load(res)\n\n\n ts = time.time()\n print(Predict_SR(currPars, lasts))\n print(\"prediction costs {}s\".format(time.time() - ts))", "sub_path": "src/Model_prediction/EM_prediction_SR.py", "file_name": "EM_prediction_SR.py", "file_ext": "py", "file_size_in_byte": 27745, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "matplotlib.use", "line_number": 19, "usage_type": "call"}, {"api_name": "argparse.ArgumentParser", "line_number": 28, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 35, "usage_type": "attribute"}, {"api_name": "os.chdir", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path.dirname", "line_number": 40, "usage_type": "call"}, {"api_name": "os.path", "line_number": 40, "usage_type": "attribute"}, {"api_name": "pickle.load", "line_number": 89, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 90, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 91, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 92, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 93, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 94, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 110, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 120, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 129, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 130, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 133, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 136, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 141, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 142, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 144, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 145, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 154, "usage_type": "call"}, {"api_name": "time.time", "line_number": 172, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 179, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 179, "usage_type": "call"}, {"api_name": "time.time", "line_number": 182, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 254, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 260, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 262, "usage_type": "call"}, {"api_name": "scipy.stats.poisson.logpmf", "line_number": 262, "usage_type": "call"}, {"api_name": "scipy.stats.poisson", "line_number": 262, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 262, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 262, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 267, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 270, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 272, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 275, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 281, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 284, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 286, "usage_type": "call"}, {"api_name": "scipy.stats.poisson.logpmf", "line_number": 286, "usage_type": "call"}, {"api_name": "scipy.stats.poisson", "line_number": 286, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 286, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 286, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 291, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 292, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 295, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 296, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 298, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 298, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 299, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 299, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 300, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 304, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 305, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 309, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 312, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 326, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 328, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 332, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 332, "usage_type": "call"}, {"api_name": "time.time", "line_number": 338, "usage_type": "call"}, {"api_name": "time.time", "line_number": 345, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 388, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 394, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 396, "usage_type": "call"}, {"api_name": "scipy.stats.poisson.logpmf", "line_number": 396, "usage_type": "call"}, {"api_name": "scipy.stats.poisson", "line_number": 396, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 396, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 396, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 401, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 404, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 406, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 409, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 415, "usage_type": "call"}, {"api_name": "numpy.zeros", "line_number": 418, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 420, "usage_type": "call"}, {"api_name": "scipy.stats.poisson.logpmf", "line_number": 420, "usage_type": "call"}, {"api_name": "scipy.stats.poisson", "line_number": 420, "usage_type": "attribute"}, {"api_name": "scipy.stats", "line_number": 420, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 420, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 425, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 426, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 429, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 430, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 432, "usage_type": "call"}, {"api_name": "numpy.transpose", "line_number": 432, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.log", "line_number": 433, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 434, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 436, "usage_type": "call"}, {"api_name": "time.time", "line_number": 447, "usage_type": "call"}, {"api_name": "time.time", "line_number": 471, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 485, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 488, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 488, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 489, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 489, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 491, "usage_type": "call"}, {"api_name": "matfuncs.expm", "line_number": 492, "usage_type": "call"}, {"api_name": "numpy.zeros_like", "line_number": 495, "usage_type": "call"}, {"api_name": "numpy.float32", "line_number": 495, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 496, "usage_type": "call"}, {"api_name": "numpy.fill_diagonal", "line_number": 497, "usage_type": "call"}, {"api_name": "numpy.matmul", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.diag", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.arange", "line_number": 498, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 500, "usage_type": "call"}, {"api_name": "numpy.linalg.matrix_power", "line_number": 501, "usage_type": "call"}, {"api_name": "numpy.linalg", "line_number": 501, "usage_type": "attribute"}, {"api_name": "numpy.where", "line_number": 505, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 506, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 507, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 507, "usage_type": "call"}, {"api_name": "numpy.eye", "line_number": 525, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 533, "usage_type": "call"}, {"api_name": "numpy.dot", "line_number": 538, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 543, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 544, "usage_type": "call"}, {"api_name": "numpy.repeat", "line_number": 545, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 545, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 552, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 552, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 553, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 557, "usage_type": "call"}, {"api_name": "scipy.special.beta", "line_number": 562, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 562, "usage_type": "name"}, {"api_name": "numpy.prod", "line_number": 562, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 563, "usage_type": "call"}, {"api_name": "scipy.special.beta", "line_number": 563, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 563, "usage_type": "name"}, {"api_name": "scipy.special.beta", "line_number": 568, "usage_type": "call"}, {"api_name": "scipy.special", "line_number": 568, "usage_type": "name"}, {"api_name": "numpy.exp", "line_number": 602, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 607, "usage_type": "call"}, {"api_name": "numpy.exp", "line_number": 612, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 617, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 617, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 618, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 618, "usage_type": "call"}, {"api_name": "numpy.mean", "line_number": 619, "usage_type": "call"}, {"api_name": "numpy.asarray", "line_number": 619, "usage_type": "call"}, {"api_name": "pickle.load", "line_number": 653, "usage_type": "call"}, {"api_name": "time.time", "line_number": 656, "usage_type": "call"}, {"api_name": "time.time", "line_number": 658, "usage_type": "call"}]}
+{"seq_id": "435432320", "text": "# -*- coding: utf-8 -*-\n\"\"\"General and basic API for models in HydroMT\"\"\"\n\nfrom abc import ABCMeta, abstractmethod\nimport os\nfrom os.path import join, isdir, isfile, abspath\nimport xarray as xr\nimport numpy as np\nimport geopandas as gpd\nfrom shapely.geometry import box\nimport logging\nfrom pathlib import Path\nimport inspect\n\nfrom ..data_adapter import DataCatalog\nfrom .. import config\n\n__all__ = [\"Model\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Model(object, metaclass=ABCMeta):\n \"\"\"General and basic API for models in HydroMT\"\"\"\n\n # FIXME\n _DATADIR = \"\" # path to the model data folder\n _NAME = \"modelname\"\n _CONF = \"model.ini\"\n _CF = dict() # configreader kwargs\n _GEOMS = {\"\": \"\"}\n _MAPS = {\"\": \"\"}\n _FOLDERS = [\"\"]\n\n def __init__(\n self,\n root=None,\n mode=\"w\",\n config_fn=None,\n data_libs=None,\n deltares_data=None,\n artifact_data=None,\n logger=logger,\n ):\n from . import ENTRYPOINTS # load within method to avoid circular imports\n\n self.logger = logger\n ep = ENTRYPOINTS.get(self._NAME, None)\n version = ep.distro.version if ep is not None else \"\"\n dist = ep.distro.name if ep is not None else \"unknown\"\n self.logger.info(f\"Initializing {self._NAME} model from {dist} (v{version}).\")\n\n # link to data\n self.data_catalog = DataCatalog(\n data_libs=data_libs,\n deltares_data=deltares_data,\n artifact_data=artifact_data,\n logger=self.logger,\n )\n\n # placeholders\n self._staticmaps = xr.Dataset()\n self._staticgeoms = dict() # dictionnary of gdp.GeoDataFrame\n self._forcing = dict() # dictionnary of xr.DataArray\n self._config = dict() # nested dictionary\n self._states = dict() # dictionnary of xr.DataArray\n self._results = dict() # dictionnary of xr.DataArray and/or xr.Dataset\n\n # model paths\n self._config_fn = self._CONF if config_fn is None else config_fn\n self.set_root(root, mode)\n\n def _check_get_opt(self, opt):\n \"\"\"Check all opt keys and raise sensible error messages if unknonwn.\"\"\"\n for method in opt.keys():\n m = method.strip(\"0123456789\")\n if not callable(getattr(self, m, None)):\n if not hasattr(self, m) and hasattr(self, f\"setup_{m}\"):\n raise DeprecationWarning(\n f'Use full name \"setup_{method}\" instead of \"{method}\"'\n )\n else:\n raise ValueError(f'Model {self._NAME} has no method \"{method}\"')\n return opt\n\n def _run_log_method(self, method, *args, **kwargs):\n \"\"\"Log method paramters before running a method\"\"\"\n method = method.strip(\"0123456789\")\n func = getattr(self, method)\n signature = inspect.signature(func)\n for i, (k, v) in enumerate(signature.parameters.items()):\n v = kwargs.get(k, v.default)\n if v is inspect.Parameter.empty:\n if len(args) >= i + 1:\n v = args[i]\n else:\n continue\n self.logger.info(f\"{method}.{k}: {v}\")\n return func(*args, **kwargs)\n\n def build(\n self, region: dict, res: float = None, write: bool = True, opt: dict = None\n ):\n \"\"\"Single method to setup and write a full model schematization and\n configuration from scratch\n\n Parameters\n ----------\n region: dict\n Description of model region. See :py:meth:`~hydromt.workflows.parse_region`\n for all options.\n res: float, optional\n Model restolution. Use only if applicable to your model. By default None.\n write: bool, optional\n Write the complete model schematization after setting up all model components.\n By default True.\n opt: dict, optional\n Model setup configuration. This is a nested dictionary where the first-level\n keys are the names of model spedific setup methods and the second-level\n keys the arguments of the method:\n\n ```{\n : {\n : , : \n }\n : {\n ...\n }\n }\n }```\n \"\"\"\n opt = self._check_get_opt(opt)\n\n # run setup_config and setup_basemaps first!\n self._run_log_method(\"setup_config\", **opt.pop(\"setup_config\", {}))\n kwargs = opt.pop(\"setup_basemaps\", {})\n kwargs.update(region=region)\n\n if res is not None: # res is optional\n kwargs.update(res=res)\n self._run_log_method(\"setup_basemaps\", **kwargs)\n\n # then loop over other methods\n for method in opt:\n self._run_log_method(method, **opt[method])\n\n # write\n if write:\n self.write()\n\n def update(self, model_out=None, write=True, opt=None):\n \"\"\"Single method to setup and write a full model schematization and\n configuration from scratch\n\n\n Parameters\n ----------\n model_out: str, path, optional\n Desitation folder to write the model schematization after updating\n the model. If None the updated model components are overwritten in the\n current model schematization if these exist. By defualt None.\n write: bool, optional\n Write the updated model schematization to disk. By default True.\n opt: dict, optional\n Model update configuration. This is a nested dictionary where the first-level\n keys are the names of model spedific setup methods and the second-level\n keys the arguments of the method:\n\n ```{\n : {\n : , : \n }\n : {\n ...\n }\n }```\n \"\"\"\n opt = self._check_get_opt(opt)\n\n # read current model\n if not self._write:\n if model_out is None:\n raise ValueError(\n '\"model_out\" directory required when updating in \"read-only\" mode'\n )\n self.read()\n self.set_root(model_out, mode=\"w\")\n\n # check if model has a region\n if self.region is None:\n raise ValueError(\n 'Model region not found, setup basemaps using \"build\" method first.'\n )\n\n # remove setup_basemaps from options and throw warning\n if \"setup_basemaps\" in opt:\n opt.pop(\"setup_basemaps\") # remove from opt\n self.logger.warning(\n '\"setup_basemaps\" can only be called when building a model.'\n )\n\n # loop over other methods from ini file\n self._run_log_method(\"setup_config\", **opt.pop(\"setup_config\", {}))\n for method in opt:\n self._run_log_method(method, **opt[method])\n\n # write\n if write:\n self.write()\n\n ## file system\n\n @property\n def root(self):\n \"\"\"Path to model folder.\"\"\"\n if self._root is None:\n raise ValueError(\"Root unknown, use set_root method\")\n return self._root\n\n def set_root(self, root, mode=\"w\"):\n \"\"\"Initialized the model root.\n In read mode it checks if the root exists.\n In write mode in creates the required model folder structure\n\n Parameters\n ----------\n root : str, optional\n path to model root\n mode : {\"r\", \"r+\", \"w\"}, optional\n read/write-only mode for model files\n \"\"\"\n if mode not in [\"r\", \"r+\", \"w\"]:\n raise ValueError(f'mode \"{mode}\" unknown, select from \"r\", \"r+\" or \"w\"')\n old_root = getattr(self, \"_root\", None)\n self._root = root if root is None else abspath(root)\n self._read = mode.startswith(\"r\")\n self._write = mode != \"r\"\n if root is not None:\n if self._write:\n for name in self._FOLDERS:\n path = join(self._root, name)\n if not isdir(path):\n os.makedirs(path)\n elif not self._read:\n self.logger.warning(\n \"Model dir already exists and \"\n f\"files might be overwritten: {path}.\"\n )\n # check directory\n elif not isdir(self._root):\n raise IOError(f'model root not found at \"{self._root}\"')\n\n ## I/O\n\n @abstractmethod\n def read(self):\n \"\"\"Method to read the complete model schematization and configuration from file.\"\"\"\n self.read_config()\n self.read_staticmaps()\n\n @abstractmethod\n def write(self):\n \"\"\"Method to write the complete model schematization and configuration to file.\"\"\"\n self.write_config()\n self.write_staticmaps()\n\n def _configread(self, fn):\n return config.configread(fn, abs_path=False)\n\n def _configwrite(self, fn):\n return config.configwrite(fn, self.config)\n\n def read_config(self, config_fn=None):\n \"\"\"Parse config from file. If no config file found a default config file is\n read in writing mode.\"\"\"\n prefix = \"User defined\"\n if config_fn is None: # prioritize user defined config path (new v0.4.1)\n if not self._read: # write-only mode > read default config\n config_fn = join(self._DATADIR, self._NAME, self._CONF)\n prefix = \"Default\"\n elif self.root is not None: # append or write mode > read model config\n config_fn = join(self.root, self._config_fn)\n prefix = \"Model\"\n cfdict = dict()\n if config_fn is not None:\n if isfile(config_fn):\n cfdict = self._configread(config_fn)\n self.logger.debug(f\"{prefix} config read from {config_fn}\")\n else:\n self.logger.error(f\"{prefix} config file not found at {config_fn}\")\n self._config = cfdict\n\n def write_config(self, config_name=None, config_root=None):\n \"\"\"Write config to \"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n if config_name is not None:\n self._config_fn = config_name\n elif self._config_fn is None:\n self._config_fn = self._CONF\n if config_root is None:\n config_root = self.root\n fn = join(config_root, self._config_fn)\n self.logger.info(f\"Writing model config to {fn}\")\n self._configwrite(fn)\n\n @abstractmethod\n def read_staticmaps(self):\n \"\"\"Read staticmaps at and parse to xarray Dataset\"\"\"\n # to read gdal raster files use: hydromt.open_mfraster()\n # to read netcdf use: xarray.open_dataset()\n if not self._write:\n # start fresh in read-only mode\n self._staticmaps = xr.Dataset()\n raise NotImplementedError()\n\n @abstractmethod\n def write_staticmaps(self):\n \"\"\"Write staticmaps at in model ready format\"\"\"\n # to write to gdal raster files use: self.staticmaps.raster.to_mapstack()\n # to write to netcdf use: self.staticmaps.to_netcdf()\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_staticgeoms(self):\n \"\"\"Read staticgeoms at and parse to dict of geopandas\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._staticgeoms = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_staticgeoms(self):\n \"\"\"Write staticmaps at in model ready format\"\"\"\n # to write use self.staticgeoms[var].to_file()\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_forcing(self):\n \"\"\"Read forcing at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._forcing = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_forcing(self):\n \"\"\"write forcing at in model ready format\"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_states(self):\n \"\"\"Read states at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._states = dict()\n raise NotImplementedError()\n\n @abstractmethod\n def write_states(self):\n \"\"\"write states at in model ready format\"\"\"\n if not self._write:\n raise IOError(\"Model opened in read-only mode\")\n raise NotImplementedError()\n\n @abstractmethod\n def read_results(self):\n \"\"\"Read results at and parse to dict of xr.DataArray\"\"\"\n if not self._write:\n # start fresh in read-only mode\n self._results = dict()\n raise NotImplementedError()\n\n ## model configuration\n\n @property\n def config(self):\n \"\"\"Returns parsed model configuration.\"\"\"\n if not self._config:\n self.read_config() # initialize default config\n return self._config\n\n def set_config(self, *args):\n \"\"\"Update the config dictionary at key(s) with values.\n\n Parameters\n ----------\n args : key(s), value tuple, with minimal length of two\n keys can given by multiple args: ('key1', 'key2', 'value')\n or a string with '.' indicating a new level: ('key1.key2', 'value')\n\n Examples\n --------\n >> # self.config = {'a': 1, 'b': {'c': {'d': 2}}}\n\n >> set_config('a', 99)\n >> {'a': 99, 'b': {'c': {'d': 2}}}\n\n >> set_config('b', 'c', 'd', 99) # identical to set_config('b.d.e', 99)\n >> {'a': 1, 'b': {'c': {'d': 99}}}\n \"\"\"\n if len(args) < 2:\n raise TypeError(\"set_config() requires a least one key and one value.\")\n args = list(args)\n value = args.pop(-1)\n if len(args) == 1 and \".\" in args[0]:\n args = args[0].split(\".\") + args[1:]\n branch = self.config # reads config at first call\n for key in args[:-1]:\n if not key in branch or not isinstance(branch[key], dict):\n branch[key] = {}\n branch = branch[key]\n branch[args[-1]] = value\n\n def setup_config(self, **cfdict):\n \"\"\"Update config with a dictionary\"\"\"\n # TODO rename to update_config\n if len(cfdict) > 0:\n self.logger.debug(f\"Setting model config options.\")\n for key, value in cfdict.items():\n self.set_config(key, value)\n\n def get_config(self, *args, fallback=None, abs_path=False):\n \"\"\"Get a config value at key(s).\n\n Parameters\n ----------\n args : tuple or string\n keys can given by multiple args: ('key1', 'key2')\n or a string with '.' indicating a new level: ('key1.key2')\n fallback: any, optional\n fallback value if key(s) not found in config, by default None.\n abs_path: bool, optional\n If True return the absolute path relative to the model root, by deafult False.\n NOTE: this assumes the config is located in model root!\n\n Returns\n value : any type\n dictionary value\n\n Examples\n --------\n >> # self.config = {'a': 1, 'b': {'c': {'d': 2}}}\n\n >> get_config('a')\n >> 1\n\n >> get_config('b', 'c', 'd') # identical to get_config('b.c.d')\n >> 2\n\n >> get_config('b.c') # # identical to get_config('b','c')\n >> {'d': 2}\n \"\"\"\n args = list(args)\n if len(args) == 1 and \".\" in args[0]:\n args = args[0].split(\".\") + args[1:]\n branch = self.config # reads config at first call\n for key in args[:-1]:\n branch = branch.get(key, {})\n if not isinstance(branch, dict):\n branch = dict()\n break\n value = branch.get(args[-1], fallback)\n if abs_path and isinstance(value, str):\n value = Path(value)\n if not value.is_absolute():\n value = Path(abspath(join(self.root, value)))\n return value\n\n ## model parameter maps, geometries and spatial properties\n\n @property\n def staticmaps(self):\n \"\"\"xarray.Dataset representation of all static parameter maps\"\"\"\n if len(self._staticmaps) == 0:\n if self._read:\n self.read_staticmaps()\n return self._staticmaps\n\n def set_staticmaps(self, data, name=None):\n \"\"\"Add data to staticmaps.\n\n All layers of staticmaps must have identical spatial coordinates.\n\n Parameters\n ----------\n data: xarray.DataArray or xarray.Dataset\n new map layer to add to staticmaps\n name: str, optional\n Name of new map layer, this is used to overwrite the name of a DataArray\n or to select a variable from a Dataset.\n \"\"\"\n if name is None:\n if isinstance(data, xr.DataArray) and data.name is not None:\n name = data.name\n elif not isinstance(data, xr.Dataset):\n raise ValueError(\"Setting a map requires a name\")\n elif name is not None and isinstance(data, xr.Dataset):\n data_vars = list(data.data_vars)\n if len(data_vars) == 1 and name not in data_vars:\n data = data.rename_vars({data_vars[0]: name})\n elif name not in data_vars:\n raise ValueError(\"Name not found in DataSet\")\n else:\n data = data[[name]]\n if isinstance(data, xr.DataArray):\n data.name = name\n data = data.to_dataset()\n if len(self._staticmaps) == 0: # new data\n self._staticmaps = data\n else:\n if isinstance(data, np.ndarray):\n if data.shape != self.shape:\n raise ValueError(\"Shape of data and staticmaps do not match\")\n data = xr.DataArray(dims=self.dims, data=data, name=name).to_dataset()\n for dvar in data.data_vars.keys():\n if dvar in self._staticmaps:\n if self._read:\n self.logger.warning(f\"Replacing staticmap: {dvar}\")\n self._staticmaps[dvar] = data[dvar]\n\n @property\n def staticgeoms(self):\n \"\"\"geopandas.GeoDataFrame representation of all model geometries\"\"\"\n if not self._staticgeoms:\n if self._read:\n self.read_staticgeoms()\n return self._staticgeoms\n\n def set_staticgeoms(self, geom, name):\n \"\"\"Add geom to staticmaps\"\"\"\n gtypes = [gpd.GeoDataFrame, gpd.GeoSeries]\n if not np.any([isinstance(geom, t) for t in gtypes]):\n raise ValueError(\n \"First parameter map(s) should be geopandas.GeoDataFrame or geopandas.GeoSeries\"\n )\n if name in self._staticgeoms:\n if self._read:\n self.logger.warning(f\"Replacing staticgeom: {name}\")\n self._staticgeoms[name] = geom\n\n @property\n def forcing(self):\n \"\"\"dict of xarray.dataarray representation of all forcing\"\"\"\n if not self._forcing:\n if self._read:\n self.read_forcing()\n return self._forcing\n\n def set_forcing(self, data, name=None):\n \"\"\"Add data to forcing attribute which is a dictionary of xarray.DataArray.\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray\n \"\"\"\n # check dataset dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for forcing DataArray.\")\n data = {name: data}\n for name in data:\n if name in self._forcing:\n self.logger.warning(f\"Replacing forcing: {name}\")\n self._forcing[name] = data[name]\n\n @property\n def states(self):\n \"\"\"dict xarray.dataarray representation of all states\"\"\"\n if not self._states:\n if self._read:\n self.read_states()\n return self._states\n\n def set_states(self, data, name=None):\n \"\"\"Add data to states attribute which is a dictionary of xarray.DataArray.\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray\n \"\"\"\n # check dataset dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for forcing DataArray.\")\n data = {name: data}\n for name in data:\n if name in self._states:\n self.logger.warning(f\"Replacing state: {name}\")\n self._states[name] = data[name]\n\n @property\n def results(self):\n \"\"\"dict xarray.dataarray representation of model results\"\"\"\n if not self._results:\n if self._read:\n self.read_results()\n return self._results\n\n def set_results(self, data, name=None, split_dataset=False):\n \"\"\"Add data to results attribute which is a dictionary of xarray.DataArray and/or xarray.Dataset.\n\n The dictionary key is taken from the variable name. In case of a DataArray\n without name, the name can be passed using the optional name argument. In case of\n a Dataset, the dictionnary key is passed using the name argument.\n\n Dataset can either be added as is to the dictionnary (default) or split into several\n DataArrays using the split_dataset argument.\n\n Arguments\n ---------\n data: xarray.Dataset or xarray.DataArray\n New forcing data to add\n name: str, optional\n Variable name, only in case data is of type DataArray or if a Dataset is added as is (split_dataset=False).\n split_dataset: bool, optional\n If data is a xarray.Dataset, either add it as is to results or split it into several xarray.DataArrays.\n \"\"\"\n # check data dtype\n dtypes = [xr.DataArray, xr.Dataset]\n if not np.any([isinstance(data, t) for t in dtypes]):\n raise ValueError(\"Data type not recognized\")\n if isinstance(data, xr.DataArray):\n # NOTE name can be different from data.name !\n if data.name is None and name is not None:\n data.name = name\n elif name is None and data.name is not None:\n name = data.name\n elif data.name is None and name is None:\n raise ValueError(\"Name required for result DataArray.\")\n data = {name: data}\n # Add to results\n if isinstance(data, xr.Dataset) and not split_dataset:\n if name is not None:\n if name in self._results:\n self.logger.warning(f\"Replacing result: {name}\")\n self._results[name] = data\n else:\n raise ValueError(\"Name required to add DataSet directly to results\")\n else:\n for name in data:\n if name in self._results:\n self.logger.warning(f\"Replacing result: {name}\")\n self._results[name] = data[name]\n\n ## properties / methods below can be used directly in actual class\n\n @property\n def crs(self):\n \"\"\"Returns coordinate reference system embedded in staticmaps.\"\"\"\n return self.staticmaps.raster.crs\n\n def set_crs(self, crs):\n \"\"\"Embed coordinate reference system staticmaps metadata.\"\"\"\n return self.staticmaps.raster.set_crs(crs)\n\n @property\n def dims(self):\n \"\"\"Returns spatial dimension names of staticmaps.\"\"\"\n return self.staticmaps.raster.dims\n\n @property\n def coords(self):\n \"\"\"Returns coordinates of staticmaps.\"\"\"\n return self.staticmaps.raster.coords\n\n @property\n def res(self):\n \"\"\"Returns coordinates of staticmaps.\"\"\"\n return self.staticmaps.raster.res\n\n @property\n def transform(self):\n \"\"\"Returns spatial transform staticmaps.\"\"\"\n return self.staticmaps.raster.transform\n\n @property\n def width(self):\n \"\"\"Returns width of staticmaps.\"\"\"\n return self.staticmaps.raster.width\n\n @property\n def height(self):\n \"\"\"Returns height of staticmaps.\"\"\"\n return self.staticmaps.raster.height\n\n @property\n def shape(self):\n \"\"\"Returns shape of staticmaps.\"\"\"\n return self.staticmaps.raster.shape\n\n @property\n def bounds(self):\n \"\"\"Returns shape of staticmaps.\"\"\"\n return self.staticmaps.raster.bounds\n\n @property\n def region(self):\n \"\"\"Returns geometry of region of the model area of interest.\"\"\"\n region = None\n if \"region\" in self.staticgeoms:\n region = self.staticgeoms[\"region\"]\n elif len(self.staticmaps) > 0:\n crs = self.crs\n if crs is None and crs.to_epsg() is not None:\n crs = crs.to_epsg() # not all CRS have an EPSG code\n region = gpd.GeoDataFrame(geometry=[box(*self.bounds)], crs=crs)\n return region\n\n def test_model_api(self):\n \"\"\"Test compliance to model API instances.\n\n Returns\n -------\n non_compliant: list\n List of objects that are non-compliant with the model API structure.\n \"\"\"\n non_compliant = []\n # Staticmaps\n if not isinstance(self.staticmaps, xr.Dataset):\n non_compliant.append(\"staticmaps\")\n # Staticgeoms\n if not isinstance(self.staticgeoms, dict):\n non_compliant.append(\"staticgeoms\")\n elif self.staticgeoms: # non-empty dict\n for name, geom in self.staticgeoms.items():\n if not isinstance(geom, gpd.GeoDataFrame):\n non_compliant.append(f\"staticgeoms.{name}\")\n # Forcing\n if not isinstance(self.forcing, dict):\n non_compliant.append(\"forcing\")\n elif self.forcing: # non-empty dict\n for name, data in self.forcing.items():\n if not isinstance(data, xr.DataArray):\n non_compliant.append(f\"forcing.{name}\")\n # Config\n if not isinstance(self.config, dict):\n non_compliant.append(\"config\")\n # States\n if not isinstance(self.states, dict):\n non_compliant.append(\"states\")\n elif self.states: # non-empty dict\n for name, data in self.states.items():\n if not isinstance(data, xr.DataArray):\n non_compliant.append(f\"states.{name}\")\n # Results\n if not isinstance(self.results, dict):\n non_compliant.append(\"results\")\n elif self.results: # non-empty dict\n dtypes = [xr.DataArray, xr.Dataset]\n for name, data in self.results.items():\n if not np.any([isinstance(data, t) for t in dtypes]):\n non_compliant.append(f\"results.{name}\")\n\n return non_compliant\n", "sub_path": "hydromt/models/model_api.py", "file_name": "model_api.py", "file_ext": "py", "file_size_in_byte": 29094, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "22", "api": [{"api_name": "logging.getLogger", "line_number": 20, "usage_type": "call"}, {"api_name": "abc.ABCMeta", "line_number": 23, "usage_type": "name"}, {"api_name": "data_adapter.DataCatalog", "line_number": 54, "usage_type": "call"}, {"api_name": "xarray.Dataset", "line_number": 62, "usage_type": "call"}, {"api_name": "inspect.signature", "line_number": 90, "usage_type": "call"}, {"api_name": "inspect.Parameter", "line_number": 93, "usage_type": "attribute"}, {"api_name": "os.path.abspath", "line_number": 235, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 241, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 242, "usage_type": "call"}, {"api_name": "os.makedirs", "line_number": 243, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 250, "usage_type": "call"}, {"api_name": "abc.abstractmethod", "line_number": 255, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 261, "usage_type": "name"}, {"api_name": "os.path.join", "line_number": 279, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 282, "usage_type": "call"}, {"api_name": "os.path.isfile", "line_number": 286, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 303, "usage_type": "call"}, {"api_name": "xarray.Dataset", "line_number": 314, "usage_type": "call"}, {"api_name": "abc.abstractmethod", "line_number": 307, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 317, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 326, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 334, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 342, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 350, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 357, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 365, "usage_type": "name"}, {"api_name": "abc.abstractmethod", "line_number": 372, "usage_type": "name"}, {"api_name": "pathlib.Path", "line_number": 471, "usage_type": "call"}, {"api_name": "pathlib.Path", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path.abspath", "line_number": 473, "usage_type": "call"}, {"api_name": "os.path.join", "line_number": 473, "usage_type": "call"}, {"api_name": "xarray.DataArray", "line_number": 500, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 502, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 504, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 512, "usage_type": "attribute"}, {"api_name": "numpy.ndarray", "line_number": 518, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 521, "usage_type": "call"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 538, "usage_type": "attribute"}, {"api_name": "geopandas.GeoSeries", "line_number": 538, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 539, "usage_type": "call"}, {"api_name": "xarray.DataArray", "line_number": 569, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 569, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 570, "usage_type": "call"}, {"api_name": "xarray.DataArray", "line_number": 572, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 607, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 607, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 608, "usage_type": "call"}, {"api_name": "xarray.DataArray", "line_number": 610, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 652, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 652, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 653, "usage_type": "call"}, {"api_name": "xarray.DataArray", "line_number": 655, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 665, "usage_type": "attribute"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 739, "usage_type": "call"}, {"api_name": "shapely.geometry.box", "line_number": 739, "usage_type": "call"}, {"api_name": "xarray.Dataset", "line_number": 752, "usage_type": "attribute"}, {"api_name": "geopandas.GeoDataFrame", "line_number": 759, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 766, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 776, "usage_type": "attribute"}, {"api_name": "xarray.DataArray", "line_number": 782, "usage_type": "attribute"}, {"api_name": "xarray.Dataset", "line_number": 782, "usage_type": "attribute"}, {"api_name": "numpy.any", "line_number": 784, "usage_type": "call"}]}
+{"seq_id": "239817964", "text": "# stdlib imports\n\nimport os\nimport numpy as np\nimport urllib\nimport json\nfrom datetime import timedelta, datetime\nimport collections\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n# import numpy as np\nimport sqlite3 as lite\nimport pandas as pd\n\n# local imports\nfrom mapio.shake import getHeaderData\nfrom libcomcat.search import get_event_by_id, search\nfrom mapio.multihaz import MultiHazardGrid\nfrom gfail.stats import get_rangebeta, get_pdfbeta\nfrom mapio.gdal import GDALGrid\nfrom mapio.gmt import GMTGrid\n\n\n# Don't delete this, it's needed in an eval function\nimport matplotlib.cm as cm # DO NOT DELETE\n# DO NOT DELETE ABOVE LINE\n\n# Define bin edges (lower and upper are clipped here but\n# are not clipped in reality)\nlshbins = [0.1, 1., 10., 100., 1000.]\nlspbins = [10., 100., 1000., 10000., 1e5]\nlqhbins = [1., 10., 100., 1000., 10000.]\nlqpbins = [100., 1000., 10000., 100000., 1e6]\n\n\ndef is_grid_point_source(grid):\n \"\"\"Was the shakemap grid constructed with a point source?\n\n This makes use of the 'urat' layer, which is the ratio of the predicted\n ground motion standard deviation to the GMPE standard deviation. The only\n reason this could ever be greater than 1.0 is if the uncertainty of the\n prediction is inflated due to the point source approxmiation; further,\n if a point source was used, there will always be some\n locations with 'urat' > 1.0.\n\n Args:\n grid (ShakeGrid): A ShakeGrid object from MapIO.\n\n Returns:\n bool: True if point rupture.\n \"\"\"\n data = grid.getData()\n urat = data['urat'].getData()\n max_urat = np.max(urat)\n if max_urat > (1 + np.finfo(float).eps):\n return True\n else:\n return False\n\n\ndef get_event_comcat(shakefile, timewindow=60, degwindow=0.3, magwindow=0.2):\n \"\"\"\n Find an event in comcat, searching first by event id and if that\n fails searching by magnitude, time, and location.\n\n Args:\n shakefile (str): path to shakemap .xml file of event to find\n timewindow (float): width of time window to search around time defined\n in shakefile (in seconds)\n degwindow (float): width of area to search around location specified in\n shakefile (in degrees).\n magwindow (float): width of magnitude window to search around the\n magnitude specified in shakefile.\n\n Returns:\n None if event not found, else tuple (info, detail, shakemap) where,\n * info: json formatted dictionary of info.json for the event\n * detail: event detail from comcat\n * shakemap: shakemap of event found (from comcat)\n\n \"\"\"\n header_dicts = getHeaderData(shakefile)\n grid_dict = header_dicts[0]\n event_dict = header_dicts[1]\n #version = grid_dict['shakemap_version']\n shaketime = grid_dict['process_timestamp']\n try:\n eid = event_dict['event_id']\n net = 'us'\n if 'event_network' in event_dict:\n net = event_dict['event_network']\n if not eid.startswith(net):\n eid = net + eid\n detail = get_event_by_id(eid, includesuperseded=True)\n except Exception as e:\n lat = event_dict['lat']\n lon = event_dict['lon']\n mag = event_dict['magnitude']\n time = event_dict['event_timestamp']\n starttime = time - timedelta(seconds=timewindow)\n endtime = time + timedelta(seconds=timewindow)\n minlat = lat - degwindow\n minlon = lon - degwindow\n maxlat = lat + degwindow\n maxlon = lon + degwindow\n minmag = max(0, mag - magwindow)\n maxmag = min(10, mag + magwindow)\n events = search(starttime=starttime,\n endtime=endtime,\n minmagnitude=minmag,\n maxmagnitude=maxmag,\n minlatitude=minlat,\n minlongitude=minlon,\n maxlatitude=maxlat,\n maxlongitude=maxlon)\n if not len(events):\n return None\n detail = events[0].getDetailEvent()\n allversions = detail.getProducts('shakemap', version='all')\n # Find the right version\n dates1 = [allv.product_timestamp for allv in allversions]\n dates = np.array([datetime.fromtimestamp(int(str(dat)[:10])) for dat in dates1])\n idx = np.argmin(np.abs(dates-shaketime))\n #vers = [allv.version for allv in allversions]\n #idx = np.where(np.array(vers) == version)[0][0]\n shakemap = allversions[idx]\n infobytes, url = shakemap.getContentBytes('info.json')\n info = json.loads(infobytes.decode('utf-8'))\n\n return info, detail, shakemap\n\n\ndef parseConfigLayers(maplayers, config, keys=None):\n \"\"\"\n Parse things that need to coodinate with each layer (like lims, logscale,\n colormaps etc.) from config file, in right order, where the order is from\n maplayers.\n\n Args:\n maplayers (dict): Dictionary containing model output.\n config (ConfigObj): Config object describing options for specific\n model.\n keys (list): List of keys of maplayers to process, e.g. ``['model']``.\n\n Returns:\n tuple: (plotorder, logscale, lims, colormaps, maskthreshes) where:\n * plotorder: maplayers keys in order of plotting.\n * logscale: list of logscale options from config corresponding to\n keys in plotorder (same order).\n * lims: list of colorbar limits from config corresponding to keys\n in plotorder (same order).\n * colormaps: list of colormaps from config corresponding to keys\n in plotorder (same order),\n * maskthreshes: list of mask thresholds from config corresponding\n to keys in plotorder (same order).\n\n \"\"\"\n # TODO:\n # - Add ability to interpret custom color maps.\n\n # get all key names, create a plotorder list in case maplayers is not an\n # ordered dict, making sure that anything called 'model' is first\n if keys is None:\n keys = list(maplayers.keys())\n plotorder = []\n\n configkeys = list(config.keys())\n\n try:\n limits = config[configkeys[0]]['display_options']['lims']\n lims = []\n except:\n lims = None\n limits = None\n\n try:\n colors = config[configkeys[0]]['display_options']['colors']\n colormaps = []\n except:\n colormaps = None\n colors = None\n\n try:\n logs = config[configkeys[0]]['display_options']['logscale']\n logscale = []\n except:\n logscale = False\n logs = None\n\n try:\n masks = config[configkeys[0]]['display_options']['maskthresholds']\n maskthreshes = []\n except:\n maskthreshes = None\n masks = None\n\n try:\n default = \\\n config[configkeys[0]]['display_options']['colors']['default']\n default = eval(default)\n except:\n default = None\n\n for i, key in enumerate(keys):\n plotorder += [key]\n if limits is not None:\n found = False\n for lim1 in limits:\n if lim1 in key:\n if type(limits[lim1]) is list:\n getlim = np.array(limits[lim1]).astype(np.float)\n else:\n try:\n getlim = eval(limits[lim1])\n except:\n getlim = None\n lims.append(getlim)\n found = True\n if not found:\n lims.append(None)\n\n if colors is not None:\n found = False\n for c in colors:\n if c in key:\n getcol = colors[c]\n colorobject = eval(getcol)\n if colorobject is None:\n colorobject = default\n colormaps.append(colorobject)\n found = True\n if not found:\n colormaps.append(default)\n\n if logs is not None:\n found = False\n for g in logs:\n getlog = False\n if g in key:\n if logs[g].lower() == 'true':\n getlog = True\n logscale.append(getlog)\n found = True\n if not found:\n logscale.append(False)\n\n if masks is not None:\n found = False\n for m in masks:\n if m in key:\n getmask = eval(masks[m])\n maskthreshes.append(getmask)\n found = True\n if not found:\n maskthreshes.append(None)\n\n # Reorder everything so model is first, if it's not already\n if plotorder[0] != 'model':\n indx = [idx for idx, key in enumerate(plotorder) if key == 'model']\n if len(indx) == 1:\n indx = indx[0]\n firstpo = plotorder.pop(indx)\n plotorder = [firstpo] + plotorder\n firstlog = logscale.pop(indx)\n logscale = [firstlog] + logscale\n firstlim = lims.pop(indx)\n lims = [firstlim] + lims\n firstcol = colormaps.pop(indx)\n colormaps = [firstcol] + colormaps\n\n return plotorder, logscale, lims, colormaps, maskthreshes\n\n\ndef text_to_json(input1):\n \"\"\"Simplification of text_to_json from shakelib.rupture.factory\n\n Args:\n input1 (str): url or filepath to text file\n\n Returns:\n json formatted stream of input1\n \"\"\"\n if os.path.exists(input1):\n with open(input1, 'r') as f:\n lines = f.readlines()\n else:\n with urllib.request.urlopen(input1) as f:\n lines = f.readlines()\n\n x = []\n y = []\n z = []\n reference = ''\n # convert to geojson\n for line in lines:\n sline = line.strip()\n if sline.startswith('#'):\n reference += sline.strip('#').strip('Source: ')\n continue\n if sline.startswith('>'):\n if len(x): # start of new line segment\n x.append(np.nan)\n y.append(np.nan)\n z.append(np.nan)\n continue\n else: # start of file\n continue\n if not len(sline.strip()):\n continue\n parts = sline.split()\n\n y.append(float(parts[0]))\n x.append(float(parts[1]))\n if len(parts) >= 3:\n z.append(float(parts[2]))\n else:\n print('Fault file has no depths, assuming zero depth')\n z.append(0.0)\n coords = []\n poly = []\n for lon, lat, dep in zip(x, y, z):\n if np.isnan(lon):\n coords.append(poly)\n poly = []\n else:\n poly.append([lon, lat, dep])\n if poly != []:\n coords.append(poly)\n\n d = {\n \"type\": \"FeatureCollection\",\n \"metadata\": {\n 'reference': reference\n },\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {\n \"rupture type\": \"rupture extent\"\n },\n \"geometry\": {\n \"type\": \"MultiPolygon\",\n \"coordinates\": [coords]\n }\n }\n ]\n }\n return json.dumps(d)\n\n\ndef write_floats(filename, grid2d):\n \"\"\"Create a binary (with acc. header file) version of a Grid2D object.\n\n Args:\n filename (str): String filename to write (i.e., 'probability.flt')\n grid2d (Grid2D): MapIO Grid2D object.\n\n Returns:\n Given a filename input of \"probability.flt\", this function will\n create that file, plus a text file called \"probability.hdr\".\n \"\"\"\n geodict = grid2d.getGeoDict().asDict()\n array = grid2d.getData().astype('float32')\n np.save(filename, array)\n npyfilename = filename + '.npy'\n os.rename(npyfilename, filename)\n fpath, fname = os.path.split(filename)\n fbase, _ = os.path.splitext(fname)\n hdrfile = os.path.join(fpath, fbase + '.hdr')\n f = open(hdrfile, 'wt')\n for key, value in geodict.items():\n if isinstance(value, int):\n fmt = '%s = %i\\n'\n elif isinstance(value, float):\n fmt = '%s = %.4f\\n'\n else:\n fmt = '%s = %s\\n'\n f.write(fmt % (key, value))\n f.close()\n\n\ndef savelayers(grids, filename):\n \"\"\"\n Save ground failure layers object as a MultiHazard HDF file, preserving\n metadata structures. All layers must have same geodictionary.\n\n Args:\n grids: Ground failure layers object.\n filename (str): Path to where you want to save this file.\n\n Returns:\n .hdf5 file containing ground failure layers\n \"\"\"\n layers = collections.OrderedDict()\n metadata = collections.OrderedDict()\n for key in list(grids.keys()):\n layers[key] = grids[key]['grid'].getData()\n metadata[key] = {\n 'description': grids[key]['description'],\n 'type': grids[key]['type'],\n 'label': grids[key]['label']\n }\n origin = {}\n header = {}\n mgrid = MultiHazardGrid(layers, grids[key]['grid'].getGeoDict(),\n origin,\n header,\n metadata=metadata)\n mgrid.save(filename)\n\n\ndef loadlayers(filename):\n \"\"\"\n Load a MultiHazard HDF file back in as a ground failure layers object in\n active memory (must have been saved for this purpose).\n Args:\n filename (str): Path to layers file (hdf5 extension).\n\n Returns:\n Ground failure layers object\n \"\"\"\n mgrid = MultiHazardGrid.load(filename)\n grids = collections.OrderedDict()\n for key in mgrid.getLayerNames():\n grids[key] = {\n 'grid': mgrid.getData()[key],\n 'description': mgrid.getMetadata()[key]['description'],\n 'type': mgrid.getMetadata()[key]['type'],\n 'label': mgrid.getMetadata()[key]['label']\n }\n\n return grids\n\n\ndef get_alert(paramalertLS, paramalertLQ, parampopLS, parampopLQ,\n hazbinLS=[1., 10., 100.], popbinLS=[100, 1000, 10000],\n hazbinLQ=[10., 100., 1000.], popbinLQ=[1000, 10000, 100000]):\n \"\"\"\n Get alert levels\n\n Args:\n paramalertLS (float): Hazard statistic of preferred landslide model\n paramalertLQ (float): Hazard statistic of preferred liquefaction model\n parampopLS (float): Exposure statistic of preferred landslide model\n parampopLQ (float): Exposure statistic of preferred liquefaction model\n hazbinLS (list): 3 element list of bin edges for landslide\n hazard alert between Green and Yellow, Yellow and Orange, and\n Orange and Red.\n popbinLS (list): same as above but for population exposure\n hazbinLQ (list): 3 element list of bin edges for liquefaction hazard\n alert between Green and Yellow, Yellow and Orange, and Orange\n and Red.\n popbinLQ (list): same as above but for population exposure\n\n Returns:\n Returns:\n tuple: (hazLS, popLS, hazLQ, popLQ, LS, LQ) where:\n * hazLS: the landslide hazard alert level (str)\n * popLS: the landslide population alert level (str)\n * hazLQ: the liquefaction hazard alert level (str)\n * popLQ: the liquefaction population alert level (str)\n * LS: the overall landslide alert level (str)\n * LQ: the overall liquefaction alert level (str)\n\n \"\"\"\n if paramalertLS is None:\n hazLS = None\n elif paramalertLS < hazbinLS[0]:\n hazLS = 'green'\n elif paramalertLS >= hazbinLS[0] and paramalertLS < hazbinLS[1]:\n hazLS = 'yellow'\n elif paramalertLS >= hazbinLS[1] and paramalertLS < hazbinLS[2]:\n hazLS = 'orange'\n elif paramalertLS > hazbinLS[2]:\n hazLS = 'red'\n else:\n hazLS = None\n\n if parampopLS is None:\n popLS = None\n elif parampopLS < popbinLS[0]:\n popLS = 'green'\n elif parampopLS >= popbinLS[0] and parampopLS < popbinLS[1]:\n popLS = 'yellow'\n elif parampopLS >= popbinLS[1] and parampopLS < popbinLS[2]:\n popLS = 'orange'\n elif parampopLS >= popbinLS[2]:\n popLS = 'red'\n else:\n popLS = None\n\n if paramalertLQ is None:\n hazLQ = None\n elif paramalertLQ < hazbinLQ[0]:\n hazLQ = 'green'\n elif paramalertLQ >= hazbinLQ[0] and paramalertLQ < hazbinLQ[1]:\n hazLQ = 'yellow'\n elif paramalertLQ >= hazbinLQ[1] and paramalertLQ < hazbinLQ[2]:\n hazLQ = 'orange'\n elif paramalertLQ >= hazbinLQ[2]:\n hazLQ = 'red'\n else:\n hazLQ = None\n\n if parampopLQ is None:\n popLQ = None\n elif parampopLQ < popbinLQ[0]:\n popLQ = 'green'\n elif parampopLQ >= popbinLQ[0] and parampopLQ < popbinLQ[1]:\n popLQ = 'yellow'\n elif parampopLQ >= popbinLQ[1] and parampopLQ < popbinLQ[2]:\n popLQ = 'orange'\n elif parampopLQ >= popbinLQ[2]:\n popLQ = 'red'\n else:\n popLQ = None\n\n num2color = {\n '1': 'green',\n '2': 'yellow',\n '3': 'orange',\n '4': 'red'\n }\n col2num = dict((v, k) for k, v in num2color.items())\n\n if popLS is not None and hazLS is not None:\n LSnum1 = col2num[hazLS]\n LSnum2 = col2num[popLS]\n LSnum = str(np.max([int(LSnum1), int(LSnum2)]))\n LS = num2color[LSnum]\n else:\n LS = None\n if popLQ is not None and hazLQ is not None:\n LQnum1 = col2num[hazLQ]\n LQnum2 = col2num[popLQ]\n LQnum = str(np.max([int(LQnum1), int(LQnum2)]))\n LQ = num2color[LQnum]\n else:\n LQ = None\n\n return hazLS, popLS, hazLQ, popLQ, LS, LQ\n\n\ndef view_database(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n realtime=False, currentonly=False, numevents=None,\n LShazmin=None, LShazmax=None, LSpopmin=None,\n LSpopmax=None, LQhazmin=None, LQhazmax=None,\n LQpopmin=None, LQpopmax=None, verbose=False,\n printcols=None, csvfile=None, printsummary=True,\n printsuccess=False, printfailed=False,\n printnotmet=False, maxcolwidth=100,\n alertreport='value', realtime_maxsec=259200.):\n \"\"\"\n Prints out information from the ground failure database based on\n search criteria and other options. If nothing is defined except the\n database, it will print out a summary and details on the successful\n event runs only.\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n realtime (bool): if True, will only include events that were run in\n near real time (defined by delay time less than realtime_maxsec)\n currentonly (bool): if True, will only include the most recent run\n of each event\n numevents (int): Include the numevents most recent events that meet\n search criteria\n LShazmin: minimum landslide hazard alert color ('green', 'yellow',\n 'orange', 'red') or minimum hazard alert statistic value\n LShazmax: same as above but for maximum landslide hazard alert\n value/color\n LSpopmin: same as above but for minimum landslide population alert\n value/color\n LSpopmax: same as above but for maximum landslide population alert\n value/color\n LQhazmin: same as above but for minimum liquefaction hazard alert\n value/color\n LQhazmax: same as above but for maximum liquefaction hazard alert\n value/color\n LQpopmin: same as above but for minimum liquefaction population alert\n value/color\n LQpopmax: same as above but for maximum liquefaction population alert\n value/color\n verbose (bool): if True, will print all columns (overridden if\n printcols is assigned)\n printcols (list): List of columns to print out (choose from id,\n eventcode, shakemap_version, note, version, lat, lon, depth,\n time, mag, location, starttime, endtime, eventdir,\n finitefault, HaggLS, ExpPopLS, HaggLQ, ExpPopLQ\n csvfile: If defined, saves csvfile of table of all events found\n (includes all fields and failed/non-runs)\n printsummary (bool): if True (default), will print summary of events\n found to screen\n printsuccess (bool): if True (default), will print out database entries\n for successful event runs found\n printfailed (bool): if True (default False), will print out information\n about failed event runs\n printnotmet (bool): if True (default False), will print out information\n about event runs that didn't meet criteria to run ground failure\n maxcolwidth (int): maximum column width for printouts of database\n entries.\n alertreport (str): 'value' if values of alert statistics should be\n printed, or 'color' if alert level colors should be printed\n realtime_maxsec (float): if realtime is True, this is the maximum delay\n between event time and processing end time in seconds\n to consider an event to be run in realtime\n\n Returns:\n Prints summaries and database info to screen as requested, saves a\n csv file if requested. Also returns a tuple where (success, fail,\n notmet, stats, criteria) where\n * success: pandas dataframe of selected events that ran\n successfully\n * fail: pandas dataframe of selected events that failed to run\n due to an error\n * notmet: pandas dataframe of selected events that failed to run\n because they did not meet the criteria to run ground failure\n * stats: dictionary containing statistics summarizing selected\n events where\n * aLSg/y/o/r is the number of overall alerts of green/yellow\n orange or red for landslides. If LS is replaced with LQ,\n it is the same but for liquefaction.\n * hazLSg/y/o/r same as above but for hazard alert level totals\n * popLSg/y/o/r same as above but for population alert level\n totals\n * nsuccess is the number of events that ran successfully\n * nfail is the number of events that failed to run\n * nnotmet is the number of events that didn't run because they\n did not meet criteria to run ground failure\n * nunique is the number of unique earthquake events run\n * nunique_success is the number of unique earthquake events\n that ran successfully\n * nrealtime is the number of events that ran in near-real-time\n * delay_median_s is the median delay time for near-real-time\n events (earthquake time until first GF run), also the same\n for mean, min, max, and standard deviation\n * criteria: dictionary containing info on what criteria were used\n for the search\n \"\"\"\n import warnings\n warnings.filterwarnings(\"ignore\")\n\n formatters = {\"time\": \"{:%Y-%m-%d}\".format,\n \"shakemap_version\": \"{:.0f}\".format,\n \"version\": \"{:.0f}\".format,\n \"starttime\": \"{:%Y-%m-%d %H:%M}\".format,\n \"endtime\": \"{:%Y-%m-%d %H:%M}\".format}\n\n criteria = dict(locals())\n # Define alert bins for later use\n hazbinLS = dict(green=[0., 1], yellow=[1., 10.], orange=[10., 100.],\n red=[100., 1e20])\n popbinLS = dict(green=[0., 100], yellow=[100., 1000.],\n orange=[1000., 10000.], red=[10000., 1e20])\n hazbinLQ = dict(green=[0., 10], yellow=[10., 100.], orange=[100., 1000.],\n red=[1000., 1e20])\n popbinLQ = dict(green=[0., 1000], yellow=[1000., 10000.],\n orange=[10000., 100000.], red=[100000., 1e20])\n\n connection = None\n connection = lite.connect(database)\n\n pd.options.display.max_colwidth = maxcolwidth\n\n # Read in entire shakemap table, do selection using pandas\n df = pd.read_sql_query(\"SELECT * FROM shakemap\", connection)\n\n df['starttime'] = pd.to_datetime(df['starttime'], utc=True)\n df['endtime'] = pd.to_datetime(df['endtime'], utc=True)\n df['time'] = pd.to_datetime(df['time'], utc=True)\n\n # Print currently running info to screen\n print('-------------------------------------------------')\n curt = df.loc[df['note'].str.contains('Currently running', na=False)]\n if len(curt) > 0:\n ccols = ['eventcode', 'time', 'shakemap_version', 'note', 'starttime']\n ccols2 = ['eventcode', 'time', 'shake_v', 'note', 'startrun']\n print('Currently running - %d runs' % len(curt))\n print('-------------------------------------------------')\n print(curt.to_string(columns=ccols, index=False,\n justify='left', header=ccols2,\n formatters=formatters))\n # Remove currently running from list\n df.drop(curt.index, inplace=True)\n\n else:\n print('No events currently running')\n print('-------------------------------------------------')\n\n okcols = list(df.keys())\n\n if eventids is not None:\n if not hasattr(eventids, '__len__'):\n eventids = [eventids]\n df = df.loc[df['eventcode'].isin(eventids)]\n\n if minmag is not None:\n df = df.loc[df['mag'] >= minmag]\n if maxmag is not None:\n df = df.loc[df['mag'] <= maxmag]\n\n # Narrow down the database based on input criteria\n\n # set default values for start and end\n endt = pd.to_datetime('now', utc=True)\n stt = pd.to_datetime('1700-01-01', utc=True)\n if starttime is not None:\n stt = pd.to_datetime(starttime, utc=True)\n if endtime is not None:\n endt = pd.to_datetime(endtime, utc=True)\n df = df.loc[(df['time'] > stt) & (df['time'] <= endt)]\n\n # Winnow down based on alert\n # Assign numerical values if colors were used\n\n if LShazmin is not None or LShazmax is not None:\n if LShazmin is None:\n LShazmin = 0.\n if LShazmax is None:\n LShazmax = 1e20\n if isinstance(LShazmin, str):\n LShazmin = hazbinLS[LShazmin][0]\n if isinstance(LShazmax, str):\n LShazmax = hazbinLS[LShazmax][1]\n df = df.loc[(df['HaggLS'] >= LShazmin) & (df['HaggLS'] <= LShazmax)]\n\n if LQhazmin is not None or LQhazmax is not None:\n if LQhazmin is None:\n LQhazmin = 0.\n if LQhazmax is None:\n LQhazmax = 1e20\n if isinstance(LQhazmin, str):\n LQhazmin = hazbinLQ[LQhazmin][0]\n if isinstance(LQhazmax, str):\n LQhazmax = hazbinLQ[LQhazmax][1]\n df = df.loc[(df['HaggLQ'] >= LQhazmin) & (df['HaggLQ'] <= LQhazmax)]\n\n if LSpopmin is not None or LSpopmax is not None:\n if LSpopmin is None:\n LSpopmin = 0.\n if LSpopmax is None:\n LSpopmax = 1e20\n if isinstance(LSpopmin, str):\n LSpopmin = popbinLS[LSpopmin][0]\n if isinstance(LSpopmax, str):\n LSpopmax = popbinLS[LSpopmax][1]\n df = df.loc[(df['ExpPopLS'] >= LSpopmin) &\n (df['ExpPopLS'] <= LSpopmax)]\n\n if LQpopmin is not None or LQpopmax is not None:\n if LQpopmin is None:\n LQpopmin = 0.\n if LQpopmax is None:\n LQpopmax = 1e20\n if isinstance(LQpopmin, str):\n LQpopmin = popbinLQ[LQpopmin][0]\n if isinstance(LQpopmax, str):\n LQpopmax = popbinLQ[LQpopmax][1]\n df = df.loc[(df['ExpPopLQ'] >= LQpopmin) &\n (df['ExpPopLQ'] <= LQpopmax)]\n\n # Figure out which were run in real time\n delays = []\n event_codes = df['eventcode'].values\n elist, counts = np.unique(event_codes, return_counts=True)\n keep = []\n rejects = []\n for idx in elist:\n vers = df.loc[df['eventcode'] == idx]['shakemap_version'].values\n if len(vers) == 0:\n rejects.append(idx)\n delays.append(float('nan'))\n continue\n sel1 = df.loc[df['eventcode'] == idx]\n # vermin = np.nanmin(vers)\n # sel1 = df.loc[(df['eventcode'] == idx) &\n # (df['shakemap_version'] == vermin)]\n if len(sel1) > 0:\n dels = []\n for index, se in sel1.iterrows():\n dels.append(np.timedelta64(se['endtime'] - se['time'], 's').astype(int))\n delay = np.nanmin(dels)\n if delay <= realtime_maxsec:\n keep.append(idx)\n delays.append(delay)\n else:\n delays.append(float('nan'))\n else:\n rejects.append(idx)\n delays.append(float('nan'))\n if realtime: # Keep just realtime events\n df = df.loc[df['eventcode'].isin(keep)]\n\n # Remove any bad/incomplete entries\n df = df.loc[~df['eventcode'].isin(rejects)]\n\n # Get only latest version for each event id if requested\n if currentonly:\n df.insert(0, 'Current', 0)\n ids = np.unique(df['eventcode'])\n for id1 in ids:\n # Get most recent one for each\n temp = df.loc[df['eventcode'] == id1].copy()\n dels2 = []\n for index, te in temp.iterrows():\n dels2.append(np.timedelta64(te['endtime'] - te['time'], 's').astype(int))\n idx = np.argmax(dels2)\n df.loc[df['endtime'] == temp.iloc[idx]['endtime'], 'Current'] = 1\n df = df.loc[df['Current'] == 1]\n df.drop_duplicates(inplace=True)\n\n # Keep just the most recent number requested\n if numevents is not None and numevents < len(df):\n df = df.iloc[(numevents*-1):]\n\n # Now that have requested dataframe, make outputs\n success = df.loc[(df['note'] == '') |\n (df['note'].str.contains('adjusted to'))]\n fail = df.loc[df['note'].str.contains('fail')]\n notmet = df.loc[(~df['note'].str.contains('fail')) & (df['note'] != '') &\n (~df['note'].str.contains('adjusted to'))]\n\n if len(df) == 0:\n print('No matching GF runs found')\n return\n cols = []\n if printcols is not None:\n for p in printcols:\n if p in okcols:\n cols.append(p)\n else:\n print('column %s defined in printcols does not exist in the '\n 'database' % p)\n elif verbose:\n cols = okcols\n else: # List of what we usually want to see\n cols = ['eventcode', 'mag', 'location', 'time', 'shakemap_version',\n 'version', 'HaggLS', 'ExpPopLS', 'HaggLQ', 'ExpPopLQ']\n\n # Compute overall alert stats (just final for each event)\n\n # get unique event code list of full database\n codes = df['eventcode'].values\n allevids, count = np.unique(codes, return_counts=True)\n nunique = len(allevids)\n\n # get unique event code list for success\n event_codes = success['eventcode'].values\n elist2, count = np.unique(event_codes, return_counts=True)\n nunique_success = len(elist2)\n # Get delays just for these events\n delays = np.array(delays)\n del_set = []\n for el in elist2:\n del_set.append(delays[np.where(elist == el)][0])\n\n # get final alert values for each\n hazalertLS = []\n hazalertLQ = []\n popalertLS = []\n popalertLQ = []\n alertLS = []\n alertLQ = []\n\n # Currently includes just the most current one\n for idx in elist2:\n vers = np.nanmax(success.loc[success['eventcode'] == idx]\n ['shakemap_version'].values)\n # endt5 = np.nanmax(success.loc[success['eventcode'] == idx]\n # ['endtime'].values)\n sel1 = success.loc[(success['eventcode'] == idx) &\n (success['shakemap_version'] == vers)]\n out = get_alert(sel1['HaggLS'].values[-1],\n sel1['HaggLQ'].values[-1],\n sel1['ExpPopLS'].values[-1],\n sel1['ExpPopLQ'].values[-1])\n hazLS, popLS, hazLQ, popLQ, LS, LQ = out\n hazalertLS.append(hazLS)\n hazalertLQ.append(hazLQ)\n popalertLS.append(popLS)\n popalertLQ.append(popLQ)\n alertLS.append(LS)\n alertLQ.append(LQ)\n\n origsuc = success.copy() # Keep copy\n\n # Convert all values to alert colors\n for index, row in success.iterrows():\n for k, bins in hazbinLS.items():\n if row['HaggLS'] >= bins[0] and row['HaggLS'] < bins[1]:\n success.loc[index, 'HaggLS'] = k\n for k, bins in hazbinLQ.items():\n if row['HaggLQ'] >= bins[0] and row['HaggLQ'] < bins[1]:\n success.loc[index, 'HaggLQ'] = k\n for k, bins in popbinLS.items():\n if row['ExpPopLS'] >= bins[0] and row['ExpPopLS'] < bins[1]:\n success.loc[index, 'ExpPopLS'] = k\n for k, bins in popbinLQ.items():\n if row['ExpPopLQ'] >= bins[0] and row['ExpPopLQ'] < bins[1]:\n success.loc[index, 'ExpPopLQ'] = k\n\n # Compile stats\n stats = dict(aLSg=len([a for a in alertLS if a == 'green']),\n aLSy=len([a for a in alertLS if a == 'yellow']),\n aLSo=len([a for a in alertLS if a == 'orange']),\n aLSr=len([a for a in alertLS if a == 'red']),\n hazLSg=len([a for a in hazalertLS if a == 'green']),\n hazLSy=len([a for a in hazalertLS if a == 'yellow']),\n hazLSo=len([a for a in hazalertLS if a == 'orange']),\n hazLSr=len([a for a in hazalertLS if a == 'red']),\n popLSg=len([a for a in popalertLS if a == 'green']),\n popLSy=len([a for a in popalertLS if a == 'yellow']),\n popLSo=len([a for a in popalertLS if a == 'orange']),\n popLSr=len([a for a in popalertLS if a == 'red']),\n aLQg=len([a for a in alertLQ if a == 'green']),\n aLQy=len([a for a in alertLQ if a == 'yellow']),\n aLQo=len([a for a in alertLQ if a == 'orange']),\n aLQr=len([a for a in alertLQ if a == 'red']),\n hazLQg=len([a for a in hazalertLQ if a == 'green']),\n hazLQy=len([a for a in hazalertLQ if a == 'yellow']),\n hazLQo=len([a for a in hazalertLQ if a == 'orange']),\n hazLQr=len([a for a in hazalertLQ if a == 'red']),\n popLQg=len([a for a in popalertLQ if a == 'green']),\n popLQy=len([a for a in popalertLQ if a == 'yellow']),\n popLQo=len([a for a in popalertLQ if a == 'orange']),\n popLQr=len([a for a in popalertLQ if a == 'red']),\n nsuccess=len(success),\n nfail=len(fail),\n nnotmet=len(notmet),\n nruns=len(df),\n nunique=nunique,\n nunique_success=nunique_success,\n nrealtime=np.sum(np.isfinite(del_set)),\n delay_median_s=float('nan'),\n delay_mean_s=float('nan'),\n delay_min_s=float('nan'),\n delay_max_s=float('nan'),\n delay_std_s=float('nan')\n )\n\n if np.sum(np.isfinite(del_set)) > 0:\n stats['delay_median_s'] = np.nanmedian(del_set)\n stats['delay_mean_s'] = np.nanmean(del_set)\n stats['delay_min_s'] = np.nanmin(del_set)\n stats['delay_max_s'] = np.nanmax(del_set)\n stats['delay_std_s'] = np.nanstd(del_set)\n\n # If date range not set by user\n if starttime is None:\n starttime = np.min(df['starttime'].values)\n if endtime is None:\n endtime = np.max(df['endtime'].values)\n\n # Now output selections in text, csv files, figures\n if csvfile is not None:\n name, ext = os.path.splitext(csvfile)\n if ext == '':\n csvfile = '%s.csv' % name\n if os.path.dirname(csvfile) == '':\n csvfile = os.path.join(os.getcwd(), csvfile)\n # make sure it's a path\n if os.path.isdir(os.path.dirname(csvfile)):\n df.to_csv(csvfile)\n else:\n raise Exception('Cannot save csv file to %s' % csvfile)\n\n # Print to screen\n if stats['nsuccess'] > 0 and printsuccess:\n print('Successful - %d runs' % stats['nsuccess'])\n print('-------------------------------------------------')\n cols2 = np.array(cols).copy()\n cols2[cols2 == 'shakemap_version'] = 'shake_v' # to save room printing\n cols2[cols2 == 'version'] = 'gf_v' # to save room printing\n cols2[cols2 == 'time'] = 'date' # to save room printing\n\n if alertreport == 'color':\n print(success.to_string(columns=cols, index=False, justify='left',\n header=list(cols2),\n formatters=formatters))\n else:\n print(origsuc.to_string(columns=cols, index=False, justify='left',\n header=list(cols2),\n formatters=formatters))\n print('-------------------------------------------------')\n\n if printfailed:\n if stats['nfail'] > 0:\n failcols = ['eventcode', 'location', 'mag', 'time',\n 'shakemap_version', 'note', 'starttime', 'endtime']\n failcols2 = ['eventcode', 'location', 'mag', 'time',\n 'shake_v', 'note', 'startrun', 'endrun']\n# if 'note' not in cols:\n# cols.append('note')\n print('Failed - %d runs' % stats['nfail'])\n print('-------------------------------------------------')\n print(fail.to_string(columns=failcols, index=False,\n formatters=formatters, justify='left', header=failcols2))\n else:\n print('No failed runs found')\n print('-------------------------------------------------')\n\n if printnotmet:\n if stats['nnotmet'] > 0:\n failcols = ['eventcode', 'location', 'mag', 'time',\n 'shakemap_version', 'note', 'starttime', 'endtime']\n failcols2 = ['eventcode', 'location', 'mag', 'time',\n 'shake_v', 'note', 'startrun', 'endrun']\n print('Criteria not met - %d runs' % stats['nnotmet'])\n print('-------------------------------------------------')\n print(notmet.to_string(columns=failcols, index=False,\n justify='left', header=failcols2,\n formatters=formatters))\n else:\n print('No runs failed to meet criteria')\n\n print('-------------------------------------------------')\n\n if printsummary:\n print('Summary %s to %s' % (str(starttime)[:10], str(endtime)[:10]))\n print('-------------------------------------------------')\n print('Of total of %d events run (%d unique)' % (stats['nruns'],\n stats['nunique']))\n print('\\tSuccessful: %d (%d unique)' % (stats['nsuccess'],\n stats['nunique_success']))\n print('\\tFailed: %d' % stats['nfail'])\n print('\\tCriteria not met: %d' % stats['nnotmet'])\n print('\\tRealtime: %d' % stats['nrealtime'])\n print('\\tMedian realtime delay: %1.1f mins' %\n (stats['delay_median_s']/60.,))\n print('-------------------------------------------------')\n print('Landslide overall alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['aLSg'])\n print('Yellow: %d' % stats['aLSy'])\n print('Orange: %d' % stats['aLSo'])\n print('Red: %d' % stats['aLSr'])\n print('-------------------------------------------------')\n print('Liquefaction overall alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['aLQg'])\n print('Yellow: %d' % stats['aLQy'])\n print('Orange: %d' % stats['aLQo'])\n print('Red: %d' % stats['aLQr'])\n print('-------------------------------------------------')\n print('Landslide hazard alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['hazLSg'])\n print('Yellow: %d' % stats['hazLSy'])\n print('Orange: %d' % stats['hazLSo'])\n print('Red: %d' % stats['hazLSr'])\n print('-------------------------------------------------')\n print('Landslide population alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['popLSg'])\n print('Yellow: %d' % stats['popLSy'])\n print('Orange: %d' % stats['popLSo'])\n print('Red: %d' % stats['popLSr'])\n print('-------------------------------------------------')\n print('Liquefaction hazard alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['hazLQg'])\n print('Yellow: %d' % stats['hazLQy'])\n print('Orange: %d' % stats['hazLQo'])\n print('Red: %d' % stats['hazLQr'])\n print('-------------------------------------------------')\n print('Liquefaction population alerts')\n print('-------------------------------------------------')\n print('Green: %d' % stats['popLQg'])\n print('Yellow: %d' % stats['popLQy'])\n print('Orange: %d' % stats['popLQo'])\n print('Red: %d' % stats['popLQr'])\n print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')\n\n if alertreport == 'value':\n return origsuc, fail, notmet, stats, criteria\n else:\n return success, fail, notmet, stats, criteria\n\n\ndef alert_summary(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, realtime=True, currentonly=True,\n filebasename=None,\n summarytypes='all'):\n \"\"\"\n Print summary plot of alerts that have been issued for set of events met\n by defined criteria\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n realtime (bool): if True, will only include events that were run in\n near real time (defined by delay time less than realtime_maxsec)\n currentonly (bool): if True, will only include the most recent run\n of each event\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n summarytypes (str): if 'all', will create three figures, one for\n overall alerts, one for hazard alerts, and one for population\n alerts. If 'overall', 'hazard', or 'population' it will create\n just the one selected.\n\n Returns:\n List of figure handles in order ['overall', 'hazard', 'population']\n Figure files of alert level summaries\n\n \"\"\"\n\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=realtime,\n currentonly=currentonly, printsummary=False,\n printsuccess=False, alertreport='color')\n stats = out[3]\n statsLS = []\n statsLQ = []\n types = []\n\n if summarytypes == 'overall' or summarytypes == 'all':\n statsLS.append([stats['aLSg'], stats['aLSy'], stats['aLSo'],\n stats['aLSr']])\n statsLQ.append([stats['aLQg'], stats['aLQy'], stats['aLQo'],\n stats['aLQr']])\n types.append('overall')\n if summarytypes == 'hazard' or summarytypes == 'all':\n statsLS.append([stats['hazLSg'], stats['hazLSy'], stats['hazLSo'],\n stats['hazLSr']])\n statsLQ.append([stats['hazLQg'], stats['hazLQy'], stats['hazLQo'],\n stats['hazLQr']])\n types.append('hazard')\n if summarytypes == 'population' or summarytypes == 'all':\n statsLS.append([stats['popLSg'], stats['popLSy'], stats['popLSo'],\n stats['popLSr']])\n statsLQ.append([stats['popLQg'], stats['popLQy'], stats['popLQo'],\n stats['popLQr']])\n types.append('population')\n figs = []\n for sLS, sLQ, typ in zip(statsLS, statsLQ, types):\n fig, ax = plt.subplots()\n index = np.arange(4)\n bar_width = 0.35\n fontsize = 12\n rects1 = ax.bar(index, sLS, bar_width,\n alpha=0.3,\n color='g',\n label='Landslide Alerts')\n\n rects2 = ax.bar(index + bar_width, sLQ, bar_width,\n alpha=0.7,\n color='g',\n label='Liquefaction Alerts')\n\n colors = ['g', 'y', 'orange', 'r']\n\n for r1, r2, c in zip(rects1, rects2, colors):\n if c == 'g':\n val = 1.00\n else:\n val = 1.05\n r1.set_color(c)\n r1.set_hatch('.')\n height = r1.get_height()\n ax.text(r1.get_x() + r1.get_width()/2., val*height,\n '%d' % int(height),\n ha='center', va='bottom', color=c,\n size=fontsize-2)\n r2.set_color(c)\n r2.set_hatch('/')\n height = r2.get_height()\n ax.text(r2.get_x() + r2.get_width()/2., val*height,\n '%d' % int(height),\n ha='center', va='bottom', color=c,\n size=fontsize-2)\n\n ax.set_xlabel('Alert', fontsize=fontsize)\n ax.set_ylabel('Total Events', fontsize=fontsize)\n\n ax.legend(fontsize=fontsize)\n\n plt.title('Ground failure %s alerts' % typ, fontsize=fontsize)\n plt.xticks(index + bar_width/2, ('Green', 'Yellow', 'Orange', 'Red'),\n fontsize=fontsize-2)\n plt.yticks(fontsize=fontsize-2)\n plt.show()\n\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n if ext == '':\n ext = '.png'\n fig.savefig('%s_%s%s' % (name, typ, ext), bbox_inches='tight')\n figs.append(fig)\n return figs\n\n\ndef plot_evolution(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n filebasename=None, changeonly=True,\n percrange=None):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n changeonly (bool): if True will only show events that changed alert\n level at least once in the time evolution plots (unless eventids\n are defined, then all will show)\n percrange: percentile to use for error bars to show uncertainty\n as value <1 (e.g., 0.95). If None, errors will not be shown\n \n\n Returns:\n Figures showing alert changes over time and delay and alert change\n statistics\n \"\"\"\n fontsize = 10\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=True,\n currentonly=False, printsummary=False,\n printsuccess=False, alertreport='value',\n eventids=eventids)\n if out is None:\n raise Exception('No events found that meet criteria')\n if eventids is not None:\n changeonly = False\n success = out[0].sort_values('starttime')\n elist = np.unique(success['eventcode'].values)\n HaggLS = []\n HaggLQ = []\n ExpPopLS = []\n ExpPopLQ = []\n eventtime = []\n times = []\n alertLS = []\n alertLQ = []\n descrip = []\n rangeHLS = []\n rangeHLQ = []\n rangeELS = []\n rangeELQ = []\n for idx in elist:\n sel1 = success.loc[success['eventcode'] == idx]\n hls = sel1['HaggLS'].values\n hlq = sel1['HaggLQ'].values\n pls = sel1['ExpPopLS'].values\n plq = sel1['ExpPopLQ'].values\n als = []\n alq = []\n for s, q, ps, pq in zip(hls, hlq, pls, plq):\n _, _, _, _, als1, alq1 = get_alert(s, q, ps, pq)\n als.append(als1)\n alq.append(alq1)\n alertLS.append(als)\n alertLQ.append(alq)\n HaggLS.append(hls)\n HaggLQ.append(hlq)\n ExpPopLS.append(pls)\n ExpPopLQ.append(plq)\n times.append(sel1['endtime'].values)\n eventtime.append(sel1['time'].values[-1])\n temp = success.loc[success['eventcode'] == idx]\n date = str(temp['time'].values[-1]).split('T')[0]\n descrip.append('M%1.1f %s (%s)' % (temp['mag'].values[-1],\n temp['location'].values[-1].title(), date))\n if percrange is not None:\n if percrange > 1 or percrange < 0.:\n raise Exception('uncertrange must be between 0 and 1')\n # Get range for input percentile\n # range for H\n range1 = get_rangebeta(sel1['PH_LS'], sel1['QH_LS'],\n prob=percrange, maxlim=sel1['HlimLS'])\n temp1 = [hls-range1[0], range1[1]-hls]\n temp1[0][temp1[0] < 0.] = 0 # zero out any negative values\n rangeHLS.append(temp1)\n range2 = get_rangebeta(sel1['PH_LQ'], sel1['QH_LQ'],\n prob=percrange, maxlim=sel1['HlimLQ'])\n temp2 = [hlq-range2[0], range2[1]-hlq]\n temp2[0][temp2[0] < 0.] = 0 # zero out any negative values\n rangeHLQ.append(temp2)\n # range for E\n # range for H\n range3 = get_rangebeta(sel1['PE_LS'], sel1['QE_LS'],\n prob=percrange, maxlim=sel1['ElimLS'])\n temp3 = [pls-range3[0], range3[1]-pls]\n temp3[0][temp3[0] < 0.] = 0\n rangeELS.append(temp3)\n range4 = get_rangebeta(sel1['PE_LQ'], sel1['QE_LQ'],\n prob=percrange, maxlim=sel1['ElimLQ'])\n temp4 = [plq-range4[0], range4[1]-plq]\n temp4[0][temp4[0] < 0.] = 0 # zero out any negative values\n rangeELQ.append(temp4)\n else:\n nanmat = np.empty((2, len(sel1)))\n nanmat[:] = np.NaN\n rangeHLS.append(nanmat)\n rangeHLQ.append(nanmat)\n rangeELS.append(nanmat)\n rangeELQ.append(nanmat)\n\n # Plot of changes over time to each alert level\n fig1, axes = plt.subplots(2, 1) # , figsize=(10, 10))\n ax1, ax2 = axes\n ax1.set_title('Landslide Summary Statistics', fontsize=fontsize)\n ax1.set_ylabel(r'Area Exposed to Hazard ($km^2$)', fontsize=fontsize)\n ax2.set_ylabel('Population Exposure', fontsize=fontsize)\n\n fig2, axes = plt.subplots(2, 1) # , figsize=(10, 10))\n ax3, ax4 = axes\n ax3.set_title('Liquefaction Summary Statistics', fontsize=fontsize)\n ax3.set_ylabel(r'Area Exposed to Hazard ($km^2$)', fontsize=fontsize)\n ax4.set_ylabel('Population Exposure', fontsize=fontsize)\n\n ax2.set_xlabel('Hours after earthquake', fontsize=fontsize)\n ax4.set_xlabel('Hours after earthquake', fontsize=fontsize)\n\n lqplot = 0\n lsplot = 0\n lsch = 0\n lqch = 0\n mindel = []\n\n zipped = zip(HaggLS, HaggLQ, ExpPopLS, ExpPopLQ, alertLS, alertLQ,\n descrip, times, eventtime)\n i = 0\n for hls, hlq, pls, plq, als, alq, des, t, et in zipped:\n resS = np.unique(als)\n resL = np.unique(alq)\n delays = [np.timedelta64(t1 - et, 's').astype(float) for t1 in t]\n mindel.append(np.min(delays))\n # Set to lower edge of green bin if zero so ratios will show up\n hls = np.array(hls)\n hls[hls == 0.] = lshbins[0]\n hlq = np.array(hlq)\n hlq[hlq == 0.] = lqhbins[0]\n pls = np.array(pls)\n pls[pls == 0.] = lspbins[0]\n plq = np.array(plq)\n plq[plq == 0.] = lqpbins[0]\n\n if (len(resS) > 1 or 'green' not in resS) or\\\n (len(resL) > 1 or 'green' not in resL):\n if len(resS) > 1 or not changeonly:\n if percrange is not None:\n ax1.errorbar(np.array(delays)/3600., hls,\n yerr=rangeHLS[i], label=des)\n ax2.errorbar(np.array(delays)/3600., pls, yerr=rangeELS[i])\n ax1.set_xscale(\"log\", nonposx='clip')\n ax1.set_yscale(\"log\", nonposy='clip')\n ax2.set_xscale(\"log\", nonposx='clip')\n ax2.set_yscale(\"log\", nonposy='clip')\n else:\n ax1.loglog(np.array(delays)/3600., hls, '.-', label=des)\n ax2.loglog(np.array(delays)/3600., pls, '.-')\n ax1.set_ylim([lshbins[0], np.max((lshbins[-1], np.max(hls)))])\n ax2.set_ylim([lspbins[0], np.max((lspbins[-1], np.max(pls)))])\n if changeonly:\n lsch += 1\n lsplot += 1\n if len(resL) > 1 or not changeonly:\n if percrange is not None:\n ax3.errorbar(np.array(delays)/3600., hlq, yerr=rangeHLQ[i],\n label=des)\n ax4.errorbar(np.array(delays)/3600., plq, yerr=rangeELQ[i])\n ax3.set_xscale(\"log\", nonposx='clip')\n ax3.set_yscale(\"log\", nonposy='clip')\n ax4.set_xscale(\"log\", nonposx='clip')\n ax4.set_yscale(\"log\", nonposy='clip')\n else:\n ax3.loglog(np.array(delays)/3600., hlq, '.-', label=des)\n ax4.loglog(np.array(delays)/3600., plq, '.-')\n ax3.set_ylim([lqhbins[0], np.max((lqhbins[-1], np.max(hlq)))])\n ax4.set_ylim([lqpbins[0], np.max((lqpbins[-1], np.max(plq)))])\n if changeonly:\n lqch += 1\n lqplot += 1\n i += 1\n print('%d of %d events had a liquefaction overall alert that changed' %\n (lqch, len(elist)))\n print('%d of %d events had a landslide overall alert that changed' %\n (lsch, len(elist)))\n\n if lsplot < 5:\n ax1.legend(fontsize=fontsize-3)\n if lqplot < 5:\n ax3.legend(fontsize=fontsize-3)\n ax1.tick_params(labelsize=fontsize-2)\n ax2.tick_params(labelsize=fontsize-2)\n ax3.tick_params(labelsize=fontsize-2)\n ax4.tick_params(labelsize=fontsize-2)\n ax1.grid(True)\n ax2.grid(True)\n ax3.grid(True)\n ax4.grid(True)\n\n alert_rectangles(ax1, lshbins)\n alert_rectangles(ax2, lspbins)\n alert_rectangles(ax3, lqhbins)\n alert_rectangles(ax4, lqpbins)\n\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n if ext == '':\n ext = '.png'\n fig1.savefig('%s_LSalert_evolution%s' % (name, ext),\n bbox_inches='tight')\n fig2.savefig('%s_LQalert_evolution%s' % (name, ext),\n bbox_inches='tight')\n\n\ndef time_delays(database, starttime=None, endtime=None,\n minmag=None, maxmag=None, eventids=None,\n filebasename=None):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n starttime (str): earliest earthquake time to include in the search,\n can be any string date recognizable by np.datetime\n endtime (str): latest earthquake time to include in the search,\n can be any string date recognizable by datetime\n minmag (float): minimum magnitude to include in search\n maxmag (float): maximum magnitude to include in search\n eventids (list): list of specific event ids to include (optional)\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n\n Returns:\n Figure showing delay and alert change statistics\n \"\"\"\n out = view_database(database, starttime=starttime, endtime=endtime,\n minmag=minmag, maxmag=maxmag, realtime=True,\n currentonly=False, printsummary=False,\n printsuccess=False, alertreport='value',\n eventids=eventids)\n\n success = out[0]\n elist = np.unique(success['eventcode'].values)\n HaggLS = []\n HaggLQ = []\n ExpPopLS = []\n ExpPopLQ = []\n eventtime = []\n times = []\n alertLS = []\n alertLQ = []\n descrip = []\n for idx in elist:\n sel1 = success.loc[success['eventcode'] == idx]\n hls = sel1['HaggLS'].values\n hlq = sel1['HaggLQ'].values\n pls = sel1['ExpPopLS'].values\n plq = sel1['ExpPopLQ'].values\n als = []\n alq = []\n for s, q, ps, pq in zip(hls, hlq, pls, plq):\n _, _, _, _, als1, alq1 = get_alert(s, q, ps, pq)\n als.append(als1)\n alq.append(alq1)\n alertLS.append(als)\n alertLQ.append(alq)\n HaggLS.append(hls)\n HaggLQ.append(hlq)\n ExpPopLS.append(pls)\n ExpPopLQ.append(plq)\n times.append(sel1['endtime'].values)\n eventtime.append(sel1['time'].values[-1])\n temp = success.loc[success['eventcode'] == idx]\n date = str(temp['time'].values[-1]).split('T')[0]\n descrip.append('M%1.1f %s (%s)' % (temp['mag'].values[-1],\n temp['location'].values[-1].title(), date))\n\n mindel = []\n delstableLS = []\n delstableLQ = []\n ratHaggLS = []\n ratHaggLQ = []\n ratPopLS = []\n ratPopLQ = []\n zipped = zip(HaggLS, HaggLQ, ExpPopLS, ExpPopLQ, alertLS, alertLQ,\n descrip, elist, times, eventtime)\n for hls, hlq, pls, plq, als, alq, des, el, t, et in zipped:\n delays = [np.timedelta64(t1 - et, 's').astype(float) for t1 in t]\n mindel.append(np.min(delays))\n delstableLS.append(delays[np.min(np.where(np.array(als) == als[-1]))])\n delstableLQ.append(delays[np.min(np.where(np.array(alq) == alq[-1]))])\n # Set to lower edge of green bin if zero so ratios will show up\n hls = np.array(hls)\n hls[hls == 0.] = 0.1\n ratHaggLS.append(hls[-1]/hls[0])\n hlq = np.array(hlq)\n hlq[hlq == 0.] = 1.\n ratHaggLQ.append(hlq[-1]/hlq[0])\n pls = np.array(pls)\n pls[pls == 0.] = 10.\n ratPopLS.append(pls[-1]/pls[0])\n plq = np.array(plq)\n plq[plq == 0.] = 100.\n ratPopLQ.append(plq[-1]/plq[0])\n\n # Don't bother making this plot when eventids are specified\n if eventids is None or len(eventids) > 25:\n # Histograms of delay times etc.\n fig, axes = plt.subplots(2, 2, figsize=(10, 10), sharey='col')\n ax1 = axes[0, 0]\n bins = np.logspace(np.log10(0.1), np.log10(1000.), 15)\n ax1.hist(np.array(mindel)/3600., color='k', edgecolor='k', alpha=0.5,\n bins=bins)\n\n ax1.set_xscale(\"log\")\n ax1.set_xlabel('Time delay to first run (hours)')\n ax1.set_ylabel('Number of events')\n vals = (np.nanmean(mindel)/3600., np.nanmedian(mindel)/3600.,\n np.nanstd(mindel)/3600.)\n # ax1.text(0.8, 0.8, 'mean: %1.1f hr\\nmedian: %1.1f hr\\nstd: %1.1f hr' %\n # vals, transform=ax1.transAxes, ha='center', va='center')\n ax1.text(0.8, 0.8, 'median: %1.1f hr' %\n vals[1], transform=ax1.transAxes, ha='center', va='center')\n delstableLS = np.array(delstableLS)\n delstableLQ = np.array(delstableLQ)\n delstable = np.max([delstableLS, delstableLQ], axis=0)\n\n ax2 = axes[1, 0]\n ax2.hist(np.array(delstable)/3600., color='k', edgecolor='k',\n alpha=0.5, bins=bins)\n ax2.set_xscale(\"log\")\n ax2.set_xlabel('Time delay till final alert color reached (hours)')\n ax2.set_ylabel('Number of events')\n vals = (np.nanmean(delstable)/3600., np.nanmedian(delstable)/3600.,\n np.nanstd(delstable)/3600.)\n # ax2.text(0.8, 0.8, 'mean: %1.1f hr\\nmedian: %1.1f hr\\nstd: %1.1f hr' %\n # vals, transform=ax2.transAxes, ha='center', va='center')\n ax2.text(0.8, 0.8, 'median: %1.1f hr' %\n vals[1], transform=ax2.transAxes, ha='center', va='center')\n\n print('Liquefaction overall alerts that changed stablized after a '\n 'median of %1.2f hours' %\n (np.median(delstableLQ[delstableLQ > 0.])/3600.))\n print('Landslide overall alerts that changed stablized after a median '\n 'of %1.2f hours' %\n (np.median(delstableLS[delstableLS > 0.])/3600.))\n\n ratHaggLS = np.array(ratHaggLS)\n ratHaggLQ = np.array(ratHaggLQ)\n ax3 = axes[0, 1]\n bins = np.logspace(np.log10(0.01), np.log10(100.), 9)\n ax3.hist(ratHaggLS[ratHaggLS != 1.], hatch='.', edgecolor='k',\n alpha=0.5, fill=False, label='Landslides',\n bins=bins)\n ax3.hist(ratHaggLQ[ratHaggLQ != 1.], hatch='/', edgecolor='k',\n alpha=0.5, fill=False, label='Liquefaction',\n bins=bins)\n ax3.set_xscale(\"log\")\n # ax3.set_xlabel(r'$H_{agg}$ final/$H_{agg}$ initial')\n ax3.set_xlabel(r'Area Exposed to Hazard $H_{final}/H_{initial}$')\n ax3.set_ylabel('Number of events')\n ax3.axvline(1., lw=2, color='k')\n arrowprops = dict(facecolor='black', width=1., headwidth=7.,\n headlength=7.)\n ax3.annotate('No change:\\nLS=%d\\nLQ=%d' %\n (len(ratHaggLS[ratHaggLS == 1.]),\n len(ratHaggLQ[ratHaggLQ == 1.])),\n xy=(0.5, 0.6), xycoords='axes fraction',\n textcoords='axes fraction', ha='center', va='center',\n xytext=(0.3, 0.6),\n arrowprops=arrowprops)\n ax3.legend(handlelength=2, handleheight=3, loc='upper right')\n\n ratPopLS = np.array(ratPopLS)\n ratPopLQ = np.array(ratPopLQ)\n ax4 = axes[1, 1]\n bins = np.logspace(np.log10(0.01), np.log10(100.), 9)\n ax4.hist(ratPopLS[ratPopLS != 1.], hatch='.', edgecolor='k',\n alpha=0.5, fill=False, bins=bins)\n ax4.hist(ratPopLQ[ratPopLQ != 1.], bins=bins,\n hatch='/', edgecolor='k', alpha=0.5, fill=False)\n ax4.set_xscale(\"log\")\n ax4.set_xlabel(r'Population Exposure $E_{final}/E_{initial}$')\n ax4.set_ylabel('Number of events')\n ax4.axvline(1., lw=2, color='k')\n ax4.annotate('No change:\\nLS=%d\\nLQ=%d' %\n (len(ratPopLS[ratPopLS == 1.]),\n len(ratPopLQ[ratPopLQ == 1.])),\n xy=(0.5, 0.75), xycoords='axes fraction',\n textcoords='axes fraction', xytext=(0.3, 0.75),\n arrowprops=arrowprops, ha='center', va='center')\n\n # Add letters\n ax1.text(0.02, 0.98, 'a)', transform=ax1.transAxes, ha='left',\n va='top', fontsize=14)\n ax2.text(0.02, 0.98, 'b)', transform=ax2.transAxes, ha='left',\n va='top', fontsize=14)\n ax3.text(0.02, 0.98, 'c)', transform=ax3.transAxes, ha='left',\n va='top', fontsize=14)\n ax4.text(0.02, 0.98, 'd)', transform=ax4.transAxes, ha='left',\n va='top', fontsize=14)\n\n plt.show()\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n fig.savefig('%s_alertdelay_stats%s' % (name, ext),\n bbox_inches='tight')\n\n\ndef plot_uncertainty(database, eventid, currentonly=True, filebasename=None,\n bars=False, percrange=0.95):\n \"\"\"\n Make a plot and print stats showing delay times and changes in alert\n statistics over time\n\n Args:\n database (str): file path to event database (.db file)\n eventid (str): event ids to plot\n currentonly (bool): if True, will only plot newest version, if False\n will plot all versions with different colors\n filebasename (str): If defined, will save a file with a modified\n version of this name depending on which alert is displayed, if no\n path is given it will save in current directory.\n bars (bool): if True, will use bars spanning percrange\n percrange (float): percentile to use for error bars to show uncertainty\n as value <1 (e.g., 0.95).\n\n Returns:\n Figure showing uncertainty\n \"\"\"\n\n fontsize = 12\n out = view_database(database, eventids=[eventid], currentonly=currentonly,\n printsummary=False)\n if out is None:\n raise Exception('No events found that meet criteria')\n\n success = out[0]\n nvers = len(success)\n # Get plots ready\n\n fig, axes = plt.subplots(2, 2, sharey=True, figsize=(14, 5))\n \n colors = np.flipud(np.linspace(0., 0.7, nvers))\n widths = np.ones(len(colors))\n # make last one thicker\n widths[-1] = 2.\n\n # Fill in plot\n i = 0\n offset = 0\n for index, row in success.iterrows():\n xvalsHLS, yvalsHLS, probsHLS = get_pdfbeta(row['PH_LS'], row['QH_LS'],\n lshbins,\n maxlim=row['HlimLS'])\n if bars:\n offset = i * 0.1\n valmin, valmax = get_rangebeta(row['PH_LS'], row['QH_LS'],\n prob=percrange,\n maxlim=row['HlimLS'])\n axes[0, 0].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n offset = 0.\n axes[0, 0].plot(xvalsHLS, yvalsHLS/np.max(yvalsHLS),\n color=str(colors[i]), lw=widths[i])\n axes[0, 0].plot(np.max((lshbins[0], row['HaggLS'])), offset, marker=7,\n color=str(colors[i]), markersize=11)\n #axes[0,0].text(row['HaggLS'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsHLQ, yvalsHLQ, probsHLQ = get_pdfbeta(row['PH_LQ'], row['QH_LQ'],\n lqhbins,\n maxlim=row['HlimLQ'])\n if bars:\n valmin, valmax = get_rangebeta(row['PH_LQ'], row['QH_LQ'],\n prob=percrange,\n maxlim=row['HlimLQ'])\n axes[0, 1].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[0, 1].plot(xvalsHLQ, yvalsHLQ/np.max(yvalsHLQ),\n color=str(colors[i]), lw=widths[i])\n axes[0, 1].plot(np.max((lqhbins[0], row['HaggLQ'])), offset, marker=7,\n color=str(colors[i]), markersize=11)\n #axes[0,1].text(row['HaggLQ'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsELS, yvalsELS, probsELS = get_pdfbeta(row['PE_LS'], row['QE_LS'],\n lspbins,\n maxlim=row['ElimLS'])\n if bars:\n valmin, valmax = get_rangebeta(row['PE_LS'], row['QE_LS'],\n prob=percrange,\n maxlim=row['ElimLS'])\n axes[1, 0].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[1, 0].plot(xvalsELS, yvalsELS/np.max(yvalsELS),\n color=str(colors[i]), lw=widths[i])\n axes[1, 0].plot(np.max((lspbins[0], row['ExpPopLS'])), offset,\n marker=7, color=str(colors[i]), markersize=11)\n #axes[1,0].text(row['ExpPopLS'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n xvalsELQ, yvalsELQ, probsELQ = get_pdfbeta(row['PE_LQ'], row['QE_LQ'],\n lqpbins,\n maxlim=row['ElimLQ'])\n if bars:\n valmin, valmax = get_rangebeta(row['PE_LQ'], row['QE_LQ'],\n prob=percrange,\n maxlim=row['ElimLQ'])\n axes[1, 1].hlines(offset+0.1, valmin, valmax,\n color=str(colors[i]), lw=2)\n else:\n axes[1, 1].plot(xvalsELQ, yvalsELQ/np.max(yvalsELQ),\n color=str(colors[i]), lw=widths[i])\n axes[1, 1].plot(np.max((lqpbins[0], row['ExpPopLQ'])), offset,\n marker=7, color=str(colors[i]), markersize=11)\n #axes[1,1].text(row['ExpPopLQ'], 0.13, '%1.0f' % row['version'],\n # color=str(colors[i]), ha='center')\n\n i += 1\n \n if not bars:\n offset = 0.9\n elif offset < 0.7:\n offset = 0.7\n \n if nvers == 1:\n vals = [0.125, 0.375, 0.625, 0.875]\n for i in range(4):\n axes[0, 0].text(vals[i], 0.1, '%.2f' % probsHLS[i], ha='center',\n va='center', transform=axes[0, 0].transAxes)\n axes[0, 1].text(vals[i], 0.1, '%.2f' % probsHLQ[i], ha='center',\n va='center', transform=axes[0, 1].transAxes)\n axes[1, 0].text(vals[i], 0.1, '%.2f' % probsELS[i], ha='center',\n va='center', transform=axes[1, 0].transAxes)\n axes[1, 1].text(vals[i], 0.1, '%.2f' % probsELQ[i], ha='center',\n va='center', transform=axes[1, 1].transAxes)\n\n alertcolors = ['g', 'y', 'orange', 'r']\n for i in range(4):\n axes[0, 0].add_patch(patches.Rectangle((lshbins[i], -0.3),\n lshbins[i+1] - lshbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[1, 0].add_patch(patches.Rectangle((lspbins[i], -0.3),\n lspbins[i+1] - lspbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[0, 1].add_patch(patches.Rectangle((lqhbins[i], -0.3),\n lqhbins[i+1] - lqhbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n axes[1, 1].add_patch(patches.Rectangle((lqpbins[i], -0.3),\n lqpbins[i+1] - lqpbins[i], 0.3,\n color=alertcolors[i], ec='k'))\n \n axes[0, 0].set_xlabel(r'Estimated Area Exposed to Hazard ($km^2$)',\n fontsize=fontsize)\n axes[1, 0].set_xlabel('Estimated Population Exposure', fontsize=fontsize)\n axes[0, 1].set_xlabel(r'Estimated Area Exposed to Hazard ($km^2$)',\n fontsize=fontsize)\n axes[1, 1].set_xlabel('Estimated Population Exposure', fontsize=fontsize)\n axes[0, 0].set_title('Landslides', fontsize=fontsize+2)\n axes[0, 1].set_title('Liquefaction', fontsize=fontsize+2)\n\n axes[0, 0].set_xlim([lshbins[0], lshbins[-1]])\n axes[1, 0].set_xlim([lspbins[0], lspbins[-1]])\n axes[0, 1].set_xlim([lqhbins[0], lqhbins[-1]])\n axes[1, 1].set_xlim([lqpbins[0], lqpbins[-1]])\n fig.canvas.draw()\n for ax in axes:\n for ax1 in ax:\n ax1.set_xscale('log')\n ax1.set_ylim([-0.3, offset+.2])\n ax1.tick_params(labelsize=fontsize)\n plt.setp(ax1.get_yticklabels(), visible=False)\n ax1.set_yticks([])\n ax1.axhline(0, color='k')\n# labels = [item.get_text() for item in ax1.get_xticklabels()]\n# labels[0] = '$\\leq$%s' % labels[0]\n# labels[-1] = '$\\geq$%s' % labels[-1]\n# ax1.set_xticklabels(labels)\n ax1.text(-0.065, -0.13, '<', transform=ax1.transAxes)\n ax1.text(0.95, -0.13, '>', transform=ax1.transAxes)\n\n plt.subplots_adjust(hspace=0.5)\n \n fig.suptitle('%4.f - M%1.1f - %s' % (row['time'].year,\n row['mag'], row['location']),\n fontsize=fontsize+2)\n plt.show()\n if filebasename is not None:\n name, ext = os.path.splitext(filebasename)\n fig.savefig('%s_uncertainty%s' % (name, ext),\n bbox_inches='tight')\n return fig\n\n\ndef alert_rectangles(ax, bins):\n \"\"\"\n Function used to color bin levels in background of axis\n \"\"\"\n colors = ['g', 'yellow', 'orange', 'r']\n xlims = ax.get_xlim()\n ylims = ax.get_ylim()\n for i, col in enumerate(colors):\n y = bins[i]\n y2 = bins[i+1]\n if col == 'g':\n corners = [[xlims[0], ylims[0]], [xlims[0], y2], [xlims[1], y2],\n [xlims[1], ylims[0]]]\n elif col == 'r':\n corners = [[xlims[0], y], [xlims[0], ylims[1]],\n [xlims[1], ylims[1]], [xlims[1], y]]\n else:\n corners = [[xlims[0], y], [xlims[0], y2], [xlims[1], y2],\n [xlims[1], y]]\n # add rectangle\n rect = patches.Polygon(corners, closed=True, facecolor=col,\n transform=ax.transData, alpha=0.2)\n ax.add_patch(rect)\n\n\ndef getFileType(filename):\n \"\"\"\n Determine whether input file is a shapefile or a grid (ESRI or GMT).\n\n Args:\n filename (str): Path to candidate filename.\n\n Returns:\n str: 'shapefile', 'grid', or 'unknown'.\n \"\"\"\n # TODO MOVE TO MAPIO.\n if os.path.isdir(filename):\n return 'dir'\n ftype = GMTGrid.getFileType(filename)\n if ftype != 'unknown':\n return 'gmt'\n # Skip over ESRI header files\n if filename.endswith('.hdr'):\n return 'unknown'\n try:\n GDALGrid.getFileGeoDict(filename)\n return 'esri'\n except:\n pass\n return 'unknown'\n", "sub_path": "gfail/utilities.py", "file_name": "utilities.py", "file_ext": "py", "file_size_in_byte": 75800, "program_lang": "python", "lang": "en", "doc_type": "code", "dataset": "code-starcoder2", "pt": "4", "api": [{"api_name": "numpy.max", "line_number": 54, "usage_type": "call"}, {"api_name": "numpy.finfo", "line_number": 55, "usage_type": "call"}, {"api_name": "mapio.shake.getHeaderData", "line_number": 82, "usage_type": "call"}, {"api_name": "libcomcat.search.get_event_by_id", "line_number": 94, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 100, "usage_type": "call"}, {"api_name": "datetime.timedelta", "line_number": 101, "usage_type": "call"}, {"api_name": "libcomcat.search.search", "line_number": 108, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.datetime.fromtimestamp", "line_number": 122, "usage_type": "call"}, {"api_name": "datetime.datetime", "line_number": 122, "usage_type": "name"}, {"api_name": "numpy.argmin", "line_number": 123, "usage_type": "call"}, {"api_name": "numpy.abs", "line_number": 123, "usage_type": "call"}, {"api_name": "json.loads", "line_number": 128, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 211, "usage_type": "call"}, {"api_name": "numpy.float", "line_number": 211, "usage_type": "attribute"}, {"api_name": "os.path.exists", "line_number": 283, "usage_type": "call"}, {"api_name": "os.path", "line_number": 283, "usage_type": "attribute"}, {"api_name": "urllib.request.urlopen", "line_number": 287, "usage_type": "call"}, {"api_name": "urllib.request", "line_number": 287, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 302, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 303, "usage_type": "attribute"}, {"api_name": "numpy.nan", "line_number": 304, "usage_type": "attribute"}, {"api_name": "numpy.isnan", "line_number": 322, "usage_type": "call"}, {"api_name": "json.dumps", "line_number": 348, "usage_type": "call"}, {"api_name": "numpy.save", "line_number": 364, "usage_type": "call"}, {"api_name": "os.rename", "line_number": 366, "usage_type": "call"}, {"api_name": "os.path.split", "line_number": 367, "usage_type": "call"}, {"api_name": "os.path", "line_number": 367, "usage_type": "attribute"}, {"api_name": "os.path.splitext", "line_number": 368, "usage_type": "call"}, {"api_name": "os.path", "line_number": 368, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 369, "usage_type": "call"}, {"api_name": "os.path", "line_number": 369, "usage_type": "attribute"}, {"api_name": "collections.OrderedDict", "line_number": 394, "usage_type": "call"}, {"api_name": "collections.OrderedDict", "line_number": 395, "usage_type": "call"}, {"api_name": "mapio.multihaz.MultiHazardGrid", "line_number": 405, "usage_type": "call"}, {"api_name": "mapio.multihaz.MultiHazardGrid.load", "line_number": 422, "usage_type": "call"}, {"api_name": "mapio.multihaz.MultiHazardGrid", "line_number": 422, "usage_type": "name"}, {"api_name": "collections.OrderedDict", "line_number": 423, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 529, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 536, "usage_type": "call"}, {"api_name": "warnings.filterwarnings", "line_number": 648, "usage_type": "call"}, {"api_name": "sqlite3.connect", "line_number": 668, "usage_type": "call"}, {"api_name": "pandas.options", "line_number": 670, "usage_type": "attribute"}, {"api_name": "pandas.read_sql_query", "line_number": 673, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 675, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 676, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 677, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 712, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 713, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 715, "usage_type": "call"}, {"api_name": "pandas.to_datetime", "line_number": 717, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 772, "usage_type": "call"}, {"api_name": "numpy.timedelta64", "line_number": 788, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 789, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 807, "usage_type": "call"}, {"api_name": "numpy.timedelta64", "line_number": 813, "usage_type": "call"}, {"api_name": "numpy.argmax", "line_number": 814, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 851, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 856, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 859, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 862, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 874, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 940, "usage_type": "call"}, {"api_name": "numpy.isfinite", "line_number": 940, "usage_type": "call"}, {"api_name": "numpy.sum", "line_number": 948, "usage_type": "call"}, {"api_name": "numpy.isfinite", "line_number": 948, "usage_type": "call"}, {"api_name": "numpy.nanmedian", "line_number": 949, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 950, "usage_type": "call"}, {"api_name": "numpy.nanmin", "line_number": 951, "usage_type": "call"}, {"api_name": "numpy.nanmax", "line_number": 952, "usage_type": "call"}, {"api_name": "numpy.nanstd", "line_number": 953, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 957, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 959, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 963, "usage_type": "call"}, {"api_name": "os.path", "line_number": 963, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 966, "usage_type": "call"}, {"api_name": "os.path", "line_number": 966, "usage_type": "attribute"}, {"api_name": "os.path.join", "line_number": 967, "usage_type": "call"}, {"api_name": "os.path", "line_number": 967, "usage_type": "attribute"}, {"api_name": "os.getcwd", "line_number": 967, "usage_type": "call"}, {"api_name": "os.path.isdir", "line_number": 969, "usage_type": "call"}, {"api_name": "os.path", "line_number": 969, "usage_type": "attribute"}, {"api_name": "os.path.dirname", "line_number": 969, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 978, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1150, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1150, "usage_type": "name"}, {"api_name": "numpy.arange", "line_number": 1151, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.title", "line_number": 1191, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1191, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.xticks", "line_number": 1192, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1192, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.yticks", "line_number": 1194, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1194, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 1195, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1195, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 1198, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1198, "usage_type": "attribute"}, {"api_name": "numpy.unique", "line_number": 1248, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1291, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1296, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1303, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1308, "usage_type": "call"}, {"api_name": "numpy.empty", "line_number": 1314, "usage_type": "call"}, {"api_name": "numpy.NaN", "line_number": 1315, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1322, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1322, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1328, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1328, "usage_type": "name"}, {"api_name": "numpy.unique", "line_number": 1347, "usage_type": "call"}, {"api_name": "numpy.unique", "line_number": 1348, "usage_type": "call"}, {"api_name": "numpy.timedelta64", "line_number": 1349, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 1350, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1352, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1354, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1356, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1358, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1365, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1367, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1373, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1374, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1375, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1376, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1382, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1384, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1390, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1391, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1392, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1393, "usage_type": "call"}, {"api_name": "os.path.splitext", "line_number": 1422, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1422, "usage_type": "attribute"}, {"api_name": "numpy.unique", "line_number": 1461, "usage_type": "call"}, {"api_name": "numpy.timedelta64", "line_number": 1506, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 1507, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 1508, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 1508, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1508, "usage_type": "call"}, {"api_name": "numpy.min", "line_number": 1509, "usage_type": "call"}, {"api_name": "numpy.where", "line_number": 1509, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1509, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1511, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1514, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1517, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1520, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1527, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1527, "usage_type": "name"}, {"api_name": "numpy.logspace", "line_number": 1529, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 1529, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1530, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 1536, "usage_type": "call"}, {"api_name": "numpy.nanmedian", "line_number": 1536, "usage_type": "call"}, {"api_name": "numpy.nanstd", "line_number": 1537, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1542, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1543, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1544, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1547, "usage_type": "call"}, {"api_name": "numpy.nanmean", "line_number": 1552, "usage_type": "call"}, {"api_name": "numpy.nanmedian", "line_number": 1552, "usage_type": "call"}, {"api_name": "numpy.nanstd", "line_number": 1553, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 1561, "usage_type": "call"}, {"api_name": "numpy.median", "line_number": 1564, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1566, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1567, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 1569, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 1569, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1592, "usage_type": "call"}, {"api_name": "numpy.array", "line_number": 1593, "usage_type": "call"}, {"api_name": "numpy.logspace", "line_number": 1595, "usage_type": "call"}, {"api_name": "numpy.log10", "line_number": 1595, "usage_type": "call"}, {"api_name": "matplotlib.pyplot.show", "line_number": 1621, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1621, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 1623, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1623, "usage_type": "attribute"}, {"api_name": "matplotlib.pyplot.subplots", "line_number": 1660, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1660, "usage_type": "name"}, {"api_name": "numpy.flipud", "line_number": 1662, "usage_type": "call"}, {"api_name": "numpy.linspace", "line_number": 1662, "usage_type": "call"}, {"api_name": "numpy.ones", "line_number": 1663, "usage_type": "call"}, {"api_name": "gfail.stats.get_pdfbeta", "line_number": 1671, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1676, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1683, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1685, "usage_type": "call"}, {"api_name": "gfail.stats.get_pdfbeta", "line_number": 1689, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1693, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1699, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1701, "usage_type": "call"}, {"api_name": "gfail.stats.get_pdfbeta", "line_number": 1705, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1709, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1715, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1717, "usage_type": "call"}, {"api_name": "gfail.stats.get_pdfbeta", "line_number": 1721, "usage_type": "call"}, {"api_name": "gfail.stats.get_rangebeta", "line_number": 1725, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1731, "usage_type": "call"}, {"api_name": "numpy.max", "line_number": 1733, "usage_type": "call"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 1759, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 1759, "usage_type": "name"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 1762, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 1762, "usage_type": "name"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 1765, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 1765, "usage_type": "name"}, {"api_name": "matplotlib.patches.Rectangle", "line_number": 1768, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 1768, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.setp", "line_number": 1791, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1791, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.subplots_adjust", "line_number": 1801, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1801, "usage_type": "name"}, {"api_name": "matplotlib.pyplot.show", "line_number": 1806, "usage_type": "call"}, {"api_name": "matplotlib.pyplot", "line_number": 1806, "usage_type": "name"}, {"api_name": "os.path.splitext", "line_number": 1808, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1808, "usage_type": "attribute"}, {"api_name": "matplotlib.patches.Polygon", "line_number": 1834, "usage_type": "call"}, {"api_name": "matplotlib.patches", "line_number": 1834, "usage_type": "name"}, {"api_name": "os.path.isdir", "line_number": 1850, "usage_type": "call"}, {"api_name": "os.path", "line_number": 1850, "usage_type": "attribute"}, {"api_name": "mapio.gmt.GMTGrid.getFileType", "line_number": 1852, "usage_type": "call"}, {"api_name": "mapio.gmt.GMTGrid", "line_number": 1852, "usage_type": "name"}, {"api_name": "mapio.gdal.GDALGrid.getFileGeoDict", "line_number": 1859, "usage_type": "call"}, {"api_name": "mapio.gdal.GDALGrid", "line_number": 1859, "usage_type": "name"}]}