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_('